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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9f1e831ffc7ea56f2674d9b55b759e17de77f7e2 | 1,507 | cpp | C++ | android-31/android/nfc/tech/NfcA.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/nfc/tech/NfcA.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/nfc/tech/NfcA.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JByteArray.hpp"
#include "../Tag.hpp"
#include "./NfcA.hpp"
namespace android::nfc::tech
{
// Fields
// QJniObject forward
NfcA::NfcA(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
android::nfc::tech::NfcA NfcA::get(android::nfc::Tag arg0)
{
return callStaticObjectMethod(
"android.nfc.tech.NfcA",
"get",
"(Landroid/nfc/Tag;)Landroid/nfc/tech/NfcA;",
arg0.object()
);
}
void NfcA::close() const
{
callMethod<void>(
"close",
"()V"
);
}
void NfcA::connect() const
{
callMethod<void>(
"connect",
"()V"
);
}
JByteArray NfcA::getAtqa() const
{
return callObjectMethod(
"getAtqa",
"()[B"
);
}
jint NfcA::getMaxTransceiveLength() const
{
return callMethod<jint>(
"getMaxTransceiveLength",
"()I"
);
}
jshort NfcA::getSak() const
{
return callMethod<jshort>(
"getSak",
"()S"
);
}
android::nfc::Tag NfcA::getTag() const
{
return callObjectMethod(
"getTag",
"()Landroid/nfc/Tag;"
);
}
jint NfcA::getTimeout() const
{
return callMethod<jint>(
"getTimeout",
"()I"
);
}
jboolean NfcA::isConnected() const
{
return callMethod<jboolean>(
"isConnected",
"()Z"
);
}
void NfcA::setTimeout(jint arg0) const
{
callMethod<void>(
"setTimeout",
"(I)V",
arg0
);
}
JByteArray NfcA::transceive(JByteArray arg0) const
{
return callObjectMethod(
"transceive",
"([B)[B",
arg0.object<jbyteArray>()
);
}
} // namespace android::nfc::tech
| 15.377551 | 59 | 0.603849 | [
"object"
] |
9f24e63640e68e98020c97989bcee79fb94e1cf9 | 542 | cpp | C++ | C++/minimum-number-of-steps-to-make-two-strings-anagram.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/minimum-number-of-steps-to-make-two-strings-anagram.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/minimum-number-of-steps-to-make-two-strings-anagram.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n)
// Space: O(1)
class Solution {
public:
int minSteps(string s, string t) {
const auto& count1 = counter(s);
const auto& count2 = counter(t);
int result = 0;
for (int i = 0; i < count1.size(); ++i) {
result += max(count1[i] - count2[i], 0);
}
return result;
}
private:
vector<int> counter(const string& s) const {
vector<int> count(26);
for (const auto& c : s) {
++count[c - 'a'];
}
return count;
}
};
| 21.68 | 52 | 0.47417 | [
"vector"
] |
9f36366efce0bc76c02536d978c0d7efefda3f36 | 4,470 | cpp | C++ | src/multithread-win.cpp | omega-graphics/common | 8e5202b2b0f93b5d40eb56a77e888181fb30e02d | [
"Apache-2.0"
] | null | null | null | src/multithread-win.cpp | omega-graphics/common | 8e5202b2b0f93b5d40eb56a77e888181fb30e02d | [
"Apache-2.0"
] | null | null | null | src/multithread-win.cpp | omega-graphics/common | 8e5202b2b0f93b5d40eb56a77e888181fb30e02d | [
"Apache-2.0"
] | null | null | null | #include "omega-common/multithread.h"
namespace OmegaCommon {
Semaphore::Semaphore(int initalValue){
sem = CreateSemaphoreA(NULL,initalValue,initalValue,NULL);
};
void Semaphore::get(){
BOOL block = TRUE;
while(block) {
DWORD signal = WaitForSingleObject(sem,0L);
switch (signal) {
case WAIT_OBJECT_0 : {
block = FALSE;
break;
}
}
}
};
void Semaphore::release(){
assert(!ReleaseSemaphore(sem,1,nullptr) && "Failed to Release Semaphore");
}
Semaphore::~Semaphore(){
CloseHandle(sem);
};
Pipe::Pipe(){
SECURITY_ATTRIBUTES securityAttributes;
securityAttributes.bInheritHandle = TRUE;
securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
securityAttributes.lpSecurityDescriptor = NULL;
CreatePipe(&file_a,&file_b,&securityAttributes,0);
SetHandleInformation(file_a,HANDLE_FLAG_INHERIT,0);
}
void Pipe::setCurrentProcessAsA() {
///
}
void Pipe::setCurrentProcessAsB() {
///
}
size_t Pipe::readA(char *buffer, size_t n_read) {
DWORD _n_read;
BOOL success = ReadFile(file_a,(LPVOID)buffer,DWORD(n_read),&_n_read,NULL);
if(!success){
return 0;
}
return (size_t)_n_read;
}
size_t Pipe::readB(char *buffer, size_t n_read) {
DWORD _n_read;
BOOL success = ReadFile(file_b,(LPVOID)buffer,DWORD(n_read),&_n_read,NULL);
if(!success){
return 0;
}
return (size_t)_n_read;
}
void Pipe::writeA(char *buffer, size_t n_write) {
WriteFile(file_a,(LPCVOID)buffer,DWORD(n_write),NULL,NULL);
}
void Pipe::writeB(char *buffer, size_t n_write) {
WriteFile(file_b,(LPCVOID)buffer,DWORD(n_write),NULL,NULL);
}
Pipe::~Pipe(){
CloseHandle(file_a);
CloseHandle(file_b);
CloseHandle(h);
}
ChildProcess ChildProcess::Open(const OmegaCommon::String &cmd, const OmegaCommon::Vector<const char *> &args) {
STARTUPINFO startupinfo;
ZeroMemory(&startupinfo,sizeof(STARTUPINFO));
startupinfo.cb = sizeof(STARTUPINFO);
ChildProcess process{};
process.use_pipe = false;
ZeroMemory(&process.processInformation,sizeof(process.processInformation));
CreateProcessA(NULL,(LPSTR)cmd.data(),NULL,NULL,FALSE,0,NULL,NULL,&startupinfo,&process.processInformation);
return process;
}
ChildProcess ChildProcess::OpenWithStdoutPipe(const OmegaCommon::String &cmd, const char *args) {
STARTUPINFO startupinfo;
ZeroMemory(&startupinfo,sizeof(STARTUPINFO));
startupinfo.cb = sizeof(STARTUPINFO);
SECURITY_ATTRIBUTES securityAttributes;
ZeroMemory(&securityAttributes,sizeof(SECURITY_ATTRIBUTES));
securityAttributes.lpSecurityDescriptor = NULL;
securityAttributes.bInheritHandle = TRUE;
securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
ChildProcess process{};
process.use_pipe = true;
ZeroMemory(&process.processInformation,sizeof(process.processInformation));
startupinfo.hStdOutput = process.pipe.file_b;
startupinfo.hStdError = process.pipe.file_b;
// file_b startupinfo.dwFlags |= STARTF_USESTDHANDLES;
BOOL f = CreateProcessA(NULL,(LPSTR)(OmegaCommon::String(cmd) + args).c_str(),&securityAttributes,NULL,FALSE,0,NULL,NULL,&startupinfo,&process.processInformation);
if(f == FALSE){
std::cerr << "ERROR:" << cmd << " is not a valid command!" << std::endl;
exit(1);
}
return process;
}
int ChildProcess::wait() {
// std::cout << "Waiting" << std::endl;
WaitForSingleObject(processInformation.hProcess,INFINITE);
std::cout << "Process has terminated" << std::endl;
DWORD exit_code;
GetExitCodeProcess(processInformation.hProcess,&exit_code);
// std::cout << "Exit Code:" << exit_code << std::endl;
CloseHandle(processInformation.hThread);
CloseHandle(processInformation.hProcess);
// std::cout << "Close Process" << exit_code << std::endl;
off = true;
return int(exit_code);
}
ChildProcess::~ChildProcess() {
if(!off){
auto rc = wait();
}
}
} | 30.202703 | 171 | 0.619911 | [
"vector"
] |
9f3f7f4443d77c47bf9957f8bca5070c4659d649 | 2,138 | cpp | C++ | codechef/acpc_replay/Gwalior2018/TALETRI.cpp | dhwanisanmukhani/competitive-coding | 5392dea65b6ac370ac641c993120d7f252f5b1ac | [
"MIT"
] | null | null | null | codechef/acpc_replay/Gwalior2018/TALETRI.cpp | dhwanisanmukhani/competitive-coding | 5392dea65b6ac370ac641c993120d7f252f5b1ac | [
"MIT"
] | null | null | null | codechef/acpc_replay/Gwalior2018/TALETRI.cpp | dhwanisanmukhani/competitive-coding | 5392dea65b6ac370ac641c993120d7f252f5b1ac | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
#define icin(x) scanf("%d", &x)
#define lcin(x) scanf("%lld", &x)
typedef long long ll;
int main(){
int t;
icin(t);
while(t--){
int a, b, c, d, e, f, l, r;
icin(a), icin(b), icin(c), icin(d), icin(e), icin(f), icin(l), icin(r);
int x, y, mx, my, nx, ny;
y = min(l, r);
x = max(l, r);
mx = max(a, b);
my = min(a, b);
nx = max(d, e);
ny = min(d, e);
if(mx > x || my > y){
printf("-1\n");
continue;
}
if(nx > x || ny > y){
printf("-1\n");
continue;
}
pair<int, int> c1 = make_pair(0, 0);
pair<int, int> a1 = make_pair(0, my);
pair<int, int> b1 = make_pair(mx, 0);
pair<int, int> f2 = make_pair(x, y);
pair<int, int> e2 = make_pair(x, y-ny);
pair<int, int> d2 = make_pair(x-nx, y);
if(a1 == d2 && b1 == e2){
printf("-1\n");
continue;
}
else if(a1 == d2){
if(e2.second > 0){
f2.second--;
e2.second--;
d2.second--;
if(e2 == b1){
f2 = make_pair(x, 1);
e2 = make_pair(x, y);
d2 = make_pair(0, 1);
}
}
else{
a1.first++;
b1.first++;
c1.first++;
if(e2 == b1){
b1 = make_pair(0, 0);
a1 = make_pair(x-1, my);
c1 = make_pair(x-1, 0);
}
}
}
else if(e2 == b1){
if(d2.first > 0){
f2.first--;
e2.first--;
d2.first--;
if(d2 == a1){
e2 = make_pair(1, 0);
f2 = make_pair(1, y);
d2 = make_pair(x, y);
}
}
else{
a1.second++;
b1.second++;
c1.second++;
if(d2 == a1){
c1 = make_pair(0, y-1);
a1 = make_pair(0, 0);
b1 = make_pair(x, y-1);
}
}
}
if(a>b){
printf("%d %d\n", a1.first, a1.second);
printf("%d %d\n", b1.first, b1.second);
}
else{
printf("%d %d\n", b1.first, b1.second);
printf("%d %d\n", a1.first, a1.second);
}
printf("%d %d\n", c1.first, c1.second);
if(e>f){
printf("%d %d\n", e2.first, e2.second);
printf("%d %d\n", d2.first, d2.second);
}
else{
printf("%d %d\n", d2.first, d2.second);
printf("%d %d\n", e2.first, e2.second);
}
printf("%d %d\n", f2.first, f2.second);
}
} | 20.557692 | 73 | 0.492516 | [
"vector"
] |
9f414f9c60ccb776fffb9bff3200387bdd08d002 | 2,563 | cpp | C++ | DirectX3D11/Objects/Model/Character.cpp | GyumLee/DirectX3D11 | 6158874aa12e790747e6fd8a53de608071c49574 | [
"Apache-2.0"
] | null | null | null | DirectX3D11/Objects/Model/Character.cpp | GyumLee/DirectX3D11 | 6158874aa12e790747e6fd8a53de608071c49574 | [
"Apache-2.0"
] | null | null | null | DirectX3D11/Objects/Model/Character.cpp | GyumLee/DirectX3D11 | 6158874aa12e790747e6fd8a53de608071c49574 | [
"Apache-2.0"
] | null | null | null | #include "Framework.h"
Character::Character()
: ModelAnimator("Character"), state(IDLE),
moveSpeed(10.0f), rotSpeed(5.0f), gravity(9.8f), jumpPower(0.0f)
{
ReadClip("idle", 1);
ReadClip("run", 1);
ReadClip("jump", 1);
Load();
}
Character::~Character()
{
}
void Character::Update()
{
Control();
Move();
Rotate();
Jump();
ModelAnimator::Update();
}
void Character::Render()
{
ModelAnimator::Render();
}
void Character::Control()
{
if (MOUSE_CLICK(0) && !ImGui::GetIO().WantCaptureMouse)
{
destPos = terrain->Picking();
Ray ray;
ray.position = position;
ray.direction = destPos - position;
float distance = ray.direction.Length();
if (aStar->CollisionObstacle(ray, distance))
{
SetPath();
}
else
{
path.clear();
path.push_back(destPos);
}
}
if (state != JUMP && KEY_DOWN(VK_SPACE))
{
SetClip(JUMP);
jumpPower = 10.0f;
}
}
void Character::Move()
{
if (path.empty())
{
if (state != JUMP)
SetClip(IDLE);
return;
}
if (state != JUMP)
SetClip(RUN);
Vector3 dest = path.back();
Vector3 direction = dest - position;
direction.y = 0.0f;
if (direction.Length() < 0.1f)
path.pop_back();
velocity = direction.Normalize();
position += velocity * moveSpeed * DELTA;
}
void Character::Rotate()
{
if (state == IDLE) return;
Vector3 cross = Vector3::Cross(Forward(), velocity);
if (cross.y < 0)
rotation.y += rotSpeed * DELTA;
else if (cross.y > 0)
rotation.y -= rotSpeed * DELTA;
}
void Character::Jump()
{
float height = terrain->GetHeight(position);
if (state != JUMP)
{
position.y = height;
return;
}
jumpPower -= gravity * DELTA;
position.y += jumpPower * DELTA;
if (position.y <= height)
{
position.y = height;
jumpPower = 0.0f;
SetClip(IDLE);
}
}
void Character::SetClip(AnimState state)
{
if (this->state != state)
{
this->state = state;
PlayClip(state);
}
}
void Character::SetPath()
{
int start = aStar->FindCloseNode(position);
int end = aStar->FindCloseNode(destPos);
aStar->GetPath(start, end, path);
aStar->MakeDirectPath(position, destPos, path);
path.insert(path.begin(), destPos);
UINT pathSize = path.size();
while (path.size() > 2)
{
vector<Vector3> tempPath = path;
tempPath.erase(tempPath.begin());
tempPath.pop_back();
Vector3 start = path.back();
Vector3 end = path.front();
aStar->MakeDirectPath(start, end, tempPath);
path.clear();
path = tempPath;
path.insert(path.begin(), end);
path.push_back(start);
if (pathSize == path.size())
break;
else
pathSize = path.size();
}
}
| 15.439759 | 65 | 0.638705 | [
"render",
"vector"
] |
9f5131565c7f9981ee63831c88d289bad2228a92 | 29,448 | cpp | C++ | src/contexts.cpp | b1f6c1c4/cfg-enum | 1a08071bde87f578ceaf834004c01b593db9bce8 | [
"BSD-3-Clause"
] | 4 | 2021-06-11T07:34:50.000Z | 2022-03-30T15:32:07.000Z | src/contexts.cpp | b1f6c1c4/cfg-enum | 1a08071bde87f578ceaf834004c01b593db9bce8 | [
"BSD-3-Clause"
] | null | null | null | src/contexts.cpp | b1f6c1c4/cfg-enum | 1a08071bde87f578ceaf834004c01b593db9bce8 | [
"BSD-3-Clause"
] | 2 | 2021-11-16T09:13:46.000Z | 2021-12-20T14:53:57.000Z | #include "contexts.h"
#include <cstdlib>
#include <iostream>
#include <cassert>
#include "model.h"
#include "wpr.h"
#include "solve.h"
using namespace std;
using smt::expr;
int name_counter = 1;
string name(iden basename) {
return "x" + to_string(rand()) + "_" +
iden_to_string(basename) + "__" + to_string(name_counter++);
}
string name(string const& basename) {
return "x" + to_string(rand()) + "_" +
basename + "__" + to_string(name_counter++);
}
/*
* BackgroundContext
*/
BackgroundContext::BackgroundContext(smt::context& ctx, std::shared_ptr<Module> module)
: ctx(ctx),
solver(ctx.make_solver())
{
for (string sort : module->sorts) {
this->sorts.insert(make_pair(sort, ctx.uninterpreted_sort(sort)));
}
}
smt::sort BackgroundContext::getUninterpretedSort(std::string name) {
auto iter = sorts.find(name);
if (iter == sorts.end()) {
printf("failed to find sort %s\n", name.c_str());
assert(false);
}
return iter->second;
}
smt::sort BackgroundContext::getSort(std::shared_ptr<Sort> sort) {
Sort* s = sort.get();
if (dynamic_cast<BooleanSort*>(s)) {
return ctx.bool_sort();
} else if (UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(s)) {
return getUninterpretedSort(usort->name);
} else if (dynamic_cast<FunctionSort*>(s)) {
assert(false && "getSort does not support FunctionSort");
} else {
assert(false && "getSort does not support unknown sort");
}
}
/*
* ModelEmbedding
*/
shared_ptr<ModelEmbedding> ModelEmbedding::makeEmbedding(
shared_ptr<BackgroundContext> ctx,
shared_ptr<Module> module)
{
unordered_map<iden, smt::func_decl> mapping;
for (VarDecl decl : module->functions) {
Sort* s = decl.sort.get();
if (FunctionSort* fsort = dynamic_cast<FunctionSort*>(s)) {
smt::sort_vector domain(ctx->ctx);
for (std::shared_ptr<Sort> domain_sort : fsort->domain) {
domain.push_back(ctx->getSort(domain_sort));
}
smt::sort range = ctx->getSort(fsort->range);
mapping.insert(make_pair(decl.name, ctx->ctx.function(
name(decl.name), domain, range)));
} else {
mapping.insert(make_pair(decl.name, ctx->ctx.function(
name(decl.name), ctx->getSort(decl.sort))));
}
}
return shared_ptr<ModelEmbedding>(new ModelEmbedding(ctx, mapping));
}
smt::func_decl ModelEmbedding::getFunc(iden name) const {
auto iter = mapping.find(name);
if (iter == mapping.end()) {
cout << "couldn't find function " << iden_to_string(name) << endl;
assert(false);
}
return iter->second;
}
smt::expr ModelEmbedding::value2expr(
shared_ptr<Value> value)
{
return value2expr(value, std::unordered_map<iden, smt::expr> {}, std::unordered_map<iden, smt::expr> {});
}
smt::expr ModelEmbedding::value2expr(
shared_ptr<Value> value,
std::unordered_map<iden, smt::expr> const& consts)
{
return value2expr(value, consts, std::unordered_map<iden, smt::expr> {});
}
smt::expr ModelEmbedding::value2expr_with_vars(
shared_ptr<Value> value,
std::unordered_map<iden, smt::expr> const& vars)
{
return value2expr(value, std::unordered_map<iden, smt::expr> {}, vars);
}
smt::expr ModelEmbedding::value2expr(
shared_ptr<Value> v,
std::unordered_map<iden, smt::expr> const& consts,
std::unordered_map<iden, smt::expr> const& vars)
{
assert(v.get() != NULL);
if (Forall* value = dynamic_cast<Forall*>(v.get())) {
if (value->decls.size() == 0) {
return value2expr(value->body, consts, vars);
}
smt::expr_vector vec_vars(ctx->ctx);
std::unordered_map<iden, smt::expr> new_vars = vars;
for (VarDecl decl : value->decls) {
expr var = ctx->ctx.bound_var(name(decl.name), ctx->getSort(decl.sort));
vec_vars.push_back(var);
new_vars.insert(make_pair(decl.name, var));
}
return smt::forall(vec_vars, value2expr(value->body, consts, new_vars));
}
else if (Exists* value = dynamic_cast<Exists*>(v.get())) {
if (value->decls.size() == 0) {
return value2expr(value->body, consts, vars);
}
smt::expr_vector vec_vars(ctx->ctx);
std::unordered_map<iden, smt::expr> new_vars = vars;
for (VarDecl decl : value->decls) {
expr var = ctx->ctx.bound_var(name(decl.name), ctx->getSort(decl.sort));
vec_vars.push_back(var);
new_vars.insert(make_pair(decl.name, var));
}
return smt::exists(vec_vars, value2expr(value->body, consts, new_vars));
}
else if (NearlyForall* value = dynamic_cast<NearlyForall*>(v.get())) {
smt::expr_vector vec_vars(ctx->ctx);
smt::expr_vector all_eq(ctx->ctx);
std::unordered_map<iden, smt::expr> new_vars1 = vars;
std::unordered_map<iden, smt::expr> new_vars2 = vars;
for (VarDecl decl : value->decls) {
expr var1 = ctx->ctx.bound_var(name(decl.name), ctx->getSort(decl.sort));
expr var2 = ctx->ctx.bound_var(name(decl.name), ctx->getSort(decl.sort));
vec_vars.push_back(var1);
vec_vars.push_back(var2);
new_vars1.insert(make_pair(decl.name, var1));
new_vars2.insert(make_pair(decl.name, var2));
all_eq.push_back(var1 == var2);
}
smt::expr_vector vec_or(ctx->ctx);
vec_or.push_back(value2expr(value->body, consts, new_vars1));
vec_or.push_back(value2expr(value->body, consts, new_vars2));
vec_or.push_back(smt::mk_and(all_eq));
return smt::forall(vec_vars, smt::mk_or(vec_or));
}
else if (Var* value = dynamic_cast<Var*>(v.get())) {
auto iter = vars.find(value->name);
if (iter == vars.end()) {
printf("couldn't find var: %s\n", iden_to_string(value->name).c_str());
assert(false);
}
return iter->second;
}
else if (Const* value = dynamic_cast<Const*>(v.get())) {
auto iter = consts.find(value->name);
if (iter == consts.end()) {
auto iter = mapping.find(value->name);
if (iter == mapping.end()) {
printf("could not find %s\n", iden_to_string(value->name).c_str());
assert(false);
}
smt::func_decl fd = iter->second;
return fd.call();
} else {
return iter->second;
}
}
else if (Eq* value = dynamic_cast<Eq*>(v.get())) {
return value2expr(value->left, consts, vars) == value2expr(value->right, consts, vars);
}
else if (Not* value = dynamic_cast<Not*>(v.get())) {
return !value2expr(value->val, consts, vars);
}
else if (Implies* value = dynamic_cast<Implies*>(v.get())) {
return !value2expr(value->left, consts, vars) || value2expr(value->right, consts, vars);
}
else if (Apply* value = dynamic_cast<Apply*>(v.get())) {
smt::expr_vector args(ctx->ctx);
for (shared_ptr<Value> arg : value->args) {
args.push_back(value2expr(arg, consts, vars));
}
Const* func_value = dynamic_cast<Const*>(value->func.get());
assert(func_value != NULL);
return getFunc(func_value->name).call(args);
}
else if (And* value = dynamic_cast<And*>(v.get())) {
if (value->args.size() == 0) {
return ctx->ctx.bool_val(true);
} else if (value->args.size() == 1) {
return value2expr(value->args[0], consts, vars);
} else {
smt::expr_vector args(ctx->ctx);
for (shared_ptr<Value> arg : value->args) {
args.push_back(value2expr(arg, consts, vars));
}
return mk_and(args);
}
}
else if (Or* value = dynamic_cast<Or*>(v.get())) {
if (value->args.size() == 0) {
return ctx->ctx.bool_val(false);
} else if (value->args.size() == 1) {
return value2expr(value->args[0], consts, vars);
} else {
smt::expr_vector args(ctx->ctx);
for (shared_ptr<Value> arg : value->args) {
args.push_back(value2expr(arg, consts, vars));
}
return mk_or(args);
}
}
else if (IfThenElse* value = dynamic_cast<IfThenElse*>(v.get())) {
return smt::ite(
value2expr(value->cond, consts, vars),
value2expr(value->then_value, consts, vars),
value2expr(value->else_value, consts, vars)
);
}
else {
//printf("value2expr got: %s\n", v->to_string().c_str());
assert(false && "value2expr does not support this case");
}
}
/*
* InductionContext
*/
InductionContext::InductionContext(
smt::context& z3ctx,
std::shared_ptr<Module> module,
int action_idx)
: ctx(new BackgroundContext(z3ctx, module)), action_idx(action_idx)
{
init(module);
}
InductionContext::InductionContext(
shared_ptr<BackgroundContext> bgctx,
std::shared_ptr<Module> module,
int action_idx)
: ctx(bgctx), action_idx(action_idx)
{
init(module);
}
void InductionContext::init(std::shared_ptr<Module> module)
{
assert(-1 <= action_idx && action_idx < (int)module->actions.size());
this->e1 = ModelEmbedding::makeEmbedding(ctx, module);
shared_ptr<Action> action = action_idx == -1
? shared_ptr<Action>(new ChoiceAction(module->actions))
: module->actions[action_idx];
ActionResult res = applyAction(this->e1, action, std::unordered_map<iden, smt::expr> {});
this->e2 = res.e;
// Add the relation between the two states
ctx->solver.add(res.constraint);
// Add the axioms
for (shared_ptr<Value> axiom : module->axioms) {
ctx->solver.add(this->e1->value2expr(axiom, std::unordered_map<iden, smt::expr> {}));
}
}
/*
* ChainContext
*/
ChainContext::ChainContext(
smt::context& z3ctx,
std::shared_ptr<Module> module,
int numTransitions)
: ctx(new BackgroundContext(z3ctx, module))
{
this->es.resize(numTransitions + 1);
this->es[0] = ModelEmbedding::makeEmbedding(ctx, module);
shared_ptr<Action> action = shared_ptr<Action>(new ChoiceAction(module->actions));
for (int i = 0; i < numTransitions; i++) {
ActionResult res = applyAction(this->es[i], action, std::unordered_map<iden, smt::expr> {});
this->es[i+1] = res.e;
// Add the relation between the two states
ctx->solver.add(res.constraint);
}
// Add the axioms
for (shared_ptr<Value> axiom : module->axioms) {
ctx->solver.add(this->es[0]->value2expr(axiom, std::unordered_map<iden, smt::expr> {}));
}
}
ActionResult do_if_else(
shared_ptr<ModelEmbedding> e,
shared_ptr<Value> condition,
shared_ptr<Action> then_body,
shared_ptr<Action> else_body,
unordered_map<iden, smt::expr> const& consts)
{
vector<shared_ptr<Action>> seq1;
seq1.push_back(shared_ptr<Action>(new Assume(condition)));
seq1.push_back(then_body);
vector<shared_ptr<Action>> seq2;
seq2.push_back(shared_ptr<Action>(new Assume(shared_ptr<Value>(new Not(condition)))));
if (else_body.get() != nullptr) {
seq2.push_back(else_body);
}
vector<shared_ptr<Action>> choices = {
shared_ptr<Action>(new SequenceAction(seq1)),
shared_ptr<Action>(new SequenceAction(seq2))
};
return applyAction(e, shared_ptr<Action>(new ChoiceAction(choices)), consts);
}
expr funcs_equal(smt::context& ctx, smt::func_decl a, smt::func_decl b) {
smt::expr_vector args(ctx);
for (int i = 0; i < (int)a.arity(); i++) {
smt::sort arg_sort = a.domain(i);
args.push_back(ctx.bound_var(name("arg"), arg_sort));
}
if (args.size() == 0) {
return a.call(args) == b.call(args);
} else {
return smt::forall(args, a.call(args) == b.call(args));
}
}
ActionResult applyAction(
shared_ptr<ModelEmbedding> e,
shared_ptr<Action> a,
unordered_map<iden, expr> const& consts)
{
shared_ptr<BackgroundContext> ctx = e->ctx;
if (LocalAction* action = dynamic_cast<LocalAction*>(a.get())) {
unordered_map<iden, expr> new_consts(consts);
for (VarDecl decl : action->args) {
smt::func_decl d = ctx->ctx.function(name(decl.name), ctx->getSort(decl.sort));
expr ex = d.call();
new_consts.insert(make_pair(decl.name, ex));
}
return applyAction(e, action->body, new_consts);
}
else if (RelationAction* action = dynamic_cast<RelationAction*>(a.get())) {
unordered_map<iden, smt::func_decl> new_mapping = e->mapping;
unordered_map<iden, smt::func_decl> twostate_mapping = e->mapping;
for (string mod : action->mods) {
iden mod_iden = string_to_iden(mod);
smt::func_decl orig_func = e->getFunc(mod_iden);
smt::sort_vector domain(ctx->ctx);
for (int i = 0; i < (int)orig_func.arity(); i++) {
domain.push_back(orig_func.domain(i));
}
string new_name = name(mod);
smt::func_decl new_func = ctx->ctx.function(new_name,
domain, orig_func.range());
new_mapping.erase(mod_iden);
new_mapping.insert(make_pair(mod_iden, new_func));
twostate_mapping.insert(make_pair(string_to_iden(mod+"'"), new_func));
}
ModelEmbedding* twostate_e = new ModelEmbedding(ctx, twostate_mapping);
smt::expr ex = twostate_e->value2expr(action->rel, consts);
ModelEmbedding* new_e = new ModelEmbedding(ctx, new_mapping);
return ActionResult(shared_ptr<ModelEmbedding>(new_e), ex);
}
else if (SequenceAction* action = dynamic_cast<SequenceAction*>(a.get())) {
smt::expr_vector parts(ctx->ctx);
for (shared_ptr<Action> sub_action : action->actions) {
ActionResult res = applyAction(e, sub_action, consts);
e = res.e;
parts.push_back(res.constraint);
}
expr ex = smt::mk_and(parts);
return ActionResult(e, smt::mk_and(parts));
}
else if (Assume* action = dynamic_cast<Assume*>(a.get())) {
return ActionResult(e, e->value2expr(action->body, consts));
}
else if (If* action = dynamic_cast<If*>(a.get())) {
return do_if_else(e, action->condition, action->then_body, nullptr, consts);
}
else if (IfElse* action = dynamic_cast<IfElse*>(a.get())) {
return do_if_else(e, action->condition, action->then_body, action->else_body, consts);
}
else if (ChoiceAction* action = dynamic_cast<ChoiceAction*>(a.get())) {
int len = action->actions.size();
vector<shared_ptr<ModelEmbedding>> es;
vector<smt::expr> constraints;
for (int i = 0; i < len; i++) {
ActionResult res = applyAction(e, action->actions[i], consts);
es.push_back(res.e);
constraints.push_back(res.constraint);
}
unordered_map<iden, smt::func_decl> mapping;
for (auto p : e->mapping) {
iden func_name = p.first;
bool is_ident = true;
smt::func_decl new_func_decl = e->getFunc(func_name);
for (int i = 0; i < len; i++) {
if (!func_decl_eq(es[i]->getFunc(func_name), e->getFunc(func_name))) {
is_ident = false;
new_func_decl = es[i]->mapping.find(func_name)->second;
break;
}
}
mapping.insert(make_pair(func_name, new_func_decl));
if (!is_ident) {
for (int i = 0; i < len; i++) {
if (!func_decl_eq(es[i]->getFunc(func_name), new_func_decl)) {
constraints[i] =
funcs_equal(ctx->ctx, es[i]->getFunc(func_name), new_func_decl) &&
constraints[i];
}
}
}
}
smt::expr_vector constraints_vec(ctx->ctx);
for (int i = 0; i < len; i++) {
constraints_vec.push_back(constraints[i]);
}
return ActionResult(
shared_ptr<ModelEmbedding>(new ModelEmbedding(e->ctx, mapping)),
smt::mk_or(constraints_vec)
);
}
else if (Assign* action = dynamic_cast<Assign*>(a.get())) {
Value* left = action->left.get();
Apply* apply = dynamic_cast<Apply*>(left);
//assert(apply != NULL);
Const* func_const = dynamic_cast<Const*>(apply != NULL ? apply->func.get() : left);
assert(func_const != NULL);
smt::func_decl orig_func = e->getFunc(func_const->name);
smt::sort_vector domain(ctx->ctx);
for (int i = 0; i < (int)orig_func.arity(); i++) {
domain.push_back(orig_func.domain(i));
}
string new_name = name(func_const->name);
smt::func_decl new_func = ctx->ctx.function(new_name,
domain, orig_func.range());
smt::expr_vector qvars(ctx->ctx);
smt::expr_vector all_eq_parts(ctx->ctx);
unordered_map<iden, smt::expr> vars;
for (int i = 0; i < (int)orig_func.arity(); i++) {
assert(apply != NULL);
shared_ptr<Value> arg = apply->args[i];
if (Var* arg_var = dynamic_cast<Var*>(arg.get())) {
expr qvar = ctx->ctx.bound_var(name(arg_var->name), ctx->getSort(arg_var->sort));
qvars.push_back(qvar);
vars.insert(make_pair(arg_var->name, qvar));
} else {
expr qvar = ctx->ctx.bound_var(name("arg"), domain[i]);
qvars.push_back(qvar);
all_eq_parts.push_back(qvar == e->value2expr(arg, consts));
}
}
unordered_map<iden, smt::func_decl> new_mapping = e->mapping;
new_mapping.erase(func_const->name);
new_mapping.insert(make_pair(func_const->name, new_func));
ModelEmbedding* new_e = new ModelEmbedding(ctx, new_mapping);
smt::expr inner = new_func.call(qvars) == smt::ite(
smt::mk_and(all_eq_parts),
e->value2expr(action->right, consts, vars),
orig_func.call(qvars));
smt::expr outer = qvars.size() == 0 ? inner : smt::forall(qvars, inner);
ActionResult ar(shared_ptr<ModelEmbedding>(new_e), outer);
return ar;
}
else if (Havoc* action = dynamic_cast<Havoc*>(a.get())) {
Value* left = action->left.get();
Apply* apply = dynamic_cast<Apply*>(left);
//assert(apply != NULL);
Const* func_const = dynamic_cast<Const*>(apply != NULL ? apply->func.get() : left);
assert(func_const != NULL);
smt::func_decl orig_func = e->getFunc(func_const->name);
smt::sort_vector domain(ctx->ctx);
for (int i = 0; i < (int)orig_func.arity(); i++) {
domain.push_back(orig_func.domain(i));
}
string new_name = name(func_const->name);
smt::func_decl new_func = ctx->ctx.function(new_name,
domain, orig_func.range());
smt::expr_vector qvars(ctx->ctx);
smt::expr_vector all_eq_parts(ctx->ctx);
unordered_map<iden, smt::expr> vars;
for (int i = 0; i < (int)orig_func.arity(); i++) {
assert(apply != NULL);
shared_ptr<Value> arg = apply->args[i];
if (Var* arg_var = dynamic_cast<Var*>(arg.get())) {
expr qvar = ctx->ctx.bound_var(name(arg_var->name), ctx->getSort(arg_var->sort));
qvars.push_back(qvar);
vars.insert(make_pair(arg_var->name, qvar));
} else {
expr qvar = ctx->ctx.bound_var(name("arg"), domain[i]);
qvars.push_back(qvar);
all_eq_parts.push_back(qvar == e->value2expr(arg, consts));
}
}
unordered_map<iden, smt::func_decl> new_mapping = e->mapping;
new_mapping.erase(func_const->name);
new_mapping.insert(make_pair(func_const->name, new_func));
ModelEmbedding* new_e = new ModelEmbedding(ctx, new_mapping);
smt::expr inner = smt::implies(
!smt::mk_and(all_eq_parts),
new_func.call(qvars) == orig_func.call(qvars));
smt::expr outer = qvars.size() == 0 ? inner : smt::forall(qvars, inner);
ActionResult ar(shared_ptr<ModelEmbedding>(new_e), outer);
return ar;
}
else {
assert(false && "applyAction does not implement this unknown case");
}
}
void ModelEmbedding::dump() {
for (auto p : mapping) {
printf("%s -> %s\n", iden_to_string(p.first).c_str(), p.second.get_name().c_str());
}
}
/*
* BasicContext
*/
BasicContext::BasicContext(
smt::context& z3ctx,
std::shared_ptr<Module> module)
: ctx(new BackgroundContext(z3ctx, module))
{
this->e = ModelEmbedding::makeEmbedding(ctx, module);
// Add the axioms
for (shared_ptr<Value> axiom : module->axioms) {
ctx->solver.add(this->e->value2expr(axiom));
}
}
BasicContext::BasicContext(
std::shared_ptr<BackgroundContext> bgctx,
std::shared_ptr<Module> module)
: ctx(bgctx)
{
this->e = ModelEmbedding::makeEmbedding(ctx, module);
// Add the axioms
for (shared_ptr<Value> axiom : module->axioms) {
ctx->solver.add(this->e->value2expr(axiom));
}
}
/*
* InitContext
*/
InitContext::InitContext(
smt::context& z3ctx,
std::shared_ptr<Module> module)
: ctx(new BackgroundContext(z3ctx, module))
{
init(module);
}
InitContext::InitContext(
shared_ptr<BackgroundContext> bgctx,
std::shared_ptr<Module> module)
: ctx(bgctx)
{
init(module);
}
void InitContext::init(std::shared_ptr<Module> module)
{
this->e = ModelEmbedding::makeEmbedding(ctx, module);
// Add the axioms
for (shared_ptr<Value> axiom : module->axioms) {
ctx->solver.add(this->e->value2expr(axiom));
}
// Add the inits
for (shared_ptr<Value> init : module->inits) {
ctx->solver.add(this->e->value2expr(init));
}
}
/*
* ConjectureContext
*/
ConjectureContext::ConjectureContext(
smt::context& z3ctx,
std::shared_ptr<Module> module)
: ctx(new BackgroundContext(z3ctx, module))
{
this->e = ModelEmbedding::makeEmbedding(ctx, module);
// Add the axioms
for (shared_ptr<Value> axiom : module->axioms) {
ctx->solver.add(this->e->value2expr(axiom));
}
// Add the conjectures
shared_ptr<Value> all_conjectures = shared_ptr<Value>(new And(module->conjectures));
shared_ptr<Value> not_conjectures = shared_ptr<Value>(new Not(all_conjectures));
ctx->solver.add(this->e->value2expr(not_conjectures));
}
/*
* InvariantsContext
*/
InvariantsContext::InvariantsContext(
smt::context& z3ctx,
std::shared_ptr<Module> module)
: ctx(new BackgroundContext(z3ctx, module))
{
this->e = ModelEmbedding::makeEmbedding(ctx, module);
// Add the axioms
for (shared_ptr<Value> axiom : module->axioms) {
ctx->solver.add(this->e->value2expr(axiom));
}
}
bool is_satisfiable(shared_ptr<Module> module, value candidate)
{
smt::context ctx(smt::Backend::z3);
BasicContext basicctx(ctx, module);
smt::solver& solver = basicctx.ctx->solver;
solver.add(basicctx.e->value2expr(candidate));
return solver.check_sat();
}
bool is_satisfiable_tryhard(shared_ptr<Module> module, value candidate)
{
ContextSolverResult res = context_solve(
"is_satisfiable",
module,
ModelType::Any,
Strictness::TryHard,
nullptr,
[module, candidate](shared_ptr<BackgroundContext> bgctx)
{
BasicContext basicctx(bgctx, module);
smt::solver& solver = basicctx.ctx->solver;
solver.add(basicctx.e->value2expr(candidate));
return vector<shared_ptr<ModelEmbedding>>{};
});
return res.res != smt::SolverResult::Unsat;
}
bool is_complete_invariant(shared_ptr<Module> module, value candidate) {
smt::context ctx(smt::Backend::z3);
{
InitContext initctx(ctx, module);
smt::solver& init_solver = initctx.ctx->solver;
init_solver.add(initctx.e->value2expr(v_not(candidate)));
init_solver.set_log_info("is_complete_invariant-init");
if (init_solver.check_sat()) {
return false;
}
}
{
ConjectureContext conjctx(ctx, module);
smt::solver& conj_solver = conjctx.ctx->solver;
conj_solver.add(conjctx.e->value2expr(candidate));
conj_solver.set_log_info("is_complete_invariant-conj");
if (conj_solver.check_sat()) {
return false;
}
}
{
InductionContext indctx(ctx, module);
smt::solver& solver = indctx.ctx->solver;
solver.add(indctx.e1->value2expr(candidate));
solver.add(indctx.e2->value2expr(v_not(candidate)));
solver.set_log_info("is_complete_invariant-ind");
if (solver.check_sat()) {
return false;
}
}
return true;
}
bool is_itself_invariant(shared_ptr<Module> module, value candidate) {
smt::context ctx(smt::Backend::z3);
{
InitContext initctx(ctx, module);
smt::solver& init_solver = initctx.ctx->solver;
init_solver.set_log_info("is_itself_invariant-init");
init_solver.add(initctx.e->value2expr(v_not(candidate)));
if (init_solver.check_sat()) {
return false;
}
}
{
InductionContext indctx(ctx, module);
smt::solver& solver = indctx.ctx->solver;
solver.set_log_info("is_itself_invariant-ind");
solver.add(indctx.e1->value2expr(candidate));
solver.add(indctx.e2->value2expr(v_not(candidate)));
if (solver.check_sat()) {
return false;
}
}
return true;
}
bool is_invariant_with_conjectures(std::shared_ptr<Module> module, value v) {
return is_itself_invariant(module, v_and({v, v_and(module->conjectures)}));
}
bool is_invariant_with_conjectures(std::shared_ptr<Module> module, vector<value> v) {
for (value c : module->conjectures) {
v.push_back(c);
}
return is_itself_invariant(module, v);
}
bool is_itself_invariant(shared_ptr<Module> module, vector<value> candidates) {
//printf("is_itself_invariant\n");
smt::context ctx(smt::Backend::z3);
value full = v_and(candidates);
for (value candidate : candidates) {
//printf("%s\n", candidate->to_string().c_str());
{
InitContext initctx(ctx, module);
smt::solver& init_solver = initctx.ctx->solver;
init_solver.add(initctx.e->value2expr(v_not(candidate)));
init_solver.set_log_info("is_itself_invariant-init");
//printf("checking init condition...\n");
if (init_solver.check_sat()) {
//cout << "failed init with candidate " << candidate->to_string() << endl;
return false;
}
}
for (int i = 0; i < (int)module->actions.size(); i++) {
InductionContext indctx(ctx, module, i);
smt::solver& solver = indctx.ctx->solver;
solver.set_log_info("is_itself_invariant-ind");
solver.add(indctx.e1->value2expr(full));
solver.add(indctx.e2->value2expr(v_not(candidate)));
//printf("checking invariant condition...\n");
if (solver.check_sat()) {
//cout << "failed with action " << module->action_names[i] << endl;
//cout << "failed with candidate " << candidate->to_string() << endl;
/*shared_ptr<Model> m1 = Model::extract_model_from_z3(
indctx.ctx->ctx, solver, module, *indctx.e1);
shared_ptr<Model> m2 = Model::extract_model_from_z3(
indctx.ctx->ctx, solver, module, *indctx.e2);
m1->dump();
m2->dump();*/
/*auto m = Model::extract_minimal_models_from_z3(
indctx.ctx->ctx,
solver, module, {indctx.e1, indctx.e2}, nullptr);
m[0]->dump();
m[1]->dump();*/
//cout << "hey " << m[0]->eval_predicate(candidates[2]) << endl;*/
return false;
}
}
}
return true;
}
bool is_wpr_itself_inductive(shared_ptr<Module> module, value candidate, int wprIter) {
smt::context ctx(smt::Backend::z3);
shared_ptr<Action> action = shared_ptr<Action>(new ChoiceAction(module->actions));
value wpr_candidate = candidate;
for (int j = 0; j < wprIter; j++) {
wpr_candidate = wpr(wpr_candidate, action)->simplify();
}
for (int i = 1; i <= wprIter + 1; i++) {
cout << "is_wpr_itself_inductive: " << i << endl;
ChainContext chainctx(ctx, module, i);
smt::solver& solver = chainctx.ctx->solver;
solver.add(chainctx.es[0]->value2expr(wpr_candidate));
solver.add(chainctx.es[i]->value2expr(v_not(candidate)));
if (solver.check_sat()) {
return false;
}
}
return true;
}
smt::SolverResult is_invariant_wrt(shared_ptr<Module> module, value invariant_so_far, vector<value> const& candidates, Strictness strictness) {
for (value candidate : candidates) {
ContextSolverResult res = context_solve(
"is_invariant_wrt init",
module,
ModelType::Any,
strictness,
nullptr,
[module, candidate](shared_ptr<BackgroundContext> bgctx)
{
InitContext initctx(bgctx, module);
smt::solver& init_solver = initctx.ctx->solver;
init_solver.add(initctx.e->value2expr(v_not(candidate)));
return vector<shared_ptr<ModelEmbedding>>{};
});
if (res.res != smt::SolverResult::Unsat) {
return res.res;
}
}
for (value candidate : candidates) {
for (int i = 0; i < (int)module->actions.size(); i++) {
ContextSolverResult res = context_solve(
"is_invariant_wrt inductiveness",
module,
ModelType::Any,
strictness,
nullptr,
[&candidate, candidates, module, i, invariant_so_far](shared_ptr<BackgroundContext> bgctx)
{
InductionContext indctx(bgctx, module, i);
smt::solver& solver = indctx.ctx->solver;
solver.set_log_info("is_invariant_wrt inductiveness");
solver.add(indctx.e1->value2expr(invariant_so_far));
solver.add(indctx.e1->value2expr(v_and(candidates)));
solver.add(indctx.e2->value2expr(v_not(candidate)));
return vector<shared_ptr<ModelEmbedding>>{};
});
if (res.res != smt::SolverResult::Unsat) {
return res.res;
}
}
}
return smt::SolverResult::Unsat;
}
bool is_invariant_wrt(shared_ptr<Module> module, value invariant_so_far, vector<value> const& candidates) {
return is_invariant_wrt(module, invariant_so_far, candidates, Strictness::Strict) == smt::SolverResult::Unsat;
}
bool is_invariant_wrt(shared_ptr<Module> module, value invariant_so_far, value candidate) {
return is_invariant_wrt(module, invariant_so_far, vector<value>{candidate});
}
bool is_invariant_wrt_tryhard(shared_ptr<Module> module, value invariant_so_far, vector<value> const& candidates) {
return is_invariant_wrt(module, invariant_so_far, candidates, Strictness::TryHard) == smt::SolverResult::Unsat;
}
bool is_invariant_wrt_tryhard(shared_ptr<Module> module, value invariant_so_far, value candidate) {
return is_invariant_wrt_tryhard(module, invariant_so_far, vector<value>{candidate});
}
| 31.76699 | 143 | 0.652031 | [
"vector",
"model"
] |
9f56e93b92823ed0b529bd7967347fa330254e36 | 22,238 | cpp | C++ | src/currency_core/gpu_miner.cpp | Virie/Virie | fc5ad5816678b06b88d08a6842e43d4205915b39 | [
"MIT"
] | 1 | 2021-03-07T13:26:43.000Z | 2021-03-07T13:26:43.000Z | src/currency_core/gpu_miner.cpp | Virie/Virie | fc5ad5816678b06b88d08a6842e43d4205915b39 | [
"MIT"
] | null | null | null | src/currency_core/gpu_miner.cpp | Virie/Virie | fc5ad5816678b06b88d08a6842e43d4205915b39 | [
"MIT"
] | null | null | null | // Copyright (c) 2014-2020 The Virie Project
// Copyright (c) 2012-2013 The Cryptonote developers
// Copyright (c) 2012-2013 The Boolberry developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifdef USE_OPENCL
#include <sstream>
#include <numeric>
#include <boost/utility/value_init.hpp>
#include <boost/interprocess/detail/atomic.hpp>
#include <boost/limits.hpp>
#include <boost/foreach.hpp>
#include "misc_language.h"
#include "include_base_utils.h"
#include "currency_format_utils.h"
#include "file_io_utils.h"
#include "common/command_line.h"
#include "string_coding.h"
#include "version.h"
#include "storages/portable_storage_template_helper.h"
#include "ethereum/libethash-cl/ethash_cl_miner.h"
#include "common/deps_version.h"
using namespace epee;
#include "gpu_miner.h"
namespace currency
{
namespace
{
static const bool set_ver = deps_version::add_lib_versions(gpu_miner::get_versions());
}
template <class t_cb_found, class t_cb_searched>
struct abstract_search_hook : public ethash_cl_miner::search_hook
{
t_cb_found m_cb_found;
t_cb_searched m_cb_searched;
abstract_search_hook(t_cb_found cb_found, t_cb_searched cb_searched) :m_cb_found(cb_found), m_cb_searched(cb_searched)
{}
//---------------- ethash_cl_miner::search_hook ----------------
virtual bool found(uint64_t const* nonces, uint32_t count)
{
return m_cb_found(nonces, count);
}
virtual bool searched(uint64_t start_nonce, uint32_t count)
{
return m_cb_searched(start_nonce, count);
}
};
template <class t_cb_found, class t_cb_searched>
std::shared_ptr<ethash_cl_miner::search_hook>
get_lambda_hooker(t_cb_found cb_found, t_cb_searched cb_searched)
{
return std::shared_ptr<ethash_cl_miner::search_hook>(new abstract_search_hook<t_cb_found, t_cb_searched>(cb_found, cb_searched));
}
namespace
{
const command_line::arg_descriptor<std::string> arg_extra_messages = { "extra-messages-file", "Specify file for extra messages to include into coinbase transactions", "", command_line::flag_t::not_use_default };
const command_line::arg_descriptor<std::string> arg_start_mining = { "start-mining", "Specify wallet address to mining for", "", command_line::flag_t::not_use_default };
const command_line::arg_descriptor<bool> arg_gpu_list_platforms = { "gpu-list-platforms", "GPU mining: list OpenCL platforms", false, command_line::flag_t::not_use_default };
const command_line::arg_descriptor<bool> arg_gpu_list_devices = { "gpu-list-devices", "GPU mining: list OpenCL devices for each platform", false, command_line::flag_t::not_use_default };
const command_line::arg_descriptor<uint32_t> arg_gpu_platform_id = { "gpu-platform-id", "GPU mining: select OpenCL platform id", 0, command_line::flag_t::not_use_default };
const command_line::arg_descriptor<uint32_t> arg_gpu_device_id = { "gpu-device-id", "GPU mining: select OpenCL device id", 0, command_line::flag_t::not_use_default };
const command_line::arg_descriptor<uint32_t> arg_gpu_local_work = { "gpu-local-work-size", "GPU mining: specify local work size ", 64 };
const command_line::arg_descriptor<uint32_t> arg_gpu_global_work = { "gpu-global-work-size", "GPU mining: specify global work size", 1048576 * 2 };
const command_line::arg_descriptor<std::string> arg_gpu_benchmark = { "gpu-benchmark", "GPU mining: perform a bechmark instead of actual mining using specified difficulty (or current BC diff if 0)", "", command_line::flag_t::not_use_default };
// const command_line::arg_descriptor<uint32_t> arg_mining_threads = { "mining-threads", "Specify mining threads count", 0, command_line::flag_t::not_use_default };
}
gpu_miner::gpu_miner(i_miner_handler* phandler) :m_stop(1),
m_template(boost::value_initialized<block>()),
m_template_no(0),
m_diffic(0),
m_height(0),
m_thread_index(0),
m_threads_total(1),
m_pausers_count(0),
m_phandler(phandler),
m_config(AUTO_VAL_INIT(m_config)),
m_current_hash_rate(0),
m_last_hr_merge_time(0),
m_hashes(0),
m_do_print_hashrate(false),
m_do_mining(false),
m_benchmark_mode(false),
m_global_work_size(0),
m_local_work_size(0),
m_ms_per_batch(ethash_cl_miner::c_defaultMSPerBatch),
m_opencl_platform(0),
m_opencl_device(0),
m_cl_allow_cpu(false),
m_extra_gpu_memory(350000000)
{
}
//-----------------------------------------------------------------------------------------------------
gpu_miner::~gpu_miner()
{
stop();
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::set_block_template(const block& bl, const wide_difficulty_type& di, uint64_t height)
{
CRITICAL_REGION_LOCAL(m_template_lock);
m_template = bl;
m_diffic = di;
m_height = height;
++m_template_no;
return true;
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::on_block_chain_update()
{
if (!is_mining())
return true;
//here miner threads may work few rounds without
return request_block_template();
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::request_block_template()
{
block bl = AUTO_VAL_INIT(bl);
wide_difficulty_type di = AUTO_VAL_INIT(di);
uint64_t height = AUTO_VAL_INIT(height);
currency::blobdata extra_nonce = PROJECT_VERSION_LONG "|ethash-solo-gpu-miner";
if (m_extra_messages.size() && m_config.current_extra_message_index < m_extra_messages.size())
{
extra_nonce = m_extra_messages[m_config.current_extra_message_index];
}
if (!m_phandler->get_block_template(bl, m_mine_address, m_mine_address, di, height, extra_nonce))
{
LOG_ERROR("Failed to get_block_template()");
return false;
}
set_block_template(bl, di, height);
return true;
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::on_idle()
{
m_update_block_template_interval.do_call([&](){
if (is_mining())
request_block_template();
return true;
});
m_update_merge_hr_interval.do_call([&](){
merge_hr();
return true;
});
return true;
}
//-----------------------------------------------------------------------------------------------------
void gpu_miner::do_print_hashrate(bool do_hr)
{
m_do_print_hashrate = do_hr;
}
//-----------------------------------------------------------------------------------------------------
void gpu_miner::merge_hr()
{
if (m_last_hr_merge_time && is_mining())
{
m_current_hash_rate = (m_hashes * 1000) / ((misc_utils::get_tick_count() - m_last_hr_merge_time + 1));
}
m_last_hr_merge_time = misc_utils::get_tick_count();
m_hashes = 0;
if (m_do_print_hashrate && is_mining())
LOG_PRINT_L0("hr: " << m_current_hash_rate << std::endl);
}
//-----------------------------------------------------------------------------------------------------
void gpu_miner::init_options(boost::program_options::options_description& desc)
{
command_line::add_arg(desc, arg_extra_messages);
command_line::add_arg(desc, arg_start_mining);
command_line::add_arg(desc, arg_gpu_list_platforms);
command_line::add_arg(desc, arg_gpu_list_devices);
command_line::add_arg(desc, arg_gpu_device_id);
command_line::add_arg(desc, arg_gpu_platform_id);
command_line::add_arg(desc, arg_gpu_local_work);
command_line::add_arg(desc, arg_gpu_global_work);
command_line::add_arg(desc, arg_gpu_benchmark);
//command_line::add_arg(desc, arg_mining_threads);
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::init(const boost::program_options::variables_map& vm)
{
m_config_folder = command_line::get_arg(vm, command_line::arg_data_dir);
epee::serialization::load_t_from_json_file(m_config, m_config_folder + "/" + MINER_CONFIG_FILENAME);
if (command_line::has_arg(vm, arg_extra_messages))
{
std::string buff;
bool r = file_io_utils::load_file_to_string(command_line::get_arg(vm, arg_extra_messages), buff);
CHECK_AND_ASSERT_MES(r, false, "Failed to load file with extra messages: " << command_line::get_arg(vm, arg_extra_messages));
std::vector<std::string> extra_vec;
boost::split(extra_vec, buff, boost::is_any_of("\n"), boost::token_compress_on);
m_extra_messages.resize(extra_vec.size());
for (size_t i = 0; i != extra_vec.size(); i++)
{
string_tools::trim(extra_vec[i]);
if (!extra_vec[i].size())
continue;
std::string buff = string_encoding::base64_decode(extra_vec[i]);
if (buff != "0")
m_extra_messages[i] = buff;
}
LOG_PRINT_L0("Loaded " << m_extra_messages.size() << " extra messages, current index " << m_config.current_extra_message_index);
}
if (command_line::has_arg(vm, arg_start_mining))
{
if (!currency::get_account_address_from_str(m_mine_address, command_line::get_arg(vm, arg_start_mining)))
{
LOG_ERROR("Target account address " << command_line::get_arg(vm, arg_start_mining) << " has wrong format, starting daemon canceled");
return false;
}
m_do_mining = true;
}
if (command_line::has_arg(vm, arg_gpu_device_id))
m_opencl_device = command_line::get_arg(vm, arg_gpu_device_id);
if (command_line::has_arg(vm, arg_gpu_platform_id))
m_opencl_platform = command_line::get_arg(vm, arg_gpu_platform_id);
if (command_line::has_arg(vm, arg_gpu_local_work))
m_local_work_size = command_line::get_arg(vm, arg_gpu_local_work);
if (command_line::has_arg(vm, arg_gpu_global_work))
m_global_work_size = command_line::get_arg(vm, arg_gpu_global_work);
if (command_line::has_arg(vm, arg_gpu_benchmark))
{
m_benchmark_mode = true;
std::string str = command_line::get_arg(vm, arg_gpu_benchmark);
m_benchmark_diff.assign(str);
// in case of benchmark don't wait for syncronization, start over there
account_public_address null_addr = AUTO_VAL_INIT(null_addr);
start(null_addr, 0);
m_do_print_hashrate = true;
}
return true;
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::deinit()
{
if (!tools::create_directories_if_necessary(m_config_folder))
{
LOG_PRINT_L0("Failed to create data directory: " << m_config_folder);
return false;
}
epee::serialization::store_t_to_json_file(m_config, m_config_folder + "/" + MINER_CONFIG_FILENAME);
return true;
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::is_mining()
{
return !m_stop;
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::start(const account_public_address& adr, size_t /* threads_count -- ignored */)
{
m_mine_address = adr;
CRITICAL_REGION_LOCAL(m_threads_lock);
if (is_mining())
{
LOG_PRINT_L0("Starting miner: miner already running");
return false;
}
if (!m_threads.empty())
{
LOG_ERROR("Starting miner canceled: there are still active mining threads");
return false;
}
m_template_no = 0;
request_block_template(); // always update block template prior to mining
ethash_set_use_dag(true);
LOG_PRINT_MAGENTA("Configuring GPU device:" << ENDL
<< " platform id: " << m_opencl_platform << ENDL
<< " device id: " << m_opencl_device << ENDL
<< " local work sz: " << m_local_work_size << ENDL
<< " global work sz: " << m_global_work_size, LOG_LEVEL_0);
bool res = ethash_cl_miner::configureGPU(
m_opencl_platform,
m_local_work_size,
m_global_work_size,
m_ms_per_batch,
m_cl_allow_cpu,
m_extra_gpu_memory,
get_block_height(m_template));
CHECK_AND_ASSERT_MES(res, false, "Failed to initialize gpu device!");
LOG_PRINT_MAGENTA("GPU configured successfully!", LOG_LEVEL_0);
if (m_benchmark_mode)
{
std::stringstream ss;
if (m_benchmark_diff != 0)
ss << m_benchmark_diff;
else
ss << "default";
LOG_PRINT_YELLOW("ATTENTION!! benchmark mode is ON (using " << ss.str() << " difficulty). Nothing will be sent to the network", LOG_LEVEL_0);
}
boost::interprocess::ipcdetail::atomic_write32(&m_stop, 0);
boost::interprocess::ipcdetail::atomic_write32(&m_thread_index, 0);
for (size_t i = 0; i != m_threads_total; i++)
m_threads.push_back(boost::thread(boost::bind(&gpu_miner::worker_thread, this)));
LOG_PRINT_L0("Mining has started with " << m_threads_total << " threads, good luck!");
return true;
}
//-----------------------------------------------------------------------------------------------------
uint64_t gpu_miner::get_speed()
{
if (is_mining())
return m_current_hash_rate;
else
return 0;
}
//-----------------------------------------------------------------------------------------------------
uint32_t gpu_miner::get_threads_count() const
{
return m_threads_total;
}
//-----------------------------------------------------------------------------------------------------
void gpu_miner::send_stop_signal()
{
boost::interprocess::ipcdetail::atomic_write32(&m_stop, 1);
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::stop()
{
LOG_PRINT_L1("Finishing " << m_threads.size() << " threads...");
send_stop_signal();
CRITICAL_REGION_LOCAL(m_threads_lock);
for(boost::thread& th : m_threads)
if (th.joinable() && th.get_id() != boost::this_thread::get_id())
th.join();
m_threads.clear();
LOG_PRINT_L0("Mining has been stopped, " << m_threads.size() << " finished");
return true;
}
//-----------------------------------------------------------------------------------------------------
void gpu_miner::on_synchronized()
{
if (m_do_mining)
{
start(m_mine_address, 0);
}
}
//-----------------------------------------------------------------------------------------------------
void gpu_miner::pause()
{
CRITICAL_REGION_LOCAL(m_miners_count_lock);
++m_pausers_count;
if (m_pausers_count == 1 && is_mining())
LOG_PRINT_L2("MINING PAUSED");
}
//-----------------------------------------------------------------------------------------------------
void gpu_miner::resume()
{
CRITICAL_REGION_LOCAL(m_miners_count_lock);
--m_pausers_count;
if (m_pausers_count < 0)
{
m_pausers_count = 0;
LOG_PRINT_RED_L0("Unexpected miner2::resume() called");
}
if (!m_pausers_count && is_mining())
LOG_PRINT_L2("MINING RESUMED");
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::handle_cli_info_commands(const boost::program_options::variables_map& vm)
{
if (command_line::has_arg(vm, arg_gpu_list_platforms))
{
ethash_cl_miner::listPlatforms();
return true;
}
if (command_line::has_arg(vm, arg_gpu_list_devices))
{
ethash_cl_miner::listAllDevices();
return true;
}
return false;
}
//-----------------------------------------------------------------------------------------------------
std::map<std::string, std::string> gpu_miner::get_versions()
{
return
{
{ "cl.hpp", "1.2.9" },
{ "opencl", ethash_cl_miner::platform_version() }
};
}
//-----------------------------------------------------------------------------------------------------
bool gpu_miner::worker_thread()
{
bool r = false;
uint32_t th_local_index = boost::interprocess::ipcdetail::atomic_inc32(&m_thread_index);
LOG_PRINT_L0("Miner thread was started [" << th_local_index << "]");
log_space::log_singletone::set_thread_log_prefix(std::string("[miner ") + std::to_string(th_local_index) + "]");
wide_difficulty_type local_diff = 0;
uint32_t local_template_ver = m_template_no - 1; // enforce DAG & ethash_cl_miner initialization at the very beginning of the work loop
uint64_t local_template_height = 0;
uint64_t local_template_epoch = UINT64_MAX;
crypto::hash block_pow_template_hash = null_hash;
block b;
std::shared_ptr<ethash_cl_miner> cl_miner_ptr(new ethash_cl_miner());
while (!m_stop)
{
if (m_pausers_count)//anti split workaround
{
misc_utils::sleep_no_w(100);
continue;
}
if (local_template_ver != m_template_no)
{
CRITICAL_REGION_BEGIN(m_template_lock);
b = m_template;
blobdata block_blob;
block_blob = get_block_hashing_blob(b);
access_nonce_in_block_blob(block_blob) = 0;
block_pow_template_hash = crypto::cn_fast_hash(block_blob.data(), block_blob.size());
local_diff = (m_benchmark_mode && m_benchmark_diff != 0) ? m_benchmark_diff : m_diffic;
CRITICAL_REGION_END();
local_template_height = get_block_height(b);
local_template_ver = m_template_no;
if (local_template_epoch != ethash_height_to_epoch(local_template_height))
{
local_template_epoch = ethash_height_to_epoch(local_template_height);
LOG_PRINT_MAGENTA("(Re)configuring DAG and GPU for epoch " << local_template_epoch << " (height " << local_template_height << ").....", LOG_LEVEL_0);
cl_miner_ptr.reset(new ethash_cl_miner());
uint64_t dag_size = 0;
const uint8_t* p_dag = ethash_get_dag(local_template_epoch, dag_size);
CHECK_AND_ASSERT_MES(p_dag != nullptr, false, "Failed to obtain DAG for epoch " << local_template_epoch);
LOG_PRINT_MAGENTA("(Re)initing GPU.....", LOG_LEVEL_0);
r = cl_miner_ptr->init(p_dag, dag_size, m_opencl_platform, m_opencl_device);
CHECK_AND_ASSERT_MES(r, false, "Failed to initialize ethash open cl miner");
}
}
if (local_template_ver == 0) // set_block_template() has not been called yet
{
LOG_PRINT_L2("Block template has not been set yet, waiting....");
epee::misc_utils::sleep_no_w(1000);
continue;
}
//set up mining handlers
auto hooker_ptr = get_lambda_hooker(
[&](uint64_t const* nonces, uint32_t count) // found handler
{
if (m_stop)
{
LOG_PRINT_MAGENTA("Found " << count << " nonces, SKIPPED because stop flag has been raised", LOG_LEVEL_1);
return true;
}
for (uint32_t i = 0; i < count; ++i)
{
uint64_t nonce = nonces[i];
crypto::hash h = get_block_longhash(local_template_height, block_pow_template_hash, nonce);
LOG_PRINT_MAGENTA("Found nonce [" << i+1 << "/" << count << "]: " << nonce << " (pow: " << h << ", boundary: 0x" << std::hex << std::setfill('0') << std::setw(16) << currency::difficulty_to_boundary(local_diff) << ", diff: " << std::dec << local_diff << ")", LOG_LEVEL_1);
if (check_hash(h, local_diff))
{
//we lucky!
b.nonce = nonce;
LOG_PRINT_GREEN((m_benchmark_mode ? " (BENCHMARK MODE) " : "") << "Found block " << get_block_hash(b) << " HEIGHT " << local_template_height << " (pow: " << h << ") for difficulty: " << local_diff, LOG_LEVEL_0);
//LOG_PRINT2("found_blocks", epee::string_tools::buff_to_hex_nodelimer(t_serializable_object_to_blob(b)), LOG_LEVEL_0);
//stop();
//return false;
if (!m_benchmark_mode)
{
if (m_phandler->handle_block_found(b))
{
//success, let's update config
++m_config.current_extra_message_index;
epee::serialization::store_t_to_json_file(m_config, m_config_folder + "/" + MINER_CONFIG_FILENAME);
}
else
{
LOG_PRINT_RED("handle_block_found failed for found block " << get_block_hash(b), LOG_LEVEL_0);
}
}
//LOG_PRINT_MAGENTA("Ignoring other found nonces for this height!", LOG_LEVEL_0);
break;
}
else
{
LOG_PRINT_MAGENTA("Found nonce [" << i+1 << "/" << count << "]: " << nonce << " doesn't met the requirements: pow: " << h << ", boundary: 0x" << std::hex << std::setfill('0') << std::setw(16) << currency::difficulty_to_boundary(local_diff) << ", diff: " << local_diff, LOG_LEVEL_0);
}
}
return true;
},
[&](uint64_t start_nonce, uint32_t count) //searched handler
{
m_hashes += count;
return true;
}
);
uint64_t upper_64_of_boundary = currency::difficulty_to_boundary(local_diff);
LOG_PRINT_MAGENTA("[Search] request for difficulty " << local_diff << ", upper boundary: 0x" << std::hex << std::setfill('0') << std::setw(16) << upper_64_of_boundary, LOG_LEVEL_3);
cl_miner_ptr->search((const uint8_t *)&block_pow_template_hash, upper_64_of_boundary, *static_cast<ethash_cl_miner::search_hook*>(hooker_ptr.get()));
//LOG_PRINT_MAGENTA("[Search] request for difficulty " << local_diff << " returned ", LOG_LEVEL_3);
}
LOG_PRINT_L0("Miner thread stopped [" << th_local_index << "]");
return true;
}
//-----------------------------------------------------------------------------------------------------
}
#endif
| 40.432727 | 296 | 0.5916 | [
"vector"
] |
9f6ad6a92e04723f1bf5b3bc9313913b0a9cb9b8 | 15,352 | cpp | C++ | src/cpp/orbprop/gravity.cpp | HiTMonitor/ginan | f348e2683507cfeca65bb58880b3abc2f9c36bcf | [
"Apache-2.0"
] | null | null | null | src/cpp/orbprop/gravity.cpp | HiTMonitor/ginan | f348e2683507cfeca65bb58880b3abc2f9c36bcf | [
"Apache-2.0"
] | null | null | null | src/cpp/orbprop/gravity.cpp | HiTMonitor/ginan | f348e2683507cfeca65bb58880b3abc2f9c36bcf | [
"Apache-2.0"
] | null | null | null |
// #pragma GCC optimize ("O0")
#include "navigation.hpp"
#include "instrument.hpp"
#include "constants.hpp"
#include "satRefSys.hpp"
#include "acsConfig.hpp"
#include "gravity.hpp"
#include "jplEph.hpp"
#include "common.hpp"
#include "sofa.hpp"
Vector3d CalcPolarAngles(
Vector3d mVec)
{
/* Norm of vector
*/
double mR = mVec.norm();
/* Azimuth of vector
*/
double mPhi;
if ((mVec(0) == 0) && (mVec(1) == 0)) { mPhi = 0; }
else { mPhi = atan2(mVec(1), mVec(0)); }
if (mPhi < 0)
{
mPhi += 2 * PI;
}
double rho = sqrt(mVec(0) * mVec(0) + mVec(1) * mVec(1)); // Length of projection in x - y - plane:
/* Altitude of vector
*/
double mTheta;
if ((mVec(2) == 0) && (rho == 0)) { mTheta = 0; }
else { mTheta = atan2(mVec(2), rho); }
Vector3d vecRAE;
vecRAE(0) = mR;
vecRAE(1) = mPhi;
vecRAE(2) = mTheta;
return vecRAE;
}
/* Calculate normalized Legendre polynomial values
*
*/
MatrixXd Legendre(
int m, ///< Maximum degree
int n, ///< Maximum order
double phi) ///< Geocentric latitude in radian
{
MatrixXd pnm = MatrixXd::Zero(m + 1, n + 1);
pnm(0, 0) = 1;
pnm(1, 1) = sqrt(3) * cos(phi);
/* diagonal coefficients
*/
for (int i = 2; i <= m; i++)
{
double s = i;
pnm(i, i) = sqrt((2 * s + 1) / (2 * s)) * cos(phi) * pnm(i - 1, i - 1);
}
/* horizontal first step coefficients
*/
for (int i = 1; i <= m; i++)
{
double s = i;
pnm(i, i - 1) = sqrt(2 * s + 1) * sin(phi) * pnm(i - 1, i - 1);
}
/* horizontal second step coefficients
*/
int j = 0, k = 2;
do
{
for (int i = k; i <= m; i++)
{
double s = i;
double h = j;
pnm(i, j) = sqrt((2 * s + 1) / ((s - h) * (s + h))) * (sqrt(2 * s - 1) * sin(phi) * pnm(i - 1, j) - sqrt(((s + h - 1) * (s - h - 1)) / (2 * s - 3)) * pnm(i - 2, j));
}
j++;
k++;
}
while (j <= n);
return pnm;
}
/* Calculate normalized Legendre polynomial first derivative values
*
*/
MatrixXd LegendreD(
int m, ///< Maximum degree
int n, ///< Maximum order
MatrixXd pnm, ///< Normalised Legendre polynomial matrix
double phi) ///< Geocentric latitude in radian
{
MatrixXd dpnm = MatrixXd::Zero(m + 1, n + 1);
dpnm(0, 0) = 0;
dpnm(1, 1) = -sqrt(3) * sin(phi);
/* diagonal coefficients
*/
for (int i = 2; i <= m; i++)
{
double s = i;
dpnm(i, i) = sqrt((2 * s + 1) / (2 * s)) * (cos(phi) * dpnm(i - 1, i - 1) - sin(phi) * pnm(i - 1, i - 1));
}
/* horizontal first step coefficients
*/
for (int i = 1; i <= m; i++)
{
double s = i;
dpnm(i, i - 1) = sqrt(2 * s + 1) * ((cos(phi) * pnm(i - 1, i - 1)) + (sin(phi) * dpnm(i - 1, i - 1)));
}
/* horizontal second step coefficients
*/
int j = 0, k = 2;
do
{
for (int i = k; i <= m; i++)
{
double s = i;
double h = j;
dpnm(i, j) = sqrt((2 * s + 1) / ((s - h) * (s + h))) * ((sqrt(2 * s - 1) * sin(phi) * dpnm(i - 1, j)) + sqrt(2 * s - 1) * cos(phi) * pnm(i - 1, j) - sqrt(((s + h - 1) * (s - h - 1)) / (2 * s - 3)) * dpnm(i - 2, j));
}
j++;
k++;
}
while (j <= n);
return dpnm;
}
GravityModel::GravityModel(
EarthGravMdlOpt gravMdlOpt,
EGMCoef uncorrectedEgmCoef)
{
gravModelType = gravMdlOpt.earthGravMdl;
mEarthGravAccDeg = gravMdlOpt.earthGravAccDeg;
mEarthGravSTMDeg = gravMdlOpt.earthGravSTMDeg;
this->uncorrectedEgmCoef = uncorrectedEgmCoef;
}
void GravityModel::solidEarthTidesCorrection(
Trace& trace,
double mjdUTC, ///< UTC in modified julian date format
EGMCoef& egmCoef, ///< Struct of Earth gravity coefficients
IERS& iers, ///< Instance of IERS class
const Vector3d& vecRAESun, ///< Rho, azimuth and altitude information of Sun
const Vector3d& vecRAEMoon) ///< Rho, azimuth and altitude information of Moon
{
/* Effect of Solid Earth Tides(elastic Earth)
* For dC21and dS21
* The coefficients we choose are in - phase(ip) amplitudes and out - of - phase amplitudes of the
* corrections for frequency dependence, and multipliers of the Delaunay variables
* Refer to Table 6.5a in IERS2010
*/
double coeff0[48][7] =
{
{2, 0, 2, 0, 2, -0.1, 0},
{0, 0, 2, 2, 2, -0.1, 0},
{1, 0, 2, 0, 1, -0.1, 0},
{1, 0, 2, 0, 2, -0.7, 0.1},
{-1, 0, 2, 2, 2, -0.1, 0},
{0, 0, 2, 0, 1, -1.3, 0.1},
{0, 0, 2, 0, 2, -6.8, 0.6},
{0, 0, 0, 2, 0, 0.1, 0},
{1, 0, 2, -2, 2, 0.1, 0},
{-1, 0, 2, 0, 1, 0.1, 0},
{-1, 0, 2, 0, 2, 0.4, 0},
{1, 0, 0, 0, 0, 1.3, -0.1},
{1, 0, 0, 0, 1, 0.3, 0},
{-1, 0, 0, 2, 0, 0.3, 0},
{-1, 0, 0, 2, 1, 0.1, 0},
{0, 1, 2, -2, 2, -1.9, 0.1},
{0, 0, 2, -2, 1, 0.5, 0},
{0, 0, 2, -2, 2, -43.4, 2.9},
{0, -1, 2, -2, 2, 0.6, 0},
{0, 1, 0, 0, 0, 1.6, -0.1},
{-2, 0, 2, 0, 1, 0.1, 0},
{0, 0, 0, 0, -2, 0.1, 0},
{0, 0, 0, 0, -1, -8.8, 0.5},
{0, 0, 0, 0, 0, 470.9, -30.2},
{0, 0, 0, 0, 1, 68.1, -4.6},
{0, 0, 0, 0, 2, -1.6, 0.1},
{-1, 0, 0, 1, 0, 0.1, 0},
{0, -1, 0, 0, -1, -0.1, 0},
{0, -1, 0, 0, 0, -20.6, -0.3},
{0, 1, -2, 2, -2, 0.3, 0},
{0, -1, 0, 0, 1, -0.3, 0},
{-2, 0, 0, 2, 0, -0.2, 0},
{-2, 0, 0, 2, 1, -0.1, 0},
{0, 0, -2, 2, -2, -5.0, 0.3},
{0, 0, -2, 2, -1, 0.2, 0},
{0, -1, -2, 2, -2, -0.2, 0},
{1, 0, 0, -2, 0, -0.5, 0},
{1, 0, 0, -2, 1, -0.1, 0},
{-1, 0, 0, 0, -1, 0.1, 0},
{-1, 0, 0, 0, 0, -2.1, 0.1},
{-1, 0, 0, 0, 1, -0.4, 0},
{0, 0, 0, -2, 0, -0.2, 0},
{-2, 0, 0, 0, 0, -0.1, 0},
{0, 0, -2, 0, -2, -0.6, 0},
{0, 0, -2, 0, -1, -0.4, 0},
{0, 0, -2, 0, 0, -0.1, 0},
{-1, 0, -2, 0, -2, -0.1, 0},
{-1, 0, -2, 0, -1, -0.1, 0}
};
/* For dC22and dS22, Refer to Table 6.5c in IERS2010
*/
double coeff2[2][6] =
{
{1, 0, 2, 0, 2, -0.3},
{0, 0, 2, 0, 2, -1.2}
};
/* STEP1 CORRECTIONS
*/
for (auto body : {eSun ,eMoon})
{
double GM_Body = 0;
double rho = 0;
double az = 0;
MatrixXd lg;
if (body == eMoon) { GM_Body = GM_Moon; rho = vecRAEMoon(0); az = vecRAEMoon(1); lg = Legendre (4, 4, vecRAEMoon(2)); }
if (body == eSun) { GM_Body = GM_Sun; rho = vecRAESun (0); az = vecRAESun (1); lg = Legendre (4, 4, vecRAESun (2)); }
double GM_Ratio = GM_Body / GM_Earth;
double RE_Rho_Pow;
double extPotentialLoveNumbers[4][4] =
{
{},
{},
{0.29525, 0.29470, 0.29801 },
{0.093, 0.093, 0.093, 0.094 }
};
for (int n = 2; n <= 3; n++)
for (int m = 0; m <= n; m++)
{
double loveNumber = extPotentialLoveNumbers[n][m];
double div = 2*n+1;
RE_Rho_Pow = pow((RE_WGS84 / rho), n+1);
egmCoef.smn(n, m) += (loveNumber / div) * GM_Ratio * RE_Rho_Pow * lg(n, m) * sin(m * az);
egmCoef.cmn(n, m) += (loveNumber / div) * GM_Ratio * RE_Rho_Pow * lg(n, m) * cos(m * az);
}
double extPotentialLoveNumbers_[3] =
{
-0.00087, -0.00079, -0.00057
};
for (int m = 0; m <= 2; m++)
{
double loveNumber = extPotentialLoveNumbers_[m];
double div = 5;
RE_Rho_Pow = pow((RE_WGS84 / rho), 3);
egmCoef.smn(4, m) += (loveNumber / div) * GM_Ratio * RE_Rho_Pow * lg(2, m) * sin(m * az);
egmCoef.cmn(4, m) += (loveNumber / div) * GM_Ratio * RE_Rho_Pow * lg(2, m) * cos(m * az);
}
}
/* STEP2 CORRECTIONS
*/
double mjdUT1 = iers.UT1_UTC () / 86400.0 + mjdUTC;
double mjdTT = iers.TT_UTC () / 86400.0 + mjdUTC;
double theta_g = iauGmst06(JD2MJD, mjdUT1, JD2MJD, mjdTT);
{
double dC21 = 0;
double dS21 = 0;
for (int jj = 0; jj < 48; jj++)
{
dC21 += 1e-12 * coeff0[jj][5] * sin(theta_g + PI); //todo aaron, cos -sin
dS21 += 1e-12 * coeff0[jj][5] * cos(theta_g + PI);
}
egmCoef.cmn(2, 1) += dC21;
egmCoef.smn(2, 1) += dS21;
}
{
double dC22 = 0;
double dS22 = 0;
for (int jj = 0; jj <= 1; jj++)
{
dC22 += 1e-12 * coeff2[jj][5] * sin(theta_g + PI);
dS22 += 1e-12 * coeff2[jj][5] * cos(theta_g + PI);
}
egmCoef.cmn(2, 2) += dC22;
egmCoef.smn(2, 2) += dS22;
}
/* Treatment of the Permanent Tide(elastic Earth)
*/
{
double dC20 = 4.4228e-8 * (-0.31460) * 0.29525;
egmCoef.cmn(2, 0) -= dC20;
}
/* Effect of Solid Earth Pole Tide(elastic Earth)
*/
{
double dC21 = -1.290e-9 * iers.xp;
double dS21 = +1.290e-9 * iers.yp;
egmCoef.cmn(2, 1) += dC21;
egmCoef.smn(2, 1) += dS21;
}
}
void GravityModel::oceanTidesCorrection(
Trace& trace,
double mjdUTC, ///< UTC in modified julian date format
EGMCoef& egmCoef, ///< Struct of Earth gravity coefficients
const Vector3d& vecRAESun, ///< Rho, azimuth and altitude information of Sun
const Vector3d& vecRAEMoon) ///< Rho, azimuth and altitude information of Moon
{
/* rho, azimuth and elevation (altitude) of Sun
*/
double rhoSun = vecRAESun(0);
double azSun = vecRAESun(1);
double elSun = vecRAESun(2);
/* rho, azimuth and elevation (altitude) of Sun
*/
double rhoMoon = vecRAEMoon(0);
double azMoon = vecRAEMoon(1);
double elMoon = vecRAEMoon(2);
for (auto body : {eSun ,eMoon})
{
double GM_Body = 0;
double rho = 0;
double az = 0;
MatrixXd lg;
if (body == eMoon) { GM_Body = GM_Moon; rho = vecRAEMoon(0); az = vecRAEMoon(1); lg = Legendre (7, 7, vecRAEMoon(2)); }
if (body == eSun) { GM_Body = GM_Sun; rho = vecRAESun (0); az = vecRAESun (1); lg = Legendre (7, 7, vecRAESun (2)); }
double GM_Ratio = GM_Body / GM_Earth;
double RE_Rho_Pow;
double loadDefCoeffs[7] =
{
0,
0,
-0.3075,
-0.1950,
-0.1320,
-0.1032,
-0.0892
};
for (int n = 2; n <= 6; n++)
{
RE_Rho_Pow = pow((RE_WGS84 / rho), n+1);
double coeff_n = loadDefCoeffs[n];
double div = 2*n+1;
for (int m = 0; m <= n; m++)
{
egmCoef.smn(n, m) += GM_Ratio * RE_Rho_Pow * lg(n, m) * sin(m * az) / div * coeff_n;
egmCoef.cmn(n, m) += GM_Ratio * RE_Rho_Pow * lg(n, m) * cos(m * az) / div * 4 * PI * SQR(RE_WGS84) * RHO_w / M_Earth * (1 + coeff_n);
}
}
}
}
void GravityModel::correctEgmCoefficients(
Trace& trace,
const double mjdUTC,
ERPValues& erpv, ///< xp, yp, ut1_utc, lod and leapsecond
const Matrix3d& mECI2BF) ///< Transformation matrix from ECI to central body fixed system)
{
//copy the uncorrected then (re)apply corrections
correctedEgmCoef = uncorrectedEgmCoef;
if ( acsConfig.forceModels.solid_earth_tides == false
&& acsConfig.forceModels.ocean_tide_loading == false)
{
//no corrections need to be applied.
return;
}
auto& egmCoef = correctedEgmCoef;
Instrument instrument("gravtop");
double dUTC_TAI = -(19 + erpv.leaps);
double xp = erpv.xp;
double yp = erpv.yp;
double dUT1_UTC = erpv.ut1_utc;
double lod = erpv.lod;
IERS iers = IERS(dUT1_UTC, dUTC_TAI, xp, yp, lod);
double jdTT = mjdUTC + JD2MJD + iers.TT_UTC() / 86400.0;
// from inertial coordinate to earth centred fixed coordiante
Vector3d rSun; jplEphPos(nav.jplEph_ptr, jdTT, E_ThirdBody::SUN, rSun); rSun = mECI2BF * rSun;
Vector3d rMoon; jplEphPos(nav.jplEph_ptr, jdTT, E_ThirdBody::MOON, rMoon); rMoon = mECI2BF * rMoon;
Vector3d vecRAESun = CalcPolarAngles(rSun); // calculating the range, azimuth and altitude
Vector3d vecRAEMoon = CalcPolarAngles(rMoon);
if (acsConfig.forceModels.solid_earth_tides)
{
Instrument instrument("solid");
solidEarthTidesCorrection (trace, mjdUTC, egmCoef, iers, vecRAESun, vecRAEMoon);
}
if (acsConfig.forceModels.ocean_tide_loading)
{
Instrument instrument("ocean");
oceanTidesCorrection (trace, mjdUTC, egmCoef, vecRAESun, vecRAEMoon);
}
}
Vector3d GravityModel::centralBodyGravityAcc(
Trace& trace,
const double mjdUTC,
ERPValues& erpv, ///< xp, yp, ut1_utc, lod and leapsecond
const Vector3d& rSat, ///< Satellite position vector in the inertial system
const Matrix3d& eci2ecef, ///< Transformation matrix from ECI to central body fixed system
bool bVarEq) ///< bVarEq = 1 if for the variational equation
{
Instrument instrument(__FUNCTION__);
auto& egmCoef = correctedEgmCoef;
int mMax;
int nMax;
if (bVarEq) { mMax = mEarthGravSTMDeg.mMax; nMax = mEarthGravSTMDeg.nMax; }
else { mMax = mEarthGravAccDeg.mMax; nMax = mEarthGravAccDeg.nMax; }
Vector3d rSat_ecef = eci2ecef * rSat;
double R = rSat_ecef.norm();
double rSat_latgc = asin(rSat_ecef.z() / R); // Geocentric latitude of satellite (n)
double rSat_longc = atan2(rSat_ecef.y(), rSat_ecef.x()); // Geocentric longitude of satellite (n)
MatrixXd pnm = Legendre (mMax, nMax, rSat_latgc); // Legendre matrix given order/degree
MatrixXd dpnm = LegendreD(mMax, nMax, pnm, rSat_latgc); // Normalised Legendre matrix given order/degree
double dUdr = 0;
double dUdlatgc = 0;
double dUdlongc = 0;
double q1 = 0;
double q2 = 0;
double q3 = 0;
for (int m = 0; m <= nMax; m++)
{
int nd = m;
double b1 = (-GM_Earth / SQR(R)) * pow((RE_WGS84 / R), nd) * (m + 1);
double b2 = ( GM_Earth / R) * pow((RE_WGS84 / R), nd);
double b3 = ( GM_Earth / R) * pow((RE_WGS84 / R), nd);
for (int n = 0; n <= mMax; n++)
{
q1 += pnm (m, n) * (egmCoef.cmn(m, n) * cos(n * rSat_longc) + egmCoef.smn(m, n) * sin(n * rSat_longc));
q2 += dpnm(m, n) * (egmCoef.cmn(m, n) * cos(n * rSat_longc) + egmCoef.smn(m, n) * sin(n * rSat_longc));
q3 += n * pnm (m, n) * (egmCoef.smn(m, n) * cos(n * rSat_longc) - egmCoef.cmn(m, n) * sin(n * rSat_longc));
}
dUdr += q1 * b1;
dUdlatgc += q2 * b2;
dUdlongc += q3 * b3;
q3 = 0;
q2 = q3;
q1 = q2;
}
double r2xy = SQR(rSat_ecef.x()) + SQR(rSat_ecef.y());
Vector3d acc;
acc.x() = rSat_ecef.x() * dUdr / R - dUdlatgc * rSat_ecef.z() / SQR(R) / sqrt(r2xy) / rSat_ecef.x() - rSat_ecef.y() * dUdlongc / r2xy;
acc.y() = rSat_ecef.y() * dUdr / R - dUdlatgc * rSat_ecef.z() / SQR(R) / sqrt(r2xy) / rSat_ecef.y() + rSat_ecef.x() * dUdlongc / r2xy;
acc.z() = rSat_ecef.z() * dUdr / R + dUdlatgc * sqrt(r2xy) / SQR(R);
return eci2ecef.transpose() * acc;
}
/* Relativistic Effects
*
*/
Vector3d GravityModel::relativityEffectsAcc(
Trace& trace, ///< Trace to output to (similar to cout)
const Vector3d& rSat, ///< Inertial position of satellite (m)
const Vector3d& vSat) ///< Inertial velocity of satellite (m/s)
{
double R = rSat.norm();
double V = vSat.norm();
Vector3d acc = GM_Earth / (SQR(CLIGHT) * pow(R, 3))
* ( (4 * GM_Earth / R - SQR(V)) * rSat + 4 * rSat.dot(vSat) * vSat);
return acc;
}
Vector3d accelPointMassGravity(
Trace& trace,
const double mjdTT,
const Vector3d& pos,
E_ThirdBody thirdBody,
Vector3d& thirdBodyPos)
{
double mGM = 0;
switch (thirdBody)
{
case E_ThirdBody::MERCURY: mGM = GM_Mercury; break;
case E_ThirdBody::VENUS: mGM = GM_Venus; break;
case E_ThirdBody::EARTH: mGM = GM_Earth; break;
case E_ThirdBody::MARS: mGM = GM_Mars; break;
case E_ThirdBody::JUPITER: mGM = GM_Jupiter; break;
case E_ThirdBody::SATURN: mGM = GM_Saturn; break;
case E_ThirdBody::URANUS: mGM = GM_Uranus; break;
case E_ThirdBody::NEPTUNE: mGM = GM_Neptune; break;
case E_ThirdBody::PLUTO: mGM = GM_Pluto; break;
case E_ThirdBody::MOON: mGM = GM_Moon; break;
case E_ThirdBody::SUN: mGM = GM_Sun; break;
}
Vector3d relativePos = pos - thirdBodyPos;
/* Acceleration
*/
return -mGM * ( relativePos .normalized() / relativePos .squaredNorm()
+ thirdBodyPos.normalized() / thirdBodyPos .squaredNorm());
}
| 27.611511 | 218 | 0.568851 | [
"vector",
"solid"
] |
9f726557c9a2958b01c2b5d0502bcc6e89852042 | 38,821 | cpp | C++ | euhatrtsplib/src/main/jni/euhatrtsp/livevideo/RtspOp.cpp | euhat/EuhatRtsp | f5d9919adff27b06e185d4469671e7aababcb941 | [
"Apache-2.0"
] | 11 | 2019-06-15T06:28:51.000Z | 2020-11-11T09:21:18.000Z | euhatrtsplib/src/main/jni/euhatrtsp/livevideo/RtspOp.cpp | baechirhoon/EuhatRtsp | f5d9919adff27b06e185d4469671e7aababcb941 | [
"Apache-2.0"
] | 2 | 2019-07-17T08:38:01.000Z | 2020-05-07T00:41:52.000Z | euhatrtsplib/src/main/jni/euhatrtsp/livevideo/RtspOp.cpp | baechirhoon/EuhatRtsp | f5d9919adff27b06e185d4469671e7aababcb941 | [
"Apache-2.0"
] | 8 | 2019-05-28T04:04:50.000Z | 2021-07-30T14:29:58.000Z | /*
* EuhatRtsp
* library and sample to play and acquire rtsp stream on Android device
*
* Copyright (c) 2014-2018 Euhat.com euhat@hotmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
#include "CommonOp.h"
#include "RtspOp.h"
#include "DecodeOp.h"
#include "SPSParser.h"
#include <android/native_window_jni.h>
static WH_THREAD_DEF(frameCallbackThread, arg)
{
EuhatRtspOp *pThis = (EuhatRtspOp *)arg;
pThis->frameCallbackProc();
return 0;
}
MemPool::MemPool(int unitSize, int maxCount)
{
unitSize_ = unitSize;
maxCount_ = maxCount;
whMutexInit(&mutex_);
}
MemPool::~MemPool()
{
whMutexFini(&mutex_);
while (pool_.size() > 0) {
void *mem = pool_.front();
pool_.pop_front();
free(mem);
}
}
void *MemPool::alloc(int size)
{
if (size > unitSize_) {
DBG(("need size %d bigger than unit size %d.\n", size, unitSize_));
return NULL;
}
void *mem = NULL;
WhMutexGuard guard(&mutex_);
if (pool_.size() > 0) {
mem = pool_.front();
pool_.pop_front();
}
if (NULL == mem) {
mem = malloc(unitSize_);
}
return mem;
}
void MemPool::dealloc(void *mem)
{
WhMutexGuard guard(&mutex_);
pool_.push_back(mem);
if (pool_.size() > maxCount_) {
mem = pool_.front();
pool_.pop_front();
free(mem);
}
}
static WH_THREAD_DEF(decodingThread, arg)
{
EuhatRtspOp *pThis = (EuhatRtspOp *)arg;
pThis->decodingProc();
return 0;
}
static WH_THREAD_DEF(previewThread, arg)
{
EuhatRtspOp *pThis = (EuhatRtspOp *)arg;
pThis->previewProc();
return 0;
}
int EuhatRtspOp::connect3(const char *url)
{
if (needReconnecting_) {
return 0;
}
needReconnecting_ = 1;
return connect2(url);
}
int EuhatRtspOp::close3()
{
if (!needReconnecting_) {
return 0;
}
needReconnecting_ = 0;
close2();
{
WhMutexGuard guard(&mutexPreview_);
while (listPreviewFrame_.size() > 0) {
char *frame = listPreviewFrame_.front();
listPreviewFrame_.pop_front();
yuvMemPool_->dealloc(frame);
}
}
return 0;
}
static WH_THREAD_DEF(timerThread, arg)
{
EuhatRtspOp *pThis = (EuhatRtspOp *)arg;
pThis->timerProc();
return 0;
}
static WH_THREAD_DEF(statusCallbackThread, arg)
{
EuhatRtspOp *pThis = (EuhatRtspOp *)arg;
pThis->statusCallbackProc();
return 0;
}
static WH_THREAD_DEF(messageThread, arg)
{
EuhatRtspOp *pThis = (EuhatRtspOp *)arg;
pThis->messageProc();
return 0;
}
EuhatRtspOp::EuhatRtspOp()
{
h264MemPool_ = new MemPool(MEM_POOL_WIDTH_MAX * MEM_POOL_HEIGHT_MAX * 3 / 2 + 40, 10);
yuvMemPool_ = new MemPool(MEM_POOL_WIDTH_MAX * MEM_POOL_HEIGHT_MAX * 3 / 2 + 40, 10);
rgbMemPool_ = new MemPool(MEM_POOL_WIDTH_MAX * MEM_POOL_HEIGHT_MAX * 4 + 40, 2);
rtsp_ = NULL;
rtspUseFlags_ = 0;
rtspFlags_ = 1;
rtspTimeOut_ = 8000;
reconnectTimeOut_ = 10000;
displayFps_ = 25;
displayBufCount_ = 100;
hasResolution_ = 0;
hasFirstFrame_ = 0;
whMutexInit(&mutexHasResolution_);
pthread_cond_init(&syncHasResolution_, NULL);
needReconnecting_ = 0;
isConnected_ = 0;
isPlaying_ = 0;
whMutexInit(&mutexDecoder_);
pthread_cond_init(&syncDecoder_, NULL);
decoder_ = EuhatDecodeOp::genDecoder();
decoder_->setOutputMemPool(yuvMemPool_);
whMutexInit(&mutexPreview_);
pthread_cond_init(&syncPreview_, NULL);
whMutexInit(&mutexPreviewDraw_);
winPreview_ = NULL;
winPreviewNeedDraw_ = 1;
whMutexInit(&mutexStatusCallback_);
whMutexInit(&mutexStatusCallbackCall_);
objStatusCallback_ = NULL;
methodsStatusCallback_.onStatus = NULL;
whMutexInit(&mutexFrameCallback_);
pthread_cond_init(&syncFrameCallback_, NULL);
whMutexInit(&mutexFrameCallbackCall_);
objFrameCallback_ = NULL;
methodsFrameCallback_.onFrame = NULL;
whMutexInit(&mutexMessage_);
whThreadCreate(messageThreadHandle_, messageThread, this);
isTimerThreadExiting_ = 0;
whThreadCreate(previewThreadHandle_, previewThread, this);
whThreadCreate(frameCallbackThreadHandle_, frameCallbackThread, this);
whThreadCreate(timerThreadHandle_, timerThread, this);
whThreadCreate(statusCallbackThreadHandle_, statusCallbackThread, this);
}
void EuhatRtspOp::startWorkThread()
{
isExiting_ = 0;
whThreadCreate(decodingThreadHandle_, decodingThread, this);
}
void EuhatRtspOp::stopWorkThread()
{
isExiting_ = 1;
pthread_cond_signal(&syncDecoder_);
whThreadJoin(decodingThreadHandle_);
while (listDecodeFrame_.size() > 0) {
char *frame = listDecodeFrame_.front();
listDecodeFrame_.pop_front();
h264MemPool_->dealloc(frame);
}
}
int EuhatRtspOp::postMessage(MessageParams ¶ms)
{
WhMutexGuard guard(&mutexMessage_);
if (params.type != 0) {
while (listMessage_.size() > 10) {
listMessage_.pop_front();
}
}
listMessage_.push_back(params);
return 1;
}
int EuhatRtspOp::postMessageStr(int type, const char *str)
{
MessageParams params;
params.type = type;
params.str = str;
return postMessage(params);
}
int EuhatRtspOp::postMessageInt(int type, int param)
{
MessageParams params;
params.type = type;
params.iParam = param;
return postMessage(params);
}
EuhatRtspOp::~EuhatRtspOp()
{
isTimerThreadExiting_ = 1;
whThreadJoin(statusCallbackThreadHandle_);
whThreadJoin(timerThreadHandle_);
postMessageInt(0, 0);
whThreadJoin(messageThreadHandle_);
pthread_cond_signal(&syncFrameCallback_);
whThreadJoin(frameCallbackThreadHandle_);
while (listFrameCallback_.size() > 0) {
char *frame = listFrameCallback_.front();
listFrameCallback_.pop_front();
yuvMemPool_->dealloc(frame);
}
pthread_cond_signal(&syncPreview_);
whThreadJoin(previewThreadHandle_);
while (listPreviewFrame_.size() > 0) {
char *frame = listPreviewFrame_.front();
listPreviewFrame_.pop_front();
yuvMemPool_->dealloc(frame);
}
whMutexFini(&mutexMessage_);
whMutexFini(&mutexFrameCallbackCall_);
pthread_cond_destroy(&syncFrameCallback_);
whMutexFini(&mutexFrameCallback_);
whMutexFini(&mutexStatusCallbackCall_);
if (winPreview_)
ANativeWindow_release(winPreview_);
whMutexFini(&mutexPreviewDraw_);
pthread_cond_destroy(&syncPreview_);
whMutexFini(&mutexPreview_);
delete decoder_;
pthread_cond_destroy(&syncDecoder_);
whMutexFini(&mutexDecoder_);
pthread_cond_destroy(&syncHasResolution_);
whMutexFini(&mutexHasResolution_);
delete h264MemPool_;
delete yuvMemPool_;
delete rgbMemPool_;
}
void getResolutionFromSPS(unsigned char *buf, const int nLen, int &Width, int &Height)
{
int iWidth = 0, iHeight = 0;
SPSParser spsReader;
bs_t s;
s.p = (uint8_t *)buf;
s.p_start = (uint8_t *)buf;
s.p_end = (uint8_t *)(buf + nLen);
s.i_left = 8;
if (spsReader.Do_Read_SPS(&s, &iWidth, &iHeight) != 0)
{
iWidth = 1920;
iHeight = 1088;
}
Width = iWidth;
Height = iHeight;
}
char NALH[4] = {0x00, 0x00, 0x00, 0x01};
void EuhatRtspOp::streamCallBack(int streamType, unsigned char *frame, unsigned len, void *context, FrameInfo *info)
{
EuhatRtspOp *euhatRtsp = (EuhatRtspOp *)context;
char *fData = NULL;
char *pYUV = NULL;
char *buffer = NULL;
int iRet = -1;
if (streamType == 2) {
if (!euhatRtsp->hasResolution_) {
if ((frame[0] & 31) == 7) {
getResolutionFromSPS(frame, len, euhatRtsp->videoWidth_, euhatRtsp->videoHeight_);
if (1088 == euhatRtsp->videoHeight_) {
euhatRtsp->videoHeightOff_ = 8;
} else if (1090 == euhatRtsp->videoHeight_) {
euhatRtsp->videoHeightOff_ = 10;
} else {
euhatRtsp->videoHeightOff_ = 0;
}
euhatRtsp->hasResolution_ = 1;
euhatRtsp->decoder_->updateWH(euhatRtsp->videoWidth_, euhatRtsp->videoHeight_ - euhatRtsp->videoHeightOff_);
//pthread_cond_signal(&euhatRtsp->syncHasResolution_);
{
WhMutexGuard guard(&euhatRtsp->mutexPreviewDraw_);
if (euhatRtsp->winPreview_) {
ANativeWindow_setBuffersGeometry(euhatRtsp->winPreview_,
euhatRtsp->videoWidth_, euhatRtsp->videoHeight_ - euhatRtsp->videoHeightOff_, WINDOW_FORMAT_RGBA_8888);
}
}
}
}
struct timeval tv;
gettimeofday(&tv, NULL);
euhatRtsp->rtspLastGetTime_ = tv.tv_sec * 1000 + tv.tv_usec / 1000;
if (!euhatRtsp->isPlaying_)
return;
if (!euhatRtsp->hasResolution_)
return;
fData = (char *)euhatRtsp->h264MemPool_->alloc(4 + 4 + len);
*(int *)fData = len + 4;
memcpy(fData + 4, NALH, 4);
memcpy(fData + 4 + 4, frame, len);
if ((frame[0] & 31) == 7) {
euhatRtsp->decoder_->updateSps(fData);
} else if ((frame[0] & 31) == 8) {
euhatRtsp->decoder_->updatePps(fData);
}
WhMutexGuard guard(&euhatRtsp->mutexDecoder_);
euhatRtsp->listDecodeFrame_.push_back(fData);
pthread_cond_signal(&euhatRtsp->syncDecoder_);
if (euhatRtsp->listDecodeFrame_.size() > 100) {
euhatRtsp->informStatus(EUHAT_STATUS_DECODING_QUEUE_TOO_LARGE, euhatRtsp->listDecodeFrame_.size() - 100, 0);
while (euhatRtsp->listDecodeFrame_.size() > 1) {
char *frame = euhatRtsp->listDecodeFrame_.front();
euhatRtsp->listDecodeFrame_.pop_front();
euhatRtsp->h264MemPool_->dealloc(frame);
}
}
}
}
int EuhatRtspOp::decodingProc()
{
JavaVM *vm = getVM();
JNIEnv *env;
vm->AttachCurrentThread(&env, NULL);
while (!isExiting_) {
char *frame = NULL;
{
WhMutexGuard guard(&mutexDecoder_);
if (listDecodeFrame_.size() > 0) {
frame = listDecodeFrame_.front();
listDecodeFrame_.pop_front();
} else {
whCondWait(&syncDecoder_, &mutexDecoder_);
}
}
if (NULL == frame)
continue;
decoder_->decode(frame + 4, *(int *)frame);
h264MemPool_->dealloc(frame);
}
vm->DetachCurrentThread();
return 1;
}
int EuhatRtspOp::initRtspSource()
{
int iRet = -1;
int i = 0;
rtsp_ = rtsp_source_new(streamCallBack, this);
if (NULL == rtsp_) {
return -1;
}
int flag = 1;
int rtspTimeOut = 8000;
if (rtspUseFlags_) {
flag = rtspFlags_;
rtspTimeOut = rtspTimeOut_;
}
iRet = rtsp_source_open(rtsp_, rtspUrl_.c_str(), flag, rtspTimeOut);
DBG(("rtsp flag is %d.\n", flag));
if (iRet < 0) {
DBG(("rtsp source open [%s], use flags %d, failed.\n", rtspUrl_.c_str(), rtspUseFlags_));
rtsp_source_free(rtsp_);
rtsp_ = NULL;
return -1;
}
iRet = rtsp_source_play(rtsp_);
if (iRet < 0) {
DBG(("rtsp source play failed.\n"));
rtsp_source_close(rtsp_);
rtsp_source_free(rtsp_);
rtsp_ = NULL;
return -1;
}
return 0;
}
void EuhatRtspOp::finiRtspSource()
{
if (rtsp_)
{
rtsp_source_close(rtsp_);
rtsp_source_free(rtsp_);
rtsp_ = NULL;
}
}
static int Table_fv1[256] = { -180, -179, -177, -176, -174, -173, -172, -170, -169, -167, -166, -165, -163, -162, -160, -159, -158, -156, -155, -153, -152, -151, -149, -148, -146, -145, -144, -142, -141, -139, -138, -137, -135, -134, -132, -131, -130, -128, -127, -125, -124, -123, -121, -120, -118, -117, -115, -114, -113, -111, -110, -108, -107, -106, -104, -103, -101, -100, -99, -97, -96, -94, -93, -92, -90, -89, -87, -86, -85, -83, -82, -80, -79, -78, -76, -75, -73, -72, -71, -69, -68, -66, -65, -64, -62, -61, -59, -58, -57, -55, -54, -52, -51, -50, -48, -47, -45, -44, -43, -41, -40, -38, -37, -36, -34, -33, -31, -30, -29, -27, -26, -24, -23, -22, -20, -19, -17, -16, -15, -13, -12, -10, -9, -8, -6, -5, -3, -2, 0, 1, 2, 4, 5, 7, 8, 9, 11, 12, 14, 15, 16, 18, 19, 21, 22, 23, 25, 26, 28, 29, 30, 32, 33, 35, 36, 37, 39, 40, 42, 43, 44, 46, 47, 49, 50, 51, 53, 54, 56, 57, 58, 60, 61, 63, 64, 65, 67, 68, 70, 71, 72, 74, 75, 77, 78, 79, 81, 82, 84, 85, 86, 88, 89, 91, 92, 93, 95, 96, 98, 99, 100, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 124, 126, 127, 129, 130, 131, 133, 134, 136, 137, 138, 140, 141, 143, 144, 145, 147, 148, 150, 151, 152, 154, 155, 157, 158, 159, 161, 162, 164, 165, 166, 168, 169, 171, 172, 173, 175, 176, 178 };
static int Table_fv2[256] = { -92, -91, -91, -90, -89, -88, -88, -87, -86, -86, -85, -84, -83, -83, -82, -81, -81, -80, -79, -78, -78, -77, -76, -76, -75, -74, -73, -73, -72, -71, -71, -70, -69, -68, -68, -67, -66, -66, -65, -64, -63, -63, -62, -61, -61, -60, -59, -58, -58, -57, -56, -56, -55, -54, -53, -53, -52, -51, -51, -50, -49, -48, -48, -47, -46, -46, -45, -44, -43, -43, -42, -41, -41, -40, -39, -38, -38, -37, -36, -36, -35, -34, -33, -33, -32, -31, -31, -30, -29, -28, -28, -27, -26, -26, -25, -24, -23, -23, -22, -21, -21, -20, -19, -18, -18, -17, -16, -16, -15, -14, -13, -13, -12, -11, -11, -10, -9, -8, -8, -7, -6, -6, -5, -4, -3, -3, -2, -1, 0, 0, 1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12, 12, 13, 14, 15, 15, 16, 17, 17, 18, 19, 20, 20, 21, 22, 22, 23, 24, 25, 25, 26, 27, 27, 28, 29, 30, 30, 31, 32, 32, 33, 34, 35, 35, 36, 37, 37, 38, 39, 40, 40, 41, 42, 42, 43, 44, 45, 45, 46, 47, 47, 48, 49, 50, 50, 51, 52, 52, 53, 54, 55, 55, 56, 57, 57, 58, 59, 60, 60, 61, 62, 62, 63, 64, 65, 65, 66, 67, 67, 68, 69, 70, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 77, 78, 79, 80, 80, 81, 82, 82, 83, 84, 85, 85, 86, 87, 87, 88, 89, 90, 90 };
static int Table_fu1[256] = { -44, -44, -44, -43, -43, -43, -42, -42, -42, -41, -41, -41, -40, -40, -40, -39, -39, -39, -38, -38, -38, -37, -37, -37, -36, -36, -36, -35, -35, -35, -34, -34, -33, -33, -33, -32, -32, -32, -31, -31, -31, -30, -30, -30, -29, -29, -29, -28, -28, -28, -27, -27, -27, -26, -26, -26, -25, -25, -25, -24, -24, -24, -23, -23, -22, -22, -22, -21, -21, -21, -20, -20, -20, -19, -19, -19, -18, -18, -18, -17, -17, -17, -16, -16, -16, -15, -15, -15, -14, -14, -14, -13, -13, -13, -12, -12, -11, -11, -11, -10, -10, -10, -9, -9, -9, -8, -8, -8, -7, -7, -7, -6, -6, -6, -5, -5, -5, -4, -4, -4, -3, -3, -3, -2, -2, -2, -1, -1, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41, 42, 42, 42, 43, 43 };
static int Table_fu2[256] = { -227, -226, -224, -222, -220, -219, -217, -215, -213, -212, -210, -208, -206, -204, -203, -201, -199, -197, -196, -194, -192, -190, -188, -187, -185, -183, -181, -180, -178, -176, -174, -173, -171, -169, -167, -165, -164, -162, -160, -158, -157, -155, -153, -151, -149, -148, -146, -144, -142, -141, -139, -137, -135, -134, -132, -130, -128, -126, -125, -123, -121, -119, -118, -116, -114, -112, -110, -109, -107, -105, -103, -102, -100, -98, -96, -94, -93, -91, -89, -87, -86, -84, -82, -80, -79, -77, -75, -73, -71, -70, -68, -66, -64, -63, -61, -59, -57, -55, -54, -52, -50, -48, -47, -45, -43, -41, -40, -38, -36, -34, -32, -31, -29, -27, -25, -24, -22, -20, -18, -16, -15, -13, -11, -9, -8, -6, -4, -2, 0, 1, 3, 5, 7, 8, 10, 12, 14, 15, 17, 19, 21, 23, 24, 26, 28, 30, 31, 33, 35, 37, 39, 40, 42, 44, 46, 47, 49, 51, 53, 54, 56, 58, 60, 62, 63, 65, 67, 69, 70, 72, 74, 76, 78, 79, 81, 83, 85, 86, 88, 90, 92, 93, 95, 97, 99, 101, 102, 104, 106, 108, 109, 111, 113, 115, 117, 118, 120, 122, 124, 125, 127, 129, 131, 133, 134, 136, 138, 140, 141, 143, 145, 147, 148, 150, 152, 154, 156, 157, 159, 161, 163, 164, 166, 168, 170, 172, 173, 175, 177, 179, 180, 182, 184, 186, 187, 189, 191, 193, 195, 196, 198, 200, 202, 203, 205, 207, 209, 211, 212, 214, 216, 218, 219, 221, 223, 225 };
static bool YV122BGR32Table(unsigned char *pYUV, unsigned char *pRGB32, int width, int height)
{
if (width < 1 || height < 1 || pYUV == NULL || pRGB32 == NULL)
return false;
const long len = width * height;
unsigned char* yData = pYUV;
unsigned char* vData = &yData[len];
unsigned char* uData = &vData[len >> 2];
int rgb[3];
int yIdx, uIdx, vIdx, idx;
int rdif, invgdif, bdif;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
yIdx = i * width + j;
vIdx = (i >> 1) * (width >> 1) + (j >> 1);
uIdx = vIdx;
rdif = Table_fv1[vData[vIdx]];
invgdif = Table_fu1[uData[uIdx]] + Table_fv2[vData[vIdx]];
bdif = Table_fu2[uData[uIdx]];
rgb[0] = yData[yIdx] + bdif;
rgb[1] = yData[yIdx] - invgdif;
rgb[2] = yData[yIdx] + rdif;
for (int k = 0; k < 3; k++) {
idx = (i * width + j) * 4 + k;
if (rgb[k] >= 0 && rgb[k] <= 255)
pRGB32[idx] = rgb[k];
else
pRGB32[idx] = (rgb[k] < 0) ? 0 : 255;
}
}
}
return true;
}
static void copyFrame(const char *src, char *dest, const int width, int height, const int stride_src, const int stride_dest) {
const int h8 = height % 8;
for (int i = 0; i < h8; i++) {
memcpy(dest, src, width);
dest += stride_dest; src += stride_src;
}
for (int i = 0; i < height; i += 8) {
memcpy(dest, src, width);
dest += stride_dest; src += stride_src;
memcpy(dest, src, width);
dest += stride_dest; src += stride_src;
memcpy(dest, src, width);
dest += stride_dest; src += stride_src;
memcpy(dest, src, width);
dest += stride_dest; src += stride_src;
memcpy(dest, src, width);
dest += stride_dest; src += stride_src;
memcpy(dest, src, width);
dest += stride_dest; src += stride_src;
memcpy(dest, src, width);
dest += stride_dest; src += stride_src;
memcpy(dest, src, width);
dest += stride_dest; src += stride_src;
}
}
static int copyToSurface(char *rgb32, int width, int height, ANativeWindow *window)
{
ANativeWindow_Buffer buffer;
if (ANativeWindow_lock(window, &buffer, NULL) == 0) {
const char *src = rgb32;
const int src_w = width * 4;
const int src_step = width * 4;
char *dest = (char *)buffer.bits;
const int dest_w = buffer.width * 4;
const int dest_step = buffer.stride * 4;
const int w = src_w < dest_w ? src_w : dest_w;
const int h = height < buffer.height ? height : buffer.height;
copyFrame(src, dest, w, h, src_step, dest_step);
ANativeWindow_unlockAndPost(window);
}
return 1;
}
static void yv122Nv21(char *yv12, char *nv21, int width, int height)
{
int frameSize = width * height;
memcpy(nv21, yv12, frameSize);
nv21 += frameSize;
yv12 += frameSize;
int halfWidth = width / 2;
int halfHeight = height / 2;
int quadFrame = halfWidth * halfHeight;
for (int i = 0; i < halfHeight; i++) {
for (int j = 0; j < halfWidth; j++) {
*nv21++ = *(yv12 + i * halfWidth + j);
*nv21++ = *(yv12 + quadFrame + i * halfWidth + j);
}
}
}
int EuhatRtspOp::previewProc()
{
JavaVM *vm = getVM();
JNIEnv *env;
vm->AttachCurrentThread(&env, NULL);
struct timeval tv;
gettimeofday(&tv, NULL);
int lastStampMs = tv.tv_usec / 1000;
while (!isTimerThreadExiting_) {
int intervalRuleMs = 1000 / displayFps_;
char *frame = NULL;
{
WhMutexGuard guard(&mutexPreview_);
if (listPreviewFrame_.size() > 0) {
frame = listPreviewFrame_.front();
listPreviewFrame_.pop_front();
} else {
whCondWait(&syncPreview_, &mutexPreview_);
}
}
if (NULL == frame)
continue;
int width = *(int *)frame;
int height = *(int *)(frame + 4);
int sizeYUV = *(int *)(frame + 8);
if (winPreviewNeedDraw_) {
char *rgb32Buf = (char *)rgbMemPool_->alloc(width * height * 4);
YV122BGR32Table((unsigned char *)frame + 4 * 3, (unsigned char *)rgb32Buf, width, height);
{
WhMutexGuard guard(&mutexPreviewDraw_);
if (NULL != winPreview_) {
copyToSurface(rgb32Buf, width, height, winPreview_);
}
}
rgbMemPool_->dealloc(rgb32Buf);
}
if (pixelFormat_ == 2) {
char *frameTmp = (char *)yuvMemPool_->alloc(sizeYUV + 4 * 3);
*(int *)frameTmp = width;
*(int *)(frameTmp + 4) = height;
*(int *)(frameTmp + 8) = sizeYUV;
yv122Nv21(frame + 4 * 3, frameTmp + 4 * 3, width, height);
yuvMemPool_->dealloc(frame);
frame = frameTmp;
}
{
WhMutexGuard guard(&mutexFrameCallback_);
listFrameCallback_.push_back(frame);
pthread_cond_signal(&syncFrameCallback_);
while (listFrameCallback_.size() > 1) {
char *frameOld = listFrameCallback_.front();
listFrameCallback_.pop_front();
yuvMemPool_->dealloc(frameOld);
}
}
gettimeofday(&tv, NULL);
int curStampMs = tv.tv_usec / 1000;
int intervalMs = curStampMs - lastStampMs;
if (intervalMs < 0)
intervalMs += 1000;
int toSleepMs = intervalRuleMs - intervalMs;
if (toSleepMs > 0)
whSleepMs(toSleepMs);
lastStampMs = curStampMs;
}
vm->DetachCurrentThread();
return 1;
}
static int decoderCallback(char *outBuf, void *context)
{
EuhatRtspOp *euhatRtsp = (EuhatRtspOp *)context;
return euhatRtsp->decodingCb(outBuf);
}
int EuhatRtspOp::connect2(const char *url)
{
DBG(("euhat rtsp op connect in.\n"));
int iRet = -1;
if (isConnected_) {
return -1;
}
decoder_->init(decoderCallback, this);
winPreviewNeedDraw_ = decoder_->updateSurface(winPreview_);
rtspUrl_ = url;
iRet = initRtspSource();
if (iRet < 0) {
DBG(("euhat rtsp init rtsp source failed.\n"));
informStatus(EUHAT_STATUS_RTSP_CONNECT_FAILED, 0, 0);
decoder_->fini();
return -2;
}
/*
{
WhMutexGuard guard(&mutexHasResolution_);
whCondWait(&syncHasResolution_, &mutexHasResolution_);
}
DBG(("euhat rtsp get width %d, height %d.\n", videoWidth_, videoHeight_));
if (!hasResolution_ || videoWidth_ == 0 || videoHeight_ == 0) {
finiRtspSource();
return -3;
}
*/
startWorkThread();
struct timeval tv;
gettimeofday(&tv, NULL);
rtspLastGetTime_ = tv.tv_sec * 1000 + tv.tv_usec / 1000;
isConnected_ = 1;
return 0;
}
int EuhatRtspOp::decodingCb(char *yuv)
{
WhMutexGuard guard(&mutexPreview_);
if (!hasFirstFrame_) {
hasFirstFrame_ = 1;
while (listPreviewFrame_.size() > 0) {
char *frame = listPreviewFrame_.front();
listPreviewFrame_.pop_front();
yuvMemPool_->dealloc(frame);
}
}
if (listPreviewFrame_.size() > displayBufCount_) {
informStatus(EUHAT_STATUS_DISPLAY_QUEUE_TOO_LARGE, listPreviewFrame_.size() - displayBufCount_, 0);
while (listPreviewFrame_.size() > 0) {
char *frame = listPreviewFrame_.front();
listPreviewFrame_.pop_front();
yuvMemPool_->dealloc(frame);
}
}
listPreviewFrame_.push_back(yuv);
pthread_cond_signal(&syncPreview_);
return 1;
}
int EuhatRtspOp::close2()
{
if (!isConnected_)
return -1;
isConnected_ = 0;
stopWorkThread();
finiRtspSource();
decoder_->fini();
hasResolution_ = 0;
hasFirstFrame_ = 0;
videoWidth_ = videoHeight_ = 0;
return 0;
}
int EuhatRtspOp::startPreview()
{
DBG(("euhat rtsp start preview.\n"));
isPlaying_ = 1;
return 0;
}
int EuhatRtspOp::stopPreview()
{
DBG(("euhat rtsp stop preview.\n"));
isPlaying_ = 0;
return 0;
}
int EuhatRtspOp::setPreviewDisplay(ANativeWindow *nativeWin)
{
WhMutexGuard guard(&mutexPreviewDraw_);
if (winPreview_ != nativeWin) {
if (winPreview_)
ANativeWindow_release(winPreview_);
winPreview_ = nativeWin;
if (winPreview_) {
ANativeWindow_setBuffersGeometry(winPreview_,
1920, 1080, WINDOW_FORMAT_RGBA_8888);
}
}
return 0;
}
int EuhatRtspOp::setStatusCallback(JNIEnv *env, jobject statusCallbackObj)
{
WhMutexGuard guard(&mutexStatusCallbackCall_);
if (!env->IsSameObject(objStatusCallback_, statusCallbackObj)) {
DBG(("register status callback.\n"));
methodsStatusCallback_.onStatus = NULL;
if (objStatusCallback_) {
env->DeleteGlobalRef(objStatusCallback_);
}
objStatusCallback_ = statusCallbackObj;
if (statusCallbackObj) {
jclass clazz = env->GetObjectClass(statusCallbackObj);
if (clazz) {
methodsStatusCallback_.onStatus = env->GetMethodID(clazz,
"onStatus", "(III)V");
} else {
DBG(("failed to get IStatusCallback object class.\n"));
env->DeleteGlobalRef(statusCallbackObj);
objStatusCallback_ = statusCallbackObj = NULL;
return -1;
}
env->ExceptionClear();
if (!methodsStatusCallback_.onStatus) {
DBG(("can't find IStatusCallback#onStatus.\n"));
env->DeleteGlobalRef(statusCallbackObj);
objStatusCallback_ = statusCallbackObj = NULL;
}
}
} else {
env->DeleteGlobalRef(statusCallbackObj);
}
return 0;
}
int EuhatRtspOp::setFrameCallback(JNIEnv *env, jobject frameCallbackObj, int pixelFormat)
{
WhMutexGuard guard(&mutexFrameCallbackCall_);
pixelFormat_ = pixelFormat;
if (!env->IsSameObject(objFrameCallback_, frameCallbackObj)) {
DBG(("register frame callback.\n"));
methodsFrameCallback_.onFrame = NULL;
if (objFrameCallback_) {
env->DeleteGlobalRef(objFrameCallback_);
}
objFrameCallback_ = frameCallbackObj;
if (frameCallbackObj) {
jclass clazz = env->GetObjectClass(frameCallbackObj);
if (clazz) {
methodsFrameCallback_.onFrame = env->GetMethodID(clazz,
"onFrame", "(Ljava/nio/ByteBuffer;II)V");
} else {
DBG(("failed to get IFrameCallback object class.\n"));
env->DeleteGlobalRef(frameCallbackObj);
objFrameCallback_ = frameCallbackObj = NULL;
return -1;
}
env->ExceptionClear();
if (!methodsFrameCallback_.onFrame) {
DBG(("can't find IFrameCallback#onFrame.\n"));
env->DeleteGlobalRef(frameCallbackObj);
objFrameCallback_ = frameCallbackObj = NULL;
}
}
} else {
env->DeleteGlobalRef(frameCallbackObj);
}
return 0;
}
static jlong setField_long(JNIEnv *env, jobject java_obj, const char *field_name, jlong val) {
jclass clazz = env->GetObjectClass(java_obj);
jfieldID field = env->GetFieldID(clazz, field_name, "J");
if (field)
env->SetLongField(java_obj, field, val);
else {
DBG(("setField_long, field '%s' not found.\n", field_name));
}
#ifdef ANDROID_NDK
env->DeleteLocalRef(clazz);
#endif
return val;
}
int EuhatRtspOp::statusCallbackProc()
{
JavaVM *vm = getVM();
JNIEnv *env;
vm->AttachCurrentThread(&env, NULL);
while (!isTimerThreadExiting_) {
StatusCallbackOnStatusParams frame;
frame.type = 0;
{
WhMutexGuard guard(&mutexStatusCallback_);
if (listStatusCallbackOnStatus_.size() > 0) {
frame = listStatusCallbackOnStatus_.front();
listStatusCallbackOnStatus_.pop_front();
}
}
if (0 == frame.type) {
whSleepMs(10);
continue;
}
{
WhMutexGuard guard(&mutexStatusCallbackCall_);
if (objStatusCallback_ != NULL && methodsStatusCallback_.onStatus != NULL) {
env->CallVoidMethod(objStatusCallback_, methodsStatusCallback_.onStatus, frame.type, frame.param0, frame.param1);
env->ExceptionClear();
} else {
DBG(("status callback not registered.\n"));
}
}
}
vm->DetachCurrentThread();
return 1;
}
static jlong nativeCreate(JNIEnv *env, jobject thiz) {
EuhatRtspOp *euhatRtsp = new EuhatRtspOp();
setField_long(env, thiz, "mNativePtr", reinterpret_cast<jlong>(euhatRtsp));
return reinterpret_cast<jlong>(euhatRtsp);
}
static void nativeDestroy(JNIEnv *env, jobject thiz, jlong rtspObj) {
setField_long(env, thiz, "mNativePtr", 0);
EuhatRtspOp *euhatRtsp = reinterpret_cast<EuhatRtspOp *>(rtspObj);
delete euhatRtsp;
}
int EuhatRtspOp::frameCallbackProc()
{
JavaVM *vm = getVM();
JNIEnv *env;
vm->AttachCurrentThread(&env, NULL);
while (!isTimerThreadExiting_) {
char *frame = NULL;
{
WhMutexGuard guard(&mutexFrameCallback_);
if (listFrameCallback_.size() > 0) {
frame = listFrameCallback_.front();
listFrameCallback_.pop_front();
} else {
whCondWait(&syncFrameCallback_, &mutexFrameCallback_);
}
}
if (NULL == frame)
continue;
{
WhMutexGuard guard(&mutexFrameCallbackCall_);
if (objFrameCallback_ != NULL && methodsFrameCallback_.onFrame != NULL) {
int width = *(int *)frame;
int height = *(int *)(frame + 4);
int sizeYUV = *(int *)(frame + 8);
jobject buf = env->NewDirectByteBuffer(frame + 4 * 3, sizeYUV);
env->CallVoidMethod(objFrameCallback_, methodsFrameCallback_.onFrame, buf, width, height);
env->ExceptionClear();
env->DeleteLocalRef(buf);
}
}
yuvMemPool_->dealloc(frame);
}
vm->DetachCurrentThread();
return 1;
}
int EuhatRtspOp::informStatus(int type, int param0, int param1)
{
WhMutexGuard guard(&mutexStatusCallback_);
StatusCallbackOnStatusParams frame;
frame.type = type;
frame.param0 = param0;
frame.param1 = param1;
listStatusCallbackOnStatus_.push_back(frame);
while (listStatusCallbackOnStatus_.size() > 1000) {
listStatusCallbackOnStatus_.pop_front();
}
return 1;
}
int EuhatRtspOp::connect(const char *url, int rtspTimeOut, int rtspFlag, int reconnectTimeOut, int displayFps, int displayBufCount)
{
rtspUseFlags_ = 1;
rtspFlags_ = rtspFlag;
rtspTimeOut_ = rtspTimeOut;
reconnectTimeOut_ = reconnectTimeOut;
displayFps_ = displayFps;
displayBufCount_ = displayBufCount;
postMessageStr(1, url);
DBG(("euhat rtsp connect, reconnect time out %d, display fps %d, buf count %d.\n", reconnectTimeOut_, displayFps_, displayBufCount_));
return 0;
}
int EuhatRtspOp::close()
{
DBG(("euhat rtsp op send close.\n"));
postMessageInt(2, 0);
return 0;
}
int EuhatRtspOp::onTimer()
{
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned long nowTime = tv.tv_sec * 1000 + tv.tv_usec / 1000;
unsigned long interval;
if (nowTime < rtspLastGetTime_) {
interval = ((unsigned long)-1) - rtspLastGetTime_ + nowTime;
} else {
interval = nowTime - rtspLastGetTime_;
}
if (interval > reconnectTimeOut_) {
rtspLastGetTime_ = nowTime;
{
WhMutexGuard guard(&mutexMessage_);
for (list<MessageParams>::iterator it = listMessage_.begin(); it != listMessage_.end(); it++) {
if (it->type == 4) {
return 1;
}
}
}
DBG(("on timer post reconnect message.\n"));
postMessageInt(4, 0);
}
return 1;
}
static jint nativeConnect(JNIEnv *env, jobject thiz, jlong rtspObj, jstring jstrUrl, jint rtspTimeOut, jint rtspFlag, jint reconnectTimeOut, jint displayFps, jint displayBufCount) {
int result = JNI_ERR;
EuhatRtspOp *euhatRtsp = reinterpret_cast<EuhatRtspOp *>(rtspObj);
const char *url = env->GetStringUTFChars(jstrUrl, JNI_FALSE);
result = euhatRtsp->connect(url, rtspTimeOut, rtspFlag, reconnectTimeOut, displayFps, displayBufCount);
env->ReleaseStringUTFChars(jstrUrl, url);
return result;
}
static jint nativeClose(JNIEnv *env, jobject thiz, jlong rtspObj) {
int result = JNI_ERR;
EuhatRtspOp *euhatRtsp = reinterpret_cast<EuhatRtspOp *>(rtspObj);
result = euhatRtsp->close();
return result;
}
static jint nativeStartPreview(JNIEnv *env, jobject thiz, jlong rtspObj) {
EuhatRtspOp *euhatRtsp = reinterpret_cast<EuhatRtspOp *>(rtspObj);
return euhatRtsp->startPreview();
}
static jint nativeStopPreview(JNIEnv *env, jobject thiz, jlong rtspObj) {
EuhatRtspOp *euhatRtsp = reinterpret_cast<EuhatRtspOp *>(rtspObj);
return euhatRtsp->stopPreview();
}
int EuhatRtspOp::timerProc()
{
while (!isTimerThreadExiting_) {
whSleepMs(5);
if (needReconnecting_) {
{
WhMutexGuard guard(&mutexMessage_);
int hasSent = 0;
for (list<MessageParams>::iterator it = listMessage_.begin(); it != listMessage_.end(); it++) {
if (it->type == 3) {
hasSent = 1;
break;
}
}
if (hasSent) {
continue;
}
}
postMessageInt(3, 0);
}
}
return 1;
}
static jint nativeSetPreviewDisplay(JNIEnv *env, jobject thiz, jlong rtspObj, jobject jSurface) {
jint result = JNI_ERR;
EuhatRtspOp *euhatRtsp = reinterpret_cast<EuhatRtspOp *>(rtspObj);
ANativeWindow *previewWindow = jSurface ? ANativeWindow_fromSurface(env, jSurface) : NULL;
result = euhatRtsp->setPreviewDisplay(previewWindow);
return result;
}
static jint nativeSetStatusCallback(JNIEnv *env, jobject thiz,
jlong rtspObj, jobject jIStatusCallback) {
jint result = JNI_ERR;
EuhatRtspOp *euhatRtsp = reinterpret_cast<EuhatRtspOp *>(rtspObj);
jobject statusCallbackObj = env->NewGlobalRef(jIStatusCallback);
result = euhatRtsp->setStatusCallback(env, statusCallbackObj);
return result;
}
static jint nativeSetFrameCallback(JNIEnv *env, jobject thiz,
jlong rtspObj, jobject jIFrameCallback, jint pixelFormat) {
jint result = JNI_ERR;
EuhatRtspOp *euhatRtsp = reinterpret_cast<EuhatRtspOp *>(rtspObj);
jobject frameCallbackObj = env->NewGlobalRef(jIFrameCallback);
result = euhatRtsp->setFrameCallback(env, frameCallbackObj, pixelFormat);
return result;
}
int EuhatRtspOp::messageProc()
{
JavaVM *vm = getVM();
JNIEnv *env;
vm->AttachCurrentThread(&env, NULL);
while (1) {
MessageParams msg;
{
WhMutexGuard guard(&mutexMessage_);
if (listMessage_.size() > 0) {
msg = listMessage_.front();
listMessage_.pop_front();
} else {
msg.type = -1;
}
}
if (msg.type == -1) {
whSleepMs(10);
continue;
}
if (msg.type == 1) {
DBG(("manually connect [%s].\n", msg.str.c_str()));
connect3(msg.str.c_str());
} else if (msg.type == 2) {
DBG(("manually close.\n"));
close3();
} else if (msg.type == 3) {
onTimer();
} else if (msg.type == 4) {
informStatus(EUHAT_STATUS_RTSP_RECONNECTING, 0, 0);
string url = rtspUrl_;
close2();
connect2(url.c_str());
} else if (msg.type == 0) {
close2();
break;
}
}
vm->DetachCurrentThread();
return 1;
}
static JNINativeMethod methods[] = {
{ "nativeCreate", "()J", (void *)nativeCreate },
{ "nativeDestroy", "(J)V", (void *)nativeDestroy },
{ "nativeConnect", "(JLjava/lang/String;IIIII)I", (void *)nativeConnect },
{ "nativeClose", "(J)I", (void *)nativeClose },
{ "nativeStartPreview", "(J)I", (void *)nativeStartPreview },
{ "nativeStopPreview", "(J)I", (void *)nativeStopPreview },
{ "nativeSetPreviewDisplay", "(JLandroid/view/Surface;)I", (void *)nativeSetPreviewDisplay },
{ "nativeSetStatusCallback", "(JLcom/euhat/rtsp/euhatrtsplib/IStatusCallback;)I", (void *)nativeSetStatusCallback },
{ "nativeSetFrameCallback", "(JLcom/euhat/rtsp/euhatrtsplib/IFrameCallback;I)I", (void *)nativeSetFrameCallback },
};
#define NUM_ARRAY_ELEMENTS(p) ((int) sizeof(p) / sizeof(p[0]))
jint registerNativeMethods(JNIEnv* env, const char *class_name, JNINativeMethod *methods, int num_methods) {
int result = 0;
jclass clazz = env->FindClass(class_name);
if (clazz) {
int result = env->RegisterNatives(clazz, methods, num_methods);
if (result < 0) {
DBG(("registerNativeMethods failed, class is %s.\n", class_name));
}
} else {
DBG(("registerNativeMethods: class '%s' not found.\n", class_name));
}
return result;
}
int registerEuhatRtsp(JNIEnv *env) {
if (registerNativeMethods(env,
"com/euhat/rtsp/euhatrtsplib/EuhatRtspPlayer",
methods, NUM_ARRAY_ELEMENTS(methods)) < 0) {
return -1;
}
return 0;
}
static JavaVM *savedVm;
void setVM(JavaVM *vm) {
savedVm = vm;
}
JavaVM *getVM() {
return savedVm;
}
JNIEnv *getEnv() {
JNIEnv *env = NULL;
if (savedVm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
env = NULL;
}
return env;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
DBG(("I'm loaded==========================\n"));
JNIEnv *env;
if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR;
}
int result = registerEuhatRtsp(env);
setVM(vm);
return JNI_VERSION_1_6;
}
| 32.216598 | 1,316 | 0.602045 | [
"object"
] |
9f792d821a2a2631c53d0f5c9e3b31e1dd07c0d7 | 943 | cc | C++ | Author/Precious_Pots_of_LPU/main.cc | aniruddha0pandey/Code-Archive | f347aa17ef3f43d6b5a3ce95f9be25d2a6cb6965 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | Author/Precious_Pots_of_LPU/main.cc | aniruddha0pandey/Code-Archive | f347aa17ef3f43d6b5a3ce95f9be25d2a6cb6965 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | Author/Precious_Pots_of_LPU/main.cc | aniruddha0pandey/Code-Archive | f347aa17ef3f43d6b5a3ce95f9be25d2a6cb6965 | [
"Apache-2.0",
"CC-BY-4.0"
] | 1 | 2020-08-16T05:48:55.000Z | 2020-08-16T05:48:55.000Z | #include <bits/stdc++.h>
std::vector<int>
arrange ( std::vector<int> pots, std::vector<int> broken_pots ) {
std::vector<int> arranged_pots(pots);
for ( int i = 0; i < broken_pots.size(); ++i ) {
for ( int j = 0; j < pots.size(); ++j ) {
if ( broken_pots[i] == pots[j] ) {
pots.erase(pots.begin() + j);
pots.push_back(broken_pots[i]);
break;
}
}
}
return pots;
}
int
main ( void ) {
int T, N, M, input;
std::cin >> T;
while ( T-- ) {
std::vector<int> pots, broken_pots, arranged_pots;
std::vector<int>::iterator it;
std::cin >> N >> M;
for ( int i = 0; i < N; ++i ) {
std::cin >> input;
pots.push_back(input);
}
for ( int i = 0; i < M; ++i ) {
std::cin >> input;
broken_pots.push_back(input);
}
arranged_pots = arrange(pots, broken_pots);
for ( it = arranged_pots.begin();
it != arranged_pots.end(); ++it ) {
std::cout << *it << " ";
} puts("");
}
return 0;
}
| 21.431818 | 65 | 0.545069 | [
"vector"
] |
9f84e3deecbe6287cd6ac212de2b4910ee2f6722 | 3,004 | cpp | C++ | examples/distributed-map/entry-processor/main.cpp | yuce/hazelcast-cpp-client | 027d56df46d770d8e2225693e4bbc91703451757 | [
"Apache-2.0"
] | 78 | 2015-10-23T13:50:12.000Z | 2021-12-17T11:22:58.000Z | examples/distributed-map/entry-processor/main.cpp | yuce/hazelcast-cpp-client | 027d56df46d770d8e2225693e4bbc91703451757 | [
"Apache-2.0"
] | 949 | 2015-10-26T12:18:38.000Z | 2022-03-31T15:49:08.000Z | examples/distributed-map/entry-processor/main.cpp | yuce/hazelcast-cpp-client | 027d56df46d770d8e2225693e4bbc91703451757 | [
"Apache-2.0"
] | 49 | 2015-10-23T13:51:52.000Z | 2021-09-01T00:26:45.000Z | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. 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 <hazelcast/client/hazelcast_client.h>
#include "employee.h"
int main() {
auto hz = hazelcast::new_client().get();
auto employees = hz.get_map("employees").get();
employees->put("John", employee{1000}).get();
employees->put("Mark", employee{1000}).get();
employees->put("Spencer", employee{1000}).get();
employee_raise_entry_processor processor;
auto result = employees->execute_on_entries<std::string, int, employee_raise_entry_processor>(
employee_raise_entry_processor{}).get();
std::cout << "The result after employees.execute_on_entries call is:" << std::endl;
for (auto &entry : result) {
std::cout << entry.first << " salary: " << *entry.second << std::endl;
}
result = employees->execute_on_keys<std::string, int, employee_raise_entry_processor>({"John", "Spencer"},
employee_raise_entry_processor{}).get();
std::cout << "The result after employees.executeOnKeys call is:" << std::endl;
for (auto &entry : result) {
std::cout << entry.first << " salary: " << *entry.second << std::endl;
}
// use submitToKey api
auto future = employees->submit_to_key<std::string, int, employee_raise_entry_processor>("Mark", employee_raise_entry_processor{});
// wait for 1 second
if (future.wait_for(boost::chrono::seconds(1)) == boost::future_status::ready) {
std::cout << "Got the result of submitToKey in 1 second for Mark" << " new salary: " << *future.get() << std::endl;
} else {
std::cout << "Could not get the result of submitToKey in 1 second for Mark" << std::endl;
}
// multiple futures
std::vector<boost::future<boost::optional<int>>> allFutures;
// test putting into a vector of futures
future = employees->submit_to_key<std::string, int, employee_raise_entry_processor>(
"Mark", processor);
allFutures.push_back(std::move(future));
allFutures.push_back(employees->submit_to_key<std::string, int, employee_raise_entry_processor>(
"John", employee_raise_entry_processor{}));
boost::wait_for_all(allFutures.begin(), allFutures.end());
for (auto &f : allFutures) {
std::cout << "Result:" << *f.get() << std::endl;
}
std::cout << "Finished" << std::endl;
return 0;
}
| 39.526316 | 135 | 0.653129 | [
"vector"
] |
9f87c151a3480fc3d4add0edc264293bcf7152f5 | 3,895 | cpp | C++ | lib/src/calibration/calibrationOnlineAlgorithm.cpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 182 | 2019-04-19T12:38:30.000Z | 2022-03-20T16:48:20.000Z | lib/src/calibration/calibrationOnlineAlgorithm.cpp | doymcc/stitchEm | 20693a55fa522d7a196b92635e7a82df9917c2e2 | [
"MIT"
] | 107 | 2019-04-23T10:49:35.000Z | 2022-03-02T18:12:28.000Z | lib/src/calibration/calibrationOnlineAlgorithm.cpp | doymcc/stitchEm | 20693a55fa522d7a196b92635e7a82df9917c2e2 | [
"MIT"
] | 59 | 2019-06-04T11:27:25.000Z | 2022-03-17T23:49:49.000Z | // Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#include "calibrationOnlineAlgorithm.hpp"
#include "calibration.hpp"
#include "cvImage.hpp"
#include "calibrationProgress.hpp"
#include "core/controllerInputFrames.hpp"
#include "util/registeredAlgo.hpp"
#include "cuda/memory.hpp"
#include "gpu/surface.hpp"
#include "libvideostitch/logging.hpp"
#include "libvideostitch/parse.hpp"
#include "libvideostitch/rigDef.hpp"
#include <memory>
#include <functional>
namespace VideoStitch {
namespace Calibration {
namespace {
Util::RegisteredAlgo<CalibrationOnlineAlgorithm, true> registeredOnline("calibration");
}
const char* CalibrationOnlineAlgorithm::docString =
"An algorithm that calibrates a panoramic multi-camera system using overlap zones between images\n";
CalibrationOnlineAlgorithm::CalibrationOnlineAlgorithm(const Ptv::Value* config) : CalibrationAlgorithmBase(config) {}
CalibrationOnlineAlgorithm::~CalibrationOnlineAlgorithm() {}
Status CalibrationOnlineAlgorithm::retrieveImages(
RigCvImages& rig, const Core::PanoDefinition& pano,
const std::vector<std::pair<videoreaderid_t, GPU::Surface&>>& frames) const {
/*Create rig of n list*/
rig.clear();
rig.resize(pano.numVideoInputs());
/* With non-video inputs, assume we can have gaps between camid and inputid */
auto videoInputs = pano.getVideoInputs();
for (auto it = frames.begin(); it != frames.end(); ++it) {
int camid = it->first;
if (camid >= (int)pano.numInputs() || camid >= (int)videoInputs.size()) {
return {Origin::CalibrationAlgorithm, ErrType::InvalidConfiguration,
"Invalid input configuration, could not retrieve calibration frames"};
}
std::shared_ptr<CvImage> cvinput;
// Get the size of the current image
const Core::InputDefinition& idef = videoInputs[camid];
const int width = (int)idef.getWidth();
const int height = (int)idef.getHeight();
FAIL_RETURN(loadInputImage(cvinput, it->second, width, height));
rig[camid].push_back(cvinput);
}
return Status::OK();
}
Potential<Ptv::Value> CalibrationOnlineAlgorithm::onFrame(
Core::PanoDefinition& pano, std::vector<std::pair<videoreaderid_t, GPU::Surface&>>& frames, mtime_t /*date*/,
FrameRate /*frameRate*/, Util::OpaquePtr** ctx) {
/*Validate configuration*/
if (!calibConfig.isValid()) {
// TODOLATERSTATUS get output from CalibrationConfig parsing
return {Origin::CalibrationAlgorithm, ErrType::InvalidConfiguration, "Invalid calibration configuration"};
}
if (calibConfig.getRigPreset()->getRigCameraDefinitionCount() != (size_t)pano.numVideoInputs()) {
return {Origin::CalibrationAlgorithm, ErrType::InvalidConfiguration,
"Calibration camera presets not matching the number of video inputs"};
}
/*
* Retrieve the control point manager, passed as an opaque pointer from the client
* or create a new one if no cp manager was passed
*/
CalibrationProgress calibProgress(nullptr, getProgressUnits(pano.numVideoInputs(), 1));
/*Perform calibration*/
std::unique_ptr<Calibration, std::function<void(Calibration*)>> calibrationAlgorithm;
if (ctx == nullptr) {
calibrationAlgorithm = std::unique_ptr<Calibration, std::function<void(Calibration*)>>(
new Calibration(calibConfig, calibProgress), [](Calibration* data) { delete data; });
} else {
if (*ctx == nullptr) {
*ctx = new Calibration(calibConfig, calibProgress);
}
calibrationAlgorithm = std::unique_ptr<Calibration, std::function<void(Calibration*)>>(
dynamic_cast<Calibration*>(*ctx), [](Calibration*) {});
}
RigCvImages rig;
if (!calibConfig.isApplyingPresetsOnly()) {
/*Load images onto cpu*/
FAIL_RETURN(retrieveImages(rig, pano, frames));
}
return calibrationAlgorithm->process(pano, rig);
}
} // namespace Calibration
} // namespace VideoStitch
| 34.469027 | 118 | 0.724775 | [
"vector"
] |
9f8e618ba280069e1629c2a01f52a3f12d84298c | 2,830 | cpp | C++ | src/caffe/layers/duplicate_layer.cpp | schnaitterm/caffe | 26c57bb54ec3aafcfe3acc6004053ac8a4a3c4d2 | [
"Intel",
"BSD-2-Clause"
] | 14 | 2018-11-02T22:41:14.000Z | 2020-05-17T09:32:00.000Z | src/caffe/layers/duplicate_layer.cpp | schnaitterm/caffe | 26c57bb54ec3aafcfe3acc6004053ac8a4a3c4d2 | [
"Intel",
"BSD-2-Clause"
] | 2 | 2018-08-01T08:28:31.000Z | 2018-10-01T15:34:36.000Z | src/caffe/layers/duplicate_layer.cpp | schnaitterm/caffe | 26c57bb54ec3aafcfe3acc6004053ac8a4a3c4d2 | [
"Intel",
"BSD-2-Clause"
] | 5 | 2018-08-25T19:51:03.000Z | 2020-05-17T09:39:19.000Z | #include <vector>
#include "caffe/layers/duplicate_layer.hpp"
namespace caffe {
template<typename Dtype>
void DuplicateLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
DuplicateParameter param = this->layer_param_.duplicate_param();
duplicates_ = param.duplicates();
CHECK_EQ(bottom[0]->num_axes(), 4) << "Blob must be dim.";
}
template<typename Dtype>
void DuplicateLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
vector<int> out_shape;
out_shape.push_back(bottom[0]->shape(0) * duplicates_); // Batch size.
out_shape.push_back(bottom[0]->shape(1)); // Channels.
out_shape.push_back(bottom[0]->shape(2)); // Depth.
out_shape.push_back(bottom[0]->shape(3)); // Height.
top[0]->Reshape(out_shape);
}
template<typename Dtype>
void DuplicateLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
for (int index = 0; index < bottom[0]->count(); ++index) {
int num = index;
const int w = num % bottom[0]->shape(3);
num = num / bottom[0]->shape(3);
const int h = num % bottom[0]->shape(2);
num = num / bottom[0]->shape(2);
const int c = num % bottom[0]->shape(1);
num = num / bottom[0]->shape(1);
for (int i = 0; i < duplicates_; ++i) {
const int out_index = (num * duplicates_ + i) * top[0]->count(1)
+ c * top[0]->count(2) + h * top[0]->count(3) + w;
top_data[out_index] = bottom_data[index];
}
}
}
template<typename Dtype>
void DuplicateLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom) {
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
const Dtype* top_diff = top[0]->cpu_diff();
for (int index = 0; index < bottom[0]->count(); ++index) {
int num = index;
const int w = num % bottom[0]->shape(3);
num = num / bottom[0]->shape(3);
const int h = num % bottom[0]->shape(2);
num = num / bottom[0]->shape(2);
const int c = num % bottom[0]->shape(1);
num = num / bottom[0]->shape(1);
bottom_diff[index] = 0;
for (int i = 0; i < duplicates_; ++i) {
const int out_index = (num * duplicates_ + i) * top[0]->count(1)
+ c * top[0]->count(2) + h * top[0]->count(3) + w;
bottom_diff[index] += top_diff[out_index];
}
}
}
#ifdef CPU_ONLY
STUB_GPU(DuplicateLayer);
#endif
INSTANTIATE_CLASS(DuplicateLayer);
REGISTER_LAYER_CLASS(Duplicate);
} // namespace caffe
| 35.375 | 80 | 0.5947 | [
"shape",
"vector"
] |
9f9159de96c295e373c8fc7932b112a515ccb2ad | 9,630 | cpp | C++ | src/viewer.cpp | codemusings/reversing-starmada | c77ae51104d6c3a2ddae42749bda4e8899573050 | [
"MIT"
] | null | null | null | src/viewer.cpp | codemusings/reversing-starmada | c77ae51104d6c3a2ddae42749bda4e8899573050 | [
"MIT"
] | null | null | null | src/viewer.cpp | codemusings/reversing-starmada | c77ae51104d6c3a2ddae42749bda4e8899573050 | [
"MIT"
] | null | null | null | #include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
//#define STB_IMAGE_IMPLEMENTATION
//#include <stb_image.h>
#include "model.hpp"
#include "sod.h"
#include "shader.hpp"
#include "viewer.hpp"
#define WIDTH 800
#define HEIGHT 600
static float z_offset = -25.0f;
static float rot_degree = 0.0f;
void vwr_process_input(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) {
z_offset -= 0.1f;
printf("z: %.1f\n", z_offset);
}
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) {
z_offset += 0.1f;
printf("z: %.1f\n", z_offset);
}
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
rot_degree -= 5.0f;
printf("rotation: %f°\n", rot_degree);
}
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
rot_degree += 5.0f;
printf("rotation: %f°\n", rot_degree);
}
}
void vwr_resize_callback(GLFWwindow *window, int width, int height)
{
glViewport(0, 0, width, height);
}
int main(int argc, char *argv[])
{
//if (argc != 2) {
// fprintf(stderr, "Usage: %s <SOD file>\n", argv[0]);
// return 1;
//}
// const char *mdl_filepath = "CDROM/setup/data/SOD/Fentd.SOD";
// const char *img_filepath = "CDROM/setup/data/Textures/RGB/Fentd.jpg";
// const char *node_name = "fentd";
const char *mdl_filepath = "CDROM/setup/data/SOD/Fente.SOD";
const char *img_filepath = "CDROM/setup/data/Textures/RGB/FEntE.tga";
const char *node_name = "fbattle_1";
// const char *mdl_filepath = "CDROM/setup/data/SOD/Borpod9.SOD";
// const char *img_filepath = "CDROM/setup/data/Textures/RGB/Bbuildng.tga";
// const char *node_name = "Borpod9_ultritiumburst";
//FILE *fp = fopen(argv[1], "r");
FILE *fp = fopen(mdl_filepath, "r");
if (!fp) {
fprintf(stderr, "Unable to read input file %s\n", argv[1]);
return 1;
}
SODFile *file = sod_new_file();
sod_read_file(file, fp);
fclose(fp);
SODNode *node = sod_find_node(file->nodes, node_name);
if (node == NULL) {
std::cerr << "Unable to find node" << std::endl;
return 1;
}
Model m(node, img_filepath);
float *vertices = m.getVertices();
//SODNodeDataMesh *data = node->data.mesh;
//int stride = 3 + 3 + 2; // coords + color + tex_coords
//int total_size = 0;
//for (int i = 0; i < data->ngroups; i++) {
// SODVertexLightingGroup *group = data->lighting_groups[i];
// int group_size = 0;
// for (int j = 0; j < group->nfaces; j++) {
// group_size = group->nfaces * 3 * stride;
// }
// total_size += group_size;
//}
//float vertices[total_size];
//int lgroup_offset = 0;
//for (int i = 0; i < data->ngroups; i++) {
// SODVertexLightingGroup *group = data->lighting_groups[i];
// for (int j = 0; j < group->nfaces; j++) {
// // 3 * (3 + 3 + 2) = 24
// int face_offset = lgroup_offset + j * 3 * stride;
// for (int k = 0; k < 3; k++) {
// printf("%d\n", face_offset + k * stride);
// SODFaceVertex *vertex = group->faces[j]->face_vertices[k];
// uint16_t v = vertex->index_vertices;
// uint16_t t = vertex->index_texcoords;
// // coords
// vertices[face_offset + k * stride + 0] = data->vertices[v]->x;
// vertices[face_offset + k * stride + 1] = data->vertices[v]->y;
// vertices[face_offset + k * stride + 2] = data->vertices[v]->z;
// // color
// vertices[face_offset + k * stride + 3] = 1.0f;
// vertices[face_offset + k * stride + 4] = 1.0f;
// vertices[face_offset + k * stride + 5] = 1.0f;
// // texture coords
// vertices[face_offset + k * stride + 6] = data->texcoords[t]->u;
// vertices[face_offset + k * stride + 7] = data->texcoords[t]->v;
// }
// }
// lgroup_offset += group->nfaces * 3 * stride;
//}
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "SOD Viewer", NULL, NULL);
if (window == NULL) {
std::cerr << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cerr << "Failed to initialize GLAD" << std::endl;
glfwTerminate();
return 1;
}
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, WIDTH, HEIGHT);
glfwSetFramebufferSizeCallback(window, vwr_resize_callback);
Shader shader("./src/vs.glsl", "./src/fs.glsl");
//float vertices[] = {
// 0.5f, 0.5f, 0.0f, // top right
// 0.5f, -0.5f, 0.0f, // bottom right
// -0.5f, -0.5f, 0.0f, // bottom left
// -0.5f, 0.5f, 0.0f // top left
//};
//unsigned int indices[] = {
// 0, 1, 3,
// 1, 2, 3
//};
// float vertices[] = {
// -0.5f, -0.5f, 0.0f,
// 0.0f, 0.5f, 0.0f,
// 0.5f, -0.5f, 0.0f,
// };
unsigned int VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
//glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
printf("%ld\n", m.getNumberOfVertices() * sizeof(float));
glBindBuffer(GL_ARRAY_BUFFER, VBO);
//glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, m.getNumberOfVertices() * sizeof(float), vertices, GL_STATIC_DRAW);
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
//glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), 0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//stbi_set_flip_vertically_on_load(true);
//int width, height, num_channels;
//unsigned char *tex_data;
//tex_data = stbi_load(img_filepath, &width, &height, &num_channels, 0);
int width = m.getTextureWidth();
int height = m.getTextureHeight();
unsigned char *tex_data = m.getTextureData();
if (tex_data) {
std::cout << "WIDTH: " << width << ", HEIGHT: " << height << std::endl;
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, tex_data);
glGenerateMipmap(GL_TEXTURE_2D);
} else {
std::cerr << "Unable to load texture: " << img_filepath << std::endl;
return 1;
}
//stbi_image_free(tex_data);
/* unbind the currently bound buffer & array */
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window)) {
vwr_process_input(window);
glClearColor(0.25f, 0.25f, 0.25f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.use();
glm::mat4 model = glm::mat4(1.0f);
model = glm::scale(model, glm::vec3(0.25f, 0.25f, 0.25f));
model = glm::rotate(model, glm::radians(rot_degree), glm::vec3(0.0f, 1.0f, 0.0f));
shader.setMat4("model", model);
glm::mat4 view = glm::mat4(1.0f);
// right
SODVector3 *vec3 = node->local_transform->right;
view = glm::translate(view, glm::vec3(vec3->x, vec3->y, vec3->z));
// up
vec3 = node->local_transform->up;
view = glm::translate(view, glm::vec3(vec3->x, vec3->y, vec3->z));
// front
vec3 = node->local_transform->front;
view = glm::translate(view, glm::vec3(vec3->x, vec3->y, vec3->z));
// position
vec3 = node->local_transform->position;
view = glm::translate(view, glm::vec3(vec3->x, vec3->y, vec3->z));
view = glm::translate(view, glm::vec3(0.0f, 0.0f, z_offset));
shader.setMat4("view", view);
glm::mat4 proj = glm::perspective(glm::radians(45.0f), (float)WIDTH/(float)HEIGHT, 0.1f, 100.0f);
shader.setMat4("proj", proj);
glBindTexture(GL_TEXTURE_2D, texture);
glBindVertexArray(VAO);
//glDrawArrays(GL_TRIANGLES, 0, sizeof(vertices));
glDrawArrays(GL_TRIANGLES, 0, m.getNumberOfVertices() * sizeof(float));
//glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
glfwTerminate();
sod_free_file(file);
return 0;
}
| 35.018182 | 105 | 0.600519 | [
"mesh",
"model"
] |
9f94f8cf7bb8aaee582e90db82bfdd1d700a949c | 15,222 | cpp | C++ | Common/ac/spritecache.cpp | adventuregamestudio/ags | 8aff3708e25a17bb762604f4ef55eb6b0f0fc2e1 | [
"Artistic-2.0"
] | 450 | 2015-01-12T22:45:54.000Z | 2022-03-16T00:28:25.000Z | Common/ac/spritecache.cpp | adventuregamestudio/ags | 8aff3708e25a17bb762604f4ef55eb6b0f0fc2e1 | [
"Artistic-2.0"
] | 1,162 | 2015-01-03T09:57:17.000Z | 2022-03-31T20:28:56.000Z | Common/ac/spritecache.cpp | adventuregamestudio/ags | 8aff3708e25a17bb762604f4ef55eb6b0f0fc2e1 | [
"Artistic-2.0"
] | 121 | 2015-02-20T14:36:40.000Z | 2022-03-08T14:01:35.000Z | //=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
#include "ac/spritecache.h"
#include "ac/common.h" // quit
#include "ac/gamestructdefines.h"
#include "debug/out.h"
#include "gfx/bitmap.h"
using namespace AGS::Common;
// [IKM] We have to forward-declare these because their implementations are in the Engine
extern void initialize_sprite(int);
extern void pre_save_sprite(Bitmap *image);
extern void get_new_size_for_sprite(int, int, int, int &, int &);
#define START_OF_LIST -1
#define END_OF_LIST -1
SpriteInfo::SpriteInfo()
: Flags(0)
, Width(0)
, Height(0)
{
}
namespace AGS
{
namespace Common
{
SpriteCache::SpriteData::SpriteData()
: Size(0)
, Flags(0)
, Image(nullptr)
{
}
SpriteCache::SpriteData::~SpriteData()
{
// TODO: investigate, if it's actually safe/preferred to delete bitmap here
// (some of these bitmaps may be assigned from outside of the cache)
}
SpriteCache::SpriteCache(std::vector<SpriteInfo> &sprInfos)
: _sprInfos(sprInfos)
{
Init();
}
SpriteCache::~SpriteCache()
{
Reset();
}
size_t SpriteCache::GetCacheSize() const
{
return _cacheSize;
}
size_t SpriteCache::GetLockedSize() const
{
return _lockedSize;
}
size_t SpriteCache::GetMaxCacheSize() const
{
return _maxCacheSize;
}
size_t SpriteCache::GetSpriteSlotCount() const
{
return _spriteData.size();
}
void SpriteCache::SetMaxCacheSize(size_t size)
{
_maxCacheSize = size;
}
void SpriteCache::Init()
{
_cacheSize = 0;
_lockedSize = 0;
_maxCacheSize = (size_t)DEFAULTCACHESIZE_KB * 1024;
_liststart = -1;
_listend = -1;
}
void SpriteCache::Reset()
{
_file.Close();
// TODO: find out if it's safe to simply always delete _spriteData.Image with array element
for (size_t i = 0; i < _spriteData.size(); ++i)
{
if (_spriteData[i].Image)
{
delete _spriteData[i].Image;
_spriteData[i].Image = nullptr;
}
}
_spriteData.clear();
_mrulist.clear();
_mrubacklink.clear();
Init();
}
void SpriteCache::SetSprite(sprkey_t index, Bitmap *sprite)
{
if (index < 0 || EnlargeTo(index) != index)
{
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Error, "SetSprite: unable to use index %d", index);
return;
}
if (!sprite)
{
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Error, "SetSprite: attempt to assign nullptr to index %d", index);
return;
}
_spriteData[index].Image = sprite;
_spriteData[index].Flags = SPRCACHEFLAG_LOCKED; // NOT from asset file
_spriteData[index].Size = 0;
#ifdef DEBUG_SPRITECACHE
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Debug, "SetSprite: (external) %d", index);
#endif
}
void SpriteCache::SetEmptySprite(sprkey_t index, bool as_asset)
{
if (index < 0 || EnlargeTo(index) != index)
{
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Error, "SetEmptySprite: unable to use index %d", index);
return;
}
if (as_asset)
_spriteData[index].Flags = SPRCACHEFLAG_ISASSET;
RemapSpriteToSprite0(index);
}
void SpriteCache::SubstituteBitmap(sprkey_t index, Bitmap *sprite)
{
if (!DoesSpriteExist(index))
{
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Error, "SubstituteBitmap: attempt to set for non-existing sprite %d", index);
return;
}
_spriteData[index].Image = sprite;
#ifdef DEBUG_SPRITECACHE
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Debug, "SubstituteBitmap: %d", index);
#endif
}
void SpriteCache::RemoveSprite(sprkey_t index, bool freeMemory)
{
if (freeMemory)
delete _spriteData[index].Image;
InitNullSpriteParams(index);
#ifdef DEBUG_SPRITECACHE
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Debug, "RemoveSprite: %d", index);
#endif
}
sprkey_t SpriteCache::EnlargeTo(sprkey_t topmost)
{
if (topmost < 0 || topmost > MAX_SPRITE_INDEX)
return -1;
if ((size_t)topmost < _spriteData.size())
return topmost;
size_t newsize = topmost + 1;
_sprInfos.resize(newsize);
_spriteData.resize(newsize);
_mrulist.resize(newsize);
_mrubacklink.resize(newsize);
return topmost;
}
sprkey_t SpriteCache::GetFreeIndex()
{
for (size_t i = MIN_SPRITE_INDEX; i < _spriteData.size(); ++i)
{
// slot empty
if (!DoesSpriteExist(i))
{
_sprInfos[i] = SpriteInfo();
_spriteData[i] = SpriteData();
return i;
}
}
// enlarge the sprite bank to find a free slot and return the first new free slot
return EnlargeTo(_spriteData.size());
}
bool SpriteCache::SpriteData::DoesSpriteExist() const
{
return (Image != nullptr) || // HAS loaded bitmap
((Flags & SPRCACHEFLAG_ISASSET) != 0); // OR found in the game resources
}
bool SpriteCache::SpriteData::IsAssetSprite() const
{
return (Flags & SPRCACHEFLAG_ISASSET) != 0; // found in game resources
}
bool SpriteCache::SpriteData::IsExternalSprite() const
{
return (Image != nullptr) && // HAS loaded bitmap
((Flags & SPRCACHEFLAG_ISASSET) == 0) && // AND NOT found in game resources
((Flags & SPRCACHEFLAG_REMAPPED) == 0); // AND was NOT remapped to another sprite
}
bool SpriteCache::SpriteData::IsLocked() const
{
return (Flags & SPRCACHEFLAG_LOCKED) != 0;
}
bool SpriteCache::DoesSpriteExist(sprkey_t index) const
{
return index >= 0 && (size_t)index < _spriteData.size() && _spriteData[index].DoesSpriteExist();
}
Bitmap *SpriteCache::operator [] (sprkey_t index)
{
// invalid sprite slot
if (index < 0 || (size_t)index >= _spriteData.size())
return nullptr;
// Externally added sprite, don't put it into MRU list
if (_spriteData[index].IsExternalSprite())
return _spriteData[index].Image;
// Sprite exists in file but is not in mem, load it
if ((_spriteData[index].Image == nullptr) && _spriteData[index].IsAssetSprite())
LoadSprite(index);
// Locked sprite that shouldn't be put into MRU list
if (_spriteData[index].IsLocked())
return _spriteData[index].Image;
if (_liststart < 0)
{
_liststart = index;
_listend = index;
_mrulist[index] = END_OF_LIST;
_mrubacklink[index] = START_OF_LIST;
}
else if (_listend != index)
{
// this is the oldest element being bumped to newest, so update start link
if (index == _liststart)
{
_liststart = _mrulist[index];
_mrubacklink[_liststart] = START_OF_LIST;
}
// already in list, link previous to next
else if (_mrulist[index] > 0)
{
_mrulist[_mrubacklink[index]] = _mrulist[index];
_mrubacklink[_mrulist[index]] = _mrubacklink[index];
}
// set this as the newest element in the list
_mrulist[index] = END_OF_LIST;
_mrulist[_listend] = index;
_mrubacklink[index] = _listend;
_listend = index;
}
return _spriteData[index].Image;
}
void SpriteCache::DisposeOldest()
{
if (_liststart < 0)
return;
sprkey_t sprnum = _liststart;
if ((_spriteData[sprnum].Image != nullptr) && !_spriteData[sprnum].IsLocked())
{
// Free the memory
// Sprites that are not from the game resources should not normally be in a MRU list;
// if such is met here there's something wrong with the internal cache logic!
if (!_spriteData[sprnum].IsAssetSprite())
{
quitprintf("SpriteCache::DisposeOldest: attempted to remove sprite %d that was added externally or does not exist", sprnum);
}
_cacheSize -= _spriteData[sprnum].Size;
delete _spriteData[sprnum].Image;
_spriteData[sprnum].Image = nullptr;
}
if (_liststart == _listend)
{
// there was one huge sprite, removing it has now emptied the cache completely
if (_cacheSize > 0)
{
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Error, "SPRITE CACHE ERROR: Sprite cache should be empty, but still has %d bytes", _cacheSize);
}
_mrulist[_liststart] = 0;
_liststart = -1;
_listend = -1;
}
else
{
sprkey_t oldstart = _liststart;
_liststart = _mrulist[_liststart];
_mrulist[oldstart] = 0;
_mrubacklink[_liststart] = START_OF_LIST;
if (oldstart == _liststart)
{
// Somehow, we have got a recursive link to itself, so we
// the game will freeze (since it is not actually freeing any
// memory)
// There must be a bug somewhere causing this, but for now
// let's just reset the cache
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Error, "RUNTIME CACHE ERROR: CACHE INCONSISTENT: RESETTING\n\tAt size %d (of %d), start %d end %d fwdlink=%d",
_cacheSize, _maxCacheSize, oldstart, _listend, _liststart);
DisposeAll();
}
}
#ifdef DEBUG_SPRITECACHE
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Debug, "DisposeOldest: disposed %d, size now %d KB", sprnum, _cacheSize / 1024);
#endif
}
void SpriteCache::DisposeAll()
{
_liststart = -1;
_listend = -1;
for (size_t i = 0; i < _spriteData.size(); ++i)
{
if (!_spriteData[i].IsLocked() && // not locked
_spriteData[i].IsAssetSprite()) // sprite from game resource
{
delete _spriteData[i].Image;
_spriteData[i].Image = nullptr;
}
_mrulist[i] = 0;
_mrubacklink[i] = 0;
}
_cacheSize = _lockedSize;
}
void SpriteCache::Precache(sprkey_t index)
{
if (index < 0 || (size_t)index >= _spriteData.size())
return;
soff_t sprSize = 0;
if (_spriteData[index].Image == nullptr)
sprSize = LoadSprite(index);
else if (!_spriteData[index].IsLocked())
sprSize = _spriteData[index].Size;
// make sure locked sprites can't fill the cache
_maxCacheSize += sprSize;
_lockedSize += sprSize;
_spriteData[index].Flags |= SPRCACHEFLAG_LOCKED;
#ifdef DEBUG_SPRITECACHE
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Debug, "Precached %d", index);
#endif
}
sprkey_t SpriteCache::GetDataIndex(sprkey_t index)
{
return (_spriteData[index].Flags & SPRCACHEFLAG_REMAPPED) == 0 ? index : 0;
}
size_t SpriteCache::LoadSprite(sprkey_t index)
{
int hh = 0;
while (_cacheSize > _maxCacheSize)
{
DisposeOldest();
hh++;
if (hh > 1000)
{
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Error, "RUNTIME CACHE ERROR: STUCK IN FREE_UP_MEM; RESETTING CACHE");
DisposeAll();
}
}
if (index < 0 || (size_t)index >= _spriteData.size())
quit("sprite cache array index out of bounds");
sprkey_t load_index = GetDataIndex(index);
Bitmap *image;
HError err = _file.LoadSprite(load_index, image);
if (!image)
{
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Warn,
"LoadSprite: failed to load sprite %d:\n%s\n - remapping to sprite 0.", index,
err ? err->FullMessage().GetCStr() : "Sprite does not exist.");
RemapSpriteToSprite0(index);
return 0;
}
// update the stored width/height
_sprInfos[index].Width = image->GetWidth();
_sprInfos[index].Height = image->GetHeight();
_spriteData[index].Image = image;
// Stop it adding the sprite to the used list just because it's loaded
// TODO: this messy hack is required, because initialize_sprite calls operator[]
// which puts the sprite to the MRU list.
_spriteData[index].Flags |= SPRCACHEFLAG_LOCKED;
// TODO: this is ugly: asks the engine to convert the sprite using its own knowledge.
// And engine assigns new bitmap using SpriteCache::SubstituteBitmap().
// Perhaps change to the callback function pointer?
initialize_sprite(index);
if (index != 0) // leave sprite 0 locked
_spriteData[index].Flags &= ~SPRCACHEFLAG_LOCKED;
// we need to store this because the main program might
// alter spritewidth/height if it resizes stuff
size_t size = _sprInfos[index].Width * _sprInfos[index].Height *
_spriteData[index].Image->GetBPP();
_spriteData[index].Size = size;
_cacheSize += size;
#ifdef DEBUG_SPRITECACHE
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Debug, "Loaded %d, size now %zu KB", index, _cacheSize / 1024);
#endif
return size;
}
void SpriteCache::RemapSpriteToSprite0(sprkey_t index)
{
_sprInfos[index].Flags = _sprInfos[0].Flags;
_sprInfos[index].Width = _sprInfos[0].Width;
_sprInfos[index].Height = _sprInfos[0].Height;
_spriteData[index].Image = nullptr;
_spriteData[index].Size = _spriteData[0].Size;
_spriteData[index].Flags |= SPRCACHEFLAG_REMAPPED;
#ifdef DEBUG_SPRITECACHE
Debug::Printf(kDbgGroup_SprCache, kDbgMsg_Debug, "RemapSpriteToSprite0: %d", index);
#endif
}
int SpriteCache::SaveToFile(const String &filename, bool compressOutput, SpriteFileIndex &index)
{
std::vector<Bitmap*> sprites;
for (const auto &data : _spriteData)
{
// NOTE: this is a horrible hack:
// because Editor expects slightly different RGB order, it swaps colors
// when loading them (call to initialize_sprite), so here we basically
// unfix that fix to save the data in a way that engine will expect.
// TODO: perhaps adjust the editor to NOT need this?!
pre_save_sprite(data.Image);
sprites.push_back(data.Image);
}
return SaveSpriteFile(filename, sprites, &_file, compressOutput, index);
}
HError SpriteCache::InitFile(const String &filename, const String &sprindex_filename)
{
std::vector<Size> metrics;
HError err = _file.OpenFile(filename, sprindex_filename, metrics);
if (!err)
return err;
// Initialize sprite infos
size_t newsize = metrics.size();
_sprInfos.resize(newsize);
_spriteData.resize(newsize);
_mrulist.resize(newsize);
_mrubacklink.resize(newsize);
for (size_t i = 0; i < metrics.size(); ++i)
{
if (!metrics[i].IsNull())
{
// Existing sprite
_spriteData[i].Flags = SPRCACHEFLAG_ISASSET;
_spriteData[i].Image = nullptr;
get_new_size_for_sprite(i, metrics[i].Width, metrics[i].Height, _sprInfos[i].Width, _sprInfos[i].Height);
}
else
{
// Handle empty slot: remap to sprite 0
if (i > 0) // FIXME: optimize
InitNullSpriteParams(i);
}
}
return HError::None();
}
void SpriteCache::DetachFile()
{
_file.Close();
}
} // namespace Common
} // namespace AGS
| 29.273077 | 165 | 0.642557 | [
"vector"
] |
7a06dcdbbdf0f01c5cd656f879ef96c5d235becc | 1,213 | hpp | C++ | tests/mghfuns/brown_badly_scaled.hpp | ptillet/umintl | 605da5703d36c2150fd1c2b979ff6e631b4cad47 | [
"MIT"
] | null | null | null | tests/mghfuns/brown_badly_scaled.hpp | ptillet/umintl | 605da5703d36c2150fd1c2b979ff6e631b4cad47 | [
"MIT"
] | null | null | null | tests/mghfuns/brown_badly_scaled.hpp | ptillet/umintl | 605da5703d36c2150fd1c2b979ff6e631b4cad47 | [
"MIT"
] | null | null | null | /* ===========================
Copyright (c) 2013 Philippe Tillet
UMinTL - Unconstrained Minimization Template Library
License : MIT X11 - See the LICENSE file in the root folder
* ===========================*/
#ifndef UMINTL_BROWN_BADLY_SCALED_HPP_
#define UMINTL_BROWN_BADLY_SCALED_HPP_
#include <cmath>
#include <vector>
#include "sum_square.hpp"
template<class BackendType>
class brown_badly_scaled : public sum_square<BackendType>{
typedef typename BackendType::VectorType VectorType;
typedef double ScalarType;
typedef sum_square<BackendType> base_type;
using base_type::M_;
using base_type::N_;
using base_type::get;
public:
brown_badly_scaled() : base_type("Brown Badly Scaled",3,2,0){ }
void init(VectorType & X) const
{
X[0] = 1;
X[1] = 1;
}
void fill_dym_dxn(VectorType const & V, ScalarType * res) const
{
get(res,0,0) = 1; get(res,0,1) = 0;
get(res,1,0) = 0; get(res,1,1) = 1;
get(res,2,0) = V[1]; get(res,2,1) = V[0];
}
void fill_ym(VectorType const & V, ScalarType * res) const
{
res[0] = V[0] - 1e6;
res[1] = V[1] - 2e-6;
res[2] = V[0]*V[1]-2;
}
};
#endif
| 26.369565 | 67 | 0.601814 | [
"vector"
] |
7a090307887d4077deb773d71fb026750537ee70 | 11,681 | cpp | C++ | beowolf/W_Common.cpp | JarateKing/Beowolf-Engine | b7ad1ed18ecb5ce7ca4e43d46ee96ed615300e85 | [
"MIT"
] | 3 | 2019-01-21T15:18:41.000Z | 2020-04-16T18:21:29.000Z | beowolf/W_Common.cpp | JarateKing/Beowolf-Engine | b7ad1ed18ecb5ce7ca4e43d46ee96ed615300e85 | [
"MIT"
] | 1 | 2020-03-10T18:22:08.000Z | 2020-03-10T18:22:08.000Z | beowolf/W_Common.cpp | JarateKing/Beowolf-Engine | b7ad1ed18ecb5ce7ca4e43d46ee96ed615300e85 | [
"MIT"
] | 1 | 2021-12-30T11:38:36.000Z | 2021-12-30T11:38:36.000Z | //-----------------------------------------------------------------------------
// File: W_Common.cpp
// Original Author: Gordon Wood
//
// See header for notes
//-----------------------------------------------------------------------------
#include "W_Common.h"
#include "W_Types.h"
namespace wolf
{
//----------------------------------------------------------
// Loads in a whole file and returns the contents. User is
// responsible for then delete[]-ing the data. Returns 0 if
// file not able to be loaded.
//----------------------------------------------------------
void* LoadWholeFile(const std::string& p_strFile)
{
FILE* fp = fopen(p_strFile.c_str(), "rb");
if( !fp )
return 0;
fseek(fp, 0, SEEK_END);
size_t len = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* pRet = new char[len+1];
fread(pRet, sizeof(char), len, fp);
pRet[len] = 0;
fclose(fp);
return pRet;
}
//----------------------------------------------------------
// Compiles a shader of the given type (GL_VERTEX_SHADER or
// GL_FRAGMENT_SHADER) from the given file and stores the
// resulting shader object in p_pShader. Returns true on success,
// else false
//----------------------------------------------------------
bool CompileShader(GLuint* p_pShader, GLenum p_eType, const std::string& p_strFile)
{
GLint iStatus;
const GLchar* pSource;
pSource = (GLchar *) LoadWholeFile(p_strFile);
if( !pSource )
{
printf("Failed to load vertex shader\n");
return false;
}
*p_pShader = glCreateShader(p_eType);
glShaderSource(*p_pShader, 1, &pSource, NULL);
glCompileShader(*p_pShader);
#if defined(DEBUG)
GLint iLogLength;
glGetShaderiv(*p_pShader, GL_INFO_LOG_LENGTH, &iLogLength);
if( iLogLength > 0 )
{
GLchar* pLog = (GLchar *)malloc(iLogLength);
glGetShaderInfoLog(*p_pShader, iLogLength, &iLogLength, pLog);
printf("Shader compile log:\n%s\n", pLog);
free(pLog);
}
#endif
glGetShaderiv(*p_pShader, GL_COMPILE_STATUS, &iStatus);
if( iStatus == 0 )
{
glDeleteShader(*p_pShader);
return false;
}
return true;
}
//----------------------------------------------------------
// Performs the linking stage of the vertex and pixel shader,
// resulting in a final program object to use. Checks for
// errors and prints them and returns true on success, else false
//----------------------------------------------------------
bool LinkProgram(GLuint p_uiProg)
{
GLint iStatus;
glLinkProgram(p_uiProg);
#if defined(DEBUG)
GLint iLogLength;
glGetProgramiv(p_uiProg, GL_INFO_LOG_LENGTH, &iLogLength);
if (iLogLength > 0)
{
GLchar* pLog = (GLchar *)malloc(iLogLength);
glGetProgramInfoLog(p_uiProg, iLogLength, &iLogLength, pLog);
printf("Program link log:\n%s\n", pLog);
free(pLog);
}
#endif
glGetProgramiv(p_uiProg, GL_LINK_STATUS, &iStatus);
if (iStatus == 0)
return false;
return true;
}
//----------------------------------------------------------
// Loads a vertex and pixel shader from the given files, and
// compiles and links them into a program. Will return 0 on
// failure (and print errors to stdout), else the created
// program object
//----------------------------------------------------------
GLuint LoadShaders(const std::string& p_strVSFile, const std::string& p_strPSFile)
{
GLuint uiVS, uiPS;
// 1. Create and compile vertex shader.
if( !CompileShader(&uiVS, GL_VERTEX_SHADER, p_strVSFile))
{
printf("Failed to compile vertex shader\n");
return 0;
}
// 2. Create and compile fragment shader.
if( !CompileShader(&uiPS, GL_FRAGMENT_SHADER, p_strPSFile))
{
printf("Failed to compile pixel shader\n");
glDeleteShader(uiVS);
return 0;
}
// 3. Create shader program that we'll (hopefully) eventually return
GLuint uiProgram = glCreateProgram();
// 4. Attach vertex shader and pixel shader to program.
glAttachShader(uiProgram, uiVS);
glAttachShader(uiProgram, uiPS);
// 5. Link program.
if( !LinkProgram(uiProgram) )
{
printf("Failed to link program: %d\n", uiProgram);
if( uiVS )
{
glDeleteShader(uiVS);
}
if( uiPS )
{
glDeleteShader(uiPS);
}
if( uiProgram )
{
glDeleteProgram(uiProgram);
}
return 0;
}
// Release vertex and fragment shaders.
if( uiVS )
glDeleteShader(uiVS);
if( uiPS )
glDeleteShader(uiPS);
return uiProgram;
}
bool LoadTGA(const std::string& p_strFile, unsigned int* p_pWidth, unsigned int* p_pHeight, unsigned char** p_ppData)
{
GLFWimage img;
if( GL_FALSE == glfwReadImage( p_strFile.c_str(), &img, 0 ) )
return false;
*p_pWidth = img.Width;
*p_pHeight = img.Height;
*p_ppData = img.Data;
return true;
}
enum
{
DDSF_MAX_MIPMAPS = 16,
DDSF_MAX_TEXTURES = 16,
DDSF_CAPS = 0x00000001,
DDSF_HEIGHT = 0x00000002,
DDSF_WIDTH = 0x00000004,
DDSF_PITCH = 0x00000008,
DDSF_PIXELFORMAT = 0x00001000,
DDSF_MIPMAPCOUNT = 0x00020000,
DDSF_LINEARSIZE = 0x00080000,
DDSF_DEPTH = 0x00800000,
// pixel format flags
DDSF_ALPHAPIXELS = 0x00000001,
DDSF_FOURCC = 0x00000004,
DDSF_RGB = 0x00000040,
DDSF_RGBA = 0x00000041,
// dwCaps1 flags
DDSF_COMPLEX = 0x00000008,
DDSF_TEXTURE = 0x00001000,
DDSF_MIPMAP = 0x00400000,
// dwCaps2 flags
DDSF_CUBEMAP = 0x00000200l,
DDSF_CUBEMAP_POSITIVEX = 0x00000400l,
DDSF_CUBEMAP_NEGATIVEX = 0x00000800l,
DDSF_CUBEMAP_POSITIVEY = 0x00001000l,
DDSF_CUBEMAP_NEGATIVEY = 0x00002000l,
DDSF_CUBEMAP_POSITIVEZ = 0x00004000l,
DDSF_CUBEMAP_NEGATIVEZ = 0x00008000l,
DDSF_CUBEMAP_ALL_FACES = 0x0000FC00l,
DDSF_VOLUME = 0x00200000l,
// compressed texture types
FOURCC_DXT1 = 0x31545844,
FOURCC_DXT3 = 0x33545844,
FOURCC_DXT5 = 0x35545844,
};
struct DXTColBlock
{
unsigned short col0;
unsigned short col1;
unsigned char row[4];
};
struct DXT3AlphaBlock
{
unsigned short row[4];
};
struct DXT5AlphaBlock
{
unsigned char alpha0;
unsigned char alpha1;
unsigned char row[6];
};
struct DDS_PIXELFORMAT
{
unsigned int dwSize;
unsigned int dwFlags;
unsigned int dwFourCC;
unsigned int dwRGBBitCount;
unsigned int dwRBitMask;
unsigned int dwGBitMask;
unsigned int dwBBitMask;
unsigned int dwABitMask;
};
struct DDS_HEADER
{
unsigned int dwSize;
unsigned int dwFlags;
unsigned int dwHeight;
unsigned int dwWidth;
unsigned int dwPitchOrLinearSize;
unsigned int dwDepth;
unsigned int dwMipMapCount;
unsigned int dwReserved1[11];
DDS_PIXELFORMAT ddspf;
unsigned int dwCaps1;
unsigned int dwCaps2;
unsigned int dwReserved2[3];
};
enum TextureType
{
TextureNone,
TextureFlat, // 1D, 2D, and rectangle textures
Texture3D,
TextureCubemap
};
struct DDS_IMAGE
{
unsigned char *pixels[DDSF_MAX_MIPMAPS]; //the mip map images
};
struct DDS_TEXTURE
{
unsigned char *buffer; //pointer to loaded dds file
unsigned int format; //compression used or pixel format
unsigned int components; //number of channels
unsigned int width; //width of base image in pixels
unsigned int height; //height of based image in pixels
unsigned int mips; //number of mip levels
unsigned int surfaces; //number of surfaces ( 1 = a texture 6 = a cube map)
DDS_IMAGE image[6];
};
#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0
#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
bool ImageSpec(DDS_HEADER *ddsh, unsigned int *format,unsigned int *components)
{
assert(format);
assert(components);
if (ddsh->ddspf.dwFlags & DDSF_FOURCC) //its a compressed texture
{
switch(ddsh->ddspf.dwFourCC)
{
case FOURCC_DXT1:
*format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
*components = 3;
break;
case FOURCC_DXT3:
*format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
*components = 4;
break;
case FOURCC_DXT5:
*format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
*components = 4;
break;
default:
printf("ERROR: Uses a compressed texture of unsupported type\n");
return false;
}
}
else if (ddsh->ddspf.dwFlags == DDSF_RGBA && ddsh->ddspf.dwRGBBitCount == 32)
{
*format = GL_BGRA;
*components = 4;
}
else if (ddsh->ddspf.dwFlags == DDSF_RGB && ddsh->ddspf.dwRGBBitCount == 32)
{
*format = GL_BGRA;
*components = 4;
}
else if (ddsh->ddspf.dwFlags == DDSF_RGB && ddsh->ddspf.dwRGBBitCount == 24)
{
*format = GL_BGR;
*components = 3;
}
else
{
printf("ERROR: Uses a texture of unsupported type");
return false;
}
return true;
}
int DDSImageSize(unsigned int w,
unsigned int h,
unsigned int components,
unsigned int format)
{
switch(format)
{
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return ((w+3)/4)* ((h+3)/4)* 8;
case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
return ((w+3)/4)*((h+3)/4)* 16;
default:
printf("ERROR: unable to determine image size\n");
return 0;
}
}
GLuint CreateTextureFromDDS(const std::string& p_strFile, unsigned int* p_pWidth, unsigned int* p_pHeight, bool* p_pHasMips)
{
DDS_TEXTURE dds;
memset(&dds, 0, sizeof(dds));
unsigned char* pBuff = (unsigned char*) LoadWholeFile(p_strFile);
unsigned char* pStart = pBuff;
// read in file marker, make sure its a DDS file
if(strncmp((char*)pBuff,"DDS ",4)!=0)
{
printf("%s is not a dds file", p_strFile.c_str());
return 0;
}
pBuff+=4; //skip over header
//read the dds header data
DDS_HEADER* ddsh;
ddsh=(DDS_HEADER*)pBuff;
pBuff+=sizeof(DDS_HEADER);
TextureType type = TextureFlat;
if (ddsh->dwCaps2 & DDSF_CUBEMAP) type = TextureCubemap;
// check if image is a volume texture
if ((ddsh->dwCaps2 & DDSF_VOLUME) && (ddsh->dwDepth > 0))
{
printf("ERROR: %s is a volume texture ", p_strFile.c_str());
return 0;
}
// get the format of the image
unsigned int format;
unsigned int components;
//get the texture format and number of color channels
ImageSpec(ddsh,&format,&components);
unsigned int width, height;
width = ddsh->dwWidth;
height = ddsh->dwHeight;
dds.buffer = (unsigned char*)pStart;
dds.format = format;
dds.components = components;
dds.height = height;
dds.width = width;
if(ddsh->dwMipMapCount==0) ddsh->dwMipMapCount++;
dds.mips = ddsh->dwMipMapCount;
dds.surfaces = 1;
GLuint uiTex = 0;
glGenTextures(1,&uiTex);
glBindTexture(GL_TEXTURE_2D,uiTex);
GL_CHECK_ERROR();
int iWidth = dds.width;
int iHeight = dds.height;
unsigned char* pData = pBuff;
for( unsigned int iMipLevel = 0; iMipLevel < dds.mips; iMipLevel++ )
{
if( iWidth == 0 )
iWidth = 1;
if( iHeight == 0 )
iHeight = 1;
unsigned int size = DDSImageSize(iWidth,iHeight,components,format);
//Start fill our texture
glCompressedTexImage2D(
GL_TEXTURE_2D,
iMipLevel,
format,
iWidth,
iHeight,
0,
size,
pData);
GL_CHECK_ERROR();
iWidth /= 2;
iHeight /= 2;
pData += size;
}
if( dds.mips > 1 )
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
else
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
GL_CHECK_ERROR();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GL_CHECK_ERROR();
if( p_pWidth )
*p_pWidth = dds.width;
if( p_pHeight )
*p_pHeight = dds.height;
if( p_pHasMips )
*p_pHasMips = dds.mips > 1;
return uiTex;
}
}
| 24.386221 | 124 | 0.641298 | [
"object"
] |
7a188cb4749213b1a852f2e8385d638dad9dbf9f | 2,997 | cc | C++ | CommBasicObjects/smartsoft/src-gen/CommBasicObjects/CommUltrasonicScanACE.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | null | null | null | CommBasicObjects/smartsoft/src-gen/CommBasicObjects/CommUltrasonicScanACE.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | 2 | 2020-08-20T14:49:47.000Z | 2020-10-07T16:10:07.000Z | CommBasicObjects/smartsoft/src-gen/CommBasicObjects/CommUltrasonicScanACE.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | 8 | 2018-06-25T08:41:28.000Z | 2020-08-13T10:39:30.000Z | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#include "CommBasicObjects/CommUltrasonicScanACE.hh"
#include <ace/SString.h>
#include "CommBasicObjects/CommTimeStampACE.hh"
#include "CommBasicObjects/CommPose3dACE.hh"
// serialization operator for element CommUltrasonicScan
ACE_CDR::Boolean operator<<(ACE_OutputCDR &cdr, const CommBasicObjectsIDL::CommUltrasonicScan &data)
{
ACE_CDR::Boolean good_bit = true;
// serialize list-element timeStamp
good_bit = good_bit && cdr << data.timeStamp;
// serialize list-element scanPoints
good_bit = good_bit && cdr << ACE_Utils::truncate_cast<ACE_CDR::ULong>(data.scanPoints.size());
std::vector<CommBasicObjectsIDL::CommPose3d>::const_iterator data_scanPointsIt;
for(data_scanPointsIt=data.scanPoints.begin(); data_scanPointsIt!=data.scanPoints.end(); data_scanPointsIt++) {
good_bit = good_bit && cdr << *data_scanPointsIt;
}
// serialize list-element intensities
good_bit = good_bit && cdr << ACE_Utils::truncate_cast<ACE_CDR::ULong>(data.intensities.size());
good_bit = good_bit && cdr.write_double_array(data.intensities.data(), data.intensities.size());
return good_bit;
}
// de-serialization operator for element CommUltrasonicScan
ACE_CDR::Boolean operator>>(ACE_InputCDR &cdr, CommBasicObjectsIDL::CommUltrasonicScan &data)
{
ACE_CDR::Boolean good_bit = true;
// deserialize type element timeStamp
good_bit = good_bit && cdr >> data.timeStamp;
// deserialize list-type element scanPoints
ACE_CDR::ULong data_scanPointsNbr;
good_bit = good_bit && cdr >> data_scanPointsNbr;
data.scanPoints.clear();
CommBasicObjectsIDL::CommPose3d data_scanPointsItem;
for(ACE_CDR::ULong i=0; i<data_scanPointsNbr; ++i) {
good_bit = good_bit && cdr >> data_scanPointsItem;
data.scanPoints.push_back(data_scanPointsItem);
}
// deserialize list-type element intensities
ACE_CDR::ULong data_intensitiesNbr;
good_bit = good_bit && cdr >> data_intensitiesNbr;
data.intensities.resize(data_intensitiesNbr);
good_bit = good_bit && cdr.read_double_array(data.intensities.data(), data_intensitiesNbr);
return good_bit;
}
// serialization operator for CommunicationObject CommUltrasonicScan
ACE_CDR::Boolean operator<<(ACE_OutputCDR &cdr, const CommBasicObjects::CommUltrasonicScan &obj)
{
return cdr << obj.get();
}
// de-serialization operator for CommunicationObject CommUltrasonicScan
ACE_CDR::Boolean operator>>(ACE_InputCDR &cdr, CommBasicObjects::CommUltrasonicScan &obj)
{
return cdr >> obj.set();
}
| 39.96 | 112 | 0.736737 | [
"vector"
] |
7a319be94372f3050142ffe6916f0b47fb0836b3 | 7,999 | cpp | C++ | AutoJoin/autojoin.cpp | JateNensvold/logcabin | 6966ab07e8780de4ee2c706df4c2530922f7d265 | [
"ISC"
] | null | null | null | AutoJoin/autojoin.cpp | JateNensvold/logcabin | 6966ab07e8780de4ee2c706df4c2530922f7d265 | [
"ISC"
] | null | null | null | AutoJoin/autojoin.cpp | JateNensvold/logcabin | 6966ab07e8780de4ee2c706df4c2530922f7d265 | [
"ISC"
] | null | null | null | #include "autojoin.h"
vector<string> autojoin::parseString(string input, char delimeter)
{
vector<string> returnlist = vector<string>();
int length = (int)input.length();
string temp = "";
for (int index = 0; index < length; index++)
{
if (input[index] == delimeter && temp != "")
{
returnlist.push_back(temp);
temp = "";
}
else
{
temp += input[index];
}
}
if (temp != "")
{
returnlist.push_back(temp);
}
return returnlist;
}
int autojoin::createHostConnection(int port, int mode, struct sockaddr_in sock)
{
int host_fd;
int opt = 1;
// Creating socket file descriptor
if ((host_fd = socket(mode, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(host_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
sock.sin_family = mode;
sock.sin_addr.s_addr = INADDR_ANY;
sock.sin_port = htons(port);
int tempvar = 0;
// Forcefully attaching socket to the port
if (tempvar = (bind(host_fd, (struct sockaddr *)&sock, sizeof(sock))) < 0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
return host_fd;
}
int autojoin::createClientConnection(string ip, int port, int mode, struct sockaddr_in socketadd)
{
int sock = 0, valread;
char address[100];
cout << "Copying address into ip" << endl;
strcpy(address, ip.c_str());
char buffer[2048] = {0};
cout << "Creating socket" << endl;
if ((sock = socket(mode, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
socketadd.sin_family = mode;
socketadd.sin_port = htons(port);
cout << "Convert Address" << endl;
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(mode, address, &socketadd.sin_addr) <= 0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
cout << "Connecting to remote host" << endl;
if (connect(sock, (struct sockaddr *)&socketadd, sizeof(socketadd)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
return sock;
}
// Name is the hash for identicon, port is the port that it will listen on, remote address/host/node
// remoteaddress is the address to reach out to for join, host makes the node the host, node puts it into passive mode
// Mode is for AF_INET for ipv4 and AF_INET6 for ipv6
int autojoinprogram(string name, string port, string remoteaddress, int mode)
{
struct sockaddr_in address;
int addrlen = sizeof(address);
int newsocket, bRead;
char buffer[2048] = {0};
autojoin autojoinobject = autojoin();
while (1)
{
if (remoteaddress == "host" || remoteaddress == "Host")
{
cout << "Node set as host node" << endl;
int hostsocket = autojoinobject.createHostConnection(stoi(port), mode, address);
if (listen(hostsocket, 3) < 0)
{
cout << "Node failure to listen on port" << endl;
perror("listen");
exit(EXIT_FAILURE);
}
while (1)
{
if ((newsocket = accept(hostsocket, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0)
{
cout << "Node failure to accept connection" << endl;
perror("accept");
exit(EXIT_FAILURE);
}
cout << "Reading transmission from socket" << endl;
bRead = read(newsocket, buffer, 2048);
string temp = buffer;
identicon printiden = identicon();
printiden.generate(temp);
if (temp == "node_no_longer_host")
{
remoteaddress = "node";
break;
}
cout << "Accept connection (y or n)" << endl;
string option = "";
while (option != "y" && option != "n")
{
cin >> option;
if (option != "y" && option != "n")
{
cout << "Invalid choice." << endl;
}
}
char *message = "";
if (option == "y")
{
message = "connection-accepted";
}
else
{
message = "connection-denied";
}
send(newsocket, message, strlen(message), 0);
}
}
if (remoteaddress == "node" || remoteaddress == "Node")
{
cout << "Node set as node listening for connections but not host for join" << endl;
int hostsocket = autojoinobject.createHostConnection(stoi(port), mode, address);
if (listen(hostsocket, 3) < 0)
{
cout << "Node failure to listen on port" << endl;
perror("listen");
exit(EXIT_FAILURE);
}
while (1)
{
if ((newsocket = accept(hostsocket, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0)
{
cout << "Reading transmition from socket" << endl;
bRead = read(newsocket, buffer, 2048);
string temp = buffer;
if (temp == "node_set_as_host")
{
remoteaddress = "host";
break;
}
else
{
char message[1024] = "not_host_node";
send(newsocket, message, strlen(message), 0);
}
}
else
{
perror("accept");
exit(EXIT_FAILURE);
}
}
}
else
{
cout << "Node configured as client to auto join" << endl;
vector<string> ip = autojoinobject.parseString(remoteaddress, ';');
cout << "Address: " + ip[0] << endl;
cout << "Port: " + ip[1] << endl;
if (ip.size() == 2)
{
newsocket = autojoinobject.createClientConnection(ip[0], stoi(ip[1]), mode, address);
cout << "Setting up connection for join from node " + name << endl;
if (newsocket == -1)
{
cout << "Exit" << endl;
exit(-1);
}
char message[2048];
identicon printiden = identicon();
printiden.generate(name);
strcpy(message, name.c_str());
cout << "Message copied in" << endl;
send(newsocket, message, strlen(message), 0);
bRead = read(newsocket, buffer, 2048);
cout << buffer << endl;
string temp = buffer;
if (temp == "connection-accepted")
{
cout << "Connection accepted configuring as node" << endl;
remoteaddress = "node";
}
else if (temp == "not_host_node")
{
cout << "Node was not host, cannot join cluster" << endl;
}
else
{
cout << "Connection denied, shutting down..." << endl;
exit(-1);
}
}
else
{
cout << "Ip size incorrect actual size: " << ip.size() << endl;
exit(0);
}
}
}
return 0;
} | 31.616601 | 118 | 0.471059 | [
"vector"
] |
7a3b74b0933e6b68989b413d32b9de091010d1f8 | 10,053 | cpp | C++ | main.cpp | mediapark-pk/bip39-cxx | 6bc635f58d36dea715a2fbf3b12313eb6db5585e | [
"MIT"
] | 1 | 2021-04-17T11:52:20.000Z | 2021-04-17T11:52:20.000Z | main.cpp | mediapark-pk/bip39-cxx | 6bc635f58d36dea715a2fbf3b12313eb6db5585e | [
"MIT"
] | null | null | null | main.cpp | mediapark-pk/bip39-cxx | 6bc635f58d36dea715a2fbf3b12313eb6db5585e | [
"MIT"
] | 2 | 2020-04-05T16:27:52.000Z | 2021-02-08T16:48:15.000Z | #include <cassert>
#include <cstdio>
#include "src/bip39.h"
#include "src/mnemonic.h"
#include "src/utils.h"
static std::string joined_mnemonic(const std::vector<std::string>& s)
{
return BIP39_Utils::Join(s, " ");
}
void TestEntropyToMnemnoic(
const std::string& entropy, const std::string& expectedMnemonic, const std::string& seed)
{
static int i = 1;
auto m = BIP39::Entropy(entropy);
auto x = (joined_mnemonic(m.words) == expectedMnemonic);
auto seedVec = m.generateSeed("TREZOR");
std::string seedStr{(char*)seedVec.data(), seedVec.size()};
auto hexStr = BIP39_Utils::base16Encode(seedStr);
bool seedMatch = hexStr == seed;
if (!x)
printf(
"%d [FAIL]: \nEntropy: %s\nExpected: %s\nActual: %s\n",
i,
entropy.c_str(),
expectedMnemonic.c_str(),
joined_mnemonic(m.words).c_str());
else if (!seedMatch)
printf(
"%d [FAIL]: Seed mismatch,\nExpected: %s, Actual: %s", i, hexStr.c_str(), seed.c_str());
else
printf("%d [Pass]\n", i++);
}
int main()
{
TestEntropyToMnemnoic(
"00000000000000000000000000000000",
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon "
"about",
"c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f"
"2cf141630c7a3c4ab7c81b2f001698e7463b04");
TestEntropyToMnemnoic(
"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
"legal winner thank year wave sausage worth useful legal winner thank yellow",
"2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1"
"c1069be3a3a5bd381ee6260e8d9739fce1f607");
TestEntropyToMnemnoic(
"80808080808080808080808080808080",
"letter advice cage absurd amount doctor acoustic avoid letter advice cage above",
"d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f12eb2e47ed2ac03b5c46"
"2a0358d18d69fe4f985ec81778c1b370b652a8");
TestEntropyToMnemnoic(
"ffffffffffffffffffffffffffffffff",
"zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong",
"ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a13332572917f0f8e5a589620c6f1"
"5b11c61dee327651a14c34e18231052e48c069");
TestEntropyToMnemnoic(
"000000000000000000000000000000000000000000000000",
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon "
"abandon abandon abandon abandon abandon abandon agent",
"035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9a565181599b79f53b84"
"4d8a71dd9f439c52a3d7b3e8a79c906ac845fa");
TestEntropyToMnemnoic(
"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
"legal winner thank year wave sausage worth useful legal winner thank year wave sausage "
"worth useful legal will",
"f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c392d168748f2d4a612ba"
"da0753b52a1c7ac53c1e93abd5c6320b9e95dd");
TestEntropyToMnemnoic(
"808080808080808080808080808080808080808080808080",
"letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount "
"doctor acoustic avoid letter always",
"107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913ffb796f841c49b1d33b6"
"10cf0e91d3aa239027f5e99fe4ce9e5088cd65");
TestEntropyToMnemnoic(
"ffffffffffffffffffffffffffffffffffffffffffffffff",
"zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when",
"0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43348d952e2265b4cd129"
"090758b3e3c2c49103b5051aac2eaeb890a528");
TestEntropyToMnemnoic(
"0000000000000000000000000000000000000000000000000000000000000000",
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon "
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon "
"abandon art",
"bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4d73245cafa9c3cca8d5"
"61a7c3de6f5d4a10be8ed2a5e608d68f92fcc8");
TestEntropyToMnemnoic(
"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
"legal winner thank year wave sausage worth useful legal winner thank year wave sausage "
"worth useful legal winner thank year wave sausage worth title",
"bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146ad717fbb7e451ce9eb83"
"5f43620bf5c514db0f8add49f5d121449d3e87");
TestEntropyToMnemnoic(
"8080808080808080808080808080808080808080808080808080808080808080",
"letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount "
"doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless",
"c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61af0aca007096df430022"
"f7a2b6fb91661a9589097069720d015e4e982f");
TestEntropyToMnemnoic(
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo "
"zoo vote",
"dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31"
"ed3992c456cdf60f5d4564b8ba3f05a69890ad");
TestEntropyToMnemnoic(
"9e885d952ad362caeb4efe34a8e91bd2",
"ozone drill grab fiber curtain grace pudding thank cruise elder eight picnic",
"274ddc525802f7c828d8ef7ddbcdc5304e87ac3535913611fbbfa986d0c9e5476c91689f9c8a54fd55bd38606a"
"a6a8595ad213d4c9c9f9aca3fb217069a41028");
TestEntropyToMnemnoic(
"6610b25967cdcca9d59875f5cb50b0ea75433311869e930b",
"gravity machine north sort system female filter attitude volume fold club stay feature "
"office ecology stable narrow fog",
"628c3827a8823298ee685db84f55caa34b5cc195a778e52d45f59bcf75aba68e4d7590e101dc414bc1bbd57376"
"66fbbef35d1f1903953b66624f910feef245ac");
TestEntropyToMnemnoic(
"68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c",
"hamster diagram private dutch cause delay private meat slide toddler razor book happy "
"fancy gospel tennis maple dilemma loan word shrug inflict delay length",
"64c87cde7e12ecf6704ab95bb1408bef047c22db4cc7491c4271d170a1b213d20b385bc1588d9c7b38f1b39d41"
"5665b8a9030c9ec653d75e65f847d8fc1fc440");
TestEntropyToMnemnoic(
"c0ba5a8e914111210f2bd131f3d5e08d",
"scheme spot photo card baby mountain device kick cradle pact join borrow",
"ea725895aaae8d4c1cf682c1bfd2d358d52ed9f0f0591131b559e2724bb234fca05aa9c02c57407e04ee9dc3b4"
"54aa63fbff483a8b11de949624b9f1831a9612");
TestEntropyToMnemnoic(
"6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3",
"horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap "
"uncle crack brave",
"fd579828af3da1d32544ce4db5c73d53fc8acc4ddb1e3b251a31179cdb71e853c56d2fcb11aed39898ce6c34b1"
"0b5382772db8796e52837b54468aeb312cfc3d");
TestEntropyToMnemnoic(
"9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863",
"panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol "
"speed nation flash devote level hobby quick inner drive ghost inside",
"72be8e052fc4919d2adf28d5306b5474b0069df35b02303de8c1729c9538dbb6fc2d731d5f832193cd9fb6aeec"
"bc469594a70e3dd50811b5067f3b88b28c3e8d");
TestEntropyToMnemnoic(
"23db8160a31d3e0dca3688ed941adbf3",
"cat swing flag economy stadium alone churn speed unique patch report train",
"deb5f45449e615feff5640f2e49f933ff51895de3b4381832b3139941c57b59205a42480c52175b6efcffaa58a"
"2503887c1e8b363a707256bdd2b587b46541f5");
TestEntropyToMnemnoic(
"8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0",
"light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart "
"sustain crack supply proud access",
"4cbdff1ca2db800fd61cae72a57475fdc6bab03e441fd63f96dabd1f183ef5b782925f00105f318309a7e9c3ea"
"6967c7801e46c8a58082674c860a37b93eda02");
TestEntropyToMnemnoic(
"066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad",
"all hour make first leader extend hole alien behind guard gospel lava path output census "
"museum junior mass reopen famous sing advance salt reform",
"26e975ec644423f4a4c4f4215ef09b4bd7ef924e85d1d17c4cf3f136c2863cf6df0a475045652c57eb5fb41513"
"ca2a2d67722b77e954b4b3fc11f7590449191d");
TestEntropyToMnemnoic(
"f30f8c1da665478f49b001d94c5fc452",
"vessel ladder alter error federal sibling chat ability sun glass valve picture",
"2aaa9242daafcee6aa9d7269f17d4efe271e1b9a529178d7dc139cd18747090bf9d60295d0ce74309a78852a9c"
"aadf0af48aae1c6253839624076224374bc63f");
TestEntropyToMnemnoic(
"c10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05",
"scissors invite lock maple supreme raw rapid void congress muscle digital elegant little "
"brisk hair mango congress clump",
"7b4a10be9d98e6cba265566db7f136718e1398c71cb581e1b2f464cac1ceedf4f3e274dc270003c670ad8d02c4"
"558b2f8e39edea2775c9e232c7cb798b069e88");
TestEntropyToMnemnoic(
"f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f",
"void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing "
"screen patrol group space point ten exist slush involve unfold",
"01f5bced59dec48e362f2c45b5de68b9fd6c92c6634f44d6d40aab69056506f0e35524a518034ddc1192e1dacd"
"32c1ed3eaa3c3b131c88ed8e7e54c49a5d0998");
return 0;
}
| 51.030457 | 100 | 0.765841 | [
"mesh",
"vector"
] |
7a405f979cf85f52ba6c610a691495a56a749929 | 864 | hpp | C++ | include/litesql/updatequery.hpp | aijle/litesql | 547dd41435dd3fb5761de386e24c0116c7f52ad7 | [
"BSD-3-Clause"
] | 11 | 2019-04-12T08:49:18.000Z | 2021-10-12T03:29:43.000Z | include/litesql/updatequery.hpp | aijle/litesql | 547dd41435dd3fb5761de386e24c0116c7f52ad7 | [
"BSD-3-Clause"
] | 4 | 2019-12-17T01:15:11.000Z | 2021-05-17T13:10:18.000Z | include/litesql/updatequery.hpp | aijle/litesql | 547dd41435dd3fb5761de386e24c0116c7f52ad7 | [
"BSD-3-Clause"
] | 5 | 2019-08-31T17:07:08.000Z | 2022-03-21T06:57:39.000Z | /* LiteSQL
*
* The list of contributors at http://litesql.sf.net/
*
* See LICENSE for copyright information. */
#ifndef _litesql_updatequery_hpp
#define _litesql_updatequery_hpp
#include "litesql/utils.hpp"
#include "litesql/expr.hpp"
/** \file updatequery.hpp
contains UpdateQuery-class. */
namespace litesql {
/** a class that helps creating UPDATE-SQL statements. methods are
self-explanatory. */
class UpdateQuery {
std::string table;
std::string _where;
std::vector<std::string> fields;
std::vector<std::string> values;
public:
UpdateQuery(const std::string& t) : table(t), _where("True") {}
UpdateQuery& where(const Expr& e);
UpdateQuery& set(const FieldType& f, const std::string& value);
operator std::string() const;
std::string asString() const { return this->operator std::string(); }
};
}
#endif
| 26.181818 | 73 | 0.69213 | [
"vector"
] |
7a41a69accbcb9a16104077ac8e650eda57d6e89 | 5,177 | hpp | C++ | plugins/xml/node.hpp | Flusspferd/flusspferd | f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5 | [
"MIT"
] | 7 | 2015-06-08T09:59:36.000Z | 2021-02-27T18:45:17.000Z | plugins/xml/node.hpp | Flusspferd/flusspferd | f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5 | [
"MIT"
] | null | null | null | plugins/xml/node.hpp | Flusspferd/flusspferd | f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5 | [
"MIT"
] | 3 | 2016-07-06T20:47:01.000Z | 2021-06-30T19:09:47.000Z | // vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_XML_NODE_HPP
#define FLUSSPFERD_XML_NODE_HPP
#include "node_map.hpp"
#include <DOM/Node.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace xml_plugin {
namespace phoenix = boost::phoenix;
namespace args = phoenix::arg_names;
#define enum_prop(x) (#x, constant, int(Arabica::DOM::Node_base:: x))
FLUSSPFERD_CLASS_DESCRIPTION(
node,
(constructible, false)
(full_name, "xml.Node")
(constructor_name, "Node")
(constructor_properties,
enum_prop(ELEMENT_NODE)
enum_prop(ATTRIBUTE_NODE)
enum_prop(TEXT_NODE)
enum_prop(CDATA_SECTION_NODE)
enum_prop(ENTITY_REFERENCE_NODE)
enum_prop(ENTITY_NODE)
enum_prop(PROCESSING_INSTRUCTION_NODE)
enum_prop(COMMENT_NODE)
enum_prop(DOCUMENT_NODE)
enum_prop(DOCUMENT_TYPE_NODE)
enum_prop(DOCUMENT_FRAGMENT_NODE)
enum_prop(NOTATION_NODE)
// Do we need max type? Guess it doesn't hurt
enum_prop(MAX_TYPE)
)
(properties,
("nodeName", getter, getNodeName)
("nodeValue", getter_setter, (getNodeValue, setNodeValue))
("nodeType", getter, getNodeType)
("parentNode", getter, getParentNode)
("childNodes", getter, getChildNodes)
("firstChild", getter, getFirstChild)
("lastChild", getter, getLastChild)
("previousSibling", getter, getPreviousSibling)
("nextSibling", getter, getNextSibling)
("attributes", getter, getAttributes)
("ownerDocument", getter, getOwnerDocument)
("namespaceURI", getter, getNamespaceURI)
("prefix", getter_setter, (getPrefix, setPrefix))
("localName", getter, getLocalName)
)
(methods,
("toString", bind, to_string)
("insertBefore", bind, insertBefore)
("replaceChild", bind, replaceChild)
("removeChild", bind, removeChild)
("appendChild", bind, appendChild)
("hasChildNodes", bind, hasChildNodes)
("cloneNode", bind, cloneNode)
("normalize", bind, normalize)
("isSupported", bind, isSupported)
("hasAttributes", bind, hasAttributes)
)
)
#undef enum_prop
{
public:
typedef arabica_node wrapped_type;
node(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map);
virtual ~node();
arabica_node const & underlying_impl() { return node_; }
string_type to_string();
// Property getters/setters
string_type getNodeName() { return node_.getNodeName(); }
flusspferd::value getNodeValue();
void setNodeValue(string_type const &s);
int getNodeType() { return node_.getNodeType(); }
object getParentNode() { return get_node(node_.getParentNode()); }
object getChildNodes();
object getFirstChild() { return get_node(node_.getFirstChild()); }
object getLastChild() { return get_node(node_.getLastChild()); }
object getPreviousSibling() { return get_node(node_.getPreviousSibling()); }
object getNextSibling() { return get_node(node_.getNextSibling()); }
object getAttributes();
object getOwnerDocument();
flusspferd::value getNamespaceURI();
flusspferd::value getPrefix();
void setPrefix(string_type const &s);
string_type getLocalName() { return node_.getLocalName(); }
// Methods
object insertBefore(node &newChild, node &refChild);
object replaceChild(node &newChild, node &oldChild);
object removeChild(node &oldChild);
object appendChild(node &newChild);
bool hasChildNodes() { return node_.hasChildNodes(); }
object cloneNode(bool deep);
void normalize() { node_.normalize(); }
bool isSupported(string_type feat, string_type ver)
{ return node_.isSupported(feat, ver); }
bool hasAttributes() { return node_.hasAttributes(); }
protected:
node(flusspferd::object const &proto);
// Used by document::document
node(flusspferd::object const &proto, wrapped_type const &node);
wrapped_type node_;
weak_node_map node_map_;
object get_node(wrapped_type const &node);
};
}
#endif
| 34.513333 | 85 | 0.723392 | [
"object"
] |
7a56d4da7cf1eb19c055f588d3cbc6a62fcbbe77 | 6,081 | cpp | C++ | tests/unittest/test_queue_ctors.cpp | digital-stage/eventpp | a0978f91f9d74a5943ed668b3fe15d64b0675b5c | [
"Apache-2.0"
] | 685 | 2018-05-13T03:59:19.000Z | 2022-03-31T22:43:43.000Z | tests/unittest/test_queue_ctors.cpp | digital-stage/eventpp | a0978f91f9d74a5943ed668b3fe15d64b0675b5c | [
"Apache-2.0"
] | 32 | 2018-06-01T03:15:13.000Z | 2022-01-18T09:23:06.000Z | tests/unittest/test_queue_ctors.cpp | digital-stage/eventpp | a0978f91f9d74a5943ed668b3fe15d64b0675b5c | [
"Apache-2.0"
] | 128 | 2018-05-13T06:41:58.000Z | 2022-03-30T16:58:10.000Z | // eventpp library
// Copyright (C) 2018 Wang Qi (wqking)
// Github: https://github.com/wqking/eventpp
// 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 "test.h"
#define private public
#include "eventpp/eventqueue.h"
#undef private
TEST_CASE("EventQueue, copy constructor from empty EventQueue")
{
using EQ = eventpp::EventQueue<int, void ()>;
EQ queue;
REQUIRE(queue.eventCallbackListMap.empty());
EQ copiedQueue(queue);
REQUIRE(copiedQueue.eventCallbackListMap.empty());
REQUIRE(copiedQueue.eventCallbackListMap.empty());
}
TEST_CASE("EventQueue, copy constructor from non-empty EventQueue")
{
using EQ = eventpp::EventQueue<int, void ()>;
EQ queue;
constexpr int event = 3;
std::vector<int> dataList(3);
queue.appendListener(event, [&dataList]() {
++dataList[0];
});
queue.appendListener(event, [&dataList]() {
++dataList[1];
});
REQUIRE(dataList == std::vector<int> { 0, 0, 0 });
queue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 1, 1, 0 });
EQ copiedQueue(queue);
copiedQueue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 2, 2, 0 });
copiedQueue.appendListener(event, [&dataList]() {
++dataList[2];
});
copiedQueue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 3, 3, 1 });
queue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 4, 4, 1 });
}
TEST_CASE("EventQueue, assign from non-empty EventQueue")
{
using EQ = eventpp::EventQueue<int, void ()>;
EQ queue;
constexpr int event = 3;
std::vector<int> dataList(3);
queue.appendListener(event, [&dataList]() {
++dataList[0];
});
queue.appendListener(event, [&dataList]() {
++dataList[1];
});
REQUIRE(dataList == std::vector<int> { 0, 0, 0 });
queue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 1, 1, 0 });
EQ assignedQueue;
assignedQueue = queue;
assignedQueue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 2, 2, 0 });
assignedQueue.appendListener(event, [&dataList]() {
++dataList[2];
});
assignedQueue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 3, 3, 1 });
queue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 4, 4, 1 });
}
TEST_CASE("EventQueue, move constructor from empty EventQueue")
{
using EQ = eventpp::EventQueue<int, void ()>;
EQ queue;
REQUIRE(queue.eventCallbackListMap.empty());
EQ movedQueue(std::move(queue));
REQUIRE(movedQueue.eventCallbackListMap.empty());
REQUIRE(queue.eventCallbackListMap.empty());
}
TEST_CASE("EventQueue, move constructor from non-empty EventQueue")
{
using EQ = eventpp::EventQueue<int, void ()>;
EQ queue;
constexpr int event = 3;
std::vector<int> dataList(3);
queue.appendListener(event, [&dataList]() {
++dataList[0];
});
queue.appendListener(event, [&dataList]() {
++dataList[1];
});
queue.appendListener(event, [&dataList]() {
++dataList[2];
});
REQUIRE(! queue.eventCallbackListMap.empty());
REQUIRE(dataList == std::vector<int> { 0, 0, 0 });
queue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 1, 1, 1 });
EQ movedQueue(std::move(queue));
REQUIRE(! movedQueue.eventCallbackListMap.empty());
REQUIRE(queue.eventCallbackListMap.empty());
movedQueue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 2, 2, 2 });
queue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 2, 2, 2 });
}
TEST_CASE("EventQueue, move assign from non-empty EventQueue")
{
using EQ = eventpp::EventQueue<int, void ()>;
EQ queue;
constexpr int event = 3;
std::vector<int> dataList(3);
queue.appendListener(event, [&dataList]() {
++dataList[0];
});
queue.appendListener(event, [&dataList]() {
++dataList[1];
});
REQUIRE(dataList == std::vector<int> { 0, 0, 0 });
queue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 1, 1, 0 });
EQ assignedQueue;
assignedQueue = std::move(queue);
assignedQueue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 2, 2, 0 });
assignedQueue.appendListener(event, [&dataList]() {
++dataList[2];
});
assignedQueue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 3, 3, 1 });
queue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 3, 3, 1 });
}
TEST_CASE("EventQueue, swap with self")
{
using EQ = eventpp::EventQueue<int, void ()>;
EQ swappedQueue;
REQUIRE(swappedQueue.eventCallbackListMap.empty());
using std::swap;
swap(swappedQueue, swappedQueue);
REQUIRE(swappedQueue.eventCallbackListMap.empty());
}
TEST_CASE("EventQueue, swap with empty EventQueue")
{
using EQ = eventpp::EventQueue<int, void ()>;
EQ queue;
REQUIRE(queue.eventCallbackListMap.empty());
EQ swappedQueue;
using std::swap;
swap(swappedQueue, queue);
REQUIRE(swappedQueue.eventCallbackListMap.empty());
queue.appendListener(1, []() {});
REQUIRE(! queue.eventCallbackListMap.empty());
REQUIRE(swappedQueue.eventCallbackListMap.empty());
}
TEST_CASE("EventQueue, swap with non-empty EventQueue")
{
using EQ = eventpp::EventQueue<int, void ()>;
EQ queue;
constexpr int event = 3;
std::vector<int> dataList(3);
queue.appendListener(event, [&dataList]() {
++dataList[0];
});
queue.appendListener(event, [&dataList]() {
++dataList[1];
});
EQ swappedQueue;
swappedQueue.appendListener(event, [&dataList]() {
++dataList[1];
});
swappedQueue.appendListener(event, [&dataList]() {
++dataList[2];
});
queue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 1, 1, 0 });
using std::swap;
swap(swappedQueue, queue);
queue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 1, 2, 1 });
swappedQueue.dispatch(event);
REQUIRE(dataList == std::vector<int> { 2, 3, 1 });
}
| 26.098712 | 75 | 0.68788 | [
"vector"
] |
7a5cb40d6d82b4394f895f7746a1e3e8fadc4261 | 8,298 | hpp | C++ | pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entry.hpp | robfalck/pyoptsparse | c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d | [
"CNRI-Python"
] | 26 | 2020-08-25T16:16:21.000Z | 2022-03-10T08:23:57.000Z | pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entry.hpp | robfalck/pyoptsparse | c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d | [
"CNRI-Python"
] | 90 | 2020-08-24T23:02:47.000Z | 2022-03-29T13:48:15.000Z | pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entry.hpp | robfalck/pyoptsparse | c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d | [
"CNRI-Python"
] | 25 | 2020-08-24T19:28:24.000Z | 2022-01-27T21:17:37.000Z | /*-------------------------------------------------------------------------------------*/
/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */
/* */
/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */
/* Charles Audet - Ecole Polytechnique, Montreal */
/* Gilles Couture - Ecole Polytechnique, Montreal */
/* John Dennis - Rice University, Houston */
/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */
/* Christophe Tribes - Ecole Polytechnique, Montreal */
/* */
/* funded in part by AFOSR and Exxon Mobil */
/* */
/* Author: Sebastien Le Digabel */
/* */
/* Contact information: */
/* Ecole Polytechnique de Montreal - GERAD */
/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */
/* e-mail: nomad@gerad.ca */
/* phone : 1-514-340-6053 #6928 */
/* fax : 1-514-340-5665 */
/* */
/* This program is free software: you can redistribute it and/or modify it under the */
/* terms of the GNU Lesser General Public License as published by the Free Software */
/* Foundation, either version 3 of the License, or (at your option) any later */
/* version. */
/* */
/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */
/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */
/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License along */
/* with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/* You can find information on the NOMAD software at www.gerad.ca/nomad */
/*-------------------------------------------------------------------------------------*/
/**
\file Parameter_Entry.hpp
\brief Parameter entry (headers)
\author Sebastien Le Digabel
\date 2010-04-05
\see Parameter_Entry.cpp
*/
#ifndef __PARAMETER_ENTRY__
#define __PARAMETER_ENTRY__
#include "Display.hpp"
#include "Uncopyable.hpp"
namespace NOMAD {
/// Parameter entry.
/**
- Describes the data relative to a parameter in a parameters file.
- Objets of this class are stored in a NOMAD::Parameter_Entries object.
*/
class Parameter_Entry : private NOMAD::Uncopyable {
private:
std::string _name; ///< Name of the parameter.
std::list<std::string> _values; ///< List of values for the parameter.
bool _ok; ///< If the parameter is valid.
bool _unique; ///< If the parameter is unique.
Parameter_Entry * _next; ///< Acces to the next parameter.
/// If the parameter has been interpreted.
bool _has_been_interpreted;
public:
/// Constructor.
/**
Ignores all entries after \c '#'.
\param entry A string describing the parameter entry -- \b IN.
\param remove_comments A boolean equal to \c true if entries after
\c '#' are ignored -- \b IN
-- \b optional (default = \c true).
*/
Parameter_Entry ( const std::string & entry , bool remove_comments = true );
/// Destructor.
virtual ~Parameter_Entry ( void ) {}
/*---------------*/
/* GET methods */
/*---------------*/
/// Access to the name of the parameter.
/**
\return The name.
*/
const std::string & get_name ( void ) const { return _name; }
/// Access to the parameter values.
/**
\return The parameter values as a list of strings.
*/
const std::list<std::string> & get_values ( void ) const { return _values; }
/// Access to the number of values of the parameter.
/**
\return The number of values.
*/
int get_nb_values ( void ) const { return static_cast<int>(_values.size()); }
/// Access to the \c _ok flag.
/**
This flag is equal to \c true if the parameter entry is well defined.
\return A boolean equal to \c true if the parameter is valid.
*/
bool is_ok ( void ) const { return _ok; }
/// Access to the \c _unique flag.
/**
This flag is decided when a parameters file is read.
\return A boolean equal to \c true if the parameter is unique
in a parameters file.
*/
bool is_unique ( void ) const { return _unique; }
/// Access to another NOMAD::Parameter_Entry.
/**
NOMAD::Parameter_Entry objects are stored in a NOMAD::Parameter_Entries
object. The link between elements is assumed by the \c _next member
returned by this function.
\return A pointer to the next entry.
*/
Parameter_Entry * get_next ( void ) const { return _next; }
/// Access to the \c _has_been_interpreted flag.
/**
\return A boolean equal to \c true if the parameter has already
been interpreted.
*/
bool has_been_interpreted ( void ) const { return _has_been_interpreted; }
/*---------------*/
/* SET methods */
/*---------------*/
/// Set the \c _next pointer.
/**
\param p A pointer to the next NOMAD::Parameter_Entry to be inserted -- \b IN.
*/
void set_next ( Parameter_Entry * p ) { _next = p; }
/// Set the \c _unique flag.
/**
\param u Value of the flag -- \b IN.
*/
void set_unique ( bool u ) { _unique = u; }
/// Set the \c _has_been_interpreted flag. to \c true.
void set_has_been_interpreted ( void ) { _has_been_interpreted = true; }
/// Comparison with another entry.
/**
The comparison is based on the parameter name.
\param p The right-hand side object -- \b IN.
\return A boolean equal to \c true if \c this->_name \c < \c p._name.
*/
bool operator < ( const Parameter_Entry & p ) const { return _name < p._name; }
/// Display.
/**
\param out The NOMAD::Display object -- \b IN.
*/
void display ( const NOMAD::Display & out ) const;
};
/// Allows the comparison of two NOMAD::Parameter_Entry objects.
struct Parameter_Entry_Comp {
/// Comparison of two NOMAD::Parameter_Entry objects.
/**
\param p1 Pointer to the first NOMAD::Parameter_Entry -- \b IN.
\param p2 Pointer to the second NOMAD::Parameter_Entry -- \b IN.
\return A boolean equal to \c true if \c *p1 \c < \c *p2.
*/
bool operator() ( const Parameter_Entry * p1 , const Parameter_Entry * p2 ) const
{
return (*p1 < *p2);
}
};
/// Display a NOMAD::Parameter_Entry object.
/**
\param out The NOMAD::Display object -- \b IN.
\param e The NOMAD::Parameter_Entry object to be displayed -- \b IN.
\return The NOMAD::Display object.
*/
inline const NOMAD::Display & operator << ( const NOMAD::Display & out ,
const NOMAD::Parameter_Entry & e )
{
e.display ( out );
return out;
}
}
#endif
| 41.49 | 91 | 0.498313 | [
"mesh",
"object"
] |
7a5f8fc6bfddd955be4dc61a11528e6bd72e971f | 26,796 | cpp | C++ | platform/windows/Corona.Simulator/Simulator.cpp | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | platform/windows/Corona.Simulator/Simulator.cpp | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | platform/windows/Corona.Simulator/Simulator.cpp | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <Winver.h>
#include <gdiplus.h>
#include <io.h>
#include <Fcntl.h>
#include "Simulator.h"
#include "MainFrm.h"
#include "SimulatorDoc.h"
#include "SimulatorDocTemplate.h"
#include "SimulatorView.h"
#include "resource.h"
#include "WinString.h"
#include "CoronaInterface.h"
#include "WinGlobalProperties.h" // set the properties
#include "CoronaInterface.h" // player interface, appDeinit()
#include "Core/Rtt_Build.h"
#include "Interop\Ipc\AsyncPipeReader.h"
#include "Rtt_Version.h" // Rtt_STRING_BUILD and Rtt_STRING_BUILD_DATE
#ifdef _DEBUG
# define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Single Instance Control
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Name of the semaphore used to control the number of instances running
LPCTSTR SINGLE_INSTANCE_OBJECT_NAME = _T("com.coronalabs.windows.single_instance.v1");
// This data is shared by all instances, so that when we
// detect that we have another instance running, we can use
// this to send messages to the window of that first instance:
#pragma data_seg (".SingleInstance")
LONG SimFirstInstanceHwnd = 0;
// If you want to add anything here the crucial thing to remember is that
// any shared data items must be initialized to some value
#pragma data_seg ()
// Tell the linker about our shared data segment
#pragma comment(linker, "/section:.SingleInstance,RWS")
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Static Member Variables
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>The one and only CSimulatorApp object.</summary>
CSimulatorApp theApp;
// CSimulatorApp initialization
// Copied from appcore.cpp
AFX_STATIC_DATA const TCHAR _afxFileSection[] = _T("Recent File List");
AFX_STATIC_DATA const TCHAR _afxFileEntry[] = _T("File%d");
AFX_STATIC_DATA const TCHAR _afxPreviewSection[] = _T("Settings");
AFX_STATIC_DATA const TCHAR _afxPreviewEntry[] = _T("PreviewPages");
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CSimulatorApp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CSimulatorApp::CSimulatorApp()
{
// Place all significant initialization in InitInstance
m_isDebugModeEnabled = false;
m_isLuaExitAllowed = false;
m_isConsoleEnabled = true;
m_isStopBuildRequested = false;
}
// InitInstance - initialize the application
BOOL CSimulatorApp::InitInstance()
{
// Load the simulator version of the Corona library, which is only used by plugins to link against by name.
// This is a thin proxy DLL which forwards Solar2D's public APIs to this EXE's statically linked Solar2D APIs.
// This ensures that plugins link with the simulator's library and not the non-simulator version of the library.
CString coronaLibraryPath = GetApplicationDir() + _T("\\Resources\\CoronaLabs.Corona.Native.dll");
if (!Rtt_VERIFY(::LoadLibrary(coronaLibraryPath)))
{
CString message =
_T("Failed to load the Solar2D Simulator's library.\r\n")
_T("This might mean that your Solar2D installation is corrupted.\r\n")
_T("You may be able to fix this by re-installing the Solar2D.");
AfxMessageBox(message, MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}
CWinApp::InitInstance();
// Hacks to make life easier
CString ret = GetProfileString(L"Preferences", L"debugBuildProcess", L"");
if (ret.GetLength() && _wgetenv(L"DEBUG_BUILD_PROCESS") == NULL) {
_wputenv_s(L"DEBUG_BUILD_PROCESS", ret);
}
if (_wgetenv(L"CORONA_PATH") == NULL) {
TCHAR coronaDir[MAX_PATH];
GetModuleFileName(NULL, coronaDir, MAX_PATH);
TCHAR* end = StrRChr(coronaDir, NULL, '\\');
if (end)
{
end[1] = 0;
_wputenv_s(L"CORONA_PATH", coronaDir);
}
}
// Initialize WinGlobalProperties object which mirrors theApp properties
// Make sure this is done before accessing any Solar2D functions
WinString strRegistryKey, strRegistryProfile, strResourcesDir;
WinString stringTranscoder(L"Ansca Corona");
SetRegistryKey(stringTranscoder.GetTCHAR());
strRegistryKey.SetTCHAR(m_pszRegistryKey);
WinString profileName(L"Corona Simulator");
m_pszProfileName = _tcsdup(profileName.GetTCHAR());
strRegistryProfile.SetTCHAR(m_pszProfileName);
strResourcesDir.SetTCHAR(GetResourceDir());
GetWinProperties()->SetRegistryKey(strRegistryKey.GetUTF8());
GetWinProperties()->SetRegistryProfile(strRegistryProfile.GetUTF8());
GetWinProperties()->SetResourcesDir(strResourcesDir.GetUTF8());
// See if we ran successfully without a crash last time (mostly
// used to detect crappy video drivers that crash us)
int lastRunSucceeded = GetProfileInt(REGISTRY_SECTION, REGISTRY_LAST_RUN_SUCCEEDED, 1);
if (!lastRunSucceeded)
{
CString message =
_T("Solar2D Simulator crashed last time it was run\n\n")
_T("This can happen because Windows or the video driver need to be updated. ")
_T("If it crashes again, make sure the software for your video card is up to date (you ")
_T("may need to visit the manufacturer's web site to check this) and ensure that all ")
_T("available Windows updates have been installed.\n\n")
_T("If the problem persists, contact support@solar2d.com including as much detail as possible.");
SHMessageBoxCheck(NULL,
message,
TEXT("Solar2D Simulator"),
MB_OK | MB_ICONEXCLAMATION,
IDOK,
L"CoronaShowCrashWarning");
}
else
{
#ifndef Rtt_DEBUG
// Set the telltale to 0 so we'll know if we don't reset it in ExitInstance()
// (but don't do it for debug builds which are probably running in the debugger)
WriteProfileInt(REGISTRY_SECTION, REGISTRY_LAST_RUN_SUCCEEDED, 0);
#endif
}
// Parse for command line arguments.
// Supports arguments starting with '-' and '/'. Arguments are not case sensitive.
CString commandLine = m_lpCmdLine;
commandLine.MakeLower();
commandLine.Replace(TCHAR('/'), TCHAR('-'));
// Don't buffer stdout and stderr as this makes debugging easier
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
// Have we been asked to run just a single instance at a time?
if (commandLine.Find(_T("-singleton")) >= 0)
{
// Check whether we have already an instance running
// (even if we get ERROR_ALREADY_EXISTS we increment the reference count so the semaphore
// will exist so long as there is a running Simulator)
HANDLE hSingleInstanceSemaphore = ::CreateSemaphore(NULL, 0, 1, SINGLE_INSTANCE_OBJECT_NAME);
DWORD err = ::GetLastError();
if (err == ERROR_ALREADY_EXISTS)
{
// The semaphore exists already, must have been created by a previous instance, tell it to quit
HWND windowHandle = (HWND)SimFirstInstanceHwnd;
ASSERT(windowHandle != 0);
if (::IsWindow(windowHandle))
{
// Fetch the other single instance app's process handle.
HANDLE processHandle = nullptr;
DWORD processId = 0;
::GetWindowThreadProcessId(windowHandle, &processId);
if (processId)
{
processHandle = ::OpenProcess(SYNCHRONIZE, FALSE, processId);
}
// Tell the other single instance app to quit, making this app instance the single instance.
if (::IsWindowEnabled(windowHandle))
{
// The app isn't displaying a modal dialog.
// This means we can close it gracefully with a close message.
::PostMessage(windowHandle, WM_CLOSE, 0, 0);
}
else
{
// *** The app is currently displaying a modal dialog. ***
// Stop the app's currently running Solar2D project. Avoids file locking issues, like with fonts.
::PostMessage(windowHandle, WM_COMMAND, ID_FILE_CLOSE, 0);
// Send a quit message to exit the app. (Not a clean way to exit an app.)
// Note: Child dialogs and Doc/View will not receive close messages because of this.
::PostMessage(windowHandle, WM_QUIT, 0, 0);
}
// Wait for the other app to exit before continuing.
// This way it's last saved registry settings will be available to this app.
if (processHandle)
{
::WaitForSingleObject(processHandle, 5000);
::CloseHandle(processHandle);
}
}
}
}
// Initialize GDIplus early to avoid crashes when double-clicking on a .lua file
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL);
// Handle the rest of the command line arguments.
if (commandLine.Find(_T("-debug")) >= 0)
{
m_isDebugModeEnabled = true;
}
if (commandLine.Find(_T("-allowluaexit")) >= 0)
{
m_isLuaExitAllowed = true;
}
if (commandLine.Find(_T("-no-console")) >= 0)
{
// No console is required, caller will grab our output from stdout and stderr
m_isConsoleEnabled = false;
}
// Display a logging window, if enabled.
if (m_isConsoleEnabled)
{
// Use the following Solar2D application as our logging window.
WinString outputViewerFilePath(GetApplicationDir());
WinString outputViewerArgs;
outputViewerArgs.Format("/parentProcess:%ld", ::GetCurrentProcessId());
outputViewerArgs.Append(L" /disableClose /windowName:\"Corona Simulator Console\"");
outputViewerFilePath.Append(L"\\Corona.Console.exe");
Interop::Ipc::Process::LaunchSettings launchSettings{};
launchSettings.FileNamePath = outputViewerFilePath.GetUTF16();
launchSettings.CommandLineArguments = outputViewerArgs.GetTCHAR();
launchSettings.IsStdInRedirectionEnabled = true;
auto launchResult = Interop::Ipc::Process::LaunchUsing(launchSettings);
m_outputViewerProcessPointer = launchResult.GetValue();
if (m_outputViewerProcessPointer)
{
auto stdInHandle = m_outputViewerProcessPointer->GetStdInHandle();
int stdInFD = _open_osfhandle((intptr_t)stdInHandle, _O_TEXT);
if (!GetConsoleWindow()) {
AllocConsole();
ShowWindow(GetConsoleWindow(), SW_HIDE);
}
::SetStdHandle(STD_OUTPUT_HANDLE, stdInHandle);
::SetStdHandle(STD_ERROR_HANDLE, stdInHandle);
FILE* notused;
freopen_s(¬used, "CONOUT$", "w", stdout);
freopen_s(¬used, "CONOUT$", "w", stderr);
int res = _dup2(stdInFD, _fileno(stdout));
res = _dup2(stdInFD, _fileno(stderr));
std::ios::sync_with_stdio();
}
}
// Stop MFC from flashing the simulator window on startup.
m_nCmdShow = SW_HIDE;
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
AfxInitRichEdit();
AfxEnableControlContainer();
int maxRecentFileCount = 10;
LoadStdProfileSettings(maxRecentFileCount); // Load standard INI file options (including MRU)
// Delete the m_pRecentFileList created in the LoadStdProfileSettings.
// We want to show directory name, not filename (which is always main.lua)
delete m_pRecentFileList;
// The nSize argument of the constructor is set to four because the
// LoadStdProfileSettings takes a default of four. If you specify a
// different value for the nMaxMRU argument you need to change the
// nSize argument for the constructor call.
m_pRecentFileList = new CRecentDirList(0, _afxFileSection, _afxFileEntry, maxRecentFileCount);
m_pRecentFileList->ReadList();
// Override default CDocManager class to manage initial directory for open file dialog
// Initial directory set below
delete m_pDocManager;
m_pDocManager = new CSimDocManager();
// Register the simulator's document template.
// This is used to manage an open Solar2D project with an MFC SDI document/view interface.
// Note: This custom doc template allows the simulator to open Solar2D projects by directory or "main.lua".
auto pDocTemplate = new CSimulatorDocTemplate();
if (!pDocTemplate)
{
return FALSE;
}
AddDocTemplate(pDocTemplate);
// Do this before any of the ways app can exit (including not authorized)
printf("\nSolar2D Simulator %d.%d (%s %s)\n\n", Rtt_BUILD_YEAR, Rtt_BUILD_REVISION, __DATE__, __TIME__);
// Load user preferences from registry
// Initialize member variables used to write out preferences
SetWorkingDir(GetProfileString(REGISTRY_SECTION, REGISTRY_WORKINGDIR, GetResourceDir()));
m_sDeviceName = GetProfileString( REGISTRY_SECTION, REGISTRY_DEVICE, _T("") );
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Fake out command line since we want to automatically open the last open project.
// This is necessary because ProcessShellCommand() initiates a "New File"
// operation if there is no filename on the command line and this is very
// hard to unravel and inject the remembered filename into.
if (!m_isDebugModeEnabled && (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew))
{
CRecentFileList *recentFileListPointer = GetRecentFileList();
if (recentFileListPointer && (recentFileListPointer->GetSize() > 0))
{
auto lastRanFilePath = (*recentFileListPointer)[0];
if (!lastRanFilePath.IsEmpty() && ::PathFileExists(lastRanFilePath))
{
// We have a remembered last project so pretend we were asked to open it on the command line.
cmdInfo.m_nShellCommand = CCommandLineInfo::FileOpen;
cmdInfo.m_strFileName = lastRanFilePath;
}
}
}
// If a Solar2D project directory was provided at the command line, then append a "main.lua" file to the path.
if (!cmdInfo.m_strFileName.IsEmpty() && ::PathIsDirectory(cmdInfo.m_strFileName))
{
TCHAR mainLuaFilePath[2048];
mainLuaFilePath[0] = _T('\0');
::PathCombine(mainLuaFilePath, cmdInfo.m_strFileName, _T("main.lua"));
if (::PathFileExists(mainLuaFilePath))
{
cmdInfo.m_strFileName = mainLuaFilePath;
}
}
// Dispatch commands specified on the command line. Will return FALSE if
// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
// This will cause a new "document" to be opened and most initialization to take place
if (!ProcessShellCommand(cmdInfo))
{
return FALSE;
}
// If Resources dir doesn't exist, exit.
CString sDir = GetResourceDir();
if (!CheckDirExists(sDir))
{
CString msg;
msg.Format( IDS_DIR_s_NOTFOUND_INSTALL, sDir );
::AfxMessageBox( msg );
return FALSE;
}
// Get the current window size (it's been calculated from the current app)
CRect cwr;
m_pMainWnd->GetWindowRect(&cwr);
m_WP.rcNormalPosition.left = GetProfileInt(REGISTRY_SECTION, REGISTRY_XPOS, REGISTRY_XPOS_DEFAULT);
m_WP.rcNormalPosition.top = GetProfileInt(REGISTRY_SECTION, REGISTRY_YPOS, REGISTRY_YPOS_DEFAULT);
// Don't use any remembered size as it might not be for the same app
m_WP.rcNormalPosition.right = m_WP.rcNormalPosition.left + (cwr.right - cwr.left);
m_WP.rcNormalPosition.bottom = m_WP.rcNormalPosition.top + (cwr.bottom - cwr.top);
m_WP.length = sizeof(WINDOWPLACEMENT);
const WINDOWPLACEMENT * wp = &m_WP;
// Places the window on the screen even if the information in WINDOWPLACEMENT puts the window off screen
SetWindowPlacement(*m_pMainWnd, wp);
// Remember the main window's HWND in the shared memory area so other instances
// can find it and tell us to do things
SimFirstInstanceHwnd = (LONG) (m_pMainWnd->GetSafeHwnd());
// Set main window size based on device
CMainFrame *pMainFrm = (CMainFrame *)m_pMainWnd;
CSimulatorView *pView = (CSimulatorView *)pMainFrm->GetActiveView();
// The one and only window has been initialized, so show and update it
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
// call DragAcceptFiles only if there's a suffix
// In an SDI app, this should occur after ProcessShellCommand
// Enable drag/drop open
m_pMainWnd->DragAcceptFiles();
// This application has been initialized and is authorized to continue.
// Returning TRUE allows this application to continue running.
return TRUE;
}
/// Gets this application's absolute path without the file name.
CString CSimulatorApp::GetApplicationDir()
{
// Fetch the app's absolute path without the file name, if not done so already.
if (m_sApplicationDir.IsEmpty())
{
const int MAX_PATH_LENGTH = 1024;
CString applicationPath;
int result;
int index;
result = ::GetModuleFileName(nullptr, applicationPath.GetBuffer(MAX_PATH_LENGTH), MAX_PATH_LENGTH);
applicationPath.ReleaseBuffer((int)result);
if (result > 0)
{
// Remove the file name from the path string.
index = applicationPath.ReverseFind(_T('\\'));
if (index > 0)
{
m_sApplicationDir = applicationPath.Left(index);
}
}
}
// Return this application's absolute path.
return m_sApplicationDir;
}
// GetResourceDir - Return directory for skin image files, and other needed files.
// Path is AppPath\Resources
CString CSimulatorApp::GetResourceDir()
{
if (m_sResourceDir.IsEmpty())
{
m_sResourceDir = GetApplicationDir();
m_sResourceDir += _T("\\Resources");
}
return m_sResourceDir;
}
bool CSimulatorApp::ShouldShowNXBuildDlg()
{
bool show = getenv("NINTENDO_SDK_ROOT") != NULL;
return show;
}
// CheckPathExists - return true if the file/directory exists.
// Make sure paths don't have trailing backslashes
bool CSimulatorApp::CheckPathExists(LPCTSTR path)
{
WIN32_FIND_DATA data;
HANDLE handle = FindFirstFile(path,&data);
if (handle != INVALID_HANDLE_VALUE)
{
FindClose(handle);
return true;
}
return false;
}
// CheckDirExists - return true if dirName is directory and exists
// Make sure paths don't have trailing backslashes
bool CSimulatorApp::CheckDirExists(LPCTSTR dirName)
{
WIN32_FIND_DATA data;
HANDLE handle = FindFirstFile(dirName,&data);
if (handle != INVALID_HANDLE_VALUE)
{
FindClose(handle);
return (0 != (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY));
}
return false;
}
// GetWorkingDir - return the directory to use for File Open dialogs
// Used to save value to registry on exit
CString CSimulatorApp::GetWorkingDir()
{
return ((CSimDocManager *)m_pDocManager)->GetInitialDir();
}
// SetWorkingDir - set the directory to use for File Open dialogs
// Remembered in registry on app exit/init, and set when project is opened
void CSimulatorApp::SetWorkingDir( CString sDir )
{
((CSimDocManager *)m_pDocManager)->SetInitialDir( sDir );
}
// ExitInstance - save position, etc. to registry
int CSimulatorApp::ExitInstance()
{
// Check if we're exiting before we initialized.
if (m_pDocManager == nullptr)
{
return CWinApp::ExitInstance();
}
// Save user preferences to registry
if (!GetDeviceName().IsEmpty())
{
WriteProfileString( REGISTRY_SECTION, REGISTRY_DEVICE, GetDeviceName());
}
if (!GetWorkingDir().IsEmpty())
{
WriteProfileString( REGISTRY_SECTION, REGISTRY_WORKINGDIR, GetWorkingDir() );
}
// Write window position (saved in CMainFrame::OnClose)
WriteProfileInt(REGISTRY_SECTION, REGISTRY_XPOS, m_WP.rcNormalPosition.left);
WriteProfileInt( REGISTRY_SECTION, REGISTRY_YPOS, m_WP.rcNormalPosition.top);
// Close the logging window if currently running.
if (m_outputViewerProcessPointer)
{
// Re-enable the logging window's close [x] button.
// Note: This window will ignore WM_CLOSE messages while the close button is disabled.
auto outputViewerWindowHandle = m_outputViewerProcessPointer->FetchMainWindowHandle();
if (outputViewerWindowHandle)
{
auto menuHandle = ::GetSystemMenu(outputViewerWindowHandle, FALSE);
if (menuHandle)
{
::EnableMenuItem(menuHandle, SC_CLOSE, MF_ENABLED);
}
}
// Close the logging window gracefully via a WM_CLOSE message.
m_outputViewerProcessPointer->RequestCloseMainWindow();
m_outputViewerProcessPointer = nullptr;
if (!GetConsoleWindow()) {
AllocConsole();
ShowWindow(GetConsoleWindow(), SW_HIDE);
}
FILE* notused;
freopen_s(¬used, "CONOUT$", "w", stdout);
freopen_s(¬used, "CONOUT$", "w", stderr);
}
// Uninitialize GDIplus
Gdiplus::GdiplusShutdown(m_gdiplusToken);
// If we got this far, we ran successfully without a crash (mostly
// used to detect crappy video drivers that crash us)
WriteProfileInt(REGISTRY_SECTION, REGISTRY_LAST_RUN_SUCCEEDED, 1);
// Exit this application.
return CWinApp::ExitInstance();
}
// PutWP - save window placement so it can be written to registry
void CSimulatorApp::PutWP(const WINDOWPLACEMENT& newval)
{
m_WP = newval;
m_WP.length = sizeof(m_WP);
}
/////////////////////////////////////////////////////////////////////////////////////////
// CRecentDirList
/////////////////////////////////////////////////////////////////////////////////////////
/* This class is a subclass of CRecentFileList which overrides the
* GetDisplayName() member function to display the directory name instead of
* the filename, which is always main.lua.
*/
BOOL CRecentDirList::GetDisplayName( CString &strName, int nIndex, LPCTSTR lpszCurDir, int nCurDir, BOOL bAtLeastName = 1) const
{
// Change entry at nIndex to remove "main.lua"
CString sOrigPath = m_arrNames[nIndex];
CString sDirPath = CCoronaProject::RemoveMainLua( sOrigPath );
m_arrNames[nIndex] = sDirPath;
BOOL bRetval = CRecentFileList::GetDisplayName( strName, nIndex, lpszCurDir, nCurDir, bAtLeastName );
// Restore entry
m_arrNames[nIndex] = sOrigPath;
return bRetval;
}
////////////////////////////////////////////////////////////////////////////////////////////
// CSimDocManager - our own version of CDocManager
////////////////////////////////////////////////////////////////////////////////////////////
// Overloaded to save working directory for File Open dialog
CSimDocManager::CSimDocManager()
{
}
CSimDocManager::CSimDocManager( CSimDocManager &mgr )
{
m_sInitialDir = mgr.m_sInitialDir;
}
// defined below
void AFXAPI _AfxAppendFilterSuffix(
CString& filter, OPENFILENAME& ofn, CDocTemplate* pTemplate, CString* pstrDefaultExt);
// Override undocumented class CDocManager in order to set initial directory for Open dialog
// This function copied from MFC source docmgr.cpp
BOOL CSimDocManager::DoPromptFileName(CString& fileName, UINT nIDSTitle, DWORD lFlags, BOOL bOpenFileDialog, CDocTemplate* pTemplate)
{
// Call derived class which only selects main.lua
CLuaFileDialog dlgFile(bOpenFileDialog, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, NULL, NULL, 0);
// Here's the big change
// Set dialog's initial directory
dlgFile.m_ofn.lpstrInitialDir = GetInitialDir();
// Load the dialog title string.
CString title;
title.LoadString(nIDSTitle);
// Set up the file filter string.
CString strFilter;
CString stringBuffer;
stringBuffer.LoadString(IDS_SIMULATOR_FILES);
strFilter += stringBuffer;
strFilter += TCHAR('\0');
strFilter += _T("main.lua");
strFilter += TCHAR('\0');
stringBuffer.LoadString(AFX_IDS_ALLFILTER);
strFilter += stringBuffer;
strFilter += (TCHAR)'\0';
strFilter += _T("*.*");
strFilter += (TCHAR)'\0';
strFilter += (TCHAR)'\0';
// Set up the dialog.
dlgFile.m_ofn.Flags |= lFlags;
dlgFile.m_ofn.nMaxCustFilter++;
dlgFile.m_ofn.lpstrFilter = strFilter;
dlgFile.m_ofn.lpstrTitle = title;
dlgFile.m_ofn.lpstrFile = fileName.GetBuffer(_MAX_PATH);
// Show the "Open File" dialog.
INT_PTR nResult = dlgFile.DoModal();
fileName.ReleaseBuffer();
return (nResult == IDOK);
}
// Copied from docmgr.cpp because DoPromptFilename needs it.
/*
AFX_STATIC void AFXAPI _AfxAppendFilterSuffix(
CString& filter, OPENFILENAME& ofn, CDocTemplate* pTemplate, CString* pstrDefaultExt)
{
ENSURE_VALID(pTemplate);
ASSERT_KINDOF(CDocTemplate, pTemplate);
CString strFilterExt, strFilterName;
if (pTemplate->GetDocString(strFilterExt, CDocTemplate::filterExt) &&
!strFilterExt.IsEmpty() &&
pTemplate->GetDocString(strFilterName, CDocTemplate::filterName) &&
!strFilterName.IsEmpty())
{
if (pstrDefaultExt != NULL)
pstrDefaultExt->Empty();
// add to filter
filter += strFilterName;
ASSERT(!filter.IsEmpty()); // must have a file type name
filter += (TCHAR)'\0'; // next string please
int iStart = 0;
do
{
CString strExtension = strFilterExt.Tokenize( _T( ";" ), iStart );
if (iStart != -1)
{
// a file based document template - add to filter list
int index = strExtension.Find(TCHAR('.'));
if (index >= 0)
{
if ((pstrDefaultExt != NULL) && pstrDefaultExt->IsEmpty())
{
// set the default extension
*pstrDefaultExt = strExtension.Mid( index + 1 ); // skip the '.'
ofn.lpstrDefExt = const_cast< LPTSTR >((LPCTSTR)(*pstrDefaultExt));
ofn.nFilterIndex = ofn.nMaxCustFilter + 1; // 1 based number
}
if (0 == index)
{
filter += (TCHAR)'*';
}
filter += strExtension;
filter += (TCHAR)';'; // Always append a ';'. The last ';' will get replaced with a '\0' later.
}
}
} while (iStart != -1);
filter.SetAt( filter.GetLength()-1, '\0' );; // Replace the last ';' with a '\0'
ofn.nMaxCustFilter++;
}
}
*/
/////////////////////////////////////////////////////////////////////////////////////
// CLuaFileDialog dialog - only allow selection of main.lua
/////////////////////////////////////////////////////////////////////////////////////
CString CLuaFileDialog::szCustomDefFilter(_T("All Files (*.*)|*.*|Lua Files (*.lua)|*.lua||"));
CString CLuaFileDialog::szCustomDefExt(_T("lua"));
CString CLuaFileDialog::szCustomDefFileName(_T("main"));
CLuaFileDialog::CLuaFileDialog(
BOOL bOpenFileDialog, // TRUE for FileOpen, FALSE for FileSaveAs
LPCTSTR lpszDefExt,
LPCTSTR lpszFileName,
DWORD dwFlags,
LPCTSTR lpszFilter,
CWnd* pParentWnd,
DWORD dwSize,
BOOL bVistaStyle)
: CFileDialog(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd, dwSize, bVistaStyle)
{
}
// OnFileNameOK - override member of CFileDialog
// Returns 0 if filename allowed, 1 otherwise
// We only allow main.lua
BOOL CLuaFileDialog::OnFileNameOK()
{
CString sPath = GetPathName();
CString sFilename = _T("\\main.lua");
if (sPath.Right(sFilename.GetLength()) == sFilename)
{
return 0;
}
::AfxMessageBox( IDS_ONLYMAINLUA );
return 1;
}
| 35.304348 | 133 | 0.697343 | [
"object"
] |
7a62458a50c4e86ff49a1577f06c4beae79bd752 | 1,925 | cpp | C++ | tests/src/utf16_string_test.cpp | friendlyanon/daw_json_link | 7456a8a69a307e63e8063765a67ceba051958b10 | [
"BSL-1.0"
] | null | null | null | tests/src/utf16_string_test.cpp | friendlyanon/daw_json_link | 7456a8a69a307e63e8063765a67ceba051958b10 | [
"BSL-1.0"
] | null | null | null | tests/src/utf16_string_test.cpp | friendlyanon/daw_json_link | 7456a8a69a307e63e8063765a67ceba051958b10 | [
"BSL-1.0"
] | 1 | 2021-08-06T10:13:11.000Z | 2021-08-06T10:13:11.000Z | // Copyright (c) Darrell Wright
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/beached/daw_json_link
//
#include <daw/json/daw_json_link.h>
#include <utf8/unchecked.h>
#include <cstddef>
#include <string>
/***
* This example shows how to parse a utf8 JSON string with the result being a
* std::u16string. This applies equally to std::wstring on windows, I believe.
*/
struct ToConverter {
std::u16string operator( )( ) const {
return { };
}
std::u16string operator( )( std::string_view sv ) const {
char const *first = std::data( sv );
char const *last = daw::data_end( sv );
auto result = std::u16string( );
result.resize( sv.size( ) );
auto *olast = utf8::unchecked::utf8to16( first, last, std::data( result ) );
result.resize(
static_cast<std::size_t>( std::distance( std::data( result ), olast ) ) );
return result;
}
};
struct FromConverter {
std::string operator( )( std::u16string const &str ) const {
char16_t const *first = std::data( str );
char16_t const *last = daw::data_end( str );
auto result = std::string( );
result.resize( str.size( ) * 3 );
auto *olast = utf8::unchecked::utf16to8( first, last, std::data( result ) );
result.resize(
static_cast<std::size_t>( std::distance( std::data( result ), olast ) ) );
return result;
}
};
using json_u16string =
daw::json::json_custom_no_name<std::u16string, ToConverter, FromConverter>;
int main( int, char ** ) {
std::string in_str = R"(["testing🎉", "🙈monkey"])";
puts( "Before" );
puts( in_str.c_str( ) );
std::vector<std::u16string> ary =
daw::json::from_json_array<json_u16string>( in_str );
assert( ary.size( ) == 2 );
auto out_str = daw::json::to_json_array<std::string, json_u16string>( ary );
puts( "After" );
puts( out_str.c_str( ) );
}
| 27.898551 | 79 | 0.664416 | [
"vector"
] |
7a69ee58b1ff4663820a50fbe366f0c0eaacea91 | 7,080 | cpp | C++ | src/manipulations/task2/filters.cpp | Specu3800/image-manipulator | 3290ede9ace4a104ba79274c42c82ff66cf4e367 | [
"MIT"
] | null | null | null | src/manipulations/task2/filters.cpp | Specu3800/image-manipulator | 3290ede9ace4a104ba79274c42c82ff66cf4e367 | [
"MIT"
] | null | null | null | src/manipulations/task2/filters.cpp | Specu3800/image-manipulator | 3290ede9ace4a104ba79274c42c82ff66cf4e367 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
#include "lib/CImg.templ"
#include "helpers.h"
#include "filters.h"
#include "histogram.h"
using namespace std;
using namespace cimg_library;
CImg<int>& applyExponentialPDF(CImg<int> &original, int Gmin, int Gmax, Histogram &histogram){
if (Gmax == 0) {cout << "Wrong Gmax value. \nType --help to view information about available commands." << endl; exit(0);}
CImg<int>* edited = new CImg<int>(original.width(), original.height(), 1, original.spectrum(), 0);
for (int c = 0; c < original.spectrum(); c++) {
double alpha = (log(1 ) + log(1.0/(original.width()*original.height()))) / (Gmin - Gmax);
int* improvedColors = new int[256];
for (int m = 0; m < 256; m++) { //apply histogram modification
improvedColors[m] = Gmin - 1.0/alpha *
log(1.0 - (1.0/(original.width()*original.height())) * histogram.cumulative[c][m]);
improvedColors[m] = normalize(improvedColors[m]);
}
for (int x = 0; x < original.width(); x++) { //apply to image
for (int y = 0; y < original.height(); y++) {
(*edited)(x, y, c) = improvedColors[original(x, y, c)];
}
}
}
//TO DISPLAY AND SAVE HISTOGRAM
// Histogram newHistogram = Histogram(*edited);
//newHistogram.displayUniformValues(0);
// ((*histogram.getUniformHistogramGraph(0, true)).append(*newHistogram.getUniformHistogramGraph(0, true), 'x', 1)).display("HISTOGRAM", false); //show difference in histogram
// histogram.getUniformHistogramGraph(0, true)->save("original_histogram.png");
// newHistogram.getUniformHistogramGraph(0, true)->save("edited_histogram.png");
return *edited;
}
CImg<int>& applyExponentialPDFSeparately(CImg<int> &original, int Gmin, int Gmax){
CImg<int>* edited = new CImg<int>(original.width(), original.height(), 1, original.spectrum(), 0);
CImg<int>* combined = new CImg<int>(original.width(), original.height(), 1, original.spectrum(), 0);
for (int x = 0; x < original.width(); x++) { //apply to image
for (int y = 0; y < original.height(); y++) {
for (int c = 0; c < original.spectrum(); c++) {
(*combined)(x, y, c) = (original(x, y, 0 , 0) + original(x, y, 0 , 1) + original(x, y, 0 , 2))/3;
}
}
}
Histogram combinedHistogram = Histogram(*combined);
*edited = applyExponentialPDF(*combined, Gmin, Gmax, combinedHistogram);
for (int x = 0; x < original.width(); x++) { //apply to image
for (int y = 0; y < original.height(); y++) {
double k = original(x, y, 0, 0) / ((*edited)(x, y, 0, 0)+0.00000001) ;
for (int c = 0; c < original.spectrum(); c++) {
(*edited)(x, y, c) = normalize(original(x, y, c) / k);
}
}
}
return *edited;
}
CImg<int>& applyLaplacianFilter(CImg<int> &original, int maskNumber){
CImg<int>* edited = new CImg<int>(original.width(), original.height(), 1, original.spectrum(), 0);
int filterMask1[3][3] = {-1, -1, -1, -1, 8, -1, -1, -1, -1};
int filterMask2[3][3] = {0, -1, 0, -1, 4, -1, 0, -1, 0};
int filterMask3[3][3] = {1, -2, 1, -2, 4, -2, 1, -2, 1};
int filterMask[3][3];
if(maskNumber == 1) {copy(&filterMask1[0][0], &filterMask1[0][0]+9, &filterMask[0][0]);}
else if(maskNumber == 2){copy(&filterMask2[0][0], &filterMask2[0][0]+9, &filterMask[0][0]);}
else if(maskNumber == 3){copy(&filterMask3[0][0], &filterMask3[0][0]+9, &filterMask[0][0]);}
else {cout << "Wrong mask value. \nType --help to view information about available commands." << endl; exit(0);}
for (int x = 1; x < original.width() - 1; x++)
{
for (int y = 1; y < original.height() - 1; y++)
{
for (int c = 0; c < original.spectrum(); c++)
{
int p = 0;
int q = 0;
int pixelValue = 0;
for (int i = x - 1; i < x + 2; i++)
{
p = 0;
for (int j = y - 1; j < y + 2; j++)
{
pixelValue += original(i, j, 0, c) * filterMask[p][q];
p++;
}
q++;
}
(*edited)(x, y, c) = normalize(pixelValue);
}
}
}
return *edited;
}
CImg<int>& applyLaplacianFilterOptimised(CImg<int> &original){
int* tabFor1 = new int[256];
int* tabFor8 = new int[256];
for(int i = 0; i < 256; i++){
tabFor1[i] = -i;
tabFor8[i] = 8*i;
}
CImg<int>* edited = new CImg<int>(original.width(), original.height(), 1, original.spectrum(), 0);
for (int x = 1; x < original.width() - 1; x++) {
for (int y = 1; y < original.height() - 1; y++) {
for (int c = 0; c < original.spectrum(); c++) {
(*edited)(x, y, c) = normalize(
tabFor1[original(x - 1, y - 1, 0, c)] + tabFor1[original(x, y - 1, 0, c)] +
tabFor1[original(x + 1, y - 1, 0, c)] +
tabFor1[original(x - 1, y, 0, c)] + tabFor8[original(x, y, 0, c)] +
tabFor1[original(x + 1, y, 0, c)] +
tabFor1[original(x - 1, y + 1, 0, c)] + tabFor1[original(x, y + 1, 0, c)] +
tabFor1[original(x + 1, y + 1, 0, c)]
);
}
}
}
return *edited;
}
CImg<int>& applyRobertsOperatorFilter(CImg<int> &original){
CImg<int>* edited = new CImg<int>(original.width(), original.height(), 1, original.spectrum(), 0);
for (int x = 1; x < original.width() - 1; x++)
{
for (int y = 1; y < original.height() - 1; y++)
{
for (int c = 0; c < original.spectrum(); c++)
{
(*edited)(x, y, c) = normalize(abs(original(x, y, c) - original(x + 1, y + 1, 0, c)) +
abs(original(x, y + 1, 0, c) - original(x + 1, y, 0, c)));
}
}
}
return *edited;
}
CImg<int>& applySobelOperatorFilter(CImg<int> &original){
CImg<int>* edited = new CImg<int>(original.width(), original.height(), 1, original.spectrum(), 0);
for (int x = 1; x < original.width() - 1; x++)
{
for (int y = 1; y < original.height() - 1; y++)
{
for (int c = 0; c < original.spectrum(); c++)
{
float xx = original(x + 1, y - 1, 0, c) + 2*original(x + 1, y, 0, c) + original(x + 1, y + 1, 0, c) - original(x - 1, y - 1, 0, c) - 2*original(x - 1, y, 0, c) - original(x - 1, y + 1, 0, c);
float yy = original(x - 1, y - 1, 0, c) + 2*original(x, y - 1, 0, c) + original(x + 1, y - 1, 0, c) - original(x - 1, y + 1, 0, c) - 2*original(x, y + 1, 0, c) - original(x + 1, y + 1, 0, c);
xx *= xx;
yy *= yy;
(*edited)(x, y, c) = normalize(sqrt(xx + yy));
}
}
}
return *edited;
}
| 41.647059 | 207 | 0.500847 | [
"vector"
] |
7a708463a24b2592454f793638f74aaffc658f86 | 7,600 | hpp | C++ | external/mapnik/include/mapnik/geometry_adapters.hpp | baiyicanggou/mapnik_mvt | 9bde52fa9958d81361c015c816858534ec0931bb | [
"Apache-2.0"
] | null | null | null | external/mapnik/include/mapnik/geometry_adapters.hpp | baiyicanggou/mapnik_mvt | 9bde52fa9958d81361c015c816858534ec0931bb | [
"Apache-2.0"
] | null | null | null | external/mapnik/include/mapnik/geometry_adapters.hpp | baiyicanggou/mapnik_mvt | 9bde52fa9958d81361c015c816858534ec0931bb | [
"Apache-2.0"
] | null | null | null | /*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_GEOMETRY_ADAPTERS_HPP
#define MAPNIK_GEOMETRY_ADAPTERS_HPP
#include <mapnik/config.hpp>
// undef B0 to workaround https://svn.boost.org/trac/boost/ticket/10467
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#undef B0
#include <boost/geometry/geometries/register/linestring.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/geometry/geometries/register/ring.hpp>
// NOTE: ideally we would not include all of boost/geometry here to save on compile time
// however we need to pull in <boost/geometry/multi/multi.hpp> for things to work
// and once we do that the compile time is == to just including boost/geometry.hpp
#include <boost/geometry.hpp>
#pragma GCC diagnostic pop
#include <mapnik/geometry.hpp>
#include <mapnik/coord.hpp>
#include <mapnik/box2d.hpp>
#include <cstdint>
// register point
BOOST_GEOMETRY_REGISTER_POINT_2D (mapnik::geometry::point<double>, double, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_POINT_2D (mapnik::geometry::point<std::int64_t>, std::int64_t, boost::geometry::cs::cartesian, x, y)
// ring
BOOST_GEOMETRY_REGISTER_RING_TEMPLATED(mapnik::geometry::linear_ring)
// needed by box2d<double>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, boost::geometry::cs::cartesian, x, y)
namespace boost {
template <typename CoordinateType>
struct range_iterator<mapnik::geometry::line_string<CoordinateType> >
{
using type = typename mapnik::geometry::line_string<CoordinateType>::iterator;
};
template <typename CoordinateType>
struct range_const_iterator<mapnik::geometry::line_string<CoordinateType> >
{
using type = typename mapnik::geometry::line_string<CoordinateType>::const_iterator;
};
template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::iterator
range_begin(mapnik::geometry::line_string<CoordinateType> & line) {return line.begin();}
template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::iterator
range_end(mapnik::geometry::line_string<CoordinateType> & line) {return line.end();}
template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::const_iterator
range_begin(mapnik::geometry::line_string<CoordinateType> const& line) {return line.begin();}
template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::const_iterator
range_end(mapnik::geometry::line_string<CoordinateType> const& line) {return line.end();}
namespace geometry { namespace traits {
// register mapnik::box2d<double>
template<> struct tag<mapnik::box2d<double> > { using type = box_tag; };
template<> struct point_type<mapnik::box2d<double> > { using type = mapnik::coord2d; };
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 0>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.minx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 1>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.miny();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 0>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 1>
{
using ct = coordinate_type<mapnik::coord2d>::type;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();}
static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); }
};
// mapnik::geometry::line_string
template<typename CoordinateType>
struct tag<mapnik::geometry::line_string<CoordinateType> >
{
using type = linestring_tag;
};
// mapnik::geometry::polygon
template<typename CoordinateType>
struct tag<mapnik::geometry::polygon<CoordinateType> >
{
using type = polygon_tag;
};
template <typename CoordinateType>
struct point_order<mapnik::geometry::linear_ring<CoordinateType> >
{
static const order_selector value = counterclockwise;
};
template<typename CoordinateType>
struct tag<mapnik::geometry::multi_point<CoordinateType> >
{
using type = multi_point_tag;
};
template<typename CoordinateType>
struct tag<mapnik::geometry::multi_line_string<CoordinateType> >
{
using type = multi_linestring_tag;
};
template<typename CoordinateType>
struct tag<mapnik::geometry::multi_polygon<CoordinateType> >
{
using type = multi_polygon_tag;
};
// ring
template <typename CoordinateType>
struct ring_const_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::geometry::linear_ring<CoordinateType> const&;
};
template <typename CoordinateType>
struct ring_mutable_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::geometry::linear_ring<CoordinateType>&;
};
// interior
template <typename CoordinateType>
struct interior_const_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::geometry::polygon<CoordinateType>::rings_container const&;
};
template <typename CoordinateType>
struct interior_mutable_type<mapnik::geometry::polygon<CoordinateType> >
{
using type = typename mapnik::geometry::polygon<CoordinateType>::rings_container&;
};
// exterior
template <typename CoordinateType>
struct exterior_ring<mapnik::geometry::polygon<CoordinateType> >
{
static mapnik::geometry::linear_ring<CoordinateType> & get(mapnik::geometry::polygon<CoordinateType> & p)
{
return p.exterior_ring;
}
static mapnik::geometry::linear_ring<CoordinateType> const& get(mapnik::geometry::polygon<CoordinateType> const& p)
{
return p.exterior_ring;
}
};
template <typename CoordinateType>
struct interior_rings<mapnik::geometry::polygon<CoordinateType> >
{
using holes_type = typename mapnik::geometry::polygon<CoordinateType>::rings_container;
static holes_type& get(mapnik::geometry::polygon<CoordinateType> & p)
{
return p.interior_rings;
}
static holes_type const& get(mapnik::geometry::polygon<CoordinateType> const& p)
{
return p.interior_rings;
}
};
}}}
#endif //MAPNIK_GEOMETRY_ADAPTERS_HPP
| 34.38914 | 124 | 0.739737 | [
"geometry"
] |
7a7ac88c278c4488b426c5dca0176c54fc32278f | 4,167 | cpp | C++ | src/Serialization/BinaryInputStreamSerializer.cpp | JacopoDT/numerare-core | a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f | [
"MIT-0"
] | null | null | null | src/Serialization/BinaryInputStreamSerializer.cpp | JacopoDT/numerare-core | a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f | [
"MIT-0"
] | null | null | null | src/Serialization/BinaryInputStreamSerializer.cpp | JacopoDT/numerare-core | a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f | [
"MIT-0"
] | null | null | null | /***
MIT License
Copyright (c) 2018 NUMERARE
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.
Parts of this file are originally Copyright (c) 2012-2017 The CryptoNote developers, The Bytecoin developers
***/
#include "BinaryInputStreamSerializer.h"
#include <algorithm>
#include <cassert>
#include <stdexcept>
#include <Common/StreamTools.h>
#include "SerializationOverloads.h"
using namespace Common;
namespace CryptoNote {
namespace {
template<typename StorageType, typename T>
void readVarintAs(IInputStream& s, T &i) {
i = static_cast<T>(readVarint<StorageType>(s));
}
}
ISerializer::SerializerType BinaryInputStreamSerializer::type() const {
return ISerializer::INPUT;
}
bool BinaryInputStreamSerializer::beginObject(Common::StringView name) {
return true;
}
void BinaryInputStreamSerializer::endObject() {
}
bool BinaryInputStreamSerializer::beginArray(size_t& size, Common::StringView name) {
readVarintAs<uint64_t>(stream, size);
return true;
}
void BinaryInputStreamSerializer::endArray() {
}
bool BinaryInputStreamSerializer::operator()(uint8_t& value, Common::StringView name) {
readVarint(stream, value);
return true;
}
bool BinaryInputStreamSerializer::operator()(uint16_t& value, Common::StringView name) {
readVarint(stream, value);
return true;
}
bool BinaryInputStreamSerializer::operator()(int16_t& value, Common::StringView name) {
readVarintAs<uint16_t>(stream, value);
return true;
}
bool BinaryInputStreamSerializer::operator()(uint32_t& value, Common::StringView name) {
readVarint(stream, value);
return true;
}
bool BinaryInputStreamSerializer::operator()(int32_t& value, Common::StringView name) {
readVarintAs<uint32_t>(stream, value);
return true;
}
bool BinaryInputStreamSerializer::operator()(int64_t& value, Common::StringView name) {
readVarintAs<uint64_t>(stream, value);
return true;
}
bool BinaryInputStreamSerializer::operator()(uint64_t& value, Common::StringView name) {
readVarint(stream, value);
return true;
}
bool BinaryInputStreamSerializer::operator()(bool& value, Common::StringView name) {
value = read<uint8_t>(stream) != 0;
return true;
}
bool BinaryInputStreamSerializer::operator()(std::string& value, Common::StringView name) {
uint64_t size;
readVarint(stream, size);
if (size > 0) {
std::vector<char> temp;
temp.resize(size);
checkedRead(&temp[0], size);
value.reserve(size);
value.assign(&temp[0], size);
} else {
value.clear();
}
return true;
}
bool BinaryInputStreamSerializer::binary(void* value, size_t size, Common::StringView name) {
checkedRead(static_cast<char*>(value), size);
return true;
}
bool BinaryInputStreamSerializer::binary(std::string& value, Common::StringView name) {
return (*this)(value, name);
}
bool BinaryInputStreamSerializer::operator()(double& value, Common::StringView name) {
assert(false); //the method is not supported for this type of serialization
throw std::runtime_error("double serialization is not supported in BinaryInputStreamSerializer");
return false;
}
void BinaryInputStreamSerializer::checkedRead(char* buf, size_t size) {
read(stream, buf, size);
}
}
| 28.9375 | 109 | 0.758579 | [
"vector"
] |
7a7e3eb1434178c1e4795bb73eb014a22b6711e4 | 644 | cpp | C++ | cpp-std/demo12b01-data-race-single.cpp | thanhit95/multi-threading | 30e745b6a6c52e56a8d8e3826ce7a97b51944caa | [
"BSD-3-Clause"
] | 15 | 2021-06-15T09:27:35.000Z | 2022-03-25T02:01:45.000Z | cpp-std/demo12b01-data-race-single.cpp | thanhit95/multi-threads | 30e745b6a6c52e56a8d8e3826ce7a97b51944caa | [
"BSD-3-Clause"
] | null | null | null | cpp-std/demo12b01-data-race-single.cpp | thanhit95/multi-threads | 30e745b6a6c52e56a8d8e3826ce7a97b51944caa | [
"BSD-3-Clause"
] | 5 | 2021-07-15T14:31:33.000Z | 2022-03-29T06:19:34.000Z | /*
DATA RACES
Version 01: Without multithreading
*/
#include <iostream>
#include <vector>
#include <numeric>
#include <thread>
using namespace std;
int getResult(int N) {
vector<bool> a;
a.resize(N + 1, false);
for (int i = 1; i <= N; ++i)
if (0 == i % 2 || 0 == i % 3)
a[i] = true;
// result = sum of a (i.e. counting number of true values in a)
int result = std::accumulate(a.begin(), a.end(), 0);
return result;
}
int main() {
constexpr int N = 8;
int result = getResult(N);
cout << "Number of integers that are divisible by 2 or 3 is: " << result << endl;
return 0;
}
| 16.947368 | 85 | 0.568323 | [
"vector"
] |
7a83c84546f3fdc7efe909eb53bbcdbed2427cea | 4,408 | cpp | C++ | src/main.cpp | Flongy/Shape-Drawer | 249b51ee0d080d92884a9b5578656793503643d3 | [
"MIT"
] | null | null | null | src/main.cpp | Flongy/Shape-Drawer | 249b51ee0d080d92884a9b5578656793503643d3 | [
"MIT"
] | null | null | null | src/main.cpp | Flongy/Shape-Drawer | 249b51ee0d080d92884a9b5578656793503643d3 | [
"MIT"
] | null | null | null | #include <cstdint>
#include <iostream>
#include <vector>
#include <GLFW/glfw3.h>
#include "Shapes.h"
#include "Scene.h"
#include "MemoryCheck.h"
constexpr uint32_t INITIAL_WIDTH = 1280;
constexpr uint32_t INITIAL_HEIGHT = 720;
struct KeyStates {
bool switch_to_test_scene{};
bool switch_to_random_scene{};
bool increase_shape_num_in_random_scene{};
bool decrease_shape_num_in_random_scene{};
};
void setProjMatrix(double width, double height) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
KeyStates* key_states = (KeyStates*)glfwGetWindowUserPointer(window);
switch (key)
{
case GLFW_KEY_1:
// Switch to testScene
if(action == GLFW_PRESS)
key_states->switch_to_test_scene = true;
return;
case GLFW_KEY_2:
// Switch to randomScene
if (action == GLFW_PRESS || action == GLFW_REPEAT)
key_states->switch_to_random_scene = true;
return;
case GLFW_KEY_EQUAL:
case GLFW_KEY_KP_ADD:
if (action == GLFW_PRESS || action == GLFW_REPEAT)
key_states->increase_shape_num_in_random_scene = true;
return;
case GLFW_KEY_MINUS:
case GLFW_KEY_KP_SUBTRACT:
if (action == GLFW_PRESS || action == GLFW_REPEAT)
key_states->decrease_shape_num_in_random_scene = true;
return;
case GLFW_KEY_ESCAPE:
// Close application on pressing ESCAPE button
glfwSetWindowShouldClose(window, GLFW_TRUE);
return;
case GLFW_KEY_M:
if(action == GLFW_PRESS)
printMemoryUsage();
return;
default:
return;
}
}
int main()
{
prepareMemoryCheck();
{
GLFWwindow* window;
if (glfwInit() == GLFW_FALSE)
return -1;
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
window = glfwCreateWindow(INITIAL_WIDTH, INITIAL_HEIGHT, "Shape-Drawer", NULL, NULL);
if (window == NULL)
{
std::cout << "Could not create a window\n";
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
setProjMatrix(INITIAL_WIDTH, INITIAL_HEIGHT);
constexpr size_t MINIMUM_SHAPE_NUM = 20;
constexpr size_t MAXIMUM_SHAPE_NUM = 1'000;
constexpr size_t CHANGE_SHAPE_NUM_STEP = 10;
int32_t random_scene_each_shape_num = MINIMUM_SHAPE_NUM;
Scene test_scene = makeTestScene();
Scene random_scene = makeRandomScene(random_scene_each_shape_num, INITIAL_WIDTH, INITIAL_HEIGHT);
Scene* current_scene_ptr = &test_scene;
KeyStates key_states{};
glfwSetWindowUserPointer(window, &key_states);
glfwSetKeyCallback(window, keyCallback);
while (!glfwWindowShouldClose(window))
{
/* RENDER BEGIN */
glClearColor(0.15f, 0.15f, 0.16f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
current_scene_ptr->drawScene();
/* RENDER END */
if (key_states.switch_to_test_scene) {
current_scene_ptr = &test_scene;
key_states.switch_to_test_scene = false;
}
else if (key_states.switch_to_random_scene) {
random_scene = makeRandomScene(random_scene_each_shape_num, INITIAL_WIDTH, INITIAL_HEIGHT);
current_scene_ptr = &random_scene;
key_states.switch_to_random_scene = false;
}
if (key_states.increase_shape_num_in_random_scene) {
random_scene_each_shape_num += CHANGE_SHAPE_NUM_STEP;
if (random_scene_each_shape_num > MAXIMUM_SHAPE_NUM) {
random_scene_each_shape_num = MAXIMUM_SHAPE_NUM;
}
else if (current_scene_ptr == &random_scene) {
// if the random scene is currently selected - reinitialize it
// otherwise - postpone creating until scene is requested
random_scene = makeRandomScene(random_scene_each_shape_num, INITIAL_WIDTH, INITIAL_HEIGHT);
}
key_states.increase_shape_num_in_random_scene = false;
}
else if (key_states.decrease_shape_num_in_random_scene) {
random_scene_each_shape_num -= CHANGE_SHAPE_NUM_STEP;
if (random_scene_each_shape_num < MINIMUM_SHAPE_NUM) {
random_scene_each_shape_num = MINIMUM_SHAPE_NUM;
}
else if (current_scene_ptr == &random_scene) {
// if the random scene is currently selected - reinitialize it
// otherwise - postpone creating until scene is requested
random_scene = makeRandomScene(random_scene_each_shape_num, INITIAL_WIDTH, INITIAL_HEIGHT);
}
key_states.decrease_shape_num_in_random_scene = false;
}
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
}
endMemoryDump();
std::cin.get();
return 0;
}
| 26.715152 | 99 | 0.744102 | [
"render",
"shape",
"vector"
] |
18562cdd7eae465906cb14cc3cb1ad2cb8a826af | 1,238 | cc | C++ | tools/djsettest.cc | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | tools/djsettest.cc | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | tools/djsettest.cc | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | #include "../DisjointSet/disjointset.hh"
#include <iostream>
#include <cmath>
using namespace bold;
using namespace std;
#define N 1000000
bool flipCoin()
{
return (rand() % 20) == 0;
}
int main()
{
// TODO convert this into unit tests
DisjointSet<int> set;
vector<int> ints(N);
iota(ints.begin(), ints.end(), 1);
random_shuffle(ints.begin(), ints.end());
int someSeenEven = -1;
int someSeenOdd = -1;
for (unsigned i = 0; i < N; ++i)
{
set.insert(ints[i]);
if (ints[i] % 2 == 0)
{
if (someSeenEven != -1)
set.merge(ints[i], someSeenEven);
if (someSeenEven == -1 || flipCoin())
someSeenEven = ints[i];
}
if (ints[i] % 2 != 0)
{
if (someSeenOdd != -1)
set.merge(ints[i], someSeenOdd);
if (someSeenOdd == -1 || flipCoin())
someSeenOdd = ints[i];
}
}
auto subSets = set.getSubSets();
cout << "Number of subsets: " << subSets.size() << endl;
for (auto subSet : subSets)
cout << "Size: " << subSet.size() << endl;
/*
auto elements = set.getElements();
cout << "Number of elements: " << elements.size() << endl;
auto subsets = set.getSubSets();
cout << "Number of subsets: " << subsets.size() << endl;
*/
}
| 19.650794 | 60 | 0.568659 | [
"vector"
] |
185e467c12da68051d7ac609eed286f59a7f9b10 | 3,807 | cpp | C++ | wireframe-conway/src/ofApp.cpp | graham-riches/sketches | 026be227193e84859aedcd350e7fcfc4b87e43d2 | [
"MIT"
] | null | null | null | wireframe-conway/src/ofApp.cpp | graham-riches/sketches | 026be227193e84859aedcd350e7fcfc4b87e43d2 | [
"MIT"
] | null | null | null | wireframe-conway/src/ofApp.cpp | graham-riches/sketches | 026be227193e84859aedcd350e7fcfc4b87e43d2 | [
"MIT"
] | null | null | null | /**
* \file ofApp.cpp
* \author Graham Riches (graham.riches@live.com)
* \brief definitions for a simple open frameworks sketch app
* \version 0.1
* \date 2021-02-10
*
* @copyright Copyright (c) 2021
*
*/
#include "ofApp.h"
#include <algorithm>
#include <filesystem>
/**
* \brief constructor for game of life application
* \param width width in tiles
* \param height in tiles
* \param wireframe_resolution how many wireframes per conway grid location
* \param sample_rate time sample rate in ms
* \param scale height scale for rendering
*/
application::application(int width, int height, int wireframe_resolution, uint64_t sample_rate, float scale)
: _conway(game_of_life{random_boolean_grid(height, width, grid_density)})
, _width(width)
, _height(height)
, _sample_rate_ms(sample_rate)
, _scale(scale)
, _last_sample_time(0)
{
_image.allocate(height, width, OF_IMAGE_GRAYSCALE);
_plane.set(1200, 900, height*wireframe_resolution, height*wireframe_resolution, OF_PRIMITIVE_TRIANGLES);
_plane.mapTexCoordsFromTexture(_image.getTexture());
}
/**
* \brief open frameworks setup function that runs prior to the main event loop
*/
void application::setup() {
auto path = std::filesystem::current_path();
auto parent_path = path.parent_path();
std::filesystem::path shader_path = parent_path / std::filesystem::path{"shaders"};
_displacement_shader.load(shader_path / std::filesystem::path{"shadersGL3/shader"});
}
/**
* \brief frame update method
*/
void application::update() {
const auto elapsed_time_ms = ofGetElapsedTimeMillis();
if ((elapsed_time_ms - _last_sample_time) / _sample_rate_ms) {
//!< update timestamp
_last_sample_time = elapsed_time_ms;
//!< get the next generation
auto current_generation = _conway.next_generation();
//!< update the image to draw it
ofPixels& pixels = _image.getPixels();
const auto width = _image.getWidth();
const auto height = _image.getHeight();
for ( uint64_t row = 0; row < height; row++ ) {
for ( uint64_t column = 0; column < width; column++ ) {
pixels[row * static_cast<int>(width) + column] = current_generation[row][column]*255;
}
}
_image.update();
}
}
/**
* \brief main method to render the scene
*/
void application::draw() {
//!< bind the texture to the shader
_image.getTexture().bind();
auto time = ofGetElapsedTimef();
auto percent_y = ofClamp(0.5 * sin(time) + 0.5, 0, 1) * _scale;
//!< start the shader
_displacement_shader.begin();
_displacement_shader.setUniform1f("scale", percent_y);
//!< push the current local coordinate system to move to a new relative one
ofPushMatrix();
//!< translate the plane into the center of the screen
auto center_x = ofGetWidth() / 2.0;
auto center_y = ofGetHeight() / 2.0;
ofTranslate(center_x, center_y);
//!< rotate it to a more isometric view
auto rotation = ofMap(0.30, 0, 1, -60, 60, true) + 60;
ofRotateDeg(rotation, 1, 0, 0);
//!< draw the wireframe
_plane.drawWireframe();
ofPopMatrix();
_displacement_shader.end();
}
void application::keyPressed(int key) { }
void application::keyReleased(int key) { }
void application::mouseMoved(int x, int y) { }
void application::mouseDragged(int x, int y, int button) { }
void application::mousePressed(int x, int y, int button) { }
void application::mouseReleased(int x, int y, int button) { }
void application::windowResized(int w, int h) { }
void application::gotMessage(ofMessage msg) { }
void application::dragEvent(ofDragInfo dragInfo) { }
void application::mouseEntered(int x, int y) { }
void application::mouseExited(int x, int y) { } | 29.976378 | 108 | 0.676386 | [
"render"
] |
1860a0ad6d35fa2123aa5815662421e476d95700 | 791 | cpp | C++ | docs/atl-mfc-shared/reference/codesnippet/CPP/cfile-class_2.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 965 | 2017-06-25T23:57:11.000Z | 2022-03-31T14:17:32.000Z | docs/atl-mfc-shared/reference/codesnippet/CPP/cfile-class_2.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 3,272 | 2017-06-24T00:26:34.000Z | 2022-03-31T22:14:07.000Z | docs/atl-mfc-shared/reference/codesnippet/CPP/cfile-class_2.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 951 | 2017-06-25T12:36:14.000Z | 2022-03-26T22:49:06.000Z | HANDLE hFile = CreateFile(_T("CFile_File.dat"),
GENERIC_WRITE, FILE_SHARE_READ,
NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
AfxMessageBox(_T("Couldn't create the file!"));
}
else
{
// Attach a CFile object to the handle we have.
CFile myFile(hFile);
static const TCHAR sz[] = _T("I love CFile!");
// write string
myFile.Write(sz, sizeof(sz));
// We need to call Close() explicitly. Note that there's no need to
// call CloseHandle() on the handle returned by the API because
// Close() automatically calls CloseHandle() for us.
myFile.Close(); | 35.954545 | 80 | 0.547408 | [
"object"
] |
18634066e4e890c0300db063f255d86ea249e853 | 7,089 | cpp | C++ | src/kbase/string_format.cpp | oceancx/kbase-cmake | dae59db030a2e0c118e627cad0dcbdc9863480bf | [
"MIT"
] | 20 | 2016-05-16T07:02:09.000Z | 2021-06-07T10:21:24.000Z | src/kbase/string_format.cpp | oceancx/kbase-cmake | dae59db030a2e0c118e627cad0dcbdc9863480bf | [
"MIT"
] | 1 | 2020-07-09T02:00:36.000Z | 2020-07-11T03:46:52.000Z | src/kbase/string_format.cpp | oceancx/kbase-cmake | dae59db030a2e0c118e627cad0dcbdc9863480bf | [
"MIT"
] | 13 | 2016-03-09T09:52:17.000Z | 2021-09-09T14:50:13.000Z | /*
@ 0xCCCCCCCC
*/
#include "kbase/string_format.h"
#include "kbase/basic_macros.h"
#include "kbase/scope_guard.h"
#if defined(OS_POSIX)
#include <cstdarg>
#endif
namespace {
using kbase::FormatError;
using kbase::NotReached;
using kbase::internal::FormatTraits;
using kbase::internal::Placeholder;
using kbase::internal::PlaceholderList;
using kbase::internal::IsDigit;
using kbase::internal::StrToUL;
enum class FormatParseState {
InText,
InFormat
};
constexpr char kEscapeBegin = '{';
constexpr char kEscapeEnd = '}';
constexpr char kSpecifierDelimeter = ':';
constexpr char kPlaceholderMark = '@';
void AppendPrintfT(std::string& str, char* buf, size_t max_count_including_null, const char* fmt,
va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int real_size = vsnprintf(buf, max_count_including_null, fmt, args_copy);
va_end(args_copy);
ENSURE(THROW, real_size >= 0)(real_size).Require();
if (static_cast<size_t>(real_size) < max_count_including_null) {
// vsnprintf() guarantees the resulting string will be terminated with a null-terminator.
str.append(buf);
return;
}
std::vector<char> backup_buf(static_cast<size_t>(real_size) + 1);
va_copy(args_copy, args);
vsnprintf(backup_buf.data(), backup_buf.size(), fmt, args_copy);
va_end(args_copy);
str.append(backup_buf.data());
}
void AppendPrintfT(std::wstring& str, wchar_t* buf, size_t max_count_including_null,
const wchar_t* fmt, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int rv = vswprintf(buf, max_count_including_null, fmt, args_copy);
va_end(args_copy);
if (rv >= 0) {
str.append(buf, rv);
return;
}
constexpr size_t kMaxAllowed = 16U * 1024 * 1024;
size_t tentative_count = max_count_including_null;
std::vector<wchar_t> backup_buf;
while (true) {
tentative_count <<= 1;
ENSURE(THROW, tentative_count <= kMaxAllowed)(tentative_count)(kMaxAllowed).Require();
backup_buf.resize(tentative_count);
va_copy(args_copy, args);
rv = vswprintf(backup_buf.data(), backup_buf.size(), fmt, args_copy);
va_end(args_copy);
if (rv > 0) {
str.append(backup_buf.data(), rv);
break;
}
}
}
template<typename StrT>
void StringAppendPrintfT(StrT& str, const typename StrT::value_type* fmt, va_list args)
{
using CharT = typename StrT::value_type;
constexpr size_t kDefaultCount = 1024U;
CharT buf[kDefaultCount];
AppendPrintfT(str, buf, kDefaultCount, fmt, args);
}
template<typename CharT>
size_t ExtractPlaceholderIndex(const CharT* first_digit, CharT*& last_digit)
{
auto index = StrToUL(first_digit, last_digit);
--last_digit;
return index;
}
template<typename CharT>
typename FormatTraits<CharT>::String AnalyzeFormatT(const CharT* fmt, PlaceholderList<CharT>& placeholders)
{
constexpr size_t kInitialCapacity = 32;
typename FormatTraits<CharT>::String analyzed_fmt;
analyzed_fmt.reserve(kInitialCapacity);
placeholders.clear();
Placeholder<CharT> placeholder;
auto state = FormatParseState::InText;
for (auto ptr = fmt; *ptr != '\0'; ++ptr) {
if (*ptr == kEscapeBegin) {
// `{` is an invalid token for in-format state.
ENSURE(THROW, state != FormatParseState::InFormat).ThrowIn<FormatError>().Require();
if (*(ptr + 1) == kEscapeBegin) {
// Use `{{` to represent literal `{`.
analyzed_fmt += kEscapeBegin;
++ptr;
} else if (IsDigit(*(ptr + 1))) {
CharT* last_digit;
placeholder.index = ExtractPlaceholderIndex(ptr + 1, last_digit);
ptr = last_digit;
ENSURE(THROW, (*(ptr + 1) == kEscapeEnd) ||
(*(ptr + 1) == kSpecifierDelimeter)).ThrowIn<FormatError>()
.Require();
if (*(ptr + 1) == kSpecifierDelimeter) {
++ptr;
}
// Turn into in-format state.
state = FormatParseState::InFormat;
} else {
ENSURE(THROW, NotReached()).ThrowIn<FormatError>().Require();
}
} else if (*ptr == kEscapeEnd) {
if (state == FormatParseState::InText) {
ENSURE(THROW, *(ptr + 1) == kEscapeEnd).ThrowIn<FormatError>().Require();
analyzed_fmt += kEscapeEnd;
++ptr;
} else {
placeholder.pos = analyzed_fmt.length();
analyzed_fmt += kPlaceholderMark;
placeholders.push_back(placeholder);
placeholder.format_specifier.clear();
// Now we turn back into in-text state.
state = FormatParseState::InText;
}
} else {
if (state == FormatParseState::InText) {
analyzed_fmt += *ptr;
} else {
placeholder.format_specifier += *ptr;
}
}
}
ENSURE(THROW, state == FormatParseState::InText).ThrowIn<FormatError>().Require();
std::sort(std::begin(placeholders), std::end(placeholders),
[](const auto& lhs, const auto& rhs) {
return lhs.index < rhs.index;
});
return analyzed_fmt;
}
} // namespace
namespace kbase {
void StringAppendPrintf(std::string& str, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT { va_end(args); };
StringAppendPrintfT(str, fmt, args);
}
void StringAppendPrintf(std::wstring& str, const wchar_t* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT { va_end(args); };
StringAppendPrintfT(str, fmt, args);
}
std::string StringPrintf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT { va_end(args); };
std::string str;
StringAppendPrintfT(str, fmt, args);
return str;
}
std::wstring StringPrintf(const wchar_t* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT { va_end(args); };
std::wstring str;
StringAppendPrintfT(str, fmt, args);
return str;
}
void StringPrintf(std::string& str, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT { va_end(args); };
str.clear();
StringAppendPrintfT(str, fmt, args);
}
void StringPrintf(std::wstring& str, const wchar_t* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT { va_end(args); };
str.clear();
StringAppendPrintfT(str, fmt, args);
}
namespace internal {
std::string AnalyzeFormat(const char* fmt, PlaceholderList<char>& placeholders)
{
return AnalyzeFormatT(fmt, placeholders);
}
std::wstring AnalyzeFormat(const wchar_t* fmt, PlaceholderList<wchar_t>& placeholders)
{
return AnalyzeFormatT(fmt, placeholders);
}
} // namespace internal
} // namespace kbase
| 27.909449 | 107 | 0.613345 | [
"vector"
] |
18705f9a9197f4242cd674c8357b91dea828bcdf | 1,909 | cpp | C++ | jni_call.cpp | XiXiLocked/cheatsheet | bb472344a38d6e8b87cc7f078a2d6e9ccfb349b6 | [
"MIT"
] | null | null | null | jni_call.cpp | XiXiLocked/cheatsheet | bb472344a38d6e8b87cc7f078a2d6e9ccfb349b6 | [
"MIT"
] | null | null | null | jni_call.cpp | XiXiLocked/cheatsheet | bb472344a38d6e8b87cc7f078a2d6e9ccfb349b6 | [
"MIT"
] | null | null | null | //jni_call.cpp
// equivalent java code
/*
package com.example.it;
public class ClassA{
public class ClassB{
public float f;
public float g;
}
public void addsomething(vector<ClassB_cpp> data)
{
ArrayList<ClassB_cpp> array = new ArrayList();
for(int i =0;i<data.size();++i)
{
ClassB d = new ClassB();
d.f = data[i].f;
d.g = data[i].g;
array.add(d)
}
}
}
*/
extern "C"
{
// 对应的是java的 com.example.it.ClassA的addsomething 方法
JNIEXPORT void JNICALL Java_com_example_it_ClassA_addsomething(JNIEnv*env,jobject thiz, vector<ClassB_cpp> data)
{
// java/util/ArrayList 对应 java.util.ArrayList
jclass ArrayList_t = env->FindClass("java/util/ArrayList");
// new时用的构造函数名固定是 <init> , "()V"是函数类型的签名
jmethodID ArrayList_Constructor = env->GetMethodID(ArrayList_t,"<init>", "()V");
// 正常的函数就是对应的函数名,add方法签名是 boolean add(E ),虽然是泛型,但是java类型擦除,最后E还是java.lang.Object . Z表示boolean类型
jmethodID ArrayList_Add = env->GetMethodID(ArrayList_t,"add", "(Ljava/lang/Object;)Z");
// 内部类用$连接
jclass ClassB_t= env->FindClass("com/example/it/ClassA$ClassB");
jmethodID ClassB_Constructor = env->GetMethodID(ClassB_t,"<init>","()V");
// F表示float类型
jfieldID f = env->GetFieldID(ClassB_t,"f","F");
// 其他类型参考 https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html#wp9502
jfieldID g = env->GetFieldID(ClassB_t,"g","F");
jobject array = env->NewObject(ArrayList_t,ArrayList_Constructor);
for(int i =0;i<data.size();++i)
{
jobject a_classB = env->NewObject(ClassB_t,bbox_Constructor);
env->SetFloatField(a_classB,f,data[i].f);
env->SetFloatField(a_classB,g,data[i].g);
env->CallBooleanMethod(array,ArrayList_Add,a_classB);
}
}
} | 34.089286 | 113 | 0.624935 | [
"object",
"vector"
] |
18756108c52083345035329819a5debddeb0ac2f | 40,890 | cpp | C++ | Compiler/rexlang_compiler/CST2ASTConvert.cpp | RonxBulld/RexLang | 6b11e5a5cc0e27b6c722db3c164e94d072710b7d | [
"Apache-2.0"
] | 4 | 2020-09-24T06:15:15.000Z | 2021-07-21T14:50:40.000Z | Compiler/rexlang_compiler/CST2ASTConvert.cpp | RonxBulld/RexLang | 6b11e5a5cc0e27b6c722db3c164e94d072710b7d | [
"Apache-2.0"
] | null | null | null | Compiler/rexlang_compiler/CST2ASTConvert.cpp | RonxBulld/RexLang | 6b11e5a5cc0e27b6c722db3c164e94d072710b7d | [
"Apache-2.0"
] | null | null | null | //
// Created by rex on 2020/1/23.
//
#include <cstring>
#include "gen/rexLangLexer.h"
#include "gen/rexLangParser.h"
#include "gen/rexLangVisitor.h"
#include "CST2ASTConvert.h"
#include "NodeDecl.h"
#include "ASTContext.h"
namespace rexlang {
void CST2ASTConvert::RemoveRoundQuotes(TString &tString) const {
if (!tString.string_.empty()&& tString.string_.str().front() == '"' && tString.string_.str().back() == '"') {
std::string _string = tString.string_.str();
_string = _string.substr(1, _string.length() - 2);
tString.string_ = this->ast_context_->CreateString(_string);
}
}
TString CST2ASTConvert::GetTextIfExist(const antlr4::Token *token, const std::string &hint) const {
TString t_string;
if (token) {
t_string.string_ = this->ast_context_->CreateString(token->getText());
antlr4::TokenSource *ts = token->getTokenSource();
t_string.location_ = this->ast_context_->CreateLocation(ts->getSourceName(), ts->getLine(), ts->getCharPositionInLine());
} else {
t_string.string_ = this->ast_context_->CreateString(hint);
}
return t_string;
}
long CST2ASTConvert::GetLongIfExist(const antlr4::Token *token, int hint) const {
if (token) {
std::string __v = token->getText();
return strtol(__v.c_str(), nullptr, 10);
} else {
return hint;
}
}
float CST2ASTConvert::GetFloatIfExist(const antlr4::Token *token, float hint) const {
if (token) {
std::string __v = token->getText();
return strtof(__v.c_str(), nullptr);
} else {
return hint;
}
}
std::vector<TString> CST2ASTConvert::GetTextVecIfExist(const std::vector<antlr4::Token *> tokens, const std::string &hint) const {
std::vector<TString> tokens_str_vec;
for (auto *tk : tokens) {
tokens_str_vec.emplace_back(GetTextIfExist(tk, hint));
}
return tokens_str_vec;
}
template<typename T, bool must_valid, typename, typename>
T CST2ASTConvert::GetFromCtxIfExist(antlr4::ParserRuleContext *ctx, const T &hint) {
if (ctx) {
antlrcpp::Any ret = visit(ctx);
if (ret.is<NodeWarp>()) {
NodeWarp node_warp = ret.as<NodeWarp>();
if (T _vp = node_warp.node_->as<typename std::remove_pointer_t<T>>()) {
return _vp;
}
}
assert(!must_valid);
}
assert(!must_valid);
return hint;
}
template<typename T, bool must_valid, typename>
T CST2ASTConvert::GetFromCtxIfExist(antlr4::ParserRuleContext *ctx, const T &hint) {
if (ctx) {
antlrcpp::Any ret = visit(ctx);
if (ret.is<T>()) {
return ret.as<T>();
}
assert(!must_valid);
}
assert(!must_valid);
return hint;
}
template<typename NodeTy, typename ... Args, typename>
NodeTy *CST2ASTConvert::CreateNode(antlr4::Token *start_token, antlr4::Token *end_token, Args ... args) {
NodeTy *node = rexlang::CreateNode<NodeTy>(this->ast_context_, args...);
Node *base_node = node;
base_node->location_start_ = this->ast_context_->CreateLocation(
start_token->getTokenSource()->getSourceName(),
start_token->getLine(),
start_token->getCharPositionInLine()
);
base_node->location_end_ = this->ast_context_->CreateLocation(
end_token->getTokenSource()->getSourceName(),
end_token->getLine(),
end_token->getCharPositionInLine()
);
return node;
}
antlrcpp::Any CST2ASTConvert::visitRexlang_src(rexLangParser::Rexlang_srcContext *context) {
TranslateUnitPtr translate_unit = CreateNode<TranslateUnit>(context->getStart(), context->getStop());
// 分析版本号
translate_unit->edition_ = GetFromCtxIfExist<unsigned int, true>(context->edition_spec(), 2);
// 分析文件具体内容
auto *src_ctx = context->src_content();
translate_unit->source_file_ = { GetFromCtxIfExist<SourceFilePtr, true>(src_ctx) };
return NodeWarp(translate_unit);
}
antlrcpp::Any CST2ASTConvert::visitSrc_content(rexLangParser::Src_contentContext *context) {
if (rexLangParser::Program_set_fileContext *program_set_file_ctx = context->program_set_file()) {
return NodeWarp(GetFromCtxIfExist<ProgramSetFilePtr, true>(program_set_file_ctx));
} else if (rexLangParser::Data_structure_fileContext *data_structure_file_ctx = context->data_structure_file()) {
return NodeWarp(GetFromCtxIfExist<DataStructureFilePtr, true>(data_structure_file_ctx));
} else if (rexLangParser::Global_variable_fileContext *global_variable_file_ctx = context->global_variable_file()) {
return NodeWarp(GetFromCtxIfExist<GlobalVariableFilePtr, true>(global_variable_file_ctx));
} else if (rexLangParser::Dll_define_fileContext *dll_define_file_ctx = context->dll_define_file()) {
return NodeWarp(GetFromCtxIfExist<DllDefineFilePtr, true>(dll_define_file_ctx));
} else {
return NodeWarp(nullptr);
}
}
antlrcpp::Any CST2ASTConvert::visitProgram_set_file(rexLangParser::Program_set_fileContext *context) {
auto program_set_file = CreateNode<ProgramSetFile>(context->getStart(), context->getStop());
for (antlr4::Token *token : context->libraries) {
TString library_name = GetTextIfExist(token);
program_set_file->libraries_.push_back(library_name);
program_set_file->ast_context_->AddDependenceLibrary(library_name.string_);
}
program_set_file->program_set_declares_ = GetFromCtxIfExist<ProgSetDeclPtr>(context->prog_set());
program_set_file->file_type_ = SourceFile::FileType::kProgramSetFile;
return NodeWarp(program_set_file);
}
antlrcpp::Any CST2ASTConvert::visitData_structure_file(rexLangParser::Data_structure_fileContext *context) {
DataStructureFilePtr data_structure_file = CreateNode<DataStructureFile>(context->getStart(), context->getStop());
for (auto *struct_decl_ctx : context->struct_declare()) {
StructureDeclPtr structure_decl = GetFromCtxIfExist<StructureDeclPtr>(struct_decl_ctx);
data_structure_file->structure_decl_map_[structure_decl->name_.string_] = structure_decl;
}
data_structure_file->file_type_ = SourceFile::FileType::kDataStructureFile;
return NodeWarp(data_structure_file);
}
antlrcpp::Any CST2ASTConvert::visitGlobal_variable_file(rexLangParser::Global_variable_fileContext *context) {
GlobalVariableFilePtr global_variable_file = CreateNode<GlobalVariableFile>(context->getStart(), context->getStop());
global_variable_file->global_variable_map_ = GetFromCtxIfExist<decltype(GlobalVariableFile::global_variable_map_)>(context->global_variable_list());
global_variable_file->file_type_ = SourceFile::FileType::kGlobalVariableFile;
return NodeWarp(global_variable_file);
}
antlrcpp::Any CST2ASTConvert::visitDll_define_file(rexLangParser::Dll_define_fileContext *context) {
DllDefineFilePtr dll_define_file = CreateNode<DllDefineFile>(context->getStart(), context->getStop());
for (auto *dll_cmd_decl_ctx : context->dll_command()) {
APICommandDeclPtr dll_command_decl = GetFromCtxIfExist<APICommandDeclPtr>(dll_cmd_decl_ctx);
dll_define_file->dll_declares_[dll_command_decl->name_.string_] = dll_command_decl;
}
for (auto *dll_cmd_decl_ctx : context->lib_command()) {
APICommandDeclPtr dll_command_decl = GetFromCtxIfExist<APICommandDeclPtr>(dll_cmd_decl_ctx);
dll_define_file->dll_declares_[dll_command_decl->name_.string_] = dll_command_decl;
}
dll_define_file->file_type_ = SourceFile::FileType::kDllDefineFile;
return NodeWarp(dll_define_file);
}
antlrcpp::Any CST2ASTConvert::visitDll_command(rexLangParser::Dll_commandContext *context) {
APICommandDeclPtr dll_command_decl = CreateNode<APICommandDecl>(context->getStart(), context->getStop());
dll_command_decl->name_ = GetTextIfExist(context->name);
dll_command_decl->return_type_name_ = GetTextIfExist(context->type);
dll_command_decl->library_file_ = GetTextIfExist(context->file);
RemoveRoundQuotes(dll_command_decl->library_file_);
dll_command_decl->library_type_ = LibraryType::kLTDynamic;
dll_command_decl->api_name_ = GetTextIfExist(context->cmd);
RemoveRoundQuotes(dll_command_decl->api_name_);
dll_command_decl->comment_ = GetFromCtxIfExist<TString>(context->table_comment());
dll_command_decl->parameters_ = GetFromCtxIfExist<std::vector<ParameterDeclPtr>>(context->params);
for (auto *parameter : dll_command_decl->parameters_) {
dll_command_decl->mapping_names_.emplace_back(parameter->name_.string_);
}
return NodeWarp(dll_command_decl);
}
antlrcpp::Any CST2ASTConvert::visitLib_command(rexLangParser::Lib_commandContext *context) {
APICommandDeclPtr dll_command_decl = CreateNode<APICommandDecl>(context->getStart(), context->getStop());
dll_command_decl->name_ = GetTextIfExist(context->name);
dll_command_decl->return_type_name_ = GetTextIfExist(context->type);
dll_command_decl->library_file_ = GetTextIfExist(context->file);
RemoveRoundQuotes(dll_command_decl->library_file_);
dll_command_decl->library_type_ = LibraryType::kLTStatic;
dll_command_decl->api_name_ = GetTextIfExist(context->cmd);
RemoveRoundQuotes(dll_command_decl->api_name_);
dll_command_decl->comment_ = GetFromCtxIfExist<TString>(context->table_comment());
dll_command_decl->parameters_ = GetFromCtxIfExist<std::vector<ParameterDeclPtr>>(context->params);
for (auto *parameter : dll_command_decl->parameters_) {
dll_command_decl->mapping_names_.emplace_back(parameter->name_.string_);
}
return NodeWarp(dll_command_decl);
}
antlrcpp::Any CST2ASTConvert::visitGlobal_variable_list(rexLangParser::Global_variable_listContext *context) {
decltype(GlobalVariableFile::global_variable_map_) global_variable_decl_map;
for (auto *global_vari_decl_ctx : context->global_variable_item()) {
GlobalVariableDeclPtr global_variable_decl = GetFromCtxIfExist<GlobalVariableDeclPtr>(global_vari_decl_ctx);
global_variable_decl_map[global_variable_decl->name_.string_] = global_variable_decl;
}
return global_variable_decl_map;
}
antlrcpp::Any CST2ASTConvert::visitGlobal_variable_item(rexLangParser::Global_variable_itemContext *context) {
GlobalVariableDeclPtr global_variable_decl = CreateNode<GlobalVariableDecl>(context->getStart(), context->getStop());
global_variable_decl->name_ = GetTextIfExist(context->name);
global_variable_decl->type_name_ = GetTextIfExist(context->type);
global_variable_decl->dimension_ = GetTextIfExist(context->dimension);
global_variable_decl->access_ = GetTextIfExist(context->access);
global_variable_decl->comment_ = GetFromCtxIfExist<TString>(context->table_comment());
return NodeWarp(global_variable_decl);
}
antlrcpp::Any CST2ASTConvert::visitEdition_spec(rexLangParser::Edition_specContext *context) {
return (unsigned int) strtoul(context->INTEGER_LITERAL()->getText().c_str(), nullptr, 10);;
}
antlrcpp::Any CST2ASTConvert::visitStruct_declare(rexLangParser::Struct_declareContext *context) {
StructureDeclPtr structure_decl = CreateNode<StructureDecl>(context->getStart(), context->getStop());
structure_decl->name_ = GetTextIfExist(context->name);
structure_decl->access_ = GetTextIfExist(context->access);
structure_decl->comment_ = GetFromCtxIfExist<TString>(context->table_comment());
for (auto *mem_ctx : context->struct_mems) {
MemberVariableDeclPtr member = GetFromCtxIfExist<MemberVariableDeclPtr>(mem_ctx);
structure_decl->members_[member->name_.string_] = member;
}
return NodeWarp(structure_decl);
}
antlrcpp::Any CST2ASTConvert::visitTable_comment(rexLangParser::Table_commentContext *context) {
return GetTextIfExist(context->comment);
}
antlrcpp::Any CST2ASTConvert::visitProg_set(rexLangParser::Prog_setContext *context) {
ProgSetDeclPtr prog_set_decl = CreateNode<ProgSetDecl>(context->getStart(), context->getStop());
prog_set_decl->name_ = GetTextIfExist(context->name);
prog_set_decl->base_ = GetTextIfExist(context->base);
prog_set_decl->access_ = GetTextIfExist(context->access);
prog_set_decl->comment_ = GetFromCtxIfExist<TString>(context->table_comment());
for (auto *vari_ctx : context->prog_set_varis) {
FileVariableDeclPtr vari_decl = GetFromCtxIfExist<FileVariableDeclPtr>(vari_ctx);
prog_set_decl->file_static_variables_[vari_decl->name_.string_] = vari_decl;
}
for (auto *func_ctx : context->functions) {
FunctionDeclPtr sub_prog_decl = GetFromCtxIfExist<FunctionDeclPtr>(func_ctx);
prog_set_decl->function_decls_[sub_prog_decl->name_.string_] = sub_prog_decl;
}
return NodeWarp(prog_set_decl);
}
antlrcpp::Any CST2ASTConvert::visitVariable_decl(rexLangParser::Variable_declContext *context) {
VariableDeclPtr variable_decl = CreateNode<VariableDecl>(context->getStart(), context->getStop());
variable_decl->name_ = GetTextIfExist(context->name);
variable_decl->type_name_ = GetTextIfExist(context->type);
variable_decl->attributes_ = GetTextVecIfExist(context->attributes);
variable_decl->dimension_ = GetTextIfExist(context->dimension);
variable_decl->comment_ = GetFromCtxIfExist<TString>(context->table_comment());
return NodeWarp(variable_decl);
}
antlrcpp::Any CST2ASTConvert::visitSub_program(rexLangParser::Sub_programContext *context) {
FunctionDeclPtr sub_prog_decl = CreateNode<FunctionDecl>(context->getStart(), context->getStop());
sub_prog_decl->name_ = GetTextIfExist(context->name);
sub_prog_decl->return_type_name_ = GetTextIfExist(context->type);
sub_prog_decl->access_ = GetTextIfExist(context->access);
sub_prog_decl->comment_ = GetFromCtxIfExist<TString>(context->table_comment());
sub_prog_decl->parameters_ = GetFromCtxIfExist<std::vector<ParameterDeclPtr>>(context->params);
for (auto *local_vari_ctx : context->local_vari) {
LocalVariableDeclPtr local_vari = GetFromCtxIfExist<LocalVariableDeclPtr>(local_vari_ctx);
sub_prog_decl->local_vari_[local_vari->name_.string_] = local_vari;
}
sub_prog_decl->statement_list_ = GetFromCtxIfExist<StatementBlockPtr>(context->statement_list());
return NodeWarp(sub_prog_decl);
}
antlrcpp::Any CST2ASTConvert::visitLocal_variable_decl(rexLangParser::Local_variable_declContext *context) {
LocalVariableDeclPtr local_variable_decl = CreateNode<LocalVariableDecl>(context->getStart(), context->getStop());
local_variable_decl->name_ = GetTextIfExist(context->name);
local_variable_decl->type_name_ = GetTextIfExist(context->type);
local_variable_decl->dimension_ = GetTextIfExist(context->dimension);
local_variable_decl->comment_ = GetFromCtxIfExist<TString>(context->table_comment());
return NodeWarp(local_variable_decl);
}
antlrcpp::Any CST2ASTConvert::visitParameter_decl_list(rexLangParser::Parameter_decl_listContext *context) {
std::vector<ParameterDeclPtr> params;
for (auto *param_vari_ctx : context->parameter_decl()) {
ParameterDeclPtr parameter_decl = GetFromCtxIfExist<ParameterDeclPtr>(param_vari_ctx);
params.emplace_back(parameter_decl);
}
if (auto *vari_param_ctx = context->vari_parameter_decl()) {
ParameterDeclPtr vari_parameter_decl = GetFromCtxIfExist<ParameterDeclPtr>(vari_param_ctx);
params.emplace_back(vari_parameter_decl);
}
return params;
}
antlrcpp::Any CST2ASTConvert::visitParameter_decl(rexLangParser::Parameter_declContext *context) {
ParameterDeclPtr parameter_decl = CreateNode<ParameterDecl>(context->getStart(), context->getStop());
parameter_decl->name_ = GetTextIfExist(context->name);
parameter_decl->type_name_ = GetTextIfExist(context->type);
parameter_decl->attributes_ = GetTextVecIfExist(context->attributes);
parameter_decl->comment_ = GetFromCtxIfExist<TString>(context->table_comment());
return NodeWarp(parameter_decl);
}
antlrcpp::Any CST2ASTConvert::visitVari_parameter_decl(rexLangParser::Vari_parameter_declContext *context) {
ParameterDeclPtr parameter_decl = CreateNode<ParameterDecl>(context->getStart(), context->getStop());
parameter_decl->name_ = GetTextIfExist(context->name);
parameter_decl->type_name_ = GetTextIfExist(context->type);
parameter_decl->attributes_ = GetTextVecIfExist(context->attributes);
parameter_decl->comment_ = GetFromCtxIfExist<TString>(context->table_comment());
return NodeWarp(parameter_decl);
}
antlrcpp::Any CST2ASTConvert::visitMember_vari_decl(rexLangParser::Member_vari_declContext *context) {
VariableDeclPtr variable_decl = GetFromCtxIfExist<VariableDeclPtr>(context->variable_decl());
MemberVariableDeclPtr member_variable_decl = nullptr;
if (variable_decl) {
member_variable_decl = CreateNode<MemberVariableDecl>(context->getStart(), context->getStop());
member_variable_decl->dimension_ = variable_decl->dimension_;
member_variable_decl->type_name_ = variable_decl->type_name_;
member_variable_decl->type_decl_ptr_ = variable_decl->type_decl_ptr_;
member_variable_decl->name_ = variable_decl->name_;
member_variable_decl->comment_ = variable_decl->comment_;
delete variable_decl;
}
return NodeWarp(member_variable_decl);
}
antlrcpp::Any CST2ASTConvert::visitFile_vari_decl(rexLangParser::File_vari_declContext *context) {
VariableDeclPtr variable_decl = GetFromCtxIfExist<VariableDeclPtr>(context->variable_decl());
FileVariableDeclPtr file_variable_decl = nullptr;
if (variable_decl) {
file_variable_decl = CreateNode<FileVariableDecl>(context->getStart(), context->getStop());
file_variable_decl->dimension_ = variable_decl->dimension_;
file_variable_decl->type_name_ = variable_decl->type_name_;
file_variable_decl->type_decl_ptr_ = variable_decl->type_decl_ptr_;
file_variable_decl->name_ = variable_decl->name_;
file_variable_decl->comment_ = variable_decl->comment_;
delete variable_decl;
}
return NodeWarp(file_variable_decl);
}
antlrcpp::Any CST2ASTConvert::visitStatement_list(rexLangParser::Statement_listContext *context) {
StatementBlockPtr statement_list = CreateNode<StatementBlock>(context->getStart(), context->getStop());
for (auto *stmt_ctx : context->stmts) {
statement_list->statements_.push_back(GetFromCtxIfExist<StatementPtr>(stmt_ctx));
}
return NodeWarp(statement_list);
}
antlrcpp::Any CST2ASTConvert::visitConditionStatement(rexLangParser::ConditionStatementContext *context) {
return NodeWarp(GetFromCtxIfExist<StatementPtr>(context->condition_statement()));
}
antlrcpp::Any CST2ASTConvert::visitAssignStatement(rexLangParser::AssignStatementContext *context) {
AssignStmtPtr assign_stmt = CreateNode<AssignStmt>(context->getStart(), context->getStop());
assign_stmt->lhs_ = GetFromCtxIfExist<HierarchyIdentifierPtr>(context->hierarchy_identifier());
assign_stmt->rhs_ = GetFromCtxIfExist<ExpressionPtr>(context->expression());
return NodeWarp(assign_stmt);
}
antlrcpp::Any CST2ASTConvert::visitExpressionStatement(rexLangParser::ExpressionStatementContext *context) {
return NodeWarp(GetFromCtxIfExist<StatementPtr>(context->expression()));
}
antlrcpp::Any CST2ASTConvert::visitLoopStatement(rexLangParser::LoopStatementContext *context) {
return NodeWarp(GetFromCtxIfExist<StatementPtr>(context->loop_statement()));
}
antlrcpp::Any CST2ASTConvert::visitSwitchStatement(rexLangParser::SwitchStatementContext *context) {
return NodeWarp(GetFromCtxIfExist<StatementPtr>(context->switch_statement()));
}
antlrcpp::Any CST2ASTConvert::visitSwitch_statement(rexLangParser::Switch_statementContext *context) {
IfStmtPtr switch_stmt = CreateNode<IfStmt>(context->getStart(), context->getStop());
ExpressionPtr major_cond_expr = GetFromCtxIfExist<ExpressionPtr>(context->major_condition_expr);
StatementPtr major_cond_body = GetFromCtxIfExist<StatementPtr>(context->major_cond_body);
switch_stmt->switches_.push_back(std::pair(major_cond_expr, major_cond_body));
assert(context->minor_condition_expr.size() == context->minor_cond_body.size());
for (size_t idx = 0; idx < context->minor_condition_expr.size(); idx++) {
ExpressionPtr minor_cond_expr = GetFromCtxIfExist<ExpressionPtr>(context->minor_condition_expr[idx]);
StatementPtr minor_cond_body = GetFromCtxIfExist<StatementPtr>(context->minor_cond_body[idx]);
switch_stmt->switches_.push_back(std::pair(minor_cond_expr, minor_cond_body));
}
switch_stmt->default_statement_ = GetFromCtxIfExist<StatementPtr>(context->default_body);
return NodeWarp(switch_stmt);
}
antlrcpp::Any CST2ASTConvert::visitWhile(rexLangParser::WhileContext *context) {
WhileStmtPtr while_stmt = CreateNode<WhileStmt>(context->getStart(), context->getStop());
while_stmt->condition_ = GetFromCtxIfExist<ExpressionPtr>(context->condition_expr);
while_stmt->loop_body_ = GetFromCtxIfExist<StatementPtr>(context->loop_body);
return NodeWarp(while_stmt);
}
antlrcpp::Any CST2ASTConvert::visitRangeFor(rexLangParser::RangeForContext *context) {
RangeForStmtPtr range_for_stmt = CreateNode<RangeForStmt>(context->getStart(), context->getStop());
range_for_stmt->range_size_ = GetFromCtxIfExist<ExpressionPtr>(context->times_expr);
range_for_stmt->loop_vari_ = GetFromCtxIfExist<HierarchyIdentifierPtr>(context->loop_variable);
range_for_stmt->loop_body_ = GetFromCtxIfExist<StatementPtr>(context->loop_body);
return NodeWarp(range_for_stmt);
}
antlrcpp::Any CST2ASTConvert::visitFor(rexLangParser::ForContext *context) {
ForStmtPtr for_stmt = CreateNode<ForStmt>(context->getStart(), context->getStop());
for_stmt->start_value_ = GetFromCtxIfExist<ExpressionPtr>(context->loop_start);
for_stmt->stop_value_ = GetFromCtxIfExist<ExpressionPtr>(context->loop_end);
for_stmt->step_value_ = GetFromCtxIfExist<ExpressionPtr>(context->loop_step);
for_stmt->loop_vari_ = GetFromCtxIfExist<HierarchyIdentifierPtr>(context->loop_variable);
for_stmt->loop_body_ = GetFromCtxIfExist<StatementPtr>(context->loop_body);
return NodeWarp(for_stmt);
}
antlrcpp::Any CST2ASTConvert::visitDoWhile(rexLangParser::DoWhileContext *context) {
DoWhileStmtPtr do_while_stmt = CreateNode<DoWhileStmt>(context->getStart(), context->getStop());
do_while_stmt->loop_body_ = GetFromCtxIfExist<StatementPtr>(context->loop_body);
do_while_stmt->conditon_ = GetFromCtxIfExist<ExpressionPtr>(context->condition_expr);
return NodeWarp(do_while_stmt);
}
antlrcpp::Any CST2ASTConvert::visitIfStmt(rexLangParser::IfStmtContext *context) {
IfStmtPtr if_stmt = CreateNode<IfStmt>(context->getStart(), context->getStop());
ExpressionPtr condition = GetFromCtxIfExist<ExpressionPtr>(context->condition_expr);
StatementPtr true_statement = GetFromCtxIfExist<StatementPtr>(context->true_stmt_list);
if_stmt->switches_.push_back(std::pair(condition, true_statement));
if_stmt->default_statement_ = GetFromCtxIfExist<StatementPtr>(context->false_stmt_list);
return NodeWarp(if_stmt);
}
antlrcpp::Any CST2ASTConvert::visitIfTrueStmt(rexLangParser::IfTrueStmtContext *context) {
IfStmtPtr if_stmt = CreateNode<IfStmt>(context->getStart(), context->getStop());
ExpressionPtr condition = GetFromCtxIfExist<ExpressionPtr>(context->condition_expr);
StatementPtr true_statement = GetFromCtxIfExist<StatementPtr>(context->true_stmt_list);
if_stmt->switches_.push_back(std::pair(condition, true_statement));
return NodeWarp(if_stmt);
}
antlrcpp::Any CST2ASTConvert::visitControlStatement(rexLangParser::ControlStatementContext *context) {
return NodeWarp(GetFromCtxIfExist<ControlStmtPtr>(context->control_statement()));
}
antlrcpp::Any CST2ASTConvert::visitContinueStmt(rexLangParser::ContinueStmtContext *context) {
ContinueStmtPtr continue_stmt = CreateNode<ContinueStmt>(context->getStart(), context->getStop());
return NodeWarp(continue_stmt);
}
antlrcpp::Any CST2ASTConvert::visitBreakStmt(rexLangParser::BreakStmtContext *context) {
BreakStmtPtr break_stmt = CreateNode<BreakStmt>(context->getStart(), context->getStop());
return NodeWarp(break_stmt);
}
antlrcpp::Any CST2ASTConvert::visitReturnStmt(rexLangParser::ReturnStmtContext *context) {
ReturnStmtPtr return_stmt = CreateNode<ReturnStmt>(context->getStart(), context->getStop());
return_stmt->return_value_ = GetFromCtxIfExist<ExpressionPtr>(context->return_expr);
return NodeWarp(return_stmt);
}
antlrcpp::Any CST2ASTConvert::visitExitStmt(rexLangParser::ExitStmtContext *context) {
ExitStmtPtr exit_stmt = CreateNode<ExitStmt>(context->getStart(), context->getStop());
return NodeWarp(exit_stmt);
}
antlrcpp::Any CST2ASTConvert::visitHierarchy_identifier(rexLangParser::Hierarchy_identifierContext *context) {
HierarchyIdentifierPtr hierarchy_identifier = CreateNode<HierarchyIdentifier>(context->getStart(), context->getStop());
NameComponentPtr forward_name_component_ = nullptr;
for (auto *name_component_ctx : context->components) {
NameComponentPtr name_component = GetFromCtxIfExist<NameComponentPtr, true>(name_component_ctx);
hierarchy_identifier->name_components_.push_back(name_component);
if (forward_name_component_) {
forward_name_component_->backward_name_component_ = name_component;
}
name_component->forward_name_component_ = forward_name_component_;
forward_name_component_ = name_component;
}
return NodeWarp(hierarchy_identifier);
}
antlrcpp::Any CST2ASTConvert::visitFuncCall(rexLangParser::FuncCallContext *context) {
FunctionCallPtr function_call = CreateNode<FunctionCall>(context->getStart(), context->getStop());
function_call->function_name_ = GetFromCtxIfExist<NameComponentPtr, true>(context->name_component());
for (auto *arg_ctx : context->arguments) {
ExpressionPtr arg_expr = GetFromCtxIfExist<ExpressionPtr>(arg_ctx);
function_call->arguments_.push_back(arg_expr);
}
return NodeWarp(function_call);
}
antlrcpp::Any CST2ASTConvert::visitIdentifier(rexLangParser::IdentifierContext *context) {
IdentifierPtr identifier = CreateNode<Identifier>(context->getStart(), context->getStop());
identifier->name_ = GetTextIfExist(context->IDENTIFIER()->getSymbol());
return NodeWarp(identifier);
}
antlrcpp::Any CST2ASTConvert::visitArrayIndex(rexLangParser::ArrayIndexContext *context) {
ArrayIndexPtr array_index = CreateNode<ArrayIndex>(context->getStart(), context->getStop());
array_index->base_ = GetFromCtxIfExist<NameComponentPtr, true>(context->name_component());
array_index->index_ = GetFromCtxIfExist<ExpressionPtr>(context->expression());
return NodeWarp(array_index);
}
antlrcpp::Any CST2ASTConvert::visitBracket(rexLangParser::BracketContext *context) {
return NodeWarp(GetFromCtxIfExist<ExpressionPtr>(context->expression()));
}
antlrcpp::Any CST2ASTConvert::visitOptElement(rexLangParser::OptElementContext *context) {
return NodeWarp(GetFromCtxIfExist<ExpressionPtr>(context->getRuleContext<antlr4::ParserRuleContext>(0)));
}
antlrcpp::Any CST2ASTConvert::visitBinaryExpr(rexLangParser::BinaryExprContext *context) {
BinaryExpressionPtr binary_expression = CreateNode<BinaryExpression>(context->getStart(), context->getStop());
binary_expression->operator_ = GetTextIfExist(context->opt);
switch (context->opt->getType()) {
case rexLangParser::K_ADD_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptAdd; break;
case rexLangParser::K_SUB_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptSub; break;
case rexLangParser::K_MUL_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptMul; break;
case rexLangParser::K_DIV_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptDiv; break;
case rexLangParser::K_FULL_DIV_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptFullDiv; break;
case rexLangParser::K_MOD_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptMod; break;
case rexLangParser::K_AECOM_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptEqual; break;
case rexLangParser::K_ASSIGN_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptEqual; break;
case rexLangParser::K_EQUAL_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptEqual; break;
case rexLangParser::K_NOT_EQUAL_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptNotEqual; break;
case rexLangParser::K_GREAT_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptGreatThan; break;
case rexLangParser::K_LESS_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptLessThan; break;
case rexLangParser::K_GREAT_EQU_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptGreatEqual; break;
case rexLangParser::K_LESS_EQU_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptLessEqual; break;
case rexLangParser::K_LIKE_EQU_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptLikeEqual; break;
case rexLangParser::K_AND_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptAnd; break;
case rexLangParser::K_OR_OPT: binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptOr; break;
default: assert(false); binary_expression->operator_type_ = BinaryExpression::OperatorType::kOptNone; break;
}
binary_expression->lhs_ = GetFromCtxIfExist<ExpressionPtr>(context->lval);
binary_expression->rhs_ = GetFromCtxIfExist<ExpressionPtr>(context->rval);
return NodeWarp(binary_expression);
}
antlrcpp::Any CST2ASTConvert::visitUnaryExpr(rexLangParser::UnaryExprContext *context) {
UnaryExpressionPtr unary_expression = CreateNode<UnaryExpression>(context->getStart(), context->getStop());
unary_expression->operator_ = GetTextIfExist(context->opt);
switch (context->opt->getType()) {
case rexLangParser::K_SUB_OPT: unary_expression->operator_type_ = UnaryExpression::OperatorType::kOptSub; break;
default: assert(false); unary_expression->operator_type_ = UnaryExpression::OperatorType::kOptNone; break;
}
unary_expression->operand_value_ = GetFromCtxIfExist<ExpressionPtr>(context->expression());
return NodeWarp(unary_expression);
}
antlrcpp::Any CST2ASTConvert::visitData_set_value(rexLangParser::Data_set_valueContext *context) {
ValueOfDataSetPtr value_of_data_set = CreateNode<ValueOfDataSet>(context->getStart(), context->getStop());
for (auto *elem_ctx : context->elems) {
value_of_data_set->elements_.push_back(GetFromCtxIfExist<ExpressionPtr>(elem_ctx));
}
return NodeWarp(value_of_data_set);
}
antlrcpp::Any CST2ASTConvert::visitDatetime_value(rexLangParser::Datetime_valueContext *context) {
return NodeWarp(GetFromCtxIfExist<ValueOfDatetimePtr>(context->datetime_value_core()));
}
ValueOfDatetimePtr CST2ASTConvert::TimeNodeBuilder(time_t time, antlr4::Token *start_token, antlr4::Token *end_token) {
ValueOfDatetimePtr value_of_datetime = CreateNode<ValueOfDatetime>(start_token, end_token);
value_of_datetime->time_ = time;
return value_of_datetime;
}
antlrcpp::Any CST2ASTConvert::visitDatetimePureNumber(rexLangParser::DatetimePureNumberContext *context) {
TString time_str = GetTextIfExist(context->time);
return TimeNodeBuilder(strtoul(time_str.string_.c_str(), nullptr, 10), context->getStart(), context->getStop());
}
tm CST2ASTConvert::TimeBuilder(unsigned year, unsigned month, unsigned day, unsigned hour, unsigned minute, unsigned second) {
tm new_time;
memset(&new_time, '\0', sizeof(tm));
new_time.tm_year = year;
new_time.tm_mon = month;
new_time.tm_mday = day;
new_time.tm_hour = hour;
new_time.tm_min = minute;
new_time.tm_sec = second;
return new_time;
}
ValueOfDatetimePtr CST2ASTConvert::TimeNodeBuilder(tm &&stm, antlr4::Token *start_token, antlr4::Token *end_token) {
return TimeNodeBuilder(mktime(&stm), start_token, end_token);
}
antlrcpp::Any CST2ASTConvert::visitDatetimeSeparateByChinese(rexLangParser::DatetimeSeparateByChineseContext *context) {
ValueOfDatetimePtr new_time = TimeNodeBuilder(TimeBuilder(
GetLongIfExist(context->year),
GetLongIfExist(context->month),
GetLongIfExist(context->day),
GetLongIfExist(context->hour),
GetLongIfExist(context->minute),
GetLongIfExist(context->second)
), context->getStart(), context->getStop());
return NodeWarp(new_time);
}
antlrcpp::Any CST2ASTConvert::visitDatetimeSeparateBySlash(rexLangParser::DatetimeSeparateBySlashContext *context) {
ValueOfDatetimePtr new_time = TimeNodeBuilder(TimeBuilder(
GetLongIfExist(context->year),
GetLongIfExist(context->month),
GetLongIfExist(context->day),
GetLongIfExist(context->hour),
GetLongIfExist(context->minute),
GetLongIfExist(context->second)
), context->getStart(), context->getStop());
return NodeWarp(new_time);
}
antlrcpp::Any CST2ASTConvert::visitDatetimeSeparateBySlashColon(rexLangParser::DatetimeSeparateBySlashColonContext *context) {
ValueOfDatetimePtr new_time = TimeNodeBuilder(TimeBuilder(
GetLongIfExist(context->year),
GetLongIfExist(context->month),
GetLongIfExist(context->day),
GetLongIfExist(context->hour),
GetLongIfExist(context->minute),
GetLongIfExist(context->second)
), context->getStart(), context->getStop());
return NodeWarp(new_time);
}
antlrcpp::Any CST2ASTConvert::visitDatetimeSeparateByBar(rexLangParser::DatetimeSeparateByBarContext *context) {
ValueOfDatetimePtr new_time = TimeNodeBuilder(TimeBuilder(
GetLongIfExist(context->year),
GetLongIfExist(context->month),
GetLongIfExist(context->day),
GetLongIfExist(context->hour),
GetLongIfExist(context->minute),
GetLongIfExist(context->second)
), context->getStart(), context->getStop());
return NodeWarp(new_time);
}
antlrcpp::Any CST2ASTConvert::visitDatetimeSeparateByBarColon(rexLangParser::DatetimeSeparateByBarColonContext *context) {
ValueOfDatetimePtr new_time = TimeNodeBuilder(TimeBuilder(
GetLongIfExist(context->year),
GetLongIfExist(context->month),
GetLongIfExist(context->day),
GetLongIfExist(context->hour),
GetLongIfExist(context->minute),
GetLongIfExist(context->second)
), context->getStart(), context->getStop());
return NodeWarp(new_time);
}
antlrcpp::Any CST2ASTConvert::visitMacro_value(rexLangParser::Macro_valueContext *context) {
ResourceRefExpressionPtr resource_ref_expression = CreateNode<ResourceRefExpression>(context->getStart(), context->getStop());
resource_ref_expression->resource_name_ = GetTextIfExist(context->IDENTIFIER()->getSymbol());
return NodeWarp(resource_ref_expression);
}
antlrcpp::Any CST2ASTConvert::visitFunc_ptr(rexLangParser::Func_ptrContext *context) {
FuncAddrExpressionPtr func_addr_expression = CreateNode<FuncAddrExpression>(context->getStart(), context->getStop());
func_addr_expression->function_name_ = GetTextIfExist(context->IDENTIFIER()->getSymbol());
return NodeWarp(func_addr_expression);
}
antlrcpp::Any CST2ASTConvert::visitBoolValueTrue(rexLangParser::BoolValueTrueContext *context) {
ValueOfBoolPtr value_of_bool = CreateNode<ValueOfBool>(context->getStart(), context->getStop());
value_of_bool->value_ = true;
return NodeWarp(value_of_bool);
}
antlrcpp::Any CST2ASTConvert::visitBoolValueFalse(rexLangParser::BoolValueFalseContext *context) {
ValueOfBoolPtr value_of_bool = CreateNode<ValueOfBool>(context->getStart(), context->getStop());
value_of_bool->value_ = false;
return NodeWarp(value_of_bool);
}
antlrcpp::Any CST2ASTConvert::visitInt(rexLangParser::IntContext *context) {
ValueOfDecimalPtr value_of_decimal = CreateNode<ValueOfDecimal>(context->getStart(), context->getStop());
value_of_decimal->int_val_ = GetLongIfExist(context->INTEGER_LITERAL()->getSymbol());
value_of_decimal->type_ = ValueOfDecimal::type::kInt;
return NodeWarp(value_of_decimal);
}
antlrcpp::Any CST2ASTConvert::visitFloat(rexLangParser::FloatContext *context) {
ValueOfDecimalPtr value_of_decimal = CreateNode<ValueOfDecimal>(context->getStart(), context->getStop());
value_of_decimal->float_val_ = GetFloatIfExist(context->FLOAT_LITERAL()->getSymbol());
value_of_decimal->type_ = ValueOfDecimal::type::kFloat;
return NodeWarp(value_of_decimal);
}
antlrcpp::Any CST2ASTConvert::visitString_value(rexLangParser::String_valueContext *context) {
ValueOfStringPtr value_of_string = CreateNode<ValueOfString>(context->getStart(), context->getStop());
value_of_string->string_literal_ = GetTextIfExist(context->STRING_LITERAL()->getSymbol());
RemoveRoundQuotes(value_of_string->string_literal_);
return NodeWarp(value_of_string);
}
CST2ASTConvert::CST2ASTConvert(ASTContext *ast_context, Diagnostic *diagnostic)
: ast_context_(ast_context) {
}
TranslateUnitPtr CST2ASTConvert::BuildTranslateUnitFromParseTree(antlr4::tree::ParseTree *tree) {
antlrcpp::Any build_result = this->visit(tree);
TranslateUnitPtr translate_unit = nullptr;
if (build_result.is<NodeWarp>()) {
if ((translate_unit = build_result.as<NodeWarp>())) {
return translate_unit;
} else {
assert(false);
return nullptr;
}
} else {
assert(false);
return nullptr;
}
}
}
| 55.860656 | 156 | 0.707777 | [
"vector"
] |
187e1e1cc87d33798df9aca42049833d319d6800 | 5,156 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/os/SomeArgs.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/os/SomeArgs.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/os/SomeArgs.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/internal/os/SomeArgs.h"
#include <elastos/core/AutoLock.h>
#include <elastos/utility/logging/Logger.h>
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace Internal {
namespace Os {
const Int32 SomeArgs::MAX_POOL_SIZE = 10;
AutoPtr<SomeArgs> SomeArgs::sPool;
Int32 SomeArgs::sPoolSize = 0;
Object SomeArgs::sPoolLock;
const Int32 SomeArgs::WAIT_NONE;
const Int32 SomeArgs::WAIT_WAITING;
const Int32 SomeArgs::WAIT_FINISHED;
CAR_INTERFACE_IMPL(SomeArgs, Object, ISomeArgs)
SomeArgs::SomeArgs()
: mWaitState(WAIT_NONE)
, mArgi1(0)
, mArgi2(0)
, mArgi3(0)
, mArgi4(0)
, mArgi5(0)
, mArgi6(0)
, mInPool(FALSE)
{
/* do nothing - reduce visibility */
}
AutoPtr<SomeArgs> SomeArgs::Obtain()
{
AutoLock lock(sPoolLock);
if (sPoolSize > 0) {
AutoPtr<SomeArgs> args = sPool;
sPool = sPool->mNext;
args->mNext = NULL;
args->mInPool = FALSE;
--sPoolSize;
return args;
}
else {
AutoPtr<SomeArgs> args = new SomeArgs();
return args;
}
}
ECode SomeArgs::Recycle()
{
if (mInPool) {
return E_ILLEGAL_STATE_EXCEPTION;
}
if (mWaitState != WAIT_NONE) {
return NOERROR;
}
AutoLock lock(sPoolLock);
Clear();
if (sPoolSize < MAX_POOL_SIZE) {
mNext = sPool;
mInPool = TRUE;
sPool = this;
++sPoolSize;
}
return NOERROR;
}
void SomeArgs::Clear()
{
mArg1 = NULL;
mArg2 = NULL;
mArg3 = NULL;
mArg4 = NULL;
mArg5 = NULL;
mArg6 = NULL;
mArgi1 = 0;
mArgi2 = 0;
mArgi3 = 0;
mArgi4 = 0;
mArgi5 = 0;
mArgi6 = 0;
}
ECode SomeArgs::GetObjectArg(
/* [in] */ Int32 index,
/* [out] */ IInterface** arg)
{
VALIDATE_NOT_NULL(arg)
switch (index) {
case 1:
*arg = mArg1;
REFCOUNT_ADD(*arg);
break;
case 2:
*arg = mArg2;
REFCOUNT_ADD(*arg);
break;
case 3:
*arg = mArg3;
REFCOUNT_ADD(*arg);
break;
case 4:
*arg = mArg4;
REFCOUNT_ADD(*arg);
break;
case 5:
*arg = mArg5;
REFCOUNT_ADD(*arg);
break;
case 6:
*arg = mArg6;
REFCOUNT_ADD(*arg);
break;
default:
Logger::E("SomeArgs", "GetObjectArg invalid index!");
}
return NOERROR;
}
ECode SomeArgs::SetObjectArg(
/* [in] */ Int32 index,
/* [in] */ IInterface* arg)
{
switch (index) {
case 1:
mArg1 = arg;
break;
case 2:
mArg2 = arg;
break;
case 3:
mArg3 = arg;
break;
case 4:
mArg4 = arg;
break;
case 5:
mArg5 = arg;
break;
case 6:
mArg6 = arg;
break;
default:
Logger::E("SomeArgs", "SetObjectArg invalid index!");
}
return NOERROR;
}
ECode SomeArgs::GetInt32Arg(
/* [in] */ Int32 index,
/* [out] */ Int32* arg)
{
VALIDATE_NOT_NULL(arg)
switch (index) {
case 1:
*arg = mArgi1;
break;
case 2:
*arg = mArgi2;
break;
case 3:
*arg = mArgi3;
break;
case 4:
*arg = mArgi4;
break;
case 5:
*arg = mArgi5;
break;
case 6:
*arg = mArgi6;
break;
default:
Logger::E("SomeArgs", "GetInt32Arg invalid index!");
}
return NOERROR;
}
ECode SomeArgs::SetInt32Arg(
/* [in] */ Int32 index,
/* [in] */ Int32 arg)
{
switch (index) {
case 1:
mArgi1 = arg;
break;
case 2:
mArgi2 = arg;
break;
case 3:
mArgi3 = arg;
break;
case 4:
mArgi4 = arg;
break;
case 5:
mArgi5 = arg;
break;
case 6:
mArgi6 = arg;
break;
default:
Logger::E("SomeArgs", "SetInt32Arg invalid index!");
}
return NOERROR;
}
} // namespace Os
} // namespace Internal
} // namespace Droid
} // namespace Elastos
| 21.940426 | 75 | 0.505625 | [
"object"
] |
187ea38249b9c0105d9a2acf61b98bed6a7de036 | 38,094 | cpp | C++ | EngineLayer/NonSpecificEnzymeSearch/NonSpecificEnzymeSearchEngine.cpp | edgargabriel/HPCMetaMorpheus | 160cc269464b8e563fa2f62f6843690b6a2533ee | [
"MIT"
] | 2 | 2020-09-10T19:14:20.000Z | 2021-09-11T16:36:56.000Z | EngineLayer/NonSpecificEnzymeSearch/NonSpecificEnzymeSearchEngine.cpp | edgargabriel/HPCMetaMorpheus | 160cc269464b8e563fa2f62f6843690b6a2533ee | [
"MIT"
] | null | null | null | EngineLayer/NonSpecificEnzymeSearch/NonSpecificEnzymeSearchEngine.cpp | edgargabriel/HPCMetaMorpheus | 160cc269464b8e563fa2f62f6843690b6a2533ee | [
"MIT"
] | 3 | 2020-09-11T01:19:47.000Z | 2021-09-02T02:05:01.000Z | #include <optional>
#include "NonSpecificEnzymeSearchEngine.h"
#include "../PeptideSpectralMatch.h"
#include "../CommonParameters.h"
#include "../Ms2ScanWithSpecificMass.h"
#include "../PrecursorSearchModes/MassDiffAcceptor.h"
#include "../MetaMorpheusEngineResults.h"
#include "../EventArgs/ProgressEventArgs.h"
#include "../ProteinScoringAndFdr/FdrClassifier.h"
#include "bankersrounding.h"
#include "Group.h"
using namespace Chemistry;
using namespace EngineLayer::FdrAnalysis;
using namespace EngineLayer::ModernSearch;
using namespace Proteomics;
using namespace Proteomics::Fragmentation;
using namespace Proteomics::ProteolyticDigestion;
namespace EngineLayer
{
namespace NonSpecificEnzymeSearch
{
//const double NonSpecificEnzymeSearchEngine::WaterMonoisotopicMass = PeriodicTable::GetElement("H")->getPrincipalIsotope()->getAtomicMass() * 2 + PeriodicTable::GetElement("O")->getPrincipalIsotope()->getAtomicMass();
// Edgar: replacing by the actual value obtained by running
const double NonSpecificEnzymeSearchEngine::WaterMonoisotopicMass = 18.01056468403;
NonSpecificEnzymeSearchEngine::NonSpecificEnzymeSearchEngine(std::vector<std::vector<PeptideSpectralMatch*>> &globalPsms,
std::vector<Ms2ScanWithSpecificMass*> &listOfSortedms2Scans,
std::vector<PeptideWithSetModifications*> &peptideIndex,
std::vector<std::vector<int>> &fragmentIndex,
std::vector<std::vector<int>> &precursorIndex,
int currentPartition,
CommonParameters *commonParams,
MassDiffAcceptor *massDiffAcceptor,
double maximumMassThatFragmentIonScoreIsDoubled,
std::vector<std::string> nestedIds,
int verbosityLevel) :
ModernSearchEngine(unusedPsms,
listOfSortedms2Scans,
peptideIndex,
fragmentIndex,
currentPartition,
commonParams,
massDiffAcceptor,
maximumMassThatFragmentIonScoreIsDoubled,
nestedIds,
verbosityLevel),
PrecursorIndex(precursorIndex),
MinimumPeptideLength(commonParameters->getDigestionParams()->getMinPeptideLength())
{
GlobalCategorySpecificPsms = globalPsms;
//ModifiedParametersNoComp = commonParameters->CloneWithNewTerminus(, std::make_optional(false));
std::optional<FragmentationTerminus> t1;
std::optional<bool> t2;
ModifiedParametersNoComp = new CommonParameters(commonParams, t1, t2);
#ifdef ORIG
ProductTypesToSearch = DissociationTypeCollection::ProductsFromDissociationType[commonParameters->getDissociationType()].
Intersect(
TerminusSpecificProductTypes::ProductIonTypesFromSpecifiedTerminus[commonParameters->getDigestionParams()->getFragmentationTerminus()]);
#endif
std::vector<ProductType> t3 = DissociationTypeCollection::ProductsFromDissociationType[commonParameters->getDissociationType()];
std::vector<ProductType> t4 = TerminusSpecificProductTypes::ProductIonTypesFromSpecifiedTerminus[commonParameters->getDigestionParams()->getFragmentationTerminus()];
for ( auto p: t3 ) {
bool found = false;
for ( auto q : t4 ) {
if ( p == q ) {
found = true;
break;
}
}
if ( found ) {
ProductTypesToSearch.push_back(p);
}
}
}
MetaMorpheusEngineResults *NonSpecificEnzymeSearchEngine::RunSpecific()
{
double progress = 0;
int oldPercentProgress = 0;
ProgressEventArgs tempVar(oldPercentProgress, "Performing nonspecific search... " +
std::to_string(CurrentPartition) + "/" +
std::to_string(commonParameters->getTotalPartitions()),
const_cast<std::vector<std::string>&>(nestedIds));
ReportProgress(&tempVar);
unsigned char byteScoreCutoff = static_cast<unsigned char>(commonParameters->getScoreCutoff());
#ifdef ORIG
//ParallelOptions *tempVar2 = new ParallelOptions();
//tempVar2->MaxDegreeOfParallelism = commonParameters->getMaxThreadsToUsePerFile();
// Parallel::ForEach(Partitioner::Create(0, ListOfSortedMs2Scans.size()), tempVar2, [&] (std::any range) {
#endif
std::vector<unsigned char> scoringTable(PeptideIndex.size());
std::unordered_set<int> idsOfPeptidesPossiblyObserved;
#ifdef ORIG
//for (int i = range::Item1; i < range::Item2; i++)
#endif
for (int i = 0; i < (int)ListOfSortedMs2Scans.size(); i++)
{
// empty the scoring table to score the new scan (conserves memory compared to allocating a new array)
//Array::Clear(scoringTable, 0, scoringTable.Length);
scoringTable.clear();
idsOfPeptidesPossiblyObserved.clear();
Ms2ScanWithSpecificMass *scan = ListOfSortedMs2Scans[i];
//get bins to add points to
std::vector<int> allBinsToSearch = GetBinsToSearch(scan);
//the entire indexed scoring is done here
for (int j = 0; j < (int)allBinsToSearch.size(); j++)
{
for (auto id = FragmentIndex[allBinsToSearch[j]].begin(); id!=FragmentIndex[allBinsToSearch[j]].end(); id++) {
scoringTable[*id]++;
}
}
//populate ids of possibly observed with those containing allowed precursor masses
std::vector<AllowedIntervalWithNotch*> validIntervals = massDiffAcceptor->GetAllowedPrecursorMassIntervalsFromObservedMass(scan->getPrecursorMass()); //.ToList(); //get all valid notches
for (auto interval : validIntervals)
{
int obsPrecursorFloorMz = static_cast<int>(std::floor(interval->AllowedInterval->getMinimum() * FragmentBinsPerDalton));
int obsPrecursorCeilingMz = static_cast<int>(std::ceil(interval->AllowedInterval->getMaximum() * FragmentBinsPerDalton));
for (auto pt : ProductTypesToSearch)
{
int dissociationBinShift = static_cast<int>(BankersRounding::round((WaterMonoisotopicMass -
DissociationTypeCollection::GetMassShiftFromProductType(pt))
* FragmentBinsPerDalton));
int lowestBin = obsPrecursorFloorMz - dissociationBinShift;
int highestBin = obsPrecursorCeilingMz - dissociationBinShift;
for (int bin = lowestBin; bin <= highestBin; bin++)
{
if (bin < (int)FragmentIndex.size() && FragmentIndex[bin].size() > 0)
{
for (auto id = FragmentIndex[bin].begin(); id != FragmentIndex[bin].end(); id++ ) {
idsOfPeptidesPossiblyObserved.insert(*id);
}
}
}
}
for (int bin = obsPrecursorFloorMz; bin <= obsPrecursorCeilingMz; bin++) //no bin shift, since they're precursor masses
{
if (bin < (int)PrecursorIndex.size() && PrecursorIndex[bin].size() > 0)
{
for (auto id = PrecursorIndex[bin].begin(); id != PrecursorIndex[bin].end(); id++) {
idsOfPeptidesPossiblyObserved.insert(*id);
}
}
}
}
// done with initial scoring; refine scores and create PSMs
if (!idsOfPeptidesPossiblyObserved.empty())
{
int maxInitialScore= scoringTable[0];
for ( auto id : idsOfPeptidesPossiblyObserved ) {
if ( maxInitialScore < scoringTable[id] ) {
maxInitialScore = scoringTable[id];
}
};
maxInitialScore += 1;
while (maxInitialScore > commonParameters->getScoreCutoff()) //go through all until we hit the end
{
maxInitialScore--;
for (int id : idsOfPeptidesPossiblyObserved ) {
if ( scoringTable[id] != maxInitialScore ) {
continue;
}
PeptideWithSetModifications *peptide = PeptideIndex[id];
std::vector<Product*> peptideTheorProducts = peptide->Fragment(
commonParameters->getDissociationType(),
commonParameters->getDigestionParams()->getFragmentationTerminus());
std::tuple<int, PeptideWithSetModifications*> notchAndUpdatedPeptide = Accepts(peptideTheorProducts,
scan->getPrecursorMass(),
peptide,
commonParameters->getDigestionParams()->getFragmentationTerminus(),
massDiffAcceptor);
int notch = std::get<0>(notchAndUpdatedPeptide);
if (notch >= 0)
{
peptide = std::get<1>(notchAndUpdatedPeptide);
peptideTheorProducts = peptide->Fragment(commonParameters->getDissociationType(),
FragmentationTerminus::Both);//.ToList();
std::vector<MatchedFragmentIon*> matchedIons = MatchFragmentIons(scan, peptideTheorProducts,
ModifiedParametersNoComp);
double thisScore = CalculatePeptideScore(scan->getTheScan(), matchedIons,
MaxMassThatFragmentIonScoreIsDoubled);
if (thisScore > commonParameters->getScoreCutoff())
{
auto tmp = peptide->getCleavageSpecificityForFdrCategory();
std::vector<PeptideSpectralMatch*> localPeptideSpectralMatches =
GlobalCategorySpecificPsms[static_cast<int>(FdrClassifier::GetCleavageSpecificityCategory(&tmp))];
if (localPeptideSpectralMatches[i] == nullptr)
{
localPeptideSpectralMatches[i] = new PeptideSpectralMatch(peptide, notch, thisScore,
i, scan,
commonParameters->getDigestionParams(),
matchedIons);
}
else
{
localPeptideSpectralMatches[i]->AddOrReplace(peptide, thisScore, notch,
commonParameters->getReportAllAmbiguity(),
matchedIons);
}
}
}
}
}
}
// report search progress
progress++;
int percentProgress = static_cast<int>((progress / ListOfSortedMs2Scans.size()) * 100);
if (percentProgress > oldPercentProgress)
{
oldPercentProgress = percentProgress;
ProgressEventArgs tempVar3(percentProgress, "Performing nonspecific search... " +
std::to_string(CurrentPartition) + "/" +
std::to_string(commonParameters->getTotalPartitions()),
const_cast<std::vector<std::string>&>(nestedIds));
ReportProgress(&tempVar3);
}
}
// });
return new MetaMorpheusEngineResults(this);
}
std::tuple<int, PeptideWithSetModifications*> NonSpecificEnzymeSearchEngine::Accepts(std::vector<Product*> &fragments,
double scanPrecursorMass,
PeptideWithSetModifications *peptide,
FragmentationTerminus fragmentationTerminus,
MassDiffAcceptor *searchMode)
{
//all masses in N and CTerminalMasses are b-ion masses, which are one water away from a full peptide
int localminPeptideLength = commonParameters->getDigestionParams()->getMinPeptideLength();
for (int i = localminPeptideLength - 1; i < (int)fragments.size(); i++) //minus one start, because fragment 1 is at index 0
{
Product *fragment = fragments[i];
double theoMass = fragment->NeutralMass -
DissociationTypeCollection::GetMassShiftFromProductType(fragment->productType) + WaterMonoisotopicMass;
int notch = searchMode->Accepts(scanPrecursorMass, theoMass);
if (notch >= 0)
{
PeptideWithSetModifications *updatedPwsm = nullptr;
if ( fragmentationTerminus == FragmentationTerminus::N)
{
//-1 for one based index
int endResidue = peptide->getOneBasedStartResidueInProtein() + fragment->TerminusFragment->FragmentNumber - 1;
std::unordered_map<int, Modification*> updatedMods;
for (auto mod : peptide->getAllModsOneIsNterminus())
{
//check if we cleaved it off, +1 for N-terminus being mod 1 and first residue being mod 2,
//+1 again for the -1 on end residue for one based index, +1 (again) for the one-based start residue
if (mod.first < endResidue - peptide->getOneBasedStartResidueInProtein() + 3)
{
updatedMods.emplace(mod.first, mod.second);
}
}
updatedPwsm = new PeptideWithSetModifications(peptide->getProtein(), peptide->getDigestionParams(),
peptide->getOneBasedStartResidueInProtein(), endResidue,
CleavageSpecificity::Unknown, "", 0, updatedMods, 0);
}
else
{
//plus one for one based index
int startResidue = peptide->getOneBasedEndResidueInProtein() - fragment->TerminusFragment->FragmentNumber + 1;
std::unordered_map<int, Modification*> updatedMods; //updateMods
int indexShift = startResidue - peptide->getOneBasedStartResidueInProtein();
for (auto mod : peptide->getAllModsOneIsNterminus())
{
if (mod.first > indexShift + 1) //check if we cleaved it off, +1 for N-terminus being mod 1 and first residue being 2
{
int key = mod.first - indexShift;
updatedMods.emplace(key, mod.second);
}
}
updatedPwsm = new PeptideWithSetModifications(peptide->getProtein(), peptide->getDigestionParams(),
startResidue, peptide->getOneBasedEndResidueInProtein(),
CleavageSpecificity::Unknown, "", 0, updatedMods, 0);
}
delete updatedPwsm;
return std::tuple<int, PeptideWithSetModifications*>(notch, updatedPwsm);
}
else if (theoMass > scanPrecursorMass)
{
break;
}
}
//if the theoretical and experimental have the same mass
if ( (int)fragments.size() > localminPeptideLength)
{
double totalMass = peptide->getMonoisotopicMass(); // + Constants.ProtonMass;
int notch = searchMode->Accepts(scanPrecursorMass, totalMass);
if (notch >= 0)
{
auto tempv = peptide->getAllModsOneIsNterminus();
//need to update so that the cleavage specificity is recorded
PeptideWithSetModifications *updatedPwsm = new PeptideWithSetModifications(peptide->getProtein(),
peptide->getDigestionParams(),
peptide->getOneBasedStartResidueInProtein(),
peptide->getOneBasedEndResidueInProtein(),
CleavageSpecificity::Unknown, "", 0,
tempv,
peptide->NumFixedMods);
return std::make_tuple(notch, updatedPwsm);
}
}
return std::make_tuple(-1, nullptr);
}
std::vector<PeptideSpectralMatch*> NonSpecificEnzymeSearchEngine::ResolveFdrCategorySpecificPsms( std::vector<std::vector<PeptideSpectralMatch*>> &AllPsms, int numNotches, const std::string &taskId, CommonParameters *commonParameters )
{
//update all psms with peptide info
#ifdef ORIG
AllPsms.ToList()->Where([&] (std::any psmArray) {
return psmArray != nullptr;
}).ToList()->ForEach([&] (std::any psmArray) {
psmArray::Where([&] (std::any psm) {
return psm != nullptr;
}).ToList()->ForEach([&] (std::any psm){
psm::ResolveAllAmbiguities();
});
});
#endif
std::vector<std::vector<PeptideSpectralMatch*>> tmpPsms;
int current=0;
for ( auto psmArray : AllPsms ) {
auto newvec = new std::vector<PeptideSpectralMatch*> ();
if ( !psmArray.empty() ) {
tmpPsms.push_back(*newvec);
for ( auto psm : psmArray ) {
if ( psm != nullptr ) {
psm->ResolveAllAmbiguities();
tmpPsms[current].push_back(psm);
}
}
current++;
}
}
// Now clear AllPsms and copy everything over.
for ( auto psmArray: AllPsms ) {
if ( !psmArray.empty() ) {
psmArray.clear();
}
}
AllPsms.clear();
current=0;
for ( auto psmArray : tmpPsms ) {
auto newvec = new std::vector<PeptideSpectralMatch*> ();
AllPsms.push_back(*newvec);
for ( auto psm: psmArray ) {
AllPsms[current].push_back(psm);
}
current++;
}
// Clear tmpPsms
for ( auto psmArray: tmpPsms ) {
if ( !psmArray.empty() ) {
psmArray.clear();
}
}
tmpPsms.clear();
for (auto psmsArray : AllPsms)
{
if (psmsArray.size() > 0)
{
#ifdef ORIG
std::vector<PeptideSpectralMatch*> cleanedPsmsArray = psmsArray.Where([&] (std::any b) {
return b != nullptr;
}).OrderByDescending([&] (std::any b) {
b::Score;
}).ThenBy([&] (std::any b) {
b::PeptideMonisotopicMass.HasValue ?
std::abs(b::ScanPrecursorMass - b::PeptideMonisotopicMass->Value) :
std::numeric_limits<double>::max();
}).GroupBy([&] (std::any b) {
(b::FullFilePath, b::ScanNumber, b::PeptideMonisotopicMass);
})->Select([&] (std::any b) {
b::First();
}).ToList();
#endif
std::vector<PeptideSpectralMatch*> tmpPsmsArray;
for ( auto b: psmsArray ) {
if ( b != nullptr ) {
tmpPsmsArray.push_back(b);
}
}
std::sort(tmpPsmsArray.begin(), tmpPsmsArray.end(), [&] (PeptideSpectralMatch* l , PeptideSpectralMatch* r) {
if ( l->getScore() > r->getScore() ) return true;
if ( l->getScore() < r->getScore() ) return false;
double lval = std::numeric_limits<double>::max();
double rval = std::numeric_limits<double>::max();
if ( l->getPeptideMonisotopicMass().has_value() ) {
lval = std::abs(l->getScanPrecursorMass() - l->getPeptideMonisotopicMass().value());
}
if ( r->getPeptideMonisotopicMass().has_value() ) {
rval = std::abs(r->getScanPrecursorMass() - r->getPeptideMonisotopicMass().value());
}
if ( lval < rval ) return true;
return false;
});
std::function<bool(PeptideSpectralMatch*,PeptideSpectralMatch*)> f1 = [&](PeptideSpectralMatch *l, PeptideSpectralMatch *r) {
if ( l->getFullFilePath() < r->getFullFilePath() ) return true;
if ( l->getFullFilePath() > r->getFullFilePath() ) return true;
if ( l->getScanNumber() < r->getScanNumber() ) return true;
if ( l->getScanNumber() > r->getScanNumber() ) return true;
if ( l->getPeptideMonisotopicMass() < r->getPeptideMonisotopicMass() ) return true;
return true;
} ;
std::function<bool(PeptideSpectralMatch*,PeptideSpectralMatch*)> f2 = [&](PeptideSpectralMatch *l, PeptideSpectralMatch *r) {
return l->getFullFilePath() == r->getFullFilePath() &&
l->getScanNumber() == r->getScanNumber() &&
l->getPeptideMonisotopicMass() == r->getPeptideMonisotopicMass();
};
std::vector<std::vector<PeptideSpectralMatch*>> cond = Group::GroupBy ( tmpPsmsArray, f1, f2);
std::vector<PeptideSpectralMatch*> cleanedPsmsArray;
for ( auto c: cond ) {
cleanedPsmsArray.push_back(c.front() );
}
std::vector<std::string> vs1 = {taskId};
FdrAnalysisEngine tempVar(cleanedPsmsArray, numNotches, commonParameters, vs1);
(&tempVar)->Run();
for (int i = 0; i < (int)psmsArray.size(); i++)
{
if (psmsArray[i] != nullptr)
{
if (psmsArray[i]->getFdrInfo() == nullptr) //if it was grouped in the cleanedPsmsArray
{
psmsArray[i] = nullptr;
}
}
}
}
}
std::vector<int> ranking(AllPsms.size()); //high int is good ranking
std::vector<int> indexesOfInterest;
for (int i = 0; i < (int)ranking.size(); i++)
{
if (AllPsms[i].size() > 0)
{
#ifdef ORIG
ranking[i] = AllPsms[i].Where([&] (std::any x) {
return x != nullptr;
})->Count([&] (std::any x) {
return x::FdrInfo::QValue <= 0.01;
}); //set ranking as number of psms above 1% FDR
#endif
ranking[i]=0;
for ( auto x: AllPsms[i] ) {
if ( x != nullptr && x->getFdrInfo()->getQValue() <= 0.01 ) {
ranking[i]++;
}
}
indexesOfInterest.push_back(i);
}
}
//get the index of the category with the highest ranking
int majorCategoryIndex = indexesOfInterest[0];
for (int i = 1; i < (int)indexesOfInterest.size(); i++)
{
int currentCategoryIndex = indexesOfInterest[i];
if (ranking[currentCategoryIndex] > ranking[majorCategoryIndex])
{
majorCategoryIndex = currentCategoryIndex;
}
}
//update other category q-values
//There's a chance of weird categories getting a random decoy before a random target,
//but we don't want to give that target a q value of zero.
//We can't just take the q of the first decoy, because if the target wasn't random (score = 40),
//but there are no other targets before the decoy (score = 5), then we're incorrectly dinging the target
//The current solution is such that if a minor category has a lower q value than it's corresponding
//score in the major category, then its q-value is changed to what it would be in the major category
#ifdef ORIG
std::vector<PeptideSpectralMatch*> majorCategoryPsms = AllPsms[majorCategoryIndex].Where([&] (std::any x) {
return x != nullptr;
}).OrderByDescending([&] (std::any x) {
x::Score;
}).ToList(); //get sorted major category
#endif
std::vector<PeptideSpectralMatch*> majorCategoryPsms;
for ( auto x : AllPsms[majorCategoryIndex] ) {
if ( x != nullptr ) {
majorCategoryPsms.push_back(x);
}
}
std::sort(majorCategoryPsms.begin(), majorCategoryPsms.end(), [&] (PeptideSpectralMatch* l , PeptideSpectralMatch* r) {
return l->getScore() > r->getScore();
});
for (int i = 0; i < (int)indexesOfInterest.size(); i++)
{
int minorCategoryIndex = indexesOfInterest[i];
if (minorCategoryIndex != majorCategoryIndex)
{
#ifdef ORIG
std::vector<PeptideSpectralMatch*> minorCategoryPsms = AllPsms[minorCategoryIndex].Where([&] (std::any x){
return x != nullptr;
}).OrderByDescending([&] (std::any x){
x::Score;
}).ToList(); //get sorted minor category
#endif
std::vector<PeptideSpectralMatch*> minorCategoryPsms;
for ( auto x : AllPsms[minorCategoryIndex] ) {
if ( x != nullptr ) {
minorCategoryPsms.push_back(x);
}
}
std::sort(minorCategoryPsms.begin(), minorCategoryPsms.end(), [&] (PeptideSpectralMatch* l , PeptideSpectralMatch* r) {
return l->getScore() > r->getScore();
});
int minorPsmIndex = 0;
int majorPsmIndex = 0;
while (minorPsmIndex < (int)minorCategoryPsms.size() &&
majorPsmIndex < (int)majorCategoryPsms.size()) //while in the lists
{
PeptideSpectralMatch *majorPsm = majorCategoryPsms[majorPsmIndex];
PeptideSpectralMatch *minorPsm = minorCategoryPsms[minorPsmIndex];
//major needs to be a lower score than the minor
if (majorPsm->getScore() > minorPsm->getScore())
{
majorPsmIndex++;
}
else
{
if (majorPsm->getFdrInfo()->getQValue() > minorPsm->getFdrInfo()->getQValue())
{
minorPsm->getFdrInfo()->setQValue(majorPsm->getFdrInfo()->getQValue());
}
minorPsmIndex++;
}
}
//wrap up if we hit the end of the major category
while (minorPsmIndex < (int)minorCategoryPsms.size())
{
PeptideSpectralMatch *majorPsm = majorCategoryPsms[majorPsmIndex - 1]; //-1 because it's out of index right now
PeptideSpectralMatch *minorPsm = minorCategoryPsms[minorPsmIndex];
if (majorPsm->getFdrInfo()->getQValue() > minorPsm->getFdrInfo()->getQValue())
{
minorPsm->getFdrInfo()->setQValue(majorPsm->getFdrInfo()->getQValue());
}
minorPsmIndex++;
}
}
}
int numTotalSpectraWithPrecursors = AllPsms[indexesOfInterest[0]].size();
std::vector<PeptideSpectralMatch*> bestPsmsList;
for (int i = 0; i < numTotalSpectraWithPrecursors; i++)
{
PeptideSpectralMatch *bestPsm = nullptr;
double lowestQ = std::numeric_limits<double>::max();
int bestIndex = -1;
for (auto index : indexesOfInterest) //foreach category
{
PeptideSpectralMatch *currentPsm = AllPsms[index][i];
if (currentPsm != nullptr)
{
double currentQValue = currentPsm->getFdrInfo()->getQValue();
if (currentQValue < lowestQ || (currentQValue == lowestQ && currentPsm->getScore() > bestPsm->getScore()))
{
if (bestIndex != -1)
{
//remove the old one so we don't use it for fdr later
AllPsms[bestIndex][i] = nullptr;
}
bestPsm = currentPsm;
lowestQ = currentQValue;
bestIndex = index;
}
else //remove the old one so we don't use it for fdr later
{
AllPsms[index][i] = nullptr;
}
}
}
if (bestPsm != nullptr)
{
bestPsmsList.push_back(bestPsm);
}
}
//It's probable that psms from some categories were removed by psms from other categories.
//however, the fdr is still affected by their presence, since it was calculated before their removal.
for (auto psmsArray : AllPsms)
{
if (psmsArray.size() > 0)
{
#ifdef ORIG
std::vector<PeptideSpectralMatch*> cleanedPsmsArray = psmsArray.Where([&] (std::any b) {
return b != nullptr;
}).OrderByDescending([&] (std::any b) {
b::Score;
}).ThenBy([&] (std::any b) {
b::PeptideMonisotopicMass.HasValue ?
std::abs(b::ScanPrecursorMass - b::PeptideMonisotopicMass->Value) :
std::numeric_limits<double>::max();
}).ToList();
#endif
std::vector<PeptideSpectralMatch*> cleanedPsmsArray;
for ( auto x : psmsArray ) {
if ( x != nullptr ) {
cleanedPsmsArray.push_back(x);
}
}
std::sort(cleanedPsmsArray.begin(), cleanedPsmsArray.end(), [&] (PeptideSpectralMatch* l , PeptideSpectralMatch* r) {
if ( l->getScore() > r->getScore() ) return true;
if ( l->getScore() < r->getScore() ) return false;
double lval = std::numeric_limits<double>::max();
double rval = std::numeric_limits<double>::max();
if ( l->getPeptideMonisotopicMass().has_value() ) {
lval = std::abs(l->getScanPrecursorMass() - l->getPeptideMonisotopicMass().value());
}
if ( r->getPeptideMonisotopicMass().has_value() ) {
rval = std::abs(r->getScanPrecursorMass() - r->getPeptideMonisotopicMass().value());
}
if ( lval < rval ) return true;
return false;
});
std::vector<std::string> vs1 = {taskId};
FdrAnalysisEngine tempVar2(cleanedPsmsArray, numNotches, commonParameters, vs1);
(&tempVar2)->Run();
}
}
#ifdef ORIG
return bestPsmsList.OrderBy([&] (std::any b) {
b::FdrInfo::QValue;
}).ThenByDescending([&] (std::any b) {
b::Score;
}).ToList();
#endif
std::sort(bestPsmsList.begin(), bestPsmsList.end(), [&] (PeptideSpectralMatch* l , PeptideSpectralMatch* r) {
if ( l->getFdrInfo()->getQValue() < r->getFdrInfo()->getQValue() ) return true;
if ( l->getFdrInfo()->getQValue() > r->getFdrInfo()->getQValue() ) return true;
if ( l->getScore() > r->getScore() ) return true;
return false;
});
return bestPsmsList;
}
}
}
| 56.268833 | 243 | 0.450858 | [
"vector"
] |
18a91a61bac089f2c43e126cef47a058bc603e32 | 7,868 | cpp | C++ | plugins/community/repos/Autodafe/src/FormantFilter.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/Autodafe/src/FormantFilter.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/Autodafe/src/FormantFilter.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z | //**************************************************************************************
//Formant Filter Module for VCV Rack by Autodafe http://www.autodafe.net
//
//And part of code Public source code by alex@smartelectronix.com
//on musicdsp.org: http://www.musicdsp.org/showArchiveComment.php?ArchiveID=110
//**************************************************************************************
#include "Autodafe.hpp"
namespace rack_plugin_Autodafe {
double CosineInterpolate(
double y1,double y2,
double mu)
{
double mu2;
mu2 = (1-cos(mu*M_PI))/2;
return(y1*(1-mu2)+y2*mu2);
}
/*
Public source code by alex@smartelectronix.com
Simple example of implementation of formant filter
Vowelnum can be 0,1,2,3,4 <=> A,E,I,O,U
Good for spectral rich input like saw or square
*/
//-------------------------------------------------------------VOWEL COEFFICIENTS
const double coeff[9][11] = {
{ 3.11044e-06,
8.943665402, -36.83889529, 92.01697887, -154.337906, 181.6233289,
-151.8651235, 89.09614114, -35.10298511, 8.388101016, -0.923313471 ///A
},
{
CosineInterpolate(3.11044e-06, 4.36215e-06,0.5),
CosineInterpolate(8.943665402, 8.90438318,0.5),
CosineInterpolate(-36.83889529, -36.55179099,0.5),
CosineInterpolate(92.01697887, 91.05750846,0.5),
CosineInterpolate(-154.337906, -152.422234,0.5),
CosineInterpolate(181.6233289, 179.1170248,0.5),
CosineInterpolate(-151.8651235, -149.6496211,0.5),
CosineInterpolate(89.09614114, 87.78352223,0.5),
CosineInterpolate(-35.10298511, -34.60687431,0.5),
CosineInterpolate(8.388101016, 8.282228154,0.5),
CosineInterpolate(-0.923313471, -0.914150747,0.5)
},
{ 4.36215e-06,
8.90438318, -36.55179099, 91.05750846, -152.422234, 179.1170248, ///E
-149.6496211, 87.78352223, -34.60687431, 8.282228154, -0.914150747
},
{
CosineInterpolate(4.36215e-06, 3.33819e-06,0.5),
CosineInterpolate(8.90438318, 8.893102966,0.5),
CosineInterpolate(-36.55179099, -36.49532826,0.5),
CosineInterpolate(91.05750846, 90.96543286,0.5),
CosineInterpolate(-152.422234, -152.4545478,0.5),
CosineInterpolate(179.1170248, 179.4835618,0.5),
CosineInterpolate(-149.6496211, -150.315433,0.5),
CosineInterpolate(87.78352223, 88.43409371,0.5),
CosineInterpolate(-34.60687431, -34.98612086,0.5),
CosineInterpolate(8.282228154, 8.407803364,0.5),
CosineInterpolate(-0.914150747, -0.932568035,0.5)
},
{ 3.33819e-06,
8.893102966, -36.49532826, 90.96543286, -152.4545478, 179.4835618,
-150.315433, 88.43409371, -34.98612086, 8.407803364, -0.932568035 ///I
},
{
CosineInterpolate(3.33819e-06 , 1.13572e-06,0.5),
CosineInterpolate(8.893102966 , 8.994734087,0.5),
CosineInterpolate(-36.49532826 , -37.2084849,0.5),
CosineInterpolate(90.96543286 , 93.22900521,0.5),
CosineInterpolate(-152.4545478 , -156.6929844,0.5),
CosineInterpolate(179.4835618 , 184.596544,0.5),
CosineInterpolate(-150.315433 , -154.3755513,0.5),
CosineInterpolate(88.43409371 , 90.49663749,0.5),
CosineInterpolate(-34.98612086 , -35.58964535,0.5),
CosineInterpolate(8.407803364 , 8.478996281,0.5),
CosineInterpolate(-0.932568035 , -0.929252233,0.5),
},
{ 1.13572e-06,
8.994734087, -37.2084849, 93.22900521, -156.6929844, 184.596544, ///O
-154.3755513, 90.49663749, -35.58964535, 8.478996281, -0.929252233
},
{
CosineInterpolate(1.13572e-06 , 4.09431e-07,0.5),
CosineInterpolate(8.994734087 , 8.997322763,0.5),
CosineInterpolate(-37.2084849 , -37.20218544,0.5),
CosineInterpolate(93.22900521 , 93.11385476,0.5),
CosineInterpolate(-156.6929844 , -156.2530937,0.5),
CosineInterpolate(184.596544 , 183.7080141,0.5),
CosineInterpolate(-154.3755513 , -153.2631681,0.5),
CosineInterpolate(90.49663749 , 89.59539726,0.5),
CosineInterpolate(-35.58964535 , -35.12454591,0.5),
CosineInterpolate(8.478996281 , 8.338655623,0.5),
CosineInterpolate(-0.929252233 , -0.910251753,0.5),
},
{ 4.09431e-07,
8.997322763, -37.20218544, 93.11385476, -156.2530937, 183.7080141, ///U
-153.2631681, 89.59539726, -35.12454591, 8.338655623, -0.910251753
}
};
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
struct FFilter {
double memory[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
float formant_filter(float in, int vowelnum, float tone)
{
float res = (float)(coeff[vowelnum][0] * in/2 +
coeff[vowelnum][1] * memory[0] +
coeff[vowelnum][2] * memory[1] +
coeff[vowelnum][3] * memory[2] +
coeff[vowelnum][4] * memory[3] +
coeff[vowelnum][5] * memory[4] +
coeff[vowelnum][6] * memory[5] +
coeff[vowelnum][7] * memory[6] +
coeff[vowelnum][8] * memory[7] +
coeff[vowelnum][9] * memory[8] +
coeff[vowelnum][10] * memory[9]);
memory[9] = memory[8];
memory[8] = memory[7];
memory[7] = memory[6];
memory[6] = memory[5];
memory[5] = memory[4];
memory[4] = memory[3];
memory[3] = memory[2];
memory[2] = memory[1];
memory[1] = memory[0];
memory[0] = (double)res;
return res;
}
};
struct FormantFilter : Module {
enum ParamIds {
VOWEL_PARAM,
ATTEN_PARAM,
NUM_PARAMS
};
enum InputIds {
INPUT,
CV_VOWEL,
NUM_INPUTS
};
enum OutputIds {
OUTPUT,
NUM_OUTPUTS
};
FormantFilter();
FFilter *ffilter = new FFilter();
void step();
};
FormantFilter::FormantFilter() {
params.resize(NUM_PARAMS);
inputs.resize(NUM_INPUTS);
outputs.resize(NUM_OUTPUTS);
}
void FormantFilter::step() {
float in = inputs[INPUT].value / 5.0f;
int vowel = params[VOWEL_PARAM].value;
float cv = clampf(inputs[CV_VOWEL].value * params[ATTEN_PARAM].value, 0, 8) ;
float ffilterout = ffilter->formant_filter(in,clampf((vowel+cv), 0, 8), 0);
outputs[OUTPUT].value= 5.0f*ffilterout;
}
struct FormantFilterWidget : ModuleWidget{
FormantFilterWidget(FormantFilter *module);
};
FormantFilterWidget::FormantFilterWidget(FormantFilter *module) : ModuleWidget(module) {
box.size = Vec(15*6, 380);
{
SVGPanel *panel = new SVGPanel();
panel->box.size = box.size;
panel->setBackground(SVG::load(assetPlugin(plugin, "res/FormantFilter.svg")));
addChild(panel);
}
addChild(createScrew<ScrewSilver>(Vec(5, 0)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x - 20, 0)));
addChild(createScrew<ScrewSilver>(Vec(5, 365)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x - 20, 365)));
addParam(createParam<AutodafeKnobBlueBig>(Vec(18,61), module, FormantFilter::VOWEL_PARAM, 0.0, 9.0, 0.0));
addParam(createParam<AutodafeKnobBlue>(Vec(27, 190), module, FormantFilter::ATTEN_PARAM, -1.0, 1.0, 0.0));
addInput(createInput<PJ301MPort>(Vec(32, 150), module, FormantFilter::CV_VOWEL));
addInput(createInput<PJ301MPort>(Vec(10, 320), module, FormantFilter::INPUT));
addOutput(createOutput<PJ301MPort>(Vec(48, 320), module, FormantFilter::OUTPUT));
}
} // namespace rack_plugin_Autodafe
using namespace rack_plugin_Autodafe;
RACK_PLUGIN_MODEL_INIT(Autodafe, FormantFilter) {
return Model::create<FormantFilter, FormantFilterWidget>("Autodafe", "Formant Filter", "Formant Filter", FILTER_TAG);
}
| 32.783333 | 120 | 0.596085 | [
"model"
] |
18ae872a9fb998408154c285917dab0dacf7fb3a | 2,851 | cpp | C++ | src/higgs/effective_theory/wilson_coefficients.cpp | dulatf/ihixs | 316d5cdf3e88f2ba69cc43668d66b4f69ff833ce | [
"MIT"
] | 1 | 2019-02-08T13:50:24.000Z | 2019-02-08T13:50:24.000Z | src/higgs/effective_theory/wilson_coefficients.cpp | dulatf/ihixs | 316d5cdf3e88f2ba69cc43668d66b4f69ff833ce | [
"MIT"
] | null | null | null | src/higgs/effective_theory/wilson_coefficients.cpp | dulatf/ihixs | 316d5cdf3e88f2ba69cc43668d66b4f69ff833ce | [
"MIT"
] | null | null | null | #include "wilson_coefficients.h"
#include "constants.h"
// the wilson coeff depends on the scheme used for the top mass
// we have implemented below the wilson coefficients using the decoupling coeff.
// of hep-ph/0512058 (Steinhauser and Schroder)
// Note that one has to express their WC's in terms of the 5 flavor a_s
//
// Also note that there is a factor -1/3 different in the overall normalization
// which is here absorbed in the overall constant (as 1/9)
void WilsonCoefficient::Configure(const double& log_muf_over_mt_sq, const string& scheme)
{
const double L = log_muf_over_mt_sq;
const double nf=consts::nf;
const double z3=consts::z3;
if (scheme=="msbar")
{
_c0 = 1.;
_c1 = 11./4.;
_c2 = 2777./288. - consts::nf * 67./96.+ L * (19./16.+consts::nf/3.);
_c3 = -2892659.0/41472.
+(897943./9216.)*consts::z3
+(1733./288.)*L
+(209./64.)* pow(L,2.)
+consts::nf*(
(55./54.)*L
+40291./20736.
-(110779./13824.)*consts::z3
+(23./32.)*pow(L,2.)
)
+pow(consts::nf,2.)*(
-6865./31104.
+(77./1728.)*L
-(1./18.)* pow(L,2)
);
}
else if (scheme=="on-shell")
{
//from eq.4.39 of hep-ph/0201415 (Steinhauser)
_c0 = 1.;
_c1 = 11./4.;
_c2 = 2777./288. - consts::nf * 67./96.+ L * (19./16.+consts::nf/3.);
_c3 = (-16567986
+ 2088288*L
+ 812592*pow(L,2)
+ 704676*nf
+ 419328*L*nf
+ 178848*pow(L,2)*nf
- 54920*pow(nf,2)
+ 11088*L*pow(nf,2)
- 13824*pow(L,2)*pow(nf,2)
+ 24244461*z3
- 1994022*nf*z3)/248832.;
}
else
{
cout<<"\n[ihixs] Error: in WilsonCoeefficient.Configure the scheme \'"
<<scheme<<"\' was not recognized."
<<"Allowed schemes are msbar and on-shell."
<<"This info comes from Particle within Model and there seems to be some incompatibility."
<<endl<<"The error is fatal"<<endl;
exit(0);
}
_c = AsSeries(1,_c0,_c1,_c2,_c3);
string verbosity_level="normal";
if (verbosity_level=="debugging"){
cout<<"[WilsonCoefficient] Configuring Wilson Coefficients: scheme = "<<scheme<<endl;
cout<<"[WilsonCoefficient] C = "<< _c<<endl;
AsSeries c_sq = _c*_c;
c_sq.Truncate(5);
cout<<"[WilsonCoefficient] C^2 = "<< c_sq <<endl;
}
}
| 36.088608 | 102 | 0.478779 | [
"model"
] |
18af3c153cf6e9b313710341203ae7db0523ad64 | 4,493 | cpp | C++ | src/assembler/MultiModel.cpp | danielepanozzo/polyfem | 34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba | [
"MIT"
] | 228 | 2018-11-23T19:32:42.000Z | 2022-03-25T10:30:51.000Z | src/assembler/MultiModel.cpp | danielepanozzo/polyfem | 34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba | [
"MIT"
] | 14 | 2019-03-11T22:44:14.000Z | 2022-03-16T14:50:35.000Z | src/assembler/MultiModel.cpp | danielepanozzo/polyfem | 34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba | [
"MIT"
] | 45 | 2018-12-31T02:04:57.000Z | 2022-03-08T02:42:01.000Z | // #define EIGEN_STACK_ALLOCATION_LIMIT 0
#include <polyfem/MultiModel.hpp>
#include <polyfem/Basis.hpp>
#include <polyfem/auto_elasticity_rhs.hpp>
#include <igl/Timer.h>
namespace polyfem
{
void MultiModel::set_size(const int size)
{
size_ = size;
// saint_venant_.set_size(size);
neo_hookean_.set_size(size);
linear_elasticity_.size() = size;
}
void MultiModel::init_multimaterial(const bool is_volume, const Eigen::MatrixXd &Es, const Eigen::MatrixXd &nus)
{
// saint_venant_.init_multimaterial(Es, nus);
neo_hookean_.init_multimaterial(is_volume, Es, nus);
linear_elasticity_.init_multimaterial(is_volume, Es, nus);
}
void MultiModel::set_parameters(const json ¶ms)
{
set_size(params["size"]);
// saint_venant_.set_parameters(params);
neo_hookean_.set_parameters(params);
linear_elasticity_.set_parameters(params);
}
Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1>
MultiModel::compute_rhs(const AutodiffHessianPt &pt) const
{
assert(pt.size() == size());
Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> res;
assert(false);
return res;
}
Eigen::VectorXd
MultiModel::assemble_grad(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const
{
const int el_id = vals.element_id;
const std::string model = multi_material_models_[el_id];
// if (model == "SaintVenant")
// return saint_venant_.assemble_grad(vals, displacement, da);
// else
if (model == "NeoHookean")
return neo_hookean_.assemble_grad(vals, displacement, da);
else if (model == "LinearElasticity")
return linear_elasticity_.assemble_grad(vals, displacement, da);
else
{
assert(false);
return Eigen::VectorXd(0, 0);
}
}
Eigen::MatrixXd
MultiModel::assemble_hessian(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const
{
const int el_id = vals.element_id;
const std::string model = multi_material_models_[el_id];
// if (model == "SaintVenant")
// return saint_venant_.assemble_hessian(vals, displacement, da);
// else
if (model == "NeoHookean")
return neo_hookean_.assemble_hessian(vals, displacement, da);
else if (model == "LinearElasticity")
return linear_elasticity_.assemble_hessian(vals, displacement, da);
else
{
assert(false);
return Eigen::MatrixXd(0, 0);
}
}
double MultiModel::compute_energy(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const
{
const int el_id = vals.element_id;
const std::string model = multi_material_models_[el_id];
// if (model == "SaintVenant")
// return saint_venant_.compute_energy(vals, displacement, da);
// else
if (model == "NeoHookean")
return neo_hookean_.compute_energy(vals, displacement, da);
else if (model == "LinearElasticity")
return linear_elasticity_.compute_energy(vals, displacement, da);
else
{
assert(false);
return 0;
}
}
void MultiModel::compute_stress_tensor(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &stresses) const
{
const std::string model = multi_material_models_[el_id];
// if (model == "SaintVenant")
// saint_venant_.compute_stress_tensor(el_id, bs, gbs, local_pts, displacement, stresses);
// else
if (model == "NeoHookean")
neo_hookean_.compute_stress_tensor(el_id, bs, gbs, local_pts, displacement, stresses);
else if (model == "LinearElasticity")
linear_elasticity_.compute_stress_tensor(el_id, bs, gbs, local_pts, displacement, stresses);
else
{
assert(false);
stresses = Eigen::MatrixXd(0, 0);
}
}
void MultiModel::compute_von_mises_stresses(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &stresses) const
{
const std::string model = multi_material_models_[el_id];
// if (model == "SaintVenant")
// saint_venant_.compute_von_mises_stresses(el_id, bs, gbs, local_pts, displacement, stresses);
// else
if (model == "NeoHookean")
neo_hookean_.compute_von_mises_stresses(el_id, bs, gbs, local_pts, displacement, stresses);
else if (model == "LinearElasticity")
linear_elasticity_.compute_von_mises_stresses(el_id, bs, gbs, local_pts, displacement, stresses);
else
{
assert(false);
stresses = Eigen::MatrixXd(0, 0);
}
}
} // namespace polyfem
| 31.640845 | 214 | 0.73136 | [
"model"
] |
18b40087aa30381a6bbf98686ed904363bc9012f | 26,541 | cpp | C++ | IP/src/iProlog/Engine.cpp | Group5SE/PrologVM | 7abbd8e419f18d2bd33fbac7c95cc9fefafb972c | [
"Apache-2.0"
] | 2 | 2019-08-26T11:52:50.000Z | 2021-11-18T17:53:57.000Z | IP/src/iProlog/Engine.cpp | Group5SE/PrologVM | 7abbd8e419f18d2bd33fbac7c95cc9fefafb972c | [
"Apache-2.0"
] | null | null | null | IP/src/iProlog/Engine.cpp | Group5SE/PrologVM | 7abbd8e419f18d2bd33fbac7c95cc9fefafb972c | [
"Apache-2.0"
] | 1 | 2017-09-14T20:47:29.000Z | 2017-09-14T20:47:29.000Z | /*
==============================================================================================
Author: Karthik Venkataramana Pemmaraju.
Compilation:g++ Engine.cpp IntStack.cpp IntList.cpp IMap.cpp IntMap.cpp ObStack.cpp Spine.cpp Clause.cpp -std=c++11 -c
Written on 11/25/2017
===============================================================================================
*/
#include "IntStack.h"
#include "ObStack.h"
#include "IntMap.h"
#include "IMap.h"
#include "Spine.h"
#include "Clause.h"
#include "IntList.h"
#include "Engine.h"
#include "Toks.h"
#include <string>
#include <map>
#include <iterator>
#include <vector>
#include <stdexcept>
#include <stdlib.h> /* realloc, free, exit, NULL */
using namespace std;
using namespace boost;
namespace iProlog{
int Engine::tag(const int t, const int w){
return -((w << 3) + t);
}
// removes tag after flipping sign
int Engine::detag(const int w){
return -w >> 3;
}
//extracts the tag of a cell
int Engine::tagOf(int const w){
return -w & 7;
}
int Engine::addSym(std::string sym){
std::map<std::string, int>::iterator itr;
itr = syms.find(sym);
int i = 0;
if(itr == syms.end()){
i = syms.size();
syms.insert({sym, i});
slist.push_back(sym);
}
else
{
i = itr -> second;
}
return i;
}
/**
* returns the symbol associated to an integer index
* in the symbol table
*/
std::string Engine::getSym(const int w){
if (w < 0 || w >= slist.size())
return "BAD SYM REF=" + std::to_string(w);
return slist[w];
}
void Engine::makeHeap(){
makeHeap(MINSIZE);
}
void Engine::makeHeap(const int size){
heap = (int*) malloc(size * sizeof(int));
heapSize = size;
clear();
}
int Engine::getTop(){
return this -> top;
}
int Engine::setTop(const int top){
return this -> top = top;
}
void Engine::clear(){
this -> top = -1;
}
void Engine::push(const int i){
heap[++top] = i;
}
int Engine::size(){
return top + 1;
}
/**
* dynamic array operation: doubles when full
*/
void Engine::expand(){
heap = (int *)realloc(heap, heapSize << 1);
heapSize = heapSize << 1;
}
void Engine::ensureSize(const int more){
if (1 + top + more >= heapSize)
expand();
}
std::vector<std::vector<std::string>> Engine::maybeExpand(std::vector<std::string> &Ws){
const int l = Ws.size();
std::vector<std::vector<std::string>> Rss; // ArrayList<String[]>
const std::string W = Ws[0];
if (W.length() < 2 || "l:" != W.substr(0, 2))
return Rss;
std::string V = W.substr(2);
for (int i = 1; i < l; i++){
std::vector<std::string> Rs(4);
std::string Vi = 1 == i ? V : V + "__" + std::to_string(i - 1);
std::string Vii = V + "__" + std::to_string(i);
Rs[0] = "h:" + Vi;
Rs[1] = "c:list";
Rs[2] = Ws[i];
Rs[3] = i == l - 1 ? "c:nil" : "v:" + Vii;
Rss.push_back(Rs);
}
return Rss;
}
/**
* expands, if needed, "lists" statements in sequence of statements
*/
std::vector<std::vector<std::string>> Engine::mapExpand(std::vector<std::vector<std::string>> &Wss){
std::vector<std::vector<std::string>> Rss;
std::vector<std::vector<std::string>>::iterator Ws;
for (Ws= Wss.begin(); Ws != Wss.end(); Ws++){
std::vector<std::vector<std::string>> Hss = maybeExpand(*Ws);
std::vector<std::string> ws;
if (Hss.size() == 0){
for (int i =0; i < Ws->size(); i++){
ws.push_back((*Ws)[i]);
}
Rss.push_back(ws);
}
else{
for (std::vector<std::vector<std::string>>::const_iterator X = Hss.begin(); X < Hss.end(); X++){
Rss.push_back(*X);
}
}
}
return Rss;
}
/**
* loads a program from a .nl file of
* "natural language" equivalents of Prolog/HiLog statements
*/
std::vector<Clause*> Engine::dload(std::string s){
const bool fromFile = true;
Toks t;
std::vector<std::vector<std::vector<std::string>>> Wsss = t.toSentences(s, fromFile); // (TO - DO on linux).
std::vector<Clause*> Cs;
for (auto Wss = Wsss.begin(); Wss != Wsss.end(); ++Wss){
// clause starts here
std::map<std::string, IntStack*> refs;
IntStack *cs = new IntStack();
IntStack *gs = new IntStack();
std::vector<std::vector<std::string>> Rss = mapExpand(*Wss);
int k = 0;
for(std::vector<std::vector<std::string>>::iterator ws= Rss.begin(); ws != Rss.end(); ++ws){
// head or body element starts here
const int lm = ws-> size();
gs->push(tag(R, k++));
cs->push(tag(A, lm));
for (std::vector<std::string>::iterator w = ws -> begin(); w != ws -> end(); ++w){
// head or body subterm starts here
if (1 == w ->size()){
*w = "c:" + *w;
}
std::string L = w ->substr(2);
std::map<std::string, IntStack*>::iterator itr1 = refs.find(L);
std::map<std::string, IntStack*>::iterator itr = refs.find(L);
IntStack* Is;
char c = w -> at(0);
switch (c){
case 'c':
cs -> push(encode(C, L));
k++;
break;
case 'n':
cs -> push(encode(N, L));
k++;
break;
case 'v':
// printUnorderedMap(refs);
// KEY EXISTS;
if( itr == refs.end())
{
Is = new IntStack(); // NECESSARY?
refs.insert({L, Is}); // puts into hash map.
}
else{
Is = itr -> second;
}
Is->push(k);
cs->push(tag(BAD, k)); // just in case we miss this
k++;
break;
case 'h':
// IntStack *Is;
if(itr1 == refs.end())
{
Is = new IntStack(); // NECESSARY?
refs.insert({L, Is}); // puts into hash map.
}
else{
Is = itr1 -> second;
// cout << " IS ) VALUES " << Is -> getTop() << " K " << k << endl;
}
Is->push(k - 1);
cs->set((k - 1), tag(A, (lm - 1)));
gs->pop();
break;
default:
std::cout << " FORGOTTEN= " << *w ;
} // end subterm
} // end element
} // end clause
// // linker
for(auto &itr: refs){
IntStack* Is = itr.second;
int leader = -1;
for (auto &j: Is -> toArray()){
if (A == tagOf(cs->get(j))){
leader = j;
break;
}
}
if (leader == -1){
// for vars, first V others U
leader = Is -> get(0);
for (auto &&i: Is -> toArray()){
if (i == leader)
{
cs->set(i, tag(V, i));
}
else{
cs->set(i, tag(U, leader));
}
}
}
else{
for (auto &&i : Is -> toArray()){
if (i == leader)
continue;
cs->set(i, tag(R, leader));
}
}
}
const int neck = 1 == gs->size() ? cs->size() : detag(gs->get(1));
std::vector<int> tgs = gs->toArray();
Clause* C = putClause(cs->toArray(), tgs, neck);
Cs.push_back(C);
} // end clause set
const int ccount = Cs.size();
std::vector<Clause*> cls(ccount);
for (int i = 0; i < ccount; i++){
cls[i] = Cs[i];
}
return cls;
}
void Engine::printMap(std::map<std::string, int> map){
cout << "{";
for(auto t = map.begin(); t != map.end(); ++t){
cout << "[" << t -> first << ", " << t -> second<< "], ";
}
cout << "}";
}
/*
* encodes string constants into symbols while leaving
* other data types untouched
*/
int Engine::encode(const int t,std::string s){
int w;
try{
w = std::stoi(s);
}
catch (const std::exception &e)
{
if (C == t){
w = addSym(s);
}
else{
return tag(BAD, 666);
}
//pp("bad in encode=" + t + ":" + s);
}
return tag(t, w);
}
// places a clause built by the Toks reader on the heap
Clause* Engine::putClause(std::vector<int> cs, std::vector<int> gs, int const neck){
const int base = size();
const int b = tag(V, base);
const int len = cs.size();
pushCells(b, 0, len, cs);
for (int i = 0; i < gs.size(); i++){
gs[i] = relocate(b, gs[i]);
}
std::vector<int> xs = getIndexables(gs[0]);
return new Clause(len, gs, base, neck, xs);
}
int Engine::relocate(int const b, int const cell){
return (tagOf(cell) < 3) ? (cell + b) : cell;
}
std::vector<int> Engine::toNums(std::vector<Clause*> clauses){
const int l = clauses.size();
std::vector<int> cls(l);
for (int i = 0; i < l; i++)
{
cls[i] = i;
}
return cls;
}
/**
* true if cell x is a variable
* assumes that variables are tagged with 0 or 1
*/
bool Engine::isVAR(int x){
//final int t = tagOf(x);
//return V == t || U == t;
return tagOf(x) < 2;
}
int Engine::getRef(int x){
return heap[detag(x)];
}
/*
* sets a heap cell to point to another one
*/
void Engine::setRef(int w, int r){
heap[detag(w)] = r;
}
/**
* removes binding for variable cells
* above savedTop
*/
void Engine::unwindTrail(int savedTop){
while (savedTop < trail->getTop()){
int href = trail->pop();
// assert href is var
setRef(href, href);
}
}
/**
* scans reference chains starting from a variable
* until it points to an unbound root variable or some
* non-variable cell
*/
int Engine::deref(int x){
while(isVAR(x)){
const int r = getRef(x);
if (r == x){
break;
}
x = r;
}
return x;
}
/**
* builds an array of embedded arrays from a heap cell
* representing a term for interaction with an external function
* including a displayer
*/
/**
* builds an array of embedded arrays from a heap cell
* representing a term for interaction with an external function
* including a displayer
*/
vector<string> Engine::exportTerm(int x){
x = deref(x);
const int t = tagOf(x);
const int w = detag(x);
string res;
if(t == Engine::C){
res = "" + getSym(w);
}
else if(t == Engine::N)
res = "" + std::to_string(w) ; // res = new Integer(w) ( Thought this is the way of doing this.)
else if(t == Engine::V)
res = "V" + std::to_string(w) ;
else if(t == Engine::R){
int a = heap[w];
if (A != tagOf(a)){
return {"*** should be A, found=" + showCell(a)};
}
int n = detag(a);
std::vector<string> arr(n);
int k = w + 1;
for (int i = 0; i < n; i++){
const int j = k + i;
if(i < n - 1)
arr[i] = convertToString(exportTerm(heap[j]));
else
arr[i] = "("+ convertToString(exportTerm(heap[j])) + ")" ;
}
return arr;
}
else
res = "*BAD TERM*" + showCell(x);
return {res};
}
string Engine::convertToString(std::vector<string> x){
string res;
for(auto &i: x)
{
res += i ;
}
return res;
}
std::string Engine::showCell(int w){
const int t = tagOf(w);
int val = detag(w);
std::string s = "";
if(t == V)
s = "v:" + std::to_string(val);
else if(t == U)
s = "u:" + std::to_string(val);
else if(t == N)
s = "n:" + std::to_string(val);
else if(t == C)
s = "c:" + std::to_string(val);
else if(t == R)
s = "r:" + std::to_string(val);
else if(t == A)
s = "a:" + std::to_string(val);
else{
s = "*BAD*=" + std::to_string(w);
}
return s;
}
// Not Sure if this is correct, peer review required! (ATTENTION!!!!!!!)
/**
* raw display of a term - to be overridden
*/
void Engine::showTerm(int x){
showTerm(exportTerm(x));
}
/**
* raw display of a externalized term
*/
void Engine::showTerm(vector<string> O){
printVector(O, false);
// cout << O -> toString(); // Print the object value here itself.
}
void Engine::ppTrail(){
for (int i = 0; i <= trail -> getTop(); i++){
const int t = trail -> get(i);
cout << "trail[" << std::to_string(i) << "]=" << showCell(t) << ":";
// showTerm(t);
}
}
/**
* extracts an integer array pointing to
* the skeleton of a clause: a cell
* pointing to its head followed by cells pointing to its body's
* goals
*/
std::vector<int> Engine::getSpine(std::vector<int> cs){
const int a = cs[1];
const int w = detag(a);
std::vector<int> rs(w - 1);
for (int i = 0; i < w - 1; i++){
const int x = cs[3 + i];
const int t = tagOf(x);
if (R != t){
cout << "*** getSpine: unexpected tag=" << std::to_string(t);
rs.erase(rs.begin(),rs.end()); // IMPORTANT - Cannot return null as in java, so sending an empty vector.
return rs;
}
rs[i] = detag(x);
}
return rs;
}
/**
* raw display of a cell as tag : value
*/
std::string Engine::showCells(int const base, int const len){
std::string buf;
for (int k = 0; k < len; k++){
int instr = heap[base + k];
buf += "[" + std::to_string(base + k) + "]";
buf += showCell(instr);
buf += " ";
}
return buf;
}
std::string Engine::showCells(std::vector<int> cs){
std::string buf;
for (int k = 0; k < cs.size(); k++)
{
buf += "[" + std::to_string(k) + "]";
buf += showCell(cs[k]);
buf += " ";
}
return buf;
}
/**
* unification algorithm for cells X1 and X2 on ustack that also takes care
* to trail bindigs below a given heap address "base"
*/
bool Engine::unify(int const base){
while (!ustack -> isEmpty()){
const int x1 = deref(ustack -> pop());
const int x2 = deref(ustack -> pop());
if (x1 != x2){
const int t1 = tagOf(x1);
const int t2 = tagOf(x2);
const int w1 = detag(x1);
const int w2 = detag(x2);
if (isVAR(x1)){ // unb. var. v1
if (isVAR(x2) && w2 > w1){ // unb. var. v2
heap[w2] = x1;
if (w2 <= base)
trail->push(x2);
}
else{ // x2 nonvar or older
heap[w1] = x2;
if (w1 <= base)
trail->push(x1);
}
}
else if (isVAR(x2)){ // x1 is NONVAR
heap[w2] = x1;
if (w2 <= base)
trail->push(x2);
}
else if (R == t1 && R == t2){ // both should be R
if (!unify_args(w1, w2))
return false;
}
else{
return false;
}
}
}
return true;
}
bool Engine::unify_args(int const w1, int const w2){
const int v1 = heap[w1];
const int v2 = heap[w2];
// both should be A
const int n1 = detag(v1);
const int n2 = detag(v2);
if (n1 != n2){
return false;
}
const int b1 = 1 + w1;
const int b2 = 1 + w2;
for (int i = n1 - 1; i >= 0; i--){
const int i1 = b1 + i;
const int i2 = b2 + i;
const int u1 = heap[i1];
const int u2 = heap[i2];
if (u1 == u2)
continue;
ustack->push(u2);
ustack->push(u1);
}
return true;
}
/*
* pushes slice[from,to] of array cs of cells to heap
*/
void Engine::pushCells(int const b, int const from, int const to, int const base){
ensureSize(to - from);
for (int i = from; i < to; i++){
push(relocate(b, heap[base + i]));
}
}
/*
* pushes slice[from,to] of array cs of cells to heap
*/
void Engine::pushCells(int const b, int const from, int const to, vector<int> cs){
ensureSize(to - from);
for (int i = from; i < to; i++){
push(relocate(b, cs[i]));
}
}
/*
* copies and relocates head of clause at offset from heap to heap
*/
int Engine::pushHead(int const b, Clause * C){
pushCells(b, 0, C->neck, C->base);
const int head = C->hgs[0];
return relocate(b, head);
}
/*
* copies and relocates body of clause at offset from heap to heap
* while also placing head as the first element of array gs that
* when returned contains references to the toplevel spine of the clause
*/
vector<int> Engine::pushBody(int const b, int const head, Clause* C){
pushCells(b, C->neck, C->len, C->base);
const int l = C->hgs.size();
vector<int> gs(l);
gs[0] = head;
for (int k = 1; k < l; k++){
const int cell = C->hgs[k];
gs[k] = relocate(b, cell);
}
return gs;
}
/*
* makes, if needed, registers associated to top goal of a Spine
* these registers will be reused when matching with candidate clauses
* note that xs contains dereferenced cells - this is done once for
* each goal's toplevel subterms
*/
void Engine::makeIndexArgs(Spine* G, int const goal){
if (0 !=G -> xs.size()){
return;
}
const int p = 1 + detag(goal);
const int n = std::min(MAXIND, detag(getRef(goal)));
G -> xs.resize(MAXIND);
for (int i = 0; i < n; i++)
{
const int cell = deref(heap[p + i]);
G -> xs[i] = cell2index(cell);
}
if (imaps.size() == 0)
return;
IMap<int> iM;
G -> cs = iM.get(imaps, vmaps, G -> xs);
}
int Engine::cell2index(int const cell){
int x = 0;
const int t = tagOf(cell);
if(t == R)
x = getRef(cell);
else if(t == N)
x = cell;
// 0 otherwise - assert: tagging with R,C,N <>0
return x;
}
std::vector<int> Engine::getIndexables(int const ref){
const int p = 1 + detag(ref);
const int n = detag(getRef(ref));
std::vector<int> xs(MAXIND);
for (int i = 0; i < MAXIND && i < n; i++){
const int cell = deref(heap[p + i]);
xs[i] = cell2index(cell);
}
return xs;
}
/*
* tests if the head of a clause, not yet copied to the heap
* for execution could possibly match the current goal, an
* abstraction of which has been place in xs
*/
bool Engine::match(std::vector<int> xs, Clause* C0){
for (int i = 0; i < MAXIND; i++){
const int x = xs[i];
const int y = C0 -> xs[i];
if (0 == x || 0 == y)
continue;
if (x != y)
{
return false;
}
}
return true;
}
/*
* transforms a spine containing references to choice point and
* immutable list of goals into a new spine, by reducing the
* first goal in the list with a clause that successfully
* unifies with it - in which case places the goals of the
* clause at the top of the new list of goals, in reverse order
*/
Spine* Engine::unfold(Spine* G){
const int ttop = trail->getTop();
const int htop = getTop();
const int base = htop + 1;
const int goal = IntList::getHead(G->gs);
//cout << "TTOP G" << G -> ttop << " BASE " << G -> base << " GOAL " << goal << " G GS " << G-> gs->toString();
makeIndexArgs(G, goal);
const int last = G -> cs.size();
for (int k = G->k; k < last; k++){
Clause* C0 = clauses[G->cs[k]];
if (!match(G->xs, C0))
{
continue;
}
const int base0 = base - (C0->base);
const int b = tag(V, base0);
const int head = pushHead(b, C0);
ustack->clear(); // set up unification stack
ustack->push(head);
ustack->push(goal);
if (!unify(base))
{
unwindTrail(ttop);
setTop(htop);
continue;
}
std::vector<int> gs = pushBody(b, head, C0);
IntList* newgs = nullptr;
newgs = IntList::getTail(IntList::app(gs, IntList::getTail(G->gs)));
G->k = k + 1;
if(!(newgs == nullptr)){
return new Spine(gs, base, IntList::getTail(G->gs), ttop, 0, cls);
}
else{
return answer(ttop);
}
} // end for
return nullptr;
}
/**
* extracts a query - by convention of the form
* goal(Vars):-body to be executed by the engine
*/
Clause* Engine::getQuery(){
if(clauses.size() >= 1)
return clauses[clauses.size() - 1];
return NULL;
}
/**
* returns the initial spine built from the
* query from which execution starts
*/
Spine* Engine::init(){
const int base = size();
Clause* G = getQuery();
if(G != NULL){
Spine* Q = new Spine(G->hgs, base, NULL , trail->getTop(), 0, cls);
spines -> push(Q);
return Q;
}
return nullptr;
}
/**
* returns an answer as a Spine while recording in it
* the top of the trail to allow the caller to retrieve
* more answers by forcing backtracking
*/
Spine* Engine::answer(int const ttop){
if(spines->elems.size() > 0)
return new Spine(spines ->elems.at(0)-> hd, ttop); // ATTTENNNNNNNNNTIOOOOOOOOOOOOOONNNNNNNN!!!!!!!!
return nullptr;
}
/**
* detects availability of alternative clauses for the
* top goal of this spine
*/
bool Engine::hasClauses(Spine* S){
if(S != NULL)
return ((S->k) < (S->cs.size()) );
return false;
}
/**
* true when there are no more goals left to solve
*/
bool Engine::hasGoals(Spine* S){
return !(S -> gs == NULL);
}
/**
* removes this spines for the spine stack and
* resets trail and heap to where they where at its
* creating time - while undoing variable binding
* up to that point
*/
void Engine::popSpine(){
Spine* G = spines->pop();
unwindTrail(G->ttop);
setTop(G->base - 1);
}
/**
* main interpreter loop: starts from a spine and works
* though a stream of answers, returned to the caller one
* at a time, until the spines stack is empty - when it
* returns null
*/
Spine* Engine::yield(){
while (!spines->empty()){
Spine* G = spines->top();
if (!hasClauses(G)){
popSpine(); // no clauses left
continue;
}
Spine* C = unfold(G);
if (C == nullptr){
popSpine(); // no matches
continue;
}
if (hasGoals(C)){
spines->push(C);
continue;
}
return C; // answer
}
return nullptr;
}
/**
* retrieves an answers and ensure the engine can be resumed
* by unwinding the trail of the query Spine
* returns an external "human readable" representation of the answer
*/
vector<string> Engine::ask(){
vector<string> R;
query = yield();
if (nullptr == query)
{
return R;
}
const int res = answer(query->ttop)->hd;
R = exportTerm(res);
unwindTrail(query->ttop);
return R;
}
/**
* initiator and consumer of the stream of answers
* generated by this engine
*/
void Engine::run(){
long ctr = 0;
for (;; ctr++){
vector<string> A = ask();
if (A.size() == 0)
{
break;
}
cout << "[" + std::to_string(ctr) + "] " << "*** ANSWER = ";
showTerm(A);
cout << endl;
}
cout << "\nTOTAL ANSWERS= " << std::to_string(ctr) << endl;
}
// // indexing extensions - ony active if START_INDEX clauses or more
vector<IntMap*> Engine::vcreate(int const l){
vector<IntMap*> vss(l);
for (int i = 0; i < l; i++)
{
vss[i] = new IntMap();
}
return vss;
}
void Engine::put(vector<IMap<int>*> imaps, vector<IntMap*> vss, vector<int> keys, int const val){
for (int i = 0; i < imaps.size(); i++){
IMap<int> iM; // ATTTTTTTTTTTTTTENNNNNNNNNNNNTIONNNNNNNNNNNN!!!!!!!!!!!!!
const int key = keys[i];
if (key != 0)
{
iM.put(imaps, i, key, val);
}
else
{
vss[i]->add(val);
}
}
}
vector<IMap<int>*>* Engine::index(vector<Clause*> clauses, vector<IntMap*> vmaps){
if (clauses.size() < START_INDEX)
{
return nullptr;
}
IMap<int> im;
vector<IMap<int>*> imaps = im.create(vmaps.size());
for (int i = 0; i < clauses.size(); ++i)
{
Clause* c = clauses[i];
put(imaps, vmaps, c->xs, i + 1); // $$$ UGLY INC
}
vector<IMap<int>*>* imPtr = &imaps;
// TO - DO
// Main::pp("INDEX");
// Main::pp(IMap::show(imaps));
// Main::pp(Arrays->toString(vmaps));
// Main::pp(L"");
return imPtr;
}
// Builds a new engine from a natural-language style assembler.nl file
Engine::~Engine(){
// delete syms;
free(heap);
delete trail;
delete ustack;
delete spines;
delete query;
}
Engine::Engine(const std::string fname){
makeHeap();
trail = new IntStack();
ustack = new IntStack();
clauses = dload(fname);
cls = toNums(clauses);
query = init();
vmaps = vcreate(MAXIND);
if(index(clauses, vmaps) != NULL)
imaps = *(index(clauses, vmaps));
}
Engine& Engine::operator=(const Engine& other){ // Assignment overload.
if( this == &other) return *this;
else{
slist = other.slist;
*heap = *(other.heap);
*trail = *(other.trail);
*ustack = *(other.ustack);
*spines = *(other.spines);
*query = *(other.query);
imaps = other.imaps;
vmaps = other.vmaps;
clauses = other.clauses;
cls = other.cls;
syms = other.syms;
}
}
Engine::Engine(Engine &other){ // copy constructor.
slist = other.slist;
*heap = *(other.heap);
*trail = *(other.trail);
*ustack = *(other.ustack);
*spines = *(other.spines);
*query = *(other.query);
imaps = other.imaps;
vmaps = other.vmaps;
clauses = other.clauses;
cls = other.cls;
syms = other.syms;
}
template<typename K>
void Engine::printVector(vector<K> x, bool flag){
if(flag == true)
cout << "(";
for(auto t = x.begin(); t != x.end(); ++t){
cout << *t;
}
cout << ")";
}
template<typename K>
void Engine::printVector(vector<K> x, int limit){
cout << " [";
int tlimit =0;
for(auto t = x.begin(); t != x.end() && tlimit <= limit; ++t, ++tlimit){
cout << *t << " ";
}
cout << "]";
}
}
// int main()
// {
// string fname = "perms.pl.nl";
// iProlog::Engine obj(fname);
// cout << "Heap length:" << obj.heap.size() << "\n";
// cout << "Clauses Array: ";
// iProlog::Engine::printVector<iProlog::Clause*>(obj.clauses, true);
// cout << "Int Clause Array with elements equal to 'Clause' :";
// iProlog::Engine::printVector<int>(obj.cls, true);
// cout << "\n";
// cout << "Symbol map:";
// obj.printMap(obj.syms);
// cout << "\n";
// cout << "Symbol List:";
// iProlog::Engine::printVector<string>(obj.slist, true);
// cout << "\n";
// obj.run();
// return 0;
// }
/*
JAVA OUTPUT:
perms.pl.nl:
Heap length:32768
Clauses Array: [iProlog.Clause@15db9742, iProlog.Clause@6d06d69c, iProlog.Clause@7852e922]
Int Clause Array with elements equal to 'Clause' :[0, 1, 2]
Symbol map:{add=0, s=1, goal=2}
Symbol List:[add, s, goal]
Spine Query:iProlog.Spine@4e25154f
ObStack Spine:[iProlog.Spine@4e25154f]
IMap array of Integer: null
IntMap array:[{}, {}, {}]
[0] *** ANSWER=[goal, [s, [s, [s, [s, 0]]]]]
TOTAL ANSWERS=1
perms.pl.nl:
Heap length:32768
Clauses Array: [iProlog.Clause@15db9742, iProlog.Clause@6d06d69c, iProlog.Clause@7852e922, iProlog.Clause@4e25154f, iProlog.Clause@70dea4e, iProlog.Clause@5c647e05, iProlog.Clause@33909752, iProlog.Clause@55f96302, iProlog.Clause@3d4eac69, iProlog.Clause@42a57993, iProlog.Clause@75b84c92]
Int Clause Array with elements equal to 'Clause' :[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Symbol map:{eq=0, sel=1, list=2, perm=3, nil=4, app=5, nrev=6, input=7, goal=8}
Symbol List:[eq, sel, list, perm, nil, app, nrev, input, goal]
Spine Query:iProlog.Spine@6bc7c054
ObStack Spine:[iProlog.Spine@6bc7c054]
IMap array of Integer: null
IntMap array:[{}, {}, {}]
[0] *** ANSWER=[goal, [list, 11, [list, 10, [list, 9, [list, 8, [list, 7, [list, 6, [list, 5, [list, 4, [list, 3, [list, 2, [list, 1, nil]]]]]]]]]]]]
TOTAL ANSWERS=1
*/
| 24.804673 | 290 | 0.554915 | [
"object",
"vector"
] |
18b6d908e8dda903ebdfe6e3cd4d7b76f9e79415 | 4,541 | hpp | C++ | pkgs/libdynd-0.7.2-0/include/dynd/dispatch_map.hpp | wangyum/anaconda | 6e5a0dbead3327661d73a61e85414cf92aa52be6 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | pkgs/libdynd-0.7.2-0/include/dynd/dispatch_map.hpp | wangyum/anaconda | 6e5a0dbead3327661d73a61e85414cf92aa52be6 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | pkgs/libdynd-0.7.2-0/include/dynd/dispatch_map.hpp | wangyum/anaconda | 6e5a0dbead3327661d73a61e85414cf92aa52be6 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
namespace dynd {
bool supercedes(type_id_t lhs, type_id_t rhs) { return is_base_id_of(rhs, lhs); }
template <size_t N>
bool supercedes(const std::array<type_id_t, N> &lhs, const std::array<type_id_t, N> &rhs)
{
for (size_t i = 0; i < N; ++i) {
if (!is_base_id_of(rhs[i], lhs[i])) {
return false;
}
}
return true;
}
class topological_sort_marker {
char m_mark;
public:
topological_sort_marker() : m_mark(0) {}
void temporarily_mark() { m_mark = 1; }
void mark() { m_mark = 2; }
bool is_temporarily_marked() { return m_mark == 1; }
bool is_marked() { return m_mark == 2; }
};
template <typename ValueType, typename ResIteratorType>
void topological_sort_visit(intptr_t i, const std::vector<ValueType> &values,
const std::vector<std::vector<intptr_t>> &edges,
std::vector<topological_sort_marker> &markers, ResIteratorType &res)
{
if (markers[i].is_temporarily_marked()) {
throw std::runtime_error("not a dag");
}
if (!markers[i].is_marked()) {
markers[i].temporarily_mark();
for (size_t j : edges[i]) {
topological_sort_visit(j, values, edges, markers, res);
}
markers[i].mark();
*res = values[i];
++res;
}
}
template <typename ValueType, typename OutputIterator>
void topological_sort(const std::vector<ValueType> &values, const std::vector<std::vector<intptr_t>> &edges,
OutputIterator res)
{
size_t size = values.size();
std::vector<topological_sort_marker> markers(values.size());
for (size_t i = 0; i < size; ++i) {
topological_sort_visit(i, values, edges, markers, res);
}
std::reverse(res - values.size(), res);
}
namespace detail {
template <typename KeyType, typename MappedType>
class dispatch_map {
public:
typedef KeyType key_type;
typedef MappedType mapped_type;
typedef std::pair<key_type, mapped_type> value_type;
typedef typename std::vector<value_type>::iterator iterator;
typedef typename std::vector<value_type>::const_iterator const_iterator;
private:
std::vector<value_type> m_values;
std::map<key_type, iterator> m_cache;
public:
dispatch_map() = default;
dispatch_map(const std::initializer_list<value_type> &values) { init(values.begin(), values.end()); }
template <typename Iter>
void init(Iter begin, Iter end)
{
std::vector<key_type> signatures;
std::vector<value_type> m;
while (begin != end) {
signatures.push_back(begin->first);
m.push_back(*begin);
++begin;
}
std::vector<std::vector<intptr_t>> edges(signatures.size());
for (size_t i = 0; i < signatures.size(); ++i) {
for (size_t j = 0; j < signatures.size(); ++j) {
if (edge(signatures[i], signatures[j])) {
edges[i].push_back(j);
}
}
}
decltype(m) res(m.size());
topological_sort(m, edges, res.begin());
m_values = res;
}
iterator find(const key_type &key)
{
auto it = m_cache.find(key);
if (it != m_cache.end()) {
return it->second;
}
return m_cache[key] = std::find_if(m_values.begin(), m_values.end(),
[key](const value_type &value) { return supercedes(key, value.first); });
}
iterator begin() { return m_values.begin(); }
const_iterator begin() const { return m_values.begin(); }
const_iterator cbegin() const { return m_values.cbegin(); }
iterator end() { return m_values.end(); }
const_iterator end() const { return m_values.end(); }
const_iterator cend() const { return m_values.cend(); }
mapped_type &operator[](const key_type &key) { return find(key)->second; }
static bool edge(const key_type &u, const key_type &v)
{
if (supercedes(u, v)) {
if (supercedes(v, u)) {
return false;
}
else {
return true;
}
}
return false;
}
};
} // namespace dynd::detail
template <typename MappedType, size_t...>
class dispatch_map;
template <typename MappedType>
class dispatch_map<MappedType, 1> : public detail::dispatch_map<type_id_t, MappedType> {
using detail::dispatch_map<type_id_t, MappedType>::dispatch_map;
};
template <typename MappedType, size_t N>
class dispatch_map<MappedType, N> : public detail::dispatch_map<std::array<type_id_t, N>, MappedType> {
using detail::dispatch_map<std::array<type_id_t, N>, MappedType>::dispatch_map;
};
} // namespace dynd
| 27.689024 | 114 | 0.631579 | [
"vector"
] |
18ba372c731b1938fb63b90997e180c906f737a4 | 239 | hpp | C++ | XGF/Include/Xinput.hpp | kadds/XGF | 610c98a93c0f287546f97efc654b95dc846721ad | [
"MIT"
] | 5 | 2017-11-09T05:02:52.000Z | 2020-06-23T09:50:25.000Z | XGF/Include/Xinput.hpp | kadds/XGF | 610c98a93c0f287546f97efc654b95dc846721ad | [
"MIT"
] | null | null | null | XGF/Include/Xinput.hpp | kadds/XGF | 610c98a93c0f287546f97efc654b95dc846721ad | [
"MIT"
] | null | null | null | #pragma once
#include "Defines.hpp"
#include <Xinput.h>
#include <vector>
namespace XGF::Input
{
class XInput
{
public:
void Initialize();
void Shutdown();
private:
std::pair<bool, XINPUT_STATE> mState[XUSER_MAX_COUNT];
};
}
| 14.058824 | 56 | 0.690377 | [
"vector"
] |
18bac9a02d1e0a6b241734f227565ee1ed81d8f9 | 505 | cpp | C++ | 1301-1400/1365-How Many Numbers Are Smaller Than the Current Number/1365-How Many Numbers Are Smaller Than the Current Number.cpp | jiadaizhao/LeetCode | 4ddea0a532fe7c5d053ffbd6870174ec99fc2d60 | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 1301-1400/1365-How Many Numbers Are Smaller Than the Current Number/1365-How Many Numbers Are Smaller Than the Current Number.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 1301-1400/1365-How Many Numbers Are Smaller Than the Current Number/1365-How Many Numbers Are Smaller Than the Current Number.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
vector<int> presum(101);
for (int num : nums) {
++presum[num];
}
for (int i = 1; i <= 100; ++i) {
presum[i] += presum[i - 1];
}
vector<int> result(nums.size());
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > 0) {
result[i] = presum[nums[i] - 1];
}
}
return result;
}
};
| 25.25 | 62 | 0.423762 | [
"vector"
] |
18bbea050d3816ebfa890a39c7f9b04f272586d8 | 9,453 | cc | C++ | components/viz/service/display/gl_renderer_copier_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | components/viz/service/display/gl_renderer_copier_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/viz/service/display/gl_renderer_copier_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/viz/service/display/gl_renderer_copier.h"
#include <stdint.h>
#include <iterator>
#include <memory>
#include "base/bind.h"
#include "components/viz/common/frame_sinks/copy_output_request.h"
#include "components/viz/test/test_context_provider.h"
#include "components/viz/test/test_gles2_interface.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/vector2d.h"
namespace viz {
namespace {
class CopierTestGLES2Interface : public TestGLES2Interface {
public:
// Sets how GL will respond to queries regarding the implementation's internal
// read-back format.
void SetOptimalReadbackFormat(GLenum format, GLenum type) {
format_ = format;
type_ = type;
}
// GLES2Interface override.
void GetIntegerv(GLenum pname, GLint* params) override {
switch (pname) {
case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
ASSERT_EQ(static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE),
CheckFramebufferStatus(GL_FRAMEBUFFER));
params[0] = format_;
break;
case GL_IMPLEMENTATION_COLOR_READ_TYPE:
ASSERT_EQ(static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE),
CheckFramebufferStatus(GL_FRAMEBUFFER));
params[0] = type_;
break;
default:
TestGLES2Interface::GetIntegerv(pname, params);
break;
}
}
private:
GLenum format_ = 0;
GLenum type_ = 0;
};
} // namespace
class GLRendererCopierTest : public testing::Test {
public:
void SetUp() override {
auto context_provider = TestContextProvider::Create(
std::make_unique<CopierTestGLES2Interface>());
context_provider->BindToCurrentThread();
copier_ = std::make_unique<GLRendererCopier>(
std::move(context_provider), nullptr,
base::BindRepeating([](const gfx::Rect& rect) { return rect; }));
}
void TearDown() override { copier_.reset(); }
GLRendererCopier* copier() const { return copier_.get(); }
CopierTestGLES2Interface* test_gl() const {
return static_cast<CopierTestGLES2Interface*>(
copier_->context_provider_->ContextGL());
}
// These simply forward method calls to GLRendererCopier.
GLuint TakeCachedObjectOrCreate(const base::UnguessableToken& source,
int which) {
GLuint result = 0;
copier_->TakeCachedObjectsOrCreate(source, which, 1, &result);
return result;
}
void CacheObjectOrDelete(const base::UnguessableToken& source,
int which,
GLuint name) {
copier_->CacheObjectsOrDelete(source, which, 1, &name);
}
std::unique_ptr<GLHelper::ScalerInterface> TakeCachedScalerOrCreate(
const CopyOutputRequest& request) {
return copier_->TakeCachedScalerOrCreate(request, true);
}
void CacheScalerOrDelete(const base::UnguessableToken& source,
std::unique_ptr<GLHelper::ScalerInterface> scaler) {
copier_->CacheScalerOrDelete(source, std::move(scaler));
}
void FreeUnusedCachedResources() { copier_->FreeUnusedCachedResources(); }
GLenum GetOptimalReadbackFormat() const {
return copier_->GetOptimalReadbackFormat();
}
// These inspect the internal state of the GLRendererCopier's cache.
size_t GetCopierCacheSize() { return copier_->cache_.size(); }
bool CacheContainsObject(const base::UnguessableToken& source,
int which,
GLuint name) {
return !copier_->cache_.empty() && copier_->cache_.count(source) != 0 &&
copier_->cache_[source].object_names[which] == name;
}
bool CacheContainsScaler(const base::UnguessableToken& source,
int scale_from,
int scale_to) {
return !copier_->cache_.empty() && copier_->cache_.count(source) != 0 &&
copier_->cache_[source].scaler &&
copier_->cache_[source].scaler->IsSameScaleRatio(
gfx::Vector2d(scale_from, scale_from),
gfx::Vector2d(scale_to, scale_to));
}
static constexpr int kKeepalivePeriod = GLRendererCopier::kKeepalivePeriod;
private:
std::unique_ptr<GLRendererCopier> copier_;
};
// Tests that named objects, such as textures or framebuffers, are only cached
// when the CopyOutputRequest has specified a "source" of requests.
TEST_F(GLRendererCopierTest, ReusesNamedObjects) {
// With no source set in a copy request, expect to never re-use any textures
// or framebuffers.
base::UnguessableToken source;
for (int which = 0; which < 3; ++which) {
const GLuint a = TakeCachedObjectOrCreate(source, which);
EXPECT_NE(0u, a);
CacheObjectOrDelete(base::UnguessableToken(), which, a);
const GLuint b = TakeCachedObjectOrCreate(source, which);
EXPECT_NE(0u, b);
CacheObjectOrDelete(base::UnguessableToken(), which, b);
EXPECT_EQ(0u, GetCopierCacheSize());
}
// With a source set in the request, objects should now be cached and re-used.
source = base::UnguessableToken::Create();
for (int which = 0; which < 3; ++which) {
const GLuint a = TakeCachedObjectOrCreate(source, which);
EXPECT_NE(0u, a);
CacheObjectOrDelete(source, which, a);
const GLuint b = TakeCachedObjectOrCreate(source, which);
EXPECT_NE(0u, b);
EXPECT_EQ(a, b);
CacheObjectOrDelete(source, which, b);
EXPECT_EQ(1u, GetCopierCacheSize());
EXPECT_TRUE(CacheContainsObject(source, which, a));
}
}
// Tests that scalers are only cached when the CopyOutputRequest has specified a
// "source" of requests, and that different scalers are created if the scale
// ratio changes.
TEST_F(GLRendererCopierTest, ReusesScalers) {
// With no source set in the request, expect to not cache a scaler.
const auto request = CopyOutputRequest::CreateStubForTesting();
ASSERT_FALSE(request->has_source());
request->SetUniformScaleRatio(2, 1);
std::unique_ptr<GLHelper::ScalerInterface> scaler =
TakeCachedScalerOrCreate(*request);
EXPECT_TRUE(scaler.get());
CacheScalerOrDelete(base::UnguessableToken(), std::move(scaler));
EXPECT_FALSE(CacheContainsScaler(base::UnguessableToken(), 2, 1));
// With a source set in the request, a scaler can now be cached and re-used.
request->set_source(base::UnguessableToken::Create());
scaler = TakeCachedScalerOrCreate(*request);
const auto* a = scaler.get();
EXPECT_TRUE(a);
CacheScalerOrDelete(request->source(), std::move(scaler));
EXPECT_TRUE(CacheContainsScaler(request->source(), 2, 1));
scaler = TakeCachedScalerOrCreate(*request);
const auto* b = scaler.get();
EXPECT_TRUE(b);
EXPECT_EQ(a, b);
EXPECT_TRUE(b->IsSameScaleRatio(gfx::Vector2d(2, 2), gfx::Vector2d(1, 1)));
CacheScalerOrDelete(request->source(), std::move(scaler));
EXPECT_TRUE(CacheContainsScaler(request->source(), 2, 1));
// With a source set in the request, but a different scaling ratio needed, the
// cached scaler should go away and a new one created, and only the new one
// should ever appear in the cache.
request->SetUniformScaleRatio(3, 2);
scaler = TakeCachedScalerOrCreate(*request);
const auto* c = scaler.get();
EXPECT_TRUE(c);
EXPECT_TRUE(c->IsSameScaleRatio(gfx::Vector2d(3, 3), gfx::Vector2d(2, 2)));
EXPECT_FALSE(CacheContainsScaler(request->source(), 2, 1));
CacheScalerOrDelete(request->source(), std::move(scaler));
EXPECT_TRUE(CacheContainsScaler(request->source(), 3, 2));
}
// Tests that cached resources are freed if unused for a while.
TEST_F(GLRendererCopierTest, FreesUnusedResources) {
// Request a texture, then cache it again.
const base::UnguessableToken source = base::UnguessableToken::Create();
const int which = 0;
const GLuint a = TakeCachedObjectOrCreate(source, which);
EXPECT_NE(0u, a);
CacheObjectOrDelete(source, which, a);
EXPECT_TRUE(CacheContainsObject(source, which, a));
// Call FreesUnusedCachedResources() the maximum number of times before the
// cache entry would be considered for freeing.
for (int i = 0; i < kKeepalivePeriod - 1; ++i) {
FreeUnusedCachedResources();
EXPECT_TRUE(CacheContainsObject(source, which, a));
if (HasFailure())
break;
}
// Calling FreeUnusedCachedResources() just one more time should cause the
// cache entry to be freed.
FreeUnusedCachedResources();
EXPECT_FALSE(CacheContainsObject(source, which, a));
EXPECT_EQ(0u, GetCopierCacheSize());
}
TEST_F(GLRendererCopierTest, DetectsBGRAForReadbackFormat) {
test_gl()->SetOptimalReadbackFormat(GL_BGRA_EXT, GL_UNSIGNED_BYTE);
EXPECT_EQ(static_cast<GLenum>(GL_BGRA_EXT), GetOptimalReadbackFormat());
}
TEST_F(GLRendererCopierTest, DetectsRGBAForReadbackFormat) {
test_gl()->SetOptimalReadbackFormat(GL_RGBA, GL_UNSIGNED_BYTE);
EXPECT_EQ(static_cast<GLenum>(GL_RGBA), GetOptimalReadbackFormat());
}
TEST_F(GLRendererCopierTest, FallsBackOnRGBAForReadbackFormat_BadFormat) {
test_gl()->SetOptimalReadbackFormat(GL_RGB, GL_UNSIGNED_BYTE);
EXPECT_EQ(static_cast<GLenum>(GL_RGBA), GetOptimalReadbackFormat());
}
TEST_F(GLRendererCopierTest, FallsBackOnRGBAForReadbackFormat_BadType) {
test_gl()->SetOptimalReadbackFormat(GL_BGRA_EXT, GL_UNSIGNED_SHORT);
EXPECT_EQ(static_cast<GLenum>(GL_RGBA), GetOptimalReadbackFormat());
}
} // namespace viz
| 38.116935 | 80 | 0.713636 | [
"geometry"
] |
18becaab1d40dc9c9ed4c0e72c59b5bc47a93aed | 3,449 | cpp | C++ | dev/g++/projects/beaglebone/beagleboneLcd/test/testlib.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/projects/beaglebone/beagleboneLcd/test/testlib.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/projects/beaglebone/beagleboneLcd/test/testlib.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | 1 | 2017-01-27T12:53:50.000Z | 2017-01-27T12:53:50.000Z | //============================================================================
// Name : HelloWorld.cpp
// Author : Yann Garcia
// Version :
// Copyright : No copyright
// Description : beagleboneCommlibrary demonstrator/test application in C++, Ansi-style
//============================================================================
#include <iostream>
#include <iomanip> // Used for setprecision
#include <memory> // Used for unique_ptr
#include <unistd.h>
#include <signal.h>
#include <limits.h>
#include "getOpt.h"
#include "converter.h"
#include "keyboard.h"
#include "lcdManager.h"
#define PWM2A_LCD 22 // P8.19 - gpio0_22
using namespace std;
static std::unique_ptr<abstractLcd> lcd;
// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
void signal_callback_handler(const int signum) { // FIXME Use one callback per signal
std::cout << "Caught signal: " << signum << std::endl;
if (lcd != NULL) {
lcd->uninitialize();
lcd.reset(nullptr);
}
// Uninitialize the wiringBbb library
::wiringBbbShutdownSys();
// Terminate program
exit(signum);
} // End of function signal_callback_handler
/***********************************************************************
Main application part
***********************************************************************/
int main(const int argc, const char * argv[]) {
// Register signal and signal handler
if (signal (SIGINT, signal_callback_handler) == SIG_ERR) {
std::cerr << "Cannot handle SIGINT" << std::endl;
exit (EXIT_FAILURE);
}
if (signal (SIGTERM, signal_callback_handler) == SIG_ERR) {
std::cerr << "Cannot handle SIGTERM" << std::endl;
exit (EXIT_FAILURE);
}
// Parse command line arguments
bool isDebugSet;
getOpt::getOpt opt(argc, argv);
opt >> getOpt::Option('d', "debug", isDebugSet, false);
std::cout <<
"Arguments: " <<
" - debug:" << (const char *)((isDebugSet == true) ? "true" : "false") <<
std::endl;
// LCD datas port in 4 bits mode
std::vector<unsigned char> dataPorts;
dataPorts.push_back(76); // DB7 - P8_39
dataPorts.push_back(77); // DB6 - P8_40
dataPorts.push_back(74); // DB5 - P8_41
dataPorts.push_back(75); // DB4 - P8_42
// Initialize the wiringBbb library
::wiringBbbSetup();
lcdManager::getInstance().createLcdDevice(abstractLcd::HD44780U, lcd);
//lcd->setPowerMode(abstractLcd::mode3_3V, PWM2A_LCD); // Set power mode to 3.3V => PWM could be required to generate the negative voltage on the Vlcd
lcd->setPowerMode();
lcd->initialize(abstractLcd::mode_4bits, abstractLcd::lcd20x4, dataPorts, 46/*en*/, 65/*rs*//*, 27rw*/);
std::cout << "LCD initialization done" << std::endl;
lcd->clear();
std::string str("Hello World!");
lcd->write(str);
std::cout << "LCD Hello World! done" << std::endl;
lcd->setCursor(2, 10);
std::cout << "LCD setCursor done" << std::endl;
str.assign("From Me");
lcd->write(str);
std::cout << "LCD From Me done" << std::endl;
while (true) {
usleep(50);
if (beagleboneUtils::keyboard::keyboard::kbhit() != 0) {
std::cout << "key pressed was: '" << (char)getchar() << "'" << std::endl;
break; // Exit from 'while' statement
}
} // End of 'while' statement
lcd->clear();
lcd->cursorOff();
lcd->uninitialize();
lcd.reset(nullptr);
// Uninitialize the wiringBbb library
::wiringBbbShutdownSys();
return EXIT_SUCCESS;
}
| 30.254386 | 152 | 0.599884 | [
"vector"
] |
18cb516093dc72576b838328e9f41d3dcde2bec9 | 2,925 | cpp | C++ | src/parametrization/SO3.cpp | leoneed03/reconstrutor | 5e6417ed2b090617202cad1a10010141e4ce6615 | [
"MIT"
] | null | null | null | src/parametrization/SO3.cpp | leoneed03/reconstrutor | 5e6417ed2b090617202cad1a10010141e4ce6615 | [
"MIT"
] | 1 | 2021-05-21T15:52:37.000Z | 2021-05-24T11:34:46.000Z | src/parametrization/SO3.cpp | leoneed03/reconstrutor | 5e6417ed2b090617202cad1a10010141e4ce6615 | [
"MIT"
] | null | null | null | //
// Copyright (c) Leonid Seniukov. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
//
#include "parametrization/SO3.h"
#include <iomanip>
namespace gdr {
SO3::SO3(const Eigen::Matrix3d &rotationEigenMatrix) {
rotationInner = Sophus::SO3d::fitToSO3(rotationEigenMatrix);
}
SO3::SO3(const Eigen::Quaterniond &rotationEigenQuat) {
rotationInner = Sophus::SO3d::fitToSO3(rotationEigenQuat.normalized().toRotationMatrix());
}
Eigen::Vector3d SO3::getLog() const {
return rotationInner.log();
}
Eigen::Quaterniond SO3::getUnitQuaternion() const {
return rotationInner.unit_quaternion();
}
const Sophus::SO3d &SO3::getRotationSophus() const {
return rotationInner;
}
std::ostream &operator<<(std::ostream &os, const SO3 &rotation3D) {
const auto &quat = rotation3D.getUnitQuaternion();
os << quat.x() << ' '
<< quat.y() << ' '
<< quat.z() << ' '
<< quat.w();
return os;
}
SO3 operator*(const SO3 &lhs, const SO3 &rhs) {
return SO3(lhs.getRotationSophus() * rhs.getRotationSophus());
}
std::vector<SO3> operator*(const SO3 &so3, const std::vector<SO3> &rotations) {
std::vector<SO3> resultOrientations;
for (const auto &rotation: rotations) {
resultOrientations.emplace_back(so3 * rotation);
}
return resultOrientations;
}
Eigen::Matrix3d SO3::getRandomRotationMatrix3d() {
int dim = 3;
std::random_device randomDevice;
std::mt19937 randomNumberGenerator(randomDevice());
double maxRotation = 89;
std::uniform_real_distribution<> distrib(-maxRotation, maxRotation);
Eigen::Matrix3d rotationMatrix;
std::vector<double> angles;
for (int i = 0; i < dim; ++i) {
angles.push_back(distrib(randomNumberGenerator));
}
rotationMatrix = Eigen::AngleAxisd(angles[0], Eigen::Vector3d::UnitX())
* Eigen::AngleAxisd(angles[1], Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(angles[2], Eigen::Vector3d::UnitZ());
return rotationMatrix;
}
Eigen::Quaterniond SO3::getRandomUnitQuaternion() {
Eigen::Matrix3d rotationMatrix = getRandomRotationMatrix3d();
Eigen::Quaterniond quaternionRotation(rotationMatrix);
return quaternionRotation.normalized();
}
SO3::SO3(const Sophus::SO3d &rotationSophus) {
rotationInner = rotationSophus;
assert(rotationInner.unit_quaternion().angularDistance(rotationSophus.unit_quaternion()) <
std::numeric_limits<double>::epsilon());
}
int SO3::getSpaceIO() const {
return spaceIomanip;
}
SO3 SO3::inverse() const {
return SO3(getRotationSophus().inverse());
}
} | 29.25 | 98 | 0.623248 | [
"vector"
] |
18d6e7cebb6eb3712e6f8ba9bc565b028cb5161a | 8,409 | cpp | C++ | src/gui/settings.cpp | vlabella/GLE | ff6b424fda75d674c6a9f270ccdade3ab149e24f | [
"BSD-3-Clause"
] | 3 | 2022-03-03T06:48:33.000Z | 2022-03-13T21:18:11.000Z | src/gui/settings.cpp | vlabella/GLE | ff6b424fda75d674c6a9f270ccdade3ab149e24f | [
"BSD-3-Clause"
] | 1 | 2022-03-14T13:01:29.000Z | 2022-03-14T13:13:23.000Z | src/gui/settings.cpp | vlabella/GLE | ff6b424fda75d674c6a9f270ccdade3ab149e24f | [
"BSD-3-Clause"
] | 1 | 2021-12-21T23:14:06.000Z | 2021-12-21T23:14:06.000Z | /***********************************************************************************
* QGLE - A Graphical Interface to GLE *
* Copyright (C) 2006 A. S. Budden & J. Struyf *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
* *
* Also add information on how to contact you by electronic and paper mail. *
***********************************************************************************/
#include "settings.h"
#include <QSettings>
// Constructor: create the settings object
GLESettings::GLESettings(QObject *parent) : QObject(parent),
consoleWindowAutoShowSize(0)
{
settingStore = new QSettings("gle", "qgle", this);
}
void GLESettings::readAll()
{
// Read the application settings
setPosition(settingStore->value("application/position", QPoint(200,200)).toPoint());
setSize(settingStore->value("application/size", QSize(400,400)).toSize());
setMainWindowState(settingStore->value("application/mainstate").toByteArray());
setDrawingAreaSize(settingStore->value("application/drawingsize", QSize(400,400)).toSize());
setStoreSize(settingStore->value("application/storeSize", true).toBool());
setStoreDirectory(settingStore->value("application/storeDirectory", true).toBool());
setSaveOnPreview(settingStore->value("application/saveOnPreview", false).toBool());
setAskAboutObjects(settingStore->value("application/askAboutKeepingObjects", true).toBool());
setAutoScaleOnOpen(settingStore->value("application/autoScaleOnOpen", true).toBool());
setLibGSLocation(settingStore->value("application/libGSLocation", QString()).toString());
setEditorLocation(settingStore->value("application/editorLocation", QString("")).toString());
setDPI(settingStore->value("application/resolution", 100).toInt());
setMonitorOpenFile(settingStore->value("application/monitorOpenFile", true).toBool());
setMonitorAutoReloadFile(settingStore->value("application/monitorAutoReload", true).toBool());
setSplitterPosition(settingStore->value("application/splitterSizes").toByteArray());
setConsoleWindowAutoShowSize(settingStore->value("application/consoleAutoShowSize", 0).toInt());
setEmulateGLEVersion(settingStore->value("application/emulateGLEVersion", 0).toInt());
setExportFormat(settingStore->value("application/exportFormat", 0).toInt());
setExportPageSize(settingStore->value("application/exportPageSize", 0).toInt());
setPreviewPageSize(settingStore->value("application/previewPageSize", 0).toInt());
setOpenExportedFigure(settingStore->value("application/openExportedFigure", true).toBool());
setExportGrayScale(settingStore->value("application/exportGrayScale", false).toBool());
setExportTransparent(settingStore->value("application/exportTransparent", false).toBool());
setExportBitmapResolution(settingStore->value("application/exportBitmapResolution", 150).toInt());
setExportVectorResolution(settingStore->value("application/exportVectorResolution", 600).toInt());
setRenderUsingCairo(settingStore->value("application/renderUsingCairo", false).toBool());
if (storeDirectory())
setPwd(settingStore->value("application/workingDirectory", "").toString());
// Read the server settings
setPort(settingStore->value("server/portNumber", DEFAULT_PORT).toInt());
setAutoStartServer(settingStore->value("server/autoStart", true).toBool());
// Read the drawing settings
setGrid(QPointF(settingStore->value("drawing/gridX", 1.0).toDouble(),
settingStore->value("drawing/gridY", 1.0).toDouble()));
setEqualGrid(settingStore->value("drawing/equalGrid", false).toBool());
setPolarSnapStartAngle(settingStore->value("drawing/polarSnapStartAngle", 0.0).toDouble());
setPolarSnapIncAngle(settingStore->value("drawing/polarSnapIncAngle", 30.0).toDouble());
setOsnapOnStart(settingStore->value("drawing/osnapOnStart", false).toBool());
setOrthoSnapOnStart(settingStore->value("drawing/orthoSnapOnStart", false).toBool());
setPolarSnapOnStart(settingStore->value("drawing/polarSnapOnStart", false).toBool());
setPolarTrackOnStart(settingStore->value("drawing/polarTrackOnStart", false).toBool());
setGridSnapOnStart(settingStore->value("drawing/gridSnapOnStart", false).toBool());
}
void GLESettings::writeAll()
{
// Store the application settings
settingStore->setValue("application/position", position());
settingStore->setValue("application/size", size());
settingStore->setValue("application/mainstate", mainWindowState());
settingStore->setValue("application/drawingsize", drawingAreaSize());
settingStore->setValue("application/storeSize", storeSize());
settingStore->setValue("application/storeDirectory", storeDirectory());
settingStore->setValue("application/saveOnPreview", saveOnPreview());
settingStore->setValue("application/autoScaleOnOpen", autoScaleOnOpen());
settingStore->setValue("application/libGSLocation", getLibGSLocation());
settingStore->setValue("application/editorLocation", editorLocation());
settingStore->setValue("application/resolution", dpi());
settingStore->setValue("application/monitorOpenFile", monitorOpenFile());
settingStore->setValue("application/monitorAutoReload", monitorAutoReloadFile());
settingStore->setValue("application/askAboutKeepingObjects", askAboutObjects());
settingStore->setValue("application/splitterSizes", splitterPosition());
settingStore->setValue("application/consoleAutoShowSize", getConsoleWindowAutoShowSize());
settingStore->setValue("application/emulateGLEVersion", getEmulateGLEVersion());
settingStore->setValue("application/exportFormat", getExportFormat());
settingStore->setValue("application/exportPageSize", getExportPageSize());
settingStore->setValue("application/previewPageSize", getPreviewPageSize());
settingStore->setValue("application/openExportedFigure", isOpenExportedFigure());
settingStore->setValue("application/exportGrayScale", isExportGrayScale());
settingStore->setValue("application/exportTransparent", isExportTransparent());
settingStore->setValue("application/exportBitmapResolution", getExportBitmapResolution());
settingStore->setValue("application/exportVectorResolution", getExportVectorResolution());
settingStore->setValue("application/renderUsingCairo", isRenderUsingCairo());
if (storeDirectory())
settingStore->setValue("application/workingDirectory", pwd());
// Store the server settings
settingStore->setValue("server/portNumber", port());
settingStore->setValue("server/autoStart", autoStartServer());
// Store the drawing settings
settingStore->setValue("drawing/gridX", grid().x());
settingStore->setValue("drawing/gridY", grid().y());
settingStore->setValue("drawing/equalGrid", equalGrid());
settingStore->setValue("drawing/polarSnapStartAngle", polarSnapStartAngle());
settingStore->setValue("drawing/polarSnapIncAngle", polarSnapIncAngle());
settingStore->setValue("drawing/osnapOnStart", osnapOnStart());
settingStore->setValue("drawing/orthoSnapOnStart", orthoSnapOnStart());
settingStore->setValue("drawing/polarSnapOnStart", polarSnapOnStart());
settingStore->setValue("drawing/polarTrackOnStart", polarSnapOnStart());
settingStore->setValue("drawing/gridSnapOnStart", gridSnapOnStart());
}
| 63.225564 | 99 | 0.709478 | [
"object"
] |
18dae198903056f8136774d4c20b231383811370 | 3,345 | cpp | C++ | Tests/UnitTests/VolumeParticleEmitter2Tests.cpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 216 | 2017-01-25T04:34:30.000Z | 2021-07-15T12:36:06.000Z | Tests/UnitTests/VolumeParticleEmitter2Tests.cpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 323 | 2017-01-26T13:53:13.000Z | 2021-07-14T16:03:38.000Z | Tests/UnitTests/VolumeParticleEmitter2Tests.cpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 33 | 2017-01-25T05:05:49.000Z | 2021-06-17T17:30:56.000Z | #include "UnitTestsUtils.hpp"
#include "gtest/gtest.h"
#include <Core/Animation/Frame.hpp>
#include <Core/Emitter/VolumeParticleEmitter2.hpp>
#include <Core/Geometry/Sphere.hpp>
#include <Core/Geometry/SurfaceToImplicit.hpp>
using namespace CubbyFlow;
TEST(VolumeParticleEmitter2, Constructors)
{
auto sphere = std::make_shared<SurfaceToImplicit2>(
std::make_shared<Sphere2>(Vector2D(1.0, 2.0), 3.0));
BoundingBox2D region({ 0.0, 0.0 }, { 3.0, 3.0 });
VolumeParticleEmitter2 emitter(sphere, region, 0.1, { -1.0, 0.5 },
{ 0.0, 0.0 }, 0.0, 30, 0.01, false, true);
EXPECT_EQ(0.01, emitter.GetJitter());
EXPECT_FALSE(emitter.GetIsOneShot());
EXPECT_TRUE(emitter.GetAllowOverlapping());
EXPECT_EQ(30u, emitter.GetMaxNumberOfParticles());
EXPECT_EQ(0.1, emitter.GetSpacing());
EXPECT_EQ(-1.0, emitter.GetInitialVelocity().x);
EXPECT_EQ(0.5, emitter.GetInitialVelocity().y);
}
TEST(VolumeParticleEmitter2, Emit)
{
auto sphere = std::make_shared<SurfaceToImplicit2>(
std::make_shared<Sphere2>(Vector2D(1.0, 2.0), 3.0));
BoundingBox2D box({ 0.0, 0.0 }, { 3.0, 3.0 });
VolumeParticleEmitter2 emitter(sphere, box, 0.3, { -1.0, 0.5 },
{ 3.0, 4.0 }, 5.0, 30, 0.0, false, false);
auto particles = std::make_shared<ParticleSystemData2>();
emitter.SetTarget(particles);
Frame frame(0, 1.0);
emitter.Update(frame.TimeInSeconds(), frame.timeIntervalInSeconds);
auto pos = particles->Positions();
auto vel = particles->Velocities();
EXPECT_EQ(30u, particles->NumberOfParticles());
for (size_t i = 0; i < particles->NumberOfParticles(); ++i)
{
EXPECT_GE(3.0, (pos[i] - Vector2D(1.0, 2.0)).Length());
EXPECT_TRUE(box.Contains(pos[i]));
Vector2D r = pos[i];
Vector2D w = 5.0 * Vector2D(-r.y, r.x);
Vector2D res = Vector2D(2.0, 4.5) + w;
EXPECT_VECTOR2_NEAR(res, vel[i], 1e-9);
}
++frame;
emitter.SetMaxNumberOfParticles(60);
emitter.Update(frame.TimeInSeconds(), frame.timeIntervalInSeconds);
EXPECT_EQ(51u, particles->NumberOfParticles());
pos = particles->Positions();
for (size_t i = 0; i < particles->NumberOfParticles(); ++i)
{
pos[i] += Vector2D(2.0, 1.5);
}
++frame;
emitter.Update(frame.TimeInSeconds(), frame.timeIntervalInSeconds);
EXPECT_LT(51u, particles->NumberOfParticles());
}
TEST(VolumeParticleEmitter2, Builder)
{
auto sphere = std::make_shared<Sphere2>(Vector2D(1.0, 2.0), 3.0);
VolumeParticleEmitter2 emitter =
VolumeParticleEmitter2::GetBuilder()
.WithSurface(sphere)
.WithMaxRegion(BoundingBox2D({ 0.0, 0.0 }, { 3.0, 3.0 }))
.WithSpacing(0.1)
.WithInitialVelocity({ -1.0, 0.5 })
.WithMaxNumberOfParticles(30)
.WithJitter(0.01)
.WithIsOneShot(false)
.WithAllowOverlapping(true)
.Build();
EXPECT_EQ(0.01, emitter.GetJitter());
EXPECT_FALSE(emitter.GetIsOneShot());
EXPECT_TRUE(emitter.GetAllowOverlapping());
EXPECT_EQ(30u, emitter.GetMaxNumberOfParticles());
EXPECT_EQ(0.1, emitter.GetSpacing());
EXPECT_EQ(-1.0, emitter.GetInitialVelocity().x);
EXPECT_EQ(0.5, emitter.GetInitialVelocity().y);
} | 33.118812 | 77 | 0.634978 | [
"geometry"
] |
18dca0b773fa5601b3399fccfac87e9c8e9d39e0 | 445 | hpp | C++ | libs/render/include/hamon/render/front_face.hpp | shibainuudon/HamonEngine | 508a69b0cf589ccb2e5d403ce9e78ff2b85cc058 | [
"MIT"
] | null | null | null | libs/render/include/hamon/render/front_face.hpp | shibainuudon/HamonEngine | 508a69b0cf589ccb2e5d403ce9e78ff2b85cc058 | [
"MIT"
] | 21 | 2022-03-02T13:11:59.000Z | 2022-03-30T15:12:41.000Z | libs/render/include/hamon/render/front_face.hpp | shibainuudon/HamonEngine | 508a69b0cf589ccb2e5d403ce9e78ff2b85cc058 | [
"MIT"
] | null | null | null | /**
* @file front_face.hpp
*
* @brief FrontFace
*/
#ifndef HAMON_RENDER_FRONT_FACE_HPP
#define HAMON_RENDER_FRONT_FACE_HPP
#include <cstdint>
namespace hamon
{
inline namespace render
{
enum class FrontFace : std::uint32_t
{
Clockwise,
CounterClockwise,
// alias
CW = Clockwise,
CCW = CounterClockwise,
};
} // inline namespace render
} // namespace hamon
#endif // HAMON_RENDER_FRONT_FACE_HPP
| 13.484848 | 38 | 0.678652 | [
"render"
] |
18dcef18b5dba5911a887bc60b4dfb6c28f10a30 | 1,936 | cpp | C++ | td/telegram/GroupCallVideoPayload.cpp | ByeCoder/td | 609eb0a53cbb1ba05f11b17fff0d78e6082390c5 | [
"BSL-1.0"
] | null | null | null | td/telegram/GroupCallVideoPayload.cpp | ByeCoder/td | 609eb0a53cbb1ba05f11b17fff0d78e6082390c5 | [
"BSL-1.0"
] | null | null | null | td/telegram/GroupCallVideoPayload.cpp | ByeCoder/td | 609eb0a53cbb1ba05f11b17fff0d78e6082390c5 | [
"BSL-1.0"
] | null | null | null | //
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "td/telegram/GroupCallVideoPayload.h"
#include "td/utils/algorithm.h"
namespace td {
static bool operator==(const GroupCallVideoSourceGroup &lhs, const GroupCallVideoSourceGroup &rhs) {
return lhs.semantics == rhs.semantics && lhs.source_ids == rhs.source_ids;
}
bool operator==(const GroupCallVideoPayload &lhs, const GroupCallVideoPayload &rhs) {
return lhs.source_groups == rhs.source_groups && lhs.endpoint == rhs.endpoint && lhs.is_paused == rhs.is_paused;
}
static td_api::object_ptr<td_api::groupCallVideoSourceGroup> get_group_call_video_source_group_object(
const GroupCallVideoSourceGroup &group) {
return td_api::make_object<td_api::groupCallVideoSourceGroup>(group.semantics, vector<int32>(group.source_ids));
}
td_api::object_ptr<td_api::groupCallParticipantVideoInfo> get_group_call_participant_video_info_object(
const GroupCallVideoPayload &payload) {
if (payload.endpoint.empty() || payload.source_groups.empty()) {
return nullptr;
}
return td_api::make_object<td_api::groupCallParticipantVideoInfo>(
transform(payload.source_groups, get_group_call_video_source_group_object), payload.endpoint, payload.is_paused);
}
GroupCallVideoPayload get_group_call_video_payload(const telegram_api::groupCallParticipantVideo *video) {
GroupCallVideoPayload result;
result.endpoint = video->endpoint_;
result.source_groups = transform(video->source_groups_, [](auto &&source_group) {
GroupCallVideoSourceGroup result;
result.semantics = source_group->semantics_;
result.source_ids = source_group->sources_;
return result;
});
result.is_paused = video->paused_;
return result;
}
} // namespace td
| 39.510204 | 119 | 0.779959 | [
"vector",
"transform"
] |
18de8486973d07c739f8ba3783b1eeb5e6d04218 | 9,303 | hpp | C++ | libogre/src/PriorityDownloadPlanner.hpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | 31 | 2015-01-28T17:01:10.000Z | 2021-11-04T08:30:37.000Z | libogre/src/PriorityDownloadPlanner.hpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | null | null | null | libogre/src/PriorityDownloadPlanner.hpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | 9 | 2015-08-02T18:39:49.000Z | 2019-10-11T10:32:30.000Z | // Copyright (c) 2009 Sirikata Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#ifndef _SIRIKATA_OGRE_PRIORITY_DOWNLOAD_PLANNER_HPP
#define _SIRIKATA_OGRE_PRIORITY_DOWNLOAD_PLANNER_HPP
#include <sirikata/ogre/ResourceDownloadPlanner.hpp>
#include <sirikata/mesh/AssetDownloadTask.hpp>
#include <sirikata/ogre/Util.hpp>
#include <sirikata/mesh/Meshdata.hpp>
#include <sirikata/mesh/Billboard.hpp>
#include <sirikata/core/util/Liveness.hpp>
#include <sirikata/core/command/Commander.hpp>
namespace Sirikata {
namespace Graphics {
class WebView;
/** Interface for a metric that can be used with PriorityDownloadPlanner. */
class PriorityDownloadPlannerMetric {
public:
virtual ~PriorityDownloadPlannerMetric() {}
virtual double calculatePriority(Graphics::Camera *camera, ProxyObjectPtr proxy) = 0;
virtual String name() const = 0;
};
typedef std::tr1::shared_ptr<PriorityDownloadPlannerMetric> PriorityDownloadPlannerMetricPtr;
class DistanceDownloadPlannerMetric : public PriorityDownloadPlannerMetric {
public:
virtual ~DistanceDownloadPlannerMetric() {}
virtual double calculatePriority(Graphics::Camera *camera, ProxyObjectPtr proxy);
virtual String name() const { return "distance"; }
};
class SolidAngleDownloadPlannerMetric : public PriorityDownloadPlannerMetric {
public:
virtual ~SolidAngleDownloadPlannerMetric() {}
virtual double calculatePriority(Graphics::Camera *camera, ProxyObjectPtr proxy);
virtual String name() const { return "solid_angle"; }
};
/** Implementation of ResourceDownloadPlanner that orders loading by a priority
* metric computed on each object. The priority metric is pluggable and a
* maximum number of objects can also be enforced.
*/
class PriorityDownloadPlanner : public ResourceDownloadPlanner,
public virtual Liveness
{
public:
PriorityDownloadPlanner(Context* c, OgreRenderer* renderer, PriorityDownloadPlannerMetricPtr metric);
~PriorityDownloadPlanner();
virtual void addNewObject(Graphics::Entity *ent, const Transfer::URI& mesh);
virtual void addNewObject(ProxyObjectPtr p, Graphics::Entity *mesh);
virtual void updateObject(ProxyObjectPtr p);
virtual void removeObject(ProxyObjectPtr p);
virtual void removeObject(Graphics::Entity* ent);
//PollingService interface
virtual void poll();
virtual void stop();
PriorityDownloadPlannerMetricPtr prioritizationMetric() {
return mMetric;
}
void setPrioritizationMetric(PriorityDownloadPlannerMetricPtr metric) {
mMetric = metric;
}
virtual Stats stats();
protected:
bool mStopped;
PriorityDownloadPlannerMetricPtr mMetric;
struct Object;
void iUpdateObject(ProxyObjectPtr p,Liveness::Token lt);
void iRemoveObject(const String& name, Liveness::Token alive);
void iAddObject(Object* r, Liveness::Token alive);
void addObject(Object* r);
Object* findObject(const String& sporef);
void removeObject(const String& sporef);
double calculatePriority(ProxyObjectPtr proxy);
void commandGetData(
const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid);
void commandGetStats(
const Command::Command& cmd, Command::Commander* cmdr, Command::CommandID cmdid);
void checkShouldLoadNewObject(Object* r);
// Checks if changes just due to budgets are possible,
// e.g. regardless of priorities, we have waiting objects and free
// spots for them.
bool budgetRequiresChange() const;
void loadObject(Object* r);
void unloadObject(Object* r);
struct Object {
Object(Graphics::Entity *m, const Transfer::URI& mesh_uri, ProxyObjectPtr _proxy = ProxyObjectPtr());
virtual ~Object(){
}
const String& id() const { return name; }
Transfer::URI file;
Graphics::Entity *mesh;
String name;
bool loaded;
float32 priority;
ProxyObjectPtr proxy;
class Hasher {
public:
size_t operator() (const Object& r) const {
return std::tr1::hash<String>()(r.name);
}
};
struct MaxHeapComparator {
bool operator()(Object* lhs, Object* rhs) {
return lhs->priority < rhs->priority;
}
};
struct MinHeapComparator {
bool operator()(Object* lhs, Object* rhs) {
return lhs->priority > rhs->priority;
}
};
};
typedef std::tr1::unordered_set<String> ObjectSet;
typedef std::tr1::unordered_map<String, Object*> ObjectMap;
// The full list
ObjectMap mObjects;
// Loading has started for these
ObjectMap mLoadedObjects;
// Waiting to be important enough to load
ObjectMap mWaitingObjects;
// Heap storage for Objects. Choice between min/max heap is at call time.
typedef std::vector<Object*> ObjectHeap;
typedef std::vector<WebView*> WebMaterialList;
// Assets represent a single graphical asset that needs to be downloaded
// from the CDN and loaded into memory. Since a single asset can be loaded
// many times by different 'Objects' (i.e. objects in the world) we track
// them separately and make sure we only issue single requests for them.
struct Asset : public Liveness
{
Transfer::URI uri;
Mesh::AssetDownloadTaskPtr downloadTask;
// Objects that want this asset to be loaded and are waiting for it
ObjectSet waitingObjects;
// Objects that are using this asset
ObjectSet usingObjects;
// Filled in by the loader with the name of the asset that's actually
// used when creating an instance (unique name for mesh, billboard
// texture, etc).
String ogreAssetName;
//Can get into a situation where we fire a callback associated with a
//transfer uri, then we delete the associated asset, then create a new
//asset with the same uri. The callback assumes that internal state
//for the asset is valid and correct (in particular, downloadTask).
//However, in these cases, the data wouldn't be valid. Use internalId
//to check that the callback that is being serviced corresponds to the
//correct asset that we have in memory.
uint64 internalId;
TextureBindingsMapPtr textureFingerprints;
std::set<String> animations;
WebMaterialList webMaterials;
// # of resources we're still waiting to finish loading
uint16 loadingResources;
// Sets of resources this Asset has loaded so we can get
// ResourceLoader to unload them. Ordered list so we can
// unload in reverse order we loaded in.
typedef std::vector<String > ResourceNameList;
ResourceNameList loadedResources;
// Store a copy so we can release the download task but still
// get at the data if another object uses this mesh.
Mesh::VisualPtr visual;
Asset(const Transfer::URI& name);
~Asset();
};
typedef std::tr1::unordered_map<Transfer::URI, Asset*, Transfer::URI::Hasher> AssetMap;
AssetMap mAssets;
// Because we aggregate all Asset requests so we only generate one
// AssetDownloadTask, we need to aggregate some priorities
// ourselves. Aggregation will still also be performed by other parts of the
// system on a per-Resource basis (TransferPool for multiple requests by
// different Assets, TransferMediator for requests across multiple Pools).
Transfer::PriorityAggregationAlgorithm* mAggregationAlgorithm;
// These are a sequence of async operations that take a URI for a
// resource/asset pair and gets it loaded. Some paths will terminate early
// since multiple resources that share an asset can share many of these
// steps.
void requestAssetForObject(Object*);
void downloadAsset(Asset* asset, Object* forObject);
void loadAsset(Transfer::URI asset_uri,uint64 assetId);
void finishLoadAsset(Asset* asset, bool success);
void loadMeshdata(Asset* asset, const Mesh::MeshdataPtr& mdptr, bool usingDefault);
void loadBillboard(Asset* asset, const Mesh::BillboardPtr& bbptr, bool usingDefault);
void loadDependentTextures(Asset* asset, bool usingDefault);
// Helper, notifies when resource has finished loading allowing us
// to figure out when the entire asset has loaded
void handleLoadedResource(Asset* asset,Liveness::Token assetAlive);
// Update the priority for an asset from all it's requestors
void updateAssetPriority(Asset* asset);
// Removes the resource's need for the asset, potentially allowing it to be
// unloaded.
void unrequestAssetForObject(Object*);
// Helper to check if it's safe to remove an asset and does so if
// possible. Properly handles current
void checkRemoveAsset(Asset* asset,Liveness::Token lt);
bool mActiveCDNArchive;
unsigned int mCDNArchive;
void iStop(Liveness::Token dpAlive);
void iPoll(Liveness::Token dpAlive);
};
} // namespace Graphics
} // namespace Sirikata
#endif //_SIRIKATA_OGRE_PRIORITY_DOWNLOAD_PLANNER_HPP
| 36.916667 | 109 | 0.705149 | [
"mesh",
"object",
"vector"
] |
18e3bbda141a634640df51e3ed5133d8626a435c | 2,074 | hpp | C++ | include/codegen/include/UnityEngine/ProBuilder/MeshOperations/MeshValidation_--c__DisplayClass5_0.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/ProBuilder/MeshOperations/MeshValidation_--c__DisplayClass5_0.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/ProBuilder/MeshOperations/MeshValidation_--c__DisplayClass5_0.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:22 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
// Including type: UnityEngine.ProBuilder.MeshOperations.MeshValidation
#include "UnityEngine/ProBuilder/MeshOperations/MeshValidation.hpp"
// Including type: UnityEngine.ProBuilder.Triangle
#include "UnityEngine/ProBuilder/Triangle.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<TResult, T>
template<typename TResult, typename T>
class Func_2;
}
// Completed forward declares
// Type namespace: UnityEngine.ProBuilder.MeshOperations
namespace UnityEngine::ProBuilder::MeshOperations {
// Autogenerated type: UnityEngine.ProBuilder.MeshOperations.MeshValidation/<>c__DisplayClass5_0
class MeshValidation::$$c__DisplayClass5_0 : public ::Il2CppObject {
public:
// public UnityEngine.ProBuilder.Triangle triangle
// Offset: 0x10
UnityEngine::ProBuilder::Triangle triangle;
// public System.Func`2<UnityEngine.ProBuilder.Triangle,System.Boolean> <>9__0
// Offset: 0x20
System::Func_2<UnityEngine::ProBuilder::Triangle, bool>* $$9__0;
// System.Boolean <CollectFaceGroups>b__0(UnityEngine.ProBuilder.Triangle x)
// Offset: 0x100C7F0
bool $CollectFaceGroups$b__0(UnityEngine::ProBuilder::Triangle x);
// public System.Void .ctor()
// Offset: 0x100B4FC
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static MeshValidation::$$c__DisplayClass5_0* New_ctor();
}; // UnityEngine.ProBuilder.MeshOperations.MeshValidation/<>c__DisplayClass5_0
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::MeshOperations::MeshValidation::$$c__DisplayClass5_0*, "UnityEngine.ProBuilder.MeshOperations", "MeshValidation/<>c__DisplayClass5_0");
#pragma pack(pop)
| 44.12766 | 183 | 0.74108 | [
"object"
] |
18ee90c30b00ce716bbf98c8a771decae32a87f8 | 8,009 | cpp | C++ | Main.cpp | hogsy/Bin2Obj | b0593c6149105c9cdff0bb148a543de8dae37c82 | [
"MIT"
] | 3 | 2021-01-12T09:57:00.000Z | 2021-05-20T21:24:35.000Z | Main.cpp | hogsy/Bin2Obj | b0593c6149105c9cdff0bb148a543de8dae37c82 | [
"MIT"
] | null | null | null | Main.cpp | hogsy/Bin2Obj | b0593c6149105c9cdff0bb148a543de8dae37c82 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2021 Mark E Sowden <hogsy@oldtimes-software.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 <cstring>
#include <cmath>
#include <iostream>
#include <vector>
struct Vertex {
float x{ 0 }, y{ 0 }, z{ 0 };
void operator*=( float v ) { x *= v; y *= v; z *= v; }
};
struct Face {
unsigned int x{ 0 }, y{ 0 }, z{ 0 };
};
static struct Environment {
const char* filePath{ nullptr };
const char* outPath{ "dump.obj" };
unsigned long startOffset{ 0 };
unsigned long stride{ 0 };
unsigned long endOffset{ 0 };
float scale{ 1.0f };
unsigned long faceStartOffset{ 0 };
unsigned long faceEndOffset{ 0 };
unsigned long faceStride{ 0 };
std::vector<Face> meshFaces;
bool verbose{ false };
std::vector<Vertex> meshVertices;
} env;
#define AbortApp( ... ) printf( __VA_ARGS__ ); exit( EXIT_FAILURE )
#define Print( ... ) printf( __VA_ARGS__ )
#define VPrint( ... ) if( env.verbose ) { printf( __VA_ARGS__ ); }
#define Warn( ... ) printf( "WARNING: " __VA_ARGS__ )
static void SetOutPath(const char* argument) { env.outPath = argument; }
static void SetStartOffset(const char* argument) { env.startOffset = strtoul(argument, nullptr, 10); }
static void SetEndOffset(const char* argument) { env.endOffset = strtoul(argument, nullptr, 10); }
static void SetStride(const char* argument) { env.stride = strtoul(argument, nullptr, 10); }
static void SetVertexScale(const char* argument) { env.scale = strtof(argument, nullptr); }
static void SetFaceStartOffset(const char* argument) { env.faceStartOffset = strtoul(argument, nullptr, 10); }
static void SetFaceEndOffset(const char* argument) { env.faceEndOffset = strtoul(argument, nullptr, 10); }
static void SetFaceStride(const char* argument) { env.faceStride = strtoul(argument, nullptr, 10); }
static void SetVerboseMode(const char* argument) { env.verbose = true; }
/**
* Parse all arguments on the command line based on the provided table.
*/
static void ParseCommandLine(int argc, char** argv) {
struct LaunchArgument {
const char* str;
void(*Callback)(const char* argument);
const char* desc;
};
// All possible arguments go in this table.
static LaunchArgument launchArguments[] = {
{ "-soff", SetStartOffset, "Set the start offset to begin reading from." },
{ "-eoff", SetEndOffset, "Set the end offset to stop reading, otherwise reads to EOF." },
{ "-stri", SetStride, "Number of bytes to proceed after reading XYZ." },
{ "-outp", SetOutPath, "Set the path for the output file." },
{ "-vtxs", SetVertexScale, "Scales the vertices by the defined amount." },
{ "-fsof", SetFaceStartOffset, "Sets the start offset to start loading face indices from." },
{ "-feof", SetFaceEndOffset, "Sets the end offset to finish loading face indices from." },
{ "-fstr", SetFaceStride, "Number of bytes to proceed after reading in face indices." },
{ "-verb", SetVerboseMode, "Enables more verbose output." },
{ nullptr }
};
// If we don't have any arguments, print them out.
if (argc <= 1) {
Print("No arguments provided. Possible arguments are provided below.\n");
Print("First argument is required to be a path to the file, then followed by any of the optional arguments.\n");
const LaunchArgument* opt = &launchArguments[0];
while (opt->str != nullptr) {
Print(" %s\t\t%s\n", opt->str, opt->desc);
opt++;
}
Print("For example,\n\tbin2obj ..\\path\\myfile.whatever -soff 128\n");
exit(EXIT_SUCCESS);
return;
}
const LaunchArgument* opt = &launchArguments[0];
while (opt->str != nullptr) {
for (int i = 0; i < argc; ++i) {
if (strcmp(opt->str, argv[i]) != 0) {
continue;
}
const char* arg = (i + 1) < argc ? argv[i + 1] : nullptr;
opt->Callback(arg);
}
opt++;
}
}
static void FileSeek(FILE* file, unsigned long numBytes, bool fromStart) {
if (fseek(file, numBytes, fromStart ? SEEK_SET : SEEK_CUR) == 0) {
return;
}
AbortApp("Failed to seek to %lu!\n", numBytes);
}
#define CloseFile(FILE) if( (FILE) != nullptr ) fclose( (FILE) ); (FILE) = nullptr
int main(int argc, char** argv) {
Print(
"Bin2Obj by Mark \"hogsy\" Sowden <hogsy@oldtimes-software.com>\n"
"==============================================================\n\n"
);
ParseCommandLine(argc, argv);
env.filePath = argv[1];
Print("Loading \"%s\"\n", env.filePath);
FILE* file = fopen(env.filePath, "rb");
if (file == nullptr) {
AbortApp("Failed to open \"%s\"!\n", env.filePath);
}
FileSeek(file, env.startOffset, true);
while (feof(file) == 0) {
Vertex v;
if (fread(&v, sizeof(Vertex), 1, file) != 1) {
break;
}
v *= env.scale;
if (std::isnan(v.x) || std::isnan(v.y) || std::isnan(v.z)) {
Warn("Encountered NaN for vertex, ");
if (std::isnan(v.x)) { Print("X "); v.x = 0.0f; }
if (std::isnan(v.y)) { Print("Y "); v.y = 0.0f; }
if (std::isnan(v.z)) { Print("Z "); v.z = 0.0f; }
Print("- defaulting to 0.0!\n");
}
VPrint( "\tx( %f ) y( %f ) z( %f )\n", v.x, v.y, v.z );
env.meshVertices.push_back(v);
if (env.endOffset > 0 && ftell(file) >= env.endOffset) {
break;
}
int r = fseek(file, env.stride, SEEK_CUR);
if (env.stride > 0 && r != 0) {
break;
}
}
Print( "Loaded in %d vertices\n", (int)env.meshVertices.size() );
// If both start and end offsets are defined for the faces, load those in.
unsigned long faceBytes = env.faceEndOffset - env.faceStartOffset;
if( faceBytes > 0 ) {
Print("Attempting to read in faces...\n");
FileSeek( file, env.faceStartOffset, true );
// Since we require both the start and end, we know how much data we want.
unsigned int numFaces = faceBytes / sizeof( Face );
env.meshFaces.reserve( numFaces );
for( unsigned int i = 0; i < numFaces; ++i ) {
Face f;
if( fread( &f, sizeof( Face ), 1, file ) != 1 ) {
Warn( "Failed to load in all desired faces, keep in mind some faces may be missing or incorrect!\n" );
break;
}
VPrint( "\tx( %d ) y( %d ) z( %d )\n", f.x, f.y, f.z );
if( f.x >= env.meshVertices.size() || f.y >= env.meshVertices.size() || f.z >= env.meshVertices.size() ) {
Warn( "Encountered out of bound vertex index, " );
if( f.x >= env.meshVertices.size() ) { Print( "X " ); f.x = 0; }
if( f.y >= env.meshVertices.size() ) { Print( "Y " ); f.y = 0; }
if( f.z >= env.meshVertices.size() ) { Print( "Z " ); f.z = 0; }
Print( "- defaulting to 0!\n" );
}
env.meshFaces.push_back(f);
int r = fseek( file, env.faceStride, SEEK_CUR );
if( env.faceStride > 0 && r != 0 ) {
break;
}
}
Print( "Loaded in %d faces\n", (int)env.meshFaces.size() );
}
CloseFile(file);
file = fopen(env.outPath, "w");
fprintf(file, "# Generated by Bin2Obj, by Mark \"hogsy\" Sowden <hogsy@oldtimes-software.com>\n\n");
for (auto& vertex : env.meshVertices) {
fprintf(file, "v %f %f %f\n", vertex.x, vertex.y, vertex.z);
}
for( auto &face : env.meshFaces ) {
fprintf(file, "f %d %d %d\n", face.x, face.y, face.z);
}
CloseFile(file);
Print("Wrote \"%s\"!\n", env.outPath);
return EXIT_SUCCESS;
}
| 35.754464 | 114 | 0.654514 | [
"vector"
] |
18f2d8b3e885c099443bc3fc0aa2c0165258fc0f | 364 | hpp | C++ | Board.hpp | marwanhresh/board-b | bcb17b9ab8602a8ffba76ab53c062c5dd4c67c5f | [
"MIT"
] | null | null | null | Board.hpp | marwanhresh/board-b | bcb17b9ab8602a8ffba76ab53c062c5dd4c67c5f | [
"MIT"
] | null | null | null | Board.hpp | marwanhresh/board-b | bcb17b9ab8602a8ffba76ab53c062c5dd4c67c5f | [
"MIT"
] | null | null | null | #include<iostream>
#include"Direction.hpp"
#include<vector>
using namespace std;
namespace ariel
{
class Board {
vector<string>board;
public:
Board(){
}
void post (unsigned int row ,unsigned int column,Direction d,string s);
string read(unsigned int row , unsigned int column,Direction d,unsigned int size);
void show();
};
}
| 21.411765 | 86 | 0.675824 | [
"vector"
] |
18f640e3dcbdad667c45f1c389c576a937414fb2 | 6,599 | cpp | C++ | IR/IR.cpp | Yveh/Compiler-Mx_star | e00164537528858ed128dbc5a5c4cf7006d6276e | [
"MIT"
] | 1 | 2020-01-23T14:34:11.000Z | 2020-01-23T14:34:11.000Z | IR/IR.cpp | Yveh/Compiler-Mx_star | e00164537528858ed128dbc5a5c4cf7006d6276e | [
"MIT"
] | null | null | null | IR/IR.cpp | Yveh/Compiler-Mx_star | e00164537528858ed128dbc5a5c4cf7006d6276e | [
"MIT"
] | null | null | null | #include "IR.h"
IROperand IROPerandVoid() {return IROperand(IROperand::Void);}
IROperand IROperandReg32(int _id, bool _pointer) {return IROperand(IROperand::Reg32, _id, _pointer);}
IROperand IROperandReg8(int _id, bool _pointer) {return IROperand(IROperand::Reg8, _id, _pointer);}
IROperand IROperandImm32(int _id, bool _pointer) {return IROperand(IROperand::Imm32, _id, _pointer);}
IROperand IROperandImm8(int _id, bool _pointer) {return IROperand(IROperand::Imm8, _id, _pointer);}
IROperand IROperandConst(int _id) {return IROperand(IROperand::constID, _id);}
std::string IROperand::to_string() {
std::string ret;
if (type == type_t::Void)
ret = "void";
else if (type == type_t::Reg32 || type == type_t::Imm32)
ret = "i32";
else
ret = "i8";
if (pointer)
ret += "*";
return ret;
}
std::string IROperand::get_id() const {
if (type == Reg32 || type == Reg8)
return "%" + std::to_string(id);
else if (type == constID)
return "str." + std::to_string(id);
else
return std::to_string(id);
}
bool IROperand::is_void() {
return type == type_t::Void;
}
IROperand::IROperand(IROperand::type_t _type, int _id, bool _pointer) : type(_type), id(_id), pointer(_pointer) {}
int IROperand::size() const {
if (type == Void)
return 0;
// else if (pointer)
// return 4;
else if (type == Reg32 || type == Imm32)
return 4;
else if (type == Reg8 || type == Imm8)
return 1;
else
return 0;
}
bool IROperand::is_reg() {
return type == Reg32 || type == Reg8;
}
bool IROperand::operator<(const IROperand &rhs) const {
return type < rhs.type || (type == rhs.type && id < rhs.id);
}
bool IROperand::operator==(const IROperand &rhs) const {
return type == rhs.type && id == rhs.id;
}
bool IROperand::is_imm() {
return type == Imm8 || type == Imm32;
}
std::string IRAlloca::to_string() {
return dst.get_id() + " = alloca " + dst.to_string();
}
IRAlloca::IRAlloca(IROperand _dst) : dst(_dst) {}
std::string IRMalloc::to_string() {
return dst.get_id() + " = malloc(" + size.get_id() + ")";
}
IRMalloc::IRMalloc(IROperand _dst, IROperand _size) : dst(_dst), size(_size) {}
std::string IRBinary::to_string() {
std::string ret;
switch (op) {
case op_t::And : ret = "&"; break;
case op_t::Or : ret = "|"; break;
case op_t::Xor : ret = "^"; break;
case op_t::Eq : ret = "=="; break;
case op_t::Ne : ret = "!="; break;
case op_t::Slt : ret = "<"; break;
case op_t::Sle : ret = "<="; break;
case op_t::Sgt : ret = ">"; break;
case op_t::Sge : ret = ">="; break;
case op_t::Shl : ret = "<<"; break;
case op_t::Ashr : ret = ">>"; break;
case op_t::Add : ret = "+"; break;
case op_t::Sub : ret = "-"; break;
case op_t::Mul : ret = "*"; break;
case op_t::Sdiv : ret = "/"; break;
case op_t::Srem : ret = "%"; break;
}
return dst.get_id() + " = " + src1.get_id() + " " + ret + " " + src2.get_id();
}
IRBinary::IRBinary(IRBinary::op_t _op, IROperand _dst, IROperand _src1, IROperand _src2) : op(_op), dst(_dst), src1(_src1), src2(_src2) {}
std::string IRBr::to_string() {
return "br " + cond.get_id() + " lab" + std::to_string(thenBlock->label) + " lab" + std::to_string(elseBlock->label);
}
IRBr::IRBr(IROperand _cond, std::shared_ptr<IRBlock> _tb, std::shared_ptr<IRBlock> _eb) : cond(_cond), thenBlock(_tb), elseBlock(_eb) {}
std::string IRCall::to_string() {
std::string ret;
if (func->retType.is_void())
ret = func->retType.to_string() + " @" + func->name + "(";
else
ret = dst.get_id() + " = " + func->retType.to_string() + "@" + func->name + "(";
bool first = true;
for (auto child : paras) {
if (!first)
ret += ",";
first = false;
ret += child.to_string() + " " + child.get_id();
}
ret += ")";
return ret;
}
IRCall::IRCall(std::shared_ptr<IRFunction> _func, std::vector<IROperand> _paras, IROperand _dst) : func(_func), paras(_paras), dst(_dst) {}
std::string IRJump::to_string() {
return "br lab" + std::to_string(block->label);
}
IRJump::IRJump(std::shared_ptr<IRBlock> _blk) : block(_blk) {}
std::string IRLoad::to_string() {
return dst.get_id() + " = load " + dst.to_string() + " " + addr.get_id();
}
IRLoad::IRLoad(IROperand _dst, IROperand _addr) : dst(_dst), addr(_addr) {}
std::string IRStore::to_string() {
return "store " + value.to_string() + " " + addr.get_id() + " " + value.get_id();
}
IRStore::IRStore(IROperand _addr, IROperand _value) : addr(_addr), value(_value) {}
std::string IRReturn::to_string() {
return "ret " + value.to_string() + " " + value.get_id();
}
IRReturn::IRReturn(IROperand _value) : value(_value) {}
IRFunction::IRFunction(std::string _name) : name(_name) {
isBuiltin = 0;
}
void IRFunction::getAllBlocks(std::shared_ptr<IRBlock> cur) {
if (vis.count(cur->label))
return;
vis.insert(cur->label);
blocks.push_back(cur);
std::vector<std::shared_ptr<IRBlock>> nxt;
for (auto inst : cur->insts) {
if (std::dynamic_pointer_cast<IRBr>(inst)) {
auto tmp = std::dynamic_pointer_cast<IRBr>(inst);
nxt.push_back(tmp->thenBlock);
nxt.push_back(tmp->elseBlock);
cur->next.push_back(tmp->thenBlock);
cur->next.push_back(tmp->elseBlock);
tmp->thenBlock->pre.push_back(cur);
tmp->elseBlock->pre.push_back(cur);
}
if (std::dynamic_pointer_cast<IRJump>(inst)) {
auto tmp = std::dynamic_pointer_cast<IRJump>(inst);
nxt.push_back(tmp->block);
cur->next.push_back(tmp->block);
tmp->block->pre.push_back(cur);
}
}
for (auto child : nxt) {
getAllBlocks(child);
}
}
IRBlock::IRBlock(int _label) : label(_label) {}
IRClass::IRClass(std::string _name) : name(_name) {
size = 0;
}
int IRClass::getOffset(std::string name) {
return offset[ref[name]];
}
IRPhi::IRPhi(IROperand _dst) : dst(_dst) {}
std::string IRPhi::to_string() {
std::string ret = dst.get_id() + " = phi ";
for (int i = 0; i < values.size(); ++i) {
if (i)
ret += ", ";
ret += "[" + values[i].get_id() + ", LAB" + std::to_string(blocks[i]->label) + "]";
}
return ret;
}
IRMove::IRMove(IROperand _dst, IROperand _src) : dst(_dst), src(_src) {}
std::string IRMove::to_string() {
return dst.get_id() + " = " + src.get_id();
}
| 30.836449 | 139 | 0.586756 | [
"vector"
] |
18f85a3c1f7e175829d854f19a7a6e8486d89ad9 | 1,673 | hpp | C++ | inc/Materials/PhongInstanced.hpp | barne856/3DSWMM | 60dd2702c82857dcf4358b8d42a1fb430a568e90 | [
"MIT"
] | null | null | null | inc/Materials/PhongInstanced.hpp | barne856/3DSWMM | 60dd2702c82857dcf4358b8d42a1fb430a568e90 | [
"MIT"
] | null | null | null | inc/Materials/PhongInstanced.hpp | barne856/3DSWMM | 60dd2702c82857dcf4358b8d42a1fb430a568e90 | [
"MIT"
] | null | null | null | #ifndef PHONG_INSTANCED_MATERIAL
#define PHONG_INSTANCED_MATERIAL
#include "Application/Material.hpp"
class PhongInstanced : public Material
{
public:
PhongInstanced()
{
material.ambient = glm::vec4(0.1f);
material.diffuse = glm::vec4(0.5f);
material.specular = glm::vec4(0.0f);
material.shininess = 32.0f;
light.ambient = glm::vec4(1.0f);
light.diffuse = glm::vec4(1.0f);
light.specular = glm::vec4(0.0f);
light_position = glm::vec4(1.0f, 0.0f, 1.0f, 0.0f);
mix_value = 0.0f;
m_shader.create("./res/Material/phong_instanced");
m_shader.use();
bind_uniform_block("material_properties", sizeof(material));
bind_uniform_block("light_properties", sizeof(light));
}
virtual ~PhongInstanced() {}
virtual void render()
{
upload_uniform_block("material_properties", &material);
upload_uniform_block("light_properties", &light);
upload_uniform_vec4("light_position", light_position);
upload_uniform_float("mix_value", mix_value);
}
glm::vec4 get_flat_color()
{
glm::vec3 ambient = (material.ambient * light.ambient);
glm::vec3 diffuse = (material.diffuse * light.diffuse);
return glm::vec4(-glm::vec3(1.0f) * (1.0f - mix_value) * 0.25f + (ambient + diffuse), 1.0f);
}
struct
{
glm::vec4 ambient;
glm::vec4 diffuse;
glm::vec4 specular;
float shininess;
} material;
struct
{
glm::vec4 ambient;
glm::vec4 diffuse;
glm::vec4 specular;
} light;
glm::vec4 light_position;
float mix_value;
};
#endif | 30.981481 | 100 | 0.617454 | [
"render"
] |
bb466778b3297db73450847f761a22235a4023a0 | 3,278 | cpp | C++ | Online Judges/LightOJ/Dynamic-Programming/1191 - Bar Codes.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | 4 | 2017-02-20T17:41:14.000Z | 2019-07-15T14:15:34.000Z | Online Judges/LightOJ/Dynamic-Programming/1191 - Bar Codes.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | null | null | null | Online Judges/LightOJ/Dynamic-Programming/1191 - Bar Codes.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | null | null | null | //1191 - Bar Codes
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long long unsigned llu;
typedef double dl;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef map<int,int> mii;
typedef map<ll,ll> mll;
typedef map<string,int> msi;
typedef map<char,int> mci;
typedef pair<int ,pii> piii;
typedef vector<pii> vpii;
typedef vector<piii> vpiii;
#define pi acos(-1.0)
#define S second
#define F first
#define pb push_back
#define MP make_pair
#define mem(a,b) memset(a,b,sizeof a)
#define all(v) v.begin(),v.end()
#define vsort(v) sort(v.begin(),v.end())
#define IO ios_base::sync_with_stdio(false);cin.tie(NULL)
#define gcd(a,b) __gcd(a,b)
#define I(a) scanf("%d",&a)
#define I2(a,b) scanf("%d%d",&a,&b)
#define L(a) scanf("%lld",&a)
#define L2(a,b) scanf("%lld%lld",&a,&b)
#define D(a) scanf("%lf",&a)
#define SP cout<<" ";
#define PI(a) printf("%d",a)
#define PL(a) printf("%lld",a)
#define PD(a) printf("%lf",a)
#define CHK cout<<"MK"<<endl
template <class T> inline T BMOD(T p,T e,T m){T ret=1;while(e){if(e&1) ret=(ret*p)%m;p=(p*p)%m;e>>=1;}return (T)ret;}
template <class T> inline T MODINV(T a,T m){return BMOD(a,m-2,m);}
template <class T> inline T isPrime(T a){for(T i=2;i<=sqrt(double(a));i++){if(a%i==0){return 0;}}return 1;}
template <class T> inline T lcm(T a, T b){return (a/gcd(a,b))*b;}
template <class T> inline T power(T a, T b){return (b==0)?1:a*power(a,b-1);}
template <class T> inline string toStr(T t) { stringstream ss; ss<<t; return ss.str();}
template <class T> inline long long toLong(T t) {stringstream ss;ss<<t;long long ret;ss>>ret;return ret;}
template <class T> inline int toInt(T t) {stringstream ss;ss<<t;int ret;ss>>ret;return ret;}
//~ cout << fixed << setprecision(20) << Ans << endl;
//~ priority_queue<piii,vpiii, greater<piii> >pq; //for dijkstra
/* _ */
/*____________|\/||_||\||_________________*/
string buffer;
int INT(){
getline(cin,buffer);
return toInt(buffer);
}
int LONG(){
getline(cin,buffer);
return toLong(buffer);
}
#define MX 11
#define MD 1e9+7
const int SIZE = 15;
ll sv[51][51][51],n,m;
ll go(int p,int k,int r){
if(p==0){
if(k==0) return 1;
return 0;
}
if(k<0) return 0;
ll &ret = sv[p][k][r];
if(ret!=-1) return ret;
ret = 0;
for(int i=1;i<=r;i++){
if(p-i>=0) ret += go(p-i,k-1,r);
}
return ret;
}
void fun(){
for(int i=0;i<51;i++){
sv[0][0][i]=1;
sv[1][1][i]=1;
}
for(int k=1;k<51;k++){
for(int i =2;i<51;i++){
for(int j=1;j<=i;j++){
for(int a =1;a<=min(k,i);a++){
sv[i][j][k]+= sv[i-a][j-1][k];
}
}
}
}
}
int main()
{
//~ IO;
//~ freopen("/home/krishna/PRG/practice/input.in","r",stdin);
int ts,cs=0;
ll k;
I(ts);
//~ mem(sv,-1);
fun();
while(ts--){
L2(n,k);L(m);
ll Ans = sv[n][k][m];
printf("Case %d: %lld\n",++cs,Ans);
}
return 0;
}
| 27.779661 | 117 | 0.535998 | [
"vector"
] |
bb46ac107955d9117ce7a98a0f3e26f2b893c787 | 8,647 | cpp | C++ | dev/spark/Gem/Code/Components/ProjectileManagerSystemComponent.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | 2 | 2020-08-20T03:40:24.000Z | 2021-02-07T20:31:43.000Z | dev/spark/Gem/Code/Components/ProjectileManagerSystemComponent.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | null | null | null | dev/spark/Gem/Code/Components/ProjectileManagerSystemComponent.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z |
#include "spark_precompiled.h"
#include "ProjectileManagerSystemComponent.h"
#include "ProjectileControllerComponent.h"
#include "Busses/DynamicSliceManagerBus.h"
#include <AzCore/Serialization/EditContext.h>
#include <AzFramework/Input/Channels/InputChannel.h>
#include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
#include <LmbrCentral/Rendering/ParticleComponentBus.h>
#include <LmbrCentral/Shape/CylinderShapeComponentBus.h>
#include <LmbrCentral/Scripting/TriggerAreaComponentBus.h>
#include <AzFramework/Network/NetworkContext.h>
#include <AzFramework/Network/NetBindingHandlerBus.h>
#include <AzFramework/Network/NetBindingComponent.h>
#include <AzFramework/Components/TransformComponent.h>
#include <GridMate/Replica/ReplicaFunctions.h>
#include <GridMate/Replica/ReplicaChunk.h>
#include <GridMate/Replica/DataSet.h>
#include <GridMate/Serialize/CompressionMarshal.h>
#include "Components/TriggerAreaComponent.h"
#include "Components/UnitNavigationComponent.h"
using namespace spark;
using namespace AzFramework;
//ProjectileManagerSystemComponent implementation
void ProjectileManagerSystemComponent::Reflect(AZ::ReflectContext* reflection)
{
if (auto serializationContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializationContext->Class<ProjectileManagerSystemComponent, AZ::Component>()
->Version(2);
if (auto editContext = serializationContext->GetEditContext())
{
editContext->Class<ProjectileManagerSystemComponent>("ProjectileManagerSystemComponent", "Responsible for the lifetime of projectiles")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "spark")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game"));
}
}
}
void ProjectileManagerSystemComponent::Init()
{
}
void ProjectileManagerSystemComponent::Activate()
{
ProjectileManagerRequestBus::Handler::BusConnect();
}
void ProjectileManagerSystemComponent::Deactivate()
{
ProjectileManagerRequestBus::Handler::BusDisconnect();
ResetProjectileManager();
}
void ProjectileManagerSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("ProjectileManagerService"));
}
void ProjectileManagerSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("ProjectileManagerService"));
}
void ProjectileManagerSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
(void)required;
}
void ProjectileManagerSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent)
{
(void)dependent;
}
void ProjectileManagerSystemComponent::RegisterProjectileAsset(const ProjectileAsset & asset)
{
}
void ProjectileManagerSystemComponent::OnSliceInstantiated(const AZ::Data::AssetId& sliceAssetId, const AZ::SliceComponent::SliceInstanceAddress& instance) {
const AzFramework::SliceInstantiationTicket ticket = (*AzFramework::SliceInstantiationResultBus::GetCurrentBusId());
// Stop listening for this ticket (since it's done). We can have have multiple tickets in flight.
AzFramework::SliceInstantiationResultBus::MultiHandler::BusDisconnect(ticket);
auto it = m_projectileSlices.find(ticket);
if (it == m_projectileSlices.end())return;
ProjectileInfo info = it->second;
m_projectileSlices.erase(it);
for (AZ::Entity *entity : instance.second->GetInstantiated()->m_entities)
{
EBUS_EVENT_ID( entity->GetId(), ProjectileRequestBus, Fire, info);
}
AZ_Printf(0, "OnSliceInstantiated with ticket=%d and assetId=%s", ticket.m_requestId, sliceAssetId.ToString<AZStd::string>().c_str());
AZ::Entity *e = (*(instance.second->GetInstantiated()->m_entities.rbegin()));
AZ_Printf(0, "ProjectileManagerSystemComponent::OnSliceInstantiated entity's state is %d", e->GetState());
}
void ProjectileManagerSystemComponent::OnSlicePreInstantiate(const AZ::Data::AssetId& sliceAssetId, const AZ::SliceComponent::SliceInstanceAddress& instance) {
//m_id = (*(instance.second->GetInstantiated()->m_entities.rbegin()))->GetId();
//AzFramework::SliceInstantiationResultBus::Handler::BusDisconnect();
AZ::Entity *e = (*(instance.second->GetInstantiated()->m_entities.rbegin()));
AZ_Printf(0, "ProjectileManagerSystemComponent::OnSlicePreInstantiate entity's state is %d", e->GetState());
}
ProjectileId ProjectileManagerSystemComponent::CreateProjectile(ProjectileInfo projectileInfo)
{
if (!AzFramework::NetQuery::IsEntityAuthoritative(GetEntityId())) return 0;
projectileInfo.projectileId = m_projectileId++;
return projectileInfo.projectileId;
}
void ProjectileManagerSystemComponent::FireProjectile(ProjectileInfo projectileInfo)
{
if (!AzFramework::NetQuery::IsEntityAuthoritative(GetEntityId())) return;
AZ_Printf(0, "OnProjectileFired");
if (!projectileInfo.autoRelease)
{
m_projectiles[projectileInfo.projectileId] = projectileInfo;
}
if (projectileInfo.type == ProjectileInfo::NORMAL_ATTACK)
{
// it's a right click attack, right now these are stored in slices so we gotta do this dance
//const AZ::Data::AssetType& projectileAssetType = azrtti_typeid<AZ::DynamicPrefabAsset>();
//AZ::Data::Asset<AZ::DynamicPrefabAsset> projectileAsset(projectileInfo.asset, projectileAssetType);
AZ::Data::Asset<AZ::DynamicPrefabAsset> projectileAsset;
EBUS_EVENT_RESULT(projectileAsset, DynamicSliceManagerRequestBus, GetDynamicSliceAsset, projectileInfo.asset);
AzFramework::SliceInstantiationTicket ticket;
AZ::Transform transform = AZ::Transform::CreateTranslation(projectileInfo.startingPosition);
EBUS_EVENT_RESULT(ticket, AzFramework::GameEntityContextRequestBus, InstantiateDynamicSlice, projectileAsset, transform, nullptr);
AzFramework::SliceInstantiationResultBus::MultiHandler::BusConnect(ticket);
m_projectileSlices[ticket] = projectileInfo;
}
else
{
// normal projectile
// these are basically just hollow entities, they can have stuff attached to them later
AZ::Entity* entity = aznew AZ::Entity;
if (entity == nullptr)
{
AZ_Warning("ProjectileManagerSystemComponent", false, "Failed to create an entity with AzFramework::GameEntityContextRequestBus, CreateGameEntity");
return;
}
// AZ_Printf(0, "the projectile state is %i", entity->GetState())
auto projectileComponent = entity->CreateComponent<ProjectileControllerComponent>();
entity->CreateComponent<AzFramework::TransformComponent>();
if (projectileInfo.triggerRadius > 0.f)
{
entity->CreateComponent(LmbrCentral::CylinderShapeComponentTypeId);
entity->CreateComponent<UnitNavigationComponent>();
projectileComponent->m_isNavEntity = true;
entity->CreateComponent<spark::Spark2dTriggerAreaComponent>();// ("{E3DF5790-F0AD-43AE-9FB2-0A37F873DECB}");
}
entity->CreateComponent<AzFramework::NetBindingComponent>();
// AZ_Printf(0, "the projectile state is %i", entity->GetState());
// activate the entity and then make a bunch of ebus calls
entity->Init();
entity->Activate();
EBUS_EVENT(AzFramework::GameEntityContextRequestBus, AddGameEntity, entity);
if (projectileInfo.triggerRadius > 0.f)
{
// trigger area
EBUS_EVENT_ID(entity->GetId(), LmbrCentral::CylinderShapeComponentRequestsBus, SetRadius, projectileInfo.triggerRadius);
EBUS_EVENT_ID(entity->GetId(), LmbrCentral::CylinderShapeComponentRequestsBus, SetHeight, 5.0f);
EBUS_EVENT_ID(entity->GetId(), LmbrCentral::TriggerAreaRequestsBus, AddRequiredTag, AZ::Crc32("unit"));
}
// transform
//EBUS_EVENT_ID(entity->GetId(), AZ::TransformBus, SetWorldTranslation, projectileInfo.startingPosition);
EBUS_EVENT_ID(entity->GetId(), NavigationEntityRequestBus, SetPosition, projectileInfo.startingPosition);
// projectile controller
EBUS_EVENT_ID(entity->GetId(), ProjectileRequestBus, Fire, projectileInfo);
}
return; //don't send to all proxies
}
void ProjectileManagerSystemComponent::ResetProjectileManager()
{
AZ_Warning("ProjectileManagerSystemComponent", false, "ResetProjectileManager");
//clear old entities:
//ctrl+g in the editor don't reconstruct system components, so we want to clear the old state to not have invalid entities in the pools
m_projectiles.clear();
m_projectileSlices.clear();
}
bool ProjectileManagerSystemComponent::IsProjectileReleased (const ProjectileId pId)
{
return m_projectiles.find(pId) == m_projectiles.end();
}
void ProjectileManagerSystemComponent::ReleaseProjectile (const ProjectileId pId)
{
auto it = m_projectiles.find(pId);
if (it == m_projectiles.end()) return;
m_projectiles.erase(it);
} | 35.879668 | 159 | 0.791141 | [
"shape",
"transform"
] |
bb477ad6ba9462d0daaad76b24d2010efdfc3b8f | 2,099 | cpp | C++ | lucas/codeforces/1241/cforces1241C.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | 2 | 2019-09-09T00:34:40.000Z | 2019-09-09T17:35:19.000Z | lucas/codeforces/1241/cforces1241C.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | null | null | null | lucas/codeforces/1241/cforces1241C.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | null | null | null | /*
* author: lucas_medeiros - github.com/medeiroslucas
* team: Lo and Behold ++
* created: 06-10-2019 12:33:16
* contest: 1241
* problem: C
* solved: False
*/
#include <bits/stdc++.h>
#define DEBUG false
#define coutd if(DEBUG) cout
#define debugf if(DEBUG) printf
#define ff first
#define ss second
#define pb push_back
#define eb emplace_back
#define sz size()
using namespace std;
using ll = long long;
using ii = pair<int, int>;
using vi = vector<int>;
const double PI = acos(-1);
const double EPS = 1e-9;
int main(){
ios_base::sync_with_stdio(false);
ll q, n, x, y, a, b, aux, j;
cin >> q;
while(q--){
cin >> n;
vector<ll> num(n);
vector<ll> order(n);
for(int i=0; i<n; i++){
cin >> aux;
num[i] = -aux;
}
cin >> x >> a >> y >> b >> j;
int lcm = (a*b)/__gcd(a, b);
sort(num.begin(), num.end());
for(int i=0; i<n; i++){
order[i] = -1;
}
int k=0;
for(int i=lcm; i<=n; i+=lcm, k++){
order[i-1] = -num[k];
}
/*
if(x > y){
for(int i=a; i<=n;i+=a){
if(order[i-1] == -1){
order[i-1] = -num[k];
k++;
}
}
for(int i=b; i<=n ;i+=b){
if(order[i-1] == -1){
order[i-1] = -num[k];
k++;
}
}
}else{
for(int i=b; i<=n;i+=b){
if(order[i-1] == -1){
order[i-1] = -num[k];
k++;
}
}
for(int i=a; i<=n ;i+=a){
if(order[i-1] == -1){
order[i-1] = -num[k];
k++;
}
}
}*/
for(int i=1; i<=n; i++){
if((i%a==0) xor (i%b ==0)){
order[i-1] = -num[k];
k++;
}
}
for(int i=0; i<n; i++){
if(order[i] == -1){
order[i] = -num[k];
k++;
}
}
ll val=0;
for(int i=1; i<=n; i++){
if(i % a == 0 and i % b == 0){
val += (double)order[i-1]*((double)x/100.0);
val += (double)order[i-1]*((double)y/100.0);
}else if(i%a==0){
val += (double)order[i-1]*((double)x/100.0);
}else if(i%b==0){
val += (double)order[i-1]*((double)y/100.0);
}
//cout << val << " **** " << j << endl;
if(val >= j){
cout << (i) << endl;
break;
}
}
if(val < j){
cout << -1 << endl;
}
}
return 0;
}
| 16.271318 | 53 | 0.468318 | [
"vector"
] |
bb49d501546bf3696beea3874449bf41585526ef | 681 | cpp | C++ | asst7_hil00/uniq.cpp | hibalubbad/hiba.baddie | 69001ad56c8a51f6e36a802bae061128d9fd5a71 | [
"MIT"
] | null | null | null | asst7_hil00/uniq.cpp | hibalubbad/hiba.baddie | 69001ad56c8a51f6e36a802bae061128d9fd5a71 | [
"MIT"
] | null | null | null | asst7_hil00/uniq.cpp | hibalubbad/hiba.baddie | 69001ad56c8a51f6e36a802bae061128d9fd5a71 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool uniq(vector <int> v,int i,int j){
if(i>=j)
return 1;
else {
for(int k = i+1;k<=j;k++){
if(v[k]==v[i])
return 0;
else{
return uniq(v,i+1,j);
}
}
}
return 0;
}
int main(){
vector <int> v;
v.push_back(1);
v.push_back(1);
v.push_back(1);
v.push_back(3);
v.push_back(1);
v.push_back(3);
v.push_back(2);
v.push_back(1);
cout<<uniq(v,5,6)<<endl;
}
// the problem is of complexity O(n) but could be of O(logn) if binary search was used instead of linear. | 21.28125 | 106 | 0.515419 | [
"vector"
] |
bb511e82cbc96bfcab4b16c389a02c3a645d4aea | 561 | cpp | C++ | 167/twosum.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | 1 | 2018-06-24T13:58:07.000Z | 2018-06-24T13:58:07.000Z | 167/twosum.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | null | null | null | 167/twosum.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>res;
if(nums.empty() || nums.size() <= 1) return res;
int left = 0, right = nums.size() - 1;
while(nums[left] + nums[right] != target){
if(nums[left] + nums[right] < target) left++;
else right--;
}
res.push_back(left+1);
res.push_back(right+1);
return res;
}
int main(){
vector<int>nums = {2,7,11,15};
vector<int>res = twoSum(nums, 9);
cout<<"First index: "<<res[0]<<endl;
cout<<"Second index: "<<res[1]<<endl;
return 0;
}
| 23.375 | 51 | 0.634581 | [
"vector"
] |
bb59617621e8f25ff43e1c6588fd88b6ba9d3c0e | 35,391 | cpp | C++ | src/CQChartsCorrelationPlot.cpp | SammyEnigma/CQCharts | 56433e32c943272b6faaf6771d0652c0507f943e | [
"MIT"
] | 14 | 2018-05-22T15:06:08.000Z | 2022-01-20T12:18:28.000Z | src/CQChartsCorrelationPlot.cpp | SammyEnigma/CQCharts | 56433e32c943272b6faaf6771d0652c0507f943e | [
"MIT"
] | 6 | 2020-09-04T15:49:24.000Z | 2022-01-12T19:06:45.000Z | src/CQChartsCorrelationPlot.cpp | SammyEnigma/CQCharts | 56433e32c943272b6faaf6771d0652c0507f943e | [
"MIT"
] | 9 | 2019-04-01T13:10:11.000Z | 2022-01-22T01:46:27.000Z | #include <CQChartsCorrelationPlot.h>
#include <CQChartsCorrelationModel.h>
#include <CQChartsView.h>
#include <CQChartsModelDetails.h>
#include <CQChartsModelData.h>
#include <CQChartsModelUtil.h>
#include <CQChartsLoader.h>
#include <CQChartsFilterModel.h>
#include <CQChartsUtil.h>
#include <CQCharts.h>
#include <CQChartsRotatedText.h>
#include <CQChartsTip.h>
#include <CQChartsViewPlotPaintDevice.h>
#include <CQChartsScriptPaintDevice.h>
#include <CQChartsPlotParameterEdit.h>
#include <CQChartsHtml.h>
#include <CQChartsWidgetUtil.h>
#include <CQPropertyViewItem.h>
#include <CQPerfMonitor.h>
#include <QMenu>
CQChartsCorrelationPlotType::
CQChartsCorrelationPlotType()
{
}
void
CQChartsCorrelationPlotType::
addParameters()
{
// options
addEnumParameter("diagonalType", "Diagonal Cell Type", "diagonalType").
addNameValue("NONE" , int(CQChartsCorrelationPlot::DiagonalType::NONE )).
addNameValue("NAME" , int(CQChartsCorrelationPlot::DiagonalType::NAME )).
addNameValue("MIN_MAX", int(CQChartsCorrelationPlot::DiagonalType::MIN_MAX)).
addNameValue("DENSITY", int(CQChartsCorrelationPlot::DiagonalType::DENSITY)).
setTip("Diagonal Cell Type");
addEnumParameter("upperDiagonalType", "Upper Diagonal Cell Type", "upperDiagonalType").
addNameValue("NONE" , int(CQChartsCorrelationPlot::OffDiagonalType::NONE )).
addNameValue("PIE" , int(CQChartsCorrelationPlot::OffDiagonalType::PIE )).
addNameValue("SHADE" , int(CQChartsCorrelationPlot::OffDiagonalType::SHADE )).
addNameValue("ELLIPSE" , int(CQChartsCorrelationPlot::OffDiagonalType::ELLIPSE )).
addNameValue("POINTS" , int(CQChartsCorrelationPlot::OffDiagonalType::POINTS )).
addNameValue("CONFIDENCE", int(CQChartsCorrelationPlot::OffDiagonalType::CONFIDENCE)).
setTip("Upper Diagonal Cell Type");
addEnumParameter("lowerDiagonalType", "Lower Diagonal Cell Type", "lowerDiagonalType").
addNameValue("NONE" , int(CQChartsCorrelationPlot::OffDiagonalType::NONE )).
addNameValue("PIE" , int(CQChartsCorrelationPlot::OffDiagonalType::PIE )).
addNameValue("SHADE" , int(CQChartsCorrelationPlot::OffDiagonalType::SHADE )).
addNameValue("ELLIPSE" , int(CQChartsCorrelationPlot::OffDiagonalType::ELLIPSE )).
addNameValue("POINTS" , int(CQChartsCorrelationPlot::OffDiagonalType::POINTS )).
addNameValue("CONFIDENCE", int(CQChartsCorrelationPlot::OffDiagonalType::CONFIDENCE)).
setTip("Lower Diagonal Cell Type");
CQChartsPlotType::addParameters();
}
QString
CQChartsCorrelationPlotType::
description() const
{
auto IMG = [](const QString &src) { return CQChartsHtml::Str::img(src); };
return CQChartsHtml().
h2("Correlation Plot").
h3("Summary").
p("Draws correlation data for model.").
h3("Limitations").
p("None.").
h3("Example").
p(IMG("images/correlation.png"));
}
CQChartsPlot *
CQChartsCorrelationPlotType::
create(View *view, const ModelP &model) const
{
return new CQChartsCorrelationPlot(view, model);
}
//------
CQChartsCorrelationPlot::
CQChartsCorrelationPlot(View *view, const ModelP &model) :
CQChartsPlot(view, view->charts()->plotType("correlation"), model),
CQChartsObjCellShapeData <CQChartsCorrelationPlot>(this),
CQChartsObjCellLabelTextData<CQChartsCorrelationPlot>(this),
CQChartsObjXLabelTextData <CQChartsCorrelationPlot>(this),
CQChartsObjYLabelTextData <CQChartsCorrelationPlot>(this)
{
}
CQChartsCorrelationPlot::
~CQChartsCorrelationPlot()
{
term();
}
//---
void
CQChartsCorrelationPlot::
init()
{
CQChartsPlot::init();
//---
NoUpdate noUpdate(this);
//---
// create correlation model
CQChartsLoader loader(charts());
correlationModel_ = loader.createCorrelationModel(model().data());
baseModel_ = dynamic_cast<CQChartsCorrelationModel *>(correlationModel_->baseModel());
nc_ = correlationModel_->columnCount();
//---
correlationModelP_ = ModelP(correlationModel_);
auto *modelData = charts()->initModelData(correlationModelP_);
charts()->setModelName(modelData, "correlationModel");
//---
addTitle();
setCellFillColor(Color(Color::Type::PALETTE));
setCellLabelTextAlign(Qt::AlignHCenter | Qt::AlignVCenter);
setXLabelTextAlign(Qt::AlignHCenter | Qt::AlignTop ); setXLabelTextAngle(Angle(90.0));
setYLabelTextAlign(Qt::AlignRight | Qt::AlignVCenter); setYLabelTextAngle(Angle( 0.0));
setXLabelTextFont(CQChartsFont().decFontSize(4));
setYLabelTextFont(CQChartsFont().decFontSize(4));
}
void
CQChartsCorrelationPlot::
term()
{
charts()->removeModel(correlationModelP_);
}
//---
void
CQChartsCorrelationPlot::
setDiagonalType(const DiagonalType &t)
{
CQChartsUtil::testAndSet(diagonalType_, t, [&]() {
drawObjs(); emit customDataChanged();
} );
}
void
CQChartsCorrelationPlot::
setLowerDiagonalType(const OffDiagonalType &t)
{
CQChartsUtil::testAndSet(lowerDiagonalType_, t, [&]() {
drawObjs(); emit customDataChanged();
} );
}
void
CQChartsCorrelationPlot::
setUpperDiagonalType(const OffDiagonalType &t)
{
CQChartsUtil::testAndSet(upperDiagonalType_, t, [&]() {
drawObjs(); emit customDataChanged();
} );
}
//---
void
CQChartsCorrelationPlot::
addProperties()
{
addBaseProperties();
// cell fill
addProp("cell/fill", "cellFilled", "visible", "Cell fill visible");
addFillProperties("cell/fill", "cellFill", "Cell");
// cell stroke
addProp("cell/stroke", "cellStroked", "visible", "Cell stroke visible");
addLineProperties("cell/stroke", "cellStroke", "Cell");
// cell label text
addProp("cell/text", "cellLabels", "visible", "Cell text label visible");
addTextProperties("cell/text", "cellLabelText", "Cell label",
CQChartsTextOptions::ValueType::ALL);
// x/y axis label text
addProp("xaxis/text", "xLabels", "visible", "X labels visible");
addTextProperties("xaxis/text", "xLabelText", "X label",
CQChartsTextOptions::ValueType::ALL);
addProp("yaxis/text", "yLabels", "visible", "Y labels visible");
addTextProperties("yaxis/text", "yLabelText", "Y label",
CQChartsTextOptions::ValueType::ALL);
// cell types
addProp("cell", "diagonalType" , "diagonal" , "Diagonal cell type");
addProp("cell", "lowerDiagonalType", "lowerDiagonal", "Lower Diagonal cell type");
addProp("cell", "upperDiagonalType", "upperDiagonal", "Upper Diagonal cell type");
}
//---
void
CQChartsCorrelationPlot::
setXLabels(bool b)
{
CQChartsUtil::testAndSet(xLabels_, b, [&]() { drawObjs(); } );
}
void
CQChartsCorrelationPlot::
setYLabels(bool b)
{
CQChartsUtil::testAndSet(yLabels_, b, [&]() { drawObjs(); } );
}
void
CQChartsCorrelationPlot::
setCellLabels(bool b)
{
CQChartsUtil::testAndSet(cellLabels_, b, [&]() { drawObjs(); } );
}
//---
void
CQChartsCorrelationPlot::
diagonalTypeSlot(bool b)
{
if (b) {
auto name = qobject_cast<QAction *>(sender())->text();
if (name == "None" ) setDiagonalType(DiagonalType::NONE);
else if (name == "Name" ) setDiagonalType(DiagonalType::NAME);
else if (name == "Min/Max") setDiagonalType(DiagonalType::MIN_MAX);
else if (name == "Density") setDiagonalType(DiagonalType::DENSITY);
}
else
setDiagonalType(DiagonalType::NONE);
}
void
CQChartsCorrelationPlot::
upperDiagonalTypeSlot(bool b)
{
if (b) {
auto name = qobject_cast<QAction *>(sender())->text();
if (name == "None" ) setUpperDiagonalType(OffDiagonalType::NONE);
else if (name == "Pie" ) setUpperDiagonalType(OffDiagonalType::PIE);
else if (name == "Shade" ) setUpperDiagonalType(OffDiagonalType::SHADE);
else if (name == "Ellipse" ) setUpperDiagonalType(OffDiagonalType::ELLIPSE);
else if (name == "Points" ) setUpperDiagonalType(OffDiagonalType::POINTS);
else if (name == "Confidence") setUpperDiagonalType(OffDiagonalType::CONFIDENCE);
}
else
setUpperDiagonalType(OffDiagonalType::NONE);
}
void
CQChartsCorrelationPlot::
lowerDiagonalTypeSlot(bool b)
{
if (b) {
auto name = qobject_cast<QAction *>(sender())->text();
if (name == "None" ) setLowerDiagonalType(OffDiagonalType::NONE);
else if (name == "Pie" ) setLowerDiagonalType(OffDiagonalType::PIE);
else if (name == "Shade" ) setLowerDiagonalType(OffDiagonalType::SHADE);
else if (name == "Ellipse" ) setLowerDiagonalType(OffDiagonalType::ELLIPSE);
else if (name == "Points" ) setLowerDiagonalType(OffDiagonalType::POINTS);
else if (name == "Confidence") setLowerDiagonalType(OffDiagonalType::CONFIDENCE);
}
else
setLowerDiagonalType(OffDiagonalType::NONE);
}
//---
CQChartsGeom::Range
CQChartsCorrelationPlot::
calcRange() const
{
Range dataRange;
// square (nc, nc)
int nc = std::max(correlationModel_->columnCount(), 1);
dataRange.updateRange(0.0, 0.0);
dataRange.updateRange(nc , nc );
//---
return dataRange;
}
//---
void
CQChartsCorrelationPlot::
preDrawObjs(PaintDevice *device) const
{
if (! isVisible())
return;
if (isCellLabelTextScaled()) {
bool first = true;
double maxWidth = 0.0, maxHeight = 0.0;
Size cellSize;
for (auto &plotObj : plotObjects()) {
auto *cellObj = dynamic_cast<CQChartsCorrelationCellObj *>(plotObj);
if (! cellObj) continue;
auto s = cellObj->calcTextSize();
maxWidth = std::max(maxWidth , s.width ());
maxHeight = std::max(maxHeight, s.height());
if (first) {
cellSize = cellObj->rect().size();
first = false;
}
}
auto cw = windowToPixelWidth (cellSize.width ());
auto ch = windowToPixelHeight(cellSize.height());
double xs = (maxWidth > 0.0 ? cw/maxWidth : 1.0);
double ys = (maxHeight > 0.0 ? ch/maxHeight : 1.0);
if (xs > 1.0 && ys > 1.0)
labelScale_ = std::max(xs, ys);
else
labelScale_ = std::min(xs, ys);
}
else {
labelScale_ = 1.0;
}
//---
CQChartsPlot::preDrawObjs(device);
}
//---
bool
CQChartsCorrelationPlot::
createObjs(PlotObjs &objs) const
{
CQPerfTrace trace("CQChartsCorrelationPlot::createObjs");
NoUpdate noUpdate(this);
//---
class RowVisitor : public CQModelVisitor {
public:
RowVisitor(const CQChartsCorrelationPlot *plot, PlotObjs &objs) :
plot_(plot), objs_(objs) {
nc_ = plot_->numColumns();
}
State visit(const QAbstractItemModel *model, const VisitData &data) override {
double y = (nc_ - 1 - data.row)*dy_;
for (int col = 0; col < numCols(); ++col) {
auto ind = model->index(data.row, col, data.parent);
bool ok;
double value = CQChartsModelUtil::modelReal(model, ind, ok);
if (! ok) value = 0.0;
//---
double x = col*dx_;
plot_->addCellObj(data.row, col, x, y, dx_, dy_, value, ind, objs_);
}
return State::OK;
}
private:
const CQChartsCorrelationPlot* plot_ { nullptr };
PlotObjs& objs_;
int nc_ { 0 };
double dx_ { 1.0 };
double dy_ { 1.0 };
};
RowVisitor visitor(this, objs);
CQModelVisit::exec(correlationModel_, visitor);
//---
return true;
}
void
CQChartsCorrelationPlot::
addCellObj(int row, int col, double x, double y, double dx, double dy, double value,
const QModelIndex &ind, PlotObjs &objs) const
{
BBox bbox(x, y, x + dx, y + dy);
auto *cellObj = createCellObj(bbox, row, col, value, ind);
objs.push_back(cellObj);
}
//---
bool
CQChartsCorrelationPlot::
probe(ProbeData &probeData) const
{
CQChartsPlotObj *obj;
if (! objNearestPoint(probeData.p, obj))
return false;
auto c = obj->rect().getCenter();
probeData.p = c;
probeData.both = true;
probeData.xvals.emplace_back(c.x, "", "");
probeData.yvals.emplace_back(c.y, "", "");
return true;
}
//---
bool
CQChartsCorrelationPlot::
addMenuItems(QMenu *menu)
{
menu->addSeparator();
//---
auto *labelsMenu = new QMenu("Labels", menu);
(void) addMenuCheckedAction(labelsMenu, "Cell", isCellLabels(), SLOT(setCellLabels(bool)));
(void) addMenuCheckedAction(labelsMenu, "X" , isXLabels (), SLOT(setXLabels (bool)));
(void) addMenuCheckedAction(labelsMenu, "Y" , isYLabels (), SLOT(setYLabels (bool)));
menu->addMenu(labelsMenu);
//---
auto isDiagonalType = [&](const DiagonalType &t) { return diagonalType() == t; };
auto *diagMenu = new QMenu("Diagonal", menu);
(void) addMenuCheckedAction(diagMenu, "None" , isDiagonalType(DiagonalType::NONE),
SLOT(diagonalTypeSlot(bool)));
(void) addMenuCheckedAction(diagMenu, "Name" , isDiagonalType(DiagonalType::NAME),
SLOT(diagonalTypeSlot(bool)));
(void) addMenuCheckedAction(diagMenu, "Min/Max", isDiagonalType(DiagonalType::MIN_MAX),
SLOT(diagonalTypeSlot(bool)));
(void) addMenuCheckedAction(diagMenu, "Density", isDiagonalType(DiagonalType::DENSITY),
SLOT(diagonalTypeSlot(bool)));
menu->addMenu(diagMenu);
//---
auto isUpperDiagonalType = [&](const OffDiagonalType &t) { return upperDiagonalType() == t; };
auto *udiagMenu = new QMenu("Upper Diagonal", menu);
(void) addMenuCheckedAction(udiagMenu, "None" ,
isUpperDiagonalType(OffDiagonalType::NONE), SLOT(upperDiagonalTypeSlot(bool)));
(void) addMenuCheckedAction(udiagMenu, "Pie" ,
isUpperDiagonalType(OffDiagonalType::PIE), SLOT(upperDiagonalTypeSlot(bool)));
(void) addMenuCheckedAction(udiagMenu, "Shade" ,
isUpperDiagonalType(OffDiagonalType::SHADE), SLOT(upperDiagonalTypeSlot(bool)));
(void) addMenuCheckedAction(udiagMenu, "Ellipse" ,
isUpperDiagonalType(OffDiagonalType::ELLIPSE), SLOT(upperDiagonalTypeSlot(bool)));
(void) addMenuCheckedAction(udiagMenu, "Points" ,
isUpperDiagonalType(OffDiagonalType::POINTS), SLOT(upperDiagonalTypeSlot(bool)));
(void) addMenuCheckedAction(udiagMenu, "Confidence",
isUpperDiagonalType(OffDiagonalType::CONFIDENCE), SLOT(upperDiagonalTypeSlot(bool)));
menu->addMenu(udiagMenu);
//---
auto isLowerDiagonalType = [&](const OffDiagonalType &t) { return lowerDiagonalType() == t; };
auto *ldiagMenu = new QMenu("Lower Diagonal", menu);
(void) addMenuCheckedAction(ldiagMenu, "None" ,
isLowerDiagonalType(OffDiagonalType::NONE), SLOT(lowerDiagonalTypeSlot(bool)));
(void) addMenuCheckedAction(ldiagMenu, "Pie" ,
isLowerDiagonalType(OffDiagonalType::PIE), SLOT(lowerDiagonalTypeSlot(bool)));
(void) addMenuCheckedAction(ldiagMenu, "Shade" ,
isLowerDiagonalType(OffDiagonalType::SHADE), SLOT(lowerDiagonalTypeSlot(bool)));
(void) addMenuCheckedAction(ldiagMenu, "Ellipse" ,
isLowerDiagonalType(OffDiagonalType::ELLIPSE), SLOT(lowerDiagonalTypeSlot(bool)));
(void) addMenuCheckedAction(ldiagMenu, "Points" ,
isLowerDiagonalType(OffDiagonalType::POINTS), SLOT(lowerDiagonalTypeSlot(bool)));
(void) addMenuCheckedAction(ldiagMenu, "Confidence",
isLowerDiagonalType(OffDiagonalType::CONFIDENCE), SLOT(lowerDiagonalTypeSlot(bool)));
menu->addMenu(ldiagMenu);
return true;
}
//------
bool
CQChartsCorrelationPlot::
hasForeground() const
{
if (! isXLabels() && ! isYLabels())
return false;
return isLayerActive(CQChartsLayer::Type::FOREGROUND);
}
void
CQChartsCorrelationPlot::
execDrawForeground(PaintDevice *device) const
{
if (isXLabels())
drawXLabels(device);
if (isYLabels())
drawYLabels(device);
}
void
CQChartsCorrelationPlot::
drawXLabels(PaintDevice *device) const
{
setPainterFont(device, xLabelTextFont());
//---
PenBrush tpenBrush;
auto tc = interpXLabelTextColor(ColorInd());
setPen(tpenBrush, PenData(true, tc, xLabelTextAlpha()));
device->setPen(tpenBrush.pen);
//---
auto textOptions = xLabelTextOptions(device);
textOptions.clipped = false;
textOptions = adjustTextOptions(textOptions);
//---
using ColRects = std::map<int, BBox>;
ColRects colRects;
double tw = 0.0;
double th = 0.0;
int nc = numColumns();
for (int c = 0; c < nc; ++c) {
Column col(c);
bool ok;
auto name = CQChartsModelUtil::modelHHeaderString(correlationModel_, col, Qt::DisplayRole, ok);
if (! name.length()) continue;
double px = 0.0;
double py = 0.0;
auto trect = CQChartsRotatedText::calcBBox(px, py, name, device->font(),
textOptions, 0, /*alignBBox*/ true);
colRects[c] = trect;
tw = std::max(tw, trect.getWidth ());
th = std::max(th, trect.getHeight());
}
//---
auto cw = windowToPixelWidth(1.0);
double tm = 4;
for (int c = 0; c < nc; ++c) {
Column col(c);
bool ok;
auto name = CQChartsModelUtil::modelHHeaderString(correlationModel_, col, Qt::DisplayRole, ok);
if (! name.length()) continue;
Point p(c + 0.5, 0);
auto p1 = windowToPixel(p);
auto trect = colRects[c];
double tw1 = std::max(trect.getWidth(), cw);
BBox tbbox1;
if (! isInvertY())
tbbox1 = BBox(p1.x - tw1/2, p1.y + tm, p1.x + tw1/2, p1.y + tm + th);
else
tbbox1 = BBox(p1.x - tw1/2, p1.y - th - tm, p1.x + tw1/2, p1.y - tm);
CQChartsDrawUtil::drawTextInBox(device, pixelToWindow(tbbox1), name, textOptions);
}
}
void
CQChartsCorrelationPlot::
drawYLabels(PaintDevice *device) const
{
setPainterFont(device, yLabelTextFont());
//---
PenBrush tpenBrush;
auto tc = interpYLabelTextColor(ColorInd());
setPen(tpenBrush, PenData(true, tc, yLabelTextAlpha()));
device->setPen(tpenBrush.pen);
//---
auto textOptions = yLabelTextOptions(device);
textOptions.clipped = false;
textOptions = adjustTextOptions(textOptions);
//---
using RowRects = std::map<int, BBox>;
RowRects colRects;
double tw = 0.0;
double th = 0.0;
int nc = numColumns();
for (int c = 0; c < nc; ++c) {
Column col(c);
bool ok;
auto name = CQChartsModelUtil::modelHHeaderString(correlationModel_, col, Qt::DisplayRole, ok);
if (! name.length()) continue;
double px = 0.0;
double py = 0.0;
auto trect = CQChartsRotatedText::calcBBox(px, py, name, device->font(),
textOptions, 0, /*alignBBox*/ true);
colRects[c] = trect;
tw = std::max(tw, trect.getWidth ());
th = std::max(th, trect.getHeight());
}
//---
auto ch = windowToPixelHeight(1.0);
double tm = 4;
for (int c = 0; c < nc; ++c) {
Column col(c);
bool ok;
auto name = CQChartsModelUtil::modelHHeaderString(correlationModel_, col, Qt::DisplayRole, ok);
if (! name.length()) continue;
Point p(0, (nc - 1 - c) + 0.5);
auto p1 = windowToPixel(p);
auto trect = colRects[c];
double th1 = std::max(trect.getHeight(), ch);
BBox tbbox1;
if (! isInvertX())
tbbox1 = BBox(p1.x - tw - tm, p1.y - th1/2, p1.x - tm, p1.y + th1/2);
else
tbbox1 = BBox(p1.x + tm, p1.y - th1/2, p1.x + tm + tw, p1.y + th1/2);
CQChartsDrawUtil::drawTextInBox(device, pixelToWindow(tbbox1), name, textOptions);
}
}
//------
CQChartsGeom::BBox
CQChartsCorrelationPlot::
calcExtraFitBBox() const
{
CQPerfTrace trace("CQChartsCorrelationPlot::calcExtraFitBBox");
auto xfont = view()->plotFont(this, xLabelTextFont());
auto yfont = view()->plotFont(this, yLabelTextFont());
BBox bbox;
double tm = 4;
int nc = numColumns();
//---
if (isXLabels()) {
double th = 0.0;
for (int c = 0; c < nc; ++c) {
Column col(c);
bool ok;
auto name = CQChartsModelUtil::modelHHeaderString(correlationModel_, col,
Qt::DisplayRole, ok);
if (! name.length()) continue;
CQChartsTextOptions options;
options.angle = xLabelTextAngle();
options.align = xLabelTextAlign();
double px = 0.0;
double py = 0.0;
auto trect = CQChartsRotatedText::calcBBox(px, py, name, xfont,
options, 0, /*alignBBox*/ true);
th = std::max(th, trect.getHeight());
}
double th1 = pixelToWindowHeight(th + tm);
BBox tbbox(0, -th1, nc, 0);
bbox += tbbox;
}
//---
if (isYLabels()) {
double tw = 0.0;
for (int c = 0; c < nc; ++c) {
Column col(c);
bool ok;
auto name = CQChartsModelUtil::modelHHeaderString(correlationModel_, col,
Qt::DisplayRole, ok);
if (! name.length()) continue;
CQChartsTextOptions options;
options.angle = yLabelTextAngle();
options.align = yLabelTextAlign();
double px = 0.0;
double py = 0.0;
auto trect = CQChartsRotatedText::calcBBox(px, py, name, yfont,
options, 0, /*alignBBox*/ true);
tw = std::max(tw, trect.getWidth());
}
double tw1 = pixelToWindowWidth(tw + tm);
BBox tbbox(-tw1, 0, 0, nc);
bbox += tbbox;
}
//---
return bbox;
}
//---
CQChartsCorrelationCellObj *
CQChartsCorrelationPlot::
createCellObj(const BBox &rect, int row, int col, double value, const QModelIndex &ind) const
{
return new CQChartsCorrelationCellObj(this, rect, row, col, value, ind);
}
//---
CQChartsPlotCustomControls *
CQChartsCorrelationPlot::
createCustomControls()
{
auto *controls = new CQChartsCorrelationPlotCustomControls(charts());
controls->init();
controls->setPlot(this);
controls->updateWidgets();
return controls;
}
//------
CQChartsCorrelationCellObj::
CQChartsCorrelationCellObj(const CQChartsCorrelationPlot *plot, const BBox &rect,
int row, int col, double value, const QModelIndex &ind) :
CQChartsPlotObj(const_cast<CQChartsCorrelationPlot *>(plot), rect),
plot_(plot), row_(row), col_(col), value_(value)
{
setDetailHint(DetailHint::MAJOR);
valueColorInd(iv_);
if (ind.isValid()) {
//setModelInd(ind);
}
}
QString
CQChartsCorrelationCellObj::
calcId() const
{
return QString("%1:%2:%3").arg(typeName()).arg(row_).arg(col_);
}
QString
CQChartsCorrelationCellObj::
calcTipId() const
{
CQChartsTableTip tableTip;
bool ok;
if (row_ != col_) {
auto xname = CQChartsModelUtil::modelHHeaderString(plot_->correlationModel(),
CQChartsColumn(row_), Qt::DisplayRole, ok);
auto yname = CQChartsModelUtil::modelHHeaderString(plot_->correlationModel(),
CQChartsColumn(col_), Qt::DisplayRole, ok);
if (xname.length())
tableTip.addTableRow("X", xname);
if (yname.length())
tableTip.addTableRow("Y", yname);
tableTip.addTableRow("Value", value());
}
else {
auto xname = CQChartsModelUtil::modelHHeaderString(plot_->correlationModel(),
CQChartsColumn(row_), Qt::DisplayRole, ok);
if (xname.length())
tableTip.addTableRow("Name", xname);
const auto &minMax = plot_->baseModel()->minMax(row_);
tableTip.addTableRow("Min", minMax.min());
tableTip.addTableRow("Max", minMax.max());
}
//---
plot()->addTipColumns(tableTip, modelInd());
//---
return tableTip.str();
}
void
CQChartsCorrelationCellObj::
getObjSelectIndices(Indices &inds) const
{
addColumnSelectIndex(inds, CQChartsColumn(modelInd().column()));
}
CQChartsGeom::Size
CQChartsCorrelationCellObj::
calcTextSize() const
{
if (! plot_->isCellLabels())
return Size();
auto font = plot_->view()->plotFont(plot_, plot_->cellLabelTextFont());
auto valueStr = CQChartsUtil::formatReal(value());
auto textOptions = plot_->cellLabelTextOptions();
textOptions.align = Qt::AlignHCenter | Qt::AlignVCenter; // TODO: allow config
textOptions.scaled = false; // TODO: allow config
return CQChartsDrawUtil::calcTextSize(valueStr, font, textOptions);
}
void
CQChartsCorrelationCellObj::
draw(PaintDevice *device) const
{
// calc pen and brush
PenBrush penBrush;
bool updateState = device->isInteractive();
calcPenBrush(penBrush, updateState);
//---
device->setColorNames();
//---
bool skipLabel = false;
CQChartsDrawUtil::setPenBrush(device, penBrush);
// diagonal
if (row_ == col_) {
auto type = plot_->diagonalType();
if (type == CQChartsCorrelationPlot::DiagonalType::NAME) {
bool ok;
auto xname = CQChartsModelUtil::modelHHeaderString(plot_->correlationModel(),
CQChartsColumn(row_), Qt::DisplayRole, ok);
if (xname.length())
drawCellLabel(device, xname);
skipLabel = true;
}
else if (type == CQChartsCorrelationPlot::DiagonalType::MIN_MAX) {
const auto &minMax = plot_->baseModel()->minMax(row_);
double x1 = rect().getXMin();
double x2 = rect().getXMax();
double y1 = rect().getYMin();
double y2 = rect().getYMax();
double w = rect().getWidth ();
double h = rect().getHeight();
BBox rect1(x1, y1, x1 + w/2.0, y1 + h/2.0);
BBox rect2(x2 - w/2.0, y2 - h/2.0, x2, y2);
drawCellLabel(device, QString::number(minMax.min()), rect1, -4);
drawCellLabel(device, QString::number(minMax.max()), rect2, -4);
//---
bool ok;
auto xname = CQChartsModelUtil::modelHHeaderString(plot_->correlationModel(),
CQChartsColumn(row_), Qt::DisplayRole, ok);
if (xname.length())
drawCellLabel(device, xname);
//---
skipLabel = true;
}
else if (type == CQChartsCorrelationPlot::DiagonalType::DENSITY) {
const auto *density = plot_->baseModel()->density(row_);
double s = rect().getMinSize()/2.0;
auto rc = rect().getCenter();
auto ps = Point(s, s);
BBox rect1(rc - ps, rc + ps);
//---
Polygon poly;
CQChartsWhiskerOpts opts;
opts.fitTail = true;
density->calcDistributionPoly(poly, plot(), rect1, Qt::Horizontal, opts);
device->drawPolygon(poly);
}
else {
device->drawRect(rect());
}
}
// upper/lower diagonal
else {
bool isLower = (row_ > col_);
auto type = (isLower ? plot_->lowerDiagonalType() : plot_->upperDiagonalType());
if (type == CQChartsCorrelationPlot::OffDiagonalType::PIE) {
Angle a1, a2;
a1 = Angle(90);
a2 = a1 - Angle(360.0*value());
auto rc = rect().getCenter();
double s = rect().getMinSize()/2.0;
auto ps = Point(s, s);
BBox rect1(rc - ps, rc + ps);
auto penBrush1 = penBrush;
plot_->setBrush(penBrush1, BrushData(false));
CQChartsDrawUtil::setPenBrush(device, penBrush1);
device->drawEllipse(rect1);
CQChartsDrawUtil::setPenBrush(device, penBrush);
CQChartsDrawUtil::drawPieSlice(device, rc, 0.0, s, a1, a2);
}
else if (type == CQChartsCorrelationPlot::OffDiagonalType::SHADE) {
device->drawRect(rect());
//---
auto lc = Qt::white;
auto fillPattern = CQChartsFillPattern::makeSolid();
if (value() > 0)
fillPattern = CQChartsFillPattern(CQChartsFillPattern::Type::FDIAG);
else if (value() < 0)
fillPattern = CQChartsFillPattern(CQChartsFillPattern::Type::BDIAG);
fillPattern.setScale(4.0);
plot_->setPenBrush(penBrush,
PenData (true, lc, Alpha()),
BrushData(true, lc, Alpha(), fillPattern));
CQChartsDrawUtil::setPenBrush(device, penBrush);
device->drawRect(rect());
}
else if (type == CQChartsCorrelationPlot::OffDiagonalType::ELLIPSE) {
const auto &rminMax = plot_->baseModel()->minMax(row_);
const auto &cminMax = plot_->baseModel()->minMax(col_);
const auto &bestFit = plot_->baseModel()->bestFit(row_, col_);
double xdev, ydev;
plot_->baseModel()->devData(row_, col_, xdev, ydev);
double rmin = rminMax.min();
double rmax = rminMax.max();
double cmin = cminMax.min();
double cmax = cminMax.max();
double s = rect().getMinSize()/2.0;
//---
// draw devation ellipse ???
double dx1 = CMathUtil::map(xdev, 0, (rmax - rmin)/2.0, 0, s);
double dy1 = CMathUtil::map(ydev, 0, (cmax - cmin)/2.0, 0, s);
BBox ebbox(Point(rect().getXMid() - dx1, rect().getYMid() - dy1),
Point(rect().getXMid() + dx1, rect().getYMid() + dy1));
device->drawEllipse(ebbox, Angle(45));
//---
// draw fit (calc fit shape at each pixel)
auto prect = plot()->windowToPixel(rect());
double dx = std::max(prect.getWidth()/100, 1.0);
Polygon poly;
for (double px = prect.getXMin(); px <= prect.getXMax(); px += dx) {
double px1 = CMathUtil::map(px, prect.getXMin(), prect.getXMax(), rmin, rmax);
double px2 = CMathUtil::map(px, prect.getXMin(), prect.getXMax(), -s, s);
double py1 = bestFit.interp(px1);
double py2 = CMathUtil::map(py1, cmin, cmax, -s, s);
poly.addPoint(Point(rect().getXMid() + px2, rect().getYMid() + py2));
}
auto path = CQChartsDrawUtil::polygonToPath(poly, /*closed*/false);
device->strokePath(path, penBrush.pen);
}
else if (type == CQChartsCorrelationPlot::OffDiagonalType::POINTS) {
const auto &rminMax = plot_->baseModel()->minMax(row_);
const auto &cminMax = plot_->baseModel()->minMax(col_);
const auto &points = plot_->baseModel()->points(row_, col_);
double rmin = rminMax.min();
double rmax = rminMax.max();
double cmin = cminMax.min();
double cmax = cminMax.max();
double sx = plot()->pixelToWindowWidth (3);
double sy = plot()->pixelToWindowHeight(3);
double s = rect().getMinSize()/2.0 - std::min(sx, sy);
auto ss = CQChartsLength::pixel(3);
//---
// draw row/col points
for (const auto &p : points) {
double x1 = rect().getXMid() + CMathUtil::map(p.x, rmin, rmax, -s, s);
double y1 = rect().getYMid() + CMathUtil::map(p.y, cmin, cmax, -s, s);
Point ps(x1, y1);
auto symbol = Symbol::circle();
CQChartsDrawUtil::drawSymbol(device, penBrush, symbol, ps, ss);
}
skipLabel = true;
}
else if (type == CQChartsCorrelationPlot::OffDiagonalType::CONFIDENCE) {
}
else if (type == CQChartsCorrelationPlot::OffDiagonalType::NONE) {
skipLabel = true;
}
}
//---
if (plot_->isCellLabels() && ! skipLabel) {
auto valueStr = CQChartsUtil::formatReal(value());
drawCellLabel(device, valueStr);
}
//---
device->resetColorNames();
}
void
CQChartsCorrelationCellObj::
drawCellLabel(PaintDevice *device, const QString &str) const
{
drawCellLabel(device, str, rect());
}
void
CQChartsCorrelationCellObj::
drawCellLabel(PaintDevice *device, const QString &str, const BBox &rect, double fontInc) const
{
// calc pen and brush
ColorInd ic;
valueColorInd(ic);
//---
// set font
auto font = plot_->cellLabelTextFont();
if (fontInc != 0.0)
font.incFontSize(fontInc);
plot_->setPainterFont(device, font);
//---
// set pen
PenBrush tPenBrush;
auto tc = plot_->interpCellLabelTextColor(ic);
plot_->setPen(tPenBrush, PenData(true, tc, plot_->cellLabelTextAlpha()));
plot_->updateObjPenBrushState(this, tPenBrush);
device->setPen(tPenBrush.pen);
//---
auto textOptions = plot_->cellLabelTextOptions(device);
textOptions.scale = plot_->labelScale(); // TODO: optional
textOptions = plot_->adjustTextOptions(textOptions);
CQChartsDrawUtil::drawTextInBox(device, rect, str, textOptions);
}
void
CQChartsCorrelationCellObj::
calcPenBrush(PenBrush &penBrush, bool updateState) const
{
// calc pen and brush
ColorInd ic;
valueColorInd(ic);
//---
// set pen and brush
auto fc = plot_->interpCellFillColor (ic);
auto bc = plot_->interpCellStrokeColor(ic);
plot_->setPenBrush(penBrush, plot_->cellPenData(bc), plot_->cellBrushData(fc));
if (updateState)
plot_->updateObjPenBrushState(this, penBrush);
}
void
CQChartsCorrelationCellObj::
valueColorInd(ColorInd &ic) const
{
ic = ColorInd(std::abs(value()));
}
void
CQChartsCorrelationCellObj::
writeScriptData(ScriptPaintDevice *device) const
{
calcPenBrush(penBrush_, /*updateState*/ false);
CQChartsPlotObj::writeScriptData(device);
std::ostream &os = device->os();
os << "\n";
os << " this.value = " << value() << ";\n";
}
double
CQChartsCorrelationCellObj::
xColorValue(bool) const
{
return col_;
}
double
CQChartsCorrelationCellObj::
yColorValue(bool) const
{
return col_;
}
//------
CQChartsCorrelationPlotCustomControls::
CQChartsCorrelationPlotCustomControls(CQCharts *charts) :
CQChartsPlotCustomControls(charts, "correlation")
{
}
void
CQChartsCorrelationPlotCustomControls::
init()
{
addWidgets();
addLayoutStretch();
connectSlots(true);
}
void
CQChartsCorrelationPlotCustomControls::
addWidgets()
{
// options group
auto optionsFrame = createGroupFrame("Options", "optionsFrame");
diagonalTypeCombo_ = createEnumEdit("diagonalType");
upperDiagonalTypeCombo_ = createEnumEdit("upperDiagonalType");
lowerDiagonalTypeCombo_ = createEnumEdit("lowerDiagonalType");
addFrameWidget(optionsFrame, "Diagonal Type" , diagonalTypeCombo_);
addFrameWidget(optionsFrame, "Upper Cell Type", upperDiagonalTypeCombo_);
addFrameWidget(optionsFrame, "Lower Cell Type", lowerDiagonalTypeCombo_);
}
void
CQChartsCorrelationPlotCustomControls::
connectSlots(bool b)
{
CQChartsWidgetUtil::connectDisconnect(b,
diagonalTypeCombo_, SIGNAL(currentIndexChanged(int)), this, SLOT(diagonalTypeSlot()));
CQChartsWidgetUtil::connectDisconnect(b,
upperDiagonalTypeCombo_, SIGNAL(currentIndexChanged(int)), this, SLOT(upperDiagonalTypeSlot()));
CQChartsWidgetUtil::connectDisconnect(b,
lowerDiagonalTypeCombo_, SIGNAL(currentIndexChanged(int)), this, SLOT(lowerDiagonalTypeSlot()));
CQChartsPlotCustomControls::connectSlots(b);
}
void
CQChartsCorrelationPlotCustomControls::
setPlot(CQChartsPlot *plot)
{
plot_ = dynamic_cast<CQChartsCorrelationPlot *>(plot);
CQChartsPlotCustomControls::setPlot(plot);
}
void
CQChartsCorrelationPlotCustomControls::
updateWidgets()
{
connectSlots(false);
//---
diagonalTypeCombo_ ->setCurrentValue((int) plot_->diagonalType());
upperDiagonalTypeCombo_->setCurrentValue((int) plot_->upperDiagonalType());
lowerDiagonalTypeCombo_->setCurrentValue((int) plot_->lowerDiagonalType());
CQChartsPlotCustomControls::updateWidgets();
//---
connectSlots(true);
}
void
CQChartsCorrelationPlotCustomControls::
diagonalTypeSlot()
{
plot_->setDiagonalType((CQChartsCorrelationPlot::DiagonalType)
diagonalTypeCombo_->currentValue());
updateWidgets();
}
void
CQChartsCorrelationPlotCustomControls::
upperDiagonalTypeSlot()
{
plot_->setUpperDiagonalType((CQChartsCorrelationPlot::OffDiagonalType)
upperDiagonalTypeCombo_->currentValue());
updateWidgets();
}
void
CQChartsCorrelationPlotCustomControls::
lowerDiagonalTypeSlot()
{
plot_->setLowerDiagonalType((CQChartsCorrelationPlot::OffDiagonalType)
lowerDiagonalTypeCombo_->currentValue());
updateWidgets();
}
| 25.046709 | 100 | 0.65624 | [
"shape",
"model"
] |
bb5beadbc103f2eda08cde9147657b9b7335b43a | 4,754 | hpp | C++ | src/image_management/image/template/image_basic.hpp | Neckrome/vectorFieldSurface | 91afebadf9815e6a2dc658cdce82691fddd603ee | [
"MIT"
] | null | null | null | src/image_management/image/template/image_basic.hpp | Neckrome/vectorFieldSurface | 91afebadf9815e6a2dc658cdce82691fddd603ee | [
"MIT"
] | null | null | null | src/image_management/image/template/image_basic.hpp | Neckrome/vectorFieldSurface | 91afebadf9815e6a2dc658cdce82691fddd603ee | [
"MIT"
] | null | null | null | /*
** TP CPE Lyon
** Copyright (C) 2015 Damien Rohmer
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef IMAGE_BASIC_HPP
#define IMAGE_BASIC_HPP
#include <iostream>
#include <vector>
namespace cpe
{
class ivec2;
/** Container for picture data storing generic values (color, depth, ...) . */
template <typename VALUE>
class image_basic
{
public:
// ********************************************* //
// ********************************************* //
// CONSTRUCTORS
// ********************************************* //
// ********************************************* //
/** Empty constructor */
image_basic();
/** \brief create square picture of size NxN
\param unsigned int N: size (width & height) of the picture
*/
image_basic(int N);
/** \brief create picture of size Nx x Ny
\param unsigned int Nx: picture width
\param unsigned int Ny: picture height
*/
image_basic(int Nx,int Ny);
// ********************************************* //
// ********************************************* //
// Picture Size
// ********************************************* //
// ********************************************* //
/** Get the picture width in pixel */
int Nx() const;
/** Get the picture height in pixel */
int Ny() const;
/** Get the full size Nx x Ny of the image */
int size() const;
// ********************************************* //
// ********************************************* //
// Pixel access
// ********************************************* //
// ********************************************* //
/** Access the value at a given offset */
VALUE const& operator[](int offset) const;
/** Access/set the value at a given offset */
VALUE& operator[](int offset);
/** Accessor on a pixel at a given (kx,ky) */
VALUE const& operator()(int x,int y) const;
/** Accessor on a pixel at a given (kx,ky) */
VALUE const& operator()(ivec2 const& index) const;
/** Accessor on a pixel at a given (kx,ky) */
VALUE& operator()(int x,int y);
/** Accessor on a pixel at a given (kx,ky) */
VALUE& operator()(ivec2 const& index);
// ********************************************* //
// ********************************************* //
// Special pixel filling
// ********************************************* //
// ********************************************* //
/** Fill the entire picture with a given value */
void fill(VALUE const& value);
/** STL compatible ranged-for loop */
typename std::vector<VALUE>::iterator begin();
/** STL compatible ranged-for loop */
typename std::vector<VALUE>::iterator end();
/** STL compatible ranged-for loop */
typename std::vector<VALUE>::const_iterator begin() const;
/** STL compatible ranged-for loop */
typename std::vector<VALUE>::const_iterator bend() const;
/** STL compatible ranged-for loop */
typename std::vector<VALUE>::const_iterator cbegin() const;
/** STL compatible ranged-for loop */
typename std::vector<VALUE>::const_iterator cbend() const;
private:
// ********************************************* //
// ********************************************* //
// Internal data
// ********************************************* //
// ********************************************* //
/** Internal data storage as std::vector of unsigned char
Picture is stored as (color_0 , color_1 , ...) vector size is therefore 3 Nx Ny
*/
std::vector<VALUE> data;
/** Storage of picture width */
int Nx_data;
/** Storage of picture height */
int Ny_data;
};
}
#include "image_basic.tpp"
#endif
| 31.276316 | 91 | 0.452251 | [
"vector"
] |
bb6198741b71e694fe84a63be582a79730a54252 | 639 | cpp | C++ | src/huntersmanager.cpp | fengjixuchui/memhunter | 3f85e66d5d4cf83bd7b5d0d457a8e62c746ba703 | [
"MIT"
] | 354 | 2018-08-13T18:19:21.000Z | 2022-03-20T10:37:20.000Z | src/huntersmanager.cpp | ZhuHuiBeiShaDiao/memhunter | 37ce1488fa041199cc8761e473947affc3286b7b | [
"MIT"
] | 3 | 2019-09-27T11:33:52.000Z | 2020-04-21T17:15:28.000Z | src/huntersmanager.cpp | ZhuHuiBeiShaDiao/memhunter | 37ce1488fa041199cc8761e473947affc3286b7b | [
"MIT"
] | 90 | 2018-11-15T12:37:51.000Z | 2022-02-14T11:12:39.000Z | #include "common.h"
//TODO: Add threading support
bool HuntersManager::RunHunters(HunterCommon::ProcessCollection &processesToAnalyze, const UINT32 nrThreads)
{
bool ret = false;
if ((!processesToAnalyze.empty()) && (nrThreads > 0))
{
for (std::vector<CustomTypes::HunterPtr>::const_iterator hunterIt = m_hunters.begin();
hunterIt != m_hunters.end();
++hunterIt)
{
if (*hunterIt != nullptr)
{
CustomTypes::HunterPtr hunter = *hunterIt;
if (ConfigManager::GetInstance().IsHunterEnabled(hunter->GetHunterID()))
{
hunter->Execute(processesToAnalyze);
}
ret = true;
}
}
}
return ret;
}
| 20.612903 | 108 | 0.674491 | [
"vector"
] |
bb62e80ed10b6d8e897369e7f572d427901c7ff5 | 323 | cpp | C++ | electives/amh/lab/l1/z1/griewank.cpp | jerry-sky/academic-notebook | be2d350289441b99168ea40412891bc65b9cb431 | [
"Unlicense"
] | 4 | 2020-12-28T21:53:00.000Z | 2022-03-22T19:24:47.000Z | electives/amh/lab/l1/z1/griewank.cpp | jerry-sky/academic-notebook | be2d350289441b99168ea40412891bc65b9cb431 | [
"Unlicense"
] | 3 | 2022-02-13T18:07:10.000Z | 2022-02-13T18:16:07.000Z | electives/amh/lab/l1/z1/griewank.cpp | jerry-sky/academic-notebook | be2d350289441b99168ea40412891bc65b9cb431 | [
"Unlicense"
] | 4 | 2020-12-28T16:05:35.000Z | 2022-03-08T16:20:00.000Z | #include "griewank.h"
double Griewank(std::vector<double> x)
{
double output = 0;
for (int i = 0; i < 4; i++)
{
output += pow(x[i], 2) * 1.0;
}
output /= 4000;
output += 1;
double tmp = 1;
for (int i = 0; i < 4; i++)
{
tmp *= cos(x[i] / sqrt(i + 1));
}
output -= tmp;
return output;
}
| 12.92 | 38 | 0.486068 | [
"vector"
] |
bb662d170a15897bb86503a3f2a31bb4435ce781 | 1,668 | cpp | C++ | StarEngine/jni/Actions/DelayedAction.cpp | madhubandubey9/StarEngine | 1d0adcf8cfd50bc223be6f333c4f2a0af5260b27 | [
"MIT"
] | 455 | 2015-02-04T01:39:12.000Z | 2022-03-18T17:28:34.000Z | StarEngine/jni/Actions/DelayedAction.cpp | madhubandubey9/StarEngine | 1d0adcf8cfd50bc223be6f333c4f2a0af5260b27 | [
"MIT"
] | 1 | 2016-12-25T09:14:12.000Z | 2016-12-25T14:48:27.000Z | StarEngine/jni/Actions/DelayedAction.cpp | madhubandubey9/StarEngine | 1d0adcf8cfd50bc223be6f333c4f2a0af5260b27 | [
"MIT"
] | 117 | 2015-01-30T10:13:54.000Z | 2022-03-08T03:46:42.000Z | #include "DelayedAction.h"
#include "../Helpers/Helpers.h"
#include "../Objects/Object.h"
#include "../Scenes/BaseScene.h"
namespace star
{
uint64 DelayedAction::ID_COUNTER = 0;
DelayedAction::DelayedAction(float32 seconds)
: Action()
, m_UniqueID(_T("DA_"))
, m_Seconds(seconds)
, m_Callback(nullptr)
, m_HasStarted(false)
{
m_UniqueID += string_cast<tstring>(ID_COUNTER++);
}
DelayedAction::DelayedAction(
const tstring & name,
float32 seconds
)
: Action(name)
, m_UniqueID(_T("DA_"))
, m_Seconds(seconds)
, m_Callback(nullptr)
, m_HasStarted(false)
{
m_UniqueID += string_cast<tstring>(ID_COUNTER++);
}
DelayedAction::~DelayedAction()
{
}
void DelayedAction::Initialize()
{
CreateTimer();
}
void DelayedAction::Restart()
{
if(!m_HasStarted)
{
m_pParent->GetScene()->GetTimerManager()->ResetTimer(
m_UniqueID,
false
);
}
else
{
m_HasStarted = false;
CreateTimer();
}
}
void DelayedAction::Pause()
{
if(!m_HasStarted)
{
m_pParent->GetScene()->GetTimerManager()->PauseTimer(
m_UniqueID,
true
);
}
}
void DelayedAction::Resume()
{
if(!m_HasStarted)
{
m_pParent->GetScene()->GetTimerManager()->PauseTimer(
m_UniqueID,
false
);
}
}
void DelayedAction::CreateTimer()
{
m_IsPaused = true;
m_pParent->GetScene()->GetTimerManager()->CreateTimer(
m_UniqueID, m_Seconds, false, false,
[&] () {
if(m_Callback)
{
m_Callback();
m_IsPaused = false;
m_HasStarted = true;
}
Destroy();
}, false);
}
}
| 17.195876 | 57 | 0.601918 | [
"object"
] |
bb85873d733abcd3f14a3db739cfdf7d0f36f0a7 | 6,107 | cpp | C++ | bipedenv/cpp/Render/MyGLFWwindow.cpp | snumrl/DistributedDeepMimic | 364d07dbdd5378b6d46d944e472e1632712ef5f6 | [
"MIT"
] | null | null | null | bipedenv/cpp/Render/MyGLFWwindow.cpp | snumrl/DistributedDeepMimic | 364d07dbdd5378b6d46d944e472e1632712ef5f6 | [
"MIT"
] | null | null | null | bipedenv/cpp/Render/MyGLFWwindow.cpp | snumrl/DistributedDeepMimic | 364d07dbdd5378b6d46d944e472e1632712ef5f6 | [
"MIT"
] | null | null | null | #include "Render/MyGLFWwindow.h"
#include "Render/GLFWMain.h"
static void initLights(double x = 0, double z = 0, double fx = 0, double fz = 0){
static float ambient[] = {0.02, 0.02, 0.02, 1.0};
static float diffuse[] = {.1, .1, .1, 1.0};
// static float ambient0[] = {.01, .01, .01, 1.0};
// static float diffuse0[] = {.2, .2, .2, 1.0};
// static float specular0[] = {.1, .1, .1, 1.0};
static float ambient0[] = {.15, .15, .15, 1.0};
static float diffuse0[] = {.2, .2, .2, 1.0};
static float specular0[] = {.1, .1, .1, 1.0};
static float spot_direction0[] = {0.0, -1.0, 0.0};
static float ambient1[] = {.02, .02, .02, 1.0};
static float diffuse1[] = {.01, .01, .01, 1.0};
static float specular1[] = {.01, .01, .01, 1.0};
static float ambient2[] = {.01, .01, .01, 1.0};
static float diffuse2[] = {.17, .17, .17, 1.0};
static float specular2[] = {.1, .1, .1, 1.0};
static float ambient3[] = {.06, .06, .06, 1.0};
static float diffuse3[] = {.15, .15, .15, 1.0};
static float specular3[] = {.1, .1, .1, 1.0};
static float front_mat_shininess[] = {24.0};
static float front_mat_specular[] = {0.2, 0.2, 0.2, 1.0};
static float front_mat_diffuse[] = {0.2, 0.2, 0.2, 1.0};
static float lmodel_ambient[] = {0.2, 0.2, 0.2, 1.0};
static float lmodel_twoside[] = {GL_TRUE};
GLfloat position0[] = {0.0, 3.0, 0.0, 1.0};
position0[0] = x;
position0[2] = z;
GLfloat position1[] = {0.0, 1.0, -1.0, 0.0};
GLfloat position2[] = {0.0, 5.0, 0.0, 1.0};
position2[0] = x;
position2[2] = z;
GLfloat position3[] = {0.0, 1.3, 0.0, 1.0};
position3[0] = fx;
position3[2] = fz;
// glClear(GL_COLOR_BUFFER_BIT);
// glEnable(GL_LIGHT0);
// glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
// glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
// glLightfv(GL_LIGHT0, GL_POSITION, position);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, ambient0);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse0);
glLightfv(GL_LIGHT0, GL_SPECULAR, specular0);
glLightfv(GL_LIGHT0, GL_POSITION, position0);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spot_direction0);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 30.0);
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 2.0);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 1.0);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 1.0);
glEnable(GL_LIGHT1);
glLightfv(GL_LIGHT1, GL_AMBIENT, ambient1);
glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse1);
glLightfv(GL_LIGHT1, GL_SPECULAR, specular1);
glLightfv(GL_LIGHT1, GL_POSITION, position1);
glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION, 2.0);
glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, 1.0);
glLightf(GL_LIGHT1, GL_QUADRATIC_ATTENUATION, 1.0);
glEnable(GL_LIGHT2);
glLightfv(GL_LIGHT2, GL_AMBIENT, ambient2);
glLightfv(GL_LIGHT2, GL_DIFFUSE, diffuse2);
glLightfv(GL_LIGHT2, GL_SPECULAR, specular2);
glLightfv(GL_LIGHT2, GL_POSITION, position2);
glLightf(GL_LIGHT2, GL_CONSTANT_ATTENUATION, 2.0);
glLightf(GL_LIGHT2, GL_LINEAR_ATTENUATION, 1.0);
glLightf(GL_LIGHT2, GL_QUADRATIC_ATTENUATION, 1.0);
glEnable(GL_LIGHT3);
glLightfv(GL_LIGHT3, GL_AMBIENT, ambient3);
glLightfv(GL_LIGHT3, GL_DIFFUSE, diffuse3);
glLightfv(GL_LIGHT3, GL_SPECULAR, specular3);
glLightfv(GL_LIGHT3, GL_POSITION, position3);
glLightf(GL_LIGHT3, GL_CONSTANT_ATTENUATION, 2.0);
glLightf(GL_LIGHT3, GL_LINEAR_ATTENUATION, 1.0);
glLightf(GL_LIGHT3, GL_QUADRATIC_ATTENUATION, 1.0);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
// glColorMaterial(GL_FRONT_AND_BACK, GL_SPECULAR);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, front_mat_shininess);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, front_mat_specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, front_mat_diffuse);
// GLfloat fogColor[] = {1.0, 1.0, 1.0, 1.0};
// glFogi(GL_FOG_MODE, GL_LINEAR);
// glFogfv(GL_FOG_COLOR, fogColor);
// glFogf(GL_FOG_DENSITY, 10);
// glHint(GL_FOG_HINT, GL_DONT_CARE);
// glFogf(GL_FOG_START, 0.);
// glFogf(GL_FOG_END, 1.);
// glEnable(GL_FOG);
}
MyGLFWwindow::MyGLFWwindow(int w, int h, const char* name, GLFWmonitor* monitor, GLFWwindow* share):
w(w), h(h){
GLFWMain::windowList.emplace_back(this);
window = glfwCreateWindow(w, h, name, monitor, share);
glfwMakeContextCurrent(window);
glfwSwapInterval(2);
glfwSetMouseButtonCallback(window, GLFWMain::mouse_button_callback);
glfwSetCursorPosCallback(window, GLFWMain::cursor_position_callback);
glfwSetKeyCallback(window, GLFWMain::key_callback);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_NORMALIZE);
glShadeModel(GL_SMOOTH);
initLights();
glClearColor(0.9, 0.9, 0.9, 1);
}
void MyGLFWwindow::addObject(DrawablePtr obj){
obj->reshape(w, h); objects.push_back(obj);
}
void MyGLFWwindow::removeObject(DrawablePtr obj){
for(auto it = objects.begin(); it != objects.end(); ++it){
if(*it == obj){
objects.erase(it);
break;
}
}
}
void MyGLFWwindow::display(){
int cw, ch; glfwGetWindowSize(window, &cw, &ch);
if(cw != w || ch != h) reshape(cw, ch);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
for(auto obj : objects) obj->display();
}
void MyGLFWwindow::mouse_button_callback(GLFWwindow* window, int button, int action, int mode){
for(auto obj : objects) obj->mouse_button_callback(window, button, action, mode);
}
void MyGLFWwindow::cursor_position_callback(GLFWwindow* window, double xpos, double ypos){
for(auto obj : objects) obj->cursor_position_callback(window, xpos, ypos);
}
void MyGLFWwindow::key_callback(GLFWwindow* window, int key, int scancode, int action, int mods){
for(auto obj : objects) obj->key_callback(window, key, scancode, action, mods);
}
void MyGLFWwindow::reshape(int w, int h){
this->w = w; this->h = h;
for(auto obj : objects) obj->reshape(w, h);
} | 34.502825 | 100 | 0.688554 | [
"render"
] |
bb86d5e05c7ee100970d492288c1990eb14d137f | 26,971 | cpp | C++ | trunk/legacy/tools/parsers/tldm_2_sdf/xml2sdf_parser.cpp | Xilinx/merlin-compiler | f47241ccf26186c60bd8aa6e0390c7dd3edabb3c | [
"Apache-2.0"
] | 23 | 2021-09-04T02:12:02.000Z | 2022-03-21T01:10:53.000Z | trunk/legacy/tools/parsers/tldm_2_sdf/xml2sdf_parser.cpp | Xilinx/merlin-compiler | f47241ccf26186c60bd8aa6e0390c7dd3edabb3c | [
"Apache-2.0"
] | 2 | 2022-03-04T02:57:29.000Z | 2022-03-25T15:58:18.000Z | trunk/legacy/tools/parsers/tldm_2_sdf/xml2sdf_parser.cpp | Xilinx/merlin-compiler | f47241ccf26186c60bd8aa6e0390c7dd3edabb3c | [
"Apache-2.0"
] | 12 | 2021-09-22T10:38:47.000Z | 2022-03-28T02:41:56.000Z | // (C) Copyright 2016-2021 Xilinx, Inc.
// All Rights Reserved.
//
// 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.
#include <stdlib.h>
#include <fstream>
#include <algorithm>
#include <string>
#include <set>
using std::string;
// #include "../src/xml_parser.h"
#include "xml_parser.h"
#include "tldm_annotate.h"
#include "iostream"
#include "header.h"
// application specific values
// #define GRAPH_UNROLL_FACTOR 8 // by default, unroll 8 copies
#define GRAPH_UNROLL_FACTOR 128 // by default, unroll 8 copies
// int test_main(char * szFile1, char * szFile2)
bool checkTaskIsWrapper(CXMLNode *xmlNode, string taskName) {
vector<CXMLNode *> nodeVecTask = xmlNode->TraverseByName("task_def", 2);
for (size_t i = 0; i < nodeVecTask.size(); i++) {
// skip the top level task
if (nodeVecTask[i]->GetLevel() == 1) {
continue;
}
string sTaskName;
sTaskName = nodeVecTask[i]->GetParam("name");
if (sTaskName == taskName) {
return tldm_xml_get_attribute(nodeVecTask[i], "module_type") == "wrapper";
}
}
return false;
}
double getTaskIOTime(CXMLNode *pTLDMRoot, string sTaskName) {
CXMLAnn_WrapperGen *pTaskAnn = get_tldm_task_ann_by_name(sTaskName);
int nofPorts = pTaskAnn->GetPortInfoNum();
double nofAccess = 0;
// cout << "Task " << sTaskName << ": " << endl; // <<
// mergedPolyInfo.access_pattern << endl;
for (int i = 0; i < nofPorts; i++) {
tldm_polyhedral_info portPolyInfo = pTaskAnn->GetPortInfo(i).poly_info;
if (portPolyInfo.properties["port_type"] != "bfifo") {
continue;
}
tldm_polyhedral_info taskAndPortPolyInfo =
tldm_polyinfo_merge(pTaskAnn->poly_info, portPolyInfo);
tldm_polyhedral_info mergedPolyInfo = taskAndPortPolyInfo;
// tldm_polyhedral_info mergedPolyInfo = tldm_polyinfo_merge(pTaskAnn ->
// GetParent() -> poly_info, taskAndPortPolyInfo);
vector<tldm_variable_range> vecVarRange =
mergedPolyInfo.get_variable_range();
string iteratorVector = mergedPolyInfo.iterator_vector;
vector<string> loopIterators = str_split(iteratorVector, ',');
// cout << iteratorVector << endl;
/////////////////////////////////////////////////////////////////
// ZP: 2014-02-19 // exclude outer loop iterations in the access calculation
vector<string> outer_iter =
str_split(pTaskAnn->poly_info.iterator_vector, ',');
vector<string> params = str_split(mergedPolyInfo.parameter_vector, ',');
vector<string> total_param = str_vector_add(outer_iter, params);
for (size_t k = 0; k < vecVarRange.size(); k++) {
if (-1 != str_vector_find(total_param, vecVarRange[k].variable)) {
vecVarRange[k].lb = "0";
vecVarRange[k].ub = "0";
}
}
/////////////////////////////////////////////////////////////////
double mul_range = 1;
for (size_t j = 0; j < loopIterators.size(); j++) {
tldm_polynomial onePoly = tldm_polynomial(loopIterators[j], vecVarRange);
int lb;
int ub;
assert(onePoly.get_bound_const(lb, ub));
int range = ub - lb + 1;
mul_range *= static_cast<double>(range);
// cout << loopIterators[j] << ", lb " << lb << ", ub " << ub << ",
// range " << ub - lb + 1 << " mul_range " << mul_range << endl;
}
// cout << "number of access: " << mul_range << endl;
nofAccess += mul_range;
}
return FPGACyclePerAccess * nofAccess;
}
int test_main(char *szApp, char *szPlatform, char *szUcf, char *szSDF) {
// system("echo here is test_main");
std::ofstream sdfFile;
sdfFile.open(szSDF);
bool mod_sel_flag = false;
bool mod_dup_flag = false;
string platform_name;
//============= Parse User Directive =============================
//================================================================
CXMLParser ucf;
ucf.parse_from_file(string(szUcf));
CXMLNode *xmlNodeUcf = ucf.get_xml_tree()->getRoot();
if (xmlNodeUcf->GetChildByName("module_selection")->GetValue() == "on") {
mod_sel_flag = true;
}
if (xmlNodeUcf->GetChildByName("module_duplication")->GetValue() == "on") {
mod_dup_flag = true;
}
platform_name = xmlNodeUcf->GetChildByName("platform_name")->GetValue();
//================================================================
CXMLParser application;
application.parse_from_file(string(szApp));
CXMLNode *xmlNode = application.get_xml_tree()->getRoot();
mark_tldm_annotation(xmlNode);
dump_task_pragma("polyinfo_modsel.rpt");
// sdfFile << xmlNode -> GetName() << endl;
// sdfFile << xmlNode -> GetValue() << endl;
vector<CXMLNode *> nodeVecTask = xmlNode->TraverseByName("task_def", 2);
vector<string> mTaskNameList;
for (size_t i = 0; i < nodeVecTask.size(); i++) {
string sTaskName;
// skip the top level task
if (nodeVecTask[i]->GetLevel() == 1) {
continue;
}
sTaskName = nodeVecTask[i]->GetParam("name");
// skip the input and output
if (sTaskName == "INPUT" || sTaskName == "OUTPUT") {
continue;
}
if (tldm_xml_get_attribute(nodeVecTask[i], "type") == "graph") {
continue;
}
// skip gid, ldu, etc.
if (tldm_xml_get_attribute(nodeVecTask[i], "module_type") != "wrapper") {
continue;
}
mTaskNameList.push_back(sTaskName);
}
map<string, int>
mTaskName2NofInstance; // number of this task in the unrolled sdf graph
map<string, int> mTaskName2MaxDup;
map<string, int> mTaskName2PCF; // performance compensate factor
sdfFile << "@TASK_LIST {" << endl;
int scaling_factor = 1;
for (size_t i = 0; i < nodeVecTask.size(); i++) {
string sTaskName;
// skip the top level task
if (nodeVecTask[i]->GetLevel() == 1) {
continue;
}
// skip non-related tasks
sTaskName = nodeVecTask[i]->GetParam("name");
if (find(mTaskNameList.begin(), mTaskNameList.end(), sTaskName) ==
mTaskNameList.end()) {
continue;
}
// get number of task instances
CXMLAnn_WrapperGen *tmpTaskAnn = get_tldm_task_ann_by_name(sTaskName);
unsigned nof_instance = my_atoi(tmpTaskAnn->GetParam(
"sdf_iter_num")); // the graph needs to be executed
// that amount of iterations
int unroll_factor = static_cast<int>(nof_instance < GRAPH_UNROLL_FACTOR
? nof_instance
: GRAPH_UNROLL_FACTOR);
mTaskName2NofInstance[sTaskName] = unroll_factor;
mTaskName2PCF[sTaskName] =
(nof_instance / unroll_factor) +
((nof_instance % unroll_factor) == 0
? 0
: 1); // ceiling(nof_instances/unroll_factor)
// get maximal allowed number of replicas
int max_dup = unroll_factor; // default is the same as the unroll factor
if (tldm_xml_get_attribute(nodeVecTask[i], "module_type") == "wrapper") {
CXMLNode *nodeRate =
SearchNodeNameUnique(nodeVecTask[i], "attribute",
"max_dup_factor"); // sdf_related parameter
unsigned user_defined_max_dup;
if (nodeRate != nullptr) {
user_defined_max_dup =
my_atoi(nodeRate->GetChildByIndex(0)->GetValue());
if (user_defined_max_dup > 1 && !mod_dup_flag) {
cout << "-------tldm_2_sdf parser ERROR:--------" << endl;
cout << "module duplication is turned off" << endl;
cout << "cannot specify maximum duplication factor of "
<< user_defined_max_dup << " for task " << sTaskName;
}
if (user_defined_max_dup > unroll_factor) {
cout << "-------tldm_2_sdf parser ERROR:--------" << endl;
cout << "Task: " << sTaskName << "\tuser spedicifed dup_factor"
<< user_defined_max_dup << endl;
cout << "unroll factor: " << unroll_factor << endl;
assert(0);
}
max_dup = static_cast<int>(user_defined_max_dup);
}
}
if (!mod_dup_flag) {
max_dup = 1;
}
mTaskName2MaxDup[sTaskName] = max_dup;
sdfFile << "\tTASK " << sTaskName << " MAX_IMPL " << max_dup;
// get user specified replicas
if (tldm_xml_get_attribute(nodeVecTask[i], "module_type") == "wrapper") {
CXMLNode *nodeRate = SearchNodeNameUnique(
nodeVecTask[i], "attribute", "dup_factor"); // sdf_related parameter
unsigned user_defined_dup;
if (nodeRate != nullptr) {
user_defined_dup = my_atoi(nodeRate->GetChildByIndex(0)->GetValue());
if (user_defined_dup > 1 && !mod_dup_flag) {
cout << "-------tldm_2_sdf parser ERROR:--------" << endl;
cout << "module duplication is turned off" << endl;
cout << "cannot specify duplication factor of " << user_defined_dup
<< " for task " << sTaskName;
}
if (user_defined_dup > unroll_factor) {
cout << "-------tldm_2_sdf parser ERROR:--------" << endl;
cout << "Task: " << sTaskName << "\tuser spedicifed dup_factor"
<< user_defined_dup << endl;
cout << "unroll factor: " << unroll_factor << endl;
assert(0);
}
sdfFile << " FIX_IMPL " << user_defined_dup;
}
}
unsigned group_id = my_atoi(tmpTaskAnn->GetParam("sdf_group_id"));
unsigned group_task_id = my_atoi(tmpTaskAnn->GetParam("sdf_task_id"));
// unsigned iter_num = my_atoi( tmpTaskAnn -> GetParam("sdf_iter_num") );
unsigned iter_num = 10; // my_atoi( tmpTaskAnn -> GetParam("sdf_iter_num")
// );
// TODO(youxiang): ZP: calculate the ITER_NUM
// 1. calculate the scaling factor
// 2. scale the iter_num using the factor
sdfFile << " GROUP_ID " << group_id << " GROUPINNER_ID " << group_task_id
<< " ITER_NUM " << iter_num; // << nof_instance;
sdfFile << endl;
}
sdfFile << "}" << endl;
// exit(0);
sdfFile << "@SCALING_FACTOR ";
sdfFile << scaling_factor << endl;
// parse fixed implementation
map<string, string> mTaskName2FixImpl;
for (size_t i = 0; i < nodeVecTask.size(); i++) {
string sTaskName;
// skip the top level task
if (nodeVecTask[i]->GetLevel() == 1) {
continue;
}
// skip non-related tasks
sTaskName = nodeVecTask[i]->GetParam("name");
if (find(mTaskNameList.begin(), mTaskNameList.end(), sTaskName) ==
mTaskNameList.end()) {
continue;
}
// add to map from name -> fixed implementation
string fixImpl = nodeVecTask[i]->GetParam("position");
if (!fixImpl.empty()) {
mTaskName2FixImpl[sTaskName] = fixImpl;
}
}
#if 1
map<string, int> mTaskName2Gdus;
for (size_t i = 0; i < mTaskNameList.size(); i++) {
mTaskName2Gdus[mTaskNameList[i]] = 0;
}
// dependency
vector<CTldmDependenceAnn *> vectorDepAnn = get_tldm_dependence_set();
// count number of gdus for each task
for (size_t i = 0; i < vectorDepAnn.size(); i++) {
CTldmDependenceAnn *depAnn = vectorDepAnn[i];
// step 0: get polyhedral_info
CXMLAnn_WrapperGen *pTask0 = depAnn->GetTask0();
CXMLAnn_WrapperGen *pTask1 = depAnn->GetTask1();
assert(pTask0);
assert(pTask1);
string proTaskName;
string conTaskName;
string dataName;
tldm_polyhedral_info poly_info_0 = pTask0->poly_info;
tldm_polyhedral_info poly_info_1 = pTask1->poly_info;
proTaskName = poly_info_0.name;
conTaskName = poly_info_1.name;
// proTaskName = pTask0 -> poly_info.name;
// conTaskName = pTask1 -> poly_info.name;
// dataName = poly_info_0.name;
// if (nport0_info.port_type != "bfifo" || nport1_info.port_type !=
// "bfifo") continue; if (poly_info_0.properties["port_type"] !=
// "bfifo" ||
// poly_info_1.properties["port_type"] != "bfifo") continue;
cout << proTaskName << " --> " << conTaskName << endl;
if (poly_info_0.properties["module_type"] != "wrapper" &&
poly_info_1.properties["module_type"] == "wrapper") {
mTaskName2Gdus[conTaskName]++;
}
if (poly_info_0.properties["module_type"] == "wrapper" &&
poly_info_1.properties["module_type"] != "wrapper") {
mTaskName2Gdus[proTaskName]++;
}
// if (pTask0 ->)
// cout << "dataName: " << dataName << endl;
}
for (map<string, int>::iterator iter = mTaskName2Gdus.begin();
iter != mTaskName2Gdus.end(); iter++) {
cout << iter->first << ": " << iter->second << endl;
}
#endif
#if 1
//============= Parse Platform Infomation =============================
//============= Get implementation lib ================================
CXMLParser platform;
platform.parse_from_file(string(szPlatform));
CXMLNode *xmlNodePlat = platform.get_xml_tree()->getRoot();
vector<CXMLNode *> nodeVecComponent =
xmlNodePlat->TraverseByName("component");
// get IOTime of each task
map<string, double> mTaskName2IOTime;
for (size_t i = 0; i < mTaskNameList.size(); i++) {
mTaskName2IOTime[mTaskNameList[i]] =
getTaskIOTime(xmlNode, mTaskNameList[i]);
}
map<string, int> mTaskName2Version;
sdfFile << "@LIBRARY {" << endl;
for (size_t i = 0; i < nodeVecComponent.size(); i++) {
// skip non-acc component
string sType;
if (nodeVecComponent[i]->GetChildByName("type") != NULL) {
sType = nodeVecComponent[i]->GetChildByName("type")->GetValue();
} else {
continue;
}
if (sType != "Accelerator" && sType != "Computation") {
continue;
}
string mComponentName = nodeVecComponent[i]->GetParam("name");
vector<CXMLNode *> nodeVecImpl =
nodeVecComponent[i]->TraverseByName("implementation");
for (size_t j = 0; j < nodeVecImpl.size(); j++) {
string mImplName = nodeVecImpl[j]->GetParam("name");
string mTaskName = nodeVecImpl[j]->GetParam("task");
// cannot find the implementation in current application
if (find(mTaskNameList.begin(), mTaskNameList.end(), mTaskName) ==
mTaskNameList.end()) {
continue;
}
// if this task has fixed implementation, skip other implementations
if (!mTaskName2FixImpl[mTaskName].empty()) { // user specified selection
if (mTaskName2FixImpl[mTaskName] != mImplName) {
continue;
}
}
if (!mod_sel_flag) { // user doesn't specify, mod_sel off, then use hw0
if (mImplName.substr(mImplName.size() - strlen("hw_imp0"),
mImplName.size()) != "hw_imp0") {
continue;
}
}
// FIXME: Peng Zhang
if (platform_name == "zed" && mComponentName == "microblaze") {
continue;
}
if (platform_name == "ml605" && mComponentName == "arm_a9") {
continue;
}
// FIXME: Peng Zhang 2013-02-10
if (sType == "Computation") {
// if (mod_dup_flag == false || platform_name !="zed") //
// one core
// {
if (mImplName.substr(mImplName.size() - 7, mImplName.size()) !=
"sw_imp0") {
continue;
}
// }
//
// else // the case we have two cores
// {
// char * task_list[] = {"parser", "dequant",
// "idct_row",
// "idct_col", "cc_mc", "tu", "denoise"}; int k;
// for (k = 0; k < 7; k++)
// {
// string s_task_name = string(task_list[k]);
// if (mImplName.find(s_task_name) == 0) break;
// }
// assert(k < 7);
// string imp_suffix = (k&1) ? "sw_imp1" : "sw_imp0";
// if (mImplName.substr(mImplName.size()-7,
// mImplName.size())
//!= imp_suffix) continue;
// }
}
int version;
// get version, start from 0
if (mTaskName2Version.find(mTaskName) == mTaskName2Version.end()) {
version = 0;
mTaskName2Version[mTaskName] = 0;
} else {
version = mTaskName2Version[mTaskName] + 1;
mTaskName2Version[mTaskName] = version;
}
// get pcf
int pcf = mTaskName2PCF[mTaskName]; // performance compensate factor
sdfFile << "\tTASK " << mTaskName << " VERSION " << version << " ";
CXMLNode *nodeMetric = nodeVecImpl[j]->GetChildByName("metrics");
double exeTime;
int areaCost;
// int initInterval;
exeTime = my_atoi((nodeMetric->GetChildByName("worst_lat")->GetValue()));
double ioTime = mTaskName2IOTime[mTaskName];
if (mImplName.substr(mImplName.size() - 7, mImplName.size()) !=
"sw_imp0") {
exeTime = exeTime > ioTime ? exeTime : ioTime;
}
exeTime *= pcf;
sdfFile << "EXETIME " << exeTime << " ";
sdfFile << "II " << exeTime << " ";
int nofFF;
int nofLUT;
if (mImplName.substr(mImplName.size() - 7, mImplName.size()) ==
"sw_imp0") {
nofFF = my_atoi(nodeMetric->GetChildByName("num_FF")->GetValue());
nofLUT = my_atoi(nodeMetric->GetChildByName("num_LUT")->GetValue());
} else {
nofFF = my_atoi(nodeMetric->GetChildByName("num_FF")->GetValue()) +
mTaskName2Gdus[mTaskName] * GDU_FF;
nofLUT = my_atoi(nodeMetric->GetChildByName("num_LUT")->GetValue()) +
mTaskName2Gdus[mTaskName] * GDU_LUT;
}
areaCost = (nofFF / 2 > nofLUT) ? nofFF / 2 : nofLUT;
sdfFile << "AREA " << areaCost << " ";
int bramSize =
my_atoi((nodeMetric->GetChildByName("num_BRAM")->GetValue())) * 16 *
1024 / 32; // 18kb --> int
// if (mImplName.substr(mImplName.size()-7, mImplName.size()) !=
// "sw_imp0") bramSize += mTaskName2Gdus[mTaskName] * GDU_BRAM;
sdfFile << "BRAM " << bramSize << " ";
int nofDSP = my_atoi((nodeMetric->GetChildByName("num_DSP")->GetValue()));
if (mImplName.substr(mImplName.size() - 7, mImplName.size()) !=
"sw_imp0") {
nofDSP += mTaskName2Gdus[mTaskName] * GDU_DSP;
}
sdfFile << "DSP " << nofDSP << " ";
sdfFile << "IMPLNAME " << mImplName << " ";
sdfFile << endl;
}
}
sdfFile << "}" << endl;
#endif
//============= SDFG Infomation =============================
//===========================================================
sdfFile << "@HSDFG 0 {" << endl;
vector<CXMLNode *> nodeVecConnect = xmlNode->TraverseByName("connect");
// int nofEdges = 0;
//==== SDFG NODES ===================
for (size_t i = 0; i < nodeVecTask.size(); i++) {
string sTaskName;
string sNodeName;
// skip the top level task
if (nodeVecTask[i]->GetLevel() == 1) {
continue;
}
sTaskName = nodeVecTask[i]->GetParam("name");
if (find(mTaskNameList.begin(), mTaskNameList.end(), sTaskName) ==
mTaskNameList.end()) {
continue;
}
sNodeName = sTaskName;
for (int j = 0; j < mTaskName2NofInstance[sTaskName]; j++) {
sdfFile << "\tNODE " << sNodeName << "_" << j << " TASK " << sTaskName
<< " LABLE " << j << endl;
}
}
sdfFile << endl << endl;
//==== SDFG ARCs ===================
// vector<string> argsRate; argsRate.push_back("rate");
//
//
std::set<string> parsedConnect;
std::set<string>::iterator ssIter;
parsedConnect.clear();
int edgeNum = 0;
for (size_t i = 0; i < vectorDepAnn.size(); i++) {
CTldmDependenceAnn *depAnn = vectorDepAnn[i];
// step 0: get polyhedral_info
CXMLAnn_WrapperGen *pTask0 = depAnn->GetTask0();
CXMLAnn_WrapperGen *pTask1 = depAnn->GetTask1();
assert(pTask0);
assert(pTask1);
string proTaskName;
string conTaskName;
string dataName;
tldm_polyhedral_info poly_info_0 = pTask0->poly_info;
tldm_polyhedral_info poly_info_1 = pTask1->poly_info;
proTaskName = poly_info_0.name;
conTaskName = poly_info_1.name;
dataName = pTask0->GetPortInfo(depAnn->GetPort0()).poly_info.name;
// proTaskName = pTask0 -> poly_info.name;
// conTaskName = pTask1 -> poly_info.name;
// dataName = poly_info_0.name;
// if (nport0_info.port_type != "bfifo" || nport1_info.port_type !=
// "bfifo") continue; if (poly_info_0.properties["port_type"] !=
// "bfifo" ||
// poly_info_1.properties["port_type"] != "bfifo") continue;
// cout << proTaskName << " --> " << conTaskName << endl;
if (proTaskName != conTaskName) {
if (find(mTaskNameList.begin(), mTaskNameList.end(), proTaskName) ==
mTaskNameList.end()) {
continue;
}
if (find(mTaskNameList.begin(), mTaskNameList.end(), conTaskName) ==
mTaskNameList.end()) {
continue;
}
assert(mTaskName2NofInstance[proTaskName] ==
mTaskName2NofInstance[conTaskName]);
// check they should be in the same graph???
for (int i = 0; i < mTaskName2NofInstance[proTaskName]; i++) {
sdfFile << "\tARC " << dataName << "_" << edgeNum++ << " FROM "
<< proTaskName << "_" << i;
sdfFile << " TO " << conTaskName << "_" << i;
sdfFile << " TYPE 2" << endl;
}
}
}
// cross-Graph edges
// has assume only one task in each graph
for (size_t i = 0; i < mTaskNameList.size(); i++) {
for (size_t j = 0; j < mTaskNameList.size(); j++) {
if (i >= j) {
continue;
}
string proTaskName = mTaskNameList[i];
string conTaskName = mTaskNameList[j];
CXMLAnn_WrapperGen *proTaskAnn;
CXMLAnn_WrapperGen *conTaskAnn;
proTaskAnn = get_tldm_task_ann_by_name(proTaskName);
conTaskAnn = get_tldm_task_ann_by_name(conTaskName);
unsigned proTask_group_id;
unsigned conTask_group_id;
// unsigned proTask_task_id, conTask_task_id;
// unsigned proTask_iter_num, conTask_iter_num;
proTask_group_id = my_atoi(proTaskAnn->GetParam("sdf_group_id"));
// proTask_task_id = my_atoi( proTaskAnn -> GetParam("sdf_task_id") );
// proTask_iter_num = my_atoi( proTaskAnn -> GetParam("sdf_iter_num") );
conTask_group_id = my_atoi(conTaskAnn->GetParam("sdf_group_id"));
// conTask_task_id = my_atoi( conTaskAnn -> GetParam("sdf_task_id") );
// conTask_iter_num = my_atoi( conTaskAnn -> GetParam("sdf_iter_num") );
// assert(proTask_iter_num == conTask_iter_num); // ?
if (proTask_group_id >= conTask_group_id) {
continue;
}
sdfFile << "\tARC edge_" << edgeNum++ << " FROM " << proTaskName << "_"
<< mTaskName2NofInstance[proTaskName] - 1;
sdfFile << " TO " << conTaskName << "_0";
sdfFile << " TYPE 2";
// sdfFile << " ITERATION_FACTOR 1";
sdfFile << endl;
}
}
// find the task with group id of 0, and mTaskNameList.size()-1
{
// if (mTaskNameList.size() != 1) // skip ARC if only one group
//{
string proTaskName;
string conTaskName;
for (size_t i = 0; i < mTaskNameList.size(); i++) {
string sTaskName = mTaskNameList[i];
CXMLAnn_WrapperGen *taskAnn;
taskAnn = get_tldm_task_ann_by_name(sTaskName);
unsigned task_group_id = my_atoi(taskAnn->GetParam("sdf_group_id"));
if (task_group_id == 0) {
conTaskName = sTaskName;
}
if ((static_cast<unsigned int>(task_group_id ==
mTaskNameList.size() - 1) != 0U)) {
proTaskName = sTaskName;
}
}
if (!proTaskName.empty()) {
sdfFile << "\tARC edge_" << edgeNum++ << " FROM " << proTaskName << "_"
<< mTaskName2NofInstance[proTaskName] - 1;
sdfFile << " TO " << conTaskName << "_0";
sdfFile << " TYPE 3";
// sdfFile << " ITERATION_FACTOR 1";
sdfFile << endl;
}
//}
}
sdfFile << "}" << endl;
//============= Parse Buffer Infomation =============================
//=======================================================================
sdfFile << "@BUFFER {" << endl;
int bufId = 0;
for (size_t i = 0; i < vectorDepAnn.size(); i++) {
CTldmDependenceAnn *depAnn = vectorDepAnn[i];
// step 0: get polyhedral_info
CXMLAnn_WrapperGen *pTask0 = depAnn->GetTask0();
CXMLAnn_WrapperGen *pTask1 = depAnn->GetTask1();
assert(pTask0);
assert(pTask1);
string proTaskName;
string conTaskName;
string dataName;
tldm_polyhedral_info poly_info_0 = pTask0->poly_info;
tldm_polyhedral_info poly_info_1 = pTask1->poly_info;
proTaskName = poly_info_0.name;
conTaskName = poly_info_1.name;
if (proTaskName == conTaskName) {
continue;
}
dataName = pTask0->GetPortInfo(depAnn->GetPort0()).poly_info.name;
// proTaskName = pTask0 -> poly_info.name;
// conTaskName = pTask1 -> poly_info.name;
// dataName = poly_info_0.name;
// if (nport0_info.port_type != "bfifo" || nport1_info.port_type !=
// "bfifo") continue; if (poly_info_0.properties["port_type"] !=
// "bfifo" ||
// poly_info_1.properties["port_type"] != "bfifo") continue;
// cout << proTaskName << " --> " << conTaskName << endl;
if (find(mTaskNameList.begin(), mTaskNameList.end(), proTaskName) ==
mTaskNameList.end()) {
continue;
}
if (find(mTaskNameList.begin(), mTaskNameList.end(), conTaskName) ==
mTaskNameList.end()) {
continue;
}
int tokenSize = 32768;
int proRate = 1;
int conRate = 1;
sdfFile << "\tBUF buf_" << bufId++ << " FROMTASK " << proTaskName;
sdfFile << " TOTASK " << conTaskName;
sdfFile << " TOKENSIZE " << tokenSize;
sdfFile << " PRORATE " << proRate;
sdfFile << " CONRATE " << conRate << endl;
}
sdfFile << "}" << endl;
return 1;
}
int main(int argc, char *argv[]) {
// printf("Hello Starting...\n");
// test_main(argv[1], argv[2]);
if (argc < 4) {
cout << "./xml2sdf_parser test.tldm_ann.xml design_metrics.xml "
"directive.xml sdf.txt"
<< endl;
exit(1);
}
test_main(argv[1], argv[2], argv[3], argv[4]);
return 1;
}
| 34.711712 | 80 | 0.584776 | [
"vector"
] |
bb875077b5b9c2bdf55875273c61037f93ce8318 | 10,923 | cc | C++ | DQMOffline/CalibMuon/src/DTt0DBValidation.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-08-09T08:42:11.000Z | 2019-08-09T08:42:11.000Z | DQMOffline/CalibMuon/src/DTt0DBValidation.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | DQMOffline/CalibMuon/src/DTt0DBValidation.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-03-19T13:44:54.000Z | 2019-03-19T13:44:54.000Z |
/*
* See header file for a description of this class.
*
* \author G. Mila - INFN Torino
*/
#include "DQMOffline/CalibMuon/interface/DTt0DBValidation.h"
// Framework
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "DQMServices/Core/interface/MonitorElement.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
// Geometry
#include "Geometry/Records/interface/MuonGeometryRecord.h"
#include "Geometry/DTGeometry/interface/DTGeometry.h"
#include "Geometry/DTGeometry/interface/DTLayer.h"
#include "Geometry/DTGeometry/interface/DTTopology.h"
// t0
#include "CondFormats/DTObjects/interface/DTT0.h"
#include "CondFormats/DataRecord/interface/DTT0Rcd.h"
#include "TFile.h"
#include <sstream>
#include <iomanip>
using namespace edm;
using namespace std;
DTt0DBValidation::DTt0DBValidation(const ParameterSet& pset) {
metname_ = "InterChannelSynchDBValidation";
LogVerbatim(metname_) << "[DTt0DBValidation] Constructor called!";
// Get the DQM needed services
dbe_ = edm::Service<DQMStore>().operator->();
dbe_->setCurrentFolder("DT/DtCalib/InterChannelSynchDBValidation");
// Get dataBase label
labelDBRef_ = pset.getParameter<string>("labelDBRef");
labelDB_ = pset.getParameter<string>("labelDB");
t0TestName_ = "t0DifferenceInRange";
if( pset.exists("t0TestName") ) t0TestName_ = pset.getParameter<string>("t0TestName");
outputMEsInRootFile_ = false;
if( pset.exists("OutputFileName") ){
outputMEsInRootFile_ = true;
outputFileName_ = pset.getParameter<std::string>("OutputFileName");
}
}
DTt0DBValidation::~DTt0DBValidation(){}
void DTt0DBValidation::beginRun(const edm::Run& run, const EventSetup& setup) {
metname_ = "InterChannelSynchDBValidation";
LogVerbatim(metname_) << "[DTt0DBValidation] Parameters initialization";
ESHandle<DTT0> t0_Ref;
setup.get<DTT0Rcd>().get(labelDBRef_, t0_Ref);
tZeroRefMap_ = &*t0_Ref;
LogVerbatim(metname_) << "[DTt0DBValidation] reference T0 version: " << t0_Ref->version();
ESHandle<DTT0> t0;
setup.get<DTT0Rcd>().get(labelDB_, t0);
tZeroMap_ = &*t0;
LogVerbatim(metname_) << "[DTt0DBValidation] T0 to validate version: " << t0->version();
//book&reset the summary histos
for(int wheel=-2; wheel<=2; wheel++){
bookHistos(wheel);
wheelSummary_[wheel]->Reset();
}
// Get the geometry
setup.get<MuonGeometryRecord>().get(dtGeom_);
// Loop over Ref DB entries
for(DTT0::const_iterator tzero = tZeroRefMap_->begin();
tzero != tZeroRefMap_->end(); tzero++) {
// t0s and rms are TDC counts
// @@@ NEW DTT0 FORMAT
// DTWireId wireId((*tzero).first.wheelId,
// (*tzero).first.stationId,
// (*tzero).first.sectorId,
// (*tzero).first.slId,
// (*tzero).first.layerId,
// (*tzero).first.cellId);
int channelId = tzero->channelId;
if ( channelId == 0 ) continue;
DTWireId wireId(channelId);
// @@@ NEW DTT0 END
float t0mean;
float t0rms;
tZeroRefMap_->get( wireId, t0mean, t0rms, DTTimeUnits::counts );
LogTrace(metname_)<< "Ref Wire: " << wireId <<endl
<< " T0 mean (TDC counts): " << t0mean
<< " T0_rms (TDC counts): " << t0rms;
t0RefMap_[wireId].push_back(t0mean);
t0RefMap_[wireId].push_back(t0rms);
}
// Loop over Ref DB entries
for(DTT0::const_iterator tzero = tZeroMap_->begin();
tzero != tZeroMap_->end(); tzero++) {
// t0s and rms are TDC counts
// @@@ NEW DTT0 FORMAT
// DTWireId wireId((*tzero).first.wheelId,
// (*tzero).first.stationId,
// (*tzero).first.sectorId,
// (*tzero).first.slId,
// (*tzero).first.layerId,
// (*tzero).first.cellId);
int channelId = tzero->channelId;
if ( channelId == 0 ) continue;
DTWireId wireId(channelId);
// @@@ NEW DTT0 END
float t0mean;
float t0rms;
tZeroMap_->get( wireId, t0mean, t0rms, DTTimeUnits::counts );
LogTrace(metname_)<< "Wire: " << wireId <<endl
<< " T0 mean (TDC counts): " << t0mean
<< " T0_rms (TDC counts): " << t0rms;
t0Map_[wireId].push_back(t0mean);
t0Map_[wireId].push_back(t0rms);
}
double difference = 0;
for(map<DTWireId, vector<float> >::const_iterator theMap = t0RefMap_.begin();
theMap != t0RefMap_.end();
theMap++) {
if(t0Map_.find((*theMap).first) != t0Map_.end()) {
// Compute the difference
difference = t0Map_[(*theMap).first][0]-(*theMap).second[0];
//book histo
DTLayerId layerId = (*theMap).first.layerId();
if(t0DiffHistos_.find(layerId) == t0DiffHistos_.end()) {
const DTTopology& dtTopo = dtGeom_->layer(layerId)->specificTopology();
const int firstWire = dtTopo.firstChannel();
const int lastWire = dtTopo.lastChannel();
bookHistos(layerId, firstWire, lastWire);
}
LogTrace(metname_)<< "Filling the histo for wire: "<<(*theMap).first
<<" difference: "<<difference;
t0DiffHistos_[layerId]->Fill((*theMap).first.wire(),difference);
}
} // Loop over the t0 map reference
}
void DTt0DBValidation::endRun(edm::Run const& run, edm::EventSetup const& setup) {
// Check the histos
string testCriterionName = t0TestName_;
for(map<DTLayerId, MonitorElement*>::const_iterator hDiff = t0DiffHistos_.begin();
hDiff != t0DiffHistos_.end();
hDiff++) {
const QReport * theDiffQReport = (*hDiff).second->getQReport(testCriterionName);
if(theDiffQReport) {
int xBin = ((*hDiff).first.station()-1)*12+(*hDiff).first.layer()+4*((*hDiff).first.superlayer()-1);
if( (*hDiff).first.station()==4 && (*hDiff).first.superlayer()==3 )
xBin = ((*hDiff).first.station()-1)*12+(*hDiff).first.layer()+4*((*hDiff).first.superlayer()-2);
int qReportStatus = theDiffQReport->getStatus()/100;
wheelSummary_[(*hDiff).first.wheel()]->setBinContent(xBin,(*hDiff).first.sector(),qReportStatus);
LogVerbatim(metname_) << "-------- layer: " << (*hDiff).first << " " << theDiffQReport->getMessage()
<< " ------- " << theDiffQReport->getStatus()
<< " ------- " << setprecision(3) << theDiffQReport->getQTresult();
vector<dqm::me_util::Channel> badChannels = theDiffQReport->getBadChannels();
for (vector<dqm::me_util::Channel>::iterator channel = badChannels.begin();
channel != badChannels.end(); channel++) {
LogVerbatim(metname_) << "layer: " << (*hDiff).first << " Bad channel: "
<< (*channel).getBin() << " Contents : "
<< (*channel).getContents();
//wheelSummary_[(*hDiff).first.wheel()]->Fill(xBin,(*hDiff).first.sector());
}
}
}
}
void DTt0DBValidation::endJob() {
// Write the histos on a file
if(outputMEsInRootFile_) dbe_->save(outputFileName_);
}
// Book a set of histograms for a given Layer
void DTt0DBValidation::bookHistos(DTLayerId lId, int firstWire, int lastWire) {
LogTrace(metname_)<< " Booking histos for L: " << lId;
// Compose the chamber name
stringstream wheel; wheel << lId.superlayerId().chamberId().wheel();
stringstream station; station << lId.superlayerId().chamberId().station();
stringstream sector; sector << lId.superlayerId().chamberId().sector();
stringstream superLayer; superLayer << lId.superlayerId().superlayer();
stringstream layer; layer << lId.layer();
string lHistoName =
"_W" + wheel.str() +
"_St" + station.str() +
"_Sec" + sector.str() +
"_SL" + superLayer.str()+
"_L" + layer.str();
dbe_->setCurrentFolder("DT/DtCalib/InterChannelSynchDBValidation/Wheel" + wheel.str() +
"/Station" + station.str() +
"/Sector" + sector.str() +
"/SuperLayer" +superLayer.str());
// Create the monitor elements
MonitorElement * hDifference;
hDifference = dbe_->book1D("T0Difference"+lHistoName, "difference between the two t0 values",lastWire-firstWire+1, firstWire-0.5, lastWire+0.5);
t0DiffHistos_[lId] = hDifference;
}
// Book the summary histos
void DTt0DBValidation::bookHistos(int wheel) {
dbe_->setCurrentFolder("DT/DtCalib/InterChannelSynchDBValidation");
stringstream wh; wh << wheel;
wheelSummary_[wheel]= dbe_->book2D("SummaryWrongT0_W"+wh.str(), "W"+wh.str()+": summary of wrong t0 differences",44,1,45,14,1,15);
wheelSummary_[wheel]->setBinLabel(1,"M1L1",1);
wheelSummary_[wheel]->setBinLabel(2,"M1L2",1);
wheelSummary_[wheel]->setBinLabel(3,"M1L3",1);
wheelSummary_[wheel]->setBinLabel(4,"M1L4",1);
wheelSummary_[wheel]->setBinLabel(5,"M1L5",1);
wheelSummary_[wheel]->setBinLabel(6,"M1L6",1);
wheelSummary_[wheel]->setBinLabel(7,"M1L7",1);
wheelSummary_[wheel]->setBinLabel(8,"M1L8",1);
wheelSummary_[wheel]->setBinLabel(9,"M1L9",1);
wheelSummary_[wheel]->setBinLabel(10,"M1L10",1);
wheelSummary_[wheel]->setBinLabel(11,"M1L11",1);
wheelSummary_[wheel]->setBinLabel(12,"M1L12",1);
wheelSummary_[wheel]->setBinLabel(13,"M2L1",1);
wheelSummary_[wheel]->setBinLabel(14,"M2L2",1);
wheelSummary_[wheel]->setBinLabel(15,"M2L3",1);
wheelSummary_[wheel]->setBinLabel(16,"M2L4",1);
wheelSummary_[wheel]->setBinLabel(17,"M2L5",1);
wheelSummary_[wheel]->setBinLabel(18,"M2L6",1);
wheelSummary_[wheel]->setBinLabel(19,"M2L7",1);
wheelSummary_[wheel]->setBinLabel(20,"M2L8",1);
wheelSummary_[wheel]->setBinLabel(21,"M2L9",1);
wheelSummary_[wheel]->setBinLabel(22,"M2L10",1);
wheelSummary_[wheel]->setBinLabel(23,"M2L11",1);
wheelSummary_[wheel]->setBinLabel(24,"M2L12",1);
wheelSummary_[wheel]->setBinLabel(25,"M3L1",1);
wheelSummary_[wheel]->setBinLabel(26,"M3L2",1);
wheelSummary_[wheel]->setBinLabel(27,"M3L3",1);
wheelSummary_[wheel]->setBinLabel(28,"M3L4",1);
wheelSummary_[wheel]->setBinLabel(29,"M3L5",1);
wheelSummary_[wheel]->setBinLabel(30,"M3L6",1);
wheelSummary_[wheel]->setBinLabel(31,"M3L7",1);
wheelSummary_[wheel]->setBinLabel(32,"M3L8",1);
wheelSummary_[wheel]->setBinLabel(33,"M3L9",1);
wheelSummary_[wheel]->setBinLabel(34,"M3L10",1);
wheelSummary_[wheel]->setBinLabel(35,"M3L11",1);
wheelSummary_[wheel]->setBinLabel(36,"M3L12",1);
wheelSummary_[wheel]->setBinLabel(37,"M4L1",1);
wheelSummary_[wheel]->setBinLabel(38,"M4L2",1);
wheelSummary_[wheel]->setBinLabel(39,"M4L3",1);
wheelSummary_[wheel]->setBinLabel(40,"M4L4",1);
wheelSummary_[wheel]->setBinLabel(41,"M4L5",1);
wheelSummary_[wheel]->setBinLabel(42,"M4L6",1);
wheelSummary_[wheel]->setBinLabel(43,"M4L7",1);
wheelSummary_[wheel]->setBinLabel(44,"M4L8",1);
}
| 37.927083 | 146 | 0.658519 | [
"geometry",
"vector"
] |
bb92bb7342f23ab1ba7734af5ebbe74538084197 | 2,968 | cpp | C++ | src/regex.cpp | Clyde-Beep/sporks-test | c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07 | [
"Apache-2.0"
] | 22 | 2020-01-25T16:50:07.000Z | 2022-01-30T02:47:17.000Z | src/regex.cpp | Clyde-Beep/sporks-test | c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07 | [
"Apache-2.0"
] | 1 | 2020-10-08T13:37:11.000Z | 2020-10-08T13:37:11.000Z | src/regex.cpp | Clyde-Beep/sporks-test | c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07 | [
"Apache-2.0"
] | 7 | 2020-03-08T04:57:26.000Z | 2022-02-28T21:57:41.000Z | /************************************************************************************
*
* Sporks, the learning, scriptable Discord bot!
*
* Copyright 2019 Craig Edwards <support@sporks.gg>
*
* 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 <sporks/regex.h>
#include <pcre.h>
#include <string>
#include <vector>
#include <iostream>
/**
* Constructor for an exception in a regex
*/
regex_exception::regex_exception(const std::string &_message) : std::exception(), message(_message) {
}
/**
* Constructor for PCRE regular expression. Takes an expression to match against and optionally a boolean to
* indicate if the expression should be treated as case sensitive (defaults to false).
* Construction compiles the regex, which for a well formed regex may be more expensive than matching against a string.
*/
PCRE::PCRE(const std::string &match, bool case_insensitive) {
compiled_regex = pcre_compile(match.c_str(), case_insensitive ? PCRE_CASELESS | PCRE_MULTILINE : PCRE_MULTILINE, &pcre_error, &pcre_error_ofs, NULL);
if (!compiled_regex) {
throw new regex_exception(pcre_error);
}
}
/**
* Match regular expression against a string, returns true on match, false if no match.
*/
bool PCRE::Match(const std::string &comparison) {
return (pcre_exec(compiled_regex, NULL, comparison.c_str(), comparison.length(), 0, 0, NULL, 0) > -1);
}
/**
* Match regular expression against a string, and populate a referenced vector with an
* array of matches, formatted pretty much like PHP's preg_match().
* Returns true if at least one match was found, false if the string did not match.
*/
bool PCRE::Match(const std::string &comparison, std::vector<std::string>& matches) {
/* Match twice: first to find out how many matches there are, and again to capture them all */
matches.clear();
int matcharr[90];
int matchcount = pcre_exec(compiled_regex, NULL, comparison.c_str(), comparison.length(), 0, 0, matcharr, 90);
if (matchcount == 0) {
throw new regex_exception("Not enough room in matcharr");
}
for (int i = 0; i < matchcount; ++i) {
/* Ugly char ops */
matches.push_back(std::string(comparison.c_str() + matcharr[2 * i], (size_t)(matcharr[2 * i + 1] - matcharr[2 * i])));
}
return matchcount > 0;
}
/**
* Destructor to free compiled regular expression structure
*/
PCRE::~PCRE()
{
/* Ugh, C libraries */
free(compiled_regex);
}
| 36.641975 | 150 | 0.68093 | [
"vector"
] |
bb931e79d193f4d7baeb5c638fb2c1efa7344ed2 | 893 | hpp | C++ | tlab/include/tlab/ext/sqlite3/connection.hpp | gwonhyeong/tlabs | ea0f08441f33af40b28235a48ecb9f545186968d | [
"MIT"
] | null | null | null | tlab/include/tlab/ext/sqlite3/connection.hpp | gwonhyeong/tlabs | ea0f08441f33af40b28235a48ecb9f545186968d | [
"MIT"
] | null | null | null | tlab/include/tlab/ext/sqlite3/connection.hpp | gwonhyeong/tlabs | ea0f08441f33af40b28235a48ecb9f545186968d | [
"MIT"
] | null | null | null | /**
* @file connection.hpp
* @author ghtak
* @brief
* @version 0.1
* @date 2019-01-17
*
* @copyright Copyright (c) 2019
*
*/
#ifndef __tlab_ext_sqlite3_connection_h__
#define __tlab_ext_sqlite3_connection_h__
#include <tlab/internal.hpp>
#include <sqlite3/sqlite3.h>
namespace tlab::ext::sqlite3{
/**
* @brief
*
*/
class connection{
public:
/**
* @brief Construct a new connection object
*
*/
connection(void);
/**
* @brief Destroy the connection object
*
*/
~connection(void);
/**
* @brief
*
* @param info
* @return true
* @return false
*/
bool open(const std::string& info);
bool open(const std::string& info , std::error_code& ec);
/**
* @brief
*
*/
void close(void);
::sqlite3* handle(void);
private:
::sqlite3* _sqlite3;
};
}
#endif | 14.403226 | 61 | 0.56551 | [
"object"
] |
bba420936abafc266a10698042b07453c19f8aed | 2,282 | cpp | C++ | src/utils/CSVReader.cpp | AFriemann/LowCarb | 073e036a5fd6787943c4cbd76ab388dbd830e7d3 | [
"MIT"
] | null | null | null | src/utils/CSVReader.cpp | AFriemann/LowCarb | 073e036a5fd6787943c4cbd76ab388dbd830e7d3 | [
"MIT"
] | 1 | 2018-12-15T13:57:26.000Z | 2018-12-15T13:57:26.000Z | src/utils/CSVReader.cpp | AFriemann/LowCarb | 073e036a5fd6787943c4cbd76ab388dbd830e7d3 | [
"MIT"
] | null | null | null | /**
* @file CSVReader.cpp
* @author see AUTHORS
* @brief CSVReader definitions file.
*/
#include "CSVReader.hpp"
Eigen::MatrixXd CSVReader::read_matrix(
const boost::filesystem::path & matrix_csv_path,
const int dimension)
const {
if (!exists(matrix_csv_path)) {
throw std::runtime_error("file does not exist: " + matrix_csv_path.string());
}
std::ifstream matrix_file;
matrix_file.open(matrix_csv_path.string());
std::string row;
size_t columns = 0;
size_t rows = 0;
Eigen::MatrixXd matrix(dimension, dimension);
while (std::getline(matrix_file, row)){
columns = 0;
size_t begin = 0;
size_t delimiter_position;
std::string entry;
do {
delimiter_position = row.find(',', begin);
entry = row.substr(begin, delimiter_position - begin);
matrix(rows, columns) = std::atof(entry.c_str());
begin = delimiter_position + 1;
columns++;
} while (delimiter_position != std::string::npos);
rows++;
}
return matrix;
}
std::vector<Eigen::Vector3d> CSVReader::read_as_vector(
const boost::filesystem::path &matrix_csv_path)
const {
if (!exists(matrix_csv_path)) {
throw std::runtime_error("file does not exist: " + matrix_csv_path.string());
}
std::ifstream file;
file.open(matrix_csv_path.string());
std::string row;
size_t columns = 0;
size_t rows = 0;
std::vector<Eigen::Vector3d> vector;
while (std::getline(file, row)){
size_t begin = 0;
size_t delimiter_position;
std::string x, y, z;
delimiter_position = row.find(',', begin);
x = row.substr(begin, delimiter_position - begin);
begin = delimiter_position + 1;
delimiter_position = row.find(',', begin);
y = row.substr(begin, delimiter_position - begin);
begin = delimiter_position + 1;
delimiter_position = row.find(',', begin);
z = row.substr(begin, delimiter_position - begin);
Eigen::Vector3d coordinate = Eigen::Vector3d(std::stod(x), std::stod(y), std::stod(z));
vector.push_back(coordinate);
}
return vector;
}
// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| 27.829268 | 96 | 0.616126 | [
"vector"
] |
bbab0116b02b6546575f671f13aa6919a360ce2c | 24,589 | cpp | C++ | UTSvrBrowser.cpp | chrisoldwood/UTSvrBrowser | 341d8b09afdcab5a296df6f074cae47c10637f0f | [
"MIT"
] | 3 | 2017-08-17T15:10:43.000Z | 2021-02-27T04:47:49.000Z | UTSvrBrowser.cpp | chrisoldwood/UTSvrBrowser | 341d8b09afdcab5a296df6f074cae47c10637f0f | [
"MIT"
] | null | null | null | UTSvrBrowser.cpp | chrisoldwood/UTSvrBrowser | 341d8b09afdcab5a296df6f074cae47c10637f0f | [
"MIT"
] | null | null | null | /******************************************************************************
** (C) Chris Oldwood
**
** MODULE: UTSVRBROWSER.CPP
** COMPONENT: The Application.
** DESCRIPTION: The CUTSvrBrowser class definition.
**
*******************************************************************************
*/
#include "Common.hpp"
#include "UTSvrBrowser.hpp"
#include <NCL/WinSock.hpp>
#include <WCL/File.hpp>
#include <WCL/StreamException.hpp>
#include <WCL/StrTok.hpp>
#include <MDBL/WhereCmp.hpp>
#include <MDBL/WhereIn.hpp>
#include <Core/Algorithm.hpp>
/******************************************************************************
**
** Global variables.
**
*******************************************************************************
*/
// "The" application object.
CUTSvrBrowser App;
/******************************************************************************
**
** Class constants.
**
*******************************************************************************
*/
#ifdef _DEBUG
const tchar* CUTSvrBrowser::VERSION = TXT("v1.0 Alpha [Debug]");
#else
const tchar* CUTSvrBrowser::VERSION = TXT("v1.0 Alpha");
#endif
const tchar* CUTSvrBrowser::APP_INI_FILE_VER = TXT("1.0");
const tchar* CUTSvrBrowser::MOD_INI_FILE_VER = TXT("1.0");
const tchar* CUTSvrBrowser::MOD_INI_FILE = TXT("UTSBMods.ini");
const tchar* CUTSvrBrowser::DEF_MASTER_ADDRESS = TXT("unreal.epicgames.com");
int CUTSvrBrowser::DEF_MASTER_PORT = 28900;
int CUTSvrBrowser::DEF_PING_THREADS = 10;
int CUTSvrBrowser::DEF_PING_ATTEMPTS = 3;
uint CUTSvrBrowser::DEF_PING_WAIT_TIME = 1000;
bool CUTSvrBrowser::DEF_AUTO_PING = false;
int CUTSvrBrowser::DEF_PING_INTERVAL = 10;
const tchar* CUTSvrBrowser::CACHE_FILENAME = TXT("UTSvrBrowser.dat");
const char* CUTSvrBrowser::CACHE_FILE_MAGIC = "UTSB";
uint16 CUTSvrBrowser::CACHE_FILE_VER = 0x000A;
/******************************************************************************
** Method: Constructor
**
** Description: Default constructor.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
CUTSvrBrowser::CUTSvrBrowser()
: CApp(m_AppWnd, m_AppCmds)
, m_AppCmds(m_AppWnd)
, m_oModIniFile(CPath::ApplicationDir(), MOD_INI_FILE)
, m_nSortCol(CAppDlg::HOST_NAME)
, m_nSortDir(CSortColumns::ASC)
, m_bDetectFavs(true)
, m_oMods()
, m_oGameTypes()
, m_oServers()
, m_oFavFiles()
, m_oFavourites()
, m_oSummary()
, m_bFltEdited(false)
, m_pFilter(nullptr)
, m_oRS(m_oServers)
, m_strCacheFile(CPath::ApplicationDir(), CACHE_FILENAME)
, m_nPingTimerID(0)
, m_nLastFound(-1)
{
}
/******************************************************************************
** Method: Destructor
**
** Description: Cleanup.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
CUTSvrBrowser::~CUTSvrBrowser()
{
// Cleanup filters.
Core::deleteAll(m_aoFilters);
}
/******************************************************************************
** Method: OnOpen()
**
** Description: Initialises the application.
**
** Parameters: None.
**
** Returns: true or false.
**
*******************************************************************************
*/
bool CUTSvrBrowser::OnOpen()
{
// Set the app title.
m_strTitle = TXT("UT Server Browser");
// Load settings.
LoadAppConfig();
// Initialise WinSock.
int nResult = CWinSock::Startup(1, 1);
if (nResult != 0)
{
FatalMsg(TXT("Failed to initialise WinSock layer: %d."), nResult);
return false;
}
// Create the main window.
if (!m_AppWnd.Create())
return false;
// Show it.
if (!m_rcLastPos.Empty())
m_AppWnd.Move(m_rcLastPos);
m_AppWnd.Show(m_iCmdShow);
m_AppCmds.InitialiseUI();
// Create the inital filter menu.
BuildFilterMenu();
// Update UI.
m_AppCmds.UpdateUI();
App.m_AppWnd.UpdateTitle();
try
{
// Server cache exists?
if (m_strCacheFile.Exists())
{
CFile oFile;
uint16 nVersion;
char szMagic[4];
oFile.Open(m_strCacheFile, GENERIC_READ);
// Read file magic.
oFile.Read(szMagic, 4);
// Read file version.
oFile >> nVersion;
// Magic AND version numbers match?
if ( (strncmp(CACHE_FILE_MAGIC, szMagic, 4) == 0)
&& (nVersion == CACHE_FILE_VER) )
{
// Read servers table.
m_oServers.Read(oFile);
}
oFile.Close();
// Fix up any changes to the favourites.
CheckFavourites();
// Apply the current filter.
ApplyFilter();
// Display cached data.
m_AppWnd.m_AppDlg.RefreshView();
}
}
catch (const CStreamException& e)
{
AlertMsg(TXT("Warning: Failed to load backup file:\n\n%s\n\n%s"), m_strCacheFile.c_str(), e.twhat());
}
// Start the ping timer.
StartPingTimer();
return true;
}
/******************************************************************************
** Method: OnClose()
**
** Description: Cleans up the application resources.
**
** Parameters: None.
**
** Returns: true or false.
**
*******************************************************************************
*/
bool CUTSvrBrowser::OnClose()
{
// Stop the ping timer.
StopPingTimer();
try
{
CFile oFile;
uint16 nVersion = CACHE_FILE_VER;
oFile.Create(m_strCacheFile);
// Write file magic.
oFile.Write(CACHE_FILE_MAGIC, 4);
// Write file version.
oFile << nVersion;
// Write servers table.
m_oServers.Write(oFile);
oFile.Close();
}
catch (const CStreamException& e)
{
AlertMsg(TXT("Warning: Failed to save backup file:\n\n%s\n\n%s"), m_strCacheFile.c_str(), e.twhat());
}
// Terminate WinSock.
CWinSock::Cleanup();
// Save settings.
SaveAppConfig();
return true;
}
/******************************************************************************
** Method: LoadAppConfig()
**
** Description: Load the app configuration.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::LoadAppConfig()
{
// Read the file versions.
CString strAppVer = m_oAppIniFile.ReadString(TXT("Version"), TXT("Version"), APP_INI_FILE_VER);
CString strModsVer = m_oModIniFile.ReadString(TXT("Version"), TXT("Version"), MOD_INI_FILE_VER);
// Read the window pos and size.
m_rcLastPos.left = m_oAppIniFile.ReadInt(TXT("UI"), TXT("Left"), 0);
m_rcLastPos.top = m_oAppIniFile.ReadInt(TXT("UI"), TXT("Top"), 0);
m_rcLastPos.right = m_oAppIniFile.ReadInt(TXT("UI"), TXT("Right"), 0);
m_rcLastPos.bottom = m_oAppIniFile.ReadInt(TXT("UI"), TXT("Bottom"), 0);
// Read the master server query settings.
m_oMtrQryOpts.m_strAddress = m_oAppIniFile.ReadString(TXT("Master"), TXT("Address"), DEF_MASTER_ADDRESS);
m_oMtrQryOpts.m_nPort = m_oAppIniFile.ReadInt (TXT("Master"), TXT("Port"), DEF_MASTER_PORT );
m_oMtrQryOpts.m_bFirewall = m_oAppIniFile.ReadBool (TXT("Master"), TXT("Firewall"), false );
m_oMtrQryOpts.m_nFirstPort = m_oAppIniFile.ReadInt (TXT("Master"), TXT("FirstPort"), 0 );
m_oMtrQryOpts.m_nLastPort = m_oAppIniFile.ReadInt (TXT("Master"), TXT("LastPort"), 65535 );
m_oMtrQryOpts.m_bTrimSpace = m_oAppIniFile.ReadBool (TXT("Master"), TXT("TrimSpace"), false );
m_oMtrQryOpts.m_bConvertSyms = m_oAppIniFile.ReadBool (TXT("Master"), TXT("ConvSyms"), false );
// Read the sorting options.
m_nSortCol = m_oAppIniFile.ReadInt(TXT("View"), TXT("SortCol"), m_nSortCol);
m_nSortDir = m_oAppIniFile.ReadInt(TXT("View"), TXT("SortDir"), m_nSortDir);
// Read the list of column widths.
for (int i = 0; i < CAppDlg::NUM_COLUMNS; ++i)
{
CString strEntry;
strEntry.Format(TXT("Column[%d]"), i);
m_anColWidths.push_back(m_oAppIniFile.ReadInt(TXT("View"), strEntry, CAppDlg::DEF_COLUMN_WIDTH));
}
// Read pinging settings.
m_oPingOpts.m_nThreads = m_oAppIniFile.ReadInt (TXT("Ping"), TXT("Threads"), DEF_PING_THREADS );
m_oPingOpts.m_nAttempts = m_oAppIniFile.ReadInt (TXT("Ping"), TXT("Attempts"), DEF_PING_ATTEMPTS );
m_oPingOpts.m_nWaitTime = m_oAppIniFile.ReadInt (TXT("Ping"), TXT("WaitTime"), DEF_PING_WAIT_TIME);
m_oPingOpts.m_bAutoPing = m_oAppIniFile.ReadBool(TXT("Ping"), TXT("AutoPing"), DEF_AUTO_PING );
m_oPingOpts.m_nAutoInterval = m_oAppIniFile.ReadInt (TXT("Ping"), TXT("Interval"), DEF_PING_INTERVAL );
// Read the filters.
int nFilters = m_oAppIniFile.ReadInt(TXT("Filters"), TXT("Count"), 0);
for (int i = 0; i < nFilters; ++i)
{
CString strSection, strEntry;
strEntry.Format(TXT("Filter[%d]"), i);
// Get next filter name.
CString strFilterName = m_oAppIniFile.ReadString(TXT("Filters"), strEntry, TXT(""));
if (strFilterName.Empty())
continue;
strSection.Format(TXT("%s Filter"), strFilterName.c_str());
// Read the filter definition.
CString strName = m_oAppIniFile.ReadString(strSection, TXT("Name"), TXT(""));
// Ignore, if invalid.
if (strName.Empty())
continue;
// Create filter and read full defintion.
CFilter* pFilter = new CFilter;
pFilter->m_strName = strName;
pFilter->m_strDesc = m_oAppIniFile.ReadString (strSection, TXT("Description"), TXT(""));
pFilter->m_bFltMods = m_oAppIniFile.ReadBool (strSection, TXT("FilterMods"), false);
pFilter->m_astrMods = m_oAppIniFile.ReadStrings(strSection, TXT("Mods"), ',', TXT(""));
pFilter->m_bFltPing = m_oAppIniFile.ReadBool (strSection, TXT("FilterPing"), false);
pFilter->m_nPingTime = m_oAppIniFile.ReadInt (strSection, TXT("PingTime"), 250);
pFilter->m_bFltErrors = m_oAppIniFile.ReadBool (strSection, TXT("FilterErrors"), true);
pFilter->m_bFltNames = m_oAppIniFile.ReadBool (strSection, TXT("FilterNames"), false);
pFilter->m_astrNames = m_oAppIniFile.ReadStrings(strSection, TXT("Names"), ',', TXT(""));
// Add to collection.
m_aoFilters.push_back(pFilter);
}
// Load the other configs.
LoadModsConfig();
LoadFavsConfig();
LoadFavourites();
// Set filter to last used.
m_pFilter = FindFilter(m_oAppIniFile.ReadString(TXT("Filters"), TXT("Default"), TXT("")));
}
/******************************************************************************
** Method: SaveAppConfig()
**
** Description: Save the app configuration.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::SaveAppConfig()
{
// Write the file version.
m_oAppIniFile.WriteString(TXT("Version"), TXT("Version"), APP_INI_FILE_VER);
// Write the window pos and size.
m_oAppIniFile.WriteInt(TXT("UI"), TXT("Left"), m_rcLastPos.left );
m_oAppIniFile.WriteInt(TXT("UI"), TXT("Top"), m_rcLastPos.top );
m_oAppIniFile.WriteInt(TXT("UI"), TXT("Right"), m_rcLastPos.right );
m_oAppIniFile.WriteInt(TXT("UI"), TXT("Bottom"), m_rcLastPos.bottom);
if (m_oMtrQryOpts.m_bModified)
{
// Write the master server query settings.
m_oAppIniFile.WriteString(TXT("Master"), TXT("Address"), m_oMtrQryOpts.m_strAddress );
m_oAppIniFile.WriteInt (TXT("Master"), TXT("Port"), m_oMtrQryOpts.m_nPort );
m_oAppIniFile.WriteBool (TXT("Master"), TXT("Firewall"), m_oMtrQryOpts.m_bFirewall );
m_oAppIniFile.WriteInt (TXT("Master"), TXT("FirstPort"), m_oMtrQryOpts.m_nFirstPort );
m_oAppIniFile.WriteInt (TXT("Master"), TXT("LastPort"), m_oMtrQryOpts.m_nLastPort );
m_oAppIniFile.WriteBool (TXT("Master"), TXT("TrimSpace"), m_oMtrQryOpts.m_bTrimSpace );
m_oAppIniFile.WriteBool (TXT("Master"), TXT("ConvSyms"), m_oMtrQryOpts.m_bConvertSyms);
}
// Write the sorting options.
m_oAppIniFile.WriteInt(TXT("View"), TXT("SortCol"), m_nSortCol);
m_oAppIniFile.WriteInt(TXT("View"), TXT("SortDir"), m_nSortDir);
// Write the list of column widths.
for (int i = 0; i < CAppDlg::NUM_COLUMNS; ++i)
{
CString strEntry;
strEntry.Format(TXT("Column[%d]"), i);
m_oAppIniFile.WriteInt(TXT("View"), strEntry, m_anColWidths[i]);
}
if (m_oPingOpts.m_bModified)
{
// Write pinging settings.
m_oAppIniFile.WriteInt (TXT("Ping"), TXT("Threads"), m_oPingOpts.m_nThreads );
m_oAppIniFile.WriteInt (TXT("Ping"), TXT("Attempts"), m_oPingOpts.m_nAttempts );
m_oAppIniFile.WriteInt (TXT("Ping"), TXT("WaitTime"), m_oPingOpts.m_nWaitTime );
m_oAppIniFile.WriteBool(TXT("Ping"), TXT("AutoPing"), m_oPingOpts.m_bAutoPing );
m_oAppIniFile.WriteInt (TXT("Ping"), TXT("Interval"), m_oPingOpts.m_nAutoInterval);
}
if (m_bFltEdited)
{
// Write the filters.
m_oAppIniFile.WriteInt(TXT("Filters"), TXT("Count"), m_aoFilters.size());
for (uint i = 0; i < m_aoFilters.size(); ++i)
{
CFilter* pFilter = m_aoFilters[i];
CString strSection, strEntry;
strEntry.Format(TXT("Filter[%d]"), i);
// Write the filter name.
m_oAppIniFile.WriteString(TXT("Filters"), strEntry, pFilter->m_strName);
strSection.Format(TXT("%s Filter"), pFilter->m_strName.c_str());
// Write the filter definition.
m_oAppIniFile.WriteString (strSection, TXT("Name"), pFilter->m_strName );
m_oAppIniFile.WriteString (strSection, TXT("Description"), pFilter->m_strDesc );
m_oAppIniFile.WriteBool (strSection, TXT("FilterMods"), pFilter->m_bFltMods );
m_oAppIniFile.WriteStrings(strSection, TXT("Mods"), ',', pFilter->m_astrMods );
m_oAppIniFile.WriteBool (strSection, TXT("FilterPing"), pFilter->m_bFltPing );
m_oAppIniFile.WriteInt (strSection, TXT("PingTime"), pFilter->m_nPingTime );
m_oAppIniFile.WriteBool (strSection, TXT("FilterErrors"), pFilter->m_bFltErrors);
m_oAppIniFile.WriteBool (strSection, TXT("FilterNames"), pFilter->m_bFltNames );
m_oAppIniFile.WriteStrings(strSection, TXT("Names"), ',', pFilter->m_astrNames );
}
}
// Save filter last used.
m_oAppIniFile.WriteString(TXT("Filters"), TXT("Default"), (m_pFilter != nullptr) ? m_pFilter->m_strName : TXT(""));
// Ave the other configs.
// SaveModsConfig();
SaveFavsConfig();
}
/******************************************************************************
** Method: LoadModsConfig()
**
** Description: Load the mods configuration.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::LoadModsConfig()
{
// Read the mods configuration.
int nMods = m_oModIniFile.ReadInt(TXT("Mods"), TXT("Count"), 0);
for (int i = 0; i < nMods; ++i)
{
CString strSection, strEntry;
strEntry.Format(TXT("Mod[%d]"), i);
// Get next mod name.
CString strModName = m_oModIniFile.ReadString(TXT("Mods"), strEntry, TXT(""));
if (strModName.Empty())
continue;
// Create the mod table entry.
CRow& mod = m_oMods.CreateRow();
mod[CMods::MOD_NAME] = strModName;
mod[CMods::FAVS_FILE] = m_oModIniFile.ReadString(strModName, TXT("FavsFile"), TXT(""));
m_oMods.InsertRow(mod, false);
// Read the list of game types the mod uses.
CString strGameTypes = m_oModIniFile.ReadString(strModName, TXT("GameTypes"), TXT(""));
if (strGameTypes.Empty())
continue;
CStrArray astrGameTypes;
// Split list of game types.
CStrTok::Split(strGameTypes, TXT(","), astrGameTypes);
// Create game type table entries.
for (size_t j = 0; j < astrGameTypes.Size(); ++j)
{
CRow& oRow = m_oGameTypes.CreateRow();
oRow[CGameTypes::GAME_TYPE] = astrGameTypes[j];
oRow[CGameTypes::MOD_NAME] = strModName;
m_oGameTypes.InsertRow(oRow, false);
}
}
}
/******************************************************************************
** Method: SaveModsConfig()
**
** Description: Save the mods configuration.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::SaveModsConfig()
{
}
/******************************************************************************
** Method: LoadFavsConfig()
**
** Description: Load the favourites configuration.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::LoadFavsConfig()
{
// Read detection setting.
m_bDetectFavs = m_oAppIniFile.ReadBool(TXT("Favourites"), TXT("Detect"), m_bDetectFavs);
// Read the favourite files configuration.
for (size_t i = 0; i < m_oMods.RowCount(); ++i)
{
CRow& oMod = m_oMods[i];
CString strFile = m_oAppIniFile.ReadString(TXT("Favourites"), oMod[CMods::MOD_NAME], TXT(""));
// Ignore if not set.
if (strFile.Empty())
continue;
// Add to favourite config files table.
CRow& oRow = m_oFavFiles.CreateRow();
oRow[CFavFiles::MOD_NAME] = oMod[CMods::MOD_NAME];
oRow[CFavFiles::MOD_FILE] = strFile;
m_oFavFiles.InsertRow(oRow, false);
}
}
/******************************************************************************
** Method: LoadFavsConfig()
**
** Description: Load the favourites configuration.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::LoadFavourites()
{
// Delete old entries.
m_oFavourites.Truncate();
// Read the favourites from the config files.
for (size_t i = 0; i < m_oFavFiles.RowCount(); ++i)
{
CRow& oFavFile = m_oFavFiles[i];
CIniFile oIniFile(oFavFile[CFavFiles::MOD_FILE]);
// Ignore if file doesn't exist.
if (!oIniFile.m_strPath.Exists())
continue;
// Read number of favourites in file.
int nFavs = oIniFile.ReadInt(TXT("UBrowser.UBrowserFavoritesFact"), TXT("FavoriteCount"), 0);
// Read all favourites.
for (int j = 0; j < nFavs; ++j)
{
CString strEntry;
strEntry.Format(TXT("Favorites[%d]"), j);
// Format: Favorites[?]=Name\Address\Port\Flag
CStrArray astrFavInfo = oIniFile.ReadStrings(TXT("UBrowser.UBrowserFavoritesFact"), strEntry, '\\', TXT(""));
// Invalid entry?
if (astrFavInfo.Size() != 4)
continue;
// Generate IP Key.
CString strKey = astrFavInfo[1] + TXT(":") + astrFavInfo[2];
// Add to favourites table.
CRow& oRow = m_oFavourites.CreateRow();
oRow[CFavourites::IP_KEY] = strKey;
oRow[CFavourites::MOD_NAME] = oFavFile[CFavFiles::MOD_NAME];
oRow[CFavourites::FAV_ID] = j;
m_oFavourites.InsertRow(oRow, false);
}
}
}
/******************************************************************************
** Method: SaveFavsConfig()
**
** Description: Save the favourites configuration.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::SaveFavsConfig()
{
if (App.m_oFavFiles.Modified())
{
// Delete entire secetion.
m_oAppIniFile.DeleteSection(TXT("Favourites"));
// Write the favourites config files.
for (size_t i = 0; i < App.m_oFavFiles.RowCount(); ++i)
{
CRow& oRow = App.m_oFavFiles[i];
m_oAppIniFile.WriteString(TXT("Favourites"), oRow[CFavFiles::MOD_NAME], oRow[CFavFiles::MOD_FILE]);
}
}
// Write detection setting.
m_oAppIniFile.WriteBool(TXT("Favourites"), TXT("Detect"), m_bDetectFavs);
}
/******************************************************************************
** Method: StartPingTimer()
**
** Description: Start the background ping timer.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::StartPingTimer()
{
if (m_nPingTimerID == 0)
m_nPingTimerID = StartTimer(m_oPingOpts.m_nAutoInterval * 1000);
}
/******************************************************************************
** Method: StopPingTimer()
**
** Description: Stop the background ping timer.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::StopPingTimer()
{
if (m_nPingTimerID != 0)
StopTimer(m_nPingTimerID);
m_nPingTimerID = 0;
}
/******************************************************************************
** Method: FindFilter()
**
** Description: Finds a filter by its name.
**
** Parameters: pszName The filters name.
**
** Returns: The filter or nullptr.
**
*******************************************************************************
*/
CFilter* CUTSvrBrowser::FindFilter(const tchar* pszName) const
{
// For all filters.
for (uint i = 0; i < m_aoFilters.size(); ++i)
{
CFilter* pFilter = m_aoFilters[i];
if (pFilter->m_strName == pszName)
return pFilter;
}
return nullptr;
}
/******************************************************************************
** Method: FilterIndex()
**
** Description: Gets the index of the given filter.
**
** Parameters: pFilter The filter.
**
** Returns: The index or -1.
**
*******************************************************************************
*/
int CUTSvrBrowser::FilterIndex(CFilter* pFilter) const
{
// For all filters.
for (uint i = 0; i < m_aoFilters.size(); ++i)
{
if (m_aoFilters[i] == pFilter)
return i;
}
return -1;
}
/******************************************************************************
** Method: ApplyFilter()
**
** Description: Applies the current filter to the server list.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::ApplyFilter()
{
// Start with all servers.
App.m_oRS = App.m_oServers.SelectAll();
// No filter in use?
if (m_pFilter == nullptr)
return;
// Filter by ping times?
if (m_pFilter->m_bFltPing)
App.m_oRS = App.m_oRS.Select(CWhereCmp(CServers::PING_TIME, CWhereCmp::LESS, m_pFilter->m_nPingTime));
// Filter errors?
if (m_pFilter->m_bFltErrors)
App.m_oRS = App.m_oRS.Select(CWhereCmp(CServers::LAST_ERROR, CWhereCmp::EQUALS, CServers::ERROR_NONE));
// Filter mods?
if (m_pFilter->m_bFltMods)
App.m_oRS = App.m_oRS.Select(CWhereIn(CServers::MOD_NAME, m_pFilter->m_astrMods));
// Filter server names?
if (m_pFilter->m_bFltNames)
{
CResultSet oRS(App.m_oServers);
// For all rows...
for (size_t i = 0; i < App.m_oRS.Count(); ++i)
{
CRow& oRow = App.m_oRS[i];
CString strName = CString(oRow[CServers::HOST_NAME]).ToLower();
bool bMatch = false;
// Matches any name in the filter?
for (size_t j = 0; ((j < m_pFilter->m_astrNames.Size()) && (!bMatch)); ++j)
{
if (strName.Find(m_pFilter->m_astrNames[j]) != -1)
bMatch = true;
}
// Matches name list?
if (bMatch)
oRS.Add(oRow);
}
App.m_oRS = oRS;
}
}
/******************************************************************************
** Method: BuildFilterMenu()
**
** Description: Build the filters main menu.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::BuildFilterMenu()
{
// Get the filters popup menu.
CPopupMenu oMenu = m_AppWnd.m_Menu.GetItemPopup(FILTER_MENU_POS);
// Delete the old filter entries.
while (oMenu.ItemCount() > FILTER_MENU_FIXED_ITEMS)
oMenu.RemoveItem(FIRST_FILTER_CMD_POS);
// Add all new filters.
for (uint i = 0; i < m_aoFilters.size(); ++i)
oMenu.AppendCmd(ID_FIRST_FILTER_CMD+i, m_aoFilters[i]->m_strName);
}
/******************************************************************************
** Method: CheckFavourites()
**
** Description: Processes the main server list to ensure the favourites are
** marked correctly.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::CheckFavourites()
{
// For all servers.
for (size_t i = 0; i < m_oServers.RowCount(); ++i)
{
CRow& oSvrRow = m_oServers[i];
CRow* pFavRow = App.m_oFavourites.SelectRow(CFavourites::IP_KEY, oSvrRow[CServers::IP_KEY].ToValue());
// Update favourites column.
if (pFavRow != nullptr)
oSvrRow[CServers::FAV_ID] = pFavRow->Field(CFavourites::FAV_ID);
else
oSvrRow[CServers::FAV_ID] = null;
}
}
/******************************************************************************
** Method: OnTimer()
**
** Description: The background ping timer has fired.
**
** Parameters: nTimerID The timer ID.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CUTSvrBrowser::OnTimer(uint /*nTimerID*/)
{
// If enabled, ping the selected server.
if (m_oPingOpts.m_bAutoPing)
m_AppCmds.OnServersPing();
}
| 27.784181 | 116 | 0.581114 | [
"object"
] |
bbac594935faee40693759c07990847159596515 | 5,278 | cpp | C++ | basic/cipher.cpp | senlinzhan/socks5 | 144d0c18560a81f5617a8b1092902d2ce2a69144 | [
"MIT"
] | 43 | 2017-10-07T02:29:00.000Z | 2022-03-20T11:39:34.000Z | basic/cipher.cpp | senlinzhan/socks5 | 144d0c18560a81f5617a8b1092902d2ce2a69144 | [
"MIT"
] | 1 | 2020-03-26T16:43:01.000Z | 2020-03-26T16:43:01.000Z | basic/cipher.cpp | senlinzhan/socks5 | 144d0c18560a81f5617a8b1092902d2ce2a69144 | [
"MIT"
] | 26 | 2018-01-05T06:20:51.000Z | 2022-01-10T06:27:12.000Z | #include "cipher.hpp"
#include <assert.h>
Cryptor::Cryptor(const std::string &key, const std::string &iv)
{
assert(key.size() == KEY_SIZE);
assert(iv.size() == BLOCK_SIZE);
for (int i = 0; i < KEY_SIZE; i++)
{
key_[i] = static_cast<Byte>(key[i]);
}
for (int i = 0; i < BLOCK_SIZE; i++)
{
iv_[i] = static_cast<Byte>(iv[i]);
}
}
Cryptor::BufferPtr Cryptor::encrypt(const Byte *in, std::size_t inLength) const
{
ContextPtr ctx(EVP_CIPHER_CTX_new(), contextDeleter);
if (ctx == nullptr)
{
return nullptr;
}
if(EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_cbc(), nullptr,
key_.data(), iv_.data()) != 1)
{
return nullptr;
}
int length1 = inLength + BLOCK_SIZE;
auto result = BufferPtr(new Buffer(length1, 0));
if(EVP_EncryptUpdate(ctx.get(), result->data(), &length1, in, inLength) != 1)
{
return nullptr;
}
int length2 = result->size() - length1;
if(EVP_EncryptFinal_ex(ctx.get(), result->data() + length1, &length2) != 1)
{
return nullptr;
}
result->resize(length1 + length2);
return result;
}
Cryptor::BufferPtr Cryptor::decrypt(const Byte *in, std::size_t inLength) const
{
ContextPtr ctx(EVP_CIPHER_CTX_new(), contextDeleter);
if (ctx == nullptr)
{
return nullptr;
}
if(EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_cbc(), nullptr,
key_.data(), iv_.data()) != 1)
{
return nullptr;
}
int length1 = inLength;
auto result = BufferPtr(new Buffer(length1, 0));
if(EVP_DecryptUpdate(ctx.get(), result->data(), &length1, in, inLength) != 1)
{
return nullptr;
}
int length2 = result->size() - length1;
if(EVP_DecryptFinal_ex(ctx.get(), result->data() + length1, &length2) != 1)
{
return nullptr;
}
result->resize(length1 + length2);
return result;
}
int Cryptor::lengthOfEncryptedData(const Buffer &buff) const
{
int length = 0;
std::copy(buff.begin(), buff.begin() + 4,
reinterpret_cast<unsigned char *>(&length));
return ntohl(length);
}
Cryptor::BufferPtr Cryptor::decryptFrom(bufferevent *inConn) const
{
assert(inConn != nullptr);
int inBuffLength = lengthOfInput(inConn);
if (inBuffLength <= LEN_BYTES)
{
return nullptr;
}
auto buff = readFrom(inConn);
int length = lengthOfEncryptedData(buff);
if (inBuffLength < length + LEN_BYTES)
{
return nullptr;
}
return decrypt(buff.data() + 4, length);
}
bool Cryptor::decryptTransfer(bufferevent *inConn, bufferevent *outConn) const
{
assert(inConn != nullptr);
assert(outConn != nullptr);
int inBuffLength = lengthOfInput(inConn);
if (inBuffLength <= LEN_BYTES)
{
return false;
}
while(lengthOfInput(inConn) > 0)
{
auto buff = readFrom(inConn);
int length = lengthOfEncryptedData(buff);
if (inBuffLength < length + LEN_BYTES)
{
return false;
}
auto decrypted = decrypt(buff.data() + LEN_BYTES, length);
if (decrypted == nullptr)
{
return false;
}
if (bufferevent_write(outConn, decrypted->data(), decrypted->size()) == -1)
{
return false;
}
evbuffer_drain(bufferevent_get_input(inConn), length + LEN_BYTES);
}
return true;
}
bool Cryptor::encryptTransfer(bufferevent *inConn, bufferevent *outConn) const
{
assert(inConn != nullptr);
assert(outConn != nullptr);
auto buff = readFrom(inConn);
if (!encryptTo(outConn, buff.data(), buff.size()))
{
return false;
}
evbuffer_drain(bufferevent_get_input(inConn), buff.size());
return true;
}
bool Cryptor::encryptTo(bufferevent *outConn, const Byte *in, std::size_t inLength) const
{
assert(outConn != nullptr);
auto encrypted = encrypt(in, inLength);
if (encrypted == nullptr)
{
return false;
}
int size = encrypted->size();
int sizeNetwork = htonl(size);
bufferevent_write(outConn, reinterpret_cast<unsigned char *>(&sizeNetwork),
LEN_BYTES);
if (bufferevent_write(outConn, encrypted->data(), encrypted->size()) == -1)
{
return false;
}
return true;
}
Cryptor::Buffer Cryptor::readFrom(bufferevent *inConn) const
{
assert(inConn != nullptr);
auto inBuff = bufferevent_get_input(inConn);
auto inBuffLength = evbuffer_get_length(inBuff);
std::vector<unsigned char> buff(inBuffLength, 0);
evbuffer_copyout(inBuff, buff.data(), buff.size());
return buff;
}
void Cryptor::removeFrom(bufferevent *inConn) const
{
assert(inConn != nullptr);
int inBuffLength = lengthOfInput(inConn);
if (inBuffLength <= LEN_BYTES)
{
return;
}
auto buff = readFrom(inConn);
int length = lengthOfEncryptedData(buff);
if (inBuffLength < length + LEN_BYTES)
{
return;
}
evbuffer_drain(bufferevent_get_input(inConn), length + LEN_BYTES);
}
| 23.251101 | 89 | 0.589996 | [
"vector"
] |
bbae128fa418d9c8edd72302c7f6784c87b7f6ae | 8,871 | cpp | C++ | mapping/src/octomap/octomap_color.cpp | sameeptandon/sail-car-log | 0ee3d598bb09d389bcbd2ebf73cd4b2411e796be | [
"BSD-2-Clause"
] | 1 | 2021-02-24T03:11:13.000Z | 2021-02-24T03:11:13.000Z | mapping/src/octomap/octomap_color.cpp | sameeptandon/sail-car-log | 0ee3d598bb09d389bcbd2ebf73cd4b2411e796be | [
"BSD-2-Clause"
] | null | null | null | mapping/src/octomap/octomap_color.cpp | sameeptandon/sail-car-log | 0ee3d598bb09d389bcbd2ebf73cd4b2411e796be | [
"BSD-2-Clause"
] | 3 | 2015-03-18T14:36:04.000Z | 2018-07-04T02:57:24.000Z | #include <string>
#include <boost/progress.hpp>
#include <pcl/common/transforms.h>
#include <octomap/octomap.h>
#include "cloud_server.h"
#include "parameters.h"
#include "../videoreader/VideoReader.h"
#include "utils/cv_utils.h"
int main(int argc, char** arv)
{
params().initialize();
int start = params().start;
int count = params().count;
int step = params().step;
int end = params().end;
// Load the octomap
boost::shared_ptr<octomap::OcTree> octree;
if (!params().cast_octomap_single)
{
octree.reset((octomap::OcTree*)octomap::OcTree::read(params().octomap_file));
std::cout << "Loaded octree of size " << octree->size() << std::endl;
if (!octree->size())
return 1;
}
// Initialize cloud server
server().initialize(params().pcd_downsampled_dir, params().color_dir,
params().h5_dir, params().map_color_window, params().count);
// Initialize reader
VideoReader reader(params().dset_dir, params().dset_avi);
cv::Mat frame;
std::vector<cv::Point2f> pixels;
std::vector<cv::Point2f> filtered_pixels;
std::vector<cv::Vec3b> pixel_colors;
boost::progress_display show_progress(params().map_color_window);
std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> current_clouds;
std::vector<Eigen::MatrixXi*> current_colors;
server().getCurrentWindow(current_clouds, current_colors);
assert (current_clouds.size() == current_colors.size());
// Reason we iterate over w in the outer loop is so that casting just once gives us
// the highest resolution coloring
std::cout << "window: " << params().map_color_window << std::endl;
for (int w = 0; w < params().map_color_window; w++)
{
reader.setFrame(start);
for (int k = start; k < end; k += step)
{
int num_steps = (k - start) / step;
if (params().handle_occlusions && params().cast_octomap_single)
octree.reset((octomap::OcTree*) octomap::OcTree::read(params().octomap_single_files[num_steps]));
// Read frame
bool success = reader.getNextFrame(frame);
if (!success)
{
std::cout << "Reached end of video before expected" << std::endl;
return 1;
}
Eigen::Matrix4f transform = server().transforms[num_steps];
//server().forward(num_steps);
if (num_steps + w >= current_clouds.size())
break;
pcl::PointCloud<pcl::PointXYZ>::Ptr pcloud(new pcl::PointCloud<pcl::PointXYZ>());
pcl::copyPointCloud(*(current_clouds[num_steps + w]), *pcloud);
// Transform point cloud
// We start with the clouds wrt imu_0
// TODO Could just do all of these transforms to all the clouds beforehand
// Transform to imu_t
pcl::transformPointCloud(*pcloud, *pcloud, transform.inverse().eval());
// Transform to lidar_t
pcl::transformPointCloud(*pcloud, *pcloud, params().T_from_i_to_l);
// Transform to camera_t
pcl::transformPointCloud(*pcloud, *pcloud, params().trans_from_l_to_c);
pcl::transformPointCloud(*pcloud, *pcloud, params().rot_to_c_from_l);
// Filter point cloud
std::vector<int> filtered_indices;
pcl::PointCloud<PointXYZ>::Ptr final_cloud(new pcl::PointCloud<PointXYZ>());
filter_lidar_cloud(pcloud, final_cloud, filtered_indices);
assert (final_cloud->size() == filtered_indices.size());
Eigen::MatrixXi* color = current_colors[num_steps + w];
std::cout << "color: " << color->rows() << ", " << color->cols() << std::endl;
std::cout << "cloud: " << pcloud->size() << std::endl;
// Get colors by projecting the point cloud
if (final_cloud->size() == 0)
continue;
project_cloud_eigen(final_cloud, Eigen::Vector3f::Zero(), Eigen::Matrix3f::Identity(),
params().intrinsics, params().distortions, pixels);
// Filter pixels
std::vector<int> filtered_indices_indices;
filter_pixels(pixels, frame, filtered_pixels, filtered_indices_indices);
std::vector<int> final_indices;
BOOST_FOREACH(int ind, filtered_indices_indices)
{
final_indices.push_back(filtered_indices[ind]);
}
// Project each remaining point back and see if it hits anything
// FIXME
// Get origin of camera in imu 0 frame
Eigen::Vector4f imu_origin = transform.block<4, 1>(0, 3);
Eigen::Vector4f lidar_origin = params().T_from_i_to_l * imu_origin;
//Eigen::Vector4f lidar_origin = params().trans_from_i_to_l * imu_origin;
octomap::point3d lidar_pos(lidar_origin(0), lidar_origin(1), lidar_origin(2));
Eigen::Vector4f camera_origin = params().trans_from_l_to_c * lidar_origin;
octomap::point3d cam_pos(imu_origin(0), imu_origin(1), imu_origin(2));
std::vector<int> octomap_indices;
std::vector<cv::Point2f> octomap_pixels;
// Treat as free space or not
bool ignore_unknown = true; // PARAM
float tol = params().raycast_tol;
if (params().handle_occlusions)
{
for (int j = 0; j < final_indices.size(); j++)
{
int ind = final_indices[j];
if (params().cast_once &&
(*color)(ind, 0) != -1) // Was already set
{
continue;
}
// Original point location in imu_0 frame
pcl::PointXYZ pt = current_clouds[num_steps + w]->at(ind);
octomap::point3d pt_origin(pt.x, pt.y, pt.z);
octomap::point3d ray_end;
double max_range = (pt_origin - cam_pos).norm() + tol;
bool cast_success = octree->castRay(cam_pos, (pt_origin - cam_pos), ray_end, ignore_unknown, max_range);
// Check that ray end didn't hit occluding object in front of the car
if (cast_success && (ray_end - pt_origin).norm() > tol)
{
//std::cout << "pt_origin: " << pt_origin << " ray_end: " << ray_end << " lidar_pos: " << lidar_pos << std::endl;
continue;
}
octomap_indices.push_back(ind);
octomap_pixels.push_back(filtered_pixels[j]);
}
}
else
{
for (int j = 0; j < final_indices.size(); j++)
{
int ind = final_indices[j];
if (params().cast_once &&
(*color)(ind, 0) != -1) // Was already set
{
continue;
}
octomap_indices.push_back(ind);
octomap_pixels.push_back(filtered_pixels[j]);
}
}
// Finally set some colors
//get_pixel_colors(filtered_pixels, frame, pixel_colors);
//assert (pixel_colors.size() == final_indices.size());
get_pixel_colors(octomap_pixels, frame, pixel_colors);
assert (pixel_colors.size() == octomap_pixels.size());
std::cout << "coloring " << pixel_colors.size() << "/" << final_indices.size() << " points" << std::endl;
//for (int j = 0; j < pixel_colors.size(); j++)
for (int j = 0; j < octomap_pixels.size(); j++)
{
// cv gives bgr so reverse
(*color)(octomap_indices[j], 0) = pixel_colors[j][2];
(*color)(octomap_indices[j], 1) = pixel_colors[j][1];
(*color)(octomap_indices[j], 2) = pixel_colors[j][0];
}
// NOTE Remember to not use cast_once if visualizing this
//cv::Mat new_frame = frame;
//set_pixel_colors(filtered_pixels, cv::Vec3b(0, 255, 0), new_frame, 4);
//set_pixel_colors(octomap_pixels, cv::Vec3b(0, 0, 255), new_frame, 4);
//cv::imshow("video", new_frame);
//char k = 0;
//while (k != 113)
//{
//k = cv::waitKey(0);
//}
// Skip
success = reader.skip(step - 1);
if (!success)
{
std::cout << "Reached end of video before expected" << std::endl;
return 1;
}
}
++show_progress;
}
server().saveCurrentColorWindow();
return 0;
}
| 37.910256 | 137 | 0.543456 | [
"object",
"vector",
"transform"
] |
bbb44504b9499e41355294b9ef389f318ddd5096 | 11,538 | cpp | C++ | src/eepp/scene/scenenode.cpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 37 | 2020-01-20T06:21:24.000Z | 2022-03-21T17:44:50.000Z | src/eepp/scene/scenenode.cpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | null | null | null | src/eepp/scene/scenenode.cpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 9 | 2019-03-22T00:33:07.000Z | 2022-03-01T01:35:59.000Z | #include <algorithm>
#include <eepp/graphics/framebuffer.hpp>
#include <eepp/graphics/globalbatchrenderer.hpp>
#include <eepp/graphics/renderer/renderer.hpp>
#include <eepp/graphics/textureregion.hpp>
#include <eepp/scene/actionmanager.hpp>
#include <eepp/scene/scenenode.hpp>
#include <eepp/window/cursormanager.hpp>
#include <eepp/window/engine.hpp>
#include <eepp/window/window.hpp>
namespace EE { namespace Scene {
SceneNode* SceneNode::New( EE::Window::Window* window ) {
return eeNew( SceneNode, ( window ) );
}
SceneNode::SceneNode( EE::Window::Window* window ) :
Node(),
mWindow( window ),
mActionManager( ActionManager::New() ),
mFrameBuffer( NULL ),
mEventDispatcher( NULL ),
mFrameBufferBound( false ),
mUseInvalidation( false ),
mUseGlobalCursors( true ),
mUpdateAllChilds( true ),
mResizeCb( -1 ),
mDrawDebugData( false ),
mDrawBoxes( false ),
mHighlightOver( false ),
mHighlightFocus( false ),
mHighlightInvalidation( false ),
mHighlightFocusColor( 234, 195, 123, 255 ),
mHighlightOverColor( 195, 123, 234, 255 ),
mHighlightInvalidationColor( 220, 0, 0, 255 ) {
mNodeFlags |= NODE_FLAG_SCENENODE;
mSceneNode = this;
enableReportSizeChangeToChilds();
if ( NULL == mWindow ) {
mWindow = Engine::instance()->getCurrentWindow();
}
mResizeCb = mWindow->pushResizeCallback( cb::Make1( this, &SceneNode::resizeNode ) );
DisplayManager* displayManager = Engine::instance()->getDisplayManager();
int currentDisplayIndex = getWindow()->getCurrentDisplayIndex();
Display* currentDisplay = displayManager->getDisplayIndex( currentDisplayIndex );
mDPI = currentDisplay->getDPI();
resizeNode( window );
}
SceneNode::~SceneNode() {
if ( -1 != mResizeCb && NULL != Engine::existsSingleton() &&
Engine::instance()->existsWindow( mWindow ) ) {
mWindow->popResizeCallback( mResizeCb );
}
onClose();
eeSAFE_DELETE( mActionManager );
eeSAFE_DELETE( mEventDispatcher );
eeSAFE_DELETE( mFrameBuffer );
}
void SceneNode::enableFrameBuffer() {
if ( NULL == mFrameBuffer )
createFrameBuffer();
}
void SceneNode::disableFrameBuffer() {
eeSAFE_DELETE( mFrameBuffer );
writeNodeFlag( NODE_FLAG_FRAME_BUFFER, 0 );
}
bool SceneNode::ownsFrameBuffer() const {
return 0 != ( mNodeFlags & NODE_FLAG_FRAME_BUFFER );
}
void SceneNode::draw() {
GlobalBatchRenderer::instance()->draw();
const View& prevView = mWindow->getView();
mWindow->setView( mWindow->getDefaultView() );
if ( mVisible && 0 != mAlpha ) {
updateScreenPos();
preDraw();
ClippingMask* clippingMask = GLi->getClippingMask();
std::list<Rectf> clips = clippingMask->getPlanesClipped();
if ( !clips.empty() )
clippingMask->clipPlaneDisable();
matrixSet();
if ( NULL == mFrameBuffer || !usesInvalidation() || invalidated() ) {
clipStart();
drawChilds();
clipEnd();
}
matrixUnset();
if ( !clips.empty() )
clippingMask->setPlanesClipped( clips );
postDraw();
writeNodeFlag( NODE_FLAG_VIEW_DIRTY, 0 );
}
mWindow->setView( prevView );
GlobalBatchRenderer::instance()->draw();
}
void SceneNode::update( const Time& time ) {
mElapsed = time;
mActionManager->update( time );
if ( NULL != mEventDispatcher )
mEventDispatcher->update( time );
checkClose();
if ( !mScheduledUpdateRemove.empty() ) {
for ( auto it = mScheduledUpdateRemove.begin(); it != mScheduledUpdateRemove.end(); ++it )
mScheduledUpdate.erase( *it );
mScheduledUpdateRemove.clear();
}
if ( !mScheduledUpdate.empty() ) {
for ( auto& node : mScheduledUpdate )
node->scheduledUpdate( time );
}
if ( mUpdateAllChilds ) {
Node::update( time );
} else {
for ( auto& nodeOver : mMouseOverNodes )
nodeOver->writeNodeFlag( NODE_FLAG_MOUSEOVER_ME_OR_CHILD, 0 );
}
mMouseOverNodes.clear();
}
void SceneNode::onSizeChange() {
if ( NULL != mFrameBuffer && ( mFrameBuffer->getWidth() < mSize.getWidth() ||
mFrameBuffer->getHeight() < mSize.getHeight() ) ) {
if ( NULL == mFrameBuffer ) {
createFrameBuffer();
} else {
Sizei fboSize( getFrameBufferSize() );
mFrameBuffer->resize( fboSize.getWidth(), fboSize.getHeight() );
}
}
Node::onSizeChange();
}
void SceneNode::addToCloseQueue( Node* node ) {
eeASSERT( NULL != node );
Node* itNode = NULL;
if ( mCloseList.count( node ) > 0 )
return;
// If the parent is closing all his children, we skip all the verifications and add it to the
// close list
if ( node->getParent() && node->getParent()->isClosingChildren() ) {
mCloseList.insert( node );
return;
}
for ( auto& closeNode : mCloseList ) {
if ( closeNode && closeNode->isParentOf( node ) ) {
// If a parent will be removed, means that the node
// that we are trying to queue will be removed by the father
// so we skip it
return;
}
}
std::vector<CloseList::iterator> itEraseList;
for ( auto it = mCloseList.begin(); it != mCloseList.end(); ++it ) {
itNode = *it;
if ( NULL == itNode || node->isParentOf( itNode ) ) {
// if the node added is parent of another node already added,
// we remove the already added node because it will be deleted
// by its parent
itEraseList.push_back( it );
}
}
// We delete all the nodes that don't need to be deleted
// because of the new added node to the queue
for ( auto ite = itEraseList.begin(); ite != itEraseList.end(); ++ite ) {
mCloseList.erase( *ite );
}
mCloseList.insert( node );
}
void SceneNode::checkClose() {
if ( !mCloseList.empty() ) {
// First we need to create a temporal copy of the close list because it can change its
// content while deleting the elements, since the elements can call to any node close()
// at any moment (and in this case during the deletion of a node).
// Once copied we need to clear the close list and start the new close list for the next
// check.
CloseList closeListCopy( mCloseList );
mCloseList.clear();
for ( Node* node : closeListCopy )
eeDelete( node );
}
}
Sizei SceneNode::getFrameBufferSize() {
return mSize.ceil().asInt();
}
void SceneNode::createFrameBuffer() {
writeNodeFlag( NODE_FLAG_FRAME_BUFFER, 1 );
eeSAFE_DELETE( mFrameBuffer );
Sizei fboSize( getFrameBufferSize() );
if ( fboSize.getWidth() < 1 )
fboSize.setWidth( 1 );
if ( fboSize.getHeight() < 1 )
fboSize.setHeight( 1 );
mFrameBuffer =
FrameBuffer::New( fboSize.getWidth(), fboSize.getHeight(), true, false, false, 4, mWindow );
// Frame buffer failed to create?
if ( !mFrameBuffer->created() ) {
eeSAFE_DELETE( mFrameBuffer );
}
}
void SceneNode::drawFrameBuffer() {
if ( NULL != mFrameBuffer ) {
if ( mFrameBuffer->hasColorBuffer() ) {
mFrameBuffer->draw( Rect( 0, 0, mSize.getWidth(), mSize.getHeight() ),
Rect( mScreenPos.x, mScreenPos.y, mScreenPos.x + mSize.getWidth(),
mScreenPos.y + mSize.getHeight() ) );
} else {
Rect r = Rect( 0, 0, mSize.getWidth(), mSize.getHeight() );
TextureRegion textureRegion( mFrameBuffer->getTexture()->getTextureId(), r,
r.getSize().asFloat() );
textureRegion.draw( mScreenPosi.x, mScreenPosi.y, Color::White, getRotation(),
getScale() );
}
}
}
void SceneNode::enableDrawInvalidation() {
mUseInvalidation = true;
}
void SceneNode::disableDrawInvalidation() {
mUseInvalidation = false;
}
EE::Window::Window* SceneNode::getWindow() {
return mWindow;
}
void SceneNode::matrixSet() {
if ( NULL != mFrameBuffer ) {
if ( !mUseInvalidation || invalidated() ) {
mFrameBufferBound = true;
mFrameBuffer->bind();
mFrameBuffer->clear();
}
if ( 0.f != mScreenPos ) {
GLi->pushMatrix();
GLi->translatef( -mScreenPos.x, -mScreenPos.y, 0.f );
}
} else {
Node::matrixSet();
}
}
void SceneNode::matrixUnset() {
if ( NULL != mFrameBuffer ) {
GlobalBatchRenderer::instance()->draw();
if ( 0.f != mScreenPos )
GLi->popMatrix();
if ( mFrameBufferBound ) {
mFrameBuffer->unbind();
mFrameBufferBound = false;
}
drawFrameBuffer();
} else {
Node::matrixUnset();
}
}
void SceneNode::sendMsg( Node* node, const Uint32& msg, const Uint32& flags ) {
NodeMessage tMsg( node, msg, flags );
node->messagePost( &tMsg );
}
void SceneNode::resizeNode( EE::Window::Window* ) {
setSize( (Float)mWindow->getWidth(), (Float)mWindow->getHeight() );
sendMsg( this, NodeMessage::WindowResize );
}
FrameBuffer* SceneNode::getFrameBuffer() const {
return mFrameBuffer;
}
void SceneNode::setEventDispatcher( EventDispatcher* eventDispatcher ) {
mEventDispatcher = eventDispatcher;
}
EventDispatcher* SceneNode::getEventDispatcher() const {
return mEventDispatcher;
}
void SceneNode::setDrawDebugData( bool debug ) {
if ( mDrawDebugData != debug ) {
mDrawDebugData = debug;
onDrawDebugDataChange();
}
}
bool SceneNode::getDrawDebugData() const {
return mDrawDebugData;
}
void SceneNode::setDrawBoxes( bool draw ) {
mDrawBoxes = draw;
invalidateDraw();
}
bool SceneNode::getDrawBoxes() const {
return mDrawBoxes;
}
void SceneNode::setHighlightOver( bool Highlight ) {
mHighlightOver = Highlight;
invalidateDraw();
}
bool SceneNode::getHighlightOver() const {
return mHighlightOver;
}
void SceneNode::setHighlightFocus( bool Highlight ) {
mHighlightFocus = Highlight;
invalidateDraw();
}
bool SceneNode::getHighlightFocus() const {
return mHighlightFocus;
}
void SceneNode::setHighlightInvalidation( bool Highlight ) {
mHighlightInvalidation = Highlight;
invalidateDraw();
}
bool SceneNode::getHighlightInvalidation() const {
return mHighlightInvalidation;
}
void SceneNode::setHighlightOverColor( const Color& color ) {
mHighlightOverColor = color;
invalidateDraw();
}
const Color& SceneNode::getHighlightOverColor() const {
return mHighlightOverColor;
}
void SceneNode::setHighlightFocusColor( const Color& color ) {
mHighlightFocusColor = color;
invalidateDraw();
}
const Color& SceneNode::getHighlightFocusColor() const {
return mHighlightFocusColor;
}
void SceneNode::setHighlightInvalidationColor( const Color& color ) {
mHighlightInvalidationColor = color;
invalidateDraw();
}
const Color& SceneNode::getHighlightInvalidationColor() const {
return mHighlightInvalidationColor;
}
const Time& SceneNode::getElapsed() const {
return mElapsed;
}
bool SceneNode::usesInvalidation() {
return mUseInvalidation;
}
void SceneNode::setUseGlobalCursors( const bool& use ) {
mUseGlobalCursors = use;
}
const bool& SceneNode::getUseGlobalCursors() {
return mUseGlobalCursors;
}
void SceneNode::setCursor( Cursor::Type cursor ) {
if ( mUseGlobalCursors ) {
mWindow->getCursorManager()->set( cursor );
}
}
bool SceneNode::isDrawInvalidator() const {
return true;
}
ActionManager* SceneNode::getActionManager() const {
return mActionManager;
}
void SceneNode::preDraw() {}
void SceneNode::postDraw() {}
void SceneNode::onDrawDebugDataChange() {}
void SceneNode::subscribeScheduledUpdate( Node* node ) {
mScheduledUpdate.insert( node );
}
void SceneNode::unsubscribeScheduledUpdate( Node* node ) {
mScheduledUpdateRemove.insert( node );
}
bool SceneNode::isSubscribedForScheduledUpdate( Node* node ) {
return mScheduledUpdate.count( node ) > 0;
}
void SceneNode::addMouseOverNode( Node* node ) {
mMouseOverNodes.insert( node );
}
void SceneNode::removeMouseOverNode( Node* node ) {
mMouseOverNodes.erase( node );
}
const bool& SceneNode::getUpdateAllChilds() const {
return mUpdateAllChilds;
}
void SceneNode::setUpdateAllChilds( const bool& updateAllChilds ) {
mUpdateAllChilds = updateAllChilds;
}
const Float& SceneNode::getDPI() const {
return mDPI;
}
}} // namespace EE::Scene
| 23.546939 | 94 | 0.703935 | [
"vector"
] |
bbb86daf518fcb7fbcf53247fe12da7c9ac47c21 | 1,204 | cpp | C++ | TAI/TP2/src/wav/wavcmp.cpp | lengors/ua-repository | 4a2ff60af8b190783e1992fe8edb40fc1147224a | [
"MIT"
] | null | null | null | TAI/TP2/src/wav/wavcmp.cpp | lengors/ua-repository | 4a2ff60af8b190783e1992fe8edb40fc1147224a | [
"MIT"
] | null | null | null | TAI/TP2/src/wav/wavcmp.cpp | lengors/ua-repository | 4a2ff60af8b190783e1992fe8edb40fc1147224a | [
"MIT"
] | null | null | null | #include <wav/wavcmp.hpp>
#include <vector>
#include <cmath>
std::optional<std::tuple<float, unsigned>> WAV::compare(SndfileHandle &file, SndfileHandle &original, const size_t &buffer_size)
{
if (file.channels() != original.channels())
return {};
int max = 0;
using ld = long double;
ld sum = 0, diff_sum = 0;
const int channels = file.channels();
std::vector<short> vector(buffer_size * channels);
std::vector<short> original_vector(buffer_size * channels);
while (size_t frames = file.readf(vector.data(), buffer_size))
{
size_t original_frames = original.readf(original_vector.data(), buffer_size);
if (original_frames != frames)
return {};
for (unsigned i = 0; i < frames * channels; ++i)
{
short &value = vector[i];
short &original_value = original_vector[i];
sum += original_value * original_value;
int diff = int(original_value) - int(value);
max = std::max(max, std::abs(diff));
diff_sum += diff * diff;
}
}
return std::tuple<float, unsigned>({ 10 * std::log10(sum / diff_sum), max });
} | 37.625 | 129 | 0.58887 | [
"vector"
] |
c7e114628a6b681e5a85d8e5242893b918194863 | 4,982 | cpp | C++ | metric/modules/distance/k-structured/TWED.cpp | Stepka/telegram_clustering_contest | 52a012af2ce821410caa98cba840364710eb4256 | [
"Apache-2.0"
] | 2 | 2019-12-03T17:08:04.000Z | 2021-08-25T05:06:29.000Z | metric/modules/distance/k-structured/TWED.cpp | Stepka/telegram_clustering_contest | 52a012af2ce821410caa98cba840364710eb4256 | [
"Apache-2.0"
] | 1 | 2021-09-02T02:25:51.000Z | 2021-09-02T02:25:51.000Z | metric/modules/distance/k-structured/TWED.cpp | Stepka/telegram_clustering_contest | 52a012af2ce821410caa98cba840364710eb4256 | [
"Apache-2.0"
] | null | null | null | /*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Copyright (c) 2018 Michael Welsch
*/
#ifndef _METRIC_DISTANCE_K_STRUCTURED_TWED_CPP
#define _METRIC_DISTANCE_K_STRUCTURED_TWED_CPP
#include "TWED.hpp"
#include <vector>
namespace metric {
/*** distance measure with time elastic cost matrix. ***/
template <typename V>
template <typename Container>
auto TWED<V>::operator()(const Container& As, const Container& Bs) const -> distance_type
{
std::vector<value_type> A;
A.reserve(As.size());
std::vector<value_type> timeA;
timeA.reserve(As.size());
std::vector<value_type> B;
B.reserve(Bs.size());
std::vector<value_type> timeB;
timeB.reserve(Bs.size());
for (auto it = As.cbegin(); it != As.cend(); ++it) {
timeA.push_back(std::distance(As.begin(), it)); // Read access to the index of the non-zero element.
A.push_back(*it); // Read access to the value of the non-zero element.
}
for (auto it = Bs.cbegin(); it != Bs.cend(); ++it) {
timeB.push_back(std::distance(Bs.begin(), it)); // Read access to the index of the non-zero element.
B.push_back(*it); // Read access to the value of the non-zero element.
}
value_type C1, C2, C3;
int sizeB = B.size();
int sizeA = A.size();
std::vector<value_type> D0(sizeB);
std::vector<value_type> Di(sizeA);
// first element
D0[0] = std::abs(A[0] - B[0]) + elastic * (std::abs(timeA[0] - 0)); // C3
// first row
for (int j = 1; j < sizeB; j++) {
D0[j] = D0[j - 1] + std::abs(B[j - 1] - B[j]) + elastic * (timeB[j] - timeB[j - 1]) + penalty; // C2
}
// second-->last row
for (int i = 1; i < sizeA; i++) {
// every first element in row
Di[0] = D0[0] + std::abs(A[i - 1] - A[i]) + elastic * (timeA[i] - timeA[i - 1]) + penalty; // C1
// remaining elements in row
for (int j = 1; j < sizeB; j++) {
C1 = D0[j] + std::abs(A[i - 1] - A[i]) + elastic * (timeA[i] - timeA[i - 1]) + penalty;
C2 = Di[j - 1] + std::abs(B[j - 1] - B[j]) + elastic * (timeB[j] - timeB[j - 1]) + penalty;
C3 = D0[j - 1] + std::abs(A[i] - B[j]) + std::abs(A[i - 1] - B[j - 1])
+ elastic * (std::abs(timeA[i] - timeB[j]) + std::abs(timeA[i - 1] - timeB[j - 1]));
Di[j] = (C1 < ((C2 < C3) ? C2 : C3)) ? C1 : ((C2 < C3) ? C2 : C3); // Di[j] = std::min({C1,C2,C3});
//std::cout << Di[j] << " [" << C1 << " " << C2 << " " << C3 << "] | "; // code for debug, added by Max F
}
//std::cout << "\n"; // code for debug, added by Max F
std::swap(D0, Di);
}
distance_type rvalue = D0[sizeB - 1];
return rvalue;
}
namespace TWED_details {
/** add zero padding to sparsed vector (preprocessing for time elatic distance) **/
template <typename T>
blaze::CompressedVector<T> addZeroPadding(blaze::CompressedVector<T> const& data)
{
// adds zero pads to blaze::sparsevector (for preparing sed)
blaze::CompressedVector<T> data_zeropadded(data.size());
data_zeropadded.reserve(2 + data.nonZeros() * 2);
T value;
bool addZeroFront;
bool addZeroLastBack;
int index;
int index_last = -1;
if (data.nonZeros() == 0) {
data_zeropadded.set(0, T(0));
data_zeropadded.set(data.size() - 1, T(0));
} else {
for (blaze::CompressedVector<double>::ConstIterator it = data.cbegin(); it != data.cend(); ++it) {
index = it->index(); // Read access to the index of the non-zero element.
value = it->value(); // Read access to the value of the non-zero element.
if (index == index_last + 1)
addZeroFront = false;
else
addZeroFront = true;
if (index > index_last + 1 && index != 1 && index != index_last + 2)
addZeroLastBack = true;
else
addZeroLastBack = false;
if (addZeroLastBack == true)
data_zeropadded.append(index_last + 1, T(0));
if (addZeroFront == true)
data_zeropadded.append(index - 1, T(0));
data_zeropadded.append(index, value);
index_last = index;
}
if (index_last < int(data.size()) - 2) // vorletzter nicht vorhanden
{
data_zeropadded.append(index_last + 1, T(0));
}
if (index_last < int(data.size()) - 1) {
data_zeropadded.append(data.size() - 1, T(0));
}
}
shrinkToFit(data_zeropadded);
return data_zeropadded;
}
} // namespace TWED_details
} // namespace metric
#endif // header guard
| 35.585714 | 118 | 0.539141 | [
"vector"
] |
c7f31071d92f4dbc3dcaf85b8bcd0fbbddb8b393 | 16,660 | cpp | C++ | NEST-14.0-FPGA/nestkernel/model_manager.cpp | OpenHEC/SNN-simulator-on-PYNQcluster | 14f86a76edf4e8763b58f84960876e95d4efc43a | [
"MIT"
] | 45 | 2019-12-09T06:45:53.000Z | 2022-01-29T12:16:41.000Z | NEST-14.0-FPGA/nestkernel/model_manager.cpp | zlchai/SNN-simulator-on-PYNQcluster | 14f86a76edf4e8763b58f84960876e95d4efc43a | [
"MIT"
] | 2 | 2020-05-23T05:34:21.000Z | 2021-09-08T02:33:46.000Z | NEST-14.0-FPGA/nestkernel/model_manager.cpp | OpenHEC/SNN-simulator-on-PYNQcluster | 14f86a76edf4e8763b58f84960876e95d4efc43a | [
"MIT"
] | 10 | 2019-12-09T06:45:59.000Z | 2021-03-25T09:32:56.000Z | /*
* model_manager.cpp
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "model_manager.h"
// C++ includes:
#include <algorithm>
#include <iostream>
#include <vector>
// Includes from libnestutil:
#include "compose.hpp"
// Includes from nestkernel:
#include "genericmodel_impl.h"
#include "kernel_manager.h"
#include "model_manager_impl.h"
#include "proxynode.h"
#include "sibling_container.h"
#include "subnet.h"
namespace nest
{
ModelManager::ModelManager()
: pristine_models_()
, models_()
, pristine_prototypes_()
, prototypes_()
, modeldict_( new Dictionary )
, synapsedict_( new Dictionary )
, subnet_model_( 0 )
, siblingcontainer_model_( 0 )
, proxynode_model_( 0 )
, proxy_nodes_()
, dummy_spike_sources_()
, model_defaults_modified_( false )
{
}
ModelManager::~ModelManager()
{
clear_models_( true );
clear_prototypes_();
// Now we can delete the clean model prototypes
std::vector< ConnectorModel* >::iterator i;
for ( i = pristine_prototypes_.begin(); i != pristine_prototypes_.end(); ++i )
{
if ( *i != 0 )
{
delete *i;
}
}
std::vector< std::pair< Model*, bool > >::iterator j;
for ( j = pristine_models_.begin(); j != pristine_models_.end(); ++j )
{
if ( ( *j ).first != 0 )
{
delete ( *j ).first;
}
}
}
void
ModelManager::initialize()
{
if ( subnet_model_ == 0 && siblingcontainer_model_ == 0
&& proxynode_model_ == 0 )
{
// initialize these models only once outside of the constructor
// as the node model asks for the # of threads to setup slipools
// but during construction of ModelManager, the KernelManager is not created
subnet_model_ = new GenericModel< Subnet >( "subnet",
/* deprecation_info */ "NEST 3.0" );
subnet_model_->set_type_id( 0 );
pristine_models_.push_back(
std::pair< Model*, bool >( subnet_model_, false ) );
siblingcontainer_model_ =
new GenericModel< SiblingContainer >( std::string( "siblingcontainer" ),
/* deprecation_info */ "" );
siblingcontainer_model_->set_type_id( 1 );
pristine_models_.push_back(
std::pair< Model*, bool >( siblingcontainer_model_, true ) );
proxynode_model_ =
new GenericModel< proxynode >( "proxynode", /* deprecation_info */ "" );
proxynode_model_->set_type_id( 2 );
pristine_models_.push_back(
std::pair< Model*, bool >( proxynode_model_, true ) );
}
// Re-create the model list from the clean prototypes
for ( index i = 0; i < pristine_models_.size(); ++i )
{
if ( pristine_models_[ i ].first != 0 )
{
// set the num of threads for the number of sli pools
pristine_models_[ i ].first->set_threads();
std::string name = pristine_models_[ i ].first->get_name();
models_.push_back( pristine_models_[ i ].first->clone( name ) );
if ( not pristine_models_[ i ].second )
{
modeldict_->insert( name, i );
}
}
}
// create proxy nodes, one for each thread and model
proxy_nodes_.resize( kernel().vp_manager.get_num_threads() );
int proxy_model_id = get_model_id( "proxynode" );
for ( thread t = 0;
t < static_cast< thread >( kernel().vp_manager.get_num_threads() );
++t )
{
for ( index i = 0; i < pristine_models_.size(); ++i )
{
if ( pristine_models_[ i ].first != 0 )
{
Node* newnode = proxynode_model_->allocate( t );
newnode->set_model_id( i );
proxy_nodes_[ t ].push_back( newnode );
}
}
Node* newnode = proxynode_model_->allocate( t );
newnode->set_model_id( proxy_model_id );
dummy_spike_sources_.push_back( newnode );
}
synapsedict_->clear();
// one list of prototypes per thread
std::vector< std::vector< ConnectorModel* > > tmp_proto(
kernel().vp_manager.get_num_threads() );
prototypes_.swap( tmp_proto );
// (re-)append all synapse prototypes
for (
std::vector< ConnectorModel* >::iterator i = pristine_prototypes_.begin();
i != pristine_prototypes_.end();
++i )
{
if ( *i != 0 )
{
std::string name = ( *i )->get_name();
for ( thread t = 0;
t < static_cast< thread >( kernel().vp_manager.get_num_threads() );
++t )
{
prototypes_[ t ].push_back( ( *i )->clone( name ) );
}
synapsedict_->insert( name, prototypes_[ 0 ].size() - 1 );
}
}
}
void
ModelManager::finalize()
{
clear_models_();
clear_prototypes_();
delete_secondary_events_prototypes();
// We free all Node memory
std::vector< std::pair< Model*, bool > >::iterator m;
for ( m = pristine_models_.begin(); m != pristine_models_.end(); ++m )
{
// delete all nodes, because cloning the model may have created instances.
( *m ).first->clear();
}
}
void
ModelManager::set_status( const DictionaryDatum& )
{
}
void
ModelManager::get_status( DictionaryDatum& )
{
}
index
ModelManager::copy_model( Name old_name, Name new_name, DictionaryDatum params )
{
if ( modeldict_->known( new_name ) || synapsedict_->known( new_name ) )
{
throw NewModelNameExists( new_name );
}
const Token oldnodemodel = modeldict_->lookup( old_name );
const Token oldsynmodel = synapsedict_->lookup( old_name );
index new_id;
if ( not oldnodemodel.empty() )
{
index old_id = static_cast< index >( oldnodemodel );
new_id = copy_node_model_( old_id, new_name );
set_node_defaults_( new_id, params );
}
else if ( not oldsynmodel.empty() )
{
index old_id = static_cast< index >( oldsynmodel );
new_id = copy_synapse_model_( old_id, new_name );
set_synapse_defaults_( new_id, params );
}
else
{
throw UnknownModelName( old_name );
}
return new_id;
}
index
ModelManager::register_node_model_( Model* model, bool private_model )
{
const index id = models_.size();
model->set_model_id( id );
model->set_type_id( id );
std::string name = model->get_name();
pristine_models_.push_back(
std::pair< Model*, bool >( model, private_model ) );
models_.push_back( model->clone( name ) );
int proxy_model_id = get_model_id( "proxynode" );
assert( proxy_model_id > 0 );
Model* proxy_model = models_[ proxy_model_id ];
assert( proxy_model != 0 );
for ( thread t = 0;
t < static_cast< thread >( kernel().vp_manager.get_num_threads() );
++t )
{
Node* newnode = proxy_model->allocate( t );
newnode->set_model_id( id );
proxy_nodes_[ t ].push_back( newnode );
}
if ( not private_model )
{
modeldict_->insert( name, id );
}
return id;
}
index
ModelManager::copy_node_model_( index old_id, Name new_name )
{
Model* old_model = get_model( old_id );
old_model->deprecation_warning( "CopyModel" );
Model* new_model = old_model->clone( new_name.toString() );
models_.push_back( new_model );
index new_id = models_.size() - 1;
modeldict_->insert( new_name, new_id );
for ( thread t = 0;
t < static_cast< thread >( kernel().vp_manager.get_num_threads() );
++t )
{
Node* newnode = proxynode_model_->allocate( t );
newnode->set_model_id( new_id );
proxy_nodes_[ t ].push_back( newnode );
}
return new_id;
}
index
ModelManager::copy_synapse_model_( index old_id, Name new_name )
{
size_t new_id = prototypes_[ 0 ].size();
if ( new_id == invalid_synindex ) // we wrapped around (=255), maximal id of
// synapse_model = 254
{
LOG( M_ERROR,
"ModelManager::copy_synapse_model_",
"CopyModel cannot generate another synapse. Maximal synapse model count "
"of 255 exceeded." );
throw KernelException( "Synapse model count exceeded" );
}
assert( new_id != invalid_synindex );
// if the copied synapse is a secondary connector model the synid of the copy
// has to be mapped to the corresponding secondary event type
if ( not get_synapse_prototype( old_id ).is_primary() )
{
( get_synapse_prototype( old_id ).get_event() )->add_syn_id( new_id );
}
for ( thread t = 0;
t < static_cast< thread >( kernel().vp_manager.get_num_threads() );
++t )
{
prototypes_[ t ].push_back(
get_synapse_prototype( old_id ).clone( new_name.toString() ) );
prototypes_[ t ][ new_id ]->set_syn_id( new_id );
}
synapsedict_->insert( new_name, new_id );
return new_id;
}
void
ModelManager::set_model_defaults( Name name, DictionaryDatum params )
{
const Token nodemodel = modeldict_->lookup( name );
const Token synmodel = synapsedict_->lookup( name );
index id;
if ( not nodemodel.empty() )
{
id = static_cast< index >( nodemodel );
set_node_defaults_( id, params );
}
else if ( not synmodel.empty() )
{
id = static_cast< index >( synmodel );
set_synapse_defaults_( id, params );
}
else
{
throw UnknownModelName( name );
}
model_defaults_modified_ = true;
}
void
ModelManager::set_node_defaults_( index model_id,
const DictionaryDatum& params )
{
params->clear_access_flags();
get_model( model_id )->set_status( params );
ALL_ENTRIES_ACCESSED( *params,
"ModelManager::set_node_defaults_",
"Unread dictionary entries: " );
}
void
ModelManager::set_synapse_defaults_( index model_id,
const DictionaryDatum& params )
{
params->clear_access_flags();
assert_valid_syn_id( model_id );
std::vector< lockPTR< WrappedThreadException > > exceptions_raised_(
kernel().vp_manager.get_num_threads() );
#ifdef _OPENMP
// We have to run this in parallel to set the status on nodes that exist on each
// thread, such as volume_transmitter.
#pragma omp parallel
{
index t = kernel().vp_manager.get_thread_id();
#else // clang-format off
for ( index t = 0; t < kernel().vp_manager.get_num_threads(); ++t )
{
#endif // clang-format on
try
{
prototypes_[ t ][ model_id ]->set_status( params );
}
catch ( std::exception& err )
{
// We must create a new exception here, err's lifetime ends at
// the end of the catch block.
exceptions_raised_.at( t ) =
lockPTR< WrappedThreadException >( new WrappedThreadException( err ) );
}
}
for ( index t = 0; t < kernel().vp_manager.get_num_threads(); ++t )
{
if ( exceptions_raised_.at( t ).valid() )
{
throw WrappedThreadException( *( exceptions_raised_.at( t ) ) );
}
}
ALL_ENTRIES_ACCESSED( *params,
"ModelManager::set_synapse_defaults_",
"Unread dictionary entries: " );
}
// TODO: replace int with index and return value -1 with invalid_index, also
// change all pertaining code
int
ModelManager::get_model_id( const Name name ) const
{
const Name model_name( name );
for ( int i = 0; i < ( int ) models_.size(); ++i )
{
assert( models_[ i ] != NULL );
if ( model_name == models_[ i ]->get_name() )
{
return i;
}
}
return -1;
}
DictionaryDatum
ModelManager::get_connector_defaults( synindex syn_id ) const
{
assert_valid_syn_id( syn_id );
DictionaryDatum dict( new Dictionary() );
for ( thread t = 0;
t < static_cast< thread >( kernel().vp_manager.get_num_threads() );
++t )
{
// each call adds to num_connections
prototypes_[ t ][ syn_id ]->get_status( dict );
}
( *dict )[ names::num_connections ] =
kernel().connection_manager.get_num_connections( syn_id );
return dict;
}
bool
ModelManager::connector_requires_symmetric( synindex syn_id ) const
{
assert_valid_syn_id( syn_id );
return prototypes_[ 0 ][ syn_id ]->requires_symmetric();
}
void
ModelManager::clear_models_( bool called_from_destructor )
{
// no message on destructor call, may come after MPI_Finalize()
if ( not called_from_destructor )
{
LOG( M_INFO,
"ModelManager::clear_models_",
"Models will be cleared and parameters reset." );
}
// We delete all models, which will also delete all nodes. The
// built-in models will be recovered from the pristine_models_ in
// init()
for ( std::vector< Model* >::iterator m = models_.begin(); m != models_.end();
++m )
{
if ( *m != 0 )
{
delete *m;
}
}
models_.clear();
proxy_nodes_.clear();
dummy_spike_sources_.clear();
modeldict_->clear();
model_defaults_modified_ = false;
}
void
ModelManager::clear_prototypes_()
{
for ( std::vector< std::vector< ConnectorModel* > >::iterator it =
prototypes_.begin();
it != prototypes_.end();
++it )
{
for ( std::vector< ConnectorModel* >::iterator pt = it->begin();
pt != it->end();
++pt )
{
if ( *pt != 0 )
{
delete *pt;
}
}
it->clear();
}
prototypes_.clear();
}
void
ModelManager::calibrate( const TimeConverter& tc )
{
for ( thread t = 0;
t < static_cast< thread >( kernel().vp_manager.get_num_threads() );
++t )
{
for (
std::vector< ConnectorModel* >::iterator pt = prototypes_[ t ].begin();
pt != prototypes_[ t ].end();
++pt )
{
if ( *pt != 0 )
{
( *pt )->calibrate( tc );
}
}
}
}
//!< Functor to compare Models by their name.
bool
ModelManager::compare_model_by_id_( const int a, const int b )
{
return kernel().model_manager.get_model( a )->get_name()
< kernel().model_manager.get_model( b )->get_name();
}
void
ModelManager::memory_info() const
{
std::cout.setf( std::ios::left );
std::vector< index > idx( get_num_node_models() );
for ( index i = 0; i < get_num_node_models(); ++i )
{
idx[ i ] = i;
}
std::sort( idx.begin(), idx.end(), compare_model_by_id_ );
std::string sep( "--------------------------------------------------" );
std::cout << sep << std::endl;
std::cout << std::setw( 25 ) << "Name" << std::setw( 13 ) << "Capacity"
<< std::setw( 13 ) << "Available" << std::endl;
std::cout << sep << std::endl;
for ( index i = 0; i < get_num_node_models(); ++i )
{
Model* mod = models_[ idx[ i ] ];
if ( mod->mem_capacity() != 0 )
{
std::cout << std::setw( 25 ) << mod->get_name() << std::setw( 13 )
<< mod->mem_capacity() * mod->get_element_size()
<< std::setw( 13 )
<< mod->mem_available() * mod->get_element_size() << std::endl;
}
}
std::cout << sep << std::endl;
std::cout.unsetf( std::ios::left );
}
void
ModelManager::create_secondary_events_prototypes()
{
if ( secondary_events_prototypes_.size()
< kernel().vp_manager.get_num_threads() )
{
delete_secondary_events_prototypes();
std::vector< SecondaryEvent* > prototype;
prototype.resize( secondary_connector_models_.size(), NULL );
secondary_events_prototypes_.resize(
kernel().vp_manager.get_num_threads(), prototype );
for ( size_t i = 0; i < secondary_connector_models_.size(); i++ )
{
if ( secondary_connector_models_[ i ] != NULL )
{
prototype = secondary_connector_models_[ i ]->create_event(
kernel().vp_manager.get_num_threads() );
for ( size_t j = 0; j < secondary_events_prototypes_.size(); j++ )
{
secondary_events_prototypes_[ j ][ i ] = prototype[ j ];
}
}
}
}
}
synindex
ModelManager::register_connection_model_( ConnectorModel* cf )
{
if ( synapsedict_->known( cf->get_name() ) )
{
delete cf;
std::string msg = String::compose(
"A synapse type called '%1' already exists.\n"
"Please choose a different name!",
cf->get_name() );
throw NamingConflict( msg );
}
pristine_prototypes_.push_back( cf );
const synindex syn_id = prototypes_.at( 0 ).size();
pristine_prototypes_.at( syn_id )->set_syn_id( syn_id );
for ( thread t = 0;
t < static_cast< thread >( kernel().vp_manager.get_num_threads() );
++t )
{
prototypes_[ t ].push_back( cf->clone( cf->get_name() ) );
prototypes_[ t ][ syn_id ]->set_syn_id( syn_id );
}
synapsedict_->insert( cf->get_name(), syn_id );
return syn_id;
}
} // namespace nest
| 25.99064 | 80 | 0.634454 | [
"vector",
"model"
] |
c7fb2476b62417fe1523191808d980874bf36199 | 10,712 | cpp | C++ | storage/diskmgr/frameworks/file_manager_service/src/fms_utils.cpp | peeweep/distributeddatamgr_file | 1e624bbc3850815fa1b2642c67123b7785bec6a1 | [
"Apache-2.0"
] | null | null | null | storage/diskmgr/frameworks/file_manager_service/src/fms_utils.cpp | peeweep/distributeddatamgr_file | 1e624bbc3850815fa1b2642c67123b7785bec6a1 | [
"Apache-2.0"
] | null | null | null | storage/diskmgr/frameworks/file_manager_service/src/fms_utils.cpp | peeweep/distributeddatamgr_file | 1e624bbc3850815fa1b2642c67123b7785bec6a1 | [
"Apache-2.0"
] | 5 | 2021-09-13T11:18:04.000Z | 2021-11-25T14:12:15.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "../include/fms_utils.h"
#include <sys/stat.h>
#include <uri.h>
#include "../include/file_info.h"
#include "../include/log_util.h"
#include "../include/root_info.h"
#include "device_storage_manager.h"
#include "message_parcel.h"
namespace OHOS {
namespace FileManager {
using namespace OHOS::AppExecFwk;
using namespace OHOS::NativeRdb;
using namespace std;
using Uri = OHOS::Uri;
unique_ptr<FmsUtils> FmsUtils::mInstance = nullptr;
FmsUtils *FmsUtils::Instance()
{
if (mInstance.get() == nullptr) {
mInstance.reset(new FmsUtils());
}
return mInstance.get();
}
FmsUtils::FmsUtils() {}
bool FmsUtils::IsPublicStorage(const Uri &uri) const
{
std::vector<string> pathVector;
const_cast<Uri &>(uri).GetPathSegments(pathVector);
string mAbilityPath = pathVector[0];
if (mAbilityPath.empty()) {
return false;
}
if (!strcmp(mAbilityPath.c_str(), PUBLIC_STORAGE_ABILITY.c_str())) {
return true;
}
return false;
}
bool FmsUtils::IsPrimaryUser(const Uri &uri) const
{
std::vector<string> pathVector;
const_cast<Uri &>(uri).GetPathSegments(pathVector);
string mUserPath = pathVector[1];
if (mUserPath.empty()) {
return false;
}
if (!strcmp(mUserPath.c_str(), PRIMARY_USER.c_str())) {
return true;
}
return false;
}
bool FmsUtils::IsUpdateRootInfo(const Uri &uri) const
{
if (!strcmp(UPDATE_ROOT_INFO.c_str(), const_cast<Uri &>(uri).GetQuery().c_str())) {
return true;
}
return false;
}
bool FmsUtils::IsCreateDir(const Uri &uri) const
{
if (!strcmp(CREATE_DIR.c_str(), const_cast<Uri &>(uri).GetQuery().c_str())) {
return true;
}
return false;
}
bool FmsUtils::IsSaveFiles(const Uri &uri) const
{
if (!strcmp(SAVE_FILES.c_str(), const_cast<Uri &>(uri).GetQuery().c_str())) {
return true;
}
return false;
}
bool FmsUtils::IsRootDirectory(const Uri &uri) const
{
constexpr int MIN_PATHVECTOR_LENGTH = 3;
std::vector<string> pathVector;
const_cast<Uri &>(uri).GetPathSegments(pathVector);
int size = pathVector.size();
if (size < MIN_PATHVECTOR_LENGTH) {
return false;
}
string mRootPath = pathVector[static_cast<int>(COMMON_NUM::TWO)];
if (mRootPath.empty()) {
return false;
}
if (!strcmp(mRootPath.c_str(), MATCH_ROOTS.c_str())) {
return true;
}
return false;
}
bool FmsUtils::IsChildDirectory(const Uri &uri) const
{
std::vector<string> pathVector;
const_cast<Uri &>(uri).GetPathSegments(pathVector);
string mLastPath;
if (pathVector.size() - 1 >= 0) {
mLastPath = pathVector[pathVector.size() - 1];
}
string mRootPath = pathVector[static_cast<int>(COMMON_NUM::TWO)];
if (mRootPath.empty() || mLastPath.empty()) {
return false;
}
if ((!strcmp(mRootPath.c_str(), MATCH_FILE.c_str())) &&
(!strcmp(mLastPath.c_str(), MATCH_FILE_CHILDREN.c_str()))) {
return true;
}
return false;
}
shared_ptr<DeviceStorageManager> storageService = DelayedSingleton<DeviceStorageManager>::GetInstance();
string GetInternalPath(void)
{
string internalPath = "";
if ((storageService->Connect()) != 0) {
return internalPath;
}
vector<shared_ptr<DS::VolumeInfo>> volumeInfos;
if (storageService->GetVolumes(volumeInfos)) {
for (auto volumeInfo : volumeInfos) {
if ((volumeInfo->GetState() == static_cast<int>(COMMON_NUM::TWO)) &&
(!volumeInfo->GetDiskId().empty())) {
internalPath = volumeInfo->GetInternalPath();
}
}
}
return internalPath;
}
string FmsUtils::GetCurrentPath(const Uri &uri) const
{
std::vector<string> pathVector;
std::string mPath = "";
const_cast<Uri &>(uri).GetPathSegments(pathVector);
if (IsPublicStorage(uri)) {
mPath = GetInternalPath();
mPath.append("/");
if (IsChildDirectory(uri)) {
for (unsigned int count = 3; count < pathVector.size() - 1; count++) {
mPath.append(pathVector[count]);
mPath.append("/");
}
} else if (IsRootDirectory(uri)) {
for (unsigned int count = 3; count < pathVector.size(); count++) {
mPath.append(pathVector[count]);
mPath.append("/");
}
} else {
mPath = "";
}
}
return mPath;
}
string FmsUtils::GetCurrentUser(const Uri &uri) const
{
std::vector<string> pathVector;
const_cast<Uri &>(uri).GetPathSegments(pathVector);
string mUserPath;
if (pathVector.size() > 1) {
mUserPath = pathVector[1];
}
return mUserPath;
}
std::shared_ptr<NativeRdb::AbsSharedResultSet> FmsUtils::VectorToResultset(
const std::vector<std::string> &columns) const
{
MessageParcel parcel(nullptr);
bool result = false;
int size = columns.size();
if (size <= 0) {
return nullptr;
}
result = parcel.WriteStringVector(columns);
if (result) {
return make_shared<NativeRdb::AbsSharedResultSet>();
} else {
return nullptr;
}
}
std::shared_ptr<NativeRdb::AbsSharedResultSet> FmsUtils::Int32ToResultset(int32_t parm) const
{
MessageParcel parcel(nullptr);
bool result = false;
result = parcel.WriteInt32(parm);
if (result) {
return make_shared<NativeRdb::AbsSharedResultSet>();
} else {
return nullptr;
}
}
int32_t FmsUtils::Mkdirs(string path) const
{
constexpr int DIR_FAULT_PERM = 0775;
for (size_t i = 1; i < path.length(); ++i) {
if (path[i] == '/') {
path[i] = '\0';
if (access(path.c_str(), 0) != 0) {
if (mkdir(path.c_str(), DIR_FAULT_PERM) == -1) {
return static_cast<int>(STATUS_NUM::FAIL);
}
}
path[i] = '/';
}
}
if (path.length() > 0 && access(path.c_str(), 0) != 0) {
if (mkdir(path.c_str(), DIR_FAULT_PERM) == -1) {
return static_cast<int>(STATUS_NUM::FAIL);
}
}
return static_cast<int>(STATUS_NUM::OK);
}
int FmsUtils::GetCurrentDirFileInfoList(std::string path, std::vector<FileInfo> &fileList) const
{
DIR *pDir = nullptr;
struct dirent *ptr = nullptr;
FileInfo fileInfo;
string fullPath;
if (!(pDir = opendir(path.c_str()))) {
return static_cast<int>(STATUS_NUM::FAIL);
}
while ((ptr = readdir(pDir)) != nullptr) {
if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
fullPath = path + "/" + ptr->d_name;
if (ptr->d_type == DT_DIR) {
fileInfo = GetFileInfo(fullPath, ptr->d_name);
} else {
fileInfo = GetFileInfo(fullPath, ptr->d_name);
}
fileList.push_back(fileInfo);
}
}
closedir(pDir);
return static_cast<int>(STATUS_NUM::OK);
}
int FmsUtils::GetDirNum(string path) const
{
int size = 0;
DIR *pDir = nullptr;
struct dirent *ptr = nullptr;
if ((pDir = opendir(path.c_str())) == nullptr) {
return -1;
}
while ((ptr = readdir(pDir)) != nullptr) {
if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) {
continue;
}
size = size + 1;
}
closedir(pDir);
return size;
}
FileInfo FmsUtils::GetFileInfo(string sourcePath, string sourceName) const
{
constexpr int DIVIDE_BY_MILLION = 1000000;
constexpr int MULTIPLY_BY_THOUSAND = 1000;
FileInfo fi;
struct stat tmp;
int r = stat(sourcePath.c_str(), &tmp);
if (r == 0 && S_ISDIR(tmp.st_mode)) {
fi.typeDir = 1;
fi.dirNum = GetDirNum(sourcePath);
} else if (r == 0) {
fi.typeDir = 0;
fi.mimeType = GetFileType(sourcePath);
fi.fileSize = tmp.st_size;
}
fi.lastUseTime =
tmp.st_mtime * MULTIPLY_BY_THOUSAND + static_cast<int64_t>((tmp.st_mtim).tv_nsec / DIVIDE_BY_MILLION);
fi.fileUri = RealPathToUri(sourcePath);
fi.fileName = sourceName;
return fi;
}
int FmsUtils::GetSearchFileInfoList(string dirPath,
string fileName,
std::vector<FileInfo> &fileInfoList) const
{
DIR *pDir = nullptr;
struct dirent *ptr = nullptr;
FileInfo fileInfo;
string mCurrentFileName;
if ((pDir = opendir(dirPath.c_str())) == nullptr) {
return static_cast<int>(STATUS_NUM::FAIL);
}
while ((ptr = readdir(pDir)) != nullptr) {
if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
mCurrentFileName = ptr->d_name;
if (mCurrentFileName.find(fileName.c_str(), 0) != mCurrentFileName.npos) {
fileInfo = GetFileInfo(dirPath + "/" + ptr->d_name, ptr->d_name);
fileInfoList.push_back(fileInfo);
}
if (ptr->d_type == DT_DIR) {
GetSearchFileInfoList(dirPath + "/" + ptr->d_name, fileName, fileInfoList);
}
}
}
closedir(pDir);
return static_cast<int>(STATUS_NUM::OK);
}
string FmsUtils::RealPathToUri(const string &realPath) const
{
string uriStr = "";
uriStr = SCHEMEOHOS + "://" + PATTERN + PUBLIC_STORAGE_ABILITY;
string internalPath = GetInternalPath();
string deviceId = internalPath.substr(internalPath.find_last_of("/"));
uriStr = uriStr + deviceId + PATTERN;
if (internalPath == realPath) {
uriStr = uriStr + MATCH_ROOTS;
} else {
string directory = "";
if (realPath.find(deviceId) != realPath.npos) {
int deviceIdLen = deviceId.length();
directory = realPath.substr(realPath.find(deviceId) + deviceIdLen);
}
uriStr = uriStr + MATCH_FILE + directory + PATTERN + MATCH_FILE_CHILDREN;
}
return uriStr;
}
std::string FmsUtils::GetFileType(const std::string &fileName) const
{
string suffixStr = fileName.substr(fileName.find_last_of('.') + 1);
return suffixStr;
}
} // namespace FileManager
} // namespace OHOS
| 31.139535 | 110 | 0.609317 | [
"vector"
] |
c7fd1bacfa6ad4f8e71aba694ff65f175295df23 | 78,915 | cp | C++ | Text/Mod/Models.cp | romiras/Blackbox-fw-playground | 6de94dc65513e657a9b86c1772e2c07742b608a8 | [
"BSD-2-Clause"
] | 1 | 2016-03-17T08:27:05.000Z | 2016-03-17T08:27:05.000Z | Text/Mod/Models.cps | Spirit-of-Oberon/LightBox | 8a45ed11dcc02ae97e86f264dcee3e07c910ff9d | [
"BSD-2-Clause"
] | null | null | null | Text/Mod/Models.cps | Spirit-of-Oberon/LightBox | 8a45ed11dcc02ae97e86f264dcee3e07c910ff9d | [
"BSD-2-Clause"
] | 1 | 2018-03-14T17:53:27.000Z | 2018-03-14T17:53:27.000Z | MODULE TextModels;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = ""
issues = ""
**)
(* re-check alien attributes: project to base attributes? *)
(* support *lists* of attribute extensions? *)
(* support for enumeration of texts within embedded views
- generally: support for enumeration of X-views within a recursive scheme?
- however: Containers already provides a general iteration scheme
-> could add recursion support to Reader later
*)
IMPORT
Files, Services, Fonts, Ports, Stores, Models, Views, Properties, Containers;
(* text file format:
text = 0 CHAR
textoffset INTEGER (> 0)
{ run }
-1 CHAR
{ char }
run = attrno BYTE (0..32)
[ attr ] attr.Internalize
( piece | lpiece | viewref )
piece = length INTEGER (> 0)
lpiece = -length INTEGER (< 0, length MOD 2 = 0)
viewref = 0 INTEGER
w INTEGER
h INTEGER
view view.Internalize
*)
CONST
(* unicode* = 1X; *)
viewcode* = 2X; (** code for embedded views **)
tab* = 9X; line* = 0DX; para* = 0EX; (** tabulator; line and paragraph separator **)
zwspace* = 8BX; nbspace* = 0A0X; digitspace* = 8FX;
hyphen* = 90X; nbhyphen* = 91X; softhyphen* = 0ADX;
(** Pref.opts, options of text-aware views **)
maskChar* = 0; hideable* = 1;
(** Prop.known/valid/readOnly **)
offset* = 0; code* = 1;
(** InfoMsg.op **)
store* = 0;
(** UpdateMsg.op **)
replace* = 0; insert* = 1; delete* = 2;
(* EditOp.mode *)
deleteRange = 0; moveBuf = 1; writeSChar = 2; writeChar = 3; writeView = 4;
dictSize = 32;
point = Ports.point;
defW = 64 * point; defH = 32 * point;
(* embedding limits - don't increase maxHeight w/o checking TextViews.StdView *)
minWidth = 5 * point; maxWidth = MAX(INTEGER) DIV 2;
minHeight = 5 * point; maxHeight = 1500 * point;
minVersion = 0; maxAttrVersion = 0; maxModelVersion = 0;
noLCharStdModelVersion = 0; maxStdModelVersion = 1;
cacheWidth = 8; cacheLen = 4096; cacheLine = 128;
TYPE
Model* = POINTER TO ABSTRACT RECORD (Containers.Model) END;
Attributes* = POINTER TO EXTENSIBLE RECORD (Stores.Store)
init-: BOOLEAN; (* immutable once init is set *)
color-: Ports.Color;
font-: Fonts.Font;
offset-: INTEGER
END;
AlienAttributes* = POINTER TO RECORD (Attributes)
store-: Stores.Alien
END;
Prop* = POINTER TO RECORD (Properties.Property)
offset*: INTEGER;
code*: CHAR
END;
Context* = POINTER TO ABSTRACT RECORD (Models.Context) END;
Pref* = RECORD (Properties.Preference)
opts*: SET; (** preset to {} **)
mask*: CHAR (** valid if maskChar IN opts **)
END;
Reader* = POINTER TO ABSTRACT RECORD
eot*: BOOLEAN;
attr*: Attributes;
char*: CHAR;
view*: Views.View;
w*, h*: INTEGER
END;
Writer* = POINTER TO ABSTRACT RECORD
attr-: Attributes
END;
InfoMsg* = RECORD (Models.Message)
op*: INTEGER
END;
UpdateMsg* = RECORD (Models.UpdateMsg)
op*: INTEGER;
beg*, end*, delta*: INTEGER (** range: [beg, end); length = length' + delta **)
END;
Directory* = POINTER TO ABSTRACT RECORD
attr-: Attributes
END;
Run = POINTER TO EXTENSIBLE RECORD
prev, next: Run;
len: INTEGER;
attr: Attributes
END;
LPiece = POINTER TO EXTENSIBLE RECORD (Run)
file: Files.File;
org: INTEGER
END;
Piece = POINTER TO RECORD (LPiece) END; (* u IS Piece => CHAR run *)
ViewRef = POINTER TO RECORD (Run) (* u IS ViewRef => View run *)
w, h: INTEGER;
view: Views.View (* embedded view *)
END;
PieceCache = RECORD
org: INTEGER;
prev: Run (* Org(prev.next) = org *)
END;
SpillFile = POINTER TO RECORD
file: Files.File; (* valid if file # NIL *)
len: INTEGER; (* len = file.Length() *)
writer: Files.Writer (* writer.Base() = file *)
END;
AttrDict = RECORD
len: BYTE;
attr: ARRAY dictSize OF Attributes
END;
StdModel = POINTER TO RECORD (Model)
len: INTEGER; (* len = sum(u : [trailer.next, trailer) : u.len) *)
id: INTEGER; (* unique (could use SYSTEM.ADR instead ...) *)
era: INTEGER; (* stable era >= k *)
trailer: Run; (* init => trailer # NIL *)
pc: PieceCache;
spill: SpillFile; (* spill file, created lazily, shared with clones *)
rd: Reader (* reader cache *)
END;
StdContext = POINTER TO RECORD (Context)
text: StdModel;
ref: ViewRef
END;
StdReader = POINTER TO RECORD (Reader)
base: StdModel; (* base = Base() *)
pos: INTEGER; (* pos = Pos() *)
era: INTEGER;
run: Run; (* era = base.era => Pos(run) + off = pos *)
off: INTEGER; (* era = base.era => 0 <= off < run.len *)
reader: Files.Reader (* file reader cache *)
END;
StdWriter = POINTER TO RECORD (Writer)
base: StdModel; (* base = Base() *)
(* hasSequencer := base.Domain() = NIL OR base.Domain().GetSequencer() = NIL *)
pos: INTEGER; (* pos = Pos() *)
era: INTEGER; (* relevant iff hasSequencer *)
run: Run (* hasSequencer & era = base.era => Pos(run) = pos *)
END;
StdDirectory = POINTER TO RECORD (Directory) END;
MoveOp = POINTER TO RECORD (Stores.Operation) (* MoveStretchFrom *)
(* move src.[beg, end) to dest.pos *)
src: StdModel;
beg, end: INTEGER;
dest: StdModel;
pos: INTEGER
END;
EditOp = POINTER TO RECORD (Stores.Operation) (* CopyStretchFrom, Delete, WriteXXX *)
mode: INTEGER;
canBunch: BOOLEAN;
text: StdModel;
beg, end: INTEGER; (* op = deleteRange: move text.[beg, end) to <first, last> *)
pos: INTEGER;
first, last: Run; (* op = moveBuf: move <first, last> to text.pos;
op = writeView: insert <first> at text.pos*)
len: INTEGER; (* op = moveBuf: length of <first, last>;
op = write[L]Char: length of spill file before writing new [long] char *)
attr: Attributes (* op = write[L]Char *)
END;
AttrList = POINTER TO RECORD
next: AttrList;
len: INTEGER;
attr: Attributes
END;
SetAttrOp = POINTER TO RECORD (Stores.Operation) (* SetAttr, Modify *)
text: StdModel;
beg: INTEGER;
list: AttrList
END;
ResizeViewOp = POINTER TO RECORD (Stores.Operation) (* ResizeView *)
text: StdModel;
pos: INTEGER;
ref: ViewRef;
w, h: INTEGER
END;
ReplaceViewOp = POINTER TO RECORD (Stores.Operation) (* ReplaceView *)
text: StdModel;
pos: INTEGER;
ref: ViewRef;
new: Views.View
END;
TextCache = RECORD
id: INTEGER; (* id of the text block served by this cache block *)
beg, end: INTEGER; (* [beg .. end) cached, 0 <= end - beg < cacheLen *)
buf: ARRAY cacheLen OF BYTE (* [beg MOD cacheLen .. end MOD cacheLen) *)
END;
Cache = ARRAY cacheWidth OF TextCache;
VAR
dir-, stdDir-: Directory;
stdProp: Properties.StdProp; (* temp for NewColor, ... NewWeight *)
prop: Prop; (* temp for NewOffset *)
nextId: INTEGER;
cache: Cache;
(** Model **)
PROCEDURE (m: Model) Internalize- (VAR rd: Stores.Reader), EXTENSIBLE;
VAR thisVersion: INTEGER;
BEGIN
m.Internalize^(rd); IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxModelVersion, thisVersion)
END Internalize;
PROCEDURE (m: Model) Externalize- (VAR wr: Stores.Writer), EXTENSIBLE;
BEGIN
m.Externalize^(wr);
wr.WriteVersion(maxModelVersion)
END Externalize;
PROCEDURE (m: Model) Length* (): INTEGER, NEW, ABSTRACT;
PROCEDURE (m: Model) NewReader* (old: Reader): Reader, NEW, ABSTRACT;
PROCEDURE (m: Model) NewWriter* (old: Writer): Writer, NEW, ABSTRACT;
PROCEDURE (m: Model) InsertCopy* (pos: INTEGER; m0: Model; beg0, end0: INTEGER), NEW, ABSTRACT;
PROCEDURE (m: Model) Insert* (pos: INTEGER; m0: Model; beg0, end0: INTEGER), NEW, ABSTRACT;
PROCEDURE (m: Model) Delete* (beg, end: INTEGER), NEW, ABSTRACT;
PROCEDURE (m: Model) SetAttr* (beg, end: INTEGER; attr: Attributes), NEW, ABSTRACT;
PROCEDURE (m: Model) Prop* (beg, end: INTEGER): Properties.Property, NEW, ABSTRACT;
PROCEDURE (m: Model) Modify* (beg, end: INTEGER; old, p: Properties.Property), NEW, ABSTRACT;
PROCEDURE (m: Model) ReplaceView* (old, new: Views.View), ABSTRACT;
PROCEDURE (m: Model) Append* (m0: Model), NEW, ABSTRACT;
(*
BEGIN
ASSERT(m # m0, 20);
m.Insert(m.Length(), m0, 0, m0.Length())
END Append;
*)
PROCEDURE (m: Model) Replace* (beg, end: INTEGER; m0: Model; beg0, end0: INTEGER),
NEW, ABSTRACT;
(*
VAR script: Stores.Operation; delta: INTEGER;
BEGIN
Models.BeginScript(m, "#System:Replacing", script);
m.Delete(beg, end);
IF beg0 >
m.Insert(beg, m0, beg0, end0);
Models.EndScript(m, script)
END Replace;
*)
(** Attributes **)
PROCEDURE (a: Attributes) CopyFrom- (source: Stores.Store), EXTENSIBLE;
(** pre: ~a.init, source.init **)
(** post: a.init **)
BEGIN
WITH source: Attributes DO
ASSERT(~a.init, 20); ASSERT(source.init, 21); a.init := TRUE;
a.color := source.color; a.font := source.font; a.offset := source.offset
END
END CopyFrom;
PROCEDURE (a: Attributes) Internalize- (VAR rd: Stores.Reader), EXTENSIBLE;
(** pre: ~a.init **)
(** post: a.init **)
VAR thisVersion: INTEGER;
fprint: INTEGER; face: Fonts.Typeface; size: INTEGER; style: SET; weight: INTEGER;
BEGIN
ASSERT(~a.init, 20); a.init := TRUE;
a.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxAttrVersion, thisVersion);
IF rd.cancelled THEN RETURN END;
rd.ReadInt(a.color);
rd.ReadInt(fprint);
rd.ReadXString(face); rd.ReadInt(size); rd.ReadSet(style); rd.ReadXInt(weight);
a.font := Fonts.dir.This(face, size, style, weight);
IF a.font.IsAlien() THEN Stores.Report("#System:AlienFont", face, "", "")
(*
ELSIF a.font.Fingerprint() # fprint THEN Stores.Report("#System:AlienFontVersion", face, "", "")
*)
END;
rd.ReadInt(a.offset)
END Internalize;
PROCEDURE (a: Attributes) Externalize- (VAR wr: Stores.Writer), EXTENSIBLE;
(** pre: a.init **)
VAR f: Fonts.Font;
BEGIN
ASSERT(a.init, 20);
a.Externalize^(wr);
wr.WriteVersion(maxAttrVersion);
wr.WriteInt(a.color);
f := a.font;
(*
wr.WriteInt(f.Fingerprint());
*)
wr.WriteInt(0);
wr.WriteXString(f.typeface); wr.WriteInt(f.size); wr.WriteSet(f.style); wr.WriteXInt(f.weight);
wr.WriteInt(a.offset)
END Externalize;
PROCEDURE (a: Attributes) InitFromProp* (p: Properties.Property), NEW, EXTENSIBLE;
(** pre: ~a.init **)
(** post: a.init, x IN p.valid => x set in a, else x defaults in a **)
VAR def: Fonts.Font; face: Fonts.Typeface; size: INTEGER; style: SET; weight: INTEGER;
BEGIN
ASSERT(~a.init, 20); a.init := TRUE;
def := Fonts.dir.Default();
face := def.typeface$; size := def.size; style := def.style; weight := def.weight;
a.color := Ports.defaultColor; a.offset := 0;
WHILE p # NIL DO
WITH p: Properties.StdProp DO
IF Properties.color IN p.valid THEN a.color := p.color.val END;
IF Properties.typeface IN p.valid THEN face := p.typeface END;
IF (Properties.size IN p.valid)
& (Ports.point <= p.size) & (p.size <= 32767 * Ports.point) THEN
size := p.size
END;
IF Properties.style IN p.valid THEN
style := style - p.style.mask + p.style.val * p.style.mask
END;
IF (Properties.weight IN p.valid) & (1 <= p.weight) & (p.weight <= 1000) THEN
weight := p.weight
END
| p: Prop DO
IF offset IN p.valid THEN a.offset := p.offset END
ELSE
END;
p := p.next
END;
a.font := Fonts.dir.This(face, size, style, weight)
END InitFromProp;
PROCEDURE (a: Attributes) Equals* (b: Attributes): BOOLEAN, NEW, EXTENSIBLE;
(** pre: a.init, b.init **)
BEGIN
ASSERT(a.init, 20); ASSERT((b # NIL) & b.init, 21);
RETURN (a = b)
OR (Services.SameType(a, b))
& (a.color = b.color) & (a.font = b.font) & (a.offset = b.offset)
END Equals;
PROCEDURE (a: Attributes) Prop* (): Properties.Property, NEW, EXTENSIBLE;
(** pre: a.init **)
VAR p: Properties.Property; sp: Properties.StdProp; tp: Prop;
BEGIN
ASSERT(a.init, 20);
NEW(sp);
sp.known := {Properties.color .. Properties.weight}; sp.valid := sp.known;
sp.color.val := a.color;
sp.typeface := a.font.typeface$;
sp.size := a.font.size;
sp.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout};
sp.style.val := a.font.style * sp.style.mask;
sp.weight := a.font.weight;
NEW(tp);
tp.known := {offset}; tp.valid := tp.known;
tp.offset := a.offset;
Properties.Insert(p, tp); Properties.Insert(p, sp);
RETURN p
END Prop;
PROCEDURE (a: Attributes) ModifyFromProp- (p: Properties.Property), NEW, EXTENSIBLE;
(** pre: ~a.init **)
VAR face: Fonts.Typeface; size: INTEGER; style: SET; weight: INTEGER;
valid: SET;
BEGIN
face := a.font.typeface; size := a.font.size;
style := a.font.style; weight := a.font.weight;
WHILE p # NIL DO
valid := p.valid;
WITH p: Properties.StdProp DO
IF Properties.color IN valid THEN a.color := p.color.val END;
IF Properties.typeface IN valid THEN
face := p.typeface
END;
IF (Properties.size IN valid)
& (Ports.point <= p.size) & (p.size <= 32767 * Ports.point) THEN
size := p.size
ELSE EXCL(valid, Properties.size)
END;
IF Properties.style IN valid THEN
style := style - p.style.mask + p.style.val * p.style.mask
END;
IF (Properties.weight IN valid) & (1 <= p.weight) & (p.weight <= 1000) THEN
weight := p.weight
ELSE EXCL(valid, Properties.weight)
END;
IF valid - {Properties.typeface .. Properties.weight} # valid THEN
a.font := Fonts.dir.This(face, size, style, weight)
END
| p: Prop DO
IF offset IN valid THEN a.offset := p.offset END
ELSE
END;
p := p.next
END
END ModifyFromProp;
PROCEDURE ReadAttr* (VAR rd: Stores.Reader; VAR a: Attributes);
VAR st: Stores.Store; alien: AlienAttributes;
BEGIN
rd.ReadStore(st); ASSERT(st # NIL, 20);
IF st IS Stores.Alien THEN
NEW(alien); alien.store := st(Stores.Alien); Stores.Join(alien, alien.store);
alien.InitFromProp(NIL); a := alien;
Stores.Report("#Text:AlienAttributes", "", "", "")
ELSE a := st(Attributes)
END
END ReadAttr;
PROCEDURE WriteAttr* (VAR wr: Stores.Writer; a: Attributes);
BEGIN
ASSERT(a # NIL, 20); ASSERT(a.init, 21);
WITH a: AlienAttributes DO wr.WriteStore(a.store) ELSE wr.WriteStore(a) END
END WriteAttr;
PROCEDURE ModifiedAttr* (a: Attributes; p: Properties.Property): Attributes;
(** pre: a.init **)
(** post: x IN p.valid => x in new attr set to value in p, else set to value in a **)
VAR h: Attributes;
BEGIN
ASSERT(a.init, 20);
h := Stores.CopyOf(a)(Attributes); h.ModifyFromProp(p);
RETURN h
END ModifiedAttr;
(** AlienAttributes **)
PROCEDURE (a: AlienAttributes) Externalize- (VAR wr: Stores.Writer);
BEGIN
HALT(100)
END Externalize;
PROCEDURE (a: AlienAttributes) CopyFrom- (source: Stores.Store);
BEGIN
a.CopyFrom^(source);
a.store := Stores.CopyOf(source(AlienAttributes).store)(Stores.Alien);
Stores.Join(a, a.store)
END CopyFrom;
PROCEDURE (a: AlienAttributes) Prop* (): Properties.Property;
BEGIN
RETURN NIL
END Prop;
PROCEDURE (a: AlienAttributes) ModifyFromProp- (p: Properties.Property);
END ModifyFromProp;
(** Prop **)
PROCEDURE (p: Prop) IntersectWith* (q: Properties.Property; OUT equal: BOOLEAN);
VAR valid: SET;
BEGIN
WITH q: Prop DO
valid := p.valid * q.valid; equal := TRUE;
IF p.offset # q.offset THEN EXCL(valid, offset) END;
IF p.code # q.code THEN EXCL(valid, code) END;
IF p.valid # valid THEN p.valid := valid; equal := FALSE END
END
END IntersectWith;
(** Context **)
PROCEDURE (c: Context) ThisModel* (): Model, ABSTRACT;
PROCEDURE (c: Context) Pos* (): INTEGER, NEW, ABSTRACT;
PROCEDURE (c: Context) Attr* (): Attributes, NEW, ABSTRACT;
(** Reader **)
PROCEDURE (rd: Reader) Base* (): Model, NEW, ABSTRACT;
PROCEDURE (rd: Reader) SetPos* (pos: INTEGER), NEW, ABSTRACT;
PROCEDURE (rd: Reader) Pos* (): INTEGER, NEW, ABSTRACT;
PROCEDURE (rd: Reader) Read*, NEW, ABSTRACT;
PROCEDURE (rd: Reader) ReadPrev*, NEW, ABSTRACT;
PROCEDURE (rd: Reader) ReadChar* (OUT ch: CHAR), NEW, ABSTRACT;
(*
BEGIN
rd.Read; ch := rd.char
END ReadChar;
*)
PROCEDURE (rd: Reader) ReadPrevChar* (OUT ch: CHAR), NEW, ABSTRACT;
(*
BEGIN
rd.ReadPrev; ch := rd.char
END ReadPrevChar;
*)
PROCEDURE (rd: Reader) ReadView* (OUT v: Views.View), NEW, ABSTRACT;
(*
BEGIN
REPEAT rd.Read UNTIL (rd.view # NIL) OR rd.eot;
v := rd.view
END ReadView;
*)
PROCEDURE (rd: Reader) ReadPrevView* (OUT v: Views.View), NEW, ABSTRACT;
(*
BEGIN
REPEAT rd.ReadPrev UNTIL (rd.view # NIL) OR rd.eot;
v := rd.view
END ReadPrevView;
*)
PROCEDURE (rd: Reader) ReadRun* (OUT attr: Attributes), NEW, ABSTRACT;
(** post: rd.eot OR a # NIL, rd.view = ViewAt(rd.Pos() - 1) **)
(*
VAR a: Attributes;
BEGIN
a := rd.attr;
REPEAT rd.Read UNTIL (rd.attr # a) OR (rd.view # NIL) OR rd.eot;
IF rd.eot THEN attr := NIL ELSE attr := rd.attr END
END ReadRun;
*)
PROCEDURE (rd: Reader) ReadPrevRun* (OUT attr: Attributes), NEW, ABSTRACT;
(** post: rd.eot OR a # NIL, rd.view = ViewAt(rd.Pos()) **)
(*
VAR a: Attributes;
BEGIN
a := rd.attr;
REPEAT rd.ReadPrev UNTIL (rd.attr # a) OR (rd.view # NIL) OR rd.eot;
IF rd.eot THEN attr := NIL ELSE attr := rd.attr END
END ReadPrevRun;
*)
(** Writer **)
PROCEDURE (wr: Writer) Base* (): Model, NEW, ABSTRACT;
PROCEDURE (wr: Writer) SetPos* (pos: INTEGER), NEW, ABSTRACT;
PROCEDURE (wr: Writer) Pos* (): INTEGER, NEW, ABSTRACT;
(* PROCEDURE (wr: Writer) WriteSChar* (ch: SHORTCHAR), NEW, ABSTRACT; *)
PROCEDURE (wr: Writer) WriteChar* (ch: CHAR), NEW, ABSTRACT;
PROCEDURE (wr: Writer) WriteView* (view: Views.View; w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (wr: Writer) SetAttr* (attr: Attributes), NEW(*, EXTENSIBLE*);
BEGIN
ASSERT(attr # NIL, 20); ASSERT(attr.init, 21); wr.attr := attr
END SetAttr;
(** Directory **)
PROCEDURE (d: Directory) New* (): Model, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewFromString* (s: ARRAY OF CHAR): Model, NEW, EXTENSIBLE;
VAR m: Model; w: Writer; i: INTEGER;
BEGIN
m := d.New(); w := m.NewWriter(NIL);
i := 0; WHILE s[i] # 0X DO w.WriteChar(s[i]); INC(i) END;
RETURN m
END NewFromString;
PROCEDURE (d: Directory) SetAttr* (attr: Attributes), NEW, EXTENSIBLE;
BEGIN
ASSERT(attr.init, 20); d.attr := attr
END SetAttr;
(* StdModel - foundation *)
PROCEDURE OpenSpill (s: SpillFile);
BEGIN
s.file := Files.dir.Temp(); s.len := 0;
s.writer := s.file.NewWriter(NIL)
END OpenSpill;
PROCEDURE Find (t: StdModel; VAR pos: INTEGER; VAR u: Run; VAR off: INTEGER);
(* post: 0 <= pos <= t.len, 0 <= off < u.len, Pos(u) + off = pos *)
(* Read/Write rely on Find to force pos into the legal range *)
VAR v: Run; m: INTEGER;
BEGIN
IF pos < 0 THEN pos := 0 END;
IF pos >= t.len THEN
u := t.trailer; off := 0; t.pc.prev := t.trailer; t.pc.org := 0
ELSE
v := t.pc.prev.next; m := pos - t.pc.org;
IF m >= 0 THEN
WHILE m >= v.len DO DEC(m, v.len); v := v.next END
ELSE
WHILE m < 0 DO v := v.prev; INC(m, v.len) END
END;
u := v; off := m; t.pc.prev := v.prev; t.pc.org := pos - m
END
END Find;
PROCEDURE Split (off: INTEGER; VAR u, un: Run);
(* pre: 0 <= off <= u.len *)
(* post: u.len = off, u.len + un.len = u'.len, Pos(u) + u.len = Pos(un) *)
VAR lp: LPiece; sp: Piece;
BEGIN
IF off = 0 THEN un := u; u := un.prev (* "split" at left edge of run *)
ELSIF off < u.len THEN (* u.len > 1 => u IS LPiece; true split *)
WITH u: Piece DO
NEW(sp); sp^ := u^; INC(sp.org, off);
un := sp
ELSE (* u IS LPiece) & ~(u IS Piece) *)
NEW(lp);
lp.prev := u.prev; lp.next := u.next; lp.len := u.len; lp.attr := u.attr;
lp.file := u(LPiece).file; lp.org := u(LPiece).org;
INC(lp.org, 2 * off);
un := lp
END;
DEC(un.len, off); DEC(u.len, un.len);
un.prev := u; un.next := u.next; un.next.prev := un; u.next := un
ELSIF off = u.len THEN un := u.next (* "split" at right edge of run *)
ELSE HALT(100)
END
END Split;
PROCEDURE Merge (t: StdModel; u: Run; VAR v: Run);
VAR p, q: LPiece;
BEGIN
WITH u: Piece DO
IF (v IS Piece) & ((u.attr = v.attr) OR u.attr.Equals(v.attr)) THEN
p := u; q := v(Piece);
IF (p.file = q.file) & (p.org + p.len = q.org) THEN
IF t.pc.prev = p THEN INC(t.pc.org, q.len)
ELSIF t.pc.prev = q THEN t.pc.prev := t.trailer; t.pc.org := 0
END;
INC(p.len, q.len); v := v.next
END
END
| u: LPiece DO (* ~(u IS Piece) *)
IF (v IS LPiece) & ~(v IS Piece) & ((u.attr = v.attr) OR u.attr.Equals(v.attr)) THEN
p := u(LPiece); q := v(LPiece);
IF (p.file = q.file) & (p.org + 2 * p.len = q.org) THEN
IF t.pc.prev = p THEN INC(t.pc.org, q.len)
ELSIF t.pc.prev = q THEN t.pc.prev := t.trailer; t.pc.org := 0
END;
INC(p.len, q.len); v := v.next
END
END
ELSE (* ignore: can't merge ViewRef runs *)
END
END Merge;
PROCEDURE Splice (un, v, w: Run); (* (u, un) -> (u, v ... w, un) *)
VAR u: Run;
BEGIN
IF v # w.next THEN (* non-empty stretch v ... w *)
u := un.prev;
u.next := v; v.prev := u; un.prev := w; w.next := un
END
END Splice;
PROCEDURE NewContext (r: ViewRef; text: StdModel): StdContext;
VAR c: StdContext;
BEGIN
NEW(c); c.text := text; c.ref := r;
Stores.Join(text, r.view);
RETURN c
END NewContext;
PROCEDURE CopyOfPiece (p: LPiece): LPiece;
VAR lp: LPiece; sp: Piece;
BEGIN
WITH p: Piece DO NEW(sp); sp^ := p^; RETURN sp
ELSE
NEW(lp);
lp.prev := p.prev; lp.next := p.next; lp.len := p.len; lp.attr := p.attr;
lp.file := p(LPiece).file; lp.org := p(LPiece).org;
RETURN lp
END
END CopyOfPiece;
PROCEDURE CopyOfViewRef (r: ViewRef; text: StdModel): ViewRef;
VAR v: ViewRef;
BEGIN
NEW(v); v^ := r^;
v.view := Views.CopyOf(r.view, Views.deep);
v.view.InitContext(NewContext(v, text));
RETURN v
END CopyOfViewRef;
PROCEDURE InvalCache (t: StdModel; pos: INTEGER);
VAR n: INTEGER;
BEGIN
n := t.id MOD cacheWidth;
IF cache[n].id = t.id THEN
IF pos <= cache[n].beg THEN cache[n].beg := 0; cache[n].end := 0
ELSIF pos < cache[n].end THEN cache[n].end := pos
END
END
END InvalCache;
PROCEDURE StdInit (t: StdModel);
VAR u: Run;
BEGIN
IF t.trailer = NIL THEN
NEW(u); u.len := MAX(INTEGER); u.attr := NIL; u.next := u; u.prev := u;
t.len := 0; t.id := nextId; INC(nextId); t.era := 0; t.trailer := u;
t.pc.prev := u; t.pc.org := 0;
IF t.spill = NIL THEN NEW(t.spill) END
END
END StdInit;
PROCEDURE CopyOf (src: StdModel; beg, end: INTEGER; dst: StdModel): StdModel;
VAR buf: StdModel; u, v, r, z, zn: Run; ud, vd: INTEGER;
BEGIN
ASSERT(beg < end, 20);
buf := Containers.CloneOf(dst)(StdModel);
ASSERT(buf.Domain() = NIL, 100);
Find(src, beg, u, ud); Find(src, end, v, vd);
z := buf.trailer; r := u;
WHILE r # v DO
WITH r: LPiece DO (* Piece or LPiece *)
zn := CopyOfPiece(r); DEC(zn.len, ud);
IF zn IS Piece THEN INC(zn(LPiece).org, ud) ELSE INC(zn(LPiece).org, 2 * ud) END
| r: ViewRef DO
zn := CopyOfViewRef(r, buf)
ELSE (* ignore *)
END;
z.next := zn; zn.prev := z; z := zn; r := r.next; ud := 0
END;
IF vd > 0 THEN (* v IS LPiece *)
zn := CopyOfPiece(v(LPiece)); zn.len := vd - ud;
IF zn IS Piece THEN INC(zn(LPiece).org, ud) ELSE INC(zn(LPiece).org, 2 * ud) END;
z.next := zn; zn.prev := z; z := zn
END;
z.next := buf.trailer; buf.trailer.prev := z;
buf.len := end - beg;
RETURN buf
END CopyOf;
PROCEDURE ProjectionOf (src: Model; beg, end: INTEGER; dst: StdModel): StdModel;
(* rider-conversion to eliminate covariance conflicts in binary operations *)
VAR buf: StdModel; rd: Reader; wr: Writer;
BEGIN
rd := src.NewReader(NIL); rd.SetPos(beg);
buf := Containers.CloneOf(dst)(StdModel); ASSERT(buf.Domain() = NIL, 100);
wr := buf.NewWriter(NIL);
WHILE beg < end DO
INC(beg);
rd.Read; wr.SetAttr(rd.attr);
IF rd.view # NIL THEN
wr.WriteView(Views.CopyOf(rd.view, Views.deep), rd.w, rd.h)
ELSE
wr.WriteChar(rd.char)
END
END;
RETURN buf
END ProjectionOf;
PROCEDURE Move (src: StdModel; beg, end: INTEGER; dest: StdModel; pos: INTEGER);
VAR pc: PieceCache; view: Views.View;
u, un, v, vn, w, wn: Run; ud, vd, wd: INTEGER;
(*initDom: BOOLEAN; newDom, dom: Stores.Domain;*)
upd: UpdateMsg; neut: Models.NeutralizeMsg;
BEGIN
Models.Broadcast(src, neut);
Find(src, beg, u, ud); Split(ud, u, un); pc := src.pc;
Find(src, end, v, vd); Split(vd, v, vn); src.pc := pc;
Merge(src, u, vn); u.next := vn; vn.prev := u;
DEC(src.len, end - beg);
InvalCache(src, beg);
INC(src.era);
upd.op := delete; upd.beg := beg; upd.end := beg + 1; upd.delta := beg - end;
Models.Broadcast(src, upd);
IF src = dest THEN
IF pos > end THEN DEC(pos, end - beg) END
ELSE
(*newDom := dest.Domain(); initDom := (src.Domain() = NIL) & (newDom # NIL);*)
w := un;
WHILE w # vn DO
(*
IF initDom THEN
dom := w.attr.Domain();
IF (dom # NIL) & (dom # newDom) THEN w.attr := Stores.CopyOf(w.attr)(Attributes) END;
Stores.InitDomain(w.attr, newDom)
END;
*)
IF ~Stores.Joined(dest, w.attr) THEN
IF ~Stores.Unattached(w.attr) THEN w.attr := Stores.CopyOf(w.attr)(Attributes) END;
Stores.Join(dest, w.attr)
END;
WITH w: ViewRef DO
view := w.view;
(*IF initDom THEN Stores.InitDomain(view, newDom) END;*)
Stores.Join(dest, view);
view.context(StdContext).text := dest
ELSE
END;
w := w.next
END
END;
Find(dest, pos, w, wd); Split(wd, w, wn); Splice(wn, un, v);
v := wn.prev; Merge(dest, v, wn); v.next := wn; wn.prev := v;
wn := w.next; Merge(dest, w, wn); w.next := wn; wn.prev := w;
INC(dest.len, end - beg);
InvalCache(dest, pos);
INC(dest.era);
upd.op := insert; upd.beg := pos; upd.end := pos + end - beg; upd.delta := end - beg;
Models.Broadcast(dest, upd)
END Move;
(* StdModel - operations *)
PROCEDURE (op: MoveOp) Do;
VAR src, dest: StdModel; beg, end, pos: INTEGER; neut: Models.NeutralizeMsg;
BEGIN
src := op.src; beg := op.beg; end := op.end; dest := op.dest; pos := op.pos;
IF src = dest THEN
IF pos < beg THEN
op.pos := end; op.beg := pos; op.end := pos + end - beg
ELSE
op.pos := beg; op.beg := pos - (end - beg); op.end := pos
END
ELSE
Models.Broadcast(op.src, neut); (* destination is neutralized by sequencer *)
op.dest := src; op.src := dest;
op.pos := beg; op.beg := pos; op.end := pos + end - beg
END;
Move(src, beg, end, dest, pos)
END Do;
PROCEDURE DoMove (name: Stores.OpName;
src: StdModel; beg, end: INTEGER;
dest: StdModel; pos: INTEGER
);
VAR op: MoveOp;
BEGIN
IF (beg < end) & ((src # dest) OR ~((beg <= pos) & (pos <= end))) THEN
NEW(op);
op.src := src; op.beg := beg; op.end := end;
op.dest := dest; op.pos := pos;
Models.Do(dest, name, op)
END
END DoMove;
PROCEDURE (op: EditOp) Do;
VAR text: StdModel; (*newDom, dom: Stores.Domain;*) pc: PieceCache;
u, un, v, vn: Run; sp: Piece; lp: LPiece; r: ViewRef;
ud, vd, beg, end, pos, len: INTEGER; w, h: INTEGER;
upd: UpdateMsg;
BEGIN
text := op.text;
CASE op.mode OF
deleteRange:
beg := op.beg; end := op.end; len := end - beg;
Find(text, beg, u, ud); Split(ud, u, un); pc := text.pc;
Find(text, end, v, vd); Split(vd, v, vn); text.pc := pc;
Merge(text, u, vn); u.next := vn; vn.prev := u;
DEC(text.len, len);
InvalCache(text, beg);
INC(text.era);
op.mode := moveBuf; op.canBunch := FALSE;
op.pos := beg; op.first := un; op.last := v; op.len := len;
upd.op := delete; upd.beg := beg; upd.end := beg + 1; upd.delta := -len;
Models.Broadcast(text, upd)
| moveBuf:
pos := op.pos;
Find(text, pos, u, ud); Split(ud, u, un); Splice(un, op.first, op.last);
INC(text.len, op.len);
InvalCache(text, pos);
INC(text.era);
op.mode := deleteRange;
op.beg := pos; op.end := pos + op.len;
upd.op := insert; upd.beg := pos; upd.end := pos + op.len; upd.delta := op.len;
Models.Broadcast(text, upd)
| writeSChar:
pos := op.pos;
InvalCache(text, pos);
Find(text, pos, u, ud); Split(ud, u, un);
IF (u.attr = op.attr) & (u IS Piece) & (u(Piece).file = text.spill.file)
& (u(Piece).org + u.len = op.len) THEN
INC(u.len);
IF text.pc.org >= pos THEN INC(text.pc.org) END
ELSE
(*
newDom := text.Domain();
IF newDom # NIL THEN
dom := op.attr.Domain();
IF (dom # NIL) & (dom # newDom) THEN
op.attr := Stores.CopyOf(op.attr)(Attributes)
END;
Stores.InitDomain(op.attr, newDom)
END;
*)
IF ~Stores.Joined(text, op.attr) THEN
IF ~Stores.Unattached(op.attr) THEN op.attr := Stores.CopyOf(op.attr)(Attributes) END;
Stores.Join(text, op.attr)
END;
NEW(sp); u.next := sp; sp.prev := u; sp.next := un; un.prev := sp;
sp.len := 1; sp.attr := op.attr;
sp.file := text.spill.file; sp.org := op.len;
IF text.pc.org > pos THEN INC(text.pc.org) END
END;
INC(text.len); INC(text.era);
op.mode := deleteRange;
upd.op := insert; upd.beg := pos; upd.end := pos + 1; upd.delta := 1;
Models.Broadcast(text, upd)
| writeChar:
pos := op.pos;
InvalCache(text, pos);
Find(text, pos, u, ud); Split(ud, u, un);
IF (u.attr = op.attr) & (u IS LPiece) & ~(u IS Piece) & (u(LPiece).file = text.spill.file)
& (u(LPiece).org + 2 * u.len = op.len) THEN
INC(u.len);
IF text.pc.org >= pos THEN INC(text.pc.org) END
ELSE
(*
newDom := text.Domain();
IF newDom # NIL THEN
dom := op.attr.Domain();
IF (dom # NIL) & (dom # newDom) THEN
op.attr := Stores.CopyOf(op.attr)(Attributes)
END;
Stores.InitDomain(op.attr, newDom)
END;
*)
IF ~Stores.Joined(text, op.attr) THEN
IF ~Stores.Unattached(op.attr) THEN op.attr := Stores.CopyOf(op.attr)(Attributes) END;
Stores.Join(text, op.attr)
END;
NEW(lp); u.next := lp; lp.prev := u; lp.next := un; un.prev := lp;
lp.len := 1; lp.attr := op.attr;
lp.file := text.spill.file; lp.org := op.len;
IF text.pc.org > pos THEN INC(text.pc.org) END
END;
INC(text.len); INC(text.era);
op.mode := deleteRange;
upd.op := insert; upd.beg := pos; upd.end := pos + 1; upd.delta := 1;
Models.Broadcast(text, upd)
| writeView:
pos := op.pos; r := op.first(ViewRef);
InvalCache(text, pos);
Find(text, pos, u, ud); Split(ud, u, un);
u.next := r; r.prev := u; r.next := un; un.prev := r;
INC(text.len); INC(text.era);
r.view.InitContext(NewContext(r, text));
(* Stores.InitDomain(r.view, text.Domain()); *)
Stores.Join(text, r.view);
w := r.w; h := r.h; r.w := defW; r.h := defH;
Properties.PreferredSize(r.view, minWidth, maxWidth, minHeight, maxHeight, defW, defH,
w, h
);
r.w := w; r.h := h;
op.mode := deleteRange;
upd.op := insert; upd.beg := pos; upd.end := pos + 1; upd.delta := 1;
Models.Broadcast(text, upd)
END
END Do;
PROCEDURE GetWriteOp (t: StdModel; pos: INTEGER; VAR op: EditOp; VAR bunch: BOOLEAN);
VAR last: Stores.Operation;
BEGIN
last := Models.LastOp(t);
IF (last # NIL) & (last IS EditOp) THEN
op := last(EditOp);
bunch := op.canBunch & (op.end = pos)
ELSE bunch := FALSE
END;
IF bunch THEN
INC(op.end)
ELSE
NEW(op); op.canBunch := TRUE;
op.text := t; op.beg := pos; op.end := pos + 1
END;
op.pos := pos
END GetWriteOp;
PROCEDURE SetPreferredSize (t: StdModel; v: Views.View);
VAR minW, maxW, minH, maxH, w, h: INTEGER;
BEGIN
t.GetEmbeddingLimits(minW, maxW, minH, maxH);
v.context.GetSize(w, h);
Properties.PreferredSize(v, minW, maxW, minH, maxH, w, h, w, h);
v.context.SetSize(w, h)
END SetPreferredSize;
PROCEDURE (op: SetAttrOp) Do;
VAR t: StdModel; attr: Attributes; z: AttrList; (*checkDom: BOOLEAN;*)
pc: PieceCache; u, un, v, vn: Run; ud, vd, pos, next: INTEGER;
upd: UpdateMsg;
BEGIN
t := op.text; z := op.list; pos := op.beg; (*checkDom := t.Domain() # NIL;*)
WHILE z # NIL DO
next := pos + z.len;
IF z.attr # NIL THEN
Find(t, pos, u, ud); Split(ud, u, un); pc := t.pc;
Find(t, next, v, vd); Split(vd, v, vn); t.pc := pc;
attr := un.attr;
WHILE un # vn DO
un.attr := z.attr;
(*
IF checkDom & (un.attr.Domain() # t.Domain()) THEN
IF un.attr.Domain() # NIL THEN un.attr := Stores.CopyOf(un.attr)(Attributes) END;
Stores.InitDomain(un.attr, t.Domain())
END;
*)
IF ~Stores.Joined(t, un.attr) THEN
IF ~Stores.Unattached(un.attr) THEN un.attr := Stores.CopyOf(un.attr)(Attributes) END;
Stores.Join(t, un.attr)
END;
Merge(t, u, un);
WITH un: ViewRef DO SetPreferredSize(t, un.view) ELSE END;
IF u.next = un THEN u := un; un := un.next ELSE u.next := un; un.prev := u END
END;
Merge(t, u, un); u.next := un; un.prev := u;
z.attr := attr
END;
pos := next; z := z.next
END;
INC(t.era);
upd.op := replace; upd.beg := op.beg; upd.end := pos; upd.delta := 0;
Models.Broadcast(t, upd)
END Do;
PROCEDURE (op: ResizeViewOp) Do;
VAR r: ViewRef; w, h: INTEGER; upd: UpdateMsg;
BEGIN
r := op.ref;
w := op.w; h := op.h; op.w := r.w; op.h := r.h; r.w := w; r.h := h;
INC(op.text.era);
upd.op := replace; upd.beg := op.pos; upd.end := op.pos + 1; upd.delta := 0;
Models.Broadcast(op.text, upd)
END Do;
PROCEDURE (op: ReplaceViewOp) Do;
VAR new: Views.View; upd: UpdateMsg;
BEGIN
new := op.new; op.new := op.ref.view; op.ref.view := new;
INC(op.text.era);
upd.op := replace; upd.beg := op.pos; upd.end := op.pos + 1; upd.delta := 0;
Models.Broadcast(op.text, upd)
END Do;
(* StdModel *)
PROCEDURE (t: StdModel) InitFrom (source: Containers.Model);
BEGIN
WITH source: StdModel DO
ASSERT(source.trailer # NIL, 20);
t.spill := source.spill; (* reduce no of temp files: share spill files among clones *)
StdInit(t)
END
END InitFrom;
PROCEDURE WriteCharacters (t: StdModel; VAR wr: Stores.Writer);
VAR r: Files.Reader; u: Run; len: INTEGER;
(*
sp: Properties.StorePref;
*)
buf: ARRAY 1024 OF BYTE;
BEGIN
r := NIL;
u := t.trailer.next;
WHILE u # t.trailer DO
WITH u: Piece DO
r := u.file.NewReader(r); r.SetPos(u.org);
len := u.len;
WHILE len > LEN(buf) DO
r.ReadBytes(buf, 0, LEN(buf)); wr.rider.WriteBytes(buf, 0, LEN(buf));
DEC(len, LEN(buf))
END;
r.ReadBytes(buf, 0, len); wr.rider.WriteBytes(buf, 0, len)
| u: LPiece DO (* ~(u IS Piece) *)
r := u.file.NewReader(r); r.SetPos(u.org);
len := 2 * u.len;
WHILE len > LEN(buf) DO
r.ReadBytes(buf, 0, LEN(buf)); wr.rider.WriteBytes(buf, 0, LEN(buf));
DEC(len, LEN(buf))
END;
r.ReadBytes(buf, 0, len); wr.rider.WriteBytes(buf, 0, len)
| u: ViewRef DO
(*
sp.view := u.view; Views.HandlePropMsg(u.view, sp);
IF sp.view # NIL THEN wr.WriteSChar(viewcode) END
*)
IF Stores.ExternalizeProxy(u.view) # NIL THEN
wr.WriteSChar(viewcode)
END
END;
u := u.next
END
END WriteCharacters;
PROCEDURE WriteAttributes (VAR wr: Stores.Writer; t: StdModel;
a: Attributes; VAR dict: AttrDict
);
VAR k, len: BYTE;
BEGIN
len := dict.len; k := 0; WHILE (k # len) & ~a.Equals(dict.attr[k]) DO INC(k) END;
wr.WriteByte(k);
IF k = len THEN
IF len < dictSize THEN dict.attr[len] := a; INC(dict.len) END;
(* ASSERT(Stores.Joined(t, a)); but bkwd-comp: *)
(* IF a.Domain() # d THEN always copy: bkwd-comp hack to avoid link *)
a := Stores.CopyOf(a)(Attributes); (* Stores.InitDomain(a, d); *) Stores.Join(t, a);
(* END; *)
WriteAttr(wr, a)
END
END WriteAttributes;
PROCEDURE (t: StdModel) Externalize (VAR wr: Stores.Writer);
VAR (*dom: Stores.Domain;*) u, v, un: Run;
attr: Attributes; dict: AttrDict;
org, runlen, pos: INTEGER; lchars: BOOLEAN;
inf: InfoMsg;
BEGIN
t.Externalize^(wr);
StdInit(t); (*dom := t.Domain();*)
wr.WriteVersion(0);
wr.WriteInt(0); org := wr.Pos();
u := t.trailer.next; v := t.trailer; dict.len := 0; lchars := FALSE;
WHILE u # v DO
attr := u.attr;
WITH u: Piece DO
runlen := u.len; un := u.next;
WHILE (un IS Piece) & un.attr.Equals(attr) DO
INC(runlen, un.len); un := un.next
END;
WriteAttributes(wr, t, attr, dict); wr.WriteInt(runlen)
| u: LPiece DO (* ~(u IS Piece) *)
runlen := 2 * u.len; un := u.next;
WHILE (un IS LPiece) & ~(un IS Piece) & un.attr.Equals(attr) DO
INC(runlen, 2 * un.len); un := un.next
END;
WriteAttributes(wr, t, attr, dict); wr.WriteInt(-runlen);
lchars := TRUE
| u: ViewRef DO
IF Stores.ExternalizeProxy(u.view) # NIL THEN
WriteAttributes(wr, t, attr, dict); wr.WriteInt(0);
wr.WriteInt(u.w); wr.WriteInt(u.h); Views.WriteView(wr, u.view)
END;
un := u.next
END;
u := un
END;
wr.WriteByte(-1);
pos := wr.Pos();
wr.SetPos(org - 5);
IF lchars THEN wr.WriteVersion(maxStdModelVersion)
ELSE wr.WriteVersion(noLCharStdModelVersion) (* version 0 did not support LONGCHAR *)
END;
wr.WriteInt(pos - org);
wr.SetPos(pos);
WriteCharacters(t, wr);
inf.op := store; Models.Broadcast(t, inf)
END Externalize;
PROCEDURE (t: StdModel) Internalize (VAR rd: Stores.Reader);
VAR u, un: Run; sp: Piece; lp: LPiece; v: ViewRef;
org, len: INTEGER; ano: BYTE; thisVersion: INTEGER;
attr: Attributes; dict: AttrDict;
BEGIN
ASSERT(t.Domain() = NIL, 20); ASSERT(t.len = 0, 21);
t.Internalize^(rd); IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxStdModelVersion, thisVersion);
IF rd.cancelled THEN RETURN END;
StdInit(t);
dict.len := 0; u := t.trailer;
rd.ReadInt(len); org := rd.Pos() + len;
rd.ReadByte(ano);
WHILE ano # -1 DO
IF ano = dict.len THEN
ReadAttr(rd, attr); Stores.Join(t, attr);
IF dict.len < dictSize THEN dict.attr[dict.len] := attr; INC(dict.len) END
ELSE
attr := dict.attr[ano]
END;
rd.ReadInt(len);
IF len > 0 THEN (* piece *)
NEW(sp); sp.len := len; sp.attr := attr;
sp.file := rd.rider.Base(); sp.org := org; un := sp;
INC(org, len)
ELSIF len < 0 THEN (* longchar piece *)
len := -len; ASSERT(~ODD(len), 100);
NEW(lp); lp.len := len DIV 2; lp.attr := attr;
lp.file := rd.rider.Base(); lp.org := org; un := lp;
INC(org, len)
ELSE (* len = 0 => embedded view *)
NEW(v); v.len := 1; v.attr := attr;
rd.ReadInt(v.w); rd.ReadInt(v.h); Views.ReadView(rd, v.view);
v.view.InitContext(NewContext(v, t));
un := v; INC(org)
END;
INC(t.len, un.len); u.next := un; un.prev := u; u := un;
rd.ReadByte(ano)
END;
rd.SetPos(org);
u.next := t.trailer; t.trailer.prev := u
END Internalize;
(*
PROCEDURE (t: StdModel) PropagateDomain;
VAR u: Run; dom: Stores.Domain;
BEGIN
IF t.Domain() # NIL THEN
u := t.trailer.next;
WHILE u # t.trailer DO
dom := u.attr.Domain();
IF (dom # NIL) & (dom # t.Domain()) THEN u.attr := Stores.CopyOf(u.attr)(Attributes) END;
Stores.InitDomain(u.attr, t.Domain());
WITH u: ViewRef DO Stores.InitDomain(u.view, t.Domain()) ELSE END;
u := u.next
END
END
END PropagateDomain;
*)
PROCEDURE (t: StdModel) GetEmbeddingLimits (OUT minW, maxW, minH, maxH: INTEGER);
BEGIN
minW := minWidth; maxW := maxWidth; minH := minHeight; maxH := maxHeight
END GetEmbeddingLimits;
PROCEDURE (t: StdModel) Length (): INTEGER;
BEGIN
StdInit(t);
RETURN t.len
END Length;
PROCEDURE (t: StdModel) NewReader (old: Reader): Reader;
VAR rd: StdReader;
BEGIN
StdInit(t);
IF (old # NIL) & (old IS StdReader) THEN rd := old(StdReader) ELSE NEW(rd) END;
IF rd.base # t THEN
rd.base := t; rd.era := -1; rd.SetPos(0)
ELSIF rd.pos > t.len THEN
rd.SetPos(t.len)
END;
rd.eot := FALSE;
RETURN rd
END NewReader;
PROCEDURE (t: StdModel) NewWriter (old: Writer): Writer;
VAR wr: StdWriter;
BEGIN
StdInit(t);
IF (old # NIL) & (old IS StdWriter) THEN wr := old(StdWriter) ELSE NEW(wr) END;
IF (wr.base # t) OR (wr.pos > t.len) THEN
wr.base := t; wr.era := -1; wr.SetPos(t.len)
END;
wr.SetAttr(dir.attr);
RETURN wr
END NewWriter;
PROCEDURE (t: StdModel) InsertCopy (pos: INTEGER; t0: Model; beg0, end0: INTEGER);
VAR buf: StdModel;
BEGIN
StdInit(t);
ASSERT(0 <= pos, 21); ASSERT(pos <= t.len, 22);
ASSERT(0 <= beg0, 23); ASSERT(beg0 <= end0, 24); ASSERT(end0 <= t0.Length(), 25);
IF beg0 < end0 THEN
WITH t0: StdModel DO buf := CopyOf(t0, beg0, end0, t)
ELSE buf := ProjectionOf(t0, beg0, end0, t)
END;
(* IF t.Domain() # NIL THEN Stores.InitDomain(buf,t.Domain()) END; *)
Stores.Join(t, buf);
DoMove("#System:Copying", buf, 0, buf.len, t, pos)
END
END InsertCopy;
PROCEDURE (t: StdModel) Insert (pos: INTEGER; t0: Model; beg, end: INTEGER);
BEGIN
StdInit(t);
ASSERT(0 <= pos, 21); ASSERT(pos <= t.len, 22);
ASSERT(0 <= beg, 23); ASSERT(beg <= end, 24); ASSERT(end <= t0.Length(), 25);
IF beg < end THEN
IF (t.Domain() # NIL) & (t0 IS StdModel) & (t0.Domain() = t.Domain()) THEN
DoMove("#System:Moving", t0(StdModel), beg, end, t, pos)
ELSE (* moving across domains *)
t.InsertCopy(pos, t0, beg, end); t0.Delete(beg, end)
END
END
END Insert;
PROCEDURE (t: StdModel) Append (t0: Model);
VAR len0: INTEGER;
BEGIN
StdInit(t);
ASSERT(t # t0, 20);
len0 := t0.Length();
IF len0 > 0 THEN
IF (t.Domain() # NIL) & (t0 IS StdModel) & (t0.Domain() = t.Domain()) THEN
DoMove("#Text:Appending", t0(StdModel), 0, len0, t, t.len)
ELSE (* moving across domains *)
t.InsertCopy(t.len, t0, 0, len0); t0.Delete(0, len0)
END
END
END Append;
PROCEDURE (t: StdModel) Delete (beg, end: INTEGER);
VAR op: EditOp;
BEGIN
StdInit(t);
ASSERT(0 <= beg, 20); ASSERT(beg <= end, 21); ASSERT(end <= t.len, 22);
IF beg < end THEN
NEW(op); op.mode := deleteRange; op.canBunch := FALSE;
op.text := t; op.beg := beg; op.end := end;
Models.Do(t, "#System:Deleting", op)
END
END Delete;
PROCEDURE (t: StdModel) SetAttr (beg, end: INTEGER; attr: Attributes);
VAR op: SetAttrOp; zp, z: AttrList;
u, v, w: Run; ud, vd: INTEGER; modified: BOOLEAN;
BEGIN
StdInit(t);
ASSERT(0 <= beg, 20); ASSERT(beg <= end, 21); ASSERT(end <= t.len, 22);
IF beg < end THEN
NEW(op); op.text := t; op.beg := beg;
Find(t, beg, u, ud); Find(t, end, v, vd);
IF vd > 0 THEN w := v.next ELSE w := v END;
zp := NIL; modified := FALSE;
WHILE u # w DO
IF u = v THEN INC(ud, v.len - vd) END;
NEW(z); z.len := u.len - ud; z.attr := attr;
IF zp = NIL THEN op.list := z ELSE zp.next:= z END;
zp := z;
modified := modified OR ~u.attr.Equals(attr);
u := u.next; ud := 0
END;
IF modified THEN Models.Do(t, "#Text:AttributeChange", op) END
END
END SetAttr;
PROCEDURE (t: StdModel) Prop (beg, end: INTEGER): Properties.Property;
VAR p, q: Properties.Property; tp: Prop;
u, v, w: Run; ud, vd: INTEGER; equal: BOOLEAN;
rd: Reader;
BEGIN
StdInit(t);
ASSERT(0 <= beg, 20); ASSERT(beg <= end, 21); ASSERT(end <= t.len, 22);
IF beg < end THEN
Find(t, beg, u, ud); Find(t, end, v, vd);
IF vd > 0 THEN w := v.next ELSE w := v END;
p := u.attr.Prop();
u := u.next;
WHILE u # w DO
Properties.Intersect(p, u.attr.Prop(), equal);
u := u.next
END;
IF beg + 1 = end THEN
t.rd := t.NewReader(t.rd); rd := t.rd;
rd.SetPos(beg); rd.Read;
IF (rd.view = NIL) OR (rd.char # viewcode) THEN
q := p; WHILE (q # NIL) & ~(q IS Prop) DO q := q.next END;
IF q # NIL THEN
tp := q(Prop)
ELSE NEW(tp); Properties.Insert(p, tp)
END;
INCL(tp.valid, code); INCL(tp.known, code); INCL(tp.readOnly, code);
tp.code := rd.char
END
END
ELSE p := NIL
END;
RETURN p
END Prop;
PROCEDURE (t: StdModel) Modify (beg, end: INTEGER; old, p: Properties.Property);
VAR op: SetAttrOp; zp, z: AttrList;
u, v, w: Run; ud, vd: INTEGER; equal, modified: BOOLEAN;
q: Properties.Property;
BEGIN
StdInit(t);
ASSERT(0 <= beg, 20); ASSERT(beg <= end, 21); ASSERT(end <= t.len, 22);
IF (beg < end) & (p # NIL) THEN
NEW(op); op.text := t; op.beg := beg;
Find(t, beg, u, ud); Find(t, end, v, vd);
IF vd > 0 THEN w := v.next ELSE w := v END;
zp := NIL; modified := FALSE;
WHILE u # w DO
IF u = v THEN INC(ud, v.len - vd) END;
IF old # NIL THEN
q := u.attr.Prop();
Properties.Intersect(q, old, equal); (* q := q * old *)
Properties.Intersect(q, old, equal) (* equal := q = old *)
END;
NEW(z); z.len := u.len - ud;
IF (old = NIL) OR equal THEN
z.attr := ModifiedAttr(u.attr, p);
modified := modified OR ~u.attr.Equals(z.attr)
END;
IF zp = NIL THEN op.list := z ELSE zp.next := z END;
zp := z;
u := u.next; ud := 0
END;
IF modified THEN Models.Do(t, "#System:Modifying", op) END
END
END Modify;
PROCEDURE (t: StdModel) ReplaceView (old, new: Views.View);
VAR c: StdContext; op: ReplaceViewOp;
BEGIN
StdInit(t);
ASSERT(old.context # NIL, 20); ASSERT(old.context IS StdContext, 21);
ASSERT(old.context(StdContext).text = t, 22);
ASSERT((new.context = NIL) OR (new.context = old.context), 24);
IF new # old THEN
c := old.context(StdContext);
IF new.context = NIL THEN new.InitContext(c) END;
(* Stores.InitDomain(new, t.Domain()); *)
Stores.Join(t, new);
NEW(op); op.text := t; op.pos := c.Pos(); op.ref := c.ref; op.new := new;
Models.Do(t, "#System:Replacing", op)
END
END ReplaceView;
PROCEDURE (t: StdModel) CopyFrom- (source: Stores.Store);
BEGIN
StdInit(t);
WITH source: StdModel DO t.InsertCopy(0, source, 0, source.len) END
END CopyFrom;
PROCEDURE (t: StdModel) Replace (beg, end: INTEGER; t0: Model; beg0, end0: INTEGER);
VAR script: Stores.Operation;
BEGIN
StdInit(t);
ASSERT(0 <= beg, 20); ASSERT(beg <= end, 21); ASSERT(end <= t.len, 22);
ASSERT(0 <= beg0, 23); ASSERT(beg0 <= end0, 24); ASSERT(end0 <= t0.Length(), 25);
ASSERT(t # t0, 26);
Models.BeginScript(t, "#System:Replacing", script);
t.Delete(beg, end); t.Insert(beg, t0, beg0, end0);
Models.EndScript(t, script)
END Replace;
(* StdContext *)
PROCEDURE (c: StdContext) ThisModel (): Model;
BEGIN
RETURN c.text
END ThisModel;
PROCEDURE (c: StdContext) GetSize (OUT w, h: INTEGER);
BEGIN
w := c.ref.w; h := c.ref.h
END GetSize;
PROCEDURE (c: StdContext) SetSize (w, h: INTEGER);
VAR t: StdModel; r: ViewRef; op: ResizeViewOp;
BEGIN
t := c.text; r := c.ref;
IF w = Views.undefined THEN w := r.w END;
IF h = Views.undefined THEN h := r.h END;
Properties.PreferredSize(r.view, minWidth, maxWidth, minHeight, maxHeight, r.w, r.h, w, h);
IF (w # r.w) OR (h # r.h) THEN
NEW(op); op.text := t; op.pos := c.Pos(); op.ref := r; op.w := w; op.h := h;
Models.Do(t, "#System:Resizing", op)
END
END SetSize;
PROCEDURE (c: StdContext) Normalize (): BOOLEAN;
BEGIN
RETURN FALSE
END Normalize;
PROCEDURE (c: StdContext) Pos (): INTEGER;
VAR t: StdModel; u, r, w: Run; pos: INTEGER;
BEGIN
t := c.text; r := c.ref;
IF t.pc.prev.next # r THEN
u := t.trailer.next; w := t.trailer; pos := 0;
WHILE (u # r) & (u # w) DO INC(pos, u.len); u := u.next END;
ASSERT(u = r, 20);
t.pc.prev := r.prev; t.pc.org := pos
END;
RETURN t.pc.org
END Pos;
PROCEDURE (c: StdContext) Attr (): Attributes;
BEGIN
RETURN c.ref.attr
END Attr;
(* StdReader *)
PROCEDURE RemapView (rd: StdReader);
VAR p: Pref;
BEGIN
p.opts := {}; Views.HandlePropMsg(rd.view, p);
IF maskChar IN p.opts THEN rd.char := p.mask ELSE rd.char := viewcode END
END RemapView;
PROCEDURE Reset (rd: StdReader);
VAR t: StdModel;
BEGIN
t := rd.base;
Find(t, rd.pos, rd.run, rd.off); rd.era := t.era
END Reset;
PROCEDURE (rd: StdReader) Base (): Model;
BEGIN
RETURN rd.base
END Base;
PROCEDURE (rd: StdReader) SetPos (pos: INTEGER);
BEGIN
ASSERT(pos >= 0, 20); ASSERT(rd.base # NIL, 21); ASSERT(pos <= rd.base.len, 22);
rd.eot := FALSE; rd.attr := NIL; rd.char := 0X; rd.view := NIL;
IF (rd.pos # pos) OR (rd.run = rd.base.trailer) THEN
rd.pos := pos; rd.era := -1
END
END SetPos;
PROCEDURE (rd: StdReader) Pos (): INTEGER;
BEGIN
RETURN rd.pos
END Pos;
PROCEDURE (rd: StdReader) Read;
VAR t: StdModel; u: Run; n, pos, len: INTEGER; lc: ARRAY 2 OF BYTE;
BEGIN
t := rd.base;
n := t.id MOD cacheWidth;
IF rd.era # t.era THEN Reset(rd) END;
u := rd.run;
WITH u: Piece DO
rd.attr := u.attr;
pos := rd.pos MOD cacheLen;
IF ~((cache[n].id = t.id) & (cache[n].beg <= rd.pos) & (rd.pos < cache[n].end)) THEN
(* cache miss *)
IF cache[n].id # t.id THEN cache[n].id := t.id; cache[n].beg := 0; cache[n].end := 0 END;
len := cacheLine;
IF len > cacheLen - pos THEN len := cacheLen - pos END;
IF len > u.len - rd.off THEN len := u.len - rd.off END;
rd.reader := u.file.NewReader(rd.reader); rd.reader.SetPos(u.org + rd.off);
rd.reader.ReadBytes(cache[n].buf, pos, len);
IF rd.pos = cache[n].end THEN
cache[n].end := rd.pos + len;
(*
INC(cache[n].end, len);
*)
IF cache[n].end - cache[n].beg >= cacheLen THEN
cache[n].beg := cache[n].end - (cacheLen - 1)
END
ELSE cache[n].beg := rd.pos; cache[n].end := rd.pos + len
END
END;
rd.char := CHR(cache[n].buf[pos] MOD 256); rd.view := NIL;
INC(rd.pos); INC(rd.off);
IF rd.off = u.len THEN rd.run := u.next; rd.off := 0 END
| u: LPiece DO (* ~(u IS Piece) *)
rd.attr := u.attr;
rd.reader := u.file.NewReader(rd.reader); rd.reader.SetPos(u.org + rd.off * 2);
rd.reader.ReadBytes(lc, 0, 2);
rd.char := CHR(lc[0] MOD 256 + 256 * (lc[1] + 128)); rd.view := NIL;
IF (cache[n].id = t.id) & (rd.pos = cache[n].end) THEN
cache[n].end := cache[n].end + 1;
IF cache[n].end - cache[n].beg >= cacheLen THEN cache[n].beg := cache[n].beg + 1 END;
(*
INC(cache[n].end);
IF cache[n].end - cache[n].beg >= cacheLen THEN INC(cache[n].beg) END
*)
END;
INC(rd.pos); INC(rd.off);
IF rd.off = u.len THEN rd.run := u.next; rd.off := 0 END
| u: ViewRef DO
rd.attr := u.attr;
rd.view := u.view; rd.w := u.w; rd.h := u.h; RemapView(rd);
IF (cache[n].id = t.id) & (rd.pos = cache[n].end) THEN
cache[n].end := cache[n].end + 1;
IF cache[n].end - cache[n].beg >= cacheLen THEN cache[n].beg := cache[n].beg + 1 END;
(*
INC(cache[n].end);
IF cache[n].end - cache[n].beg >= cacheLen THEN INC(cache[n].beg) END
*)
END;
INC(rd.pos); rd.run := u.next; rd.off := 0
ELSE
rd.eot := TRUE; rd.attr := NIL; rd.char := 0X; rd.view := NIL
END
END Read;
PROCEDURE (rd: StdReader) ReadPrev;
VAR t: StdModel; u: Run; n, pos, len: INTEGER; lc: ARRAY 2 OF BYTE;
BEGIN
t := rd.base;
n := t.id MOD cacheWidth;
IF rd.era # t.era THEN Reset(rd) END;
IF rd.off > 0 THEN DEC(rd.off)
ELSIF rd.pos > 0 THEN
rd.run := rd.run.prev; rd.off := rd.run.len - 1
ELSE rd.run := t.trailer
END;
u := rd.run;
WITH u: Piece DO
rd.attr := u.attr;
DEC(rd.pos);
pos := rd.pos MOD cacheLen;
IF ~((cache[n].id = t.id) & (cache[n].beg <= rd.pos) & (rd.pos < cache[n].end)) THEN
(* cache miss *)
IF cache[n].id # t.id THEN cache[n].id := t.id; cache[n].beg := 0; cache[n].end := 0 END;
len := cacheLine;
IF len > pos + 1 THEN len := pos + 1 END;
IF len > rd.off + 1 THEN len := rd.off + 1 END;
rd.reader := u.file.NewReader(rd.reader);
rd.reader.SetPos(u.org + rd.off - (len - 1));
rd.reader.ReadBytes(cache[n].buf, pos - (len - 1), len);
IF rd.pos = cache[n].beg - 1 THEN
cache[n].beg := cache[n] .beg - len;
(*
DEC(cache[n].beg, len);
*)
IF cache[n].end - cache[n].beg >= cacheLen THEN
cache[n].end := cache[n].beg + (cacheLen - 1)
END
ELSE cache[n].beg := rd.pos - (len - 1); cache[n].end := rd.pos + 1
END
END;
rd.char := CHR(cache[n].buf[pos] MOD 256); rd.view := NIL
| u: LPiece DO (* ~(u IS Piece) *)
rd.attr := u.attr;
rd.reader := u.file.NewReader(rd.reader);
rd.reader.SetPos(u.org + 2 * rd.off);
rd.reader.ReadBytes(lc, 0, 2);
rd.char := CHR(lc[0] MOD 256 + 256 * (lc[1] + 128)); rd.view := NIL;
IF (cache[n].id = t.id) & (rd.pos = cache[n].beg) THEN
cache[n].beg := cache[n].beg - 1;
IF cache[n].end - cache[n].beg >= cacheLen THEN cache[n].end := cache[n].end - 1 END
(*
DEC(cache[n].beg);
IF cache[n].end - cache[n].beg >= cacheLen THEN DEC(cache[n].end) END
*)
END;
DEC(rd.pos)
| u: ViewRef DO
rd.attr := u.attr;
rd.view := u.view; rd.w := u.w; rd.h := u.h; RemapView(rd);
IF (cache[n].id = t.id) & (rd.pos = cache[n].beg) THEN
cache[n].beg := cache[n].beg - 1;
IF cache[n].end - cache[n].beg >= cacheLen THEN cache[n].end := cache[n].end - 1 END
(*
DEC(cache[n].beg);
IF cache[n].end - cache[n].beg >= cacheLen THEN DEC(cache[n].end) END
*)
END;
DEC(rd.pos)
ELSE
rd.eot := TRUE; rd.attr := NIL; rd.char := 0X; rd.view := NIL
END
END ReadPrev;
PROCEDURE (rd: StdReader) ReadChar (OUT ch: CHAR);
BEGIN
rd.Read; ch := rd.char
END ReadChar;
PROCEDURE (rd: StdReader) ReadPrevChar (OUT ch: CHAR);
BEGIN
rd.ReadPrev; ch := rd.char
END ReadPrevChar;
PROCEDURE (rd: StdReader) ReadView (OUT v: Views.View);
VAR t: StdModel; u: Run;
BEGIN
t := rd.base;
IF rd.era # t.era THEN Reset(rd) END;
DEC(rd.pos, rd.off);
u := rd.run;
WHILE u IS LPiece DO INC(rd.pos, u.len); u := u.next END;
WITH u: ViewRef DO
INC(rd.pos); rd.run := u.next; rd.off := 0;
rd.attr := u.attr; rd.view := u.view; rd.w := u.w; rd.h := u.h; RemapView(rd)
ELSE (* u = t.trailer *)
ASSERT(u = t.trailer, 100);
rd.run := u; rd.off := 0;
rd.eot := TRUE; rd.attr := NIL; rd.char := 0X; rd.view := NIL
END;
v := rd.view
END ReadView;
PROCEDURE (rd: StdReader) ReadPrevView (OUT v: Views.View);
VAR t: StdModel; u: Run;
BEGIN
t := rd.base;
IF rd.era # t.era THEN Reset(rd) END;
DEC(rd.pos, rd.off);
u := rd.run.prev;
WHILE u IS LPiece DO DEC(rd.pos, u.len); u := u.prev END;
rd.run := u; rd.off := 0;
WITH u: ViewRef DO
DEC(rd.pos);
rd.attr := u.attr; rd.view := u.view; rd.w := u.w; rd.h := u.h; RemapView(rd)
ELSE (* u = t.trailer *)
ASSERT(u = t.trailer, 100);
rd.eot := TRUE; rd.attr := NIL; rd.char := 0X; rd.view := NIL
END;
v := rd.view
END ReadPrevView;
PROCEDURE (rd: StdReader) ReadRun (OUT attr: Attributes);
VAR t: StdModel; a0: Attributes; u, trailer: Run; pos: INTEGER;
BEGIN
t := rd.base;
IF rd.era # t.era THEN Reset(rd) END;
a0 := rd.attr; u := rd.run; pos := rd.pos - rd.off; trailer := t.trailer;
WHILE (u.attr = a0) & ~(u IS ViewRef) & (u # trailer) DO
INC(pos, u.len); u := u.next
END;
rd.run := u; rd.pos := pos; rd.off := 0;
rd.Read;
attr := rd.attr
END ReadRun;
PROCEDURE (rd: StdReader) ReadPrevRun (OUT attr: Attributes);
VAR t: StdModel; a0: Attributes; u, trailer: Run; pos: INTEGER;
BEGIN
t := rd.base;
IF rd.era # t.era THEN Reset(rd) END;
a0 := rd.attr; u := rd.run; pos := rd.pos - rd.off; trailer := t.trailer;
IF u # trailer THEN u := u.prev; DEC(pos, u.len) END;
WHILE (u.attr = a0) & ~(u IS ViewRef) & (u # trailer) DO
u := u.prev; DEC(pos, u.len)
END;
IF u # trailer THEN
rd.run := u.next; rd.pos := pos + u.len; rd.off := 0
ELSE
rd.run := trailer; rd.pos := 0; rd.off := 0
END;
rd.ReadPrev;
attr := rd.attr
END ReadPrevRun;
(* StdWriter *)
PROCEDURE WriterReset (wr: StdWriter);
VAR t: StdModel; u: Run; uo: INTEGER;
BEGIN
t := wr.base;
Find(t, wr.pos, u, uo); Split(uo, u, wr.run); wr.era := t.era
END WriterReset;
PROCEDURE (wr: StdWriter) Base (): Model;
BEGIN
RETURN wr.base
END Base;
PROCEDURE (wr: StdWriter) SetPos (pos: INTEGER);
BEGIN
ASSERT(pos >= 0, 20); ASSERT(wr.base # NIL, 21); ASSERT(pos <= wr.base.len, 22);
IF wr.pos # pos THEN
wr.pos := pos; wr.era := -1
END
END SetPos;
PROCEDURE (wr: StdWriter) Pos (): INTEGER;
BEGIN
RETURN wr.pos
END Pos;
PROCEDURE WriteSChar (wr: StdWriter; ch: SHORTCHAR);
VAR t: StdModel; u, un: Run; p: Piece; pos, spillPos: INTEGER;
op: EditOp; bunch: BOOLEAN;
BEGIN
t := wr.base; pos := wr.pos;
IF t.spill.file = NIL THEN OpenSpill(t.spill) END;
t.spill.writer.WriteByte(SHORT(ORD(ch))); spillPos := t.spill.len; t.spill.len := spillPos + 1;
IF (t.Domain() = NIL) OR (t.Domain().GetSequencer() = NIL) THEN
(* optimized for speed - writing to unbound text *)
InvalCache(t, pos);
IF wr.era # t.era THEN WriterReset(wr) END;
un := wr.run; u := un.prev;
IF (u.attr # NIL) & u.attr.Equals(wr.attr) & (u IS Piece) & (u(Piece).file = t.spill.file)
& (u(Piece).org + u.len = spillPos) THEN
INC(u.len);
IF t.pc.org >= pos THEN INC(t.pc.org) END
ELSE
NEW(p); u.next := p; p.prev := u; p.next := un; un.prev := p;
p.len := 1; p.attr := wr.attr;
p.file := t.spill.file; p.org := spillPos;
IF t.pc.org > pos THEN INC(t.pc.org) END;
IF ~Stores.Joined(t, p.attr) THEN
IF ~Stores.Unattached(p.attr) THEN p.attr := Stores.CopyOf(p.attr)(Attributes) END;
Stores.Join(t, p.attr)
END
END;
INC(t.era); INC(t.len);
INC(wr.era)
ELSE
GetWriteOp(t, pos, op, bunch);
IF (op.attr = NIL) OR ~op.attr.Equals(wr.attr) THEN op.attr := wr.attr END;
op.mode := writeSChar; (*op.attr := wr.attr;*) op.len := spillPos;
IF bunch THEN Models.Bunch(t) ELSE Models.Do(t, "#System:Inserting", op) END
END;
wr.pos := pos + 1
END WriteSChar;
PROCEDURE (wr: StdWriter) WriteChar (ch: CHAR);
VAR t: StdModel; u, un: Run; lp: LPiece; pos, spillPos: INTEGER;
fw: Files.Writer; op: EditOp; bunch: BOOLEAN;
BEGIN
IF (ch >= 20X) & (ch < 7FX)
OR (ch = tab) OR (ch = line) OR (ch = para)
OR (ch = zwspace) OR (ch = digitspace)
OR (ch = hyphen) OR (ch = nbhyphen) OR (ch >= 0A0X) & (ch < 100X) THEN
WriteSChar(wr, SHORT(ch)) (* could inline! *)
ELSIF ch = 200BX THEN wr.WriteChar(zwspace)
ELSIF ch = 2010X THEN wr.WriteChar(hyphen)
ELSIF ch = 2011X THEN wr.WriteChar(nbhyphen)
ELSIF ch >= 100X THEN
t := wr.base; pos := wr.pos;
IF t.spill.file = NIL THEN OpenSpill(t.spill) END;
fw := t.spill.writer;
fw.WriteByte(SHORT(SHORT(ORD(ch))));
fw.WriteByte(SHORT(SHORT(ORD(ch) DIV 256 - 128)));
spillPos := t.spill.len; t.spill.len := spillPos + 2;
IF (t.Domain() = NIL) OR (t.Domain().GetSequencer() = NIL) THEN
(* optimized for speed - writing to unbound text *)
InvalCache(t, pos);
IF wr.era # t.era THEN WriterReset(wr) END;
un := wr.run; u := un.prev;
IF (u.attr # NIL) & u.attr.Equals(wr.attr) & (u IS LPiece) & ~(u IS Piece) & (u(LPiece).file = t.spill.file)
& (u(LPiece).org + 2 * u.len = spillPos) THEN
INC(u.len);
IF t.pc.org >= pos THEN INC(t.pc.org) END
ELSE
NEW(lp); u.next := lp; lp.prev := u; lp.next := un; un.prev := lp;
lp.len := 1; lp.attr := wr.attr;
lp.file := t.spill.file; lp.org := spillPos;
IF t.pc.org > pos THEN INC(t.pc.org) END;
IF ~Stores.Joined(t, lp.attr) THEN
IF ~Stores.Unattached(lp.attr) THEN lp.attr := Stores.CopyOf(lp.attr)(Attributes) END;
Stores.Join(t, lp.attr)
END
END;
INC(t.era); INC(t.len);
INC(wr.era)
ELSE
GetWriteOp(t, pos, op, bunch);
IF (op.attr = NIL) OR ~op.attr.Equals(wr.attr) THEN op.attr := wr.attr END;
op.mode := writeChar; (*op.attr := wr.attr;*) op.len := spillPos;
IF bunch THEN Models.Bunch(t) ELSE Models.Do(t, "#System:Inserting", op) END
END;
wr.pos := pos + 1
END
END WriteChar;
PROCEDURE (wr: StdWriter) WriteView (view: Views.View; w, h: INTEGER);
VAR t: StdModel; u, un: Run; r: ViewRef; pos: INTEGER;
op: EditOp; bunch: BOOLEAN;
BEGIN
ASSERT(view # NIL, 20); ASSERT(view.context = NIL, 21);
t := wr.base; pos := wr.pos;
Stores.Join(t, view);
IF (t.Domain() = NIL) OR (t.Domain().GetSequencer() = NIL) THEN
(* optimized for speed - writing to unbound text *)
IF wr.era # t.era THEN WriterReset(wr) END;
InvalCache(t, pos);
NEW(r); r.len := 1; r.attr := wr.attr; r.view := view; r.w := defW; r.h := defH;
un := wr.run; u := un.prev; u.next := r; r.prev := u; r.next := un; un.prev := r;
IF t.pc.org > pos THEN INC(t.pc.org) END;
INC(t.era); INC(t.len);
view.InitContext(NewContext(r, t));
Properties.PreferredSize(view, minWidth, maxWidth, minHeight, maxHeight, defW, defH,
w, h
);
r.w := w; r.h := h;
INC(wr.era)
ELSE
NEW(r); r.len := 1; r.attr := wr.attr; r.view := view; r.w := w; r.h := h;
GetWriteOp(t, pos, op, bunch);
op.mode := writeView; op.first := r;
IF bunch THEN Models.Bunch(t) ELSE Models.Do(t, "#System:Inserting", op) END
END;
INC(wr.pos)
END WriteView;
(* StdDirectory *)
PROCEDURE (d: StdDirectory) New (): Model;
VAR t: StdModel;
BEGIN
NEW(t); StdInit(t); RETURN t
END New;
(** miscellaneous procedures **)
(*
PROCEDURE DumpRuns* (t: Model);
VAR u: Run; n, i, beg, end: INTEGER; name: ARRAY 64 OF CHAR; r: Files.Reader; b: BYTE;
BEGIN
Sub.synch := FALSE;
WITH t: StdModel DO
u := t.trailer.next;
REPEAT
WITH u: Piece DO
Sub.String("short");
Sub.Int(u.len);
Sub.Char(" "); Sub.IntForm(SYSTEM.ADR(u.file^), 16, 8, "0", FALSE);
Sub.Int(u.org); Sub.Char(" ");
r := u.file.NewReader(NIL); r.SetPos(u.org); i := 0;
WHILE i < 16 DO r.ReadByte(b); Sub.Char(CHR(b)); INC(i) END;
Sub.Ln
| u: LPiece DO (* ~(u IS Piece) *)
Sub.String("long");
Sub.Int(-u.len);
Sub.Char(" "); Sub.IntForm(SYSTEM.ADR(u.file^), 16, 8, "0", FALSE);
Sub.Int(u.org); Sub.Char(" ");
r := u.file.NewReader(NIL); r.SetPos(u.org); i := 0;
WHILE i < 16 DO r.ReadByte(b); Sub.Char(CHR(b)); INC(i) END;
Sub.Ln
| u: ViewRef DO
Sub.String("view");
Services.GetTypeName(u.view, name);
Sub.String(name); Sub.Int(u.w); Sub.Int(u.h); Sub.Ln
ELSE
Sub.Char("?"); Sub.Ln
END;
u := u.next
UNTIL u = t.trailer;
n := t.id MOD cacheWidth;
IF cache[n].id = t.id THEN
beg := cache[n].beg; end := cache[n].end;
Sub.Int(beg); Sub.Int(end); Sub.Ln;
Sub.Char("{");
WHILE beg < end DO Sub.Char(CHR(cache[n].buf[beg MOD cacheLen])); INC(beg) END;
Sub.Char("}"); Sub.Ln
ELSE Sub.String("not cached"); Sub.Ln
END
END
END DumpRuns;
*)
PROCEDURE NewColor* (a: Attributes; color: Ports.Color): Attributes;
BEGIN
ASSERT(a # NIL, 20); ASSERT(a.init, 21);
stdProp.valid := {Properties.color}; stdProp.color.val := color;
RETURN ModifiedAttr(a, stdProp)
END NewColor;
PROCEDURE NewFont* (a: Attributes; font: Fonts.Font): Attributes;
BEGIN
ASSERT(a # NIL, 20); ASSERT(a.init, 21);
stdProp.valid := {Properties.typeface .. Properties.weight};
stdProp.typeface := font.typeface$;
stdProp.size := font.size;
stdProp.style.val := font.style;
stdProp.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout};
stdProp.weight := font.weight;
RETURN ModifiedAttr(a, stdProp)
END NewFont;
PROCEDURE NewOffset* (a: Attributes; offset: INTEGER): Attributes;
BEGIN
ASSERT(a # NIL, 20); ASSERT(a.init, 21);
prop.valid := {0 (*global constant offset masked by param :-( *)}; prop.offset := offset;
RETURN ModifiedAttr(a, prop)
END NewOffset;
PROCEDURE NewTypeface* (a: Attributes; typeface: Fonts.Typeface): Attributes;
BEGIN
ASSERT(a # NIL, 20); ASSERT(a.init, 21);
stdProp.valid := {Properties.typeface}; stdProp.typeface := typeface;
RETURN ModifiedAttr(a, stdProp)
END NewTypeface;
PROCEDURE NewSize* (a: Attributes; size: INTEGER): Attributes;
BEGIN
ASSERT(a # NIL, 20); ASSERT(a.init, 21);
stdProp.valid := {Properties.size}; stdProp.size := size;
RETURN ModifiedAttr(a, stdProp)
END NewSize;
PROCEDURE NewStyle* (a: Attributes; style: SET): Attributes;
BEGIN
ASSERT(a # NIL, 20); ASSERT(a.init, 21);
stdProp.valid := {Properties.style}; stdProp.style.val := style; stdProp.style.mask := -{};
RETURN ModifiedAttr(a, stdProp)
END NewStyle;
PROCEDURE NewWeight* (a: Attributes; weight: INTEGER): Attributes;
BEGIN
ASSERT(a # NIL, 20); ASSERT(a.init, 21);
stdProp.valid := {Properties.weight}; stdProp.weight := weight;
RETURN ModifiedAttr(a, stdProp)
END NewWeight;
PROCEDURE WriteableChar* (ch: CHAR): BOOLEAN;
(* must be identical to test in (StdWriter)WriteChar - inlined there for efficiency *)
BEGIN
RETURN
(ch >= 20X) & (ch < 7FX) OR
(ch = tab) OR (ch = line) OR (ch = para) OR
(ch = zwspace) OR (ch = digitspace) OR
(ch = hyphen) OR (ch = nbhyphen) OR
(ch >= 0A0X) (* need to augment with test for valid Unicode *)
END WriteableChar;
PROCEDURE CloneOf* (source: Model): Model;
BEGIN
ASSERT(source # NIL, 20);
RETURN Containers.CloneOf(source)(Model)
END CloneOf;
PROCEDURE SetDir* (d: Directory);
BEGIN
ASSERT(d # NIL, 20); ASSERT(d.attr # NIL, 21); ASSERT(d.attr.init, 22);
dir := d
END SetDir;
PROCEDURE Init;
VAR d: StdDirectory; a: Attributes;
BEGIN
NEW(a); a.InitFromProp(NIL);
NEW(stdProp); stdProp.known := -{};
NEW(prop); prop.known := -{};
NEW(d); stdDir := d; dir := d; d.SetAttr(a)
END Init;
BEGIN
Init
END TextModels.
| 37.686246 | 135 | 0.502629 | [
"model"
] |
2a07062d59c27f7e77ad55893638e9409bf90b11 | 27,085 | cc | C++ | ggadget/win32/tests/gdiplus_graphics_test.cc | suzhe/google-gadgets-for-linux | b58baabd8458c8515c9902b8176151a08d240983 | [
"Apache-2.0"
] | 175 | 2015-01-01T12:40:33.000Z | 2019-05-24T22:33:59.000Z | ggadget/win32/tests/gdiplus_graphics_test.cc | suzhe/google-gadgets-for-linux | b58baabd8458c8515c9902b8176151a08d240983 | [
"Apache-2.0"
] | 11 | 2015-01-19T16:30:56.000Z | 2018-04-25T01:06:52.000Z | ggadget/win32/tests/gdiplus_graphics_test.cc | suzhe/google-gadgets-for-linux | b58baabd8458c8515c9902b8176151a08d240983 | [
"Apache-2.0"
] | 97 | 2015-01-19T15:35:29.000Z | 2019-05-15T05:48:02.000Z | /*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This file contains the tests for GdiplusGraphics ,GdiplusCanvas, GdiplusFont
// and GdiplusImage. Modified from gtk/cairo_graphics_test.cc
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <io.h>
#include <string.h>
#include <windows.h>
#ifdef GDIPVER
#undef GDIPVER
#endif
#define GDIPVER 0x0110
#include <gdiplus.h>
#include <string>
#include <cstdlib>
#include <cstdio>
#include "ggadget/common.h"
#include "ggadget/scoped_ptr.h"
#include "ggadget/system_utils.h"
#include "ggadget/win32/gdiplus_canvas.h"
#include "ggadget/win32/gdiplus_graphics.h"
#include "ggadget/win32/gdiplus_image.h"
#include "ggadget/win32/gdiplus_font.h"
#include "unittest/gtest.h"
using ggadget::CanvasInterface;
using ggadget::Color;
using ggadget::ImageInterface;
using ggadget::FontInterface;
using ggadget::scoped_ptr;
using ggadget::UTF16Char;
using ggadget::UTF16String;
using ggadget::ConvertStringUTF16ToUTF8;
using ggadget::down_cast;
using ggadget::ReadFileContents;
using ggadget::win32::GdiplusCanvas;
using ggadget::win32::GdiplusGraphics;
using ggadget::win32::GdiplusFont;
using ggadget::win32::GdiplusImage;
const double kPi = 3.141592653589793;
bool g_savepng = false;
static std::string kTestFile120day("120day.png");
static std::string kTestFileBase("base.png");
static std::string kTestFileKitty419("kitty419.jpg");
static std::string kTestFileTestMask("testmask.png");
static std::string kTestFileOpaque("opaque.png");
// Get CLSID of specified encode, copied from msdn.
// link: http://msdn.microsoft.com/en-us/library/ms533843(v=vs.85).aspx
// @param format the format of image codec, such as "image/png"
// @param clsid[OUT] the output clsid of given encoder
// Returns 0 if success, otherwise return -1.
int GetEncoderClsid(const wchar_t* format, CLSID* clsid) {
UINT num = 0; // number of image encoders
UINT size = 0; // size of the image encoder array in bytes
Gdiplus::ImageCodecInfo* image_codec_info = NULL;
Gdiplus::GetImageEncodersSize(&num, &size);
if (size == 0)
return -1; // Failure
image_codec_info = reinterpret_cast<Gdiplus::ImageCodecInfo*>(malloc(size));
if (image_codec_info == NULL)
return -1; // Failure
GetImageEncoders(num, size, image_codec_info);
for (UINT j = 0; j < num; ++j) {
if (wcscmp(image_codec_info[j].MimeType, format) == 0) {
*clsid = image_codec_info[j].Clsid;
free(image_codec_info);
return 0; // Success
}
}
free(image_codec_info);
return -1; // Failure
}
// fixture for creating the GdiplusCanvas object
class GdiplusGfxTest : public testing::Test {
protected:
GdiplusGfxTest() : gfx_(2.0) {
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
target_.reset(down_cast<GdiplusCanvas*>(gfx_.NewCanvas(300, 150)));
}
~GdiplusGfxTest() {
if (g_savepng) {
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
wchar_t file[100] = {0};
wsprintf(file, L"%S.png", test_info->name());
CLSID pngClsid;
GetEncoderClsid(L"image/png", &pngClsid);
target_->GetImage()->Save(file, &pngClsid);
}
target_.reset(NULL);
Gdiplus::GdiplusShutdown(gdiplusToken);
}
GdiplusGraphics gfx_;
scoped_ptr<GdiplusCanvas> target_;
ULONG_PTR gdiplusToken;
};
TEST_F(GdiplusGfxTest, Zoom) {
EXPECT_DOUBLE_EQ(2.0, gfx_.GetZoom());
EXPECT_EQ(600, target_->GetImage()->GetWidth());
EXPECT_EQ(300, target_->GetImage()->GetHeight());
gfx_.SetZoom(1.0);
EXPECT_DOUBLE_EQ(1.0, gfx_.GetZoom());
EXPECT_DOUBLE_EQ(300.0, target_->GetWidth());
EXPECT_DOUBLE_EQ(150.0, target_->GetHeight());
EXPECT_EQ(300, target_->GetImage()->GetWidth());
EXPECT_EQ(150, target_->GetImage()->GetHeight());
}
// This test is meaningful only with -savepng
TEST_F(GdiplusGfxTest, NewCanvas) {
EXPECT_TRUE(target_->DrawFilledRect(150, 0, 150, 150, Color(1, 1, 1)));
CanvasInterface* c = gfx_.NewCanvas(100, 100);
ASSERT_TRUE(c != NULL);
EXPECT_TRUE(c->DrawFilledRect(0, 0, 100, 100, Color(1, 0, 0)));
c->Destroy();
c = NULL;
}
TEST_F(GdiplusGfxTest, LoadImage) {
std::string buffer;
ReadFileContents(kTestFile120day.c_str(), &buffer);
ImageInterface* img = gfx_.NewImage("", buffer, false);
ASSERT_NE(static_cast<ImageInterface*>(NULL), img);
ImageInterface* img1 = gfx_.NewImage("", buffer, false);
ASSERT_NE(static_cast<ImageInterface*>(NULL), img1);
ASSERT_TRUE(img != img1);
img->Destroy();
img1->Destroy();
img = gfx_.NewImage(kTestFile120day, buffer, false);
ASSERT_FALSE(NULL == img);
img1 = gfx_.NewImage(kTestFile120day, buffer, false);
ASSERT_FALSE(NULL == img1);
ASSERT_TRUE(img != img1);
img1->Destroy();
img1 = gfx_.NewImage(kTestFile120day, buffer, true);
ASSERT_TRUE(img != img1);
img1->Destroy();
EXPECT_TRUE(NULL == gfx_.NewImage("", std::string(), false));
EXPECT_DOUBLE_EQ(450.0, img->GetWidth());
EXPECT_DOUBLE_EQ(310.0, img->GetHeight());
EXPECT_EQ(kTestFile120day, img->GetTag());
img->Destroy();
img = NULL;
}
// This test is meaningful only with -savepng
TEST_F(GdiplusGfxTest, DrawCanvas) {
ImageInterface* img;
double h, scale;
// PNG
std::string buffer;
ReadFileContents(kTestFileBase.c_str(), &buffer);
img = gfx_.NewImage("", buffer, false);
ASSERT_FALSE(NULL == img);
h = img->GetHeight();
scale = 150. / h;
EXPECT_FALSE(target_->DrawCanvas(50., 0., NULL));
EXPECT_TRUE(target_->PushState());
target_->ScaleCoordinates(scale, scale);
EXPECT_TRUE(target_->MultiplyOpacity(.5));
EXPECT_TRUE(target_->DrawCanvas(150., 0., img->GetCanvas()));
EXPECT_TRUE(target_->PopState());
img->Destroy();
img = NULL;
// JPG
ReadFileContents(kTestFileKitty419.c_str(), &buffer);
img = gfx_.NewImage("", buffer, false);
ASSERT_FALSE(NULL == img);
h = img->GetHeight();
scale = 150. / h;
EXPECT_TRUE(target_->PushState());
target_->ScaleCoordinates(scale, scale);
EXPECT_TRUE(target_->DrawCanvas(0., 0., img->GetCanvas()));
EXPECT_TRUE(target_->PopState());
img->Destroy();
img = NULL;
}
// This test is meaningful only with -savepng
TEST_F(GdiplusGfxTest, DrawImageMask) {
ImageInterface* mask, *img;
double h, scale;
std::string buffer;
ReadFileContents(kTestFileTestMask.c_str(), &buffer);
mask = gfx_.NewImage("", buffer, true);
ASSERT_FALSE(NULL == mask);
ReadFileContents(kTestFile120day.c_str(), &buffer);
img = gfx_.NewImage("", buffer, false);
ASSERT_FALSE(NULL == img);
EXPECT_DOUBLE_EQ(450.0, mask->GetWidth());
EXPECT_DOUBLE_EQ(310.0, mask->GetHeight());
h = mask->GetHeight();
scale = 150. / h;
EXPECT_TRUE(target_->PushState());
EXPECT_TRUE(target_->DrawFilledRect(0, 0, 300, 150, Color(0, 0, 1)));
EXPECT_TRUE(target_->MultiplyOpacity(0.7));
EXPECT_TRUE(target_->DrawCanvasWithMask(0, 0, img->GetCanvas(),
0, 0, mask->GetCanvas()));
EXPECT_TRUE(target_->PopState());
CanvasInterface* c = gfx_.NewCanvas(100, 100);
ASSERT_TRUE(c != NULL);
EXPECT_TRUE(c->DrawFilledRect(0, 0, 100, 100, Color(0, 1, 0)));
EXPECT_TRUE(target_->DrawCanvasWithMask(150, 0, c, 0, 0, mask->GetCanvas()));
mask->Destroy();
mask = NULL;
img->Destroy();
img = NULL;
c->Destroy();
c = NULL;
}
// This test is meaningful only with -savepng
TEST_F(GdiplusGfxTest, NewFontAndDrawText) {
FontInterface* font1 = gfx_.NewFont(
"Calibri", 14, FontInterface::STYLE_ITALIC, FontInterface::WEIGHT_BOLD);
EXPECT_EQ(FontInterface::STYLE_ITALIC, font1->GetStyle());
EXPECT_EQ(FontInterface::WEIGHT_BOLD, font1->GetWeight());
EXPECT_DOUBLE_EQ(14.0, font1->GetPointSize());
EXPECT_FALSE(target_->DrawText(0, 0, 100, 30, NULL, font1, Color(1, 0, 0),
CanvasInterface::ALIGN_LEFT, CanvasInterface::VALIGN_TOP,
CanvasInterface::TRIMMING_NONE, 0));
EXPECT_FALSE(target_->DrawText(0, 0, 100, 30, "abc", NULL, Color(1, 0, 0),
CanvasInterface::ALIGN_LEFT, CanvasInterface::VALIGN_TOP,
CanvasInterface::TRIMMING_NONE, 0));
ASSERT_TRUE(font1 != NULL);
EXPECT_TRUE(target_->DrawText(0, 0, 100, 30, "hello world", font1,
Color(1, 0, 0), CanvasInterface::ALIGN_LEFT,
CanvasInterface::VALIGN_TOP,
CanvasInterface::TRIMMING_NONE, 0));
FontInterface* font2 = gfx_.NewFont("Times New Roman", 14,
FontInterface::STYLE_NORMAL, FontInterface::WEIGHT_NORMAL);
ASSERT_TRUE(font2 != NULL);
EXPECT_TRUE(target_->DrawText(0, 30, 100, 30, "hello world", font2,
Color(0, 1, 0), CanvasInterface::ALIGN_LEFT,
CanvasInterface::VALIGN_TOP,
CanvasInterface::TRIMMING_NONE, 0));
FontInterface* font3 = gfx_.NewFont("Times New Roman", 14,
FontInterface::STYLE_NORMAL,
FontInterface::WEIGHT_BOLD);
ASSERT_TRUE(font3 != NULL);
EXPECT_TRUE(target_->DrawText(0, 60, 100, 30, "hello world", font3,
Color(0, 0, 1), CanvasInterface::ALIGN_LEFT,
CanvasInterface::VALIGN_TOP,
CanvasInterface::TRIMMING_NONE, 0));
FontInterface* font4 = gfx_.NewFont("Times New Roman", 14,
FontInterface::STYLE_ITALIC, FontInterface::WEIGHT_NORMAL);
ASSERT_TRUE(font4 != NULL);
EXPECT_TRUE(target_->DrawText(0, 90, 100, 30, "hello world", font4,
Color(0, 1, 1), CanvasInterface::ALIGN_LEFT,
CanvasInterface::VALIGN_TOP,
CanvasInterface::TRIMMING_NONE, 0));
FontInterface* font5 = gfx_.NewFont("Times New Roman", 16,
FontInterface::STYLE_NORMAL, FontInterface::WEIGHT_NORMAL);
ASSERT_TRUE(font5 != NULL);
EXPECT_TRUE(target_->DrawText(0, 120, 100, 30, "hello world", font5,
Color(1, 1, 0), CanvasInterface::ALIGN_LEFT,
CanvasInterface::VALIGN_TOP,
CanvasInterface::TRIMMING_NONE, 0));
font1->Destroy();
font2->Destroy();
font3->Destroy();
font4->Destroy();
font5->Destroy();
}
// This test is meaningful only with -savepng.
TEST_F(GdiplusGfxTest, DrawTextWithTexture) {
ImageInterface* img;
std::string buffer;
ReadFileContents(kTestFileKitty419.c_str(), &buffer);
img = gfx_.NewImage("", buffer, false);
ASSERT_FALSE(NULL == img);
FontInterface* font = gfx_.NewFont("Times New Roman", 20,
FontInterface::STYLE_NORMAL, FontInterface::WEIGHT_BOLD);
// Test underline, strikeout and wrap.
EXPECT_TRUE(target_->DrawFilledRect(0, 0, 150, 90, Color(.7, 0, 0)));
EXPECT_TRUE(target_->DrawTextWithTexture(0, 0, 150, 90,
"hello world, gooooooogle",
font, img->GetCanvas(), CanvasInterface::ALIGN_LEFT,
CanvasInterface::VALIGN_TOP, CanvasInterface::TRIMMING_NONE,
CanvasInterface::TEXT_FLAGS_UNDERLINE |
CanvasInterface::TEXT_FLAGS_WORDWRAP));
EXPECT_TRUE(target_->DrawFilledRect(0, 100, 150, 50, Color(.7, 0, 0)));
EXPECT_TRUE(target_->DrawTextWithTexture(0, 100, 150, 50, "hello world",
font, img->GetCanvas(), CanvasInterface::ALIGN_LEFT,
CanvasInterface::VALIGN_TOP, CanvasInterface::TRIMMING_NONE,
CanvasInterface::TEXT_FLAGS_UNDERLINE |
CanvasInterface::TEXT_FLAGS_STRIKEOUT));
// test alignment
EXPECT_TRUE(target_->DrawFilledRect(180, 0, 120, 60, Color(.7, 0, 0)));
EXPECT_TRUE(target_->DrawTextWithTexture(180, 0, 120, 60, "hello", font,
img->GetCanvas(), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_NONE, 0));
EXPECT_TRUE(target_->DrawFilledRect(180, 80, 120, 60, Color(.7, 0, 0)));
EXPECT_TRUE(target_->DrawTextWithTexture(180, 80, 120, 60, "hello", font,
img->GetCanvas(), CanvasInterface::ALIGN_RIGHT,
CanvasInterface::VALIGN_BOTTOM,
CanvasInterface::TRIMMING_NONE, 0));
img->Destroy();
img = NULL;
font->Destroy();
font = NULL;
}
// This test is meaningful only with -savepng.
TEST_F(GdiplusGfxTest, TextAttributeAndAlignment) {
FontInterface* font5 = gfx_.NewFont("Times New Roman", 16,
FontInterface::STYLE_NORMAL, FontInterface::WEIGHT_NORMAL);
// Test underline, strikeout and wrap.
EXPECT_TRUE(target_->DrawFilledRect(0, 0, 100, 110, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(0, 120, 100, 30, Color(.3, .3, .1)));
EXPECT_TRUE(target_->DrawText(0, 0, 100, 120, "hello world, gooooooogle",
font5, Color(1, 1, 0), CanvasInterface::ALIGN_LEFT,
CanvasInterface::VALIGN_TOP, CanvasInterface::TRIMMING_NONE,
CanvasInterface::TEXT_FLAGS_UNDERLINE |
CanvasInterface::TEXT_FLAGS_WORDWRAP));
EXPECT_TRUE(target_->DrawText(0, 120, 100, 30, "hello world", font5,
Color(1, 1, 0), CanvasInterface::ALIGN_LEFT,
CanvasInterface::VALIGN_TOP, CanvasInterface::TRIMMING_NONE,
CanvasInterface::TEXT_FLAGS_UNDERLINE |
CanvasInterface::TEXT_FLAGS_STRIKEOUT));
// Test alignment.
EXPECT_TRUE(target_->DrawFilledRect(200, 0, 100, 60, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(200, 80, 100, 60, Color(.3, .3, .1)));
EXPECT_TRUE(target_->DrawText(200, 0, 100, 60, "hello", font5,
Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_NONE, 0));
EXPECT_TRUE(target_->DrawText(200, 80, 100, 60, "hello", font5,
Color(1, 1, 1), CanvasInterface::ALIGN_RIGHT,
CanvasInterface::VALIGN_BOTTOM,
CanvasInterface::TRIMMING_NONE, 0));
font5->Destroy();
}
// This test is meaningful only with -savepng.
TEST_F(GdiplusGfxTest, JustifyAlignmentTest) {
FontInterface* font5 = gfx_.NewFont("Times New Roman", 14,
FontInterface::STYLE_NORMAL, FontInterface::WEIGHT_NORMAL);
EXPECT_TRUE(target_->DrawFilledRect(0, 0, 100, 80, Color(.3, .3, .1)));
EXPECT_TRUE(target_->DrawText(
0, 0, 100, 80, "This is a loooooooooogword !\n it is a new line.",
font5, Color(1, 1, 0), CanvasInterface::ALIGN_JUSTIFY,
CanvasInterface::VALIGN_TOP, CanvasInterface::TRIMMING_PATH_ELLIPSIS,
CanvasInterface::TEXT_FLAGS_UNDERLINE |
CanvasInterface::TEXT_FLAGS_WORDWRAP));
EXPECT_TRUE(target_->DrawFilledRect(150, 0, 100, 80, Color(.3, .3, .1)));
EXPECT_TRUE(target_->DrawText(
150, 0, 100, 80, "This is a loooooooooogword !\nit is a new line.",
font5, Color(1, 1, 0), CanvasInterface::ALIGN_LEFT,
CanvasInterface::VALIGN_TOP, CanvasInterface::TRIMMING_PATH_ELLIPSIS,
CanvasInterface::TEXT_FLAGS_UNDERLINE |
CanvasInterface::TEXT_FLAGS_WORDWRAP));
}
// This test is meaningful only with -savepng.
TEST_F(GdiplusGfxTest, SinglelineTrimming) {
FontInterface* font5 = gfx_.NewFont("Times New Roman", 16,
FontInterface::STYLE_NORMAL, FontInterface::WEIGHT_NORMAL);
EXPECT_TRUE(target_->DrawFilledRect(0, 0, 100, 30, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(200, 0, 100, 30, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(0, 40, 100, 30, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(200, 40, 100, 30, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(0, 80, 100, 30, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(200, 80, 100, 30, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawText(0, 0, 100, 30, "hello world", font5,
Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_BOTTOM,
CanvasInterface::TRIMMING_NONE, 0));
EXPECT_TRUE(target_->DrawText(0, 40, 100, 30, "hello world", font5,
Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_BOTTOM,
CanvasInterface::TRIMMING_CHARACTER, 0));
EXPECT_TRUE(target_->DrawText(0, 80, 100, 30, "hello world", font5,
Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_BOTTOM,
CanvasInterface::TRIMMING_CHARACTER_ELLIPSIS, 0));
EXPECT_TRUE(target_->DrawText(200, 0, 100, 30, "hello world", font5,
Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_BOTTOM,
CanvasInterface::TRIMMING_WORD, 0));
EXPECT_TRUE(target_->DrawText(200, 40, 100, 30, "hello world", font5,
Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_BOTTOM,
CanvasInterface::TRIMMING_WORD_ELLIPSIS, 0));
EXPECT_TRUE(target_->DrawText(200, 80, 100, 30, "hello world", font5,
Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_BOTTOM,
CanvasInterface::TRIMMING_PATH_ELLIPSIS, 0));
font5->Destroy();
}
// This test is meaningful only with -savepng.
TEST_F(GdiplusGfxTest, MultilineTrimming) {
FontInterface* font5 = gfx_.NewFont("Times New Roman", 16,
FontInterface::STYLE_NORMAL, FontInterface::WEIGHT_NORMAL);
EXPECT_TRUE(target_->DrawFilledRect(0, 0, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(0, 50, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(0, 100, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(200, 0, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(200, 50, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(200, 100, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawText(0, 0, 100, 40, "Hello world, gooooogle",
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_NONE,
CanvasInterface::TEXT_FLAGS_WORDWRAP));
EXPECT_TRUE(target_->DrawText(0, 50, 100, 40, "Hello world, gooooogle",
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_CHARACTER,
CanvasInterface::TEXT_FLAGS_WORDWRAP));
EXPECT_TRUE(target_->DrawText(0, 100, 100, 40, "Hello world, gooooogle",
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_CHARACTER_ELLIPSIS,
CanvasInterface::TEXT_FLAGS_WORDWRAP));
EXPECT_TRUE(target_->DrawText(200, 0, 100, 40, "Hello world, gooooogle",
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE, CanvasInterface::TRIMMING_WORD,
CanvasInterface::TEXT_FLAGS_WORDWRAP));
EXPECT_TRUE(target_->DrawText(200, 50, 100, 40, "Hello world, gooooogle",
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_WORD_ELLIPSIS,
CanvasInterface::TEXT_FLAGS_WORDWRAP));
EXPECT_TRUE(target_->DrawText(200, 100, 100, 40, "Hello world, gooooogle",
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_PATH_ELLIPSIS,
CanvasInterface::TEXT_FLAGS_WORDWRAP));
font5->Destroy();
}
// This test is meaningful only with -savepng.
TEST_F(GdiplusGfxTest, ChineseTrimming) {
UTF16String text(reinterpret_cast<const UTF16Char*>(L"你好,谷歌"));
std::string utf8_string;
ConvertStringUTF16ToUTF8(text, &utf8_string);
FontInterface* font5 = gfx_.NewFont("Times New Roman", 16,
FontInterface::STYLE_NORMAL, FontInterface::WEIGHT_NORMAL);
EXPECT_TRUE(target_->DrawFilledRect(0, 0, 105, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(0, 50, 105, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(0, 100, 105, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(180, 0, 105, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(180, 50, 105, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(180, 100, 105, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawText(0, 0, 105, 40, utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_NONE, 0));
EXPECT_TRUE(target_->DrawText(0, 50, 105, 40, utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_CHARACTER, 0));
EXPECT_TRUE(target_->DrawText(0, 100, 105, 40, utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_CHARACTER_ELLIPSIS, 0));
EXPECT_TRUE(target_->DrawText(180, 0, 105, 40, utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_WORD, 0));
EXPECT_TRUE(target_->DrawText(180, 50, 105, 40, utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_WORD_ELLIPSIS, 0));
EXPECT_TRUE(target_->DrawText(180, 100, 105, 40, utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_PATH_ELLIPSIS, 0));
font5->Destroy();
}
// This test is meaningful only with -savepng.
TEST_F(GdiplusGfxTest, RTLTrimming) {
FontInterface* font5 = gfx_.NewFont("Times New Roman", 16,
FontInterface::STYLE_NORMAL, FontInterface::WEIGHT_NORMAL);
UTF16String text(
reinterpret_cast<const UTF16Char*>(L"سَدفهلكجشِلكَفهسدفلكجسدف"));
std::string utf8_string;
ConvertStringUTF16ToUTF8(text, &utf8_string);
EXPECT_TRUE(target_->DrawFilledRect(0, 0, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(0, 50, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(0, 100, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(200, 0, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(200, 50, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawFilledRect(200, 100, 100, 40, Color(.1, .1, 0)));
EXPECT_TRUE(target_->DrawText(0, 0, 100, 40,
utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_NONE, 0));
EXPECT_TRUE(target_->DrawText(0, 50, 100, 40,
utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_CHARACTER, 0));
EXPECT_TRUE(target_->DrawText(0, 100, 100, 40,
utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_CHARACTER_ELLIPSIS, 0));
EXPECT_TRUE(target_->DrawText(200, 0, 100, 40,
utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_WORD, 0));
EXPECT_TRUE(target_->DrawText(200, 50, 100, 40,
utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_WORD_ELLIPSIS, 0));
EXPECT_TRUE(target_->DrawText(200, 100, 100, 40,
utf8_string.c_str(),
font5, Color(1, 1, 1), CanvasInterface::ALIGN_CENTER,
CanvasInterface::VALIGN_MIDDLE,
CanvasInterface::TRIMMING_PATH_ELLIPSIS, 0));
font5->Destroy();
}
// This test is meaningful only with -savepng.
TEST_F(GdiplusGfxTest, ColorMultiply) {
ImageInterface* img;
double h, scale;
// PNG
std::string buffer;
ReadFileContents(kTestFileBase.c_str(), &buffer);
img = gfx_.NewImage("", buffer, false);
ASSERT_FALSE(NULL == img);
h = img->GetHeight();
scale = 150. / h;
ImageInterface* img1 = img->MultiplyColor(Color(0, 0.5, 1));
EXPECT_TRUE(target_->PushState());
target_->ScaleCoordinates(scale, scale);
EXPECT_TRUE(target_->MultiplyOpacity(.5));
EXPECT_TRUE(target_->DrawCanvas(150., 0., img1->GetCanvas()));
EXPECT_TRUE(target_->PopState());
// JPG
ReadFileContents(kTestFileBase.c_str(), &buffer);
img = gfx_.NewImage("", buffer, false);
ASSERT_FALSE(NULL == img);
h = img->GetHeight();
scale = 150. / h;
img1 = img->MultiplyColor(Color(0.5, 0, 0.8));
EXPECT_TRUE(target_->PushState());
target_->ScaleCoordinates(scale, scale);
EXPECT_TRUE(target_->DrawCanvas(0., 0., img1->GetCanvas()));
EXPECT_TRUE(target_->PopState());
img1->Destroy();
img1 = NULL;
img->Destroy();
img = NULL;
}
TEST_F(GdiplusGfxTest, ImageOpaque) {
struct Images {
std::string filename;
bool opaque;
} images[] = {
{ kTestFile120day, true },
{ kTestFileBase, false },
{ kTestFileOpaque, true },
{ "", false }
};
for (size_t i = 0; images[i].filename.length(); ++i) {
std::string content;
ASSERT_TRUE(ReadFileContents(images[i].filename.c_str(), &content));
ImageInterface* img = gfx_.NewImage("", content, false);
ASSERT_TRUE(img);
EXPECT_EQ(images[i].opaque, img->IsFullyOpaque());
img->Destroy();
img = NULL;
}
}
int main(int argc, char** argv) {
testing::ParseGTestFlags(&argc, argv);
// g_type_init();
// Hack for autoconf out-of-tree build.
char* srcdir = getenv("srcdir");
if (srcdir && *srcdir) {
kTestFile120day = std::string(srcdir) + std::string("/") + kTestFile120day;
kTestFileBase = std::string(srcdir) + std::string("/") + kTestFileBase;
kTestFileKitty419 = std::string(srcdir) + std::string("/")
+ kTestFileKitty419;
kTestFileTestMask = std::string(srcdir) + std::string("/")
+ kTestFileTestMask;
kTestFileOpaque = std::string(srcdir) + std::string("/") + kTestFileOpaque;
}
for (int i = 0; i < argc; i++) {
if (0 == strcasecmp(argv[i], "-savepng")) {
g_savepng = true;
break;
}
}
return RUN_ALL_TESTS();
}
| 38.41844 | 79 | 0.666937 | [
"object"
] |
2a088f1dbac7d94d60807e52cadbf2110f3ce791 | 2,911 | hpp | C++ | Test/Case01_ActualExamples.hpp | GoPlan/cldeparser | 430bd983fa2c448680f3b7452c40ebb4c1ca3048 | [
"MIT"
] | null | null | null | Test/Case01_ActualExamples.hpp | GoPlan/cldeparser | 430bd983fa2c448680f3b7452c40ebb4c1ca3048 | [
"MIT"
] | null | null | null | Test/Case01_ActualExamples.hpp | GoPlan/cldeparser | 430bd983fa2c448680f3b7452c40ebb4c1ca3048 | [
"MIT"
] | null | null | null | //
// Created by LE, Duc Anh on 8/28/15.
//
#ifndef CLDEPARSER_TEST_CASE01_ACTUALEXAMPLES_HPP
#define CLDEPARSER_TEST_CASE01_ACTUALEXAMPLES_HPP
#include <fstream>
#include "JsonTestFixture.h"
#define CUSTOMERMAP_JSON "JsonExamples/CustomerMap.json"
namespace CLDEParser {
namespace Test {
TEST_F(JsonTestFixture, CustomerMap) {
std::ifstream file{CUSTOMERMAP_JSON};
ASSERT_TRUE(!file.operator!());
std::string document((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
auto sptrJson = parserInstance().Parse(document);
ASSERT_TRUE(sptrJson.operator->());
ASSERT_TRUE(sptrJson->Type() == CLDEParser::Parsing::Json::JsonEntityType::Object);
// Root
auto sptrRoot = CLDEParser::Parsing::Json::JsonEntityHelper::ToSPtrObject(sptrJson);
ASSERT_TRUE(sptrRoot.operator->());
// Name
auto sptrNameValue = sptrRoot->GetValue("Name");
ASSERT_TRUE(sptrNameValue->Type() == CLDEParser::Parsing::Json::JsonValueType::String);
ASSERT_TRUE(sptrNameValue->strValue == "Customer");
// TableName
auto sptrTableNameValue = sptrRoot->GetValue("TableName");
ASSERT_TRUE(sptrTableNameValue->Type() == CLDEParser::Parsing::Json::JsonValueType::String);
ASSERT_TRUE(sptrTableNameValue->strValue == "Customer");
// ColumnsForGet
auto sptrColumnsForGet = sptrRoot->GetValue("ColumnsForGet");
ASSERT_TRUE(sptrColumnsForGet->Type() == CLDEParser::Parsing::Json::JsonValueType::Entity);
auto sptrColumnsForGetArray = CLDEParser::Parsing::Json::JsonEntityHelper::ToSPtrArray(sptrColumnsForGet->sptrJsonEntity);
ASSERT_TRUE(sptrColumnsForGetArray->Container().size() == 4);
auto sptrThirdColumn = *(sptrColumnsForGetArray->Container().cbegin() + 2);
ASSERT_TRUE(sptrThirdColumn->CopyToString() == "LastName");
// Version
auto sptrVersionArray= CLDEParser::Parsing::Json::JsonEntityHelper::ToSPtrArray(sptrRoot->GetValue("Version")->sptrJsonEntity);
auto sptrVersionIterator = sptrVersionArray->Container().cbegin();
auto sptrAuthor = CLDEParser::Parsing::Json::JsonEntityHelper::ToSPtrObject((*sptrVersionIterator)->sptrJsonEntity);
auto sptrVersion = CLDEParser::Parsing::Json::JsonEntityHelper::ToSPtrObject((*(sptrVersionIterator+1))->sptrJsonEntity);
ASSERT_TRUE(sptrAuthor.operator->());
ASSERT_TRUE(sptrVersion.operator->());
auto verMajor = sptrVersion->GetValue("Major")->intValue;
auto verMinor = sptrVersion->GetValue("Minor")->intValue;
ASSERT_TRUE(verMajor == 1);
ASSERT_TRUE(verMinor == 0);
}
}
}
#endif //CLDEPARSER_TEST_CASE01_ACTUALEXAMPLES_HPP
| 46.206349 | 139 | 0.663346 | [
"object"
] |
2a0a8f585906645dc204ebeb7f914aedfb9ebc07 | 732 | cpp | C++ | coding-blocks/CGPA.cpp | jatin69/Revision-cpp | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 4 | 2020-01-16T14:49:46.000Z | 2021-08-23T12:45:19.000Z | coding-blocks/CGPA.cpp | jatin69/coding-practice | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 2 | 2018-06-06T13:08:11.000Z | 2018-10-02T19:07:32.000Z | coding-blocks/CGPA.cpp | jatin69/coding-practice | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 5 | 2018-10-02T13:49:16.000Z | 2021-08-11T07:29:50.000Z | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> A(n);
vector<int> B(n);
for (int i = 0; i < n; ++i) {
cin >> A[i];
B[i] = A[i];
}
int count = 0;
vector<int> C;
bool goforit = false;
do {
goforit = false;
A = B;
B = C;
sort(A.begin(), A.end());
for (int i = 1; i < A.size(); ++i) {
if (A[i] == A[i - 1]) {
B.push_back(A[i]);
A.erase(A.begin() + i - 1);
}
}
for (int i = 1; i < A.size(); ++i) {
if (A[i] > A[i - 1]) {
count++;
}
}
for (int i = 1; i < B.size(); ++i) {
if (A[i] != A[i - 1]) {
goforit = true;
}
}
if (!goforit || B.empty()) {
B = C;
}
} while (!B.empty());
cout << count << "\n";
return 0;
}
| 14.076923 | 38 | 0.423497 | [
"vector"
] |
2a1c68b1cacc0c0687f2560b40b32c1406066c47 | 452 | hpp | C++ | src/pge/file.hpp | MichaCzu/p-engine | 79666ce4d211c010b082112235f222de87d1e811 | [
"MIT"
] | null | null | null | src/pge/file.hpp | MichaCzu/p-engine | 79666ce4d211c010b082112235f222de87d1e811 | [
"MIT"
] | null | null | null | src/pge/file.hpp | MichaCzu/p-engine | 79666ce4d211c010b082112235f222de87d1e811 | [
"MIT"
] | null | null | null | //zapisywanie i wczytywanie danych z pliku. ( niby zbędne ale dla czytelności potem )
#pragma once
#include <string>
#include <vector>
namespace pge {
namespace file {
bool init();
bool close();
bool remove(std::string path);
std::wstring read_nextline(std::string path);
std::wstring read(std::string path, int mode = 0);
bool write(std::string path, std::wstring text, int mode = 0);
std::vector<std::string> get_folderlist(std::string path);
}
} | 25.111111 | 85 | 0.725664 | [
"vector"
] |
2a1c862db412b06ce0629026ca79db8e0673cb94 | 11,660 | cpp | C++ | src/main.cpp | GbaLog/wad_packer | 212af80a8e1e475221be4b5ec241bd77ec126899 | [
"MIT"
] | 4 | 2021-09-12T00:13:04.000Z | 2022-02-19T11:18:33.000Z | src/main.cpp | GbaLog/wad_packer | 212af80a8e1e475221be4b5ec241bd77ec126899 | [
"MIT"
] | null | null | null | src/main.cpp | GbaLog/wad_packer | 212af80a8e1e475221be4b5ec241bd77ec126899 | [
"MIT"
] | null | null | null | #include <fstream>
#include <cstring>
#include "Tracer.h"
#include "MemReader.h"
#include "PixMapDecoder.h"
#include "WadDecoder.h"
#include "BmpEncoder.h"
#include "BmpDecoder.h"
#include "MemWriter.h"
#include "Common.h"
//-----------------------------------------------------------------------------
bool readFile(const std::string & filename, VecByte & data)
{
std::ifstream file;
file.open(filename, std::ios::in | std::ios::binary);
if (!file)
{
TRACE(ERR) << "Can't open file for reading: " << filename;
return false;
}
data.insert(data.end(), std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
return true;
}
//-----------------------------------------------------------------------------
void crackPath(const std::string & filename, std::string & path, std::string & file)
{
auto it = filename.find_last_of("\\/");
if (it != std::string::npos)
{
path = filename.substr(0, it);
file = filename.substr(it + 1);
}
else
{
path.clear();
file = filename;
}
it = file.find_last_of('.');
if (it != std::string::npos)
file = file.substr(0, it);
}
//-----------------------------------------------------------------------------
void encodeBmpFile(const std::string & filename, const BmpData & data)
{
VecByte buffer;
BMPEncoder enc;
if (enc.encode(data, buffer) == false)
{
TRACE(ERR) << "Can't encode BMP data for file: " << filename;
return;
}
std::ofstream decFile(filename, std::ios::out | std::ios::binary);
if (!decFile)
{
TRACE(WRN) << "Cannot create file: " << filename;
return;
}
decFile.write((char *)buffer.data(), buffer.size());
}
//-----------------------------------------------------------------------------
void encodeTextureToBmp(const std::string & filename, const WadTexture & item)
{
const std::string imgName = filename + ".bmp";
const std::string mipmap1Name = filename + "_mip1.bmp";
const std::string mipmap2Name = filename + "_mip2.bmp";
const std::string mipmap3Name = filename + "_mip3.bmp";
BMPEncoder enc;
BmpData bmpData;
bmpData._width = item._header._width;
bmpData._height = item._header._height;
bmpData._data = item._body._image;
if (item._body._colors.size() != 256)
{
TRACE(WRN) << "Color palette is not 256: " << item._body._colors.size();
return;
}
bmpData._palette.reserve(256);
for (int i = 0; i < 256; ++i)
{
const auto & itemColors = item._body._colors;
Color clr;
clr._red = itemColors.at(i)._red;
clr._green = itemColors.at(i)._green;
clr._blue = itemColors.at(i)._blue;
clr._reserved = 0;
bmpData._palette.push_back(clr);
}
encodeBmpFile(imgName, bmpData);
bmpData._width = item._header._width / 2;
bmpData._height = item._header._height / 2;
bmpData._data = item._body._mipmap1;
encodeBmpFile(mipmap1Name, bmpData);
bmpData._width = item._header._width / 4;
bmpData._height = item._header._height / 4;
bmpData._data = item._body._mipmap2;
encodeBmpFile(mipmap2Name, bmpData);
bmpData._width = item._header._width / 8;
bmpData._height = item._header._height / 8;
bmpData._data = item._body._mipmap3;
encodeBmpFile(mipmap3Name, bmpData);
}
//-----------------------------------------------------------------------------
void encodeTexturesToBmp(const std::string & filename, const std::vector<WadTexture> & items)
{
std::string dir = "decoded_"; dir += filename;
system(std::string("rmdir /S /Q " + dir).c_str());
system(std::string("mkdir " + dir).c_str());
for (const auto & item : items)
{
std::string filename = dir + "/" + item._header._name;
TRACE(DBG) << "Filename: " << filename;
encodeTextureToBmp(filename, item);
}
}
//-----------------------------------------------------------------------------
bool decodeWad(const std::string & filename)
{
TRACE(DBG) << "Decode wad: " << filename;
std::ifstream file;
file.open(filename, std::ios::in | std::ios::binary);
if (!file)
{
TRACE(ERR) << "Can't open file: " << filename;
return false;
}
VecByte fullFile{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
WadFileData fileData;
WadDecoder dec;
if (dec.decode(fullFile, fileData) == false)
{
TRACE(ERR) << "Can't decode wad file: " << filename;
return false;
}
TRACE(DBG) << "WAD header: number of all textures: " << fileData._header._numOfTextures;
encodeTexturesToBmp(filename, fileData._textures);
return true;
}
//-----------------------------------------------------------------------------
void normalizeBmpData(VecByte & data, uint32_t width, uint32_t height)
{
std::vector<uint8_t> copyData;
const uint8_t * ptr = data.data();
for (uint32_t i = 0; i < height; ++i)
{
copyData.insert(copyData.end(), ptr, ptr + width);
ptr += (width + 3) & ~3;
}
data = std::move(copyData);
}
//-----------------------------------------------------------------------------
bool loadTexture(const std::string & filename, WadTexture & texture)
{
std::string name;
std::string path;
crackPath(filename, path, name);
if (name.size() > 16)
{
TRACE(ERR) << "File name size is greater than 16";
return false;
}
WadLumpHeader & li = texture._lump;
memset(&li, 0, sizeof(li));
li._offsetOfTexture = sizeof(WadHeader);
li._compressedLen = 0;
li._fullLen = 0;
li._type = 0x43;
li._compressionType = 0;
li._dummy = 0;
strncpy(li._name, name.c_str(), name.size());
if (readFile(filename, texture._body._image) == false)
{
TRACE(ERR) << "Can't read original image: " << filename;
return false;
}
BmpDecoder dec;
BmpData bmpData;
if (dec.decode(texture._body._image, bmpData) == false)
{
TRACE(ERR) << "Can't decode picture in file: " << filename;
return false;
}
uint32_t w = bmpData._width;
uint32_t h = bmpData._height;
if (w % 16 != 0 || h % 16 != 0)
{
TRACE(ERR) << "Image width and height should be divisible by 16: width: " << w << ", height: " << h;
return false;
}
if (w * h >= 12288)
{
TRACE(ERR) << "Image size can't be greater than 12288";
return false;
}
texture._body._image = std::move(bmpData._data);
WadTextureHeader & header = texture._header;
memset(&header, 0, sizeof(header));
strncpy(header._name, name.c_str(), name.size());
header._width = w;
header._height = h;
header._offsetOfImage = sizeof(WadTextureHeader);
header._offsetOfMipmap1 = header._offsetOfImage + (w * h);
header._offsetOfMipmap2 = header._offsetOfMipmap1 + ((w / 2) * (h / 2));
header._offsetOfMipmap3 = header._offsetOfMipmap2 + ((w / 4) * (h / 4));
li._fullLen = header._offsetOfMipmap3 + ((w / 8) * (h / 8)) + 2 + (256 * 3) + 2;
li._compressedLen = li._fullLen;
const std::string mipmap1Name = path + "/" + name + "_mip1.bmp";
const std::string mipmap2Name = path + "/" + name + "_mip2.bmp";
const std::string mipmap3Name = path + "/" + name + "_mip3.bmp";
if (readFile(mipmap1Name, texture._body._mipmap1) == false ||
readFile(mipmap2Name, texture._body._mipmap2) == false ||
readFile(mipmap3Name, texture._body._mipmap3) == false)
{
TRACE(ERR) << "Can't read one of mipmaps";
return false;
}
return true;
}
//-----------------------------------------------------------------------------
void encodeTextureToVecByte(const WadTexture & texture, VecByte & fullTextureData)
{
fullTextureData.clear();
fullTextureData.resize(texture._lump._fullLen);
MemWriter wr(fullTextureData.data(), fullTextureData.size());
const auto & body = texture._body;
wr.writeData(&texture._header, sizeof(WadTextureHeader));
wr.writeData(body._image.data(), body._image.size());
uint32_t w = texture._header._width;
uint32_t h = texture._header._height;
BmpDecoder dec;
BmpData mipmap1;
BmpData mipmap2;
BmpData mipmap3;
if (dec.decode(body._mipmap1, mipmap1) == false ||
dec.decode(body._mipmap2, mipmap2) == false ||
dec.decode(body._mipmap3, mipmap3) == false)
{
TRACE(ERR) << "Can't decode one of mipmap";
return;
}
if (mipmap1._data.size() != getMipmap1Size(w, h))
{
normalizeBmpData(mipmap1._data, w / 2, h / 2);
}
if (mipmap2._data.size() != getMipmap2Size(w, h))
{
normalizeBmpData(mipmap2._data, w / 4, h / 4);
}
if (mipmap3._data.size() != getMipmap3Size(w, h))
{
normalizeBmpData(mipmap3._data, w / 8, h / 8);
}
wr.writeData(mipmap1._data.data(), mipmap1._data.size());
wr.writeData(mipmap2._data.data(), mipmap2._data.size());
wr.writeData(mipmap3._data.data(), mipmap3._data.size());
wr.writeUint8(0x00);
wr.writeUint8(0x01);
//Palette must be the same for all images
for (size_t i = 0; i < mipmap1._palette.size(); ++i)
{
wr.writeUint8(mipmap1._palette[i]._red);
wr.writeUint8(mipmap1._palette[i]._green);
wr.writeUint8(mipmap1._palette[i]._blue);
}
wr.writeUint8(0x00);
wr.writeUint8(0x00);
}
//-----------------------------------------------------------------------------
bool encodeToWad(const std::string & wadFilename, const std::string & path, VecString files)
{
if (path.empty() == false)
{
for (auto & it : files)
it = path + "/" + it;
}
WadHeader wh;
wh._magicWord = (('3' << 24) | ('D' << 16) | ('A' << 8) | 'W');
wh._numOfTextures = files.size();
VecWadTexture textures;
textures.reserve(wh._numOfTextures);
uint32_t fullLumpLen = 0;
for (const auto & file : files)
{
TRACE(DBG) << "Process file: " << file;
WadTexture texture;
if (loadTexture(file, texture) == false)
{
TRACE(ERR) << "Can't load texture: " << file;
return false;
}
texture._lump._offsetOfTexture += fullLumpLen;
fullLumpLen += texture._lump._fullLen;
textures.push_back(texture);
}
wh._offsetOfLumps = sizeof(WadHeader) + fullLumpLen;
std::ofstream ofs(wadFilename, std::ios::out | std::ios::binary);
if (!ofs)
{
TRACE(ERR) << "Can't open file for writing: " << wadFilename;
return false;
}
ofs.write((char *)&wh, sizeof(wh));
for (const auto & texture : textures)
{
VecByte textureData;
encodeTextureToVecByte(texture, textureData);
ofs.write((char *)textureData.data(), textureData.size());
}
for (const auto & texture : textures)
{
ofs.write((char *)&texture._lump, sizeof(texture._lump));
}
return true;
}
//-----------------------------------------------------------------------------
int main(int argc, char * argv[])
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " <filename> for unpacking\n"
<< " " << argv[0] << " <wad filename> [--path path] file1.bmp path/file2.bmp path/file3.bmp"
<< " for packing(path required if `--path` option is not used)\n";
return EXIT_FAILURE;
}
if (argc == 2)
{
if (decodeWad(argv[1]) == false)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
std::string path;
VecString files;
for (int arg = 2; arg < argc; ++arg)
{
if (strcmp(argv[arg], "--path") == 0)
{
path = argv[++arg];
continue;
}
files.push_back(argv[arg]);
}
if (encodeToWad(argv[1], path, std::move(files)) == false)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
| 28.933002 | 113 | 0.56964 | [
"vector"
] |
2a1da8b3e8da92be0480c7883becfddc0eafa878 | 1,877 | hpp | C++ | Workspace/src/Animation.hpp | Llemmert/UntitledCatGame | 4618cef62d329a90a7387a63cdf87b5b9762097b | [
"MIT"
] | null | null | null | Workspace/src/Animation.hpp | Llemmert/UntitledCatGame | 4618cef62d329a90a7387a63cdf87b5b9762097b | [
"MIT"
] | null | null | null | Workspace/src/Animation.hpp | Llemmert/UntitledCatGame | 4618cef62d329a90a7387a63cdf87b5b9762097b | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <fstream>
#include <math.h>
using namespace std;
class AnimationFrame
{
SDL_Texture *frame;
int millis;
public:
void init(SDL_Texture *newFrame, int newMillis = 100)
{
frame = newFrame;
millis = newMillis;
}
void read(MediaManager *media, ifstream &in)
{
string fname;
in >> millis >> fname;
frame = media->read("Workspace/media/" + fname + ".bmp");
// cout << "reading " << fname << ".bmp" << endl;
}
int getMillis() { return millis; }
SDL_Texture *getTexture() { return frame; }
};
class Animation
{
vector<AnimationFrame *> frames;
int totalTime;
int currentTime;
public:
Animation()
{
totalTime = 0;
currentTime = 0;
}
void read(MediaManager *media, string filename)
{
int max;
ifstream in;
in.open(filename);
in >> max;
for (int i = 0; i < max; i++)
{
AnimationFrame *af = new AnimationFrame();
af->read(media, in);
add(af);
}
in.close();
}
void add(AnimationFrame *af)
{
frames.push_back(af);
totalTime += af->getMillis();
}
void update(double dt)
{
currentTime += (int)(dt * 1000);
// cout << "Total Time " << totalTime << endl;
currentTime %= totalTime;
}
SDL_Texture *getTexture()
{
int checkTime = 0;
int t = 0;
for (t = 0; t < frames.size(); t++)
{
if (checkTime + frames[t]->getMillis() > currentTime)
break;
checkTime += frames[t]->getMillis();
}
if (t == frames.size())
t = 0;
return frames[t]->getTexture();
}
~Animation()
{
for (auto f : frames)
delete f;
}
}; | 21.825581 | 65 | 0.50293 | [
"vector"
] |
2a20b3cdd1121343beac23d96e9b8203eb5d06e9 | 377 | cpp | C++ | LeetCode/1014.best-sightseeing-pair.ac.cpp | Kresnt/AlgorithmTraining | 3dec1e712f525b4f406fe669d97888f322dfca97 | [
"MIT"
] | null | null | null | LeetCode/1014.best-sightseeing-pair.ac.cpp | Kresnt/AlgorithmTraining | 3dec1e712f525b4f406fe669d97888f322dfca97 | [
"MIT"
] | null | null | null | LeetCode/1014.best-sightseeing-pair.ac.cpp | Kresnt/AlgorithmTraining | 3dec1e712f525b4f406fe669d97888f322dfca97 | [
"MIT"
] | null | null | null | #pragma G++ optimize("O2")
class Solution {
public:
int maxScoreSightseeingPair(vector<int>& A) {
const int n = A.size();
int ans(INT_MIN), q(-1);
for(int i = n - 1; i >= 0; --i) {
if(q != -1 && A[i] + i + A[q] - q > ans) {
ans = (A[i] + i + A[q] - q);
}
if(q == -1 || A[i] - i >= A[q] - q)
q = i;
}
return ans;
}
};
| 20.944444 | 48 | 0.413793 | [
"vector"
] |
2a3041e500604793fece73e3b05dccbfbdf1417d | 1,881 | cpp | C++ | boost/bind.cpp | lolyu/aoi | a26e5eb205aafadc7301b2e4acc67915d3bcc935 | [
"MIT"
] | null | null | null | boost/bind.cpp | lolyu/aoi | a26e5eb205aafadc7301b2e4acc67915d3bcc935 | [
"MIT"
] | null | null | null | boost/bind.cpp | lolyu/aoi | a26e5eb205aafadc7301b2e4acc67915d3bcc935 | [
"MIT"
] | null | null | null | // #include <boost/bind.hpp>
#include <boost/bind/bind.hpp>
#include <iostream>
#include <algorithm>
using namespace std;
int f(int a, int b)
{
return a + b;
}
int g(int a, int b, int c)
{
return a + b + c;
}
int h(int &a, int &b)
{
return a++ + b++;
}
void print(int x)
{
cout << x << endl;
}
struct F2
{
int s;
typedef void result_type;
void operator()(int x) { s += x; }
};
class A
{
public:
int m_a = 0;
void inc(int x)
{
m_a += x;
}
};
int main()
{
int a = 10, b = 20;
print(boost::bind(f, 10, 20)()); // 30
print(boost::bind(f, boost::placeholders::_1, boost::placeholders::_1)(10, 20)); // 20
print(boost::bind(h, a, boost::placeholders::_2)(a, b)); // 30
print(a); // 10
print(b); // 21
// values are stored into the function object by copy of value, use boost::ref or boost::cref to store values by reference
print(boost::bind(h, boost::ref(a), boost::placeholders::_2)(a, b)); // 31
print(a); // 11
print(b); // 22
F2 f2 = {0};
int ar[] = {1, 2, 3};
// By default, bind makes a copy of the provided function object
std::for_each(ar, ar + 3, boost::bind(f2, boost::placeholders::_1));
print(f2.s); // 0
std::for_each(ar, ar + 3, boost::bind(boost::ref(f2), boost::placeholders::_1));
print(f2.s); // 6
A ao;
boost::bind(&A::inc, ao, boost::placeholders::_1)(100);
print(ao.m_a); // 0
boost::bind(&A::inc, boost::ref(ao), boost::placeholders::_1)(100);
print(ao.m_a); // 100
return 0;
} | 25.767123 | 126 | 0.461988 | [
"object"
] |
2a3afbb1d24b7d9b666c365dafb3600be46f242a | 7,528 | cpp | C++ | tilerun/src/scenes/Temple_scene.cpp | PrincenMaxim/gba-sprite-engine | b5d321b84397c2ec7c4aa57d89ace7d78ab8b751 | [
"MIT"
] | null | null | null | tilerun/src/scenes/Temple_scene.cpp | PrincenMaxim/gba-sprite-engine | b5d321b84397c2ec7c4aa57d89ace7d78ab8b751 | [
"MIT"
] | null | null | null | tilerun/src/scenes/Temple_scene.cpp | PrincenMaxim/gba-sprite-engine | b5d321b84397c2ec7c4aa57d89ace7d78ab8b751 | [
"MIT"
] | null | null | null | //
// Created by Gebruiker on 23/12/2020.
//
#include "Temple_scene.h"
#include "../backgrounds/temple_input.h"
#include "../sprites/pink_guy_sprites.h"
#include "../sprites/owlet_sprites.h"
#include "../sprites/dude_sprites.h"
#include "../sounds/coinsound.h"
std::vector<Sprite *> Temple_scene::sprites(){
std::vector<Sprite *> sprites;
for( int j =0 ; j<coinSprites.size(); j++){
sprites.push_back(coinSprites[j].get());
}
for(int h =0; h<player.getSprite().size(); h++){
sprites.push_back(player.getSprite()[h]);
}
return sprites;
};
std::vector<Background *> Temple_scene::backgrounds(){
return{
bg_statics.get(),
bg_dynamics.get(),
bg_3_filler.get()
};
}
void Temple_scene::scrollCoins(){
for (int s = 0; s<coinSprites.size(); s++){
if(coinSprites[s] != nullptr) coinSprites[s].get()->moveTo(coinX[s] - scrollStatics, coinY[s]);
}
}
void Temple_scene::removeCoins(){
for(int i=0; i<coinSprites.size(); i++){
if(player.getSprite()[1]->collidesWith(*coinSprites[i].get()) || player.getSprite()[0]->collidesWith(*coinSprites[i].get())){
engine->dequeueAllSounds();
coinY[i]=GBA_SCREEN_HEIGHT+16;
collectedCoins++;
scrollCoins();
engine->enqueueSound(coinsound, sizeof(coinsound), 98000);
}
}
}
void Temple_scene::loadCoins() {
for(int i = 0; i<3; i++){
if(skin_choice == 0){
coinSprites.push_back(builder.withSize(SIZE_16_16)
.withLocation(coinX[i], coinY[i])
.withData(pink_guy_coinTiles, sizeof(pink_guy_coinTiles))
.withAnimated(5, 3)
.buildPtr());
}
else if(skin_choice == 1){
coinSprites.push_back(builder.withSize(SIZE_16_16)
.withLocation(coinX[i], coinY[i])
.withData(owlet_coinTiles, sizeof(owlet_coinTiles))
.withAnimated(5, 3)
.buildPtr());
}
else if(skin_choice == 2) {
coinSprites.push_back(builder.withSize(SIZE_16_16)
.withLocation(coinX[i], coinY[i])
.withData(dude_coinTiles, sizeof(dude_coinTiles))
.withAnimated(5, 3)
.buildPtr());
}
}
}
void Temple_scene::load() {
engine.get()->enableText();
loadCoins();
switch (skin_choice) {
case 0 :
foregroundPalette = std::unique_ptr<ForegroundPaletteManager>(
new ForegroundPaletteManager(pink_guy_sharedPal, sizeof(pink_guy_sharedPal)));
break;
case 1 :
foregroundPalette = std::unique_ptr<ForegroundPaletteManager>(
new ForegroundPaletteManager(owlet_sharedPal, sizeof(owlet_sharedPal)));
break;
case 2 :
foregroundPalette = std::unique_ptr<ForegroundPaletteManager>(
new ForegroundPaletteManager(dude_sharedPal, sizeof(dude_sharedPal)));
break;
}
backgroundPalette = std::unique_ptr<BackgroundPaletteManager>(
new BackgroundPaletteManager(temple_sharedPal, sizeof(temple_sharedPal)));
bg_statics = std::unique_ptr<Background>(
new Background(1, temple_staticsTiles, sizeof(temple_staticsTiles),
temple_map, sizeof(temple_map), 18, 1, MAPLAYOUT_32X64));
bg_dynamics = std::unique_ptr<Background>(
new Background(2, temple_cloudsTiles, sizeof(temple_cloudsTiles),
temple_clouds_map, sizeof(temple_clouds_map),
14, 2, MAPLAYOUT_32X32));
bg_3_filler = std::unique_ptr<Background>(
new Background(3, temple_cloudsTiles, sizeof(temple_cloudsTiles),
temple_clouds_map, sizeof(temple_clouds_map),
14, 3, MAPLAYOUT_32X32));
//is hetzelfde als
//bg_statics->useMapScreenBlock(18);
//bg_dynamics->useMapScreenBlock(14);
//bg_3_filler->useMapScreenBlock(14);
player.setBuilder(builder, startY, skin_choice);
bg_statics.get()->scroll(0, 0);
bg_dynamics.get()->scroll(0,0);
}
void Temple_scene::tick(u16 keys) {
TextStream::instance().clear();
moveLeft = keys & KEY_LEFT;
moveRight = keys & KEY_RIGHT;
moveUp = keys & KEY_UP;
moveDown = keys & KEY_DOWN;
bPressed = keys & KEY_B;
/*TextStream::instance().setText("x_tile: " + std::to_string(player.getPosX()), 1, 1);
TextStream::instance().setText("y_tile: " + std::to_string(player.getPosY()), 2, 1);
TextStream::instance().setText("jumpTimer: " + std::to_string(player.getJumpTimer()), 3, 1);
TextStream::instance().setText(
"collision: " + std::to_string(player.collision(moveUp, moveDown, moveLeft, moveRight,
nullptr, collisionMap_temple, mapWidth)), 4, 1);*/
TextStream::instance().setText(std::to_string(engine->getTimer()->getMinutes())+":"+
std::to_string(engine->getTimer()->getSecs())+":"+
std::to_string(engine->getTimer()->getMsecs()),1,1);
timer += 1;
if (timer % 30 == 0) {
scrollX++;
}
bg_dynamics->scroll(scrollX,0);
if (player.getPosX() % 1 == 0 && player.getPosX() > 40 && keys & KEY_RIGHT && scrollStatics < 270 &&
player.collision(moveUp, moveDown, moveLeft, moveRight, nullptr, collisionMap_temple, mapWidth) == 0) {
if (bPressed) scrollStatics += 2;
else scrollStatics += 1;
bg_statics.get()->scroll(scrollStatics, 0);
scrollCoins();
}
if (player.getPosX() % 1 == 0 && player.getPosX() > 40 && keys & KEY_LEFT && scrollStatics > 0 &&
player.getPosX() < 200 &&
player.collision(moveUp, moveDown, moveLeft, moveRight, nullptr, collisionMap_temple, mapWidth) == 0) {
if (bPressed) scrollStatics -= 2;
else scrollStatics -= 1;
bg_statics.get()->scroll(scrollStatics, 0);
scrollCoins();
}
player.calcJumpDirection(moveUp, moveLeft, moveRight);
//running
if (bPressed) {
player.move(moveUp, moveDown, moveLeft, moveRight, nullptr, this->collisionMap_temple, bPressed, mapWidth,
scrollStatics);
}
//walking
else {
if (timer % 2 == 0) {
player.move(moveUp, moveDown, moveLeft, moveRight, nullptr, this->collisionMap_temple, bPressed, mapWidth,
scrollStatics);
}
}
player.isIdle(moveUp, moveDown, moveLeft, moveRight);
player.setGravity(nullptr, this->collisionMap_temple, mapWidth, scrollStatics);
removeCoins();
if (player.calcTileX() == 62) {
save->setCoinsTemple(collectedCoins);
FloatingIslands_scene *floatingIslandsScene = new FloatingIslands_scene(engine, save);
engine->setScene(floatingIslandsScene);
}
if (player.fellOfMap(nullptr, this->collisionMap_temple, mapWidth)) {
Death_scene *deathScene = new Death_scene(engine, save);
engine->transitionIntoScene(deathScene, new FadeOutScene(2));
}
}
| 37.452736 | 133 | 0.576382 | [
"vector"
] |
2a3e1a8a03968dd7982fc18521c7f62289258341 | 1,003 | cc | C++ | LeetCode/MS Prep/2008_maxEarnTaxi.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | LeetCode/MS Prep/2008_maxEarnTaxi.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | LeetCode/MS Prep/2008_maxEarnTaxi.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1470935/C%2B%2BPython-DP-O(M%2BN)-Clean-and-Concise
#include<iostream>
#include<set>
#include<vector>
using namespace std;
#define pii pair<int, int>
class Solution {
public:
long long maxTaxiEarnings(int n, vector<vector<int>>& rides) {
vector<vector<pii>> rideStartAt(n);
for (auto& ride : rides) {
int s = ride[0], e = ride[1], t = ride[2];
rideStartAt[s].push_back({e, e - s + t}); // [end, dollar]
}
vector<long long> dp(n+1);
for (int i = n-1; i >= 1; --i) {
for (auto& [e, d] : rideStartAt[i]) {
dp[i] = max(dp[i], dp[e] + d);
}
dp[i] = max(dp[i], dp[i + 1]);
}
return dp[1];
}
};
int main()
{
int n = 20;
vector<vector<int> >rides { {1, 6, 1},{3, 10, 2},{10, 12, 3},{11, 12, 2},{12, 15, 2 }, { 13, 18, 1 } };
Solution o;
cout << o.maxTaxiEarnings(n, rides);
} | 30.393939 | 119 | 0.511466 | [
"vector"
] |
2a48551d93b797cc2509de75ffcdf7c84712ea57 | 23,692 | cpp | C++ | source/edgecollapse.cpp | spockthegray/mantaflow | df72cf235e14ef4f3f8fac9141b5e0a8707406b3 | [
"Apache-2.0"
] | 158 | 2018-06-24T17:42:13.000Z | 2022-03-12T13:29:43.000Z | source/edgecollapse.cpp | spockthegray/mantaflow | df72cf235e14ef4f3f8fac9141b5e0a8707406b3 | [
"Apache-2.0"
] | 5 | 2018-09-05T07:30:48.000Z | 2020-07-01T08:56:28.000Z | source/edgecollapse.cpp | spockthegray/mantaflow | df72cf235e14ef4f3f8fac9141b5e0a8707406b3 | [
"Apache-2.0"
] | 35 | 2018-06-13T04:05:42.000Z | 2022-03-29T16:55:24.000Z | /******************************************************************************
*
* MantaFlow fluid solver framework
* Copyright 2011 Tobias Pfaff, Nils Thuerey
*
* This program is free software, distributed under the terms of the
* Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Mesh edge collapse and subdivision
*
******************************************************************************/
/******************************************************************************/
// Copyright note:
//
// These functions (C) Chris Wojtan
// Long-term goal is to unify with his split&merge codebase
//
/******************************************************************************/
#include "edgecollapse.h"
#include <queue>
using namespace std;
namespace Manta {
// 8-point butterfly subdivision scheme (as described by Brochu&Bridson 2009)
Vec3 ButterflySubdivision(Mesh& m, const Corner &ca, const Corner &cb)
{
Vec3 p = m.nodes(m.corners(ca.prev).node).pos + m.nodes(m.corners(ca.next).node).pos;
Vec3 q = m.nodes(ca.node).pos + m.nodes(cb.node).pos;
Vec3 r = m.nodes(m.corners(m.corners(ca.next).opposite).node).pos
+ m.nodes(m.corners(m.corners(ca.prev).opposite).node).pos
+ m.nodes(m.corners(m.corners(cb.next).opposite).node).pos
+ m.nodes(m.corners(m.corners(cb.prev).opposite).node).pos;
return ( 8*p + 2*q - r)/16.0;
}
// Modified Butterfly Subdivision Scheme from:
// Interpolating Subdivision for Meshes with Arbitrary Topology
// Denis Zorin, Peter Schroder, and Wim Sweldens
// input the Corner that satisfies the following:
// c.prev.node is the extraordinary vertex,
// and c.next.node is the other vertex involved in the subdivision
Vec3 OneSidedButterflySubdivision(Mesh& m, const int valence, const Corner &c) {
Vec3 out;
Vec3 p0 = m.nodes(m.corners(c.prev).node).pos;
Vec3 p1 = m.nodes(m.corners(c.next).node).pos;
if(valence==3) {
Vec3 p2 = m.nodes(c.node).pos;
Vec3 p3 = m.nodes(m.corners(m.corners(c.next).opposite).node).pos;
out = (5.0/12.0)*p1 - (1.0/12.0)*(p2+p3) + 0.75*p0;
}
else if(valence==4) {
Vec3 p2 = m.nodes(m.corners(m.corners(c.next).opposite).node).pos;
out = 0.375*p1 - 0.125*p2 + 0.75*p0;
}
else {
// rotate around extraordinary vertex,
// calculate subdivision weights,
// and interpolate vertex position
double rv = 1.0/(double)valence;
out = 0.0;
int current = c.prev;
for(int j=0; j<valence; j++) {
double s = (0.25 + cos(2*M_PI*j*rv) + 0.5*cos(4*M_PI*j*rv))*rv;
Vec3 p = m.nodes(m.corners(m.corners(current).prev).node).pos;
out += s*p;
current = m.corners(m.corners(m.corners(current).next).opposite).next;
}
out += 0.75* m.nodes(m.corners(c.prev).node).pos;
}
return out;
}
// Modified Butterfly Subdivision Scheme from:
// Interpolating Subdivision for Meshes with Arbitrary Topology
// Denis Zorin, Peter Schroder, and Wim Sweldens
Vec3 ModifiedButterflySubdivision(Mesh& m, const Corner &ca, const Corner &cb, const Vec3& fallback)
{
// calculate the valence of the two parent vertices
int start = ca.prev;
int current = start;
int valenceA = 0;
do {
valenceA++;
int op = m.corners(m.corners(current).next).opposite;
if (op < 0) return fallback;
current = m.corners(op).next;
}
while(current != start);
start = ca.next;
current = start;
int valenceB = 0;
do {
valenceB++;
int op = m.corners(m.corners(current).next).opposite;
if (op < 0) return fallback;
current = m.corners(op).next;
}
while(current != start);
// if both vertices have valence 6, use butterfly subdivision
if(valenceA==6 && valenceB==6) {
return ButterflySubdivision(m, ca,cb);
}
else if(valenceA==6) // use a one-sided scheme
{
return OneSidedButterflySubdivision(m, valenceB,cb);
}
else if(valenceB==6) // use a one-sided scheme
{
return OneSidedButterflySubdivision(m, valenceA,ca);
}
else // average the results from two one-sided schemes
{
return 0.5*( OneSidedButterflySubdivision(m, valenceA,ca)
+ OneSidedButterflySubdivision(m, valenceB,cb) );
}
}
bool gAbort = false;
// collapse an edge on triangle "trinum".
// "which" is 0,1, or 2,
// where which==0 is the triangle edge from p0 to p1,
// which==1 is the triangle edge from p1 to p2,
// and which==2 is the triangle edge from p2 to p0,
void CollapseEdge(Mesh& m, const int trinum, const int which, const Vec3 &edgevect, const Vec3 &endpoint,
vector<int> &deletedNodes, std::map<int,bool> &taintedTris, int &numCollapses, bool doTubeCutting)
{
if (gAbort) return;
// I wanted to draw a pretty picture of an edge collapse,
// but I don't know how to make wacky angled lines in ASCII.
// Instead, I will show the before case and tell you what needs to be done.
// BEFORE:
// *
// / \.
// /C0 \.
// / \.
// / \.
// / B \.
// / \.
// /C1 C2 \.
// P0 *---------------* P1
// \C2 C1 /
// \ /
// \ A /
// \ /
// \ /
// \C0 /
// \ /
// *
//
// We are going to collapse the edge between P0 and P1
// by deleting P1,
// and taking all references to P1,
// and rerouting them to P0 instead
//
// What we need to do:
// Move position of P0
// Preserve connectivity in both triangles:
// (C1.opposite).opposite = C2.o
// (C2.opposite).opposite = C1.o
// Delete references to Corners of deleted triangles in both P0 and P1's Corner list
// Reassign references to P1:
// loop through P1 triangles:
// rename P1 references to P0 in p lists.
// rename Corner.v references
// Copy P1's list of Corners over to P0's list of Corners
// Delete P1
Corner ca_old[3], cb_old[3];
ca_old[0] = m.corners(trinum, which);
ca_old[1] = m.corners(ca_old[0].next);
ca_old[2] = m.corners(ca_old[0].prev);
bool haveB = false;
if (ca_old[0].opposite>=0) {
cb_old[0] = m.corners(ca_old[0].opposite);
cb_old[1] = m.corners(cb_old[0].next);
cb_old[2] = m.corners(cb_old[0].prev);
haveB = true;
}
if (!haveB) {
// for now, don't collapse
return;
}
int P0 = ca_old[2].node;
int P1 = ca_old[1].node;
///////////////
// avoid creating nonmanifold edges
bool nonmanifold = false;
bool nonmanifold2 = false;
set<int>& ring0 = m.get1Ring(P0).nodes;
set<int>& ring1 = m.get1Ring(P1).nodes;
// check for intersections of the 1-rings of P0,P1
int cl=0, commonVert=-1;
for(set<int>::iterator it=ring1.begin(); it != ring1.end(); ++it)
if (ring0.find(*it) != ring0.end()) {
cl++;
if (*it != ca_old[0].node && *it != cb_old[0].node) commonVert = *it;
}
nonmanifold = cl>2;
nonmanifold2 = cl>3;
if(nonmanifold &&
ca_old[1].opposite>=0 && cb_old[1].opposite>=0 &&
ca_old[2].opposite>=0 && cb_old[2].opposite>=0 ) // collapsing this edge would create a non-manifold edge
{
if(nonmanifold2)
return;
bool topTet = false;
bool botTet = false;
// check if collapsing this edge will collapse a tet.
if(m.corners(ca_old[1].opposite).node == m.corners(ca_old[2].opposite).node)
botTet = true;
if(m.corners(cb_old[1].opposite).node == m.corners(cb_old[2].opposite).node)
topTet = true;
if(topTet^botTet) {
// safe pyramid case.
// collapse the whole tet!
// First collapse the top of the pyramid,
// then carry on collapsing the original verts.
Corner cc_old[3],cd_old[3];
if(botTet)
cc_old[0] = m.corners(ca_old[1].opposite);
else // topTet
cc_old[0] = cb_old[2];
cc_old[1] = m.corners(cc_old[0].next);
cc_old[2] = m.corners(cc_old[0].prev);
if (cc_old[0].opposite<0) return;
cd_old[0] = m.corners(cc_old[0].opposite);
cd_old[1] = m.corners(cd_old[0].next);
cd_old[2] = m.corners(cd_old[0].prev);
int P2 = cc_old[2].node;
int P3 = cc_old[1].node;
// update tri props of all adjacent triangles of P0,P1 (do before CT updates!)
for (int i=0; i<m.numTriChannels(); i++)
{};//TODO: handleTriPropertyEdgeCollapse(trinum, P2,P3, cc_old[0], cd_old[0]);
m.mergeNode(P2, P3);
// Preserve connectivity in both triangles
if (cc_old[1].opposite>=0)
m.corners(cc_old[1].opposite).opposite = cc_old[2].opposite;
if (cc_old[2].opposite>=0)
m.corners(cc_old[2].opposite).opposite = cc_old[1].opposite;
if (cd_old[1].opposite>=0)
m.corners(cd_old[1].opposite).opposite = cd_old[2].opposite;
if (cd_old[2].opposite>=0)
m.corners(cd_old[2].opposite).opposite = cd_old[1].opposite;
////////////////////
// mark the two triangles and the one node for deletion
int tmpTrinum = cc_old[0].tri;
int tmpOthertri = cd_old[0].tri;
m.removeTriFromLookup(tmpTrinum);
m.removeTriFromLookup(tmpOthertri);
taintedTris[tmpTrinum] = true;
taintedTris[tmpOthertri] = true;
deletedNodes.push_back(P3);
numCollapses++;
// recompute Corners for triangles A and B
if(botTet)
ca_old[0] = m.corners(ca_old[2].opposite);
else
ca_old[0] = m.corners(ca_old[1].prev);
ca_old[1] = m.corners(ca_old[0].next);
ca_old[2] = m.corners(ca_old[0].prev);
cb_old[0] = m.corners(ca_old[0].opposite);
cb_old[1] = m.corners(cb_old[0].next);
cb_old[2] = m.corners(cb_old[0].prev);
///////////////
// avoid creating nonmanifold edges... again
ring0 = m.get1Ring(ca_old[2].node).nodes;
ring1 = m.get1Ring(ca_old[1].node).nodes;
// check for intersections of the 1-rings of P0,P1
cl=0;
for(set<int>::iterator it=ring1.begin(); it != ring1.end(); ++it)
if (*it != ca_old[0].node && ring0.find(*it) != ring0.end())
cl++;
if(cl>2) { // nonmanifold
// this can happen if collapsing the first tet leads to another similar collapse that requires the collapse of a tet.
// for now, just move on and pick this up later.
// if the original component was very small, this first collapse could have led to a tiny piece of nonmanifold geometry.
// in this case, just delete everything that remains.
if(m.corners(ca_old[0].opposite).tri==cb_old[0].tri && m.corners(ca_old[1].opposite).tri==cb_old[0].tri && m.corners(ca_old[2].opposite).tri==cb_old[0].tri) {
taintedTris[ca_old[0].tri] = true;
taintedTris[cb_old[0].tri] = true;
m.removeTriFromLookup(ca_old[0].tri);
m.removeTriFromLookup(cb_old[0].tri);
deletedNodes.push_back(ca_old[0].node);
deletedNodes.push_back(ca_old[1].node);
deletedNodes.push_back(ca_old[2].node);
}
return;
}
} else if(topTet && botTet && ca_old[1].opposite>=0 && ca_old[2].opposite>=0 && cb_old[1].opposite>=0 && cb_old[2].opposite>=0)
{
if(!(m.corners(ca_old[1].opposite).node == m.corners(ca_old[2].opposite).node &&
m.corners(cb_old[1].opposite).node == m.corners(cb_old[2].opposite).node &&
(m.corners(ca_old[1].opposite).node == m.corners(cb_old[1].opposite).node ||
(m.corners(ca_old[1].opposite).node == cb_old[0].node &&
m.corners(cb_old[1].opposite).node == ca_old[0].node) )))
{
// just collapse one for now.
// collapse the whole tet!
// First collapse the top of the pyramid,
// then carry on collapsing the original verts.
Corner cc_old[3],cd_old[3];
// collapse top
{
cc_old[0] = m.corners(ca_old[1].opposite);
cc_old[1] = m.corners(cc_old[0].next);
cc_old[2] = m.corners(cc_old[0].prev);
if (cc_old[0].opposite<0) return;
cd_old[0] = m.corners(cc_old[0].opposite);
cd_old[1] = m.corners(cd_old[0].next);
cd_old[2] = m.corners(cd_old[0].prev);
int P2 = cc_old[2].node;
int P3 = cc_old[1].node;
// update tri props of all adjacent triangles of P0,P1 (do before CT updates!)
// TODO: handleTriPropertyEdgeCollapse(trinum, P2,P3, cc_old[0], cd_old[0]);
m.mergeNode(P2, P3);
// Preserve connectivity in both triangles
if (cc_old[1].opposite>=0)
m.corners(cc_old[1].opposite).opposite = cc_old[2].opposite;
if (cc_old[2].opposite>=0)
m.corners(cc_old[2].opposite).opposite = cc_old[1].opposite;
if (cd_old[1].opposite>=0)
m.corners(cd_old[1].opposite).opposite = cd_old[2].opposite;
if (cd_old[2].opposite>=0)
m.corners(cd_old[2].opposite).opposite = cd_old[1].opposite;
////////////////////
// mark the two triangles and the one node for deletion
int tmpTrinum = cc_old[0].tri;
int tmpOthertri = cd_old[0].tri;
taintedTris[tmpTrinum] = true;
taintedTris[tmpOthertri] = true;
m.removeTriFromLookup(tmpTrinum);
m.removeTriFromLookup(tmpOthertri);
deletedNodes.push_back(P3);
numCollapses++;
}
// then collapse bottom
{
//cc_old[0] = [ca_old[1].opposite;
cc_old[0] = cb_old[2];
cc_old[1] = m.corners(cc_old[0].next);
cc_old[2] = m.corners(cc_old[0].prev);
if (cc_old[0].opposite<0) return;
cd_old[0] = m.corners(cc_old[0].opposite);
cd_old[1] = m.corners(cd_old[0].next);
cd_old[2] = m.corners(cd_old[0].prev);
int P2 = cc_old[2].node;
int P3 = cc_old[1].node;
// update tri props of all adjacent triangles of P0,P1 (do before CT updates!)
// TODO: handleTriPropertyEdgeCollapse(trinum, P2,P3, cc_old[0], cd_old[0]);
m.mergeNode(P2, P3);
// Preserve connectivity in both triangles
if (cc_old[1].opposite>=0)
m.corners(cc_old[1].opposite).opposite = cc_old[2].opposite;
if (cc_old[2].opposite>=0)
m.corners(cc_old[2].opposite).opposite = cc_old[1].opposite;
if (cd_old[1].opposite>=0)
m.corners(cd_old[1].opposite).opposite = cd_old[2].opposite;
if (cd_old[2].opposite>=0)
m.corners(cd_old[2].opposite).opposite = cd_old[1].opposite;
////////////////////
// mark the two triangles and the one node for deletion
int tmpTrinum = cc_old[0].tri;
int tmpOthertri = cd_old[0].tri;
taintedTris[tmpTrinum] = true;
taintedTris[tmpOthertri] = true;
deletedNodes.push_back(P3);
numCollapses++;
}
// Though we've collapsed a lot of stuff, we still haven't collapsed the original edge.
// At this point we still haven't guaranteed that this original collapse weill be safe.
// quit for now, and we'll catch the remaining short edges the next time this function is called.
return;
}
}
else if (doTubeCutting)
{
// tube case
//cout<<"CollapseEdge:tube case" << endl;
// find the edges that touch the common vert
int P2 = commonVert;
int P1P2=-1, P2P1, P2P0=-1, P0P2=-1; // corners across from the cutting seam
int start = ca_old[0].next;
int end = cb_old[0].prev;
int current = start;
do {
// rotate around vertex P1 counter-clockwise
int op = m.corners(m.corners(current).next).opposite;
if (op < 0) errMsg("tube cutting failed, no opposite");
current = m.corners(op).next;
if(m.corners(m.corners(current).prev).node==commonVert)
P1P2 = m.corners(current).next;
}
while(current != end);
start = ca_old[0].prev;
end = cb_old[0].next;
current = start;
do {
// rotate around vertex P0 clockwise
int op = m.corners(m.corners(current).prev).opposite;
if (op < 0) errMsg("tube cutting failed, no opposite");
current = m.corners(op).prev;
if(m.corners(m.corners(current).next).node==commonVert)
P2P0 = m.corners(current).prev;
} while(current != end);
if (P1P2 < 0 || P2P0 < 0)
errMsg("tube cutting failed, ill geometry");
P2P1 = m.corners(P1P2).opposite;
P0P2 = m.corners(P2P0).opposite;
// duplicate vertices on the top half of the cut,
// and use them to split the tube at this seam
int P0b = m.addNode(Node(m.nodes(P0).pos));
int P1b = m.addNode(Node(m.nodes(P1).pos));
int P2b = m.addNode(Node(m.nodes(P2).pos));
for (int i=0; i<m.numNodeChannels(); i++) {
m.nodeChannel(i)->addInterpol(P0, P0, 0.5);
m.nodeChannel(i)->addInterpol(P1, P1, 0.5);
m.nodeChannel(i)->addInterpol(P2, P2, 0.5);
}
// offset the verts in the normal directions to avoid self intersections
Vec3 offsetVec = cross(m.nodes(P1).pos-m.nodes(P0).pos, m.nodes(P2).pos-m.nodes(P0).pos);
normalize(offsetVec);
offsetVec *= 0.01; // HACK:
m.nodes(P0).pos -= offsetVec;
m.nodes(P1).pos -= offsetVec;
m.nodes(P2).pos -= offsetVec;
m.nodes(P0b).pos += offsetVec;
m.nodes(P1b).pos += offsetVec;
m.nodes(P2b).pos += offsetVec;
// create a list of all triangles which touch P0, P1, and P2 from the top,
map<int,bool> topTris;
start = cb_old[0].next;
end = m.corners(P0P2).prev;
current = start;
topTris[start/3]=true;
do {
// rotate around vertex P0 counter-clockwise
current = m.corners(m.corners(m.corners(current).next).opposite).next;
topTris[current/3]=true;
} while(current != end);
start = m.corners(P0P2).next;
end = m.corners(P2P1).prev;
current = start;
topTris[start/3]=true;
do {
// rotate around vertex P0 counter-clockwise
current = m.corners(m.corners(m.corners(current).next).opposite).next;
topTris[current/3]=true;
} while(current != end);
start = m.corners(P2P1).next;
end = cb_old[0].prev;
current = start;
topTris[start/3]=true;
do {
// rotate around vertex P0 counter-clockwise
current = m.corners(m.corners(m.corners(current).next).opposite).next;
topTris[current/3]=true;
} while(current != end);
// create two new triangles,
int Ta = m.addTri(Triangle(P0,P1,P2));
int Tb = m.addTri(Triangle(P1b,P0b,P2b));
for (int i=0; i<m.numTriChannels(); i++) {
m.triChannel(i)->addNew();
m.triChannel(i)->addNew();
}
// sew the tris to close the cut on each side
for(int c=0; c<3; c++) m.addCorner(Corner(Ta, m.tris(Ta).c[c]));
for(int c=0; c<3; c++) m.addCorner(Corner(Tb, m.tris(Tb).c[c]));
for(int c=0; c<3; c++) {
m.corners(Ta,c).next = 3*Ta+((c+1)%3);
m.corners(Ta,c).prev = 3*Ta+((c+2)%3);
m.corners(Tb,c).next = 3*Tb+((c+1)%3);
m.corners(Tb,c).prev = 3*Tb+((c+2)%3);
}
m.corners(Ta,0).opposite = P1P2;
m.corners(Ta,1).opposite = P2P0;
m.corners(Ta,2).opposite = ca_old[1].prev;
m.corners(Tb,0).opposite = P0P2;
m.corners(Tb,1).opposite = P2P1;
m.corners(Tb,2).opposite = cb_old[1].prev;
for (int c=0; c<3; c++) {
m.corners(m.corners(Ta,c).opposite).opposite = 3*Ta+c;
m.corners(m.corners(Tb,c).opposite).opposite = 3*Tb+c;
}
// replace P0,P1,P2 on the top with P0b,P1b,P2b.
for(map<int,bool>::iterator tti=topTris.begin(); tti!=topTris.end(); tti++) {
//cout << "H " << tti->first << " : " << m.tris(tti->first).c[0] << " " << m.tris(tti->first).c[1] << " " << m.tris(tti->first).c[2] << " " << endl;
for(int i=0; i<3; i++) {
int cn = m.tris(tti->first).c[i];
set<int>& ring = m.get1Ring(cn).nodes;
if (ring.find(P0) != ring.end() && cn!=P0 && cn!=P1 && cn!=P2 && cn!=P0b && cn!=P1b && cn!=P2b) {
ring.erase(P0);
ring.insert(P0b);
m.get1Ring(P0).nodes.erase(cn);
m.get1Ring(P0b).nodes.insert(cn);
}
if (ring.find(P1) != ring.end() && cn!=P0 && cn!=P1 && cn!=P2 && cn!=P0b && cn!=P1b && cn!=P2b) {
ring.erase(P1);
ring.insert(P1b);
m.get1Ring(P1).nodes.erase(cn);
m.get1Ring(P1b).nodes.insert(cn);
}
if (ring.find(P2) != ring.end() && cn!=P0 && cn!=P1 && cn!=P2 && cn!=P0b && cn!=P1b && cn!=P2b) {
ring.erase(P2);
ring.insert(P2b);
m.get1Ring(P2).nodes.erase(cn);
m.get1Ring(P2b).nodes.insert(cn);
}
if(cn==P0) {
m.tris(tti->first).c[i]=P0b;
m.corners(tti->first,i).node = P0b;
m.get1Ring(P0).tris.erase(tti->first);
m.get1Ring(P0b).tris.insert(tti->first);
}
else if(cn==P1) {
m.tris(tti->first).c[i]=P1b;
m.corners(tti->first,i).node = P1b;
m.get1Ring(P1).tris.erase(tti->first);
m.get1Ring(P1b).tris.insert(tti->first);
}
else if(cn==P2) {
m.tris(tti->first).c[i]=P2b;
m.corners(tti->first,i).node = P2b;
m.get1Ring(P2).tris.erase(tti->first);
m.get1Ring(P2b).tris.insert(tti->first);
}
}
}
//m.sanityCheck(true, &deletedNodes, &taintedTris);
return;
}
return;
}
if(ca_old[1].opposite>=0 && ca_old[2].opposite>=0 && cb_old[1].opposite>=0 && cb_old[2].opposite>=0 && ca_old[0].opposite>=0 && cb_old[0].opposite>=0 &&
((m.corners(ca_old[1].opposite).node == m.corners(ca_old[2].opposite).node && // two-pyramid tubey case (6 tris, 5 verts)
m.corners(cb_old[1].opposite).node == m.corners(cb_old[2].opposite).node &&
(m.corners(ca_old[1].opposite).node == m.corners(cb_old[1].opposite).node ||
(m.corners(ca_old[1].opposite).node==cb_old[0].node && // single tetrahedron case
m.corners(cb_old[1].opposite).node==ca_old[0].node) ))
||
(m.corners(ca_old[0].opposite).tri==m.corners(cb_old[0].opposite).tri && m.corners(ca_old[1].opposite).tri==m.corners(cb_old[0].opposite).tri && m.corners(ca_old[2].opposite).tri==m.corners(cb_old[0].opposite).tri // nonmanifold: 2 tris, 3 verts
&& m.corners(cb_old[0].opposite).tri==m.corners(ca_old[0].opposite).tri && m.corners(cb_old[1].opposite).tri==m.corners(ca_old[0].opposite).tri && m.corners(cb_old[2].opposite).tri==m.corners(ca_old[0].opposite).tri)
))
{
// both top and bottom are closed pyramid caps, or it is a single tet
// delete the whole component!
// flood fill to mark all triangles in the component
map<int,bool> markedTris;
queue<int> triQ;
triQ.push(trinum);
markedTris[trinum] = true;
int iters = 0;
while(!triQ.empty()) {
int trival = triQ.front();
triQ.pop();
for(int i=0; i<3; i++) {
int newtri = m.corners(m.corners(trival,i).opposite).tri;
if(markedTris.find(newtri)==markedTris.end()) {
triQ.push(newtri);
markedTris[newtri] = true;
}
}
iters++;
}
map<int,bool> markedverts;
for(map<int,bool>::iterator mit=markedTris.begin(); mit!=markedTris.end(); mit++) {
taintedTris[mit->first] = true;
markedverts[m.tris(mit->first).c[0]] = true;
markedverts[m.tris(mit->first).c[1]] = true;
markedverts[m.tris(mit->first).c[2]] = true;
}
for(map<int,bool>::iterator mit=markedverts.begin(); mit!=markedverts.end(); mit++)
deletedNodes.push_back(mit->first);
return;
}
//////////////////////////
// begin original edge collapse
// update tri props of all adjacent triangles of P0,P1 (do before CT updates!)
// TODO: handleTriPropertyEdgeCollapse(trinum, P0,P1, ca_old[0], cb_old[0]);
m.mergeNode(P0, P1);
// Move position of P0
m.nodes(P0).pos = endpoint + 0.5*edgevect;
// Preserve connectivity in both triangles
if (ca_old[1].opposite>=0)
m.corners(ca_old[1].opposite).opposite = ca_old[2].opposite;
if (ca_old[2].opposite>=0)
m.corners(ca_old[2].opposite).opposite = ca_old[1].opposite;
if (haveB && cb_old[1].opposite>=0)
m.corners(cb_old[1].opposite).opposite = cb_old[2].opposite;
if (haveB && cb_old[2].opposite>=0)
m.corners(cb_old[2].opposite).opposite = cb_old[1].opposite;
////////////////////
// mark the two triangles and the one node for deletion
taintedTris[ca_old[0].tri] = true;
m.removeTriFromLookup(ca_old[0].tri);
if (haveB) {
taintedTris[cb_old[0].tri] = true;
m.removeTriFromLookup(cb_old[0].tri);
}
deletedNodes.push_back(P1);
numCollapses++;
}
} // namespace
| 35.52024 | 249 | 0.612992 | [
"mesh",
"geometry",
"vector"
] |
2a4cf06cdf800f69fa06d54c4905f9d93ced655c | 1,226 | cpp | C++ | pvio/src/pvio/utility/worker.cpp | vrajur/PVIO | 634c023c2d6859dbab4fd47e4ae027e60e47c684 | [
"Apache-2.0"
] | 244 | 2020-10-10T07:44:38.000Z | 2022-03-05T15:07:47.000Z | pvio/src/pvio/utility/worker.cpp | vrajur/PVIO | 634c023c2d6859dbab4fd47e4ae027e60e47c684 | [
"Apache-2.0"
] | 10 | 2020-10-10T12:14:42.000Z | 2021-07-25T11:12:18.000Z | pvio/src/pvio/utility/worker.cpp | vrajur/PVIO | 634c023c2d6859dbab4fd47e4ae027e60e47c684 | [
"Apache-2.0"
] | 63 | 2020-10-10T07:44:41.000Z | 2022-02-22T07:45:37.000Z | /**************************************************************************
* This file is part of PVIO
*
* Copyright (c) ZJU-SenseTime Joint Lab of 3D Vision. 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 <pvio/utility/worker.h>
namespace pvio {
void Worker::worker_loop() {
while (worker_running) {
auto l = lock();
#if defined(PVIO_ENABLE_THREADING)
if (worker_running && empty()) {
worker_cv.wait(l, [this] { return !worker_running || !empty(); });
}
#else
if (empty()) break;
#endif
if (!worker_running) break;
work(l);
}
}
} // namespace pvio
| 32.263158 | 78 | 0.598695 | [
"3d"
] |
2a4df9fef69eb78e78393808c2ed5dc65770aa7f | 768 | cpp | C++ | dataStructure/CAnalyse/src/win/getSubPaths.cpp | Elendeer/homework | b17db0dddc8ce23ce047cb764f759d9ec47f6a8b | [
"MIT"
] | 1 | 2020-10-14T03:45:24.000Z | 2020-10-14T03:45:24.000Z | dataStructure/CAnalyse/src/win/getSubPaths.cpp | Elendeer/homework | b17db0dddc8ce23ce047cb764f759d9ec47f6a8b | [
"MIT"
] | null | null | null | dataStructure/CAnalyse/src/win/getSubPaths.cpp | Elendeer/homework | b17db0dddc8ce23ce047cb764f759d9ec47f6a8b | [
"MIT"
] | null | null | null | #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(NT)
#include "../../inc/AddressParser.hpp"
#include <direct.h>
#include <io.h>
using std::vector;
using std::string;
vector<string> AddressParser::getSubPaths(string dir_path) {
_chdir(dir_path.c_str());
vector<string> paths;
_finddata_t file;
long lf;
if ((lf = _findfirst((dir_path + "*").c_str(), &file)) == -1) {
throw (string)"path error";
}
else {
while(_findnext(lf, &file) == 0) {
if (strcmp(file.name, ".") == 0 || strcmp(file.name, "..") == 0)
continue;
paths.push_back(file.name);
}
_findclose(lf);
}
_chdir(m_current_working_directory.c_str());
return paths;
}
#endif | 21.942857 | 76 | 0.575521 | [
"vector"
] |
2a52da7c7b8b1c3761981f30e80431a4fc3b4bb8 | 14,965 | cpp | C++ | src/emulator.cpp | ttrung149/nes | 69d2ba2074a9f1c9d8a64e0e213005e4419bf190 | [
"MIT"
] | null | null | null | src/emulator.cpp | ttrung149/nes | 69d2ba2074a9f1c9d8a64e0e213005e4419bf190 | [
"MIT"
] | null | null | null | src/emulator.cpp | ttrung149/nes | 69d2ba2074a9f1c9d8a64e0e213005e4419bf190 | [
"MIT"
] | null | null | null | #include "emulator.h"
#define OPEN_SANS_FONT_DIR "utils/open-sans.ttf"
static const std::chrono::duration<int, std::micro> REFRESH_PERIOD(12000);
/* NES resolution */
#define NES_WINDOW_WIDTH 256
#define NES_WINDOW_HEIGHT 240
/* GUI resolution */
#define VIDEO_WIDTH 768
#define VIDEO_HEIGHT 720
/* GUI size (with debugging display) */
#define DEBUG_WIDTH 1056
#define DEBUG_HEIGHT 720
static const char *FLAGS_CHAR[8] = { "N", "V", "_", "B", "D", "I", "Z", "C" };
#define NUM_FLAGS 8
#define NUM_REGS 5
#define NUM_DISASM_INSTR 25
#define CHR_ROM_SIZE 128
#define NUM_PALETTE_SELECTION 8
static const SDL_Color WHITE = { 255, 255, 255, 100 };
static const SDL_Color GREY = { 180, 180, 180, 100 };
static const SDL_Color RED = { 255, 0, 0, 100 };
static const SDL_Color BLUE = { 0, 255, 255, 100 };
static const SDL_Color GREEN = { 0, 255, 0, 100 };
/*=============================================================================
* EMULATOR METHODS
*===========================================================================*/
Emulator::Emulator(Emulator::MODE m, const char *nes_file) : mode(m) {
// Create bus connection
cpu.connect_to_bus(&main_bus);
main_bus.connect_to_cpu(&cpu);
ppu.connect_to_bus(&main_bus);
main_bus.connect_to_ppu(&ppu);
cartridge = std::make_shared<Cartridge>(nes_file);
main_bus.connect_to_cartridge(cartridge);
cpu.reset();
SDL_Init(SDL_INIT_VIDEO);
// Create window size based on mode
if (mode == DEBUG_MODE) {
_disasm_instr_map = cpu.disasm(0x0000, 0xFFFF);
SDL_CreateWindowAndRenderer(DEBUG_WIDTH, DEBUG_HEIGHT, 0, &window, &renderer);
_is_emulating = false;
}
else if (mode == NORMAL_MODE) {
SDL_CreateWindowAndRenderer(VIDEO_WIDTH, VIDEO_HEIGHT, 0, &window, &renderer);
_is_emulating = true;
}
SDL_RenderClear(renderer);
TTF_Init();
}
Emulator::~Emulator() { stop(); }
void Emulator::_handle_debug_inputs() {
SDL_Scancode code = event.key.keysym.scancode;
if (event.type == SDL_KEYDOWN) {
switch (code) {
case SDL_SCANCODE_N: {
do { cpu.clock(); } while (!cpu.instr_completed());
do { cpu.clock(); } while (cpu.instr_completed());
break;
}
case SDL_SCANCODE_F: {
do { main_bus.clock(); } while (!ppu.frame_completed());
do { main_bus.clock(); } while (!cpu.instr_completed());
ppu.reset_frame();
break;
}
case SDL_SCANCODE_P: {
_curr_palette_selection += 1;
_curr_palette_selection &= 0x07;
break;
}
case SDL_SCANCODE_SPACE: { _is_emulating = !_is_emulating; break; }
case SDL_SCANCODE_R: { main_bus.reset(); break; }
default: break;
}
}
}
void Emulator::_handle_controller_inputs() {
SDL_Scancode code = event.key.keysym.scancode;
if (event.type == SDL_KEYDOWN) {
switch (code) {
// First controller: up, left, down, right
case SDL_SCANCODE_W: main_bus.controller[0] |= 0x08; break;
case SDL_SCANCODE_A: main_bus.controller[0] |= 0x02; break;
case SDL_SCANCODE_S: main_bus.controller[0] |= 0x04; break;
case SDL_SCANCODE_D: main_bus.controller[0] |= 0x01; break;
// First controller: A, B, Select, Start
case SDL_SCANCODE_T: main_bus.controller[0] |= 0x80; break;
case SDL_SCANCODE_Y: main_bus.controller[0] |= 0x40; break;
case SDL_SCANCODE_LSHIFT: main_bus.controller[0] |= 0x20; break;
case SDL_SCANCODE_RETURN: main_bus.controller[0] |= 0x10; break;
// Second controller: up, left, down, right
case SDL_SCANCODE_UP: main_bus.controller[1] |= 0x08; break;
case SDL_SCANCODE_LEFT: main_bus.controller[1] |= 0x02; break;
case SDL_SCANCODE_DOWN: main_bus.controller[1] |= 0x04; break;
case SDL_SCANCODE_RIGHT: main_bus.controller[1] |= 0x01; break;
// Second controller: A, B, Select, Start
case SDL_SCANCODE_H: main_bus.controller[1] |= 0x80; break;
case SDL_SCANCODE_J: main_bus.controller[1] |= 0x40; break;
case SDL_SCANCODE_K: main_bus.controller[1] |= 0x20; break;
case SDL_SCANCODE_L: main_bus.controller[1] |= 0x10; break;
default: break;
}
}
else if (event.type == SDL_KEYUP) {
switch (code) {
// First controller: up, left, down, right
case SDL_SCANCODE_W: main_bus.controller[0] &= ~0x08; break;
case SDL_SCANCODE_A: main_bus.controller[0] &= ~0x02; break;
case SDL_SCANCODE_S: main_bus.controller[0] &= ~0x04; break;
case SDL_SCANCODE_D: main_bus.controller[0] &= ~0x01; break;
// First controller: A, B, Select, Start
case SDL_SCANCODE_T: main_bus.controller[0] &= ~0x80; break;
case SDL_SCANCODE_Y: main_bus.controller[0] &= ~0x40; break;
case SDL_SCANCODE_LSHIFT: main_bus.controller[0] &= ~0x20; break;
case SDL_SCANCODE_RETURN: main_bus.controller[0] &= ~0x10; break;
// Second controller: up, left, down, right
case SDL_SCANCODE_UP: main_bus.controller[1] &= ~0x08; break;
case SDL_SCANCODE_LEFT: main_bus.controller[1] &= ~0x02; break;
case SDL_SCANCODE_DOWN: main_bus.controller[1] &= ~0x04; break;
case SDL_SCANCODE_RIGHT: main_bus.controller[1] &= ~0x01; break;
// Second controller: A, B, Select, Start
case SDL_SCANCODE_H: main_bus.controller[1] &= ~0x80; break;
case SDL_SCANCODE_J: main_bus.controller[1] &= ~0x40; break;
case SDL_SCANCODE_K: main_bus.controller[1] &= ~0x20; break;
case SDL_SCANCODE_L: main_bus.controller[1] &= ~0x10; break;
default: break;
}
}
}
/* Begin emulation */
void Emulator::begin() {
using namespace std::chrono;
_init_video_renderer();
if (mode == DEBUG_MODE) _init_debugging_gui_renderer();
assert(renderer);
while (true) {
SDL_RenderClear(renderer);
SDL_PollEvent(&event);
_handle_controller_inputs();
if (mode == DEBUG_MODE) _handle_debug_inputs();
if (event.type == SDL_QUIT) { stop(); return; }
if (_is_emulating && system_clock::now() - _start > REFRESH_PERIOD) {
do { main_bus.clock(); } while (!ppu.frame_completed());
ppu.reset_frame();
_start = system_clock::now();
}
if (mode == DEBUG_MODE) _render_debugging_gui();
_render_video();
SDL_RenderPresent(renderer);
}
}
/* Stop emulation */
void Emulator::stop() {
assert(window);
assert(renderer);
TTF_Quit();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
/*=============================================================================
* VIDEO RENDERER
*===========================================================================*/
void Emulator::_init_video_renderer() {
video_rect.x = 0;
video_rect.y = 0;
video_rect.w = VIDEO_WIDTH;
video_rect.h = VIDEO_HEIGHT;
assert(renderer);
video_text = std::make_shared<Texture>(renderer,
NES_WINDOW_WIDTH, NES_WINDOW_HEIGHT, video_rect);
ppu.set_video_texture(video_text);
}
void Emulator::_render_video() {
assert(video_text);
video_text->render_texture();
}
/*=============================================================================
* DEBUGGING GUI HELPERS
*===========================================================================*/
void Emulator::_init_debugging_gui_renderer() {
_init_flags_renderer();
_init_regs_renderer();
_init_disasm_renderer();
_init_palette_selection_renderer();
_init_chr_rom_renderer();
}
void Emulator::_render_debugging_gui() {
_render_flags();
_render_regs();
_render_disasm();
_render_palette_selection();
_render_chr_rom();
}
void Emulator::_render_str(const std::string &str, TTF_Font *font,
const SDL_Color &col, SDL_Rect &bound) {
SDL_Surface *surf = TTF_RenderText_Solid(font, str.c_str(), col);
assert(surf);
SDL_Texture *text = SDL_CreateTextureFromSurface(renderer, surf);
assert(text);
bound.w = surf->w; // Resize boundaries box's width
bound.h = surf->h; // Rezize boundaries box's height
SDL_FreeSurface(surf);
assert(renderer);
SDL_RenderCopy(renderer, text, nullptr, &bound);
SDL_DestroyTexture(text);
}
/*=============================================================================
* PALETTE SELECTION GUI RENDERER
*===========================================================================*/
void Emulator::_init_palette_selection_renderer() {
_curr_palette_selection = 0;
assert(renderer);
for (uint8_t i = 0; i < NUM_PALETTE_SELECTION; ++i) {
palettes_rects[i].x = VIDEO_WIDTH + 10 + 30 * i;
palettes_rects[i].y = 175;
palettes_rects[i].w = 20;
palettes_rects[i].h = 5;
palettes_texts[i] = std::make_shared<Texture>(renderer, 4, 1, palettes_rects[i]);
}
}
void Emulator::_render_palette_selection() {
assert(renderer);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderDrawLine(
renderer,
VIDEO_WIDTH + 10 + 30 * _curr_palette_selection, 188,
VIDEO_WIDTH + 10 + 30 * _curr_palette_selection + 20, 188
);
SDL_SetRenderDrawColor(renderer, 25, 25, 25, 100);
for (uint8_t i = 0; i < NUM_PALETTE_SELECTION; ++i) {
ppu.get_palettes_texture(palettes_texts[i], i);
palettes_texts[i]->render_texture();
}
}
/*=============================================================================
* CHR ROM GUI RENDERER
*===========================================================================*/
void Emulator::_init_chr_rom_renderer() {
chr_rom_rects[0].x = VIDEO_WIDTH + 10; chr_rom_rects[1].x = VIDEO_WIDTH + 148;
chr_rom_rects[0].y = 40; chr_rom_rects[1].y = 40;
chr_rom_rects[0].w = CHR_ROM_SIZE; chr_rom_rects[1].w = CHR_ROM_SIZE;
chr_rom_rects[0].h = CHR_ROM_SIZE; chr_rom_rects[1].h = CHR_ROM_SIZE;
assert(renderer);
chr_rom_texts[0] = std::make_shared<Texture>(renderer,
CHR_ROM_SIZE, CHR_ROM_SIZE, chr_rom_rects[0]);
chr_rom_texts[1] = std::make_shared<Texture>(renderer,
CHR_ROM_SIZE, CHR_ROM_SIZE, chr_rom_rects[1]);
}
void Emulator::_render_chr_rom() {
ppu.get_chr_rom_texture(chr_rom_texts[0], 0, _curr_palette_selection);
ppu.get_chr_rom_texture(chr_rom_texts[1], 1, _curr_palette_selection);
for (const auto &text : chr_rom_texts) text->render_texture();
}
/*=============================================================================
* CPU REGISTERS GUI RENDERER
*===========================================================================*/
void Emulator::_init_regs_renderer() {
regs_font = TTF_OpenFont(OPEN_SANS_FONT_DIR, 18);
assert(regs_font);
// A register // X register
regs_rects[0].x = VIDEO_WIDTH + 10; regs_rects[1].x = VIDEO_WIDTH + 80;
regs_rects[0].y = 195; regs_rects[1].y = 195;
// Y register // PC register
regs_rects[2].x = VIDEO_WIDTH + 150; regs_rects[3].x = VIDEO_WIDTH + 10;
regs_rects[2].y = 195; regs_rects[3].y = 215;
// STKP registers
regs_rects[4].x = VIDEO_WIDTH + 110;
regs_rects[4].y = 215;
}
void Emulator::_render_regs() {
assert(regs_font);
std::string str;
str = "A: $"; str += cpu6502::hex_str(cpu.a, 2);
_render_str(str, regs_font, GREY, regs_rects[0]);
str = "X: $"; str += cpu6502::hex_str(cpu.x, 2);
_render_str(str, regs_font, GREY, regs_rects[1]);
str = "Y: $"; str += cpu6502::hex_str(cpu.y, 2);
_render_str(str, regs_font, GREY, regs_rects[2]);
str = "PC: $"; str += cpu6502::hex_str(cpu.pc, 4);
_render_str(str, regs_font, GREY, regs_rects[3]);
str = "STKP: $"; str += cpu6502::hex_str(cpu.stkp, 4);
_render_str(str, regs_font, GREY, regs_rects[4]);
}
/*=============================================================================
* CPU FLAGS GUI RENDERER
*===========================================================================*/
void Emulator::_init_flags_renderer() {
flags_font = TTF_OpenFont(OPEN_SANS_FONT_DIR, 18);
assert(flags_font);
for (int i = 0; i < NUM_FLAGS; ++i) {
flags_rects[i].x = VIDEO_WIDTH + 10 + i * 24;
flags_rects[i].y = 5;
}
}
void Emulator::_render_flags() {
assert(flags_font);
for (int i = 0; i < NUM_FLAGS; ++i) {
if (cpu.status & (0x80 >> i))
_render_str(FLAGS_CHAR[i], flags_font, GREEN, flags_rects[i]);
else
_render_str(FLAGS_CHAR[i], flags_font, RED, flags_rects[i]);
}
}
/*=============================================================================
* DISASSEMBLED INSTRUCTIONS GUI RENDERER
*===========================================================================*/
void Emulator::_init_disasm_renderer() {
disasm_font = TTF_OpenFont(OPEN_SANS_FONT_DIR, 14);
assert(disasm_font);
for (int i = 0; i < NUM_DISASM_INSTR; ++i) {
disasm_instr_rects[i].x = VIDEO_WIDTH + 10;
disasm_instr_rects[i].y = 245 + i * 18;
}
}
void Emulator::_render_disasm() {
assert(disasm_font);
auto it = _disasm_instr_map.find(cpu.pc);
if (it == _disasm_instr_map.end()) {
_render_str("Press 'N' to continue", disasm_font, WHITE, disasm_instr_rects[0]);
return;
}
auto _it = it;
int instr_line_idx = NUM_DISASM_INSTR / 2 - 1;
// Render the previous 10 instructions before the current instruction
_it--;
while (_it != _disasm_instr_map.end() && instr_line_idx >= 0) {
_render_str(_it->second, disasm_font, WHITE, disasm_instr_rects[instr_line_idx]);
instr_line_idx--;
_it--;
}
// Render current instruction that PC is pointing to
instr_line_idx = NUM_DISASM_INSTR / 2;
_render_str(it->second, disasm_font, BLUE, disasm_instr_rects[instr_line_idx]);
instr_line_idx++;
// Render the next 10 instructions after the current instruction
_it = it;
_it++;
while (_it != _disasm_instr_map.end() && instr_line_idx < NUM_DISASM_INSTR) {
_render_str(_it->second, disasm_font, WHITE, disasm_instr_rects[instr_line_idx]);
instr_line_idx++;
_it++;
}
}
| 36.5 | 89 | 0.566789 | [
"render"
] |
2a52fc3cf0a19a7efd06043488553885fadeed69 | 748 | cc | C++ | cpp/src/str/canPermutePalindrome.cc | dacozai/algorithm-diary | 8ed5e119e4450e92e63276047ef19bbf422c2770 | [
"MIT"
] | 1 | 2019-10-17T08:34:55.000Z | 2019-10-17T08:34:55.000Z | cpp/src/str/canPermutePalindrome.cc | dacozai/algorithm-diary | 8ed5e119e4450e92e63276047ef19bbf422c2770 | [
"MIT"
] | 1 | 2020-05-24T08:32:13.000Z | 2020-05-24T08:32:13.000Z | cpp/src/str/canPermutePalindrome.cc | dacozai/algorithm-diary | 8ed5e119e4450e92e63276047ef19bbf422c2770 | [
"MIT"
] | null | null | null | #include "test.h"
/** Question no 266 easy Palindrome Permutation
* Author : Li-Han, Chen; 陳立瀚
* Date : 3rd, February, 2020
* Source : https://leetcode.com/problems/palindrome-permutation/
*
* Implement strStr().
*
* Given a string, determine if a permutation of the string could form a palindrome.
*
*/
/** Solution
* Runtime 0 ms MeMory 8.4 MB;
* faster than 100.00%, less than 75.00%
* O(n) ; O(1)
*/
bool canPermutePalindrome(std::string s) {
int LEN = 128;// ASCII letters
std::vector<int> mine(128, 0);
for (auto ch: s) {
mine[(int) ch]++;
}
int flag=0;
for(int i=0; i<LEN && flag<=1;i++) {
if (mine[i]%2==1) {
flag++;
}
}
return flag<=1;
} | 21.371429 | 84 | 0.564171 | [
"vector"
] |
2a5a1e79742244b98c5bd570770c94a5ba08bb14 | 1,075 | cpp | C++ | R-Recursion/ReplacePi.cpp | riyasingh240601/LearnCPP | 5dc75a4d7cd1a1c4519018bc4ef1f54151c0a8ed | [
"MIT"
] | 1 | 2022-03-26T02:34:12.000Z | 2022-03-26T02:34:12.000Z | R-Recursion/ReplacePi.cpp | riyasingh240601/LearnCPP | 5dc75a4d7cd1a1c4519018bc4ef1f54151c0a8ed | [
"MIT"
] | null | null | null | R-Recursion/ReplacePi.cpp | riyasingh240601/LearnCPP | 5dc75a4d7cd1a1c4519018bc4ef1f54151c0a8ed | [
"MIT"
] | null | null | null |
//------------------------------------PROBLEM :String Replace PI using Recursion ----------------------------------
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
#define mp make_pair
typedef pair<int, int> pii;
typedef pair<ll, ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vpii;
typedef vector<pl> vpl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))
//character array and index
void addPi(char s[],int i){
if(s[i]=='\0' and s[i+1]=='\0'){
return;
}
if(s[i]=='p' and s[i+1]=='i'){
int j=i+2;
while(s[j]!='\0')j++;
while(j>=i+2){
s[j+2]=s[j];
j--;
}
s[i]='3';
s[i+1]='.';
s[i+2]='1';
s[i+3]='4';
addPi(s,i+4);
}else{
//no p and corresponding 'i'
addPi(s,i+1);
}
}
int main()
{
ios_base :: sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
char arr[10000];
cin>>arr;
addPi(arr,0);
cout<<arr;
return 0;
}
| 17.622951 | 115 | 0.544186 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.