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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08f8847df9b3ec5badb627ff05eed98347a648ec | 10,256 | cpp | C++ | pvdn/detection/utils/image_operations.cpp | larsOhne/pvdn | 0b6a8d0463909009152973f2edddbe49a054d4a2 | [
"CC0-1.0"
] | 13 | 2021-01-02T06:08:01.000Z | 2021-12-15T17:23:19.000Z | pvdn/detection/utils/image_operations.cpp | larsOhne/pvdn | 0b6a8d0463909009152973f2edddbe49a054d4a2 | [
"CC0-1.0"
] | 2 | 2021-01-28T07:53:28.000Z | 2021-07-29T15:50:40.000Z | pvdn/detection/utils/image_operations.cpp | larsOhne/pvdn | 0b6a8d0463909009152973f2edddbe49a054d4a2 | [
"CC0-1.0"
] | 1 | 2021-02-11T10:58:39.000Z | 2021-02-11T10:58:39.000Z | //#include "python3.8/Python.h"
#include "python2.7/Python.h"
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
#include <vector>
#include "HeadLampObject.h"
#include <numeric>
// using namespace std;
extern "C"
{
int min (int a, int b)
{
int result;
if (a < b)
{
result = a;
}
else
{
result = b;
}
return result;
}
int max (int a, int b)
{
int result;
if (a > b)
{
result = a;
}
else
{
result = b;
}
return result;
}
int bin_img_at(uint8_t *img, int x, int y, int height, int width)
{
int index = y * width + x;
return img[index];
}
float img_at(float *img, int x, int y, int height, int width)
{
int index = y * width + x;
return img[index];
}
float ii_at(float *img, int x, int y, int height, int width)
{
int index = y * width + x;
return img[index];
}
double threshold (float *img, float *ii, int x, int y, int h, int w, double k, int window, float eps)
{
int xmin = std::max(0, x - window / 2);
int ymin = std::max(0, y - window / 2);
int xmax = std::min(w-1, x + window / 2);
int ymax = std::min(h-1, y + window / 2);
int area = (xmax - xmin) * (ymax - ymin);
double m;
m = (double)ii_at(ii, xmin, ymin, h, w);
m = m + (double)ii_at(ii, xmax, ymax, h, w);
m = m - (double)ii_at(ii, xmax, ymin, h, w);
m = m - (double)ii_at(ii, xmin, ymax, h, w);
m = m / (double)area;
// local deviation
double delta = img_at(img, x, y, h, w) - m;
// dynamic threshold + small number for numerial stability
double t = m * (1. + k * (1.0 - delta / (1.0 - delta + eps)));
return t;
}
void binarize (float *img, uint8_t *bin_img, float *ii, int h, int w, int window, float k, float eps)
{
int x = 0;
int y = 0;
int i = 0;
// iterate over all pixels in image
for (y = 0; y < h; y++)
{
for (x = 0; x < w; x++)
{
bin_img[y*w + x] = (uint8_t)((double)(img_at(img, x, y, h, w)) > threshold(img, ii, x, y, h, w, (double)k, window, eps));
}
}
}
std::vector<int> sort_indexes(std::vector<int> &v) {
// initialize original index locations
std::vector<int> idx(v.size());
std::iota(idx.begin(), idx.end(), 0);
// sort indexes based on comparing values in v
// using std::stable_sort instead of std::sort
// to avoid unnecessary index re-orderings
// when v contains elements of equal values
stable_sort(idx.begin(), idx.end(),
[&v](int i1, int i2) {return v[i1] < v[i2];});
return idx;
}
std::vector<int> filter_idxs(int *bb1, std::vector<int> bb_list_orig, std::vector<int> idxs, int last, std::vector<int> area, double overlap_thresh)
{
int i = 0;
int offset = 0;
int h;
int w;
double overlap;
int xx1, yy1, xx2, yy2;
std::vector<int> swap_idxs;
std::vector<int> erase_idxs = {last};
for (i = 0; i < last; i++)
{
offset = i * 4;
xx1 = std::max(bb1[0], bb_list_orig.at(idxs.at(i)*4+0));
yy1 = std::max(bb1[1], bb_list_orig.at(idxs.at(i)*4+1));
xx2 = std::min(bb1[2], bb_list_orig.at(idxs.at(i)*4+2));
yy2 = std::min(bb1[3], bb_list_orig.at(idxs.at(i)*4+3));
h = std::max(0, xx2 - xx1 + 1);
w = std::max(0, yy2 - yy1 + 1);
overlap = (double)(w * h) / (double)area.at(idxs.at(i));
if (overlap <= overlap_thresh)
{
swap_idxs.push_back(idxs.at(i));
}
else{
erase_idxs.push_back(i);
}
}
return swap_idxs;
}
std::vector<HeadLampObject*> non_maximum_supression(std::vector<HeadLampObject*> bbs, int length, double overlap_thresh)
{
std::vector<int> bboxes(length*4);
std::vector<int> area(length);
std::vector<int> y2(length);
// convert HeadLampObjects to bounding boxes
// also compute the area of each bounding box
int i = 0;
int offset = 0;
for (i = 0; i < length; i++)
{
int *bb = bbs.at(i)->bbox();
offset = i * 4;
bboxes.at(offset+0) = bb[0];
bboxes.at(offset+1) = bb[1];
bboxes.at(offset+2) = bb[2];
bboxes.at(offset+3) = bb[3];
area.at(i) = (bb[2] - bb[0] + 1 ) * (bb[3] - bb[1] + 1);
y2.at(i) = bb[3];
}
i = 0;
// init list of picked indexes
std::vector<int> pick;
// sort bboxes by the bottom-right y-coordinate
std::vector<int> idxs;
idxs = sort_indexes(y2);
int h = 0;
int w = 0;
int bb[4];
int idx = 0;
while (idxs.size() > 0)
{
// grab the last index in the indexes list and add the
// index value to the list of picked indexes
int last = idxs.size() - 1;
idx = idxs.at(last);
pick.push_back(idx);
// find the largest (x, y) coordinates for the start of
// the bounding box and the smallest (x, y) coordinates
// for the end of the bounding box
bb[0] = bboxes.at(idx*4+0);
bb[1] = bboxes.at(idx*4+1);
bb[2] = bboxes.at(idx*4+2);
bb[3] = bboxes.at(idx*4+3);
idxs = filter_idxs(bb, bboxes, idxs, last, area, overlap_thresh);
}
std::vector<int> picked_bbs(pick.size()*4);
std::vector<HeadLampObject*> proposed(pick.size());
i = 0;
offset = 0;
idx = 0;
int xx1, yy1, xx2, yy2;
for (i = 0; i < pick.size(); i++)
{
idx = pick.at(i);
offset = idx * 4;
xx1 = bboxes.at(idx*4+0);
yy1 = bboxes.at(idx*4+1);
xx2 = bboxes.at(idx*4+2);
yy2 = bboxes.at(idx*4+3);
int bb[4] = {xx1, yy1, xx2, yy2};
HeadLampObject *hlo = new HeadLampObject();
hlo->from_bb(bb);
proposed.at(i) = hlo;
}
return proposed;
}
void find_proposals(int *final_proposals, uint8_t *bin_img, int h, int w, int padding, int nms_distance)
{
double overlap_thresh = 0.05; // TODO: make it parameter
int x = padding;
int y = padding;
int i;
bool match_found;
std::vector<HeadLampObject*> to_consider = {};
std::vector<HeadLampObject*> proposals = {};
// flood fill algorithm
for (y = padding; y < (h - padding); y++)
{
std::vector<HeadLampObject*> updated = {};
for (x = padding; x < (w - padding); x++)
{
if (bin_img_at(bin_img, x, y, h, w) == 1)
{
match_found = false;
i = 0;
for (i = 0; i < to_consider.size(); i++)
{
if (to_consider.at(i)->is_neighbor(x, y, nms_distance) == true)
{
match_found = true;
// add point to proposal
int *proposal_bb;
proposal_bb = to_consider.at(i)->bbox();
int xmin = std::min(proposal_bb[0], x);
int ymin = std::min(proposal_bb[1], y);
int xmax = std::max(proposal_bb[2], x + 1);
int ymax = std::max(proposal_bb[3], y + 1);
int new_bb[4] = {xmin, ymin, xmax, ymax};
to_consider.at(i)->from_bb(new_bb);
updated.push_back(to_consider.at(i));
// no need to look for more
break;
}
}
if (match_found == false)
{
// create new HeadLampObject with default height and width of 3
HeadLampObject *new_proposal = new HeadLampObject();
new_proposal->center_pos_x = x;
new_proposal->center_pos_y = y;
new_proposal->width = 3;
new_proposal->height = 3;
new_proposal->conf = 1;
proposals.push_back(new_proposal);
updated.push_back(new_proposal);
}
}
}
to_consider = updated;
}
// apply non maximum supression
std::vector<HeadLampObject*> picked;
std::vector<HeadLampObject*> filtered;
picked = non_maximum_supression(proposals, proposals.size(), overlap_thresh);
// filter out very small proposals
i = 0;
for (i = 0; i < picked.size(); i++)
{
if (picked.at(i)->width * picked.at(i)->height > 10)
{
if (picked.at(i)->width > 5)
{
picked.at(i)->source = 0;
filtered.push_back(picked.at(i));
}
}
}
// convert HeadLampObjects to bounding boxes
i = 0;
for (i = 0; i < filtered.size(); i++)
{
int *bb = filtered.at(i)->bbox();
final_proposals[i*4+0] = bb[0];
final_proposals[i*4+1] = bb[1];
final_proposals[i*4+2] = bb[2];
final_proposals[i*4+3] = bb[3];
}
// call destructor on all HeadLampObjects
i = 0;
for (i = 0; i < proposals.size(); i++)
{
if (i < picked.size())
{
delete[] picked.at(i);
}
delete[] proposals.at(i);
}
}
} | 29.813953 | 152 | 0.455831 | [
"vector"
] |
1c02362df5fad69a779a12c39018c0336a295a29 | 12,581 | cpp | C++ | Source/TitaniumKit/test/GlobalObjectTests.cpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 20 | 2015-04-02T06:55:30.000Z | 2022-03-29T04:27:30.000Z | Source/TitaniumKit/test/GlobalObjectTests.cpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 692 | 2015-04-01T21:05:49.000Z | 2020-03-10T10:11:57.000Z | Source/TitaniumKit/test/GlobalObjectTests.cpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 22 | 2015-04-01T20:57:51.000Z | 2022-01-18T17:33:15.000Z | /**
* TitaniumKit
*
* Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#include "Titanium/GlobalObject.hpp"
#include "NativeGlobalObjectExample.hpp"
#include "gtest/gtest.h"
#define XCTAssertEqual ASSERT_EQ
#define XCTAssertNotEqual ASSERT_NE
#define XCTAssertTrue ASSERT_TRUE
#define XCTAssertFalse ASSERT_FALSE
#define XCTAssertNoThrow ASSERT_NO_THROW
using namespace HAL;
class GlobalObjectTests : public testing::Test
{
protected:
virtual void SetUp()
{
}
virtual void TearDown()
{
}
JSContextGroup js_context_group;
};
TEST_F(GlobalObjectTests, basicFeatures)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
auto foo = js_context.CreateObject();
XCTAssertFalse(foo.HasProperty("bar"));
auto bar = js_context.CreateObject();
foo.SetProperty("bar", bar, {JSPropertyAttribute::ReadOnly, JSPropertyAttribute::DontDelete});
XCTAssertTrue(foo.HasProperty("bar"));
XCTAssertFalse(bar.HasProperty("baz"));
auto baz = js_context.CreateObject();
bar.SetProperty("baz", baz, {JSPropertyAttribute::ReadOnly, JSPropertyAttribute::DontDelete});
XCTAssertTrue(bar.HasProperty("baz"));
XCTAssertFalse(baz.HasProperty("number"));
baz.SetProperty("number", js_context.CreateNumber(42), {JSPropertyAttribute::DontDelete});
XCTAssertTrue(baz.HasProperty("number"));
XCTAssertFalse(global_object.HasProperty("foo"));
global_object.SetProperty("foo", foo, {JSPropertyAttribute::ReadOnly, JSPropertyAttribute::DontDelete});
XCTAssertTrue(global_object.HasProperty("foo"));
auto number = js_context.JSEvaluateScript("foo.bar.baz.number;");
XCTAssertEqual(42, static_cast<uint32_t>(number));
//std::clog << "MDL: number = " << number << std::endl;
number = js_context.JSEvaluateScript("foo.bar.baz.number = 24;");
XCTAssertEqual(24, static_cast<uint32_t>(number));
for (const auto& property_name : static_cast<std::vector<JSString>>(global_object.GetPropertyNames())) {
std::clog << "MDL: property_name = " << property_name << std::endl;
}
XCTAssertTrue(global_object.HasProperty("global"));
XCTAssertTrue(global_object.HasProperty("require"));
XCTAssertTrue(global_object.HasProperty("setTimeout"));
XCTAssertTrue(global_object.HasProperty("setInterval"));
XCTAssertTrue(global_object.HasProperty("clearInterval"));
XCTAssertTrue(global_object.HasProperty("clearTimeout"));
}
TEST_F(GlobalObjectTests, requireModuleExports_change_parent)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string hello_js = R"js(
module.exports = sayHello;
function sayHello(name) {
return 'Hello, ' + name;
}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello.js", hello_js);
JSValue result = js_context.JSEvaluateScript("var re = require; var hello = re('hello'); hello('World');");
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
result = js_context.JSEvaluateScript("var a = {}; a.require = require; var hello = a.require('hello'); hello('World');");
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
result = js_context.JSEvaluateScript("var a = this; var hello = a.require('hello'); hello('World');");
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
}
TEST_F(GlobalObjectTests, requireModuleExports)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var hello = require('hello');
hello('World');
)js";
std::string hello_js = R"js(
module.exports = sayHello;
function sayHello(name) {
return 'Hello, ' + name;
}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello.js", hello_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
}
TEST_F(GlobalObjectTests, requireExports)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var m = require('hello');
m.hello('World');
)js";
std::string hello_js = R"js(
exports.hello = sayHello;
function sayHello(name) {
return 'Hello, ' + name;
}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello.js", hello_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
}
TEST_F(GlobalObjectTests, requireFromCurrent)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var hello = require('./hello');
hello('World');
)js";
std::string hello_js = R"js(
module.exports = sayHello;
function sayHello(name) {
return 'Hello, ' + name;
}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("hello.js", hello_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
}
TEST_F(GlobalObjectTests, requireWithJS)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var hello = require('hello.js');
hello('World');
)js";
std::string hello_js = R"js(
module.exports = sayHello;
function sayHello(name) {
return 'Hello, ' + name;
}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello.js", hello_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
}
TEST_F(GlobalObjectTests, requireWithJSON)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var hello = require('hello');
hello.name
)js";
std::string hello_js = R"js(
{"name":"Hello, World"}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello.json", hello_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
}
TEST_F(GlobalObjectTests, requireWithIndexJSON)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var hello = require('hello');
hello.name
)js";
std::string hello_js = R"js(
{"name":"Hello, World"}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello/index.json", hello_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
}
TEST_F(GlobalObjectTests, requireFromDirectory)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var hello = require('hello');
hello('World');
)js";
std::string hello_js = R"js(
module.exports = sayHello;
function sayHello(name) {
return 'Hello, ' + name;
}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello/index.js", hello_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
}
TEST_F(GlobalObjectTests, requireFromPackageJSON)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var hello = require('hello');
hello('World');
)js";
std::string package_json = R"js(
{"main": "main.js"}
)js";
std::string hello_js = R"js(
module.exports = sayHello;
function sayHello(name) {
return 'Hello, ' + name;
}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello/package.json", package_json);
global_object_ptr->add_require("node_modules/hello/main.js", hello_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
}
TEST_F(GlobalObjectTests, requireDuplicateModules)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var hello1 = require('hello');
var hello2 = require('hello');
hello1('World1 ') + hello2('World2');
)js";
std::string hello_js = R"js(
module.exports = sayHello;
function sayHello(name) {
return 'Hello, ' + name;
}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello.js", hello_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World1 Hello, World2", static_cast<std::string>(result));
}
TEST_F(GlobalObjectTests, requireModuleCache)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var hello1 = require('hello');
var hello2 = require('hello');
(hello1 === hello2);
)js";
std::string hello_js = R"js(
module.exports = sayHello;
function sayHello(name) {
return 'Hello, ' + name;
}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello.js", hello_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsBoolean());
XCTAssertTrue(static_cast<bool>(result));
}
TEST_F(GlobalObjectTests, requireNestedModule)
{
JSContext js_context = js_context_group.CreateContext(JSExport<NativeGlobalObjectExample>::Class());
auto global_object = js_context.get_global_object();
std::string app_js = R"js(
var hello = require('m');
hello('World');
)js";
std::string module_js = R"js(
var hello = require('./hello');
module.exports = hello;
)js";
std::string hello_js = R"js(
module.exports = sayHello;
function sayHello(name) {
return 'Hello, ' + name;
}
)js";
auto global_object_ptr = global_object.GetPrivate<NativeGlobalObjectExample>();
XCTAssertNotEqual(nullptr, global_object_ptr);
global_object_ptr->add_require("node_modules/hello.js", hello_js);
global_object_ptr->add_require("node_modules/m.js", module_js);
JSValue result = js_context.JSEvaluateScript(app_js);
XCTAssertTrue(result.IsString());
XCTAssertEqual("Hello, World", static_cast<std::string>(result));
} | 30.536408 | 122 | 0.75614 | [
"vector"
] |
1c0c1ce9429800fb72e988c1776bed5d02235b85 | 9,248 | cpp | C++ | source/utils/CppUtils.cpp | Frangou-Lab/libgene | 28d11eea1489dd473f8376ff6475b53f12594fe6 | [
"Apache-2.0"
] | null | null | null | source/utils/CppUtils.cpp | Frangou-Lab/libgene | 28d11eea1489dd473f8376ff6475b53f12594fe6 | [
"Apache-2.0"
] | null | null | null | source/utils/CppUtils.cpp | Frangou-Lab/libgene | 28d11eea1489dd473f8376ff6475b53f12594fe6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Frangou Lab
*
* 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 <cassert>
#include <algorithm>
#include <locale>
#include <cctype>
#include "CppUtils.hpp"
#include "StringUtils.hpp"
#include "../file/sequence/FastaFile.hpp"
#include "../file/sequence/FastqFile.hpp"
#include "../file/TxtFile.hpp"
#include "../file/sequence/GenomicCsvFile.hpp"
#include "../file/sequence/GenomicTsvFile.hpp"
#include "../file/sequence/GenBankFile.hpp"
#include "../file/alignment/sam/SamFile.hpp"
#include "../file/alignment/bam/BamFile.hpp"
#include "../file/alignment/bed/BedFile.hpp"
#include "../def/Flags.hpp"
#include "../io/streams/PlainStringInputStream.hpp"
namespace gene::utils {
std::string
ConstructOutputNameWithFile(std::string inputFileName,
FileType type,
std::string outputFilePath,
const std::unique_ptr<CommandLineFlags>& flags,
std::string suffix)
{
if (!outputFilePath.empty()) {
if (suffix == "-split") {
std::string pathExtension = GetExtension(outputFilePath);
return StringByDeletingPathExtension(outputFilePath) + suffix + '.' + pathExtension;
} else {
return outputFilePath;
}
}
// Have to construct output, check out file type flag
if (flags->outputFormat() != FileType::Unknown)
type = flags->outputFormat();
return StringByDeletingPathExtension(inputFileName) + suffix + '.' + type2extension(type);
}
enum FileType str2type(const std::string &str)
{
if (str == "fasta")
return FileType::Fasta;
if (str.find("fastq") != std::string::npos || str == "fq")
return FileType::Fastq;
if (str.find("csv") != std::string::npos)
return FileType::Csv;
if (str.find("tsv") != std::string::npos)
return FileType::Tsv;
if (str == "gbk" || str == "gb")
return FileType::GenBank;
if (str == "sam")
return FileType::Sam;
if (str == "bam")
return FileType::Bam;
if (str == "bed")
return FileType::Bed;
if (str == "txt")
return FileType::PlainTxt;
return FileType::Unknown;
}
std::string type2str(enum FileType type)
{
switch (type) {
case FileType::Fasta:
return "fasta";
case FileType::Fastq:
return "fastq";
case FileType::Csv:
return "csv";
case FileType::Tsv:
return "tsv";
case FileType::Sam:
return "sam";
case FileType::Bam:
return "bam";
case FileType::Bed:
return "bed";
case FileType::PlainTxt:
return "txt";
case FileType::GenBank:
return "gbk";
case FileType::Unknown:
return "";
}
}
std::string type2extension(enum FileType type)
{
switch (type) {
case FileType::Fasta:
return FastaFile::defaultExtension();
case FileType::Fastq:
return FastqFile::defaultExtension();
case FileType::Csv:
return GenomicCsvFile::defaultExtension();
case FileType::Tsv:
return GenomicTsvFile::defaultExtension();
case FileType::GenBank:
return GenBankFile::defaultExtension();
case FileType::Sam:
return SamFile::defaultExtension();
case FileType::Bam:
return BamFile::defaultExtension();
case FileType::Bed:
return BedFile::defaultExtension();
case FileType::PlainTxt:
return TxtFile::defaultExtension();
default:
assert(false);
}
}
enum FileType extension2type(const std::string &ext)
{
if (Contains(FastaFile::extensions(), ext))
return FileType::Fasta;
if (Contains(FastqFile::extensions(), ext))
return FileType::Fastq;
if (Contains(GenomicCsvFile::extensions(), ext))
return FileType::Csv;
if (Contains(GenomicTsvFile::extensions(), ext))
return FileType::Tsv;
if (Contains(GenBankFile::extensions(), ext))
return FileType::GenBank;
if (Contains(SamFile::extensions(), ext))
return FileType::Sam;
if (Contains(BamFile::extensions(), ext))
return FileType::Bam;
if (Contains(BedFile::extensions(), ext))
return FileType::Bed;
if (Contains(TxtFile::extensions(), ext))
return FileType::PlainTxt;
return FileType::Unknown;
}
std::string str2extension(const std::string &str)
{
return type2extension(str2type(str));
}
std::string extension2str(const std::string &ext)
{
return type2str(extension2type(ext));
}
//
// Searches for a reverse string 'what' which is interpreted as a reverse
// complement without having to actually create this reverse complement
//
int64_t FindAsReverseComplement(const std::string& where,
const std::string& what)
{
const int64_t targetLength = where.size();
const int64_t adapterLength = what.size();
if (adapterLength > targetLength)
return std::string::npos;
int64_t j;
for (int64_t i = 0; i < targetLength - adapterLength; ++i) {
for (j = adapterLength - 1;
j >= 0 && AreComplements(where[i + (j - adapterLength - 1)],
what[j]); --j) {
;
}
if (j == 0) {
// Found a complete match starting from 'i'
return i;
}
}
return std::string::npos;
}
//
// Searches for a reverse string 'what' which is interpreted as a reverse
// complement without having to actually create this reverse complement
// starting from the end of 'where'
//
int64_t RfindAsReverseComplement(const std::string& where, const std::string& what)
{
const int64_t targetLength = where.size();
const int64_t adapterLength = what.size();
if (adapterLength > targetLength)
return std::string::npos;
for (int64_t i = targetLength - 1; i > adapterLength; --i) {
int64_t j;
for (j = adapterLength - 1; j >= 0; --j) {
if (!AreComplements(where[i - (j - adapterLength - 1)], what[j]))
break;
}
if (j == 0) {
// Found a complete match starting from 'i + adapterLength'
return i + adapterLength;
}
}
return std::string::npos;
}
bool AreComplements(char a, char b)
{
if (a == 'G')
return b == 'C';
if (a == 'C')
return b == 'G';
if (a == 'A')
return b == 'T' || b == 'U';
if (a == 'T')
return b == 'A';
if (a == 'U')
return b == 'A';
return false;
}
FastqVariant FormatNameToVariant(const std::string& format)
{
if (format.find(Flags::kIllumina1_8Suffix) != std::string::npos) {
return FastqVariant::Illumina1_8;
} else if (format.find(Flags::kIllumina1_5Suffix) != std::string::npos) {
return FastqVariant::Illumina1_5;
} else if (format.find(Flags::kIllumina1_3Suffix) != std::string::npos) {
return FastqVariant::Illumina1_3;
} else if (format.find(Flags::kSangerSuffix) != std::string::npos) {
return FastqVariant::Sanger;
} else if (format.find(Flags::kSolexaSuffix) != std::string::npos) {
return FastqVariant::Solexa;
} else {
assert(false);
}
}
std::string FastqVariantToSuffix(FastqVariant variant)
{
switch (variant) {
case FastqVariant::Illumina1_8:
return Flags::kIllumina1_8Suffix;
case FastqVariant::Illumina1_5:
return Flags::kIllumina1_5Suffix;
case FastqVariant::Illumina1_3:
return Flags::kIllumina1_3Suffix;
case FastqVariant::Sanger:
return Flags::kSangerSuffix;
case FastqVariant::Solexa:
return Flags::kSolexaSuffix;
}
}
std::vector<std::string> LoadQueriesFromFile(std::string path)
{
std::vector<std::string> queries;
PlainStringInputStream queries_file(path);
if (queries_file) {
std::string line;
while (!(line = queries_file.ReadLine()).empty()) {
int64_t spacePosition = line.find(' ');
int64_t nextSpace = line.find(' ', spacePosition + 1);
if (nextSpace != std::string::npos &&
nextSpace != (int64_t)line.size() - 1) {
spacePosition = nextSpace;
}
if (spacePosition != std::string::npos &&
spacePosition != 0 &&
spacePosition != (int64_t)line.size() - 1) {
line[spacePosition] = '&';
}
queries.push_back(line);
}
}
return queries;
}
}
| 29.832258 | 96 | 0.594831 | [
"vector"
] |
1c0e652fb8e369344a534cf213ec9c71caf73890 | 4,566 | cc | C++ | config/test/config-flags1/config-flags1.cc | Ubix/wanproxy | 76ca6cc15d8dd87f2bad7e56c935b8dfb765ae68 | [
"BSD-2-Clause"
] | 98 | 2015-01-07T14:31:54.000Z | 2022-03-19T16:38:56.000Z | config/test/config-flags1/config-flags1.cc | Ubix/wanproxy | 76ca6cc15d8dd87f2bad7e56c935b8dfb765ae68 | [
"BSD-2-Clause"
] | 23 | 2015-04-26T06:17:08.000Z | 2020-09-20T09:20:05.000Z | config/test/config-flags1/config-flags1.cc | Ubix/wanproxy | 76ca6cc15d8dd87f2bad7e56c935b8dfb765ae68 | [
"BSD-2-Clause"
] | 32 | 2015-01-04T01:15:05.000Z | 2021-11-13T22:47:41.000Z | /*
* Copyright (c) 2009-2013 Juli Mallett. 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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <common/test.h>
#include <config/config.h>
#include <config/config_class.h>
#include <config/config_type_flags.h>
#define FLAG_A (0x00000001)
#define FLAG_B (0x00000002)
#define FLAG_C (0x00000004)
typedef ConfigTypeFlags<unsigned int> TestConfigTypeFlags;
static struct TestConfigTypeFlags::Mapping test_config_type_flags_map[] = {
{ "A", FLAG_A },
{ "B", FLAG_B },
{ "C", FLAG_C },
{ NULL, 0 }
};
static TestConfigTypeFlags
test_config_type_flags("test-flags", test_config_type_flags_map);
#if 0
template<typename T, typename Ti>
int foo(T Ti::*f);
#endif
class TestConfigClassFlags : public ConfigClass {
struct Instance : public ConfigClassInstance {
unsigned int flags1_;
unsigned int flags2_;
unsigned int flags3_;
unsigned int flags4_;
Instance(void)
: flags1_(0),
flags2_(0),
flags3_(0),
flags4_(0)
{ }
bool activate(const ConfigObject *)
{
if (flags1_ != FLAG_A) {
ERROR("/test/config/flags/class") << "Field (flags1) does not have expected value.";
return (false);
}
if (flags2_ != (FLAG_A | FLAG_B | FLAG_C)) {
ERROR("/test/config/flags/class") << "Field (flags2) does not have expected value.";
return (false);
}
if (flags3_ != FLAG_C) {
ERROR("/test/config/flags/class") << "Field (flags3) does not have expected value.";
return (false);
}
if (flags4_ != 0) {
ERROR("/test/config/flags/class") << "Field (flags4) does not have expected value.";
return (false);
}
INFO("/test/config/flags/class") << "Got all expected values.";
return (true);
}
};
public:
TestConfigClassFlags(void)
: ConfigClass("test-config-flags", new ConstructorFactory<ConfigClassInstance, Instance>)
{
add_member("flags1", &test_config_type_flags, &Instance::flags1_);
add_member("flags2", &test_config_type_flags, &Instance::flags2_);
add_member("flags3", &test_config_type_flags, &Instance::flags3_);
add_member("flags4", &test_config_type_flags, &Instance::flags4_);
}
~TestConfigClassFlags()
{ }
};
int
main(void)
{
Config config;
TestConfigClassFlags test_config_class_flags;
config.import(&test_config_class_flags);
TestGroup g("/test/config/flags1", "ConfigTypeFlags #1");
{
Test _(g, "Create test object.");
if (config.create("test-config-flags", "test"))
_.pass();
}
{
Test _(g, "Fail to create duplicate test object.");
if (!config.create("test-config-flags", "test"))
_.pass();
}
{
Test _(g, "Set flags1.");
if (config.set("test", "flags1", "A"))
_.pass();
}
{
Test _(g, "Set flags2.");
if (config.set("test", "flags2", "B"))
_.pass();
}
{
Test _(g, "Premature activate test object.");
if (!config.activate("test"))
_.pass();
}
{
Test _(g, "Set flags3.");
if (config.set("test", "flags3", "C"))
_.pass();
}
{
Test _(g, "Premature activate test object again.");
if (!config.activate("test"))
_.pass();
}
{
Test _(g, "Correctly-set flags2. (Including duplicate B.)");
if (config.set("test", "flags2", "A") &&
config.set("test", "flags2", "B") &&
config.set("test", "flags2", "C"))
_.pass();
}
{
Test _(g, "Activate test object.");
if (config.activate("test"))
_.pass();
}
}
| 27.178571 | 90 | 0.681997 | [
"object"
] |
1c138506a3c7d6b2cd2bc5afaab4c64f6d65f44a | 4,176 | cpp | C++ | Source/DialogueBox.cpp | AramisHM/Irrahm-Studio | f1ceec1bfcd349facd98932c6485a25de3bd874f | [
"MIT"
] | null | null | null | Source/DialogueBox.cpp | AramisHM/Irrahm-Studio | f1ceec1bfcd349facd98932c6485a25de3bd874f | [
"MIT"
] | null | null | null | Source/DialogueBox.cpp | AramisHM/Irrahm-Studio | f1ceec1bfcd349facd98932c6485a25de3bd874f | [
"MIT"
] | null | null | null | /*
Irrahm Engine
Developer: Aramis Hornung Moraes
Dialogue.cpp - System's general definitions, variables and fuctions. Some windows/dialogue boxes build sets.
For more informations about the functions in this source file, go to "Dialogue.h".
*/
#include "video/irrlicht.h"
#include "namespaces.h"
#include "device.h"
#include "video.h"
#include "gui.h"
#include "simulations.h"
/* Dialogue boxes Edite Boxes. */
IGUIEditBox *px, /* Position X. */
*py, /* Position Y. */
*pz, /* Position Z. */
*pq,
*pcx,
*pcy,
*pcz,
*v0,
*ang; /* angle X. */
IGUIWindow *window[64]; /* A vector of windows that we reuse. */
stringw AboutText; /* Show a texte loaded from a XML on the "About" window. */
IGUIStaticText *InformationText; /* The right bottom debug text. */
void SplashBox()
{
window[0] = env->addWindow(rect<s32>(resolution.Width/2 - 310, resolution.Height/2 - 129, resolution.Width/2 - 313 + 630, resolution.Height/2 - 120 + 360), false, L"");
device->getGUIEnvironment()->addImage(driver->getTexture("./data/splash.png"), core::position2d<s32>(0,20), -1, window[0]);
device->getGUIEnvironment()->addStaticText(L"Irrahm Engine version 1.1\nHornung Moraes, Aramis", rect<s32>(216, 320, 413, 359), false, true, window[0]);
}
void AboutBox()
{
IGUIWindow *about_window = device->getGUIEnvironment()->addMessageBox(L"Sobre", AboutText.c_str());
device->getGUIEnvironment()->addImage(driver->getTexture("./data/Mr.Aramis.PNG"), core::position2d<s32>(20,200), -1, about_window);
}
void ToolsBoxE()
{
window[1] = env->addWindow(rect<s32>(0, 54, 300, 560), false, L"Eletromagnetismo");
env->addButton(rect<s32>(10,30,40,50), window[1], GUI_ID_FORCE_1, L"E1", L"Adicionar campo de forca.");
env->addButton(rect<s32>(50,30,80,50), window[1], GUI_ID_FORCE_2, L"E2", L"Adicionar campo de forca.");
env->addButton(rect<s32>(90,30,110,50), window[1], GUI_ID_FORCE_Q, L"q", L"Adicionar carga de prova.");
env->addButton(rect<s32>(140,30,240,50), window[1], GUI_ID_CALCULATE, L"Calcular", L"Calcular.");
px = env->addEditBox(L"0", rect<s32>(10, 60, 140, 80), true, window[1]); env->addStaticText(L" X pos (metros)", rect<s32>(140, 60, 280, 80), false, true, window[1]);
py = env->addEditBox(L"0", rect<s32>(10, 90, 140, 110), true, window[1]); env->addStaticText(L" Y pos (metros)", rect<s32>(140, 90, 280, 110), false, true, window[1]);
pz = env->addEditBox(L"0", rect<s32>(10, 120, 140, 140), true, window[1]); env->addStaticText(L" Z pos (metros)", rect<s32>(140, 120, 280, 140), false, true, window[1]);
pq = env->addEditBox(L"1", rect<s32>(10, 150, 140, 170), true, window[1]); env->addStaticText(L" Q (micro coulombs)", rect<s32>(140, 150, 280, 170), false, true, window[1]);
}
void ToolsBoxC()
{
window[1] = env->addWindow(rect<s32>(0, 54, 300, 560), false, L"Lancamentos");
env->addButton(rect<s32>(10,30,40,50), window[1], GUI_ID_FORCE_BALL, L"Bola", L"Adicionar progetil.");
env->addButton(rect<s32>(50,30,80,50), window[1], GUI_ID_FORCE_PLAT, L"Plat", L"Adicionar plataforma.");
env->addButton(rect<s32>(90,30,120,50), window[1], GUI_ID_FORCE_QL, L"QL", L"Queda livre.");
env->addButton(rect<s32>(130,30,150,50), window[1], GUI_ID_FORCE_LH, L"LH", L"Lancamento horizontal.");
env->addButton(rect<s32>(160,30,190,50), window[1], GUI_ID_FORCE_LO, L"LO", L"Lancamento obliquo.");
px = env->addEditBox(L"0", rect<s32>(10, 60, 140, 80), true, window[1]); env->addStaticText(L" X pos (metros)", rect<s32>(140, 60, 280, 80), false, true, window[1]);
py = env->addEditBox(L"0", rect<s32>(10, 90, 140, 110), true, window[1]); env->addStaticText(L" Y pos (metros)", rect<s32>(140, 90, 280, 110), false, true, window[1]);
pz = env->addEditBox(L"0", rect<s32>(10, 120, 140, 140), true, window[1]); env->addStaticText(L" Z pos (metros)", rect<s32>(140, 120, 280, 140), false, true, window[1]);
ang = env->addEditBox(L"45", rect<s32>(10, 150, 140, 170), true, window[1]); env->addStaticText(L" Angulo (deg)", rect<s32>(140, 150, 280, 170), false, true, window[1]);
v0 = env->addEditBox(L"0", rect<s32>(10, 180, 140, 200), true, window[1]); env->addStaticText(L" Vel. Ini. (m/s)", rect<s32>(140, 180, 280, 200), false, true, window[1]);
} | 60.521739 | 174 | 0.66978 | [
"vector"
] |
1c1393e095b8a1bd988cb72e2c2618ff5442aafe | 1,311 | cpp | C++ | signalTest.cpp | paulbendixen/testring | 9c246d389eff4cf9371703ae04029ed49259b0f5 | [
"MIT"
] | null | null | null | signalTest.cpp | paulbendixen/testring | 9c246d389eff4cf9371703ae04029ed49259b0f5 | [
"MIT"
] | null | null | null | signalTest.cpp | paulbendixen/testring | 9c246d389eff4cf9371703ae04029ed49259b0f5 | [
"MIT"
] | null | null | null | //
// Created by expert on 16-04-17.
//
#include "signalTest.hpp"
#include <algorithm>
#include <array>
#include <fstream>
#include <iostream>
void signalTest::runTest( double runlength )
{
// generate a signal
std::vector< double > signal;
signal.resize( static_cast< unsigned long >( std::round( runlength * this->samplerate ) ) );
int t = 0;
std::generate( signal.begin(), signal.end(), [&t](){ return std::sin( 2 * M_PI * 440.0 * t++ / 44.1e3 );});
// add some noise
std::transform( signal.begin(), signal.end(), signal.begin(), [this](double s ){ return s + this->dist
(this->generator); } );
// filter it
constexpr std::array< double, 3 > filterCoefficients = { .25, .5, .25 };
std::array< double, 3 > buffer;
sg14::ring_span< double > delayline( buffer.begin(), buffer.end() );
double time = 0.0;
std::ofstream myfile;
myfile.open( "testresults.csv", std::ios::out );
for ( auto& value: signal )
{
myfile << time << ',';
time += 1/this->samplerate;
myfile << value << ',';
delayline.push_back(value);
value = std::inner_product( delayline.begin(), delayline.end(), filterCoefficients.begin(), 0.0 );
myfile << value << '\n';
}
// plot it (use gplot)
}
signalTest::signalTest( double samplerate )
:generator( device() ), dist(0, .5 ), samplerate( samplerate )
{
}
| 27.893617 | 108 | 0.639207 | [
"vector",
"transform"
] |
1c2353143fadbe0d5b7d0cbe9cb9afda3e886267 | 42,545 | cc | C++ | game/graphics.cc | Faerbit/Saxum | 3b255142337e08988f2b4f1f56d6e061e8754336 | [
"CC-BY-3.0",
"CC-BY-4.0"
] | 2 | 2015-03-12T16:19:10.000Z | 2015-11-24T20:23:26.000Z | game/graphics.cc | Faerbit/Saxum | 3b255142337e08988f2b4f1f56d6e061e8754336 | [
"CC-BY-3.0",
"CC-BY-4.0"
] | 15 | 2015-03-14T14:13:12.000Z | 2015-06-02T18:39:55.000Z | game/graphics.cc | Faerbit/Saxum | 3b255142337e08988f2b4f1f56d6e061e8754336 | [
"CC-BY-3.0",
"CC-BY-4.0"
] | null | null | null | #include "graphics.hh"
#include <lodepng/lodepng.h>
#include <iomanip>
#include <sstream>
#include <functional>
#include <ACGL/OpenGL/Creator/ShaderProgramCreator.hh>
#include "LinearMath/btIDebugDraw.h"
using namespace ACGL::OpenGL;
const double lightUpdateDelay = 0.5f;
const double windUpdateDelay = 0.5f;
const int maxShadowSampleCount = 26;
Graphics::Graphics(glm::uvec2 windowSize, float nearPlane,
float farPlane, int cube_size,
unsigned int maxShadowRenderCount,
std::string screenPath,
std::string screenContinuePath) {
this->windowSize = windowSize;
this->nearPlane = nearPlane;
if (farPlane > 0) {
this->farPlane = farPlane;
}
else {
this->farPlane = 0;
}
if (cube_size > 0) {
this->cube_size = cube_size;
}
else {
this->cube_size = 0;
}
if (maxShadowRenderCount < maxShadowSampleCount) {
this->maxShadowRenderCount = maxShadowRenderCount;
}
else {
this->maxShadowRenderCount = 0;
}
this->loadingScreenPath = screenPath;
this->loadingScreenContinuePath = screenContinuePath;
gameStart = false;
renderShadows = true;
renderFlames = true;
renderWorld = true;
renderDebug = false;
}
Graphics::Graphics() {
}
void Graphics::init(Level* level) {
// save Level
this->level = level;
// OpenGL state:
glClearColor( 0.0, 0.0, 0.0, 1.0 );
glEnable( GL_DEPTH_TEST );
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
glEnable(GL_MULTISAMPLE);
lastLightUpdate = 0;
lastWindUpdate = - windUpdateDelay;
windTarget = 0.0f;
wind = glm::vec2(0.0f, 0.0f);
windDirection = glm::vec2(1.0f, 1.0f);
windDirectionTarget = glm::vec2(1.0f, 1.0f);
textureMovementPosition = glm::vec2(0.0, 0.0);
// construct VAO to give shader correct Attribute locations
SharedArrayBuffer ab = SharedArrayBuffer(new ArrayBuffer());
ab->defineAttribute("aPosition", GL_FLOAT, 3);
ab->defineAttribute("aTexCoord", GL_FLOAT, 2);
ab->defineAttribute("aNormal", GL_FLOAT, 3);
SharedVertexArrayObject vao = SharedVertexArrayObject(new VertexArrayObject());
vao->attachAllAttributes(ab);
// look up all shader files starting with 'phong' and build a ShaderProgram from it:
lightingShader = ShaderProgramCreator("phong").attributeLocations(
vao->getAttributeLocations()).create();
skydomeShader = ShaderProgramCreator("skydome").attributeLocations(
vao->getAttributeLocations()).create();
depthShader = ShaderProgramCreator("depth")
.attributeLocations(vao->getAttributeLocations()).create();
depthCubeShader = ShaderProgramCreator("depth_cube")
.attributeLocations(vao->getAttributeLocations()).create();
SharedArrayBuffer flame_positions_ab = SharedArrayBuffer(new ArrayBuffer());
flame_positions_ab->defineAttribute("aPosition", GL_FLOAT, 3);
flame_positions_ab->defineAttribute("aColor", GL_FLOAT, 3);
SharedVertexArrayObject flame_positions = SharedVertexArrayObject(new VertexArrayObject());
flame_positions->attachAllAttributes(flame_positions_ab);
flameShader = ShaderProgramCreator("flame")
.attributeLocations(flame_positions->getAttributeLocations()).create();
fullscreen_quad_ab = SharedArrayBuffer(new ArrayBuffer());
fullscreen_quad_ab->defineAttribute("aPosition", GL_FLOAT, 2);
fullscreen_quad_ab->defineAttribute("aTexCoord", GL_FLOAT, 2);
float quadData[] = {
-1.0f, 1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f
};
fullscreen_quad_ab->setDataElements(6, quadData);
fullscreen_quad = SharedVertexArrayObject(new VertexArrayObject);
fullscreen_quad->attachAllAttributes(fullscreen_quad_ab);
flamePostShader = ShaderProgramCreator("flame_post")
.attributeLocations(fullscreen_quad->getAttributeLocations()).create();
debug_ab = SharedArrayBuffer(new ArrayBuffer());
debug_ab->defineAttribute("aPosition", GL_FLOAT, 3);
debug_ab->defineAttribute("aColor", GL_FLOAT, 3);
debug_vao = SharedVertexArrayObject(new VertexArrayObject());
debug_vao->attachAllAttributes(debug_ab);
debug_vao->setMode(GL_LINES);
debugShader = ShaderProgramCreator("debug")
.attributeLocations(debug_vao->getAttributeLocations()).create();
debugDrawer = DebugDraw();
level->getPhysics()->getWorld()->setDebugDrawer(&debugDrawer);
depth_directionalMaps = std::vector<SharedTexture2D>(5);
framebuffer_directional = std::vector<SharedFrameBufferObject>(5);
for (unsigned int i = 0; i<depth_directionalMaps.size(); i++) {
depth_directionalMaps.at(i) = SharedTexture2D( new Texture2D(windowSize, GL_DEPTH_COMPONENT24));
depth_directionalMaps.at(i)->setMinFilter(GL_NEAREST);
depth_directionalMaps.at(i)->setMagFilter(GL_NEAREST);
depth_directionalMaps.at(i)->setWrapS(GL_CLAMP_TO_EDGE);
depth_directionalMaps.at(i)->setWrapT(GL_CLAMP_TO_EDGE);
depth_directionalMaps.at(i)->setCompareMode(GL_COMPARE_REF_TO_TEXTURE);
}
for (unsigned int i = 0; i<framebuffer_directional.size(); i++) {
framebuffer_directional.at(i) = SharedFrameBufferObject(new FrameBufferObject());
framebuffer_directional.at(i)->setDepthTexture(depth_directionalMaps.at(i));
framebuffer_directional.at(i)->validate();
}
// always generate and bind all cube maps, because otherwise the shader won't work
depth_cubeMaps = std::vector<ACGL::OpenGL::SharedTextureCubeMap>(maxShadowSampleCount);
for (unsigned int i = 0; i<depth_cubeMaps.size(); i++) {
depth_cubeMaps.at(i) = SharedTextureCubeMap(new TextureCubeMap(glm::vec2(cube_size, cube_size), GL_DEPTH_COMPONENT24));
depth_cubeMaps.at(i)->setMinFilter(GL_NEAREST);
depth_cubeMaps.at(i)->setMagFilter(GL_NEAREST);
depth_cubeMaps.at(i)->setWrapS(GL_CLAMP_TO_EDGE);
depth_cubeMaps.at(i)->setWrapT(GL_CLAMP_TO_EDGE);
depth_cubeMaps.at(i)->setCompareMode(GL_COMPARE_REF_TO_TEXTURE);
}
framebuffer_cube = SharedFrameBufferObject(new FrameBufferObject());
light_fbo_color_texture = SharedTexture2D(new Texture2D(windowSize, GL_RGBA8));
light_fbo_color_texture->setMinFilter(GL_NEAREST);
light_fbo_color_texture->setMagFilter(GL_NEAREST);
light_fbo_color_texture->setWrapS(GL_CLAMP_TO_BORDER);
light_fbo_color_texture->setWrapT(GL_CLAMP_TO_BORDER);
light_fbo_depth_texture = SharedTexture2D(new Texture2D(windowSize, GL_DEPTH24_STENCIL8));
light_fbo_depth_texture->setMinFilter(GL_NEAREST);
light_fbo_depth_texture->setMagFilter(GL_NEAREST);
light_fbo_depth_texture->setWrapS(GL_CLAMP_TO_BORDER);
light_fbo_depth_texture->setWrapT(GL_CLAMP_TO_BORDER);
framebuffer_light = SharedFrameBufferObject(new FrameBufferObject());
framebuffer_light->attachColorTexture("oColor", light_fbo_color_texture);
framebuffer_light->setDepthTexture(light_fbo_depth_texture);
framebuffer_light->setClearColor(glm::vec4(0.0f, 0.0f, 0.0f, 1.0f));
framebuffer_light->validate();
flamePostShader->use();
flamePostShader->setUniform("windowSizeX", int(windowSize.x));
flamePostShader->setUniform("windowSizeY", int(windowSize.y));
bindTextureUnits();
// set shader variables that stay the same across the runtime of the application
skydomeShader->use();
skydomeShader->setUniform("farPlane", farPlane);
skydomeShader->setUniform("skydomeSize", level->getSkydomeSize());
skydomeShader->setUniform("fogColorDay", level->getFogColourDay());
skydomeShader->setUniform("fogColorRise", level->getFogColourRise());
skydomeShader->setUniform("fogColorNight", level->getFogColourNight());
skydomeShader->setUniform("sunColor", level->getDirectionalLight()->getColour());
lightingShader->use();
lightingShader->setUniform("farPlane", farPlane);
lightingShader->setUniform("fogColorDay", level->getFogColourDay());
lightingShader->setUniform("fogColorRise", level->getFogColourRise());
lightingShader->setUniform("fogColorNight", level->getFogColourNight());
lightingShader->setUniform("ambientColor", level->getAmbientLight());
if(level->getDirectionalLight()) {
lightingShader->setUniform("directionalLightVector",
level->getDirectionalLight()->getPosition());
lightingShader->setUniform("directionalColor",
level->getDirectionalLight()->getColour());
lightingShader->setUniform("targetDirectionalIntensity",
level->getDirectionalLight()->getIntensity());
}
depthCubeShader->use();
depthCubeShader->setUniform("farPlane", farPlane);
level->sortObjects(Material::getAllTextures()->size());
#ifdef SAXUM_DEBUG
std::cout << "There were " << Material::getAllTextures()->size()
<< " materials used in this level." << std::endl;
cout << "There are " << level->checkMaxSurroundingLights() << " max surrounding lights." << endl;
#endif
initShadowRenderQueue();
updateLights();
}
void Graphics::bindTextureUnits(){
unsigned int textureCount = Material::getAllTextures()->size();
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &number_of_texture_units);
printf("Your graphics card supports %d texture units.\n", number_of_texture_units);
// Exit if we need more texture units
if (number_of_texture_units < (int)textureCount + maxShadowSampleCount + 9) {
printf("You need at least %d texture units to run this application. Exiting\n", textureCount + maxShadowSampleCount + 9);
exit(-1);
}
loadingShader->use();
loadingShader->setTexture("screen", loadingScreen, 0);
loadingShader->setTexture("screenContinue", loadingContinueScreen, 1);
lightingShader->use();
for(unsigned int i = 0; i<Material::getAllTextures()->size(); i++) {
lightingShader->setTexture("uTexture", Material::getAllTextures()->at(i), i+2);
}
for (unsigned int i = 0; i<depth_directionalMaps.size(); i++) {
lightingShader->setTexture("shadowMap_directional" + std::to_string(i), depth_directionalMaps.at(i), textureCount + i + 2);
}
if (level->getLights()->size() > 0) {
for(unsigned int i = 0; i<depth_cubeMaps.size(); i++){
lightingShader->setTexture("shadowMap_cube" + std::to_string(i), depth_cubeMaps.at(i), textureCount + i + 7);
}
}
flamePostShader->use();
flamePostShader->setTexture("light_fbo", light_fbo_color_texture, textureCount + maxShadowSampleCount + 7);
skydomeShader->use();
skydomeShader->setTexture("dayTexture", level->getSkydome()->getDayTexture(), textureCount + maxShadowSampleCount + 8);
skydomeShader->setTexture("nightTexture", level->getSkydome()->getNightTexture(), textureCount + maxShadowSampleCount + 9);
printf("This application used %d texture units.\n", textureCount + maxShadowSampleCount + 9);
}
void Graphics::renderLoadingScreen() {
loadingScreen = Texture2DFileManager::the()->get(Texture2DCreator(loadingScreenPath));
loadingScreen->generateMipmaps();
loadingScreen->setMinFilter(GL_NEAREST_MIPMAP_LINEAR);
loadingScreen->setMagFilter(GL_LINEAR);
loadingContinueScreen = Texture2DFileManager::the()->get(Texture2DCreator(loadingScreenContinuePath));
loadingContinueScreen->generateMipmaps();
loadingContinueScreen->setMinFilter(GL_NEAREST_MIPMAP_LINEAR);
loadingContinueScreen->setMagFilter(GL_LINEAR);
loadingScreenWidth = (float)loadingScreen->getWidth();
loadingScreenHeight = (float)loadingScreen->getHeight();
fullscreen_quad_ab_loading = SharedArrayBuffer(new ArrayBuffer());
fullscreen_quad_ab_loading->defineAttribute("aPosition", GL_FLOAT, 2);
fullscreen_quad_ab_loading->defineAttribute("aTexCoord", GL_FLOAT, 2);
float quadData[24];
if (loadingScreenWidth/loadingScreenHeight < ((float)windowSize.x)/((float)windowSize.y)) {
float quadTemp[24] ={
-(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), 1.0f, 0.0f, 1.0f,
(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), 1.0f, 1.0f, 1.0f,
(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), -1.0f, 1.0f, 0.0f,
(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), -1.0f, 1.0f, 0.0f,
-(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), -1.0f, 0.0f, 0.0f,
-(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), 1.0f, 0.0f, 1.0f
};
for(int i = 0; i<24; i++) {
quadData[i] = quadTemp[i];
}
}
else {
float quadTemp[24] = {
-1.0f, ((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 0.0f, 1.0f,
1.0f, ((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 1.0f, 1.0f,
1.0f, -((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 1.0f, 0.0f,
1.0f, -((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 1.0f, 0.0f,
-1.0f, -((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 0.0f, 0.0f,
-1.0f, ((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 0.0f, 1.0f
};
for(int i = 0; i<24; i++) {
quadData[i] = quadTemp[i];
}
}
fullscreen_quad_ab_loading->setDataElements(6, quadData);
fullscreen_quad_loading = SharedVertexArrayObject(new VertexArrayObject);
fullscreen_quad_loading->attachAllAttributes(fullscreen_quad_ab_loading);
loadingShader = ShaderProgramCreator("loading")
.attributeLocations(fullscreen_quad_loading->getAttributeLocations()).create();
loadingShader->use();
loadingShader->setUniform("time", 0.0f);
loadingShader->setTexture("screen", loadingScreen, 0);
loadingShader->setTexture("screenContinue", loadingContinueScreen, 1);
fullscreen_quad_loading->render();
}
glm::uvec2 Graphics::getWindowSize() {
return windowSize;
}
void Graphics::render(double time)
{
if (!gameStart) {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, windowSize.x, windowSize.y);
loadingShader->use();
loadingShader->setUniform("time", float(time));
fullscreen_quad_loading->render();
}
else {
double nextLightUpdate = lastLightUpdate + lightUpdateDelay;
if (time >= nextLightUpdate)
{
updateLights();
lastLightUpdate = time;
}
// At first render shadows
std::vector<glm::mat4> depthViewProjectionMatrices = std::vector<glm::mat4>(framebuffer_directional.size());
if (renderShadows) {
// update priorities
for(unsigned int i = 0; i<shadowRenderQueue.size(); i++) {
shadowRenderQueue.at(i).currentPriority += shadowRenderQueue.at(i).priority;
}
// schedule lights with highest priority
// tuple : Light, currentPriority, slot
std::vector<std::tuple<std::shared_ptr<Light>, int, int>> renderQueue =
std::vector<std::tuple<std::shared_ptr<Light>, int, int>>(maxShadowRenderCount);
for(unsigned int i = 0; i<shadowRenderQueue.size(); i++) {
for(unsigned int j = 0; j<renderQueue.size(); j++){
if (shadowRenderQueue.at(i).currentPriority > std::get<1>(renderQueue.at(j))){
if (renderQueue.at(j) != renderQueue.back()) {
renderQueue.at(j+1) = renderQueue.at(j);
}
renderQueue.at(j) = std::make_tuple(shadowRenderQueue.at(i).light, shadowRenderQueue.at(i).currentPriority, i);
break;
}
}
}
// reset currentPriority
for(unsigned int i = 0; i<renderQueue.size(); i++) {
shadowRenderQueue.at(std::get<2>(renderQueue.at(i))).currentPriority = 0;
}
depthCubeShader->use();
// render depth textures for point lights
glViewport(0, 0, cube_size, cube_size);
depthCubeShader->use();
glm::mat4 depthProjectionMatrix_pointlights = glm::perspective(1.571f, (float)cube_size/(float)cube_size, 0.1f, 50.0f);
glm::vec3 looking_directions[6] = {glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f),
glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, 0.0f, -1.0f)};
glm::vec3 upvectors[6] = {glm::vec3(0.0f, -1.0f, 0.0f),glm::vec3(0.0f, -1.0f, 0.0f),glm::vec3(0.0f, 0.0f, -1.0f),
glm::vec3(0.0f, 0.0f, -1.0f),glm::vec3(0.0f, -1.0f, 0.0f),glm::vec3(0.0f, -1.0f, 0.0f)};
framebuffer_cube->bind();
for (unsigned int i_pointlight = 0; i_pointlight < renderQueue.size(); i_pointlight++) {
// check if queue points to a existing light
if (std::get<0>(renderQueue.at(i_pointlight))) {
// render each side of the cube
glm::vec3 position = glm::vec3(0.0f);
if (std::get<0>(renderQueue.at(i_pointlight))->isFlame()) {
position = std::get<0>(renderQueue.at(i_pointlight))->getPosition();
position = glm::vec3(position.x - 0.75f*wind.y, position.y, position.z + 0.75f*wind.x);
}
else {
position = std::get<0>(renderQueue.at(i_pointlight))->getPosition();
}
for (int i_face = 0; i_face<6; i_face++) {
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i_face,
depth_cubeMaps.at(std::get<2>(renderQueue.at(i_pointlight)))->getObjectName(), 0);
glClear(GL_DEPTH_BUFFER_BIT);
glm::mat4 viewMatrix = glm::lookAt(position, position + looking_directions[i_face], upvectors[i_face]);
glm::mat4 depthViewProjectionMatrix_face = depthProjectionMatrix_pointlights * viewMatrix;
std::vector<glm::mat4> viewMatrixVector = std::vector<glm::mat4>(1);
viewMatrixVector.at(0) = viewMatrix;
level->render(depthCubeShader, false, std::get<0>(renderQueue.at(i_pointlight))->getPosition(), 1, &depthViewProjectionMatrix_face, &viewMatrixVector);
if (!framebuffer_cube->isFrameBufferObjectComplete()) {
printf("Framebuffer incomplete, unknown error occured during shadow generation!\n");
}
}
}
}
glViewport(0, 0, windowSize.x, windowSize.y);
// render depth textures for sun
float sunAngle = glm::dot(glm::vec3(0.0f, 1.0f, 0.0f), glm::normalize(level->getDirectionalLight()->getPosition()));
glm::vec3 sunVector = (level->getCameraCenter()->getPosition() + level->getDirectionalLight()->getPosition());
if (sunAngle > 0.0f) {
depthShader->use();
for (unsigned int i = 0; i<framebuffer_directional.size(); i++) {
framebuffer_directional.at(i)->bind();
glClear(GL_DEPTH_BUFFER_BIT);
float projection_size = 0.0f;
switch(i) {
case 0:
projection_size = 10.0f;
break;
case 1:
projection_size = 20.0f;
break;
case 2:
projection_size = 40.0f;
break;
case 3:
projection_size = 60.0f;
break;
case 4:
projection_size = farPlane/1.5f;
break;
}
depthViewProjectionMatrices.at(i) = glm::ortho<float>(-projection_size, projection_size, -projection_size, projection_size, -farPlane/1.5f, farPlane/1.5f) *
glm::lookAt(sunVector, level->getCameraCenter()->getPosition(), glm::vec3(0,1,0));
level->render(depthShader, false, level->getCameraCenter()->getPosition(), -1, &depthViewProjectionMatrices.at(i));
if (!framebuffer_directional.at(i)->isFrameBufferObjectComplete()) {
printf("Framebuffer incomplete, unknown error occured during shadow generation!\n");
}
}
}
}
// lighting render pass
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//wind
double nextWindUpdate = lastWindUpdate + lightUpdateDelay;
if (time >= nextWindUpdate)
{
const float windTargetEnd = 0.7f;
windTarget = static_cast<float>(rand()) / static_cast<float>(RAND_MAX/pow(windTargetEnd, 2));
windTarget = sqrt(windTarget);
windTarget *= 0.8f*pow(sin(0.1f*time), 2) +0.2f;
const float windDirectionXEnd = 0.5f;
float windDirectionX = static_cast<float>(rand()) / static_cast<float>(RAND_MAX/pow(windDirectionXEnd, 2));
windDirectionX = sqrt(windDirectionX);
const float windDirectionYEnd = 0.5f;
float windDirectionY = static_cast<float>(rand()) / static_cast<float>(RAND_MAX/pow(windDirectionYEnd, 2));
windDirectionY = sqrt(windDirectionY);
windDirectionTarget = glm::vec2(windDirectionX, windDirectionY);
lastWindUpdate = time;
}
const float windApproachSpeed= 0.0005f;
if (windApproachSpeed*static_cast<float>(time)>1.0f) {
wind = glm::normalize(windDirection)*windTarget;
windDirection = windDirectionTarget;
}
else {
windDirection.x = windDirection.x + windApproachSpeed*static_cast<float>(time)*windDirectionTarget.x - windDirection.x;
windDirection.y = windDirection.y + windApproachSpeed*static_cast<float>(time)*windDirectionTarget.y - windDirection.x;
wind = wind + (windApproachSpeed*static_cast<float>(time)) * (glm::normalize(windDirection)*windTarget - wind);
}
//set view and projection matrix
glm::mat4 lightingViewProjectionMatrix = glm::perspective(1.571f, (float)windowSize.x/(float)windowSize.y, 0.1f, farPlane) * buildViewMatrix(level);
//render skydome
skydomeShader->use();
// set fog Parameters
skydomeShader->setUniform("cameraCenter", level->getCameraCenter()->getPosition());
skydomeShader->setUniform("directionalVector", level->getDirectionalLight()->getPosition());
level->getSkydome()->render(skydomeShader, false, &lightingViewProjectionMatrix);
lightingShader->use();
// convert texture to homogenouse coordinates
glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);
std::vector<glm::mat4> depthBiasVPs = std::vector<glm::mat4>(depthViewProjectionMatrices.size());
for (unsigned int i = 0; i<depthBiasVPs.size(); i++) {
depthBiasVPs.at(i) = biasMatrix * depthViewProjectionMatrices.at(i);
}
// set fog Parameters
lightingShader->setUniform("cameraCenter", level->getCameraCenter()->getPosition());
if(level->getDirectionalLight()) {
lightingShader->setUniform("directionalLightVector",
level->getDirectionalLight()->getPosition());
}
// set Material Parameters
lightingShader->setUniform("camera", level->getPhysics()->getCameraPosition());
textureMovementPosition += wind/5.0f;
lightingShader->setUniform("movingTextureOffset", textureMovementPosition);
lightingShader->setUniform("movement", wind);
lightingShader->setUniform("time", (float) time);
if (renderWorld) {
// render the level
level->enqueueObjects(this);
for (unsigned int i = 0; i<Material::getAllTextures()->size(); i++) {
bool parametersSet = false;
for(unsigned int j = 0; j<renderQueue.size(); j++) {
if(renderQueue.at(j)->at(i).size() != 0) {
if (!parametersSet) {
parametersSet = true;
Material* material = renderQueue.at(j)->at(i).at(0)->getMaterial();
if (material->isMoving()) {
lightingShader->setUniform("movingTexture", true);
}
else {
lightingShader->setUniform("movingTexture", false);
}
lightingShader->setUniform("uTexture", material->getTextureUnit());
lightingShader->setUniform("ambientFactor", material->getAmbientFactor());
lightingShader->setUniform("diffuseFactor", material->getDiffuseFactor());
lightingShader->setUniform("specularFactor", material->getSpecularFactor());
lightingShader->setUniform("shininess", material->getShininess());
}
for(unsigned int k = 0; k<renderQueue.at(j)->at(i).size(); k++) {
renderQueue.at(j)->at(i).at(k)->render(lightingShader, true, &lightingViewProjectionMatrix, &depthBiasVPs);
}
}
}
}
// render water plane last for correct transparency
if (level->getWaterPlane()) {
Material* material = level->getWaterPlane()->getMaterial();
if (material->isMoving()) {
lightingShader->setUniform("movingTexture", true);
}
else {
lightingShader->setUniform("movingTexture", false);
}
lightingShader->setUniform("uTexture", material->getTextureUnit());
lightingShader->setUniform("ambientFactor", material->getAmbientFactor());
lightingShader->setUniform("diffuseFactor", material->getDiffuseFactor());
lightingShader->setUniform("specularFactor", material->getSpecularFactor());
lightingShader->setUniform("shininess", material->getShininess());
level->getWaterPlane()->render(lightingShader, true, &lightingViewProjectionMatrix, &depthBiasVPs);
}
renderQueue.clear();
}
if (renderDebug) {
debugDrawer.setDebugMode(btIDebugDraw::DBG_DrawWireframe);
level->getPhysics()->getWorld()->debugDrawWorld();
debugDrawer.setDebugMode(btIDebugDraw::DBG_NoDebug);
unsigned int data_count = debugDrawer.getData()->size();
float* debugData = new float[data_count];
for (unsigned int i = 0; i<data_count; i++) {
debugData[i] = debugDrawer.getData()->at(i);
}
debug_ab->setDataElements(data_count/6, debugData);
debugDrawer.clearData();
delete[] debugData;
debugShader->use();
debugShader->setUniform("viewProjectionMatrix", lightingViewProjectionMatrix);
debug_vao->render();
}
// draw flames on top
if (renderFlames) {
flameShader->use();
// cull faces to get consistent color while using alpha
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
// draw with colors
for(unsigned int i = 0; i<closestFlames.size(); i++) {
closestFlames.at(i)->render(flameShader, lightingViewProjectionMatrix, float(time), true, wind);
}
glDisable(GL_CULL_FACE);
framebuffer_light->bind();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer_light->getObjectName());
glBlitFramebuffer(0, 0, windowSize.x, windowSize.y, 0, 0, windowSize.x, windowSize.y,
GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
// draw slightly larger only for stencil buffer to blur edges
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 1, 0xFF); //Set any stencil to 1
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glStencilMask(0xFF);//write to stencil buffer
glClear(GL_STENCIL_BUFFER_BIT);//clear stencil buffer
for(unsigned int i = 0; i<closestFlames.size(); i++) {
closestFlames.at(i)->render(flameShader, lightingViewProjectionMatrix, float(time), false, wind);
}
glStencilFunc(GL_EQUAL, 1, 0xFF); //Pass test if stencil value is 1
glStencilMask(0x00);// don't write to stencil buffer
flamePostShader->use();
fullscreen_quad->render();
glDepthMask(GL_TRUE);
glDisable(GL_STENCIL_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer_light->getObjectName());
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBlitFramebuffer(0, 0, windowSize.x, windowSize.y, 0, 0, windowSize.x, windowSize.y,
GL_COLOR_BUFFER_BIT, GL_NEAREST);
}
}
}
void Graphics::updateLights() {
std::vector<std::shared_ptr<Light>> oldClosestLights = std::vector<std::shared_ptr<Light>>(*closestLights);
closestLights = level->getClosestLights(maxShadowSampleCount);
if (closestLights->size() > 0) {
lightingShader->use();
lightingShader->setUniform("lightCount", (int) closestLights->size());
lightingShader->setUniform("maxShadowRenderCount", min((int)closestLights->size(), maxShadowSampleCount));
// find new closest lights for the shadow render queue
unsigned int i = 0;
std::vector<std::shared_ptr<Light>> compareClosestLights = std::vector<std::shared_ptr<Light>>(*closestLights);
while(i<oldClosestLights.size()) {
bool found = false;
for(unsigned int j = 0; j<compareClosestLights.size(); j++) {
if (oldClosestLights.at(i) == compareClosestLights.at(j)){
found = true;
compareClosestLights.erase(compareClosestLights.begin() + j);
break;
}
}
if (found) {
oldClosestLights.erase(oldClosestLights.begin() + i);
}
else {
i++;
}
}
assert(oldClosestLights.size() == compareClosestLights.size());
// replace old lights with the new ones in the shadow render queue
for(unsigned int i = 0; i<oldClosestLights.size(); i++) {
for(unsigned int j = 0; j<shadowRenderQueue.size(); j++) {
if(oldClosestLights.at(i) == shadowRenderQueue.at(j).light) {
shadowRenderQueue.at(j).light = compareClosestLights.at(i);
// 15000 is larger priority than any light can get during one tick
shadowRenderQueue.at(j).currentPriority = 15000;
}
}
}
// update priority of the shadow render queue
for(unsigned int i = 0; i<shadowRenderQueue.size(); i++) {
float distance = glm::distance(level->getCameraCenter()->getPosition(), shadowRenderQueue.at(i).light->getPosition());
shadowRenderQueue.at(i).priority = (int) 100*std::exp(5.0f - 0.1f * distance);
}
// Build light position array
glm::vec3 lightSources[shadowRenderQueue.size()];
for(unsigned int i = 0; i<shadowRenderQueue.size(); i++) {
lightSources[i] = shadowRenderQueue.at(i).light->getPosition();
}
glUniform3fv(lightingShader->getUniformLocation("lightSources"),
sizeof(lightSources), (GLfloat*) lightSources);
// Build light colour array
glm::vec3 lightColours[shadowRenderQueue.size()];
for(unsigned int i = 0; i<shadowRenderQueue.size(); i++) {
lightColours[i] = shadowRenderQueue.at(i).light->getColour();
}
glUniform3fv(lightingShader->getUniformLocation("lightColors"),
sizeof(lightColours), (GLfloat*) lightColours);
// Build light attenuation array
float lightIntensities[shadowRenderQueue.size()];
for(unsigned int i = 0; i<shadowRenderQueue.size(); i++) {
lightIntensities[i] = shadowRenderQueue.at(i).light->getIntensity();
}
glUniform1fv(lightingShader->getUniformLocation("lightIntensities"),
sizeof(lightIntensities), (GLfloat*) lightIntensities);
bool isFlame[shadowRenderQueue.size()];
closestFlames = std::vector<Flame*>();
for(unsigned int i = 0; i<shadowRenderQueue.size(); i++) {
if (shadowRenderQueue.at(i).light->isFlame()) {
closestFlames.push_back(shadowRenderQueue.at(i).light->getFlame());
isFlame[i] = true;
}
else {
isFlame[i] = false;
}
}
glUniform1iv(lightingShader->getUniformLocation("isFlame"), sizeof(isFlame), (GLint*) isFlame);
}
}
void Graphics::saveWindowSize(glm::uvec2 windowSize) {
this->windowSize = windowSize;
}
void Graphics::resize(glm::uvec2 windowSize) {
this->windowSize = windowSize;
if (gameStart) {
for (unsigned int i = 0; i<depth_directionalMaps.size(); i++) {
depth_directionalMaps.at(i)->resize(glm::vec2(windowSize.x, windowSize.y));
}
light_fbo_color_texture->resize(windowSize);
light_fbo_depth_texture->resize(windowSize);
flamePostShader->setUniform("windowSizeX", int(windowSize.x));
flamePostShader->setUniform("windowSizeY", int(windowSize.y));
bindTextureUnits();
}
else {
float quadData[24];
if (loadingScreenWidth/loadingScreenHeight < ((float)windowSize.x)/((float)windowSize.y)) {
float quadTemp[24] ={
-(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), 1.0f, 0.0f, 1.0f,
(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), 1.0f, 1.0f, 1.0f,
(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), -1.0f, 1.0f, 0.0f,
(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), -1.0f, 1.0f, 0.0f,
-(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), -1.0f, 0.0f, 0.0f,
-(((float)windowSize.y*loadingScreenWidth)/((float)windowSize.x*loadingScreenHeight)), 1.0f, 0.0f, 1.0f
};
for(int i = 0; i<24; i++) {
quadData[i] = quadTemp[i];
}
}
else {
float quadTemp[24] = {
-1.0f, ((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 0.0f, 1.0f,
1.0f, ((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 1.0f, 1.0f,
1.0f, -((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 1.0f, 0.0f,
1.0f, -((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 1.0f, 0.0f,
-1.0f, -((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 0.0f, 0.0f,
-1.0f, ((float)windowSize.x*loadingScreenHeight)/((float)windowSize.y*loadingScreenWidth), 0.0f, 1.0f
};
for(int i = 0; i<24; i++) {
quadData[i] = quadTemp[i];
}
}
fullscreen_quad_ab_loading->setDataElements(6, quadData);
fullscreen_quad_loading = SharedVertexArrayObject(new VertexArrayObject);
fullscreen_quad_loading->attachAllAttributes(fullscreen_quad_ab_loading);
}
}
glm::mat4 Graphics::buildViewMatrix(Level* level) {
//construct lookAt (cameraPosition = cameraCenter + cameraVector)
if(level->getCamera()->getIsPhysicsCamera())
return glm::lookAt(level->getCamera()->getPosition(), level->getCamera()->getPosition() + level->getCamera()->getDirection(), glm::vec3(0.0f, 1.0f, 0.0f));
return glm::lookAt((level->getCameraCenter()->getPosition() + level->getCamera()->getVector()),
level->getCameraCenter()->getPosition(), glm::vec3(0.0f, 1.0f, 0.0f));
}
float Graphics::getFarPlane() {
return farPlane;
}
void Graphics::saveDepthBufferToDisk(int face, std::string filename) {
printf("Starting saving of depth buffer...\n");
float *depthbuffer = new float[1024*1024];
std::vector<unsigned char> image (1024 * 1024 * 4);
glGetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, GL_DEPTH_COMPONENT, GL_FLOAT, depthbuffer);
for (unsigned int i = 0; i<1024*1024; i++) {
image[i * 4 + 0] = depthbuffer[i] * 255;
image[i * 4 + 1] = depthbuffer[i] * 255;
image[i * 4 + 2] = depthbuffer[i] * 255;
image[i * 4 + 3] = 255;
}
unsigned error = lodepng::encode(filename.c_str(), image, 1024, 1024);
if (error) {
std::cout << "Encoder error " << error << ": " << lodepng_error_text(error) << std::endl;
}
else {
printf("Saving complete!\n");
}
delete [] depthbuffer;
}
void Graphics::startGame() {
gameStart = true;
}
void Graphics::setRenderShadows(bool state) {
if(!state) {
for(unsigned int i = 0; i<framebuffer_directional.size(); i++) {
framebuffer_directional.at(i)->bind();
glClear(GL_DEPTH_BUFFER_BIT);
}
for(unsigned int i_pointlight = 0; i_pointlight<depth_cubeMaps.size(); i_pointlight++) {
for(int i_face = 0; i_face<6; i_face++) {
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i_face, depth_cubeMaps.at(i_pointlight)->getObjectName(), 0);
glClear(GL_DEPTH_BUFFER_BIT);
}
}
}
renderShadows = state;
}
void Graphics::setRenderFlames(bool state) {
renderFlames = state;
}
bool Graphics::getRenderShadows() {
return renderShadows;
}
bool Graphics::getRenderFlames() {
return renderFlames;
}
void Graphics::setRenderDebug(bool state) {
renderDebug = state;
}
bool Graphics::getRenderDebug() {
return renderDebug;
}
void Graphics::setRenderWorld(bool state) {
renderWorld = state;
}
bool Graphics::getRenderWorld() {
return renderWorld;
}
void Graphics::enqueueObjects(std::vector<std::vector<Object*>>* queue){
renderQueue.push_back(queue);
}
void Graphics::initShadowRenderQueue() {
closestLights = level->getClosestLights(maxShadowSampleCount);
int maxLights = min((int)closestLights->size(), maxShadowSampleCount);
shadowRenderQueue = std::vector<ShadowRenderQueueSlot>(maxLights);
glViewport(0, 0, cube_size, cube_size);
glm::mat4 depthProjectionMatrix_pointlights = glm::perspective(1.571f, (float)cube_size/(float)cube_size, 0.1f, 50.0f);
glm::vec3 looking_directions[6] = {glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f),
glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, 0.0f, -1.0f)};
glm::vec3 upvectors[6] = {glm::vec3(0.0f, -1.0f, 0.0f),glm::vec3(0.0f, -1.0f, 0.0f),glm::vec3(0.0f, 0.0f, -1.0f),
glm::vec3(0.0f, 0.0f, -1.0f),glm::vec3(0.0f, -1.0f, 0.0f),glm::vec3(0.0f, -1.0f, 0.0f)};
framebuffer_cube->bind();
for(unsigned int i = 0; i<shadowRenderQueue.size(); i++){
shadowRenderQueue.at(i).light = closestLights->at(i);
shadowRenderQueue.at(i).currentPriority = 0;
// render depth textures for point lights
depthCubeShader->use();
// render each side of the cube
for (int i_face = 0; i_face<6; i_face++) {
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i_face, depth_cubeMaps.at(i)->getObjectName(), 0);
glClear(GL_DEPTH_BUFFER_BIT);
glm::mat4 viewMatrix = glm::lookAt(shadowRenderQueue.at(i).light->getPosition(),
shadowRenderQueue.at(i).light->getPosition() + looking_directions[i_face], upvectors[i_face]);
glm::mat4 depthViewProjectionMatrix_face = depthProjectionMatrix_pointlights * viewMatrix;
std::vector<glm::mat4> viewMatrixVector = std::vector<glm::mat4>();
viewMatrixVector.push_back(viewMatrix);
level->render(depthCubeShader, false, shadowRenderQueue.at(i).light->getPosition(), 1, &depthViewProjectionMatrix_face, &viewMatrixVector);
if (!framebuffer_cube->isFrameBufferObjectComplete()) {
printf("Framebuffer incomplete, unknown error occured during shadow generation!\n");
}
}
}
}
| 46.855727 | 181 | 0.625291 | [
"render",
"object",
"vector"
] |
1c2a7e61b64b24977eb4772c6530c17472bdc57c | 14,699 | cpp | C++ | src/lib/THClReduce.cpp | spijdar/cltorch | 579800c5eb3809324056bd5a6cb1af892938ca5f | [
"BSD-3-Clause"
] | 308 | 2015-06-11T02:41:57.000Z | 2022-01-21T04:31:56.000Z | src/lib/THClReduce.cpp | spijdar/cltorch | 579800c5eb3809324056bd5a6cb1af892938ca5f | [
"BSD-3-Clause"
] | 76 | 2015-06-21T11:57:46.000Z | 2022-02-26T07:23:16.000Z | src/lib/THClReduce.cpp | spijdar/cltorch | 579800c5eb3809324056bd5a6cb1af892938ca5f | [
"BSD-3-Clause"
] | 29 | 2015-06-11T11:15:10.000Z | 2021-11-01T13:54:10.000Z | #include <iostream>
#include "THClReduce.h"
#include "THClTypeParseTraits.h"
using namespace std;
#define THCL_NONCONTIG_REDUCE_BLOCK_SIZE 32 * 16
static int getNonContigReduceBlockSize(THClState *state) {
int blockSize = 1024;
int maxWorkgroupSize = ((easycl::DeviceInfo *)state->deviceInfoByDevice[state->currentDevice])->maxWorkGroupSize;
if( blockSize > maxWorkgroupSize ) {
blockSize = maxWorkgroupSize;
}
return blockSize;
}
static dim3 getNoncontigReduceBlock(THClState *state) {
return dim3(getNonContigReduceBlockSize(state));
}
static dim3 getContigReduceBlock(THClState *state, int64 numSlices, int64 reductionSize) {
// If the number of slices is low but the reduction dimension size
// is high, then we should increase block size for greater parallelism.
// Aim for at least 32 warps per SM (assume 15 SMs; don't bother
// inquiring the real number for now).
int maxWarps = 4; // better occupancy if many blocks are around
// For numSlices > 15 * 8, there are > 32 warps active per SM.
if (numSlices < 15 * 8) {
maxWarps = 8;
if (numSlices < 15 * 4) {
maxWarps = 16;
if (numSlices < 15 * 2) {
maxWarps = 32;
}
}
}
// Scale up block size based on the reduction dimension size
int64 warpsInReductionSize = THClCeilDiv(reductionSize, 32ll);
// int64 warpsInReductionSize = DIVUP(reductionSize, 32L);
int numWarps =
warpsInReductionSize > (int64) maxWarps ? maxWarps : (int) warpsInReductionSize;
// warpsInReductionSize > (int64) maxWarps ? maxWarps : (int) warpsInReductionSize;
int targetSize = numWarps * 32;
// but is this greater than maxWorkgroupSize? We should check :-)
int maxWorkgroupSize = ((easycl::DeviceInfo *)state->deviceInfoByDevice[state->currentDevice])->maxWorkGroupSize;
if(targetSize > maxWorkgroupSize) {
targetSize = maxWorkgroupSize;
}
return dim3(targetSize);
}
static bool getNoncontigReduceGrid(THClState *state, int64 elements, dim3& grid) {
// One output point per thread
return THCL_getGridFromTiles(THClCeilDiv(elements, (int64) getNonContigReduceBlockSize(state)), grid);
// return THCL_getGridFromTiles(DIVUP(elements, THCL_NONCONTIG_REDUCE_BLOCK_SIZE), grid);
}
static bool getContigReduceGrid(int64 elements, dim3& grid) {
// One output point per block
return THCL_getGridFromTiles(elements, grid);
}
template<typename IndexType>
void kernelLaunch_THClTensor_reduceNoncontigDim(
THClState *state,
dim3 &grid,
dim3 &block,
int ADims,
int BDims,
TensorInfo<IndexType> out,
TensorInfo<IndexType> in,
IndexType reductionStride,
IndexType reductionSize,
IndexType totalSlices,
float init,
HasOperator2 const*modifyOp,
HasOperator3 const*reduceOp) {
// cl->finish();
StatefulTimer::timeCheck("Reduce-noncontig START");
std::string uniqueName = "THClTensor_reduceNoncontigDim_" + easycl::toString(ADims) + "_" + easycl::toString(BDims) + "_" +
TypeParseTraits<IndexType>::name + "_" + modifyOp->operator2() + "_" + reduceOp->operator3();
EasyCL *cl = in.wrapper->getCl();
CLKernel *kernel = 0;
if(cl->kernelExists(uniqueName)) {
kernel = cl->getKernel(uniqueName);
StatefulTimer::timeCheck("Apply3 1aa");
} else {
// launch kernel here....
TemplatedKernel kernelBuilder(cl);
std::set<int> dims_set;
if(ADims >= 0) {
dims_set.insert(ADims);
}
if(BDims >= 0) {
dims_set.insert(BDims);
}
std::vector<int> dims;
for( std::set<int>::iterator it = dims_set.begin(); it != dims_set.end(); it++ ) {
dims.push_back(*it);
}
std::string indexType = TypeParseTraits<IndexType>::name;
kernelBuilder
.set("include_THClReduceApplyUtils", THClReduceApplyUtils_getKernelTemplate())
.set("dims", dims)
.set("dim1", ADims)
.set("dim2", BDims)
.set("defreduceblock", 1)
.set("WarpSize", 32) // probably can do like 'if nvidia 32 else 64' ?
.set("MAX_CLTORCH_DIMS", MAX_CLTORCH_DIMS)
.set("IndexType", indexType)
.set("modify_operation", modifyOp->operator2())
.set("reduce_operation", reduceOp->operator3())
;
kernel = kernelBuilder.buildKernel(uniqueName, "THClReduce.cl", THClReduce_getKernelSource(), "THClTensor_reduceNoncontigDim");
}
THClKernels k(state, kernel);
k.out(out);
k.in(in);
k.in((int)reductionStride);
k.in((int)reductionSize);
k.in((int)totalSlices);
k.in(init);
k.run(grid, block);
if(state->addFinish) cl->finish();
StatefulTimer::timeCheck("Reduce-noncontig END");
}
template<typename IndexType>
void kernelLaunch_THClTensor_reduceContigDim(
THClState *state,
dim3 &grid,
dim3 &block,
size_t smemSize,
int ADims,
int BDims,
TensorInfo<IndexType> out,
TensorInfo<IndexType> in,
IndexType reductionSize,
IndexType totalSlices,
float init,
HasOperator2 const*modifyOp,
HasOperator3 const*reduceOp) {
StatefulTimer::timeCheck("Reduce-contig START");
std::string uniqueName = "THClTensor_reduceContigDim_" + easycl::toString(ADims) + "_" + easycl::toString(BDims) + "_" +
TypeParseTraits<IndexType>::name + "_" + modifyOp->operator2() + "_" + reduceOp->operator3();
EasyCL *cl = in.wrapper->getCl();
CLKernel *kernel = 0;
if(cl->kernelExists(uniqueName)) {
kernel = cl->getKernel(uniqueName);
StatefulTimer::timeCheck("Apply3 1aa");
} else {
// launch kernel here....
TemplatedKernel kernelBuilder(cl);
std::set<int> dims_set;
if(ADims >= 0) {
dims_set.insert(ADims);
}
if(BDims >= 0) {
dims_set.insert(BDims);
}
std::vector<int> dims;
for( std::set<int>::iterator it = dims_set.begin(); it != dims_set.end(); it++ ) {
dims.push_back(*it);
}
std::string indexType = TypeParseTraits<IndexType>::name;
kernelBuilder
.set("include_THClReduceApplyUtils", THClReduceApplyUtils_getKernelTemplate())
.set("dims", dims)
.set("dim1", ADims)
.set("defreduceblock", 1)
.set("dim2", BDims)
.set("WarpSize", 32) // probably can do like 'if nvidia 32 else 64' ?
.set("MAX_CLTORCH_DIMS", MAX_CLTORCH_DIMS)
// .set("IndexType", indexType)
.set("IndexType", "int")
.set("modify_operation", modifyOp->operator2())
.set("reduce_operation", reduceOp->operator3())
;
kernel = kernelBuilder.buildKernel(uniqueName, "THClReduce.cl", THClReduce_getKernelSource(), "THClTensor_reduceContigDim");
}
THClKernels k(state, kernel);
k.out(out);
k.in(in);
k.in((int)reductionSize);
k.in((int)totalSlices);
k.in(init);
k.localFloats(smemSize / sizeof(float));
k.run(grid, block);
if(state->addFinish) cl->finish();
StatefulTimer::timeCheck("Reduce-contig END");
}
// Performs a reduction out[..., 0, ...] = reduce_i(modify(in[..., i, ...])) for
// all in where i and the out's 0 are indexed at dimension `dim`
bool THClTensor_reduceDim(THClState* state,
THClTensor* out,
THClTensor* in,
float init,
const HasOperator2 *modifyOp,
const HasOperator3 *reduceOp,
int dim) {
int64 inElements = THClTensor_nElement(state, in);
int64 reductionSize = THClTensor_size(state, in, dim);
int64 reductionStride = THClTensor_stride(state, in, dim);
int64 outElements = inElements / reductionSize;
if (THClTensor_nDimension(state, out) > MAX_CLTORCH_DIMS ||
THClTensor_nDimension(state, in) > MAX_CLTORCH_DIMS) {
return false;
}
if (THClTensor_nDimension(state, in) == 0) {
// Zero-dim tensor; do nothing
return true;
}
// Is the reduction dimension contiguous? If so, then we can use a
// shared memory reduction kernel to increase performance.
bool contigReduction = (reductionStride == 1);
dim3 block;
dim3 grid;
int smemSize = 0; // contiguous reduction uses smem
if (contigReduction) {
if (!getContigReduceGrid(outElements, grid)) {
return false;
}
block = getContigReduceBlock(state, outElements, reductionSize);
smemSize = sizeof(float) * block.x();
} else {
if (!getNoncontigReduceGrid(state, outElements, grid)) {
return false;
}
block = getNoncontigReduceBlock(state);
}
// Resize out to correspond to the reduced size
THLongStorage* sizes = THClTensor_newSizeOf(state, in);
THLongStorage_set(sizes, dim, 1);
THClTensor_resize(state, out, sizes, NULL);
THLongStorage_free(sizes);
if (THCL_canUse32BitIndexMath(state, out) &&
THCL_canUse32BitIndexMath(state, in)) {
TensorInfo<uint32> outInfo(state, out);
TensorInfo<uint32> inInfo(state, in, dim);
int OUT = outInfo.dims;
int IN = inInfo.dims;
if(outInfo.isContiguous()) OUT = -2;
if(inInfo.isContiguous()) IN = -2;
if (contigReduction) {
kernelLaunch_THClTensor_reduceContigDim<uint32> (
state, grid, block, smemSize, OUT, IN, outInfo, inInfo, (uint32) reductionSize,
(uint32) outElements, init, modifyOp, reduceOp);
} else {
kernelLaunch_THClTensor_reduceNoncontigDim<uint32> (
state, grid, block, OUT, IN, outInfo, inInfo, (uint32) reductionStride, (uint32) reductionSize,
(uint32) outElements, init, modifyOp, reduceOp);
}
} else {
TensorInfo<uint64> outInfo(state, out);
TensorInfo<uint64> inInfo(state, in, dim);
int OUT = outInfo.dims;
int IN = inInfo.dims;
if(outInfo.isContiguous()) OUT = -2;
if(inInfo.isContiguous()) IN = -2;
if (contigReduction) {
kernelLaunch_THClTensor_reduceContigDim<uint64> (
state, grid, block, smemSize, OUT, IN, outInfo, inInfo, (uint64) reductionSize,
(uint64) outElements, init, modifyOp, reduceOp);
} else {
kernelLaunch_THClTensor_reduceNoncontigDim<uint64> (
state, grid, block, OUT, IN, outInfo, inInfo, (uint64) reductionStride, (uint64) reductionSize,
(uint64) outElements, init, modifyOp, reduceOp);
}
}
return true;
}
std::string THClReduce_getKernelSource() {
// [[[cog
// import stringify
// stringify.write_kernel( "kernel", "THClReduce.cl" )
// ]]]
// generated using cog, from THClReduce.cl:
const char * kernelSource =
"// Threads per thread block\n"
"#define THCL_NONCONTIG_REDUCE_BLOCK_SIZE 32 * 16\n"
"\n"
"static inline float modifyOp(float _in1) {\n"
" float _out;\n"
" float *in1 = &_in1;\n"
" float *out = &_out;\n"
" {{modify_operation}};\n"
" return _out;\n"
"}\n"
"\n"
"static inline float reduceOp(float _in1, float _in2) {\n"
" // I guess the compiler can sort this stuff out :-P\n"
" float _out;\n"
" float *in1 = &_in1;\n"
" float *in2 = &_in2;\n"
" float *out = &_out;\n"
" {{reduce_operation}};\n"
" return _out;\n"
"}\n"
"\n"
"{{include_THClReduceApplyUtils}}\n"
"\n"
"static inline {{IndexType}} getReduceNoncontigDimSliceIndex() {\n"
" // Each thread handles one slice\n"
" return getLinearBlockId() * THCL_NONCONTIG_REDUCE_BLOCK_SIZE + /*threadIdx.x*/ get_local_id(0);\n"
"}\n"
"\n"
"// Kernel that handles an entire reduction of a slice of a tensor per each thread\n"
"kernel void\n"
"THClTensor_reduceNoncontigDim(global TensorInfoCl *out_info,\n"
" global float *out_data,\n"
" global TensorInfoCl *in_info,\n"
" global float *in_data,\n"
" int reductionStride,\n"
" int reductionSize,\n"
" int totalSlices,\n"
" float init) {\n"
" const {{IndexType}} sliceIndex = getReduceNoncontigDimSliceIndex();\n"
"\n"
" if ((int)sliceIndex >= totalSlices) {\n"
" return;\n"
" }\n"
"\n"
" // Each thread picks a point in `out` and `in` for which it is\n"
" // producing the reduction\n"
" const {{IndexType}} outOffset =\n"
" IndexToOffset_{{1000 + dim1}}_get(sliceIndex, &out_info[0]);\n"
" const {{IndexType}} inBaseOffset =\n"
" IndexToOffset_{{1000 + dim2}}_get(sliceIndex, &in_info[0]);\n"
"\n"
" // For each point in reductionSize, reduce into `r`\n"
" {{IndexType}} inOffset = inBaseOffset;\n"
" float r = init;\n"
"\n"
" for ({{IndexType}} i = 0; (int)i < reductionSize; ++i) {\n"
" r = reduceOp(r, modifyOp(in_data[inOffset]));\n"
" inOffset += reductionStride;\n"
" }\n"
"\n"
" // Write out reduced value\n"
" out_data[outOffset] = r;\n"
"}\n"
"\n"
"static inline {{IndexType}} getReduceContigDimSliceIndex() {\n"
" // Each block handles one slice\n"
" return getLinearBlockId();\n"
"}\n"
"\n"
"// Kernel that handles an entire reduction of a slice of a tensor per\n"
"// each block\n"
"kernel void\n"
"THClTensor_reduceContigDim(global TensorInfoCl *out_info,\n"
" global float *out_data,\n"
" global TensorInfoCl *in_info,\n"
" global float *in_data,\n"
" int reductionSize,\n"
" int totalSlices,\n"
" float init,\n"
" local float *smem) {\n"
" const {{IndexType}} sliceIndex = getReduceContigDimSliceIndex();\n"
"\n"
" if ((int)sliceIndex >= totalSlices) {\n"
" return;\n"
" }\n"
"\n"
" // Get the offset in `out` for the reduction\n"
" const {{IndexType}} outOffset =\n"
" IndexToOffset_{{1000 + dim1}}_get(sliceIndex, &out_info[0]);\n"
"\n"
" // Get the base offset in `in` for this block's reduction\n"
" const {{IndexType}} inBaseOffset =\n"
" IndexToOffset_{{1000 + dim2}}_get(sliceIndex, &in_info[0]);\n"
"\n"
" // Each thread in the block will reduce some subset of elements in\n"
" // the slice. The elements are guaranteed contiguous starting at\n"
" // `inBaseOffset`.\n"
" float r = init;\n"
" for ({{IndexType}} i = /*threadIdx.x*/ get_local_id(0); (int)i < reductionSize; i += /*blockDim.x*/ get_local_size(0)) {\n"
" r = reduceOp(r, modifyOp(in_data[inBaseOffset + i]));\n"
" }\n"
"\n"
" // Reduce within the block\n"
"// extern __shared__ float smem[];\n"
" r = reduceBlock(smem, /*blockDim.x*/ get_local_size(0), r, init);\n"
"\n"
" if (/*threadIdx.x*/ get_local_id(0) == 0) {\n"
" // Write out reduced value\n"
" out_data[outOffset] = r;\n"
" }\n"
"}\n"
"\n"
"";
// [[[end]]]
return kernelSource;
}
| 34.263403 | 131 | 0.633444 | [
"vector"
] |
1c2f9ca479f1e81c10ed8ab455f0be348e3c0c74 | 21,780 | cpp | C++ | KeyboardInit.cpp | RadStr/Music-Keyboard | 0c6ec4fc98c215911c5680ed0397b320770849d0 | [
"MIT"
] | 1 | 2019-05-14T20:16:41.000Z | 2019-05-14T20:16:41.000Z | KeyboardInit.cpp | RadStr/Music-Keyboard | 0c6ec4fc98c215911c5680ed0397b320770849d0 | [
"MIT"
] | 21 | 2019-08-07T09:54:13.000Z | 2020-03-06T16:16:20.000Z | KeyboardInit.cpp | RadStr/Music-Keyboard | 0c6ec4fc98c215911c5680ed0397b320770849d0 | [
"MIT"
] | null | null | null | #include "Keyboard.h"
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////
/////// Constructor
//////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Keyboard::Keyboard(SDL_Window *window, SDL_Renderer *renderer) {
std::ofstream& logger = LoggerClass::getLogger();
audioFromFileCVT = nullptr;
audioFromFileBufferIndex = 0;
recordStartTime = 0;
SDL_StopTextInput();
this->window = window;
this->renderer = renderer;
SDL_GetWindowSize(this->window, &windowWidth, &windowHeight);
quit = false;
isRecording = false;
shouldRedrawTextboxes = false;
shouldRedrawKeys = false;
shouldRedrawKeyLabels = false;
keyPressedByMouse = nullptr;
recordStartTime = 0;
keySetWindowTextColor = GlobalConstants::WHITE;
textboxWithFocus = nullptr;
if (window == nullptr) {
throw std::invalid_argument("Keyboard couldn't be initalized because window does not exist.");
}
this->configFileTextbox = ConfigFileTextbox("TEXTBOX WITH PATH TO THE CONFIG FILE");
this->directoryWithFilesTextbox = DirectoryWithFilesTextbox("TEXTBOX WITH PATH TO THE DIRECTORY CONTAINING FILES");
this->recordFilePathTextbox = RecordFilePathTextbox("TEXTBOX WITH PATH TO THE RECORDED FILE");
this->playFileTextbox = PlayFileTextbox("TEXTBOX WITH PATH TO THE FILE TO BE PLAYED");
this->audioPlayingLabel = Label("");
logger << "resizeTextboxes()...: ";
resizeTextboxes();
logger << "resizeTextboxes() done, SDL error: " << SDL_GetError() << std::endl;
logger << "Initializing HW..." << std::endl;
initAudioHW();
logger << "HW initialized, SDL error: " << SDL_GetError() << std::endl;
logger << "Calling initKeyboard()...";
size_t tmp = 0; // Not Ideal
initKeyboard("", &tmp);
logger << "initKeyboard() ended, SDL error was: " << SDL_GetError() << std::endl;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////
/////// Init methods
//////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int Keyboard::initKeyboard(const std::string &configFilename, size_t *totalLinesInFile) {
if (configFilename == "") {
return Keyboard::defaultInit(MAX_KEYS, true);
}
return this->readConfigfile(totalLinesInFile);
}
int Keyboard::defaultInit(size_t totalKeys, bool initAudioBuffer) {
size_t currKey = 0;
int currX = 0;
if (this->keys.size() != totalKeys) {
freeKeys();
this->keys.resize(totalKeys);
for (size_t i = 0; i < this->keys.size(); i++) {
keys[i].initKey();
}
}
else {
for (size_t i = 0; i < this->keys.size(); i++) {
keys[i].freeKey();
}
}
SDL_GetWindowSize(this->window, &windowWidth, &windowHeight);
this->setBlackAndWhiteKeysCounts();
this->setKeySizes();
setRenderer();
this->recordKey.resizeButton(0, 0, this->whiteKeyWidth, 3 * this->blackKeyHeight / 4);
this->recordKey.ID = 0;
this->resizeTextboxes();
size_t li = this->keys.size() - 1; // Last index
if (isWhiteKey(li)) { // If the last key is black then the boundary is a bit different
this->isLastKeyBlack = false;
}
else {
this->isLastKeyBlack = true;
}
for (currKey = 0; currKey < this->keys.size(); currKey++) {
setKeyLocation(&currX, currKey);
this->keys[currKey].isDefaultSound = initAudioBuffer;
this->keys[currKey].ID = currKey;
this->keys[currKey].pressCount = 0;
defaultInitControlKeys(currKey);
// Frequency is the same as rate - samples per second
int ret = SDL_BuildAudioCVT(&this->keys[currKey].audioConvert, this->audioSpec.format, this->audioSpec.channels, this->audioSpec.freq,
this->audioSpec.format, this->audioSpec.channels, this->audioSpec.freq);
this->keys[currKey].audioConvert.buf = nullptr;
if (ret != 0) {
throw std::runtime_error("Same formats aren't the same ... Shouldn't happen");
}
if (initAudioBuffer) {
initKeyWithDefaultAudioNonStatic(&this->keys[currKey]);
}
}
drawWindow();
return 0;
}
void Keyboard::initAudioHW() {
std::ofstream& logger = LoggerClass::getLogger();
logger << "Setting audioSpec...";
this->audioSpec = SDL_AudioSpec();
audioSpec.freq = 22050; // number of samples per second
// Some formats are horrible, for example on my computer AUDIO_U16SYS causes so much crackling it's unlistenable. Even after the remove of reduceCrackling
audioSpec.format = AUDIO_S16SYS; // sample type (here: signed short i.e. 16 bit) // TODO: Later make user choose the format
audioSpec.channels = 1;
audioSpec.samples = CALLBACK_SIZE; // buffer-size
audioSpec.userdata = this; // counter, keeping track of current sample number
audioSpec.callback = audio_callback; // function SDL calls periodically to refill the buffer
logger << "audioSpec set successfully" << std::endl;
logger << "SDL_Error: " << SDL_GetError() << std::endl;
logger << "Opening audio device...";
this->audioDevID = SDL_OpenAudioDevice(nullptr, 0, &this->audioSpec, &this->audioSpec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_CHANNELS_CHANGE);
logger << "Audio device opened" << std::endl;
logger << "SDL_Error: " << SDL_GetError() << std::endl;
for (size_t i = 0; i < this->audioSpec.channels; i++) {
currentlyUnpressedKeys.push_back(std::vector<Sint32>());
}
logger << "Audio device can start playing audio soon...";
SDL_PauseAudioDevice(this->audioDevID, 0); // Start playing the audio
logger << "Callback function will be now regularly called" << std::endl;
logger << "SDL_Error: " << SDL_GetError() << std::endl;
}
void Keyboard::initKeyWithDefaultAudioStatic(Key *key, const SDL_AudioSpec &audioSpecLocal) {
constexpr Uint32 numberOfSeconds = 10;
if (key != nullptr) {
key->freeKey();
generateTone(audioSpecLocal, static_cast<int>(key->ID), numberOfSeconds, &key->audioConvert);
}
}
/////////////////////////////////////////////////// Last method in this file:
constexpr void Keyboard::defaultInitControlKeys(size_t currKey) {
this->recordKey.keysym.mod = KMOD_NUM;
this->recordKey.keysym.scancode = SDL_SCANCODE_KP_MULTIPLY;
this->recordKey.keysym.sym = SDLK_KP_MULTIPLY;
switch (currKey) {
case 0:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_A;
this->keys[currKey].keysym.sym = SDLK_a;
break;
case 1:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_B;
this->keys[currKey].keysym.sym = SDLK_b;
break;
case 2:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_C;
this->keys[currKey].keysym.sym = SDLK_c;
break;
case 3:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_D;
this->keys[currKey].keysym.sym = SDLK_d;
break;
case 4:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_E;
this->keys[currKey].keysym.sym = SDLK_e;
break;
case 5:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F;
this->keys[currKey].keysym.sym = SDLK_f;
break;
case 6:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_G;
this->keys[currKey].keysym.sym = SDLK_g;
break;
case 7:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_H;
this->keys[currKey].keysym.sym = SDLK_h;
break;
case 8:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_I;
this->keys[currKey].keysym.sym = SDLK_i;
break;
case 9:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_J;
this->keys[currKey].keysym.sym = SDLK_j;
break;
case 10:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_K;
this->keys[currKey].keysym.sym = SDLK_k;
break;
case 11:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_L;
this->keys[currKey].keysym.sym = SDLK_l;
break;
case 12:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_M;
this->keys[currKey].keysym.sym = SDLK_m;
break;
case 13:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_N;
this->keys[currKey].keysym.sym = SDLK_n;
break;
case 14:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_O;
this->keys[currKey].keysym.sym = SDLK_o;
break;
case 15:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_P;
this->keys[currKey].keysym.sym = SDLK_p;
break;
case 16:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_Q;
this->keys[currKey].keysym.sym = SDLK_q;
break;
case 17:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_R;
this->keys[currKey].keysym.sym = SDLK_r;
break;
case 18:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_S;
this->keys[currKey].keysym.sym = SDLK_s;
break;
case 19:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_T;
this->keys[currKey].keysym.sym = SDLK_t;
break;
case 20:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_U;
this->keys[currKey].keysym.sym = SDLK_u;
break;
case 21:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_V;
this->keys[currKey].keysym.sym = SDLK_v;
break;
case 22:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_W;
this->keys[currKey].keysym.sym = SDLK_w;
break;
case 23:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_X;
this->keys[currKey].keysym.sym = SDLK_x;
break;
case 24:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_Y;
this->keys[currKey].keysym.sym = SDLK_y;
break;
case 25:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_Z;
this->keys[currKey].keysym.sym = SDLK_z;
break;
case 26:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_1;
this->keys[currKey].keysym.sym = SDLK_1;
break;
case 27:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_2;
this->keys[currKey].keysym.sym = SDLK_2;
break;
case 28:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_3;
this->keys[currKey].keysym.sym = SDLK_3;
break;
case 29:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_4;
this->keys[currKey].keysym.sym = SDLK_4;
break;
case 30:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_5;
this->keys[currKey].keysym.sym = SDLK_5;
break;
case 31:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_6;
this->keys[currKey].keysym.sym = SDLK_6;
break;
case 32:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_7;
this->keys[currKey].keysym.sym = SDLK_7;
break;
case 33:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_8;
this->keys[currKey].keysym.sym = SDLK_8;
break;
case 34:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_9;
this->keys[currKey].keysym.sym = SDLK_9;
break;
case 35:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_0;
this->keys[currKey].keysym.sym = SDLK_0;
break;
case 36:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F1;
this->keys[currKey].keysym.sym = SDLK_F1;
break;
case 37:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F2;
this->keys[currKey].keysym.sym = SDLK_F2;
break;
case 38:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F3;
this->keys[currKey].keysym.sym = SDLK_F3;
break;
case 39:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F4;
this->keys[currKey].keysym.sym = SDLK_F4;
break;
case 40:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F5;
this->keys[currKey].keysym.sym = SDLK_F5;
break;
case 41:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F6;
this->keys[currKey].keysym.sym = SDLK_F6;
break;
case 42:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F7;
this->keys[currKey].keysym.sym = SDLK_F7;
break;
case 43:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F8;
this->keys[currKey].keysym.sym = SDLK_F8;
break;
case 44:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F9;
this->keys[currKey].keysym.sym = SDLK_F9;
break;
case 45:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F10;
this->keys[currKey].keysym.sym = SDLK_F10;
break;
case 46:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F11;
this->keys[currKey].keysym.sym = SDLK_F11;
break;
case 47:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_KP_0;
this->keys[currKey].keysym.sym = SDLK_KP_0;
break;
case 48:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_KP_1;
this->keys[currKey].keysym.sym = SDLK_KP_1;
break;
case 49:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_KP_2;
this->keys[currKey].keysym.sym = SDLK_KP_2;
break;
case 50:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_KP_3;
this->keys[currKey].keysym.sym = SDLK_KP_3;
break;
case 51:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_KP_4;
this->keys[currKey].keysym.sym = SDLK_KP_4;
break;
case 52:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_KP_5;
this->keys[currKey].keysym.sym = SDLK_KP_5;
break;
case 53:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_KP_6;
this->keys[currKey].keysym.sym = SDLK_KP_6;
break;
case 54:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_KP_7;
this->keys[currKey].keysym.sym = SDLK_KP_7;
break;
case 55:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_KP_8;
this->keys[currKey].keysym.sym = SDLK_KP_8;
break;
case 56:
this->keys[currKey].keysym.mod = KMOD_NUM;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_KP_9;
this->keys[currKey].keysym.sym = SDLK_KP_9;
break;
case 57:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_A;
this->keys[currKey].keysym.sym = SDLK_a;
break;
case 58:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_B;
this->keys[currKey].keysym.sym = SDLK_b;
break;
case 59:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_C;
this->keys[currKey].keysym.sym = SDLK_c;
break;
case 60:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_D;
this->keys[currKey].keysym.sym = SDLK_d;
break;
case 61:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_E;
this->keys[currKey].keysym.sym = SDLK_e;
break;
case 62:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_F;
this->keys[currKey].keysym.sym = SDLK_f;
break;
case 63:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_G;
this->keys[currKey].keysym.sym = SDLK_g;
break;
case 64:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_H;
this->keys[currKey].keysym.sym = SDLK_h;
break;
case 65:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_I;
this->keys[currKey].keysym.sym = SDLK_i;
break;
case 66:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_J;
this->keys[currKey].keysym.sym = SDLK_j;
break;
case 67:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_K;
this->keys[currKey].keysym.sym = SDLK_k;
break;
case 68:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_L;
this->keys[currKey].keysym.sym = SDLK_l;
break;
case 69:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_M;
this->keys[currKey].keysym.sym = SDLK_m;
break;
case 70:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_N;
this->keys[currKey].keysym.sym = SDLK_n;
break;
case 71:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_O;
this->keys[currKey].keysym.sym = SDLK_o;
break;
case 72:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_P;
this->keys[currKey].keysym.sym = SDLK_p;
break;
case 73:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_Q;
this->keys[currKey].keysym.sym = SDLK_q;
break;
case 74:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_R;
this->keys[currKey].keysym.sym = SDLK_r;
break;
case 75:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_S;
this->keys[currKey].keysym.sym = SDLK_s;
break;
case 76:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_T;
this->keys[currKey].keysym.sym = SDLK_t;
break;
case 77:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_U;
this->keys[currKey].keysym.sym = SDLK_u;
break;
case 78:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_V;
this->keys[currKey].keysym.sym = SDLK_v;
break;
case 79:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_W;
this->keys[currKey].keysym.sym = SDLK_w;
break;
case 80:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_X;
this->keys[currKey].keysym.sym = SDLK_x;
break;
case 81:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_Y;
this->keys[currKey].keysym.sym = SDLK_y;
break;
case 82:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_Z;
this->keys[currKey].keysym.sym = SDLK_z;
break;
case 83:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_1;
this->keys[currKey].keysym.sym = SDLK_1;
break;
case 84:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_2;
this->keys[currKey].keysym.sym = SDLK_2;
break;
case 85:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_3;
this->keys[currKey].keysym.sym = SDLK_3;
break;
case 86:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_4;
this->keys[currKey].keysym.sym = SDLK_4;
break;
case 87:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_5;
this->keys[currKey].keysym.sym = SDLK_5;
break;
default:
this->keys[currKey].keysym.mod = KMOD_NONE;
this->keys[currKey].keysym.scancode = SDL_SCANCODE_5;
this->keys[currKey].keysym.sym = SDLK_5;
break;
}
} | 35.072464 | 171 | 0.664233 | [
"vector"
] |
1c33b60823796ac97de22db49ceaa3d44a28c8d9 | 886 | cpp | C++ | code/test/triangulation.cpp | Brunovsky/competitive | 41cf49378e430ca20d844f97c67aa5059ab1e973 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | code/test/triangulation.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | code/test/triangulation.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include "test_utils.hpp"
#include "geometry/triangulation.hpp"
#include "geometry/utils2d.hpp"
#include "geometry/generator2d.hpp"
void stress_test_constrained_triangulation() {
LOOP_FOR_DURATION_OR_RUNS_TRACKED (30s, now, 20'000, runs) {
print_time(now, 30s, "stress constrained triangulation {} runs", runs);
int N = rand_unif<int>(5, 150);
int S = rand_unif<int>(5, min(70, 2 * N));
auto dist = rand_point_distribution();
auto pts = generate_points(N, dist, 0);
auto segments = non_overlapping_sample(pts, S, {}, false);
Wedge* edge = constrained_triangulation(pts, segments);
auto faces = Wedge::extract_faces(edge);
assert(check_constrained_triangulation(faces, pts, segments));
Wedge::release();
}
}
int main() {
RUN_BLOCK(stress_test_constrained_triangulation());
return 0;
}
| 30.551724 | 79 | 0.671558 | [
"geometry"
] |
1c36e09364260718722db7af985b97216a19fa91 | 1,478 | cpp | C++ | LeetCode/C++/205. Isomorphic Strings.cpp | shreejitverma/GeeksforGeeks | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-18T05:14:28.000Z | 2022-03-08T07:00:08.000Z | LeetCode/C++/205. Isomorphic Strings.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 6 | 2022-01-13T04:31:04.000Z | 2022-03-12T01:06:16.000Z | LeetCode/C++/205. Isomorphic Strings.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-14T19:53:53.000Z | 2022-02-18T05:14:30.000Z | //Runtime: 24 ms, faster than 8.57% of C++ online submissions for Isomorphic Strings.
//Memory Usage: 9.3 MB, less than 7.37% of C++ online submissions for Isomorphic Strings.
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.size() != t.size()) return false;
//need to ensure 1-to-1 mapping,
//so we need to maps
map<char, char> m, im;
set<char> values;
for(int i = 0; i < s.size(); i++){
if(m.find(s[i]) == m.end()){
m[s[i]] = t[i];
}else if(m[s[i]] != t[i]){
return false;
}
if(im.find(t[i]) == im.end()){
im[t[i]] = s[i];
}else if(im[t[i]] != s[i]){
return false;
}
}
return true;
}
};
//https://leetcode.com/problems/isomorphic-strings/discuss/57796/My-6-lines-solution
/**
indirect mapping
**/
//Runtime: 16 ms, faster than 36.56% of C++ online submissions for Isomorphic Strings.
//Memory Usage: 9 MB, less than 32.11% of C++ online submissions for Isomorphic Strings.
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<int> ms(128, 0), mt(128, 0);
for(int i = 0; i < s.size(); i++){
if(ms[s[i]] != mt[t[i]]){
return false;
}
ms[s[i]] = i+1;
mt[t[i]] = i+1;
}
return true;
}
};
| 27.37037 | 89 | 0.485792 | [
"vector"
] |
1c49f4ec3cec883bac01df9eed737f46b5fbb7f6 | 18,809 | cpp | C++ | src/mongo/db/update/delta_executor_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/update/delta_executor_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/update/delta_executor_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2020-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/bson/json.h"
#include "mongo/bson/mutable/document.h"
#include "mongo/db/update/delta_executor.h"
#include "mongo/logv2/log.h"
#include "mongo/unittest/unittest.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest
namespace mongo {
namespace {
TEST(DeltaExecutorTest, Delete) {
BSONObj preImage(fromjson("{f1: {a: {b: {c: 1}, c: 1}}}"));
UpdateIndexData indexData;
constexpr bool mustCheckExistenceForInsertOperations = true;
indexData.addPath(FieldRef("p.a.b"));
indexData.addPath(FieldRef("f1.a.b"));
FieldRefSet fieldRefSet;
{
// When a path in the diff is a prefix of index path.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
DeltaExecutor test(fromjson("{d: {f1: false, f2: false, f3: false}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(), BSONObj());
ASSERT(result.indexesAffected);
}
{
// When a path in the diff is same as index path.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
DeltaExecutor test(fromjson("{sf1: {sa: {d: {p: false, c: false, b: false}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {}}}"));
ASSERT(result.indexesAffected);
}
{
// When the index path is a prefix of a path in the diff.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {sa: {sb: {d: {c: false}}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {b: {}, c: 1}}}"));
ASSERT(result.indexesAffected);
}
{
// With common parent, but path diverges.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {sa: {d: {c: false}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {b: {c: 1}}}}"));
ASSERT(!result.indexesAffected);
}
}
TEST(DeltaExecutorTest, Update) {
BSONObj preImage(fromjson("{f1: {a: {b: {c: 1}, c: 1}}}"));
UpdateIndexData indexData;
constexpr bool mustCheckExistenceForInsertOperations = true;
indexData.addPath(FieldRef("p.a.b"));
indexData.addPath(FieldRef("f1.a.b"));
FieldRefSet fieldRefSet;
{
// When a path in the diff is a prefix of index path.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
DeltaExecutor test(fromjson("{u: {f1: false, f2: false, f3: false}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: false, f2: false, f3: false}"));
ASSERT(result.indexesAffected);
}
{
// When a path in the diff is same as index path.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {sa: {u: {p: false, c: false, b: false}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {b: false, c: false, p: false}}}"));
ASSERT(result.indexesAffected);
}
{
// When the index path is a prefix of a path in the diff.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {sa: {sb: {u: {c: false}}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {b: {c: false}, c: 1}}}"));
ASSERT(result.indexesAffected);
}
{
// With common parent, but path diverges.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {sa: {u: {c: false}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {b: {c: 1}, c: false}}}"));
ASSERT(!result.indexesAffected);
}
}
TEST(DeltaExecutorTest, Insert) {
UpdateIndexData indexData;
constexpr bool mustCheckExistenceForInsertOperations = true;
indexData.addPath(FieldRef("p.a.b"));
// 'UpdateIndexData' will canonicalize the path and remove all numeric components. So the '2'
// and '33' components should not matter.
indexData.addPath(FieldRef("f1.2.a.33.b"));
FieldRefSet fieldRefSet;
{
// When a path in the diff is a prefix of index path.
auto doc = mutablebson::Document(BSONObj());
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
DeltaExecutor test(fromjson("{i: {f1: false, f2: false, f3: false}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: false, f2: false, f3: false}"));
ASSERT(result.indexesAffected);
}
{
// When a path in the diff is same as index path.
auto doc = mutablebson::Document(fromjson("{f1: {a: {c: true}}}}"));
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {sa: {i: {p: false, c: false, b: false}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {p: false, c: false, b: false}}}"));
ASSERT(result.indexesAffected);
}
{
// When the index path is a prefix of a path in the diff.
auto doc = mutablebson::Document(fromjson("{f1: {a: {b: {c: {e: 1}}}}}"));
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {sa: {sb: {sc: {i : {d: 2} }}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {b: {c: {e: 1, d: 2}}}}}"));
ASSERT(result.indexesAffected);
}
{
// With common parent, but path diverges.
auto doc = mutablebson::Document(fromjson("{f1: {a: {b: {c: 1}}}}"));
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {sa: {i: {c: 2}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {b: {c: 1}, c: 2}}}"));
ASSERT(!result.indexesAffected);
}
}
TEST(DeltaExecutorTest, InsertNumericFieldNamesTopLevel) {
BSONObj preImage;
UpdateIndexData indexData;
constexpr bool mustCheckExistenceForInsertOperations = true;
indexData.addPath(FieldRef{"1"});
FieldRefSet fieldRefSet;
// Insert numeric fields at the top level, which means they are guaranteed to be object key
// names (rather than possibly being indices of an array).
{
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
DeltaExecutor test(fromjson("{i: {'0': false, '1': false, '2': false}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{'0': false, '1': false, '2': false}"));
ASSERT(result.indexesAffected);
}
{
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
DeltaExecutor test(fromjson("{i: {'0': false, '2': false}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{'0': false, '2': false}"));
ASSERT(!result.indexesAffected);
}
}
TEST(DeltaExecutorTest, InsertNumericFieldNamesNested) {
BSONObj preImage{fromjson("{a: {}}")};
UpdateIndexData indexData;
constexpr bool mustCheckExistenceForInsertOperations = true;
indexData.addPath(FieldRef{"a.1"});
FieldRefSet fieldRefSet;
// Insert numeric fields not at the top level, which means they may possibly be indices of an
// array.
{
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
DeltaExecutor test(fromjson("{sa: {i: {'0': false, '1': false, '2': false}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{a: {'0': false, '1': false, '2': false}}"));
ASSERT(result.indexesAffected);
}
{
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
DeltaExecutor test(fromjson("{sa: {i: {'0': false, '2': false}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{a: {'0': false, '2': false}}"));
ASSERT(result.indexesAffected);
}
}
TEST(DeltaExecutorTest, ArraysInIndexPath) {
BSONObj preImage(fromjson("{f1: [{a: {b: {c: 1}, c: 1}}, 1]}"));
UpdateIndexData indexData;
constexpr bool mustCheckExistenceForInsertOperations = true;
indexData.addPath(FieldRef("p.a.b"));
// Numeric components will be ignored, so they should not matter.
indexData.addPath(FieldRef("f1.9.a.10.b"));
FieldRefSet fieldRefSet;
{
// Test resize.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
DeltaExecutor test(fromjson("{sf1: {a: true, l: 1}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: [{a: {b: {c: 1}, c: 1}}]}"));
ASSERT(result.indexesAffected);
}
{
// When the index path is a prefix of a path in the diff and also involves numeric
// components along the way. The numeric components should always be ignored.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {a: true, s0: {sa: {sb: {i: {d: 1} }}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: [{a: {b: {c: 1, d: 1}, c: 1}}, 1]}"));
ASSERT(result.indexesAffected);
}
{
// When inserting a sub-object into array, and the sub-object diverges from the index path.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {a: true, u2: {b: 1}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: [{a: {b: {c: 1}, c: 1}}, 1, {b:1}]}"));
ASSERT(result.indexesAffected);
}
{
// When a common array path element is updated, but the paths diverge at the last element.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {a: true, s0: {sa: {d: {c: false} }}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: [{a: {b: {c: 1}}}, 1]}"));
ASSERT(!result.indexesAffected);
}
}
TEST(DeltaExecutorTest, ArraysAfterIndexPath) {
BSONObj preImage(fromjson("{f1: {a: {b: [{c: 1}, 2]}}}"));
UpdateIndexData indexData;
constexpr bool mustCheckExistenceForInsertOperations = true;
indexData.addPath(FieldRef("p.a.b"));
// 'UpdateIndexData' will canonicalize the path and remove all numeric components. So the '9'
// and '10' components should not matter.
indexData.addPath(FieldRef("f1.9.a.10"));
FieldRefSet fieldRefSet;
{
// Test resize.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
DeltaExecutor test(fromjson("{sf1: {sa: {sb: {a: true, l: 1}}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {b: [{c: 1}]}}}"));
ASSERT(result.indexesAffected);
}
{
// Updating a sub-array element.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {sa: {sb: {a: true, s0: {u: {c: 2}} }}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {b: [{c: 2}, 2]}}}"));
ASSERT(result.indexesAffected);
}
{
// Updating an array element.
auto doc = mutablebson::Document(preImage);
UpdateExecutor::ApplyParams params(doc.root(), fieldRefSet);
params.indexData = &indexData;
auto test = DeltaExecutor(fromjson("{sf1: {sa: {sb: {a: true, u0: 1 }}}}"),
mustCheckExistenceForInsertOperations);
auto result = test.applyUpdate(params);
ASSERT_BSONOBJ_BINARY_EQ(params.element.getDocument().getObject(),
fromjson("{f1: {a: {b: [1, 2]}}}"));
ASSERT(result.indexesAffected);
}
}
} // namespace
} // namespace mongo
| 48.104859 | 99 | 0.609549 | [
"object"
] |
1c4c945b67ad94c9124f34c4b2b842575b85195f | 8,894 | hpp | C++ | src/mts/pes.hpp | steinwurf/mts | c0dc4fc564469dee3ddf8ef3968208df33ea650b | [
"BSD-3-Clause"
] | 2 | 2017-12-09T20:08:43.000Z | 2020-01-13T13:01:13.000Z | src/mts/pes.hpp | steinwurf/mts | c0dc4fc564469dee3ddf8ef3968208df33ea650b | [
"BSD-3-Clause"
] | 1 | 2019-02-26T14:48:55.000Z | 2019-02-26T14:48:55.000Z | src/mts/pes.hpp | steinwurf/mts | c0dc4fc564469dee3ddf8ef3968208df33ea650b | [
"BSD-3-Clause"
] | 2 | 2017-12-09T20:08:00.000Z | 2019-12-03T02:09:39.000Z | // Copyright (c) Steinwurf ApS 2017.
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <cstdint>
#include <cassert>
#include <vector>
#include <memory>
#include <endian/big_endian.hpp>
#include <bnb/stream_reader.hpp>
#include <boost/optional.hpp>
#include "helper.hpp"
#include "stream_type.hpp"
namespace mts
{
// packetized elementary stream
class pes
{
public:
static boost::optional<pes> parse(
const uint8_t* data, uint64_t size, std::error_code& error)
{
bnb::stream_reader<endian::big_endian> reader(data, size, error);
return parse(reader);
}
static boost::optional<pes> parse(
bnb::stream_reader<endian::big_endian>& reader)
{
mts::pes pes;
reader.read_bytes<3>(pes.m_packet_start_code_prefix);
reader.read_bytes<1>(pes.m_stream_id);
uint16_t read_packet_length = 0;
reader.read_bytes<2>(read_packet_length);
if (reader.error())
return boost::none;
uint64_t bytes_to_skip = read_packet_length;
// A value of 0 indicates that the PES packet length is neither
// specified nor bounded and is allowed only in PES packets whose
// payload consists of bytes from a video elementary stream contained
// in transport stream packets.
//
// From ISO/IEC 13818-1:2013 p. 35
if (bytes_to_skip == 0)
{
bytes_to_skip = reader.remaining_size();
}
auto packet_reader = reader.skip(bytes_to_skip);
if (pes.m_stream_id != 0xbc && // program_stream_map
pes.m_stream_id != 0xbe && // padding_stream
pes.m_stream_id != 0xbf && // private_stream_2
pes.m_stream_id != 0xf0 && // ECM
pes.m_stream_id != 0xf1 && // EMM
pes.m_stream_id != 0xff && // program_stream_directory
pes.m_stream_id != 0xf2 && // DSMCC
pes.m_stream_id != 0xf8) // H.222.1 type E
{
packet_reader
.read_bits<bitter::u8, bitter::msb0, 2, 2, 1, 1, 1, 1>()
.get<0>().expect_eq(0x02)
.get<1>(pes.m_scrambling_control)
.get<2>(pes.m_priority)
.get<3>(pes.m_data_alignment_indicator)
.get<4>(pes.m_copyright)
.get<5>(pes.m_original_or_copy);
packet_reader
.read_bits<bitter::u8, bitter::msb0, 2, 1, 1, 1, 1, 1, 1>()
.get<0>(pes.m_pts_dts_flags).expect_ne(0x01)
.get<1>(pes.m_escr_flag)
.get<2>(pes.m_es_rate_flag)
.get<3>(pes.m_dsm_trick_mode_flag)
.get<4>(pes.m_additional_copy_info_flag)
.get<5>(pes.m_crc_flag)
.get<6>(pes.m_extension_flag);
uint8_t header_data_length = 0;
packet_reader.read_bytes<1>(header_data_length);
auto header_reader = packet_reader.skip(header_data_length);
if (pes.has_presentation_timestamp())
{
uint8_t ts_32_30 = 0;
uint16_t ts_29_15 = 0;
uint16_t ts_14_0 = 0;
header_reader
.read_bits<bitter::u40, bitter::msb0, 4, 3, 1, 15, 1, 15, 1>()
.get<1>(ts_32_30)
.get<3>(ts_29_15)
.get<5>(ts_14_0);
pes.m_pts = helper::read_timestamp(ts_32_30, ts_29_15, ts_14_0);
}
if (pes.has_decoding_timestamp())
{
uint8_t ts_32_30 = 0;
uint16_t ts_29_15 = 0;
uint16_t ts_14_0 = 0;
header_reader
.read_bits<bitter::u40, bitter::msb0, 4, 3, 1, 15, 1, 15, 1>()
.get<1>(ts_32_30)
.get<3>(ts_29_15)
.get<5>(ts_14_0);
pes.m_dts = helper::read_timestamp(ts_32_30, ts_29_15, ts_14_0);
}
if (pes.m_escr_flag)
{
uint8_t escr_32_30 = 0;
uint16_t escr_29_15 = 0;
uint16_t escr_14_0 = 0;
uint16_t escr_base = 0;
header_reader
.read_bits<bitter::u48, bitter::msb0, 2, 3, 1, 15, 1, 15, 1, 9, 1>()
.get<1>(escr_32_30)
.get<3>(escr_29_15)
.get<5>(escr_14_0)
.get<7>(escr_base);
pes.m_escr = helper::read_timestamp(
escr_32_30, escr_29_15, escr_14_0) * 300 + escr_base;
}
if (pes.m_es_rate_flag)
{
header_reader
.read_bits<bitter::u24, bitter::msb0, 1, 22, 1>()
.get<1>(pes.m_es_rate);
}
if (pes.m_dsm_trick_mode_flag)
{
header_reader
.read_bits<bitter::u8, bitter::msb0, 3, 5>()
.get<0>(pes.m_trick_mode_control)
.get<1>(pes.m_trick_mode_data);
}
if (pes.m_additional_copy_info_flag)
{
header_reader
.read_bits<bitter::u8, bitter::msb0, 1, 7>()
.get<1>(pes.m_additional_copy_info);
}
if (pes.m_crc_flag)
{
header_reader.read_bytes<2>(pes.m_previous_crc);
}
}
if (reader.error())
return boost::none;
pes.m_payload_data = packet_reader.remaining_data();
pes.m_payload_size = (uint32_t)packet_reader.remaining_size();
return pes;
}
public:
bool has_presentation_timestamp() const
{
return (m_pts_dts_flags & 0x02) == 0x02;
}
bool has_decoding_timestamp() const
{
return m_pts_dts_flags == 0x03;
}
bool has_elementary_stream_clock_reference() const
{
return m_escr_flag;
}
uint32_t packet_start_code_prefix() const
{
return m_packet_start_code_prefix;
}
uint8_t stream_id() const
{
return m_stream_id;
}
uint8_t scrambling_control() const
{
return m_scrambling_control;
}
uint8_t priority() const
{
return m_priority;
}
bool data_alignment_indicator() const
{
return m_data_alignment_indicator;
}
bool copyright() const
{
return m_copyright;
}
bool original_or_copy() const
{
return m_original_or_copy;
}
bool has_es_rate() const
{
return m_es_rate_flag;
}
bool has_dsm_trick_mode() const
{
return m_dsm_trick_mode_flag;
}
bool has_additional_copy_info() const
{
return m_additional_copy_info_flag;
}
bool has_previous_crc() const
{
return m_crc_flag;
}
bool has_extension() const
{
return m_extension_flag;
}
uint64_t presentation_timestamp() const
{
assert(has_presentation_timestamp());
return m_pts;
}
uint64_t decoding_timestamp() const
{
assert(has_decoding_timestamp());
return m_dts;
}
uint64_t elementary_stream_clock_reference() const
{
assert(has_elementary_stream_clock_reference());
return m_escr;
}
uint32_t es_rate() const
{
assert(has_es_rate());
return m_es_rate;
}
uint8_t trick_mode_control() const
{
assert(has_dsm_trick_mode());
return m_trick_mode_control;
}
uint8_t trick_mode_data() const
{
assert(has_dsm_trick_mode());
return m_trick_mode_data;
}
uint8_t additional_copy_info() const
{
assert(has_additional_copy_info());
return m_additional_copy_info;
}
uint16_t previous_crc() const
{
assert(has_previous_crc());
return m_previous_crc;
}
const uint8_t* payload_data() const
{
return m_payload_data;
}
uint32_t payload_size() const
{
return m_payload_size;
}
private:
uint32_t m_packet_start_code_prefix = 0;
uint8_t m_stream_id = 0;
uint8_t m_scrambling_control = 0;
uint8_t m_priority = 0;
bool m_data_alignment_indicator = false;
bool m_copyright = false;
bool m_original_or_copy = false;
uint8_t m_pts_dts_flags = 0;
bool m_escr_flag = false;
bool m_es_rate_flag = false;
bool m_dsm_trick_mode_flag = false;
bool m_additional_copy_info_flag = false;
bool m_crc_flag = false;
bool m_extension_flag = false;
uint64_t m_pts = 0;
uint64_t m_dts = 0;
uint64_t m_escr = 0;
uint32_t m_es_rate = 0;
uint8_t m_trick_mode_control = 0;
uint8_t m_trick_mode_data = 0;
uint8_t m_additional_copy_info = 0;
uint16_t m_previous_crc = 0;
const uint8_t* m_payload_data = nullptr;
uint32_t m_payload_size = 0;
};
} | 25.557471 | 84 | 0.570272 | [
"vector"
] |
1c59b05958d4a3d19b7e6a16520c7bda873548f5 | 988 | cpp | C++ | Online Judges/UVA/11463/3415632_AC_55ms_0kB.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | 4 | 2017-02-20T17:41:14.000Z | 2019-07-15T14:15:34.000Z | Online Judges/UVA/11463/3415632_AC_55ms_0kB.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | null | null | null | Online Judges/UVA/11463/3415632_AC_55ms_0kB.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 9999999
vector<int>e[101];
int ok[101],sv[101][101],grp[101][101];
int ts,n,p,st,en,cs=0;
int floyed()
{
for(int k=0; k<n; k++)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
sv[i][j]=min(sv[i][k]+sv[k][j],sv[i][j]);
}
}
}
}
int main()
{
cin>>ts;
while(ts--)
{
cin>>n>>p;
//memset(grp,0,sizeof grp);
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
sv[i][j]=(i==j)?0:inf;
}
}
while(p--)
{
int u,v;
cin>>u>>v;
sv[u][v]=1;
sv[v][u]=1;
}
cin>>st>>en;
floyed();
int mx=0;
for(int i=0;i<n;i++)
{
mx=max(mx,sv[st][i]+sv[i][en]);
}
cout<<"Case "<<++cs<<": "<<mx<<endl;
}
}
| 18.641509 | 57 | 0.346154 | [
"vector"
] |
1c5afc410e47440a59f1abba77ac6b7af0643643 | 10,574 | cxx | C++ | main/store/source/storlckb.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/store/source/storlckb.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/store/source/storlckb.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_store.hxx"
#include "storlckb.hxx"
#include "sal/types.h"
#include "sal/macros.h"
#include "rtl/string.h"
#include "rtl/ref.hxx"
#include "osl/mutex.hxx"
#include "store/types.h"
#include "object.hxx"
#include "storbase.hxx"
#include "stordata.hxx"
#include "storpage.hxx"
using namespace store;
/*========================================================================
*
* OStoreLockBytes implementation.
*
*======================================================================*/
const sal_uInt32 OStoreLockBytes::m_nTypeId = sal_uInt32(0x94190310);
/*
* OStoreLockBytes.
*/
OStoreLockBytes::OStoreLockBytes (void)
: m_xManager (),
m_xNode (),
m_bWriteable (false)
{
}
/*
* ~OStoreLockBytes.
*/
OStoreLockBytes::~OStoreLockBytes (void)
{
if (m_xManager.is())
{
if (m_xNode.is())
{
OStorePageDescriptor aDescr (m_xNode->m_aDescr);
if (m_bWriteable)
m_xManager->releasePage (aDescr, store_AccessReadWrite);
else
m_xManager->releasePage (aDescr, store_AccessReadOnly);
}
}
}
/*
* isKindOf.
*/
sal_Bool SAL_CALL OStoreLockBytes::isKindOf (sal_uInt32 nTypeId)
{
return (nTypeId == m_nTypeId);
}
/*
* create.
*/
storeError OStoreLockBytes::create (
OStorePageManager *pManager,
rtl_String *pPath,
rtl_String *pName,
storeAccessMode eMode)
{
rtl::Reference<OStorePageManager> xManager (pManager);
if (!xManager.is())
return store_E_InvalidAccess;
if (!(pPath && pName))
return store_E_InvalidParameter;
OStoreDirectoryPageObject aPage;
storeError eErrCode = xManager->iget (
aPage, STORE_ATTRIB_ISFILE,
pPath, pName, eMode);
if (eErrCode != store_E_None)
return eErrCode;
if (!(aPage.attrib() & STORE_ATTRIB_ISFILE))
{
// No ISFILE in older versions (backward compatibility).
if (aPage.attrib() & STORE_ATTRIB_ISLINK)
return store_E_NotFile;
}
// ...
inode_holder_type xNode (aPage.get());
if (eMode != store_AccessReadOnly)
eErrCode = xManager->acquirePage (xNode->m_aDescr, store_AccessReadWrite);
else
eErrCode = xManager->acquirePage (xNode->m_aDescr, store_AccessReadOnly);
if (eErrCode != store_E_None)
return eErrCode;
// ...
m_xManager = xManager;
m_xNode = xNode;
m_bWriteable = (eMode != store_AccessReadOnly);
// Check for truncation.
if (eMode == store_AccessCreate)
{
// Truncate to zero length.
eErrCode = setSize(0);
}
return eErrCode;
}
/*
* readAt.
*/
storeError OStoreLockBytes::readAt (
sal_uInt32 nOffset,
void *pBuffer,
sal_uInt32 nBytes,
sal_uInt32 &rnDone)
{
rnDone = 0;
if (!m_xManager.is())
return store_E_InvalidAccess;
if (!pBuffer)
return store_E_InvalidParameter;
if (!nBytes)
return store_E_None;
// Acquire exclusive access.
osl::MutexGuard aGuard (*m_xManager);
// Determine data length.
OStoreDirectoryPageObject aPage (m_xNode.get());
sal_uInt32 nDataLen = aPage.dataLength();
if ((nOffset + nBytes) > nDataLen)
nBytes = nDataLen - nOffset;
// Read data.
OStoreDataPageObject aData;
sal_uInt8 *pData = (sal_uInt8*)pBuffer;
while ((0 < nBytes) && (nOffset < nDataLen))
{
// Determine 'Offset' scope.
inode::ChunkScope eScope = m_xNode->scope (nOffset);
if (eScope == inode::SCOPE_INTERNAL)
{
// Read from inode page (internal scope).
inode::ChunkDescriptor aDescr (
nOffset, m_xNode->capacity());
sal_uInt32 nLength = sal_uInt32(aDescr.m_nLength);
nLength = SAL_MIN(nLength, nBytes);
memcpy (
&pData[rnDone],
&m_xNode->m_pData[aDescr.m_nOffset],
nLength);
// Adjust counters.
rnDone += nLength;
nOffset += nLength;
nBytes -= nLength;
}
else
{
// Read from data page (external scope).
inode::ChunkDescriptor aDescr (
nOffset - m_xNode->capacity(), OStoreDataPageData::capacity(m_xNode->m_aDescr)); // @@@
sal_uInt32 nLength = sal_uInt32(aDescr.m_nLength);
nLength = SAL_MIN(nLength, nBytes);
storeError eErrCode = aPage.read (aDescr.m_nPage, aData, *m_xManager);
if (eErrCode != store_E_None)
{
if (eErrCode != store_E_NotExists)
return eErrCode;
memset (
&pData[rnDone],
0,
nLength);
}
else
{
PageHolderObject< data > xData (aData.makeHolder<data>());
memcpy (
&pData[rnDone],
&xData->m_pData[aDescr.m_nOffset],
nLength);
}
// Adjust counters.
rnDone += nLength;
nOffset += nLength;
nBytes -= nLength;
}
}
// Done.
return store_E_None;
}
/*
* writeAt.
*/
storeError OStoreLockBytes::writeAt (
sal_uInt32 nOffset,
const void *pBuffer,
sal_uInt32 nBytes,
sal_uInt32 &rnDone)
{
rnDone = 0;
if (!m_xManager.is())
return store_E_InvalidAccess;
if (!m_bWriteable)
return store_E_AccessViolation;
if (!pBuffer)
return store_E_InvalidParameter;
if (!nBytes)
return store_E_None;
// Acquire exclusive access.
osl::MutexGuard aGuard (*m_xManager);
// Write data.
OStoreDirectoryPageObject aPage (m_xNode.get());
const sal_uInt8 *pData = (const sal_uInt8*)pBuffer;
storeError eErrCode = store_E_None;
while (nBytes > 0)
{
// Determine 'Offset' scope.
inode::ChunkScope eScope = m_xNode->scope (nOffset);
if (eScope == inode::SCOPE_INTERNAL)
{
// Write to inode page (internal scope).
inode::ChunkDescriptor aDescr (
nOffset, m_xNode->capacity());
sal_uInt32 nLength = sal_uInt32(aDescr.m_nLength);
nLength = SAL_MIN(nLength, nBytes);
memcpy (
&m_xNode->m_pData[aDescr.m_nOffset],
&pData[rnDone], nLength);
// Mark inode dirty.
aPage.touch();
// Adjust counters.
rnDone += nLength;
nOffset += nLength;
nBytes -= nLength;
// Adjust data length.
if (aPage.dataLength() < nOffset)
aPage.dataLength (nOffset);
}
else
{
// Write to data page (external scope).
OStoreDataPageObject aData;
inode::ChunkDescriptor aDescr (
nOffset - m_xNode->capacity(), OStoreDataPageData::capacity(m_xNode->m_aDescr)); // @@@
sal_uInt32 nLength = sal_uInt32(aDescr.m_nLength);
if ((aDescr.m_nOffset > 0) || (nBytes < nLength))
{
// Unaligned. Need to load/create data page.
// @@@ loadOrCreate()
eErrCode = aPage.read (aDescr.m_nPage, aData, *m_xManager);
if (eErrCode != store_E_None)
{
if (eErrCode != store_E_NotExists)
return eErrCode;
eErrCode = aData.construct<data>(m_xManager->allocator());
if (eErrCode != store_E_None)
return eErrCode;
}
}
PageHolderObject< data > xData (aData.makeHolder<data>());
if (!xData.is())
{
eErrCode = aData.construct<data>(m_xManager->allocator());
if (eErrCode != store_E_None)
return eErrCode;
xData = aData.makeHolder<data>();
}
// Modify data page.
nLength = SAL_MIN(nLength, nBytes);
memcpy (
&xData->m_pData[aDescr.m_nOffset],
&pData[rnDone], nLength);
// Save data page.
eErrCode = aPage.write (aDescr.m_nPage, aData, *m_xManager);
if (eErrCode != store_E_None)
return eErrCode;
// Adjust counters.
rnDone += nLength;
nOffset += nLength;
nBytes -= nLength;
// Adjust data length.
if (aPage.dataLength() < nOffset)
aPage.dataLength (nOffset);
}
}
// Check for modified inode.
if (aPage.dirty())
return m_xManager->saveObjectAt (aPage, aPage.location());
else
return store_E_None;
}
/*
* flush.
*/
storeError OStoreLockBytes::flush (void)
{
if (!m_xManager.is())
return store_E_InvalidAccess;
return m_xManager->flush();
}
/*
* setSize.
*/
storeError OStoreLockBytes::setSize (sal_uInt32 nSize)
{
if (!m_xManager.is())
return store_E_InvalidAccess;
if (!m_bWriteable)
return store_E_AccessViolation;
// Acquire exclusive access.
osl::MutexGuard aGuard (*m_xManager);
// Determine current length.
OStoreDirectoryPageObject aPage (m_xNode.get());
sal_uInt32 nDataLen = aPage.dataLength();
if (nSize == nDataLen)
return store_E_None;
if (nSize < nDataLen)
{
// Truncate.
storeError eErrCode = store_E_None;
// Determine 'Size' scope.
inode::ChunkScope eSizeScope = m_xNode->scope (nSize);
if (eSizeScope == inode::SCOPE_INTERNAL)
{
// Internal 'Size' scope. Determine 'Data' scope.
inode::ChunkScope eDataScope = m_xNode->scope (nDataLen);
if (eDataScope == inode::SCOPE_EXTERNAL)
{
// External 'Data' scope. Truncate all external data pages.
eErrCode = aPage.truncate (0, *m_xManager);
if (eErrCode != store_E_None)
return eErrCode;
}
// Truncate internal data page.
inode::ChunkDescriptor aDescr (nSize, m_xNode->capacity());
memset (
&(m_xNode->m_pData[aDescr.m_nOffset]),
0, aDescr.m_nLength);
}
else
{
// External 'Size' scope. Truncate external data pages.
inode::ChunkDescriptor aDescr (
nSize - m_xNode->capacity(), OStoreDataPageData::capacity(m_xNode->m_aDescr)); // @@@
sal_uInt32 nPage = aDescr.m_nPage;
if (aDescr.m_nOffset) nPage += 1;
eErrCode = aPage.truncate (nPage, *m_xManager);
if (eErrCode != store_E_None)
return eErrCode;
}
}
// Set (extended or truncated) size.
aPage.dataLength (nSize);
// Save modified inode.
return m_xManager->saveObjectAt (aPage, aPage.location());
}
/*
* stat.
*/
storeError OStoreLockBytes::stat (sal_uInt32 &rnSize)
{
rnSize = 0;
if (!m_xManager.is())
return store_E_InvalidAccess;
OStoreDirectoryPageObject aPage (m_xNode.get());
rnSize = aPage.dataLength();
return store_E_None;
}
| 23.602679 | 91 | 0.655476 | [
"object"
] |
1c61c683f0b2f4c1d205b81422943939a7a1e831 | 1,822 | hpp | C++ | include/meevax/memory/cell.hpp | yamacir-kit/meevax | ff9449a16380eac727c914a33449e9b3a7597b8e | [
"Apache-2.0"
] | 13 | 2018-11-27T02:06:58.000Z | 2022-01-01T16:07:12.000Z | include/meevax/memory/cell.hpp | yamacir-kit/meevax | ff9449a16380eac727c914a33449e9b3a7597b8e | [
"Apache-2.0"
] | 89 | 2017-11-24T23:58:06.000Z | 2022-02-06T14:54:01.000Z | include/meevax/memory/cell.hpp | yamacir-kit/meevax | ff9449a16380eac727c914a33449e9b3a7597b8e | [
"Apache-2.0"
] | 4 | 2017-12-22T15:45:46.000Z | 2020-01-12T19:50:45.000Z | /*
Copyright 2018-2021 Tatsuya Yamasaki.
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 INCLUDED_MEEVAX_MEMORY_CELL_HPP
#define INCLUDED_MEEVAX_MEMORY_CELL_HPP
#include <meevax/memory/collector.hpp>
#include <meevax/memory/simple_pointer.hpp>
namespace meevax
{
inline namespace memory
{
template <typename T>
struct cell
: public simple_pointer<T>
, private collector::object
{
explicit cell(std::nullptr_t = nullptr)
{}
explicit cell(simple_pointer<T> const& datum)
: simple_pointer<T> { datum }
, collector::object { simple_pointer<T>::get() }
{}
explicit cell(cell const& datum)
: simple_pointer<T> { datum.get() }
, collector::object { simple_pointer<T>::get() }
{}
auto operator =(cell const& another) -> auto &
{
return store(another);
}
void reset(const_pointer<T> data = nullptr)
{
collector::object::reset(simple_pointer<T>::reset(data));
}
auto store(cell const& another) -> auto &
{
reset(another.get());
return *this;
}
void swap(cell & another)
{
auto const copy = simple_pointer<T>::get();
reset(another.get());
another.reset(copy);
}
};
} // namespace memory
} // namespace meevax
#endif // INCLUDED_MEEVAX_MEMORY_CELL_HPP
| 25.305556 | 75 | 0.673436 | [
"object"
] |
1c6b4b161a0452bafc1f269b901661c1b6007ce2 | 5,238 | hpp | C++ | include/elemental/blas-like/level3/TwoSidedTrsm.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | include/elemental/blas-like/level3/TwoSidedTrsm.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | include/elemental/blas-like/level3/TwoSidedTrsm.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef BLAS_TWOSIDEDTRSM_HPP
#define BLAS_TWOSIDEDTRSM_HPP
namespace elem {
namespace internal {
template<typename F>
inline void
TwoSidedTrsmLUnb( UnitOrNonUnit diag, Matrix<F>& A, const Matrix<F>& L )
{
#ifndef RELEASE
CallStackEntry entry("internal::TwoSidedTrsmLUnb");
#endif
// Use the Variant 4 algorithm
const int n = A.Height();
const int lda = A.LDim();
const int ldl = L.LDim();
F* ABuffer = A.Buffer();
const F* LBuffer = L.LockedBuffer();
for( int j=0; j<n; ++j )
{
const int a21Height = n - (j+1);
// Extract and store the diagonal value of L
const F lambda11 = ( diag==UNIT ? 1 : LBuffer[j+j*ldl] );
// a10 := a10 / lambda11
F* a10 = &ABuffer[j];
if( diag != UNIT )
for( int k=0; k<j; ++k )
a10[k*lda] /= lambda11;
// A20 := A20 - l21 a10
F* A20 = &ABuffer[j+1];
const F* l21 = &LBuffer[(j+1)+j*ldl];
blas::Geru( a21Height, j, F(-1), l21, 1, a10, lda, A20, lda );
// alpha11 := alpha11 / |lambda11|^2
ABuffer[j+j*lda] /= lambda11*Conj(lambda11);
const F alpha11 = ABuffer[j+j*lda];
// a21 := a21 / conj(lambda11)
F* a21 = &ABuffer[(j+1)+j*lda];
if( diag != UNIT )
for( int k=0; k<a21Height; ++k )
a21[k] /= Conj(lambda11);
// a21 := a21 - (alpha11/2)l21
for( int k=0; k<a21Height; ++k )
a21[k] -= (alpha11/2)*l21[k];
// A22 := A22 - (l21 a21' + a21 l21')
F* A22 = &ABuffer[(j+1)+(j+1)*lda];
blas::Her2( 'L', a21Height, F(-1), l21, 1, a21, 1, A22, lda );
// a21 := a21 - (alpha11/2)l21
for( int k=0; k<a21Height; ++k )
a21[k] -= (alpha11/2)*l21[k];
}
}
template<typename F>
inline void
TwoSidedTrsmUUnb( UnitOrNonUnit diag, Matrix<F>& A, const Matrix<F>& U )
{
#ifndef RELEASE
CallStackEntry entry("internal::TwoSidedTrsmUUnb");
#endif
// Use the Variant 4 algorithm
// (which annoyingly requires conjugations for the Her2)
const int n = A.Height();
const int lda = A.LDim();
const int ldu = U.LDim();
F* ABuffer = A.Buffer();
const F* UBuffer = U.LockedBuffer();
std::vector<F> a12Conj( n ), u12Conj( n );
for( int j=0; j<n; ++j )
{
const int a21Height = n - (j+1);
// Extract and store the diagonal value of U
const F upsilon11 = ( diag==UNIT ? 1 : UBuffer[j+j*ldu] );
// a01 := a01 / upsilon11
F* a01 = &ABuffer[j*lda];
if( diag != UNIT )
for( int k=0; k<j; ++k )
a01[k] /= upsilon11;
// A02 := A02 - a01 u12
F* A02 = &ABuffer[(j+1)*lda];
const F* u12 = &UBuffer[j+(j+1)*ldu];
blas::Geru( j, a21Height, F(-1), a01, 1, u12, ldu, A02, lda );
// alpha11 := alpha11 / |upsilon11|^2
ABuffer[j+j*lda] /= upsilon11*Conj(upsilon11);
const F alpha11 = ABuffer[j+j*lda];
// a12 := a12 / conj(upsilon11)
F* a12 = &ABuffer[j+(j+1)*lda];
if( diag != UNIT )
for( int k=0; k<a21Height; ++k )
a12[k*lda] /= Conj(upsilon11);
// a12 := a12 - (alpha11/2)u12
for( int k=0; k<a21Height; ++k )
a12[k*lda] -= (alpha11/2)*u12[k*ldu];
// A22 := A22 - (a12' u12 + u12' a12)
F* A22 = &ABuffer[(j+1)+(j+1)*lda];
for( int k=0; k<a21Height; ++k )
a12Conj[k] = Conj(a12[k*lda]);
for( int k=0; k<a21Height; ++k )
u12Conj[k] = Conj(u12[k*ldu]);
blas::Her2
( 'U', a21Height, F(-1), &u12Conj[0], 1, &a12Conj[0], 1, A22, lda );
// a12 := a12 - (alpha11/2)u12
for( int k=0; k<a21Height; ++k )
a12[k*lda] -= (alpha11/2)*u12[k*ldu];
}
}
} // namespace internal
template<typename F>
inline void
LocalTwoSidedTrsm
( UpperOrLower uplo, UnitOrNonUnit diag,
DistMatrix<F,STAR,STAR>& A, const DistMatrix<F,STAR,STAR>& B )
{
#ifndef RELEASE
CallStackEntry entry("LocalTwoSidedTrsm");
#endif
TwoSidedTrsm( uplo, diag, A.Matrix(), B.LockedMatrix() );
}
} // namespace elem
#include "./TwoSidedTrsm/LVar4.hpp"
#include "./TwoSidedTrsm/UVar4.hpp"
namespace elem {
template<typename F>
inline void
TwoSidedTrsm
( UpperOrLower uplo, UnitOrNonUnit diag, Matrix<F>& A, const Matrix<F>& B )
{
#ifndef RELEASE
CallStackEntry entry("TwoSidedTrsm");
#endif
if( uplo == LOWER )
internal::TwoSidedTrsmLVar4( diag, A, B );
else
internal::TwoSidedTrsmUVar4( diag, A, B );
}
template<typename F>
inline void
TwoSidedTrsm
( UpperOrLower uplo, UnitOrNonUnit diag,
DistMatrix<F>& A, const DistMatrix<F>& B )
{
#ifndef RELEASE
CallStackEntry entry("TwoSidedTrsm");
#endif
if( uplo == LOWER )
internal::TwoSidedTrsmLVar4( diag, A, B );
else
internal::TwoSidedTrsmUVar4( diag, A, B );
}
} // namespace elem
#endif // ifndef BLAS_TWOSIDEDTRSM_HPP
| 28.16129 | 76 | 0.560519 | [
"vector"
] |
1c70b80cf7a42b399f3903e5c241a27c4e94c5a4 | 59,770 | cpp | C++ | atmel-rf-driver/source/NanostackRfPhyAtmel.cpp | ghsecuritylab/BLEClient_mbedDevConn_Watson | f162ec8a99ab3b21cee28aaed65da60cf5dd6618 | [
"Apache-2.0"
] | 1 | 2019-05-28T04:54:23.000Z | 2019-05-28T04:54:23.000Z | atmel-rf-driver/source/NanostackRfPhyAtmel.cpp | ghsecuritylab/BLEClient_mbedDevConn_Watson | f162ec8a99ab3b21cee28aaed65da60cf5dd6618 | [
"Apache-2.0"
] | 1 | 2017-02-20T10:48:02.000Z | 2017-02-21T11:34:16.000Z | atmel-rf-driver/source/NanostackRfPhyAtmel.cpp | ghsecuritylab/BLEClient_mbedDevConn_Watson | f162ec8a99ab3b21cee28aaed65da60cf5dd6618 | [
"Apache-2.0"
] | 3 | 2017-02-07T15:06:06.000Z | 2021-02-19T13:56:31.000Z | /*
* Copyright (c) 2014-2015 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* 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 <string.h>
#include "platform/arm_hal_interrupt.h"
#include "nanostack/platform/arm_hal_phy.h"
#include "ns_types.h"
#include "NanostackRfPhyAtmel.h"
#include "randLIB.h"
#include "AT86RFReg.h"
#include "nanostack/platform/arm_hal_phy.h"
#include "toolchain.h"
/*Worst case sensitivity*/
#define RF_DEFAULT_SENSITIVITY -88
/*Run calibration every 5 minutes*/
#define RF_CALIBRATION_INTERVAL 6000000
/*Wait ACK for 2.5ms*/
#define RF_ACK_WAIT_DEFAULT_TIMEOUT 50
/*Base CCA backoff (50us units) - substitutes for Inter-Frame Spacing*/
#define RF_CCA_BASE_BACKOFF 13 /* 650us */
/*CCA random backoff (50us units)*/
#define RF_CCA_RANDOM_BACKOFF 51 /* 2550us */
#define RF_BUFFER_SIZE 128
#define RF_PHY_MODE OQPSK_SIN_250
/*Radio RX and TX state definitions*/
#define RFF_ON 0x01
#define RFF_RX 0x02
#define RFF_TX 0x04
#define RFF_CCA 0x08
typedef enum
{
RF_MODE_NORMAL = 0,
RF_MODE_SNIFFER = 1,
RF_MODE_ED = 2
}rf_mode_t;
/*Atmel RF Part Type*/
typedef enum
{
ATMEL_UNKNOW_DEV = 0,
ATMEL_AT86RF212,
ATMEL_AT86RF231,
ATMEL_AT86RF233
}rf_trx_part_e;
/*Atmel RF states*/
typedef enum
{
NOP = 0x00,
BUSY_RX = 0x01,
RF_TX_START = 0x02,
FORCE_TRX_OFF = 0x03,
FORCE_PLL_ON = 0x04,
RX_ON = 0x06,
TRX_OFF = 0x08,
PLL_ON = 0x09,
BUSY_RX_AACK = 0x11,
SLEEP = 0x0F,
RX_AACK_ON = 0x16,
TX_ARET_ON = 0x19
}rf_trx_states_t;
/*RF receive buffer*/
static uint8_t rf_buffer[RF_BUFFER_SIZE];
/*ACK wait duration changes depending on data rate*/
static uint16_t rf_ack_wait_duration = RF_ACK_WAIT_DEFAULT_TIMEOUT;
static int8_t rf_sensitivity = RF_DEFAULT_SENSITIVITY;
static rf_mode_t rf_mode = RF_MODE_NORMAL;
static uint8_t radio_tx_power = 0x00; // Default to +4dBm
static uint8_t rf_phy_channel = 12;
static uint8_t rf_tuned = 1;
static uint8_t rf_use_antenna_diversity = 0;
static uint8_t tx_sequence = 0xff;
static uint8_t need_ack = 0;
static uint8_t rf_rx_mode = 0;
static uint8_t rf_flags = 0;
static uint8_t rf_rnd_rssi = 0;
static int8_t rf_radio_driver_id = -1;
static phy_device_driver_s device_driver;
static uint8_t mac_tx_handle = 0;
/* Channel configurations for 2.4 and sub-GHz */
static const phy_rf_channel_configuration_s phy_24ghz = {2405000000U, 5000000U, 250000U, 16U, M_OQPSK};
static const phy_rf_channel_configuration_s phy_subghz = {868300000U, 2000000U, 250000U, 11U, M_OQPSK};
static const phy_device_channel_page_s phy_channel_pages[] = {
{ CHANNEL_PAGE_0, &phy_24ghz},
{ CHANNEL_PAGE_2, &phy_subghz},
{ CHANNEL_PAGE_0, NULL}
};
/**
* RF output power write
*
* \brief TX power has to be set before network start.
*
* \param power
* AT86RF233
* 0 = 4 dBm
* 1 = 3.7 dBm
* 2 = 3.4 dBm
* 3 = 3 dBm
* 4 = 2.5 dBm
* 5 = 2 dBm
* 6 = 1 dBm
* 7 = 0 dBm
* 8 = -1 dBm
* 9 = -2 dBm
* 10 = -3 dBm
* 11 = -4 dBm
* 12 = -6 dBm
* 13 = -8 dBm
* 14 = -12 dBm
* 15 = -17 dBm
*
* AT86RF212B
* See datasheet for TX power settings
*
* \return 0, Supported Value
* \return -1, Not Supported Value
*/
static int8_t rf_tx_power_set(uint8_t power);
static rf_trx_part_e rf_radio_type_read(void);
static void rf_ack_wait_timer_start(uint16_t slots);
static void rf_ack_wait_timer_stop(void);
static void rf_handle_cca_ed_done(void);
static void rf_handle_tx_end(void);
static void rf_handle_rx_end(void);
static void rf_on(void);
static void rf_receive(void);
static void rf_poll_trx_state_change(rf_trx_states_t trx_state);
static void rf_init(void);
static int8_t rf_device_register(const uint8_t *mac_addr);
static void rf_device_unregister(void);
static int8_t rf_start_cca(uint8_t *data_ptr, uint16_t data_length, uint8_t tx_handle, data_protocol_e data_protocol );
static void rf_cca_abort(void);
static void rf_calibration_cb(void);
static void rf_init_phy_mode(void);
static void rf_ack_wait_timer_interrupt(void);
static void rf_calibration_timer_interrupt(void);
static void rf_calibration_timer_start(uint32_t slots);
static void rf_cca_timer_interrupt(void);
static void rf_cca_timer_start(uint32_t slots);
static uint8_t rf_scale_lqi(int8_t rssi);
static int8_t rf_interface_state_control(phy_interface_state_e new_state, uint8_t rf_channel);
static int8_t rf_extension(phy_extension_type_e extension_type,uint8_t *data_ptr);
static int8_t rf_address_write(phy_address_type_e address_type,uint8_t *address_ptr);
static void rf_if_cca_timer_start(uint32_t slots);
static void rf_if_enable_promiscuous_mode(void);
static void rf_if_lock(void);
static void rf_if_unlock(void);
static uint8_t rf_if_read_rnd(void);
static void rf_if_calibration_timer_start(uint32_t slots);
static void rf_if_interrupt_handler(void);
static void rf_if_ack_wait_timer_start(uint16_t slots);
static void rf_if_ack_wait_timer_stop(void);
static void rf_if_ack_pending_ctrl(uint8_t state);
static void rf_if_calibration(void);
static uint8_t rf_if_read_register(uint8_t addr);
static void rf_if_set_bit(uint8_t addr, uint8_t bit, uint8_t bit_mask);
static void rf_if_clear_bit(uint8_t addr, uint8_t bit);
static void rf_if_write_register(uint8_t addr, uint8_t data);
static void rf_if_reset_radio(void);
static void rf_if_enable_ant_div(void);
static void rf_if_disable_ant_div(void);
static void rf_if_enable_slptr(void);
static void rf_if_disable_slptr(void);
static void rf_if_write_antenna_diversity_settings(void);
static void rf_if_write_set_tx_power_register(uint8_t value);
static void rf_if_write_rf_settings(void);
static uint8_t rf_if_check_cca(void);
static uint8_t rf_if_check_crc(void);
static uint8_t rf_if_read_trx_state(void);
static void rf_if_read_packet(uint8_t *ptr, uint8_t len);
static void rf_if_write_short_addr_registers(uint8_t *short_address);
static uint8_t rf_if_last_acked_pending(void);
static void rf_if_write_pan_id_registers(uint8_t *pan_id);
static void rf_if_write_ieee_addr_registers(uint8_t *address);
static void rf_if_write_frame_buffer(uint8_t *ptr, uint8_t length);
static void rf_if_change_trx_state(rf_trx_states_t trx_state);
static void rf_if_enable_tx_end_interrupt(void);
static void rf_if_enable_rx_end_interrupt(void);
static void rf_if_enable_cca_ed_done_interrupt(void);
static void rf_if_start_cca_process(void);
static uint8_t rf_if_read_received_frame_length(void);
static int8_t rf_if_read_rssi(void);
static uint8_t rf_if_read_rx_status(void);
static void rf_if_set_channel_register(uint8_t channel);
static void rf_if_enable_promiscuous_mode(void);
static void rf_if_disable_promiscuous_mode(void);
static uint8_t rf_if_read_part_num(void);
static void rf_if_enable_irq(void);
static void rf_if_disable_irq(void);
#ifdef MBED_CONF_RTOS_PRESENT
#include "mbed.h"
#include "rtos.h"
static void rf_if_irq_task_process_irq();
#define SIG_RADIO 1
#define SIG_TIMER_ACK 2
#define SIG_TIMER_CAL 4
#define SIG_TIMER_CCA 8
#define SIG_TIMERS (SIG_TIMER_ACK|SIG_TIMER_CAL|SIG_TIMER_CCA)
#define SIG_ALL (SIG_RADIO|SIG_TIMERS)
#endif
// HW pins to RF chip
#define SPI_SPEED 7500000
class UnlockedSPI : public SPI {
public:
UnlockedSPI(PinName mosi, PinName miso, PinName sclk) :
SPI(mosi, miso, sclk) { }
virtual void lock() { }
virtual void unlock() { }
};
class RFBits {
public:
RFBits(PinName spi_mosi, PinName spi_miso,
PinName spi_sclk, PinName spi_cs,
PinName spi_rst, PinName spi_slp, PinName spi_irq);
UnlockedSPI spi;
DigitalOut CS;
DigitalOut RST;
DigitalOut SLP_TR;
InterruptIn IRQ;
Timeout ack_timer;
Timeout cal_timer;
Timeout cca_timer;
#ifdef MBED_CONF_RTOS_PRESENT
Thread irq_thread;
Mutex mutex;
void rf_if_irq_task();
#endif
};
RFBits::RFBits(PinName spi_mosi, PinName spi_miso,
PinName spi_sclk, PinName spi_cs,
PinName spi_rst, PinName spi_slp, PinName spi_irq)
: spi(spi_mosi, spi_miso, spi_sclk),
CS(spi_cs),
RST(spi_rst),
SLP_TR(spi_slp),
IRQ(spi_irq)
#ifdef MBED_CONF_RTOS_PRESENT
,irq_thread(osPriorityRealtime, 1024)
#endif
{
#ifdef MBED_CONF_RTOS_PRESENT
irq_thread.start(this, &RFBits::rf_if_irq_task);
#endif
}
static RFBits *rf;
static uint8_t rf_part_num = 0;
static uint8_t rf_rx_lqi;
static int8_t rf_rx_rssi;
static uint8_t rf_rx_status;
/*TODO: RSSI Base value setting*/
static int8_t rf_rssi_base_val = -91;
static uint8_t rf_if_spi_exchange(uint8_t out);
static void rf_if_lock(void)
{
platform_enter_critical();
}
static void rf_if_unlock(void)
{
platform_exit_critical();
}
#ifdef MBED_CONF_RTOS_PRESENT
static void rf_if_cca_timer_signal(void)
{
rf->irq_thread.signal_set(SIG_TIMER_CCA);
}
static void rf_if_cal_timer_signal(void)
{
rf->irq_thread.signal_set(SIG_TIMER_CAL);
}
static void rf_if_ack_timer_signal(void)
{
rf->irq_thread.signal_set(SIG_TIMER_ACK);
}
#endif
/* Delay functions for RF Chip SPI access */
#ifdef __CC_ARM
__asm static void delay_loop(uint32_t count)
{
1
SUBS a1, a1, #1
BCS %BT1
BX lr
}
#elif defined (__ICCARM__)
static void delay_loop(uint32_t count)
{
__asm volatile(
"loop: \n"
" SUBS %0, %0, #1 \n"
" BCS.n loop\n"
: "+r" (count)
:
: "cc"
);
}
#else // GCC
static void delay_loop(uint32_t count)
{
__asm__ volatile (
"%=:\n\t"
#if defined(__thumb__) && !defined(__thumb2__)
"SUB %0, #1\n\t"
#else
"SUBS %0, %0, #1\n\t"
#endif
"BCS %=b\n\t"
: "+l" (count)
:
: "cc"
);
}
#endif
static void delay_ns(uint32_t ns)
{
uint32_t cycles_per_us = SystemCoreClock / 1000000;
// Cortex-M0 takes 4 cycles per loop (SUB=1, BCS=3)
// Cortex-M3 and M4 takes 3 cycles per loop (SUB=1, BCS=2)
// Cortex-M7 - who knows?
// Cortex M3-M7 have "CYCCNT" - would be better than a software loop, but M0 doesn't
// Assume 3 cycles per loop for now - will be 33% slow on M0. No biggie,
// as original version of code was 300% slow on M4.
// [Note that this very calculation, plus call overhead, will take multiple
// cycles. Could well be 100ns on its own... So round down here, startup is
// worth at least one loop iteration.]
uint32_t count = (cycles_per_us * ns) / 3000;
delay_loop(count);
}
// t1 = 180ns, SEL falling edge to MISO active [SPI setup assumed slow enough to not need manual delay]
#define CS_SELECT() {rf->CS = 0; /* delay_ns(180); */}
// t9 = 250ns, last clock to SEL rising edge, t8 = 250ns, SPI idle time between consecutive access
#define CS_RELEASE() {delay_ns(250); rf->CS = 1; delay_ns(250);}
/*
* \brief Function sets the TX power variable.
*
* \param power TX power setting
*
* \return 0 Success
* \return -1 Fail
*/
MBED_UNUSED static int8_t rf_tx_power_set(uint8_t power)
{
int8_t ret_val = -1;
radio_tx_power = power;
rf_if_lock();
rf_if_write_set_tx_power_register(radio_tx_power);
rf_if_unlock();
ret_val = 0;
return ret_val;
}
/*
* \brief Read connected radio part.
*
* This function only return valid information when rf_init() is called
*
* \return
*/
static rf_trx_part_e rf_radio_type_read(void)
{
rf_trx_part_e ret_val = ATMEL_UNKNOW_DEV;
switch (rf_part_num)
{
case PART_AT86RF212:
ret_val = ATMEL_AT86RF212;
break;
case PART_AT86RF231:
ret_val = ATMEL_AT86RF231;
break;
case PART_AT86RF233:
ret_val = ATMEL_AT86RF231;
break;
default:
break;
}
return ret_val;
}
/*
* \brief Function starts the ACK wait timeout.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_if_ack_wait_timer_start(uint16_t slots)
{
#ifdef MBED_CONF_RTOS_PRESENT
rf->ack_timer.attach(rf_if_ack_timer_signal, slots*50e-6);
#else
rf->ack_timer.attach(rf_ack_wait_timer_interrupt, slots*50e-6);
#endif
}
/*
* \brief Function starts the calibration interval.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_if_calibration_timer_start(uint32_t slots)
{
#ifdef MBED_CONF_RTOS_PRESENT
rf->cal_timer.attach(rf_if_cal_timer_signal, slots*50e-6);
#else
rf->cal_timer.attach(rf_calibration_timer_interrupt, slots*50e-6);
#endif
}
/*
* \brief Function starts the CCA interval.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_if_cca_timer_start(uint32_t slots)
{
#ifdef MBED_CONF_RTOS_PRESENT
rf->cca_timer.attach(rf_if_cca_timer_signal, slots*50e-6);
#else
rf->cca_timer.attach(rf_cca_timer_interrupt, slots*50e-6);
#endif
}
/*
* \brief Function stops the ACK wait timeout.
*
* \param none
*
* \return none
*/
static void rf_if_ack_wait_timer_stop(void)
{
rf->ack_timer.detach();
}
/*
* \brief Function reads data from the given RF SRAM address.
*
* \param ptr Read pointer
* \param sram_address Read address in SRAM
* \param len Length of the read
*
* \return none
*/
static void rf_if_read_payload(uint8_t *ptr, uint8_t sram_address, uint8_t len)
{
uint8_t i;
CS_SELECT();
rf_if_spi_exchange(0x20);
rf_if_spi_exchange(sram_address);
for(i=0; i<len; i++)
*ptr++ = rf_if_spi_exchange(0);
/*Read LQI and RSSI in variable*/
rf_rx_lqi = rf_if_spi_exchange(0);
rf_rx_rssi = rf_if_spi_exchange(0);
rf_rx_status = rf_if_spi_exchange(0);
CS_RELEASE();
}
/*
* \brief Function sets bit(s) in given RF register.
*
* \param addr Address of the register to set
* \param bit Bit(s) to set
* \param bit_mask Masks the field inside the register
*
* \return none
*/
static void rf_if_set_bit(uint8_t addr, uint8_t bit, uint8_t bit_mask)
{
uint8_t reg = rf_if_read_register(addr);
reg &= ~bit_mask;
reg |= bit;
rf_if_write_register(addr, reg);
}
/*
* \brief Function clears bit(s) in given RF register.
*
* \param addr Address of the register to clear
* \param bit Bit(s) to clear
*
* \return none
*/
static void rf_if_clear_bit(uint8_t addr, uint8_t bit)
{
uint8_t reg = rf_if_read_register(addr);
reg &= ~bit;
rf_if_write_register(addr, reg);
}
/*
* \brief Function writes register in RF.
*
* \param addr Address on the RF
* \param data Written data
*
* \return none
*/
static void rf_if_write_register(uint8_t addr, uint8_t data)
{
uint8_t cmd = 0xC0;
CS_SELECT();
rf_if_spi_exchange(cmd | addr);
rf_if_spi_exchange(data);
CS_RELEASE();
}
/*
* \brief Function reads RF register.
*
* \param addr Address on the RF
*
* \return Read data
*/
static uint8_t rf_if_read_register(uint8_t addr)
{
uint8_t cmd = 0x80;
uint8_t data;
CS_SELECT();
rf_if_spi_exchange(cmd | addr);
data = rf_if_spi_exchange(0);
CS_RELEASE();
return data;
}
/*
* \brief Function resets the RF.
*
* \param none
*
* \return none
*/
static void rf_if_reset_radio(void)
{
rf->spi.frequency(SPI_SPEED);
rf->IRQ.rise(0);
rf->RST = 1;
wait(10e-4);
rf->RST = 0;
wait(10e-3);
CS_RELEASE();
rf->SLP_TR = 0;
wait(10e-3);
rf->RST = 1;
wait(10e-3);
rf->IRQ.rise(&rf_if_interrupt_handler);
}
/*
* \brief Function enables the promiscuous mode.
*
* \param none
*
* \return none
*/
static void rf_if_enable_promiscuous_mode(void)
{
/*Set AACK_PROM_MODE to enable the promiscuous mode*/
rf_if_set_bit(XAH_CTRL_1, AACK_PROM_MODE, AACK_PROM_MODE);
}
/*
* \brief Function enables the promiscuous mode.
*
* \param none
*
* \return none
*/
static void rf_if_disable_promiscuous_mode(void)
{
/*Set AACK_PROM_MODE to enable the promiscuous mode*/
rf_if_clear_bit(XAH_CTRL_1, AACK_PROM_MODE);
}
/*
* \brief Function enables the Antenna diversity usage.
*
* \param none
*
* \return none
*/
static void rf_if_enable_ant_div(void)
{
/*Set ANT_EXT_SW_EN to enable controlling of antenna diversity*/
rf_if_set_bit(ANT_DIV, ANT_EXT_SW_EN, ANT_EXT_SW_EN);
}
/*
* \brief Function disables the Antenna diversity usage.
*
* \param none
*
* \return none
*/
static void rf_if_disable_ant_div(void)
{
rf_if_clear_bit(ANT_DIV, ANT_EXT_SW_EN);
}
/*
* \brief Function sets the SLP TR pin.
*
* \param none
*
* \return none
*/
static void rf_if_enable_slptr(void)
{
rf->SLP_TR = 1;
}
/*
* \brief Function clears the SLP TR pin.
*
* \param none
*
* \return none
*/
static void rf_if_disable_slptr(void)
{
rf->SLP_TR = 0;
}
/*
* \brief Function writes the antenna diversity settings.
*
* \param none
*
* \return none
*/
static void rf_if_write_antenna_diversity_settings(void)
{
/*Recommended setting of PDT_THRES is 3 when antenna diversity is used*/
rf_if_set_bit(RX_CTRL, 0x03, 0x0f);
rf_if_write_register(ANT_DIV, ANT_DIV_EN | ANT_EXT_SW_EN | ANT_CTRL_DEFAULT);
}
/*
* \brief Function writes the TX output power register.
*
* \param value Given register value
*
* \return none
*/
static void rf_if_write_set_tx_power_register(uint8_t value)
{
rf_if_write_register(PHY_TX_PWR, value);
}
/*
* \brief Function returns the RF part number.
*
* \param none
*
* \return part number
*/
static uint8_t rf_if_read_part_num(void)
{
return rf_if_read_register(PART_NUM);
}
/*
* \brief Function writes the RF settings and initialises SPI interface.
*
* \param none
*
* \return none
*/
static void rf_if_write_rf_settings(void)
{
/*Reset RF module*/
rf_if_reset_radio();
rf_part_num = rf_if_read_part_num();
rf_if_write_register(XAH_CTRL_0,0);
rf_if_write_register(TRX_CTRL_1, 0x20);
/*CCA Mode - Carrier sense OR energy above threshold. Channel list is set separately*/
rf_if_write_register(PHY_CC_CCA, 0x05);
/*Read transceiver PART_NUM*/
rf_part_num = rf_if_read_register(PART_NUM);
/*Sub-GHz RF settings*/
if(rf_part_num == PART_AT86RF212)
{
/*GC_TX_OFFS mode-dependent setting - OQPSK*/
rf_if_write_register(RF_CTRL_0, 0x32);
if(rf_if_read_register(VERSION_NUM) == VERSION_AT86RF212B)
{
/*TX Output Power setting - 0 dBm North American Band*/
rf_if_write_register(PHY_TX_PWR, 0x03);
}
else
{
/*TX Output Power setting - 0 dBm North American Band*/
rf_if_write_register(PHY_TX_PWR, 0x24);
}
/*PHY Mode: IEEE 802.15.4-2006/2011 - OQPSK-SIN-250*/
rf_if_write_register(TRX_CTRL_2, RF_PHY_MODE);
/*Based on receiver Characteristics. See AT86RF212B Datasheet where RSSI BASE VALUE in range -97 - -100 dBm*/
rf_rssi_base_val = -98;
}
/*2.4GHz RF settings*/
else
{
/*Set RPC register*/
rf_if_write_register(TRX_RPC, 0xef);
/*PHY Mode: IEEE 802.15.4 - Data Rate 250 kb/s*/
rf_if_write_register(TRX_CTRL_2, 0);
rf_rssi_base_val = -91;
}
}
/*
* \brief Function checks the channel availability
*
* \param none
*
* \return 1 Channel clear
* \return 0 Channel not clear
*/
static uint8_t rf_if_check_cca(void)
{
uint8_t retval = 0;
if(rf_if_read_register(TRX_STATUS) & CCA_STATUS)
{
retval = 1;
}
return retval;
}
/*
* \brief Function checks if the CRC is valid in received frame
*
* \param none
*
* \return 1 CRC ok
* \return 0 CRC failed
*/
static uint8_t rf_if_check_crc(void)
{
uint8_t retval = 0;
if(rf_if_read_register(PHY_RSSI) & CRC_VALID)
{
retval = 1;
}
return retval;
}
/*
* \brief Function returns the RF state
*
* \param none
*
* \return RF state
*/
static uint8_t rf_if_read_trx_state(void)
{
return rf_if_read_register(TRX_STATUS) & 0x1F;
}
/*
* \brief Function reads data from RF SRAM.
*
* \param ptr Read pointer
* \param len Length of the read
*
* \return none
*/
static void rf_if_read_packet(uint8_t *ptr, uint8_t len)
{
if(rf_part_num == PART_AT86RF231 || rf_part_num == PART_AT86RF212)
rf_if_read_payload(ptr, 0, len);
else if(rf_part_num == PART_AT86RF233)
rf_if_read_payload(ptr, 1, len);
}
/*
* \brief Function writes RF short address registers
*
* \param short_address Given short address
*
* \return none
*/
static void rf_if_write_short_addr_registers(uint8_t *short_address)
{
rf_if_write_register(SHORT_ADDR_1, *short_address++);
rf_if_write_register(SHORT_ADDR_0, *short_address);
}
/*
* \brief Function sets the frame pending in ACK message
*
* \param state Given frame pending state
*
* \return none
*/
static void rf_if_ack_pending_ctrl(uint8_t state)
{
rf_if_lock();
if(state)
{
rf_if_set_bit(CSMA_SEED_1, (1 << AACK_SET_PD), (1 << AACK_SET_PD));
}
else
{
rf_if_clear_bit(CSMA_SEED_1, (1 << AACK_SET_PD));
}
rf_if_unlock();
}
/*
* \brief Function returns the state of frame pending control
*
* \param none
*
* \return Frame pending state
*/
static uint8_t rf_if_last_acked_pending(void)
{
uint8_t last_acked_data_pending;
rf_if_lock();
if(rf_if_read_register(CSMA_SEED_1) & 0x20)
last_acked_data_pending = 1;
else
last_acked_data_pending = 0;
rf_if_unlock();
return last_acked_data_pending;
}
/*
* \brief Function calibrates the RF part.
*
* \param none
*
* \return none
*/
static void rf_if_calibration(void)
{
rf_if_set_bit(FTN_CTRL, FTN_START, FTN_START);
/*Wait while calibration is running*/
while(rf_if_read_register(FTN_CTRL) & FTN_START);
}
/*
* \brief Function writes RF PAN Id registers
*
* \param pan_id Given PAN Id
*
* \return none
*/
static void rf_if_write_pan_id_registers(uint8_t *pan_id)
{
rf_if_write_register(PAN_ID_1, *pan_id++);
rf_if_write_register(PAN_ID_0, *pan_id);
}
/*
* \brief Function writes RF IEEE Address registers
*
* \param address Given IEEE Address
*
* \return none
*/
static void rf_if_write_ieee_addr_registers(uint8_t *address)
{
uint8_t i;
uint8_t temp = IEEE_ADDR_0;
for(i=0; i<8; i++)
rf_if_write_register(temp++, address[7-i]);
}
/*
* \brief Function writes data in RF frame buffer.
*
* \param ptr Pointer to data
* \param length Pointer to length
*
* \return none
*/
static void rf_if_write_frame_buffer(uint8_t *ptr, uint8_t length)
{
uint8_t i;
uint8_t cmd = 0x60;
CS_SELECT();
rf_if_spi_exchange(cmd);
rf_if_spi_exchange(length + 2);
for(i=0; i<length; i++)
rf_if_spi_exchange(*ptr++);
CS_RELEASE();
}
/*
* \brief Function returns 8-bit random value.
*
* \param none
*
* \return random value
*/
static uint8_t rf_if_read_rnd(void)
{
uint8_t temp;
uint8_t tmp_rpc_val = 0;
/*RPC must be disabled while reading the random number*/
if(rf_part_num == PART_AT86RF233)
{
tmp_rpc_val = rf_if_read_register(TRX_RPC);
rf_if_write_register(TRX_RPC, 0xc1);
}
wait(1e-3);
temp = ((rf_if_read_register(PHY_RSSI)>>5) << 6);
wait(1e-3);
temp |= ((rf_if_read_register(PHY_RSSI)>>5) << 4);
wait(1e-3);
temp |= ((rf_if_read_register(PHY_RSSI)>>5) << 2);
wait(1e-3);
temp |= ((rf_if_read_register(PHY_RSSI)>>5));
wait(1e-3);
if(rf_part_num == PART_AT86RF233)
rf_if_write_register(TRX_RPC, tmp_rpc_val);
return temp;
}
/*
* \brief Function changes the state of the RF.
*
* \param trx_state Given RF state
*
* \return none
*/
static void rf_if_change_trx_state(rf_trx_states_t trx_state)
{
rf_if_lock();
rf_if_write_register(TRX_STATE, trx_state);
/*Wait while not in desired state*/
rf_poll_trx_state_change(trx_state);
rf_if_unlock();
}
/*
* \brief Function enables the TX END interrupt
*
* \param none
*
* \return none
*/
static void rf_if_enable_tx_end_interrupt(void)
{
rf_if_set_bit(IRQ_MASK, TRX_END, 0x08);
}
/*
* \brief Function enables the RX END interrupt
*
* \param none
*
* \return none
*/
static void rf_if_enable_rx_end_interrupt(void)
{
rf_if_set_bit(IRQ_MASK, TRX_END, 0x08);
}
/*
* \brief Function enables the CCA ED interrupt
*
* \param none
*
* \return none
*/
static void rf_if_enable_cca_ed_done_interrupt(void)
{
rf_if_set_bit(IRQ_MASK, CCA_ED_DONE, 0x10);
}
/*
* \brief Function starts the CCA process
*
* \param none
*
* \return none
*/
static void rf_if_start_cca_process(void)
{
rf_if_set_bit(PHY_CC_CCA, CCA_REQUEST, 0x80);
}
/*
* \brief Function returns the length of the received packet
*
* \param none
*
* \return packet length
*/
static uint8_t rf_if_read_received_frame_length(void)
{
uint8_t length;
CS_SELECT();
rf_if_spi_exchange(0x20);
length = rf_if_spi_exchange(0);
CS_RELEASE();
return length;
}
/*
* \brief Function returns the RSSI of the received packet
*
* \param none
*
* \return packet RSSI
*/
static int8_t rf_if_read_rssi(void)
{
int16_t rssi_calc_tmp;
if(rf_part_num == PART_AT86RF212)
rssi_calc_tmp = rf_rx_rssi * 103;
else
rssi_calc_tmp = rf_rx_rssi * 100;
rssi_calc_tmp /= 100;
rssi_calc_tmp = (rf_rssi_base_val + rssi_calc_tmp);
return (int8_t)rssi_calc_tmp;
}
/*
* \brief Function returns the RSSI of the received packet
*
* \param none
*
* \return packet RSSI
*/
MBED_UNUSED uint8_t rf_if_read_rx_status(void)
{
return rf_rx_status;
}
/*
* \brief Function sets the RF channel field
*
* \param Given channel
*
* \return none
*/
static void rf_if_set_channel_register(uint8_t channel)
{
rf_if_set_bit(PHY_CC_CCA, channel, 0x1f);
}
/*
* \brief Function enables RF irq pin interrupts in RF interface.
*
* \param none
*
* \return none
*/
static void rf_if_enable_irq(void)
{
rf->IRQ.enable_irq();
}
/*
* \brief Function disables RF irq pin interrupts in RF interface.
*
* \param none
*
* \return none
*/
static void rf_if_disable_irq(void)
{
rf->IRQ.disable_irq();
}
#ifdef MBED_CONF_RTOS_PRESENT
static void rf_if_interrupt_handler(void)
{
rf->irq_thread.signal_set(SIG_RADIO);
}
// Started during construction of rf, so variable
// rf isn't set at the start. Uses 'this' instead.
void RFBits::rf_if_irq_task(void)
{
for (;;) {
osEvent event = irq_thread.signal_wait(0);
if (event.status != osEventSignal) {
continue;
}
rf_if_lock();
if (event.value.signals & SIG_RADIO) {
rf_if_irq_task_process_irq();
}
if (event.value.signals & SIG_TIMER_ACK) {
rf_ack_wait_timer_interrupt();
}
if (event.value.signals & SIG_TIMER_CCA) {
rf_cca_timer_interrupt();
}
if (event.value.signals & SIG_TIMER_CAL) {
rf_calibration_timer_interrupt();
}
rf_if_unlock();
}
}
static void rf_if_irq_task_process_irq(void)
#else
/*
* \brief Function is a RF interrupt vector. End of frame in RX and TX are handled here as well as CCA process interrupt.
*
* \param none
*
* \return none
*/
static void rf_if_interrupt_handler(void)
#endif
{
uint8_t irq_status;
/*Read interrupt flag*/
irq_status = rf_if_read_register(IRQ_STATUS);
/*Disable interrupt on RF*/
rf_if_clear_bit(IRQ_MASK, irq_status);
/*RX start interrupt*/
if(irq_status & RX_START)
{
}
/*Address matching interrupt*/
if(irq_status & AMI)
{
}
if(irq_status & TRX_UR)
{
}
/*Frame end interrupt (RX and TX)*/
if(irq_status & TRX_END)
{
/*TX done interrupt*/
if(rf_if_read_trx_state() == PLL_ON || rf_if_read_trx_state() == TX_ARET_ON)
{
rf_handle_tx_end();
}
/*Frame received interrupt*/
else
{
rf_handle_rx_end();
}
}
if(irq_status & CCA_ED_DONE)
{
rf_handle_cca_ed_done();
}
}
/*
* \brief Function writes/read data in SPI interface
*
* \param out Output data
*
* \return Input data
*/
static uint8_t rf_if_spi_exchange(uint8_t out)
{
uint8_t v;
v = rf->spi.write(out);
// t9 = t5 = 250ns, delay between LSB of last byte to next MSB or delay between LSB & SEL rising
// [SPI setup assumed slow enough to not need manual delay]
// delay_ns(250);
return v;
}
/*
* \brief Function sets given RF flag on.
*
* \param x Given RF flag
*
* \return none
*/
static void rf_flags_set(uint8_t x)
{
rf_flags |= x;
}
/*
* \brief Function clears given RF flag on.
*
* \param x Given RF flag
*
* \return none
*/
static void rf_flags_clear(uint8_t x)
{
rf_flags &= ~x;
}
/*
* \brief Function checks if given RF flag is on.
*
* \param x Given RF flag
*
* \return states of the given flags
*/
static uint8_t rf_flags_check(uint8_t x)
{
return (rf_flags & x);
}
/*
* \brief Function clears all RF flags.
*
* \param none
*
* \return none
*/
static void rf_flags_reset(void)
{
rf_flags = 0;
}
/*
* \brief Function initialises and registers the RF driver.
*
* \param none
*
* \return rf_radio_driver_id Driver ID given by NET library
*/
static int8_t rf_device_register(const uint8_t *mac_addr)
{
rf_trx_part_e radio_type;
rf_init();
radio_type = rf_radio_type_read();
if(radio_type != ATMEL_UNKNOW_DEV)
{
/*Set pointer to MAC address*/
device_driver.PHY_MAC = (uint8_t *)mac_addr;
device_driver.driver_description = (char*)"ATMEL_MAC";
//Create setup Used Radio chips
if(radio_type == ATMEL_AT86RF212)
{
device_driver.link_type = PHY_LINK_15_4_SUBGHZ_TYPE;
}
else
{
device_driver.link_type = PHY_LINK_15_4_2_4GHZ_TYPE;
}
device_driver.phy_channel_pages = phy_channel_pages;
/*Maximum size of payload is 127*/
device_driver.phy_MTU = 127;
/*No header in PHY*/
device_driver.phy_header_length = 0;
/*No tail in PHY*/
device_driver.phy_tail_length = 0;
/*Set address write function*/
device_driver.address_write = &rf_address_write;
/*Set RF extension function*/
device_driver.extension = &rf_extension;
/*Set RF state control function*/
device_driver.state_control = &rf_interface_state_control;
/*Set transmit function*/
device_driver.tx = &rf_start_cca;
/*NULLIFY rx and tx_done callbacks*/
device_driver.phy_rx_cb = NULL;
device_driver.phy_tx_done_cb = NULL;
/*Register device driver*/
rf_radio_driver_id = arm_net_phy_register(&device_driver);
}
return rf_radio_driver_id;
}
/*
* \brief Function unregisters the RF driver.
*
* \param none
*
* \return none
*/
static void rf_device_unregister()
{
if (rf_radio_driver_id >= 0) {
arm_net_phy_unregister(rf_radio_driver_id);
rf_radio_driver_id = -1;
}
}
/*
* \brief Function is a call back for ACK wait timeout.
*
* \param none
*
* \return none
*/
static void rf_ack_wait_timer_interrupt(void)
{
rf_if_lock();
/*Force PLL state*/
rf_if_change_trx_state(FORCE_PLL_ON);
rf_poll_trx_state_change(PLL_ON);
/*Start receiver in RX_AACK_ON state*/
rf_rx_mode = 0;
rf_flags_clear(RFF_RX);
rf_receive();
rf_if_unlock();
}
/*
* \brief Function is a call back for calibration interval timer.
*
* \param none
*
* \return none
*/
static void rf_calibration_timer_interrupt(void)
{
/*Calibrate RF*/
rf_calibration_cb();
/*Start new calibration timeout*/
rf_calibration_timer_start(RF_CALIBRATION_INTERVAL);
}
/*
* \brief Function is a call back for cca interval timer.
*
* \param none
*
* \return none
*/
static void rf_cca_timer_interrupt(void)
{
/*Start CCA process*/
if(rf_if_read_trx_state() == BUSY_RX_AACK)
{
if(device_driver.phy_tx_done_cb){
device_driver.phy_tx_done_cb(rf_radio_driver_id, mac_tx_handle, PHY_LINK_CCA_FAIL, 1, 1);
}
}
else
{
/*Set radio in RX state to read channel*/
rf_receive();
rf_if_enable_cca_ed_done_interrupt();
rf_if_start_cca_process();
}
}
/*
* \brief Function starts the ACK wait timeout.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_ack_wait_timer_start(uint16_t slots)
{
rf_if_ack_wait_timer_start(slots);
}
/*
* \brief Function starts the calibration interval.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_calibration_timer_start(uint32_t slots)
{
rf_if_calibration_timer_start(slots);
}
/*
* \brief Function starts the CCA timout.
*
* \param slots Given slots, resolution 50us
*
* \return none
*/
static void rf_cca_timer_start(uint32_t slots)
{
rf_if_cca_timer_start(slots);
}
/*
* \brief Function stops the ACK wait timeout.
*
* \param none
*
* \return none
*/
static void rf_ack_wait_timer_stop(void)
{
rf_if_ack_wait_timer_stop();
}
/*
* \brief Function writes various RF settings in startup.
*
* \param none
*
* \return none
*/
static void rf_write_settings(void)
{
rf_if_lock();
rf_if_write_rf_settings();
/*Set output power*/
rf_if_write_set_tx_power_register(radio_tx_power);
/*Initialise Antenna Diversity*/
if(rf_use_antenna_diversity)
rf_if_write_antenna_diversity_settings();
rf_if_unlock();
}
/*
* \brief Function writes 16-bit address in RF address filter.
*
* \param short_address Given short address
*
* \return none
*/
static void rf_set_short_adr(uint8_t * short_address)
{
rf_if_lock();
/*Wake up RF if sleeping*/
if(rf_flags_check(RFF_ON) == 0)
{
rf_if_disable_slptr();
rf_poll_trx_state_change(TRX_OFF);
}
/*Write address filter registers*/
rf_if_write_short_addr_registers(short_address);
/*RF back to sleep*/
if(rf_flags_check(RFF_ON) == 0)
{
rf_if_enable_slptr();
}
rf_if_unlock();
}
/*
* \brief Function writes PAN Id in RF PAN Id filter.
*
* \param pan_id Given PAN Id
*
* \return none
*/
static void rf_set_pan_id(uint8_t *pan_id)
{
rf_if_lock();
/*Wake up RF if sleeping*/
if(rf_flags_check(RFF_ON) == 0)
{
rf_if_disable_slptr();
rf_poll_trx_state_change(TRX_OFF);
}
/*Write address filter registers*/
rf_if_write_pan_id_registers(pan_id);
/*RF back to sleep*/
if(rf_flags_check(RFF_ON) == 0)
{
rf_if_enable_slptr();
}
rf_if_unlock();
}
/*
* \brief Function writes 64-bit address in RF address filter.
*
* \param address Given 64-bit address
*
* \return none
*/
static void rf_set_address(uint8_t *address)
{
rf_if_lock();
/*Wake up RF if sleeping*/
if(rf_flags_check(RFF_ON) == 0)
{
rf_if_disable_slptr();
rf_poll_trx_state_change(TRX_OFF);
}
/*Write address filter registers*/
rf_if_write_ieee_addr_registers(address);
/*RF back to sleep*/
if(rf_flags_check(RFF_ON) == 0)
{
rf_if_enable_slptr();
}
rf_if_unlock();
}
/*
* \brief Function sets the RF channel.
*
* \param ch New channel
*
* \return none
*/
static void rf_channel_set(uint8_t ch)
{
rf_if_lock();
rf_phy_channel = ch;
if(ch < 0x1f)
rf_if_set_channel_register(ch);
rf_if_unlock();
}
/*
* \brief Function initialises the radio driver and resets the radio.
*
* \param none
*
* \return none
*/
static void rf_init(void)
{
/*Reset RF module*/
rf_if_reset_radio();
rf_if_lock();
/*Write RF settings*/
rf_write_settings();
/*Initialise PHY mode*/
rf_init_phy_mode();
/*Clear RF flags*/
rf_flags_reset();
/*Set RF in TRX OFF state*/
rf_if_change_trx_state(TRX_OFF);
/*Set RF in PLL_ON state*/
rf_if_change_trx_state(PLL_ON);
/*Start receiver*/
rf_receive();
/*Read random variable. This will be used when seeding pseudo-random generator*/
rf_rnd_rssi = rf_if_read_rnd();
/*Start RF calibration timer*/
rf_calibration_timer_start(RF_CALIBRATION_INTERVAL);
rf_if_unlock();
}
/**
* \brief Function gets called when MAC is setting radio off.
*
* \param none
*
* \return none
*/
static void rf_off(void)
{
if(rf_flags_check(RFF_ON))
{
rf_if_lock();
rf_cca_abort();
uint16_t while_counter = 0;
/*Wait while receiving*/
while(rf_if_read_trx_state() == BUSY_RX_AACK)
{
while_counter++;
if(while_counter == 0xffff)
break;
}
/*RF state change: RX_AACK_ON->PLL_ON->TRX_OFF->SLEEP*/
if(rf_if_read_trx_state() == RX_AACK_ON)
{
rf_if_change_trx_state(PLL_ON);
}
rf_if_change_trx_state(TRX_OFF);
rf_if_enable_slptr();
/*Disable Antenna Diversity*/
if(rf_use_antenna_diversity)
rf_if_disable_ant_div();
rf_if_unlock();
}
/*Clears all flags*/
rf_flags_reset();
}
/*
* \brief Function polls the RF state until it has changed to desired state.
*
* \param trx_state RF state
*
* \return none
*/
static void rf_poll_trx_state_change(rf_trx_states_t trx_state)
{
uint16_t while_counter = 0;
rf_if_lock();
if(trx_state != RF_TX_START)
{
if(trx_state == FORCE_PLL_ON)
trx_state = PLL_ON;
else if(trx_state == FORCE_TRX_OFF)
trx_state = TRX_OFF;
while(rf_if_read_trx_state() != trx_state)
{
while_counter++;
if(while_counter == 0x1ff)
break;
}
}
rf_if_unlock();
}
/*
* \brief Function starts the CCA process before starting data transmission and copies the data to RF TX FIFO.
*
* \param data_ptr Pointer to TX data
* \param data_length Length of the TX data
* \param tx_handle Handle to transmission
* \return 0 Success
* \return -1 Busy
*/
static int8_t rf_start_cca(uint8_t *data_ptr, uint16_t data_length, uint8_t tx_handle, data_protocol_e data_protocol )
{
(void)data_protocol;
/*Check if transmitter is busy*/
if(rf_if_read_trx_state() == BUSY_RX_AACK)
{
/*Return busy*/
return -1;
}
else
{
rf_if_lock();
/*Check if transmitted data needs to be acked*/
if(*data_ptr & 0x20)
need_ack = 1;
else
need_ack = 0;
/*Store the sequence number for ACK handling*/
tx_sequence = *(data_ptr + 2);
/*Write TX FIFO*/
rf_if_write_frame_buffer(data_ptr, (uint8_t)data_length);
rf_flags_set(RFF_CCA);
/*Start CCA timeout*/
rf_cca_timer_start(RF_CCA_BASE_BACKOFF + randLIB_get_random_in_range(0, RF_CCA_RANDOM_BACKOFF));
/*Store TX handle*/
mac_tx_handle = tx_handle;
rf_if_unlock();
}
/*Return success*/
return 0;
}
/*
* \brief Function aborts CCA process.
*
* \param none
*
* \return none
*/
static void rf_cca_abort(void)
{
/*Clear RFF_CCA RF flag*/
rf_flags_clear(RFF_CCA);
}
/*
* \brief Function starts the transmission of the frame.
*
* \param none
*
* \return none
*/
static void rf_start_tx(void)
{
/*Only start transmitting from RX state*/
uint8_t trx_state = rf_if_read_trx_state();
if(trx_state != RX_AACK_ON)
{
if(device_driver.phy_tx_done_cb){
device_driver.phy_tx_done_cb(rf_radio_driver_id, mac_tx_handle, PHY_LINK_CCA_FAIL, 1, 1);
}
}
else
{
/*RF state change: ->PLL_ON->RF_TX_START*/
rf_if_change_trx_state(FORCE_PLL_ON);
rf_flags_clear(RFF_RX);
rf_if_enable_tx_end_interrupt();
rf_flags_set(RFF_TX);
rf_if_change_trx_state(RF_TX_START);
}
}
/*
* \brief Function sets the RF in RX state.
*
* \param none
*
* \return none
*/
static void rf_receive(void)
{
uint16_t while_counter = 0;
if(rf_flags_check(RFF_ON) == 0)
{
rf_on();
}
/*If not yet in RX state set it*/
if(rf_flags_check(RFF_RX) == 0)
{
rf_if_lock();
/*Wait while receiving data*/
while(rf_if_read_trx_state() == BUSY_RX_AACK)
{
while_counter++;
if(while_counter == 0xffff)
{
break;
}
}
rf_if_change_trx_state(PLL_ON);
if((rf_mode == RF_MODE_SNIFFER) || (rf_mode == RF_MODE_ED))
{
rf_if_change_trx_state(RX_ON);
}
else
{
/*ACK is always received in promiscuous mode to bypass address filters*/
if(rf_rx_mode)
{
rf_rx_mode = 0;
rf_if_enable_promiscuous_mode();
}
else
{
rf_if_disable_promiscuous_mode();
}
rf_if_change_trx_state(RX_AACK_ON);
}
/*If calibration timer was unable to calibrate the RF, run calibration now*/
if(!rf_tuned)
{
/*Start calibration. This can be done in states TRX_OFF, PLL_ON or in any receive state*/
rf_if_calibration();
/*RF is tuned now*/
rf_tuned = 1;
}
rf_channel_set(rf_phy_channel);
rf_flags_set(RFF_RX);
// Don't receive packets when ED mode enabled
if (rf_mode != RF_MODE_ED)
{
rf_if_enable_rx_end_interrupt();
}
rf_if_unlock();
}
/*Stop the running CCA process*/
if(rf_flags_check(RFF_CCA))
rf_cca_abort();
}
/*
* \brief Function calibrates the radio.
*
* \param none
*
* \return none
*/
static void rf_calibration_cb(void)
{
/*clear tuned flag to start tuning in rf_receive*/
rf_tuned = 0;
/*If RF is in default receive state, start calibration*/
if(rf_if_read_trx_state() == RX_AACK_ON)
{
rf_if_lock();
/*Set RF in PLL_ON state*/
rf_if_change_trx_state(PLL_ON);
/*Set RF in TRX_OFF state to start PLL tuning*/
rf_if_change_trx_state(TRX_OFF);
/*Set RF in RX_ON state to calibrate*/
rf_if_change_trx_state(RX_ON);
/*Calibrate FTN*/
rf_if_calibration();
/*RF is tuned now*/
rf_tuned = 1;
/*Back to default receive state*/
rf_flags_clear(RFF_RX);
rf_receive();
rf_if_unlock();
}
}
/*
* \brief Function sets RF_ON flag when radio is powered.
*
* \param none
*
* \return none
*/
static void rf_on(void)
{
/*Set RFF_ON flag*/
if(rf_flags_check(RFF_ON) == 0)
{
rf_if_lock();
rf_flags_set(RFF_ON);
/*Enable Antenna diversity*/
if(rf_use_antenna_diversity)
/*Set ANT_EXT_SW_EN to enable controlling of antenna diversity*/
rf_if_enable_ant_div();
/*Wake up from sleep state*/
rf_if_disable_slptr();
rf_poll_trx_state_change(TRX_OFF);
rf_if_unlock();
}
}
/*
* \brief Function handles the received ACK frame.
*
* \param seq_number Sequence number of received ACK
* \param data_pending Pending bit state in received ACK
*
* \return none
*/
static void rf_handle_ack(uint8_t seq_number, uint8_t data_pending)
{
phy_link_tx_status_e phy_status;
rf_if_lock();
/*Received ACK sequence must be equal with transmitted packet sequence*/
if(tx_sequence == seq_number)
{
rf_ack_wait_timer_stop();
/*When data pending bit in ACK frame is set, inform NET library*/
if(data_pending)
phy_status = PHY_LINK_TX_DONE_PENDING;
else
phy_status = PHY_LINK_TX_DONE;
/*Call PHY TX Done API*/
if(device_driver.phy_tx_done_cb){
device_driver.phy_tx_done_cb(rf_radio_driver_id, mac_tx_handle,phy_status, 1, 1);
}
}
rf_if_unlock();
}
/*
* \brief Function is a call back for RX end interrupt.
*
* \param none
*
* \return none
*/
static void rf_handle_rx_end(void)
{
uint8_t rf_lqi = 0;
int8_t rf_rssi = 0;
/*Start receiver*/
rf_flags_clear(RFF_RX);
rf_receive();
/*Frame received interrupt*/
if(rf_flags_check(RFF_RX))
{
/*Check CRC_valid bit*/
if(rf_if_check_crc())
{
uint8_t *rf_rx_ptr;
uint8_t receiving_ack = 0;
/*Read length*/
uint8_t len = rf_if_read_received_frame_length();
rf_rx_ptr = rf_buffer;
/*ACK frame*/
if(len == 5)
{
/*Read ACK in static ACK buffer*/
receiving_ack = 1;
}
/*Check the length is valid*/
if(len > 1 && len < RF_BUFFER_SIZE)
{
/*Read received packet*/
rf_if_read_packet(rf_rx_ptr, len);
if(!receiving_ack)
{
rf_rssi = rf_if_read_rssi();
/*Scale LQI using received RSSI*/
rf_lqi = rf_scale_lqi(rf_rssi);
}
if(rf_mode == RF_MODE_SNIFFER)
{
if( device_driver.phy_rx_cb ){
device_driver.phy_rx_cb(rf_buffer,len - 2, rf_lqi, rf_rssi, rf_radio_driver_id);
}
}
else
{
/*Handle received ACK*/
if(receiving_ack && ((rf_buffer[0] & 0x07) == 0x02))
{
uint8_t pending = 0;
/*Check if data is pending*/
if ((rf_buffer[0] & 0x10))
{
pending=1;
}
/*Send sequence number in ACK handler*/
rf_handle_ack(rf_buffer[2], pending);
}
else
{
if( device_driver.phy_rx_cb ){
device_driver.phy_rx_cb(rf_buffer,len - 2, rf_lqi, rf_rssi, rf_radio_driver_id);
}
}
}
}
}
}
}
/*
* \brief Function is called when MAC is shutting down the radio.
*
* \param none
*
* \return none
*/
static void rf_shutdown(void)
{
/*Call RF OFF*/
rf_off();
}
/*
* \brief Function is a call back for TX end interrupt.
*
* \param none
*
* \return none
*/
static void rf_handle_tx_end(void)
{
phy_link_tx_status_e phy_status = PHY_LINK_TX_SUCCESS;
rf_rx_mode = 0;
/*If ACK is needed for this transmission*/
if(need_ack && rf_flags_check(RFF_TX))
{
rf_ack_wait_timer_start(rf_ack_wait_duration);
rf_rx_mode = 1;
}
rf_flags_clear(RFF_RX);
/*Start receiver*/
rf_receive();
/*Call PHY TX Done API*/
if(device_driver.phy_tx_done_cb){
device_driver.phy_tx_done_cb(rf_radio_driver_id, mac_tx_handle, phy_status, 1, 1);
}
}
/*
* \brief Function is a call back for CCA ED done interrupt.
*
* \param none
*
* \return none
*/
static void rf_handle_cca_ed_done(void)
{
rf_flags_clear(RFF_CCA);
/*Check the result of CCA process*/
if(rf_if_check_cca())
{
rf_start_tx();
}
else
{
/*Send CCA fail notification*/
if(device_driver.phy_tx_done_cb){
device_driver.phy_tx_done_cb(rf_radio_driver_id, mac_tx_handle, PHY_LINK_CCA_FAIL, 1, 1);
}
}
}
/*
* \brief Function returns the TX power variable.
*
* \param none
*
* \return radio_tx_power TX power variable
*/
MBED_UNUSED static uint8_t rf_tx_power_get(void)
{
return radio_tx_power;
}
/*
* \brief Function enables the usage of Antenna diversity.
*
* \param none
*
* \return 0 Success
*/
MBED_UNUSED static int8_t rf_enable_antenna_diversity(void)
{
int8_t ret_val = 0;
rf_use_antenna_diversity = 1;
return ret_val;
}
/*
* \brief Function gives the control of RF states to MAC.
*
* \param new_state RF state
* \param rf_channel RF channel
*
* \return 0 Success
*/
static int8_t rf_interface_state_control(phy_interface_state_e new_state, uint8_t rf_channel)
{
int8_t ret_val = 0;
switch (new_state)
{
/*Reset PHY driver and set to idle*/
case PHY_INTERFACE_RESET:
break;
/*Disable PHY Interface driver*/
case PHY_INTERFACE_DOWN:
rf_shutdown();
break;
/*Enable PHY Interface driver*/
case PHY_INTERFACE_UP:
rf_mode = RF_MODE_NORMAL;
rf_channel_set(rf_channel);
rf_receive();
rf_if_enable_irq();
break;
/*Enable wireless interface ED scan mode*/
case PHY_INTERFACE_RX_ENERGY_STATE:
rf_mode = RF_MODE_ED;
rf_channel_set(rf_channel);
rf_receive();
rf_if_disable_irq();
// Read status to clear pending flags.
rf_if_read_register(IRQ_STATUS);
// Must set interrupt mask to be able to read IRQ status. GPIO interrupt is disabled.
rf_if_set_bit(IRQ_MASK, CCA_ED_DONE, CCA_ED_DONE);
// ED can be initiated by writing arbitrary value to PHY_ED_LEVEL
rf_if_write_register(PHY_ED_LEVEL, 0xff);
break;
case PHY_INTERFACE_SNIFFER_STATE: /**< Enable Sniffer state */
rf_mode = RF_MODE_SNIFFER;
rf_channel_set(rf_channel);
rf_flags_clear(RFF_RX);
rf_receive();
break;
}
return ret_val;
}
/*
* \brief Function controls the ACK pending, channel setting and energy detection.
*
* \param extension_type Type of control
* \param data_ptr Data from NET library
*
* \return 0 Success
*/
static int8_t rf_extension(phy_extension_type_e extension_type, uint8_t *data_ptr)
{
switch (extension_type)
{
/*Control MAC pending bit for Indirect data transmission*/
case PHY_EXTENSION_CTRL_PENDING_BIT:
if(*data_ptr)
{
rf_if_ack_pending_ctrl(1);
}
else
{
rf_if_ack_pending_ctrl(0);
}
break;
/*Return frame pending status*/
case PHY_EXTENSION_READ_LAST_ACK_PENDING_STATUS:
*data_ptr = rf_if_last_acked_pending();
break;
/*Set channel*/
case PHY_EXTENSION_SET_CHANNEL:
break;
/*Read energy on the channel*/
case PHY_EXTENSION_READ_CHANNEL_ENERGY:
// End of the ED measurement is indicated by CCA_ED_DONE
while (!(rf_if_read_register(IRQ_STATUS) & CCA_ED_DONE));
// RF input power: RSSI base level + 1[db] * PHY_ED_LEVEL
*data_ptr = rf_sensitivity + rf_if_read_register(PHY_ED_LEVEL);
// Read status to clear pending flags.
rf_if_read_register(IRQ_STATUS);
// Next ED measurement is started, next PHY_EXTENSION_READ_CHANNEL_ENERGY call will return the result.
rf_if_write_register(PHY_ED_LEVEL, 0xff);
break;
/*Read status of the link*/
case PHY_EXTENSION_READ_LINK_STATUS:
break;
default:
break;
}
return 0;
}
/*
* \brief Function sets the addresses to RF address filters.
*
* \param address_type Type of address
* \param address_ptr Pointer to given address
*
* \return 0 Success
*/
static int8_t rf_address_write(phy_address_type_e address_type, uint8_t *address_ptr)
{
int8_t ret_val = 0;
switch (address_type)
{
/*Set 48-bit address*/
case PHY_MAC_48BIT:
break;
/*Set 64-bit address*/
case PHY_MAC_64BIT:
rf_set_address(address_ptr);
break;
/*Set 16-bit address*/
case PHY_MAC_16BIT:
rf_set_short_adr(address_ptr);
break;
/*Set PAN Id*/
case PHY_MAC_PANID:
rf_set_pan_id(address_ptr);
break;
}
return ret_val;
}
/*
* \brief Function initialises the ACK wait time and returns the used PHY mode.
*
* \param none
*
* \return tmp Used PHY mode
*/
static void rf_init_phy_mode(void)
{
uint8_t tmp = 0;
uint8_t part = rf_if_read_part_num();
/*Read used PHY Mode*/
tmp = rf_if_read_register(TRX_CTRL_2);
/*Set ACK wait time for used data rate*/
if(part == PART_AT86RF212)
{
if((tmp & 0x1f) == 0x00)
{
rf_sensitivity = -110;
rf_ack_wait_duration = 938;
tmp = BPSK_20;
}
else if((tmp & 0x1f) == 0x04)
{
rf_sensitivity = -108;
rf_ack_wait_duration = 469;
tmp = BPSK_40;
}
else if((tmp & 0x1f) == 0x14)
{
rf_sensitivity = -108;
rf_ack_wait_duration = 469;
tmp = BPSK_40_ALT;
}
else if((tmp & 0x1f) == 0x08)
{
rf_sensitivity = -101;
rf_ack_wait_duration = 50;
tmp = OQPSK_SIN_RC_100;
}
else if((tmp & 0x1f) == 0x09)
{
rf_sensitivity = -99;
rf_ack_wait_duration = 30;
tmp = OQPSK_SIN_RC_200;
}
else if((tmp & 0x1f) == 0x18)
{
rf_sensitivity = -102;
rf_ack_wait_duration = 50;
tmp = OQPSK_RC_100;
}
else if((tmp & 0x1f) == 0x19)
{
rf_sensitivity = -100;
rf_ack_wait_duration = 30;
tmp = OQPSK_RC_200;
}
else if((tmp & 0x1f) == 0x0c)
{
rf_sensitivity = -100;
rf_ack_wait_duration = 20;
tmp = OQPSK_SIN_250;
}
else if((tmp & 0x1f) == 0x0d)
{
rf_sensitivity = -98;
rf_ack_wait_duration = 25;
tmp = OQPSK_SIN_500;
}
else if((tmp & 0x1f) == 0x0f)
{
rf_sensitivity = -98;
rf_ack_wait_duration = 25;
tmp = OQPSK_SIN_500_ALT;
}
else if((tmp & 0x1f) == 0x1c)
{
rf_sensitivity = -101;
rf_ack_wait_duration = 20;
tmp = OQPSK_RC_250;
}
else if((tmp & 0x1f) == 0x1d)
{
rf_sensitivity = -99;
rf_ack_wait_duration = 25;
tmp = OQPSK_RC_500;
}
else if((tmp & 0x1f) == 0x1f)
{
rf_sensitivity = -99;
rf_ack_wait_duration = 25;
tmp = OQPSK_RC_500_ALT;
}
else if((tmp & 0x3f) == 0x2A)
{
rf_sensitivity = -91;
rf_ack_wait_duration = 25;
tmp = OQPSK_SIN_RC_400_SCR_ON;
}
else if((tmp & 0x3f) == 0x0A)
{
rf_sensitivity = -91;
rf_ack_wait_duration = 25;
tmp = OQPSK_SIN_RC_400_SCR_OFF;
}
else if((tmp & 0x3f) == 0x3A)
{
rf_sensitivity = -97;
rf_ack_wait_duration = 25;
tmp = OQPSK_RC_400_SCR_ON;
}
else if((tmp & 0x3f) == 0x1A)
{
rf_sensitivity = -97;
rf_ack_wait_duration = 25;
tmp = OQPSK_RC_400_SCR_OFF;
}
else if((tmp & 0x3f) == 0x2E)
{
rf_sensitivity = -93;
rf_ack_wait_duration = 13;
tmp = OQPSK_SIN_1000_SCR_ON;
}
else if((tmp & 0x3f) == 0x0E)
{
rf_sensitivity = -93;
rf_ack_wait_duration = 13;
tmp = OQPSK_SIN_1000_SCR_OFF;
}
else if((tmp & 0x3f) == 0x3E)
{
rf_sensitivity = -95;
rf_ack_wait_duration = 13;
tmp = OQPSK_RC_1000_SCR_ON;
}
else if((tmp & 0x3f) == 0x1E)
{
rf_sensitivity = -95;
rf_ack_wait_duration = 13;
tmp = OQPSK_RC_1000_SCR_OFF;
}
}
else
{
rf_sensitivity = -101;
rf_ack_wait_duration = 20;
}
/*Board design might reduces the sensitivity*/
//rf_sensitivity += RF_SENSITIVITY_CALIBRATION;
}
static uint8_t rf_scale_lqi(int8_t rssi)
{
uint8_t scaled_lqi;
/*rssi < RF sensitivity*/
if(rssi < rf_sensitivity)
scaled_lqi=0;
/*-91 dBm < rssi < -81 dBm (AT86RF233 XPro)*/
/*-90 dBm < rssi < -80 dBm (AT86RF212B XPro)*/
else if(rssi < (rf_sensitivity + 10))
scaled_lqi=31;
/*-81 dBm < rssi < -71 dBm (AT86RF233 XPro)*/
/*-80 dBm < rssi < -70 dBm (AT86RF212B XPro)*/
else if(rssi < (rf_sensitivity + 20))
scaled_lqi=207;
/*-71 dBm < rssi < -61 dBm (AT86RF233 XPro)*/
/*-70 dBm < rssi < -60 dBm (AT86RF212B XPro)*/
else if(rssi < (rf_sensitivity + 30))
scaled_lqi=255;
/*-61 dBm < rssi < -51 dBm (AT86RF233 XPro)*/
/*-60 dBm < rssi < -50 dBm (AT86RF212B XPro)*/
else if(rssi < (rf_sensitivity + 40))
scaled_lqi=255;
/*-51 dBm < rssi < -41 dBm (AT86RF233 XPro)*/
/*-50 dBm < rssi < -40 dBm (AT86RF212B XPro)*/
else if(rssi < (rf_sensitivity + 50))
scaled_lqi=255;
/*-41 dBm < rssi < -31 dBm (AT86RF233 XPro)*/
/*-40 dBm < rssi < -30 dBm (AT86RF212B XPro)*/
else if(rssi < (rf_sensitivity + 60))
scaled_lqi=255;
/*-31 dBm < rssi < -21 dBm (AT86RF233 XPro)*/
/*-30 dBm < rssi < -20 dBm (AT86RF212B XPro)*/
else if(rssi < (rf_sensitivity + 70))
scaled_lqi=255;
/*rssi > RF saturation*/
else if(rssi > (rf_sensitivity + 80))
scaled_lqi=111;
/*-21 dBm < rssi < -11 dBm (AT86RF233 XPro)*/
/*-20 dBm < rssi < -10 dBm (AT86RF212B XPro)*/
else
scaled_lqi=255;
return scaled_lqi;
}
NanostackRfPhyAtmel::NanostackRfPhyAtmel(PinName spi_mosi, PinName spi_miso,
PinName spi_sclk, PinName spi_cs, PinName spi_rst, PinName spi_slp, PinName spi_irq,
PinName i2c_sda, PinName i2c_scl)
: _mac(i2c_sda, i2c_scl), _mac_addr(), _rf(NULL), _mac_set(false),
_spi_mosi(spi_mosi), _spi_miso(spi_miso), _spi_sclk(spi_sclk),
_spi_cs(spi_cs), _spi_rst(spi_rst), _spi_slp(spi_slp), _spi_irq(spi_irq)
{
_rf = new RFBits(_spi_mosi, _spi_miso, _spi_sclk, _spi_cs, _spi_rst, _spi_slp, _spi_irq);
}
NanostackRfPhyAtmel::~NanostackRfPhyAtmel()
{
delete _rf;
}
int8_t NanostackRfPhyAtmel::rf_register()
{
if (NULL == _rf) {
return -1;
}
rf_if_lock();
if (rf != NULL) {
rf_if_unlock();
error("Multiple registrations of NanostackRfPhyAtmel not supported");
return -1;
}
// Read the mac address if it hasn't been set by a user
rf = _rf;
if (!_mac_set) {
int ret = _mac.read_eui64((void*)_mac_addr);
if (ret < 0) {
rf = NULL;
rf_if_unlock();
return -1;
}
}
int8_t radio_id = rf_device_register(_mac_addr);
if (radio_id < 0) {
rf = NULL;
}
rf_if_unlock();
return radio_id;
}
void NanostackRfPhyAtmel::rf_unregister()
{
rf_if_lock();
if (NULL == rf) {
rf_if_unlock();
return;
}
rf_device_unregister();
rf = NULL;
rf_if_unlock();
}
void NanostackRfPhyAtmel::get_mac_address(uint8_t *mac)
{
rf_if_lock();
if (NULL == rf) {
error("NanostackRfPhyAtmel Must be registered to read mac address");
rf_if_unlock();
return;
}
memcpy((void*)mac, (void*)_mac_addr, sizeof(_mac_addr));
rf_if_unlock();
}
void NanostackRfPhyAtmel::set_mac_address(uint8_t *mac)
{
rf_if_lock();
if (NULL != rf) {
error("NanostackRfPhyAtmel cannot change mac address when running");
rf_if_unlock();
return;
}
memcpy((void*)_mac_addr, (void*)mac, sizeof(_mac_addr));
_mac_set = true;
rf_if_unlock();
}
| 23.774861 | 121 | 0.64447 | [
"vector"
] |
1c73f8f193efb09271152766df51d8734198609e | 5,235 | cpp | C++ | src/pcd/types.cpp | ErlangZ/Caffe | fcbd1c8871e31a5abdc40f7eac92929fd697363d | [
"BSD-2-Clause"
] | null | null | null | src/pcd/types.cpp | ErlangZ/Caffe | fcbd1c8871e31a5abdc40f7eac92929fd697363d | [
"BSD-2-Clause"
] | null | null | null | src/pcd/types.cpp | ErlangZ/Caffe | fcbd1c8871e31a5abdc40f7eac92929fd697363d | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2016 Baidu.com, Inc. All Rights Reserved
// @author erlangz(zhengwenchao@baidu.com)
// @date 2016/12/22 16:13:51
// @file types.cpp
// @brief
#include "pcd/types.h"
#include <boost/typeof/typeof.hpp>
#include <boost/foreach.hpp>
#include <pcl/filters/extract_indices.h>
namespace adu {
namespace perception {
Box::Box(const std::string& file_, int id_, const pt::ptree& root) {
file = file_;
id = id_;
//Rotation
BOOST_AUTO(r, root.get_child("rotation"));
//phi - Z axis; theta - X axis; psi - Y axis
rotation_z = Eigen::AngleAxisd(r.get<double>("phi"), Eigen::Vector3d::UnitZ());
rotation_x = Eigen::AngleAxisd(r.get<double>("theta"), Eigen::Vector3d::UnitX());
rotation_y = Eigen::AngleAxisd(r.get<double>("psi"), Eigen::Vector3d::UnitY());
std::vector<double> size;
BOOST_FOREACH(const pt::ptree::value_type& item, root.get_child("size")) {
size.push_back(item.second.get_value<double>());
}
//AlignedBox
BOOST_AUTO(center, root.get_child("position"));
bounding_box = Eigen::AlignedBox3d(Eigen::Vector3d(center.get<double>("x") - size[0]/2, center.get<double>("y") - size[1]/2, center.get<double>("z") - size[2]/2),
Eigen::Vector3d(center.get<double>("x") + size[0]/2, center.get<double>("y") + size[1]/2, center.get<double>("z") + size[2]/2));
//Type
const std::string& type_str = root.get<std::string>("type");
if (type_str == "smallMot") {
type = smallMot;
} else if (type_str == "pedestrian") {
type = pedestrian;
} else if (type_str == "bigMot") {
type = bigMot;
} else if (type_str == "midMot") {
type = midMot;
} else if (type_str == "nonMot") {
type = nonMot;
} else if (type_str == "unknow") {
type = unknown;
} else if (type_str == "cluster") {
type = cluster;
} else {
std::cout << type_str << std::endl;
}
}
void Box::show(pcl::visualization::PCLVisualizer& viewer) {
Eigen::Vector3f color = get_color();
viewer.addCube(bounding_box.min().x(), bounding_box.max().x(),
bounding_box.min().y(), bounding_box.max().y(),
bounding_box.min().z(), bounding_box.max().z(),
color(0), color(1), color(2),
id_str());
}
pcl::PointCloud<pcl::PointXYZ>::Ptr Box::get_cloud(pcl::PointCloud<pcl::PointXYZ>::Ptr point_cloud) {
return BoxFilter::filter(point_cloud, BoxFilter::filter(point_cloud, *this));
}
std::string Box::type_str() const {
switch (type) {
case smallMot:
case midMot:
case bigMot: return "vehicle";
case pedestrian: return "pedestrian";
default: return "unknown";
}
}
const std::string Box::id_str() const {
std::stringstream ss;
ss << file << "-" << type << "-" << id;
return ss.str();
}
Eigen::Vector3f Box::get_color() const {
switch (type) {
case smallMot: return Eigen::Vector3f(0.0, 1.0, 0.0);
case midMot: return Eigen::Vector3f(0.0, 0.8, 0.0);
case bigMot: return Eigen::Vector3f(0.0, 0.9, 0.0);
case nonMot: return Eigen::Vector3f(0.0, 0.7, 0.0);
case pedestrian: return Eigen::Vector3f(1.0, 0.0, 0.0);
case cluster: return Eigen::Vector3f(0.0, 0.5, 0.5);
case unknown: return Eigen::Vector3f(0.0, 0.0, 1.0);
}
std::cerr << "PCD/Types.h Get Unknow Color:" << type << std::endl;
return Eigen::Vector3f(0.0, 0.0, 0.0);
}
std::string Box::debug_string() const {
std::stringstream ss;
ss << "type:" << type
<< " box:(" << bounding_box.max().transpose() << ","<< bounding_box.min().transpose() << ")";
return ss.str();
}
pcl::PointIndices::Ptr BoxFilter::filter(const pcl::PointCloud<pcl::PointXYZ>::Ptr& point_cloud, const Box& box) {
pcl::PointIndices::Ptr indice(new pcl::PointIndices);
for (size_t i = 0; i < point_cloud->size(); i++) {
if (box.bounding_box.exteriorDistance(Eigen::Vector3d(point_cloud->at(i).x, point_cloud->at(i).y, point_cloud->at(i).z)) == 0) {
indice->indices.push_back(i);
}
}
return indice;
}
pcl::PointCloud<pcl::PointXYZ>::Ptr BoxFilter::filter(
const pcl::PointCloud<pcl::PointXYZ>::Ptr& point_cloud,
const pcl::PointIndices::Ptr& point_indice) {
pcl::ExtractIndices<pcl::PointXYZ> eifilter(true);
eifilter.setInputCloud(point_cloud);
eifilter.setIndices(point_indice);
pcl::PointCloud<pcl::PointXYZ>::Ptr output_point(new pcl::PointCloud<pcl::PointXYZ>);
eifilter.filter(*output_point);
return output_point;
}
Label::Label(const std::string& file, const pt::ptree& root) {
file_name = file;
int i = 0;
BOOST_FOREACH(const pt::ptree::value_type& result, root.get_child("result")) {
boxes.push_back(Box::Ptr(new Box(file_name, i++, result.second)));
}
}
std::string Label::debug_string() const {
std::stringstream ss;
ss << "file_name:" << file_name
<< "Boxes:(" << boxes.size() << ")";
for (size_t i = 0; i < boxes.size(); i++) {
ss << "[" << boxes[i]->debug_string() << "]";
}
return ss.str();
}
} // namespace perception
} // namespace adu
| 35.612245 | 167 | 0.601337 | [
"vector"
] |
cc679bdaa21ece8c688a9e910d02cb1622ebc671 | 15,325 | hpp | C++ | libs/boost_1_72_0/boost/proto/fusion.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/proto/fusion.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/proto/fusion.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
/// \file fusion.hpp
/// Make any Proto expression a valid Fusion sequence
//
// Copyright 2008 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_PROTO_FUSION_HPP_EAN_11_04_2006
#define BOOST_PROTO_FUSION_HPP_EAN_11_04_2006
#include <boost/config.hpp>
#include <boost/fusion/include/as_list.hpp>
#include <boost/fusion/include/category_of.hpp>
#include <boost/fusion/include/intrinsic.hpp>
#include <boost/fusion/include/is_segmented.hpp>
#include <boost/fusion/include/is_view.hpp>
#include <boost/fusion/include/iterator_base.hpp>
#include <boost/fusion/include/single_view.hpp>
#include <boost/fusion/include/tag_of_fwd.hpp>
#include <boost/fusion/include/transform.hpp>
#include <boost/fusion/sequence/comparison/enable_comparison.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/long.hpp>
#include <boost/mpl/sequence_tag_fwd.hpp>
#include <boost/proto/eval.hpp>
#include <boost/proto/make_expr.hpp>
#include <boost/proto/proto_fwd.hpp>
#include <boost/proto/traits.hpp>
#include <boost/utility/enable_if.hpp>
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4510) // default constructor could not be generated
#pragma warning(disable : 4512) // assignment operator could not be generated
#pragma warning(disable : 4610) // can never be instantiated - user defined
// constructor required
#endif
namespace boost {
namespace proto {
namespace detail {
template <typename Expr, long Pos>
struct expr_iterator : fusion::iterator_base<expr_iterator<Expr, Pos>> {
typedef Expr expr_type;
static const long index = Pos;
typedef fusion::random_access_traversal_tag category;
typedef tag::proto_expr_iterator<typename Expr::proto_tag,
typename Expr::proto_domain>
fusion_tag;
explicit expr_iterator(Expr &e) : expr(e) {}
Expr &expr;
};
template <typename Tag> struct as_element {
template <typename Sig> struct result;
template <typename This, typename Expr>
struct result<This(Expr)> : result<This(Expr const &)> {};
template <typename This, typename Expr>
struct result<This(Expr &)>
: mpl::if_c<is_same<Tag, typename Expr::proto_tag>::value,
flat_view<Expr>, fusion::single_view<Expr &>> {};
template <typename Expr>
typename result<as_element(Expr &)>::type const operator()(Expr &e) const {
return typename result<as_element(Expr &)>::type(e);
}
template <typename Expr>
typename result<as_element(Expr const &)>::type const
operator()(Expr const &e) const {
return typename result<as_element(Expr const &)>::type(e);
}
};
template <typename Expr>
struct flat_view : fusion::sequence_base<flat_view<Expr>> {
typedef fusion::forward_traversal_tag category;
typedef tag::proto_flat_view<typename Expr::proto_tag,
typename Expr::proto_domain>
fusion_tag;
typedef
typename fusion::result_of::as_list<typename fusion::result_of::transform<
Expr, as_element<typename Expr::proto_tag>>::type>::type
segments_type;
explicit flat_view(Expr &e)
: segs_(fusion::as_list(
fusion::transform(e, as_element<typename Expr::proto_tag>()))) {}
segments_type segs_;
};
} // namespace detail
namespace result_of {
template <typename Expr> struct flatten : flatten<Expr const &> {};
template <typename Expr> struct flatten<Expr &> {
typedef detail::flat_view<Expr> type;
};
} // namespace result_of
namespace functional {
/// \brief A PolymorphicFunctionObject type that returns a "flattened"
/// view of a Proto expression tree.
///
/// A PolymorphicFunctionObject type that returns a "flattened"
/// view of a Proto expression tree. For a tree with a top-most node
/// tag of type \c T, the elements of the flattened sequence are
/// determined by recursing into each child node with the same
/// tag type and returning those nodes of different type. So for
/// instance, the Proto expression tree corresponding to the
/// expression <tt>a | b | c</tt> has a flattened view with elements
/// [a, b, c], even though the tree is grouped as
/// <tt>((a | b) | c)</tt>.
struct flatten {
BOOST_PROTO_CALLABLE()
template <typename Sig> struct result;
template <typename This, typename Expr>
struct result<This(Expr)> : result<This(Expr const &)> {};
template <typename This, typename Expr> struct result<This(Expr &)> {
typedef proto::detail::flat_view<Expr> type;
};
template <typename Expr>
proto::detail::flat_view<Expr> const operator()(Expr &e) const {
return proto::detail::flat_view<Expr>(e);
}
template <typename Expr>
proto::detail::flat_view<Expr const> const operator()(Expr const &e) const {
return proto::detail::flat_view<Expr const>(e);
}
};
} // namespace functional
/// \brief A function that returns a "flattened"
/// view of a Proto expression tree.
///
/// For a tree with a top-most node
/// tag of type \c T, the elements of the flattened sequence are
/// determined by recursing into each child node with the same
/// tag type and returning those nodes of different type. So for
/// instance, the Proto expression tree corresponding to the
/// expression <tt>a | b | c</tt> has a flattened view with elements
/// [a, b, c], even though the tree is grouped as
/// <tt>((a | b) | c)</tt>.
template <typename Expr> proto::detail::flat_view<Expr> const flatten(Expr &e) {
return proto::detail::flat_view<Expr>(e);
}
/// \overload
///
template <typename Expr>
proto::detail::flat_view<Expr const> const flatten(Expr const &e) {
return proto::detail::flat_view<Expr const>(e);
}
/// INTERNAL ONLY
///
template <typename Context> struct eval_fun : proto::callable {
explicit eval_fun(Context &ctx) : ctx_(ctx) {}
template <typename Sig> struct result;
template <typename This, typename Expr>
struct result<This(Expr)> : result<This(Expr const &)> {};
template <typename This, typename Expr>
struct result<This(Expr &)> : proto::result_of::eval<Expr, Context> {};
template <typename Expr>
typename proto::result_of::eval<Expr, Context>::type
operator()(Expr &e) const {
return proto::eval(e, this->ctx_);
}
template <typename Expr>
typename proto::result_of::eval<Expr const, Context>::type
operator()(Expr const &e) const {
return proto::eval(e, this->ctx_);
}
private:
Context &ctx_;
};
/// INTERNAL ONLY
///
template <typename Context>
struct is_callable<eval_fun<Context>> : mpl::true_ {};
} // namespace proto
} // namespace boost
namespace boost {
namespace fusion {
namespace extension {
template <typename Tag> struct is_sequence_impl;
template <typename Tag, typename Domain>
struct is_sequence_impl<proto::tag::proto_flat_view<Tag, Domain>> {
template <typename Sequence> struct apply : mpl::true_ {};
};
template <typename Tag, typename Domain>
struct is_sequence_impl<proto::tag::proto_expr<Tag, Domain>> {
template <typename Sequence> struct apply : mpl::true_ {};
};
template <typename Tag> struct is_view_impl;
template <typename Tag, typename Domain>
struct is_view_impl<proto::tag::proto_flat_view<Tag, Domain>> {
template <typename Sequence> struct apply : mpl::true_ {};
};
template <typename Tag, typename Domain>
struct is_view_impl<proto::tag::proto_expr<Tag, Domain>> {
template <typename Sequence> struct apply : mpl::false_ {};
};
template <typename Tag> struct value_of_impl;
template <typename Tag, typename Domain>
struct value_of_impl<proto::tag::proto_expr_iterator<Tag, Domain>> {
template <typename Iterator,
long Arity = proto::arity_of<typename Iterator::expr_type>::value>
struct apply {
typedef
typename proto::result_of::child_c<typename Iterator::expr_type,
Iterator::index>::value_type type;
};
template <typename Iterator> struct apply<Iterator, 0> {
typedef typename proto::result_of::value<
typename Iterator::expr_type>::value_type type;
};
};
template <typename Tag> struct deref_impl;
template <typename Tag, typename Domain>
struct deref_impl<proto::tag::proto_expr_iterator<Tag, Domain>> {
template <typename Iterator,
long Arity = proto::arity_of<typename Iterator::expr_type>::value>
struct apply {
typedef typename proto::result_of::child_c<typename Iterator::expr_type &,
Iterator::index>::type type;
static type call(Iterator const &iter) {
return proto::child_c<Iterator::index>(iter.expr);
}
};
template <typename Iterator> struct apply<Iterator, 0> {
typedef
typename proto::result_of::value<typename Iterator::expr_type &>::type
type;
static type call(Iterator const &iter) { return proto::value(iter.expr); }
};
};
template <typename Tag> struct advance_impl;
template <typename Tag, typename Domain>
struct advance_impl<proto::tag::proto_expr_iterator<Tag, Domain>> {
template <typename Iterator, typename N> struct apply {
typedef proto::detail::expr_iterator<typename Iterator::expr_type,
Iterator::index + N::value>
type;
static type call(Iterator const &iter) { return type(iter.expr); }
};
};
template <typename Tag> struct distance_impl;
template <typename Tag, typename Domain>
struct distance_impl<proto::tag::proto_expr_iterator<Tag, Domain>> {
template <typename IteratorFrom, typename IteratorTo>
struct apply : mpl::long_<IteratorTo::index - IteratorFrom::index> {};
};
template <typename Tag> struct next_impl;
template <typename Tag, typename Domain>
struct next_impl<proto::tag::proto_expr_iterator<Tag, Domain>> {
template <typename Iterator>
struct apply : advance_impl<proto::tag::proto_expr_iterator<Tag, Domain>>::
template apply<Iterator, mpl::long_<1>> {};
};
template <typename Tag> struct prior_impl;
template <typename Tag, typename Domain>
struct prior_impl<proto::tag::proto_expr_iterator<Tag, Domain>> {
template <typename Iterator>
struct apply : advance_impl<proto::tag::proto_expr_iterator<Tag, Domain>>::
template apply<Iterator, mpl::long_<-1>> {};
};
template <typename Tag> struct category_of_impl;
template <typename Tag, typename Domain>
struct category_of_impl<proto::tag::proto_expr<Tag, Domain>> {
template <typename Sequence> struct apply {
typedef random_access_traversal_tag type;
};
};
template <typename Tag> struct size_impl;
template <typename Tag, typename Domain>
struct size_impl<proto::tag::proto_expr<Tag, Domain>> {
template <typename Sequence>
struct apply
: mpl::long_<0 == Sequence::proto_arity_c ? 1 : Sequence::proto_arity_c> {
};
};
template <typename Tag> struct begin_impl;
template <typename Tag, typename Domain>
struct begin_impl<proto::tag::proto_expr<Tag, Domain>> {
template <typename Sequence> struct apply {
typedef proto::detail::expr_iterator<Sequence, 0> type;
static type call(Sequence &seq) { return type(seq); }
};
};
template <typename Tag> struct end_impl;
template <typename Tag, typename Domain>
struct end_impl<proto::tag::proto_expr<Tag, Domain>> {
template <typename Sequence> struct apply {
typedef proto::detail::expr_iterator<
Sequence, 0 == Sequence::proto_arity_c ? 1 : Sequence::proto_arity_c>
type;
static type call(Sequence &seq) { return type(seq); }
};
};
template <typename Tag> struct value_at_impl;
template <typename Tag, typename Domain>
struct value_at_impl<proto::tag::proto_expr<Tag, Domain>> {
template <typename Sequence, typename Index,
long Arity = proto::arity_of<Sequence>::value>
struct apply {
typedef
typename proto::result_of::child_c<Sequence, Index::value>::value_type
type;
};
template <typename Sequence, typename Index>
struct apply<Sequence, Index, 0> {
typedef typename proto::result_of::value<Sequence>::value_type type;
};
};
template <typename Tag> struct at_impl;
template <typename Tag, typename Domain>
struct at_impl<proto::tag::proto_expr<Tag, Domain>> {
template <typename Sequence, typename Index,
long Arity = proto::arity_of<Sequence>::value>
struct apply {
typedef
typename proto::result_of::child_c<Sequence &, Index::value>::type type;
static type call(Sequence &seq) {
return proto::child_c<Index::value>(seq);
}
};
template <typename Sequence, typename Index>
struct apply<Sequence, Index, 0> {
typedef typename proto::result_of::value<Sequence &>::type type;
static type call(Sequence &seq) { return proto::value(seq); }
};
};
template <typename Tag> struct convert_impl;
template <typename Tag, typename Domain>
struct convert_impl<proto::tag::proto_expr<Tag, Domain>> {
template <typename Sequence> struct apply {
typedef typename proto::result_of::unpack_expr<Tag, Domain, Sequence>::type
type;
static type call(Sequence &seq) {
return proto::unpack_expr<Tag, Domain>(seq);
}
};
};
template <typename Tag, typename Domain>
struct convert_impl<proto::tag::proto_flat_view<Tag, Domain>> {
template <typename Sequence> struct apply {
typedef typename proto::result_of::unpack_expr<Tag, Domain, Sequence>::type
type;
static type call(Sequence &seq) {
return proto::unpack_expr<Tag, Domain>(seq);
}
};
};
template <typename Tag> struct is_segmented_impl;
template <typename Tag, typename Domain>
struct is_segmented_impl<proto::tag::proto_flat_view<Tag, Domain>> {
template <typename Iterator> struct apply : mpl::true_ {};
};
template <typename Tag> struct segments_impl;
template <typename Tag, typename Domain>
struct segments_impl<proto::tag::proto_flat_view<Tag, Domain>> {
template <typename Sequence> struct apply {
typedef typename Sequence::segments_type const &type;
static type call(Sequence &sequence) { return sequence.segs_; }
};
};
template <typename Tag, typename Domain>
struct category_of_impl<proto::tag::proto_flat_view<Tag, Domain>> {
template <typename Sequence> struct apply {
typedef forward_traversal_tag type;
};
};
} // namespace extension
namespace traits {
template <typename Seq1, typename Seq2>
struct enable_equality<
Seq1, Seq2,
typename enable_if_c<
mpl::or_<proto::is_expr<Seq1>, proto::is_expr<Seq2>>::value>::type>
: mpl::false_ {};
template <typename Seq1, typename Seq2>
struct enable_comparison<
Seq1, Seq2,
typename enable_if_c<
mpl::or_<proto::is_expr<Seq1>, proto::is_expr<Seq2>>::value>::type>
: mpl::false_ {};
} // namespace traits
} // namespace fusion
} // namespace boost
namespace boost {
namespace mpl {
template <typename Tag, typename Args, long Arity>
struct sequence_tag<proto::expr<Tag, Args, Arity>> {
typedef fusion::fusion_sequence_tag type;
};
template <typename Tag, typename Args, long Arity>
struct sequence_tag<proto::basic_expr<Tag, Args, Arity>> {
typedef fusion::fusion_sequence_tag type;
};
} // namespace mpl
} // namespace boost
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#endif
| 31.663223 | 80 | 0.703948 | [
"transform"
] |
cc6d4fc381f023db471a626fafe92ef0fff7e128 | 16,832 | cpp | C++ | source/houaud/test/hou/aud/test_ogg_file_in.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | 2 | 2018-04-12T20:59:20.000Z | 2018-07-26T16:04:07.000Z | source/houaud/test/hou/aud/test_ogg_file_in.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | source/houaud/test/hou/aud/test_ogg_file_in.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#include "hou/test.hpp"
#include "hou/aud/test_data.hpp"
#include "hou/aud/aud_exceptions.hpp"
#include "hou/aud/ogg_file_in.hpp"
#include "hou/sys/file.hpp"
#include "hou/sys/sys_exceptions.hpp"
using namespace hou;
using namespace testing;
namespace
{
class test_ogg_file_in : public Test
{
public:
// Note: OGG files are always read with 16 bits per sample in the Houzi
// library. For this reason there are no tests involving buffers with 8 bits
// per sample.
static const std::string mono16_unicode_filename;
static const std::string mono16_filename;
static const std::string stereo16_filename;
static const std::string low_sample_rate_filename;
static const std::string wav_filename;
};
class TestOggFileInDeathTest : public test_ogg_file_in
{};
const std::string test_ogg_file_in::mono16_unicode_filename
= get_data_dir() + u8"TestOgg\U00004f60\U0000597d.ogg";
const std::string test_ogg_file_in::mono16_filename
= get_data_dir() + u8"TestOgg-mono-16-44100.ogg";
const std::string test_ogg_file_in::stereo16_filename
= get_data_dir() + u8"TestOgg-stereo-16-44100.ogg";
const std::string test_ogg_file_in::low_sample_rate_filename
= get_data_dir() + u8"TestOgg-mono-16-22050.ogg";
const std::string test_ogg_file_in::wav_filename
= get_data_dir() + u8"TestWav-mono-16-44100.wav";
} // namespace
TEST_F(test_ogg_file_in, check_success)
{
EXPECT_TRUE(ogg_file_in::check(mono16_unicode_filename));
}
TEST_F(test_ogg_file_in, check_failure_invalid_format)
{
EXPECT_FALSE(ogg_file_in::check(wav_filename));
}
TEST_F(TestOggFileInDeathTest, check_failure_invalid_file)
{
std::string invalid_filename = u8"Invalidfile";
EXPECT_ERROR_N(
ogg_file_in::check(invalid_filename), file_open_error, invalid_filename);
}
TEST_F(test_ogg_file_in, path_constructor)
{
ogg_file_in fi(mono16_unicode_filename);
EXPECT_FALSE(fi.eof());
EXPECT_FALSE(fi.error());
EXPECT_EQ(42206u, fi.get_byte_count());
EXPECT_EQ(0u, fi.get_read_byte_count());
EXPECT_EQ(0u, fi.get_read_element_count());
EXPECT_EQ(0, fi.get_byte_pos());
EXPECT_EQ(audio_buffer_format::mono16, fi.get_format());
EXPECT_EQ(1u, fi.get_channel_count());
EXPECT_EQ(2u, fi.get_bytes_per_sample());
EXPECT_EQ(44100u, fi.get_sample_rate());
EXPECT_EQ(21103u, fi.get_sample_count());
EXPECT_EQ(0, fi.get_sample_pos());
}
TEST_F(TestOggFileInDeathTest, path_constructor_failure_file_not_existing)
{
std::string invalid_filename = u8"InvalidFileName";
EXPECT_ERROR_N(
ogg_file_in fi(invalid_filename), file_open_error, invalid_filename);
}
TEST_F(TestOggFileInDeathTest, path_constructor_failure_invalid_ogg_file)
{
static constexpr size_t stringSize = 4u;
struct OggMetadata
{
char id[stringSize];
uint32_t chunk_size;
char form[stringSize];
char sc1Id[stringSize];
uint32_t sc1Size;
uint16_t format;
uint16_t channels;
uint32_t sample_rate;
uint32_t byteRate;
uint16_t blockAlign;
uint16_t bitsPerSample;
char sc2Id[stringSize];
uint32_t sc2Size;
};
std::string invalid_filename = get_output_dir() + u8"dummyOggFile.wav";
{
file dummyOggFile(
invalid_filename, file_open_mode::write, file_type::binary);
OggMetadata data;
data.id[0] = 'F';
data.id[1] = 'a';
data.id[2] = 'K';
data.id[3] = 'E';
dummyOggFile.write(&data, 1u);
}
EXPECT_ERROR_0(ogg_file_in fi(invalid_filename), invalid_audio_data);
remove_dir(invalid_filename);
}
TEST_F(TestOggFileInDeathTest, path_constructor_failure_no_ogg_header)
{
std::string invalid_filename = get_output_dir() + u8"dummyOggFile.wav";
{
file dummyOggFile(
invalid_filename, file_open_mode::write, file_type::binary);
}
EXPECT_ERROR_0(ogg_file_in fi(invalid_filename), invalid_audio_data);
remove_dir(invalid_filename);
}
TEST_F(test_ogg_file_in, move_constructor)
{
ogg_file_in fi_dummy(mono16_unicode_filename);
ogg_file_in fi(std::move(fi_dummy));
EXPECT_FALSE(fi.eof());
EXPECT_FALSE(fi.error());
EXPECT_EQ(42206u, fi.get_byte_count());
EXPECT_EQ(0u, fi.get_read_byte_count());
EXPECT_EQ(0u, fi.get_read_element_count());
EXPECT_EQ(0, fi.get_byte_pos());
EXPECT_EQ(audio_buffer_format::mono16, fi.get_format());
EXPECT_EQ(1u, fi.get_channel_count());
EXPECT_EQ(2u, fi.get_bytes_per_sample());
EXPECT_EQ(44100u, fi.get_sample_rate());
EXPECT_EQ(21103u, fi.get_sample_count());
EXPECT_EQ(0, fi.get_sample_pos());
}
TEST_F(test_ogg_file_in, audio_buffer_format_attributes)
{
ogg_file_in fi_mono16(mono16_filename);
ogg_file_in fi_stereo16(stereo16_filename);
EXPECT_EQ(audio_buffer_format::mono16, fi_mono16.get_format());
EXPECT_EQ(1u, fi_mono16.get_channel_count());
EXPECT_EQ(2u, fi_mono16.get_bytes_per_sample());
EXPECT_EQ(audio_buffer_format::stereo16, fi_stereo16.get_format());
EXPECT_EQ(2u, fi_stereo16.get_channel_count());
EXPECT_EQ(2u, fi_stereo16.get_bytes_per_sample());
}
TEST_F(test_ogg_file_in, sample_rate_attributes)
{
ogg_file_in fi_normal_rate(mono16_filename);
ogg_file_in fi_low_rate(low_sample_rate_filename);
EXPECT_EQ(44100u, fi_normal_rate.get_sample_rate());
EXPECT_EQ(22050u, fi_low_rate.get_sample_rate());
}
TEST_F(test_ogg_file_in, get_sample_count)
{
ogg_file_in fi_mono16(mono16_filename);
ogg_file_in fi_stereo16(stereo16_filename);
EXPECT_EQ(21231u, fi_mono16.get_sample_count());
EXPECT_EQ(21231u, fi_stereo16.get_sample_count());
EXPECT_EQ(42462u, fi_mono16.get_byte_count());
EXPECT_EQ(84924u, fi_stereo16.get_byte_count());
}
TEST_F(test_ogg_file_in, set_byte_pos)
{
ogg_file_in fi(mono16_filename);
EXPECT_EQ(0, fi.get_byte_pos());
fi.set_byte_pos(6);
EXPECT_EQ(6, fi.get_byte_pos());
fi.set_byte_pos(0);
EXPECT_EQ(0, fi.get_byte_pos());
fi.set_byte_pos(static_cast<ogg_file_in::byte_position>(fi.get_byte_count()));
EXPECT_EQ(static_cast<ogg_file_in::byte_position>(fi.get_byte_count()),
fi.get_byte_pos());
}
TEST_F(TestOggFileInDeathTest, set_byte_pos_error_position_in_sample)
{
ogg_file_in fi(mono16_filename);
EXPECT_PRECOND_ERROR(fi.set_byte_pos(3));
EXPECT_PRECOND_ERROR(fi.set_byte_pos(
static_cast<ogg_file_in::byte_position>(fi.get_byte_count() + 3)));
}
TEST_F(TestOggFileInDeathTest, set_byte_pos_error_invalid_position)
{
ogg_file_in fi(mono16_filename);
EXPECT_ERROR_0(fi.set_byte_pos(-2), cursor_error);
EXPECT_ERROR_0(fi.set_byte_pos(static_cast<ogg_file_in::byte_position>(
fi.get_byte_count() + 2)),
cursor_error);
}
TEST_F(test_ogg_file_in, move_byte_pos)
{
ogg_file_in fi(mono16_filename);
EXPECT_EQ(0, fi.get_byte_pos());
fi.move_byte_pos(6);
EXPECT_EQ(6, fi.get_byte_pos());
fi.move_byte_pos(-2);
EXPECT_EQ(4, fi.get_byte_pos());
fi.move_byte_pos(-4);
EXPECT_EQ(0, fi.get_byte_pos());
fi.move_byte_pos(
static_cast<ogg_file_in::byte_position>(fi.get_byte_count()));
EXPECT_EQ(static_cast<ogg_file_in::byte_position>(fi.get_byte_count()),
fi.get_byte_pos());
}
TEST_F(TestOggFileInDeathTest, move_byte_pos_error_position_in_sample)
{
ogg_file_in fi(mono16_filename);
fi.move_byte_pos(4);
EXPECT_PRECOND_ERROR(fi.move_byte_pos(3));
EXPECT_PRECOND_ERROR(fi.move_byte_pos(
static_cast<ogg_file_in::byte_position>(fi.get_byte_count() + 3)));
}
TEST_F(TestOggFileInDeathTest, move_byte_pos_error_invalid_position)
{
ogg_file_in fi(mono16_filename);
fi.move_byte_pos(4);
EXPECT_ERROR_0(fi.move_byte_pos(-6), cursor_error);
EXPECT_ERROR_0(fi.move_byte_pos(static_cast<ogg_file_in::byte_position>(
fi.get_byte_count() - 2)),
cursor_error);
}
TEST_F(test_ogg_file_in, set_sample_pos_mono16)
{
ogg_file_in fi(mono16_filename);
EXPECT_EQ(0, fi.get_byte_pos());
EXPECT_EQ(0, fi.get_sample_pos());
fi.set_sample_pos(3);
EXPECT_EQ(6, fi.get_byte_pos());
EXPECT_EQ(3, fi.get_sample_pos());
fi.set_sample_pos(
static_cast<ogg_file_in::byte_position>(fi.get_sample_count()));
EXPECT_EQ(static_cast<ogg_file_in::byte_position>(fi.get_byte_count()),
fi.get_byte_pos());
EXPECT_EQ(static_cast<ogg_file_in::sample_position>(fi.get_sample_count()),
fi.get_sample_pos());
}
TEST_F(test_ogg_file_in, set_sample_pos_stereo16)
{
ogg_file_in fi(stereo16_filename);
EXPECT_EQ(0, fi.get_byte_pos());
EXPECT_EQ(0, fi.get_sample_pos());
fi.set_sample_pos(3);
EXPECT_EQ(12, fi.get_byte_pos());
EXPECT_EQ(3, fi.get_sample_pos());
fi.set_sample_pos(
static_cast<ogg_file_in::byte_position>(fi.get_sample_count()));
EXPECT_EQ(static_cast<ogg_file_in::byte_position>(fi.get_byte_count()),
fi.get_byte_pos());
EXPECT_EQ(static_cast<ogg_file_in::sample_position>(fi.get_sample_count()),
fi.get_sample_pos());
}
TEST_F(TestOggFileInDeathTest, set_sample_pos_error_invalid_position)
{
ogg_file_in fi(mono16_filename);
EXPECT_ERROR_0(fi.set_sample_pos(-1), cursor_error);
EXPECT_ERROR_0(fi.set_sample_pos(static_cast<ogg_file_in::byte_position>(
fi.get_sample_count() + 1)),
cursor_error);
}
TEST_F(test_ogg_file_in, move_sample_pos_mono16)
{
ogg_file_in fi(mono16_filename);
EXPECT_EQ(0, fi.get_byte_pos());
EXPECT_EQ(0, fi.get_sample_pos());
fi.move_sample_pos(3);
EXPECT_EQ(6, fi.get_byte_pos());
EXPECT_EQ(3, fi.get_sample_pos());
fi.move_sample_pos(-1);
EXPECT_EQ(4, fi.get_byte_pos());
EXPECT_EQ(2, fi.get_sample_pos());
fi.move_sample_pos(-2);
EXPECT_EQ(0, fi.get_byte_pos());
EXPECT_EQ(0, fi.get_sample_pos());
fi.move_sample_pos(
static_cast<ogg_file_in::byte_position>(fi.get_sample_count()));
EXPECT_EQ(static_cast<ogg_file_in::byte_position>(fi.get_byte_count()),
fi.get_byte_pos());
EXPECT_EQ(static_cast<ogg_file_in::sample_position>(fi.get_sample_count()),
fi.get_sample_pos());
}
TEST_F(test_ogg_file_in, move_sample_pos_stereo16)
{
ogg_file_in fi(stereo16_filename);
EXPECT_EQ(0, fi.get_byte_pos());
EXPECT_EQ(0, fi.get_sample_pos());
fi.move_sample_pos(3);
EXPECT_EQ(12, fi.get_byte_pos());
EXPECT_EQ(3, fi.get_sample_pos());
fi.move_sample_pos(-1);
EXPECT_EQ(8, fi.get_byte_pos());
EXPECT_EQ(2, fi.get_sample_pos());
fi.move_sample_pos(-2);
EXPECT_EQ(0, fi.get_byte_pos());
EXPECT_EQ(0, fi.get_sample_pos());
fi.move_sample_pos(
static_cast<ogg_file_in::byte_position>(fi.get_sample_count()));
EXPECT_EQ(static_cast<ogg_file_in::byte_position>(fi.get_byte_count()),
fi.get_byte_pos());
EXPECT_EQ(static_cast<ogg_file_in::sample_position>(fi.get_sample_count()),
fi.get_sample_pos());
}
TEST_F(TestOggFileInDeathTest, move_sample_pos_error_invalid_position)
{
ogg_file_in fi(mono16_filename);
fi.move_sample_pos(2);
EXPECT_ERROR_0(fi.move_sample_pos(-3), cursor_error);
EXPECT_ERROR_0(fi.move_sample_pos(static_cast<ogg_file_in::byte_position>(
fi.get_sample_count() + 1)),
cursor_error);
}
TEST_F(test_ogg_file_in, read_to_variable)
{
using buffer_type = uint16_t;
static constexpr size_t buffer_size = 1u;
static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size;
ogg_file_in fi(mono16_unicode_filename);
buffer_type buffer;
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_EQ(buffer_size, fi.get_read_sample_count());
EXPECT_EQ(10124u, buffer);
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_EQ(buffer_size, fi.get_read_sample_count());
EXPECT_EQ(11584u, buffer);
}
TEST_F(test_ogg_file_in, read_to_basic_array)
{
using buffer_type = uint16_t;
static constexpr size_t buffer_size = 3u;
static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size;
ogg_file_in fi(mono16_unicode_filename);
buffer_type buffer[buffer_size];
fi.read(buffer, buffer_size);
buffer_type buffer_ref1[buffer_size] = {10124u, 11584u, 9754u};
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_EQ(buffer_size, fi.get_read_sample_count());
EXPECT_ARRAY_EQ(buffer_ref1, buffer, buffer_size);
fi.read(buffer, buffer_size);
buffer_type buffer_ref2[buffer_size] = {11404u, 10203u, 11732u};
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_EQ(buffer_size, fi.get_read_sample_count());
EXPECT_ARRAY_EQ(buffer_ref2, buffer, buffer_size);
}
TEST_F(test_ogg_file_in, read_to_array)
{
using buffer_type = uint16_t;
static constexpr size_t buffer_size = 3u;
static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size;
ogg_file_in fi(mono16_unicode_filename);
std::array<buffer_type, buffer_size> buffer = {0, 0, 0};
fi.read(buffer);
std::array<buffer_type, buffer_size> buffer_ref1 = {10124u, 11584u, 9754u};
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_EQ(buffer_size, fi.get_read_sample_count());
EXPECT_EQ(buffer_ref1, buffer);
fi.read(buffer);
std::array<buffer_type, buffer_size> buffer_ref2 = {11404u, 10203u, 11732u};
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_EQ(buffer_size, fi.get_read_sample_count());
EXPECT_EQ(buffer_ref2, buffer);
}
TEST_F(test_ogg_file_in, read_to_vector)
{
using buffer_type = uint16_t;
static constexpr size_t buffer_size = 3u;
static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size;
ogg_file_in fi(mono16_unicode_filename);
std::vector<buffer_type> buffer(buffer_size, 0u);
fi.read(buffer);
std::vector<buffer_type> buffer_ref1 = {10124u, 11584u, 9754u};
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_EQ(buffer_size, fi.get_read_sample_count());
EXPECT_EQ(buffer_ref1, buffer);
fi.read(buffer);
std::vector<buffer_type> buffer_ref2 = {11404u, 10203u, 11732u};
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_EQ(buffer_size, fi.get_read_sample_count());
EXPECT_EQ(buffer_ref2, buffer);
}
TEST_F(test_ogg_file_in, read_to_string)
{
using buffer_type = std::string::value_type;
static constexpr size_t buffer_size = 4u;
static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size;
ogg_file_in fi(mono16_unicode_filename);
std::string buffer(buffer_size, 0);
fi.read(buffer);
std::string buffer_ref1 = {-116, 39, 64, 45};
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_EQ(buffer_size / 2, fi.get_read_sample_count());
EXPECT_EQ(buffer_ref1, buffer);
fi.read(buffer);
std::string buffer_ref2 = {26, 38, -116, 44};
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_EQ(buffer_size / 2, fi.get_read_sample_count());
EXPECT_EQ(buffer_ref2, buffer);
}
TEST_F(TestOggFileInDeathTest, read_to_invalid_size_buffer)
{
using buffer_type = uint8_t;
static constexpr size_t buffer_size = 3u;
std::vector<buffer_type> buffer(buffer_size, 0u);
ogg_file_in fi(mono16_filename);
EXPECT_EQ(audio_buffer_format::mono16, fi.get_format());
EXPECT_PRECOND_ERROR(fi.read(buffer));
}
TEST_F(test_ogg_file_in, read_all_to_vector)
{
ogg_file_in fi(mono16_filename);
std::vector<uint8_t> file_content(fi.get_byte_count());
fi.read(file_content);
fi.set_byte_pos(0u);
auto fi_content = fi.read_all<std::vector<uint8_t>>();
EXPECT_EQ(file_content, fi_content);
EXPECT_EQ(file_content.size(), fi.get_read_byte_count());
EXPECT_EQ(file_content.size(), static_cast<size_t>(fi.get_byte_pos()));
}
TEST_F(test_ogg_file_in, read_all_to_vector_not_from_start)
{
ogg_file_in fi(mono16_filename);
std::vector<uint8_t> file_content(fi.get_byte_count());
fi.read(file_content);
fi.set_byte_pos(2u);
auto fi_content = fi.read_all<std::vector<uint8_t>>();
EXPECT_EQ(file_content, fi_content);
EXPECT_EQ(file_content.size(), fi.get_read_byte_count());
EXPECT_EQ(file_content.size(), static_cast<size_t>(fi.get_byte_pos()));
}
TEST_F(test_ogg_file_in, eof)
{
ogg_file_in fi(mono16_filename);
std::vector<uint8_t> buffer(fi.get_byte_count() + 2u, 0u);
fi.read(buffer);
EXPECT_TRUE(fi.eof());
EXPECT_EQ(fi.get_byte_count(), fi.get_read_byte_count());
EXPECT_TRUE(fi.eof());
fi.get_byte_pos();
EXPECT_TRUE(fi.eof());
fi.set_byte_pos(0u);
EXPECT_FALSE(fi.eof());
EXPECT_FALSE(fi.error());
}
| 27.913765 | 80 | 0.756595 | [
"vector"
] |
cc6f466329d7283c6d4f2decd617df6dfdbb5e98 | 1,314 | cpp | C++ | DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/07_DPCPP_Library/src/zip_iterator.cpp | tiwaria1/oneAPI-samples | 18310adf63c7780715f24034acfb0bf01d15521f | [
"MIT"
] | 310 | 2020-07-09T01:00:11.000Z | 2022-03-31T17:52:14.000Z | DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/07_DPCPP_Library/src/zip_iterator.cpp | tiwaria1/oneAPI-samples | 18310adf63c7780715f24034acfb0bf01d15521f | [
"MIT"
] | 438 | 2020-06-30T23:25:19.000Z | 2022-03-31T00:37:13.000Z | DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/07_DPCPP_Library/src/zip_iterator.cpp | tiwaria1/oneAPI-samples | 18310adf63c7780715f24034acfb0bf01d15521f | [
"MIT"
] | 375 | 2020-06-04T22:58:24.000Z | 2022-03-30T11:04:18.000Z | //==============================================================
// Copyright © 2020 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <oneapi/dpl/algorithm>
#include <oneapi/dpl/execution>
#include <oneapi/dpl/iterator>
using namespace sycl;
using namespace oneapi::dpl::execution;
int main() {
queue q;
std::cout << "Device : " << q.get_device().get_info<info::device::name>() << std::endl;
constexpr int num_elements = 16;
std::vector<int> input_v1(num_elements, 2), input_v2(num_elements, 5), input_v3(num_elements, 0);
//Zip Iterator zips up the iterators of individual containers of interest.
auto start = oneapi::dpl::make_zip_iterator(input_v1.begin(), input_v2.begin(), input_v3.begin());
auto end = oneapi::dpl::make_zip_iterator(input_v1.end(), input_v2.end(), input_v3.end());
//create device policy
auto exec_policy = make_device_policy(q);
std::for_each(exec_policy, start, end, [](auto t) {
//The zip iterator is used for expressing bounds in PSTL algorithms.
using std::get;
get<2>(t) = get<1>(t) * get<0>(t);
});
for (auto it = input_v3.begin(); it < input_v3.end(); it++)
std::cout << (*it) <<" ";
std::cout << "\n";
return 0;
}
| 39.818182 | 102 | 0.589041 | [
"vector"
] |
cc6f652502fd8ebf12a75a73fc594dce39ca196a | 1,375 | cpp | C++ | examples/data_distribution/binscatter/binscatter_4.cpp | lpea/matplotplusplus | 642f04b5bc2f7c7ec0f4b81c683bbd30bcbc4ed8 | [
"MIT"
] | 1 | 2022-03-22T11:09:19.000Z | 2022-03-22T11:09:19.000Z | examples/data_distribution/binscatter/binscatter_4.cpp | lpea/matplotplusplus | 642f04b5bc2f7c7ec0f4b81c683bbd30bcbc4ed8 | [
"MIT"
] | null | null | null | examples/data_distribution/binscatter/binscatter_4.cpp | lpea/matplotplusplus | 642f04b5bc2f7c7ec0f4b81c683bbd30bcbc4ed8 | [
"MIT"
] | 1 | 2022-03-22T11:46:39.000Z | 2022-03-22T11:46:39.000Z | #include <matplot/matplot.h>
#include <random>
#include <tuple>
int main() {
using namespace matplot;
auto f = figure(true);
f->width(f->width() * 2);
f->height(f->height() * 2);
f->x_position(200);
f->y_position(100);
auto x = randn(1e6, 0, 1);
auto y = transform(x, [](double x) { return 2 * x + randn(0, 1); });
bin_scatter_style b = bin_scatter_style::heatmap;
histogram::binning_algorithm a = histogram::binning_algorithm::automatic;
subplot(2, 3, 0);
binscatter(x, y, a, b, histogram::normalization::count);
axis(tight);
title("Normalization: Count");
subplot(2, 3, 1);
binscatter(x, y, a, b, histogram::normalization::probability);
axis(tight);
title("Normalization: Probability");
subplot(2, 3, 2);
binscatter(x, y, a, b, histogram::normalization::cummulative_count);
axis(tight);
title("Normalization: Cummulative count");
subplot(2, 3, 3);
binscatter(x, y, a, b, histogram::normalization::count_density);
axis(tight);
title("Normalization: Count density");
subplot(2, 3, 4);
binscatter(x, y, a, b, histogram::normalization::pdf);
axis(tight);
title("Normalization: PDF");
subplot(2, 3, 5);
binscatter(x, y, a, b, histogram::normalization::cdf);
axis(tight);
title("Normalization: CDF");
f->show();
return 0;
} | 25.943396 | 77 | 0.621091 | [
"transform"
] |
cc85b137ecb3d5a67a8acee0caf77d9af9b8efef | 382 | cpp | C++ | C++/count-ways-to-distribute-candies.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/count-ways-to-distribute-candies.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/count-ways-to-distribute-candies.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n * k)
// Space: O(k)
class Solution {
public:
int waysToDistribute(int n, int k) {
static int MOD = 1e9 + 7;
vector<int64_t> dp(k, 1);
for (int i = 1; i < n; ++i) {
for (int j = min(i, k) - 1; j >= 1; --j) {
dp[j] = ((j + 1) * dp[j] + dp[j - 1]) % MOD;
}
}
return dp[k - 1];
}
};
| 22.470588 | 60 | 0.379581 | [
"vector"
] |
cc89571b1d8fad78a26dd16f8c09f90a99500787 | 587 | cpp | C++ | frifun.cpp | biswajitcsecu/C-practice | bdd3eaf2e8fdbbf36a3b3ed9ed5757964ffc5e22 | [
"Apache-2.0"
] | 1 | 2020-11-25T16:14:34.000Z | 2020-11-25T16:14:34.000Z | frifun.cpp | biswajitcsecu/C-practice | bdd3eaf2e8fdbbf36a3b3ed9ed5757964ffc5e22 | [
"Apache-2.0"
] | null | null | null | frifun.cpp | biswajitcsecu/C-practice | bdd3eaf2e8fdbbf36a3b3ed9ed5757964ffc5e22 | [
"Apache-2.0"
] | null | null | null |
// Demonstrate object assignment.
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
void setab(int i, int j) { a = i, b = j; }
void showab();
};
void myclass::showab()
{
cout << "a is " << a << '\n';
cout << "b is " << b << '\n';
}
int main()
{
myclass ob1, ob2;
ob1.setab(10, 20);
ob2.setab(0, 0);
cout << "ob1 before assignment: \n";
ob1.showab();
cout << "ob2 before assignment: \n";
ob2.showab();
cout << '\n';
ob2 = ob1; // assign ob1 to ob2
cout << "ob1 after assignment: \n";
ob1.showab();
cout << "ob2 after assignment: \n";
ob2.showab();
return 0;
} | 16.771429 | 42 | 0.599659 | [
"object"
] |
cc8ba5f8fffd864153d2b8e9696863734b48cc08 | 2,040 | cpp | C++ | examples/1-1-2-segments_intersection/main.cpp | hyperpower/CarpioPlus | 68cc6c976d6c3ba6adec847a94c344be3f4690aa | [
"MIT"
] | null | null | null | examples/1-1-2-segments_intersection/main.cpp | hyperpower/CarpioPlus | 68cc6c976d6c3ba6adec847a94c344be3f4690aa | [
"MIT"
] | 1 | 2018-06-18T03:52:56.000Z | 2018-06-18T03:52:56.000Z | examples/1-1-2-segments_intersection/main.cpp | hyperpower/CarpioPlus | 68cc6c976d6c3ba6adec847a94c344be3f4690aa | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
#include <string>
#include "geometry/geometry.hpp"
using namespace carpio;
typedef IntersectionPairSS_<double, 2> Inter;
typedef Point_<double, 2> Point2;
typedef Segment_<double, 2> Seg2;
typedef GGnuplotActor_<double, 2> GA;
int a_case(const Point2& p1,
const Point2& p2,
const Point2& p3,
const Point2& p4){
Seg2 seg1(p1, p2);
Seg2 seg2(p3, p4);
Inter inter(seg1, seg2);
auto strtype = ToString(inter.cal_intersection_type());
std::cout << "Intersection Type : "<< strtype << std::endl;
Point2 np = inter.cal_intersection_point();
std::cout << "new point : "<< np << std::endl;
Gnuplot gnu;
gnu.set_terminal_png("./fig/" + strtype +".png");
gnu.set_xrange(-5, 5);
gnu.set_yrange(-5, 5);
gnu.set_label(1, strtype, -4.5, 4);
auto a1 = GA::LinesPoints(seg1, 3);
a1->style() = "with linespoints pointtype 7 pointsize 3 lw 3 lc variable";
auto a2 = GA::LinesPoints(seg2, 2);
a2->style() = "with linespoints pointtype 7 pointsize 3 lw 3 lc variable";
auto a3 = GA::Points(np, 1);
a3->style() = "with linespoints pointtype 1 pointsize 3 lw 3 lc variable";
gnu.add(a1);
gnu.add(a2);
gnu.add(a3);
gnu.plot();
}
int main(int argc, char** argv) {
Point2 p1( -1, 0);
Point2 p2( 3, 0.5);
Point2 p3( 0.8, 2.0);
Point2 p4(-0.3, -1.0);
// intersect
a_case(p1, p2, p3, p4);
// NO
a_case(Point2( -1, 0), Point2(3, 0.5),
Point2(0.8, 2.0), Point2(-0.3, 1.0));
// CONNECT
a_case(Point2( -1, 0), Point2(3, 0.5),
Point2( -1, 0), Point2(-0.3, 1.0));
// TOUCH
a_case(Point2( -1, 0), Point2(3, 0.0),
Point2( 0, 0), Point2(-0.5, 1.0));
// OVERLAP
a_case(Point2( 0, -1), Point2( 4, 3),
Point2( -1, -2), Point2( 2, 1));
// SAME
a_case(Point2( -1, -1), Point2( 2, 2),
Point2( -1, -1), Point2( 2, 2));
} | 28.732394 | 78 | 0.55049 | [
"geometry"
] |
cc905978a34cc27cd4da912dd7292e69f7aabf6b | 2,377 | hpp | C++ | src/InternalNode.hpp | romz-pl/amittai-btree | ccfb9a36068d641be57bcbfe4ca53bea19685f8e | [
"Apache-2.0"
] | null | null | null | src/InternalNode.hpp | romz-pl/amittai-btree | ccfb9a36068d641be57bcbfe4ca53bea19685f8e | [
"Apache-2.0"
] | 13 | 2018-04-22T14:54:10.000Z | 2018-05-04T05:14:13.000Z | src/InternalNode.hpp | romz-pl/amittai-btree | ccfb9a36068d641be57bcbfe4ca53bea19685f8e | [
"Apache-2.0"
] | null | null | null | #ifndef ROMZ_AMITTAI_BTREE_INTERNALNODE_H
#define ROMZ_AMITTAI_BTREE_INTERNALNODE_H
//
// 1. Let us consider a node containing m pointers (m <= n).
// Available indexes: i = 1, 2, ..., m.
//
// 2. Valid pointers: P_1, P_2, ..., P_m
//
// 3. Valid keys: K_1, K_2, ..., K_{m-1}
//
// 4. For i = 2, 3, ..., (m − 1) pointer P_i points to the subtree that contains
// search-key values:
// a) greater than or equal to K_{i−1} and
// b) less than K_i and.
//
// 5. Pointer P_m points to the part of the subtree that contains those key values
// greater than or equal to K_{m−1}.
//
// 6. Pointer P_1 points to the part of the subtree that contains those
// search-key values less than K_1.
//
#include <vector>
#include "Definitions.hpp"
#include "Node.hpp"
#include "KeyType.h"
#include "InternalElt.h"
class InternalNode : public Node
{
friend class Io;
friend class Printer;
public:
InternalNode( BPlusTree *tree, InternalNode* parent );
~InternalNode();
bool is_leaf() const override;
std::size_t size() const override;
KeyType key_at( std::size_t index ) const;
void set_key_at( std::size_t index, const KeyType& key );
Node* first_child() const;
void populate_new_root( Node* old_node, const KeyType& new_key, Node* new_node );
void insert_after( Node* old_node, const KeyType& new_key, Node* new_node );
void remove( std::size_t index );
Node* remove_and_return_only_child();
KeyType replace_and_return_first_key();
void move_first_to_end_of( InternalNode* recipient );
void move_last_to_front_of( InternalNode* recipient, std::size_t parent_index );
Node* lookup( const KeyType& key ) const;
std::size_t node_index( Node* node ) const;
Node* neighbor( std::size_t index ) const;
InternalNode* internal() override;
const InternalNode* internal() const override;
static void move_half( InternalNode *from, InternalNode *to );
static void move_all ( InternalNode *from, InternalNode *to, std::size_t index_in_parent );
private:
void copy_last_from( const InternalElt& pair );
void copy_first_from( const InternalElt& pair, std::size_t parent_index );
bool is_sorted() const;
private:
std::vector< InternalElt > m_elt;
// Key used where only the entry's pointer has meaning.
const KeyType DUMMY_KEY{-1};
};
#endif
| 27.011364 | 95 | 0.687 | [
"vector"
] |
cc911069db0fb80c6d1668caec69dcb9b8f7835e | 27,344 | cpp | C++ | Source/main.cpp | kwoolytech/AmazonKinesisProducerCpp | a3ae85be069ccc5f4169928b9c9766cab9544719 | [
"MIT"
] | null | null | null | Source/main.cpp | kwoolytech/AmazonKinesisProducerCpp | a3ae85be069ccc5f4169928b9c9766cab9544719 | [
"MIT"
] | null | null | null | Source/main.cpp | kwoolytech/AmazonKinesisProducerCpp | a3ae85be069ccc5f4169928b9c9766cab9544719 | [
"MIT"
] | null | null | null | #include <gst/gst.h>
#include <gst/app/gstappsink.h>
#include <string.h>
#include <chrono>
#include <Logger.h>
#include "KinesisVideoProducer.h"
#include <vector>
#include <stdlib.h>
#include <mutex>
#include <IotCertCredentialProvider.h>
using namespace std;
using namespace com::amazonaws::kinesis::video;
using namespace log4cplus;
#ifdef __cplusplus
extern "C" {
#endif
int gstreamer_init(int, char **);
#ifdef __cplusplus
}
#endif
LOGGER_TAG("com.amazonaws.kinesis.video.gstreamer");
#define DEFAULT_RETENTION_PERIOD_HOURS 2
#define DEFAULT_KMS_KEY_ID ""
#define DEFAULT_STREAMING_TYPE STREAMING_TYPE_REALTIME
#define DEFAULT_CONTENT_TYPE "video/h264"
#define DEFAULT_MAX_LATENCY_SECONDS 60
#define DEFAULT_FRAGMENT_DURATION_MILLISECONDS 2000
#define DEFAULT_TIMECODE_SCALE_MILLISECONDS 1
#define DEFAULT_KEY_FRAME_FRAGMENTATION TRUE
#define DEFAULT_FRAME_TIMECODES TRUE
#define DEFAULT_ABSOLUTE_FRAGMENT_TIMES TRUE
#define DEFAULT_FRAGMENT_ACKS TRUE
#define DEFAULT_RESTART_ON_ERROR TRUE
#define DEFAULT_RECALCULATE_METRICS TRUE
#define DEFAULT_STREAM_FRAMERATE 25
#define DEFAULT_AVG_BANDWIDTH_BPS (4 * 1024 * 1024)
#define DEFAULT_BUFFER_DURATION_SECONDS 120
#define DEFAULT_REPLAY_DURATION_SECONDS 40
#define DEFAULT_CONNECTION_STALENESS_SECONDS 60
#define DEFAULT_CODEC_ID "V_MPEG4/ISO/AVC"
#define DEFAULT_TRACKNAME "kinesis_video"
#define DEFAULT_FRAME_DURATION_MS 1
#define DEFAULT_CREDENTIAL_ROTATION_SECONDS 3600
#define DEFAULT_CREDENTIAL_EXPIRATION_SECONDS 180
typedef struct _CustomData {
_CustomData():
synthetic_dts(0),
stream_status(STATUS_SUCCESS),
main_loop(NULL),
first_pts(GST_CLOCK_TIME_NONE),
use_absolute_fragment_times(true) {
producer_start_time = chrono::duration_cast<nanoseconds>(systemCurrentTime().time_since_epoch()).count();
}
GMainLoop *main_loop;
unique_ptr<KinesisVideoProducer> kinesis_video_producer;
shared_ptr<KinesisVideoStream> kinesis_video_stream;
bool stream_started;
char *stream_name;
// stores any error status code reported by StreamErrorCallback.
atomic_uint stream_status;
// Used in file uploading only. Assuming frame timestamp are relative. Add producer_start_time to each frame's
// timestamp to convert them to absolute timestamp. This way fragments dont overlap after token rotation when doing
// file uploading.
uint64_t producer_start_time;
unique_ptr<Credentials> credential;
uint64_t synthetic_dts;
bool use_absolute_fragment_times;
// Pts of first video frame
uint64_t first_pts;
} CustomData;
namespace com { namespace amazonaws { namespace kinesis { namespace video {
class SampleClientCallbackProvider : public ClientCallbackProvider {
public:
UINT64 getCallbackCustomData() override {
return reinterpret_cast<UINT64> (this);
}
StorageOverflowPressureFunc getStorageOverflowPressureCallback() override {
return storageOverflowPressure;
}
static STATUS storageOverflowPressure(UINT64 custom_handle, UINT64 remaining_bytes);
};
class SampleStreamCallbackProvider : public StreamCallbackProvider {
UINT64 custom_data_;
public:
SampleStreamCallbackProvider(UINT64 custom_data) : custom_data_(custom_data) {}
UINT64 getCallbackCustomData() override {
return custom_data_;
}
StreamConnectionStaleFunc getStreamConnectionStaleCallback() override {
return streamConnectionStaleHandler;
};
StreamErrorReportFunc getStreamErrorReportCallback() override {
return streamErrorReportHandler;
};
DroppedFrameReportFunc getDroppedFrameReportCallback() override {
return droppedFrameReportHandler;
};
FragmentAckReceivedFunc getFragmentAckReceivedCallback() override {
return fragmentAckReceivedHandler;
};
private:
static STATUS
streamConnectionStaleHandler(UINT64 custom_data, STREAM_HANDLE stream_handle,
UINT64 last_buffering_ack);
static STATUS
streamErrorReportHandler(UINT64 custom_data, STREAM_HANDLE stream_handle, UPLOAD_HANDLE upload_handle, UINT64 errored_timecode,
STATUS status_code);
static STATUS
droppedFrameReportHandler(UINT64 custom_data, STREAM_HANDLE stream_handle,
UINT64 dropped_frame_timecode);
static STATUS
fragmentAckReceivedHandler( UINT64 custom_data, STREAM_HANDLE stream_handle,
UPLOAD_HANDLE upload_handle, PFragmentAck pFragmentAck);
};
class SampleCredentialProvider : public StaticCredentialProvider {
// Test rotation period is 40 second for the grace period.
const std::chrono::duration<uint64_t> ROTATION_PERIOD = std::chrono::seconds(DEFAULT_CREDENTIAL_ROTATION_SECONDS);
public:
SampleCredentialProvider(const Credentials &credentials) :
StaticCredentialProvider(credentials) {}
void updateCredentials(Credentials &credentials) override {
// Copy the stored creds forward
credentials = credentials_;
// Update only the expiration
auto now_time = std::chrono::duration_cast<std::chrono::seconds>(
systemCurrentTime().time_since_epoch());
auto expiration_seconds = now_time + ROTATION_PERIOD;
credentials.setExpiration(std::chrono::seconds(expiration_seconds.count()));
LOG_INFO("New credentials expiration is " << credentials.getExpiration().count());
}
};
class SampleDeviceInfoProvider : public DefaultDeviceInfoProvider {
public:
device_info_t getDeviceInfo() override {
auto device_info = DefaultDeviceInfoProvider::getDeviceInfo();
// Set the storage size to 128mb
device_info.storageInfo.storageSize = 128 * 1024 * 1024;
return device_info;
}
};
STATUS
SampleClientCallbackProvider::storageOverflowPressure(UINT64 custom_handle, UINT64 remaining_bytes) {
UNUSED_PARAM(custom_handle);
LOG_WARN("Reporting storage overflow. Bytes remaining " << remaining_bytes);
return STATUS_SUCCESS;
}
STATUS SampleStreamCallbackProvider::streamConnectionStaleHandler(UINT64 custom_data,
STREAM_HANDLE stream_handle,
UINT64 last_buffering_ack) {
LOG_WARN("Reporting stream stale. Last ACK received " << last_buffering_ack);
return STATUS_SUCCESS;
}
STATUS
SampleStreamCallbackProvider::streamErrorReportHandler(UINT64 custom_data, STREAM_HANDLE stream_handle,
UPLOAD_HANDLE upload_handle, UINT64 errored_timecode, STATUS status_code) {
LOG_ERROR("Reporting stream error. Errored timecode: " << errored_timecode << " Status: "
<< status_code);
CustomData *data = reinterpret_cast<CustomData *>(custom_data);
bool terminate_pipeline = false;
// In realtime streaming, retriable error can be handled underneath. Otherwise terminate pipeline
// and store error status if error is fatal.
if (!IS_RETRIABLE_ERROR(status_code) && !IS_RECOVERABLE_ERROR(status_code)) {
data->stream_status = status_code;
terminate_pipeline = true;
}
if (terminate_pipeline && data->main_loop != NULL) {
LOG_WARN("Terminating pipeline due to unrecoverable stream error: " << status_code);
g_main_loop_quit(data->main_loop);
}
return STATUS_SUCCESS;
}
STATUS
SampleStreamCallbackProvider::droppedFrameReportHandler(UINT64 custom_data, STREAM_HANDLE stream_handle,
UINT64 dropped_frame_timecode) {
LOG_WARN("Reporting dropped frame. Frame timecode " << dropped_frame_timecode);
return STATUS_SUCCESS;
}
STATUS
SampleStreamCallbackProvider::fragmentAckReceivedHandler(UINT64 custom_data, STREAM_HANDLE stream_handle,
UPLOAD_HANDLE upload_handle, PFragmentAck pFragmentAck) {
CustomData *data = reinterpret_cast<CustomData *>(custom_data);
LOG_DEBUG("Reporting fragment ack received. Ack timecode " << pFragmentAck->timestamp);
return STATUS_SUCCESS;
}
} // namespace video
} // namespace kinesis
} // namespace amazonaws
} // namespace com;
void create_kinesis_video_frame(Frame *frame, const nanoseconds &pts, const nanoseconds &dts, FRAME_FLAGS flags,
void *data, size_t len) {
frame->flags = flags;
frame->decodingTs = static_cast<UINT64>(dts.count()) / DEFAULT_TIME_UNIT_IN_NANOS;
frame->presentationTs = static_cast<UINT64>(pts.count()) / DEFAULT_TIME_UNIT_IN_NANOS;
// set duration to 0 due to potential high spew from rtsp streams
frame->duration = 0;
frame->size = static_cast<UINT32>(len);
frame->frameData = reinterpret_cast<PBYTE>(data);
frame->trackId = DEFAULT_TRACK_ID;
}
bool put_frame(shared_ptr<KinesisVideoStream> kinesis_video_stream, void *data, size_t len, const nanoseconds &pts, const nanoseconds &dts, FRAME_FLAGS flags) {
Frame frame;
create_kinesis_video_frame(&frame, pts, dts, flags, data, len);
return kinesis_video_stream->putFrame(frame);
}
static GstFlowReturn on_new_sample(GstElement *sink, CustomData *data) {
GstBuffer *buffer;
bool isDroppable, isHeader, delta;
size_t buffer_size;
GstFlowReturn ret = GST_FLOW_OK;
STATUS curr_stream_status = data->stream_status.load();
GstSample *sample = nullptr;
GstMapInfo info;
if (STATUS_FAILED(curr_stream_status)) {
LOG_ERROR("Received stream error: " << curr_stream_status);
ret = GST_FLOW_ERROR;
goto CleanUp;
}
info.data = nullptr;
sample = gst_app_sink_pull_sample(GST_APP_SINK (sink));
// capture cpd at the first frame
if (!data->stream_started) {
data->stream_started = true;
GstCaps* gstcaps = (GstCaps*) gst_sample_get_caps(sample);
GstStructure * gststructforcaps = gst_caps_get_structure(gstcaps, 0);
const GValue *gstStreamFormat = gst_structure_get_value(gststructforcaps, "codec_data");
gchar *cpd = gst_value_serialize(gstStreamFormat);
data->kinesis_video_stream->start(std::string(cpd));
g_free(cpd);
}
buffer = gst_sample_get_buffer(sample);
isHeader = GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_HEADER);
isDroppable = GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_CORRUPTED) ||
GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DECODE_ONLY) ||
(GST_BUFFER_FLAGS(buffer) == GST_BUFFER_FLAG_DISCONT) ||
(GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DISCONT) && GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT)) ||
// drop if buffer contains header only and has invalid timestamp
(isHeader && (!GST_BUFFER_PTS_IS_VALID(buffer) || !GST_BUFFER_DTS_IS_VALID(buffer)));
if (!isDroppable) {
delta = GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT);
FRAME_FLAGS kinesis_video_flags = delta ? FRAME_FLAG_NONE : FRAME_FLAG_KEY_FRAME;
// For some rtsp sources the dts is invalid, therefore synthesize.
if (!GST_BUFFER_DTS_IS_VALID(buffer)) {
data->synthetic_dts += DEFAULT_FRAME_DURATION_MS * HUNDREDS_OF_NANOS_IN_A_MILLISECOND * DEFAULT_TIME_UNIT_IN_NANOS;
buffer->dts = data->synthetic_dts;
} else if (GST_BUFFER_DTS_IS_VALID(buffer)) {
data->synthetic_dts = buffer->dts;
}
if (data->use_absolute_fragment_times) {
if (data->first_pts == GST_CLOCK_TIME_NONE) {
data->first_pts = buffer->pts;
}
buffer->pts += data->producer_start_time - data->first_pts;
}
if (!gst_buffer_map(buffer, &info, GST_MAP_READ)){
goto CleanUp;
}
put_frame(data->kinesis_video_stream, info.data, info.size, std::chrono::nanoseconds(buffer->pts),
std::chrono::nanoseconds(buffer->dts), kinesis_video_flags);
}
CleanUp:
if (info.data != nullptr) {
gst_buffer_unmap(buffer, &info);
}
if (sample != nullptr) {
gst_sample_unref(sample);
}
return ret;
}
static bool format_supported_by_source(GstCaps *src_caps, GstCaps *query_caps, int width, int height, int framerate) {
gst_caps_set_simple(query_caps,
"width", G_TYPE_INT, width,
"height", G_TYPE_INT, height,
"framerate", GST_TYPE_FRACTION, framerate, 1,
NULL);
bool is_match = gst_caps_can_intersect(query_caps, src_caps);
// in case the camera has fps as 10000000/333333
if(!is_match) {
gst_caps_set_simple(query_caps,
"framerate", GST_TYPE_FRACTION_RANGE, framerate, 1, framerate+1, 1,
NULL);
is_match = gst_caps_can_intersect(query_caps, src_caps);
}
return is_match;
}
static bool resolution_supported(GstCaps *src_caps, GstCaps *query_caps_h264,
CustomData &data, int width, int height, int framerate) {
if (query_caps_h264 &&
format_supported_by_source(src_caps, query_caps_h264, width, height, framerate)) {
return true;
}
return false;
}
/* This function is called when an error message is posted on the bus */
static void error_cb(GstBus *bus, GstMessage *msg, CustomData *data) {
GError *err;
gchar *debug_info;
/* Print error details on the screen */
gst_message_parse_error(msg, &err, &debug_info);
g_printerr("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message);
g_printerr("Debugging information: %s\n", debug_info ? debug_info : "none");
g_clear_error(&err);
g_free(debug_info);
g_main_loop_quit(data->main_loop);
}
void kinesis_video_init(CustomData *data) {
unique_ptr<DeviceInfoProvider> device_info_provider(new SampleDeviceInfoProvider());
unique_ptr<ClientCallbackProvider> client_callback_provider(new SampleClientCallbackProvider());
unique_ptr<StreamCallbackProvider> stream_callback_provider(new SampleStreamCallbackProvider(
reinterpret_cast<UINT64>(data)));
char const *accessKey;
char const *secretKey;
char const *sessionToken;
char const *defaultRegion;
string defaultRegionStr;
string sessionTokenStr;
char const *iot_get_credential_endpoint;
char const *cert_path;
char const *private_key_path;
char const *role_alias;
char const *ca_cert_path;
unique_ptr<CredentialProvider> credential_provider;
if (nullptr == (defaultRegion = getenv(DEFAULT_REGION_ENV_VAR))) {
defaultRegionStr = DEFAULT_AWS_REGION;
} else {
defaultRegionStr = string(defaultRegion);
}
LOG_INFO("Using region: " << defaultRegionStr);
if (nullptr != (accessKey = getenv(ACCESS_KEY_ENV_VAR)) &&
nullptr != (secretKey = getenv(SECRET_KEY_ENV_VAR))) {
LOG_INFO("Using aws credentials for Kinesis Video Streams");
if (nullptr != (sessionToken = getenv(SESSION_TOKEN_ENV_VAR))) {
LOG_INFO("Session token detected.");
sessionTokenStr = string(sessionToken);
} else {
LOG_INFO("No session token was detected.");
sessionTokenStr = "";
}
data->credential.reset(new Credentials(string(accessKey),
string(secretKey),
sessionTokenStr,
std::chrono::seconds(DEFAULT_CREDENTIAL_EXPIRATION_SECONDS)));
credential_provider.reset(new SampleCredentialProvider(*data->credential.get()));
} else if (nullptr != (iot_get_credential_endpoint = getenv("IOT_GET_CREDENTIAL_ENDPOINT")) &&
nullptr != (cert_path = getenv("CERT_PATH")) &&
nullptr != (private_key_path = getenv("PRIVATE_KEY_PATH")) &&
nullptr != (role_alias = getenv("ROLE_ALIAS")) &&
nullptr != (ca_cert_path = getenv("CA_CERT_PATH"))) {
LOG_INFO("Using IoT credentials for Kinesis Video Streams");
credential_provider.reset(new IotCertCredentialProvider(iot_get_credential_endpoint,
cert_path,
private_key_path,
role_alias,
ca_cert_path,
data->stream_name));
} else {
LOG_AND_THROW("No valid credential method was found");
}
data->kinesis_video_producer = KinesisVideoProducer::createSync(move(device_info_provider),
move(client_callback_provider),
move(stream_callback_provider),
move(credential_provider),
defaultRegionStr);
LOG_DEBUG("Client is ready");
}
void kinesis_video_stream_init(CustomData *data) {
/* create a test stream */
map<string, string> tags;
char tag_name[MAX_TAG_NAME_LEN];
char tag_val[MAX_TAG_VALUE_LEN];
SPRINTF(tag_name, "piTag");
SPRINTF(tag_val, "piValue");
STREAMING_TYPE streaming_type = DEFAULT_STREAMING_TYPE;
data->use_absolute_fragment_times = DEFAULT_ABSOLUTE_FRAGMENT_TIMES;
unique_ptr<StreamDefinition> stream_definition(new StreamDefinition(
data->stream_name,
hours(DEFAULT_RETENTION_PERIOD_HOURS),
&tags,
DEFAULT_KMS_KEY_ID,
streaming_type,
DEFAULT_CONTENT_TYPE,
duration_cast<milliseconds> (seconds(DEFAULT_MAX_LATENCY_SECONDS)),
milliseconds(DEFAULT_FRAGMENT_DURATION_MILLISECONDS),
milliseconds(DEFAULT_TIMECODE_SCALE_MILLISECONDS),
DEFAULT_KEY_FRAME_FRAGMENTATION,
DEFAULT_FRAME_TIMECODES,
data->use_absolute_fragment_times,
DEFAULT_FRAGMENT_ACKS,
DEFAULT_RESTART_ON_ERROR,
DEFAULT_RECALCULATE_METRICS,
0,
DEFAULT_STREAM_FRAMERATE,
DEFAULT_AVG_BANDWIDTH_BPS,
seconds(DEFAULT_BUFFER_DURATION_SECONDS),
seconds(DEFAULT_REPLAY_DURATION_SECONDS),
seconds(DEFAULT_CONNECTION_STALENESS_SECONDS),
DEFAULT_CODEC_ID,
DEFAULT_TRACKNAME,
nullptr,
0));
data->kinesis_video_stream = data->kinesis_video_producer->createStreamSync(move(stream_definition));
// reset state
data->stream_status = STATUS_SUCCESS;
data->stream_started = false;
LOG_DEBUG("Stream is ready");
}
int gstreamer_live_source_init(int argc, char* argv[], CustomData *data, GstElement *pipeline) {
int width = 0, height = 0, framerate = 25, bitrateInKBPS = 512;
char device[32] = { 0 };
// index 1 is stream name which is already processed
for (int i = 2; i < argc; i++) {
if (i < argc) {
if ((0 == STRCMPI(argv[i], "-w")) ||
(0 == STRCMPI(argv[i], "--w"))) {
if (STATUS_FAILED(STRTOI32(argv[i + 1], NULL, 10, &width))) {
return 1;
}
}
else if ((0 == STRCMPI(argv[i], "-h")) ||
(0 == STRCMPI(argv[i], "--h"))) {
if (STATUS_FAILED(STRTOI32(argv[i + 1], NULL, 10, &height))) {
return 1;
}
}
else if ((0 == STRCMPI(argv[i], "-f")) ||
(0 == STRCMPI(argv[i], "--f"))) {
if (STATUS_FAILED(STRTOI32(argv[i + 1], NULL, 10, &framerate))) {
return 1;
}
}
else if ((0 == STRCMPI(argv[i], "-b")) ||
(0 == STRCMPI(argv[i], "--b"))) {
if (STATUS_FAILED(STRTOI32(argv[i + 1], NULL, 10, &bitrateInKBPS))) {
return 1;
}
}
else if ((0 == STRCMPI(argv[i], "-d")) ||
(0 == STRCMPI(argv[i], "--d"))) {
STRCPY(device, argv[i + 1]);
}
i++;
}
else if (0 == STRCMPI(argv[i], "-?") ||
0 == STRCMPI(argv[i], "--help")) {
g_printerr("Invalid arguments\n");
return 1;
}
else if (argv[i][0] == '/' ||
argv[i][0] == '-') {
g_printerr("Invalid arguments\n");
return 1;
}
}
if ((width == 0 && height != 0) || (width != 0 && height == 0)) {
g_printerr("Invalid resolution\n");
return 1;
}
LOG_DEBUG("Streaming with live source and width: " << width << ", height: " << height << ", fps: " << framerate << ", bitrateInKBPS" << bitrateInKBPS);
GstElement *source_filter, *filter, *appsink, *h264parse, *source;
/* create the elemnents */
/*
gst-launch-1.0 v4l2src device=/dev/video0 ! video/x-raw,format=I420,width=1280,height=720,framerate=15/1 ! x264enc pass=quant bframes=0 ! video/x-h264,profile=baseline,format=I420,width=1280,height=720,framerate=15/1 ! matroskamux ! filesink location=test.mkv
*/
source_filter = gst_element_factory_make("capsfilter", "source_filter");
filter = gst_element_factory_make("capsfilter", "encoder_filter");
appsink = gst_element_factory_make("appsink", "appsink");
h264parse = gst_element_factory_make("h264parse", "h264parse"); // needed to enforce avc stream format
source = gst_element_factory_make("v4l2src", "source");
if (!pipeline || !source || !source_filter || !filter || !appsink || !h264parse) {
g_printerr("Not all elements could be created.\n");
return 1;
}
g_object_set(G_OBJECT (source), "do-timestamp", TRUE, "device", device, NULL);
/* Determine whether device supports h264 encoding and select a streaming resolution supported by the device*/
if (GST_STATE_CHANGE_FAILURE == gst_element_set_state(source, GST_STATE_READY)) {
g_printerr("Unable to set the source to ready state.\n");
return 1;
}
GstPad *srcpad = gst_element_get_static_pad(source, "src");
GstCaps *src_caps = gst_pad_query_caps(srcpad, NULL);
gst_element_set_state(source, GST_STATE_NULL);
GstCaps *query_caps_h264 = gst_caps_new_simple("video/x-h264",
"width", G_TYPE_INT, width,
"height", G_TYPE_INT, height,
NULL);
if (width != 0 && height != 0) {
if (!resolution_supported(src_caps, query_caps_h264, *data, width, height, framerate)) {
g_printerr("Resolution %dx%d not supported by video source\n", width, height);
return 1;
}
} else {
if (!resolution_supported(src_caps, query_caps_h264, *data, 1280, 720, 20)) {
g_printerr("Default resolution 1280x720 and framerate 20 are not supported by video source\n");
return 1;
}
}
gst_caps_unref(src_caps);
gst_object_unref(srcpad);
gst_caps_set_simple(query_caps_h264,
"stream-format", G_TYPE_STRING, "byte-stream",
"alignment", G_TYPE_STRING, "au",
NULL);
g_object_set(G_OBJECT (source_filter), "caps", query_caps_h264, NULL);
gst_caps_unref(query_caps_h264);
/* configure filter */
GstCaps *h264_caps = gst_caps_new_simple("video/x-h264",
"stream-format", G_TYPE_STRING, "avc",
"alignment", G_TYPE_STRING, "au",
NULL);
g_object_set(G_OBJECT (filter), "caps", h264_caps, NULL);
gst_caps_unref(h264_caps);
/* configure appsink */
g_object_set(G_OBJECT (appsink), "emit-signals", TRUE, "sync", FALSE, NULL);
g_signal_connect(appsink, "new-sample", G_CALLBACK(on_new_sample), data);
gst_bin_add_many(GST_BIN (pipeline), source, source_filter, h264parse, filter, appsink, NULL);
if (!gst_element_link_many(source, source_filter, h264parse, filter, appsink, NULL)) {
g_printerr("Elements could not be linked.\n");
gst_object_unref(pipeline);
return 1;
}
return 0;
}
int gstreamer_init(int argc, char* argv[], CustomData *data) {
/* init GStreamer */
gst_init(&argc, &argv);
GstElement *pipeline;
int ret;
GstStateChangeReturn gst_ret;
// Reset first frame pts
data->first_pts = GST_CLOCK_TIME_NONE;
LOG_INFO("Streaming from live source");
pipeline = gst_pipeline_new("live-kinesis-pipeline");
ret = gstreamer_live_source_init(argc, argv, data, pipeline);
if (ret != 0){
return ret;
}
/* Instruct the bus to emit signals for each received message, and connect to the interesting signals */
GstBus *bus = gst_element_get_bus(pipeline);
gst_bus_add_signal_watch(bus);
g_signal_connect (G_OBJECT(bus), "message::error", (GCallback) error_cb, data);
gst_object_unref(bus);
/* start streaming */
gst_ret = gst_element_set_state(pipeline, GST_STATE_PLAYING);
if (gst_ret == GST_STATE_CHANGE_FAILURE) {
g_printerr("Unable to set the pipeline to the playing state.\n");
gst_object_unref(pipeline);
return 1;
}
data->main_loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(data->main_loop);
/* free resources */
gst_bus_remove_signal_watch(bus);
gst_element_set_state(pipeline, GST_STATE_NULL);
gst_object_unref(pipeline);
g_main_loop_unref(data->main_loop);
data->main_loop = NULL;
return 0;
}
int main(int argc, char* argv[]) {
PropertyConfigurator::doConfigure("./kvs_log_configuration");
if (argc < 2) {
LOG_ERROR(
"Usage: AWS_ACCESS_KEY_ID=MY AWS_SECRET_ACCESS_KEY=MY AWS_DEFAULT_REGION=MY ./AmazonKinesisProducerCpp my-stream-name -w width -h height -f framerate -b bitrateInKBPS\n");
return 1;
}
CustomData data;
char stream_name[MAX_STREAM_NAME_LEN + 1];
STATUS stream_status = STATUS_SUCCESS;
STRNCPY(stream_name, argv[1], MAX_STREAM_NAME_LEN);
stream_name[MAX_STREAM_NAME_LEN] = '\0';
data.stream_name = stream_name;
try{
kinesis_video_init(&data);
kinesis_video_stream_init(&data);
} catch (runtime_error &err) {
LOG_ERROR("Failed to initialize kinesis video with an exception: " << err.what());
return 1;
}
gstreamer_init(argc, argv, &data);
if (STATUS_SUCCEEDED(stream_status)) {
// if stream_status is success after eos, send out remaining frames.
data.kinesis_video_stream->stopSync();
} else {
data.kinesis_video_stream->stop();
}
data.kinesis_video_producer->freeStream(data.kinesis_video_stream);
return 0;
}
| 38.350631 | 266 | 0.647345 | [
"vector"
] |
cc95a0e5b67066164b1608e240fc49295662c564 | 8,936 | cpp | C++ | examples/ShadowMapping/MainWindow.cpp | unclejimbo/Klein | bf0f91161ea583d4b053ebae17b92ed57680d8a4 | [
"BSD-3-Clause"
] | 37 | 2017-10-03T16:49:43.000Z | 2022-03-11T05:45:05.000Z | examples/ShadowMapping/MainWindow.cpp | unclejimbo/Klein | bf0f91161ea583d4b053ebae17b92ed57680d8a4 | [
"BSD-3-Clause"
] | null | null | null | examples/ShadowMapping/MainWindow.cpp | unclejimbo/Klein | bf0f91161ea583d4b053ebae17b92ed57680d8a4 | [
"BSD-3-Clause"
] | 3 | 2019-09-01T15:59:20.000Z | 2020-04-17T12:29:43.000Z | #include "MainWindow.h"
#include <Klein/Input/TrackballCameraController.h>
#include <Klein/Render/CheckerboardTextureImage.h>
#include <Klein/Render/DirectionalShadowCaster.h>
#include <Klein/Render/PBRMaterial.h>
#include <imgui.h>
#include <QColor>
#include <QVector3D>
#include <Qt3DCore/QEntity>
#include <Qt3DCore/QTransform>
#include <Qt3DExtras/QPlaneMesh>
#include <Qt3DRender/QCamera>
#include <Qt3DRender/QCameraSelector>
#include <Qt3DRender/QClearBuffers>
#include <Qt3DRender/QDirectionalLight>
#include <Qt3DRender/QEnvironmentLight>
#include <Qt3DRender/QFrameGraphNode>
#include <Qt3DRender/QMesh>
#include <Qt3DRender/QNoDraw>
#include <Qt3DRender/QRenderSettings>
#include <Qt3DRender/QRenderSurfaceSelector>
#include <Qt3DRender/QTexture>
#include <Qt3DRender/QTextureWrapMode>
#include <Qt3DRender/QViewport>
Qt3DRender::QAbstractTexture* loadTexture(
Qt3DCore::QNode* parent,
const QString& file,
bool genMipMaps,
Qt3DRender::QAbstractTexture::Filter filter)
{
Qt3DRender::QTextureWrapMode wrapMode;
wrapMode.setX(Qt3DRender::QTextureWrapMode::ClampToEdge);
wrapMode.setY(Qt3DRender::QTextureWrapMode::ClampToEdge);
auto texture = new Qt3DRender::QTextureLoader(parent);
texture->setSource(QUrl::fromLocalFile(file));
texture->setWrapMode(wrapMode);
texture->setGenerateMipMaps(genMipMaps);
texture->setMagnificationFilter(filter);
texture->setMinificationFilter(filter);
return texture;
}
MainWindow::MainWindow(QWindow* parent) : Klein::AbstractQt3DWindow(parent) {}
void MainWindow::resizeEvent(QResizeEvent*)
{
if (m_camera) {
m_camera->setAspectRatio(this->width() / (float)this->height());
}
if (m_cameraController) { m_cameraController->setWindowSize(this->size()); }
}
Qt3DCore::QEntity* MainWindow::createSceneGraph()
{
auto rootEntity = new Qt3DCore::QEntity;
auto bunnyMesh = new Qt3DRender::QMesh(rootEntity);
bunnyMesh->setSource(
QUrl::fromLocalFile(QStringLiteral("./data/mesh/bunny.obj")));
auto planeMesh = new Qt3DExtras::QPlaneMesh(rootEntity);
planeMesh->setWidth(5.0f);
planeMesh->setHeight(5.0f);
auto brdfMap = loadTexture(rootEntity,
QStringLiteral("./data/envmap/brdfSmith.dds"),
false,
Qt3DRender::QAbstractTexture::Linear);
auto irradianceMap =
loadTexture(rootEntity,
QStringLiteral("./data/envmap/outdoorDiffuseHDR.dds"),
false,
Qt3DRender::QAbstractTexture::Linear);
auto specularMap =
loadTexture(rootEntity,
QStringLiteral("./data/envmap/outdoorSpecularHDR.dds"),
false,
Qt3DRender::QAbstractTexture::Linear);
auto texture = new Qt3DRender::QTexture2D(rootEntity);
auto image = new Klein::CheckerboardTextureImage(texture);
texture->addTextureImage(image);
// This material both casts and recieves shadow
auto bunnyMaterial0 = new Klein::PBRMaterial(rootEntity);
bunnyMaterial0->setBaseColor(QColor("teal"));
bunnyMaterial0->setRoughness(1.0f);
bunnyMaterial0->setMetalness(0.0f);
bunnyMaterial0->setShadowCastingEnabled(true);
bunnyMaterial0->setShadowReceivingEnabled(true);
bunnyMaterial0->setEnvLightBrdf(brdfMap);
bunnyMaterial0->setEnvLightIntensity(0.2f);
bunnyMaterial0->setBaseColorMap(texture);
bunnyMaterial0->setRoughnessMap(texture);
bunnyMaterial0->setMetalnessMap(texture);
bunnyMaterial0->setNormalMap(texture);
// This material only casts shadow
auto bunnyMaterial1 = new Klein::PBRMaterial(rootEntity);
bunnyMaterial1->setBaseColor(QColor("orange"));
bunnyMaterial1->setRoughness(1.0f);
bunnyMaterial1->setMetalness(0.0f);
bunnyMaterial1->setShadowCastingEnabled(true);
bunnyMaterial1->setEnvLightBrdf(brdfMap);
bunnyMaterial1->setEnvLightIntensity(0.2f);
bunnyMaterial1->setBaseColorMap(texture);
bunnyMaterial1->setRoughnessMap(texture);
bunnyMaterial1->setMetalnessMap(texture);
bunnyMaterial1->setNormalMap(texture);
// This material only recieves shadow
auto planeMaterial = new Klein::PBRMaterial(rootEntity);
planeMaterial->setBaseColor(QColor("white"));
planeMaterial->setRoughness(1.0f);
planeMaterial->setMetalness(0.0f);
planeMaterial->setShadowReceivingEnabled(true);
planeMaterial->setEnvLightBrdf(brdfMap);
planeMaterial->setEnvLightIntensity(0.2f);
auto bunnyTransform0 = new Qt3DCore::QTransform(rootEntity);
bunnyTransform0->setScale(0.5f);
bunnyTransform0->setTranslation(QVector3D(0.8f, 0.5f, 0.8f));
auto bunnyTransform1 = new Qt3DCore::QTransform(rootEntity);
bunnyTransform1->setScale(0.5f);
bunnyTransform1->setTranslation(QVector3D(-0.0f, 0.5f, -0.0f));
auto bunnyTransform2 = new Qt3DCore::QTransform(rootEntity);
bunnyTransform2->setScale(0.5f);
bunnyTransform2->setTranslation(QVector3D(-0.8f, 0.5f, -0.8f));
auto bunny0 = new Qt3DCore::QEntity(rootEntity);
bunny0->addComponent(bunnyMesh);
bunny0->addComponent(bunnyMaterial0);
bunny0->addComponent(bunnyTransform0);
auto bunny1 = new Qt3DCore::QEntity(rootEntity);
bunny1->addComponent(bunnyMesh);
bunny1->addComponent(bunnyMaterial1);
bunny1->addComponent(bunnyTransform1);
auto bunny2 = new Qt3DCore::QEntity(rootEntity);
bunny2->addComponent(bunnyMesh);
bunny2->addComponent(bunnyMaterial0);
bunny2->addComponent(bunnyTransform2);
auto plane = new Qt3DCore::QEntity(rootEntity);
plane->addComponent(planeMesh);
plane->addComponent(planeMaterial);
// Direct lighting creates shadow
auto dlightLighting = new Qt3DRender::QDirectionalLight(rootEntity);
dlightLighting->setWorldDirection(QVector3D(-1.0f, -1.0f, -1.0f));
dlightLighting->setIntensity(2.0f);
dlightLighting->setColor(Qt::white);
auto dlight = new Qt3DCore::QEntity(rootEntity);
dlight->addComponent(dlightLighting);
// Set up the shadow map
m_dcaster = new Klein::DirectionalShadowCaster(rootEntity);
m_dcaster->setSize(QSize(2048, 2048));
m_dcaster->lookAt(QVector3D(3.0f, 3.0f, 3.0f),
QVector3D(0.0f, 0.0f, 0.0f),
QVector3D(0.0f, 1.0f, 0.0f));
m_dcaster->setFrustum(-2.0f, 2.0f, -2.0f, 2.0f, 0.1f, 20.0f);
// Image-based lighting doesn't create shadow
auto ibl = new Qt3DCore::QEntity(rootEntity);
auto envMap = new Qt3DRender::QEnvironmentLight(ibl);
envMap->setIrradiance(irradianceMap);
envMap->setSpecular(specularMap);
ibl->addComponent(envMap);
m_camera = new Qt3DRender::QCamera(rootEntity);
m_camera->setPosition(QVector3D(2.0f, 2.0f, 2.0f));
m_camera->setViewCenter(QVector3D(0, 0, 0));
auto aspect = (this->width() + 0.0f) / this->height();
m_camera->lens()->setPerspectiveProjection(60.0f, aspect, 0.1f, 100.0f);
m_cameraController = new Klein::TrackballCameraController(rootEntity);
m_cameraController->setCamera(m_camera);
m_cameraController->setWindowSize(this->size());
return rootEntity;
}
Qt3DRender::QRenderSettings* MainWindow::createRenderSettings(
Qt3DCore::QEntity* root)
{
auto rootNode = new Qt3DRender::QFrameGraphNode(root);
// Shadow map generation
{
auto surfaceSelector = new Qt3DRender::QRenderSurfaceSelector(rootNode);
surfaceSelector->setSurface(this);
surfaceSelector->setExternalRenderTargetSize(m_dcaster->size());
auto viewport = new Qt3DRender::QViewport(surfaceSelector);
viewport->setNormalizedRect(QRect(0, 0, 1, 1));
// Set up framegraph for shadow map
auto shadowCaster = m_dcaster->attachTo(viewport);
// Set up framegraph for shadow casting material
Klein::BasePBRMaterial::attachShadowPassTo(shadowCaster);
}
// Forward pass
{
auto surfaceSelector = new Qt3DRender::QRenderSurfaceSelector(rootNode);
surfaceSelector->setSurface(this);
auto viewport = new Qt3DRender::QViewport(surfaceSelector);
viewport->setNormalizedRect(QRect(0, 0, 1, 1));
auto clearBuffers = new Qt3DRender::QClearBuffers(viewport);
clearBuffers->setBuffers(Qt3DRender::QClearBuffers::ColorDepthBuffer);
clearBuffers->setClearColor(QColor(255, 255, 255));
new Qt3DRender::QNoDraw(clearBuffers);
auto cameraSelctor = new Qt3DRender::QCameraSelector(viewport);
cameraSelctor->setCamera(m_camera);
Klein::BasePBRMaterial::attachRenderPassTo(
cameraSelctor,
m_dcaster->shadowMap(),
m_dcaster->lightSpaceMatrix(),
m_dcaster->lightDirection(),
100.0f);
}
auto settings = new Qt3DRender::QRenderSettings(root);
settings->setActiveFrameGraph(rootNode);
return settings;
}
| 37.864407 | 80 | 0.708259 | [
"mesh",
"render"
] |
cc968b7dda17744b5eff14270930339f000bee9a | 788 | cpp | C++ | aws-cpp-sdk-compute-optimizer/source/model/GetEnrollmentStatusRequest.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-compute-optimizer/source/model/GetEnrollmentStatusRequest.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-compute-optimizer/source/model/GetEnrollmentStatusRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/compute-optimizer/model/GetEnrollmentStatusRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::ComputeOptimizer::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
GetEnrollmentStatusRequest::GetEnrollmentStatusRequest()
{
}
Aws::String GetEnrollmentStatusRequest::SerializePayload() const
{
return "{}";
}
Aws::Http::HeaderValueCollection GetEnrollmentStatusRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "ComputeOptimizerService.GetEnrollmentStatus"));
return headers;
}
| 22.514286 | 108 | 0.775381 | [
"model"
] |
cc9a95c0d3ed52f7c9cf94a967f755f4c286a468 | 2,235 | hpp | C++ | samples/threat_level/src/NpcWeaponSystem.hpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 41 | 2017-08-29T12:14:36.000Z | 2022-02-04T23:49:48.000Z | samples/threat_level/src/NpcWeaponSystem.hpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 11 | 2017-09-02T15:32:45.000Z | 2021-12-27T13:34:56.000Z | samples/threat_level/src/NpcWeaponSystem.hpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 5 | 2020-01-25T17:51:45.000Z | 2022-03-01T05:20:30.000Z | /*-----------------------------------------------------------------------
Matt Marchant 2017
http://trederia.blogspot.com
crogine test application - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#ifndef TL_NPC_WEAPONS_SYSTEM_HPP_
#define TL_NPC_WEAPONS_SYSTEM_HPP_
#include <crogine/ecs/System.hpp>
#include <crogine/detail/glm/vec3.hpp>
#include <vector>
struct NpcWeapon final
{
enum
{
Pulse,
Laser,
Orb,
Missile
}type;
float damage = 0.f;
glm::vec3 velocity = glm::vec3(0.f);
};
class NpcWeaponSystem final : public cro::System
{
public:
explicit NpcWeaponSystem(cro::MessageBus&);
void handleMessage(const cro::Message&) override;
void process(float) override;
private:
float m_backgroundSpeed;
void onEntityAdded(cro::Entity) override;
void processPulse(std::size_t&, float);
void processLaser(cro::Entity, float);
void processOrb(std::size_t&, float);
void processMissile(cro::Entity);
std::size_t m_orbCount;
std::vector<std::int32_t> m_aliveOrbs;
std::size_t m_deadOrbCount;
std::vector<std::int32_t> m_deadOrbs;
std::vector<std::int32_t> m_activeLasers;
std::size_t m_alivePulseCount;
std::vector<std::int32_t> m_alivePulses;
std::size_t m_deadPulseCount;
std::vector<std::int32_t> m_deadPulses;
};
#endif //TL_NPC_WEAPONS_SYSTEM_HPP_ | 26.927711 | 73 | 0.691275 | [
"vector"
] |
cc9e21d829dddb55c96fd926020d2852354cb44c | 82,218 | cpp | C++ | vegastrike/src/cmd/unit_xml.cpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | vegastrike/src/cmd/unit_xml.cpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | vegastrike/src/cmd/unit_xml.cpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | #include "unit_xml.h"
#include "unit_factory.h"
#include "audiolib.h"
#include "xml_support.h"
#include <fstream>
#include <expat.h>
#include <float.h>
#include <limits.h>
#include "configxml.h"
#include "vs_globals.h"
#include "vegastrike.h"
#include <assert.h>
#include "images.h"
#include "xml_serializer.h"
#include "vsfilesystem.h"
#include "gfx/cockpit_generic.h"
#include "unit_collide.h"
#include "unit_generic.h"
#include "gfx/sphere.h"
#include "role_bitmask.h"
#include "cmd/collide2/Stdafx.h"
#include "cmd/collide2/CSopcodecollider.h"
#include "networking/netclient.h"
#define VS_PI (3.1415926536)
/*ADDED FOR extensible use of unit pretty print and unit load */
UNITLOADTYPE current_unit_load_mode = DEFAULT;
extern float getFuelConversion();
string KillQuadZeros( string inp )
{
std::string::size_type text = 0;
while ( ( text = inp.find( ".000000", text ) ) != string::npos )
inp = inp.substr( 0, text )+inp.substr( text+7 );
return inp;
}
string MakeUnitXMLPretty( string str, Unit *un )
{
string writestr;
if (un) {
writestr += "Name: "+un->name;
writestr += " "+un->getFullname();
Flightgroup *fg = un->getFlightgroup();
if (fg)
writestr += " Designation "+fg->name+" "+XMLSupport::tostring( un->getFgSubnumber() );
writestr += "\n";
}
static std::set< string >lookfor;
if ( lookfor.empty() ) {
lookfor.insert( "Shie" );
lookfor.insert( "Armo" );
//lookfor.insert ("Hull");
lookfor.insert( "Reac" );
lookfor.insert( "Moun" );
lookfor.insert( "Comp" );
//lookfor.insert ("Desc");
lookfor.insert( "Engi" );
lookfor.insert( "Mane" );
lookfor.insert( "Jump" );
//lookfor.insert ("Defe");
lookfor.insert( "Stat" );
lookfor.insert( "Engi" );
//lookfor.insert ("Hold");
lookfor.insert( "Rada" );
}
std::string::size_type foundpos;
while ( ( foundpos = str.find( "<" ) ) != string::npos ) {
if (str.size() <= foundpos+1)
break;
str = str.substr( foundpos+1 );
if (str.size() > 3) {
char mycomp[5] = {str[0], str[1], str[2], str[3], 0};
if ( lookfor.find( mycomp ) != lookfor.end() ) {
int newline = str.find( ">" );
if (newline > 0)
if (str[newline-1] == '/')
newline -= 1;
writestr += KillQuadZeros( str.substr( 0, newline )+"\n" );
}
}
}
return writestr;
}
int GetModeFromName( const char *input_buffer )
{
if (strlen( input_buffer ) > 3) {
if (input_buffer[0] == 'a'
&& input_buffer[1] == 'd'
&& input_buffer[2] == 'd')
return 1;
if (input_buffer[0] == 'm'
&& input_buffer[1] == 'u'
&& input_buffer[2] == 'l')
return 2;
}
return 0;
}
extern bool CheckAccessory( Unit* );
void Unit::beginElement( void *userData, const XML_Char *name, const XML_Char **atts )
{
( (Unit*) userData )->beginElement( name, AttributeList( atts ) );
}
void Unit::endElement( void *userData, const XML_Char *name )
{
( (Unit*) userData )->endElement( name );
}
namespace UnitXML
{
enum Names
{
UNKNOWN,
UNIT,
SUBUNIT,
MESHFILE,
SHIELDMESH,
RAPIDMESH,
MOUNT,
MESHLIGHT,
DOCK,
XFILE,
X,
Y,
Z,
RI,
RJ,
RK,
QI,
QJ,
QK,
RED,
GREEN,
BLUE,
ALPHA,
ACTIVATIONSPEED,
MOUNTSIZE,
WEAPON,
DEFENSE,
ARMOR,
WARPDRIVERATING,
FORWARD,
RETRO,
FRONT,
BACK,
LEFT,
RIGHT,
FRONTRIGHTTOP,
BACKRIGHTTOP,
FRONTLEFTTOP,
BACKLEFTTOP,
FRONTRIGHTBOTTOM,
BACKRIGHTBOTTOM,
FRONTLEFTBOTTOM,
BACKLEFTBOTTOM,
TOP,
BOTTOM,
SHIELDS,
RECHARGE,
LEAK,
HULL,
STRENGTH,
STATS,
MASS,
MOMENTOFINERTIA,
FUEL,
THRUST,
MANEUVER,
YAW,
ROLL,
PITCH,
ENGINE,
COMPUTER,
AACCEL,
ENERGY,
REACTOR,
LIMIT,
RESTRICTED,
MAX,
MIN,
MAXSPEED,
AFTERBURNER,
SHIELDTIGHT,
ITTS,
AMMO,
HUDIMAGE,
SOUND,
MINTARGETSIZE,
MAXCONE,
LOCKCONE,
RANGE,
ISCOLOR,
RADAR,
CLOAK,
CLOAKRATE,
CLOAKMIN,
CLOAKENERGY,
CLOAKGLASS,
CLOAKWAV,
CLOAKMP3,
ENGINEWAV,
ENGINEMP3,
HULLWAV,
HULLMP3,
ARMORWAV,
ARMORMP3,
SHIELDWAV,
SHIELDMP3,
EXPLODEWAV,
EXPLODEMP3,
EXPLOSIONANI,
COCKPIT,
JUMP,
DELAY,
JUMPENERGY,
JUMPWAV,
NETCOM,
NETCOMM_MINFREQ,
NETCOMM_MAXFREQ,
NETCOMM_SECURED,
NETCOMM_VIDEO,
NETCOMM_CRYPTO,
DOCKINTERNAL,
WORMHOLE,
RAPID,
AFTERBURNENERGY,
MISSING,
UNITSCALE,
PRICE,
VOLUME,
QUANTITY,
CARGO,
HOLD,
CATEGORY,
IMPORT,
PRICESTDDEV,
QUANTITYSTDDEV,
DAMAGE,
COCKPITDAMAGE,
REPAIRDROID,
ECM,
DESCRIPTION,
UPGRADE,
MOUNTOFFSET,
SUBUNITOFFSET,
SLIDE_START,
SLIDE_END,
TRACKINGCONE,
MISSIONCARGO,
MAXIMUM,
LIGHTTYPE,
COMBATROLE,
RECURSESUBUNITCOLLISION,
WARPENERGY,
FACECAMERA,
XYSCALE,
INSYSENERGY,
ZSCALE,
NUMANIMATIONSTAGES,
STARTFRAME,
TEXTURESTARTTIME
};
const EnumMap::Pair element_names[37] = {
EnumMap::Pair( "UNKNOWN", UNKNOWN ),
EnumMap::Pair( "Unit", UNIT ),
EnumMap::Pair( "SubUnit", SUBUNIT ),
EnumMap::Pair( "Sound", SOUND ),
EnumMap::Pair( "MeshFile", MESHFILE ),
EnumMap::Pair( "ShieldMesh", SHIELDMESH ),
EnumMap::Pair( "RapidMesh", RAPIDMESH ),
EnumMap::Pair( "Light", MESHLIGHT ),
EnumMap::Pair( "Defense", DEFENSE ),
EnumMap::Pair( "Armor", ARMOR ),
EnumMap::Pair( "Shields", SHIELDS ),
EnumMap::Pair( "Hull", HULL ),
EnumMap::Pair( "Stats", STATS ),
EnumMap::Pair( "Thrust", THRUST ),
EnumMap::Pair( "Maneuver", MANEUVER ),
EnumMap::Pair( "Engine", ENGINE ),
EnumMap::Pair( "Computer", COMPUTER ),
EnumMap::Pair( "Cloak", CLOAK ),
EnumMap::Pair( "Energy", ENERGY ),
EnumMap::Pair( "Reactor", REACTOR ),
EnumMap::Pair( "Restricted", RESTRICTED ),
EnumMap::Pair( "Yaw", YAW ),
EnumMap::Pair( "Pitch", PITCH ),
EnumMap::Pair( "Roll", ROLL ),
EnumMap::Pair( "Mount", MOUNT ),
EnumMap::Pair( "Radar", RADAR ),
EnumMap::Pair( "Cockpit", COCKPIT ),
EnumMap::Pair( "Jump", JUMP ),
EnumMap::Pair( "Netcomm", NETCOM ),
EnumMap::Pair( "Dock", DOCK ),
EnumMap::Pair( "Hold", HOLD ),
EnumMap::Pair( "Cargo", CARGO ),
EnumMap::Pair( "Category", CATEGORY ),
EnumMap::Pair( "Import", IMPORT ),
EnumMap::Pair( "CockpitDamage", COCKPITDAMAGE ),
EnumMap::Pair( "Upgrade", UPGRADE ),
EnumMap::Pair( "Description", DESCRIPTION ),
};
const EnumMap::Pair attribute_names[119] = {
EnumMap::Pair( "UNKNOWN", UNKNOWN ),
EnumMap::Pair( "missing", MISSING ),
EnumMap::Pair( "file", XFILE ),
EnumMap::Pair( "x", X ),
EnumMap::Pair( "y", Y ),
EnumMap::Pair( "z", Z ),
EnumMap::Pair( "xyscale", XYSCALE ),
EnumMap::Pair( "zscale", ZSCALE ),
EnumMap::Pair( "ri", RI ),
EnumMap::Pair( "rj", RJ ),
EnumMap::Pair( "rk", RK ),
EnumMap::Pair( "qi", QI ),
EnumMap::Pair( "qj", QJ ),
EnumMap::Pair( "qk", QK ),
EnumMap::Pair( "activationSpeed", ACTIVATIONSPEED ),
EnumMap::Pair( "red", RED ),
EnumMap::Pair( "green", GREEN ),
EnumMap::Pair( "blue", BLUE ),
EnumMap::Pair( "alpha", ALPHA ),
EnumMap::Pair( "size", MOUNTSIZE ),
EnumMap::Pair( "forward", FORWARD ),
EnumMap::Pair( "retro", RETRO ),
EnumMap::Pair( "frontrighttop", FRONTRIGHTTOP ),
EnumMap::Pair( "backrighttop", BACKRIGHTTOP ),
EnumMap::Pair( "frontlefttop", FRONTLEFTTOP ),
EnumMap::Pair( "backlefttop", BACKLEFTTOP ),
EnumMap::Pair( "frontrightbottom", FRONTRIGHTBOTTOM ),
EnumMap::Pair( "backrightbottom", BACKRIGHTBOTTOM ),
EnumMap::Pair( "frontleftbottom", FRONTLEFTBOTTOM ),
EnumMap::Pair( "backleftbottom", BACKLEFTBOTTOM ),
EnumMap::Pair( "front", FRONT ),
EnumMap::Pair( "back", BACK ),
EnumMap::Pair( "left", LEFT ),
EnumMap::Pair( "right", RIGHT ),
EnumMap::Pair( "top", TOP ),
EnumMap::Pair( "bottom", BOTTOM ),
EnumMap::Pair( "recharge", RECHARGE ),
EnumMap::Pair( "warpenergy", WARPENERGY ),
EnumMap::Pair( "insysenergy", INSYSENERGY ),
EnumMap::Pair( "leak", LEAK ),
EnumMap::Pair( "strength", STRENGTH ),
EnumMap::Pair( "mass", MASS ),
EnumMap::Pair( "momentofinertia", MOMENTOFINERTIA ),
EnumMap::Pair( "fuel", FUEL ),
EnumMap::Pair( "yaw", YAW ),
EnumMap::Pair( "pitch", PITCH ),
EnumMap::Pair( "roll", ROLL ),
EnumMap::Pair( "accel", AACCEL ),
EnumMap::Pair( "limit", LIMIT ),
EnumMap::Pair( "max", MAX ),
EnumMap::Pair( "min", MIN ),
EnumMap::Pair( "weapon", WEAPON ),
EnumMap::Pair( "maxspeed", MAXSPEED ),
EnumMap::Pair( "afterburner", AFTERBURNER ),
EnumMap::Pair( "tightness", SHIELDTIGHT ),
EnumMap::Pair( "itts", ITTS ),
EnumMap::Pair( "ammo", AMMO ),
EnumMap::Pair( "HudImage", HUDIMAGE ),
EnumMap::Pair( "ExplosionAni", EXPLOSIONANI ),
EnumMap::Pair( "MaxCone", MAXCONE ),
EnumMap::Pair( "TrackingCone", TRACKINGCONE ),
EnumMap::Pair( "LockCone", LOCKCONE ),
EnumMap::Pair( "MinTargetSize", MINTARGETSIZE ),
EnumMap::Pair( "Range", RANGE ),
EnumMap::Pair( "EngineMp3", ENGINEMP3 ),
EnumMap::Pair( "EngineWav", ENGINEWAV ),
EnumMap::Pair( "HullMp3", HULLMP3 ),
EnumMap::Pair( "HullWav", HULLWAV ),
EnumMap::Pair( "ArmorMp3", ARMORMP3 ),
EnumMap::Pair( "ArmorWav", ARMORWAV ),
EnumMap::Pair( "ShieldMp3", SHIELDMP3 ),
EnumMap::Pair( "ShieldWav", SHIELDWAV ),
EnumMap::Pair( "ExplodeMp3", EXPLODEMP3 ),
EnumMap::Pair( "ExplodeWav", EXPLODEWAV ),
EnumMap::Pair( "CloakRate", CLOAKRATE ),
EnumMap::Pair( "CloakGlass", CLOAKGLASS ),
EnumMap::Pair( "CloakEnergy", CLOAKENERGY ),
EnumMap::Pair( "CloakMin", CLOAKMIN ),
EnumMap::Pair( "CloakMp3", CLOAKMP3 ),
EnumMap::Pair( "CloakWav", CLOAKWAV ),
EnumMap::Pair( "Color", ISCOLOR ),
EnumMap::Pair( "Restricted", RESTRICTED ),
EnumMap::Pair( "Delay", DELAY ),
EnumMap::Pair( "AfterburnEnergy", AFTERBURNENERGY ),
EnumMap::Pair( "JumpEnergy", JUMPENERGY ),
EnumMap::Pair( "JumpWav", JUMPWAV ),
EnumMap::Pair( "min_freq", NETCOMM_MINFREQ ),
EnumMap::Pair( "max_freq", NETCOMM_MAXFREQ ),
EnumMap::Pair( "secured", NETCOMM_SECURED ),
EnumMap::Pair( "video", NETCOMM_VIDEO ),
EnumMap::Pair( "crypto_method", NETCOMM_CRYPTO ),
EnumMap::Pair( "DockInternal", DOCKINTERNAL ),
EnumMap::Pair( "RAPID", RAPID ),
EnumMap::Pair( "Wormhole", WORMHOLE ),
EnumMap::Pair( "Scale", UNITSCALE ),
EnumMap::Pair( "Price", PRICE ),
EnumMap::Pair( "Volume", VOLUME ),
EnumMap::Pair( "Quantity", QUANTITY ),
EnumMap::Pair( "PriceStdDev", PRICESTDDEV ),
EnumMap::Pair( "PriceStDev", PRICESTDDEV ),
EnumMap::Pair( "QuantityStdDev", QUANTITYSTDDEV ),
EnumMap::Pair( "Damage", DAMAGE ),
EnumMap::Pair( "RepairDroid", REPAIRDROID ),
EnumMap::Pair( "ECM", ECM ),
EnumMap::Pair( "Description", DESCRIPTION ),
EnumMap::Pair( "MountOffset", MOUNTOFFSET ),
EnumMap::Pair( "SubunitOffset", SUBUNITOFFSET ),
EnumMap::Pair( "SlideEnd", SLIDE_START ),
EnumMap::Pair( "SlideStart", SLIDE_END ),
EnumMap::Pair( "MissionCargo", MISSIONCARGO ),
EnumMap::Pair( "Maximum", MAXIMUM ),
EnumMap::Pair( "LightType", LIGHTTYPE ),
EnumMap::Pair( "CombatRole", COMBATROLE ),
EnumMap::Pair( "RecurseSubunitCollision", RECURSESUBUNITCOLLISION ),
EnumMap::Pair( "FaceCamera", FACECAMERA ),
EnumMap::Pair( "NumAnimationStages", NUMANIMATIONSTAGES ),
EnumMap::Pair( "StartFrame", STARTFRAME ),
EnumMap::Pair( "TextureStartTime", TEXTURESTARTTIME ),
EnumMap::Pair( "WarpDriveRating", WARPDRIVERATING )
};
const EnumMap element_map( element_names, 37 );
const EnumMap attribute_map( attribute_names, 119 );
} //end of namespace
std::string delayucharStarHandler( const XMLType &input, void *mythis )
{
static int jumpdelaymult = XMLSupport::parse_int( vs_config->getVariable( "physics", "jump_delay_multiplier", "5" ) );
unsigned char uc = (*input.w.uc)/jumpdelaymult;
if (uc < 1)
uc = 1;
return XMLSupport::tostring( (int) uc );
}
//USED TO BE IN UNIT_FUNCTIONS*.CPP BUT NOW ON BOTH CLIENT AND SERVER SIDE
std::vector< Mesh* >MakeMesh( unsigned int mysize )
{
std::vector< Mesh* >temp;
for (unsigned int i = 0; i < mysize; i++)
temp.push_back( NULL );
return temp;
}
void addShieldMesh( Unit::XML *xml, const char *filename, const float scale, int faction, class Flightgroup *fg )
{
static bool forceit = XMLSupport::parse_bool( vs_config->getVariable( "graphics", "forceOneOneShieldBlend", "true" ) );
xml->shieldmesh = Mesh::LoadMesh( filename, Vector( scale, scale, scale ), faction, fg );
if (xml->shieldmesh && forceit) {
xml->shieldmesh->SetBlendMode( ONE, ONE, true );
xml->shieldmesh->setEnvMap( false, true );
xml->shieldmesh->setLighting( true, true );
}
}
void addRapidMesh( Unit::XML *xml, const char *filename, const float scale, int faction, class Flightgroup *fg )
{
xml->rapidmesh = Mesh::LoadMesh( filename, Vector( scale, scale, scale ), faction, fg );
}
void pushMesh( std::vector< Mesh* > &meshes,
float &randomstartframe,
float &randomstartseconds,
const char *filename,
const float scale,
int faction,
class Flightgroup *fg,
int startframe,
double texturestarttime )
{
vector< Mesh* >m = Mesh::LoadMeshes( filename, Vector( scale, scale, scale ), faction, fg );
for (unsigned int i = 0; i < m.size(); ++i) {
meshes.push_back( m[i] );
if (startframe >= 0) {
meshes.back()->setCurrentFrame( startframe );
} else if (startframe == -2) {
float r = ( (float) rand() )/RAND_MAX;
meshes.back()->setCurrentFrame( r*meshes.back()->getFramesPerSecond() );
} else if (startframe == -1) {
if (randomstartseconds == 0)
randomstartseconds = randomstartframe*meshes.back()->getNumLOD()/meshes.back()->getFramesPerSecond();
meshes.back()->setCurrentFrame( randomstartseconds*meshes.back()->getFramesPerSecond() );
}
if (texturestarttime > 0) {
meshes.back()->setTextureCumulativeTime( texturestarttime );
} else {
float fps = meshes.back()->getTextureFramesPerSecond();
int frames = meshes.back()->getNumTextureFrames();
double ran = randomstartframe;
if (fps > 0 && frames > 1) {
ran *= frames/fps;
} else {
ran *= 1000;
}
meshes.back()->setTextureCumulativeTime( ran );
}
}
}
Mount * createMount( const std::string &name, int ammo, int volume, float xyscale, float zscale, bool banked ) //short fix
{
return new Mount( name.c_str(), ammo, volume, xyscale, zscale, 1, 1, banked );
}
using XMLSupport::EnumMap;
using XMLSupport::Attribute;
using XMLSupport::AttributeList;
extern int GetModeFromName( const char* );
extern int parseMountSizes( const char *str );
static unsigned int CLAMP_UINT( float x )
{
return (unsigned int) ( ( (x) > 4294967295.0 ) ? (unsigned int) 4294967295U : ( (x) < 0 ? 0 : (x) ) );
} //short fix
#define ADDTAGNAME( a ) do {pImage->unitwriter->AddTag( a );} \
while (0)
#define ADDTAG do {pImage->unitwriter->AddTag( name );} \
while (0)
#define ADDELEMNAME( a, b, c ) do {pImage->unitwriter->AddElement( a, b, c );} \
while (0)
#define ADDELEM( b, c ) do {pImage->unitwriter->AddElement( (*iter).name, b, c );} \
while (0)
#define ADDDEFAULT do {pImage->unitwriter->AddElement( (*iter).name, stringHandler, XMLType( (*iter).value ) );} \
while (0)
#define ADDELEMI( b ) do {ADDELEM( intStarHandler, XMLType( &b ) );} \
while (0)
#define ADDELEMF( b ) do {ADDELEM( floatStarHandler, XMLType( &b ) );} \
while (0)
void Unit::beginElement( const string &name, const AttributeList &attributes )
{
using namespace UnitXML;
static float game_speed = XMLSupport::parse_float( vs_config->getVariable( "physics", "game_speed", "1" ) );
static float game_accel = XMLSupport::parse_float( vs_config->getVariable( "physics", "game_accel", "1" ) );
Cargo carg;
float act_speed = 0;
int volume = -1; //short fix
string filename;
QVector P;
int indx;
QVector Q;
QVector R;
QVector pos;
float xyscale = -1;
float zscale = -1;
bool tempbool;
unsigned int dirfrac = 0;
float fbrltb[6] = {-1};
AttributeList::const_iterator iter;
float halocolor[4];
int ammo = -1; //short fix
int mntsiz = weapon_info::NOWEAP;
string light_type;
Names elem = (Names) element_map.lookup( name );
switch (elem)
{
case SHIELDMESH:
ADDTAG;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case XFILE:
ADDELEM( stringHandler, (*iter).value );
addShieldMesh( xml, (*iter).value.c_str(), xml->unitscale, faction, flightgroup );
break;
case SHIELDTIGHT:
ADDDEFAULT;
shieldtight = parse_float( (*iter).value );
break;
}
}
break;
case RAPIDMESH:
ADDTAG;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case XFILE:
ADDDEFAULT;
addRapidMesh( xml, (*iter).value.c_str(), xml->unitscale, faction, NULL );
xml->hasColTree = true;
break;
case RAPID:
ADDDEFAULT;
xml->hasColTree = parse_bool( (*iter).value );
break;
}
}
break;
case HOLD:
ADDTAG;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case VOLUME:
ADDELEM( floatStarHandler, XMLType( &pImage->CargoVolume ) );
ADDELEM( floatStarHandler, XMLType( &pImage->UpgradeVolume ) );
pImage->UpgradeVolume = pImage->CargoVolume = parse_float( (*iter).value );
break;
}
}
pImage->unitwriter->AddTag( "Category" );
pImage->unitwriter->AddElement( "file", Unit::cargoSerializer, XMLType( (int) 0 ) );
pImage->unitwriter->EndTag( "Category" );
break;
case IMPORT:
Q.i = Q.k = 0;
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case QUANTITY:
carg.quantity = parse_int( (*iter).value );
//import cargo from ze maztah liztz
break;
case PRICE:
carg.price = parse_float( (*iter).value );
break;
case PRICESTDDEV:
Q.i = parse_float( (*iter).value );
break;
case QUANTITYSTDDEV:
Q.k = parse_float( (*iter).value );
break;
}
}
ImportPartList( xml->cargo_category, carg.price, Q.i, carg.quantity, Q.k );
break;
case CATEGORY:
//this is autogenerated by the handler
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case XFILE:
xml->cargo_category = XMLSupport::replace_space( (*iter).value );
break;
}
}
break;
case CARGO:
///handling taken care of above;
assert( xml->unitlevel >= 2 );
xml->unitlevel++;
carg.category = xml->cargo_category;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case QUANTITY:
carg.quantity = parse_int( (*iter).value );
break;
case MASS:
carg.mass = parse_float( (*iter).value );
break;
case VOLUME:
carg.volume = parse_float( (*iter).value );
break;
case PRICE:
carg.price = parse_float( (*iter).value );
break;
case MISSIONCARGO:
carg.mission = parse_bool( (*iter).value );
break;
case XFILE:
carg.content = XMLSupport::replace_space( (*iter).value );
break;
case DESCRIPTION:
carg.description = strdup( (*iter).value.c_str() ); //mem leak...but hey--only for mpl
break;
}
}
if (carg.mass != 0)
AddCargo( carg, false );
break;
case MESHFILE:
{
std::string file = "box.bfxm";
int startframe = 0;
double texturestarttime = 0;
ADDTAG;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case XFILE:
ADDDEFAULT;
file = (*iter).value;
break;
case STARTFRAME:
if (strtoupper( (*iter).value ) == "RANDOM")
startframe = -1;
else if (strtoupper( (*iter).value ) == "ASYNC")
startframe = -2;
else
startframe = parse_int( (*iter).value );
break;
case TEXTURESTARTTIME:
if (strtoupper( (*iter).value ) == "RANDOM")
texturestarttime = -1;
else
texturestarttime = parse_float( (*iter).value );
}
}
switch (current_unit_load_mode)
{
case NO_MESH:
break;
default:
pushMesh( xml->meshes, xml->randomstartframe, xml->randomstartseconds,
file.c_str(), xml->unitscale, faction, flightgroup, startframe, texturestarttime );
}
break;
}
case UPGRADE:
{
assert( xml->unitlevel >= 1 );
xml->unitlevel++;
double percent;
int moffset = 0;
int soffset = 0;
//don't serialize
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case XFILE:
filename = (*iter).value.c_str();
break;
case SUBUNITOFFSET:
soffset = parse_int( (*iter).value );
break;
case MOUNTOFFSET:
moffset = parse_int( (*iter).value );
break;
}
}
int upgrfac = FactionUtil::GetUpgradeFaction();
Unit *upgradee = UnitFactory::createUnit( filename.c_str(), true, upgrfac );
Unit::Upgrade( upgradee, moffset, soffset, GetModeFromName( filename.c_str() ), true, percent, NULL );
upgradee->Kill();
break;
}
case DOCK:
{
ADDTAG;
DockingPorts::Type::Value dockType = DockingPorts::Type::DEFAULT;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
pos = QVector( 0, 0, 0 );
P = QVector( 1, 1, 1 );
Q = QVector( FLT_MAX, FLT_MAX, FLT_MAX );
R = QVector( FLT_MAX, FLT_MAX, FLT_MAX );
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case DOCKINTERNAL:
ADDDEFAULT;
dockType = DockingPorts::Type::Value(parse_int((*iter).value));
break;
case X:
ADDDEFAULT;
pos.i = xml->unitscale*parse_float( (*iter).value );
break;
case Y:
ADDDEFAULT;
pos.j = xml->unitscale*parse_float( (*iter).value );
break;
case Z:
ADDDEFAULT;
pos.k = xml->unitscale*parse_float( (*iter).value );
break;
case TOP:
ADDDEFAULT;
R.j = xml->unitscale*parse_float( (*iter).value );
break;
case BOTTOM:
ADDDEFAULT;
Q.j = xml->unitscale*parse_float( (*iter).value );
break;
case LEFT:
ADDDEFAULT;
Q.i = xml->unitscale*parse_float( (*iter).value );
break;
case RIGHT:
ADDDEFAULT;
R.i = parse_float( (*iter).value );
break;
case BACK:
ADDDEFAULT;
Q.k = xml->unitscale*parse_float( (*iter).value );
break;
case FRONT:
ADDDEFAULT;
R.k = xml->unitscale*parse_float( (*iter).value );
break;
case MOUNTSIZE:
ADDDEFAULT;
P.i = xml->unitscale*parse_float( (*iter).value );
P.j = xml->unitscale*parse_float( (*iter).value );
break;
}
}
if (Q.i == FLT_MAX || Q.j == FLT_MAX || Q.k == FLT_MAX || R.i == FLT_MAX || R.j == FLT_MAX || R.k == FLT_MAX) {
pImage->dockingports.push_back( DockingPorts( pos.Cast(), P.i, 0, dockType ) );
} else {
QVector tQ = Q.Min( R );
QVector tR = R.Max( Q );
pImage->dockingports.push_back( DockingPorts( tQ.Cast(), tR.Cast(), 0, dockType ) );
}
}
break;
case MESHLIGHT:
ADDTAG;
vs_config->gethColor( "unit", "engine", halocolor, 0xffffffff );
assert( xml->unitlevel == 1 );
xml->unitlevel++;
P = QVector( 1, 1, 1 );
Q = QVector( 1, 1, 1 );
pos = QVector( 0, 0, 0 );
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case LIGHTTYPE:
ADDDEFAULT;
light_type = (*iter).value;
break;
case X:
ADDDEFAULT;
pos.i = xml->unitscale*parse_float( (*iter).value );
break;
case Y:
ADDDEFAULT;
pos.j = xml->unitscale*parse_float( (*iter).value );
break;
case Z:
ADDDEFAULT;
pos.k = xml->unitscale*parse_float( (*iter).value );
break;
case RED:
ADDDEFAULT;
halocolor[0] = parse_float( (*iter).value );
break;
case GREEN:
ADDDEFAULT;
halocolor[1] = parse_float( (*iter).value );
break;
case BLUE:
ADDDEFAULT;
halocolor[2] = parse_float( (*iter).value );
break;
case ALPHA:
ADDDEFAULT;
halocolor[3] = parse_float( (*iter).value );
break;
case XFILE:
ADDDEFAULT;
filename = (*iter).value;
break;
case ACTIVATIONSPEED:
act_speed = parse_float( (*iter).value );
break;
case MOUNTSIZE:
ADDDEFAULT;
P.i = xml->unitscale*parse_float( (*iter).value );
P.j = xml->unitscale*parse_float( (*iter).value );
P.k = xml->unitscale*parse_float( (*iter).value );
break;
}
}
addHalo( filename.c_str(), pos, P.Cast(), GFXColor( halocolor[0],
halocolor[1],
halocolor[2],
halocolor[3] ), light_type, act_speed );
break;
case MOUNT:
ADDTAG;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
Q = QVector( 0, 1, 0 );
R = QVector( 0, 0, 1 );
pos = QVector( 0, 0, 0 );
tempbool = false;
ADDELEMNAME( "size", Unit::mountSerializer, XMLType( XMLSupport::tostring( xml->unitscale ), (int) xml->mountz.size() ) );
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case VOLUME:
volume = XMLSupport::parse_int( (*iter).value );
break;
case XYSCALE:
xyscale = XMLSupport::parse_float( (*iter).value );
break;
case ZSCALE:
zscale = XMLSupport::parse_float( (*iter).value );
break;
case WEAPON:
filename = (*iter).value;
break;
case AMMO:
ammo = XMLSupport::parse_int( (*iter).value );
break;
case MOUNTSIZE:
tempbool = true;
mntsiz = parseMountSizes( (*iter).value.c_str() );
break;
case X:
pos.i = xml->unitscale*parse_float( (*iter).value );
break;
case Y:
pos.j = xml->unitscale*parse_float( (*iter).value );
break;
case Z:
pos.k = xml->unitscale*parse_float( (*iter).value );
break;
case RI:
R.i = parse_float( (*iter).value );
break;
case RJ:
R.j = parse_float( (*iter).value );
break;
case RK:
R.k = parse_float( (*iter).value );
break;
case QI:
Q.i = parse_float( (*iter).value );
break;
case QJ:
Q.j = parse_float( (*iter).value );
break;
case QK:
Q.k = parse_float( (*iter).value );
break;
}
}
Q.Normalize();
if ( fabs( Q.i ) == fabs( R.i ) && fabs( Q.j ) == fabs( R.j ) && fabs( Q.k ) == fabs( R.k ) ) {
Q.i = -1;
Q.j = 0;
Q.k = 0;
}
R.Normalize();
CrossProduct( Q, R, P );
CrossProduct( R, P, Q );
Q.Normalize();
//Transformation(Quaternion (from_vectors (P,Q,R),pos);
indx = xml->mountz.size();
xml->mountz.push_back( createMount( filename.c_str(), ammo, volume, xyscale, zscale, false /*no way to do banked in XML*/ ) );
xml->mountz[indx]->SetMountOrientation( Quaternion::from_vectors( P.Cast(), Q.Cast(), R.Cast() ) );
xml->mountz[indx]->SetMountPosition( pos.Cast() );
if (tempbool)
xml->mountz[indx]->size = mntsiz;
else
xml->mountz[indx]->size = xml->mountz[indx]->type->size;
setAverageGunSpeed();
break;
case SUBUNIT:
ADDTAG;
assert( xml->unitlevel == 1 );
ADDELEMNAME( "file", Unit::subunitSerializer, XMLType( (int) xml->units.size() ) );
xml->unitlevel++;
Q = QVector( 0, 1, 0 );
R = QVector( 0, 0, 1 );
pos = QVector( 0, 0, 0 );
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case XFILE:
filename = (*iter).value;
break;
case X:
ADDDEFAULT;
pos.i = xml->unitscale*parse_float( (*iter).value );
break;
case Y:
ADDDEFAULT;
pos.j = xml->unitscale*parse_float( (*iter).value );
break;
case Z:
ADDDEFAULT;
pos.k = xml->unitscale*parse_float( (*iter).value );
break;
case RI:
ADDDEFAULT;
R.i = parse_float( (*iter).value );
break;
case RJ:
ADDDEFAULT;
R.j = parse_float( (*iter).value );
break;
case RK:
ADDDEFAULT;
R.k = parse_float( (*iter).value );
break;
case QI:
ADDDEFAULT;
Q.i = parse_float( (*iter).value );
break;
case QJ:
ADDDEFAULT;
Q.j = parse_float( (*iter).value );
break;
case QK:
ADDDEFAULT;
Q.k = parse_float( (*iter).value );
break;
case RESTRICTED:
ADDDEFAULT;
fbrltb[0] = parse_float( (*iter).value ); //minimum dot turret can have with "fore" vector
break;
}
}
indx = xml->units.size();
xml->units.push_back( UnitFactory::createUnit( filename.c_str(), true, faction, xml->unitModifications, NULL ) ); //I set here the fg arg to NULL
if (xml->units.back()->name == "LOAD_FAILED") {
xml->units.back()->limits.yaw = 0;
xml->units.back()->limits.pitch = 0;
xml->units.back()->limits.roll = 0;
xml->units.back()->limits.lateral = xml->units.back()->limits.retro = xml->units.back()->limits.forward =
xml->units.back()->limits.afterburn = 0.0;
}
xml->units.back()->SetRecursiveOwner( this );
xml->units[indx]->SetOrientation( Q, R );
R.Normalize();
xml->units[indx]->prev_physical_state = xml->units[indx]->curr_physical_state;
xml->units[indx]->SetPosition( pos );
xml->units[indx]->limits.structurelimits = R.Cast();
xml->units[indx]->limits.limitmin = fbrltb[0];
xml->units[indx]->name = filename;
if (xml->units[indx]->pImage->unitwriter != NULL)
xml->units[indx]->pImage->unitwriter->setName( filename );
CheckAccessory( xml->units[indx] ); //turns on the ceerazy rotation for the turret
break;
case COCKPITDAMAGE:
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case DAMAGE:
pImage->cockpit_damage[xml->damageiterator++] = parse_float( (*iter).value );
break;
}
}
break;
case NETCOM:
{
float minfreq = 0, maxfreq = 0;
bool video = false, secured = false;
string method;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case NETCOMM_MINFREQ:
minfreq = parse_float( (*iter).value );
break;
case NETCOMM_MAXFREQ:
maxfreq = parse_float( (*iter).value );
break;
case NETCOMM_SECURED:
secured = parse_bool( (*iter).value );
break;
case NETCOMM_VIDEO:
video = parse_bool( (*iter).value );
break;
case NETCOMM_CRYPTO:
method = (*iter).value;
break;
}
}
break;
}
case JUMP:
{
static float insys_jump_cost =
XMLSupport::parse_float( vs_config->getVariable( "physics", "insystem_jump_cost", ".1" ) );
bool foundinsysenergy = false;
//serialization covered in LoadXML
assert( xml->unitlevel == 1 );
xml->unitlevel++;
jump.drive = -1; //activate the jump unit
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case MISSING:
//serialization covered in LoadXML
if ( parse_bool( (*iter).value ) )
jump.drive = -2;
break;
case JUMPENERGY:
//serialization covered in LoadXML
jump.energy = parse_float( (*iter).value ); //short fix
if (!foundinsysenergy)
jump.insysenergy = jump.energy*insys_jump_cost;
break;
case INSYSENERGY:
//serialization covered in LoadXML
jump.insysenergy = parse_float( (*iter).value ); //short fix
foundinsysenergy = true;
break;
case WARPDRIVERATING:
jump.warpDriveRating = parse_float( (*iter).value );
break;
case DAMAGE:
jump.damage = float_to_int( parse_float( (*iter).value ) ); //short fix
break;
case DELAY:
//serialization covered in LoadXML
{
static int jumpdelaymult =
XMLSupport::parse_int( vs_config->getVariable( "physics", "jump_delay_multiplier", "5" ) );
jump.delay = parse_int( (*iter).value )*jumpdelaymult;
break;
}
case FUEL:
//serialization covered in LoadXML
jump.energy = -parse_float( (*iter).value ); //short fix
break;
case WORMHOLE:
//serialization covered in LoadXML
pImage->forcejump = parse_bool( (*iter).value );
if (pImage->forcejump)
jump.drive = -2;
break;
}
}
break;
}
case SOUND:
ADDTAG;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case CLOAKWAV:
ADDDEFAULT;
sound->cloak = AUDCreateSoundWAV( (*iter).value, false );
break;
case JUMPWAV:
ADDDEFAULT;
sound->jump = AUDCreateSoundWAV( (*iter).value, false );
break;
case CLOAKMP3:
ADDDEFAULT;
sound->cloak = AUDCreateSoundMP3( (*iter).value, false );
break;
case ENGINEWAV:
ADDDEFAULT;
sound->engine = AUDCreateSoundWAV( (*iter).value, true );
break;
case ENGINEMP3:
ADDDEFAULT;
sound->engine = AUDCreateSoundMP3( (*iter).value, true );
break;
case SHIELDMP3:
ADDDEFAULT;
sound->shield = AUDCreateSoundMP3( (*iter).value, false );
break;
case SHIELDWAV:
ADDDEFAULT;
sound->shield = AUDCreateSoundWAV( (*iter).value, false );
break;
case EXPLODEMP3:
ADDDEFAULT;
sound->explode = AUDCreateSoundMP3( (*iter).value, false );
break;
case EXPLODEWAV:
ADDDEFAULT;
sound->explode = AUDCreateSoundWAV( (*iter).value, false );
break;
case ARMORMP3:
ADDDEFAULT;
sound->armor = AUDCreateSoundMP3( (*iter).value, false );
break;
case ARMORWAV:
ADDDEFAULT;
sound->armor = AUDCreateSoundWAV( (*iter).value, false );
break;
case HULLWAV:
ADDDEFAULT;
sound->hull = AUDCreateSoundWAV( (*iter).value, false );
break;
case HULLMP3:
ADDDEFAULT;
sound->hull = AUDCreateSoundMP3( (*iter).value, false );
break;
}
}
if (sound->cloak == -1) {
static std::string ssound = vs_config->getVariable( "unitaudio", "cloak", "sfx43.wav" );
sound->cloak = AUDCreateSound( ssound, false );
}
if (sound->engine == -1) {
static std::string ssound = vs_config->getVariable( "unitaudio", "afterburner", "sfx10.wav" );
sound->engine = AUDCreateSound( ssound, false );
}
if (sound->shield == -1) {
static std::string ssound = vs_config->getVariable( "unitaudio", "shield", "sfx09.wav" );
sound->shield = AUDCreateSound( ssound, false );
}
if (sound->armor == -1) {
static std::string ssound = vs_config->getVariable( "unitaudio", "armor", "sfx08.wav" );
sound->armor = AUDCreateSound( ssound, false );
}
if (sound->hull == -1) {
static std::string ssound = vs_config->getVariable( "unitaudio", "armor", "sfx08.wav" );
sound->hull = AUDCreateSound( ssound, false );
}
if (sound->explode == -1) {
static std::string ssound = vs_config->getVariable( "unitaudio", "explode", "explosion.wav" );
sound->explode = AUDCreateSound( ssound, false );
}
if (sound->jump == -1) {
static std::string ssound = vs_config->getVariable( "unitaudio", "explode", "sfx43.wav" );
sound->jump = AUDCreateSound( ssound, false );
}
break;
case CLOAK:
//serialization covered elsewhere
assert( xml->unitlevel == 2 );
xml->unitlevel++;
pImage->cloakrate = (int) ( .2*(2147483647) ); //short fix
cloakmin = 1;
pImage->cloakenergy = 0;
cloaking = INT_MIN; //lowest negative number //short fix
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case MISSING:
//serialization covered in LoadXML
if ( parse_bool( (*iter).value ) )
cloaking = -1; //short fix
break;
case CLOAKMIN:
//serialization covered in LoadXML
cloakmin = (int) ( ( (-1) > 1 )*parse_float( (*iter).value ) ); //short fix
break;
case CLOAKGLASS:
//serialization covered in LoadXML
pImage->cloakglass = parse_bool( (*iter).value );
break;
case CLOAKRATE:
//serialization covered in LoadXML
pImage->cloakrate = (int) ( (2147483647)*parse_float( (*iter).value ) ); //short fix
break;
case CLOAKENERGY:
//serialization covered in LoadXML
pImage->cloakenergy = parse_float( (*iter).value );
break;
}
}
if ( (cloakmin&0x1) && !pImage->cloakglass )
cloakmin -= 1;
if ( (cloakmin&0x1) == 0 && pImage->cloakglass )
cloakmin += 1;
break;
case ARMOR:
assert( xml->unitlevel == 2 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case FRONT:
dirfrac = ( CLAMP_UINT( parse_float( (*iter).value ) ) )/4;
armor.frontrighttop += dirfrac;
armor.frontlefttop += dirfrac;
armor.frontrightbottom += dirfrac;
armor.frontleftbottom += dirfrac;
break;
case BACK:
dirfrac = ( CLAMP_UINT( parse_float( (*iter).value ) ) )/4;
armor.backrighttop += dirfrac;
armor.backlefttop += dirfrac;
armor.backrightbottom += dirfrac;
armor.backleftbottom += dirfrac;
break;
case RIGHT:
dirfrac = ( CLAMP_UINT( parse_float( (*iter).value ) ) )/4;
armor.frontrighttop += dirfrac;
armor.backrighttop += dirfrac;
armor.frontrightbottom += dirfrac;
armor.backrightbottom += dirfrac;
break;
case LEFT:
dirfrac = ( CLAMP_UINT( parse_float( (*iter).value ) ) )/4;
armor.backlefttop += dirfrac;
armor.frontlefttop += dirfrac;
armor.backleftbottom += dirfrac;
armor.frontleftbottom += dirfrac;
break;
case FRONTRIGHTTOP:
//serialization covered in LoadXML
armor.frontrighttop = CLAMP_UINT( parse_float( (*iter).value ) ); //short fix
break;
case BACKRIGHTTOP:
//serialization covered in LoadXML
armor.backrighttop = CLAMP_UINT( parse_float( (*iter).value ) ); //short fix
break;
case FRONTLEFTTOP:
//serialization covered in LoadXML
armor.frontlefttop = CLAMP_UINT( parse_float( (*iter).value ) ); //short fix
break;
case BACKLEFTTOP:
//serialization covered in LoadXML
armor.backlefttop = CLAMP_UINT( parse_float( (*iter).value ) ); //short fix
break;
case FRONTRIGHTBOTTOM:
//serialization covered in LoadXML
armor.frontrightbottom = CLAMP_UINT( parse_float( (*iter).value ) ); //short fix
break;
case BACKRIGHTBOTTOM:
//serialization covered in LoadXML
armor.backrightbottom = CLAMP_UINT( parse_float( (*iter).value ) ); //short fix
break;
case FRONTLEFTBOTTOM:
//serialization covered in LoadXML
armor.frontleftbottom = CLAMP_UINT( parse_float( (*iter).value ) ); //short fix
break;
case BACKLEFTBOTTOM:
//serialization covered in LoadXML
armor.backleftbottom = CLAMP_UINT( parse_float( (*iter).value ) ); //short fix
break;
}
}
break;
case SHIELDS:
//serialization covered in LoadXML
assert( xml->unitlevel == 2 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case FRONT:
//serialization covered in LoadXML
fbrltb[0] = parse_float( (*iter).value );
shield.number++;
break;
case BACK:
//serialization covered in LoadXML
fbrltb[1] = parse_float( (*iter).value );
shield.number++;
break;
case LEFT:
//serialization covered in LoadXML
fbrltb[3] = parse_float( (*iter).value );
shield.number++;
break;
case RIGHT:
//serialization covered in LoadXML
fbrltb[2] = parse_float( (*iter).value );
shield.number++;
break;
case TOP:
//serialization covered in LoadXML
fbrltb[4] = parse_float( (*iter).value );
shield.number++;
break;
case BOTTOM:
//serialization covered in LoadXML
fbrltb[5] = parse_float( (*iter).value );
shield.number++;
break;
case RECHARGE:
//serialization covered in LoadXML
shield.recharge = parse_float( (*iter).value );
break;
case LEAK:
//serialization covered in LoadXML
shield.leak = parse_int( (*iter).value );
break;
}
}
switch (shield.number)
{
case 2:
shield.shield2fb.frontmax = shield.shield2fb.front = fbrltb[0]; //short fix
shield.shield2fb.backmax = shield.shield2fb.back = fbrltb[1]; //short fix
break;
case 8: //short fix
shield.shield8.frontrighttop = CLAMP_UINT( .25*fbrltb[0]+.25*fbrltb[2] ); //short fix
shield.shield8.backrighttop = CLAMP_UINT( .25*fbrltb[1]+.25*fbrltb[2] ); //short fix
shield.shield8.frontlefttop = CLAMP_UINT( .25*fbrltb[0]+.25*fbrltb[3] ); //short fix
shield.shield8.backlefttop = CLAMP_UINT( .25*fbrltb[1]+.25*fbrltb[3] ); //short fix
shield.shield8.frontrightbottom = CLAMP_UINT( .25*fbrltb[0]+.25*fbrltb[2] ); //short fix
shield.shield8.backrightbottom = CLAMP_UINT( .25*fbrltb[1]+.25*fbrltb[2] ); //short fix
shield.shield8.frontleftbottom = CLAMP_UINT( .25*fbrltb[0]+.25*fbrltb[3] ); //short fix
shield.shield8.backleftbottom = CLAMP_UINT( .25*fbrltb[1]+.25*fbrltb[3] ); //short fix
break;
case 4:
default:
shield.shield4fbrl.frontmax = shield.shield4fbrl.front = (fbrltb[0]); //short fix
shield.shield4fbrl.backmax = shield.shield4fbrl.back = (fbrltb[1]); //short fix
shield.shield4fbrl.rightmax = shield.shield4fbrl.right = (fbrltb[2]); //short fix
shield.shield4fbrl.leftmax = shield.shield4fbrl.left = fbrltb[3]; //short fix
}
break;
case HULL:
assert( xml->unitlevel == 2 );
xml->unitlevel++;
maxhull = 0;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case STRENGTH:
hull = parse_float( (*iter).value );
break;
case MAXIMUM:
maxhull = parse_float( (*iter).value );
break;
}
}
if (maxhull == 0) {
maxhull = hull;
if (maxhull == 0)
maxhull = 1;
}
break;
case STATS:
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case MASS:
Mass = parse_float( (*iter).value );
break;
case MOMENTOFINERTIA:
Momentofinertia = parse_float( (*iter).value );
break;
case FUEL:
fuel = Mass*60*getFuelConversion();
//FIXME! This is a hack until we get csv support
//FIXME FIXME FIXME got support a long time ago! --chuck_starchaser
break;
}
}
break;
case MANEUVER:
assert( xml->unitlevel == 2 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case YAW:
limits.yaw = parse_float( (*iter).value )*(VS_PI/180);
break;
case PITCH:
limits.pitch = parse_float( (*iter).value )*(VS_PI/180);
break;
case ROLL:
limits.roll = parse_float( (*iter).value )*(VS_PI/180);
break;
}
}
break;
case ENGINE:
assert( xml->unitlevel == 2 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case AACCEL:
break;
case FORWARD:
limits.forward = game_speed*game_accel*parse_float( (*iter).value );
break;
case RETRO:
limits.retro = game_speed*game_accel*parse_float( (*iter).value );
break;
case AFTERBURNER:
limits.afterburn = game_speed*game_accel*parse_float( (*iter).value );
break;
case LEFT:
limits.lateral = game_speed*game_accel*parse_float( (*iter).value );
break;
case RIGHT:
limits.lateral = game_speed*game_accel*parse_float( (*iter).value );
break;
case TOP:
limits.vertical = game_speed*game_accel*parse_float( (*iter).value );
break;
case BOTTOM:
limits.vertical = game_speed*game_accel*parse_float( (*iter).value );
break;
}
}
break;
case COMPUTER:
ADDTAG;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case MAXSPEED:
computer.max_combat_speed = game_speed*parse_float( (*iter).value );
ADDELEM( speedStarHandler, XMLType( &computer.max_combat_speed ) );
break;
case AFTERBURNER:
computer.max_combat_ab_speed = game_speed*parse_float( (*iter).value );
ADDELEM( speedStarHandler, XMLType( &computer.max_combat_ab_speed ) );
break;
case YAW:
computer.max_yaw_right = computer.max_yaw_left = parse_float( (*iter).value )*(VS_PI/180);
ADDELEM( angleStarHandler, XMLType( &computer.max_yaw_right ) );
break;
case PITCH:
computer.max_pitch_up = computer.max_pitch_down = parse_float( (*iter).value )*(VS_PI/180);
ADDELEM( angleStarHandler, XMLType( &computer.max_pitch_up ) );
break;
case ROLL:
computer.max_roll_right = computer.max_roll_left = parse_float( (*iter).value )*(VS_PI/180);
ADDELEM( angleStarHandler, XMLType( &computer.max_roll_right ) );
break;
case SLIDE_START:
computer.slide_start = parse_int( (*iter).value );
ADDELEM( ucharStarHandler, XMLType( &computer.slide_start ) );
break;
case SLIDE_END:
computer.slide_end = parse_int( (*iter).value );
ADDELEM( ucharStarHandler, XMLType( &computer.slide_end ) );
break;
}
}
pImage->unitwriter->AddTag( "Radar" );
ADDELEMNAME( "itts", boolStarHandler, XMLType( &computer.itts ) );
ADDELEMNAME( "color", charStarHandler, XMLType( &computer.radar.capability ) );
ADDELEMNAME( "mintargetsize", charStarHandler, XMLType( &computer.radar.mintargetsize ) );
ADDELEMNAME( "range", floatStarHandler, XMLType( &computer.radar.maxrange ) );
ADDELEMNAME( "maxcone", floatStarHandler, XMLType( &computer.radar.maxcone ) );
ADDELEMNAME( "TrackingCone", floatStarHandler, XMLType( &computer.radar.trackingcone ) );
ADDELEMNAME( "lockcone", floatStarHandler, XMLType( &computer.radar.lockcone ) );
pImage->unitwriter->EndTag( "Radar" );
break;
case RADAR:
//handled above
assert( xml->unitlevel == 2 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case ITTS:
computer.itts = parse_bool( (*iter).value );
break;
case MINTARGETSIZE:
computer.radar.mintargetsize = parse_float( (*iter).value );
break;
case MAXCONE:
computer.radar.maxcone = parse_float( (*iter).value );
break;
case LOCKCONE:
computer.radar.lockcone = parse_float( (*iter).value );
break;
case TRACKINGCONE:
computer.radar.trackingcone = parse_float( (*iter).value );
break;
case RANGE:
computer.radar.maxrange = parse_float( (*iter).value );
break;
case ISCOLOR:
computer.radar.capability = atoi( (*iter).value.c_str() );
if (computer.radar.capability == 0)
computer.radar.capability = parse_bool( (*iter).value );
break;
}
}
break;
case REACTOR:
assert( xml->unitlevel == 2 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case RECHARGE:
recharge = parse_float( (*iter).value );
break;
case WARPENERGY:
maxwarpenergy = ( parse_float( (*iter).value ) ); //short fix
break;
case LIMIT:
maxenergy = energy = parse_float( (*iter).value );
break;
}
}
break;
case YAW:
ADDTAG;
xml->yprrestricted += Unit::XML::YRESTR;
assert( xml->unitlevel == 2 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case MAX:
ADDDEFAULT;
xml->ymax = parse_float( (*iter).value )*(VS_PI/180);
break;
case MIN:
ADDDEFAULT;
xml->ymin = parse_float( (*iter).value )*(VS_PI/180);
break;
}
}
break;
case PITCH:
ADDTAG;
xml->yprrestricted += Unit::XML::PRESTR;
assert( xml->unitlevel == 2 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case MAX:
ADDDEFAULT;
xml->pmax = parse_float( (*iter).value )*(VS_PI/180);
break;
case MIN:
ADDDEFAULT;
xml->pmin = parse_float( (*iter).value )*(VS_PI/180);
break;
}
}
break;
case DESCRIPTION:
ADDTAG;
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case RECURSESUBUNITCOLLISION:
ADDDEFAULT;
graphicOptions.RecurseIntoSubUnitsOnCollision = XMLSupport::parse_bool( iter->value );
break;
case FACECAMERA:
ADDDEFAULT;
graphicOptions.FaceCamera = XMLSupport::parse_bool( iter->value );
break;
case COMBATROLE:
ADDDEFAULT;
xml->calculated_role = true;
this->setCombatRole( iter->value );
break;
case NUMANIMATIONSTAGES:
graphicOptions.NumAnimationPoints = XMLSupport::parse_int( iter->value );
if (graphicOptions.NumAnimationPoints > 0)
graphicOptions.Animating = 0;
break;
}
}
break;
case ROLL:
ADDTAG;
xml->yprrestricted += Unit::XML::RRESTR;
assert( xml->unitlevel == 2 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case MAX:
ADDDEFAULT;
xml->rmax = parse_float( (*iter).value )*(VS_PI/180);
break;
case MIN:
ADDDEFAULT;
xml->rmin = parse_float( (*iter).value )*(VS_PI/180);
break;
}
}
break;
case UNIT:
assert( xml->unitlevel == 0 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
default:
break;
case UNITSCALE:
xml->unitscale = parse_float( (*iter).value );
break;
case COCKPIT:
VSFileSystem::vs_fprintf( stderr, "Cockpit attrib deprecated use tag" );
break;
}
}
break;
case COCKPIT:
ADDTAG;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case XFILE:
pImage->cockpitImage = (*iter).value;
ADDELEM( stringStarHandler, XMLType( &pImage->cockpitImage ) );
break;
case X:
pImage->CockpitCenter.i = xml->unitscale*parse_float( (*iter).value );
ADDELEM( scaledFloatStarHandler, XMLType( tostring( xml->unitscale ), &pImage->CockpitCenter.i ) );
break;
case Y:
pImage->CockpitCenter.j = xml->unitscale*parse_float( (*iter).value );
ADDELEM( scaledFloatStarHandler, XMLType( tostring( xml->unitscale ), &pImage->CockpitCenter.j ) );
break;
case Z:
pImage->CockpitCenter.k = xml->unitscale*parse_float( (*iter).value );
ADDELEM( scaledFloatStarHandler, XMLType( tostring( xml->unitscale ), &pImage->CockpitCenter.k ) );
break;
}
}
break;
case DEFENSE:
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case HUDIMAGE:
if ( (*iter).value.length() ) {
pImage->pHudImage = createVSSprite( (*iter).value.c_str() );
xml->hudimage = (*iter).value;
}
break;
case EXPLOSIONANI:
if ( (*iter).value.length() ) {
pImage->explosion_type = (*iter).value;
{
cache_ani( pImage->explosion_type );
}
}
break;
case REPAIRDROID:
pImage->repair_droid = (unsigned char) parse_float( (*iter).value );
break;
case ECM:
pImage->ecm = (int) ( ( (-1) > 1 )*parse_float( (*iter).value ) ); //short fix
pImage->ecm = pImage->ecm > 0 ? -pImage->ecm : pImage->ecm;
break;
default:
break;
}
}
break;
case THRUST:
assert( xml->unitlevel == 1 );
xml->unitlevel++;
break;
case ENERGY:
assert( xml->unitlevel == 1 );
xml->unitlevel++;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( attribute_map.lookup( (*iter).name ) )
{
case AFTERBURNENERGY:
afterburnenergy = ( parse_float( (*iter).value ) ); //short fix
break;
default:
break;
}
}
break;
case RESTRICTED:
ADDTAG;
assert( xml->unitlevel == 1 );
xml->unitlevel++;
break;
case UNKNOWN:
ADDTAG;
default:
for (iter = attributes.begin(); iter != attributes.end(); iter++)
ADDDEFAULT;
xml->unitlevel++;
break;
}
}
#undef ADDELEMF
#undef ADDELEMI
#undef ADDDEFAULT
#undef ADDELEM
#undef ADDELEMNAME
#undef ADDTAG
#undef ADDTAGNAME
void Unit::endElement( const string &name )
{
using namespace UnitXML;
pImage->unitwriter->EndTag( name );
Names elem = (Names) element_map.lookup( name );
switch (elem)
{
case UNKNOWN:
xml->unitlevel--;
break;
default:
xml->unitlevel--;
break;
}
}
using namespace VSFileSystem;
void Unit::LoadXML( const char *filename, const char *modifications, string *xmlbuffer )
{}
void Unit::LoadXML( VSFileSystem::VSFile &f, const char *modifications, string *xmlbuffer )
{
shield.number = 0;
string filename( f.GetFilename() );
graphicOptions.RecurseIntoSubUnitsOnCollision = !isSubUnit();
std::string collideTreeHash = VSFileSystem::GetHashName( string( modifications )+"#"+filename );
pImage->unitwriter = new XMLSerializer( name.get().c_str(), modifications, this );
pImage->unitwriter->AddTag( "Unit" );
string *myhudim = &pImage->unitwriter->randomdata[0];
float *myscale = &pImage->unitscale;
pImage->unitwriter->AddElement( "scale", floatStarHandler, XMLType( myscale ) );
{
pImage->unitwriter->AddTag( "Jump" );
pImage->unitwriter->AddElement( "missing", lessNeg1Handler, XMLType( &jump.drive ) );
pImage->unitwriter->AddElement( "warpDriveRating", floatStarHandler, XMLType( &jump.warpDriveRating ) );
pImage->unitwriter->AddElement( "jumpenergy", floatStarHandler, XMLType( &jump.energy ) ); //short fix
pImage->unitwriter->AddElement( "insysenergy", floatStarHandler, XMLType( &jump.insysenergy ) ); //short fix
pImage->unitwriter->AddElement( "delay", delayucharStarHandler, XMLType( &jump.delay ) );
pImage->unitwriter->AddElement( "damage", ucharStarHandler, XMLType( &jump.damage ) );
pImage->unitwriter->AddElement( "wormhole", ucharStarHandler, XMLType( &pImage->forcejump ) );
pImage->unitwriter->EndTag( "Jump" );
}
{
unsigned int i;
for (i = 0; i <= (UnitImages< void >::NUMGAUGES+MAXVDUS); i++) {
pImage->unitwriter->AddTag( "CockpitDamage" );
pImage->unitwriter->AddElement( "damage", floatStarHandler, XMLType( &pImage->cockpit_damage[i] ) );
pImage->unitwriter->EndTag( "CockpitDamage" );
}
}
{
pImage->unitwriter->AddTag( "Defense" );
pImage->unitwriter->AddElement( "HudImage", stringStarHandler, XMLType( myhudim ) );
if ( pImage->explosion_type.get().length() )
pImage->unitwriter->AddElement( "ExplosionAni", stringStarHandler, XMLType( &pImage->explosion_type ) );
pImage->unitwriter->AddElement( "RepairDroid", ucharStarHandler, XMLType( &pImage->repair_droid ) );
pImage->unitwriter->AddElement( "ECM", intToFloatHandler, XMLType( &pImage->ecm ) ); //short fix
{
pImage->unitwriter->AddTag( "Cloak" );
pImage->unitwriter->AddElement( "missing", cloakHandler, XMLType( &cloaking ) );
pImage->unitwriter->AddElement( "cloakmin", intToFloatHandler, XMLType( &cloakmin ) ); //short fix
pImage->unitwriter->AddElement( "cloakglass", ucharStarHandler, XMLType( &pImage->cloakglass ) );
pImage->unitwriter->AddElement( "cloakrate", intToFloatHandler, XMLType( &pImage->cloakrate ) ); //short fix
pImage->unitwriter->AddElement( "cloakenergy", floatStarHandler, XMLType( &pImage->cloakenergy ) );
pImage->unitwriter->EndTag( "Cloak" );
}
{
pImage->unitwriter->AddTag( "Armor" );
pImage->unitwriter->AddElement( "frontrighttop", floatStarHandler, XMLType( &armor.frontrighttop ) ); //short fix
pImage->unitwriter->AddElement( "backrighttop", floatStarHandler, XMLType( &armor.backrighttop ) ); //short fix
pImage->unitwriter->AddElement( "frontlefttop", floatStarHandler, XMLType( &armor.frontlefttop ) ); //short fix
pImage->unitwriter->AddElement( "backlefttop", floatStarHandler, XMLType( &armor.backlefttop ) ); //short fix
pImage->unitwriter->AddElement( "frontrightbottom", floatStarHandler, XMLType( &armor.frontrightbottom ) ); //short fix
pImage->unitwriter->AddElement( "backrightbottom", floatStarHandler, XMLType( &armor.backrightbottom ) ); //short fix
pImage->unitwriter->AddElement( "frontleftbottom", floatStarHandler, XMLType( &armor.frontleftbottom ) ); //short fix
pImage->unitwriter->AddElement( "backleftbottom", floatStarHandler, XMLType( &armor.backleftbottom ) ); //short fix
pImage->unitwriter->EndTag( "Armor" );
}
{
pImage->unitwriter->AddTag( "Shields" );
pImage->unitwriter->AddElement( "front", shieldSerializer, XMLType( (void*) &shield ) );
pImage->unitwriter->AddElement( "recharge", floatStarHandler, XMLType( &shield.recharge ) );
pImage->unitwriter->AddElement( "leak", charStarHandler, XMLType( &shield.leak ) );
pImage->unitwriter->EndTag( "Shields" );
}
{
pImage->unitwriter->AddTag( "Hull" );
pImage->unitwriter->AddElement( "strength", floatStarHandler, XMLType( &hull ) );
pImage->unitwriter->AddElement( "maximum", floatStarHandler, XMLType( &maxhull ) );
pImage->unitwriter->EndTag( "Hull" );
}
pImage->unitwriter->EndTag( "Defense" );
}
{
pImage->unitwriter->AddTag( "Energy" );
pImage->unitwriter->AddElement( "afterburnenergy", floatStarHandler, XMLType( &afterburnenergy ) ); //short fix
pImage->unitwriter->AddTag( "Reactor" );
pImage->unitwriter->AddElement( "recharge", floatStarHandler, XMLType( &recharge ) );
pImage->unitwriter->AddElement( "limit", floatStarHandler, XMLType( &maxenergy ) );
pImage->unitwriter->AddElement( "warpenergy", floatStarHandler, XMLType( &maxwarpenergy ) ); //short fix
pImage->unitwriter->EndTag( "Reactor" );
pImage->unitwriter->EndTag( "Energy" );
}
{
pImage->unitwriter->AddTag( "Stats" );
pImage->unitwriter->AddElement( "mass", massSerializer, XMLType( &Mass ) );
pImage->unitwriter->AddElement( "momentofinertia", floatStarHandler, XMLType( &Momentofinertia ) );
pImage->unitwriter->AddElement( "fuel", floatStarHandler, XMLType( &fuel ) );
pImage->unitwriter->EndTag( "Stats" );
pImage->unitwriter->AddTag( "Thrust" );
{
pImage->unitwriter->AddTag( "Maneuver" );
pImage->unitwriter->AddElement( "yaw", angleStarHandler, XMLType( &limits.yaw ) );
pImage->unitwriter->AddElement( "pitch", angleStarHandler, XMLType( &limits.pitch ) );
pImage->unitwriter->AddElement( "roll", angleStarHandler, XMLType( &limits.roll ) );
pImage->unitwriter->EndTag( "Maneuver" );
}
{
pImage->unitwriter->AddTag( "Engine" );
pImage->unitwriter->AddElement( "forward", accelStarHandler, XMLType( &limits.forward ) );
pImage->unitwriter->AddElement( "retro", accelStarHandler, XMLType( &limits.retro ) );
pImage->unitwriter->AddElement( "left", accelStarHandler, XMLType( &limits.lateral ) );
pImage->unitwriter->AddElement( "right", accelStarHandler, XMLType( &limits.lateral ) );
pImage->unitwriter->AddElement( "top", accelStarHandler, XMLType( &limits.vertical ) );
pImage->unitwriter->AddElement( "bottom", accelStarHandler, XMLType( &limits.vertical ) );
pImage->unitwriter->AddElement( "afterburner", accelStarHandler, XMLType( &limits.afterburn ) );
pImage->unitwriter->EndTag( "Engine" );
}
pImage->unitwriter->EndTag( "Thrust" );
}
pImage->CockpitCenter.Set( 0, 0, 0 );
xml = new XML();
xml->randomstartframe = ( (float) rand() )/RAND_MAX;
xml->randomstartseconds = 0;
xml->calculated_role = false;
xml->damageiterator = 0;
xml->unitModifications = modifications;
xml->shieldmesh = NULL;
xml->rapidmesh = NULL;
xml->hasColTree = true;
xml->unitlevel = 0;
xml->unitscale = 1;
XML_Parser parser = XML_ParserCreate( NULL );
XML_SetUserData( parser, this );
XML_SetElementHandler( parser, &Unit::beginElement, &Unit::endElement );
if (xmlbuffer != NULL)
XML_Parse( parser, xmlbuffer->c_str(), xmlbuffer->length(), 1 );
else
XML_Parse( parser, ( f.ReadFull() ).c_str(), f.Size(), 1 );
XML_ParserFree( parser );
//Load meshes into subunit
pImage->unitwriter->EndTag( "Unit" );
meshdata = xml->meshes;
meshdata.push_back( NULL );
corner_min = Vector( FLT_MAX, FLT_MAX, FLT_MAX );
corner_max = Vector( -FLT_MAX, -FLT_MAX, -FLT_MAX );
warpenergy = maxwarpenergy;
*myhudim = xml->hudimage;
unsigned int a;
if ( xml->mountz.size() ) {
//DO not destroy anymore, just affect address
for (a = 0; a < xml->mountz.size(); a++)
mounts.push_back( *xml->mountz[a] );
}
unsigned char parity = 0;
for (a = 0; a < xml->mountz.size(); a++) {
static bool half_sounds = XMLSupport::parse_bool( vs_config->getVariable( "audio", "every_other_mount", "false" ) );
if (a%2 == parity) {
int b = a;
if ( a%4 == 2 && (int) a < (GetNumMounts()-1) )
if (mounts[a].type->type != weapon_info::PROJECTILE && mounts[a+1].type->type != weapon_info::PROJECTILE)
b = a+1;
mounts[b].sound = AUDCreateSound( mounts[b].type->sound, mounts[b].type->type != weapon_info::PROJECTILE );
} else if ( (!half_sounds) || mounts[a].type->type == weapon_info::PROJECTILE ) {
mounts[a].sound = AUDCreateSound( mounts[a].type->sound, mounts[a].type->type != weapon_info::PROJECTILE ); //lloping also flase in unit_customize
}
if (a > 0)
if (mounts[a].sound == mounts[a-1].sound && mounts[a].sound != -1)
printf( "error" );
}
for (a = 0; a < xml->units.size(); a++)
SubUnits.prepend( xml->units[a] );
calculate_extent( false );
pImage->unitscale = xml->unitscale;
string tmpname( filename );
vector< mesh_polygon >polies;
this->colTrees = collideTrees::Get( collideTreeHash );
if (this->colTrees)
this->colTrees->Inc();
csOPCODECollider *colShield = NULL;
if (xml->shieldmesh) {
meshdata.back() = xml->shieldmesh;
if (!this->colTrees) {
if ( meshdata.back() ) {
meshdata.back()->GetPolys( polies );
colShield = new csOPCODECollider( polies );
}
}
} else {
Mesh *tmp = NULL;
static int shieldstacks = XMLSupport::parse_int( vs_config->getVariable( "graphics", "shield_detail", "16" ) );
static std::string shieldtex = vs_config->getVariable( "graphics", "shield_texture", "shield.bmp" );
static std::string shieldtechnique = vs_config->getVariable( "graphics", "shield_technique", "" );
meshdata.back() = new SphereMesh( rSize(), shieldstacks, shieldstacks, shieldtex.c_str(), shieldtechnique, NULL, false, ONE, ONE );
tmp = meshdata.back();
}
meshdata.back()->EnableSpecialFX();
if (!this->colTrees) {
polies.clear();
if (xml->rapidmesh)
xml->rapidmesh->GetPolys( polies );
csOPCODECollider *csrc = NULL;
if (xml->hasColTree)
csrc = getCollideTree( Vector( 1, 1, 1 ),
xml->rapidmesh
? &polies : NULL );
this->colTrees = new collideTrees( collideTreeHash,
csrc,
colShield );
if (xml->rapidmesh && xml->hasColTree) //if we have a speciaal rapid mesh we need to generate things now
for (unsigned int i = 1; i < collideTreesMaxTrees; ++i)
if (!this->colTrees->rapidColliders[i]) {
unsigned int which = 1<<i;
this->colTrees->rapidColliders[i] = getCollideTree( Vector( which, which, which ),
&polies );
}
}
if (xml->rapidmesh)
delete xml->rapidmesh;
delete xml;
}
csOPCODECollider* Unit::getCollideTree( const Vector &scale, const std::vector< mesh_polygon > *pol )
{
vector< mesh_polygon >polies;
if (!pol)
for (int j = 0; j < nummesh(); j++)
meshdata[j]->GetPolys( polies );
else
polies = *pol;
if (scale.i != 1 || scale.j != 1 || scale.k != 1) {
for (vector< mesh_polygon >::iterator i = polies.begin(); i != polies.end(); ++i)
for (unsigned int j = 0; j < i->v.size(); ++j) {
i->v[j].i *= scale.i;
i->v[j].j *= scale.j;
i->v[j].k *= scale.k;
}
}
return new csOPCODECollider( polies );
}
| 39.834302 | 158 | 0.500547 | [
"mesh",
"vector"
] |
ccaa191621da793f187f5e54bfff6b557e0b2b35 | 9,397 | cpp | C++ | src/addons/sbml_sim/sbml_sim1.cpp | rheiland/pc4sbml | 9b570ebd03fc7123e5caad2bccc3fc262b0a36f7 | [
"BSD-3-Clause"
] | 2 | 2020-01-09T21:27:45.000Z | 2020-05-04T11:10:23.000Z | src/addons/sbml_sim/sbml_sim1.cpp | rheiland/pc4sbml | 9b570ebd03fc7123e5caad2bccc3fc262b0a36f7 | [
"BSD-3-Clause"
] | null | null | null | src/addons/sbml_sim/sbml_sim1.cpp | rheiland/pc4sbml | 9b570ebd03fc7123e5caad2bccc3fc262b0a36f7 | [
"BSD-3-Clause"
] | null | null | null |
#include "../../core/PhysiCell_cell.h"
#include "libsbmlsim/libsbmlsim.h"
// Model_t* my_model;
SBMLDocument_t* my_doc;
// Model my_sbml_model;
//extern "C" {
//}
//SBMLSIM_EXPORT myResult* simulateSBMLFromFile(const char* file, double sim_time, double dt, int print_interval, int print_amount, int method, int use_lazy_method) {
int read_sbml_file(const char* file)
{
// SBMLDocument_t* my_doc;
// my_sbml_model = Model();
// Model_t* m;
myResult *rtn;
unsigned int err_num;
// double atol = 0.0;
// double rtol = 0.0;
// rf. ~/dev/libsbmlsim-1.4.0/src/lib_main.c
double atol = ABSOLUTE_ERROR_TOLERANCE;
double rtol = RELATIVE_ERROR_TOLERANCE;
// double facmax = 0.0;
double facmax = DEFAULT_FACMAX;
std::cout << "------------> readSBMLFromFile\n";
my_doc = readSBMLFromFile(file); //rwh2
if (my_doc == NULL) {
// return create_myResult_with_errorCode(Unknown);
std::cout << "CRAP: got NULL in read_sbml_file\n";
return 1;
}
#ifdef get_model
my_model = SBMLDocument_getModel(my_doc); //rwh2 - needs to go into each cell
// my_sbml_model = *my_model;
std::cout << "---> sizeof(my_model) = " << sizeof(my_model) << std::endl;
std::cout << "---> sizeof(*my_model) = " << sizeof(*my_model) << std::endl<< std::endl;
std::cout << "---> my_model->getNumCompartments() = " << my_model->getNumCompartments() << std::endl;
std::cout << "---> my_model->getNumParameters() = " << my_model->getNumParameters() << std::endl;
std::cout << "---> my_model->getNumSpecies() = " << my_model->getNumSpecies() << std::endl;
// time:10 step:100 dt:0000024.
double sim_time = 10.0;
sim_time = 5.0;
double dt = 0.000024;
dt = 0.001;
int print_interval = 10;
int print_amount = 1;
int method = MTHD_RUNGE_KUTTA;
boolean use_lazy_method = false;
// ---- do the actual simulation -------------
std::cout << "---------> Yehaw: calling simulateSBMLModel\n";
rtn = simulateSBMLModel(my_model, sim_time, dt, print_interval, print_amount, method, use_lazy_method, atol, rtol, facmax);
if (rtn == NULL) {
rtn = create_myResult_with_errorCode(SimulationFailed);
std::cout << "-------> CRAP: got NULL in sbml_sim.cpp: read_sbml_file(), simulateSBMLModel\n";
// return 1;
}
else {
std::cout << "---> rtn->num_of_rows = " << rtn->num_of_rows << std::endl;
std::cout << "---> rtn->num_of_columns_sp = " << rtn->num_of_columns_sp << std::endl;
std::cout << "---> rtn->num_of_columns_param = " << rtn->num_of_columns_param << std::endl;
std::cout << "---> rtn->num_of_columns_comp = " << rtn->num_of_columns_comp << std::endl;
for (int idx=0; idx<10; idx++ )
std::cout << "---> rtn->column_name_time[ " << idx << " = " << rtn->column_name_time[idx] << std::endl;
for (int idx=0; idx<4; idx++ ) // energy, glucose, hydrogen, oxygen
std::cout << "---> rtn->column_name_sp[ " << idx << " = " << rtn->column_name_sp[idx] << std::endl;
// for (int idx=0; idx<10; idx++ )
for (int idx=0; idx<9; idx++ )
std::cout << "---> rtn->column_name_param[ " << idx << " = " << rtn->column_name_param[idx] << std::endl;
// for (int idx=0; idx<500; idx+=10 )
for (int idx=0; idx<9; idx+=1 )
std::cout << idx << " --> " << rtn->values_time[idx] << ", " << rtn->values_sp[idx] << std::endl;
// std::cout << idx << " --> " << rtn->values_time[idx] << ", " << rtn->values_sp[idx] << std::endl;
double *value_time_p = rtn->values_time;
double *value_sp_p = rtn->values_sp;
double *value_param_p = rtn->values_param;
double *value_comp_p = rtn->values_comp;
/*
if ((fp_s = my_fopen(fp_s, file_s, "w")) == NULL) {
return;
}
if ((fp_p = my_fopen(fp_p, file_p, "w")) == NULL) {
return;
}
if ((fp_c = my_fopen(fp_c, file_c, "w")) == NULL ) {
return;
}
*/
#ifdef print_species
char delimiter = ',';
/* Species */
for (int i = 0; i < rtn->num_of_rows; i++) {
// fprintf(fp_s, "%.16g", *(value_time_p));
printf( "%.16g", *(value_time_p));
value_time_p++;
for (int j = 0; j < rtn->num_of_columns_sp; j++) {
// printf(fp_s, "%c%.16g", delimiter, *(value_sp_p));
printf("%c%.16g", delimiter, *(value_sp_p));
value_sp_p++;
}
printf("\n");
}
#endif //print_species
/* Parameters */
/*
value_time_p = result->values_time;
for (i = 0; i < result->num_of_rows; i++) {
fprintf(fp_p, "%.16g", *(value_time_p));
value_time_p++;
for (j = 0; j < result->num_of_columns_param; j++) {
fprintf(fp_p, "%c%.16g", delimiter, *(value_param_p));
value_param_p++;
}
fprintf(fp_p, "\n");
}
*/
/* Compartments */
/*
value_time_p = result->values_time;
for (i = 0; i < result->num_of_rows; i++) {
fprintf(fp_c, "%.16g", *(value_time_p));
value_time_p++;
for (j = 0; j < result->num_of_columns_comp; j++) {
fprintf(fp_c, "%c%.16g", delimiter, *(value_comp_p));
value_comp_p++;
}
fprintf(fp_c, "\n");
}
*/
}
#endif // get_model
// SBMLDocument_free(my_doc);
return 0;
}
void solve_sbml(PhysiCell::Cell* pCell)
{
static double sim_time = 10.0;
static double sbml_dt = 0.001; // diffusion_dt = 0.01 (default; rf. PhysiCell_constants.h)
// static double sbml_dt = 0.01; //0.001; // diffusion_dt = 0.01 (default; rf. PhysiCell_constants.h)
// static double sbml_dt = 0.1; //0.001; // diffusion_dt = 0.01 (default; rf. PhysiCell_constants.h)
static int print_interval = 10;
static int print_amount = 1;
static int method = MTHD_RUNGE_KUTTA;
static boolean use_lazy_method = false;
static double atol = 0.0;
static double rtol = 0.0;
static double facmax = 0.0;
std::vector<double> density[3];
Model_t *mm = pCell->phenotype.molecular.molecular_model;
// std::cout << " >>>> sbml_sim.cpp: mm oxygen ic="<<mm->getAttribute.getElementBySId("oxygen") << std::endl;
//initialConcentration
double oxy_val;
double new_oxy_val;
int oxygen_i = microenvironment.find_density_index( "oxygen" );
int glucose_i = microenvironment.find_density_index( "glucose" );
int vi = microenvironment.nearest_voxel_index(pCell->position);
// dv = microenv->nearest_density_vector(vi);
std::cout << " >>>> sbml_sim.cpp: vi="<< vi << std::endl;
microenvironment(vi)[oxygen_i] =
microenvironment(vi)[glucose_i] =
mm->getElementBySId("Oxygen")->getAttribute("initialConcentration", oxy_val);
new_oxy_val = oxy_val + 2.42;
mm->getElementBySId("Oxygen")->setAttribute("initialConcentration", new_oxy_val);
mm->getElementBySId("Oxygen")->getAttribute("initialConcentration", oxy_val);
std::cout << " >>>> sbml_sim.cpp: mm oxygen ic="<< oxy_val << std::endl;
std::cout << " >>>> sbml_sim.cpp: t="<<PhysiCell::PhysiCell_globals.current_time << ", solve_sbml for Cell ID= " << pCell->ID << std::endl;
myResult *mm_res = simulateSBMLModel( pCell->phenotype.molecular.molecular_model, sim_time, sbml_dt, print_interval, print_amount, method, use_lazy_method, atol, rtol, facmax);
// std::cout << "solve_sbml for Cell ID= " << pCell->ID << std::endl;
std::cout << "--- num_of_rows = " << mm_res->num_of_rows << std::endl;
std::cout << "--- num_of_columns_sp = " << mm_res->num_of_columns_sp << std::endl;
// Energy_0,Glucose_0,Hydrogen_0,Oxygen_0, Energy_1, etc…
// So, to extract *just* the values of Energy, one would get every 4th value (modulo (# of species)),
// starting at the 0th (Energy) in the list.
std::cout << "values_sp = " <<mm_res->values_sp[0]<<","<<mm_res->values_sp[1]<<","<<mm_res->values_sp[2]<<","<<mm_res->values_sp[3]<<","<<mm_res->values_sp[4]<<","<<mm_res->values_sp[5]<<"," <<std::endl;
// int idx_species = 0; // Energy
// int idx_species = 1; // Glucose
// int idx_species = 2; // Hydrogen
int idx_species = 3; // Oxygen
float tmax = 598.;
tmax = 0.;
std::cout << "PhysiCell::PhysiCell_globals.current_time = " <<PhysiCell::PhysiCell_globals.current_time<<std::endl;
if (PhysiCell::PhysiCell_globals.current_time > tmax) //rwh: let's only write results at the end
{
std::ofstream myfile;
std::string fname = "species.csv";
// myfile.open ("species.csv");
myfile.open (fname);
std::cout << "----------- " << __FILE__ << ":" <<__FUNCTION__ <<": selected species in " << fname << std::endl;
for (int idx=0; idx<=mm_res->num_of_rows-1; idx++ ) {
// std::cout << mm_res->values_sp[idx]<<", ";
// myfile << "Writing this to a file.\n";
// std::cout << mm_res->values_time[idx]<<", "<<mm_res->values_sp[idx_species]<<std::endl;
myfile << mm_res->values_time[idx]<<", "<<mm_res->values_sp[idx_species]<<std::endl;
idx_species += mm_res->num_of_columns_sp; // increment to get next value for this species
}
std::cout << std::endl;
myfile.close ();
}
// include/libsbmlsim/myResult.h
// typedef struct myResult{
// LibsbmlsimErrorCode error_code;
// const char *error_message;
// int num_of_rows;
// int num_of_columns_sp;
// int num_of_columns_param;
// int num_of_columns_comp;
// const char *column_name_time;
// const char **column_name_sp;
// const char **column_name_param;
// const char **column_name_comp;
// double *values_time;
// double *values_sp;
// double *values_param;
// double *values_comp;
// /* new code*/
// double* values_time_fordelay;
// int num_of_delay_rows;
// } myResult;
} | 38.044534 | 205 | 0.628286 | [
"vector",
"model"
] |
ccb6d061cee868eeab48f32e13a9c157f19e9698 | 2,885 | hpp | C++ | include/slam_handle.hpp | atharva-18/landmark-slam-2d | b3f0cc16fb3361311acb64f48035c7d2930fadb3 | [
"Apache-2.0"
] | 3 | 2021-11-14T08:11:29.000Z | 2022-02-23T07:00:32.000Z | include/slam_handle.hpp | atharva-18/landmark-slam-2d | b3f0cc16fb3361311acb64f48035c7d2930fadb3 | [
"Apache-2.0"
] | null | null | null | include/slam_handle.hpp | atharva-18/landmark-slam-2d | b3f0cc16fb3361311acb64f48035c7d2930fadb3 | [
"Apache-2.0"
] | 1 | 2021-11-19T06:20:31.000Z | 2021-11-19T06:20:31.000Z | /*
* Copyright (C) 2021 Atharva Pusalkar
*
* 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 LANDMARK_SLAM_2D_SLAM_HANDLE_HPP
#define LANDMARK_SLAM_2D_SLAM_HANDLE_HPP
#include <deque>
#include <string>
#include <vector>
#include <eigen3/Eigen/Core>
#include "geometry_msgs/msg/polygon.hpp"
#include <geometry_msgs/msg/pose2_d.h>
#include <geometry_msgs/msg/twist.h>
#include <rclcpp/rclcpp.hpp>
#include <visualization_msgs/msg/marker.hpp>
#include <visualization_msgs/msg/marker_array.hpp>
#include "slam.hpp"
namespace ns_slam {
class Command {
public:
double vx, vy, dtheta;
};
class SlamHandle : public rclcpp::Node
{
public:
// Constructor
SlamHandle();
// Getters
int getNodeRate() const;
// Methods
void loadParameters();
void subscribeToTopics();
void publishToTopics();
void sendMap();
void sendState();
void sendVisualization();
private:
rclcpp::Subscription<geometry_msgs::msg::Polygon>::SharedPtr landmarkDetectionsSubscriber_;
rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr stateEstimateSubscriber_;
rclcpp::Publisher<geometry_msgs::msg::Polygon>::SharedPtr slamMapPublisher_;
rclcpp::Publisher<visualization_msgs::msg::MarkerArray>::SharedPtr slamMapRvizPublisher_;
rclcpp::Publisher<geometry_msgs::msg::Pose2D>::SharedPtr slamStatePublisher_;
void landmarkDetectionsCallback(const geometry_msgs::msg::Polygon::SharedPtr landmarks);
void stateEstimateCallback(const geometry_msgs::msg::Twist::SharedPtr state_estimate);
std::string state_estimation_topic_name_;
std::string landmark_detections_topic_name_;
std::string slam_map_topic_name_;
std::string slam_map_rviz_topic_name_;
std::string slam_pose_topic_name_;
int node_rate_;
Slam slam_;
std::vector<geometry_msgs::msg::Point32> landmarks_;
std::vector<geometry_msgs::msg::Point32> received_landmarks_;
std::vector<geometry_msgs::msg::Point32> corrected_landmarks_;
geometry_msgs::msg::Twist state_estimate_;
geometry_msgs::msg::Polygon slam_map_;
geometry_msgs::msg::Pose2D slam_state_;
double previous_time_stamp_ = 0.0;
double current_time_stamp_;
int n_particles_;
Eigen::Vector3d z;
Eigen::Matrix3d R;
Eigen::Vector2d p;
std::deque<Command> us;
double vx_ = 0;
double vy_ = 0;
double theta_dt_ = 0;
double steps_ = 0;
};
}
#endif //ESTIMATION_SLAM_SLAM_HANDLE_HPP
| 27.740385 | 93 | 0.761872 | [
"vector"
] |
ccbfba69953d832e7edd2f8863fe531c91ff0991 | 4,894 | cpp | C++ | tggd_alakajam13/Application.Starters.cpp | playdeezgames/tggd_alakajam13 | e4433a14d4e74cc4f711c7bb6610c87e2fd9b377 | [
"MIT"
] | null | null | null | tggd_alakajam13/Application.Starters.cpp | playdeezgames/tggd_alakajam13 | e4433a14d4e74cc4f711c7bb6610c87e2fd9b377 | [
"MIT"
] | null | null | null | tggd_alakajam13/Application.Starters.cpp | playdeezgames/tggd_alakajam13 | e4433a14d4e74cc4f711c7bb6610c87e2fd9b377 | [
"MIT"
] | null | null | null | #include <Application.Keyboard.h>
#include <Application.Options.h>
#include <Application.UIState.h>
#include <Audio.Mux.h>
#include <Audio.Sfx.h>
#include <Data.JSON.Store.h>
#include <Data.JSON.Stores.h>
#include <Data.SQLite.Store.h>
#include <Data.SQLite.Stores.h>
#include <functional>
#include <Game.h>
#include <States.h>
#include <Sublayouts.h>
#include <UIState.h>
#include <vector>
#include <Visuals.Colors.h>
#include <Visuals.Confirmations.h>
#include <Visuals.Fonts.h>
#include <Visuals.Layouts.h>
#include <Visuals.Messages.h>
#include <Visuals.Sprites.h>
#include <Visuals.Textures.h>
namespace application
{
static const std::string FILE_CONFIG_COLORS = "config/graphics/colors.json";
static const std::string FILE_CONFIG_SFX = "config/audio/sfx.json";
static const std::string FILE_CONFIG_MUX = "config/audio/mux.json";
static const std::string FILE_CONFIG_TEXTURES = "config/graphics/textures.json";
static const std::string FILE_CONFIG_SPRITES = "config/graphics/sprites.json";
static const std::string FILE_CONFIG_FONTS = "config/graphics/fonts.json";
static const std::string FILE_CONFIG_LAYOUTS = "config/ui/layouts.json";
static const std::string FILE_CONFIG_KEYBOARD = "config/keyboard.json";
static const std::string FILE_CONFIG_OPTIONS = "config/options.json";
static const std::string FILE_CONFIG_TIPS = "config/tips.json";
static const std::string VISUAL_TYPE_WORLD_MAP = "WorldMap";
static const std::string VISUAL_TYPE_NAVIGATOR = "Navigator";
static const std::string VISUAL_TYPE_FISHBOARD = "Fishboard";
static const std::string CONNECTION_MEMORY = ":memory:";
static const std::string CONNECTION_AUTOSAVE = "autosave.db";
static const std::string CONNECTION_SLOT_1 = "slot1.db";
static const std::string CONNECTION_SLOT_2 = "slot2.db";
static const std::string CONNECTION_SLOT_3 = "slot3.db";
static const std::string CONNECTION_SLOT_4 = "slot4.db";
static const std::string CONNECTION_SLOT_5 = "slot5.db";
std::vector<std::function<void()>> starters =
{
application::UIState::DoSetFinalState(::UIState::QUIT),
data::json::Stores::DoSetStoreFile(data::json::Store::COLORS, FILE_CONFIG_COLORS,std::nullopt),
data::json::Stores::DoSetStoreFile(data::json::Store::SOUND_EFFECTS, FILE_CONFIG_SFX,std::nullopt),
data::json::Stores::DoSetStoreFile(data::json::Store::MUSIC_THEMES, FILE_CONFIG_MUX,std::nullopt),
data::json::Stores::DoSetStoreFile(data::json::Store::TEXTURES, FILE_CONFIG_TEXTURES,std::nullopt),
data::json::Stores::DoSetStoreFile(data::json::Store::SPRITES, FILE_CONFIG_SPRITES,std::nullopt),
data::json::Stores::DoSetStoreFile(data::json::Store::FONTS, FILE_CONFIG_FONTS,std::nullopt),
data::json::Stores::DoSetStoreFile(data::json::Store::LAYOUTS, FILE_CONFIG_LAYOUTS,std::nullopt),
data::json::Stores::DoSetStoreFile(data::json::Store::KEYS, FILE_CONFIG_KEYBOARD,std::nullopt),
data::json::Stores::DoSetStoreFile(data::json::Store::OPTIONS, FILE_CONFIG_OPTIONS,std::nullopt),
data::json::Stores::DoSetStoreFile(data::json::Store::TIPS, FILE_CONFIG_TIPS,std::nullopt),
visuals::Colors::DoSetStore(data::json::Store::COLORS),
visuals::Textures::DoSetStore(data::json::Store::TEXTURES),
visuals::Sprites::DoSetStore(data::json::Store::SPRITES),
visuals::Fonts::DoSetStore(data::json::Store::FONTS),
visuals::Layouts::DoSetStore(data::json::Store::LAYOUTS),
visuals::Messages::Reset,
application::Keyboard::DoSetStore(data::json::Store::KEYS),
Options::DoSetStore(data::json::Store::OPTIONS),
visuals::Confirmations::Reset,
data::json::Stores::Start,
data::sqlite::Stores::DoSetConnection(data::sqlite::Store::IN_MEMORY, CONNECTION_MEMORY),
data::sqlite::Stores::DoSetConnection(data::sqlite::Store::AUTOSAVE, CONNECTION_AUTOSAVE),
data::sqlite::Stores::DoSetConnection(data::sqlite::Store::SLOT_1, CONNECTION_SLOT_1),
data::sqlite::Stores::DoSetConnection(data::sqlite::Store::SLOT_2, CONNECTION_SLOT_2),
data::sqlite::Stores::DoSetConnection(data::sqlite::Store::SLOT_3, CONNECTION_SLOT_3),
data::sqlite::Stores::DoSetConnection(data::sqlite::Store::SLOT_4, CONNECTION_SLOT_4),
data::sqlite::Stores::DoSetConnection(data::sqlite::Store::SLOT_5, CONNECTION_SLOT_5),
audio::Mux::DoSetStore(data::json::Store::MUSIC_THEMES),
audio::Sfx::DoSetStore(data::json::Store::SOUND_EFFECTS),
state::Splash::Start,
state::Tip::Start,
state::MainMenu::Start,
state::About::Start,
state::ConfirmQuit::Start,
state::Options::Start,
state::StartGame::Start,
state::LeavePlay::Start,
state::GameOver::Start,
state::in_play::Board::Start,
state::in_play::Next::Start,
game::DoAddResetter(visuals::Confirmations::Reset),
game::DoAddResetter(visuals::Messages::Reset),
game::Start,
sublayout::UIHamburger::Start,
Options::Initialize,
visuals::Layouts::Start
};
const std::vector<std::function<void()>>& Engine::GetStarters()
{
return starters;
}
} | 48.455446 | 101 | 0.755006 | [
"vector"
] |
ccc1f817638e6405334d5e603f249f8a11821cb4 | 142,319 | cpp | C++ | MemoryStringPool.cpp | Kochise/SigEngine | 0b533b99bf90d65ad1f44a34f77c161c1d0fa623 | [
"MIT"
] | null | null | null | MemoryStringPool.cpp | Kochise/SigEngine | 0b533b99bf90d65ad1f44a34f77c161c1d0fa623 | [
"MIT"
] | null | null | null | MemoryStringPool.cpp | Kochise/SigEngine | 0b533b99bf90d65ad1f44a34f77c161c1d0fa623 | [
"MIT"
] | 1 | 2020-09-26T09:46:48.000Z | 2020-09-26T09:46:48.000Z | // MemoryStringPool.cpp: implementation of the CMemoryStringPool class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Memory.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
// === CLASSE DE CHAINE AUTO-DIMENSIONNABLE ===========================================================================
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
CMemoryStringPool::CMemoryStringPool
( const char* i_panStringName // = "CMemoryStringPool"
)
{
#ifdef _DEBUG
SetClassName(i_panStringName); // Default object name
_SetClassType("CMemoryStringPool");
mp_oTreeString.SetClassName(mp_oStrObjectName+"::mp_oTreeString");
#endif // _DEBUG
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
CMemoryStringPool::~CMemoryStringPool()
{
#ifdef _DEBUG
TRACE
( "%s::~%s : %d/%d (%d%%) unused bytes left (%d/%d string%s free)\n"
, (CString) mp_oStrObjectName
, (CString) mp_oStrObjectClass
, GetBufferFree()
, GetBufferSize()
, (int) (((LONGLONG) GetBufferFree() * 100) / GetBufferSize())
, mp_oTreeString.GetSlotFree()
, mp_oTreeString.GetSlotTotal()
, (mp_oTreeString.GetSlotFree() > 1) ? "s" : ""
);
#endif // _DEBUG
_DeleteBuffer();
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::CreateBuffer
( int i_nBufferSize
, BOOL i_bZeroMemory
)
{
if(i_nBufferSize <= 0)
{ // Test slot size
#ifdef _DEBUG
TRACE
( "ERROR : %s::CreateBuffer(i_nBufferSize <= 0) = Wrong buffer size\n"
, (CString) mp_oStrObjectName
);
// ASSERT(!(i_nBufferSize <= 0));
#endif // _DEBUG
return (-1);
}
else
{ // Everything OK
mp_bZeroMemory = i_bZeroMemory;
// Delete the previous buffers
_DeleteBuffer();
// Create string descriptor tree
if((i_nBufferSize >> 6) == 0)
{
mp_oTreeString.CreateBuffer
( sizeof(sMSP)
, 8 // 8 strings
);
}
else
{
mp_oTreeString.CreateBuffer
( sizeof(sMSP)
, i_nBufferSize >> 6 // Average of 64 bytes per string
);
}
sMBP l_sTempoMBP;
// Create the new buffer
l_sTempoMBP.nBufferSize = ALIGN(i_nBufferSize); // 8 bytes boundary, helps 64 bits CPU
l_sTempoMBP.panBuffer = new char[l_sTempoMBP.nBufferSize + sizeof(sMBP)] + sizeof(sMBP);
l_sTempoMBP.panBufferPrev = NULL;
l_sTempoMBP.panBufferNext = NULL;
l_sTempoMBP.nBufferBegin = 0;
l_sTempoMBP.nBufferHead = 0;
l_sTempoMBP.nBufferTail = 0;
l_sTempoMBP.nBufferEnd = l_sTempoMBP.nBufferSize;
// Zero memory if needed
if(mp_bZeroMemory == TRUE)
{
ZeroMemory
( l_sTempoMBP.panBuffer
, l_sTempoMBP.nBufferSize
);
}
else{}
// Copy sMBP chunk at the beginning of the buffer
mp_psBufferFirst = (sMBP*) l_sTempoMBP.panBuffer - 1;
*(mp_psBufferFirst) = l_sTempoMBP;
// Double linked buffers
mp_psBufferTail = mp_psBufferFirst;
mp_psBufferPrev = mp_psBufferFirst;
#ifdef _DEBUG
TRACE
( "%s::CreateBuffer(BufferSize = %d, ZeroMemory = %s)\n"
, (CString) mp_oStrObjectName
, i_nBufferSize
, (mp_bZeroMemory == TRUE) ? "YES" : "NO"
);
#endif // _DEBUG
return true;
}
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::AddStringHead
( const char* i_panStringBuffer
, bool i_bForce // = false
)
{
sMSP l_sStringPointer = {0, 0, 0, 0};
_EncodeString(l_sStringPointer, i_panStringBuffer);
#ifndef TEST_NEWMETHOD
int l_nStringIndex = mp_oTreeString.GetNodeIndex(l_sStringPointer.nHashNoCase);
#else // TEST_NEWMETHOD
int l_nStringIndex = mp_oTreeString.GetNodeIndexCRC(&l_sStringPointer);
int l_nStringLocation;
#endif // TEST_NEWMETHOD
int l_nStringSize;
int l_nStringHole;
if
(
(l_nStringIndex != -1)
&& (i_bForce == false)
)
{ // The string is already in the buffer
mp_oTreeString.SetNodeCount(l_nStringIndex, mp_oTreeString.GetNodeCount(l_nStringIndex) + 1);
}
else
{ // Get string size
#ifndef TEST_NEWMETHOD
l_nStringSize = GetStringLength(i_panStringBuffer);
#else // TEST_NEWMETHOD
l_nStringSize = l_sStringPointer.nLength;
#endif // TEST_NEWMETHOD
l_nStringHole = ALIGN(l_nStringSize);
// Stack the string in the buffer
#ifndef TEST_NEWMETHOD
l_sStringPointer.nLocation = _StreamString(i_panStringBuffer, l_nStringHole, l_nStringSize);
#else // TEST_NEWMETHOD
l_nStringLocation = _StreamString(i_panStringBuffer, l_nStringHole, l_nStringSize);
#endif // TEST_NEWMETHOD
// Add the string descriptor in the tree
l_nStringIndex = mp_oTreeString.AddSlotHead((BYTE*) &l_sStringPointer);
// Set string properties
mp_oTreeString.SetNodeSize(l_nStringIndex, l_nStringSize);
mp_oTreeString.SetNodeHole(l_nStringIndex, l_nStringHole);
mp_oTreeString.SetNodeCount(l_nStringIndex, 1);
#ifndef TEST_NEWMETHOD
#else // TEST_NEWMETHOD
mp_oTreeString.SetNodeData(l_nStringIndex, l_nStringLocation);
#endif // TEST_NEWMETHOD
}
return l_nStringIndex;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::AddStringTail
( const char* i_panStringBuffer
, bool i_bForce // = false
)
{
sMSP l_sStringPointer = {0, 0, 0, 0};
sMSP* l_psMSP;
int l_nStringIndex = -1;
int l_nStringSize;
int l_nStringHole;
#ifndef TEST_NEWMETHOD
#else // TEST_NEWMETHOD
int l_nStringLocation;
#endif // TEST_NEWMETHOD
if(i_panStringBuffer != NULL)
{
if(*i_panStringBuffer != 0)
{
_EncodeString(l_sStringPointer, i_panStringBuffer);
#ifndef TEST_NEWMETHOD
l_nStringIndex = mp_oTreeString.GetNodeIndex(l_sStringPointer.nHashNoCase);
#else // TEST_NEWMETHOD
l_nStringIndex = mp_oTreeString.GetNodeIndexCRC(&l_sStringPointer);
#endif // TEST_NEWMETHOD
if
(
(l_nStringIndex != -1)
&& (i_bForce == false)
)
{ // The string is already in the buffer
mp_oTreeString.SetNodeCount(l_nStringIndex, mp_oTreeString.GetNodeCount(l_nStringIndex) + 1);
}
else
{ // Get string size
#ifndef TEST_NEWMETHOD
l_nStringSize = GetStringLength(i_panStringBuffer);
#else // TEST_NEWMETHOD
l_nStringSize = l_sStringPointer.nLength;
#endif // TEST_NEWMETHOD
l_nStringHole = ALIGN(l_nStringSize);
// Stack the string in the buffer
#ifndef TEST_NEWMETHOD
l_sStringPointer.nLocation = _StreamString(i_panStringBuffer, l_nStringHole, l_nStringSize);
#else // TEST_NEWMETHOD
l_nStringLocation = _StreamString(i_panStringBuffer, l_nStringHole, l_nStringSize);
#endif // TEST_NEWMETHOD
// Add the string descriptor in the tree
l_nStringIndex = mp_oTreeString.AddSlotTail((BYTE*) &l_sStringPointer);
// Set string properties
mp_oTreeString.SetNodeSize(l_nStringIndex, l_nStringSize);
mp_oTreeString.SetNodeHole(l_nStringIndex, l_nStringHole);
mp_oTreeString.SetNodeCount(l_nStringIndex, 1);
#ifndef TEST_NEWMETHOD
#else // TEST_NEWMETHOD
mp_oTreeString.SetNodeData(l_nStringIndex, l_nStringLocation);
#endif // TEST_NEWMETHOD
}
}
else
{ // Queue empty string
l_psMSP = (sMSP*) mp_oTreeString.GetSlotPointer(0);
if(l_psMSP != NULL)
{ // Try to get the first NULL char to stuff an empty string
#ifndef TEST_NEWMETHOD
l_sStringPointer.nLocation = mp_oTreeString.GetNodeSize(0) + 1;
#else // TEST_NEWMETHOD
l_sStringPointer.nLength = 0;
l_nStringLocation = mp_oTreeString.GetNodeSize(0) + 1;
#endif // TEST_NEWMETHOD
}
else{}
l_nStringIndex = mp_oTreeString.AddSlotTail((BYTE*) &l_sStringPointer);
// Set string properties
mp_oTreeString.SetNodeSize(l_nStringIndex, 0);
mp_oTreeString.SetNodeHole(l_nStringIndex, 0);
mp_oTreeString.SetNodeCount(l_nStringIndex, 1);
#ifndef TEST_NEWMETHOD
#else // TEST_NEWMETHOD
mp_oTreeString.SetNodeData(l_nStringIndex, l_nStringLocation);
#endif // TEST_NEWMETHOD
}
}
else{}
return l_nStringIndex;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
void CMemoryStringPool::operator +=
( const char* i_panStringBuffer
)
{
AddStringTail(i_panStringBuffer);
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::InsertStringAt
( const char* i_panStringBuffer
, int i_nStringIndex
)
{
sMSP l_sStringPointer = {0, 0, 0, 0};
_EncodeString(l_sStringPointer, i_panStringBuffer);
#ifndef TEST_NEWMETHOD
int l_nStringIndex = mp_oTreeString.GetNodeIndex(l_sStringPointer.nHashNoCase);
#else // TEST_NEWMETHOD
int l_nStringIndex = mp_oTreeString.GetNodeIndexCRC(&l_sStringPointer);
int l_nStringLocation;
#endif // TEST_NEWMETHOD
int l_nStringSize;
int l_nStringHole;
if(l_nStringIndex != -1)
{ // The string is already in the buffer
mp_oTreeString.SetNodeCount(l_nStringIndex, mp_oTreeString.GetNodeCount(l_nStringIndex) + 1);
}
else
{ // Get string size
#ifndef TEST_NEWMETHOD
l_nStringSize = GetStringLength(i_panStringBuffer);
#else // TEST_NEWMETHOD
l_nStringSize = l_sStringPointer.nLength;
#endif // TEST_NEWMETHOD
l_nStringHole = ALIGN(l_nStringSize);
// Stack the string in the buffer
#ifndef TEST_NEWMETHOD
l_sStringPointer.nLocation = _StreamString(i_panStringBuffer, l_nStringHole, l_nStringSize);
#else // TEST_NEWMETHOD
l_nStringLocation = _StreamString(i_panStringBuffer, l_nStringHole, l_nStringSize);
#endif // TEST_NEWMETHOD
// Add the string descriptor in the tree
l_nStringIndex = mp_oTreeString.InsertSlotAt((BYTE*) &l_sStringPointer, i_nStringIndex);
// Set string properties
mp_oTreeString.SetNodeSize(l_nStringIndex, l_nStringSize);
mp_oTreeString.SetNodeHole(l_nStringIndex, l_nStringHole);
mp_oTreeString.SetNodeCount(l_nStringIndex, 1);
#ifndef TEST_NEWMETHOD
#else // TEST_NEWMETHOD
mp_oTreeString.SetNodeData(l_nStringIndex, l_nStringLocation);
#endif // TEST_NEWMETHOD
}
return l_nStringIndex;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::InsertStringAfter
( const char* i_panStringBuffer
, int i_nStringIndex
)
{
return InsertStringAt(i_panStringBuffer, i_nStringIndex + 1);
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::InsertStringDicho
( const char* i_panStringBuffer
, int i_nByteToCompare // = 4
, BOOL i_bBigEndian // = FALSE
)
{
sMSP l_sStringPointer = {0, 0, 0, 0};
_EncodeString(l_sStringPointer, i_panStringBuffer);
#ifndef TEST_NEWMETHOD
int l_nStringIndex = mp_oTreeString.GetNodeIndex(l_sStringPointer.nHashNoCase);
#else // TEST_NEWMETHOD
int l_nStringIndex = mp_oTreeString.GetNodeIndexCRC(&l_sStringPointer);
int l_nStringLocation;
#endif // TEST_NEWMETHOD
int l_nStringSize;
int l_nStringHole;
if(l_nStringIndex != -1)
{ // The string is already in the buffer
mp_oTreeString.SetNodeCount(l_nStringIndex, mp_oTreeString.GetNodeCount(l_nStringIndex) + 1);
}
else
{ // Get string size
#ifndef TEST_NEWMETHOD
l_nStringSize = GetStringLength(i_panStringBuffer);
#else // TEST_NEWMETHOD
l_nStringSize = l_sStringPointer.nLength;
#endif // TEST_NEWMETHOD
l_nStringHole = ALIGN(l_nStringSize);
// Stack the string in the buffer
#ifndef TEST_NEWMETHOD
l_sStringPointer.nLocation = _StreamString(i_panStringBuffer, l_nStringHole, l_nStringSize);
#else // TEST_NEWMETHOD
l_nStringLocation = _StreamString(i_panStringBuffer, l_nStringHole, l_nStringSize);
#endif // TEST_NEWMETHOD
// Add the string descriptor in the tree
l_nStringIndex = mp_oTreeString.InsertSlotDicho((BYTE*) &l_sStringPointer);
// Set string properties
mp_oTreeString.SetNodeSize(l_nStringIndex, l_nStringSize);
mp_oTreeString.SetNodeHole(l_nStringIndex, l_nStringHole);
mp_oTreeString.SetNodeCount(l_nStringIndex, 1);
#ifndef TEST_NEWMETHOD
#else // TEST_NEWMETHOD
mp_oTreeString.SetNodeData(l_nStringIndex, l_nStringLocation);
#endif // TEST_NEWMETHOD
}
return l_nStringIndex;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
void CMemoryStringPool::RemoveStringAll
( void
)
{
mp_psBufferFirst->nBufferBegin = 0;
mp_psBufferFirst->nBufferHead = 0;
mp_psBufferFirst->nBufferTail = 0;
// Double linked buffers
mp_psBufferTail = mp_psBufferFirst;
mp_psBufferPrev = mp_psBufferFirst;
// Free all string locators
mp_oTreeString.RemoveNodeAll(); // RemoveSlotAll
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::RemoveStringHead
( void
)
{
return mp_oTreeString.RemoveSlotHead();
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::RemoveStringTail
( void
)
{
return mp_oTreeString.RemoveSlotTail();
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::RemoveStringAt
( int i_nStringIndex
)
{
return mp_oTreeString.RemoveSlotAt(i_nStringIndex);
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::RemoveStringAfter
( int i_nStringIndex
)
{
return mp_oTreeString.RemoveSlotAfter(i_nStringIndex);
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
void CMemoryStringPool::operator -=
( int i_nStringIndex
)
{
RemoveStringAt(i_nStringIndex);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::Push
( const char* i_panStringBuffer
)
{
return AddStringTail(i_panStringBuffer);
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::Push
( void
)
{
return mp_oTreeString.Push();
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::Pop
( char* o_panStringBuffer
)
{
return GetStringBuffer(o_panStringBuffer, mp_oTreeString.Pop(NULL));
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
char* CMemoryStringPool::Pop
( void
)
{
return _LocateString(mp_oTreeString.Pop(NULL));
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringLength
( const char* i_panStringBuffer
)
{
int l_nStringLength = 1; // + Null char
while(*i_panStringBuffer != 0)
{
i_panStringBuffer += 1;
l_nStringLength += 1;
}
return l_nStringLength;
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringLength
( int i_nStringIndex
)
{
return mp_oTreeString.GetNodeSize(i_nStringIndex);
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringIndex
( const char* i_panStringBuffer
, int i_nStringLenght // = -1
)
{
sMSP l_sStringPointer = {0, 0, 0, 0};
_EncodeString(l_sStringPointer, i_panStringBuffer, i_nStringLenght);
#ifndef TEST_NEWMETHOD
return mp_oTreeString.GetNodeIndex(l_sStringPointer.nHashNoCase);
#else // TEST_NEWMETHOD
return mp_oTreeString.GetNodeIndexCRC(&l_sStringPointer);
#endif // TEST_NEWMETHOD
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringCompare
( const char* i_panStringFrom
, const char* i_panStringTo
)
{
while
(
(*i_panStringFrom != 0)
&& (*i_panStringTo != 0)
&& (*i_panStringFrom != *i_panStringTo)
)
{
i_panStringFrom += 1;
i_panStringTo += 1;
}
return *i_panStringFrom - *i_panStringTo;
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringDiff
( const char* i_panStringFrom
, const char* i_panStringTo
)
{
int l_nIndex = 0;
while
(
(*i_panStringFrom != 0)
&& (*i_panStringTo != 0)
&& (*i_panStringFrom != *i_panStringTo)
)
{
i_panStringFrom += 1;
i_panStringTo += 1;
l_nIndex += 1;
}
return l_nIndex;
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringCount
( int i_nStringIndex
)
{
return mp_oTreeString.GetNodeCount(i_nStringIndex);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
void CMemoryStringPool::SetStringCount
( int i_nStringIndex
, unsigned int i_nStringCount
)
{
mp_oTreeString.SetNodeCount(i_nStringIndex, i_nStringCount);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::IncStringCount
( int i_nStringIndex
)
{
return mp_oTreeString.IncNodeCount(i_nStringIndex);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::DecStringCount
( int i_nStringIndex
)
{
return mp_oTreeString.DecNodeCount(i_nStringIndex);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringData
( int i_nStringIndex
)
{
return mp_oTreeString.GetNodeData(i_nStringIndex);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
void CMemoryStringPool::SetStringData
( int i_nStringIndex
, int i_nStringData
)
{
mp_oTreeString.SetNodeData(i_nStringIndex, i_nStringData);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringHole
( int i_nStringIndex
)
{
return mp_oTreeString.GetNodeHole(i_nStringIndex);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringSize
( int i_nStringIndex
)
{
return mp_oTreeString.GetNodeCount(i_nStringIndex);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringBuffer
( char* o_panStringBuffer
, int i_nStringIndex
)
{
char* l_panString = _LocateString(i_nStringIndex);
int l_nStringLenght;
if(l_panString != NULL)
{
l_nStringLenght = mp_oTreeString.GetNodeSize(i_nStringIndex);
#ifdef USEMEMCPY
MEMCPY
#else
memcpy
#endif // USEMEMCPY
( o_panStringBuffer
, l_panString
, l_nStringLenght
);
return l_nStringLenght;
}
else
{
return 0;
}
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::SetStringBuffer
( const char* i_panStringBuffer
, int i_nStringIndex
)
{
int l_nStringLenght = GetStringLength(i_panStringBuffer);
int l_nStringHole = mp_oTreeString.GetNodeHole(i_nStringIndex);
if(l_nStringLenght > l_nStringHole)
{
l_nStringLenght = l_nStringHole;
}
else{}
#ifdef USEMEMCPY
MEMCPY
#else
memcpy
#endif // USEMEMCPY
( _LocateString(i_nStringIndex)
, (void*) i_panStringBuffer
, l_nStringLenght
);
return l_nStringLenght;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
char* CMemoryStringPool::GetStringPointer
( int i_nStringIndex
)
{
return _LocateString(i_nStringIndex);
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
char* CMemoryStringPool::operator []
( int i_nStringIndex
)
{
return GetStringPointer(i_nStringIndex);
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
void CMemoryStringPool::Sort
( void
)
{
mp_oTreeString.SortInt();
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
void CMemoryStringPool::RemoveOnCountThreshold
( int i_nNodeCountMax
)
{
mp_oTreeString.RemoveOnCountThreshold(i_nNodeCountMax);
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetBufferSize
( void
)
{
int l_nBufferSize = 0;
// Get the right buffer
sMBP* l_psMBP = (sMBP*) mp_psBufferFirst->panBuffer;
while(l_psMBP != NULL)
{
l_psMBP -= 1;
l_nBufferSize += l_psMBP->nBufferSize;
l_psMBP = (sMBP*) l_psMBP->panBufferNext;
}
return l_nBufferSize;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetBufferFree
( void
)
{
int l_nBufferFree = 0;
// Get the right buffer
sMBP* l_psMBP = (sMBP*) mp_psBufferFirst->panBuffer;
while(l_psMBP != NULL)
{
l_psMBP -= 1;
// Get the free space at the end of each block
l_nBufferFree += l_psMBP->nBufferEnd - l_psMBP->nBufferTail;
l_psMBP = (sMBP*) l_psMBP->panBufferNext;
}
return l_nBufferFree;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringCount
( const char* i_panStringBuffer
)
{
sMSP l_sStringPointer = {0, 0, 0, 0};
_EncodeString(l_sStringPointer, i_panStringBuffer);
#ifndef TEST_NEWMETHOD
return mp_oTreeString.GetNodeCount(mp_oTreeString.GetNodeIndex(l_sStringPointer.nHashNoCase));
#else // TEST_NEWMETHOD
return mp_oTreeString.GetNodeCount(mp_oTreeString.GetNodeIndexCRC(&l_sStringPointer));
#endif // TEST_NEWMETHOD
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringTail
( void
)
{
return mp_oTreeString.GetSlotTail();
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringNumber
( void
)
{
return mp_oTreeString.GetNodeNumber();
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringSize
( void
)
{
return 8;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::GetStringFree
( void
)
{
return mp_oTreeString.GetSlotFree();
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
bool CMemoryStringPool::SaveToFile
( CFile& i_roFileOut
)
{
sMBP l_sTempoMBP;
sMBP* l_psMBP = mp_psBufferFirst;
// Tree saving first
mp_oTreeString.SaveToFile(i_roFileOut);
// Block informations
// int nBufferSize = Size of the saved buffer, length to read back
// char* panBuffer = NULL
// char* panBufferPrev = NULL
// char* panBufferNext = NULL
// int nBufferBegin = 0
// int nBufferHead = 0
// int nBufferTail = Tail location
// int nBufferEnd = Size of struct sMBP
l_sTempoMBP.nBufferSize = mp_psBufferTail->nBufferTail;
l_sTempoMBP.panBuffer = NULL;
l_sTempoMBP.panBufferPrev = NULL;
l_sTempoMBP.panBufferNext = NULL;
l_sTempoMBP.nBufferBegin = 0;
l_sTempoMBP.nBufferHead = 0;
l_sTempoMBP.nBufferTail = mp_psBufferTail->nBufferTail;
l_sTempoMBP.nBufferEnd = sizeof(sMBP);
i_roFileOut.Write
( &l_sTempoMBP
, sizeof(sMBP)
);
l_psMBP = (sMBP*) mp_psBufferFirst->panBuffer;
while(l_psMBP != NULL)
{ // Save all blocks up to the current defined tail, not further
l_psMBP -= 1;
if(l_psMBP->nBufferBegin < mp_psBufferTail->nBufferTail)
{
if(l_psMBP != mp_psBufferTail)
{ // Save the whole block
i_roFileOut.Write
( l_psMBP->panBuffer
, l_psMBP->nBufferSize
);
}
else
{ // Save up to the tail
i_roFileOut.Write
( l_psMBP->panBuffer
, l_psMBP->nBufferTail - l_psMBP->nBufferBegin
);
}
l_psMBP = (sMBP*) l_psMBP->panBufferNext;
}
else
{
l_psMBP = NULL;
}
}
return true;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
bool CMemoryStringPool::LoadFromFile
( CFile& i_roFileIn
)
{
sMBP l_sTempoMBP;
bool l_bResult = false;
if(mp_oTreeString.LoadFromFile(i_roFileIn) == true)
{
if
(
i_roFileIn.Read
( &l_sTempoMBP
, sizeof(sMBP)
)
== sizeof(sMBP)
)
{
// int nBufferSize = Size of the saved buffer, length to read back
// char* panBuffer = NULL
// char* panBufferPrev = NULL
// char* panBufferNext = NULL
// int nBufferBegin = 0
// int nBufferHead = 0
// int nBufferTail = Tail location
// int nBufferEnd = Size of struct sMBP
if(l_sTempoMBP.nBufferEnd == sizeof(sMBP))
{
if((l_sTempoMBP.panBuffer = new char[l_sTempoMBP.nBufferSize + sizeof(sMBP)]) != NULL)
{
_DeleteBuffer(); // Erase everything, we're changing of buffer
mp_psBufferFirst = (sMBP*) l_sTempoMBP.panBuffer;
// Double linked buffers
mp_psBufferTail = mp_psBufferFirst;
mp_psBufferPrev = mp_psBufferFirst;
mp_psBufferFirst->nBufferSize = l_sTempoMBP.nBufferSize;
mp_psBufferFirst->panBufferPrev = NULL;
mp_psBufferFirst->panBufferNext = NULL;
mp_psBufferFirst->nBufferBegin = 0;
mp_psBufferFirst->nBufferHead = 0;
mp_psBufferFirst->nBufferTail = l_sTempoMBP.nBufferTail;
mp_psBufferFirst->nBufferEnd = l_sTempoMBP.nBufferTail;
l_sTempoMBP.panBuffer += l_sTempoMBP.nBufferEnd; // sizeof(sMBP)
mp_psBufferFirst->panBuffer = l_sTempoMBP.panBuffer;
if
(
i_roFileIn.Read
( l_sTempoMBP.panBuffer
, l_sTempoMBP.nBufferSize
)
== l_sTempoMBP.nBufferSize
)
{
return true;
}
else{}
}
else{}
}
else{}
}
else{}
}
else{}
return l_bResult;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
void CMemoryStringPool::_DeleteBuffer
(
)
{
sMBP* l_psMBP = mp_psBufferFirst;
if(l_psMBP != NULL)
{
// Scan all blocks
while(l_psMBP->panBufferNext != NULL)
{
l_psMBP = (sMBP*) l_psMBP->panBufferNext - 1;
// Delete previous buffer, now out of scope
delete [] ((sMBP*) ((sMBP*) l_psMBP->panBufferPrev - 1)->panBuffer - 1);
}
// Delete current remaining buffer
delete [] ((sMBP*) l_psMBP->panBuffer - 1);
}
else{}
mp_psBufferFirst = NULL;
mp_psBufferTail = NULL;
mp_psBufferPrev = NULL;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
CMemoryStringPool::sMBP*
CMemoryStringPool::_ExpandBuffer
( int i_nByteReach
)
{
sMBP* l_psMBP = _LocateBuffer(i_nByteReach);
int l_nDivider = 1;
sMBP l_sTempoMBP;
// New buffer to replace to old one, thus starting from 0
l_sTempoMBP.panBufferPrev = NULL;
l_sTempoMBP.panBufferNext = NULL;
l_sTempoMBP.nBufferBegin = 0;
l_sTempoMBP.nBufferHead = 0;
l_sTempoMBP.nBufferTail = mp_psBufferTail->nBufferTail;
l_sTempoMBP.nBufferEnd = 0;
while(l_sTempoMBP.nBufferEnd < i_nByteReach)
{
l_sTempoMBP.nBufferEnd += mp_psBufferFirst->nBufferEnd;
}
l_sTempoMBP.nBufferSize = l_sTempoMBP.nBufferEnd;
// Create the new buffer
while
(
((l_sTempoMBP.panBuffer = new char[l_sTempoMBP.nBufferSize + sizeof(sMBP)]) == NULL)
&& (l_nDivider < 8)
)
{ // If buffer size is too big, try to allocate a smaller block
do
{
if(l_sTempoMBP.nBufferEnd > i_nByteReach)
{ // Reduce
l_sTempoMBP.nBufferEnd -= mp_psBufferFirst->nBufferEnd >> l_nDivider;
}
else
{ // Increase
l_sTempoMBP.nBufferEnd += mp_psBufferFirst->nBufferEnd >> l_nDivider;
}
}
while(l_sTempoMBP.nBufferEnd > i_nByteReach);
l_sTempoMBP.nBufferSize = l_sTempoMBP.nBufferEnd;
l_nDivider += 1;
}
if(l_sTempoMBP.panBuffer != NULL)
{
l_sTempoMBP.panBuffer += sizeof(sMBP);
// Zero memory if needed
if(mp_bZeroMemory == TRUE)
{
ZeroMemory
( l_sTempoMBP.panBuffer
, l_sTempoMBP.nBufferSize
);
}
else{}
// Set the new chunk
*((sMBP*) l_sTempoMBP.panBuffer - 1) = l_sTempoMBP;
#ifdef _DEBUG
TRACE
( "%s::_ExpandBuffer(%d+%d->%d slot%s) moved from [0x%08X->0x%08X[ to [0x%08X->0x%08X[ (%d bytes)\n"
, (CString) mp_oStrObjectName
, GetStringNumber()
, l_sTempoMBP.nBufferEnd - GetStringNumber()
, l_sTempoMBP.nBufferEnd
, (l_sTempoMBP.nBufferEnd > 1) ? "s" : ""
, mp_psBufferFirst->panBuffer - sizeof(sMBP)
, mp_psBufferFirst->panBuffer + mp_psBufferFirst->nBufferSize
, l_sTempoMBP.panBuffer - sizeof(sMBP)
, l_sTempoMBP.panBuffer + l_sTempoMBP.nBufferSize
, l_sTempoMBP.nBufferSize + sizeof(sMBP)
);
#endif // _DEBUG
// To help memory mapping
char* l_panArrayFrom;
char* l_panArrayTo = l_sTempoMBP.panBuffer;
int l_nCopySize;
l_psMBP = (sMBP*) mp_psBufferFirst->panBuffer;
while(l_psMBP != NULL)
{ // Copy remaining blocks content
l_psMBP -= 1; // - sizeof(sMBP)
l_panArrayFrom = l_psMBP->panBuffer;
if(l_psMBP->nBufferTail < i_nByteReach)
{
l_nCopySize = l_psMBP->nBufferTail - l_psMBP->nBufferBegin;
}
else
{
l_nCopySize = i_nByteReach - l_psMBP->nBufferTail;
}
#ifdef USEMEMMOVE
MEMMOVE
#else
memmove
#endif // USEMEMMOVE
( l_panArrayTo // New pool
, l_panArrayFrom // Old pool
, l_nCopySize // Copy only used slots
);
l_panArrayTo += l_nCopySize;
l_psMBP = (sMBP*) l_psMBP->panBufferNext;
}
_DeleteBuffer(); // Delete old blocks
mp_psBufferFirst = (sMBP*) l_sTempoMBP.panBuffer - 1; // Switch for the new block
// Double linked buffers
mp_psBufferTail = mp_psBufferFirst;
mp_psBufferPrev = mp_psBufferFirst;
return mp_psBufferFirst;
}
else
{
#ifdef _DEBUG
TRACE
( "ERROR : %s::_ExpandBuffer(FAILED) = Block misexpansion\n"
, (CString) mp_oStrObjectName
);
#endif // _DEBUG
return NULL;
}
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::_ReduceBuffer
( int i_nByteReach
)
{
// Start from the farther slot to reach
sMBP* l_psMBP = _LocateBuffer(1<<31);
while
(
(l_psMBP > NULL)
&& (l_psMBP->nBufferBegin > i_nByteReach)
)
{
if(l_psMBP->panBufferNext != NULL)
{
delete [] (sMBP*) (l_psMBP->panBufferNext - 1);
l_psMBP->panBufferNext = NULL;
}
else{}
l_psMBP = (sMBP*) (l_psMBP->panBufferPrev - 1);
}
mp_psBufferTail = l_psMBP;
int l_nDivider = 1;
sMBP l_sTempoMBP;
// New buffer to replace to old one, thus starting from 0
l_sTempoMBP.panBufferPrev = NULL;
l_sTempoMBP.panBufferNext = NULL;
l_sTempoMBP.nBufferBegin = 0;
l_sTempoMBP.nBufferHead = 0;
l_sTempoMBP.nBufferTail = 0;
l_sTempoMBP.nBufferEnd = 0;
while(l_sTempoMBP.nBufferEnd < i_nByteReach)
{
l_sTempoMBP.nBufferEnd += mp_psBufferFirst->nBufferEnd;
}
l_sTempoMBP.nBufferSize = l_sTempoMBP.nBufferEnd;
// Create the new buffer
while
(
((l_sTempoMBP.panBuffer = new char[l_sTempoMBP.nBufferSize + sizeof(sMBP)]) == NULL)
&& (l_nDivider < 8)
)
{ // If buffer size is too big, try to allocate a smaller block
do
{
if(l_sTempoMBP.nBufferEnd > i_nByteReach)
{ // Reduce
l_sTempoMBP.nBufferEnd -= mp_psBufferFirst->nBufferEnd >> l_nDivider;
}
else
{ // Increase
l_sTempoMBP.nBufferEnd += mp_psBufferFirst->nBufferEnd >> l_nDivider;
}
}
while(l_sTempoMBP.nBufferEnd > i_nByteReach);
l_nDivider += 1;
l_sTempoMBP.nBufferSize = l_sTempoMBP.nBufferEnd;
}
if(l_sTempoMBP.panBuffer != NULL)
{
l_sTempoMBP.panBuffer += sizeof(sMBP);
// Zero memory if needed
if(mp_bZeroMemory == TRUE)
{
ZeroMemory
( l_sTempoMBP.panBuffer
, l_sTempoMBP.nBufferSize
);
}
else{}
// Set the new chunk
*((sMBP*) l_sTempoMBP.panBuffer - 1) = l_sTempoMBP;
#ifdef _DEBUG
TRACE
( "%s::_ReduceBuffer(%d-%d->%d slot%s) moved from [0x%08X->0x%08X[ to [0x%08X->0x%08X[ (%d bytes)\n"
, (CString) mp_oStrObjectName
, GetStringNumber()
, GetStringNumber() - l_sTempoMBP.nBufferEnd
, l_sTempoMBP.nBufferEnd
, (l_sTempoMBP.nBufferEnd > 1) ? "s" : ""
, mp_psBufferFirst->panBuffer - sizeof(sMBP)
, mp_psBufferFirst->panBuffer + mp_psBufferFirst->nBufferSize
, l_sTempoMBP.panBuffer - sizeof(sMBP)
, l_sTempoMBP.panBuffer + l_sTempoMBP.nBufferSize
, l_sTempoMBP.nBufferSize + sizeof(sMBP)
);
#endif // _DEBUG
l_psMBP = (sMBP*) mp_psBufferFirst->panBuffer;
// To help memory mapping
char* l_panArrayFrom;
char* l_panArrayTo = l_sTempoMBP.panBuffer;
int l_nCopySize;
while(l_psMBP != NULL)
{ // Copy remaining blocks content
l_psMBP -= 1; // - sizeof(sMBP)
l_panArrayFrom = l_psMBP->panBuffer;
if(l_psMBP->nBufferTail < i_nByteReach)
{
l_nCopySize = l_psMBP->nBufferTail - l_psMBP->nBufferBegin;
}
else
{
l_nCopySize = i_nByteReach - l_psMBP->nBufferTail;
}
#ifdef USEMEMMOVE
MEMMOVE
#else
memmove
#endif // USEMEMMOVE
( l_panArrayTo // New pool
, l_panArrayFrom // Old pool
, l_nCopySize // Copy only used slots
);
l_panArrayTo += l_nCopySize;
l_psMBP = (sMBP*) mp_psBufferFirst->panBuffer;
}
_DeleteBuffer(); // Delete old blocks
mp_psBufferFirst = (sMBP*) l_sTempoMBP.panBuffer - 1; // Switch for the new block
// Double linked buffers
mp_psBufferTail = mp_psBufferFirst;
mp_psBufferPrev = mp_psBufferFirst;
return mp_psBufferFirst->nBufferEnd;
}
else
{
#ifdef _DEBUG
TRACE
( "ERROR : %s::_ReduceBuffer(FAILED) = Block misreducing\n"
, (CString) mp_oStrObjectName
);
#endif // _DEBUG
return (-1);
}
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
CMemoryStringPool::sMBP*
CMemoryStringPool::_LocateBuffer
( int i_nByteIndex
)
{
if(i_nByteIndex == (1<<31))
{ // Get the farther end, beyon the tail
mp_psBufferPrev = mp_psBufferTail;
while(mp_psBufferPrev->panBufferNext != NULL)
{
mp_psBufferPrev = (sMBP*) mp_psBufferPrev->panBufferNext - 1;
}
}
else
{
if
(
(mp_psBufferPrev == NULL)
|| (mp_psBufferPrev->nBufferBegin > i_nByteIndex)
|| (mp_psBufferPrev->nBufferEnd <= i_nByteIndex)
)
{
if(i_nByteIndex < (mp_psBufferTail->nBufferTail >> 1))
{ // From start
mp_psBufferPrev = mp_psBufferFirst;
while
(
(mp_psBufferPrev->nBufferEnd <= i_nByteIndex)
&& (mp_psBufferPrev->panBufferNext != NULL)
)
{ // Next buffer
mp_psBufferPrev = (sMBP*) mp_psBufferPrev->panBufferNext - 1;
}
}
else
{ // From end
mp_psBufferPrev = mp_psBufferTail;
while
(
(mp_psBufferPrev->nBufferBegin > i_nByteIndex)
&& (mp_psBufferPrev->panBufferPrev != NULL)
)
{ // Previous buffer
mp_psBufferPrev = (sMBP*) mp_psBufferPrev->panBufferPrev - 1;
}
}
}
else{}
}
return mp_psBufferPrev;
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
void CMemoryStringPool::_EncodeString
( sMSP& o_rsStringPointer
, const char* i_panStringBuffer
, int i_nStringSize // = -1
, bool i_bStuffing // = false
)
{
unsigned int l_nHash;
int l_nLoop = i_nStringSize;
unsigned char l_nChar;
// Init
o_rsStringPointer.nHashRaw = 0;
o_rsStringPointer.nHashCase = 0;
o_rsStringPointer.nHashNoCase = 0;
if
(
(i_bStuffing == true)
&& (l_nLoop < 0)
)
{ // Avoid too much stuffing
l_nLoop = 256;
}
else{}
#ifndef TEST_NEWMETHOD
#else // TEST_NEWMETHOD
o_rsStringPointer.nLength = min(l_nLoop, GetStringLength(i_panStringBuffer));
#endif // TEST_NEWMETHOD
l_nChar = *i_panStringBuffer;
while
(
(l_nLoop != 0)
&& (
(
(i_bStuffing == false)
&& (l_nChar != 0)
)
|| (i_bStuffing == true)
)
)
{
o_rsStringPointer.nHashRaw <<= 4;
o_rsStringPointer.nHashCase <<= 4;
o_rsStringPointer.nHashNoCase <<= 4;
if(l_nChar == 0)
{ // Stuffing
o_rsStringPointer.nHashRaw += ' ';
o_rsStringPointer.nHashCase += ' ';
o_rsStringPointer.nHashNoCase += ' ';
}
else
{ // See "MemoryStringContainer.h"
o_rsStringPointer.nHashRaw += l_nChar;
o_rsStringPointer.nHashCase += g_panNormal[l_nChar];
o_rsStringPointer.nHashNoCase += g_panNoCase[l_nChar];
// Next character
i_panStringBuffer += 1;
l_nChar = *i_panStringBuffer;
}
// RAW
l_nHash = o_rsStringPointer.nHashRaw & 0xF0000000; // (unsigned int) 0xF << (32 - 4)
if(l_nHash != 0)
{
o_rsStringPointer.nHashRaw ^= l_nHash >> 24; // 32 - 8
o_rsStringPointer.nHashRaw ^= l_nHash;
}
else{}
// CASE
l_nHash = o_rsStringPointer.nHashCase & 0xF0000000;
if(l_nHash != 0)
{
o_rsStringPointer.nHashCase ^= l_nHash >> 24;
o_rsStringPointer.nHashCase ^= l_nHash;
}
else{}
// NOCASE
l_nHash = o_rsStringPointer.nHashNoCase & 0xF0000000;
if(l_nHash != 0)
{
o_rsStringPointer.nHashNoCase ^= l_nHash >> 24;
o_rsStringPointer.nHashNoCase ^= l_nHash;
}
else{}
l_nLoop -= 1;
}
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::_StreamString
( const char* i_panStringBuffer
, unsigned short i_nStringHole
, unsigned short i_nStringSize
, int i_nStringLocation // = -1
)
{
int l_nStringLocation;
if(i_nStringLocation == -1)
{ // Default location, queue the string
while((mp_psBufferTail->nBufferEnd - mp_psBufferTail->nBufferTail) < i_nStringHole)
{ // When not enough place, reserve the remaining place for a future usage (reserve a dummy string then free it)
RemoveStringAt(mp_oTreeString.AllocNode(0, mp_psBufferTail->nBufferEnd - mp_psBufferTail->nBufferTail));
// Expand the buffer up to a new one
_ExpandBuffer(mp_psBufferTail->nBufferEnd + i_nStringHole);
}
// Get the current tail
l_nStringLocation = mp_psBufferTail->nBufferTail;
}
else
{ // Use the requested Location, may overwritte some data
l_nStringLocation = i_nStringLocation;
}
sMBP* l_psMBP = _LocateBuffer(l_nStringLocation);
if(l_psMBP != NULL)
{
#ifdef USEMEMCPY
MEMCPY
#else
memcpy
#endif // USEMEMCPY
( &l_psMBP->panBuffer[l_nStringLocation - l_psMBP->nBufferBegin]
, (void*) i_panStringBuffer
, i_nStringSize
);
if(i_nStringLocation == -1)
{ // If we requested the tail, moving it accordingly
mp_psBufferTail->nBufferTail += i_nStringHole;
}
else{} // Requested Location, existing place, don't move the Tail
return l_nStringLocation;
}
else
{ // If no Buffer found, return the default Location
return 0;
}
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
char* CMemoryStringPool::_LocateString
( int i_nStringIndex
)
{
sMBP* l_psMBP;
sMSP* l_psMSP;
#ifndef TEST_NEWMETHOD
#else // TEST_NEWMETHOD
int l_nStringLocation;
#endif // TEST_NEWMETHOD
if
(
(i_nStringIndex < mp_oTreeString.GetSlotTail()) // Do not reserve another slot
&& ((l_psMSP = (sMSP*) mp_oTreeString.GetSlotPointer(i_nStringIndex)) != NULL)
&& (l_psMSP->nHashRaw != 0) // If string have a hash (is valid)
)
{ // If Slot found, get String location
#ifndef TEST_NEWMETHOD
l_psMBP = _LocateBuffer(l_psMSP->nLocation);
#else // TEST_NEWMETHOD
l_psMBP = _LocateBuffer(l_nStringLocation = mp_oTreeString.GetNodeData(i_nStringIndex));
#endif // TEST_NEWMETHOD
// Return String address
#ifndef TEST_NEWMETHOD
return &l_psMBP->panBuffer[l_psMSP->nLocation - l_psMBP->nBufferBegin];
#else // TEST_NEWMETHOD
return &l_psMBP->panBuffer[l_nStringLocation - l_psMBP->nBufferBegin];
#endif // TEST_NEWMETHOD
}
else
{ // If no Slot found or bad index, return NULL
return NULL;
}
} // 100 %
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
int CMemoryStringPool::_SearchString
( const char* i_panStringBuffer
, int i_nStringIndex // = -1
)
{
int l_nStringIndex;
char* l_panString;
if(i_nStringIndex < 0)
{ // Start from the Head
l_nStringIndex = 0;
}
else
{ // Start from the requested index
l_nStringIndex = i_nStringIndex;
}
while
(
((l_panString = _LocateString(l_nStringIndex)) != NULL)
&& (GetStringCompare(i_panStringBuffer, l_panString) != 0)
)
{ // As long as the strings doesn't match, try the next one
l_nStringIndex += 1;
}
if(l_panString != NULL)
{ // If the strings matches, return the correct index
return i_nStringIndex;
}
else
{ // Tail reached, return invalid index
return -1;
}
}
// ADDITIVE CODING : STRING HASH FUNCTIONS
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
unsigned int CMemoryStringPool::_HashRS(const char* i_panStringBuffer)
{
unsigned int length = GetStringLength(i_panStringBuffer) - 1;
unsigned int b = 378551;
unsigned int a = 63689;
unsigned int hash = 0;
for
( unsigned int i = 0
; i < length
; i++
)
{
hash = hash * a + i_panStringBuffer[i];
a = a * b;
}
return (hash & 0x7FFFFFFF);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
unsigned int CMemoryStringPool::_HashJS(const char* i_panStringBuffer)
{
unsigned int length = GetStringLength(i_panStringBuffer) - 1;
unsigned int hash = 1315423911;
for
( unsigned int i = 0
; i < length
; i++
)
{
hash ^= ((hash << 5) + i_panStringBuffer[i] + (hash >> 2));
}
return (hash & 0x7FFFFFFF);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
unsigned int CMemoryStringPool::_HashPJW(const char* i_panStringBuffer)
{
unsigned int length = GetStringLength(i_panStringBuffer) - 1;
unsigned int BitsInUnsignedInt = (unsigned int)(sizeof(unsigned int) * 8);
unsigned int ThreeQuarters = (unsigned int)((BitsInUnsignedInt * 3) / 4);
unsigned int OneEighth = (unsigned int)(BitsInUnsignedInt / 8);
unsigned int HighBits = (unsigned int)(0xFFFFFFFF) << (BitsInUnsignedInt - OneEighth);
unsigned int hash = 0;
unsigned int test = 0;
for
( unsigned int i = 0
; i < length
; i++
)
{
hash = (hash << OneEighth) + i_panStringBuffer[i];
if((test = hash & HighBits) != 0)
{
hash = (( hash ^ (test >> ThreeQuarters)) & (~HighBits));
}
}
return (hash & 0x7FFFFFFF);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
unsigned int CMemoryStringPool::_HashELF(const char* i_panStringBuffer)
{
unsigned int length = GetStringLength(i_panStringBuffer) - 1;
unsigned int hash = 0;
unsigned int x = 0;
for
( unsigned int i = 0
; i < length
; i++
)
{
hash = (hash << 4) + i_panStringBuffer[i];
if((x = hash & 0xF0000000L) != 0)
{
hash ^= (x >> 24);
hash &= ~x;
}
}
return (hash & 0x7FFFFFFF);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
unsigned int CMemoryStringPool::_HashBKDR(const char* i_panStringBuffer)
{
unsigned int length = GetStringLength(i_panStringBuffer) - 1;
unsigned int seed = 131; // 31 131 1313 13131 131313 etc..
unsigned int hash = 0;
for
( unsigned int i = 0
; i < length
; i++
)
{
hash = (hash * seed) + i_panStringBuffer[i];
}
return (hash & 0x7FFFFFFF);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
unsigned int CMemoryStringPool::_HashSDBM(const char* i_panStringBuffer)
{
unsigned int length = GetStringLength(i_panStringBuffer) - 1;
unsigned int hash = 0;
for
( unsigned int i = 0
; i < length
; i++
)
{
hash = i_panStringBuffer[i] + (hash << 6) + (hash << 16) - hash;
}
return (hash & 0x7FFFFFFF);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
unsigned int CMemoryStringPool::_HashDJB(const char* i_panStringBuffer)
{
unsigned int length = GetStringLength(i_panStringBuffer) - 1;
unsigned int hash = 5381;
for
( unsigned int i = 0
; i < length
; i++
)
{
hash = ((hash << 5) + hash) + i_panStringBuffer[i];
}
return (hash & 0x7FFFFFFF);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
unsigned int CMemoryStringPool::_HashDEK(const char* i_panStringBuffer)
{
unsigned int length = GetStringLength(i_panStringBuffer) - 1;
unsigned int hash = length;
for
( unsigned int i = 0
; i < length
; i++
)
{
hash = ((hash << 5) ^ (hash >> 27)) ^ i_panStringBuffer[i];
}
return (hash & 0x7FFFFFFF);
}
/*--- START FUNCTION HEADER --------------------------------------------------*/
/* Name : */
/* Role : */
/* Type : public */
/* Interface : RETURN (direct value) */
/* None */
/* OUTPUT (pointer to value) */
/* None */
/* INPUT (pointer to value, direct/default value) */
/* None */
/* Pre-condition : None */
/* Constraints : Sets the default values to */
/* Behavior : */
/*----------------------------------------------------------------------------*/
/* PROC */
/* */
/* A..... */
/*----------------------------------------------------------------------------*/
/*--- END FUNCTION HEADER ----------------------------------------------------*/
unsigned int CMemoryStringPool::_HashAP(const char* i_panStringBuffer)
{
unsigned int length = GetStringLength(i_panStringBuffer) - 1;
unsigned int hash = 0;
for
( unsigned int i = 0
; i < length
; i++
)
{
hash
^= ((i & 1) == 0)
? ( (hash << 7) ^ i_panStringBuffer[i] ^ (hash >> 3))
: (~((hash << 11) ^ i_panStringBuffer[i] ^ (hash >> 5)))
;
}
return (hash & 0x7FFFFFFF);
}
| 48.113252 | 120 | 0.286392 | [
"object"
] |
cccae67f6b0d48b403a9187e38db2a5b72d4cb0b | 8,087 | cc | C++ | src/stats.cc | lorenzo-stoakes/janus | 88cb536d569edf15af112230b02ea946c828cc12 | [
"MIT"
] | 1 | 2022-02-16T11:23:47.000Z | 2022-02-16T11:23:47.000Z | src/stats.cc | lorenzo-stoakes/janus | 88cb536d569edf15af112230b02ea946c828cc12 | [
"MIT"
] | null | null | null | src/stats.cc | lorenzo-stoakes/janus | 88cb536d569edf15af112230b02ea946c828cc12 | [
"MIT"
] | null | null | null | #include "janus.hh"
#include <cstdint>
namespace janus
{
// Maximum number of runners we might ever see.
static constexpr uint64_t MAX_RUNNERS = 500;
// Read through market updates in specified dynamic buffer, updating interval
// stats in specified stats object.
// TODO(lorenzo): This is too much code for 1 function and there is too much
// indentation.
static void add_interval_stats(stats& stats, dynamic_buffer& dyn_buf)
{
struct interval_state
{
uint64_t num_updates;
uint64_t num_timestamps;
uint64_t sum_intervals_ms;
uint64_t worst_interval_ms;
};
std::array<interval_state, NUM_STATS_INTERVALS> pre_post_states{};
std::array<interval_state, NUM_STATS_INTERVALS> pre_inplay_states{};
interval_state inplay_state{};
std::array<bool, NUM_STATS_INTERVALS> post_started{};
std::array<bool, NUM_STATS_INTERVALS> inplay_started{};
bool calc_post = (stats.flags & stats_flags::HAVE_METADATA) == stats_flags::HAVE_METADATA;
bool calc_inplay = (stats.flags & stats_flags::WENT_INPLAY) == stats_flags::WENT_INPLAY;
bool inplay = false;
uint64_t timestamp = 0;
while (dyn_buf.read_offset() != dyn_buf.size()) {
update u = dyn_buf.read<update>();
if (u.type == update_type::TIMESTAMP) {
uint64_t next = get_update_timestamp(u);
// If we're at the first timestamp there's nothing to do.
if (timestamp == 0) {
timestamp = next;
continue;
}
// If we encounter a duplicate timestamp, ignore the
// update.
if (timestamp == next)
continue;
uint64_t delta_ms = next - timestamp;
for (uint64_t i = 0; i < NUM_STATS_INTERVALS; i++) {
if (calc_post && post_started[i]) {
interval_state& state = pre_post_states[i];
state.num_timestamps++;
state.sum_intervals_ms += delta_ms;
if (delta_ms > state.worst_interval_ms)
state.worst_interval_ms = delta_ms;
}
if (calc_inplay && inplay_started[i]) {
interval_state& state = pre_inplay_states[i];
// TODO(lorenzo): Duplication.
state.num_timestamps++;
state.sum_intervals_ms += delta_ms;
if (delta_ms > state.worst_interval_ms)
state.worst_interval_ms = delta_ms;
}
}
if (inplay) {
// TODO(lorenzo): More duplication!
inplay_state.num_timestamps++;
inplay_state.sum_intervals_ms += delta_ms;
if (delta_ms > inplay_state.worst_interval_ms)
inplay_state.worst_interval_ms = delta_ms;
}
// We set things started after we first enter the
// interval so we look at the first delta in the
// interval rather than the first delta prior to it.
// Determine which intervals have started to accumulate stats.
for (uint64_t i = 0; i < NUM_STATS_INTERVALS; i++) {
uint64_t interval_mins = INTERVAL_PERIODS_MINS[i];
uint64_t interval_ms = interval_mins * MS_PER_MIN;
if (calc_post && next < stats.start_timestamp) {
uint64_t diff = stats.start_timestamp - next;
if (diff <= interval_ms)
post_started[i] = true;
} else {
post_started[i] = false;
}
if (calc_inplay && next < stats.inplay_timestamp) {
uint64_t diff = stats.inplay_timestamp - next;
if (diff <= interval_ms)
inplay_started[i] = true;
} else {
inplay_started[i] = false;
}
}
timestamp = next;
} else if (u.type == update_type::MARKET_INPLAY) {
inplay = true;
}
// Track number of updates too.
for (uint64_t i = 0; i < NUM_STATS_INTERVALS; i++) {
if (calc_post && post_started[i]) {
interval_state& state = pre_post_states[i];
state.num_updates++;
}
if (calc_inplay && inplay_started[i]) {
interval_state& state = pre_inplay_states[i];
state.num_updates++;
}
}
if (inplay)
inplay_state.num_updates++;
}
for (uint64_t i = 0; i < NUM_STATS_INTERVALS; i++) {
if (calc_post) {
interval_state& state = pre_post_states[i];
interval_stats& target = stats.pre_post_intervals[i];
target.num_updates = state.num_updates;
target.worst_update_interval_ms = state.worst_interval_ms;
if (state.num_timestamps > 0) {
double avg = static_cast<double>(state.sum_intervals_ms);
avg /= static_cast<double>(state.num_timestamps);
target.mean_update_interval_ms = avg;
} else {
target.mean_update_interval_ms = 0;
}
}
if (calc_inplay) {
// TODO(lorenzo): Duplication.
interval_state& state = pre_inplay_states[i];
interval_stats& target = stats.pre_inplay_intervals[i];
target.num_updates = state.num_updates;
target.worst_update_interval_ms = state.worst_interval_ms;
if (state.num_timestamps > 0) {
double avg = static_cast<double>(state.sum_intervals_ms);
avg /= static_cast<double>(state.num_timestamps);
target.mean_update_interval_ms = avg;
} else {
target.mean_update_interval_ms = 0;
}
}
}
if (inplay) {
// TODO(lorenzo): Duplication.
interval_stats& target = stats.inplay_intervals;
target.num_updates = inplay_state.num_updates;
target.worst_update_interval_ms = inplay_state.worst_interval_ms;
if (inplay_state.num_timestamps > 0) {
double avg = static_cast<double>(inplay_state.sum_intervals_ms);
avg /= static_cast<double>(inplay_state.num_timestamps);
target.mean_update_interval_ms = avg;
} else {
target.mean_update_interval_ms = 0;
}
}
}
auto generate_stats(meta_view* meta, dynamic_buffer& dyn_buf) -> stats
{
stats ret = {
.flags = stats_flags::DEFAULT,
.num_updates = dyn_buf.size() / sizeof(update),
};
bool have_meta = meta != nullptr;
if (have_meta) {
ret.flags |= stats_flags::HAVE_METADATA;
// If there's no metadata we work this out from runner IDs we
// encounter below.
ret.num_runners = meta->runners().size();
ret.start_timestamp = meta->market_start_timestamp();
}
std::array<uint64_t, MAX_RUNNERS> seen_runners{};
uint64_t num_seen_runners = 0;
auto have_seen_runner = [&seen_runners, &num_seen_runners](uint64_t id) -> bool {
for (uint64_t i = 0; i < num_seen_runners; i++) {
if (id == seen_runners[i])
return true;
}
return false;
};
std::array<uint64_t, MAX_RUNNERS> seen_removals{};
uint64_t num_seen_removals = 0;
auto have_seen_removal = [&seen_removals, &num_seen_removals](uint64_t id) -> bool {
for (uint64_t i = 0; i < num_seen_removals; i++) {
if (id == seen_removals[i])
return true;
}
return false;
};
dyn_buf.reset_read();
uint64_t timestamp = 0;
bool first = true;
uint64_t runner_id = 0;
while (dyn_buf.read_offset() != dyn_buf.size()) {
update u = dyn_buf.read<update>();
switch (u.type) {
case update_type::TIMESTAMP:
timestamp = get_update_timestamp(u);
if (first) {
ret.first_timestamp = timestamp;
first = false;
}
break;
case update_type::MARKET_INPLAY:
ret.flags |= stats_flags::WENT_INPLAY;
ret.inplay_timestamp = timestamp;
break;
case update_type::MARKET_CLOSE:
ret.flags |= stats_flags::WAS_CLOSED;
break;
case update_type::RUNNER_ID:
runner_id = get_update_runner_id(u);
if (!have_seen_runner(runner_id))
seen_runners[num_seen_runners++] = runner_id;
break;
case update_type::RUNNER_SP:
ret.flags |= stats_flags::SAW_SP;
break;
case update_type::RUNNER_WON:
ret.flags |= stats_flags::SAW_WINNER;
ret.winner_runner_id = runner_id;
break;
case update_type::RUNNER_REMOVAL:
if (!have_seen_removal(runner_id))
seen_removals[num_seen_removals++] = runner_id;
break;
default:
// We don't care about the other updates.
break;
}
}
ret.last_timestamp = timestamp;
if (have_meta) {
if (timestamp > ret.start_timestamp)
ret.flags |= stats_flags::PAST_POST;
} else {
ret.num_runners = num_seen_runners;
}
ret.num_removals = num_seen_removals;
// If we don't know the post time and we didn't go inplay, we can't
// gather interval statistics.
bool gone_inplay = (ret.flags & stats_flags::WENT_INPLAY) == stats_flags::WENT_INPLAY;
if (!have_meta && !gone_inplay)
return ret;
// We have to perform a second pass since we had to determine inplay
// time.
dyn_buf.reset_read();
add_interval_stats(ret, dyn_buf);
return ret;
}
} // namespace janus
| 29.300725 | 91 | 0.698776 | [
"object"
] |
ccd4efe2a2712eb19d9101938757c453c90ff347 | 4,889 | cpp | C++ | Contrib-Intel/RSD-PSME-RMM/application/src/registration/attach.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 5 | 2019-11-11T07:57:26.000Z | 2022-03-28T08:26:53.000Z | Contrib-Intel/RSD-PSME-RMM/application/src/registration/attach.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 3 | 2019-09-05T21:47:07.000Z | 2019-09-17T18:10:45.000Z | Contrib-Intel/RSD-PSME-RMM/application/src/registration/attach.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 11 | 2019-07-20T00:16:32.000Z | 2022-01-11T14:17:48.000Z | /*!
* @copyright
* Copyright (c) 2017-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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 "agent-framework/command/registry.hpp"
#include "agent-framework/command/psme_commands.hpp"
#include "agent-framework/exceptions/exception.hpp"
#include "psme/rest/server/error/error_factory.hpp"
#include "psme/core/agent/agent_manager.hpp"
#include "configuration/configuration.hpp"
using namespace agent_framework::command;
using namespace agent_framework::module;
using namespace psme::core::agent;
using namespace psme::rest::error;
using configuration::Configuration;
namespace {
const char GAMI_API_VERSION[] = "1.0.0";
bool are_vectors_same(const std::vector<std::string>& v1, const std::vector<std::string>& v2) {
return (v1.size() != v2.size()) ? false : std::is_permutation(v1.begin(), v1.end(), v2.begin());
}
std::vector<std::string> capabilities_to_string_vector(const Capabilities& caps) {
std::vector<std::string> result{};
for (const auto& cap : caps) {
result.emplace_back(cap.get_name());
}
return result;
}
Capabilities string_vector_to_capabilities(const std::vector<std::string>& str_caps) {
Capabilities caps{};
for (const auto& str_cap : str_caps) {
caps.emplace_back(Capability(str_cap));
}
return caps;
}
JsonAgentSPtr get_agent_by_address_and_port(const std::string& address, int port) {
auto agent_manager = AgentManager::get_instance();
for (JsonAgentSPtr agent : agent_manager->get_agents()) {
if (agent->get_ipv4address() == address && agent->get_port() == port) {
return agent;
}
}
return nullptr;
}
void handle_attach(const Attach::Request& request, Attach::Response& response) {
if (!request.is_valid()) {
throw json_rpc::JsonRpcException(json_rpc::common::ERROR_RPC_INVALID_REQUEST, "Invalid data format");
}
log_info("rest", "Registration: Request.IP = " << request.get_ipv4_address()
<< " gamiId = " << request.get_gami_id()
<< " port = " << request.get_port()
<< " capabilities = " << request.get_capabilities().to_json().dump());
JsonAgentSPtr agent = get_agent_by_address_and_port(request.get_ipv4_address(), request.get_port());
// check if agent was found
if (agent) {
auto agent_caps = capabilities_to_string_vector(agent->get_capabilities());
// check if agent is already registered
if (agent->get_gami_id() == request.get_gami_id()
&& agent->get_version() == ::GAMI_API_VERSION
&& agent->get_vendor() == request.get_vendor()
&& are_vectors_same(request.get_capabilities().get_array(), agent_caps)) {
// agent already registered - reconnection - ok
log_info("rest", "Reconnection detected");
}
else {
// conflict
std::string message = "Registration conflict: another agent is already connected on " +
request.get_ipv4_address() + ":" + std::to_string(request.get_port());
log_warning("rest", message);
throw ServerException(ErrorFactory::create_conflict_error(message));
}
}
else {
// agent was not found, register a new one
agent = std::make_shared<JsonAgent>(
request.get_gami_id(),
request.get_ipv4_address(),
request.get_port(),
request.get_version(),
request.get_vendor(),
string_vector_to_capabilities(request.get_capabilities().get_array())
);
AgentManager::get_instance()->add_agent(agent);
log_info("registration", "Agent " << request.get_gami_id() << " registered.");
}
// prepare response
const json::Json& configuration = Configuration::get_instance().to_json();
const auto& eventing_address = configuration.value("eventing", json::Json::object()).value("address", std::string{});
const auto& eventing_port = configuration.value("eventing", json::Json::object()).value("port", int{});
response.set_ipv4_address(eventing_address);
response.set_version(::GAMI_API_VERSION);
response.set_port(eventing_port);
}
}
REGISTER_COMMAND(Attach, ::handle_attach);
| 35.686131 | 121 | 0.658008 | [
"object",
"vector"
] |
ccd7542d19655fb330f5d0ccbf6a75714808a0c5 | 1,736 | cpp | C++ | pytorch/th_demosaicing_operator.cpp | VLOGroup/optox | f9d61d64aa7bb44080601517539ba5aefd75d365 | [
"MIT"
] | 7 | 2020-06-17T21:05:46.000Z | 2021-03-28T03:52:53.000Z | pytorch/th_demosaicing_operator.cpp | khammernik/optox | ae8bf1b4c1bfeb1e2fea24f549182d5610e09d82 | [
"MIT"
] | 4 | 2021-01-26T12:43:41.000Z | 2022-02-10T00:01:41.000Z | pytorch/th_demosaicing_operator.cpp | khammernik/optox | ae8bf1b4c1bfeb1e2fea24f549182d5610e09d82 | [
"MIT"
] | 4 | 2020-09-16T10:03:48.000Z | 2022-01-05T01:22:14.000Z | ///@file th_demosaicing_operator.h
///@brief PyTorch wrappers for demosaicing operator
///@author Erich Kobler <erich.kobler@icg.tugraz.at>
///@date 04.2019
#include <vector>
#include "th_utils.h"
#include "operators/demosaicing_operator.h"
#include <torch/extension.h>
#include <pybind11/pybind11.h>
template<typename T>
at::Tensor forward(optox::DemosaicingOperator<T> &op, at::Tensor th_input)
{
// parse the input tensors
auto input = getDTensorTorch<T, 4>(th_input);
// allocate the output tensor
auto in_shape = th_input.sizes().vec();
in_shape[3] = 1;
auto th_output = at::empty(in_shape, th_input.options());
auto output = getDTensorTorch<T, 4>(th_output);
op.forward({output.get()}, {input.get()});
return th_output;
}
template<typename T>
at::Tensor adjoint(optox::DemosaicingOperator<T> &op, at::Tensor th_input)
{
// parse the input tensors
auto input = getDTensorTorch<T, 4>(th_input);
// allocate the output tensor
auto in_shape = th_input.sizes().vec();
in_shape[3] = 3;
auto th_output = at::empty(in_shape, th_input.options());
auto output = getDTensorTorch<T, 4>(th_output);
op.adjoint({output.get()}, {input.get()});
return th_output;
}
template<typename T>
void declare_op(py::module &m, const std::string &typestr)
{
std::string pyclass_name = std::string("Demosaicing_") + typestr;
py::class_<optox::DemosaicingOperator<T>>(m, pyclass_name.c_str(), py::buffer_protocol(), py::dynamic_attr())
.def(py::init<const std::string&>())
.def("forward", forward<T>)
.def("adjoint", adjoint<T>);
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
{
declare_op<float>(m, "float");
declare_op<double>(m, "double");
}
| 27.125 | 113 | 0.680876 | [
"vector"
] |
ccd86da876e2c415177a6d9344b482fd52ca91c7 | 33,695 | cpp | C++ | etc/bbb/main.cpp | kvark/dark | 50174d101e798b91fe583e2430d40df971050792 | [
"MIT"
] | 4 | 2015-03-31T22:07:07.000Z | 2021-09-06T07:47:18.000Z | etc/bbb/main.cpp | kvark/dark | 50174d101e798b91fe583e2430d40df971050792 | [
"MIT"
] | 1 | 2015-06-25T21:27:12.000Z | 2015-06-25T21:27:12.000Z | etc/bbb/main.cpp | kvark/dark | 50174d101e798b91fe583e2430d40df971050792 | [
"MIT"
] | null | null | null | /* bbb.cpp - big block BWT compressor version 1, Aug. 31, 2006.
(C) 2006, Matt Mahoney, mmahoney (at) cs.fit.edu
This is free software under GPL, http://www.gnu.org/licenses/gpl.txt
To compress/decompress: bbb command input output
Commands are concatenated, e.g.
bbb cfqm10 in out = compress (c) in fast mode (f), quiet (q), 10 MiB block size.
bbb df = decompress in fast mode.
Commands:
c = compress (default).
d = decompress.
f = fast mode, needs 5x blocksize in memory, default is 1.25x blocksize.
bN, kN, mN = blocksize N bytes, KiB, MiB (compression only), default = m4.
q = quiet (no output except for errors).
The compression format is a memory efficient Burrows-Wheeler Transform (BWT) followed
by a PAQ-like compression using a single order-0 context (no mixing) followed by 5 more
adaptive stages with low order contexts, and bitwise arithmetic coding.
LOW MEMORY BWT
The BWT is able to sort blocks as large as 80% of available memory in slow
mode or 20% in fast mode. Using larger blocks generally improves compression,
especially for text. In fast mode, the bytes of a block are sorted by their
right context (with wrap around) before compression with an order 0 model.
For example, the block "banana" is sorted as follows:
sorted
block context T
----- ------- ---
0 n abana a
1 n anaba a
2 b anana a <- p (starting point for inverse transform)
3 a banan b
4 a nanab n
5 a naban n
After decompression, the transform is inverted by making a sorted copy of the
block, T, then traversing the block as follows: from position p, find the
next byte in T, then find the matching byte in the block with the same rank,
i.e. if t[p] = the j'th occurrence of byte c, then set p = such that
block[p] = the j'th occurrence of c. Repeat n times, where n = block size.
The initial value of p is the sorted position of the original first byte,
which must be sent by the compressor.
Start at p = 2 (transmitted by the compressor).
Output block[2] = 'b'
T[2] contains the third 'a'.
Find the third 'a' in block at position 5.
Set p = 5.
output block[5] = 'a'
T[5] contains the second 'n'
Find the second 'n' in block at position 1.
Set p = 1.
etc...
In fast mode, an array of n pointers into the block of n bytes is sorted
using std::stable_sort() (normally quicksort). Each pointer uses 4 bytes
of memory, so the program needs 5n total memory.
In slow mode, the block is divided into 16 subblocks and the pointers are
sorted as usual. Then the pointers are written to 16 temporary files and
merged. This is fast because the pointers are accessed sequentially.
This requires n/4 bytes for the pointers, plus the original block (5n/4
total), and 4n bytes on disk.
To invert the transform in fast mode, a linked list is built, then traversed,
Note that T can be represented by just the cumulative counts of lexicographically
preceding values (a=0, b=3, c=4, d=4,..., n=4, o=6, ...). Then the list is
built by scanning the block and keeping a count of each value.
block ptr
----- ---
n 0 -> 4 (count n=5)
n 1 -> 5 (count n=6)
b 2 -> 3 (count b=4) <- p
a 3 -> 0 (count a=1)
a 4 -> 1 (count a=2)
a 5 -> 2 (count a=3)
Then the list is traversed:
2 -> 3 -> 0 -> 4 -> 1 -> 5
b a n a n a
The linked list requires 4 bytes for each pointer, so again it requires 5n
memory. In slow mode, instead of building a list, the program searches the
block. If block[p] is the j'th occurrence of c in T, then the program must
scan the block from the beginning and count j occurrences of c. To make the
scan faster, the program builds an index of every 16'th occurrence of c, then
searches linearly from there. The steps are:
p = start (transmitted by compressor)
Repeat n times
Output block[p]
Find c such that count[c] <= p < count[c+1] by binary search on count[]
Let j = p - count[c]
p = index[c][j/16]
scan p forward (j mod 16) occurrences of c in block
A 2-D index would have variable row lengths, so it is organized into a 1
dimensional array with each row c having length (count[c+1]-count[c])/16 + 1,
which is at most n/16 + 256 elements. Each pointer is 4 bytes, so memory usage
is about 5n/4 including the block. No temporary files are used.
ENTROPY CODING
BWT data is best coded with an order 0 model. The transformed text tends to
have long runs of identical bytes (e.g. "nnbaaa"). The BWT data is modeled
with a modified PAQ with just one context (no mixing) followed by a 5 stage
SSE (APM) and bitwise arithmetic coding. Modeling typically takes about
as much time as sorting and unsorting in slow mode. The model uses about 5 MB
memory.
The order 0 model consists of a mapping:
order 1, 2, 3 contexts ----------+
V
order 0 context -> bit history -> p -> APM chain -> arithmetic coder
t1 sm
Bits are coded one at a time. The arithmetic coder maintains a range
[lo, hi), initially [0, 1) and repeatedly subdivides the range in proportion
to p(0), p(1), the next bit probabilites predicted by the model. The final
output is the shortest base 256 number x such that lo <= x < hi. As the leading
bytes of x become known, they are output. To decompress, the model predictions
are repeated as during compression, then the actual bit is determined by which
half of the subrange contains x.
The model inputs a bytewise order 0 context consisting of the last 0 to 7 bits
of the current byte, plus the number of bits. There are a total of 255 possible
bitwise contexts. For each context, a table (t1) maintains an 8 bit state
representing the history of 0 and 1 bits previously seen. This history is mapped
by another table (a StateMap sm) to a probability, p, that the next bit will be 1.
This table is adaptive: after each prediction, the mapping (state -> p) is adjusted
to improve the last prediction.
The output of the StateMap is passed through a series of 6 more adaptive tables,
(Adaptive Probability Maps, or APM) each of which maps a context and the input
probability to an output probability. The input probability is interpolated between
33 bins on a nonlinear scale with smaller bins near 0 and 1. After each prediction,
the corresponding table entries on both sides of p are adjusted to improve the
last prediction. The APM chain is like this:
+ A11 ->+ +--->---+ +--->---+
| | | | | |
p ->+ +-> A2 -> A3 +-> A4 -+-+-> A5 -+-> Encoder
| |
+ A12 ->+
A11 and A12 both take c0 (the preceding bits of the current byte) as additional
context, but one is fast adapting and the other is slow adapting. Their
outputs are averaged.
A2 is an order 1 context (previous byte and current partial byte).
A3 takes the previous (but not current) byte as context, plus 2 bits that depend
on the current run length (0, 1, 2-3, or 4+), the number of times the last
byte was repeated.
A4 takes the current byte and the low 5 bits of the second byte back.
The output is averaged with 3/4 weight to the A3 output with 1/4 weight.
A5 takes a 14 bit hash of an order 3 context (last 3 bytes plus current partial
byte) and is averaged with 1/2 weight to the A4 output.
The StateMap, state table, APM, Encoder, and associated code (Array, squash(),
stretch()) are taken from PAQ8 with minor non-functional changes (e.g. removing
global context).
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <algorithm>
#define NDEBUG // remove for debugging
#include <cassert>
using namespace std;
// 8, 16, 32 bit unsigned types
typedef unsigned char U8;
typedef unsigned short U16;
typedef unsigned int U32;
//////////////////////////// Array ////////////////////////////
// Array<T, ALIGN> a(n); creates n elements of T initialized to 0 bits.
// Constructors for T are not called.
// Indexing is bounds checked if assertions are on.
// a.size() returns n.
// a.resize(n) changes size to n, padding with 0 bits or truncating.
// Copy and assignment are not supported.
// Memory is aligned on a ALIGN byte boundary (power of 2), default is none.
template <class T, int ALIGN=0> class Array {
private:
int n; // user size
int reserved; // actual size
char *ptr; // allocated memory, zeroed
T* data; // start of n elements of aligned data
void create(int i); // create with size i
public:
explicit Array(int i=0) {create(i);}
~Array();
T& operator[](int i) {
#ifndef NDEBUG
if (i<0 || i>=n) fprintf(stderr, "%d out of bounds %d\n", i, n), exit(1);
#endif
return data[i];
}
const T& operator[](int i) const {
#ifndef NDEBUG
if (i<0 || i>=n) fprintf(stderr, "%d out of bounds %d\n", i, n), exit(1);
#endif
return data[i];
}
int size() const {return n;}
void resize(int i); // change size to i
private:
Array(const Array&); // no copy or assignment
Array& operator=(const Array&);
};
template<class T, int ALIGN> void Array<T, ALIGN>::resize(int i) {
if (i<=reserved) {
n=i;
return;
}
char *saveptr=ptr;
T *savedata=data;
int saven=n;
create(i);
if (savedata && saveptr) {
memcpy(data, savedata, sizeof(T)*min(i, saven));
free(saveptr);
}
}
template<class T, int ALIGN> void Array<T, ALIGN>::create(int i) {
n=reserved=i;
if (i<=0) {
data=0;
ptr=0;
return;
}
const int sz=ALIGN+n*sizeof(T);
ptr = (char*)calloc(sz, 1);
if (!ptr) fprintf(stderr, "Out of memory\n"), exit(1);
data = (ALIGN ? (T*)(ptr+ALIGN-(((long)ptr)&(ALIGN-1))) : (T*)ptr);
assert((char*)data>=ptr && (char*)data<=ptr+ALIGN);
}
template<class T, int ALIGN> Array<T, ALIGN>::~Array() {
free(ptr);
}
///////////////////////// state table ////////////////////////
// State table:
// nex(state, 0) = next state if bit y is 0, 0 <= state < 256
// nex(state, 1) = next state if bit y is 1
// nex(state, 2) = number of zeros in bit history represented by state
// nex(state, 3) = number of ones represented
//
// States represent a bit history within some context.
// State 0 is the starting state (no bits seen).
// States 1-30 represent all possible sequences of 1-4 bits.
// States 31-252 represent a pair of counts, (n0,n1), the number
// of 0 and 1 bits respectively. If n0+n1 < 16 then there are
// two states for each pair, depending on if a 0 or 1 was the last
// bit seen.
// If n0 and n1 are too large, then there is no state to represent this
// pair, so another state with about the same ratio of n0/n1 is substituted.
// Also, when a bit is observed and the count of the opposite bit is large,
// then part of this count is discarded to favor newer data over old.
static const U8 State_table[256][4]={
{ 1, 2, 0, 0},{ 3, 5, 1, 0},{ 4, 6, 0, 1},{ 7, 10, 2, 0}, // 0-3
{ 8, 12, 1, 1},{ 9, 13, 1, 1},{ 11, 14, 0, 2},{ 15, 19, 3, 0}, // 4-7
{ 16, 23, 2, 1},{ 17, 24, 2, 1},{ 18, 25, 2, 1},{ 20, 27, 1, 2}, // 8-11
{ 21, 28, 1, 2},{ 22, 29, 1, 2},{ 26, 30, 0, 3},{ 31, 33, 4, 0}, // 12-15
{ 32, 35, 3, 1},{ 32, 35, 3, 1},{ 32, 35, 3, 1},{ 32, 35, 3, 1}, // 16-19
{ 34, 37, 2, 2},{ 34, 37, 2, 2},{ 34, 37, 2, 2},{ 34, 37, 2, 2}, // 20-23
{ 34, 37, 2, 2},{ 34, 37, 2, 2},{ 36, 39, 1, 3},{ 36, 39, 1, 3}, // 24-27
{ 36, 39, 1, 3},{ 36, 39, 1, 3},{ 38, 40, 0, 4},{ 41, 43, 5, 0}, // 28-31
{ 42, 45, 4, 1},{ 42, 45, 4, 1},{ 44, 47, 3, 2},{ 44, 47, 3, 2}, // 32-35
{ 46, 49, 2, 3},{ 46, 49, 2, 3},{ 48, 51, 1, 4},{ 48, 51, 1, 4}, // 36-39
{ 50, 52, 0, 5},{ 53, 43, 6, 0},{ 54, 57, 5, 1},{ 54, 57, 5, 1}, // 40-43
{ 56, 59, 4, 2},{ 56, 59, 4, 2},{ 58, 61, 3, 3},{ 58, 61, 3, 3}, // 44-47
{ 60, 63, 2, 4},{ 60, 63, 2, 4},{ 62, 65, 1, 5},{ 62, 65, 1, 5}, // 48-51
{ 50, 66, 0, 6},{ 67, 55, 7, 0},{ 68, 57, 6, 1},{ 68, 57, 6, 1}, // 52-55
{ 70, 73, 5, 2},{ 70, 73, 5, 2},{ 72, 75, 4, 3},{ 72, 75, 4, 3}, // 56-59
{ 74, 77, 3, 4},{ 74, 77, 3, 4},{ 76, 79, 2, 5},{ 76, 79, 2, 5}, // 60-63
{ 62, 81, 1, 6},{ 62, 81, 1, 6},{ 64, 82, 0, 7},{ 83, 69, 8, 0}, // 64-67
{ 84, 71, 7, 1},{ 84, 71, 7, 1},{ 86, 73, 6, 2},{ 86, 73, 6, 2}, // 68-71
{ 44, 59, 5, 3},{ 44, 59, 5, 3},{ 58, 61, 4, 4},{ 58, 61, 4, 4}, // 72-75
{ 60, 49, 3, 5},{ 60, 49, 3, 5},{ 76, 89, 2, 6},{ 76, 89, 2, 6}, // 76-79
{ 78, 91, 1, 7},{ 78, 91, 1, 7},{ 80, 92, 0, 8},{ 93, 69, 9, 0}, // 80-83
{ 94, 87, 8, 1},{ 94, 87, 8, 1},{ 96, 45, 7, 2},{ 96, 45, 7, 2}, // 84-87
{ 48, 99, 2, 7},{ 48, 99, 2, 7},{ 88,101, 1, 8},{ 88,101, 1, 8}, // 88-91
{ 80,102, 0, 9},{103, 69,10, 0},{104, 87, 9, 1},{104, 87, 9, 1}, // 92-95
{106, 57, 8, 2},{106, 57, 8, 2},{ 62,109, 2, 8},{ 62,109, 2, 8}, // 96-99
{ 88,111, 1, 9},{ 88,111, 1, 9},{ 80,112, 0,10},{113, 85,11, 0}, // 100-103
{114, 87,10, 1},{114, 87,10, 1},{116, 57, 9, 2},{116, 57, 9, 2}, // 104-107
{ 62,119, 2, 9},{ 62,119, 2, 9},{ 88,121, 1,10},{ 88,121, 1,10}, // 108-111
{ 90,122, 0,11},{123, 85,12, 0},{124, 97,11, 1},{124, 97,11, 1}, // 112-115
{126, 57,10, 2},{126, 57,10, 2},{ 62,129, 2,10},{ 62,129, 2,10}, // 116-119
{ 98,131, 1,11},{ 98,131, 1,11},{ 90,132, 0,12},{133, 85,13, 0}, // 120-123
{134, 97,12, 1},{134, 97,12, 1},{136, 57,11, 2},{136, 57,11, 2}, // 124-127
{ 62,139, 2,11},{ 62,139, 2,11},{ 98,141, 1,12},{ 98,141, 1,12}, // 128-131
{ 90,142, 0,13},{143, 95,14, 0},{144, 97,13, 1},{144, 97,13, 1}, // 132-135
{ 68, 57,12, 2},{ 68, 57,12, 2},{ 62, 81, 2,12},{ 62, 81, 2,12}, // 136-139
{ 98,147, 1,13},{ 98,147, 1,13},{100,148, 0,14},{149, 95,15, 0}, // 140-143
{150,107,14, 1},{150,107,14, 1},{108,151, 1,14},{108,151, 1,14}, // 144-147
{100,152, 0,15},{153, 95,16, 0},{154,107,15, 1},{108,155, 1,15}, // 148-151
{100,156, 0,16},{157, 95,17, 0},{158,107,16, 1},{108,159, 1,16}, // 152-155
{100,160, 0,17},{161,105,18, 0},{162,107,17, 1},{108,163, 1,17}, // 156-159
{110,164, 0,18},{165,105,19, 0},{166,117,18, 1},{118,167, 1,18}, // 160-163
{110,168, 0,19},{169,105,20, 0},{170,117,19, 1},{118,171, 1,19}, // 164-167
{110,172, 0,20},{173,105,21, 0},{174,117,20, 1},{118,175, 1,20}, // 168-171
{110,176, 0,21},{177,105,22, 0},{178,117,21, 1},{118,179, 1,21}, // 172-175
{110,180, 0,22},{181,115,23, 0},{182,117,22, 1},{118,183, 1,22}, // 176-179
{120,184, 0,23},{185,115,24, 0},{186,127,23, 1},{128,187, 1,23}, // 180-183
{120,188, 0,24},{189,115,25, 0},{190,127,24, 1},{128,191, 1,24}, // 184-187
{120,192, 0,25},{193,115,26, 0},{194,127,25, 1},{128,195, 1,25}, // 188-191
{120,196, 0,26},{197,115,27, 0},{198,127,26, 1},{128,199, 1,26}, // 192-195
{120,200, 0,27},{201,115,28, 0},{202,127,27, 1},{128,203, 1,27}, // 196-199
{120,204, 0,28},{205,115,29, 0},{206,127,28, 1},{128,207, 1,28}, // 200-203
{120,208, 0,29},{209,125,30, 0},{210,127,29, 1},{128,211, 1,29}, // 204-207
{130,212, 0,30},{213,125,31, 0},{214,137,30, 1},{138,215, 1,30}, // 208-211
{130,216, 0,31},{217,125,32, 0},{218,137,31, 1},{138,219, 1,31}, // 212-215
{130,220, 0,32},{221,125,33, 0},{222,137,32, 1},{138,223, 1,32}, // 216-219
{130,224, 0,33},{225,125,34, 0},{226,137,33, 1},{138,227, 1,33}, // 220-223
{130,228, 0,34},{229,125,35, 0},{230,137,34, 1},{138,231, 1,34}, // 224-227
{130,232, 0,35},{233,125,36, 0},{234,137,35, 1},{138,235, 1,35}, // 228-231
{130,236, 0,36},{237,125,37, 0},{238,137,36, 1},{138,239, 1,36}, // 232-235
{130,240, 0,37},{241,125,38, 0},{242,137,37, 1},{138,243, 1,37}, // 236-239
{130,244, 0,38},{245,135,39, 0},{246,137,38, 1},{138,247, 1,38}, // 240-243
{140,248, 0,39},{249,135,40, 0},{250, 69,39, 1},{ 80,251, 1,39}, // 244-247
{140,252, 0,40},{249,135,41, 0},{250, 69,40, 1},{ 80,251, 1,40}, // 248-251
{140,252, 0,41}}; // 253-255 are reserved
#define nex(state,sel) State_table[state][sel]
///////////////////////////// Squash //////////////////////////////
// return p = 1/(1 + exp(-d)), d scaled by 8 bits, p scaled by 12 bits
int squash(int d) {
static const int t[33]={
1,2,3,6,10,16,27,45,73,120,194,310,488,747,1101,
1546,2047,2549,2994,3348,3607,3785,3901,3975,4022,
4050,4068,4079,4085,4089,4092,4093,4094};
if (d>2047) return 4095;
if (d<-2047) return 0;
int w=d&127;
d=(d>>7)+16;
return (t[d]*(128-w)+t[(d+1)]*w+64) >> 7;
}
//////////////////////////// Stretch ///////////////////////////////
// Inverse of squash. d = ln(p/(1-p)), d scaled by 8 bits, p by 12 bits.
// d has range -2047 to 2047 representing -8 to 8. p has range 0 to 4095.
class Stretch {
Array<short> t;
public:
Stretch();
int operator()(int p) const {
assert(p>=0 && p<4096);
return t[p];
}
} stretch;
Stretch::Stretch(): t(4096) {
int pi=0;
for (int x=-2047; x<=2047; ++x) { // invert squash()
int i=squash(x);
for (int j=pi; j<=i; ++j)
t[j]=x;
pi=i+1;
}
t[4095]=2047;
}
//////////////////////////// StateMap //////////////////////////
// A StateMap maps a nonstationary counter state to a probability.
// After each mapping, the mapping is adjusted to improve future
// predictions. Methods:
//
// sm.p(y, cx) converts state cx (0-255) to a probability (0-4095),
// and trains by updating the previous prediction with y (0-1).
// Counter state -> probability * 256
class StateMap {
protected:
int cxt; // context
Array<U16> t; // 256 states -> probability * 64K
public:
StateMap();
int p(int y, int cx) {
assert(cx>=0 && cx<t.size());
t[cxt]+=(y<<16)-t[cxt]+128 >> 8;
return t[cxt=cx] >> 4;
}
};
StateMap::StateMap(): cxt(0), t(256) {
for (int i=0; i<256; ++i) {
int n0=nex(i,2);
int n1=nex(i,3);
if (n0==0) n1*=128;
if (n1==0) n0*=128;
t[i] = 65536*(n1+1)/(n0+n1+2);
}
}
//////////////////////////// APM //////////////////////////////
// APM maps a probability and a context into a new probability
// that bit y will next be 1. After each guess it updates
// its state to improve future guesses. Methods:
//
// APM a(N) creates with N contexts, uses 66*N bytes memory.
// a.p(y, pr, cx, rate=8) returned adjusted probability in context cx (0 to
// N-1). rate determines the learning rate (smaller = faster, default 8).
// Probabilities are scaled 12 bits (0-4095). Update on last bit y (0-1).
class APM {
int index; // last p, context
const int N; // number of contexts
Array<U16> t; // [N][33]: p, context -> p
public:
APM(int n);
int p(int y, int pr=2048, int cxt=0, int rate=8) {
assert(pr>=0 && pr<4096 && cxt>=0 && cxt<N && rate>0 && rate<32);
pr=stretch(pr);
int g=(y<<16)+(y<<rate)-y-y;
t[index] += g-t[index] >> rate;
t[index+1] += g-t[index+1] >> rate;
const int w=pr&127; // interpolation weight (33 points)
index=(pr+2048>>7)+cxt*33;
return t[index]*(128-w)+t[index+1]*w >> 11;
}
};
// maps p, cxt -> p initially
APM::APM(int n): index(0), N(n), t(n*33) {
for (int i=0; i<N; ++i)
for (int j=0; j<33; ++j)
t[i*33+j] = i==0 ? squash((j-16)*128)*16 : t[j];
}
//////////////////////////// Predictor //////////////////////////
class Predictor {
int pr; // next return value of p() (0-4095)
public:
Predictor(): pr(2048) {}
int p() const {return pr;}
void update(int y);
};
void Predictor::update(int y) {
static int c0=1; // bitwise context: last 0-7 bits with a leading 1 (1-255)
static U32 c4=0; // last 4 whole bytes, last is in low 8 bits
static int bpos=0; // number of bits in c0 (0-7)
static Array<U8> t1(256); // context -> state
static StateMap sm; // state -> pr
static U8* cp=&t1[0]; // context pointer
static int run=0; // count of consecutive identical bytes (0-65535)
static int runcxt=0; // (0-3) if run is 0, 1, 2-3, 4+
static APM a11(256), a12(256), a2(65536), a3(1024), a4(8192), a5(16384);
// update model
*cp=nex(*cp, y);
// update context
c0+=c0+y;
if (++bpos==8) {
bpos=0;
c4=c4<<8|c0-256;
c0=1;
bpos=0;
if (((c4^c4>>8)&255)==0) {
if (run<65535)
++run;
if (run==1 || run==2 || run==4) runcxt+=256;
}
else run=0, runcxt=0;
}
// predict
cp=&t1[c0];
pr=sm.p(y, *cp);
pr=a11.p(y, pr, c0, 5)+a12.p(y, pr, c0, 9)+1>>1;
pr=a2.p(y, pr, c0|c4<<8&0xff00, 7);
pr=a3.p(y, pr, c4&255|runcxt, 8);
pr=a4.p(y, pr, c0|c4&0x1f00, 7)*3+pr+2>>2;
pr=a5.p(y, pr, c0^(c4&0xffffff)*123456791>>18, 7)+pr+1>>1;
}
//////////////////////////// Encoder ////////////////////////////
// An Encoder does arithmetic encoding. Methods:
// Encoder(COMPRESS, f) creates encoder for compression to archive f, which
// must be open past any header for writing in binary mode.
// Encoder(DECOMPRESS, f) creates encoder for decompression from archive f,
// which must be open past any header for reading in binary mode.
// code(i) in COMPRESS mode compresses bit i (0 or 1) to file f.
// code() in DECOMPRESS mode returns the next decompressed bit from file f.
// Global y is set to the last bit coded or decoded by code().
// compress(c) in COMPRESS mode compresses one byte.
// decompress() in DECOMPRESS mode decompresses and returns one byte.
// flush() should be called exactly once after compression is done and
// before closing f. It does nothing in DECOMPRESS mode.
// size() returns current length of archive
// setFile(f) sets alternate source to FILE* f for decompress() in COMPRESS
// mode (for testing transforms).
typedef enum {COMPRESS, DECOMPRESS} Mode;
class Encoder {
private:
Predictor predictor;
const Mode mode; // Compress or decompress?
FILE* archive; // Compressed data file
U32 x1, x2; // Range, initially [0, 1), scaled by 2^32
U32 x; // Decompress mode: last 4 input bytes of archive
FILE *alt; // decompress() source in COMPRESS mode
// Compress bit y or return decompressed bit
int code(int y=0) {
int p=predictor.p();
assert(p>=0 && p<4096);
p+=p<2048;
U32 xmid=x1 + (x2-x1>>12)*p + ((x2-x1&0xfff)*p>>12);
assert(xmid>=x1 && xmid<x2);
if (mode==DECOMPRESS) y=x<=xmid;
y ? (x2=xmid) : (x1=xmid+1);
predictor.update(y);
while (((x1^x2)&0xff000000)==0) { // pass equal leading bytes of range
if (mode==COMPRESS) putc(x2>>24, archive);
x1<<=8;
x2=(x2<<8)+255;
if (mode==DECOMPRESS) x=(x<<8)+(getc(archive)&255); // EOF is OK
}
return y;
}
public:
Encoder(Mode m, FILE* f);
Mode getMode() const {return mode;}
long size() const {return ftell(archive);} // length of archive so far
void flush(); // call this when compression is finished
void setFile(FILE* f) {alt=f;}
// Compress one byte
void compress(int c) {
assert(mode==COMPRESS);
for (int i=7; i>=0; --i)
code((c>>i)&1);
}
// Decompress and return one byte
int decompress() {
if (mode==COMPRESS) {
assert(alt);
return getc(alt);
}
else {
int c=0;
for (int i=0; i<8; ++i)
c+=c+code();
return c;
}
}
};
Encoder::Encoder(Mode m, FILE* f):
mode(m), archive(f), x1(0), x2(0xffffffff), x(0), alt(0) {
if (mode==DECOMPRESS) { // x = first 4 bytes of archive
for (int i=0; i<4; ++i)
x=(x<<8)+(getc(archive)&255);
}
}
void Encoder::flush() {
if (mode==COMPRESS)
putc(x1>>24, archive); // Flush first unequal byte of range
}
///////////////////////////////// BWT //////////////////////////////
// Globals
bool fast=false; // transform method: fast uses 5x blocksize memory, slow uses 5x/4
int blockSize=0x400000; // max BWT block size
int n=0; // number of elements in block, 0 < n <= blockSize
Array<U8> block; // [n] text to transform
Array<int> ptr; // [n] or [n/16] indexes into block to sort
const int PAD=72; // extra bytes in block (copy of beginning)
int pos=0; // bytes compressed/decompressed so far
bool quiet=false; // q option?
// true if block[a+1...] < block[b+1...] wrapping at n
inline bool lessthan(int a, int b) {
if (a<0) return false;
if (b<0) return true;
int r=block[a+1]-block[b+1]; // an optimization
if (r) return r<0;
r=memcmp(&block[a+2], &block[b+2], PAD-8);
if (r) return r<0;
if (a<b) {
int r=memcmp(&block[a+1], &block[b+1], n-b-1);
if (r) return r<0;
r=memcmp(&block[a+n-b], &block[0], b-a);
if (r) return r<0;
return memcmp(&block[0], &block[b-a], a)<0;
}
else {
int r=memcmp(&block[a+1], &block[b+1], n-a-1);
if (r) return r<0;
r=memcmp(&block[0], &block[b+n-a], a-b);
if (r) return r<0;
return memcmp(&block[a-b], &block[0], b)<0;
}
}
// read 4 byte value LSB first, or -1 at EOF
int read4(FILE* f) {
unsigned int r=getc(f);
r|=getc(f)<<8;
r|=getc(f)<<16;
r|=getc(f)<<24;
return r;
}
// read n<=blockSize bytes from in to block, BWT, write to out
int encodeBlock(FILE* in, Encoder& en) {
n=fread(&block[0], 1, blockSize, in); // n = actual block size
if (n<1) return 0;
assert(block.size()>=n+PAD);
for (int i=0; i<PAD; ++i) block[i+n]=block[i];
// fast mode: sort the pointers to the block
if (fast) {
if (!quiet) printf("sorting %10d to %10d \r", pos, pos+n);
assert(ptr.size()>=n);
for (int i=0; i<n; ++i) ptr[i]=i;
stable_sort(&ptr[0], &ptr[n], lessthan); // faster than sort() or qsort()
int p=min_element(&ptr[0], &ptr[n])-&ptr[0];
en.compress(n>>24);
en.compress(n>>16);
en.compress(n>>8);
en.compress(n);
en.compress(p>>24);
en.compress(p>>16);
en.compress(p>>8);
en.compress(p);
if (!quiet) printf("compressing %10d to %10d \r", pos, pos+n);
for (int i=0; i<n; ++i) {
en.compress(block[ptr[i]]);
if (!quiet && i && (i&0xffff)==0)
printf("compressed %10d of %10d \r", pos+i, pos+n);
}
pos+=n;
return n;
}
// slow mode: divide the block into 16 parts, sort them, write the pointers
// to temporary files, then merge them.
else {
// write header
if (!quiet) printf("writing header at %10d \r", pos);
int p=0;
for (int i=1; i<n; ++i)
if (lessthan(i, 0)) ++p;
en.compress(n>>24);
en.compress(n>>16);
en.compress(n>>8);
en.compress(n);
en.compress(p>>24);
en.compress(p>>16);
en.compress(p>>8);
en.compress(p);
// sort pointers in 16 parts to temporary files
const int subBlockSize = (n-1)/16+1; // max size of sub-block
int start=0, end=subBlockSize; // range of current sub-block
FILE* tmp[16]; // temporary files
for (int i=0; i<16; ++i) {
if (!quiet) printf("sorting %10d to %10d \r", pos+start, pos+end);
tmp[i]=tmpfile();
if (!tmp[i]) perror("tmpfile()"), exit(1);
for (int j=start; j<end; ++j) ptr[j-start]=j;
stable_sort(&ptr[0], &ptr[end-start], lessthan);
for (int j=start; j<end; ++j) { // write pointers
int c=ptr[j-start];
fprintf(tmp[i], "%c%c%c%c", c, c>>8, c>>16, c>>24);
}
start=end;
end+=subBlockSize;
if (end>n) end=n;
}
// merge sorted pointers
if (!quiet) printf("merging %10d to %10d \r", pos, pos+n);
unsigned int t[16]; // current pointers
for (int i=0; i<16; ++i) { // init t
rewind(tmp[i]);
t[i]=read4(tmp[i]);
}
for (int i=0; i<n; ++i) { // merge and compress
int j=min_element(t, t+16, lessthan)-t;
en.compress(block[t[j]]);
if (!quiet && i && (i&0xffff)==0)
printf("compressed %10d of %10d \r", pos+i, pos+n);
t[j]=read4(tmp[j]);
}
for (int i=0; i<16; ++i) // delete tmp files
fclose(tmp[i]);
pos+=n;
return n;
}
}
// forward BWT
void encode(FILE* in, Encoder& en) {
block.resize(blockSize+PAD);
if (fast) ptr.resize(blockSize+1);
else ptr.resize((blockSize-1)/16+2);
while (encodeBlock(in, en));
en.compress(0); // mark EOF
en.compress(0);
en.compress(0);
en.compress(0);
}
// inverse BWT of one block
int decodeBlock(Encoder& en, FILE* out) {
// read block size
int n=en.decompress();
n=n*256+en.decompress();
n=n*256+en.decompress();
n=n*256+en.decompress();
if (n==0) return n;
if (!blockSize) { // first block? allocate memory
blockSize = n;
if (!quiet) printf("block size = %d\n", blockSize);
block.resize(blockSize+PAD);
if (fast) ptr.resize(blockSize);
else ptr.resize(blockSize/16+256);
}
else if (n<1 || n>blockSize) {
printf("file corrupted: block=%d max=%d\n", n, blockSize);
exit(1);
}
// read pointer to first byte
int p=en.decompress();
p=p*256+en.decompress();
p=p*256+en.decompress();
p=p*256+en.decompress();
if (p<0 || p>=n) {
printf("file corrupted: p=%d n=%d\n", p, n);
exit(1);
}
// decompress and read block
for (int i=0; i<n; ++i) {
block[i]=en.decompress();
if (!quiet && i && (i&0xffff)==0)
printf("decompressed %10d of %10d \r", pos+i, pos+n);
}
for (int i=0; i<PAD; ++i) block[i+n]=block[i]; // circular pad
// count (sort) bytes
if (!quiet) printf("unsorting %10d to %10d \r", pos, pos+n);
Array<int> t(257); // i -> number of bytes < i in block
for (int i=0; i<n; ++i)
++t[block[i]+1];
for (int i=1; i<257; ++i)
t[i]+=t[i-1];
assert(t[256]==n);
// fast mode: build linked list
if (fast) {
for (int i=0; i<n; ++i)
ptr[t[block[i]]++]=i;
assert(t[255]==n);
// traverse list
for (int i=0; i<n; ++i) {
assert(p>=0 && p<n);
putc(block[p], out);
p=ptr[p];
}
return n;
}
// slow: build ptr[t[c]+c+i] = position of i*16'th occurrence of c in block
Array<int> count(256); // i -> count of i in block
for (int i=0; i<n; ++i) {
int c=block[i];
if ((count[c]++ & 15)==0)
ptr[(t[c]>>4)+c+(count[c]>>4)]=i;
}
// decode
int c=block[p];
for (int i=0; i<n; ++i) {
assert(p>=0 && p<n);
putc(c, out);
// find next c by binary search in t so that t[c] <= p < t[c+1]
c=127;
int d=64;
while (d) {
if (t[c]>p) c-=d;
else if (t[c+1]<=p) c+=d;
else break;
d>>=1;
}
if (c==254 && t[255]<=p && p<t[256]) c=255;
assert(c>=0 && c<256 && t[c]<=p && p<t[c+1]);
// find approximate position of p
int offset=p-t[c];
const U8* q=&block[ptr[(t[c]>>4)+c+(offset>>4)]]; // start of linear search
offset&=15;
// find next p by linear search for offset'th occurrence of c in block
while (offset--)
if (*++q != c) q=(const U8*)memchr(q, c, &block[n]-q);
assert(q && q>=&block[0] && q<&block[n]);
p=q-&block[0];
}
pos+=n;
return n;
}
// inverse BWT of file
void decode(Encoder& en, FILE* out) {
while (decodeBlock(en, out));
}
/////////////////////////////// main ////////////////////////////
int main(int argc, char** argv) {
clock_t start=clock();
// check for args
if (argc<4) {
printf("bbb Big Block BWT file compressor, ver. 1\n"
"(C) 2006, Matt Mahoney. Free under GPL, http://www.gnu.org/licenses/gpl.txt\n"
"\n"
"To compress/decompress a file: bbb command input output\n"
"\n"
"Commands:\n"
"c = compress (default), d = decompress.\n"
"f = fast mode, needs 5x block size memory, default uses 1.25x block size.\n"
"q = quiet (no output except error messages).\n"
"bN, kN, mN = use block size N bytes, KiB, MiB, default = m4 (compression only).\n"
"\n"
"Commands should be concatenated in any order, e.g. bbb cfm100q foo foo.bbb\n"
"means compress foo to foo.bbb in fast mode using 100 MiB block size in quiet\n"
"mode.\n");
exit(0);
}
// read options
Mode mode=COMPRESS;
const char* p=argv[1];
while (*p) {
switch (*p) {
case 'c': mode=COMPRESS; break;
case 'd': mode=DECOMPRESS; break;
case 'f': fast=true; break;
case 'b': blockSize=atoi(p+1); break;
case 'k': blockSize=atoi(p+1)<<10; break;
case 'm': blockSize=atoi(p+1)<<20; break;
case 'q': quiet=true; break;
}
++p;
}
if (blockSize<1) printf("Block size must be at least 1\n"), exit(1);
// open files
FILE* in=fopen(argv[2], "rb");
if (!in) perror(argv[2]), exit(1);
FILE* out=fopen(argv[3], "wb");
if (!out) perror(argv[3]), exit(1);
// encode or decode
if (mode==COMPRESS) {
if (!quiet) printf("Compressing %s to %s in %s mode, block size = %d\n",
argv[2], argv[3], fast ? "fast" : "slow", blockSize);
Encoder en(COMPRESS, out);
encode(in, en);
en.flush();
}
else if (mode==DECOMPRESS) {
blockSize=0;
if (!quiet) printf("Decompressing %s to %s in %s mode\n",
argv[2], argv[3], fast ? "fast" : "slow");
Encoder en(DECOMPRESS, in);
decode(en, out);
}
if (!quiet) printf("%ld -> %ld in %1.2f sec \n", ftell(in), ftell(out),
(clock()-start+0.0)/CLOCKS_PER_SEC);
return 0;
}
| 36.505959 | 91 | 0.566197 | [
"model",
"transform"
] |
ccd963524048789c4892a78028bfd57a1ec83ea4 | 6,128 | hpp | C++ | src/verification/production/impl/production_impl.hpp | GeniusVentures/SuperGenius | ae43304f4a2475498ef56c971296175acb88d0ee | [
"MIT"
] | 1 | 2021-07-10T21:25:03.000Z | 2021-07-10T21:25:03.000Z | src/verification/production/impl/production_impl.hpp | GeniusVentures/SuperGenius | ae43304f4a2475498ef56c971296175acb88d0ee | [
"MIT"
] | null | null | null | src/verification/production/impl/production_impl.hpp | GeniusVentures/SuperGenius | ae43304f4a2475498ef56c971296175acb88d0ee | [
"MIT"
] | null | null | null |
#ifndef SUPERGENIUS_PRODUCTION_IMPL_HPP
#define SUPERGENIUS_PRODUCTION_IMPL_HPP
#include "verification/production.hpp"
#include <memory>
#include <boost/asio/basic_waitable_timer.hpp>
#include <outcome/outcome.hpp>
#include "application/app_state_manager.hpp"
#include "authorship/proposer.hpp"
#include "blockchain/block_tree.hpp"
#include "clock/timer.hpp"
#include "base/logger.hpp"
#include "verification/production/production_gossiper.hpp"
#include "verification/production/production_lottery.hpp"
#include "verification/production/epoch_storage.hpp"
#include "verification/production/impl/block_executor.hpp"
#include "crypto/hasher.hpp"
#include "crypto/sr25519_types.hpp"
#include "primitives/production_configuration.hpp"
#include "primitives/common.hpp"
#include "storage/trie/trie_storage.hpp"
namespace sgns::verification {
enum class ProductionState {
WAIT_BLOCK, // Node is just executed and waits for the new block to sync
// missing blocks
CATCHING_UP, // Node received first block announce and started fetching
// blocks between announced one and the latest finalized one
NEED_SLOT_TIME, // Missing blocks were received, now slot time should be
// calculated
SYNCHRONIZED // All missing blocks were received and applied, slot time was
// calculated, current peer can start block production
};
inline const auto kTimestampId =
primitives::InherentIdentifier::fromString("timstap0").value();
inline const auto kProdSlotId =
primitives::InherentIdentifier::fromString("prodslot").value();
class ProductionImpl : public Production, public std::enable_shared_from_this<ProductionImpl> {
public:
/**Node configuration must contain 'genesis' option
* Create an instance of Production implementation
* @param lottery - implementation of Production Lottery
* @param proposer - block proposer
* @param block_tree - tree of the blocks
* @param gossiper of this verification
* @param keypair - SR25519 keypair of this node
* @param authority_index of this node
* @param clock to measure time
* @param hasher to take hashes
* @param timer to be used by the implementation; the recommended one is
* sgns::clock::BasicWaitableTimer
* @param event_bus to deliver events over
*/
ProductionImpl(std::shared_ptr<application::AppStateManager> app_state_manager,
std::shared_ptr<ProductionLottery> lottery,
std::shared_ptr<BlockExecutor> block_executor,
std::shared_ptr<storage::trie::TrieStorage> trie_db,
std::shared_ptr<EpochStorage> epoch_storage,
std::shared_ptr<primitives::ProductionConfiguration> configuration,
std::shared_ptr<authorship::Proposer> proposer,
std::shared_ptr<blockchain::BlockTree> block_tree,
std::shared_ptr<ProductionGossiper> gossiper,
crypto::SR25519Keypair keypair,
std::shared_ptr<clock::SystemClock> clock,
std::shared_ptr<crypto::Hasher> hasher,
std::unique_ptr<clock::Timer> timer,
std::shared_ptr<authority::AuthorityUpdateObserver>
authority_update_observer);
~ProductionImpl() override = default;
bool start();
void setExecutionStrategy(ExecutionStrategy strategy) override {
execution_strategy_ = strategy;
}
void runEpoch(Epoch epoch,
ProductionTimePoint starting_slot_finish_time) override;
void onBlockAnnounce(const network::BlockAnnounce &announce) override;
ProductionMeta getProductionMeta() const;
private:
/**
* Run the next Production slot
*/
void runSlot();
/**
* Finish the current Production slot
*/
void finishSlot();
/**
* Gather the block and broadcast it
* @param output that we are the leader of this slot
*/
void processSlotLeadership(const crypto::VRFOutput &output);
/**
* Finish the Production epoch
*/
void finishEpoch();
ProductionLottery::SlotsLeadership getEpochLeadership(const Epoch &epoch) const;
outcome::result<primitives::PreRuntime> productionPreDigest(
const crypto::VRFOutput &output,
primitives::AuthorityIndex authority_index) const;
primitives::Seal sealBlock(const primitives::Block &block) const;
/**
* To be called if we are far behind other nodes to skip some slots and
* finally synchronize with the network
*/
void synchronizeSlots(const primitives::BlockHeader &new_header);
private:
std::shared_ptr<application::AppStateManager> app_state_manager_;
std::shared_ptr<ProductionLottery> lottery_;
std::shared_ptr<BlockExecutor> block_executor_;
std::shared_ptr<storage::trie::TrieStorage> trie_storage_;
std::shared_ptr<EpochStorage> epoch_storage_;
std::shared_ptr<primitives::ProductionConfiguration> genesis_configuration_;
std::shared_ptr<authorship::Proposer> proposer_;
std::shared_ptr<blockchain::BlockTree> block_tree_;
std::shared_ptr<ProductionGossiper> gossiper_;
crypto::SR25519Keypair keypair_;
std::shared_ptr<clock::SystemClock> clock_;
std::shared_ptr<crypto::Hasher> hasher_;
std::unique_ptr<clock::Timer> timer_;
std::shared_ptr<authority::AuthorityUpdateObserver>
authority_update_observer_;
ProductionState current_state_{ProductionState::WAIT_BLOCK};
Epoch current_epoch_;
/// Estimates of the first block production slot time. Input for the median
/// algorithm
std::vector<ProductionTimePoint> first_slot_times_{};
/// Number of blocks we need to use in median algorithm to get the slot time
const uint32_t kSlotTail = 30;
ProductionSlotNumber current_slot_{};
ProductionLottery::SlotsLeadership slots_leadership_;
ProductionTimePoint next_slot_finish_time_;
boost::optional<ExecutionStrategy> execution_strategy_;
base::Logger log_;
};
} // namespace sgns::verification
#endif // SUPERGENIUS_PRODUCTION_IMPL_HPP
| 36.694611 | 97 | 0.718179 | [
"vector"
] |
ccd98b0e96f695bd903eb2551da816d61ab516c8 | 1,695 | cpp | C++ | BasicByteBuffer/BasicByteBuffer/main.cpp | yagizarkayin/BasicByteBuffer | ef7d49694709e46d88ea44ec631ce98f7d5a5363 | [
"MIT"
] | null | null | null | BasicByteBuffer/BasicByteBuffer/main.cpp | yagizarkayin/BasicByteBuffer | ef7d49694709e46d88ea44ec631ce98f7d5a5363 | [
"MIT"
] | null | null | null | BasicByteBuffer/BasicByteBuffer/main.cpp | yagizarkayin/BasicByteBuffer | ef7d49694709e46d88ea44ec631ce98f7d5a5363 | [
"MIT"
] | null | null | null | #include "BasicByteBuffer.h"
#include <iostream>
struct Vec3
{
float x;
float y;
float z;
void print()
{
std::cout << "X: " << x << "Y: " << y << "Z: " << z << std::endl;
}
};
enum Color
{
BANANA = 1,
APPLE = 2,
ORANGE = 3
};
// WARNING: Since you have to initialize your data first, and then read the value into it,
// it is not recommended to use it with large classes such as this one.
// It is only for demonstration purposes
class VeryLargeClass
{
public:
VeryLargeClass()
{
std::cout << "This is a very large class" << std::endl;
}
void increaseAll()
{
for (auto& mesh : meshPoints)
{
mesh.x = 3.2f;
mesh.y = -2.6f;
mesh.z = 1.1f;
}
}
void printAll()
{
for (auto& mesh : meshPoints)
{
mesh.print();
}
}
private:
Vec3 meshPoints[256];
};
int main()
{
Vec3 out_singlePoint{ 0.2f, -0.3f, 1.5f };
const double out_doubleValue = 3579.246;
Color out_myColor = Color::BANANA;
VeryLargeClass out_myVeryLargeClassInstance;
out_myVeryLargeClassInstance.increaseAll();
out_myVeryLargeClassInstance.printAll();
BasicByteWriter writer;
writer.write(out_singlePoint);
writer.write(out_doubleValue);
writer.write(out_myColor);
writer.write(out_myVeryLargeClassInstance);
const std::vector<byte> result = writer.getDataAndResetBuffer();
BasicByteReader reader(const_cast<byte*>(result.data()), result.size());
Vec3 in_singlePoint;
double in_doubleValue;
Color in_myColor;
VeryLargeClass in_myVeryLargeClassInstance;
reader.read(in_singlePoint);
reader.read(in_doubleValue);
reader.read(in_myColor);
reader.read(in_myVeryLargeClassInstance);
in_myVeryLargeClassInstance.printAll();
std::cin.get();
return 0;
} | 18.031915 | 91 | 0.696755 | [
"mesh",
"vector"
] |
efa634640cb1bb1f9e4b2d41f290b583ea817df9 | 4,830 | hpp | C++ | inc/priam/row.hpp | npeshek-spotx/libpriamcql | 19bf933f796cd022c5f5a6737b8c8e1ebda5c490 | [
"Apache-2.0"
] | 1 | 2021-01-11T19:26:29.000Z | 2021-01-11T19:26:29.000Z | inc/priam/row.hpp | npeshek-spotx/libpriamcql | 19bf933f796cd022c5f5a6737b8c8e1ebda5c490 | [
"Apache-2.0"
] | 10 | 2020-04-22T16:17:11.000Z | 2021-02-04T19:48:46.000Z | inc/priam/row.hpp | npeshek-spotx/libpriamcql | 19bf933f796cd022c5f5a6737b8c8e1ebda5c490 | [
"Apache-2.0"
] | 2 | 2019-08-15T02:07:38.000Z | 2021-01-11T18:21:17.000Z | #pragma once
#include "priam/cpp_driver.hpp"
#include "priam/value.hpp"
namespace priam
{
class result;
class row
{
/// For private constructor, only result's can create rows.
friend result;
public:
class iterator
{
public:
using iterator_category = std::input_iterator_tag;
using value_type = priam::value;
using difference_type = std::ptrdiff_t;
using pointer = const priam::value*;
using reference = const priam::value&;
iterator(cass_iterator_ptr iter_ptr, const CassValue* cass_value)
: m_iter_ptr(std::move(iter_ptr)),
m_cass_value(cass_value)
{
}
iterator(const iterator&) = delete;
iterator(iterator&& other)
: m_iter_ptr(std::move(other.m_iter_ptr)),
m_cass_value(std::exchange(other.m_cass_value, nullptr))
{
}
auto operator=(const iterator&) noexcept -> iterator& = delete;
auto operator =(iterator&& other) noexcept -> iterator&
{
if (std::addressof(other) != this)
{
m_iter_ptr = std::move(other.m_iter_ptr);
m_cass_value = std::exchange(other.m_cass_value, nullptr);
}
return *this;
}
auto operator++() -> iterator&
{
advance();
return *this;
}
auto operator++(int) -> iterator
{
advance();
return iterator{std::move(m_iter_ptr), std::exchange(m_cass_value, nullptr)};
}
auto operator*() -> priam::value { return priam::value{m_cass_value}; }
auto operator==(const iterator& other) const -> bool { return m_cass_value == other.m_cass_value; }
auto operator!=(const iterator& other) const -> bool { return !(*this == other); }
private:
/// The iterator must maintain the lifetime of the cassandra driver's iterator.
cass_iterator_ptr m_iter_ptr{nullptr};
/// The current value in the row.
const CassValue* m_cass_value{nullptr};
auto advance() -> void
{
if (cass_iterator_next(m_iter_ptr.get()))
{
m_cass_value = cass_iterator_get_column(m_iter_ptr.get());
}
else
{
end();
}
}
auto end() -> void
{
m_iter_ptr = nullptr;
m_cass_value = nullptr;
}
};
auto begin() const -> iterator;
auto end() const -> iterator;
row(const row&) = delete;
row(row&&) = delete;
auto operator=(const row&) -> row& = delete;
auto operator=(row &&) -> row& = delete;
/**
* @param name The column's name to fetch.
* @throws std::runtime_error If the column does not exist.
* @return The column's value.
*/
auto column(std::string_view name) const -> value;
/**
* @param name The column's name to fetch.
* @throws std::runtime_error If the column does not exist.
* @return The column's value.
*/
auto operator[](std::string_view name) const -> value;
/**
* @param column_idx The column's index to fetch.
* @throws std::out_of_range If the column index requested is out of bounds.
* @return The column's value.
*/
auto column(size_t column_idx) const -> value;
/**
* @param column_idx The column's index to fetch.
* @throws std::out_of_range If the column index requested is out of bounds.
* @return The column's value.
*/
auto operator[](size_t column_idx) const -> value;
/**
* Iterate over each column's value in the row. The functor takes a single parameter `const priam::value&`.
* @param value_callback Callback function to be called on each column value.
*/
template<typename functor_type>
auto for_each(functor_type&& value_callback) const -> void
{
if (m_cass_row != nullptr)
{
cass_iterator_ptr cass_iterator_ptr(cass_iterator_from_row(m_cass_row));
while (cass_iterator_next(cass_iterator_ptr.get()))
{
const CassValue* cass_value = cass_iterator_get_column(cass_iterator_ptr.get());
if (cass_value != nullptr)
{
const priam::value value(cass_value);
value_callback(value);
}
}
}
}
private:
/// The underlying cassandra driver row object, this object does not need to be free'ed.
const CassRow* m_cass_row{nullptr};
/**
* @param cass_row The underlying cassandra row object.
*/
explicit row(const CassRow* cass_row);
};
} // namespace priam
| 30 | 112 | 0.569565 | [
"object"
] |
efb976cfe8e459d0a2000231e1499d02bcc1dbad | 25,773 | cpp | C++ | apps/cor2cor/cor2cor.cpp | bmatejek/gsvgaps | 4beb271167d306ad7e87b214895670f3d7c65dbd | [
"MIT"
] | null | null | null | apps/cor2cor/cor2cor.cpp | bmatejek/gsvgaps | 4beb271167d306ad7e87b214895670f3d7c65dbd | [
"MIT"
] | null | null | null | apps/cor2cor/cor2cor.cpp | bmatejek/gsvgaps | 4beb271167d306ad7e87b214895670f3d7c65dbd | [
"MIT"
] | null | null | null | // Source file for the program to process sparse correspondences
// Include files
#include "R3Shapes/R3Shapes.h"
////////////////////////////////////////////////////////////////////////
// Program arguments
////////////////////////////////////////////////////////////////////////
static char *input_mesh1_name = NULL;
static char *input_mesh2_name = NULL;
static char *input_correspondence_name = NULL;
static char *output_correspondence_name = NULL;
static int correspondences_trace_symmetry_axis = 0;
static int interpolation_min_correspondences = 0;
static int interpolation_max_correspondences = 0;
static RNLength interpolation_min_spacing = 0;
static RNLength interpolation_max_spacing = 0;
static int print_verbose = 0;
static int print_debug = 0;
////////////////////////////////////////////////////////////////////////
// Type definitions
////////////////////////////////////////////////////////////////////////
struct SparseVertexCorrespondence {
// vertices[0] and vertices[1] have same number of entries
// For every i, vertices[0][i] and vertices[1][i] are corresponding
// vertices in mesh[0] and mesh[1], respectively
R3Mesh *mesh[2];
RNArray<R3MeshVertex *> vertices[2];
int nvertices;
SparseVertexCorrespondence(R3Mesh *mesh0, R3Mesh *mesh1) {
mesh[0] = mesh0;
mesh[1] = mesh1;
nvertices = 0;
};
};
////////////////////////////////////////////////////////////////////////
// Input/output
////////////////////////////////////////////////////////////////////////
static R3Mesh *
ReadMesh(char *filename)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Allocate mesh
R3Mesh *mesh = new R3Mesh();
assert(mesh);
// Read mesh from file
if (!mesh->ReadFile(filename)) {
fprintf(stderr, "Unable to read mesh %s\n", filename);
return NULL;
}
// Print statistics
if (print_verbose) {
printf("Read mesh from %s ...\n", filename);
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Faces = %d\n", mesh->NFaces());
printf(" # Edges = %d\n", mesh->NEdges());
printf(" # Vertices = %d\n", mesh->NVertices());
fflush(stdout);
}
// Return success
return mesh;
}
static SparseVertexCorrespondence *
ReadSparseVertexCorrespondence(R3Mesh *mesh0, R3Mesh *mesh1, char *filename)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Parse filename extension
const char *extension;
if (!(extension = strrchr(filename, '.'))) {
printf("Filename %s has no extension (e.g., .cor)\n", filename);
return 0;
}
// Open file
FILE *fp = fopen(filename, "r");
if (!fp) {
fprintf(stderr, "Unable to open correspondence file %s\n", filename);
return NULL;
}
// Create correspondence
SparseVertexCorrespondence *correspondence = new SparseVertexCorrespondence(mesh0, mesh1);
if (!correspondence) {
fprintf(stderr, "Unable to allocate correspondence for %s\n", filename);
return NULL;
}
// Check filename extension
if (!strcmp(extension, ".cor")) {
// Read correspondences
int id0, id1;
while (fscanf(fp, "%d%d", &id0, &id1) == (unsigned int) 2) {
R3MeshVertex *vertex0 = mesh0->Vertex(id0);
R3MeshVertex *vertex1 = mesh1->Vertex(id1);
correspondence->vertices[0].Insert(vertex0);
correspondence->vertices[1].Insert(vertex1);
correspondence->nvertices++;
}
}
else if (!strcmp(extension, ".vk")) {
// Read header
double fdummy;
char format[256], dummy[256];
int nmeshes, ncorrespondences, idummy;
if (fscanf(fp, "%s%s%s%s%s%d%s%s%s%d%s%d%d%d%d%d", dummy, format, dummy, dummy, dummy, &nmeshes,
dummy, dummy, dummy, &idummy, dummy, &idummy, &idummy, &idummy, &idummy, &ncorrespondences) != (unsigned int) 16) {
fprintf(stderr, "Unable to read %s\n", filename);
return NULL;
}
// Read correspondences
int id0, id1;
while (fscanf(fp, "%d%lg%d%lg", &id0, &fdummy, &id1, &fdummy) == (unsigned int) 4) {
R3MeshVertex *vertex0 = mesh0->Vertex(id0);
R3MeshVertex *vertex1 = mesh1->Vertex(id1);
correspondence->vertices[0].Insert(vertex0);
correspondence->vertices[1].Insert(vertex1);
correspondence->nvertices++;
}
// Check number of correspondences
if (correspondence->nvertices != ncorrespondences) {
fprintf(stderr, "Mismatching number of correspondences in %s\n", filename);
return NULL;
}
}
else {
fprintf(stderr, "Unrecognized correspondence file extension: %s\n", extension);
return NULL;
}
// Close file
fclose(fp);
// Print statistics
if (print_verbose) {
printf("Read sparse correspondences from %s ...\n", filename);
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Correspondences = %d\n", correspondence->nvertices);
fflush(stdout);
}
// Return correspondence
return correspondence;
}
static int
WriteSparseVertexCorrespondence(SparseVertexCorrespondence *correspondence, char *filename)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Open file
FILE *fp = fopen(filename, "w");
if (!fp) {
fprintf(stderr, "Unable to open map file %s\n", filename);
return 0;
}
// Write corresponding vertex IDs
for (int i = 0; i < correspondence->nvertices; i++) {
R3MeshVertex *v0 = correspondence->vertices[0].Kth(i);
R3MeshVertex *v1 = correspondence->vertices[1].Kth(i);
int id0 = correspondence->mesh[0]->VertexID(v0);
int id1 = correspondence->mesh[1]->VertexID(v1);
fprintf(fp, "%6d %6d\n", id0, id1);
}
// Close file
fclose(fp);
// Print statistics
if (print_verbose) {
printf("Wrote correspondences to %s ...\n", filename);
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Correspondences = %d\n", correspondence->nvertices);
fflush(stdout);
}
// Return success
return 1;
}
////////////////////////////////////////////////////////////////////////
// Interpolation
////////////////////////////////////////////////////////////////////////
static RNLength
ComputePropertyDifference0(R3MeshPropertySet **properties, R3MeshVertex *vertex0, R3MeshVertex *vertex1)
{
// Initialize property
RNLength delta = 0;
// Compute property in feature space
for (int i = 0; i < properties[0]->NProperties(); i++) {
R3MeshProperty *property0 = properties[0]->Property(i);
R3MeshProperty *property1 = properties[1]->Property(i);
double value0 = property0->VertexValue(vertex0);
double value1 = property1->VertexValue(vertex1);
double d = fabs(value1 - value0);
if (value0 > 0) delta += d / value0;
// else if (d > 0) delta += RN_INFINITY;
}
// Return L1 difference of properties
return delta;
}
static RNLength
ComputePropertyDifference1(R3MeshPropertySet **properties, R3MeshVertex *vertex0, R3MeshVertex *vertex1)
{
// Initialize property
RNLength delta = 0;
// Compute property in feature space
for (int i = 0; i < properties[0]->NProperties(); i++) {
R3MeshProperty *property0 = properties[0]->Property(i);
R3MeshProperty *property1 = properties[1]->Property(i);
double value0 = property0->VertexValue(vertex0);
double value1 = property1->VertexValue(vertex1);
double d = fabs(value1 - value0);
if (value1 > 0) delta += d / value1;
// else if (d > 0) delta += RN_INFINITY;
}
// Return L1 difference of properties
return delta;
}
static RNScalar *
CreateSides(R3Mesh *mesh, RNArray<R3MeshVertex *>& correspondence_vertices)
{
// Allocate/initialize sides
RNScalar *sides = new RNScalar [ mesh->NVertices() ];
for (int i = 0; i < mesh->NVertices(); i++) sides[i] = 0;
// Compute axis
R3mesh_mark++;
RNArray<R3MeshEdge *> axis_edges;
RNArray<R3MeshVertex *> axis_vertices;
for (int i = 0; i < correspondence_vertices.NEntries(); i++) {
RNArray<R3MeshEdge *> shortest_path_edges;
R3MeshVertex *vertex0 = correspondence_vertices.Kth(i);
R3MeshVertex *vertex1 = correspondence_vertices.Kth((i+1) % correspondence_vertices.NEntries());
mesh->DijkstraDistance(vertex1, vertex0, &shortest_path_edges);
R3MeshVertex *vertex = vertex0;
for (int j = 0; j < shortest_path_edges.NEntries(); j++) {
R3MeshEdge *edge = shortest_path_edges.Kth(j);
assert(mesh->IsVertexOnEdge(vertex, edge));
axis_edges.Insert(edge);
axis_vertices.Insert(vertex);
vertex = mesh->VertexAcrossEdge(edge, vertex);
mesh->SetVertexMark(vertex, R3mesh_mark);
}
}
// Find seed vertex on ccw side
R3MeshVertex *ccw_seed = NULL;
for (int j = 0; j < axis_edges.NEntries(); j++) {
R3MeshVertex *vertex = axis_vertices.Kth(j);
R3MeshEdge *edge = axis_edges.Kth(j);
assert(mesh->IsVertexOnEdge(vertex, edge));
R3MeshEdge *ccw_edge = mesh->EdgeOnVertex(vertex, edge, RN_CCW);
R3MeshVertex *ccw_vertex = mesh->VertexAcrossEdge(ccw_edge, vertex);
if (mesh->VertexMark(ccw_vertex) == R3mesh_mark) continue;
ccw_seed = ccw_vertex;
break;
}
// Check if found seed
if (!ccw_seed) return sides;
// Compute distances from axis
RNLength *distances = mesh->DijkstraDistances(axis_vertices);
// Flood fill ccw side from seed
RNArray<R3MeshVertex *> stack;
stack.Insert(ccw_seed);
mesh->SetVertexMark(ccw_seed, R3mesh_mark);
while (!stack.IsEmpty()) {
R3MeshVertex *vertex = stack.Tail();
stack.RemoveTail();
sides[mesh->VertexID(vertex)] = distances[mesh->VertexID(vertex)];
for (int i = 0; i < mesh->VertexValence(vertex); i++) {
R3MeshEdge *edge = mesh->EdgeOnVertex(vertex, i);
R3MeshVertex *neighbor = mesh->VertexAcrossEdge(edge, vertex);
if (mesh->VertexMark(neighbor) != R3mesh_mark) {
mesh->SetVertexMark(neighbor, R3mesh_mark);
stack.Insert(neighbor);
}
}
}
// Flood fill cw side from seed
for (int i = 0; i < mesh->NVertices(); i++) {
R3MeshVertex *vertex = mesh->Vertex(i);
if (mesh->VertexMark(vertex) == R3mesh_mark) continue;
sides[mesh->VertexID(vertex)] = -distances[mesh->VertexID(vertex)];
}
// Delete distances
delete [] distances;
// Return sides
return sides;
}
static int
CreateProperties(R3MeshPropertySet **properties, SparseVertexCorrespondence *correspondence, int previous_ncorrespondences)
{
// Start statistics
RNTime start_time;
start_time.Read();
if (print_debug) {
printf(" Updating properties ...\n");
fflush(stdout);
}
// Create property set
for (int i = 0; i < 2; i++) {
R3Mesh *mesh = correspondence->mesh[i];
// Compute distance properties
for (int j = previous_ncorrespondences; j < correspondence->nvertices; j++) {
R3MeshVertex *vertex = correspondence->vertices[i].Kth(j);
char name[256];
sprintf(name, "d%d\n", mesh->VertexID(vertex));
RNLength *distances = mesh->DijkstraDistances(vertex);
R3MeshProperty *property = new R3MeshProperty(mesh, name, distances);
properties[i]->Insert(property);
delete [] distances;
}
// Compute side properties
if (correspondences_trace_symmetry_axis) {
if (previous_ncorrespondences == 0) {
RNScalar *sides = CreateSides(mesh, correspondence->vertices[i]);
R3MeshProperty *property = new R3MeshProperty(mesh, "Side", sides);
property->Multiply(1);
properties[i]->Insert(property);
delete [] sides;
}
}
}
// Debug information
if (print_debug) {
static int counter = 1;
char buffer[256];
sprintf(buffer, "properties0%d.arff", counter);
properties[0]->Write(buffer);
sprintf(buffer, "properties1%d.arff", counter);
properties[1]->Write(buffer);
counter++;
}
// Print messhage
if (print_debug) {
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Properties = %d\n", properties[0]->NProperties());
fflush(stdout);
}
// Return success
return 1;
}
static R3MeshProperty *
CreateImportances(R3Mesh *mesh, RNArray<R3MeshVertex *>& correspondence_vertices)
{
// Start statistics
RNTime start_time;
start_time.Read();
if (print_debug) {
printf(" Creating importances ...\n");
fflush(stdout);
}
// Allocate importances
R3MeshProperty *importances = new R3MeshProperty(mesh, "Importance");
if (!importances) {
fprintf(stderr, "Unable to allocate importances\n");
return NULL;
}
// Compute curvatures
R3MeshProperty curvatures(mesh);
for (int i = 0; i < mesh->NVertices(); i++) {
R3MeshVertex *vertex = mesh->Vertex(i);
RNScalar value = mesh->VertexGaussCurvature(vertex);
curvatures.SetVertexValue(i, value);
}
// Normalize curvatures
RNScalar min_curvature = curvatures.Minimum();
RNScalar max_curvature = curvatures.Maximum();
if (min_curvature < 0) min_curvature = 0;
if (max_curvature > 1000) max_curvature = 1000;
if (max_curvature <= min_curvature) max_curvature = min_curvature + 1;
for (int i = 0; i < mesh->NVertices(); i++) {
RNScalar value = curvatures.VertexValue(i);
if (value < min_curvature) value = min_curvature;
if (value > max_curvature) value = max_curvature;
value = (value - min_curvature) / (max_curvature - min_curvature);
curvatures.SetVertexValue(i, value);
}
// Blur curvatures
RNScalar spacing = sqrt( 1.0 / (correspondence_vertices.NEntries() * RN_PI));
RNScalar sigma = 0.2 * spacing;
curvatures.Blur(sigma);
// Compute importances
for (int i = 0; i < mesh->NVertices(); i++) {
RNScalar value = curvatures.VertexValue(i);
if (curvatures.IsLocalMaximum(i)) value *= 2;
importances->SetVertexValue(i, value);
}
// Debugging
if (print_debug) {
static int iteration = 1;
char buffer[256];
sprintf(buffer, "importance%d.val", iteration++);
importances->Write(buffer);
}
// Print messhage
if (print_debug) {
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Importances = %d\n", mesh->NVertices());
printf(" # Correspondences = %d\n", correspondence_vertices.NEntries());
printf(" Spacing = %g\n", spacing);
printf(" Sigma = %g\n", sigma);
fflush(stdout);
}
// Return importances
return importances;
}
static RNArray<R3MeshVertex *> *
CreateCandidates(R3Mesh *mesh, RNArray<R3MeshVertex *>& correspondence_vertices, int max_candidates)
{
// Create importances
R3MeshProperty *importances = CreateImportances(mesh, correspondence_vertices);
if (!importances) return NULL;
// Start statistics
RNTime start_time;
start_time.Read();
if (print_debug) {
printf(" Creating candidates ...\n");
fflush(stdout);
}
// Allocate array of candidates
RNArray<R3MeshVertex *> *candidates = new RNArray<R3MeshVertex *>();
if (!candidates) {
fprintf(stderr, "Unable to allocate candidates\n");
return NULL;
}
// Find candidates one at a time
RNArray<R3MeshVertex *> current_vertices(correspondence_vertices);
for (int i = 0; i < max_candidates; i++) {
// Compute distances from current vertices
RNLength *dists = mesh->DijkstraDistances(current_vertices);
// Find candidate vertex with highest value (importance * distance)
R3MeshVertex *candidate = NULL;
RNScalar best_value = -FLT_MAX;
for (int i = 0; i < mesh->NVertices(); i++) {
if (dists[i] == 0) continue;
RNScalar value = (1 + importances->VertexValue(i)) * dists[i];
if (value > best_value) {
candidate = mesh->Vertex(i);
best_value = value;
}
}
// Delete distances from current vertices
delete [] dists;
// Check if found candidate vertex
if (!candidate) break;
// Add candidate
candidates->Insert(candidate);
current_vertices.Insert(candidate);
}
// Debugging
if (print_debug) {
static int iteration = 1;
char buffer[256];
sprintf(buffer, "candidate%d.pid", iteration++);
FILE *fp = fopen(buffer, "w");
for (int i = 0; i < candidates->NEntries(); i++)
fprintf(fp, "%d\n", mesh->VertexID(candidates->Kth(i)));
fclose(fp);
}
// Print statistics
if (print_debug) {
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Candidates = %d\n", candidates->NEntries());
fflush(stdout);
}
// Delete importances
delete importances;
// Return candidates
return candidates;
}
static int
InterpolateCorrespondence(SparseVertexCorrespondence *correspondence,
int min_correspondences, int max_correspondences,
RNLength min_spacing, RNLength max_spacing,
R3MeshPropertySet **properties, int max_candidates)
{
// Start statistics
RNTime start_time;
start_time.Read();
R3mesh_mark++;
int count = 0;
if (print_debug) {
static int iteration = 1;
printf(" Iteration %d ...\n", iteration++);
fflush(stdout);
}
// Get convenient variables
R3Mesh *mesh0 = correspondence->mesh[0];
R3Mesh *mesh1 = correspondence->mesh[1];
// Create candidates
RNArray<R3MeshVertex *> *candidates0 = CreateCandidates(mesh0, correspondence->vertices[0], max_candidates);
if (!candidates0 || candidates0->IsEmpty()) return 0;
RNArray<R3MeshVertex *> *candidates1 = CreateCandidates(mesh1, correspondence->vertices[1], max_candidates);
if (!candidates1 || candidates1->IsEmpty()) return 0;
// Create struct to store new correspondences
SparseVertexCorrespondence mutually_closest_candidates(mesh0, mesh1);
// Consider each candidate in candidates0
for (int i = 0; i < candidates0->NEntries(); i++) {
R3MeshVertex *candidate0 = candidates0->Kth(i);
if (mesh0->VertexMark(candidate0) == R3mesh_mark) continue;
// Find closest candidate in candidates1
RNScalar distance1 = FLT_MAX;
R3MeshVertex *candidate1 = NULL;
for (int j = 0; j < candidates1->NEntries(); j++) {
R3MeshVertex *vertex1 = candidates1->Kth(j);
if (mesh1->VertexMark(vertex1) == R3mesh_mark) continue;
RNLength distance = ComputePropertyDifference0(properties, candidate0, vertex1);
if (distance < distance1) {
candidate1 = vertex1;
distance1 = distance;
}
}
// Check if found candidate1
if (!candidate1) continue;
// Check if there is a candidate0 closer to candidate1
RNScalar distance2 = FLT_MAX;
R3MeshVertex *candidate2 = NULL;
for (int j = 0; j < candidates0->NEntries(); j++) {
R3MeshVertex *vertex0 = candidates0->Kth(j);
if (mesh0->VertexMark(candidate0) == R3mesh_mark) continue;
RNLength distance = ComputePropertyDifference1(properties, vertex0, candidate1);
if (distance < distance2) {
candidate2 = vertex0;
distance2 = distance;
}
}
// Check if mutually closest
if (candidate0 != candidate2) {
if (print_debug) {
RNScalar side0 = properties[0]->Property(properties[0]->NProperties()-1)->VertexValue(candidate0);
RNScalar side1 = properties[1]->Property(properties[1]->NProperties()-1)->VertexValue(candidate1);
RNScalar side_fraction = (distance1 > 0) ? fabs(side0 - side1) / distance1 : 0;
printf(" M %d %d : %g (%g) : %d %g\n", mesh0->VertexID(candidate0), mesh1->VertexID(candidate1), distance1, side_fraction,
mesh0->VertexID(candidate2), distance2);
fflush(stdout);
}
continue;
}
// Found a mutually closest correspondence
mutually_closest_candidates.vertices[0].Insert(candidate0);
mutually_closest_candidates.vertices[1].Insert(candidate1);
mutually_closest_candidates.nvertices++;
mesh0->SetVertexMark(candidate0, R3mesh_mark);
mesh1->SetVertexMark(candidate1, R3mesh_mark);
count++;
// Print debug message
if (print_debug) {
RNScalar side0 = properties[0]->Property(properties[0]->NProperties()-1)->VertexValue(candidate0);
RNScalar side1 = properties[1]->Property(properties[1]->NProperties()-1)->VertexValue(candidate1);
RNScalar side_fraction = (distance1 > 0) ? fabs(side0 - side1) / distance1 : 0;
printf(" C %d %d : %g (%g)\n", mesh0->VertexID(candidate0), mesh1->VertexID(candidate1), distance1, side_fraction);
fflush(stdout);
}
}
// Add mutually closest candidates to sparse correspondence
for (int i = 0; i < count; i++) {
correspondence->vertices[0].Insert(mutually_closest_candidates.vertices[0].Kth(i));
correspondence->vertices[1].Insert(mutually_closest_candidates.vertices[1].Kth(i));
correspondence->nvertices++;
}
// Print statistics
if (print_debug) {
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Correspondences = %d\n", correspondence->nvertices);
printf(" # New Correspondences = %d\n", count);
printf(" # Candidates = %d %d\n", candidates0->NEntries(), candidates1->NEntries());
fflush(stdout);
}
// Delete the candidates
delete candidates0;
delete candidates1;
// Return success
return 1;
}
static int
InterpolateCorrespondence(SparseVertexCorrespondence *correspondence,
int min_correspondences, int max_correspondences,
RNLength min_spacing, RNLength max_spacing)
{
// Start statistics
RNTime start_time;
start_time.Read();
int niterations = 0;
if (print_verbose) {
printf("Interpolating correspondences ...\n");
fflush(stdout);
}
// Get convenient variables
R3Mesh *mesh0 = correspondence->mesh[0];
R3Mesh *mesh1 = correspondence->mesh[1];
// Check/adjust number of correspondences
if (min_correspondences > mesh0->NVertices()) min_correspondences = mesh0->NVertices();
if (min_correspondences > mesh1->NVertices()) min_correspondences = mesh1->NVertices();
if (min_correspondences <= correspondence->nvertices) return 1;
// Create properties
R3MeshPropertySet **properties = new R3MeshPropertySet *[ 2 ];
properties[0] = new R3MeshPropertySet(mesh0);
properties[1] = new R3MeshPropertySet(mesh1);
CreateProperties(properties, correspondence, 0);
// Interpolate correspondences a bit at a time (coarse to fine)
while (correspondence->nvertices < min_correspondences) {
// Remember old number of correspondences
int ncorrespondences = correspondence->nvertices;
// Create correspondences
if (!InterpolateCorrespondence(correspondence,
min_correspondences, max_correspondences,
min_spacing, max_spacing,
properties, 2 * ncorrespondences)) return 0;
// Check if created any new correspondences
if (correspondence->nvertices == ncorrespondences) break;
// Update properties
if (correspondence->nvertices < min_correspondences) {
CreateProperties(properties, correspondence, ncorrespondences);
}
// Update statistics
niterations++;
}
// Print statistics
if (print_verbose) {
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Iterations = %d\n", niterations);
printf(" # Correspondences = %d\n", correspondence->nvertices);
printf(" Min Correspondences = %d\n", min_correspondences);
printf(" Min Spacing = %g\n", min_spacing);
fflush(stdout);
}
// Return success
return 1;
}
////////////////////////////////////////////////////////////////////////
// Parse program arguments
////////////////////////////////////////////////////////////////////////
static int
ParseArgs(int argc, char **argv)
{
// Parse arguments
argc--; argv++;
while (argc > 0) {
if ((*argv)[0] == '-') {
if (!strcmp(*argv, "-v")) print_verbose = 1;
else if (!strcmp(*argv, "-debug")) print_debug = 1;
else if (!strcmp(*argv, "-symmetry_axis")) correspondences_trace_symmetry_axis = 1;
else if (!strcmp(*argv, "-interpolate")) { argc--; argv++; interpolation_min_correspondences = atoi(*argv); }
else { fprintf(stderr, "Invalid program argument: %s", *argv); exit(1); }
argv++; argc--;
}
else {
if (!input_mesh1_name) input_mesh1_name = *argv;
else if (!input_mesh2_name) input_mesh2_name = *argv;
else if (!input_correspondence_name) input_correspondence_name = *argv;
else if (!output_correspondence_name) output_correspondence_name = *argv;
else { fprintf(stderr, "Invalid program argument: %s", *argv); exit(1); }
argv++; argc--;
}
}
// Check input filename
if (!input_mesh1_name || !input_mesh2_name || !input_correspondence_name || !output_correspondence_name) {
fprintf(stderr, "Usage: mshcorr input_mesh1 input_mesh2 input_correspondence output_correspondence [options]\n");
return 0;
}
// Return OK status
return 1;
}
////////////////////////////////////////////////////////////////////////
// Main
////////////////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
// Check number of arguments
if (!ParseArgs(argc, argv)) exit(1);
// Read meshes
R3Mesh *meshes[2] = { NULL, NULL };
meshes[0] = ReadMesh(input_mesh1_name);
if (!meshes[0]) exit(-1);
meshes[1] = ReadMesh(input_mesh2_name);
if (!meshes[1]) exit(-1);
// Read sparse correspondence
SparseVertexCorrespondence *correspondence = ReadSparseVertexCorrespondence(meshes[0], meshes[1], input_correspondence_name);
if (!correspondence) exit(-1);
// Interpolate correspondences
if (interpolation_min_correspondences) {
if (!InterpolateCorrespondence(correspondence,
interpolation_min_correspondences, interpolation_max_correspondences,
interpolation_min_spacing, interpolation_max_spacing)) {
exit(-1);
}
}
// Write sparse correspondence
int status = WriteSparseVertexCorrespondence(correspondence, output_correspondence_name);
if (!status) exit(-1);
// Return success
return 0;
}
| 31.089264 | 133 | 0.648081 | [
"mesh"
] |
efbbeb46fc569a04e470bb18c1f2cd5204ca8efc | 11,571 | cpp | C++ | Shader.cpp | uw-loci/SpimVisualize | 1dd30c02ad52eb3e2e91f3f778b615ba4a8d39d1 | [
"MIT"
] | null | null | null | Shader.cpp | uw-loci/SpimVisualize | 1dd30c02ad52eb3e2e91f3f778b615ba4a8d39d1 | [
"MIT"
] | 1 | 2016-04-26T19:16:30.000Z | 2016-06-16T19:11:52.000Z | Shader.cpp | uw-loci/SpimVisualize | 1dd30c02ad52eb3e2e91f3f778b615ba4a8d39d1 | [
"MIT"
] | null | null | null | /*
GLSL Shader abstraction
MIT License
Copyright (c) 2009, Markus Broecker <mbrckr@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
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 "Shader.h"
#include <GL/glew.h>
#include <GL/gl.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <cassert>
#include <iomanip>
#include <algorithm>
#include <glm/gtc/type_ptr.hpp>
// long shaders are looooooooooooooooooooong
const unsigned int BUFFER_SIZE = 2048;
// maybe this is only needed on win32 as the include does not support all features of c++11...
/*
namespace std
{
static inline std::string to_string(unsigned int v)
{
#ifdef LINUX_BUILD
return std::to_string((unsigned long long)v);
#else
return std::to_string((_ULonglong)v);
#endif
}
}
*/
namespace ShaderLog
{
static void info(const std::string& msg)
{
std::clog << "[Shader Info]: " << msg << std::endl;
}
static void compileInfo(const std::string& msg)
{
std::clog << "[Shader Compilation]: " << msg << std::endl;
}
static void error(const std::string& msg)
{
std::cerr << "[Shader Error]: " << msg << std::endl;
}
std::vector<std::string>& split(const std::string &s, char delim, std::vector<std::string> &elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
{
item.erase(item.find_last_not_of(" \n\r\t")+1);
if (!item.empty())
elems.push_back(item);
}
return elems;
}
}
static void compileShader(const std::string& fileName, GLint shader, const std::map<std::string, std::string>& defines)
{
std::vector<std::string> contents;
std::ifstream file;
file.open( fileName.c_str() );
if (!file.is_open())
{
ShaderLog::error("Error opening file " + fileName + ".");
}
std::string line;
while (!file.eof())
{
std::getline( file, line );
line.append("\n");
contents.push_back( line );
}
file.close();
// preprocessing
if (!defines.empty())
{
// for all lines, find the tokens that begin with #define
for (size_t i = 0; i < contents.size(); ++i)
{
const std::string& line = contents[i];
if (line.find("#define") != std::string::npos)
{
// locate the token
std::string token = line.substr(line.find("#define ") + 8);
token = token.substr(0, token.find_first_of(' '));
auto replace = defines.find(token);
if (replace != defines.end())
{
std::string newLine = "#define " + token + " " + replace->second + "\n";
//std::cout << "[Debug] Replacing line \"" << line << "\" (token: " << token << ") with \"" << newLine << "\"\n";
contents[i] = newLine;
}
}
}
}
/*
std::cerr << "[Debug] Shader source:\n";
for (size_t i = 0; i < contents.size(); ++i)
{
std::cerr << "[Sauce] " << std::setw(2) << i << ": " << contents[i]; // << std::endl;
}
*/
const char *glLines[BUFFER_SIZE];
for (unsigned int i = 0; i < contents.size(); ++i)
glLines[i] = contents[i].c_str();
glShaderSource( shader, (GLsizei)contents.size(), glLines , 0 );
glCompileShader( shader );
char buffer[BUFFER_SIZE];
memset( buffer, 0, BUFFER_SIZE );
int length = 0;
glGetShaderInfoLog( shader, BUFFER_SIZE, &length, buffer );
if (length > 0)
{
std::vector <std::string> log;
ShaderLog::split(std::string(buffer), '\n', log);
if (log.size() > 1)
ShaderLog::compileInfo("File: " + fileName);
for (int i = 0; i < (int)log.size(); ++i)
ShaderLog::compileInfo(log[i]);
}
}
Shader::Shader(const std::string& vpFile, const std::string& fpFile) : mGeometryShader(0), mVertexSource(vpFile), mFragmentSource(fpFile), linkedSuccessfully(false)
{
mProgram = glCreateProgram();
mVertexShader = glCreateShader(GL_VERTEX_SHADER);
mFragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
reload();
}
Shader::Shader(const std::string& vpFile, const std::string& gpFile, const std::string& fpFile) : mVertexSource(vpFile), mGeometrySource(gpFile), mFragmentSource(fpFile), linkedSuccessfully(false)
{
mProgram = glCreateProgram();
mVertexShader = glCreateShader(GL_VERTEX_SHADER);
mGeometryShader = glCreateShader(GL_GEOMETRY_SHADER);
mFragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
reload();
}
Shader::Shader(const std::string& vpFile, const std::string& fpFile, const std::vector<std::pair<std::string, std::string> >& defines) : mGeometryShader(0), mVertexSource(vpFile), mFragmentSource(fpFile), linkedSuccessfully(false)
{
mProgram = glCreateProgram();
mVertexShader = glCreateShader(GL_VERTEX_SHADER);
mFragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
for (auto i = defines.begin(); i != defines.end(); ++i)
mDefines[i->first] = i->second;
reload();
}
Shader::Shader(const std::string& vpFile, const std::string& gpFile, const std::string& fpFile, const std::vector<std::pair<std::string, std::string> >& defines) : mVertexSource(vpFile), mGeometrySource(gpFile), mFragmentSource(fpFile), linkedSuccessfully(false)
{
mProgram = glCreateProgram();
mVertexShader = glCreateShader(GL_VERTEX_SHADER);
mGeometryShader = glCreateShader(GL_GEOMETRY_SHADER);
mFragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
for (auto i = defines.begin(); i != defines.end(); ++i)
mDefines[i->first] = i->second;
reload();
}
Shader::~Shader()
{
glDeleteShader( mVertexShader );
if (glIsShader(mGeometryShader))
glDeleteShader( mGeometryShader );
glDeleteShader( mFragmentShader );
glDeleteProgram( mProgram );
}
void Shader::reload()
{
compileShader(mVertexSource, mVertexShader, mDefines);
if (glIsShader(mGeometryShader))
compileShader(mGeometrySource, mGeometryShader, mDefines);
compileShader(mFragmentSource, mFragmentShader, mDefines);
link();
}
void Shader::link()
{
// attach all shaders we have
glAttachShader( mProgram, mVertexShader );
if (glIsShader(mGeometryShader))
glAttachShader( mProgram, mGeometryShader );
glAttachShader( mProgram, mFragmentShader );
glLinkProgram( mProgram );
// check for errors
char buffer[BUFFER_SIZE];
memset( buffer, 0, BUFFER_SIZE );
int length = 0;
glGetProgramInfoLog( mProgram, BUFFER_SIZE, &length, buffer );
if (length > 0)
ShaderLog::info( std::string(buffer) );
// validate
glValidateProgram( mProgram );
int status;
glGetProgramiv( mProgram, GL_VALIDATE_STATUS, &status );
if (status == GL_FALSE)
ShaderLog::error("Shader validation failed.\n");
#ifndef LINUX_BUILD
else
{
ShaderLog::info("Created shader " + std::to_string(mProgram));
linkedSuccessfully = true;
}
#endif
mUniformLocations.clear();
}
void Shader::bind() const
{
glUseProgram( mProgram );
}
void Shader::disable() const
{
glUseProgram( 0 );
}
int Shader::getUniform(const std::string& name) const
{
IntMap::iterator loc = mUniformLocations.find(name);
if (loc == mUniformLocations.end())
{
int u = glGetUniformLocation( mProgram, name.c_str());
#ifndef LINUX_BUILD
if (u < 0)
ShaderLog::error("Uniform location \"" + name + "\" not found in shader " + std::to_string(mProgram));
#endif
// this assumes that the insertion will succeeed
loc = mUniformLocations.insert( std::make_pair(name, u) ).first;
}
return loc->second;
}
void Shader::setUniform(const std::string& name, int i) const
{
glUniform1i( getUniform(name), i );
}
void Shader::setUniform(const std::string& name, float f) const
{
glUniform1f( getUniform(name), f );
}
void Shader::setUniform(const std::string& name, float x, float y) const
{
glUniform2f( getUniform(name), x, y );
}
void Shader::setUniform(const std::string& name, float x, float y, float z) const
{
glUniform3f( getUniform(name), x, y, z );
}
void Shader::setUniform(const std::string& name, float x, float y, float z, float w) const
{
glUniform4f( getUniform(name), x, y, z, w );
}
void Shader::setUniform(const std::string& name, const glm::vec2& v) const
{
glUniform2f( getUniform( name ), v.x, v.y );
}
void Shader::setUniform(const std::string& name, const glm::vec3& v) const
{
glUniform3f( getUniform( name ), v.x, v.y, v.z );
}
void Shader::setUniform(const std::string& name, const glm::vec4& v) const
{
glUniform4f( getUniform( name ), v.x, v.y, v.z, v.w );
}
void Shader::setMatrix4(const std::string& name, const glm::mat4& m) const
{
glUniformMatrix4fv( getUniform(name), 1, GL_FALSE, glm::value_ptr(m) );
}
void Shader::setMatrix4(const std::string& name, const glm::dmat4& m) const
{
glUniformMatrix4dv(getUniform(name), 1, GL_FALSE, glm::value_ptr(m));
}
void Shader::setMatrix4(const std::string& name, const float* matrix) const
{
glUniformMatrix4fv( getUniform(name), 1, GL_FALSE, matrix);
}
void Shader::setMatrices4(const std::string& name, const std::vector<glm::mat4>& m) const
{
glUniformMatrix4fv(getUniform(name), (GLsizei)m.size(), GL_FALSE, glm::value_ptr(m[0]));
}
void Shader::setTexture1D(const std::string& name, unsigned int textureId, unsigned int textureUnit) const
{
glActiveTexture(GL_TEXTURE0 + textureUnit);
glBindTexture(GL_TEXTURE_1D, textureId);
glUniform1i( getUniform(name), textureUnit );
}
void Shader::setTexture2D(const std::string& name, unsigned int textureId, unsigned int textureUnit) const
{
glActiveTexture(GL_TEXTURE0 + textureUnit);
glBindTexture(GL_TEXTURE_2D, textureId);
glUniform1i( getUniform(name), textureUnit );
}
void Shader::setTexture3D(const std::string& name, unsigned int textureId, unsigned int textureUnit) const
{
glActiveTexture(GL_TEXTURE0 + textureUnit);
glBindTexture(GL_TEXTURE_3D, textureId);
glUniform1i(getUniform(name), textureUnit);
}
void Shader::setTextureCube(const std::string& name, unsigned int texId, unsigned int unit) const
{
glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_CUBE_MAP, texId);
glUniform1i( getUniform(name), unit );
}
void Shader::setAttributeLocation(unsigned int attributeLocation, const std::string& name)
{
glBindAttribLocation(mProgram, attributeLocation, name.c_str());
}
int Shader::getAttributeLocation(const std::string& name)
{
auto loc = mAttributeLocations.find(name);
if (loc == mAttributeLocations.end())
{
int u = glGetAttribLocation(mProgram, name.c_str());
#ifndef LINUX_BUILD
if (u < 0)
ShaderLog::error("Attribute location \"" + name + "\" not found in shader " + std::to_string(mProgram));
#endif
// this assumes that the insertion will succeeed
loc = mAttributeLocations.insert(std::make_pair(name, u)).first;
}
return loc->second;
}
void Shader::setUniform(const std::string& name, const glm::ivec2& v) const
{
glUniform2i(getUniform(name), v.x, v.y);
}
void Shader::setUniform(const std::string& name, int i, int j) const
{
glUniform2i(getUniform(name), i, j);
}
| 25.656319 | 262 | 0.706076 | [
"vector"
] |
efc1267dc67da2e0ee0e56ca39aed32ca3fc6548 | 9,248 | cpp | C++ | test/string.cpp | ntoskrnl7/ext | 1117df828b1d3e41de0b9c55709c5b6c64ff2257 | [
"BSD-3-Clause"
] | 2 | 2020-08-18T15:05:01.000Z | 2021-12-27T02:06:04.000Z | test/string.cpp | ntoskrnl7/ext | 1117df828b1d3e41de0b9c55709c5b6c64ff2257 | [
"BSD-3-Clause"
] | 1 | 2020-11-07T18:14:59.000Z | 2020-11-07T18:14:59.000Z | test/string.cpp | ntoskrnl7/ext | 1117df828b1d3e41de0b9c55709c5b6c64ff2257 | [
"BSD-3-Clause"
] | 1 | 2020-11-07T17:08:53.000Z | 2020-11-07T17:08:53.000Z | #define CXX_USE_NULLPTR
#include <ext/string>
#include <gtest/gtest.h>
TEST(string_test, stoul) {
#if defined(_MSC_VER)
EXPECT_EQ(std::stoul("-12345"), 4294954951);
EXPECT_EQ(std::stoul("12345"), 12345);
EXPECT_EQ(std::stoul("0xffffffff", nullptr, 16),
std::numeric_limits<unsigned long>::max());
EXPECT_EQ(std::stoul(L"-12345"), 4294954951);
EXPECT_EQ(std::stoul(L"12345"), 12345);
EXPECT_EQ(std::stoul(L"0xffffffff", nullptr, 16),
std::numeric_limits<unsigned long>::max());
#else
EXPECT_EQ((uint32_t)std::stoul("-12345"), 4294954951);
EXPECT_EQ(std::stoul("12345"), 12345);
EXPECT_EQ((uint32_t)std::stoul("0xffffffff", nullptr, 16),
std::numeric_limits<uint32_t>::max());
EXPECT_EQ((uint32_t)std::stoul(L"-12345"), 4294954951);
EXPECT_EQ(std::stoul(L"12345"), 12345);
EXPECT_EQ((uint32_t)std::stoul(L"0xffffffff", nullptr, 16),
std::numeric_limits<uint32_t>::max());
#endif
EXPECT_THROW(EXPECT_EQ(std::stoul("hello", nullptr, 16),
std::numeric_limits<unsigned long>::max()),
std::invalid_argument);
EXPECT_THROW(EXPECT_EQ(std::stoul("Lhello", nullptr, 16),
std::numeric_limits<unsigned long>::max()),
std::invalid_argument);
EXPECT_THROW(EXPECT_EQ(std::stoul("0xffffffffffffffffff", nullptr, 16),
std::numeric_limits<unsigned long>::max()),
std::out_of_range);
EXPECT_THROW(EXPECT_EQ(std::stoul(L"0xffffffffffffffffff", nullptr, 16),
std::numeric_limits<unsigned long>::max()),
std::out_of_range);
}
TEST(string_test, stoull) {
EXPECT_EQ(std::stoull("-12345"), 18446744073709539271ull);
EXPECT_EQ(std::stoull("12345"), 12345);
EXPECT_EQ(std::stoull("0xffffffffffffffff", nullptr, 16),
std::numeric_limits<unsigned long long>::max());
EXPECT_EQ(std::stoull("-12345"), 18446744073709539271ull);
EXPECT_EQ(std::stoull("12345"), 12345);
EXPECT_EQ(std::stoull("0xffffffffffffffff", nullptr, 16),
std::numeric_limits<unsigned long long>::max());
EXPECT_EQ(std::stoull(L"-12345"), 18446744073709539271ull);
EXPECT_EQ(std::stoull(L"12345"), 12345);
EXPECT_THROW(EXPECT_EQ(std::stoull("hello", nullptr, 16),
std::numeric_limits<unsigned long long>::max()),
std::invalid_argument);
EXPECT_THROW(EXPECT_EQ(std::stoull("Lhello", nullptr, 16),
std::numeric_limits<unsigned long long>::max()),
std::invalid_argument);
EXPECT_THROW(EXPECT_EQ(std::stoull("0xffffffffffffffffff", nullptr, 16),
std::numeric_limits<unsigned long long>::max()),
std::out_of_range);
EXPECT_THROW(EXPECT_EQ(std::stoull(L"0xffffffffffffffffff", nullptr, 16),
std::numeric_limits<unsigned long long>::max()),
std::out_of_range);
}
TEST(string_test, movable_string_test) {
using namespace ext::string;
movable::string a(512, 'a');
movable::string b(a.begin(), a.end());
EXPECT_EQ(a, b);
movable::wstring aw(512, L'a');
movable::wstring bw(aw.begin(), aw.end());
EXPECT_EQ(aw, bw);
}
TEST(string_test, printable_test) {
std::string str = "\x0e\x10test\x0f\x11test\x0a\x12";
EXPECT_STREQ(ext::printable(str).c_str(), "testtest");
std::wstring str_w = L"\x0e\x10test\x0f\x11test\x0a\x12";
EXPECT_STREQ(ext::printable(str_w).c_str(), L"testtest");
str = "\x0e\x10test\x0f\x11test\x0a\x12";
EXPECT_STREQ(ext::lprintable(str).c_str(), "test\x0f\x11test\x0a\x12");
str_w = L"\x0e\x10test\x0f\x11test\x0a\x12";
EXPECT_STREQ(ext::lprintable(str_w).c_str(), L"test\x0f\x11test\x0a\x12");
str = "\x0e\x10test\x0f\x11test\x0a\x12";
EXPECT_STREQ(ext::rprintable(str).c_str(), "\x0e\x10test\x0f\x11test");
str_w = L"\x0e\x10test\x0f\x11test\x0a\x12";
EXPECT_STREQ(ext::rprintable(str_w).c_str(), L"\x0e\x10test\x0f\x11test");
EXPECT_STREQ(ext::printable(std::string("\x0e\x10test\x0e\x10")).c_str(),
"test");
EXPECT_STREQ(ext::printable(std::wstring(L"\x0e\x10test\x0e\x10")).c_str(),
L"test");
EXPECT_STREQ(ext::lprintable(std::string("\x0e\x10test\x0e\x10")).c_str(),
"test\x0e\x10");
EXPECT_STREQ(ext::lprintable(std::wstring(L"\x0e\x10test\x0e\x10")).c_str(),
L"test\x0e\x10");
EXPECT_STREQ(ext::rprintable(std::string("\x0e\x10test\x0e\x10")).c_str(),
"\x0e\x10test");
EXPECT_STREQ(ext::rprintable(std::wstring(L"\x0e\x10test\x0e\x10")).c_str(),
L"\x0e\x10test");
EXPECT_STREQ(ext::printable("\x0e\x10test\x0e\x10").c_str(), "test");
EXPECT_STREQ(ext::printable(L"\x0e\x10test\x0e\x10").c_str(), L"test");
EXPECT_STREQ(ext::lprintable("\x0e\x10test\x0e\x10").c_str(), "test\x0e\x10");
EXPECT_STREQ(ext::lprintable(L"\x0e\x10test\x0e\x10").c_str(),
L"test\x0e\x10");
EXPECT_STREQ(ext::rprintable("\x0e\x10test\x0e\x10").c_str(), "\x0e\x10test");
EXPECT_STREQ(ext::rprintable(L"\x0e\x10test\x0e\x10").c_str(),
L"\x0e\x10test");
#if (!defined(_MSC_VER)) || (defined(_MSC_VER) && _MSC_VER > 1600)
const std::string const_str = "\x0e\x10\x0e\x10test\x0e\x10\x0e\x10";
EXPECT_STREQ(ext::printable(const_str).c_str(), "test");
const std::wstring const_wstr = L"\x0e\x10\x0e\x10test\x0e\x10\x0e\x10";
EXPECT_STREQ(ext::printable(const_wstr).c_str(), L"test");
#endif
}
TEST(string_test, trim_test) {
std::string str = " test ";
EXPECT_STREQ(ext::trim(str).c_str(), "test");
std::wstring str_w = L" test ";
EXPECT_STREQ(ext::trim(str_w).c_str(), L"test");
str = " test ";
EXPECT_STREQ(ext::ltrim(str).c_str(), "test ");
str_w = L" test ";
EXPECT_STREQ(ext::ltrim(str_w).c_str(), L"test ");
str = " test ";
EXPECT_STREQ(ext::rtrim(str).c_str(), " test");
str_w = L" test ";
EXPECT_STREQ(ext::rtrim(str_w).c_str(), L" test");
EXPECT_STREQ(ext::trim(std::string(" test ")).c_str(), "test");
EXPECT_STREQ(ext::trim(std::wstring(L" test ")).c_str(), L"test");
EXPECT_STREQ(ext::ltrim(std::string(" test ")).c_str(), "test ");
EXPECT_STREQ(ext::ltrim(std::wstring(L" test ")).c_str(), L"test ");
EXPECT_STREQ(ext::rtrim(std::string(" test ")).c_str(), " test");
EXPECT_STREQ(ext::rtrim(std::wstring(L" test ")).c_str(), L" test");
EXPECT_STREQ(ext::trim(" test ").c_str(), "test");
EXPECT_STREQ(ext::trim(L" test ").c_str(), L"test");
EXPECT_STREQ(ext::ltrim(" test ").c_str(), "test ");
EXPECT_STREQ(ext::ltrim(L" test ").c_str(), L"test ");
EXPECT_STREQ(ext::rtrim(" test ").c_str(), " test");
EXPECT_STREQ(ext::rtrim(L" test ").c_str(), L" test");
#if (!defined(_MSC_VER)) || (defined(_MSC_VER) && _MSC_VER > 1600)
const std::string const_str = " test ";
EXPECT_STREQ(ext::trim(const_str).c_str(), "test");
const std::wstring const_wstr = L" test ";
EXPECT_STREQ(ext::trim(const_wstr).c_str(), L"test");
#endif
}
TEST(string_test, search_test) {
EXPECT_TRUE(ext::search("hello, world :-)", "world"));
EXPECT_TRUE(ext::search("hello, world :-)", "World"));
EXPECT_TRUE(ext::search("hello, world :-)", "world", true));
EXPECT_FALSE(ext::search("hello, world :-)", "World", true));
}
TEST(string_test, equal_test) {
EXPECT_TRUE(ext::equal("hello, world :-)", "hello, world :-)"));
EXPECT_TRUE(ext::equal("hello, world :-)", "hello, World :-)"));
EXPECT_TRUE(ext::equal("hello, world :-)", "hello, world :-)", true));
EXPECT_FALSE(ext::equal("hello, world :-)", "hello, World :-)", true));
}
TEST(string_test, replace_all_test) {
std::string str = "hello, world :-)";
EXPECT_STREQ(ext::replace_all(str, ":-", ";-").c_str(), "hello, world ;-)");
std::wstring str_w = L"hello, world :-)";
EXPECT_STREQ(ext::replace_all(str_w, L":-", L";-").c_str(),
L"hello, world ;-)");
}
TEST(string_test, split_test) {
std::vector<std::string> list = ext::split("a,b,c,d", ",");
EXPECT_EQ(list.size(), 4);
EXPECT_EQ(list[0], "a");
EXPECT_EQ(list[1], "b");
EXPECT_EQ(list[2], "c");
EXPECT_EQ(list[3], "d");
}
#ifdef __cpp_lambdas
TEST(string_test, split_int_test) {
std::vector<int> list =
ext::split<int>("10,20,30,40", ",",
[](const std::string &val) { return std::stoul(val); });
EXPECT_EQ(list.size(), 4);
EXPECT_EQ(list[0], 10);
EXPECT_EQ(list[1], 20);
EXPECT_EQ(list[2], 30);
EXPECT_EQ(list[3], 40);
}
#ifndef CXX_STD_ANY_NOT_SUPPORTED
#include <any>
TEST(string_test, split_any_test) {
auto list = ext::split<std::any>("10,b,30,c", ",",
[](const std::string &val) -> std::any {
try {
return std::stoul(val);
} catch (const std::exception &) {
}
return val;
});
EXPECT_EQ(list.size(), 4);
EXPECT_EQ(std::any_cast<unsigned long>(list[0]), 10);
EXPECT_EQ(std::any_cast<std::string>(list[1]), "b");
EXPECT_EQ(std::any_cast<unsigned long>(list[2]), 30);
EXPECT_EQ(std::any_cast<std::string>(list[3]), "c");
}
#endif
#endif | 38.057613 | 80 | 0.614079 | [
"vector"
] |
efce67beae52719e3f8440a6f6de54c6b1e13eaf | 6,041 | cpp | C++ | sources/libengine/engine/sound.cpp | Gaeldrin/cage | 6399a5cdcb3932e8d422901ce7d72099dc09273c | [
"MIT"
] | null | null | null | sources/libengine/engine/sound.cpp | Gaeldrin/cage | 6399a5cdcb3932e8d422901ce7d72099dc09273c | [
"MIT"
] | null | null | null | sources/libengine/engine/sound.cpp | Gaeldrin/cage | 6399a5cdcb3932e8d422901ce7d72099dc09273c | [
"MIT"
] | null | null | null | #include <cage-core/flatSet.h>
#include <cage-engine/sound.h>
#include <cage-engine/voices.h>
#include <cage-engine/speaker.h>
#include "engine.h"
#include <vector>
#include <robin_hood.h>
namespace cage
{
namespace
{
template<class T>
void eraseUnused(T &map, const FlatSet<uintPtr> &used)
{
auto it = map.begin();
while (it != map.end())
{
if (used.count(it->first))
it++;
else
it = map.erase(it);
}
}
struct EmitSound
{
TransformComponent transform, transformHistory;
SoundComponent sound = {};
uintPtr id = 0;
};
struct EmitListener
{
TransformComponent transform, transformHistory;
ListenerComponent listener = {};
uintPtr id = 0;
};
struct Emit
{
std::vector<EmitListener> listeners;
std::vector<EmitSound> sounds;
uint64 time = 0;
};
struct PrepareListener
{
// todo split by sound category (music / voice over / effect)
Holder<VoicesMixer> mixer;
Holder<Voice> chaining; // register this mixer in the engine effects mixer
robin_hood::unordered_map<uintPtr, Holder<Voice>> voicesMapping;
};
struct SoundPrepareImpl
{
Emit emitBuffers[3];
Emit *emitRead = nullptr, *emitWrite = nullptr;
Holder<SwapBufferGuard> swapController;
InterpolationTimingCorrector itc;
uint64 emitTime = 0;
uint64 dispatchTime = 0;
real interFactor;
robin_hood::unordered_map<uintPtr, PrepareListener> listenersMapping;
explicit SoundPrepareImpl(const EngineCreateConfig &config)
{
SwapBufferGuardCreateConfig cfg(3);
cfg.repeatedReads = true;
swapController = newSwapBufferGuard(cfg);
}
void finalize()
{
listenersMapping.clear();
}
void emit(uint64 time)
{
auto lock = swapController->write();
if (!lock)
{
CAGE_LOG_DEBUG(SeverityEnum::Warning, "engine", "skipping sound emit");
return;
}
emitWrite = &emitBuffers[lock.index()];
ClearOnScopeExit resetEmitWrite(emitWrite);
emitWrite->listeners.clear();
emitWrite->sounds.clear();
emitWrite->time = time;
// emit listeners
for (Entity *e : ListenerComponent::component->entities())
{
EmitListener c;
c.transform = e->value<TransformComponent>(TransformComponent::component);
if (e->has(TransformComponent::componentHistory))
c.transformHistory = e->value<TransformComponent>(TransformComponent::componentHistory);
else
c.transformHistory = c.transform;
c.listener = e->value<ListenerComponent>(ListenerComponent::component);
c.id = (uintPtr)e;
emitWrite->listeners.push_back(c);
}
// emit voices
for (Entity *e : SoundComponent::component->entities())
{
EmitSound c;
c.transform = e->value<TransformComponent>(TransformComponent::component);
if (e->has(TransformComponent::componentHistory))
c.transformHistory = e->value<TransformComponent>(TransformComponent::componentHistory);
else
c.transformHistory = c.transform;
c.sound = e->value<SoundComponent>(SoundComponent::component);
c.id = (uintPtr)e;
emitWrite->sounds.push_back(c);
}
}
void prepare(PrepareListener &l, Holder<Voice> &v, const EmitSound &e)
{
Holder<Sound> s = engineAssets()->get<AssetSchemeIndexSound, Sound>(e.sound.name);
if (!s)
{
v.clear();
return;
}
if (!v)
v = l.mixer->newVoice();
v->sound = s.share();
const transform t = interpolate(e.transformHistory, e.transform, interFactor);
v->position = t.position;
v->startTime = e.sound.startTime;
v->gain = e.sound.gain;
}
void prepare(PrepareListener &l, const EmitListener &e)
{
{ // listener
if (!l.mixer)
{
l.mixer = newVoicesMixer({});
l.chaining = engineEffectsMixer()->newVoice();
l.chaining->callback.bind<VoicesMixer, &VoicesMixer::process>(+l.mixer);
}
Listener &p = l.mixer->listener();
const transform t = interpolate(e.transformHistory, e.transform, interFactor);
p.position = t.position;
p.orientation = t.orientation;
p.rolloffFactor = e.listener.rolloffFactor;
p.gain = e.listener.gain;
}
{ // remove obsolete
FlatSet<uintPtr> used;
used.reserve(emitRead->sounds.size());
for (const EmitSound &s : emitRead->sounds)
if (e.listener.sceneMask & s.sound.sceneMask)
used.insert(e.id);
eraseUnused(l.voicesMapping, used);
}
for (const EmitSound &s : emitRead->sounds)
if (e.listener.sceneMask & s.sound.sceneMask)
prepare(l, l.voicesMapping[s.id], s);
}
void prepare()
{
OPTICK_EVENT("prepare");
{ // remove obsolete
FlatSet<uintPtr> used;
used.reserve(emitRead->listeners.size());
for (const EmitListener &e : emitRead->listeners)
used.insert(e.id);
eraseUnused(listenersMapping, used);
}
for (const EmitListener &e : emitRead->listeners)
prepare(listenersMapping[e.id], e);
}
void tick(uint64 time)
{
auto lock = swapController->read();
if (!lock)
{
CAGE_LOG_DEBUG(SeverityEnum::Warning, "engine", "skipping sound tick");
return;
}
{
emitRead = &emitBuffers[lock.index()];
ClearOnScopeExit resetEmitRead(emitRead);
emitTime = emitRead->time;
dispatchTime = itc(emitTime, time, soundThread().updatePeriod());
interFactor = saturate(real(dispatchTime - emitTime) / controlThread().updatePeriod());
prepare();
}
{
OPTICK_EVENT("speaker");
engineSpeaker()->process(dispatchTime);
}
}
};
SoundPrepareImpl *soundPrepare;
}
void soundEmit(uint64 time)
{
soundPrepare->emit(time);
}
void soundTick(uint64 time)
{
soundPrepare->tick(time);
}
void soundFinalize()
{
soundPrepare->finalize();
}
void soundCreate(const EngineCreateConfig &config)
{
soundPrepare = systemArena().createObject<SoundPrepareImpl>(config);
}
void soundDestroy()
{
systemArena().destroy<SoundPrepareImpl>(soundPrepare);
soundPrepare = nullptr;
}
}
| 24.358871 | 94 | 0.658335 | [
"vector",
"transform"
] |
efcf6567cf11fcb0648874c61550120c1853456e | 822 | cpp | C++ | C++/0764-Largest-Plus-Sign/soln.cpp | wyaadarsh/LeetCode-Solutions | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | [
"MIT"
] | 5 | 2020-07-24T17:48:59.000Z | 2020-12-21T05:56:00.000Z | C++/0764-Largest-Plus-Sign/soln.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | null | null | null | C++/0764-Largest-Plus-Sign/soln.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | 2 | 2020-07-24T17:49:01.000Z | 2020-08-31T19:57:35.000Z | class Solution {
public:
int orderOfLargestPlusSign(int N, vector<vector<int>>& mines) {
int grid[N][N];
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
grid[i][j] = min(min(i, j), min(N - 1 - i, N - 1 - j)) + 1;
}
}
for(vector<int> & mine : mines) {
int r = mine[0], c = mine[1];
for (int idx = 0; idx < N; ++idx) {
grid[r][idx] = min(grid[r][idx], abs(idx - c));
grid[idx][c] = min(grid[idx][c], abs(idx - r));
}
}
int ans = 0;
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
// cout << grid[i][j] << endl;
ans = max(ans, grid[i][j]);
}
}
return ans;
}
};
| 30.444444 | 75 | 0.358881 | [
"vector"
] |
efd011f183864928536100f14ff9f603426c4399 | 3,327 | cpp | C++ | uhk/acm4123.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/acm4123.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/acm4123.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <cctype>
#include <vector>
#include <queue>
#include <string>
#include <iostream>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define foR for
#define for9 for
#define retunr return
#define reutrn return
#define reutnr return
const int inf = (1 << 31) - 1;
const ll INF = (1ll << 63) - 1;
const double PI = acos(-1.0);
const double eps = 1e-7;
const ll MOD = 100000007ll;
const int maxn = 50000 + 100;
const int maxm = 100000 + 100;
int N, M;
struct Node
{
int u;
int v;
int w;
Node() {}
Node(int a, int b, int c) : u(a), v(b), w(c) {}
};
vector<Node> G[maxn];
int dis[maxn][2];
int maxpre[maxn][2];
int stdpmax[maxn][20];
int Log2[maxn];
int stdpmin[maxn][20];
void dfs1(int u, int fa)
{
int i, j;
for (i = 0; i < G[u].size(); i++)
{
int v = G[u][i].v;
int w = G[u][i].w;
if (v == fa)
continue;
dfs1(v, u);
if (dis[u][1] < dis[v][0] + w)
{
dis[u][1] = dis[v][0] + w;
maxpre[u][1] = v;
if (dis[u][0] < dis[u][1])
{
swap(dis[u][0], dis[u][1]);
swap(maxpre[u][0], maxpre[u][1]);
}
}
}
}
void dfs2(int u, int fa)
{
int i, j, k;
for (i = 0; i < G[u].size(); i++)
{
int v = G[u][i].v;
int w = G[u][i].w;
if (v == fa)
continue;
if (maxpre[u][0] == v)
{
if (dis[v][1] < dis[u][1] + w)
{
dis[v][1] = dis[u][1] + w;
maxpre[v][1] = u;
if (dis[v][0] < dis[v][1])
{
swap(dis[v][1], dis[v][0]);
swap(maxpre[v][1], maxpre[v][0]);
}
}
}
else
{
if (dis[v][1] < dis[u][0] + w)
{
dis[v][1] = dis[u][0] + w;
maxpre[v][1] = u;
if (dis[v][0] < dis[v][1])
{
swap(dis[v][1], dis[v][0]);
swap(maxpre[v][1], maxpre[v][0]);
}
}
}
dfs2(v, u);
}
}
void solve_dis()
{
memset(dis, 0, sizeof(dis));
memset(maxpre, 0, sizeof(maxpre));
dfs1(1, 0);
dfs2(1, 0);
}
void initRMQ()
{
int i, j, k;
memset(stdpmax, 0, sizeof(stdpmax));
memset(stdpmin, 0, sizeof(stdpmin));
for (i = 1; i <= N; i++)
stdpmin[i][0] = stdpmax[i][0] = dis[i][0];
Log2[0] = -1;
for (i = 1; i <= N; i++)
{
Log2[i] = (i & (i - 1)) == 0 ? (Log2[i - 1] + 1) : Log2[i - 1];
}
for (j = 1; j <= Log2[N]; j++)
{
for (i = 1; i + (1 << j) - 1 <= N; i++)
{
stdpmax[i][j] = max(stdpmax[i][j - 1], stdpmax[i + (1 << (j - 1))][j - 1]);
stdpmin[i][j] = min(stdpmin[i][j - 1], stdpmin[i + (1 << (j - 1))][j - 1]);
}
}
}
int querymaxRMQ(int l, int r)
{
int k = Log2[r - l + 1];
return max(stdpmax[l][k], stdpmax[r - (1 << k) + 1][k]);
}
int queryminRMQ(int l, int r)
{
int k = Log2[r - l + 1];
return min(stdpmin[l][k], stdpmin[r - (1 << k) + 1][k]);
}
int main()
{
int i, j, k, m, Q, res;
while (scanf("%d %d", &N, &M) != EOF && N + M)
{
for (i = 1; i <= N; i++)
{
G[i].clear();
}
int a, b, c;
for (i = 1; i <= N - 1; i++)
{
scanf("%d %d %d", &a, &b, &c);
G[a].push_back(Node(a, b, c));
G[b].push_back(Node(b, a, c));
}
solve_dis();
initRMQ();
for (m = 1; m <= M; m++)
{
scanf("%d", &Q);
res = 0;
for (i = 1, j = 1; i <= N; i++)
{
while (querymaxRMQ(i, j) - queryminRMQ(i, j) <= Q && j <= N)
{
j++;
}
if (res < j - i)
res = j - i;
}
printf("%d\n", res);
}
}
return 0;
} | 18.903409 | 78 | 0.481515 | [
"vector"
] |
efd036d843b5f006cd376e77eb90537bb9335f9f | 18,741 | cpp | C++ | Tests/48/Test.cpp | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Tests/48/Test.cpp | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Tests/48/Test.cpp | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
// TEST Foundation::Memory
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Characters/String.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Memory/BLOB.h"
#include "Stroika/Foundation/Memory/Bits.h"
#include "Stroika/Foundation/Memory/ObjectFieldUtilities.h"
#include "Stroika/Foundation/Memory/Optional.h"
#include "Stroika/Foundation/Memory/SharedByValue.h"
#include "Stroika/Foundation/Memory/SharedPtr.h"
#include "../TestHarness/NotCopyable.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using std::byte;
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Memory;
using namespace TestHarness;
namespace {
void Test1_Optional ()
{
{
using Characters::String;
optional<String> x;
x = String{L"x"};
}
{
optional<int> x;
VerifyTestResult (not x.has_value ());
x = 1;
VerifyTestResult (x.has_value ());
VerifyTestResult (*x == 1);
}
{
// Careful about self-assignment
optional<int> x;
x = 3;
x = max (*x, 1);
VerifyTestResult (x == 3);
}
auto testOptionalOfThingNotCopyable = [] () {
{
optional<NotCopyable> n1;
VerifyTestResult (not n1.has_value ());
optional<NotCopyable> n2{NotCopyable ()}; // use r-value reference to move
VerifyTestResult (n2.has_value ());
}
{
[[maybe_unused]] optional<NotCopyable> a;
optional<NotCopyable> a1{NotCopyable ()};
a1 = NotCopyable ();
}
};
testOptionalOfThingNotCopyable ();
{
optional<int> x;
if (x) {
VerifyTestResult (false);
}
}
{
optional<int> x;
if (optional<int> y = x) {
VerifyTestResult (false);
}
}
{
optional<int> x = 3;
if (optional<int> y = x) {
VerifyTestResult (y == 3);
}
else {
VerifyTestResult (false);
}
}
{
float* d1 = nullptr;
double* d2 = nullptr;
VerifyTestResult (not OptionalFromNullable (d1).has_value ());
VerifyTestResult (not OptionalFromNullable (d2).has_value ());
}
{
constexpr optional<int> x{1};
VerifyTestResult (x == 1);
}
{
optional<int> d;
[[maybe_unused]] optional<double> t1 = d; // no warnings - this direction OK
[[maybe_unused]] optional<double> t2 = optional<double> (d); // ""
}
{
[[maybe_unused]] optional<double> d;
//Optional<uint64_t> t1 = d; // should generate warning or error
// SKIP SINCE SWITCH TO C++ optional - generates warning - optional<uint64_t> t2 = optional<uint64_t> (d); // should not
}
{
optional<int> x = 1;
VerifyTestResult (Characters::ToString (x) == L"1");
}
{
// empty optional < any other value
VerifyTestResult (optional<int>{} < -9999);
VerifyTestResult (optional<int>{-9999} > optional<int>{});
}
}
void Test2_SharedByValue ()
{
using Memory::BLOB;
// par Example Usage from doc header
SharedByValue<vector<byte>> b{BLOB::Hex ("abcd1245").Repeat (100).As<vector<byte>> ()};
SharedByValue<vector<byte>> c = b; // copied by reference until 'c' or 'b' changed values
VerifyTestResult (c.cget () == b.cget ());
}
void Test_4_Optional_Of_Mapping_Copy_Problem_ ()
{
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Containers;
Mapping<int, float> ml1, ml2;
ml1 = ml2;
optional<Mapping<int, float>> ol1, ol2;
if (ol2.has_value ()) {
ml1 = *ol2;
}
ol1 = ml1;
optional<Mapping<int, float>> xxxx2 (ml1);
// fails to compile prior to 2013-09-09
optional<Mapping<int, float>> xxxx1 (ol1);
// fails to compile prior to 2013-09-09
ol1 = ol2;
}
// temporarily put this out here to avoid MSVC compiler bug -- LGP 2014-02-26
// SB nested inside function where used...
// --LGP 2014-02-26
namespace {
struct X_ {
int a = 0;
};
struct jimStdSP_ : std::enable_shared_from_this<jimStdSP_> {
int field = 1;
shared_ptr<jimStdSP_> doIt ()
{
return shared_from_this ();
}
};
struct jimMIXStdSP_ : X_, std::enable_shared_from_this<jimMIXStdSP_> {
int field = 1;
shared_ptr<jimMIXStdSP_> doIt ()
{
return shared_from_this ();
}
};
struct jimStkSP_ : Memory::enable_shared_from_this<jimStkSP_> {
int field = 1;
SharedPtr<jimStkSP_> doIt ()
{
return shared_from_this ();
}
};
struct jimMIStkSP_ : X_, Memory::enable_shared_from_this<jimMIStkSP_> {
int field = 1;
SharedPtr<jimMIStkSP_> doIt ()
{
return shared_from_this ();
}
};
}
void Test_5_SharedPtr ()
{
{
SharedPtr<int> p (new int (3));
VerifyTestResult (p.use_count () == 1);
VerifyTestResult (p.unique ());
VerifyTestResult (*p == 3);
}
{
static int nCreates = 0;
static int nDestroys = 0;
struct COUNTED_OBJ {
COUNTED_OBJ ()
{
++nCreates;
}
COUNTED_OBJ (const COUNTED_OBJ&)
{
++nCreates;
}
~COUNTED_OBJ ()
{
++nDestroys;
}
const COUNTED_OBJ& operator= (const COUNTED_OBJ&) = delete;
};
struct CNT2 : COUNTED_OBJ {
};
{
SharedPtr<COUNTED_OBJ> p (new COUNTED_OBJ ());
}
VerifyTestResult (nCreates == nDestroys);
{
SharedPtr<COUNTED_OBJ> p (SharedPtr<CNT2> (new CNT2 ()));
VerifyTestResult (nCreates == nDestroys + 1);
}
VerifyTestResult (nCreates == nDestroys);
}
{
shared_ptr<jimStdSP_> x (new jimStdSP_ ());
shared_ptr<jimStdSP_> y = x->doIt ();
VerifyTestResult (x == y);
}
{
shared_ptr<jimMIXStdSP_> x (new jimMIXStdSP_ ());
shared_ptr<jimMIXStdSP_> y = x->doIt ();
shared_ptr<X_> xx = x;
VerifyTestResult (x == y);
}
{
SharedPtr<jimStkSP_> x (new jimStkSP_ ());
SharedPtr<jimStkSP_> y = x->doIt ();
VerifyTestResult (x == y);
}
{
SharedPtr<jimMIStkSP_> x (new jimMIStkSP_ ());
SharedPtr<jimMIStkSP_> y = x->doIt ();
SharedPtr<X_> xx = x;
VerifyTestResult (x == y);
}
}
}
namespace {
void Test_6_Bits_ ()
{
{
VerifyTestResult (BitSubstring (0x3, 0, 1) == 1);
VerifyTestResult (BitSubstring (0x3, 1, 2) == 1);
VerifyTestResult (BitSubstring (0x3, 2, 3) == 0);
VerifyTestResult (BitSubstring (0x3, 0, 3) == 0x3);
VerifyTestResult (BitSubstring (0xff, 0, 8) == 0xff);
VerifyTestResult (BitSubstring (0xff, 8, 16) == 0x0);
}
{
VerifyTestResult (Bit (0) == 0x1);
VerifyTestResult (Bit (1) == 0x2);
VerifyTestResult (Bit (3) == 0x8);
VerifyTestResult (Bit (15) == 0x8000);
VerifyTestResult (Bit<int> (1, 2) == 0x6);
VerifyTestResult (Bit<int> (1, 2, 15) == 0x8006);
}
}
}
namespace {
void Test_7_BLOB_ ()
{
{
vector<uint8_t> b = {1, 2, 3, 4, 5};
Memory::BLOB bl = b;
VerifyTestResult (bl.size () == 5 and b == bl.As<vector<uint8_t>> ());
VerifyTestResult (bl.size () == 5 and bl.As<vector<uint8_t>> () == b);
}
{
Memory::BLOB bl{1, 2, 3, 4, 5};
VerifyTestResult (bl.size () == 5 and bl.As<vector<uint8_t>> () == (vector<uint8_t>{1, 2, 3, 4, 5}));
}
{
#if (defined(__clang_major__) && !defined(__APPLE__) && (__clang_major__ >= 7)) || (defined(__clang_major__) && defined(__APPLE__) && (__clang_major__ >= 10))
DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wself-assign-overloaded\"")
#endif
DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wself-move\"")
Memory::BLOB bl{1, 2, 3, 4, 5};
bl = bl; // assure self-assign OK
bl = move (bl);
VerifyTestResult (bl.size () == 5 and bl.As<vector<uint8_t>> () == (vector<uint8_t>{1, 2, 3, 4, 5}));
DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wself-move\"")
#if (defined(__clang_major__) && !defined(__APPLE__) && (__clang_major__ >= 7)) || (defined(__clang_major__) && defined(__APPLE__) && (__clang_major__ >= 10))
DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wself-assign-overloaded\"")
#endif
}
{
const char kSrc1_[] = "This is a very good test of a very good test";
const char kSrc2_[] = "";
const char kSrc3_[] = "We eat wiggly worms. That was a very good time to eat the worms. They are awesome!";
const char kSrc4_[] = "0123456789";
VerifyTestResult (Memory::BLOB ((const byte*)kSrc1_, (const byte*)kSrc1_ + ::strlen (kSrc1_)) == Memory::BLOB::Raw (kSrc1_, kSrc1_ + strlen (kSrc1_)));
VerifyTestResult (Memory::BLOB ((const byte*)kSrc2_, (const byte*)kSrc2_ + ::strlen (kSrc2_)) == Memory::BLOB::Raw (kSrc2_, kSrc2_ + strlen (kSrc2_)));
VerifyTestResult (Memory::BLOB ((const byte*)kSrc3_, (const byte*)kSrc3_ + ::strlen (kSrc3_)) == Memory::BLOB::Raw (kSrc3_, kSrc3_ + strlen (kSrc3_)));
VerifyTestResult (Memory::BLOB ((const byte*)kSrc4_, (const byte*)kSrc4_ + ::strlen (kSrc4_)) == Memory::BLOB::Raw (kSrc4_, kSrc4_ + strlen (kSrc4_)));
VerifyTestResult (Memory::BLOB ((const byte*)kSrc1_, (const byte*)kSrc1_ + ::strlen (kSrc1_)) == Memory::BLOB::Raw (kSrc1_, kSrc1_ + NEltsOf (kSrc1_) - 1));
VerifyTestResult (Memory::BLOB ((const byte*)kSrc2_, (const byte*)kSrc2_ + ::strlen (kSrc2_)) == Memory::BLOB::Raw (kSrc2_, kSrc2_ + NEltsOf (kSrc2_) - 1));
VerifyTestResult (Memory::BLOB ((const byte*)kSrc3_, (const byte*)kSrc3_ + ::strlen (kSrc3_)) == Memory::BLOB::Raw (kSrc3_, kSrc3_ + NEltsOf (kSrc3_) - 1));
VerifyTestResult (Memory::BLOB ((const byte*)kSrc4_, (const byte*)kSrc4_ + ::strlen (kSrc4_)) == Memory::BLOB::Raw (kSrc4_, kSrc4_ + NEltsOf (kSrc4_) - 1));
}
{
using Memory::BLOB;
VerifyTestResult ((BLOB::Hex ("61 70 70 6c 65 73 20 61 6e 64 20 70 65 61 72 73 0d 0a") == BLOB{0x61, 0x70, 0x70, 0x6c, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x70, 0x65, 0x61, 0x72, 0x73, 0x0d, 0x0a}));
VerifyTestResult ((BLOB::Hex ("4a 94 99 ac 55 f7 a2 8b 1b ca 75 62 f6 9a cf de 41 9d") == BLOB{0x4a, 0x94, 0x99, 0xac, 0x55, 0xf7, 0xa2, 0x8b, 0x1b, 0xca, 0x75, 0x62, 0xf6, 0x9a, 0xcf, 0xde, 0x41, 0x9d}));
VerifyTestResult ((BLOB::Hex ("68 69 20 6d 6f 6d 0d 0a") == BLOB{0x68, 0x69, 0x20, 0x6d, 0x6f, 0x6d, 0x0d, 0x0a}));
VerifyTestResult ((BLOB::Hex ("29 14 4a db 4e ce 20 45 09 56 e8 13 65 2f e8 d6") == BLOB{0x29, 0x14, 0x4a, 0xdb, 0x4e, 0xce, 0x20, 0x45, 0x09, 0x56, 0xe8, 0x13, 0x65, 0x2f, 0xe8, 0xd6}));
VerifyTestResult ((BLOB::Hex ("29144adb4ece20450956e813652fe8d6") == BLOB{0x29, 0x14, 0x4a, 0xdb, 0x4e, 0xce, 0x20, 0x45, 0x09, 0x56, 0xe8, 0x13, 0x65, 0x2f, 0xe8, 0xd6}));
VerifyTestResult ((BLOB::Hex ("29144adb4ece20450956e813652fe8d6").AsHex () == L"29144adb4ece20450956e813652fe8d6"));
}
}
}
namespace {
namespace Test9_SmallStackBuffer_ {
void DoTest ()
{
{
SmallStackBuffer<int> x0{0};
SmallStackBuffer<int> x1{x0};
x0 = x1;
}
{
// Test using String elements, since those will test construction/reserve logic
using Characters::String;
SmallStackBuffer<String> buf1{3};
for (int i = 0; i < 1000; i++) {
buf1.push_back (String{L"hi mom"});
}
SmallStackBuffer<String> buf2{buf1};
buf1.resize (0);
}
{
SmallStackBuffer<int> x0{4};
SmallStackBuffer<int> assign2;
assign2 = x0;
VerifyTestResult (x0.size () == assign2.size ()); // test regression fixed 2019-03-20
VerifyTestResult (x0.size () == 4);
}
}
}
}
namespace {
namespace Test10_OptionalSelfAssign_ {
void DoTest ()
{
{
#if (defined(__clang_major__) && !defined(__APPLE__) && (__clang_major__ >= 7)) || (defined(__clang_major__) && defined(__APPLE__) && (__clang_major__ >= 10))
DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wself-assign-overloaded\""); // explicitly assigning value of variable ... to itself
#endif
// ASSIGN
{
optional<int> x;
x = x;
}
{
optional<Characters::String> x;
x = x;
}
{
optional<int> x{1};
x = x;
}
{
optional<Characters::String> x{L"x"};
x = x;
}
}
// note - see https://stroika.atlassian.net/browse/STK-556 - we DON'T support Optional self-move
#if (defined(__clang_major__) && !defined(__APPLE__) && (__clang_major__ >= 7)) || (defined(__clang_major__) && defined(__APPLE__) && (__clang_major__ >= 10))
DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wself-assign-overloaded\"");
#endif
}
}
}
namespace {
namespace Test11_ObjectFieldUtilities_ {
void DoTest ();
namespace Private_ {
struct X1 {
int a;
int b;
};
struct X2 {
public:
int a;
private:
int b;
private:
friend void Test11_ObjectFieldUtilities_::DoTest ();
};
}
void DoTest ()
{
{
VerifyTestResult (
ConvertPointerToDataMemberToOffset (&Private_::X1::a) == 0 or ConvertPointerToDataMemberToOffset (&Private_::X1::b) == 0);
VerifyTestResult (
ConvertPointerToDataMemberToOffset (&Private_::X1::a) != 0 or ConvertPointerToDataMemberToOffset (&Private_::X1::b) != 0);
}
{
Private_::X1 t;
static_assert (is_standard_layout_v<Private_::X1>);
void* aAddr = &t.a;
void* bAddr = &t.b;
VerifyTestResult (GetObjectOwningField (aAddr, &Private_::X1::a) == &t);
VerifyTestResult (GetObjectOwningField (bAddr, &Private_::X1::b) == &t);
}
{
// Check and warning but since X2 is not standard layout, this isn't guaranteed to work
Private_::X2 t;
static_assert (not is_standard_layout_v<Private_::X2>);
void* aAddr = &t.a;
void* bAddr = &t.b;
VerifyTestResultWarning (GetObjectOwningField (aAddr, &Private_::X2::a) == &t);
VerifyTestResultWarning (GetObjectOwningField (bAddr, &Private_::X2::b) == &t);
}
}
}
}
namespace {
namespace Test12_OffsetOf_ {
struct Person {
int firstName;
int lastName;
};
struct NotDefaultConstructible {
NotDefaultConstructible () = delete;
constexpr NotDefaultConstructible (int) {}
int firstName{};
int lastName{};
};
void DoTest ()
{
{
[[maybe_unused]] size_t kOffset_ = OffsetOf (&Person::lastName);
VerifyTestResult (OffsetOf (&Person::firstName) == 0);
}
{
[[maybe_unused]] size_t kOffset_ = OffsetOf (&NotDefaultConstructible::lastName);
VerifyTestResult (OffsetOf (&NotDefaultConstructible::firstName) == 0);
}
#if 0
// disabled til we can figure out a way to get this constexpr version of OffsetOf() working...
{
[[maybe_unused]] constexpr size_t kOffsetx_ = OffsetOf_Constexpr (&Person::lastName);
static_assert (OffsetOf_Constexpr (&Person::firstName) == 0);
}
#endif
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test1_Optional ();
Test2_SharedByValue ();
Test_4_Optional_Of_Mapping_Copy_Problem_ ();
Test_5_SharedPtr ();
Test_6_Bits_ ();
Test_7_BLOB_ ();
Test9_SmallStackBuffer_::DoTest ();
Test10_OptionalSelfAssign_::DoTest ();
Test11_ObjectFieldUtilities_::DoTest ();
Test12_OffsetOf_::DoTest ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
| 38.091463 | 217 | 0.523878 | [
"vector"
] |
efd8e1a08566bb4e28c98ad9afeb53941c3996e5 | 5,320 | cc | C++ | models/processor/spx/core.cc | Basseuph/manifold | 99779998911ed7e8b8ff6adacc7f93080409a5fe | [
"BSD-3-Clause"
] | 8 | 2016-01-22T18:28:48.000Z | 2021-05-07T02:27:21.000Z | models/processor/spx/core.cc | Basseuph/manifold | 99779998911ed7e8b8ff6adacc7f93080409a5fe | [
"BSD-3-Clause"
] | 3 | 2016-04-15T02:58:58.000Z | 2017-01-19T17:07:34.000Z | models/processor/spx/core.cc | Basseuph/manifold | 99779998911ed7e8b8ff6adacc7f93080409a5fe | [
"BSD-3-Clause"
] | 10 | 2015-12-11T04:16:55.000Z | 2019-05-25T20:58:13.000Z | #ifdef USE_QSIM
#include <string.h>
#include <libconfig.h++>
#include <sys/time.h>
#include <sstream>
#include "core.h"
#include "pipeline.h"
#include "outorder.h"
#include "inorder.h"
using namespace std;
using namespace libconfig;
using namespace manifold;
using namespace manifold::kernel;
using namespace manifold::spx;
spx_core_t::spx_core_t(const int nodeID, const char *configFileName, const int coreID) :
node_id(nodeID),
core_id(coreID),
clock_cycle(0),
active(true),
qsim_proxy_request_sent(false)
{
Config parser;
try {
parser.readFile(configFileName);
parser.setAutoConvert(true);
}
catch(FileIOException e) {
fprintf(stdout,"cannot read configuration file %s\n",configFileName);
exit(EXIT_FAILURE);
}
catch(ParseException e) {
fprintf(stdout,"cannot parse configuration file %s\n",configFileName);
exit(EXIT_FAILURE);
}
try {
// Pipeline model
const char *pipeline_model = parser.lookup("pipeline");
if(!strcasecmp(pipeline_model,"outorder"))
pipeline = new outorder_t(this,&parser);
else if(!strcasecmp(pipeline_model,"inorder"))
pipeline = new inorder_t(this,&parser);
else {
fprintf(stdout,"unknown core type %s\n",pipeline_model);
exit(EXIT_FAILURE);
}
// Qsim proxy
qsim_proxy = new spx_qsim_proxy_t(pipeline);
pipeline->set_qsim_proxy(qsim_proxy);
}
catch(SettingNotFoundException e) {
fprintf(stdout,"%s not defined\n",e.getPath());
exit(EXIT_FAILURE);
}
catch(SettingTypeException e) {
fprintf(stdout,"%s has incorrect type\n",e.getPath());
exit(EXIT_FAILURE);
}
}
spx_core_t::~spx_core_t() {
delete qsim_proxy;
delete pipeline;
}
int spx_core_t::get_qsim_osd_state() const {
return pipeline->Qsim_osd_state;
}
void spx_core_t::turn_on() {
active = true;
}
void spx_core_t::turn_off() {
active = false;
}
void spx_core_t::tick()
{
clock_cycle = m_clk->NowTicks();
if(clock_cycle) pipeline->stats.interval.clock_cycle++;
pipeline->commit();
pipeline->memory();
pipeline->execute();
pipeline->allocate();
if(active) pipeline->frontend();
#ifdef LIBKITFOX
pipeline->counter.frontend_undiff.switching++;
pipeline->counter.scheduler_undiff.switching++;
pipeline->counter.ex_int_undiff.switching++;
pipeline->counter.ex_fp_undiff.switching++;
pipeline->counter.lsu_undiff.switching++;
pipeline->counter.undiff.switching++;
print_stats(100000, stderr);
#else
// This will periodically print the stats to show the progress of simulation -- for debugging
print_stats(100000, stdout);
#endif
if (get_qsim_osd_state() == QSIM_OSD_TERMINATED) {
fprintf(stdout, "SPX core %d out of insn", core_id);
manifold::kernel::Manifold::Terminate();
}
}
void spx_core_t::print_stats(uint64_t sampling_period, FILE *LogFile)
{
if(clock_cycle&&((clock_cycle%sampling_period) == 0)) {
fprintf(LogFile,"clk_cycle= %3.1lfM | core%d | \
IPC= %lf ( %lu / %lu ), \
avgIPC= %lf ( %lu / %lu )\n",
(double)clock_cycle/1e6, core_id,
(double)pipeline->stats.interval.uop_count / (double)pipeline->stats.interval.clock_cycle,
pipeline->stats.interval.uop_count,
pipeline->stats.interval.clock_cycle,
(double)pipeline->stats.uop_count / (double)clock_cycle,
pipeline->stats.uop_count,
clock_cycle);
reset_interval_stats();
}
}
void spx_core_t::reset_interval_stats()
{
pipeline->stats.interval.clock_cycle = 0;
pipeline->stats.interval.Mop_count = 0;
pipeline->stats.interval.uop_count = 0;
}
void spx_core_t::print_stats(std::ostream& out)
{
out << "************ SPX Core " << core_id << " [node " << node_id << "] stats *************" << endl;
out << " Total clock cycles: " << (double)clock_cycle/1e6 << "M" << endl;
out << " avgIPC = " << (double)pipeline->stats.uop_count / (double) clock_cycle << endl; }
void spx_core_t::handle_cache_response(int temp, cache_request_t *cache_request)
{
pipeline->handle_cache_response(temp,cache_request);
}
void spx_core_t::send_qsim_proxy_request()
{
if(!qsim_proxy_request_sent) { /* Do not send multiple requests */
qsim_proxy_request_sent = true;
qsim_proxy_request_t *qsim_proxy_request = new qsim_proxy_request_t(core_id, getComponentId());
#ifdef DEBUG_NEW_QSIM_1
std::cerr << "( Core " << std::dec << core_id << " ) [send request to qsim] @ " << std::dec << clock_cycle << std::endl << std::flush;
#endif
Send(OUT_TO_QSIM, qsim_proxy_request);
}
}
void spx_core_t::handle_qsim_response(int temp, qsim_proxy_request_t *qsim_proxy_request)
{
assert(qsim_proxy_request->get_core_id() == core_id);
if (qsim_proxy_request->is_extended() == false) {
assert(qsim_proxy_request_sent);
qsim_proxy_request_sent = false;
}
/* qsim_proxy_request is deleted here */
qsim_proxy->handle_qsim_response(qsim_proxy_request);
}
#endif // USE_QSIM
| 30.4 | 142 | 0.643797 | [
"model"
] |
efde9ea3cdbab41b6c5adde0f16adc82e816cc6f | 5,207 | cpp | C++ | Engine/Source/Runtime/Launch/Private/IOS/LaunchIOS.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Launch/Private/IOS/LaunchIOS.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Launch/Private/IOS/LaunchIOS.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#import <UIKit/UIKit.h>
#include "LaunchPrivatePCH.h"
#include "IOSAppDelegate.h"
#include "IOSView.h"
#include "IOSCommandLineHelper.h"
#include "GameLaunchDaemonMessageHandler.h"
#include "AudioDevice.h"
FEngineLoop GEngineLoop;
FGameLaunchDaemonMessageHandler GCommandSystem;
void FAppEntry::Suspend()
{
if (GEngine && GEngine->GetMainAudioDevice())
{
GEngine->GetMainAudioDevice()->SuspendContext();
}
}
void FAppEntry::Resume()
{
if (GEngine && GEngine->GetMainAudioDevice())
{
GEngine->GetMainAudioDevice()->ResumeContext();
}
}
void FAppEntry::PreInit(IOSAppDelegate* AppDelegate, UIApplication* Application)
{
// make a controller object
AppDelegate.IOSController = [[IOSViewController alloc] init];
// property owns it now
[AppDelegate.IOSController release];
// point to the GL view we want to use
AppDelegate.RootView = [AppDelegate.IOSController view];
if (AppDelegate.OSVersion >= 6.0f)
{
// this probably works back to OS4, but would need testing
[AppDelegate.Window setRootViewController:AppDelegate.IOSController];
}
else
{
[AppDelegate.Window addSubview:AppDelegate.RootView];
}
// reset badge count on launch
Application.applicationIconBadgeNumber = 0;
}
static void MainThreadInit()
{
IOSAppDelegate* AppDelegate = [IOSAppDelegate GetDelegate];
// Size the view appropriately for any potentially dynamically attached displays,
// prior to creating any framebuffers
CGRect MainFrame = [[UIScreen mainScreen] bounds];
// we need to swap if compiled with ios7, or compiled with ios8 and running on 7
#ifndef __IPHONE_8_0
bool bDoLandscapeSwap = true;
#else
bool bDoLandscapeSwap = AppDelegate.OSVersion < 8.0f;
#endif
if (bDoLandscapeSwap && !AppDelegate.bDeviceInPortraitMode)
{
Swap(MainFrame.size.width, MainFrame.size.height);
}
// @todo: use code similar for presizing for secondary screens
// CGRect FullResolutionRect =
// CGRectMake(
// 0.0f,
// 0.0f,
// GSystemSettings.bAllowSecondaryDisplays ?
// Max<float>(MainFrame.size.width, GSystemSettings.SecondaryDisplayMaximumWidth) :
// MainFrame.size.width,
// GSystemSettings.bAllowSecondaryDisplays ?
// Max<float>(MainFrame.size.height, GSystemSettings.SecondaryDisplayMaximumHeight) :
// MainFrame.size.height
// );
CGRect FullResolutionRect = MainFrame;
AppDelegate.IOSView = [[FIOSView alloc] initWithFrame:FullResolutionRect];
AppDelegate.IOSView.clearsContextBeforeDrawing = NO;
AppDelegate.IOSView.multipleTouchEnabled = YES;
// add it to the window
[AppDelegate.RootView addSubview:AppDelegate.IOSView];
// initialize the backbuffer of the view (so the RHI can use it)
[AppDelegate.IOSView CreateFramebuffer:YES];
}
void FAppEntry::PlatformInit()
{
// call a function in the main thread to do some processing that needs to happen there, now that the .ini files are loaded
dispatch_async(dispatch_get_main_queue(), ^{ MainThreadInit(); });
// wait until the GLView is fully initialized, so the RHI can be initialized
IOSAppDelegate* AppDelegate = [IOSAppDelegate GetDelegate];
while (!AppDelegate.IOSView || !AppDelegate.IOSView->bIsInitialized)
{
FPlatformProcess::Sleep(0.001f);
}
// set the GL context to this thread
[AppDelegate.IOSView MakeCurrent];
}
void FAppEntry::Init()
{
FPlatformProcess::SetRealTimeMode();
//extern TCHAR GCmdLine[16384];
GEngineLoop.PreInit(FCommandLine::Get());
// initialize messaging subsystem
FModuleManager::LoadModuleChecked<IMessagingModule>("Messaging");
//Set up the message handling to interface with other endpoints on our end.
NSLog(@"%s", "Initializing ULD Communications in game mode\n");
GCommandSystem.Init();
GLog->SetCurrentThreadAsMasterThread();
// start up the engine
GEngineLoop.Init();
}
static FSuspendRenderingThread* SuspendThread = NULL;
void FAppEntry::Tick()
{
if (SuspendThread != NULL)
{
delete SuspendThread;
SuspendThread = NULL;
FPlatformProcess::SetRealTimeMode();
}
// tick the engine
GEngineLoop.Tick();
}
void FAppEntry::SuspendTick()
{
if (!SuspendThread)
{
SuspendThread = new FSuspendRenderingThread(true);
}
FPlatformProcess::Sleep(0.1f);
}
void FAppEntry::Shutdown()
{
NSLog(@"%s", "Shutting down Game ULD Communications\n");
GCommandSystem.Shutdown();
// kill the engine
GEngineLoop.Exit();
}
FString GSavedCommandLine;
int main(int argc, char *argv[])
{
for(int Option = 1; Option < argc; Option++)
{
GSavedCommandLine += TEXT(" ");
GSavedCommandLine += UTF8_TO_TCHAR(argv[Option]);
}
FIOSCommandLineHelper::InitCommandArgs(FString());
#if !UE_BUILD_SHIPPING
if (FParse::Param(FCommandLine::Get(), TEXT("WaitForDebugger")))
{
while(!FPlatformMisc::IsDebuggerPresent())
{
FPlatformMisc::LowLevelOutputDebugString(TEXT("Waiting for debugger...\n"));
FPlatformProcess::Sleep(1.f);
}
FPlatformMisc::LowLevelOutputDebugString(TEXT("Debugger attached.\n"));
}
#endif
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([IOSAppDelegate class]));
}
} | 25.4 | 123 | 0.729403 | [
"object"
] |
efe423c4a40087aaed5317070572c7505c123cf7 | 18,790 | cpp | C++ | src/MainWindow.cpp | shin0bi-y/silice-text-editor | 1142ab6ce7eff073885d8be745b23d4816405c00 | [
"BSD-2-Clause"
] | 3 | 2021-06-14T12:02:35.000Z | 2021-06-25T16:31:42.000Z | src/MainWindow.cpp | shin0bi-y/silice-text-editor | 1142ab6ce7eff073885d8be745b23d4816405c00 | [
"BSD-2-Clause"
] | null | null | null | src/MainWindow.cpp | shin0bi-y/silice-text-editor | 1142ab6ce7eff073885d8be745b23d4816405c00 | [
"BSD-2-Clause"
] | 1 | 2021-05-20T13:32:43.000Z | 2021-05-20T13:32:43.000Z | #include "MainWindow.h"
#include <iostream>
#include <filesystem>
#include <string>
#include <LibSL.h>
#include <LibSL_gl.h>
#include "imgui.h"
#include "imgui_internal.h"
#include "FileDialog.h"
#include "../libs/implot/implot.h"
#include "FST/FSTReader.h"
#include "sourcePath.h"
#include "FSTWindow.h"
#include <nlohmann/json.hpp>
#include <thread>
#include <mutex>
using json = nlohmann::json;
namespace fs = std::filesystem;
// Todo : set fileFullPath when doing "make debug" to show the file name in the editor
ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_PassthruCentralNode;
ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar
| ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove
| ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
bool p_open_dockspace = true;
bool p_open_editor = true;
static GLuint g_FontTexture;
static ImFont *font_general;
static ImFont *font_code; // font used for the TextEditor's code
std::map<std::string, bool> checked_algos;
bool show_fullpath = false;
//-------------------------------------------------------
static bool ImGui_Impl_CreateFontsTexture(const std::string &general_font_name, const std::string &code_font_name)
{
// Build texture atlas
ImGuiIO &io = ::ImGui::GetIO();
ImFontConfig font_cfg = ImFontConfig();
font_cfg.SizePixels = 22;
io.Fonts->AddFontDefault(&font_cfg);
return true;
}
//-------------------------------------------------------
void MainWindow::ShowDockSpace()
{
static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_PassthruCentralNode;
// We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into,
// because it would be confusing to have two docking targets within each others.
ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->Pos);
ImGui::SetNextWindowSize(viewport->Size);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
// When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background and handle the pass-thru hole, so we ask Begin() to not render a background.
if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) {
window_flags |= ImGuiWindowFlags_NoBackground;
}
// Important: note that we proceed even if Begin() returns false (aka window is collapsed).
// This is because we want to keep our DockSpace() active. If a DockSpace() is inactive,
// all active windows docked into it will lose their parent and become undocked.
// We cannot preserve the docking relationship between an active window and an inactive docking, otherwise
// any change of dockspace/settings would lead to windows being stuck in limbo and never being visible.
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace", nullptr, window_flags);
ImGui::PopStyleVar();
ImGui::PopStyleVar(2);
// DockSpace
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)
{
ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
static auto first_time = true;
if (first_time)
{
first_time = false;
ImGui::DockBuilderRemoveNode(dockspace_id); // clear any previous layout
ImGui::DockBuilderAddNode(dockspace_id, dockspace_flags | ImGuiDockNodeFlags_DockSpace);
ImGui::DockBuilderSetNodeSize(dockspace_id, viewport->Size);
// split the dockspace into 2 nodes -- DockBuilderSplitNode takes in the following args in the following order
// window ID to split, direction, fraction (between 0 and 1), the final two setting let's us choose which id we want (which ever one we DON'T set as NULL, will be returned by the function)
// out_id_at_dir is the id of the node in the direction we specified earlier, out_id_at_opposite_dir is in the opposite direction
auto dock_id_left = ImGui::DockBuilderSplitNode(dockspace_id, ImGuiDir_Left, 0.7f, nullptr, &dockspace_id);
// we now dock our windows into the docking node we made above
ImGui::DockBuilderDockWindow("PlotWindow", dock_id_left);
for (const auto &[filename, editor] : this->editors)
{
ImGui::DockBuilderDockWindow(fs::path(editor.first.file_path).filename().string().c_str(), dockspace_id);
}
ImGui::DockBuilderFinish(dockspace_id);
}
}
bool error = false;
if (ImGui::BeginMenuBar()) {
if (ImGui::BeginMenu("File")) {
/*if (ImGui::MenuItem("Open fst")) {
auto fullpath = openFileDialog(OFD_FILTER_ALL);
if (!fullpath.empty()) {
fstWindow.load(fullpath, this->editors, this->lp);
std::cout << "file " << fullpath << " opened" << std::endl;
}
}
ImGui::Separator();
*/
if (ImGui::MenuItem("Load session")) {
if (exists("debugger.dat")) {
std::ifstream stream("debugger.dat");
json data;
stream >> data;
fstWindow.load(data, this->editors, this->lp);
std::cout << "debug opened with file " << data["filePath"] << std::endl;
} else {
error = true;
}
}
if (ImGui::MenuItem("Save session", nullptr, false, fstWindow.reader())) {
if (fstWindow.reader()) {
std::ofstream save("/debugger.dat");
json fstWindowJSON = fstWindow.save();
//std::cout << std::setw(4) << fstWindowJSON << std::endl;
save << std::setw(4) << fstWindowJSON << std::endl;
}
}
ImGui::Separator();
if (ImGui::MenuItem("Quit", "Alt-F4")) {
ImGui::End();
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Docking")) {
// Disabling fullscreen would allow the window to be moved to the front of other windows,
// which we can't undo at the moment without finer window depth/z control.
//ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant);
if (ImGui::MenuItem("NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0))
dockspace_flags ^= ImGuiDockNodeFlags_NoSplit;
if (ImGui::MenuItem("NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0))
dockspace_flags ^= ImGuiDockNodeFlags_NoResize;
if (ImGui::MenuItem("NoDockingInCentralNode", "",
(dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0))
dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode;
if (ImGui::MenuItem("PassthruCentralNode", "",
(dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0))
dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode;
if (ImGui::MenuItem("AutoHideTabBar", "",
(dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0))
dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar;
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::End();
}
//-------------------------------------------------------
bool test_ptr = true;
void MainWindow::ShowCodeEditors(TextEditor& editor, std::list<std::string>& algo_list)
{
auto cpos = editor.GetCursorPosition();
ImGui::Begin(fs::path(editor.file_path).filename().string().c_str(), nullptr, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_MenuBar);
if (ImGui::BeginMenuBar()) {
if (ImGui::BeginMenu("File")) {
if (ImGui::MenuItem("Save", "Ctrl + S", nullptr, editor.file_path.empty())) {
auto textToSave = editor.GetText();
std::string path = editor.file_path;
if (!path.empty()) {
std::fstream file(editor.file_path);
file << textToSave;
}
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Edit")) {
bool ro = editor.IsReadOnly();
if (ImGui::MenuItem("Read-only mode", nullptr, &ro)) {
editor.SetReadOnly(ro);
}
ImGui::Separator();
if (ImGui::MenuItem("Undo", "ALT-Backspace", nullptr, !ro && editor.CanUndo())) {
editor.Undo();
}
if (ImGui::MenuItem("Redo", "Ctrl-Y", nullptr, !ro && editor.CanRedo())) {
editor.Redo();
}
ImGui::Separator();
if (ImGui::MenuItem("Copy", "Ctrl-C", nullptr, editor.HasSelection())) {
editor.Copy();
}
if (ImGui::MenuItem("Cut", "Ctrl-X", nullptr, !ro && editor.HasSelection())) {
editor.Cut();
}
if (ImGui::MenuItem("Delete", "Del", nullptr, !ro && editor.HasSelection())) {
editor.Delete();
}
if (ImGui::MenuItem("Paste", "Ctrl-V", nullptr, !ro && ImGui::GetClipboardText() != nullptr)) {
editor.Paste();
}
ImGui::Separator();
if (ImGui::MenuItem("Select all", nullptr, nullptr))
editor.SetSelection(TextEditor::Coordinates(), TextEditor::Coordinates(editor.GetTotalLines(), 0));
ImGui::EndMenu();
}
if (ImGui::BeginMenu("View")) {
if (ImGui::MenuItem("Dark palette")) {
editor.SetPalette(TextEditor::GetDarkPalette());
}
if (ImGui::MenuItem("Light palette")) {
editor.SetPalette(TextEditor::GetLightPalette());
}
if (ImGui::MenuItem("Retro blue palette")) {
editor.SetPalette(TextEditor::GetRetroBluePalette());
}
ImGui::Separator();
if (ImGui::MenuItem("Toggle index colorization", nullptr, editor.hasIndexColorization())) {
editor.mIndexColorization = !editor.mIndexColorization;
}
if (ImGui::MenuItem("Show silice file's fullpath", nullptr, show_fullpath)) {
show_fullpath = !show_fullpath;
}
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
if (editor.hasIndexColorization()) {
ImGui::Separator();
for (const auto &item : algo_list)
{
ImGui::SameLine();
if (ImGui::Checkbox(item.c_str(), &checked_algos[item.c_str()]))
{
fstWindow.setAlgoToColorize(checked_algos);
}
}
ImGui::Separator();
}
if (show_fullpath)
{
ImGui::Text("%6d/%-6d %6d lines | %s | %s | %s | %s", cpos.mLine + 1, cpos.mColumn + 1, editor.GetTotalLines(),
editor.IsOverwrite() ? "Ovr" : "Ins",
editor.CanUndo() ? "*" : " ",
editor.GetLanguageDefinition().mName.c_str(), editor.file_path.c_str());
}
else
{
ImGui::Text("%6d/%-6d %6d lines | %s | %s | %s | %s", cpos.mLine + 1, cpos.mColumn + 1, editor.GetTotalLines(),
editor.IsOverwrite() ? "Ovr" : "Ins",
editor.CanUndo() ? "*" : " ",
editor.GetLanguageDefinition().mName.c_str(), fs::path(editor.file_path).filename().string().c_str());
}
ImGui::PushFont(font_code);
p_open_editor = ImGui::IsWindowFocused();
editor.Render("TextEditor");
this->ZoomMouseWheel(editor);
ImGui::PopFont();
ImGui::End();
}
//-------------------------------------------------------
void MainWindow::ZoomMouseWheel(TextEditor& editor)
{
if (ImGui::GetIO().KeysDown[LIBSL_KEY_CTRL] && (p_open_editor || editor.p_open_editor)) {
if (ImGui::GetIO().MouseWheel > 0 || ImGui::GetIO().KeysDown[LIBSL_KEY_UP]) {
if (ImGui::GetFontSize() < 28) {
editor.ScaleFont(true);
}
} else if (ImGui::GetIO().MouseWheel < 0 || ImGui::GetIO().KeysDown[LIBSL_KEY_DOWN]) {
if (ImGui::GetFontSize() > 8) {
editor.ScaleFont(false);
}
}
}
}
//-------------------------------------------------------
void MainWindow::getSiliceFiles() {
// Looks for every Silice files needed in the design
std::ifstream file("build.v.files.log");
static std::mutex mutex;
std::vector<std::thread> thread_vector;
std::string filename;
if (file.is_open())
{
while (file.good())
{
filename = "";
file >> filename;
if (!filename.empty())
{
if (fs::is_regular_file(filename) && fs::path(filename).extension() == ".ice")
{
thread_vector.emplace_back([this](std::string file_path) {
std::list<std::string> list = this->lp.getAlgos(file_path);
mutex.lock();
this->editors.insert(std::make_pair(file_path, std::make_pair(TextEditor(file_path, this->lp), list)));
mutex.unlock();
}, filename);
}
}
}
for (auto &thread : thread_vector)
{
thread.join();
}
file.close();
}
}
//-------------------------------------------------------
void MainWindow::Init() {
ImGui_Impl_CreateFontsTexture("NotoSans-Regular.ttf", "JetBrainsMono-Bold.ttf");
this->getSiliceFiles();
// Initializing checkboxes
for (const auto &[filepath, editor] : this->editors)
{
for (const auto &algoname : editor.second)
{
checked_algos[algoname] = true;
std::cout << algoname << std::endl;
}
}
const std::string str = "icarus.fst";
fstWindow.load(str, this->editors, this->lp);
fstWindow.setAlgoToColorize(checked_algos);
ImGui::GetStyle().FrameRounding = 4.0f;
ImGui::GetStyle().GrabRounding = 4.0f;
ImVec4 *colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_Text] = ImVec4(0.95f, 0.96f, 0.98f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.36f, 0.42f, 0.47f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.11f, 0.15f, 0.17f, 1.00f);
colors[ImGuiCol_ChildBg] = ImVec4(0.15f, 0.18f, 0.22f, 1.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
colors[ImGuiCol_Border] = ImVec4(0.08f, 0.10f, 0.12f, 1.00f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.20f, 0.25f, 0.29f, 1.00f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.12f, 0.20f, 0.28f, 1.00f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.09f, 0.12f, 0.14f, 1.00f);
colors[ImGuiCol_TitleBg] = ImVec4(0.09f, 0.12f, 0.14f, 0.65f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.08f, 0.10f, 0.12f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.15f, 0.18f, 0.22f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.39f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.20f, 0.25f, 0.29f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.18f, 0.22f, 0.25f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.09f, 0.21f, 0.31f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.28f, 0.56f, 1.00f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.28f, 0.56f, 1.00f, 1.00f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.37f, 0.61f, 1.00f, 1.00f);
colors[ImGuiCol_Button] = ImVec4(0.20f, 0.25f, 0.29f, 1.00f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.28f, 0.56f, 1.00f, 1.00f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);
colors[ImGuiCol_Header] = ImVec4(0.20f, 0.25f, 0.29f, 0.55f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_Separator] = ImVec4(0.20f, 0.25f, 0.29f, 1.00f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.25f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
colors[ImGuiCol_Tab] = ImVec4(0.11f, 0.15f, 0.17f, 1.00f);
colors[ImGuiCol_TabHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);
colors[ImGuiCol_TabActive] = ImVec4(0.20f, 0.25f, 0.29f, 1.00f);
colors[ImGuiCol_TabUnfocused] = ImVec4(0.11f, 0.15f, 0.17f, 1.00f);
colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.11f, 0.15f, 0.17f, 1.00f);
colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);
colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
}
void MainWindow::Render()
{
ImGui::PushFont(font_general);
this->ShowDockSpace();
for (auto &[filename, editor] : this->editors)
{
this->ShowCodeEditors(editor.first, editor.second);
}
fstWindow.render();
ImGui::PopFont();
}
| 42.31982 | 202 | 0.595423 | [
"render",
"vector"
] |
efe86e9fa72d25c7f68ce04486d481901c9360a3 | 420 | cpp | C++ | week3-exercise3/victim.cpp | jakah/hu-v1oopc-exercises | 74d830fa150525705306bcb59652cc9baa991985 | [
"MIT"
] | null | null | null | week3-exercise3/victim.cpp | jakah/hu-v1oopc-exercises | 74d830fa150525705306bcb59652cc9baa991985 | [
"MIT"
] | null | null | null | week3-exercise3/victim.cpp | jakah/hu-v1oopc-exercises | 74d830fa150525705306bcb59652cc9baa991985 | [
"MIT"
] | null | null | null | #include "victim.hpp"
#include "rectangle.hpp"
victim::victim(window & w, vector start, vector end):
rectangle(w, start, end),
hit(false)
{}
void victim::interact( drawable & other ){
if( this != & other){
if( overlaps( other )){
hit = true;
}
}
}
void victim::update(){
if(hit == true){
*this = victim(w,start+ vector(1,1), end - vector(1,1));
}
}
| 17.5 | 64 | 0.533333 | [
"vector"
] |
efe961c4f36c23492895d14265b93d58b19f4b33 | 3,522 | cpp | C++ | JustnEngine/src/Components/PlayerController.cpp | JustenG/ComputerGraphics | 81a1859206aaeb6498cbbb1607b04ba6d0d2e978 | [
"Unlicense"
] | null | null | null | JustnEngine/src/Components/PlayerController.cpp | JustenG/ComputerGraphics | 81a1859206aaeb6498cbbb1607b04ba6d0d2e978 | [
"Unlicense"
] | null | null | null | JustnEngine/src/Components/PlayerController.cpp | JustenG/ComputerGraphics | 81a1859206aaeb6498cbbb1607b04ba6d0d2e978 | [
"Unlicense"
] | null | null | null | #include "Components\PlayerController.h"
#include "Components\Transform.h"
#include "Entitys\GameObject.h"
#include "Physics\PhysXManager.h"
#include "GLFW\glfw3.h"
#include "all_includes.h"
PlayerController::PlayerController()
{
m_physXManager = PhysXManager::GetInstance();
m_currentWindow = glfwGetCurrentContext();
}
PlayerController::~PlayerController()
{
}
void PlayerController::Update(float deltaTime)
{
bool onGround; //set to true if we are on the ground
float movementSpeed = 10.0f; //forward and back movement speed
float rotationSpeed = 1.0f; //turn speed
//check if we have a contact normal. if y is greater than .3 we assume this is solid ground.This is a rather primitive way to do this.Can you do better ?
if (myHitReport->GetPlayerContactNormal().y > 0.3f)
{
m_yVelocity = -0.1f;
onGround = true;
}
else
{
m_yVelocity += m_gravity * deltaTime;
onGround = false;
}
myHitReport->ClearPlayerContactNormal();
const PxVec3 up(0, 1, 0);
//scan the keys and set up our intended velocity based on a global transform
PxVec3 velocity(0, m_yVelocity, 0);
if (glfwGetKey(m_currentWindow, GLFW_KEY_W) == GLFW_PRESS)
{
velocity.x -= movementSpeed*deltaTime;
}
if (glfwGetKey(m_currentWindow, GLFW_KEY_S) == GLFW_PRESS)
{
velocity.x += movementSpeed*deltaTime;
}
//To do.. add code to control z movement and jumping
float minDistance = 0.001f;
PxControllerFilters filter;
//make controls relative to player facing
PxQuat rotation(m_rotation, PxVec3(0, 1, 0));
//PxVec3 velocity(0, m_yVelocity, 0);
//move the controller
if(m_playerController != nullptr)
m_playerController->move(rotation.rotate(velocity), minDistance, deltaTime, filter);
}
void PlayerController::Start()
{
if (GetGameObject()->GetComponent<Transform>() != nullptr)
m_myTransform = GetGameObject()->GetComponent<Transform>();
vec3 pos = m_myTransform->GetPosition();
m_physXMaterial = m_physXManager->GetPhysics()->createMaterial(0.5f, 0.5f, 0.5f);
//ControllerHitRe
myHitReport = new MyControllerHitReport();
//describe our controller...
PxCapsuleControllerDesc desc;
desc.height = 1.6f;
desc.radius = 1.0f;
desc.position.set(0, 5, 0);
desc.material = m_physXMaterial;
desc.reportCallback = myHitReport; //connect it to our collision detection routine
desc.density = 10; //create the layer controller
PxControllerManager* controllerManager = m_physXManager->GetControllerManager();
if (controllerManager != nullptr)
{
PxController* controller = controllerManager->createController(desc);
m_playerController = controller;
if(m_playerController != nullptr)
m_playerController->setPosition(PxExtendedVec3(pos.x, pos.y, pos.z)); //set up some variables to control our player with
}
m_yVelocity = 0; //initialize character velocity
m_rotation = 0; //and rotation
m_gravity = -0.5f; //set up the player gravity
myHitReport->ClearPlayerContactNormal(); //initialize the contact normal (what we are in contact with)
}
void MyControllerHitReport::onShapeHit(const PxControllerShapeHit &hit)
{
//gets a reference to a structure which tells us what has been hit and where
//get the acter from the shape we hit
PxRigidActor* actor = hit.shape->getActor();
//get the normal of the thing we hit and store it so the player controller can respond correctly
_playerContactNormal = hit.worldNormal;
//try to cast to a dynamic actor
PxRigidDynamic* myActor = actor->is<PxRigidDynamic>();
if (myActor)
{
//this is where we can apply forces to things we hit
}
} | 31.446429 | 154 | 0.747871 | [
"shape",
"transform",
"solid"
] |
efef489e58baf90df5b9051d9167ad2cdf386ee0 | 1,227 | cpp | C++ | src/server/history/jumping_history.cpp | BioRyajenka/operational-transformation | 2e666ca2a62e74dd6b405928e686a627ca3a3181 | [
"Apache-2.0"
] | null | null | null | src/server/history/jumping_history.cpp | BioRyajenka/operational-transformation | 2e666ca2a62e74dd6b405928e686a627ca3a3181 | [
"Apache-2.0"
] | null | null | null | src/server/history/jumping_history.cpp | BioRyajenka/operational-transformation | 2e666ca2a62e74dd6b405928e686a627ca3a3181 | [
"Apache-2.0"
] | 2 | 2021-03-07T06:57:02.000Z | 2021-08-06T16:01:07.000Z | //
// Created by Igor on 05.02.2021.
//
#include "jumping_history.h"
void jumping_history::push(const std::shared_ptr<operation> &new_op) {
stack.emplace_back();
std::vector<std::shared_ptr<operation>> &jumps = stack[stack.size() - 1];
// current is stack.size() - 1
jumps.push_back(new_op); // from current to current + 1 - 2^0
for (int i = 1; (1 << i) <= (int)stack.size(); i++) {
// from current to current + 1 - 2^i
// = (from current - 2^(i-1) to (current + 1 - 2^i))
// + (from current to current + 1 - 2^(i-1))
auto op = std::make_shared<operation>();
op->apply(*stack[stack.size() - 1 - (1 << (i - 1))][i - 1]);
op->apply(*jumps[i - 1]);
jumps.push_back(op);
}
}
std::unique_ptr<operation> jumping_history::fetch(const int from) const {
// from "from" to "stack.size() - 1"
int mask = (int)stack.size() - from;
int cur = from;
auto op = std::make_unique<operation>();
for (int i = 0; (1 << i) <= mask; i++) {
if (mask & (1 << i)) {
cur += 1 << i;
op->apply(*stack[cur - 1][i]);
}
}
return op;
}
int jumping_history::last_state() const {
return stack.size();
}
| 28.534884 | 77 | 0.534637 | [
"vector"
] |
eff023bc9867ebef6c56fcb7775d1296b78499c2 | 7,297 | cpp | C++ | src/core/RUcs.cpp | ouxianghui/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 12 | 2021-03-26T03:23:30.000Z | 2021-12-31T10:05:44.000Z | src/core/RUcs.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | null | null | null | src/core/RUcs.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 9 | 2021-06-23T08:26:40.000Z | 2022-01-20T07:18:10.000Z | /**
* Copyright (c) 2011-2016 by Andrew Mustun. All rights reserved.
*
* This file is part of the QCAD project.
*
* QCAD 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.
*
* QCAD 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 QCAD.
*/
#include "RUcs.h"
#include "RLine.h"
#include "RTriangle.h"
RPropertyTypeId RUcs::PropertyName;
RPropertyTypeId RUcs::PropertyOriginX;
RPropertyTypeId RUcs::PropertyOriginY;
RPropertyTypeId RUcs::PropertyOriginZ;
RPropertyTypeId RUcs::PropertyXAxisDirectionX;
RPropertyTypeId RUcs::PropertyXAxisDirectionY;
RPropertyTypeId RUcs::PropertyXAxisDirectionZ;
RPropertyTypeId RUcs::PropertyYAxisDirectionX;
RPropertyTypeId RUcs::PropertyYAxisDirectionY;
RPropertyTypeId RUcs::PropertyYAxisDirectionZ;
void RUcs::init() {
RUcs::PropertyName.generateId(typeid(RUcs), "", "Name");
RUcs::PropertyOriginX.generateId(typeid(RUcs), "Origin", "X");
RUcs::PropertyOriginY.generateId(typeid(RUcs), "Origin", "Y");
RUcs::PropertyOriginZ.generateId(typeid(RUcs), "Origin", "Z");
RUcs::PropertyXAxisDirectionX.generateId(typeid(RUcs), "X Axis", "X");
RUcs::PropertyXAxisDirectionY.generateId(typeid(RUcs), "X Axis", "Y");
RUcs::PropertyXAxisDirectionZ.generateId(typeid(RUcs), "X Axis", "Z");
RUcs::PropertyYAxisDirectionX.generateId(typeid(RUcs), "Y Axis", "X");
RUcs::PropertyYAxisDirectionY.generateId(typeid(RUcs), "Y Axis", "Y");
RUcs::PropertyYAxisDirectionZ.generateId(typeid(RUcs), "Y Axis", "Z");
}
bool RUcs::setProperty(RPropertyTypeId propertyTypeId, const QVariant& value, RTransaction* transaction) {
Q_UNUSED(transaction);
bool ret = false;
ret = RObject::setMember(name, value, PropertyName == propertyTypeId);
ret = ret || RObject::setMember(origin.x, value, PropertyOriginX == propertyTypeId);
ret = ret || RObject::setMember(origin.y, value, PropertyOriginY == propertyTypeId);
ret = ret || RObject::setMember(origin.z, value, PropertyOriginZ == propertyTypeId);
ret = ret || RObject::setMember(xAxisDirection.x, value, PropertyName == propertyTypeId);
ret = ret || RObject::setMember(xAxisDirection.y, value, PropertyName == propertyTypeId);
ret = ret || RObject::setMember(xAxisDirection.z, value, PropertyName == propertyTypeId);
ret = ret || RObject::setMember(yAxisDirection.x, value, PropertyName == propertyTypeId);
ret = ret || RObject::setMember(yAxisDirection.y, value, PropertyName == propertyTypeId);
ret = ret || RObject::setMember(yAxisDirection.z, value, PropertyName == propertyTypeId);
return ret;
}
QPair<QVariant, RPropertyAttributes> RUcs::getProperty(
RPropertyTypeId& propertyTypeId, bool /*humanReadable*/,
bool /*noAttributes*/) {
if (propertyTypeId == PropertyName) {
return qMakePair(QVariant(name), RPropertyAttributes());
}
if (propertyTypeId == PropertyOriginX) {
return qMakePair(QVariant(origin.x), RPropertyAttributes());
}
if (propertyTypeId == PropertyOriginY) {
return qMakePair(QVariant(origin.y), RPropertyAttributes());
}
if (propertyTypeId == PropertyOriginZ) {
return qMakePair(QVariant(origin.z), RPropertyAttributes());
}
if (propertyTypeId == PropertyXAxisDirectionX) {
return qMakePair(QVariant(xAxisDirection.x), RPropertyAttributes());
}
if (propertyTypeId == PropertyXAxisDirectionY) {
return qMakePair(QVariant(xAxisDirection.y), RPropertyAttributes());
}
if (propertyTypeId == PropertyXAxisDirectionZ) {
return qMakePair(QVariant(xAxisDirection.z), RPropertyAttributes());
}
if (propertyTypeId == PropertyYAxisDirectionX) {
return qMakePair(QVariant(yAxisDirection.x), RPropertyAttributes());
}
if (propertyTypeId == PropertyYAxisDirectionY) {
return qMakePair(QVariant(yAxisDirection.y), RPropertyAttributes());
}
if (propertyTypeId == PropertyYAxisDirectionZ) {
return qMakePair(QVariant(yAxisDirection.z), RPropertyAttributes());
}
return qMakePair(QVariant(), RPropertyAttributes());
}
/**
* \return Vector that indicates the direction of the Z-Axis
* (orthogonal to the XY plane).
*/
RVector RUcs::getZAxisDirection() {
return RVector::getCrossProduct(xAxisDirection, yAxisDirection);
}
/**
* Maps the given UCS (user coordinate system) position to an
* absolute WCS (world coordinate system) position.
*/
RVector RUcs::mapFromUcs(const RVector& positionUcs) {
return origin
+ xAxisDirection.getUnitVector() * positionUcs.x
+ yAxisDirection.getUnitVector() * positionUcs.y
+ getZAxisDirection().getUnitVector() * positionUcs.z;
}
/**
* Maps the given WCS position to a UCS position.
*/
RVector RUcs::mapToUcs(const RVector& positionWcs) {
// normal of UCS XY plane in WCS:
RVector normal = getZAxisDirection();
// a ray from the WCS position in the direction of the UCS plane normal:
RLine ray(positionWcs, positionWcs + normal);
// the UCS XY plane as a WCS triangle:
RTriangle plane(origin, origin + xAxisDirection, origin + yAxisDirection);
// the Z coordinate of the result is the distance of the given position to the
// XY plane:
double z = plane.getDistanceTo(positionWcs, false);
// find intersection point of ray with XY plane:
// QList<RVector> res = plane.getIntersectionPoints(ray, false);
QList<RVector> res = RShape::getIntersectionPoints(plane, ray, false);
if (res.size()==0) {
qDebug("RUcs::mapToUcs: no intersection between plane and normal");
return RVector();
}
// intersection point of ray with XY plane:
RVector onPlane = res.front();
// find absolute value of X as distance of given position to Y axis of this UCS:
RLine yAxisUcs(origin, origin + yAxisDirection);
double x = yAxisUcs.getDistanceTo(onPlane, false);
// find absolute value of Y as distance of given position to X axis of this UCS:
RLine xAxisUcs(origin, origin + xAxisDirection);
double y = xAxisUcs.getDistanceTo(onPlane, false);
// determine sign of X/Y coordinates:
if (RTriangle(origin, origin-xAxisDirection, origin+yAxisDirection).isPointInQuadrant(onPlane)) {
return RVector(-x, y, z);
}
else if (RTriangle(origin, origin-xAxisDirection, origin-yAxisDirection).isPointInQuadrant(onPlane)) {
return RVector(-x, -y, z);
}
else if (RTriangle(origin, origin+xAxisDirection, origin-yAxisDirection).isPointInQuadrant(onPlane)) {
return RVector(x, -y, z);
}
else {
return RVector(x, y, z);
}
}
/**
* Stream operator for QDebug
*/
QDebug operator<<(QDebug dbg, const RUcs& u) {
dbg.nospace() << "RUcs(" << u.name << ", " << u.origin << ", " << u.xAxisDirection << ", " << u.yAxisDirection << ")";
return dbg.space();
}
| 36.668342 | 122 | 0.703166 | [
"vector"
] |
eff293d73ade63bb53ad0fb989a5c7483f65c79a | 785 | cpp | C++ | CODECHEF/CHRL1.cpp | aqfaridi/Competitve-Programming-Codes | d055de2f42d3d6bc36e03e67804a1dd6b212241f | [
"MIT"
] | null | null | null | CODECHEF/CHRL1.cpp | aqfaridi/Competitve-Programming-Codes | d055de2f42d3d6bc36e03e67804a1dd6b212241f | [
"MIT"
] | null | null | null | CODECHEF/CHRL1.cpp | aqfaridi/Competitve-Programming-Codes | d055de2f42d3d6bc36e03e67804a1dd6b212241f | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <vector>
#include <iomanip>
#include <cmath>
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
#define MAX 100010
#define MOD 1000000007
int wt[40],cost[40],ans,n;
void knapsack(int i,int k,int total)
{
if(i==n+1 || k<=0)
{
ans = max(ans,total);
return;
}
if(k>=cost[i])
knapsack(i+1,k-cost[i],total+wt[i]);
knapsack(i+1,k,total);
}
int main()
{
ios::sync_with_stdio(false);
int t,k;
cin>>t;
while(t--)
{
ans = 0;
cin>>n>>k;
for(int i=1;i<=n;i++)
cin>>cost[i]>>wt[i];
knapsack(1,k,0);
cout<<ans<<endl;
}
return 0;
}
| 17.065217 | 44 | 0.540127 | [
"vector"
] |
eff91756b1c897696e3c3ccc0b74a6f26fbb968f | 18,898 | cc | C++ | src/library/specex_psf.cc | marcelo-alvarez/specex | 809c5540e76dc1681453488732d5845078427ad1 | [
"BSD-3-Clause"
] | null | null | null | src/library/specex_psf.cc | marcelo-alvarez/specex | 809c5540e76dc1681453488732d5845078427ad1 | [
"BSD-3-Clause"
] | null | null | null | src/library/specex_psf.cc | marcelo-alvarez/specex | 809c5540e76dc1681453488732d5845078427ad1 | [
"BSD-3-Clause"
] | null | null | null | #include <iomanip>
#include <cmath>
#include <string>
#include <harp.hpp>
#include "specex_psf.h"
//#include "specex_base_analytic_psf.h"
#include "specex_message.h"
using namespace std;
/* weights and abcissa for gauss integrations (borrowed from DAOPHOT),
explained in Numerical recipes */
static double Dx[4][4] ={{0.00000000, 0.0, 0.0 , 0.0 },
{-0.28867513, 0.28867513, 0.0 , 0.0 },
{-0.38729833, 0.00000000, 0.38729833, 0.0 },
{-0.43056816, -0.16999052, 0.16999052, 0.43056816}};
static double Wt[4][4]= {{1.00000000, 0.0 , 0.0 , 0.0 },
{0.50000000, 0.50000000, 0.0 , 0.0 },
{0.27777778, 0.44444444, 0.27777778, 0.0 },
{0.17392742, 0.32607258, 0.32607258, 0.17392742}};
// number of points (per coordinate) to integrate over a pixel.
#define NPT 4
//#define INTEGRATING_TAIL
double specex::PSF::PixValue(const double &Xc, const double &Yc,
const double &XPix, const double &YPix,
const harp::vector_double &Params,
harp::vector_double *PosDer,
harp::vector_double *ParamDer) const
{
double xPixCenter = floor(XPix+0.5);
double yPixCenter = floor(YPix+0.5);
harp::vector_double tmpPosDer;
if(PosDer) {
tmpPosDer.resize(2);
tmpPosDer.clear();
}
harp::vector_double tmpParamDer;
int npar=0;
if(ParamDer) {
npar = ParamDer->size();
tmpParamDer.resize(npar);
tmpParamDer.clear();
}
double val = 0;
for (int ix=0; ix<NPT; ++ix)
{
double x = xPixCenter+Dx[NPT-1][ix] - Xc;
double wx = Wt[NPT-1][ix];
for (int iy=0; iy<NPT; ++iy)
{
double y = yPixCenter+Dx[NPT-1][iy] -Yc;
double weight = wx*Wt[NPT-1][iy];
double prof = Profile(x,y,Params,PosDer,ParamDer);
if(prof == PSF_NAN_VALUE) return PSF_NAN_VALUE;
#ifdef EXTERNAL_TAIL
#ifdef INTEGRATING_TAIL
double tail_prof = TailProfile(x,y,Params,true); // TRY INTEGRATING TAIL
prof += Params(psf_tail_amplitude_index)*tail_prof;
if(ParamDer) (*ParamDer)(psf_tail_amplitude_index) = tail_prof;
#endif
#endif
val += weight*prof;
if (PosDer)
tmpPosDer += weight*(*PosDer);
if (ParamDer)
tmpParamDer += weight*(*ParamDer);
}
}
if (PosDer)
*PosDer = tmpPosDer;
if (ParamDer)
*ParamDer = tmpParamDer;
return val;
}
specex::PSF::PSF() {
name = "unknown";
hSizeX = hSizeY = 12;
#ifdef EXTERNAL_TAIL
r_tail_profile_must_be_computed = true;
psf_tail_amplitude_index = -1;
#endif
gain=1;
readout_noise=1;
psf_error=0.0;
arc_exposure_id=0;
mjd=0;
plate_id=0;
ccd_image_n_cols=0;
ccd_image_n_rows=0;
camera_id="unknown";
}
#ifdef EXTERNAL_TAIL
#define NX_TAIL_PROFILE 1000
#define NY_TAIL_PROFILE 8000
#define TAIL_OVERSAMPLING 2.
double specex::PSF::TailProfileValue(const double& dx, const double &dy) const {
double r2 = square(dx*r_tail_x_scale)+square(dy*r_tail_y_scale);
return r2/(r2_tail_core_size+r2)*pow(r2_tail_core_size+r2,-r_tail_power_law_index/2.);
}
void specex::PSF::ComputeTailProfile(const harp::vector_double &Params) {
if(r_tail_profile_must_be_computed == false) {
SPECEX_WARNING("calling specex::PSF::ComputeTailProfile when r_tail_profile_must_be_computed =false");
return;
}
SPECEX_INFO("specex::PSF::ComputeTailProfile ...");
r_tail_profile.resize(NX_TAIL_PROFILE,NY_TAIL_PROFILE); // hardcoded
if(! HasParam("TAILCORE"))
SPECEX_ERROR("in PSF::ComputeTailProfile, missing param TAILCORE, need to allocate them, for instance with PSF::AllocateDefaultParams()");
r2_tail_core_size = square(Params(ParamIndex("TAILCORE")));
r_tail_x_scale = Params(ParamIndex("TAILXSCA"));
r_tail_y_scale = Params(ParamIndex("TAILYSCA"));
r_tail_power_law_index = Params(ParamIndex("TAILINDE"));
for(int j=0;j<NY_TAIL_PROFILE;j++) {
for(int i=0;i<NX_TAIL_PROFILE;i++) {
r_tail_profile(i,j) = TailProfileValue(i/TAIL_OVERSAMPLING,j/TAIL_OVERSAMPLING);
}
}
// store index of PSF tail amplitude
psf_tail_amplitude_index = ParamIndex("TAILAMP");
r_tail_profile_must_be_computed = false;
SPECEX_INFO("specex::PSF::ComputeTailProfile done");
}
double specex::PSF::TailProfile(const double& dx, const double &dy, const harp::vector_double &Params, bool full_calculation) const {
if(r_tail_profile_must_be_computed) {
#pragma omp critical
{
const_cast<specex::PSF*>(this)->ComputeTailProfile(Params);
}
}
if(full_calculation) return TailProfileValue(dx,dy);
double dxo = fabs(dx*TAIL_OVERSAMPLING);
double dyo = fabs(dy*TAIL_OVERSAMPLING);
int di = int(dxo);
int dj = int(dyo);
if(di>=NX_TAIL_PROFILE-1 || dj>=NY_TAIL_PROFILE-1) return 0.;
return r_tail_profile(di,dj); // faster
return (
(di+1-dxo)*(dj+1-dyo)*r_tail_profile(di,dj)
+(dxo-di)*(dj+1-dyo)*r_tail_profile(di+1,dj)
+(di+1-dxo)*(dyo-dj)*r_tail_profile(di,dj+1)
+(dxo-di)*(dyo-dj)*r_tail_profile(di+1,dj+1)
);
}
/*
double specex::PSF::TailAmplitudeXW(const double &x, const double& wavelength, int fiber_bundle) const {
const PSF_Params& params = ParamsOfBundles.find(fiber_bundle)->second;
params.AllParPolXW[ParamIndex("TAILAMP")]->Value(x,wavelength);
}
double specex::PSF::TailAmplitudeFW(const int fiber, const double& wavelength, int fiber_bundle) const {
return TailAmplitudeXW(Xccd(fiber,wavelength),wavelength,fiber_bundle);
}
double specex::PSF::TailValueWithParamsXY(const double &Xc, const double &Yc,
const int IPix, const int JPix,
const harp::vector_double &Params,
harp::vector_double* derivative_r_tail_amplitude) const {
double r_prof = TailProfile(IPix-Xc,JPix-Yc, Params);
if(derivative_r_tail_amplitude) {
SPECEX_ERROR("need a way to do this");
// return scalar ?
}
return Params(psf_tail_amplitude_index)*r_prof;
}
double specex::PSF::TailValueFW(const int fiber, const double& wave,
const int IPix, const int JPix, int bundle_id,
harp::vector_double* derivative_r_tail_amplitude) const {
double X=Xccd(fiber,wave);
double Y=Yccd(fiber,wave);
return TailValueWithParamsXY(X,Y,IPix,JPix,AllLocalParamsXW(X,wave,bundle_id), derivative_r_tail_amplitude);
}
*/
#endif
int specex::PSF::BundleNFitPar(int bundle_id) const {
std::map<int,PSF_Params>::const_iterator it = ParamsOfBundles.find(bundle_id);
if(it==ParamsOfBundles.end()) SPECEX_ERROR("no such bundle #" << bundle_id);
const std::vector<Pol_p>& P=it->second.FitParPolXW;
int n=0;
for(size_t p=0;p<P.size();p++)
n += P[p]->coeff.size();
return n;
}
int specex::PSF::BundleNAllPar(int bundle_id) const {
std::map<int,PSF_Params>::const_iterator it = ParamsOfBundles.find(bundle_id);
if(it==ParamsOfBundles.end()) SPECEX_ERROR("no such bundle #" << bundle_id);
const std::vector<Pol_p>& P=it->second.AllParPolXW;
int n=0;
for(size_t p=0;p<P.size();p++)
n += P[p]->coeff.size();
return n;
}
int specex::PSF::TracesNPar() const {
int n=0;
for(std::map<int,Trace>::const_iterator it=FiberTraces.begin(); it!=FiberTraces.end(); ++it) {
n += it->second.X_vs_W.coeff.size();
n += it->second.Y_vs_W.coeff.size();
}
return n;
}
specex::PSF::~PSF() {
}
const std::string& specex::PSF::ParamName(int p) const {
if(!ParamsOfBundles.size()) SPECEX_ERROR("Requiring name of param when no params of bundles in PSF");
if(p>=int(ParamsOfBundles.begin()->second.AllParPolXW.size())) SPECEX_ERROR("Requiring name of param at index " << p << " when only " << ParamsOfBundles.begin()->second.AllParPolXW.size() << " PSF params");
return ParamsOfBundles.begin()->second.AllParPolXW[p]->name;
}
int specex::PSF::ParamIndex(const std::string& name) const {
if(!ParamsOfBundles.size()) return -1;
for(size_t p=0;p< ParamsOfBundles.begin()->second.AllParPolXW.size();p++) {
if( ParamsOfBundles.begin()->second.AllParPolXW[p]->name == name) return int(p);
}
return -1;
};
bool specex::PSF::HasParam(const std::string& name) const {
return (ParamIndex(name)>=0);
}
void specex::PSF::AllocateDefaultParams() {
harp::vector_double params = DefaultParams();
std::vector<std::string> param_names = DefaultParamNames();
PSF_Params pars;
ParamsOfBundles[0] = pars;
for(size_t p = 0; p<params.size(); p++) {
Pol_p pol(new Pol(0,0,1,0,0,1));
pol->Fill();
pol->name = param_names[p];
ParamsOfBundles[0].AllParPolXW.push_back(pol);
}
}
void specex::PSF::StampLimits(const double &X, const double &Y,
int &BeginI, int &EndI,
int &BeginJ, int &EndJ) const {
int iPix = int(floor(X+0.5));
int jPix = int(floor(Y+0.5));
BeginI = iPix-hSizeX;
BeginJ = jPix-hSizeY;
EndI = iPix+hSizeX+1;
EndJ = jPix+hSizeY+1;
}
const specex::Trace& specex::PSF::GetTrace(int fiber) const {
std::map<int,specex::Trace>::const_iterator it = FiberTraces.find(fiber);
if(it == FiberTraces.end()) SPECEX_ERROR("No trace for fiber " << fiber);
return it->second;
}
specex::Trace& specex::PSF::GetTrace(int fiber) {
std::map<int,specex::Trace>::iterator it = FiberTraces.find(fiber);
if(it == FiberTraces.end()) SPECEX_ERROR("No trace for fiber " << fiber);
return it->second;
}
void specex::PSF::AddTrace(int fiber) {
std::map<int,specex::Trace>::iterator it = FiberTraces.find(fiber);
if(it != FiberTraces.end()) {
SPECEX_WARNING("Trace for fiber " << fiber << " already exists");
}else{
FiberTraces[fiber]=specex::Trace();
LoadXYPol();
}
}
void specex::PSF::LoadXYPol() {
#pragma omp critical
{
XPol.clear();
YPol.clear();
for(std::map<int,specex::Trace>::iterator it = FiberTraces.begin(); it != FiberTraces.end(); ++it) {
XPol[it->first] = &(it->second.X_vs_W);
YPol[it->first] = &(it->second.Y_vs_W);
}
}
}
double specex::PSF::Xccd(int fiber, const double& wave) const {
std::map<int,specex::Legendre1DPol*>::const_iterator it = XPol.find(fiber);
if(it==XPol.end()) {
const_cast<specex::PSF*>(this)->LoadXYPol();
it = XPol.find(fiber);
if(it == XPol.end()) SPECEX_ERROR("No trace for fiber " << fiber);
}
return it->second->Value(wave);
}
double specex::PSF::Yccd(int fiber, const double& wave) const {
std::map<int,specex::Legendre1DPol*>::const_iterator it = YPol.find(fiber);
if(it==YPol.end()) {
const_cast<specex::PSF*>(this)->LoadXYPol();
it = YPol.find(fiber);
if(it == YPol.end()) SPECEX_ERROR("No trace for fiber " << fiber);
}
return it->second->Value(wave);
}
//! Access to the current PSF, with user provided Params.
double specex::PSF::PSFValueWithParamsXY(const double &Xc, const double &Yc,
const int IPix, const int JPix,
const harp::vector_double &Params,
harp::vector_double *PosDer, harp::vector_double *ParamDer,
bool with_core, bool with_tail) const {
if(PosDer) PosDer->clear();
if(ParamDer) ParamDer->clear();
double val = 0;
if(with_core) val += PixValue(Xc,Yc,IPix, JPix, Params, PosDer, ParamDer);
#ifdef EXTERNAL_TAIL
#ifdef INTEGRATING_TAIL
if(with_tail && !with_core) {
double prof = TailProfile(IPix-Xc,JPix-Yc, Params, with_core);
if(ParamDer) (*ParamDer)(psf_tail_amplitude_index) = prof;
val += Params(psf_tail_amplitude_index)*prof;
}
#else
if(with_tail) {
double prof = TailProfile(IPix-Xc,JPix-Yc, Params, with_core);
if(ParamDer) (*ParamDer)(psf_tail_amplitude_index) = prof;
val += Params(psf_tail_amplitude_index)*prof;
}
#endif
#endif
return val;
}
//! Access to the current PSF, with user provided Params.
double specex::PSF::PSFValueWithParamsFW(const int fiber, const double &wave,
const int IPix, const int JPix,
const harp::vector_double &Params,
harp::vector_double *PosDer, harp::vector_double *ParamDer,
bool with_core, bool with_tail) const {
double X=Xccd(fiber,wave);
double Y=Yccd(fiber,wave);
return PSFValueWithParamsFW(X,Y,IPix,JPix,Params,PosDer,ParamDer,with_core,with_tail);
}
//! Access to the current PSF
double specex::PSF::PSFValueFW(const int fiber, const double &wave,
const int IPix, const int JPix, int bundle_id,
harp::vector_double *PosDer, harp::vector_double *ParamDer,
bool with_core, bool with_tail) const {
double X=Xccd(fiber,wave);
double Y=Yccd(fiber,wave);
return PSFValueWithParamsXY(X,Y,IPix,JPix,AllLocalParamsXW(X,wave,bundle_id), PosDer, ParamDer);
}
int specex::PSF::GetBundleOfFiber(int fiber) const {
// find bundle for this fiber
int bundle=0;
bool found=false;
for(std::map<int,specex::PSF_Params>::const_iterator it=ParamsOfBundles.begin() ; it != ParamsOfBundles.end(); ++it) {
if (fiber>=it->second.fiber_min && fiber<=it->second.fiber_max) {
SPECEX_DEBUG("Found bundle of fiber #" << fiber << " : " << it->first);
bundle=it->first;
found=true;
break;
}
}
if(!found) {
SPECEX_ERROR("Did not find any bundle for fiber #" << fiber);
}
return bundle;
}
harp::vector_double specex::PSF::AllLocalParamsXW(const double &X, const double &wave, int bundle_id) const {
std::map<int,PSF_Params>::const_iterator it = ParamsOfBundles.find(bundle_id);
if(it==ParamsOfBundles.end()) SPECEX_ERROR("no such bundle #" << bundle_id);
const std::vector<Pol_p>& P=it->second.AllParPolXW;
harp::vector_double params(P.size());
for (size_t k =0; k < P.size(); ++k)
params(k) = P[k]->Value(X,wave);
return params;
}
harp::vector_double specex::PSF::AllLocalParamsFW(const int fiber, const double &wave, int bundle_id) const {
if(bundle_id<0) { // not given
bundle_id = GetBundleOfFiber(fiber);
}
double X=Xccd(fiber,wave);
return AllLocalParamsXW(X,wave,bundle_id);
}
harp::vector_double specex::PSF::FitLocalParamsXW(const double &X, const double &wave, int bundle_id) const {
std::map<int,PSF_Params>::const_iterator it = ParamsOfBundles.find(bundle_id);
if(it==ParamsOfBundles.end()) SPECEX_ERROR("no such bundle #" << bundle_id);
const std::vector<Pol_p>& P=it->second.FitParPolXW;
harp::vector_double params(P.size());
for (size_t k =0; k < P.size(); ++k)
params(k) = P[k]->Value(X,wave);
return params;
}
harp::vector_double specex::PSF::FitLocalParamsFW(const int fiber, const double &wave, int bundle_id) const {
double X=Xccd(fiber,wave);
return FitLocalParamsXW(X,wave,bundle_id);
}
harp::vector_double specex::PSF::AllLocalParamsXW_with_AllBundleParams(const double &X, const double &wave, int bundle_id, const harp::vector_double& ForThesePSFParams) const {
std::map<int,PSF_Params>::const_iterator it = ParamsOfBundles.find(bundle_id);
if(it==ParamsOfBundles.end()) SPECEX_ERROR("no such bundle #" << bundle_id);
const std::vector<Pol_p>& P=it->second.AllParPolXW;
harp::vector_double params(LocalNAllPar());
if(BundleNAllPar(bundle_id)>ForThesePSFParams.size()) SPECEX_ERROR("VaryingCoordNPar(bundle_id)<=ForThesePSFParams.size()");
int index=0;
for (size_t k =0; k < P.size(); ++k) {
size_t c_size = P[k]->coeff.size();
params(k)=specex::dot(ublas::project(ForThesePSFParams,ublas::range(index,index+c_size)),P[k]->Monomials(X,wave));
index += c_size;
}
return params;
}
harp::vector_double specex::PSF::AllLocalParamsFW_with_AllBundleParams(const int fiber, const double &wave, int bundle_id, const harp::vector_double& ForThesePSFParams) const {
double X=Xccd(fiber,wave);
return AllLocalParamsXW_with_AllBundleParams(X,wave,bundle_id,ForThesePSFParams);
}
harp::vector_double specex::PSF::AllLocalParamsXW_with_FitBundleParams(const double &X, const double &wave, int bundle_id, const harp::vector_double& ForThesePSFParams) const {
harp::vector_double params(LocalNAllPar());
std::map<int,PSF_Params>::const_iterator it = ParamsOfBundles.find(bundle_id);
if(it==ParamsOfBundles.end()) SPECEX_ERROR("no such bundle #" << bundle_id);
const std::vector<Pol_p>& AP=it->second.AllParPolXW;
const std::vector<Pol_p>& FP=it->second.FitParPolXW;
// whe need to find which param is fixed and which is not
size_t fk=0;
int index=0;
for (size_t ak =0; ak < AP.size(); ++ak) { // loop on all params
const Pol_p APk = AP[ak];
if((fk<FP.size()) && (APk==FP[fk])) { // this is a fit param because the addresses are the same
size_t c_size = APk->coeff.size();
params(ak)=specex::dot(ublas::project(ForThesePSFParams,ublas::range(index,index+c_size)),APk->Monomials(X,wave));
//SPECEX_INFO("DEBUG all param " << ak << " and fit = " << fk << " are the same, param val = " << params(ak));
index += c_size;
// change free param index for next iteration
fk++;
}else{ // this not a free param
params(ak)=APk->Value(X,wave);
//SPECEX_INFO("DEBUG all param " << ak << " is not it fit, param val = " << params(ak));
}
}
return params;
}
harp::vector_double specex::PSF::AllLocalParamsFW_with_FitBundleParams(const int fiber, const double &wave, int bundle_id, const harp::vector_double& ForThesePSFParams) const {
double X=Xccd(fiber,wave);
return AllLocalParamsXW_with_FitBundleParams(X,wave,bundle_id,ForThesePSFParams);
}
harp::vector_double specex::PSF::FitLocalParamsXW_with_FitBundleParams(const double &X, const double &wave, int bundle_id, const harp::vector_double& ForThesePSFParams) const {
std::map<int,PSF_Params>::const_iterator it = ParamsOfBundles.find(bundle_id);
if(it==ParamsOfBundles.end()) SPECEX_ERROR("no such bundle #" << bundle_id);
const std::vector<Pol_p>& P=it->second.FitParPolXW;
harp::vector_double params(P.size());
if(BundleNFitPar(bundle_id)>ForThesePSFParams.size()) SPECEX_ERROR("VaryingCoordNPar(bundle_id)<=ForThesePSFParams.size()");
int index=0;
for (size_t k =0; k < P.size(); ++k) {
size_t c_size = P[k]->coeff.size();
params(k)=specex::dot(ublas::project(ForThesePSFParams,ublas::range(index,index+c_size)),P[k]->Monomials(X,wave));
index += c_size;
}
return params;
}
harp::vector_double specex::PSF::FitLocalParamsFW_with_FitBundleParams(const int fiber, const double &wave, int bundle_id, const harp::vector_double& ForThesePSFParams) const {
double X=Xccd(fiber,wave);
return FitLocalParamsXW_with_FitBundleParams(X,wave,bundle_id,ForThesePSFParams);
}
bool specex::PSF::IsLinear() const {
if(Name() == "GAUSSHERMITE") return true;
return false;
}
/*
void specex::PSF::WriteFits(const std::string& filename, int first_hdu) const {
fitsfile * fp;
harp::fits::create ( fp, filename );
WriteFits(fp,first_hdu);
harp::fits::close ( fp );
SPECEX_INFO("wrote psf in " << filename);
}
void specex::PSF::ReadFits(const std::string& filename, int first_hdu) {
fitsfile * fp;
harp::fits::open_read ( fp, filename );
ReadFits(fp,first_hdu);
harp::fits::close ( fp );
SPECEX_INFO("read psf in " << filename);
}
*/
| 32.582759 | 208 | 0.68457 | [
"vector"
] |
efffe74469ead0b2551a8160a0b6fb58b2abde72 | 2,001 | cpp | C++ | tree/102_Binary_Tree_Level_Order_Traversal.cpp | zephyr-fun/LeetCodeSolution | adab165bcd269daf3e611a26187977ccd458d02a | [
"MIT"
] | null | null | null | tree/102_Binary_Tree_Level_Order_Traversal.cpp | zephyr-fun/LeetCodeSolution | adab165bcd269daf3e611a26187977ccd458d02a | [
"MIT"
] | null | null | null | tree/102_Binary_Tree_Level_Order_Traversal.cpp | zephyr-fun/LeetCodeSolution | adab165bcd269daf3e611a26187977ccd458d02a | [
"MIT"
] | null | null | null | /***
* Author: zephyr
* Date: 2020-12-01 22:26:48
* LastEditors: zephyr
* LastEditTime: 2021-01-04 09:50:08
* FilePath: \tree\102_Binary_Tree_Level_Order_Traversal.cpp
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> res;
if(!root)
return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int currentLevelSize = q.size();
res.emplace_back(vector<int> ());
for(int i = 1; i<=currentLevelSize; i++)
{
auto node = q.front();
q.pop();
res.back().emplace_back(node->val);
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
}
return res;
}
// way 2
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> res;
if(!root)
return res;
queue<TreeNode*> q_node;
q_node.push(root);
while(!q_node.empty())
{
int levelsize = q_node.size();
vector<int> temp;
for(int i = 0; i < levelsize; i++)
{
auto node = q_node.front();
q_node.pop();
temp.emplace_back(node->val);
if(node->left)
q_node.push(node->left);
if(node->right)
q_node.push(node->right);
}
res.emplace_back(temp);
}
return res;
} | 25.0125 | 90 | 0.543228 | [
"vector"
] |
5601b138985ceddc3c019083e506d0d0f4d25412 | 3,038 | hpp | C++ | Falcor/Samples/SSTDemo/Utils/TRT/InferenceEngine.hpp | wotatz/sst-demo | 5c8422d59102dc2ef61a1cbf07d9bbc10a5925f9 | [
"BSD-3-Clause"
] | 14 | 2020-05-12T22:19:20.000Z | 2022-01-30T18:08:29.000Z | Falcor/Samples/SSTDemo/Utils/TRT/InferenceEngine.hpp | wotatz/sst-demo | 5c8422d59102dc2ef61a1cbf07d9bbc10a5925f9 | [
"BSD-3-Clause"
] | null | null | null | Falcor/Samples/SSTDemo/Utils/TRT/InferenceEngine.hpp | wotatz/sst-demo | 5c8422d59102dc2ef61a1cbf07d9bbc10a5925f9 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "Falcor.h"
#include "FalcorCUDA.h"
#include "Utils/Cuda/CudaBuffer.h"
#include "NvInfer.h"
#include <memory>
#include <string>
#include <vector>
// Logger for TensorRT info/warning/errors (TensorRT example : 'sample_uff_mnist')
class Logger : public nvinfer1::ILogger
{
public:
Logger(Severity severity = Severity::kERROR) : reportableSeverity(severity) {}
void log(Severity severity, const char* msg) override
{
// suppress messages with severity enum value greater than the reportable
if (severity > reportableSeverity)
return;
switch (severity)
{
case Severity::kINTERNAL_ERROR: Falcor::logError(msg);
break;
case Severity::kERROR: Falcor::logError(msg);
break;
case Severity::kWARNING: Falcor::logWarning(msg);
break;
case Severity::kINFO: Falcor::logInfo(msg);
break;
default: break;
}
}
Severity reportableSeverity;
};
namespace nvinfer1
{
class ICudaEngine;
class IExecutionContext;
}
class InferenceEngine
{
public:
using UniquePtr = std::unique_ptr<InferenceEngine>;
struct NvInferDeleter
{
template <typename T>
void operator()(T* obj) const
{
if (obj)
{
obj->destroy();
}
}
};
struct BufferInfo
{
std::string mName;
nvinfer1::DataType mDtype;
uint64_t mSize = 0;
bool mIsInput = false;
};
static InferenceEngine::UniquePtr create(const std::string& path, const char* name, int batchSize = 1);
static InferenceEngine::UniquePtr create(nvinfer1::ICudaEngine* pEngine, const char* name, int batchSize = 1);
InferenceEngine(const char* name, int batchSize);
~InferenceEngine();
bool isValid() const { return mpEngine != nullptr && mpContext != nullptr; }
bool serialze(const std::string& path) const;
void reset();
std::vector<BufferInfo> getBufferInfos() const;
std::vector<CudaBuffer<void>> generateCudaBuffers(bool generateInputBuffers);
size_t getEngineDeviceMemoryInMB() const { return mEngineDeviceMemory; }
size_t getAllocatedBufferMemoryMB() const { return mAllocatedBufferMemory; }
nvinfer1::ICudaEngine* getEngine() const { return mpEngine.get(); }
nvinfer1::IExecutionContext* getExecutionContext() const { return mpContext.get(); }
const std::string& getName() const { return mName; }
int getNumInputs() const;
int getNumOutputs() const;
void executeAsync(void** bindings, FalcorCUDA::cudaStream_t stream);
void executeBlocking(void** bindings);
private:
void calculateDeviceMemoryinMB();
bool createExecutionContext();
bool deserialze(const std::string& path);
std::string mName;
std::unique_ptr<nvinfer1::ICudaEngine, NvInferDeleter> mpEngine = nullptr;
std::unique_ptr<nvinfer1::IExecutionContext, NvInferDeleter> mpContext = nullptr;
int mBatchSize;
size_t mWorkspaceSize = 0;
size_t mEngineDeviceMemory = 0;
size_t mAllocatedBufferMemory = 0;
};
| 26.649123 | 114 | 0.686636 | [
"vector"
] |
56051d0b19bc7c5d376d5b29a45c8dcda06256dd | 9,745 | cpp | C++ | Axis.Capsicum/application/executors/gpu/facades/GPUSolverFacade.cpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | 2 | 2021-07-23T08:49:54.000Z | 2021-07-29T22:07:30.000Z | Axis.Capsicum/application/executors/gpu/facades/GPUSolverFacade.cpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | Axis.Capsicum/application/executors/gpu/facades/GPUSolverFacade.cpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | #include "GPUSolverFacade.hpp"
#include "application/executors/gpu/commands/GatherVectorCommand.hpp"
#include "application/executors/gpu/commands/PushBcToVectorCommand.hpp"
#include "domain/analyses/NumericalModel.hpp"
#include "domain/analyses/ReducedNumericalModel.hpp"
#include "domain/analyses/ModelOperatorFacade.hpp"
#include "foundation/memory/pointer.hpp"
namespace aaegc = axis::application::executors::gpu::commands;
namespace aaegf = axis::application::executors::gpu::facades;
namespace ada = axis::domain::analyses;
namespace adbc = axis::domain::boundary_conditions;
namespace adc = axis::domain::collections;
namespace adcu = axis::domain::curves;
namespace ade = axis::domain::elements;
namespace assg = axis::services::scheduling::gpu;
namespace afc = axis::foundation::computing;
namespace afm = axis::foundation::memory;
aaegf::GPUSolverFacade::GPUSolverFacade(void)
{
solverTask_ = nullptr;
}
aaegf::GPUSolverFacade::~GPUSolverFacade(void)
{
delete solverTask_;
DeleteTaskList(curves_);
DeleteTaskList(accelerationBcs_);
DeleteTaskList(velocityBcs_);
DeleteTaskList(displacementBcs_);
DeleteTaskList(loadsBcs_);
DeleteTaskList(locksBcs_);
}
void aaegf::GPUSolverFacade::SetSolverTask( assg::GPUTask& task )
{
if (solverTask_ != nullptr && solverTask_ != &task)
{
delete solverTask_;
}
solverTask_ = &task;
}
void aaegf::GPUSolverFacade::AddBoundaryConditionTask(
adbc::BoundaryCondition::ConstraintType type, assg::GPUTask& task,
adbc::BoundaryConditionUpdateCommand& command, size_type blockSize)
{
bc_tuple tuple(task, command, blockSize);
switch (type)
{
case adbc::BoundaryCondition::PrescribedDisplacement:
displacementBcs_.push_back(tuple);
break;
case adbc::BoundaryCondition::PrescribedVelocity:
velocityBcs_.push_back(tuple);
break;
case adbc::BoundaryCondition::NodalLoad:
loadsBcs_.push_back(tuple);
break;
case adbc::BoundaryCondition::Lock:
locksBcs_.push_back(tuple);
break;
default:
assert(!"Unknown boundary condition type!");
break;
}
}
void aaegf::GPUSolverFacade::AddCurveTask( assg::GPUTask& task,
adcu::CurveUpdateCommand& command, size_type blockSize)
{
curves_.push_back(curve_tuple(task, command, blockSize));
}
void aaegf::GPUSolverFacade::AllocateMemory( void )
{
solverTask_->AllocateMemory();
AllocateTaskListMemory(curves_);
AllocateTaskListMemory(accelerationBcs_);
AllocateTaskListMemory(velocityBcs_);
AllocateTaskListMemory(displacementBcs_);
AllocateTaskListMemory(loadsBcs_);
AllocateTaskListMemory(locksBcs_);
}
void aaegf::GPUSolverFacade::DeallocateMemory( void )
{
solverTask_->DeallocateMemory();
DeallocateTaskListMemory(curves_);
DeallocateTaskListMemory(accelerationBcs_);
DeallocateTaskListMemory(velocityBcs_);
DeallocateTaskListMemory(displacementBcs_);
DeallocateTaskListMemory(loadsBcs_);
DeallocateTaskListMemory(locksBcs_);
}
void aaegf::GPUSolverFacade::InitMemory( void )
{
solverTask_->InitMemory();
InitTaskListMemory(curves_);
InitTaskListMemory(accelerationBcs_);
InitTaskListMemory(velocityBcs_);
InitTaskListMemory(displacementBcs_);
InitTaskListMemory(loadsBcs_);
InitTaskListMemory(locksBcs_);
}
void aaegf::GPUSolverFacade::Mirror( void )
{
solverTask_->Mirror();
MirrorTaskListMemory(curves_);
MirrorTaskListMemory(accelerationBcs_);
MirrorTaskListMemory(velocityBcs_);
MirrorTaskListMemory(displacementBcs_);
MirrorTaskListMemory(loadsBcs_);
MirrorTaskListMemory(locksBcs_);
}
void aaegf::GPUSolverFacade::Restore( void )
{
solverTask_->Restore();
RestoreTaskListMemory(curves_);
RestoreTaskListMemory(accelerationBcs_);
RestoreTaskListMemory(velocityBcs_);
RestoreTaskListMemory(displacementBcs_);
RestoreTaskListMemory(loadsBcs_);
RestoreTaskListMemory(locksBcs_);
}
void aaegf::GPUSolverFacade::ClaimMemory( void *baseAddress, uint64 blockSize )
{
solverTask_->ClaimMemory(baseAddress, blockSize);
}
void aaegf::GPUSolverFacade::ReturnMemory( void *baseAddress )
{
solverTask_->ReturnMemory(baseAddress);
}
void * aaegf::GPUSolverFacade::GetGPUModelArenaAddress( void ) const
{
return solverTask_->GetDeviceMemoryAddress(0);
}
void aaegf::GPUSolverFacade::UpdateCurves( real time )
{
curve_task_list::iterator end = curves_.end();
for (curve_task_list::iterator it = curves_.begin(); it != end; ++it)
{ // run asynchronously...
adcu::CurveUpdateCommand& curveCmd = *it->GPUCommand;
assg::GPUTask& curveTask = *it->Task;
curveCmd.SetTime(time);
curveTask.RunCommand(curveCmd);
}
for (curve_task_list::iterator it = curves_.begin(); it != end; ++it)
{ // ...and then synchronize
assg::GPUTask& curveTask = *it->Task;
curveTask.Synchronize();
}
}
void aaegf::GPUSolverFacade::UpdateAccelerations(
afm::RelativePointer& globalAccelerationVector, real time,
afm::RelativePointer& vectorMask)
{
UpdateBoundaryCondition(accelerationBcs_, globalAccelerationVector, time,
vectorMask, false);
}
void aaegf::GPUSolverFacade::UpdateVelocities(
afm::RelativePointer& globalVelocityVector, real time,
afm::RelativePointer& vectorMask)
{
UpdateBoundaryCondition(velocityBcs_, globalVelocityVector, time,
vectorMask, false);
}
void aaegf::GPUSolverFacade::UpdateDisplacements(
afm::RelativePointer& globalDisplacementVector, real time,
afm::RelativePointer& vectorMask)
{
UpdateBoundaryCondition(displacementBcs_, globalDisplacementVector,
time, vectorMask, false);
}
void aaegf::GPUSolverFacade::UpdateExternalLoads(
afm::RelativePointer& externalLoadVector, real time,
axis::foundation::memory::RelativePointer& vectorMask)
{
UpdateBoundaryCondition(loadsBcs_, externalLoadVector, time,
vectorMask, true);
}
void aaegf::GPUSolverFacade::UpdateLocks(
afm::RelativePointer& globalDisplacementVector, real time,
afm::RelativePointer& vectorMask)
{
UpdateBoundaryCondition(locksBcs_, globalDisplacementVector, time,
vectorMask, false);
}
void aaegf::GPUSolverFacade::RunKernel( afc::KernelCommand& kernel )
{
solverTask_->RunCommand(kernel);
}
void aaegf::GPUSolverFacade::GatherVector( afm::RelativePointer& vectorPtr,
afm::RelativePointer& modelPtr )
{
aaegc::GatherVectorCommand gatherCmd(modelPtr, vectorPtr);
solverTask_->RunCommand(gatherCmd);
}
void aaegf::GPUSolverFacade::Synchronize( void )
{
solverTask_->Synchronize();
}
void aaegf::GPUSolverFacade::UpdateBoundaryCondition( bc_task_list& bcTasks,
afm::RelativePointer& targetVector, real time,
afm::RelativePointer& vectorMask, bool ignoreMask)
{
bc_task_list::iterator end = bcTasks.end();
for (bc_task_list::iterator it = bcTasks.begin(); it != end; ++it)
{ // run asynchronously...
adbc::BoundaryConditionUpdateCommand& bcCmd = *it->GPUCommand;
bcCmd.Configure(time, vectorMask);
assg::GPUTask& bcTask = *it->Task;
bcTask.RunCommand(bcCmd);
}
for (bc_task_list::iterator it = bcTasks.begin(); it != end; ++it)
{ // ...and then synchronize
assg::GPUTask& bcTask = *it->Task;
bcTask.Synchronize();
}
for (bc_task_list::iterator it = bcTasks.begin(); it != end; ++it)
{ // gather results into the global vector
assg::GPUTask& bcTask = *it->Task;
aaegc::PushBcToVectorCommand gatherCmd(targetVector, vectorMask, ignoreMask, it->BlockSize);
bcTask.RunCommand(gatherCmd);
}
for (bc_task_list::iterator it = bcTasks.begin(); it != end; ++it)
{ // ...and then synchronize again
assg::GPUTask& bcTask = *it->Task;
bcTask.Synchronize();
}
}
template <class T>
void aaegf::GPUSolverFacade::AllocateTaskListMemory(std::list<Tuple<T>>& tasks)
{
typedef std::list<Tuple<T>> task_list;
task_list::iterator end = tasks.end();
for (task_list::iterator it = tasks.begin(); it != end; ++it)
{
(*it).Task->AllocateMemory();
}
}
template <class T>
void aaegf::GPUSolverFacade::DeallocateTaskListMemory(std::list<Tuple<T>>& tasks)
{
typedef std::list<Tuple<T>> task_list;
task_list::iterator end = tasks.end();
for (task_list::iterator it = tasks.begin(); it != end; ++it)
{
(*it).Task->DeallocateMemory();
}
}
template <class T>
void aaegf::GPUSolverFacade::InitTaskListMemory(std::list<Tuple<T>>& tasks)
{
typedef std::list<Tuple<T>> task_list;
task_list::iterator end = tasks.end();
for (task_list::iterator it = tasks.begin(); it != end; ++it)
{
(*it).Task->InitMemory();
}
}
template <class T>
void aaegf::GPUSolverFacade::MirrorTaskListMemory(std::list<Tuple<T>>& tasks)
{
typedef std::list<Tuple<T>> task_list;
task_list::iterator end = tasks.end();
for (task_list::iterator it = tasks.begin(); it != end; ++it)
{
(*it).Task->Mirror();
}
}
template <class T>
void aaegf::GPUSolverFacade::RestoreTaskListMemory(std::list<Tuple<T>>& tasks)
{
typedef std::list<Tuple<T>> task_list;
task_list::iterator end = tasks.end();
for (task_list::iterator it = tasks.begin(); it != end; ++it)
{
(*it).Task->Restore();
}
}
template <class T>
void aaegf::GPUSolverFacade::DeleteTaskList( std::list<Tuple<T>>& tasks )
{
typedef std::list<Tuple<T>> task_list;
task_list::iterator end = tasks.end();
for (task_list::iterator it = tasks.begin(); it != end; ++it)
{
delete (*it).Task;
}
}
void aaegf::GPUSolverFacade::PrepareForCollectionRound( ada::ReducedNumericalModel& model )
{
solverTask_->Restore();
ada::ModelOperatorFacade& mof = model.GetOperator();
mof.RefreshLocalMemory();
}
template <class T>
aaegf::GPUSolverFacade::Tuple<T>::Tuple( assg::GPUTask& bcTask, T& command,
size_type blockSize )
{
Task = &bcTask;
GPUCommand = &command;
BlockSize = blockSize;
}
| 29.089552 | 96 | 0.733197 | [
"vector",
"model"
] |
56060f3d32c948453d68ae30eaa7eec501575b0c | 4,273 | cpp | C++ | SEngine/source/Engine.cpp | subr3v/s-engine | d77b9ccd0fff3982a303f14ce809691a570f61a3 | [
"MIT"
] | 2 | 2016-04-01T21:10:33.000Z | 2018-02-26T19:36:56.000Z | SEngine/source/Engine.cpp | subr3v/s-engine | d77b9ccd0fff3982a303f14ce809691a570f61a3 | [
"MIT"
] | 1 | 2017-04-05T01:33:08.000Z | 2017-04-05T01:33:08.000Z | SEngine/source/Engine.cpp | subr3v/s-engine | d77b9ccd0fff3982a303f14ce809691a570f61a3 | [
"MIT"
] | null | null | null | #include "Engine.h"
#include "ConfigVariableManager.h"
#include "ImGuiEngine.h"
#include "NetworkEventHandler.h"
#include "MaterialManager.h"
#include "Scene.h"
#include "EngineVariables.h"
#include "Profiler.h"
namespace SEngine
{
struct FEngineModules
{
FTimer* Timer;
FWindow* Window;
FInput* Input;
FNetworkEventHandler* NetworkEventHandler;
FGraphicsContext* GraphicsContext;
FMaterialManager* MaterialManager;
FImGuiImpl* ImGui;
FScene* CurrentScene;
FScene* NextScene;
};
FEngineModules EngineModules;
static void InitCore(HINSTANCE hInstance, int nCmdShow)
{
FConfigVariableManager::Get().Initialise();
// Startup socket version 2.2
WSADATA w;
int error = WSAStartup(0x0202, &w);
int32 Width = EngineVariables::WindowWidth.AsInt();
int32 Height = EngineVariables::WindowHeight.AsInt();
std::string& WindowTitle = EngineVariables::WindowTitle.AsString();
// Core Module
EngineModules.Window = new FWindow(hInstance, nCmdShow, Width, Height);
EngineModules.Input = new FInput();
EngineModules.NetworkEventHandler = new FNetworkEventHandler();
EngineModules.Timer = new FTimer();
EngineModules.Window->SetTitle(WindowTitle);
EngineModules.Window->RegisterEventHandler(EngineModules.Input);
EngineModules.Window->RegisterEventHandler(EngineModules.NetworkEventHandler);
}
static void ShutdownCore()
{
delete EngineModules.Timer;
delete EngineModules.NetworkEventHandler;
delete EngineModules.Input;
delete EngineModules.Window;
// Shuts down sockets
WSACleanup();
FConfigVariableManager::Get().Shutdown();
}
static void InitRendering()
{
EngineModules.GraphicsContext = new FGraphicsContext(EngineModules.Window->GetHandle());
EngineModules.MaterialManager = new FMaterialManager(EngineModules.GraphicsContext);
EngineModules.MaterialManager->LoadMaterials();
}
static void ShutdownRendering()
{
delete EngineModules.MaterialManager;
delete EngineModules.GraphicsContext;
}
static void InitImGui()
{
EngineModules.ImGui = new FImGuiImpl(EngineModules.GraphicsContext, EngineModules.MaterialManager, EngineModules.Input);
EngineModules.ImGui->Init();
}
static void ShutdownImGui()
{
delete EngineModules.ImGui;
}
void Init(HINSTANCE hInstance, int nCmdShow)
{
// Make sure everything is zero-ed out.
memset(&EngineModules, 0, sizeof(FEngineModules));
InitCore(hInstance, nCmdShow);
InitRendering();
InitImGui();
}
void Shutdown()
{
ShutdownImGui();
ShutdownRendering();
ShutdownCore();
}
void Run(FScene* StartingScene)
{
ChangeScene(StartingScene);
float DeltaTime = 0.0f;
FTimer* Timer = EngineModules.Timer;
Timer->Start();
while (EngineModules.Window->HandleEvents())
{
Timer->Restart();
DeltaTime = Timer->GetElapsedTimeSeconds();
FProfiler::Get().PushSection("Engine", "Update");
EngineModules.ImGui->Update(DeltaTime);
if (EngineModules.CurrentScene != nullptr)
{
EngineModules.CurrentScene->Update(DeltaTime);
FProfiler::Get().PopSection();
EngineModules.CurrentScene->Render(DeltaTime);
}
else
{
FProfiler::Get().PopSection();
}
EngineModules.ImGui->Render();
EngineModules.GraphicsContext->SwapBuffers();
if (EngineModules.NextScene != nullptr)
{
if (EngineModules.CurrentScene != nullptr)
{
EngineModules.CurrentScene->Unload();
delete EngineModules.CurrentScene;
}
EngineModules.CurrentScene = EngineModules.NextScene;
EngineModules.CurrentScene->Load();
EngineModules.NextScene = nullptr;
}
EngineModules.Input->SignalFrameEnded();
FProfiler::Get().OnFrameEnded();
}
if (EngineModules.CurrentScene != nullptr)
{
EngineModules.CurrentScene->Unload();
delete EngineModules.CurrentScene;
EngineModules.CurrentScene = nullptr;
}
}
FWindow* SEngine::GetWindow()
{
return EngineModules.Window;
}
FGraphicsContext* SEngine::GetGraphicsContext()
{
return EngineModules.GraphicsContext;
}
FMaterialManager* SEngine::GetMaterialManager()
{
return EngineModules.MaterialManager;
}
FInput* SEngine::GetInput()
{
return EngineModules.Input;
}
FTimer* SEngine::GetTimer()
{
return EngineModules.Timer;
}
FNetworkEventHandler* SEngine::GetNetworkEventHandler()
{
return EngineModules.NetworkEventHandler;
}
void SEngine::ChangeScene(FScene* NextScene)
{
EngineModules.NextScene = NextScene;
}
}
| 21.912821 | 121 | 0.765738 | [
"render"
] |
5608e28f99999b60846ffae6078b3124260f8bc4 | 1,079 | cc | C++ | aoj/volumn5/0505/0505aoj.cc | punkieL/proCon | 7e994d67e5efdf7ac0b1bee5e0b19b317f07e8af | [
"MIT"
] | 1 | 2015-10-06T16:27:42.000Z | 2015-10-06T16:27:42.000Z | aoj/volumn5/0505/0505aoj.cc | punkieL/proCon | 7e994d67e5efdf7ac0b1bee5e0b19b317f07e8af | [
"MIT"
] | 1 | 2016-03-02T16:18:11.000Z | 2016-03-02T16:18:11.000Z | aoj/volumn5/0505/0505aoj.cc | punkieL/proCon | 7e994d67e5efdf7ac0b1bee5e0b19b317f07e8af | [
"MIT"
] | null | null | null | /*c++98*/
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <cmath>
using namespace std;
int main(int args, char *argc[]){
int student,locations;
//ifstream ifs("input.txt");
while(cin>>student>>locations, student&&locations){
int wishes[locations];
for(int i=0;i<locations;i++)
wishes[i]=0;//,printf("wishes[%d]:%d ",i,wishes[i]);printf("\n");
int stu=student;
while(stu--){
int loc=locations;
while(loc--){
int tmp;cin>>tmp;
wishes[locations-loc-1]+=tmp;
}
}
/*for(int i=0;i<locations;i++)
printf("wishes[%d]:%d ",i,wishes[i]);printf("\n");*/
map<double,int> res;
int loc=locations;
while(loc--){
res.insert(make_pair((double)wishes[loc]-(double)loc/100,loc));
}
for(map<double,int>::iterator iz=(--res.end());
iz!=res.begin();iz--)
//cout<<"("<<(iz->first)<<")",
cout<<(iz->second)+1<<" ";
cout<<(res.begin())->second+1<<"\n";
}
return 0;
}
| 22.479167 | 71 | 0.570899 | [
"vector"
] |
560e216a69c4cc703a4486cd10bd2ec12a72a0f1 | 6,033 | cpp | C++ | directfire_github/trunk/gameui/battle.net/gamepage.cpp | zhwsh00/DirectFire-android | 10c757e1be0b25dee951f9ba3a0e1f6d5c04a938 | [
"MIT"
] | 1 | 2015-08-12T04:05:33.000Z | 2015-08-12T04:05:33.000Z | directfire_github/trunk/gameui/battle.net/gamepage.cpp | zhwsh00/DirectFire-android | 10c757e1be0b25dee951f9ba3a0e1f6d5c04a938 | [
"MIT"
] | null | null | null | directfire_github/trunk/gameui/battle.net/gamepage.cpp | zhwsh00/DirectFire-android | 10c757e1be0b25dee951f9ba3a0e1f6d5c04a938 | [
"MIT"
] | null | null | null | #include "gamepage.h"
#include "gamepageitem.h"
#include "gamepagetitle.h"
#include "gamecore/resource/resourcemgr.h"
#include "gamecore/sounds/soundmgr.h"
#include "gamecore/utils/ccutils.h"
#include <algorithm>
using namespace std;
GamePage::GamePage(uilib::BasWidget *container) : BasPage(container)
{
m_title = new GamePageTitle;
LangDef *lang = ResourceMgr::getInstance()->getLangDef();
m_title->setTitle(lang->getStringById(StringEnum::GameList));
m_title->setRefreshCB(this,callfuncND_selector(GamePage::onTitleRefreshClick));
m_title->setSortByMapNameCB(this,callfuncND_selector(GamePage::onTitleNameSortClick));
m_title->setSortByPlayerNumCB(this,callfuncND_selector(GamePage::onTitleNumSortClick));
m_title->setTowerModelCB(this,callfuncND_selector(GamePage::onTitleTdModeClick));
m_title->setDfModelCB(this,callfuncND_selector(GamePage::onTitleDfModeClick));
this->addChild(m_title);
float srate = getAdaptResourceScale();
m_title->setLeft("parent",uilib::Left);
m_title->setBottom("parent",uilib::Top);
m_title->setLeftMargin(20);
m_title->setRightMargin(20);
m_title->setWidth(610 * srate);
m_title->setHeight(92 * srate);
this->setTopMargin(30);
m_scrollList = new VerScrollWidget("","");
m_scrollList->setMargins(5);
this->addChild(m_scrollList);
m_scrollList->setLeft("parent",uilib::Left);
m_scrollList->setRight("parent",uilib::Right);
m_scrollList->setTop("parent",uilib::Top);
m_scrollList->setTopMargin(10);
m_scrollList->setBottom("parent",uilib::Bottom);
m_scrollList->setSpacing(20);
m_scrollList->setVerticalScrollPolicy(uilib::ScrollShow_Never);
m_scrollList->setHorizontalScrollPolicy(uilib::ScrollShow_Never);
m_init = false;
m_serverIface = ServerInterface::getInstance();
m_gameType = GameType::RunType_Battle;
}
GamePage::~GamePage()
{
}
void GamePage::resetHallInfo(int sortType)
{
m_scrollList->delAllFixedSizeWidget();
m_rooms.clear();
m_runRooms.clear();
m_serverIface->getHallRoomInfo(m_rooms);
const std::vector<UiMsgEv::MapInfo> *mapsInfo = m_serverIface->getMapsInfo();
std::vector<int> noadds;
int mapType;
if(m_gameType == GameType::RunType_Battle){
mapType = 0;
}else if(m_gameType == GameType::RunType_Td){
mapType = 1;
}else{
mapType = 0;//toll is no supported,just set to battle mode
}
for(unsigned int i = 0;i < mapsInfo->size();i++){
bool add = false;
const UiMsgEv::MapInfo &map = mapsInfo->at(i);
for(unsigned int k = 0;k < m_rooms.size();k++){
UiMsgEv::RoomMapInfoEv &ev = m_rooms[k];
if(ev.m_mapType == mapType && ev.m_mapId == map.m_mapId){
ev.m_alignNum = map.m_maxAlign;
ev.m_suppNum = map.m_maxPlayer;
ev.m_mapAbbrevName = map.m_mapAbbvName;
ev.m_mapHeight = map.m_height;
ev.m_mapWidth = map.m_width;
ev.m_mapName = map.m_mapName;
ev.m_mapFile = map.m_gateId;
ev.m_coinCost = map.m_costGolds;
add = true;
m_runRooms.push_back(ev);
break;
}
}
if(!add && map.m_mapType == mapType){
noadds.push_back(i);
}
}
for(unsigned int i = 0;i < noadds.size();i++){
const UiMsgEv::MapInfo &map = mapsInfo->at(noadds[i]);
m_runRooms.push_back(UiMsgEv::RoomMapInfoEv());
UiMsgEv::RoomMapInfoEv &ev = m_runRooms[m_runRooms.size() - 1];
ev.m_mapId = map.m_mapId;
ev.m_alignNum = map.m_maxAlign;
ev.m_suppNum = map.m_maxPlayer;
ev.m_mapAbbrevName = map.m_mapAbbvName;
ev.m_mapHeight = map.m_height;
ev.m_mapWidth = map.m_width;
ev.m_mapName = map.m_mapName;
ev.m_mapFile = map.m_gateId;
ev.m_coinCost = map.m_costGolds;
ev.m_roomsCount = 0;
ev.m_inMapUserCount = 0;
}
if(sortType == 1)
std::sort(m_runRooms.begin(),m_runRooms.end(),game_sortByOnlineNum);
else if(sortType == 2)
std::sort(m_runRooms.begin(),m_runRooms.end(),game_sortByMapName);
float w = m_anchorWidth - m_scrollList->leftMargin() * 8;
float h = 100;
CCSize size = CCSizeMake(w,h);
for(unsigned int i = 0;i < m_runRooms.size();i++){
GamePageItem *item = new GamePageItem(this);
item->setWidth(w);
item->setHeight(h);
item->setRoomInfo(&m_runRooms[i]);
FSizeWidgetDelegate *dele = new FSizeWidgetDelegate(item,size);
m_scrollList->addFixedSizeWidget(dele);
item->finish();
}
m_init = true;
m_scrollList->layout(true);
m_scrollList->scrollToBegin(true);
}
void GamePage::moveinPage()
{
if(m_init){
if(m_scrollList->scrollItemCount() == 0
&& !m_title->isRefreshing())
m_serverIface->refreshHallInfo(m_gameType);
}else{
m_serverIface->refreshHallInfo(m_gameType);
}
}
void GamePage::moveoutPage()
{
}
void GamePage::startRefreshing()
{
if(m_title)
m_title->setRefreshing(true);
}
void GamePage::endRefreshing()
{
if(m_title)
m_title->setRefreshing(false);
}
void GamePage::setGameType(GameType::RunType type)
{
m_gameType = type;
}
GameType::RunType GamePage::getGameType()
{
return m_gameType;
}
void GamePage::onTitleRefreshClick(CCNode *node,void *data)
{
SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL);
if(!m_title->isRefreshing())
m_serverIface->refreshHallInfo();
}
void GamePage::onTitleNameSortClick(CCNode *node,void *data)
{
resetHallInfo(2);
}
void GamePage::onTitleNumSortClick(CCNode *node,void *data)
{
resetHallInfo(1);
}
void GamePage::onTitleTdModeClick(CCNode *node,void *data)
{
m_gameType = GameType::RunType_Td;
resetHallInfo(2);
}
void GamePage::onTitleDfModeClick(CCNode *node,void *data)
{
m_gameType = GameType::RunType_Battle;
resetHallInfo(2);
}
| 32.610811 | 91 | 0.658213 | [
"vector"
] |
56219628268ad3edd7add4d673e549cbdb5d5efd | 630 | cpp | C++ | Directx11FPS/Scenes/ParticipateTest.cpp | sekys/FPS | d582b6b5fb55adc88b6c4aa6a4cd2145488db31f | [
"MIT"
] | null | null | null | Directx11FPS/Scenes/ParticipateTest.cpp | sekys/FPS | d582b6b5fb55adc88b6c4aa6a4cd2145488db31f | [
"MIT"
] | null | null | null | Directx11FPS/Scenes/ParticipateTest.cpp | sekys/FPS | d582b6b5fb55adc88b6c4aa6a4cd2145488db31f | [
"MIT"
] | 1 | 2018-03-27T16:02:28.000Z | 2018-03-27T16:02:28.000Z | #include "./classes/App/class.Game.h"
#include "ParticipateTest.h"
#include "./classes/Help/Base/class.ParticipateSystem.h"
ParticipateTest::ParticipateTest()
{
parts = new Participate();
}
PLUGIN ParticipateTest::Init() {
parts->gravitacia = true;
parts->box.SetSize(vec(0.0, 0.0, 0.0) ,
vec(-200.0f, -200.0f, 200.0f) ,
vec(200.0f, 200.0f, -200.0f) );
parts->Set(3000);
parts->RandomizeInBox();
PLUGIN_MSG("Participate TEST online.");
return PLUGIN_CONTINUE;
}
ParticipateTest::~ParticipateTest() {
SAFE_DELETE(parts);
}
PLUGIN ParticipateTest::Frame(double d) {
parts->Render(d);
return PLUGIN_CONTINUE;
}
| 24.230769 | 56 | 0.703175 | [
"render"
] |
5622e99b8e20ac404fd37c07935c0ae0624d3993 | 1,708 | cpp | C++ | Greedy_SOLN_jobSequencing.cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 2 | 2021-10-01T04:20:04.000Z | 2021-10-01T04:20:06.000Z | Greedy_SOLN_jobSequencing.cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 1 | 2021-10-01T18:00:09.000Z | 2021-10-01T18:00:09.000Z | Greedy_SOLN_jobSequencing.cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 8 | 2021-10-01T04:20:38.000Z | 2022-03-19T17:05:05.000Z | #include <algorithm>
#include <bits/stdc++.h>
#define ll long long
#define pb(x) push_back(x);
#define pp() pop_back()
#define vi vector<int>
#define v(x) vector<x>
#define pii pair<int, int>
#define pqq priority_queue
#define g(x) greater<x>
#define all(arr) arr.begin(), arr.end()
#define loop(i, n) for (int i = 0; i < n; i++)
#define MOD ll(1e9 + 7)
#define tests(t) \
int t; \
cin >> t; \
while (t--)
using namespace std;
void Solve(vector<pii> &jobs, int n, int &noOfJobs, int &maxProfit)
{
sort(all(jobs), greater<pii>()); //sorted based on max profit -> min profit.
vector<int> slots(n, -1);
int res = 0;
loop(i, n)
{
pii temp = jobs[i];
int x = 0, deadline = temp.second;
while (x < deadline)
{
if (slots[x] == -1)
{
res += temp.first;
slots[x] = 1; //job scheduled.
break;
}
x++;
}
maxProfit = (maxProfit < res) ? res : maxProfit;
}
int x = -1;
while (++x < n)
{
if (slots[x] != -1)
noOfJobs++;
}
return;
}
int main()
{
// IOS();
tests(t)
{
cout << "Number of jobs (n) | <profit,deadline>\n";
int n;
cin >> n;
vector<pii> jobs;
loop(i, n)
{
int deadline, profit;
cin >> profit >> deadline;
jobs.push_back(make_pair(profit, deadline));
}
int noOfJobs = 0, maxProfit = 0;
Solve(jobs, n, noOfJobs, maxProfit);
cout << "No of Jobs Performed : " << noOfJobs << endl
<< "Max Profit : " << maxProfit << endl;
}
return 0;
} | 23.081081 | 80 | 0.485363 | [
"vector"
] |
5626fa17b7d3b4c5899f12c6b0659752dc16b434 | 1,449 | hpp | C++ | src/share/scan/src/util.hpp | RoepStoep/cordova-plugin-scan | 48ecf95ab70f053d57e7e9a9db92ec6f951a8dae | [
"MIT"
] | null | null | null | src/share/scan/src/util.hpp | RoepStoep/cordova-plugin-scan | 48ecf95ab70f053d57e7e9a9db92ec6f951a8dae | [
"MIT"
] | null | null | null | src/share/scan/src/util.hpp | RoepStoep/cordova-plugin-scan | 48ecf95ab70f053d57e7e9a9db92ec6f951a8dae | [
"MIT"
] | null | null | null |
#ifndef UTIL_HPP
#define UTIL_HPP
// includes
#include <iostream>
#include <string>
#include <vector>
#include <chrono>
#include "libmy.hpp"
// types
class Bad_Input : public std::exception {};
class Bad_Output : public std::exception {};
class Scanner_Number {
private:
const std::string m_string;
int m_pos {0};
public:
explicit Scanner_Number (const std::string & s);
std::string get_token ();
bool eos () const;
char get_char ();
void unget_char ();
};
class Timer {
private:
using time_t = std::chrono::time_point<std::chrono::system_clock>;
using second_t = std::chrono::duration<double>;
double m_elapsed {0.0};
bool m_running {false};
time_t m_start;
public:
void reset() {
m_elapsed = 0.0;
m_running = false;
}
void start() {
m_start = now();
m_running = true;
}
void stop() {
m_elapsed += time();
m_running = false;
}
double elapsed() const {
double time = m_elapsed;
if (m_running) time += this->time();
return time;
}
private:
static time_t now() {
return std::chrono::system_clock::now();
}
double time() const {
assert(m_running);
return std::chrono::duration_cast<second_t>(now() - m_start).count();
}
};
// functions
void load_file (std::vector<uint8> & table, std::istream & file);
bool string_is_nat (const std::string & s);
#endif // !defined UTIL_HPP
| 15.75 | 75 | 0.621118 | [
"vector"
] |
562e226b3a7370c9cf1360c7d72fa0dc74c46ba1 | 2,263 | hpp | C++ | core/include/cubos/core/io/sources/single_axis.hpp | GameDevTecnico/cubos | 51f89c9f3afc8afe502d167dadecab7dfe5b1c7b | [
"MIT"
] | 2 | 2021-09-28T14:13:27.000Z | 2022-03-26T11:36:48.000Z | core/include/cubos/core/io/sources/single_axis.hpp | GameDevTecnico/cubos | 51f89c9f3afc8afe502d167dadecab7dfe5b1c7b | [
"MIT"
] | 72 | 2021-09-29T08:55:26.000Z | 2022-03-29T21:21:00.000Z | core/include/cubos/core/io/sources/single_axis.hpp | GameDevTecnico/cubos | 51f89c9f3afc8afe502d167dadecab7dfe5b1c7b | [
"MIT"
] | null | null | null | #ifndef CUBOS_CORE_IO_SINGLE_AXIS_HPP
#define CUBOS_CORE_IO_SINGLE_AXIS_HPP
#include <cubos/core/io/window.hpp>
#include <cubos/core/io/sources/source.hpp>
#include <variant>
#include <tuple>
namespace cubos::core::io
{
/// SingleAxis is used to bind position change in one axis to the gameplay logic.
/// The bindings are only invoken when change in the position occurs.
/// Handles events subscription and context creation for when a change in the position in an axis.
/// Handles mouse axis and keyboard keys
/// @see Source
class SingleAxis : public Source
{
public:
/// Creates a Single Axis source associated to a mouse axis
/// @param axis the axis assoaiated to this Single Axis source
SingleAxis(cubos::core::io::MouseAxis axis);
/// Creates a Single Axis source associated to keyboard keys
/// @param negativeKey the keyboard key associated to moving in the negative direction in the axis
/// @param positiveKey the keyboard key associated to moving in the positive direction in the axis
SingleAxis(cubos::core::io::Key negativeKey, cubos::core::io::Key positiveKey);
/// Checks if the position in the axis associated with this Single Axis source has been changed since last
/// checked
/// @return true if the position associated with this Single Axis has been changed, otherwise false
bool isTriggered() override;
/// Subscribes this object to callbacks in the Input Manager
/// @see unsubscribeEvents
void subscribeEvents() override;
/// Unsubscribes this object to callbacks in the Input Manager
/// @see subscribeEvents
void unsubscribeEvents() override;
/// Creates the context related to this Single Axis
/// @return context created by this Single Axis
Context createContext() override;
private:
std::variant<cubos::core::io::MouseAxis, std::tuple<cubos::core::io::Key, cubos::core::io::Key>> inputs;
void handleAxis(float value);
void handlePositive();
void handleNegative();
bool wasTriggered;
float value = 0;
};
} // namespace cubos::core::io
#endif // CUBOS_CORE_IO_SINGLE_AXIS_HPP
| 39.017241 | 114 | 0.68449 | [
"object"
] |
563a137ae6baeaaf7cb11571abbc284a0cb8f81e | 2,582 | cpp | C++ | src/io.cpp | FamousCake/flow | 77f134f74996225f679a1b9d796b7328ad6e1867 | [
"MIT"
] | null | null | null | src/io.cpp | FamousCake/flow | 77f134f74996225f679a1b9d796b7328ad6e1867 | [
"MIT"
] | null | null | null | src/io.cpp | FamousCake/flow | 77f134f74996225f679a1b9d796b7328ad6e1867 | [
"MIT"
] | null | null | null | #include "inc/io.h"
using namespace std;
void IO::printArray(int A[], int count, int w, const char msg[])
{
cout << '\n' << msg << '\n';
cout << "Pointer is : " << A << endl;
for (int i = 0; i < count; ++i)
{
cout << setw(w) << A[i];
}
cout << endl;
}
void IO::printResidualNetwork(ResidualNetwork &A, int w, const char msg[])
{
cout << '\n' << msg << '\n';
cout << "Pointer is : " << &A << endl;
for (int i = 0; i < A.getCount(); ++i)
{
cout << endl;
for (int j = 0; j < A.getCount(); ++j)
{
cout << setw(w) << A.getEdge(i, j).weight;
}
}
cout << endl;
}
ResidualNetwork IO::ReadGraph()
{
char t;
int vertexCount, edgeCount;
int source, sink;
vector<vector<ResidualEdge>> E;
while (cin >> t)
{
if (t == 'c')
{
cin.ignore(256, '\n');
}
else if (t == 'p')
{
string s;
cin >> s >> vertexCount >> edgeCount;
E = vector<vector<ResidualEdge>>(vertexCount);
}
else if (t == 'n')
{
int a;
char b;
cin >> a >> b;
if (b == 's')
{
source = a - 1;
}
else if (b == 't')
{
sink = a - 1;
}
}
else if (t == 'a')
{
int a, b, c;
cin >> a >> b >> c;
E[a - 1].push_back(ResidualEdge(a - 1, b - 1, c, E[b - 1].size()));
E[b - 1].push_back(ResidualEdge(b - 1, a - 1, 0, E[a - 1].size() - 1));
}
}
return ResidualNetwork(E, source, sink);
}
void IO::WriteGraph(ResidualNetwork &E)
{
int edgeCount = 0;
for (int i = 0; i < E.getCount(); ++i)
{
for (int j = 0; j < E.getCount(); ++j)
{
if (E.getEdge(i, j).weight)
{
edgeCount++;
}
}
}
cout << "c" << endl;
cout << "c This is a generated graph" << endl;
cout << "c" << endl;
cout << "p max " << E.getCount() << " " << edgeCount << endl;
cout << "n " << E.getSource() + 1 << " s" << endl;
cout << "n " << E.getSink() + 1 << " t" << endl;
for (int i = 0; i < E.getCount(); ++i)
{
for (int j = 0; j < E.getCount(); ++j)
{
if (E.getEdge(i, j).weight)
{
cout << "a " << i + 1 << " " << j + 1 << " " << E.getEdge(i, j).weight << endl;
}
}
}
cout << "c End of file;";
}
| 21.163934 | 95 | 0.384198 | [
"vector"
] |
563c82a382aa84b3b3aae1ff94d386f882759bf1 | 4,324 | cpp | C++ | Dicom/dicom/data/SH.cpp | drleq/CppDicom | e320fad8414fabfb51c5eb80964f8b6def578247 | [
"MIT"
] | null | null | null | Dicom/dicom/data/SH.cpp | drleq/CppDicom | e320fad8414fabfb51c5eb80964f8b6def578247 | [
"MIT"
] | null | null | null | Dicom/dicom/data/SH.cpp | drleq/CppDicom | e320fad8414fabfb51c5eb80964f8b6def578247 | [
"MIT"
] | null | null | null | #include "dicom_pch.h"
#include "dicom/data/SH.h"
#include "dicom/data/detail/combine_strings.h"
#include "dicom/data/detail/DefaultCharacterRepertoire.h"
#include "dicom/data/detail/locate_separators.h"
#include "dicom/data/detail/validate_separator_locations.h"
using namespace std;
namespace dicom::data {
SH::SH()
: SH(encoded_string())
{}
//--------------------------------------------------------------------------------------------------------
SH::SH(const encoded_string& value)
: SH(encoded_string(value))
{}
//--------------------------------------------------------------------------------------------------------
SH::SH(encoded_string&& value)
: VR(VRType::SH),
m_value(forward<encoded_string>(value))
{}
//--------------------------------------------------------------------------------------------------------
SH::SH(const vector<encoded_string>& values)
: VR(VRType::SH)
{
if (!detail::combine_strings(values, &m_value)) {
throw string_invalid_error();
}
}
//--------------------------------------------------------------------------------------------------------
SH::SH(initializer_list<encoded_string> values)
: VR(VRType::SH)
{
if (!detail::combine_strings(values, &m_value)) {
throw string_invalid_error();
}
}
//--------------------------------------------------------------------------------------------------------
SH::SH(const SH& other)
: VR(other),
m_value(other.m_value),
m_parsed_offsets(other.m_parsed_offsets)
{}
//--------------------------------------------------------------------------------------------------------
SH::SH(SH&& other)
: VR(forward<VR>(other)),
m_value(move(other.m_value)),
m_parsed_offsets(move(other.m_parsed_offsets))
{}
//--------------------------------------------------------------------------------------------------------
SH::~SH() = default;
//--------------------------------------------------------------------------------------------------------
SH& SH::operator = (const SH& other) {
VR::operator = (other);
m_value = other.m_value;
m_parsed_offsets = other.m_parsed_offsets;
return *this;
}
//--------------------------------------------------------------------------------------------------------
SH& SH::operator = (SH&& other) {
VR::operator = (forward<VR>(other));
m_value = move(other.m_value);
m_parsed_offsets = move(other.m_parsed_offsets);
return *this;
}
//--------------------------------------------------------------------------------------------------------
ValidityType SH::Validate() const {
if (m_value.Validity() == ValidityType::Invalid) {
return ValidityType::Invalid;
}
// Get the offsets for multiplicity markers
vector<size_t> parsed_offsets;
if (!detail::locate_separators(parsed_offsets, m_value, detail::MultiplicityChar)) {
return ValidityType::Invalid;
}
/*** Essential checks ***/
// Check for invalid characters
auto& parsed = m_value.Parsed();
bool invalid = any_of(
parsed.cbegin(),
parsed.cend(),
[](wchar_t c) { return (c == 0x0A) || (c == 0x0C) || (c == 0x0D); }
);
if (invalid) { return ValidityType::Invalid; }
m_parsed_offsets.swap(parsed_offsets);
/*** Strict checks ***/
// Values are not allowed to exceed 16 characters
if (!detail::validate_separator_locations(parsed, m_parsed_offsets, 16)) {
return ValidityType::Acceptable;
}
return ValidityType::Valid;
}
//--------------------------------------------------------------------------------------------------------
int32_t SH::Compare(const VR* other) const {
auto result = VR::Compare(other);
if (result) { return result; }
auto typed = static_cast<const SH*>(other);
return m_value.Compare(typed->m_value);
}
} | 31.794118 | 111 | 0.404255 | [
"vector"
] |
564403759bd9b0afbac9221a24f72dca348a515b | 29,369 | cpp | C++ | sxaccelerate/src/graph/SxGQuery.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | 1 | 2020-02-29T03:26:32.000Z | 2020-02-29T03:26:32.000Z | sxaccelerate/src/graph/SxGQuery.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | null | null | null | sxaccelerate/src/graph/SxGQuery.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | null | null | null | // ---------------------------------------------------------------------------
//
// The general purpose cross platform C/C++ framework
//
// S x A c c e l e r a t e
//
// Home: https://www.sxlib.de
// License: Apache 2
// Authors: see src/AUTHORS
//
// ---------------------------------------------------------------------------
#include <SxGQuery.h>
SxGQuery::SxGQuery () {}
SxGQuery::SxGQuery (const SxGQuery &in)
{
this->rootExpr = in.rootExpr;
makeGraph ();
}
SxGQuery::SxGQuery (const sx::N &n)
{
SxPtr<SxGQExprBase> e = n;
this->rootExpr = e;
makeGraph ();
}
SxGQuery::SxGQuery (const SxPtr<SxGQExprBase> &r)
{
SX_CHECK (r.getPtr ());
rootExpr = r;
makeGraph ();
}
SxGQuery::SxGQuery (const SxPtr<SxGQExprList> &r)
{
SX_CHECK (r.getPtr ());
rootExpr = r;
makeGraph ();
}
SxGQuery::~SxGQuery () { }
SxGQuery &SxGQuery::operator= (const SxGQuery &in)
{
if (this == &in) return *this;
this->rootExpr = in.rootExpr;
patternGraph = SxGraph<SxGQPattern>();
makeGraph ();
return *this;
}
// operator= allows to assign a SxGQExprBase object to SxGQuery
SxGQuery &SxGQuery::operator= (const SxPtr<SxGQExprBase> &r)
{
SX_CHECK (r.getPtr ());
this->rootExpr = r;
patternGraph = SxGraph<SxGQPattern>();
makeGraph ();
return *this;
}
SxGQuery &SxGQuery::operator= (const SxPtr<SxGQExprList> &r)
{
SX_CHECK (r.getPtr ());
this->rootExpr = r;
patternGraph = SxGraph<SxGQPattern>();
makeGraph ();
return *this;
}
void SxGQuery::makeGraph ()
{
if (rootExpr->isOp ()) {
rootExpr->makeGraph (&patternGraph);
} else {
patternGraph.createNode (rootExpr->getGraphNode ());
}
}
// returns the matched selections of nodes' Idx.
SxGQuery::SelSet SxGQuery::matchAll (const SxPtr<SxGraph<SxGProps> > &g,
const SxGraph<SxGProps>::Iterator &gIt)
{
selections = SxGQuery::SelSet::create ();
SxGQuery::SelSet tmpSels = SxGQuery::SelSet::create ();
bool res = false, finalRes = false;
SxGraph<SxGProps>::ConstIterator tIt;
// list for visited pattern nodes overall
SxGQuery::Selection gVisited = SxGQuery::Selection::create ();
SxGQuery::Selection visited = SxGQuery::Selection::create ();
SxGQuery::Selection fullVisited = SxGQuery::Selection::create ();
auto it = gIt;
// this iterator goes over all nodes
// irrespective of edges. It allows to
// cover all connected components of the
// graph.
auto patternIt = patternGraph.begin (sx::Undefined, (*patternGraph.begin ()));
while (patternIt.isValid ()) {
while (it.isValid ()) {
SX_CHECK (selections.getPtr ());
SX_CHECK (tmpSels.getPtr ());
visited = SxGQuery::Selection::create ();
// it is important to start with fresh iterator
// in order to cover all possible paths to a node
tIt = g->begin (*it);
res = matchAllCurrent (patternGraph.begin (*patternIt), tIt, tmpSels, visited);
if (res == true) {
// at least one match found during this loop
finalRes = true;
// store the full matched set of pattern nodes
fullVisited = visited;
selections->append (std::move(*tmpSels));
}
++it;
}
if (!finalRes) {
return SxGQuery::SelSet::create ();
}
gVisited->append (*fullVisited);
finalRes = false;
it = gIt;
// skip the visited pattern nodes
while (patternIt.isValid () && gVisited->contains (patternIt->getId ()))
++patternIt;
}
return selections;
}
SxGQuery::SelSet SxGQuery::matchAll (const SxPtr<SxGraph<SxGProps> > &g)
{
return matchAll (g, g->begin (sx::Undefined, (*g->begin ())));
}
SxGQuery::Selection SxGQuery::match (const SxPtr<SxGraph<SxGProps> > &g,
const SxGraph<SxGProps>::Iterator &gIt)
{
bool res = false;
SxGQuery::Selection sel = SxGQuery::Selection::create ();
SxGQuery::Selection visited = SxGQuery::Selection::create ();
auto it = gIt;
SxGraph<SxGProps>::ConstIterator tIt;
auto patternIt = patternGraph.begin (sx::Undefined, (*patternGraph.begin ()));
while (patternIt.isValid ()) {
while (it.isValid ()) {
tIt = g->begin (*it);
res = evalCurrent (patternGraph.begin (*patternIt), tIt, sel, visited);
if (res == true) break;
++it;
}
if (!res) {
sel->removeAll ();
break;
}
res = false;
it = gIt;
// skip the visited pattern nodes
while (patternIt.isValid () && visited->contains (patternIt->getId ()))
++patternIt;
}
return sel;
}
SxGQuery::Selection SxGQuery::match (const SxPtr<SxGraph<SxGProps> > &g)
{
return match (g, g->begin (sx::Undefined, (*g->begin ())));
}
bool SxGQuery::matchOneIncomingOnce (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::Selection &sel,
SxGQuery::Selection &visited) const
{
bool finalRes = false;
for (ssize_t i = 0; i < gIt.getSizeIn (); ++i) {
if(evalCurrent (it, gIt.in (i), sel, visited)) {
finalRes = true; // atleast one match found
break;
}
}
return finalRes;
}
bool SxGQuery::matchAllIncomingOnce (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::Selection &sel,
SxGQuery::Selection &visited) const
{
SX_CHECK (it.isValid ());
SX_CHECK (gIt.isValid ());
SxGQuery::Selection resSel = SxGQuery::Selection::create ();
bool res = true, visitable = false;
for (ssize_t i = 0; i < it.getSizeIn (); ++i) {
auto inIt = it.in (i);
if (!visited->contains (inIt->getId ())) {
visitable = true;
res = matchOneIncomingOnce (inIt, gIt, resSel, visited);
if (!res) break;
}
}
if (res && visitable) {
resSel->append (*sel);
sel = resSel;
}
return res;
}
// Single match function that evaluates current
// pattern node and recursively checks all incoming
// and outgoing edges too.
bool SxGQuery::evalCurrent (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::Selection &sel,
SxGQuery::Selection &visited) const
{
SX_CHECK (it.isValid ());
SX_CHECK (gIt.isValid ());
// if this node has already been visited
// still evaluate it so that calling function
// can know success/failure. But don't append
// it to the result.
if (visited->contains (it->getId ())) {
SxGQuery::Selection tmpSel = SxGQuery::Selection::create ();
return it->eval (gIt, tmpSel);
}
bool res = false;
ssize_t siz = sel->getSize ();
res = it->eval (gIt, sel);
if (res) {
visited->append (it->getId ());
res = matchAllIncomingOnce (it, gIt, sel, visited);
}
if (res && it.getSizeOut () > 0) {
switch(it->getRelType ()) {
case SxGQPattern::RelationType::OrderedDirect:
res = matchOnceChildrenOD (it, gIt, sel, visited);
break;
case SxGQPattern::RelationType::OrderedIndirect:
res = matchOnceChildrenOI (it, gIt, sel, visited);
break;
case SxGQPattern::RelationType::UnorderedDirect:
res = matchOnceChildrenUD (it, gIt, sel, visited);
break;
case SxGQPattern::RelationType::UnorderedIndirect:
res = matchOnceChildrenUI (it, gIt, sel, visited);
break;
}
}
if (!res) sel->resize (siz);
return res;
}
// match all in data graph for the given incoming node in pattern graph
bool SxGQuery::matchAllOneIncoming (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::SelSet &sels,
SxGQuery::Selection &visited) const
{
SxGQuery::SelSet resSet = SxGQuery::SelSet::create ();
bool finalRes = false;
SxGQuery::Selection tmpVisited;
for (ssize_t i = 0; i < gIt.getSizeIn (); ++i) {
SxGQuery::SelSet tmpSels = SxGQuery::SelSet::create ();
tmpVisited = SxGQuery::Selection::create (*visited);
if(matchAllCurrent (it, gIt.in (i), tmpSels, tmpVisited)) {
finalRes = true; // atleast one match found
resSet->append (std::move(*crossSelections (tmpSels, sels)) );
}
}
visited = tmpVisited; // update visited list
if (finalRes) sels = resSet;
return finalRes;
}
bool SxGQuery::matchAllIncoming (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::SelSet &sels,
SxGQuery::Selection &visited) const
{
SX_CHECK (it.isValid ());
SX_CHECK (gIt.isValid ());
SxGQuery::SelSet resSet = SxGQuery::SelSet::create ();
resSet= crossSelections (resSet, sels);
bool res = true, visitable = false;
for (ssize_t i = 0; i < it.getSizeIn (); ++i) {
auto inIt = it.in (i);
if (!visited->contains (inIt->getId ())) {
visitable = true;
res = matchAllOneIncoming (inIt, gIt, resSet, visited);
if (!res) break;
}
}
if (visitable && res) sels = resSet;
return res;
}
// match all function that evaluates current
// pattern node and recursively checks all incoming
// and outgoing edges too.
bool SxGQuery::matchAllCurrent (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::SelSet &sels,
SxGQuery::Selection &visited) const
{
SX_CHECK (it.isValid ());
SX_CHECK (gIt.isValid ());
// if this node has already been visited
// still evaluate it so that calling function
// can know success/failure. But don't append
// it to the result.
if (visited->contains (it->getId ())) {
SxGQuery::SelSet tmpSels = SxGQuery::SelSet::create ();
return it->matchAll(gIt, tmpSels);
}
bool res = false;
ssize_t setSize = sels->getSize ();
ssize_t siz = (setSize == 0)? 0 : sels->first()->getSize ();
res = it->matchAll (gIt, sels);
if (res) {
visited->append (it->getId ());
res = matchAllIncoming (it, gIt, sels, visited);
}
if (res && it.getSizeOut () > 0) {
switch(it->getRelType ()) {
case SxGQPattern::RelationType::OrderedDirect:
res = matchAllChildrenOD (it, gIt, sels, visited);
break;
case SxGQPattern::RelationType::OrderedIndirect:
res = matchAllChildrenOI (it, gIt, sels, visited);
break;
case SxGQPattern::RelationType::UnorderedDirect:
res = matchAllChildrenUD (it, gIt, sels, visited);
break;
case SxGQPattern::RelationType::UnorderedIndirect:
res = matchAllChildrenUI (it, gIt, sels, visited);
break;
}
}
if (!res) resizeSelections (sels, setSize, siz);
return res;
}
void SxGQuery::resizeSelections (SxGQuery::SelSet &sels,
ssize_t setSize,
ssize_t selSize) const
{
sels->resize (setSize);
for (auto it = sels->begin ();it != sels->end (); ++it) {
(*it)->resize (selSize);
}
}
SxGQuery::SelSet SxGQuery::crossSelections (SxGQuery::SelSet &sels1,
SxGQuery::SelSet &sels2) const
{
SX_CHECK (sels1.getPtr ());
SX_CHECK (sels2.getPtr ());
SxGQuery::SelSet res = SxGQuery::SelSet::create ();
if (sels1->getSize () == 0) {
for (auto it2 = sels2->begin ();it2 != sels2->end (); ++it2) {
SxGQuery::Selection ptr = SxGQuery::Selection::create ();
ptr->append ((*(*it2)));
res->append (ptr);
}
} else if (sels2->getSize () == 0) {
for (auto it1 = sels1->begin ();it1 != sels1->end (); ++it1) {
SxGQuery::Selection ptr = SxGQuery::Selection::create ();
ptr->append ((*(*it1)));
res->append (ptr);
}
} else {
for (auto it1 = sels1->begin ();it1 != sels1->end (); ++it1) {
for (auto it2 = sels2->begin ();it2 != sels2->end (); ++it2) {
SxGQuery::Selection ptr = SxGQuery::Selection::create ();
ptr->append ((*(*it1)));
ptr->append ((*(*it2)));
res->append (ptr);
}
}
}
SX_CHECK (res.getPtr ());
return res;
}
// match all ordered-direct starting from given child node in data graph
bool SxGQuery::matchAllOD (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::SelSet &sels, ssize_t childIdx,
SxGQuery::Selection &visited) const
{
SX_CHECK (it.getSizeOut () > 0, it.getSizeOut ());
bool res = true;
ssize_t setSize = sels->getSize ();
ssize_t siz = (setSize == 0)? 0 : sels->first()->getSize ();
ssize_t outSize = gIt.getSizeOut ();
auto currIt = gIt.out (childIdx);
if ((outSize-childIdx) < it.getSizeOut ()) {
return false;
}
for (ssize_t j = 0; j < it.getSizeOut (); ++j) {
res = matchAllCurrent (it.out(j), gIt.out (childIdx), sels, visited);
if (!res) break;
SX_CHECK (childIdx < outSize, childIdx, outSize);
++childIdx;
}
if (!res) resizeSelections (sels, setSize, siz);
return res;
}
// match all child nodes of pattern graph ordered-direct (default)
bool SxGQuery::matchAllChildrenOD (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::SelSet &sels,
SxGQuery::Selection &visited) const
{
SxGQuery::SelSet resSet = SxGQuery::SelSet::create ();
bool finalRes = false;
ssize_t outSize = gIt.getSizeOut ();
SxGQuery::Selection tmpVisited = SxGQuery::Selection::create (*visited);
for (ssize_t c = 0; c < outSize; ++c) {
SxGQuery::SelSet childSels = SxGQuery::SelSet::create ();
tmpVisited = SxGQuery::Selection::create (*visited);
if (matchAllOD (it, gIt, childSels, c, tmpVisited)) {
finalRes = true;
resSet->append (std::move(*crossSelections(sels, childSels)));
}
}
// update the visited list once all matches
// for a particular node have been found.
visited = tmpVisited;
if (finalRes) sels = resSet;
return finalRes;
}
// match all child nodes of pattern graph unordered-indirect
bool SxGQuery::matchAllChildrenUI (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &pIt,
SxGQuery::SelSet &sels,
SxGQuery::Selection &visited) const
{
SxGQuery::Selection prevMatches = SxGQuery::Selection::create ();
SxPtr<SxList<SxGQuery::SelSet> > prevSels = SxPtr<SxList<SxGQuery::SelSet> >::create ();
ssize_t outSize = pIt.getSizeOut ();
SxGQuery::Selection tmpVisited = SxGQuery::Selection::create (*visited);
bool finalRes = false;
bool res = false;
SxGQuery::Selection currMatches = SxGQuery::Selection::create ();
SxPtr<SxList<SxGQuery::SelSet> > currSels = SxPtr<SxList<SxGQuery::SelSet> >::create ();
for (ssize_t exprIdx = 0; exprIdx < it.getSizeOut (); ++exprIdx) {
auto chIt = it.out (exprIdx);
finalRes = false;
res = false;
for (ssize_t cIdx = 0; cIdx < outSize; ++cIdx) {
SxGQuery::SelSet resSet = SxGQuery::SelSet::create ();
tmpVisited = SxGQuery::Selection::create (*visited);
res = matchAllCurrent (chIt, pIt.out (cIdx), resSet, tmpVisited);
if (res == true) {
// atleast one match found for curr expr
finalRes = true;
currMatches->append (cIdx);
SxGQuery::SelSet tmpSels = SxGQuery::SelSet::create ();
if (prevMatches->getSize () > 0) {
auto pMIt = prevMatches->begin ();
auto pSIt = prevSels->begin ();
for (;pMIt != prevMatches->end (); (++pMIt,++pSIt)) {
tmpSels->append (std::move( *(crossSelections (*pSIt, resSet)) ) );
}
} else {
// prevMatches is empty i-e. we are in first expression
*tmpSels = *resSet;
}
SX_CHECK (tmpSels->getSize () > 0, tmpSels->getSize ());
currSels->append (tmpSels);
}
}
visited = tmpVisited;
// if no match found then return
if (finalRes == false) {
return false;
}
*prevMatches = std::move(*currMatches);
*prevSels = std::move(*currSels);
}
SxGQuery::SelSet rSet = SxGQuery::SelSet::create ();
for (auto sIt = prevSels->begin (); sIt != prevSels->end (); ++sIt) {
rSet->append ( std::move( *(crossSelections (sels, *sIt)) ) );
}
sels = rSet;
return true;
}
// match all child nodes of pattern graph ordered-indirect
bool SxGQuery::matchAllChildrenOI (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::SelSet &sels,
SxGQuery::Selection &visited) const
{
SxGQuery::Selection prevMatches = SxGQuery::Selection::create ();
SxPtr<SxList<SxGQuery::SelSet> > prevSels = SxPtr<SxList<SxGQuery::SelSet> >::create ();
ssize_t cIdx = 0;
ssize_t outSize = gIt.getSizeOut ();
ssize_t exprsLeft = it.getSizeOut ();
SxGQuery::Selection tmpVisited;
bool finalRes = false;
bool res = false;
SxGQuery::Selection currMatches = SxGQuery::Selection::create ();
SxPtr<SxList<SxGQuery::SelSet> > currSels = SxPtr<SxList<SxGQuery::SelSet> >::create ();
for (ssize_t exprIdx = 0; exprIdx < it.getSizeOut (); ++exprIdx) {
auto chIt = it.out (exprIdx);
finalRes = false;
res = false;
for (; cIdx < outSize; ++cIdx) {
// if number of siblings left to process
// are less than the number of expresssions
// left then stop
if ((outSize-cIdx) < exprsLeft)
break;
SxGQuery::SelSet resSet = SxGQuery::SelSet::create ();
tmpVisited = SxGQuery::Selection::create (*visited);
res = matchAllCurrent (chIt, gIt.out (cIdx), resSet, tmpVisited);
if (res == true) {
// atleast one match found for curr expr
finalRes = true;
currMatches->append (cIdx);
SxGQuery::SelSet tmpSels = SxGQuery::SelSet::create ();
if (prevMatches->getSize () > 0) {
auto pMIt = prevMatches->begin ();
auto pSIt = prevSels->begin ();
for (;pMIt != prevMatches->end (); (++pMIt,++pSIt)) {
if (*pMIt < cIdx) {
tmpSels->append (std::move( *(crossSelections (*pSIt, resSet)) ) );
} else {
// childIdx's in prevMatches are in sorted order
// so once (*pMIt >= cIdx), the rest of them will
// also be greater than cIdx. Due to "Ordered"
// requirement those won't match. so break loop.
break;
}
}
} else {
// prevMatches is empty i-e. we are in first expression
*tmpSels = *resSet;
}
SX_CHECK (tmpSels->getSize () > 0, tmpSels->getSize ());
currSels->append (tmpSels);
}
}
visited = tmpVisited;
// if no match found then return
if (finalRes == false) return false;
--exprsLeft;
*prevMatches = std::move (*currMatches);
*prevSels = std::move (*currSels);
// start next loop from firstChildIdx+1
// that matched in prev iteration.
SX_CHECK (prevMatches->getSize() > 0, prevMatches->getSize ());
cIdx = prevMatches->first ()+1;
}
SxGQuery::SelSet rSet = SxGQuery::SelSet::create ();
for (auto sIt = prevSels->begin (); sIt != prevSels->end (); ++sIt) {
rSet->append ( std::move( *(crossSelections (sels, *sIt)) ) );
}
sels = rSet;
return true;
}
// match all child nodes of pattern graph unordered-direct
bool SxGQuery::matchAllChildrenUD (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::SelSet &sels,
SxGQuery::Selection &visited) const
{
SX_CHECK (it.getSizeOut () > 0, it.getSizeOut ());
SxGQuery::Selection prevMatches = SxGQuery::Selection::create ();
SxGQuery::Selection tmpVisited = SxGQuery::Selection::create (*visited);
SxPtr<SxList<SxGQuery::SelSet> > prevSels =
SxPtr<SxList<SxGQuery::SelSet> >::create ();
ssize_t outSize = gIt.getSizeOut ();
ssize_t cIdx = 0;
ssize_t exprIdx = 0;
bool finalRes = false;
bool res = false;
bool res1 = false, res2 = false;
auto exprIt = it.out (exprIdx);
// go over the childList to find all matches for first expr
for (; cIdx < outSize; ++cIdx) {
SxGQuery::SelSet resSet = SxGQuery::SelSet::create ();
tmpVisited = SxGQuery::Selection::create (*visited);
res = matchAllCurrent (exprIt, gIt.out (cIdx), resSet, tmpVisited);
if (res == true) {
// at least one match found for curr expr
finalRes = true;
prevMatches->append (cIdx);
prevSels->append (resSet);
}
}
visited = tmpVisited;
if (!finalRes) return false;
exprIdx++;
for (; exprIdx < it.getSizeOut (); ++exprIdx) {
exprIt = it.out (exprIdx);
SxGQuery::Selection currMatches = SxGQuery::Selection::create ();
SxPtr<SxList<SxGQuery::SelSet> > currSels =
SxPtr<SxList<SxGQuery::SelSet> >::create ();
finalRes = false;
res = false;
auto pMIt = prevMatches->begin ();
auto pSIt = prevSels->begin ();
for (; pMIt != prevMatches->end (); ++pMIt, ++pSIt) {
cIdx = *pMIt;
res1 = false; res2 = false;
if ((cIdx-1) >= 0) {
auto prevIt = gIt.out ((cIdx-1));
SxGQuery::SelSet resSet = SxGQuery::SelSet::create ();
tmpVisited = SxGQuery::Selection::create (*visited);
res1 = matchAllCurrent (exprIt, prevIt, resSet, tmpVisited);
if (res1) {
currMatches->append ((cIdx-1));
currSels->append ( crossSelections (*pSIt, resSet) );
}
}
if ((cIdx+1) < outSize) {
auto nextIt = gIt.out ((cIdx+1));
SxGQuery::SelSet resSet = SxGQuery::SelSet::create ();
tmpVisited = SxGQuery::Selection::create (*visited);
res2 = matchAllCurrent (exprIt, nextIt, resSet, tmpVisited);
if (res2) {
currMatches->append ((cIdx+1));
currSels->append ( crossSelections (*pSIt, resSet) );
}
}
res = res1 || res2;
// if any one of the prevMatched child results in
// successful match for next sibling/expr, it is enough
// to continue with matching next exprs.
if (res) finalRes = true;
}
visited = tmpVisited;
// if no match found then return
if (finalRes == false) return false;
prevMatches = currMatches;
prevSels = currSels;
}
SxGQuery::SelSet rSet = SxGQuery::SelSet::create ();
for (auto sIt = prevSels->begin (); sIt != prevSels->end (); ++sIt) {
rSet->append ( std::move( *(crossSelections (sels, *sIt)) ) );
}
sels = rSet;
return true;
}
// recursively find one match starting at given child node unordered-direct
bool SxGQuery::matchOnceUDR (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
ssize_t childIdx, ssize_t exprChildIdx,
SxGQuery::Selection &sel,
SxGQuery::Selection &visited) const
{
bool res;
ssize_t siz = sel->getSize ();
res = evalCurrent (it.out (exprChildIdx), gIt.out (childIdx), sel, visited);
if (res == true) {
++exprChildIdx;
if (exprChildIdx < it.getSizeOut ()) {
bool res1 = false, res2 = false;
if ((childIdx+1) < gIt.getSizeOut ()) {
res1 = matchOnceUDR (it, gIt, (childIdx+1), exprChildIdx, sel, visited);
if (res1) return true;
else sel->resize (siz);
}
if ((childIdx-1) >= 0) {
res2 = matchOnceUDR (it, gIt, (childIdx-1), exprChildIdx, sel, visited);
if (res2) return true;
else sel->resize (siz);
}
res = res1 || res2;
// incase could not match either of next or prev neighbor child
if (!res) sel->resize (siz);
} else {
// path completed
return true;
}
}
return res;
}
// go through all child nodes and find one match unordered-direct
bool SxGQuery::matchOnceChildrenUD (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::Selection &sel,
SxGQuery::Selection &visited) const
{
for (ssize_t i=0; i < gIt.getSizeOut (); ++i) {
if (matchOnceUDR (it, gIt, i, 0, sel, visited))
return true;
}
return false;
}
// go through all child nodes and find one match unordered-indirect
bool SxGQuery::matchOnceChildrenUI (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::Selection &sel,
SxGQuery::Selection &visited) const
{
ssize_t siz = sel->getSize ();
ssize_t outSize = gIt.getSizeOut ();
ssize_t childIdx = 0;
ssize_t exprChildIdx = 0;
bool finalRes = false;
auto chIt = it.out (exprChildIdx);
for (; childIdx < outSize; ++childIdx) {
if (evalCurrent (chIt, gIt.out (childIdx), sel, visited)) {
// go to next expr
exprChildIdx++;
if (exprChildIdx >= it.getSizeOut ()) {
finalRes = true;
break;
}
chIt = it.out (exprChildIdx);
// loop will increment it to 0
childIdx = -1;
}
}
if (!finalRes) sel->resize (siz);
return finalRes;
}
// find one match for ordered and direct
bool SxGQuery::matchOnceOD (const SxGraph<SxGQPattern>::ConstIterator &pIt,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::Selection &sel,
ssize_t childIdx,
SxGQuery::Selection &visited) const
{
ssize_t siz = sel->getSize ();
if ((gIt.getSizeOut ()-childIdx) < pIt.getSizeOut ()) {
return false;
}
for (ssize_t j=0; j < pIt.getSizeOut (); ++j) {
auto chIt = pIt.out (j);
if (!evalCurrent (chIt, gIt.out (childIdx), sel, visited)) {
sel->resize (siz);
return false;
}
++childIdx;
}
return true;
}
// match once ordered and direct
bool SxGQuery::matchOnceChildrenOD (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::Selection &sel,
SxGQuery::Selection &visited) const
{
for (ssize_t i=0; i < gIt.getSizeOut (); ++i) {
if (matchOnceOD (it, gIt, sel, i, visited)) return true;
}
return false;
}
// find one match ordered-indirect
bool SxGQuery::matchOnceChildrenOI (const SxGraph<SxGQPattern>::ConstIterator &it,
const SxGraph<SxGProps>::ConstIterator &gIt,
SxGQuery::Selection &sel,
SxGQuery::Selection &visited) const
{
ssize_t siz = sel->getSize ();
ssize_t exprsLeft = it.getSizeOut ();
ssize_t outSize = gIt.getSizeOut ();
bool finalRes = false;
ssize_t i = 0;
auto chIt = it.out (i);
for (ssize_t j=0; j < gIt.getSizeOut (); ++j) {
if ((outSize-j) < exprsLeft) break;
if (evalCurrent (chIt, gIt.out (j), sel, visited)) {
++i;
if (i >= it.getSizeOut ()) {
finalRes = true;
break;
}
chIt = it.out (i);
exprsLeft--;
}
}
if (!finalRes) sel->resize (siz);
return finalRes;
}
| 32.777902 | 91 | 0.55991 | [
"object"
] |
871d2cba4113801c5ac0ca0b6ca3f2c1dc859e5f | 16,978 | cc | C++ | src/info/info_server.cc | ngvozdiev/ctr-base | f730ea9b3d9be6dd8a1f8dbc96339bb1e5efcb9d | [
"MIT"
] | 1 | 2020-11-11T15:26:46.000Z | 2020-11-11T15:26:46.000Z | src/info/info_server.cc | ngvozdiev/ctr-base | f730ea9b3d9be6dd8a1f8dbc96339bb1e5efcb9d | [
"MIT"
] | null | null | null | src/info/info_server.cc | ngvozdiev/ctr-base | f730ea9b3d9be6dd8a1f8dbc96339bb1e5efcb9d | [
"MIT"
] | null | null | null | #include "info_server.h"
#include <gflags/gflags.h>
#include <google/protobuf/repeated_field.h>
#include <ncode/common.h>
#include <ncode/logging.h>
#include <ncode/lp/demand_matrix.h>
#include <ncode/net/net_common.h>
#include <ncode/substitute.h>
#include <ncode/viz/server.h>
#include <cstdint>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <type_traits>
#include <utility>
#include <vector>
#include "../common.h"
#include "tm_gen.h"
#define SET_SIMPLE_FIELD(name) \
if (mask.name()) { \
out.set_##name(original.name()); \
}
#define SET_COMPLEX_FIELD(name) \
if (mask.name()) { \
*(out.mutable_##name()) = original.name(); \
}
#define SET_DISCRETE_DIST(name) \
if (mask.name##_multiplier() != 0.0) { \
*(out.mutable_##name()) = \
ScaleDiscreteDistribution(original.name(), mask.name##_multiplier()); \
}
#define EVALUATE_NUM_FIELD(name) \
if (mask.name()) { \
if (constraint.lower_limit_open() && \
info.name() < constraint.lower_limit()) { \
return false; \
} \
\
if (info.name() <= constraint.lower_limit()) { \
return false; \
} \
\
if (constraint.upper_limit_open() && \
info.name() > constraint.upper_limit()) { \
return false; \
} \
\
if (info.name() >= constraint.upper_limit()) { \
return false; \
} \
}
DEFINE_uint64(info_server_port, 8080, "The port to run the server on");
DEFINE_uint64(info_server_threads, 10,
"Number of threads to serve requests on");
namespace ctr {
static info::DiscreteDistribution ScaleDiscreteDistribution(
const info::DiscreteDistribution& original, double multiplier) {
CHECK(original.value_multiplier() == 1.0);
std::map<uint64_t, uint64_t> new_value_counts;
for (const auto& value_and_count : original.values_and_counts()) {
uint64_t value = value_and_count.value();
uint64_t count = value_and_count.count();
uint64_t new_value = static_cast<uint64_t>(value * multiplier);
new_value_counts[new_value] += count;
}
info::DiscreteDistribution out;
out.set_value_multiplier(multiplier);
for (const auto& new_value_and_count : new_value_counts) {
info::ValueAndCount* value_and_count = out.add_values_and_counts();
value_and_count->set_value(new_value_and_count.first);
value_and_count->set_count(new_value_and_count.second);
}
return out;
}
static info::TopologyInfo ApplyTopologyMask(
const info::TopologyInfo& original, const info::TopologyInfoMask& mask) {
info::TopologyInfo out;
out.set_topology_id(original.topology_id());
SET_SIMPLE_FIELD(node_count);
SET_SIMPLE_FIELD(link_count);
SET_SIMPLE_FIELD(unidirectional_link_count);
SET_SIMPLE_FIELD(multiple_link_count);
SET_SIMPLE_FIELD(diameter_hops);
SET_SIMPLE_FIELD(diameter_micros);
SET_SIMPLE_FIELD(llpd);
SET_COMPLEX_FIELD(node_in_degrees);
SET_COMPLEX_FIELD(node_out_degrees);
SET_COMPLEX_FIELD(link_capacities);
SET_COMPLEX_FIELD(link_delays);
SET_COMPLEX_FIELD(links);
SET_COMPLEX_FIELD(node_names);
SET_SIMPLE_FIELD(name);
SET_SIMPLE_FIELD(date);
SET_SIMPLE_FIELD(description);
SET_DISCRETE_DIST(shortest_path_delays);
SET_DISCRETE_DIST(shortest_path_hop_counts);
return out;
}
static bool ConstraintMatches(const info::TopologyInfo& info,
const info::FieldConstraint& constraint) {
if (constraint.topology_id() &&
constraint.topology_id() != info.topology_id()) {
return false;
}
if (constraint.has_topology_mask()) {
const info::TopologyInfoMask& mask = constraint.topology_mask();
EVALUATE_NUM_FIELD(node_count);
EVALUATE_NUM_FIELD(link_count);
EVALUATE_NUM_FIELD(unidirectional_link_count);
EVALUATE_NUM_FIELD(multiple_link_count);
EVALUATE_NUM_FIELD(diameter_hops);
EVALUATE_NUM_FIELD(diameter_micros);
EVALUATE_NUM_FIELD(llpd);
}
return true;
}
static info::Demand ApplyDemandMask(const info::Demand& original,
const info::DemandMask& mask) {
info::Demand out;
SET_SIMPLE_FIELD(ingress_index);
SET_SIMPLE_FIELD(egress_index);
SET_SIMPLE_FIELD(rate_bps);
SET_SIMPLE_FIELD(flow_count);
SET_SIMPLE_FIELD(shortest_path_delay_micros);
return out;
}
static info::TrafficMatrixInfo ApplyTrafficInfoMask(
const info::TrafficMatrixInfo& original,
const info::TrafficMatrixInfoMask& mask) {
info::TrafficMatrixInfo out;
out.set_topology_id(original.topology_id());
out.set_traffic_matrix_id(original.traffic_matrix_id());
SET_SIMPLE_FIELD(demand_count);
SET_SIMPLE_FIELD(demand_fraction);
SET_SIMPLE_FIELD(total_demand_bps);
SET_SIMPLE_FIELD(locality);
SET_SIMPLE_FIELD(max_commodity_scale_factor);
SET_SIMPLE_FIELD(is_trivial);
SET_COMPLEX_FIELD(demands_out_degree);
SET_COMPLEX_FIELD(demands_in_degree);
SET_DISCRETE_DIST(demand_rates);
SET_DISCRETE_DIST(demand_flow_counts);
if (mask.demand_mask().ByteSize() != 0) {
for (const auto& demand : original.demands()) {
*(out.add_demands()) = ApplyDemandMask(demand, mask.demand_mask());
}
}
return out;
}
static bool ConstraintMatches(const info::TrafficMatrixInfo& info,
const info::FieldConstraint& constraint) {
if (constraint.traffic_matrix_id() &&
constraint.traffic_matrix_id() != info.traffic_matrix_id()) {
return false;
}
if (constraint.has_traffic_matrix_mask()) {
const info::TrafficMatrixInfoMask& mask = constraint.traffic_matrix_mask();
EVALUATE_NUM_FIELD(demand_count);
EVALUATE_NUM_FIELD(demand_fraction);
EVALUATE_NUM_FIELD(total_demand_bps);
EVALUATE_NUM_FIELD(locality);
EVALUATE_NUM_FIELD(max_commodity_scale_factor);
}
return true;
}
static info::RoutingInfo ApplyRoutingInfoMask(
const info::RoutingInfo& original, const info::RoutingInfoMask& mask) {
info::RoutingInfo out;
out.set_routing_id(original.routing_id());
out.set_traffic_matrix_id(original.traffic_matrix_id());
out.set_routing_system(original.routing_system());
out.set_topology_id(original.topology_id());
SET_SIMPLE_FIELD(congested_flows_fraction);
SET_SIMPLE_FIELD(congested_demands_fraction);
SET_SIMPLE_FIELD(total_latency_stretch);
SET_COMPLEX_FIELD(link_utilizations);
SET_COMPLEX_FIELD(latency_stretch);
SET_COMPLEX_FIELD(latency_stretch_uncongested);
SET_DISCRETE_DIST(flow_delays);
SET_DISCRETE_DIST(flow_delays_uncongested);
return out;
}
static bool ConstraintMatches(const info::RoutingInfo& info,
const info::FieldConstraint& constraint) {
if (constraint.routing_id() && constraint.routing_id() != info.routing_id()) {
return false;
}
if (!constraint.routing_system().empty() &&
constraint.routing_system() != info.routing_system()) {
return false;
}
if (constraint.has_routing_mask()) {
const info::RoutingInfoMask& mask = constraint.routing_mask();
EVALUATE_NUM_FIELD(congested_flows_fraction);
EVALUATE_NUM_FIELD(congested_demands_fraction);
EVALUATE_NUM_FIELD(total_latency_stretch);
}
return true;
}
template <typename T>
static bool ConstraintMatchesExpression(
const T& element,
const info::ConstraintOrExpression& constraint_or_expression) {
if (constraint_or_expression.has_constraint()) {
return ConstraintMatches(element, constraint_or_expression.constraint());
}
if (constraint_or_expression.has_expression()) {
const info::ConstraintExpression& expression =
constraint_or_expression.expression();
switch (expression.type()) {
case info::ConstraintExpression::NOT:
CHECK(expression.has_op_one());
return !ConstraintMatchesExpression(element, expression.op_one());
case info::ConstraintExpression::AND:
CHECK(expression.has_op_one());
CHECK(expression.has_op_two());
return ConstraintMatchesExpression(element, expression.op_one()) &&
ConstraintMatchesExpression(element, expression.op_two());
case info::ConstraintExpression::OR:
CHECK(expression.has_op_one());
CHECK(expression.has_op_two());
return ConstraintMatchesExpression(element, expression.op_one()) ||
ConstraintMatchesExpression(element, expression.op_two());
default:
LOG(ERROR) << "Invalid expression type " << expression.type();
return false;
}
}
return true;
}
template <typename T>
static void Filter(std::vector<T>* values, std::function<bool(T)> filter) {
std::vector<T> out;
for (const auto& v : *values) {
if (filter(v)) {
out.emplace_back(v);
}
}
*values = out;
}
template <typename T>
static void Filter(std::set<T>* values, std::function<bool(T)> filter) {
std::set<T> out;
for (const auto& v : *values) {
if (filter(v)) {
out.insert(v);
}
}
*values = out;
}
InfoServer::InfoServer(std::unique_ptr<InfoStorage> info_storage)
: nc::ProtobufServer<ctr::info::Request, ctr::info::Response>(
nc::viz::TCPServerConfig(FLAGS_info_server_port, 1 << 10),
FLAGS_info_server_threads),
info_storage_(std::move(info_storage)) {}
std::unique_ptr<ctr::info::Response> InfoServer::HandleSelect(
const info::SelectInfoRequest& request) const {
std::vector<const info::TopologyInfo*> selected_topologies;
std::vector<const info::TrafficMatrixInfo*> selected_traffic_matrices;
std::vector<const info::RoutingInfo*> selected_routings;
bool return_topologies = false;
bool return_tms = false;
bool return_routing = false;
if (request.topology_mask().SerializeAsString() !=
info::TopologyInfoMask::default_instance().SerializeAsString()) {
return_topologies = true;
}
if (request.traffic_matrix_mask().SerializeAsString() !=
info::TrafficMatrixInfoMask::default_instance().SerializeAsString()) {
return_topologies = true;
return_tms = true;
}
if (request.routing_mask().SerializeAsString() !=
info::RoutingInfoMask::default_instance().SerializeAsString()) {
return_topologies = true;
return_tms = true;
return_routing = true;
}
for (const info::TopologyInfo* topology_info :
info_storage_->GetAllTopologyInfos()) {
if (return_topologies &&
!ConstraintMatchesExpression(*topology_info, request.constraints())) {
continue;
}
if (!return_tms) {
selected_topologies.emplace_back(topology_info);
continue;
}
bool tm_added = false;
for (const info::TrafficMatrixInfo* tm_info :
info_storage_->GetAllTrafficMatrixInfos(
topology_info->topology_id())) {
if (!ConstraintMatchesExpression(*tm_info, request.constraints())) {
continue;
}
if (!return_routing) {
selected_traffic_matrices.emplace_back(tm_info);
tm_added = true;
continue;
}
bool routing_added = false;
for (const info::RoutingInfo* routing_info :
info_storage_->GetAllRoutingInfos(tm_info->traffic_matrix_id())) {
if (!ConstraintMatchesExpression(*routing_info,
request.constraints())) {
continue;
}
selected_routings.emplace_back(routing_info);
routing_added = true;
}
if (routing_added) {
selected_traffic_matrices.emplace_back(tm_info);
tm_added = true;
}
}
if (tm_added) {
selected_topologies.emplace_back(topology_info);
}
}
auto out = nc::make_unique<ctr::info::Response>();
info::SelectInfoResponse* select_response =
out->mutable_select_info_response();
for (const info::TopologyInfo* topology_info : selected_topologies) {
*(select_response->add_topology_info()) =
ApplyTopologyMask(*topology_info, request.topology_mask());
}
for (const info::TrafficMatrixInfo* traffic_matrix_info :
selected_traffic_matrices) {
*(select_response->add_traffic_matrix_info()) = ApplyTrafficInfoMask(
*traffic_matrix_info, request.traffic_matrix_mask());
}
for (const info::RoutingInfo* routing_info : selected_routings) {
*(select_response->add_routing_info()) =
ApplyRoutingInfoMask(*routing_info, request.routing_mask());
}
return out;
}
std::unique_ptr<ctr::info::Response> InfoServer::HandleRequest(
const ctr::info::Request& request) {
LOG(INFO) << "R " << request.DebugString();
if (request.has_select_info_request()) {
return HandleSelect(request.select_info_request());
}
if (request.has_traffic_matrix_generate_request()) {
return HandleTMGenRequest(request.traffic_matrix_generate_request());
}
LOG(INFO) << "Empty request";
return nc::make_unique<ctr::info::Response>();
}
static std::unique_ptr<ctr::info::Response> GetTMGenResponseWithError(
const std::string& error) {
auto response = nc::make_unique<ctr::info::Response>();
response->mutable_generate_traffic_matrix_response()->set_error(error);
return response;
}
std::unique_ptr<ctr::info::Response> InfoServer::HandleTMGenRequest(
const info::TrafficMatrixGenerateRequest& request) const {
if (request.flow_count_distribution_case() ==
info::TrafficMatrixGenerateRequest::FLOW_COUNT_DISTRIBUTION_NOT_SET) {
return GetTMGenResponseWithError(
"Need one of constant_flow_count or demand_based_total_flow_count");
}
uint64_t topology_id = request.topology_id();
const info::TopologyInfo* topology_info =
info_storage_->GetTopologyInfoOrNull(topology_id);
if (topology_info == nullptr) {
return GetTMGenResponseWithError(
nc::Substitute("Unable to find topology with ID $0", topology_id));
}
std::unique_ptr<nc::net::GraphStorage> graph = InfoToGraph(*topology_info);
std::mt19937 gen(request.seed());
auto demand_matrix =
GenerateRoughan(*graph, nc::net::Bandwidth::FromGBitsPerSecond(1), &gen);
demand_matrix = LocalizeDemandMatrix(*demand_matrix, request.locality());
demand_matrix = BalanceReverseDemands(*demand_matrix, 0.1);
double csf = demand_matrix->MaxCommodityScaleFactor({}, 1.0);
CHECK(csf != 0);
CHECK(csf == csf);
demand_matrix = demand_matrix->Scale(csf);
double load = 1.0 / request.max_commodity_scale_factor();
demand_matrix = demand_matrix->Scale(load);
std::unique_ptr<ctr::TrafficMatrix> tm;
switch (request.flow_count_distribution_case()) {
case info::TrafficMatrixGenerateRequest::kConstantFlowCount: {
tm = TrafficMatrix::ConstantFromDemandMatrix(
*demand_matrix, request.constant_flow_count());
break;
}
case info::TrafficMatrixGenerateRequest::kDemandBasedTotalFlowCount: {
tm = TrafficMatrix::DistributeFromDemandMatrix(
*demand_matrix, request.demand_based_total_flow_count());
break;
}
case info::TrafficMatrixGenerateRequest::FLOW_COUNT_DISTRIBUTION_NOT_SET: {
LOG(FATAL) << "Should not happen";
}
}
uint64_t traffic_matrix_id =
info_storage_->AddTrafficMatrix(topology_id, *tm);
auto response = nc::make_unique<ctr::info::Response>();
response->mutable_generate_traffic_matrix_response()->set_traffic_matrix_id(
traffic_matrix_id);
return response;
}
void InfoServer::LogMessage(const LoggedMessage& logged_message) {
info::RequestLogEntry log_entry;
*(log_entry.mutable_request()) = *(logged_message.request);
log_entry.set_request_size_bytes(logged_message.request->ByteSize());
log_entry.set_response_size_bytes(logged_message.response_size_bytes);
const nc::viz::TCPConnectionInfo& connection_info =
logged_message.header_and_message->tcp_connection_info;
log_entry.set_connection_id(connection_info.connection_id);
log_entry.set_remote_ip(connection_info.remote_ip);
log_entry.set_remote_port(connection_info.remote_port);
log_entry.set_request_rx_ms(
logged_message.header_and_message->time_rx.count());
log_entry.set_request_started_processing_ms(
logged_message.processing_started.count());
log_entry.set_request_done_processing_ms(
logged_message.processing_done.count());
log_entry.set_response_sent_ms(logged_message.response_sent.count());
log_entry.set_worker_index(logged_message.worker_index);
LOG(INFO) << log_entry.DebugString();
}
} // namespace ctr
| 34.438134 | 80 | 0.688479 | [
"vector"
] |
871f801e5f3c30cf839a6a56618b9169b6f7f2fa | 4,405 | cpp | C++ | pwiz/analysis/demux/SpectrumPeakExtractor.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/analysis/demux/SpectrumPeakExtractor.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/analysis/demux/SpectrumPeakExtractor.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | //
// $Id$
//
//
// Original author: Jarrett Egertson <jegertso .@. uw.edu>
//
// 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.
//
#define PWIZ_SOURCE
#include "SpectrumPeakExtractor.hpp"
namespace pwiz {
namespace analysis {
SpectrumPeakExtractor::SpectrumPeakExtractor(const std::vector<double>& peakMzList, const pwiz::chemistry::MZTolerance& massError)
{
_numPeakBins = peakMzList.size();
_ranges = boost::shared_array< std::pair<double, double> >(new std::pair<double, double>[_numPeakBins]);
_maxDelta = 0.0;
for (size_t i = 0; i < peakMzList.size(); ++i)
{
double peakMz = peakMzList[i];
double deltaMz = peakMz - (peakMz - massError);
if (deltaMz > _maxDelta) _maxDelta = deltaMz;
_ranges[i].first = peakMz - deltaMz;
_ranges[i].second = peakMz + deltaMz;
}
_minValue = _ranges[0].first;
_maxValue = _ranges[_numPeakBins - 1].second;
boost::shared_array< std::pair<double, double> > range_copy = boost::shared_array< std::pair<double, double> >(new std::pair<double, double>[_numPeakBins]);
std::copy(_ranges.get(), _ranges.get() + _numPeakBins, range_copy.get());
/* Verify non-overlapping of ranges. Overlap may be observed if the peaks are not centroided. Overlapping ranges are undesirable because they
* could duplicate signal, which should be a conserved quantity. */
for (size_t i = 0; i + 1 < _numPeakBins; ++i)
{
if (range_copy[i].second > range_copy[i + 1].first)
{
// find center and snap edges to this center
double center = (range_copy[i].second + range_copy[i].first + range_copy[i + 1].second + range_copy[i + 1].first) / 4.0;
_ranges[i].second = center;
_ranges[i + 1].first = center;
}
}
}
void SpectrumPeakExtractor::operator()(msdata::Spectrum_const_ptr spectrum, MatrixType& m, size_t rowNum, double weight) const
{
// Puts intensities observed in the spectrum into bins specified by _ranges
msdata::BinaryDataArray_const_ptr mzArray = spectrum->getMZArray();
msdata::BinaryDataArray_const_ptr intensityArray = spectrum->getIntensityArray();
// intitialize the filtered values to zero
m.row(rowNum).setZero();
size_t binStartIndex = 0;
for (size_t queryIndex = 0; queryIndex < mzArray->data.size(); ++queryIndex)
{
// iterating through each "query" peak in the MS/MS spectrum to be filtered
double query = mzArray->data[queryIndex];
if (query < _minValue) continue;
if (query > _maxValue) break;
double minStart = query - _maxDelta;
// move the starting point for this search and future searches to the first bin
// that could possibly contain this peak
for (; binStartIndex < _numPeakBins; ++binStartIndex)
{
if (_ranges[binStartIndex].first >= minStart) break;
}
// look forward for peak bins that contain this query
for (size_t binIndex = binStartIndex; binIndex < _numPeakBins; ++binIndex)
{
// stop once past the query
if (_ranges[binIndex].first > query) break;
if (_ranges[binIndex].first <= query && query <= _ranges[binIndex].second)
{
m.row(rowNum)[binIndex] += intensityArray->data[queryIndex];
}
}
}
// for (int i = 0; i < _numPeakBins; ++i) intensities[i] *= weight;
m.row(rowNum) *= weight;
}
size_t SpectrumPeakExtractor::numPeaks() const
{
return _numPeakBins;
}
} // namespace analysis
} // namespace pwiz | 42.76699 | 164 | 0.612032 | [
"vector"
] |
87218a2e94f14ecc713fad0279b53ec6d9a20bb7 | 3,915 | cpp | C++ | Flight_controller/FC_util/src/HexaActuationSystem.cpp | AhmedHumais/HEAR_FC | 2e9abd990757f8b14711aa4f02f5ad85698da6fe | [
"Unlicense"
] | null | null | null | Flight_controller/FC_util/src/HexaActuationSystem.cpp | AhmedHumais/HEAR_FC | 2e9abd990757f8b14711aa4f02f5ad85698da6fe | [
"Unlicense"
] | null | null | null | Flight_controller/FC_util/src/HexaActuationSystem.cpp | AhmedHumais/HEAR_FC | 2e9abd990757f8b14711aa4f02f5ad85698da6fe | [
"Unlicense"
] | null | null | null | #include "HexaActuationSystem.hpp"
namespace HEAR{
ESCMotor::ESCMotor(int t_pin, int t_freq){
_pwmPin = t_pin;
_freq = t_freq;
this->initialize();
}
bool ESCMotor::initialize(){
_pwm = new RCOutput_Navio2();
if(!(_pwm->initialize(_pwmPin)) ) {
return 1;
}
_pwm->set_frequency(_pwmPin, _freq);
if ( !(_pwm->enable(_pwmPin)) ) {
return 1;
}
}
void ESCMotor::applyCommand(int t_command){
//std::cout << "Received Command on PIN: " << _pwmPin << " Value :" << t_command << "\r"; //std::endl;
_pwm->set_duty_cycle(_pwmPin, t_command);
}
HexaActuationSystem::HexaActuationSystem(int b_uid) : Block(BLOCK_ID::HEXAACTUATIONSYSTEM, b_uid){
body_rate_port = createInputPort<Vector3D<float>>(IP::BODY_RATE_CMD, "BODY_RATE_CMD");
thrust_port = createInputPort<float>(IP::THRUST_CMD, "THRUST_CMD");
cmd_out_port = createOutputPort<std::vector<float>>(OP::MOTOR_CMD, "MOTOR_CMD");
}
void HexaActuationSystem::process() {
if ( _hb_timer.tockMilliSeconds() > _hb_tol_ms){
_armed = false;
_take_off = false;
}
Vector3D<float> body_rate_cmd;
body_rate_port->read(body_rate_cmd);
_u[0] = body_rate_cmd.x;
_u[1] = body_rate_cmd.y;
_u[2] = body_rate_cmd.z;
thrust_port->read(_u[3]);
this->command();
}
void HexaActuationSystem::heartbeatCb(const std_msgs::Empty::ConstPtr& msg){
_hb_timer.tick();
}
void HexaActuationSystem::update(UpdateMsg* u_msg){
if(u_msg->getType() == UPDATE_MSG_TYPE::BOOL_MSG){
bool arm_val = ((BoolMsg*)u_msg)->data;;
if(arm_val){
if(_armed){
_take_off = arm_val;
std::cout << "take off \n";
}
else{
_armed = arm_val;
std::cout << "arm called \n";
}
}
else{
_armed = arm_val;
_take_off = arm_val;
std::cout << "disarm called \n";
}
// print armed
}
}
void HexaActuationSystem::setESCValues(int t_armed, int t_min, int t_max) {
_escMin_armed = t_armed;
_escMin = t_min;
_escMax = t_max;
}
void HexaActuationSystem::command(){
//TODO split into more methods
for(int i = 0; i < 6; i++){
_commands[i] = 0.0;
}
//Update pulse values
for(int i = 0; i < 6; i++){
for(int j = 0; j < 4; j++){
_commands[i] += _geometry[i][j] * _u[j];
}
}
//_u (PID outputs) should be between 0 and 1. Thus, we have to adjust for the range _escMin_armed to _escMax on _commands.
//Normalize and Constrain
for(int i = 0; i < 6; i++){
_commands[i] = (_commands[i] * (_escMax-_escMin_armed)) + _escMin_armed;
}
//Get minimum command
float min_command = _commands[0];
for(int i = 1; i < 6; i++){
if(_commands[i] < min_command){
min_command = _commands[i];
}
}
float bias = 0;
//Anti saturation
if(min_command < _escMin_armed){
bias = _escMin_armed - min_command;
for(int i = 0; i < 6; i++){
_commands[i] = _commands[i] + bias;
}
}
for(int i = 0; i < 6; i++){
if(_armed){
if(_take_off){
_commands[i] = this->constrain(_commands[i], _escMin_armed, _escMax);
}
else{
_commands[i] = _escMin_armed;
}
}else{
_commands[i] = _escMin;
}
}
//Actuate
for(int i = 0; i < 6; i++){
_actuators[i]->applyCommand(_commands[i]);
}
cmd_out_port->write(_commands);
}
int HexaActuationSystem::constrain(float value, int min_value, int max_value) {
if ((int)value > max_value) {
value = max_value;
}
// bug cathed in the original code
else if ((int)value < min_value) {
value = min_value;
}
return int(value);
}
} | 24.46875 | 126 | 0.564496 | [
"vector"
] |
87301a7f98eb7a3c4f7e02aa7ee113077094099a | 2,485 | cpp | C++ | src/WorkerThread.cpp | LUSpace/pactree | e91d832fb286fe7d37063b5d112c2cea55720f85 | [
"Apache-2.0"
] | 14 | 2021-08-29T19:04:30.000Z | 2022-03-10T09:35:21.000Z | src/WorkerThread.cpp | LUSpace/pactree | e91d832fb286fe7d37063b5d112c2cea55720f85 | [
"Apache-2.0"
] | 2 | 2021-12-08T07:53:48.000Z | 2022-02-17T04:16:35.000Z | src/WorkerThread.cpp | LUSpace/pactree | e91d832fb286fe7d37063b5d112c2cea55720f85 | [
"Apache-2.0"
] | 7 | 2021-08-22T23:57:19.000Z | 2022-01-26T19:31:00.000Z | // SPDX-FileCopyrightText: Copyright (c) 2019-2021 Virginia Tech
// SPDX-License-Identifier: Apache-2.0
#include "WorkerThread.h"
#include "Oplog.h"
#include "Combiner.h"
#include "pactree.h"
#include <assert.h>
#include <libpmemobj.h>
WorkerThread::WorkerThread(int id, int activeNuma) {
this->workerThreadId = id;
this->activeNuma = activeNuma;
this->workQueue = &g_workQueue[workerThreadId];
this->logDoneCount = 0;
this->opcount = 0;
if (id == 0) freeQueue = new std::queue<std::pair<uint64_t, void*>>;
}
bool WorkerThread::applyOperation() {
std::vector<OpStruct *>* oplog = workQueue->front();
int numaNode = workerThreadId % activeNuma;
SearchLayer* sl = g_perNumaSlPtr[numaNode];
uint8_t hash = static_cast<uint8_t>(workerThreadId / activeNuma);
bool ret = false;
for (auto opsPtr : *oplog) {
OpStruct &ops = *opsPtr;
if (ops.hash != hash) continue;
opcount++;
if (ops.op == OpStruct::insert){
void *newNodePtr= reinterpret_cast<void*> (((unsigned long)(ops.poolId)) << 48 | (ops.newNodeOid.off));
sl->insert(ops.key, newNodePtr);
opsPtr->op = OpStruct::done;
}
else if (ops.op == OpStruct::remove) {
sl->remove(ops.key, ops.oldNodePtr);
opsPtr->op = OpStruct::done;
flushToNVM((char*)&ops,sizeof(OpStruct));
if (workerThreadId == 0) {
std::pair<uint64_t, void *> removePair;
removePair.first = logDoneCount;
removePair.second = ops.oldNodePtr;
freeQueue->push(removePair);
ret = true;
}
}
else{
if(ops.op == OpStruct::done){
printf("done? %p\n",opsPtr);
}
exit(1);
}
flushToNVM((char*)opsPtr,sizeof(OpStruct));
smp_wmb();
}
workQueue->pop();
logDoneCount++;
return ret;
}
bool WorkerThread::isWorkQueueEmpty() {
return !workQueue->read_available();
}
void WorkerThread::freeListNodes(uint64_t removeCount) {
assert(workerThreadId == 0 && freeQueue != NULL);
if (freeQueue->empty()) return;
while (!freeQueue->empty()) {
std::pair<uint64_t, void*> removePair = freeQueue->front();
if (removePair.first < removeCount) {
PMEMoid ptr = pmemobj_oid(removePair.second);
pmemobj_free(&ptr);
freeQueue->pop();
}
else break;
}
}
| 31.858974 | 115 | 0.58672 | [
"vector"
] |
87323d291008d4e05cd15e6aac7ff09d9d54792c | 7,212 | cpp | C++ | src/njli/StopWatch.cpp | njligames/Engine | 899c7b79cea33a72fc34f159134f721b56715d3d | [
"MIT"
] | 1 | 2019-02-13T05:41:54.000Z | 2019-02-13T05:41:54.000Z | src/njli/StopWatch.cpp | njligames/Engine | 899c7b79cea33a72fc34f159134f721b56715d3d | [
"MIT"
] | null | null | null | src/njli/StopWatch.cpp | njligames/Engine | 899c7b79cea33a72fc34f159134f721b56715d3d | [
"MIT"
] | null | null | null | //
// StopWatch.cpp
// JLIGameEngineTest
//
// Created by James Folk on 1/8/15.
// Copyright (c) 2015 James Folk. All rights reserved.
//
#include "StopWatch.h"
#include "JLIFactoryTypes.h"
#include "World.h"
#include "StopWatchBuilder.h"
#define FORMATSTRING "{\"njli::StopWatch\":[]}"
#include "btPrint.h"
#include "JsonJLI.h"
namespace njli
{
StopWatch::StopWatch():
AbstractFactoryObject(this),
AbstractClock(),
m_CurrentClock(new btClock()),
m_IsStopped(false),
m_StoppedMilliseconds(-1)
{
}
StopWatch::StopWatch(const AbstractBuilder &builder):
AbstractFactoryObject(this),
AbstractClock(),
m_CurrentClock(new btClock()),
m_IsStopped(false),
m_StoppedMilliseconds(-1)
{
}
StopWatch::StopWatch(const StopWatch ©):
AbstractFactoryObject(this),
AbstractClock(copy),
m_CurrentClock(new btClock()),
m_IsStopped(false),
m_StoppedMilliseconds(-1)
{
}
StopWatch::~StopWatch()
{
delete m_CurrentClock;
m_CurrentClock = NULL;
}
StopWatch &StopWatch::operator=(const StopWatch &rhs)
{
if(this != &rhs)
{
AbstractClock::operator=(rhs);
}
return *this;
}
s32 StopWatch::calculateSerializeBufferSize() const
{
//TODO: calculateSerializeBufferSize
return 0;
}
void StopWatch::serialize(void* dataBuffer, btSerializer* serializer) const
{
//TODO: serialize
}
const char *StopWatch::getClassName()const
{
return "StopWatch";
}
s32 StopWatch::getType()const
{
return StopWatch::type();
}
StopWatch::operator std::string() const
{
return njli::JsonJLI::parse(string_format("%s", FORMATSTRING));
}
StopWatch **StopWatch::createArray(const u32 size)
{
return (StopWatch**)World::getInstance()->getWorldFactory()->createArray(StopWatch::type(), size);
}
void StopWatch::destroyArray(StopWatch **array, const u32 size)
{
World::getInstance()->getWorldFactory()->destroyArray((AbstractFactoryObject**)array, size);
}
StopWatch *StopWatch::create()
{
return dynamic_cast<StopWatch*>(World::getInstance()->getWorldFactory()->create(StopWatch::type()));
}
StopWatch *StopWatch::create(const StopWatchBuilder &builder)
{
AbstractBuilder *b = (AbstractBuilder *)&builder;
return dynamic_cast<StopWatch*>(World::getInstance()->getWorldFactory()->create(*b));
}
StopWatch *StopWatch::clone(const StopWatch &object)
{
return dynamic_cast<StopWatch*>(World::getInstance()->getWorldFactory()->clone(object, false));
}
StopWatch *StopWatch::copy(const StopWatch &object)
{
return dynamic_cast<StopWatch*>(World::getInstance()->getWorldFactory()->clone(object, true));
}
void StopWatch::destroy(StopWatch *object)
{
if(object)
{
World::getInstance()->getWorldFactory()->destroy(object);
}
}
void StopWatch::load(StopWatch &object, lua_State *L, int index)
{
// Push another reference to the table on top of the stack (so we know
// where it is, and this function can work for negative, positive and
// pseudo indices
lua_pushvalue(L, index);
// stack now contains: -1 => table
lua_pushnil(L);
// stack now contains: -1 => nil; -2 => table
while (lua_next(L, -2))
{
// stack now contains: -1 => value; -2 => key; -3 => table
// copy the key so that lua_tostring does not modify the original
lua_pushvalue(L, -2);
// stack now contains: -1 => key; -2 => value; -3 => key; -4 => table
const char *key = lua_tostring(L, -1);
const char *value = lua_tostring(L, -2);
if(lua_istable(L, -2))
{
StopWatch::load(object, L, -2);
}
else
{
if(lua_isnumber(L, index))
{
double number = lua_tonumber(L, index);
printf("%s => %f\n", key, number);
}
else if(lua_isstring(L, index))
{
const char *v = lua_tostring(L, index);
printf("%s => %s\n", key, v);
}
else if(lua_isboolean(L, index))
{
bool v = lua_toboolean(L, index);
printf("%s => %d\n", key, v);
}
else if(lua_isuserdata(L, index))
{
// swig_lua_userdata *usr;
// swig_type_info *type;
// assert(lua_isuserdata(L,index));
// usr=(swig_lua_userdata*)lua_touserdata(L,index); /* get data */
// type = usr->type;
// njli::AbstractFactoryObject *object = static_cast<njli::AbstractFactoryObject*>(usr->ptr);
// printf("%s => %d:%s\n", key, object->getType(), object->getClassName());
}
}
// pop value + copy of key, leaving original key
lua_pop(L, 2);
// stack now contains: -1 => key; -2 => table
}
// stack now contains: -1 => table (when lua_next returns 0 it pops the key
// but does not push anything.)
// Pop table
lua_pop(L, 1);
// Stack is now the same as it was on entry to this function
}
u32 StopWatch::type()
{
return JLI_OBJECT_TYPE_StopWatch;
}
void StopWatch::update(f64 milliseconds)
{
}
//TODO: fill in specific methods for StopWatch
//Start or continue the current lap.
void StopWatch::start()
{
m_IsStopped = false;
m_CurrentClock->reset();
}
unsigned long int StopWatch::getMilliseconds(s32 index)
{
if (index < 0)
{
if (isStopped())
return m_StoppedMilliseconds;
return m_CurrentClock->getTimeMilliseconds();
}
else if (index < m_Laps.size())
{
return m_Laps.at(index);
}
return -1;
}
//stop the current lap
//if already stopped, reset.
void StopWatch::stop()
{
if (!isStopped())
{
m_IsStopped = true;
m_StoppedMilliseconds = getMilliseconds();
}
}
bool StopWatch::isStopped()const
{
return m_IsStopped;
}
//stop the current lap and start a new lap.
bool StopWatch::lap()
{
if (!isStopped())
{
m_Laps.push_back(getMilliseconds());
m_CurrentClock->reset();
return true;
}
return false;
}
void StopWatch::clearLaps()
{
m_Laps.clear();
}
//return the current number of laps.
u64 StopWatch::numberOfLaps()
{
return m_Laps.size();
}
} | 27.422053 | 112 | 0.535774 | [
"object"
] |
8738cb21a65e020d1f1e325e0cb8ccd00866b675 | 15,630 | cc | C++ | PacDisplay/PacEvtDisplay.cc | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | PacDisplay/PacEvtDisplay.cc | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | PacDisplay/PacEvtDisplay.cc | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | #include "BaBar/BaBar.hh"
#include "PacDisplay/PacEvtDisplay.hh"
#include "AbsEnv/AbsEnv.hh"
#include "PacEmc/PacEmcCluster.hh"
#include "PacEmc/PacReconstructEmc.hh"
#include "PacEnv/PacConfig.hh"
#include "PacDetector/PacCylDetector.hh"
#include "PacGeom/PacCylDetElem.hh"
#include "PacGeom/PacCylDetType.hh"
#include "PacGeom/PacDetector.hh"
#include "PacGeom/PacHelix.hh"
#include "PacGeom/PacPieceTraj.hh"
#include "PacGeom/PacPlaneDetElem.hh"
#include "PacGeom/PacConeDetElem.hh"
#include "PacGeom/PacConeDetType.hh"
#include "PacGeom/PacRectDetType.hh"
#include "PacGeom/PacRingDetType.hh"
#include "PacGeom/PacCylVoxelSet.hh"
#include "DetectorModel/DetElemList.hh"
#include "DetectorModel/DetMaterial.hh"
#include "DetectorModel/DetSet.hh"
#include "PacSim/PacSimTrack.hh"
#include "PacSim/PacSimHit.hh"
#include "PDT/Pdt.hh"
#include "PDT/PdtEntry.hh"
#include "PDT/PdtPid.hh"
#include "ProxyDict/Ifd.hh"
#include "TrajGeom/TrkLineTraj.hh"
#include "TrkBase/TrkExchangePar.hh"
#include "TrkBase/TrkHelixUtils.hh"
#include "TrkEnv/TrkEnv.hh"
#include "AbsCalo/AbsRecoCalo.hh"
#include "G3Data/GVertex.hh"
#include "G3Data/GTrack.hh"
#include "GenEnv/GenEnv.hh"
#include "TrkBase/TrkRecoTrk.hh"
#include "KalmanTrack/KalRep.hh"
#include "KalmanTrack/KalInterface.hh"
#include "PacEmc/PacEmcCluster.hh"
#include "PacEmc/PacReconstructEmc.hh"
#include "TrajGeom/TrkLineTraj.hh"
#include "TrkBase/TrkExchangePar.hh"
#include "TrkBase/TrkHelixUtils.hh"
#include "CLHEP/Geometry/HepPoint.h"
#include "CLHEP/Matrix/Vector.h"
#include "CLHEP/Vector/ThreeVector.h"
#include "BField/BField.hh"
#include <TParticle.h>
#include <TParticlePDG.h>
PacEvtDisplay::PacEvtDisplay(){
}
PacEvtDisplay::~PacEvtDisplay(){
}
void
PacEvtDisplay::init(const char* filename,unsigned resolution,bool verbose) {
_resolution = resolution;
_verbose=verbose;
_dispfile = new TFile(filename,"RECREATE");
// setup the trees;
// materials
_materials = new TTree("materials","materials");
_materials->Branch("material",&_dmat.zeff,PacDispMat::rootnames());
// cylinders
_cylinders = new TTree("cylinders","cylinders");
_cylinders->Branch("cylinder",&_dcyl.radius,PacDispCyl::rootnames());
// rings
_rings = new TTree("rings","rings");
_rings->Branch("ring",&_dring.z,PacDispRing::rootnames());
// rectangles
_rects = new TTree("rects","rects");
_rects->Branch("rect",&_drect.cx,PacDispRect::rootnames());
// cones
_cones = new TTree("cones","cones");
_cones->Branch("cone",&_dcone.tanTheta,PacDispCone::rootnames());
// generated tracks
_gentrks = new TTree("gentracks","gentracks");
_gentrks->Branch("trajectory",&_gtrajs);
_gentrks->Branch("trajpoint",&_gpoints);
// simulated tracks
_simtrks = new TTree("simtracks","simtracks");
_simtrks->Branch("trajectory",&_strajs);
_simtrks->Branch("trajpoint",&_spoints);
// reconstructed tracks
_rectrks = new TTree("rectracks","rectracks");
_rectrks->Branch("trajectory",&_rtrajs);
_rectrks->Branch("trajpoint",&_rpoints);
// simhits
_simhits = new TTree("simhits","simhits");
_simhits->Branch("simhit",&_shits);
// clusters
_clusters= new TTree("clusters","clusters");
_clusters->Branch("cluster",&_clusts);
// voxel cylinders
_vcylinders = new TTree("vcylinders","vcylinders");
_vcylinders->Branch("vcylinder",&_vcyl.radius,PacDispCyl::rootnames());
// voxel rings
_vrings = new TTree("vrings","vrings");
_vrings->Branch("vring",&_vring.z,PacDispRing::rootnames());
// voxel rectangles
_vrects = new TTree("vrects","vrects");
_vrects->Branch("vrect",&_vrect.cx,PacDispRect::rootnames());
// get the detector
_detector = dynamic_cast<PacCylDetector*>(Ifd<PacDetector>::get(gblPEnv, "Tracking Det" ));
if(_detector == 0)
cerr << "Couldn't find detector!!!! " << endl;
}
void
PacEvtDisplay::finalize(){
// store objects and close file
_dispfile->Write();
_dispfile->Close();
}
void
PacEvtDisplay::reset() {
// clear out storage from last event
_gtrajs.clear();
_strajs.clear();
_rtrajs.clear();
_gpoints.clear();
_spoints.clear();
_rpoints.clear();
_shits.clear();
_clusts.clear();
}
void
PacEvtDisplay::drawDetector(){
//Get Detector Information
DetElemList elements; // list of DetectorElements
_detector->detectorModel()->listAllElements(elements);
DetElemList::const_iterator ielem = elements.begin();
TwoDCoord* nullpoint = new TwoDCoord(0.0,0.0);
while(ielem != elements.end()){
// only draw elements without large gaps
static double maxgap=0.5;
const PacDetElem* elem;
if( (elem = dynamic_cast<const PacDetElem*>(*ielem)) != 0 &&
elem->gapFraction() < maxgap) {
const PacCylDetElem* celem;
const PacPlaneDetElem* pelem;
const PacConeDetElem* coelem;
if((celem = dynamic_cast<const PacCylDetElem*>(*ielem)) != 0) {
const PacCylDetType* ctype = celem->cylType();
_dcyl.radius = celem->radius();
_dcyl.lowZ = ctype->lowZ();
_dcyl.hiZ = ctype->hiZ();
_dcyl.thickness = ctype->thick();
const DetMaterial* detmat = &(ctype->material(nullpoint));
if(detmat != 0){
_dcyl.imat = fillMat(detmat);
_cylinders->Fill();
}
} else if ((pelem = dynamic_cast<const PacPlaneDetElem*>(*ielem)) != 0) {
// plane: decide if a ring or a rectangle
const PacRingDetType* ringtype = dynamic_cast<const PacRingDetType*>(pelem->planeType());
const PacRectDetType* recttype = dynamic_cast<const PacRectDetType*>(pelem->planeType());
if(ringtype != 0){
_dring.z = pelem->midpoint().z();
_dring.thickness = ringtype->thick();
_dring.radlow = ringtype->lowrad();
_dring.radhigh = ringtype->highrad();
const DetMaterial* detmat = &(ringtype->material(nullpoint));
if(detmat != 0){
_dring.imat = fillMat(detmat);
_rings->Fill();
}
} else if(recttype != 0){
_drect.cx = pelem->midpoint().x();
_drect.cy = pelem->midpoint().y();
_drect.cz = pelem->midpoint().z();
_drect.nx = pelem->normal().x();
_drect.ny = pelem->normal().y();
_drect.nz = pelem->normal().z();
_drect.ux = pelem->udir().x();
_drect.uy = pelem->udir().y();
_drect.uz = pelem->udir().z();
_drect.thickness = recttype->thick();
_drect.usize = recttype->uSize();
_drect.vsize = recttype->vSize();
const DetMaterial* detmat = &(recttype->material(nullpoint));
if(detmat != 0){
_drect.imat = fillMat(detmat);
_rects->Fill();
}
}
} else if ((coelem = dynamic_cast<const PacConeDetElem*>(*ielem)) != 0) {
_dcone.tanTheta = coelem->tanTheta();
_dcone.zVertex = coelem->zVertex();
const PacConeDetType* cotype = coelem->coneType();
_dcone.thick = cotype->thick();
_dcone.lowR = cotype->lowR();
_dcone.hiR = cotype->hiR();
const DetMaterial* detmat = &(cotype->material(nullpoint));
if(detmat != 0){
_dcone.imat = fillMat(detmat);
_cones->Fill();
}
} else {
cout << "Error: unknown element " << *ielem << endl;
}
}
ielem++;
}
}
int
PacEvtDisplay::fillMat(const DetMaterial* detmat) {
std::string matname = *(detmat->name());
std::map<std::string,int>::const_iterator ifound = _matlist.find(matname);
if(ifound == _matlist.end()){
// new material
int imat = _matlist.size();
_matlist[matname] = imat;
if (_verbose)cout << "found new material " << matname << " ID # = " << imat << endl;
_dmat.zeff = detmat->zeff();
_dmat.aeff = detmat->aeff();
_dmat.density = detmat->density();
_dmat.radlen = detmat->radiationLength();
_dmat.intlen = detmat->intLength();
snprintf(_dmat.matname,STRINGSIZE,"%s",matname.c_str());
_materials->Fill();
}
return _matlist[matname];
}
void
PacEvtDisplay::drawVoxels(){
//Get Detector Information
DetElemList elements; // list of DetectorElements
const std::vector<PacCylVoxelSet*>& vsets = _detector->voxelSets();
for(std::vector<PacCylVoxelSet*>::const_iterator ivset = vsets.begin();ivset!=vsets.end();ivset++){
const std::vector<PacCylDetElem*>& relems = (*ivset)->relems();
const std::vector<PacPlaneDetElem*>& zelems = (*ivset)->zelems();
const std::vector<PacPlaneDetElem*>& felems = (*ivset)->felems();
for(std::vector<PacCylDetElem*>::const_iterator icyl=relems.begin();icyl != relems.end();icyl++){
const PacCylDetElem* celem = *icyl;
if(celem != 0){
const PacCylDetType* ctype = celem->cylType();
_vcyl.radius = celem->radius();
_vcyl.lowZ = ctype->lowZ();
_vcyl.hiZ = ctype->hiZ();
_vcyl.thickness = ctype->thick();
_vcyl.imat = 0;
_vcylinders->Fill();
}
}
for(std::vector<PacPlaneDetElem*>::const_iterator iring=zelems.begin();iring!=zelems.end();iring++){
const PacPlaneDetElem* relem = *iring;
if(relem != 0){
const PacRingDetType* ringtype = dynamic_cast<const PacRingDetType*>(relem->planeType());
if(ringtype != 0){
_vring.z = relem->midpoint().z();
_vring.thickness = ringtype->thick();
_vring.radlow = ringtype->lowrad();
_vring.radhigh = ringtype->highrad();
_vring.imat = 0;
_vrings->Fill();
} else {
cout << "Z element is not a ring! " << endl;
}
}
}
for(std::vector<PacPlaneDetElem*>::const_iterator iphi=felems.begin();iphi!=felems.end();iphi++){
const PacPlaneDetElem* felem = *iphi;
if(felem != 0){
const PacRectDetType* recttype = dynamic_cast<const PacRectDetType*>(felem->planeType());
if(recttype != 0){
_vrect.cx = felem->midpoint().x();
_vrect.cy = felem->midpoint().y();
_vrect.cz = felem->midpoint().z();
_vrect.nx = felem->normal().x();
_vrect.ny = felem->normal().y();
_vrect.nz = felem->normal().z();
_vrect.ux = felem->udir().x();
_vrect.uy = felem->udir().y();
_vrect.uz = felem->udir().z();
_vrect.thickness = recttype->thick();
_vrect.usize = recttype->uSize();
_vrect.vsize = recttype->vSize();
_vrect.imat = 0;
_vrects->Fill();
} else {
cout << "Phi element is not a rectangle! " << endl;
}
}
}
}
}
void
PacEvtDisplay::drawGTrack(const GTrack* gentrk,double range,const BField* bfield) {
// get GTrack information
const PdtEntry* pdt = gentrk->pdt();
assert(pdt != 0);
Hep3Vector mom = gentrk->p4().vect();
const GVertex* gvtx = gentrk->vertex();
HepPoint pos;
if(gvtx != 0)
pos = gvtx->position();
else
cout << "No GVertex found for GTrack!!" << endl;
// set traj parameters
int pid(0);
int charge = (int)pdt->charge();
if(charge == 0) {
pid = (int)pdt->pidNeutId();
} else {
pid = pdt->pidId();
}
_gtrajs.push_back(PacDispTrackTraj(pdt->lundId(),charge,kGreen,_gpoints.size(),_gpoints.size()+_resolution));
//check for magnetic field
bool hasfield = bfield != 0 && fabs(bfield->bFieldZ(pos)) > 0.0;
// charged particles
if(charge != 0 && hasfield ){
// temp data
HepVector hpars(5);
double dcharge = pdt->charge();
double localflt(0.0);
// compute helix parameters and create helix trajectory
TrkHelixUtils::helixFromMom(hpars,localflt,pos,mom,dcharge,*bfield);
PacHelix helix(hpars,localflt,range);
fillTrajPoints(&helix,_gpoints);
} else {
// neutral particle, or no BField; create line traj
TrkLineTraj line(pos,mom,range);
fillTrajPoints(&line,_gpoints);
}
}
void
PacEvtDisplay::drawParticle(const TParticle* tpart,double range,const BField* bfield) {
Hep3Vector mom(tpart->Px(),tpart->Py(),tpart->Pz());
HepPoint pos(tpart->Vx(),tpart->Vy(),tpart->Vz());
int pid = tpart->GetPdgCode();
const TParticlePDG* pdg = (const_cast<TParticle*>(tpart))->GetPDG();
int charge(0);
if(pdg != 0)
charge = 3*pdg->Charge();
_gtrajs.push_back(PacDispTrackTraj(pid,charge,kGreen,_gpoints.size(),_gpoints.size()+_resolution));
//check for magnetic field
bool hasfield = bfield != 0 && fabs(bfield->bFieldZ(pos)) > 0.0;
// charged particles
if(charge != 0 && hasfield ){
// temp data
HepVector hpars(5);
double localflt(0.0);
// compute helix parameters and create helix trajectory
TrkHelixUtils::helixFromMom(hpars,localflt,pos,mom,charge,*bfield);
PacHelix helix(hpars,localflt,range);
fillTrajPoints(&helix,_gpoints);
} else {
// neutral particle, or no BField; create line traj
TrkLineTraj line(pos,mom,range);
fillTrajPoints(&line,_gpoints);
}
}
void
PacEvtDisplay::drawSimTrack(const PacSimTrack* simtrk) {
const PdtEntry* pdt = simtrk->pdt();
assert(pdt != 0);
// set traj parameters
int pid(0);
int charge = (int)pdt->charge();
if(charge == 0) {
pid = (int)pdt->pidNeutId();
} else {
pid = pdt->pidId();
}
_strajs.push_back(PacDispTrackTraj(pdt->lundId(),charge,kBlue,_spoints.size(),_spoints.size()+_resolution));
const PacPieceTraj* simtraj = simtrk->getTraj();
fillTrajPoints(simtraj,_spoints);
}
void
PacEvtDisplay::drawRecTrack(const TrkRecoTrk* rectrk) {
int pid = (int)rectrk->defaultType();
//Get Reconstructed Track data
KalInterface kinter;
rectrk->attach(kinter,rectrk->defaultType());
const KalRep* kalrep = kinter.kalmanRep();
int charge = kalrep->charge();
_rtrajs.push_back(PacDispTrackTraj(pid,charge,kRed,_rpoints.size(),_rpoints.size()+_resolution));
const TrkDifPieceTraj& rectraj = kalrep->pieceTraj();
fillTrajPoints(&rectraj,_rpoints);
}
void
PacEvtDisplay::drawSimHits(const PacSimTrack* track,unsigned istrk) {
const std::vector<PacSimHit>& points = track->getHitList();
PacDispSimHit dhit;
dhit.isimtrk = istrk;
for(int i = 0; i < points.size(); i++) {
dhit.point.x = points[i].position().x();
dhit.point.y = points[i].position().y();
dhit.point.z = points[i].position().z();
dhit.effect = points[i].detEffect();
dhit.eloss = points[i].momentumIn().mag()-points[i].momentumOut().mag();
_shits.push_back(dhit);
}
}
void
PacEvtDisplay::drawCluster(const AbsRecoCalo *calo) {
const PacEmcCluster *cluster= dynamic_cast<const PacEmcCluster*>(calo);
PacEmcModel *model= PacEmcModel::getModel();
PacDispCluster dclust;
for ( unsigned i=0; i< cluster->pacEmcDigis()->size(); i++) {
const PacEmcDigi *digi= (*cluster->pacEmcDigis())[i];
// w.r.t. EMC geometry (0,0,0)
dclust.theta= digi->whereLocal().theta();
dclust.phi= digi->whereLocal().phi();
dclust.ith= digi->theta();
dclust.iph= digi->phi();
dclust.rlocal= digi->whereLocal().mag();
dclust.dtheta= model->deltaTheta( digi->theta() );
dclust.dphi= model->deltaPhi( digi->theta() );
// global coordinate
HepPoint pos= digi->where();
dclust.x= pos.x();
dclust.y= pos.y();
dclust.z= pos.z();
dclust.energy= digi->energy();
_clusts.push_back(dclust);
}
}
void
PacEvtDisplay::fillTrees(){
_gentrks->Fill();
_simtrks->Fill();
_rectrks->Fill();
_simhits->Fill();
_clusters->Fill();
}
void
PacEvtDisplay::fillTrajPoints(const Trajectory* traj, std::vector<PacDispPoint>& tpoints) {
double smin = traj->lowRange();
double smax = traj->hiRange();
double step = (smax - smin)/_resolution;
for(unsigned n = 0; n < _resolution; n++) {
double s = smin + n*step;
HepPoint p = traj->position(s);
tpoints.push_back(PacDispPoint(p.x(),p.y(),p.z()));
}
}
| 33.904555 | 111 | 0.65112 | [
"geometry",
"vector",
"model"
] |
8748a5ce03eb4305228af9d6c43f212efd4037b2 | 3,588 | cpp | C++ | compiler/luci/profile/src/CircleNodeOrigin.test.cpp | chogba6/ONE | 3d35259f89ee3109cfd35ab6f38c231904487f3b | [
"Apache-2.0"
] | 255 | 2020-05-22T07:45:29.000Z | 2022-03-29T23:58:22.000Z | compiler/luci/profile/src/CircleNodeOrigin.test.cpp | chogba6/ONE | 3d35259f89ee3109cfd35ab6f38c231904487f3b | [
"Apache-2.0"
] | 5,102 | 2020-05-22T07:48:33.000Z | 2022-03-31T23:43:39.000Z | compiler/luci/profile/src/CircleNodeOrigin.test.cpp | chogba6/ONE | 3d35259f89ee3109cfd35ab6f38c231904487f3b | [
"Apache-2.0"
] | 120 | 2020-05-22T07:51:08.000Z | 2022-02-16T19:08:05.000Z | /*
* Copyright (c) 2021 Samsung Electronics Co., Ltd. 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 "luci/Profile/CircleNodeID.h"
#include "luci/Profile/CircleNodeOrigin.h"
#include <luci/IR/CircleNodes.h>
#include <gtest/gtest.h>
TEST(LuciCircleNodeOrigin, simple_single_origin)
{
auto g = loco::make_graph();
auto add = g->nodes()->create<luci::CircleAdd>();
ASSERT_FALSE(has_origin(add));
auto origin = luci::single_origin(3, "add");
add_origin(add, origin);
ASSERT_TRUE(has_origin(add));
auto sources = get_origin(add)->sources();
ASSERT_EQ(1, sources.size());
for (auto source : sources)
{
ASSERT_EQ(3, source->id());
ASSERT_EQ(0, source->name().compare("add"));
}
}
TEST(LuciCircleNodeOrigin, simple_composite_origin_with_initializer)
{
auto g = loco::make_graph();
auto mul = g->nodes()->create<luci::CircleMul>();
ASSERT_FALSE(has_origin(mul));
auto origin =
luci::composite_origin({luci::single_origin(3, "add"), luci::single_origin(7, "sub")});
add_origin(mul, origin);
ASSERT_TRUE(has_origin(mul));
bool add_origin_passed = false;
bool sub_origin_passed = false;
auto sources = get_origin(mul)->sources();
ASSERT_EQ(2, sources.size());
for (auto source : sources)
{
if (source->id() == 3 && source->name().compare("add") == 0)
add_origin_passed = true;
if (source->id() == 7 && source->name().compare("sub") == 0)
sub_origin_passed = true;
}
ASSERT_EQ(true, add_origin_passed);
ASSERT_EQ(true, sub_origin_passed);
}
TEST(LuciCircleNodeOrigin, simple_composite_origin_with_vector)
{
auto g = loco::make_graph();
auto mul = g->nodes()->create<luci::CircleMul>();
ASSERT_FALSE(has_origin(mul));
std::vector<std::shared_ptr<luci::CircleNodeOrigin>> vec;
vec.push_back(luci::single_origin(3, "add"));
vec.push_back(luci::single_origin(7, "sub"));
auto origin = luci::composite_origin(vec);
add_origin(mul, origin);
ASSERT_TRUE(has_origin(mul));
bool add_origin_passed = false;
bool sub_origin_passed = false;
auto sources = get_origin(mul)->sources();
ASSERT_EQ(2, sources.size());
for (auto source : sources)
{
if (source->id() == 3 && source->name().compare("add") == 0)
add_origin_passed = true;
if (source->id() == 7 && source->name().compare("sub") == 0)
sub_origin_passed = true;
}
ASSERT_EQ(true, add_origin_passed);
ASSERT_EQ(true, sub_origin_passed);
}
TEST(LuciCircleNodeOrigin, composite_origin_empty_ctor_NEG)
{
ASSERT_ANY_THROW(luci::composite_origin({}));
}
TEST(LuciCircleNodeOrigin, add_null_origin_NEG)
{
auto g = loco::make_graph();
auto add = g->nodes()->create<luci::CircleAdd>();
ASSERT_FALSE(has_origin(add));
add_origin(add, nullptr);
ASSERT_FALSE(has_origin(add));
}
TEST(LuciCircleNodeOrigin, add_empty_origin_NEG)
{
auto g = loco::make_graph();
auto add = g->nodes()->create<luci::CircleAdd>();
ASSERT_FALSE(has_origin(add));
add_origin(add, luci::composite_origin({nullptr, nullptr}));
ASSERT_FALSE(has_origin(add));
}
| 26.977444 | 91 | 0.695931 | [
"vector"
] |
874ae08f220fe6feea7c937663445a97d1845c9d | 3,631 | cpp | C++ | RNGSimulation.cpp | SleepingGlaceon/VRiftMCarloSimulation | c018d9be651105894cd97ae51f52e67e3a188ba3 | [
"MIT"
] | null | null | null | RNGSimulation.cpp | SleepingGlaceon/VRiftMCarloSimulation | c018d9be651105894cd97ae51f52e67e3a188ba3 | [
"MIT"
] | null | null | null | RNGSimulation.cpp | SleepingGlaceon/VRiftMCarloSimulation | c018d9be651105894cd97ae51f52e67e3a188ba3 | [
"MIT"
] | null | null | null | #include "RNGSimulation.h"
static const int knockbackAR = 15;
static const int doubleAR = 15;
static const int speed = 10;
static const int huntsAdded = 25;
VRiftSimulation::VRiftSimulation()
{
std::vector<int> steps;
std::vector<int> floor;
std::map<int,int> totalFloors;
}
void VRiftSimulation::simulateOneRun(int initialHunts, int addedHunts, double normalCr, double knockbackCR)
{
Floor floorTracking;
while(initialHunts > 0)
{
srand(time(NULL));
int ar = rand()%100;
int cr = rand()%100;
if(ar < doubleAR)
{
floorTracking.addSteps(2*speed);
}
else if (ar < doubleAR +knockbackAR)
{
if(cr < knockbackCR)
{
floorTracking.addSteps(speed);
}
else
{
floorTracking.subtractSteps(10);
}
}
else
{
if(cr < normalCr)
{
floorTracking.addSteps(speed);
}
}
initialHunts--;
initialHunts+= (floorTracking.getAndResetBonus()*huntsAdded);
}
floor.push_back(floorTracking.getFloor());
}
void VRiftSimulation::simulateLots(int initialHunts, int addedHunts, double normalCR, double knockbackCR, int trials)
{
for (int i = 0; i< trials; i ++)
{
simulateOneRun(initialHunts,addedHunts,normalCR,knockbackCR);
}
for (std::vector<int>::iterator it = floor.begin(); it!=floor.end(); it++)
{
totalFloors[*it]++;
}
}
void VRiftSimulation::printResults()
{
std::cout << "results\n";
for(std::map<int,int>::iterator it= totalFloors.begin(); it!= totalFloors.end(); it++)
{
std::cout << "floor" << it -> first << " " << it->second << std::endl;
}
}
Floor::Floor(int floor, int steps)
{
currentFloor = floor;
currentSteps = steps;
bonusesToAdd = 0;
}
int Floor::getFloor()
{
return currentFloor;
}
int Floor::getSteps()
{
return currentSteps;
}
int Floor::getAndResetBonus()
{
int bonus = bonusesToAdd;
bonusesToAdd = 0;
return bonus;
}
/*
Adds steps to the floor and adjusts the floor number accordingly
assumes that we're adding positive numbers only (no 0 or negatives)
*/
void Floor::addSteps(int steps)
{
currentSteps += steps;
if((currentFloor%8)==0)
{
currentSteps -=1;
currentFloor++;
bonusesToAdd++;
}
while((currentFloor%8)!=0) ///while not at eclipse floor, seeing if we're past the floor
{
int floorStepCount = (currentFloor/8)*10 +20; ///int arithmetic is intentional
if(currentSteps>floorStepCount)
{
currentSteps-=floorStepCount;
currentFloor++;
}
else
{
break;
}
}
if((currentFloor%8)==0) ///if we get to eclipse floor
{
currentSteps = 1;
bonusesToAdd++;
}
}
///pushbacks only push to the start of a floor
void Floor::subtractSteps(int steps)
{
currentSteps -= steps;
if(currentSteps<1)
currentSteps=1;
}
int Floor::getTotalSteps()
{
int tempFloor = currentFloor;
int tempSteps = currentSteps;
while(tempFloor%8 != 0)
{
tempFloor--;
tempSteps+= (tempFloor/8 * 10)+20; ///int arithmetic is intentional here
}
while(tempFloor/8 != 0)
{
tempFloor -=8;
tempSteps+= (tempFloor/8 * 70) +71;
}
tempSteps--;
return tempSteps;
}
| 23.888158 | 118 | 0.557147 | [
"vector"
] |
875449284dd23388b32812b196b0bf3442201dda | 16,195 | cxx | C++ | main/unotools/source/config/inetoptions.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/unotools/source/config/inetoptions.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/unotools/source/config/inetoptions.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_unotools.hxx"
#include <unotools/inetoptions.hxx>
#include "rtl/instance.hxx"
#include <tools/urlobj.hxx>
#ifndef _WILDCARD_HXX
#include <tools/wldcrd.hxx>
#endif
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <utility>
#include <com/sun/star/beans/PropertyChangeEvent.hpp>
#include <com/sun/star/beans/XPropertiesChangeListener.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <osl/mutex.hxx>
#include <rtl/ustring.h>
#include <rtl/ustring.hxx>
#include <sal/types.h>
#include <unotools/configitem.hxx>
#include <unotools/processfactory.hxx>
#include <osl/diagnose.h>
#include <salhelper/refobj.hxx>
#include <rtl/logfile.hxx>
#include "itemholder1.hxx"
using namespace com::sun;
//============================================================================
//
// takeAny
//
//============================================================================
namespace {
template< typename T > inline T takeAny(star::uno::Any const & rAny)
{
T aValue = T();
rAny >>= aValue;
return aValue;
}
}
//============================================================================
//
// SvtInetOptions::Impl
//
//============================================================================
class SvtInetOptions::Impl: public salhelper::ReferenceObject,
public utl::ConfigItem
{
public:
enum Index
{
INDEX_NO_PROXY,
INDEX_PROXY_TYPE,
INDEX_FTP_PROXY_NAME,
INDEX_FTP_PROXY_PORT,
INDEX_HTTP_PROXY_NAME,
INDEX_HTTP_PROXY_PORT
};
Impl();
star::uno::Any getProperty(Index nIndex);
void
setProperty(Index nIndex, star::uno::Any const & rValue, bool bFlush);
inline void flush() { Commit(); }
void
addPropertiesChangeListener(
star::uno::Sequence< rtl::OUString > const & rPropertyNames,
star::uno::Reference< star::beans::XPropertiesChangeListener > const &
rListener);
void
removePropertiesChangeListener(
star::uno::Sequence< rtl::OUString > const & rPropertyNames,
star::uno::Reference< star::beans::XPropertiesChangeListener > const &
rListener);
private:
enum { ENTRY_COUNT = INDEX_HTTP_PROXY_PORT + 1 };
struct Entry
{
enum State { UNKNOWN, KNOWN, MODIFIED };
inline Entry(): m_eState(UNKNOWN) {}
rtl::OUString m_aName;
star::uno::Any m_aValue;
State m_eState;
};
// MSVC has problems with the below Map type when
// star::uno::Reference< star::beans::XPropertiesChangeListener > is not
// wrapped in class Listener:
class Listener:
public star::uno::Reference< star::beans::XPropertiesChangeListener >
{
public:
Listener(star::uno::Reference<
star::beans::XPropertiesChangeListener > const &
rListener):
star::uno::Reference< star::beans::XPropertiesChangeListener >(
rListener)
{}
};
typedef std::map< Listener, std::set< rtl::OUString > > Map;
osl::Mutex m_aMutex;
Entry m_aEntries[ENTRY_COUNT];
Map m_aListeners;
virtual inline ~Impl() { Commit(); }
virtual void Notify(star::uno::Sequence< rtl::OUString > const & rKeys);
virtual void Commit();
void notifyListeners(star::uno::Sequence< rtl::OUString > const & rKeys);
};
//============================================================================
// virtual
void
SvtInetOptions::Impl::Notify(star::uno::Sequence< rtl::OUString > const &
rKeys)
{
{
osl::MutexGuard aGuard(m_aMutex);
for (sal_Int32 i = 0; i < rKeys.getLength(); ++i)
for (sal_Int32 j = 0; j < ENTRY_COUNT; ++j)
if (rKeys[i] == m_aEntries[j].m_aName)
{
m_aEntries[j].m_eState = Entry::UNKNOWN;
break;
}
}
notifyListeners(rKeys);
}
//============================================================================
// virtual
void SvtInetOptions::Impl::Commit()
{
star::uno::Sequence< rtl::OUString > aKeys(ENTRY_COUNT);
star::uno::Sequence< star::uno::Any > aValues(ENTRY_COUNT);
sal_Int32 nCount = 0;
{
osl::MutexGuard aGuard(m_aMutex);
for (sal_Int32 i = 0; i < ENTRY_COUNT; ++i)
if (m_aEntries[i].m_eState == Entry::MODIFIED)
{
aKeys[nCount] = m_aEntries[i].m_aName;
aValues[nCount] = m_aEntries[i].m_aValue;
++nCount;
m_aEntries[i].m_eState = Entry::KNOWN;
}
}
if (nCount > 0)
{
aKeys.realloc(nCount);
aValues.realloc(nCount);
PutProperties(aKeys, aValues);
}
}
//============================================================================
void
SvtInetOptions::Impl::notifyListeners(
star::uno::Sequence< rtl::OUString > const & rKeys)
{
typedef std::pair< star::uno::Reference< star::beans::XPropertiesChangeListener >,
star::uno::Sequence< star::beans::PropertyChangeEvent > > Listen2EventPair;
typedef std::vector< Listen2EventPair > NotificationList;
NotificationList aNotifications;
{
osl::MutexGuard aGuard(m_aMutex);
aNotifications.reserve(m_aListeners.size());
Map::const_iterator aMapEnd(m_aListeners.end());
for (Map::const_iterator aIt(m_aListeners.begin()); aIt != aMapEnd;
++aIt)
{
const Map::mapped_type &rSet = aIt->second;
Map::mapped_type::const_iterator aSetEnd(rSet.end());
star::uno::Sequence< star::beans::PropertyChangeEvent >
aEvents(rKeys.getLength());
sal_Int32 nCount = 0;
for (sal_Int32 i = 0; i < rKeys.getLength(); ++i)
{
rtl::OUString
aTheKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
"Inet/")));
aTheKey += rKeys[i];
if (rSet.find(aTheKey) != aSetEnd)
{
aEvents[nCount].PropertyName = aTheKey;
aEvents[nCount].PropertyHandle = -1;
++nCount;
}
}
if (nCount > 0)
aNotifications.push_back( Listen2EventPair( aIt->first, aEvents));
}
}
for (NotificationList::size_type i = 0; i < aNotifications.size(); ++i)
if (aNotifications[i].first.is())
aNotifications[i].first->
propertiesChange(aNotifications[i].second);
}
//============================================================================
SvtInetOptions::Impl::Impl():
ConfigItem(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Inet/Settings")))
{
m_aEntries[INDEX_NO_PROXY].m_aName
= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetNoProxy"));
m_aEntries[INDEX_PROXY_TYPE].m_aName
= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetProxyType"));
m_aEntries[INDEX_FTP_PROXY_NAME].m_aName
= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetFTPProxyName"));
m_aEntries[INDEX_FTP_PROXY_PORT].m_aName
= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetFTPProxyPort"));
m_aEntries[INDEX_HTTP_PROXY_NAME].m_aName
= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetHTTPProxyName"));
m_aEntries[INDEX_HTTP_PROXY_PORT].m_aName
= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetHTTPProxyPort"));
star::uno::Sequence< rtl::OUString > aKeys(ENTRY_COUNT);
for (sal_Int32 i = 0; i < ENTRY_COUNT; ++i)
aKeys[i] = m_aEntries[i].m_aName;
if (!EnableNotification(aKeys))
OSL_ENSURE(false,
"SvtInetOptions::Impl::Impl(): Bad EnableNotifications()");
}
//============================================================================
star::uno::Any SvtInetOptions::Impl::getProperty(Index nPropIndex)
{
for (int nTryCount = 0; nTryCount < 10; ++nTryCount)
{
{
osl::MutexGuard aGuard(m_aMutex);
if (m_aEntries[nPropIndex].m_eState != Entry::UNKNOWN)
return m_aEntries[nPropIndex].m_aValue;
}
star::uno::Sequence< rtl::OUString > aKeys(ENTRY_COUNT);
int nIndices[ENTRY_COUNT];
sal_Int32 nCount = 0;
{
osl::MutexGuard aGuard(m_aMutex);
for (int i = 0; i < ENTRY_COUNT; ++i)
if (m_aEntries[i].m_eState == Entry::UNKNOWN)
{
aKeys[nCount] = m_aEntries[i].m_aName;
nIndices[nCount] = i;
++nCount;
}
}
if (nCount > 0)
{
aKeys.realloc(nCount);
star::uno::Sequence< star::uno::Any >
aValues(GetProperties(aKeys));
OSL_ENSURE(aValues.getLength() == nCount,
"SvtInetOptions::Impl::getProperty():"
" Bad GetProperties() result");
nCount = std::min(nCount, aValues.getLength());
{
osl::MutexGuard aGuard(m_aMutex);
for (sal_Int32 i = 0; i < nCount; ++i)
{
int nIndex = nIndices[i];
if (m_aEntries[nIndex].m_eState == Entry::UNKNOWN)
{
m_aEntries[nIndices[i]].m_aValue = aValues[i];
m_aEntries[nIndices[i]].m_eState = Entry::KNOWN;
}
}
}
}
}
OSL_ENSURE(false,
"SvtInetOptions::Impl::getProperty(): Possible life lock");
{
osl::MutexGuard aGuard(m_aMutex);
return m_aEntries[nPropIndex].m_aValue;
}
}
//============================================================================
void SvtInetOptions::Impl::setProperty(Index nIndex,
star::uno::Any const & rValue,
bool bFlush)
{
SetModified();
{
osl::MutexGuard aGuard(m_aMutex);
m_aEntries[nIndex].m_aValue = rValue;
m_aEntries[nIndex].m_eState = bFlush ? Entry::KNOWN : Entry::MODIFIED;
}
star::uno::Sequence< rtl::OUString > aKeys(1);
aKeys[0] = m_aEntries[nIndex].m_aName;
if (bFlush)
{
star::uno::Sequence< star::uno::Any > aValues(1);
aValues[0] = rValue;
PutProperties(aKeys, aValues);
}
else
notifyListeners(aKeys);
}
//============================================================================
void
SvtInetOptions::Impl::addPropertiesChangeListener(
star::uno::Sequence< rtl::OUString > const & rPropertyNames,
star::uno::Reference< star::beans::XPropertiesChangeListener > const &
rListener)
{
osl::MutexGuard aGuard(m_aMutex);
Map::mapped_type & rEntry = m_aListeners[rListener];
for (sal_Int32 i = 0; i < rPropertyNames.getLength(); ++i)
rEntry.insert(rPropertyNames[i]);
}
//============================================================================
void
SvtInetOptions::Impl::removePropertiesChangeListener(
star::uno::Sequence< rtl::OUString > const & rPropertyNames,
star::uno::Reference< star::beans::XPropertiesChangeListener > const &
rListener)
{
osl::MutexGuard aGuard(m_aMutex);
Map::iterator aIt(m_aListeners.find(rListener));
if (aIt != m_aListeners.end())
{
for (sal_Int32 i = 0; i < rPropertyNames.getLength(); ++i)
aIt->second.erase(rPropertyNames[i]);
if (aIt->second.empty())
m_aListeners.erase(aIt);
}
}
//============================================================================
//
// SvtInetOptions
//
//============================================================================
namespace
{
class LocalSingleton : public rtl::Static< osl::Mutex, LocalSingleton >
{
};
}
// static
SvtInetOptions::Impl * SvtInetOptions::m_pImpl = 0;
//============================================================================
SvtInetOptions::SvtInetOptions()
{
osl::MutexGuard aGuard(LocalSingleton::get());
if (!m_pImpl)
{
RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtInetOptions_Impl::ctor()");
m_pImpl = new Impl;
ItemHolder1::holdConfigItem(E_INETOPTIONS);
}
m_pImpl->acquire();
}
//============================================================================
SvtInetOptions::~SvtInetOptions()
{
osl::MutexGuard aGuard(LocalSingleton::get());
if (m_pImpl->release() == 0)
m_pImpl = 0;
}
//============================================================================
rtl::OUString SvtInetOptions::GetProxyNoProxy() const
{
return takeAny< rtl::OUString >(m_pImpl->
getProperty(Impl::INDEX_NO_PROXY));
}
//============================================================================
sal_Int32 SvtInetOptions::GetProxyType() const
{
return takeAny< sal_Int32 >(m_pImpl->
getProperty(Impl::INDEX_PROXY_TYPE));
}
//============================================================================
rtl::OUString SvtInetOptions::GetProxyFtpName() const
{
return takeAny< rtl::OUString >(m_pImpl->
getProperty(
Impl::INDEX_FTP_PROXY_NAME));
}
//============================================================================
sal_Int32 SvtInetOptions::GetProxyFtpPort() const
{
return takeAny< sal_Int32 >(m_pImpl->
getProperty(Impl::INDEX_FTP_PROXY_PORT));
}
//============================================================================
rtl::OUString SvtInetOptions::GetProxyHttpName() const
{
return takeAny< rtl::OUString >(m_pImpl->
getProperty(
Impl::INDEX_HTTP_PROXY_NAME));
}
//============================================================================
sal_Int32 SvtInetOptions::GetProxyHttpPort() const
{
return takeAny< sal_Int32 >(m_pImpl->
getProperty(Impl::INDEX_HTTP_PROXY_PORT));
}
//============================================================================
void SvtInetOptions::SetProxyNoProxy(rtl::OUString const & rValue,
bool bFlush)
{
m_pImpl->setProperty(Impl::INDEX_NO_PROXY,
star::uno::makeAny(rValue),
bFlush);
}
//============================================================================
void SvtInetOptions::SetProxyType(ProxyType eValue, bool bFlush)
{
m_pImpl->setProperty(Impl::INDEX_PROXY_TYPE,
star::uno::makeAny(sal_Int32(eValue)),
bFlush);
}
//============================================================================
void SvtInetOptions::SetProxyFtpName(rtl::OUString const & rValue,
bool bFlush)
{
m_pImpl->setProperty(Impl::INDEX_FTP_PROXY_NAME,
star::uno::makeAny(rValue),
bFlush);
}
//============================================================================
void SvtInetOptions::SetProxyFtpPort(sal_Int32 nValue, bool bFlush)
{
m_pImpl->setProperty(Impl::INDEX_FTP_PROXY_PORT,
star::uno::makeAny(nValue),
bFlush);
}
//============================================================================
void SvtInetOptions::SetProxyHttpName(rtl::OUString const & rValue,
bool bFlush)
{
m_pImpl->setProperty(Impl::INDEX_HTTP_PROXY_NAME,
star::uno::makeAny(rValue),
bFlush);
}
//============================================================================
void SvtInetOptions::SetProxyHttpPort(sal_Int32 nValue, bool bFlush)
{
m_pImpl->setProperty(Impl::INDEX_HTTP_PROXY_PORT,
star::uno::makeAny(nValue),
bFlush);
}
//============================================================================
void SvtInetOptions::flush()
{
m_pImpl->flush();
}
//============================================================================
void
SvtInetOptions::addPropertiesChangeListener(
star::uno::Sequence< rtl::OUString > const & rPropertyNames,
star::uno::Reference< star::beans::XPropertiesChangeListener > const &
rListener)
{
m_pImpl->addPropertiesChangeListener(rPropertyNames, rListener);
}
//============================================================================
void
SvtInetOptions::removePropertiesChangeListener(
star::uno::Sequence< rtl::OUString > const & rPropertyNames,
star::uno::Reference< star::beans::XPropertiesChangeListener > const &
rListener)
{
m_pImpl->removePropertiesChangeListener(rPropertyNames, rListener);
}
| 29.935305 | 96 | 0.580858 | [
"vector"
] |
8754b08dced5c548107b328652ff3c63b5ab4bf3 | 3,364 | cc | C++ | LightValidation/PSCalibration/src/DetectorMessenger.cc | murffer/DetectorSim | 1ba114c405eff42c0a52b6dc394cbecfc2d2bab0 | [
"Apache-2.0"
] | 5 | 2018-01-13T22:42:24.000Z | 2021-03-19T07:38:47.000Z | LightValidation/GS20Calibration/src/DetectorMessenger.cc | murffer/DetectorSim | 1ba114c405eff42c0a52b6dc394cbecfc2d2bab0 | [
"Apache-2.0"
] | 1 | 2017-05-03T19:01:12.000Z | 2017-05-03T19:01:12.000Z | LightValidation/GS20Calibration/src/DetectorMessenger.cc | murffer/DetectorSim | 1ba114c405eff42c0a52b6dc394cbecfc2d2bab0 | [
"Apache-2.0"
] | 3 | 2015-10-10T15:12:22.000Z | 2021-10-18T00:53:35.000Z | #include "DetectorMessenger.hh"
#include "DetectorConstruction.hh"
#include "G4UIdirectory.hh"
#include "G4UIcmdWithAString.hh"
#include "G4UIcmdWithAnInteger.hh"
#include "G4UIcmdWithADoubleAndUnit.hh"
#include "G4UIcmdWithADouble.hh"
#include "G4UIcmdWithoutParameter.hh"
DetectorMessenger::DetectorMessenger(
DetectorConstruction* Det)
:Detector(Det)
{
detDir = new G4UIdirectory("/det/");
detDir->SetGuidance("detector control");
AbsThickCmd = new G4UIcmdWithADoubleAndUnit("/det/setDetectorThick",this);
AbsThickCmd->SetGuidance("Set Thickness of the Absorber");
AbsThickCmd->SetParameterName("Size",false);
AbsThickCmd->SetRange("Size>=0.");
AbsThickCmd->SetUnitCategory("Length");
AbsThickCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
RefThickCmd = new G4UIcmdWithADoubleAndUnit("/det/setRefThick",this);
RefThickCmd->SetGuidance("Set Thickness of the Light Reflector (teflon)");
RefThickCmd->SetParameterName("Size",false);
RefThickCmd->SetRange("Size>=0.");
RefThickCmd->SetUnitCategory("Length");
RefThickCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
MntThickCmd = new G4UIcmdWithADoubleAndUnit("/det/setMntThick",this);
MntThickCmd->SetGuidance("Set Thickness of the Mounting (Optical Grease)");
MntThickCmd->SetParameterName("Size",false);
MntThickCmd->SetRange("Size>=0.");
MntThickCmd->SetUnitCategory("Length");
MntThickCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
SizeRadiusCmd = new G4UIcmdWithADoubleAndUnit("/det/setDetectorRadius",this);
SizeRadiusCmd->SetGuidance("Set tranverse size of the calorimeter");
SizeRadiusCmd->SetParameterName("Size",false);
SizeRadiusCmd->SetRange("Size>0.");
SizeRadiusCmd->SetUnitCategory("Length");
SizeRadiusCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
DetMaterialCmd = new G4UIcmdWithAString("/det/setDetectorMaterial",this);
DetMaterialCmd->SetGuidance("Set the detector material");
DetMaterialCmd->SetCandidates("GS20 EJ426 PSLiF G4_PLASTIC_SC_VINYLTOLUENE");
DetMaterialCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
UpdateCmd = new G4UIcmdWithoutParameter("/det/update",this);
UpdateCmd->SetGuidance("Update calorimeter geometry.");
UpdateCmd->SetGuidance("This command MUST be applied before \"beamOn\" ");
UpdateCmd->SetGuidance("if you changed geometrical value(s).");
UpdateCmd->AvailableForStates(G4State_Idle);
}
DetectorMessenger::~DetectorMessenger()
{
delete AbsThickCmd;
delete RefThickCmd;
delete MntThickCmd;
delete SizeRadiusCmd;
delete UpdateCmd;
delete detDir;
delete DetMaterialCmd;
}
void DetectorMessenger::SetNewValue(G4UIcommand* command,G4String newValue)
{
if( command == AbsThickCmd )
{ Detector->SetDetectorThickness(AbsThickCmd->GetNewDoubleValue(newValue));}
if( command == MntThickCmd )
{ Detector->SetMountingThickness(AbsThickCmd->GetNewDoubleValue(newValue));}
if( command == RefThickCmd )
{ Detector->SetReflectorThickness(AbsThickCmd->GetNewDoubleValue(newValue));}
if( command == SizeRadiusCmd )
{ Detector->SetDetectorRadius(SizeRadiusCmd->GetNewDoubleValue(newValue));}
if( command == DetMaterialCmd )
{ Detector->SetDetectorMaterial(newValue);}
if( command == UpdateCmd )
{ Detector->UpdateGeometry(); }
}
| 35.787234 | 80 | 0.754459 | [
"geometry"
] |
875c0f1a197dca811f34bf68ebb4a02092caacfd | 1,093 | cpp | C++ | Train/summer 2017/CF_contest/419 - 430/423/A.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | 1 | 2019-12-19T06:51:20.000Z | 2019-12-19T06:51:20.000Z | Train/summer 2017/CF_contest/419 - 430/423/A.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | Train/summer 2017/CF_contest/419 - 430/423/A.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// input handle
#define in(n) scanf("%d",&n)
#define inf(n) scanf("%lf",&n)
#define inl(n) scanf("%lld",&n)
#define ot(x) printf("%d ", x)
#define ln() printf("\n")
#define otl(x) printf("%lld ", x)
#define otf(x) printf("%.2lf ", x)
// helpers defines
#define all(v) v.begin(), v.end()
#define sz(v) ((int)((v).size()))
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a))
//helpers
void file() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
}
// constants
const int MN = 1e5 + 5;
const int MW = 1e3 + 5;
const int OO = 1e9 + 5;
typedef long long int lli;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef pair<lli, string> lls;
int main() {
file();
int n, a, b, aa = 0, don = 0, x;
lli ans = 0;
in(n), in(a), in(b);
for (int i = 0; i < n and in(x); don = 0, ++i) {
if (x == 2 and b)
don = 1, b--;
else if (x == 1 and a)
don = 1, a--;
else if (x == 1 and !a and b)
don = 1, b--, aa++;
else if (x == 1 and !a and !b and aa)
don = 1, aa--;
if (!don)
ans += x;
}
ot(ans);
return 0;
}
| 21.431373 | 49 | 0.561757 | [
"vector"
] |
87636b813497ae6b0ca953abbfd383e8439dd752 | 27,697 | cpp | C++ | emulator/src/lib/formats/cassimg.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/lib/formats/cassimg.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/lib/formats/cassimg.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Nathan Woods
/*********************************************************************
cassimg.cpp
Cassette tape image abstraction code
*********************************************************************/
#include <string.h>
#include <assert.h>
#include "imageutl.h"
#include "cassimg.h"
#include <algorithm>
/* debugging parameters */
#define LOG_PUT_SAMPLES 0
#define DUMP_CASSETTES 0
#define SAMPLES_PER_BLOCK 0x40000
#define CASSETTE_FLAG_DIRTY 0x10000
CASSETTE_FORMATLIST_START(cassette_default_formats)
CASSETTE_FORMATLIST_END
/*********************************************************************
helper code
*********************************************************************/
static double map_double(double d, uint64_t low, uint64_t high, uint64_t value)
{
return d * (value - low) / (high - low);
}
static size_t waveform_bytes_per_sample(int waveform_flags)
{
return (size_t) (1 << ((waveform_flags & 0x06) / 2));
}
/*********************************************************************
extrapolation and interpolation
*********************************************************************/
static int32_t extrapolate8(int8_t value)
{
return ((int32_t) value) << 24;
}
static int32_t extrapolate16(int16_t value)
{
return ((int32_t) value) << 16;
}
static int8_t interpolate8(int32_t value)
{
return (int8_t) (value >> 24);
}
static int16_t interpolate16(int32_t value)
{
return (int16_t) (value >> 16);
}
/*********************************************************************
initialization and termination
*********************************************************************/
static cassette_image *cassette_init(const struct CassetteFormat *format, void *file, const struct io_procs *procs, int flags)
{
cassette_image *cassette;
cassette = global_alloc_clear<cassette_image>();
cassette->format = format;
cassette->io.file = file;
cassette->io.procs = procs;
cassette->flags = flags;
return cassette;
}
static void cassette_finishinit(cassette_image::error err, cassette_image *cassette, cassette_image **outcassette)
{
if (cassette && ((err != cassette_image::error::SUCCESS) || !outcassette))
{
cassette_close(cassette);
cassette = nullptr;
}
if (outcassette)
*outcassette = cassette;
}
static cassette_image::error try_identify_format(const struct CassetteFormat &format, cassette_image *image, const std::string &extension, int flags, struct CassetteOptions &opts)
{
// is this the right extension?
if (!extension.empty() && !image_find_extension(format.extensions, extension.c_str()))
return cassette_image::error::INVALID_IMAGE;
// invoke format->identify
memset(&opts, 0, sizeof(opts));
cassette_image::error err = format.identify(image, &opts);
if (err != cassette_image::error::SUCCESS)
return err;
// is this a read only format, but the cassette was not opened read only?
if (((flags & CASSETTE_FLAG_READONLY) == 0) && (format.save == nullptr))
return cassette_image::error::READ_WRITE_UNSUPPORTED;
// success!
return cassette_image::error::SUCCESS;
}
cassette_image::error cassette_open_choices(void *file, const struct io_procs *procs, const std::string &extension,
const struct CassetteFormat *const *formats, int flags, cassette_image **outcassette)
{
cassette_image::error err;
cassette_image *cassette;
const struct CassetteFormat *format;
struct CassetteOptions opts = {0, };
int i;
/* if not specified, use the dummy arguments */
if (!formats)
formats = cassette_default_formats;
/* create the cassette object */
cassette = cassette_init(nullptr, file, procs, flags);
if (!cassette)
{
err = cassette_image::error::OUT_OF_MEMORY;
goto done;
}
/* identify the image */
format = nullptr;
for (i = 0; !format && formats[i]; i++)
{
// try this format
err = try_identify_format(*formats[i], cassette, extension, flags, opts);
if (err != cassette_image::error::SUCCESS && err != cassette_image::error::INVALID_IMAGE)
goto done;
// did we succeed?
if (err == cassette_image::error::SUCCESS)
format = formats[i];
}
/* have we found a proper format */
if (!format)
{
err = cassette_image::error::INVALID_IMAGE;
goto done;
}
cassette->format = format;
/* read the options */
cassette->channels = opts.channels;
cassette->sample_frequency = opts.sample_frequency;
/* load the image */
err = format->load(cassette);
if (err != cassette_image::error::SUCCESS)
goto done;
/* success */
cassette->flags &= ~CASSETTE_FLAG_DIRTY;
err = cassette_image::error::SUCCESS;
done:
cassette_finishinit(err, cassette, outcassette);
return err;
}
cassette_image::error cassette_open(void *file, const struct io_procs *procs,
const struct CassetteFormat *format, int flags, cassette_image **outcassette)
{
const struct CassetteFormat *formats[2];
formats[0] = format;
formats[1] = nullptr;
return cassette_open_choices(file, procs, nullptr, formats, flags, outcassette);
}
cassette_image::error cassette_create(void *file, const struct io_procs *procs, const struct CassetteFormat *format,
const struct CassetteOptions *opts, int flags, cassette_image **outcassette)
{
cassette_image::error err;
cassette_image *cassette;
static const struct CassetteOptions default_options = { 1, 16, 44100 };
/* cannot create to a read only image */
if (flags & CASSETTE_FLAG_READONLY)
return cassette_image::error::INVALID_IMAGE;
/* is this a good format? */
if (format->save == nullptr)
return cassette_image::error::INVALID_IMAGE;
/* normalize arguments */
if (!opts)
opts = &default_options;
/* create the cassette object */
cassette = cassette_init(format, file, procs, flags);
if (!cassette)
{
err = cassette_image::error::OUT_OF_MEMORY;
goto done;
}
/* read the options */
cassette->channels = opts->channels;
cassette->sample_frequency = opts->sample_frequency;
err = cassette_image::error::SUCCESS;
done:
cassette_finishinit(err, cassette, outcassette);
return err;
}
static cassette_image::error cassette_perform_save(cassette_image *cassette)
{
struct CassetteInfo info;
cassette_get_info(cassette, &info);
return cassette->format->save(cassette, &info);
}
cassette_image::error cassette_save(cassette_image *cassette)
{
cassette_image::error err;
if (!cassette->format || !cassette->format->save)
return cassette_image::error::UNSUPPORTED;
err = cassette_perform_save(cassette);
if (err != cassette_image::error::SUCCESS)
return err;
cassette->flags &= ~CASSETTE_FLAG_DIRTY;
return cassette_image::error::SUCCESS;
}
void cassette_get_info(cassette_image *cassette, struct CassetteInfo *info)
{
memset(info, 0, sizeof(*info));
info->channels = cassette->channels;
info->sample_count = cassette->sample_count;
info->sample_frequency = cassette->sample_frequency;
info->bits_per_sample = (int) waveform_bytes_per_sample(cassette->flags) * 8;
}
void cassette_close(cassette_image *cassette)
{
if (cassette)
{
if ((cassette->flags & CASSETTE_FLAG_DIRTY) && (cassette->flags & CASSETTE_FLAG_SAVEONEXIT))
cassette_save(cassette);
for (auto & elem : cassette->blocks)
{
global_free(elem);
}
global_free(cassette);
}
}
void cassette_change(cassette_image *cassette, void *file, const struct io_procs *procs, const struct CassetteFormat *format, int flags)
{
if ((flags & CASSETTE_FLAG_READONLY) == 0)
flags |= CASSETTE_FLAG_DIRTY;
cassette->io.file = file;
cassette->io.procs = procs;
cassette->format = format;
cassette->flags = flags;
}
/*********************************************************************
calls for accessing the raw cassette image
*********************************************************************/
void cassette_image_read(cassette_image *cassette, void *buffer, uint64_t offset, size_t length)
{
io_generic_read(&cassette->io, buffer, offset, length);
}
void cassette_image_write(cassette_image *cassette, const void *buffer, uint64_t offset, size_t length)
{
io_generic_write(&cassette->io, buffer, offset, length);
}
uint64_t cassette_image_size(cassette_image *cassette)
{
return io_generic_size(&cassette->io);
}
/*********************************************************************
waveform accesses
*********************************************************************/
struct manipulation_ranges
{
int channel_first;
int channel_last;
size_t sample_first;
size_t sample_last;
};
static size_t my_round(double d)
{
size_t result;
d += 0.5;
result = (size_t) d;
return result;
}
static cassette_image::error compute_manipulation_ranges(cassette_image *cassette, int channel,
double time_index, double sample_period, struct manipulation_ranges *ranges)
{
if (channel < 0)
{
ranges->channel_first = 0;
ranges->channel_last = cassette->channels - 1;
}
else
{
ranges->channel_first = channel;
ranges->channel_last = channel;
}
ranges->sample_first = my_round(time_index * cassette->sample_frequency);
ranges->sample_last = my_round((time_index + sample_period) * cassette->sample_frequency);
if (ranges->sample_last > ranges->sample_first)
ranges->sample_last--;
return cassette_image::error::SUCCESS;
}
static cassette_image::error lookup_sample(cassette_image *cassette, int channel, size_t sample, int32_t **ptr)
{
*ptr = nullptr;
size_t sample_blocknum = (sample / SAMPLES_PER_BLOCK) * cassette->channels + channel;
size_t sample_index = sample % SAMPLES_PER_BLOCK;
/* is this block beyond the edge of our waveform? */
if (sample_blocknum >= cassette->blocks.size()) {
size_t osize = cassette->blocks.size();
cassette->blocks.resize(sample_blocknum + 1);
memset(&cassette->blocks[osize], 0, (cassette->blocks.size()-osize)*sizeof(cassette->blocks[0]));
}
if (cassette->blocks[sample_blocknum] == nullptr)
cassette->blocks[sample_blocknum] = global_alloc(sample_block);
sample_block &block = *cassette->blocks[sample_blocknum];
/* is this sample access off the current block? */
if (sample_index >= block.size()) {
size_t osize = block.size();
block.resize(SAMPLES_PER_BLOCK);
memset(&block[osize], 0, (SAMPLES_PER_BLOCK-osize)*sizeof(block[0]));
}
*ptr = &block[sample_index];
return cassette_image::error::SUCCESS;
}
/*********************************************************************
waveform accesses
*********************************************************************/
cassette_image::error cassette_get_samples(cassette_image *cassette, int channel,
double time_index, double sample_period, size_t sample_count, size_t sample_bytes,
void *samples, int waveform_flags)
{
cassette_image::error err;
struct manipulation_ranges ranges;
size_t sample_index;
size_t cassette_sample_index;
uint8_t *dest_ptr;
const int32_t *source_ptr;
double d;
int16_t word;
int32_t dword;
int64_t sum;
assert(cassette);
err = compute_manipulation_ranges(cassette, channel, time_index, sample_period, &ranges);
if (err != cassette_image::error::SUCCESS)
return err;
for (sample_index = 0; sample_index < sample_count; sample_index++)
{
sum = 0;
for (channel = ranges.channel_first; channel <= ranges.channel_last; channel++)
{
/* find the sample that we are putting */
d = map_double(ranges.sample_last + 1 - ranges.sample_first, 0, sample_count, sample_index) + ranges.sample_first;
cassette_sample_index = (size_t) d;
err = lookup_sample(cassette, channel, cassette_sample_index, (int32_t **) &source_ptr);
if (err != cassette_image::error::SUCCESS)
return err;
sum += *source_ptr;
}
/* average out the samples */
sum /= (ranges.channel_last + 1 - ranges.channel_first);
/* and write out the result */
dest_ptr = (uint8_t*)samples;
dest_ptr += waveform_bytes_per_sample(waveform_flags) * sample_index * cassette->channels;
switch(waveform_bytes_per_sample(waveform_flags))
{
case 1:
*((int8_t *) dest_ptr) = interpolate8(sum);
break;
case 2:
word = interpolate16(sum);
if (waveform_flags & CASSETTE_WAVEFORM_ENDIAN_FLIP)
word = flipendian_int16(word);
*((int16_t *) dest_ptr) = word;
break;
case 4:
dword = sum;
if (waveform_flags & CASSETTE_WAVEFORM_ENDIAN_FLIP)
dword = flipendian_int32(dword);
*((int32_t *) dest_ptr) = dword;
break;
}
}
return cassette_image::error::SUCCESS;
}
cassette_image::error cassette_put_samples(cassette_image *cassette, int channel,
double time_index, double sample_period, size_t sample_count, size_t sample_bytes,
const void *samples, int waveform_flags)
{
cassette_image::error err;
struct manipulation_ranges ranges;
size_t sample_index;
int32_t *dest_ptr;
int32_t dest_value;
int16_t word;
int32_t dword;
const uint8_t *source_ptr;
double d;
if (!cassette)
return cassette_image::error::SUCCESS;
if (sample_period == 0)
return cassette_image::error::SUCCESS;
err = compute_manipulation_ranges(cassette, channel, time_index, sample_period, &ranges);
if (err != cassette_image::error::SUCCESS)
return err;
if (cassette->sample_count < ranges.sample_last+1)
cassette->sample_count = ranges.sample_last + 1;
cassette->flags |= CASSETTE_FLAG_DIRTY;
if (LOG_PUT_SAMPLES)
{
LOG_FORMATS("cassette_put_samples(): Putting samples TIME=[%2.6g..%2.6g] INDEX=[%i..%i]\n",
time_index, time_index + sample_period,
(int)ranges.sample_first, (int)ranges.sample_last);
}
for (sample_index = ranges.sample_first; sample_index <= ranges.sample_last; sample_index++)
{
/* figure out the source pointer */
d = map_double(sample_count, ranges.sample_first, ranges.sample_last + 1, sample_index);
source_ptr = (const uint8_t*)samples;
source_ptr += ((size_t) d) * sample_bytes;
/* compute the value that we are writing */
switch(waveform_bytes_per_sample(waveform_flags)) {
case 1:
if (waveform_flags & CASSETTE_WAVEFORM_UNSIGNED)
dest_value = extrapolate8((int8_t)(*source_ptr - 128));
else
dest_value = extrapolate8(*((int8_t *) source_ptr));
break;
case 2:
word = *((int16_t *) source_ptr);
if (waveform_flags & CASSETTE_WAVEFORM_ENDIAN_FLIP)
word = flipendian_int16(word);
dest_value = extrapolate16(word);
break;
case 4:
dword = *((int32_t *) source_ptr);
if (waveform_flags & CASSETTE_WAVEFORM_ENDIAN_FLIP)
dword = flipendian_int32(dword);
dest_value = dword;
break;
default:
return cassette_image::error::INTERNAL;
}
for (channel = ranges.channel_first; channel <= ranges.channel_last; channel++)
{
/* find the sample that we are putting */
err = lookup_sample(cassette, channel, sample_index, &dest_ptr);
if (err != cassette_image::error::SUCCESS)
return err;
*dest_ptr = dest_value;
}
}
return cassette_image::error::SUCCESS;
}
cassette_image::error cassette_get_sample(cassette_image *cassette, int channel,
double time_index, double sample_period, int32_t *sample)
{
return cassette_get_samples(cassette, channel, time_index,
sample_period, 1, 0, sample, CASSETTE_WAVEFORM_32BIT);
}
cassette_image::error cassette_put_sample(cassette_image *cassette, int channel,
double time_index, double sample_period, int32_t sample)
{
return cassette_put_samples(cassette, channel, time_index,
sample_period, 1, 0, &sample, CASSETTE_WAVEFORM_32BIT);
}
/*********************************************************************
waveform accesses to/from the raw image
*********************************************************************/
cassette_image::error cassette_read_samples(cassette_image *cassette, int channels, double time_index,
double sample_period, size_t sample_count, uint64_t offset, int waveform_flags)
{
cassette_image::error err;
size_t chunk_sample_count;
size_t bytes_per_sample;
size_t sample_bytes;
size_t samples_loaded = 0;
double chunk_time_index;
double chunk_sample_period;
int channel;
uint8_t buffer[8192];
bytes_per_sample = waveform_bytes_per_sample(waveform_flags);
sample_bytes = bytes_per_sample * channels;
while(samples_loaded < sample_count)
{
chunk_sample_count = std::min(sizeof(buffer) / sample_bytes, (sample_count - samples_loaded));
chunk_sample_period = map_double(sample_period, 0, sample_count, chunk_sample_count);
chunk_time_index = time_index + map_double(sample_period, 0, sample_count, samples_loaded);
cassette_image_read(cassette, buffer, offset, chunk_sample_count * sample_bytes);
for (channel = 0; channel < channels; channel++)
{
err = cassette_put_samples(cassette, channel, chunk_time_index, chunk_sample_period,
chunk_sample_count, sample_bytes, &buffer[channel * bytes_per_sample], waveform_flags);
if (err != cassette_image::error::SUCCESS)
return err;
}
offset += chunk_sample_count * sample_bytes;
samples_loaded += chunk_sample_count;
}
return cassette_image::error::SUCCESS;
}
cassette_image::error cassette_write_samples(cassette_image *cassette, int channels, double time_index,
double sample_period, size_t sample_count, uint64_t offset, int waveform_flags)
{
cassette_image::error err;
size_t chunk_sample_count;
size_t bytes_per_sample;
size_t sample_bytes;
size_t samples_saved = 0;
double chunk_time_index;
double chunk_sample_period;
int channel;
uint8_t buffer[8192];
bytes_per_sample = waveform_bytes_per_sample(waveform_flags);
sample_bytes = bytes_per_sample * channels;
while(samples_saved < sample_count)
{
chunk_sample_count = std::min(sizeof(buffer) / sample_bytes, (sample_count - samples_saved));
chunk_sample_period = map_double(sample_period, 0, sample_count, chunk_sample_count);
chunk_time_index = time_index + map_double(sample_period, 0, sample_count, samples_saved);
for (channel = 0; channel < channels; channel++)
{
err = cassette_get_samples(cassette, channel, chunk_time_index, chunk_sample_period,
chunk_sample_count, sample_bytes, &buffer[channel * bytes_per_sample], waveform_flags);
if (err != cassette_image::error::SUCCESS)
return err;
}
cassette_image_write(cassette, buffer, offset, chunk_sample_count * sample_bytes);
offset += chunk_sample_count * sample_bytes;
samples_saved += chunk_sample_count;
}
return cassette_image::error::SUCCESS;
}
/*********************************************************************
waveform accesses to/from the raw image
*********************************************************************/
static const int8_t *choose_wave(const struct CassetteModulation *modulation, size_t *wave_bytes_length)
{
static const int8_t square_wave[] = { -128, 127 };
static const int8_t sine_wave[] = { 0, 48, 89, 117, 127, 117, 89, 48, 0, -48, -89, -117, -127, -117, -89, -48 };
if (modulation->flags & CASSETTE_MODULATION_SINEWAVE)
{
*wave_bytes_length = ARRAY_LENGTH(sine_wave);
return sine_wave;
}
else
{
*wave_bytes_length = ARRAY_LENGTH(square_wave);
return square_wave;
}
}
cassette_image::error cassette_modulation_identify(cassette_image *cassette, const struct CassetteModulation *modulation,
struct CassetteOptions *opts)
{
size_t wave_bytes_length;
choose_wave(modulation, &wave_bytes_length);
opts->bits_per_sample = 8;
opts->channels = 1;
opts->sample_frequency = (uint32_t) (std::max(modulation->zero_frequency_high, modulation->one_frequency_high) * wave_bytes_length * 2);
return cassette_image::error::SUCCESS;
}
cassette_image::error cassette_put_modulated_data(cassette_image *cassette, int channel, double time_index,
const void *data, size_t data_length, const struct CassetteModulation *modulation,
double *time_displacement)
{
cassette_image::error err;
const uint8_t *data_bytes = (const uint8_t *)data;
const int8_t *wave_bytes;
size_t wave_bytes_length;
double total_displacement = 0.0;
double pulse_period;
double pulse_frequency;
uint8_t b;
int i;
wave_bytes = choose_wave(modulation, &wave_bytes_length);
while(data_length--)
{
b = *(data_bytes++);
for (i = 0; i < 8; i++)
{
pulse_frequency = (b & (1 << i)) ? modulation->one_frequency_cannonical : modulation->zero_frequency_cannonical;
pulse_period = 1 / pulse_frequency;
err = cassette_put_samples(cassette, 0, time_index, pulse_period, wave_bytes_length, 1, wave_bytes, CASSETTE_WAVEFORM_8BIT);
if (err != cassette_image::error::SUCCESS)
goto done;
time_index += pulse_period;
total_displacement += pulse_period;
}
}
err = cassette_image::error::SUCCESS;
done:
if (time_displacement)
*time_displacement = total_displacement;
return err;
}
cassette_image::error cassette_put_modulated_filler(cassette_image *cassette, int channel, double time_index,
uint8_t filler, size_t filler_length, const struct CassetteModulation *modulation,
double *time_displacement)
{
cassette_image::error err;
double delta;
double total_displacement = 0.0;
while(filler_length--)
{
err = cassette_put_modulated_data(cassette, channel, time_index, &filler, 1, modulation, &delta);
if (err != cassette_image::error::SUCCESS)
return err;
total_displacement += delta;
time_index += delta;
}
if (time_displacement)
*time_displacement = total_displacement;
return cassette_image::error::SUCCESS;
}
cassette_image::error cassette_read_modulated_data(cassette_image *cassette, int channel, double time_index,
uint64_t offset, uint64_t length, const struct CassetteModulation *modulation,
double *time_displacement)
{
cassette_image::error err;
uint8_t buffer_stack[1024];
uint8_t *buffer;
uint8_t *alloc_buffer = nullptr;
double delta;
double total_displacement = 0.0;
size_t this_length;
size_t buffer_length;
if (length <= sizeof(buffer_stack))
{
buffer = buffer_stack;
buffer_length = sizeof(buffer_stack);
}
else
{
buffer_length = std::min<uint64_t>(length, 100000);
alloc_buffer = (uint8_t*)malloc(buffer_length);
if (!alloc_buffer)
{
err = cassette_image::error::OUT_OF_MEMORY;
goto done;
}
buffer = alloc_buffer;
}
while(length > 0)
{
this_length = (std::min<uint64_t>)(length, buffer_length);
cassette_image_read(cassette, buffer, offset, this_length);
err = cassette_put_modulated_data(cassette, channel, time_index, buffer, this_length, modulation, &delta);
if (err != cassette_image::error::SUCCESS)
goto done;
total_displacement += delta;
time_index += delta;
length -= this_length;
}
if (time_displacement)
*time_displacement = total_displacement;
err = cassette_image::error::SUCCESS;
done:
if (alloc_buffer)
free(alloc_buffer);
return err;
}
cassette_image::error cassette_put_modulated_data_bit(cassette_image *cassette, int channel, double time_index,
uint8_t data, const struct CassetteModulation *modulation,
double *time_displacement)
{
cassette_image::error err;
const int8_t *wave_bytes;
size_t wave_bytes_length;
double total_displacement = 0.0;
double pulse_period;
double pulse_frequency;
wave_bytes = choose_wave(modulation, &wave_bytes_length);
pulse_frequency = (data) ? modulation->one_frequency_cannonical : modulation->zero_frequency_cannonical;
pulse_period = 1 / pulse_frequency;
err = cassette_put_samples(cassette, 0, time_index, pulse_period, wave_bytes_length, 1, wave_bytes, CASSETTE_WAVEFORM_8BIT);
if (err != cassette_image::error::SUCCESS)
goto done;
time_index += pulse_period;
total_displacement += pulse_period;
err = cassette_image::error::SUCCESS;
done:
if (time_displacement)
*time_displacement = total_displacement;
return err;
}
/*********************************************************************
waveform accesses to/from the raw image
*********************************************************************/
cassette_image::error cassette_legacy_identify(cassette_image *cassette, struct CassetteOptions *opts,
const struct CassetteLegacyWaveFiller *legacy_args)
{
opts->channels = 1;
opts->bits_per_sample = 16;
opts->sample_frequency = legacy_args->sample_frequency;
return cassette_image::error::SUCCESS;
}
cassette_image::error cassette_legacy_construct(cassette_image *cassette,
const struct CassetteLegacyWaveFiller *legacy_args)
{
cassette_image::error err;
int length;
int sample_count;
std::vector<uint8_t> bytes;
std::vector<uint8_t> chunk;
std::vector<int16_t> samples;
int pos = 0;
uint64_t offset = 0;
uint64_t size;
struct CassetteLegacyWaveFiller args;
/* sanity check the args */
assert(legacy_args->header_samples >= -1);
assert(legacy_args->trailer_samples >= 0);
assert(legacy_args->fill_wave);
size = cassette_image_size(cassette);
/* normalize the args */
args = *legacy_args;
if (args.chunk_size == 0)
args.chunk_size = 1;
else if (args.chunk_size < 0)
args.chunk_size = cassette_image_size(cassette);
if (args.sample_frequency == 0)
args.sample_frequency = 11025;
/* allocate a buffer for the binary data */
chunk.resize(args.chunk_size);
/* determine number of samples */
if (args.chunk_sample_calc != nullptr)
{
if (size > 0x7FFFFFFF)
{
err = cassette_image::error::OUT_OF_MEMORY;
goto done;
}
bytes.resize(size);
cassette_image_read(cassette, &bytes[0], 0, size);
sample_count = args.chunk_sample_calc(&bytes[0], (int)size);
// chunk_sample_calc functions report errors by returning negative numbers
if (sample_count < 0)
{
err = cassette_image::error::INVALID_IMAGE;
goto done;
}
if (args.header_samples < 0)
args.header_samples = sample_count;
}
else
{
sample_count = ((size + args.chunk_size - 1) / args.chunk_size)
* args.chunk_samples;
}
sample_count += args.header_samples + args.trailer_samples;
/* allocate a buffer for the completed samples */
samples.resize(sample_count);
/* if there has to be a header */
if (args.header_samples > 0)
{
length = args.fill_wave(&samples[pos], sample_count - pos, CODE_HEADER);
if (length < 0)
{
err = cassette_image::error::INVALID_IMAGE;
goto done;
}
pos += length;
}
/* convert the file data to samples */
while((pos < sample_count) && (offset < size))
{
cassette_image_read(cassette, &chunk[0], offset, args.chunk_size);
offset += args.chunk_size;
length = args.fill_wave(&samples[pos], sample_count - pos, &chunk[0]);
if (length < 0)
{
err = cassette_image::error::INVALID_IMAGE;
goto done;
}
pos += length;
if (length == 0)
break;
}
/* if there has to be a trailer */
if (args.trailer_samples > 0)
{
length = args.fill_wave(&samples[pos], sample_count - pos, CODE_TRAILER);
if (length < 0)
{
err = cassette_image::error::INVALID_IMAGE;
goto done;
}
pos += length;
}
/* specify the wave */
err = cassette_put_samples(cassette, 0, 0.0, ((double) pos) / args.sample_frequency,
pos, 2, &samples[0], CASSETTE_WAVEFORM_16BIT);
if (err != cassette_image::error::SUCCESS)
goto done;
/* success! */
err = cassette_image::error::SUCCESS;
#if DUMP_CASSETTES
cassette_dump(cassette, "C:\\TEMP\\CASDUMP.WAV");
#endif
done:
return err;
}
/*********************************************************************
cassette_dump
A debugging call to dump a cassette image to a disk based wave file
*********************************************************************/
void cassette_dump(cassette_image *image, const char *filename)
{
FILE *f;
struct io_generic saved_io;
const struct CassetteFormat *saved_format;
f = fopen(filename, "wb");
if (!f)
return;
memcpy(&saved_io, &image->io, sizeof(saved_io));
saved_format = image->format;
image->io.file = f;
image->io.procs = &stdio_ioprocs_noclose;
image->format = &wavfile_format;
cassette_perform_save(image);
memcpy(&image->io, &saved_io, sizeof(saved_io));
image->format = saved_format;
fclose(f);
}
| 27.100783 | 179 | 0.696249 | [
"object",
"vector"
] |
8771fa52dc11b52a136e7a38c96bff2880915d6f | 2,817 | cpp | C++ | MultiStream/ImageStream.cpp | H7272/MultiStream2 | a81c8bf68184279f848d6a115b259946e673bec8 | [
"Apache-2.0"
] | null | null | null | MultiStream/ImageStream.cpp | H7272/MultiStream2 | a81c8bf68184279f848d6a115b259946e673bec8 | [
"Apache-2.0"
] | null | null | null | MultiStream/ImageStream.cpp | H7272/MultiStream2 | a81c8bf68184279f848d6a115b259946e673bec8 | [
"Apache-2.0"
] | null | null | null | #include "ImageStream.h"
#pragma comment(lib, "Ws2_32.lib")
using namespace cv;
/**
* @VideoStream .
* @brief:Image Captur And Send to Client.
*/
void* ImageStream::VideoStream(void* arg)
{
// Initialize Winsock
WSADATA wsaData;
if (0 != WSAStartup(MAKEWORD(2, 2), &wsaData)) {
return 0;
}
// SetData.
struct TransfarDoc* TransfarDoc = (struct TransfarDoc*)arg;
ClientBuffer* pClientBuffer = TransfarDoc->pClientBuffer;
SOCKET* pListenSocket = TransfarDoc->pListenSocket;
int JPGQuality = TransfarDoc->JPGQuality;
const int DataBufferSize = TransfarDoc->DataBufferSize;
const int CameraPort = TransfarDoc->CameraPort;
const double CameraWidth = TransfarDoc->CameraWidth;
const double CameraHight = TransfarDoc->CameraHight;
const double CameraFPS = TransfarDoc->CameraFPS;
while (1) {
// If Client 0 Then Wait Continue.
if (0 == pClientBuffer->IsSize()) {
Sleep(1);
continue;
}
// Connect Camera.
cv::VideoCapture captre(CameraPort, CAP_DSHOW);
if (!captre.isOpened()) {
printf("StreamTH:open camera failed \n");
continue;
}
// Setting GetImage Info.
cv::Mat frame;
captre.set(CAP_PROP_FRAME_WIDTH, CameraWidth);
captre.set(CAP_PROP_FRAME_HEIGHT, CameraHight);
captre.set(CAP_PROP_FPS, CameraFPS);
// Setting Encode Data Info.
std::vector<int> param = std::vector<int>(2);
param[0] = cv::IMWRITE_JPEG_QUALITY;
param[1] = JPGQuality;
std::vector<unsigned char> ibuff;
// Create ImageData.
char* sendbuf = NULL;
sendbuf = new char[DataBufferSize]();
// StratStreaming.
while (0 != pClientBuffer->IsSize()) {
memset(sendbuf, 0, DataBufferSize);
ibuff.clear();
ibuff.resize(DataBufferSize);
// Captre Image.
captre >> frame;
imencode(".jpg", frame, ibuff, param);
// Check ibuff Size.
if (ibuff.size() >= DataBufferSize) {
printf("StreamTH: Image Size Over!!! %d \n", (int)ibuff.size());
break;
}
// Image to SendBuffer.
int pos = 0;
for (unsigned char i : ibuff) { sendbuf[pos++] = i; }
//Send Imag Buffer.
pClientBuffer->SendImage(pListenSocket, sendbuf, DataBufferSize);
}
// Disconnect Process.
printf("StreamTH:CloseCaptre \n");
ibuff.shrink_to_fit();
captre.release();
pClientBuffer->DeleteAllClient();
printf("StreamTH:Wait Next Connect...%d :\n", (int)pClientBuffer->IsSize());
}
return 0;
} | 33.535714 | 84 | 0.57295 | [
"vector"
] |
87786b521dd7acff841f6d5bdbc24ab89f97a09d | 3,237 | cpp | C++ | src/game/sys/sound/sound_comp.cpp | lowkey42/MagnumOpus | 87897b16192323b40064119402c74e014a48caf3 | [
"MIT"
] | 5 | 2020-03-13T23:16:33.000Z | 2022-03-20T19:16:46.000Z | src/game/sys/sound/sound_comp.cpp | lowkey42/MagnumOpus | 87897b16192323b40064119402c74e014a48caf3 | [
"MIT"
] | 24 | 2015-04-20T20:26:23.000Z | 2015-11-20T22:39:38.000Z | src/game/sys/sound/sound_comp.cpp | lowkey42/medienprojekt | 87897b16192323b40064119402c74e014a48caf3 | [
"MIT"
] | 1 | 2022-03-08T03:11:21.000Z | 2022-03-08T03:11:21.000Z | #include "sound_comp.hpp"
#include <unordered_map>
#include <core/audio/sound.hpp>
#include <game/sys/state/state_comp.hpp>
#include <sf2/sf2.hpp>
#include <string>
namespace mo {
namespace sys {
namespace sound {
struct Sound_entry{
std::string sound_name;
audio::Sound_ptr ptr;
};
struct Sounds_map{
std::unordered_map<sys::state::Entity_state, Sound_entry> sounds;
};
Sound_comp_data::Sound_comp_data(std::unique_ptr<Sounds_map> data, std::vector<audio::Sound_ptr> ptrs){
_data = std::move(data);
_loaded_sounds = std::move(ptrs);
}
Sound_comp_data::~Sound_comp_data() = default;
Sound_comp_data& Sound_comp_data::operator=(Sound_comp_data&& rhs) noexcept {
_data = std::move(rhs._data);
_loaded_sounds = std::move(rhs._loaded_sounds);
return *this;
}
}
namespace state {
sf2_enumDef(sys::state::Entity_state,
idle,
walking,
attacking_melee,
attacking_range,
interacting,
taking,
change_weapon,
damaged,
healed,
dying,
dead,
resurrected
)
}
namespace sound {
sf2_structDef(Sound_entry,
sound_name
)
sf2_structDef(Sounds_map,
sounds
)
sf2_structDef(Sound_comp_data,
_data
)
void Sound_comp::load(sf2::JsonDeserializer& state,
asset::Asset_manager& asset_mgr){
auto aid = _sc_data ? _sc_data.aid().str() : std::string{};
state.read_virtual(
sf2::vmember("aid", aid)
);
_sc_data = asset_mgr.load<Sound_comp_data>(asset::AID(aid));
}
void Sound_comp::save(sf2::JsonSerializer& state)const {
auto aid = _sc_data ? _sc_data.aid().str() : std::string{};
state.write_virtual(
sf2::vmember("aid", aid)
);
}
std::shared_ptr<const audio::Sound> Sound_comp::get_sound(int pos) const noexcept {
std::shared_ptr<const audio::Sound> ret;
audio::Sound_ptr ptr = _sc_data->_loaded_sounds.at(pos);
if(!_sc_data->_loaded_sounds.at(pos)){
return {};
}
ret = std::shared_ptr<const audio::Sound> (ptr);
return ret;
}
}
}
namespace asset {
std::shared_ptr<sys::sound::Sound_comp_data> Loader<sys::sound::Sound_comp_data>::load(istream in) {
auto r = std::make_unique<sys::sound::Sounds_map>();
sf2::deserialize_json(in, [&](auto& msg, uint32_t row, uint32_t column) {
ERROR("Error parsing JSON from "<<in.aid().str()<<" at "<<row<<":"<<column<<": "<<msg);
}, *r);
// TODO [Sebastian]: automatic calculation of enum-class ending
using estate = sys::state::Entity_state;
int end = static_cast<int>(estate::resurrected);
std::vector<audio::Sound_ptr> ptrs(end, audio::Sound_ptr());
for(int i = 0; i <= end; i++){
auto cur_iter = r->sounds.find(estate(i));
// if entry for entity_state(i) is given in config-file -> map it into the corresponding array position
if(cur_iter != r->sounds.end()){
cur_iter->second.ptr = in.manager().load<audio::Sound>(cur_iter->second.sound_name);
ptrs.at(i) = cur_iter->second.ptr;
}
}
// Generating new Sound-Shared-Ptr and set _sc_data-ptr to what r pointed to
auto sc_data = std::make_shared<sys::sound::Sound_comp_data>(std::move(r), std::move(ptrs));
return sc_data;
}
void Loader<sys::sound::Sound_comp_data>::store(ostream out, const sys::sound::Sound_comp_data& asset) {
sf2::serialize_json(out, asset);
}
}
}
| 23.627737 | 106 | 0.688601 | [
"vector"
] |
8780dbdbec46b695dc71fd0f8755eb000cc9da81 | 4,398 | cpp | C++ | Engine/Source/Core/Engine.cpp | TzuChieh/XenoGameEngine | 69d7524ee05491c8e6f8c45fdb6a12bfcecb4731 | [
"MIT"
] | 4 | 2016-09-04T12:58:44.000Z | 2020-11-11T15:48:41.000Z | Engine/Source/Core/Engine.cpp | TzuChieh/VirtualGameEngine | 69d7524ee05491c8e6f8c45fdb6a12bfcecb4731 | [
"MIT"
] | 1 | 2016-07-16T15:46:32.000Z | 2016-08-05T11:01:16.000Z | Engine/Source/Core/Engine.cpp | TzuChieh/VirtualGameEngine | 69d7524ee05491c8e6f8c45fdb6a12bfcecb4731 | [
"MIT"
] | null | null | null | #include "Engine.h"
#include "Common/type.h"
#include "Common/ThirdPartyLib/glew.h"
#include "Game/GameProgram.h"
#include "Render/Renderer.h"
#include "Physics/PhysicsEngine.h"
#include "Input.h"
#include "Platform.h"
#include "Timer.h"
#include "Core/EngineProxy.h"
#include <iostream>
DEFINE_LOG_SENDER(Engine);
using namespace ve;
Engine::Engine(Platform* platform) :
m_platform(platform),
m_gameProgram(nullptr),
m_renderer(nullptr),
m_physicsEngine(nullptr),
m_world(this)
{
// OpenGL core-profile & extension functions will be loaded after GLEW initialized
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK)
{
ENGINE_LOG(Engine, LogLevel::FATAL_ERROR, "GLEW initialization failed");
decompose();
}
if(!m_world.init())
{
ENGINE_LOG(Engine, LogLevel::FATAL_ERROR, "World initialization failed");
decompose();
}
}
Engine::~Engine()
{
}
bool Engine::initSubsystems()
{
if(!verifyEngineSubsystems())
{
return false;
}
if(!initEngineSubsystems())
{
return false;
}
ENGINE_LOG(Engine, LogLevel::NOTE_MESSAGE, "initialized");
return true;
}
void Engine::start()
{
ENGINE_LOG(Engine, LogLevel::NOTE_MESSAGE, "started");
run();
}
void Engine::stop()
{
ENGINE_LOG(Engine, LogLevel::NOTE_MESSAGE, "stopped");
decompose();
}
void Engine::run()
{
float64 lastTimeS = m_platform->getTimer()->getCurrentTimeS();
float64 currentTimeS = lastTimeS;
float64 unprocessedTimeS = 0.0;
float64 fpsTimeAccumulator = 0.0;
uint32 fps = 0;
uint32 fpsCounter = 0;
// TEMP
const float64 targetUpdateStepS = 1.0f / 60.0f;
while(!m_platform->shouldClose())
{
bool needRendering = false;
lastTimeS = currentTimeS;
currentTimeS = m_platform->getTimer()->getCurrentTimeS();
unprocessedTimeS += (currentTimeS - lastTimeS);
while(unprocessedTimeS > targetUpdateStepS)
{
update(static_cast<float32>(targetUpdateStepS));
unprocessedTimeS -= targetUpdateStepS;
fpsTimeAccumulator += targetUpdateStepS;
needRendering = true;
}
if(needRendering)
{
render();
fpsCounter++;
if(fpsTimeAccumulator >= 1.0)
{
fps = fpsCounter;
fpsTimeAccumulator -= 1.0;
fpsCounter = 0;
//std::cout << "FPS: " << fps << std::endl;
}
needRendering = false;
}
// debug: naive loop
/*update(targetUpdateStepS);
render();*/
}
stop();
}
void Engine::update(float deltaS)
{
m_platform->update();
m_physicsEngine->update(deltaS);
m_gameProgram->update(deltaS);
}
void Engine::render()
{
m_renderer->render();
m_platform->refresh();
}
void Engine::decompose()
{
if(m_gameProgram)
{
m_gameProgram->decompose();
}
if(m_physicsEngine)
{
m_physicsEngine->decompose();
}
if(m_renderer)
{
m_renderer->decompose();
}
ENGINE_LOG(Engine, LogLevel::NOTE_MESSAGE, "decomposed");
}
Platform* Engine::getPlatform() { return m_platform; }
GameProgram* Engine::getGameProgram() { return m_gameProgram.get(); }
Renderer* Engine::getRenderer() { return m_renderer.get(); }
PhysicsEngine* Engine::getPhysicsEngine() { return m_physicsEngine.get(); }
World* Engine::getWorld() { return &m_world; }
void Engine::setGameProgram(std::unique_ptr<GameProgram> gameProgram)
{
m_gameProgram = std::move(gameProgram);
}
void Engine::setRenderer(std::unique_ptr<Renderer> renderer)
{
m_renderer = std::move(renderer);
}
void Engine::setPhysicsEngine(std::unique_ptr<PhysicsEngine> physicsEngine)
{
m_physicsEngine = std::move(physicsEngine);
}
bool Engine::verifyEngineSubsystems()
{
if(!m_renderer || !m_physicsEngine || !m_gameProgram)
{
ENGINE_LOG(Engine, LogLevel::FATAL_ERROR, "subsystem validation failed");
ENGINE_LOG(Engine, LogLevel::FATAL_ERROR,
"The following subsystems are required : Renderer, PhysicsEngine and GameProgram.");
decompose();
return false;
}
return true;
}
bool Engine::initEngineSubsystems()
{
if(!m_renderer->init(EngineProxy(this)))
{
ENGINE_LOG(Engine, LogLevel::FATAL_ERROR, "Renderer initialization failed");
decompose();
return false;
}
if(!m_physicsEngine->init(this))
{
ENGINE_LOG(Engine, LogLevel::FATAL_ERROR, "PhysicsEngine initialization failed");
decompose();
return false;
}
if(!m_gameProgram->init(this))
{
ENGINE_LOG(Engine, LogLevel::FATAL_ERROR, "GameProgram initialization failed");
decompose();
return false;
}
return true;
} | 19.460177 | 97 | 0.699181 | [
"render"
] |
8785d51ca34e1e67409a49d0760ab1abfc56da3e | 638 | hpp | C++ | ScheduleBuilder.hpp | eroicaleo/HEES | bfc1e297d6b0b7f928e590cdb97d9ccda069f483 | [
"MIT"
] | null | null | null | ScheduleBuilder.hpp | eroicaleo/HEES | bfc1e297d6b0b7f928e590cdb97d9ccda069f483 | [
"MIT"
] | null | null | null | ScheduleBuilder.hpp | eroicaleo/HEES | bfc1e297d6b0b7f928e590cdb97d9ccda069f483 | [
"MIT"
] | null | null | null | #ifndef _SCHEDULE_BUILDER_HPP_
#define _SCHEDULE_BUILDER_HPP_
#include <iostream>
#include <vector>
#include "DP/taskScheduling.hpp"
using std::vector;
using std::ostream;
class ScheduleBuilder {
public:
ScheduleBuilder() : m_inaccurateFlag(false) {}
// Leave all destructor, copy/move operations default
void BuildScheduleFromFile(const char *filename);
void PredictEnergyForSchedule(double initEnergy);
void DumpSchedule(ostream &os = std::cout) const;
private:
vector<dpTableEntry> m_schedule;
bool m_inaccurateFlag;
double getScheduleEnergy() const;
int getScheduleFinishTime() const;
double m_initialEnergy;
};
#endif
| 22.785714 | 54 | 0.791536 | [
"vector"
] |
878cdd3eec4b69e009a4cc1e632ff95b4f0f742a | 4,789 | hpp | C++ | ajg/synth/bindings/python/adapter.hpp | legutierr/synth | 7540072bde2ea9c8258c2dca69d2ed3bd62fb991 | [
"BSL-1.0"
] | 1 | 2016-04-10T14:13:34.000Z | 2016-04-10T14:13:34.000Z | ajg/synth/bindings/python/adapter.hpp | legutierr/synth | 7540072bde2ea9c8258c2dca69d2ed3bd62fb991 | [
"BSL-1.0"
] | null | null | null | ajg/synth/bindings/python/adapter.hpp | legutierr/synth | 7540072bde2ea9c8258c2dca69d2ed3bd62fb991 | [
"BSL-1.0"
] | null | null | null | // (C) Copyright 2014 Alvaro J. Genial (http://alva.ro)
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
#ifndef AJG_SYNTH_BINDINGS_PYTHON_ADAPTER_HPP_INCLUDED
#define AJG_SYNTH_BINDINGS_PYTHON_ADAPTER_HPP_INCLUDED
#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>
#include <ajg/synth/detail/text.hpp>
#include <ajg/synth/adapters/concrete_adapter.hpp>
#include <ajg/synth/bindings/python/conversions.hpp>
namespace ajg {
namespace synth {
namespace {
namespace py = ::boost::python;
using bindings::python::get_string;
using bindings::python::get_datetime;
} // namespace
//
// specialization for boost::python::object
////////////////////////////////////////////////////////////////////////////////////////////////////
template <class Behavior>
struct adapter<Behavior, py::object> : concrete_adapter<Behavior, py::object> {
adapter(py::object const& adapted) : concrete_adapter<Behavior, py::object>(adapted) {}
AJG_SYNTH_ADAPTER_TYPEDEFS(Behavior);
virtual boolean_type to_boolean() const { return boolean_type(this->adapted()); }
virtual datetime_type to_datetime() const { return get_datetime<traits_type>(this->adapted()); }
// virtual void input (istream_type& in) { in >> this->adapted(); }
// virtual void output(ostream_type& out) const { out << this->adapted(); }
virtual void output(ostream_type& out) const { out << get_string<traits_type>(this->adapted()); }
virtual iterator begin() { return begin<iterator>(this->adapted()); }
virtual iterator end() { return end<iterator>(this->adapted()); }
virtual const_iterator begin() const { return begin<const_iterator>(this->adapted()); }
virtual const_iterator end() const { return end<const_iterator>(this->adapted()); }
virtual boolean_type is_boolean() const { return PyBool_Check(this->adapted().ptr()); }
virtual boolean_type is_string() const { return PyString_Check(this->adapted().ptr()); }
virtual boolean_type is_numeric() const { return PyNumber_Check(this->adapted().ptr()); }
optional<value_type> index(value_type const& what) const {
// Per https://docs.djangoproject.com/en/dev/topics/templates/#variables
// TODO: Move this to django::engine.
// TODO: Support arbitrary values as keys for non-django general case.
PyObject *const o = this->adapted().ptr();
std::string const k = text::narrow(what.to_string());
// 1. Dictionary lookup
if (PyMapping_Check(o)) {
// TODO: If value is a py::object, use PyMapping_HasKey(o, <value>.ptr())
if (PyMapping_HasKeyString(o, const_cast<char*>(k.c_str()))) {
return value_type(py::object(this->adapted()[py::str(k)]));
}
}
// 2. Attribute lookup
// TODO: If value is a py::object, use PyObject_HasAttr(o, <value>.ptr()) and attr(...)
if (PyObject_HasAttrString(o, k.c_str())) {
py::object obj = this->adapted().attr(py::str(k));
// 3. Method call
if (PyCallable_Check(obj.ptr())) {
obj = obj();
}
return value_type(obj);
}
// 4. List-index lookup
if (PySequence_Check(o)) {
Py_ssize_t n = static_cast<Py_ssize_t>(what.to_floating());
if (n < PySequence_Size(o)) {
return value_type(py::object(this->adapted()[py::long_(n)]));
}
}
return boost::none;
}
private:
typedef typename py::stl_input_iterator<py::object> stl_iterator_type;
typedef detail::text<string_type> text;
private:
template <class I>
inline static I begin(py::object const& obj) {
if (PyObject_HasAttrString(obj.ptr(), "__iter__")) {
return I(stl_iterator_type(obj));
}
else if (PyObject_HasAttrString(obj.ptr(), "__getitem__")) {
// TODO: Don't instantiate a list; use a lazy iterator or generator.
return I(stl_iterator_type(py::list(obj)));
}
else {
std::string const& type = text::narrow(class_name(obj));
AJG_SYNTH_THROW(std::runtime_error(type + " object is not iterable"));
}
}
template <class I>
inline static I end(py::object const& obj) {
return I(stl_iterator_type());
}
inline static string_type class_name(py::object const& obj) {
return get_string<traits_type>(obj.attr("__class__").attr("__name__"));
}
};
}} // namespace ajg::synth
#endif // AJG_SYNTH_BINDINGS_PYTHON_ADAPTER_HPP_INCLUDED
| 37.708661 | 101 | 0.624765 | [
"object"
] |
87915bc9cc288a8208212e4ed11143e86d74b96a | 1,331 | hpp | C++ | src/Aurora/Framework/Transform.hpp | sjuhyeon/Aurora | 9a6249bcac9beb0ac9792137b522160156e1dd71 | [
"MIT"
] | 1 | 2022-02-23T17:42:51.000Z | 2022-02-23T17:42:51.000Z | src/Aurora/Framework/Transform.hpp | sjuhyeon/Aurora | 9a6249bcac9beb0ac9792137b522160156e1dd71 | [
"MIT"
] | null | null | null | src/Aurora/Framework/Transform.hpp | sjuhyeon/Aurora | 9a6249bcac9beb0ac9792137b522160156e1dd71 | [
"MIT"
] | null | null | null | #pragma once
#include "Aurora/Core/Vector.hpp"
namespace Aurora
{
struct Transform
{
Vector3 Translation = { 0.0f, 0.0f, 0.0f };
Vector3 Rotation = { 0.0f, 0.0f, 0.0f };
Vector3 Scale = { 1.0f, 1.0f, 1.0f };
glm::vec3 Up = { 0.0f, 1.0f, 0.0f };
glm::vec3 Right = { 1.0f, 0.0f, 0.0f };
glm::vec3 Forward = { 0.0f, 0.0f, -1.0f };
bool Locked = false; // For debug purposes
Transform() = default;
Transform(const Transform& other) = default;
explicit Transform(const glm::vec3& translation) : Translation(translation) {}
[[nodiscard]] Matrix4 GetTransform() const
{
const glm::mat4 transformX = glm::rotate(glm::mat4(1.0f),
glm::radians(Rotation.x),
glm::vec3(1.0f, 0.0f, 0.0f));
const glm::mat4 transformY = glm::rotate(glm::mat4(1.0f),
glm::radians(Rotation.y),
glm::vec3(0.0f, 1.0f, 0.0f));
const glm::mat4 transformZ = glm::rotate(glm::mat4(1.0f),
glm::radians(Rotation.z),
glm::vec3(0.0f, 0.0f, 1.0f));
// Y * X * Z
const glm::mat4 roationMatrix = transformY * transformX * transformZ;
return glm::translate(glm::mat4(1.0f), Translation) * roationMatrix * glm::scale(glm::mat4(1.0f), Scale);
}
void SetFromMatrix(const Matrix4& mat)
{
glm::DecomposeTransform(mat, Translation, Rotation, Scale);
Rotation = glm::degrees(Rotation);
}
};
} | 28.319149 | 109 | 0.63411 | [
"vector",
"transform"
] |
87992e3945f37ea453ee886461f94d2ae670252b | 2,966 | cpp | C++ | src/mining/journal_builder.cpp | z-btc/z-btc-main | 325510d88c0acafdbc041d3e03f6600c8509cda9 | [
"OML"
] | 2 | 2021-07-07T09:55:43.000Z | 2021-07-07T10:20:34.000Z | src/mining/journal_builder.cpp | MatterPool/bitcoin-sv-1 | c0e0cbd801ec46c0bd5bf6c91903eb943166f279 | [
"OML"
] | null | null | null | src/mining/journal_builder.cpp | MatterPool/bitcoin-sv-1 | c0e0cbd801ec46c0bd5bf6c91903eb943166f279 | [
"OML"
] | 2 | 2020-08-20T20:24:42.000Z | 2021-01-21T09:24:56.000Z | // Copyright (c) 2019 Bitcoin Association.
// Distributed under the Open BSV software license, see the accompanying file LICENSE.
#include <mining/journal.h>
#include <mining/journal_builder.h>
#include <mining/journal_change_set.h>
#include <logging.h>
using mining::CJournalBuilder;
using mining::CJournalChangeSetPtr;
using mining::CJournalPtr;
using mining::JournalUpdateReason;
using mining::CJournalChangeSet;
CJournalBuilder::CJournalBuilder()
: mJournal{ std::make_shared<CJournal>() }
{}
CJournalBuilder::~CJournalBuilder() = default;
// Fetch a new empty change set
CJournalChangeSetPtr CJournalBuilder::getNewChangeSet(JournalUpdateReason updateReason)
{
return std::make_unique<CJournalChangeSet>(*this, updateReason);
}
// Get our current journal
CJournalPtr CJournalBuilder::getCurrentJournal() const
{
std::shared_lock<std::shared_mutex> lock { mMtx };
return mJournal;
}
// Clear the current journal
void CJournalBuilder::clearJournal()
{
std::unique_lock<std::shared_mutex> lock { mMtx };
clearJournalUnlocked();
}
// Apply a change set
void CJournalBuilder::applyChangeSet(const CJournalChangeSet& changeSet)
{
// If the cause of this change is a new block arriving or a reorg, then
// create a new journal based on the old journal. This is for no other
// reason than to maintain the desired model of having journals linked
// to blocks.
JournalUpdateReason updateReason { changeSet.getUpdateReason() };
if(updateReason == JournalUpdateReason::NEW_BLOCK || updateReason == JournalUpdateReason::REORG)
{
LogPrint(BCLog::JOURNAL, "Journal builder creating new journal for %s\n",
enum_cast<std::string>(changeSet.getUpdateReason()).c_str());
// Replace old journal
std::unique_lock<std::shared_mutex> lock { mMtx };
CJournalPtr oldJournal { mJournal };
mJournal = std::make_shared<CJournal>(*oldJournal);
oldJournal->setCurrent(false);
}
// Don't log for every individual transaction, it'll swamp the log
if(changeSet.getChangeSet().size() > 1)
{
LogPrint(BCLog::JOURNAL, "Journal builder applying change set size %d for %s\n",
changeSet.getChangeSet().size(), enum_cast<std::string>(changeSet.getUpdateReason()).c_str());
}
if(updateReason == JournalUpdateReason::RESET)
{
// RESET is both a clear and apply operation
std::unique_lock<std::shared_mutex> lock { mMtx };
clearJournalUnlocked();
mJournal->applyChanges(changeSet);
}
else
{
// Pass changes down to journal for it to apply to itself
std::shared_lock<std::shared_mutex> lock { mMtx };
mJournal->applyChanges(changeSet);
}
}
// Clear the current journal - caller holds mutex
void CJournalBuilder::clearJournalUnlocked()
{
CJournalPtr oldJournal { mJournal };
mJournal = std::make_shared<CJournal>();
oldJournal->setCurrent(false);
}
| 32.955556 | 106 | 0.707687 | [
"model"
] |
87a58e6b6c173a882637ee27dce9af8f897aeb7c | 1,796 | cpp | C++ | source/core/slim-manager/SlimManager.cpp | izenecloud/sf1r-ad-delivery | 998eadb243098446854615de9a96e58a24bd2f4f | [
"Apache-2.0"
] | 18 | 2015-04-20T03:40:36.000Z | 2020-01-09T08:43:07.000Z | source/core/slim-manager/SlimManager.cpp | izenecloud/sf1r-ad-delivery | 998eadb243098446854615de9a96e58a24bd2f4f | [
"Apache-2.0"
] | null | null | null | source/core/slim-manager/SlimManager.cpp | izenecloud/sf1r-ad-delivery | 998eadb243098446854615de9a96e58a24bd2f4f | [
"Apache-2.0"
] | 7 | 2015-02-01T13:53:35.000Z | 2020-07-07T15:45:36.000Z | #include "SlimManager.h"
#include "SlimRecommend.h"
namespace sf1r {
SlimManager::SlimManager(const boost::shared_ptr<AdSearchService>& adSearchService,
const boost::shared_ptr<DocumentManager>& documentManager,
const std::string& collection,
LaserManager* laser)
: collection_(collection)
, adSearchService_(adSearchService)
, documentManager_(documentManager)
, laser_(laser)
{
rpcServer_ = new slim::SlimRpcServer(_similar_cluster, _similar_tareid, _rw_mutex);
rpcServer_->start("127.0.0.1", 38611, 2);
recommend_ = new slim::SlimRecommend(laser_->indexManager_,
laser_->tokenizer_,
_similar_cluster,
_similar_tareid,
_rw_mutex,
laser);
}
SlimManager::~SlimManager()
{
if (recommend_ != NULL) {
delete recommend_;
recommend_ = NULL;
}
if (rpcServer_ != NULL) {
rpcServer_->stop();
delete rpcServer_;
rpcServer_ = NULL;
}
}
bool SlimManager::recommend(const slim::SlimRecommendParam& param,
GetDocumentsByIdsActionItem& actionItem,
RawTextResultFromMIA& res) const
{
std::vector<docid_t> docIdList;
if (!recommend_->recommend(param.title_, param.id_, param.topn_, docIdList)) {
res.error_ = "Internal ERROR in Recommend Engine";
return false;
}
for (int i = 0; i != (int)docIdList.size(); ++i) {
actionItem.idList_.push_back(docIdList[i]);
}
adSearchService_->getDocumentsByIds(actionItem, res);
return true;
}
}
| 30.440678 | 87 | 0.566815 | [
"vector"
] |
87a5b604f21f81b1db1eee9763c71bf606e58347 | 565 | cpp | C++ | lib/model/src/World.cpp | beryan/Adventure2019 | a07b6ffee7ee196d9f499aa145906732ee067af0 | [
"MIT"
] | 1 | 2020-03-03T12:16:22.000Z | 2020-03-03T12:16:22.000Z | lib/model/src/World.cpp | beryan/Adventure2019 | a07b6ffee7ee196d9f499aa145906732ee067af0 | [
"MIT"
] | null | null | null | lib/model/src/World.cpp | beryan/Adventure2019 | a07b6ffee7ee196d9f499aa145906732ee067af0 | [
"MIT"
] | 1 | 2020-03-03T12:16:23.000Z | 2020-03-03T12:16:23.000Z | //
// Created by arehal on 1/17/19.
//
#include <iostream>
#include "World.h"
using model::World;
namespace model {
//constructors
World::World()
: areas({})
{ }
World::World(std::vector<Area> areas)
: areas(std::move(areas))
{ }
//getters and setters
std::vector<Area>& World::getAreas() {
return areas;
}
void World::setAreas(const std::vector<Area> &areas) {
this->areas = areas;
}
void World::addArea(const Area &area) {
this->areas.push_back(area);
}
} | 17.121212 | 58 | 0.548673 | [
"vector",
"model"
] |
87a83470ca6e1d5a86fd8794a15f5c23060d8599 | 695 | hpp | C++ | header/friedrichdb/field_t.hpp | jinncrafters/friedrichdb | 313180fee8f230b2a406000b948210c77c4253a3 | [
"BSD-3-Clause"
] | 1 | 2018-01-26T09:15:01.000Z | 2018-01-26T09:15:01.000Z | header/friedrichdb/field_t.hpp | duckstax/friedrichdb | 313180fee8f230b2a406000b948210c77c4253a3 | [
"BSD-3-Clause"
] | 1 | 2018-06-21T07:41:38.000Z | 2018-06-21T07:41:38.000Z | header/friedrichdb/field_t.hpp | duckstax/friedrichdb | 313180fee8f230b2a406000b948210c77c4253a3 | [
"BSD-3-Clause"
] | null | null | null | #ifndef FIELD_T_HPP
#define FIELD_T_HPP
#include "friedrichdb/data_types/ordering.h"
#include <vector>
#include <memory>
namespace friedrichdb {
using byte = std::uint8_t;
class field_t final : public implement::ordered<field_t> {
public:
field_t() = default;
~field_t() = default;
void set(const byte *data, std::size_t size);
void push_back(const char *data, std::size_t size);
byte *data();
const byte *data() const;;
std::size_t size() const;;
private:
std::vector <byte> data_;
};
using field_ptr = std::shared_ptr<field_t>;
}
#endif
| 19.857143 | 66 | 0.569784 | [
"vector"
] |
87a91ce1162221708a14b81738f7adb0bebfa152 | 20,357 | cpp | C++ | src/draw_helpers/ThemeDrawHelper.cpp | omi-lab/tp_maps_ui | 720690b4b30e1db2c9231d6b86b61434cc32d3a5 | [
"MIT"
] | 1 | 2018-11-06T12:30:38.000Z | 2018-11-06T12:30:38.000Z | src/draw_helpers/ThemeDrawHelper.cpp | omi-lab/tp_maps_ui | 720690b4b30e1db2c9231d6b86b61434cc32d3a5 | [
"MIT"
] | null | null | null | src/draw_helpers/ThemeDrawHelper.cpp | omi-lab/tp_maps_ui | 720690b4b30e1db2c9231d6b86b61434cc32d3a5 | [
"MIT"
] | 2 | 2018-11-05T10:58:08.000Z | 2020-12-09T12:39:04.000Z | #include "tp_maps_ui/draw_helpers/ThemeDrawHelper.h"
#include "tp_maps_ui/layers/UILayer.h"
#include "tp_maps/Map.h"
#include "tp_maps/shaders/FrameShader.h"
#include "tp_maps/textures/BasicTexture.h"
#include "tp_image_utils/SaveImages.h"
namespace tp_maps_ui
{
namespace
{
using Vert = tp_maps::FrameShader::Vertex;
//##################################################################################################
struct FrameDetails_lt
{
std::vector<GLushort> indexes;
std::vector<tp_maps::FrameShader::Vertex> verts;
tp_maps::FrameShader::VertexBuffer* vertexBuffer{nullptr};
bool updateVertexBuffer{true};
glm::vec4 textColor{0.0f, 0.0f, 0.0f, 1.0f};
glm::vec4 placeholderTextColor{0.5f, 0.5f, 0.5f, 1.0f};
};
//##################################################################################################
struct TextureCoords_lt
{
float x0 = 0.0f;
float x1 = 0.0f;
float y0 = 0.0f;
float y1 = 0.0f;
};
//##################################################################################################
struct TextureBuffer_lt
{
TPPixel* rawData;
tp_image_utils::ColorMap& textureData;
size_t cx=1;
size_t cy=1;
size_t rh=1;
//################################################################################################
TextureBuffer_lt(TPPixel* rawData_, tp_image_utils::ColorMap& textureData_):
rawData(rawData_),
textureData(textureData_)
{
}
//################################################################################################
TextureCoords_lt drawCell(size_t w, size_t h, const std::function<TPPixel(float, float)>& func)
{
TextureCoords_lt textureCoords;
size_t x=0;
size_t y=0;
float fw = float(w);
float fh = float(h);
//-- Make sure we have space to draw the cell --------------------------------------------------
if((cx+3+w)<textureData.width() && (cy+3+h)<textureData.height())
{
x = cx+1;
cx = cx+3+w;
y = cy+1;
}
else
{
cx = 1;
cy += rh+3;
rh=1;
if((cx+3+w)<textureData.width() && (cy+3+h)<textureData.height())
{
x = cx+1;
cx = cx+3+w;
y = cy+1;
}
else
{
return textureCoords;
}
}
if(h>rh)
rh = h;
//-- Draw the cell -----------------------------------------------------------------------------
for(size_t yy=0; yy<h; yy++)
{
float fy = float(yy)/fh;
for(size_t xx=0; xx<w; xx++)
rawData[(x+xx)+(textureData.width()*(y+yy))] = func(float(xx)/fw, fy);
}
//-- Draw the cell borders ---------------------------------------------------------------------
{
for(size_t xx=0; xx<w; xx++)
{
rawData[(x+xx)+(textureData.width()*(y-1))] = rawData[(x+xx)+(textureData.width()*(y))];
rawData[(x+xx)+(textureData.width()*(y+h))] = rawData[(x+xx)+(textureData.width()*((y+h)-1))];
}
for(size_t yy=0; yy<h; yy++)
{
rawData[(x-1)+(textureData.width()*(y+yy))] = rawData[(x)+(textureData.width()*(y+yy))];
rawData[(x+w)+(textureData.width()*(y+yy))] = rawData[((x+w)-1)+(textureData.width()*(y+yy))];
}
rawData[(x-1)+(textureData.width()*(y-1))] = rawData[x+(textureData.width()*y)];
rawData[(x+w)+(textureData.width()*(y-1))] = rawData[((x+w)-1)+(textureData.width()*y)];
rawData[(x-1)+(textureData.width()*(y+h))] = rawData[x+(textureData.width()*((y+h)-1))];
rawData[(x+w)+(textureData.width()*(y+h))] = rawData[((x+w)-1)+(textureData.width()*((y+h)-1))];
}
//-- Calculate the texture coords --------------------------------------------------------------
{
textureCoords.x0 = float((x+w)) / float(textureData.width());
textureCoords.x1 = float(x) / float(textureData.width());
textureCoords.y0 = float(y) / float(textureData.height());
textureCoords.y1 = float((y+h)) / float(textureData.height());
}
return textureCoords;
}
};
}
//##################################################################################################
struct ThemeDrawHelper::Private
{
TP_REF_COUNT_OBJECTS("tp_maps_ui::ThemeDrawHelper::Private");
TP_NONCOPYABLE(Private);
ThemeDrawHelper* q;
ThemeParameters themeParameters;
FrameDetails_lt normalPanelFrameDetails;
FrameDetails_lt editableFrameDetails;
FrameDetails_lt raisedButtonFrameDetails;
FrameDetails_lt sunkenButtonFrameDetails;
FrameDetails_lt checkedCheckBoxFrameDetails;
FrameDetails_lt uncheckedCheckBoxFrameDetails;
FrameDetails_lt raisedHandleFrameDetails;
FrameDetails_lt sunkenHandleFrameDetails;
FrameDetails_lt overlayFrameDetails;
tp_maps::BasicTexture* texture{nullptr};
GLuint textureID{0};
glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};
bool bindBeforeRender{true};
//################################################################################################
Private(ThemeDrawHelper* q_, const ThemeParameters& themeParameters_):
q(q_),
themeParameters(themeParameters_)
{
}
//################################################################################################
~Private()
{
if(textureID)
{
q->map()->makeCurrent();
q->map()->deleteTexture(textureID);
}
delete texture;
deleteVertexBuffers();
}
//################################################################################################
void deleteVertexBuffers()
{
delete normalPanelFrameDetails.vertexBuffer;
normalPanelFrameDetails.vertexBuffer=nullptr;
delete editableFrameDetails.vertexBuffer;
editableFrameDetails.vertexBuffer=nullptr;
delete raisedButtonFrameDetails.vertexBuffer;
raisedButtonFrameDetails.vertexBuffer=nullptr;
delete sunkenButtonFrameDetails.vertexBuffer;
sunkenButtonFrameDetails.vertexBuffer=nullptr;
delete checkedCheckBoxFrameDetails.vertexBuffer;
checkedCheckBoxFrameDetails.vertexBuffer=nullptr;
delete uncheckedCheckBoxFrameDetails.vertexBuffer;
uncheckedCheckBoxFrameDetails.vertexBuffer=nullptr;
delete overlayFrameDetails.vertexBuffer;
overlayFrameDetails.vertexBuffer=nullptr;
delete raisedHandleFrameDetails.vertexBuffer;
raisedHandleFrameDetails.vertexBuffer=nullptr;
delete sunkenHandleFrameDetails.vertexBuffer;
sunkenHandleFrameDetails.vertexBuffer=nullptr;
}
//################################################################################################
static void drawCell(TPPixel* rawData, tp_image_utils::ColorMap& textureData, size_t x, size_t y, size_t w, size_t h, const std::function<TPPixel(float, float)>& func)
{
float fw = float(w);
float fh = float(h);
for(size_t yy=0; yy<h; yy++)
{
float fy = float(yy)/fh;
for(size_t xx=0; xx<w; xx++)
rawData[(x+xx)+(textureData.width()*(y+yy))] = func(float(xx)/fw, fy);
}
}
//################################################################################################
static void generateFrame(TextureBuffer_lt& textureBuffer, FrameDetails_lt& frame, const FrameParameters& colors)
{
frame.textColor.x = float(colors.textColor.r)/255.0f;
frame.textColor.y = float(colors.textColor.g)/255.0f;
frame.textColor.z = float(colors.textColor.b)/255.0f;
frame.textColor.w = float(colors.textColor.a)/255.0f;
frame.placeholderTextColor.x = float(colors.placeholderTextColor.r)/255.0f;
frame.placeholderTextColor.y = float(colors.placeholderTextColor.g)/255.0f;
frame.placeholderTextColor.z = float(colors.placeholderTextColor.b)/255.0f;
frame.placeholderTextColor.w = float(colors.placeholderTextColor.a)/255.0f;
size_t borderSize = colors.borderSize;
size_t centerSize = 10;
float borderSizeF = float(borderSize);
size_t leftColumnW = borderSize;
size_t centerColumnW = centerSize;
size_t rightColumnW = borderSize;
size_t topRowH = borderSize;
size_t centerRowH = centerSize;
size_t bottomRowH = borderSize;
TextureCoords_lt ttl;
TextureCoords_lt ttc;
TextureCoords_lt ttr;
TextureCoords_lt tcl;
TextureCoords_lt tcc;
TextureCoords_lt tcr;
TextureCoords_lt tbl;
TextureCoords_lt tbc;
TextureCoords_lt tbr;
switch(colors.drawMode)
{
case FrameDrawMode::Square: //------------------------------------------------------------------
{
ttl = textureBuffer.drawCell( leftColumnW, topRowH, [&](float, float){return colors.tl;});
ttc = textureBuffer.drawCell(centerColumnW, topRowH, [&](float, float){return colors.t; });
ttr = textureBuffer.drawCell( rightColumnW, topRowH, [&](float, float){return colors.tr;});
tcl = textureBuffer.drawCell( leftColumnW, centerRowH, [&](float, float){return colors.l; });
tcc = textureBuffer.drawCell(centerColumnW, centerRowH, [&](float, float){return colors.c; });
tcr = textureBuffer.drawCell( rightColumnW, centerRowH, [&](float, float){return colors.r; });
tbl = textureBuffer.drawCell( leftColumnW, bottomRowH, [&](float, float){return colors.bl;});
tbc = textureBuffer.drawCell(centerColumnW, bottomRowH, [&](float, float){return colors.b; });
tbr = textureBuffer.drawCell( rightColumnW, bottomRowH, [&](float, float){return colors.br;});
break;
}
case FrameDrawMode::Rounded: //-----------------------------------------------------------------
{
auto drawRadius = [&](const TPPixel& c, float fx, float fy)
{
return [=](float x, float y)
{
x = fx-x;
y = fy-y;
float a = 1.0f;
float l=std::sqrt(x*x + y*y);
if(l>0.8f)
a = std::clamp(1.0f - (l-0.8f)*5, 0.0f, 1.0f);
a = a*a*255.0f;
return TPPixel(c.r, c.g, c.b, uint8_t(a));
};
};
ttl = textureBuffer.drawCell( leftColumnW, topRowH, drawRadius(colors.tl, 0.0f, 1.0f));
ttc = textureBuffer.drawCell(centerColumnW, topRowH, [&](float, float){return colors.t; });
ttr = textureBuffer.drawCell( rightColumnW, topRowH, drawRadius(colors.tr, 1.0f, 1.0f));
tcl = textureBuffer.drawCell( leftColumnW, centerRowH, [&](float, float){return colors.l; });
tcc = textureBuffer.drawCell(centerColumnW, centerRowH, [&](float, float){return colors.c; });
tcr = textureBuffer.drawCell( rightColumnW, centerRowH, [&](float, float){return colors.r; });
tbl = textureBuffer.drawCell( leftColumnW, bottomRowH, drawRadius(colors.bl, 0.0f, 0.0f));
tbc = textureBuffer.drawCell(centerColumnW, bottomRowH, [&](float, float){return colors.b; });
tbr = textureBuffer.drawCell( rightColumnW, bottomRowH, drawRadius(colors.br, 1.0f, 0.0f));
break;
}
}
frame.verts.clear();
frame.indexes.clear();
frame.updateVertexBuffer = true;
glm::vec3 normal = {0.0f, 0.0f, 1.0f};
#if 0
//Print out the full texture
frame.verts.resize(4);
frame.verts[0] = Vert({0, 0, 0.0f}, {0.0f, 0.0f, 0.0f}, normal, {0, 0});
frame.verts[1] = Vert({0, 0, 0.0f}, {1.0f, 0.0f, 0.0f}, normal, {1, 0});
frame.verts[2] = Vert({0, 0, 0.0f}, {1.0f, 1.0f, 0.0f}, normal, {1, 1});
frame.verts[3] = Vert({0, 0, 0.0f}, {0.0f, 1.0f, 0.0f}, normal, {0, 1});
frame.indexes = {3,2,0,2,1,0};
#else
auto addIndexes = [&]()
{
for(auto i : {0, 1, 2, 0, 2, 3})
frame.indexes.push_back(GLushort(size_t(i)+frame.verts.size()));
};
auto addCell = [&](float px0, float py0, float px1, float py1, float rx0, float ry0, float rx1, float ry1, const TextureCoords_lt& t)
{
addIndexes();
frame.verts.push_back(Vert({px0, py0, 0.0f}, {rx0, ry0, 0.0f}, normal, {t.x0, t.y0}));
frame.verts.push_back(Vert({px1, py0, 0.0f}, {rx1, ry0, 0.0f}, normal, {t.x1, t.y0}));
frame.verts.push_back(Vert({px1, py1, 0.0f}, {rx1, ry1, 0.0f}, normal, {t.x1, t.y1}));
frame.verts.push_back(Vert({px0, py1, 0.0f}, {rx0, ry1, 0.0f}, normal, {t.x0, t.y1}));
};
float px0 = 0.0f;
float px1 = borderSizeF;
float px2 = -borderSizeF;
float px3 = 0.0f;
float py0 = 0.0f;
float py1 = borderSizeF;
float py2 = -borderSizeF;
float py3 = 0.0f;
float rx0 = 0.0f;
float rx1 = 0.0f;
float rx2 = 1.0f;
float rx3 = 1.0f;
float ry0 = 0.0f;
float ry1 = 0.0f;
float ry2 = 1.0f;
float ry3 = 1.0f;
addCell(px0, py0, px1, py1, rx0, ry0, rx1, ry1, ttl);
addCell(px1, py0, px2, py1, rx1, ry0, rx2, ry1, ttc);
addCell(px2, py0, px3, py1, rx2, ry0, rx3, ry1, ttr);
addCell(px0, py1, px1, py2, rx0, ry1, rx1, ry2, tcl);
addCell(px1, py1, px2, py2, rx1, ry1, rx2, ry2, tcc);
addCell(px2, py1, px3, py2, rx2, ry1, rx3, ry2, tcr);
addCell(px0, py2, px1, py3, rx0, ry2, rx1, ry3, tbl);
addCell(px1, py2, px2, py3, rx1, ry2, rx2, ry3, tbc);
addCell(px2, py2, px3, py3, rx2, ry2, rx3, ry3, tbr);
std::reverse(frame.indexes.begin(), frame.indexes.end());
#endif
}
//################################################################################################
static void generateOverlay(TextureBuffer_lt& textureBuffer, FrameDetails_lt& frame, const OverlayParameters& params)
{
size_t cellSize = 1;
auto t = textureBuffer.drawCell(cellSize, cellSize, [&](float, float){return params.color;});
frame.verts.clear();
frame.indexes.clear();
frame.updateVertexBuffer = true;
glm::vec3 normal = {0.0f, 0.0f, 1.0f};
frame.verts.resize(4);
frame.verts[0] = Vert({0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, normal, {t.x0, t.y0});
frame.verts[1] = Vert({0.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, normal, {t.x1, t.y0});
frame.verts[2] = Vert({0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 0.0f}, normal, {t.x1, t.y1});
frame.verts[3] = Vert({0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, normal, {t.x0, t.y1});
frame.indexes = {3,2,0,2,1,0};
}
//################################################################################################
void populateGeometry()
{
if(texture)
return;
texture = new tp_maps::BasicTexture(q->map());
texture->setMagFilterOption(GL_NEAREST);
texture->setMinFilterOption(GL_NEAREST);
tp_image_utils::ColorMap textureData(512, 512);
TextureBuffer_lt textureBuffer(textureData.data(), textureData);
generateFrame(textureBuffer, normalPanelFrameDetails, themeParameters.normalPanelFrame );
generateFrame(textureBuffer, editableFrameDetails, themeParameters.editableFrame );
generateFrame(textureBuffer, raisedButtonFrameDetails, themeParameters.raisedButtonFrame );
generateFrame(textureBuffer, sunkenButtonFrameDetails, themeParameters.sunkenButtonFrame );
generateFrame(textureBuffer, checkedCheckBoxFrameDetails, themeParameters.checkedCheckBoxFrame );
generateFrame(textureBuffer, uncheckedCheckBoxFrameDetails, themeParameters.uncheckedCheckBoxFrame);
generateFrame(textureBuffer, raisedHandleFrameDetails, themeParameters.raisedHandleFrame );
generateFrame(textureBuffer, sunkenHandleFrameDetails, themeParameters.sunkenHandleFrame );
generateOverlay(textureBuffer, overlayFrameDetails, themeParameters.overlay);
q->setRecommendedSize(FillType::CheckBox, themeParameters.checkedCheckBoxFrame.recommendedSize);
q->setRecommendedSize(FillType::Slider , themeParameters. raisedHandleFrame.recommendedSize);
if(!themeParameters.debugToFile.empty())
tp_image_utils::saveImage(themeParameters.debugToFile, textureData);
texture->setImage(textureData);
}
//################################################################################################
void drawFrame(const glm::mat4& matrix, FrameDetails_lt& frame, float width, float height, const glm::vec4& color)
{
populateGeometry();
if(!texture || !texture->imageReady())
return;
auto shader = q->map()->getShader<tp_maps::FrameShader>();
if(shader->error())
return;
if(bindBeforeRender)
{
bindBeforeRender=false;
q->map()->deleteTexture(textureID);
textureID = texture->bindTexture();
}
if(!textureID)
return;
if(!frame.vertexBuffer || frame.updateVertexBuffer)
{
delete frame.vertexBuffer;
frame.vertexBuffer = shader->generateVertexBuffer(q->map(), frame.indexes, frame.verts);
frame.updateVertexBuffer=false;
}
shader->use();
shader->setMatrix(matrix);
shader->setScale({width, height, 1.0f});
shader->setTexture(textureID);
shader->draw(GL_TRIANGLES, frame.vertexBuffer, color);
}
//################################################################################################
FrameDetails_lt& selectFrameDetails(BoxType boxType, FillType fillType, VisualModifier visualModifier)
{
TP_UNUSED(boxType);
switch(fillType)
{
case FillType::CheckBox:
{
switch(visualModifier)
{
case VisualModifier::Checked:
return checkedCheckBoxFrameDetails;
default:
return uncheckedCheckBoxFrameDetails;
}
}
case FillType::Editable:
{
return editableFrameDetails;
}
case FillType::Panel:
{
return normalPanelFrameDetails;
}
case FillType::Slider:
{
switch(visualModifier)
{
case VisualModifier::Pressed:
return sunkenHandleFrameDetails;
default:
return raisedHandleFrameDetails;
}
}
default:
{
switch(visualModifier)
{
case VisualModifier::Pressed:
return sunkenButtonFrameDetails;
default:
return raisedButtonFrameDetails;
}
}
}
}
};
//##################################################################################################
ThemeDrawHelper::ThemeDrawHelper(UILayer* layer, const ThemeParameters& themeParameters):
DrawHelper(layer),
d(new Private(this, themeParameters))
{
}
//##################################################################################################
ThemeDrawHelper::~ThemeDrawHelper()
{
delete d;
}
//##################################################################################################
const ThemeParameters& ThemeDrawHelper::themeParameters() const
{
return d->themeParameters;
}
//##################################################################################################
void ThemeDrawHelper::drawBox(const glm::mat4& matrix, float width, float height, BoxType boxType, FillType fillType, VisualModifier visualModifier)
{
d->drawFrame(matrix, d->selectFrameDetails(boxType, fillType, visualModifier), width, height, d->color);
}
//##################################################################################################
void ThemeDrawHelper::drawOverlay(const glm::mat4& matrix, float width, float height, float fade)
{
auto c = d->color;
c.w = fade;
d->drawFrame(matrix, d->overlayFrameDetails, width, height, c);
}
//##################################################################################################
glm::vec4 ThemeDrawHelper::textColor(BoxType boxType, FillType fillType, VisualModifier visualModifier)
{
d->populateGeometry();
return d->selectFrameDetails(boxType, fillType, visualModifier).textColor;
}
//##################################################################################################
glm::vec4 ThemeDrawHelper::placeholderTextColor(BoxType boxType, FillType fillType, VisualModifier visualModifier)
{
d->populateGeometry();
return d->selectFrameDetails(boxType, fillType, visualModifier).placeholderTextColor;
}
//##################################################################################################
void ThemeDrawHelper::invalidateBuffers()
{
DrawHelper::invalidateBuffers();
d->deleteVertexBuffers();
d->normalPanelFrameDetails .updateVertexBuffer = true;
d->editableFrameDetails .updateVertexBuffer = true;
d->raisedButtonFrameDetails .updateVertexBuffer = true;
d->sunkenButtonFrameDetails .updateVertexBuffer = true;
d->checkedCheckBoxFrameDetails .updateVertexBuffer = true;
d->uncheckedCheckBoxFrameDetails.updateVertexBuffer = true;
d->overlayFrameDetails .updateVertexBuffer = true;
d->textureID = 0;
d->bindBeforeRender = true;
}
}
| 33.537068 | 169 | 0.572629 | [
"vector"
] |
87baf8c8a845739cd688eb1392f78f79e9a0fc31 | 193,889 | cpp | C++ | android/android_9/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// #define LOG_NDEBUG 0
#define ATRACE_TAG ATRACE_TAG_GRAPHICS
#include <stdint.h>
#include <sys/types.h>
#include <algorithm>
#include <errno.h>
#include <math.h>
#include <mutex>
#include <dlfcn.h>
#include <inttypes.h>
#include <stdatomic.h>
#include <optional>
#include <cutils/properties.h>
#include <log/log.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <binder/PermissionCache.h>
#include <dvr/vr_flinger.h>
#include <ui/DebugUtils.h>
#include <ui/DisplayInfo.h>
#include <ui/DisplayStatInfo.h>
#include <gui/BufferQueue.h>
#include <gui/GuiConfig.h>
#include <gui/IDisplayEventConnection.h>
#include <gui/LayerDebugInfo.h>
#include <gui/Surface.h>
#include <ui/GraphicBufferAllocator.h>
#include <ui/PixelFormat.h>
#include <ui/UiConfig.h>
#include <utils/misc.h>
#include <utils/String8.h>
#include <utils/String16.h>
#include <utils/StopWatch.h>
#include <utils/Timers.h>
#include <utils/Trace.h>
#include <private/android_filesystem_config.h>
#include <private/gui/SyncFeatures.h>
#include "BufferLayer.h"
#include "Client.h"
#include "ColorLayer.h"
#include "Colorizer.h"
#include "ContainerLayer.h"
#include "DdmConnection.h"
#include "DispSync.h"
#include "DisplayDevice.h"
#include "EventControlThread.h"
#include "EventThread.h"
#include "Layer.h"
#include "LayerVector.h"
#include "MonitoredProducer.h"
#include "SurfaceFlinger.h"
#include "clz.h"
#include "DisplayHardware/ComposerHal.h"
#include "DisplayHardware/FramebufferSurface.h"
#include "DisplayHardware/HWComposer.h"
#include "DisplayHardware/VirtualDisplaySurface.h"
#include "Effects/Daltonizer.h"
#include "RenderEngine/RenderEngine.h"
#include <cutils/compiler.h>
#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
#include <android/hardware/configstore/1.1/types.h>
#include <configstore/Utils.h>
#include <layerproto/LayerProtoParser.h>
#define DISPLAY_COUNT 1
/*
* DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
* black pixels.
*/
#define DEBUG_SCREENSHOTS false
namespace android {
using namespace android::hardware::configstore;
using namespace android::hardware::configstore::V1_0;
using ui::ColorMode;
using ui::Dataspace;
using ui::Hdr;
using ui::RenderIntent;
namespace {
class ConditionalLock {
public:
ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
if (lock) {
mMutex.lock();
}
}
~ConditionalLock() { if (mLocked) mMutex.unlock(); }
private:
Mutex& mMutex;
bool mLocked;
};
} // namespace anonymous
// ---------------------------------------------------------------------------
const String16 sHardwareTest("android.permission.HARDWARE_TEST");
const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
const String16 sDump("android.permission.DUMP");
// ---------------------------------------------------------------------------
int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
bool SurfaceFlinger::useHwcForRgbToYuv;
uint64_t SurfaceFlinger::maxVirtualDisplaySize;
bool SurfaceFlinger::hasSyncFramework;
bool SurfaceFlinger::useVrFlinger;
int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
bool SurfaceFlinger::hasWideColorDisplay;
std::string getHwcServiceName() {
char value[PROPERTY_VALUE_MAX] = {};
property_get("debug.sf.hwc_service_name", value, "default");
ALOGI("Using HWComposer service: '%s'", value);
return std::string(value);
}
bool useTrebleTestingOverride() {
char value[PROPERTY_VALUE_MAX] = {};
property_get("debug.sf.treble_testing_override", value, "false");
ALOGI("Treble testing override: '%s'", value);
return std::string(value) == "true";
}
std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
switch(displayColorSetting) {
case DisplayColorSetting::MANAGED:
return std::string("Managed");
case DisplayColorSetting::UNMANAGED:
return std::string("Unmanaged");
case DisplayColorSetting::ENHANCED:
return std::string("Enhanced");
default:
return std::string("Unknown ") +
std::to_string(static_cast<int>(displayColorSetting));
}
}
NativeWindowSurface::~NativeWindowSurface() = default;
namespace impl {
class NativeWindowSurface final : public android::NativeWindowSurface {
public:
static std::unique_ptr<android::NativeWindowSurface> create(
const sp<IGraphicBufferProducer>& producer) {
return std::make_unique<NativeWindowSurface>(producer);
}
explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
: surface(new Surface(producer, false)) {}
~NativeWindowSurface() override = default;
private:
sp<ANativeWindow> getNativeWindow() const override { return surface; }
void preallocateBuffers() override { surface->allocateBuffers(); }
sp<Surface> surface;
};
} // namespace impl
SurfaceFlingerBE::SurfaceFlingerBE()
: mHwcServiceName(getHwcServiceName()),
mRenderEngine(nullptr),
mFrameBuckets(),
mTotalTime(0),
mLastSwapTime(0),
mComposerSequenceId(0) {
}
SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
: BnSurfaceComposer(),
mTransactionFlags(0),
mTransactionPending(false),
mAnimTransactionPending(false),
mLayersRemoved(false),
mLayersAdded(false),
mRepaintEverything(0),
mBootTime(systemTime()),
mBuiltinDisplays(),
mVisibleRegionsDirty(false),
mGeometryInvalid(false),
mAnimCompositionPending(false),
mDebugRegion(0),
mDebugDDMS(0),
mDebugDisableHWC(0),
mDebugDisableTransformHint(0),
mDebugInSwapBuffers(0),
mLastSwapBufferTime(0),
mDebugInTransaction(0),
mLastTransactionTime(0),
mBootFinished(false),
mForceFullDamage(false),
mPrimaryDispSync("PrimaryDispSync"),
mPrimaryHWVsyncEnabled(false),
mHWVsyncAvailable(false),
mHasPoweredOff(false),
mNumLayers(0),
mVrFlingerRequestsDisplay(false),
mMainThreadId(std::this_thread::get_id()),
mCreateBufferQueue(&BufferQueue::createBufferQueue),
mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
ALOGI("SurfaceFlinger is starting");
vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
&ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
&ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
hasSyncFramework = getBool< ISurfaceFlingerConfigs,
&ISurfaceFlingerConfigs::hasSyncFramework>(true);
dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
&ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
&ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
&ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
// Vr flinger is only enabled on Daydream ready devices.
useVrFlinger = getBool< ISurfaceFlingerConfigs,
&ISurfaceFlingerConfigs::useVrFlinger>(false);
maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
&ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
hasWideColorDisplay =
getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
V1_1::DisplayOrientation primaryDisplayOrientation =
getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
V1_1::DisplayOrientation::ORIENTATION_0);
switch (primaryDisplayOrientation) {
case V1_1::DisplayOrientation::ORIENTATION_90:
mPrimaryDisplayOrientation = DisplayState::eOrientation90;
break;
case V1_1::DisplayOrientation::ORIENTATION_180:
mPrimaryDisplayOrientation = DisplayState::eOrientation180;
break;
case V1_1::DisplayOrientation::ORIENTATION_270:
mPrimaryDisplayOrientation = DisplayState::eOrientation270;
break;
default:
mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
break;
}
ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
// debugging stuff...
char value[PROPERTY_VALUE_MAX];
property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
mGpuToCpuSupported = !atoi(value);
property_get("debug.sf.showupdates", value, "0");
mDebugRegion = atoi(value);
property_get("debug.sf.ddms", value, "0");
mDebugDDMS = atoi(value);
if (mDebugDDMS) {
if (!startDdmConnection()) {
// start failed, and DDMS debugging not enabled
mDebugDDMS = 0;
}
}
ALOGI_IF(mDebugRegion, "showupdates enabled");
ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
property_get("debug.sf.disable_backpressure", value, "0");
mPropagateBackpressure = !atoi(value);
ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
property_get("debug.sf.enable_hwc_vds", value, "0");
mUseHwcVirtualDisplays = atoi(value);
ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
property_get("ro.sf.disable_triple_buffer", value, "1");
mLayerTripleBufferingDisabled = atoi(value);
ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
const size_t defaultListSize = MAX_LAYERS;
auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
property_get("debug.sf.early_phase_offset_ns", value, "0");
const int earlyWakeupOffsetOffsetNs = atoi(value);
ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
sfVsyncPhaseOffsetNs);
// We should be reading 'persist.sys.sf.color_saturation' here
// but since /data may be encrypted, we need to wait until after vold
// comes online to attempt to read the property. The property is
// instead read after the boot animation
if (useTrebleTestingOverride()) {
// Without the override SurfaceFlinger cannot connect to HIDL
// services that are not listed in the manifests. Considered
// deriving the setting from the set service name, but it
// would be brittle if the name that's not 'default' is used
// for production purposes later on.
setenv("TREBLE_TESTING_OVERRIDE", "true", true);
}
}
void SurfaceFlinger::onFirstRef()
{
mEventQueue->init(this);
}
SurfaceFlinger::~SurfaceFlinger()
{
}
void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
{
// the window manager died on us. prepare its eulogy.
// restore initial conditions (default device unblank, etc)
initializeDisplays();
// restart the boot-animation
startBootAnim();
}
static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
status_t err = client->initCheck();
if (err == NO_ERROR) {
return client;
}
return nullptr;
}
sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
return initClient(new Client(this));
}
sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
const sp<IGraphicBufferProducer>& gbp) {
if (authenticateSurfaceTexture(gbp) == false) {
return nullptr;
}
const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
if (layer == nullptr) {
return nullptr;
}
return initClient(new Client(this, layer));
}
sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
bool secure)
{
class DisplayToken : public BBinder {
sp<SurfaceFlinger> flinger;
virtual ~DisplayToken() {
// no more references, this display must be terminated
Mutex::Autolock _l(flinger->mStateLock);
flinger->mCurrentState.displays.removeItem(this);
flinger->setTransactionFlags(eDisplayTransactionNeeded);
}
public:
explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
: flinger(flinger) {
}
};
sp<BBinder> token = new DisplayToken(this);
Mutex::Autolock _l(mStateLock);
DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
info.displayName = displayName;
mCurrentState.displays.add(token, info);
mInterceptor->saveDisplayCreation(info);
return token;
}
void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
Mutex::Autolock _l(mStateLock);
ssize_t idx = mCurrentState.displays.indexOfKey(display);
if (idx < 0) {
ALOGW("destroyDisplay: invalid display token");
return;
}
const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
if (!info.isVirtualDisplay()) {
ALOGE("destroyDisplay called for non-virtual display");
return;
}
mInterceptor->saveDisplayDeletion(info.displayId);
mCurrentState.displays.removeItemsAt(idx);
setTransactionFlags(eDisplayTransactionNeeded);
}
sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
return nullptr;
}
return mBuiltinDisplays[id];
}
void SurfaceFlinger::bootFinished()
{
if (mStartPropertySetThread->join() != NO_ERROR) {
ALOGE("Join StartPropertySetThread failed!");
}
const nsecs_t now = systemTime();
const nsecs_t duration = now - mBootTime;
ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
// wait patiently for the window manager death
const String16 name("window");
sp<IBinder> window(defaultServiceManager()->getService(name));
if (window != 0) {
window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
}
if (mVrFlinger) {
mVrFlinger->OnBootFinished();
}
// stop boot animation
// formerly we would just kill the process, but we now ask it to exit so it
// can choose where to stop the animation.
property_set("service.bootanim.exit", "1");
const int LOGTAG_SF_STOP_BOOTANIM = 60110;
LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
readPersistentProperties();
});
postMessageAsync(readProperties);
}
void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
class MessageDestroyGLTexture : public MessageBase {
RE::RenderEngine& engine;
uint32_t texture;
public:
MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
: engine(engine), texture(texture) {}
virtual bool handler() {
engine.deleteTextures(1, &texture);
return true;
}
};
postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
}
class DispSyncSource final : public VSyncSource, private DispSync::Callback {
public:
DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
const char* name) :
mName(name),
mValue(0),
mTraceVsync(traceVsync),
mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
mVsyncEventLabel(String8::format("VSYNC-%s", name)),
mDispSync(dispSync),
mCallbackMutex(),
mVsyncMutex(),
mPhaseOffset(phaseOffset),
mEnabled(false) {}
~DispSyncSource() override = default;
void setVSyncEnabled(bool enable) override {
Mutex::Autolock lock(mVsyncMutex);
if (enable) {
status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
static_cast<DispSync::Callback*>(this));
if (err != NO_ERROR) {
ALOGE("error registering vsync callback: %s (%d)",
strerror(-err), err);
}
//ATRACE_INT(mVsyncOnLabel.string(), 1);
} else {
status_t err = mDispSync->removeEventListener(
static_cast<DispSync::Callback*>(this));
if (err != NO_ERROR) {
ALOGE("error unregistering vsync callback: %s (%d)",
strerror(-err), err);
}
//ATRACE_INT(mVsyncOnLabel.string(), 0);
}
mEnabled = enable;
}
void setCallback(VSyncSource::Callback* callback) override{
Mutex::Autolock lock(mCallbackMutex);
mCallback = callback;
}
void setPhaseOffset(nsecs_t phaseOffset) override {
Mutex::Autolock lock(mVsyncMutex);
// Normalize phaseOffset to [0, period)
auto period = mDispSync->getPeriod();
phaseOffset %= period;
if (phaseOffset < 0) {
// If we're here, then phaseOffset is in (-period, 0). After this
// operation, it will be in (0, period)
phaseOffset += period;
}
mPhaseOffset = phaseOffset;
// If we're not enabled, we don't need to mess with the listeners
if (!mEnabled) {
return;
}
status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
mPhaseOffset);
if (err != NO_ERROR) {
ALOGE("error changing vsync offset: %s (%d)",
strerror(-err), err);
}
}
private:
virtual void onDispSyncEvent(nsecs_t when) {
VSyncSource::Callback* callback;
{
Mutex::Autolock lock(mCallbackMutex);
callback = mCallback;
if (mTraceVsync) {
mValue = (mValue + 1) % 2;
ATRACE_INT(mVsyncEventLabel.string(), mValue);
}
}
if (callback != nullptr) {
callback->onVSyncEvent(when);
}
}
const char* const mName;
int mValue;
const bool mTraceVsync;
const String8 mVsyncOnLabel;
const String8 mVsyncEventLabel;
DispSync* mDispSync;
Mutex mCallbackMutex; // Protects the following
VSyncSource::Callback* mCallback = nullptr;
Mutex mVsyncMutex; // Protects the following
nsecs_t mPhaseOffset;
bool mEnabled;
};
class InjectVSyncSource final : public VSyncSource {
public:
InjectVSyncSource() = default;
~InjectVSyncSource() override = default;
void setCallback(VSyncSource::Callback* callback) override {
std::lock_guard<std::mutex> lock(mCallbackMutex);
mCallback = callback;
}
void onInjectSyncEvent(nsecs_t when) {
std::lock_guard<std::mutex> lock(mCallbackMutex);
if (mCallback) {
mCallback->onVSyncEvent(when);
}
}
void setVSyncEnabled(bool) override {}
void setPhaseOffset(nsecs_t) override {}
private:
std::mutex mCallbackMutex; // Protects the following
VSyncSource::Callback* mCallback = nullptr;
};
// Do not call property_set on main thread which will be blocked by init
// Use StartPropertySetThread instead.
void SurfaceFlinger::init() {
ALOGI( "SurfaceFlinger's main thread ready to run. "
"Initializing graphics H/W...");
ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Mutex::Autolock _l(mStateLock);
// start the EventThread
mEventThreadSource =
std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
true, "app");
mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
[this]() { resyncWithRateLimit(); },
impl::EventThread::InterceptVSyncsCallback(),
"appEventThread");
mSfEventThreadSource =
std::make_unique<DispSyncSource>(&mPrimaryDispSync,
SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
mSFEventThread =
std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
[this]() { resyncWithRateLimit(); },
[this](nsecs_t timestamp) {
mInterceptor->saveVSyncEvent(timestamp);
},
"sfEventThread");
mEventQueue->setEventThread(mSFEventThread.get());
mVsyncModulator.setEventThread(mSFEventThread.get());
// Get a RenderEngine for the given display / config (can't fail)
getBE().mRenderEngine =
RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
hasWideColorDisplay
? RE::RenderEngine::WIDE_COLOR_SUPPORT
: 0);
LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
"Starting with vr flinger active is not currently supported.");
getBE().mHwc.reset(
new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
// Process any initial hotplug and resulting display changes.
processDisplayHotplugEventsLocked();
LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
"Registered composer callback but didn't create the default primary display");
// make the default display GLContext current so that we can create textures
// when creating Layers (which may happens before we render something)
getDefaultDisplayDeviceLocked()->makeCurrent();
if (useVrFlinger) {
auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
// This callback is called from the vr flinger dispatch thread. We
// need to call signalTransaction(), which requires holding
// mStateLock when we're not on the main thread. Acquiring
// mStateLock from the vr flinger dispatch thread might trigger a
// deadlock in surface flinger (see b/66916578), so post a message
// to be handled on the main thread instead.
sp<LambdaMessage> message = new LambdaMessage([=]() {
ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
mVrFlingerRequestsDisplay = requestDisplay;
signalTransaction();
});
postMessageAsync(message);
};
mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
vrFlingerRequestDisplayCallback);
if (!mVrFlinger) {
ALOGE("Failed to start vrflinger");
}
}
mEventControlThread = std::make_unique<impl::EventControlThread>(
[this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
// initialize our drawing state
mDrawingState = mCurrentState;
// set initial conditions (e.g. unblank default device)
initializeDisplays();
getBE().mRenderEngine->primeCache();
// Inform native graphics APIs whether the present timestamp is supported:
if (getHwComposer().hasCapability(
HWC2::Capability::PresentFenceIsNotReliable)) {
mStartPropertySetThread = new StartPropertySetThread(false);
} else {
mStartPropertySetThread = new StartPropertySetThread(true);
}
if (mStartPropertySetThread->Start() != NO_ERROR) {
ALOGE("Run StartPropertySetThread failed!");
}
mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
Dataspace::SRGB_LINEAR);
ALOGV("Done initializing");
}
void SurfaceFlinger::readPersistentProperties() {
Mutex::Autolock _l(mStateLock);
char value[PROPERTY_VALUE_MAX];
property_get("persist.sys.sf.color_saturation", value, "1.0");
mGlobalSaturationFactor = atof(value);
updateColorMatrixLocked();
ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
property_get("persist.sys.sf.native_mode", value, "0");
mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
}
void SurfaceFlinger::startBootAnim() {
// Start boot animation service by setting a property mailbox
// if property setting thread is already running, Start() will be just a NOP
mStartPropertySetThread->Start();
// Wait until property was set
if (mStartPropertySetThread->join() != NO_ERROR) {
ALOGE("Join StartPropertySetThread failed!");
}
}
size_t SurfaceFlinger::getMaxTextureSize() const {
return getBE().mRenderEngine->getMaxTextureSize();
}
size_t SurfaceFlinger::getMaxViewportDims() const {
return getBE().mRenderEngine->getMaxViewportDims();
}
// ----------------------------------------------------------------------------
bool SurfaceFlinger::authenticateSurfaceTexture(
const sp<IGraphicBufferProducer>& bufferProducer) const {
Mutex::Autolock _l(mStateLock);
return authenticateSurfaceTextureLocked(bufferProducer);
}
bool SurfaceFlinger::authenticateSurfaceTextureLocked(
const sp<IGraphicBufferProducer>& bufferProducer) const {
sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
}
status_t SurfaceFlinger::getSupportedFrameTimestamps(
std::vector<FrameEvent>* outSupported) const {
*outSupported = {
FrameEvent::REQUESTED_PRESENT,
FrameEvent::ACQUIRE,
FrameEvent::LATCH,
FrameEvent::FIRST_REFRESH_START,
FrameEvent::LAST_REFRESH_START,
FrameEvent::GPU_COMPOSITION_DONE,
FrameEvent::DEQUEUE_READY,
FrameEvent::RELEASE,
};
ConditionalLock _l(mStateLock,
std::this_thread::get_id() != mMainThreadId);
if (!getHwComposer().hasCapability(
HWC2::Capability::PresentFenceIsNotReliable)) {
outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
}
return NO_ERROR;
}
status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
Vector<DisplayInfo>* configs) {
if (configs == nullptr || display.get() == nullptr) {
return BAD_VALUE;
}
if (!display.get())
return NAME_NOT_FOUND;
int32_t type = NAME_NOT_FOUND;
for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
if (display == mBuiltinDisplays[i]) {
type = i;
break;
}
}
if (type < 0) {
return type;
}
// TODO: Not sure if display density should handled by SF any longer
class Density {
static int getDensityFromProperty(char const* propName) {
char property[PROPERTY_VALUE_MAX];
int density = 0;
if (property_get(propName, property, nullptr) > 0) {
density = atoi(property);
}
return density;
}
public:
static int getEmuDensity() {
return getDensityFromProperty("qemu.sf.lcd_density"); }
static int getBuildDensity() {
return getDensityFromProperty("ro.sf.lcd_density"); }
};
configs->clear();
ConditionalLock _l(mStateLock,
std::this_thread::get_id() != mMainThreadId);
for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
DisplayInfo info = DisplayInfo();
float xdpi = hwConfig->getDpiX();
float ydpi = hwConfig->getDpiY();
if (type == DisplayDevice::DISPLAY_PRIMARY) {
// The density of the device is provided by a build property
float density = Density::getBuildDensity() / 160.0f;
if (density == 0) {
// the build doesn't provide a density -- this is wrong!
// use xdpi instead
ALOGE("ro.sf.lcd_density must be defined as a build property");
density = xdpi / 160.0f;
}
if (Density::getEmuDensity()) {
// if "qemu.sf.lcd_density" is specified, it overrides everything
xdpi = ydpi = density = Density::getEmuDensity();
density /= 160.0f;
}
info.density = density;
// TODO: this needs to go away (currently needed only by webkit)
sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
info.orientation = hw ? hw->getOrientation() : 0;
} else {
// TODO: where should this value come from?
static const int TV_DENSITY = 213;
info.density = TV_DENSITY / 160.0f;
info.orientation = 0;
}
info.w = hwConfig->getWidth();
info.h = hwConfig->getHeight();
info.xdpi = xdpi;
info.ydpi = ydpi;
info.fps = 1e9 / hwConfig->getVsyncPeriod();
info.appVsyncOffset = vsyncPhaseOffsetNs;
// This is how far in advance a buffer must be queued for
// presentation at a given time. If you want a buffer to appear
// on the screen at time N, you must submit the buffer before
// (N - presentationDeadline).
//
// Normally it's one full refresh period (to give SF a chance to
// latch the buffer), but this can be reduced by configuring a
// DispSync offset. Any additional delays introduced by the hardware
// composer or panel must be accounted for here.
//
// We add an additional 1ms to allow for processing time and
// differences between the ideal and actual refresh rate.
info.presentationDeadline = hwConfig->getVsyncPeriod() -
sfVsyncPhaseOffsetNs + 1000000;
// All non-virtual displays are currently considered secure.
info.secure = true;
if (type == DisplayDevice::DISPLAY_PRIMARY &&
mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
std::swap(info.w, info.h);
}
configs->push_back(info);
}
return NO_ERROR;
}
status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
DisplayStatInfo* stats) {
if (stats == nullptr) {
return BAD_VALUE;
}
// FIXME for now we always return stats for the primary display
memset(stats, 0, sizeof(*stats));
stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
return NO_ERROR;
}
int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
if (display == nullptr) {
ALOGE("%s : display is nullptr", __func__);
return BAD_VALUE;
}
sp<const DisplayDevice> device(getDisplayDevice(display));
if (device != nullptr) {
return device->getActiveConfig();
}
return BAD_VALUE;
}
void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
this);
int32_t type = hw->getDisplayType();
int currentMode = hw->getActiveConfig();
if (mode == currentMode) {
ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
return;
}
if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
ALOGW("Trying to set config for virtual display");
return;
}
hw->setActiveConfig(mode);
getHwComposer().setActiveConfig(type, mode);
}
status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
class MessageSetActiveConfig: public MessageBase {
SurfaceFlinger& mFlinger;
sp<IBinder> mDisplay;
int mMode;
public:
MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
int mode) :
mFlinger(flinger), mDisplay(disp) { mMode = mode; }
virtual bool handler() {
Vector<DisplayInfo> configs;
mFlinger.getDisplayConfigs(mDisplay, &configs);
if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
ALOGE("Attempt to set active config = %d for display with %zu configs",
mMode, configs.size());
return true;
}
sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
if (hw == nullptr) {
ALOGE("Attempt to set active config = %d for null display %p",
mMode, mDisplay.get());
} else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
ALOGW("Attempt to set active config = %d for virtual display",
mMode);
} else {
mFlinger.setActiveConfigInternal(hw, mMode);
}
return true;
}
};
sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
postMessageSync(msg);
return NO_ERROR;
}
status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Vector<ColorMode>* outColorModes) {
if ((outColorModes == nullptr) || (display.get() == nullptr)) {
return BAD_VALUE;
}
if (!display.get()) {
return NAME_NOT_FOUND;
}
int32_t type = NAME_NOT_FOUND;
for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
if (display == mBuiltinDisplays[i]) {
type = i;
break;
}
}
if (type < 0) {
return type;
}
std::vector<ColorMode> modes;
{
ConditionalLock _l(mStateLock,
std::this_thread::get_id() != mMainThreadId);
modes = getHwComposer().getColorModes(type);
}
outColorModes->clear();
std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
return NO_ERROR;
}
ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
sp<const DisplayDevice> device(getDisplayDevice(display));
if (device != nullptr) {
return device->getActiveColorMode();
}
return static_cast<ColorMode>(BAD_VALUE);
}
void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
ColorMode mode, Dataspace dataSpace,
RenderIntent renderIntent) {
int32_t type = hw->getDisplayType();
ColorMode currentMode = hw->getActiveColorMode();
Dataspace currentDataSpace = hw->getCompositionDataSpace();
RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
if (mode == currentMode && dataSpace == currentDataSpace &&
renderIntent == currentRenderIntent) {
return;
}
if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
ALOGW("Trying to set config for virtual display");
return;
}
hw->setActiveColorMode(mode);
hw->setCompositionDataSpace(dataSpace);
hw->setActiveRenderIntent(renderIntent);
getHwComposer().setActiveColorMode(type, mode, renderIntent);
ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
decodeColorMode(mode).c_str(), mode,
decodeRenderIntent(renderIntent).c_str(), renderIntent,
hw->getDisplayType());
}
status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
ColorMode colorMode) {
class MessageSetActiveColorMode: public MessageBase {
SurfaceFlinger& mFlinger;
sp<IBinder> mDisplay;
ColorMode mMode;
public:
MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
ColorMode mode) :
mFlinger(flinger), mDisplay(disp) { mMode = mode; }
virtual bool handler() {
Vector<ColorMode> modes;
mFlinger.getDisplayColorModes(mDisplay, &modes);
bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
if (mMode < ColorMode::NATIVE || !exists) {
ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
return true;
}
sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
if (hw == nullptr) {
ALOGE("Attempt to set active color mode %s (%d) for null display %p",
decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
} else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
ALOGW("Attempt to set active color mode %s %d for virtual display",
decodeColorMode(mMode).c_str(), mMode);
} else {
mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
RenderIntent::COLORIMETRIC);
}
return true;
}
};
sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
postMessageSync(msg);
return NO_ERROR;
}
status_t SurfaceFlinger::clearAnimationFrameStats() {
Mutex::Autolock _l(mStateLock);
mAnimFrameTracker.clearStats();
return NO_ERROR;
}
status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
Mutex::Autolock _l(mStateLock);
mAnimFrameTracker.getStats(outStats);
return NO_ERROR;
}
status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
HdrCapabilities* outCapabilities) const {
Mutex::Autolock _l(mStateLock);
sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
if (displayDevice == nullptr) {
ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
return BAD_VALUE;
}
// At this point the DisplayDeivce should already be set up,
// meaning the luminance information is already queried from
// hardware composer and stored properly.
const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
*outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
capabilities.getDesiredMaxLuminance(),
capabilities.getDesiredMaxAverageLuminance(),
capabilities.getDesiredMinLuminance());
return NO_ERROR;
}
status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
Mutex::Autolock _l(mStateLock);
if (mInjectVSyncs == enable) {
return;
}
if (enable) {
ALOGV("VSync Injections enabled");
if (mVSyncInjector.get() == nullptr) {
mVSyncInjector = std::make_unique<InjectVSyncSource>();
mInjectorEventThread = std::make_unique<
impl::EventThread>(mVSyncInjector.get(),
[this]() { resyncWithRateLimit(); },
impl::EventThread::InterceptVSyncsCallback(),
"injEventThread");
}
mEventQueue->setEventThread(mInjectorEventThread.get());
} else {
ALOGV("VSync Injections disabled");
mEventQueue->setEventThread(mSFEventThread.get());
}
mInjectVSyncs = enable;
});
postMessageSync(enableVSyncInjections);
return NO_ERROR;
}
status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Mutex::Autolock _l(mStateLock);
if (!mInjectVSyncs) {
ALOGE("VSync Injections not enabled");
return BAD_VALUE;
}
if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
ALOGV("Injecting VSync inside SurfaceFlinger");
mVSyncInjector->onInjectSyncEvent(when);
}
return NO_ERROR;
}
status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
NO_THREAD_SAFETY_ANALYSIS {
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
if ((uid != AID_SHELL) &&
!PermissionCache::checkPermission(sDump, pid, uid)) {
ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}
// Try to acquire a lock for 1s, fail gracefully
const status_t err = mStateLock.timedLock(s2ns(1));
const bool locked = (err == NO_ERROR);
if (!locked) {
ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
return TIMED_OUT;
}
outLayers->clear();
mCurrentState.traverseInZOrder([&](Layer* layer) {
outLayers->push_back(layer->getLayerDebugInfo());
});
mStateLock.unlock();
return NO_ERROR;
}
// ----------------------------------------------------------------------------
sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
ISurfaceComposer::VsyncSource vsyncSource) {
if (vsyncSource == eVsyncSourceSurfaceFlinger) {
return mSFEventThread->createEventConnection();
} else {
return mEventThread->createEventConnection();
}
}
// ----------------------------------------------------------------------------
void SurfaceFlinger::waitForEvent() {
mEventQueue->waitMessage();
}
void SurfaceFlinger::signalTransaction() {
mEventQueue->invalidate();
}
void SurfaceFlinger::signalLayerUpdate() {
mEventQueue->invalidate();
}
void SurfaceFlinger::signalRefresh() {
mRefreshPending = true;
mEventQueue->refresh();
}
status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
nsecs_t reltime, uint32_t /* flags */) {
return mEventQueue->postMessage(msg, reltime);
}
status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
nsecs_t reltime, uint32_t /* flags */) {
status_t res = mEventQueue->postMessage(msg, reltime);
if (res == NO_ERROR) {
msg->wait();
}
return res;
}
void SurfaceFlinger::run() {
do {
waitForEvent();
} while (true);
}
void SurfaceFlinger::enableHardwareVsync() {
Mutex::Autolock _l(mHWVsyncLock);
if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
mPrimaryDispSync.beginResync();
//eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
mEventControlThread->setVsyncEnabled(true);
mPrimaryHWVsyncEnabled = true;
}
}
void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Mutex::Autolock _l(mHWVsyncLock);
if (makeAvailable) {
mHWVsyncAvailable = true;
} else if (!mHWVsyncAvailable) {
// Hardware vsync is not currently available, so abort the resync
// attempt for now
return;
}
const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
const nsecs_t period = activeConfig->getVsyncPeriod();
mPrimaryDispSync.reset();
mPrimaryDispSync.setPeriod(period);
if (!mPrimaryHWVsyncEnabled) {
mPrimaryDispSync.beginResync();
//eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
mEventControlThread->setVsyncEnabled(true);
mPrimaryHWVsyncEnabled = true;
}
}
void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Mutex::Autolock _l(mHWVsyncLock);
if (mPrimaryHWVsyncEnabled) {
//eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
mEventControlThread->setVsyncEnabled(false);
mPrimaryDispSync.endResync();
mPrimaryHWVsyncEnabled = false;
}
if (makeUnavailable) {
mHWVsyncAvailable = false;
}
}
void SurfaceFlinger::resyncWithRateLimit() {
static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
// No explicit locking is needed here since EventThread holds a lock while calling this method
static nsecs_t sLastResyncAttempted = 0;
const nsecs_t now = systemTime();
if (now - sLastResyncAttempted > kIgnoreDelay) {
resyncToHardwareVsync(false);
}
sLastResyncAttempted = now;
}
void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
hwc2_display_t displayId, int64_t timestamp) {
Mutex::Autolock lock(mStateLock);
// Ignore any vsyncs from a previous hardware composer.
if (sequenceId != getBE().mComposerSequenceId) {
return;
}
int32_t type;
if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
return;
}
bool needsHwVsync = false;
{ // Scope for the lock
Mutex::Autolock _l(mHWVsyncLock);
if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
}
}
if (needsHwVsync) {
enableHardwareVsync();
} else {
disableHardwareVsync(false);
}
}
void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
*compositorTiming = getBE().mCompositorTiming;
}
void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
HWC2::Connection connection) {
ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
connection == HWC2::Connection::Connected ? "connected" : "disconnected");
// Ignore events that do not have the right sequenceId.
if (sequenceId != getBE().mComposerSequenceId) {
return;
}
// Only lock if we're not on the main thread. This function is normally
// called on a hwbinder thread, but for the primary display it's called on
// the main thread with the state lock already held, so don't attempt to
// acquire it here.
ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
if (std::this_thread::get_id() == mMainThreadId) {
// Process all pending hot plug events immediately if we are on the main thread.
processDisplayHotplugEventsLocked();
}
setTransactionFlags(eDisplayTransactionNeeded);
}
void SurfaceFlinger::onRefreshReceived(int sequenceId,
hwc2_display_t /*display*/) {
Mutex::Autolock lock(mStateLock);
if (sequenceId != getBE().mComposerSequenceId) {
return;
}
repaintEverything();
}
void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
ATRACE_CALL();
Mutex::Autolock lock(mStateLock);
getHwComposer().setVsyncEnabled(disp,
enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
}
// Note: it is assumed the caller holds |mStateLock| when this is called
void SurfaceFlinger::resetDisplayState() {
disableHardwareVsync(true);
// Clear the drawing state so that the logic inside of
// handleTransactionLocked will fire. It will determine the delta between
// mCurrentState and mDrawingState and re-apply all changes when we make the
// transition.
mDrawingState.displays.clear();
getRenderEngine().resetCurrentSurface();
mDisplays.clear();
}
void SurfaceFlinger::updateVrFlinger() {
if (!mVrFlinger)
return;
bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
return;
}
if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
ALOGE("Vr flinger is only supported for remote hardware composer"
" service connections. Ignoring request to transition to vr"
" flinger.");
mVrFlingerRequestsDisplay = false;
return;
}
Mutex::Autolock _l(mStateLock);
int currentDisplayPowerMode = getDisplayDeviceLocked(
mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
if (!vrFlingerRequestsDisplay) {
mVrFlinger->SeizeDisplayOwnership();
}
resetDisplayState();
getBE().mHwc.reset(); // Delete the current instance before creating the new one
getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
"Switched to non-remote hardware composer");
if (vrFlingerRequestsDisplay) {
mVrFlinger->GrantDisplayOwnership();
} else {
enableHardwareVsync();
}
mVisibleRegionsDirty = true;
invalidateHwcGeometry();
// Re-enable default display.
sp<DisplayDevice> hw(getDisplayDeviceLocked(
mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
// Reset the timing values to account for the period of the swapped in HWC
const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
const nsecs_t period = activeConfig->getVsyncPeriod();
mAnimFrameTracker.setDisplayRefreshPeriod(period);
// Use phase of 0 since phase is not known.
// Use latency of 0, which will snap to the ideal latency.
setCompositorTimingSnapped(0, period, 0);
android_atomic_or(1, &mRepaintEverything);
setTransactionFlags(eDisplayTransactionNeeded);
}
void SurfaceFlinger::onMessageReceived(int32_t what) {
ATRACE_CALL();
switch (what) {
case MessageQueue::INVALIDATE: {
bool frameMissed = !mHadClientComposition &&
mPreviousPresentFence != Fence::NO_FENCE &&
(mPreviousPresentFence->getSignalTime() ==
Fence::SIGNAL_TIME_PENDING);
ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
if (frameMissed) {
mTimeStats.incrementMissedFrames();
if (mPropagateBackpressure) {
signalLayerUpdate();
break;
}
}
// Now that we're going to make it to the handleMessageTransaction()
// call below it's safe to call updateVrFlinger(), which will
// potentially trigger a display handoff.
updateVrFlinger();
bool refreshNeeded = handleMessageTransaction();
refreshNeeded |= handleMessageInvalidate();
refreshNeeded |= mRepaintEverything;
if (refreshNeeded) {
// Signal a refresh if a transaction modified the window state,
// a new buffer was latched, or if HWC has requested a full
// repaint
signalRefresh();
}
break;
}
case MessageQueue::REFRESH: {
handleMessageRefresh();
break;
}
}
}
bool SurfaceFlinger::handleMessageTransaction() {
uint32_t transactionFlags = peekTransactionFlags();
if (transactionFlags) {
handleTransaction(transactionFlags);
return true;
}
return false;
}
bool SurfaceFlinger::handleMessageInvalidate() {
ATRACE_CALL();
return handlePageFlip();
}
void SurfaceFlinger::handleMessageRefresh() {
ATRACE_CALL();
mRefreshPending = false;
nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
preComposition(refreshStartTime);
rebuildLayerStacks();
setUpHWComposer();
doDebugFlashRegions();
doTracing("handleRefresh");
logLayerStats();
doComposition();
postComposition(refreshStartTime);
mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
mHadClientComposition = false;
for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
mHadClientComposition = mHadClientComposition ||
getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
}
mVsyncModulator.onRefreshed(mHadClientComposition);
mLayersWithQueuedFrames.clear();
}
void SurfaceFlinger::doDebugFlashRegions()
{
// is debugging enabled
if (CC_LIKELY(!mDebugRegion))
return;
const bool repaintEverything = mRepaintEverything;
for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
const sp<DisplayDevice>& hw(mDisplays[dpy]);
if (hw->isDisplayOn()) {
// transform the dirty region into this screen's coordinate space
const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
if (!dirtyRegion.isEmpty()) {
// redraw the whole screen
doComposeSurfaces(hw);
// and draw the dirty region
const int32_t height = hw->getHeight();
auto& engine(getRenderEngine());
engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
hw->swapBuffers(getHwComposer());
}
}
}
postFramebuffer();
if (mDebugRegion > 1) {
usleep(mDebugRegion * 1000);
}
for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
auto& displayDevice = mDisplays[displayId];
if (!displayDevice->isDisplayOn()) {
continue;
}
status_t result = displayDevice->prepareFrame(*getBE().mHwc);
ALOGE_IF(result != NO_ERROR,
"prepareFrame for display %zd failed:"
" %d (%s)",
displayId, result, strerror(-result));
}
}
void SurfaceFlinger::doTracing(const char* where) {
ATRACE_CALL();
ATRACE_NAME(where);
if (CC_UNLIKELY(mTracing.isEnabled())) {
mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
}
}
void SurfaceFlinger::logLayerStats() {
ATRACE_CALL();
if (CC_UNLIKELY(mLayerStats.isEnabled())) {
int32_t hwcId = -1;
for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
if (displayDevice->isPrimary()) {
hwcId = displayDevice->getHwcDisplayId();
break;
}
}
if (hwcId < 0) {
ALOGE("LayerStats: Hmmm, no primary display?");
return;
}
mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
}
}
void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
{
ATRACE_CALL();
ALOGV("preComposition");
bool needExtraInvalidate = false;
mDrawingState.traverseInZOrder([&](Layer* layer) {
if (layer->onPreComposition(refreshStartTime)) {
needExtraInvalidate = true;
}
});
if (needExtraInvalidate) {
signalLayerUpdate();
}
}
void SurfaceFlinger::updateCompositorTiming(
nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
std::shared_ptr<FenceTime>& presentFenceTime) {
// Update queue of past composite+present times and determine the
// most recently known composite to present latency.
getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
nsecs_t compositeToPresentLatency = -1;
while (!getBE().mCompositePresentTimes.empty()) {
SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
// Cached values should have been updated before calling this method,
// which helps avoid duplicate syscalls.
nsecs_t displayTime = cpt.display->getCachedSignalTime();
if (displayTime == Fence::SIGNAL_TIME_PENDING) {
break;
}
compositeToPresentLatency = displayTime - cpt.composite;
getBE().mCompositePresentTimes.pop();
}
// Don't let mCompositePresentTimes grow unbounded, just in case.
while (getBE().mCompositePresentTimes.size() > 16) {
getBE().mCompositePresentTimes.pop();
}
setCompositorTimingSnapped(
vsyncPhase, vsyncInterval, compositeToPresentLatency);
}
void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
// Integer division and modulo round toward 0 not -inf, so we need to
// treat negative and positive offsets differently.
nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
(vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
((-sfVsyncPhaseOffsetNs) % vsyncInterval);
// Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
if (idealLatency <= 0) {
idealLatency = vsyncInterval;
}
// Snap the latency to a value that removes scheduling jitter from the
// composition and present times, which often have >1ms of jitter.
// Reducing jitter is important if an app attempts to extrapolate
// something (such as user input) to an accurate diasplay time.
// Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
// with (presentLatency % interval).
nsecs_t bias = vsyncInterval / 2;
int64_t extraVsyncs =
(compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
getBE().mCompositorTiming.interval = vsyncInterval;
getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
}
void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
{
ATRACE_CALL();
ALOGV("postComposition");
// Release any buffers which were replaced this frame
nsecs_t dequeueReadyTime = systemTime();
for (auto& layer : mLayersWithQueuedFrames) {
layer->releasePendingBuffer(dequeueReadyTime);
}
// |mStateLock| not needed as we are on the main thread
const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
getBE().mGlCompositionDoneTimeline.updateSignalTimes();
std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
glCompositionDoneFenceTime =
std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
} else {
glCompositionDoneFenceTime = FenceTime::NO_FENCE;
}
getBE().mDisplayTimeline.updateSignalTimes();
sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
getBE().mDisplayTimeline.push(presentFenceTime);
nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
// We use the refreshStartTime which might be sampled a little later than
// when we started doing work for this frame, but that should be okay
// since updateCompositorTiming has snapping logic.
updateCompositorTiming(
vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
CompositorTiming compositorTiming;
{
std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
compositorTiming = getBE().mCompositorTiming;
}
mDrawingState.traverseInZOrder([&](Layer* layer) {
bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
presentFenceTime, compositorTiming);
if (frameLatched) {
recordBufferingStats(layer->getName().string(),
layer->getOccupancyHistory(false));
}
});
if (presentFenceTime->isValid()) {
if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
enableHardwareVsync();
} else {
disableHardwareVsync(false);
}
}
if (!hasSyncFramework) {
if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
enableHardwareVsync();
}
}
if (mAnimCompositionPending) {
mAnimCompositionPending = false;
if (presentFenceTime->isValid()) {
mAnimFrameTracker.setActualPresentFence(
std::move(presentFenceTime));
} else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
// The HWC doesn't support present fences, so use the refresh
// timestamp instead.
nsecs_t presentTime =
getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
mAnimFrameTracker.setActualPresentTime(presentTime);
}
mAnimFrameTracker.advanceFrame();
}
mTimeStats.incrementTotalFrames();
if (mHadClientComposition) {
mTimeStats.incrementClientCompositionFrames();
}
if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
hw->getPowerMode() == HWC_POWER_MODE_OFF) {
return;
}
nsecs_t currentTime = systemTime();
if (mHasPoweredOff) {
mHasPoweredOff = false;
} else {
nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
getBE().mFrameBuckets[numPeriods] += elapsedTime;
} else {
getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
}
getBE().mTotalTime += elapsedTime;
}
getBE().mLastSwapTime = currentTime;
}
void SurfaceFlinger::rebuildLayerStacks() {
ATRACE_CALL();
ALOGV("rebuildLayerStacks");
// rebuild the visible layer list per screen
if (CC_UNLIKELY(mVisibleRegionsDirty)) {
ATRACE_NAME("rebuildLayerStacks VR Dirty");
mVisibleRegionsDirty = false;
invalidateHwcGeometry();
for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Region opaqueRegion;
Region dirtyRegion;
Vector<sp<Layer>> layersSortedByZ;
Vector<sp<Layer>> layersNeedingFences;
const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
const Transform& tr(displayDevice->getTransform());
const Rect bounds(displayDevice->getBounds());
if (displayDevice->isDisplayOn()) {
computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
mDrawingState.traverseInZOrder([&](Layer* layer) {
bool hwcLayerDestroyed = false;
if (layer->belongsToDisplay(displayDevice->getLayerStack(),
displayDevice->isPrimary())) {
Region drawRegion(tr.transform(
layer->visibleNonTransparentRegion));
drawRegion.andSelf(bounds);
if (!drawRegion.isEmpty()) {
layersSortedByZ.add(layer);
} else {
// Clear out the HWC layer if this layer was
// previously visible, but no longer is
hwcLayerDestroyed = layer->destroyHwcLayer(
displayDevice->getHwcDisplayId());
}
} else {
// WM changes displayDevice->layerStack upon sleep/awake.
// Here we make sure we delete the HWC layers even if
// WM changed their layer stack.
hwcLayerDestroyed = layer->destroyHwcLayer(
displayDevice->getHwcDisplayId());
}
// If a layer is not going to get a release fence because
// it is invisible, but it is also going to release its
// old buffer, add it to the list of layers needing
// fences.
if (hwcLayerDestroyed) {
auto found = std::find(mLayersWithQueuedFrames.cbegin(),
mLayersWithQueuedFrames.cend(), layer);
if (found != mLayersWithQueuedFrames.cend()) {
layersNeedingFences.add(layer);
}
}
});
}
displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
displayDevice->setLayersNeedingFences(layersNeedingFences);
displayDevice->undefinedRegion.set(bounds);
displayDevice->undefinedRegion.subtractSelf(
tr.transform(opaqueRegion));
displayDevice->dirtyRegion.orSelf(dirtyRegion);
}
}
}
// Returns a data space that fits all visible layers. The returned data space
// can only be one of
// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
// - Dataspace::DISPLAY_P3
// The returned HDR data space is one of
// - Dataspace::UNKNOWN
// - Dataspace::BT2020_HLG
// - Dataspace::BT2020_PQ
Dataspace SurfaceFlinger::getBestDataspace(
const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
Dataspace bestDataSpace = Dataspace::SRGB;
*outHdrDataSpace = Dataspace::UNKNOWN;
for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
switch (layer->getDataSpace()) {
case Dataspace::V0_SCRGB:
case Dataspace::V0_SCRGB_LINEAR:
case Dataspace::DISPLAY_P3:
bestDataSpace = Dataspace::DISPLAY_P3;
break;
case Dataspace::BT2020_PQ:
case Dataspace::BT2020_ITU_PQ:
*outHdrDataSpace = Dataspace::BT2020_PQ;
break;
case Dataspace::BT2020_HLG:
case Dataspace::BT2020_ITU_HLG:
// When there's mixed PQ content and HLG content, we set the HDR
// data space to be BT2020_PQ and convert HLG to PQ.
if (*outHdrDataSpace == Dataspace::UNKNOWN) {
*outHdrDataSpace = Dataspace::BT2020_HLG;
}
break;
default:
break;
}
}
return bestDataSpace;
}
// Pick the ColorMode / Dataspace for the display device.
void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
ColorMode* outMode, Dataspace* outDataSpace,
RenderIntent* outRenderIntent) const {
if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
*outMode = ColorMode::NATIVE;
*outDataSpace = Dataspace::UNKNOWN;
*outRenderIntent = RenderIntent::COLORIMETRIC;
return;
}
Dataspace hdrDataSpace;
Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
// respect hdrDataSpace only when there is no legacy HDR support
const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
!displayDevice->hasLegacyHdrSupport(hdrDataSpace);
if (isHdr) {
bestDataSpace = hdrDataSpace;
}
RenderIntent intent;
switch (mDisplayColorSetting) {
case DisplayColorSetting::MANAGED:
case DisplayColorSetting::UNMANAGED:
intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
break;
case DisplayColorSetting::ENHANCED:
intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
break;
default: // vendor display color setting
intent = static_cast<RenderIntent>(mDisplayColorSetting);
break;
}
displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
}
void SurfaceFlinger::setUpHWComposer() {
ATRACE_CALL();
ALOGV("setUpHWComposer");
for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
// If nothing has changed (!dirty), don't recompose.
// If something changed, but we don't currently have any visible layers,
// and didn't when we last did a composition, then skip it this time.
// The second rule does two things:
// - When all layers are removed from a display, we'll emit one black
// frame, then nothing more until we get new layers.
// - When a display is created with a private layer stack, we won't
// emit any black frames until a layer is added to the layer stack.
bool mustRecompose = dirty && !(empty && wasEmpty);
ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
"dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
mustRecompose ? "doing" : "skipping",
dirty ? "+" : "-",
empty ? "+" : "-",
wasEmpty ? "+" : "-");
mDisplays[dpy]->beginFrame(mustRecompose);
if (mustRecompose) {
mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
}
}
// build the h/w work list
if (CC_UNLIKELY(mGeometryInvalid)) {
mGeometryInvalid = false;
for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
const auto hwcId = displayDevice->getHwcDisplayId();
if (hwcId >= 0) {
const Vector<sp<Layer>>& currentLayers(
displayDevice->getVisibleLayersSortedByZ());
for (size_t i = 0; i < currentLayers.size(); i++) {
const auto& layer = currentLayers[i];
if (!layer->hasHwcLayer(hwcId)) {
if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
layer->forceClientComposition(hwcId);
continue;
}
}
layer->setGeometry(displayDevice, i);
if (mDebugDisableHWC || mDebugRegion) {
layer->forceClientComposition(hwcId);
}
}
}
}
}
// Set the per-frame data
for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
auto& displayDevice = mDisplays[displayId];
const auto hwcId = displayDevice->getHwcDisplayId();
if (hwcId < 0) {
continue;
}
if (mDrawingState.colorMatrixChanged) {
displayDevice->setColorTransform(mDrawingState.colorMatrix);
status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
"display %zd: %d", displayId, result);
}
for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
if (layer->isHdrY410()) {
layer->forceClientComposition(hwcId);
} else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
!displayDevice->hasHDR10Support()) {
layer->forceClientComposition(hwcId);
} else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
!displayDevice->hasHLGSupport()) {
layer->forceClientComposition(hwcId);
}
if (layer->getForceClientComposition(hwcId)) {
ALOGV("[%s] Requesting Client composition", layer->getName().string());
layer->setCompositionType(hwcId, HWC2::Composition::Client);
continue;
}
layer->setPerFrameData(displayDevice);
}
if (hasWideColorDisplay) {
ColorMode colorMode;
Dataspace dataSpace;
RenderIntent renderIntent;
pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
}
}
mDrawingState.colorMatrixChanged = false;
for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
auto& displayDevice = mDisplays[displayId];
if (!displayDevice->isDisplayOn()) {
continue;
}
status_t result = displayDevice->prepareFrame(*getBE().mHwc);
ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
" %d (%s)", displayId, result, strerror(-result));
}
}
void SurfaceFlinger::doComposition() {
ATRACE_CALL();
ALOGV("doComposition");
const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
const sp<DisplayDevice>& hw(mDisplays[dpy]);
if (hw->isDisplayOn()) {
// transform the dirty region into this screen's coordinate space
const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
// repaint the framebuffer (if needed)
doDisplayComposition(hw, dirtyRegion);
hw->dirtyRegion.clear();
hw->flip();
}
}
postFramebuffer();
}
void SurfaceFlinger::postFramebuffer()
{
ATRACE_CALL();
ALOGV("postFramebuffer");
const nsecs_t now = systemTime();
mDebugInSwapBuffers = now;
for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
auto& displayDevice = mDisplays[displayId];
if (!displayDevice->isDisplayOn()) {
continue;
}
const auto hwcId = displayDevice->getHwcDisplayId();
if (hwcId >= 0) {
getBE().mHwc->presentAndGetReleaseFences(hwcId);
}
displayDevice->onSwapBuffersCompleted();
displayDevice->makeCurrent();
for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
// The layer buffer from the previous frame (if any) is released
// by HWC only when the release fence from this frame (if any) is
// signaled. Always get the release fence from HWC first.
auto hwcLayer = layer->getHwcLayer(hwcId);
sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
// If the layer was client composited in the previous frame, we
// need to merge with the previous client target acquire fence.
// Since we do not track that, always merge with the current
// client target acquire fence when it is available, even though
// this is suboptimal.
if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
releaseFence = Fence::merge("LayerRelease", releaseFence,
displayDevice->getClientTargetAcquireFence());
}
layer->onLayerDisplayed(releaseFence);
}
// We've got a list of layers needing fences, that are disjoint with
// displayDevice->getVisibleLayersSortedByZ. The best we can do is to
// supply them with the present fence.
if (!displayDevice->getLayersNeedingFences().isEmpty()) {
sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
for (auto& layer : displayDevice->getLayersNeedingFences()) {
layer->onLayerDisplayed(presentFence);
}
}
if (hwcId >= 0) {
getBE().mHwc->clearReleaseFences(hwcId);
}
}
mLastSwapBufferTime = systemTime() - now;
mDebugInSwapBuffers = 0;
// |mStateLock| not needed as we are on the main thread
if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
logFrameStats();
}
}
}
void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
{
ATRACE_CALL();
// here we keep a copy of the drawing state (that is the state that's
// going to be overwritten by handleTransactionLocked()) outside of
// mStateLock so that the side-effects of the State assignment
// don't happen with mStateLock held (which can cause deadlocks).
State drawingState(mDrawingState);
Mutex::Autolock _l(mStateLock);
const nsecs_t now = systemTime();
mDebugInTransaction = now;
// Here we're guaranteed that some transaction flags are set
// so we can call handleTransactionLocked() unconditionally.
// We call getTransactionFlags(), which will also clear the flags,
// with mStateLock held to guarantee that mCurrentState won't change
// until the transaction is committed.
mVsyncModulator.onTransactionHandled();
transactionFlags = getTransactionFlags(eTransactionMask);
handleTransactionLocked(transactionFlags);
mLastTransactionTime = systemTime() - now;
mDebugInTransaction = 0;
invalidateHwcGeometry();
// here the transaction has been committed
}
DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
HWC2::Connection connection) const {
// Figure out whether the event is for the primary display or an
// external display by matching the Hwc display id against one for a
// connected display. If we did not find a match, we then check what
// displays are not already connected to determine the type. If we don't
// have a connected primary display, we assume the new display is meant to
// be the primary display, and then if we don't have an external display,
// we assume it is that.
const auto primaryDisplayId =
getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
const auto externalDisplayId =
getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
if (primaryDisplayId && primaryDisplayId == display) {
return DisplayDevice::DISPLAY_PRIMARY;
} else if (externalDisplayId && externalDisplayId == display) {
return DisplayDevice::DISPLAY_EXTERNAL;
} else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
return DisplayDevice::DISPLAY_PRIMARY;
} else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
return DisplayDevice::DISPLAY_EXTERNAL;
}
return DisplayDevice::DISPLAY_ID_INVALID;
}
void SurfaceFlinger::processDisplayHotplugEventsLocked() {
for (const auto& event : mPendingHotplugEvents) {
auto displayType = determineDisplayType(event.display, event.connection);
if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
continue;
}
if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
ALOGE("External displays are not supported by the vr hardware composer.");
continue;
}
getBE().mHwc->onHotplug(event.display, displayType, event.connection);
if (event.connection == HWC2::Connection::Connected) {
if (!mBuiltinDisplays[displayType].get()) {
ALOGV("Creating built in display %d", displayType);
mBuiltinDisplays[displayType] = new BBinder();
// All non-virtual displays are currently considered secure.
DisplayDeviceState info(displayType, true);
info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
"Built-in Screen" : "External Screen";
mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
mInterceptor->saveDisplayCreation(info);
}
} else {
ALOGV("Removing built in display %d", displayType);
ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
if (idx >= 0) {
const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
mInterceptor->saveDisplayDeletion(info.displayId);
mCurrentState.displays.removeItemsAt(idx);
}
mBuiltinDisplays[displayType].clear();
}
processDisplayChangesLocked();
}
mPendingHotplugEvents.clear();
}
sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
bool hasWideColorGamut = false;
std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
if (hasWideColorDisplay) {
std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
for (ColorMode colorMode : modes) {
switch (colorMode) {
case ColorMode::DISPLAY_P3:
case ColorMode::ADOBE_RGB:
case ColorMode::DCI_P3:
hasWideColorGamut = true;
break;
default:
break;
}
std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
colorMode);
hwcColorModes.emplace(colorMode, renderIntents);
}
}
HdrCapabilities hdrCapabilities;
getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
auto nativeWindow = nativeWindowSurface->getNativeWindow();
/*
* Create our display's surface
*/
std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
renderSurface->setNativeWindow(nativeWindow.get());
const int displayWidth = renderSurface->queryWidth();
const int displayHeight = renderSurface->queryHeight();
// Make sure that composition can never be stalled by a virtual display
// consumer that isn't processing buffers fast enough. We have to do this
// in two places:
// * Here, in case the display is composed entirely by HWC.
// * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
// window's swap interval in eglMakeCurrent, so they'll override the
// interval we set here.
if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
nativeWindow->setSwapInterval(nativeWindow.get(), 0);
}
// virtual displays are always considered enabled
auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
: HWC_POWER_MODE_OFF;
sp<DisplayDevice> hw =
new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
dispSurface, std::move(renderSurface), displayWidth, displayHeight,
hasWideColorGamut, hdrCapabilities,
getHwComposer().getSupportedPerFrameMetadata(hwcId),
hwcColorModes, initialPowerMode);
if (maxFrameBufferAcquiredBuffers >= 3) {
nativeWindowSurface->preallocateBuffers();
}
ColorMode defaultColorMode = ColorMode::NATIVE;
Dataspace defaultDataSpace = Dataspace::UNKNOWN;
if (hasWideColorGamut) {
defaultColorMode = ColorMode::SRGB;
defaultDataSpace = Dataspace::SRGB;
}
setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
RenderIntent::COLORIMETRIC);
if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
}
hw->setLayerStack(state.layerStack);
hw->setProjection(state.orientation, state.viewport, state.frame);
hw->setDisplayName(state.displayName);
return hw;
}
void SurfaceFlinger::processDisplayChangesLocked() {
// here we take advantage of Vector's copy-on-write semantics to
// improve performance by skipping the transaction entirely when
// know that the lists are identical
const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
if (!curr.isIdenticalTo(draw)) {
mVisibleRegionsDirty = true;
const size_t cc = curr.size();
size_t dc = draw.size();
// find the displays that were removed
// (ie: in drawing state but not in current state)
// also handle displays that changed
// (ie: displays that are in both lists)
for (size_t i = 0; i < dc;) {
const ssize_t j = curr.indexOfKey(draw.keyAt(i));
if (j < 0) {
// in drawing state but not in current state
// Call makeCurrent() on the primary display so we can
// be sure that nothing associated with this display
// is current.
const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
if (hw != nullptr) hw->disconnect(getHwComposer());
if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
mEventThread->onHotplugReceived(draw[i].type, false);
mDisplays.removeItem(draw.keyAt(i));
} else {
// this display is in both lists. see if something changed.
const DisplayDeviceState& state(curr[j]);
const wp<IBinder>& display(curr.keyAt(j));
const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
if (state_binder != draw_binder) {
// changing the surface is like destroying and
// recreating the DisplayDevice, so we just remove it
// from the drawing state, so that it get re-added
// below.
sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
if (hw != nullptr) hw->disconnect(getHwComposer());
mDisplays.removeItem(display);
mDrawingState.displays.removeItemsAt(i);
dc--;
// at this point we must loop to the next item
continue;
}
const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
if (disp != nullptr) {
if (state.layerStack != draw[i].layerStack) {
disp->setLayerStack(state.layerStack);
}
if ((state.orientation != draw[i].orientation) ||
(state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
disp->setProjection(state.orientation, state.viewport, state.frame);
}
if (state.width != draw[i].width || state.height != draw[i].height) {
disp->setDisplaySize(state.width, state.height);
}
}
}
++i;
}
// find displays that were added
// (ie: in current state but not in drawing state)
for (size_t i = 0; i < cc; i++) {
if (draw.indexOfKey(curr.keyAt(i)) < 0) {
const DisplayDeviceState& state(curr[i]);
sp<DisplaySurface> dispSurface;
sp<IGraphicBufferProducer> producer;
sp<IGraphicBufferProducer> bqProducer;
sp<IGraphicBufferConsumer> bqConsumer;
mCreateBufferQueue(&bqProducer, &bqConsumer, false);
int32_t hwcId = -1;
if (state.isVirtualDisplay()) {
// Virtual displays without a surface are dormant:
// they have external state (layer stack, projection,
// etc.) but no internal state (i.e. a DisplayDevice).
if (state.surface != nullptr) {
// Allow VR composer to use virtual displays.
if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
int width = 0;
int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
int height = 0;
status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
int intFormat = 0;
status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
auto format = static_cast<ui::PixelFormat>(intFormat);
getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
}
// TODO: Plumb requested format back up to consumer
sp<VirtualDisplaySurface> vds =
new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
bqProducer, bqConsumer,
state.displayName);
dispSurface = vds;
producer = vds;
}
} else {
ALOGE_IF(state.surface != nullptr,
"adding a supported display, but rendering "
"surface is provided (%p), ignoring it",
state.surface.get());
hwcId = state.type;
dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
producer = bqProducer;
}
const wp<IBinder>& display(curr.keyAt(i));
if (dispSurface != nullptr) {
mDisplays.add(display,
setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
producer));
if (!state.isVirtualDisplay()) {
mEventThread->onHotplugReceived(state.type, true);
}
}
}
}
}
mDrawingState.displays = mCurrentState.displays;
}
void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
{
// Notify all layers of available frames
mCurrentState.traverseInZOrder([](Layer* layer) {
layer->notifyAvailableFrames();
});
/*
* Traversal of the children
* (perform the transaction for each of them if needed)
*/
if (transactionFlags & eTraversalNeeded) {
mCurrentState.traverseInZOrder([&](Layer* layer) {
uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
if (!trFlags) return;
const uint32_t flags = layer->doTransaction(0);
if (flags & Layer::eVisibleRegion)
mVisibleRegionsDirty = true;
});
}
/*
* Perform display own transactions if needed
*/
if (transactionFlags & eDisplayTransactionNeeded) {
processDisplayChangesLocked();
processDisplayHotplugEventsLocked();
}
if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
// The transform hint might have changed for some layers
// (either because a display has changed, or because a layer
// as changed).
//
// Walk through all the layers in currentLayers,
// and update their transform hint.
//
// If a layer is visible only on a single display, then that
// display is used to calculate the hint, otherwise we use the
// default display.
//
// NOTE: we do this here, rather than in rebuildLayerStacks() so that
// the hint is set before we acquire a buffer from the surface texture.
//
// NOTE: layer transactions have taken place already, so we use their
// drawing state. However, SurfaceFlinger's own transaction has not
// happened yet, so we must use the current state layer list
// (soon to become the drawing state list).
//
sp<const DisplayDevice> disp;
uint32_t currentlayerStack = 0;
bool first = true;
mCurrentState.traverseInZOrder([&](Layer* layer) {
// NOTE: we rely on the fact that layers are sorted by
// layerStack first (so we don't have to traverse the list
// of displays for every layer).
uint32_t layerStack = layer->getLayerStack();
if (first || currentlayerStack != layerStack) {
currentlayerStack = layerStack;
// figure out if this layerstack is mirrored
// (more than one display) if so, pick the default display,
// if not, pick the only display it's on.
disp.clear();
for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
sp<const DisplayDevice> hw(mDisplays[dpy]);
if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
if (disp == nullptr) {
disp = std::move(hw);
} else {
disp = nullptr;
break;
}
}
}
}
if (disp == nullptr) {
// NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
// redraw after transform hint changes. See bug 8508397.
// could be null when this layer is using a layerStack
// that is not visible on any display. Also can occur at
// screen off/on times.
disp = getDefaultDisplayDeviceLocked();
}
// disp can be null if there is no display available at all to get
// the transform hint from.
if (disp != nullptr) {
layer->updateTransformHint(disp);
}
first = false;
});
}
/*
* Perform our own transaction if needed
*/
if (mLayersAdded) {
mLayersAdded = false;
// Layers have been added.
mVisibleRegionsDirty = true;
}
// some layers might have been removed, so
// we need to update the regions they're exposing.
if (mLayersRemoved) {
mLayersRemoved = false;
mVisibleRegionsDirty = true;
mDrawingState.traverseInZOrder([&](Layer* layer) {
if (mLayersPendingRemoval.indexOf(layer) >= 0) {
// this layer is not visible anymore
// TODO: we could traverse the tree from front to back and
// compute the actual visible region
// TODO: we could cache the transformed region
Region visibleReg;
visibleReg.set(layer->computeScreenBounds());
invalidateLayerStack(layer, visibleReg);
}
});
}
commitTransaction();
updateCursorAsync();
}
void SurfaceFlinger::updateCursorAsync()
{
for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
auto& displayDevice = mDisplays[displayId];
if (displayDevice->getHwcDisplayId() < 0) {
continue;
}
for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
layer->updateCursorPosition(displayDevice);
}
}
}
void SurfaceFlinger::commitTransaction()
{
if (!mLayersPendingRemoval.isEmpty()) {
// Notify removed layers now that they can't be drawn from
for (const auto& l : mLayersPendingRemoval) {
recordBufferingStats(l->getName().string(),
l->getOccupancyHistory(true));
l->onRemoved();
}
mLayersPendingRemoval.clear();
}
// If this transaction is part of a window animation then the next frame
// we composite should be considered an animation as well.
mAnimCompositionPending = mAnimTransactionPending;
mDrawingState = mCurrentState;
// clear the "changed" flags in current state
mCurrentState.colorMatrixChanged = false;
mDrawingState.traverseInZOrder([](Layer* layer) {
layer->commitChildList();
});
mTransactionPending = false;
mAnimTransactionPending = false;
mTransactionCV.broadcast();
}
void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Region& outDirtyRegion, Region& outOpaqueRegion)
{
ATRACE_CALL();
ALOGV("computeVisibleRegions");
Region aboveOpaqueLayers;
Region aboveCoveredLayers;
Region dirty;
outDirtyRegion.clear();
mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
// start with the whole surface at its current location
const Layer::State& s(layer->getDrawingState());
// only consider the layers on the given layer stack
if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
return;
/*
* opaqueRegion: area of a surface that is fully opaque.
*/
Region opaqueRegion;
/*
* visibleRegion: area of a surface that is visible on screen
* and not fully transparent. This is essentially the layer's
* footprint minus the opaque regions above it.
* Areas covered by a translucent surface are considered visible.
*/
Region visibleRegion;
/*
* coveredRegion: area of a surface that is covered by all
* visible regions above it (which includes the translucent areas).
*/
Region coveredRegion;
/*
* transparentRegion: area of a surface that is hinted to be completely
* transparent. This is only used to tell when the layer has no visible
* non-transparent regions and can be removed from the layer list. It
* does not affect the visibleRegion of this layer or any layers
* beneath it. The hint may not be correct if apps don't respect the
* SurfaceView restrictions (which, sadly, some don't).
*/
Region transparentRegion;
// handle hidden surfaces by setting the visible region to empty
if (CC_LIKELY(layer->isVisible())) {
const bool translucent = !layer->isOpaque(s);
Rect bounds(layer->computeScreenBounds());
visibleRegion.set(bounds);
Transform tr = layer->getTransform();
if (!visibleRegion.isEmpty()) {
// Remove the transparent area from the visible region
if (translucent) {
if (tr.preserveRects()) {
// transform the transparent region
transparentRegion = tr.transform(s.activeTransparentRegion);
} else {
// transformation too complex, can't do the
// transparent region optimization.
transparentRegion.clear();
}
}
// compute the opaque region
const int32_t layerOrientation = tr.getOrientation();
if (layer->getAlpha() == 1.0f && !translucent &&
((layerOrientation & Transform::ROT_INVALID) == false)) {
// the opaque region is the layer's footprint
opaqueRegion = visibleRegion;
}
}
}
if (visibleRegion.isEmpty()) {
layer->clearVisibilityRegions();
return;
}
// Clip the covered region to the visible region
coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
// Update aboveCoveredLayers for next (lower) layer
aboveCoveredLayers.orSelf(visibleRegion);
// subtract the opaque region covered by the layers above us
visibleRegion.subtractSelf(aboveOpaqueLayers);
// compute this layer's dirty region
if (layer->contentDirty) {
// we need to invalidate the whole region
dirty = visibleRegion;
// as well, as the old visible region
dirty.orSelf(layer->visibleRegion);
layer->contentDirty = false;
} else {
/* compute the exposed region:
* the exposed region consists of two components:
* 1) what's VISIBLE now and was COVERED before
* 2) what's EXPOSED now less what was EXPOSED before
*
* note that (1) is conservative, we start with the whole
* visible region but only keep what used to be covered by
* something -- which mean it may have been exposed.
*
* (2) handles areas that were not covered by anything but got
* exposed because of a resize.
*/
const Region newExposed = visibleRegion - coveredRegion;
const Region oldVisibleRegion = layer->visibleRegion;
const Region oldCoveredRegion = layer->coveredRegion;
const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
}
dirty.subtractSelf(aboveOpaqueLayers);
// accumulate to the screen dirty region
outDirtyRegion.orSelf(dirty);
// Update aboveOpaqueLayers for next (lower) layer
aboveOpaqueLayers.orSelf(opaqueRegion);
// Store the visible region in screen space
layer->setVisibleRegion(visibleRegion);
layer->setCoveredRegion(coveredRegion);
layer->setVisibleNonTransparentRegion(
visibleRegion.subtract(transparentRegion));
});
outOpaqueRegion = aboveOpaqueLayers;
}
void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
const sp<DisplayDevice>& hw(mDisplays[dpy]);
if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
hw->dirtyRegion.orSelf(dirty);
}
}
}
bool SurfaceFlinger::handlePageFlip()
{
ALOGV("handlePageFlip");
nsecs_t latchTime = systemTime();
bool visibleRegions = false;
bool frameQueued = false;
bool newDataLatched = false;
// Store the set of layers that need updates. This set must not change as
// buffers are being latched, as this could result in a deadlock.
// Example: Two producers share the same command stream and:
// 1.) Layer 0 is latched
// 2.) Layer 0 gets a new frame
// 2.) Layer 1 gets a new frame
// 3.) Layer 1 is latched.
// Display is now waiting on Layer 1's frame, which is behind layer 0's
// second frame. But layer 0's second frame could be waiting on display.
mDrawingState.traverseInZOrder([&](Layer* layer) {
if (layer->hasQueuedFrame()) {
frameQueued = true;
if (layer->shouldPresentNow(mPrimaryDispSync)) {
mLayersWithQueuedFrames.push_back(layer);
} else {
layer->useEmptyDamage();
}
} else {
layer->useEmptyDamage();
}
});
for (auto& layer : mLayersWithQueuedFrames) {
const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
layer->useSurfaceDamage();
invalidateLayerStack(layer, dirty);
if (layer->isBufferLatched()) {
newDataLatched = true;
}
}
mVisibleRegionsDirty |= visibleRegions;
// If we will need to wake up at some time in the future to deal with a
// queued frame that shouldn't be displayed during this vsync period, wake
// up during the next vsync period to check again.
if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
signalLayerUpdate();
}
// Only continue with the refresh if there is actually new work to do
return !mLayersWithQueuedFrames.empty() && newDataLatched;
}
void SurfaceFlinger::invalidateHwcGeometry()
{
mGeometryInvalid = true;
}
void SurfaceFlinger::doDisplayComposition(
const sp<const DisplayDevice>& displayDevice,
const Region& inDirtyRegion)
{
// We only need to actually compose the display if:
// 1) It is being handled by hardware composer, which may need this to
// keep its virtual display state machine in sync, or
// 2) There is work to be done (the dirty region isn't empty)
bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
ALOGV("Skipping display composition");
return;
}
ALOGV("doDisplayComposition");
if (!doComposeSurfaces(displayDevice)) return;
// swap buffers (presentation)
displayDevice->swapBuffers(getHwComposer());
}
bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
{
ALOGV("doComposeSurfaces");
const Region bounds(displayDevice->bounds());
const DisplayRenderArea renderArea(displayDevice);
const auto hwcId = displayDevice->getHwcDisplayId();
const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
ATRACE_INT("hasClientComposition", hasClientComposition);
bool applyColorMatrix = false;
bool needsLegacyColorMatrix = false;
bool legacyColorMatrixApplied = false;
if (hasClientComposition) {
ALOGV("hasClientComposition");
Dataspace outputDataspace = Dataspace::UNKNOWN;
if (displayDevice->hasWideColorGamut()) {
outputDataspace = displayDevice->getCompositionDataSpace();
}
getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
getBE().mRenderEngine->setDisplayMaxLuminance(
displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
const bool skipClientColorTransform = getBE().mHwc->hasCapability(
HWC2::Capability::SkipClientColorTransform);
applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
if (applyColorMatrix) {
getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
}
needsLegacyColorMatrix =
(displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
outputDataspace != Dataspace::UNKNOWN &&
outputDataspace != Dataspace::SRGB);
if (!displayDevice->makeCurrent()) {
ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
displayDevice->getDisplayName().string());
getRenderEngine().resetCurrentSurface();
// |mStateLock| not needed as we are on the main thread
if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
}
return false;
}
// Never touch the framebuffer if we don't have any framebuffer layers
if (hasDeviceComposition) {
// when using overlays, we assume a fully transparent framebuffer
// NOTE: we could reduce how much we need to clear, for instance
// remove where there are opaque FB layers. however, on some
// GPUs doing a "clean slate" clear might be more efficient.
// We'll revisit later if needed.
getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
} else {
// we start with the whole screen area and remove the scissor part
// we're left with the letterbox region
// (common case is that letterbox ends-up being empty)
const Region letterbox(bounds.subtract(displayDevice->getScissor()));
// compute the area to clear
Region region(displayDevice->undefinedRegion.merge(letterbox));
// screen is already cleared here
if (!region.isEmpty()) {
// can happen with SurfaceView
drawWormhole(displayDevice, region);
}
}
if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
// just to be on the safe side, we don't set the
// scissor on the main display. It should never be needed
// anyways (though in theory it could since the API allows it).
const Rect& bounds(displayDevice->getBounds());
const Rect& scissor(displayDevice->getScissor());
if (scissor != bounds) {
// scissor doesn't match the screen's dimensions, so we
// need to clear everything outside of it and enable
// the GL scissor so we don't draw anything where we shouldn't
// enable scissor for this frame
const uint32_t height = displayDevice->getHeight();
getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
scissor.getWidth(), scissor.getHeight());
}
}
}
/*
* and then, render the layers targeted at the framebuffer
*/
ALOGV("Rendering client layers");
const Transform& displayTransform = displayDevice->getTransform();
bool firstLayer = true;
for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
const Region clip(bounds.intersect(
displayTransform.transform(layer->visibleRegion)));
ALOGV("Layer: %s", layer->getName().string());
ALOGV(" Composition type: %s",
to_string(layer->getCompositionType(hwcId)).c_str());
if (!clip.isEmpty()) {
switch (layer->getCompositionType(hwcId)) {
case HWC2::Composition::Cursor:
case HWC2::Composition::Device:
case HWC2::Composition::Sideband:
case HWC2::Composition::SolidColor: {
const Layer::State& state(layer->getDrawingState());
if (layer->getClearClientTarget(hwcId) && !firstLayer &&
layer->isOpaque(state) && (state.color.a == 1.0f)
&& hasClientComposition) {
// never clear the very first layer since we're
// guaranteed the FB is already cleared
layer->clearWithOpenGL(renderArea);
}
break;
}
case HWC2::Composition::Client: {
// switch color matrices lazily
if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
if (!legacyColorMatrixApplied) {
getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
legacyColorMatrixApplied = true;
}
} else if (legacyColorMatrixApplied) {
getRenderEngine().setSaturationMatrix(mat4());
legacyColorMatrixApplied = false;
}
layer->draw(renderArea, clip);
break;
}
default:
break;
}
} else {
ALOGV(" Skipping for empty clip");
}
firstLayer = false;
}
if (applyColorMatrix) {
getRenderEngine().setupColorTransform(mat4());
}
if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
getRenderEngine().setSaturationMatrix(mat4());
}
// disable scissor at the end of the frame
getBE().mRenderEngine->disableScissor();
return true;
}
void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
const int32_t height = displayDevice->getHeight();
auto& engine(getRenderEngine());
engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
}
status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
const sp<IBinder>& handle,
const sp<IGraphicBufferProducer>& gbc,
const sp<Layer>& lbc,
const sp<Layer>& parent)
{
// add this layer to the current state list
{
Mutex::Autolock _l(mStateLock);
if (mNumLayers >= MAX_LAYERS) {
ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
MAX_LAYERS);
return NO_MEMORY;
}
if (parent == nullptr) {
mCurrentState.layersSortedByZ.add(lbc);
} else {
if (parent->isPendingRemoval()) {
ALOGE("addClientLayer called with a removed parent");
return NAME_NOT_FOUND;
}
parent->addChild(lbc);
}
if (gbc != nullptr) {
mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
mMaxGraphicBufferProducerListSize,
"Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
mGraphicBufferProducerList.size(),
mMaxGraphicBufferProducerListSize, mNumLayers);
}
mLayersAdded = true;
mNumLayers++;
}
// attach this layer to the client
client->attachLayer(handle, lbc);
return NO_ERROR;
}
status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Mutex::Autolock _l(mStateLock);
return removeLayerLocked(mStateLock, layer, topLevelOnly);
}
status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
bool topLevelOnly) {
if (layer->isPendingRemoval()) {
return NO_ERROR;
}
const auto& p = layer->getParent();
ssize_t index;
if (p != nullptr) {
if (topLevelOnly) {
return NO_ERROR;
}
sp<Layer> ancestor = p;
while (ancestor->getParent() != nullptr) {
ancestor = ancestor->getParent();
}
if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
ALOGE("removeLayer called with a layer whose parent has been removed");
return NAME_NOT_FOUND;
}
index = p->removeChild(layer);
} else {
index = mCurrentState.layersSortedByZ.remove(layer);
}
// As a matter of normal operation, the LayerCleaner will produce a second
// attempt to remove the surface. The Layer will be kept alive in mDrawingState
// so we will succeed in promoting it, but it's already been removed
// from mCurrentState. As long as we can find it in mDrawingState we have no problem
// otherwise something has gone wrong and we are leaking the layer.
if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
ALOGE("Failed to find layer (%s) in layer parent (%s).",
layer->getName().string(),
(p != nullptr) ? p->getName().string() : "no-parent");
return BAD_VALUE;
} else if (index < 0) {
return NO_ERROR;
}
layer->onRemovedFromCurrentState();
mLayersPendingRemoval.add(layer);
mLayersRemoved = true;
mNumLayers -= 1 + layer->getChildrenCount();
setTransactionFlags(eTransactionNeeded);
return NO_ERROR;
}
uint32_t SurfaceFlinger::peekTransactionFlags() {
return android_atomic_release_load(&mTransactionFlags);
}
uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
return android_atomic_and(~flags, &mTransactionFlags) & flags;
}
uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
}
uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
VSyncModulator::TransactionStart transactionStart) {
uint32_t old = android_atomic_or(flags, &mTransactionFlags);
mVsyncModulator.setTransactionStart(transactionStart);
if ((old & flags)==0) { // wake the server up
signalTransaction();
}
return old;
}
bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
for (const ComposerState& state : states) {
// Here we need to check that the interface we're given is indeed
// one of our own. A malicious client could give us a nullptr
// IInterface, or one of its own or even one of our own but a
// different type. All these situations would cause us to crash.
if (state.client == nullptr) {
return true;
}
sp<IBinder> binder = IInterface::asBinder(state.client);
if (binder == nullptr) {
return true;
}
if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
return true;
}
}
return false;
}
void SurfaceFlinger::setTransactionState(
const Vector<ComposerState>& states,
const Vector<DisplayState>& displays,
uint32_t flags)
{
ATRACE_CALL();
Mutex::Autolock _l(mStateLock);
uint32_t transactionFlags = 0;
if (containsAnyInvalidClientState(states)) {
return;
}
if (flags & eAnimation) {
// For window updates that are part of an animation we must wait for
// previous animation "frames" to be handled.
while (mAnimTransactionPending) {
status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
if (CC_UNLIKELY(err != NO_ERROR)) {
// just in case something goes wrong in SF, return to the
// caller after a few seconds.
ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
"waiting for previous animation frame");
mAnimTransactionPending = false;
break;
}
}
}
for (const DisplayState& display : displays) {
transactionFlags |= setDisplayStateLocked(display);
}
for (const ComposerState& state : states) {
transactionFlags |= setClientStateLocked(state);
}
// Iterate through all layers again to determine if any need to be destroyed. Marking layers
// as destroyed should only occur after setting all other states. This is to allow for a
// child re-parent to happen before marking its original parent as destroyed (which would
// then mark the child as destroyed).
for (const ComposerState& state : states) {
setDestroyStateLocked(state);
}
// If a synchronous transaction is explicitly requested without any changes, force a transaction
// anyway. This can be used as a flush mechanism for previous async transactions.
// Empty animation transaction can be used to simulate back-pressure, so also force a
// transaction for empty animation transactions.
if (transactionFlags == 0 &&
((flags & eSynchronous) || (flags & eAnimation))) {
transactionFlags = eTransactionNeeded;
}
if (transactionFlags) {
if (mInterceptor->isEnabled()) {
mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
}
// this triggers the transaction
const auto start = (flags & eEarlyWakeup)
? VSyncModulator::TransactionStart::EARLY
: VSyncModulator::TransactionStart::NORMAL;
setTransactionFlags(transactionFlags, start);
// if this is a synchronous transaction, wait for it to take effect
// before returning.
if (flags & eSynchronous) {
mTransactionPending = true;
}
if (flags & eAnimation) {
mAnimTransactionPending = true;
}
while (mTransactionPending) {
status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
if (CC_UNLIKELY(err != NO_ERROR)) {
// just in case something goes wrong in SF, return to the
// called after a few seconds.
ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
mTransactionPending = false;
break;
}
}
}
}
uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
{
ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
if (dpyIdx < 0)
return 0;
uint32_t flags = 0;
DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
if (disp.isValid()) {
const uint32_t what = s.what;
if (what & DisplayState::eSurfaceChanged) {
if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
disp.surface = s.surface;
flags |= eDisplayTransactionNeeded;
}
}
if (what & DisplayState::eLayerStackChanged) {
if (disp.layerStack != s.layerStack) {
disp.layerStack = s.layerStack;
flags |= eDisplayTransactionNeeded;
}
}
if (what & DisplayState::eDisplayProjectionChanged) {
if (disp.orientation != s.orientation) {
disp.orientation = s.orientation;
flags |= eDisplayTransactionNeeded;
}
if (disp.frame != s.frame) {
disp.frame = s.frame;
flags |= eDisplayTransactionNeeded;
}
if (disp.viewport != s.viewport) {
disp.viewport = s.viewport;
flags |= eDisplayTransactionNeeded;
}
}
if (what & DisplayState::eDisplaySizeChanged) {
if (disp.width != s.width) {
disp.width = s.width;
flags |= eDisplayTransactionNeeded;
}
if (disp.height != s.height) {
disp.height = s.height;
flags |= eDisplayTransactionNeeded;
}
}
}
return flags;
}
uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
const layer_state_t& s = composerState.state;
sp<Client> client(static_cast<Client*>(composerState.client.get()));
sp<Layer> layer(client->getLayerUser(s.surface));
if (layer == nullptr) {
return 0;
}
if (layer->isPendingRemoval()) {
ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
return 0;
}
uint32_t flags = 0;
const uint32_t what = s.what;
bool geometryAppliesWithResize =
what & layer_state_t::eGeometryAppliesWithResize;
// If we are deferring transaction, make sure to push the pending state, as otherwise the
// pending state will also be deferred.
if (what & layer_state_t::eDeferTransaction) {
layer->pushPendingState();
}
if (what & layer_state_t::ePositionChanged) {
if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
flags |= eTraversalNeeded;
}
}
if (what & layer_state_t::eLayerChanged) {
// NOTE: index needs to be calculated before we update the state
const auto& p = layer->getParent();
if (p == nullptr) {
ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
if (layer->setLayer(s.z) && idx >= 0) {
mCurrentState.layersSortedByZ.removeAt(idx);
mCurrentState.layersSortedByZ.add(layer);
// we need traversal (state changed)
// AND transaction (list changed)
flags |= eTransactionNeeded|eTraversalNeeded;
}
} else {
if (p->setChildLayer(layer, s.z)) {
flags |= eTransactionNeeded|eTraversalNeeded;
}
}
}
if (what & layer_state_t::eRelativeLayerChanged) {
// NOTE: index needs to be calculated before we update the state
const auto& p = layer->getParent();
if (p == nullptr) {
ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
mCurrentState.layersSortedByZ.removeAt(idx);
mCurrentState.layersSortedByZ.add(layer);
// we need traversal (state changed)
// AND transaction (list changed)
flags |= eTransactionNeeded|eTraversalNeeded;
}
} else {
if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
flags |= eTransactionNeeded|eTraversalNeeded;
}
}
}
if (what & layer_state_t::eSizeChanged) {
if (layer->setSize(s.w, s.h)) {
flags |= eTraversalNeeded;
}
}
if (what & layer_state_t::eAlphaChanged) {
if (layer->setAlpha(s.alpha))
flags |= eTraversalNeeded;
}
if (what & layer_state_t::eColorChanged) {
if (layer->setColor(s.color))
flags |= eTraversalNeeded;
}
if (what & layer_state_t::eMatrixChanged) {
if (layer->setMatrix(s.matrix))
flags |= eTraversalNeeded;
}
if (what & layer_state_t::eTransparentRegionChanged) {
if (layer->setTransparentRegionHint(s.transparentRegion))
flags |= eTraversalNeeded;
}
if (what & layer_state_t::eFlagsChanged) {
if (layer->setFlags(s.flags, s.mask))
flags |= eTraversalNeeded;
}
if (what & layer_state_t::eCropChanged) {
if (layer->setCrop(s.crop, !geometryAppliesWithResize))
flags |= eTraversalNeeded;
}
if (what & layer_state_t::eFinalCropChanged) {
if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
flags |= eTraversalNeeded;
}
if (what & layer_state_t::eLayerStackChanged) {
ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
// We only allow setting layer stacks for top level layers,
// everything else inherits layer stack from its parent.
if (layer->hasParent()) {
ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
layer->getName().string());
} else if (idx < 0) {
ALOGE("Attempt to set layer stack on layer without parent (%s) that "
"that also does not appear in the top level layer list. Something"
" has gone wrong.", layer->getName().string());
} else if (layer->setLayerStack(s.layerStack)) {
mCurrentState.layersSortedByZ.removeAt(idx);
mCurrentState.layersSortedByZ.add(layer);
// we need traversal (state changed)
// AND transaction (list changed)
flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
}
}
if (what & layer_state_t::eDeferTransaction) {
if (s.barrierHandle != nullptr) {
layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
} else if (s.barrierGbp != nullptr) {
const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
if (authenticateSurfaceTextureLocked(gbp)) {
const auto& otherLayer =
(static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
layer->deferTransactionUntil(otherLayer, s.frameNumber);
} else {
ALOGE("Attempt to defer transaction to to an"
" unrecognized GraphicBufferProducer");
}
}
// We don't trigger a traversal here because if no other state is
// changed, we don't want this to cause any more work
}
if (what & layer_state_t::eReparent) {
bool hadParent = layer->hasParent();
if (layer->reparent(s.parentHandleForChild)) {
if (!hadParent) {
mCurrentState.layersSortedByZ.remove(layer);
}
flags |= eTransactionNeeded|eTraversalNeeded;
}
}
if (what & layer_state_t::eReparentChildren) {
if (layer->reparentChildren(s.reparentHandle)) {
flags |= eTransactionNeeded|eTraversalNeeded;
}
}
if (what & layer_state_t::eDetachChildren) {
layer->detachChildren();
}
if (what & layer_state_t::eOverrideScalingModeChanged) {
layer->setOverrideScalingMode(s.overrideScalingMode);
// We don't trigger a traversal here because if no other state is
// changed, we don't want this to cause any more work
}
return flags;
}
void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
const layer_state_t& state = composerState.state;
sp<Client> client(static_cast<Client*>(composerState.client.get()));
sp<Layer> layer(client->getLayerUser(state.surface));
if (layer == nullptr) {
return;
}
if (layer->isPendingRemoval()) {
ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
return;
}
if (state.what & layer_state_t::eDestroySurface) {
removeLayerLocked(mStateLock, layer);
}
}
status_t SurfaceFlinger::createLayer(
const String8& name,
const sp<Client>& client,
uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
{
if (int32_t(w|h) < 0) {
ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
int(w), int(h));
return BAD_VALUE;
}
status_t result = NO_ERROR;
sp<Layer> layer;
String8 uniqueName = getUniqueLayerName(name);
switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
case ISurfaceComposerClient::eFXSurfaceNormal:
result = createBufferLayer(client,
uniqueName, w, h, flags, format,
handle, gbp, &layer);
break;
case ISurfaceComposerClient::eFXSurfaceColor:
result = createColorLayer(client,
uniqueName, w, h, flags,
handle, &layer);
break;
default:
result = BAD_VALUE;
break;
}
if (result != NO_ERROR) {
return result;
}
// window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
// TODO b/64227542
if (windowType == 441731) {
windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
layer->setPrimaryDisplayOnly();
}
layer->setInfo(windowType, ownerUid);
result = addClientLayer(client, *handle, *gbp, layer, *parent);
if (result != NO_ERROR) {
return result;
}
mInterceptor->saveSurfaceCreation(layer);
setTransactionFlags(eTransactionNeeded);
return result;
}
String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
{
bool matchFound = true;
uint32_t dupeCounter = 0;
// Tack on our counter whether there is a hit or not, so everyone gets a tag
String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
// Loop over layers until we're sure there is no matching name
while (matchFound) {
matchFound = false;
mDrawingState.traverseInZOrder([&](Layer* layer) {
if (layer->getName() == uniqueName) {
matchFound = true;
uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
}
});
}
ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
return uniqueName;
}
status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
{
// initialize the surfaces
switch (format) {
case PIXEL_FORMAT_TRANSPARENT:
case PIXEL_FORMAT_TRANSLUCENT:
format = PIXEL_FORMAT_RGBA_8888;
break;
case PIXEL_FORMAT_OPAQUE:
format = PIXEL_FORMAT_RGBX_8888;
break;
}
sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
status_t err = layer->setBuffers(w, h, format, flags);
if (err == NO_ERROR) {
*handle = layer->getHandle();
*gbp = layer->getProducer();
*outLayer = layer;
}
ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
return err;
}
status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
const String8& name, uint32_t w, uint32_t h, uint32_t flags,
sp<IBinder>* handle, sp<Layer>* outLayer)
{
*outLayer = new ColorLayer(this, client, name, w, h, flags);
*handle = (*outLayer)->getHandle();
return NO_ERROR;
}
status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
{
// called by a client when it wants to remove a Layer
status_t err = NO_ERROR;
sp<Layer> l(client->getLayerUser(handle));
if (l != nullptr) {
mInterceptor->saveSurfaceDeletion(l);
err = removeLayer(l);
ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
"error removing layer=%p (%s)", l.get(), strerror(-err));
}
return err;
}
status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
{
// called by ~LayerCleaner() when all references to the IBinder (handle)
// are gone
sp<Layer> l = layer.promote();
if (l == nullptr) {
// The layer has already been removed, carry on
return NO_ERROR;
}
// If we have a parent, then we can continue to live as long as it does.
return removeLayer(l, true);
}
// ---------------------------------------------------------------------------
void SurfaceFlinger::onInitializeDisplays() {
// reset screen orientation and use primary layer stack
Vector<ComposerState> state;
Vector<DisplayState> displays;
DisplayState d;
d.what = DisplayState::eDisplayProjectionChanged |
DisplayState::eLayerStackChanged;
d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
d.layerStack = 0;
d.orientation = DisplayState::eOrientationDefault;
d.frame.makeInvalid();
d.viewport.makeInvalid();
d.width = 0;
d.height = 0;
displays.add(d);
setTransactionState(state, displays, 0);
setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
/*stateLockHeld*/ false);
const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
const nsecs_t period = activeConfig->getVsyncPeriod();
mAnimFrameTracker.setDisplayRefreshPeriod(period);
// Use phase of 0 since phase is not known.
// Use latency of 0, which will snap to the ideal latency.
setCompositorTimingSnapped(0, period, 0);
}
void SurfaceFlinger::initializeDisplays() {
class MessageScreenInitialized : public MessageBase {
SurfaceFlinger* flinger;
public:
explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
virtual bool handler() {
flinger->onInitializeDisplays();
return true;
}
};
sp<MessageBase> msg = new MessageScreenInitialized(this);
postMessageAsync(msg); // we may be called from main thread, use async message
}
void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
int mode, bool stateLockHeld) {
ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
this);
int32_t type = hw->getDisplayType();
int currentMode = hw->getPowerMode();
if (mode == currentMode) {
return;
}
hw->setPowerMode(mode);
if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
ALOGW("Trying to set power mode for virtual display");
return;
}
if (mInterceptor->isEnabled()) {
ConditionalLock lock(mStateLock, !stateLockHeld);
ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
if (idx < 0) {
ALOGW("Surface Interceptor SavePowerMode: invalid display token");
return;
}
mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
}
if (currentMode == HWC_POWER_MODE_OFF) {
// Turn on the display
getHwComposer().setPowerMode(type, mode);
if (type == DisplayDevice::DISPLAY_PRIMARY &&
mode != HWC_POWER_MODE_DOZE_SUSPEND) {
// FIXME: eventthread only knows about the main display right now
mEventThread->onScreenAcquired();
resyncToHardwareVsync(true);
}
mVisibleRegionsDirty = true;
mHasPoweredOff = true;
repaintEverything();
struct sched_param param = {0};
param.sched_priority = 1;
if (sched_setscheduler(0, SCHED_FIFO, ¶m) != 0) {
ALOGW("Couldn't set SCHED_FIFO on display on");
}
} else if (mode == HWC_POWER_MODE_OFF) {
// Turn off the display
struct sched_param param = {0};
if (sched_setscheduler(0, SCHED_OTHER, ¶m) != 0) {
ALOGW("Couldn't set SCHED_OTHER on display off");
}
if (type == DisplayDevice::DISPLAY_PRIMARY &&
currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
disableHardwareVsync(true); // also cancels any in-progress resync
// FIXME: eventthread only knows about the main display right now
mEventThread->onScreenReleased();
}
getHwComposer().setPowerMode(type, mode);
mVisibleRegionsDirty = true;
// from this point on, SF will stop drawing on this display
} else if (mode == HWC_POWER_MODE_DOZE ||
mode == HWC_POWER_MODE_NORMAL) {
// Update display while dozing
getHwComposer().setPowerMode(type, mode);
if (type == DisplayDevice::DISPLAY_PRIMARY &&
currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
// FIXME: eventthread only knows about the main display right now
mEventThread->onScreenAcquired();
resyncToHardwareVsync(true);
}
} else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
// Leave display going to doze
if (type == DisplayDevice::DISPLAY_PRIMARY) {
disableHardwareVsync(true); // also cancels any in-progress resync
// FIXME: eventthread only knows about the main display right now
mEventThread->onScreenReleased();
}
getHwComposer().setPowerMode(type, mode);
} else {
ALOGE("Attempting to set unknown power mode: %d\n", mode);
getHwComposer().setPowerMode(type, mode);
}
ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
}
void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
class MessageSetPowerMode: public MessageBase {
SurfaceFlinger& mFlinger;
sp<IBinder> mDisplay;
int mMode;
public:
MessageSetPowerMode(SurfaceFlinger& flinger,
const sp<IBinder>& disp, int mode) : mFlinger(flinger),
mDisplay(disp) { mMode = mode; }
virtual bool handler() {
sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
if (hw == nullptr) {
ALOGE("Attempt to set power mode = %d for null display %p",
mMode, mDisplay.get());
} else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
ALOGW("Attempt to set power mode = %d for virtual display",
mMode);
} else {
mFlinger.setPowerModeInternal(
hw, mMode, /*stateLockHeld*/ false);
}
return true;
}
};
sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
postMessageSync(msg);
}
// ---------------------------------------------------------------------------
status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
NO_THREAD_SAFETY_ANALYSIS {
String8 result;
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
if ((uid != AID_SHELL) &&
!PermissionCache::checkPermission(sDump, pid, uid)) {
result.appendFormat("Permission Denial: "
"can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
} else {
// Try to get the main lock, but give up after one second
// (this would indicate SF is stuck, but we want to be able to
// print something in dumpsys).
status_t err = mStateLock.timedLock(s2ns(1));
bool locked = (err == NO_ERROR);
if (!locked) {
result.appendFormat(
"SurfaceFlinger appears to be unresponsive (%s [%d]), "
"dumping anyways (no locks held)\n", strerror(-err), err);
}
bool dumpAll = true;
size_t index = 0;
size_t numArgs = args.size();
if (numArgs) {
if ((index < numArgs) &&
(args[index] == String16("--list"))) {
index++;
listLayersLocked(args, index, result);
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--latency"))) {
index++;
dumpStatsLocked(args, index, result);
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--latency-clear"))) {
index++;
clearStatsLocked(args, index, result);
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--dispsync"))) {
index++;
mPrimaryDispSync.dump(result);
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--static-screen"))) {
index++;
dumpStaticScreenStats(result);
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--frame-events"))) {
index++;
dumpFrameEventsLocked(result);
dumpAll = false;
}
if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
index++;
dumpWideColorInfo(result);
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--enable-layer-stats"))) {
index++;
mLayerStats.enable();
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--disable-layer-stats"))) {
index++;
mLayerStats.disable();
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--clear-layer-stats"))) {
index++;
mLayerStats.clear();
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--dump-layer-stats"))) {
index++;
mLayerStats.dump(result);
dumpAll = false;
}
if ((index < numArgs) && (args[index] == String16("--timestats"))) {
index++;
mTimeStats.parseArgs(asProto, args, index, result);
dumpAll = false;
}
}
if (dumpAll) {
if (asProto) {
LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
} else {
dumpAllLocked(args, index, result);
}
}
if (locked) {
mStateLock.unlock();
}
}
write(fd, result.string(), result.size());
return NO_ERROR;
}
void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
size_t& /* index */, String8& result) const
{
mCurrentState.traverseInZOrder([&](Layer* layer) {
result.appendFormat("%s\n", layer->getName().string());
});
}
void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
String8& result) const
{
String8 name;
if (index < args.size()) {
name = String8(args[index]);
index++;
}
const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
const nsecs_t period = activeConfig->getVsyncPeriod();
result.appendFormat("%" PRId64 "\n", period);
if (name.isEmpty()) {
mAnimFrameTracker.dumpStats(result);
} else {
mCurrentState.traverseInZOrder([&](Layer* layer) {
if (name == layer->getName()) {
layer->dumpFrameStats(result);
}
});
}
}
void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
String8& /* result */)
{
String8 name;
if (index < args.size()) {
name = String8(args[index]);
index++;
}
mCurrentState.traverseInZOrder([&](Layer* layer) {
if (name.isEmpty() || (name == layer->getName())) {
layer->clearFrameStats();
}
});
mAnimFrameTracker.clearStats();
}
// This should only be called from the main thread. Otherwise it would need
// the lock and should use mCurrentState rather than mDrawingState.
void SurfaceFlinger::logFrameStats() {
mDrawingState.traverseInZOrder([&](Layer* layer) {
layer->logFrameStats();
});
mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
}
void SurfaceFlinger::appendSfConfigString(String8& result) const
{
result.append(" [sf");
if (isLayerTripleBufferingDisabled())
result.append(" DISABLE_TRIPLE_BUFFERING");
result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
maxFrameBufferAcquiredBuffers);
result.append("]");
}
void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
{
result.appendFormat("Static screen stats:\n");
for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
float percent = 100.0f *
static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
b + 1, bucketTimeSec, percent);
}
float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
float percent = 100.0f *
static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
}
void SurfaceFlinger::recordBufferingStats(const char* layerName,
std::vector<OccupancyTracker::Segment>&& history) {
Mutex::Autolock lock(getBE().mBufferingStatsMutex);
auto& stats = getBE().mBufferingStats[layerName];
for (const auto& segment : history) {
if (!segment.usedThirdBuffer) {
stats.twoBufferTime += segment.totalTime;
}
if (segment.occupancyAverage < 1.0f) {
stats.doubleBufferedTime += segment.totalTime;
} else if (segment.occupancyAverage < 2.0f) {
stats.tripleBufferedTime += segment.totalTime;
}
++stats.numSegments;
stats.totalTime += segment.totalTime;
}
}
void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
result.appendFormat("Layer frame timestamps:\n");
const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
const size_t count = currentLayers.size();
for (size_t i=0 ; i<count ; i++) {
currentLayers[i]->dumpFrameEvents(result);
}
}
void SurfaceFlinger::dumpBufferingStats(String8& result) const {
result.append("Buffering stats:\n");
result.append(" [Layer name] <Active time> <Two buffer> "
"<Double buffered> <Triple buffered>\n");
Mutex::Autolock lock(getBE().mBufferingStatsMutex);
typedef std::tuple<std::string, float, float, float> BufferTuple;
std::map<float, BufferTuple, std::greater<float>> sorted;
for (const auto& statsPair : getBE().mBufferingStats) {
const char* name = statsPair.first.c_str();
const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
if (stats.numSegments == 0) {
continue;
}
float activeTime = ns2ms(stats.totalTime) / 1000.0f;
float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
stats.totalTime;
float doubleBufferRatio = static_cast<float>(
stats.doubleBufferedTime) / stats.totalTime;
float tripleBufferRatio = static_cast<float>(
stats.tripleBufferedTime) / stats.totalTime;
sorted.insert({activeTime, {name, twoBufferRatio,
doubleBufferRatio, tripleBufferRatio}});
}
for (const auto& sortedPair : sorted) {
float activeTime = sortedPair.first;
const BufferTuple& values = sortedPair.second;
result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
std::get<0>(values).c_str(), activeTime,
std::get<1>(values), std::get<2>(values),
std::get<3>(values));
}
result.append("\n");
}
void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
result.appendFormat("DisplayColorSetting: %s\n",
decodeDisplayColorSetting(mDisplayColorSetting).c_str());
// TODO: print out if wide-color mode is active or not
for (size_t d = 0; d < mDisplays.size(); d++) {
const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
int32_t hwcId = displayDevice->getHwcDisplayId();
if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
continue;
}
result.appendFormat("Display %d color modes:\n", hwcId);
std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
for (auto&& mode : modes) {
result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
}
ColorMode currentMode = displayDevice->getActiveColorMode();
result.appendFormat(" Current color mode: %s (%d)\n",
decodeColorMode(currentMode).c_str(), currentMode);
}
result.append("\n");
}
LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
LayersProto layersProto;
const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
const State& state = useDrawing ? mDrawingState : mCurrentState;
state.traverseInZOrder([&](Layer* layer) {
LayerProto* layerProto = layersProto.add_layers();
layer->writeToProto(layerProto, stateSet);
});
return layersProto;
}
LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
LayersProto layersProto;
const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
SizeProto* resolution = layersProto.mutable_resolution();
resolution->set_w(displayDevice->getWidth());
resolution->set_h(displayDevice->getHeight());
layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
layersProto.set_global_transform(
static_cast<int32_t>(displayDevice->getOrientationTransform()));
mDrawingState.traverseInZOrder([&](Layer* layer) {
if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
LayerProto* layerProto = layersProto.add_layers();
layer->writeToProto(layerProto, hwcId);
}
});
return layersProto;
}
void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
String8& result) const
{
bool colorize = false;
if (index < args.size()
&& (args[index] == String16("--color"))) {
colorize = true;
index++;
}
Colorizer colorizer(colorize);
// figure out if we're stuck somewhere
const nsecs_t now = systemTime();
const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
const nsecs_t inTransaction(mDebugInTransaction);
nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
/*
* Dump library configuration.
*/
colorizer.bold(result);
result.append("Build configuration:");
colorizer.reset(result);
appendSfConfigString(result);
appendUiConfigString(result);
appendGuiConfigString(result);
result.append("\n");
result.append("\nWide-Color information:\n");
dumpWideColorInfo(result);
colorizer.bold(result);
result.append("Sync configuration: ");
colorizer.reset(result);
result.append(SyncFeatures::getInstance().toString());
result.append("\n");
const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
colorizer.bold(result);
result.append("DispSync configuration: ");
colorizer.reset(result);
result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
" ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
result.append("\n");
// Dump static screen stats
result.append("\n");
dumpStaticScreenStats(result);
result.append("\n");
dumpBufferingStats(result);
/*
* Dump the visible layer list
*/
colorizer.bold(result);
result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
colorizer.reset(result);
LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
result.append("\n");
/*
* Dump Display state
*/
colorizer.bold(result);
result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
colorizer.reset(result);
for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
const sp<const DisplayDevice>& hw(mDisplays[dpy]);
hw->dump(result);
}
result.append("\n");
/*
* Dump SurfaceFlinger global state
*/
colorizer.bold(result);
result.append("SurfaceFlinger global state:\n");
colorizer.reset(result);
HWComposer& hwc(getHwComposer());
sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
getBE().mRenderEngine->dump(result);
if (hw) {
hw->undefinedRegion.dump(result, "undefinedRegion");
result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
hw->getOrientation(), hw->isDisplayOn());
}
result.appendFormat(
" last eglSwapBuffers() time: %f us\n"
" last transaction time : %f us\n"
" transaction-flags : %08x\n"
" refresh-rate : %f fps\n"
" x-dpi : %f\n"
" y-dpi : %f\n"
" gpu_to_cpu_unsupported : %d\n"
,
mLastSwapBufferTime/1000.0,
mLastTransactionTime/1000.0,
mTransactionFlags,
1e9 / activeConfig->getVsyncPeriod(),
activeConfig->getDpiX(),
activeConfig->getDpiY(),
!mGpuToCpuSupported);
result.appendFormat(" eglSwapBuffers time: %f us\n",
inSwapBuffersDuration/1000.0);
result.appendFormat(" transaction time: %f us\n",
inTransactionDuration/1000.0);
/*
* VSYNC state
*/
mEventThread->dump(result);
result.append("\n");
/*
* HWC layer minidump
*/
for (size_t d = 0; d < mDisplays.size(); d++) {
const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
int32_t hwcId = displayDevice->getHwcDisplayId();
if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
continue;
}
result.appendFormat("Display %d HWC layers:\n", hwcId);
Layer::miniDumpHeader(result);
mCurrentState.traverseInZOrder([&](Layer* layer) {
layer->miniDump(result, hwcId);
});
result.append("\n");
}
/*
* Dump HWComposer state
*/
colorizer.bold(result);
result.append("h/w composer state:\n");
colorizer.reset(result);
bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
result.appendFormat(" h/w composer %s\n",
hwcDisabled ? "disabled" : "enabled");
hwc.dump(result);
/*
* Dump gralloc state
*/
const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
alloc.dump(result);
/*
* Dump VrFlinger state if in use.
*/
if (mVrFlingerRequestsDisplay && mVrFlinger) {
result.append("VrFlinger state:\n");
result.append(mVrFlinger->Dump().c_str());
result.append("\n");
}
}
const Vector< sp<Layer> >&
SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
// Note: mStateLock is held here
wp<IBinder> dpy;
for (size_t i=0 ; i<mDisplays.size() ; i++) {
if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
dpy = mDisplays.keyAt(i);
break;
}
}
if (dpy == nullptr) {
ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
// Just use the primary display so we have something to return
dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
}
return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
}
bool SurfaceFlinger::startDdmConnection()
{
void* libddmconnection_dso =
dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
if (!libddmconnection_dso) {
return false;
}
void (*DdmConnection_start)(const char* name);
DdmConnection_start =
(decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
if (!DdmConnection_start) {
dlclose(libddmconnection_dso);
return false;
}
(*DdmConnection_start)(getServiceName());
return true;
}
void SurfaceFlinger::updateColorMatrixLocked() {
mat4 colorMatrix;
if (mGlobalSaturationFactor != 1.0f) {
// Rec.709 luma coefficients
float3 luminance{0.213f, 0.715f, 0.072f};
luminance *= 1.0f - mGlobalSaturationFactor;
mat4 saturationMatrix = mat4(
vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
vec4{0.0f, 0.0f, 0.0f, 1.0f}
);
colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
} else {
colorMatrix = mClientColorMatrix * mDaltonizer();
}
if (mCurrentState.colorMatrix != colorMatrix) {
mCurrentState.colorMatrix = colorMatrix;
mCurrentState.colorMatrixChanged = true;
setTransactionFlags(eTransactionNeeded);
}
}
status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
switch (code) {
case CREATE_CONNECTION:
case CREATE_DISPLAY:
case BOOT_FINISHED:
case CLEAR_ANIMATION_FRAME_STATS:
case GET_ANIMATION_FRAME_STATS:
case SET_POWER_MODE:
case GET_HDR_CAPABILITIES:
case ENABLE_VSYNC_INJECTIONS:
case INJECT_VSYNC:
{
// codes that require permission check
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
!PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}
break;
}
/*
* Calling setTransactionState is safe, because you need to have been
* granted a reference to Client* and Handle* to do anything with it.
*
* Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
*/
case SET_TRANSACTION_STATE:
case CREATE_SCOPED_CONNECTION:
{
return OK;
}
case CAPTURE_SCREEN:
{
// codes that require permission check
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
if ((uid != AID_GRAPHICS) &&
!PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}
break;
}
case CAPTURE_LAYERS: {
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
if ((uid != AID_GRAPHICS) &&
!PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}
break;
}
}
return OK;
}
status_t SurfaceFlinger::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
status_t credentialCheck = CheckTransactCodeCredentials(code);
if (credentialCheck != OK) {
return credentialCheck;
}
status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
CHECK_INTERFACE(ISurfaceComposer, data, reply);
IPCThreadState* ipc = IPCThreadState::self();
const int uid = ipc->getCallingUid();
if (CC_UNLIKELY(uid != AID_SYSTEM
&& !PermissionCache::checkCallingPermission(sHardwareTest))) {
const int pid = ipc->getCallingPid();
ALOGE("Permission Denial: "
"can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}
int n;
switch (code) {
case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
return NO_ERROR;
case 1002: // SHOW_UPDATES
n = data.readInt32();
mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
invalidateHwcGeometry();
repaintEverything();
return NO_ERROR;
case 1004:{ // repaint everything
repaintEverything();
return NO_ERROR;
}
case 1005:{ // force transaction
Mutex::Autolock _l(mStateLock);
setTransactionFlags(
eTransactionNeeded|
eDisplayTransactionNeeded|
eTraversalNeeded);
return NO_ERROR;
}
case 1006:{ // send empty update
signalRefresh();
return NO_ERROR;
}
case 1008: // toggle use of hw composer
n = data.readInt32();
mDebugDisableHWC = n ? 1 : 0;
invalidateHwcGeometry();
repaintEverything();
return NO_ERROR;
case 1009: // toggle use of transform hint
n = data.readInt32();
mDebugDisableTransformHint = n ? 1 : 0;
invalidateHwcGeometry();
repaintEverything();
return NO_ERROR;
case 1010: // interrogate.
reply->writeInt32(0);
reply->writeInt32(0);
reply->writeInt32(mDebugRegion);
reply->writeInt32(0);
reply->writeInt32(mDebugDisableHWC);
return NO_ERROR;
case 1013: {
sp<const DisplayDevice> hw(getDefaultDisplayDevice());
reply->writeInt32(hw->getPageFlipCount());
return NO_ERROR;
}
case 1014: {
Mutex::Autolock _l(mStateLock);
// daltonize
n = data.readInt32();
switch (n % 10) {
case 1:
mDaltonizer.setType(ColorBlindnessType::Protanomaly);
break;
case 2:
mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
break;
case 3:
mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
break;
default:
mDaltonizer.setType(ColorBlindnessType::None);
break;
}
if (n >= 10) {
mDaltonizer.setMode(ColorBlindnessMode::Correction);
} else {
mDaltonizer.setMode(ColorBlindnessMode::Simulation);
}
updateColorMatrixLocked();
return NO_ERROR;
}
case 1015: {
Mutex::Autolock _l(mStateLock);
// apply a color matrix
n = data.readInt32();
if (n) {
// color matrix is sent as a column-major mat4 matrix
for (size_t i = 0 ; i < 4; i++) {
for (size_t j = 0; j < 4; j++) {
mClientColorMatrix[i][j] = data.readFloat();
}
}
} else {
mClientColorMatrix = mat4();
}
// Check that supplied matrix's last row is {0,0,0,1} so we can avoid
// the division by w in the fragment shader
float4 lastRow(transpose(mClientColorMatrix)[3]);
if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
ALOGE("The color transform's last row must be (0, 0, 0, 1)");
}
updateColorMatrixLocked();
return NO_ERROR;
}
// This is an experimental interface
// Needs to be shifted to proper binder interface when we productize
case 1016: {
n = data.readInt32();
mPrimaryDispSync.setRefreshSkipCount(n);
return NO_ERROR;
}
case 1017: {
n = data.readInt32();
mForceFullDamage = static_cast<bool>(n);
return NO_ERROR;
}
case 1018: { // Modify Choreographer's phase offset
n = data.readInt32();
mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
return NO_ERROR;
}
case 1019: { // Modify SurfaceFlinger's phase offset
n = data.readInt32();
mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
return NO_ERROR;
}
case 1020: { // Layer updates interceptor
n = data.readInt32();
if (n) {
ALOGV("Interceptor enabled");
mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
}
else{
ALOGV("Interceptor disabled");
mInterceptor->disable();
}
return NO_ERROR;
}
case 1021: { // Disable HWC virtual displays
n = data.readInt32();
mUseHwcVirtualDisplays = !n;
return NO_ERROR;
}
case 1022: { // Set saturation boost
Mutex::Autolock _l(mStateLock);
mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
updateColorMatrixLocked();
return NO_ERROR;
}
case 1023: { // Set native mode
mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
invalidateHwcGeometry();
repaintEverything();
return NO_ERROR;
}
case 1024: { // Is wide color gamut rendering/color management supported?
reply->writeBool(hasWideColorDisplay);
return NO_ERROR;
}
case 1025: { // Set layer tracing
n = data.readInt32();
if (n) {
ALOGV("LayerTracing enabled");
mTracing.enable();
doTracing("tracing.enable");
reply->writeInt32(NO_ERROR);
} else {
ALOGV("LayerTracing disabled");
status_t err = mTracing.disable();
reply->writeInt32(err);
}
return NO_ERROR;
}
case 1026: { // Get layer tracing status
reply->writeBool(mTracing.isEnabled());
return NO_ERROR;
}
// Is a DisplayColorSetting supported?
case 1027: {
sp<const DisplayDevice> hw(getDefaultDisplayDevice());
if (!hw) {
return NAME_NOT_FOUND;
}
DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
switch (setting) {
case DisplayColorSetting::MANAGED:
reply->writeBool(hasWideColorDisplay);
break;
case DisplayColorSetting::UNMANAGED:
reply->writeBool(true);
break;
case DisplayColorSetting::ENHANCED:
reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
break;
default: // vendor display color setting
reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
break;
}
return NO_ERROR;
}
}
}
return err;
}
void SurfaceFlinger::repaintEverything() {
android_atomic_or(1, &mRepaintEverything);
signalTransaction();
}
// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
class WindowDisconnector {
public:
WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
~WindowDisconnector() {
native_window_api_disconnect(mWindow, mApi);
}
private:
ANativeWindow* mWindow;
const int mApi;
};
status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
int32_t minLayerZ, int32_t maxLayerZ,
bool useIdentityTransform,
ISurfaceComposer::Rotation rotation) {
ATRACE_CALL();
if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
device, minLayerZ, maxLayerZ, std::placeholders::_1);
return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
}
status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
float frameScale, bool childrenOnly) {
ATRACE_CALL();
class LayerRenderArea : public RenderArea {
public:
LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
: RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
mLayer(layer),
mCrop(crop),
mFlinger(flinger),
mChildrenOnly(childrenOnly) {}
const Transform& getTransform() const override { return mTransform; }
Rect getBounds() const override {
const Layer::State& layerState(mLayer->getDrawingState());
return Rect(layerState.active.w, layerState.active.h);
}
int getHeight() const override { return mLayer->getDrawingState().active.h; }
int getWidth() const override { return mLayer->getDrawingState().active.w; }
bool isSecure() const override { return false; }
bool needsFiltering() const override { return false; }
Rect getSourceCrop() const override {
if (mCrop.isEmpty()) {
return getBounds();
} else {
return mCrop;
}
}
class ReparentForDrawing {
public:
const sp<Layer>& oldParent;
const sp<Layer>& newParent;
ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
: oldParent(oldParent), newParent(newParent) {
oldParent->setChildrenDrawingParent(newParent);
}
~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
};
void render(std::function<void()> drawLayers) override {
if (!mChildrenOnly) {
mTransform = mLayer->getTransform().inverse();
drawLayers();
} else {
Rect bounds = getBounds();
screenshotParentLayer =
new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
bounds.getWidth(), bounds.getHeight(), 0);
ReparentForDrawing reparent(mLayer, screenshotParentLayer);
drawLayers();
}
}
private:
const sp<Layer> mLayer;
const Rect mCrop;
// In the "childrenOnly" case we reparent the children to a screenshot
// layer which has no properties set and which does not draw.
sp<ContainerLayer> screenshotParentLayer;
Transform mTransform;
SurfaceFlinger* mFlinger;
const bool mChildrenOnly;
};
auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
auto parent = layerHandle->owner.promote();
if (parent == nullptr || parent->isPendingRemoval()) {
ALOGE("captureLayers called with a removed parent");
return NAME_NOT_FOUND;
}
const int uid = IPCThreadState::self()->getCallingUid();
const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
return PERMISSION_DENIED;
}
Rect crop(sourceCrop);
if (sourceCrop.width() <= 0) {
crop.left = 0;
crop.right = parent->getCurrentState().active.w;
}
if (sourceCrop.height() <= 0) {
crop.top = 0;
crop.bottom = parent->getCurrentState().active.h;
}
int32_t reqWidth = crop.width() * frameScale;
int32_t reqHeight = crop.height() * frameScale;
LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
if (!layer->isVisible()) {
return;
} else if (childrenOnly && layer == parent.get()) {
return;
}
visitor(layer);
});
};
return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
}
status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
TraverseLayersFunction traverseLayers,
sp<GraphicBuffer>* outBuffer,
bool useIdentityTransform) {
ATRACE_CALL();
renderArea.updateDimensions(mPrimaryDisplayOrientation);
const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
*outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
// This mutex protects syncFd and captureResult for communication of the return values from the
// main thread back to this Binder thread
std::mutex captureMutex;
std::condition_variable captureCondition;
std::unique_lock<std::mutex> captureLock(captureMutex);
int syncFd = -1;
std::optional<status_t> captureResult;
const int uid = IPCThreadState::self()->getCallingUid();
const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
sp<LambdaMessage> message = new LambdaMessage([&]() {
// If there is a refresh pending, bug out early and tell the binder thread to try again
// after the refresh.
if (mRefreshPending) {
ATRACE_NAME("Skipping screenshot for now");
std::unique_lock<std::mutex> captureLock(captureMutex);
captureResult = std::make_optional<status_t>(EAGAIN);
captureCondition.notify_one();
return;
}
status_t result = NO_ERROR;
int fd = -1;
{
Mutex::Autolock _l(mStateLock);
renderArea.render([&]() {
result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
useIdentityTransform, forSystem, &fd);
});
}
{
std::unique_lock<std::mutex> captureLock(captureMutex);
syncFd = fd;
captureResult = std::make_optional<status_t>(result);
captureCondition.notify_one();
}
});
status_t result = postMessageAsync(message);
if (result == NO_ERROR) {
captureCondition.wait(captureLock, [&]() { return captureResult; });
while (*captureResult == EAGAIN) {
captureResult.reset();
result = postMessageAsync(message);
if (result != NO_ERROR) {
return result;
}
captureCondition.wait(captureLock, [&]() { return captureResult; });
}
result = *captureResult;
}
if (result == NO_ERROR) {
sync_wait(syncFd, -1);
close(syncFd);
}
return result;
}
void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
TraverseLayersFunction traverseLayers, bool yswap,
bool useIdentityTransform) {
ATRACE_CALL();
auto& engine(getRenderEngine());
// get screen geometry
const auto raWidth = renderArea.getWidth();
const auto raHeight = renderArea.getHeight();
const auto reqWidth = renderArea.getReqWidth();
const auto reqHeight = renderArea.getReqHeight();
Rect sourceCrop = renderArea.getSourceCrop();
bool filtering = false;
if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
filtering = static_cast<int32_t>(reqWidth) != raHeight ||
static_cast<int32_t>(reqHeight) != raWidth;
} else {
filtering = static_cast<int32_t>(reqWidth) != raWidth ||
static_cast<int32_t>(reqHeight) != raHeight;
}
// if a default or invalid sourceCrop is passed in, set reasonable values
if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
sourceCrop.setLeftTop(Point(0, 0));
sourceCrop.setRightBottom(Point(raWidth, raHeight));
} else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Transform tr;
uint32_t flags = 0x00;
switch (mPrimaryDisplayOrientation) {
case DisplayState::eOrientation90:
flags = Transform::ROT_90;
break;
case DisplayState::eOrientation180:
flags = Transform::ROT_180;
break;
case DisplayState::eOrientation270:
flags = Transform::ROT_270;
break;
}
tr.set(flags, raWidth, raHeight);
sourceCrop = tr.transform(sourceCrop);
}
// ensure that sourceCrop is inside screen
if (sourceCrop.left < 0) {
ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
}
if (sourceCrop.right > raWidth) {
ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
}
if (sourceCrop.top < 0) {
ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
}
if (sourceCrop.bottom > raHeight) {
ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
}
// assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
engine.setOutputDataSpace(Dataspace::SRGB);
engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
// make sure to clear all GL error flags
engine.checkErrors();
Transform::orientation_flags rotation = renderArea.getRotationFlags();
if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
// convert hw orientation into flag presentation
// here inverse transform needed
uint8_t hw_rot_90 = 0x00;
uint8_t hw_flip_hv = 0x00;
switch (mPrimaryDisplayOrientation) {
case DisplayState::eOrientation90:
hw_rot_90 = Transform::ROT_90;
hw_flip_hv = Transform::ROT_180;
break;
case DisplayState::eOrientation180:
hw_flip_hv = Transform::ROT_180;
break;
case DisplayState::eOrientation270:
hw_rot_90 = Transform::ROT_90;
break;
}
// transform flags operation
// 1) flip H V if both have ROT_90 flag
// 2) XOR these flags
uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
if (rotation_rot_90 & hw_rot_90) {
rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
}
rotation = static_cast<Transform::orientation_flags>
((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
}
// set-up our viewport
engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
rotation);
engine.disableTexturing();
const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
// redraw the screen entirely...
engine.clearWithColor(0, 0, 0, alpha);
traverseLayers([&](Layer* layer) {
if (filtering) layer->setFiltering(true);
layer->draw(renderArea, useIdentityTransform);
if (filtering) layer->setFiltering(false);
});
}
status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
TraverseLayersFunction traverseLayers,
ANativeWindowBuffer* buffer,
bool useIdentityTransform,
bool forSystem,
int* outSyncFd) {
ATRACE_CALL();
bool secureLayerIsVisible = false;
traverseLayers([&](Layer* layer) {
secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
});
// We allow the system server to take screenshots of secure layers for
// use in situations like the Screen-rotation animation and place
// the impetus on WindowManager to not persist them.
if (secureLayerIsVisible && !forSystem) {
ALOGW("FB is protected: PERMISSION_DENIED");
return PERMISSION_DENIED;
}
// this binds the given EGLImage as a framebuffer for the
// duration of this scope.
RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
if (bufferBond.getStatus() != NO_ERROR) {
ALOGE("got ANWB binding error while taking screenshot");
return INVALID_OPERATION;
}
// this will in fact render into our dequeued buffer
// via an FBO, which means we didn't have to create
// an EGLSurface and therefore we're not
// dependent on the context's EGLConfig.
renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
if (DEBUG_SCREENSHOTS) {
getRenderEngine().finish();
*outSyncFd = -1;
const auto reqWidth = renderArea.getReqWidth();
const auto reqHeight = renderArea.getReqHeight();
uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
delete [] pixels;
} else {
base::unique_fd syncFd = getRenderEngine().flush();
if (syncFd < 0) {
getRenderEngine().finish();
}
*outSyncFd = syncFd.release();
}
return NO_ERROR;
}
void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
TraverseLayersFunction traverseLayers) {
if (DEBUG_SCREENSHOTS) {
for (size_t y = 0; y < h; y++) {
uint32_t const* p = (uint32_t const*)vaddr + y * s;
for (size_t x = 0; x < w; x++) {
if (p[x] != 0xFF000000) return;
}
}
ALOGE("*** we just took a black screenshot ***");
size_t i = 0;
traverseLayers([&](Layer* layer) {
const Layer::State& state(layer->getDrawingState());
ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
layer->isVisible() ? '+' : '-', i, layer->getName().string(),
layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
static_cast<float>(state.color.a));
i++;
});
}
}
// ---------------------------------------------------------------------------
void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
layersSortedByZ.traverseInZOrder(stateSet, visitor);
}
void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
}
void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
int32_t maxLayerZ,
const LayerVector::Visitor& visitor) {
// We loop through the first level of layers without traversing,
// as we need to interpret min/max layer Z in the top level Z space.
for (const auto& layer : mDrawingState.layersSortedByZ) {
if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
continue;
}
const Layer::State& state(layer->getDrawingState());
// relative layers are traversed in Layer::traverseInZOrder
if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
continue;
}
layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
return;
}
if (!layer->isVisible()) {
return;
}
visitor(layer);
});
}
}
}; // namespace android
#if defined(__gl_h_)
#error "don't include gl/gl.h in this file"
#endif
#if defined(__gl2_h_)
#error "don't include gl2/gl2.h in this file"
#endif
| 37.597246 | 119 | 0.607858 | [
"geometry",
"render",
"vector",
"transform"
] |
87bd345088c5411a39960441c61199d1474b0d41 | 4,123 | cpp | C++ | src/demo/ahe/square-benchmark.cpp | carlzhangweiwen/gazelle_mpc | 45818ccf6375100a8fe2680f44f37d713380aa5c | [
"MIT"
] | 50 | 2018-10-05T02:46:53.000Z | 2022-03-20T08:47:46.000Z | src/demo/ahe/square-benchmark.cpp | WeiBenqiang/gazelle_mpc | f4eb3bae09bf4897f2651946eac7dee17e094a6f | [
"MIT"
] | 7 | 2018-10-11T17:19:12.000Z | 2022-03-08T16:45:11.000Z | src/demo/ahe/square-benchmark.cpp | WeiBenqiang/gazelle_mpc | f4eb3bae09bf4897f2651946eac7dee17e094a6f | [
"MIT"
] | 20 | 2018-12-09T17:44:11.000Z | 2022-03-01T12:13:21.000Z | /*
NN-Layers-Benchmarking: This code benchmarks FC and Conv layers for a neural network
List of Authors:
Chiraag Juvekar, chiraag@mit.edu
License Information:
MIT License
Copyright (c) 2017, Massachusetts Institute of Technology (MIT)
*/
#include <pke/gazelle.h>
#include <utils/backend.h>
#include <iostream>
#include <random>
#include "math/bit_twiddle.h"
using namespace std;
using namespace lbcrypto;
int main() {
std::cout << "NN Layers Benchmark (ms):" << std::endl;
//------------------ Setup Parameters ------------------
ui64 nRep = 1;
double start, stop;
ui64 z = RootOfUnity(opt::phim << 1, opt::q);
ui64 z_p = RootOfUnity(opt::phim << 1, opt::p);
ftt_precompute(z, opt::q, opt::logn);
ftt_precompute(z_p, opt::p, opt::logn);
encoding_precompute(opt::p, opt::logn);
precompute_automorph_index(opt::phim);
DiscreteGaussianGenerator dgg = DiscreteGaussianGenerator(4.0);
FVParams slow_params {
false,
opt::q, opt::p, opt::logn, opt::phim,
(opt::q/opt::p),
OPTIMIZED, std::make_shared<DiscreteGaussianGenerator>(dgg),
8
};
FVParams fast_params = slow_params;
fast_params.fast_modulli = true;
FVParams test_params = fast_params;
//------------------- Synthetic Data -------------------
ui32 vec_size = 2048;
std::cin >> vec_size;
uv64 vec_c = get_dgg_testvector(vec_size, opt::p);
uv64 vec_s = get_dgg_testvector(vec_size, opt::p);
//----------------------- KeyGen -----------------------
nRep = 10;
auto kp = KeyGen(test_params);
start = currentDateTime();
for(ui64 i=0; i < nRep; i++){
kp = KeyGen(test_params);
}
stop = currentDateTime();
std::cout << " KeyGen: " << (stop-start)/nRep << std::endl;
//----------------- Client Preprocess ------------------
nRep = 100;
auto ct_vec = preprocess_client_share(kp.sk, vec_c, test_params);
start = currentDateTime();
for(ui64 i=0; i < nRep; i++){
ct_vec = preprocess_client_share(kp.sk, vec_c, test_params);
}
stop = currentDateTime();
std::cout << " Preprocess Client: " << (stop-start)/nRep << std::endl;
//----------------- Server Preprocess -----------------
std::vector<uv64> pt_vec;
uv64 vec_s_f;
std::tie(pt_vec, vec_s_f) = preprocess_server_share(vec_s, test_params);
start = currentDateTime();
for(ui64 i=0; i < nRep; i++){
std::tie(pt_vec, vec_s_f) = preprocess_server_share(vec_s, test_params);
}
stop = currentDateTime();
std::cout << " Preprocess Server: " << (stop-start)/nRep << std::endl;
//---------------------- Square -----------------------
auto ct_c_f = square_online(ct_vec, pt_vec, test_params);
start = currentDateTime();
for(ui64 i=0; i < nRep; i++){
ct_c_f = square_online(ct_vec, pt_vec, test_params);
}
stop = currentDateTime();
std::cout << " Multiply: " << (stop-start)/nRep << std::endl;
//------------------- Post-Process ---------------------
auto vec_c_f = postprocess_client_share(kp.sk, ct_c_f, vec_size, test_params);
start = currentDateTime();
for(ui64 i=0; i < nRep; i++){
vec_c_f = postprocess_client_share(kp.sk, ct_c_f, vec_size, test_params);
}
stop = currentDateTime();
std::cout << " Post-Process: " << (stop-start)/nRep << std::endl;
//--------------------- Square PT ----------------------
start = currentDateTime();
auto vec_c_f_ref = square_pt(vec_c, vec_s, vec_s_f, opt::p);
for(ui64 i=0; i < nRep; i++){
vec_c_f_ref = square_pt(vec_c, vec_s, vec_s_f, opt::p);
}
stop = currentDateTime();
std::cout << " Multiply PT: " << (stop-start)/nRep << std::endl;
//----------------------- Check ------------------------
// std::cout << std::endl;
// std::cout << "Margin ct: " << NoiseMargin(kp.sk, ct_vec[0], test_params) << std::endl;
// std::cout << "Margin prod: " << NoiseMargin(kp.sk, ct_prod, test_params) << std::endl;
std::cout << std::endl;
check_vec_eq(vec_c_f_ref, vec_c_f, "square mismatch:\n");
return 0;
}
| 32.722222 | 93 | 0.570943 | [
"vector"
] |
87c0026cfb3abfefc43227a77e7a26320d47430a | 20,669 | hpp | C++ | include/System/Security/Cryptography/AesCryptoServiceProvider.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Security/Cryptography/AesCryptoServiceProvider.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Security/Cryptography/AesCryptoServiceProvider.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Security.Cryptography.Aes
#include "System/Security/Cryptography/Aes.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Security::Cryptography
namespace System::Security::Cryptography {
// Skipping declaration: CipherMode because it is already included!
// Skipping declaration: PaddingMode because it is already included!
// Forward declaring type: ICryptoTransform
class ICryptoTransform;
}
// Completed forward declares
// Type namespace: System.Security.Cryptography
namespace System::Security::Cryptography {
// Forward declaring type: AesCryptoServiceProvider
class AesCryptoServiceProvider;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Security::Cryptography::AesCryptoServiceProvider);
DEFINE_IL2CPP_ARG_TYPE(::System::Security::Cryptography::AesCryptoServiceProvider*, "System.Security.Cryptography", "AesCryptoServiceProvider");
// Type namespace: System.Security.Cryptography
namespace System::Security::Cryptography {
// Size: 0x44
#pragma pack(push, 1)
// Autogenerated type: System.Security.Cryptography.AesCryptoServiceProvider
// [TokenAttribute] Offset: FFFFFFFF
class AesCryptoServiceProvider : public ::System::Security::Cryptography::Aes {
public:
// public System.Void .ctor()
// Offset: 0x11EC7CC
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AesCryptoServiceProvider* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Security::Cryptography::AesCryptoServiceProvider::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AesCryptoServiceProvider*, creationType>()));
}
// public override System.Byte[] get_IV()
// Offset: 0x11ED190
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Byte[] SymmetricAlgorithm::get_IV()
::ArrayW<uint8_t> get_IV();
// public override System.Void set_IV(System.Byte[] value)
// Offset: 0x11ED198
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Void SymmetricAlgorithm::set_IV(System.Byte[] value)
void set_IV(::ArrayW<uint8_t> value);
// public override System.Byte[] get_Key()
// Offset: 0x11ED1A0
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Byte[] SymmetricAlgorithm::get_Key()
::ArrayW<uint8_t> get_Key();
// public override System.Void set_Key(System.Byte[] value)
// Offset: 0x11ED1A8
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Void SymmetricAlgorithm::set_Key(System.Byte[] value)
void set_Key(::ArrayW<uint8_t> value);
// public override System.Int32 get_KeySize()
// Offset: 0x11ED1B0
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Int32 SymmetricAlgorithm::get_KeySize()
int get_KeySize();
// public override System.Void set_KeySize(System.Int32 value)
// Offset: 0x11ED1B8
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Void SymmetricAlgorithm::set_KeySize(System.Int32 value)
void set_KeySize(int value);
// public override System.Int32 get_FeedbackSize()
// Offset: 0x11ED1C0
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Int32 SymmetricAlgorithm::get_FeedbackSize()
int get_FeedbackSize();
// public override System.Security.Cryptography.CipherMode get_Mode()
// Offset: 0x11ED1C8
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Security.Cryptography.CipherMode SymmetricAlgorithm::get_Mode()
::System::Security::Cryptography::CipherMode get_Mode();
// public override System.Void set_Mode(System.Security.Cryptography.CipherMode value)
// Offset: 0x11ED1D0
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Void SymmetricAlgorithm::set_Mode(System.Security.Cryptography.CipherMode value)
void set_Mode(::System::Security::Cryptography::CipherMode value);
// public override System.Security.Cryptography.PaddingMode get_Padding()
// Offset: 0x11ED234
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Security.Cryptography.PaddingMode SymmetricAlgorithm::get_Padding()
::System::Security::Cryptography::PaddingMode get_Padding();
// public override System.Void set_Padding(System.Security.Cryptography.PaddingMode value)
// Offset: 0x11ED23C
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Void SymmetricAlgorithm::set_Padding(System.Security.Cryptography.PaddingMode value)
void set_Padding(::System::Security::Cryptography::PaddingMode value);
// public override System.Void GenerateIV()
// Offset: 0x11EC83C
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Void SymmetricAlgorithm::GenerateIV()
void GenerateIV();
// public override System.Void GenerateKey()
// Offset: 0x11EC86C
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Void SymmetricAlgorithm::GenerateKey()
void GenerateKey();
// public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(System.Byte[] key, System.Byte[] iv)
// Offset: 0x11EC89C
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Security.Cryptography.ICryptoTransform SymmetricAlgorithm::CreateDecryptor(System.Byte[] key, System.Byte[] iv)
::System::Security::Cryptography::ICryptoTransform* CreateDecryptor(::ArrayW<uint8_t> key, ::ArrayW<uint8_t> iv);
// public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(System.Byte[] key, System.Byte[] iv)
// Offset: 0x11ED09C
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Security.Cryptography.ICryptoTransform SymmetricAlgorithm::CreateEncryptor(System.Byte[] key, System.Byte[] iv)
::System::Security::Cryptography::ICryptoTransform* CreateEncryptor(::ArrayW<uint8_t> key, ::ArrayW<uint8_t> iv);
// public override System.Security.Cryptography.ICryptoTransform CreateDecryptor()
// Offset: 0x11ED244
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Security.Cryptography.ICryptoTransform SymmetricAlgorithm::CreateDecryptor()
::System::Security::Cryptography::ICryptoTransform* CreateDecryptor();
// public override System.Security.Cryptography.ICryptoTransform CreateEncryptor()
// Offset: 0x11ED298
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Security.Cryptography.ICryptoTransform SymmetricAlgorithm::CreateEncryptor()
::System::Security::Cryptography::ICryptoTransform* CreateEncryptor();
// protected override System.Void Dispose(System.Boolean disposing)
// Offset: 0x11ED2EC
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Void SymmetricAlgorithm::Dispose(System.Boolean disposing)
void Dispose(bool disposing);
}; // System.Security.Cryptography.AesCryptoServiceProvider
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::get_IV
// Il2CppName: get_IV
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<uint8_t> (System::Security::Cryptography::AesCryptoServiceProvider::*)()>(&System::Security::Cryptography::AesCryptoServiceProvider::get_IV)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "get_IV", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::set_IV
// Il2CppName: set_IV
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesCryptoServiceProvider::*)(::ArrayW<uint8_t>)>(&System::Security::Cryptography::AesCryptoServiceProvider::set_IV)> {
static const MethodInfo* get() {
static auto* value = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "set_IV", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::get_Key
// Il2CppName: get_Key
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<uint8_t> (System::Security::Cryptography::AesCryptoServiceProvider::*)()>(&System::Security::Cryptography::AesCryptoServiceProvider::get_Key)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "get_Key", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::set_Key
// Il2CppName: set_Key
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesCryptoServiceProvider::*)(::ArrayW<uint8_t>)>(&System::Security::Cryptography::AesCryptoServiceProvider::set_Key)> {
static const MethodInfo* get() {
static auto* value = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "set_Key", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::get_KeySize
// Il2CppName: get_KeySize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Security::Cryptography::AesCryptoServiceProvider::*)()>(&System::Security::Cryptography::AesCryptoServiceProvider::get_KeySize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "get_KeySize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::set_KeySize
// Il2CppName: set_KeySize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesCryptoServiceProvider::*)(int)>(&System::Security::Cryptography::AesCryptoServiceProvider::set_KeySize)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "set_KeySize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::get_FeedbackSize
// Il2CppName: get_FeedbackSize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Security::Cryptography::AesCryptoServiceProvider::*)()>(&System::Security::Cryptography::AesCryptoServiceProvider::get_FeedbackSize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "get_FeedbackSize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::get_Mode
// Il2CppName: get_Mode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Security::Cryptography::CipherMode (System::Security::Cryptography::AesCryptoServiceProvider::*)()>(&System::Security::Cryptography::AesCryptoServiceProvider::get_Mode)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "get_Mode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::set_Mode
// Il2CppName: set_Mode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesCryptoServiceProvider::*)(::System::Security::Cryptography::CipherMode)>(&System::Security::Cryptography::AesCryptoServiceProvider::set_Mode)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System.Security.Cryptography", "CipherMode")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "set_Mode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::get_Padding
// Il2CppName: get_Padding
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Security::Cryptography::PaddingMode (System::Security::Cryptography::AesCryptoServiceProvider::*)()>(&System::Security::Cryptography::AesCryptoServiceProvider::get_Padding)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "get_Padding", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::set_Padding
// Il2CppName: set_Padding
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesCryptoServiceProvider::*)(::System::Security::Cryptography::PaddingMode)>(&System::Security::Cryptography::AesCryptoServiceProvider::set_Padding)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System.Security.Cryptography", "PaddingMode")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "set_Padding", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::GenerateIV
// Il2CppName: GenerateIV
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesCryptoServiceProvider::*)()>(&System::Security::Cryptography::AesCryptoServiceProvider::GenerateIV)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "GenerateIV", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::GenerateKey
// Il2CppName: GenerateKey
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesCryptoServiceProvider::*)()>(&System::Security::Cryptography::AesCryptoServiceProvider::GenerateKey)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "GenerateKey", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::CreateDecryptor
// Il2CppName: CreateDecryptor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Security::Cryptography::ICryptoTransform* (System::Security::Cryptography::AesCryptoServiceProvider::*)(::ArrayW<uint8_t>, ::ArrayW<uint8_t>)>(&System::Security::Cryptography::AesCryptoServiceProvider::CreateDecryptor)> {
static const MethodInfo* get() {
static auto* key = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* iv = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "CreateDecryptor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{key, iv});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::CreateEncryptor
// Il2CppName: CreateEncryptor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Security::Cryptography::ICryptoTransform* (System::Security::Cryptography::AesCryptoServiceProvider::*)(::ArrayW<uint8_t>, ::ArrayW<uint8_t>)>(&System::Security::Cryptography::AesCryptoServiceProvider::CreateEncryptor)> {
static const MethodInfo* get() {
static auto* key = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* iv = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "CreateEncryptor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{key, iv});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::CreateDecryptor
// Il2CppName: CreateDecryptor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Security::Cryptography::ICryptoTransform* (System::Security::Cryptography::AesCryptoServiceProvider::*)()>(&System::Security::Cryptography::AesCryptoServiceProvider::CreateDecryptor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "CreateDecryptor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::CreateEncryptor
// Il2CppName: CreateEncryptor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Security::Cryptography::ICryptoTransform* (System::Security::Cryptography::AesCryptoServiceProvider::*)()>(&System::Security::Cryptography::AesCryptoServiceProvider::CreateEncryptor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "CreateEncryptor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesCryptoServiceProvider::Dispose
// Il2CppName: Dispose
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesCryptoServiceProvider::*)(bool)>(&System::Security::Cryptography::AesCryptoServiceProvider::Dispose)> {
static const MethodInfo* get() {
static auto* disposing = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesCryptoServiceProvider*), "Dispose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{disposing});
}
};
| 68.896667 | 300 | 0.768784 | [
"vector"
] |
d7ad4131ece6f2edce23e2fc082c9c9a4a012f83 | 2,831 | cpp | C++ | Libraries/RobsJuceModules/romos/TestSuite/romos_TestEventGenerator.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 34 | 2017-04-19T18:26:02.000Z | 2022-02-15T17:47:26.000Z | Libraries/RobsJuceModules/romos/TestSuite/romos_TestEventGenerator.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 307 | 2017-05-04T21:45:01.000Z | 2022-02-03T00:59:01.000Z | Libraries/RobsJuceModules/romos/TestSuite/romos_TestEventGenerator.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 4 | 2017-09-05T17:04:31.000Z | 2021-12-15T21:24:28.000Z | #include "romos_TestEventGenerator.h"
//using namespace rsTestRomos;
namespace rsTestRomos
{
std::vector<romos::NoteEvent> TestEventGenerator::generateNoteOnOffPair(unsigned int key, unsigned int velocity,
unsigned int deltaFramesForNoteOn, unsigned int durationInFrames)
{
std::vector<romos::NoteEvent> result;
if(durationInFrames == 0)
return result; // return an empty vector - note-ons with simultaneous note-offs are discarded
result.push_back(romos::NoteEvent(deltaFramesForNoteOn, key, velocity));
result.push_back(romos::NoteEvent(deltaFramesForNoteOn + durationInFrames, key, 0));
return result;
}
std::vector<romos::NoteEvent> TestEventGenerator::generateSimultaneousNotes(unsigned int key, unsigned int velocity,
unsigned int deltaFramesForNoteOn, unsigned int durationInFrames,
unsigned int numNotes, unsigned int noteSpacing)
{
std::vector<romos::NoteEvent> result;
unsigned int currentKey = key;
for(unsigned int i = 1; i <= numNotes; i++)
{
result = mergeEvents(result, generateNoteOnOffPair(currentKey, velocity, deltaFramesForNoteOn, durationInFrames));
currentKey += noteSpacing;
}
return result;
}
std::vector<romos::NoteEvent> TestEventGenerator::mergeEvents(const std::vector<romos::NoteEvent>& eventArray1,
const std::vector<romos::NoteEvent>& eventArray2)
{
std::vector<romos::NoteEvent> result;
result.reserve(eventArray1.size() + eventArray2.size());
unsigned int i;
for(i = 0; i < eventArray1.size(); i++)
result.push_back(eventArray1[i]);
for(i = 0; i < eventArray2.size(); i++)
result.push_back(eventArray2[i]);
std::sort(result.begin(), result.end(), noteEventLessByDeltaFrames);
return result;
}
void TestEventGenerator::convertNoteEventsToStartsAndDurations(const std::vector<romos::NoteEvent>& events,
std::vector<romos::NoteEvent>& noteOns, std::vector<int>& durations)
{
unsigned int i;
noteOns.clear();
for(i = 0; i < events.size(); i++)
{
if(events[i].getVelocity() != 0)
noteOns.push_back(events[i]);
}
durations.reserve(noteOns.size());
for(i = 0; i < noteOns.size(); i++)
{
int noteOffIndex = findIndexOfMatchingNoteOff(events, noteOns[i]);
if(noteOffIndex > -1)
durations.push_back(events[noteOffIndex].getDeltaFrames() - noteOns[i].getDeltaFrames());
else
durations.push_back(INT_MAX); // no matching note-off - potentially infinite duration, but INT_MAX is the largest we have
}
}
int TestEventGenerator::findIndexOfMatchingNoteOff(const std::vector<romos::NoteEvent>& events, romos::NoteEvent noteOnEvent)
{
unsigned int i;
unsigned int startIndex = rosic::findElement(events, noteOnEvent) + 1;
for(i = startIndex; i < events.size(); i++)
{
if(events[i].isNoteOff() && events[i].getKey() == noteOnEvent.getKey())
return i;
}
return -1;
}
} | 35.3875 | 128 | 0.726245 | [
"vector"
] |
d7add128a3f3ce4c57dee406460925411068be2d | 9,548 | cpp | C++ | client/include/game/CPickups.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 368 | 2015-01-01T21:42:00.000Z | 2022-03-29T06:22:22.000Z | client/include/game/CPickups.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 92 | 2019-01-23T23:02:31.000Z | 2022-03-23T19:59:40.000Z | client/include/game/CPickups.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 179 | 2015-02-03T23:41:17.000Z | 2022-03-26T08:27:16.000Z | /*
Plugin-SDK (Grand Theft Auto San Andreas) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CPickups.h"
unsigned int MAX_COLLECTED_PICKUPS = 20;
unsigned int MAX_PICKUP_MESSAGES = 16;
unsigned int MAX_NUM_PICKUPS = 620;
unsigned char &CPickups::DisplayHelpMessage = *(unsigned char *)0x8A5F48;
int &CPickups::PlayerOnWeaponPickup = *(int *)0x97D640;
int &CPickups::StaticCamStartTime = *(int *)0x978618;
CVector *CPickups::StaticCamCoors = (CVector *)0x97D660;
CVehicle *&CPickups::pPlayerVehicle = *(CVehicle **)0x97861C;
bool &CPickups::bPickUpcamActivated = *(bool *)0x978620;
unsigned short &CPickups::CollectedPickUpIndex = *(unsigned short *)0x978624;
int *CPickups::aPickUpsCollected = (int *)0x978628;
unsigned short &CPickups::NumMessages = *(unsigned short *)0x978678;
tPickupMessage *CPickups::aMessages = (tPickupMessage *)0x978680;
CPickup *CPickups::aPickUps = (CPickup *)0x9788C0;
int &CollectPickupBuffer = *(int *)0x97D644;
// Converted from cdecl void CPickups::AddToCollectedPickupsArray(int handle) 0x455240
void CPickups::AddToCollectedPickupsArray(int handle) {
plugin::Call<0x455240, int>(handle);
}
// Converted from cdecl void CPickups::CreatePickupCoorsCloseToCoors(float in_x,float in_y,float in_z,float *out_x,float *out_y,float *out_z) 0x458A80
void CPickups::CreatePickupCoorsCloseToCoors(float in_x, float in_y, float in_z, float* out_x, float* out_y, float* out_z) {
plugin::Call<0x458A80, float, float, float, float*, float*, float*>(in_x, in_y, in_z, out_x, out_y, out_z);
}
// Converted from cdecl void CPickups::CreateSomeMoney(CVector coors,int amount) 0x458970
void CPickups::CreateSomeMoney(CVector coors, int amount) {
plugin::Call<0x458970, CVector, int>(coors, amount);
}
// Converted from cdecl void CPickups::DetonateMinesHitByGunShot(CVector *shotOrigin,CVector *shotTarget) 0x4590C0
void CPickups::DetonateMinesHitByGunShot(CVector* shotOrigin, CVector* shotTarget) {
plugin::Call<0x4590C0, CVector*, CVector*>(shotOrigin, shotTarget);
}
// Converted from cdecl void CPickups::DoCollectableEffects(CEntity *entity) 0x455E20
void CPickups::DoCollectableEffects(CEntity* entity) {
plugin::Call<0x455E20, CEntity*>(entity);
}
// Converted from cdecl void CPickups::DoMineEffects(CEntity *entity) 0x4560E0
void CPickups::DoMineEffects(CEntity* entity) {
plugin::Call<0x4560E0, CEntity*>(entity);
}
// Converted from cdecl void CPickups::DoMoneyEffects(CEntity *entity) 0x454E80
void CPickups::DoMoneyEffects(CEntity* entity) {
plugin::Call<0x454E80, CEntity*>(entity);
}
// Converted from cdecl void CPickups::DoPickUpEffects(CEntity *entity) 0x455720
void CPickups::DoPickUpEffects(CEntity* entity) {
plugin::Call<0x455720, CEntity*>(entity);
}
// Converted from cdecl CPickup* CPickups::FindPickUpForThisObject(CObject *object) 0x4551C0
CPickup* CPickups::FindPickUpForThisObject(CObject* object) {
return plugin::CallAndReturn<CPickup*, 0x4551C0, CObject*>(object);
}
// Converted from cdecl int CPickups::GenerateNewOne(CVector coors,uint modelId,uchar pickupType,uint ammo,uint moneyPerDay,bool isEmpty,char *message) 0x456F20
int CPickups::GenerateNewOne(CVector coors, unsigned int modelId, unsigned char pickupType, unsigned int ammo, unsigned int moneyPerDay, bool isEmpty, char* message) {
return plugin::CallAndReturn<int, 0x456F20, CVector, unsigned int, unsigned char, unsigned int, unsigned int, bool, char*>(coors, modelId, pickupType, ammo, moneyPerDay, isEmpty, message);
}
// Converted from cdecl int CPickups::GenerateNewOne_WeaponType(CVector coors,eWeaponType weaponType,uchar pickupType,uint ammo,bool isEmpty,char *message) 0x457380
int CPickups::GenerateNewOne_WeaponType(CVector coors, eWeaponType weaponType, unsigned char pickupType, unsigned int ammo, bool isEmpty, char* message) {
return plugin::CallAndReturn<int, 0x457380, CVector, eWeaponType, unsigned char, unsigned int, bool, char*>(coors, weaponType, pickupType, ammo, isEmpty, message);
}
// Converted from cdecl int CPickups::GetActualPickupIndex(int pickupIndex) 0x4552A0
int CPickups::GetActualPickupIndex(int pickupIndex) {
return plugin::CallAndReturn<int, 0x4552A0, int>(pickupIndex);
}
// Converted from cdecl int CPickups::GetNewUniquePickupIndex(int pickupIndex) 0x456A30
int CPickups::GetNewUniquePickupIndex(int pickupIndex) {
return plugin::CallAndReturn<int, 0x456A30, int>(pickupIndex);
}
// Converted from cdecl int CPickups::GetUniquePickupIndex(int pickupIndex) 0x455280
int CPickups::GetUniquePickupIndex(int pickupIndex) {
return plugin::CallAndReturn<int, 0x455280, int>(pickupIndex);
}
// Converted from cdecl bool CPickups::GivePlayerGoodiesWithPickUpMI(ushort modelId,int playerId) 0x4564F0
bool CPickups::GivePlayerGoodiesWithPickUpMI(unsigned short modelId, int playerId) {
return plugin::CallAndReturn<bool, 0x4564F0, unsigned short, int>(modelId, playerId);
}
// Converted from cdecl void CPickups::Init(void) 0x454A70
void CPickups::Init() {
plugin::Call<0x454A70>();
}
// Converted from cdecl bool CPickups::IsPickUpPickedUp(int pickupHandle) 0x454B40
bool CPickups::IsPickUpPickedUp(int pickupHandle) {
return plugin::CallAndReturn<bool, 0x454B40, int>(pickupHandle);
}
// Converted from cdecl bool CPickups::Load(void) 0x5D35A0
bool CPickups::Load() {
return plugin::CallAndReturn<bool, 0x5D35A0>();
}
// Converted from cdecl int CPickups::ModelForWeapon(eWeaponType weaponType) 0x454AC0
int CPickups::ModelForWeapon(eWeaponType weaponType) {
return plugin::CallAndReturn<int, 0x454AC0, eWeaponType>(weaponType);
}
// Converted from cdecl void CPickups::PassTime(uint time) 0x455200
void CPickups::PassTime(unsigned int time) {
plugin::Call<0x455200, unsigned int>(time);
}
// Converted from cdecl void CPickups::PickedUpHorseShoe(void) 0x455390
void CPickups::PickedUpHorseShoe() {
plugin::Call<0x455390>();
}
// Converted from cdecl void CPickups::PickedUpOyster(void) 0x4552D0
void CPickups::PickedUpOyster() {
plugin::Call<0x4552D0>();
}
// Converted from cdecl void CPickups::PictureTaken(void) 0x456A70
void CPickups::PictureTaken() {
plugin::Call<0x456A70>();
}
// Converted from cdecl bool CPickups::PlayerCanPickUpThisWeaponTypeAtThisMoment(eWeaponType weaponType) 0x4554C0
bool CPickups::PlayerCanPickUpThisWeaponTypeAtThisMoment(eWeaponType weaponType) {
return plugin::CallAndReturn<bool, 0x4554C0, eWeaponType>(weaponType);
}
// Converted from cdecl void CPickups::ReInit(void) 0x456E60
void CPickups::ReInit() {
plugin::Call<0x456E60>();
}
// Converted from cdecl void CPickups::RemoveMissionPickUps(void) 0x456DE0
void CPickups::RemoveMissionPickUps() {
plugin::Call<0x456DE0>();
}
// Converted from cdecl void CPickups::RemovePickUp(int pickupHandle) 0x4573D0
void CPickups::RemovePickUp(int pickupHandle) {
plugin::Call<0x4573D0, int>(pickupHandle);
}
// Converted from cdecl void CPickups::RemovePickUpsInArea(float cornerA_x,float cornerA_y,float cornerA_z,float cornerB_x,float cornerB_y,float cornerB_z) 0x456D30
void CPickups::RemovePickUpsInArea(float cornerA_x, float cornerA_y, float cornerA_z, float cornerB_x, float cornerB_y, float cornerB_z) {
plugin::Call<0x456D30, float, float, float, float, float, float>(cornerA_x, cornerA_y, cornerA_z, cornerB_x, cornerB_y, cornerB_z);
}
// Converted from cdecl void CPickups::RemovePickupObjects(void) 0x455470
void CPickups::RemovePickupObjects() {
plugin::Call<0x455470>();
}
// Converted from cdecl void CPickups::RemoveUnnecessaryPickups(CVector const&posn,float radius) 0x4563A0
void CPickups::RemoveUnnecessaryPickups(CVector const& posn, float radius) {
plugin::Call<0x4563A0, CVector const&, float>(posn, radius);
}
// Converted from cdecl void CPickups::RenderPickUpText(void) 0x455000
void CPickups::RenderPickUpText() {
plugin::Call<0x455000>();
}
// Converted from cdecl bool CPickups::Save(void) 0x5D3540
bool CPickups::Save() {
return plugin::CallAndReturn<bool, 0x5D3540>();
}
// Converted from cdecl bool CPickups::TestForPickupsInBubble(CVector posn,float radius) 0x456450
bool CPickups::TestForPickupsInBubble(CVector posn, float radius) {
return plugin::CallAndReturn<bool, 0x456450, CVector, float>(posn, radius);
}
// Converted from cdecl bool CPickups::TryToMerge_WeaponType(CVector posn,eWeaponType weaponType,uchar pickupType,uint ammo, bool) 0x4555A0
bool CPickups::TryToMerge_WeaponType(CVector posn, eWeaponType weaponType, unsigned char pickupType, unsigned int ammo, bool _IGNORED_ arg4) {
return plugin::CallAndReturn<bool, 0x4555A0, CVector, eWeaponType, unsigned char, unsigned int, bool>(posn, weaponType, pickupType, ammo, arg4);
}
// Converted from cdecl void CPickups::Update(void) 0x458DE0
void CPickups::Update() {
plugin::Call<0x458DE0>();
}
// Converted from cdecl void CPickups::UpdateMoneyPerDay(int pickupHandle,ushort money) 0x455680
void CPickups::UpdateMoneyPerDay(int pickupHandle, unsigned short money) {
plugin::Call<0x455680, int, unsigned short>(pickupHandle, money);
}
// Converted from cdecl int CPickups::WeaponForModel(int modelId) 0x454AE0
int CPickups::WeaponForModel(int modelId) {
return plugin::CallAndReturn<int, 0x454AE0, int>(modelId);
}
// Converted from cdecl void ModifyStringLabelForControlSetting(char *stringLabel) 0x454B70
void ModifyStringLabelForControlSetting(char* stringLabel) {
plugin::Call<0x454B70, char*>(stringLabel);
} | 44.616822 | 192 | 0.77744 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.