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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e9569ca77a3ceba3a9a685aa565e0c926826f099 | 10,821 | cpp | C++ | src/Scene.cpp | carlosemv/cobra | 13bf3ad45ce25cf449e389970c6873c67f4430fd | [
"MIT"
] | 1 | 2019-03-18T12:35:24.000Z | 2019-03-18T12:35:24.000Z | src/Scene.cpp | carlosemv/cobra | 13bf3ad45ce25cf449e389970c6873c67f4430fd | [
"MIT"
] | null | null | null | src/Scene.cpp | carlosemv/cobra | 13bf3ad45ce25cf449e389970c6873c67f4430fd | [
"MIT"
] | null | null | null | #include "Scene.h"
Scene::Scene(std::string config_file)
{
YAML::Node config = YAML::LoadFile(config_file);
height = config["height"].as<int>();
width = config["width"].as<int>();
load_collections(config);
if (config["background"])
bg_color = get_color(config["background"]);
else
bg_color = Scene::DEFAULT_BG;
for (auto node : config["objects"]) {
std::string type_name;
auto o_type_name = get_value<std::string>(node, "type");
if (o_type_name) {
type_name = o_type_name.value();
} else {
std::cerr << "Missing object type; ignoring object.\n";
continue;
}
auto obj_name = get_value<std::string>(node, "name");
Object obj;
auto o_obj = make_object(node, type_name, obj_name);
if (o_obj) {
obj = o_obj.value();
} else {
continue;
}
if (node["name"]) {
obj.name = node["name"].as<std::string>();
}
if (obj.is_polygon()) {
obj.edges = std::list<Edge>();
auto point = obj.points.begin();
for (; point+1 != obj.points.end(); ++point) {
Edge e(*point, *(point+1));
obj.edges.value().push_back(e);
}
}
if (node["color"]) {
obj.line_color = get_color(node["color"]);
} else {
obj.line_color = Scene::DEFAULT_LINE;
}
load_fill(node, obj);
this->objects.push_back(obj);
}
}
std::optional<Object> Scene::make_object(YAML::Node& node, std::string type_name,
std::optional<std::string> obj_name) const
{
ObjectType type;
try {
type = Object::type_names.at(type_name);
} catch (const std::out_of_range& e) {
std::cerr << "Invalid object type " << type_name
<< "; ignoring object.\n";
return std::nullopt;
}
Object obj;
switch (type) {
case ObjectType::Line:
{
auto start = get_point(node["start"]);
auto end = get_point(node["end"]);
obj = Object(type_name, {start, end});
break;
}
case ObjectType::Polyline:
{
std::vector<Point> points;
for (auto p : node["points"])
points.push_back(get_point(p));
obj = Object(type_name, points);
break;
}
case ObjectType::Polygon:
{
std::vector<Point> points;
for (auto p : node["points"])
points.push_back(get_point(p));
points.push_back(points.front());
obj = Object(type_name, points);
break;
}
case ObjectType::Circle:
{
auto circle = make_circle(node, type_name, obj_name);
if (circle)
obj = circle.value();
else
return std::nullopt;
break;
}
case ObjectType::Arc:
{
auto arc = make_arc(node, type_name, obj_name);
if (arc)
obj = arc.value();
else
return std::nullopt;
break;
}
case ObjectType::Rect:
{
auto rect = make_rect(node, type_name, obj_name);
if (rect)
obj = rect.value();
else
return std::nullopt;
break;
}
default:
{
std::cerr << "unexpected type " <<
type_name << "; ignoring object.\n";
return std::nullopt;
}
}
return obj;
}
std::optional<Object> Scene::make_circle(YAML::Node& node, std::string type_name,
std::optional<std::string> obj_name) const
{
Object obj;
auto center = get_point(node["center"]);
obj = Object(type_name, {center});
auto radius = get_int(node["radius"]);
if (radius) {
obj.radius = radius.value();
} else {
std::cerr << invalid_value_err("radius",
obj_name, type_name);
return std::nullopt;
}
return obj;
}
std::optional<Object> Scene::make_arc(YAML::Node& node, std::string type_name,
std::optional<std::string> obj_name) const
{
auto obj = make_circle(node, type_name, obj_name);
if (obj)
obj.value().arc = get_arc(node["arc"]);
return obj;
}
std::optional<Object> Scene::make_rect(YAML::Node& node, std::string type_name,
std::optional<std::string> obj_name) const
{
auto c = get_point(node["corner"]);
int width, height;
auto o_width = get_int(node["width"]);
if (not o_width) {
std::cerr << invalid_value_err("width",
obj_name, type_name);
return std::nullopt;
} else {
width = o_width.value();
}
auto o_height = get_int(node["height"]);
if (not o_height) {
std::cerr << invalid_value_err("height",
obj_name, type_name);
return std::nullopt;
} else {
height = o_height.value();
}
std::vector<Point> points = {
{c.x, c.y},
{c.x+width, c.y},
{c.x+width, c.y-height},
{c.x, c.y-height},
{c.x, c.y}
};
return Object(type_name, points);
}
Point Scene::get_point(YAML::Node node) const
{
Point p = {0, 0};
if (node.IsSequence()) {
for (auto i = 0; i < 2; ++i) {
auto o_int = get_int(node[i]);
if (o_int) {
p[i] = o_int.value();
} else {
if (node[i]) {
std::cerr << "Invalid or unkown value \""
<< node[i].as<std::string>() << "\"";
} else {
std::cerr << "Missing value";
}
std::cerr << " in position "
<< ((i==0) ? "\"x\"" : "\"y\"")
<< " of point; replacing with "
<< p[i] << ".\n";
}
}
} else if (node.IsScalar()) {
auto name = node.as<std::string>();
try {
p = points.at(name);
} catch (const std::out_of_range& e) {
std::cerr << "Unkown point " << name
<< "; replacing with " << p
<< "\n";
}
} else {
std::cerr << "Invalid point;"
<< " replacing with "<< p << "\n";
}
return p;
}
Arc Scene::get_arc(YAML::Node node) const
{
Arc arc = {0, 1};
if (node.IsSequence()) {
for (auto i = 0; i < 2; ++i) {
auto o_float = get_float(node[i]);
if (o_float) {
arc[i] = o_float.value();
} else {
if (node[i]) {
std::cerr << "Invalid or unkown value \""
<< node[i].as<std::string>() << "\"";
} else {
std::cerr << "Missing value";
}
std::cerr << " in position "
<< ((i==0) ? "\"left\"" : "\"right\"")
<< " of arc; replacing with "
<< arc[i] << ".\n";
}
}
} else if (node.IsScalar()) {
auto name = node.as<std::string>();
try {
arc = arcs.at(name);
} catch (const std::out_of_range& e) {
std::cerr << "Unkown arc " << name
<< "; replacing with " << arc
<< "\n";
}
} else {
std::cerr << "Invalid arc;"
<< " replacing with "<< arc << "\n";
}
if (arc.x < 0 or arc.x > 1 or arc.y < 0 or arc.y > 1) {
std::cerr << "Invalid arc " << arc.x << ", " << arc.y;
arc = Arc(0, 1);
std::cerr << "; using " << arc.x << ", " << arc.y
<< " instead.\n";
}
return arc;
}
Color Scene::get_color(YAML::Node node) const
{
Color c = DEFAULT_LINE;
if (node.IsSequence()) {
std::array<double, 3> value = {0};
for (auto i = 0; i < 3; ++i) {
auto o_float = get_float(node[i]);
if (o_float) {
value[i] = o_float.value();
} else {
if (node[i]) {
std::cerr << "Invalid or unkown value \""
<< node[i].as<std::string>() << "\"";
} else {
std::cerr << "Missing value";
}
std::cerr << " in position " << i
<< " of color; replacing with "
<< c[i] << ".\n";
}
}
return {value[0], value[1], value[2]};
} else if (node.IsScalar()) {
auto name = node.as<std::string>();
try {
c = palette.from_string(name);
} catch (const std::out_of_range& e) {
std::cerr << "Unkown color " << name
<< "; replacing with " << c
<< "\n";
}
} else {
std::cerr << "Invalid color;"
<< " replacing with "<< c << "\n";
}
return c;
}
std::optional<int> Scene::get_int(YAML::Node node) const
{
if (not node)
return std::nullopt;
try {
return node.as<int>();
} catch (const YAML::BadConversion& e) {
try {
auto name = node.as<std::string>();
return int_vars.at(name);
} catch (const std::out_of_range& e) {
return std::nullopt;
}
}
}
std::optional<double> Scene::get_float(YAML::Node node) const
{
if (not node)
return std::nullopt;
try {
return node.as<double>();
} catch (const YAML::BadConversion& e) {
try {
auto name = node.as<std::string>();
return float_vars.at(name);
} catch (const std::out_of_range& e) {
return std::nullopt;
}
}
}
void Scene::load_fill(YAML::Node& node, Object& obj) const
{
if (node["fill"] or node["fill_color"] or node["flood_points"]) {
if (node["fill_color"]) {
obj.fill_color = get_color(node["fill_color"]);
} else {
obj.fill_color = Scene::DEFAULT_FILL;
}
if (node["fill"]) {
auto fill_n = node["fill"].as<std::string>();
try {
obj.fill = Object::fill_names.at(fill_n);
} catch (const std::out_of_range& e) {
obj.fill = std::nullopt;
std::cerr << "Invalid fill method "
<< fill_n << "; ";
}
} else if (node["flood_points"]) {
obj.fill = FillMethod::Flood;
} else {
obj.fill = FillMethod::Scanline;
}
if (obj.fill == FillMethod::Flood) {
std::vector<Point> points;
for (auto p : node["flood_points"])
points.push_back(get_point(p));
obj.flood_points = points;
}
if (not obj.fill) {
std::cerr << "not filling ";
if (obj.name) {
std::cerr << "object \"" << obj.name.value()
<< "\".\n";
} else {
std::cerr << obj.type_name << " object\n";
}
}
}
}
void Scene::load_collections(YAML::Node config)
{
for (auto color : config["colors"]) {
std::string name;
std::array<double, 3> value;
auto elem = get_element<decltype(value)>(color, "color");
if (elem) {
std::tie(name, value) = elem.value();
palette.add_color(name, {value[0], value[1], value[2]});
}
}
for (auto point : config["points"]) {
std::string name;
ipair_t value;
auto elem = get_element<decltype(value)>(point, "point");
if (elem) {
std::tie(name, value) = elem.value();
points[name] = Point(value);
}
}
for (auto arc : config["arcs"]) {
std::string name;
dpair_t value;
auto elem = get_element<decltype(value)>(arc, "arc");
if (elem) {
std::tie(name, value) = elem.value();
arcs[name] = Arc(value);
}
}
for (auto var : config["variables"]) {
std::string type_name;
if (var.IsSequence()) {
type_name = var[0].as<std::string>();
} else if (var.IsMap()) {
if (var["type"]) {
type_name = var["type"].as<std::string>();
} else {
std::cerr << "variable definition is missing type;"
<< " ignoring definition.\n";
continue;
}
} else {
continue;
}
if (type_name == "integer") {
auto elem = get_element<int>(var, "variable", true);
if (elem) {
auto [name, value] = elem.value();
int_vars[name] = value;
}
} else if (type_name == "float") {
auto elem = get_element<double>(var, "variable", true);
if (elem) {
auto [name, value] = elem.value();
float_vars[name] = value;
}
} else {
std::cerr << "variable definition has an"
<< " invalid type \"" << type_name
<< "\"; ignoring definition.\n";
}
}
}
const std::string Scene::invalid_value_err(std::string field,
std::optional<std::string> obj_name, std::string type_name)
{
std::string err;
err += "Invalid or missing " + field + " value; ";
if (obj_name) {
err += "ignoring object \"" + obj_name.value() + "\".\n";
} else {
err += "ignoring " + type_name + " object.\n";
}
return err;
} | 22.219713 | 81 | 0.580168 | [
"object",
"vector"
] |
e95c6291192a286966e5287ab72c93da3b1ed85e | 1,422 | cpp | C++ | code/piglatin.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 8 | 2020-02-21T22:21:01.000Z | 2022-02-16T05:30:54.000Z | code/piglatin.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | null | null | null | code/piglatin.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 3 | 2020-08-05T05:42:35.000Z | 2021-08-30T05:39:51.000Z | #define _USE_MATH_DEFINES
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_set>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <unordered_set>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
void pySplit(string & splitString, char seperator, vector<string> & seperated)
{
int endIndex = 0;
seperated.clear();
seperated.push_back("");
for (unsigned int i = 0; i < splitString.size(); i++)
{
if (splitString[i] == seperator)
{
endIndex++;
seperated.push_back("");
}
else
{
seperated[endIndex] += splitString[i];
}
}
}
int main()
{
ull i, j, k;
string thing;
string temp;
vector<string> splitLine;
while (getline(cin, thing))
{
pySplit(thing, ' ', splitLine);
for (auto i : splitLine)
{
temp = "";
bool found = false;
if (i[0] == 'a' || i[0] == 'e' || i[0] == 'i'
|| i[0] == 'o' || i[0] == 'u' || i[0] == 'y')
{
temp = i + "yay";
}
else
{
j = 0;
while (j < i.size() && !found)
{
if (i[j] == 'a' || i[j] == 'e' || i[j] == 'i'
|| i[j] == 'o' || i[j] == 'u' || i[j] == 'y')
{
found = true;
}
j++;
}
j -= 1;
temp += i.substr(j);
temp += i.substr(0, j);
temp += "ay";
}
cout << temp << " ";
}
cout << "\n";
}
return 0;
}
| 17.13253 | 78 | 0.526723 | [
"vector"
] |
e9616eaf2d2d0a9733d1ee9763ede54d70f95854 | 22,359 | cpp | C++ | io/geometry/geo_reader_ply.cpp | ppearson/ImaginePartial | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | [
"Apache-2.0"
] | 1 | 2018-07-10T13:36:38.000Z | 2018-07-10T13:36:38.000Z | io/geometry/geo_reader_ply.cpp | ppearson/ImaginePartial | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | [
"Apache-2.0"
] | null | null | null | io/geometry/geo_reader_ply.cpp | ppearson/ImaginePartial | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | [
"Apache-2.0"
] | null | null | null | /*
Imagine
Copyright 2011-2019 Peter Pearson.
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 "geo_reader_ply.h"
#include <algorithm>
#include <cstdio>
#include "global_context.h"
#include "utils/string_helpers.h"
#include "utils/io/data_conversion.h"
#include "objects/mesh.h"
#include "geometry/standard_geometry_instance.h"
namespace Imagine
{
GeoReaderPly::GeoReaderPly()
{
}
bool GeoReaderPly::readFile(const std::string& path, const GeoReaderOptions& options)
{
std::fstream fileStream(path.c_str(), std::ios::in | std::ios::binary);
PlyHeader headerInfo;
if (!readHeader(fileStream, headerInfo))
{
GlobalContext::instance().getLogger().error("Cannot process PLY header of file: %s", path.c_str());
return false;
}
m_readOptions = options;
if (headerInfo.type == eASCII)
{
return readASCIIFile(fileStream, headerInfo, options);
}
else
{
return readBinaryFile(fileStream, path, headerInfo, options);
}
return false;
}
bool GeoReaderPly::readHeader(std::fstream& fileStream, PlyHeader& header) const
{
char buf[256];
memset(buf, 0, 256);
std::string line;
line.resize(256);
std::string key;
std::string value;
Element newElement;
while (fileStream.getline(buf, 256))
{
if (buf[0] == 0)
continue;
line.assign(buf);
// check for trailing \r with line endings
if (line[line.size() - 1] == '\r')
line = line.substr(0, line.size() - 1);
if (line == "end_header")
{
if (newElement.count > 0)
{
header.elements.emplace_back(newElement);
}
break;
}
splitInTwo(line, key, value, " ");
if (key == "format")
{
std::string type;
std::string version;
splitInTwo(value, type, version, " ");
if (type == "ascii")
header.type = eASCII;
else if (type == "binary_big_endian")
header.type = eBinaryBigEndian;
else if (type == "binary_little_endian")
header.type = eBinaryLittleEndian;
}
else if (key == "element")
{
if (newElement.count > 0)
{
header.elements.emplace_back(newElement);
newElement = Element();
}
std::string type;
std::string count;
splitInTwo(value, type, count, " ");
if (type == "vertex")
{
newElement.type = Element::eEVertex;
unsigned int elementCount = atol(count.c_str());
newElement.count = elementCount;
}
else if (type == "face")
{
newElement.type = Element::eEFace;
unsigned int elementCount = atol(count.c_str());
newElement.count = elementCount;
}
}
else if (key == "property")
{
std::string type;
std::string other;
splitInTwo(value, type, other, " ");
Property newProperty;
if (type == "float")
{
newProperty.mainDataType = Property::eFloat;
const std::string& propertyName = other;
newProperty.name = propertyName;
if (newElement.type == Element::eEVertex)
{
if (propertyName == "x")
{
newElement.xVIndex = newElement.properties.size();
}
else if (propertyName == "y")
{
newElement.yVIndex = newElement.properties.size();
}
else if (propertyName == "z")
{
newElement.zVIndex = newElement.properties.size();
}
}
newElement.properties.emplace_back(newProperty);
}
else if (type == "uchar")
{
newProperty.mainDataType = Property::eUChar;
const std::string& propertyName = other;
newProperty.name = propertyName;
newElement.properties.emplace_back(newProperty);
}
else if (type == "list")
{
std::string mainType;
std::string remainder;
splitInTwo(other, mainType, remainder, " ");
// several apps which use rply to save out ply files
// use the non-standard 'uint8' type, so we need to cope
// with this...
if (mainType == "uchar" || mainType == "uint8")
{
newProperty.mainDataType = Property::eUChar;
}
newProperty.list = true;
std::string listDataType;
std::string remainder2;
splitInTwo(remainder, listDataType, remainder2, " ");
if (listDataType == "int")
{
newProperty.listDataType = Property::eInt;
}
newElement.properties.emplace_back(newProperty);
}
else if (type == "int")
{
newProperty.mainDataType = Property::eInt;
const std::string& propertyName = other;
newProperty.name = propertyName;
newElement.properties.emplace_back(newProperty);
}
}
}
return header.type != eNone;
}
bool GeoReaderPly::readASCIIFile(std::fstream& fileStream, const PlyHeader& header, const GeoReaderOptions& options)
{
char buf[256];
memset(buf, 0, 256);
std::string line;
line.resize(256);
Mesh* pNewMesh = new Mesh();
if (!pNewMesh)
return false;
Material* pDefaultMaterial = pNewMesh->getMaterialManager().getMaterialFromID(1);
pNewMesh->setMaterial(pDefaultMaterial);
// TODO: StandardGeometryInstance support
std::vector<Point> aPoints;
EditableGeometryInstance* pNewGeoInstance = nullptr;
pNewGeoInstance = new EditableGeometryInstance();
pNewMesh->setGeometryInstance(pNewGeoInstance);
// TODO: a lot of this string manipulation / copying can be optimised...
std::vector<Element>::const_iterator itEl = header.elements.begin();
for (; itEl != header.elements.end(); ++itEl)
{
const Element& element = *itEl;
if (element.type == Element::eEVertex)
{
aPoints.reserve(element.count);
// assume for the moment we just have float types at the beginning
for (unsigned int i = 0; i < element.count; i++)
{
fileStream.getline(buf, 256);
// assume for the moment that the first items are x, y, z vertex positions, and just read those in...
Point newPoint;
sscanf(buf, "%f %f %f", &newPoint.x, &newPoint.y, &newPoint.z);
aPoints.emplace_back(newPoint);
}
}
else if (element.type == Element::eEFace)
{
std::deque<Face>& faces = pNewGeoInstance->getFaces();
for (unsigned int i = 0; i < element.count; i++)
{
fileStream.getline(buf, 256);
line.assign(buf);
std::string count;
std::string remainder;
splitInTwo(line, count, remainder, " ");
unsigned int numVerts = atol(count.c_str());
Face newFace(numVerts);
// newFace.reserveUVs(numVerts);
unsigned int vertices[5];
if (numVerts == 3)
{
sscanf(remainder.c_str(), "%u %u %u", &vertices[0], &vertices[1], &vertices[2]);
newFace.addVertex(vertices[0]);
newFace.addVertex(vertices[1]);
newFace.addVertex(vertices[2]);
}
else if (numVerts == 4)
{
sscanf(remainder.c_str(), "%u %u %u %u", &vertices[0], &vertices[1], &vertices[2], &vertices[3]);
newFace.addVertex(vertices[0]);
newFace.addVertex(vertices[1]);
newFace.addVertex(vertices[2]);
newFace.addVertex(vertices[3]);
}
else
{
// only pay this penalty if we need to, on the assumption it will be rare...
std::vector<std::string> aValues;
splitString(remainder, aValues, " ");
std::vector<std::string>::const_iterator itVal = aValues.begin();
for (; itVal != aValues.end(); ++itVal)
{
const std::string& val = *itVal;
unsigned int vertex = atoi(val.c_str());
newFace.addVertex(vertex);
}
}
faces.emplace_back(newFace);
}
}
}
std::deque<Point>& geoPoints = pNewGeoInstance->getPoints();
std::copy(aPoints.begin(), aPoints.end(), std::back_inserter(geoPoints));
// now we've copied the points for the EditableGeometryInstance, we need to go through the faces
// calculating the normals
std::deque<Face>& faces = pNewGeoInstance->getFaces();
std::deque<Face>::iterator itFace = faces.begin();
for (; itFace != faces.end(); ++itFace)
{
Face& face = *itFace;
face.calculateNormal(pNewGeoInstance);
}
fileStream.close();
m_newObject = pNewMesh;
postProcess();
return true;
}
bool GeoReaderPly::readBinaryFile(std::fstream& fileStream, const std::string& path, const PlyHeader& header, const GeoReaderOptions& options)
{
Mesh* pNewMesh = new Mesh();
if (!pNewMesh)
return false;
Material* pDefaultMaterial = pNewMesh->getMaterialManager().getMaterialFromID(1);
pNewMesh->setMaterial(pDefaultMaterial);
std::vector<Point> aTempPoints; // for use with EditableGeo
std::vector<Point>* pActualPoints = nullptr;
EditableGeometryInstance* pNewEditableGeoInstance = nullptr;
StandardGeometryInstance* pNewStandardGeoInstance = nullptr;
if (options.meshType == GeoReaderOptions::eStandardMesh)
{
pNewStandardGeoInstance = new StandardGeometryInstance();
pNewMesh->setGeometryInstance(pNewStandardGeoInstance);
pActualPoints = &pNewStandardGeoInstance->getPoints();
}
else
{
pNewEditableGeoInstance = new EditableGeometryInstance();
pNewMesh->setGeometryInstance(pNewEditableGeoInstance);
pActualPoints = &aTempPoints;
}
std::vector<Element>::const_iterator itEl = header.elements.begin();
for (; itEl != header.elements.end(); ++itEl)
{
const Element& element = *itEl;
if (element.type == Element::eEVertex)
{
pActualPoints->reserve(element.count);
Matrix4 rotate;
rotate.setRotationX(-90.0f);
// assumption here is x y z items are floats and at the beginning
size_t skipSize = 0;
for (unsigned int i = 0; i < element.properties.size(); i++)
{
const Property& property = element.properties[i];
if (property.name == "x" || property.name == "y" || property.name == "z")
continue;
skipSize += Property::getMemSize(property.mainDataType);
}
for (unsigned int i = 0; i < element.count; i++)
{
// we can ideally just read the values into the point item directly...
Point newPoint;
fileStream.read((char*)&newPoint.x, sizeof(float) * 3);
if (header.type == eBinaryBigEndian)
{
newPoint.x = reverseFloatBytes(newPoint.x);
newPoint.y = reverseFloatBytes(newPoint.y);
newPoint.z = reverseFloatBytes(newPoint.z);
}
if (options.rotate90NegX)
{
newPoint = rotate.transformAffine(newPoint);
}
pActualPoints->emplace_back(newPoint);
if (skipSize > 0)
{
// skip past stuff we don't care about
fileStream.seekg(skipSize, std::ios::cur);
}
}
}
else if (element.type == Element::eEFace)
{
if (element.properties.size() == 0)
{
GlobalContext::instance().getLogger().error("Cannot import PLY file: %s - no known face properties found.", path.c_str());
return false;
}
// find the first list element on the assumption that it's the vertex indices list
// TODO: this isn't always going to work, but for all files tested so far, does.
unsigned int vertexListPropertiesIndex = 0;
size_t preSkipSize = 0;
for (unsigned int i = 0; i < element.properties.size(); i++)
{
const Property& testProperty = element.properties[i];
if (testProperty.list)
{
vertexListPropertiesIndex = i;
break;
}
else
{
preSkipSize += Property::getMemSize(testProperty.mainDataType);
}
}
// assume for the moment that the first element property is the vertex indices list
const Property& property = element.properties[vertexListPropertiesIndex];
if (!property.list)
{
GlobalContext::instance().getLogger().error("Cannot import PLY file: %s - unsupported property combination", path.c_str());
return false;
}
if (property.mainDataType != Property::eUChar && property.mainDataType != Property::eChar)
{
GlobalContext::instance().getLogger().error("Cannot import PLY file: %s - unsupported property combination", path.c_str());
return false;
}
// see if there are other
size_t afterSkipSize = 0;
if (element.properties.size() > 1)
{
for (unsigned int i = vertexListPropertiesIndex + 1; i < element.properties.size(); i++)
{
const Property& prop = element.properties[i];
afterSkipSize += Property::getMemSize(prop.mainDataType);
}
}
// in theory, except for the first time through, we can possibly get away
// with combining the pre and after skips together as they'll happen together,
// but to future-proof this, do them separately.
std::deque<Face>& faces = pNewEditableGeoInstance->getFaces();
std::vector<unsigned int> aNGonVertices;
if (header.type == eBinaryLittleEndian)
{
if (options.meshType == GeoReaderOptions::eStandardMesh)
{
std::vector<uint32_t>& aPolyOffsets = pNewStandardGeoInstance->getPolygonOffsets();
std::vector<uint32_t>& aPolyIndices = pNewStandardGeoInstance->getPolygonIndices();
aPolyOffsets.reserve(element.count + 1);
aPolyIndices.reserve(element.count * 3); // rough estimate...
for (unsigned int i = 0; i < element.count; i++)
{
unsigned char numVerts = 0;
if (preSkipSize > 0)
{
// skip past stuff we don't care about
fileStream.seekg(preSkipSize, std::ios::cur);
}
fileStream.read((char*)&numVerts, sizeof(unsigned char));
unsigned int vertices[4];
if (numVerts == 3)
{
fileStream.read((char*)&vertices[0], sizeof(unsigned int) * 3);
aPolyIndices.emplace_back(vertices[0]);
aPolyIndices.emplace_back(vertices[1]);
aPolyIndices.emplace_back(vertices[2]);
}
else if (numVerts == 4)
{
fileStream.read((char*)&vertices[0], sizeof(unsigned int) * 4);
aPolyIndices.emplace_back(vertices[0]);
aPolyIndices.emplace_back(vertices[1]);
aPolyIndices.emplace_back(vertices[2]);
aPolyIndices.emplace_back(vertices[3]);
}
else
{
// only pay this penalty if we need to, on the assumption it'll be pretty rare...
aNGonVertices.resize(numVerts);
fileStream.read((char*)aNGonVertices.data(), sizeof(unsigned int) * numVerts);
std::copy(aNGonVertices.begin(), aNGonVertices.end(), std::back_inserter(aPolyIndices));
}
aPolyOffsets.emplace_back(aPolyIndices.size());
if (afterSkipSize > 0)
{
// skip past stuff we don't care about
fileStream.seekg(afterSkipSize, std::ios::cur);
}
}
}
else
{
for (unsigned int i = 0; i < element.count; i++)
{
unsigned char numVerts = 0;
if (preSkipSize > 0)
{
// skip past stuff we don't care about
fileStream.seekg(preSkipSize, std::ios::cur);
}
fileStream.read((char*)&numVerts, sizeof(unsigned char));
Face newFace((unsigned int)numVerts);
// newFace.reserveUVs(numVerts);
unsigned int vertices[4];
if (numVerts == 3)
{
fileStream.read((char*)&vertices[0], sizeof(unsigned int) * 3);
newFace.addVertex(vertices[0]);
newFace.addVertex(vertices[1]);
newFace.addVertex(vertices[2]);
}
else if (numVerts == 4)
{
fileStream.read((char*)&vertices[0], sizeof(unsigned int) * 4);
newFace.addVertex(vertices[0]);
newFace.addVertex(vertices[1]);
newFace.addVertex(vertices[2]);
newFace.addVertex(vertices[3]);
}
else
{
// only pay this penalty if we need to, on the assumption it'll be pretty rare...
aNGonVertices.resize(numVerts);
fileStream.read((char*)aNGonVertices.data(), sizeof(unsigned int) * numVerts);
std::vector<unsigned int>::const_iterator itVert = aNGonVertices.begin();
for (; itVert != aNGonVertices.end(); ++itVert)
{
newFace.addVertex(*itVert);
}
}
faces.emplace_back(newFace);
if (afterSkipSize > 0)
{
// skip past stuff we don't care about
fileStream.seekg(afterSkipSize, std::ios::cur);
}
}
}
}
else
{
// we need to convert byte orders around, so
if (options.meshType == GeoReaderOptions::eStandardMesh)
{
std::vector<uint32_t>& aPolyOffsets = pNewStandardGeoInstance->getPolygonOffsets();
std::vector<uint32_t>& aPolyIndices = pNewStandardGeoInstance->getPolygonIndices();
aPolyOffsets.reserve(element.count + 1);
aPolyIndices.reserve(element.count * 3); // rough estimate...
for (unsigned int i = 0; i < element.count; i++)
{
unsigned char numVerts = 0;
if (preSkipSize > 0)
{
// skip past stuff we don't care about
fileStream.seekg(preSkipSize, std::ios::cur);
}
fileStream.read((char*)&numVerts, sizeof(unsigned char));
unsigned int vertices[4];
if (numVerts == 3)
{
fileStream.read((char*)&vertices[0], sizeof(unsigned int) * 3);
// TODO: this can be more inlined, and it probably aliases too
// but doing it this way is useful for debugging, so...
vertices[0] = reverseUIntBytes(vertices[0]);
vertices[1] = reverseUIntBytes(vertices[1]);
vertices[2] = reverseUIntBytes(vertices[2]);
aPolyIndices.emplace_back(vertices[0]);
aPolyIndices.emplace_back(vertices[1]);
aPolyIndices.emplace_back(vertices[2]);
}
else if (numVerts == 4)
{
fileStream.read((char*)&vertices[0], sizeof(unsigned int) * 4);
// TODO: this can be more inlined, and it probably aliases too
// but doing it this way is useful for debugging, so...
vertices[0] = reverseUIntBytes(vertices[0]);
vertices[1] = reverseUIntBytes(vertices[1]);
vertices[2] = reverseUIntBytes(vertices[2]);
vertices[3] = reverseUIntBytes(vertices[3]);
aPolyIndices.emplace_back(vertices[0]);
aPolyIndices.emplace_back(vertices[1]);
aPolyIndices.emplace_back(vertices[2]);
aPolyIndices.emplace_back(vertices[3]);
}
else
{
// only pay this penalty if we need to, on the assumption it'll be pretty rare...
aNGonVertices.resize(numVerts);
fileStream.read((char*)aNGonVertices.data(), sizeof(unsigned int) * numVerts);
std::vector<unsigned int>::const_iterator itVert = aNGonVertices.begin();
for (; itVert != aNGonVertices.end(); ++itVert)
{
unsigned int vertexIndex = *itVert;
aPolyIndices.emplace_back(reverseUIntBytes(vertexIndex));
}
}
aPolyOffsets.emplace_back(aPolyIndices.size());
if (afterSkipSize > 0)
{
// skip past stuff we don't care about
fileStream.seekg(afterSkipSize, std::ios::cur);
}
}
}
else
{
for (unsigned int i = 0; i < element.count; i++)
{
unsigned char numVerts = 0;
if (preSkipSize > 0)
{
// skip past stuff we don't care about
fileStream.seekg(preSkipSize, std::ios::cur);
}
fileStream.read((char*)&numVerts, sizeof(unsigned char));
Face newFace((unsigned int)numVerts);
// newFace.reserveUVs(numVerts);
unsigned int vertices[4];
if (numVerts == 3)
{
fileStream.read((char*)&vertices[0], sizeof(unsigned int) * 3);
// TODO: this can be more inlined, and it probably aliases too
// but doing it this way is useful for debugging, so...
vertices[0] = reverseUIntBytes(vertices[0]);
vertices[1] = reverseUIntBytes(vertices[1]);
vertices[2] = reverseUIntBytes(vertices[2]);
newFace.addVertex(vertices[0]);
newFace.addVertex(vertices[1]);
newFace.addVertex(vertices[2]);
}
else if (numVerts == 4)
{
fileStream.read((char*)&vertices[0], sizeof(unsigned int) * 4);
// TODO: this can be more inlined, and it probably aliases too
// but doing it this way is useful for debugging, so...
vertices[0] = reverseUIntBytes(vertices[0]);
vertices[1] = reverseUIntBytes(vertices[1]);
vertices[2] = reverseUIntBytes(vertices[2]);
vertices[3] = reverseUIntBytes(vertices[3]);
newFace.addVertex(vertices[0]);
newFace.addVertex(vertices[1]);
newFace.addVertex(vertices[2]);
newFace.addVertex(vertices[3]);
}
else
{
// only pay this penalty if we need to, on the assumption it'll be pretty rare...
aNGonVertices.resize(numVerts);
fileStream.read((char*)aNGonVertices.data(), sizeof(unsigned int) * numVerts);
std::vector<unsigned int>::const_iterator itVert = aNGonVertices.begin();
for (; itVert != aNGonVertices.end(); ++itVert)
{
unsigned int vertexIndex = *itVert;
newFace.addVertex(reverseUIntBytes(vertexIndex));
}
}
faces.emplace_back(newFace);
if (afterSkipSize > 0)
{
// skip past stuff we don't care about
fileStream.seekg(afterSkipSize, std::ios::cur);
}
}
}
}
}
}
if (options.meshType != GeoReaderOptions::eStandardMesh)
{
std::deque<Point>& geoPoints = pNewEditableGeoInstance->getPoints();
std::copy(pActualPoints->begin(), pActualPoints->end(), std::back_inserter(geoPoints));
// now we've copied the points for the EditableGeometryInstance, we need to go through the faces
// calculating the normals
std::deque<Face>& faces = pNewEditableGeoInstance->getFaces();
std::deque<Face>::iterator itFace = faces.begin();
for (; itFace != faces.end(); ++itFace)
{
Face& face = *itFace;
face.calculateNormal(pNewEditableGeoInstance);
}
}
fileStream.close();
m_newObject = pNewMesh;
postProcess();
return true;
}
} // namespace Imagine
namespace
{
Imagine::GeoReader* createGeoReaderPly()
{
return new Imagine::GeoReaderPly();
}
const bool registered = Imagine::FileIORegistry::instance().registerGeoReader("ply", createGeoReaderPly);
}
| 27.879052 | 142 | 0.63764 | [
"mesh",
"geometry",
"vector"
] |
e974ece96493756c8c28d01a516b61a09a810294 | 13,977 | cpp | C++ | source/cpfs_winfsp/main.cpp | clayne/CyberpunkSaveEditor | 2069ea833ced56f549776179c2147b27d32d650c | [
"MIT"
] | 276 | 2020-12-21T11:54:44.000Z | 2022-03-28T16:49:44.000Z | source/cpfs_winfsp/main.cpp | 13397729377/CyberpunkSaveEditor | 2069ea833ced56f549776179c2147b27d32d650c | [
"MIT"
] | 37 | 2020-12-21T18:25:12.000Z | 2022-03-31T23:51:33.000Z | source/cpfs_winfsp/main.cpp | 13397729377/CyberpunkSaveEditor | 2069ea833ced56f549776179c2147b27d32d650c | [
"MIT"
] | 36 | 2020-12-21T12:02:08.000Z | 2022-03-21T10:47:43.000Z | #define WIN32_NO_STATUS
#define NOMINMAX
#include <windows.h>
#include <shellapi.h>
#include <commctrl.h>
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#pragma comment(lib, "comctl32.lib")
#include <winfsp/winfsp.h>
#include <cstdio>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/dist_sink.h>
#include <cpfs_winfsp/resource.h>
#include <cpfs_winfsp/cpfs.hpp>
void debug_symlink(const std::filesystem::path& p);
//#define CONSOLE_LOG_AT_STARTUP
constexpr auto WNDCLS_NAME = L"cpfs_systray";
static constexpr UINT WMAPP_SYSTRAYCB = (WM_APP + 100);
static HINSTANCE s_hInst = NULL;
static HWND s_hAboutDlg = NULL;
static HICON s_hIcon = NULL;
static HMENU s_hCtxMenu = NULL;
LRESULT WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
BOOL AddNotificationIcon(HWND hWnd);
BOOL DeleteNotificationIcon(HWND hWnd);
BOOL ShowAboutDlg(HWND hWnd);
VOID ShowContextMenu(HWND hWnd, POINT pt);
std::shared_ptr<spdlog::sinks::dist_sink_mt> s_console_sink_wrapper;
spdlog::sink_ptr s_console_sink;
void ShowConsole()
{
if (!s_console_sink)
{
AllocConsole();
SetConsoleCtrlHandler(nullptr, true);
// remove close button
HWND hWnd = ::GetConsoleWindow();
if (hWnd != NULL)
{
HMENU hMenu = ::GetSystemMenu(hWnd, FALSE);
if (hMenu != NULL)
{
DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
}
}
s_console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
s_console_sink_wrapper->add_sink(s_console_sink);
}
}
void HideConsole()
{
if (s_console_sink)
{
FreeConsole();
s_console_sink_wrapper->remove_sink(s_console_sink);
s_console_sink.reset();
}
}
int wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nShowCmd)
{
s_hInst = hInstance;
//----------------------------------------
s_hIcon = LoadIconW(s_hInst, MAKEINTRESOURCE(IDI_ICON1));
WNDCLASSEXW wcex = {sizeof(wcex)};
wcex.lpfnWndProc = WndProc;
wcex.hInstance = s_hInst;
wcex.lpszClassName = WNDCLS_NAME;
RegisterClassExW(&wcex);
HWND hwnd = CreateWindowExW(0, WNDCLS_NAME, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0);
UpdateWindow(hwnd);
//----------------------------------------
s_console_sink_wrapper = std::make_shared<spdlog::sinks::dist_sink_mt>();
std::vector<spdlog::sink_ptr> spdlog_sinks;
spdlog_sinks.emplace_back(s_console_sink_wrapper);
// todo: add rotating file logger..
auto combined_logger = std::make_shared<spdlog::logger>("cpfs_logger", std::begin(spdlog_sinks), std::end(spdlog_sinks));
spdlog::set_default_logger(combined_logger);
spdlog::set_level(spdlog::level::debug);
spdlog::set_pattern("[%x %X.%e] [%^-%L-%$] [tid:%t] [%s:%#] %!: %v");
#ifdef CONSOLE_LOG_AT_STARTUP
ShowConsole();
#endif
//
//ShowAboutBubble();
cpfs cpfs;
SPDLOG_INFO("initializing cpfs");
#ifdef _DEBUG
if (!cpfs.init(-1))
#else
if (!cpfs.init(0))
#endif
{
return -1;
}
SPDLOG_INFO("loading archives");
if (!cpfs.load_archives())
{
return -1;
}
SPDLOG_INFO("starting cpfs");
if (!cpfs.start())
{
return -1;
}
if (1)
{
std::filesystem::path test_path(cpfs.disk_letter);
test_path /= "\\D251917154DF532F";
SPDLOG_INFO("symlink test..");
std::filesystem::directory_entry dirent(test_path);
if (dirent.is_symlink())
{
SPDLOG_INFO("symlink {} resolved to: {}", test_path.string(), std::filesystem::read_symlink(test_path).string());
}
else
{
SPDLOG_INFO("{} wasn't recognized as a symlink (type:{})", test_path.string(), dirent.status().type());
}
}
if (0)
{
SPDLOG_INFO("symlink testing #2");
debug_symlink("Z:\\0af6d3d6f362bf06");
debug_symlink("D:\\Desktop\\cpsavedit\\BUF_FILES\\big_folder_test2\\sdsd");
}
NOTIFYICONDATAW nid = {sizeof(nid)};
nid.hWnd = hwnd;
nid.uID = IDI_ICON1;
nid.uFlags = NIF_INFO;
nid.dwInfoFlags = NIIF_INFO | NIIF_RESPECT_QUIET_TIME;
wcscpy_s(nid.szInfoTitle, L"CPFS");
wcscpy_s(nid.szInfo, L"successfully mounted");
Shell_NotifyIconW(NIM_MODIFY, &nid);
MSG msg;
bool running = true;
while (running)
{
if (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
if (msg.message == WM_QUIT)
running = false;
}
if (running)
{
}
}
//if (0)
//{
// redx::filesystem::recursive_directory_iterator it(cpfs.tfs, "base\\worlds\\03_night_city\\sectors\\_generated\\global_illumination");
// SPDLOG_INFO("start");
// size_t i = 0;
// for (const auto& dirent: it)
// {
// SPDLOG_INFO("[{:04d}][{}] {}", i++,
// (dirent.is_reserved_for_file() ? "R" : (dirent.is_file() ? "F" : "D")),
// dirent.tfs_path().strv());
//
// if (dirent.is_reserved_for_file())
// {
// SPDLOG_INFO("IS_RESERVED_FOR_FILE");
// redx::filesystem::directory_entry d(cpfs.tfs, dirent.tfs_path());
// SPDLOG_INFO("resolved: {}", d.tfs_path().strv());
// }
//
// if (i > 500) break;
// }
// SPDLOG_INFO("end");
//}
return 0;
}
BOOL InitCtxMenu()
{
HMENU hMenu = LoadMenuW(s_hInst, MAKEINTRESOURCE(IDR_MENU1));
if (hMenu)
{
s_hCtxMenu = GetSubMenu(hMenu, 0);
RemoveMenu(hMenu, 0, MF_BYPOSITION);
DestroyMenu(hMenu);
return TRUE;
}
return FALSE;
}
BOOL AddNotificationIcon(HWND hWnd)
{
NOTIFYICONDATAW nid = {sizeof(nid)};
nid.hWnd = hWnd;
nid.uID = IDI_ICON1;
nid.uFlags = NIF_ICON | NIF_MESSAGE;
nid.uCallbackMessage = WMAPP_SYSTRAYCB;
nid.hIcon = s_hIcon;
if (!Shell_NotifyIconW(NIM_ADD, &nid))
{
SPDLOG_CRITICAL("couldn't add notify icon, {}", cp::os::last_error_string());
return false;
}
nid.uVersion = NOTIFYICON_VERSION_4;
Shell_NotifyIconW(NIM_SETVERSION, &nid);
return true;
}
BOOL DeleteNotificationIcon(HWND hWnd)
{
NOTIFYICONDATAW nid = {sizeof(nid)};
nid.hWnd = hWnd;
nid.uID = IDI_ICON1;
//wnid.uFlags = NIF_GUID;
//nid.guidItem = __uuidof(cpfs_systray_cls);
return Shell_NotifyIcon(NIM_DELETE, &nid);
}
LRESULT WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch (Msg)
{
case WM_CREATE:
{
InitCtxMenu();
AddNotificationIcon(hWnd);
break;
}
case WM_DESTROY:
{
DeleteNotificationIcon(hWnd);
DestroyMenu(s_hCtxMenu);
PostQuitMessage(0);
break;
}
case WMAPP_SYSTRAYCB:
{
switch (LOWORD(lParam))
{
case WM_CONTEXTMENU:
{
POINT const pt = {LOWORD(wParam), HIWORD(wParam)};
ShowContextMenu(hWnd, pt);
break;
}
default:
break;
}
break;
}
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case IDM_ABOUT:
{
ShowAboutDlg(hWnd);
break;
}
case IDM_LOG:
{
UINT state = GetMenuState(s_hCtxMenu, IDM_LOG, MF_BYCOMMAND);
if (!(state & MF_CHECKED))
{
CheckMenuItem(s_hCtxMenu, IDM_LOG, MF_BYCOMMAND | MF_CHECKED);
ShowConsole();
}
else
{
CheckMenuItem(s_hCtxMenu, IDM_LOG, MF_BYCOMMAND | MF_UNCHECKED);
HideConsole();
}
break;
}
case IDM_EXIT:
{
DestroyWindow(hWnd);
break;
}
default:
break;
}
break;
}
default:
break;
}
return DefWindowProc(hWnd, Msg, wParam, lParam);
}
INT_PTR CALLBACK AboutDlgFunc(HWND hWndDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch (Msg)
{
case WM_INITDIALOG:
{
SendMessageW(hWndDlg, WM_SETICON, 0, (LPARAM)s_hIcon);
return TRUE;
}
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case IDOK:
{
EndDialog(hWndDlg, wParam);
return TRUE;
}
case IDC_BUTTON1:
{
ShellExecuteA(NULL, "open", "https://github.com/PixelRick/", NULL, NULL, SW_SHOWNORMAL);
return TRUE;
}
case IDC_BUTTON2:
{
ShellExecuteA(NULL, "open", "http://www.secfs.net/winfsp/", NULL, NULL, SW_SHOWNORMAL);
return TRUE;
}
default:
break;
}
}
default:
break;
}
return FALSE;
}
BOOL ShowAboutDlg(HWND hWnd)
{
//CreateDialogW
DialogBoxW(s_hInst, MAKEINTRESOURCE(IDD_DIALOG1), hWnd, &AboutDlgFunc);
return true;
}
void ShowContextMenu(HWND hWnd, POINT pt)
{
if (s_hCtxMenu)
{
// our window must be foreground before calling TrackPopupMenu or the menu will not disappear when the user clicks away
SetForegroundWindow(hWnd);
// respect menu drop alignment
UINT uFlags = TPM_RIGHTBUTTON;
if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0)
{
uFlags |= TPM_RIGHTALIGN;
}
else
{
uFlags |= TPM_LEFTALIGN;
}
TrackPopupMenuEx(s_hCtxMenu, uFlags, pt.x, pt.y, hWnd, NULL);
}
}
void debug_symlink(const std::filesystem::path& p)
{
HANDLE Handle;
SPDLOG_INFO("checking symlink {} target", p.string());
Handle = CreateFileW(p.c_str(),
FILE_READ_ATTRIBUTES | READ_CONTROL, 0, 0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (Handle != INVALID_HANDLE_VALUE)
{
FILE_ATTRIBUTE_TAG_INFO AttributeTagInfo;
if (GetFileInformationByHandleEx(Handle, FileAttributeTagInfo, &AttributeTagInfo, sizeof AttributeTagInfo))
{
SPDLOG_INFO("symlink target attributes:{:X} tag:{:X}",
AttributeTagInfo.FileAttributes, AttributeTagInfo.ReparseTag);
}
else
{
SPDLOG_INFO("GetFileInformationByHandleEx failed:{}", cp::os::last_error_string());
}
BY_HANDLE_FILE_INFORMATION ByHandleInfo;
if (GetFileInformationByHandle(Handle, &ByHandleInfo))
{
SPDLOG_INFO("symlink target nFileSizeHigh:{:X} nFileSizeLow:{:X} nNumberOfLinks:{:X} nFileIndexHigh:{:X} nFileIndexLow:{:X}",
ByHandleInfo.nFileSizeHigh, ByHandleInfo.nFileSizeLow, ByHandleInfo.nNumberOfLinks, ByHandleInfo.nFileIndexHigh, ByHandleInfo.nFileIndexLow);
}
else
{
SPDLOG_INFO("GetFileInformationByHandle failed:{}", cp::os::last_error_string());
}
WCHAR wbuf[1000]{};
if (GetFinalPathNameByHandleW(Handle, wbuf, 1000, FILE_NAME_OPENED))
{
SPDLOG_INFO("symlink target FinalPathName:{}", std::filesystem::path(wbuf).string());
}
else
{
SPDLOG_INFO("GetFinalPathNameByHandleW failed:{}", cp::os::last_error_string());
}
CloseHandle(Handle);
}
SPDLOG_INFO("checking symlink {}", p.string());
Handle = CreateFileW(p.c_str(),
FILE_READ_ATTRIBUTES | READ_CONTROL, 0, 0,
OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, 0);
if (Handle != INVALID_HANDLE_VALUE)
{
FILE_ATTRIBUTE_TAG_INFO AttributeTagInfo;
if (GetFileInformationByHandleEx(Handle, FileAttributeTagInfo, &AttributeTagInfo, sizeof AttributeTagInfo))
{
SPDLOG_INFO("symlink attributes:{:X} tag:{:X}", AttributeTagInfo.FileAttributes, AttributeTagInfo.ReparseTag);
}
else
{
SPDLOG_INFO("GetFileInformationByHandleEx failed:{}", cp::os::last_error_string());
}
char buf[2000];
DWORD resp_size = 0;
if (DeviceIoControl(Handle, FSCTL_GET_REPARSE_POINT, NULL, 0, buf, 2000, &resp_size, NULL))
{
auto reparse_data = reinterpret_cast<REPARSE_DATA_BUFFER*>(buf);
SPDLOG_INFO("symlink reparse_data->ReparseTag:{}", reparse_data->ReparseTag);
if (reparse_data->ReparseTag == IO_REPARSE_TAG_SYMLINK)
{
const size_t subslen = reparse_data->SymbolicLinkReparseBuffer.SubstituteNameLength / 2;
const size_t subsoff = reparse_data->SymbolicLinkReparseBuffer.SubstituteNameOffset / 2;
const size_t prntlen = reparse_data->SymbolicLinkReparseBuffer.PrintNameLength / 2;
const size_t prntoff = reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset / 2;
std::wstring_view wsubs(reparse_data->SymbolicLinkReparseBuffer.PathBuffer + subsoff, subslen);
std::filesystem::path subs_path(wsubs);
std::wstring_view wprnt(reparse_data->SymbolicLinkReparseBuffer.PathBuffer + prntoff, prntlen);
std::filesystem::path prnt_path(wprnt);
SPDLOG_INFO("symlink Flags:{:X}, SubstituteName:{} PrintName:{}", reparse_data->SymbolicLinkReparseBuffer.Flags, subs_path.string(), prnt_path.string());
}
}
else
{
SPDLOG_INFO("DeviceIoControl failed:{}", cp::os::last_error_string());
}
WCHAR wbuf[1000]{};
if (GetFinalPathNameByHandleW(Handle, wbuf, 1000, FILE_NAME_OPENED))
{
SPDLOG_INFO("symlink target FinalPathName:{}", std::filesystem::path(wbuf).string());
}
else
{
SPDLOG_INFO("GetFinalPathNameByHandleW failed:{}", cp::os::last_error_string());
}
CloseHandle(Handle);
}
WIN32_FIND_DATA FindData;
Handle = FindFirstFileExW(p.c_str(), FindExInfoStandard, &FindData, FindExSearchNameMatch, NULL, 0);
if (Handle != INVALID_HANDLE_VALUE)
{
SPDLOG_INFO("symlink dirsearch Attrs:{:X}, FileName:{} AltFileName:{}",
FindData.dwFileAttributes, std::filesystem::path(FindData.cFileName).string(), std::filesystem::path(FindData.cAlternateFileName).string());
}
}
| 26.775862 | 195 | 0.623524 | [
"vector"
] |
e97d8dcb24cb898b91b6407a97746360569a5e7c | 16,203 | cxx | C++ | codes/Controller/InteractorStyles/InteractorStylePolygonDraw.cxx | wuzhuobin/Vessel_Project | eab73b02067f4542f5e9be50cc72de44d64fc322 | [
"Apache-2.0"
] | 3 | 2017-06-03T03:17:39.000Z | 2021-01-17T05:51:31.000Z | codes/Controller/InteractorStyles/InteractorStylePolygonDraw.cxx | wuzhuobin/Vessel_Project | eab73b02067f4542f5e9be50cc72de44d64fc322 | [
"Apache-2.0"
] | 4 | 2017-04-19T13:59:30.000Z | 2017-05-11T02:52:49.000Z | codes/Controller/InteractorStyles/InteractorStylePolygonDraw.cxx | wuzhuobin/Vessel_Project | eab73b02067f4542f5e9be50cc72de44d64fc322 | [
"Apache-2.0"
] | 1 | 2018-05-02T06:58:31.000Z | 2018-05-02T06:58:31.000Z | /*
Author: Wong, Matthew Lun
Date: 16th, June 2016
Occupation: Chinese University of Hong Kong,
Department of Imaging and Inteventional Radiology,
Junior Research Assistant
Author: Lok, Ka Hei Jason
Date: 16th, June 2016
Occupation: Chinese University of Hong Kong,
Department of Imaging and Inteventional Radiology,
M.Phil Student
This class allows interactive segmentation on images with contour widget.
Wong Matthew Lun, Lok Ka Hei
Copyright (C) 2016
*/
#include <vtkContourWidget.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkPolygon.h>
#include <vtkMath.h>
#include <vtkLinearContourLineInterpolator.h>
#include <vtkBezierContourLineInterpolator.h>
#include <vtkProperty.h>
#include <vtkContourWidget.h>
#include <vtkOrientedGlyphContourRepresentation.h>
#include <vtkIncrementalOctreePointLocator.h>
#include <vtkObjectFactory.h>
#include <vtkImageActorPointPlacer.h>
#include <vtkPolyData.h>
#include <vtkImageData.h>
#include <algorithm>
#include "InteractorStylePolygonDraw.h"
#include "ImageViewer.h"
using namespace std;
vtkStandardNewMacro(InteractorStylePolygonDraw);
InteractorStylePolygonDraw::InteractorStylePolygonDraw()
:AbstractNavigation()
{
this->m_interpolator =
vtkSmartPointer<vtkBezierContourLineInterpolator>::New();
}
InteractorStylePolygonDraw::~InteractorStylePolygonDraw()
{
}
void InteractorStylePolygonDraw::OnLeftButtonDown()
{
AbstractNavigation::OnLeftButtonDown();
}
void InteractorStylePolygonDraw::OnRightButtonDown()
{
AbstractNavigation::OnRightButtonDown();
if (m_currentContour != nullptr) {
m_currentContour->CloseLoop();
}
}
void InteractorStylePolygonDraw::OnMouseMove()
{
if (GetCustomEnabled()) {
NewContour();
m_currentContour->EnabledOn();
}
}
void InteractorStylePolygonDraw::OnKeyPress()
{
std::string key = this->Interactor->GetKeySym();
if (key == "Escape") {
CleanAllContours();
}
else if (key == "Return" ) {
this->FillPolygon();
}
else {
AbstractNavigation::OnKeyPress();
}
}
void InteractorStylePolygonDraw::SetCustomEnabled(bool b)
{
AbstractNavigation::SetCustomEnabled(b);
if (!b) {
CleanAllContours();
m_currentContour = nullptr;
}
}
void InteractorStylePolygonDraw::NewContour()
{
// if user is manipulate a contour widget, the interactorstyle will not
// generate new contour widget
if (m_currentContour != nullptr &&
m_currentContour->GetWidgetState() != vtkContourWidget::Manipulate) {
return;
}
// close loop the last contour
if (m_contours.size() != 0) {
m_contours.back()->CloseLoop();
}
m_contours.push_back(vtkSmartPointer<vtkContourWidget>::New());
m_currentContour = m_contours.back();
m_currentContour->SetRepresentation(
vtkSmartPointer<vtkOrientedGlyphContourRepresentation>::New());
m_currentContour->SetInteractor(this->Interactor);
m_currentContour->SetCurrentRenderer(GetImageViewer()->GetRenderer());
m_currentContour->ContinuousDrawOn();
m_currentContour->FollowCursorOn();
m_currentContourRep = vtkOrientedGlyphContourRepresentation::SafeDownCast(
m_currentContour->GetContourRepresentation());
m_currentContourRep->GetLinesProperty()->SetColor(0, 255, 0);
m_currentContourRep->SetLineInterpolator(m_interpolator);
m_currentContourRep->AlwaysOnTopOn();
vtkSmartPointer<vtkImageActorPointPlacer> pointPlacer =
vtkSmartPointer<vtkImageActorPointPlacer>::New();
pointPlacer->SetImageActor(GetImageViewer()->GetImageActor());
m_currentContourRep->SetPointPlacer(pointPlacer);
}
void InteractorStylePolygonDraw::SetContourLabel(unsigned char noSegLabel)
{
this->m_contourLabel = noSegLabel;
}
void InteractorStylePolygonDraw::CleanCurrentContour()
{
if (m_contours.size() > 0) {
m_contours.back()->EnabledOff();
m_contours.pop_back();
}
// none contours left, just set m_currentContour = nullptr
if (m_contours.size() == 0) {
m_currentContour = nullptr;
}
else {
m_currentContour = m_contours.back();
}
GetImageViewer()->Render();
}
void InteractorStylePolygonDraw::CleanAllContours()
{
for (list<vtkSmartPointer<vtkContourWidget>>::const_iterator cit
= m_contours.cbegin(); cit != m_contours.cend();
++cit) {
(*cit)->EnabledOff();
}
m_contours.clear();
m_currentContour = nullptr;
GetImageViewer()->Render();
}
void InteractorStylePolygonDraw::SetAllContoursEnabled(int flag)
{
for (list<vtkSmartPointer<vtkContourWidget>>::const_iterator cit
= m_contours.cbegin(); cit != m_contours.cend();
++cit) {
(*cit)->SetEnabled(flag);
}
}
void InteractorStylePolygonDraw::SetSmoothCurveEnable()
{
SetLineInterpolator(0);
}
void InteractorStylePolygonDraw::SetPolygonEnable()
{
SetLineInterpolator(1);
}
void InteractorStylePolygonDraw::SetLineInterpolator(int i)
{
switch (i)
{
case 0:
this->m_interpolator = vtkSmartPointer<vtkBezierContourLineInterpolator>::New();
break;
case 1:
this->m_interpolator = vtkSmartPointer<vtkLinearContourLineInterpolator>::New();
break;
}
if (m_currentContour != nullptr &&
m_currentContour->GetWidgetState() != vtkContourWidget::Manipulate) {
CleanCurrentContour();
}
}
void InteractorStylePolygonDraw::FillPolygon()
{
FillPolygon(&m_contours, m_contourLabel);
}
void InteractorStylePolygonDraw::FillPolygon(
std::list<vtkSmartPointer<vtkContourWidget>> * contour, unsigned char label)
{
vtkSmartPointer<vtkPoints> fillPoints =
vtkSmartPointer<vtkPoints>::New();
list<vtkSmartPointer<vtkPolygon>> contourPolygons;
for (list<vtkSmartPointer<vtkContourWidget>>::const_iterator cit = contour->cbegin();
cit != contour->cend(); ++cit) {
vtkPolyData* _polyData;
if ((*cit) == nullptr) {
continue;
}
if ((*cit)->GetContourRepresentation() == nullptr ||
(*cit)->GetContourRepresentation()->GetNumberOfNodes() < 3) {
continue;
}
// Check if contour is drawn correctly
_polyData = (*cit)->GetContourRepresentation()->GetContourRepresentationAsPolyData();
if (_polyData == nullptr || _polyData->GetNumberOfPoints() < 3) {
vtkErrorMacro( << "_polyData is nullptr");
continue;
}
(*cit)->CloseLoop();
contourPolygons.push_back(vtkSmartPointer<vtkPolygon>::New());
// Get the coordinates of the contour data points
double lastPoint[3] = { VTK_DOUBLE_MAX, VTK_DOUBLE_MAX, VTK_DOUBLE_MAX };
for (vtkIdType i = 0; i < _polyData->GetNumberOfPoints(); i++)
{
double displayCoordinate[3];
const double* worldCoordinate = _polyData->GetPoint(i);
//Take one image data 1 to be reference
displayCoordinate[0] = ((worldCoordinate[0] - GetOrigin()[0]) / GetSpacing()[0] );
displayCoordinate[1] = ((worldCoordinate[1] - GetOrigin()[1]) / GetSpacing()[1] );
displayCoordinate[2] = ((worldCoordinate[2] - GetOrigin()[2]) / GetSpacing()[2] );
displayCoordinate[GetSliceOrientation()] = GetSlice();
//cout << s[0] << " " << s[1] << " " << s[2] << endl;
//Test whether the points are inside the polygon or not
// if the points is too close to the previous point, skip it to avoid error in PointInPolygon algorithm
double d = vtkMath::Distance2BetweenPoints(lastPoint, displayCoordinate);
if (d < 1E-5)
continue;
memcpy(lastPoint, displayCoordinate, sizeof(displayCoordinate));
// Because the index of the SliceOrientation is wrong in double
// it need to be set manually
contourPolygons.back()->GetPoints()->InsertNextPoint(displayCoordinate);
}
}
FillPolygon(&contourPolygons, label );
}
void InteractorStylePolygonDraw::FillPolygon(
std::list<vtkSmartPointer<vtkPolygon>>* contourPolygon, unsigned char label) {
vtkSmartPointer<vtkPoints> fillPoints =
vtkSmartPointer<vtkPoints>::New();
for (list<vtkSmartPointer<vtkPolygon>>::const_iterator cit = contourPolygon->cbegin();
cit != contourPolygon->cend(); ++cit) {
if ((*cit) == nullptr || (*cit)->GetPoints()->GetNumberOfPoints() < 3) {
continue;
}
//Test whether the points are inside the polygon or not
double normalVector[3];
(*cit)->ComputeNormal((*cit)->GetPoints()->GetNumberOfPoints(),
static_cast<double*>((*cit)->GetPoints()->GetData()->GetVoidPointer(0)), normalVector);
int bounds[6];
std::copy((*cit)->GetPoints()->GetBounds(), (*cit)->GetPoints()->GetBounds() + 6, bounds);
// doing clamping
for (int boundIndex = 0; boundIndex < 3; ++boundIndex) {
bounds[2 * boundIndex] =
max(bounds[2 * boundIndex] - 3, GetExtent()[2 * boundIndex]);
bounds[2 * boundIndex + 1] =
min(bounds[2 * boundIndex + 1] + 3, GetExtent()[2 * boundIndex + 1]);
}
for (int x = bounds[0]; x <= bounds[1]; x++) {
for (int y = bounds[2]; y <= bounds[3]; y++) {
for (int z = bounds[4]; z <= bounds[5]; z++) {
double p[3] = {
static_cast<double>(x),
static_cast<double>(y),
static_cast<double>(z) };
if (vtkPolygon::PointInPolygon(p, (*cit)->GetPoints()->GetNumberOfPoints(),
static_cast<double*>(
(*cit)->GetPoints()->GetData()->GetVoidPointer(0)),
(*cit)->GetPoints()->GetBounds(), normalVector)) {
fillPoints->InsertNextPoint(p);
unsigned char * pixel = static_cast<unsigned char *>(GetImageViewer()->GetOverlay()->GetScalarPointer(p[0], p[1], p[2]));
*pixel = label;
}
}
}
}
}
if (fillPoints->GetNumberOfPoints() < 1)
return;
//m_imageViewer->GetOverlay()->SetPixels(fillPoints, (unsigned char)label);
GetImageViewer()->GetOverlay()->Modified();
SAFE_DOWN_CAST_IMAGE_CONSTITERATOR(InteractorStylePolygonDraw, GetImageViewer()->Render());
}
void InteractorStylePolygonDraw::FillPolygon(
std::list<vtkSmartPointer<vtkPolygon>>* contourPolygon, unsigned char label, int slice)
{
vtkSmartPointer<vtkPoints> fillPoints =
vtkSmartPointer<vtkPoints>::New();
for (list<vtkSmartPointer<vtkPolygon>>::const_iterator cit = contourPolygon->cbegin();
cit != contourPolygon->cend(); ++cit) {
if ((*cit) == nullptr || (*cit)->GetPoints()->GetNumberOfPoints() < 3) {
continue;
}
const double* lastPoint =
(*cit)->GetPoints()->GetPoint((*cit)->GetPoints()->GetNumberOfPoints() - 1);
const double* firstPoint = (*cit)->GetPoints()->GetPoint(0);
// remove duplicate last point
// without this, pointsInPolygon may be wrong
while (std::equal(lastPoint, lastPoint + 3, firstPoint)) {
(*cit)->GetPoints()->SetNumberOfPoints((*cit)->GetPoints()->GetNumberOfPoints() - 1);
}
//Test whether the points are inside the polygon or not
double normalVector[3];
(*cit)->ComputeNormal((*cit)->GetPoints()->GetNumberOfPoints(),
static_cast<double*>((*cit)->GetPoints()->GetData()->GetVoidPointer(0)), normalVector);
int bounds[6];
std::copy((*cit)->GetBounds(), (*cit)->GetBounds() + 6, bounds);
// doing clamping
for (int boundIndex = 0; boundIndex < 3; ++boundIndex) {
bounds[2 * boundIndex] =
max(bounds[2 * boundIndex] - 3, GetExtent()[2 * boundIndex]);
bounds[2 * boundIndex + 1] =
min(bounds[2 * boundIndex + 1] + 3, GetExtent()[2 * boundIndex + 1]);
}
for (int x = bounds[0]; x <= bounds[1]; x++) {
for (int y = bounds[2]; y <= bounds[3]; y++) {
for (int z = bounds[4]; z <= bounds[5]; z++) {
double p[3] = {
static_cast<double>(x),
static_cast<double>(y),
static_cast<double>(z) };
if (vtkPolygon::PointInPolygon(p, (*cit)->GetPoints()->GetNumberOfPoints(),
static_cast<double*>(
(*cit)->GetPoints()->GetData()->GetVoidPointer(0)),
(*cit)->GetPoints()->GetBounds(), normalVector)) {
p[GetSliceOrientation()] = slice;
fillPoints->InsertNextPoint(p[0], p[1], p[2]);
unsigned char * pixel = static_cast<unsigned char *>(GetImageViewer()->GetOverlay()->GetScalarPointer(p[0], p[1], p[2]));
*pixel = label;
}
}
}
}
}
if (fillPoints->GetNumberOfPoints() < 1)
return;
//m_imageViewer->GetOverlay()->SetPixels(fillPoints, (unsigned char)label);
GetImageViewer()->GetOverlay()->Modified();
SAFE_DOWN_CAST_IMAGE_CONSTITERATOR(InteractorStylePolygonDraw, GetImageViewer()->Render());
}
//void InteractorStylePolygonDraw::FillPolygon(
// std::list<vtkSmartPointer<vtkContourWidget>> * contour, unsigned char label)
//{
// for (list<vtkSmartPointer<vtkContourWidget>>::const_iterator cit = contour->cbegin();
// cit != contour->cend(); ++cit) {
// vtkPolyData* _polyData;
// if ((*cit) == nullptr) {
// continue;
// }
// if ((*cit)->GetContourRepresentation() == nullptr) {
// continue;
// }
// _polyData = (*cit)->GetContourRepresentation()->GetContourRepresentationAsPolyData();
// if (_polyData == nullptr || _polyData->GetNumberOfPoints() < 3) {
// continue;
// }
// (*cit)->CloseAllLoops();
//
// // Check if contour is drawn
// if (_polyData->GetNumberOfPoints() == 0)
// return;
//
// vtkSmartPointer<vtkPolygon> polygon = vtkSmartPointer<vtkPolygon>::New();
// int numOfPoints = _polyData->GetNumberOfPoints();
//
// // Get the coordinates of the contour data points
//
// double lastPoint[3] = { VTK_DOUBLE_MAX, VTK_DOUBLE_MAX, VTK_DOUBLE_MAX };
// for (vtkIdType i = 0; i < numOfPoints; i++)
// {
// double worldCoordinate[3];
// double displayCoordinate[3];
// _polyData->GetPoint(i, worldCoordinate);
//
// //Take one image data 1 to be reference
// displayCoordinate[0] = (worldCoordinate[0] - GetOrigin()[0]) / GetSpacing()[0];
// displayCoordinate[1] = (worldCoordinate[1] - GetOrigin()[1]) / GetSpacing()[1];
// displayCoordinate[2] = (worldCoordinate[2] - GetOrigin()[2]) / GetSpacing()[2];
// //cout << s[0] << " " << s[1] << " " << s[2] << endl;
// //Test whether the points are inside the polygon or not
// // if the points is too close to the previous point, skip it to avoid error in PointInPolygon algorithm
// double d = vtkMath::Distance2BetweenPoints(lastPoint, displayCoordinate);
// if (d < 1E-5)
// continue;
// memcpy(lastPoint, displayCoordinate, sizeof(double) * 3);
// displayCoordinate[GetSliceOrientation()] = 0.0;
// polygon->GetPoints()->InsertNextPoint(displayCoordinate);
//
// }
// //Test whether the points are inside the polygon or not
// double n[3];
// polygon->ComputeNormal(polygon->GetPoints()->GetNumberOfPoints(),
// static_cast<double*>(polygon->GetPoints()->GetData()->GetVoidPointer(0)), n);
// double bounds[6];
// int bounds_int[6];
//
// polygon->GetPoints()->GetBounds(bounds);
//
// bounds_int[0] = floor(bounds[0]) - 3;
// bounds_int[1] = ceil(bounds[1]) + 3;
// bounds_int[2] = floor(bounds[2]) - 3;
// bounds_int[3] = ceil(bounds[3]) + 3;
// bounds_int[4] = floor(bounds[4]) - 3;
// bounds_int[5] = ceil(bounds[5]) + 3;
//
// // Clamp values to within extent specified
// bounds_int[0] = { bounds_int[0] < this->GetExtent()[0] ? this->GetExtent()[0] : bounds_int[0] };
// bounds_int[1] = { bounds_int[1] > this->GetExtent()[1] ? this->GetExtent()[1] : bounds_int[1] };
// bounds_int[2] = { bounds_int[2] < this->GetExtent()[2] ? this->GetExtent()[2] : bounds_int[2] };
// bounds_int[3] = { bounds_int[3] > this->GetExtent()[3] ? this->GetExtent()[3] : bounds_int[3] };
// bounds_int[4] = { bounds_int[4] < this->GetExtent()[4] ? this->GetExtent()[4] : bounds_int[4] };
// bounds_int[5] = { bounds_int[5] > this->GetExtent()[5] ? this->GetExtent()[5] : bounds_int[5] };
//
// // for using overlay::SetPixels()
//
//
// vtkSmartPointer<vtkPoints> fillPoints =
// vtkSmartPointer<vtkPoints>::New();
// bounds_int[GetSliceOrientation() * 2] = 0;
// bounds_int[GetSliceOrientation() * 2 + 1] = 0;
//
// for (int x = bounds_int[0]; x <= bounds_int[1]; x++) {
// for (int y = bounds_int[2]; y <= bounds_int[3]; y++) {
// for (int z = bounds_int[4]; z <= bounds_int[5]; z++) {
// double p[3] = { x, y, z };
// if (vtkPolygon::PointInPolygon(p, polygon->GetPoints()->GetNumberOfPoints(),
// static_cast<double*>(polygon->GetPoints()->GetData()->GetVoidPointer(0)), bounds, n)) {
// p[GetSliceOrientation()] = m_imageViewer->GetSlice();
// fillPoints->InsertNextPoint(p[0], p[1], p[2]);
// }
// }
// }
// }
//
// m_imageViewer->GetOverlay()->SetPixels(fillPoints, (unsigned char)label);
//
// }
//
//
// m_imageViewer->GetOverlay()->Modified();
// for (std::list<MyImageViewer*>::iterator it = m_synchronalViewers.begin();
// it != m_synchronalViewers.end(); ++it) {
// (*it)->Render();
// }
//
//
//}
//
//
| 32.212724 | 127 | 0.686786 | [
"render"
] |
e97e514de8aee817042405fb628b4d012d782822 | 19,952 | cpp | C++ | tests/src/distance_2d.cpp | viennagrid/viennagrid-dev | 6e47c8d098a0b691d6b9988f2444cd11d440f4c2 | [
"MIT"
] | 7 | 2015-09-13T03:50:58.000Z | 2019-06-27T14:24:49.000Z | tests/src/distance_2d.cpp | viennagrid/viennagrid-dev | 6e47c8d098a0b691d6b9988f2444cd11d440f4c2 | [
"MIT"
] | null | null | null | tests/src/distance_2d.cpp | viennagrid/viennagrid-dev | 6e47c8d098a0b691d6b9988f2444cd11d440f4c2 | [
"MIT"
] | 5 | 2015-07-03T07:14:15.000Z | 2021-05-20T00:51:58.000Z | /* =======================================================================
Copyright (c) 2011-2014, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#ifdef _MSC_VER
#pragma warning( disable : 4503 ) //truncated name decoration
#endif
#include <cmath>
#include "viennagrid/forwards.hpp"
#include "viennagrid/mesh/element_creation.hpp"
#include "viennagrid/config/default_configs.hpp"
#include "viennagrid/point.hpp"
#include "viennagrid/algorithm/distance.hpp"
inline void fuzzy_check(double a, double b)
{
if (a > b || a < b)
{
if ( (std::abs(a - b) / std::max( std::abs(a), std::abs(b) ) > 1e-10)
&& (std::abs(a - b) > 1e-10)
)
{
std::cerr << "FAILED!" << std::endl;
std::cerr << "Result mismatch: " << a << " vs. " << b << std::endl;
exit(EXIT_FAILURE);
}
}
std::cout << "PASSED! (" << a << ", " << b << ")" << std::endl;
}
//
// Line 2d
//
inline void setup_mesh(viennagrid::line_2d_mesh & mesh)
{
typedef viennagrid::line_2d_mesh MeshType;
// typedef viennagrid::config::line_2d ConfigType;
typedef viennagrid::line_tag CellTag;
typedef viennagrid::result_of::point<MeshType>::type PointType;
typedef viennagrid::result_of::handle<MeshType, viennagrid::vertex_tag>::type VertexHandleType;
typedef viennagrid::result_of::element<MeshType, CellTag>::type CellType;
const size_t s = 9;
PointType p[s];
VertexHandleType v[s];
p[0] = PointType(3.0, 0.0);
p[1] = PointType(1.0, 1.0);
p[2] = PointType(5.0, 1.0);
p[3] = PointType(3.0, 2.0);
p[4] = PointType(0.0, 3.0);
p[5] = PointType(3.0, 3.0);
p[6] = PointType(1.0, 4.0);
p[7] = PointType(2.0, 1.0);
p[8] = PointType(3.0, 2.0);
//upgrade to vertex:
std::cout << "Adding vertices to mesh..." << std::endl;
for (size_t i = 0; i < s; ++i)
{
v[i] = viennagrid::make_vertex( mesh, p[i] );
}
std::cout << "Adding cells to mesh..." << std::endl;
VertexHandleType vertices[2];
vertices[0] = v[0];
vertices[1] = v[6];
viennagrid::make_element<CellType>( mesh, vertices, vertices+2 );
vertices[0] = v[1];
vertices[1] = v[4];
viennagrid::make_element<CellType>( mesh, vertices, vertices+2 );
vertices[0] = v[1];
vertices[1] = v[5];
viennagrid::make_element<CellType>( mesh, vertices, vertices+2 );
vertices[0] = v[2];
vertices[1] = v[3];
viennagrid::make_element<CellType>( mesh, vertices, vertices+2 );
vertices[0] = v[7];
vertices[1] = v[8];
viennagrid::make_element<CellType>( mesh, vertices, vertices+2 );
}
inline void test(viennagrid::line_2d_mesh)
{
typedef viennagrid::line_2d_mesh Mesh;
typedef viennagrid::line_tag CellTag;
typedef viennagrid::result_of::point<Mesh>::type PointType;
typedef viennagrid::result_of::element<Mesh, CellTag>::type CellType;
Mesh mesh;
setup_mesh(mesh);
PointType A(0, 0);
PointType B(1, 0);
PointType C(2, 0);
PointType D(3, 0);
PointType E(4, 0);
PointType F(0, 1);
PointType G(1, 1);
PointType H(3, 1);
PointType I(4, 1);
PointType J(0, 2);
PointType K(2, 2);
PointType L(5, 2);
PointType M(5, 3);
PointType N(0, 4);
PointType O(1, 4);
PointType P(4, 4);
PointType Q(2, 5);
PointType R(3, 5);
CellType line0 = viennagrid::elements<CellTag>(mesh)[0];
CellType line1 = viennagrid::elements<CellTag>(mesh)[1];
CellType line2 = viennagrid::elements<CellTag>(mesh)[2];
CellType line3 = viennagrid::elements<CellTag>(mesh)[3];
CellType line = viennagrid::elements<CellTag>(mesh)[4];
//
// Distance checks for points to line
//
std::cout << "Distance of point A to line... ";
fuzzy_check( viennagrid::distance(A, line), std::sqrt(5.0) );
std::cout << "Distance of point B to line... ";
fuzzy_check( viennagrid::distance(B, line), std::sqrt(2.0) );
std::cout << "Distance of point C to line... ";
fuzzy_check( viennagrid::distance(C, line), 1.0 );
std::cout << "Distance of point D to line... ";
fuzzy_check( viennagrid::distance(D, line), std::sqrt(2.0) );
std::cout << "Distance of point E to line... ";
fuzzy_check( viennagrid::distance(E, line), 3.0 * std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point F to line... ";
fuzzy_check( viennagrid::distance(F, line), 2.0 );
std::cout << "Distance of point G to line... ";
fuzzy_check( viennagrid::distance(G, line), 1.0 );
std::cout << "Distance of point H to line... ";
fuzzy_check( viennagrid::distance(H, line), std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point I to line... ";
fuzzy_check( viennagrid::distance(I, line), std::sqrt(2.0) );
std::cout << "Distance of point J to line... ";
fuzzy_check( viennagrid::distance(J, line), std::sqrt(5.0) );
std::cout << "Distance of point K to line... ";
fuzzy_check( viennagrid::distance(K, line), std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point L to line... ";
fuzzy_check( viennagrid::distance(L, line), 2.0 );
std::cout << "Distance of point M to line... ";
fuzzy_check( viennagrid::distance(M, line), std::sqrt(5.0) );
std::cout << "Distance of point N to line... ";
fuzzy_check( viennagrid::distance(N, line), 5.0 * std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point O to line... ";
fuzzy_check( viennagrid::distance(O, line), 2.0 * std::sqrt(2.0) );
std::cout << "Distance of point P to line... ";
fuzzy_check( viennagrid::distance(P, line), std::sqrt(5.0) );
std::cout << "Distance of point Q to line... ";
fuzzy_check( viennagrid::distance(Q, line), std::sqrt(10.0) );
std::cout << "Distance of point R to line... ";
fuzzy_check( viennagrid::distance(R, line), 3.0 );
//
// Distance checks line to line
//
std::cout << "Distance of line0 to line0... ";
fuzzy_check( viennagrid::distance(line0, line0), 0.0 );
std::cout << "Distance of line0 to line1... ";
double s01 = ( 3.0 + std::sqrt(5.0) + std::sqrt(20.0) ) / 2.0;
double dist01 = std::sqrt( s01 * (s01 - 3.0) * (s01 - std::sqrt(5.0)) * (s01 - std::sqrt(20.0)) ) * 2.0 / std::sqrt(20.0);
fuzzy_check( viennagrid::distance(line0, line1), dist01 );
std::cout << "Distance of line0 to line2... ";
fuzzy_check( viennagrid::distance(line0, line2), 0.0 );
std::cout << "Distance of line0 to line3... ";
double s03 = ( 2.0 + std::sqrt(8.0) + std::sqrt(20.0) ) / 2.0;
double dist03 = std::sqrt( s03 * (s03 - 2.0) * (s03 - std::sqrt(8.0)) * (s03 - std::sqrt(20.0)) ) * 2.0 / std::sqrt(20.0);
fuzzy_check( viennagrid::distance(line0, line3), dist03 );
std::cout << "Distance of line1 to line0... ";
fuzzy_check( viennagrid::distance(line1, line0), dist01 );
std::cout << "Distance of line1 to line1... ";
fuzzy_check( viennagrid::distance(line1, line1), 0.0 );
std::cout << "Distance of line1 to line2... ";
fuzzy_check( viennagrid::distance(line1, line2), 0.0 );
std::cout << "Distance of line1 to line3... ";
fuzzy_check( viennagrid::distance(line1, line3), std::sqrt(5.0) );
std::cout << "Distance of line2 to line0... ";
fuzzy_check( viennagrid::distance(line2, line0), 0.0 );
std::cout << "Distance of line2 to line1... ";
fuzzy_check( viennagrid::distance(line2, line1), 0.0 );
std::cout << "Distance of line2 to line2... ";
fuzzy_check( viennagrid::distance(line2, line2), 0.0 );
std::cout << "Distance of line2 to line3... ";
fuzzy_check( viennagrid::distance(line2, line3), std::sqrt(2.0) / 2.0 );
std::cout << "Distance of line3 to line0... ";
fuzzy_check( viennagrid::distance(line3, line0), dist03 );
std::cout << "Distance of line3 to line1... ";
fuzzy_check( viennagrid::distance(line3, line1), std::sqrt(5.0) );
std::cout << "Distance of line3 to line2... ";
fuzzy_check( viennagrid::distance(line3, line2), std::sqrt(2.0) / 2.0 );
std::cout << "Distance of line3 to line3... ";
fuzzy_check( viennagrid::distance(line3, line3), 0.0 );
}
//
// Triangular
//
inline void setup_mesh(viennagrid::triangular_2d_mesh & mesh)
{
typedef viennagrid::triangular_2d_mesh MeshType;
typedef viennagrid::triangle_tag CellTag;
typedef viennagrid::result_of::point<MeshType>::type PointType;
typedef viennagrid::result_of::handle<MeshType, viennagrid::vertex_tag>::type VertexHandleType;
typedef viennagrid::result_of::element<MeshType, CellTag>::type CellType;
const size_t s = 4;
PointType p[s];
VertexHandleType v[s];
p[0] = PointType(2.0, 1.0);
p[1] = PointType(3.0, 2.0);
p[2] = PointType(3.0, 3.0);
p[3] = PointType(1.0, 2.0);
//upgrade to vertex:
std::cout << "Adding vertices to mesh..." << std::endl;
for (size_t i = 0; i < s; ++i)
{
v[i] = viennagrid::make_vertex( mesh, p[i] );
}
std::cout << "Adding cells to mesh..." << std::endl;
VertexHandleType vertices[3];
vertices[0] = v[0];
vertices[1] = v[2];
vertices[2] = v[3];
viennagrid::make_element<CellType>( mesh, vertices, vertices+3 );
vertices[0] = v[0];
vertices[1] = v[1];
vertices[2] = v[2];
viennagrid::make_element<CellType>( mesh, vertices, vertices+3 );
}
inline void test(viennagrid::triangular_2d_mesh)
{
typedef viennagrid::triangular_2d_mesh Mesh;
typedef viennagrid::triangle_tag CellTag;
typedef viennagrid::result_of::point<Mesh>::type PointType;
typedef viennagrid::result_of::element<Mesh, CellTag>::type CellType;
Mesh mesh;
setup_mesh(mesh);
PointType A(0, 0);
PointType B(1, 0);
PointType C(2, 0);
PointType D(3, 0);
PointType E(4, 0);
PointType F(0, 1);
PointType G(1, 1);
PointType H(3, 1);
PointType I(4, 1);
PointType J(0, 2);
PointType K(2, 2);
PointType L(5, 2);
PointType M(5, 3);
PointType N(0, 4);
PointType O(1, 4);
PointType P(4, 4);
PointType Q(2, 5);
PointType R(3, 5);
CellType t0 = viennagrid::elements<CellTag>(mesh)[0];
CellType t1 = viennagrid::elements<CellTag>(mesh)[1];
//
// Distance checks for t0
//
std::cout << "Distance of point A to triangle t0... ";
fuzzy_check( viennagrid::distance(A, t0), 3.0 * std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point B to triangle t0... ";
fuzzy_check( viennagrid::distance(B, t0), std::sqrt(2.0) );
std::cout << "Distance of point C to triangle t0... ";
fuzzy_check( viennagrid::distance(C, t0), 1.0 );
std::cout << "Distance of point D to triangle t0... ";
fuzzy_check( viennagrid::distance(D, t0), std::sqrt(2.0) );
std::cout << "Distance of point E to triangle t0... ";
fuzzy_check( viennagrid::distance(E, t0), std::sqrt(5.0) );
std::cout << "Distance of point F to triangle t0... ";
fuzzy_check( viennagrid::distance(F, t0), std::sqrt(2.0) );
std::cout << "Distance of point G to triangle t0... ";
fuzzy_check( viennagrid::distance(G, t0), std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point H to triangle t0... ";
fuzzy_check( viennagrid::distance(H, t0), 2.0 / std::sqrt(5.0) );
std::cout << "Distance of point I to triangle t0... ";
fuzzy_check( viennagrid::distance(I, t0), 4.0 / std::sqrt(5.0) );
std::cout << "Distance of point J to triangle t0... ";
fuzzy_check( viennagrid::distance(J, t0), 1.0 );
std::cout << "Distance of point K to triangle t0... ";
fuzzy_check( viennagrid::distance(K, t0), 0.0 );
std::cout << "Distance of point L to triangle t0... ";
fuzzy_check( viennagrid::distance(L, t0), std::sqrt(5.0) );
std::cout << "Distance of point M to triangle t0... ";
fuzzy_check( viennagrid::distance(M, t0), 2.0 );
std::cout << "Distance of point N to triangle t0... ";
fuzzy_check( viennagrid::distance(N, t0), std::sqrt(5.0) );
std::cout << "Distance of point O to triangle t0... ";
fuzzy_check( viennagrid::distance(O, t0), 4.0 / std::sqrt(5.0) );
std::cout << "Distance of point P to triangle t0... ";
fuzzy_check( viennagrid::distance(P, t0), std::sqrt(2.0) );
std::cout << "Distance of point Q to triangle t0... ";
fuzzy_check( viennagrid::distance(Q, t0), std::sqrt(5.0) );
std::cout << "Distance of point R to triangle t0... ";
fuzzy_check( viennagrid::distance(t0, R), 2.0 );
std::cout << std::endl;
//
// Distance checks for t1
//
std::cout << "Distance of point A to triangle t1... ";
fuzzy_check( viennagrid::distance(A, t1), std::sqrt(5.0) );
std::cout << "Distance of point B to triangle t1... ";
fuzzy_check( viennagrid::distance(B, t1), std::sqrt(2.0) );
std::cout << "Distance of point C to triangle t1... ";
fuzzy_check( viennagrid::distance(C, t1), 1.0 );
std::cout << "Distance of point D to triangle t1... ";
fuzzy_check( viennagrid::distance(D, t1), std::sqrt(2.0) );
std::cout << "Distance of point E to triangle t1... ";
fuzzy_check( viennagrid::distance(E, t1), 3.0 * std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point F to triangle t1... ";
fuzzy_check( viennagrid::distance(F, t1), 2.0 );
std::cout << "Distance of point G to triangle t1... ";
fuzzy_check( viennagrid::distance(G, t1), 1.0 );
std::cout << "Distance of point H to triangle t1... ";
fuzzy_check( viennagrid::distance(H, t1), std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point I to triangle t1... ";
fuzzy_check( viennagrid::distance(I, t1), std::sqrt(2.0) );
std::cout << "Distance of point J to triangle t1... ";
fuzzy_check( viennagrid::distance(J, t1), std::sqrt(5.0) );
std::cout << "Distance of point K to triangle t1... ";
fuzzy_check( viennagrid::distance(K, t1), 0.5 / std::sqrt(1.25) );
std::cout << "Distance of point L to triangle t1... ";
fuzzy_check( viennagrid::distance(L, t1), 2.0 );
std::cout << "Distance of point M to triangle t1... ";
fuzzy_check( viennagrid::distance(M, t1), 2.0 );
std::cout << "Distance of point N to triangle t1... ";
double s = ( std::sqrt(5.0) + std::sqrt(10.0) + std::sqrt(13.0) ) / 2.0; //semiperimeter
fuzzy_check( viennagrid::distance(N, t1), std::sqrt( s * (s - std::sqrt(5.0)) * (s - std::sqrt(10.0)) * (s - std::sqrt(13.0)) ) * 2.0 / std::sqrt(5.0) ); //Heron's formula
std::cout << "Distance of point O to triangle t1... ";
fuzzy_check( viennagrid::distance(O, t1), std::sqrt(5.0) );
std::cout << "Distance of point P to triangle t1... ";
fuzzy_check( viennagrid::distance(P, t1), std::sqrt(2.0) );
std::cout << "Distance of point Q to triangle t1... ";
fuzzy_check( viennagrid::distance(Q, t1), std::sqrt(5.0) );
std::cout << "Distance of point R to triangle t1... ";
fuzzy_check( viennagrid::distance(R, t1), 2.0 );
}
//
// Quadrilateral
//
inline void setup_mesh(viennagrid::quadrilateral_2d_mesh & mesh)
{
typedef viennagrid::quadrilateral_2d_mesh MeshType;
typedef viennagrid::quadrilateral_tag CellTag;
typedef viennagrid::result_of::point<MeshType>::type PointType;
typedef viennagrid::result_of::handle<MeshType, viennagrid::vertex_tag>::type VertexHandleType;
typedef viennagrid::result_of::element<MeshType, CellTag>::type CellType;
const size_t s = 4;
PointType p[s];
VertexHandleType v[s];
p[0] = PointType(2.0, 1.0);
p[1] = PointType(3.0, 2.0);
p[2] = PointType(1.0, 2.0);
p[3] = PointType(3.0, 3.0);
//upgrade to vertex:
std::cout << "Adding vertices to mesh..." << std::endl;
for (size_t i = 0; i < s; ++i)
{
v[i] = viennagrid::make_vertex( mesh, p[i] );
// viennagrid::point( mesh, v[i] ) = p[i];
}
std::cout << "Adding cells to mesh..." << std::endl;
viennagrid::make_element<CellType>( mesh, v, v+4 );
}
inline void test(viennagrid::quadrilateral_2d_mesh)
{
typedef viennagrid::quadrilateral_2d_mesh Mesh;
typedef viennagrid::quadrilateral_tag CellTag;
typedef viennagrid::result_of::point<Mesh>::type PointType;
typedef viennagrid::result_of::element<Mesh, CellTag>::type CellType;
Mesh mesh;
setup_mesh(mesh);
PointType A(0, 0);
PointType B(1, 0);
PointType C(2, 0);
PointType D(3, 0);
PointType E(4, 0);
PointType F(0, 1);
PointType G(1, 1);
PointType H(3, 1);
PointType I(4, 1);
PointType J(0, 2);
PointType K(2, 2);
PointType L(5, 2);
PointType M(5, 3);
PointType N(0, 4);
PointType O(1, 4);
PointType P(4, 4);
PointType Q(2, 5);
PointType R(3, 5);
CellType quad = viennagrid::elements<CellTag>(mesh)[0];
//
// Distance checks for quadrilateral
//
std::cout << "Distance of point A to quadrilateral... ";
fuzzy_check( viennagrid::distance(A, quad), 3.0 * std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point B to quadrilateral... ";
fuzzy_check( viennagrid::distance(B, quad), std::sqrt(2.0) );
std::cout << "Distance of point C to quadrilateral... ";
fuzzy_check( viennagrid::distance(C, quad), 1.0 );
std::cout << "Distance of point D to quadrilateral... ";
fuzzy_check( viennagrid::distance(D, quad), std::sqrt(2.0) );
std::cout << "Distance of point E to quadrilateral... ";
fuzzy_check( viennagrid::distance(E, quad), 3.0 * std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point F to quadrilateral... ";
fuzzy_check( viennagrid::distance(F, quad), std::sqrt(2.0) );
std::cout << "Distance of point G to quadrilateral... ";
fuzzy_check( viennagrid::distance(G, quad), std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point H to quadrilateral... ";
fuzzy_check( viennagrid::distance(H, quad), std::sqrt(2.0) / 2.0 );
std::cout << "Distance of point I to quadrilateral... ";
fuzzy_check( viennagrid::distance(I, quad), std::sqrt(2.0) );
std::cout << "Distance of point J to quadrilateral... ";
fuzzy_check( viennagrid::distance(J, quad), 1.0 );
std::cout << "Distance of point K to quadrilateral... ";
fuzzy_check( viennagrid::distance(K, quad), 0.0 );
std::cout << "Distance of point L to quadrilateral... ";
fuzzy_check( viennagrid::distance(L, quad), 2.0 );
std::cout << "Distance of point M to quadrilateral... ";
fuzzy_check( viennagrid::distance(M, quad), 2.0 );
std::cout << "Distance of point N to quadrilateral... ";
fuzzy_check( viennagrid::distance(N, quad), std::sqrt(5.0) );
std::cout << "Distance of point O to quadrilateral... ";
fuzzy_check( viennagrid::distance(O, quad), 4.0 / std::sqrt(5.0) );
std::cout << "Distance of point P to quadrilateral... ";
fuzzy_check( viennagrid::distance(P, quad), std::sqrt(2.0) );
std::cout << "Distance of point Q to quadrilateral... ";
fuzzy_check( viennagrid::distance(Q, quad), std::sqrt(5.0) );
std::cout << "Distance of point R to quadrilateral... ";
fuzzy_check( viennagrid::distance(quad, R), 2.0 );
}
int main()
{
std::cout << "*****************" << std::endl;
std::cout << "* Test started! *" << std::endl;
std::cout << "*****************" << std::endl;
std::cout << "==== Testing line mesh in 2D ====" << std::endl;
test(viennagrid::line_2d_mesh());
std::cout << "==== Testing triangular mesh in 2D ====" << std::endl;
test(viennagrid::triangular_2d_mesh());
std::cout << "==== Testing quadrilateral mesh in 2D ====" << std::endl;
test(viennagrid::quadrilateral_2d_mesh());
std::cout << "*******************************" << std::endl;
std::cout << "* Test finished successfully! *" << std::endl;
std::cout << "*******************************" << std::endl;
return EXIT_SUCCESS;
}
| 31.371069 | 173 | 0.604751 | [
"mesh"
] |
e98e29b77e9908c8912581c85b4157026bf59ecd | 1,661 | cpp | C++ | CPlusPlusFundamentals/Exarsise-Strings-Stream-LTC/02.NumeralSystem/main.cpp | bozhikovstanislav/Cpp-SoftUni | 6562d15b9e3a550b11566630a1bc1ec65670bff7 | [
"MIT"
] | null | null | null | CPlusPlusFundamentals/Exarsise-Strings-Stream-LTC/02.NumeralSystem/main.cpp | bozhikovstanislav/Cpp-SoftUni | 6562d15b9e3a550b11566630a1bc1ec65670bff7 | [
"MIT"
] | null | null | null | CPlusPlusFundamentals/Exarsise-Strings-Stream-LTC/02.NumeralSystem/main.cpp | bozhikovstanislav/Cpp-SoftUni | 6562d15b9e3a550b11566630a1bc1ec65670bff7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
std::string intToSystemNumber(const std::string baseInput,
const int number) {
//abcdefghij
//300
std::string answer;
std::string numberStr = std::to_string(number);
answer.resize(numberStr.size());
for ( size_t i = 0; i < numberStr.size(); ++i ) {
const int index = numberStr[i] - '0';
answer[i] = baseInput[index];
}
return answer;
}
int numberSystemToInt(const std::vector<int> &allValues,
const std::string valueStr) {
int answer = 0;
int multiplier = 1;
const int SIZE = (int) valueStr.size();
for ( int i = SIZE - 1; i >= 0; --i ) {
const int index = valueStr[i];
answer += (multiplier * allValues[index]);
multiplier *= 10;
}
return answer;
}
int main() {
std::string baseInput;
getline(std::cin, baseInput);
std::string firstNumberStr;
getline(std::cin, firstNumberStr);
std::string secondNumberStr;
getline(std::cin, secondNumberStr);
std::vector<int> numberValues(255, 0);
for ( size_t i = 0; i < baseInput.size(); ++i ) {
//abcdefghij
const unsigned char letter = baseInput[i];
numberValues[letter] = i;
}
const int firstNumberInt =
numberSystemToInt(numberValues, firstNumberStr);
const int secondNumberInt =
numberSystemToInt(numberValues, secondNumberStr);
const int answerInt = firstNumberInt + secondNumberInt;
// std::cout << answerInt << std::endl;
std::cout << intToSystemNumber(baseInput, answerInt);
return 0;
}
| 23.394366 | 61 | 0.602649 | [
"vector"
] |
e9950b52984de360cf745667c26d7b54bc765c6d | 2,883 | cc | C++ | mindspore/ccsrc/backend/kernel_compiler/cpu/unique_cpu_kernel.cc | dongkcs/mindspore | cd7df6dbf463ff3128e9181e9d0c779cecb81320 | [
"Apache-2.0"
] | 2 | 2020-11-23T13:46:37.000Z | 2020-12-20T02:02:38.000Z | mindspore/ccsrc/backend/kernel_compiler/cpu/unique_cpu_kernel.cc | dongkcs/mindspore | cd7df6dbf463ff3128e9181e9d0c779cecb81320 | [
"Apache-2.0"
] | 1 | 2020-12-29T06:46:38.000Z | 2020-12-29T06:46:38.000Z | mindspore/ccsrc/backend/kernel_compiler/cpu/unique_cpu_kernel.cc | dongkcs/mindspore | cd7df6dbf463ff3128e9181e9d0c779cecb81320 | [
"Apache-2.0"
] | 1 | 2021-05-12T06:30:29.000Z | 2021-05-12T06:30:29.000Z | /**
* Copyright 2020 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 "backend/kernel_compiler/cpu/unique_cpu_kernel.h"
#include "runtime/device/cpu/cpu_device_address.h"
namespace mindspore {
namespace kernel {
void UniqueCPUKernel::InitKernel(const CNodePtr &kernel_node) {
CheckParam(kernel_node);
auto input_shape = AnfAlgo::GetPrevNodeOutputInferShape(kernel_node, 0);
n_ = input_shape[0];
dtype_ = AnfAlgo::GetPrevNodeOutputInferDataType(kernel_node, 0);
}
bool UniqueCPUKernel::Launch(const std::vector<kernel::AddressPtr> &inputs,
const std::vector<kernel::AddressPtr> & /*workspace*/,
const std::vector<kernel::AddressPtr> &outputs) {
if (dtype_ == kNumberTypeInt32) {
LaunchKernel<int>(inputs, outputs);
} else if (dtype_ == kNumberTypeFloat32) {
LaunchKernel<float>(inputs, outputs);
} else if (dtype_ == kNumberTypeInt64) {
LaunchKernel<int64_t>(inputs, outputs);
}
return true;
}
template <typename T>
void UniqueCPUKernel::LaunchKernel(const std::vector<AddressPtr> &inputs, const std::vector<AddressPtr> &outputs) {
auto x_addr = reinterpret_cast<T *>(inputs[0]->addr);
auto y_addr = reinterpret_cast<T *>(outputs[0]->addr);
auto idx_addr = reinterpret_cast<int *>(outputs[1]->addr);
std::unordered_map<T, int> uniq;
int n = SizeToInt(n_);
uniq.reserve(n * 2);
for (int i = 0, j = 0; i < n; ++i) {
auto it = uniq.emplace(x_addr[i], j);
idx_addr[i] = it.first->second;
if (it.second) {
++j;
}
}
for (const auto &it : uniq) {
y_addr[it.second] = it.first;
}
}
void UniqueCPUKernel::CheckParam(const CNodePtr &kernel_node) {
auto input_shape = AnfAlgo::GetPrevNodeOutputInferShape(kernel_node, 0);
if (input_shape.size() != 1) {
MS_LOG(EXCEPTION) << "Input dims is " << input_shape.size() << ", but UniqueCPUKernel only support 1d.";
}
size_t input_num = AnfAlgo::GetInputTensorNum(kernel_node);
if (input_num != 1) {
MS_LOG(EXCEPTION) << "Input number is " << input_num << ", but UniqueCPUKernel needs 1 input.";
}
size_t output_num = AnfAlgo::GetOutputTensorNum(kernel_node);
if (output_num != 2) {
MS_LOG(EXCEPTION) << "Output number is " << output_num << ", but UniqueCPUKernel needs 2 output.";
}
}
} // namespace kernel
} // namespace mindspore
| 36.493671 | 115 | 0.690253 | [
"vector"
] |
e997613d554d07310917498f755ca56d7c0ade2f | 33,888 | cc | C++ | src/main.cc | Kronuz/Xapiand | a71570859dcfc9f48090d845053f359b07f4f78c | [
"MIT"
] | 370 | 2016-03-14T12:19:08.000Z | 2022-03-25T02:07:29.000Z | src/main.cc | YosefMac/Xapiand-1 | a71570859dcfc9f48090d845053f359b07f4f78c | [
"MIT"
] | 34 | 2015-11-30T19:06:40.000Z | 2022-02-26T03:46:58.000Z | src/main.cc | YosefMac/Xapiand-1 | a71570859dcfc9f48090d845053f359b07f4f78c | [
"MIT"
] | 31 | 2015-02-13T22:27:34.000Z | 2022-03-25T02:07:34.000Z | /*
* Copyright (c) 2015-2019 Dubalu LLC
*
* 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 "config.h" // for XAPIAND_CHAISCRIPT, XAPIAND_UUID...
#include <chrono> // for std::chrono::
#include <clocale> // for std::setlocale, LC_CTYPE
#include <csignal> // for sigaction, sigemptyset
#include <cstdlib> // for std::size_t, std::atoi, std::getenv, std::exit, std::setenv
#include <cstring> // for std::strcmp
#include <errno.h> // for errno
#include <fcntl.h> // for O_RDWR, O_CREAT
#include <grp.h> // for getgrgid, group, getgrnam, gid_t
#include <limits.h> // for PATH_MAX
#include <memory> // for std::make_unique
#include <pwd.h> // for passwd, getpwnam, getpwuid
#include <signal.h> // for NSIG, sigaction, signal, SIG_IGN, SIGHUP
#include <sys/resource.h> // for rlimit
#include <sysexits.h> // for EX_NOUSER, EX_OK, EX_USAGE, EX_OSFILE
#include <unistd.h> // for unlink, STDERR_FILENO, chdir
#include <vector> // for vector
#ifdef HAVE_SYS_PRCTL_H
#ifdef HAVE_SYS_CAPABILITY_H
#include <sys/capability.h>
#include <sys/prctl.h>
#endif
#endif
#ifdef USE_ICU
#include <unicode/uvernum.h>
#endif
#ifdef XAPIAND_CHAISCRIPT
#include "chaiscript/chaiscript_defines.hpp" // for chaiscript::Build_Info
#endif
#include "check_size.h" // for check_size
#include "database/handler.h" // for DatabaseHandler
#include "database/schema.h" // for default_spc
#include "endpoint.h" // for Endpoint, Endpoint::cwd
#include "error.hh" // for error::name, error::description
#include "ev/ev++.h" // for ::DEVPOLL, ::EPOLL, ::KQUEUE
#include "exception.h" // for SystemExit
#include "fs.hh" // for mkdirs
#include "hashes.hh" // for fnv1ah32
#include "io.hh" // for io::dup2, io::open, io::close, io::write
#include "log.h" // for L_INFO, L_CRIT, L_NOTICE
#include "logger.h" // for Logging
#include "manager.h" // for XapiandManager
#include "nanosleep.h" // for nanosleep
#include "opts.h" // for opts_t
#include "package.h" // for Package::
#include "strings.hh" // for strings::format, strings::center
#include "system.hh" // for get_max_files_per_proc, get_open_files_system_wide
#include "traceback.h" // for backtrace, traceback, collect_callstack_sig_handler
#include "xapian.h" // for XAPIAN_HAS_GLASS_BACKEND, XAPIAN...
#if defined(__linux__) && !defined(__GLIBC__)
#include <pthread.h> // for pthread_attr_t, pthread_setattr_default_np
#endif
#define FDS_RESERVED 50 // Is there a better approach?
#define FDS_PER_CLIENT 2 // KQUEUE + IPv4
#define FDS_PER_DATABASE 7 // Writable~=7, Readable~=5
opts_t opts;
static const bool is_tty = isatty(STDERR_FILENO) != 0;
template<typename T, std::size_t N>
static ssize_t write(int fildes, T (&&buf)[N]) {
return write(fildes, buf, N - 1);
}
static ssize_t write(int fildes, std::string_view str) {
return write(fildes, str.data(), str.size());
}
template <std::size_t N>
class signals_t {
static constexpr int signals = N;
std::array<std::string, signals> tty_messages;
std::array<std::string, signals> messages;
std::array<std::string, signals> names;
public:
signals_t() {
for (std::size_t signum = 0; signum < signals; ++signum) {
#if defined(__linux__)
const char* sig_str = strsignal(signum);
#elif defined(__APPLE__) || defined(__FreeBSD__)
const char* sig_str = sys_signame[signum];
#endif
switch (signum) {
case SIGQUIT:
case SIGILL:
case SIGTRAP:
case SIGABRT:
#if defined(__APPLE__) || defined(__FreeBSD__)
case SIGEMT:
#endif
case SIGFPE:
case SIGBUS:
case SIGSEGV:
case SIGSYS:
// create core image
tty_messages[signum] = strings::format(LIGHT_RED + "Signal received: {}" + CLEAR_COLOR + "\n", sig_str);
messages[signum] = strings::format("Signal received: {}\n", sig_str);
names[signum] = sig_str;
break;
case SIGHUP:
case SIGINT:
case SIGKILL:
case SIGPIPE:
case SIGALRM:
case SIGTERM:
case SIGXCPU:
case SIGXFSZ:
case SIGVTALRM:
case SIGPROF:
case SIGUSR1:
case SIGUSR2:
#if defined(__linux__)
case SIGSTKFLT:
#endif
// terminate process
tty_messages[signum] = strings::format(BROWN + "Signal received: {}" + CLEAR_COLOR + "\n", sig_str);
messages[signum] = strings::format("Signal received: {}\n", sig_str);
names[signum] = sig_str;
break;
case SIGSTOP:
case SIGTSTP:
case SIGTTIN:
case SIGTTOU:
// stop process
tty_messages[signum] = strings::format(SADDLE_BROWN + "Signal received: {}" + CLEAR_COLOR + "\n", sig_str);
messages[signum] = strings::format("Signal received: {}\n", sig_str);
names[signum] = sig_str;
break;
case SIGURG:
case SIGCONT:
case SIGCHLD:
case SIGIO:
case SIGWINCH:
#if defined(__APPLE__) || defined(__FreeBSD__)
case SIGINFO:
#endif
// discard signal
tty_messages[signum] = strings::format(STEEL_BLUE + "Signal received: {}" + CLEAR_COLOR + "\n", sig_str);
messages[signum] = strings::format("Signal received: {}\n", sig_str);
names[signum] = sig_str;
break;
default:
tty_messages[signum] = strings::format(STEEL_BLUE + "Signal received: {}" + CLEAR_COLOR + "\n", sig_str);
messages[signum] = strings::format("Signal received: {}\n", sig_str);
names[signum] = sig_str;
break;
}
}
}
void write(int fildes, int signum) {
if (is_tty) {
::write(fildes, tty_messages[(signum >= 0 && signum < signals) ? signum : signals - 1]);
} else {
::write(fildes, messages[(signum >= 0 && signum < signals) ? signum : signals - 1]);
}
}
const std::string& name(int signum) {
return names[(signum >= 0 && signum < signals) ? signum : signals - 1];
}
};
static signals_t<NSIG> signals;
void toggle_hooks(int /*unused*/) {
if (logger_info_hook != 0u) {
logger_info_hook = 0;
if (is_tty) {
::write(STDERR_FILENO, STEEL_BLUE + "Info hooks disabled!" + CLEAR_COLOR + "\n");
} else {
::write(STDERR_FILENO, "Info hooks disabled!\n");
}
} else {
logger_info_hook = fnv1ah32::hash("");
if (is_tty) {
::write(STDERR_FILENO, STEEL_BLUE + "Info hooks enabled!" + CLEAR_COLOR + "\n");
} else {
::write(STDERR_FILENO, "Info hooks enabled!\n");
}
}
}
void sig_handler(int signum) {
int old_errno = errno; // save errno because write will clobber it
signals.write(STDERR_FILENO, signum);
if (signum == SIGTERM || signum == SIGINT) {
int null = ::open("/dev/null", O_RDONLY);
if (null == -1) {
exit(EX_OSFILE);
}
::dup2(null, STDIN_FILENO);
}
// #if defined(__APPLE__) || defined(__FreeBSD__)
// if (signum == SIGINFO) {
// toggle_hooks(signum);
// }
// #endif
auto manager = XapiandManager::manager();
if (manager && !manager->is_deinited()) {
try {
manager->signal_sig(signum);
} catch (const SystemExit& exc) {
// Flag atom_sig for clean exit in the next Manager::join() timeout
manager->atom_sig = -exc.code;
}
} else {
if (signum == SIGTERM || signum == SIGINT) {
exit(EX_SOFTWARE);
}
}
errno = old_errno;
}
void backtrace_sig_handler(int signum)
{
// print traceback
auto tb = traceback(signals.name(signum).c_str(), nullptr, 0, backtrace(), 4);
if (is_tty) {
::write(STDERR_FILENO, DEBUG_COL);
::write(STDERR_FILENO, tb);
::write(STDERR_FILENO, CLEAR_COLOR + "\n");
} else {
::write(STDERR_FILENO, tb);
::write(STDERR_FILENO, "\n");
}
// restore default handler, and continue
signal(signum, SIG_DFL);
kill(getpid(), signum);
}
void setup_signal_handlers() {
signal(SIGHUP, SIG_IGN); // Ignore terminal line hangup
signal(SIGPIPE, SIG_IGN); // Ignore write on a pipe with no reader
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART; // If restarting works we save iterations
sa.sa_handler = sig_handler;
sigaction(SIGTERM, &sa, nullptr); // On software termination signal
sigaction(SIGINT, &sa, nullptr); // On interrupt program (Ctrl-C)
#if defined(__APPLE__) || defined(__FreeBSD__)
sigaction(SIGINFO, &sa, nullptr); // On status request from keyboard (Ctrl-T)
#endif
sigaction(SIGUSR1, &sa, nullptr);
#ifdef XAPIAND_TRACEBACKS
sa.sa_handler = backtrace_sig_handler;
sigaction(SIGQUIT, &sa, nullptr);
sigaction(SIGILL, &sa, nullptr);
sigaction(SIGTRAP, &sa, nullptr);
sigaction(SIGABRT, &sa, nullptr);
#if defined(__APPLE__) || defined(__FreeBSD__)
sigaction(SIGEMT, &sa, nullptr);
#endif
sigaction(SIGFPE, &sa, nullptr);
sigaction(SIGBUS, &sa, nullptr);
sigaction(SIGSEGV, &sa, nullptr);
sigaction(SIGSYS, &sa, nullptr);
#endif
sa.sa_flags |= SA_SIGINFO;
sa.sa_sigaction = collect_callstack_sig_handler;
sigaction(SIGUSR2, &sa, nullptr);
}
/*
* From https://github.com/antirez/redis/blob/b46239e58b00774d121de89e0e033b2ed3181eb0/src/server.c#L1496
*
* This function will try to raise the max number of open files accordingly to
* the configured max number of clients. It also reserves a number of file
* descriptors for extra operations of persistence, listening sockets, log files and so forth.
*
* If it will not be possible to set the limit accordingly to the configured
* max number of clients, the function will do the reverse setting
* to the value that we can actually handle.
*/
void adjustOpenFilesLimit()
{
// Try getting the currently available number of files (-10%):
ssize_t available_files_system_wide = get_max_files_system_wide() - get_open_files_system_wide();
ssize_t aprox_available_files_system_wide = (available_files_system_wide * 8) / 10;
// Try calculating minimum and recommended number of files:
ssize_t new_database_pool_size;
ssize_t new_max_clients;
ssize_t files = 1;
ssize_t minimum_files = 1;
ssize_t recommended_files = 1;
ssize_t open_files_per_proc = get_open_files_per_proc();
while (true) {
ssize_t used_files = open_files_per_proc + FDS_RESERVED;
used_files += FDS_PER_DATABASE;
new_database_pool_size = (files - used_files) / FDS_PER_DATABASE;
if (new_database_pool_size > opts.database_pool_size) {
new_database_pool_size = opts.database_pool_size;
}
used_files += (new_database_pool_size + 1) * FDS_PER_DATABASE;
used_files += FDS_PER_CLIENT;
new_max_clients = (files - used_files) / FDS_PER_CLIENT;
if (new_max_clients > opts.max_clients) {
new_max_clients = opts.max_clients;
}
used_files += (new_max_clients + 1) * FDS_PER_CLIENT;
if (new_database_pool_size < 1 || new_max_clients < 1) {
files = minimum_files = used_files;
} else if (new_database_pool_size < opts.database_pool_size || new_max_clients < opts.max_clients) {
files = recommended_files = used_files;
} else {
break;
}
}
ssize_t max_files_per_proc = get_max_files_per_proc();
ssize_t available_files = max_files_per_proc - open_files_per_proc;
// Calculate max_files (from configuration, recommended and available numbers):
ssize_t max_files = opts.max_files;
if (max_files != 0) {
if (max_files > aprox_available_files_system_wide) {
L_WARNING_ONCE("The requested open files limit of {} {} the system-wide currently available number of files: {}", max_files, max_files > available_files ? "exceeds" : "almost exceeds", available_files);
}
} else {
max_files = recommended_files;
if (max_files > aprox_available_files_system_wide) {
L_WARNING_ONCE("The minimum recommended open files limit of {} {} the system-wide currently available number of files: {}", max_files, max_files > available_files ? "exceeds" : "almost exceeds", available_files);
}
}
// Set the the max number of files:
// Increase if the current limit is not enough for our needs or
// decrease if the user requests it.
if (opts.max_files != 0 || available_files < max_files) {
bool increasing = available_files < max_files;
const ssize_t step = 16;
int setrlimit_errno = 0;
// Try to set the file limit to match 'max_files' or at least to the higher value supported less than max_files.
ssize_t new_max_files = max_files;
while (new_max_files != available_files) {
struct rlimit rl;
rl.rlim_cur = static_cast<rlim_t>(new_max_files);
rl.rlim_max = static_cast<rlim_t>(new_max_files);
if (setrlimit(RLIMIT_NOFILE, &rl) != -1) {
if (increasing) {
L_INFO("Increased maximum number of open files to {} (it was originally set to {})", new_max_files, (std::size_t)available_files);
} else {
L_INFO("Decresed maximum number of open files to {} (it was originally set to {})", new_max_files, (std::size_t)available_files);
}
break;
}
// We failed to set file limit to 'new_max_files'. Try with a smaller limit decrementing by a few FDs per iteration.
setrlimit_errno = errno;
if (!increasing || new_max_files < step) {
// Assume that the limit we get initially is still valid if our last try was even lower.
new_max_files = available_files;
break;
}
new_max_files -= step;
}
if (setrlimit_errno != 0) {
L_ERR("Server can't set maximum open files to {} because of OS error: {} ({}): {}", max_files, error::name(setrlimit_errno), setrlimit_errno, error::description(setrlimit_errno));
}
max_files = new_max_files;
} else {
max_files = available_files;
}
// Calculate database_pool_size and max_clients from current max_files:
files = max_files;
ssize_t used_files = FDS_RESERVED;
used_files += FDS_PER_DATABASE;
new_database_pool_size = (files - used_files) / FDS_PER_DATABASE;
if (new_database_pool_size > opts.database_pool_size) {
new_database_pool_size = opts.database_pool_size;
}
used_files += (new_database_pool_size + 1) * FDS_PER_DATABASE;
used_files += FDS_PER_CLIENT;
new_max_clients = (files - used_files) / FDS_PER_CLIENT;
if (new_max_clients > opts.max_clients) {
new_max_clients = opts.max_clients;
}
// Warn about changes to the configured database_pool_size or max_clients:
if (new_database_pool_size > 0 && new_database_pool_size < opts.database_pool_size) {
L_WARNING_ONCE("You requested a database_pool_size of {} requiring at least {} max file descriptors", opts.database_pool_size, (opts.database_pool_size + 1) * FDS_PER_DATABASE + FDS_RESERVED);
L_WARNING_ONCE("Current maximum open files is {} so database_pool_size has been reduced to {} to compensate for low limit.", max_files, new_database_pool_size);
}
if (new_max_clients > 0 && new_max_clients < opts.max_clients) {
L_WARNING_ONCE("You requested max_clients of {} requiring at least {} max file descriptors", opts.max_clients, (opts.max_clients + 1) * FDS_PER_CLIENT + FDS_RESERVED);
L_WARNING_ONCE("Current maximum open files is {} so max_clients has been reduced to {} to compensate for low limit.", max_files, new_max_clients);
}
// Warn about minimum/recommended sizes:
if (max_files < minimum_files) {
L_CRIT("Your open files limit of {} is not enough for the server to start. Please increase your system-wide open files limit to at least {}",
max_files,
minimum_files);
L_WARNING_ONCE("If you need to increase your system-wide open files limit use 'ulimit -n'");
throw SystemExit(EX_OSFILE);
} else if (max_files < recommended_files) {
L_WARNING_ONCE("Your current max_files of {} is not enough. Please increase your system-wide open files limit to at least {}",
max_files,
recommended_files);
L_WARNING_ONCE("If you need to increase your system-wide open files limit use 'ulimit -n'");
}
// Set new values:
opts.max_files = max_files;
opts.database_pool_size = new_database_pool_size;
opts.max_clients = new_max_clients;
}
void demote(const char* username, const char* group) {
// lose root privileges if we have them
uid_t uid = getuid();
if (
uid == 0
#ifdef HAVE_SETRESUID
// Get full root privileges. Normally being effectively root is enough,
// but some security modules restrict actions by processes that are only
// effectively root. To make sure we don't hit those problems, we try
// to switch to root fully.
|| setresuid(0, 0, 0) == 0
#endif
|| geteuid() == 0
) {
if (username == nullptr || *username == '\0') {
L_CRIT("Can't run as root without the --uid switch");
throw SystemExit(EX_USAGE);
}
// Get the target user:
struct passwd *pw;
if ((pw = getpwnam(username)) == nullptr) {
uid = std::atoi(username);
if ((uid == 0u) || (pw = getpwuid(uid)) == nullptr) {
L_CRIT("Can't find the user {} to switch to", username);
throw SystemExit(EX_NOUSER);
}
}
uid = pw->pw_uid;
gid_t gid = pw->pw_gid;
username = pw->pw_name;
// Get the target group:
struct group *gr;
if ((group != nullptr) && (*group != 0)) {
if ((gr = getgrnam(group)) == nullptr) {
gid = std::atoi(group);
if ((gid == 0u) || (gr = getgrgid(gid)) == nullptr) {
L_CRIT("Can't find the group {} to switch to", group);
throw SystemExit(EX_NOUSER);
}
}
gid = gr->gr_gid;
group = gr->gr_name;
} else {
if ((gr = getgrgid(gid)) == nullptr) {
L_CRIT("Can't find the group id {}", gid);
throw SystemExit(EX_NOUSER);
}
group = gr->gr_name;
}
#ifdef HAVE_SYS_PRCTL_H
#ifdef HAVE_SYS_CAPABILITY_H
// Create an empty set of capabilities.
cap_t capabilities = cap_init();
// Capabilities have three subsets:
// INHERITABLE: Capabilities permitted after an execv()
// EFFECTIVE: Currently effective capabilities
// PERMITTED: Limiting set for the two above.
// See man 7 capabilities for details, Thread Capability Sets.
//
// We need the following capabilities:
// CAP_SYS_NICE For nice(2), setpriority(2),
// sched_setscheduler(2), sched_setparam(2),
// sched_setaffinity(2), etc.
// CAP_SETUID For setuid(), setresuid()
// in the last two subsets. We do not need to retain any capabilities
// over an exec().
cap_value_t root_caps[2] = { CAP_SYS_NICE, CAP_SETUID };
if (cap_set_flag(capabilities, CAP_PERMITTED, sizeof root_caps / sizeof root_caps[0], root_caps, CAP_SET) ||
cap_set_flag(capabilities, CAP_EFFECTIVE, sizeof root_caps / sizeof root_caps[0], root_caps, CAP_SET)) {
L_CRIT("Cannot manipulate capability data structure as root: {} ({}) {}", error::name(errno), errno, error::description(errno));
throw SystemExit(EX_OSERR);
}
// Above, we just manipulated the data structure describing the flags,
// not the capabilities themselves. So, set those capabilities now.
if (cap_set_proc(capabilities)) {
L_CRIT("Cannot set capabilities as root: {} ({}) {}", error::name(errno), errno, error::description(errno));
throw SystemExit(EX_OSERR);
}
// We wish to retain the capabilities across the identity change,
// so we need to tell the kernel.
if (prctl(PR_SET_KEEPCAPS, 1L)) {
L_CRIT("Cannot keep capabilities after dropping privileges: {} ({}) {}", error::name(errno), errno, error::description(errno));
throw SystemExit(EX_OSERR);
}
#endif
#endif
// Drop extra privileges (aside from capabilities) by switching
// to the target group and user:
if (setgid(gid) < 0 || setuid(uid) < 0) {
L_CRIT("Failed to assume identity of {}:{}", username, group);
throw SystemExit(EX_OSERR);
}
#ifdef HAVE_SYS_PRCTL_H
#ifdef HAVE_SYS_CAPABILITY_H
// We can still switch to a different user due to having the CAP_SETUID
// capability. Let's clear the capability set, except for the CAP_SYS_NICE
// in the permitted and effective sets.
if (cap_clear(capabilities)) {
L_CRIT("Cannot clear capability data structure: {} ({}) {}", error::name(errno), errno, error::description(errno));
throw SystemExit(EX_OSERR);
}
cap_value_t user_caps[1] = { CAP_SYS_NICE };
if (cap_set_flag(capabilities, CAP_PERMITTED, sizeof user_caps / sizeof user_caps[0], user_caps, CAP_SET) ||
cap_set_flag(capabilities, CAP_EFFECTIVE, sizeof user_caps / sizeof user_caps[0], user_caps, CAP_SET)) {
L_CRIT("Cannot manipulate capability data structure as user: {} ({}) {}", error::name(errno), errno, error::description(errno));
throw SystemExit(EX_OSERR);
}
// Apply modified capabilities.
if (cap_set_proc(capabilities)) {
L_CRIT("Cannot set capabilities as user: {} ({}) {}", error::name(errno), errno, error::description(errno));
throw SystemExit(EX_OSERR);
}
#endif
#endif
L_NOTICE("Running as {}:{}", username, group);
}
}
void detach() {
pid_t pid = fork();
if (pid != 0) {
std::exit(EX_OK); /* parent exits */
}
setsid(); /* create a new session */
/* Every output goes to /dev/null */
int fd;
if ((fd = io::open("/dev/null", O_RDWR, 0)) != -1) {
io::dup2(fd, STDIN_FILENO);
io::dup2(fd, STDOUT_FILENO);
io::dup2(fd, STDERR_FILENO);
if (fd > STDERR_FILENO) { io::close(fd); }
}
}
void writepid(const char* pidfile) {
/* Try to write the pid file in a best-effort way. */
int fd = io::open(pidfile, O_RDWR | O_CREAT, 0644);
if (fd != -1) {
auto pid = strings::format("{}\n", (unsigned long)getpid());
io::write(fd, pid.data(), pid.size());
io::close(fd);
}
}
void usedir(std::string_view path, bool force) {
auto directory = normalize_path(path);
if (strings::endswith(directory, "/.xapiand")) {
directory.resize(directory.size() - 9);
}
auto xapiand_directory = directory + "/.xapiand";
if (force) {
if (!mkdirs(xapiand_directory)) {
L_ERR("Cannot create working directory: {}: {} ({}): {}", repr(directory), error::name(errno), errno, error::description(errno));
throw SystemExit(EX_OSFILE);
}
} else {
if (!mkdir(directory) || !mkdir(xapiand_directory)) {
L_ERR("Cannot create working directory: {}: {} ({}): {}", repr(directory), error::name(errno), errno, error::description(errno));
throw SystemExit(EX_OSFILE);
}
DIR *dirp = opendir(xapiand_directory);
if (dirp) {
bool empty = true;
struct dirent *ent;
while ((ent = readdir(dirp)) != nullptr) {
const char *s = ent->d_name;
if (ent->d_type == DT_DIR) {
continue;
}
if (ent->d_type == DT_REG) {
if (
std::strcmp(s, "node") == 0 ||
std::strcmp(s, "iamchert") == 0 ||
std::strcmp(s, "iamglass") == 0 ||
std::strcmp(s, "iamhoney") == 0
) {
empty = true;
break;
}
}
empty = false;
}
closedir(dirp);
if (!empty) {
L_CRIT("Working directory must be empty or a valid Xapiand database: {}", directory);
throw SystemExit(EX_DATAERR);
}
}
}
if (chdir(directory.c_str()) == -1) {
L_CRIT("Cannot change current working directory to {}", directory);
throw SystemExit(EX_OSFILE);
}
char buffer[PATH_MAX + 1];
if (getcwd(buffer, sizeof(buffer)) == nullptr) {
L_CRIT("Cannot get current working directory");
throw SystemExit(EX_OSFILE);
}
Endpoint::cwd = normalize_path(buffer, true); // Endpoint::cwd must always end with slash
L_NOTICE("Changed current working directory to {}", Endpoint::cwd);
}
Endpoints
resolve_index_endpoints(const Endpoint& endpoint) {
// This function tries to resolve endpoints the "right" way (using XapiandManager)
// but if it fails, it tries to get all available shard directories directly,
// otherwise it uses the passed endpoint as single endpoint.
auto endpoints = XapiandManager::resolve_index_endpoints(endpoint);
if (endpoints.empty()) {
auto base_path = endpoint.path + "/";
DIR *dirp = ::opendir(base_path.c_str());
if (dirp != nullptr) {
struct dirent *ent;
while ((ent = ::readdir(dirp)) != nullptr) {
const char *n = ent->d_name;
if (ent->d_type == DT_DIR) {
if (n[0] == '.' && (n[1] == '\0' || (n[1] == '.' && n[2] == '\0'))) {
continue;
}
// This is a valid directory
if (n[0] == '.' && n[1] == '_' && n[2] == '_') {
endpoints.add(Endpoint(base_path + n));
}
}
}
::closedir(dirp);
}
if (endpoints.empty()) {
endpoints.add(endpoint);
}
}
return endpoints;
}
void banner() {
set_thread_name("MAIN");
std::vector<std::string> values({
strings::format("Xapian v{}.{}.{}", Xapian::major_version(), Xapian::minor_version(), Xapian::revision()),
#ifdef XAPIAND_CHAISCRIPT
strings::format("ChaiScript v{}.{}", chaiscript::Build_Info::version_major(), chaiscript::Build_Info::version_minor()),
#endif
#ifdef USE_ICU
strings::format("ICU v{}.{}", U_ICU_VERSION_MAJOR_NUM, U_ICU_VERSION_MINOR_NUM),
#endif
});
if (Logging::log_level >= LOG_NOTICE) {
constexpr auto outer = rgb(0, 128, 0);
constexpr auto inner = rgb(144, 238, 144);
constexpr auto top = rgb(255, 255, 255);
L(-LOG_NOTICE, NO_COLOR,
"\n\n" +
outer + " _ " + rgb(255, 255, 255) + " ___\n" +
outer + " _-´´" + top + "_" + outer + "``-_ " + rgb(255, 255, 255) + " __ / / _ _\n" +
outer + " .´ " + top + "_-´ `-_" + outer + " `. " + rgb(224, 224, 224) + " \\ \\/ /__ _ _ __ (_) __ _ _ __ __| |\n" +
outer + " | " + top + "`-_ _-´" + outer + " | " + rgb(192, 192, 192) + " \\ // _` | '_ \\| |/ _` | '_ \\ / _` |\n" +
outer + " | " + inner + "`-_" + top + "`-´" + inner + "_-´" + outer + " | " + rgb(160, 160, 160) + " / \\ (_| | |_) | | (_| | | | | (_| |\n" +
outer + " | " + inner + "`-_`-´_-´" + outer + " | " + rgb(128, 128, 128) + " / /\\__\\__,_| .__/|_|\\__,_|_| |_|\\__,_|\n" +
outer + " `-_ " + inner + "`-´" + outer + " _-´ " + rgb(96, 96, 96) + "/_/" + rgb(144, 238, 144) + "{:^9}" + rgb(96, 96, 96) + "|_|" + rgb(0, 128, 0) + "{:>24}" + "\n" +
outer + " ``-´´ " + rgb(0, 128, 0) + "{:>42}" + "\n" +
rgb(0, 96, 0) + "{:>54}" + "\n\n",
"v" + Package::VERSION,
"rev:" + Package::REVISION,
Package::BUGREPORT,
"Using " + strings::join(values, ", ", " and "));
}
L(-LOG_NOTICE, WHITE, "{} (pid:{})", Package::STRING, getpid());
}
void setup() {
std::vector<std::string> modes;
if (opts.strict) {
modes.emplace_back("strict");
}
if (!modes.empty()) {
L_INFO("Activated " + strings::join(modes, ", ", " and ") + ((modes.size() == 1) ? " mode by default." : " modes by default."));
}
adjustOpenFilesLimit();
usedir(opts.database, opts.force);
}
void server(std::chrono::steady_clock::time_point process_start) {
if (opts.detach) {
L_NOTICE("Xapiand is done with all work here. Daemon on process ID [{}] taking over!", getpid());
}
nanosleep(100000000); // sleep for 100 milliseconds
setup();
ev::default_loop default_loop(opts.ev_flags);
L_INFO("Connection processing backend: {}", ev_backend(default_loop.backend()));
auto& manager = XapiandManager::make(&default_loop, opts.ev_flags, process_start);
manager->run();
long managers = manager.use_count() - 1;
if (managers == 0) {
L(-LOG_NOTICE, NOTICE_COL, "Xapiand is cleanly done with all work!");
} else {
L(-LOG_WARNING, WARNING_COL, "Xapiand is uncleanly done with all work ({})!\n{}", managers, manager->dump_tree());
}
manager.reset();
}
void dump_documents() {
std::shared_ptr<XapiandManager> manager;
int fd = opts.filename.empty() ? STDOUT_FILENO : io::open(opts.filename.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0600);
if (fd != -1) {
try {
setup();
manager = XapiandManager::make();
DatabaseHandler db_handler;
Endpoint endpoint(opts.dump_documents);
auto endpoints = resolve_index_endpoints(endpoint);
L_INFO("Dumping database: {}", repr(endpoints.to_string()));
db_handler.reset(endpoints, DB_OPEN);
auto sha256 = db_handler.dump_documents(fd);
L(-LOG_NOTICE, NOTICE_COL, "Dump sha256 = {}", sha256);
manager->join();
manager.reset();
} catch (...) {
if (fd != STDOUT_FILENO) {
io::close(fd);
}
if (manager) {
manager->join();
manager.reset();
}
throw;
}
if (fd != STDOUT_FILENO) {
io::close(fd);
}
} else {
L_CRIT("Cannot open file: {}", opts.filename);
throw SystemExit(EX_OSFILE);
}
}
void restore_documents() {
std::shared_ptr<XapiandManager> manager;
int fd = (opts.filename.empty() || opts.filename == "-") ? STDIN_FILENO : io::open(opts.filename.c_str(), O_RDONLY);
if (fd != -1) {
try {
setup();
manager = XapiandManager::make();
DatabaseHandler db_handler;
Endpoint endpoint(opts.restore_documents);
auto endpoints = resolve_index_endpoints(endpoint);
L_INFO("Restoring into: {}", repr(endpoints.to_string()));
db_handler.reset(endpoints, DB_CREATE_OR_OPEN | DB_WRITABLE | DB_DISABLE_WAL | DB_RESTORE | DB_DISABLE_AUTOCOMMIT);
auto sha256 = db_handler.restore_documents(fd);
L(-LOG_NOTICE, NOTICE_COL, "Restore sha256 = {}", sha256);
manager->join();
manager.reset();
} catch (...) {
if (fd != STDIN_FILENO) {
io::close(fd);
}
if (manager) {
manager->join();
manager.reset();
}
throw;
}
if (fd != STDIN_FILENO) {
io::close(fd);
}
} else {
L_CRIT("Cannot open file: {}", opts.filename);
throw SystemExit(EX_OSFILE);
}
}
void
cleanup_manager()
{
try {
auto& manager = XapiandManager::manager();
if (manager) {
// At exit, join manager
manager->join();
auto sig = manager->atom_sig.load();
if (sig < 0) {
_Exit(-sig);
}
}
} catch (const SystemExit& exc) {
_Exit(exc.code);
} catch (...) {
_Exit(EX_SOFTWARE);
}
}
int main(int argc, char **argv) {
#ifdef XAPIAND_CHECK_SIZES
check_size();
#endif
int exit_code = EX_OK;
auto process_start = std::chrono::steady_clock::now();
#if defined(__linux__) && !defined(__GLIBC__)
pthread_attr_t a;
memset(&a, 0, sizeof(pthread_attr_t));
pthread_attr_setstacksize(&a, 8*1024*1024); // 8MB as GLIBC
pthread_attr_setguardsize(&a, 4096); // one page
pthread_setattr_default_np(&a);
#endif
try {
opts = parseOptions(argc, argv);
if (opts.detach) {
detach();
}
if (!opts.pidfile.empty()) {
writepid(opts.pidfile.c_str());
}
atexit(cleanup_manager);
// Initialize options:
setup_signal_handlers();
std::setlocale(LC_CTYPE, "");
// Logging thread must be created after fork the parent process
auto& handlers = Logging::handlers;
if (opts.logfile.compare("syslog") == 0) {
handlers.push_back(std::make_unique<SysLog>());
} else if (!opts.logfile.empty()) {
handlers.push_back(std::make_unique<StreamLogger>(opts.logfile.c_str()));
}
if (!opts.detach || handlers.empty()) {
handlers.push_back(std::make_unique<StderrLogger>());
}
Logging::log_level += opts.verbosity;
Logging::colors = opts.colors;
Logging::no_colors = opts.no_colors;
demote(opts.uid.c_str(), opts.gid.c_str());
if (opts.strict) {
default_spc.flags.strict = true;
}
banner();
try {
if (!opts.dump_documents.empty()) {
dump_documents();
} else if (!opts.restore_documents.empty()) {
restore_documents();
} else {
server(process_start);
}
} catch (const SystemExit& exc) {
exit_code = exc.code;
} catch (const BaseException& exc) {
L_CRIT("Uncaught exception: {}", *exc.get_context() ? exc.get_context() : "Unkown BaseException!");
exit_code = EX_SOFTWARE;
} catch (const Xapian::Error& exc) {
L_CRIT("Uncaught exception: {}", exc.get_description());
exit_code = EX_SOFTWARE;
} catch (const std::exception& exc) {
L_CRIT("Uncaught exception: {}", *exc.what() ? exc.what() : "Unkown std::exception!");
exit_code = EX_SOFTWARE;
} catch (...) {
L_CRIT("Uncaught exception!");
exit_code = EX_SOFTWARE;
}
} catch (const SystemExit& exc) {
exit_code = exc.code;
} catch (...) {
L_CRIT("Uncaught exception!!");
exit_code = EX_SOFTWARE;
}
if (!opts.pidfile.empty()) {
L_INFO("Removing the pid file.");
unlink(opts.pidfile.c_str());
}
Logging::finish();
Logging::join();
return exit_code;
}
| 33.652433 | 215 | 0.640522 | [
"vector"
] |
e999ceefd60608053e4041a637122c4537dc60ea | 1,714 | cpp | C++ | aizu-online-judge/DSL/1_A.cpp | zaurus-yusya/atcoder | 5fc345b3da50222fa1366d1ce52ae58799488cef | [
"MIT"
] | 3 | 2020-05-27T16:27:12.000Z | 2021-01-27T12:47:12.000Z | aizu-online-judge/DSL/1_A.cpp | zaurus-yusya/Competitive-Programming | c72e13a11f76f463510bd4a476b86631d9d1b13a | [
"MIT"
] | null | null | null | aizu-online-judge/DSL/1_A.cpp | zaurus-yusya/Competitive-Programming | c72e13a11f76f463510bd4a476b86631d9d1b13a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
#define rep(i,n) for(ll i=0;i<(n);i++)
#define repr(i,n) for(ll i=(n-1);i>=0;i--)
#define all(x) x.begin(),x.end()
#define br cout << "\n";
using namespace std;
const int INF = 1e9;
const int MOD = 1e9+7;
using Graph = vector<vector<ll>>;
template<class T> inline bool chmin(T &a, T b) { if(a > b){ a = b; return true;} return false;}
template<class T> inline bool chmax(T &a, T b) { if(a < b){ a = b; return true;} return false;}
// 0 false, 1 true
// string to int : -48
// ceil(a) 1.2->2.0
// c++17 g++ -std=c++17 a.cpp
struct UnionFind
{
vector<long long> d;
UnionFind(long long n = 0) : d(n, -1)
{
}
//root : -size, not root: root
long long root(long long x){
if(d[x] < 0){
return x;
}
return d[x] = root(d[x]);
}
bool unite(long long x, long long y){
x = root(x);
y = root(y);
if(x == y){
return false;
}
if(d[x] > d[y]){
swap(x, y);
}
d[x] += d[y];
d[y] = x;
return true;
}
long long size(long long x){
return -d[root(x)];
}
bool issame(long long a, long long b){
return root(a) == root(b);
}
};
int main() {
std::cout << std::fixed << std::setprecision(15);
ll n, q;
cin >> n >> q;
UnionFind uf(n);
rep(i,q){
ll com;
cin >> com;
ll a, b;
cin >> a >> b;
if(com == 0){
uf.unite(a,b);
}else{
if(uf.issame(a,b)){
cout << 1 << endl;
}else{
cout << 0 << endl;
}
}
}
} | 20.902439 | 95 | 0.456243 | [
"vector"
] |
e99baa5a478930de761c89bf148e4112acf82114 | 7,252 | cpp | C++ | Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/DirectWrite inline object sample/C++/DWriteInlineObject.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2022-01-21T01:40:58.000Z | 2022-01-21T01:41:10.000Z | Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/DirectWrite inline object sample/C++/DWriteInlineObject.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 1 | 2022-03-15T04:21:41.000Z | 2022-03-15T04:21:41.000Z | Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/DirectWrite inline object sample/C++/DWriteInlineObject.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | null | null | null | //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved
#include "pch.h"
#include "DWriteInlineObject.h"
using namespace Microsoft::WRL;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Input;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
DWriteInlineObject::DWriteInlineObject()
{
}
void DWriteInlineObject::HandleDeviceLost()
{
// Release window size-dependent resources prior to creating a new device and swap chain.
m_inlineImage = nullptr;
m_textLayout = nullptr;
DirectXBase::HandleDeviceLost();
}
void DWriteInlineObject::CreateDeviceIndependentResources()
{
DirectXBase::CreateDeviceIndependentResources();
// Create a DirectWrite text format object.
DX::ThrowIfFailed(
m_dwriteFactory->CreateTextFormat(
L"Segoe UI",
nullptr,
DWRITE_FONT_WEIGHT_LIGHT,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
64.0f,
L"en-US", // locale
&m_textFormat
)
);
// Center the text horizontally.
DX::ThrowIfFailed(
m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)
);
// Center the text vertically.
DX::ThrowIfFailed(
m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)
);
}
void DWriteInlineObject::CreateDeviceResources()
{
DirectXBase::CreateDeviceResources();
m_sampleOverlay = ref new SampleOverlay();
m_sampleOverlay->Initialize(
m_d2dDevice.Get(),
m_d2dContext.Get(),
m_wicFactory.Get(),
m_dwriteFactory.Get(),
"DirectWrite inline object sample"
);
DX::ThrowIfFailed(
m_d2dContext->CreateSolidColorBrush(
D2D1::ColorF(D2D1::ColorF::Black),
&m_blackBrush
)
);
}
void DWriteInlineObject::CreateWindowSizeDependentResources()
{
DirectXBase::CreateWindowSizeDependentResources();
Platform::String^ text = "Inline object * sample";
D2D1_SIZE_F size = m_d2dContext->GetSize();
// Create a DirectWrite Text Layout object
DX::ThrowIfFailed(
m_dwriteFactory->CreateTextLayout(
text->Data(), // Text to be displayed
text->Length(), // Length of the text
m_textFormat.Get(), // DirectWrite Text Format object
size.width, // Width of the Text Layout
size.height, // Height of the Text Layout
&m_textLayout
)
);
m_inlineImage = new InlineImage(m_d2dContext.Get(), m_wicFactory.Get(), L"img1.jpg");
DWRITE_TEXT_RANGE textRange = {14, 1};
DX::ThrowIfFailed(
m_textLayout->SetInlineObject(m_inlineImage.Get(), textRange)
);
}
void DWriteInlineObject::Render()
{
m_d2dContext->BeginDraw();
m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
m_d2dContext->DrawTextLayout(
D2D1::Point2F(0.0f, 0.0f),
m_textLayout.Get(),
m_blackBrush.Get()
);
// We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
// is lost. It will be handled during the next call to Present.
HRESULT hr = m_d2dContext->EndDraw();
if (hr != D2DERR_RECREATE_TARGET)
{
DX::ThrowIfFailed(hr);
}
m_sampleOverlay->Render();
}
void DWriteInlineObject::Initialize(
_In_ CoreApplicationView^ applicationView
)
{
applicationView->Activated +=
ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DWriteInlineObject::OnActivated);
CoreApplication::Suspending +=
ref new EventHandler<SuspendingEventArgs^>(this, &DWriteInlineObject::OnSuspending);
CoreApplication::Resuming +=
ref new EventHandler<Platform::Object^>(this, &DWriteInlineObject::OnResuming);
}
void DWriteInlineObject::SetWindow(
_In_ CoreWindow^ window
)
{
window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
window->SizeChanged +=
ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DWriteInlineObject::OnWindowSizeChanged);
DisplayInformation::GetForCurrentView()->DpiChanged +=
ref new TypedEventHandler<DisplayInformation^, Platform::Object^>(this, &DWriteInlineObject::OnDpiChanged);
DisplayInformation::DisplayContentsInvalidated +=
ref new TypedEventHandler<DisplayInformation^, Platform::Object^>(this, &DWriteInlineObject::OnDisplayContentsInvalidated);
// Disable all pointer visual feedback for better performance when touching.
auto pointerVisualizationSettings = PointerVisualizationSettings::GetForCurrentView();
pointerVisualizationSettings->IsContactFeedbackEnabled = false;
pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false;
DirectXBase::Initialize(window, DisplayInformation::GetForCurrentView()->LogicalDpi);
}
void DWriteInlineObject::Load(
_In_ Platform::String^ entryPoint
)
{
}
void DWriteInlineObject::Run()
{
Render();
Present();
m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
}
void DWriteInlineObject::Uninitialize()
{
}
void DWriteInlineObject::OnWindowSizeChanged(
_In_ CoreWindow^ sender,
_In_ WindowSizeChangedEventArgs^ args
)
{
UpdateForWindowSizeChange();
m_sampleOverlay->UpdateForWindowSizeChange();
Render();
Present();
}
void DWriteInlineObject::OnDpiChanged(_In_ DisplayInformation^ sender, _In_ Platform::Object^ args)
{
SetDpi(sender->LogicalDpi);
Render();
Present();
}
void DWriteInlineObject::OnDisplayContentsInvalidated(_In_ DisplayInformation^ sender, _In_ Platform::Object^ args)
{
// Ensure the D3D Device is available for rendering.
ValidateDevice();
Render();
Present();
}
void DWriteInlineObject::OnActivated(
_In_ CoreApplicationView^ applicationView,
_In_ IActivatedEventArgs^ args
)
{
m_window->Activate();
}
void DWriteInlineObject::OnSuspending(
_In_ Platform::Object^ sender,
_In_ SuspendingEventArgs^ args
)
{
// Hint to the driver that the app is entering an idle state and that its memory
// can be temporarily used for other apps.
Trim();
}
void DWriteInlineObject::OnResuming(
_In_ Platform::Object^ sender,
_In_ Platform::Object^ args
)
{
}
IFrameworkView^ DirectXAppSource::CreateView()
{
return ref new DWriteInlineObject();
}
[Platform::MTAThread]
int main(Platform::Array<Platform::String^>^)
{
auto directXAppSource = ref new DirectXAppSource();
CoreApplication::Run(directXAppSource);
return 0;
}
| 28.217899 | 131 | 0.692085 | [
"render",
"object"
] |
e9a32af681dc4459910e8532c442aff3e7b89b07 | 14,761 | cpp | C++ | src/SOURCE/parallelTFSF.cpp | Seideman-Group/chiML | 9ace5dccdbc6c173e8383f6a31ff421b4fefffdf | [
"MIT"
] | 1 | 2019-04-27T05:25:27.000Z | 2019-04-27T05:25:27.000Z | src/SOURCE/parallelTFSF.cpp | Seideman-Group/chiML | 9ace5dccdbc6c173e8383f6a31ff421b4fefffdf | [
"MIT"
] | null | null | null | src/SOURCE/parallelTFSF.cpp | Seideman-Group/chiML | 9ace5dccdbc6c173e8383f6a31ff421b4fefffdf | [
"MIT"
] | 2 | 2019-04-03T10:08:21.000Z | 2019-09-30T22:40:28.000Z | /** @file SOURCE/parallelTFSF.cpp
* @brief Class creates a TFSF surface to introduce an incident pulse
*
* A class used to introduce a plane wave from a TFSF surface centered at loc in a box the size of sz
*
* @author Thomas A. Purcell (tpurcell90)
* @bug No known bugs
*/
#include <SOURCE/parallelTFSF.hpp>
void updateIncdFieldJ(const std::vector<cplx>& pulseVec, int pulAddStart, cplx prefact, const std::vector<paramUpIncdField>& upList, cplx_grid_ptr incd_i, cplx_grid_ptr incd_j, cplx_grid_ptr incd_k, std::shared_ptr<IncdCPMLCplx> pml_incd )
{
std::transform(pulseVec.data(), pulseVec.data()+pulseVec.size(), &incd_i->point(pulAddStart), &incd_i->point(pulAddStart), [&](cplx pul, cplx incd){return incd + prefact * pul;} );
for(auto& param : upList)
{
zaxpy_(param.nSz_, param.prefactor_j_, &incd_j->point(param.indPosK_), 1, &incd_i->point(param.indI_), 1);
zaxpy_(param.nSz_, -1.0*param.prefactor_j_, &incd_j->point(param.indNegK_), 1, &incd_i->point(param.indI_), 1);
}
pml_incd->updateGrid();
}
void updateIncdFieldK(const std::vector<cplx>& pulseVec, int pulAddStart, cplx prefact, const std::vector<paramUpIncdField>& upList, cplx_grid_ptr incd_i, cplx_grid_ptr incd_j, cplx_grid_ptr incd_k, std::shared_ptr<IncdCPMLCplx> pml_incd )
{
std::transform(pulseVec.data(), pulseVec.data()+pulseVec.size(), &incd_i->point(pulAddStart), &incd_i->point(pulAddStart), [&](cplx pul, cplx incd){return incd + prefact * pul;} );
for(auto& param : upList)
{
zaxpy_(param.nSz_, param.prefactor_k_, &incd_k->point(param.indPosJ_), 1, &incd_i->point(param.indI_), 1);
zaxpy_(param.nSz_, -1.0*param.prefactor_k_, &incd_k->point(param.indNegJ_), 1, &incd_i->point(param.indI_), 1);
}
pml_incd->updateGrid();
}
void updateIncdFieldJK(const std::vector<cplx>& pulseVec, int pulAddStart, cplx prefact, const std::vector<paramUpIncdField>& upList, cplx_grid_ptr incd_i, cplx_grid_ptr incd_j, cplx_grid_ptr incd_k, std::shared_ptr<IncdCPMLCplx> pml_incd )
{
std::transform(pulseVec.data(), pulseVec.data()+pulseVec.size(), &incd_i->point(pulAddStart), &incd_i->point(pulAddStart), [&](cplx pul, cplx incd){return incd + prefact * pul;} );
for(auto& param : upList)
{
zaxpy_(param.nSz_, param.prefactor_j_, &incd_j->point(param.indPosK_), 1, &incd_i->point(param.indI_), 1);
zaxpy_(param.nSz_, -1.0*param.prefactor_j_, &incd_j->point(param.indNegK_), 1, &incd_i->point(param.indI_), 1);
zaxpy_(param.nSz_, param.prefactor_k_, &incd_k->point(param.indPosJ_), 1, &incd_i->point(param.indI_), 1);
zaxpy_(param.nSz_, -1.0*param.prefactor_k_, &incd_k->point(param.indNegJ_), 1, &incd_i->point(param.indI_), 1);
}
pml_incd->updateGrid();
}
void updateIncdPols(const std::vector<paramUpIncdField>& upList, cplx_grid_ptr incdU , std::vector<cplx_grid_ptr>& incdP, std::vector<cplx_grid_ptr>& incdPrevP, cplx* scratch )
{
for(auto& param : upList)
{
for(int pp = 0; pp < param.aChiXi_.size(); ++pp)
{
zcopy_(param.nSz_, &incdP[pp]->point(param.indI_), 1, scratch, 1);
zscal_(param.nSz_, param.aChiAlpha_[pp], &incdP[pp]->point(param.indI_), 1);
zaxpy_(param.nSz_, param.aChiXi_ [pp], &incdPrevP[pp]->point(param.indI_), 1, &incdP[pp]->point(param.indI_), 1);
zaxpy_(param.nSz_, param.aChiGamma_[pp], &incdU->point(param.indI_), 1, &incdP[pp]->point(param.indI_), 1);
zcopy_(param.nSz_, scratch, 1, &incdPrevP[pp]->point(param.indI_), 1);
}
}
}
void incdD2U( double chiFact, cplx_grid_ptr incdU, cplx_grid_ptr incdD, real_grid_ptr ep_mu, const std::vector<cplx_grid_ptr>& incdP, cplx* scratch )
{
std::transform(incdD->data(), incdD->data()+incdD->size(), ep_mu->data(), incdU->data(), [](cplx a, double b){return a/b; });
for(int pp = 0; pp < incdP.size(); ++pp)
{
std::transform(incdP[pp]->data(), incdP[pp]->data()+incdP[pp]->size(), ep_mu->data(), scratch, [](cplx a, double b){return -1.0*a/b; });
zaxpy_(incdU->size(), 1.0, scratch, 1, incdU->data(), 1);
}
}
void fillPulseVec(const std::vector<double>& distVec, std::vector<std::shared_ptr<Pulse>> pulses, double tt, std::vector<cplx>& pulseVec)
{
std::fill_n(pulseVec.begin(), pulseVec.size(), 0.0);
for(auto& p : pulses)
std::transform(distVec.begin(), distVec.end(), pulseVec.begin(), pulseVec.begin(), [&](double dist, cplx pVal){ return pVal + p->pulse(tt - dist); } );
}
void tfsfUpdateFxnReal::addIncdFields(real_pgrid_ptr grid_Ui, real_pgrid_ptr grid_Di, std::shared_ptr<paramStoreTFSF> sur, real_grid_ptr ep_mu, double* tempEpMuStore)
{
for(int ll = 0; ll < sur->indsD_.size(); ll+=2)
daxpy_(sur->szTrans_[0], sur->prefactor_, reinterpret_cast<double*>(&sur->incdField_->point( sur->indsD_[ll] ) ), 2*sur->strideIncd_, &grid_Di->point( sur->indsD_[ll+1] ), sur->strideMain_);
for(int ll = 0; ll < sur->indsU_.size(); ll+=2)
daxpy_(sur->szTrans_[0], sur->prefactor_, reinterpret_cast<double*>(&sur->incdField_->point( sur->indsU_[ll] ) ), 2*sur->strideIncd_, &grid_Ui->point( sur->indsU_[ll+1] ), sur->strideMain_);
}
void tfsfUpdateFxnCplx::addIncdFields(cplx_pgrid_ptr grid_Ui, cplx_pgrid_ptr grid_Di, std::shared_ptr<paramStoreTFSF> sur, real_grid_ptr ep_mu, cplx* tempEpMuStore)
{
for(int ll = 0; ll < sur->indsD_.size(); ll+=2)
zaxpy_(sur->szTrans_[0], sur->prefactor_, &sur->incdField_->point( sur->indsD_[ll] ), sur->strideIncd_, &grid_Di->point( sur->indsD_[ll+1] ), sur->strideMain_);
for(int ll = 0; ll < sur->indsU_.size(); ll+=2)
zaxpy_(sur->szTrans_[0], sur->prefactor_, &sur->incdField_->point( sur->indsU_[ll] ), sur->strideIncd_, &grid_Ui->point( sur->indsU_[ll+1] ), sur->strideMain_);
}
void tfsfUpdateFxnReal::addIncdFieldsEPChange(real_pgrid_ptr grid_Ui, real_pgrid_ptr grid_Di, std::shared_ptr<paramStoreTFSF> sur, real_grid_ptr ep_mu, double* tempEpMuStore)
{
for(int ll = 0; ll < sur->indsD_.size(); ll+=2)
daxpy_(sur->szTrans_[0], sur->prefactor_, reinterpret_cast<double*>(&sur->incdField_->point( sur->indsD_[ll] ) ), 2*sur->strideIncd_, &grid_Di->point( sur->indsD_[ll+1] ), sur->strideMain_);
for(int ll = 0; ll < sur->indsU_.size(); ll+=2)
{
dcopy_(sur->szTrans_[0], reinterpret_cast<double*>(&sur->incdField_->point( sur->indsU_[ll] ) ), 2*sur->strideIncd_, tempEpMuStore , 1);
dcopy_(sur->szTrans_[0], &ep_mu->point( sur->indsU_[ll] ) , sur->strideIncd_, tempEpMuStore+sur->szTrans_[0], 1);
std::transform(tempEpMuStore, tempEpMuStore+sur->szTrans_[0], tempEpMuStore+sur->szTrans_[0], tempEpMuStore, std::divides<double>() );
daxpy_(sur->szTrans_[0], sur->prefactor_, tempEpMuStore, 1, &grid_Ui->point( sur->indsU_[ll+1] ), sur->strideMain_);
}
}
void tfsfUpdateFxnCplx::addIncdFieldsEPChange(cplx_pgrid_ptr grid_Ui, cplx_pgrid_ptr grid_Di, std::shared_ptr<paramStoreTFSF> sur, real_grid_ptr ep_mu, cplx* tempEpMuStore)
{
for(int ll = 0; ll < sur->indsD_.size(); ll+=2)
zaxpy_(sur->szTrans_[0], sur->prefactor_, &sur->incdField_->point( sur->indsD_[ll] ), sur->strideIncd_, &grid_Di->point( sur->indsD_[ll+1] ), sur->strideMain_);
for(int ll = 0; ll < sur->indsU_.size(); ll+=2)
{
zcopy_(sur->szTrans_[0], &sur->incdField_->point( sur->indsU_[ll] ), sur->strideIncd_, tempEpMuStore , 1);
dcopy_(sur->szTrans_[0], &ep_mu->point( sur->indsU_[ll] ), sur->strideIncd_, reinterpret_cast<double*>(tempEpMuStore+sur->szTrans_[0]), 2);
std::transform(tempEpMuStore, tempEpMuStore+sur->szTrans_[0], tempEpMuStore+sur->szTrans_[0], tempEpMuStore, std::divides<cplx>() );
zaxpy_(sur->szTrans_[0], sur->prefactor_, tempEpMuStore, 1, &grid_Ui->point( sur->indsU_[ll+1] ), sur->strideMain_);
}
}
parallelTFSFReal::parallelTFSFReal(std::shared_ptr<mpiInterface> gridComm, std::array<int,3> loc, std::array<int,3> sz, double theta, double phi, double psi, POLARIZATION circPol, double kLenRelJ, std::array<double,3> d, std::array<int,3> m, double dt, std::vector<std::shared_ptr<Pulse>> pul, std::array<pgrid_ptr,3> E, std::array<pgrid_ptr,3> H, std::array<pgrid_ptr,3> D, std::array<pgrid_ptr,3> B, std::array<int_pgrid_ptr,3> physE, std::array<int_pgrid_ptr,3> physH, std::vector<std::shared_ptr<Obj>> objArr, int nomPMLThick, double pmlM, double pmlMA, double pmlAMax) :
parallelTFSFBase<double>(gridComm, loc, sz, theta, phi, psi, circPol, kLenRelJ, d, m, dt, pul, E, H, D, B, physE, physH, objArr, nomPMLThick, pmlM, pmlMA, pmlAMax)
{
if(E_[0])
{
if( std::any_of(eps_[0]->data(), eps_[0]->data() + eps_[0]->size(), [=](double a){ return a != eps_[0]->point(0); } ) )
addEIncd_[0] = tfsfUpdateFxnReal::addIncdFieldsEPChange;
else
addEIncd_[0] = tfsfUpdateFxnReal::addIncdFields;
}
else
{
addEIncd_[0] = [](real_pgrid_ptr, real_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, double*){ return; };
}
if(E_[1])
{
if( std::any_of(eps_[1]->data(), eps_[1]->data() + eps_[1]->size(), [=](double a){ return a != eps_[1]->point(0); } ) )
addEIncd_[1] = tfsfUpdateFxnReal::addIncdFieldsEPChange;
else
addEIncd_[1] = tfsfUpdateFxnReal::addIncdFields;
}
else
{
addEIncd_[1] = [](real_pgrid_ptr, real_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, double*){ return; };
}
if(E_[2])
{
if( std::any_of(eps_[2]->data(), eps_[2]->data() + eps_[2]->size(), [=](double a){ return a != eps_[2]->point(0); } ) )
addEIncd_[2] = tfsfUpdateFxnReal::addIncdFieldsEPChange;
else
addEIncd_[2] = tfsfUpdateFxnReal::addIncdFields;
}
else
{
addEIncd_[2] = [](real_pgrid_ptr, real_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, double*){ return; };
}
if(H_[0])
{
if( std::any_of(mu_[0]->data(), mu_[0]->data() + mu_[0]->size(), [=](double a){ return a != mu_[0]->point(0); } ) )
addHIncd_[0] = tfsfUpdateFxnReal::addIncdFieldsEPChange;
else
addHIncd_[0] = tfsfUpdateFxnReal::addIncdFields;
}
else
{
addHIncd_[0] = [](real_pgrid_ptr, real_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, double*){ return; };
}
if(H_[1])
{
if( std::any_of(mu_[1]->data(), mu_[1]->data() + mu_[1]->size(), [=](double a){ return a != mu_[1]->point(0); } ) )
addHIncd_[1] = tfsfUpdateFxnReal::addIncdFieldsEPChange;
else
addHIncd_[1] = tfsfUpdateFxnReal::addIncdFields;
}
else
{
addHIncd_[1] = [](real_pgrid_ptr, real_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, double*){ return; };
}
if(H_[2])
{
if( std::any_of(mu_[2]->data(), mu_[2]->data() + mu_[2]->size(), [=](double a){ return a != mu_[2]->point(0); } ) )
addHIncd_[2] = tfsfUpdateFxnReal::addIncdFieldsEPChange;
else
addHIncd_[2] = tfsfUpdateFxnReal::addIncdFields;
}
else
{
addHIncd_[2] = [](real_pgrid_ptr, real_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, double*){ return; };
}
}
parallelTFSFCplx::parallelTFSFCplx(std::shared_ptr<mpiInterface> gridComm, std::array<int,3> loc, std::array<int,3> sz, double theta, double phi, double psi, POLARIZATION circPol, double kLenRelJ, std::array<double,3> d, std::array<int,3> m, double dt, std::vector<std::shared_ptr<Pulse>> pul, std::array<pgrid_ptr,3> E, std::array<pgrid_ptr,3> H, std::array<pgrid_ptr,3> D, std::array<pgrid_ptr,3> B, std::array<int_pgrid_ptr,3> physE, std::array<int_pgrid_ptr,3> physH, std::vector<std::shared_ptr<Obj>> objArr, int nomPMLThick, double pmlM, double pmlMA, double pmlAMax) :
parallelTFSFBase<cplx>(gridComm, loc, sz, theta, phi, psi, circPol, kLenRelJ, d, m, dt, pul, E, H, D, B, physE, physH, objArr, nomPMLThick, pmlM, pmlMA, pmlAMax)
{
if(E_[0])
{
if( std::any_of(eps_[0]->data(), eps_[0]->data() + eps_[0]->size(), [=](double a){ return a != eps_[0]->point(0); } ) )
addEIncd_[0] = tfsfUpdateFxnCplx::addIncdFieldsEPChange;
else
addEIncd_[0] = tfsfUpdateFxnCplx::addIncdFields;
}
else
{
addEIncd_[0] = [](cplx_pgrid_ptr, cplx_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, cplx*){ return; };
}
if(E_[1])
{
if( std::any_of(eps_[1]->data(), eps_[1]->data() + eps_[1]->size(), [=](double a){ return a != eps_[1]->point(0); } ) )
addEIncd_[1] = tfsfUpdateFxnCplx::addIncdFieldsEPChange;
else
addEIncd_[1] = tfsfUpdateFxnCplx::addIncdFields;
}
else
{
addEIncd_[1] = [](cplx_pgrid_ptr, cplx_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, cplx*){ return; };
}
if(E_[2])
{
if( std::any_of(eps_[2]->data(), eps_[2]->data() + eps_[2]->size(), [=](double a){ return a != eps_[2]->point(0); } ) )
addEIncd_[2] = tfsfUpdateFxnCplx::addIncdFieldsEPChange;
else
addEIncd_[2] = tfsfUpdateFxnCplx::addIncdFields;
}
else
{
addEIncd_[2] = [](cplx_pgrid_ptr, cplx_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, cplx*){ return; };
}
if(H_[0])
{
if( std::any_of(mu_[0]->data(), mu_[0]->data() + mu_[0]->size(), [=](double a){ return a != mu_[0]->point(0); } ) )
addHIncd_[0] = tfsfUpdateFxnCplx::addIncdFieldsEPChange;
else
addHIncd_[0] = tfsfUpdateFxnCplx::addIncdFields;
}
else
{
addHIncd_[0] = [](cplx_pgrid_ptr, cplx_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, cplx*){ return; };
}
if(H_[1])
{
if( std::any_of(mu_[1]->data(), mu_[1]->data() + mu_[1]->size(), [=](double a){ return a != mu_[1]->point(0); } ) )
addHIncd_[1] = tfsfUpdateFxnCplx::addIncdFieldsEPChange;
else
addHIncd_[1] = tfsfUpdateFxnCplx::addIncdFields;
}
else
{
addHIncd_[1] = [](cplx_pgrid_ptr, cplx_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, cplx*){ return; };
}
if(H_[2])
{
if( std::any_of(mu_[2]->data(), mu_[2]->data() + mu_[2]->size(), [=](double a){ return a != mu_[2]->point(0); } ) )
addHIncd_[2] = tfsfUpdateFxnCplx::addIncdFieldsEPChange;
else
addHIncd_[2] = tfsfUpdateFxnCplx::addIncdFields;
}
else
{
addHIncd_[2] = [](cplx_pgrid_ptr, cplx_pgrid_ptr, std::shared_ptr<paramStoreTFSF>, real_grid_ptr, cplx*){ return; };
}
} | 54.468635 | 575 | 0.637287 | [
"vector",
"transform"
] |
e9a44851472ff3d9b4777362fdfe751a97588454 | 4,383 | cpp | C++ | src/engine/e_language.cpp | gerich-home/zteeworlds | 73ad5e6d34d5639c67c93298f21dcd523b06bf73 | [
"Zlib"
] | 2 | 2017-09-30T22:06:07.000Z | 2021-07-20T23:50:33.000Z | src/engine/e_language.cpp | gerich-home/zteeworlds | 73ad5e6d34d5639c67c93298f21dcd523b06bf73 | [
"Zlib"
] | null | null | null | src/engine/e_language.cpp | gerich-home/zteeworlds | 73ad5e6d34d5639c67c93298f21dcd523b06bf73 | [
"Zlib"
] | 1 | 2017-09-30T22:06:14.000Z | 2017-09-30T22:06:14.000Z | #include "e_language.h"
#include <stdlib.h>
#include <stdio.h>
#include <base/system.h>
#include <string.h>
#include "e_linereader.h"
#include "e_engine.h"
#include <vector>
void format_replace(char * text)
{
int i = 0;
int j = 0;
int len = str_length(text);
while (i < len)
{
if (text[i] == '\\' && text[i + 1] == '\\')
{
text[j] = '\\';
i += 2;
j++;
continue;
}
if (text[i] == '\\' && text[i + 1] == 'n')
{
text[j] = '\n';
i += 2;
j++;
continue;
}
if (text[i] == '\\' && text[i + 1] == 'r')
{
text[j] = '\r';
i += 2;
j++;
continue;
}
text[j] = text[i];
i++;
j++;
}
mem_zero(text + j, len - j);
}
typedef struct LANGUAGE_ITEM
{
int gid;
const char * str;
const char * translated;
bool delete_str;
bool delete_translated;
} LANGUAGE_ITEM;
std::vector<LANGUAGE_ITEM *> language;
void lang_init()
{
language.clear();
}
void lang_free()
{
if (language.size() == 0) return;
for (int i = 0; i < language.size(); i++)
{
if (language[i])
{
if (language[i]->delete_str && language[i]->str)
{
free((void *)language[i]->str);
language[i]->str = 0;
}
if (language[i]->delete_translated && language[i]->translated)
{
free((void *)language[i]->translated);
language[i]->translated = 0;
}
}
delete language[i];
language[i] = 0;
}
language.clear();
}
int lang_load(const char * filename)
{
lang_free();
if (str_length(filename) == 0) return 1;
IOHANDLE file;
char fn_buf[512];
str_format(fn_buf, sizeof(fn_buf), "languages/%s", filename);
file = engine_openfile(fn_buf, IOFLAG_READ);
while(file)
{
int gid = -1;
const char * str = 0;
char *line = "";
LINEREADER lr;
char buf[4096];
linereader_init(&lr, file);
if (!(line = linereader_get(&lr))) // skiping language name
{
io_close(file);
break;
}
while (line = linereader_get(&lr))
{
format_replace(line);
if (str_length(line) == 0 || line[0] == '\r' || line[0] == '\n') continue;
if (!str)
{
sscanf(line, "%d", &gid);
if (gid != -1)
{
int start = 0, len = str_length(line);
while (line[len - 1] <= ' ' && len > 0) len--;
while (line[start] >= '0' && line[start] <= '9') start++;
if (line[start] != 0)
{
start++;
if (line[start] != 0)
{
len -= start;
mem_copy(buf, line + start, len);
buf[len] = 0;
} else buf[0] = 0;
} else buf[0] = 0;
str = buf;
}
} else {
LANGUAGE_ITEM * langitem = new LANGUAGE_ITEM;
langitem->gid = gid;
langitem->str = strdup(str);
langitem->translated = strdup(line);
langitem->delete_str = true;
langitem->delete_translated = true;
language.push_back(langitem);
gid = -1;
str = 0;
}
}
io_close(file);
file = 0;
dbg_msg("lang", "Language %s loaded", filename);
return 0;
}
dbg_msg("lang", "Cannot load language %s", filename);
return 1;
}
const char * _T(int gid, const char * str)
{
if (!str) return str;
char buf[4096];
int start = 0, end = str_length(str);
while (str[start] && (str[start] == ' ' || str[start] == '\n') && start < end) start++;
mem_copy(buf, str + start, end - start + 1);
end = str_length(buf) - 1;
while (buf[end] && (buf[end] == ' ' || buf[end] == '\n') && end > 0) { buf[end] = 0; end--; };
if (language.size() > 0)
{
for (int q = 0; q < 2; q++)
{
for (int i = 0; i < language.size(); i++)
{
if (!language[i] || !language[i]->str) continue;
if ((language[i]->gid == gid || q == 1) && strcmp(language[i]->str, buf) == 0)
{
if (language[i]->translated)
return language[i]->translated;
else
return language[i]->str;
}
}
}
}
LANGUAGE_ITEM * langitem = new LANGUAGE_ITEM;
langitem->gid = gid;
langitem->str = strdup(buf);
langitem->translated = 0;
langitem->delete_str = true;
langitem->delete_translated = false;
language.push_back(langitem);
#ifdef CONF_DEBUG
dbg_msg("lang", "%d %s", gid, str);
#endif
return str;
}
int get_gid(const char * str)
{
int q = 0;
for (int i = 0; i < strlen(str); i++)
{
q = (q + str[i] * i)%65536;
}
return q;
} | 20.291667 | 96 | 0.522473 | [
"vector"
] |
e9b0bfef8dfbee6661967df8b58ae7ede54f5e03 | 8,483 | cpp | C++ | legacy/src/allegro_flare/platform/win/midi_win.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 25 | 2015-03-30T02:02:43.000Z | 2019-03-04T22:29:12.000Z | legacy/src/allegro_flare/platform/win/midi_win.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 122 | 2015-04-01T08:15:26.000Z | 2019-10-16T20:31:22.000Z | legacy/src/allegro_flare/platform/win/midi_win.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 4 | 2016-09-02T12:14:09.000Z | 2018-11-23T20:38:49.000Z |
#include <allegro_flare/midi_win.h>
#include <mmsystem.h> /* multimedia functions (such as MIDI) for Windows */
#include <windows.h> /* required before including mmsystem.h */
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
static bool midi_initialized = false;
std::vector<MIDI_IN_DEVICE *> midi_in_device;
std::vector<MIDI_OUT_DEVICE *> midi_out_device;
static HMIDIOUT current_midi_out_device_handler; //<- eventually this will be a vector
// so multiple devices can be used
// simultaniously.
void init_midi()
{
if (midi_initialized) return;
std::cout << "init_midi();" << std::endl;
for (int i=0; i<(int)midi_out_device.size(); i++)
delete midi_out_device[i];
for (int i=0; i<(int)midi_in_device.size(); i++)
delete midi_in_device[i];
midi_out_device.clear();
midi_in_device.clear();
for (int i=0; i<(int)midiOutGetNumDevs(); i++)
{
midi_out_device.push_back(new MIDI_OUT_DEVICE());
MIDIOUTCAPS device;
midiOutGetDevCaps(i, &device, sizeof(MIDIOUTCAPS));
midi_out_device.back()->device_port_num = i;
midi_out_device.back()->open = false;
midi_out_device.back()->manufacturer_id = device.wMid;
midi_out_device.back()->product_id = device.wPid;
midi_out_device.back()->driver_version = device.vDriverVersion;
midi_out_device.back()->name = device.szPname;
midi_out_device.back()->name = device.szPname;
midi_out_device.back()->device_type = device.wTechnology;
midi_out_device.back()->num_voices = device.wVoices;
midi_out_device.back()->num_notes = device.wNotes;
midi_out_device.back()->num_channels = device.wChannelMask;
}
for (int i=0; i<(int)midiInGetNumDevs(); i++)
{
midi_in_device.push_back(new MIDI_IN_DEVICE());
MIDIINCAPS device;
midiInGetDevCaps(i, &device, sizeof(MIDIINCAPS));
midi_in_device.back()->device_port_num = i;
midi_in_device.back()->open = false;
midi_in_device.back()->manufacturer_id = device.wMid;
midi_in_device.back()->product_id = device.wPid;
midi_in_device.back()->driver_version = device.vDriverVersion;
midi_out_device.back()->name = device.szPname;
}
for (unsigned i=0; i<midi_out_device.size(); i++)
{
std::cout << "out " << midi_out_device[i]->device_port_num << ": " << midi_out_device[i]->name << "" << std::endl;
}
for (unsigned i=0; i<midi_in_device.size(); i++)
{
std::cout << "in " << midi_in_device[i]->device_port_num << ": " << midi_in_device[i]->name << "" << std::endl;
}
midi_initialized = true;
}
void uninstall_midi()
{
if (!midi_initialized) return;
// turn any MIDI notes currently playing:
midiOutReset(current_midi_out_device_handler);
// Remove any data in MIDI device and close the MIDI Output port
midiOutClose(current_midi_out_device_handler);
}
bool open_midi_device(MIDI_OUT_DEVICE *dev)
{
if (!midi_initialized) return false;
if (!dev) return false;
if (dev->open) return false;
MIDIOUTCAPS device;
midiOutGetDevCaps(dev->device_port_num, &device, sizeof(MIDIOUTCAPS));
MMRESULT flag = midiOutOpen(¤t_midi_out_device_handler, dev->device_port_num, 0, 0, CALLBACK_NULL);
if (flag != MMSYSERR_NOERROR) return false;
dev->open = true;
return true;
}
typedef union
{
unsigned long word;
unsigned char data[4];
} midi_message;
bool midi_patch_change(unsigned char channel, unsigned char patch_num)
{
midi_message message;
message.data[0] = PATCH_CHANGE; // MIDI command byte
message.data[1] = patch_num; // MIDI first data byte
message.data[2] = 0; // MIDI second data byte
message.data[3] = 0; // Unused parameter
MMRESULT flag = midiOutShortMsg(current_midi_out_device_handler, message.word);
if (flag != MMSYSERR_NOERROR)
{
std::cout << "midi_patch_change(): MIDI output is not open." << std::endl;
return false;
}
return true;
}
// max velocity of 127
bool midi_note_on(unsigned char channel, unsigned char pitch, unsigned char velocity)
{
midi_message message;
message.data[0] = NOTE_ON; // MIDI command byte
message.data[1] = pitch; // MIDI first data byte
message.data[2] = velocity; // MIDI second data byte (0-127)
message.data[3] = 0; // Unused parameter
MMRESULT flag = midiOutShortMsg(current_midi_out_device_handler, message.word);
if (flag != MMSYSERR_NOERROR)
{
std::cout << "note_on(): MIDI output is not open." << std::endl;
return false;
}
return true;
}
bool midi_note_off(unsigned char channel, unsigned char pitch)
{
midi_message message;
message.data[0] = NOTE_ON; // MIDI command byte
message.data[1] = pitch; // MIDI first data byte
message.data[2] = 0; // MIDI second data byte
message.data[3] = 0; // Unused parameter
MMRESULT flag = midiOutShortMsg(current_midi_out_device_handler, message.word);
if (flag != MMSYSERR_NOERROR)
{
std::cout << "note_off(): MIDI output is not open." << std::endl;
return false;
}
return true;
}
void midi_all_notes_off()
{
midiOutReset(current_midi_out_device_handler);
}
// below is untested
typedef union
{
unsigned long word;
unsigned char data[8];
} midi_sysex_message;
std::string __get_midiOutPrepareHeader_error_message(UINT err)
{
switch (err)
{
case MIDIERR_NOTREADY: return "MIDIERR_NOTREADY"; break;
case MIDIERR_UNPREPARED : return "MIDIERR_UNPREPARED"; break;
case MMSYSERR_INVALHANDLE: return "MMSYSERR_INVALHANDLE"; break;
case MMSYSERR_INVALPARAM: return "MIDIERR_NOTREADY"; break;
default: break;
}
std::stringstream ss;
ss << "(unknown error code " << err << ")";
return ss.str();
}
bool midi_sysex_send_message(char device_id, char command_format, char command, char data)
{
if (device_id == 0xF7
|| command_format == 0xF7
|| command == 0xF7
|| data == 0xF7
)
{
std::cout
<< "[" << __FILE__ << " : " << __FUNCTION__ << "] end message byte (0xF7) within the message. Not sending.]"
<< std::endl;
return false;
}
// help here:
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd798474%28v=vs.85%29.aspx
// and here:
// http://web.tiscalinet.it/giordy/midi-tech/lowmidi.htm
MIDIHDR header;
//char sysEx[] = {0xF0, 0x7F, 0x7F, 0x04, 0x01, 0x7F, 0x7F, 0xF7}; //< WAS, but this caused a narrowing error
//unsigned char sysEx[] = {0xF0, 0x7F, 0x7F, 0x04, 0x01, 0x7F, 0x7F, 0xF7};
/* Store pointer in MIDIHDR */
// header.lpData = (LPBYTE)&sysEx[0];
/* Store its size in the MIDIHDR */
//header.dwBufferLength = sizeof(sysEx);
/* Flags must be set to 0 */
//header.dwFlags = 0;
UINT err = midiOutPrepareHeader(current_midi_out_device_handler, &header, sizeof(MIDIHDR));
if (err)
{
std::cout
<< "[" << __FILE__ << " : " << __FUNCTION__ << "] could not prepare header for the midi message."
<< " -- " << __get_midiOutPrepareHeader_error_message(err) << std::endl;
return false;
}
midi_sysex_message message;
message.data[0] = SYSTEM_MESSAGE; // MIDI command byte
message.data[1] = 0x7F; // MIDI start message byte
message.data[2] = device_id;
message.data[3] = 0x02;
message.data[4] = command_format;
message.data[5] = command;
message.data[6] = data;
message.data[7] = 0xF7; // MIDI end message byte
// ok, this function needs to check that the correct paramaters are being sent out.
// right now, it's just a complete guess! the NULL param should be something else
MMRESULT flag = midiOutLongMsg(current_midi_out_device_handler, &header, message.word);
if (flag != MMSYSERR_NOERROR)
{
std::cout << __FUNCTION__ << ": MIDI output is not open." << std::endl;
return false;
}
// yuck, a busy wait
while (midiOutUnprepareHeader(current_midi_out_device_handler, &header, sizeof(MIDIHDR)) == MIDIERR_STILLPLAYING)
{
/* Should put a delay in here rather than a busy-wait */
}
return true;
}
/*
// example program
void main()
{
init_midi();
for (unsigned i=0; i<midi_out_device.size(); i++)
std::cout << midi_out_device[i]->device_port_num << ": " << midi_out_device[i]->name << std::endl;
if (!midi_out_device.empty()) { open_midi_device(midi_out_device[0]); }
midi_note_on(0, 60, 127);
}
*/
| 25.097633 | 120 | 0.664623 | [
"vector"
] |
e9bae3616165c945adb96a2020b125a58eb5e571 | 26,699 | cc | C++ | examples/peerconnection/mediasoup_client/peer_connection_client.cc | chensongpoixs/cwebrtc | 3cc02facc428e9ff21650ff6ffb92370c26dd91e | [
"BSD-3-Clause"
] | null | null | null | examples/peerconnection/mediasoup_client/peer_connection_client.cc | chensongpoixs/cwebrtc | 3cc02facc428e9ff21650ff6ffb92370c26dd91e | [
"BSD-3-Clause"
] | null | null | null | examples/peerconnection/mediasoup_client/peer_connection_client.cc | chensongpoixs/cwebrtc | 3cc02facc428e9ff21650ff6ffb92370c26dd91e | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2012 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "examples/peerconnection/mediasoup_client/peer_connection_client.h"
#include "examples/peerconnection/mediasoup_client/defaults.h"
#include "rtc_base/checks.h"
#include "rtc_base/logging.h"
#include "rtc_base/net_helpers.h"
#include <iostream>
#include <thread>
#ifdef WIN32
#include "rtc_base/win32_socket_server.h"
#endif
#include "rtc_base/strings/json.h"
namespace {
// This is our magical hangup signal.
const char kByeMessage[] = "BYE";
// Delay between server connection retries, in milliseconds
const int kReconnectDelay = 2000;
rtc::AsyncSocket* CreateClientSocket(int family) {
#ifdef WIN32
rtc::Win32Socket* sock = new rtc::Win32Socket();
sock->CreateT(family, SOCK_STREAM);
return sock;
#elif defined(WEBRTC_POSIX)
rtc::Thread* thread = rtc::Thread::Current();
RTC_DCHECK(thread != NULL);
return thread->socketserver()->CreateAsyncSocket(family, SOCK_STREAM);
#else
#error Platform not supported.
#endif
}
} // namespace
PeerConnectionClient::PeerConnectionClient()
: callback_(NULL), resolver_(NULL), state_(NOT_CONNECTED), my_id_(-1),m_websocket_protoo_id(7583332) {}
PeerConnectionClient::~PeerConnectionClient() {}
void PeerConnectionClient::InitSocketSignals() {
RTC_DCHECK(control_socket_.get() != NULL);
// RTC_DCHECK(hanging_get_.get() != NULL);
control_socket_->SignalCloseEvent.connect(this,
&PeerConnectionClient::OnClose);
// hanging_get_->SignalCloseEvent.connect(this, &PeerConnectionClient::OnClose);
control_socket_->SignalConnectEvent.connect(this,
&PeerConnectionClient::OnConnect);
control_socket_->SignalWriteEvent.connect(this, &PeerConnectionClient::OnWrite);
// hanging_get_->SignalConnectEvent.connect(
// this, &PeerConnectionClient::OnHangingGetConnect);
control_socket_->SignalReadEvent.connect(this, &PeerConnectionClient::OnRead);
// hanging_get_->SignalReadEvent.connect(
// this, &PeerConnectionClient::OnHangingGetRead);
}
int PeerConnectionClient::id() const {
return my_id_;
}
bool PeerConnectionClient::is_connected() const {
return my_id_ != -1;
}
const Peers& PeerConnectionClient::peers() const {
return peers_;
}
void PeerConnectionClient::RegisterObserver(
PeerConnectionClientObserver* callback) {
RTC_DCHECK(!callback_);
callback_ = callback;
}
void PeerConnectionClient::Connect(const std::string& server,
int port,
const std::string& client_name) {
RTC_DCHECK(!server.empty());
RTC_DCHECK(!client_name.empty());
if (state_ != NOT_CONNECTED) {
RTC_LOG(WARNING)
<< "The client must not be connected before you can call Connect()";
callback_->OnServerConnectionFailure();
return;
}
if (server.empty() || client_name.empty()) {
callback_->OnServerConnectionFailure();
return;
}
if (port <= 0)
port = kDefaultServerPort;
server_address_.SetIP(server);
server_address_.SetPort(port);
client_name_ = client_name;
/*
if (server_address_.IsUnresolvedIP()) {
state_ = RESOLVING;
resolver_ = new rtc::AsyncResolver();
resolver_->SignalDone.connect(this, &PeerConnectionClient::OnResolveResult);
resolver_->Start(server_address_);
} else*/
{
DoConnect();
}
}
void PeerConnectionClient::OnResolveResult(
rtc::AsyncResolverInterface* resolver) {
if (resolver_->GetError() != 0) {
callback_->OnServerConnectionFailure();
resolver_->Destroy(false);
resolver_ = NULL;
state_ = NOT_CONNECTED;
} else {
server_address_ = resolver_->address();
DoConnect();
}
}
void PeerConnectionClient::DoConnect() {
control_socket_.reset(CreateClientSocket(server_address_.ipaddr().family()));
// hanging_get_.reset(CreateClientSocket(server_address_.ipaddr().family()));
InitSocketSignals();
//char buffer[1024] = {0};
//sprintf(buffer, "[%s]", std::to_string(std::this_thread::get_id()));
// RTC_LOG(INFO) << __FUNCTION__ << " start , thread_id = " << buffer;
RTC_LOG(INFO) << "connect websocket id = " << std::this_thread::get_id();
RTC_LOG(INFO)<< "[INFO]" << __FUNCTION__ << ", start thread_id = " << std::this_thread::get_id();
/*
GET /?roomId=chensong&peerId=xiqhlyrn HTTP/1.1
Host: 127.0.0.1:9000
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 Edg/95.0.1020.44
Upgrade: websocket
Origin: https://169.254.119.31:3000
Sec-WebSocket-Version: 13
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
Sec-WebSocket-Key: sloDVaAu6/ye7AgZlX1BJw==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Protocol: protoo
*/
/* char buffer[1024];
snprintf(buffer, sizeof(buffer), "GET /sign_in?%s HTTP/1.0\r\n\r\n",
client_name_.c_str());*/
onconnect_data_.clear();
char line[1024] = {0};
snprintf(line, 1024, "GET /%s HTTP/1.1\r\n", "/?roomId=chensong&peerId=xiqhlyrn");
onconnect_data_ = line;
snprintf(line, 1024, "Host: %s:%d\r\n", server_address_.hostname().c_str(), server_address_.ip());
onconnect_data_ += line;
static const char * user_agent = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36\r\n";
onconnect_data_ += user_agent;
snprintf(line, 1024, "Upgrade: websocket\r\n");
onconnect_data_ += line;
snprintf(line, 1024, "Connection: Upgrade\r\n");
onconnect_data_ += line;
snprintf(line, 1024, "Origin: http://%s:%u\r\n", server_address_.hostname().c_str(), server_address_.ip());
onconnect_data_ += line;
snprintf(line, 1024, "Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n");
onconnect_data_ += line;
snprintf(line, 1024, "Sec-WebSocket-Version: 13\r\n");
onconnect_data_ += line;
static const char * websocketproto = "Sec-WebSocket-Protocol: protoo\r\n";
onconnect_data_ += websocketproto;
onconnect_data_ += "\r\n";
bool ret = ConnectControlSocket();
// RTC_LOG(INFO) << __FUNCTION__ << " connect end !@!! , thread_id = " << buffer;
RTC_LOG(INFO) << "[INFO]" << __FUNCTION__ << ", end thread_id = " << std::this_thread::get_id();
if (ret)
{
state_ = SIGNING_IN;
}
if (!ret) {
callback_->OnServerConnectionFailure();
}
}
bool PeerConnectionClient::SendToPeer(int peer_id, const std::string& message) {
if (state_ != CONNECTED)
return false;
RTC_DCHECK(is_connected());
RTC_DCHECK(control_socket_->GetState() == rtc::Socket::CS_CLOSED);
if (!is_connected() || peer_id == -1)
return false;
char headers[1024];
snprintf(headers, sizeof(headers),
"POST /message?peer_id=%i&to=%i HTTP/1.0\r\n"
"Content-Length: %zu\r\n"
"Content-Type: text/plain\r\n"
"\r\n",
my_id_, peer_id, message.length());
onconnect_data_ = headers;
onconnect_data_ += message;
return ConnectControlSocket();
}
bool PeerConnectionClient::SendHangUp(int peer_id) {
return SendToPeer(peer_id, kByeMessage);
}
bool PeerConnectionClient::IsSendingMessage() {
return state_ == CONNECTED &&
control_socket_->GetState() != rtc::Socket::CS_CLOSED;
}
bool PeerConnectionClient::SignOut() {
if (state_ == NOT_CONNECTED || state_ == SIGNING_OUT)
return true;
/*if (hanging_get_->GetState() != rtc::Socket::CS_CLOSED)
hanging_get_->Close();*/
if (control_socket_->GetState() == rtc::Socket::CS_CLOSED) {
state_ = SIGNING_OUT;
if (my_id_ != -1) {
char buffer[1024];
snprintf(buffer, sizeof(buffer),
"GET /sign_out?peer_id=%i HTTP/1.0\r\n\r\n", my_id_);
onconnect_data_ = buffer;
return ConnectControlSocket();
} else {
// Can occur if the app is closed before we finish connecting.
return true;
}
} else {
state_ = SIGNING_OUT_WAITING;
}
return true;
}
void PeerConnectionClient::Close()
{
control_socket_->Close();
// hanging_get_->Close();
onconnect_data_.clear();
peers_.clear();
if (resolver_ != NULL) {
resolver_->Destroy(false);
resolver_ = NULL;
}
my_id_ = -1;
state_ = NOT_CONNECTED;
}
bool PeerConnectionClient::ConnectControlSocket() {
RTC_DCHECK(control_socket_->GetState() == rtc::Socket::CS_CLOSED);
int err = control_socket_->Connect(server_address_);
if (err == SOCKET_ERROR) {
Close();
return false;
}
return true;
}
void PeerConnectionClient::OnConnect(rtc::AsyncSocket* socket)
{
/*char buffer[1024] = {0};
sprintf(buffer, "%p", std::this_thread::get_id());
RTC_LOG(INFO) << __FUNCTION__ << ", thread_id = " << buffer; */
RTC_LOG(INFO) << "[INFO]" << __FUNCTION__ << ", start thread_id = " << std::this_thread::get_id();
RTC_LOG(INFO) << __FUNCTION__ << ", start !!! thread_id = " << std::this_thread::get_id();
RTC_DCHECK(!onconnect_data_.empty());
state_ = CONNECT_HANDSHAKE;
size_t sent = socket->Send(onconnect_data_.c_str(), onconnect_data_.length());
RTC_DCHECK(sent == onconnect_data_.length());
onconnect_data_.clear();
RTC_LOG(INFO) << __FUNCTION__ << ", end !!!";
}
void PeerConnectionClient::OnWrite(rtc::AsyncSocket* socket)
{
RTC_LOG(INFO)<< "[INFO]" << __FUNCTION__ << ", start thread_id = " << std::this_thread::get_id();
//char buffer[1024] = {0};
//sprintf(buffer, "%p", std::this_thread::get_id());
//RTC_LOG(INFO) << __FUNCTION__ << ", thread_id = " << buffer;
RTC_LOG(INFO) << __FUNCTION__ << ", start !!! thread_id = " << std::this_thread::get_id();
RTC_LOG(INFO) << "write data ^_^ !!!";
//control_socket_->SignalWriteEvent.connect(this, &PeerConnectionClient::OnWrite);
}
void PeerConnectionClient::OnHangingGetConnect(rtc::AsyncSocket* socket) {
char buffer[1024];
snprintf(buffer, sizeof(buffer), "GET /wait?peer_id=%i HTTP/1.0\r\n\r\n",
my_id_);
int len = static_cast<int>(strlen(buffer));
int sent = socket->Send(buffer, len);
RTC_DCHECK(sent == len);
}
void PeerConnectionClient::OnMessageFromPeer(int peer_id,
const std::string& message) {
if (message.length() == (sizeof(kByeMessage) - 1) &&
message.compare(kByeMessage) == 0) {
callback_->OnPeerDisconnected(peer_id);
} else {
callback_->OnMessageFromPeer(peer_id, message);
}
}
bool PeerConnectionClient::GetHeaderValue(const std::string& data,
size_t eoh,
const char* header_pattern,
size_t* value) {
RTC_DCHECK(value != NULL);
size_t found = data.find(header_pattern);
if (found != std::string::npos && found < eoh) {
*value = atoi(&data[found + strlen(header_pattern)]);
return true;
}
return false;
}
bool PeerConnectionClient::GetHeaderValue(const std::string& data,
size_t eoh,
const char* header_pattern,
std::string* value) {
RTC_DCHECK(value != NULL);
size_t found = data.find(header_pattern);
if (found != std::string::npos && found < eoh) {
size_t begin = found + strlen(header_pattern);
size_t end = data.find("\r\n", begin);
if (end == std::string::npos)
end = eoh;
value->assign(data.substr(begin, end - begin));
return true;
}
return false;
}
bool PeerConnectionClient::ReadIntoBuffer(rtc::AsyncSocket* socket,
std::string* data,
size_t* content_length) {
char buffer[0xffff];
do {
int bytes = socket->Recv(buffer, sizeof(buffer), nullptr);
if (bytes <= 0)
break;
data->append(buffer, bytes);
} while (true);
return data->length() > 0 ? true : false;
/////////////////////////////////////////////////////////////////////////////////////////
bool ret = false;
size_t i = data->find("\r\n\r\n");
if (i != std::string::npos) {
RTC_LOG(INFO) << "Headers received";
if (GetHeaderValue(*data, i, "\r\nContent-Length: ", content_length)) {
size_t total_response_size = (i + 4) + *content_length;
if (data->length() >= total_response_size) {
ret = true;
std::string should_close;
const char kConnection[] = "\r\nConnection: ";
if (GetHeaderValue(*data, i, kConnection, &should_close) &&
should_close.compare("close") == 0) {
socket->Close();
// Since we closed the socket, there was no notification delivered
// to us. Compensate by letting ourselves know.
OnClose(socket, 0);
}
} else {
// We haven't received everything. Just continue to accept data.
}
} else {
RTC_LOG(LS_ERROR) << "No content length field specified by the server.";
}
}
return ret;
}
void PeerConnectionClient::OnRead(rtc::AsyncSocket* socket)
{
RTC_LOG(INFO) << "[INFO]" << __FUNCTION__ << ", start thread_id = " << std::this_thread::get_id();
/*char buffer[1024] = {0};
sprintf(buffer, "%p", std::this_thread::get_id());
RTC_LOG(INFO) << __FUNCTION__ << ", thread_id = " << buffer;*/
size_t content_length = 0;
if (ReadIntoBuffer(socket, &control_data_, &content_length))
{
// TODO@chensong 2021-12-31 websocket 连接进行handshake 交换
int status = 0;
if (state_ == CONNECT_HANDSHAKE)
{
// 判断服务器校验是否成功
if (sscanf(control_data_.c_str(), "HTTP/1.1 %d", &status) != 1 || status != 101)
{
state_ = SIGNING_OUT_WAITING;
RTC_LOG(INFO) << "websocket protoo handshake failed !!! message = " << control_data_;
}
else
{
state_ = CONNECTED; // 连接成功哈
RTC_LOG(INFO) << "websocket protoo handshake sucesss !!!";
}
//json data = {
// "request":true,
// "id":7583332, //
// "method":"getRouterRtpCapabilities", //方法
// "data":{
//}
//};
Json::StyledWriter writer;
Json::Value jmessage;
jmessage["request"] = true;
jmessage["id"] = ++m_websocket_protoo_id;
jmessage["method"] = "getRouterRtpCapabilities";
jmessage["data"] = Json::objectValue;
//SendMessage(writer.write(jmessage));
//
std::string message = writer.write(jmessage);
RTC_LOG(INFO) << "[INFO]" << "send message = " << message << " !!!";
sendData(wsheader_type::TEXT_FRAME, (const uint8_t *)message.c_str(), message.length());
// socket->Send(message.c_str(), message.length());
control_data_.clear();
}
else if (state_ == CONNECTED)
{
// 正常业务的处理
RTC_LOG(INFO) << "[INFO]" << "recv message = " << control_data_ << " !!!";
// m_recv_data.insert(m_recv_data.end(), (const uint8_t *)control_data_.c_str());
for (const char &value : control_data_)
{
m_recv_data.push_back(value);
}
wsheader_type ws;
if (m_recv_data.size() < 2) { return; /* Need at least 2 */ }
const uint8_t * data = (uint8_t *) &m_recv_data[0]; // peek, but don't consume
ws.fin = (data[0] & 0x80) == 0x80;
ws.opcode = (wsheader_type::opcode_type) (data[0] & 0x0f);
ws.mask = (data[1] & 0x80) == 0x80;
ws.N0 = (data[1] & 0x7f);
ws.header_size = 2 + (ws.N0 == 126? 2 : 0) + (ws.N0 == 127? 8 : 0) + (ws.mask? 4 : 0);
if (m_recv_data.size() < ws.header_size)
{
return; /* Need: ws.header_size - rxbuf.size() */
}
int i = 0;
if (ws.N0 < 126) {
ws.N = ws.N0;
i = 2;
}
else if (ws.N0 == 126) {
ws.N = 0;
ws.N |= ((uint64_t) data[2]) << 8;
ws.N |= ((uint64_t) data[3]) << 0;
i = 4;
}
else if (ws.N0 == 127) {
ws.N = 0;
ws.N |= ((uint64_t) data[2]) << 56;
ws.N |= ((uint64_t) data[3]) << 48;
ws.N |= ((uint64_t) data[4]) << 40;
ws.N |= ((uint64_t) data[5]) << 32;
ws.N |= ((uint64_t) data[6]) << 24;
ws.N |= ((uint64_t) data[7]) << 16;
ws.N |= ((uint64_t) data[8]) << 8;
ws.N |= ((uint64_t) data[9]) << 0;
i = 10;
}
if (ws.mask) {
ws.masking_key[0] = ((uint8_t) data[i+0]) << 0;
ws.masking_key[1] = ((uint8_t) data[i+1]) << 0;
ws.masking_key[2] = ((uint8_t) data[i+2]) << 0;
ws.masking_key[3] = ((uint8_t) data[i+3]) << 0;
}
else {
ws.masking_key[0] = 0;
ws.masking_key[1] = 0;
ws.masking_key[2] = 0;
ws.masking_key[3] = 0;
}
if (m_recv_data.size() < ws.header_size+ws.N)
{
return; /* Need: ws.header_size+ws.N - rxbuf.size() */
}
// We got a whole message, now do something with it:
if (
ws.opcode == wsheader_type::TEXT_FRAME
|| ws.opcode == wsheader_type::BINARY_FRAME
|| ws.opcode == wsheader_type::CONTINUATION
) {
if (ws.mask)
{
for (size_t i = 0; i != ws.N; ++i)
{
m_recv_data[i+ws.header_size] ^= ws.masking_key[i&0x3];
}
}
receivedData.insert(receivedData.end(), m_recv_data.begin()+ws.header_size, m_recv_data.begin()+ws.header_size+(size_t)ws.N);// just feed
if (ws.fin)
{
if (ws.opcode == wsheader_type::TEXT_FRAME)
{
std::string stringMessage(receivedData.begin(), receivedData.end());
//callable.OnMessage(stringMessage);
RTC_LOG(INFO) << "[INFO] recv stringMessage = " <<stringMessage;
}
else
{
RTC_LOG(INFO) << "[INFO] recv receivedData = " <<receivedData.data();
// callable.OnMessage(receivedData);
}
receivedData.erase(receivedData.begin(), receivedData.end());
std::vector<uint8_t> ().swap(receivedData);// free memory
}
}
else if (ws.opcode == wsheader_type::PING)
{
if (ws.mask)
{
for (size_t i = 0; i != ws.N; ++i)
{
m_recv_data[i+ws.header_size] ^= ws.masking_key[i&0x3];
}
}
std::string data(m_recv_data.begin()+ws.header_size, m_recv_data.begin()+ws.header_size+(size_t)ws.N);
sendData(wsheader_type::PONG,(uint8_t*)data.c_str(),data.length());
}
else if (ws.opcode == wsheader_type::PONG)
{
}
else if (ws.opcode == wsheader_type::CLOSE)
{
// close();
}
else
{
fprintf(stderr, "ERROR: Got unexpected WebSocket message.\n");
// close();
}
m_recv_data.erase(m_recv_data.begin(), m_recv_data.begin() + ws.header_size+(size_t)ws.N);
}
else
{
// warring
}
control_data_.clear();
return;
////////////////////////////////////////////////////////////////////////////////////////////
size_t peer_id = 0, eoh = 0;
bool ok =
ParseServerResponse(control_data_, content_length, &peer_id, &eoh);
if (ok) {
if (my_id_ == -1) {
// First response. Let's store our server assigned ID.
RTC_DCHECK(state_ == SIGNING_IN);
my_id_ = static_cast<int>(peer_id);
RTC_DCHECK(my_id_ != -1);
// The body of the response will be a list of already connected peers.
if (content_length) {
size_t pos = eoh + 4;
while (pos < control_data_.size()) {
size_t eol = control_data_.find('\n', pos);
if (eol == std::string::npos)
break;
int id = 0;
std::string name;
bool connected;
if (ParseEntry(control_data_.substr(pos, eol - pos), &name, &id,
&connected) &&
id != my_id_) {
peers_[id] = name;
callback_->OnPeerConnected(id, name);
}
pos = eol + 1;
}
}
RTC_DCHECK(is_connected());
callback_->OnSignedIn();
} else if (state_ == SIGNING_OUT) {
Close();
callback_->OnDisconnected();
} else if (state_ == SIGNING_OUT_WAITING) {
SignOut();
}
}
control_data_.clear();
/* if (state_ == SIGNING_IN) {
RTC_DCHECK(hanging_get_->GetState() == rtc::Socket::CS_CLOSED);
state_ = CONNECTED;
hanging_get_->Connect(server_address_);
}*/
}
}
void PeerConnectionClient::sendData(wsheader_type::opcode_type type,const uint8_t* message_begin, size_t message_len)
{
// TODO:
// Masking key should (must) be derived from a high quality random
// number generator, to mitigate attacks on non-WebSocket friendly
// middleware:
std::vector<uint8_t> txbuf;
const uint8_t masking_key[4] = { 0x12, 0x34, 0x56, 0x78 };
// TODO: consider acquiring a lock on txbuf...
std::vector<uint8_t> header;
header.assign(2 + (message_len >= 126 ? 2 : 0) + (message_len >= 65536 ? 6 : 0) + (true ? 4 : 0), 0);
header[0] = 0x80 | type;
if (false) {}
else if (message_len < 126) {
header[1] = (message_len & 0xff) | (true ? 0x80 : 0);
if (true)
{
header[2] = masking_key[0];
header[3] = masking_key[1];
header[4] = masking_key[2];
header[5] = masking_key[3];
}
}
else if (message_len < 65536) {
header[1] = 126 | (true ? 0x80 : 0);
header[2] = (message_len >> 8) & 0xff;
header[3] = (message_len >> 0) & 0xff;
if (true) {
header[4] = masking_key[0];
header[5] = masking_key[1];
header[6] = masking_key[2];
header[7] = masking_key[3];
}
}
else { // TODO: run coverage testing here
header[1] = 127 | (true ? 0x80 : 0);
header[2] = (message_len >> 56) & 0xff;
header[3] = (message_len >> 48) & 0xff;
header[4] = (message_len >> 40) & 0xff;
header[5] = (message_len >> 32) & 0xff;
header[6] = (message_len >> 24) & 0xff;
header[7] = (message_len >> 16) & 0xff;
header[8] = (message_len >> 8) & 0xff;
header[9] = (message_len >> 0) & 0xff;
if (true) {
header[10] = masking_key[0];
header[11] = masking_key[1];
header[12] = masking_key[2];
header[13] = masking_key[3];
}
}
// N.B. - txbuf will keep growing until it can be transmitted over the socket:
txbuf.insert(txbuf.end(), header.begin(), header.end());
//write data
size_t offset = txbuf.size();
txbuf.resize(offset+message_len);
for (size_t i = 0; i< message_len; ++i)
{
txbuf[offset+i] = message_begin[i];
}
if (true) {
size_t message_offset = txbuf.size() - message_len;
for (size_t i = 0; i != message_len; ++i) {
txbuf[message_offset + i] ^= masking_key[i & 0x3];
}
}
if (txbuf.size())
{
control_socket_->Send(&txbuf[0], txbuf.size());
}
}
void PeerConnectionClient::OnHangingGetRead(rtc::AsyncSocket* socket) {
RTC_LOG(INFO) << __FUNCTION__;
size_t content_length = 0;
if (ReadIntoBuffer(socket, ¬ification_data_, &content_length)) {
size_t peer_id = 0, eoh = 0;
bool ok =
ParseServerResponse(notification_data_, content_length, &peer_id, &eoh);
if (ok) {
// Store the position where the body begins.
size_t pos = eoh + 4;
if (my_id_ == static_cast<int>(peer_id)) {
// A notification about a new member or a member that just
// disconnected.
int id = 0;
std::string name;
bool connected = false;
if (ParseEntry(notification_data_.substr(pos), &name, &id,
&connected)) {
if (connected) {
peers_[id] = name;
callback_->OnPeerConnected(id, name);
} else {
peers_.erase(id);
callback_->OnPeerDisconnected(id);
}
}
} else {
OnMessageFromPeer(static_cast<int>(peer_id),
notification_data_.substr(pos));
}
}
notification_data_.clear();
}
//if (hanging_get_->GetState() == rtc::Socket::CS_CLOSED &&
// state_ == CONNECTED) {
// hanging_get_->Connect(server_address_);
//}
}
bool PeerConnectionClient::ParseEntry(const std::string& entry,
std::string* name,
int* id,
bool* connected) {
RTC_DCHECK(name != NULL);
RTC_DCHECK(id != NULL);
RTC_DCHECK(connected != NULL);
RTC_DCHECK(!entry.empty());
*connected = false;
size_t separator = entry.find(',');
if (separator != std::string::npos) {
*id = atoi(&entry[separator + 1]);
name->assign(entry.substr(0, separator));
separator = entry.find(',', separator + 1);
if (separator != std::string::npos) {
*connected = atoi(&entry[separator + 1]) ? true : false;
}
}
return !name->empty();
}
int PeerConnectionClient::GetResponseStatus(const std::string& response) {
int status = -1;
size_t pos = response.find(' ');
if (pos != std::string::npos)
status = atoi(&response[pos + 1]);
return status;
}
bool PeerConnectionClient::ParseServerResponse(const std::string& response,
size_t content_length,
size_t* peer_id,
size_t* eoh) {
int status = GetResponseStatus(response.c_str());
if (status != 200) {
RTC_LOG(LS_ERROR) << "Received error from server";
Close();
callback_->OnDisconnected();
return false;
}
*eoh = response.find("\r\n\r\n");
RTC_DCHECK(*eoh != std::string::npos);
if (*eoh == std::string::npos)
return false;
*peer_id = -1;
// See comment in peer_channel.cc for why we use the Pragma header and
// not e.g. "X-Peer-Id".
GetHeaderValue(response, *eoh, "\r\nPragma: ", peer_id);
return true;
}
void PeerConnectionClient::OnClose(rtc::AsyncSocket* socket, int err) {
RTC_LOG(INFO) << __FUNCTION__;
socket->Close();
#ifdef WIN32
if (err != WSAECONNREFUSED) {
#else
if (err != ECONNREFUSED) {
#endif
/*if (socket == hanging_get_.get()) {
if (state_ == CONNECTED) {
hanging_get_->Close();
hanging_get_->Connect(server_address_);
}
} else*/ {
callback_->OnMessageSent(err);
}
} else {
if (socket == control_socket_.get()) {
RTC_LOG(WARNING) << "Connection refused; retrying in 2 seconds";
rtc::Thread::Current()->PostDelayed(RTC_FROM_HERE, kReconnectDelay, this,
0);
} else {
Close();
callback_->OnDisconnected();
}
}
}
void PeerConnectionClient::OnMessage(rtc::Message* msg) {
// ignore msg; there is currently only one supported message ("retry")
DoConnect();
}
| 31.300117 | 168 | 0.607251 | [
"vector"
] |
e9c13458a085e2767f07f91ae443253fe6d974a1 | 2,621 | cpp | C++ | service/simulator/src/common/request_model.cpp | jonghenhan/iotivity | 7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31 | [
"Apache-2.0"
] | 301 | 2015-01-20T16:11:32.000Z | 2021-11-25T04:29:36.000Z | service/simulator/src/common/request_model.cpp | jonghenhan/iotivity | 7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31 | [
"Apache-2.0"
] | 21 | 2019-10-02T08:31:36.000Z | 2021-12-09T21:46:49.000Z | service/simulator/src/common/request_model.cpp | jonghenhan/iotivity | 7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31 | [
"Apache-2.0"
] | 233 | 2015-01-26T03:41:59.000Z | 2022-03-18T23:54:04.000Z | /******************************************************************
*
* Copyright 2015 Samsung Electronics All Rights Reserved.
*
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************/
#include "request_model.h"
#include "experimental/logger.h"
RequestModel::RequestModel(const std::string &type)
: m_type(type) {}
std::string RequestModel::getType() const
{
return m_type;
}
SupportedQueryParams RequestModel::getQueryParams()
{
return m_queryParams;
}
std::vector<std::string> RequestModel::getQueryParams(const std::string &key)
{
if (m_queryParams.end() != m_queryParams.find(key))
{
return m_queryParams[key];
}
return std::vector<std::string>();
}
std::shared_ptr<SimulatorResourceModelSchema> RequestModel::getRequestRepSchema()
{
return m_repSchema;
}
ResponseModelSP RequestModel::getResponseModel(int code)
{
if (m_responseList.end() != m_responseList.find(code))
{
return m_responseList[code];
}
return nullptr;
}
void RequestModel::setType(const std::string &type)
{
m_type = type;
}
void RequestModel::setQueryParams(const std::string &key,
const std::vector<std::string> &values)
{
if (0 != values.size())
{
m_queryParams[key] = values;
}
}
void RequestModel::addQueryParam(const std::string &key, const std::string &value)
{
m_queryParams[key].push_back(value);
}
void RequestModel::setResponseModel(int code, ResponseModelSP &responseModel)
{
if (responseModel)
{
m_responseList[code] = responseModel;
}
}
void RequestModel::setRequestBodyModel(const std::shared_ptr<SimulatorResourceModelSchema>
&repSchema)
{
m_repSchema = repSchema;
}
SimulatorResult RequestModel::validateResponse(int code, const SimulatorResourceModel &resModel)
{
if (m_responseList.end() == m_responseList.find(code))
{
return SIMULATOR_INVALID_RESPONSE_CODE;
}
return m_responseList[code]->verifyResponse(resModel);
}
| 24.961905 | 96 | 0.657764 | [
"vector"
] |
e9c3820beef95c70750d1e4e4fd1fe536486a107 | 2,850 | cc | C++ | ui/gfx/geometry/size_unittest.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"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/gfx/geometry/size_unittest.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ui/gfx/geometry/size_unittest.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/geometry/size.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gfx {
TEST(SizeTest, SetToMinMax) {
Size a;
a = Size(3, 5);
EXPECT_EQ(Size(3, 5).ToString(), a.ToString());
a.SetToMax(Size(2, 4));
EXPECT_EQ(Size(3, 5).ToString(), a.ToString());
a.SetToMax(Size(3, 5));
EXPECT_EQ(Size(3, 5).ToString(), a.ToString());
a.SetToMax(Size(4, 2));
EXPECT_EQ(Size(4, 5).ToString(), a.ToString());
a.SetToMax(Size(8, 10));
EXPECT_EQ(Size(8, 10).ToString(), a.ToString());
a.SetToMin(Size(9, 11));
EXPECT_EQ(Size(8, 10).ToString(), a.ToString());
a.SetToMin(Size(8, 10));
EXPECT_EQ(Size(8, 10).ToString(), a.ToString());
a.SetToMin(Size(11, 9));
EXPECT_EQ(Size(8, 9).ToString(), a.ToString());
a.SetToMin(Size(7, 11));
EXPECT_EQ(Size(7, 9).ToString(), a.ToString());
a.SetToMin(Size(3, 5));
EXPECT_EQ(Size(3, 5).ToString(), a.ToString());
}
TEST(SizeTest, Enlarge) {
Size test(3, 4);
test.Enlarge(5, -8);
EXPECT_EQ(test, Size(8, -4));
}
TEST(SizeTest, IntegerOverflow) {
int int_max = std::numeric_limits<int>::max();
int int_min = std::numeric_limits<int>::min();
Size max_size(int_max, int_max);
Size min_size(int_min, int_min);
Size test;
test = Size();
test.Enlarge(int_max, int_max);
EXPECT_EQ(test, max_size);
test = Size();
test.Enlarge(int_min, int_min);
EXPECT_EQ(test, min_size);
test = Size(10, 20);
test.Enlarge(int_max, int_max);
EXPECT_EQ(test, max_size);
test = Size(-10, -20);
test.Enlarge(int_min, int_min);
EXPECT_EQ(test, min_size);
}
TEST(SizeTest, OperatorAddSub) {
Size lhs(100, 20);
Size rhs(50, 10);
lhs += rhs;
EXPECT_EQ(Size(150, 30), lhs);
lhs = Size(100, 20);
EXPECT_EQ(Size(150, 30), lhs + rhs);
lhs = Size(100, 20);
lhs -= rhs;
EXPECT_EQ(Size(50, 10), lhs);
lhs = Size(100, 20);
EXPECT_EQ(Size(50, 10), lhs - rhs);
}
TEST(SizeTest, OperatorAddOverflow) {
int int_max = std::numeric_limits<int>::max();
Size lhs(int_max, int_max);
Size rhs(int_max, int_max);
EXPECT_EQ(Size(int_max, int_max), lhs + rhs);
}
TEST(SizeTest, OperatorSubClampAtZero) {
Size lhs(10, 10);
Size rhs(100, 100);
EXPECT_EQ(Size(0, 0), lhs - rhs);
lhs = Size(10, 10);
rhs = Size(100, 100);
lhs -= rhs;
EXPECT_EQ(Size(0, 0), lhs);
}
TEST(SizeTest, OperatorCompare) {
Size lhs(100, 20);
Size rhs(50, 10);
EXPECT_TRUE(lhs != rhs);
EXPECT_FALSE(lhs == rhs);
rhs = Size(100, 20);
EXPECT_TRUE(lhs == rhs);
EXPECT_FALSE(lhs != rhs);
}
TEST(SizeTest, Transpose) {
gfx::Size s(1, 2);
EXPECT_EQ(gfx::Size(2, 1), TransposeSize(s));
s.Transpose();
EXPECT_EQ(gfx::Size(2, 1), s);
}
} // namespace gfx
| 22.8 | 73 | 0.639649 | [
"geometry"
] |
e9cea9f8b5d09feb91d9e8e7df2b9d564aed21c5 | 7,437 | cpp | C++ | src/microservice.cpp | afairon/markov-cpp-playground | cec0e3e27046a8da9b1e51ea93e1caf801dbafda | [
"MIT"
] | null | null | null | src/microservice.cpp | afairon/markov-cpp-playground | cec0e3e27046a8da9b1e51ea93e1caf801dbafda | [
"MIT"
] | null | null | null | src/microservice.cpp | afairon/markov-cpp-playground | cec0e3e27046a8da9b1e51ea93e1caf801dbafda | [
"MIT"
] | null | null | null | #include <iostream>
#include <cpprest/filestream.h>
#include "microservice_controller.hpp"
#include "version.hpp"
#include "utils.hpp"
using namespace web;
using namespace http;
// opHandlers init REST method
void MicroserviceController::opHandlers() {
_listener.support(methods::GET, std::bind(&MicroserviceController::handleGet, this, std::placeholders::_1));
_listener.support(methods::POST, std::bind(&MicroserviceController::handlePost, this, std::placeholders::_1));
_listener.support(methods::PUT, std::bind(&MicroserviceController::handlePut, this, std::placeholders::_1));
_listener.support(methods::DEL, std::bind(&MicroserviceController::handleDelete, this, std::placeholders::_1));
_listener.support(methods::PATCH, std::bind(&MicroserviceController::handlePatch, this, std::placeholders::_1));
_listener.support(methods::HEAD, std::bind(&MicroserviceController::handleHead, this, std::placeholders::_1));
_listener.support(methods::OPTIONS, std::bind(&MicroserviceController::handleOptions, this, std::placeholders::_1));
}
// getExt returns file type
file_type MicroserviceController::getExt(const std::string& file) const {
std::string ext = file.substr(file.find_last_of(".") + 1);
if (ext == "html") {
return HTML;
} else if (ext == "css") {
return CSS;
} else if (ext == "js") {
return JS;
} else if (ext == "jpg" || ext == "jpeg") {
return JPEG;
} else if (ext == "png") {
return PNG;
} else if (ext == "webp") {
return WEBP;
} else if (ext == "ico") {
return ICO;
}
return UNKNOWN;
}
// serveStatic serve static files
void MicroserviceController::serveStatic(const std::string& filepath, const http_request& message) {
auto path = requestPath(message);
std::string uri, file, ext, content_type;
file_type type;
if (path.size() < 2) {
message.reply(status_codes::NotFound);
return;
}
uri = "static";
for (int i = 1; i < path.size(); ++i) {
uri += "/";
uri += path[i];
}
file = path[path.size()-1];
type = getExt(file);
switch (type) {
case HTML:
content_type = "text/html; charset=UTF-8";
break;
case CSS:
content_type = "text/css; charset=UTF-8";
break;
case JS:
content_type = "text/javascript; charset=UTF-8";
break;
case JPEG:
content_type = "image/jpeg";
break;
case PNG:
content_type = "image/png";
break;
case WEBP:
content_type = "image/webp";
break;
default:
content_type = "application/octet-stream";
break;
}
concurrency::streams::fstream::open_istream(U(uri), std::ios::in).then([=](concurrency::streams::istream is) {
message.reply(status_codes::OK, is, content_type).then([=](pplx::task<void> t) {
try {
t.get();
} catch (...) {
message.reply(status_codes::InternalError);
}
});
}).then([=](pplx::task<void> t) {
try {
t.get();
} catch (...) {
message.reply(status_codes::NotFound);
}
});
return;
}
// handleGet handles GET event
void MicroserviceController::handleGet(http_request message) {
auto path = requestPath(message);
if (!path.empty()) {
if (path[0] == "static") {
return serveStatic("static", message);
} else if (path.size() > 1 && path[0] == "api" && path[1] == "generate") {
auto response = json::value::object();
NGram tokens = {StartToken};
for (; tokens.back() != EndToken;) {
NGram::const_iterator begin = tokens.begin() + tokens.size()-1;
NGram::const_iterator last = tokens.begin() + tokens.size();
NGram sub(begin, last);
std::string next = chain->Generate(sub);
tokens.push_back(next);
}
NGram::const_iterator begin = tokens.begin() + 1;
NGram::const_iterator last = tokens.begin() + tokens.size() - 1;
NGram sub(begin, last);
std::string generated = join(sub, " ");
response["next"] = json::value::string(generated);
message.reply(status_codes::OK, response);
return;
}
}
concurrency::streams::fstream::open_istream("static/index.html", std::ios::in).then([=](concurrency::streams::istream is) {
message.reply(status_codes::OK, is, "text/html; charset=UTF-8");
});
}
// handlePost handles POST event
void MicroserviceController::handlePost(http_request message) {
auto path = requestPath(message);
if (!path.empty()) {
// Precict word
if (path.size() > 1 && path[0] == "api" && path[1] == "predict") {
auto response = json::value::object();
auto req = message.extract_json().get();
auto seq = req["seq"].as_string();
std::string next = chain->Generate(split(seq, ' '));
response["next"] = json::value::string("");
if (next.length() > 1 && next != EndToken) {
response["next"] = json::value::string(next);
}
message.reply(status_codes::OK, response);
return;
// Train user-defined model
} else if (path.size() > 1 && path[0] == "api" && path[1] == "train") {
auto response = json::value::object();
auto req = message.extract_json().get();
auto seq = req["seq"].as_string();
chain->Add(split(seq, ' '));
response["OK"] = json::value::boolean(true);
message.reply(status_codes::OK, response);
return;
}
}
message.reply(status_codes::NotImplemented, responseNotImpl(methods::POST));
}
// handlePut handles PUT event
void MicroserviceController::handlePut(http_request message) {
message.reply(status_codes::NotImplemented, responseNotImpl(methods::PUT));
}
// handleDelete handles DELETE event
void MicroserviceController::handleDelete(http_request message) {
message.reply(status_codes::NotImplemented, responseNotImpl(methods::DEL));
}
// handlePatch handles Patch event
void MicroserviceController::handlePatch(http_request message) {
message.reply(status_codes::NotImplemented, responseNotImpl(methods::PATCH));
}
// handleHead handles HEAD event
void MicroserviceController::handleHead(http_request message) {
message.reply(status_codes::NotImplemented, responseNotImpl(methods::HEAD));
}
// handleOptions handles OPTIONS event
void MicroserviceController::handleOptions(http_request message) {
message.reply(status_codes::NotImplemented, responseNotImpl(methods::OPTIONS));
}
// responseNotImpl returns default message when method has not been implemented yet
json::value MicroserviceController::responseNotImpl(const http::method& method) {
auto response = json::value::object();
response["service"] = json::value::string(U("Markov Playground"));
response["version"] = json::value::string(U(version));
response["method"] = json::value::string(U(method));
return response;
}
// setChain assigns Markov chain to controller
void MicroserviceController::setChain(WordPrediction* ch) {
chain = ch;
} | 35.927536 | 127 | 0.606293 | [
"object",
"model"
] |
839c136ab53aa3bbd54c3932dc70389101845e9c | 3,447 | cpp | C++ | test/devices/test_GPS.cpp | perryrob/oxcart | 5c29535be2b813c7caebcfec31a8f934b0c88228 | [
"BSD-4-Clause"
] | 1 | 2017-03-20T20:13:16.000Z | 2017-03-20T20:13:16.000Z | test/devices/test_GPS.cpp | perryrob/oxcart | 5c29535be2b813c7caebcfec31a8f934b0c88228 | [
"BSD-4-Clause"
] | null | null | null | test/devices/test_GPS.cpp | perryrob/oxcart | 5c29535be2b813c7caebcfec31a8f934b0c88228 | [
"BSD-4-Clause"
] | null | null | null | /********************************************************************************
Copyright (c) 2017 Bob Perry / asw204k_AT_yahoo.com
All rights reserved.
Please see license in the project root directory fro more details
*/
#include "oxGPSDbus.h"
#include "devices/GPS.h"
#include <iostream>
#include <cassert>
using namespace std;
static void libgps_dump_state(struct gps_data_t *collect)
{
if (collect->set & ONLINE_SET)
(void)fprintf(stdout, "ONLINE: %lf\n", collect->online);
if (collect->set & TIME_SET)
(void)fprintf(stdout, "TIME: %lf\n", collect->fix.time);
if (collect->set & LATLON_SET)
(void)fprintf(stdout, "LATLON: lat/lon: %lf %lf\n",
collect->fix.latitude, collect->fix.longitude);
if (collect->set & ALTITUDE_SET)
(void)fprintf(stdout, "ALTITUDE: altitude: %lf U: climb: %lf\n",
collect->fix.altitude, collect->fix.climb);
if (collect->set & SPEED_SET)
(void)fprintf(stdout, "SPEED: %lf\n", collect->fix.speed);
if (collect->set & TRACK_SET)
(void)fprintf(stdout, "TRACK: track: %lf\n", collect->fix.track);
if (collect->set & CLIMB_SET)
(void)fprintf(stdout, "CLIMB: climb: %lf\n", collect->fix.climb);
if (collect->set & STATUS_SET)
(void)fprintf(stdout, "STATUS: status: %d\n", collect->status);
if (collect->set & MODE_SET)
(void)fprintf(stdout, "MODE: mode: %d\n", collect->fix.mode);
if (collect->set & DOP_SET)
(void)fprintf(stdout,
"DOP: satellites %d, pdop=%lf, hdop=%lf, vdop=%lf\n",
collect->satellites_used, collect->dop.pdop,
collect->dop.hdop, collect->dop.vdop);
if (collect->set & VERSION_SET)
(void)fprintf(stdout, "VERSION: release=%s rev=%s proto=%d.%d\n",
collect->version.release,
collect->version.rev,
collect->version.proto_major,
collect->version.proto_minor);
if (collect->set & POLICY_SET)
(void)fprintf(stdout,
"POLICY: watcher=%s nmea=%s raw=%d scaled=%s timing=%s, devpath=%s\n",
collect->policy.watcher ? "true" : "false",
collect->policy.nmea ? "true" : "false",
collect->policy.raw,
collect->policy.scaled ? "true" : "false",
collect->policy.timing ? "true" : "false",
collect->policy.devpath);
if (collect->set & SATELLITE_SET) {
int i;
(void)fprintf(stdout, "SKY: satellites in view: %d\n",
collect->satellites_visible);
for (i = 0; i < collect->satellites_visible; i++) {
(void)fprintf(stdout, " %2.2d: %2.2d %3.3d %3.0f %c\n",
collect->skyview[i].PRN,
collect->skyview[i].elevation,
collect->skyview[i].azimuth,
collect->skyview[i].ss,
collect->skyview[i].used ? 'Y' : 'N');
}
}
if (collect->set & DEVICE_SET)
(void)fprintf(stdout, "DEVICE: Device is '%s', driver is '%s'\n",
collect->dev.path, collect->dev.driver);
if (collect->set & DEVICELIST_SET) {
int i;
(void)fprintf(stdout, "DEVICELIST:%d devices:\n",
collect->devices.ndevices);
for (i = 0; i < collect->devices.ndevices; i++) {
(void)fprintf(stdout, "%d: path='%s' driver='%s'\n",
collect->devices.ndevices,
collect->devices.list[i].path,
collect->devices.list[i].driver);
}
}
}
int main(int argc, char *argv[] ) {
OxGPSDbus bus;
GPS gps;
gps.NMEA();
bus.add_device( &gps );
bus.run();
b::this_thread::sleep(b::posix_time::milliseconds(1000));
bus.stop();
libgps_dump_state( gps.get_data() );
return 0;
}
| 31.916667 | 81 | 0.615318 | [
"3d"
] |
839d108e8262a105c90352ebdd672388ffd600ad | 548 | hpp | C++ | src/emulator/gpu/GPUTypes.hpp | m4tx/nsfgbe | 7e19319a50c0e8554ff1df2857bc8debb15e9183 | [
"MIT"
] | null | null | null | src/emulator/gpu/GPUTypes.hpp | m4tx/nsfgbe | 7e19319a50c0e8554ff1df2857bc8debb15e9183 | [
"MIT"
] | null | null | null | src/emulator/gpu/GPUTypes.hpp | m4tx/nsfgbe | 7e19319a50c0e8554ff1df2857bc8debb15e9183 | [
"MIT"
] | null | null | null | #ifndef GAMEBOY_EMULATOR_GPUTYPES_H
#define GAMEBOY_EMULATOR_GPUTYPES_H
#include <Types.hpp>
namespace nsfgbe {
enum class GPUModeId : Byte {
HBLANK = 0,
VBLANK = 1,
OAM_SEARCH = 2,
PIXEL_TRANSFER = 3,
};
enum class PixelSource : Byte {
/** Background/window pixel (using background palette) */
BG,
/** Object pixel (using sprite palette 0) */
OB0,
/** Object pixel (using sprite palette 1) */
OB1,
};
struct Pixel {
PixelSource source;
Byte value;
};
}
#endif //GAMEBOY_EMULATOR_GPUTYPES_H
| 16.117647 | 61 | 0.660584 | [
"object"
] |
839f7b11ca5b131349beb52b62ee87b350ec6e0b | 5,260 | cpp | C++ | src/parse_cmdline.cpp | kaikrueger/ec2-api | c53b7adcc83ae0c1ba758abe10ac8d4c41e05d69 | [
"BSD-4-Clause"
] | 1 | 2015-08-08T05:37:03.000Z | 2015-08-08T05:37:03.000Z | src/parse_cmdline.cpp | kaikrueger/ec2-api | c53b7adcc83ae0c1ba758abe10ac8d4c41e05d69 | [
"BSD-4-Clause"
] | null | null | null | src/parse_cmdline.cpp | kaikrueger/ec2-api | c53b7adcc83ae0c1ba758abe10ac8d4c41e05d69 | [
"BSD-4-Clause"
] | null | null | null | /*
* @file parse_cmdline.cpp
* @date 2011-10-17
*
* Created by Kai Krueger <kai.krueger@itwm.fraunhofer.de>
*
* Copyright (c) 2011 Fraunhofer ITWM
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <iostream>
#include <string>
#include <vector>
#include <map>
#include <boost/program_options.hpp>
#include <parse_cmdline.hpp>
namespace po = boost::program_options;
namespace ec2 {
typedef std::map< std::string, std::string> ParameterMap_Type;
template <typename T, int N>char (&array2(T(&)[N]))[N];
std::pair<std::string, std::string> init2[] = {
std::pair<std::string, std::string> ( "private-key", "AWSAccessKeyId" ),
//std::pair<std::string, std::string> ( "", "SecurityToken" ),
std::pair<std::string, std::string> ( "owner", "Owner.1" ),
//std::pair<std::string, std::string> ( "", "" ),
//std::pair<std::string, std::string> ( "", "" ),
//std::pair<std::string, std::string> ( "", "" )
};
std::map< std::string, std::string> opt2key2 ( init2, init2 + sizeof array2 ( init2 ) );
} // namespace ec2
void ec2::parse_cmdline(
int argc
, char **argv
, const po::options_description &specific
)
{
try {
po::options_description general("GENERAL OPTIONS");
general.add_options()
("private-key,K",po::value< std::string >(), "Specify KEY as the private key to use. Defaults to the value of the "
"EC2_PRIVATE_KEY environment variable (if set). Overrides the default.")
("cert,C",po::value< std::string >(), "Specify CERT as the X509 certificate to use. Defaults to the value "
"of the EC2_CERT environment variable (if set). Overrides the default.")
("url,U",po::value< std::string>(), "Specify URL as the web service URL to use. Defaults to the value of "
"'https://ec2.amazonaws.com' or to that of the EC2_URL environment "
"variable (if set). Overrides the default.")
("region", po::value< std::string>(), "Specify REGION as the web service region to use."
"This option will override the URL specified by the \"-U URL\" option"
"and EC2_URL environment variable.")
("help,h,?", "this help message")
("verbose,v", "verbose output")
("debug","Display additional debugging information.")
;
po::options_description cmdline_options;
cmdline_options.add(general).add(specific);
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, cmdline_options), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << cmdline_options << std::endl;
}
// print variables
po::variables_map::iterator it;
for ( it=vm.begin() ; it != vm.end(); it++ ) {
std::cout << (*it).first << " = ";
//std::cout << " => " << vm.get((*it).first).value();
//std::cout << vm[(*it).first].as<std::string>();
std::cout << (*it).second.as<std::string>();
std::cout<< std::endl;
}
} catch(std::exception &e){
throw;
}
}
const po::options_description &ec2::option_describe_images()
{
static po::options_description specific("SPECIFIC OPTIONS");
specific.add_options()
("all,a", po::value< std::string >(), "Describe all AMIs, public, private or owned, that the user has access to.")
("owner,o", po::value< std::string >(), "OWNER Only AMIs owned by the users specified are described. OWNER may either be a"
"user's account id for images owned by that user, 'self' for images owned by"
"you, or 'amazon' for images owned by Amazon.")
("executable-by,x",po::value< std::string >(), " USER"
"Only AMIs with launch permissions as specified are described. USER may either"
"be a user's account id for AMIs owned by you for which the user has explicit"
"launch permissions, 'self' for AMIs you have explicit launch permissions for,"
"or 'all' for AMIs with public launch permissions.")
;
return specific;
}
/*
* Local variables:
* tab-width: 2
* c-indent-level: 2
* c-basic-offset: 2
* project-name: ec2-api
* End:
*/
| 35.066667 | 127 | 0.664639 | [
"vector"
] |
83a0f36b72695786d45a381fa2ea8cc4d1ab525b | 30,116 | cc | C++ | lib/spot-2.8.1/spot/twaalgos/remfin.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | lib/spot-2.8.1/spot/twaalgos/remfin.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | lib/spot-2.8.1/spot/twaalgos/remfin.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | // -*- coding: utf-8 -*-
// Copyright (C) 2015-2018 Laboratoire de Recherche et Développement
// de l'Epita (LRDE).
//
// This file is part of Spot, a model checking library.
//
// Spot is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Spot is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "config.h"
#include <spot/twaalgos/remfin.hh>
#include <spot/twaalgos/sccinfo.hh>
#include <iostream>
#include <spot/twaalgos/cleanacc.hh>
#include <spot/twaalgos/totgba.hh>
#include <spot/twaalgos/isdet.hh>
#include <spot/twaalgos/mask.hh>
#include <spot/twaalgos/alternation.hh>
// #define TRACE
#ifdef TRACE
#define trace std::cerr
#else
#define trace while (0) std::cerr
#endif
namespace spot
{
namespace
{
enum strategy_t
{
trivial = 1U,
weak = 2U,
alternation = 4U,
rabin = 8U,
streett = 16U,
};
using strategy =
std::function<twa_graph_ptr(const const_twa_graph_ptr& aut)>;
twa_graph_ptr
remove_fin_impl(const const_twa_graph_ptr&, const strategy_t);
using EdgeMask = std::vector<bool>;
template< typename Edges, typename Apply >
void for_each_edge(const const_twa_graph_ptr& aut,
const Edges& edges,
const EdgeMask& mask,
Apply apply)
{
for (const auto& e: edges)
{
unsigned edge_id = aut->edge_number(e);
if (mask[edge_id])
apply(edge_id);
}
}
template< typename Edges >
acc_cond::mark_t scc_acc_marks(const_twa_graph_ptr aut,
const Edges& edges,
const EdgeMask& mask)
{
acc_cond::mark_t scc_mark = {};
for_each_edge(aut, edges, mask, [&] (unsigned e)
{
scc_mark |= aut->edge_data(e).acc;
});
return scc_mark;
}
// Transforms automaton from transition based acceptance to state based
// acceptance.
void make_state_acc(twa_graph_ptr & aut)
{
unsigned nst = aut->num_states();
for (unsigned s = 0; s < nst; ++s)
{
acc_cond::mark_t acc = {};
for (auto& t: aut->out(s))
acc |= t.acc;
for (auto& t: aut->out(s))
t.acc = acc;
}
aut->prop_state_acc(true);
}
// Check whether the SCC contains non-accepting cycles.
//
// A cycle is accepting (in a Rabin automaton) if there exists an
// acceptance pair (Fᵢ, Iᵢ) such that some states from Iᵢ are
// visited while no states from Fᵢ are visited.
//
// Consequently, a cycle is non-accepting if for all acceptance
// pairs (Fᵢ, Iᵢ), either no states from Iᵢ are visited or some
// states from Fᵢ are visited. (This corresponds to an accepting
// cycle with Streett acceptance.)
//
// final are those edges which are used in the resulting tba
// acceptance condition.
bool is_scc_tba_type(const_twa_graph_ptr aut,
const scc_info& si,
const unsigned scc,
const std::vector<bool>& keep,
const rs_pairs_view& aut_pairs,
std::vector<bool>& final)
{
if (si.is_rejecting_scc(scc))
return true;
auto scc_acc = scc_acc_marks(aut, si.inner_edges_of(scc), keep);
auto scc_pairs = rs_pairs_view(aut_pairs.pairs(), scc_acc);
// If there is one aut_fin_alone that is not in the SCC,
// any cycle in the SCC is accepting.
if (scc_pairs.fins_alone().proper_subset(aut_pairs.fins_alone()))
{
for_each_edge(aut, si.edges_of(scc), keep, [&](unsigned e)
{
final[e] = true;
});
return true;
}
auto scc_infs_alone = scc_pairs.infs_alone();
// Firstly consider whole SCC as one large cycle. If there is
// no inf without matching fin then the cycle formed by the
// entire SCC is not accepting. However that does not
// necessarily imply that all cycles in the SCC are also
// non-accepting. We may have a smaller cycle that is
// accepting, but which becomes non-accepting when extended with
// more edges.
if (!scc_infs_alone)
{
// Check whether the SCC is accepting. We do that by simply
// converting that SCC into a TGBA and running our emptiness
// check. This is not a really smart implementation and
// could be improved.
auto& states = si.states_of(scc);
std::vector<bool> keep_states(aut->num_states(), false);
for (auto s: states)
keep_states[s] = true;
auto sccaut = mask_keep_accessible_states(aut,
keep_states,
states.front());
// Prevent recurring into this function by skipping the
// Rabin strategy
auto skip = strategy_t::rabin;
// If SCCAUT is empty, the SCC is BA-type (and none of its
// states are final). If SCCAUT is nonempty, the SCC is not
// BA type
return remove_fin_impl(sccaut, skip)->is_empty();
}
// Remaining infs corresponds to I₁s that have been seen without seeing
// the matching F₁. In this SCC any edge in these I₁ is therefore
// final. Otherwise we do not know: it is possible that there is
// a non-accepting cycle in the SCC that does not visit Fᵢ.
std::set<unsigned> unknown;
for_each_edge(aut, si.inner_edges_of(scc), keep, [&](unsigned e)
{
const auto& ed = aut->edge_data(e);
if (ed.acc & scc_infs_alone)
final[e] = true;
else
unknown.insert(e);
});
// Erase edges that cannot belong to a cycle, i.e., that edges
// whose 'dst' is not 'src' of any unknown edges.
std::vector<unsigned> remove;
do
{
remove.clear();
std::set<unsigned> srcs;
for (auto e: unknown)
srcs.insert(aut->edge_storage(e).src);
for (auto e: unknown)
if (srcs.find(aut->edge_storage(e).dst) == srcs.end())
remove.push_back(e);
for (auto r: remove)
unknown.erase(r);
}
while (!remove.empty());
// Check whether it is possible to build non-accepting cycles
// using only the "unknown" edges.
using filter_data_t = std::pair<const_twa_graph_ptr, std::vector<bool>&>;
scc_info::edge_filter filter =
[](const twa_graph::edge_storage_t& t, unsigned, void* data)
-> scc_info::edge_filter_choice
{
auto& d = *static_cast<filter_data_t*>(data);
if (d.second[d.first->edge_number(t)])
return scc_info::edge_filter_choice::keep;
else
return scc_info::edge_filter_choice::ignore;
};
{
std::vector<bool> keep;
while (!unknown.empty())
{
keep.assign(aut->edge_vector().size(), false);
for (auto e: unknown)
keep[e] = true;
auto filter_data = filter_data_t{aut, keep};
auto init = aut->edge_storage(*unknown.begin()).src;
scc_info si(aut, init, filter, &filter_data,
scc_info_options::TRACK_STATES);
for (unsigned uscc = 0; uscc < si.scc_count(); ++uscc)
{
for_each_edge(aut, si.edges_of(uscc), keep, [&](unsigned e)
{
unknown.erase(e);
});
if (si.is_rejecting_scc(uscc))
continue;
if (!is_scc_tba_type(aut, si, uscc, keep, aut_pairs, final))
return false;
}
}
}
return true;
}
// Specialized conversion from transition based Rabin acceptance to
// transition based Büchi acceptance.
// Is able to detect SCCs that are TBA-type (i.e., they can be
// converted to Büchi acceptance without chaning their structure).
//
// See "Deterministic ω-automata vis-a-vis Deterministic Büchi
// Automata", S. Krishnan, A. Puri, and R. Brayton (ISAAC'94) for
// some details about detecting Büchi-typeness.
//
// We essentially apply this method SCC-wise. The paper is
// concerned about *deterministic* automata, but we apply the
// algorithm on non-deterministic automata as well: in the worst
// case it is possible that a TBA-type SCC with some
// non-deterministic has one accepting and one rejecting run for
// the same word. In this case we may fail to detect the
// TBA-typeness of the SCC, but the resulting automaton should
// be correct nonetheless.
twa_graph_ptr
tra_to_tba(const const_twa_graph_ptr& aut)
{
std::vector<acc_cond::rs_pair> pairs;
if (!aut->acc().is_rabin_like(pairs))
return nullptr;
auto aut_pairs = rs_pairs_view(pairs);
auto code = aut->get_acceptance();
if (code.is_t())
return nullptr;
// if is TBA type
scc_info si(aut, scc_info_options::TRACK_STATES);
std::vector<bool> scc_is_tba_type(si.scc_count(), false);
std::vector<bool> final(aut->edge_vector().size(), false);
std::vector<bool> keep(aut->edge_vector().size(), true);
for (unsigned scc = 0; scc < si.scc_count(); ++scc)
scc_is_tba_type[scc] = is_scc_tba_type(aut, si, scc, keep,
aut_pairs, final);
auto res = make_twa_graph(aut->get_dict());
res->copy_ap_of(aut);
res->prop_copy(aut, { false, false, false, false, false, true });
res->new_states(aut->num_states());
res->set_buchi();
res->set_init_state(aut->get_init_state_number());
trival deterministic = aut->prop_universal();
trival complete = aut->prop_complete();
std::vector<unsigned> state_map(aut->num_states());
for (unsigned scc = 0; scc < si.scc_count(); ++scc)
{
auto states = si.states_of(scc);
if (scc_is_tba_type[scc])
{
for (const auto& e: si.edges_of(scc))
{
bool acc = final[aut->edge_number(e)];
res->new_acc_edge(e.src, e.dst, e.cond, acc);
}
}
else
{
complete = trival::maybe();
// The main copy is only accepting for inf_alone
// and for all Inf sets that have no matching Fin
// sets in this SCC.
auto scc_pairs = rs_pairs_view(pairs, si.acc_sets_of(scc));
auto scc_infs_alone = scc_pairs.infs_alone();
for (const auto& e: si.edges_of(scc))
{
bool acc = !!(e.acc & scc_infs_alone);
res->new_acc_edge(e.src, e.dst, e.cond, acc);
}
auto fins_alone = aut_pairs.fins_alone();
for (auto r: scc_pairs.fins().sets())
{
acc_cond::mark_t pairinf = scc_pairs.paired_with_fin(r);
unsigned base = res->new_states(states.size());
for (auto s: states)
state_map[s] = base++;
for (const auto& e: si.inner_edges_of(scc))
{
if (e.acc.has(r))
continue;
auto src = state_map[e.src];
auto dst = state_map[e.dst];
bool cacc = fins_alone.has(r) || (pairinf & e.acc);
res->new_acc_edge(src, dst, e.cond, cacc);
// We need only one non-deterministic jump per
// cycle. As an approximation, we only do
// them on back-links.
if (e.dst <= e.src)
{
deterministic = false;
bool jacc = !!(e.acc & scc_infs_alone);
res->new_acc_edge(e.src, dst, e.cond, jacc);
}
}
}
}
}
res->prop_complete(complete);
res->prop_universal(deterministic);
res->purge_dead_states();
res->merge_edges();
if (!aut_pairs.infs())
make_state_acc(res);
return res;
}
// If the DNF is
// Fin(1)&Inf(2)&Inf(4) | Fin(2)&Fin(3)&Inf(1) |
// Inf(1)&Inf(3) | Inf(1)&Inf(2) | Fin(4)
// this returns the following map:
// {1} => Inf(2)&Inf(4)
// {2,3} => Inf(1)
// {} => Inf(1)&Inf(3) | Inf(1)&Inf(2)
// {4} => t
static std::map<acc_cond::mark_t, acc_cond::acc_code>
split_dnf_acc_by_fin(const acc_cond::acc_code& acc)
{
std::map<acc_cond::mark_t, acc_cond::acc_code> res;
auto pos = &acc.back();
if (pos->sub.op == acc_cond::acc_op::Or)
--pos;
auto start = &acc.front();
while (pos > start)
{
if (pos->sub.op == acc_cond::acc_op::Fin)
{
// We have only a Fin term, without Inf. In this case
// only, the Fin() may encode a disjunction of sets.
for (auto s: pos[-1].mark.sets())
{
acc_cond::mark_t fin = {};
fin.set(s);
res[fin] = acc_cond::acc_code{};
}
pos -= pos->sub.size + 1;
}
else
{
// We have a conjunction of Fin and Inf sets.
auto end = pos - pos->sub.size - 1;
acc_cond::mark_t fin = {};
acc_cond::mark_t inf = {};
while (pos > end)
{
switch (pos->sub.op)
{
case acc_cond::acc_op::And:
--pos;
break;
case acc_cond::acc_op::Fin:
fin |= pos[-1].mark;
assert(pos[-1].mark.count() == 1);
pos -= 2;
break;
case acc_cond::acc_op::Inf:
inf |= pos[-1].mark;
pos -= 2;
break;
case acc_cond::acc_op::FinNeg:
case acc_cond::acc_op::InfNeg:
case acc_cond::acc_op::Or:
SPOT_UNREACHABLE();
break;
}
}
assert(pos == end);
acc_cond::acc_word w[2];
w[0].mark = inf;
w[1].sub.op = acc_cond::acc_op::Inf;
w[1].sub.size = 1;
acc_cond::acc_code c;
c.insert(c.end(), w, w + 2);
auto p = res.emplace(fin, c);
if (!p.second)
p.first->second |= std::move(c);
}
}
return res;
}
static twa_graph_ptr
remove_fin_weak(const const_twa_graph_ptr& aut)
{
// Clone the original automaton.
auto res = make_twa_graph(aut,
{
true, // state based
true, // inherently weak
true, true, // determinisitic
true, // complete
true, // stutter inv.
});
scc_info si(res, scc_info_options::NONE);
// We will modify res in place, and the resulting
// automaton will only have one acceptance set.
acc_cond::mark_t all_acc = res->set_buchi();
res->prop_state_acc(true);
unsigned n = res->num_states();
for (unsigned src = 0; src < n; ++src)
{
if (!si.reachable_state(src))
continue;
acc_cond::mark_t acc = {};
unsigned scc = si.scc_of(src);
if (si.is_accepting_scc(scc) && !si.is_trivial(scc))
acc = all_acc;
for (auto& t: res->out(src))
t.acc = acc;
}
return res;
}
twa_graph_ptr trivial_strategy(const const_twa_graph_ptr& aut)
{
if (aut->acc().is_f())
{
// The original acceptance was equivalent to
// "f". Simply return an empty automaton with "t"
// acceptance.
auto res = make_twa_graph(aut->get_dict());
res->set_generalized_buchi(0);
res->set_init_state(res->new_state());
res->prop_stutter_invariant(true);
res->prop_weak(true);
res->prop_complete(false);
return res;
}
return (!aut->acc().uses_fin_acceptance())
? std::const_pointer_cast<twa_graph>(aut)
: nullptr;
}
twa_graph_ptr weak_strategy(const const_twa_graph_ptr& aut)
{
// FIXME: we should check whether the automaton is inherently weak.
return (aut->prop_weak().is_true())
? remove_fin_weak(aut)
: nullptr;
}
twa_graph_ptr alternation_strategy(const const_twa_graph_ptr& aut)
{
return (!aut->is_existential())
? remove_fin(remove_alternation(aut))
: nullptr;
}
twa_graph_ptr streett_strategy(const const_twa_graph_ptr& aut)
{
return (aut->get_acceptance().used_inf_fin_sets().first)
? streett_to_generalized_buchi_maybe(aut)
: nullptr;
}
twa_graph_ptr rabin_strategy(const const_twa_graph_ptr& aut)
{
return rabin_to_buchi_maybe(aut);
}
twa_graph_ptr default_strategy(const const_twa_graph_ptr& aut)
{
std::vector<acc_cond::acc_code> code;
std::vector<acc_cond::mark_t> rem;
std::vector<acc_cond::mark_t> keep;
std::vector<acc_cond::mark_t> add;
bool has_true_term = false;
acc_cond::mark_t allinf = {};
acc_cond::mark_t allfin = {};
{
auto acccode = aut->get_acceptance();
if (!acccode.is_dnf())
{
acccode = acccode.to_dnf();
if (acccode.is_f())
{
// The original acceptance was equivalent to
// "f". Simply return an empty automaton with "t"
// acceptance.
auto res = make_twa_graph(aut->get_dict());
res->set_generalized_buchi(0);
res->set_init_state(res->new_state());
res->prop_stutter_invariant(true);
res->prop_weak(true);
res->prop_complete(false);
return res;
}
}
auto split = split_dnf_acc_by_fin(acccode);
auto sz = split.size();
assert(sz > 0);
rem.reserve(sz);
code.reserve(sz);
keep.reserve(sz);
add.reserve(sz);
for (auto p: split)
{
// The empty Fin should always come first
assert(p.first || rem.empty());
rem.emplace_back(p.first);
allfin |= p.first;
acc_cond::mark_t inf = {};
if (!p.second.empty())
{
auto pos = &p.second.back();
auto end = &p.second.front();
while (pos > end)
{
switch (pos->sub.op)
{
case acc_cond::acc_op::And:
case acc_cond::acc_op::Or:
--pos;
break;
case acc_cond::acc_op::Inf:
inf |= pos[-1].mark;
pos -= 2;
break;
case acc_cond::acc_op::Fin:
case acc_cond::acc_op::FinNeg:
case acc_cond::acc_op::InfNeg:
SPOT_UNREACHABLE();
break;
}
}
}
if (!inf)
{
has_true_term = true;
}
code.emplace_back(std::move(p.second));
keep.emplace_back(inf);
allinf |= inf;
add.emplace_back(acc_cond::mark_t({}));
}
}
assert(add.size() > 0);
acc_cond acc = aut->acc();
unsigned extra_sets = 0;
// Do we have common sets between the acceptance terms?
// If so, we need extra sets to distinguish the terms.
bool interference = false;
{
auto sz = keep.size();
acc_cond::mark_t sofar = {};
for (unsigned i = 0; i < sz; ++i)
{
auto k = keep[i];
if (k & sofar)
{
interference = true;
break;
}
sofar |= k;
}
if (interference)
{
trace << "We have interferences\n";
// We need extra set, but we will try
// to reuse the Fin number if they are
// not used as Inf as well.
std::vector<int> exs(acc.num_sets());
for (auto f: allfin.sets())
{
if (allinf.has(f)) // Already used as Inf
{
exs[f] = acc.add_set();
++extra_sets;
}
else
{
exs[f] = f;
}
}
for (unsigned i = 0; i < sz; ++i)
{
acc_cond::mark_t m = {};
for (auto f: rem[i].sets())
m.set(exs[f]);
trace << "rem[" << i << "] = " << rem[i]
<< " m = " << m << '\n';
add[i] = m;
code[i] &= acc.inf(m);
trace << "code[" << i << "] = " << code[i] << '\n';
}
}
else if (has_true_term)
{
trace << "We have a true term\n";
unsigned one = acc.add_sets(1);
extra_sets += 1;
acc_cond::mark_t m({one});
auto c = acc.inf(m);
for (unsigned i = 0; i < sz; ++i)
{
if (!code[i].is_t())
continue;
add[i] = m;
code[i] &= std::move(c);
// Use false for the other terms.
c = acc.fin({});
trace << "code[" << i << "] = " << code[i] << '\n';
}
}
}
acc_cond::acc_code new_code = aut->acc().fin({});
for (auto c: code)
new_code |= std::move(c);
unsigned cs = code.size();
for (unsigned i = 0; i < cs; ++i)
trace << i << " Rem " << rem[i] << " Code " << code[i]
<< " Keep " << keep[i] << '\n';
unsigned nst = aut->num_states();
auto res = make_twa_graph(aut->get_dict());
res->copy_ap_of(aut);
res->prop_copy(aut, { true, false, false, false, false, true });
res->new_states(nst);
res->set_acceptance(aut->num_sets() + extra_sets, new_code);
res->set_init_state(aut->get_init_state_number());
// If the input had no Inf, the output is a state-based automaton.
if (!allinf)
res->prop_state_acc(true);
bool sbacc = res->prop_state_acc().is_true();
scc_info si(aut, scc_info_options::TRACK_STATES);
unsigned nscc = si.scc_count();
std::vector<unsigned> state_map(nst);
for (unsigned n = 0; n < nscc; ++n)
{
auto m = si.acc_sets_of(n);
auto states = si.states_of(n);
trace << "SCC #" << n << " uses " << m << '\n';
// What to keep and add into the main copy
acc_cond::mark_t main_sets = {};
acc_cond::mark_t main_add = {};
bool intersects_fin = false;
for (unsigned i = 0; i < cs; ++i)
if (!(m & rem[i]))
{
main_sets |= keep[i];
main_add |= add[i];
}
else
{
intersects_fin = true;
}
trace << "main_sets " << main_sets << "\nmain_add "
<< main_add << '\n';
// Create the main copy
for (auto s: states)
for (auto& t: aut->out(s))
{
acc_cond::mark_t a = {};
if (sbacc || SPOT_LIKELY(si.scc_of(t.dst) == n))
a = (t.acc & main_sets) | main_add;
res->new_edge(s, t.dst, t.cond, a);
}
// We do not need any other copy if the SCC is non-accepting,
// of if it does not intersect any Fin.
if (!intersects_fin || si.is_rejecting_scc(n))
continue;
// Create clones
for (unsigned i = 0; i < cs; ++i)
if (m & rem[i])
{
auto r = rem[i];
trace << "rem[" << i << "] = " << r << " requires a copy\n";
unsigned base = res->new_states(states.size());
for (auto s: states)
state_map[s] = base++;
auto k = keep[i];
auto a = add[i];
for (auto s: states)
{
auto ns = state_map[s];
for (auto& t: aut->out(s))
{
if ((t.acc & r) || si.scc_of(t.dst) != n)
continue;
auto nd = state_map[t.dst];
res->new_edge(ns, nd, t.cond, (t.acc & k) | a);
// We need only one non-deterministic jump per
// cycle. As an approximation, we only do
// them on back-links.
if (t.dst <= s)
{
acc_cond::mark_t a = {};
if (sbacc)
a = (t.acc & main_sets) | main_add;
res->new_edge(s, nd, t.cond, a);
}
}
}
}
}
res->purge_dead_states();
trace << "before cleanup: " << res->get_acceptance() << '\n';
cleanup_acceptance_here(res);
trace << "after cleanup: " << res->get_acceptance() << '\n';
if (res->acc().is_f())
{
// "f" is not generalized-Büchi. Just return an
// empty automaton instead.
auto res2 = make_twa_graph(res->get_dict());
res2->set_generalized_buchi(0);
res2->set_init_state(res2->new_state());
res2->prop_stutter_invariant(true);
res2->prop_weak(true);
res2->prop_complete(false);
return res2;
}
res->merge_edges();
return res;
}
twa_graph_ptr remove_fin_impl(const const_twa_graph_ptr& aut,
const strategy_t skip = {})
{
auto simp = simplify_acceptance(aut);
auto handle = [&](strategy stra, strategy_t type) -> twa_graph_ptr
{
return (type & skip) ? nullptr : stra(simp);
};
if (auto maybe = handle(trivial_strategy, strategy_t::trivial))
return maybe;
if (auto maybe = handle(weak_strategy, strategy_t::weak))
return maybe;
if (auto maybe = handle(alternation_strategy, strategy_t::alternation))
return maybe;
// The order between Rabin and Streett matters because for
// instance "Streett 1" (even generalized Streett 1) is
// Rabin-like, and dually "Rabin 1" is Streett-like.
//
// We therefore check Rabin before Streett, because the
// resulting automata are usually smaller, and it can preserve
// determinism.
//
// Note that SPOT_STREETT_CONV_MIN default to 3, which means
// that regardless of this order, Rabin 1 is not handled by
// streett_strategy unless SPOT_STREETT_CONV_MIN is changed.
if (auto maybe = handle(rabin_strategy, strategy_t::rabin))
return maybe;
if (auto maybe = handle(streett_strategy, strategy_t::streett))
return maybe;
return default_strategy(simp);
}
}
bool
rabin_is_buchi_realizable(const const_twa_graph_ptr& inaut)
{
auto aut = cleanup_acceptance(inaut);
std::vector<acc_cond::rs_pair> pairs;
if (!aut->acc().is_rabin_like(pairs))
return false;
auto aut_pairs = rs_pairs_view(pairs);
if (aut->get_acceptance().is_t())
return false;
// if is TBA type
scc_info si(aut, scc_info_options::TRACK_STATES);
std::vector<bool> final(aut->edge_vector().size(), false);
std::vector<bool> keep(aut->edge_vector().size(), true);
for (unsigned scc = 0; scc < si.scc_count(); ++scc)
if (!is_scc_tba_type(aut, si, scc, keep, aut_pairs, final))
return false;
return true;
}
twa_graph_ptr
rabin_to_buchi_maybe(const const_twa_graph_ptr& aut)
{
bool is_state_acc = aut->prop_state_acc().is_true();
auto res = tra_to_tba(aut);
if (res && is_state_acc)
make_state_acc(res);
return res;
}
twa_graph_ptr remove_fin(const const_twa_graph_ptr& aut)
{
twa_graph_ptr res = remove_fin_impl(aut);
assert(!res->acc().uses_fin_acceptance());
assert(!res->acc().is_f());
return res;
}
}
| 34.896871 | 79 | 0.50352 | [
"vector",
"model"
] |
83aceadf6ce0c21f54289b8f35c481d1bcc809c6 | 4,606 | cpp | C++ | zynq/hls/mmult_fixed/mmult_fixed.cpp | swappad/cs5222-lab-fpga-mlp | 46fb9cb798460474c16f2f60a89a0807307fb971 | [
"MIT"
] | 1 | 2022-03-08T08:38:36.000Z | 2022-03-08T08:38:36.000Z | zynq/hls/mmult_fixed/mmult_fixed.cpp | swappad/cs5222-lab-fpga-mlp | 46fb9cb798460474c16f2f60a89a0807307fb971 | [
"MIT"
] | null | null | null | zynq/hls/mmult_fixed/mmult_fixed.cpp | swappad/cs5222-lab-fpga-mlp | 46fb9cb798460474c16f2f60a89a0807307fb971 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include "mmult.h"
// --------------------------------------------------------------------
// function to be accelerated in HW wrapped with AXI4-Stream interface
void mmult_hw (AXI_VAL in_stream[IS_SIZE], AXI_VAL out_stream[OS_SIZE])
{
#pragma HLS INTERFACE s_axilite port=return bundle=CONTROL_BUS
#pragma HLS INTERFACE axis port=in_stream
#pragma HLS INTERFACE axis port=out_stream
// Assertions (to avoid out of array bound writes)
assert(BATCH%TILING==0);
assert(FEAT%W_WIDTH_RATIO==0);
assert(FEAT%IN_WIDTH_RATIO==0);
assert((BATCH*CLASSES)%OUT_WIDTH_RATIO==0);
// Hardware memory buffers
// CLASSES 10
// FEAT 265
// TILING 64
out_T offset_buf[CLASSES];
in_T in_buf[TILING][FEAT];
#pragma HLS ARRAY_PARTITION variable=in_buf block factor=32 dim=2
w_T weight_buf[CLASSES][FEAT];
#pragma HLS ARRAY_PARTITION variable=weight_buf block factor=32 dim=2
out_T out_buf[TILING][CLASSES];
// Input and output AXI stream indices
int is_idx = 0;
int os_idx = 0;
// Stream in offset vector
// CSE548 TODO
LOAD_OFF_1: for(int i=0; i < CLASSES; i+=OUT_WIDTH_RATIO) {
#pragma HLS pipeline II=1
ap_int<64> tmp = pop_stream(in_stream[is_idx++]);
offset_buf[i+0] = tmp.range(31,0);
offset_buf[i+1] = tmp.range(63,32);
}
// Stream in weight matrix
// CSE548 TODO
LOAD_W_1: for(int i=0; i < CLASSES; i++) {
LOAD_W_2: for(int j=0; j < FEAT; j+=W_WIDTH_RATIO) {
#pragma HLS pipeline II=1
axi_T packet = pop_stream(in_stream[is_idx++]);
ap_int<64> tmp = packet;
weight_buf[i][j+0] = (w_T) tmp.range(7,0); // tmp.range(63,56);
weight_buf[i][j+1] = (w_T) tmp.range(15,8); // tmp.range(55,48);
weight_buf[i][j+2] = (w_T) tmp.range(23,16); // tmp.range(47,40);
weight_buf[i][j+3] = (w_T) tmp.range(31,24); // tmp.range(39,32);
weight_buf[i][j+4] = (w_T) tmp.range(39,32); // tmp.range(31,24);
weight_buf[i][j+5] = (w_T) tmp.range(47,40); // tmp.range(23,16);
weight_buf[i][j+6] = (w_T) tmp.range(55,48); // tmp.range(15,7);
weight_buf[i][j+7] = (w_T) tmp.range(63,56); // tmp.range(7,0);
}
}
// Iterate over tiles
LT: for (int t = 0; t < BATCH; t+=TILING) {
// Stream in input tile
// CSE548 TODO
LOAD_I_1: for(int i=0; i < TILING; i++) {
LOAD_I_2: for(int j=0; j < FEAT; j+=IN_WIDTH_RATIO) {
#pragma HLS pipeline II=1
ap_uint<64> tmp= pop_stream(in_stream[is_idx++]);
in_buf[i][j+0] = (in_T) tmp.range(7,0); // tmp.range(63,56); //
in_buf[i][j+1] = (in_T) tmp.range(15,8); // tmp.range(55,48); //
in_buf[i][j+2] = (in_T) tmp.range(23,16); // tmp.range(47,40); //
in_buf[i][j+3] = (in_T) tmp.range(31,24); // tmp.range(39,32); //
in_buf[i][j+4] = (in_T) tmp.range(39,32); // tmp.range(31,24); //
in_buf[i][j+5] = (in_T) tmp.range(47,40); // tmp.range(23,16); //
in_buf[i][j+6] = (in_T) tmp.range(55,48); // tmp.range(15,7); //
in_buf[i][j+7] = (in_T) tmp.range(63,56); // tmp.range(7,0); //
}
}
// Perform matrix multiplication
L1: for (int i = 0; i < TILING; i++) {
// Iterate over output classes
L2: for (int j = 0; j < CLASSES; j++) {
// Perform the dot product
#pragma HLS pipeline II=1
out_T tmp = offset_buf[j];
L3: for(int k = 0; k < FEAT; k++) {
out_T mult = in_buf[i][k] * weight_buf[j][k];
tmp = tmp + mult;
}
out_buf[i][j] = tmp;
}
}
// Stream out output matrix
// CSE548 TODO
STORE_O_1: for(int i=0; i < TILING; i++) {
STORE_O_2: for(int j=0; j < CLASSES; j+=OUT_WIDTH_RATIO) {
#pragma HLS pipeline II=1
ap_int<64> tmp;
tmp.range(31,0) = out_buf[i][j+0];
tmp.range(63,32) = out_buf[i][j+1];
axi_T packet = tmp;
out_stream[os_idx++] = push_stream(packet, os_idx == (OS_SIZE));
}
}
}
}
// --------------------------------------------------------
// functions to insert and extract elements from an axi stream
// includes conversion to correct data type
axi_T pop_stream(AXI_VAL const &e)
{
#pragma HLS INLINE
axi_T ret = e.data;
volatile ap_uint<sizeof(axi_T)> strb = e.strb;
volatile ap_uint<sizeof(axi_T)> keep = e.keep;
volatile ap_uint<AXI_U> user = e.user;
volatile ap_uint<1> last = e.last;
volatile ap_uint<AXI_TI> id = e.id;
volatile ap_uint<AXI_TD> dest = e.dest;
return ret;
}
AXI_VAL push_stream(axi_T const &v, bool last = false)
{
#pragma HLS INLINE
AXI_VAL e;
e.data = v;
e.strb = (1<<sizeof(axi_T))-1;
e.keep = (1<<sizeof(axi_T))-1;
e.user = 0;
e.last = last ? 1 : 0;
e.id = 0;
e.dest = 0;
return e;
}
| 29.33758 | 72 | 0.599436 | [
"vector"
] |
83b099c984c45c755499affd4afcbfa374755975 | 32,946 | cpp | C++ | lib/src/BoxTools/NodeAMRIO.cpp | boywert/chombo | e06f9f5d23125c7759be33430f57a5beb1112f8d | [
"BSD-3-Clause-LBNL"
] | 4 | 2019-09-05T01:15:10.000Z | 2021-08-06T13:26:21.000Z | lib/src/BoxTools/NodeAMRIO.cpp | boywert/chombo | e06f9f5d23125c7759be33430f57a5beb1112f8d | [
"BSD-3-Clause-LBNL"
] | null | null | null | lib/src/BoxTools/NodeAMRIO.cpp | boywert/chombo | e06f9f5d23125c7759be33430f57a5beb1112f8d | [
"BSD-3-Clause-LBNL"
] | 2 | 2018-12-02T14:02:34.000Z | 2020-12-07T14:22:17.000Z | #ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
// NodeAMRIO.cpp
// petermc, 4 March 2003
// adapted from AMRIO by DTGraves, Fri, Dec 3, 1999
#include <fstream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include "NodeFArrayBox.H"
#include "HDF5Portable.H"
#include "NamespaceHeader.H"
using std::system;
using std::fstream;
using std::string;
#ifndef __IBMCPP__
using std::sprintf;
#endif
template <>
inline void dataSize(const NodeFArrayBox& item, Vector<int>& a_sizes,
const Box& box, const Interval& comps)
{
Box boxNodes = surroundingNodes(box);
a_sizes[0] = boxNodes.numPts() * comps.size();
}
template <>
inline const char* name(const NodeFArrayBox& a_dummySpecializationArg)
{
// Attempt to get rid of warnings on IBM...
//static const char* name = "NodeFArrayBox";
const char* name = "NodeFArrayBox";
return name;
}
#include "NamespaceFooter.H"
#ifdef CH_USE_HDF5
#include "CH_HDF5.H"
#include "NodeAMRIO.H"
#include "BoxIterator.H"
#include "LayoutIterator.H"
#include "VisItChomboDriver.H"
#include "NamespaceHeader.H"
template <>
inline void dataTypes(Vector<hid_t>& a_types, const NodeFArrayBox& dummy)
{
a_types.resize(1);
a_types[0] = H5T_NATIVE_REAL;
}
// ---------------------------------------------------------
/*
\\ write out hierarchy of amr data in HDF5 format
\\ filename, == file to output to
\\ a_vectData == data at each level
\\ a_vectNames== names of variables
\\ a_domain == domain at coarsest level
\\ a_dx == grid spacing at coarsest level
\\ a_dt == time step at coarsest level
\\ a_time == time
\\ a_vectRatio == refinement ratio at all levels
\\ (ith entry is refinement ratio between levels i and i + 1)
\\ a_numLevels == number of levels to output
*/
void
WriteAMRHierarchyHDF5(const string& filename,
const Vector<DisjointBoxLayout>& a_vectGrids,
const Vector<LevelData<NodeFArrayBox>* > & a_vectData,
const Vector<string>& a_vectNames,
const Box& a_domain,
const Real& a_dx,
const Real& a_dt,
const Real& a_time,
const Vector<int>& a_refRatio,
const int& a_numLevels,
const RealVect& a_origin,
const Interval& a_comps )
{
HDF5Handle handle(filename.c_str(), HDF5Handle::CREATE);
WriteAMRHierarchyHDF5(handle, a_vectGrids, a_vectData, a_vectNames,
a_domain, a_dx, a_dt, a_time, a_refRatio, a_numLevels,
a_origin, a_comps);
#ifdef CH_MPI
MPI_Barrier(Chombo_MPI::comm);
#endif
handle.close();
}
// ---------------------------------------------------------
/*
\\ write out hierarchy of amr data in HDF5 format
\\ filename, == file to output to
\\ a_vectData == data at each level
\\ a_vectNames== names of variables
\\ a_domain == domain at coarsest level
\\ a_dx == grid spacing in each direction at coarsest level
\\ a_dt == time step at coarsest level
\\ a_time == time
\\ a_vectRatio == refinement ratio in each direction at all levels
\\ (ith entry is refinement ratio between levels i and i + 1)
\\ a_numLevels == number of levels to output
*/
void
WriteAnisotropicAMRHierarchyHDF5(
const string& filename,
const Vector<DisjointBoxLayout>& a_vectGrids,
const Vector<LevelData<NodeFArrayBox>* > & a_vectData,
const Vector<string>& a_vectNames,
const Box& a_domain,
const RealVect& a_dx,
const Real& a_dt,
const Real& a_time,
const Vector<IntVect>& a_refRatios,
const int& a_numLevels,
const RealVect& a_origin,
const Interval& a_comps )
{
HDF5Handle handle(filename.c_str(), HDF5Handle::CREATE);
WriteAnisotropicAMRHierarchyHDF5(handle, a_vectGrids, a_vectData, a_vectNames,
a_domain, a_dx, a_dt, a_time, a_refRatios, a_numLevels,
a_origin, a_comps);
#ifdef CH_MPI
MPI_Barrier(Chombo_MPI::comm);
#endif
handle.close();
}
// ---------------------------------------------------------
void
WriteAMRHierarchyHDF5(const string& filename,
const Vector<DisjointBoxLayout>& a_vectGrids,
const Vector<Vector<LevelData<NodeFArrayBox>* > >& a_vectData,
const Vector<string>& a_vectNames,
const Box& a_domain,
const Real& a_dx,
const Real& a_dt,
const Real& a_time,
const Vector<int>& a_vectRatio,
const int& a_numLevels)
{
// We have a_vectData[component][level].
// Each component should have the same number of levels.
CH_assert(a_numLevels > 0);
CH_assert(a_vectRatio.size() >= a_numLevels-1);
int numvarsOrig = a_vectData.size();
int numvars = 0;
Vector<int> numvarsEach(numvarsOrig);
for (int ivarOrig = 0; ivarOrig < numvarsOrig; ivarOrig++)
{
CH_assert( a_vectData[ivarOrig].size() >= a_numLevels );
numvarsEach[ivarOrig] = a_vectData[ivarOrig][0]->nComp();
numvars += numvarsEach[ivarOrig];
}
CH_assert( a_vectNames.size() == numvars );
Vector<LevelData<NodeFArrayBox>* > vectVarsNode(a_numLevels, NULL);
for (int ilev = 0; ilev < a_numLevels; ilev++)
{
const DisjointBoxLayout& grids = a_vectGrids[ilev];
// What about ghosts in the LevelData?
// Different variables may have different ghost vectors.
// Solution: dispense with ghosts.
vectVarsNode[ilev] = new LevelData<NodeFArrayBox>(grids, numvars);
LevelData<NodeFArrayBox>& vectVarsNodeLevel = *vectVarsNode[ilev];
int ivar = 0;
for (int ivarOrig = 0; ivarOrig < numvarsOrig; ivarOrig++)
for (int ivarEach = 0; ivarEach < numvarsEach[ivarOrig]; ivarEach++)
{
Interval newInterval(ivar, ivar);
Interval oldInterval(ivarEach, ivarEach);
const LevelData<NodeFArrayBox>& dataLevel = *a_vectData[ivarOrig][ilev];
// dataLevel.copyTo(oldInterval, vectVarsNodeLevel, newInterval);
// Use copy() instead of copyTo() because it is more efficient.
for (DataIterator dit = dataLevel.dataIterator(); dit.ok(); ++dit)
{
const NodeFArrayBox& dataLevelNfab = dataLevel[dit()];
NodeFArrayBox& vectVarsNodeLevelNfab = vectVarsNodeLevel[dit()];
Box bx(vectVarsNodeLevelNfab.box()); // no ghosts
vectVarsNodeLevelNfab.copy(bx,
newInterval,
bx,
dataLevelNfab,
oldInterval);
}
ivar++;
}
vectVarsNodeLevel.exchange(vectVarsNodeLevel.interval());
}
WriteAMRHierarchyHDF5(filename,
a_vectGrids,
vectVarsNode,
a_vectNames,
a_domain,
a_dx, a_dt, a_time,
a_vectRatio,
a_numLevels);
for (int ilev = 0; ilev < a_numLevels; ilev++)
delete vectVarsNode[ilev];
}
// ---------------------------------------------------------
void
WriteAMRHierarchyHDF5(HDF5Handle& handle,
const Vector<DisjointBoxLayout>& a_vectGrids,
const Vector<LevelData<NodeFArrayBox>* > & a_vectData,
const Vector<string>& a_vectNames,
const Box& a_domain,
const Real& a_dx,
const Real& a_dt,
const Real& a_time,
const Vector<int>& a_refRatio,
const int& a_numLevels,
const RealVect& a_origin,
const Interval& a_comps )
{
Interval comps_interval( a_comps );
if ( a_comps.size() <= 0 ) comps_interval.define( 0,a_vectData[0]->nComp() -1 );
int nComps = comps_interval.size() ;
CH_assert(a_numLevels > 0);
CH_assert(a_vectData.size() >= a_numLevels);
CH_assert(a_refRatio.size() >= a_numLevels-1);
CH_assert(a_vectNames.size() == nComps);
HDF5HeaderData header;
string filedescriptor("VanillaAMRFileType");
header.m_string ["filetype"] = filedescriptor;
// string centeringdescriptor("node");
// header.m_string ["data_centering"] = centeringdescriptor;
header.m_int ["data_centering"] = 7; // 7 for node-centered data
header.m_int ["num_levels"] = a_numLevels;
header.m_int ["num_components"] = nComps;
// write the grid origin if it isn't zero
if ( a_origin != RealVect::Zero )
{
header.m_realvect["origin"] = a_origin ;
}
for (int ivar = 0; ivar < nComps; ivar++)
{
char labelChSt[100];
sprintf(labelChSt, "component_%d", ivar);
string label(labelChSt);
header.m_string[label] = a_vectNames[ivar];
}
header.writeToFile(handle);
Box domainLevel = a_domain;
Real dtLevel = a_dt;
Real dxLevel = a_dx;
for (int ilev = 0; ilev < a_numLevels; ilev++)
{
int refLevel = 1;
if (ilev != a_numLevels -1)
refLevel = a_refRatio[ilev];
if (ilev != 0)
{
domainLevel.refine(a_refRatio[ilev-1]);
dtLevel /= a_refRatio[ilev-1];
dxLevel /= a_refRatio[ilev-1];
}
CH_assert(a_vectData[ilev] != NULL);
const LevelData<NodeFArrayBox>& dataLevel = *a_vectData[ilev];
const IntVect ghostVect(dataLevel.ghostVect());
CH_assert(dataLevel.nComp() >= nComps);
int eek = writeLevel(handle, ilev, dataLevel,
dxLevel, dtLevel, a_time,
domainLevel, refLevel,
ghostVect, comps_interval);
if (eek != 0)
MayDay::Error("WriteAMRHierarchyHDF5: Error in writeLevel");
}
}
// ---------------------------------------------------------
void
WriteAnisotropicAMRHierarchyHDF5(
HDF5Handle& handle,
const Vector<DisjointBoxLayout>& a_vectGrids,
const Vector<LevelData<NodeFArrayBox>* > & a_vectData,
const Vector<string>& a_vectNames,
const Box& a_domain,
const RealVect& a_dx, // for each direction
const Real& a_dt,
const Real& a_time,
const Vector<IntVect>& a_refRatios,
const int& a_numLevels,
const RealVect& a_origin,
const Interval& a_comps )
{
Interval comps_interval( a_comps );
if ( a_comps.size() <= 0 ) comps_interval.define( 0,a_vectData[0]->nComp() -1 );
int nComps = comps_interval.size() ;
CH_assert(a_numLevels > 0);
CH_assert(a_vectData.size() >= a_numLevels);
CH_assert(a_refRatios.size() >= a_numLevels-1);
CH_assert(a_vectNames.size() == nComps);
HDF5HeaderData header;
string filedescriptor("VanillaAMRFileType");
header.m_string ["filetype"] = filedescriptor;
// string centeringdescriptor("node");
// header.m_string ["data_centering"] = centeringdescriptor;
header.m_int ["data_centering"] = 7; // 7 for node-centered data
header.m_int ["num_levels"] = a_numLevels;
header.m_int ["num_components"] = nComps;
// write the grid origin if it isn't zero
if ( a_origin != RealVect::Zero )
{
header.m_realvect["origin"] = a_origin ;
}
for (int ivar = 0; ivar < nComps; ivar++)
{
char labelChSt[100];
sprintf(labelChSt, "component_%d", ivar);
string label(labelChSt);
header.m_string[label] = a_vectNames[ivar];
}
header.writeToFile(handle);
Box domainLevel = a_domain;
Real dtLevel = a_dt;
RealVect dxLevel = a_dx;
for (int ilev = 0; ilev < a_numLevels; ilev++)
{
IntVect refLevel = IntVect::Unit;
if (ilev != a_numLevels -1)
refLevel = a_refRatios[ilev];
if (ilev != 0)
{
domainLevel.refine(a_refRatios[ilev-1]);
dtLevel /= a_refRatios[ilev-1][0]; // HACK use the 0 dir ref ratio
dxLevel /= a_refRatios[ilev-1];
}
CH_assert(a_vectData[ilev] != NULL);
const LevelData<NodeFArrayBox>& dataLevel = *a_vectData[ilev];
const IntVect ghostVect(dataLevel.ghostVect());
CH_assert(dataLevel.nComp() >= nComps);
int eek = writeLevel(handle, ilev, dataLevel,
dxLevel, dtLevel, a_time,
domainLevel, refLevel,
ghostVect, comps_interval);
if (eek != 0)
MayDay::Error("WriteAMRHierarchyHDF5: Error in writeLevel");
}
}
// ---------------------------------------------------------
void
WriteAMRHierarchyHDF5(const string& filename,
const Vector<DisjointBoxLayout>& a_vectGrids,
const Vector<LevelData<NodeFArrayBox>* > & a_vectData,
const Box& a_domain,
const Vector<int>& a_refRatio,
const int& a_numLevels)
{
HDF5Handle handle(filename.c_str(), HDF5Handle::CREATE);
WriteAMRHierarchyHDF5(handle, a_vectGrids, a_vectData,
a_domain, a_refRatio, a_numLevels);
#ifdef CH_MPI
MPI_Barrier(Chombo_MPI::comm);
#endif
handle.close();
}
// ---------------------------------------------------------
void
WriteAMRHierarchyHDF5(HDF5Handle& handle,
const Vector<DisjointBoxLayout>& a_vectGrids,
const Vector<LevelData<NodeFArrayBox>* > & a_vectData,
const Box& a_domain,
const Vector<int>& a_refRatio,
const int& a_numLevels)
{
CH_assert(a_numLevels > 0);
CH_assert(a_vectData.size() >= a_numLevels);
CH_assert(a_refRatio.size() >= a_numLevels-1);
Real dxin = 1.0;
Real dtin = 1.0;
Real time = 1.0;
HDF5HeaderData header;
int nComp = a_vectData[0]->nComp();
string filedescriptor("VanillaAMRFileType");
header.m_string ["filetype"] = filedescriptor;
// string centeringdescriptor("node");
// header.m_string ["data_centering"] = centeringdescriptor;
header.m_int ["data_centering"] = 7; // 7 for node-centered data
header.m_int ["num_levels"] = a_numLevels;
header.m_int ["num_components"] = nComp;
for (int ivar = 0; ivar < nComp; ivar++)
{
char labelChSt[100];
sprintf(labelChSt, "component_%d", ivar);
string label(labelChSt);
header.m_string[label] = label;
}
header.writeToFile(handle);
Box domainLevel = a_domain;
Real dtLevel = dtin;
Real dxLevel = dxin;
for (int ilev = 0; ilev < a_numLevels; ilev++)
{
int refLevel = 1;
if (ilev != a_numLevels -1)
refLevel = a_refRatio[ilev];
if (ilev != 0)
{
domainLevel.refine(a_refRatio[ilev-1]);
dtLevel /= a_refRatio[ilev-1];
dxLevel /= a_refRatio[ilev-1];
}
CH_assert(a_vectData[ilev] != NULL);
const LevelData<NodeFArrayBox>& dataLevel = *a_vectData[ilev];
CH_assert(dataLevel.nComp() == nComp);
int eek = writeLevel(handle, ilev, dataLevel,
dxLevel, dtLevel, time,
domainLevel, refLevel);
if (eek != 0)
MayDay::Error("WriteAMRHierarchyHDF5: Error in writeLevel");
}
}
// ---------------------------------------------------------
//
/*
\\ Read in hierarchy of amr data in HDF5 format
\\ filename, == file to output to
\\ a_vectData == data at each level
\\ a_vectNames== names of variables
\\ a_domain == domain at coarsest level
\\ a_dx == grid spacing at coarsest level
\\ a_dt == time step at coarsest level
\\ a_time == time
\\ a_vectRatio == refinement ratio at all levels
\\ (ith entry is refinement ratio between levels i and i + 1)
\\ a_numLevels == number of levels to output
return values:
0: success
-1: bogus number of levels
-2: bogus number of components
-3: error in readlevel
-4: file open failed
*/
int
ReadAMRHierarchyHDF5(const string& filename,
Vector<DisjointBoxLayout>& a_vectGrids,
Vector<LevelData<NodeFArrayBox>* > & a_vectData,
Vector<string>& a_vectNames,
Box& a_domain,
Real& a_dx,
Real& a_dt,
Real& a_time,
Vector<int>& a_refRatio,
int& a_numLevels,
bool a_setGhost)
{
HDF5Handle handle;
int err = handle.open(filename.c_str(), HDF5Handle::OPEN_RDONLY);
if ( err < 0) return -4;
int eekflag = ReadAMRHierarchyHDF5(handle, a_vectGrids, a_vectData,
a_vectNames, a_domain, a_dx, a_dt,
a_time, a_refRatio, a_numLevels,
a_setGhost);
#ifdef CH_MPI
MPI_Barrier(Chombo_MPI::comm);
#endif
handle.close();
return (eekflag);
}
// ---------------------------------------------------------
int
ReadAMRHierarchyHDF5(HDF5Handle& handle,
Vector<DisjointBoxLayout>& a_vectGrids,
Vector<LevelData<NodeFArrayBox>* > & a_vectData,
Vector<string>& a_vectNames,
Box& a_domain,
Real& a_dx,
Real& a_dt,
Real& a_time,
Vector<int>& a_refRatio,
int& a_numLevels,
bool a_setGhost)
{
HDF5HeaderData header;
header.readFromFile(handle);
a_numLevels = header.m_int["num_levels"];
if (a_numLevels <= 0)
{
MayDay::Warning("ReadAMRHierarchyHDF5: Bogus number of levels");
return (-1);
}
a_vectData.resize(a_numLevels);
a_refRatio.resize(a_numLevels);
a_vectGrids.resize(a_numLevels);
int nComp = header.m_int["num_components"];
if (nComp <= 0)
{
MayDay::Warning("ReadAMRHierarchyHDF5: Bogus number of Components");
return (-2);
}
a_vectNames.resize(nComp);
for (int ivar = 0; ivar < nComp; ivar++)
{
char labelChSt[100];
sprintf(labelChSt, "component_%d", ivar);
string label(labelChSt);
a_vectNames[ivar] = header.m_string[label];
}
for (int ilev = 0; ilev < a_numLevels; ilev++)
{
int refLevel = 0;
Box domainLevel;
Real dtLevel;
Real dxLevel;
a_vectData[ilev] = new LevelData<NodeFArrayBox>();
int eek = readLevel(handle, ilev, *(a_vectData[ilev]),
dxLevel, dtLevel, a_time,
domainLevel, refLevel, Interval(), a_setGhost);
if (eek != 0)
{
MayDay::Warning("ReadAMRHierarchyHDF5: readLevel failed");
return (-3);
}
const DisjointBoxLayout& dbl = a_vectData[ilev]->getBoxes();
a_vectGrids[ilev]= dbl;
if (ilev == 0)
{
a_domain = domainLevel;
a_dt = dtLevel;
a_dx = dxLevel;
}
a_refRatio[ilev] = refLevel;
}
return (0);
}
// ---------------------------------------------------------
int
ReadAMRHierarchyHDF5(const string& filename,
Vector<DisjointBoxLayout>& a_vectGrids,
Vector<LevelData<NodeFArrayBox>* > & a_vectData,
Box& a_domain,
Vector<int>& a_refRatio,
int& a_numLevels,
bool a_setGhost)
{
HDF5Handle handle;
int err = handle.open(filename.c_str(), HDF5Handle::OPEN_RDONLY);
if ( err < 0) return -4;
int eekflag = ReadAMRHierarchyHDF5(handle, a_vectGrids, a_vectData,
a_domain, a_refRatio, a_numLevels,
a_setGhost);
#ifdef CH_MPI
MPI_Barrier(Chombo_MPI::comm);
#endif
handle.close();
return (eekflag);
}
// ---------------------------------------------------------
int
ReadAMRHierarchyHDF5(HDF5Handle& handle,
Vector<DisjointBoxLayout>& a_vectGrids,
Vector<LevelData<NodeFArrayBox>* > & a_vectData,
Box& a_domain,
Vector<int>& a_refRatio,
int& a_numLevels,
bool a_setGhost)
{
HDF5HeaderData header;
header.readFromFile(handle);
a_numLevels = header.m_int["num_levels"];
if (a_numLevels <= 0)
{
MayDay::Warning("ReadAMRHierarchyHDF5: Bogus number of levels");
return (-1);
}
a_vectData.resize(a_numLevels);
a_refRatio.resize(a_numLevels);
a_vectGrids.resize(a_numLevels);
// int nComp = header.m_int["num_components"];
for (int ilev = 0; ilev < a_numLevels; ilev++)
{
int refLevel = 0;
Box domainLevel;
Real dtLevel;
Real dxLevel;
Real time;
a_vectData[ilev] = new LevelData<NodeFArrayBox>();
int eek = readLevel(handle, ilev, *(a_vectData[ilev]),
dxLevel, dtLevel, time,
domainLevel, refLevel, Interval(), a_setGhost);
if (eek != 0)
{
MayDay::Warning("ReadAMRHierarchyHDF5: readLevel failed");
return (-3);
}
const DisjointBoxLayout& dbl = a_vectData[ilev]->getBoxes();
a_vectGrids[ilev]= dbl;
if (ilev == 0)
{
a_domain = domainLevel;
}
a_refRatio[ilev] = refLevel;
}
return (0);
}
// put simple debugging functions here, at the end of the hdf5 stuff
static void
ChomboVisVisualizeFile(const char *fname)
{
char command[2000];
sprintf(command,"$CHOMBOVIS_HOME/bin/chombovis debug_level=0 %s &",fname);
int ret;
ret = system(command);
}
static VisItChomboDriver visit;
static void
VisItVisualizeFile(const char *fname)
{
visit.VisualizeFile(fname);
}
static void
VisualizeFile(const char *fname)
{
const char *use_chombovis = getenv("CHOMBO_USE_CHOMBOVIS");
if (use_chombovis)
ChomboVisVisualizeFile(fname);
else
VisItVisualizeFile(fname);
}
// ---------------------------------------------------------
void
writeNFAB(const NodeFArrayBox* a_dataPtr)
{
if (a_dataPtr == NULL) return;
const char* fname = "nfab.hdf5";
writeNFABname(a_dataPtr, fname);
}
// ---------------------------------------------------------
void
viewNFAB(const NodeFArrayBox* a_dataPtr)
{
if (a_dataPtr == NULL) return;
const char* fname = tempnam(NULL,NULL);
writeNFABname(a_dataPtr, fname);
VisualizeFile(fname);
}
// ---------------------------------------------------------
void
writeNFABname(const NodeFArrayBox* a_dataPtr,
const char* a_filename)
{
if (a_dataPtr == NULL) return;
const NodeFArrayBox& data = *a_dataPtr;
HDF5Handle handle(a_filename, HDF5Handle::CREATE);
HDF5HeaderData header;
int numlevels= 1;
int nComp = data.getFab().nComp();
string filedescriptor("VanillaAMRFileType");
header.m_string ["filetype"] = filedescriptor;
// string centeringdescriptor("node");
// header.m_string ["data_centering"] = centeringdescriptor;
header.m_int ["data_centering"] = 7; // 7 for node-centered data
header.m_int ["num_levels"] = numlevels;
header.m_int ["num_components"] = nComp;
for (int ivar = 0; ivar < nComp; ivar++)
{
char labelChSt[100];
sprintf(labelChSt, "component_%d", ivar);
string label(labelChSt);
header.m_string[label] = label;
}
header.writeToFile(handle);
Box domainLevel = data.box();
// put bogus numbers here
Real dtLevel = 1.0;
Real dxLevel = 1.0;
Real time = 1.0;
int refLevel = 1;
// build bogus DisjointBoxLayout here
Vector<Box> boxes(1,domainLevel);
unsigned int myprocID= procID();
Vector<int> procAssign(1,myprocID);
DisjointBoxLayout grids(boxes, procAssign);
LevelData<NodeFArrayBox> ldf(grids, nComp);
// now copy nfab into ldf
DataIterator dit = ldf.dataIterator();
ldf[dit()].copy(data);
int eek = writeLevel(handle, 0, ldf, dxLevel, dtLevel, time,
domainLevel, refLevel);
if (eek != 0)
MayDay::Error("writeFABname: error in writeLEvel");
handle.close();
}
// ---------------------------------------------------------
void
writeNodeLevel(const LevelData<NodeFArrayBox>* a_dataPtr)
{
if (a_dataPtr == NULL) return;
const char* fname = "LDF.hdf5";
writeNodeLevelname(a_dataPtr, fname);
}
// ---------------------------------------------------------
void
viewNodeLevel(const LevelData<NodeFArrayBox>* a_dataPtr)
{
if (a_dataPtr == NULL) return;
const char* fname = tempnam(NULL,NULL);
writeNodeLevelname(a_dataPtr, fname);
VisualizeFile(fname);
}
// ---------------------------------------------------------
void
writeNodeLevelname(const LevelData<NodeFArrayBox>* a_dataPtr,
const char* a_filename)
{
if (a_dataPtr == NULL) return;
const LevelData<NodeFArrayBox>& data = *a_dataPtr;
HDF5Handle handle(a_filename, HDF5Handle::CREATE);
HDF5HeaderData header;
int numlevels = 1;
int nComp = data.nComp();
string filedescriptor("VanillaAMRFileType");
header.m_string ["filetype"] = filedescriptor;
// string centeringdescriptor("node");
// header.m_string ["data_centering"] = centeringdescriptor;
header.m_int ["data_centering"] = 7; // 7 for node-centered data
header.m_int ["num_levels"] = numlevels;
header.m_int ["num_components"] = nComp;
for (int ivar = 0; ivar < nComp; ivar++)
{
char labelChSt[100];
sprintf(labelChSt, "component_%d", ivar);
string label(labelChSt);
header.m_string[label] = label;
}
header.writeToFile(handle);
// need to figure out what domain will contain this LevelData
// This must be LayoutIterator instead of DataIterator because
// we want domain over ALL procs.
const DisjointBoxLayout& levelBoxes = data.getBoxes();
LayoutIterator lit = levelBoxes.layoutIterator();
lit.reset();
Box domain = levelBoxes.get(lit());
for (lit.reset(); lit.ok(); ++lit)
{
const Box thisBox = levelBoxes.get(lit());
D_TERM6(
if (thisBox.smallEnd(0)<domain.smallEnd(0))
domain.setSmall(0,thisBox.smallEnd(0)); ,
if (thisBox.smallEnd(1)<domain.smallEnd(1))
domain.setSmall(1,thisBox.smallEnd(1)); ,
if (thisBox.smallEnd(2)<domain.smallEnd(2))
domain.setSmall(2, thisBox.smallEnd(2)); ,
if (thisBox.smallEnd(3)<domain.smallEnd(3))
domain.setSmall(3,thisBox.smallEnd(3)); ,
if (thisBox.smallEnd(4)<domain.smallEnd(4))
domain.setSmall(4,thisBox.smallEnd(4)); ,
if (thisBox.smallEnd(5)<domain.smallEnd(5))
domain.setSmall(5, thisBox.smallEnd(5)); );
D_TERM6(
if (thisBox.bigEnd(0)>domain.bigEnd(0))
domain.setBig(0,thisBox.bigEnd(0)); ,
if (thisBox.bigEnd(1)>domain.bigEnd(1))
domain.setBig(1,thisBox.bigEnd(1)); ,
if (thisBox.bigEnd(2)>domain.bigEnd(2))
domain.setBig(2, thisBox.bigEnd(2)); ,
if (thisBox.bigEnd(3)>domain.bigEnd(3))
domain.setBig(3,thisBox.bigEnd(3)); ,
if (thisBox.bigEnd(4)>domain.bigEnd(4))
domain.setBig(4,thisBox.bigEnd(4)); ,
if (thisBox.bigEnd(5)>domain.bigEnd(5))
domain.setBig(5, thisBox.bigEnd(5)); );
} // end loop over boxes on level to determine "domain"
// put bogus numbers here
Real dtLevel = 1.0;
Real dxLevel = 1.0;
Real time = 1.0;
int refLevel = 1;
IntVect ghostVect = data.ghostVect();
int eek = writeLevel(handle, 0, data, dxLevel, dtLevel, time,
domain, refLevel, ghostVect);
if (eek != 0)
MayDay::Error("WriteNodeLevelname: error in writeNodeLevel");
handle.close();
}
// ---------------------------------------------------------
void
WritePartialAMRHierarchyHDF5(const string& filename,
const Vector<DisjointBoxLayout>& a_vectGrids,
const Vector<LevelData<NodeFArrayBox>* > & a_vectData,
const Vector<string>& a_vectNames,
const Box& a_baseDomain,
const Real& a_baseDx,
const Real& a_dt,
const Real& a_time,
const Vector<int>& a_vectRatio,
const Interval& a_levels)
{
int numLevels = a_levels.size();
// now make new dataholders which only have numLevels entries,
// and which will move the baseLevel to level 0
Vector<DisjointBoxLayout> newVectGrids(numLevels);
Vector<LevelData<NodeFArrayBox> * > newVectData(numLevels);
Vector<int> newVectRatio(numLevels);
int leveloffset = a_levels.begin();
for (int srcLevel = a_levels.begin(); srcLevel <= a_levels.end(); srcLevel++)
{
int destLevel = srcLevel-leveloffset;
newVectGrids[destLevel] = a_vectGrids[srcLevel];
newVectData[destLevel] = a_vectData[srcLevel];
newVectRatio[destLevel] = a_vectRatio[srcLevel];
}
WriteAMRHierarchyHDF5(filename, newVectGrids, newVectData, a_vectNames,
a_baseDomain, a_baseDx, a_dt, a_time,
newVectRatio, numLevels);
}
// ---------------------------------------------------------
void
WritePartialAMRHierarchyHDF5(const string& filename,
const Vector<DisjointBoxLayout>& a_vectGrids,
const Vector<Vector<LevelData<NodeFArrayBox>* > >& a_vectData,
const Vector<string>& a_vectNames,
const Box& a_baseDomain,
const Real& a_baseDx,
const Real& a_dt,
const Real& a_time,
const Vector<int>& a_vectRatio,
const Interval& a_levels)
{
// We have a_vectData[component][level].
// Each component should have the same number of levels.
int numvarsOrig = a_vectData.size();
int numvars = 0;
Vector<int> numvarsEach(numvarsOrig);
// need at least one set of data.
// let numlevels by the number of levels in the first set.
CH_assert(a_vectData.size() >= 1);
int numlevels = a_vectData[0].size();
for (int ivarOrig = 0; ivarOrig < numvarsOrig; ivarOrig++)
{
CH_assert( a_vectData[ivarOrig].size() >= numlevels );
numvarsEach[ivarOrig] = a_vectData[ivarOrig][0]->nComp();
numvars += numvarsEach[ivarOrig];
}
CH_assert( a_vectNames.size() == numvars );
Vector<LevelData<NodeFArrayBox>* > vectVarsNode(numlevels, NULL);
for (int ilev = 0; ilev < numlevels; ilev++)
{
const DisjointBoxLayout& grids = a_vectGrids[ilev];
// What about ghosts in the LevelData?
// Different variables may have different ghost vectors.
// Solution: dispense with ghosts.
vectVarsNode[ilev] = new LevelData<NodeFArrayBox>(grids, numvars);
LevelData<NodeFArrayBox>& vectVarsNodeLevel = *vectVarsNode[ilev];
int ivar = 0;
for (int ivarOrig = 0; ivarOrig < numvars; ivarOrig++)
for (int ivarEach = 0; ivarEach < numvarsEach[ivarOrig]; ivarEach++)
{
Interval newInterval(ivar, ivar);
Interval oldInterval(ivarEach, ivarEach);
const LevelData<NodeFArrayBox>& dataLevel = *a_vectData[ivar][ilev];
// dataLevel.copyTo(oldInterval, vectVarsNodeLevel, newInterval);
// Use copy() instead of copyTo() because it is more efficient.
for (DataIterator dit = dataLevel.dataIterator(); dit.ok(); ++dit)
{
const NodeFArrayBox& dataLevelNfab = dataLevel[dit()];
NodeFArrayBox& vectVarsNodeLevelNfab = vectVarsNodeLevel[dit()];
Box bx(vectVarsNodeLevelNfab.box()); // no ghosts
vectVarsNodeLevelNfab.copy(bx,
newInterval,
bx,
dataLevelNfab,
oldInterval);
}
ivar++;
}
}
WritePartialAMRHierarchyHDF5(filename,
a_vectGrids,
vectVarsNode,
a_vectNames,
a_baseDomain,
a_baseDx, a_dt, a_time,
a_vectRatio,
a_levels);
for (int ilev = 0; ilev < numlevels; ilev++)
delete vectVarsNode[ilev];
}
#include "NamespaceFooter.H"
#endif // CH_USE_HDF5
| 32.946 | 91 | 0.578462 | [
"vector"
] |
83b15e64bf6290b12f0fc54ab91548525e1d7b7e | 2,776 | hh | C++ | CCured/program-dependence-graph/include/FunctionWrapper.hh | Lightninghkm/DataGuard | 4ac1370f7607cec5fc81c3b57f5a62fb1d40f463 | [
"Apache-2.0"
] | 9 | 2022-02-25T01:48:43.000Z | 2022-03-20T04:48:44.000Z | CCured/program-dependence-graph/include/FunctionWrapper.hh | Lightninghkm/DataGuard | 4ac1370f7607cec5fc81c3b57f5a62fb1d40f463 | [
"Apache-2.0"
] | 1 | 2022-03-19T08:48:07.000Z | 2022-03-21T00:51:51.000Z | CCured/program-dependence-graph/include/FunctionWrapper.hh | Lightninghkm/DataGuard | 4ac1370f7607cec5fc81c3b57f5a62fb1d40f463 | [
"Apache-2.0"
] | null | null | null | #ifndef FUNCTIONWRAPPER_H_
#define FUNCTIONWRAPPER_H_
#include "LLVMEssentials.hh"
#include "Tree.hh"
#include "PDGUtils.hh"
namespace pdg
{
class FunctionWrapper
{
public:
FunctionWrapper(llvm::Function *func)
{
_func = func;
for (auto arg_iter = _func->arg_begin(); arg_iter != _func->arg_end(); arg_iter++)
{
_arg_list.push_back(&*arg_iter);
}
_entry_node = new Node(GraphNodeType::FUNC_ENTRY);
_entry_node->setFunc(*func);
}
llvm::Function *getFunc() const { return _func; }
Node *getEntryNode() { return _entry_node; }
void addInst(llvm::Instruction &i);
void buildFormalTreeForArgs();
void buildFormalTreesForRetVal();
llvm::DIType *getArgDIType(llvm::Argument &arg);
llvm::DIType *getReturnValDIType() { return _ret_val_formal_in_tree->getRootNode()->getDIType(); }
llvm::DILocalVariable *getArgDILocalVar(llvm::Argument &arg);
llvm::AllocaInst *getArgAllocaInst(llvm::Argument &arg);
Tree *getArgFormalInTree(llvm::Argument &arg);
Tree *getArgFormalOutTree(llvm::Argument &arg);
Tree *getRetFormalInTree() { return _ret_val_formal_in_tree; }
Tree *getRetFormalOutTree() { return _ret_val_formal_out_tree; }
std::map<llvm::Argument *, Tree *> &getArgFormalInTreeMap() { return _arg_formal_in_tree_map; }
std::map<llvm::Argument *, Tree *> &getArgFormalOutTreeMap() { return _arg_formal_out_tree_map; }
std::vector<llvm::AllocaInst *> &getAllocInsts() { return _alloca_insts; }
std::vector<llvm::DbgDeclareInst *> &getDbgDeclareInsts() { return _dbg_declare_insts; }
std::vector<llvm::LoadInst *> &getLoadInsts() { return _load_insts; }
std::vector<llvm::StoreInst *> &getStoreInsts() { return _store_insts; }
std::vector<llvm::CallInst *> &getCallInsts() { return _call_insts; }
std::vector<llvm::ReturnInst *> &getReturnInsts() { return _return_insts; }
std::vector<llvm::Argument *> &getArgList() { return _arg_list; }
bool hasNullRetVal() { return (_ret_val_formal_in_tree == nullptr); }
std::set<llvm::Value *> computeAddrVarDerivedFromArg(llvm::Argument &arg);
private:
Node *_entry_node;
llvm::Function *_func;
std::vector<llvm::AllocaInst *> _alloca_insts;
std::vector<llvm::DbgDeclareInst *> _dbg_declare_insts;
std::vector<llvm::LoadInst *> _load_insts;
std::vector<llvm::StoreInst *> _store_insts;
std::vector<llvm::CallInst *> _call_insts;
std::vector<llvm::ReturnInst *> _return_insts;
std::vector<llvm::Argument *> _arg_list;
std::map<llvm::Argument *, Tree *> _arg_formal_in_tree_map;
std::map<llvm::Argument *, Tree *> _arg_formal_out_tree_map;
Tree *_ret_val_formal_in_tree;
Tree *_ret_val_formal_out_tree;
};
} // namespace pdg
#endif | 42.707692 | 102 | 0.701009 | [
"vector"
] |
83b1c3e7e61cef8e03e7195cfefe2c78f1349a17 | 1,865 | cpp | C++ | CrashCourse/CrashCourse/Bullet.cpp | CapySloth/crash-course | f2f7649e1c1d86b459fc4fc0d3b922f4bdf6aaa3 | [
"MIT"
] | null | null | null | CrashCourse/CrashCourse/Bullet.cpp | CapySloth/crash-course | f2f7649e1c1d86b459fc4fc0d3b922f4bdf6aaa3 | [
"MIT"
] | null | null | null | CrashCourse/CrashCourse/Bullet.cpp | CapySloth/crash-course | f2f7649e1c1d86b459fc4fc0d3b922f4bdf6aaa3 | [
"MIT"
] | null | null | null | #include <cmath>
#include <iostream>
#include "Bullet.h"
#include "Utils.h"
#include "Entity.h"
const int Bullet::msDefaultWidth = 5;
const int Bullet::msDefaultHeight = 5;
const sf::Vector2f mVelocity = { 2, 2 };
const sf::Color Bullet::msDefaultColor = { 255, 255, 255, 255 };// white
int i = 0;
Bullet::Bullet()
: mRect()
, mColor()
{
mRect.left = 0;
mRect.top = 0;
mRect.width = msDefaultHeight;
mRect.height = msDefaultWidth;
mColor = msDefaultColor;
active = false;
mRect.top = 100;
mRect.left = 100;
mVelocity;
}
void Bullet::Reset()
{
mRect.left = -500;
mRect.top = -500;
mRect.width = msDefaultWidth;
mRect.height = msDefaultHeight;
mColor = msDefaultColor;
active = false;
mVelocity;
}
void Bullet::Move()
{
////Move the bullet on X axis
mRect.left += getVelocity().x;
////Move the bullet on Y axis
mRect.top += getVelocity().y;
//If the dot collided or went too far up or down
//CheckCollision(mRect, object);
}
void Bullet::CalculateTragectory(float delta, float mHeading) {
float acceleration = 1.0f;
//Determine facing direction vector
float dirX = cos(mHeading);
float dirY = sin(mHeading);
//Calculate velocity for this frame
mVelocity.x = dirX * delta * 500;
mVelocity.y = dirY * delta * 500;
}
void Bullet::Update(float delta)
{
if (mRect.top < 0) {
//mRect.x = mRect.x + 600;
Reset();
}
if (mRect.left > 700) {
Reset();
//mRect.x = mRect.x - 600;
}
if (mRect.top < 0) {
//mRect.y = mRect.y + 600;
Reset();
}
if (mRect.left > 700) {
//mRect.y = mRect.y - 600;
Reset();
}
}
void Bullet::Draw(sf::RenderWindow & window) const
{
if (active) {
sf::RectangleShape bullet(sf::Vector2f(mRect.width, mRect.height));
bullet.setOrigin(sf::Vector2f(1, 1));
bullet.setFillColor(msDefaultColor);
bullet.setPosition(sf::Vector2f(mRect.left, mRect.top));
window.draw(bullet);
}
}
| 19.840426 | 72 | 0.662735 | [
"object",
"vector"
] |
83b34ad9b86dafbd2c05ff45c9011d4e4d414bfe | 5,129 | hpp | C++ | src/vulkan/scene.hpp | shacklettbp/csknowviz | 8c4e1b9f8bc15818ab47e0a6252c168bd9fc25c7 | [
"MIT"
] | null | null | null | src/vulkan/scene.hpp | shacklettbp/csknowviz | 8c4e1b9f8bc15818ab47e0a6252c168bd9fc25c7 | [
"MIT"
] | null | null | null | src/vulkan/scene.hpp | shacklettbp/csknowviz | 8c4e1b9f8bc15818ab47e0a6252c168bd9fc25c7 | [
"MIT"
] | null | null | null | #pragma once
#include <rlpbr/config.hpp>
#include <rlpbr_core/scene.hpp>
#include <filesystem>
#include <list>
#include <mutex>
#include <optional>
#include <string_view>
#include <unordered_map>
#include "descriptors.hpp"
#include "utils.hpp"
#include "core.hpp"
#include "memory.hpp"
#include "shader.hpp"
// Forward declare ktxTexture as kind of an opaque backing data type
struct ktxTexture;
namespace RLpbr {
namespace vk {
struct VulkanScene;
struct BLAS {
VkAccelerationStructureKHR hdl;
VkDeviceAddress devAddr;
};
struct BLASData {
public:
BLASData(const BLASData &) = delete;
BLASData(BLASData &&) = default;
~BLASData();
const DeviceState &dev;
std::vector<BLAS> accelStructs;
LocalBuffer storage;
};
struct TLAS {
VkAccelerationStructureKHR hdl;
std::optional<HostBuffer> buildStorage;
uint32_t numBuildInstances;
std::optional<LocalBuffer> tlasStorage;
VkDeviceAddress tlasStorageDevAddr;
size_t numStorageBytes;
void build(const DeviceState &dev,
MemoryAllocator &alloc,
const std::vector<ObjectInstance> &instances,
const std::vector<InstanceTransform> &instance_transforms,
const std::vector<InstanceFlags> &instance_flags,
const std::vector<ObjectInfo> &objects,
const BLASData &blases,
uint64_t additional_blas_addr,
VkCommandBuffer build_cmd);
void free(const DeviceState &dev);
};
struct ReservoirGrid {
AABB bbox;
VkDeviceMemory storage;
VkDeviceAddress devAddr;
LocalBuffer grid;
};
struct VulkanEnvironment : public EnvironmentBackend {
VulkanEnvironment(const DeviceState &dev, MemoryAllocator &alloc,
const VulkanScene &scene, const Camera &cam);
VulkanEnvironment(const VulkanEnvironment &) = delete;
~VulkanEnvironment();
uint32_t addLight(const glm::vec3 &position, const glm::vec3 &color);
void removeLight(uint32_t light_idx);
std::vector<PackedLight> lights;
const DeviceState &dev;
TLAS tlas;
ReservoirGrid reservoirGrid;
Camera prevCam;
};
struct TextureData {
TextureData(const DeviceState &d, MemoryAllocator &a);
TextureData(const TextureData &) = delete;
TextureData(TextureData &&);
~TextureData();
const DeviceState &dev;
MemoryAllocator &alloc;
VkDeviceMemory memory;
std::vector<LocalTexture> textures;
std::vector<VkImageView> views;
};
struct SharedSceneState {
SharedSceneState(const DeviceState &dev,
VkDescriptorPool scene_pool,
VkDescriptorSetLayout scene_layout,
MemoryAllocator &alloc);
std::mutex lock;
VkDescriptorSet descSet;
HostBuffer addrData;
std::vector<uint32_t> freeSceneIDs;
uint32_t numSceneIDs;
};
class SceneID {
public:
SceneID(SharedSceneState &shared);
SceneID(const SceneID &) = delete;
SceneID(SceneID &&o);
~SceneID();
uint32_t getID() const { return id_; }
private:
SharedSceneState *shared_;
uint32_t id_;
};
struct VulkanScene : public Scene {
TextureData textures;
LocalBuffer data;
VkDeviceSize indexOffset;
uint32_t numMeshes;
std::optional<SceneID> sceneID;
BLASData blases;
};
class VulkanLoader : public LoaderBackend {
public:
VulkanLoader(const DeviceState &dev,
MemoryAllocator &alloc,
const QueueState &transfer_queue,
const QueueState &render_queue,
SharedSceneState &shared_scene_state,
uint32_t render_qf,
uint32_t max_texture_resolution);
VulkanLoader(const DeviceState &dev,
MemoryAllocator &alloc,
const QueueState &transfer_queue,
const QueueState &render_queue,
uint32_t render_qf,
uint32_t max_texture_resolution);
// FIXME get rid of these two hacky params
std::shared_ptr<Scene> loadScene(SceneLoadData &&load_info,
VkDescriptorSet texture_set,
uint32_t scene_id);
std::shared_ptr<Scene> loadScene(SceneLoadData &&load_info);
private:
VulkanLoader(const DeviceState &dev,
MemoryAllocator &alloc,
const QueueState &transfer_queue,
const QueueState &render_queue,
SharedSceneState *shared_scene_state,
VkDescriptorSet scene_set,
uint32_t render_qf,
uint32_t max_texture_resolution);
const DeviceState &dev;
MemoryAllocator &alloc;
const QueueState &transfer_queue_;
const QueueState &render_queue_;
SharedSceneState *shared_scene_state_;
VkDescriptorSet scene_set_;
VkCommandPool transfer_cmd_pool_;
VkCommandBuffer transfer_cmd_;
VkCommandPool render_cmd_pool_;
VkCommandBuffer render_cmd_;
VkSemaphore transfer_sema_;
VkFence fence_;
uint32_t render_qf_;
uint32_t max_texture_resolution_;
};
}
}
| 25.645 | 73 | 0.664457 | [
"vector"
] |
83c2ac835b983e31997d6f7633351c39b6b1d020 | 11,689 | cpp | C++ | src/rpc/interest.cpp | PlatopiaCore/platopia | b0598f4ac9c8b36cfffe9b4a304b8394e03409ca | [
"MIT"
] | 14 | 2018-05-17T04:27:59.000Z | 2019-06-12T02:48:29.000Z | src/rpc/interest.cpp | PlatopiaCore/platopia | b0598f4ac9c8b36cfffe9b4a304b8394e03409ca | [
"MIT"
] | null | null | null | src/rpc/interest.cpp | PlatopiaCore/platopia | b0598f4ac9c8b36cfffe9b4a304b8394e03409ca | [
"MIT"
] | 5 | 2018-05-21T03:57:20.000Z | 2018-12-13T06:12:35.000Z | /*
* interest.cpp
*/
#include "base58.h"
#include "chain.h"
#include "coins.h"
#include "config.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "dstencode.h"
#include "init.h"
#include "keystore.h"
#include "merkleblock.h"
#include "net.h"
#include "policy/policy.h"
#include "primitives/transaction.h"
#include "rpc/server.h"
#include "rpc/tojson.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "script/standard.h"
#include "txmempool.h"
#include "uint256.h"
#include "utilstrencodings.h"
#include "validation.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include "validation.h"
#include <cstdint>
#include <univalue.h>
static UniValue getinterestinfo(const Config &config,
const JSONRPCRequest &request) {
if (request.fHelp || request.params.size() != 0) {
throw std::runtime_error(
"getinterestinfo\n"
"\nReturns the current interest taken and remain in the blockchain.\n"
"\nResult:\n"
"{\n"
" \"total\": 2400000000.00000000, (numeric) total interest\n"
" \"left\": xxx, (numeric) left interest\n"
" \"leftPercentage\": \"xx%\", (percentage) left / total\n"
" \"currentPeriod\": (object) interest info of current period\n"
" {\n"
" \"total\": xxx, (numeric) total interest in current period\n"
" \"taken\": xxx, (numeric) interest taken in current period\n"
" \"takenPercentage\": \"xx%\", (percentage) interest taken percentage in current period\n"
" \"left\": xxx, (numeric) interest left in current period\n"
" \"leftPercentage\": \"xx%\" (percentage) interest left percentage in current period\n"
" }\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getinterestinfo", "") +
HelpExampleRpc("getinterestinfo", ""));
}
double periodMinInterestRate;
CAmount periodTotal;
CAmount periodTaken;
CAmount totalLeft;
if(!GetCurrentInterestInfo(periodMinInterestRate, periodTotal, periodTaken, totalLeft))
{
throw JSONRPCError(RPC_INTERNAL_ERROR,
std::string("Can't get interest info, please retry."));
}
int periodTakenPercentage = static_cast<int>(periodTaken * 100 / periodTotal);
int leftPercentage = static_cast<int>(static_cast<double>(totalLeft) / Params().TotalInterest() * 100);
UniValue results(UniValue::VOBJ);
results.push_back(Pair("total", ValueFromAmount(Params().TotalInterest())));
results.push_back(Pair("left", ValueFromAmount(totalLeft)));
char percent[20] = {0};
sprintf(percent, "%d%%", leftPercentage);
results.push_back(Pair("leftPercentage", UniValue(UniValue::VSTR, string(percent))));
UniValue period(UniValue::VOBJ);
period.push_back(Pair("total", ValueFromAmount(periodTotal)));
period.push_back(Pair("taken", ValueFromAmount(periodTaken)));
sprintf(percent, "%d%%", periodTakenPercentage);
period.push_back(Pair("takenPercentage", UniValue(UniValue::VSTR, string(percent))));
period.push_back(Pair("left", ValueFromAmount(totalLeft)));
sprintf(percent, "%d%%", 100 - periodTakenPercentage);
period.push_back(Pair("leftPercentage", UniValue(UniValue::VSTR, string(percent))));
results.push_back(Pair("currentPeriod", period));
return results;
}
static UniValue getmyinterest(const Config &config,
const JSONRPCRequest &request) {
if (request.fHelp || request.params.size() != 0) {
throw std::runtime_error(
"getmyinterest\n"
"\nReturns my locked principal and interest.\n"
"\nResult:\n"
"{\n"
" \"total\": 2400000000.00000000, (numeric) total interest\n"
" \"left\": xxx, (numeric) left interest\n"
" \"leftPercentage\": \"xx%\", (percentage) left / total\n"
" \"currentPeriod\": (object) interest info of current period\n"
" {\n"
" \"total\": xxx, (numeric) total interest in current period\n"
" \"taken\": xxx, (numeric) interest taken in current period\n"
" \"takenPercentage\": \"xx%\", (percentage) interest taken percentage in current period\n"
" \"left\": xxx, (numeric) interest left in current period\n"
" \"leftPercentage\": \"xx%\" (percentage) interest left percentage in current period\n"
" }\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getmyinterest", "") +
HelpExampleRpc("getmyinterest", ""));
}
CAmount principal(0);
CAmount interest(0);
int currentHeight = chainActive.Height();
std::vector<CTxOutVerbose> vDepositItem;
pwalletMain->GetAllDeposit(vDepositItem);
for(std::vector<CTxOutVerbose>::iterator i = vDepositItem.begin(); i != vDepositItem.end(); ++i)
{
if(currentHeight - i->height + 1 <= i->nLockTime)
{
principal += i->nPrincipal;
interest += i->nValue - i->nPrincipal;
}
}
UniValue results(UniValue::VOBJ);
results.push_back(Pair("LockedPrincipal", ValueFromAmount(principal)));
results.push_back(Pair("LockedInterest", ValueFromAmount(interest)));
return results;
}
static UniValue getinterestlist(const Config &config,
const JSONRPCRequest &request) {
if (request.fHelp || request.params.size() != 0) {
throw std::runtime_error(
"getinterestlist\n"
"\nReturns all interest list.\n"
"\nResult:\n"
"{\n"
" \"lockedDeposit\": locked deposit transactions\n"
" [\n"
" {\n"
" \"txid\": \"txid\",\n"
" \"vout\": n,\n"
" \"remianBlocks\": 15360,\n"
" \"remainDays\": 16,\n"
" \"interestRatePer100Days\": \"1.28571%\", interest rate for 100 block days\n"
" \"principal\": xx,\n"
" \"interest\": xx\n"
" },\n"
" ...\n"
" ],\n"
" \"finishedDeposit\": unlocked deposit transactions\n"
" [\n"
" {\n"
" \"txid\": \"txid\",\n"
" \"vout\": n,\n"
" \"interestRatePer100Days\": \"1.28571%\", interest rate for 100 block days\n"
" \"principal\": xx,\n"
" \"interest\": xx\n"
" },\n"
" ...\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getinterestlist", "") +
HelpExampleRpc("getinterestlist", ""));
}
const int currentHeight = chainActive.Height();
std::vector<CTxOutVerbose> vDepositItem;
pwalletMain->GetAllDeposit(vDepositItem);
UniValue lockedArray(UniValue::VARR);
UniValue releasedArray(UniValue::VARR);
for(std::vector<CTxOutVerbose>::iterator i = vDepositItem.begin(); i != vDepositItem.end(); ++i)
{
int remianBlocks = i->nLockTime - (currentHeight - i->height + 1) + 1;
int remainDays = (remianBlocks + (Params().BlocksPerDay() - 1)) / Params().BlocksPerDay();
UniValue item(UniValue::VOBJ);
if(remianBlocks <= 0)
{
item.push_back(Pair("txid", i->txid.GetHex()));
item.push_back(Pair("vout", i->n));
char interestRateStr[20] = {0};
sprintf(interestRateStr, "%.5f%%", GetInterestRate(i->nLockTime, i->height) * 100);
item.push_back(Pair("interestRatePer100Days", interestRateStr));
item.push_back(Pair("principal", ValueFromAmount(i->nPrincipal)));
item.push_back(Pair("interest", ValueFromAmount(i->nValue - i->nPrincipal)));
releasedArray.push_back(item);
}
else
{
item.push_back(Pair("txid", i->txid.GetHex()));
item.push_back(Pair("vout", i->n));
item.push_back(Pair("remianBlocks", remianBlocks));
item.push_back(Pair("remainDays", remainDays));
char interestRateStr[20] = {0};
sprintf(interestRateStr, "%.5f%%", GetInterestRate(i->nLockTime, i->height) * 100);
item.push_back(Pair("interestRatePer100Days", interestRateStr));
item.push_back(Pair("principal", ValueFromAmount(i->nPrincipal)));
item.push_back(Pair("interest", ValueFromAmount(i->nValue - i->nPrincipal)));
lockedArray.push_back(item);
}
}
UniValue results(UniValue::VOBJ);
results.push_back(Pair("lockedDeposit", lockedArray));
results.push_back(Pair("finishedDeposit", releasedArray));
return results;
}
static UniValue getlockinterest(const Config &config,
const JSONRPCRequest &request) {
if (request.fHelp || request.params.size() != 2) {
throw std::runtime_error(
"getlockinterest lockdays principal\n"
"\nGet interest of principal for lockdays.\n"
"\nArguments:\n"
"1. \"lockdays\" (numeric, required) lockdays, value among [16, 32, 64, 128, 256, 512, 1024]\n"
"2. \"principal\" (numeric, required) amount to deposit\n"
"\nResult:\n"
"{\n"
" \"locktime\":locktime, (numeric) adjusted locktime for interest, may small than given lockdays * 960\n"
" \"interest\":interest, (numeric) interest got\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getlockinterest", "16 123.456") +
HelpExampleRpc("getlockinterest", "16 123.456"));
}
int locktime = request.params[0].get_int() * Params().BlocksPerDay();
if(locktime <= 0)
{
throw JSONRPCError(
RPC_INVALID_PARAMETER,
"Invalid locktime. Locktime must > 0.");
}
CAmount principal = AmountFromValue(request.params[1]);
if(principal <= 0)
{
throw JSONRPCError(
RPC_INVALID_PARAMETER,
"Invalid locktime. satoshi must > 0.");
}
CAmount interest = GetInterest(principal, locktime, chainActive.Height() + 1);
int adjustedLockTime = Params().AdjustToLockInterestThreshold(locktime);
UniValue results(UniValue::VOBJ);
results.push_back(Pair("locktime", adjustedLockTime));
results.push_back(Pair("interest", ValueFromAmount(interest)));
return results;
}
static const CRPCCommand commands[] = {
// category name actor (function) okSafeMode
// ------------------- ------------------------ ---------------------- ----------
{ "interest", "getinterestinfo", getinterestinfo, true, {} },
{ "interest", "getmyinterest", getmyinterest, false, {} },
{ "interest", "getinterestlist", getinterestlist, false, {} },
{ "interest", "getlockinterest", getlockinterest, true, {"lockdays", "principal"} },
};
void RegisterInterestRPCCommands(CRPCTable &t) {
if (GetBoolArg("-disablewallet", false)) {
return;
}
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) {
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
}
| 41.303887 | 120 | 0.564719 | [
"object",
"vector"
] |
83c3eab0dfa1195d5d8ddb7f6ba57d77a829e27d | 8,153 | cpp | C++ | 2nd semester/1st module/Task 5.cpp | a37h/MIPT-OOP-C-course-tasks | 6aeb915f11ba2a3a5a14eef87e703dd430eee76f | [
"MIT"
] | 1 | 2019-10-22T17:28:48.000Z | 2019-10-22T17:28:48.000Z | 2nd semester/1st module/Task 5.cpp | a37h/MIPT-OOP-C-course-tasks | 6aeb915f11ba2a3a5a14eef87e703dd430eee76f | [
"MIT"
] | null | null | null | 2nd semester/1st module/Task 5.cpp | a37h/MIPT-OOP-C-course-tasks | 6aeb915f11ba2a3a5a14eef87e703dd430eee76f | [
"MIT"
] | 1 | 2021-12-29T19:58:03.000Z | 2021-12-29T19:58:03.000Z | // ФИВТ | ООП на C++ | 2 семестр, 1 модуль, задача D
// https://contest.yandex.ru/contest/3970/problems/D/
// ............Зал круглых столов............
// Единственный способ попасть в Зал Круглых Столов – пройти через Колонный Коридор.
// Стены Коридора изображаются на карте прямыми линиями, которые параллельны осиOY системы координат.
// Вход в Коридор находится снизу, а выход из Коридора в Зал – сверху.
// В Коридоре есть цилиндрические(на карте круглые) Колонны одинакового радиуса R.
// Разработайте алгоритм, который по информации о размерах Коридора, и размещения Колонн определяет диаметр
// наибольшего из Круглых Столов, который можно пронести через такой Коридор, сохраняя поверхность Стола
// горизонтальной.
// ............ Формат ввода ............
// В первой строке задано два целых числа XL и XR - x - координаты левой и правой стен Коридора.
// Во второй строке находится целое число R(1≤R≤1000000)(1≤R≤1000000) - радиус всех Колон.
// В третьей - целое число N(1≤N≤200)(1≤N≤200), задающее количество Колон.
// Далее идут N строк, в каждой из которых по два целых числа – x - и y - координаты центра
// соответствующей Колоны.
// Все входные координаты – целые числа, не превышающие по модулю 1000000.
// ............ Формат вывода ............
// Вывести одно число - искомый диаметр наибольшего Стола.
// Диаметр нужно выводить с точностью 3 знака после десятичной точки(даже в случае, если он окажется целым).
// Если нельзя пронести ни одного Стола, то ответ должен быть : 0.000
// Точность 3 знака после точки, по обычнам правилам округления, означает, что ответ, который выводится
// в выходной файл, должен отличатся от точного не более чем на 5×10−45×10−4(то есть на 0.0005). Например,
// если точный ответ 1.234567, то в файле должно находится число 1.235.Если точный ответ 5.0005, то
// необходимо округлять в большую сторону, то есть в файл необходимо вывести 5.001.
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <stack>
double makeDoubleFine(double input)
{
double a = input * 1000;
double b = double(a);
double shit = a - b;
double newResult;
if (shit >= 0.5)
{
return (b / 1000 + 0.001);
}
else
{
return (b / 1000);
}
}
struct Pillar
{
Pillar(double input1, double input2)
: x(input1), y(input2)
{ }
double x, y;
};
struct bfsVerts {
char colour = 0;
double parent = -1;
};
class MatrixGraph {
public:
explicit MatrixGraph(double _verticesCount, double input2) : verticesCount(_verticesCount), edges(_verticesCount), PillarOwnRadius(input2), dfsNeeds(verticesCount) {
for (double i = 0; i < verticesCount; i++) { edges[i].resize(verticesCount); }
}
void AddEdge(double input1, double input2)
{
edges[input1][input2] = 1;
edges[input2][input1] = 1;
}
void GetNearVertices(double vertex, std::vector<double>& vertices) const
{
if (vertices.empty() != 1)
vertices.clear();
for (double i = 0; i < verticesCount; i++)
if (edges[vertex][i] == 1) vertices.push_back(i);
}
void push_Pillar(Pillar *x) { Pillars.push_back(x); Pillars[0]->x; }
double binSearch(double left, double right)
{
double mid = (left + right) / 2;
while (mid != left && mid != right)
{
bool IsThatMidOk = itFits(mid);
if (IsThatMidOk)
{
left = mid;
}
else
{
right = mid;
}
mid = (left + right) / 2;
}
return mid;
}
// Возвращает 1 если inputCurrentMid подходит и путь есть, 0 иначе.
bool itFits(double inputCurrentMid)
{
// Очистим граф и вершины
for (double i = 0; i < verticesCount; i++)
{
for (double j = 0; j < verticesCount; j++)
{
edges[i][j] = 0;
}
dfsNeeds[i].parent = -1;
dfsNeeds[i].colour = 0;
}
// Построим ребра сваязанные с левой стеной
for (double j = 0; j < verticesCount; j++)
{
if ((j != 0) && (_ifEdge_(Pillars[0]->x, 0, Pillars[j]->x, 0, inputCurrentMid, 0)))
{
AddEdge(0, j);
}
}
// Построим ребра сваязанные с правой стеной
for (double j = 0; j < verticesCount; j++)
{
if ((j != 1) && (_ifEdge_(Pillars[1]->x, 0, Pillars[j]->x, 0, inputCurrentMid, 0)))
{
AddEdge(1, j);
}
}
// Построим все остальные ребра
for (double i = 2; i < verticesCount; i++)
{
for (double j = 2; j < verticesCount; j++)
{
if ((i != j) && (_ifEdge_(Pillars[i]->x, Pillars[i]->y, Pillars[j]->x, Pillars[j]->y, inputCurrentMid, 1)))
{
AddEdge(i, j);
}
}
}
// Вызовем DFS от 0 и дойдем (или не дойдем) до 1
bool DidWeMadeItThroughTheCoridor = !dfs(1, 0);
return DidWeMadeItThroughTheCoridor;
}
private:
// Возвращает 1 если найден путь из inputVertFROM в inputVertTO
bool dfs(double inputVertFROM, double inputVertTO)
{
// Очередь для реализации обхода в глубину, сразу закидываем туда начальную вершину
std::stack<double> dfsStack;
dfsStack.push(inputVertFROM);
// Вектор для вызова функции GetNearVerts
std::vector<double> tempVertsVector;
while ((dfsStack.empty() == 0))
{
// Вынимаем элемент из стека
double temporaryVert = dfsStack.top();
dfsStack.pop();
// Получаем список смежных с ним вершин
GetNearVertices(temporaryVert, tempVertsVector);
for (int i = 0; i < tempVertsVector.size(); i++)
{
// Обрабатываем только НЕ родительские вершины
if (tempVertsVector[i] != dfsNeeds[temporaryVert].parent)
{
// Если вершина еще не помечена то кидаем её в очередь на dfs
if (dfsNeeds[tempVertsVector[i]].colour == 0)
{
dfsStack.push(tempVertsVector[i]);
dfsNeeds[tempVertsVector[i]].parent = temporaryVert;
// Отметим её (и не будем вызывать от неё dfs если она уже окрашена)
dfsNeeds[tempVertsVector[i]].colour = 1;
}
// Проверим, пришли ли в конечную вершину
if (tempVertsVector[i] == inputVertTO)
{
for (double i = 0; i < dfsStack.size(); i++)
dfsStack.pop();
return 1;
}
}
}
}
return 0;
}
bool _ifEdge_(double x1, double y1, double x2, double y2, double currentMid, bool wallOrPillar) {
double DistanceBetweenTwoPillars = sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
if (wallOrPillar == 0) // Если стена
{
// Если ребро нужно строить значит расстояние между стеной и пилларом меньше чем радиус пиллара + диаметр стола
return(DistanceBetweenTwoPillars < PillarOwnRadius + currentMid);
}
else
if (wallOrPillar == 1) // Если не стена
{
// Если ребро нужно строить значит расстояние между двумя пилларами меньше чем 2 радиуса пиллара + диаметр стола
return(DistanceBetweenTwoPillars < PillarOwnRadius * 2 + currentMid);
}
}
double verticesCount; // Количество вершин в графе
double PillarOwnRadius; // Радиус колон
std::vector<std::vector<double>> edges; // Матриац смежности
std::vector<Pillar*> Pillars; // Массив колон + стен (левая стена 0, правая стена 1)
std::vector<bfsVerts> dfsNeeds;
};
int main(void)
{
double XL, XR, R, N; // XL - х координата левой стены, XR - х координата правой стены
std::cin >> XL >> XR >> R >> N; // R - радиус колон, N - количество колон
// Построим граф из N+2 вершин (N колон + 2 стены) + закинем радиус R
MatrixGraph task(N + 2, R);
Pillar temp1(XL, -1);
Pillar temp2(XR, -1);
task.push_Pillar(&temp1);
task.push_Pillar(&temp2);
bool ShouldWeEvenWork = 0;
// Вводим координаты всех колон
for (double i = 0; i < N; i++)
{
double Ttemp1, Ttemp2;
std::cin >> Ttemp1;
std::cin >> Ttemp2;
Pillar *Ttemp = new Pillar(Ttemp1, Ttemp2);
task.push_Pillar(Ttemp);
if ((Ttemp1 >= XL) && (Ttemp1 <= XR))
{
ShouldWeEvenWork = 1;
}
}
double result;
if (ShouldWeEvenWork)
{
result = task.binSearch(0, abs(XR - XL));
result = makeDoubleFine(result);
}
else
{
result = XR - XL;
result = makeDoubleFine(result);
}
std::cout.setf(std::ios::fixed);
std::cout << std::setprecision(3) << result;
} | 28.506993 | 167 | 0.636575 | [
"vector"
] |
83cbecf3c3b4d0947fc460ed65f7c7202c5f57e8 | 1,773 | cpp | C++ | Engine/src/graphics/Window.cpp | DaanSander/Polygon-Engine | cdbf42b070c75f37d1e52caa788546f83156d80d | [
"MIT"
] | null | null | null | Engine/src/graphics/Window.cpp | DaanSander/Polygon-Engine | cdbf42b070c75f37d1e52caa788546f83156d80d | [
"MIT"
] | null | null | null | Engine/src/graphics/Window.cpp | DaanSander/Polygon-Engine | cdbf42b070c75f37d1e52caa788546f83156d80d | [
"MIT"
] | null | null | null | #include "Window.h"
namespace engine { namespace graphics {
extern "C" __declspec(dllexport) unsigned int NvOptimusEnablement = 0x1;
Window::Window(unsigned int width, unsigned int height, char* name) {
this->width = width;
this->height = height;
this->name = name;
if (!glfwInit()) {
printf("Could not initialize the glfw library");
return;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(width, height, name, NULL, NULL);
if (!window) {
printf("Could not create window");
glfwTerminate();
return;
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwShowWindow(window);
glfwSetWindowUserPointer(window, this);
this->inputHandler = new io::InputHandler(window);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
}
Window::~Window() {
delete inputHandler;
glfwTerminate();
//glfwDestroyWindow(window);
}
void Window::executeCallbacks(std::vector<EventCallbackfunc> callbacks) {
for (unsigned int i = 0; i < callbacks.size(); i++) {
callbacks[i]();
}
}
void Window::addRenderCallback(EventCallbackfunc callback) {
render_callbacks.push_back(callback);
}
void Window::addUpdateCallback(EventCallbackfunc callback) {
update_callbacks.push_back(callback);
}
void Window::addExitCallback(EventCallbackfunc callback) {
exit_callbacks.push_back(callback);
}
void Window::render() {
glfwSwapBuffers(window);
}
void Window::tick() {
this->inputHandler->tick();
glfwPollEvents();
}
int Window::shouldClose() {
return glfwWindowShouldClose(window);
}
}} | 21.888889 | 74 | 0.72194 | [
"render",
"vector"
] |
83d21bce4b9560f77d00e732ab6e2169efbf4e37 | 3,663 | hpp | C++ | src/Simulation.hpp | ericwolter/position-based-fluids | 30e92ead037b397573a0b7fb9fbac3770093793a | [
"MIT"
] | 2 | 2018-01-03T01:26:54.000Z | 2022-01-01T08:43:04.000Z | src/Simulation.hpp | ericwolter/position-based-fluids | 30e92ead037b397573a0b7fb9fbac3770093793a | [
"MIT"
] | null | null | null | src/Simulation.hpp | ericwolter/position-based-fluids | 30e92ead037b397573a0b7fb9fbac3770093793a | [
"MIT"
] | null | null | null | #ifndef __SIMULATION_HPP
#define __SIMULATION_HPP
#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <cmath>
#include <stdexcept>
#include <assert.h>
#include <algorithm>
#include "hesp.hpp"
#include "Parameters.hpp"
#include "Particle.hpp"
#include "OCLPerfMon.h"
#include "OCL_Logger.h"
#include <GLFW/glfw3.h>
// Macro used for the end of cell list
static const int END_OF_CELL_LIST = -1;
using std::map;
using std::vector;
using std::string;
class Simulation
{
private:
// Avoid copy
Simulation &operator=(const Simulation &other);
Simulation (const Simulation &other);
// Init particles positions
void CreateParticles();
// Create cached buffers
cl::Memory CreateCachedBuffer(cl::ImageFormat& format, int elements);
// Lock and unlock opengl objects
void LockGLObjects();
void UnlockGLObjects();
public:
// OpenCL objects supplied by OpenCL setup
const cl::Context &mCLContext;
const cl::Device &mCLDevice;
// holds all OpenCL kernels required for the simulation
map<string, cl::Kernel> mKernels;
// command queue all OpenCL calls are run on
cl::CommandQueue mQueue;
// ranges used for executing the kernels
cl::NDRange mGlobalRange;
cl::NDRange mLocalRange;
// The device memory buffers holding the simulation data
cl::Buffer mCellsBuffer;
cl::Buffer mParticlesListBuffer;
cl::Buffer mFriendsListBuffer;
cl::BufferGL mPositionsPingBuffer;
cl::BufferGL mPositionsPongBuffer;
cl::Memory mPredictedPingBuffer;
cl::Memory mPredictedPongBuffer;
cl::Buffer mVelocitiesBuffer;
cl::Buffer mDensityBuffer;
cl::Buffer mLambdaBuffer;
cl::Buffer mDeltaBuffer;
cl::Buffer mOmegaBuffer;
cl::Buffer mParameters;
cl::Image2D mSurfacesMask;
cl::Image2DGL mParticlePosImg;
// Radix related
cl_uint mKeysCount;
cl::Buffer mInKeysBuffer;
cl::Buffer mInPermutationBuffer;
cl::Buffer mOutKeysBuffer;
cl::Buffer mOutPermutationBuffer;
cl::Buffer mHistogramBuffer;
cl::Buffer mGlobSumBuffer;
cl::Buffer mHistoTempBuffer;
// OpenGL locking related
vector<cl::Memory> mGLLockList;
// Private member functions
void updateCells();
void updateVelocities();
void applyViscosity();
void applyVorticity();
void predictPositions();
void buildFriendsList();
void updatePredicted(int iterationIndex);
void computeScaling(int iterationIndex);
void computeDelta(int iterationIndex);
void radixsort();
void packData(cl::Memory& sourceImg, cl::Memory& pongImg, cl::Buffer packSource, int iterationIndex);
public:
// Default constructor.
explicit Simulation(const cl::Context &clContext, const cl::Device &clDevice);
// Destructor.
~Simulation ();
// Create all buffer and particles
void InitBuffers();
// Init Grid
void InitCells();
// Load force masks
void LoadForceMasks();
// Load and build kernels
bool InitKernels();
// Perform single simulation step
void Step();
// Get a list of kernel files
const std::string *KernelFileList();
public:
// Open GL Sharing buffers
GLuint mSharedPingBufferID;
GLuint mSharedPongBufferID;
// Open GL Sharing Texture buffer
GLuint mSharedParticlesPos;
GLuint mSharedFriendsList;
// Performance measurement
OCLPerfMon PerfData;
// OCL Logging
OCL_Logger oclLog;
// Rendering state
bool bPauseSim;
bool bReadFriendsList;
bool bDumpParticlesData;
cl_float fWavePos;
};
#endif // __SIMULATION_HPP
| 23.785714 | 106 | 0.693967 | [
"vector"
] |
83d25cb04fcdee6a99d83f3c9f6d9edd0a5c31d7 | 4,737 | cpp | C++ | Sources/Internal/Systems/RenderSystem.cpp | nameless323/KiotoEngine | 3db271540b4cacdfbca697acfa029dd8caf72761 | [
"MIT"
] | 4 | 2019-04-26T15:48:10.000Z | 2020-06-02T02:15:07.000Z | Sources/Internal/Systems/RenderSystem.cpp | nameless323/KiotoEngine | 3db271540b4cacdfbca697acfa029dd8caf72761 | [
"MIT"
] | 2 | 2017-08-11T10:49:55.000Z | 2020-04-04T13:20:22.000Z | Sources/Internal/Systems/RenderSystem.cpp | nameless323/KiotoEngine | 3db271540b4cacdfbca697acfa029dd8caf72761 | [
"MIT"
] | 1 | 2021-02-07T08:28:04.000Z | 2021-02-07T08:28:04.000Z | #include "stdafx.h"
#include "Systems/RenderSystem.h"
#include "AssetsSystem/AssetsSystem.h"
#include "Component/LightComponent.h"
#include "Component/RenderComponent.h"
#include "Core/ECS/Entity.h"
#include "Render/Geometry/Mesh.h"
#include "Render/Material.h"
#include "Render/Shader.h"
#include "Render/RenderObject.h"
#include "Render/RenderSettings.h"
#include "Render/RenderPass/ForwardRenderPass.h"
#include "Render/RenderPass/WireframeRenderPass.h"
#include "Render/RenderPass/GrayscaleRenderPass.h"
#include "Render/RenderPass/EditorGizmosPass.h"
#include "Render/RenderPass/ShadowMapRenderPass.h"
namespace Kioto
{
static constexpr uint32 MAX_LIGHTS_COUNT = 256;
RenderSystem::RenderSystem()
{
m_renderPasses.reserve(Kioto::RenderSettings::MaxRenderPassesCount);
m_drawData.RenderObjects.reserve(2048);
m_drawData.Lights.reserve(MAX_LIGHTS_COUNT);
m_components.reserve(2048);
m_lights.reserve(256);
}
void RenderSystem::Init()
{
AddRenderPass(new Renderer::ShadowMapRenderPass);
m_forwardRenderPass = new Renderer::ForwardRenderPass();
AddRenderPass(m_forwardRenderPass);
AddRenderPass(new Renderer::EditorGizmosPass());
AddRenderPass(new Renderer::GrayscaleRenderPass());
AddRenderPass(new Renderer::WireframeRenderPass());
}
void RenderSystem::OnEntityAdd(Entity* entity)
{
ParseLights(entity);
ParseRenderComponents(entity);
}
void RenderSystem::OnEntityRemove(Entity* entity)
{
TryRemoveLight(entity);
TryRemoveRenderComponent(entity);
}
void RenderSystem::Update(float32 dt)
{
for (auto rc : m_components)
{
if (!rc->GetIsEnabled())
continue;
Renderer::RenderObject* ro = rc->GetRenderObject();
TransformComponent* tc = rc->GetEntity()->GetTransform();
ro->SetToWorld(tc->GetToWorld());
ro->SetToModel(tc->GetToModel());
m_drawData.RenderObjects.push_back(ro); // [a_vorontcov] TODO: Don't like copying this around.
}
for (auto l : m_lights)
{
if (!l->GetIsEnabled())
continue;
l->GetLight()->Position = l->GetEntity()->GetTransform()->GetWorldPosition();
m_drawData.Lights.push_back(l->GetLight());
}
for (auto pass : m_renderPasses)
m_renderGraph.AddPass(pass);
m_renderGraph.SheduleGraph();
m_renderGraph.Execute(m_drawData);
m_drawData.RenderObjects.clear();
m_drawData.Lights.clear();
}
void RenderSystem::Draw()
{
m_renderGraph.Submit();
}
void RenderSystem::Shutdown()
{
for (auto it : m_renderPasses)
SafeDelete(it);
m_renderPasses.clear();
m_lights.clear();
}
void RenderSystem::AddRenderPass(Renderer::RenderPass* pass)
{
m_renderPasses.push_back(pass);
}
void RenderSystem::RemoveRenderPass(Renderer::RenderPass* pass)
{
m_renderPasses.erase(std::remove(m_renderPasses.begin(), m_renderPasses.end(), pass), m_renderPasses.end());
SafeDelete(pass);
}
void RenderSystem::ParseLights(Entity* entity)
{
LightComponent* light = entity->GetComponent<LightComponent>();
if (light == nullptr)
return;
m_lights.push_back(light);
}
void RenderSystem::ParseRenderComponents(Entity* entity)
{
RenderComponent* renderComponent = entity->GetComponent<RenderComponent>();
if (renderComponent == nullptr)
return;
Renderer::RenderObject* ro = new Renderer::RenderObject();
std::string materialName = AssetsSystem::GetAssetFullPath(renderComponent->GetMaterial());
std::string meshName = AssetsSystem::GetAssetFullPath(renderComponent->GetMesh());
assert(!materialName.empty() && !meshName.empty());
Renderer::Material* material = AssetsSystem::GetRenderAssetsManager()->GetOrLoadAsset<Renderer::Material>(materialName);
ro->SetMaterial(material);
ro->SetMesh(AssetsSystem::GetRenderAssetsManager()->GetOrLoadAsset<Renderer::Mesh>(meshName));
Renderer::RegisterRenderObject(*ro);
renderComponent->SetRenderObject(ro);
m_components.push_back(renderComponent);
}
void RenderSystem::TryRemoveLight(Entity* entity)
{
LightComponent* light = entity->GetComponent<LightComponent>();
if (light == nullptr)
return;
auto it = std::find(m_lights.begin(), m_lights.end(), light);
if (it != m_lights.end())
m_lights.erase(it);
}
void RenderSystem::TryRemoveRenderComponent(Entity* entity)
{
RenderComponent* t = entity->GetComponent<RenderComponent>();
if (t == nullptr)
return;
auto it = std::find(m_components.begin(), m_components.end(), t);
if (it != m_components.end())
{
Renderer::RenderObject* ro = t->GetRenderObject();
SafeDelete(ro);
t->SetRenderObject(nullptr);
m_components.erase(it);
}
}
} | 29.240741 | 124 | 0.708887 | [
"mesh",
"geometry",
"render"
] |
83d5fd2a135e34114e95dfe4d7d21f6b1f724e64 | 2,121 | inl | C++ | src/cunumeric/matrix/potrf_template.inl | bryevdv/cunumeric | 7965ceb96d3252371c22cf32d38ac91c4db77a38 | [
"Apache-2.0"
] | null | null | null | src/cunumeric/matrix/potrf_template.inl | bryevdv/cunumeric | 7965ceb96d3252371c22cf32d38ac91c4db77a38 | [
"Apache-2.0"
] | null | null | null | src/cunumeric/matrix/potrf_template.inl | bryevdv/cunumeric | 7965ceb96d3252371c22cf32d38ac91c4db77a38 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021-2022 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace cunumeric {
using namespace Legion;
using namespace legate;
template <VariantKind KIND, LegateTypeCode CODE>
struct PotrfImplBody;
template <LegateTypeCode CODE>
struct support_potrf : std::false_type {
};
template <>
struct support_potrf<LegateTypeCode::DOUBLE_LT> : std::true_type {
};
template <>
struct support_potrf<LegateTypeCode::FLOAT_LT> : std::true_type {
};
template <>
struct support_potrf<LegateTypeCode::COMPLEX64_LT> : std::true_type {
};
template <>
struct support_potrf<LegateTypeCode::COMPLEX128_LT> : std::true_type {
};
template <VariantKind KIND>
struct PotrfImpl {
template <LegateTypeCode CODE, std::enable_if_t<support_potrf<CODE>::value>* = nullptr>
void operator()(Array& array) const
{
using VAL = legate_type_of<CODE>;
auto shape = array.shape<2>();
if (shape.empty()) return;
size_t strides[2];
auto arr = array.write_accessor<VAL, 2>(shape).ptr(shape, strides);
auto m = static_cast<int32_t>(shape.hi[0] - shape.lo[0] + 1);
auto n = static_cast<int32_t>(shape.hi[1] - shape.lo[1] + 1);
assert(m > 0 && n > 0);
PotrfImplBody<KIND, CODE>()(arr, m, n);
}
template <LegateTypeCode CODE, std::enable_if_t<!support_potrf<CODE>::value>* = nullptr>
void operator()(Array& array) const
{
assert(false);
}
};
template <VariantKind KIND>
static void potrf_template(TaskContext& context)
{
auto& array = context.outputs()[0];
type_dispatch(array.code(), PotrfImpl<KIND>{}, array);
}
} // namespace cunumeric
| 27.545455 | 90 | 0.712871 | [
"shape"
] |
83d6edc53585b0bab4cbda01207ab2312bd1a003 | 24,158 | cpp | C++ | Core/Utilities/QProgInfo/Visualization/DrawLatex.cpp | shenzhi-git/QPanda-2 | 62daccc913cfd5984c0b2ac27b7ef0574c921c29 | [
"Apache-2.0"
] | null | null | null | Core/Utilities/QProgInfo/Visualization/DrawLatex.cpp | shenzhi-git/QPanda-2 | 62daccc913cfd5984c0b2ac27b7ef0574c921c29 | [
"Apache-2.0"
] | null | null | null | Core/Utilities/QProgInfo/Visualization/DrawLatex.cpp | shenzhi-git/QPanda-2 | 62daccc913cfd5984c0b2ac27b7ef0574c921c29 | [
"Apache-2.0"
] | null | null | null | #include "Core/Utilities/QProgInfo/Visualization/DrawLatex.h"
#include "Core/QuantumCircuit/QGate.h"
#include "Core/QuantumCircuit/QGlobalVariable.h"
#include "Core/QuantumCircuit/QuantumMeasure.h"
#include <sstream>
#include <memory>
#include <fstream>
namespace // namespace LATEX TOOL
{
const std::string LATEX_QWIRE = "\\qw";
const std::string LATEX_CWIRE = "\\cw";
/* special gate symbol */
const std::string LATEX_SWAP = "\\qswap";
const std::string LATEX_CNOT = "\\targ";
const std::string LATEX_MEASURE = "\\meter";
const std::string LATEX_RESET = "\\gate{\\mathrm{\\left|0\\right\\rangle}}";
const std::string LATEX_HEADER = "\\documentclass[border=2px]{standalone}\n"
"\n"
"\\usepackage[braket, qm]{qcircuit}\n"
"\\usepackage{graphicx}\n"
"\n"
"\\begin{document}\n"
"\\scalebox{1.0}{\n"
"\\Qcircuit @C = 1.0em @R = 0.2em @!R{ \\\\\n";
const std::string LATEX_FOOTER = "\\\\ }}\n"
"\\end{document}\n";
std::string latex_qubit(uint64_t qid)
{
/*
latex syntax:
\ghost command is used to get the spacing
and connections right. \ghost behaves like an invisible
gate that allows the quantum wires on either side of your
multigate to connect correctly.
In addition it is possible to use a classical input to a
gate with \cghost, or no input with \nghost.
The \lstick command is used
for input labels (on the left of the diagram), and the
\rstick command is used for output labels (on the right
of the diagram)
@see latex package qcircuit tutorial
*/
std::stringstream ss;
ss << "\\nghost{{q}_{" << qid << "}: \\ket{0}} & \\lstick{{q}_{" << qid << "}: \\ket{0}}";
return std::move(ss.str());
}
std::string latex_cbit(uint64_t qid)
{
std::stringstream ss;
ss << "\\nghost{\\mathrm{{c}_{" << qid << "} : 0}} & \\lstick{\\mathrm{{c}_{" << qid << "} : 0}}";
return std::move(ss.str());
}
std::string latex_ctrl(uint64_t ctrl, uint64_t target)
{
std::stringstream ss;
ss << "\\ctrl{" << (int)target - (int)ctrl << "}";
return std::move(ss.str());
}
/**
* @brief generate single bits gate latex str
*
* @param[in] gate_name name of gate
* @param[in] qbits not used
* @param[in] param gate param
* @param[in] is_dagger gate is dagger
* @return gate latex string
*/
std::vector<std::string> latex_single_bit_gate(const std::string &gate_name,
std::vector<size_t> qbits,
const std::string ¶m = "",
bool is_dagger = false)
{
std::string gate_latex = "\\gate{\\mathrm{" + gate_name + "}" +
(!param.empty() ? "\\,\\mathrm{" + param + "}" : "") +
(is_dagger ? "^\\dagger" : "") + "}";
return {gate_latex};
}
/**
* @brief generate mulit bits gate latex str
*
* @param[in] gate_name name of gate
* @param[in] qbits gate qbits id
* @param[in] param gate param
* @param[in] is_dagger gate is dagger
* @return gate latex string, matchs qbits
*/
std::vector<std::string> latex_multi_bits_gate(const std::string &gate_name,
std::vector<size_t> qbits,
const std::string ¶m = "",
bool is_dagger = false)
{
QPANDA_ASSERT(2 > qbits.size(), "Mulit bits gate have at least two target bits");
std::vector<std::string> gate_latex;
int row_span_offset = int(qbits.back()) - int(qbits.front());
std::stringstream ss;
ss << "\\multigate{" << row_span_offset << "}"
<< "{\\mathrm{" + gate_name + "}" << (!param.empty() ? "\\,(\\mathrm{" + param + "})}" : "}")
<< "_<<<{" << qbits.front() << "}";
gate_latex.push_back(ss.str());
for (size_t i = 1; i < qbits.size(); i++)
{
std::stringstream ss;
ss << "\\ghost{\\mathrm{" + gate_name + "}" << (!param.empty() ? "\\,(\\mathrm{" + param + "})}" : "}")
<< "_<<<{" << qbits.at(i) << "}";
gate_latex.push_back(ss.str());
}
return gate_latex;
}
/**
* @brief generate ctrl gate latex str
*
* @param[in] gate_name name of gate
* @param[in] qbits gate qbits id
* @param[in] param gate param
* @param[in] is_dagger gate is dagger
* @return gate latex string, matchs qbits
*/
std::vector<std::string> latex_ctrl_gate(const std::string &gate_name,
std::vector<size_t> qbits,
const std::string ¶m = "",
bool is_dagger = false)
{
QPANDA_ASSERT(2 != qbits.size(), "Ctrl gate should have two target bits");
std::vector<std::string> gate_latex;
/* qbits.front() is control bit, qbits.back() is target bit */
uint64_t ctrl_bit = qbits.front();
uint64_t target_bit = qbits.back();
std::string ctrl_latex = latex_ctrl(ctrl_bit, target_bit);
if ("CNOT" == gate_name)
{
gate_latex.emplace_back(ctrl_latex);
gate_latex.emplace_back(LATEX_CNOT);
}
else
{
std::string gate = "\\gate{\\mathrm{" + gate_name + "}" +
(!param.empty() ? "\\,\\mathrm{" + param + "}" : "") +
(is_dagger ? "^\\dagger" : "") +
"}";
gate_latex.emplace_back(ctrl_latex);
gate_latex.emplace_back(gate);
}
return gate_latex;
}
/**
* @brief generate swap gate latex str
*
* @param[in] gate_name name of gate
* @param[in] qbits gate qbits id
* @param[in] param gate param
* @param[in] is_dagger gate is dagger
* @return gate latex string, matchs qbits
*/
std::vector<std::string> latex_swap_gate(const std::string &gate_name,
std::vector<size_t> qbits,
const std::string ¶m = "",
bool is_dagger = false)
{
QPANDA_ASSERT(2 != qbits.size(), "Swap gate should have two target bits");
std::vector<std::string> gate_latex;
uint64_t qbit1 = qbits.front();
uint64_t qbit2 = qbits.back();
int offset = (int)qbit1 - (int)qbit2;
std::stringstream ss;
ss << "\\qwx[" << offset << "]";
std::string swap_qwx = LATEX_SWAP + ss.str();
if (offset > 0)
{
gate_latex.emplace_back(swap_qwx);
gate_latex.emplace_back(LATEX_SWAP);
}
else if (offset < 0)
{
gate_latex.emplace_back(LATEX_SWAP);
gate_latex.emplace_back(swap_qwx);
}
else
{
QCERR_AND_THROW(std::runtime_error, "Swap self");
}
return gate_latex;
}
/**
* @brief get measure to cbit latex statement
*
* @param[in] cbit classic bit id
* @param[in] qbit quantum bit id
* @param[in] total_qbit_size total quantum bit size
* @return measure to cbit latex statement
*/
std::string latex_measure_to(uint64_t cbit, uint64_t qbit, size_t total_qbit_size)
{
std::stringstream ss;
ss << "\\dstick{_{_{\\hspace{0.0em}" << cbit << "}}} \\cw \\ar @{<=} ["
<< (int)qbit - (int)cbit - (int)total_qbit_size << ", 0]";
return std::move(ss.str());
}
std::string latex_barrier(size_t span_start, size_t span_end)
{
std::stringstream ss;
ss << "\\barrier[0em]{" << span_end - span_start << "}";
return std::move(ss.str());
}
} // namespace LATEX TOOL
namespace // namespace utils
{
auto compare_int_min = [](const int &q1, const int &q2)
{ return q1 < q2; };
} // namespace utils
QPANDA_BEGIN
DrawLatex::DrawLatex(const QProg &prog, LayeredTopoSeq &layer_info, uint32_t length)
: AbstractDraw(prog, layer_info, length),
m_latex_qwire(LATEX_QWIRE),
m_latex_cwire(LATEX_CWIRE),
m_latex_time_seq("")
{
}
void DrawLatex::init(std::vector<int> &qbits, std::vector<int> &cbits)
{
/* insert qbits and cbits to latex matrix first col */
std::vector<int>::iterator max_qid_it = std::max_element(qbits.begin(), qbits.end());
std::vector<int>::iterator max_cid_it = std::max_element(cbits.begin(), cbits.end());
int max_qid = -1;
int max_cid = -1;
if (max_qid_it != qbits.end())
max_qid = *max_qid_it;
if (max_cid_it != cbits.end())
max_cid = *max_cid_it;
for (int i = 0; i <= max_qid; i++)
{
m_latex_qwire.insert(i, 0, latex_qubit(i));
}
for (int i = 0; i <= max_cid; i++)
{
m_latex_cwire.insert(i, 0, latex_cbit(i));
}
}
void DrawLatex::draw_by_layer()
{
const auto &layer_info = m_layer_info;
uint32_t layer_id = 0;
for (auto seq_item_itr = layer_info.begin(); seq_item_itr != layer_info.end(); ++seq_item_itr, ++layer_id)
{
for (auto &seq_node_item : (*seq_item_itr))
{
auto opt_node_info = seq_node_item.first;
append_node((DAGNodeType)(opt_node_info->m_type), opt_node_info, layer_id);
}
}
}
void DrawLatex::append_node(DAGNodeType t, pOptimizerNodeInfo &node_info, uint64_t layer_id)
{
if (DAGNodeType::NUKNOW_SEQ_NODE_TYPE < t && t <= DAGNodeType::MAX_GATE_TYPE)
{
append_gate(node_info, layer_id);
}
else if (DAGNodeType::MEASURE == t)
{
append_measure(node_info, layer_id);
}
else if (DAGNodeType::RESET == t)
{
append_reset(node_info, layer_id);
}
else if (DAGNodeType::QUBIT == t)
{
QCERR_AND_THROW(std::runtime_error, "OptimizerNodeInfo shuould not contain qubits");
}
else
{
QCERR_AND_THROW(std::runtime_error, "OptimizerNodeInfo contains uknown nodes");
}
}
int DrawLatex::update_layer_time_seq(int time_seq)
{
m_layer_max_time_seq = std::max(m_layer_max_time_seq, time_seq);
return m_layer_max_time_seq;
}
void DrawLatex::append_gate(pOptimizerNodeInfo &node_info, uint64_t layer_id)
{
GateType gate_type = (GateType)(node_info->m_type);
if (BARRIER_GATE == gate_type)
{
/*
in qpanda barrier is a special single bit gate
we process barrier in different way
and barrier won't comsume time
*/
return append_barrier(node_info, layer_id);
}
QVec qubits_vec = node_info->m_target_qubits;
QVec ctrl_vec = node_info->m_control_qubits;
std::shared_ptr<AbstractQGateNode> p_gate = std::dynamic_pointer_cast<AbstractQGateNode>(*(node_info->m_iter));
/* get gate name */
std::string gate_name = TransformQGateType::getInstance()[gate_type];
/* get gate parameter */
std::string gate_param;
get_gate_parameter(p_gate, gate_param);
/* get dagger */
bool is_dagger = check_dagger(p_gate, p_gate->isDagger());
int gate_time_seq = 0;
std::vector<std::string> gate_latex_str;
/* get qbits id */
std::vector<size_t> qubits_id;
std::for_each(qubits_vec.begin(), qubits_vec.end(), [&qubits_id](const Qubit *qbit)
{ qubits_id.emplace_back(qbit->getPhysicalQubitPtr()->getQubitAddr()); });
/* get gate span rows */
std::vector<size_t> used_bits(qubits_id);
for (auto q_ptr : ctrl_vec)
{
used_bits.emplace_back(q_ptr->getPhysicalQubitPtr()->getQubitAddr());
}
auto target_span = std::minmax_element(used_bits.begin(), used_bits.end(), compare_int_min);
size_t span_start = *target_span.first;
size_t span_end = *target_span.second;
/* get gate latex matrix dst col */
size_t gate_col = get_dst_col(layer_id, span_start, span_end);
/* trick for put gate span qwires placeholder in matrix, then next gate will not appear at occupied qwires */
for (size_t r = span_start; r <= span_end; r++)
{
/*
if qubit is not used, m_latex_qwire[r][0] should be default
then not marked m_latex_qwire[r][gate_col] as span row
*/
// if (!m_latex_qwire.is_empty(r, 0))
// {
m_latex_qwire.insert(r, gate_col, LATEX_QWIRE);
// }
}
switch (gate_type)
{
case ISWAP_THETA_GATE:
case ISWAP_GATE:
case SQISWAP_GATE:
case SWAP_GATE:
{
gate_latex_str = latex_swap_gate(gate_name, qubits_id, gate_param, is_dagger);
/*
record layer time sequnce
FIXME:this time calcutaion code is from DraPicture, I can't explain why,
why add control bits size multiplied with swap gate time?
*/
gate_time_seq = m_time_sequence_conf.get_swap_gate_time_sequence() * (ctrl_vec.size() + 1);
break;
}
case CU_GATE:
case CNOT_GATE:
case CZ_GATE:
case CP_GATE:
case CPHASE_GATE:
{
if (CPHASE_GATE == gate_type)
{
gate_name = "CR";
}
gate_latex_str = latex_ctrl_gate(gate_name, qubits_id, gate_param, is_dagger);
gate_time_seq = m_time_sequence_conf.get_ctrl_node_time_sequence() * (ctrl_vec.size() + 1);
break;
}
case TWO_QUBIT_GATE:
case TOFFOLI_GATE:
case ORACLE_GATE:
{
gate_latex_str = latex_multi_bits_gate(gate_name, qubits_id, gate_param, is_dagger);
break;
}
case BARRIER_GATE:
{
QCERR_AND_THROW(std::runtime_error, "BARRIER_GATE should be processd in another way");
break;
}
/*
single target bit gate:
P0_GATE,
P1_GATE,
PAULI_X_GATE,
PAULI_Y_GATE,
PAULI_Z_GATE,
X_HALF_PI,
Y_HALF_PI,
Z_HALF_PI,
P_GATE,
HADAMARD_GATE,
T_GATE,
S_GATE,
RX_GATE,
RY_GATE,
RZ_GATE,
RPHI_GATE,
U1_GATE,
U2_GATE,
U3_GATE,
U4_GATE,
P00_GATE,
P11_GATE,
I_GATE,
ECHO_GATE,
*/
default:
gate_latex_str = latex_single_bit_gate(gate_name, qubits_id, gate_param, is_dagger);
gate_time_seq = ctrl_vec.size() > 0 ? (m_time_sequence_conf.get_ctrl_node_time_sequence() * ctrl_vec.size()) : m_time_sequence_conf.get_single_gate_time_sequence();
break;
}
/* insert gate latex statement to matrix, row = qibit id */
for (size_t i = 0; i < qubits_id.size(); ++i)
{
size_t gate_row = qubits_id.at(i);
/* gate_latex_str matchs qubits_id sequnce */
m_latex_qwire.insert(gate_row, gate_col, gate_latex_str.at(i));
}
/* insert crtl latex statement to matrix */
size_t ctrl_col = gate_col;
size_t target_qubit_id = qubits_vec.front()->getPhysicalQubitPtr()->getQubitAddr();
for (const auto qbit : ctrl_vec)
{
size_t ctrl_qbit_id = qbit->getPhysicalQubitPtr()->getQubitAddr();
std::string gate_ctrl_latex_str = latex_ctrl(ctrl_qbit_id, target_qubit_id);
uint64_t ctrl_row = ctrl_qbit_id;
m_latex_qwire.insert(ctrl_row, ctrl_col, gate_ctrl_latex_str);
}
/* update curent layer latex matrix col range */
m_layer_col_range[layer_id] = std::max(gate_col, m_layer_col_range[layer_id]);
/* record layer time sequnce*/
update_layer_time_seq(gate_time_seq);
}
void DrawLatex::append_barrier(pOptimizerNodeInfo &node_info, uint64_t layer_id)
{
/* get target bits */
QVec qubits_vec = node_info->m_target_qubits;
QPANDA_ASSERT(qubits_vec.size() != 1, "barrier should only have one target bit");
/* get control info */
QVec ctrl_vec = node_info->m_control_qubits;
/* barrier is special single bit gate in qpanda, qubits_vec and ctrl_vec contains all qibits be barriered */
/* gather barrier sapn qubit rows */
std::vector<size_t> span_id;
std::for_each(qubits_vec.begin(), qubits_vec.end(), [&span_id](const Qubit *qbit)
{ span_id.push_back(qbit->getPhysicalQubitPtr()->getQubitAddr()); });
std::for_each(ctrl_vec.begin(), ctrl_vec.end(), [&span_id](const Qubit *qbit)
{ span_id.push_back(qbit->getPhysicalQubitPtr()->getQubitAddr()); });
auto target_span = std::minmax_element(span_id.begin(), span_id.end(), compare_int_min);
size_t span_start = *target_span.first;
size_t span_end = *target_span.second;
size_t barrier_col = get_dst_col(layer_id, span_start, span_end);
/*
barrier is special in latex.
for current col barrier, it's latex statment "\barrier" is append to gate or qwire last col
like "\qw \barrier[0em]{1}"
barrier always append to latex content before current col, so minus 1
*/
barrier_col -= 1;
size_t barrier_row = qubits_vec.front()->getPhysicalQubitPtr()->getQubitAddr();
std::string barrier_latex = latex_barrier(span_start, span_end);
/* insert barrier to matrix */
if (m_latex_qwire.is_empty(barrier_row, barrier_col))
{
barrier_latex = LATEX_QWIRE + " " + barrier_latex;
}
else
{
barrier_latex = m_latex_qwire[barrier_row][barrier_col] + " " + barrier_latex;
}
m_latex_qwire.insert(barrier_row, barrier_col, barrier_latex);
/*
record curent layer end at latex matrix col,
barrier should occupy barrier_col + 1 for barrirer_col had minused 1
*/
m_layer_col_range[layer_id] = std::max(barrier_col + 1, m_layer_col_range[layer_id]);
}
void DrawLatex::append_measure(pOptimizerNodeInfo &node_info, uint64_t layer_id)
{
std::shared_ptr<AbstractQuantumMeasure> p_measure = std::dynamic_pointer_cast<AbstractQuantumMeasure>(*(node_info->m_iter));
size_t qbit_id = p_measure->getQuBit()->getPhysicalQubitPtr()->getQubitAddr();
size_t cbit_id = p_measure->getCBit()->get_addr();
size_t qbits_row = m_latex_qwire.max_row();
size_t total_qbits_size = qbits_row ? qbits_row + 1 : 0;
size_t meas_col = get_dst_col(layer_id, qbit_id, qbits_row);
m_latex_qwire.insert(qbit_id, meas_col, LATEX_MEASURE);
/* trick for put measure span qwires placeholder in matrix */
for (size_t r = qbit_id + 1; r <= qbits_row; r++)
{
/*
if qubit is not used, m_latex_qwire[r][0] should be default
then not marked m_latex_qwire[r][gate_col] as span row
*/
// if (!m_latex_qwire.is_empty(r, 0))
// {
m_latex_qwire.insert(r, meas_col, LATEX_QWIRE);
// }
}
m_latex_cwire.insert(cbit_id, meas_col, latex_measure_to(cbit_id, qbit_id, total_qbits_size));
/* record curent layer end at latex matrix col */
m_layer_col_range[layer_id] = std::max(meas_col, m_layer_col_range[layer_id]);
update_layer_time_seq(m_time_sequence_conf.get_measure_time_sequence());
}
void DrawLatex::append_reset(pOptimizerNodeInfo &node_info, uint64_t layer_id)
{
std::shared_ptr<AbstractQuantumReset> p_reset = std::dynamic_pointer_cast<AbstractQuantumReset>(*(node_info->m_iter));
int qubit_index = p_reset->getQuBit()->getPhysicalQubitPtr()->getQubitAddr();
size_t gate_col = get_dst_col(layer_id, qubit_index, qubit_index);
m_latex_qwire.insert(qubit_index, gate_col, LATEX_RESET);
/* record curent layer end at latex matrix col */
m_layer_col_range[layer_id] = std::max(gate_col, m_layer_col_range[layer_id]);
update_layer_time_seq(m_time_sequence_conf.get_reset_time_sequence());
}
void DrawLatex::draw_by_time_sequence(const std::string config_data /*= CONFIG_PATH*/)
{
m_time_sequence_conf.load_config(config_data);
const auto &layer_info = m_layer_info;
int time_seq = 0;
m_latex_time_seq.insert(0, 0, "\\nghost{\\mathrm{time :}}&\\lstick{\\mathrm{time :}}");
size_t qbit_max_row = m_latex_qwire.max_row();
std::stringstream ss;
std::string time_seq_str;
uint32_t layer_id = 0;
for (auto seq_item_itr = layer_info.begin(); seq_item_itr != layer_info.end(); ++seq_item_itr, ++layer_id)
{
m_layer_max_time_seq = 0;
for (auto &seq_node_item : (*seq_item_itr))
{
auto opt_node_info = seq_node_item.first;
append_node((DAGNodeType)(opt_node_info->m_type), opt_node_info, layer_id);
}
time_seq += m_layer_max_time_seq;
size_t time_col = m_layer_col_range.at(layer_id);
ss.clear();
ss << time_seq;
time_seq_str.clear();
ss >> time_seq_str;
m_latex_time_seq.insert(0, time_col, time_seq_str);
}
}
std::string DrawLatex::present(const std::string &file_name)
{
align_matrix_col();
/* add two empty wire to extend right border, beautfier latex output */
m_latex_qwire.max_col() += 2;
m_latex_cwire.max_col() += 2;
std::string out_str(LATEX_HEADER);
for (const auto &row : m_latex_qwire)
{
for (const auto &elem : row)
{
/* add "&" seperate matrix element to format latex array */
out_str += elem + "&";
}
/* elemiate last '&' */
out_str.pop_back();
out_str += "\\\\\n";
}
for (auto row : m_latex_cwire)
{
for (auto elem : row)
{
out_str += elem + "&";
}
/* elemiate last '&' */
out_str.pop_back();
out_str += "\\\\\n";
}
/* if draw_by_time_sequnce not be called, first element should be empty */
if (!m_latex_time_seq.is_empty(0, 0))
{
for (auto row : m_latex_time_seq)
{
for (auto elem : row)
{
out_str += elem + "&";
}
/* elemiate last '&' */
out_str.pop_back();
out_str += "\\\\\n";
}
}
out_str += LATEX_FOOTER;
std::fstream f(file_name, std::ios_base::out);
f << out_str;
f.close();
return out_str;
}
size_t DrawLatex::get_dst_col(size_t layer_id, size_t span_start, size_t span_end)
{
/*
trans layer to destination latex matrix col
if layer == 0, col = layer + 1 for the first latex matrix col contains qubits symbol.
else gates in current layer start col after last layer col
*/
uint64_t gate_col = layer_id == 0 ? layer_id + 1 : m_layer_col_range.at(layer_id - 1) + 1;
/*
as gates in same layer may cross much col,
for gate with ctrl bits may cross whole qwires, other gate in same layer can't be placed at same col
gates in same layer may spread at multi cols,
so find valid zone to put gate, return the col num
*/
return find_valid_matrix_col(span_start, span_end, gate_col);
}
void DrawLatex::align_matrix_col()
{
size_t &qwire_col = m_latex_qwire.max_col();
size_t &cwire_col = m_latex_cwire.max_col();
size_t max_col = std::max(qwire_col, cwire_col);
qwire_col = max_col;
cwire_col = max_col;
m_latex_time_seq.max_col() = max_col;
}
size_t DrawLatex::find_valid_matrix_col(size_t span_start, size_t span_end, size_t col)
{
for (size_t r = span_start; r <= span_end; ++r)
{
if (!m_latex_qwire.is_empty(r, col))
{
return find_valid_matrix_col(span_start, span_end, ++col);
}
}
return col;
}
QPANDA_END | 33.977496 | 172 | 0.58817 | [
"vector"
] |
83d75bfee1f4abe17e68cb8ffcb486b03173dc6c | 5,674 | cpp | C++ | src/DataStructures/Model/Animator.cpp | MajorArkwolf/ICT398-Project-Red | 953f047507356aafdea856ff28f49de5b97b66cc | [
"MIT"
] | 2 | 2021-04-18T09:49:36.000Z | 2021-06-08T03:19:18.000Z | src/DataStructures/Model/Animator.cpp | MajorArkwolf/ICT398-Project-Red | 953f047507356aafdea856ff28f49de5b97b66cc | [
"MIT"
] | null | null | null | src/DataStructures/Model/Animator.cpp | MajorArkwolf/ICT398-Project-Red | 953f047507356aafdea856ff28f49de5b97b66cc | [
"MIT"
] | 1 | 2022-03-14T06:06:07.000Z | 2022-03-14T06:06:07.000Z | #include "Animator.hpp"
#include "Engine/Engine.hpp"
void model::Animator::BoneTransform(double TimeInSeconds) {
transforms_.resize(100);
animation_time_ += TimeInSeconds;
if (animated_model_ != nullptr) {
if (loaded_animation_ != nullptr) {
if (animated_model_->is_animated_) {
double ticks_per_second = loaded_animation_->GetTicksPerSecond();
double time_in_ticks = animation_time_ * ticks_per_second;
if (end_when_completed_) {
if (time_in_ticks >= loaded_animation_->GetDuration()) {
clip_ended_ = true;
return;
}
}
glm::mat4 identity(1.0f);
double animation_time = fmod(time_in_ticks, loaded_animation_->GetDuration());
ReadNodeHeirarchy(animation_time, animated_model_->root_joint_, identity);
}
} else {
for (unsigned i = 0; i < 100; i++) {
transforms_[i] = glm::mat4(1.0f);
}
}
}
}
void model::Animator::ReadNodeHeirarchy(const double &AnimationTime, const JointsName& jN,
const glm::mat4 &ParentTransform) {
glm::mat4 node_transformation(jN.transform);
const auto* pNodeAnim = loaded_animation_->FindNodeAnim(jN.name);
if (pNodeAnim) {
// Interpolate scaling and generate scaling transformation matrix
// aiVector3D Scaling;
// CalcInterpolatedScaling(Scaling, AnimationTime, pNodeAnim);
// glm::mat4 ScalingM(1.0f);
// ScalingM.InitScaleTransform(Scaling.x, Scaling.y, Scaling.z);
// Interpolate rotation and generate rotation transformation matrix
glm::mat4 rotation_m = glm::mat4(CalcInterpolatedRotation(AnimationTime, pNodeAnim));
// Interpolate translation and generate translation transformation matrix
//TranslationM.InitTranslationTransform(Translation.x, Translation.y, Translation.z);
glm::mat4 translation_m = glm::translate(glm::mat4(1.0f), CalcInterpolatedPosition(AnimationTime, pNodeAnim));
// Combine the above transformations
node_transformation = translation_m * rotation_m /** ScalingM*/;
}
glm::mat4 global_transformation = ParentTransform * node_transformation;
if (animated_model_->bone_mapping_.find(jN.name) != animated_model_->bone_mapping_.end()) {
unsigned bone_index = animated_model_->bone_mapping_[jN.name];
transforms_[bone_index] = animated_model_->global_inverse_transform_ * global_transformation *
animated_model_->bone_info_[bone_index].bone_offset;
}
for (auto &child : jN.children) {
ReadNodeHeirarchy(AnimationTime, child, global_transformation);
}
}
glm::quat model::Animator::CalcInterpolatedRotation(double AnimationTime, const AnimJointNode *pNodeAnim) {
glm::quat out;
// we need at least two values to interpolate...
if (pNodeAnim->num_rot_keys == 1) {
out = pNodeAnim->rot_key[0].second;
return out;
}
unsigned rotation_index = loaded_animation_->FindRotation(AnimationTime, pNodeAnim);
unsigned new_rotation_index = (rotation_index + 1);
assert(new_rotation_index < pNodeAnim->num_rot_keys);
double delta_time = pNodeAnim->rot_key[new_rotation_index].first - pNodeAnim->rot_key[rotation_index].first;
double factor = (AnimationTime - pNodeAnim->rot_key[rotation_index].first) / delta_time;
//assert(Factor >= 0.0f && Factor <= 1.0f);
const glm::quat& start_rotation_q = pNodeAnim->rot_key[rotation_index].second;
const glm::quat& end_rotation_q = pNodeAnim->rot_key[new_rotation_index].second;
out = glm::slerp(start_rotation_q, end_rotation_q, static_cast<float>(factor));
out = glm::normalize(out);
return out;
}
glm::vec3 model::Animator::CalcInterpolatedPosition(double AnimationTime, const AnimJointNode *pNodeAnim) {
glm::vec3 out;
if (pNodeAnim->num_pos_keys == 1) {
out = pNodeAnim->pos_key[0].second;
return out;
}
unsigned position_index = loaded_animation_->FindPosition(AnimationTime, pNodeAnim);
unsigned next_position_index = (position_index + 1);
assert(next_position_index < pNodeAnim->num_pos_keys);
double delta_time = pNodeAnim->pos_key[next_position_index].first - pNodeAnim->pos_key[position_index].first;
double factor = (AnimationTime - pNodeAnim->pos_key[position_index].first) / delta_time;
//assert(Factor >= 0.0f && Factor <= 1.0f);
const glm::vec3& start = pNodeAnim->pos_key[position_index].second;
const glm::vec3& end = pNodeAnim->pos_key[next_position_index].second;
glm::vec3 delta = end - start;
out = start + static_cast<float>(factor) * delta;
return out;
}
//ALL CHECKS WITH THE STRING MUST BE UPPERCASE
void model::Animator::LoadAnimation(const std::string& newAnim, bool endWhenCompletedFlag) {
size_t index = 0;
if (loaded_animation_ != nullptr) {
index = loaded_animation_->GetName().find(newAnim);
} else {
index = std::string::npos;
}
if (index == std::string::npos) {
animation_time_ = 0.0;
loaded_animation_ = animated_model_->GetAnimation(newAnim);
end_when_completed_ = endWhenCompletedFlag;
clip_ended_ = false;
}
}
void model::Animator::ResetAnimationTime() {
animation_time_ = 0.0;
}
bool model::Animator::IsAnimationedEnded() const {
return clip_ended_;
}
void model::Animator::LinkToModel(size_t modelID) {
animated_model_ = redengine::Engine::get().model_manager_.getModel(modelID);
}
| 43.312977 | 118 | 0.673246 | [
"model",
"transform"
] |
83d86a554fc0897f289a3bbe26af780f7d29cfa9 | 872 | cpp | C++ | atcoder/abc011/C/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | atcoder/abc011/C/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | atcoder/abc011/C/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | #include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
int N;
vector<int> G(3);
bool solve() {
if (find(G.begin(), G.end(), N) != G.end()) return false;
int c = 0;
while (N > 0) {
int PN = N;
for (int x = 3; x > 0; --x) {
if (N - x < 0) continue;
bool pass = true;
for (int i = 0; i < 3; ++i) {
if (G[i] == N - x) {
pass = false;
}
}
if (pass) {
N = N - x;
++c;
break;
}
}
if (PN == N) return false;
}
return c <= 100;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> N;
cin >> G[0] >> G[1] >> G[2];
auto ans = solve() ? "YES" : "NO";
cout << ans << endl;
return 0;
} | 20.27907 | 61 | 0.369266 | [
"vector"
] |
83d9cea83b92a9f4140cb7dd5bf4bf86c20d5340 | 1,122 | cpp | C++ | FakeReal/Source/Engine/Graphic/Node/Model/Bone.cpp | UGEL4/FakeReal | 4ffc39fc500629fd537f688c56d5acdfc34d0b30 | [
"Apache-2.0"
] | null | null | null | FakeReal/Source/Engine/Graphic/Node/Model/Bone.cpp | UGEL4/FakeReal | 4ffc39fc500629fd537f688c56d5acdfc34d0b30 | [
"Apache-2.0"
] | null | null | null | FakeReal/Source/Engine/Graphic/Node/Model/Bone.cpp | UGEL4/FakeReal | 4ffc39fc500629fd537f688c56d5acdfc34d0b30 | [
"Apache-2.0"
] | null | null | null | #include "Bone.h"
#include "../../Stream/Property.h"
namespace FakeReal {
IMPLEMENT_RTTI(Bone, Node);
IMPLEMENT_INITIAL_BEGIN(Bone)
IMPLEMENT_INITIAL_END;
BEGIN_ADD_PROPERTY(Bone, Node)
REGISTER_PROPERTY(mInvBindPos, "InvBindPos", Property::F_SAVE_LOAD_CLONE)
REGISTER_PROPERTY(mIndex, "Bone Index", Property::F_SAVE_LOAD_CLONE)
REGISTER_PROPERTY(mName, "Name", Property::F_SAVE_LOAD_CLONE)
END_ADD_PROPERTY;
Bone::Bone()
{
mIndex = -1;
}
Bone::Bone(const std::string& name, int index)
{
mName = name;
mIndex = index;
}
Bone::~Bone()
{
}
int Bone::GetParentIndex() const
{
if (m_pParent)
{
Bone* pParent = DynamicCast<Bone>(m_pParent);
if (pParent)
return pParent->GetIndex();
}
return -1;
}
void Bone::GetAllBoneArray(std::vector<Bone*>& BoneArray)
{
BoneArray.emplace_back(this);
for (size_t i = 0; i < m_pChildList.size(); i++)
{
Bone* pBone = DynamicCast<Bone>(m_pChildList[i]);
if (pBone)
pBone->GetAllBoneArray(BoneArray);
}
}
void Bone::SetLocalMat(const glm::mat4& matrix)
{
mbIsChange = true;
mLocalTransform.SetMatrix(matrix);
}
}
| 19.016949 | 74 | 0.688948 | [
"vector"
] |
83d9dbfdb0945ce46429b17b146ed57b7d8a377b | 12,836 | cc | C++ | content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-02-03T05:32:07.000Z | 2019-02-03T05:32:07.000Z | content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
#include "third_party/khronos/GLES2/gl2.h"
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES 1
#endif
#include "third_party/khronos/GLES2/gl2ext.h"
#include <algorithm>
#include <map>
#include "base/atomicops.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "content/common/gpu/client/gpu_channel_host.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gles2_cmd_helper.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_trace_implementation.h"
#include "gpu/command_buffer/client/transfer_buffer.h"
#include "gpu/command_buffer/common/constants.h"
#include "gpu/command_buffer/common/gpu_memory_allocation.h"
#include "gpu/command_buffer/common/mailbox.h"
#include "gpu/skia_bindings/gl_bindings_skia_cmd_buffer.h"
#include "third_party/skia/include/core/SkTypes.h"
namespace content {
namespace {
static base::LazyInstance<base::Lock>::Leaky
g_default_share_groups_lock = LAZY_INSTANCE_INITIALIZER;
typedef std::map<GpuChannelHost*,
scoped_refptr<WebGraphicsContext3DCommandBufferImpl::ShareGroup> >
ShareGroupMap;
static base::LazyInstance<ShareGroupMap> g_default_share_groups =
LAZY_INSTANCE_INITIALIZER;
scoped_refptr<WebGraphicsContext3DCommandBufferImpl::ShareGroup>
GetDefaultShareGroupForHost(GpuChannelHost* host) {
base::AutoLock lock(g_default_share_groups_lock.Get());
ShareGroupMap& share_groups = g_default_share_groups.Get();
ShareGroupMap::iterator it = share_groups.find(host);
if (it == share_groups.end()) {
scoped_refptr<WebGraphicsContext3DCommandBufferImpl::ShareGroup> group =
new WebGraphicsContext3DCommandBufferImpl::ShareGroup();
share_groups[host] = group;
return group;
}
return it->second;
}
} // namespace anonymous
WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits::SharedMemoryLimits()
: command_buffer_size(kDefaultCommandBufferSize),
start_transfer_buffer_size(kDefaultStartTransferBufferSize),
min_transfer_buffer_size(kDefaultMinTransferBufferSize),
max_transfer_buffer_size(kDefaultMaxTransferBufferSize),
mapped_memory_reclaim_limit(gpu::gles2::GLES2Implementation::kNoLimit) {}
WebGraphicsContext3DCommandBufferImpl::ShareGroup::ShareGroup() {
}
WebGraphicsContext3DCommandBufferImpl::ShareGroup::~ShareGroup() {
DCHECK(contexts_.empty());
}
WebGraphicsContext3DCommandBufferImpl::WebGraphicsContext3DCommandBufferImpl(
int surface_id,
const GURL& active_url,
GpuChannelHost* host,
const Attributes& attributes,
bool lose_context_when_out_of_memory,
const SharedMemoryLimits& limits,
WebGraphicsContext3DCommandBufferImpl* share_context)
: lose_context_when_out_of_memory_(lose_context_when_out_of_memory),
attributes_(attributes),
visible_(false),
host_(host),
surface_id_(surface_id),
active_url_(active_url),
gpu_preference_(attributes.preferDiscreteGPU ? gfx::PreferDiscreteGpu
: gfx::PreferIntegratedGpu),
mem_limits_(limits),
weak_ptr_factory_(this) {
if (share_context) {
DCHECK(!attributes_.shareResources);
share_group_ = share_context->share_group_;
} else {
share_group_ = attributes_.shareResources
? GetDefaultShareGroupForHost(host)
: scoped_refptr<WebGraphicsContext3DCommandBufferImpl::ShareGroup>(
new ShareGroup());
}
}
WebGraphicsContext3DCommandBufferImpl::
~WebGraphicsContext3DCommandBufferImpl() {
if (real_gl_) {
real_gl_->SetErrorMessageCallback(NULL);
}
Destroy();
}
bool WebGraphicsContext3DCommandBufferImpl::MaybeInitializeGL() {
if (initialized_)
return true;
if (initialize_failed_)
return false;
TRACE_EVENT0("gpu", "WebGfxCtx3DCmdBfrImpl::MaybeInitializeGL");
if (!CreateContext(surface_id_ != 0)) {
Destroy();
initialize_failed_ = true;
return false;
}
if (gl_ && attributes_.webGL)
gl_->EnableFeatureCHROMIUM("webgl_enable_glsl_webgl_validation");
command_buffer_->SetChannelErrorCallback(
base::Bind(&WebGraphicsContext3DCommandBufferImpl::OnGpuChannelLost,
weak_ptr_factory_.GetWeakPtr()));
command_buffer_->SetOnConsoleMessageCallback(
base::Bind(&WebGraphicsContext3DCommandBufferImpl::OnErrorMessage,
weak_ptr_factory_.GetWeakPtr()));
real_gl_->SetErrorMessageCallback(getErrorMessageCallback());
visible_ = true;
initialized_ = true;
return true;
}
bool WebGraphicsContext3DCommandBufferImpl::InitializeCommandBuffer(
bool onscreen, WebGraphicsContext3DCommandBufferImpl* share_context) {
if (!host_.get())
return false;
CommandBufferProxyImpl* share_group_command_buffer = NULL;
if (share_context) {
share_group_command_buffer = share_context->command_buffer_.get();
}
::gpu::gles2::ContextCreationAttribHelper attribs_for_gles2;
ConvertAttributes(attributes_, &attribs_for_gles2);
attribs_for_gles2.lose_context_when_out_of_memory =
lose_context_when_out_of_memory_;
DCHECK(attribs_for_gles2.buffer_preserved);
std::vector<int32> attribs;
attribs_for_gles2.Serialize(&attribs);
// Create a proxy to a command buffer in the GPU process.
if (onscreen) {
command_buffer_.reset(host_->CreateViewCommandBuffer(
surface_id_,
share_group_command_buffer,
attribs,
active_url_,
gpu_preference_));
} else {
command_buffer_.reset(host_->CreateOffscreenCommandBuffer(
gfx::Size(1, 1),
share_group_command_buffer,
attribs,
active_url_,
gpu_preference_));
}
if (!command_buffer_) {
DLOG(ERROR) << "GpuChannelHost failed to create command buffer.";
return false;
}
DVLOG_IF(1, gpu::error::IsError(command_buffer_->GetLastError()))
<< "Context dead on arrival. Last error: "
<< command_buffer_->GetLastError();
// Initialize the command buffer.
bool result = command_buffer_->Initialize();
LOG_IF(ERROR, !result) << "CommandBufferProxy::Initialize failed.";
return result;
}
bool WebGraphicsContext3DCommandBufferImpl::CreateContext(bool onscreen) {
TRACE_EVENT0("gpu", "WebGfxCtx3DCmdBfrImpl::CreateContext");
scoped_refptr<gpu::gles2::ShareGroup> gles2_share_group;
scoped_ptr<base::AutoLock> share_group_lock;
bool add_to_share_group = false;
if (!command_buffer_) {
WebGraphicsContext3DCommandBufferImpl* share_context = NULL;
share_group_lock.reset(new base::AutoLock(share_group_->lock()));
share_context = share_group_->GetAnyContextLocked();
if (!InitializeCommandBuffer(onscreen, share_context)) {
LOG(ERROR) << "Failed to initialize command buffer.";
return false;
}
if (share_context)
gles2_share_group = share_context->GetImplementation()->share_group();
add_to_share_group = true;
}
// Create the GLES2 helper, which writes the command buffer protocol.
gles2_helper_.reset(new gpu::gles2::GLES2CmdHelper(command_buffer_.get()));
if (!gles2_helper_->Initialize(mem_limits_.command_buffer_size)) {
LOG(ERROR) << "Failed to initialize GLES2CmdHelper.";
return false;
}
if (attributes_.noAutomaticFlushes)
gles2_helper_->SetAutomaticFlushes(false);
// Create a transfer buffer used to copy resources between the renderer
// process and the GPU process.
transfer_buffer_ .reset(new gpu::TransferBuffer(gles2_helper_.get()));
DCHECK(host_.get());
// Create the object exposing the OpenGL API.
bool bind_generates_resources = false;
real_gl_.reset(
new gpu::gles2::GLES2Implementation(gles2_helper_.get(),
gles2_share_group.get(),
transfer_buffer_.get(),
bind_generates_resources,
lose_context_when_out_of_memory_,
command_buffer_.get()));
setGLInterface(real_gl_.get());
if (!real_gl_->Initialize(
mem_limits_.start_transfer_buffer_size,
mem_limits_.min_transfer_buffer_size,
mem_limits_.max_transfer_buffer_size,
mem_limits_.mapped_memory_reclaim_limit)) {
LOG(ERROR) << "Failed to initialize GLES2Implementation.";
return false;
}
if (add_to_share_group)
share_group_->AddContextLocked(this);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableGpuClientTracing)) {
trace_gl_.reset(new gpu::gles2::GLES2TraceImplementation(GetGLInterface()));
setGLInterface(trace_gl_.get());
}
return true;
}
bool WebGraphicsContext3DCommandBufferImpl::InitializeOnCurrentThread() {
if (!MaybeInitializeGL()) {
DLOG(ERROR) << "Failed to initialize context.";
return false;
}
if (gpu::error::IsError(command_buffer_->GetLastError())) {
LOG(ERROR) << "Context dead on arrival. Last error: "
<< command_buffer_->GetLastError();
return false;
}
return true;
}
void WebGraphicsContext3DCommandBufferImpl::Destroy() {
share_group_->RemoveContext(this);
gpu::gles2::GLES2Interface* gl = GetGLInterface();
if (gl) {
// First flush the context to ensure that any pending frees of resources
// are completed. Otherwise, if this context is part of a share group,
// those resources might leak. Also, any remaining side effects of commands
// issued on this context might not be visible to other contexts in the
// share group.
gl->Flush();
setGLInterface(NULL);
}
trace_gl_.reset();
real_gl_.reset();
transfer_buffer_.reset();
gles2_helper_.reset();
real_gl_.reset();
if (command_buffer_) {
if (host_.get())
host_->DestroyCommandBuffer(command_buffer_.release());
command_buffer_.reset();
}
host_ = NULL;
}
gpu::ContextSupport*
WebGraphicsContext3DCommandBufferImpl::GetContextSupport() {
return real_gl_.get();
}
bool WebGraphicsContext3DCommandBufferImpl::isContextLost() {
return initialize_failed_ ||
(command_buffer_ && IsCommandBufferContextLost()) ||
context_lost_reason_ != GL_NO_ERROR;
}
WGC3Denum WebGraphicsContext3DCommandBufferImpl::getGraphicsResetStatusARB() {
if (IsCommandBufferContextLost() &&
context_lost_reason_ == GL_NO_ERROR) {
return GL_UNKNOWN_CONTEXT_RESET_ARB;
}
return context_lost_reason_;
}
bool WebGraphicsContext3DCommandBufferImpl::IsCommandBufferContextLost() {
// If the channel shut down unexpectedly, let that supersede the
// command buffer's state.
if (host_.get() && host_->IsLost())
return true;
gpu::CommandBuffer::State state = command_buffer_->GetLastState();
return state.error == gpu::error::kLostContext;
}
// static
WebGraphicsContext3DCommandBufferImpl*
WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
GpuChannelHost* host,
const WebGraphicsContext3D::Attributes& attributes,
bool lose_context_when_out_of_memory,
const GURL& active_url,
const SharedMemoryLimits& limits,
WebGraphicsContext3DCommandBufferImpl* share_context) {
if (!host)
return NULL;
if (share_context && share_context->IsCommandBufferContextLost())
return NULL;
return new WebGraphicsContext3DCommandBufferImpl(
0,
active_url,
host,
attributes,
lose_context_when_out_of_memory,
limits,
share_context);
}
namespace {
WGC3Denum convertReason(gpu::error::ContextLostReason reason) {
switch (reason) {
case gpu::error::kGuilty:
return GL_GUILTY_CONTEXT_RESET_ARB;
case gpu::error::kInnocent:
return GL_INNOCENT_CONTEXT_RESET_ARB;
case gpu::error::kUnknown:
return GL_UNKNOWN_CONTEXT_RESET_ARB;
}
NOTREACHED();
return GL_UNKNOWN_CONTEXT_RESET_ARB;
}
} // anonymous namespace
void WebGraphicsContext3DCommandBufferImpl::OnGpuChannelLost() {
context_lost_reason_ = convertReason(
command_buffer_->GetLastState().context_lost_reason);
if (context_lost_callback_) {
context_lost_callback_->onContextLost();
}
share_group_->RemoveAllContexts();
DCHECK(host_.get());
{
base::AutoLock lock(g_default_share_groups_lock.Get());
g_default_share_groups.Get().erase(host_.get());
}
}
} // namespace content
| 31.693827 | 80 | 0.735587 | [
"object",
"vector"
] |
83da0e907f8f8b3d4644962643ce74a267b24ceb | 3,077 | cpp | C++ | Mistix_The_Right_One/BarricadeManager.cpp | Subve/Mistix | 72615ec36b387ae905ffd630b384fc7859b4e2d9 | [
"MIT"
] | null | null | null | Mistix_The_Right_One/BarricadeManager.cpp | Subve/Mistix | 72615ec36b387ae905ffd630b384fc7859b4e2d9 | [
"MIT"
] | null | null | null | Mistix_The_Right_One/BarricadeManager.cpp | Subve/Mistix | 72615ec36b387ae905ffd630b384fc7859b4e2d9 | [
"MIT"
] | null | null | null | #include "BarricadeManager.h"
BarricadeManager::BarricadeManager()
{
}
BarricadeManager::~BarricadeManager()
{
}
void BarricadeManager::SpawnBarricades(std::vector<std::unique_ptr<Barricade>>& barykady,int &barricade_startamount)
{
int amount_barricades = 0;
while(amount_barricades<barricade_startamount)
{
if (amount_barricades < 0) amount_barricades = 0;
auto barricade_pozycja_x = static_cast<float>(rand()&600+100);
auto barricade_pozycja_y = static_cast<float>(rand()%500+50);
barykady.push_back(std::make_unique<Barricade>());
barykady[amount_barricades]->setPosition(barricade_pozycja_x, barricade_pozycja_y);
if(abs(800-barricade_pozycja_x)>abs(600-barricade_pozycja_y))
{
barykady[amount_barricades]->setRotation(90);
}
barykady[amount_barricades]->used = false;
barykady[amount_barricades]->used_kill = false;
amount_barricades += 1;
}
}
void BarricadeManager::StopEnemy(std::vector<std::unique_ptr<Barricade>>& barykady,std::vector<std::unique_ptr<Enemy>>& enemies,sf::Time &elapsed_time)
{
for (int i = 0;i < barykady.size();i++)
{
for (int j = 0;j < enemies.size();j++)
{
if (barykady[i]->getGlobalBounds().intersects(enemies[j]->getGlobalBounds()) && barykady[i]->used == false&&enemies[j]->ableToMove==true)
{
enemies[j]->ableToMove = false;
barykady[i]->used = true;
barykady[i]->elapsed_barricade_time = sf::milliseconds(0);
}
}
}
}
void BarricadeManager::LetEnemyGo(std::vector<std::unique_ptr<Barricade>>& barykady,
std::vector<std::unique_ptr<Enemy>>& enemies, sf::Time& delta_barricade)
{
for (int i = 0;i < barykady.size();i++)
{
for (int j = 0;j < enemies.size();j++)
{if (barykady[i]->elapsed_barricade_time >= delta_barricade)
{
{
if (barykady[i]->getGlobalBounds().intersects(enemies[j]->getGlobalBounds()) && barykady[i]->used == true && enemies[j]->ableToMove == false)
{
enemies[j]->ableToMove = true;
barykady[i]->used_kill = true;
barykady[i]->elapsed_barricade_time -= delta_barricade;
}
}
}
}
}
}
void BarricadeManager::KillBarricades(std::vector<std::unique_ptr<Barricade>>& barykady)
{
for(int i=0;i<barykady.size();i++)
{
if(barykady[i]->used_kill==true||barykady[i]->elapsed_barricade_time>sf::seconds(9))
{
barykady.erase(barykady.begin() + i);
}
}
}
void BarricadeManager::RespawnBarricades(std::vector<std::unique_ptr<Barricade>>& barykady)
{
int numer = barykady.size();
auto barricade_pozycja_x = static_cast<float>(rand() & 600 + 100);
auto barricade_pozycja_y = static_cast<float>(rand() % 500 + 50);
barykady.emplace_back(std::make_unique<Barricade>());
barykady[numer]->setPosition(barricade_pozycja_x, barricade_pozycja_y);
barykady[numer]->used = false;
barykady[numer]->used_kill = false;
}
void BarricadeManager::renderBarricade(sf::RenderTarget& window, std::vector<std::unique_ptr<Barricade>>& barykady)
{
for (int i = 0;i < barykady.size();i++)
{
window.draw(*barykady[i]);
}
}
| 25.641667 | 151 | 0.682808 | [
"vector"
] |
83deefd7aa7526022ffda34f03b99cb0b8decb71 | 2,293 | cpp | C++ | kernel/devices/pci/VirtioQueue.cpp | DeanoBurrito/northport | 6da490b02bfe7d0a12a25316db879ecc249be1c7 | [
"MIT"
] | 19 | 2021-12-10T12:48:44.000Z | 2022-03-30T09:17:14.000Z | kernel/devices/pci/VirtioQueue.cpp | DeanoBurrito/northport | 6da490b02bfe7d0a12a25316db879ecc249be1c7 | [
"MIT"
] | 24 | 2021-11-30T10:00:05.000Z | 2022-03-29T10:19:21.000Z | kernel/devices/pci/VirtioQueue.cpp | DeanoBurrito/northport | 6da490b02bfe7d0a12a25316db879ecc249be1c7 | [
"MIT"
] | 2 | 2021-11-24T00:52:10.000Z | 2021-12-27T23:47:32.000Z | #include <devices/pci/VirtioQueue.h>
#include <memory/PhysicalMemory.h>
namespace Kernel::Devices::Pci
{
sl::Vector<VirtioQueue> VirtioQueue::FindQueues(VirtioPciCommonConfig* config)
{
volatile VirtioPciCommonConfig* cfg = config;
sl::Vector<VirtioQueue> queues;
for (size_t i = 0; i < cfg->numberOfQueues; i++)
{
queues.EmplaceBack();
cfg->queueSelect = i;
queues[i].id = i;
queues[i].size = cfg->queueSize;
queues[i].cfg = cfg;
}
return queues;
}
VirtioQueue::~VirtioQueue()
{
if (descriptorTable.base.ptr != nullptr)
FreeBuffer();
}
void VirtioQueue::AllocBuffer(size_t queueSizeHint)
{
cfg->queueSelect = id;
const size_t actualMax = sl::min(queueSizeHint, (size_t)cfg->queueSize);
size = cfg->queueSize = actualMax;
size_t totalSize = 0;
totalSize += cfg->queueSize * 16;
totalSize += cfg->queueSize * 2 + 6;
totalSize += cfg->queueSize * 8 + 6;
totalSize += 10; //worst-case misalignment we could have, this gives us some room for error
totalSize = (totalSize / PAGE_FRAME_SIZE + 1);
sl::NativePtr physicalBuffer = Memory::PMM::Global()->AllocPages(totalSize);
descriptorTable = { physicalBuffer.raw, (size_t)cfg->queueSize * 16 };
availableRing = { descriptorTable.base.raw + descriptorTable.length, (size_t)cfg->queueSize * 2 + 6 };
availableRing.base = (availableRing.base.raw / 2 + 1) * 2;
usedRing = { availableRing.base.raw + availableRing.length, (size_t)cfg->queueSize * 8 + 6};
usedRing.base = (usedRing.base.raw / 8 + 1) * 8;
//write back these addresses to the device queue config
cfg->queueDesc = descriptorTable.base.raw;
cfg->queueDriver = availableRing.base.raw;
cfg->queueDevice = usedRing.base.raw;
}
void VirtioQueue::FreeBuffer()
{
//TODO: implement free buffers
}
bool VirtioQueue::IsEnabled()
{
cfg->queueSelect = id;
return (cfg->queueEnable != 0);
}
void VirtioQueue::SetEnabled(bool yes)
{
cfg->queueSelect = id;
cfg->queueEnable = yes ? 1 : 0;
}
}
| 30.986486 | 110 | 0.597034 | [
"vector"
] |
83df34bfd60fc2178c720ce34badaf0134cc2f1f | 4,731 | cpp | C++ | oanda_v20/test/src/oanda_exception_test.cpp | CodeRancher/offcenter_oanda | c7817299b2c7199508307b2379179923e3f60fdc | [
"Apache-2.0"
] | null | null | null | oanda_v20/test/src/oanda_exception_test.cpp | CodeRancher/offcenter_oanda | c7817299b2c7199508307b2379179923e3f60fdc | [
"Apache-2.0"
] | null | null | null | oanda_v20/test/src/oanda_exception_test.cpp | CodeRancher/offcenter_oanda | c7817299b2c7199508307b2379179923e3f60fdc | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Scott Brauer
*
* 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 BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* File: oanda_exception_test.cpp
* Author: Scott Brauer
*
* Mon 21 Dec 2020 04:32:08 PM MST
*/
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <cpprest/http_msg.h>
#include "oanda/v20/endpoint/OandaConnectionException.hpp"
#include "oanda/v20/endpoint/OandaExceptionFactory.hpp"
#include "oanda/v20/endpoint/OandaEndpoints.hpp"
#include "WaitForMessage.hpp"
TEST (OandaExceptions, BadRequest)
{
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::BadRequest, "{\"unused\" : \"I am unused\"}"),
oanda::v20::endpoint::BadRequest);
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::BadRequest, "{\"errorMessage\" : \"The request was missing required data\"}"),
oanda::v20::endpoint::MalformedRequest);
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::BadRequest, "{\"errorMessage\" : \"Invalid value specified for 'instrument'\"}"),
oanda::v20::endpoint::InvalidInstrument);
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::BadRequest, "{\"rejectReason\" : \" STOP_LOSS_ON_FILL_PRICE_PRECISION_EXCEEDED\"}"),
oanda::v20::endpoint::PrecisionExceeded);
}
TEST (OandaExceptions, Unauthorized)
{
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::Unauthorized, "{\"unused\" : \"I am unused\"}"),
oanda::v20::endpoint::Unauthorized);
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::Unauthorized, "{\"errorMessage\" : \"The provided request was forbidden.\"}"),
oanda::v20::endpoint::InvalidAccountID);
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::Unauthorized, "{\"errorMessage\" : \"Insufficient authorization to perform request.\"}"),
oanda::v20::endpoint::InsufficientAuthorization);
}
TEST (OandaExceptions, Forbidden)
{
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::Forbidden, "{\"unused\" : \"I am unused\"}"),
oanda::v20::endpoint::Forbidden);
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::Forbidden, "{\"errorMessage\" : \"Insufficient authorization to perform request.\"}"),
oanda::v20::endpoint::AccountNotTradable);
}
TEST (OandaExceptions, NotFound)
{
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::NotFound, "{\"unused\" : \"I am unused\"}"),
oanda::v20::endpoint::NotFound);
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::NotFound, "{\"errorMessage\" : \"The trade ID specified does not exist\"}"),
oanda::v20::endpoint::NoSuchTrade);
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::NotFound, "{\"errorMessage\" : \"The transaction ID specified does not exist\"}"),
oanda::v20::endpoint::NoSuchTransaction);
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::NotFound, "{\"errorMessage\" : \"The order ID specified does not exist\"}"),
oanda::v20::endpoint::NoSuchOrder);
}
TEST (OandaExceptions, MethodNotAllowed)
{
EXPECT_THROW(
oanda::v20::endpoint::oandaExceptionFactory(web::http::status_codes::MethodNotAllowed, "{\"unused\" : \"I am unused\"}"),
oanda::v20::endpoint::MethodNotAllowed);
}
TEST (OandaExceptions, BearerTokenNotSupplied)
{
oanda::v20::endpoint::OandaPracticeServer server;
oanda::v20::endpoint::OandaAuthorization authorization("ABCD");
oanda::v20::endpoint::OandaEndpoints::Ptr endpoints = oanda::v20::endpoint::OandaEndpoints::factory(server, authorization);
/*
ASSERT_THROW(
endpoints->accountsSync([](oanda::v20::endpoint::account::AccountsResponse accounts) -> void {
FAIL(); // This should never execute. An exception must be returned.
}
), oanda::v20::endpoint::InsufficientAuthorization);
endpoints->accountsAsync([](pplx::task<oanda::v20::endpoint::account::AccountsResponse> accounts) -> void {
ASSERT_THROW(accounts.get(), oanda::v20::endpoint::InsufficientAuthorization);
});
*/
}
| 37.547619 | 161 | 0.730501 | [
"vector"
] |
83e3358924f951208fece963b26a89dbdc469dbe | 14,042 | cpp | C++ | Framework/Common/GraphicsManager.cpp | ucchen/GameEngineFromScratch | e8d3abd71149682097a69b0fbab2f2029aee7952 | [
"MIT"
] | 1 | 2020-05-25T11:34:54.000Z | 2020-05-25T11:34:54.000Z | Framework/Common/GraphicsManager.cpp | SaeruHikari/GameEngineFromScratch | 940564362b5da9c2873d267cb54107a2ce8e8c4c | [
"MIT"
] | null | null | null | Framework/Common/GraphicsManager.cpp | SaeruHikari/GameEngineFromScratch | 940564362b5da9c2873d267cb54107a2ce8e8c4c | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
#include "GraphicsManager.hpp"
#include "SceneManager.hpp"
#include "IApplication.hpp"
#include "IPhysicsManager.hpp"
#include "ForwardGeometryPass.hpp"
#include "ShadowMapPass.hpp"
#include "BRDFIntegrator.hpp"
using namespace My;
using namespace std;
int GraphicsManager::Initialize()
{
int result = 0;
m_Frames.resize(GfxConfiguration::kMaxInFlightFrameCount);
#if !defined(OS_WEBASSEMBLY)
m_InitPasses.push_back(make_shared<BRDFIntegrator>());
#endif
InitConstants();
m_DrawPasses.push_back(make_shared<ShadowMapPass>());
m_DrawPasses.push_back(make_shared<ForwardGeometryPass>());
return result;
}
void GraphicsManager::Finalize()
{
#ifdef DEBUG
ClearDebugBuffers();
#endif
EndScene();
}
void GraphicsManager::Tick()
{
if (g_pSceneManager->IsSceneChanged())
{
EndScene();
cerr << "[GraphicsManager] Detected Scene Change, reinitialize buffers ..." << endl;
const Scene& scene = g_pSceneManager->GetSceneForRendering();
BeginScene(scene);
g_pSceneManager->NotifySceneIsRenderingQueued();
}
UpdateConstants();
BeginFrame();
Draw();
EndFrame();
Present();
m_nFrameIndex = (m_nFrameIndex + 1) % GfxConfiguration::kMaxInFlightFrameCount;
}
void GraphicsManager::ResizeCanvas(int32_t width, int32_t height)
{
cerr << "[GraphicsManager] Resize Canvas to " << width << "x" << height << endl;
}
void GraphicsManager::UpdateConstants()
{
// update scene object position
auto& frame = m_Frames[m_nFrameIndex];
for (auto& pDbc : frame.batchContexts)
{
if (void* rigidBody = pDbc->node->RigidBody()) {
Matrix4X4f trans;
// the geometry has rigid body bounded, we blend the simlation result here.
Matrix4X4f simulated_result = g_pPhysicsManager->GetRigidBodyTransform(rigidBody);
BuildIdentityMatrix(trans);
// apply the rotation part of the simlation result
memcpy(trans[0], simulated_result[0], sizeof(float) * 3);
memcpy(trans[1], simulated_result[1], sizeof(float) * 3);
memcpy(trans[2], simulated_result[2], sizeof(float) * 3);
// replace the translation part of the matrix with simlation result directly
memcpy(trans[3], simulated_result[3], sizeof(float) * 3);
pDbc->modelMatrix = trans;
} else {
pDbc->modelMatrix = *pDbc->node->GetCalculatedTransform();
}
}
// Generate the view matrix based on the camera's position.
CalculateCameraMatrix();
CalculateLights();
SetPerFrameConstants(frame.frameContext);
SetPerBatchConstants(frame.batchContexts);
SetLightInfo(frame.lightInfo);
}
void GraphicsManager::Draw()
{
auto& frame = m_Frames[m_nFrameIndex];
for (auto& pDrawPass : m_DrawPasses)
{
BeginPass();
pDrawPass->Draw(frame);
EndPass();
}
}
void GraphicsManager::CalculateCameraMatrix()
{
auto& scene = g_pSceneManager->GetSceneForRendering();
auto pCameraNode = scene.GetFirstCameraNode();
DrawFrameContext& frameContext = m_Frames[m_nFrameIndex].frameContext;
if (pCameraNode) {
auto transform = *pCameraNode->GetCalculatedTransform();
frameContext.camPos = Vector3f({transform[3][0], transform[3][1], transform[3][2]});
InverseMatrix4X4f(transform);
frameContext.viewMatrix = transform;
}
else {
// use default build-in camera
Vector3f position = { 0.0f, -5.0f, 0.0f }, lookAt = { 0.0f, 0.0f, 0.0f }, up = { 0.0f, 0.0f, 1.0f };
BuildViewRHMatrix(frameContext.viewMatrix, position, lookAt, up);
}
float fieldOfView = PI / 3.0f;
float nearClipDistance = 1.0f;
float farClipDistance = 100.0f;
if (pCameraNode) {
auto pCamera = scene.GetCamera(pCameraNode->GetSceneObjectRef());
// Set the field of view and screen aspect ratio.
fieldOfView = dynamic_pointer_cast<SceneObjectPerspectiveCamera>(pCamera)->GetFov();
nearClipDistance = pCamera->GetNearClipDistance();
farClipDistance = pCamera->GetFarClipDistance();
}
const GfxConfiguration& conf = g_pApp->GetConfiguration();
float screenAspect = (float)conf.screenWidth / (float)conf.screenHeight;
// Build the perspective projection matrix.
BuildPerspectiveFovRHMatrix(frameContext.projectionMatrix, fieldOfView, screenAspect, nearClipDistance, farClipDistance);
}
void GraphicsManager::CalculateLights()
{
DrawFrameContext& frameContext = m_Frames[m_nFrameIndex].frameContext;
LightInfo& light_info = m_Frames[m_nFrameIndex].lightInfo;
frameContext.numLights = 0;
auto& scene = g_pSceneManager->GetSceneForRendering();
for (auto LightNode : scene.LightNodes) {
Light& light = light_info.lights[frameContext.numLights];
auto pLightNode = LightNode.second.lock();
if (!pLightNode) continue;
auto trans_ptr = pLightNode->GetCalculatedTransform();
light.lightPosition = { 0.0f, 0.0f, 0.0f, 1.0f };
light.lightDirection = { 0.0f, 0.0f, -1.0f, 0.0f };
Transform(light.lightPosition, *trans_ptr);
Transform(light.lightDirection, *trans_ptr);
Normalize(light.lightDirection);
auto pLight = scene.GetLight(pLightNode->GetSceneObjectRef());
if (pLight) {
light.lightGuid = pLight->GetGuid();
light.lightColor = pLight->GetColor().Value;
light.lightIntensity = pLight->GetIntensity();
light.lightCastShadow = pLight->GetIfCastShadow();
const AttenCurve& atten_curve = pLight->GetDistanceAttenuation();
light.lightDistAttenCurveType = atten_curve.type;
memcpy(light.lightDistAttenCurveParams, &atten_curve.u, sizeof(atten_curve.u));
light.lightAngleAttenCurveType = AttenCurveType::kNone;
Matrix4X4f view;
Matrix4X4f projection;
BuildIdentityMatrix(projection);
float nearClipDistance = 1.0f;
float farClipDistance = 100.0f;
if (pLight->GetType() == SceneObjectType::kSceneObjectTypeLightInfi)
{
light.lightType = LightType::Infinity;
Vector4f target = { 0.0f, 0.0f, 0.0f, 1.0f };
auto pCameraNode = scene.GetFirstCameraNode();
if (pCameraNode) {
auto pCamera = scene.GetCamera(pCameraNode->GetSceneObjectRef());
nearClipDistance = pCamera->GetNearClipDistance();
farClipDistance = pCamera->GetFarClipDistance();
target[2] = - (0.75f * nearClipDistance + 0.25f * farClipDistance);
// calculate the camera target position
auto trans_ptr = pCameraNode->GetCalculatedTransform();
Transform(target, *trans_ptr);
}
light.lightPosition = target - light.lightDirection * farClipDistance;
Vector3f position;
memcpy(&position, &light.lightPosition, sizeof position);
Vector3f lookAt;
memcpy(&lookAt, &target, sizeof lookAt);
Vector3f up = { 0.0f, 0.0f, 1.0f };
if (abs(light.lightDirection[0]) <= 0.2f
&& abs(light.lightDirection[1]) <= 0.2f)
{
up = { 0.1f, 0.1f, 1.0f};
}
BuildViewRHMatrix(view, position, lookAt, up);
float sm_half_dist = min(farClipDistance * 0.25f, 800.0f);
BuildOrthographicMatrix(projection,
- sm_half_dist, sm_half_dist,
sm_half_dist, - sm_half_dist,
nearClipDistance, farClipDistance + sm_half_dist);
// notify shader about the infinity light by setting 4th field to 0
light.lightPosition[3] = 0.0f;
}
else
{
Vector3f position;
memcpy(&position, &light.lightPosition, sizeof position);
Vector4f tmp = light.lightPosition + light.lightDirection;
Vector3f lookAt;
memcpy(&lookAt, &tmp, sizeof lookAt);
Vector3f up = { 0.0f, 0.0f, 1.0f };
if (abs(light.lightDirection[0]) <= 0.1f
&& abs(light.lightDirection[1]) <= 0.1f)
{
up = { 0.0f, 0.707f, 0.707f};
}
BuildViewRHMatrix(view, position, lookAt, up);
if (pLight->GetType() == SceneObjectType::kSceneObjectTypeLightSpot)
{
light.lightType = LightType::Spot;
auto plight = dynamic_pointer_cast<SceneObjectSpotLight>(pLight);
const AttenCurve& angle_atten_curve = plight->GetAngleAttenuation();
light.lightAngleAttenCurveType = angle_atten_curve.type;
memcpy(light.lightAngleAttenCurveParams, &angle_atten_curve.u, sizeof(angle_atten_curve.u));
float fieldOfView = light.lightAngleAttenCurveParams[0][1] * 2.0f;
float screenAspect = 1.0f;
// Build the perspective projection matrix.
BuildPerspectiveFovRHMatrix(projection, fieldOfView, screenAspect, nearClipDistance, farClipDistance);
}
else if (pLight->GetType() == SceneObjectType::kSceneObjectTypeLightArea)
{
light.lightType = LightType::Area;
auto plight = dynamic_pointer_cast<SceneObjectAreaLight>(pLight);
light.lightSize = plight->GetDimension();
}
else // omni light
{
light.lightType = LightType::Omni;
//auto plight = dynamic_pointer_cast<SceneObjectOmniLight>(pLight);
float fieldOfView = PI / 2.0f; // 90 degree for each cube map face
float screenAspect = 1.0f;
// Build the perspective projection matrix.
BuildPerspectiveFovRHMatrix(projection, fieldOfView, screenAspect, nearClipDistance, farClipDistance);
}
}
light.lightVP = view * projection;
frameContext.numLights++;
}
else
{
assert(0);
}
}
}
void GraphicsManager::BeginScene(const Scene& scene)
{
for (auto pPass : m_InitPasses)
{
BeginCompute();
pPass->Dispatch();
EndCompute();
}
}
#ifdef DEBUG
void GraphicsManager::DrawEdgeList(const EdgeList& edges, const Vector3f& color)
{
PointList point_list;
for (auto edge : edges)
{
point_list.push_back(edge->first);
point_list.push_back(edge->second);
}
DrawLine(point_list, color);
}
void GraphicsManager::DrawPolygon(const Face& polygon, const Vector3f& color)
{
PointSet vertices;
PointList edges;
for (auto pEdge : polygon.Edges)
{
vertices.insert({pEdge->first, pEdge->second});
edges.push_back(pEdge->first);
edges.push_back(pEdge->second);
}
DrawLine(edges, color);
DrawPointSet(vertices, color);
DrawTriangle(polygon.GetVertices(), color * 0.5f);
}
void GraphicsManager::DrawPolygon(const Face& polygon, const Matrix4X4f& trans, const Vector3f& color)
{
PointSet vertices;
PointList edges;
for (auto pEdge : polygon.Edges)
{
vertices.insert({pEdge->first, pEdge->second});
edges.push_back(pEdge->first);
edges.push_back(pEdge->second);
}
DrawLine(edges, trans, color);
DrawPointSet(vertices, trans, color);
DrawTriangle(polygon.GetVertices(), trans, color * 0.5f);
}
void GraphicsManager::DrawPolyhydron(const Polyhedron& polyhedron, const Vector3f& color)
{
for (auto pFace : polyhedron.Faces)
{
DrawPolygon(*pFace, color);
}
}
void GraphicsManager::DrawPolyhydron(const Polyhedron& polyhedron, const Matrix4X4f& trans, const Vector3f& color)
{
for (auto pFace : polyhedron.Faces)
{
DrawPolygon(*pFace, trans, color);
}
}
void GraphicsManager::DrawBox(const Vector3f& bbMin, const Vector3f& bbMax, const Vector3f& color)
{
// ******0--------3********
// *****/: /|********
// ****1--------2 |********
// ****| : | |********
// ****| 4- - - | 7********
// ****|/ |/*********
// ****5--------6**********
// vertices
PointPtr points[8];
for (int i = 0; i < 8; i++)
points[i] = make_shared<Point>(bbMin);
*points[0] = *points[2] = *points[3] = *points[7] = bbMax;
points[0]->data[0] = bbMin[0];
points[2]->data[1] = bbMin[1];
points[7]->data[2] = bbMin[2];
points[1]->data[2] = bbMax[2];
points[4]->data[1] = bbMax[1];
points[6]->data[0] = bbMax[0];
// edges
EdgeList edges;
// top
edges.push_back(make_shared<Edge>(make_pair(points[0], points[3])));
edges.push_back(make_shared<Edge>(make_pair(points[3], points[2])));
edges.push_back(make_shared<Edge>(make_pair(points[2], points[1])));
edges.push_back(make_shared<Edge>(make_pair(points[1], points[0])));
// bottom
edges.push_back(make_shared<Edge>(make_pair(points[4], points[7])));
edges.push_back(make_shared<Edge>(make_pair(points[7], points[6])));
edges.push_back(make_shared<Edge>(make_pair(points[6], points[5])));
edges.push_back(make_shared<Edge>(make_pair(points[5], points[4])));
// side
edges.push_back(make_shared<Edge>(make_pair(points[0], points[4])));
edges.push_back(make_shared<Edge>(make_pair(points[1], points[5])));
edges.push_back(make_shared<Edge>(make_pair(points[2], points[6])));
edges.push_back(make_shared<Edge>(make_pair(points[3], points[7])));
DrawEdgeList(edges, color);
}
#endif
| 34.16545 | 125 | 0.609457 | [
"geometry",
"object",
"transform"
] |
83eda78cd3ec6f136fd0963b24e9b228eda0d83f | 61,599 | cpp | C++ | project/test/basic_parser/exception.cpp | daishe/commander | 0a23abcbe406e234a4242e0d508bb89d72b28e25 | [
"BSL-1.0"
] | null | null | null | project/test/basic_parser/exception.cpp | daishe/commander | 0a23abcbe406e234a4242e0d508bb89d72b28e25 | [
"BSL-1.0"
] | null | null | null | project/test/basic_parser/exception.cpp | daishe/commander | 0a23abcbe406e234a4242e0d508bb89d72b28e25 | [
"BSL-1.0"
] | null | null | null | // Copyright Marek Dalewski 2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <commander/parser.hpp>
#include <boost/test/unit_test.hpp>
#include "helpers.hpp"
#include <optional>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <vector>
BOOST_AUTO_TEST_CASE( exception )
{
namespace com = commander;
using sv = std::string_view;
// using mismatch_error = com::mismatch_error<std::string, std::string>;
using missing_value_error = com::missing_value_error<std::string, std::string>;
using input_not_consumed = com::input_not_consumed<std::string, std::string>;
std::vector<std::tuple<std::string, std::string, std::string>> res;
auto true_callback = [&res](sv argument, sv header, auto value) -> bool {
if constexpr (com::is_placeholder_v<decltype(value)>)
res.emplace_back(argument, header, "placeholder_t");
else if constexpr (com::is_no_value_v<decltype(value)>)
res.emplace_back(argument, header, "no_value_t");
else if constexpr (std::is_same_v<decltype(value), int32_t>)
res.emplace_back(argument, header, std::string("int32_t ") + std::to_string(value));
else if constexpr (std::is_same_v<decltype(value), uint64_t>)
res.emplace_back(argument, header, std::string("uint64_t ") + std::to_string(value));
else
res.emplace_back(argument, header, value);
return true;
};
auto false_callback = [&true_callback](sv argument, sv header, auto value) -> bool {
return !true_callback(argument, header, value);
};
auto make_callback = [&true_callback, &false_callback](size_t count) -> auto {
return make_splited_callback(count, true_callback, false_callback);
};
commander::basic_parser<std::string_view, std::string> parser;
{
// -a -ab -abc
{
// -a
{
const char* arg = "-a";
// 0 0 1
{
res.clear();
parser(arg, make_callback(0));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, arg, "-a");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), arg, "-a", "int32_t 12345");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), arg, "-a", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
parser(arg, make_callback(0));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), arg, "-a", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
}
// -ab
{
const char* arg = "-ab";
// 0 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "-b");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, arg, "-b");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), arg, "-b", "int32_t 12345");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "-b");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 3);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), arg, "-b", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "-b");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), arg, "-b", "int32_t 12345");
parser();
}
// 2 0 1
{
res.clear();
parser(arg, make_callback(2));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "uint64_t 12345");
parser();
}
// 2 1
{
res.clear();
parser(arg, make_callback(2));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "int32_t 12345");
parser();
}
}
// -abc
{
const char* arg = "-abc";
// 0 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(1)), missing_value_error, arg, "-b");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(1)), missing_value_error, arg, "-b");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "int32_t 12345");
parser();
}
// 2 0 1
{
res.clear();
parser(arg, make_callback(2));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
CHECK_TUPLE_3(res.at(2), arg, "-c", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "-c");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 3);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, arg, "-c");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), arg, "-c", "int32_t 12345");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "-c");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 4);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 5);
CHECK_TUPLE_3(res.at(4), arg, "-c", "uint64_t 12345");
parser();
}
// 2 1
{
res.clear();
parser(arg, make_callback(2));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
CHECK_TUPLE_3(res.at(2), arg, "-c", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "-c");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 3);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), arg, "-c", "int32_t 12345");
parser();
}
// 3 0 1
{
res.clear();
parser(arg, make_callback(3));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
CHECK_TUPLE_3(res.at(2), arg, "-c", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 5);
CHECK_TUPLE_3(res.at(4), "--", "--", "uint64_t 12345");
parser();
}
// 3 1
{
res.clear();
parser(arg, make_callback(3));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
CHECK_TUPLE_3(res.at(2), arg, "-c", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "int32_t 12345");
parser();
}
}
}
// -a=v -ab=v -abc=v
{
// -a=v
{
const char* arg = "-a=v";
// 0 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), input_not_consumed, arg, "-a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), input_not_consumed, arg, "-a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
}
// -ab=v
{
const char* arg = "-ab=v";
// 0 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(1)), input_not_consumed, arg, "-b");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(1)), input_not_consumed, arg, "-b");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "int32_t 12345");
parser();
}
// 2 0 1
{
res.clear();
parser(arg, make_callback(2));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "uint64_t 12345");
parser();
}
// 2 1
{
res.clear();
parser(arg, make_callback(2));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "int32_t 12345");
parser();
}
}
// -abc=v
{
const char* arg = "-abc=v";
// 0 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), missing_value_error, arg, "-a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(1)), missing_value_error, arg, "-b");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(1)), missing_value_error, arg, "-b");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "int32_t 12345");
parser();
}
// 2 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(2)), input_not_consumed, arg, "-c");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
CHECK_TUPLE_3(res.at(2), arg, "-c", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 5);
CHECK_TUPLE_3(res.at(4), "--", "--", "uint64_t 12345");
parser();
}
// 2 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(2)), input_not_consumed, arg, "-c");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
CHECK_TUPLE_3(res.at(2), arg, "-c", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "int32_t 12345");
parser();
}
// 3 0 1
{
res.clear();
parser(arg, make_callback(3));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
CHECK_TUPLE_3(res.at(2), arg, "-c", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 5);
CHECK_TUPLE_3(res.at(4), "--", "--", "uint64_t 12345");
parser();
}
// 3 1
{
res.clear();
parser(arg, make_callback(3));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(0), arg, "-a", "no_value_t");
CHECK_TUPLE_3(res.at(1), arg, "-b", "no_value_t");
CHECK_TUPLE_3(res.at(2), arg, "-c", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 4);
CHECK_TUPLE_3(res.at(3), "--", "--", "int32_t 12345");
parser();
}
}
}
}
{
// --a --ab --abc
{
// --a
{
const char* arg = "--a";
// 0 0 1
{
res.clear();
parser(arg, make_callback(0));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--a", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "--a");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, arg, "--a");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), arg, "--a", "int32_t 12345");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "--a");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), arg, "--a", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
parser(arg, make_callback(0));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--a", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "--a");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), arg, "--a", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--a", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--a", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
}
// --ab
{
const char* arg = "--ab";
// 0 0 1
{
res.clear();
parser(arg, make_callback(0));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--ab", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "--ab");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, arg, "--ab");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), arg, "--ab", "int32_t 12345");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "--ab");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), arg, "--ab", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
parser(arg, make_callback(0));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--ab", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "--ab");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), arg, "--ab", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--ab", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--ab", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
}
// --abc
{
const char* arg = "--abc";
// 0 0 1
{
res.clear();
parser(arg, make_callback(0));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--abc", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "--abc");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, arg, "--abc");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), arg, "--abc", "int32_t 12345");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "--abc");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), arg, "--abc", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
parser(arg, make_callback(0));
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--abc", "placeholder_t");
CHECK_EXCEPTION_AH(parser(), missing_value_error, arg, "--abc");
BOOST_CHECK(parser.value() == arg); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), arg, "--abc", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--abc", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--abc", "placeholder_t");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
}
}
// --a=v --ab=v --abc=v
{
// --a=v
{
const char* arg = "--a=v";
// 0 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), input_not_consumed, arg, "--a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--a", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), input_not_consumed, arg, "--a");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--a", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--a", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--a", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
}
// --ab=v
{
const char* arg = "--ab=v";
// 0 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), input_not_consumed, arg, "--ab");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--ab", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), input_not_consumed, arg, "--ab");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--ab", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--ab", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--ab", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
}
// --abc=v
{
const char* arg = "--abc=v";
// 0 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), input_not_consumed, arg, "--abc");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--abc", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 0 1
{
res.clear();
CHECK_EXCEPTION_AH(parser(arg, make_callback(0)), input_not_consumed, arg, "--abc");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--abc", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
// 1 0 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--abc", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_EXCEPTION_AH(parser(int32_t(12345), make_callback(0)), input_not_consumed, "--", "--");
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
parser(uint64_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 3);
CHECK_TUPLE_3(res.at(2), "--", "--", "uint64_t 12345");
parser();
}
// 1 1
{
res.clear();
parser(arg, make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
CHECK_TUPLE_3(res.at(0), arg, "--abc", "v");
parser();
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 1);
parser(int32_t(12345), make_callback(1));
BOOST_CHECK(parser.value() == std::nullopt); BOOST_CHECK(res.size() == 2);
CHECK_TUPLE_3(res.at(1), "--", "--", "int32_t 12345");
parser();
}
}
}
}
}
| 42.658587 | 115 | 0.453092 | [
"vector"
] |
83f77bfb9f61bc03d94054cfae86957fd112c3d1 | 3,716 | hpp | C++ | dfg/iter/CustomAccessIterator.hpp | tc3t/dfglib | 7157973e952234a010da8e9fbd551a912c146368 | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2017-08-01T04:42:29.000Z | 2017-08-01T04:42:29.000Z | dfg/iter/CustomAccessIterator.hpp | tc3t/dfglib | 7157973e952234a010da8e9fbd551a912c146368 | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 128 | 2018-04-06T23:01:51.000Z | 2022-03-31T20:19:38.000Z | dfg/iter/CustomAccessIterator.hpp | tc3t/dfglib | 7157973e952234a010da8e9fbd551a912c146368 | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 3 | 2018-03-21T01:11:05.000Z | 2021-04-05T19:20:31.000Z | #pragma once
#include "../dfgDefs.hpp"
#include <iterator>
#include <tuple>
DFG_ROOT_NS_BEGIN{ DFG_SUB_NS(iter) {
// Iterator that provides custom access for existing iterator, for example iterator of int elements in std::vector<std::pair<int, double>>
template <class MainIterator_T, class Access_T>
class CustomAccessIterator
{
public:
using iterator_category = typename std::iterator_traits<MainIterator_T>::iterator_category;
using difference_type = typename std::iterator_traits<MainIterator_T>::difference_type;
using pointer = decltype(Access_T()(MainIterator_T()));
using value_type = typename std::remove_const<typename std::remove_pointer<pointer>::type>::type;
using reference = typename std::add_lvalue_reference<typename std::remove_pointer<pointer>::type>::type;
CustomAccessIterator(const MainIterator_T& iter)
: m_iter(iter)
{}
// Returns underlying iterator which this iterator uses.
MainIterator_T underlyingIterator() const
{
return m_iter;
}
auto operator->() const -> pointer
{
return Access_T()(m_iter);
}
auto operator*() const -> reference
{
return *operator->();
}
bool operator<(const CustomAccessIterator& other) const
{
return this->m_iter < other.m_iter;
}
bool operator==(const CustomAccessIterator& other) const
{
return this->m_iter == other.m_iter;
}
bool operator!=(const CustomAccessIterator& other) const
{
return !(*this == other);
}
CustomAccessIterator operator-(const difference_type nDiff) const
{
return CustomAccessIterator(m_iter - nDiff);
}
difference_type operator-(const CustomAccessIterator& other) const
{
return this->m_iter - other.m_iter;
}
CustomAccessIterator operator+(const difference_type nDiff) const
{
return CustomAccessIterator(m_iter + nDiff);
}
CustomAccessIterator& operator++()
{
++this->m_iter;
return *this;
}
CustomAccessIterator operator++(int)
{
auto iter = *this;
++*this;
return iter;
}
CustomAccessIterator& operator--()
{
--this->m_iter;
return *this;
}
CustomAccessIterator operator--(int)
{
auto iter = *this;
--*this;
return iter;
}
CustomAccessIterator& operator+=(difference_type nDiff)
{
this->m_iter += nDiff;
return *this;
}
CustomAccessIterator& operator-=(difference_type nDiff)
{
this->m_iter -= nDiff;
return *this;
}
MainIterator_T m_iter;
}; // class CustomAccessIterator
namespace DFG_DETAIL_NS
{
template <size_t Index_T, class Iter_T>
class TupleAccessFunc
{
public:
using TupleType = typename std::remove_reference<decltype(*Iter_T())>::type;
using ReturnValueType = typename std::tuple_element<Index_T, TupleType>::type;
ReturnValueType* operator()(const Iter_T& iter) const { using namespace std; return &get<Index_T>(*iter); }
};
}
// Returns custom access iterator that accesses tuple element in container of tuples.
// Example:
// std::vector<std::pair<std::string, double>> cont;
// auto stringIterator = makeTupleElementAccessIterator<0>(cont.begin());
// auto doubleIterator = makeTupleElementAccessIterator<1>(cont.begin());
template <size_t Index_T, class Iter_T>
auto makeTupleElementAccessIterator(const Iter_T& iter) -> CustomAccessIterator<Iter_T, DFG_DETAIL_NS::TupleAccessFunc<Index_T, Iter_T>>
{
return CustomAccessIterator<Iter_T, DFG_DETAIL_NS::TupleAccessFunc<Index_T, Iter_T>>(iter);
}
}} // module namespace
| 27.525926 | 138 | 0.670883 | [
"vector"
] |
83f8d67b0b4c4d83175a0a775cf919113ca22e3b | 2,730 | cpp | C++ | C++/Paradigm/3. Reduce.cpp | Alfonsxh/GeekbangNotes | 3949b26f10d73c2040399b32c18caac06f5823f1 | [
"Apache-2.0"
] | null | null | null | C++/Paradigm/3. Reduce.cpp | Alfonsxh/GeekbangNotes | 3949b26f10d73c2040399b32c18caac06f5823f1 | [
"Apache-2.0"
] | null | null | null | C++/Paradigm/3. Reduce.cpp | Alfonsxh/GeekbangNotes | 3949b26f10d73c2040399b32c18caac06f5823f1 | [
"Apache-2.0"
] | null | null | null | //
// Created by xiaohui on 19-1-24.
//
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/// 模板函数只遍历可迭代对象
/// \tparam Iter 迭代器类型
/// \tparam T 原始类型
/// \tparam Op 操作函数返回类型
/// \param start 迭代开始处
/// \param end 迭代结束处
/// \param init 结果初始化值
/// \param op 操作函数
/// \return
template<class Iter, class T, class Op>
T reduce(Iter start, Iter end, T init, Op op) {
T result = init;
for (; start != end; start++) {
result = op(result, *start);
}
return result;
}
// 雇员结构体
struct Employee {
string name;
string id;
int vacation;
double salary;
};
template<class T, class Cond>
struct counter {
Cond cond;
size_t operator()(size_t c, T t) {
return c + (cond(t) ? 1 : 0);
}
};
template<class Iter, class Cond>
size_t count_if(Iter begin, Iter end, Cond c) {
auto op = counter<typename Iter::value_type, Cond>{c};
return reduce(begin, end, size_t(0), op);
}
int main() {
vector<Employee> v_employee;
Employee employee_001 = {"Tom", "001", 10, 10000.0};
v_employee.push_back(employee_001);
Employee employee_002 = {"John", "002", 7, 220.0};
v_employee.push_back(employee_002);
Employee employee_003 = {"Alfons", "003", 6, 9000.0};
v_employee.push_back(employee_003);
Employee employee_004 = {"Mich", "004", 1, 101000.0};
v_employee.push_back(employee_004);
// 计算总薪金
double sum_salaries = reduce(v_employee.begin(), v_employee.end(), 0.0,
[](double s, Employee e) -> double { return s + e.salary; });
cout << "sum salaries is -> " << sum_salaries << endl;
// 计算最高薪金
double max_salary = reduce(v_employee.begin(), v_employee.end(), 0.0,
[](double s, Employee e) -> double {
return s > e.salary ? s : e.salary;
});
cout << "max salary is -> " << max_salary << endl;
// 计算最高薪金对象
Employee max_salary_person = reduce(v_employee.begin(), v_employee.end(), *v_employee.begin(),
[](Employee s, Employee e) -> Employee { return s.salary > e.salary ? s : e; });
cout << "max salary person is -> " << max_salary_person.name << endl;
// 计算最低薪金对象
Employee min_salary_person = reduce(v_employee.begin(), v_employee.end(), *v_employee.begin(),
[](Employee s, Employee e) -> Employee { return s.salary < e.salary ? s : e; });
cout << "min salary person is -> " << min_salary_person.name << endl;
size_t cnt = count_if(v_employee.begin(), v_employee.end(), [](Employee e) -> bool { return e.salary < 10000; });
cout << cnt <<endl;
return 0;
} | 29.673913 | 120 | 0.579487 | [
"vector"
] |
860940bec1ee0024bf8573b167a174f6b9b12717 | 2,299 | cpp | C++ | source/net/Net.cpp | wnewbery/cpphttp | adfc148716bc65aff29e881d1872c9dea6fc6af9 | [
"MIT"
] | 19 | 2017-03-28T02:17:42.000Z | 2021-02-12T03:26:58.000Z | source/net/Net.cpp | wnewbery/cpphttp | adfc148716bc65aff29e881d1872c9dea6fc6af9 | [
"MIT"
] | 3 | 2016-07-14T10:15:06.000Z | 2016-11-22T21:04:01.000Z | source/net/Net.cpp | wnewbery/cpphttp | adfc148716bc65aff29e881d1872c9dea6fc6af9 | [
"MIT"
] | 9 | 2017-10-19T07:15:42.000Z | 2019-09-17T07:08:25.000Z | #include "net/Net.hpp"
#include "net/Os.hpp"
#include "String.hpp"
#include <cassert>
#ifdef HTTP_USE_OPENSSL
#include "net/OpenSsl.hpp"
#endif
#ifdef _WIN32
#include "net/Schannel.hpp"
namespace http
{
namespace detail
{
SecurityFunctionTableW *sspi;
}
void init_net()
{
WSADATA wsa_data;
WSAStartup(MAKEWORD(2, 2), &wsa_data);
#ifdef HTTP_USE_OPENSSL
detail::init_openssl();
#else
detail::sspi = InitSecurityInterfaceW();
#endif
}
std::string win_error_string(int err)
{
struct Buffer
{
wchar_t *p;
Buffer() : p(nullptr) {}
~Buffer()
{
LocalFree(p);
}
};
Buffer buffer;
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&buffer.p, 0, nullptr);
return utf16_to_utf8(buffer.p);
}
int last_net_error()
{
return WSAGetLastError();
}
bool would_block(int err)
{
return err == WSAEWOULDBLOCK;
}
std::string errno_string(int err)
{
char buffer[1024];
if (strerror_s(buffer, sizeof(buffer), err))
throw std::runtime_error("strerror_s failed");
return buffer;
}
WinError::WinError(const char *msg)
: WinError(msg, GetLastError())
{}
}
#else
#include <cstring> //strerror_r
#include <vector>
#include <pthread.h>
#include <signal.h>
#include <iostream>
#include <cstdlib>
namespace http
{
void init_net()
{
detail::init_openssl();
//Linux sends a sigpipe when a socket or pipe has an error. better to handle the error where it
//happens at the read/write site
signal(SIGPIPE, SIG_IGN);
}
int last_net_error()
{
return errno;
}
bool would_block(int err)
{
return err == EAGAIN || err == EWOULDBLOCK;
}
std::string errno_string(int err)
{
char buffer[1024];
errno = 0;
auto ret = strerror_r(err, buffer, sizeof(buffer));
if (errno) throw std::runtime_error("strerror_r failed");
return ret;
}
}
#endif
| 22.105769 | 104 | 0.588082 | [
"vector"
] |
860fd3a02c2792311a4cd8aec1aa131fd88b435d | 2,202 | cpp | C++ | test/test_rewind.cpp | stfc-aeg/odin-data | 6c6353a11e0b813fc9db866ba610649dbbec95da | [
"Apache-2.0"
] | 7 | 2018-06-12T15:48:52.000Z | 2021-06-01T03:50:42.000Z | test/test_rewind.cpp | stfc-aeg/odin-data | 6c6353a11e0b813fc9db866ba610649dbbec95da | [
"Apache-2.0"
] | 211 | 2017-05-18T13:38:02.000Z | 2022-03-03T11:05:47.000Z | test/test_rewind.cpp | dls-controls/odin-data | ddbfb90d361d0b397fcfd30df4a749faaa8c84d6 | [
"Apache-2.0"
] | 8 | 2017-05-15T08:05:05.000Z | 2022-03-13T18:31:41.000Z | #include <iostream>
#include <vector>
#include <hdf5.h>
#include <hdf5_hl.h>
int main(int argc, char *argv[]) {
hsize_t CHUNK_NX = 704;
hsize_t CHUNK_NY = 1484;
size_t buf_size = CHUNK_NX * CHUNK_NY * sizeof(int16_t);
int16_t data_buf[CHUNK_NY][CHUNK_NX];
int16_t one_buf[CHUNK_NY][CHUNK_NX];
uint32_t filter_mask = 0;
hid_t dtype = H5T_NATIVE_UINT16;
static const hsize_t dims[] = {1, 1484, 1408};
std::vector<hsize_t> dset_dims(dims, dims + sizeof(dims)/ sizeof(dims[0]));
std::vector<hsize_t> max_dims = dset_dims;
max_dims[0] = H5S_UNLIMITED;
/* Create the data space */
hid_t dataspace = H5Screate_simple(dset_dims.size(), &dset_dims.front(), &max_dims.front());
/* Create a new file */
hid_t fapl = H5Pcreate(H5P_FILE_ACCESS);
H5Pset_libver_bounds(fapl, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST);
hid_t file = H5Fcreate("/tmp/rewind.hdf5", H5F_ACC_TRUNC, H5P_DEFAULT, fapl);
/* Create properties */
hid_t prop = H5Pcreate(H5P_DATASET_CREATE);
char fill_value[8] = {0, 0, 0, 0, 0, 0, 0, 0};
H5Pset_fill_value(prop, dtype, fill_value);
static const hsize_t cdims[] = {1, CHUNK_NY, CHUNK_NX};
std::vector<hsize_t> chunk_dims(cdims, cdims + sizeof(cdims)/ sizeof(cdims[0]));
H5Pset_chunk(prop, dset_dims.size(), &chunk_dims.front());
hid_t dapl = H5Pcreate(H5P_DATASET_ACCESS);
hid_t dset_id = H5Dcreate2(file, "data", dtype, dataspace, H5P_DEFAULT, prop, dapl);
/* Initialize data for one chunk */
int i, n, j;
for (i = n = 0; i < CHUNK_NY; i++) {
for (j = 0; j < CHUNK_NX; j++) {
data_buf[i][j] = n++;
one_buf[i][j] = 1;
}
}
/* Write chunk data using the direct write function. */
static const hsize_t offst[] = {0, 0, 0};
std::vector<hsize_t> offset(offst, offst + sizeof(offst)/ sizeof(offst[0]));
H5DOwrite_chunk(dset_id, H5P_DEFAULT, filter_mask, &offset.front(), buf_size, data_buf);
/* Write second chunk. */
offset[2] = CHUNK_NX;
H5DOwrite_chunk(dset_id, H5P_DEFAULT, filter_mask, &offset.front(), buf_size, data_buf);
/* Overwrite first chunk. */
offset[2] = 0;
H5DOwrite_chunk(dset_id, H5P_DEFAULT, filter_mask, &offset.front(), buf_size, one_buf);
H5Fclose(file);
return 0;
}
| 33.876923 | 94 | 0.683015 | [
"vector"
] |
861760f7560fb45f00bffff0b5c5954b40d89517 | 16,359 | cpp | C++ | src/physics/characters.cpp | wareya/kotareci | 14c87d1364d442456f93cebe73a288f85b79ba74 | [
"Libpng"
] | null | null | null | src/physics/characters.cpp | wareya/kotareci | 14c87d1364d442456f93cebe73a288f85b79ba74 | [
"Libpng"
] | null | null | null | src/physics/characters.cpp | wareya/kotareci | 14c87d1364d442456f93cebe73a288f85b79ba74 | [
"Libpng"
] | null | null | null | #include "subroutines.hpp"
#include "../input.hpp"
#include "../components/player.hpp"
#include "../blib/bmath.hpp"
#include <vector>
#ifdef CLIENT
#include "../samples.hpp"
#endif
static const float basegravity = 720;
static const float max_gravity = 2000;
static const float maxspeed = 300;
static const float jumpspeed = -300; // initial velocity of a jump in physics pixels per second
static const int max_bounces = 10; // number of bounces to handle during motion
static const int stepsize = 4; // size of stairs in physics pixels
float baseaccel = 1000;
float deaccel = 1300;
float struggleslow = 0.2f; // struggle reaches 0.2 at low end
float strugglehard = 0.15f; // struggle reaches 0.15 at high end
float strugglepoint = 0.25f; // The point on the acceleration curve with the LEAST struggle
namespace Sys
{
namespace Physicsers
{
// Benetnasch predicts movement and rescales it based on the actual time taken
// in order to compromise on the advantages of both delta time and interpolated timestep.
// Returns the hspeed after a given period of movement in terms of a given fixed rate.
float given_movement(double hspeed, Input::PlayerInput input, Sys::Character * character, float delta, int * info)
{
/* Due to REASONS, Benetnasch isn't using the typical += accel *= friction method of handling walking speed.
* Instead, we're going to "manually" model struggle as we approach the desired max speed.
*/
float delta_baseaccel = baseaccel*delta;
float delta_deaccel = deaccel*delta;
int direction = (input.inputs[Input::RIGHT] - input.inputs[Input::LEFT]);
// whether we're accelerating in the same direction we're moving
// (with "not" for not controlling)
int direction_agreement = (sign(direction) == sign(hspeed) and direction) != 0 ? 1 : -1;
// with "yes" for not moving, yet controlling
if (hspeed == 0 and direction) direction_agreement = 1;
if(direction_agreement == 1)
{
float speed = fabs(hspeed);
// We need to get how close we are to the max speed to model struggle
float fraction = speed/maxspeed;
bool started_lesser = (fraction < 1.0f);
//hspeed += direction * delta_baseaccel;
if(started_lesser)
{
// Transform how close we are to the max speed, into the modifier
if (fraction < strugglepoint)
{
fraction /= strugglepoint; // gradient 0 ~ 1
fraction *= 1.0f-struggleslow; // gradient ex. 0 ~ 0.8
fraction += struggleslow; // gradient ex. 0.2 ~ 1
}
else
{
fraction -= strugglepoint; // gradient ex. 0.75 ~ 0
fraction /= 1.0f-strugglepoint; //gradient ex. 1.0 ~ 0
fraction *= -1; // gradient ex. -1.0 ~ 0
fraction += 1; // gradient ex. 0 ~ 1.0
fraction *= fraction; // curve down
fraction *= 1.0f-strugglehard; // gradient ex. 0 ~ 0.85
fraction += strugglehard; // gradient ex. 0.15 ~ 1
}
//fraction /= 1.0f-strugglemodel;
speed += delta_baseaccel*fraction;
#define INFO_CHECKFAST (1<<0)
*info |= INFO_CHECKFAST;
hspeed = direction * speed;
}
else
{ // if we're agreeing with our movement, but STARTED going too fast,
// we need to use a completely different model in order to
// agree with the non-direction_agreement case.
// However, it still needs to be here (rather than non-direction_agreement)
// in order to gracefully go to maxspeed.
speed -= delta_deaccel;
#define INFO_CHECKSLOW (1<<1)
*info |= INFO_CHECKSLOW;
hspeed = sign(hspeed) * speed;
}
}
else // non-direction_agreement case
{
float speed = fabs(hspeed);
float apply = delta_deaccel;
if(direction == 0)
{ // Model struggle of approaching zero speed (rather than continuing to counter-accelerate) if we're not controlling
float fraction = speed/maxspeed;
if(fraction > 1.0)
fraction = 1.0;
fraction *= 1.0f-struggleslow; // gradient ex. 0 ~ 0.8
fraction += struggleslow; // gradient ex. 0.2 ~ 1
apply *= fraction;
}
#define INFO_CHECKREVERSE (1<<2)
if(fabs(hspeed) < delta_deaccel and direction == 0)
*info |= INFO_CHECKREVERSE;
hspeed -= sign(hspeed)*apply;
}
return hspeed;
}
bool MoveCharacters()
{
if(!Physicsers::delta_is_too_damn_low)
{
for(auto player : Sys::Players)
{
auto character = player->character;
if(!character)
continue;
/*
* predef
*/
double &x = character->position->x;
double &y = character->position->y;
double &hspeed = character->hspeed;
double &vspeed = character->vspeed;
Input::PlayerInput & input = player->input;
// Our acceleration code isn't perfectly framerate-independent, so we need to do a little black magic.
// It turns out that if you only have motion and force, doing delta time on it can work.
// I was stubborn about this for a while, but you just have to make the motion assuming half the force
// and then apply the full force to the velocity afterwards.
// Get the force of handling left/right inputs at particular "virtual" delta time
float virtual_delta = 1.0/85;
int info = 0;
float hforce = given_movement(hspeed, input, character, virtual_delta, &info) - hspeed;
hforce /= virtual_delta;
int oldhsign = sign(hspeed);
int jumping = (input.inputs[Input::JUMP] & !input.last_inputs[Input::JUMP]);
// Apply impulse to vertical velocity if jumping
if(jumping)
vspeed = jumpspeed;
bool started_feathery = (vspeed < max_gravity);
// Set up force of gravity
float vforce = 0;
if(!place_meeting(character, 0, 0.01) or jumping)
vforce = basegravity;
/*
* This is a continuous contact solver, but it doesn't handle e.g. bunnyhopping from the point you hit the ground.
*/
// In continuous time, the speed would have a total effect on the position
// corresponding to the average of the start and end velocities, at least assuming
// the start and end forces have a linear force being applied to them (i.e. zero "jerk")
// hforce/vforce would be applied for "delta" period of time.
// Basically, we want to change position by a force. Easy. But we want to apply
// a force to that force. This happens within the delta window as well.
// So "times delta" *should* happen twice here for the accelerations.
auto h_auto = hspeed + hforce*delta/2;
auto v_auto = vspeed + vforce*delta/2;
if(info & INFO_CHECKFAST)
if(abs(h_auto) > maxspeed)
h_auto = oldhsign * maxspeed;
if(info & INFO_CHECKSLOW)
if(abs(h_auto) < maxspeed)
h_auto = oldhsign * maxspeed;
if(info & INFO_CHECKREVERSE)
if(sign(h_auto) != oldhsign)
h_auto = 0;
if(v_auto > max_gravity and started_feathery)
v_auto = max_gravity;
// hspeed/vspeed would be applied to position for "delta" period of time".
// This is the vector of linear motion for the delta frame we're working on.
h_auto *= delta;
v_auto *= delta;
hspeed += hforce*delta;
vspeed += vforce*delta;
if(info & INFO_CHECKFAST)
if(abs(hspeed) > maxspeed)
hspeed = oldhsign * maxspeed;
if(info & INFO_CHECKSLOW)
if(abs(hspeed) < maxspeed)
hspeed = oldhsign * maxspeed;
if(info & INFO_CHECKREVERSE)
if(sign(hspeed) != oldhsign)
hspeed = 0;
if(vspeed > max_gravity and started_feathery)
vspeed = max_gravity;
/* movement solver starts here */
// we're in the wallmask; try to get out of it if it's really easy
if (place_meeting(character, 0, 0))
{
//puts("woaaAAAHHHh we're in the wallmask 1!");
for (int i = 1; i < stepsize; i += 1)
{
if(!place_meeting(character, 0, -i))
{
y -= i;
//puts("eject up");
break;
}
}
}
for (int i = max_bounces; i > 0; --i)
{
//puts("rectifying a collision");
float mx, my;
// move snugly to whatever we might've hit, and store the x and y deltas from that motion
std::tie(mx, my) = move_contact(character, h_auto, v_auto);
float travelled = sqdist(mx, my);
float totravel = sqdist(h_auto, v_auto);
h_auto -= mx;
v_auto -= my;
if (travelled < totravel) // we collided with something
{
// Check whether there's anything to our side
if(place_meeting(character, crop1(h_auto), 0))
{
// store original y before sloping
auto oy = y;
// check for slopes
if(!place_meeting(character, crop1(h_auto), stepsize)) // slope down a sloped ceiling step
y += stepsize;
else if(!place_meeting(character, crop1(h_auto), -stepsize)) // slope up a normal ground slope
y -= stepsize;
// no slope; it's a wall
if(oy == y)
{
hspeed = 0;
h_auto = 0;
}
}
// assume floor otherwise
else
{
vspeed = 0;
v_auto = 0;
}
}
// we did not collide with something
else
{
// we might want to "down" a slope
bool sloped = false;
// only if we're walking on the ground
if(vspeed == 0)
{
for (int i = stepsize; i <= abs(mx)+stepsize; i += stepsize)
{
if(!place_meeting(character, 0, i) and place_meeting(character, 0, i+1))
{
sloped = true;
//puts("downslope");
y += i;
vspeed = 0;
v_auto = 0;
break;
}
}
}
if(!sloped) // whole bounce with no collisions to do
{
h_auto = 0;
v_auto = 0;
break;
}
}
if(v_auto == 0 and h_auto == 0) // exhausted travellable period anyways
break;
}
// update weapon things
auto rawangle = input.aimDirection;
auto dir = deg2rad(rawangle);
int shooting = (input.inputs[Input::SHOOT] and not input.last_inputs[Input::SHOOT]);
if(shooting)
{
auto shotspeed = 800;
auto predistance = 20;
auto vx = cos(dir);
auto vy = -sin(dir);
for(auto i = -5; i <= 5; i++)
new Bullet(Ent::New(), character->center_x()+vx*predistance + vy*i*3, character->center_y()-6+vy*predistance - vx*i*3, vx*shotspeed + hspeed, vy*shotspeed, 1);
#ifdef CLIENT
fauxmix_emitter_fire(character->gun_emitter);
#endif
}
auto aiming_left = (rawangle >= 90 and rawangle < 270);
character->weaponsprite->angle = rawangle-180*aiming_left;
character->weaponsprite->flip = aiming_left;
character->stand->flip = aiming_left;
character->run->flip = aiming_left;
auto running = (fabs(hspeed) > 1);
character->stand->visible = !running;
character->run->visible = running;
if(running)
character->run->index += hspeed/35*delta*(character->run->flip*-2+1);
else
character->run->index = 0;
}
}
return false;
}
}
}
| 47.417391 | 187 | 0.420625 | [
"vector",
"model",
"transform"
] |
8622a71b233d145c261e6091e6e0d2cfa770408e | 34,389 | cpp | C++ | KeePass.1.39.a/KeePassLibCpp/Details/PwFileImpl.cpp | rrvt/KeePassLastPass | 217b627d906cf0af21ac69643a2d2e24e88f934b | [
"MIT"
] | null | null | null | KeePass.1.39.a/KeePassLibCpp/Details/PwFileImpl.cpp | rrvt/KeePassLastPass | 217b627d906cf0af21ac69643a2d2e24e88f934b | [
"MIT"
] | null | null | null | KeePass.1.39.a/KeePassLibCpp/Details/PwFileImpl.cpp | rrvt/KeePassLastPass | 217b627d906cf0af21ac69643a2d2e24e88f934b | [
"MIT"
] | null | null | null | /*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2021 Dominik Reichl <dominik.reichl@t-online.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "StdAfx.h"
#include "../PwManager.h"
#include "../Crypto/TwofishClass.h"
#include "../Crypto/SHA2/SHA2.h"
#include "../Crypto/ARCFour.h"
#include "../Util/AppUtil.h"
#include "../Util/Base64.h"
#include "../Util/PwUtil.h"
#include "../Util/MemUtil.h"
#include "../Util/StrUtil.h"
#include "../Util/TranslateEx.h"
#include "PwCompatImpl.h"
#include <boost/static_assert.hpp>
#define _OPENDB_FAIL_LIGHT \
{ \
if(pVirtualFile != NULL) \
{ \
mem_erase(pVirtualFile, uAllocated); \
SAFE_DELETE_ARRAY(pVirtualFile); \
} \
m_dwKeyEncRounds = PWM_STD_KEYENCROUNDS; \
}
#define _OPENDB_FAIL \
{ \
_OPENDB_FAIL_LIGHT; \
SAFE_DELETE_ARRAY(pwGroupTemplate.pszGroupName); \
SAFE_DELETE_ARRAY(pwEntryTemplate.pszTitle); \
SAFE_DELETE_ARRAY(pwEntryTemplate.pszURL); \
SAFE_DELETE_ARRAY(pwEntryTemplate.pszUserName); \
SAFE_DELETE_ARRAY(pwEntryTemplate.pszPassword); \
SAFE_DELETE_ARRAY(pwEntryTemplate.pszAdditional); \
SAFE_DELETE_ARRAY(pwEntryTemplate.pszBinaryDesc); \
SAFE_DELETE_ARRAY(pwEntryTemplate.pBinaryData); \
return PWE_INVALID_FILESTRUCTURE; \
}
#define RESET_TIME_FIELD_NORMAL(pTimeEx) { \
(pTimeEx)->btDay = 1; (pTimeEx)->btHour = 0; (pTimeEx)->btMinute = 0; \
(pTimeEx)->btMonth = 1; (pTimeEx)->btSecond = 0; (pTimeEx)->shYear = 2004; }
#define RESET_TIME_FIELD_EXPIRE(pTimeEx) { \
(pTimeEx)->btDay = 28; (pTimeEx)->btHour = 23; (pTimeEx)->btMinute = 59; \
(pTimeEx)->btMonth = 12; (pTimeEx)->btSecond = 59; (pTimeEx)->shYear = 4092; }
#define RESET_PWG_TEMPLATE(ptrx) { \
memset(ptrx, 0, sizeof(PW_GROUP)); \
RESET_TIME_FIELD_NORMAL(&(ptrx)->tCreation); RESET_TIME_FIELD_NORMAL(&(ptrx)->tLastMod); \
RESET_TIME_FIELD_NORMAL(&(ptrx)->tLastAccess); RESET_TIME_FIELD_EXPIRE(&(ptrx)->tExpire); }
#define RESET_PWE_TEMPLATE(ptrx) { \
memset(ptrx, 0, sizeof(PW_ENTRY)); \
RESET_TIME_FIELD_NORMAL(&(ptrx)->tCreation); RESET_TIME_FIELD_NORMAL(&(ptrx)->tLastMod); \
RESET_TIME_FIELD_NORMAL(&(ptrx)->tLastAccess); RESET_TIME_FIELD_EXPIRE(&(ptrx)->tExpire); }
// int CPwManager::OpenDatabase(const TCHAR *pszFile, _Out_opt_ PWDB_REPAIR_INFO *pRepair)
// {
// return this->OpenDatabaseEx(pszFile, pRepair, NULL);
// }
#define PWMOD_CHECK_AVAIL(w_Cnt_p) { if((static_cast<UINT64>(pos) + static_cast<UINT64>( \
w_Cnt_p)) > static_cast<UINT64>(uFileSize)) { ASSERT(FALSE); _OPENDB_FAIL; } }
// If bIgnoreCorrupted is TRUE the manager will try to ignore all database file
// errors, i.e. try to read as much as possible instead of breaking out at the
// first error.
// To open a file normally, set bIgnoreCorrupted to FALSE (default).
// To open a file in rescue mode, set it to TRUE.
int CPwManager::OpenDatabase(const TCHAR *pszFile, _Out_opt_ PWDB_REPAIR_INFO *pRepair)
{
char *pVirtualFile;
unsigned long uFileSize, uAllocated, uEncryptedPartSize;
unsigned long pos;
PW_DBHEADER hdr;
sha256_ctx sha32;
UINT8 uFinalKey[32];
char *p;
USHORT usFieldType;
DWORD dwFieldSize;
PW_GROUP pwGroupTemplate;
PW_ENTRY pwEntryTemplate;
BOOST_STATIC_ASSERT(sizeof(char) == 1);
ASSERT(pszFile != NULL); if(pszFile == NULL) return PWE_INVALID_PARAM;
ASSERT(pszFile[0] != 0); if(pszFile[0] == 0) return PWE_INVALID_PARAM; // Length != 0
RESET_PWG_TEMPLATE(&pwGroupTemplate);
RESET_PWE_TEMPLATE(&pwEntryTemplate);
if(pRepair != NULL) { ZeroMemory(pRepair, sizeof(PWDB_REPAIR_INFO)); }
FILE *fp = NULL;
_tfopen_s(&fp, pszFile, _T("rb"));
if(fp == NULL) return PWE_NOFILEACCESS_READ;
// Get file size
fseek(fp, 0, SEEK_END);
uFileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
if(uFileSize < sizeof(PW_DBHEADER))
{ fclose(fp); return PWE_INVALID_FILEHEADER; }
// Allocate enough memory to hold the complete file
uAllocated = uFileSize + 16 + 1 + 64 + 4; // 16 = encryption buffer space, 1+64 = string terminating NULLs, 4 unused
pVirtualFile = new char[uAllocated];
if(pVirtualFile == NULL) { fclose(fp); return PWE_NO_MEM; }
memset(&pVirtualFile[uFileSize + 16], 0, 1 + 64);
fread(pVirtualFile, 1, uFileSize, fp);
fclose(fp);
// Extract header structure from memory file
memcpy(&hdr, pVirtualFile, sizeof(PW_DBHEADER));
// Check if it's a KDBX file created by KeePass 2.x
if((hdr.dwSignature1 == PWM_DBSIG_1_KDBX_P) && (hdr.dwSignature2 == PWM_DBSIG_2_KDBX_P))
{ _OPENDB_FAIL_LIGHT; return PWE_UNSUPPORTED_KDBX; }
if((hdr.dwSignature1 == PWM_DBSIG_1_KDBX_R) && (hdr.dwSignature2 == PWM_DBSIG_2_KDBX_R))
{ _OPENDB_FAIL_LIGHT; return PWE_UNSUPPORTED_KDBX; }
// Check if we can open this
if((hdr.dwSignature1 != PWM_DBSIG_1) || (hdr.dwSignature2 != PWM_DBSIG_2))
{ _OPENDB_FAIL_LIGHT; return PWE_INVALID_FILESIGNATURE; }
if((hdr.dwVersion & 0xFFFFFF00) != (PWM_DBVER_DW & 0xFFFFFF00))
{
if((hdr.dwVersion == 0x00020000) || (hdr.dwVersion == 0x00020001) || (hdr.dwVersion == 0x00020002))
{
if(pVirtualFile != NULL)
{
mem_erase(pVirtualFile, uAllocated);
SAFE_DELETE_ARRAY(pVirtualFile);
}
return ((CPwCompatImpl::OpenDatabaseV2(this, pszFile) != FALSE) ?
PWE_SUCCESS : PWE_UNKNOWN);
}
else if(hdr.dwVersion <= 0x00010002)
{
if(pVirtualFile != NULL)
{
mem_erase(pVirtualFile, uAllocated);
SAFE_DELETE_ARRAY(pVirtualFile);
}
return ((CPwCompatImpl::OpenDatabaseV1(this, pszFile) != FALSE) ?
PWE_SUCCESS : PWE_UNKNOWN);
}
else { ASSERT(FALSE); _OPENDB_FAIL; }
}
if(hdr.dwGroups == 0) { _OPENDB_FAIL_LIGHT; return PWE_DB_EMPTY; }
// Select algorithm
if((hdr.dwFlags & PWM_FLAG_RIJNDAEL) != 0) m_nAlgorithm = ALGO_AES;
else if((hdr.dwFlags & PWM_FLAG_TWOFISH) != 0) m_nAlgorithm = ALGO_TWOFISH;
else { ASSERT(FALSE); _OPENDB_FAIL; }
m_dwKeyEncRounds = hdr.dwKeyEncRounds;
// Generate m_pTransformedMasterKey from m_pMasterKey
if(_TransformMasterKey(hdr.aMasterSeed2) == FALSE) { ASSERT(FALSE); _OPENDB_FAIL; }
ProtectTransformedMasterKey(false);
// Hash the master password with the salt in the file
sha256_begin(&sha32);
sha256_hash(hdr.aMasterSeed, 16, &sha32);
sha256_hash(m_pTransformedMasterKey, 32, &sha32);
sha256_end((unsigned char *)uFinalKey, &sha32);
ProtectTransformedMasterKey(true);
if(pRepair == NULL)
{
// ASSERT(((uFileSize - sizeof(PW_DBHEADER)) % 16) == 0);
if(((uFileSize - sizeof(PW_DBHEADER)) % 16) != 0)
{
_OPENDB_FAIL_LIGHT;
return PWE_INVALID_FILESIZE;
}
}
else // Repair the database
{
if(((uFileSize - sizeof(PW_DBHEADER)) % 16) != 0)
{
uFileSize -= sizeof(PW_DBHEADER); ASSERT((uFileSize & 0xF) != 0);
uFileSize &= ~0xFUL;
uFileSize += sizeof(PW_DBHEADER);
}
ASSERT(((uFileSize - sizeof(PW_DBHEADER)) % 16) == 0);
pRepair->dwOriginalGroupCount = hdr.dwGroups;
pRepair->dwOriginalEntryCount = hdr.dwEntries;
}
if(m_nAlgorithm == ALGO_AES)
{
CRijndael aes;
// Initialize Rijndael algorithm
if(aes.Init(CRijndael::CBC, CRijndael::DecryptDir, uFinalKey,
CRijndael::Key32Bytes, hdr.aEncryptionIV) != RIJNDAEL_SUCCESS)
{ _OPENDB_FAIL_LIGHT; return PWE_CRYPT_ERROR; }
// Decrypt! The first bytes aren't encrypted (that's the header)
uEncryptedPartSize = (unsigned long)aes.PadDecrypt((UINT8 *)pVirtualFile + sizeof(PW_DBHEADER),
uFileSize - sizeof(PW_DBHEADER), (UINT8 *)pVirtualFile + sizeof(PW_DBHEADER));
}
else if(m_nAlgorithm == ALGO_TWOFISH)
{
CTwofish twofish;
if(twofish.Init(uFinalKey, 32, hdr.aEncryptionIV) != true)
{ _OPENDB_FAIL };
uEncryptedPartSize = (unsigned long)twofish.PadDecrypt((UINT8 *)pVirtualFile + sizeof(PW_DBHEADER),
uFileSize - sizeof(PW_DBHEADER), (UINT8 *)pVirtualFile + sizeof(PW_DBHEADER));
}
else
{
ASSERT(FALSE); _OPENDB_FAIL; // This should never happen
}
mem_erase(uFinalKey, 32);
#if 0
// For debugging purposes, a file containing the plain text is created.
// This code of course must not be compiled into the final binary.
#pragma message("PLAIN TEXT OUTPUT IS ENABLED!")
#pragma message("DO NOT DISTRIBUTE THIS BINARY!")
// std::basic_string<TCHAR> tstrClear = pszFile;
// tstrClear += _T(".plaintext.bin");
// FILE *fpClear = NULL;
// _tfopen_s(&fpClear, tstrClear.c_str(), _T("wb"));
// fwrite(pVirtualFile, 1, uFileSize, fpClear);
// fclose(fpClear); fpClear = NULL;
#endif
// Check for success (non-repair mode only)
if(pRepair == NULL)
{
if((uEncryptedPartSize > 2147483446) || ((uEncryptedPartSize == 0) &&
((hdr.dwGroups != 0) || (hdr.dwEntries != 0))))
{
_OPENDB_FAIL_LIGHT;
return PWE_INVALID_KEY;
}
}
// Check if key is correct (with very high probability)
if(pRepair == NULL)
{
unsigned char vContentsHash[32];
sha256_begin(&sha32);
sha256_hash((unsigned char *)pVirtualFile + sizeof(PW_DBHEADER), uEncryptedPartSize, &sha32);
sha256_end(vContentsHash, &sha32);
if(memcmp(hdr.aContentsHash, vContentsHash, 32) != 0)
{ _OPENDB_FAIL_LIGHT; return PWE_INVALID_KEY; }
}
NewDatabase(); // Create a new database and initialize internal structures
ASSERT(memcmp(&hdr, pVirtualFile, sizeof(PW_DBHEADER)) == 0);
HashHeaderWithoutContentHash((BYTE*)pVirtualFile, m_vHeaderHash);
// Add groups from the memory file to the internal structures
pos = sizeof(PW_DBHEADER);
// char *pStart = &pVirtualFile[pos];
DWORD uCurGroup = 0;
while(uCurGroup < hdr.dwGroups)
{
p = &pVirtualFile[pos];
PWMOD_CHECK_AVAIL(2);
// if(pRepair != NULL) { if(IsBadReadPtr(p, 2) != FALSE) { _OPENDB_FAIL; } }
memcpy(&usFieldType, p, 2);
p += 2; pos += 2;
// if(pos >= uFileSize) { _OPENDB_FAIL; }
PWMOD_CHECK_AVAIL(4);
// if(pRepair != NULL) { if(IsBadReadPtr(p, 4) != FALSE) { _OPENDB_FAIL; } }
memcpy(&dwFieldSize, p, 4);
p += 4; pos += 4;
// if(pos >= (uFileSize + dwFieldSize)) { _OPENDB_FAIL; }
PWMOD_CHECK_AVAIL(dwFieldSize);
// if(pRepair != NULL) { if(IsBadReadPtr(p, dwFieldSize) != FALSE) { _OPENDB_FAIL; } }
if(!ReadGroupField(usFieldType, dwFieldSize, (BYTE *)p,
&pwGroupTemplate, pRepair)) { _OPENDB_FAIL; }
if(usFieldType == 0xFFFF)
++uCurGroup; // Now and ONLY now the counter gets increased
p += dwFieldSize;
// if(p < pStart) { _OPENDB_FAIL; }
pos += dwFieldSize;
// if(pos >= uFileSize) { _OPENDB_FAIL; }
}
SAFE_DELETE_ARRAY(pwGroupTemplate.pszGroupName);
// Get the entries
DWORD uCurEntry = 0;
while(uCurEntry < hdr.dwEntries)
{
p = &pVirtualFile[pos];
PWMOD_CHECK_AVAIL(2);
// if(pRepair != NULL) { if(IsBadReadPtr(p, 2) != FALSE) { _OPENDB_FAIL; } }
memcpy(&usFieldType, p, 2);
p += 2; pos += 2;
// if(pos >= uFileSize) { _OPENDB_FAIL; }
PWMOD_CHECK_AVAIL(4);
// if(pRepair != NULL) { if(IsBadReadPtr(p, 4) != FALSE) { _OPENDB_FAIL; } }
memcpy(&dwFieldSize, p, 4);
p += 4; pos += 4;
// if(pos >= (uFileSize + dwFieldSize)) { _OPENDB_FAIL; }
PWMOD_CHECK_AVAIL(dwFieldSize);
// if(pRepair != NULL) { if(IsBadReadPtr(p, dwFieldSize) != FALSE) { _OPENDB_FAIL; } }
if(!ReadEntryField(usFieldType, dwFieldSize, (BYTE *)p,
&pwEntryTemplate, pRepair)) { _OPENDB_FAIL; }
if(usFieldType == 0xFFFF)
++uCurEntry; // Now and ONLY now the counter gets increased
p += dwFieldSize;
// if(p < pStart) { _OPENDB_FAIL; }
pos += dwFieldSize;
// if(pos >= uFileSize) { _OPENDB_FAIL; }
}
SAFE_DELETE_ARRAY(pwEntryTemplate.pszTitle);
SAFE_DELETE_ARRAY(pwEntryTemplate.pszURL);
SAFE_DELETE_ARRAY(pwEntryTemplate.pszUserName);
SAFE_DELETE_ARRAY(pwEntryTemplate.pszPassword);
SAFE_DELETE_ARRAY(pwEntryTemplate.pszAdditional);
SAFE_DELETE_ARRAY(pwEntryTemplate.pszBinaryDesc);
SAFE_DELETE_ARRAY(pwEntryTemplate.pBinaryData);
memcpy(&m_dbLastHeader, &hdr, sizeof(PW_DBHEADER));
// Erase and delete memory file
mem_erase(pVirtualFile, uAllocated);
SAFE_DELETE_ARRAY(pVirtualFile);
const DWORD dwRemovedStreams = _LoadAndRemoveAllMetaStreams(true);
if(pRepair != NULL) pRepair->dwRecognizedMetaStreamCount = dwRemovedStreams;
VERIFY(DeleteLostEntries() == 0);
FixGroupTree();
return PWE_SUCCESS;
}
int CPwManager::SaveDatabase(const TCHAR *pszFile, BYTE *pWrittenDataHash32)
{
DWORD uEncryptedPartSize, i, pos, dwFieldSize;
UINT8 uFinalKey[32];
sha256_ctx sha32;
USHORT usFieldType;
BYTE aCompressedTime[5];
ASSERT(pszFile != NULL);
if(pszFile == NULL) return PWE_INVALID_PARAM;
ASSERT(pszFile[0] != 0);
if(pszFile[0] == 0) return PWE_INVALID_PARAM;
if(m_dwNumGroups == 0) return PWE_DB_EMPTY;
_AddAllMetaStreams();
UINT64 qwFileSize = sizeof(PW_DBHEADER);
BYTE *pbt;
// Create a dummy ext data structure for computing its size
m_vHeaderHash.resize(32);
CKpMemoryStream msExtDataSize(true);
WriteExtData(msExtDataSize);
qwFileSize += 2 + 4 + msExtDataSize.GetSize();
// Get the size of all groups
for(i = 0; i < m_dwNumGroups; ++i)
{
qwFileSize += 94; // 6+4+6+6+5+6+5+6+5+6+5+6+4+6+6+2+6+4 = 94
pbt = _StringToUTF8(m_pGroups[i].pszGroupName);
qwFileSize += szlen((char *)pbt) + 1;
SAFE_DELETE_ARRAY(pbt);
}
// Get the size of all entries together
for(i = 0; i < m_dwNumEntries; ++i)
{
ASSERT_ENTRY(&m_pEntries[i]);
UnlockEntryPassword(&m_pEntries[i]);
qwFileSize += 134; // 6+16+6+4+6+4+6+6+6+6+6+6+5+6+5+6+5+6+5+6 = 122
pbt = _StringToUTF8(m_pEntries[i].pszTitle);
qwFileSize += szlen((char *)pbt) + 1;
SAFE_DELETE_ARRAY(pbt);
pbt = _StringToUTF8(m_pEntries[i].pszUserName);
qwFileSize += szlen((char *)pbt) + 1;
SAFE_DELETE_ARRAY(pbt);
pbt = _StringToUTF8(m_pEntries[i].pszURL);
qwFileSize += szlen((char *)pbt) + 1;
SAFE_DELETE_ARRAY(pbt);
pbt = _StringToUTF8(m_pEntries[i].pszPassword);
qwFileSize += szlen((char *)pbt) + 1;
SAFE_DELETE_ARRAY(pbt);
pbt = _StringToUTF8(m_pEntries[i].pszAdditional);
qwFileSize += szlen((char *)pbt) + 1;
SAFE_DELETE_ARRAY(pbt);
pbt = _StringToUTF8(m_pEntries[i].pszBinaryDesc);
qwFileSize += szlen((char *)pbt) + 1;
SAFE_DELETE_ARRAY(pbt);
qwFileSize += m_pEntries[i].uBinaryDataLen;
LockEntryPassword(&m_pEntries[i]);
}
// Round up file size to 16-byte boundary for Rijndael/Twofish
qwFileSize = (qwFileSize + 16) - (qwFileSize % 16);
const UINT64 qwAlloc = qwFileSize + 16;
if(qwAlloc > 0xFFFFFFFFULL) { _LoadAndRemoveAllMetaStreams(false); return PWE_NO_MEM; }
const DWORD uAlloc = static_cast<DWORD>(qwAlloc);
char *pVirtualFile = NULL;
try { pVirtualFile = new char[uAlloc]; }
catch(...) { }
if(pVirtualFile == NULL) { _LoadAndRemoveAllMetaStreams(false); return PWE_NO_MEM; }
// Build header structure
PW_DBHEADER hdr;
hdr.dwSignature1 = PWM_DBSIG_1;
hdr.dwSignature2 = PWM_DBSIG_2;
hdr.dwFlags = PWM_FLAG_SHA2; // The one and only hash algorithm available currently
if(m_nAlgorithm == ALGO_AES) hdr.dwFlags |= PWM_FLAG_RIJNDAEL;
else if(m_nAlgorithm == ALGO_TWOFISH) hdr.dwFlags |= PWM_FLAG_TWOFISH;
else { ASSERT(FALSE); _LoadAndRemoveAllMetaStreams(false); return PWE_INVALID_PARAM; }
hdr.dwVersion = PWM_DBVER_DW;
hdr.dwGroups = m_dwNumGroups;
hdr.dwEntries = m_dwNumEntries;
hdr.dwKeyEncRounds = m_dwKeyEncRounds;
// Make up the master key hash seed and the encryption IV
m_random.GetRandomBuffer(hdr.aMasterSeed, 16);
m_random.GetRandomBuffer((BYTE *)hdr.aEncryptionIV, 16);
m_random.GetRandomBuffer(hdr.aMasterSeed2, 32);
// We have everything except the contents hash
HashHeaderWithoutContentHash((BYTE*)&hdr, m_vHeaderHash);
CKpMemoryStream msExtData(true);
WriteExtData(msExtData);
ASSERT(msExtData.GetSize() == msExtDataSize.GetSize());
// Skip the header, it will be written later
pos = sizeof(PW_DBHEADER);
BYTE *pb;
// Store all groups to memory file
for(i = 0; i < m_dwNumGroups; ++i)
{
if(i == 0)
{
usFieldType = 0x0000; dwFieldSize = static_cast<DWORD>(msExtData.GetSize());
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
memcpy(&pVirtualFile[pos], msExtData.GetBuffer(), dwFieldSize); pos += dwFieldSize;
}
usFieldType = 0x0001; dwFieldSize = 4;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
memcpy(&pVirtualFile[pos], &m_pGroups[i].uGroupId, 4); pos += 4;
pb = _StringToUTF8(m_pGroups[i].pszGroupName);
usFieldType = 0x0002; dwFieldSize = szlen((char *)pb) + 1;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
ASSERT((pb != NULL) && (szlen((char *)pb) == (dwFieldSize - 1)) && ((pos + dwFieldSize) <= qwAlloc));
szcpy(&pVirtualFile[pos], (char *)pb); pos += dwFieldSize;
SAFE_DELETE_ARRAY(pb);
usFieldType = 0x0003; dwFieldSize = 5;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
CPwUtil::PwTimeToTime(&m_pGroups[i].tCreation, aCompressedTime);
memcpy(&pVirtualFile[pos], aCompressedTime, 5); pos += 5;
usFieldType = 0x0004; dwFieldSize = 5;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
CPwUtil::PwTimeToTime(&m_pGroups[i].tLastMod, aCompressedTime);
memcpy(&pVirtualFile[pos], aCompressedTime, 5); pos += 5;
usFieldType = 0x0005; dwFieldSize = 5;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
CPwUtil::PwTimeToTime(&m_pGroups[i].tLastAccess, aCompressedTime);
memcpy(&pVirtualFile[pos], aCompressedTime, 5); pos += 5;
usFieldType = 0x0006; dwFieldSize = 5;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
CPwUtil::PwTimeToTime(&m_pGroups[i].tExpire, aCompressedTime);
memcpy(&pVirtualFile[pos], aCompressedTime, 5); pos += 5;
usFieldType = 0x0007; dwFieldSize = 4;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
memcpy(&pVirtualFile[pos], &m_pGroups[i].uImageId, 4); pos += 4;
usFieldType = 0x0008; dwFieldSize = 2;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
memcpy(&pVirtualFile[pos], &m_pGroups[i].usLevel, 2); pos += 2;
usFieldType = 0x0009; dwFieldSize = 4;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
memcpy(&pVirtualFile[pos], &m_pGroups[i].dwFlags, 4); pos += 4;
usFieldType = 0xFFFF; dwFieldSize = 0;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
}
// Store all entries to memory file
for(i = 0; i < m_dwNumEntries; ++i)
{
UnlockEntryPassword(&m_pEntries[i]);
usFieldType = 0x0001; dwFieldSize = 16;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
memcpy(&pVirtualFile[pos], &m_pEntries[i].uuid, 16); pos += 16;
usFieldType = 0x0002; dwFieldSize = 4;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
memcpy(&pVirtualFile[pos], &m_pEntries[i].uGroupId, 4); pos += 4;
usFieldType = 0x0003; dwFieldSize = 4;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
memcpy(&pVirtualFile[pos], &m_pEntries[i].uImageId, 4); pos += 4;
pb = _StringToUTF8(m_pEntries[i].pszTitle);
usFieldType = 0x0004;
dwFieldSize = szlen((char *)pb) + 1; // Add terminating NULL character space
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
ASSERT((pb != NULL) && (szlen((char *)pb) == (dwFieldSize - 1)) && ((pos + dwFieldSize) <= qwAlloc));
szcpy(&pVirtualFile[pos], (char *)pb); pos += dwFieldSize;
SAFE_DELETE_ARRAY(pb);
pb = _StringToUTF8(m_pEntries[i].pszURL);
usFieldType = 0x0005;
dwFieldSize = szlen((char *)pb) + 1; // Add terminating NULL character space
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
ASSERT((pb != NULL) && (szlen((char *)pb) == (dwFieldSize - 1)) && ((pos + dwFieldSize) <= qwAlloc));
szcpy(&pVirtualFile[pos], (char *)pb); pos += dwFieldSize;
SAFE_DELETE_ARRAY(pb);
pb = _StringToUTF8(m_pEntries[i].pszUserName);
usFieldType = 0x0006;
dwFieldSize = szlen((char *)pb) + 1; // Add terminating NULL character space
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
ASSERT((pb != NULL) && (szlen((char *)pb) == (dwFieldSize - 1)) && ((pos + dwFieldSize) <= qwAlloc));
szcpy(&pVirtualFile[pos], (char *)pb); pos += dwFieldSize;
SAFE_DELETE_ARRAY(pb);
pb = _StringToUTF8(m_pEntries[i].pszPassword);
usFieldType = 0x0007;
dwFieldSize = szlen((char *)pb) + 1; // Add terminating NULL character space
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
ASSERT((pb != NULL) && (szlen((char *)pb) == (dwFieldSize - 1)) && ((pos + dwFieldSize) <= qwAlloc));
szcpy(&pVirtualFile[pos], (char *)pb); pos += dwFieldSize;
if(pb != NULL) mem_erase(pb, szlen((char *)pb));
SAFE_DELETE_ARRAY(pb);
pb = _StringToUTF8(m_pEntries[i].pszAdditional);
usFieldType = 0x0008;
dwFieldSize = szlen((char *)pb) + 1; // Add terminating NULL character space
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
ASSERT((pb != NULL) && (szlen((char *)pb) == (dwFieldSize - 1)) && ((pos + dwFieldSize) <= qwAlloc));
szcpy(&pVirtualFile[pos], (char *)pb); pos += dwFieldSize;
SAFE_DELETE_ARRAY(pb);
usFieldType = 0x0009; dwFieldSize = 5;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
CPwUtil::PwTimeToTime(&m_pEntries[i].tCreation, aCompressedTime);
memcpy(&pVirtualFile[pos], aCompressedTime, 5); pos += 5;
usFieldType = 0x000A; dwFieldSize = 5;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
CPwUtil::PwTimeToTime(&m_pEntries[i].tLastMod, aCompressedTime);
memcpy(&pVirtualFile[pos], aCompressedTime, 5); pos += 5;
usFieldType = 0x000B; dwFieldSize = 5;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
CPwUtil::PwTimeToTime(&m_pEntries[i].tLastAccess, aCompressedTime);
memcpy(&pVirtualFile[pos], aCompressedTime, 5); pos += 5;
usFieldType = 0x000C; dwFieldSize = 5;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
CPwUtil::PwTimeToTime(&m_pEntries[i].tExpire, aCompressedTime);
memcpy(&pVirtualFile[pos], aCompressedTime, 5); pos += 5;
pb = _StringToUTF8(m_pEntries[i].pszBinaryDesc);
usFieldType = 0x000D;
dwFieldSize = szlen((char *)pb) + 1;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
ASSERT((pb != NULL) && (szlen((char *)pb) == (dwFieldSize - 1)) && ((pos + dwFieldSize) <= qwAlloc));
szcpy(&pVirtualFile[pos], (char *)pb); pos += dwFieldSize;
SAFE_DELETE_ARRAY(pb);
usFieldType = 0x000E; dwFieldSize = m_pEntries[i].uBinaryDataLen;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
if((m_pEntries[i].pBinaryData != NULL) && (dwFieldSize != 0))
memcpy(&pVirtualFile[pos], m_pEntries[i].pBinaryData, dwFieldSize);
pos += dwFieldSize;
usFieldType = 0xFFFF; dwFieldSize = 0;
memcpy(&pVirtualFile[pos], &usFieldType, 2); pos += 2;
memcpy(&pVirtualFile[pos], &dwFieldSize, 4); pos += 4;
LockEntryPassword(&m_pEntries[i]);
}
ASSERT((pos <= qwFileSize) && ((pos + 33) > qwAlloc));
sha256_begin(&sha32);
sha256_hash((unsigned char *)pVirtualFile + sizeof(PW_DBHEADER), pos - sizeof(PW_DBHEADER), &sha32);
sha256_end((unsigned char *)hdr.aContentsHash, &sha32);
// Copy the completed header
memcpy(pVirtualFile, &hdr, sizeof(PW_DBHEADER));
// Generate m_pTransformedMasterKey from m_pMasterKey
if(_TransformMasterKey(hdr.aMasterSeed2) == FALSE)
{ ASSERT(FALSE); SAFE_DELETE_ARRAY(pVirtualFile); _LoadAndRemoveAllMetaStreams(false); return PWE_CRYPT_ERROR; }
ProtectTransformedMasterKey(false);
// Hash the master password with the generated hash salt
sha256_begin(&sha32);
sha256_hash(hdr.aMasterSeed, 16, &sha32);
sha256_hash(m_pTransformedMasterKey, 32, &sha32);
sha256_end((unsigned char *)uFinalKey, &sha32);
ProtectTransformedMasterKey(true);
#if 0
// For debugging purposes, a file containing the plain text is created.
// This code of course must not be compiled into the final binary.
#pragma message("PLAIN TEXT OUTPUT IS ENABLED!")
#pragma message("DO NOT DISTRIBUTE THIS BINARY!")
// std::basic_string<TCHAR> tstrClear = pszFile;
// tstrClear += _T(".plaintext.bin");
// FILE *fpClear = NULL;
// _tfopen_s(&fpClear, tstrClear.c_str(), _T("wb"));
// fwrite(pVirtualFile, 1, static_cast<size_t>(qwFileSize), fpClear);
// fclose(fpClear); fpClear = NULL;
#endif
if(m_nAlgorithm == ALGO_AES)
{
CRijndael aes;
if(aes.Init(CRijndael::CBC, CRijndael::EncryptDir, uFinalKey,
CRijndael::Key32Bytes, hdr.aEncryptionIV) != RIJNDAEL_SUCCESS)
{
SAFE_DELETE_ARRAY(pVirtualFile);
_LoadAndRemoveAllMetaStreams(false);
return PWE_CRYPT_ERROR;
}
uEncryptedPartSize = static_cast<unsigned long>(aes.PadEncrypt(
(UINT8 *)pVirtualFile + sizeof(PW_DBHEADER), pos - sizeof(PW_DBHEADER),
(UINT8 *)pVirtualFile + sizeof(PW_DBHEADER)));
}
else if(m_nAlgorithm == ALGO_TWOFISH)
{
CTwofish twofish;
if(twofish.Init(uFinalKey, 32, hdr.aEncryptionIV) == false)
{
SAFE_DELETE_ARRAY(pVirtualFile);
_LoadAndRemoveAllMetaStreams(false);
return PWE_CRYPT_ERROR;
}
uEncryptedPartSize = static_cast<unsigned long>(twofish.PadEncrypt(
(UINT8 *)pVirtualFile + sizeof(PW_DBHEADER),
pos - sizeof(PW_DBHEADER), (UINT8 *)pVirtualFile + sizeof(PW_DBHEADER)));
}
else
{
ASSERT(FALSE);
SAFE_DELETE_ARRAY(pVirtualFile);
_LoadAndRemoveAllMetaStreams(false);
return PWE_INVALID_PARAM;
}
mem_erase(uFinalKey, 32);
// Check if all went correct
ASSERT((uEncryptedPartSize % 16) == 0);
if((uEncryptedPartSize > 2147483446) || ((uEncryptedPartSize == 0) &&
(this->GetNumberOfGroups() != 0)))
{
ASSERT(FALSE);
SAFE_DELETE_ARRAY(pVirtualFile);
_LoadAndRemoveAllMetaStreams(false);
return PWE_CRYPT_ERROR;
}
const DWORD dwToWrite = uEncryptedPartSize + sizeof(PW_DBHEADER);
const int nWriteRes = AU_WriteBigFile(pszFile, (BYTE *)pVirtualFile, dwToWrite,
m_bUseTransactedFileWrites);
if(nWriteRes != PWE_SUCCESS)
{
mem_erase(pVirtualFile, uAlloc);
SAFE_DELETE_ARRAY(pVirtualFile);
_LoadAndRemoveAllMetaStreams(false);
return nWriteRes;
}
if(pWrittenDataHash32 != NULL) // Caller requests hash of written data
{
sha256_ctx shaWritten;
sha256_begin(&shaWritten);
sha256_hash((unsigned char *)pVirtualFile, dwToWrite, &shaWritten);
sha256_end(pWrittenDataHash32, &shaWritten);
}
memcpy(&m_dbLastHeader, &hdr, sizeof(PW_DBHEADER)); // Backup last database header
mem_erase(pVirtualFile, uAlloc);
SAFE_DELETE_ARRAY(pVirtualFile);
_LoadAndRemoveAllMetaStreams(false);
return PWE_SUCCESS;
}
#define PWMRF_CHECK_AVAIL(w_Cnt_q) { if(dwFieldSize < static_cast<DWORD>(w_Cnt_q)) { \
ASSERT(FALSE); return false; } else { ASSERT(dwFieldSize == static_cast<DWORD>(w_Cnt_q)); } }
bool CPwManager::ReadGroupField(USHORT usFieldType, DWORD dwFieldSize,
const BYTE *pData, PW_GROUP *pGroup, PWDB_REPAIR_INFO *pRepair)
{
BYTE aCompressedTime[5];
switch(usFieldType)
{
case 0x0000:
if(!ReadExtData(pData, dwFieldSize, pGroup, NULL, pRepair)) return false;
break;
case 0x0001:
PWMRF_CHECK_AVAIL(4);
memcpy(&pGroup->uGroupId, pData, 4);
break;
case 0x0002:
ASSERT(dwFieldSize != 0);
SAFE_DELETE_ARRAY(pGroup->pszGroupName);
pGroup->pszGroupName = _UTF8ToString((UTF8_BYTE *)pData);
break;
case 0x0003:
PWMRF_CHECK_AVAIL(5);
memcpy(aCompressedTime, pData, 5);
CPwUtil::TimeToPwTime(aCompressedTime, &pGroup->tCreation);
break;
case 0x0004:
PWMRF_CHECK_AVAIL(5);
memcpy(aCompressedTime, pData, 5);
CPwUtil::TimeToPwTime(aCompressedTime, &pGroup->tLastMod);
break;
case 0x0005:
PWMRF_CHECK_AVAIL(5);
memcpy(aCompressedTime, pData, 5);
CPwUtil::TimeToPwTime(aCompressedTime, &pGroup->tLastAccess);
break;
case 0x0006:
PWMRF_CHECK_AVAIL(5);
memcpy(aCompressedTime, pData, 5);
CPwUtil::TimeToPwTime(aCompressedTime, &pGroup->tExpire);
break;
case 0x0007:
PWMRF_CHECK_AVAIL(4);
memcpy(&pGroup->uImageId, pData, 4);
break;
case 0x0008:
PWMRF_CHECK_AVAIL(2);
memcpy(&pGroup->usLevel, pData, 2);
break;
case 0x0009:
PWMRF_CHECK_AVAIL(4);
memcpy(&pGroup->dwFlags, pData, 4);
break;
case 0xFFFF:
AddGroup(pGroup);
SAFE_DELETE_ARRAY(pGroup->pszGroupName);
RESET_PWG_TEMPLATE(pGroup);
break;
default:
ASSERT(FALSE);
break;
}
return true;
}
bool CPwManager::ReadEntryField(USHORT usFieldType, DWORD dwFieldSize,
const BYTE *pData, PW_ENTRY *pEntry, PWDB_REPAIR_INFO *pRepair)
{
BYTE aCompressedTime[5];
switch(usFieldType)
{
case 0x0000:
if(!ReadExtData(pData, dwFieldSize, NULL, pEntry, pRepair)) return false;
break;
case 0x0001:
PWMRF_CHECK_AVAIL(16);
memcpy(pEntry->uuid, pData, 16);
break;
case 0x0002:
PWMRF_CHECK_AVAIL(4);
memcpy(&pEntry->uGroupId, pData, 4);
break;
case 0x0003:
PWMRF_CHECK_AVAIL(4);
memcpy(&pEntry->uImageId, pData, 4);
break;
case 0x0004:
ASSERT(dwFieldSize != 0);
SAFE_DELETE_ARRAY(pEntry->pszTitle);
pEntry->pszTitle = _UTF8ToString((UTF8_BYTE *)pData);
break;
case 0x0005:
ASSERT(dwFieldSize != 0);
SAFE_DELETE_ARRAY(pEntry->pszURL);
pEntry->pszURL = _UTF8ToString((UTF8_BYTE *)pData);
break;
case 0x0006:
ASSERT(dwFieldSize != 0);
SAFE_DELETE_ARRAY(pEntry->pszUserName);
pEntry->pszUserName = _UTF8ToString((UTF8_BYTE *)pData);
break;
case 0x0007:
ASSERT(dwFieldSize != 0);
if(pEntry->pszPassword != NULL)
mem_erase(pEntry->pszPassword, _tcslen(pEntry->pszPassword) * sizeof(TCHAR));
SAFE_DELETE_ARRAY(pEntry->pszPassword);
pEntry->pszPassword = _UTF8ToString((UTF8_BYTE *)pData);
break;
case 0x0008:
ASSERT(dwFieldSize != 0);
SAFE_DELETE_ARRAY(pEntry->pszAdditional);
pEntry->pszAdditional = _UTF8ToString((UTF8_BYTE *)pData);
break;
case 0x0009:
PWMRF_CHECK_AVAIL(5);
memcpy(aCompressedTime, pData, 5);
CPwUtil::TimeToPwTime(aCompressedTime, &pEntry->tCreation);
break;
case 0x000A:
PWMRF_CHECK_AVAIL(5);
memcpy(aCompressedTime, pData, 5);
CPwUtil::TimeToPwTime(aCompressedTime, &pEntry->tLastMod);
break;
case 0x000B:
PWMRF_CHECK_AVAIL(5);
memcpy(aCompressedTime, pData, 5);
CPwUtil::TimeToPwTime(aCompressedTime, &pEntry->tLastAccess);
break;
case 0x000C:
PWMRF_CHECK_AVAIL(5);
memcpy(aCompressedTime, pData, 5);
CPwUtil::TimeToPwTime(aCompressedTime, &pEntry->tExpire);
break;
case 0x000D:
ASSERT(dwFieldSize != 0);
SAFE_DELETE_ARRAY(pEntry->pszBinaryDesc);
pEntry->pszBinaryDesc = _UTF8ToString((UTF8_BYTE *)pData);
break;
case 0x000E:
SAFE_DELETE_ARRAY(pEntry->pBinaryData);
if(dwFieldSize != 0)
{
pEntry->pBinaryData = new BYTE[dwFieldSize];
memcpy(pEntry->pBinaryData, pData, dwFieldSize);
pEntry->uBinaryDataLen = dwFieldSize;
}
break;
case 0xFFFF:
ASSERT(dwFieldSize == 0);
AddEntry(pEntry);
SAFE_DELETE_ARRAY(pEntry->pszTitle);
SAFE_DELETE_ARRAY(pEntry->pszURL);
SAFE_DELETE_ARRAY(pEntry->pszUserName);
if(pEntry->pszPassword != NULL)
mem_erase(pEntry->pszPassword, _tcslen(pEntry->pszPassword) * sizeof(TCHAR));
SAFE_DELETE_ARRAY(pEntry->pszPassword);
SAFE_DELETE_ARRAY(pEntry->pszAdditional);
SAFE_DELETE_ARRAY(pEntry->pszBinaryDesc);
SAFE_DELETE_ARRAY(pEntry->pBinaryData);
RESET_PWE_TEMPLATE(pEntry);
break;
default:
ASSERT(FALSE);
break;
}
return true;
}
bool CPwManager::ReadExtData(const BYTE* pData, DWORD dwDataSize, PW_GROUP* pg,
PW_ENTRY* pe, PWDB_REPAIR_INFO* pRepair)
{
// No group- or entry-specific ext data yet
UNREFERENCED_PARAMETER(pg);
UNREFERENCED_PARAMETER(pe);
if(dwDataSize == 0) return true;
CKpMemoryStream ms(pData, dwDataSize);
std::vector<BYTE> vFieldData;
bool bEos = false, bResult = true;
while(!bEos)
{
USHORT usFieldType;
DWORD dwFieldSize;
if(FAILED(ms.Read((BYTE*)&usFieldType, 2))) { bResult = false; break; }
if(FAILED(ms.Read((BYTE*)&dwFieldSize, 4))) { bResult = false; break; }
if(dwFieldSize > 0)
{
if(vFieldData.size() < dwFieldSize) vFieldData.resize(dwFieldSize);
if(FAILED(ms.Read(&vFieldData[0], dwFieldSize))) { bResult = false; break; }
}
switch(usFieldType)
{
case 0x0000:
// Ignore field
break;
case 0x0001:
if((m_vHeaderHash.size() == dwFieldSize) && (pRepair == NULL))
{
if(memcmp(&m_vHeaderHash[0], &vFieldData[0], dwFieldSize) != 0)
bResult = false;
}
break;
case 0x0002:
// Ignore random data
break;
case 0xFFFF:
bEos = true;
break;
default:
ASSERT(FALSE);
break;
}
if(!bResult) break;
}
return bResult;
}
void CPwManager::WriteExtData(CKpMemoryStream& ms)
{
WriteExtDataField(ms, 0x0001, &m_vHeaderHash[0], static_cast<DWORD>(
m_vHeaderHash.size()));
// Store random data to prevent guessing attacks that use the content hash
BYTE vRandom[32];
m_random.GetRandomBuffer(&vRandom[0], 32);
WriteExtDataField(ms, 0x0002, &vRandom[0], 32);
WriteExtDataField(ms, 0xFFFF, NULL, 0);
}
void CPwManager::WriteExtDataField(CKpMemoryStream& ms, USHORT usFieldType,
const BYTE* pData, DWORD dwFieldSize)
{
// pData may be NULL
ms.Write((BYTE*)&usFieldType, 2);
ms.Write((BYTE*)&dwFieldSize, 4);
if(dwFieldSize > 0) ms.Write(pData, dwFieldSize);
}
| 33.130058 | 117 | 0.70825 | [
"vector"
] |
8623f649de3b0e6daaccc10187f36b3f31b51a7c | 2,196 | cc | C++ | ppapi/proxy/plugin_resource_tracker_unittest.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | ppapi/proxy/plugin_resource_tracker_unittest.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | ppapi/proxy/plugin_resource_tracker_unittest.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright (c) 2011 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 "base/memory/scoped_ptr.h"
#include "base/process/process.h"
#include "ppapi/proxy/mock_resource.h"
#include "ppapi/proxy/plugin_dispatcher.h"
#include "ppapi/proxy/plugin_resource_tracker.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/proxy/ppapi_proxy_test.h"
#include "ppapi/shared_impl/proxy_lock.h"
namespace ppapi {
namespace proxy {
namespace {
// Object so we know when a resource has been released.
class TrackedMockResource : public MockResource {
public:
TrackedMockResource(const HostResource& serialized)
: MockResource(serialized) {
tracked_alive_count++;
}
~TrackedMockResource() {
tracked_alive_count--;
}
static int tracked_alive_count;
};
int TrackedMockResource::tracked_alive_count = 0;
} // namespace
class PluginResourceTrackerTest : public PluginProxyTest {
public:
PluginResourceTrackerTest() {}
~PluginResourceTrackerTest() {}
};
TEST_F(PluginResourceTrackerTest, PluginResourceForHostResource) {
ProxyAutoLock lock;
PP_Resource host_resource = 0x5678;
HostResource serialized;
serialized.SetHostResource(pp_instance(), host_resource);
// When we haven't added an object, the return value should be 0.
EXPECT_EQ(0, resource_tracker().PluginResourceForHostResource(serialized));
EXPECT_EQ(0, TrackedMockResource::tracked_alive_count);
TrackedMockResource* object = new TrackedMockResource(serialized);
EXPECT_EQ(1, TrackedMockResource::tracked_alive_count);
PP_Resource plugin_resource = object->GetReference();
// Now that the object has been added, the return value should be the plugin
// resource ID we already got.
EXPECT_EQ(plugin_resource,
resource_tracker().PluginResourceForHostResource(serialized));
// Releasing the resource should have freed it.
resource_tracker().ReleaseResource(plugin_resource);
EXPECT_EQ(0, TrackedMockResource::tracked_alive_count);
EXPECT_EQ(0, resource_tracker().PluginResourceForHostResource(serialized));
}
} // namespace proxy
} // namespace ppapi
| 30.5 | 78 | 0.772769 | [
"object"
] |
86247a66af12cfc209e56d990b66269a4e7c8a0a | 36,687 | cpp | C++ | 3.PointMassEuler/PointMass_Euler/MathLib.cpp | Cabrra/Physics-Projects | 8fb3ec73b58ab1a2055e47b780bd298ef2c14bbb | [
"MIT"
] | 1 | 2021-12-10T07:34:04.000Z | 2021-12-10T07:34:04.000Z | 3.PointMassEuler/PointMass_Euler/MathLib.cpp | Cabrra/Physics-Projects | 8fb3ec73b58ab1a2055e47b780bd298ef2c14bbb | [
"MIT"
] | null | null | null | 3.PointMassEuler/PointMass_Euler/MathLib.cpp | Cabrra/Physics-Projects | 8fb3ec73b58ab1a2055e47b780bd298ef2c14bbb | [
"MIT"
] | null | null | null |
#include"MathLib.h"
/********************************************************************************************************************
Author : Richard Bahin
Function: Vector3D()
Input : none
Output : none
Returns : none
comment : Vector3D class constructor
TODO : none
*********************************************************************************************************************/
Vector3D::Vector3D()
{
x=0.0f;
y=0.0f;
z=0.0f;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Vector3D(float,float,float)
Input : first ,second and third component of the vector
Output : none
Returns : none
comment : Vector3D class constructor with 3 arguments
TODO : none
*********************************************************************************************************************/
Vector3D::Vector3D(float a , float b , float c)
{
x=a;
y=b;
z=c;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Vector3D
Input : argument of type vector
Output : none
Returns : none
comment : Vector3D class copy constructor
TODO : none
*********************************************************************************************************************/
Vector3D::Vector3D(const Vector3D& V)
{
x=V.x;
y=V.y;
z=V.z;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: operator =
Input : none
Output : none
Returns : a vector of type Vector3D
comment : overloaded assignment operator
TODO : none
*********************************************************************************************************************/
Vector3D& Vector3D::operator =(const Vector3D& V)
{
x=V.x;
y=V.y;
z=V.z;
return *this;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Norm()
Input : none
Output : none
Returns : argument of type float
comment : This function will calculate the norm or magnitude of a vector
TODO : TBA
*********************************************************************************************************************/
float Vector3D::Norm()
{ // norm=length=magnitude all the same
return sqrt(x*x + y*y + z*z);
}
/********************************************************************************************************************
Author : Richard Bahin
Function: NormSquared()
Input : none
Output : none
Returns : argument of type float
comment : This function will calculate the square of the norm(magnitude) of a vector
TODO : TBA
*********************************************************************************************************************/
float Vector3D::NormSquared()
{
return(x*x + y*y + z*z);
}
/********************************************************************************************************************
Author : Richard Bahin
Function: operator *=
Input : argument of type float
Output : none
Returns : argument of type Vector3D
comment : This function will a vector by a scalar k and return a vector , V=K*V1
TODO : TBA
*********************************************************************************************************************/
Vector3D& Vector3D::operator *=(float k)
{
x*=k;
y*=k;
z*=k;
return *this;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: operator +=
Input : argument of type Vector3D
Output : none
Returns : argument of type Vector3D
comment : This function will add two vectors and return a vector , V = V1 + V2
TODO : TBA
*********************************************************************************************************************/
Vector3D& Vector3D::operator +=( Vector3D V)
{
x += V.x;
y += V.y;
z += V.z;
return *this;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: operator -=
Input : argument of type Vector3D
Output : none
Returns : argument of type Vector3D
comment : This function will subtract two vectors and return a vector , V = V1 - V2
TODO : TBA
*********************************************************************************************************************/
Vector3D& Vector3D::operator -=( Vector3D V )
{
x-=V.x;
y-=V.y;
z-=V.z;
return *this;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: operator -()
Input : none
Output : none
Returns : argument of type Vector3D
comment : This function will reverse a vector , V = -V1
TODO : TBA
*********************************************************************************************************************/
Vector3D Vector3D::operator -()
{
return Vector3D(-1*x,-1*y,-1*z);
}
/********************************************************************************************************************
Author : Richard Bahin
Function: operator /=
Input : argument of type float
Output : none
Returns : argument of type Vector3D
comment : This function will divide a vector by a scalar and return a vector , V = V1/k
TODO : TBA
*********************************************************************************************************************/
Vector3D& Vector3D::operator /=(float k)
{
assert(k!=0.0f);
x/=k;
y/=k;
z/=k;
return *this;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: operator Normalize()
Input : none
Output : none
Returns : argument of type Vector3D
comment : This function will normalize a vector and return a normalized vector , V = V1/||v1||
TODO : TBA
*********************************************************************************************************************/
Vector3D Vector3D::Normalize()const
{
Vector3D V;
float m=sqrtf(x*x+y*y+z*z);
if(m!=ZERO) V=Vector3D(x/m,y/m,z/m);
return V;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: ConvertToD3DXVector()
Input : none
Output : none
Returns : a vector of type D3DXVECTOR3
comment : This function will convert our custom Vector3D into the Microsoft Direct3D vector type : D3DXVECTOR3
TODO : TBA
*********************************************************************************************************************/
D3DXVECTOR3 Vector3D::ConvertToD3DXVector()
{
return D3DXVECTOR3(x,y,z);
}
/********************************************************************************************************************
Author : Richard Bahin
Function: overloaded operator *()
Input : a scalar and a vector
Output : none
Returns : a vector of type Vector3D
comment : This function will multiply a vector by a saclar
TODO : TBA
*********************************************************************************************************************/
Vector3D operator *(float k, Vector3D V)
{
return Vector3D(k*V.x , k*V.y , k*V.z);
}
/********************************************************************************************************************
Author : Richard Bahin
Function: overloaded operator *()
Input : a scalar and a vector
Output : none
Returns : a vector of type Vector3D
comment : This function will multiply on the right a vector by a scalar
TODO : TBA
*********************************************************************************************************************/
Vector3D operator* ( Vector3D V , float k)
{
return Vector3D(V.x*k , V.y*k , V.z*k) ;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: overloaded operator +()
Input : Two vectors
Output : none
Returns : a vector of type Vector3D
comment : This function will add 2 vectors
TODO : TBA
*********************************************************************************************************************/
Vector3D operator +( Vector3D U, Vector3D V)
{
return Vector3D( U.x + V.x ,U.y + V.y ,U.z + V.z);
}
/********************************************************************************************************************
Author : Richard Bahin
Function: overloaded operator -()
Input :Two vectors
Output : none
Returns : a vector of type Vector3D
comment : This function will subtract two vectors
TODO : TBA
*********************************************************************************************************************/
Vector3D operator -( Vector3D U, Vector3D V)
{
return Vector3D( U.x - V.x ,U.y - V.y , U.z - V.z );
}
/********************************************************************************************************************
Author : Richard Bahin
Function: overloaded operator *()
Input :Two vectors
Output : none
Returns : a scalar(float)
comment : This function will dot multiply two vectors
TODO : TBA
*********************************************************************************************************************/
float operator *( Vector3D U , Vector3D V )
{
return (float)(U.x*V.x + U.y*V.y + U.z*V.z );
}
/********************************************************************************************************************
Author : Richard Bahin
Function: overloaded operator /()
Input : A vectors and a scalar
Output : none
Returns : a vector of type Vector3D
comment : This function will divide a vector by a scalar
TODO : TBA
*********************************************************************************************************************/
Vector3D operator/( Vector3D V , float k)
{
assert(k!=0.0f);
return Vector3D(V.x/k , V.y/k , V.z/k );
}
/********************************************************************************************************************
Author : Richard Bahin
Function: overloaded operator ^()
Input :Two vectors
Output : none
Returns : a vector of type Vector3D
comment : This function will cross multiply ( cross product) two vectors
TODO : TBA
*********************************************************************************************************************/
Vector3D operator^( Vector3D U , Vector3D V )
{
return Vector3D(U.y*V.z - U.z*V.y , U.z*V.x - U.x*V.z , U.x*V.y - U.y*V.x);
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Component(U,V)
Input :Two vectors
Output : none
Returns : a scalar (float)
comment : This function will compute the component of a vector U onto a vector V
TODO : TBA
*********************************************************************************************************************/
// The component of u onto v
float Component( Vector3D U , Vector3D V)
{
return(U*V.Normalize());
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Projection(U,V)
Input :Two vectors
Output : none
Returns : a Vector of type Vector3D
comment : This function will compute the component of a vector U onto a vector V
TODO : TBA
*********************************************************************************************************************/
Vector3D Projection( Vector3D U , Vector3D V)
{
return( Component(U,V)*V.Normalize());
}
// ---------------------------------------------------Matrix class implementation------------------------------------
/********************************************************************************************************************
Author : Richard Bahin
Function: Matrix3D()
Input : none
Output : none
Returns : none
comment : MatrixD class constructor
TODO : none
*********************************************************************************************************************/
Matrix3D::Matrix3D()
{
m11=m12=m13=0.0f;
m21=m22=m23=0.0f;
m31=m32=m33=0.0f;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Matrix3D(...)
Input : The matrix entries values
Output : none
Returns : none
comment : MatrixD class constructor with argument values
TODO : none
*********************************************************************************************************************/
Matrix3D::Matrix3D(float a11,float a12,float a13,
float a21,float a22,float a23,
float a31,float a32,float a33)
{
m11=a11 ; m12=a12 ; m13=a13;
m21=a21 ; m22=a22 ; m23=a23;
m31=a31 ; m32=a32 ; m33=a33;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Matrix3D()
Input : argument of type reference matrix
Output : none
Returns : none
comment : MatrixD copy constructor
TODO : none
*********************************************************************************************************************/
Matrix3D::Matrix3D(const Matrix3D & M)
{
m11=M.m11 ; m12=M.m12 ; m13=M.m13;
m21=M.m21 ; m22=M.m22 ; m23=M.m23;
m31=M.m31 ; m32=M.m32 ; m33=M.m33;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Overloaded operator=()
Input : An argument of type reference Matrix3D
Output : none
Returns : none
comment : MatrixD class constructor
TODO : none
*********************************************************************************************************************/
Matrix3D& Matrix3D::operator =(const Matrix3D& M)
{
m11=M.m11 ; m12=M.m12 ; m13=M.m13;
m21=M.m21 ; m22=M.m22 ; m23=M.m23;
m31=M.m31 ; m32=M.m32 ; m33=M.m33;
return *this;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Overloaded operator*=()
Input : An argument of type float
Output : none
Returns : A matrix (reference Matrix3D)
comment : this function multiplies a matrix by a scalar
TODO : TBA
*********************************************************************************************************************/
Matrix3D& Matrix3D::operator *=(float k)
{
m11*=k; m12*=k; m13*=k;
m21*=k; m22*=k; m23*=k;
m31*=k; m32*=k; m33*=k;
return *this;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Overloaded operator+=()
Input : An argument of type Matrix3D
Output : none
Returns : A matrix (reference Matrix3D)
comment : this function will add two matrices
TODO : TBA
*********************************************************************************************************************/
Matrix3D& Matrix3D::operator +=(Matrix3D M)
{
m11+=M.m11 ; m12+=M.m12 ; m13+=M.m13;
m21+=M.m21 ; m22+=M.m22 ; m23+=M.m23;
m31+=M.m31 ; m32+=M.m32 ; m33+=M.m33;
return *this;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Overloaded operator-=()
Input : An argument of type Matrix3D
Output : none
Returns : A matrix (reference Matrix3D)
comment : this function will subtract two matrices
TODO : TBA
*********************************************************************************************************************/
Matrix3D& Matrix3D::operator -=(Matrix3D M )
{
m11-=M.m11 ; m12-=M.m12 ; m13-=M.m13;
m21-=M.m21 ; m22-=M.m22 ; m23-=M.m23;
m31-=M.m31 ; m32-=M.m32 ; m33-=M.m33;
return *this;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Overloaded operator/=()
Input : An argument of type float (a scalar)
Output : none
Returns : A matrix (reference Matrix3D)
comment : this function will a matrix by a scalar
TODO : TBA
*********************************************************************************************************************/
Matrix3D& Matrix3D::operator /=(float k )
{
//assert(k!=0.0f);
m11/=k; m12/=k; m13/=k;
m21/=k; m22/=k; m23/=k;
m31/=k; m32/=k; m33/=k;
return *this;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Transpose()
Input : none
Output : none
Returns : A matrix (Matrix3D)
comment : this function will compute the transpose of a matrix
TODO : TBA
*********************************************************************************************************************/
Matrix3D Matrix3D::Transpose()const{
return Matrix3D(m11,m21,m31,
m12,m22,m32,
m13,m23,m33);
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Determinant()
Input : none
Output : none
Returns : A scalar (float)
comment : this function will compute the determinant of a matrix
TODO : TBA
*********************************************************************************************************************/
float Matrix3D::Determinant()
{
return( m11*(m22*m33-m23*m32) - m12*(m21*m33-m31*m23)+ m13*(m21*m32-m31*m22));
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Inverse()
Input : none
Output : none
Returns : A matrix (Matrix3D)
comment : this function will compute the inverse of a matrix
TODO : TBA
*********************************************************************************************************************/
Matrix3D Matrix3D::Inverse()
{
Matrix3D adjointMatrix;
Matrix3D cofactorMatrix;
Matrix3D inverseMatrix;
float c11,c12,c13,c21,c22,c23,c31,c32,c33; // cofactors
c11= m11*(m22*m33-m31*m23);
c12= -m12*(m21*m33-m31*m23);
c13= m13*(m21*m32-m31*m22);
c21= -m21*(m12*m33-m32*m13);
c22= m22*(m11*m33-m31*m13);
c23= -m23*(m11*m32-m31*m12);
c31= m31*(m12*m23-m22*m13);
c32= -m32*(m11*m23-m21*m13);
c33= m33*(m11*m22-m21*m12);
// compute the cofactor matrix
cofactorMatrix=Matrix3D(c11,c12,c13,
c21,c22,c23,
c31,c32,c33);
// compute the adjoint matrix by transposing the cofactor matrix
adjointMatrix=cofactorMatrix.Transpose();
float det=Determinant();
if(det!=ZERO) inverseMatrix=adjointMatrix/Determinant();
return inverseMatrix;
}
/********************************************************************************************************************
Author : Richard Bahin
Function: Orthonormalize()
Input : none
Output : none
Returns : A matrix (Matrix3D)
comment : this function will orthonormalize a matrix using Gram-Schmidt Orthonormalization Algorithm
TODO : TBA
*********************************************************************************************************************/
Matrix3D Matrix3D::Orthonormalize()
{
Vector3D U,V,W;
U=Vector3D(m11,m21,m31);
V=Vector3D(m12,m22,m32);
W=Vector3D(m13,m23,m33);
U=U.Normalize();
V=V-Projection(V,U);
V=V.Normalize();
W=U^V;
m11=U.x ; m12=V.x ; m13=W.x ;
m21=U.y ; m22=V.y; m23=W.y ;
m31=U.z ; m32=V.z ; m33=W.z ;
return *this;
}
Matrix3D operator +( Matrix3D M , Matrix3D N)
{
return Matrix3D( M.m11 + N.m11 , M.m12 + N.m12 , M.m13 + N.m13 ,
M.m21 + N.m21 , M.m22 + N.m22 , M.m23 + N.m23 ,
M.m31 + N.m31 , M.m32 + N.m32 , M.m33 + N.m33);
}
Matrix3D operator -( Matrix3D M, Matrix3D N)
{
return Matrix3D( M.m11 - N.m11 , M.m12 - N.m12 , M.m13 - N.m13 ,
M.m21 - N.m21 , M.m22 - N.m22 , M.m23 - N.m23 ,
M.m31 - N.m31 , M.m32 - N.m32 , M.m33 - N.m33);
}
Matrix3D operator *( Matrix3D M, Matrix3D N)
{
return Matrix3D( M.m11*N.m11 + M.m12*N.m21 + M.m13*N.m31,
M.m11*N.m12 + M.m12*N.m22 + M.m13*N.m32,
M.m11*N.m13 + M.m12*N.m23 + M.m13*N.m33,
M.m21*N.m11 + M.m22*N.m21 + M.m23*N.m31,
M.m21*N.m12 + M.m22*N.m22 + M.m23*N.m32,
M.m21*N.m13 + M.m22*N.m23 + M.m23*N.m33,
M.m31*N.m11 + M.m32*N.m21 + M.m33*N.m31,
M.m31*N.m12 + M.m32*N.m22 + M.m33*N.m32,
N.m31*N.m13 + M.m32*N.m23 + M.m33*N.m33);
}
Vector3D operator *(Matrix3D M,Vector3D V)
{
return Vector3D(M.m11*V.x+M.m12*V.y+M.m13*V.z , M.m21*V.x + M.m22*V.y + M.m23*V.z ,M.m31*V.x+M.m32*V.y+M.m33*V.z);
}
Vector3D operator *(Vector3D V, Matrix3D M)
{
return Vector3D(M.m11*V.x+M.m12*V.y+M.m13*V.z , M.m21*V.x + M.m22*V.y + M.m23*V.z ,M.m31*V.x+M.m32*V.y+M.m33*V.z);
}
Matrix3D operator *( Matrix3D M,float k)
{
return Matrix3D( M.m11*k , M.m12*k , M.m13*k ,
M.m21*k , M.m22*k , M.m23*k ,
M.m31*k , M.m32*k , M.m33*k);
}
Matrix3D operator *(float k, Matrix3D M)
{
return Matrix3D( M.m11*k , M.m12*k , M.m13*k ,
M.m21*k , M.m22*k , M.m23*k ,
M.m31*k , M.m32*k , M.m33*k);
}
Matrix3D operator /( Matrix3D M , float k)
{
assert(k>ZERO);
return Matrix3D( M.m11/k , M.m12/k , M.m13/k ,
M.m21/k , M.m22/k , M.m23/k ,
M.m31/k , M.m32/k , M.m33/k );
}
float Matrix3D::Trace()
{
return( m11 + m22 + m33 );
}
Matrix3D Skew(Vector3D V)
{
return Matrix3D( 0 , -V.z , V.y ,
V.z , 0 , -V.x ,
-V.y , V.x , 0 );
}
D3DXMATRIX Matrix3D::ConvertToD3DXMatrix()
{
return D3DXMATRIX( m11, m12, m13, 0,
m21, m22, m23, 0,
m31, m32, m33, 0,
0 , 0 , 0 , 1 );
}
//////////////////////////////////end of Matrix3D class implementation//////////////////////////////////////////////////
///////////////////////////////////////////Begin Quaternions//////////////////////////////////////////////////////////////
Quaternion::Quaternion()
{
w=0.0;
v.x = v.y = v.z= 0.0;
}
Quaternion::Quaternion(float a , float b ,float c , float d)
{
w =a;
v.x =b;
v.y =c;
v.z =d;
}
Quaternion::Quaternion(float a , Vector3D vec)
{
w=a;
v=vec;
}
Quaternion::Quaternion(const Quaternion &q)
{
w=q.w;
v=q.v;
}
Quaternion & Quaternion::operator =(const Quaternion& q)
{
w=q.w;
v=q.v;
return *this;
}
Quaternion& Quaternion::operator +=(Quaternion q)
{
w+=q.w;
v+=q.v;
return *this;
}
Quaternion& Quaternion::operator *=(float k)
{
w*=k;
v*=k;
return *this;
}
Quaternion& Quaternion::operator /=(float k)
{
assert(k!=0.0f);
w/=k;
v/=k;
return *this;
}
Quaternion Quaternion::operator~()const
{
return Quaternion(w,-1*v);
}
float Quaternion::Norm()
{
return((float)(w*w+ v.x*v.x + v.y*v.y + v.z*v.z));
}
float Quaternion::Dot(Quaternion q1 , Quaternion q2)
{
return( q1.w*q2.w + q1.v*q2.v);
}
Quaternion Quaternion::Inverse()const
{
float N=(w*w+ v.x*v.x + v.y*v.y + v.z*v.z);
if (N==0.0f) N=1.0f;
return( Quaternion( w/N ,-1*v/N ) );
}
Quaternion operator+(const Quaternion q1 ,const Quaternion q2)
{
return( Quaternion( q1.w + q2.w , q1.v + q2.v ) );
}
Quaternion operator-(const Quaternion q1 ,const Quaternion q2)
{
return( Quaternion( q1.w - q2.w , q1.v - q2.v ) );
}
Quaternion operator*(const Quaternion q1 , const Quaternion q2)
{
return ( Quaternion (q1.w*q2.w - q1.v*q2.v , q1.w*q2.v + q2.w*q1.v + q1.v^q2.v) );
}
Quaternion operator*(float k, const Quaternion q)
{
return Quaternion(k*q.w,k*q.v);
}
Quaternion operator*(const Quaternion q ,float k )
{
return Quaternion(q.w*k,q.v*k);
}
Quaternion operator/(const Quaternion q, float k)
{
assert(k!=0.0f);
return Quaternion(q.w/k,q.v/k);
}
Vector3D Quaternion::GetVector3D()
{
return(Vector3D(v.x,v.y,v.z));
}
float Quaternion::GetScalar()
{
return w;
}
| 44.415254 | 213 | 0.281898 | [
"vector"
] |
8626cc608fe0230091aae40a2e888d5928fd22d9 | 925 | cpp | C++ | continguousSubArrayOfEqualNumberOf0&1.cpp | anishmo99/CPP | a9e7f8e8a7a2cca7fe8ab2f6f4d1dff8e6cc2c49 | [
"MIT"
] | 2 | 2020-08-09T02:09:50.000Z | 2020-08-09T07:07:47.000Z | continguousSubArrayOfEqualNumberOf0&1.cpp | anishmo99/CPP | a9e7f8e8a7a2cca7fe8ab2f6f4d1dff8e6cc2c49 | [
"MIT"
] | null | null | null | continguousSubArrayOfEqualNumberOf0&1.cpp | anishmo99/CPP | a9e7f8e8a7a2cca7fe8ab2f6f4d1dff8e6cc2c49 | [
"MIT"
] | 4 | 2020-05-25T10:24:14.000Z | 2021-05-03T07:52:35.000Z | class Solution {
public:
int findMaxLength(vector<int>& nums) {
map<int,int>m;
int max_len=0,count=0;
for(int i=0;i<nums.size();i++)
{
count=count+(nums.at(i)==1?1:-1);
if(count==0)
{
max_len=max(max_len,i+1);
}
else if(m.find(count)==m.end())
{
m[count]=i;
}
else
{
max_len=max(max_len,i-m[count]);
}
}
return max_len;
}
};
/*
* //gfg solution
* int maxLen(int arr[], int n) {
int max_len=0,count=0;
map<int,int>m;
for(int i=0;i<n;i++)
{
count+=arr[i]==1?1:-1;
if(count==0)
max_len=max(max_len,i+1);
else if(m.find(count)==m.end())
m[count]=i;
else
max_len=max(max_len,i-m[count]);
}
return max_len;
}
*/ | 21.511628 | 48 | 0.414054 | [
"vector"
] |
86270dc661f4f7bfdef7c282084a420e4e617fd3 | 1,782 | cpp | C++ | Basic Programs/CPP/BinaryTreeLifting.cpp | PrajaktaSathe/HacktoberFest2020 | e84fc7a513afe3dd75c7c28db1866d7f5e6a8147 | [
"MIT"
] | null | null | null | Basic Programs/CPP/BinaryTreeLifting.cpp | PrajaktaSathe/HacktoberFest2020 | e84fc7a513afe3dd75c7c28db1866d7f5e6a8147 | [
"MIT"
] | null | null | null | Basic Programs/CPP/BinaryTreeLifting.cpp | PrajaktaSathe/HacktoberFest2020 | e84fc7a513afe3dd75c7c28db1866d7f5e6a8147 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define LG 20
#define MAX_N 100005
int N, M, Q;
vector < pair < int , long long >> adj[MAX_N];
int dep[MAX_N], anc[LG][MAX_N];
long long dist[MAX_N], dist0[MAX_N], dist1[MAX_N];
void dfs(int u, int p)
{
anc[0][u] = p;
for (int i = 1; i < LG; i++)
anc[i][u] = anc[i - 1][anc[i - 1][u]];
for (auto &ed : adj[u])
{
if (ed.first != p)
{
int v = ed.first;
dep[v] = dep[u] + 1;
dist[v] = dist[u] + ed.second;
dist0[v] = dist0[u];
dist1[v] = dist1[u];
if (ed.second & 1) dist1[v] += ed.second;
else dist0[v] += ed.second;
dfs(v, u);
}
}
}
int getlca (int u, int v)
{
if (dep[u] > dep[v])
swap(u, v);
for (int i = LG - 1; i >= 0; i--)
if (dep[v] - (1 << i) >= dep[u])
v = anc[i][v];
if (u == v)
return u;
for (int i = LG - 1; i >= 0; i--)
if (anc[i][u] != anc[i][v])
u = anc[i][u], v = anc[i][v];
return anc[0][u];
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N >> M >> Q;
for (int i = 0; i < M; i++)
{
int u, v;
long long w;
cin >> u >> v >> w;
adj[u].emplace_back(v, w);
adj[v].emplace_back(u, w);
}
dep[1] = dist[1] = dist0[1] = dist1[1] = 0;
dfs(1, 1);
while (Q--) {
int u, v; cin >> u >> v;
int lca = getlca(u, v);
long long total = dist[u] + dist[v] - 2 * dist[lca];
long long ans;
if (total & 1)
ans = dist0[u] + dist0[v] - 2 * dist0[lca];
else
ans = dist1[u] + dist1[v] - 2 * dist1[lca];
cout << ans << "\n";
}
return 0;
} | 21.214286 | 60 | 0.427048 | [
"vector"
] |
862b32b533f76a7165db2dc00890be2528e5939e | 2,876 | cpp | C++ | samples/core/shared_ptr/Object.cpp | aphenriques/integral | 157b1e07905a88f7786d8823bde19a3546502912 | [
"MIT"
] | 40 | 2015-01-18T19:03:12.000Z | 2022-03-06T19:16:16.000Z | samples/core/shared_ptr/Object.cpp | aphenriques/integral | 157b1e07905a88f7786d8823bde19a3546502912 | [
"MIT"
] | 7 | 2019-06-25T20:53:27.000Z | 2021-01-16T14:14:52.000Z | samples/core/shared_ptr/Object.cpp | aphenriques/integral | 157b1e07905a88f7786d8823bde19a3546502912 | [
"MIT"
] | 7 | 2015-05-13T12:31:15.000Z | 2019-07-23T20:22:50.000Z | //
// Object.cpp
// integral
//
// MIT License
//
// Copyright (c) 2014, 2015, 2016, 2017, 2020 André Pereira Henriques (aphenriques (at) outlook (dot) com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <iostream>
#include <functional>
#include <memory>
#include <lua.hpp>
#include <integral/integral.hpp>
class Object {
public:
void print() const {
std::cout << "Object::print" << std::endl;
}
};
extern "C" {
LUALIB_API int luaopen_libObject(lua_State *luaState) {
try {
integral::pushClassMetatable<Object>(luaState);
integral::setFunction(luaState, "print", &Object::print);
integral::setFunction(luaState, "getShared", &std::make_shared<Object>);
// std::shared_ptr<T> has automatic synthetic inheritance do T as if it was defined as:
// integral::defineInheritance(luaState, [](std::shared_ptr<T> *sharedPtrPointer) -> T * {
// return sharedPtrPointer->get();
// });
// or:
// integral::defineInheritance(luaState, std::function<T *(std::shared_ptr<T> *)>(&std::shared_ptr<T>::get));
// the following statement may not work if the get method is from a base class of std::shared_ptr (may fail in some stdlib implementations)
// integral::defineInheritance<std::shared_ptr<T>, T>(luaState, &std::shared_ptr<T>::get);
return 1;
} catch (const std::exception &exception) {
lua_pushstring(luaState, (std::string("[shared_ptr sample setup] ") + exception.what()).c_str());
} catch (...) {
lua_pushstring(luaState, "[shared_ptr sample setup] unknown exception thrown");
}
// Error return outside catch scope so that the exception destructor can be called
return lua_error(luaState);
}
}
| 42.925373 | 151 | 0.675591 | [
"object"
] |
86314142129f088c607f8099af95aedf606398d0 | 13,835 | cpp | C++ | snpbridge.cpp | glennhickey/snpMerge | 2de237eb74f4baa83105e6becd109a8d76c83177 | [
"MIT"
] | 1 | 2020-04-19T10:47:50.000Z | 2020-04-19T10:47:50.000Z | snpbridge.cpp | glennhickey/snpMerge | 2de237eb74f4baa83105e6becd109a8d76c83177 | [
"MIT"
] | null | null | null | snpbridge.cpp | glennhickey/snpMerge | 2de237eb74f4baa83105e6becd109a8d76c83177 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2015 by Glenn Hickey (hickey@soe.ucsc.edu)
*
* Released under the MIT license, see LICENSE.cactus
*/
#include "snpbridge.h"
using namespace vcflib;
using namespace vg;
using namespace std;
SNPBridge::SNPBridge() : _vg(NULL)
{
}
SNPBridge::~SNPBridge()
{
}
void SNPBridge::processGraph(VG* vg, VariantCallFile* vcf, int offset,
int windowSize)
{
_vg = vg;
_gv1.init(offset);
_gv2.init(offset);
Variant var1(*vcf);
Variant var2(*vcf);
// skip to first variant after offset
for (int vcfPos = -1; vcfPos < offset; vcfPos = var1.position)
{
if (!vcf->getNextVariant(var1))
{
// empty file
cerr << "No variants found in VCF" << endl;
return;
}
}
_gv1.loadVariant(vg, var1);
int graphLen = vgRefLength(var1);
for (; vcf->getNextVariant(var2); swap(var1, var2), swap(_gv1, _gv2))
{
// skip ahead until var2 doesn't overlap var1 or anything between
bool breakOut = false;
int prev_position = var1.position + var1.alleles[0].size();
while (!breakOut && var2.position < prev_position)
{
cerr << "Skipping variant at " << var2.position << " because it "
<< "overlaps previous variant at position " << var1.position << endl;
prev_position = max(prev_position,
(int)(var2.position + var2.alleles[0].size()));
breakOut = !vcf->getNextVariant(var2);
}
if (breakOut)
{
break;
}
if (var2.position >= offset + graphLen)
{
// stop after end of vg
break;
}
_gv2.loadVariant(vg, var2);
if (var2.position - (var1.position + var1.alleles[0].length() - 1) >
windowSize)
{
// skip because further than window size
continue;
}
#ifdef DEBUG
cerr << "\nv1 " << _gv1 << endl << "v2 " << _gv2 << endl;
#endif
computeLinkCounts(var1, var2);
#ifdef DEBUG
cerr << "Linkcounts: ";
for (int i = 0; i < _linkCounts.size(); ++i)
{
for (int j = 0; j < _linkCounts[i].size(); ++j)
{
cerr << "(" << i <<"-" << j << "=" << _linkCounts[i][j] << ") ";
}
}
cerr << endl;
#endif
for (int a1 = 1; a1 < var1.alleles.size(); ++a1)
{
for (int a2 = 1; a2 < var2.alleles.size(); ++a2)
{
// note can probably get what we need by calling once instead
// of in loop....
Phase phase = phaseRelation(var1, a1, var2, a2);
if (phase != GT_OTHER)
{
makeBridge(a1, a2, phase);
// we can get away with breaking here (and below) because results
// mutually exclusive (see simplifying assumption in
// phaseRelation()). So as soon as we see a GT_AND or
// GT_XOR, then everything else must be GT_OTHER
break;
}
else
{
#ifdef DEBUG
cerr << a1 << " OTHER " << a2 << " detected at "
<< _gv1.getVariant().position << " ";
for (int i = 0; i < _linkCounts.size(); ++i)
{
cerr << "(";
for (int j = 0; j < _linkCounts[i].size(); ++j)
{
cerr << _linkCounts[i][j] << ",";
}
cerr << ") ";
}
cerr << endl;
#endif
}
}
}
}
}
void SNPBridge::makeBridge(int allele1, int allele2, Phase phase)
{
#ifdef DEBUG
cerr << allele1 << " " << phase2str(phase) << " " << allele2 << " detected at "
<< _gv1.getVariant().position << " ";
for (int i = 0; i < _linkCounts.size(); ++i)
{
cerr << "(";
for (int j = 0; j < _linkCounts[i].size(); ++j)
{
cerr << _linkCounts[i][j] << ",";
}
cerr << ") ";
}
cerr << endl;
#endif
Node* node1 = _gv1.getGraphAllele(allele1).back();
Node* ref1 = _gv1.getGraphAllele(0).back();
Node* node2 = _gv2.getGraphAllele(allele2).front();
Node* ref2 = _gv2.getGraphAllele(0).front();
// note we don't use references here because they get altered by
// calls to create and destroy.
vector<pair<int64_t, bool> > outEdges1 = _vg->edges_on_end[node1->id()];
vector<pair<int64_t, bool> > inEdges2 = _vg->edges_on_start[node2->id()];
// make sure there's no other way out of node1 but the
// new bridges that we'll add
for (auto p : outEdges1)
{
#ifdef DEBUG
cerr << "destroy1 " << node1->id() << " " << true << ", " << p.first << " " << p.second << endl;
#endif
Edge* edge = _vg->get_edge(NodeSide(node1->id(), true),
NodeSide(p.first, p.second));
assert(edge != NULL);
_vg->destroy_edge(edge);
}
// make sure there's no other way into node 2 than
// the bridges we add
for (auto p : inEdges2)
{
#ifdef DEBUG
cerr << "destroy2 " << p.first << " " << !p.second << ", " << node2->id() << " " << false << endl;
#endif
Edge* edge = _vg->get_edge(NodeSide(p.first, !p.second),
NodeSide(node2->id(), false));
if (p.first == node1->id())
{
// should have been deleted above
assert(edge == NULL);
}
else
{
assert(edge != NULL);
_vg->destroy_edge(edge);
}
}
// find the path between the two variant alleles along the
// reference. since we only deal with consecutive variants,
// it's sufficient to stick this path between
list<Node*> refPath;
_gv1.getReferencePathTo(_gv2, refPath);
// if there's no path, we assume the variants are directly adjacent
// and just stick edges between them
if (refPath.empty())
{
if (phase == GT_AND || phase == GT_FROM_REF || phase == GT_TO_REF)
{
_vg->create_edge(node1, node2, false, false);
#ifdef DEBUG
cerr << "create adj alt-alt " << node1->id() << ", " << node2->id() << endl;
#endif
}
if (phase == GT_FROM_REF || phase == GT_XOR)
{
_vg->create_edge(ref1, node2, false, false);
#ifdef DEBUG
cerr << "create adj ref-alt " << ref1->id() << ", " << node2->id() << endl;
#endif
}
if (phase == GT_TO_REF || phase == GT_XOR)
{
_vg->create_edge(node1, ref2, false, false);
#ifdef DEBUG
cerr << "create adj alt-ref " << node1->id() << ", " << ref2->id() << endl;
#endif
}
}
// otherwise, make a copy of ref path and stick that in between
else
{
Node* prev = node1;
Node* refPrev = ref1;
for (auto refNode : refPath)
{
Node* cpyNode = _vg->create_node(refNode->sequence());
_vg->create_edge(prev, cpyNode, false, false);
#ifdef DEBUG
cerr << "create " << cpyNode->id() << endl;
cerr << "create " << prev->id() << " -> " << cpyNode->id() << endl;
#endif
prev = cpyNode;
refPrev = refNode;
}
if (phase == GT_AND || phase == GT_FROM_REF || phase == GT_TO_REF)
{
_vg->create_edge(prev, node2, false, false);
#ifdef DEBUG
cerr << "create alt-alt " << prev->id() << ", " << node2->id() << endl;
#endif
}
if (phase == GT_FROM_REF || phase == GT_XOR)
{
_vg->create_edge(refPrev, node2, false, false);
#ifdef DEBUG
cerr << "create ref-alt " << refPrev->id() << ", " << node2->id() << endl;
#endif
}
if (phase == GT_TO_REF || phase == GT_XOR)
{
_vg->create_edge(prev, ref2, false, false);
#ifdef DEBUG
cerr << "create alt-ref " << prev->id() << ", " << ref2->id() << endl;
#endif
}
}
}
SNPBridge::Phase SNPBridge::phaseRelation(Variant& v1, int allele1,
Variant& v2, int allele2) const
{
// this is where we could take into account allele
// frequencies to, for example, ignore really rare alleles.
// But for now, we only do an all or nothing -- ie
// the variants are alt-alt only if there isn't a single sample
// saying otherwise.
bool to_ref = _linkCounts[allele1][0] > 0;
bool from_ref = _linkCounts[0][allele2] > 0;
bool to_alt = _linkCounts[allele1][allele2] > 0;
bool to_other_alt = false;
for (int i = 1; i < v2.alleles.size(); ++i)
{
if (i != allele2 && _linkCounts[allele1][i] > 0)
{
to_other_alt = true;
break;
}
}
bool from_other_alt = false;
for (int i = 1; i < v1.alleles.size(); ++i)
{
if (i != allele1 && _linkCounts[i][allele2] > 0)
{
from_other_alt = true;
break;
}
}
// don't handle multi allele cases
if (from_other_alt || to_other_alt)
{
return GT_OTHER;
}
if (to_alt)
{
if (!from_ref && !to_ref)
{
return GT_AND;
}
if (from_ref && !to_ref)
{
return GT_FROM_REF;
}
if (!from_ref && to_ref)
{
return GT_TO_REF;
}
}
else
{
if (!to_ref)
{
cerr << "allele 1 " << allele1 << " to ref " << _linkCounts[allele1][0] << " and "
<< "to_ref " << to_ref << endl;
cerr << "Alternate allele " << allele1 << " never seen in GT for "
<< "variant " << v1 << endl;
}
if (!from_ref)
{
cerr << "allele 2 " << allele2 << " from ref " << _linkCounts[0][allele2] << " and "
<< "from_ref " << from_ref << endl;
cerr << "Alternate allele " << allele2 << " never seen in GT for "
<< "variant " << v2 << endl;
}
return GT_XOR;
}
return GT_OTHER;
}
void SNPBridge::computeLinkCounts(Variant& v1, Variant& v2)
{
// make our matrix and set to 0
initLinkCounts(v1, v2);
assert(!v1.alleles.empty() && !v2.alleles.empty());
for (auto& sample : v1.sampleNames)
{
// treat missing GT information in one variant with respect
// to the other as a warning. But count all possible links
// once so it will never get phased.
if (v2.samples.find(sample) == v2.samples.end())
{
cerr << "Warning: Sample " << sample << " not found in variant " << v2
<< ". Assuming unphased" << endl;
for (auto& i : _linkCounts)
{
for (auto& j : i)
{
++j;
}
}
continue;
}
// parse out GT info for sample (it'll look like 0|1 etc.)
string& gt1 = v1.samples[sample]["GT"].front();
string& gt2 = v2.samples[sample]["GT"].front();
vector<string> gtspec1 = split(gt1, "|");
vector<string> gtspec2 = split(gt2, "|");
// don't expect this but check in case
if (gtspec1.size() != gtspec2.size())
{
stringstream ss;
ss << "Sample " << sample << "has different ploidy in "
<< v1 << " and " << v2 << ". This is not supported";
throw runtime_error(ss.str());
}
// so if the GT info looks like 0|1 1|0 2|1 etc. we have
// two "chromosomes", and iterate each. we count a link
// looking at the two variants, and recording what we see
// at the same chromosome at the same sample.
for (int chrom = 0; chrom < gtspec1.size(); ++chrom)
{
// treat . as wildcard
if (gtspec1[chrom] == "." && gtspec2[chrom] == ".")
{
// two .'s mean we see everything
for (int g1 = 0; g1 < v1.alleles.size(); ++g1)
{
for (int g2 = 0; g2 < v2.alleles.size(); ++g2)
{
++_linkCounts[g1][g2];
}
}
}
else if (gtspec1[chrom] == ".")
{
// g1 == . means we see all combindations of g1 with
// given value of g2
int g2;
convert(gtspec2[chrom], g2);
for (int g1 = 0; g1 < v1.alleles.size(); ++g1)
{
++_linkCounts[g1][g2];
}
}
else if (gtspec2[chrom] == ".")
{
// g2 == . means we see all combinations of g2 with
// given value of g1
int g1;
convert(gtspec1[chrom], g1);
for (int g2 = 0; g2 < v2.alleles.size(); ++g2)
{
++_linkCounts[g1][g2];
}
}
else
{
// normal case. update the link count for the indexes
// found on the give allele. Example
// Sample NA12878 has GT 0|1 for var1 and 0|0 for var2
// then we update _linkCounts[0][1] + 1 (when chrom = 0)
// and _linkCounots[0][0] + 1 (when chrom = 1)
int g1, g2;
convert(gtspec1[chrom], g1);
convert(gtspec2[chrom], g2);
++_linkCounts[g1][g2];
}
}
}
}
void SNPBridge::initLinkCounts(Variant& v1,
Variant& v2)
{
// set _linkCounts to 0 and make sure it's at least
// big enough to hold our alleles
for (int i = 0; i < v1.alleles.size(); ++i)
{
if (_linkCounts.size() < v1.alleles.size())
{
_linkCounts.push_back(vector<int>(v2.alleles.size(), 0));
}
else
{
if (_linkCounts[i].size() < v2.alleles.size())
{
_linkCounts[i].resize(v2.alleles.size());
}
_linkCounts[i].assign(v2.alleles.size(), 0);
}
}
}
int SNPBridge::vgRefLength(Variant& var) const
{
// duplicating some code from the built in traversal of graphvariant,
// but it's nice to have path length at outset to make scope checking
// simpler (to relax assumption that vg contains whole vcf).
if (_vg->paths.has_path(var.sequenceName) == false)
{
stringstream ss;
ss << "Unable to find path for " << var.sequenceName << " in vg file";
throw runtime_error(ss.str());
}
int len = 0;
list<Mapping>& path = _vg->paths.get_path(var.sequenceName);
for (auto& mapping : path)
{
if (mapping.position().is_reverse() == true)
{
throw(runtime_error("Reverse Mapping not supported"));
}
if (mapping.edit_size() > 1 || (
mapping.edit_size() == 1 && mapping.edit(0).from_length() !=
mapping.edit(0).to_length()))
{
stringstream ss;
ss << pb2json(mapping) << ": Only mappings with a single trvial edit"
<< " supported in ref path";
throw runtime_error(ss.str());
}
len += _vg->get_node(mapping.position().node_id())->sequence().length();
}
return len;
}
| 27.781124 | 102 | 0.546151 | [
"vector"
] |
864cb6cca166ac122c2347d6e6f89ceea9570765 | 6,484 | hpp | C++ | engine/SparseLib/include/jit_domain/jit_spmm_default.hpp | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 172 | 2021-09-14T18:34:17.000Z | 2022-03-30T06:49:53.000Z | engine/SparseLib/include/jit_domain/jit_spmm_default.hpp | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 40 | 2021-09-14T02:26:12.000Z | 2022-03-29T08:34:04.000Z | engine/SparseLib/include/jit_domain/jit_spmm_default.hpp | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 33 | 2021-09-15T07:27:25.000Z | 2022-03-25T08:30:57.000Z | // Copyright (c) 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ENGINE_SPARSELIB_INCLUDE_JIT_DOMAIN_JIT_SPMM_DEFAULT_HPP_
#define ENGINE_SPARSELIB_INCLUDE_JIT_DOMAIN_JIT_SPMM_DEFAULT_HPP_
#include <omp.h>
#include <glog/logging.h>
#include <vector>
#include <string>
#include <unordered_map>
#include "jit_generator.hpp"
#include "../kernels/sparse_data.hpp"
#include "../kernels/spmm_types.hpp"
#include "utils.hpp"
namespace jd {
/**
* @brief jit_spmm_default_t calculates this kind matmul: sparse x dense = dst.
* weight(M, K) * activation(K, N) + bias(M, 1) = dst(M, N)
*/
class jit_spmm_default_t : public jit_generator {
public:
explicit jit_spmm_default_t(const ssd::flat_param_t& param)
: jit_generator(), param_(param), csrp_(param_.sparse_ptr) {}
virtual ~jit_spmm_default_t() {}
public:
const void* sequence_vals() const { return seq_vals_.data(); }
private:
ssd::flat_param_t param_;
csrp_data_t<int8_t>* csrp_;
std::vector<int8_t> seq_vals_;
private:
void generate() override;
private:
// internal API of op kernel
Xbyak::Zmm TH_Vmm(int i = 0); // Register allocator of load weight. 1D shape=(TH)
Xbyak::Zmm TW_Vmm(int i = 0); // Register allocator of load activation. 1D shape=(TW)
Xbyak::Zmm dst_tile_Vmm(int i, int j); // Reg alloc of DST tile. 2D shape=(TH,TW), stride=(TW,1)
void params_alias(const ssd::flat_param_t& param);
void read_params();
void load_bias(const std::vector<int64_t>& m_indices);
void load_dense(const std::vector<int64_t>& k_indices);
void load_sparse();
void tile_product(int tile_height, int tile_width);
void handle_dst_buffer_init(int kb_idx, const std::vector<int64_t>& m_indices);
void handle_dst_buffer_epilogue(int kb_idx, const std::vector<int64_t>& m_indices);
void mul_scale(int i);
void move_out(int i, int j, int row_idx, int bytes = 1);
std::unordered_map<int64_t, std::vector<int64_t>> get_idx_balanced(const std::vector<int64_t>& m_indices,
const std::vector<int64_t>& sparse_indptr,
const std::vector<int64_t>& sparse_indices, int lo,
int hi);
std::unordered_map<int64_t, std::vector<int8_t>> get_val_balanced(const std::vector<int64_t>& m_indices,
const std::vector<int64_t>& sparse_indptr,
const std::vector<int64_t>& sparse_indices, int lo,
int hi, const std::vector<int8_t>& sparse_inddata);
void repeat_THx4xTW_matmal(const std::vector<int64_t>& m_indices,
const std::unordered_map<int64_t, std::vector<int64_t>>& k_indices_map,
const std::unordered_map<int64_t, std::vector<int8_t>>& k_inddata_map);
void clear_dst_tile();
void load_intermediate_dst(const std::vector<int64_t>& m_indices);
void store_intermediate_dst(const std::vector<int64_t>& m_indices);
void save_sequence_vals(const std::vector<int64_t>& m_indices,
const std::unordered_map<int64_t, std::vector<int8_t>>& k_inddata_map, int pos1, int pos2);
void gen_sub_function();
private:
int64_t n_blocks_ = 0; // The number of blocks divided in N dimension.
int64_t nb_size_ = 0; // The number of columns contained in a block of N dimension.
int64_t k_blocks_ = 0; // The number of blocks divided in K dimension.
int64_t kb_size_ = 0; // The number of columns contained in a block of K dimension.
int64_t TW_ = 0; // tile_width, its unit is different from numerical matrix.
int64_t nt_size_ = 0; // The number of columns contained in a tile of N dimension.
int64_t n_tiles_ = 0; // The number of tiles contained in a block of N dimension.
int64_t TH_ = 0; // tile_height, its unit is different from numerical matrix.
int64_t mt_size_ = 0; // The number of rows contained in a tile of M dimension.
int64_t m_tiles_ = 0; // The number of tiles contained in a block of M dimension.
std::vector<int64_t> dst_stride_;
data_type output_type_;
const int64_t PADDED_NEG_ONE = -1;
const int64_t PADDED_ZERO = 0;
int64_t seq_pos = 0;
const uint8_t* sub_func_fptr_ = nullptr;
private:
static constexpr int stack_space_needed_ = 200;
static constexpr int BYTE8 = 8;
static constexpr int BYTE4 = 4;
static constexpr int BYTE1 = 1;
static constexpr int VREG_NUMS = 32;
#ifdef XBYAK64
static constexpr int PTR_SIZE = 8;
#else
static constexpr int PTR_SIZE = 4;
#endif
// Register decomposition
const Xbyak::Reg64& param1 = rdi;
const Xbyak::Reg64& reg_seq_vals = rcx; // the first argument which is packed nonzero values pointer
const Xbyak::Reg64& reg_dense = rdx; // the second argument which is input matrix pointer
const Xbyak::Reg64& reg_bias = rsi; // the third argument which is bias values pointer
const Xbyak::Reg64& reg_dst = rax; // the fourth argument which is output matrix pointer
const Xbyak::Reg64& reg_scale = rbx; // the scale
const Xbyak::Reg64& reg_nb_start = r8; // start iteration count in the C dimension, useful for multithreading
const Xbyak::Reg64& reg_nb_end = r9; // end iteration count in the C dimension, useful for multithreading
const Xbyak::Opmask& reg_k1 = k1;
const Xbyak::Reg64& reg_nt_relative_idx = r10;
const Xbyak::Reg64& reg_nt_absolute_idx = r11;
const Xbyak::Zmm& vpermt2d_arg_idx = zmm31;
const Xbyak::Zmm& vpshufb_arg_b = zmm30;
const Xbyak::Zmm& vreg_temp = zmm29;
const Xbyak::Zmm& vreg_dst_temp = vreg_temp;
static constexpr int USED_VREGS = 3;
};
} // namespace jd
#endif // ENGINE_SPARSELIB_INCLUDE_JIT_DOMAIN_JIT_SPMM_DEFAULT_HPP_
| 48.38806 | 120 | 0.677822 | [
"shape",
"vector"
] |
86557dd365c22a96aa6faf6ffb1d7364e09853c9 | 705 | hxx | C++ | src/utility/DetectorStop.hxx | TWLord/DUNEPrismTools | bde52eb1331ac10ba81cdf1bf63488707bfe5496 | [
"MIT"
] | null | null | null | src/utility/DetectorStop.hxx | TWLord/DUNEPrismTools | bde52eb1331ac10ba81cdf1bf63488707bfe5496 | [
"MIT"
] | null | null | null | src/utility/DetectorStop.hxx | TWLord/DUNEPrismTools | bde52eb1331ac10ba81cdf1bf63488707bfe5496 | [
"MIT"
] | 3 | 2018-01-09T20:57:33.000Z | 2019-11-24T03:48:28.000Z | #ifndef DP_DETECTORSTOP_HXX_SEEN
#define DP_DETECTORSTOP_HXX_SEEN
#include "TXMLEngine.h"
#include <string>
#include <vector>
namespace {
static std::string const rptagname = "RunPlan";
static std::string const dstagname = "Detector";
static std::string const sstagname = "Stops";
static std::string const stagname = "Stop";
}
struct DetectorStop {
double ActiveExent[3];
double CenterPosition[3];
double POTExposure;
DetectorStop();
bool ConfigureDetector(XMLNodePointer_t node);
DetectorStop CloneDetectorConfig();
bool ConfigureStop(XMLNodePointer_t node);
};
std::vector<DetectorStop> ReadDetectorStopConfig(
std::string const &fname, std::string const &RPName = "");
#endif
| 22.03125 | 62 | 0.757447 | [
"vector"
] |
865c0bead16610964758ff7ac7e36c376b461427 | 21,435 | cxx | C++ | ITSMFT/ITS/ITSUpgradeRec/AliITSUVertexer.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1 | 2017-04-27T17:28:15.000Z | 2017-04-27T17:28:15.000Z | ITSMFT/ITS/ITSUpgradeRec/AliITSUVertexer.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 3 | 2017-07-13T10:54:50.000Z | 2018-04-17T19:04:16.000Z | ITSMFT/ITS/ITSUpgradeRec/AliITSUVertexer.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 5 | 2017-03-29T12:21:12.000Z | 2018-01-15T15:52:24.000Z | #include <Riostream.h>
#include <TBranch.h>
#include <TClonesArray.h>
#include <TMath.h>
#include <TString.h>
#include <TTree.h>
#include "AliESDVertex.h"
#include "AliITSUClusterLines.h"
#include "AliITSUClusterPix.h"
#include "AliITSUVertexer.h"
#include "AliLog.h"
#include "AliStrLine.h"
#include "AliVertexerTracks.h"
using TMath::Abs;
using TMath::Sqrt;
using TMath::ATan2;
using TMath::TwoPi;
using TMath::BubbleLow;
using std::cout;
using std::endl;
//////////////////////////////////////////////////////////////////////
// This class is used to compute the position of all the primary //
// vertices in a single event using the upgraded ITS. //
// Optimizations ongoing. //
// Origin puccio@to.infn.it Feb. 20 2014 //
//////////////////////////////////////////////////////////////////////
//_____________________________________________________________________________________________
AliITSUVertexer::AliITSUVertexer(Double_t phicut, Double_t zcut, Double_t paircut,Double_t clcut, Int_t cclcut) : AliVertexer(),
fClusterContribCut(cclcut),
fClusterCut(clcut),
fClusterIndex(),
fClusterPhi(),
fClusters(),
fLines("AliStrLine",1000),
fLinesClusters("AliITSUClusterLines.h",1000),
fLinesPhi(0),
fNoClusters(0),
fNoLines(0),
fNoVertices(0),
fPairCut(paircut),
fPhiCut(phicut),
fZCut(zcut),
fUsedClusters(),
fUsedLines(),
fVertices(NULL)
#ifdef MC_CHECK
,fGoodLines(0),fGoodLinesPhi(0),fParticleId(0)
#endif
{
// Standard I/O constructor
}
//_____________________________________________________________________________________________
AliITSUVertexer::~AliITSUVertexer() {
// Destructor
Reset();
}
//_____________________________________________________________________________________________
void AliITSUVertexer::FindVerticesForCurrentEvent() {
// Try to find all the primary vertices in the current
fNoVertices=0;
FindTracklets();
if(fNoLines<2) {
//fVertices.push_back(AliESDVertex());
return;// AliESDVertex();
}
// fVertices.push_back(AliVertexerTracks::TrackletVertexFinder(&fLines,1));
//fNoVertices=1;
fUsedLines=new Short_t[fNoLines];
for(UInt_t i=0;i<fNoLines;++i) fUsedLines[i]=-1;
fNoClusters=0;
for(UInt_t i1=0;i1<fNoLines;++i1) {
if(fUsedLines[i1]!=-1) continue;
AliStrLine* line1 = (AliStrLine*)fLines.At(i1);
for(UInt_t i2=i1+1;i2<fNoLines;++i2) {
if(fUsedLines[i2]!=-1) continue;
AliStrLine* line2 = (AliStrLine*)fLines.At(i2);
if(line1->GetDCA(line2)<=fPairCut) {
//cout << fNoClusters <<" " << i1 << " " << i2 << " ";
new(fLinesClusters[fNoClusters])AliITSUClusterLines(i1,line1,i2,line2);
AliITSUClusterLines* current=(AliITSUClusterLines*)fLinesClusters.At(fNoClusters);
Double_t p[3];
current->GetVertex(p);
if((p[0]*p[0]+p[1]*p[1])>=4) { // Beam pipe check
fLinesClusters.RemoveAt(fNoClusters);
fLinesClusters.Compress();
break;
}
fUsedLines[i1]=fNoClusters;
fUsedLines[i2]=fNoClusters;
for(UInt_t i3=0;i3<fNoLines;++i3) {
if(fUsedLines[i3]!=-1) continue;
AliStrLine *line3 = (AliStrLine*)fLines.At(i3);
//cout << p[0] << " " << p[1] << " " << p[2] << endl;
//line3->PrintStatus();
if(line3->GetDistFromPoint(p)<=fPairCut) {
//cout << i3 << " ";
current->Add(i3,line3);
fUsedLines[i3]=fNoClusters;
current->GetVertex(p);
}
}
++fNoClusters;
//cout << endl;
break;
}
}
}
fLinesClusters.Sort();
for(UInt_t i0=0;i0<fNoClusters; ++i0) {
Double_t p0[3],p1[3];
AliITSUClusterLines *clu0 = (AliITSUClusterLines*)fLinesClusters.At(i0);
clu0->GetVertex(p0);
for(UInt_t i1=i0+1;i1<fNoClusters; ++i1) {
AliITSUClusterLines *clu1 = (AliITSUClusterLines*)fLinesClusters.At(i1);
clu1->GetVertex(p1);
if (TMath::Abs(p0[2]-p1[2])<=fClusterCut) {
Double_t distance=(p0[0]-p1[0])*(p0[0]-p1[0])+(p0[1]-p1[1])*(p0[1]-p1[1])+(p0[2]-p1[2])*(p0[2]-p1[2]);
//Bool_t flag=kFALSE;
if(distance<=fPairCut*fPairCut) {
UInt_t n=0;
Int_t *labels=clu1->GetLabels(n);
for(UInt_t icl=0; icl<n; ++icl) clu0->Add(labels[icl],(AliStrLine*)fLines.At(labels[icl]));
clu0->GetVertex(p0);
//flag=kTRUE;
}
fLinesClusters.RemoveAt(i1);
fLinesClusters.Compress();
fNoClusters--;
i1--;
//if(flag) i1=10;
}
}
}
fVertices=new AliESDVertex[fNoClusters];
for(UInt_t i0=0; i0<fNoClusters; ++i0) {
AliITSUClusterLines *clu0 = (AliITSUClusterLines*)fLinesClusters.At(i0);
Int_t size=clu0->GetSize();
if(size<fClusterContribCut&&fNoClusters>1) {
fLinesClusters.RemoveAt(i0);
fLinesClusters.Compress();
fNoClusters--;
continue;
}
Double_t p0[3],cov[6];
clu0->GetVertex(p0);
clu0->GetCovMatrix(cov);
if((p0[0]*p0[0]+p0[1]*p0[1])<1.98*1.98) {
fVertices[fNoVertices++]=AliESDVertex(p0,cov,99999.,size);
}
}
return;// AliVertexerTracks::TrackletVertexFinder(&fLines,0);
}
//______________________________________________________________________
AliESDVertex* AliITSUVertexer::FindVertexForCurrentEvent(TTree *cluTree)
{
// Reconstruction of all the primary vertices in the event. It returns the vertex with the highest number of contributors.
Reset();
for(Int_t i=0;i<3;++i) {
TBranch* br = cluTree->GetBranch(Form("ITSRecPoints%d",i));
if (!br) return NULL;
br->SetAddress(&fClusters[i]);
}
cluTree->GetEntry(0);
SortClusters();
FindVerticesForCurrentEvent();
if(fNoVertices<1) return NULL;
return new AliESDVertex(fVertices[0]);
}
//_____________________________________________________________________________________________
Int_t AliITSUVertexer::MatchPoints(UShort_t layer, Double_t anchor, Double_t *p0, Double_t *p1) {
// Method for matching clusters with similar phi and z inside the range [zmin,zmax]
AliDebug(3,Form("Matching points on layer %i...\n",layer));
Double_t xyz[3][3]; // {{0: 'min', 1: 'mid', 2: 'max'},{0: 'x', 1: 'y', 2: 'z'}}
AliITSUClusterPix* cl[3]; // {0: 'min', 1: 'mid', 2: 'max'}
Double_t phi[3]; // {0: 'min', 1: 'mid', 2: 'max'}
Int_t nocl=fClusters[layer]->GetEntriesFast();
Int_t imin=0,imax=nocl!=0 ? nocl-1 : nocl,imid=(imax+imin)/2;
Double_t a=0,b=0,c=0;
if(layer==2) {
a=(p0[0]-p1[0])*(p0[0]-p1[0])+(p0[1]-p1[1])*(p0[1]-p1[1]);
b=(p1[0]-p0[0])*p0[0]+(p1[1]-p0[1])*p0[1];
c=p0[0]*p0[0]+p0[1]*p0[1];
}
Int_t flag=-1;
while (imax > imin) {
while(fUsedClusters[layer][fClusterIndex[layer][imin]]==kTRUE&&imin<imax) ++imin;
while(fUsedClusters[layer][fClusterIndex[layer][imax]]==kTRUE&&imax>0) --imax;
if(imax<imin) return -1;
cl[0] = (AliITSUClusterPix*)fClusters[layer]->At(fClusterIndex[layer][imin]);
cl[0]->GetGlobalXYZ(xyz[0]);
phi[0] = fClusterPhi[layer][fClusterIndex[layer][imin]];
AliDebug(4,Form("Cluster min: %i, %i, %f, %i\n",imin,cl[0]->GetLabel(0),phi[0]-anchor,fUsedClusters[layer][fClusterIndex[layer][imin]]));
if((Abs(phi[0]-anchor)<=fPhiCut||Abs(Abs(phi[0]-anchor)-TMath::TwoPi())<=fPhiCut)) {
AliDebug(4,Form("Ok min: %i \n",imin));
if(layer==2) {
if(fUsedClusters[layer][fClusterIndex[layer][imin]]) {
flag=1;
break;
}
c-=(xyz[0][0]*xyz[0][0]+xyz[0][1]*xyz[0][1]);
Double_t z=p0[2]+(p1[2]-p0[2])*(-b+Sqrt(b*b-a*c))/a;
Double_t zmin=z-fZCut,zmax=z+fZCut;
if(zmin<=xyz[0][2]&&xyz[0][2]<=zmax) {
AliDebug(4,Form("Ok Z: %i \n",imin));
return fClusterIndex[layer][imin];
}
AliDebug(4,Form("No Z match: %i \n",imin));
c=p0[0]*p0[0]+p0[1]*p0[1];
flag=1;
break;
} else if(!fUsedClusters[layer][fClusterIndex[layer][imin]]) return fClusterIndex[layer][imin];
}
cl[2] = (AliITSUClusterPix*)fClusters[layer]->At(fClusterIndex[layer][imax]);
cl[2]->GetGlobalXYZ(xyz[2]);
phi[2] = fClusterPhi[layer][fClusterIndex[layer][imax]];
AliDebug(4,Form("Cluster max: %i, %i, %f, %i\n",imax,cl[2]->GetLabel(0),phi[2]-anchor,fUsedClusters[layer][fClusterIndex[layer][imax]]));
if((Abs(phi[2]-anchor)<=fPhiCut||Abs(Abs(phi[2]-anchor)-TMath::TwoPi())<=fPhiCut)) {
AliDebug(4,Form("Ok max: %i \n",imax));
if(layer==2) {
if(fUsedClusters[layer][fClusterIndex[layer][imax]]) {
flag=3;
break;
}
c-=(xyz[2][0]*xyz[2][0]+xyz[2][1]*xyz[2][1]);
Double_t z=p0[2]+(p1[2]-p0[2])*(-b+Sqrt(b*b-a*c))/a;
Double_t zmin=z-fZCut,zmax=z+fZCut;
if(zmin<=xyz[2][2]&&xyz[2][2]<=zmax) {
AliDebug(4,Form("Ok Z: %i \n",imax));
return fClusterIndex[layer][imax];
}
c=p0[0]*p0[0]+p0[1]*p0[1];
AliDebug(4,Form("No Z match: %i \n",imax));
flag=3;
break;
} else if(!fUsedClusters[layer][fClusterIndex[layer][imax]]) return fClusterIndex[layer][imax];
}
imid=(imax+imin)/2;
if(imid==imin) return -1;
Int_t step=1,sign=-1;
while(fUsedClusters[layer][fClusterIndex[layer][imid]]) {
imid=imid+step;
sign*=-1;
step=(step+sign)*(-1);
if(imid>=imax||imid<=imin) return -1;
}
cl[1] = (AliITSUClusterPix*)fClusters[layer]->At(fClusterIndex[layer][imid]);
cl[1]->GetGlobalXYZ(xyz[1]);
phi[1] = fClusterPhi[layer][fClusterIndex[layer][imid]];
AliDebug(4,Form("Cluster mid: %i, %i, %f, %i \n",imid,cl[1]->GetLabel(0),phi[1]-anchor,fUsedClusters[layer][fClusterIndex[layer][imid]]));
//cout << imin << " " << imid << " " << imax << endl;
//cout << fClusterIndex[layer][imid] << endl;
if((Abs(phi[1]-anchor)<=fPhiCut||Abs(Abs(phi[1]-anchor)-TMath::TwoPi())<=fPhiCut)) {
AliDebug(4,Form("Ok mid: %i \n",imid));
if(layer==2) {
c-=(xyz[1][0]*xyz[1][0]+xyz[1][1]*xyz[1][1]);
Double_t z=p0[2]+(p1[2]-p0[2])*(-b+Sqrt(b*b-a*c))/a;
Double_t zmin=z-fZCut,zmax=z+fZCut;
if(zmin<=xyz[1][2]&&xyz[1][2]<=zmax) {
AliDebug(4,Form("Ok Z: %i \n",imid));
return fClusterIndex[layer][imid];
}
AliDebug(4,Form("No Z match: %i \n",imid));
c=p0[0]*p0[0]+p0[1]*p0[1];
flag=2;
break;
} else if(!fUsedClusters[layer][fClusterIndex[layer][imid]]) return fClusterIndex[layer][imid];
}
// determine which subarray to search
if (phi[1] < anchor) {
// change min index to search upper subarray
AliDebug(4,"Case minor\n");
imin = imid + 1;
--imax;
} else if (phi[1] > anchor) {
AliDebug(4,"Case greater\n");
// change max index to search lower subarray
++imin;
imax = imid - 1;
} else if(!fUsedClusters[layer][fClusterIndex[layer][imid]]) {
return fClusterIndex[layer][imid];
} else return -1;
}
if(flag>-1) {
AliDebug(4,"Flag issued, starting forward backward check\n");
Int_t start=imid;
switch(flag) {
case 1:
start=imin;
break;
case 2:
start=imid;
break;
case 3:
start=imax;
break;
}
Int_t curr=start-1;
Bool_t lap=kFALSE;
while(1){
if(curr==-1&&!lap) {
lap=kTRUE;
curr=nocl-1;
} else if(lap) break;
cl[0] = (AliITSUClusterPix*)fClusters[layer]->At(fClusterIndex[layer][curr]);
cl[0]->GetGlobalXYZ(xyz[0]);
phi[0] = fClusterPhi[layer][fClusterIndex[layer][curr]];
AliDebug(4,Form("Looking backward: %i, %i, %f, %i\n",curr,cl[0]->GetLabel(0),phi[0]-anchor,fUsedClusters[layer][fClusterIndex[layer][curr]]));
if(!(Abs(phi[0]-anchor)<=fPhiCut||Abs(Abs(phi[0]-anchor)-TMath::TwoPi())<=fPhiCut)) break;
if(fUsedClusters[layer][fClusterIndex[layer][curr]]) {
curr--;
continue;
}
AliDebug(4,Form("Ok backward: %i \n",curr));
c-=(xyz[0][0]*xyz[0][0]+xyz[0][1]*xyz[0][1]);
Double_t z=p0[2]+(p1[2]-p0[2])*(-b+Sqrt(b*b-a*c))/a;
Double_t zmin=z-fZCut,zmax=z+fZCut;
if(zmin<=xyz[0][2]&&xyz[0][2]<=zmax) {
AliDebug(4,Form("Ok Z: %i \n",curr));
return fClusterIndex[layer][curr];
}
AliDebug(4,Form("No Z match: %i \n",curr));
c=p0[0]*p0[0]+p0[1]*p0[1];
curr--;
}
lap=kFALSE;
curr=start+1;
while(1){
if(curr==nocl&&!lap) {
curr=0;
lap=kTRUE;
} else if(lap) break;
cl[0] = (AliITSUClusterPix*)fClusters[layer]->At(fClusterIndex[layer][curr]);
cl[0]->GetGlobalXYZ(xyz[0]);
phi[0] = fClusterPhi[layer][fClusterIndex[layer][curr]];
AliDebug(4,Form("Looking forward: %i, %i, %f, %i\n",curr,cl[0]->GetLabel(0),phi[0]-anchor,fUsedClusters[layer][fClusterIndex[layer][curr]]));
if(!(Abs(phi[0]-anchor)<=fPhiCut||Abs(Abs(phi[0]-anchor)-TMath::TwoPi())<=fPhiCut)) break;
if(fUsedClusters[layer][fClusterIndex[layer][curr]]) {
curr++;
continue;
}
AliDebug(4,Form("Ok forward: %i \n",curr));
c-=(xyz[0][0]*xyz[0][0]+xyz[0][1]*xyz[0][1]);
Double_t z=p0[2]+(p1[2]-p0[2])*(-b+Sqrt(b*b-a*c))/a;
Double_t zmin=z-fZCut,zmax=z+fZCut;
if(zmin<=xyz[0][2]&&xyz[0][2]<=zmax) {
AliDebug(4,Form("Ok Z: %i \n",curr));
return fClusterIndex[layer][curr];
}
AliDebug(4,Form("No Z match: %i \n",curr));
c=p0[0]*p0[0]+p0[1]*p0[1];
curr++;
}
}
if(imax==imin&&imax!=0) {
cl[0] = (AliITSUClusterPix*)fClusters[layer]->At(fClusterIndex[layer][imin]);
cl[0]->GetGlobalXYZ(xyz[0]);
phi[0] = fClusterPhi[layer][fClusterIndex[layer][imin]];
AliDebug(4,Form("Cluster eq: %i, %i, %f, %i\n",imin,cl[0]->GetLabel(0),phi[0]-anchor,fUsedClusters[layer][fClusterIndex[layer][imin]]));
if((Abs(phi[0]-anchor)<=fPhiCut||Abs(Abs(phi[0]-anchor)-TMath::TwoPi())<=fPhiCut)&&!fUsedClusters[layer][fClusterIndex[layer][imin]]) {
AliDebug(4,Form("Ok eq: %i \n",imin));
if(layer==2) {
c-=(xyz[0][0]*xyz[0][0]+xyz[0][1]*xyz[0][1]);
Double_t z=p0[2]+(p1[2]-p0[2])*(-b+Sqrt(b*b-a*c))/a;
Double_t zmin=z-fZCut,zmax=z+fZCut;
if(zmin<=xyz[0][2]&&xyz[0][2]<=zmax) {
AliDebug(4,Form("Ok Z eq: %i \n",imin));
return fClusterIndex[layer][imin];
}
AliDebug(4,Form("No Z eq: %i \n",imin));
c=p0[0]*p0[0]+p0[1]*p0[1];
} else return fClusterIndex[layer][imin];
}
}
// no match found :(
return -1;
}
//_____________________________________________________________________________________________
void AliITSUVertexer::PrintStatus() const {
// Prints all the cuts and important data members for the current status
cout << "Cut on phi: " << fPhiCut << endl;
cout << "Cut on z: " << fZCut << endl;
}
//_____________________________________________________________________________________________
void AliITSUVertexer::Reset() {
// Resets the vertexer for a new event (or for its destruction)
AliDebug(2,"Resetting the vertexer...\n");
fNoVertices=0;
for(Int_t i=0;i<3;++i) {
delete[] fUsedClusters[i];
delete[] fClusterIndex[i];
delete[] fClusterPhi[i];
}
if(fNoLines>2) {
delete []fUsedLines;
}
delete[] fVertices;
fLinesPhi=0;
fLines.Clear();
fLinesClusters.Clear();
#ifdef MC_CHECK
fGoodLines=0;
fGoodLinesPhi=0;
delete[] fParticleId;
#endif
//delete fVertices;
}
//_____________________________________________________________________________________________
void AliITSUVertexer::FindTracklets() {
// It combines recpoints over the first three layers to define a list of tracklets
// Here it uses the ordered list of points. Second and third layers are ordered using phi
AliDebug(2,"Calling the trackleter...\n");
UInt_t noPntL[3];
for(UShort_t i=0;i<3;++i) {
noPntL[i]=fClusters[i]->GetEntries();
fUsedClusters[i]=new Bool_t[noPntL[i]];
for(UInt_t ii=0;ii<noPntL[i];++ii) fUsedClusters[i][ii]=kFALSE;
}
#ifdef MC_CHECK
fParticleId=new UInt_t[noPntL[0]];
#endif
fNoLines=0;
UInt_t nolinesphi=0;
Double_t p0[3],p1[3],pp2[3];
for(UInt_t i0=0;i0<noPntL[0];++i0) {
if(fUsedClusters[0][i0]) continue;
AliITSUClusterPix* cluster0=(AliITSUClusterPix*)fClusters[0]->At(i0);
cluster0->GetGlobalXYZ(p0);
vector<Int_t> tmp;
Int_t i1=0;
Int_t label0=cluster0->GetLabel(0);
AliDebug(4,Form("Layer 0: %i\n",label0));
while(i1>=0) {
i1 = MatchPoints(1,fClusterPhi[0][i0]);
if(i1<0) break;
++nolinesphi;
AliITSUClusterPix* cluster1=(AliITSUClusterPix*)fClusters[1]->At(i1);
cluster1->GetGlobalXYZ(p1);
tmp.push_back(i1);
fUsedClusters[1][i1]=kTRUE;
Int_t i2 = MatchPoints(2,fClusterPhi[1][i1],p0,p1);
if(i2<0) continue;
#ifdef MC_CHECK
CheckMC(i0,i1,i2);
#endif
AliITSUClusterPix* cluster2=(AliITSUClusterPix*)fClusters[2]->At(i2);
cluster2->GetGlobalXYZ(pp2);
fUsedClusters[0][i0]=kTRUE;
fUsedClusters[2][i2]=kTRUE;
// Errors to be checked...
Float_t cov0[6],cov1[6],cov2[6];
cluster0->GetGlobalCov(cov0);
cluster1->GetGlobalCov(cov1);
cluster2->GetGlobalCov(cov2);
//Error on tracklet direction near the vertex
Double_t rad1=TMath::Sqrt(p0[0]*p0[0]+p0[1]*p0[1]);
Double_t rad2=TMath::Sqrt(p1[0]*p1[0]+p1[1]*p1[1]);
Double_t factor=(rad1+rad2)/(rad2-rad1);
//Curvature error
Double_t curvErr=0;
Double_t bField=0.5;
Double_t meanPtSelTrk=0.630;
Double_t curvRadius=meanPtSelTrk/(0.3*bField)*100; //cm
Double_t dRad=TMath::Sqrt((p0[0]-p1[0])*(p0[0]-p1[0])+(p0[1]-p1[1])*(p0[1]-p1[1]));
Double_t aux=dRad/2.+rad1;
curvErr=TMath::Sqrt(curvRadius*curvRadius-dRad*dRad/4.)-TMath::Sqrt(curvRadius*curvRadius-aux*aux); //cm
Double_t sq[3],wmat[9]={1,0,0,0,1,0,0,0,1};
sq[0]=(cov0[0]+curvErr*curvErr/2.)*factor*factor;//cov1[0]+cov2[0]);
sq[1]=(cov0[3]+curvErr*curvErr/2.)*factor*factor;//cov1[3]+cov2[3]);
sq[2]=(cov0[5])*factor*factor;//cov1[5]+cov2[5]);
// Multiple scattering
Double_t meanPSelTrk=0.875;
Double_t pOverMass=meanPSelTrk/0.140;
Double_t beta2=pOverMass*pOverMass/(1+pOverMass*pOverMass);
Double_t p2=meanPSelTrk*meanPSelTrk;
Double_t rBP=1.98; // Beam pipe radius
Double_t dBP=0.08/35.3; // 800 um of Be
Double_t dL1=0.01; //approx. 1% of radiation length
Double_t theta2BP=14.1*14.1/(beta2*p2*1e6)*dBP;
Double_t theta2L1=14.1*14.1/(beta2*p2*1e6)*dL1;
Double_t rtantheta1=(rad2-rad1)*TMath::Tan(TMath::Sqrt(theta2L1));
Double_t rtanthetaBP=(rad1-rBP)*TMath::Tan(TMath::Sqrt(theta2BP));
for(Int_t ico=0; ico<3;ico++){
sq[ico]+=rtantheta1*rtantheta1*factor*factor/3.;
sq[ico]+=rtanthetaBP*rtanthetaBP*factor*factor/3.;
}
if(sq[0]!=0) wmat[0]=1/sq[0];
if(sq[1]!=0) wmat[4]=1/sq[1];
if(sq[2]!=0) wmat[8]=1/sq[2];
/*Int_t label0=cluster0->GetLabel(0);
Int_t label1=cluster1->GetLabel(0);
Int_t label2=cluster2->GetLabel(0);*/
//cout << label0 << " " << label1 << " "<<label2 << endl;
//printf("%f\t%f\t%f\n-\t%f\t%f\n-\t-\t%f\n",wmat[0],wmat[1],wmat[2],wmat[3],wmat[4],wmat[5]);
//gSystem->Exec(Form("echo %i >> trkl",cluster0->GetLabel(0)+cluster1->GetLabel(0)));
new(fLines[fNoLines++])AliStrLine(p0,sq,wmat,p1,kTRUE);
break;
}
for(UInt_t itmp=0; itmp<tmp.size(); ++itmp) fUsedClusters[1][tmp.at(itmp)]=kFALSE;
tmp.clear();
//((AliStrLine*)fLines[fNoLines-1])->PrintStatus();
//printf("(%f,%f,%f) and (%f,%f,%f)\n",p0[0],p0[1],p0[2],p1[0],p1[1],p1[2]);
}
fLinesPhi=nolinesphi;
//cout << Form("=======================================================\nNolinesphi: %i, nolines: %i\nGood Nolinesphi: %i, good nolines: %i\n",nolinesphi,fNoLines,fGoodLinesPhi,fGoodLines);
}
//___________________________________________________________________________
void AliITSUVertexer::SortClusters() {
// Reading of the clusters on the first three layer of the upgraded ITS
for(Int_t i=0;i<3;++i) {
TClonesArray *clr=fClusters[i];
Int_t nocl=clr->GetEntriesFast();
if(nocl==0) {
fClusterPhi[i]=new Double_t[1];
fClusterPhi[i][0]=-999999;
fClusterIndex[i]=new Int_t[1];
fClusterIndex[i][0]=0;
} else {
fClusterPhi[i]=new Double_t[nocl];
fClusterIndex[i]=new Int_t[nocl];
for(Int_t k=0;k<nocl;++k) {
AliITSUClusterPix* cl=(AliITSUClusterPix*)clr->At(k);
Double_t pt[3];
cl->GetGlobalXYZ(pt);
fClusterPhi[i][k]=ATan2(pt[1],pt[0]);
}
BubbleLow(nocl,fClusterPhi[i],fClusterIndex[i]);
}
}
}
#ifdef MC_CHECK
//___________________________________________________________________________
Bool_t AliITSUVertexer::CheckMC(UInt_t i0, UInt_t i1, UInt_t i2) {
// Debugging function
//cout << "Checking MC truth" << endl;
Int_t label=0;
Bool_t flag=kFALSE;
AliITSUClusterPix* p0=(AliITSUClusterPix*)fClusters[0]->At(i0);
AliITSUClusterPix* p1=(AliITSUClusterPix*)fClusters[1]->At(i1);
for(Int_t i=0; i<3; ++i) {
label=p0->GetLabel(i);
for(Int_t j=0; j<3; ++j) {
if(label==p1->GetLabel(j)&&label>0) {
fGoodLinesPhi++;
flag=kTRUE;
break;
}
}
if(flag) break;
}
if(!flag) return kFALSE;
AliITSUClusterPix* p2=(AliITSUClusterPix*)fClusters[2]->At(i2);
for(Int_t j=0; j<3; ++j) {
if(label==p2->GetLabel(j)) {
fParticleId[fGoodLines]=label;
fGoodLines++;
//cout << label << endl;
return kTRUE;
}
}
return kFALSE;
}
#endif
| 34.241214 | 191 | 0.616422 | [
"vector"
] |
8670f81fdede82be35c8f684fb9a00182915ab80 | 1,655 | cpp | C++ | nas.cpp | danmastalerz/asd-playground | 30fe094dce52bc432bc4ba2fd485b101818fc09b | [
"MIT"
] | null | null | null | nas.cpp | danmastalerz/asd-playground | 30fe094dce52bc432bc4ba2fd485b101818fc09b | [
"MIT"
] | null | null | null | nas.cpp | danmastalerz/asd-playground | 30fe094dce52bc432bc4ba2fd485b101818fc09b | [
"MIT"
] | null | null | null | /*
idea taka, że dla każdej wartości mamy zbiór pozycji na których ta wartość występuje
potem dla każdej wartości szukamy najdłuższego spójnego podciągu rosnącego o 1 w tym zbiorze
i bierzemy maksa z tego
ale to nie przechodziło pamięciowo xD
więc zamiast map<int, set<int>> jest map<int, vector<int>> a potem usuwamy duplikaty/sortujemy.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <set>
using namespace std;
#define FOR(n) for(int i = 0; i < n; i++)
#define FOR2(a, b) for (int i = a; i <= b; i++)
#define LOAD_ARRAY(n, t) for (int i = 0; i < n; i++) cin >> t[i]
int main() {
int n, m;
scanf("%d", &n);
scanf("%d", &m);
map<int, vector<int>> x;
int temp;
FOR(n) {
for (int j = 0; j < m; j++) {
scanf("%d", &temp);
x[temp].push_back(j);
}
}
int max_ans = 1;
int ans = 1;
for (auto& it : x) {
ans = 1;
sort(it.second.begin(), it.second.end());
it.second.erase(unique( it.second.begin(), it.second.end() ), it.second.end());
for (auto it2 = it.second.begin(); it2 != it.second.end(); it2++) {
auto next_ = next(it2, 1);
if (next_ == it.second.end()) continue;
if (*it2 == *next_ - 1) {
ans++;
max_ans = max(max_ans, ans);
}
else {
max_ans = max(max_ans, ans);
ans = 1;
}
}
}
printf("%d", max_ans);
}
| 23.985507 | 96 | 0.503927 | [
"vector"
] |
8671dec872326902dcf27a20d4d3782ae3364110 | 5,235 | cpp | C++ | src/SystemVector.cpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | 2 | 2018-07-04T16:44:04.000Z | 2021-01-03T07:26:27.000Z | src/SystemVector.cpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | src/SystemVector.cpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | #include "SystemVector.hpp"
#include "DOFVector.hpp"
#include "DOFVectorOperations.hpp"
#include "MatrixVector.hpp"
namespace AMDiS
{
SystemVector::SystemVector(std::string name_,
std::vector<FiniteElemSpace const*> feSpace_,
int size,
bool createVec_)
: name(name_),
componentSpaces(feSpace_),
vectors(size),
createVec(createVec_)
{
if (createVec_)
for (int i = 0; i < size; i++)
vectors[i] = new DOFVector<double>(componentSpaces[i], "tmp");
}
SystemVector::SystemVector(const SystemVector& rhs)
: name(rhs.getName()),
componentSpaces(rhs.getFeSpaces()),
vectors(rhs.getSize())
{
for (size_t i = 0; i < vectors.size(); i++)
vectors[i] = new DOFVector<double>(*rhs.getDOFVector(int( i )));
}
SystemVector::~SystemVector()
{
if (createVec)
{
for (size_t i = 0; i < vectors.size(); i++)
delete vectors[i];
}
}
int SystemVector::getUsedSize() const
{
int totalSize = 0;
for (size_t i = 0; i < vectors.size(); i++)
totalSize += vectors[i]->getUsedSize();
return totalSize;
}
double& SystemVector::operator[](DegreeOfFreedom index)
{
DegreeOfFreedom localIndex = index;
DegreeOfFreedom vectorIndex = 0;
while (localIndex >= vectors[vectorIndex]->getUsedSize())
localIndex -= vectors[vectorIndex++]->getUsedSize();
return (*(vectors[vectorIndex]))[localIndex];
}
double SystemVector::operator[](DegreeOfFreedom index) const
{
DegreeOfFreedom localIndex = index;
DegreeOfFreedom vectorIndex = 0;
while (localIndex >= vectors[vectorIndex]->getUsedSize())
localIndex -= vectors[vectorIndex++]->getUsedSize();
return (*(vectors[vectorIndex]))[localIndex];
}
void SystemVector::set(double value)
{
for (size_t i = 0; i < vectors.size(); i++)
vectors[i]->set(value);
}
void SystemVector::setCoarsenOperation(RefineCoarsenOperation op)
{
for (size_t i = 0; i < vectors.size(); i++)
vectors[i]->setCoarsenOperation(op);
}
void SystemVector::setRefineOperation(RefineCoarsenOperation op)
{
for (size_t i = 0; i < vectors.size(); i++)
vectors[i]->setRefineOperation(op);
}
SystemVector& SystemVector::operator=(double value)
{
for (size_t i = 0; i < vectors.size(); i++)
(*(vectors[i])) = value;
return *this;
}
SystemVector& SystemVector::operator=(SystemVector const& rhs)
{
TEST_EXIT_DBG(rhs.vectors.size() == vectors.size())("Invalied sizes!\n");
for (size_t i = 0; i < vectors.size(); i++)
(*(vectors[i])) = (*(rhs.getDOFVector(int( i ))));
return *this;
}
void SystemVector::copy(SystemVector const& rhs)
{
TEST_EXIT_DBG(getSize() == rhs.getSize())("Invalid sizes!\n");
for (size_t i = 0; i < vectors.size(); i++)
vectors[i]->copy(*(const_cast<SystemVector&>(rhs).getDOFVector(int( i ))));
}
void SystemVector::interpol(std::vector<std::function<double(WorldVector<double>)>>& f)
{
for (size_t i = 0; i < vectors.size(); i++)
vectors[i]->interpol(f[i]);
}
void SystemVector::interpol(SystemVector* v, double factor)
{
for (int i = 0; i < v->getSize(); i++)
vectors[i]->interpol(v->getDOFVector(i), factor);
}
size_t SystemVector::calcMemoryUsage() const
{
size_t result = 0;
for (size_t i = 0; i < vectors.size(); i++)
result += vectors[i]->calcMemoryUsage();
result += sizeof(SystemVector);
return result;
}
/* ----- OPERATORS WITH SYSTEM-VECTORS ------------------------------------ */
SystemVector& operator*=(SystemVector& x, double d)
{
for (int i = 0; i < x.getSize(); i++)
*(x.getDOFVector(i)) *= d;
return x;
}
double operator*(SystemVector const& x, SystemVector const& y)
{
TEST_EXIT_DBG(x.getSize() == y.getSize())("invalid size\n");
double result = 0.0;
for (int i = 0; i < x.getSize(); i++)
result += (*x.getDOFVector(i)) * (*y.getDOFVector(i));
return result;
}
SystemVector& operator+=(SystemVector& x, SystemVector const& y)
{
TEST_EXIT_DBG(x.getSize() == y.getSize())("invalid size\n");
for (int i = 0; i < x.getSize(); i++)
(*(x.getDOFVector(i))) += (*(y.getDOFVector(i)));
return x;
}
SystemVector& operator-=(SystemVector& x, SystemVector const& y)
{
TEST_EXIT_DBG(x.getSize() == y.getSize())("invalid size\n");
for (int i = 0; i < x.getSize(); i++)
(*(x.getDOFVector(i))) -= (*(y.getDOFVector(i)));
return x;
}
double norm(SystemVector const* x)
{
double result = 0.0;
for (int i = 0; i < x->getSize(); i++)
result += x->getDOFVector(i)->squareNrm2();
return std::sqrt(result);
}
double L2Norm(SystemVector const* x)
{
double result = 0.0;
for (int i = 0; i < x->getSize(); i++)
result += x->getDOFVector(i)->L2NormSquare();
return std::sqrt(result);
}
double H1Norm(SystemVector const* x)
{
double result = 0.0;
for (int i = 0; i < x->getSize(); i++)
result += x->getDOFVector(i)->H1NormSquare();
return std::sqrt(result);
}
} // end namespace AMDiS
| 24.348837 | 89 | 0.594842 | [
"vector"
] |
8672668ab9357d86219a3d04c3378634c2ff8b75 | 6,931 | cpp | C++ | Applications/Scale/scale.cpp | MariaHammer/opensim-core_HaeufleMuscle | 96257e9449d9ac430bbb54e56cd13aaebeee1242 | [
"Apache-2.0"
] | 532 | 2015-03-13T18:51:10.000Z | 2022-03-27T08:08:29.000Z | Applications/Scale/scale.cpp | MariaHammer/opensim-core_HaeufleMuscle | 96257e9449d9ac430bbb54e56cd13aaebeee1242 | [
"Apache-2.0"
] | 2,701 | 2015-01-03T21:33:34.000Z | 2022-03-30T07:13:41.000Z | Applications/Scale/scale.cpp | MariaHammer/opensim-core_HaeufleMuscle | 96257e9449d9ac430bbb54e56cd13aaebeee1242 | [
"Apache-2.0"
] | 271 | 2015-02-16T23:25:29.000Z | 2022-03-30T20:12:17.000Z | /* -------------------------------------------------------------------------- *
* OpenSim: scale.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ayman Habib *
* *
* 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. *
* -------------------------------------------------------------------------- */
// INCLUDES
#include <string>
#include <OpenSim/version.h>
#include <OpenSim/Common/Storage.h>
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/ScaleSet.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Tools/ScaleTool.h>
#include <OpenSim/Common/MarkerData.h>
#include <OpenSim/Simulation/Model/MarkerSet.h>
#include <OpenSim/Simulation/Model/ForceSet.h>
#include <OpenSim/Common/LoadOpenSimLibrary.h>
#include <OpenSim/Simulation/Model/Analysis.h>
using namespace std;
using namespace OpenSim;
static void PrintUsage(const char *aProgName, ostream &aOStream);
//______________________________________________________________________________
/**
* Test program to read SIMM model elements from an XML file.
*
* @param argc Number of command line arguments (should be 1).
* @param argv Command line arguments: simmReadXML inFile
*/
int main(int argc,char **argv)
{
//TODO: put these options on the command line
//LoadOpenSimLibrary("osimSimbodyEngine");
// DEPRECATION NOTICE
const std::string deprecationNotice = R"(
THIS EXECUTABLE IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE.
Use opensim-cmd instead, which can do everything that this executable can.
scale -S SetupFileName -> opensim-cmd run-tool SetupFileName
scale -PS -> opensim-cmd print-xml scale
)";
log_warn(deprecationNotice);
// SET OUTPUT FORMATTING
IO::SetDigitsPad(4);
// REGISTER TYPES
Object::registerType(ScaleTool());
ScaleTool::registerTypes();
// PARSE COMMAND LINE
string inName;
string option = "";
if (argc < 2) {
PrintUsage(argv[0], cout);
exit(-1);
} else {
// Load libraries first
LoadOpenSimLibraries(argc,argv);
int i;
for(i=1;i<=(argc-1);i++) {
option = argv[i];
// PRINT THE USAGE OPTIONS
if((option=="-help")||(option=="-h")||(option=="-Help")||(option=="-H")||
(option=="-usage")||(option=="-u")||(option=="-Usage")||(option=="-U")) {
PrintUsage(argv[0], cout);
return(0);
// Identify the setup file
} else if((option=="-S")||(option=="-Setup")) {
if (argv[i+1]==0){
PrintUsage(argv[0], cout);
return(0);
}
inName = argv[i+1];
break;
// Print a default setup file
} else if((option=="-PrintSetup")||(option=="-PS")) {
ScaleTool *subject = new ScaleTool();
subject->setName("default");
// Add in useful objects that may need to be instantiated
Object::setSerializeAllDefaults(true);
subject->print("default_Setup_Scale.xml");
Object::setSerializeAllDefaults(false);
log_info("Created file default_Setup_Scale.xml with "
"default setup");
return(0);
// PRINT PROPERTY INFO
} else if((option=="-PropertyInfo")||(option=="-PI")) {
if((i+1)>=argc) {
Object::PrintPropertyInfo(cout,"");
} else {
char *compoundName = argv[i+1];
if(compoundName[0]=='-') {
Object::PrintPropertyInfo(cout,"");
} else {
Object::PrintPropertyInfo(cout,compoundName);
}
}
return(0);
// Unrecognized
} else {
log_error("Unrecognized option {} on command line... "
"Ignored", option);
PrintUsage(argv[0], cout);
return(0);
}
}
}
try {
// Run the tool.
std::unique_ptr<ScaleTool> subject(new ScaleTool(inName));
const bool success = subject->run();
if (success) return EXIT_SUCCESS;
else return EXIT_FAILURE;
}
catch(const Exception& x) {
x.print(cout);
}
}
//_____________________________________________________________________________
/**
* Print the usage for this application
*/
void PrintUsage(const char *aProgName, ostream &aOStream)
{
string progName=IO::GetFileNameFromURI(aProgName);
aOStream<<"\n\n"<<progName<<":\n"<<GetVersionAndDate()<<"\n\n";
aOStream<<"Option Argument Action / Notes\n";
aOStream<<"------ -------- --------------\n";
aOStream<<"-Help, -H Print the command-line options for "<<progName<<".\n";
aOStream<<"-PrintSetup, -PS Generates a template Setup file to customize scaling\n";
aOStream<<"-Setup, -S SetupFileName Specify an xml setup file for scaling a generic model.\n";
aOStream<<"-PropertyInfo, -PI Print help information for properties in setup files.\n";
}
| 41.011834 | 109 | 0.515221 | [
"object",
"model"
] |
86867745dff84637f1fc32219ad053aceea2e414 | 1,301 | cpp | C++ | 2017.8.4/c.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | 2017.8.4/c.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | 2017.8.4/c.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | #include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#define ll long long
#define read(a) scanf("%d",&a);
const int maxn=20;
const int inf=99999999;
int c[maxn][maxn];
int pre[maxn];
bool book[maxn];
using namespace std;
int main(){
freopen("test.txt","r",stdin);
int t;
int ca;
int i,j;
int n,m;
scanf("%d",&t);
ca=0;
int ans;
int mini;
int start,end,weight;
while(t--){
ca++;
scanf("%d %d",&n,&m);
memset(c,0,sizeof(c));
while(m--){
scanf("%d %d %d",&start,&end,&weight);
c[start][end]+=weight;
}
ans=0;
while(1){
memset(pre,0,sizeof(pre));
memset(book,false,sizeof(book));
queue<int>que;
que.push(1);
book[1]=true;
mini=inf;
while(!que.empty()){
int num=que.front();
if(num==n)
break;
for(i=1;i<=n;i++){
if(book[i]==false&&c[num][i]>0){
book[i]=true;
que.push(i);
pre[i]=num;
mini=min(mini,c[num][i]);
}
}
que.pop();
}
if(book[n]==false)
break;
int tmp=n;
while(pre[tmp]!=0){
c[pre[tmp]][tmp]-=mini;
c[tmp][pre[tmp]]+=mini;
tmp=pre[tmp];
}
ans+=mini;
}
printf("Case %d: %d\n",ca,ans);
}
return 0;
} | 17.346667 | 41 | 0.566487 | [
"vector"
] |
8686906b25cfc4f08cfe9910cb1ca259cb4918f9 | 928 | cpp | C++ | Tree/105_ConstructBinaryTreefromPreorderandInorderTraversal.cpp | trierbo/OJCode | 327f78b12d3461f64c42375d611b6b65e71f4f78 | [
"MIT"
] | null | null | null | Tree/105_ConstructBinaryTreefromPreorderandInorderTraversal.cpp | trierbo/OJCode | 327f78b12d3461f64c42375d611b6b65e71f4f78 | [
"MIT"
] | null | null | null | Tree/105_ConstructBinaryTreefromPreorderandInorderTraversal.cpp | trierbo/OJCode | 327f78b12d3461f64c42375d611b6b65e71f4f78 | [
"MIT"
] | null | null | null | #include <cstddef>
#include <vector>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return buildSubTree(preorder, inorder, 0, 0, inorder.size());
}
TreeNode* buildSubTree(vector<int>& preorder, vector<int>& inorder, int parentIndex, int left, int right) {
if (left >= right)
return NULL;
TreeNode *subtree = new TreeNode(preorder[parentIndex]);
int pos = find(inorder.begin()+left, inorder.begin()+right, subtree->val) - inorder.begin();
subtree->left = buildSubTree(preorder, inorder, parentIndex+1, left, pos);
subtree->right = buildSubTree(preorder, inorder, parentIndex+pos-left+1, pos+1, right);
return subtree;
}
};
| 32 | 111 | 0.649784 | [
"vector"
] |
868a8838be2a1f2175b4afdf726d24fb7b2cc12d | 2,185 | hpp | C++ | libcaf_core/caf/ipv4_endpoint.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | 2,517 | 2015-01-04T22:19:43.000Z | 2022-03-31T12:20:48.000Z | libcaf_core/caf/ipv4_endpoint.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | 894 | 2015-01-07T14:21:21.000Z | 2022-03-30T06:37:18.000Z | libcaf_core/caf/ipv4_endpoint.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | 570 | 2015-01-21T18:59:33.000Z | 2022-03-31T19:00:02.000Z | // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include <cstdint>
#include <functional>
#include "caf/detail/comparable.hpp"
#include "caf/detail/core_export.hpp"
#include "caf/ipv4_address.hpp"
namespace caf {
/// An IP endpoint that contains an ::ipv4_address and a port.
class CAF_CORE_EXPORT ipv4_endpoint : detail::comparable<ipv4_endpoint> {
public:
// -- constructors -----------------------------------------------------------
ipv4_endpoint(ipv4_address address, uint16_t port);
ipv4_endpoint() = default;
ipv4_endpoint(const ipv4_endpoint&) = default;
ipv4_endpoint& operator=(const ipv4_endpoint&) = default;
// -- properties -------------------------------------------------------------
/// Returns the IPv4 address.
ipv4_address address() const noexcept {
return address_;
}
/// Sets the address of this endpoint.
void address(ipv4_address x) noexcept {
address_ = x;
}
/// Returns the port of this endpoint.
uint16_t port() const noexcept {
return port_;
}
/// Sets the port of this endpoint.
void port(uint16_t x) noexcept {
port_ = x;
}
/// Returns a hash for this object
size_t hash_code() const noexcept;
/// Compares this endpoint to `x`.
/// @returns 0 if `*this == x`, a positive value if `*this > x` and a negative
/// value otherwise.
long compare(ipv4_endpoint x) const noexcept;
template <class Inspector>
friend bool inspect(Inspector& f, ipv4_endpoint& x) {
return f.object(x).fields(f.field("address", x.address_),
f.field("port", x.port_));
}
private:
ipv4_address address_; /// The address of this endpoint.
uint16_t port_; /// The port of this endpoint.
};
CAF_CORE_EXPORT std::string to_string(const ipv4_endpoint& ep);
} // namespace caf
namespace std {
template <>
struct hash<caf::ipv4_endpoint> {
size_t operator()(const caf::ipv4_endpoint& ep) const noexcept {
return ep.hash_code();
}
};
} // namespace std
| 26.011905 | 80 | 0.652632 | [
"object"
] |
868ccb484c2e53e89f6a09a4fd455c8da7f81fcb | 1,197 | hpp | C++ | include/bvh.hpp | DestinationStellar/TrivalRayTracing | 881cc654685fae27b90195fd9b917e0ed7d1b4a2 | [
"MIT"
] | null | null | null | include/bvh.hpp | DestinationStellar/TrivalRayTracing | 881cc654685fae27b90195fd9b917e0ed7d1b4a2 | [
"MIT"
] | null | null | null | include/bvh.hpp | DestinationStellar/TrivalRayTracing | 881cc654685fae27b90195fd9b917e0ed7d1b4a2 | [
"MIT"
] | null | null | null | #ifndef BVHH
#define BVHH
#include "object3d.hpp"
#include "group.hpp"
#include <algorithm>
#include <memory>
using std::shared_ptr;
class BVHnode : public Object3D {
public:
BVHnode();
BVHnode(const Group& list, double time0, double time1)
: BVHnode(list.getObjects(), 0, list.getGroupSize(), time0, time1)
{}
BVHnode(
const std::vector<shared_ptr<Object3D>>& src_objects,
size_t start, size_t end, double time0, double time1);
virtual bool intersect(
const Ray& r, Hit& rec, float tmin = 0.0, float tmax = infinity) const override;
virtual bool bounding_box(double time0, double time1, AABB& output_box) const override;
public:
shared_ptr<Object3D> left;
shared_ptr<Object3D> right;
AABB box;
};
inline bool box_compare(const shared_ptr<Object3D> a, const shared_ptr<Object3D> b, int axis) ;
bool box_x_compare (const shared_ptr<Object3D> a, const shared_ptr<Object3D> b) ;
bool box_y_compare (const shared_ptr<Object3D> a, const shared_ptr<Object3D> b) ;
bool box_z_compare (const shared_ptr<Object3D> a, const shared_ptr<Object3D> b) ;
#endif
| 24.428571 | 95 | 0.671679 | [
"vector"
] |
868d39ab3965bda725bfc50267f7c1707d6e93a3 | 43,406 | cpp | C++ | tf2_src/game/client/tf/tf_hud_weaponselection.cpp | d3fc0n6/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | tf2_src/game/client/tf/tf_hud_weaponselection.cpp | Counter2828/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | null | null | null | tf2_src/game/client/tf/tf_hud_weaponselection.cpp | Counter2828/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#include "cbase.h"
#include "weapon_selection.h"
#include "iclientmode.h"
#include "history_resource.h"
#include "hud_macros.h"
#include <KeyValues.h>
#include <vgui/IScheme.h>
#include <vgui/ISurface.h>
#include <vgui/ISystem.h>
#include <vgui_controls/AnimationController.h>
#include <vgui_controls/Panel.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/TextImage.h>
#include <vgui_controls/EditablePanel.h>
#include "vgui/ILocalize.h"
#include <string.h>
#include "baseobject_shared.h"
#include "tf_imagepanel.h"
#include "item_model_panel.h"
#include "c_tf_player.h"
#include "c_tf_weapon_builder.h"
#include "tf_spectatorgui.h"
#include "tf_gamerules.h"
#include "tf_logic_halloween_2014.h"
#include "inputsystem/iinputsystem.h"
#ifndef WIN32
#define _cdecl
#endif
#define SELECTION_TIMEOUT_THRESHOLD 2.5f // Seconds
#define SELECTION_FADEOUT_TIME 3.0f
#define FASTSWITCH_DISPLAY_TIMEOUT 0.5f
#define FASTSWITCH_FADEOUT_TIME 0.5f
ConVar tf_weapon_select_demo_start_delay( "tf_weapon_select_demo_start_delay", "1.0", FCVAR_CLIENTDLL | FCVAR_ARCHIVE, "Delay after spawning to start the weapon bucket demo." );
ConVar tf_weapon_select_demo_time( "tf_weapon_select_demo_time", "0.5", FCVAR_CLIENTDLL | FCVAR_ARCHIVE, "Time to pulse each weapon bucket upon spawning as a new class. 0 to turn off." );
//-----------------------------------------------------------------------------
// Purpose: tf weapon selection hud element
//-----------------------------------------------------------------------------
class CHudWeaponSelection : public CBaseHudWeaponSelection, public vgui::EditablePanel
{
DECLARE_CLASS_SIMPLE( CHudWeaponSelection, vgui::Panel );
public:
CHudWeaponSelection( const char *pElementName );
virtual ~CHudWeaponSelection( void );
virtual bool ShouldDraw();
virtual void OnWeaponPickup( C_BaseCombatWeapon *pWeapon );
virtual void SwitchToLastWeapon( void ) OVERRIDE;
virtual void CycleToNextWeapon( void );
virtual void CycleToPrevWeapon( void );
virtual C_BaseCombatWeapon *GetWeaponInSlot( int iSlot, int iSlotPos );
virtual void SelectWeaponSlot( int iSlot );
virtual C_BaseCombatWeapon *GetSelectedWeapon( void );
virtual void OpenSelection( void );
virtual void HideSelection( void );
virtual void Init();
virtual void LevelInit();
virtual void LevelShutdown( void );
virtual void FireGameEvent( IGameEvent *event );
virtual void Reset(void)
{
CBaseHudWeaponSelection::Reset();
// selection time is a little farther back so we don't show it when we spawn
m_flSelectionTime = gpGlobals->curtime - ( FASTSWITCH_DISPLAY_TIMEOUT + FASTSWITCH_FADEOUT_TIME + 0.1 );
}
virtual void SelectSlot( int iSlot );
void _cdecl UserCmd_Slot11( void );
void _cdecl UserCmd_Slot12( void );
protected:
struct SlotLayout_t
{
float x, y;
float wide, tall;
};
void ComputeSlotLayout( SlotLayout_t *rSlot, int nActiveSlot, int nSelectionMode );
virtual void OnThink();
virtual void PerformLayout( void );
virtual void PostChildPaint();
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
void DrawSelection( C_BaseCombatWeapon *pSelectedWeapon );
virtual bool IsWeaponSelectable()
{
if (IsInSelectionMode())
return true;
return false;
}
private:
C_BaseCombatWeapon *FindNextWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition);
C_BaseCombatWeapon *FindPrevWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition);
void FastWeaponSwitch( int iWeaponSlot );
void PlusTypeFastWeaponSwitch( int iWeaponSlot, bool *pbPlaySwitchSound );
int GetNumVisibleSlots();
bool ShouldDrawInternal();
virtual void SetSelectedWeapon( C_BaseCombatWeapon *pWeapon )
{
m_hSelectedWeapon = pWeapon;
}
virtual void SetSelectedSlot( int slot )
{
m_iSelectedSlot = slot;
}
void DrawString( wchar_t *text, int xpos, int ypos, Color col, bool bCenter = false );
void DrawWeaponTexture( C_TFPlayer *pPlayer, C_BaseCombatWeapon *pWeapon, int xpos, int ypos, float flLargeBoxWide, float flLargeBoxTall );
CPanelAnimationVar( vgui::HFont, m_hNumberFont, "NumberFont", "HudSelectionText" );
CPanelAnimationVar( vgui::HFont, m_hTextFont, "TextFont", "HudSelectionText" );
CPanelAnimationVarAliasType( float, m_flSmallBoxWide, "SmallBoxWide", "32", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flSmallBoxTall, "SmallBoxTall", "21", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flPlusStyleBoxWide, "PlusStyleBoxWide", "120", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flPlusStyleBoxTall, "PlusStyleBoxTall", "84", "proportional_float" );
CPanelAnimationVar( float, m_flPlusStyleExpandPercent, "PlusStyleExpandSelected", "0.3" )
CPanelAnimationVarAliasType( float, m_flLargeBoxWide, "LargeBoxWide", "108", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flLargeBoxTall, "LargeBoxTall", "72", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flBoxGap, "BoxGap", "12", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flRightMargin, "RightMargin", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flSelectionNumberXPos, "SelectionNumberXPos", "4", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flSelectionNumberYPos, "SelectionNumberYPos", "4", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flIconXPos, "IconXPos", "16", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flIconYPos, "IconYPos", "8", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flTextYPos, "TextYPos", "54", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flErrorYPos, "ErrorYPos", "60", "proportional_float" );
CPanelAnimationVar( float, m_flAlphaOverride, "Alpha", "255" );
CPanelAnimationVar( float, m_flSelectionAlphaOverride, "SelectionAlpha", "255" );
CPanelAnimationVar( Color, m_TextColor, "TextColor", "SelectionTextFg" );
CPanelAnimationVar( Color, m_NumberColor, "NumberColor", "SelectionNumberFg" );
CPanelAnimationVar( Color, m_EmptyBoxColor, "EmptyBoxColor", "SelectionEmptyBoxBg" );
CPanelAnimationVar( Color, m_BoxColor, "BoxColor", "SelectionBoxBg" );
CPanelAnimationVar( Color, m_SelectedBoxColor, "SelectedBoxClor", "SelectionSelectedBoxBg" );
CPanelAnimationVar( float, m_flWeaponPickupGrowTime, "SelectionGrowTime", "0.1" );
CPanelAnimationVar( float, m_flTextScan, "TextScan", "1.0" );
CPanelAnimationVar( int, m_iMaxSlots, "MaxSlots", "6" );
CPanelAnimationVar( bool, m_bPlaySelectionSounds, "PlaySelectSounds", "1" );
CTFImagePanel *m_pActiveWeaponBG;
CItemModelPanel *m_pModelPanels[MAX_WEAPON_SLOTS];
float m_flDemoStartTime;
float m_flDemoModeChangeTime;
int m_iDemoModeSlot;
// HUDTYPE_PLUS weapon display
int m_iSelectedBoxPosition; // in HUDTYPE_PLUS, the position within a slot
int m_iSelectedSlot; // in HUDTYPE_PLUS, the slot we're currently moving in
CPanelAnimationVar( float, m_flHorizWeaponSelectOffsetPoint, "WeaponBoxOffset", "0" );
int m_iActiveSlot; // used to store the active slot to refresh the layout when using hud_fastswitch
};
DECLARE_HUDELEMENT( CHudWeaponSelection );
DECLARE_HUD_COMMAND_NAME( CHudWeaponSelection, Slot11, "CHudWeaponSelection");
DECLARE_HUD_COMMAND_NAME( CHudWeaponSelection, Slot12, "CHudWeaponSelection");
HOOK_COMMAND( slot11, Slot11 );
HOOK_COMMAND( slot12, Slot12 );
void CHudWeaponSelection::UserCmd_Slot11(void)
{
SelectSlot( 11 );
}
void CHudWeaponSelection::UserCmd_Slot12(void)
{
SelectSlot( 12 );
}
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CHudWeaponSelection::CHudWeaponSelection( const char *pElementName ) : CBaseHudWeaponSelection( pElementName ), EditablePanel( NULL, "HudWeaponSelection" )
{
vgui::Panel *pParent = g_pClientMode->GetViewport();
SetParent( pParent );
SetPostChildPaintEnabled( true );
m_flDemoStartTime = -1;
m_flDemoModeChangeTime = 0;
m_iDemoModeSlot = -1;
m_iActiveSlot = -1;
ListenForGameEvent( "localplayer_changeclass" );
for ( int i = 0; i < MAX_WEAPON_SLOTS; i++ )
{
m_pModelPanels[i] = new CItemModelPanel( this, VarArgs( "modelpanel%d", i ) );
}
}
CHudWeaponSelection::~CHudWeaponSelection( void )
{
}
//-----------------------------------------------------------------------------
// Purpose: sets up display for showing weapon pickup
//-----------------------------------------------------------------------------
void CHudWeaponSelection::OnWeaponPickup( C_BaseCombatWeapon *pWeapon )
{
// add to pickup history
CHudHistoryResource *pHudHR = GET_HUDELEMENT( CHudHistoryResource );
if ( pHudHR )
{
pHudHR->AddToHistory( pWeapon );
}
}
//-----------------------------------------------------------------------------
// Purpose: updates animation status
//-----------------------------------------------------------------------------
void CHudWeaponSelection::OnThink()
{
float flSelectionTimeout = SELECTION_TIMEOUT_THRESHOLD;
float flSelectionFadeoutTime = SELECTION_FADEOUT_TIME;
if ( hud_fastswitch.GetBool() || (::input->IsSteamControllerActive()) )
{
flSelectionTimeout = FASTSWITCH_DISPLAY_TIMEOUT;
flSelectionFadeoutTime = FASTSWITCH_FADEOUT_TIME;
}
// Time out after awhile of inactivity
if ( ( gpGlobals->curtime - m_flSelectionTime ) > flSelectionTimeout )
{
// close
if ( gpGlobals->curtime - m_flSelectionTime > flSelectionTimeout + flSelectionFadeoutTime )
{
HideSelection();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: returns true if the panel should draw
//-----------------------------------------------------------------------------
bool CHudWeaponSelection::ShouldDraw()
{
bool bShouldDraw = ShouldDrawInternal();
if ( !bShouldDraw && m_pActiveWeaponBG && m_pActiveWeaponBG->IsVisible() )
{
m_pActiveWeaponBG->SetVisible( false );
}
C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( pPlayer && pPlayer->m_Shared.InCond( TF_COND_HALLOWEEN_GHOST_MODE ) )
{
bShouldDraw = false;
}
if ( TFGameRules() && TFGameRules()->ShowMatchSummary() )
{
bShouldDraw = false;
}
if ( CTFMinigameLogic::GetMinigameLogic() && CTFMinigameLogic::GetMinigameLogic()->GetActiveMinigame() )
{
bShouldDraw = false;
}
return bShouldDraw;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CHudWeaponSelection::ShouldDrawInternal()
{
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
{
if ( IsInSelectionMode() )
{
HideSelection();
}
return false;
}
// Make sure the player's allowed to switch weapons
if ( pPlayer->IsAllowedToSwitchWeapons() == false )
return false;
if ( pPlayer->IsAlive() == false )
return false;
// we only show demo mode in hud_fastswitch 0
if ( hud_fastswitch.GetInt() == 0 && !::input->IsSteamControllerActive() && ( m_iDemoModeSlot >= 0 || m_flDemoStartTime > 0 ) )
{
return true;
}
bool bret = CBaseHudWeaponSelection::ShouldDraw();
if ( !bret )
return false;
// draw weapon selection a little longer if in fastswitch so we can see what we've selected
if ( (hud_fastswitch.GetBool() || ::input->IsSteamControllerActive()) && ( gpGlobals->curtime - m_flSelectionTime ) < (FASTSWITCH_DISPLAY_TIMEOUT + FASTSWITCH_FADEOUT_TIME) )
return true;
return ( m_bSelectionVisible ) ? true : false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudWeaponSelection::Init()
{
CHudElement::Init();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudWeaponSelection::LevelInit()
{
CHudElement::LevelInit();
m_iMaxSlots = clamp( m_iMaxSlots, 0, MAX_WEAPON_SLOTS );
for ( int i = 0; i < MAX_WEAPON_SLOTS; i++ )
{
m_pModelPanels[i]->SetVisible( false );
}
InvalidateLayout( false, true );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudWeaponSelection::LevelShutdown( void )
{
CHudElement::LevelShutdown();
// Clear out our weaponry on level change
for ( int i = 0; i < MAX_WEAPON_SLOTS; i++ )
{
if ( m_pModelPanels[i] )
{
m_pModelPanels[i]->SetItem( NULL );
}
}
}
//-------------------------------------------------------------------------
// Purpose: Calculates how many weapons slots need to be displayed
//-------------------------------------------------------------------------
int CHudWeaponSelection::GetNumVisibleSlots()
{
int nCount = 0;
// iterate over all the weapon slots
for ( int i = 0; i < m_iMaxSlots; i++ )
{
if ( GetFirstPos( i ) )
{
nCount++;
}
}
return nCount;
}
//-----------------------------------------------------------------------------
// Purpose: Figure out where to put the item model panels for this weapon
// selection slot layout
//-----------------------------------------------------------------------------
void CHudWeaponSelection::ComputeSlotLayout( SlotLayout_t *rSlot, int nActiveSlot, int nSelectionMode )
{
int nNumSlots = GetNumVisibleSlots();
if ( nNumSlots <= 0 )
return;
switch( nSelectionMode )
{
case HUDTYPE_CAROUSEL:
case HUDTYPE_BUCKETS:
case HUDTYPE_FASTSWITCH:
{
// calculate where to start drawing
int nTotalHeight = ( nNumSlots - 1 ) * ( m_flSmallBoxTall + m_flBoxGap ) + m_flLargeBoxTall;
int xStartPos = GetWide() - m_flBoxGap - m_flRightMargin;
int ypos = ( GetTall() - nTotalHeight ) / 2;
// iterate over all the weapon slots
for ( int i = 0; i < m_iMaxSlots; i++ )
{
if ( i == nActiveSlot )
{
rSlot[i].wide = m_flLargeBoxWide;
rSlot[i].tall = m_flLargeBoxTall;
}
else
{
rSlot[i].wide = m_flSmallBoxWide;
rSlot[i].tall = m_flSmallBoxTall;
}
rSlot[i].x = xStartPos - ( rSlot[i].wide + m_flBoxGap );
rSlot[i].y = ypos;
ypos += ( rSlot[i].tall + m_flBoxGap );
}
}
break;
case HUDTYPE_PLUS:
{
// bucket style
int screenCenterX = GetWide() / 2;
int screenCenterY = GetTall() / 2; // Height isn't quite screen height, so adjust for center alignement
// Modifiers for the four directions. Used to change the x and y offsets
// of each box based on which bucket we're drawing. Bucket directions are
// 0 = UP, 1 = RIGHT, 2 = DOWN, 3 = LEFT
int xModifiers[] = { 0, 1, 0, -1, -1, 1 };
int yModifiers[] = { -1, 0, 1, 0, 1, 1 };
int boxWide = m_flPlusStyleBoxWide;
int boxTall = m_flPlusStyleBoxTall;
int boxWideSelected = m_flPlusStyleBoxWide * ( 1.f + m_flPlusStyleExpandPercent );
int boxTallSelected = m_flPlusStyleBoxTall * ( 1.f + m_flPlusStyleExpandPercent );
// Draw the four buckets
for ( int i = 0; i < m_iMaxSlots; ++i )
{
if( i == nActiveSlot )
{
rSlot[i].wide = boxWideSelected;
rSlot[i].tall = boxTallSelected;
}
else
{
rSlot[i].wide = boxWide;
rSlot[i].tall = boxTall;
}
// Set the top left corner so the first box would be centered in the screen.
int xPos = screenCenterX -( rSlot[i].wide / 2 );
int yPos = screenCenterY -( rSlot[i].tall / 2 );
// Offset the box position
rSlot[ i ].x = xPos + ( rSlot[i].wide + 5 ) * xModifiers[ i ];
rSlot[ i ].y = yPos + ( rSlot[i].tall + 5 ) * yModifiers[ i ];
}
}
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudWeaponSelection::PerformLayout( void )
{
BaseClass::PerformLayout();
C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pPlayer )
return;
int nNumSlots = GetNumVisibleSlots();
if ( nNumSlots <= 0 )
return;
// find and display our current selection
C_BaseCombatWeapon *pSelectedWeapon = NULL;
int fastswitch = hud_fastswitch.GetInt();
if ( ::input->IsSteamControllerActive() )
{
fastswitch = HUDTYPE_FASTSWITCH;
}
switch ( fastswitch )
{
case HUDTYPE_FASTSWITCH:
pSelectedWeapon = pPlayer->GetActiveWeapon();
break;
default:
pSelectedWeapon = GetSelectedWeapon();
break;
}
if ( !pSelectedWeapon )
return;
// calculate where to start drawing
int iActiveSlot = (pSelectedWeapon ? pSelectedWeapon->GetSlot() : -1);
SlotLayout_t rSlot[ MAX_WEAPON_SLOTS ];
ComputeSlotLayout( rSlot, iActiveSlot, fastswitch );
// iterate over all the weapon slots
for ( int i = 0; i < m_iMaxSlots; i++ )
{
m_pModelPanels[i]->SetVisible( false );
if ( i == iActiveSlot )
{
for ( int slotpos = 0; slotpos < MAX_WEAPON_POSITIONS; slotpos++ )
{
C_BaseCombatWeapon *pWeapon = GetWeaponInSlot(i, slotpos);
if ( !pWeapon )
continue;
if ( !pWeapon->VisibleInWeaponSelection() )
continue;
m_pModelPanels[i]->SetItem( pWeapon->GetAttributeContainer()->GetItem() );
m_pModelPanels[i]->SetSize( rSlot[i].wide, rSlot[ i ].tall );
vgui::IScheme *pScheme = vgui::scheme()->GetIScheme( GetScheme() );
if ( pPlayer->GetTeamNumber() == TF_TEAM_BLUE )
{
m_pModelPanels[i]->SetBorder( pScheme->GetBorder("TFFatLineBorderBlueBG") );
}
else
{
m_pModelPanels[i]->SetBorder( pScheme->GetBorder("TFFatLineBorderRedBG") );
}
m_pModelPanels[i]->SetPos( rSlot[i].x, rSlot[ i ].y );
m_pModelPanels[i]->SetVisible( true );
}
}
else
{
// check to see if there is a weapons in this bucket
if ( GetFirstPos( i ) )
{
C_BaseCombatWeapon *pWeapon = GetFirstPos( i );
if ( !pWeapon )
continue;
m_pModelPanels[i]->SetItem( pWeapon->GetAttributeContainer()->GetItem() );
m_pModelPanels[i]->SetSize( rSlot[i].wide, rSlot[ i ].tall );
vgui::IScheme *pScheme = vgui::scheme()->GetIScheme( GetScheme() );
m_pModelPanels[i]->SetBorder( pScheme->GetBorder("TFFatLineBorder") );
m_pModelPanels[i]->SetVisible( true );
m_pModelPanels[i]->SetPos( rSlot[i].x, rSlot[ i ].y );
}
}
}
}
//-------------------------------------------------------------------------
// Purpose: draws the selection area
//-------------------------------------------------------------------------
void CHudWeaponSelection::PostChildPaint()
{
C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pPlayer )
return;
int fastswitch = hud_fastswitch.GetInt();
if ( ::input->IsSteamControllerActive() )
{
fastswitch = HUDTYPE_FASTSWITCH;
}
if ( fastswitch == 0 )
{
// See if we should start the bucket demo
if ( m_flDemoStartTime > 0 && m_flDemoStartTime < gpGlobals->curtime )
{
float flDemoTime = tf_weapon_select_demo_time.GetFloat();
if ( flDemoTime > 0 )
{
m_iDemoModeSlot = 0;
m_flDemoModeChangeTime = gpGlobals->curtime + flDemoTime;
gHUD.LockRenderGroup( gHUD.LookupRenderGroupIndexByName( "weapon_selection" ) );
}
m_flDemoStartTime = -1;
m_iSelectedSlot = m_iDemoModeSlot;
InvalidateLayout();
}
// scroll through the slots for demo mode
if ( m_iDemoModeSlot >= 0 && m_flDemoModeChangeTime < gpGlobals->curtime )
{
// Keep iterating until we find a slot that has a weapon in it
while ( !GetFirstPos( ++m_iDemoModeSlot ) && m_iDemoModeSlot < m_iMaxSlots )
{
// blank
}
m_flDemoModeChangeTime = gpGlobals->curtime + tf_weapon_select_demo_time.GetFloat();
InvalidateLayout();
}
if ( m_iDemoModeSlot >= m_iMaxSlots )
{
m_iDemoModeSlot = -1;
gHUD.UnlockRenderGroup( gHUD.LookupRenderGroupIndexByName( "weapon_selection" ) );
}
}
// find and display our current selection
C_BaseCombatWeapon *pSelectedWeapon = NULL;
switch ( fastswitch )
{
case HUDTYPE_FASTSWITCH:
pSelectedWeapon = pPlayer->GetActiveWeapon();
break;
default:
pSelectedWeapon = GetSelectedWeapon();
break;
}
if ( !pSelectedWeapon )
return;
if ( fastswitch == 0 )
{
if ( m_iDemoModeSlot > -1 )
{
pSelectedWeapon = GetWeaponInSlot( m_iDemoModeSlot, 0 );
m_iSelectedSlot = m_iDemoModeSlot;
m_iSelectedBoxPosition = 0;
}
}
if ( m_pActiveWeaponBG )
{
m_pActiveWeaponBG->SetVisible( fastswitch != HUDTYPE_PLUS && pSelectedWeapon != NULL );
}
int nNumSlots = GetNumVisibleSlots();
if ( nNumSlots <= 0 )
return;
DrawSelection( pSelectedWeapon );
}
//-----------------------------------------------------------------------------
// Purpose: Draws the vertical style weapon selection buckets, for PC/mousewheel controls
//-----------------------------------------------------------------------------
void CHudWeaponSelection::DrawSelection( C_BaseCombatWeapon *pSelectedWeapon )
{
// if we're not supposed to draw the selection, the don't draw the selection
if( !m_bSelectionVisible )
return;
C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pPlayer )
return;
int nNumSlots = GetNumVisibleSlots();
if ( nNumSlots <= 0 )
return;
// calculate where to start drawing
int iActiveSlot = (pSelectedWeapon ? pSelectedWeapon->GetSlot() : -1);
int nFastswitchMode = hud_fastswitch.GetInt();
if ( ::input->IsSteamControllerActive() )
{
nFastswitchMode = HUDTYPE_FASTSWITCH;
}
if ( nFastswitchMode == HUDTYPE_FASTSWITCH )
{
if ( m_iActiveSlot != iActiveSlot )
{
m_iActiveSlot = iActiveSlot;
InvalidateLayout( true );
}
}
// draw the bucket set
// iterate over all the weapon slots
for ( int i = 0; i < m_iMaxSlots; i++ )
{
int xpos, ypos;
m_pModelPanels[i]->GetPos( xpos, ypos );
int wide, tall;
m_pModelPanels[i]->GetSize( wide, tall );
if ( i == iActiveSlot )
{
bool bFirstItem = true;
for ( int slotpos = 0; slotpos < MAX_WEAPON_POSITIONS; slotpos++ )
{
C_BaseCombatWeapon *pWeapon = GetWeaponInSlot(i, slotpos);
if ( !pWeapon )
continue;
if ( !pWeapon->VisibleInWeaponSelection() )
continue;
if ( !pWeapon->CanBeSelected() )
{
int msgX = xpos + ( m_flLargeBoxWide * 0.5 );
int msgY = ypos + (int)m_flErrorYPos;
Color ammoColor = Color( 255, 0, 0, 255 );
wchar_t *pText = g_pVGuiLocalize->Find( "#TF_OUT_OF_AMMO" );
DrawString( pText, msgX, msgY, ammoColor, true );
}
if ( pWeapon == pSelectedWeapon || ( m_iDemoModeSlot == i ) )
{
// draw the number
int shortcut = bFirstItem ? i + 1 : -1;
if ( IsPC() && shortcut >= 0 && nFastswitchMode != HUDTYPE_PLUS )
{
Color numberColor = m_NumberColor;
numberColor[3] *= m_flSelectionAlphaOverride / 255.0f;
surface()->DrawSetTextColor(numberColor);
surface()->DrawSetTextFont(m_hNumberFont);
wchar_t wch = '0' + shortcut;
surface()->DrawSetTextPos( xpos + wide - XRES(5) - m_flSelectionNumberXPos, ypos + YRES(5) + m_flSelectionNumberYPos );
surface()->DrawUnicodeChar(wch);
}
}
bFirstItem = false;
}
}
else
{
// check to see if there is a weapons in this bucket
if ( GetFirstPos( i ) )
{
C_BaseCombatWeapon *pWeapon = GetFirstPos( i );
if ( !pWeapon )
continue;
// draw the number
if ( IsPC() && nFastswitchMode != HUDTYPE_PLUS )
{
int x = xpos + XRES(5);
int y = ypos + YRES(5);
Color numberColor = m_NumberColor;
numberColor[3] *= m_flAlphaOverride / 255.0f;
surface()->DrawSetTextColor(numberColor);
surface()->DrawSetTextFont(m_hNumberFont);
wchar_t wch = '0' + i + 1;
surface()->DrawSetTextPos(x + m_flSmallBoxWide - XRES(10) - m_flSelectionNumberXPos, y + m_flSelectionNumberYPos);
surface()->DrawUnicodeChar(wch);
}
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudWeaponSelection::DrawWeaponTexture( C_TFPlayer *pPlayer, C_BaseCombatWeapon *pWeapon, int xpos, int ypos, float flLargeBoxWide, float flLargeBoxTall )
{
// draw icon
const CHudTexture *pTexture = pWeapon->GetSpriteInactive(); // red team
if ( pPlayer )
{
if ( pPlayer->GetTeamNumber() == TF_TEAM_BLUE )
{
pTexture = pWeapon->GetSpriteActive();
}
}
if ( pTexture )
{
Color col( 255, 255, 255, 255 );
pTexture->DrawSelf( xpos, ypos, flLargeBoxWide, flLargeBoxTall, col );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudWeaponSelection::DrawString( wchar_t *text, int xpos, int ypos, Color col, bool bCenter )
{
surface()->DrawSetTextColor( col );
surface()->DrawSetTextFont( m_hTextFont );
// count the position
int slen = 0, charCount = 0, maxslen = 0;
{
for (wchar_t *pch = text; *pch != 0; pch++)
{
if (*pch == '\n')
{
// newline character, drop to the next line
if (slen > maxslen)
{
maxslen = slen;
}
slen = 0;
}
else if (*pch == '\r')
{
// do nothing
}
else
{
slen += surface()->GetCharacterWidth( m_hTextFont, *pch );
charCount++;
}
}
}
if (slen > maxslen)
{
maxslen = slen;
}
int x = xpos;
if ( bCenter )
{
x = xpos - slen * 0.5;
}
surface()->DrawSetTextPos( x, ypos );
// adjust the charCount by the scan amount
charCount *= m_flTextScan;
for (wchar_t *pch = text; charCount > 0; pch++)
{
if (*pch == '\n')
{
// newline character, move to the next line
surface()->DrawSetTextPos( x + ((m_flLargeBoxWide - slen) / 2), ypos + (surface()->GetFontTall(m_hTextFont) * 1.1f));
}
else if (*pch == '\r')
{
// do nothing
}
else
{
surface()->DrawUnicodeChar(*pch);
charCount--;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: hud scheme settings
//-----------------------------------------------------------------------------
void CHudWeaponSelection::ApplySchemeSettings(vgui::IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
SetPaintBackgroundEnabled(false);
// set our size
int screenWide, screenTall;
int x, y;
GetPos(x, y);
GetHudSize(screenWide, screenTall);
SetBounds(0, 0, screenWide, screenTall);
// load control settings...
LoadControlSettings( "resource/UI/HudWeaponSelection.res" );
m_pActiveWeaponBG = dynamic_cast<CTFImagePanel*>( FindChildByName("ActiveWeapon") );
if ( m_pActiveWeaponBG )
{
m_pActiveWeaponBG->SetVisible( false );
}
}
//-----------------------------------------------------------------------------
// Purpose: Opens weapon selection control
//-----------------------------------------------------------------------------
void CHudWeaponSelection::OpenSelection( void )
{
Assert(!IsInSelectionMode());
InvalidateLayout();
CBaseHudWeaponSelection::OpenSelection();
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("OpenWeaponSelectionMenu");
m_iSelectedBoxPosition = 0;
m_iSelectedSlot = -1;
}
//-----------------------------------------------------------------------------
// Purpose: Closes weapon selection control immediately
//-----------------------------------------------------------------------------
void CHudWeaponSelection::HideSelection( void )
{
for ( int i = 0; i < MAX_WEAPON_SLOTS; i++ )
{
if ( m_pModelPanels[i] )
{
m_pModelPanels[i]->SetVisible( false );
}
}
m_flSelectionTime = 0;
CBaseHudWeaponSelection::HideSelection();
g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("CloseWeaponSelectionMenu");
}
//-----------------------------------------------------------------------------
// Purpose: Returns the next available weapon item in the weapon selection
//-----------------------------------------------------------------------------
C_BaseCombatWeapon *CHudWeaponSelection::FindNextWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition)
{
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return NULL;
C_BaseCombatWeapon *pNextWeapon = NULL;
// search all the weapons looking for the closest next
int iLowestNextSlot = MAX_WEAPON_SLOTS;
int iLowestNextPosition = MAX_WEAPON_POSITIONS;
for ( int i = 0; i < MAX_WEAPONS; i++ )
{
C_BaseCombatWeapon *pWeapon = pPlayer->GetWeapon(i);
if ( !pWeapon )
continue;
if ( pWeapon->VisibleInWeaponSelection() )
{
int weaponSlot = pWeapon->GetSlot(), weaponPosition = pWeapon->GetPosition();
// see if this weapon is further ahead in the selection list
if ( weaponSlot > iCurrentSlot || (weaponSlot == iCurrentSlot && weaponPosition > iCurrentPosition) )
{
// see if this weapon is closer than the current lowest
if ( weaponSlot < iLowestNextSlot || (weaponSlot == iLowestNextSlot && weaponPosition < iLowestNextPosition) )
{
iLowestNextSlot = weaponSlot;
iLowestNextPosition = weaponPosition;
pNextWeapon = pWeapon;
}
}
}
}
return pNextWeapon;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the prior available weapon item in the weapon selection
//-----------------------------------------------------------------------------
C_BaseCombatWeapon *CHudWeaponSelection::FindPrevWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition)
{
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return NULL;
C_BaseCombatWeapon *pPrevWeapon = NULL;
// search all the weapons looking for the closest next
int iLowestPrevSlot = -1;
int iLowestPrevPosition = -1;
for ( int i = 0; i < MAX_WEAPONS; i++ )
{
C_BaseCombatWeapon *pWeapon = pPlayer->GetWeapon(i);
if ( !pWeapon )
continue;
if ( pWeapon->VisibleInWeaponSelection() )
{
int weaponSlot = pWeapon->GetSlot(), weaponPosition = pWeapon->GetPosition();
// see if this weapon is further ahead in the selection list
if ( weaponSlot < iCurrentSlot || (weaponSlot == iCurrentSlot && weaponPosition < iCurrentPosition) )
{
// see if this weapon is closer than the current lowest
if ( weaponSlot > iLowestPrevSlot || (weaponSlot == iLowestPrevSlot && weaponPosition > iLowestPrevPosition) )
{
iLowestPrevSlot = weaponSlot;
iLowestPrevPosition = weaponPosition;
pPrevWeapon = pWeapon;
}
}
}
}
return pPrevWeapon;
}
//-----------------------------------------------------------------------------
// Purpose: Moves the selection to the next item in the menu
//-----------------------------------------------------------------------------
void CHudWeaponSelection::CycleToNextWeapon( void )
{
// Get the local player.
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
if ( pPlayer->IsAlive() == false )
return;
// PASSTIME don't CycleToNextWeapon if it's not allowed
if ( !pPlayer->IsAllowedToSwitchWeapons() )
return;
C_BaseCombatWeapon *pNextWeapon = NULL;
if ( IsInSelectionMode() )
{
// find the next selection spot
C_BaseCombatWeapon *pWeapon = GetSelectedWeapon();
if ( !pWeapon )
return;
pNextWeapon = FindNextWeaponInWeaponSelection( pWeapon->GetSlot(), pWeapon->GetPosition() );
}
else
{
// open selection at the current place
pNextWeapon = pPlayer->GetActiveWeapon();
if ( pNextWeapon )
{
pNextWeapon = FindNextWeaponInWeaponSelection( pNextWeapon->GetSlot(), pNextWeapon->GetPosition() );
}
}
if ( !pNextWeapon )
{
// wrap around back to start
pNextWeapon = FindNextWeaponInWeaponSelection(-1, -1);
}
if ( pNextWeapon )
{
SetSelectedWeapon( pNextWeapon );
if ( !IsInSelectionMode() )
{
OpenSelection();
}
InvalidateLayout();
// cancel demo mode
m_iDemoModeSlot = -1;
m_flDemoStartTime = -1;
// Play the "cycle to next weapon" sound
if( m_bPlaySelectionSounds )
pPlayer->EmitSound( "Player.WeaponSelectionMoveSlot" );
}
}
//-----------------------------------------------------------------------------
// Purpose: Moves the selection to the previous item in the menu
//-----------------------------------------------------------------------------
void CHudWeaponSelection::CycleToPrevWeapon( void )
{
// Get the local player.
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
if ( pPlayer->IsAlive() == false )
return;
// PASSTIME don't CycleToNextWeapon if it's not allowed
if ( !pPlayer->IsAllowedToSwitchWeapons() )
return;
C_BaseCombatWeapon *pNextWeapon = NULL;
if ( IsInSelectionMode() )
{
// find the next selection spot
C_BaseCombatWeapon *pWeapon = GetSelectedWeapon();
if ( !pWeapon )
return;
pNextWeapon = FindPrevWeaponInWeaponSelection( pWeapon->GetSlot(), pWeapon->GetPosition() );
}
else
{
// open selection at the current place
pNextWeapon = pPlayer->GetActiveWeapon();
if ( pNextWeapon )
{
pNextWeapon = FindPrevWeaponInWeaponSelection( pNextWeapon->GetSlot(), pNextWeapon->GetPosition() );
}
}
if ( !pNextWeapon )
{
// wrap around back to end of weapon list
pNextWeapon = FindPrevWeaponInWeaponSelection(MAX_WEAPON_SLOTS, MAX_WEAPON_POSITIONS);
}
if ( pNextWeapon )
{
SetSelectedWeapon( pNextWeapon );
if ( !IsInSelectionMode() )
{
OpenSelection();
}
InvalidateLayout();
// cancel demo mode
m_iDemoModeSlot = -1;
m_flDemoStartTime = -1;
// Play the "cycle to next weapon" sound
if( m_bPlaySelectionSounds )
pPlayer->EmitSound( "Player.WeaponSelectionMoveSlot" );
}
}
//-----------------------------------------------------------------------------
// Purpose: returns the weapon in the specified slot
//-----------------------------------------------------------------------------
C_BaseCombatWeapon *CHudWeaponSelection::GetWeaponInSlot( int iSlot, int iSlotPos )
{
C_BasePlayer *player = C_BasePlayer::GetLocalPlayer();
if ( !player )
return NULL;
for ( int i = 0; i < MAX_WEAPONS; i++ )
{
C_BaseCombatWeapon *pWeapon = player->GetWeapon(i);
if ( pWeapon == NULL )
continue;
if ( pWeapon->GetSlot() == iSlot && pWeapon->GetPosition() == iSlotPos )
return pWeapon;
}
return NULL;
}
C_BaseCombatWeapon *CHudWeaponSelection::GetSelectedWeapon( void )
{
if ( hud_fastswitch.GetInt() == 0 && !::input->IsSteamControllerActive() && m_iDemoModeSlot >= 0 )
{
C_BaseCombatWeapon *pWeapon = GetFirstPos( m_iDemoModeSlot );
return pWeapon;
}
else
{
return m_hSelectedWeapon;
}
}
void CHudWeaponSelection::FireGameEvent( IGameEvent *event )
{
const char * type = event->GetName();
if ( Q_strcmp(type, "localplayer_changeclass") == 0 )
{
for ( int i = 0; i < MAX_WEAPON_SLOTS; i++ )
{
if ( m_pModelPanels[i] )
{
m_pModelPanels[i]->SetVisible( false );
}
}
int nUpdateType = event->GetInt( "updateType" );
bool bIsCreationUpdate = ( nUpdateType == DATA_UPDATE_CREATED );
// Don't demo selection in minmode
ConVarRef cl_hud_minmode( "cl_hud_minmode", true );
if ( !cl_hud_minmode.IsValid() || cl_hud_minmode.GetBool() == false )
{
if ( !bIsCreationUpdate )
{
m_flDemoStartTime = gpGlobals->curtime + tf_weapon_select_demo_start_delay.GetFloat();
}
}
}
else
{
CHudElement::FireGameEvent( event );
}
}
//-----------------------------------------------------------------------------
// Purpose: Opens the next weapon in the slot
//-----------------------------------------------------------------------------
void CHudWeaponSelection::FastWeaponSwitch( int iWeaponSlot )
{
// get the slot the player's weapon is in
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
// see where we should start selection
int iPosition = -1;
C_BaseCombatWeapon *pActiveWeapon = pPlayer->GetActiveWeapon();
if ( pActiveWeapon && pActiveWeapon->GetSlot() == iWeaponSlot )
{
// start after this weapon
iPosition = pActiveWeapon->GetPosition();
}
C_BaseCombatWeapon *pNextWeapon = NULL;
// search for the weapon after the current one
pNextWeapon = FindNextWeaponInWeaponSelection(iWeaponSlot, iPosition);
// make sure it's in the same bucket
if ( !pNextWeapon || pNextWeapon->GetSlot() != iWeaponSlot )
{
// just look for any weapon in this slot
pNextWeapon = FindNextWeaponInWeaponSelection(iWeaponSlot, -1);
}
// see if we found a weapon that's different from the current and in the selected slot
if ( pNextWeapon && pNextWeapon != pActiveWeapon && pNextWeapon->GetSlot() == iWeaponSlot )
{
// select the new weapon
::input->MakeWeaponSelection( pNextWeapon );
}
else if ( pNextWeapon != pActiveWeapon )
{
// error sound
pPlayer->EmitSound( "Player.DenyWeaponSelection" );
}
// kill any fastswitch display
m_flSelectionTime = 0.0f;
}
//-----------------------------------------------------------------------------
// Purpose: Opens the next weapon in the slot
//-----------------------------------------------------------------------------
void CHudWeaponSelection::PlusTypeFastWeaponSwitch( int iWeaponSlot, bool *pbPlaySwitchSound )
{
// get the slot the player's weapon is in
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
int newSlot = m_iSelectedSlot;
// Changing slot number does not necessarily mean we need to change the slot - the player could be
// scrolling through the same slot but in the opposite direction. Slot pairs are 0,2 and 1,3 - so
// compare the 0 bits to see if we're within a pair. Otherwise, reset the box to the zero position.
if ( -1 == m_iSelectedSlot || ( ( m_iSelectedSlot ^ iWeaponSlot ) & 1 ) )
{
// Changing vertical/horizontal direction. Reset the selected box position to zero.
m_iSelectedBoxPosition = 0;
m_iSelectedSlot = iWeaponSlot;
}
else
{
// Still in the same horizontal/vertical direction. Determine which way we're moving in the slot.
int increment = 1;
if ( m_iSelectedSlot != iWeaponSlot )
{
// Decrementing within the slot. If we're at the zero position in this slot,
// jump to the zero position of the opposite slot. This also counts as our increment.
increment = -1;
if ( 0 == m_iSelectedBoxPosition )
{
newSlot = ( m_iSelectedSlot + 2 ) % 4;
increment = 0;
}
}
// Find out of the box position is at the end of the slot
int lastSlotPos = -1;
for ( int slotPos = 0; slotPos < MAX_WEAPON_POSITIONS; ++slotPos )
{
C_BaseCombatWeapon *pWeapon = GetWeaponInSlot( newSlot, slotPos );
if ( pWeapon )
{
lastSlotPos = slotPos;
}
}
// Increment/Decrement the selected box position
if ( m_iSelectedBoxPosition + increment <= lastSlotPos )
{
m_iSelectedBoxPosition += increment;
m_iSelectedSlot = newSlot;
}
else
{
// error sound
pPlayer->EmitSound( "Player.DenyWeaponSelection" );
*pbPlaySwitchSound = false;
return;
}
}
// Select the weapon in this position
bool bWeaponSelected = false;
C_BaseCombatWeapon *pActiveWeapon = pPlayer->GetActiveWeapon();
C_BaseCombatWeapon *pWeapon = GetWeaponInSlot( m_iSelectedSlot, m_iSelectedBoxPosition );
if ( pWeapon && CanBeSelectedInHUD( pWeapon ) )
{
if ( pWeapon != pActiveWeapon )
{
// Select the new weapon
::input->MakeWeaponSelection( pWeapon );
SetSelectedWeapon( pWeapon );
bWeaponSelected = true;
}
}
if ( !bWeaponSelected )
{
// Still need to set this to make hud display appear
SetSelectedWeapon( pPlayer->GetActiveWeapon() );
}
}
//-----------------------------------------------------------------------------
// Purpose: Moves selection to the specified slot
//-----------------------------------------------------------------------------
void CHudWeaponSelection::SelectWeaponSlot( int iSlot )
{
// iSlot is one higher than it should be, since it's the number key, not the 0-based index into the weapons
--iSlot;
// Get the local player.
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return;
// Don't try and read past our possible number of slots
if ( iSlot >= MAX_WEAPON_SLOTS )
return;
// Make sure the player's allowed to switch weapons
if ( pPlayer->IsAllowedToSwitchWeapons() == false )
return;
bool bPlaySwitchSound = true;
int nFastswitchMode = hud_fastswitch.GetInt();
if ( ::input->IsSteamControllerActive() )
{
nFastswitchMode = HUDTYPE_FASTSWITCH;
}
switch( nFastswitchMode )
{
case HUDTYPE_FASTSWITCH:
{
FastWeaponSwitch( iSlot );
return;
}
case HUDTYPE_PLUS:
PlusTypeFastWeaponSwitch( iSlot, &bPlaySwitchSound );
// ------------------------------------------------------
// FALLTHROUGH! Plus and buckets both use the item model
// panels so fix them up in both cases.
// ------------------------------------------------------
case HUDTYPE_BUCKETS:
{
int slotPos = 0;
C_BaseCombatWeapon *pActiveWeapon = GetSelectedWeapon();
// start later in the list
if ( IsInSelectionMode() && pActiveWeapon && pActiveWeapon->GetSlot() == iSlot )
{
slotPos = pActiveWeapon->GetPosition() + 1;
}
// find the weapon in this slot
pActiveWeapon = GetNextActivePos( iSlot, slotPos );
if ( !pActiveWeapon )
{
pActiveWeapon = GetNextActivePos( iSlot, 0 );
}
if ( pActiveWeapon != NULL )
{
if ( !IsInSelectionMode() )
{
// open the weapon selection
OpenSelection();
}
InvalidateLayout();
// Mark the change
SetSelectedWeapon( pActiveWeapon );
m_iDemoModeSlot = -1;
m_flDemoStartTime = -1;
}
}
break;
default:
break;
}
if( m_bPlaySelectionSounds && bPlaySwitchSound )
pPlayer->EmitSound( "Player.WeaponSelectionMoveSlot" );
}
//-----------------------------------------------------------------------------
// Purpose: Menu Selection Code
//-----------------------------------------------------------------------------
void CHudWeaponSelection::SelectSlot( int iSlot )
{
// A menu may be overriding weapon selection commands
if ( HandleHudMenuInput( iSlot ) )
{
return;
}
// If we're in observer mode, see if the spectator GUI wants to use it
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( pPlayer && pPlayer->IsObserver() )
{
CTFSpectatorGUI *pPanel = (CTFSpectatorGUI*)gViewPortInterface->FindPanelByName( PANEL_SPECGUI );
if ( pPanel )
{
pPanel->SelectSpec( iSlot );
}
return;
}
// If we're not allowed to draw, ignore weapon selections
if ( !CHudElement::ShouldDraw() )
{
return;
}
// iSlot is one higher than it should be, since it's the number key, not the 0-based index into the weapons
if ( !IsInSelectionMode() && ( iSlot - 1 >= MAX_WEAPON_SLOTS ) )
{
OpenSelection();
}
UpdateSelectionTime();
SelectWeaponSlot( iSlot );
}
//-----------------------------------------------------------------------------
// Purpose: Menu Selection Code
//-----------------------------------------------------------------------------
void CHudWeaponSelection::SwitchToLastWeapon()
{
C_TFPlayer *pTFPlayer = ToTFPlayer( C_BasePlayer::GetLocalPlayer() );
if ( !pTFPlayer )
return;
if (TFGameRules() && TFGameRules()->IsPasstimeMode() && pTFPlayer->m_Shared.HasPasstimeBall() )
return;
CBaseHudWeaponSelection::SwitchToLastWeapon();
}
| 28.975968 | 187 | 0.62542 | [
"model"
] |
8697bb5dd1304899fa83e3ca429088dda9110b2e | 7,251 | cc | C++ | src/idt/targets/typescript_cpp_v8/core/compiler_environment.cc | aabtop/reify | ddc7ce0250ecba78755eaa4793ad8135e4009131 | [
"MIT"
] | 6 | 2020-05-19T21:35:10.000Z | 2021-06-22T15:49:04.000Z | src/idt/targets/typescript_cpp_v8/core/compiler_environment.cc | aabtop/reify | ddc7ce0250ecba78755eaa4793ad8135e4009131 | [
"MIT"
] | 26 | 2020-05-24T20:56:39.000Z | 2021-09-04T04:46:30.000Z | src/idt/targets/typescript_cpp_v8/core/compiler_environment.cc | aabtop/reify | ddc7ce0250ecba78755eaa4793ad8135e4009131 | [
"MIT"
] | null | null | null | #include <fmt/format.h>
#include <fstream>
#include <iostream>
#include <string_view>
#include "compiled_module_impl.h"
#include "project.h"
#include "public_include/reify/typescript_cpp_v8/typescript_cpp_v8.h"
#include "typescript_compiler.h"
namespace reify {
namespace typescript_cpp_v8 {
class CompilerEnvironment::Impl {
public:
Impl(VirtualFilesystem* virtual_filesystem,
const std::vector<InputModule>* initial_modules,
SnapshotOptions snapshot_cache_options)
: initial_modules_(initial_modules),
tsc_(virtual_filesystem,
snapshot_cache_options == SnapshotOptions::kNoSnapshot
? TypeScriptCompiler::SnapshotOptions::kNoSnapshot
: TypeScriptCompiler::SnapshotOptions::kCacheSnapshot) {}
enum class GenerateDeclarationFiles { Yes, No };
std::variant<TypeScriptCompiler::TranspileResults, TypeScriptCompiler::Error>
Compile(const VirtualFilesystem::AbsolutePath& path,
GenerateDeclarationFiles generate_declaration_files);
private:
const std::vector<InputModule>* initial_modules_;
TypeScriptCompiler tsc_;
};
CompilerEnvironment::CompilerEnvironment(
VirtualFilesystem* virtual_filesystem,
const std::vector<InputModule>* initial_modules,
SnapshotOptions snapshot_options)
: impl_(new CompilerEnvironment::Impl(virtual_filesystem, initial_modules,
snapshot_options)) {}
CompilerEnvironment::~CompilerEnvironment() {}
CompilerEnvironment::CompileResults CompilerEnvironment::Compile(
const VirtualFilesystem::AbsolutePath& path) {
auto transpile_results_or_error =
impl_->Compile(path, Impl::GenerateDeclarationFiles::No);
if (auto error =
std::get_if<TypeScriptCompiler::Error>(&transpile_results_or_error)) {
return *error;
}
return std::shared_ptr<CompiledModule>(
new CompiledModule(std::make_unique<CompiledModule::Impl>(
std::move(std::get<TypeScriptCompiler::TranspileResults>(
transpile_results_or_error)))));
}
std::variant<TypeScriptCompiler::TranspileResults, TypeScriptCompiler::Error>
CompilerEnvironment::Impl::Compile(
const VirtualFilesystem::AbsolutePath& path,
GenerateDeclarationFiles generate_declaration_files) {
return tsc_.TranspileToJavaScript(
path, {*initial_modules_,
(generate_declaration_files == GenerateDeclarationFiles::Yes)});
}
namespace {
bool WriteToFile(const std::filesystem::path& path, std::string_view content) {
std::ofstream fout(path);
if (fout.fail()) {
std::cerr << "Error opening " << path << " for writing." << std::endl;
return false;
}
fout.write(content.data(), content.length());
if (fout.fail()) {
std::cerr << "Error writing data to " << path << std::endl;
return false;
}
return true;
}
const char* TSCONFIG_JSON_CONTENT_TEMPLATE = R"json(
{{
"compilerOptions": {{
"target": "ES2015",
"module": "ES2015",
"lib": [
"ES5",
"ES2015.Core",
"ES2015.Symbol",
"ES2015.Iterable",
"ES2015.Generator",
"ES2019.Array",
"ES2019.Object",
"ES2019.String",
"ES2019.Symbol",
],
"strict": true,
"baseUrl": ".",
"paths": {{
"{module_name}": [
"{decls_subdir}/{module_name}"
],
}},
}},
}}
)json";
} // namespace
CompilerEnvironment::CompilerEnvironment(CompilerEnvironment&& x)
: impl_(std::move(x.impl_)) {}
std::optional<utils::Error> CompilerEnvironment::CreateWorkspaceDirectory(
const std::filesystem::path& out_dir_path,
const std::vector<InputModule>& initial_modules) {
InMemoryFilesystem filesystem(InMemoryFilesystem::FileMap(
{{initial_modules[0].path, std::string(initial_modules[0].content)}}));
CompilerEnvironment compiler_environment(&filesystem, &initial_modules);
auto transpile_results_or_error = compiler_environment.impl_->Compile(
initial_modules[0].path, Impl::GenerateDeclarationFiles::Yes);
if (std::holds_alternative<TypeScriptCompiler::Error>(
transpile_results_or_error)) {
// We shouldn't have any errors here since we're just compiling a
// TypeScript file generated by us.
assert(false);
}
std::filesystem::create_directories(out_dir_path);
if (!std::filesystem::directory_entry(out_dir_path).exists()) {
return utils::Error{
fmt::format("Error creating directory {}", out_dir_path.string())};
}
const auto declarations_directory = out_dir_path / DECLS_SUBDIR;
std::filesystem::create_directories(declarations_directory);
if (!std::filesystem::directory_entry(declarations_directory).exists()) {
return utils::Error{fmt::format("Error creating declarations directory {}",
declarations_directory.string())};
}
auto transpile_results = std::get<TypeScriptCompiler::TranspileResults>(
transpile_results_or_error);
for (auto& declaration : transpile_results.declaration_files) {
auto out_path = declarations_directory / declaration.path;
if (!WriteToFile(out_path, declaration.content)) {
return utils::Error{fmt::format("Error writing to declaration file {}",
out_path.string())};
}
}
const std::string& main_module_file =
initial_modules[0].path.components().back();
// Remove the ".ts" extension.
const std::string main_module_name =
main_module_file.substr(0, main_module_file.size() - 3);
if (!WriteToFile(out_dir_path / "tsconfig.json",
fmt::format(TSCONFIG_JSON_CONTENT_TEMPLATE,
fmt::arg("decls_subdir", DECLS_SUBDIR),
fmt::arg("module_name", main_module_name)))) {
return utils::Error{"Error writing tsconfig.json file."};
}
return std::nullopt;
}
CompilerEnvironmentThreadSafe::CompilerEnvironmentThreadSafe(
VirtualFilesystem* virtual_filesystem,
const std::vector<CompilerEnvironment::InputModule>&
typescript_input_modules)
: virtual_filesystem_(std::move(virtual_filesystem)),
typescript_input_modules_(typescript_input_modules) {
compilation_thread_.Enqueue([this] {
compiler_environment_.emplace(virtual_filesystem_,
&typescript_input_modules_);
});
}
CompilerEnvironmentThreadSafe::~CompilerEnvironmentThreadSafe() {
compilation_thread_.Enqueue([this] { compiler_environment_ = std::nullopt; });
}
CompilerEnvironmentThreadSafe::CompileFuture
CompilerEnvironmentThreadSafe::Compile(
const VirtualFilesystem::AbsolutePath& sources) {
return compilation_thread_.EnqueueWithResult<CompileResults>(
[this, sources] { return compiler_environment_->Compile(sources); });
}
CompilerEnvironmentThreadSafe::MultiCompileFuture
CompilerEnvironmentThreadSafe::MultiCompile(
const std::set<VirtualFilesystem::AbsolutePath>& sources) {
return compilation_thread_.EnqueueWithResult<MultiCompileResults>(
[this, sources] {
MultiCompileResults results;
for (const auto& source : sources) {
results[source] = compiler_environment_->Compile(source);
}
return results;
});
}
} // namespace typescript_cpp_v8
} // namespace reify
| 35.028986 | 80 | 0.701834 | [
"object",
"vector"
] |
869eb23fa4e381d9d01f4b53969adbc5470bebe3 | 4,196 | cc | C++ | chrome/browser/sync/notifier/base/async_dns_lookup.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | chrome/browser/sync/notifier/base/async_dns_lookup.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/sync/notifier/base/async_dns_lookup.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notifier/base/async_dns_lookup.h"
#include "build/build_config.h"
#if defined(OS_POSIX)
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#include <sys/types.h>
#endif // defined(OS_POSIX)
#include <vector>
#include "base/basictypes.h"
#include "base/logging.h"
#include "chrome/browser/sync/notifier/base/nethelpers.h"
#include "chrome/browser/sync/notifier/gaia_auth/inet_aton.h"
#include "talk/base/byteorder.h"
#include "talk/base/common.h"
#include "talk/base/socketaddress.h"
#include "talk/base/thread.h"
enum { MSG_TIMEOUT = talk_base::SignalThread::ST_MSG_FIRST_AVAILABLE };
#ifndef WIN32
const int WSAHOST_NOT_FOUND = 11001; // Follows the format in winsock2.h.
#endif // WIN32
namespace notifier {
AsyncDNSLookup::AsyncDNSLookup(const talk_base::SocketAddress& server)
: server_(new talk_base::SocketAddress(server)),
error_(0) {
// Timeout after 5 seconds.
talk_base::Thread::Current()->PostDelayed(5000, this, MSG_TIMEOUT);
}
AsyncDNSLookup::~AsyncDNSLookup() {
}
void AsyncDNSLookup::DoWork() {
std::string hostname(server_->IPAsString());
in_addr addr;
if (inet_aton(hostname.c_str(), &addr)) {
talk_base::CritScope scope(&cs_);
ip_list_.push_back(talk_base::NetworkToHost32(addr.s_addr));
} else {
LOG(INFO) << "(" << hostname << ")";
hostent ent;
char buffer[8192];
int errcode = 0;
hostent* host = SafeGetHostByName(hostname.c_str(), &ent,
buffer, sizeof(buffer),
&errcode);
talk_base::Thread::Current()->Clear(this, MSG_TIMEOUT);
if (host) {
talk_base::CritScope scope(&cs_);
// Check to see if this already timed out.
if (error_ == 0) {
for (int index = 0; true; ++index) {
uint32* addr = reinterpret_cast<uint32*>(host->h_addr_list[index]);
if (addr == 0) { // 0 = end of list.
break;
}
uint32 ip = talk_base::NetworkToHost32(*addr);
LOG(INFO) << "(" << hostname << ") resolved to: "
<< talk_base::SocketAddress::IPToString(ip);
ip_list_.push_back(ip);
}
// Maintain the invariant that either the list is not empty or the
// error is non zero when we are done with processing the dnslookup.
if (ip_list_.empty() && error_ == 0) {
error_ = WSAHOST_NOT_FOUND;
}
}
FreeHostEnt(host);
} else {
{ // Scoping for the critical section.
talk_base::CritScope scope(&cs_);
// Check to see if this already timed out.
if (error_ == 0) {
error_ = errcode;
}
}
LOG(ERROR) << "(" << hostname << ") error: " << error_;
}
}
}
void AsyncDNSLookup::OnMessage(talk_base::Message* message) {
ASSERT(message);
if (message->message_id == MSG_TIMEOUT) {
OnTimeout();
} else {
talk_base::SignalThread::OnMessage(message);
}
}
void AsyncDNSLookup::OnTimeout() {
// Allow the scope for the critical section to be the whole method, just to
// be sure that the worker thread can't exit while we are doing
// SignalWorkDone (because that could possibly cause the class to be
// deleted).
talk_base::CritScope scope(&cs_);
// Check to see if the ip list was already filled (or errored out).
if (!ip_list_.empty() || error_ != 0) {
return;
}
// Worker thread is taking too long so timeout.
error_ = WSAHOST_NOT_FOUND;
// Rely on the caller to do the Release/Destroy.
//
// Doing this signal while holding cs_ won't cause a deadlock because the
// AsyncDNSLookup::DoWork thread doesn't have any locks at this point, and it
// is the only thread being held up by this.
SignalWorkDone(this);
// Ensure that no more "WorkDone" signaling is done.
// Don't call Release or Destroy since that was already done by the callback.
SignalWorkDone.disconnect_all();
}
} // namespace notifier
| 30.852941 | 79 | 0.647521 | [
"vector"
] |
86a7b343606a7bcbeff867a87d66a57fd609db20 | 1,690 | cpp | C++ | games/chess/gameManager.cpp | stewythe1st/sir-checkmatesalot | 136f25aba36420fbf4c51b365c012d4f4f1dc7f9 | [
"MIT"
] | null | null | null | games/chess/gameManager.cpp | stewythe1st/sir-checkmatesalot | 136f25aba36420fbf4c51b365c012d4f4f1dc7f9 | [
"MIT"
] | null | null | null | games/chess/gameManager.cpp | stewythe1st/sir-checkmatesalot | 136f25aba36420fbf4c51b365c012d4f4f1dc7f9 | [
"MIT"
] | null | null | null | // $This is a class that manages the Chess Game and it's GameObjects. Competitors should never have to care about this class's existance.
#include "gameManager.h"
#include "ai.h"
// The Game Objects
#include "gameObject.h"
#include "move.h"
#include "piece.h"
#include "player.h"
Chess::GameManager::GameManager() :
Joueur::BaseGameManager()
{
this->chessGame = new Chess::Game();
this->chessAI = new Chess::AI();
this->setup(this->chessGame, this->chessAI);
}
// @overrides
Joueur::BaseGameObject* Chess::GameManager::createGameObject(const std::string& gameObjectName)
{
if (gameObjectName == "GameObject")
{
return new Chess::GameObject();
}
else if (gameObjectName == "Move")
{
return new Chess::Move();
}
else if (gameObjectName == "Piece")
{
return new Chess::Piece();
}
else if (gameObjectName == "Player")
{
return new Chess::Player();
}
throw new std::runtime_error(("Game object '" + gameObjectName + "' not found to create new instance of").c_str());
}
// @overrides
void Chess::GameManager::setupAI(const std::string& playerID)
{
Joueur::BaseGameManager::setupAI(playerID);
this->chessAI->player = (Chess::Player*)(this->getGameObject(playerID));
this->chessAI->game = this->chessGame;
}
// @overrides
boost::property_tree::ptree* Chess::GameManager::orderAI(const std::string& order, boost::property_tree::ptree* args)
{
auto ptrees = this->getOrderArgsPtrees(args);
if (order == "runTurn")
{
auto returned = this->chessAI->runTurn(
);
return this->serialize(returned);
}
delete ptrees;
return nullptr;
}
| 24.492754 | 137 | 0.648521 | [
"object"
] |
86a99e97dd53100b786c7118ad112d26dd83dcff | 17,341 | tcc | C++ | src/concurrent-utils/concurrent-queue.tcc | max-plutonium/concurrent-utils | bec4956b767581878acc98f2904dcfa9654084ec | [
"X11"
] | null | null | null | src/concurrent-utils/concurrent-queue.tcc | max-plutonium/concurrent-utils | bec4956b767581878acc98f2904dcfa9654084ec | [
"X11"
] | null | null | null | src/concurrent-utils/concurrent-queue.tcc | max-plutonium/concurrent-utils | bec4956b767581878acc98f2904dcfa9654084ec | [
"X11"
] | null | null | null | /*
* Copyright (C) 2014-2015 Max Plutonium <plutonium.max@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT HOLDER(S) 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.
*
* Except as contained in this notice, the name(s) of the above copyright
* holders shall not be used in advertising or otherwise to promote the
* sale, use or other dealings in this Software without prior written
* authorization.
*/
#include "concurrent-queue.h"
namespace concurrent_utils {
/**
* @internal
* @brief Creates a queue's node from given arguments
* @param args List of arguments.
* @return Address of the constructed node.
*/
template <typename Tp, typename Alloc>
template<typename... Args>
auto
details::basic_forward_queue<Tp, Alloc>::
_create_node(Args &&...args) -> scoped_node_ptr
{
using traits = std::allocator_traits<node_alloc_type>;
node_alloc_type &alloc = _get_node_allocator();
auto guarded_ptr = std::__allocate_guarded(alloc);
traits::construct(alloc, guarded_ptr.get(), std::forward<Args>(args)...);
scoped_node_ptr node { guarded_ptr.get(), *this };
guarded_ptr = nullptr;
return node;
}
/**
* @internal
* @brief Puts the given node @a p to end of the queue
*/
template <typename Tp, typename Alloc>
void
details::basic_forward_queue<Tp, Alloc>::
_hook(node *p) noexcept
{
if(_impl.last)
_impl.last->next = p;
else
_impl.next = p;
_impl.last = p;
}
/**
* @internal
* @brief Takes the next node from the queue
* @return Address of taken node.
*/
template <typename Tp, typename Alloc>
auto
details::basic_forward_queue<Tp, Alloc>::
_unhook_next() noexcept -> scoped_node_ptr
{
scoped_node_ptr node { _impl.next, *this };
if(!node)
return node;
else if(!_impl.next->next)
_impl.last = nullptr;
_impl.next = _impl.next->next;
return node;
}
/**
* @internal
* @brief Sequentially takes and deletes all nodes from queue
* @note Without blocking.
*/
template <typename Tp, typename Alloc>
void
details::basic_forward_queue<Tp, Alloc>::_clear()
{
while(_unhook_next());
}
/**
* @internal
* @brief Copies content of @a other to self
* @note If an exception occurs during nodes are copying, saves
* the original queue's state.
*/
template <typename Tp, typename Lock, typename Alloc>
template<typename Tp2, typename Lock2, typename Alloc2>
void
concurrent_queue<Tp, Lock, Alloc>::
_assign(concurrent_queue<Tp2, Lock2, Alloc2> const &other)
{
static_assert(std::is_constructible<Tp, Tp2>::value,
"template argument substituting Tp in the second"
" queue object declaration must be constructible from"
" Tp in the first queue object declaration");
// temp's destructor should be executed after all unlocks
concurrent_queue<Tp, Lock, Alloc> temp;
// to protect deadlocks
ordered_lock<Lock, Lock2> locker { _lock, other._lock };
for(auto *other_node_ptr = other._impl.next;
other_node_ptr;
other_node_ptr = other_node_ptr->next)
{
// might throw
typename _base::scoped_node_ptr
node_ptr = temp._create_node(nullptr, std::ref(other_node_ptr->t));
temp._hook(node_ptr.release());
}
// we can unlock other now
std::unique_lock<Lock> locker2 { _lock, std::adopt_lock };
locker.release();
other._lock.unlock();
// swap contents with the temp object
swap_unsafe(temp);
}
/**
* @internal
* @brief Appends contents of @a other to itself by moving
* nodes using a simple exchange of pointers
*/
template <typename Tp, typename Lock, typename Alloc>
template <typename Lock2>
void
concurrent_queue<Tp, Lock, Alloc>::
_append(concurrent_queue<Tp, Lock2, Alloc> &&other)
{
// to protect deadlocks
ordered_lock<Lock, Lock2> locker { _lock, other._lock };
if(this->_impl.last)
this->_impl.last->next = other._impl.next;
else
this->_impl.next = other._impl.next;
this->_impl.last = other._impl.last;
other._impl.next = other._impl.last = nullptr;
}
/**
* @internal
* @brief Appends contents of @a other to itself by copying nodes
* @note The original queue is still in initial state.
*/
template <typename Tp, typename Lock, typename Alloc>
template<typename Tp2, typename Lock2, typename Alloc2>
void
concurrent_queue<Tp, Lock, Alloc>::
_append(concurrent_queue<Tp2, Lock2, Alloc2> const &other)
{
static_assert(std::is_constructible<Tp, Tp2>::value,
"template argument substituting Tp in the second"
" queue object declaration must be constructible from"
" Tp in the first queue object declaration");
// temp's destructor should be executed after all unlocks
concurrent_queue<Tp, Lock, Alloc> temp;
// to protect deadlocks
ordered_lock<Lock, Lock2> locker { _lock, other._lock };
for(auto *other_node_ptr = other._impl.next;
other_node_ptr;
other_node_ptr = other_node_ptr->next)
{
// might throw
typename _base::scoped_node_ptr
node_ptr = temp._create_node(nullptr, std::ref(other_node_ptr->t));
temp._hook(node_ptr.release());
}
locker.unlock();
// move contents from the temp object
_append(std::move(temp));
}
/**
* @internal
* @brief Waits for items to appear in the queue
* @return true, if the queue has been closed.
*/
template <typename Tp, typename Lock, typename Alloc>
bool
concurrent_queue<Tp, Lock, Alloc>::
_wait(std::unique_lock<Lock> &lk)
{
_cond.wait(lk, [this]() { return _closed || !_base::_empty(); });
return _closed;
}
/**
* @internal
* @brief Waits for items to appear in the queue until @a atime
* @return true, if the queue is closed.
*/
template <typename Tp, typename Lock, typename Alloc>
template<typename Clock, typename Duration>
bool
concurrent_queue<Tp, Lock, Alloc>::
_wait(std::unique_lock<Lock> &lk,
const std::chrono::time_point<Clock, Duration> &atime)
{
_cond.wait_until(lk, atime, [this]() {
return _closed || !_base::_empty(); });
return _closed;
}
/**
* @internal
* @brief Waits for items to appear in the queue within @a rtime
* @return true, if the queue is closed.
*/
template <typename Tp, typename Lock, typename Alloc>
template <typename Rep, typename Period>
bool
concurrent_queue<Tp, Lock, Alloc>::
_wait(std::unique_lock<Lock> &lk,
const std::chrono::duration<Rep, Period> &rtime)
{
_cond.wait_for(lk, rtime, [this]() {
return _closed || !_base::_empty(); });
return _closed;
}
/**
* Initializes all fields
*/
template <typename Tp, typename Lock, typename Alloc>
concurrent_queue<Tp, Lock, Alloc>::
concurrent_queue() noexcept
{
}
/**
* Blocks and clears the queue
*/
template <typename Tp, typename Lock, typename Alloc>
concurrent_queue<Tp, Lock, Alloc>::
~concurrent_queue()
{
close();
_lock.lock();
_base::_clear();
}
/**
* @brief Copies contents of @a other to itself
* @note If an exception occurs during items are copying,
* the queue is still empty.
*/
template <typename Tp, typename Lock, typename Alloc>
concurrent_queue<Tp, Lock, Alloc>::
concurrent_queue(const concurrent_queue<Tp, Lock, Alloc> &other)
: concurrent_queue()
{
_assign(other);
}
/**
* @brief Clears all contents and copies contents of @a other to itself
* @note If an exception occurs during items are copying, saves
* the original queue's state.
*/
template <typename Tp, typename Lock, typename Alloc>
concurrent_queue<Tp, Lock, Alloc> &
concurrent_queue<Tp, Lock, Alloc>::
operator=(concurrent_queue<Tp, Lock, Alloc> const &other)
{
if(this != std::addressof(other))
_assign(other);
return *this;
}
/**
* @copydoc concurrent_queue(const concurrent_queue &other)
*/
template <typename Tp, typename Lock, typename Alloc>
template <typename Tp2, typename Lock2, typename Alloc2>
concurrent_queue<Tp, Lock, Alloc>::
concurrent_queue(concurrent_queue<Tp2, Lock2, Alloc2> const &other)
: concurrent_queue()
{
_assign(other);
}
/**
* @copydoc concurrent_queue &concurrent_queue::operator=(const concurrent_queue &other)
*/
template <typename Tp, typename Lock, typename Alloc>
template <typename Tp2, typename Lock2, typename Alloc2>
concurrent_queue<Tp, Lock, Alloc> &
concurrent_queue<Tp, Lock, Alloc>::
operator=(concurrent_queue<Tp2, Lock2, Alloc2> const &other)
{
_assign(other); return *this;
}
/**
* @brief Appends contents of @a other to itself by moving items
*/
template <typename Tp, typename Lock, typename Alloc>
template <typename Lock2>
concurrent_queue<Tp, Lock, Alloc> &
concurrent_queue<Tp, Lock, Alloc>::
append(concurrent_queue<Tp, Lock2, Alloc> &&other)
{
_append(std::move(other)); return *this;
}
/**
* @brief Appends contents of @a other to itself by copying items
* @note The original queue is still in initial state.
*/
template <typename Tp, typename Lock, typename Alloc>
template <typename Tp2, typename Lock2, typename Alloc2>
concurrent_queue<Tp, Lock, Alloc> &
concurrent_queue<Tp, Lock, Alloc>::
append(concurrent_queue<Tp2, Lock2, Alloc2> const &other)
{
_append(other); return *this;
}
/**
* @brief Closes the queue
*/
template <typename Tp, typename Lock, typename Alloc>
void
concurrent_queue<Tp, Lock, Alloc>::close()
{
std::lock_guard<Lock> lk(_lock);
_closed = true;
_cond.notify_all();
}
/**
* @brief Exchanges contents with @a other
*/
template <typename Tp, typename Lock, typename Alloc>
template <typename Lock2>
void
concurrent_queue<Tp, Lock, Alloc>::
swap(concurrent_queue<Tp, Lock2, Alloc> &other) noexcept
{
// to protect deadlocks
ordered_lock<Lock, Lock2> locker(_lock, other._lock);
swap_unsafe(other);
}
/**
* @brief Exchanges contents with @a other
* @note Without blocking.
*/
template <typename Tp, typename Lock, typename Alloc>
template <typename Lock2>
void
concurrent_queue<Tp, Lock, Alloc>::
swap_unsafe(concurrent_queue<Tp, Lock2, Alloc> &other) noexcept
{
_base::_impl.swap(other._base::_impl);
}
/**
* @brief Creates an item from given arguments and puts it
* to the queue, if it is not closed
* @return true, if the queue is not closed.
* @snippet concurrent-queue.cc push
*/
template <typename Tp, typename Lock, typename Alloc>
template<typename... Args>
bool
concurrent_queue<Tp, Lock, Alloc>::
push(Args &&...args)
{
static_assert(std::is_constructible<value_type, Args...>::value,
"template argument substituting Tp"
" must be constructible from given arguments");
typename _base::scoped_node_ptr node
= _base::_create_node(nullptr, std::forward<Args>(args)...);
std::lock_guard<Lock> lk(_lock);
if(_closed) return false;
_base::_hook(node.release());
_cond.notify_one();
return true;
}
/**
* @brief Takes the next item from the queue and forwards
* it by reference @a val if the queue is not empty
* @return false, if the queue is already empty; true otherwise.
* @snippet concurrent-queue.cc pull
*/
template <typename Tp, typename Lock, typename Alloc>
bool
concurrent_queue<Tp, Lock, Alloc>::
pull(value_type &val)
{
typename _base::scoped_node_ptr node { nullptr, *this };
{
std::lock_guard<Lock> lk(_lock);
node = _base::_unhook_next();
}
if(node) {
val = std::move_if_noexcept(node->t);
return true;
}
return false;
}
/**
* @brief Waits for items to appear in the queue,
* then takes first item and forwards it by reference @a val,
* if the queue is not closed
* @return false, if the queue is empty or closed, true otherwise.
* @snippet concurrent-queue.cc wait_pull
*/
template <typename Tp, typename Lock, typename Alloc>
bool
concurrent_queue<Tp, Lock, Alloc>::
wait_pull(value_type &val)
{
typename _base::scoped_node_ptr node { nullptr, *this };
{
std::unique_lock<Lock> lk(_lock);
if(_wait(lk)) return false; // if closed
node = _base::_unhook_next();
}
if(node) {
val = std::move_if_noexcept(node->t);
return true;
}
return false;
}
/**
* @brief Waits for items to appear in the queue until @a atime,
* then takes first item and forwards it by reference @a val,
* if the queue is not closed
* @return false, if the queue is empty or closed, true otherwise.
* @snippet concurrent-queue.cc wait_pull
*/
template <typename Tp, typename Lock, typename Alloc>
template <typename Clock, typename Duration>
bool
concurrent_queue<Tp, Lock, Alloc>::
wait_pull(const std::chrono::time_point<Clock, Duration> &atime,
value_type &val)
{
typename _base::scoped_node_ptr node { nullptr, *this };
{
std::unique_lock<Lock> lk(_lock);
if(_wait(lk, atime)) return false; // if closed
node = _base::_unhook_next();
}
if(node) {
val = std::move_if_noexcept(node->t);
return true;
}
return false;
}
/**
* @brief Waits for items to appear in the queue within @a rtime,
* then takes first item and forwards it by reference @a val,
* if the queue is not closed
* @return false, if the queue is empty or closed, true otherwise.
* @snippet concurrent-queue.cc wait_pull
*/
template <typename Tp, typename Lock, typename Alloc>
template <typename Rep, typename Period>
bool
concurrent_queue<Tp, Lock, Alloc>::
wait_pull(const std::chrono::duration<Rep, Period> &rtime,
value_type &val)
{
typename _base::scoped_node_ptr node { nullptr, *this };
{
std::unique_lock<Lock> lk(_lock);
if(_wait(lk, rtime)) return false; // if closed
node = _base::_unhook_next();
}
if(node) {
val = std::move_if_noexcept(node->t);
return true;
}
return false;
}
/**
* @brief Creates an item from given arguments and puts it to the queue
* without blocking, if it is not closed
* @return true, if the queue is not closed.
*/
template <typename Tp, typename Lock, typename Alloc>
template<typename... Args>
bool
concurrent_queue<Tp, Lock, Alloc>::
push_unsafe(Args &&...args)
{
static_assert(std::is_constructible<value_type, Args...>::value,
"template argument substituting Tp"
" must be constructible from given arguments");
if(_closed) return false;
typename _base::scoped_node_ptr node
= _base::_create_node(nullptr, std::forward<Args>(args)...);
_base::_hook(node.release());
_cond.notify_one();
return true;
}
/**
* @brief Takes the next item from the queue without blocking
* and forwards it by reference @a val if the queue is not empty
* @return false, if the queue is already empty; true otherwise.
*/
template <typename Tp, typename Lock, typename Alloc>
bool
concurrent_queue<Tp, Lock, Alloc>::
pull_unsafe(value_type &val)
{
typename _base::scoped_node_ptr node = _base::_unhook_next();
if(node) {
val = std::move_if_noexcept(node->t);
return true;
}
return false;
}
} // namespace concurrent_utils
| 30.422807 | 88 | 0.635949 | [
"object"
] |
86b633275dbdf3466af4f007787bae05e9b0e826 | 4,629 | cpp | C++ | android/app/src/cpp/src/crypto/rx/RxQueue.cpp | chadananda/PocketMiner | 0f16b86853859c9b481ddbd20fc454c9692faa1a | [
"MIT"
] | 28 | 2021-05-11T03:28:57.000Z | 2022-03-09T14:34:57.000Z | android/app/src/cpp/src/crypto/rx/RxQueue.cpp | chadananda/PocketMiner | 0f16b86853859c9b481ddbd20fc454c9692faa1a | [
"MIT"
] | 10 | 2021-05-16T19:50:31.000Z | 2022-01-30T03:56:45.000Z | android/app/src/cpp/src/crypto/rx/RxQueue.cpp | chadananda/PocketMiner | 0f16b86853859c9b481ddbd20fc454c9692faa1a | [
"MIT"
] | 12 | 2021-07-19T22:14:58.000Z | 2022-02-08T02:24:05.000Z | /* XMRig
* Copyright (c) 2018 Lee Clagett <https://github.com/vtnerd>
* Copyright (c) 2018-2019 tevador <tevador@gmail.com>
* Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "crypto/rx/RxQueue.h"
#include "backend/common/interfaces/IRxListener.h"
#include "base/io/Async.h"
#include "base/io/log/Log.h"
#include "base/io/log/Tags.h"
#include "base/tools/Cvt.h"
#include "crypto/rx/RxBasicStorage.h"
#ifdef XMRIG_FEATURE_HWLOC
# include "crypto/rx/RxNUMAStorage.h"
#endif
xmrig::RxQueue::RxQueue(IRxListener *listener) :
m_listener(listener)
{
m_async = std::make_shared<Async>(this);
m_thread = std::thread(&RxQueue::backgroundInit, this);
}
xmrig::RxQueue::~RxQueue()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_state = STATE_SHUTDOWN;
lock.unlock();
m_cv.notify_one();
m_thread.join();
delete m_storage;
}
xmrig::RxDataset *xmrig::RxQueue::dataset(const Job &job, uint32_t nodeId)
{
std::lock_guard<std::mutex> lock(m_mutex);
if (isReadyUnsafe(job)) {
return m_storage->dataset(job, nodeId);
}
return nullptr;
}
xmrig::HugePagesInfo xmrig::RxQueue::hugePages()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_storage && m_state == STATE_IDLE ? m_storage->hugePages() : HugePagesInfo();
}
template<typename T>
bool xmrig::RxQueue::isReady(const T &seed)
{
std::lock_guard<std::mutex> lock(m_mutex);
return isReadyUnsafe(seed);
}
void xmrig::RxQueue::enqueue(const RxSeed &seed, const std::vector<uint32_t> &nodeset, uint32_t threads, bool hugePages, bool oneGbPages, RxConfig::Mode mode, int priority)
{
std::unique_lock<std::mutex> lock(m_mutex);
if (!m_storage) {
# ifdef XMRIG_FEATURE_HWLOC
if (!nodeset.empty()) {
m_storage = new RxNUMAStorage(nodeset);
}
else
# endif
{
m_storage = new RxBasicStorage();
}
}
if (m_state == STATE_PENDING && m_seed == seed) {
return;
}
m_queue.emplace_back(seed, nodeset, threads, hugePages, oneGbPages, mode, priority);
m_seed = seed;
m_state = STATE_PENDING;
lock.unlock();
m_cv.notify_one();
}
template<typename T>
bool xmrig::RxQueue::isReadyUnsafe(const T &seed) const
{
return m_storage != nullptr && m_storage->isAllocated() && m_state == STATE_IDLE && m_seed == seed;
}
void xmrig::RxQueue::backgroundInit()
{
while (m_state != STATE_SHUTDOWN) {
std::unique_lock<std::mutex> lock(m_mutex);
if (m_state == STATE_IDLE) {
m_cv.wait(lock, [this]{ return m_state != STATE_IDLE; });
}
if (m_state != STATE_PENDING) {
continue;
}
const auto item = m_queue.back();
m_queue.clear();
lock.unlock();
LOG_INFO("%s" MAGENTA_BOLD("init dataset%s") " algo " WHITE_BOLD("%s (") CYAN_BOLD("%u") WHITE_BOLD(" threads)") BLACK_BOLD(" seed %s..."),
Tags::randomx(),
item.nodeset.size() > 1 ? "s" : "",
item.seed.algorithm().name(),
item.threads,
Cvt::toHex(item.seed.data().data(), 8).data()
);
m_storage->init(item.seed, item.threads, item.hugePages, item.oneGbPages, item.mode, item.priority);
lock.lock();
if (m_state == STATE_SHUTDOWN || !m_queue.empty()) {
continue;
}
m_state = STATE_IDLE;
m_async->send();
}
}
void xmrig::RxQueue::onReady()
{
std::unique_lock<std::mutex> lock(m_mutex);
const bool ready = m_listener && m_state == STATE_IDLE;
lock.unlock();
if (ready) {
m_listener->onDatasetReady();
}
}
namespace xmrig {
template bool RxQueue::isReady(const Job &);
template bool RxQueue::isReady(const RxSeed &);
} // namespace xmrig
| 25.295082 | 172 | 0.632966 | [
"vector"
] |
86c1df8349b1da96de05e9fae61dcf580f629763 | 9,470 | cpp | C++ | c++/1.cpp | Crazyokd/leetcode-solution | 3aed88651fec391a02aba490ce72454c6f9e5409 | [
"MIT"
] | 1 | 2022-02-26T04:56:00.000Z | 2022-02-26T04:56:00.000Z | c++/1.cpp | Crazyokd/leetcode-solution | 3aed88651fec391a02aba490ce72454c6f9e5409 | [
"MIT"
] | null | null | null | c++/1.cpp | Crazyokd/leetcode-solution | 3aed88651fec391a02aba490ce72454c6f9e5409 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<map>
#include<algorithm>
#include<cstring>
#include<regex>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
map<int,int> m;
for(int i=0;i<nums.size();i++){
int another=target-nums[i];
if(m[another]){
ans.push_back(m[another]-1);
ans.push_back(i);
break;
}
m[nums[i]]=i+1;
}
return ans;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = new ListNode();
int n1=0,n2=0,carry=0;
ListNode *current=head;
while(l1!=nullptr || l2 != nullptr || carry != 0){
if(l1==nullptr)n1=0;
else{
n1=l1->val;
l1=l1->next;
}
if(l2==nullptr)n2=0;
else{
n2=l2->val;
l2=l2->next;
}
current->next=new ListNode((n1+n2+carry)%10);
current=current->next;
carry=(n1+n2+carry)/10;
}
return head->next;
}
int lengthOfLongestSubstring(string s) {
//使用map
map<int,int> m;
//cur_sta表示当前子串起点
int ans=0,cur_sta=0,len=s.size();
for(int i=0;i<len;i++){
if(m[(int)s[i]]){
//如果当前字符已经出现过
ans=max(i-cur_sta,ans);
//擦除
for(int j=cur_sta;j<m[(int)s[i]]-1;j++){
m[(int)s[j]]=0;
}
cur_sta=m[(int)s[i]];
}
m[(int)s[i]]=i+1;
}
return max(ans,len-cur_sta);
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1=nums1.size(),len2=nums2.size();
vector<int> ans;
int cur1=0,cur2=0;
while(cur1 < len1 || cur2 < len2){
while(cur1< len1 && (cur2 ==len2 || nums1[cur1] <= nums2[cur2])){
ans.push_back(nums1[cur1]);
cur1++;
}
while(cur2 < len2 && (cur1 == len1 || nums1[cur1] > nums2[cur2])){
ans.push_back(nums2[cur2]);
cur2++;
}
}
cout<<ans.size()<<endl;
for(int i=0;i<ans.size();i++){
cout<<ans[i]<<endl;
}
if((ans.size())%2==0)return (ans[ans.size()/2-1]+ans[ans.size()/2])/2.0;
else return ans[ans.size()/2];
}
//dp
string longestPalindrome1(string s) {
const int N=1005;
bool a[N][N]={0};
int sta=0,ans=1;
for(int i=0;i<s.size();i++){
for(int j=0;j<s.size()-i;j++){
if(s[j]==s[j+i] && (j+1 >= j+i-1 || a[j+1][j+i-1])){
a[j][j+i]=true;
if(i+1>ans){
ans=i+1;
sta=j;
}
}
}
}
return s.substr(sta,ans);
}
//马拉车算法
string longestPalindrome(string s){
if(s.size() < 2)return s;
const int N=2005;
int a[N]={0};
char cc[N];
int center=0,maxRight=0,maxLen=1,sta=0;
//预处理
cc[0]='#';
for(int i=0;i<s.size();i++){
cc[i*2+1]=s[i];
cc[2*(i+1)]='#';
}
for(int i=0;i < s.size()*2+1;i++){
if(i < maxRight){
//核心算法
a[i] = min(a[2*center-i],maxRight-i);
}
int left=i-(a[i]+1),right=i+(a[i]+1);
while(left >= 0 && right < s.size()*2+1 && cc[left] == cc[right]){
left--;
right++;
a[i]++;
}
//更新maxRight
if(a[i] + i > maxRight){
maxRight =a[i] + i;
center = i;
}
//更新答案
if(a[i] > maxLen){
maxLen = a[i];
sta = (i - a[i])/2;
}
}
return s.substr(sta,maxLen);
}
//题意
// 将给定的字符串按如下的Z字型排列,并从左至右输出
// | / /
// | /| /|
// |/ |/
// | |
string convert(string s, int numRows) {
vector<vector<char>> ans(numRows);
int down=0,up=numRows-2;
for(int i=0;i < s.size();i++){
if(down < numRows){
ans[down].push_back(s[i]);
down++;
}else if(up > 0){
ans[up].push_back(s[i]);
up--;
}else{
down=0;
up=numRows-2;
i--;
}
}
string solution="";
for(int i=0;i<numRows;i++){
for(int j=0;j < ans[i].size();j++){
solution.push_back(ans[i][j]);
}
}
return solution;
}
//注意最大值和最小值
int reverse(int x) {
long long ans=0;
int maxx=-1*((1<<31)+1),minn=(1<<31);
while(x != 0){
ans=ans*10+x%10;
x/=10;
}
if(ans > maxx || ans < minn)return 0;
return ans;
}
int myAtoi(string s) {
int maxx=-1*((1<<31)+1),minn=1<<31;
bool allowSign=true,allowSpace=true;
int sign=1;
vector<int> ans;
for(int i=0;i<s.size();i++){
if(s[i]==' '){
if(allowSpace)continue;
else break;
}else if((s[i] == '+' || s[i] == '-')){
if(!allowSign)break;
if(s[i] == '-')sign = -1;
allowSign=false;
allowSpace=false;
}else if(s[i] <= '9' && s[i] >= '0'){
allowSign=false;
allowSpace=false;
ans.push_back((int)(s[i]-'0'));
}else{
break;
}
}
long long res=0;
bool leadingZero=true;
int substitute = sign > 0 ? maxx : minn;
for(int i=0;i<ans.size();i++){
if(!ans[i] && leadingZero)continue;
if(ans.size() - i > 10)return substitute;
leadingZero=false;
res=res*10+ans[i];
}
if(res > maxx || res < minn)return substitute;
return sign*res;
}
bool isPalindrome(int x) {
if(x < 0)return false;
vector<int> res;
while(x){
res.push_back(x%10);
x/=10;
}
int len=res.size();
for(int i=0;i<len/2;i++){
if(res[i] != res[len-i-1])
return false;
}
return true;
}
//通过分支判断无法实现功能
// bool isMatch(string s, string p) {
// int ps=0,pp=0;
// //对p中*前后的字符进行预处理
// for(int i=2;i<p.size();){
// if(p[i-1] == '*' && (p[i] == '*' || p[i] == p[i-2]))p.erase(p.begin()+i);
// else i++;
// }
// int lens=s.size(),lenp=p.size();
// while(ps < lens && pp < lenp){
// //直接出现*视为无效
// if(p[pp] == '*'){
// pp++;
// continue;
// }
// if(pp+1 < lenp && p[pp+1] == '*'){
// while(ps < lens && (s[ps] == p[pp] || p[pp] == '.'))ps++;
// pp+=2;
// }else{
// if(s[ps] != p[pp] && p[pp] != '.')return false;
// ps++;
// pp++;
// }
// }
// if(ps < lens || pp < lenp)return false;
// return true;
// }
bool isMatch1(string s, string p) {
return regex_match(s,regex(p));
}
// dp[a][b]表示将s[a]与p[b]相匹配,若返回false,表示不能将s[a]与p[b]相匹配
bool solver(string &s,string &p,int a ,int b,vector<vector<int>> &dp) {
// 递归终止条件
//若dp[a][b]!=-1,表示已经计算过,return
if(dp[a][b]!=-1) return dp[a][b];
//匹配完毕,return true
if(a>=s.length() && b>=p.length()) return dp[a][b] = true;
//p已经使用完但s还有未匹配的,return false
if(b>=p.length()) return dp[a][b] = false;
//s[a]能与p[b]相匹配
bool match = ( a <s.length() && (s[a]==p[b] || p[b]=='.'));
//关键算法,若出现*通配符,可选择不匹配或选择匹配
if( b<p.length()-1 && p[b+1]=='*') return dp[a][b] = solver(s,p,a,b+2,dp) || ( match && solver(s,p,a+1,b,dp));
//普通匹配
if(match) return dp[a][b] = solver(s,p,a+1,b+1,dp);
return dp[a][b] = false;
}
bool isMatch(string s, string p) {
vector<vector<int>> dp( s.length()+1, vector<int>(p.length()+1,-1) );
return solver(s,p,0,0,dp);
}
};
int main(){
vector<int> ans(2);//创建一个size=2的vector
string s="aacabdkacaa";
map<int,int> m;
m[1]=2;
// cout<<m[1];
m.erase(1);
// cout<<m[1];
// cout<<(int)s[1];
Solution solution=Solution();
// cout<<solution.lengthOfLongestSubstring(s);
vector<int> a,b;
a.push_back(1),a.push_back(3);
b.push_back(2);
// solution.findMedianSortedArrays(a,b);
// cout<<solution.longestPalindrome1(s);
// s.append("#");
// cout<<solution.longestPalindrome(s)<<endl;
string ss="PAYPALISHIRING";
// cout<<solution.convert(ss,3);
// cout<<solution.reverse(-123);
// cout<<solution.myAtoi("-0042");
// cout<<solution.isPalindrome(1001);
cout<<solution.isMatch("aa","a*");
return 0;
} | 29.318885 | 118 | 0.420063 | [
"vector"
] |
86c690305d553a57d439665f9811253fd34fce9a | 953 | cpp | C++ | cpp/src/exercise/e0100/e0017.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | cpp/src/exercise/e0100/e0017.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | cpp/src/exercise/e0100/e0017.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | #include "extern.h"
class Solution {
vector<string> LETTER { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
public:
vector<string> letterInter(string& digits, const vector<string>& strs) {
if (digits.empty()) return strs;
vector<string> result {};
int digit = digits.back() - '0'; digits.pop_back();
for (char l : LETTER[digit])
for (const string& str : strs)
result.push_back(l + str);
return letterInter(digits, result);
}
vector<string> letterCombinations(string& digits) {
vector<string> result { "" };
result = letterInter(digits, result);
return result.size() == 1 ? vector<string>{} : result; // exclude no digit situation
}
};
TEST(e0100, e0017) {
string s1 = "23";
vector<string> r1{ "ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf" };
ASSERT_THAT(Solution().letterCombinations(s1), r1);
}
| 32.862069 | 95 | 0.565582 | [
"vector"
] |
86c6a0b77fc2c2454822611b659eb441fef03637 | 8,757 | cpp | C++ | src/syntax/parser_expr.cpp | ionlang/ionlang | 839a5fc3aa0b575dc43e61c6e833e90e00dc922d | [
"Unlicense"
] | 13 | 2020-08-20T15:01:10.000Z | 2021-11-25T05:53:01.000Z | src/syntax/parser_expr.cpp | ionlang/ion | 839a5fc3aa0b575dc43e61c6e833e90e00dc922d | [
"Unlicense"
] | 3 | 2020-08-10T18:55:52.000Z | 2021-10-11T06:33:07.000Z | src/syntax/parser_expr.cpp | ionlang/ion | 839a5fc3aa0b575dc43e61c6e833e90e00dc922d | [
"Unlicense"
] | 2 | 2019-06-30T14:58:47.000Z | 2019-09-24T20:01:57.000Z | #include <ionlang/const/grammar.h>
#include <ionlang/lexical/classifier.h>
#include <ionlang/syntax/parser.h>
namespace ionlang {
AstPtrResult<Expression<>> Parser::parseExpression(const std::shared_ptr<Block>& parent) {
AstPtrResult<Expression<>> primaryExpression = this->parsePrimaryExpr(parent);
IONLANG_PARSER_ASSERT(util::hasValue(primaryExpression))
// TODO: Change this so the check of whether it's a bin. operation is done here, and the parseOperationExpr() is forcefully invoked.
/**
* NOTE: Will return the parsed primary expression if a binary
* operator isn't present as the next (current) token.
*/
return util::getResultValue(this->parseOperationExpr(
0,
util::getResultValue(primaryExpression),
parent
));
}
AstPtrResult<Expression<>> Parser::parsePrimaryExpr(const std::shared_ptr<Block>& parent) {
if (this->is(TokenKind::SymbolParenthesesL)) {
return this->parseParenthesesExpr(parent);
}
else if (this->is(TokenKind::Identifier)) {
return this->parseIdExpr(parent);
}
// TODO: Support unary and binary operation parsing.
// TODO: Not proper parent.
// Otherwise, it must be a literal value.
AstPtrResult<Expression<>> literal = this->parseLiteral(parent);
IONLANG_PARSER_ASSERT(util::hasValue(literal))
return util::getResultValue(literal);
}
AstPtrResult<Expression<>> Parser::parseParenthesesExpr(const std::shared_ptr<Block>& parent) {
this->beginSourceLocationMapping();
IONLANG_PARSER_ASSERT(this->skipOver(TokenKind::SymbolParenthesesL))
AstPtrResult<Expression<>> expression = this->parseExpression(parent);
IONLANG_PARSER_ASSERT(this->skipOver(TokenKind::SymbolParenthesesR))
this->finishSourceLocationMapping(util::getResultValue(expression));
return expression;
}
AstPtrResult<Expression<>> Parser::parseIdExpr(const std::shared_ptr<Block>& parent) {
this->beginSourceLocationMapping();
if (this->isNext(TokenKind::SymbolParenthesesL)) {
return util::getResultValue(this->parseCallExpr(parent));
}
else if (this->isNext(TokenKind::SymbolBraceL)) {
return util::getResultValue(this->parseStructDefExpr(parent));
}
// TODO: Is this the correct parent for the ref?
PtrResolvable<VariableDeclStmt> variableDeclRef =
util::getResultValue(this->parseResolvable<VariableDeclStmt>(parent));
this->finishSourceLocationMapping(variableDeclRef);
return std::make_shared<VariableRefExpr>(variableDeclRef);
}
AstPtrResult<Expression<>> Parser::parseOperationExpr(
uint32_t minimumOperatorPrecedence,
std::shared_ptr<Expression<>> leftSideExpression,
const std::shared_ptr<Block>& parent
) {
auto isOperatorAndPrecedenceGraterThan = [](TokenKind tokenKind, uint32_t precedence) -> bool {
return Classifier::isIntrinsicOperator(tokenKind)
&& *util::findIntrinsicOperatorKindPrecedence(tokenKind) >= precedence;
};
TokenKind tokenKindBuffer = this->tokenStream.get().kind;
while (isOperatorAndPrecedenceGraterThan(tokenKindBuffer, minimumOperatorPrecedence)) {
std::optional<IntrinsicOperatorKind> operatorKind =
util::findIntrinsicOperatorKind(tokenKindBuffer);
IONLANG_PARSER_ASSERT(operatorKind.has_value())
std::optional<uint32_t> operatorPrecedence =
util::findIntrinsicOperatorKindPrecedence(tokenKindBuffer);
IONLANG_PARSER_ASSERT(operatorPrecedence.has_value())
// Skip the operator token.
this->tokenStream.skip();
AstPtrResult<Expression<>> rightSidePrimaryExpressionResult =
this->parsePrimaryExpr(parent);
tokenKindBuffer = this->tokenStream.get().kind;
/**
* TODO: https://en.wikipedia.org/wiki/Operator-precedence_parser.
* ... or a right-associative operator ... check is missing here.
*/
while (isOperatorAndPrecedenceGraterThan(tokenKindBuffer, *operatorPrecedence)) {
rightSidePrimaryExpressionResult = this->parseOperationExpr(
util::findIntrinsicOperatorKindPrecedence(tokenKindBuffer).value_or(0),
util::getResultValue(rightSidePrimaryExpressionResult),
parent
);
tokenKindBuffer = this->tokenStream.get().kind;
}
// TODO: Make sure both side's type are the same? Or leave it up to type-checking?
leftSideExpression = OperationExpr::make(
// TODO: Should copy the type, not use it, because it will be linked.
leftSideExpression->type,
*operatorKind,
leftSideExpression,
util::getResultValue(rightSidePrimaryExpressionResult)
);
}
return leftSideExpression;
}
AstPtrResult<CallExpr> Parser::parseCallExpr(const std::shared_ptr<Block>& parent) {
this->beginSourceLocationMapping();
AstPtrResult<Identifier> calleeId = this->parseIdentifier();
IONLANG_PARSER_ASSERT(util::hasValue(calleeId))
IONLANG_PARSER_ASSERT(this->skipOver(TokenKind::SymbolParenthesesL))
CallArgs callArgs{};
while (!this->is(TokenKind::SymbolParenthesesR)) {
AstPtrResult<Expression<>> primaryExpr = this->parsePrimaryExpr(parent);
IONLANG_PARSER_ASSERT(util::hasValue(primaryExpr))
callArgs.push_back(util::getResultValue(primaryExpr));
if (this->is(TokenKind::SymbolComma) && this->isNext(TokenKind::SymbolParenthesesR)) {
// TODO: Use DiagnosticBuilder.
throw std::runtime_error("No lonely leading comma");
}
else if (!this->is(TokenKind::SymbolParenthesesR)) {
IONLANG_PARSER_ASSERT(this->skipOver(TokenKind::SymbolComma))
}
}
IONLANG_PARSER_ASSERT(this->skipOver(TokenKind::SymbolParenthesesR))
std::shared_ptr<CallExpr> callExpr = CallExpr::make(
Resolvable<>::make(
ResolvableKind::FunctionLike,
util::getResultValue(calleeId),
parent
),
callArgs,
Resolvable<Type>::make(
ResolvableKind::PrototypeReturnType,
util::getResultValue(calleeId),
parent
)
);
this->finishSourceLocationMapping(callExpr);
return callExpr;
}
AstPtrResult<StructDefExpr> Parser::parseStructDefExpr(
const std::shared_ptr<Block>& parent
) {
this->beginSourceLocationMapping();
std::optional<std::string> name = this->parseName();
IONLANG_PARSER_ASSERT(name.has_value())
IONLANG_PARSER_ASSERT(this->skipOver(TokenKind::SymbolBraceL))
std::vector<std::shared_ptr<Expression<>>> values{};
while (!this->is(TokenKind::SymbolBraceR)) {
AstPtrResult<Expression<>> value = this->parseExpression(parent);
IONLANG_PARSER_ASSERT(util::hasValue(value))
values.push_back(util::getResultValue(value));
}
this->tokenStream.skip();
std::shared_ptr<StructDefExpr> structDefinition = StructDefExpr::make(
Resolvable<StructType>::make(
ResolvableKind::StructType,
std::make_shared<Identifier>(*name),
parent
),
values
);
this->finishSourceLocationMapping(structDefinition);
return structDefinition;
}
AstPtrResult<CastExpr> Parser::parseCastExpr(const std::shared_ptr<Block>& parent) {
this->beginSourceLocationMapping();
IONLANG_PARSER_ASSERT(this->skipOver(TokenKind::SymbolParenthesesL))
AstPtrResult<Resolvable<Type>> type = this->parseType(parent);
IONLANG_PARSER_ASSERT(util::hasValue(type))
IONLANG_PARSER_ASSERT(this->skipOver(TokenKind::SymbolParenthesesR))
AstPtrResult<Expression<>> value = this->parsePrimaryExpr(parent);
IONLANG_PARSER_ASSERT(util::hasValue(value))
std::shared_ptr<CastExpr> cast = CastExpr::make(
util::getResultValue(type),
util::getResultValue(value)
);
// TODO: Is this proper parent?
cast->setParent(parent);
this->finishSourceLocationMapping(cast);
return cast;
}
}
| 36.037037 | 140 | 0.638689 | [
"vector"
] |
f86a42e5ce238447338d2a124c66fcc84f46a5a5 | 5,654 | cpp | C++ | src/mapper.cpp | ympek/floodsar | 54d284d031e35b3e4c8bcf738f142ff12700b46c | [
"MIT"
] | null | null | null | src/mapper.cpp | ympek/floodsar | 54d284d031e35b3e4c8bcf738f142ff12700b46c | [
"MIT"
] | null | null | null | src/mapper.cpp | ympek/floodsar | 54d284d031e35b3e4c8bcf738f142ff12700b46c | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <sstream>
#include <filesystem>
#include <cmath>
#include "gdal_priv.h"
#include "cpl_conv.h" // for CPLMalloc()
#include "ogrsf_frmts.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <thread>
#include "XYPair.hpp"
#include "BoundingBox.hpp"
#include "utils.hpp"
#include <algorithm>
#include "../vendor/cxxopts.hpp"
namespace fs = std::filesystem;
//std::vector<std::string> dates {
//"20201101", "20201104", "20201105", "20201106", "20201107", "20201110", "20201111", "20201112", "20201113", "20201116", "20201117", "20201118", "20201119", "20201122", "20201123", "20201124", "20201125", "20201128", "20201129", "20201130", "20201201", "20201204", "20201205", "20201206", "20201207", "20201210", "20201211", "20201212", "20201213", "20201216", "20201217", "20201218", "20201219", "20201222", "20201223", "20201224", "20201225", "20201228", "20201229", "20201230", "20201231", "20210103", "20210104", "20210105", "20210106", "20210109", "20210110", "20210111", "20210112", "20210115", "20210116", "20210117", "20210118", "20210121", "20210122", "20210123", "20210124", "20210127", "20210128", "20210129", "20210202", "20210203", "20210204", "20210205", "20210208", "20210209", "20210210", "20210211", "20210214", "20210215", "20210216", "20210217", "20210220", "20210221", "20210222", "20210223", "20210226", "20210227", "20210228", "20210301", "20210304", "20210305", "20210306", "20210307", "20210310", "20210311", "20210312", "20210313", "20210316", "20210317", "20210318", "20210319", "20210322", "20210323", "20210324", "20210325", "20210328", "20210329", "20210330", "20210331" };
std::vector<std::string> dates {
"20170220", "20170222", "20170223", "20170225", "20170226", "20170228", "20170301", "20170303", "20170304", "20170306", "20170307", "20170309", "20170310", "20170312", "20170313", "20170315", "20170316", "20170318", "20170319", "20170321", "20170322", "20170324", "20170424", "20170524", "20170723", "DUMMY"
};
int main(int argc, char** argv) {
GDALAllRegister();
cxxopts::Options options("Floodsar::Mapper", " - command line options");
options.add_options()
("c,classes", "all classes", cxxopts::value<int>())
("f,floods", "flood classes", cxxopts::value<int>())
("b,base", "use base algo, provide polarization", cxxopts::value<std::string>())
;
int numAllClassess = 2;
int numFloodClasses = 1;
std::vector<int> floodClasses;
std::string pointsFile;
std::string mapDirectory;
auto userInput = options.parse(argc, argv);
if(!fs::exists("./raster")) {
fs::copy_file("./.floodsar-cache/cropped/resampled__VV_" + dates[0], "./raster");
}
if (userInput.count("base")) {
// base algoritm mapping.
floodClasses.push_back(1);
std::string pol = userInput["base"].as<std::string>();
// bedzie VV albo VH
pointsFile = "./.floodsar-cache/1d_output/" + pol;
mapDirectory = "./mapped/base_algo_pol_" + pol + "/";
} else {
// improved algo mapping.
numAllClassess = userInput["classes"].as<int>();
numFloodClasses = userInput["floods"].as<int>();
std::string floodclassesFile = "./.floodsar-cache/kmeans_outputs/KMEANS_INPUT_cl_"
+ std::to_string(numAllClassess) + "/" + std::to_string(numAllClassess)
+ "-clusters.txt_" + std::to_string(numFloodClasses) + "_floodclasses.txt";
std::ifstream floodclassesFileStream(floodclassesFile);
int floodClass;
while (floodclassesFileStream >> floodClass) {
floodClasses.push_back(floodClass);
}
floodclassesFileStream.close();
pointsFile = "./.floodsar-cache/kmeans_outputs/KMEANS_INPUT_cl_"
+ std::to_string(numAllClassess) + "/" + std::to_string(numAllClassess)
+ "-points.txt";
mapDirectory = "./mapped/" + std::to_string(numAllClassess) + "__" + std::to_string(numFloodClasses) + "/";
}
std::string rasterToClassify = "./raster";
std::ifstream pointsStream(pointsFile);
int point;
int dateIndex = 0;
int bufferIndex = 0;
fs::create_directory("./mapped/");
fs::create_directory(mapDirectory);
std::string mapPath = mapDirectory + dates[dateIndex] + ".tif";
std::filesystem::copy_file(rasterToClassify, mapPath);
auto raster = static_cast<GDALDataset*>(GDALOpen(mapPath.c_str(), GA_Update));
auto rasterBand = raster->GetRasterBand(1);
const unsigned int xSize = rasterBand->GetXSize();
const unsigned int ySize = rasterBand->GetYSize();
const unsigned int words = xSize * ySize;
double* buffer = static_cast<double*>(CPLMalloc(sizeof(double) * words));
while(pointsStream >> point) {
if (std::find(floodClasses.begin(), floodClasses.end(), point) != floodClasses.end()) {
buffer[bufferIndex] = 1;
} else {
buffer[bufferIndex] = 0;
}
bufferIndex++;
if (bufferIndex == words) {
bufferIndex = 0;
auto error = rasterBand->RasterIO(GF_Write, 0, 0, xSize, ySize, buffer, xSize, ySize, GDT_Float64, 0, 0);
if (error == CE_Failure) {
std::cout << "[] Could not read raster\n";
} else {
std::cout << "zapisano " + mapPath + '\n';
}
dateIndex++;
if (dateIndex > dates.size()) {
std::cout << "Its time to stop. \n";
break;
}
mapPath = mapDirectory + dates[dateIndex] + ".tif";
std::filesystem::copy_file(rasterToClassify, mapPath);
raster->FlushCache();
GDALClose(raster);
raster = static_cast<GDALDataset*>(GDALOpen(mapPath.c_str(), GA_Update));
rasterBand = raster->GetRasterBand(1);
}
}
pointsStream.close();
CPLFree(buffer);
return 0;
}
| 37.197368 | 1,203 | 0.655996 | [
"vector"
] |
f86dbf516c5a4f82b0bfc37370e8291ee8fea644 | 1,166 | cpp | C++ | Data Structure/Matrix/Print A Given Matrix in Spiral Form/SolutionByTanmay.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 261 | 2019-09-30T19:47:29.000Z | 2022-03-29T18:20:07.000Z | Data Structure/Matrix/Print A Given Matrix in Spiral Form/SolutionByTanmay.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 647 | 2019-10-01T16:51:29.000Z | 2021-12-16T20:39:44.000Z | Data Structure/Matrix/Print A Given Matrix in Spiral Form/SolutionByTanmay.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 383 | 2019-09-30T19:32:07.000Z | 2022-03-24T16:18:26.000Z | #include <iostream>
#include <vector>
using namespace std;
void printSpriral(vector<vector<int>>& matrix)
{
int top = 0, right = matrix[0].size() - 1, bottom = matrix.size() - 1, left = 0;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
cout << matrix[top][i] << " ";
}
top++;
for (int i = top; i <= bottom; i++) {
cout << matrix[i][right] << " ";
}
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) {
cout << matrix[bottom][i] << " ";
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
cout << matrix[i][left] << " ";
}
left++;
}
}
cout << endl;
}
int main()
{
int R, C, val;
cin >> R >> C;
vector<vector<int>> matrix;
for (int i = 0; i < R; i++) {
vector<int> v;
for (int j = 0; j < C; j++) {
cin >> val;
v.push_back(val);
}
matrix.push_back(v);
}
printSpriral(matrix);
return 0;
}
| 22.423077 | 84 | 0.399657 | [
"vector"
] |
f873a7562e3042b0256373ef734afb37c23b67a9 | 4,034 | cc | C++ | mayz-src/AmisModel.cc | mynlp/enju | d984a630b30b95de16f3b715277e95dc6fbe15b4 | [
"Apache-2.0"
] | 48 | 2016-10-11T06:07:02.000Z | 2022-03-02T16:26:25.000Z | mayz-src/AmisModel.cc | mynlp/enju | d984a630b30b95de16f3b715277e95dc6fbe15b4 | [
"Apache-2.0"
] | 7 | 2017-02-13T09:14:34.000Z | 2019-01-18T06:06:29.000Z | mayz-src/AmisModel.cc | mynlp/enju | d984a630b30b95de16f3b715277e95dc6fbe15b4 | [
"Apache-2.0"
] | 18 | 2016-11-13T23:14:28.000Z | 2022-01-12T15:21:44.000Z | /**********************************************************************
*
* Copyright (c) 2005, Tsujii Laboratory, The University of Tokyo.
* All rights reserved.
*
* @file AmisModel.cc
* @version Time-stamp: <2006-06-03 19:27:52 yusuke>
* Classes for handling ME models
*
**********************************************************************/
#include <memory>
#include "AmisModel.h"
using namespace std;
using namespace mayz;
namespace mayz {
const std::string AmisModel::TOKEN_SEPARATOR( "//" );
const std::string AmisModel::DONT_CARE( "_" );
AmisModel::AmisModel() {
}
AmisModel::~AmisModel() {
/*
for ( std::vector< std::vector< std::string >* >::iterator it = feature_table.begin();
it != feature_table.end();
++it ) {
delete *it;
}
*/
}
// bool AmisModel::extractFeatures( const std::string& name,
// std::vector< AmisFeature >& features,
// std::string& category ) const {
// AmisFeature id_list;
// makeTokenList( name, id_list, category );
// FeatureTableMap::const_iterator table_it = feature_table.find( category );
// if ( table_it == feature_table.end() ) return false; // unknown category
// return extractFeatures( table_it->second.mask_table, id_list, features );
// }
bool AmisModel::extractFeatures( const std::string& category,
const std::vector< std::string >& token_list,
std::vector< AmisFeature >& features ) const {
FeatureTableMap::const_iterator table_it = feature_table.find( category );
if ( table_it == feature_table.end() ) return false; // unknown category
AmisFeature id_list( token_list.size() );
makeAmisFeature( token_list, id_list );
return extractFeatures( table_it->second.mask_table, id_list, features );
}
bool AmisModel::extractFeatures( const std::vector< AmisFeatureMask >& mask_table,
const AmisFeature& id_list,
std::vector< AmisFeature >& features ) {
for ( std::vector< AmisFeatureMask >::const_iterator mask_it = mask_table.begin();
mask_it != mask_table.end();
++mask_it ) {
AmisFeature feature( id_list.size() );
if ( feature.applyMask( id_list, *mask_it ) ) {
features.push_back( feature );
}
}
return true;
}
bool AmisModel::importModel( std::istream& model_file ) {
std::string name;
double value;
std::string category;
AmisFeature token_list;
while ( model_file ) {
model_file >> name >> value;
double x = log( value );
if ( x != 0.0 ) {
registerTokenList( name, token_list, category );
feature_table[ category ].lambda_table[ token_list ] = x;
}
}
return true;
}
AmisHandler::AmisHandler() {
}
AmisHandler::~AmisHandler() {
for ( std::map< std::string, AmisModel* >::iterator it = amis_table.begin();
it != amis_table.end(); ) {
if ( it->second != NULL ) {
delete it->second;
}
amis_table.erase(it++);
}
}
void AmisHandler::deleteAmisModel( const std::string& name ) {
std::map< std::string, AmisModel* >::iterator it = amis_table.find( name );
if ( it == amis_table.end() || it->second == NULL ) {
//RUNERR("Amis model is not found: " << name);
return;
}
erase( it );
}
AmisModel* AmisHandler::newAmisModel( const std::string& name ) {
if ( amis_table.find( name ) != amis_table.end() ) {
//RUNERR("Amis model is already generated: " << name);
return NULL;
}
return amis_table[ name ] = new AmisModel;
}
AmisModel* AmisHandler::getAmisModel( const std::string& name ) {
std::map< std::string, AmisModel* >::iterator it = amis_table.find( name );
if ( it == amis_table.end() ) {
//RUNERR("Amis model not found: " << name);
return NULL;
}
return it->second;
}
}
| 32.532258 | 90 | 0.571145 | [
"vector",
"model"
] |
f881275fa0215f06f8d3c64e6c3cc9f43d3a1a87 | 9,123 | cpp | C++ | source/backend/colour/colutils.cpp | acekiller/povray | ae6837fb8625bb9ca00830f8871c90c87dd21b75 | [
"Zlib"
] | 1 | 2015-06-21T05:27:57.000Z | 2015-06-21T05:27:57.000Z | source/backend/colour/colutils.cpp | binji/povray | ae6837fb8625bb9ca00830f8871c90c87dd21b75 | [
"Zlib"
] | null | null | null | source/backend/colour/colutils.cpp | binji/povray | ae6837fb8625bb9ca00830f8871c90c87dd21b75 | [
"Zlib"
] | null | null | null | /*******************************************************************************
* colutils.cpp
*
* This module implements the utility functions for colors.
*
* from Persistence of Vision Ray Tracer ('POV-Ray') version 3.7.
* Copyright 1991-2003 Persistence of Vision Team
* Copyright 2003-2009 Persistence of Vision Raytracer Pty. Ltd.
* ---------------------------------------------------------------------------
* NOTICE: This source code file is provided so that users may experiment
* with enhancements to POV-Ray and to port the software to platforms other
* than those supported by the POV-Ray developers. There are strict rules
* regarding how you are permitted to use this file. These rules are contained
* in the distribution and derivative versions licenses which should have been
* provided with this file.
*
* These licences may be found online, linked from the end-user license
* agreement that is located at http://www.povray.org/povlegal.html
* ---------------------------------------------------------------------------
* POV-Ray is based on the popular DKB raytracer version 2.12.
* DKBTrace was originally written by David K. Buck.
* DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins.
* ---------------------------------------------------------------------------
* $File: //depot/povray/smp/source/backend/colour/colutils.cpp $
* $Revision: #19 $
* $Change: 5088 $
* $DateTime: 2010/08/05 17:08:44 $
* $Author: clipka $
*******************************************************************************/
/*********************************************************************************
* NOTICE
*
* This file is part of a BETA-TEST version of POV-Ray version 3.7. It is not
* final code. Use of this source file is governed by both the standard POV-Ray
* licences referred to in the copyright header block above this notice, and the
* following additional restrictions numbered 1 through 4 below:
*
* 1. This source file may not be re-distributed without the written permission
* of Persistence of Vision Raytracer Pty. Ltd.
*
* 2. This notice may not be altered or removed.
*
* 3. Binaries generated from this source file by individuals for their own
* personal use may not be re-distributed without the written permission
* of Persistence of Vision Raytracer Pty. Ltd. Such personal-use binaries
* are not required to have a timeout, and thus permission is granted in
* these circumstances only to disable the timeout code contained within
* the beta software.
*
* 4. Binaries generated from this source file for use within an organizational
* unit (such as, but not limited to, a company or university) may not be
* distributed beyond the local organizational unit in which they were made,
* unless written permission is obtained from Persistence of Vision Raytracer
* Pty. Ltd. Additionally, the timeout code implemented within the beta may
* not be disabled or otherwise bypassed in any manner.
*
* The following text is not part of the above conditions and is provided for
* informational purposes only.
*
* The purpose of the no-redistribution clause is to attempt to keep the
* circulating copies of the beta source fresh. The only authorized distribution
* point for the source code is the POV-Ray website and Perforce server, where
* the code will be kept up to date with recent fixes. Additionally the beta
* timeout code mentioned above has been a standard part of POV-Ray betas since
* version 1.0, and is intended to reduce bug reports from old betas as well as
* keep any circulating beta binaries relatively fresh.
*
* All said, however, the POV-Ray developers are open to any reasonable request
* for variations to the above conditions and will consider them on a case-by-case
* basis.
*
* Additionally, the developers request your co-operation in fixing bugs and
* generally improving the program. If submitting a bug-fix, please ensure that
* you quote the revision number of the file shown above in the copyright header
* (see the '$Revision:' field). This ensures that it is possible to determine
* what specific copy of the file you are working with. The developers also would
* like to make it known that until POV-Ray 3.7 is out of beta, they would prefer
* to emphasize the provision of bug fixes over the addition of new features.
*
* Persons wishing to enhance this source are requested to take the above into
* account. It is also strongly suggested that such enhancements are started with
* a recent copy of the source.
*
* The source code page (see http://www.povray.org/beta/source/) sets out the
* conditions under which the developers are willing to accept contributions back
* into the primary source tree. Please refer to those conditions prior to making
* any changes to this source, if you wish to submit those changes for inclusion
* with POV-Ray.
*
*********************************************************************************/
// frame.h must always be the first POV file included (pulls in platform config)
#include "backend/frame.h"
#include "backend/colour/colutils.h"
#include "backend/colour/colour.h"
#include "backend/math/vector.h"
// this must be the last file included
#include "base/povdebug.h"
namespace pov
{
/*****************************************************************************
*
* FUNCTION
*
* colour2photonRgbe
*
* INPUT
*
*
* OUTPUT
*
*
* RETURNS
*
* AUTHOR
*
originally float2rgb
Bruce Walter - http://www.graphics.cornell.edu/online/formats/rgbe/
This file contains code to read and write four byte rgbe file format
developed by Greg Ward. It handles the conversions between rgbe and
pixels consisting of floats. The data is assumed to be an array of floats.
By default there are three floats per pixel in the order red, green, blue.
(RGBE_DATA_??? values control this.) Only the mimimal header reading and
writing is implemented. Each routine does error checking and will return
a status value as defined below. This code is intended as a skeleton so
feel free to modify it to suit your needs.
(Place notice here if you modified the code.)
posted to http://www.graphics.cornell.edu/~bjw/
written by Bruce Walter (bjw@graphics.cornell.edu) 5/26/95
based on code written by Greg Ward
*
* DESCRIPTION
*
* standard conversion from float pixels to rgbe pixels.
*
* CHANGES
*
* May 25, 20020 - incorporated into POV-Ray - Nathan Kopp
* For photons, our exponent will almost always be
* negative, so we use e+250 to get a larger range of negative
* exponents.
*
******************************************************************************/
void colour2photonRgbe(SMALL_COLOUR rgbe, const RGBColour& c)
{
float v;
int e;
v = c[pRED];
if (c[pGREEN] > v) v = c[pGREEN];
if (c[pBLUE] > v) v = c[pBLUE];
if (v < 1e-32) {
rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0;
}
else {
v = frexp(v,&e) * 256.0/v;
rgbe[0] = (unsigned char) (c[pRED] * v);
rgbe[1] = (unsigned char) (c[pGREEN] * v);
rgbe[2] = (unsigned char) (c[pBLUE] * v);
//rgbe[3] = (unsigned char) (e + 128);
rgbe[3] = (unsigned char) (e + 250);
}
}
/*****************************************************************************
*
* FUNCTION
*
* photonRgbe2colour
*
* INPUT
*
*
* OUTPUT
*
*
* RETURNS
*
* AUTHOR
*
originally float2rgb
Bruce Walter - http://www.graphics.cornell.edu/online/formats/rgbe/
This file contains code to read and write four byte rgbe file format
developed by Greg Ward. It handles the conversions between rgbe and
pixels consisting of floats. The data is assumed to be an array of floats.
By default there are three floats per pixel in the order red, green, blue.
(RGBE_DATA_??? values control this.) Only the mimimal header reading and
writing is implemented. Each routine does error checking and will return
a status value as defined below. This code is intended as a skeleton so
feel free to modify it to suit your needs.
(Place notice here if you modified the code.)
posted to http://www.graphics.cornell.edu/~bjw/
written by Bruce Walter (bjw@graphics.cornell.edu) 5/26/95
based on code written by Greg Ward
*
* DESCRIPTION
*
* standard conversion from rgbe to float pixels
* note: Ward uses ldexp(col+0.5,exp-(128+8)). However we wanted pixels
* in the range [0,1] to map back into the range [0,1].
*
* CHANGES
*
* May 25, 20020 - incorporated into POV-Ray - Nathan Kopp
* For photons, our exponent will almost always be
* negative, so we use e+250 to get a larger range of negative
* exponents.
*
******************************************************************************/
void photonRgbe2colour(RGBColour& c, const SMALL_COLOUR rgbe)
{
float f;
if (rgbe[3]) { /*nonzero pixel*/
f = ldexp(1.0,rgbe[3]-(int)(250+8));
c[pRED] = rgbe[0] * f;
c[pGREEN] = rgbe[1] * f;
c[pBLUE] = rgbe[2] * f;
}
else
c.clear();
}
}
| 38.821277 | 83 | 0.644744 | [
"vector"
] |
f886d648178c56aeab0f0ca9556c2a60a4703126 | 572 | cpp | C++ | src/carl/converter/CoCoAAdaptor.cpp | smtrat/carl-windows | 22b3a7677477cdbed9adc7619479ce82a0304666 | [
"MIT"
] | 29 | 2015-05-19T12:17:16.000Z | 2021-03-05T17:53:00.000Z | src/carl/converter/CoCoAAdaptor.cpp | smtrat/carl-windows | 22b3a7677477cdbed9adc7619479ce82a0304666 | [
"MIT"
] | 36 | 2016-10-26T12:47:11.000Z | 2021-03-03T15:19:38.000Z | src/carl/converter/CoCoAAdaptor.cpp | smtrat/carl-windows | 22b3a7677477cdbed9adc7619479ce82a0304666 | [
"MIT"
] | 16 | 2015-05-27T07:35:19.000Z | 2021-03-05T17:53:08.000Z | #include "CoCoAAdaptor.h"
#ifdef USE_COCOA
#include <CoCoA/library.H>
namespace carl {
namespace cocoawrapper {
CoCoA::RingElem gcd(const CoCoA::RingElem& p, const CoCoA::RingElem& q) {
return CoCoA::gcd(p, q);
}
CoCoA::factorization<CoCoA::RingElem> factor(const CoCoA::RingElem& p) {
return CoCoA::factor(p);
}
std::vector<CoCoA::RingElem> ReducedGBasis(const std::vector<CoCoA::RingElem>& p) {
return CoCoA::ReducedGBasis(CoCoA::ideal(p));
}
CoCoA::factorization<CoCoA::RingElem> SqFreeFactor(const CoCoA::RingElem& p) {
return CoCoA::factor(p);
}
}
}
#endif
| 21.185185 | 83 | 0.725524 | [
"vector"
] |
f888af3fcf8c6c2a06ca2115ca092fd4f0e4e966 | 396 | cpp | C++ | leetcode/11_Container With Most Water.cpp | wllvcxz/leetcode | 82358a0946084ba935ca1870b5e3f7c29c03fac3 | [
"MIT"
] | null | null | null | leetcode/11_Container With Most Water.cpp | wllvcxz/leetcode | 82358a0946084ba935ca1870b5e3f7c29c03fac3 | [
"MIT"
] | null | null | null | leetcode/11_Container With Most Water.cpp | wllvcxz/leetcode | 82358a0946084ba935ca1870b5e3f7c29c03fac3 | [
"MIT"
] | null | null | null | #include <vector>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int l = 0;
int r = height.size()-1;
int maxv = 0;
while(l<r){
maxv = max(maxv, (r-l)*min(height[l], height[r]));
if(height[l]<height[r])
l++;
else
r--;
}
return maxv;
}
};
| 19.8 | 62 | 0.431818 | [
"vector"
] |
f889e534ce4365b6aba2122aff6567241e3f896b | 1,072 | cpp | C++ | dataStructure.cpp | rgoettemoeller/Inceptive-Event-Filtering | f8f80f5dd72e438d3fdefd570b54706ca18d67a7 | [
"BSD-4-Clause-UC"
] | 1 | 2021-04-07T14:07:36.000Z | 2021-04-07T14:07:36.000Z | dataStructure.cpp | rgoettemoeller/Inceptive-Event-Filtering | f8f80f5dd72e438d3fdefd570b54706ca18d67a7 | [
"BSD-4-Clause-UC"
] | null | null | null | dataStructure.cpp | rgoettemoeller/Inceptive-Event-Filtering | f8f80f5dd72e438d3fdefd570b54706ca18d67a7 | [
"BSD-4-Clause-UC"
] | null | null | null | #include "dataStructure.h"
#include "inputCameraData_generated.h"
using namespace std;
using namespace Camera::Data;
//imports the data into a sorted array of structs
void fillTimeArray(values *ValuesElement, unsigned long long timeValue, short p)
{
for(int i = 0; i < sizeof(ValuesElement->t); i++)
{
if(ValuesElement->t[i] == 0)
{
ValuesElement->t[i] = timeValue;
ValuesElement->p = ((ValuesElement->p) << 1) | p;
break;
}
}
}
//copies the data to a medium that can be stored in the buffer
//This was a workaround to a bug encountered where I could not just save
//the same vector of import data as it was into a new buffer.
void convertOriginalData(const flatbuffers::Vector<const Camera::Data::dataPoint*>* importDataVector, dataPoint *exportedData)
{
for(int i = 0; i < importDataVector->size(); i++){
exportedData[i] = dataPoint(importDataVector->Get(i)->x(), importDataVector->Get(i)->y(), importDataVector->Get(i)->time(), importDataVector->Get(i)->polarity());
}
} | 36.965517 | 170 | 0.663246 | [
"vector"
] |
f88effd2bbb589f0c6146264c8c1267ee21c2ea7 | 99,157 | cc | C++ | src/clang_indexer.cc | ioperations/cquery | 0b99257bb8f5f19d979b6c0cf916758beca1bcd9 | [
"MIT"
] | null | null | null | src/clang_indexer.cc | ioperations/cquery | 0b99257bb8f5f19d979b6c0cf916758beca1bcd9 | [
"MIT"
] | null | null | null | src/clang_indexer.cc | ioperations/cquery | 0b99257bb8f5f19d979b6c0cf916758beca1bcd9 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cassert>
#include <chrono>
#include <climits>
#include <iostream>
#include <loguru.hpp>
#include "clang_cursor.h"
#include "clang_utils.h"
#include "indexer.h"
#include "platform.h"
#include "serializer.h"
#include "timer.h"
#include "type_printer.h"
// TODO: See if we can use clang_indexLoc_getFileLocation to get a type ref on
// |Foobar| in DISALLOW_COPY(Foobar)
#if CINDEX_VERSION >= 47
#define CINDEX_HAVE_PRETTY 1
#endif
#if CINDEX_VERSION >= 48
#define CINDEX_HAVE_ROLE 1
#endif
namespace {
// For typedef/using spanning less than or equal to (this number) of lines,
// display their declarations on hover.
constexpr int k_max_lines_display_type_alias_declarations = 3;
// TODO How to check if a reference to type is a declaration?
// This currently also includes constructors/destructors.
// It seems declarations in functions are not indexed.
bool IsDeclContext(CXIdxEntityKind kind) {
switch (kind) {
case CXIdxEntity_CXXClass:
case CXIdxEntity_CXXNamespace:
case CXIdxEntity_ObjCCategory:
case CXIdxEntity_ObjCClass:
case CXIdxEntity_ObjCProtocol:
case CXIdxEntity_Struct:
return true;
default:
return false;
}
}
role GetRole(const CXIdxEntityRefInfo* ref_info, role role) {
#if CINDEX_HAVE_ROLE
return static_cast<enum role>(static_cast<int>(ref_info->role));
#else
return role;
#endif
}
SymbolKind GetSymbolKind(CXCursorKind kind) {
switch (kind) {
case CXCursor_TranslationUnit:
return SymbolKind::File;
case CXCursor_FunctionDecl:
case CXCursor_CXXMethod:
case CXCursor_Constructor:
case CXCursor_Destructor:
case CXCursor_ConversionFunction:
case CXCursor_FunctionTemplate:
case CXCursor_OverloadedDeclRef:
case CXCursor_LambdaExpr:
case CXCursor_ObjCInstanceMethodDecl:
case CXCursor_ObjCClassMethodDecl:
return SymbolKind::Func;
case CXCursor_StructDecl:
case CXCursor_UnionDecl:
case CXCursor_ClassDecl:
case CXCursor_EnumDecl:
case CXCursor_ObjCInterfaceDecl:
case CXCursor_ObjCCategoryDecl:
case CXCursor_ObjCImplementationDecl:
case CXCursor_Namespace:
return SymbolKind::Type;
default:
return SymbolKind::Invalid;
}
}
// Inverse of libclang/CXIndexDataConsumer.cpp getEntityKindFromSymbolKind
ls_symbol_kind GetSymbolKind(CXIdxEntityKind kind) {
switch (kind) {
case CXIdxEntity_Unexposed:
return ls_symbol_kind::Unknown;
case CXIdxEntity_Typedef:
return ls_symbol_kind::TypeAlias;
case CXIdxEntity_Function:
return ls_symbol_kind::Function;
case CXIdxEntity_Variable:
// Can also be Parameter
return ls_symbol_kind::Variable;
case CXIdxEntity_Field:
return ls_symbol_kind::Field;
case CXIdxEntity_EnumConstant:
return ls_symbol_kind::EnumMember;
case CXIdxEntity_ObjCClass:
return ls_symbol_kind::Class;
case CXIdxEntity_ObjCProtocol:
return ls_symbol_kind::Interface;
case CXIdxEntity_ObjCCategory:
return ls_symbol_kind::Interface;
case CXIdxEntity_ObjCInstanceMethod:
return ls_symbol_kind::Method;
case CXIdxEntity_ObjCClassMethod:
return ls_symbol_kind::StaticMethod;
case CXIdxEntity_ObjCProperty:
return ls_symbol_kind::Property;
case CXIdxEntity_ObjCIvar:
return ls_symbol_kind::Field;
case CXIdxEntity_Enum:
return ls_symbol_kind::Enum;
case CXIdxEntity_Struct:
case CXIdxEntity_Union:
return ls_symbol_kind::Struct;
case CXIdxEntity_CXXClass:
return ls_symbol_kind::Class;
case CXIdxEntity_CXXNamespace:
return ls_symbol_kind::Namespace;
case CXIdxEntity_CXXNamespaceAlias:
return ls_symbol_kind::Namespace;
case CXIdxEntity_CXXStaticVariable:
return ls_symbol_kind::Field;
case CXIdxEntity_CXXStaticMethod:
return ls_symbol_kind::StaticMethod;
case CXIdxEntity_CXXInstanceMethod:
return ls_symbol_kind::Method;
case CXIdxEntity_CXXConstructor:
return ls_symbol_kind::Constructor;
case CXIdxEntity_CXXDestructor:
return ls_symbol_kind::Method;
case CXIdxEntity_CXXConversionFunction:
return ls_symbol_kind::Constructor;
case CXIdxEntity_CXXTypeAlias:
return ls_symbol_kind::TypeAlias;
case CXIdxEntity_CXXInterface:
return ls_symbol_kind::Struct;
}
return ls_symbol_kind::Unknown;
}
storage_class GetStorageClass(CX_StorageClass storage) {
switch (storage) {
case CX_SC_Invalid:
case CX_SC_OpenCLWorkGroupLocal:
return storage_class::Invalid;
case CX_SC_None:
return storage_class::None;
case CX_SC_Extern:
return storage_class::Extern;
case CX_SC_Static:
return storage_class::Static;
case CX_SC_PrivateExtern:
return storage_class::PrivateExtern;
case CX_SC_Auto:
return storage_class::Auto;
case CX_SC_Register:
return storage_class::Register;
}
return storage_class::None;
}
// Caches all instances of constructors, regardless if they are indexed or not.
// The constructor may have a make_unique call associated with it that we need
// to export. If we do not capture the parameter type description for the
// constructor we will not be able to attribute the constructor call correctly.
struct ConstructorCache {
struct Constructor {
Usr usr;
std::vector<std::string> param_type_desc;
};
std::unordered_map<Usr, std::vector<Constructor>> constructors;
// This should be called whenever there is a constructor declaration.
void NotifyConstructor(ClangCursor ctor_cursor) {
auto build_type_desc = [](ClangCursor cursor) {
std::vector<std::string> type_desc;
for (ClangCursor arg : cursor.get_arguments()) {
if (arg.get_kind() == CXCursor_ParmDecl)
type_desc.push_back(arg.get_type_description());
}
return type_desc;
};
Constructor ctor{ctor_cursor.get_usr_hash(),
build_type_desc(ctor_cursor)};
// Insert into |constructors_|.
auto type_usr_hash = ctor_cursor.get_semantic_parent().get_usr_hash();
auto existing_ctors = constructors.find(type_usr_hash);
if (existing_ctors != constructors.end()) {
existing_ctors->second.push_back(ctor);
} else {
constructors[type_usr_hash] = {ctor};
}
}
// Tries to lookup a constructor in |type_usr| that takes arguments most
// closely aligned to |param_type_desc|.
optional<Usr> TryFindConstructorUsr(
Usr type_usr, const std::vector<std::string>& param_type_desc) {
auto count_matching_prefix_length = [](const char* a, const char* b) {
int matched = 0;
while (*a && *b) {
if (*a != *b) break;
++a;
++b;
++matched;
}
// Additional score if the strings were the same length, which makes
// "a"/"a" match higher than "a"/"a&"
if (*a == *b) matched += 1;
return matched;
};
// Try to find constructors for the type. If there are no constructors
// available, return an empty result.
auto ctors_it = constructors.find(type_usr);
if (ctors_it == constructors.end()) return nullopt;
const std::vector<Constructor>& ctors = ctors_it->second;
if (ctors.empty()) return nullopt;
Usr best_usr = ctors[0].usr;
int best_score = INT_MIN;
// Scan constructors for the best possible match.
for (const Constructor& ctor : ctors) {
// If |param_type_desc| is empty and the constructor is as well, we
// don't need to bother searching, as this is the match.
if (param_type_desc.empty() && ctor.param_type_desc.empty()) {
best_usr = ctor.usr;
break;
}
// Weight matching parameter length heavily, as it is more accurate
// than the fuzzy type matching approach.
int score = 0;
if (param_type_desc.size() == ctor.param_type_desc.size())
score += param_type_desc.size() * 1000;
// Do prefix-based match on parameter type description. This works
// well in practice because clang appends qualifiers to the end of
// the type, ie, |foo *&&|
for (size_t i = 0; i < std::min(param_type_desc.size(),
ctor.param_type_desc.size());
++i) {
score += count_matching_prefix_length(
param_type_desc[i].c_str(),
ctor.param_type_desc[i].c_str());
}
if (score > best_score) {
best_usr = ctor.usr;
best_score = score;
}
}
return best_usr;
}
};
struct IndexParam {
std::unordered_set<CXFile> seen_cx_files;
std::vector<AbsolutePath> seen_files;
std::unordered_map<AbsolutePath, FileContents> file_contents;
// Only use this when strictly needed (ie, primary translation unit is
// needed). Most logic should get the IndexFile instance via
// |file_consumer|.
//
// This can be null if we're not generating an index for the primary
// translation unit.
IndexFile* primary_file = nullptr;
ClangTranslationUnit* tu = nullptr;
FileConsumer* file_consumer = nullptr;
NamespaceHelper ns;
ConstructorCache ctors;
IndexParam(ClangTranslationUnit* tu, FileConsumer* file_consumer)
: tu(tu), file_consumer(file_consumer) {}
#if CINDEX_HAVE_PRETTY
CXPrintingPolicy print_policy = nullptr;
CXPrintingPolicy print_policy_more = nullptr;
~IndexParam() {
clang_PrintingPolicy_dispose(print_policy);
clang_PrintingPolicy_dispose(print_policy_more);
}
std::string PrettyPrintCursor(CXCursor cursor, bool initializer = true) {
if (!print_policy) {
print_policy = clang_getCursorPrintingPolicy(cursor);
clang_PrintingPolicy_setProperty(print_policy,
CXPrintingPolicy_TerseOutput, 1);
clang_PrintingPolicy_setProperty(
print_policy, CXPrintingPolicy_FullyQualifiedName, 1);
clang_PrintingPolicy_setProperty(
print_policy, CXPrintingPolicy_SuppressInitializers, 1);
print_policy_more = clang_getCursorPrintingPolicy(cursor);
clang_PrintingPolicy_setProperty(
print_policy_more, CXPrintingPolicy_FullyQualifiedName, 1);
clang_PrintingPolicy_setProperty(print_policy_more,
CXPrintingPolicy_TerseOutput, 1);
}
return ToString(clang_getCursorPrettyPrinted(
cursor, initializer ? print_policy_more : print_policy));
}
#endif
};
IndexFile* ConsumeFile(IndexParam* param, CXFile file) {
bool is_first_ownership = false;
IndexFile* db =
param->file_consumer->TryConsumeFile(file, &is_first_ownership);
// If we are generating an index for the file:
if (db && is_first_ownership) {
// Fetch indexed file contents from libclang.
size_t size;
const char* contents_ptr =
clang_getFileContents(param->tu->cx_tu, file, &size);
std::string contents(contents_ptr, size);
// Update cached file contents.
db->file_contents = contents;
// Setup quick access to line offsets with the file.
param->file_contents[db->path] = FileContents(db->path, contents);
// Set modification time.
db->last_modification_time = clang_getFileTime(file);
}
// Register that we saw this file even if it is not being indexed so that we
// can generate a dependency graph.
if (param->seen_cx_files.insert(file).second) {
optional<AbsolutePath> file_name = FileName(file);
// file_name may be empty when it contains .. and is outside of
// WorkingDir. https://reviews.llvm.org/D42893
// https://github.com/cquery-project/cquery/issues/413
if (file_name && !file_name->path.empty())
param->seen_files.push_back(*file_name);
}
if (is_first_ownership) {
// Report skipped source range list.
CXSourceRangeList* skipped =
clang_getSkippedRanges(param->tu->cx_tu, file);
for (unsigned i = 0; i < skipped->count; ++i) {
Range range = ResolveCXSourceRange(skipped->ranges[i]);
db->skipped_by_preprocessor.push_back(range);
}
clang_disposeSourceRangeList(skipped);
}
return db;
}
// Returns true if the given entity kind can be called implicitly, ie, without
// actually being written in the source code.
bool CanBeCalledImplicitly(CXIdxEntityKind kind) {
switch (kind) {
case CXIdxEntity_CXXConstructor:
case CXIdxEntity_CXXConversionFunction:
case CXIdxEntity_CXXDestructor:
return true;
default:
return false;
}
}
// Returns true if the cursor spelling contains the given string. This is
// useful to check for implicit function calls.
bool CursorSpellingContainsString(CXCursor cursor, CXTranslationUnit cx_tu,
std::string_view needle) {
CXSourceRange range = clang_Cursor_getSpellingNameRange(cursor, 0, 0);
CXToken* tokens;
unsigned num_tokens;
clang_tokenize(cx_tu, range, &tokens, &num_tokens);
bool result = false;
for (unsigned i = 0; i < num_tokens; ++i) {
CXString name = clang_getTokenSpelling(cx_tu, tokens[i]);
if (needle == clang_getCString(name)) {
result = true;
break;
}
clang_disposeString(name);
}
clang_disposeTokens(cx_tu, tokens, num_tokens);
return result;
}
// Returns the document content for the given range. May not work perfectly
// when there are tabs instead of spaces.
std::string GetDocumentContentInRange(CXTranslationUnit cx_tu,
CXSourceRange range) {
std::string result;
CXToken* tokens;
unsigned num_tokens;
clang_tokenize(cx_tu, range, &tokens, &num_tokens);
optional<Range> previous_token_range;
for (unsigned i = 0; i < num_tokens; ++i) {
// Add whitespace between the previous token and this one.
Range token_range =
ResolveCXSourceRange(clang_getTokenExtent(cx_tu, tokens[i]));
if (previous_token_range) {
// Insert newlines.
int16_t line_delta =
token_range.start.line - previous_token_range->end.line;
assert(line_delta >= 0);
if (line_delta > 0) {
result.append((size_t)line_delta, '\n');
// Reset column so we insert starting padding.
previous_token_range->end.column = 0;
}
// Insert spaces.
int16_t column_delta =
token_range.start.column - previous_token_range->end.column;
assert(column_delta >= 0);
result.append((size_t)column_delta, ' ');
}
previous_token_range = token_range;
// Add token content.
CXString spelling = clang_getTokenSpelling(cx_tu, tokens[i]);
result += clang_getCString(spelling);
clang_disposeString(spelling);
}
clang_disposeTokens(cx_tu, tokens, num_tokens);
return result;
}
void SetUsePreflight(IndexFile* db, ClangCursor parent) {
switch (GetSymbolKind(parent.get_kind())) {
case SymbolKind::Func:
(void)db->ToFuncId(parent.cx_cursor);
break;
case SymbolKind::Type:
(void)db->ToTypeId(parent.cx_cursor);
break;
case SymbolKind::Var:
(void)db->ToVarId(parent.cx_cursor);
break;
default:
break;
}
}
// |parent| should be resolved before using |SetUsePreflight| so that |def| will
// not be invalidated by |To{Func,Type,Var}Id|.
IndexId::LexicalRef SetUse(IndexFile* db, Range range, ClangCursor parent,
role role) {
switch (GetSymbolKind(parent.get_kind())) {
case SymbolKind::Func:
return IndexId::LexicalRef(range, db->ToFuncId(parent.cx_cursor),
SymbolKind::Func, role);
case SymbolKind::Type:
return IndexId::LexicalRef(range, db->ToTypeId(parent.cx_cursor),
SymbolKind::Type, role);
case SymbolKind::Var:
return IndexId::LexicalRef(range, db->ToVarId(parent.cx_cursor),
SymbolKind::Var, role);
default:
return IndexId::LexicalRef(range, AnyId(), SymbolKind::File, role);
}
}
// |parent| should be resolved before using |SetUsePreflight| so that |def| will
// not be invalidated by |To{Func,Type,Var}Id|.
IndexId::LexicalRef SetRef(IndexFile* db, Range range, ClangCursor parent,
role role) {
switch (GetSymbolKind(parent.get_kind())) {
case SymbolKind::Func:
return IndexId::LexicalRef(range, db->ToFuncId(parent.cx_cursor),
SymbolKind::Func, role);
case SymbolKind::Type:
return IndexId::LexicalRef(range, db->ToTypeId(parent.cx_cursor),
SymbolKind::Type, role);
case SymbolKind::Var:
return IndexId::LexicalRef(range, db->ToVarId(parent.cx_cursor),
SymbolKind::Var, role);
default:
return IndexId::LexicalRef(range, AnyId(), SymbolKind::File, role);
}
}
const char* GetAnonName(CXCursorKind kind) {
switch (kind) {
case CXCursor_ClassDecl:
return "(anon class)";
case CXCursor_EnumDecl:
return "(anon enum)";
case CXCursor_StructDecl:
return "(anon struct)";
case CXCursor_UnionDecl:
return "(anon union)";
default:
return "(anon)";
}
}
void SetTypeName(IndexType* type, const ClangCursor& cursor,
const CXIdxContainerInfo* container, const char* name,
IndexParam* param) {
CXIdxContainerInfo parent;
// |name| can be null in an anonymous struct (see
// tests/types/anonymous_struct.cc).
if (!name) name = GetAnonName(cursor.get_kind());
if (!container) parent.cursor = cursor.get_semantic_parent().cx_cursor;
// Investigate why clang_getCursorPrettyPrinted gives `struct A {}`
// `namespace ns {}` which are not qualified. type->def.detailed_name =
// param->PrettyPrintCursor(cursor.cx_cursor);
type->def.detailed_name =
param->ns.QualifiedName(container ? container : &parent, name);
auto idx = type->def.detailed_name.rfind(name);
assert(idx != std::string::npos);
type->def.short_name_offset = idx;
type->def.short_name_size = strlen(name);
}
// Finds the cursor associated with the declaration type of |cursor|. This
// strips
// qualifies from |cursor| (ie, Foo* => Foo) and removes template arguments
// (ie, Foo<A,B> => Foo<*,*>).
optional<IndexId::Type> ResolveToDeclarationType(IndexFile* db,
ClangCursor cursor,
IndexParam* param) {
ClangType type = cursor.get_type();
// auto x = new Foo() will not be deduced to |Foo| if we do not use the
// canonical type. However, a canonical type will look past typedefs so we
// will not accurately report variables on typedefs if we always do this.
if (type.cx_type.kind == CXType_Auto) type = type.get_canonical();
type = type.strip_qualifiers();
if (type.is_builtin()) {
// For builtin types, use type kinds as USR hash.
return db->ToTypeId(type.cx_type.kind);
}
ClangCursor declaration =
type.get_declaration().template_specialization_to_template_definition();
optional<Usr> usr = declaration.get_opt_usr_hash();
if (!usr) return nullopt;
IndexId::Type type_id = db->ToTypeId(*usr);
IndexType* typ = db->Resolve(type_id);
if (typ->def.detailed_name.empty()) {
std::string name = declaration.get_spell_name();
SetTypeName(typ, declaration, nullptr, name.c_str(), param);
}
return type_id;
}
void SetVarDetail(IndexVar* var, std::string_view short_name,
const ClangCursor& cursor,
const CXIdxContainerInfo* semantic_container,
bool is_first_seen, IndexFile* db, IndexParam* param) {
IndexVar::Def& def = var->def;
const CXType cx_type = clang_getCursorType(cursor.cx_cursor);
std::string type_name = ToString(clang_getTypeSpelling(cx_type));
// clang may report "(lambda at foo.cc)" which end up being a very long
// string. Shorten it to just "lambda".
if (type_name.find("(lambda at") != std::string::npos) type_name = "lambda";
if (g_config->index.comments) def.comments = cursor.get_comments();
def.storage =
GetStorageClass(clang_Cursor_getStorageClass(cursor.cx_cursor));
// TODO how to make PrettyPrint'ed variable name qualified?
std::string qualified_name =
#if 0 && CINDEX_HAVE_PRETTY
cursor.get_kind() != CXCursor_EnumConstantDecl
? param->PrettyPrintCursor(cursor.cx_cursor)
:
#endif
param->ns.QualifiedName(semantic_container, short_name);
if (cursor.get_kind() == CXCursor_EnumConstantDecl && semantic_container) {
CXType enum_type = clang_getCanonicalType(
clang_getEnumDeclIntegerType(semantic_container->cursor));
std::string hover = qualified_name + " = ";
if (enum_type.kind == CXType_UInt || enum_type.kind == CXType_ULong ||
enum_type.kind == CXType_ULongLong)
hover += std::to_string(
clang_getEnumConstantDeclUnsignedValue(cursor.cx_cursor));
else
hover += std::to_string(
clang_getEnumConstantDeclValue(cursor.cx_cursor));
def.detailed_name = std::move(qualified_name);
def.hover = hover;
} else {
#if 0 && CINDEX_HAVE_PRETTY
//def.detailed_name = param->PrettyPrintCursor(cursor.cx_cursor, false);
#else
ConcatTypeAndName(type_name, qualified_name);
def.detailed_name = type_name;
// Append the textual initializer, bit field, constructor to |hover|.
// Omit |hover| for these types:
// int (*a)(); int (&a)(); int (&&a)(); int a[1]; auto x = ...
// We can take these into consideration after we have better support for
// inside-out syntax.
CXType deref = cx_type;
while (deref.kind == CXType_Pointer ||
deref.kind == CXType_MemberPointer ||
deref.kind == CXType_LValueReference ||
deref.kind == CXType_RValueReference)
deref = clang_getPointeeType(deref);
if (deref.kind != CXType_Unexposed && deref.kind != CXType_Auto &&
clang_getResultType(deref).kind == CXType_Invalid &&
clang_getElementType(deref).kind == CXType_Invalid) {
const FileContents& fc = param->file_contents[db->path];
optional<int> spell_end = fc.ToOffset(cursor.get_spell().end);
optional<int> extent_end = fc.ToOffset(cursor.get_extent().end);
if (extent_end && *spell_end < *extent_end)
def.hover =
std::string(def.detailed_name.c_str()) +
fc.content.substr(*spell_end, *extent_end - *spell_end);
}
#endif
}
// FIXME QualifiedName should return index
auto idx = def.detailed_name.rfind(short_name.begin(), std::string::npos,
short_name.size());
assert(idx != std::string::npos);
def.short_name_offset = idx;
def.short_name_size = short_name.size();
if (is_first_seen) {
optional<IndexId::Type> var_type =
ResolveToDeclarationType(db, cursor, param);
if (var_type) {
// Don't treat enum definition variables as instantiations.
bool is_enum_member =
semantic_container &&
semantic_container->cursor.kind == CXCursor_EnumDecl;
if (!is_enum_member)
db->Resolve(var_type.value())->instances.push_back(var->id);
def.type = *var_type;
}
}
}
void OnIndexReferenceFunction(IndexFile* db, Range loc,
ClangCursor parent_cursor,
IndexId::Func called_id, role role) {
switch (GetSymbolKind(parent_cursor.get_kind())) {
case SymbolKind::Func: {
IndexFunc* parent =
db->Resolve(db->ToFuncId(parent_cursor.cx_cursor));
IndexFunc* called = db->Resolve(called_id);
parent->def.callees.push_back(
IndexId::SymbolRef(loc, called->id, SymbolKind::Func, role));
called->uses.push_back(
IndexId::LexicalRef(loc, parent->id, SymbolKind::Func, role));
break;
}
case SymbolKind::Type: {
IndexType* parent =
db->Resolve(db->ToTypeId(parent_cursor.cx_cursor));
IndexFunc* called = db->Resolve(called_id);
called = db->Resolve(called_id);
called->uses.push_back(
IndexId::LexicalRef(loc, parent->id, SymbolKind::Type, role));
break;
}
default: {
IndexFunc* called = db->Resolve(called_id);
called->uses.push_back(
IndexId::LexicalRef(loc, AnyId(), SymbolKind::File, role));
break;
}
}
}
template <typename T>
void Uniquify(std::vector<Id<T>>& ids) {
std::unordered_set<Id<T>> seen;
size_t n = 0;
for (size_t i = 0; i < ids.size(); i++)
if (seen.insert(ids[i]).second) ids[n++] = ids[i];
ids.resize(n);
}
void Uniquify(std::vector<IndexId::LexicalRef>& refs) {
std::unordered_set<Range> seen;
size_t n = 0;
for (size_t i = 0; i < refs.size(); i++)
if (seen.insert(refs[i].range).second) refs[n++] = refs[i];
refs.resize(n);
}
} // namespace
// static
const int IndexFile::kMajorVersion = 16;
// static
const int IndexFile::kMinorVersion = 0;
IndexFile::IndexFile(const AbsolutePath& path)
: id_cache(path), path(path), file_contents("#error <NONE>") {}
IndexId::Type IndexFile::ToTypeId(Usr usr) {
auto it = id_cache.usr_to_type_id.find(usr);
if (it != id_cache.usr_to_type_id.end()) return it->second;
IndexId::Type id(types.size());
types.push_back(IndexType(id, usr));
id_cache.usr_to_type_id[usr] = id;
id_cache.type_id_to_usr[id] = usr;
return id;
}
IndexId::Func IndexFile::ToFuncId(Usr usr) {
auto it = id_cache.usr_to_func_id.find(usr);
if (it != id_cache.usr_to_func_id.end()) return it->second;
IndexId::Func id(funcs.size());
funcs.push_back(IndexFunc(id, usr));
id_cache.usr_to_func_id[usr] = id;
id_cache.func_id_to_usr[id] = usr;
return id;
}
IndexId::Var IndexFile::ToVarId(Usr usr) {
auto it = id_cache.usr_to_var_id.find(usr);
if (it != id_cache.usr_to_var_id.end()) return it->second;
IndexId::Var id(vars.size());
vars.push_back(IndexVar(id, usr));
id_cache.usr_to_var_id[usr] = id;
id_cache.var_id_to_usr[id] = usr;
return id;
}
IndexId::Type IndexFile::ToTypeId(const CXCursor& cursor) {
return ToTypeId(ClangCursor(cursor).get_usr_hash());
}
IndexId::Func IndexFile::ToFuncId(const CXCursor& cursor) {
return ToFuncId(ClangCursor(cursor).get_usr_hash());
}
IndexId::Var IndexFile::ToVarId(const CXCursor& cursor) {
return ToVarId(ClangCursor(cursor).get_usr_hash());
}
IndexType* IndexFile::Resolve(IndexId::Type id) { return &types[id.id]; }
IndexFunc* IndexFile::Resolve(IndexId::Func id) { return &funcs[id.id]; }
IndexVar* IndexFile::Resolve(IndexId::Var id) { return &vars[id.id]; }
std::string IndexFile::ToString() {
return Serialize(serialize_format::Json, *this);
}
IndexType::IndexType(IndexId::Type id, Usr usr) : usr(usr), id(id) {}
void AddRef(IndexFile* db, std::vector<IndexId::LexicalRef>& refs, Range range,
ClangCursor parent, role role = role::Reference) {
switch (GetSymbolKind(parent.get_kind())) {
case SymbolKind::Func:
refs.push_back(IndexId::LexicalRef(
range, db->ToFuncId(parent.cx_cursor), SymbolKind::Func, role));
break;
case SymbolKind::Type:
refs.push_back(IndexId::LexicalRef(
range, db->ToTypeId(parent.cx_cursor), SymbolKind::Type, role));
break;
default:
refs.push_back(
IndexId::LexicalRef(range, AnyId(), SymbolKind::File, role));
break;
}
}
void AddRefSpell(IndexFile* db, std::vector<IndexId::LexicalRef>& refs,
ClangCursor cursor) {
AddRef(db, refs, cursor.get_spell(), cursor.get_lexical_parent().cx_cursor);
}
CXCursor FromContainer(const CXIdxContainerInfo* parent) {
return parent ? parent->cursor : clang_getNullCursor();
}
IdCache::IdCache(const AbsolutePath& primary_file)
: primary_file(primary_file) {}
void OnIndexDiagnostic(CXClientData client_data, CXDiagnosticSet diagnostics,
void* reserved) {
IndexParam* param = static_cast<IndexParam*>(client_data);
for (unsigned i = 0; i < clang_getNumDiagnosticsInSet(diagnostics); ++i) {
CXDiagnostic diagnostic = clang_getDiagnosticInSet(diagnostics, i);
CXSourceLocation diag_loc = clang_getDiagnosticLocation(diagnostic);
// Skip diagnostics in system headers.
// if (clang_Location_isInSystemHeader(diag_loc))
// continue;
// Get db so we can attribute diagnostic to the right indexed file.
CXFile file;
unsigned int line, column;
clang_getSpellingLocation(diag_loc, &file, &line, &column, nullptr);
// Skip empty diagnostic.
if (!line && !column) continue;
IndexFile* db = ConsumeFile(param, file);
if (!db) continue;
// Build diagnostic.
optional<lsDiagnostic> ls_diagnostic =
BuildAndDisposeDiagnostic(diagnostic, db->path);
// Check to see if we have already reported this diagnostic, as
// sometimes libclang will report the same diagnostic twice. See
// https://github.com/cquery-project/cquery/issues/594 for a repro.
if (ls_diagnostic && !ContainsValue(db->diagnostics_, *ls_diagnostic))
db->diagnostics_.push_back(*ls_diagnostic);
}
}
CXIdxClientFile OnIndexIncludedFile(CXClientData client_data,
const CXIdxIncludedFileInfo* file) {
IndexParam* param = static_cast<IndexParam*>(client_data);
// file->hashLoc only has the position of the hash. We don't have the full
// range for the include.
CXSourceLocation hash_loc =
clang_indexLoc_getCXSourceLocation(file->hashLoc);
CXFile cx_file;
unsigned int line;
clang_getSpellingLocation(hash_loc, &cx_file, &line, nullptr, nullptr);
line--;
IndexFile* db = ConsumeFile(param, cx_file);
if (!db) return nullptr;
optional<AbsolutePath> include_path = FileName(file->file);
if (!include_path) return nullptr;
IndexInclude include;
include.line = line;
include.resolved_path = include_path->path;
if (!include.resolved_path.empty()) db->includes.push_back(include);
return nullptr;
}
ClangCursor::VisitResult DumpVisitor(ClangCursor cursor, ClangCursor parent,
int* level) {
for (int i = 0; i < *level; ++i) std::cerr << " ";
std::cerr << ToString(cursor.get_kind()) << " " << cursor.get_spell_name()
<< std::endl;
*level += 1;
cursor.VisitChildren(&DumpVisitor, level);
*level -= 1;
return ClangCursor::VisitResult::Continue;
}
void Dump(ClangCursor cursor) {
int level = 0;
cursor.VisitChildren(&DumpVisitor, &level);
}
struct FindChildOfKindParam {
CXCursorKind target_kind;
optional<ClangCursor> result;
FindChildOfKindParam(CXCursorKind target_kind) : target_kind(target_kind) {}
};
ClangCursor::VisitResult FindTypeVisitor(ClangCursor cursor, ClangCursor parent,
optional<ClangCursor>* result) {
switch (cursor.get_kind()) {
case CXCursor_TypeRef:
case CXCursor_TemplateRef:
*result = cursor;
return ClangCursor::VisitResult::Break;
default:
break;
}
return ClangCursor::VisitResult::Recurse;
}
optional<ClangCursor> FindType(ClangCursor cursor) {
optional<ClangCursor> result;
cursor.VisitChildren(&FindTypeVisitor, &result);
return result;
}
bool IsTypeDefinition(const CXIdxContainerInfo* container) {
if (!container) return false;
return GetSymbolKind(container->cursor.kind) == SymbolKind::Type;
}
struct VisitDeclForTypeUsageParam {
IndexFile* db;
optional<IndexId::Type> toplevel_type;
int has_processed_any = false;
optional<ClangCursor> previous_cursor;
optional<IndexId::Type> initial_type;
VisitDeclForTypeUsageParam(IndexFile* db,
optional<IndexId::Type> toplevel_type)
: db(db), toplevel_type(toplevel_type) {}
};
void VisitDeclForTypeUsageVisitorHandler(ClangCursor cursor,
VisitDeclForTypeUsageParam* param) {
param->has_processed_any = true;
IndexFile* db = param->db;
// For |A<int> a| where there is a specialization for |A<int>|,
// the |referenced_usr| below resolves to the primary template and
// attributes the use to the primary template instead of the specialization.
// |toplevel_type| is retrieved |clang_getCursorType| which can be a
// specialization. If its name is the same as the primary template's, we
// assume the use should be attributed to the specialization. This heuristic
// fails when a member class bears the same name with its container.
//
// template<class T>
// struct C { struct C {}; };
// C<int>::C a;
//
// We will attribute |::C| to the parent class.
if (param->toplevel_type) {
IndexType* ref_type = db->Resolve(*param->toplevel_type);
std::string name = cursor.get_referenced().get_spell_name();
if (name == ref_type->def.ShortName()) {
AddRefSpell(db, ref_type->uses, cursor);
param->toplevel_type = nullopt;
return;
}
}
optional<Usr> referenced_usr =
cursor.get_referenced()
.template_specialization_to_template_definition()
.get_opt_usr_hash();
// May be empty, happens in STL.
if (!referenced_usr) return;
IndexId::Type ref_type_id = db->ToTypeId(*referenced_usr);
if (!param->initial_type) param->initial_type = ref_type_id;
IndexType* ref_type_def = db->Resolve(ref_type_id);
// TODO: Should we even be visiting this if the file is not from the main
// def? Try adding assert on |loc| later.
AddRefSpell(db, ref_type_def->uses, cursor);
}
ClangCursor::VisitResult VisitDeclForTypeUsageVisitor(
ClangCursor cursor, ClangCursor parent, VisitDeclForTypeUsageParam* param) {
switch (cursor.get_kind()) {
case CXCursor_TemplateRef:
case CXCursor_TypeRef:
if (param->previous_cursor) {
VisitDeclForTypeUsageVisitorHandler(
param->previous_cursor.value(), param);
}
param->previous_cursor = cursor;
return ClangCursor::VisitResult::Continue;
// We do not want to recurse for everything, since if we do that we will
// end up visiting method definition bodies/etc. Instead, we only
// recurse for things that can logically appear as part of an inline
// variable initializer, ie,
//
// class Foo {
// int x = (Foo)3;
// }
case CXCursor_CallExpr:
case CXCursor_CStyleCastExpr:
case CXCursor_CXXStaticCastExpr:
case CXCursor_CXXReinterpretCastExpr:
return ClangCursor::VisitResult::Recurse;
default:
return ClangCursor::VisitResult::Continue;
}
return ClangCursor::VisitResult::Continue;
}
// Add usages to any seen TypeRef or TemplateRef under the given |decl_cursor|.
// This returns the first seen TypeRef or TemplateRef value, which can be
// useful if trying to figure out ie, what a using statement refers to. If
// trying to generally resolve a cursor to a type, use
// ResolveToDeclarationType, which works in more scenarios.
// If |decl_cursor| is a variable of a template type, clang_getCursorType
// may return a specialized template which is preciser than the primary
// template.
// We use |toplevel_type| to attribute the use to the specialized template
// instead of the primary template.
optional<IndexId::Type> AddDeclTypeUsages(
IndexFile* db, ClangCursor decl_cursor,
optional<IndexId::Type> toplevel_type,
const CXIdxContainerInfo* semantic_container,
const CXIdxContainerInfo* lexical_container) {
//
// The general AST format for definitions follows this pattern:
//
// template<typename A, typename B>
// struct Container;
//
// struct S1;
// struct S2;
//
// Container<Container<S1, S2>, S2> foo;
//
// =>
//
// VarDecl
// TemplateRef Container
// TemplateRef Container
// TypeRef struct S1
// TypeRef struct S2
// TypeRef struct S2
//
//
// Here is another example:
//
// enum A {};
// enum B {};
//
// template<typename T>
// struct Foo {
// struct Inner {};
// };
//
// Foo<A>::Inner a;
// Foo<B> b;
//
// =>
//
// EnumDecl A
// EnumDecl B
// ClassTemplate Foo
// TemplateTypeParameter T
// StructDecl Inner
// VarDecl a
// TemplateRef Foo
// TypeRef enum A
// TypeRef struct Foo<enum A>::Inner
// CallExpr Inner
// VarDecl b
// TemplateRef Foo
// TypeRef enum B
// CallExpr Foo
//
//
// Determining the actual type of the variable/declaration from just the
// children is tricky. Doing so would require looking up the template
// definition associated with a TemplateRef, figuring out how many children
// it has, and then skipping that many TypeRef values. This also has to work
// with the example below (skipping the last TypeRef). As a result, we
// determine variable types using |ResolveToDeclarationType|.
//
//
// We skip the last type reference for methods/variables which are defined
// out-of-line w.r.t. the parent type.
//
// S1* Foo::foo() {}
//
// The above example looks like this in the AST:
//
// CXXMethod foo
// TypeRef struct S1
// TypeRef class Foo
// CompoundStmt
// ...
//
// The second TypeRef is an uninteresting usage.
bool process_last_type_ref = true;
if (IsTypeDefinition(semantic_container) &&
!IsTypeDefinition(lexical_container)) {
//
// In some code, such as the following example, we receive a cursor
// which is not a definition and is not associated with a definition due
// to an error condition. In this case, it is the Foo::Foo constructor.
//
// struct Foo {};
//
// template<class T>
// Foo::Foo() {}
//
if (!decl_cursor.is_definition()) {
ClangCursor def = decl_cursor.get_definition();
if (def.get_kind() != CXCursor_FirstInvalid) decl_cursor = def;
}
process_last_type_ref = false;
}
VisitDeclForTypeUsageParam param(db, toplevel_type);
decl_cursor.VisitChildren(&VisitDeclForTypeUsageVisitor, ¶m);
// VisitDeclForTypeUsageVisitor guarantees that if there are multiple
// TypeRef children, the first one will always be visited.
if (param.previous_cursor && process_last_type_ref) {
VisitDeclForTypeUsageVisitorHandler(param.previous_cursor.value(),
¶m);
} else {
// If we are not processing the last type ref, it *must* be a TypeRef or
// TemplateRef.
//
// We will not visit every child if the is_interseting is false, so
// previous_cursor
// may not point to the last TemplateRef.
assert(
param.previous_cursor.has_value() == false ||
(param.previous_cursor.value().get_kind() == CXCursor_TypeRef ||
param.previous_cursor.value().get_kind() == CXCursor_TemplateRef));
}
if (param.initial_type) return param.initial_type;
CXType cx_under = clang_getTypedefDeclUnderlyingType(decl_cursor.cx_cursor);
if (cx_under.kind == CXType_Invalid) return nullopt;
return db->ToTypeId(ClangType(cx_under).strip_qualifiers().get_usr_hash());
}
// Various versions of LLVM (ie, 4.0) will not visit inline variable references
// for template arguments.
ClangCursor::VisitResult AddDeclInitializerUsagesVisitor(ClangCursor cursor,
ClangCursor parent,
IndexFile* db) {
/*
We need to index the |DeclRefExpr| below (ie, |var| inside of
Foo<int>::var).
template<typename T>
struct Foo {
static constexpr int var = 3;
};
int a = Foo<int>::var;
=>
VarDecl a
UnexposedExpr var
DeclRefExpr var
TemplateRef Foo
*/
switch (cursor.get_kind()) {
case CXCursor_DeclRefExpr: {
if (cursor.get_referenced().get_kind() != CXCursor_VarDecl) break;
// TODO: when we resolve the template type to the definition, we get
// a different Usr.
// ClangCursor ref =
// cursor.get_referenced().template_specialization_to_template_definition().get_type().strip_qualifiers().get_usr_hash();
// std::string ref_usr =
// cursor.get_referenced().template_specialization_to_template_definition().get_type().strip_qualifiers().get_usr_hash();
optional<Usr> ref_usr =
cursor.get_referenced()
.template_specialization_to_template_definition()
.get_usr_hash();
// std::string ref_usr = ref.get_usr_hash();
if (!ref_usr) break;
IndexVar* ref_var = db->Resolve(db->ToVarId(*ref_usr));
AddRefSpell(db, ref_var->uses, cursor);
break;
}
default:
break;
}
return ClangCursor::VisitResult::Recurse;
}
ClangCursor::VisitResult VisitMacroDefinitionAndExpansions(ClangCursor cursor,
ClangCursor parent,
IndexParam* param) {
switch (cursor.get_kind()) {
case CXCursor_MacroDefinition:
case CXCursor_MacroExpansion: {
// Resolve location, find IndexFile instance.
CXSourceRange cx_source_range =
clang_Cursor_getSpellingNameRange(cursor.cx_cursor, 0, 0);
CXFile file;
Range decl_loc_spelling =
ResolveCXSourceRange(cx_source_range, &file);
IndexFile* db = ConsumeFile(param, file);
if (!db) break;
// TODO: Considering checking clang_Cursor_isMacroFunctionLike, but
// the only real difference will be that we show 'callers' instead
// of 'refs' (especially since macros cannot have overrides)
Usr decl_usr;
if (cursor.get_kind() == CXCursor_MacroDefinition)
decl_usr = cursor.get_usr_hash();
else
decl_usr = cursor.get_referenced().get_usr_hash();
SetUsePreflight(db, parent);
IndexVar* var_def = db->Resolve(db->ToVarId(decl_usr));
if (cursor.get_kind() == CXCursor_MacroDefinition) {
CXSourceRange cx_extent =
clang_getCursorExtent(cursor.cx_cursor);
var_def->def.detailed_name = cursor.get_display_name();
var_def->def.short_name_offset = 0;
var_def->def.short_name_size =
int16_t(strlen(var_def->def.detailed_name.c_str()));
var_def->def.hover =
"#define " +
GetDocumentContentInRange(param->tu->cx_tu, cx_extent);
var_def->def.kind = ls_symbol_kind::Macro;
if (g_config->index.comments)
var_def->def.comments = cursor.get_comments();
var_def->def.spell =
SetUse(db, decl_loc_spelling, parent, role::Definition);
var_def->def.extent =
SetUse(db, ResolveCXSourceRange(cx_extent, nullptr), parent,
role::None);
} else
AddRef(db, var_def->uses, decl_loc_spelling, parent);
break;
}
default:
break;
}
return ClangCursor::VisitResult::Continue;
}
namespace {
// TODO Move to another file and use clang C++ API
struct TemplateVisitorData {
IndexFile* db;
IndexParam* param;
ClangCursor container;
};
ClangCursor::VisitResult TemplateVisitor(ClangCursor cursor, ClangCursor parent,
TemplateVisitorData* data) {
IndexFile* db = data->db;
IndexParam* param = data->param;
switch (cursor.get_kind()) {
default:
break;
case CXCursor_DeclRefExpr: {
ClangCursor ref_cursor =
clang_getCursorReferenced(cursor.cx_cursor);
if (ref_cursor.get_kind() == CXCursor_NonTypeTemplateParameter) {
IndexId::Var ref_var_id =
db->ToVarId(ref_cursor.get_usr_hash());
IndexVar* ref_var = db->Resolve(ref_var_id);
if (ref_var->def.detailed_name.empty()) {
ClangCursor sem_parent = ref_cursor.get_semantic_parent();
ClangCursor lex_parent = ref_cursor.get_lexical_parent();
SetUsePreflight(db, sem_parent);
SetUsePreflight(db, lex_parent);
ref_var = db->Resolve(ref_var_id);
ref_var->def.spell = SetUse(db, ref_cursor.get_spell(),
sem_parent, role::Definition);
ref_var->def.extent = SetUse(db, ref_cursor.get_extent(),
lex_parent, role::None);
ref_var = db->Resolve(ref_var_id);
ref_var->def.kind = ls_symbol_kind::TypeParameter;
SetVarDetail(ref_var, ref_cursor.get_spell_name(),
ref_cursor, nullptr, true, db, param);
ClangType ref_type =
clang_getCursorType(ref_cursor.cx_cursor);
// TODO optimize
if (ref_type.get_usr().size()) {
IndexType* ref_type_index =
db->Resolve(db->ToTypeId(ref_type.get_usr_hash()));
// The cursor extent includes `type name`, not just
// `name`. There seems no way to extract the spelling
// range of `type` and we do not want to do subtraction
// here. See
// https://github.com/jacobdufault/cquery/issues/252
AddRef(db, ref_type_index->uses,
ref_cursor.get_extent(),
ref_cursor.get_lexical_parent());
}
}
AddRefSpell(db, ref_var->uses, cursor);
}
break;
}
case CXCursor_OverloadedDeclRef: {
unsigned num_overloaded =
clang_getNumOverloadedDecls(cursor.cx_cursor);
for (unsigned i = 0; i != num_overloaded; i++) {
ClangCursor overloaded =
clang_getOverloadedDecl(cursor.cx_cursor, i);
switch (overloaded.get_kind()) {
default:
break;
case CXCursor_FunctionDecl:
case CXCursor_FunctionTemplate: {
IndexId::Func called_id =
db->ToFuncId(overloaded.get_usr_hash());
OnIndexReferenceFunction(db, cursor.get_spell(),
data->container, called_id,
role::Call);
break;
}
}
}
break;
}
case CXCursor_TemplateRef: {
ClangCursor ref_cursor =
clang_getCursorReferenced(cursor.cx_cursor);
if (ref_cursor.get_kind() == CXCursor_TemplateTemplateParameter) {
IndexId::Type ref_type_id =
db->ToTypeId(ref_cursor.get_usr_hash());
IndexType* ref_type = db->Resolve(ref_type_id);
// TODO It seems difficult to get references to template
// template parameters. CXCursor_TemplateTemplateParameter can
// be visited by visiting CXCursor_TranslationUnit, but not
// (confirm this) by visiting {Class,Function}Template. Thus we
// need to initialize it here.
if (ref_type->def.detailed_name.empty()) {
ClangCursor sem_parent = ref_cursor.get_semantic_parent();
ClangCursor lex_parent = ref_cursor.get_lexical_parent();
SetUsePreflight(db, sem_parent);
SetUsePreflight(db, lex_parent);
ref_type = db->Resolve(ref_type_id);
ref_type->def.spell = SetUse(db, ref_cursor.get_spell(),
sem_parent, role::Definition);
ref_type->def.extent = SetUse(db, ref_cursor.get_extent(),
lex_parent, role::None);
#if 0 && CINDEX_HAVE_PRETTY
ref_type->def.detailed_name = param->PrettyPrintCursor(ref_cursor.cx_cursor);
#else
ref_type->def.detailed_name = ref_cursor.get_spell_name();
#endif
ref_type->def.short_name_offset = 0;
ref_type->def.short_name_size =
int16_t(strlen(ref_type->def.detailed_name.c_str()));
ref_type->def.kind = ls_symbol_kind::TypeParameter;
}
AddRefSpell(db, ref_type->uses, cursor);
}
break;
}
case CXCursor_TypeRef: {
ClangCursor ref_cursor =
clang_getCursorReferenced(cursor.cx_cursor);
if (ref_cursor.get_kind() == CXCursor_TemplateTypeParameter) {
IndexId::Type ref_type_id =
db->ToTypeId(ref_cursor.get_usr_hash());
IndexType* ref_type = db->Resolve(ref_type_id);
// TODO It seems difficult to get a FunctionTemplate's template
// parameters.
// CXCursor_TemplateTypeParameter can be visited by visiting
// CXCursor_TranslationUnit, but not (confirm this) by visiting
// {Class,Function}Template. Thus we need to initialize it here.
if (ref_type->def.detailed_name.empty()) {
ClangCursor sem_parent = ref_cursor.get_semantic_parent();
ClangCursor lex_parent = ref_cursor.get_lexical_parent();
SetUsePreflight(db, sem_parent);
SetUsePreflight(db, lex_parent);
ref_type = db->Resolve(ref_type_id);
ref_type->def.spell = SetUse(db, ref_cursor.get_spell(),
sem_parent, role::Definition);
ref_type->def.extent = SetUse(db, ref_cursor.get_extent(),
lex_parent, role::None);
#if 0 && CINDEX_HAVE_PRETTY
// template<class T> void f(T t){} // weird, the name is empty
ref_type->def.detailed_name = param->PrettyPrintCursor(ref_cursor.cx_cursor);
#else
ref_type->def.detailed_name = ref_cursor.get_spell_name();
#endif
ref_type->def.short_name_offset = 0;
ref_type->def.short_name_size =
int16_t(strlen(ref_type->def.detailed_name.c_str()));
ref_type->def.kind = ls_symbol_kind::TypeParameter;
}
AddRefSpell(db, ref_type->uses, cursor);
}
break;
}
}
return ClangCursor::VisitResult::Recurse;
}
} // namespace
std::string NamespaceHelper::QualifiedName(const CXIdxContainerInfo* container,
std::string_view unqualified_name) {
if (!container) return std::string(unqualified_name);
// Anonymous namespaces are not processed by indexDeclaration. We trace
// nested namespaces bottom-up through clang_getCursorSemanticParent until
// one that we know its qualified name. Then do another trace top-down and
// put their names into a map of USR -> qualified_name.
ClangCursor cursor(container->cursor);
std::vector<ClangCursor> namespaces;
std::string qualifier;
while (cursor.get_kind() != CXCursor_TranslationUnit &&
GetSymbolKind(cursor.get_kind()) == SymbolKind::Type) {
auto it = container_cursor_to_qualified_name.find(cursor);
if (it != container_cursor_to_qualified_name.end()) {
qualifier = it->second;
break;
}
namespaces.push_back(cursor);
cursor = clang_getCursorSemanticParent(cursor.cx_cursor);
}
for (size_t i = namespaces.size(); i > 0;) {
i--;
std::string name = namespaces[i].get_spell_name();
// Empty name indicates unnamed namespace, anonymous struct, anonymous
// union, ...
if (name.size())
qualifier += name;
else
qualifier += GetAnonName(namespaces[i].get_kind());
qualifier += "::";
container_cursor_to_qualified_name[namespaces[i]] = qualifier;
}
// C++17 string::append
return qualifier + std::string(unqualified_name);
}
void OnIndexDeclaration(CXClientData client_data, const CXIdxDeclInfo* decl) {
IndexParam* param = static_cast<IndexParam*>(client_data);
// Track all constructor declarations, as we may need to use it to manually
// associate std::make_unique and the like as constructor invocations.
if (decl->entityInfo->kind == CXIdxEntity_CXXConstructor) {
param->ctors.NotifyConstructor(decl->cursor);
}
CXFile file;
clang_getSpellingLocation(clang_indexLoc_getCXSourceLocation(decl->loc),
&file, nullptr, nullptr, nullptr);
IndexFile* db = ConsumeFile(param, file);
if (!db) return;
// The language of this declaration
LanguageId decl_lang = [&decl]() {
switch (clang_getCursorLanguage(decl->cursor)) {
case CXLanguage_C:
return LanguageId::C;
case CXLanguage_CPlusPlus:
return LanguageId::Cpp;
case CXLanguage_ObjC:
return LanguageId::ObjC;
default:
return LanguageId::Unknown;
};
}();
// Only update the file language if the new language is "greater" than the
// old
if (decl_lang > db->language) {
db->language = decl_lang;
}
ClangCursor sem_parent(FromContainer(decl->semanticContainer));
ClangCursor lex_parent(FromContainer(decl->lexicalContainer));
SetUsePreflight(db, sem_parent);
SetUsePreflight(db, lex_parent);
ClangCursor cursor = decl->cursor;
switch (decl->entityInfo->kind) {
case CXIdxEntity_Unexposed:
LOG_S(INFO) << "CXIdxEntity_Unexposed " << cursor.get_spell_name();
break;
case CXIdxEntity_CXXNamespace: {
Range spell = cursor.get_spell();
IndexId::Type ns_id = db->ToTypeId(HashUsr(decl->entityInfo->USR));
IndexType* ns = db->Resolve(ns_id);
ns->def.kind = GetSymbolKind(decl->entityInfo->kind);
if (ns->def.detailed_name.empty()) {
SetTypeName(ns, cursor, decl->semanticContainer,
decl->entityInfo->name, param);
ns->def.spell = SetUse(db, spell, sem_parent, role::Definition);
ns->def.extent =
SetUse(db, cursor.get_extent(), lex_parent, role::None);
if (decl->semanticContainer) {
IndexId::Type parent_id = db->ToTypeId(
ClangCursor(decl->semanticContainer->cursor)
.get_usr_hash());
db->Resolve(parent_id)->derived.push_back(ns_id);
// |ns| may be invalidated.
ns = db->Resolve(ns_id);
ns->def.bases.push_back(parent_id);
}
}
AddRef(db, ns->uses, spell, lex_parent);
break;
}
case CXIdxEntity_CXXNamespaceAlias:
assert(false && "CXXNamespaceAlias");
break;
case CXIdxEntity_ObjCProperty:
case CXIdxEntity_ObjCIvar:
case CXIdxEntity_EnumConstant:
case CXIdxEntity_Field:
case CXIdxEntity_Variable:
case CXIdxEntity_CXXStaticVariable: {
Range spell = cursor.get_spell();
// Do not index implicit template instantiations.
if (cursor !=
cursor.template_specialization_to_template_definition())
break;
IndexId::Var var_id = db->ToVarId(HashUsr(decl->entityInfo->USR));
IndexVar* var = db->Resolve(var_id);
// TODO: Eventually run with this if. Right now I want to iron out
// bugs this may shadow.
// TODO: Verify this gets called multiple times
// if (!decl->isRedeclaration) {
SetVarDetail(var, std::string(decl->entityInfo->name), decl->cursor,
decl->semanticContainer, !decl->isRedeclaration, db,
param);
// FIXME https://github.com/jacobdufault/cquery/issues/239
var->def.kind = GetSymbolKind(decl->entityInfo->kind);
if (var->def.kind == ls_symbol_kind::Variable &&
decl->cursor.kind == CXCursor_ParmDecl)
var->def.kind = ls_symbol_kind::Parameter;
//}
if (decl->isDefinition) {
var->def.spell =
SetUse(db, spell, sem_parent, role::Definition);
var->def.extent =
SetUse(db, cursor.get_extent(), lex_parent, role::None);
} else {
var->declarations.push_back(
SetRef(db, spell, lex_parent, role::Declaration));
}
cursor.VisitChildren(&AddDeclInitializerUsagesVisitor, db);
var = db->Resolve(var_id);
// Declaring variable type information. Note that we do not insert
// an interesting reference for parameter declarations - that is
// handled when the function declaration is encountered since we
// won't receive ParmDecl declarations for unnamed parameters.
// TODO: See if we can remove this function call.
AddDeclTypeUsages(db, cursor, var->def.type,
decl->semanticContainer, decl->lexicalContainer);
// We don't need to assign declaring type multiple times if this
// variable has already been seen.
if (decl->isDefinition && decl->semanticContainer) {
switch (GetSymbolKind(decl->semanticContainer->cursor.kind)) {
case SymbolKind::Func: {
db->Resolve(
db->ToFuncId(decl->semanticContainer->cursor))
->def.vars.push_back(var_id);
break;
}
case SymbolKind::Type:
if (decl->semanticContainer->cursor.kind !=
CXCursor_EnumDecl) {
db->Resolve(
db->ToTypeId(decl->semanticContainer->cursor))
->def.vars.push_back(var_id);
}
break;
default:
break;
}
}
break;
}
case CXIdxEntity_ObjCInstanceMethod:
case CXIdxEntity_ObjCClassMethod:
case CXIdxEntity_Function:
case CXIdxEntity_CXXConstructor:
case CXIdxEntity_CXXDestructor:
case CXIdxEntity_CXXInstanceMethod:
case CXIdxEntity_CXXStaticMethod:
case CXIdxEntity_CXXConversionFunction: {
Range spell = cursor.get_spell();
Range extent = cursor.get_extent();
ClangCursor decl_cursor_resolved =
cursor.template_specialization_to_template_definition();
bool is_template_specialization = cursor != decl_cursor_resolved;
IndexId::Func func_id =
db->ToFuncId(decl_cursor_resolved.cx_cursor);
IndexFunc* func = db->Resolve(func_id);
if (g_config->index.comments)
func->def.comments = cursor.get_comments();
func->def.kind = GetSymbolKind(decl->entityInfo->kind);
func->def.storage =
GetStorageClass(clang_Cursor_getStorageClass(decl->cursor));
// We don't actually need to know the return type, but we need to
// mark it as an interesting usage.
AddDeclTypeUsages(db, cursor, nullopt, decl->semanticContainer,
decl->lexicalContainer);
// Add definition or declaration. This is a bit tricky because we
// treat template specializations as declarations, even though they
// are technically definitions.
// TODO: Support multiple function definitions, which is common for
// template specializations.
if (decl->isDefinition && !is_template_specialization) {
// assert(!func->def.spell);
// assert(!func->def.extent);
func->def.spell =
SetUse(db, spell, sem_parent, role::Definition);
func->def.extent = SetUse(db, extent, lex_parent, role::None);
} else {
IndexFunc::Declaration declaration;
declaration.spell =
SetUse(db, spell, lex_parent, role::Declaration);
// Add parameters.
for (ClangCursor arg : cursor.get_arguments()) {
switch (arg.get_kind()) {
case CXCursor_ParmDecl: {
Range param_spelling = arg.get_spell();
// If the name is empty (which is common for
// parameters), clang will report a range with
// length 1, which is not correct.
if (param_spelling.start.column ==
(param_spelling.end.column - 1) &&
arg.get_display_name().empty()) {
param_spelling.end.column -= 1;
}
declaration.param_spellings.push_back(
param_spelling);
break;
}
default:
break;
}
}
func->declarations.push_back(declaration);
}
// Emit definition data for the function. We do this even if it
// isn't a definition because there can be, for example, interfaces,
// or a class declaration that doesn't have a definition yet. If we
// never end up indexing the definition, then there will not be any
// (ie) outline information.
if (!is_template_specialization) {
// Build detailed name. The type desc looks like void (void *).
// We insert the qualified name before the first '('.
// FIXME GetFunctionSignature should set index
#if CINDEX_HAVE_PRETTY
func->def.detailed_name =
param->PrettyPrintCursor(decl->cursor);
#else
func->def.detailed_name =
GetFunctionSignature(db, ¶m->ns, decl);
#endif
auto idx = func->def.detailed_name.find(decl->entityInfo->name);
assert(idx != std::string::npos);
func->def.short_name_offset = idx;
func->def.short_name_size = strlen(decl->entityInfo->name);
// CXCursor_OverloadedDeclRef in templates are not processed by
// OnIndexReference, thus we use TemplateVisitor to collect
// function references.
if (decl->entityInfo->templateKind == CXIdxEntity_Template) {
TemplateVisitorData data;
data.db = db;
data.param = param;
data.container = cursor;
cursor.VisitChildren(&TemplateVisitor, &data);
// TemplateVisitor calls ToFuncId which invalidates func
func = db->Resolve(func_id);
}
// Add function usage information. We only want to do it once
// per definition/declaration. Do it on definition since there
// should only ever be one of those in the entire program.
if (IsTypeDefinition(decl->semanticContainer)) {
IndexId::Type declaring_type_id =
db->ToTypeId(decl->semanticContainer->cursor);
IndexType* declaring_type_def =
db->Resolve(declaring_type_id);
func->def.declaring_type = declaring_type_id;
// Mark a type reference at the ctor/dtor location.
if (decl->entityInfo->kind == CXIdxEntity_CXXConstructor)
AddRef(db, declaring_type_def->uses, spell,
FromContainer(decl->lexicalContainer));
// Add function to declaring type.
declaring_type_def->def.funcs.push_back(func_id);
}
// Process inheritance.
if (clang_CXXMethod_isVirtual(decl->cursor)) {
CXCursor* overridden;
unsigned int num_overridden;
clang_getOverriddenCursors(decl->cursor, &overridden,
&num_overridden);
for (unsigned i = 0; i < num_overridden; ++i) {
ClangCursor parent =
ClangCursor(overridden[i])
.template_specialization_to_template_definition();
IndexId::Func parent_id =
db->ToFuncId(parent.get_usr_hash());
IndexFunc* parent_def = db->Resolve(parent_id);
func = db->Resolve(
func_id); // ToFuncId invalidated func_def
func->def.bases.push_back(parent_id);
parent_def->derived.push_back(func_id);
}
clang_disposeOverriddenCursors(overridden);
}
}
break;
}
case CXIdxEntity_Typedef:
case CXIdxEntity_CXXTypeAlias: {
// Note we want to fetch the first TypeRef. Running
// ResolveCursorType(decl->cursor) would return
// the type of the typedef/using, not the type of the referenced
// type.
optional<IndexId::Type> alias_of =
AddDeclTypeUsages(db, cursor, nullopt, decl->semanticContainer,
decl->lexicalContainer);
IndexId::Type type_id =
db->ToTypeId(HashUsr(decl->entityInfo->USR));
IndexType* type = db->Resolve(type_id);
if (alias_of) type->def.alias_of = alias_of.value();
ClangCursor decl_cursor = decl->cursor;
Range spell = decl_cursor.get_spell();
Range extent = decl_cursor.get_extent();
type->def.spell = SetUse(db, spell, sem_parent, role::Definition);
type->def.extent = SetUse(db, extent, lex_parent, role::None);
SetTypeName(type, decl_cursor, decl->semanticContainer,
decl->entityInfo->name, param);
type->def.kind = GetSymbolKind(decl->entityInfo->kind);
if (g_config->index.comments)
type->def.comments = decl_cursor.get_comments();
// For Typedef/CXXTypeAlias spanning a few lines, display the
// declaration line, with spelling name replaced with qualified
// name.
// TODO Think how to display multi-line declaration like `typedef
// struct {
// ... } foo;` https://github.com/jacobdufault/cquery/issues/29
if (extent.end.line - extent.start.line <
k_max_lines_display_type_alias_declarations) {
FileContents& fc = param->file_contents[db->path];
optional<int> extent_start = fc.ToOffset(extent.start),
spell_start = fc.ToOffset(spell.start),
spell_end = fc.ToOffset(spell.end),
extent_end = fc.ToOffset(extent.end);
if (extent_start && spell_start && spell_end && extent_end) {
type->def.hover =
fc.content.substr(*extent_start,
*spell_start - *extent_start) +
type->def.detailed_name.c_str() +
fc.content.substr(*spell_end, *extent_end - *spell_end);
}
}
AddRef(db, type->uses, spell,
FromContainer(decl->lexicalContainer));
break;
}
case CXIdxEntity_ObjCProtocol:
case CXIdxEntity_ObjCCategory:
case CXIdxEntity_ObjCClass:
case CXIdxEntity_Enum:
case CXIdxEntity_Union:
case CXIdxEntity_Struct:
case CXIdxEntity_CXXInterface:
case CXIdxEntity_CXXClass: {
Range spell = cursor.get_spell();
IndexId::Type type_id =
db->ToTypeId(HashUsr(decl->entityInfo->USR));
IndexType* type = db->Resolve(type_id);
// TODO: Eventually run with this if. Right now I want to iron out
// bugs this may shadow.
// TODO: For type section, verify if this ever runs for non
// definitions? if (!decl->isRedeclaration) {
SetTypeName(type, cursor, decl->semanticContainer,
decl->entityInfo->name, param);
type->def.kind = GetSymbolKind(decl->entityInfo->kind);
if (g_config->index.comments)
type->def.comments = cursor.get_comments();
// }
if (decl->isDefinition) {
type->def.spell =
SetUse(db, spell, sem_parent, role::Definition);
type->def.extent =
SetUse(db, cursor.get_extent(), lex_parent, role::None);
if (cursor.get_kind() == CXCursor_EnumDecl) {
ClangType enum_type =
clang_getEnumDeclIntegerType(decl->cursor);
if (!enum_type.is_builtin()) {
IndexType* int_type =
db->Resolve(db->ToTypeId(enum_type.get_usr_hash()));
AddRef(db, int_type->uses, spell,
FromContainer(decl->lexicalContainer));
// type is invalidated.
type = db->Resolve(type_id);
}
}
} else
AddRef(db, type->declarations, spell,
FromContainer(decl->lexicalContainer),
role::Declaration);
switch (decl->entityInfo->templateKind) {
default:
break;
case CXIdxEntity_TemplateSpecialization:
case CXIdxEntity_TemplatePartialSpecialization: {
// TODO Use a different dimension
ClangCursor origin_cursor =
cursor.template_specialization_to_template_definition();
IndexId::Type origin_id =
db->ToTypeId(origin_cursor.get_usr_hash());
IndexType* origin = db->Resolve(origin_id);
// |type| may be invalidated.
type = db->Resolve(type_id);
// template<class T> class function; // not visited by
// OnIndexDeclaration template<> class function<int> {}; //
// current cursor
if (origin->def.detailed_name.empty()) {
SetTypeName(origin, origin_cursor, nullptr,
&type->def.ShortName()[0], param);
origin->def.kind = type->def.kind;
}
// TODO The name may be assigned in
// |ResolveToDeclarationType| but |spell| is nullopt.
CXFile origin_file;
Range origin_spell = origin_cursor.get_spell(&origin_file);
if (!origin->def.spell && file == origin_file) {
ClangCursor origin_sem =
origin_cursor.get_semantic_parent();
ClangCursor origin_lex =
origin_cursor.get_lexical_parent();
SetUsePreflight(db, origin_sem);
SetUsePreflight(db, origin_lex);
origin = db->Resolve(origin_id);
type = db->Resolve(type_id);
origin->def.spell = SetUse(db, origin_spell, origin_sem,
role::Definition);
origin->def.extent =
SetUse(db, origin_cursor.get_extent(), origin_lex,
role::None);
}
origin->derived.push_back(type_id);
type->def.bases.push_back(origin_id);
}
// fallthrough
case CXIdxEntity_Template: {
TemplateVisitorData data;
data.db = db;
data.container = cursor;
data.param = param;
cursor.VisitChildren(&TemplateVisitor, &data);
break;
}
}
// type_def->alias_of
// type_def->funcs
// type_def->types
// type_def->uses
// type_def->vars
// Add type-level inheritance information.
CXIdxCXXClassDeclInfo const* class_info =
clang_index_getCXXClassDeclInfo(decl);
if (class_info) {
for (unsigned int i = 0; i < class_info->numBases; ++i) {
const CXIdxBaseClassInfo* base_class = class_info->bases[i];
AddDeclTypeUsages(db, base_class->cursor, nullopt,
decl->semanticContainer,
decl->lexicalContainer);
optional<IndexId::Type> parent_type_id =
ResolveToDeclarationType(db, base_class->cursor, param);
// type_def ptr could be invalidated by
// ResolveToDeclarationType and TemplateVisitor.
type = db->Resolve(type_id);
if (parent_type_id) {
IndexType* parent_type_def =
db->Resolve(parent_type_id.value());
parent_type_def->derived.push_back(type_id);
type->def.bases.push_back(*parent_type_id);
}
}
}
break;
}
}
}
// https://github.com/jacobdufault/cquery/issues/174
// Type-dependent member access expressions do not have accurate spelling
// ranges.
//
// Not type dependent
// C<int> f; f.x // .x produces a MemberRefExpr which has a spelling range
// of `x`.
//
// Type dependent
// C<T> e; e.x // .x produces a MemberRefExpr which has a spelling range
// of `e` (weird) and an empty spelling name.
//
// To attribute the use of `x` in `e.x`, we use cursor extent `e.x`
// minus cursor spelling `e` minus the period.
void CheckTypeDependentMemberRefExpr(Range* spell, const ClangCursor& cursor,
IndexParam* param, const IndexFile* db) {
if (cursor.get_kind() == CXCursor_MemberRefExpr &&
cursor.get_spell_name().empty()) {
*spell = cursor.get_extent().RemovePrefix(spell->end);
const FileContents& fc = param->file_contents[db->path];
optional<int> maybe_period = fc.ToOffset(spell->start);
if (maybe_period) {
int i = *maybe_period;
if (fc.content[i] == '.') spell->start.column++;
// -> is likely unexposed.
}
}
}
void OnIndexReference(CXClientData client_data, const CXIdxEntityRefInfo* ref) {
// TODO: Use clang_getFileUniqueID
CXFile file;
clang_getSpellingLocation(clang_indexLoc_getCXSourceLocation(ref->loc),
&file, nullptr, nullptr, nullptr);
IndexParam* param = static_cast<IndexParam*>(client_data);
IndexFile* db = ConsumeFile(param, file);
if (!db) return;
ClangCursor cursor(ref->cursor);
ClangCursor lex_parent(FromContainer(ref->container));
ClangCursor referenced;
if (ref->referencedEntity) referenced = ref->referencedEntity->cursor;
SetUsePreflight(db, lex_parent);
switch (ref->referencedEntity->kind) {
case CXIdxEntity_Unexposed:
LOG_S(INFO) << "CXIdxEntity_Unexposed " << cursor.get_spell_name();
break;
case CXIdxEntity_CXXNamespace: {
IndexType* ns =
db->Resolve(db->ToTypeId(referenced.get_usr_hash()));
AddRef(db, ns->uses, cursor.get_spell(),
FromContainer(ref->container));
break;
}
case CXIdxEntity_CXXNamespaceAlias: {
IndexType* ns =
db->Resolve(db->ToTypeId(referenced.get_usr_hash()));
AddRef(db, ns->uses, cursor.get_spell(),
FromContainer(ref->container));
if (!ns->def.spell) {
ClangCursor sem_parent = referenced.get_semantic_parent();
ClangCursor lex_parent = referenced.get_lexical_parent();
SetUsePreflight(db, sem_parent);
SetUsePreflight(db, lex_parent);
ns->def.spell = SetUse(db, referenced.get_spell(), sem_parent,
role::Definition);
ns->def.extent =
SetUse(db, referenced.get_extent(), lex_parent, role::None);
std::string name = referenced.get_spell_name();
SetTypeName(ns, referenced, nullptr, name.c_str(), param);
}
break;
}
case CXIdxEntity_ObjCProperty:
case CXIdxEntity_ObjCIvar:
case CXIdxEntity_EnumConstant:
case CXIdxEntity_CXXStaticVariable:
case CXIdxEntity_Variable:
case CXIdxEntity_Field: {
Range loc = cursor.get_spell();
CheckTypeDependentMemberRefExpr(&loc, cursor, param, db);
referenced =
referenced.template_specialization_to_template_definition();
IndexId::Var var_id = db->ToVarId(referenced.get_usr_hash());
IndexVar* var = db->Resolve(var_id);
// Lambda paramaters are not processed by OnIndexDeclaration and
// may not have a short_name yet. Note that we only process the
// lambda parameter as a definition if it is in the same file as the
// reference, as lambdas cannot be split across files.
if (var->def.detailed_name.empty()) {
CXFile referenced_file;
Range spell = referenced.get_spell(&referenced_file);
if (file == referenced_file) {
var->def.spell =
SetUse(db, spell, lex_parent, role::Definition);
var->def.extent = SetUse(db, referenced.get_extent(),
lex_parent, role::None);
// TODO Some of the logic here duplicates
// CXIdxEntity_Variable branch of OnIndexDeclaration. But
// there `decl` is of type CXIdxDeclInfo and has more
// information, thus not easy to reuse the code.
SetVarDetail(var, referenced.get_spell_name(), referenced,
nullptr, true, db, param);
var->def.kind = ls_symbol_kind::Parameter;
}
}
AddRef(db, var->uses, loc, FromContainer(ref->container),
GetRole(ref, role::Reference));
break;
}
case CXIdxEntity_CXXConversionFunction:
case CXIdxEntity_CXXStaticMethod:
case CXIdxEntity_CXXInstanceMethod:
case CXIdxEntity_ObjCInstanceMethod:
case CXIdxEntity_ObjCClassMethod:
case CXIdxEntity_Function:
case CXIdxEntity_CXXConstructor:
case CXIdxEntity_CXXDestructor: {
// TODO: Redirect container to constructor for the following
// example, ie,
// we should be inserting an outgoing function call from the
// Foo ctor.
//
// int Gen() { return 5; }
// class Foo {
// int x = Gen();
// }
// TODO: search full history?
Range loc = cursor.get_spell();
IndexId::Func called_id =
db->ToFuncId(HashUsr(ref->referencedEntity->USR));
IndexFunc* called = db->Resolve(called_id);
std::string_view short_name = called->def.ShortName();
// libclang doesn't provide a nice api to check if the given
// function call is implicit. ref->kind should probably work (it's
// either direct or implicit), but libclang only supports implicit
// for objective-c.
bool is_implicit =
CanBeCalledImplicitly(ref->referencedEntity->kind) &&
// Treats empty short_name as an implicit call like
// implicit move constructor in `vector<int> a = f();`
(short_name.empty() ||
// For explicit destructor call, ref->cursor may be
// "~" while called->def.short_name is "~A"
// "~A" is not a substring of ref->cursor, but we
// should take this case as not `is_implicit`.
(short_name[0] != '~' &&
!CursorSpellingContainsString(ref->cursor, param->tu->cx_tu,
short_name)));
// Extents have larger ranges and thus less specific, and will be
// overriden by other functions if exist.
//
// Type-dependent member access expressions do not have useful
// spelling ranges. See the comment above for the CXIdxEntity_Field
// case.
if (is_implicit)
loc = cursor.get_extent();
else
CheckTypeDependentMemberRefExpr(&loc, cursor, param, db);
OnIndexReferenceFunction(
db, loc, ref->container->cursor, called_id,
GetRole(ref, role::Call) |
(is_implicit ? role::Implicit : role::None));
// Checks if |str| starts with |start|. Ignores case.
auto str_begin = [](const char* start, const char* str) {
while (*start && *str) {
char a = tolower(*start);
char b = tolower(*str);
if (a != b) return false;
++start;
++str;
}
return !*start;
};
bool is_template =
ref->referencedEntity->templateKind !=
CXIdxEntityCXXTemplateKind::CXIdxEntity_NonTemplate;
if (g_config->index.attributeMakeCallsToCtor && is_template &&
str_begin("make", ref->referencedEntity->name)) {
// Try to find the return type of called function. That type
// will have the constructor function we add a usage to.
optional<ClangCursor> opt_found_type = FindType(ref->cursor);
if (opt_found_type) {
Usr ctor_type_usr =
opt_found_type->get_referenced().get_usr_hash();
ClangCursor call_cursor = ref->cursor;
// Build a type description from the parameters of the call,
// so we can try to find a constructor with the same type
// description.
std::vector<std::string> call_type_desc;
for (ClangType type :
call_cursor.get_type().get_arguments()) {
std::string type_desc = type.get_spell_name();
if (!type_desc.empty())
call_type_desc.push_back(type_desc);
}
// Try to find the constructor and add a reference.
optional<Usr> ctor_usr = param->ctors.TryFindConstructorUsr(
ctor_type_usr, call_type_desc);
if (ctor_usr) {
IndexFunc* ctor = db->Resolve(db->ToFuncId(*ctor_usr));
ctor->uses.push_back(
IndexId::LexicalRef(loc, AnyId(), SymbolKind::File,
role::Call | role::Implicit));
}
}
}
break;
}
case CXIdxEntity_ObjCCategory:
case CXIdxEntity_ObjCProtocol:
case CXIdxEntity_ObjCClass:
case CXIdxEntity_Typedef:
case CXIdxEntity_CXXInterface: // MSVC __interface
case CXIdxEntity_CXXTypeAlias:
case CXIdxEntity_Enum:
case CXIdxEntity_Union:
case CXIdxEntity_Struct:
case CXIdxEntity_CXXClass: {
referenced =
referenced.template_specialization_to_template_definition();
IndexType* ref_type =
db->Resolve(db->ToTypeId(referenced.get_usr_hash()));
if (!ref->parentEntity || IsDeclContext(ref->parentEntity->kind))
AddRefSpell(db, ref_type->declarations, ref->cursor);
else
AddRefSpell(db, ref_type->uses, ref->cursor);
break;
}
}
}
optional<std::vector<std::unique_ptr<IndexFile>>> Parse(
FileConsumerSharedState* file_consumer_shared, const std::string& file0,
const std::vector<std::string>& args,
const std::vector<FileContents>& file_contents, ClangIndex* index,
bool dump_ast) {
if (!g_config->index.enabled) return nullopt;
optional<AbsolutePath> file = NormalizePath(file0);
if (!file) {
LOG_S(WARNING) << "Cannot index " << file0
<< " because it can not be found";
return nullopt;
}
std::vector<CXUnsavedFile> unsaved_files;
for (const FileContents& contents : file_contents) {
CXUnsavedFile unsaved;
unsaved.Filename = contents.path.path.c_str();
unsaved.Contents = contents.content.c_str();
unsaved.Length = (unsigned long)contents.content.size();
unsaved_files.push_back(unsaved);
}
std::unique_ptr<ClangTranslationUnit> tu = ClangTranslationUnit::Create(
index, file->path, args, unsaved_files,
CXTranslationUnit_KeepGoing |
CXTranslationUnit_DetailedPreprocessingRecord);
if (!tu) return nullopt;
if (dump_ast) Dump(clang_getTranslationUnitCursor(tu->cx_tu));
IndexerCallbacks callback = {0};
// Available callbacks:
// - abortQuery
// - enteredMainFile
// - ppIncludedFile
// - importedASTFile
// - startedTranslationUnit
callback.diagnostic = &OnIndexDiagnostic;
callback.ppIncludedFile = &OnIndexIncludedFile;
callback.indexDeclaration = &OnIndexDeclaration;
callback.indexEntityReference = &OnIndexReference;
FileConsumer file_consumer(file_consumer_shared, *file);
IndexParam param(tu.get(), &file_consumer);
for (const FileContents& contents : file_contents)
param.file_contents[contents.path] = contents;
CXFile cx_file = clang_getFile(tu->cx_tu, file->path.c_str());
param.primary_file = ConsumeFile(¶m, cx_file);
CXIndexAction index_action = clang_IndexAction_create(index->cx_index);
// |index_result| is a CXErrorCode instance.
int index_result = clang_indexTranslationUnit(
index_action, ¶m, &callback, sizeof(IndexerCallbacks),
CXIndexOpt_IndexFunctionLocalSymbols |
CXIndexOpt_SkipParsedBodiesInSession |
CXIndexOpt_IndexImplicitTemplateInstantiations,
tu->cx_tu);
if (index_result != CXError_Success) {
LOG_S(ERROR) << "Indexing " << *file
<< " failed with errno=" << index_result;
return nullopt;
}
clang_IndexAction_dispose(index_action);
ClangCursor(clang_getTranslationUnitCursor(tu->cx_tu))
.VisitChildren(&VisitMacroDefinitionAndExpansions, ¶m);
std::unordered_map<AbsolutePath, int> inc_to_line;
// TODO
if (param.primary_file)
for (auto& inc : param.primary_file->includes)
inc_to_line[inc.resolved_path] = inc.line;
auto result = param.file_consumer->TakeLocalState();
auto args_hash = HashArguments(args);
for (std::unique_ptr<IndexFile>& entry : result) {
entry->import_file = *file;
entry->args_hash = args_hash;
for (IndexFunc& func : entry->funcs) {
// e.g. declaration + out-of-line definition
Uniquify(func.derived);
Uniquify(func.uses);
}
for (IndexType& type : entry->types) {
Uniquify(type.derived);
Uniquify(type.uses);
// e.g. declaration + out-of-line definition
Uniquify(type.def.funcs);
}
for (IndexVar& var : entry->vars) Uniquify(var.uses);
if (param.primary_file) {
// If there are errors, show at least one at the include position.
auto it = inc_to_line.find(entry->path);
if (it != inc_to_line.end()) {
int line = it->second;
for (auto ls_diagnostic : entry->diagnostics_) {
if (ls_diagnostic.severity != lsDiagnosticSeverity::Error)
continue;
ls_diagnostic.range =
LsRange(LsPosition(line, 10), LsPosition(line, 10));
param.primary_file->diagnostics_.push_back(ls_diagnostic);
break;
}
}
}
// Update dependencies for the file. Do not include the file in its own
// dependency set.
entry->dependencies = param.seen_files;
entry->dependencies.erase(
std::remove(entry->dependencies.begin(), entry->dependencies.end(),
entry->path),
entry->dependencies.end());
}
return std::move(result);
}
void ConcatTypeAndName(std::string& type, const std::string& name) {
if (type.size() &&
(type.back() != ' ' && type.back() != '*' && type.back() != '&'))
type.push_back(' ');
type.append(name);
}
void IndexInit() {
clang_enableStackTraces();
if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
clang_toggleCrashRecovery(1);
}
void ClangSanityCheck(const Project::Entry& entry) {
std::vector<const char*> args;
ClangIndex index;
std::vector<CXUnsavedFile> unsaved;
std::unique_ptr<ClangTranslationUnit> tu = ClangTranslationUnit::Create(
&index, entry.filename, entry.args, unsaved, 0);
if (!tu) ABORT_S() << "Creating translation unit failed";
struct ClientData {
int num_diagnostics = 0;
};
IndexerCallbacks callback = {0};
callback.abortQuery = [](CXClientData client_data, void* reserved) {
return 0;
};
callback.diagnostic = [](CXClientData client_data,
CXDiagnosticSet diagnostics, void* reserved) {
((ClientData*)client_data)->num_diagnostics +=
clang_getNumDiagnosticsInSet(diagnostics);
for (unsigned i = 0; i < clang_getNumDiagnosticsInSet(diagnostics);
++i) {
CXDiagnostic diagnostic = clang_getDiagnosticInSet(diagnostics, i);
// Get db so we can attribute diagnostic to the right indexed file.
CXFile file;
unsigned int line, column;
CXSourceLocation diag_loc = clang_getDiagnosticLocation(diagnostic);
clang_getSpellingLocation(diag_loc, &file, &line, &column, nullptr);
std::string file_name;
if (FileName(file)) file_name = FileName(file)->path + ":";
LOG_S(WARNING) << file_name << line << ":" << column << " "
<< ToString(clang_getDiagnosticSpelling(diagnostic));
clang_disposeDiagnostic(diagnostic);
}
};
callback.enteredMainFile = [](CXClientData client_data, CXFile main_file,
void* reserved) -> CXIdxClientFile {
return nullptr;
};
callback.ppIncludedFile =
[](CXClientData client_data,
const CXIdxIncludedFileInfo* file) -> CXIdxClientFile {
return nullptr;
};
callback.importedASTFile =
[](CXClientData client_data,
const CXIdxImportedASTFileInfo*) -> CXIdxClientASTFile {
return nullptr;
};
callback.startedTranslationUnit =
[](CXClientData client_data, void* reserved) -> CXIdxClientContainer {
return nullptr;
};
callback.indexDeclaration = [](CXClientData client_data,
const CXIdxDeclInfo* decl) {};
callback.indexEntityReference = [](CXClientData client_data,
const CXIdxEntityRefInfo* ref) {};
const unsigned k_index_opts = 0;
CXIndexAction index_action = clang_IndexAction_create(tu->cx_tu);
ClientData index_param;
clang_toggleCrashRecovery(0);
clang_indexTranslationUnit(index_action, &index_param, &callback,
sizeof(IndexerCallbacks), k_index_opts,
tu->cx_tu);
clang_IndexAction_dispose(index_action);
LOG_S(INFO) << "Got " << index_param.num_diagnostics << " diagnostics";
}
std::string GetClangVersion() {
std::string version_string = ToString(clang_getClangVersion());
return SplitString(version_string, " ")[2];
}
// |SymbolRef| is serialized this way.
// |Use| also uses this though it has an extra field |file|,
// which is not used by Index* so it does not need to be serialized.
void Reflect(Reader& visitor, Reference& value) {
if (visitor.Format() == serialize_format::Json) {
std::string t = visitor.GetString();
char* s = const_cast<char*>(t.c_str());
value.range = Range(s);
s = strchr(s, '|');
value.id.id = RawId(strtol(s + 1, &s, 10));
value.kind = static_cast<SymbolKind>(strtol(s + 1, &s, 10));
value.role = static_cast<role>(strtol(s + 1, &s, 10));
} else {
Reflect(visitor, value.range);
Reflect(visitor, value.id);
Reflect(visitor, value.kind);
Reflect(visitor, value.role);
}
}
void Reflect(Writer& visitor, Reference& value) {
if (visitor.Format() == serialize_format::Json) {
std::string s = value.range.ToString();
// RawId(-1) -> "-1"
s += '|' + std::to_string(
static_cast<std::make_signed<RawId>::type>(value.id.id));
s += '|' + std::to_string(int(value.kind));
s += '|' + std::to_string(int(value.role));
Reflect(visitor, s);
} else {
Reflect(visitor, value.range);
Reflect(visitor, value.id);
Reflect(visitor, value.kind);
Reflect(visitor, value.role);
}
}
| 40.521864 | 133 | 0.583428 | [
"vector"
] |
f89039dda63490c7d8078fcea75fcbd22215ad44 | 9,179 | cpp | C++ | src/StorageFolding.cpp | trgardos/Halide | 3d895bcf7c9b6632dda6445c218ed2361b698584 | [
"MIT"
] | null | null | null | src/StorageFolding.cpp | trgardos/Halide | 3d895bcf7c9b6632dda6445c218ed2361b698584 | [
"MIT"
] | null | null | null | src/StorageFolding.cpp | trgardos/Halide | 3d895bcf7c9b6632dda6445c218ed2361b698584 | [
"MIT"
] | 1 | 2021-02-18T14:18:09.000Z | 2021-02-18T14:18:09.000Z | #include "StorageFolding.h"
#include "IROperator.h"
#include "IRMutator.h"
#include "Simplify.h"
#include "Bounds.h"
#include "IRPrinter.h"
#include "Substitute.h"
#include "Debug.h"
#include "Monotonic.h"
#include "ExprUsesVar.h"
namespace Halide {
namespace Internal {
using std::string;
using std::vector;
using std::map;
// Fold the storage of a function in a particular dimension by a particular factor
class FoldStorageOfFunction : public IRMutator {
string func;
int dim;
Expr factor;
using IRMutator::visit;
void visit(const Call *op) {
IRMutator::visit(op);
op = expr.as<Call>();
internal_assert(op);
if (op->name == func && op->call_type == Call::Halide) {
vector<Expr> args = op->args;
internal_assert(dim < (int)args.size());
args[dim] = is_one(factor) ? 0 : (args[dim] % factor);
expr = Call::make(op->type, op->name, args, op->call_type,
op->func, op->value_index, op->image, op->param);
}
}
void visit(const Provide *op) {
IRMutator::visit(op);
op = stmt.as<Provide>();
internal_assert(op);
if (op->name == func) {
vector<Expr> args = op->args;
args[dim] = is_one(factor) ? 0 : (args[dim] % factor);
stmt = Provide::make(op->name, op->values, args);
}
}
public:
FoldStorageOfFunction(string f, int d, Expr e) :
func(f), dim(d), factor(e) {}
};
// Attempt to fold the storage of a particular function in a statement
class AttemptStorageFoldingOfFunction : public IRMutator {
string func;
using IRMutator::visit;
void visit(const ProducerConsumer *op) {
if (op->name == func) {
// Can't proceed into the pipeline for this func
stmt = op;
} else {
IRMutator::visit(op);
}
}
void visit(const For *op) {
if (op->for_type != ForType::Serial && op->for_type != ForType::Unrolled) {
// We can't proceed into a parallel for loop.
// TODO: If there's no overlap between the region touched
// by the threads as this loop counter varies
// (i.e. there's no cross-talk between threads), then it's
// safe to proceed.
stmt = op;
return;
}
Box box = box_touched(op->body, func);
Stmt result = op;
// Try each dimension in turn from outermost in
for (size_t i = box.size(); i > 0; i--) {
Expr min = simplify(box[i-1].min);
Expr max = simplify(box[i-1].max);
debug(3) << "\nConsidering folding " << func << " over for loop over " << op->name << '\n'
<< "Min: " << min << '\n'
<< "Max: " << max << '\n';
bool min_monotonic_increasing =
(is_monotonic(min, op->name) == Monotonic::Increasing);
bool max_monotonic_decreasing =
(is_monotonic(max, op->name) == Monotonic::Decreasing);
// The min or max has to be monotonic with the loop
// variable, and should depend on the loop variable.
if (min_monotonic_increasing ||
max_monotonic_decreasing) {
// The max of the extent over all values of the loop variable must be a constant
Expr extent = simplify(max - min);
Scope<Interval> scope;
scope.push(op->name, Interval(Variable::make(Int(32), op->name + ".loop_min"),
Variable::make(Int(32), op->name + ".loop_max")));
Expr max_extent = bounds_of_expr_in_scope(extent, scope).max;
scope.pop(op->name);
max_extent = find_constant_bound(simplify(max_extent), Direction::Upper);
if (const int64_t *extent = as_const_int(max_extent)) {
int factor = 1;
while (factor <= *extent && factor < 1024) factor *= 2;
debug(3) << "Proceeding with factor " << factor << "\n";
Fold fold = {(int)i - 1, factor};
dims_folded.push_back(fold);
result = FoldStorageOfFunction(func, (int)i - 1, factor).mutate(result);
Expr next_var = Variable::make(Int(32), op->name) + 1;
Expr next_min = substitute(op->name, next_var, min);
if (is_one(simplify(max < next_min))) {
// There's no overlapping usage between loop
// iterations, so we can continue to search
// for further folding opportinities
// recursively.
} else {
stmt = result;
return;
}
} else {
debug(3) << "Not folding because extent not bounded by a constant\n"
<< "extent = " << extent << "\n"
<< "max extent = " << max_extent << "\n";
}
} else {
debug(3) << "Not folding because loop min or max not monotonic in the loop variable\n"
<< "min = " << min << "\n"
<< "max = " << max << "\n";
}
}
// Any folds that took place folded dimensions away entirely, so we can proceed recursively.
if (const For *f = result.as<For>()) {
Stmt body = mutate(f->body);
if (body.same_as(f->body)) {
stmt = result;
} else {
stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
}
} else {
stmt = result;
}
}
public:
struct Fold {
int dim;
Expr factor;
};
vector<Fold> dims_folded;
AttemptStorageFoldingOfFunction(string f) : func(f) {}
};
/** Check if a buffer's allocated is referred to directly via an
* intrinsic. If so we should leave it alone. (e.g. it may be used
* extern). */
class IsBufferSpecial : public IRVisitor {
public:
string func;
bool special = false;
IsBufferSpecial(string f) : func(f) {}
private:
using IRVisitor::visit;
void visit(const Variable *var) {
if (var->type.is_handle() &&
var->name == func + ".buffer") {
special = true;
}
}
};
// Look for opportunities for storage folding in a statement
class StorageFolding : public IRMutator {
using IRMutator::visit;
void visit(const Realize *op) {
Stmt body = mutate(op->body);
AttemptStorageFoldingOfFunction folder(op->name);
IsBufferSpecial special(op->name);
op->accept(&special);
if (special.special) {
debug(3) << "Not attempting to fold " << op->name << " because its buffer is used\n";
if (body.same_as(op->body)) {
stmt = op;
} else {
stmt = Realize::make(op->name, op->types, op->bounds, op->condition, body);
}
} else {
debug(3) << "Attempting to fold " << op->name << "\n";
Stmt new_body = folder.mutate(body);
if (new_body.same_as(op->body)) {
stmt = op;
} else if (new_body.same_as(body)) {
stmt = Realize::make(op->name, op->types, op->bounds, op->condition, body);
} else {
Region bounds = op->bounds;
for (size_t i = 0; i < folder.dims_folded.size(); i++) {
int d = folder.dims_folded[i].dim;
Expr f = folder.dims_folded[i].factor;
internal_assert(d >= 0 &&
d < (int)bounds.size());
bounds[d] = Range(0, f);
}
stmt = Realize::make(op->name, op->types, bounds, op->condition, new_body);
}
}
}
};
// Because storage folding runs before simplification, it's useful to
// at least substitute in constants before running it, and also simplify the RHS of Let Stmts.
class SubstituteInConstants : public IRMutator {
using IRMutator::visit;
Scope<Expr> scope;
void visit(const LetStmt *op) {
Expr value = simplify(mutate(op->value));
Stmt body;
if (is_const(value)) {
scope.push(op->name, value);
body = mutate(op->body);
scope.pop(op->name);
} else {
body = mutate(op->body);
}
if (body.same_as(op->body) && value.same_as(op->value)) {
stmt = op;
} else {
stmt = LetStmt::make(op->name, value, body);
}
}
void visit(const Variable *op) {
if (scope.contains(op->name)) {
expr = scope.get(op->name);
} else {
expr = op;
}
}
};
Stmt storage_folding(Stmt s) {
s = SubstituteInConstants().mutate(s);
s = StorageFolding().mutate(s);
return s;
}
}
}
| 32.434629 | 102 | 0.513346 | [
"vector"
] |
f8967b2a256ea2bd18816dd37f038a864bf58ef1 | 1,741 | cpp | C++ | 0001-0100/79-word-search/main.cpp | janreggie/leetcode | c59718e127b598c4de7d07c9c93064eb12b2e5c9 | [
"MIT",
"Unlicense"
] | null | null | null | 0001-0100/79-word-search/main.cpp | janreggie/leetcode | c59718e127b598c4de7d07c9c93064eb12b2e5c9 | [
"MIT",
"Unlicense"
] | null | null | null | 0001-0100/79-word-search/main.cpp | janreggie/leetcode | c59718e127b598c4de7d07c9c93064eb12b2e5c9 | [
"MIT",
"Unlicense"
] | null | null | null | #include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
class Solution
{
size_t _width, _height;
std::vector<std::vector<char>> _board;
std::string _word;
public:
bool exist(const std::vector<std::vector<char>>& board, const std::string& word)
{
_height = board.size();
_width = board[0].size();
_board = board;
_word = word;
for (size_t x = 0; x < _width; ++x) {
for (size_t y = 0; y < _height; ++y) {
if (_word[0] == _board[y][x] && exist(0, x, y)) {
return true;
}
}
}
return false;
}
private:
// Check if word[ind:] exists starting from board[y][x]
bool exist(size_t ind, size_t x, size_t y)
{
if (ind == _word.size()) {
return true;
}
if (x >= _width || y >= _height) {
return false;
}
const char first = _word.at(ind);
if (_board[y][x] != first) {
return false;
}
_board[y][x] = ' '; // Set it to any character
const bool result = exist(ind + 1, x - 1, y) ||
exist(ind + 1, x + 1, y) ||
exist(ind + 1, x, y - 1) ||
exist(ind + 1, x, y + 1);
_board[y][x] = first;
return result;
}
};
template<class T, class U>
std::ostream&
operator<<(std::ostream& os, const std::pair<T, U>& p)
{
os << "(" << p.first << "," << p.second << ")";
return os;
}
int
main()
{
const std::vector<std::vector<char>> board{
{ 'A', 'B', 'C', 'E' },
{ 'S', 'F', 'E', 'S' },
{ 'A', 'D', 'E', 'E' }
};
const std::vector<std::pair<std::string, bool>> testcases{
{ "ABCESEEEFS", true }
};
for (const auto& tc : testcases) {
std::cout << "testing " << tc << std::endl;
Solution soln;
const bool actual = soln.exist(board, tc.first);
if (tc.second != actual) {
return 1;
}
}
}
| 19.561798 | 81 | 0.552556 | [
"vector"
] |
f89710adbe742717e1b07994359d52511326b8ea | 3,939 | cpp | C++ | LibMathematics/CurvesSurfacesVolumes/Wm5BSplineFitBasis.cpp | bazhenovc/WildMagic | b1a7cc2140dde23d8d9a4ece52a07bd5ff938239 | [
"BSL-1.0"
] | 48 | 2015-10-07T07:26:14.000Z | 2022-03-18T14:30:07.000Z | LibMathematics/CurvesSurfacesVolumes/Wm5BSplineFitBasis.cpp | zouxiaohang/WildMagic | b1a7cc2140dde23d8d9a4ece52a07bd5ff938239 | [
"BSL-1.0"
] | null | null | null | LibMathematics/CurvesSurfacesVolumes/Wm5BSplineFitBasis.cpp | zouxiaohang/WildMagic | b1a7cc2140dde23d8d9a4ece52a07bd5ff938239 | [
"BSL-1.0"
] | 21 | 2015-09-01T03:14:47.000Z | 2022-01-04T04:07:46.000Z | // Geometric Tools, LLC
// Copyright (c) 1998-2012
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.1 (2010/10/01)
#include "Wm5MathematicsPCH.h"
#include "Wm5BSplineFitBasis.h"
#include "Wm5Memory.h"
namespace Wm5
{
//----------------------------------------------------------------------------
template <typename Real>
BSplineFitBasis<Real>::BSplineFitBasis (int quantity, int degree)
{
assertion(1 <= degree && degree < quantity, "Invalid inputs.\n");
mQuantity = quantity;
mDegree = degree;
mValue = new1<Real>(degree + 1);
mKnot = new1<Real>(2*degree);
}
//----------------------------------------------------------------------------
template <typename Real>
BSplineFitBasis<Real>::~BSplineFitBasis ()
{
delete1(mValue);
delete1(mKnot);
}
//----------------------------------------------------------------------------
template <typename Real>
int BSplineFitBasis<Real>::GetQuantity () const
{
return mQuantity;
}
//----------------------------------------------------------------------------
template <typename Real>
int BSplineFitBasis<Real>::GetDegree () const
{
return mDegree;
}
//----------------------------------------------------------------------------
template <typename Real>
void BSplineFitBasis<Real>::Compute (Real t, int& imin, int& imax) const
{
assertion((Real)0 <= t && t <= (Real)1, "Invalid input.\n");
// Use scaled time and scaled knots so that 1/(Q-D) does not need to
// be explicitly stored by the class object. Determine the extreme
// indices affected by local control.
Real QmD = (Real)(mQuantity - mDegree);
Real tValue;
if (t <= (Real)0)
{
tValue = (Real)0;
imin = 0;
imax = mDegree;
}
else if (t >= (Real)1)
{
tValue = QmD;
imax = mQuantity - 1;
imin = imax - mDegree;
}
else
{
tValue = QmD*t;
imin = (int)tValue;
imax = imin + mDegree;
}
// Precompute the knots.
for (int i0 = 0, i1 = imax+1-mDegree; i0 < 2*mDegree; ++i0, ++i1)
{
if (i1 <= mDegree)
{
mKnot[i0] = (Real)0;
}
else if (i1 >= mQuantity)
{
mKnot[i0] = QmD;
}
else
{
mKnot[i0] = (Real)(i1 - mDegree);
}
}
// Initialize the basis function evaluation table. The first degree-1
// entries are zero, but they do not have to be set explicitly.
mValue[mDegree] = (Real)1;
// Update the basis function evaluation table, each iteration overwriting
// the results from the previous iteration.
for (int row = mDegree-1; row >= 0; --row)
{
int k0 = mDegree, k1 = row;
Real knot0 = mKnot[k0], knot1 = mKnot[k1];
Real invDenom = ((Real)1)/(knot0 - knot1);
Real c1 = (knot0 - tValue)*invDenom, c0;
mValue[row] = c1*mValue[row + 1];
for (int col = row + 1; col < mDegree; ++col)
{
c0 = (tValue - knot1)*invDenom;
mValue[col] *= c0;
knot0 = mKnot[++k0];
knot1 = mKnot[++k1];
invDenom = ((Real)1)/(knot0 - knot1);
c1 = (knot0 - tValue)*invDenom;
mValue[col] += c1*mValue[col + 1];
}
c0 = (tValue - knot1)*invDenom;
mValue[mDegree] *= c0;
}
}
//----------------------------------------------------------------------------
template <typename Real>
Real BSplineFitBasis<Real>::GetValue (int i) const
{
assertion(0 <= i && i <= mDegree, "Invalid index\n");
return mValue[i];
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Explicit instantiation.
//----------------------------------------------------------------------------
template WM5_MATHEMATICS_ITEM
class BSplineFitBasis<float>;
template WM5_MATHEMATICS_ITEM
class BSplineFitBasis<double>;
//----------------------------------------------------------------------------
}
| 27.93617 | 79 | 0.503173 | [
"object"
] |
f89e47854d27361fc393c35b3a5188a2213290f9 | 1,006 | cc | C++ | examples/load_model/main.cc | Liuweiming/tensorflow_c | 2bb512ba20bafc21e1d6a9940b93cde8f4080ab5 | [
"MIT"
] | 1 | 2021-03-02T06:29:23.000Z | 2021-03-02T06:29:23.000Z | examples/load_model/main.cc | Liuweiming/tensorflow_c | 2bb512ba20bafc21e1d6a9940b93cde8f4080ab5 | [
"MIT"
] | null | null | null | examples/load_model/main.cc | Liuweiming/tensorflow_c | 2bb512ba20bafc21e1d6a9940b93cde8f4080ab5 | [
"MIT"
] | null | null | null | //
// Created by sergio on 16/05/19.
//
#include <iomanip>
#include <numeric>
#include "model.h"
#include "tensor.h"
using namespace tf_cpp;
int main() {
Model model("load_model.pb");
std::cout << "operations: -----------" << std::endl;
for (auto &op : model.get_operations()) {
std::cout << op << std::endl;
}
std::cout << "-------------------" << std::endl;
Tensor input_a(model.get_graph(), "input_a", {1, 100}, TF_FLOAT);
Tensor input_b(model.get_graph(), "input_b", {1, 100}, TF_FLOAT);
Tensor output(model.get_graph(), "result", {1, 100}, TF_FLOAT);
std::vector<float> data(100);
std::iota(data.begin(), data.end(), 0);
for (std::size_t i = 0; i != data.size(); ++i) {
input_a.at<float>(0, i) = data[i];
input_b.at<float>(0, i) = data[i];
}
model.run({&input_a, &input_b}, {&output});
for (std::size_t i = 0; i != data.size(); ++i) {
std::cout << output.at<float>(0, i) << " ";
}
std::cout << std::endl;
}
| 25.794872 | 68 | 0.540755 | [
"vector",
"model"
] |
f8a6f26c821fccb1b8850d02ae221834e55dcf06 | 5,551 | cpp | C++ | sources/obj/train.cpp | marcin-sucharski/Train3D | 7b271eb15e5479e596307047469ea5582ab062c2 | [
"MIT"
] | 2 | 2017-02-07T21:28:37.000Z | 2019-07-09T10:55:57.000Z | sources/obj/train.cpp | marcin-sucharski/Train3D | 7b271eb15e5479e596307047469ea5582ab062c2 | [
"MIT"
] | null | null | null | sources/obj/train.cpp | marcin-sucharski/Train3D | 7b271eb15e5479e596307047469ea5582ab062c2 | [
"MIT"
] | null | null | null | #include "train.h"
#include "../res/vertex-format.h"
#include "../res/mesh-generator.h"
#include <glm/gtx/vector_angle.hpp>
using namespace glm;
namespace train {
namespace obj {
const float Train::initialVelocity = 7.f;
const float Train::minimalVelocity = 2.f;
const float Train::plankLength = 1.5f;
const float Train::plankWidth = 0.64f;
const float Train::plankHeight = 0.1f;
const float Train::wheelRadius = 0.4f;
const float Train::wheelWidth = 0.07f;
const float Train::connectionWidth = 0.06f;
const float Train::trainYOffset = wheelRadius + 0.1f;
const float Train::accelerationG = 9.8f;
Train::Train(gfx::ShaderManager &shaderManager, Rails &rails)
: curveProvider(rails.getCurve()),
curve(rails.getCurve()),
wheelAngle(0.0f),
velocity(initialVelocity),
totalDistance(0.f),
wheelTexture(gfx::Texture::fromFile("data/textures/wheel.png")),
plankTexture(gfx::Texture::fromFile("data/textures/plank.png")),
wheelMesh(buildWheelMesh()),
plankMesh(buildPlankMesh()),
wheelConnectionMesh(buildWheelConnectionMesh()),
shader(prepareShader(shaderManager)) {
}
void Train::update(double dt) {
if (!curve.hasNext()) {
curve.restart();
}
const auto curr = curve.getCurrentPoint();
const auto diff = static_cast<float>(dt) * velocity;
const auto next = curve.getNext(diff);
totalDistance += diff;
const float kineticEnergy = velocity * velocity * 0.5f;
const float energyDiff = (curr.position.y - next.position.y) * accelerationG;
const float newKineticEnergy = kineticEnergy + energyDiff;
velocity = sqrt(newKineticEnergy * 2.f);
velocity = max(velocity, minimalVelocity);
velocity -= (velocity * velocity) * 0.01f * dt;
}
void Train::draw(const model::Camera &camera) {
const auto current = curve.getCurrentPoint();
mat4x4 trainModel = inverse(lookAt(
current.position,
current.position + current.forward,
current.up
));
trainModel = rotate(trainModel, radians(90.f), vec3(0.f, 1.f, 0.f));
trainModel = translate(trainModel, vec3(0.f, trainYOffset, 0.f));
shader.bind();
shader.setUniform("projectionView", camera.getProjectionView());
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, wheelTexture.getHandle());
shader.setUniform("diffuse", 0);
const float sign[2] = {1.0f, -1.0f};
for (int i = 0; i < 4; ++i) {
mat4x4 model = trainModel;
model = translate(model, vec3(0.f, 0.f, 1.f) * plankWidth * 0.5f * sign[(i + 1) % 2]);
model = translate(model, vec3(0.f, 0.f, 1.f) * wheelWidth * 0.5f * sign[(i + 1) % 2]);
model = translate(model, vec3(1.f, 0.f, 0.f) * plankLength * 0.5f * 0.9f * sign[i >= 2]);
model = rotate(model, radians(90.f), vec3(1.f, 0.f, 0.f));
model = translate(model, vec3(0.f, wheelWidth * -0.5f, 0.f));
const float rot = totalDistance / wheelRadius;
model = rotate(model, pi<float>() * 0.3f * i - rot, vec3(0.f, 1.f, 0.f));
shader.setUniform("model", model);
shader.setUniform("invModel", transpose(inverse(model)));
wheelMesh.draw();
}
for (int i = 0; i < 2; ++i) {
mat4x4 model = trainModel;
model = translate(model, vec3(0.f, 0.f, plankWidth * 0.5f + wheelWidth * 1.5f) * sign[i % 2]);
const float rot = totalDistance / wheelRadius;
model = translate(model, vec3(sin(rot), cos(rot), 0.f) * wheelRadius * 0.8f);
shader.setUniform("model", model);
shader.setUniform("invModel", transpose(inverse(model)));
wheelConnectionMesh.draw();
}
glBindTexture(GL_TEXTURE_2D, wheelTexture.getHandle());
mat4x4 plankModel = trainModel;
shader.setUniform("model", plankModel);
shader.setUniform("invModel", transpose(inverse(plankModel)));
plankMesh.draw();
shader.unbind();
}
gfx::ShaderProgram &Train::prepareShader(gfx::ShaderManager &shaderManager) {
return shaderManager.get(
"vert/standard.glsl",
"frag/standard.glsl",
res::StandardVertex::Definition
);
}
gfx::Mesh Train::buildWheelMesh() {
auto wheelMeshData = res::MeshGenerator::cylinder(64, wheelRadius, wheelWidth);
return gfx::Mesh::create(wheelMeshData);
}
gfx::Mesh Train::buildPlankMesh() {
auto plankMeshData = res::MeshGenerator::texturedCube(vec3(plankLength, plankHeight, plankWidth) * 0.5f);
return gfx::Mesh::create(plankMeshData);
}
gfx::Mesh Train::buildWheelConnectionMesh() {
auto conn = res::MeshGenerator::texturedCube(vec3(
plankLength * 0.5f * 0.9f,
connectionWidth,
connectionWidth
));
return gfx::Mesh::create(conn);
}
}
} | 40.224638 | 117 | 0.554134 | [
"mesh",
"model"
] |
f8a70b6ad16d8d58bd79c355ecec18415ebff8a2 | 1,840 | cpp | C++ | src/ZeroDim.cpp | iit-DLSLab/locomotion-viewer | 854985b65204ecb4727e702227f896efe9a4c3e2 | [
"Apache-2.0"
] | 6 | 2020-04-06T10:09:14.000Z | 2022-01-07T02:05:06.000Z | src/ZeroDim.cpp | iit-DLSLab/locomotion-viewer | 854985b65204ecb4727e702227f896efe9a4c3e2 | [
"Apache-2.0"
] | null | null | null | src/ZeroDim.cpp | iit-DLSLab/locomotion-viewer | 854985b65204ecb4727e702227f896efe9a4c3e2 | [
"Apache-2.0"
] | 2 | 2018-12-24T12:17:26.000Z | 2021-03-01T23:21:10.000Z | //
// Created by Romeo Orsolino on 06/04/2020.
//
#include <locomotion_viewer/ZeroDim.h>
namespace locomotion_viewer {
ZeroDim::ZeroDim(std::string base_frame,
std::string marker_topic,
ros::NodeHandle nh) : RvizVisualTools(base_frame, marker_topic, nh) {}
ZeroDim::~ZeroDim() {}
bool ZeroDim::publishEigenSphere(Eigen::Vector3d & point,
rviz_visual_tools::colors color,
rviz_visual_tools::scales scale,
const std::string & ns)
{
geometry_msgs::Point temp;
temp.x = point(0);
temp.y = point(1);
temp.z = point(2);
publishSphere(temp, color, scale, "com");
}
bool ZeroDim::publishEigenSpheres(Eigen::VectorXd & eigen_path_x,
Eigen::VectorXd & eigen_path_y,
Eigen::VectorXd & eigen_path_z,
rviz_visual_tools::colors color,
rviz_visual_tools::scales scale,
const std::string & ns)
{
geometry_msgs::Point temp;
geometry_msgs::Point first;
std::vector<geometry_msgs::Point> trajectory;
int points_num = eigen_path_x.rows();
for (std::size_t i = 0; i < points_num; ++i)
{
temp.x = eigen_path_x(i);
temp.y = eigen_path_y(i);
temp.z = eigen_path_z(i);
if (i == 0)
{
first = temp;
}
trajectory.push_back(temp);
}
publishSpheres(trajectory, color, scale, "intermediate_points");
}
} | 31.724138 | 89 | 0.474457 | [
"vector"
] |
f8a97a4f8941fb5d19f6b9ae17dbe0bcbf2ca794 | 33,147 | cpp | C++ | build/cpp_test/src/massive/munit/client/PrintClientBase.cpp | TomBebb/hxecs | 80620512df7b32d70f1b59facdf8f6349192a166 | [
"BSD-3-Clause"
] | null | null | null | build/cpp_test/src/massive/munit/client/PrintClientBase.cpp | TomBebb/hxecs | 80620512df7b32d70f1b59facdf8f6349192a166 | [
"BSD-3-Clause"
] | null | null | null | build/cpp_test/src/massive/munit/client/PrintClientBase.cpp | TomBebb/hxecs | 80620512df7b32d70f1b59facdf8f6349192a166 | [
"BSD-3-Clause"
] | null | null | null | // Generated by Haxe 3.4.7
#include <hxcpp.h>
#ifndef INCLUDED_Lambda
#include <Lambda.h>
#endif
#ifndef INCLUDED_List
#include <List.h>
#endif
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_StringBuf
#include <StringBuf.h>
#endif
#ifndef INCLUDED_StringTools
#include <StringTools.h>
#endif
#ifndef INCLUDED__List_ListNode
#include <_List/ListNode.h>
#endif
#ifndef INCLUDED_massive_haxe_Exception
#include <massive/haxe/Exception.h>
#endif
#ifndef INCLUDED_massive_munit_AssertionException
#include <massive/munit/AssertionException.h>
#endif
#ifndef INCLUDED_massive_munit_IAdvancedTestResultClient
#include <massive/munit/IAdvancedTestResultClient.h>
#endif
#ifndef INCLUDED_massive_munit_ICoverageTestResultClient
#include <massive/munit/ICoverageTestResultClient.h>
#endif
#ifndef INCLUDED_massive_munit_ITestResultClient
#include <massive/munit/ITestResultClient.h>
#endif
#ifndef INCLUDED_massive_munit_MUnitException
#include <massive/munit/MUnitException.h>
#endif
#ifndef INCLUDED_massive_munit_TestResult
#include <massive/munit/TestResult.h>
#endif
#ifndef INCLUDED_massive_munit_client_AbstractTestResultClient
#include <massive/munit/client/AbstractTestResultClient.h>
#endif
#ifndef INCLUDED_massive_munit_client_PrintClientBase
#include <massive/munit/client/PrintClientBase.h>
#endif
#ifndef INCLUDED_massive_munit_util_MathUtil
#include <massive/munit/util/MathUtil.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_35_new,"massive.munit.client.PrintClientBase","new",0x78e7185f,"massive.munit.client.PrintClientBase.new","massive/munit/client/PrintClientBase.hx",35,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_57_initializeTestClass,"massive.munit.client.PrintClientBase","initializeTestClass",0x4df93115,"massive.munit.client.PrintClientBase.initializeTestClass","massive/munit/client/PrintClientBase.hx",57,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_63_updateTestClass,"massive.munit.client.PrintClientBase","updateTestClass",0xc78451bc,"massive.munit.client.PrintClientBase.updateTestClass","massive/munit/client/PrintClientBase.hx",63,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_80_finalizeTestClass,"massive.munit.client.PrintClientBase","finalizeTestClass",0x6abe5547,"massive.munit.client.PrintClientBase.finalizeTestClass","massive/munit/client/PrintClientBase.hx",80,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_104_setCurrentTestClassCoverage,"massive.munit.client.PrintClientBase","setCurrentTestClassCoverage",0xe1d848d6,"massive.munit.client.PrintClientBase.setCurrentTestClassCoverage","massive/munit/client/PrintClientBase.hx",104,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_114_reportFinalCoverage,"massive.munit.client.PrintClientBase","reportFinalCoverage",0xbc183c29,"massive.munit.client.PrintClientBase.reportFinalCoverage","massive/munit/client/PrintClientBase.hx",114,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_149_printIndentedLines,"massive.munit.client.PrintClientBase","printIndentedLines",0x85b904a8,"massive.munit.client.PrintClientBase.printIndentedLines","massive/munit/client/PrintClientBase.hx",149,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_159_printReports,"massive.munit.client.PrintClientBase","printReports",0x9ce900b3,"massive.munit.client.PrintClientBase.printReports","massive/munit/client/PrintClientBase.hx",159,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_163_printFinalIgnoredStatistics,"massive.munit.client.PrintClientBase","printFinalIgnoredStatistics",0x09275b8b,"massive.munit.client.PrintClientBase.printFinalIgnoredStatistics","massive/munit/client/PrintClientBase.hx",163,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_185_filterIngored,"massive.munit.client.PrintClientBase","filterIngored",0x7df97a0b,"massive.munit.client.PrintClientBase.filterIngored","massive/munit/client/PrintClientBase.hx",185,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_189_printFinalStatistics,"massive.munit.client.PrintClientBase","printFinalStatistics",0x9f291dad,"massive.munit.client.PrintClientBase.printFinalStatistics","massive/munit/client/PrintClientBase.hx",189,0x1ddc6930)
static const ::String _hx_array_data_4385fced_19[] = {
HX_("\nTests: ",dd,c9,27,c7),
};
static const ::String _hx_array_data_4385fced_20[] = {
HX_(" Passed: ",36,9a,0f,7e),
};
static const ::String _hx_array_data_4385fced_21[] = {
HX_(" Failed: ",c3,79,b7,3a),
};
static const ::String _hx_array_data_4385fced_22[] = {
HX_(" Errors: ",51,13,30,17),
};
static const ::String _hx_array_data_4385fced_23[] = {
HX_(" Ignored: ",f8,ad,04,5a),
};
static const ::String _hx_array_data_4385fced_24[] = {
HX_(" Time: ",33,28,15,86),
};
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_205_printOverallResult,"massive.munit.client.PrintClientBase","printOverallResult",0x5757b77e,"massive.munit.client.PrintClientBase.printOverallResult","massive/munit/client/PrintClientBase.hx",205,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_210_print,"massive.munit.client.PrintClientBase","print",0x027fddec,"massive.munit.client.PrintClientBase.print","massive/munit/client/PrintClientBase.hx",210,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_214_printLine,"massive.munit.client.PrintClientBase","printLine",0x514f8800,"massive.munit.client.PrintClientBase.printLine","massive/munit/client/PrintClientBase.hx",214,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_221_indentString,"massive.munit.client.PrintClientBase","indentString",0xed10027e,"massive.munit.client.PrintClientBase.indentString","massive/munit/client/PrintClientBase.hx",221,0x1ddc6930)
HX_LOCAL_STACK_FRAME(_hx_pos_ff06a10c772ba8ce_40_boot,"massive.munit.client.PrintClientBase","boot",0x49673b53,"massive.munit.client.PrintClientBase.boot","massive/munit/client/PrintClientBase.hx",40,0x1ddc6930)
namespace massive{
namespace munit{
namespace client{
void PrintClientBase_obj::__construct(hx::Null< bool > __o_includeIgnoredReport){
bool includeIgnoredReport = __o_includeIgnoredReport.Default(true);
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_35_new)
HXLINE( 42) this->divider2 = HX_("==============================",a0,f8,06,d2);
HXLINE( 41) this->divider1 = HX_("------------------------------",a0,a6,7a,e6);
HXLINE( 48) super::__construct();
HXLINE( 49) this->id = HX_("simple",32,04,7f,b8);
HXLINE( 50) this->verbose = false;
HXLINE( 51) this->includeIgnoredReport = includeIgnoredReport;
HXLINE( 52) this->printLine(HX_("MUnit Results",27,bf,ec,01),null());
HXLINE( 53) this->printLine(this->divider1,null());
}
Dynamic PrintClientBase_obj::__CreateEmpty() { return new PrintClientBase_obj; }
void *PrintClientBase_obj::_hx_vtable = 0;
Dynamic PrintClientBase_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< PrintClientBase_obj > _hx_result = new PrintClientBase_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool PrintClientBase_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x0097fcd8) {
return inClassId==(int)0x00000001 || inClassId==(int)0x0097fcd8;
} else {
return inClassId==(int)0x54aae2d1;
}
}
void PrintClientBase_obj::initializeTestClass(){
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_57_initializeTestClass)
HXLINE( 58) this->super::initializeTestClass();
HXLINE( 59) this->printLine(((HX_("Class: ",be,50,e2,36) + this->currentTestClass) + HX_(" ",20,00,00,00)),null());
}
void PrintClientBase_obj::updateTestClass( ::massive::munit::TestResult result){
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_63_updateTestClass)
HXLINE( 64) this->super::updateTestClass(result);
HXLINE( 65) if (this->verbose) {
HXLINE( 65) ::String _hx_tmp = ((HX_(" ",20,00,00,00) + result->name) + HX_(": ",a6,32,00,00));
HXDLIN( 65) this->printLine(((_hx_tmp + result->get_type()) + HX_(" ",20,00,00,00)),null());
}
else {
HXLINE( 68) ::String _g = result->get_type();
HXDLIN( 68) ::String _hx_switch_0 = _g;
if ( (_hx_switch_0==HX_("ERROR",a8,03,18,f1)) ){
HXLINE( 72) this->print(HX_("x",78,00,00,00));
HXDLIN( 72) goto _hx_goto_2;
}
if ( (_hx_switch_0==HX_("FAIL",de,81,76,2e)) ){
HXLINE( 71) this->print(HX_("!",21,00,00,00));
HXDLIN( 71) goto _hx_goto_2;
}
if ( (_hx_switch_0==HX_("IGNORE",12,65,4b,45)) ){
HXLINE( 73) this->print(HX_(",",2c,00,00,00));
HXDLIN( 73) goto _hx_goto_2;
}
if ( (_hx_switch_0==HX_("PASS",d1,ac,12,35)) ){
HXLINE( 70) this->print(HX_(".",2e,00,00,00));
HXDLIN( 70) goto _hx_goto_2;
}
if ( (_hx_switch_0==HX_("UNKNOWN",6a,f7,4e,61)) ){
HXLINE( 74) goto _hx_goto_2;
}
_hx_goto_2:;
}
}
void PrintClientBase_obj::finalizeTestClass(){
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_80_finalizeTestClass)
HXLINE( 81) this->super::finalizeTestClass();
HXLINE( 83) {
HXLINE( 83) int _g = (int)0;
HXDLIN( 83) ::Array< ::String > _g1 = this->getTraces();
HXDLIN( 83) while((_g < _g1->length)){
HXLINE( 83) ::String item = _g1->__get(_g);
HXDLIN( 83) _g = (_g + (int)1);
HXLINE( 85) this->printLine((HX_("TRACE: ",4b,1c,d8,07) + item),(int)1);
}
}
HXLINE( 88) {
HXLINE( 88) int _g2 = (int)0;
HXDLIN( 88) ::Array< ::Dynamic> _g11 = this->currentClassResults;
HXDLIN( 88) while((_g2 < _g11->length)){
HXLINE( 88) ::massive::munit::TestResult result = _g11->__get(_g2).StaticCast< ::massive::munit::TestResult >();
HXDLIN( 88) _g2 = (_g2 + (int)1);
HXLINE( 90) {
HXLINE( 90) ::String _g21 = result->get_type();
HXDLIN( 90) ::String _hx_switch_0 = _g21;
if ( (_hx_switch_0==HX_("ERROR",a8,03,18,f1)) ){
HXLINE( 92) this->printLine((HX_("ERROR: ",4e,70,de,69) + ::Std_obj::string(result->error)),(int)1);
HXDLIN( 92) goto _hx_goto_6;
}
if ( (_hx_switch_0==HX_("FAIL",de,81,76,2e)) ){
HXLINE( 93) this->printLine((HX_("FAIL: ",04,68,81,9a) + ::Std_obj::string(result->failure)),(int)1);
HXDLIN( 93) goto _hx_goto_6;
}
if ( (_hx_switch_0==HX_("IGNORE",12,65,4b,45)) ){
HXLINE( 95) ::String ingoredString = result->get_location();
HXLINE( 96) if (hx::IsNotNull( result->description )) {
HXLINE( 96) ingoredString = (ingoredString + (HX_(" - ",73,6f,18,00) + result->description));
}
HXLINE( 97) this->printLine((HX_("IGNORE: ",38,80,bc,ba) + ingoredString),(int)1);
HXLINE( 94) goto _hx_goto_6;
}
if ( (_hx_switch_0==HX_("PASS",d1,ac,12,35)) || (_hx_switch_0==HX_("UNKNOWN",6a,f7,4e,61)) ){
HXLINE( 98) goto _hx_goto_6;
}
_hx_goto_6:;
}
}
}
}
void PrintClientBase_obj::setCurrentTestClassCoverage( ::Dynamic result){
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_104_setCurrentTestClassCoverage)
HXLINE( 105) this->super::setCurrentTestClassCoverage(result);
HXLINE( 106) this->print(((HX_(" [",3b,1c,00,00) + ( (Float)(result->__Field(HX_("percent",c5,aa,da,78),hx::paccDynamic)) )) + HX_("%]",98,20,00,00)));
}
void PrintClientBase_obj::reportFinalCoverage( ::Dynamic __o_percent,::Array< ::Dynamic> missingCoverageResults,::String summary,::String classBreakdown,::String packageBreakdown,::String executionFrequency){
::Dynamic percent = __o_percent.Default(0);
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_114_reportFinalCoverage)
HXLINE( 115) this->super::reportFinalCoverage(percent,missingCoverageResults,summary,classBreakdown,packageBreakdown,executionFrequency);
HXLINE( 117) this->printLine(HX_("",00,00,00,00),null());
HXLINE( 118) this->printLine(this->divider1,null());
HXLINE( 119) this->printLine(HX_("COVERAGE REPORT",ec,ab,03,2a),null());
HXLINE( 120) this->printLine(this->divider1,null());
HXLINE( 122) bool _hx_tmp;
HXDLIN( 122) if (hx::IsNotNull( missingCoverageResults )) {
HXLINE( 122) _hx_tmp = (missingCoverageResults->length > (int)0);
}
else {
HXLINE( 122) _hx_tmp = false;
}
HXDLIN( 122) if (_hx_tmp) {
HXLINE( 124) this->printLine(HX_("MISSING CODE BLOCKS:",1b,96,b2,63),null());
HXLINE( 125) {
HXLINE( 125) int _g = (int)0;
HXDLIN( 125) while((_g < missingCoverageResults->length)){
HXLINE( 125) ::Dynamic result = missingCoverageResults->__get(_g);
HXDLIN( 125) _g = (_g + (int)1);
HXLINE( 127) this->printLine((((( (::String)(result->__Field(HX_("className",a3,92,3d,dc),hx::paccDynamic)) ) + HX_(" [",3b,1c,00,00)) + ( (Float)(result->__Field(HX_("percent",c5,aa,da,78),hx::paccDynamic)) )) + HX_("%]",98,20,00,00)),(int)1);
HXLINE( 128) {
HXLINE( 128) int _g1 = (int)0;
HXDLIN( 128) ::Array< ::String > _g2 = ( (::Array< ::String >)(result->__Field(HX_("blocks",86,2e,ea,a7),hx::paccDynamic)) );
HXDLIN( 128) while((_g1 < _g2->length)){
HXLINE( 128) ::String item = _g2->__get(_g1);
HXDLIN( 128) _g1 = (_g1 + (int)1);
HXLINE( 130) this->printIndentedLines(item,(int)2);
}
}
HXLINE( 132) this->printLine(HX_("",00,00,00,00),null());
}
}
}
HXLINE( 136) if (hx::IsNotNull( executionFrequency )) {
HXLINE( 138) this->printLine(HX_("CODE EXECUTION FREQUENCY:",b9,13,e4,96),null());
HXLINE( 139) this->printIndentedLines(executionFrequency,(int)1);
HXLINE( 140) this->printLine(HX_("",00,00,00,00),null());
}
HXLINE( 143) if (hx::IsNotNull( classBreakdown )) {
HXLINE( 143) this->printIndentedLines(classBreakdown,(int)0);
}
HXLINE( 144) if (hx::IsNotNull( packageBreakdown )) {
HXLINE( 144) this->printIndentedLines(packageBreakdown,(int)0);
}
HXLINE( 145) if (hx::IsNotNull( summary )) {
HXLINE( 145) this->printIndentedLines(summary,(int)0);
}
}
void PrintClientBase_obj::printIndentedLines(::String value,hx::Null< int > __o_indent){
int indent = __o_indent.Default(1);
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_149_printIndentedLines)
HXLINE( 150) ::Array< ::String > lines = value.split(HX_("\n",0a,00,00,00));
HXLINE( 151) {
HXLINE( 151) int _g = (int)0;
HXDLIN( 151) while((_g < lines->length)){
HXLINE( 151) ::String line = lines->__get(_g);
HXDLIN( 151) _g = (_g + (int)1);
HXLINE( 153) this->printLine(line,indent);
}
}
}
HX_DEFINE_DYNAMIC_FUNC2(PrintClientBase_obj,printIndentedLines,(void))
void PrintClientBase_obj::printReports(){
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_159_printReports)
HXDLIN( 159) this->printFinalIgnoredStatistics(this->ignoreCount);
}
void PrintClientBase_obj::printFinalIgnoredStatistics(int count){
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_163_printFinalIgnoredStatistics)
HXLINE( 164) bool _hx_tmp;
HXDLIN( 164) if (!(!(this->includeIgnoredReport))) {
HXLINE( 164) _hx_tmp = (count == (int)0);
}
else {
HXLINE( 164) _hx_tmp = true;
}
HXDLIN( 164) if (_hx_tmp) {
HXLINE( 164) return;
}
HXLINE( 166) ::List items = ::Lambda_obj::filter(this->totalResults,this->filterIngored_dyn());
HXLINE( 168) if ((items->length == (int)0)) {
HXLINE( 168) return;
}
HXLINE( 170) this->printLine(HX_("",00,00,00,00),null());
HXLINE( 171) this->printLine(((HX_("Ignored (",7a,9b,b5,50) + count) + HX_("):",f1,23,00,00)),null());
HXLINE( 172) this->printLine(this->divider1,null());
HXLINE( 174) {
HXLINE( 174) ::_List::ListNode _g_head = items->h;
HXDLIN( 174) while(hx::IsNotNull( _g_head )){
HXLINE( 174) ::massive::munit::TestResult val = ( ( ::massive::munit::TestResult)(_g_head->item) );
HXDLIN( 174) _g_head = _g_head->next;
HXDLIN( 174) ::massive::munit::TestResult result = val;
HXLINE( 176) ::String ingoredString = result->get_location();
HXLINE( 177) if (hx::IsNotNull( result->description )) {
HXLINE( 177) ingoredString = (ingoredString + (HX_(" - ",73,6f,18,00) + result->description));
}
HXLINE( 178) this->printLine((HX_("IGNORE: ",38,80,bc,ba) + ingoredString),(int)1);
}
}
HXLINE( 180) this->printLine(HX_("",00,00,00,00),null());
}
HX_DEFINE_DYNAMIC_FUNC1(PrintClientBase_obj,printFinalIgnoredStatistics,(void))
bool PrintClientBase_obj::filterIngored( ::massive::munit::TestResult result){
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_185_filterIngored)
HXDLIN( 185) return (result->get_type() == HX_("IGNORE",12,65,4b,45));
}
HX_DEFINE_DYNAMIC_FUNC1(PrintClientBase_obj,filterIngored,return )
void PrintClientBase_obj::printFinalStatistics(bool result,int testCount,int passCount,int failCount,int errorCount,int ignoreCount,Float time){
HX_GC_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_189_printFinalStatistics)
HXLINE( 190) this->printLine(this->divider2,null());
HXLINE( 191) ::StringBuf sb = ::StringBuf_obj::__alloc( HX_CTX );
HXLINE( 192) {
HXLINE( 192) ::String x;
HXDLIN( 192) if (result) {
HXLINE( 192) x = HX_("PASSED",70,7f,b4,a0);
}
else {
HXLINE( 192) x = HX_("FAILED",bd,71,81,9a);
}
HXDLIN( 192) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 192) sb->flush();
}
HXDLIN( 192) if (hx::IsNull( sb->b )) {
HXLINE( 192) sb->b = ::Array_obj< ::String >::__new(1)->init(0,::Std_obj::string(x));
}
else {
HXLINE( 192) ::Array< ::String > sb1 = sb->b;
HXDLIN( 192) sb1->push(::Std_obj::string(x));
}
}
HXLINE( 193) {
HXLINE( 193) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 193) sb->flush();
}
HXDLIN( 193) if (hx::IsNull( sb->b )) {
HXLINE( 193) sb->b = ::Array_obj< ::String >::fromData( _hx_array_data_4385fced_19,1);
}
else {
HXLINE( 193) sb->b->push(HX_("\nTests: ",dd,c9,27,c7));
}
}
HXDLIN( 193) {
HXLINE( 193) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 193) sb->flush();
}
HXDLIN( 193) if (hx::IsNull( sb->b )) {
HXLINE( 193) sb->b = ::Array_obj< ::String >::__new(1)->init(0,::Std_obj::string(testCount));
}
else {
HXLINE( 193) ::Array< ::String > sb2 = sb->b;
HXDLIN( 193) sb2->push(::Std_obj::string(testCount));
}
}
HXLINE( 194) {
HXLINE( 194) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 194) sb->flush();
}
HXDLIN( 194) if (hx::IsNull( sb->b )) {
HXLINE( 194) sb->b = ::Array_obj< ::String >::fromData( _hx_array_data_4385fced_20,1);
}
else {
HXLINE( 194) sb->b->push(HX_(" Passed: ",36,9a,0f,7e));
}
}
HXDLIN( 194) {
HXLINE( 194) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 194) sb->flush();
}
HXDLIN( 194) if (hx::IsNull( sb->b )) {
HXLINE( 194) sb->b = ::Array_obj< ::String >::__new(1)->init(0,::Std_obj::string(passCount));
}
else {
HXLINE( 194) ::Array< ::String > sb3 = sb->b;
HXDLIN( 194) sb3->push(::Std_obj::string(passCount));
}
}
HXLINE( 195) {
HXLINE( 195) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 195) sb->flush();
}
HXDLIN( 195) if (hx::IsNull( sb->b )) {
HXLINE( 195) sb->b = ::Array_obj< ::String >::fromData( _hx_array_data_4385fced_21,1);
}
else {
HXLINE( 195) sb->b->push(HX_(" Failed: ",c3,79,b7,3a));
}
}
HXDLIN( 195) {
HXLINE( 195) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 195) sb->flush();
}
HXDLIN( 195) if (hx::IsNull( sb->b )) {
HXLINE( 195) sb->b = ::Array_obj< ::String >::__new(1)->init(0,::Std_obj::string(failCount));
}
else {
HXLINE( 195) ::Array< ::String > sb4 = sb->b;
HXDLIN( 195) sb4->push(::Std_obj::string(failCount));
}
}
HXLINE( 196) {
HXLINE( 196) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 196) sb->flush();
}
HXDLIN( 196) if (hx::IsNull( sb->b )) {
HXLINE( 196) sb->b = ::Array_obj< ::String >::fromData( _hx_array_data_4385fced_22,1);
}
else {
HXLINE( 196) sb->b->push(HX_(" Errors: ",51,13,30,17));
}
}
HXDLIN( 196) {
HXLINE( 196) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 196) sb->flush();
}
HXDLIN( 196) if (hx::IsNull( sb->b )) {
HXLINE( 196) sb->b = ::Array_obj< ::String >::__new(1)->init(0,::Std_obj::string(errorCount));
}
else {
HXLINE( 196) ::Array< ::String > sb5 = sb->b;
HXDLIN( 196) sb5->push(::Std_obj::string(errorCount));
}
}
HXLINE( 197) {
HXLINE( 197) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 197) sb->flush();
}
HXDLIN( 197) if (hx::IsNull( sb->b )) {
HXLINE( 197) sb->b = ::Array_obj< ::String >::fromData( _hx_array_data_4385fced_23,1);
}
else {
HXLINE( 197) sb->b->push(HX_(" Ignored: ",f8,ad,04,5a));
}
}
HXDLIN( 197) {
HXLINE( 197) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 197) sb->flush();
}
HXDLIN( 197) if (hx::IsNull( sb->b )) {
HXLINE( 197) sb->b = ::Array_obj< ::String >::__new(1)->init(0,::Std_obj::string(ignoreCount));
}
else {
HXLINE( 197) ::Array< ::String > sb6 = sb->b;
HXDLIN( 197) sb6->push(::Std_obj::string(ignoreCount));
}
}
HXLINE( 198) {
HXLINE( 198) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 198) sb->flush();
}
HXDLIN( 198) if (hx::IsNull( sb->b )) {
HXLINE( 198) sb->b = ::Array_obj< ::String >::fromData( _hx_array_data_4385fced_24,1);
}
else {
HXLINE( 198) sb->b->push(HX_(" Time: ",33,28,15,86));
}
}
HXDLIN( 198) {
HXLINE( 198) Float x1 = ::massive::munit::util::MathUtil_obj::round(time,(int)5);
HXDLIN( 198) if (hx::IsNotNull( sb->charBuf )) {
HXLINE( 198) sb->flush();
}
HXDLIN( 198) if (hx::IsNull( sb->b )) {
HXLINE( 198) sb->b = ::Array_obj< ::String >::__new(1)->init(0,::Std_obj::string(x1));
}
else {
HXLINE( 198) ::Array< ::String > sb7 = sb->b;
HXDLIN( 198) sb7->push(::Std_obj::string(x1));
}
}
HXLINE( 199) this->printLine(sb->toString(),null());
HXLINE( 200) this->printLine(HX_("",00,00,00,00),null());
}
void PrintClientBase_obj::printOverallResult(bool result){
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_205_printOverallResult)
HXDLIN( 205) this->printLine(HX_("",00,00,00,00),null());
}
void PrintClientBase_obj::print( ::Dynamic value){
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_210_print)
HXDLIN( 210) ::massive::munit::client::PrintClientBase _hx_tmp = hx::ObjectPtr<OBJ_>(this);
HXDLIN( 210) ::String _hx_tmp1 = _hx_tmp->output;
HXDLIN( 210) _hx_tmp->output = (_hx_tmp1 + ::Std_obj::string(value));
}
HX_DEFINE_DYNAMIC_FUNC1(PrintClientBase_obj,print,(void))
void PrintClientBase_obj::printLine( ::Dynamic value, ::Dynamic __o_indent){
::Dynamic indent = __o_indent.Default(0);
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_214_printLine)
HXLINE( 215) value = ::Std_obj::string(value);
HXLINE( 216) value = this->indentString(( (::String)(value) ),indent);
HXLINE( 217) this->print((HX_("\n",0a,00,00,00) + ::Std_obj::string(value)));
}
HX_DEFINE_DYNAMIC_FUNC2(PrintClientBase_obj,printLine,(void))
::String PrintClientBase_obj::indentString(::String value, ::Dynamic __o_indent){
::Dynamic indent = __o_indent.Default(0);
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_221_indentString)
HXLINE( 222) if (hx::IsGreater( indent,(int)0 )) {
HXLINE( 222) value = (::StringTools_obj::lpad(HX_("",00,00,00,00),HX_(" ",20,00,00,00),(indent * (int)4)) + value);
}
HXLINE( 223) return value;
}
HX_DEFINE_DYNAMIC_FUNC2(PrintClientBase_obj,indentString,return )
::String PrintClientBase_obj::DEFAULT_ID;
hx::ObjectPtr< PrintClientBase_obj > PrintClientBase_obj::__new(hx::Null< bool > __o_includeIgnoredReport) {
hx::ObjectPtr< PrintClientBase_obj > __this = new PrintClientBase_obj();
__this->__construct(__o_includeIgnoredReport);
return __this;
}
hx::ObjectPtr< PrintClientBase_obj > PrintClientBase_obj::__alloc(hx::Ctx *_hx_ctx,hx::Null< bool > __o_includeIgnoredReport) {
PrintClientBase_obj *__this = (PrintClientBase_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(PrintClientBase_obj), true, "massive.munit.client.PrintClientBase"));
*(void **)__this = PrintClientBase_obj::_hx_vtable;
__this->__construct(__o_includeIgnoredReport);
return __this;
}
PrintClientBase_obj::PrintClientBase_obj()
{
}
void PrintClientBase_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(PrintClientBase);
HX_MARK_MEMBER_NAME(divider1,"divider1");
HX_MARK_MEMBER_NAME(divider2,"divider2");
HX_MARK_MEMBER_NAME(verbose,"verbose");
HX_MARK_MEMBER_NAME(includeIgnoredReport,"includeIgnoredReport");
::massive::munit::client::AbstractTestResultClient_obj::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void PrintClientBase_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(divider1,"divider1");
HX_VISIT_MEMBER_NAME(divider2,"divider2");
HX_VISIT_MEMBER_NAME(verbose,"verbose");
HX_VISIT_MEMBER_NAME(includeIgnoredReport,"includeIgnoredReport");
::massive::munit::client::AbstractTestResultClient_obj::__Visit(HX_VISIT_ARG);
}
hx::Val PrintClientBase_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"print") ) { return hx::Val( print_dyn() ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"verbose") ) { return hx::Val( verbose ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"divider1") ) { return hx::Val( divider1 ); }
if (HX_FIELD_EQ(inName,"divider2") ) { return hx::Val( divider2 ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"printLine") ) { return hx::Val( printLine_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"printReports") ) { return hx::Val( printReports_dyn() ); }
if (HX_FIELD_EQ(inName,"indentString") ) { return hx::Val( indentString_dyn() ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"filterIngored") ) { return hx::Val( filterIngored_dyn() ); }
break;
case 15:
if (HX_FIELD_EQ(inName,"updateTestClass") ) { return hx::Val( updateTestClass_dyn() ); }
break;
case 17:
if (HX_FIELD_EQ(inName,"finalizeTestClass") ) { return hx::Val( finalizeTestClass_dyn() ); }
break;
case 18:
if (HX_FIELD_EQ(inName,"printIndentedLines") ) { return hx::Val( printIndentedLines_dyn() ); }
if (HX_FIELD_EQ(inName,"printOverallResult") ) { return hx::Val( printOverallResult_dyn() ); }
break;
case 19:
if (HX_FIELD_EQ(inName,"initializeTestClass") ) { return hx::Val( initializeTestClass_dyn() ); }
if (HX_FIELD_EQ(inName,"reportFinalCoverage") ) { return hx::Val( reportFinalCoverage_dyn() ); }
break;
case 20:
if (HX_FIELD_EQ(inName,"includeIgnoredReport") ) { return hx::Val( includeIgnoredReport ); }
if (HX_FIELD_EQ(inName,"printFinalStatistics") ) { return hx::Val( printFinalStatistics_dyn() ); }
break;
case 27:
if (HX_FIELD_EQ(inName,"setCurrentTestClassCoverage") ) { return hx::Val( setCurrentTestClassCoverage_dyn() ); }
if (HX_FIELD_EQ(inName,"printFinalIgnoredStatistics") ) { return hx::Val( printFinalIgnoredStatistics_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
hx::Val PrintClientBase_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 7:
if (HX_FIELD_EQ(inName,"verbose") ) { verbose=inValue.Cast< bool >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"divider1") ) { divider1=inValue.Cast< ::String >(); return inValue; }
if (HX_FIELD_EQ(inName,"divider2") ) { divider2=inValue.Cast< ::String >(); return inValue; }
break;
case 20:
if (HX_FIELD_EQ(inName,"includeIgnoredReport") ) { includeIgnoredReport=inValue.Cast< bool >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void PrintClientBase_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("divider1","\x38","\x23","\x98","\x4b"));
outFields->push(HX_HCSTRING("divider2","\x39","\x23","\x98","\x4b"));
outFields->push(HX_HCSTRING("verbose","\x82","\xd7","\xb9","\x71"));
outFields->push(HX_HCSTRING("includeIgnoredReport","\x1e","\x1a","\xbf","\xa1"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo PrintClientBase_obj_sMemberStorageInfo[] = {
{hx::fsString,(int)offsetof(PrintClientBase_obj,divider1),HX_HCSTRING("divider1","\x38","\x23","\x98","\x4b")},
{hx::fsString,(int)offsetof(PrintClientBase_obj,divider2),HX_HCSTRING("divider2","\x39","\x23","\x98","\x4b")},
{hx::fsBool,(int)offsetof(PrintClientBase_obj,verbose),HX_HCSTRING("verbose","\x82","\xd7","\xb9","\x71")},
{hx::fsBool,(int)offsetof(PrintClientBase_obj,includeIgnoredReport),HX_HCSTRING("includeIgnoredReport","\x1e","\x1a","\xbf","\xa1")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo PrintClientBase_obj_sStaticStorageInfo[] = {
{hx::fsString,(void *) &PrintClientBase_obj::DEFAULT_ID,HX_HCSTRING("DEFAULT_ID","\xf9","\x83","\x2f","\x18")},
{ hx::fsUnknown, 0, null()}
};
#endif
static ::String PrintClientBase_obj_sMemberFields[] = {
HX_HCSTRING("divider1","\x38","\x23","\x98","\x4b"),
HX_HCSTRING("divider2","\x39","\x23","\x98","\x4b"),
HX_HCSTRING("verbose","\x82","\xd7","\xb9","\x71"),
HX_HCSTRING("includeIgnoredReport","\x1e","\x1a","\xbf","\xa1"),
HX_HCSTRING("initializeTestClass","\x16","\xbb","\x49","\x2f"),
HX_HCSTRING("updateTestClass","\x3d","\x87","\xe5","\x60"),
HX_HCSTRING("finalizeTestClass","\x08","\xad","\xf8","\x06"),
HX_HCSTRING("setCurrentTestClassCoverage","\xd7","\x3b","\xb4","\x88"),
HX_HCSTRING("reportFinalCoverage","\x2a","\xc6","\x68","\x9d"),
HX_HCSTRING("printIndentedLines","\xc7","\x75","\x8b","\x9c"),
HX_HCSTRING("printReports","\x92","\xc0","\x6f","\x0e"),
HX_HCSTRING("printFinalIgnoredStatistics","\x8c","\x4e","\x03","\xb0"),
HX_HCSTRING("filterIngored","\x4c","\x9d","\x5a","\x62"),
HX_HCSTRING("printFinalStatistics","\x8c","\x54","\x51","\xe4"),
HX_HCSTRING("printOverallResult","\x9d","\x28","\x2a","\x6e"),
HX_HCSTRING("print","\x2d","\x58","\x8b","\xc8"),
HX_HCSTRING("printLine","\xc1","\xb6","\xab","\xc8"),
HX_HCSTRING("indentString","\x5d","\xc2","\x96","\x5e"),
::String(null()) };
static void PrintClientBase_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(PrintClientBase_obj::__mClass,"__mClass");
HX_MARK_MEMBER_NAME(PrintClientBase_obj::DEFAULT_ID,"DEFAULT_ID");
};
#ifdef HXCPP_VISIT_ALLOCS
static void PrintClientBase_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(PrintClientBase_obj::__mClass,"__mClass");
HX_VISIT_MEMBER_NAME(PrintClientBase_obj::DEFAULT_ID,"DEFAULT_ID");
};
#endif
hx::Class PrintClientBase_obj::__mClass;
static ::String PrintClientBase_obj_sStaticFields[] = {
HX_HCSTRING("DEFAULT_ID","\xf9","\x83","\x2f","\x18"),
::String(null())
};
void PrintClientBase_obj::__register()
{
hx::Object *dummy = new PrintClientBase_obj;
PrintClientBase_obj::_hx_vtable = *(void **)dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("massive.munit.client.PrintClientBase","\xed","\xfc","\x85","\x43");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = PrintClientBase_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(PrintClientBase_obj_sStaticFields);
__mClass->mMembers = hx::Class_obj::dupFunctions(PrintClientBase_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< PrintClientBase_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = PrintClientBase_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = PrintClientBase_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = PrintClientBase_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void PrintClientBase_obj::__boot()
{
{
HX_STACKFRAME(&_hx_pos_ff06a10c772ba8ce_40_boot)
HXDLIN( 40) DEFAULT_ID = HX_("simple",32,04,7f,b8);
}
}
} // end namespace massive
} // end namespace munit
} // end namespace client
| 44.078457 | 282 | 0.667904 | [
"object",
"3d"
] |
f8aa799938499ca5153fe8f49d4cce6f63accaf9 | 3,153 | cc | C++ | topcoder/tco2017/CheeseSlicing.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | topcoder/tco2017/CheeseSlicing.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | topcoder/tco2017/CheeseSlicing.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using vi = vector<int>; using vvi = vector<vi>;
using ii = pair<int,int>; using vii = vector<ii>;
using l = long long; using vl = vector<l>; using vvl = vector<vl>;
using ll = pair<l,l>; using vll = vector<ll>; using vvll = vector<vll>;
using lu = unsigned long long;
using vb = vector<bool>; using vvb = vector<vb>;
using vd = vector<double>; using vvd = vector<vd>;
const int INF = numeric_limits<int>::max();
const double EPS = 1e-10;
const l e0=1, e3=1000, e5=100000, e6=e3*e3, e7=10*e6, e8=10*e7, e9=10*e8;
#define ALL(x) begin(x), end(x)
#define F(a,b,c) for (l a = l(b); a < l(c); a++)
#define B(a,b,c) for (l a = l(b); a > l(c); a--)
// #define ONLINE_JUDGE
#if defined ONLINE_JUDGE
const bool enable_log = false;
#else
const bool enable_log = true;
#endif
struct VoidStream { void operator&(std::ostream&) { } };
#define LOG !(enable_log) ? (void) 0 : VoidStream() & cerr
const l MAX = 101;
l DP[MAX][MAX][MAX];
class CheeseSlicing {
public:
l s;
l score(vl& v) {
if (v[0] < s) return 0;
return v[1] * v[2];
}
l f(vl& v) {
if (v[0] < s) return 0;
l& r = DP[v[0]][v[1]][v[2]];
if (r == -1) {
r = score(v);
F(j, 0, 3) {
if (v[j] < s) continue;
vl t1 = v;
vl t2 = v;
t1[j] = s;
t2[j] = v[j] - s;
sort(ALL(t1)); sort(ALL(t2));
r = max(r, score(t1) + f(t2));
}
}
return r;
}
int totalArea(int A, int B, int C, int S) {
s = S;
fill(&DP[0][0][0], &DP[MAX][0][0], -1);
vl v = {A, B, C};
sort(ALL(v));
return f(v);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 1; int Arg1 = 3; int Arg2 = 3; int Arg3 = 2; int Arg4 = 0; verify_case(0, Arg4, totalArea(Arg0, Arg1, Arg2, Arg3)); }
void test_case_1() { int Arg0 = 5; int Arg1 = 3; int Arg2 = 5; int Arg3 = 3; int Arg4 = 25; verify_case(1, Arg4, totalArea(Arg0, Arg1, Arg2, Arg3)); }
void test_case_2() { int Arg0 = 5; int Arg1 = 5; int Arg2 = 5; int Arg3 = 2; int Arg4 = 58; verify_case(2, Arg4, totalArea(Arg0, Arg1, Arg2, Arg3)); }
void test_case_3() { int Arg0 = 100; int Arg1 = 100; int Arg2 = 100; int Arg3 = 1; int Arg4 = 1000000; verify_case(3, Arg4, totalArea(Arg0, Arg1, Arg2, Arg3)); }
// END CUT HERE
;
};
// BEGIN CUT HERE
int main() {
CheeseSlicing ___test;
___test.run_test(-1);
}
// END CUT HERE
| 36.662791 | 308 | 0.567713 | [
"vector"
] |
f8ac06d7ef9d89805642b997862c937cf988aa59 | 21,239 | cpp | C++ | src/MainWindow.cpp | skytranlong/AxpFileManager | 3bc1643d528bf61440468e8a0b38791f35cf39c9 | [
"WTFPL"
] | null | null | null | src/MainWindow.cpp | skytranlong/AxpFileManager | 3bc1643d528bf61440468e8a0b38791f35cf39c9 | [
"WTFPL"
] | null | null | null | src/MainWindow.cpp | skytranlong/AxpFileManager | 3bc1643d528bf61440468e8a0b38791f35cf39c9 | [
"WTFPL"
] | 2 | 2021-11-10T07:18:29.000Z | 2022-01-06T07:45:54.000Z | #include "MainWindow.hpp"
#include "ui_MainWindow.h"
#include <QDirModel>
#include <QDesktopServices>
#include <QFileDialog>
#include <QFileIconProvider>
#include <QProcess>
#include <QLocale>
#include <QMutex>
#include <QMessageBox>
#include <QThread>
#include <QTimer>
#include <QDirIterator>
#include <QList>
#include <QSysInfo>
#include "AxpArchive.hpp"
#include "AxpArchivePort.hpp"
#include "AboutDialog.hpp"
#include "AxpItem.hpp"
#include "AxpItemModel.hpp"
#include "Log.hpp"
#include "Utils.hpp"
#include "LaunchExtendsUtils.hpp"
MainWindow* MainWindow::s_instance = nullptr;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
s_instance = this;
LOG_DEBUG(__FUNCTION__ << QThread::currentThread());
ui->setupUi(this);
ui->splitter->setStretchFactor(0, 0);
ui->splitter->setStretchFactor(1, 1);
m_axpArchive = new AxpArchivePort;
m_dirModel = new QStandardItemModel(ui->dirList);
m_fileModel = new QStandardItemModel(ui->fileList);
m_fileModel->setSortRole(AxpItem::ItemTypeRole);
m_fileModel->setHorizontalHeaderLabels(QStringList() << "Name" << "Size" << "Status");
ui->dirList->setModel(m_dirModel);
ui->fileList->setModel(m_fileModel);
ui->fileList->horizontalHeader()->setSectionResizeMode(
0, QHeaderView::Stretch);
connect(this, &MainWindow::invoke, this, &MainWindow::invokeCallback);
const auto& args = QCoreApplication::arguments();
if (args.size() > 1) {
const QString& opennedPath = args.at(1);
QTimer::singleShot(0, [this, opennedPath](){
this->openAxpArchive(opennedPath);
});
}
}
MainWindow::~MainWindow()
{
LOG_DEBUG(__FUNCTION__ << "called");
delete m_axpArchive;
delete ui;
s_instance = nullptr;
}
MainWindow *MainWindow::getInstance()
{
return s_instance;
}
Ui::MainWindow* MainWindow::getUi() const
{
return ui;
}
QString MainWindow::getSelectedDirAxpKey() const
{
auto curIndex = ui->dirList->currentIndex();
if (!curIndex.isValid()) return QString();
auto data = curIndex.data(AxpItem::ItemKeyRole);
return !data.isNull() && data.isValid() ? data.toString() : QString();
}
void MainWindow::openAxpArchive(const QString &fileName)
{
if (fileName.isEmpty())
{
LOG(__FUNCTION__ << "You must input axp file name");
return;
}
if (!this->closeOpenningAxp())
{
return;
}
m_axpArchive->setAxpArchiveFileName(fileName);
m_axpArchive->setAxpArchiveFileEditable(false);
m_axpArchive->setProgressCallback([this](auto fileName, auto cur, auto total) {
QString qStringFileName = QString::fromLocal8Bit(fileName.data());
emit this->invoke([=](){
this->setProgress(qStringFileName, cur, total);
});
this->onAxpReadListProgress(qStringFileName, cur, total);
});
m_axpArchive->startOpenAxpArchive([=]() {
emit this->invoke([=](){
const auto& nativePath = QDir::toNativeSeparators(fileName);
ui->workingPathLabel->setText("File: <a href=\""+nativePath+"\">"+nativePath+"</a>");
ui->workingPathLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
});
QStandardItem* item = new AxpItem("/");
item->setText(QFileInfo(fileName).fileName());
item->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirIcon));
m_dirModel->appendRow(item);
auto rootIndex = m_dirModel->index(0, 0);
ui->dirList->expand(rootIndex);
},
[=](){
emit this->invoke([=](){
if (auto errCode = m_axpArchive->getLastError() != AXP::AXP_ERRORS::AXP_ERR_SUCCESS)
{
LOG_DEBUG("Error:" << static_cast<int>(errCode) << m_axpArchive->getLastErrorMessage());
QMessageBox::warning(this, "Error - Can not open file",
QString("Error Code: %1\nError Message: %2\nFile name: %3")
.arg(static_cast<int>(errCode))
.arg(m_axpArchive->getLastErrorMessage())
.arg(fileName));
m_axpArchive->close();
return;
}
ui->actionSave->setDisabled(false);
ui->actionSave_As->setDisabled(false);
ui->actionExtract_All_Data->setDisabled(false);
ui->actionAdd_File->setDisabled(false);
ui->actionAdd_Folder->setDisabled(false);
ui->actionClose_openning_file->setDisabled(false);
ui->saveBtn->setDisabled(false);
ui->saveAsBtn->setDisabled(false);
ui->addFileBtn->setDisabled(false);
ui->addFolderBtn->setDisabled(false);
ui->extractAllBtn->setDisabled(false);
// ui->extractSelectedBtn->setDisabled(true);
});
// LaunchExtendsUtils::downloadLaunchExtends();
});
}
void MainWindow::onAxpReadListProgress(const QString &fileName, const size_t current, const size_t total)
{
Q_UNUSED(current);
Q_UNUSED(total);
auto dirs = fileName.split('/');
QString fileBaseName = dirs.back();
auto dirParent = m_dirModel->item(0, 0);
if (!dirParent)
{
LOG(__FUNCTION__ << "Error: not found diParent." << fileName << current << total);
return;
}
int dirSize = dirs.size() - 1;
for (int i = 0; i < dirSize; ++i) {
auto& pathPart = dirs.at(i);
bool foundParent = false;
int rowCount = dirParent->rowCount();
for (int r = 0; r < rowCount; ++r) {
auto child = dirParent->child(r);
if (child->text() == pathPart) {
dirParent = child;
foundParent = true;
break;
}
}
if (!foundParent) {
QString key;
for (int j = 0; j <= i; ++j) {
key += dirs[j] + '/';
}
auto newChild = new AxpItem(key);
dirParent->appendRow(newChild);
dirParent = newChild;
}
}
}
void MainWindow::setProgress(const QString &name, const std::size_t current, const std::size_t total)
{
ui->progressBar->setMaximum(static_cast<int>(total));
ui->progressBar->setValue(static_cast<int>(current));
ui->messageLabel->setText(
"[" + QString::number(current) + "/" + QString::number(total) + "]: " + name
);
}
bool MainWindow::closeOpenningAxp()
{
if (m_axpArchive->isModified())
{
auto retMsg = QMessageBox::question(this, "Confirm discard modified", "You have unsave changes!\n\nDo you want to discard?");
if (retMsg != QMessageBox::StandardButton::Yes)
{
return false;
}
}
ui->actionSave->setDisabled(true);
ui->actionSave_As->setDisabled(true);
ui->actionExtract_All_Data->setDisabled(true);
ui->actionAdd_File->setDisabled(true);
ui->actionAdd_Folder->setDisabled(true);
ui->actionClose_openning_file->setDisabled(true);
ui->saveBtn->setDisabled(true);
ui->saveAsBtn->setDisabled(true);
ui->addFileBtn->setDisabled(true);
ui->addFolderBtn->setDisabled(true);
ui->extractAllBtn->setDisabled(true);
ui->extractSelectedBtn->setDisabled(true);
// CLose first
m_fileModel->removeRows(0, m_fileModel->rowCount());
m_dirModel->clear();
m_axpArchive->close();
return true;
}
bool MainWindow::event(QEvent* event)
{
if (event->type() == QEvent::Close)
{
if (!this->closeOpenningAxp())
{
event->ignore();
return false;
}
}
return QMainWindow::event(event);
}
void MainWindow::on_actionOpen_triggered()
{
static QString opennedPath;
opennedPath = QFileDialog::getOpenFileName(
this, "Open File", opennedPath, tr("Axp archive (*.axp);;All Files (*)")
);
this->openAxpArchive(opennedPath);
}
void MainWindow::on_actionAbout_triggered()
{
QMessageBox::information(this, "About us", "Axp File Manager Application\n\nCopyright (c) Dark.Hades");
}
void MainWindow::on_actionNew_triggered()
{
static QString opennedPath;
opennedPath = QFileDialog::getSaveFileName(
this, tr("Create new Axp archive file"), opennedPath,
tr("Axp archive (*.axp);;All Files (*)"));
if (opennedPath.isEmpty())
{
return;
}
m_axpArchive->close();
if (!m_axpArchive->saveToDiskFile(opennedPath.toLocal8Bit().data()))
{
return;
}
this->openAxpArchive(opennedPath);
}
void MainWindow::setCurrentDir(const QModelIndex &index)
{
LOG_DEBUG(__FUNCTION__ << "called");
ui->dirList->setDisabled(true);
QThread* setCurDirThread = new QThread();
connect(setCurDirThread, &QThread::started, [=](auto) {
LOG_DEBUG("setCurrentDir::Thread" << "called");
m_fileModel->removeRows(0, m_fileModel->rowCount());
auto rootIndex = ui->dirList->model()->index(0, 0);
bool isRoot = (index == rootIndex);
QString parentKey = this->getSelectedDirAxpKey();
auto& fileList = m_axpArchive->getFileList();
bool startedFound = false;
QMap<QString, bool> addedItems;
for (const auto& fileInfo : fileList) {
auto& fKey = fileInfo.first;
QString local8BitFileName = QString::fromLocal8Bit(fKey.c_str());
if (isRoot || local8BitFileName.indexOf(parentKey) == 0) {
auto keySize = isRoot ? 0 : parentKey.size();
QString itemPathName = local8BitFileName.mid(keySize);
int indexOfSlash = itemPathName.indexOf('/');
QString itemName = itemPathName.mid(0, indexOfSlash);
if (addedItems.count(itemName)) {
continue;
}
addedItems[itemName] = true;
bool isDir = (indexOfSlash != -1);
QList<QStandardItem*> items;
items.reserve(m_fileModel->columnCount());
auto item = new AxpItem(isDir ? local8BitFileName.mid(0, keySize + itemName.size() + 1) : local8BitFileName);
items.append(item);
auto sizeItem = new QStandardItem();
#if !defined(QT_DEBUG)
#endif
if (!isDir)
{
sizeItem->setText(
QLocale(QLocale::English).toString(static_cast<double>(fileInfo.second.size), 'f', 0) + " B"
);
}
sizeItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignRight);
items.append(sizeItem);
auto statusItem = new QStandardItem();
QString statusTxt;
switch (fileInfo.second.status)
{
case AxpArchivePort::FileListData::FileStatus::NEW:
statusItem->setForeground(Qt::green);
statusTxt = "New";
break;
case AxpArchivePort::FileListData::FileStatus::DELETED:
statusItem->setForeground(Qt::red);
statusTxt = "Deleted";
break;
case AxpArchivePort::FileListData::FileStatus::MODIFIED:
statusItem->setForeground(Qt::yellow);
statusTxt = "Modified";
break;
case AxpArchivePort::FileListData::FileStatus::ORIGIN:
statusItem->setForeground(Qt::black);
statusTxt = "Origin";
break;
default:
statusTxt = "Unknown";
}
statusItem->setText(statusTxt);
statusItem->setTextAlignment(Qt::AlignCenter);
items.append(statusItem);
m_fileModel->appendRow(items);
startedFound = true;
} else {
if (startedFound) {
break;
}
}
}
m_fileModel->sort(0);
setCurDirThread->quit();
});
connect(setCurDirThread, &QThread::finished, [=]() {
setCurDirThread->deleteLater();
});
connect(setCurDirThread, &QThread::destroyed, [=]() {
ui->dirList->setDisabled(false);
LOG_DEBUG("setCurrentDir::Thread" << "completed");
});
setCurDirThread->start();
LOG_DEBUG(__FUNCTION__ << "completed!");
}
void MainWindow::on_actionExtract_All_Data_triggered()
{
static QString opennedPath;
opennedPath = QFileDialog::getExistingDirectory(this, "Choose folder to save extract file(s)", opennedPath);
if (opennedPath.isEmpty()) {
return;
}
auto m_extractItemListThread = new QThread(this);
connect(m_extractItemListThread, &QThread::started, [=](){
LOG_DEBUG("Extract ThreadID:" << QThread::currentThread());
QFileInfo fileInfo(m_axpArchive->getArchiveFileName());
QDir targetDir(opennedPath + '/' + fileInfo.fileName() + "-Output");
if (!targetDir.exists())
{
targetDir.mkpath(".");
}
auto& m_fileList = m_axpArchive->getFileList();
uint32_t i = 0;
for (const auto& fileInfo : m_fileList)
{
++i;
const auto fKeyName = fileInfo.first;
const auto& fname = QString::fromLocal8Bit(fKeyName.c_str());
emit this->invoke([=]() {
this->setProgress(fname, i, static_cast<uint>(m_fileList.size()));
});
auto toFileName(targetDir.filePath(fname));
if (!m_axpArchive->extractToDisk(fKeyName, toFileName.toLocal8Bit().data())) {
LOG_DEBUG("Write error");
}
}
LOG("Extracted resources!");
if (targetDir.exists()) {
QDesktopServices::openUrl(targetDir.path());
}
m_extractItemListThread->quit();
});
m_extractItemListThread->start();
}
void MainWindow::on_actionExit_triggered()
{
if (this->closeOpenningAxp())
{
this->close();
}
}
void MainWindow::on_workingPathLabel_linkActivated(const QString &link)
{
QProcess::startDetached("explorer.exe", (QStringList() << "/select," << link));
}
void MainWindow::on_actionAdd_File_triggered()
{
LOG_DEBUG(__FUNCTION__ << "called");
auto opennedPaths = QFileDialog::getOpenFileNames(
this, "Choose file(s) to add", nullptr, "All files (*)"
);
LOG_DEBUG(__FUNCTION__ << opennedPaths);
auto& fileList = m_axpArchive->getFileList();
for (const auto& q_diskFileName : opennedPaths)
{
auto selectedPath = this->getSelectedDirAxpKey();
QFileInfo fileInfo(q_diskFileName);
if (!fileInfo.exists())
{
continue;
}
AxpArchivePort::FileName diskFileName = q_diskFileName.toLocal8Bit().data();
AxpArchivePort::FileName fileName = ((selectedPath == "") || (selectedPath == "/"))
? fileInfo.fileName().toLocal8Bit().data()
: QDir(selectedPath).filePath(fileInfo.fileName()).toLocal8Bit().data();
auto& fileListItem = fileList[fileName];
switch (fileListItem.status)
{
case AxpArchivePort::FileListData::FileStatus::UNKNOWN:
case AxpArchivePort::FileListData::FileStatus::NEW:
fileListItem.status = AxpArchivePort::FileListData::FileStatus::NEW;
break;
default:
fileListItem.status = AxpArchivePort::FileListData::FileStatus::MODIFIED;
}
fileListItem.nameFromDisk = diskFileName;
fileListItem.size = AXP::getDiskFileSize(diskFileName.data());
}
// Update list view
this->setCurrentDir(ui->dirList->currentIndex());
LOG_DEBUG(__FUNCTION__ << "completed");
}
void MainWindow::on_actionAdd_Folder_triggered()
{
auto opennedPaths = QFileDialog::getExistingDirectory(this, "Choose folder to add");
if (opennedPaths.isEmpty())
{
return;
}
LOG_DEBUG(__FUNCTION__ << opennedPaths);
QThread* loadThread = new QThread;
connect(loadThread, &QThread::started, [=](){
QStringList pathArr = opennedPaths.split('/');
const auto& dirBaseName = pathArr.back();
const auto opennedPathSize = opennedPaths.size();
auto& fileList = m_axpArchive->getFileList();
QDirIterator itDir(opennedPaths, QDir::Files, QDirIterator::Subdirectories);
while (itDir.hasNext())
{
const auto& diskFileName = itDir.next();
const AxpArchivePort::FileName fileName = (dirBaseName + diskFileName.mid(opennedPathSize)).toLocal8Bit().data();
LOG_DEBUG(__FUNCTION__ << fileName.data());
auto& fileListData = fileList[fileName];
switch (fileListData.status)
{
case AxpArchivePort::FileListData::FileStatus::UNKNOWN:
case AxpArchivePort::FileListData::FileStatus::NEW:
fileListData.status = AxpArchivePort::FileListData::FileStatus::NEW;
break;
default:
fileListData.status = AxpArchivePort::FileListData::FileStatus::MODIFIED;
}
fileListData.nameFromDisk = diskFileName.toLocal8Bit().data();
fileListData.size = AXP::getDiskFileSize(diskFileName.toLocal8Bit().data());
this->onAxpReadListProgress(QString::fromLocal8Bit(fileName.data()), 0, 0);
}
loadThread->quit();
});
connect(loadThread, &QThread::finished, [=](){
emit this->invoke([=](){
this->setCurrentDir(ui->dirList->currentIndex());
});
loadThread->deleteLater();
});
loadThread->start();
}
void MainWindow::on_actionSave_As_triggered()
{
auto opennedPaths = QFileDialog::getSaveFileName(this, "Save File...", QFileInfo(m_axpArchive->getArchiveFileName()).fileName());
QThread* saveThread = new QThread;
connect(saveThread, &QThread::started, [=](){
if (m_axpArchive->saveToDiskFile(opennedPaths.toLocal8Bit().data()))
{
QDesktopServices::openUrl(QFileInfo(opennedPaths).path());
}
else
{
LOG(__FUNCTION__ << m_axpArchive->getLastErrorMessage());
}
saveThread->deleteLater();
saveThread->quit();
});
saveThread->start();
}
void MainWindow::on_actionNew_From_directory_triggered()
{
static QString opennedPath;
opennedPath = QFileDialog::getExistingDirectory(this, "Choose folder to create new Axp", QDir(opennedPath).filePath(".."));
if (opennedPath.isEmpty())
{
return;
}
auto fileBaseName = Utils::basename(opennedPath);
static constexpr auto fileExt = ".axp";
static QString opennedPathSave;
if (opennedPathSave.isEmpty())
{
QDir::setCurrent(opennedPath);
}
opennedPathSave = QFileDialog::getSaveFileName(
this, "Save File...",
fileBaseName.indexOf(fileExt) != -1 ? fileBaseName : (fileBaseName + fileExt)
);
if (opennedPathSave.isEmpty())
{
return;
}
QDir::setCurrent(QDir(opennedPathSave).filePath(".."));
m_axpArchive->close();
QThread* saveThread = new QThread;
connect(saveThread, &QThread::started, [=](){
QStringList pathArr = opennedPath.split('/');
const auto opennedPathSize = opennedPath.size();
auto& fileList = m_axpArchive->getFileList();
QDirIterator itDir(opennedPath, QDir::Files, QDirIterator::Subdirectories);
while (itDir.hasNext())
{
const auto& diskFileName = itDir.next();
const AxpArchivePort::FileName fileName = (diskFileName.mid(opennedPathSize + 1)).toLocal8Bit().data();
LOG_DEBUG(__FUNCTION__ << fileName.data());
auto& fileListItem = fileList[fileName];
switch (fileListItem.status)
{
case AxpArchivePort::FileListData::FileStatus::UNKNOWN:
case AxpArchivePort::FileListData::FileStatus::NEW:
fileListItem.status = AxpArchivePort::FileListData::FileStatus::NEW;
break;
default:
fileListItem.status = AxpArchivePort::FileListData::FileStatus::MODIFIED;
}
fileListItem.nameFromDisk = diskFileName.toLocal8Bit().data();
}
m_axpArchive->setProgressCallback([this](auto fileName, auto cur, auto total) {
QString qStringFileName = QString::fromLocal8Bit(fileName.data());
emit this->invoke([=](){
this->setProgress(qStringFileName, cur, total);
});
});
if (!m_axpArchive->saveToDiskFile(opennedPathSave.toLocal8Bit().data()))
{
LOG(__FUNCTION__ << "error" << m_axpArchive->getLastErrorMessage());
saveThread->quit();
return;
}
// Prevent ask
m_axpArchive->close();
emit this->invoke([=](){
this->openAxpArchive(opennedPathSave);
});
saveThread->quit();
});
connect(saveThread, &QThread::finished, [=](){
saveThread->deleteLater();
});
saveThread->start();
}
void MainWindow::on_actionSave_triggered()
{
auto opennedPaths = m_axpArchive->getArchiveFileName();
QThread* saveThread = new QThread;
connect(saveThread, &QThread::started, [=](){
if (m_axpArchive->isModified())
{
if (m_axpArchive->saveToDiskFile(opennedPaths.toLocal8Bit().data()))
{
emit this->invoke([=](){
this->openAxpArchive(opennedPaths);
});
}
else
{
LOG(__FUNCTION__ << m_axpArchive->getLastErrorMessage());
}
}
saveThread->deleteLater();
saveThread->quit();
});
saveThread->start();
}
void MainWindow::on_actionClose_openning_file_triggered()
{
this->closeOpenningAxp();
}
void MainWindow::on_addFileBtn_clicked()
{
this->on_actionAdd_File_triggered();
}
void MainWindow::on_addFolderBtn_clicked()
{
this->on_actionAdd_Folder_triggered();
}
void MainWindow::on_extractAllBtn_clicked()
{
this->on_actionExtract_All_Data_triggered();
}
void MainWindow::on_extractSelectedBtn_clicked()
{
}
void MainWindow::on_saveBtn_clicked()
{
this->on_actionSave_triggered();
}
void MainWindow::on_saveAsBtn_clicked()
{
this->on_actionSave_As_triggered();
}
| 29.830056 | 132 | 0.637177 | [
"model"
] |
f8ad0f3e84d162a58de7a7f9ea35862563357c79 | 2,739 | hpp | C++ | spectral/basis/spectral_elem_collection.hpp | simonpp/2dRidgeletBTE | 5d08cbb5c57fc276c7a528f128615d23c37ef6a0 | [
"BSD-3-Clause"
] | 1 | 2019-11-08T03:15:56.000Z | 2019-11-08T03:15:56.000Z | spectral/basis/spectral_elem_collection.hpp | simonpp/2dRidgeletBTE | 5d08cbb5c57fc276c7a528f128615d23c37ef6a0 | [
"BSD-3-Clause"
] | null | null | null | spectral/basis/spectral_elem_collection.hpp | simonpp/2dRidgeletBTE | 5d08cbb5c57fc276c7a528f128615d23c37ef6a0 | [
"BSD-3-Clause"
] | 1 | 2019-11-08T03:15:56.000Z | 2019-11-08T03:15:56.000Z | #pragma once
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/container/map.hpp>
#include <boost/fusion/container/map/map_fwd.hpp>
#include <boost/fusion/include/at_key.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/map.hpp>
#include <boost/fusion/include/map_fwd.hpp>
#include <boost/fusion/include/zip_view.hpp>
#include <boost/fusion/sequence/intrinsic/at_key.hpp>
#include <boost/fusion/view/zip_view.hpp>
#include <boost/mpl/for_each.hpp>
#include <cassert>
#include <map>
#include "spectral/basis/spectral_function.hpp"
namespace boltzmann {
/**
* Stores subelements (i.e. functions in phi, r coord. as std::map or std::vec)
*/
template <class... Args>
class SpectralElemCollection
{
public:
typedef boost::fusion::map<boost::fusion::pair<Args, std::map<typename Args::id_t, Args>>...>
map_t;
typedef boost::fusion::map<boost::fusion::pair<Args, std::vector<Args>>...> vec_t;
const map_t &get_map() const
{
assert(is_finalized_ == true);
return elems_;
}
const vec_t &get_vec() const
{
assert(is_finalized_ == true);
return vec_;
}
private:
typedef SpectralElemCollection<Args...> this_type;
public:
SpectralElemCollection()
: finalizer_(this)
, is_finalized_(false)
{
}
// ----------------------------------------------------------------------
// copy constructor
SpectralElemCollection(const this_type &other)
: finalizer_(other.finalizer_)
, is_finalized_(other.is_finalized_)
{
boost::fusion::copy(other.elems_, elems_);
boost::fusion::copy(other.vec_, vec_);
}
// ----------------------------------------------------------------------
template <typename ELEM>
void add_elem(const ELEM &elem)
{
assert(!is_finalized_);
auto &elem_map = boost::fusion::at_key<ELEM>(elems_);
if (elem_map.find(elem.get_id()) != elem_map.end()) {
// element is already stored => do nothing
} else {
elem_map[elem.get_id()] = elem;
}
}
// ----------------------------------------------------------------------
void finalize()
{
assert(is_finalized_ == false);
boost::fusion::for_each(elems_, finalizer_);
is_finalized_ = true;
}
protected:
struct finalizer_t
{
finalizer_t(this_type *ref)
: ref_(ref)
{
}
template <typename T>
void operator()(const T &t) const
{
typedef typename T::first_type index_type;
for (auto it = t.second.begin(); it != t.second.end(); ++it) {
boost::fusion::at_key<index_type>(ref_->vec_).push_back(it->second);
}
}
this_type *ref_;
};
finalizer_t finalizer_;
map_t elems_;
vec_t vec_;
bool is_finalized_;
};
}
| 25.361111 | 95 | 0.616283 | [
"vector"
] |
f8ae4306cd15877a1a1472cc6870cff571fa7bb9 | 11,671 | cpp | C++ | src/external/oculus/SampleCommon/Src/Render/DebugLines.cpp | korejan/OpenXR-SDK-Source | 5d07a936f0348a709d777d922eb4579acf6dcf36 | [
"MIT",
"Unlicense",
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2020-09-02T21:59:29.000Z | 2021-08-03T09:27:10.000Z | thirdparty/oculus_mobile_sdk/SampleCommon/Src/Render/DebugLines.cpp | Crogarox/godot_openxr | 780fbbbc27d2a2a9560ad5fd3415338ac1885b03 | [
"MIT"
] | 4 | 2021-02-10T04:51:31.000Z | 2022-03-02T01:11:09.000Z | src/external/oculus/SampleCommon/Src/Render/DebugLines.cpp | korejan/ALVR-OpenXR-Engine | 9bdd6f73d881e46835dfc9af892e9a4184242764 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"Unlicense"
] | 1 | 2021-10-25T00:50:24.000Z | 2021-10-25T00:50:24.000Z | /************************************************************************************
Filename : DebugLines.cpp
Content : Class that manages and renders debug lines.
Created : April 22, 2014
Authors : Jonathan E. Wright
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
*************************************************************************************/
#include "DebugLines.h"
#include <stdlib.h>
#include "Egl.h"
#include "Misc/Log.h"
#include "GlGeometry.h"
#include "GlProgram.h"
using OVR::Bounds3f;
using OVR::Matrix4f;
using OVR::Posef;
using OVR::Quatf;
using OVR::Vector2f;
using OVR::Vector3f;
using OVR::Vector4f;
namespace OVRFW {
static const char* DebugLineVertexSrc = R"glsl(
attribute vec4 Position;
attribute vec4 VertexColor;
varying lowp vec4 outColor;
void main()
{
gl_Position = TransformVertex( Position );
outColor = VertexColor;
}
)glsl";
static const char* DebugLineFragmentSrc = R"glsl(
varying lowp vec4 outColor;
void main()
{
gl_FragColor = outColor;
}
)glsl";
//==============================================================
// OvrDebugLinesLocal
//
class OvrDebugLinesLocal : public OvrDebugLines {
public:
struct DebugLines_t {
DebugLines_t() : DrawSurf(&Surf) {}
ovrSurfaceDef Surf;
ovrDrawSurface DrawSurf;
VertexAttribs Attr;
std::vector<long long> EndFrame;
};
typedef unsigned short LineIndex_t;
static const int MAX_DEBUG_LINES = 2048;
OvrDebugLinesLocal();
virtual ~OvrDebugLinesLocal();
virtual void Init();
virtual void Shutdown();
virtual void BeginFrame(const long long frameNum);
virtual void AppendSurfaceList(std::vector<ovrDrawSurface>& surfaceList);
virtual void AddLine(
const Vector3f& start,
const Vector3f& end,
const Vector4f& startColor,
const Vector4f& endColor,
const long long endFrame,
const bool depthTest);
virtual void AddPoint(
const Vector3f& pos,
const float size,
const Vector4f& color,
const long long endFrame,
const bool depthTest);
// Add a debug point without a specified color. The axis lines will use default
// colors: X = red, Y = green, Z = blue (same as Maya).
virtual void
AddPoint(const Vector3f& pos, const float size, const long long endFrame, const bool depthTest);
virtual void AddBounds(Posef const& pose, Bounds3f const& bounds, Vector4f const& color);
virtual void AddAxes(
const Vector3f& origin,
const Matrix4f& axes,
const float size,
const Vector4f& color,
const long long endFrame,
const bool depthTest);
private:
DebugLines_t DepthTested;
DebugLines_t NonDepthTested;
bool Initialized;
GlProgram LineProgram;
void RemoveExpired(const long long frameNum, DebugLines_t& lines);
};
//==============================
// OvrDebugLinesLocal::OvrDebugLinesLocal
OvrDebugLinesLocal::OvrDebugLinesLocal() : Initialized(false) {}
//==============================
// OvrDebugLinesLocal::OvrDebugLinesLocal
OvrDebugLinesLocal::~OvrDebugLinesLocal() {
Shutdown();
}
//==============================
// OvrDebugLinesLocal::Init
void OvrDebugLinesLocal::Init() {
if (Initialized) {
// JDC: multi-activity test ASSERT_WITH_TAG( !Initialized, "DebugLines" );
return;
}
// this is only freed by the OS when the program exits
if (LineProgram.VertexShader == 0 || LineProgram.FragmentShader == 0) {
LineProgram = GlProgram::Build(DebugLineVertexSrc, DebugLineFragmentSrc, NULL, 0);
}
// the indices will never change once we've set them up, we just won't necessarily
// use all of the index buffer to render.
const int MAX_INDICES = MAX_DEBUG_LINES * 2;
std::vector<LineIndex_t> indices;
indices.reserve(MAX_INDICES);
for (LineIndex_t i = 0; i < MAX_INDICES; ++i) {
indices.push_back(i);
}
for (int i = 0; i < 2; i++) {
DebugLines_t& dl = i == 0 ? NonDepthTested : DepthTested;
dl.Surf.geo.Create(dl.Attr, indices);
dl.Surf.geo.primitiveType = GL_LINES;
ovrGraphicsCommand& gc = dl.Surf.graphicsCommand;
gc.GpuState.blendDst = GL_ONE_MINUS_SRC_ALPHA;
gc.GpuState.depthEnable = gc.GpuState.depthMaskEnable = i == 1;
gc.GpuState.lineWidth = 2.0f;
gc.Program = LineProgram;
}
Initialized = true;
}
//==============================
// OvrDebugLinesLocal::Shutdown
void OvrDebugLinesLocal::Shutdown() {
if (!Initialized) {
// OVR_ASSERT_WITH_TAG( !Initialized, "DebugLines" );
return;
}
DepthTested.Surf.geo.Free();
NonDepthTested.Surf.geo.Free();
GlProgram::Free(LineProgram);
Initialized = false;
}
//==============================
// OvrDebugLinesLocal::AppendSurfaceList
void OvrDebugLinesLocal::AppendSurfaceList(std::vector<ovrDrawSurface>& surfaceList) {
for (int j = 0; j < 2; j++) {
DebugLines_t& dl = j == 0 ? NonDepthTested : DepthTested;
int verts = dl.Attr.position.size();
if (verts == 0) {
continue;
}
dl.Surf.geo.Update(dl.Attr);
dl.Surf.geo.indexCount = verts;
surfaceList.push_back(dl.DrawSurf);
}
}
//==============================
// OvrDebugLinesLocal::AddLine
void OvrDebugLinesLocal::AddLine(
const Vector3f& start,
const Vector3f& end,
const Vector4f& startColor,
const Vector4f& endColor,
const long long endFrame,
const bool depthTest) {
// OVR_LOG( "OvrDebugLinesLocal::AddDebugLine" );
DebugLines_t& dl = depthTest ? DepthTested : NonDepthTested;
dl.Attr.position.push_back(start);
dl.Attr.position.push_back(end);
dl.Attr.color.push_back(startColor);
dl.Attr.color.push_back(endColor);
dl.EndFrame.push_back(endFrame);
// OVR_ASSERT( DepthTested.EndFrame.GetSizeI() < MAX_DEBUG_LINES );
// OVR_ASSERT( NonDepthTested.EndFrame.GetSizeI() < MAX_DEBUG_LINES );
}
//==============================
// OvrDebugLinesLocal::AddPoint
void OvrDebugLinesLocal::AddPoint(
const Vector3f& pos,
const float size,
const Vector4f& color,
const long long endFrame,
const bool depthTest) {
float const hs = size * 0.5f;
Vector3f const fwd(0.0f, 0.0f, hs);
Vector3f const right(hs, 0.0f, 0.0f);
Vector3f const up(0.0f, hs, 0.0f);
AddLine(pos - fwd, pos + fwd, color, color, endFrame, depthTest);
AddLine(pos - right, pos + right, color, color, endFrame, depthTest);
AddLine(pos - up, pos + up, color, color, endFrame, depthTest);
}
//==============================
// OvrDebugLinesLocal::AddPoint
void OvrDebugLinesLocal::AddPoint(
const Vector3f& pos,
const float size,
const long long endFrame,
const bool depthTest) {
float const hs = size * 0.5f;
Vector3f const fwd(0.0f, 0.0f, hs);
Vector3f const right(hs, 0.0f, 0.0f);
Vector3f const up(0.0f, hs, 0.0f);
AddLine(
pos - fwd,
pos + fwd,
Vector4f(0.0f, 0.0f, 1.0f, 1.0f),
Vector4f(0.0f, 0.0f, 1.0f, 1.0f),
endFrame,
depthTest);
AddLine(
pos - right,
pos + right,
Vector4f(1.0f, 0.0f, 0.0f, 1.0f),
Vector4f(1.0f, 0.0f, 0.0f, 1.0f),
endFrame,
depthTest);
AddLine(
pos - up,
pos + up,
Vector4f(0.0f, 1.0f, 0.0f, 1.0f),
Vector4f(0.0f, 1.0f, 0.0f, 1.0f),
endFrame,
depthTest);
}
//==============================
// OvrDebugLinesLocal::AddAxes
void OvrDebugLinesLocal::AddAxes(
const Vector3f& origin,
const Matrix4f& axes,
const float size,
const Vector4f& color,
const long long endFrame,
const bool depthTest) {
const float half_size = size * 0.5f;
Vector3f const fwd = Vector3f(axes.M[2][0], axes.M[2][1], axes.M[2][2]) * half_size;
Vector3f const right = Vector3f(axes.M[0][0], axes.M[0][1], axes.M[0][2]) * half_size;
Vector3f const up = Vector3f(axes.M[1][0], axes.M[1][1], axes.M[1][2]) * half_size;
AddLine(
origin - fwd,
origin + fwd,
Vector4f(0.0f, 0.0f, 1.0f, 1.0f),
Vector4f(0.0f, 0.0f, 1.0f, 1.0f),
endFrame,
depthTest);
AddLine(
origin - right,
origin + right,
Vector4f(1.0f, 0.0f, 0.0f, 1.0f),
Vector4f(1.0f, 0.0f, 0.0f, 1.0f),
endFrame,
depthTest);
AddLine(
origin - up,
origin + up,
Vector4f(0.0f, 1.0f, 0.0f, 1.0f),
Vector4f(0.0f, 1.0f, 0.0f, 1.0f),
endFrame,
depthTest);
}
//==============================
// OvrDebugLinesLocal::AddBounds
void OvrDebugLinesLocal::AddBounds(
Posef const& pose,
Bounds3f const& bounds,
Vector4f const& color) {
Vector3f const& mins = bounds.GetMins();
Vector3f const& maxs = bounds.GetMaxs();
Vector3f corners[8];
corners[0] = mins;
corners[7] = maxs;
corners[1] = Vector3f(mins.x, maxs.y, mins.z);
corners[2] = Vector3f(mins.x, maxs.y, maxs.z);
corners[3] = Vector3f(mins.x, mins.y, maxs.z);
corners[4] = Vector3f(maxs.x, mins.y, mins.z);
corners[5] = Vector3f(maxs.x, maxs.y, mins.z);
corners[6] = Vector3f(maxs.x, mins.y, maxs.z);
// transform points
for (int i = 0; i < 8; ++i) {
corners[i] = pose.Rotation.Rotate(corners[i]);
corners[i] += pose.Translation;
}
AddLine(corners[0], corners[1], color, color, 1, true);
AddLine(corners[1], corners[2], color, color, 1, true);
AddLine(corners[2], corners[3], color, color, 1, true);
AddLine(corners[3], corners[0], color, color, 1, true);
AddLine(corners[7], corners[6], color, color, 1, true);
AddLine(corners[6], corners[4], color, color, 1, true);
AddLine(corners[4], corners[5], color, color, 1, true);
AddLine(corners[5], corners[7], color, color, 1, true);
AddLine(corners[0], corners[4], color, color, 1, true);
AddLine(corners[1], corners[5], color, color, 1, true);
AddLine(corners[2], corners[7], color, color, 1, true);
AddLine(corners[3], corners[6], color, color, 1, true);
}
//==============================
// OvrDebugLinesLocal::BeginFrame
void OvrDebugLinesLocal::BeginFrame(const long long frameNum) {
// LOG( "OvrDebugLinesLocal::RemoveExpired: frame %lli, removing %i lines", frameNum,
// DepthTestedLines.GetSizeI() + NonDepthTestedLines.GetSizeI() );
DepthTested.Surf.geo.indexCount = 0;
NonDepthTested.Surf.geo.indexCount = 0;
RemoveExpired(frameNum, DepthTested);
RemoveExpired(frameNum, NonDepthTested);
}
//==============================
// OvrDebugLinesLocal::RemoveExpired
void OvrDebugLinesLocal::RemoveExpired(const long long frameNum, DebugLines_t& lines) {
for (int i = lines.EndFrame.size() - 1; i >= 0; --i) {
if (frameNum >= lines.EndFrame[i]) {
lines.Attr.position.erase(
lines.Attr.position.cbegin() + (i * 2), lines.Attr.position.cbegin() + (i * 2) + 2);
lines.Attr.color.erase(
lines.Attr.color.cbegin() + (i * 2), lines.Attr.color.cbegin() + (i * 2) + 2);
lines.EndFrame.erase(lines.EndFrame.cbegin() + i);
}
}
}
//==============================
// OvrDebugLines::Create
OvrDebugLines* OvrDebugLines::Create() {
return new OvrDebugLinesLocal;
}
//==============================
// OvrDebugLines::Free
void OvrDebugLines::Free(OvrDebugLines*& debugLines) {
if (debugLines != NULL) {
delete debugLines;
debugLines = NULL;
}
}
} // namespace OVRFW
| 30.713158 | 100 | 0.601405 | [
"render",
"vector",
"transform"
] |
f8b2ae205ba4a5c97b94c3dfe55a8ac2981739a7 | 20,976 | cpp | C++ | src/nebedit/nebedit.cpp | ptitSeb/freespace2 | 500ee249f7033aac9b389436b1737a404277259c | [
"Linux-OpenIB"
] | 1 | 2020-07-14T07:29:18.000Z | 2020-07-14T07:29:18.000Z | src/nebedit/nebedit.cpp | ptitSeb/freespace2 | 500ee249f7033aac9b389436b1737a404277259c | [
"Linux-OpenIB"
] | 2 | 2019-01-01T22:35:56.000Z | 2022-03-14T07:34:00.000Z | src/nebedit/nebedit.cpp | ptitSeb/freespace2 | 500ee249f7033aac9b389436b1737a404277259c | [
"Linux-OpenIB"
] | 2 | 2021-03-07T11:40:42.000Z | 2021-12-26T21:40:39.000Z | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on
* the source.
*/
/*
* $Logfile: /Freespace2/code/nebedit/NebEdit.cpp $
* $Revision: 110 $
* $Date: 2002-06-09 06:41:30 +0200 (Sun, 09 Jun 2002) $
* $Author: relnev $
*
* Program to edit nebulas in 2d
*
* $Log$
* Revision 1.3 2002/06/09 04:41:23 relnev
* added copyright header
*
* Revision 1.2 2002/05/07 03:16:47 theoddone33
* The Great Newline Fix
*
* Revision 1.1.1.1 2002/05/03 03:28:10 root
* Initial import.
*
*
* 7 7/15/99 3:07p Dave
* 32 bit detection support. Mouse coord commandline.
*
* 6 5/19/99 4:07p Dave
* Moved versioning code into a nice isolated common place. Fixed up
* updating code on the pxo screen. Fixed several stub problems.
*
* 5 1/08/99 2:06p Dave
* Fixed pfoview for software mode.
*
* 4 12/18/98 1:14a Dave
* Rough 1024x768 support for Direct3D. Proper detection and usage through
* the launcher.
*
* 3 11/13/98 2:32p Dave
* Improved commandline parsing for exe pathname.
*
* 2 10/24/98 9:51p Dave
*
* 1 10/24/98 9:39p Dave
*
* 13 4/13/98 10:11a John
* Made timer functions thread safe. Made timer_init be called in all
* projects.
*
* 12 3/23/98 1:35p Sandeep
*
* 11 3/05/98 11:15p Hoffoss
* Changed non-game key checking to use game_check_key() instead of
* game_poll().
*
* 10 12/29/97 5:10p Allender
* fixed problems with speed not being reported properly in multiplayer
* games. Made read_flying_controls take frametime as a parameter. More
* ship/weapon select stuff
*
* 9 12/04/97 3:47p John
* Made joystick move mouse cursor
*
* 8 11/21/97 11:32a John
* Added nebulas. Fixed some warpout bugs.
*
* 7 11/19/97 10:15p Adam
* upped maxtris to 200
*
* 6 11/19/97 4:28p Sandeep
* added poly/vert counter
*
* 5 11/19/97 1:59p Sandeep
* Added multiple vertex editing mode
*
* 4 11/16/97 2:29p John
* added versioning to nebulas; put nebula code into freespace.
*
* 3 11/13/97 12:04p Sandeep
* Added face editing support, deletion support, and a saving and loading
* stuff.
*
* 2 11/10/97 9:59p John
* some tweaking
*
* 1 11/10/97 9:42p John
*
* $NoKeywords: $
*/
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <dos.h>
#include "pstypes.h"
#include "2d.h"
#include "3d.h"
#include "key.h"
#include "palman.h"
#include "bmpman.h"
#include "timer.h"
#include "floating.h"
#include "osapi.h"
#include "cfile.h"
#include "linklist.h"
#include "lighting.h"
#include "mouse.h"
#include "vecmat.h"
#include "physics.h"
#include "model.h"
#include "font.h"
#define SCREEN_W 640
#define SCREEN_H 480
vector ViewerPos;
matrix ViewerOrient;
matrix ModelOrient;
vector ModelPos;
physics_info ViewerPhysics;
float ViewerZoom = 1.0f;
int test_model = -1;
int Fred_running = 0;
int Pofview_running = 0;
float flFrametime = 0.0f;
int Font1 = -1;
color color_green;
vector Global_light_world = { 0.208758f, -0.688253f, -0.694782f };
// nebula stuff
#define NEB_W 6
#define NEB_H 6
#define MAX_TRIS 200
#define MAX_POINTS 300
int neb_w = 0, neb_h = 0;
int nebula_inited = 0;
int num_pts = 0;
int x[MAX_POINTS], y[MAX_POINTS], l[MAX_POINTS];
float scale_factor = 1.0f;
int num_tris = 0;
int tri[MAX_TRIS][3];
color nebula_color;
int Mouse_x, Mouse_y;
int Current_point;
BOOL Selected[MAX_POINTS];
BOOL Sel_mode = 0; // 0 = 1 point at a time, 1 = select multiple points
int Current_face;
int View_mode = 0; // 0 = 2d editor, 1 = 3d viewer
int Vert_mode = 0; // 0 = Move vertices/Add vertices, 2 = Move face/Add face
int Which_vert = 0; // Current vertex of the faceadd
int Orig_pos_x;
int Orig_pos_y;
int End_pos_x;
int End_pos_y;
BOOL Draw_sel_box = FALSE;
int Neb_created = 0;
int Nebedit_running = 1;
extern int load_nebula_sub(char*);
extern void project_2d_onto_sphere(vector *, float, float);
void create_default_neb()
{
int i,j;
neb_w = NEB_W;
neb_h = NEB_H;
num_pts = neb_w*neb_h;
for (j=0; j<neb_h; j++ ) {
for (i=0; i<neb_w; i++ ) {
x[i+j*neb_w] = ((i+1)*SCREEN_W)/(neb_w+2);
y[i+j*neb_w] = ((j+3)*SCREEN_H)/(neb_h+6);
if ( (j==0) || (j==neb_h-1)) {
l[i+j*neb_w] = 0;
} else {
l[i+j*neb_w] = 31;
}
}
}
num_tris = 0;
for (j=0; j<neb_h-1; j++ ) {
for (i=0; i<neb_w-1; i++ ) {
tri[num_tris][0] = i+neb_w*j;
tri[num_tris][1] = i+neb_w*j+1;
tri[num_tris][2] = i+neb_w*(j+1)+1;
num_tris++;
tri[num_tris][0] = i+neb_w*j;
tri[num_tris][1] = i+neb_w*(j+1)+1;
tri[num_tris][2] = i+neb_w*(j+1);
num_tris++;
}
}
Neb_created = 1;
}
#define NEBULA_FILE_ID "NEBU"
#define NEBULA_MAJOR_VERSION 1 // Can be 1-?
#define NEBULA_MINOR_VERSION 0 // Can be 0-99
void save_nebula_sub(char *filename)
{
FILE *fp;
float xf, yf;
int version;
fp = fopen(filename, "wb");
// ID of NEBU
fwrite( "NEBU", 4, 1, fp );
version = NEBULA_MAJOR_VERSION*100+NEBULA_MINOR_VERSION;
fwrite( &version, sizeof(int), 1, fp );
fwrite( &num_pts, sizeof(int), 1, fp );
fwrite( &num_tris, sizeof(int), 1, fp );
for (int i=0; i<num_pts; i++ ) {
xf = float(x[i])/640.0f;
yf = float(y[i])/480.0f;
fwrite( &xf, sizeof(float), 1, fp );
fwrite( &yf, sizeof(float), 1, fp );
fwrite( &l[i], sizeof(int), 1, fp );
}
for (i=0; i<num_tris; i++ ) {
fwrite( &tri[i][0], sizeof(int), 1, fp );
fwrite( &tri[i][1], sizeof(int), 1, fp );
fwrite( &tri[i][2], sizeof(int), 1, fp );
}
fclose(fp);
}
void nebedit_close()
{
save_nebula_sub( "autosaved.neb" );
}
void save_nebula()
{
char filename[255] = "\0";
//char filter[255] = "Nebula Files\0
OPENFILENAME o;
memset(&o,0,sizeof(o));
o.lStructSize = sizeof(o);
//o.hwndOwner = GetActiveWindow();
o.lpstrFilter = "Nebula Files\0*.NEB\0\0";
o.lpstrFile = filename;
o.nMaxFile = 256;
o.Flags = OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
o.lpstrDefExt = "*.NEB";
if (!GetSaveFileName(&o)) return;
save_nebula_sub(filename);
}
void load_nebula()
{
char filename[255] = "\0";
OPENFILENAME o;
memset(&o,0,sizeof(o));
o.lStructSize = sizeof(OPENFILENAME);
//o.hwndOwner = GetActiveWindow();
o.lpstrFilter = "Nebula Files\0*.NEB\0\0";
o.lpstrFile = filename;
o.nMaxFile = 256;
o.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
o.lpstrDefExt = "*.NEB";
int create_default = 0;
if (!GetOpenFileName(&o)) {
create_default = 1;
} else {
if ( !load_nebula_sub(filename)) {
create_default = 1;
}
}
if ( create_default ) {
create_default_neb();
}
Neb_created = 1;
}
void nebula_init()
{
if ( nebula_inited ) return;
memset(Selected, 0, sizeof(BOOL)*MAX_POINTS);
nebula_inited++;
create_default_neb();
gr_init_alphacolor( &nebula_color, 0, 255, 0, 255 );
return;
}
void draw_tri_2d( int i, int j, int k )
{
int index[3];
index[0] = i;
index[1] = j;
index[2] = k;
vertex va, vb, vc;
vertex * verts[3] = { &va, &vb, &vc };
// gr_zbuffering = 0;
for (int v=0; v<3; v++ ) {
verts[v]->sx = i2fl(x[index[v]]);
verts[v]->sy = i2fl(y[index[v]]);
verts[v]->u = 0.0f;
verts[v]->v = 0.0f;
verts[v]->sw = 1.0f;
verts[v]->r = verts[v]->g = verts[v]->b = (ubyte)(i2fl(l[index[v]])/31.0f);
}
// gr_set_color( 0, 0, 0 );
gr_tmapper(3, verts, TMAP_FLAG_RAMP | TMAP_FLAG_GOURAUD | TMAP_FLAG_NEBULA );
if ( !keyd_pressed[KEY_LSHIFT] ) {
gr_set_color(100,100,100);
gr_line( x[i], y[i], x[j], y[j] );
gr_line( x[j], y[j], x[k], y[k] );
gr_line( x[k], y[k], x[i], y[i] );
}
}
void nebula_draw_2d()
{
int i;
for (i=0; i<num_tris; i++ ) {
draw_tri_2d( tri[i][0], tri[i][1], tri[i][2] );
}
gr_set_color(100,0,0);
for (i=0; i<num_pts; i++ ) {
gr_circle( x[i], y[i], 4 );
}
if ((Sel_mode==1)) { // multiple selection
if (Draw_sel_box) {
gr_set_color(200,0,200);
gr_line(Orig_pos_x, Orig_pos_y, Orig_pos_x, End_pos_y);
gr_line(Orig_pos_x, End_pos_y, End_pos_x, End_pos_y);
gr_line(End_pos_x, Orig_pos_y, End_pos_x, End_pos_y);
gr_line(End_pos_x, Orig_pos_y, Orig_pos_x, Orig_pos_y);
} else {
gr_set_color(0,100,0);
for (int i=0;i<num_pts;i++)
if (Selected[i]) gr_circle( x[i], y[i], 5);
}
} else if ((Vert_mode==0)&&(Current_point>-1)) {
gr_set_color(0,100,0);
gr_circle( x[Current_point], y[Current_point], 5);
} else if (Vert_mode == 1) {
for (i=0;i<Which_vert;i++) {
gr_set_color(0,0,100);
gr_circle( x[tri[num_tris][i]], y[tri[num_tris][i]], 6);
}
gr_set_color(200,200,0);
if (Current_face>-1) {
gr_line(x[tri[Current_face][0]], y[tri[Current_face][0]],
x[tri[Current_face][1]], y[tri[Current_face][1]]);
gr_line(x[tri[Current_face][1]], y[tri[Current_face][1]],
x[tri[Current_face][2]], y[tri[Current_face][2]]);
gr_line(x[tri[Current_face][2]], y[tri[Current_face][2]],
x[tri[Current_face][0]], y[tri[Current_face][0]]);
}
}
}
void draw_tri_3d( int i, int j, int k )
{
int index[3];
index[2] = k;
index[1] = j;
index[0] = i;
vertex va, vb, vc;
vertex * verts[3] = { &va, &vb, &vc };
//gr_zbuffering = 0;
for (int v=0; v<3; v++ ) {
vector tmp;
project_2d_onto_sphere( &tmp, 1.0f - i2fl(x[index[v]])/640.0f, i2fl(y[index[v]])/480.0f );
vm_vec_scale( &tmp, 10.0f );
g3_rotate_faraway_vertex( verts[v], &tmp );
//g3_rotate_vertex( verts[v], &tmp );
g3_project_vertex( verts[v] );
verts[v]->r = verts[v]->g = verts[v]->b = (ubyte)(i2fl(l[index[v]])/31.0f);
}
//gr_zbuffering = 0;
//gr_set_color_fast( &nebula_color );
//gr_set_color( 0, 0, 0 );
g3_draw_poly(3, verts, TMAP_FLAG_RAMP | TMAP_FLAG_GOURAUD | TMAP_FLAG_NEBULA );
}
void nebula_draw_3d()
{
int i;
for (i=0; i<num_tris; i++ ) {
draw_tri_3d( tri[i][0], tri[i][1], tri[i][2] );
}
}
void render_frame()
{
gr_reset_clip();
gr_set_color(0,0,0); // set color to black
gr_rect(0,0,SCREEN_W,SCREEN_H); // clear screen
light_reset();
light_add_directional( &Global_light_world, 0.1f, 1.0f, 1.0f, 1.0f );
g3_start_frame(1);
g3_set_view_matrix(&ViewerPos, &ViewerOrient,ViewerZoom);
if ( View_mode == 0 ) {
nebula_draw_2d();
gr_set_font(Font1);
gr_set_color_fast( &color_green );
gr_printf(10,10,"Nebula Editor. Mode :");
if (Sel_mode ==1) {
gr_printf(180, 10, "Multiple Vertex Selection Editing");
} else if (Vert_mode ==0 ) {
gr_printf(180,10,"Vertex Editing");
if(Current_point >= 0){
gr_printf(180, 20, "Current vertex intensity : %d\n", l[Current_point]);
}
} else if (Vert_mode ==1) {
gr_printf(180,10,"Face Editing");
}
char blah[255];
gr_printf(20,30,"# Points:");
gr_printf(100,30, itoa(num_pts, blah, 10));
gr_printf(220,30,"# Polys:");
gr_printf(300,30, itoa(num_tris, blah, 10));
} else {
nebula_draw_3d();
model_render( test_model, &ModelOrient, &ModelPos );
}
g3_end_frame();
gr_flip();
}
int get_closest(int mx, int my)
{
int i, closest = -1, cval = 100000;
for (i=0; i<num_pts; i++ ) {
int dist;
int dx, dy;
dx = x[i] - mx;
dy = y[i] - my;
dist = fl2i(fl_sqrt( i2fl((dx*dx)+(dy*dy)) ));
if ( dist < cval ) {
cval = dist;
closest = i;
}
}
return closest;
}
int get_closest_face(int mx, int my)
{
int i, closest = -1, cval = 100000;
for (i=0; i<num_tris; i++ ) {
int dist;
int dx, dy;
dx = x[tri[i][0]] - mx;
dy = y[tri[i][0]] - my;
dx += x[tri[i][1]] - mx;
dy += y[tri[i][1]] - my;
dx += x[tri[i][2]] - mx;
dy += y[tri[i][2]] - my;
dist = fl2i(fl_sqrt( i2fl((dx*dx)+(dy*dy)) ));
/*
dist += fl2i(fl_sqrt( i2fl((dx*dx)+(dy*dy)) ));
dx = x[tri[i][2]] - mx;
dy = y[tri[i][2]] - my;
dist += fl2i(fl_sqrt( i2fl((dx*dx)+(dy*dy)) ));
*/
if ( dist < cval ) {
cval = dist;
closest = i;
}
}
return closest;
}
void delete_face(int i)
{
for (int j=i;j<num_tris;j++) {
memcpy(tri[j], tri[j+1], sizeof(int)*3);
}
num_tris--;
}
void delete_vert(int i)
{
for (int j=0;j<num_tris;j++) {
if ((tri[j][0]==i)||(tri[j][1]==i)||(tri[j][2]==i)) {
delete_face(j);
j=0;
}
}
for (j=0;j<num_tris;j++) {
if (tri[j][0]>i) tri[j][0]--;
if (tri[j][1]>i) tri[j][1]--;
if (tri[j][2]>i) tri[j][2]--;
}
for (j=i;j<num_pts;j++) {
x[j] = x[j+1];
y[j] = y[j+1];
l[j] = l[j+1];
}
num_pts--;
}
int add_vert(int mx, int my)
{
Assert(num_pts<300);
x[num_pts] = mx;
y[num_pts] = my;
l[num_pts] = 0;
num_pts++;
return num_pts-1;
}
void select_by_box(int x1, int y1, int x2, int y2)
{
if (x1>x2) {
int temp = x1;
x1 = x2;
x2 = temp;
}
if (y1>y2) {
int temp = y1;
y1 = y2;
y2 = temp;
}
for (int i=0;i<num_pts;i++) {
if ((x[i]<=x2) && (x[i]>=x1) &&
(y[i]<=y2) && (y[i]>=y1)) {
Selected[i] = TRUE;
}
}
}
void sphericalize_nebula()
{
int idx1, idx2;
int px = SCREEN_W / (neb_w - 1);
int py = SCREEN_H / (neb_h - 1);
// flatten out the nebula so that it covers the entire sphere evenly
for(idx1=0; idx1<neb_w; idx1++){
for(idx2=0; idx2<neb_h; idx2++){
x[idx1+idx2*neb_w] = px * idx1;
y[idx1+idx2*neb_w] = py * idx2;
}
}
}
void controls_read_all(control_info * ci, float sim_time )
{
float kh;
{
float temp = ci->heading;
float temp1 = ci->pitch;
memset( ci, 0, sizeof(control_info) );
ci->heading = temp;
ci->pitch = temp1;
}
// From keyboard...
kh = (key_down_timef(KEY_PAD6) - key_down_timef(KEY_PAD4))/8.0f;
if (kh == 0.0f)
ci->heading = 0.0f;
else if (kh > 0.0f) {
if (ci->heading < 0.0f)
ci->heading = 0.0f;
} else // kh < 0
if (ci->heading > 0.0f)
ci->heading = 0.0f;
ci->heading += kh;
kh = (key_down_timef(KEY_PAD8) - key_down_timef(KEY_PAD2))/8.0f;
if (kh == 0.0f)
ci->pitch = 0.0f;
else if (kh > 0.0f) {
if (ci->pitch < 0.0f)
ci->pitch = 0.0f;
} else // kh < 0
if (ci->pitch > 0.0f)
ci->pitch = 0.0f;
ci->pitch += kh;
ci->bank = (key_down_timef(KEY_PAD7) - key_down_timef(KEY_PAD9))*.75f;
ci->forward = key_down_timef(KEY_A) - key_down_timef(KEY_Z);
ci->sideways = key_down_timef(KEY_PAD3) - key_down_timef(KEY_PAD1);
ci->vertical = key_down_timef(KEY_PADPLUS) - key_down_timef(KEY_PADENTER);
}
int check_keys()
{
int k;
while( (k = key_inkey()) != 0 ) {
//mprintf(( "Key = %x\n", k ));
if ( k == KEY_ESC ) {
return 1;
}
switch( k ) {
case KEY_ENTER:
Sel_mode = FALSE;
Vert_mode = !Vert_mode;
Which_vert = 0;
break;
case KEY_DELETE:
if (Sel_mode) break;
if (Vert_mode==1) delete_face(Current_face);
else if (Vert_mode==0) {
delete_vert(Current_point);
}
break;
case KEY_MINUS:
scale_factor -= 0.05f;
mprintf(( "Scale = %.1f\n", scale_factor ));
break;
case KEY_EQUAL:
scale_factor += 0.05f;
mprintf(( "Scale = %.1f\n", scale_factor ));
break;
case KEY_INSERT:
Sel_mode = !Sel_mode;
break;
case KEY_SPACEBAR:
View_mode = !View_mode;
break;
case KEY_COMMA:
if (Sel_mode) {
int i;
for (i=0;i<num_pts;i++) if (Selected[i]) {
if ( l[i] > 0 ) {
l[i]--;
}
}
} else if (Vert_mode==0) {
if ( Current_point > -1 ) {
if ( l[Current_point] > 0 ) {
l[Current_point]--;
}
}
} else if (Vert_mode ==1) {
if ( l[tri[Current_face][0]] > 0 ) {
l[tri[Current_face][0]]--;
}
if ( l[tri[Current_face][1]] > 0 ) {
l[tri[Current_face][1]]--;
}
if ( l[tri[Current_face][2]] > 0 ) {
l[tri[Current_face][2]]--;
}
}
break;
case KEY_PERIOD:
if (Sel_mode) {
int i;
for (i=0;i<num_pts;i++) if (Selected[i]) {
if ( l[i] < 31 ) {
l[i]++;
}
}
} else if (Vert_mode==0) {
if ( Current_point > -1 ) {
if ( l[Current_point] < 31 ) {
l[Current_point]++;
}
}
} else if (Vert_mode ==1) {
if ( l[tri[Current_face][0]] <31 ) {
l[tri[Current_face][0]]++;
}
if ( l[tri[Current_face][1]] <31) {
l[tri[Current_face][1]]++;
}
if ( l[tri[Current_face][2]] <31 ) {
l[tri[Current_face][2]]++;
}
}
break;
case KEY_F5:
save_nebula();
break;
case KEY_F7:
load_nebula();
break;
case KEY_BACKSP:
sphericalize_nebula();
break;
}
}
return 0;
}
void os_close()
{
exit(1);
}
int newtri[3];
int mdflag = 0;
int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow)
{
int i;
fix t1, t2;
control_info ci;
float speed = 20.0f; // how fast viewer moves
// setup the fred exe directory so CFILE can init properly
/*
char *c = GetCommandLine();
Assert(c != NULL);
char *tok = strtok(c, " ");
Assert(tok != NULL);
*/
timer_init();
// cfile_init(tok);
cfile_init(__argv[0]);
os_init( "NebEdit", "NebEdit" ); //SCREEN_W, SCREEN_H );
palette_load_table( "gamepalette1-01.pcx" );
gr_init(GR_640, GR_SOFTWARE, 8);
key_init();
mouse_init();
Font1 = gr_init_font( "font01.vf" );
gr_init_alphacolor( &color_green, 0,255,0,255 );
test_model = model_load( "fighter01.pof", 0, NULL );
physics_init( &ViewerPhysics );
ViewerPhysics.flags |= PF_ACCELERATES | PF_SLIDE_ENABLED;
ViewerPhysics.max_vel.x = 2.0f*speed; //sideways
ViewerPhysics.max_vel.y = 2.0f*speed; //up/down
ViewerPhysics.max_vel.z = 2.0f*speed; //forward
ViewerPhysics.max_rear_vel = 2.0f*speed; //backward -- controlled seperately
memset( &ci, 0, sizeof(control_info) );
ModelOrient = vmd_identity_matrix;
ModelPos.x=0.0f; ModelPos.y = 0.0f; ModelPos.z = 0.0f;
ViewerOrient = vmd_identity_matrix;
ViewerPos.x=0.0f; ViewerPos.y = 0.0f; ViewerPos.z = -50.0f;
flFrametime = 0.033f;
t1 = timer_get_fixed_seconds();
nebula_init();
int some_selected = 0;
while(1) {
some_selected = FALSE;
if (Sel_mode==1) {
for (i=0;i<num_pts;i++) {
if (Selected[i]) {
some_selected = TRUE;
break;
}
}
}
mouse_get_pos( &Mouse_x, &Mouse_y );
if (Current_face==-1) {
Current_face = get_closest_face(Mouse_x, Mouse_y);
}
if ( check_keys() ){
break;
}
if ( Sel_mode==1 ) {
// Special mouse handlers for multiple selmode
if (mouse_down_count(LOWEST_MOUSE_BUTTON)) {
Orig_pos_x = Mouse_x;
Orig_pos_y = Mouse_y;
}
if (mouse_down(LOWEST_MOUSE_BUTTON)) {
for (i=0;i<num_pts;i++) {
if (Selected[i]) {
x[i]+=Mouse_x - Orig_pos_x;
y[i]+=Mouse_y - Orig_pos_y;
}
}
Orig_pos_x = Mouse_x;
Orig_pos_y = Mouse_y;
}
if (mouse_down_count(MOUSE_RIGHT_BUTTON)) {
Orig_pos_x = Mouse_x;
Orig_pos_y = Mouse_y;
for (i=0;i<num_pts;i++) {
Selected[i] = FALSE;
}
}
if (mouse_down(MOUSE_RIGHT_BUTTON)) {
Draw_sel_box = TRUE;
End_pos_x = Mouse_x;
End_pos_y = Mouse_y;
}
if (mouse_up_count(MOUSE_RIGHT_BUTTON)) {
Draw_sel_box = FALSE;
End_pos_x = Mouse_x;
End_pos_y = Mouse_y;
select_by_box(Orig_pos_x, Orig_pos_y, End_pos_x, End_pos_y);
}
} else {
if ( mouse_down(LOWEST_MOUSE_BUTTON) ) {
if ( mdflag ) {
if (Vert_mode==0) {
x[Current_point] = Mouse_x;
y[Current_point] = Mouse_y;
} else if (Vert_mode==1) {
x[tri[Current_face][0]] += Mouse_x - Orig_pos_x;
y[tri[Current_face][0]] += Mouse_y - Orig_pos_y;
x[tri[Current_face][1]] += Mouse_x - Orig_pos_x;
y[tri[Current_face][1]] += Mouse_y - Orig_pos_y;
x[tri[Current_face][2]] += Mouse_x - Orig_pos_x;
y[tri[Current_face][2]] += Mouse_y - Orig_pos_y;
Orig_pos_x = Mouse_x;
Orig_pos_y = Mouse_y;
}
} else {
if (Vert_mode == 1) {
Current_face = get_closest_face(Mouse_x, Mouse_y);
Orig_pos_x = Mouse_x;
Orig_pos_y = Mouse_y;
}
if (Vert_mode==0) {
Current_point = get_closest(Mouse_x, Mouse_y);
mouse_set_pos(x[Current_point], y[Current_point]);
}
mdflag = TRUE;
}
}
if ( mouse_up_count(LOWEST_MOUSE_BUTTON)) {
//Current_point = -1;
//Current_face = -1;
mdflag = FALSE;
}
if ( mouse_up_count(MOUSE_RIGHT_BUTTON) ) {
if (Vert_mode==0) {
Current_point = add_vert(Mouse_x, Mouse_y);
} else if (Vert_mode==1) {
if ((num_tris<MAX_TRIS-1)) {
tri[num_tris][Which_vert] = get_closest(Mouse_x, Mouse_y);
Which_vert++;
if (Which_vert>2) {
Which_vert = 0;
num_tris++;
}
}
}
}
}
controls_read_all(&ci, flFrametime );
physics_read_flying_controls( &ViewerOrient, &ViewerPhysics, &ci, flFrametime );
physics_sim(&ViewerPos, &ViewerOrient, &ViewerPhysics, flFrametime );
render_frame();
t2 = timer_get_fixed_seconds();
if ( t2 > t1 ) {
flFrametime = f2fl(t2 - t1);
}
t1 = t2;
}
nebedit_close();
return 0;
}
// Stub functions and variables.
// These do nothing but are needed to prevent link errors.
void demo_set_playback_filter() {}
void freespace_menu_background()
{
gr_reset_clip();
gr_clear();
}
int game_check_key()
{
return key_inkey();
}
int game_poll()
{
return key_inkey();
}
vector Camera_pos;
vector Dead_player_last_vel;
// end stubs
| 21.338759 | 92 | 0.611079 | [
"vector",
"model",
"3d"
] |
f8b9cd4660ae5d1f1bd26ddca62f3f171b3aed7f | 16,344 | cpp | C++ | src/Geometry3D.cpp | omi-lab/tp_math_utils | bbcdec7a680fb2fd029006ad456efb5e81d840c3 | [
"MIT"
] | null | null | null | src/Geometry3D.cpp | omi-lab/tp_math_utils | bbcdec7a680fb2fd029006ad456efb5e81d840c3 | [
"MIT"
] | null | null | null | src/Geometry3D.cpp | omi-lab/tp_math_utils | bbcdec7a680fb2fd029006ad456efb5e81d840c3 | [
"MIT"
] | 3 | 2018-08-30T10:01:10.000Z | 2020-10-07T10:56:26.000Z | #include "tp_math_utils/Geometry3D.h"
#include "tp_math_utils/Intersection.h"
#include "tp_math_utils/Plane.h"
#include "tp_math_utils/Ray.h"
#include "tp_math_utils/JSONUtils.h"
#include "tp_utils/DebugUtils.h"
#include "nanoflann.hpp"
#include "glm/gtx/norm.hpp"
#include "glm/gtx/normal.hpp"
#include <array>
namespace tp_math_utils
{
namespace
{
struct Face_lt
{
std::array<int, 3> indexes{};
glm::vec3 normal{};
};
//##################################################################################################
std::vector<Face_lt> calculateFaces(const Geometry3D& geometry, bool calculateNormals)
{
std::vector<Face_lt> faces;
size_t count=0;
for(const auto& indexes : geometry.indexes)
{
if(indexes.indexes.size()<3)
continue;
if(indexes.type == geometry.triangleFan)
count+=indexes.indexes.size()-2;
else if(indexes.type == geometry.triangleStrip)
count+=indexes.indexes.size()-2;
else if(indexes.type == geometry.triangles)
count+=indexes.indexes.size()/3;
}
faces.reserve(count);
for(const auto& indexes : geometry.indexes)
{
auto calcVMax = [&](size_t sub)
{
return (sub>indexes.indexes.size())?0:indexes.indexes.size()-sub;
};
if(indexes.type == geometry.triangleFan)
{
const auto& f = indexes.indexes.front();
size_t vMax = calcVMax(1);
for(size_t v=1; v<vMax; v++)
{
Face_lt& face = faces.emplace_back();
face.indexes[0] = f;
face.indexes[1] = indexes.indexes.at(v);
face.indexes[2] = indexes.indexes.at(v+1);
}
}
else if(indexes.type == geometry.triangleStrip)
{
size_t vMax = calcVMax(2);
for(size_t v=0; v<vMax; v++)
{
Face_lt& face = faces.emplace_back();
if(v&1)
{
face.indexes[0] = indexes.indexes.at(v);
face.indexes[1] = indexes.indexes.at(v+2);
face.indexes[2] = indexes.indexes.at(v+1);
}
else
{
face.indexes[0] = indexes.indexes.at(v);
face.indexes[1] = indexes.indexes.at(v+1);
face.indexes[2] = indexes.indexes.at(v+2);
}
}
}
else if(indexes.type == geometry.triangles)
{
size_t vMax = calcVMax(2);
for(size_t v=0; v<vMax; v+=3)
{
Face_lt& face = faces.emplace_back();
face.indexes[0] = indexes.indexes.at(v);
face.indexes[1] = indexes.indexes.at(v+1);
face.indexes[2] = indexes.indexes.at(v+2);
}
}
}
if(calculateNormals)
for(auto& face : faces)
face.normal = glm::triangleNormal(
geometry.verts.at(size_t(face.indexes[0])).vert,
geometry.verts.at(size_t(face.indexes[1])).vert,
geometry.verts.at(size_t(face.indexes[2])).vert);
return faces;
}
}
//##################################################################################################
std::vector<std::string> normalCalculationModes()
{
return
{
"None",
"CalculateFaceNormals",
"CalculateVertexNormals",
"CalculateAdaptiveNormals"
};
}
//##################################################################################################
std::string normalCalculationModeToString(NormalCalculationMode mode)
{
switch(mode)
{
case NormalCalculationMode::None: return "None";
case NormalCalculationMode::CalculateFaceNormals: return "CalculateFaceNormals";
case NormalCalculationMode::CalculateVertexNormals: return "CalculateVertexNormals";
case NormalCalculationMode::CalculateAdaptiveNormals: return "CalculateAdaptiveNormals";
}
return "None";
}
//##################################################################################################
NormalCalculationMode normalCalculationModeFromString(const std::string& mode)
{
if(mode == "None") return NormalCalculationMode::None;
if(mode == "CalculateFaceNormals") return NormalCalculationMode::CalculateFaceNormals;
if(mode == "CalculateVertexNormals") return NormalCalculationMode::CalculateVertexNormals;
if(mode == "CalculateAdaptiveNormals") return NormalCalculationMode::CalculateAdaptiveNormals;
return NormalCalculationMode::None;
}
//##################################################################################################
Vertex3D Vertex3D::interpolate(float u, const Vertex3D& v0, const Vertex3D& v1)
{
float v = 1.0f - u;
tp_math_utils::Vertex3D result;
result.vert = (v*v0.vert ) + (u*v1.vert );
result.color = (v*v0.color ) + (u*v1.color );
result.texture = (v*v0.texture) + (u*v1.texture);
result.normal = (v*v0.normal ) + (u*v1.normal );
return result;
}
//##################################################################################################
Vertex3D Vertex3D::interpolate(float u, float v, const Vertex3D& v0, const Vertex3D& v1, const Vertex3D& v2)
{
float w = 1.0f - (u+v);
tp_math_utils::Vertex3D result;
result.vert = (w*v0.vert ) + (u*v1.vert ) + (v*v2.vert );
result.color = (w*v0.color ) + (u*v1.color ) + (v*v2.color );
result.texture = (w*v0.texture) + (u*v1.texture) + (v*v2.texture);
result.normal = (w*v0.normal ) + (u*v1.normal ) + (v*v2.normal );
return result;
}
//##################################################################################################
void Geometry3D::add(const Geometry3D& other)
{
auto offset = verts.size();
verts.reserve(offset+other.verts.size());
for(const auto& vert : other.verts)
verts.push_back(vert);
indexes.reserve(indexes.size()+other.indexes.size());
for(const auto& index : other.indexes)
for(auto& i : indexes.emplace_back(index).indexes)
i+=int(offset);
}
//##################################################################################################
std::string Geometry3D::stats() const
{
size_t indexCount{0};
size_t triangleCount{0};
for(const auto& index : indexes)
{
indexCount += index.indexes.size();
if(index.type == triangleFan)
triangleCount+=index.indexes.size()-2;
else if(index.type == triangleStrip)
triangleCount+=index.indexes.size()-2;
else if(index.type == triangles)
triangleCount+=index.indexes.size()/3;
}
return
std::string("Verts: ") + std::to_string(verts.size()) +
std::string(" indexes: ") + std::to_string(indexCount) +
std::string(" triangles: ") + std::to_string(triangleCount);
}
//##################################################################################################
void Geometry3D::convertToTriangles()
{
std::vector<Face_lt> faces = calculateFaces(*this, false);
indexes.clear();
Indexes3D& newIndexes = indexes.emplace_back();
newIndexes.type = triangles;
newIndexes.indexes.resize(faces.size()*3);
for(size_t i=0; i<newIndexes.indexes.size(); i++)
newIndexes.indexes[i] = int(i);
std::vector<Vertex3D> newVerts;
newVerts.reserve(faces.size()*3);
for(const auto& face : faces)
{
for(const auto& i : face.indexes)
{
auto& v = newVerts.emplace_back();
v = verts[size_t(i)];
}
}
verts.swap(newVerts);
}
//##################################################################################################
void Geometry3D::calculateNormals(NormalCalculationMode mode, float minDot)
{
switch(mode)
{
case NormalCalculationMode::None:
break;
case NormalCalculationMode::CalculateFaceNormals:
calculateFaceNormals();
break;
case NormalCalculationMode::CalculateVertexNormals:
calculateVertexNormals();
break;
case NormalCalculationMode::CalculateAdaptiveNormals:
calculateAdaptiveNormals(minDot);
break;
}
}
//##################################################################################################
void Geometry3D::calculateVertexNormals()
{
const size_t vMax = verts.size();
std::vector<int> normalCounts(vMax, 0);
for(auto& vert : verts)
vert.normal = {0.0f, 0.0f, 0.0f};
std::vector<Face_lt> faces = calculateFaces(*this, true);
{
auto const* face = faces.data();
auto faceMax = face + faces.size();
for(; face<faceMax; face++)
{
if(std::isnan(face->normal.x) || std::isnan(face->normal.y) || std::isnan(face->normal.z) ||
std::isinf(face->normal.x) || std::isinf(face->normal.y) || std::isinf(face->normal.z))
continue;
for(const auto& i : face->indexes)
{
auto ii = size_t(i);
normalCounts[ii]++;
verts[ii].normal += face->normal;
}
}
}
{
auto vert = verts.data();
auto vertMax = vert+vMax;
auto count = normalCounts.data();
for(; vert<vertMax; vert++, count++)
{
if(*count)
vert->normal = glm::normalize(vert->normal);
else
vert->normal = {0.0f, 0.0f, 1.0f};
}
}
}
//##################################################################################################
void Geometry3D::calculateFaceNormals()
{
std::vector<Face_lt> faces = calculateFaces(*this, true);
indexes.clear();
Indexes3D& newIndexes = indexes.emplace_back();
newIndexes.type = triangles;
newIndexes.indexes.resize(faces.size()*3);
for(size_t i=0; i<newIndexes.indexes.size(); i++)
newIndexes.indexes[i] = int(i);
std::vector<Vertex3D> newVerts;
newVerts.reserve(faces.size()*3);
for(const auto& face : faces)
{
for(const auto& i : face.indexes)
{
auto& v = newVerts.emplace_back();
v = verts[size_t(i)];
v.normal = face.normal;
}
}
verts = std::move(newVerts);
}
namespace
{
struct VertCloud
{
std::vector<Vertex3D> pts;
inline size_t kdtree_get_point_count() const { return pts.size(); }
inline float kdtree_get_pt(const size_t idx, const size_t dim) const
{
switch(dim)
{
case 0: return pts[idx].vert.x;
case 1: return pts[idx].vert.y;
case 2: return pts[idx].vert.z;
case 3: return pts[idx].color.x;
case 4: return pts[idx].color.y;
case 5: return pts[idx].color.z;
case 6: return pts[idx].texture.x;
}
return pts[idx].texture.y;
}
template <class BBOX>
bool kdtree_get_bbox(BBOX&) const { return false; }
};
}
//##################################################################################################
void Geometry3D::combineSimilarVerts()
{
size_t insertPos=0;
std::vector<size_t> idxLookup;
idxLookup.resize(verts.size());
typedef nanoflann::KDTreeSingleIndexDynamicAdaptor<nanoflann::L2_Simple_Adaptor<float, VertCloud>, VertCloud, 8> KDTree;
VertCloud cloud;
cloud.pts.reserve(verts.size());
KDTree tree(8, cloud, nanoflann::KDTreeSingleIndexAdaptorParams(10 /* max leaf */) );
for(size_t i=0; i<verts.size(); i++)
{
const auto& vert = verts.at(i);
bool found=false;
{
float query[8] = {vert.vert.x, vert.vert.y, vert.vert.z, vert.color.x, vert.color.y, vert.color.z, vert.texture.x, vert.texture.y};
size_t index;
float dist2;
nanoflann::KNNResultSet<float> resultSet(1);
resultSet.init(&index, &dist2);
if(tree.findNeighbors(resultSet, query, nanoflann::SearchParams(10)))
{
if(dist2 < 0.0000001f)
{
found = true;
idxLookup[i] = index;
}
}
}
if(!found)
{
cloud.pts.push_back(vert);
tree.addPoints(insertPos, insertPos);
idxLookup[i] = insertPos;
insertPos++;
}
}
verts.swap(cloud.pts);
for(auto& ii : indexes)
for(auto& i : ii.indexes)
i = int(idxLookup[size_t(i)]);
}
//##################################################################################################
void Geometry3D::calculateAdaptiveNormals(float minDot)
{
combineSimilarVerts();
const size_t vMax = verts.size();
for(auto& vert : verts)
vert.normal = {0.0f, 0.0f, 0.0f};
struct VertCluster_lt
{
glm::vec3 normal{0,0,0};
int newVertIndex{0};
};
struct VertDetails_lt
{
std::vector<VertCluster_lt> clusters;
};
std::vector<VertDetails_lt> clusters(vMax);
std::vector<Face_lt> faces = calculateFaces(*this, true);
std::vector<std::array<int, 3>> faceClusters(faces.size());
size_t newVertsCount=0;
for(size_t f=0; f<faces.size(); f++)
{
const auto& face = faces.at(f);
for(size_t i=0; i<3; i++)
{
auto& vertClusters = clusters.at(face.indexes.at(i));
bool done=false;
for(size_t c=0; c<vertClusters.clusters.size(); c++)
{
auto& cluster = vertClusters.clusters.at(c);
if(glm::dot(glm::normalize(cluster.normal), face.normal)>minDot)
{
faceClusters.at(f).at(i) = int(c);
cluster.normal += face.normal;
done=true;
break;
}
}
if(!done)
{
newVertsCount++;
faceClusters.at(f).at(i) = int(vertClusters.clusters.size());
auto& cluster = vertClusters.clusters.emplace_back();
cluster.normal = face.normal;
}
}
}
{
std::vector<Vertex3D> newVerts;
newVerts.reserve(newVertsCount);
for(size_t c=0; c<clusters.size(); c++)
{
auto& vertClusters = clusters.at(c);
for(auto& cluster : vertClusters.clusters)
{
cluster.newVertIndex = int(newVerts.size());
auto& newVert = newVerts.emplace_back();
newVert = verts.at(c);
newVert.normal = glm::normalize(cluster.normal);
}
}
verts = std::move(newVerts);
}
indexes.clear();
Indexes3D& newIndexes = indexes.emplace_back();
newIndexes.type = triangles;
newIndexes.indexes.reserve(faces.size()*3);
for(size_t f=0; f<faceClusters.size(); f++)
{
const auto& face = faces.at(f);
const auto& faceCluster = faceClusters.at(f);
for(size_t i=0; i<3; i++)
{
const auto& vertClusters = clusters.at(face.indexes.at(i));
newIndexes.indexes.push_back(vertClusters.clusters.at(faceCluster.at(i)).newVertIndex);
}
}
}
//##################################################################################################
void Geometry3D::transform(const glm::mat4& m)
{
glm::mat3 r(m);
for(auto& vert : verts)
{
vert.vert = tpProj(m, vert.vert);
vert.normal = r * vert.normal;
}
}
//##################################################################################################
void Geometry3D::addBackFaces()
{
std::vector<Face_lt> faces = calculateFaces(*this, false);
size_t size = verts.size();
verts.resize(size*2);
for(size_t i=0; i<size; i++)
{
auto& dst = verts.at(i+size);
dst = verts.at(i);
dst.normal = -dst.normal;
}
auto& newTriangles = indexes.emplace_back();
newTriangles.type = triangles;
newTriangles.indexes.reserve(faces.size()*3);
for(const auto& face : faces)
{
newTriangles.indexes.push_back(face.indexes[2] + int(size));
newTriangles.indexes.push_back(face.indexes[1] + int(size));
newTriangles.indexes.push_back(face.indexes[0] + int(size));
}
}
//##################################################################################################
tp_utils::StringID Geometry3D::getName() const
{
return (!comments.empty())?tp_utils::StringID(comments.front()):material.name;
}
//##################################################################################################
size_t Geometry3D::sizeInBytes(const std::vector<Geometry3D>& geometry)
{
size_t size{0};
for(const auto& mesh : geometry)
{
for(const auto& indexes : mesh.indexes)
size += indexes.indexes.size() * sizeof(int);
size += mesh.verts.size() * sizeof(Vertex3D);
for(const auto& comment : mesh.comments)
size += comment.size();
}
return size;
}
//##################################################################################################
nlohmann::json Geometry::saveState() const
{
nlohmann::json j;
j["geometry"] = vec2VectorToJSON(geometry);
j["transform"] = mat4ToJSON(transform);
j["material"] = material.saveState();
return j;
}
//##################################################################################################
void Geometry::loadState(const nlohmann::json& j)
{
geometry = vec2VectorFromJSON(TPJSON(j, "geometry"));
transform = mat4FromJSON(TPJSON(j, "transform"));
material.loadState(TPJSON(j, "material"));
}
}
| 28.130809 | 137 | 0.5558 | [
"mesh",
"geometry",
"vector",
"transform"
] |
f8c75a325de97392978bfc703e886e44d8a6c91b | 4,101 | hpp | C++ | psrdada_cpp/dada_write_client.hpp | ewanbarr/psrdada_cpp | 67e61eb3f45600113f1107a9251467ca530e35c7 | [
"MIT"
] | 2 | 2019-04-01T09:00:06.000Z | 2019-08-21T14:15:49.000Z | psrdada_cpp/dada_write_client.hpp | ewanbarr/psrdada_cpp | 67e61eb3f45600113f1107a9251467ca530e35c7 | [
"MIT"
] | 1 | 2018-11-29T12:34:14.000Z | 2018-12-03T19:32:45.000Z | psrdada_cpp/dada_write_client.hpp | ewanbarr/psrdada_cpp | 67e61eb3f45600113f1107a9251467ca530e35c7 | [
"MIT"
] | 2 | 2019-03-05T12:09:18.000Z | 2019-07-05T11:50:16.000Z | #ifndef PSRDADA_CPP_DADA_WRITE_CLIENT_HPP
#define PSRDADA_CPP_DADA_WRITE_CLIENT_HPP
#include "psrdada_cpp/dada_client_base.hpp"
#include "psrdada_cpp/raw_bytes.hpp"
#include "psrdada_cpp/common.hpp"
namespace psrdada_cpp {
/**
* @brief Class that provides means for writing to
* a DADA ring buffer
*/
class DadaWriteClient: public DadaClientBase
{
public:
/**
* @brief A helper class for encapsulating
* the DADA buffer header blocks.
*/
class HeaderStream
{
private:
DadaWriteClient& _parent;
std::unique_ptr<RawBytes> _current_block;
public:
/**
* @brief Create a new instance
*
* @param parent A reference to the parent writing client
*/
HeaderStream(DadaWriteClient& parent);
HeaderStream(HeaderStream const&) = delete;
~HeaderStream();
/**
* @brief Get the next header block in the ring buffer
*
* @detail As only one block can be open at a time, release() must
* be called between subsequenct next() calls.
*
* @return A RawBytes instance wrapping a pointer to share memory
*/
RawBytes& next();
/**
* @brief Release the current header block.
*
* @detail This will mark the block as filled, making it
* readable by reading client.
*/
void release();
};
class DataStream
{
private:
DadaWriteClient& _parent;
std::unique_ptr<RawBytes> _current_block;
std::size_t _block_idx;
public:
/**
* @brief Create a new instance
*
* @param parent A reference to the parent writing client
*/
DataStream(DadaWriteClient& parent);
DataStream(DataStream const&) = delete;
~DataStream();
/**
* @brief Get the next data block in the ring buffer
*
* @detail As only one block can be open at a time, release() must
* be called between subsequenct next() calls.
*
* @return A RawBytes instance wrapping a pointer to share memory
*/
RawBytes& next();
/**
* @brief Release the current data block.
*
* @detail This will mark the block as filled, making it
* readable by reading client.
*/
void release(bool eod=false);
/**
* @brief Return the index of the currently open block
*/
std::size_t block_idx() const;
};
public:
/**
* @brief Create a new client for writing to a DADA buffer
*
* @param[in] key The hexidecimal shared memory key
* @param log A MultiLog instance for logging buffer transactions
*/
DadaWriteClient(key_t key, MultiLog& log);
DadaWriteClient(DadaWriteClient const&) = delete;
~DadaWriteClient();
/**
* @brief Get a reference to a header stream manager
*
* @return A HeaderStream manager object for the current buffer
*/
HeaderStream& header_stream();
/**
* @brief Get a reference to a data stream manager
*
* @return A DataStream manager object for the current buffer
*/
DataStream& data_stream();
void reset();
private:
void lock();
void release();
bool _locked;
HeaderStream _header_stream;
DataStream _data_stream;
};
} //namespace psrdada_cpp
#endif //PSRDADA_CPP_DADA_WRITE_CLIENT_HPP | 30.377778 | 82 | 0.512558 | [
"object"
] |
f8d804e25637996a25bcbb861320f552089c0b51 | 48,189 | cc | C++ | contrib/Delphes-3.1.2/external/fastjet/Selector.cc | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | contrib/Delphes-3.1.2/external/fastjet/Selector.cc | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | contrib/Delphes-3.1.2/external/fastjet/Selector.cc | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | //STARTHEADER
// $Id: Selector.cc 1332 2013-11-20 20:52:59Z pavel $
//
// Copyright (c) 2005-2011, Matteo Cacciari, Gavin P. Salam and Gregory Soyez
//
//----------------------------------------------------------------------
// This file is part of FastJet.
//
// FastJet is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// The algorithms that underlie FastJet have required considerable
// development and are described in hep-ph/0512210. If you use
// FastJet as part of work towards a scientific publication, please
// include a citation to the FastJet paper.
//
// FastJet is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with FastJet. If not, see <http://www.gnu.org/licenses/>.
//----------------------------------------------------------------------
//ENDHEADER
#include <sstream>
#include <algorithm>
#include "fastjet/Selector.hh"
#ifndef __FJCORE__
#include "fastjet/GhostedAreaSpec.hh" // for area support
#endif // __FJCORE__
using namespace std;
FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh
//----------------------------------------------------------------------
// implementations of some of the more complex bits of Selector
//----------------------------------------------------------------------
// implementation of the operator() acting on a vector of jets
std::vector<PseudoJet> Selector::operator()(const std::vector<PseudoJet> & jets) const {
std::vector<PseudoJet> result;
const SelectorWorker * worker_local = validated_worker();
if (worker_local->applies_jet_by_jet()) {
//if (false) {
// for workers that apply jet by jet, this is more efficient
for (std::vector<PseudoJet>::const_iterator jet = jets.begin();
jet != jets.end(); jet++) {
if (worker_local->pass(*jet)) result.push_back(*jet);
}
} else {
// for workers that can only be applied to entire vectors,
// go through the following
std::vector<const PseudoJet *> jetptrs(jets.size());
for (unsigned i = 0; i < jets.size(); i++) {
jetptrs[i] = & jets[i];
}
worker_local->terminator(jetptrs);
for (unsigned i = 0; i < jetptrs.size(); i++) {
if (jetptrs[i]) result.push_back(jets[i]);
}
}
return result;
}
//----------------------------------------------------------------------
// count the number of jets that pass the cuts
unsigned int Selector::count(const std::vector<PseudoJet> & jets) const {
unsigned n = 0;
const SelectorWorker * worker_local = validated_worker();
// separate strategies according to whether the worker applies jet by jet
if (worker_local->applies_jet_by_jet()) {
for (unsigned i = 0; i < jets.size(); i++) {
if (worker_local->pass(jets[i])) n++;
}
} else {
std::vector<const PseudoJet *> jetptrs(jets.size());
for (unsigned i = 0; i < jets.size(); i++) {
jetptrs[i] = & jets[i];
}
worker_local->terminator(jetptrs);
for (unsigned i = 0; i < jetptrs.size(); i++) {
if (jetptrs[i]) n++;
}
}
return n;
}
//----------------------------------------------------------------------
// sift the input jets into two vectors -- those that pass the selector
// and those that do not
void Selector::sift(const std::vector<PseudoJet> & jets,
std::vector<PseudoJet> & jets_that_pass,
std::vector<PseudoJet> & jets_that_fail
) const {
const SelectorWorker * worker_local = validated_worker();
jets_that_pass.clear();
jets_that_fail.clear();
// separate strategies according to whether the worker applies jet by jet
if (worker_local->applies_jet_by_jet()) {
for (unsigned i = 0; i < jets.size(); i++) {
if (worker_local->pass(jets[i])) {
jets_that_pass.push_back(jets[i]);
} else {
jets_that_fail.push_back(jets[i]);
}
}
} else {
std::vector<const PseudoJet *> jetptrs(jets.size());
for (unsigned i = 0; i < jets.size(); i++) {
jetptrs[i] = & jets[i];
}
worker_local->terminator(jetptrs);
for (unsigned i = 0; i < jetptrs.size(); i++) {
if (jetptrs[i]) {
jets_that_pass.push_back(jets[i]);
} else {
jets_that_fail.push_back(jets[i]);
}
}
}
}
#ifndef __FJCORE__
// area using default ghost area
double Selector::area() const{
return area(gas::def_ghost_area);
}
// implementation of the Selector's area function
double Selector::area(double ghost_area) const{
if (! is_geometric()) throw InvalidArea();
// has area will already check we've got a valid worker
if (_worker->has_known_area()) return _worker->known_area();
// generate a set of "ghosts"
double rapmin, rapmax;
get_rapidity_extent(rapmin, rapmax);
GhostedAreaSpec ghost_spec(rapmin, rapmax, 1, ghost_area);
std::vector<PseudoJet> ghosts;
ghost_spec.add_ghosts(ghosts);
// check what passes the selection
return ghost_spec.ghost_area() * ((*this)(ghosts)).size();
}
#endif // __FJCORE__
//----------------------------------------------------------------------
// implementations of some of the more complex bits of SelectorWorker
//----------------------------------------------------------------------
// check if it has a finite area
bool SelectorWorker::has_finite_area() const {
if (! is_geometric()) return false;
double rapmin, rapmax;
get_rapidity_extent(rapmin, rapmax);
return (rapmax != std::numeric_limits<double>::infinity())
&& (-rapmin != std::numeric_limits<double>::infinity());
}
//----------------------------------------------------------------------
// very basic set of selectors (at the moment just the identity!)
//----------------------------------------------------------------------
//----------------------------------------------------------------------
/// helper for selecting the n hardest jets
class SW_Identity : public SelectorWorker {
public:
/// ctor with specification of the number of objects to keep
SW_Identity(){}
/// just let everything pass
virtual bool pass(const PseudoJet &) const {
return true;
}
/// For each jet that does not pass the cuts, this routine sets the
/// pointer to 0.
virtual void terminator(vector<const PseudoJet *> &) const {
// everything passes, hence nothing to nullify
return;
}
/// returns a description of the worker
virtual string description() const { return "Identity";}
/// strictly speaking, this is geometric
virtual bool is_geometric() const { return true;}
};
// returns an "identity" selector that lets everything pass
Selector SelectorIdentity() {
return Selector(new SW_Identity);
}
//----------------------------------------------------------------------
// selector and workers for operators
//----------------------------------------------------------------------
//----------------------------------------------------------------------
/// helper for combining selectors with a logical not
class SW_Not : public SelectorWorker {
public:
/// ctor
SW_Not(const Selector & s) : _s(s) {}
/// return a copy of the current object
virtual SelectorWorker* copy(){ return new SW_Not(*this);}
/// returns true if a given object passes the selection criterium
/// this has to be overloaded by derived workers
virtual bool pass(const PseudoJet & jet) const {
// make sure that the "pass" can be applied on both selectors
if (!applies_jet_by_jet())
throw Error("Cannot apply this selector worker to an individual jet");
return ! _s.pass(jet);
}
/// returns true if this can be applied jet by jet
virtual bool applies_jet_by_jet() const {return _s.applies_jet_by_jet();}
/// select the jets in the list that pass both selectors
virtual void terminator(vector<const PseudoJet *> & jets) const {
// if we can apply the selector jet-by-jet, call the base selector
// that does exactly that
if (applies_jet_by_jet()){
SelectorWorker::terminator(jets);
return;
}
// check the effect of the selector we want to negate
vector<const PseudoJet *> s_jets = jets;
_s.worker()->terminator(s_jets);
// now apply the negation: all the jets that pass the base
// selector (i.e. are not NULL) have to be set to NULL
for (unsigned int i=0; i<s_jets.size(); i++){
if (s_jets[i]) jets[i] = NULL;
}
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << "!(" << _s.description() << ")";
return ostr.str();
}
/// is geometric if the underlying selector is
virtual bool is_geometric() const { return _s.is_geometric();}
/// returns true if the worker can be set_referenced
virtual bool takes_reference() const { return _s.takes_reference();}
/// set the reference jet for this selector
virtual void set_reference(const PseudoJet &ref) { _s.set_reference(ref);}
protected:
Selector _s;
};
// logical not applied on a selector
Selector operator!(const Selector & s) {
return Selector(new SW_Not(s));
}
//----------------------------------------------------------------------
/// Base class for binary operators
class SW_BinaryOperator: public SelectorWorker {
public:
/// ctor
SW_BinaryOperator(const Selector & s1, const Selector & s2) : _s1(s1), _s2(s2) {
// stores info for more efficient access to the selector's properties
// we can apply jet by jet only if this is the case for both sub-selectors
_applies_jet_by_jet = _s1.applies_jet_by_jet() && _s2.applies_jet_by_jet();
// the selector takes a reference if either of the sub-selectors does
_takes_reference = _s1.takes_reference() || _s2.takes_reference();
// we have a well-defined area provided the two objects have one
_is_geometric = _s1.is_geometric() && _s2.is_geometric();
}
/// returns true if this can be applied jet by jet
virtual bool applies_jet_by_jet() const {return _applies_jet_by_jet;}
/// returns true if this takes a reference jet
virtual bool takes_reference() const{
return _takes_reference;
}
/// sets the reference jet
virtual void set_reference(const PseudoJet ¢re){
_s1.set_reference(centre);
_s2.set_reference(centre);
}
/// check if it has a finite area
virtual bool is_geometric() const { return _is_geometric;}
protected:
Selector _s1, _s2;
bool _applies_jet_by_jet;
bool _takes_reference;
bool _is_geometric;
};
//----------------------------------------------------------------------
/// helper for combining selectors with a logical and
class SW_And: public SW_BinaryOperator {
public:
/// ctor
SW_And(const Selector & s1, const Selector & s2) : SW_BinaryOperator(s1,s2){}
/// return a copy of this
virtual SelectorWorker* copy(){ return new SW_And(*this);}
/// returns true if a given object passes the selection criterium
/// this has to be overloaded by derived workers
virtual bool pass(const PseudoJet & jet) const {
// make sure that the "pass" can be applied on both selectors
if (!applies_jet_by_jet())
throw Error("Cannot apply this selector worker to an individual jet");
return _s1.pass(jet) && _s2.pass(jet);
}
/// select the jets in the list that pass both selectors
virtual void terminator(vector<const PseudoJet *> & jets) const {
// if we can apply the selector jet-by-jet, call the base selector
// that does exactly that
if (applies_jet_by_jet()){
SelectorWorker::terminator(jets);
return;
}
// check the effect of the first selector
vector<const PseudoJet *> s1_jets = jets;
_s1.worker()->terminator(s1_jets);
// apply the second
_s2.worker()->terminator(jets);
// terminate the jets that wiuld be terminated by _s1
for (unsigned int i=0; i<jets.size(); i++){
if (! s1_jets[i]) jets[i] = NULL;
}
}
/// returns the rapidity range for which it may return "true"
virtual void get_rapidity_extent(double & rapmin, double & rapmax) const {
double s1min, s1max, s2min, s2max;
_s1.get_rapidity_extent(s1min, s1max);
_s2.get_rapidity_extent(s2min, s2max);
rapmax = min(s1max, s2max);
rapmin = max(s1min, s2min);
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << "(" << _s1.description() << " && " << _s2.description() << ")";
return ostr.str();
}
};
// logical and between two selectors
Selector operator&&(const Selector & s1, const Selector & s2) {
return Selector(new SW_And(s1,s2));
}
//----------------------------------------------------------------------
/// helper for combining selectors with a logical or
class SW_Or: public SW_BinaryOperator {
public:
/// ctor
SW_Or(const Selector & s1, const Selector & s2) : SW_BinaryOperator(s1,s2) {}
/// return a copy of this
virtual SelectorWorker* copy(){ return new SW_Or(*this);}
/// returns true if a given object passes the selection criterium
/// this has to be overloaded by derived workers
virtual bool pass(const PseudoJet & jet) const {
// make sure that the "pass" can be applied on both selectors
if (!applies_jet_by_jet())
throw Error("Cannot apply this selector worker to an individual jet");
return _s1.pass(jet) || _s2.pass(jet);
}
/// returns true if this can be applied jet by jet
virtual bool applies_jet_by_jet() const {
// watch out, even though it's the "OR" selector, to be applied jet
// by jet, both the base selectors need to be jet-by-jet-applicable,
// so the use of a && in the line below
return _s1.applies_jet_by_jet() && _s2.applies_jet_by_jet();
}
/// select the jets in the list that pass both selectors
virtual void terminator(vector<const PseudoJet *> & jets) const {
// if we can apply the selector jet-by-jet, call the base selector
// that does exactly that
if (applies_jet_by_jet()){
SelectorWorker::terminator(jets);
return;
}
// check the effect of the first selector
vector<const PseudoJet *> s1_jets = jets;
_s1.worker()->terminator(s1_jets);
// apply the second
_s2.worker()->terminator(jets);
// resurrect any jet that has been terminated by the second one
// and not by the first one
for (unsigned int i=0; i<jets.size(); i++){
if (s1_jets[i]) jets[i] = s1_jets[i];
}
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << "(" << _s1.description() << " || " << _s2.description() << ")";
return ostr.str();
}
/// returns the rapidity range for which it may return "true"
virtual void get_rapidity_extent(double & rapmin, double & rapmax) const {
double s1min, s1max, s2min, s2max;
_s1.get_rapidity_extent(s1min, s1max);
_s2.get_rapidity_extent(s2min, s2max);
rapmax = max(s1max, s2max);
rapmin = min(s1min, s2min);
}
};
// logical or between two selectors
Selector operator ||(const Selector & s1, const Selector & s2) {
return Selector(new SW_Or(s1,s2));
}
//----------------------------------------------------------------------
/// helper for multiplying two selectors (in an operator-like way)
class SW_Mult: public SW_And {
public:
/// ctor
SW_Mult(const Selector & s1, const Selector & s2) : SW_And(s1,s2) {}
/// return a copy of this
virtual SelectorWorker* copy(){ return new SW_Mult(*this);}
/// select the jets in the list that pass both selectors
virtual void terminator(vector<const PseudoJet *> & jets) const {
// if we can apply the selector jet-by-jet, call the base selector
// that does exactly that
if (applies_jet_by_jet()){
SelectorWorker::terminator(jets);
return;
}
// first apply _s2
_s2.worker()->terminator(jets);
// then apply _s1
_s1.worker()->terminator(jets);
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << "(" << _s1.description() << " * " << _s2.description() << ")";
return ostr.str();
}
};
// logical and between two selectors
Selector operator*(const Selector & s1, const Selector & s2) {
return Selector(new SW_Mult(s1,s2));
}
//----------------------------------------------------------------------
// selector and workers for kinematic cuts
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// a series of basic classes that allow easy implementations of
// min, max and ranges on a quantity-to-be-defined
// generic holder for a quantity
class QuantityBase{
public:
QuantityBase(double q) : _q(q){}
virtual ~QuantityBase(){}
virtual double operator()(const PseudoJet & jet ) const =0;
virtual string description() const =0;
virtual bool is_geometric() const { return false;}
virtual double comparison_value() const {return _q;}
virtual double description_value() const {return comparison_value();}
protected:
double _q;
};
// generic holder for a squared quantity
class QuantitySquareBase : public QuantityBase{
public:
QuantitySquareBase(double sqrtq) : QuantityBase(sqrtq*sqrtq), _sqrtq(sqrtq){}
virtual double description_value() const {return _sqrtq;}
protected:
double _sqrtq;
};
// generic_quantity >= minimum
template<typename QuantityType>
class SW_QuantityMin : public SelectorWorker{
public:
/// detfault ctor (initialises the pt cut)
SW_QuantityMin(double qmin) : _qmin(qmin) {}
/// returns true is the given object passes the selection pt cut
virtual bool pass(const PseudoJet & jet) const {return _qmin(jet) >= _qmin.comparison_value();}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << _qmin.description() << " >= " << _qmin.description_value();
return ostr.str();
}
virtual bool is_geometric() const { return _qmin.is_geometric();}
protected:
QuantityType _qmin; ///< the cut
};
// generic_quantity <= maximum
template<typename QuantityType>
class SW_QuantityMax : public SelectorWorker {
public:
/// detfault ctor (initialises the pt cut)
SW_QuantityMax(double qmax) : _qmax(qmax) {}
/// returns true is the given object passes the selection pt cut
virtual bool pass(const PseudoJet & jet) const {return _qmax(jet) <= _qmax.comparison_value();}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << _qmax.description() << " <= " << _qmax.description_value();
return ostr.str();
}
virtual bool is_geometric() const { return _qmax.is_geometric();}
protected:
QuantityType _qmax; ///< the cut
};
// generic quantity in [minimum:maximum]
template<typename QuantityType>
class SW_QuantityRange : public SelectorWorker {
public:
/// detfault ctor (initialises the pt cut)
SW_QuantityRange(double qmin, double qmax) : _qmin(qmin), _qmax(qmax) {}
/// returns true is the given object passes the selection pt cut
virtual bool pass(const PseudoJet & jet) const {
double q = _qmin(jet); // we could identically use _qmax
return (q >= _qmin.comparison_value()) && (q <= _qmax.comparison_value());
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << _qmin.description_value() << " <= " << _qmin.description() << " <= " << _qmax.description_value();
return ostr.str();
}
virtual bool is_geometric() const { return _qmin.is_geometric();}
protected:
QuantityType _qmin; // the lower cut
QuantityType _qmax; // the upper cut
};
//----------------------------------------------------------------------
/// helper class for selecting on pt
class QuantityPt2 : public QuantitySquareBase{
public:
QuantityPt2(double pt) : QuantitySquareBase(pt){}
virtual double operator()(const PseudoJet & jet ) const { return jet.perp2();}
virtual string description() const {return "pt";}
};
// returns a selector for a minimum pt
Selector SelectorPtMin(double ptmin) {
return Selector(new SW_QuantityMin<QuantityPt2>(ptmin));
}
// returns a selector for a maximum pt
Selector SelectorPtMax(double ptmax) {
return Selector(new SW_QuantityMax<QuantityPt2>(ptmax));
}
// returns a selector for a pt range
Selector SelectorPtRange(double ptmin, double ptmax) {
return Selector(new SW_QuantityRange<QuantityPt2>(ptmin, ptmax));
}
//----------------------------------------------------------------------
/// helper class for selecting on transverse energy
class QuantityEt2 : public QuantitySquareBase{
public:
QuantityEt2(double Et) : QuantitySquareBase(Et){}
virtual double operator()(const PseudoJet & jet ) const { return jet.Et2();}
virtual string description() const {return "Et";}
};
// returns a selector for a minimum Et
Selector SelectorEtMin(double Etmin) {
return Selector(new SW_QuantityMin<QuantityEt2>(Etmin));
}
// returns a selector for a maximum Et
Selector SelectorEtMax(double Etmax) {
return Selector(new SW_QuantityMax<QuantityEt2>(Etmax));
}
// returns a selector for a Et range
Selector SelectorEtRange(double Etmin, double Etmax) {
return Selector(new SW_QuantityRange<QuantityEt2>(Etmin, Etmax));
}
//----------------------------------------------------------------------
/// helper class for selecting on energy
class QuantityE : public QuantityBase{
public:
QuantityE(double E) : QuantityBase(E){}
virtual double operator()(const PseudoJet & jet ) const { return jet.E();}
virtual string description() const {return "E";}
};
// returns a selector for a minimum E
Selector SelectorEMin(double Emin) {
return Selector(new SW_QuantityMin<QuantityE>(Emin));
}
// returns a selector for a maximum E
Selector SelectorEMax(double Emax) {
return Selector(new SW_QuantityMax<QuantityE>(Emax));
}
// returns a selector for a E range
Selector SelectorERange(double Emin, double Emax) {
return Selector(new SW_QuantityRange<QuantityE>(Emin, Emax));
}
//----------------------------------------------------------------------
/// helper class for selecting on mass
class QuantityM2 : public QuantitySquareBase{
public:
QuantityM2(double m) : QuantitySquareBase(m){}
virtual double operator()(const PseudoJet & jet ) const { return jet.m2();}
virtual string description() const {return "mass";}
};
// returns a selector for a minimum mass
Selector SelectorMassMin(double mmin) {
return Selector(new SW_QuantityMin<QuantityM2>(mmin));
}
// returns a selector for a maximum mass
Selector SelectorMassMax(double mmax) {
return Selector(new SW_QuantityMax<QuantityM2>(mmax));
}
// returns a selector for a mass range
Selector SelectorMassRange(double mmin, double mmax) {
return Selector(new SW_QuantityRange<QuantityM2>(mmin, mmax));
}
//----------------------------------------------------------------------
/// helper for selecting on rapidities: quantity
class QuantityRap : public QuantityBase{
public:
QuantityRap(double rap) : QuantityBase(rap){}
virtual double operator()(const PseudoJet & jet ) const { return jet.rap();}
virtual string description() const {return "rap";}
virtual bool is_geometric() const { return true;}
};
/// helper for selecting on rapidities: min
class SW_RapMin : public SW_QuantityMin<QuantityRap>{
public:
SW_RapMin(double rapmin) : SW_QuantityMin<QuantityRap>(rapmin){}
virtual void get_rapidity_extent(double &rapmin, double & rapmax) const{
rapmax = std::numeric_limits<double>::max();
rapmin = _qmin.comparison_value();
}
};
/// helper for selecting on rapidities: max
class SW_RapMax : public SW_QuantityMax<QuantityRap>{
public:
SW_RapMax(double rapmax) : SW_QuantityMax<QuantityRap>(rapmax){}
virtual void get_rapidity_extent(double &rapmin, double & rapmax) const{
rapmax = _qmax.comparison_value();
rapmin = -std::numeric_limits<double>::max();
}
};
/// helper for selecting on rapidities: range
class SW_RapRange : public SW_QuantityRange<QuantityRap>{
public:
SW_RapRange(double rapmin, double rapmax) : SW_QuantityRange<QuantityRap>(rapmin, rapmax){
assert(rapmin<=rapmax);
}
virtual void get_rapidity_extent(double &rapmin, double & rapmax) const{
rapmax = _qmax.comparison_value();
rapmin = _qmin.comparison_value();
}
virtual bool has_known_area() const { return true;} ///< the area is analytically known
virtual double known_area() const {
return twopi * (_qmax.comparison_value()-_qmin.comparison_value());
}
};
// returns a selector for a minimum rapidity
Selector SelectorRapMin(double rapmin) {
return Selector(new SW_RapMin(rapmin));
}
// returns a selector for a maximum rapidity
Selector SelectorRapMax(double rapmax) {
return Selector(new SW_RapMax(rapmax));
}
// returns a selector for a rapidity range
Selector SelectorRapRange(double rapmin, double rapmax) {
return Selector(new SW_RapRange(rapmin, rapmax));
}
//----------------------------------------------------------------------
/// helper for selecting on |rapidities|
class QuantityAbsRap : public QuantityBase{
public:
QuantityAbsRap(double absrap) : QuantityBase(absrap){}
virtual double operator()(const PseudoJet & jet ) const { return abs(jet.rap());}
virtual string description() const {return "|rap|";}
virtual bool is_geometric() const { return true;}
};
/// helper for selecting on |rapidities|: max
class SW_AbsRapMax : public SW_QuantityMax<QuantityAbsRap>{
public:
SW_AbsRapMax(double absrapmax) : SW_QuantityMax<QuantityAbsRap>(absrapmax){}
virtual void get_rapidity_extent(double &rapmin, double & rapmax) const{
rapmax = _qmax.comparison_value();
rapmin = -_qmax.comparison_value();
}
virtual bool has_known_area() const { return true;} ///< the area is analytically known
virtual double known_area() const {
return twopi * 2 * _qmax.comparison_value();
}
};
/// helper for selecting on |rapidities|: max
class SW_AbsRapRange : public SW_QuantityRange<QuantityAbsRap>{
public:
SW_AbsRapRange(double absrapmin, double absrapmax) : SW_QuantityRange<QuantityAbsRap>(absrapmin, absrapmax){}
virtual void get_rapidity_extent(double &rapmin, double & rapmax) const{
rapmax = _qmax.comparison_value();
rapmin = -_qmax.comparison_value();
}
virtual bool has_known_area() const { return true;} ///< the area is analytically known
virtual double known_area() const {
return twopi * 2 * (_qmax.comparison_value()-max(_qmin.comparison_value(),0.0)); // this should handle properly absrapmin<0
}
};
// returns a selector for a minimum |rapidity|
Selector SelectorAbsRapMin(double absrapmin) {
return Selector(new SW_QuantityMin<QuantityAbsRap>(absrapmin));
}
// returns a selector for a maximum |rapidity|
Selector SelectorAbsRapMax(double absrapmax) {
return Selector(new SW_AbsRapMax(absrapmax));
}
// returns a selector for a |rapidity| range
Selector SelectorAbsRapRange(double rapmin, double rapmax) {
return Selector(new SW_AbsRapRange(rapmin, rapmax));
}
//----------------------------------------------------------------------
/// helper for selecting on pseudo-rapidities
class QuantityEta : public QuantityBase{
public:
QuantityEta(double eta) : QuantityBase(eta){}
virtual double operator()(const PseudoJet & jet ) const { return jet.eta();}
virtual string description() const {return "eta";}
// virtual bool is_geometric() const { return true;} // not strictly only y and phi-dependent
};
// returns a selector for a pseudo-minimum rapidity
Selector SelectorEtaMin(double etamin) {
return Selector(new SW_QuantityMin<QuantityEta>(etamin));
}
// returns a selector for a pseudo-maximum rapidity
Selector SelectorEtaMax(double etamax) {
return Selector(new SW_QuantityMax<QuantityEta>(etamax));
}
// returns a selector for a pseudo-rapidity range
Selector SelectorEtaRange(double etamin, double etamax) {
return Selector(new SW_QuantityRange<QuantityEta>(etamin, etamax));
}
//----------------------------------------------------------------------
/// helper for selecting on |pseudo-rapidities|
class QuantityAbsEta : public QuantityBase{
public:
QuantityAbsEta(double abseta) : QuantityBase(abseta){}
virtual double operator()(const PseudoJet & jet ) const { return abs(jet.eta());}
virtual string description() const {return "|eta|";}
virtual bool is_geometric() const { return true;}
};
// returns a selector for a minimum |pseudo-rapidity|
Selector SelectorAbsEtaMin(double absetamin) {
return Selector(new SW_QuantityMin<QuantityAbsEta>(absetamin));
}
// returns a selector for a maximum |pseudo-rapidity|
Selector SelectorAbsEtaMax(double absetamax) {
return Selector(new SW_QuantityMax<QuantityAbsEta>(absetamax));
}
// returns a selector for a |pseudo-rapidity| range
Selector SelectorAbsEtaRange(double absetamin, double absetamax) {
return Selector(new SW_QuantityRange<QuantityAbsEta>(absetamin, absetamax));
}
//----------------------------------------------------------------------
/// helper for selecting on azimuthal angle
///
/// Note that the bounds have to be specified as min<max
/// phimin has to be > -2pi
/// phimax has to be < 4pi
class SW_PhiRange : public SelectorWorker {
public:
/// detfault ctor (initialises the pt cut)
SW_PhiRange(double phimin, double phimax) : _phimin(phimin), _phimax(phimax){
assert(_phimin<_phimax);
assert(_phimin>-twopi);
assert(_phimax<2*twopi);
_phispan = _phimax - _phimin;
}
/// returns true is the given object passes the selection pt cut
virtual bool pass(const PseudoJet & jet) const {
double dphi=jet.phi()-_phimin;
if (dphi >= twopi) dphi -= twopi;
if (dphi < 0) dphi += twopi;
return (dphi <= _phispan);
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << _phimin << " <= phi <= " << _phimax;
return ostr.str();
}
virtual bool is_geometric() const { return true;}
protected:
double _phimin; // the lower cut
double _phimax; // the upper cut
double _phispan; // the span of the range
};
// returns a selector for a phi range
Selector SelectorPhiRange(double phimin, double phimax) {
return Selector(new SW_PhiRange(phimin, phimax));
}
//----------------------------------------------------------------------
/// helper for selecting on both rapidity and azimuthal angle
class SW_RapPhiRange : public SW_And{
public:
SW_RapPhiRange(double rapmin, double rapmax, double phimin, double phimax)
: SW_And(SelectorRapRange(rapmin, rapmax), SelectorPhiRange(phimin, phimax)){
_known_area = ((phimax-phimin > twopi) ? twopi : phimax-phimin) * (rapmax-rapmin);
}
/// if it has a computable area, return it
virtual double known_area() const{
return _known_area;
}
protected:
double _known_area;
};
Selector SelectorRapPhiRange(double rapmin, double rapmax, double phimin, double phimax) {
return Selector(new SW_RapPhiRange(rapmin, rapmax, phimin, phimax));
}
//----------------------------------------------------------------------
/// helper for selecting the n hardest jets
class SW_NHardest : public SelectorWorker {
public:
/// ctor with specification of the number of objects to keep
SW_NHardest(unsigned int n) : _n(n) {};
/// pass makes no sense here normally the parent selector will throw
/// an error but for internal use in the SW, we'll throw one from
/// here by security
virtual bool pass(const PseudoJet &) const {
if (!applies_jet_by_jet())
throw Error("Cannot apply this selector worker to an individual jet");
return false;
}
/// For each jet that does not pass the cuts, this routine sets the
/// pointer to 0.
virtual void terminator(vector<const PseudoJet *> & jets) const {
// nothing to do if the size is too small
if (jets.size() < _n) return;
// do we want to first chech if things are already ordered before
// going through the ordering process? For now, no. Maybe carry
// out timing tests at some point to establish the optimal
// strategy.
vector<double> minus_pt2(jets.size());
vector<unsigned int> indices(jets.size());
for (unsigned int i=0; i<jets.size(); i++){
indices[i] = i;
// we need to make sure that the object has not already been
// nullified. Note that if we have less than _n jets, this
// whole n-hardest selection will not have any effect.
minus_pt2[i] = jets[i] ? -jets[i]->perp2() : 0.0;
}
IndexedSortHelper sort_helper(& minus_pt2);
partial_sort(indices.begin(), indices.begin()+_n, indices.end(), sort_helper);
for (unsigned int i=_n; i<jets.size(); i++)
jets[indices[i]] = NULL;
}
/// returns true if this can be applied jet by jet
virtual bool applies_jet_by_jet() const {return false;}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << _n << " hardest";
return ostr.str();
}
protected:
unsigned int _n;
};
// returns a selector for the n hardest jets
Selector SelectorNHardest(unsigned int n) {
return Selector(new SW_NHardest(n));
}
//----------------------------------------------------------------------
// selector and workers for geometric ranges
//----------------------------------------------------------------------
//----------------------------------------------------------------------
/// a generic class for objects that contain a position
class SW_WithReference : public SelectorWorker{
public:
/// ctor
SW_WithReference() : _is_initialised(false){};
/// returns true if the worker takes a reference jet
virtual bool takes_reference() const { return true;}
/// sets the reference jet
virtual void set_reference(const PseudoJet ¢re){
_is_initialised = true;
_reference = centre;
}
protected:
PseudoJet _reference;
bool _is_initialised;
};
//----------------------------------------------------------------------
/// helper for selecting on objects within a distance 'radius' of a reference
class SW_Circle : public SW_WithReference {
public:
SW_Circle(const double &radius) : _radius2(radius*radius) {}
/// return a copy of the current object
virtual SelectorWorker* copy(){ return new SW_Circle(*this);}
/// returns true if a given object passes the selection criterium
/// this has to be overloaded by derived workers
virtual bool pass(const PseudoJet & jet) const {
// make sure the centre is initialised
if (! _is_initialised)
throw Error("To use a SelectorCircle (or any selector that requires a reference), you first have to call set_reference(...)");
return jet.squared_distance(_reference) <= _radius2;
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << "distance from the centre <= " << sqrt(_radius2);
return ostr.str();
}
/// returns the rapidity range for which it may return "true"
virtual void get_rapidity_extent(double & rapmin, double & rapmax) const{
// make sure the centre is initialised
if (! _is_initialised)
throw Error("To use a SelectorCircle (or any selector that requires a reference), you first have to call set_reference(...)");
rapmax = _reference.rap()+sqrt(_radius2);
rapmin = _reference.rap()-sqrt(_radius2);
}
virtual bool is_geometric() const { return true;} ///< implies a finite area
virtual bool has_finite_area() const { return true;} ///< regardless of the reference
virtual bool has_known_area() const { return true;} ///< the area is analytically known
virtual double known_area() const {
return pi * _radius2;
}
protected:
double _radius2;
};
// select on objets within a distance 'radius' of a variable location
Selector SelectorCircle(const double & radius) {
return Selector(new SW_Circle(radius));
}
//----------------------------------------------------------------------
/// helper for selecting on objects with a distance to a reference
/// betwene 'radius_in' and 'radius_out'
class SW_Doughnut : public SW_WithReference {
public:
SW_Doughnut(const double &radius_in, const double &radius_out)
: _radius_in2(radius_in*radius_in), _radius_out2(radius_out*radius_out) {}
/// return a copy of the current object
virtual SelectorWorker* copy(){ return new SW_Doughnut(*this);}
/// returns true if a given object passes the selection criterium
/// this has to be overloaded by derived workers
virtual bool pass(const PseudoJet & jet) const {
// make sure the centre is initialised
if (! _is_initialised)
throw Error("To use a SelectorDoughnut (or any selector that requires a reference), you first have to call set_reference(...)");
double distance2 = jet.squared_distance(_reference);
return (distance2 <= _radius_out2) && (distance2 >= _radius_in2);
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << sqrt(_radius_in2) << " <= distance from the centre <= " << sqrt(_radius_out2);
return ostr.str();
}
/// returns the rapidity range for which it may return "true"
virtual void get_rapidity_extent(double & rapmin, double & rapmax) const{
// make sure the centre is initialised
if (! _is_initialised)
throw Error("To use a SelectorDoughnut (or any selector that requires a reference), you first have to call set_reference(...)");
rapmax = _reference.rap()+sqrt(_radius_out2);
rapmin = _reference.rap()-sqrt(_radius_out2);
}
virtual bool is_geometric() const { return true;} ///< implies a finite area
virtual bool has_finite_area() const { return true;} ///< regardless of the reference
virtual bool has_known_area() const { return true;} ///< the area is analytically known
virtual double known_area() const {
return pi * (_radius_out2-_radius_in2);
}
protected:
double _radius_in2, _radius_out2;
};
// select on objets with distance from the centre is between 'radius_in' and 'radius_out'
Selector SelectorDoughnut(const double & radius_in, const double & radius_out) {
return Selector(new SW_Doughnut(radius_in, radius_out));
}
//----------------------------------------------------------------------
/// helper for selecting on objects with rapidity within a distance 'delta' of a reference
class SW_Strip : public SW_WithReference {
public:
SW_Strip(const double &delta) : _delta(delta) {}
/// return a copy of the current object
virtual SelectorWorker* copy(){ return new SW_Strip(*this);}
/// returns true if a given object passes the selection criterium
/// this has to be overloaded by derived workers
virtual bool pass(const PseudoJet & jet) const {
// make sure the centre is initialised
if (! _is_initialised)
throw Error("To use a SelectorStrip (or any selector that requires a reference), you first have to call set_reference(...)");
return abs(jet.rap()-_reference.rap()) <= _delta;
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << "|rap - rap_reference| <= " << _delta;
return ostr.str();
}
/// returns the rapidity range for which it may return "true"
virtual void get_rapidity_extent(double & rapmin, double & rapmax) const{
// make sure the centre is initialised
if (! _is_initialised)
throw Error("To use a SelectorStrip (or any selector that requires a reference), you first have to call set_reference(...)");
rapmax = _reference.rap()+_delta;
rapmin = _reference.rap()-_delta;
}
virtual bool is_geometric() const { return true;} ///< implies a finite area
virtual bool has_finite_area() const { return true;} ///< regardless of the reference
virtual bool has_known_area() const { return true;} ///< the area is analytically known
virtual double known_area() const {
return twopi * 2 * _delta;
}
protected:
double _delta;
};
// select on objets within a distance 'radius' of a variable location
Selector SelectorStrip(const double & half_width) {
return Selector(new SW_Strip(half_width));
}
//----------------------------------------------------------------------
/// helper for selecting on objects with rapidity within a distance
/// 'delta_rap' of a reference and phi within a distanve delta_phi of
/// a reference
class SW_Rectangle : public SW_WithReference {
public:
SW_Rectangle(const double &delta_rap, const double &delta_phi)
: _delta_rap(delta_rap), _delta_phi(delta_phi) {}
/// return a copy of the current object
virtual SelectorWorker* copy(){ return new SW_Rectangle(*this);}
/// returns true if a given object passes the selection criterium
/// this has to be overloaded by derived workers
virtual bool pass(const PseudoJet & jet) const {
// make sure the centre is initialised
if (! _is_initialised)
throw Error("To use a SelectorRectangle (or any selector that requires a reference), you first have to call set_reference(...)");
return (abs(jet.rap()-_reference.rap()) <= _delta_rap) && (abs(jet.delta_phi_to(_reference)) <= _delta_phi);
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << "|rap - rap_reference| <= " << _delta_rap << " && |phi - phi_reference| <= " << _delta_phi ;
return ostr.str();
}
/// returns the rapidity range for which it may return "true"
virtual void get_rapidity_extent(double & rapmin, double & rapmax) const{
// make sure the centre is initialised
if (! _is_initialised)
throw Error("To use a SelectorRectangle (or any selector that requires a reference), you first have to call set_reference(...)");
rapmax = _reference.rap()+_delta_rap;
rapmin = _reference.rap()-_delta_rap;
}
virtual bool is_geometric() const { return true;} ///< implies a finite area
virtual bool has_finite_area() const { return true;} ///< regardless of the reference
virtual bool has_known_area() const { return true;} ///< the area is analytically known
virtual double known_area() const {
return 4 * _delta_rap * _delta_phi;
}
protected:
double _delta_rap, _delta_phi;
};
// select on objets within a distance 'radius' of a variable location
Selector SelectorRectangle(const double & half_rap_width, const double & half_phi_width) {
return Selector(new SW_Rectangle(half_rap_width, half_phi_width));
}
//----------------------------------------------------------------------
/// helper for selecting the jets that carry at least a given fraction
/// of the reference jet
class SW_PtFractionMin : public SW_WithReference {
public:
/// ctor with specification of the number of objects to keep
SW_PtFractionMin(double fraction) : _fraction2(fraction*fraction){}
/// return a copy of the current object
virtual SelectorWorker* copy(){ return new SW_PtFractionMin(*this);}
/// return true if the jet carries a large enough fraction of the reference.
/// Throw an error if the reference is not initialised.
virtual bool pass(const PseudoJet & jet) const {
// make sure the centre is initialised
if (! _is_initialised)
throw Error("To use a SelectorPtFractionMin (or any selector that requires a reference), you first have to call set_reference(...)");
// otherwise, just call that method on the jet
return (jet.perp2() >= _fraction2*_reference.perp2());
}
/// returns a description of the worker
virtual string description() const {
ostringstream ostr;
ostr << "pt >= " << sqrt(_fraction2) << "* pt_ref";
return ostr.str();
}
protected:
double _fraction2;
};
// select objects that carry at least a fraction "fraction" of the reference jet
// (Note that this selectir takes a reference)
Selector SelectorPtFractionMin(double fraction){
return Selector(new SW_PtFractionMin(fraction));
}
//----------------------------------------------------------------------
// additional (mostly helper) selectors
//----------------------------------------------------------------------
//----------------------------------------------------------------------
/// helper for selecting the 0-momentum jets
class SW_IsZero : public SelectorWorker {
public:
/// ctor
SW_IsZero(){}
/// return true if the jet has zero momentum
virtual bool pass(const PseudoJet & jet) const {
return jet==0;
}
/// rereturns a description of the worker
virtual string description() const { return "zero";}
};
// select objects with zero momentum
Selector SelectorIsZero(){
return Selector(new SW_IsZero());
}
//----------------------------------------------------------------------
#ifndef __FJCORE__
/// helper for selecting the pure ghost
class SW_IsPureGhost : public SelectorWorker {
public:
/// ctor
SW_IsPureGhost(){}
/// return true if the jet is a pure-ghost jet
virtual bool pass(const PseudoJet & jet) const {
// if the jet has no area support then it's certainly not a ghost
if (!jet.has_area()) return false;
// otherwise, just call that method on the jet
return jet.is_pure_ghost();
}
/// rereturns a description of the worker
virtual string description() const { return "pure ghost";}
};
// select objects that are (or are only made of) ghosts
Selector SelectorIsPureGhost(){
return Selector(new SW_IsPureGhost());
}
//----------------------------------------------------------------------
// Selector and workers for obtaining a Selector from an old
// RangeDefinition
//
// This is mostly intended for backward compatibility and is likely to
// be removed in a future major release of FastJet
//----------------------------------------------------------------------
//----------------------------------------------------------------------
/// helper for selecting on both rapidity and azimuthal angle
class SW_RangeDefinition : public SelectorWorker{
public:
/// ctor from a RangeDefinition
SW_RangeDefinition(const RangeDefinition &range) : _range(&range){}
/// transfer the selection creterium to the underlying RangeDefinition
virtual bool pass(const PseudoJet & jet) const {
return _range->is_in_range(jet);
}
/// returns a description of the worker
virtual string description() const {
return _range->description();
}
/// returns the rapidity range for which it may return "true"
virtual void get_rapidity_extent(double & rapmin, double & rapmax) const{
_range->get_rap_limits(rapmin, rapmax);
}
/// check if it has a finite area
virtual bool is_geometric() const { return true;}
/// check if it has an analytically computable area
virtual bool has_known_area() const { return true;}
/// if it has a computable area, return it
virtual double known_area() const{
return _range->area();
}
protected:
const RangeDefinition *_range;
};
// ctor from a RangeDefinition
//----------------------------------------------------------------------
//
// This is provided for backward compatibility and will be removed in
// a future major release of FastJet
Selector::Selector(const RangeDefinition &range) {
_worker.reset(new SW_RangeDefinition(range));
}
#endif // __FJCORE__
// operators applying directly on a Selector
//----------------------------------------------------------------------
// operator &=
// For 2 Selectors a and b, a &= b is eauivalent to a = a & b;
Selector & Selector::operator &=(const Selector & b){
_worker.reset(new SW_And(*this, b));
return *this;
}
// operator &=
// For 2 Selectors a and b, a &= b is eauivalent to a = a & b;
Selector & Selector::operator |=(const Selector & b){
_worker.reset(new SW_Or(*this, b));
return *this;
}
FASTJET_END_NAMESPACE // defined in fastjet/internal/base.hh
| 33.302695 | 139 | 0.652265 | [
"object",
"vector"
] |
f8e2687b8ecea6599dadcfa9d4175de438e14615 | 6,305 | cpp | C++ | src/ir/daphneir/DaphneDistributableOpInterface.cpp | daphne-eu/daphne | 64d4040132cf4059efaf184c4e363dbb921c87d6 | [
"Apache-2.0"
] | 10 | 2022-03-31T21:49:35.000Z | 2022-03-31T23:37:06.000Z | src/ir/daphneir/DaphneDistributableOpInterface.cpp | daphne-eu/daphne | 64d4040132cf4059efaf184c4e363dbb921c87d6 | [
"Apache-2.0"
] | 3 | 2022-03-31T22:10:10.000Z | 2022-03-31T22:46:30.000Z | src/ir/daphneir/DaphneDistributableOpInterface.cpp | daphne-eu/daphne | 64d4040132cf4059efaf184c4e363dbb921c87d6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 The DAPHNE Consortium
*
* 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 <ir/daphneir/Daphne.h>
#include <string>
#include <vector>
#include <stdexcept>
namespace mlir::daphne
{
#include <ir/daphneir/DaphneDistributableOpInterface.cpp.inc>
}
using namespace mlir;
// ****************************************************************************
// DistributableOpInterface utilities
// ****************************************************************************
// For families of operations.
Type getWrappedType(Value v) {
// Get the type wrapped into this distributed handle.
Type wrappedType = v.getType().cast<daphne::HandleType>().getDataType();
// Remove all information on interesting properties except for the type.
// This is necessary since these properties do not necessarily hold for a
// distributed partition of the whole data object.
return wrappedType.dyn_cast<daphne::MatrixType>().withSameElementTypeAndRepr();
}
template<class EwBinaryOp>
std::vector<mlir::Value> createEquivalentDistributedDAG_EwBinaryOp(EwBinaryOp *op, mlir::OpBuilder &builder,
mlir::ValueRange distributedInputs)
{
auto loc = op->getLoc();
auto compute = builder.create<daphne::DistributedComputeOp>(loc,
ArrayRef<Type>{daphne::HandleType::get(op->getContext(), op->getType())},
distributedInputs);
auto &block = compute.body().emplaceBlock();
auto argLhs = block.addArgument(getWrappedType(distributedInputs[0]));
auto argRhs = block.addArgument(getWrappedType(distributedInputs[1]));
{
mlir::OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPoint(&block, block.begin());
mlir::Type resTyOrig = op->getType();
mlir::Type resTy = resTyOrig.dyn_cast<mlir::daphne::MatrixType>().withSameElementTypeAndRepr();
auto addOp = builder.create<EwBinaryOp>(loc, resTy, argLhs, argRhs);
builder.create<daphne::ReturnOp>(loc, ArrayRef<Value>{addOp});
}
std::vector<Value> ret({builder.create<daphne::DistributedCollectOp>(loc, compute.getResult(0))});
return ret;
}
template<class EwBinaryOp>
std::vector<bool> getOperandDistrPrimitives_EwBinaryOp(EwBinaryOp *op) {
Type tL0 = op->lhs().getType();
auto tL = tL0.dyn_cast<daphne::MatrixType>();
Type tR0 = op->rhs().getType();
auto tR = tR0.dyn_cast<daphne::MatrixType>();
const ssize_t nrL = tL.getNumRows();
const ssize_t ncL = tL.getNumCols();
const ssize_t nrR = tR.getNumRows();
const ssize_t ncR = tR.getNumCols();
if(nrL == -1 || nrR == -1 || ncL == -1 || ncR == -1)
throw std::runtime_error(
"unknown shapes of left and/or right operand to elementwise "
"binary operation are not supported while deciding "
"distribute/broadcast"
);
if(nrL == nrR && ncL == ncR) // matrix-matrix
return {false, false}; // distribute both inputs
else if(nrR == 1 && ncL == ncR) // matrix-row
return {false, true}; // distribute lhs, broadcast rhs
else if(nrL == nrR && ncR == 1) // matrix-col
return {false, true}; // distribute lhs, broadcast rhs
else
throw std::runtime_error(
"mismatching shapes of left and right operand to elementwise "
"binary operation while deciding distribute/broadcast"
);
}
// ****************************************************************************
// DistributableOpInterface implementations
// ****************************************************************************
#define IMPL_EWBINARYOP(OP) \
std::vector<mlir::Value> mlir::daphne::OP::createEquivalentDistributedDAG(mlir::OpBuilder &builder, \
mlir::ValueRange distributedInputs) \
{ \
return createEquivalentDistributedDAG_EwBinaryOp(this, builder, distributedInputs); \
} \
\
std::vector<bool> mlir::daphne::OP::getOperandDistrPrimitives() { \
return getOperandDistrPrimitives_EwBinaryOp(this); \
}
// TODO We should use traits (like for shape inference) so that we don't need
// to repeat here.
// Arithmetic
IMPL_EWBINARYOP(EwAddOp)
IMPL_EWBINARYOP(EwSubOp)
IMPL_EWBINARYOP(EwMulOp)
IMPL_EWBINARYOP(EwDivOp)
IMPL_EWBINARYOP(EwPowOp)
IMPL_EWBINARYOP(EwModOp)
IMPL_EWBINARYOP(EwLogOp)
// Min/max
IMPL_EWBINARYOP(EwMinOp)
IMPL_EWBINARYOP(EwMaxOp)
// Logical
IMPL_EWBINARYOP(EwAndOp)
IMPL_EWBINARYOP(EwOrOp)
IMPL_EWBINARYOP(EwXorOp)
// Strings
IMPL_EWBINARYOP(EwConcatOp)
// Comparisons
IMPL_EWBINARYOP(EwEqOp)
IMPL_EWBINARYOP(EwNeqOp)
IMPL_EWBINARYOP(EwLtOp)
IMPL_EWBINARYOP(EwLeOp)
IMPL_EWBINARYOP(EwGtOp)
IMPL_EWBINARYOP(EwGeOp)
std::vector<mlir::Value> daphne::RowAggMaxOp::createEquivalentDistributedDAG(
OpBuilder &builder, ValueRange distributedInputs
) {
auto loc = getLoc();
auto compute = builder.create<daphne::DistributedComputeOp>(loc,
ArrayRef<Type>{daphne::HandleType::get(getContext(), getType())},
distributedInputs);
auto &block = compute.body().emplaceBlock();
auto arg = block.addArgument(getWrappedType(distributedInputs[0]));
{
mlir::OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPoint(&block, block.begin());
mlir::Type resTy = getType().dyn_cast<mlir::daphne::MatrixType>().withSameElementTypeAndRepr();
auto aggOp = builder.create<RowAggMaxOp>(loc, resTy, arg);
builder.create<daphne::ReturnOp>(loc, ArrayRef<Value>{aggOp});
}
std::vector<Value> ret({builder.create<daphne::DistributedCollectOp>(loc, compute.getResult(0))});
return ret;
}
std::vector<bool> daphne::RowAggMaxOp::getOperandDistrPrimitives() {
return {false};
} | 36.445087 | 108 | 0.658525 | [
"object",
"shape",
"vector"
] |
25cd1b000e4017e323a024f79e8f50483b06c0a7 | 1,292 | hh | C++ | TEvtGen/EvtGen/EvtGenModels/EvtGenericDalitz.hh | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TEvtGen/EvtGen/EvtGenModels/EvtGenericDalitz.hh | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TEvtGen/EvtGen/EvtGenModels/EvtGenericDalitz.hh | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | //--------------------------------------------------------------------------
//
// Environment:
// This software is part of the EvtGen package developed jointly
// for the BaBar and CLEO collaborations. If you use all or part
// of it, please give an appropriate acknowledgement.
//
// Copyright Information: See EvtGen/COPYRIGHT
// Copyright (C) 1998 Caltech, UCSB
//
// Module: EvtGen/EvtGenericDalitz.hh
//
// Description: Model to describe a generic dalitz decay
//
// Modification history:
//
// DCC 16 December, 2011 Module created
//
//------------------------------------------------------------------------
#ifndef EVTGENERICDALITZ_HH
#define EVTGENERICDALITZ_HH
#include "EvtGenBase/EvtDecayAmp.hh"
#include "EvtGenBase/EvtFlatte.hh"
#include "EvtGenBase/EvtDalitzReso.hh"
#include <string>
#include <vector>
class EvtParticle;
class EvtGenericDalitz:public EvtDecayAmp {
public:
EvtGenericDalitz() {}
virtual ~EvtGenericDalitz() {}
std::string getName();
EvtDecayBase* clone();
void init();
void initProbMax() {};//prob max will be set in init
void decay(EvtParticle *p);
std::string getParamName(int i);
private:
int _d1,_d2,_d3;
std::vector<std::pair<EvtComplex,EvtDalitzReso> > _resonances;
};
#endif
| 23.071429 | 76 | 0.622291 | [
"vector",
"model"
] |
25db2e6382d1e1fc46923d01e3d43b049f5f853d | 1,094 | cpp | C++ | src/nodes/GeoIntersectsNode.cpp | niniemann/sempr | 2f3b04c031d70b9675ad441f97728a8fb839abed | [
"BSD-3-Clause"
] | 8 | 2018-03-28T19:45:47.000Z | 2022-03-23T16:53:24.000Z | src/nodes/GeoIntersectsNode.cpp | niniemann/sempr | 2f3b04c031d70b9675ad441f97728a8fb839abed | [
"BSD-3-Clause"
] | 58 | 2018-01-31T11:10:04.000Z | 2021-08-13T11:48:31.000Z | src/nodes/GeoIntersectsNode.cpp | niniemann/sempr | 2f3b04c031d70b9675ad441f97728a8fb839abed | [
"BSD-3-Clause"
] | 1 | 2018-07-04T12:30:06.000Z | 2018-07-04T12:30:06.000Z | #include "nodes/GeoIntersectsNode.hpp"
#include <rete-core/TupleWME.hpp>
namespace sempr {
GeoIntersectsNode::GeoIntersectsNode(
rete::PersistentInterpretation<GeosGeometryInterface::Ptr> geo1,
rete::PersistentInterpretation<GeosGeometryInterface::Ptr> geo2)
:
rete::Builtin("geo:intersects"),
geo1_(std::move(geo1)),
geo2_(std::move(geo2))
{
}
rete::WME::Ptr GeoIntersectsNode::process(rete::Token::Ptr token)
{
GeosGeometryInterface::Ptr g1, g2;
geo1_.interpretation->getValue(token, g1);
geo2_.interpretation->getValue(token, g2);
if (!g1->geometry() || !g2->geometry()) return nullptr;
bool ok = g1->geometry()->intersects(g2->geometry());
if (ok)
return std::make_shared<rete::EmptyWME>();
else
return nullptr;
}
bool GeoIntersectsNode::operator==(const rete::BetaNode& other) const
{
auto o = dynamic_cast<const GeoIntersectsNode*>(&other);
if (!o) return false;
return *(o->geo1_.accessor) == *(this->geo1_.accessor) &&
*(o->geo2_.accessor) == *(this->geo2_.accessor);
}
}
| 24.863636 | 69 | 0.664534 | [
"geometry"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.