hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cf608bec139d8ca2f0bb8a828a1b05ab3f822182 | 1,903 | cpp | C++ | vnpy/api/xtp/pyscript/td/xtp_td_wrap.cpp | tanzedan/vnpy | 16c616ece1597a5766bf2fb3529f5789958330b6 | [
"MIT"
] | 4 | 2018-04-05T15:35:02.000Z | 2022-01-04T11:23:19.000Z | vnpy/api/xtp/pyscript/td/xtp_td_wrap.cpp | motw2014/vnpy | 16c616ece1597a5766bf2fb3529f5789958330b6 | [
"MIT"
] | null | null | null | vnpy/api/xtp/pyscript/td/xtp_td_wrap.cpp | motw2014/vnpy | 16c616ece1597a5766bf2fb3529f5789958330b6 | [
"MIT"
] | 1 | 2019-03-17T14:36:08.000Z | 2019-03-17T14:36:08.000Z | virtual void onDisconnected()
{
try
{
this->get_override("onDisconnected")();
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onError(dict data)
{
try
{
this->get_override("onError")(data);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onOrderEvent(dict data, dict error)
{
try
{
this->get_override("onOrderEvent")(data, error);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onTradeEvent(dict data)
{
try
{
this->get_override("onTradeEvent")(data);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onCancelOrderError(dict data, dict error)
{
try
{
this->get_override("onCancelOrderError")(data, error);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onQueryOrder(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onQueryOrder")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onQueryTrade(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onQueryTrade")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onQueryPosition(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onQueryPosition")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
virtual void onQueryAsset(dict data, dict error, int id, bool last)
{
try
{
this->get_override("onQueryAsset")(data, error, id, last);
}
catch (error_already_set const &)
{
PyErr_Print();
}
};
| 17.458716 | 70 | 0.575933 | tanzedan |
cf64d57c0d7e1d8d50f24da7f252d8716a7050ad | 729 | cpp | C++ | ares/msx/cartridge/board/super-lode-runner.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | ares/msx/cartridge/board/super-lode-runner.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | ares/msx/cartridge/board/super-lode-runner.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | //Super Lode Runner
//(not working: requires MSX BASIC)
struct SuperLodeRunner : Interface {
using Interface::Interface;
Memory::Readable<n8> rom;
auto load() -> void override {
Interface::load(rom, "program.rom");
}
auto save() -> void override {
}
auto unload() -> void override {
}
auto read(n16 address, n8 data) -> n8 override {
if(address >= 0x8000 && address <= 0xbfff) data = rom.read(bank << 14 | (n14)address);
return data;
}
auto write(n16 address, n8 data) -> void override {
if(address >= 0x0000 && address <= 0x3fff) bank = data;
}
auto power() -> void override {
bank = 0;
}
auto serialize(serializer& s) -> void override {
s(bank);
}
n8 bank;
};
| 19.702703 | 90 | 0.611797 | CasualPokePlayer |
cf6948ccff79c9e64eb5f1ed40341ca8d67abcf0 | 1,960 | cpp | C++ | src/App.cpp | bubba169/moja-game | f99f353f6f8d45e2af26b1a505eb08121164823b | [
"Apache-2.0"
] | null | null | null | src/App.cpp | bubba169/moja-game | f99f353f6f8d45e2af26b1a505eb08121164823b | [
"Apache-2.0"
] | null | null | null | src/App.cpp | bubba169/moja-game | f99f353f6f8d45e2af26b1a505eb08121164823b | [
"Apache-2.0"
] | null | null | null | #include <Mojagame.h>
App::App( AppConfig* config ) : _config(config) {
_grapevine = new Grapevine();
_platform = new Platform();
_scene = new Scene();
App::_current = this;
}
App::~App() {
delete _platform;
delete _grapevine;
delete _scene;
}
App* App::_current;
App* App::current() {
return _current;
}
/**
* Platform interface
*/
int App::run(int argc, char* argv[])
{
std::size_t pos = std::string(argv[0]).find_last_of('/');
if (pos == std::string::npos) {
_appPath = "";
} else {
_appPath = std::string(argv[0]).substr(0, pos);
}
printf("App path is %s\n", _appPath.c_str());
// This is the final step to enter the game loop
_lastTick = _platform->timeInMilliseconds();
return _platform->run( this );
}
void App::tick()
{
unsigned long currentTime = _platform->timeInMilliseconds();
double sinceLastTick = (currentTime - _lastTick) / 1000.0;
_lastTick = currentTime;
// Update the app
update(sinceLastTick);
// render
render();
}
/**
* Functions to override
*/
void App::init() {
_scene->init(_config->stageWidth, _config->stageHeight);
}
void App::update( double seconds ) {}
void App::render() {
_scene->render();
}
void App::shutdown() {}
/**
* Functions that wouldn't normally be overridden
*/
void App::resize(int width, int height, float pixelRatio) {
_scene->resize(width, height, pixelRatio);
Bundle size;
size.set("width", width);
size.set("height", height);
_grapevine->send(SYSTEM_MESSAGE_RESIZE, &size);
}
/**
* Getters
*/
Platform* App::getPlatform() {
return _platform;
}
Grapevine* App::getGrapevine() {
return _grapevine;
}
AppConfig* App::getConfig() {
return _config;
}
Scene* App::getScene() {
return _scene;
}
std::string App::getPath(std::string path) {
if (path.at(0) != '/') {
path = "/" + path;
}
return _appPath + path;
} | 18.666667 | 64 | 0.612755 | bubba169 |
cf6a6a6d9bf04a7fc286aab8c0200cd082c7d3b6 | 1,701 | cpp | C++ | Scripts/GameLoop/LoopStateWin.cpp | solidajenjo/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 10 | 2019-02-25T11:36:23.000Z | 2021-11-03T22:51:30.000Z | Scripts/GameLoop/LoopStateWin.cpp | solidajenjo/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 146 | 2019-02-05T13:57:33.000Z | 2019-11-07T16:21:31.000Z | Scripts/GameLoop/LoopStateWin.cpp | FractalPuppy/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 3 | 2019-11-17T20:49:12.000Z | 2020-04-19T17:28:28.000Z | #include "LoopStateWin.h"
#include "Application.h"
#include "ModuleTime.h"
#include "ModuleScene.h"
#include "ModuleInput.h"
#include "ComponentAudioSource.h"
#include "ComponentImage.h"
#include "GameLoop.h"
#include "GameObject.h"
#define MENU_SCENE "MenuScene"
LoopStateWin::LoopStateWin(GameLoop* GL) : LoopState(GL)
{
}
LoopStateWin::~LoopStateWin()
{
}
void LoopStateWin::Update()
{
//First Outro video then loading for credits
//TODO Disable UI!!
if (outroVideo == nullptr && gLoop->outroVideoGO != nullptr)
{
gLoop->outroVideoGO->SetActive(true);
outroVideo = gLoop->outroVideoGO->GetComponent<ComponentImage>();
outroVideo->PlayVideo();
StopLvlMusic();
}
if (outroVideo != nullptr && !outroVideo->videoFinished)
{
if (gLoop->App->input->AnyKeyPressed())
{
if (!gLoop->outroSkipTextGO->isActive())
{
gLoop->outroSkipTextGO->SetActive(true);
return;
}
else
{
outroVideo->StopVideo();
}
}
else
{
return;
}
}
if (!gLoop->loadingGO->isActive())
{
gLoop->loadingGO->SetActive(true);
}
gLoop->currentLoopState = (LoopState*)gLoop->loadingState;
gLoop->playerMenuGO->SetActive(false);
gLoop->sceneToLoad = MENU_SCENE;
gLoop->App->scene->actionAfterLoad = true;
gLoop->App->scene->stateAfterLoad = "Credits";
gLoop->stateAfterLoad = (LoopState*)gLoop->creditsState;
}
void LoopStateWin::StopLvlMusic() //Temporal Fix to stop all music //TODO: we should have a musicLvlController
{
if (gLoop->audioGO == nullptr) return;
for (Component* audioSource : gLoop->audioGO->GetComponentsInChildren(ComponentType::AudioSource))
{
((ComponentAudioSource*) audioSource)->Stop();
}
gLoop->audioGO->SetActive(false);
}
| 21 | 110 | 0.703704 | solidajenjo |
cf6cd1a0c64297f7bbb38e71b6df9c875e1d7b5b | 560 | cpp | C++ | LittleBearDllNew/function/MessageBoxProc.cpp | satadriver/LittleBear | ad3939f971b1c3ac4a97d2c228e52b4eb1f388e5 | [
"Apache-2.0"
] | null | null | null | LittleBearDllNew/function/MessageBoxProc.cpp | satadriver/LittleBear | ad3939f971b1c3ac4a97d2c228e52b4eb1f388e5 | [
"Apache-2.0"
] | null | null | null | LittleBearDllNew/function/MessageBoxProc.cpp | satadriver/LittleBear | ad3939f971b1c3ac4a97d2c228e52b4eb1f388e5 | [
"Apache-2.0"
] | null | null | null |
#include <windows.h>
#include "../network/NetWorkData.h"
int __stdcall MessageBoxProc(char * msgparam){
char * param = msgparam;
int caplen = *(int*)param;
param += sizeof(int);
char *szcap = new char[caplen + 4];
memset(szcap,0,caplen + 4);
memmove(szcap,param,caplen);
param += caplen;
int textlen = *(int*)param;
char * sztext = new char[textlen + 4];
param += sizeof(int);
memset(sztext,0,textlen + 4);
memmove(sztext,param,textlen);
param += sizeof(int);
MessageBoxA(0,sztext,szcap,MB_OKCANCEL);
delete msgparam;
return TRUE;
}
| 17.5 | 46 | 0.675 | satadriver |
cf71987536faba6b3dffd0ab446b58c52cd5bbd1 | 244 | cpp | C++ | contests/UnBalloon/2-maratona/c-complexo-demais/complexo_demais.cpp | XatubaPox/programming-competitive | f5fe512266de7109f45259a82a74035ed19d9474 | [
"MIT"
] | 1 | 2022-01-25T13:11:45.000Z | 2022-01-25T13:11:45.000Z | contests/UnBalloon/2-maratona/c-complexo-demais/complexo_demais.cpp | XatubaPox/programming-competitive | f5fe512266de7109f45259a82a74035ed19d9474 | [
"MIT"
] | null | null | null | contests/UnBalloon/2-maratona/c-complexo-demais/complexo_demais.cpp | XatubaPox/programming-competitive | f5fe512266de7109f45259a82a74035ed19d9474 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main (){
int a, b, c, d, com1, com2;
cin >> a >> b >> c >> d;
com1 = (a * c) - (b * d);
com2 = (a * d) + (b * c);
printf("(%i) + (%ii)\n", com1, com2);
return 0;
}
| 14.352941 | 41 | 0.422131 | XatubaPox |
cf79c6deb54ab67715ce12a04a4e39c542afc31f | 17,493 | cc | C++ | src/oxli/assembler.cc | sadeepdarshana/khmer | bee54c4f579611d970c59367323d31d3545cafa6 | [
"CNRI-Python"
] | 558 | 2015-05-22T15:03:21.000Z | 2022-03-23T04:49:17.000Z | src/oxli/assembler.cc | sadeepdarshana/khmer | bee54c4f579611d970c59367323d31d3545cafa6 | [
"CNRI-Python"
] | 1,057 | 2015-05-14T20:27:04.000Z | 2022-03-08T09:29:36.000Z | src/oxli/assembler.cc | sadeepdarshana/khmer | bee54c4f579611d970c59367323d31d3545cafa6 | [
"CNRI-Python"
] | 193 | 2015-05-18T10:13:34.000Z | 2021-12-10T11:58:01.000Z | /*
This file is part of khmer, https://github.com/dib-lab/khmer/, and is
Copyright (C) 2015-2016, The Regents of the University of California.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the Michigan State University nor the names
of its contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
LICENSE (END)
Contact: khmer-project@idyll.org
*/
#include "oxli/assembler.hh"
#include <algorithm>
#include <iostream>
using namespace std;
namespace oxli
{
/********************************
* Simple Linear Assembly
********************************/
LinearAssembler::LinearAssembler(const Hashgraph * ht) :
graph(ht), _ksize(ht->ksize())
{
}
// Starting from the given seed k-mer, assemble the maximal linear path in
// both directions.
std::string LinearAssembler::assemble(const Kmer seed_kmer,
const Hashgraph * stop_bf)
const
{
if (graph->get_count(seed_kmer) == 0) {
// If the seed k-mer is not in the de Bruijn graph, stop trying to make
// something happen. It's not going to happen!
return "";
}
std::list<KmerFilter> node_filters;
if (stop_bf) {
node_filters.push_back(get_stop_bf_filter(stop_bf));
}
std::shared_ptr<SeenSet> visited = std::make_shared<SeenSet>();
AssemblerTraverser<TRAVERSAL_RIGHT> rcursor(graph, seed_kmer, node_filters, visited);
AssemblerTraverser<TRAVERSAL_LEFT> lcursor(graph, seed_kmer, node_filters, visited);
std::string right_contig = _assemble_directed<TRAVERSAL_RIGHT>(rcursor);
std::string left_contig = _assemble_directed<TRAVERSAL_LEFT>(lcursor);
#if DEBUG_ASSEMBLY
std::cout << "Left: " << left_contig << std::endl;
std::cout << "Right: " << right_contig << std::endl;
#endif
right_contig = right_contig.substr(_ksize);
return left_contig + right_contig;
}
std::string LinearAssembler::assemble_right(const Kmer seed_kmer,
const Hashgraph * stop_bf)
const
{
std::list<KmerFilter> node_filters;
if (stop_bf) {
node_filters.push_back(get_stop_bf_filter(stop_bf));
}
AssemblerTraverser<TRAVERSAL_RIGHT> cursor(graph, seed_kmer, node_filters);
return _assemble_directed<TRAVERSAL_RIGHT>(cursor);
}
std::string LinearAssembler::assemble_left(const Kmer seed_kmer,
const Hashgraph * stop_bf)
const
{
std::list<KmerFilter> node_filters;
if (stop_bf) {
node_filters.push_back(get_stop_bf_filter(stop_bf));
}
AssemblerTraverser<TRAVERSAL_LEFT> cursor(graph, seed_kmer, node_filters);
return _assemble_directed<TRAVERSAL_LEFT>(cursor);
}
template <>
std::string LinearAssembler::
_assemble_directed<TRAVERSAL_LEFT>(AssemblerTraverser<TRAVERSAL_LEFT>& cursor)
const
{
std::string contig = cursor.cursor.get_string_rep(_ksize);
if (!cursor.cursor.is_forward()) {
contig = _revcomp(contig);
}
#if DEBUG_ASSEMBLY
std::cout << "## assemble_linear_left[start] at " << contig << std::endl;
#endif
reverse(contig.begin(), contig.end());
char next_base;
unsigned int found = 0;
while ((next_base = cursor.next_symbol()) != '\0') {
contig += next_base;
found++;
}
reverse(contig.begin(), contig.end());
#if DEBUG_ASSEMBLY
std::cout << "## assemble_linear_left[end] found " << found << std::endl;
#endif
return contig;
}
template<>
std::string LinearAssembler::
_assemble_directed<TRAVERSAL_RIGHT>(AssemblerTraverser<TRAVERSAL_RIGHT>& cursor)
const
{
std::string contig = cursor.cursor.get_string_rep(_ksize);
if (!cursor.cursor.is_forward()) {
contig = _revcomp(contig);
}
char next_base;
unsigned int found = 0;
#if DEBUG_ASSEMBLY
std::cout << "## assemble_linear_right[start] at " << contig << std::endl;
#endif
while ((next_base = cursor.next_symbol()) != '\0') {
contig += next_base;
found++;
}
#if DEBUG_ASSEMBLY
std::cout << "## assemble_linear_right[end] found " << found << std::endl;
#endif
return contig;
}
/********************************
* Labeled Assembly
********************************/
SimpleLabeledAssembler::SimpleLabeledAssembler(const LabelHash * lh) :
graph(lh->graph), lh(lh), _ksize(lh->graph->ksize())
{
linear_asm = new LinearAssembler(graph);
}
SimpleLabeledAssembler::~SimpleLabeledAssembler()
{
delete this->linear_asm;
}
// Starting from the given seed k-mer, assemble all maximal linear paths in
// both directions, using labels to skip over tricky bits.
StringVector SimpleLabeledAssembler::assemble(const Kmer seed_kmer,
const Hashgraph * stop_bf)
const
{
#if DEBUG_ASSEMBLY
std::cout << "Assemble Labeled: " << seed_kmer.repr(_ksize) << std::endl;
#endif
KmerFilterList node_filters;
if (stop_bf) {
node_filters.push_back(get_stop_bf_filter(stop_bf));
}
std::shared_ptr<SeenSet> visited = std::make_shared<SeenSet>();
#if DEBUG_ASSEMBLY
std::cout << "Assemble Labeled RIGHT: " << seed_kmer.repr(_ksize) << std::endl;
#endif
StringVector right_paths;
AssemblerTraverser<TRAVERSAL_RIGHT> rcursor(graph, seed_kmer, node_filters, visited);
_assemble_directed<TRAVERSAL_RIGHT>(rcursor, right_paths);
#if DEBUG_ASSEMBLY
std::cout << "Assemble Labeled LEFT: " << seed_kmer.repr(_ksize) << std::endl;
#endif
StringVector left_paths;
AssemblerTraverser<TRAVERSAL_LEFT> lcursor(graph, seed_kmer, node_filters, visited);
_assemble_directed<TRAVERSAL_LEFT>(lcursor, left_paths);
StringVector paths;
for (unsigned int i = 0; i < left_paths.size(); i++) {
for (unsigned int j = 0; j < right_paths.size(); j++) {
std::string right = right_paths[j];
right = right.substr(_ksize);
std::string contig = left_paths[i] + right;
paths.push_back(contig);
}
}
visited->clear();
return paths;
}
template <bool direction>
void SimpleLabeledAssembler::
_assemble_directed(AssemblerTraverser<direction>& start_cursor,
StringVector& paths)
const
{
#if DEBUG_ASSEMBLY
std::cout << "## assemble_labeled_directed_" << direction << " [start] at " <<
start_cursor.cursor.repr(_ksize) << std::endl;
#endif
// prime the traversal with the first linear segment
std::string root_contig = linear_asm->_assemble_directed<direction>
(start_cursor);
#if DEBUG_ASSEMBLY
std::cout << "Primed: " << root_contig << std::endl;
std::cout << "Cursor: " << start_cursor.cursor.repr(_ksize) << std::endl;
#endif
StringVector segments;
std::vector< AssemblerTraverser<direction> > cursors;
segments.push_back(root_contig);
cursors.push_back(start_cursor);
while(segments.size() != 0) {
std::string segment = segments.back();
AssemblerTraverser<direction> cursor = cursors.back();
#if DEBUG_ASSEMBLY
std::cout << "Pop: " << segments.size() << " segments on stack." << std::endl;
std::cout << "Segment: " << segment << std::endl;
std::cout << "Cursor: " << cursor.cursor.repr(_ksize) << std::endl;
std::cout << "n_filters: " << cursor.n_filters() << std::endl;
#endif
segments.pop_back();
cursors.pop_back();
// check if the cursor has hit a HDN or reached a dead end
if (cursor.cursor_degree() > 1) {
LabelSet labels;
lh->get_tag_labels(cursor.cursor, labels);
if(labels.size() == 0) {
// if no labels are found we can do nothing; gather this contig
#if DEBUG_ASSEMBLY
std::cout << "no-label dead-end" << std::endl;
#endif
paths.push_back(segment);
continue;
} else {
// if there are labels, try to hop the HDN.
// first, get a label filter
cursor.push_filter(get_simple_label_intersect_filter(labels, lh));
KmerQueue branch_starts;
// now get neighbors that pass the filter
cursor.neighbors(branch_starts);
// remove the filter
cursor.pop_filter();
// no neighbors found; done with this path
if (branch_starts.empty()) {
#if DEBUG_ASSEMBLY
std::cout << "no-neighbors dead-end" << std::endl;
#endif
paths.push_back(segment);
continue;
}
// found some neighbors; extend them
while(!branch_starts.empty()) {
// spin off a cursor for the new branch
AssemblerTraverser<direction> branch_cursor(cursor);
branch_cursor.cursor = branch_starts.front();
branch_starts.pop();
#if DEBUG_ASSEMBLY
std::cout << "Branch cursor: " << branch_cursor.cursor.repr(
_ksize) << std::endl;
#endif
// assemble linearly as far as possible
std::string branch = linear_asm->_assemble_directed<direction>(branch_cursor);
// create a new segment with the branch
std::string new_segment = branch_cursor.join_contigs(segment, branch, 1);
#if DEBUG_ASSEMBLY
std::cout << "Push segment: " << new_segment << std::endl;
std::cout << "Push cursor: " << branch_cursor.cursor.repr(_ksize) << std::endl;
#endif
segments.push_back(new_segment);
cursors.push_back(branch_cursor);
}
}
} else {
// this segment is a dead-end; keep the contig
#if DEBUG_ASSEMBLY
std::cout << "degree-1 dead-end" << std::endl;
#endif
paths.push_back(segment);
continue;
}
}
}
/***************************************
* Junction-counting assembler
***************************************/
JunctionCountAssembler::JunctionCountAssembler(Hashgraph * ht) :
graph(ht), _ksize(ht->ksize()), traverser(ht), linear_asm(ht)
{
std::vector<uint64_t> table_sizes = graph->get_tablesizes();
junctions = new Countgraph(_ksize, table_sizes);
}
JunctionCountAssembler::~JunctionCountAssembler()
{
delete this->junctions;
}
uint16_t JunctionCountAssembler::consume(std::string sequence)
{
// first we need to put the sequence in the graph
graph->consume_string(sequence);
// now we find its high degree nodes and count the
// branch junctions
KmerIterator kmers(sequence.c_str(), _ksize);
Kmer kmer = kmers.next();
if (kmers.done()) {
return 0;
}
Kmer next_kmer = kmers.next();
if (kmers.done()) {
return 0;
}
uint16_t d = this->traverser.degree(kmer);
uint16_t next_d = this->traverser.degree(next_kmer);
uint16_t n_junctions = 0;
while(!kmers.done()) {
if (d > 2 || next_d > 2) {
count_junction(kmer, next_kmer);
n_junctions++;
#if DEBUG_ASSEMBLY
std::cout << "Junction: " << kmer.repr(_ksize) << ", " << next_kmer.repr(
_ksize) << std::endl;
std::cout << "Junction Count: " << get_junction_count(kmer,
next_kmer) << std::endl;
#endif
}
kmer = next_kmer;
d = next_d;
next_kmer = kmers.next();
next_d = this->traverser.degree(next_kmer);
}
return n_junctions / 2;
}
void JunctionCountAssembler::count_junction(Kmer kmer_a, Kmer kmer_b)
{
junctions->count(kmer_a.kmer_u ^ kmer_b.kmer_u);
}
BoundedCounterType JunctionCountAssembler::get_junction_count(Kmer kmer_a,
Kmer kmer_b)
const
{
return junctions->get_count(kmer_a.kmer_u ^ kmer_b.kmer_u);
}
// Starting from the given seed k-mer, assemble all maximal linear paths in
// both directions, using junction counts to skip over tricky bits.
StringVector JunctionCountAssembler::assemble(const Kmer seed_kmer,
const Hashtable * stop_bf)
const
{
#if DEBUG_ASSEMBLY
std::cout << "Assemble Junctions: " << seed_kmer.repr(_ksize) << std::endl;
#endif
KmerFilterList node_filters;
if (stop_bf) {
node_filters.push_back(get_stop_bf_filter(stop_bf));
}
std::shared_ptr<SeenSet> visited = std::make_shared<SeenSet>();
#if DEBUG_ASSEMBLY
std::cout << "Assemble Junctions RIGHT: " << seed_kmer.repr(
_ksize) << std::endl;
#endif
StringVector right_paths;
AssemblerTraverser<TRAVERSAL_RIGHT> rcursor(graph, seed_kmer, node_filters, visited);
_assemble_directed<TRAVERSAL_RIGHT>(rcursor, right_paths);
#if DEBUG_ASSEMBLY
std::cout << "Assemble Junctions LEFT: " << seed_kmer.repr(_ksize) << std::endl;
#endif
StringVector left_paths;
AssemblerTraverser<TRAVERSAL_LEFT> lcursor(graph, seed_kmer, node_filters, visited);
_assemble_directed<TRAVERSAL_LEFT>(lcursor, left_paths);
StringVector paths;
for (unsigned int i = 0; i < left_paths.size(); i++) {
for (unsigned int j = 0; j < right_paths.size(); j++) {
std::string right = right_paths[j];
right = right.substr(_ksize);
std::string contig = left_paths[i] + right;
paths.push_back(contig);
}
}
visited->clear();
return paths;
}
template <bool direction>
void JunctionCountAssembler::
_assemble_directed(AssemblerTraverser<direction>& start_cursor,
StringVector& paths)
const
{
#if DEBUG_ASSEMBLY
std::cout << "## assemble_junctions_directed_" << direction << " [start] at " <<
start_cursor.cursor.repr(_ksize) << std::endl;
#endif
// prime the traversal with the first linear segment
std::string root_contig = linear_asm._assemble_directed<direction>
(start_cursor);
#if DEBUG_ASSEMBLY
std::cout << "Primed: " << root_contig << std::endl;
std::cout << "Cursor: " << start_cursor.cursor.repr(_ksize) << std::endl;
#endif
StringVector segments;
std::vector< AssemblerTraverser<direction> > cursors;
segments.push_back(root_contig);
cursors.push_back(start_cursor);
while(segments.size() != 0) {
std::string segment = segments.back();
AssemblerTraverser<direction> cursor = cursors.back();
#if DEBUG_ASSEMBLY
std::cout << "Pop: " << segments.size() << " segments on stack." << std::endl;
std::cout << "Segment: " << segment << std::endl;
std::cout << "Cursor: " << cursor.cursor.repr(_ksize) << std::endl;
std::cout << "n_filters: " << cursor.n_filters() << std::endl;
#endif
segments.pop_back();
cursors.pop_back();
// check if the cursor has hit a HDN or reached a dead end
if (cursor.cursor_degree() > 1) {
cursor.push_filter(get_junction_count_filter(cursor.cursor, this->junctions));
KmerQueue branch_starts;
// now get neighbors that pass the filter
cursor.neighbors(branch_starts);
// remove the filter
cursor.pop_filter();
// no neighbors found; done with this path
if (branch_starts.empty()) {
paths.push_back(segment);
continue;
}
// found some neighbors; extend them
while(!branch_starts.empty()) {
// spin off a cursor for the new branch
AssemblerTraverser<direction> branch_cursor(cursor);
branch_cursor.cursor = branch_starts.front();
branch_starts.pop();
// assemble linearly as far as possible
std::string branch = linear_asm._assemble_directed<direction>(branch_cursor);
// create a new segment with the branch
std::string new_segment = branch_cursor.join_contigs(segment, branch, 1);
segments.push_back(new_segment);
cursors.push_back(branch_cursor);
}
} else {
// this segment is a dead-end; keep the contig
paths.push_back(segment);
continue;
}
}
}
}
| 32.758427 | 99 | 0.63231 | sadeepdarshana |
cf79d84525dbac544bc9cf6a6930997cbb1ab8a6 | 9,972 | hpp | C++ | src/imgui/imgui_impl_dx11_shaders.hpp | SleepKiller/shaderpatch | 4bda848df0273993c96f1d20a2cf79161088a77d | [
"MIT"
] | 13 | 2019-03-25T09:40:12.000Z | 2022-03-13T16:12:39.000Z | src/imgui/imgui_impl_dx11_shaders.hpp | SleepKiller/shaderpatch | 4bda848df0273993c96f1d20a2cf79161088a77d | [
"MIT"
] | 110 | 2018-10-16T09:05:43.000Z | 2022-03-16T23:32:28.000Z | src/imgui/imgui_impl_dx11_shaders.hpp | SleepKiller/swbfii-shaderpatch | b49ce3349d4dd09b19237ff4766652166ba1ffd4 | [
"MIT"
] | 1 | 2020-02-06T20:32:50.000Z | 2020-02-06T20:32:50.000Z |
constexpr inline static unsigned char imgui_impl_dx11_vs_shader[] =
{68, 88, 66, 67, 193, 41, 206, 126, 110, 128, 143, 52, 233, 167, 187,
47, 111, 86, 223, 148, 1, 0, 0, 0, 80, 4, 0, 0, 6, 0,
0, 0, 56, 0, 0, 0, 24, 1, 0, 0, 32, 2, 0, 0, 156,
2, 0, 0, 108, 3, 0, 0, 220, 3, 0, 0, 65, 111, 110, 57,
216, 0, 0, 0, 216, 0, 0, 0, 0, 2, 254, 255, 152, 0, 0,
0, 64, 0, 0, 0, 2, 0, 36, 0, 0, 0, 60, 0, 0, 0,
60, 0, 0, 0, 36, 0, 1, 0, 60, 0, 0, 0, 0, 0, 2,
0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 0, 3, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 254, 255, 31, 0, 0,
2, 5, 0, 0, 128, 0, 0, 15, 144, 31, 0, 0, 2, 5, 0,
1, 128, 1, 0, 15, 144, 31, 0, 0, 2, 5, 0, 2, 128, 2,
0, 15, 144, 5, 0, 0, 3, 0, 0, 15, 128, 0, 0, 85, 144,
2, 0, 228, 160, 4, 0, 0, 4, 0, 0, 15, 128, 1, 0, 228,
160, 0, 0, 0, 144, 0, 0, 228, 128, 2, 0, 0, 3, 0, 0,
15, 128, 0, 0, 228, 128, 3, 0, 228, 160, 4, 0, 0, 4, 0,
0, 3, 192, 0, 0, 255, 128, 0, 0, 228, 160, 0, 0, 228, 128,
1, 0, 0, 2, 0, 0, 12, 192, 0, 0, 228, 128, 1, 0, 0,
2, 0, 0, 15, 224, 1, 0, 228, 144, 1, 0, 0, 2, 1, 0,
3, 224, 2, 0, 228, 144, 255, 255, 0, 0, 83, 72, 68, 82, 0,
1, 0, 0, 64, 0, 1, 0, 64, 0, 0, 0, 89, 0, 0, 4,
70, 142, 32, 0, 0, 0, 0, 0, 4, 0, 0, 0, 95, 0, 0,
3, 50, 16, 16, 0, 0, 0, 0, 0, 95, 0, 0, 3, 242, 16,
16, 0, 1, 0, 0, 0, 95, 0, 0, 3, 50, 16, 16, 0, 2,
0, 0, 0, 103, 0, 0, 4, 242, 32, 16, 0, 0, 0, 0, 0,
1, 0, 0, 0, 101, 0, 0, 3, 242, 32, 16, 0, 1, 0, 0,
0, 101, 0, 0, 3, 50, 32, 16, 0, 2, 0, 0, 0, 104, 0,
0, 2, 1, 0, 0, 0, 56, 0, 0, 8, 242, 0, 16, 0, 0,
0, 0, 0, 86, 21, 16, 0, 0, 0, 0, 0, 70, 142, 32, 0,
0, 0, 0, 0, 1, 0, 0, 0, 50, 0, 0, 10, 242, 0, 16,
0, 0, 0, 0, 0, 70, 142, 32, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6, 16, 16, 0, 0, 0, 0, 0, 70, 14, 16, 0, 0,
0, 0, 0, 0, 0, 0, 8, 242, 32, 16, 0, 0, 0, 0, 0,
70, 14, 16, 0, 0, 0, 0, 0, 70, 142, 32, 0, 0, 0, 0,
0, 3, 0, 0, 0, 54, 0, 0, 5, 242, 32, 16, 0, 1, 0,
0, 0, 70, 30, 16, 0, 1, 0, 0, 0, 54, 0, 0, 5, 50,
32, 16, 0, 2, 0, 0, 0, 70, 16, 16, 0, 2, 0, 0, 0,
62, 0, 0, 1, 83, 84, 65, 84, 116, 0, 0, 0, 6, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 3, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 82, 68, 69, 70, 200, 0, 0,
0, 1, 0, 0, 0, 76, 0, 0, 0, 1, 0, 0, 0, 28, 0,
0, 0, 0, 4, 254, 255, 0, 129, 0, 0, 160, 0, 0, 0, 60,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0,
0, 118, 101, 114, 116, 101, 120, 66, 117, 102, 102, 101, 114, 0, 171,
171, 171, 60, 0, 0, 0, 1, 0, 0, 0, 100, 0, 0, 0, 64,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 124, 0, 0, 0,
0, 0, 0, 0, 64, 0, 0, 0, 2, 0, 0, 0, 144, 0, 0,
0, 0, 0, 0, 0, 80, 114, 111, 106, 101, 99, 116, 105, 111, 110,
77, 97, 116, 114, 105, 120, 0, 171, 171, 171, 3, 0, 3, 0, 4,
0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 105, 99, 114,
111, 115, 111, 102, 116, 32, 40, 82, 41, 32, 72, 76, 83, 76, 32,
83, 104, 97, 100, 101, 114, 32, 67, 111, 109, 112, 105, 108, 101, 114,
32, 49, 48, 46, 49, 0, 73, 83, 71, 78, 104, 0, 0, 0, 3,
0, 0, 0, 8, 0, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0,
0, 89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0,
0, 0, 1, 0, 0, 0, 15, 15, 0, 0, 95, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0,
3, 3, 0, 0, 80, 79, 83, 73, 84, 73, 79, 78, 0, 67, 79,
76, 79, 82, 0, 84, 69, 88, 67, 79, 79, 82, 68, 0, 79, 83,
71, 78, 108, 0, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 80,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0,
0, 0, 0, 0, 15, 0, 0, 0, 92, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 15, 0,
0, 0, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3,
0, 0, 0, 2, 0, 0, 0, 3, 12, 0, 0, 83, 86, 95, 80,
79, 83, 73, 84, 73, 79, 78, 0, 67, 79, 76, 79, 82, 0, 84,
69, 88, 67, 79, 79, 82, 68, 0, 171};
constexpr inline static unsigned char imgui_impl_dx11_ps_shader[] =
{68, 88, 66, 67, 150, 64, 133, 239, 64, 93, 176, 41, 27, 158, 89,
90, 221, 169, 17, 109, 1, 0, 0, 0, 32, 3, 0, 0, 6, 0,
0, 0, 56, 0, 0, 0, 192, 0, 0, 0, 92, 1, 0, 0, 216,
1, 0, 0, 120, 2, 0, 0, 236, 2, 0, 0, 65, 111, 110, 57,
128, 0, 0, 0, 128, 0, 0, 0, 0, 2, 255, 255, 88, 0, 0,
0, 40, 0, 0, 0, 0, 0, 40, 0, 0, 0, 40, 0, 0, 0,
40, 0, 1, 0, 36, 0, 0, 0, 40, 0, 0, 0, 0, 0, 1,
2, 255, 255, 31, 0, 0, 2, 0, 0, 0, 128, 0, 0, 15, 176,
31, 0, 0, 2, 0, 0, 0, 128, 1, 0, 3, 176, 31, 0, 0,
2, 0, 0, 0, 144, 0, 8, 15, 160, 66, 0, 0, 3, 0, 0,
15, 128, 1, 0, 228, 176, 0, 8, 228, 160, 5, 0, 0, 3, 0,
0, 15, 128, 0, 0, 228, 128, 0, 0, 228, 176, 1, 0, 0, 2,
0, 8, 15, 128, 0, 0, 228, 128, 255, 255, 0, 0, 83, 72, 68,
82, 148, 0, 0, 0, 64, 0, 0, 0, 37, 0, 0, 0, 90, 0,
0, 3, 0, 96, 16, 0, 0, 0, 0, 0, 88, 24, 0, 4, 0,
112, 16, 0, 0, 0, 0, 0, 85, 85, 0, 0, 98, 16, 0, 3,
242, 16, 16, 0, 1, 0, 0, 0, 98, 16, 0, 3, 50, 16, 16,
0, 2, 0, 0, 0, 101, 0, 0, 3, 242, 32, 16, 0, 0, 0,
0, 0, 104, 0, 0, 2, 1, 0, 0, 0, 69, 0, 0, 9, 242,
0, 16, 0, 0, 0, 0, 0, 70, 16, 16, 0, 2, 0, 0, 0,
70, 126, 16, 0, 0, 0, 0, 0, 0, 96, 16, 0, 0, 0, 0,
0, 56, 0, 0, 7, 242, 32, 16, 0, 0, 0, 0, 0, 70, 14,
16, 0, 0, 0, 0, 0, 70, 30, 16, 0, 1, 0, 0, 0, 62,
0, 0, 1, 83, 84, 65, 84, 116, 0, 0, 0, 3, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 82, 68, 69, 70, 152, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 28, 0, 0,
0, 0, 4, 255, 255, 0, 129, 0, 0, 110, 0, 0, 0, 92, 0,
0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
101, 0, 0, 0, 2, 0, 0, 0, 5, 0, 0, 0, 4, 0, 0,
0, 255, 255, 255, 255, 0, 0, 0, 0, 1, 0, 0, 0, 12, 0,
0, 0, 115, 97, 109, 112, 108, 101, 114, 48, 0, 116, 101, 120, 116,
117, 114, 101, 48, 0, 77, 105, 99, 114, 111, 115, 111, 102, 116, 32,
40, 82, 41, 32, 72, 76, 83, 76, 32, 83, 104, 97, 100, 101, 114,
32, 67, 111, 109, 112, 105, 108, 101, 114, 32, 49, 48, 46, 49, 0,
171, 171, 73, 83, 71, 78, 108, 0, 0, 0, 3, 0, 0, 0, 8,
0, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 92, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0,
0, 0, 15, 15, 0, 0, 98, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 3, 3, 0, 0,
83, 86, 95, 80, 79, 83, 73, 84, 73, 79, 78, 0, 67, 79, 76,
79, 82, 0, 84, 69, 88, 67, 79, 79, 82, 68, 0, 171, 79, 83,
71, 78, 44, 0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 32,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0,
0, 0, 0, 0, 15, 0, 0, 0, 83, 86, 95, 84, 97, 114, 103,
101, 116, 0, 171, 171};
| 74.977444 | 78 | 0.286502 | SleepKiller |
cf7d1141ef88a7242dd538b4f82daa4596954eb6 | 607 | cpp | C++ | 98.validate-binary-search-tree.159689697.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | 98.validate-binary-search-tree.159689697.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | 98.validate-binary-search-tree.159689697.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValid(TreeNode * root, TreeNode * &prev)
{
if(!root)return true;
if(!(isValid(root->left,prev)))return false;
if(prev!=NULL&&prev->val>=root->val)return false;
prev= root;
return isValid(root->right,prev);
}
bool isValidBST(TreeNode* root) {
TreeNode * prev = NULL;
return isValid(root,prev);
}
};
| 23.346154 | 59 | 0.560132 | blossom2017 |
cf7dc474ebd427220acf680c83be738994184d17 | 3,920 | cpp | C++ | hi_dsp_library/dywapitchtrack/PitchDetection.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_dsp_library/dywapitchtrack/PitchDetection.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_dsp_library/dywapitchtrack/PitchDetection.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | /* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HISE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licenses for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licensing:
*
* http://www.hise.audio/
*
* HISE is based on the JUCE library,
* which must be separately licensed for closed source applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
namespace hise { using namespace juce;
double PitchDetection::detectPitch(float* fullData, int numSamples, double sampleRate)
{
dywapitchtracker tracker;
dywapitch_inittracking(&tracker);
auto numPerCheck = dywapitch_neededsamplecount((int)(50.0 * (44100.0 / sampleRate)));
Array<double> pitchResults;
int startSample = 0;
while ((startSample + numPerCheck) < numSamples)
{
const double pitchResult = dywapitch_computepitch(&tracker, fullData, startSample, numPerCheck);
auto thisPitch = pitchResult * (sampleRate / 44100.0);
pitchResults.add(thisPitch);
startSample += numPerCheck / 2;
}
if (!pitchResults.isEmpty())
{
pitchResults.sort();
return pitchResults[pitchResults.size() / 2];
}
return 0.0;
}
double PitchDetection::detectPitch(const File &fileToScan, AudioSampleBuffer &workingBuffer, double sampleRate)
{
const int numSamplesPerDetection = workingBuffer.getNumSamples();
AudioFormatManager afm;
afm.registerBasicFormats();
ScopedPointer<AudioFormatReader> afr = afm.createReaderFor(std::unique_ptr<InputStream>(new FileInputStream(File(fileToScan))));
int64 startSample = 0;
Array<double> pitchResults;
while (startSample + numSamplesPerDetection < afr->lengthInSamples)
{
afr->read(&workingBuffer, 0, workingBuffer.getNumSamples(), startSample, true, true);
auto thisPitch = detectPitch(workingBuffer, 0, numSamplesPerDetection, sampleRate);
pitchResults.add(thisPitch);
startSample += numSamplesPerDetection / 2;
}
if (pitchResults.size() > 0)
{
return pitchResults[pitchResults.size() / 2];
}
return 0.0;
}
double PitchDetection::detectPitch(const AudioSampleBuffer &buffer, int startSample, int numSamples, double sampleRate)
{
Array<DywaFloat> doubleSamples;
doubleSamples.ensureStorageAllocated(numSamples);
for (int i = 0; i < numSamples; i++)
{
if (buffer.getNumChannels() == 2)
{
const double value = (double)(buffer.getSample(0, startSample + i) + buffer.getSample(1, startSample + i)) / 2.0;
doubleSamples.set(i, value);
}
else
{
const double value = (double)(buffer.getSample(0, startSample + i));
doubleSamples.set(i, value);
}
}
dywapitchtracker tracker;
dywapitch_inittracking(&tracker);
const double pitchResult = dywapitch_computepitch(&tracker, doubleSamples.getRawDataPointer(), 0, numSamples);
return pitchResult * (sampleRate / 44100.0);
}
int PitchDetection::getNumSamplesNeeded(double sampleRate)
{
return getNumSamplesNeeded(sampleRate, 50.0);
}
int PitchDetection::getNumSamplesNeeded(double sampleRate, double minFrequencyToAnalyse)
{
return dywapitch_neededsamplecount((int)(minFrequencyToAnalyse * (44100.0 / sampleRate)));
}
} // namespace hise
| 28.405797 | 129 | 0.713265 | Matt-Dub |
cf7fa47cfadeb082783b387895eac6395ed54bac | 5,121 | cpp | C++ | tab/tools/tab_com.cpp | constcut/mtherapp | 20b8e32361ef492d5b7cb4ff150f0956e952fdef | [
"MIT"
] | 2 | 2022-03-04T17:54:48.000Z | 2022-03-28T06:20:31.000Z | tab/tools/tab_com.cpp | constcut/aurals | bb00fac92a3a919867fe2e482c37fc0abe5e6984 | [
"MIT"
] | null | null | null | tab/tools/tab_com.cpp | constcut/aurals | bb00fac92a3a919867fe2e482c37fc0abe5e6984 | [
"MIT"
] | null | null | null | #include "tab/Tab.hpp"
#include "midi/MidiFile.hpp"
#include "GmyFile.hpp"
#include "TabLoader.hpp"
#include "GtpFiles.hpp"
#include <fstream>
#include <QDebug>
using namespace aurals;
//TODO prepare undo operations
//They have to be for all possible commands
void Tab::setSignsTillEnd(size_t num, size_t denom) {
_macroCommands.push_back(TwoIntCommand<TabCommand>{TabCommand::SetSignTillEnd, num, denom});
for (size_t trackId = 0; trackId < this->size(); ++trackId)
for (size_t i = _currentBar; i < this->at(trackId)->size(); ++i){
this->at(trackId)->at(i)->setSignDenum(denom);
this->at(trackId)->at(i)->setSignNum(num);
qDebug() << "Changing bar " << i << " on " << num << " " << denom;
}
}
void Tab::moveCursorInTrackRight() {
if (_displayBar < at(0)->size() - 1)
++_displayBar;
}
void Tab::moveCursorInTrackLeft() {
if (_displayBar > 0)
--_displayBar;
}
void Tab::changeTrackVolume(size_t newVol) {
_macroCommands.push_back(IntCommand<TabCommand>{TabCommand::Volume, newVol});
at(_currentTrack)->setVolume(newVol);
}
void Tab::changeTrackName(std::string newName) {
_macroCommands.push_back(StringCommand<TabCommand>{TabCommand::Name, newName});
at(_currentTrack)->setName(newName);
}
void Tab::changeTrackInstrument(size_t val) {
_macroCommands.push_back(IntCommand<TabCommand>{TabCommand::Instument, val});
at(_currentTrack)->setInstrument(val);
}
void Tab::changeTrackPanoram(size_t val) {
_macroCommands.push_back(IntCommand<TabCommand>{TabCommand::Panoram, val});
at(_currentTrack)->setPan(val);
}
void Tab::createNewTrack() {
Tab* pTab = this;
auto track = std::make_unique<Track>();
track->setParent(pTab);
std::string iName("NewInstrument");
track->setName(iName);
track->setInstrument(25);
track->setVolume(15);
track->setDrums(false);
track->setPan(8); //center now
auto& tuning = track->getTuningRef();
tuning.setStringsAmount(6);
tuning.setTune(0, 64);
tuning.setTune(1, 59);
tuning.setTune(2, 55);
tuning.setTune(3, 50);
tuning.setTune(4, 45);
tuning.setTune(5, 40);
if (pTab->size()) {
for (size_t barI=0; barI < pTab->at(0)->size(); ++barI) {
auto bar = std::make_unique<Bar>();
bar->flush();
bar->setSignDenum(4); bar->setSignNum(4); //Подумать над механизмами, разные размеры только при полиритмии нужны
bar->setRepeat(0);
auto beat = std::make_unique<Beat>();
beat->setPause(true);
beat->setDotted(0);
beat->setDuration(3);
beat->setDurationDetail(0);
bar->push_back(std::move(beat));
track->push_back(std::move(bar));
}
}
else {
auto bar = std::make_unique<Bar>();
bar->flush();
bar->setSignDenum(4); bar->setSignNum(4);
bar->setRepeat(0);
auto beat = std::make_unique<Beat>();
beat->setPause(true);
beat->setDotted(0);
beat->setDuration(3);
beat->setDurationDetail(0);
bar->push_back(std::move(beat));
track->push_back(std::move(bar));
}
pTab->push_back(std::move(track));
pTab->connectTracks();
}
void Tab::midiPause() {
if (_isPlaying == false) {
//STARTMIDI
_isPlaying = true;
}
else {
//MidiEngine::stopDefaultFile();
_isPlaying = false;
}
}
void Tab::setMarker(std::string text) {
auto& fromFirstTrack = at(0)->at(_currentBar);
fromFirstTrack->setMarker(text,0);
}
void Tab::openReprise() {
auto& firstTrackBar = this->at(0)->at(_currentBar);
std::uint8_t repeat = firstTrackBar->getRepeat();
std::uint8_t repeatOpens = repeat & 1;
std::uint8_t repeatCloses = repeat & 2;
if (repeatOpens){
firstTrackBar->setRepeat(0); //flush
firstTrackBar->setRepeat(repeatCloses);
}
else
firstTrackBar->setRepeat(1);
}
void Tab::closeReprise(size_t count) {
_macroCommands.push_back(IntCommand<TabCommand>{TabCommand::CloseReprise, count});
auto& firstTrackBar = this->at(0)->at(_currentBar);
std::uint8_t repeat = firstTrackBar->getRepeat();
std::uint8_t repeatOpens = repeat & 1;
std::uint8_t repeatCloses = repeat & 2;
if (repeatCloses) {
firstTrackBar->setRepeat(0);
firstTrackBar->setRepeat(repeatOpens);
}
else {
if (count)
firstTrackBar->setRepeat(2, count);
}
}
void Tab::gotoBar(size_t pos) {
_macroCommands.push_back(IntCommand<TabCommand>{TabCommand::GotoBar, pos});
_currentBar = pos;
_displayBar = pos;
}
void Tab::saveAs(std::string filename) {
_macroCommands.push_back(StringCommand<TabCommand>{TabCommand::SaveAs, filename});
std::ofstream file(filename);
GmyFile gmyFile;
gmyFile.saveToFile(file, this);
file.close();
}
void Tab::onTabCommand(TabCommand command) {
_macroCommands.push_back(command);
if (_handlers.count(command))
(this->*_handlers.at(command))();
}
| 25.605 | 124 | 0.629369 | constcut |
cf869f7a2b62a398c965eb211f3d2ccc82f9018e | 1,012 | cpp | C++ | Week 4/Week 4 Sample Programs/Pr7-1.cpp | sugamkarki/NAMI-Year-II-Term-I-Software_Engineering | 39182816b670dcb75ec322e24b346a4cfeb80be0 | [
"Apache-2.0"
] | null | null | null | Week 4/Week 4 Sample Programs/Pr7-1.cpp | sugamkarki/NAMI-Year-II-Term-I-Software_Engineering | 39182816b670dcb75ec322e24b346a4cfeb80be0 | [
"Apache-2.0"
] | null | null | null | Week 4/Week 4 Sample Programs/Pr7-1.cpp | sugamkarki/NAMI-Year-II-Term-I-Software_Engineering | 39182816b670dcb75ec322e24b346a4cfeb80be0 | [
"Apache-2.0"
] | null | null | null | /**
* @file Pr7-1.cpp
* @author your name (you@domain.com)
* @brief
* @version 0.1
* @date 2020-12-14
*
* @copyright Copyright (c) 2020
*
*/
#include <iostream>
/**
* @brief
*
*/
using namespace std;
int main()
{
/**
* @brief
*
*/
const int NUM_EMPLOYEES = 6;
int hours[NUM_EMPLOYEES];
// Get the hours worked by each employee.
/**
* @brief
*
*/
cout << "Enter the hours worked by "
<< NUM_EMPLOYEES << " employees: ";
cin >> hours[0];
cin >> hours[1];
cin >> hours[2];
cin >> hours[3];
cin >> hours[4];
cin >> hours[5];
/**
* @brief
*
*/
// Display the values in the array.
cout << "The hours you entered are:";
cout << " " << hours[0];
cout << " " << hours[1];
cout << " " << hours[2];
cout << " " << hours[3];
cout << " " << hours[4];
cout << " " << hours[5] << endl;
/**
* @brief
*
*/
return 0;
} | 17.152542 | 45 | 0.4417 | sugamkarki |
cf89a29bc26a7caa9493f3cd67ef36d25d5eecd7 | 4,419 | hh | C++ | include/upnpdevice.hh | vbtdung/h-box | 9d39aef2adee5384d556a4dcf991d6af262ca92e | [
"MIT"
] | 1 | 2018-09-16T06:13:12.000Z | 2018-09-16T06:13:12.000Z | include/upnpdevice.hh | vbtdung/h-box | 9d39aef2adee5384d556a4dcf991d6af262ca92e | [
"MIT"
] | null | null | null | include/upnpdevice.hh | vbtdung/h-box | 9d39aef2adee5384d556a4dcf991d6af262ca92e | [
"MIT"
] | null | null | null | /*
Copyright (c) 2010-2012 Aalto University
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 UPNPDEVICE_HH
#define UPNPDEVICE_HH
#include <string>
#include <list>
#include "proxyserver.hh"
using namespace std;
/**
* @class upnp_service
* @brief A data structure to represent an UPnP service.
* @author Vu Ba Tien Dung
*
*/
class upnp_service {
private:
string serviceDescription;
string serviceName;
public:
/**
* Constructor of upnp_service class
* @param serviceDescription this is the service's description XML string
*
*/
upnp_service(const string& serviceDescription) : serviceDescription(serviceDescription) {
serviceName = "";
}
/**
* Constructor of upnp_service class
* @param serviceDescription this is the service's description XML string
*
*/
upnp_service(const string& serviceName, const string& serviceDescription) : serviceName(serviceName), serviceDescription(serviceDescription) {
}
// getters and setters
string getServiceName() const { return serviceName; }
string getServiceDescription() const { return serviceDescription; }
};
/**
* @class upnp_device
* @brief UPnP device data structure.
* @author Dung
*
*/
class upnp_device {
private:
string STATE;
string deviceName;
string deviceDescription;
list<upnp_service> upnpServices;
int remotePort;
int localPort;
int rewritePort;
string ipAddress;
bool isMediaServer;
tcp_proxy_server* server;
public:
/**
* Constructor of upnp_device class
* @param deviceDescription this is the device's description XML string
*
*/
upnp_device(const string& deviceDescription) : deviceDescription(deviceDescription) {
deviceName = "";
isMediaServer = false;
STATE = "INIT";
remotePort = 0;
localPort = 0;
server = NULL;
}
~upnp_device() {
if (server) delete server;
}
// getters and setters
string getState() { return STATE; }
void setState(const string& STATE) { this->STATE = STATE; }
string getIpAddress() { return ipAddress; }
void setIpAddress(string ipAddress) { this->ipAddress = ipAddress; }
int getRemotePort() { return remotePort; }
void setRemotePort(int remotePort) { this->remotePort = remotePort; }
int getLocalPort() { return localPort; }
void setLocalPort(int localPort) { this->localPort = localPort; }
bool getMediaServer() { return isMediaServer; }
void setMediaServer(bool isMediaServer) { this->isMediaServer = isMediaServer; }
tcp_proxy_server* getServer() { return server; }
void setServer(tcp_proxy_server* server) { this->server = server; }
void setDeviceName(string name) { this->deviceName = name; }
string getDeviceName() { return deviceName; }
void setDeviceDescription(string description) { this->deviceDescription = description; }
string getDeviceDescription() { return deviceDescription; }
list<upnp_service> getServiceList() { return upnpServices; }
void start() {
STATE = "READY";
}
void addUpnpService(const upnp_service& service) {
for (list<upnp_service>::iterator it = upnpServices.begin(); it != upnpServices.end(); it++)
if (it->getServiceName() == service.getServiceName())
return;
upnpServices.insert(upnpServices.begin(), service);
}
void removeUpnpService(const string serviceName) {
list<upnp_service>::iterator it;
for (it = upnpServices.begin(); it != upnpServices.end(); it++)
if ((*it).getServiceName() == serviceName)
break;
upnpServices.erase(it);
}
};
#endif
| 29.657718 | 143 | 0.742476 | vbtdung |
cf89b08d967eeaa4b97f2f80785b3611011af143 | 1,567 | cpp | C++ | module_05/ex03/ShrubberyCreationForm.cpp | paulahemsi/piscine_cpp | f98feefd8e70308f77442f9b4cb64758676349a7 | [
"MIT"
] | 4 | 2021-12-14T18:02:53.000Z | 2022-03-24T01:12:38.000Z | module_05/ex02/ShrubberyCreationForm.cpp | paulahemsi/piscine_cpp | f98feefd8e70308f77442f9b4cb64758676349a7 | [
"MIT"
] | null | null | null | module_05/ex02/ShrubberyCreationForm.cpp | paulahemsi/piscine_cpp | f98feefd8e70308f77442f9b4cb64758676349a7 | [
"MIT"
] | 3 | 2021-11-01T00:34:50.000Z | 2022-01-29T19:57:30.000Z |
#include "ShrubberyCreationForm.hpp"
#include <iostream>
#include <fstream>
# define V_CYAN "\e[0;38;5;44m"
# define RESET "\e[0m"
ShrubberyCreationForm::ShrubberyCreationForm(std::string target) : AForm("ShrubberyCreationForm", 145, 137)
{
this->setTarget(target);
std::cout << *this << std::endl;
return ;
}
void ShrubberyCreationForm::_createFile(void)const
{
std::string line;
std::string name = this->getTarget() + "_shrubbery";
std::ofstream outputFile(name.c_str());
std::ifstream inputFile("trees.txt");
if(inputFile && outputFile)
{
while(getline(inputFile, line))
outputFile << line << std::endl;
std::cout << V_CYAN << name << " was sussefuly created and filled with beautifull ASCII trees, go take a look!" << RESET << std::endl;
}
else
std::cout << V_CYAN << "Error creating file" << RESET << std::endl;
outputFile.close();
inputFile.close();
}
bool ShrubberyCreationForm::execute(Bureaucrat const &executor) const
{
if (AForm::execute(executor))
{
this->_createFile();
return (true);
}
return (false);
}
std::ostream &operator<<(std::ostream &outputFile, ShrubberyCreationForm const &i)
{
outputFile << V_CYAN
<< i.getName()
<< std::endl
<< "Grade to sign: "
<< i.getGradeToSign()
<< std::endl
<< "Grade to execute: "
<< i.getGradeToExecute()
<< std::endl
<< "Target: "
<< i.getTarget()
<< std::endl
<< "Is signed: ";
if (i.getIsSigned())
outputFile << "Yes." << RESET << std::endl;
else
outputFile << "No." << RESET << std::endl;
return (outputFile);
}
| 23.742424 | 136 | 0.64582 | paulahemsi |
cf9043d6181db83caf01cf8750abc169b60d67b9 | 1,983 | cpp | C++ | update-client-hub/modules/pal-blockdevice/source/arm_uc_pal_blockdevice_mbed.cpp | linlingao/mbed-cloud-client | 13e0cef7f9508c10d50f3beb049eafea2af6f17b | [
"Apache-2.0"
] | null | null | null | update-client-hub/modules/pal-blockdevice/source/arm_uc_pal_blockdevice_mbed.cpp | linlingao/mbed-cloud-client | 13e0cef7f9508c10d50f3beb049eafea2af6f17b | [
"Apache-2.0"
] | null | null | null | update-client-hub/modules/pal-blockdevice/source/arm_uc_pal_blockdevice_mbed.cpp | linlingao/mbed-cloud-client | 13e0cef7f9508c10d50f3beb049eafea2af6f17b | [
"Apache-2.0"
] | null | null | null | //----------------------------------------------------------------------------
// The confidential and proprietary information contained in this file may
// only be used by a person authorised under and to the extent permitted
// by a subsisting licensing agreement from ARM Limited or its affiliates.
//
// (C) COPYRIGHT 2017 ARM Limited or its affiliates.
// ALL RIGHTS RESERVED
//
// This entire notice must be reproduced on all copies of this file
// and copies of this file may only be made by a person if such person is
// permitted to do so under the terms of a subsisting license agreement
// from ARM Limited or its affiliates.
//----------------------------------------------------------------------------
#include "arm_uc_config.h"
#if defined(ARM_UC_FEATURE_PAL_BLOCKDEVICE) && (ARM_UC_FEATURE_PAL_BLOCKDEVICE == 1)
#if defined(TARGET_LIKE_MBED)
#include "update-client-pal-blockdevice/arm_uc_pal_blockdevice_platform.h"
#include "mbed.h"
extern BlockDevice *arm_uc_blockdevice;
int32_t arm_uc_blockdevice_init(void)
{
return arm_uc_blockdevice->init();
}
uint32_t arm_uc_blockdevice_get_program_size(void)
{
return arm_uc_blockdevice->get_program_size();
}
uint32_t arm_uc_blockdevice_get_erase_size(void)
{
return arm_uc_blockdevice->get_erase_size();
}
int32_t arm_uc_blockdevice_erase(uint64_t address, uint64_t size)
{
return arm_uc_blockdevice->erase(address, size);
}
int32_t arm_uc_blockdevice_program(const uint8_t *buffer,
uint64_t address,
uint32_t size)
{
return arm_uc_blockdevice->program(buffer, address, size);
}
int32_t arm_uc_blockdevice_read(uint8_t *buffer,
uint64_t address,
uint32_t size)
{
return arm_uc_blockdevice->read(buffer, address, size);
}
#endif /* #if defined(TARGET_LIKE_MBED) */
#endif /* defined(ARM_UC_FEATURE_PAL_BLOCKDEVICE) */
| 33.05 | 84 | 0.655572 | linlingao |
cf9c90ec735a4cfa1930fc220d98f50ac5d81adb | 1,062 | cpp | C++ | src/XML/XMLConfigMarkISection.cpp | dmalysiak/Lazarus | 925d92843e311d2cd5afd437766563d0d5ab9052 | [
"Apache-2.0"
] | 1 | 2019-04-29T05:31:32.000Z | 2019-04-29T05:31:32.000Z | src/XML/XMLConfigMarkISection.cpp | dmalysiak/Lazarus | 925d92843e311d2cd5afd437766563d0d5ab9052 | [
"Apache-2.0"
] | null | null | null | src/XML/XMLConfigMarkISection.cpp | dmalysiak/Lazarus | 925d92843e311d2cd5afd437766563d0d5ab9052 | [
"Apache-2.0"
] | null | null | null | /*
* XMLConfigMarkISection.cpp
*
* Created on: Feb 11, 2014
* Author: clustro
*/
#include "XMLConfigMarkISection.h"
#include <stdexcept>
namespace Lazarus {
XMLConfigMarkISection::XMLConfigMarkISection(const std::string& name)
{
m_name = name;
}
XMLConfigMarkISection::~XMLConfigMarkISection()
{
for(auto it : m_parameter_map)
delete it.second;
}
void XMLConfigMarkISection::addParameter(XMLConfigParameter* param)
{
m_params.appendLast(param);
//register the parameter in the lookup map
m_parameter_map[param->getName()]=param;
}
XMLConfigParameter* XMLConfigMarkISection::getParameter(const std::string& name)
{
XMLConfigParameter* r = NULL;
try
{
r = m_parameter_map.at(name);
}
catch(std::out_of_range e)
{
printf("ERROR: Parameter '%s' has not been found in section map\n",name.c_str());
throw;
}
return r;
}
Lazarus::FastNCSList<XMLConfigParameter*>* XMLConfigMarkISection::getParameters()
{
return &m_params;
}
const std::string& XMLConfigMarkISection::getName()
{
return m_name;
}
} /* namespace Lazarus */
| 17.409836 | 83 | 0.731638 | dmalysiak |
cfa513fb403af0c1b44258b41759fa11b473937c | 11,545 | cpp | C++ | uav_interface/OLED.cpp | NHLStenden-CVDS/TwirreArduino | 2832c6d7fa0f46e41bac3bf4124b24446f8dcde8 | [
"MIT"
] | null | null | null | uav_interface/OLED.cpp | NHLStenden-CVDS/TwirreArduino | 2832c6d7fa0f46e41bac3bf4124b24446f8dcde8 | [
"MIT"
] | null | null | null | uav_interface/OLED.cpp | NHLStenden-CVDS/TwirreArduino | 2832c6d7fa0f46e41bac3bf4124b24446f8dcde8 | [
"MIT"
] | null | null | null | /*
* Twirre: architecture for autonomous UAVs using interchangeable commodity components
*
* Copyright© 2017 Centre of expertise in Computer Vision & Data Science, NHL Stenden University of applied sciences
*
* 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 <Wire.h>
#include "OLED.h"
#include "Arduino.h"
#ifndef _BV
#define _BV(bit) (1 << (bit))
#endif
#define TOTALFONTS 2
#include "font/font5x7.h"
#include "font/font8x16.h"
// Add the font name as declared in the header file. Remove as many as possible to conserve FLASH memory.
const unsigned char *OLED::fontsPointer[] =
{ font5x7, font8x16 };
static uint8_t screenmemory[] =
{
//SparkFun Electronics LOGO
// ROW0, BYTE0 to BYTE63
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// ROW1, BYTE64 to BYTE127
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// ROW2, BYTE128 to BYTE191
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// ROW3, BYTE192 to BYTE255
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// ROW4, BYTE256 to BYTE319
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// ROW5, BYTE320 to BYTE383
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };
OLED::OLED(const char* name) :
Device(name, "OLED Display")
{
//_printstring = reinterpret_cast<uint8_t*>(malloc(sizeof(uint8_t) * (_printstringLength + 1)));
_AddVariable("cursorx", &_cursorX);
_AddVariable("cursory", &_cursorY);
_AddVariable("font", &_font);
_AddVariable("printchar", &_printchar);
_AddVariable("printflag", &_printflag);
_AddVariable("clearflag", &_clearflag);
//_AddVariable("printstring", _printstring, &_printstringLength);
pinMode(PIN_RESET, OUTPUT); // Set RST pin as OUTPUT
digitalWrite(PIN_RESET, HIGH); // Initially set RST HIGH
delay(5); // VDD (3.3V) goes high at start, lets just chill for 5 ms
digitalWrite(PIN_RESET, LOW); // Bring RST low, reset the display
delay(10); // wait 10ms
digitalWrite(PIN_RESET, HIGH); // Set RST HIGH, bring out of reset
setColor(WHITE);
setDrawMode(NORM);
// Display Init sequence for 64x48 OLED module
command(DISPLAYOFF); // 0xAE
command(SETDISPLAYCLOCKDIV); // 0xD5
command(0x80); // the suggested ratio 0x80
command(SETMULTIPLEX); // 0xA8
command(0x2F);
command(SETDISPLAYOFFSET); // 0xD3
command(0x0); // no offset
command(SETSTARTLINE | 0x0); // line #0
command(CHARGEPUMP); // enable charge pump
command(0x14);
command(NORMALDISPLAY); // 0xA6
command(DISPLAYALLONRESUME); // 0xA4
command(SEGREMAP | 0x1);
command(COMSCANDEC);
command(SETCOMPINS); // 0xDA
command(0x12);
command(SETCONTRAST); // 0x81
command(0x8F);
command(SETPRECHARGE); // 0xd9
command(0xF1);
command(SETVCOMDESELECT); // 0xDB
command(0x40);
command(DISPLAYON); //--turn on oled panel
clear(ALL); // Erase hardware memory inside the OLED controller to avoid random data in memory.
/*
for(int i = 0; i < 40 ; i++){
pixel(i,i);
pixel(40-i,i);
}
*/
setCursor(1, 2);
setFontType(1);
print("Twirre V2");
display();
}
void OLED::ValuesChanged()
{
//setFontType(0);
//setCursor(0,0);
//print(String("") + _printstringLength);
//display();
if (_clearflag)
{
clear(PAGE);
_clearflag = 0;
}
if (_printflag)
{
//_printstring[_printstringLength] = 0;
setFontType(_font);
if (_cursorX < 255 && _cursorY < 255)
{
setCursor(_cursorX, _cursorY);
_cursorX = 255;
_cursorY = 255;
}
write(_printchar);
//print(reinterpret_cast<const char*>(_printstring));
_printflag = 0;
display();
}
}
void OLED::command(uint8_t c)
{
Wire1.beginTransmission(I2CADDRESS);
Wire1.write(0x00);
Wire1.write(c);
Wire1.endTransmission();
}
void OLED::data(uint8_t c)
{
Wire1.beginTransmission(I2CADDRESS);
Wire1.write(0x40);
Wire1.write(c);
Wire1.endTransmission();
}
void OLED::setPageAddress(uint8_t add)
{
add = 0xb0 | add;
command(add);
return;
}
void OLED::setColumnAddress(uint8_t add)
{
command((0x10 | (add >> 4)) + 0x02);
command((0x0f & add));
return;
}
void OLED::clear(uint8_t mode)
{
// uint8_t page=6, col=0x40;
if (mode == ALL)
{
for (int i = 0; i < 8; i++)
{
setPageAddress(i);
setColumnAddress(0);
for (int j = 0; j < 0x80; j++)
{
data(0);
}
}
}
else
{
memset(screenmemory, 0, 384); // (64 x 48) / 8 = 384
//display();
}
}
void OLED::setCursor(uint8_t x, uint8_t y)
{
cursorX = x;
cursorY = y;
}
void OLED::pixel(uint8_t x, uint8_t y)
{
pixel(x, y, foreColor, drawMode);
}
void OLED::pixel(uint8_t x, uint8_t y, uint8_t color, uint8_t mode)
{
if ((x < 0) || (x >= LCDWIDTH) || (y < 0) || (y >= LCDHEIGHT)) return;
if (mode == XOR)
{
if (color == WHITE) screenmemory[x + (y / 8) * LCDWIDTH] ^= _BV((y & 0x7));
}
else
{
if (color == WHITE)
screenmemory[x + (y / 8) * LCDWIDTH] |= _BV((y & 0x7));
else
screenmemory[x + (y / 8) * LCDWIDTH] &= ~_BV((y & 0x7));
}
}
void OLED::display(void)
{
uint8_t i, j;
for (i = 0; i < 6; i++)
{
setPageAddress(i);
setColumnAddress(0);
for (j = 0; j < 0x40; j++)
{
data(screenmemory[i * 0x40 + j]);
}
}
}
void OLED::setColor(uint8_t color)
{
foreColor = color;
}
/** \brief Set draw mode.
Set current draw mode with NORM or XOR.
*/
void OLED::setDrawMode(uint8_t mode)
{
drawMode = mode;
}
uint8_t OLED::setFontType(uint8_t type)
{
if ((type >= TOTALFONTS) || (type < 0)) return false;
fontType = type;
fontWidth = pgm_read_byte(fontsPointer[fontType] + 0);
fontHeight = pgm_read_byte(fontsPointer[fontType] + 1);
fontStartChar = pgm_read_byte(fontsPointer[fontType] + 2);
fontTotalChar = pgm_read_byte(fontsPointer[fontType] + 3);
fontMapWidth = (pgm_read_byte(fontsPointer[fontType]+4) * 100) + pgm_read_byte(fontsPointer[fontType] + 5); // two bytes values into integer 16
return true;
}
size_t OLED::write(uint8_t c)
{
if (c == '\n')
{
cursorY += fontHeight;
cursorX = 0;
}
else if (c == '\r')
{
// skip
}
else
{
drawChar(cursorX, cursorY, c, foreColor, drawMode);
cursorX += fontWidth + 1;
if ((cursorX > (LCDWIDTH - fontWidth)))
{
cursorY += fontHeight;
cursorX = 0;
}
}
return 1;
}
void OLED::drawChar(uint8_t x, uint8_t y, uint8_t c, uint8_t color, uint8_t mode)
{
// TODO - New routine to take font of any height, at the moment limited to font height in multiple of 8 pixels
uint8_t rowsToDraw, row, tempC;
uint8_t i, j, temp;
uint16_t charPerBitmapRow, charColPositionOnBitmap, charRowPositionOnBitmap, charBitmapStartPosition;
if ((c < fontStartChar) || (c > (fontStartChar + fontTotalChar - 1))) // no bitmap for the required c
return;
tempC = c - fontStartChar;
// each row (in datasheet is call page) is 8 bits high, 16 bit high character will have 2 rows to be drawn
rowsToDraw = fontHeight / 8; // 8 is LCD's page size, see SSD1306 datasheet
if (rowsToDraw <= 1) rowsToDraw = 1;
// the following draw function can draw anywhere on the screen, but SLOW pixel by pixel draw
if (rowsToDraw == 1)
{
for (i = 0; i < fontWidth + 1; i++)
{
if (i == fontWidth) // this is done in a weird way because for 5x7 font, there is no margin, this code add a margin after col 5
temp = 0;
else
temp = pgm_read_byte(fontsPointer[fontType]+FONTHEADERSIZE+(tempC*fontWidth)+i);
for (j = 0; j < 8; j++)
{ // 8 is the LCD's page height (see datasheet for explanation)
if (temp & 0x1)
{
pixel(x + i, y + j, color, mode);
}
else
{
pixel(x + i, y + j, !color, mode);
}
temp >>= 1;
}
}
return;
}
// font height over 8 bit
// take character "0" ASCII 48 as example
charPerBitmapRow = fontMapWidth / fontWidth; // 256/8 =32 char per row
charColPositionOnBitmap = tempC % charPerBitmapRow; // =16
charRowPositionOnBitmap = int(tempC / charPerBitmapRow); // =1
charBitmapStartPosition = (charRowPositionOnBitmap * fontMapWidth * (fontHeight / 8)) + (charColPositionOnBitmap * fontWidth);
// each row on LCD is 8 bit height (see datasheet for explanation)
for (row = 0; row < rowsToDraw; row++)
{
for (i = 0; i < fontWidth; i++)
{
temp = pgm_read_byte(fontsPointer[fontType]+FONTHEADERSIZE+(charBitmapStartPosition+i+(row*fontMapWidth)));
for (j = 0; j < 8; j++)
{ // 8 is the LCD's page height (see datasheet for explanation)
if (temp & 0x1)
{
pixel(x + i, y + j + (row * 8), color, mode);
}
else
{
pixel(x + i, y + j + (row * 8), !color, mode);
}
temp >>= 1;
}
}
}
}
| 29.678663 | 463 | 0.661758 | NHLStenden-CVDS |
cfa6559ed374df5ed9d3535040d86d09a4e33776 | 1,810 | hpp | C++ | extlibs/include/Jopnal/Utility/DateTime.hpp | Jopnal/Jopmodel | cfd50b9fd24eaf63497bf5bed883f0b831d9ad65 | [
"Zlib"
] | 2 | 2016-07-16T17:21:10.000Z | 2016-08-09T11:41:33.000Z | extlibs/include/Jopnal/Utility/DateTime.hpp | Jopnal/Jopmodel | cfd50b9fd24eaf63497bf5bed883f0b831d9ad65 | [
"Zlib"
] | null | null | null | extlibs/include/Jopnal/Utility/DateTime.hpp | Jopnal/Jopmodel | cfd50b9fd24eaf63497bf5bed883f0b831d9ad65 | [
"Zlib"
] | null | null | null | // Jopnal Engine C++ Library
// Copyright (c) 2016 Team Jopnal
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgement in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//////////////////////////////////////////////
#ifndef JOP_DATETIME_HPP
#define JOP_DATETIME_HPP
// Headers
#include <Jopnal/Header.hpp>
#include <string>
//////////////////////////////////////////////
namespace jop
{
class JOP_API DateTime
{
public:
struct Date
{
uint16 year;
uint8 month;
uint8 day;
};
struct Time
{
uint8 hour;
uint8 minute;
uint8 second;
};
public:
DateTime();
DateTime& update(const bool date = true, const bool time = true);
const Date& getDate() const;
const Time& getTime() const;
bool operator ==(const DateTime& right) const;
bool operator !=(const DateTime& right) const;
private:
Date m_date;
Time m_time;
};
}
#endif | 24.133333 | 77 | 0.61105 | Jopnal |
cfa6e83d21638c08d9c9441c4e5b89bbed2ebb51 | 302 | cpp | C++ | src/main.cpp | z3t0/Game | cda8dccebd488519d4a018c0d11cccc69e5e5859 | [
"MIT"
] | null | null | null | src/main.cpp | z3t0/Game | cda8dccebd488519d4a018c0d11cccc69e5e5859 | [
"MIT"
] | null | null | null | src/main.cpp | z3t0/Game | cda8dccebd488519d4a018c0d11cccc69e5e5859 | [
"MIT"
] | null | null | null | // Main file
// Copyright (C) Rafi Khan 2016
// Includes
#include "Game.hpp"
#include <iostream>
// Defines
#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600
#define WINDOW_TITLE "Game"
int main() {
Game game (WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE);
game.update();
return 0;
}
| 13.130435 | 58 | 0.688742 | z3t0 |
bbc1bbb95bd10f881dd3d39f332bc8700fff32ce | 3,881 | cpp | C++ | test/unit_test/sql_test.cpp | KaiserLancelot/klib | 5fe789c24dae999ab3512e5882f14a194dd34699 | [
"MIT"
] | 1 | 2022-02-28T12:31:44.000Z | 2022-02-28T12:31:44.000Z | test/unit_test/sql_test.cpp | KaiserLancelot/klib | 5fe789c24dae999ab3512e5882f14a194dd34699 | [
"MIT"
] | null | null | null | test/unit_test/sql_test.cpp | KaiserLancelot/klib | 5fe789c24dae999ab3512e5882f14a194dd34699 | [
"MIT"
] | 1 | 2021-11-06T14:23:21.000Z | 2021-11-06T14:23:21.000Z | #include <cstdint>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include <catch2/catch.hpp>
#include "klib/sql.h"
#include "klib/util.h"
TEST_CASE("sql", "[sql]") {
{
klib::SqlDatabase db("test.db", klib::SqlDatabase::ReadWrite,
"6K4VpQY5&b*WRR^Y");
REQUIRE_NOTHROW(db.transaction());
REQUIRE_NOTHROW(db.drop_table_if_exists("Cars"));
REQUIRE_NOTHROW(db.exec("CREATE TABLE Cars(Name TEXT, Price INT);"));
std::vector<std::string> names = {"Audi", "Mercedes", "Skoda",
"Volvo", "Bentley", "Citroen",
"Hummer", "Volkswagen"};
std::vector<std::int32_t> prices = {52642, 57127, 9000, 29000,
350000, 21000, 41400, 21600};
klib::SqlQuery query(db);
REQUIRE_NOTHROW(
query.prepare("INSERT INTO Cars(Name, Price) VALUES(?, ?);"));
for (std::size_t i = 0; i < 8; ++i) {
REQUIRE_NOTHROW(query.bind(1, names[i]));
REQUIRE_NOTHROW(query.bind(2, prices[i]));
REQUIRE(query.exec() == 1);
}
REQUIRE(db.exec("UPDATE Cars SET Name='aaa' WHERE Price > 50000") == 3);
REQUIRE_NOTHROW(db.commit());
REQUIRE_NOTHROW(db.transaction());
for (std::size_t i = 0; i < 8; ++i) {
REQUIRE_NOTHROW(query.bind(1, names[i]));
REQUIRE_NOTHROW(query.bind(2, prices[i]));
REQUIRE(query.exec() == 1);
}
REQUIRE_NOTHROW(db.rollback());
REQUIRE_NOTHROW(db.vacuum());
REQUIRE(std::filesystem::exists("test.db"));
REQUIRE(db.table_exists("Cars"));
REQUIRE(db.table_line_count("Cars") == 8);
REQUIRE_NOTHROW(query.prepare("SELECT * FROM Cars WHERE Price > ?"));
REQUIRE_NOTHROW(query.bind(1, 50000));
while (query.next()) {
REQUIRE(query.get_column_name(0) == "Name");
REQUIRE(query.get_column_name(1) == "Price");
REQUIRE_NOTHROW(std::cout << query.get_column(0).as_text() << ' ');
REQUIRE_NOTHROW(std::cout << query.get_column(1).as_int32() << '\n');
}
std::cout << '\n';
REQUIRE_NOTHROW(query.prepare("SELECT * FROM Cars"));
while (query.next()) {
REQUIRE_NOTHROW(std::cout << query.get_column(0).as_text() << ' ');
REQUIRE_NOTHROW(std::cout << query.get_column(1).as_int32() << '\n');
}
std::cout << '\n';
while (query.next()) {
REQUIRE_NOTHROW(std::cout << query.get_column(0).as_text() << ' ');
REQUIRE_NOTHROW(std::cout << query.get_column(1).as_int32() << '\n');
}
}
{
klib::SqlDatabase db("test.db", klib::SqlDatabase::ReadWrite,
"6K4VpQY5&b*WRR^Y");
REQUIRE(db.table_exists("Cars"));
REQUIRE(db.table_line_count("Cars") == 8);
klib::SqlQuery query(db);
REQUIRE_NOTHROW(query.prepare("SELECT * FROM Cars"));
std::cout << '\n';
while (query.next()) {
REQUIRE_NOTHROW(std::cout << query.get_column(0).as_text() << ' ');
REQUIRE_NOTHROW(std::cout << query.get_column(1).as_int32() << '\n');
}
}
}
TEST_CASE("blob", "[sql]") {
klib::SqlDatabase db("test2.db", klib::SqlDatabase::ReadWrite, "");
REQUIRE_NOTHROW(db.transaction());
REQUIRE_NOTHROW(db.drop_table_if_exists("BlobTest"));
REQUIRE_NOTHROW(db.exec("CREATE TABLE BlobTest(Data BLOB);"));
REQUIRE(std::filesystem::exists("zlib-v1.2.11.tar.gz"));
std::string blob = klib::read_file("zlib-v1.2.11.tar.gz", true);
klib::SqlQuery query(db);
REQUIRE_NOTHROW(query.prepare("INSERT INTO BlobTest(Data) VALUES(?);"));
REQUIRE_NOTHROW(query.bind(1, std::data(blob), std::size(blob)));
REQUIRE(query.exec() == 1);
REQUIRE_NOTHROW(db.commit());
REQUIRE_NOTHROW(query.prepare("SELECT * FROM BlobTest"));
REQUIRE(query.next());
REQUIRE(query.get_column(0).as_blob() == blob);
REQUIRE_NOTHROW(query.finalize());
REQUIRE_NOTHROW(db.vacuum());
}
| 33.456897 | 76 | 0.605514 | KaiserLancelot |
bbc7b559c1c6530d70446f6bd8bd5d7db83e2534 | 950 | cpp | C++ | LeetCode/100/78.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | LeetCode/100/78.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | LeetCode/100/78.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | // created by Kona @VSCode
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <queue>
#include <vector>
#include <string.h>
#define LOCAL_TEST
typedef long long ll;
using std::cin;
using std::cout;
using std::endl;
using std::map;
using std::queue;
using std::string;
using std::vector;
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> res;
res.reserve(1 << n);
for (int vis = (1 << n) - 1; vis >= 0; --vis) {
vector<int> tmp;
tmp.reserve(10);
for (int i = 0; i < n; ++i) {
if (vis & (1 << i)) tmp.push_back(nums[i]);
}
res.push_back(std::move(tmp));
}
return res;
}
};
int main() {
std::ios_base::sync_with_stdio(false);
#ifdef LOCAL_TEST
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* code */
return 0;
} | 19.791667 | 53 | 0.578947 | K-ona |
bbcab6e5eb97ed4e4c7d6b2bca67ec20f072dc1f | 1,690 | tcc | C++ | ulmblas/level2/hpur2.tcc | sneha0401/ulmBLAS | 2b7665c6abc1784fe4041febd9d12de519ef4f08 | [
"BSD-3-Clause"
] | 95 | 2015-05-14T15:21:44.000Z | 2022-03-17T08:02:08.000Z | ulmblas/level2/hpur2.tcc | sneha0401/ulmBLAS | 2b7665c6abc1784fe4041febd9d12de519ef4f08 | [
"BSD-3-Clause"
] | 4 | 2020-06-25T14:59:49.000Z | 2022-02-16T12:45:00.000Z | ulmblas/level2/hpur2.tcc | sneha0401/ulmBLAS | 2b7665c6abc1784fe4041febd9d12de519ef4f08 | [
"BSD-3-Clause"
] | 40 | 2015-09-14T02:43:43.000Z | 2021-12-26T11:43:36.000Z | #ifndef ULMBLAS_LEVEL2_HPUR2_TCC
#define ULMBLAS_LEVEL2_HPUR2_TCC 1
#include <ulmblas/auxiliary/conjugate.h>
#include <ulmblas/auxiliary/real.h>
#include <ulmblas/level1extensions/axpy2v.h>
#include <ulmblas/level2/hpur2.h>
namespace ulmBLAS {
template <typename IndexType, typename Alpha, typename TX, typename TY,
typename TA>
void
hpur2(IndexType n,
bool conj,
const Alpha &alpha,
const TX *x,
IndexType incX,
const TY *y,
IndexType incY,
TA *A)
{
if (n==0 || alpha==Alpha(0)) {
return;
}
if (!conj) {
for (IndexType j=0; j<n; ++j) {
axpy2v(j+1,
alpha*conjugate(y[j*incY]),
conjugate(alpha*x[j*incX]),
x, incX,
y, incY,
A, IndexType(1));
A[j] = real(A[j]);
A += j+1;
}
} else {
for (IndexType j=0; j<n; ++j) {
acxpy(j+1,
conjugate(alpha)*y[j*incY],
x, incX,
A, IndexType(1));
acxpy(j+1,
alpha*x[j*incX],
y, incY,
A, IndexType(1));
A[j] = real(A[j]);
A += j+1;
}
}
}
template <typename IndexType, typename Alpha, typename TX, typename TY,
typename TA>
void
hpur2(IndexType n,
const Alpha &alpha,
const TX *x,
IndexType incX,
const TY *y,
IndexType incY,
TA *A)
{
hpur2(n, false, alpha, x, incX, y, incY, A);
}
} // namespace ulmBLAS
#endif // ULMBLAS_LEVEL2_HPUR2_TCC
| 23.802817 | 71 | 0.478107 | sneha0401 |
bbcb7f036369bf66a496a344ac3d96e25f6c73be | 6,964 | cpp | C++ | common/Uart.cpp | loliot/lot-API | cec96c68450c1f3730480a8c142dc98e0fd35f17 | [
"MIT"
] | 2 | 2021-03-07T22:54:42.000Z | 2021-07-07T23:56:10.000Z | common/Uart.cpp | loliot/lot-API | cec96c68450c1f3730480a8c142dc98e0fd35f17 | [
"MIT"
] | 16 | 2019-10-10T06:37:59.000Z | 2020-01-29T09:56:06.000Z | common/Uart.cpp | loliot/lot-API | cec96c68450c1f3730480a8c142dc98e0fd35f17 | [
"MIT"
] | 20 | 2019-10-08T11:16:11.000Z | 2020-01-05T13:26:45.000Z | /*
* MIT License
* Copyright (c) 2019-2020 Hyeonki Hong <hhk7734@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "../Uart.h"
#include "../lot.h"
#include <stdio.h> // sprintf()
#include <unistd.h> // write(), close(), usleep()
#include <string.h> // strcpy(), strlen()
#include <fcntl.h> // open(), fcntl()
#include <termios.h>
#include <sys/ioctl.h> // ioctl()
#include <errno.h> // errno
#include <stdexcept>
static inline ssize_t unistd_write( int fd, const void *buf, size_t n )
{
return write( fd, buf, n );
}
namespace lot
{
Uart::Uart( uint16_t bus_num )
: m_fd( -1 )
{
sprintf( m_device, "%s%d", "/dev/ttyS", bus_num );
init();
}
Uart::Uart( const char *device )
: m_fd( -1 )
{
if( device != NULL )
{
strcpy( m_device, device );
}
init();
}
Uart::~Uart()
{
close( m_fd );
}
void Uart::baudrate( uint32_t baud_rate )
{
struct termios options;
speed_t baud_rate_ = B0;
// clang-format off
switch( baud_rate )
{
case 50: baud_rate_ = B50; break;
case 75: baud_rate_ = B75; break;
case 110: baud_rate_ = B110; break;
case 134: baud_rate_ = B134; break;
case 150: baud_rate_ = B150; break;
case 200: baud_rate_ = B200; break;
case 300: baud_rate_ = B300; break;
case 600: baud_rate_ = B600; break;
case 1200: baud_rate_ = B1200; break;
case 1800: baud_rate_ = B1800; break;
case 2400: baud_rate_ = B2400; break;
case 4800: baud_rate_ = B4800; break;
case 9600: baud_rate_ = B9600; break;
case 19200: baud_rate_ = B19200; break;
case 38400: baud_rate_ = B38400; break;
case 57600: baud_rate_ = B57600; break;
case 115200: baud_rate_ = B115200; break;
case 230400: baud_rate_ = B230400; break;
case 460800: baud_rate_ = B460800; break;
case 500000: baud_rate_ = B500000; break;
case 576000: baud_rate_ = B576000; break;
case 921600: baud_rate_ = B921600; break;
case 1000000: baud_rate_ = B1000000; break;
case 1152000: baud_rate_ = B1152000; break;
case 1500000: baud_rate_ = B1500000; break;
case 2000000: baud_rate_ = B2000000; break;
case 2500000: baud_rate_ = B2500000; break;
case 3000000: baud_rate_ = B3000000; break;
case 3500000: baud_rate_ = B3500000; break;
case 4000000: baud_rate_ = B4000000; break;
default:
baud_rate_ = B115200;
Log::warning( "The baudrate is invalid. It will set default buadrate(115200).\r\n" );
break;
};
// clang-format on
tcgetattr( m_fd, &options );
cfsetispeed( &options, baud_rate_ );
cfsetospeed( &options, baud_rate_ );
tcsetattr( m_fd, TCSANOW, &options );
usleep( 10000 );
}
void Uart::mode( UartMode uart_mode )
{
struct termios options;
tcgetattr( m_fd, &options );
// Raw level read/write. Non-standard.
cfmakeraw( &options );
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 100; // timeout = 10s
// Ignore Error.
options.c_iflag |= IGNPAR;
// Disable implementation-defined output processing.
options.c_oflag &= ~OPOST;
options.c_cflag |= ( CLOCAL | CREAD );
options.c_cflag &= ~CSIZE;
switch( uart_mode % 4 )
{
case 0:
options.c_cflag |= CS5;
case 1:
options.c_cflag |= CS6;
case 2:
options.c_cflag |= CS7;
case 3:
options.c_cflag |= CS8;
}
switch( static_cast<uint8_t>( uart_mode / 8 ) )
{
case 0:
// None
options.c_cflag &= ~PARENB;
options.c_iflag &= ~INPCK;
break;
case 1:
// Even
options.c_iflag |= INPCK;
options.c_cflag |= PARENB;
options.c_cflag &= ~PARODD;
break;
case 2:
// Odd
options.c_iflag |= INPCK;
options.c_cflag |= PARENB;
options.c_cflag |= PARODD;
break;
case 3:
// Mark
break;
case 4:
// Space
break;
}
switch( static_cast<uint8_t>( uart_mode / 4 ) % 2 )
{
case 0:
options.c_cflag &= ~CSTOPB;
break;
case 1:
options.c_cflag |= CSTOPB;
break;
}
options.c_lflag &= ~( ISIG | ICANON | ECHO | ECHOE );
tcsetattr( m_fd, TCSANOW, &options );
usleep( 10000 );
}
uint16_t Uart::available( void )
{
int result;
if( ioctl( m_fd, FIONREAD, &result ) < 0 )
{
Log::warning( "Failed to read UART RX buffer size.\r\n" );
return 0;
}
return result;
}
void Uart::transmit( uint8_t *buffer, uint16_t size )
{
unistd_write( m_fd, buffer, size );
}
void Uart::transmit( uint8_t data )
{
unistd_write( m_fd, &data, 1 );
}
void Uart::receive( uint8_t *buffer, uint16_t size )
{
if( read( m_fd, buffer, size ) != size )
{
Log::warning( "Failed to read UART RX buffer.\r\n" );
}
}
uint8_t Uart::receive( void )
{
uint8_t data;
receive( &data, 1 );
return data;
}
void Uart::init( void )
{
// No controlling tty, Enables nonblocking mode.
m_fd = open( m_device, O_RDWR | O_NOCTTY | O_NONBLOCK );
if( m_fd < 0 )
{
Log::error( "Failed to open %s.\r\n", m_device );
throw std::runtime_error( strerror( errno ) );
}
// Explicit reset due to O_NONBLOCK.
fcntl( m_fd, F_SETFL, O_RDWR );
baudrate( 115200 );
mode( lot::U8N1 );
}
} // namespace lot
| 27.309804 | 97 | 0.572229 | loliot |
bbd3b343fce753023dfc6462e0fb3caa48a0136e | 1,415 | cpp | C++ | src/frontend/Gui/Gui_textures.cpp | bpapaspyros/RobSim | b126e892910085fde4d14f50380b8db44fa7cd24 | [
"MIT"
] | null | null | null | src/frontend/Gui/Gui_textures.cpp | bpapaspyros/RobSim | b126e892910085fde4d14f50380b8db44fa7cd24 | [
"MIT"
] | null | null | null | src/frontend/Gui/Gui_textures.cpp | bpapaspyros/RobSim | b126e892910085fde4d14f50380b8db44fa7cd24 | [
"MIT"
] | null | null | null | #include <iostream>
#include <SOIL/SOIL.h>
#include "frontend/Gui/Gui_textures.h"
Gui_textures::Gui_textures(){
background = "../res/world/moon.jpg";
}
/*- -------------------------------------------------------------- -*/
GLuint Gui_textures::loadEpicTex(std::string filename){
GLuint tex;
tex = SOIL_load_OGL_texture(
filename.c_str(),
SOIL_LOAD_AUTO,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_POWER_OF_TWO
| SOIL_FLAG_MIPMAPS
| SOIL_FLAG_MULTIPLY_ALPHA
| SOIL_FLAG_COMPRESS_TO_DXT
| SOIL_FLAG_DDS_LOAD_DIRECT
| SOIL_FLAG_INVERT_Y
);
if( !tex )
{
std::cerr << "Could not load the texture from file: " << filename << std::endl;
}
return tex;
}
/*- -------------------------------------------------------------- -*/
void Gui_textures::drawEpicBackground() {
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
glColor3f(1, 1, 1);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-30, -30, 0);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 30, -30, 0);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 30, 30, 0);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-30, 30, 0);
glEnd();
glDisable(GL_TEXTURE_2D);
}
/*- -------------------------------------------------------------- -*/
| 24.824561 | 91 | 0.475618 | bpapaspyros |
bbd6b046403f207d4c30199808bc32c1844dd87a | 462 | cpp | C++ | Smallest_Numbers_of_Notes.cpp | omkarugale7/codechef-questions | 05cb8f4f9e5bded9ca3b8ee4e913bdd314cb0585 | [
"MIT"
] | null | null | null | Smallest_Numbers_of_Notes.cpp | omkarugale7/codechef-questions | 05cb8f4f9e5bded9ca3b8ee4e913bdd314cb0585 | [
"MIT"
] | null | null | null | Smallest_Numbers_of_Notes.cpp | omkarugale7/codechef-questions | 05cb8f4f9e5bded9ca3b8ee4e913bdd314cb0585 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
int n, ans = 0, j = 0;
cin >> n;
int re[6] = {100, 50, 10, 5, 2, 1};
while (n > 0)
{
int b = n / re[j];
if (b != 0)
{
ans += b;
n -= b * re[j];
}
j++;
}
cout << ans << endl;
}
return 0;
} | 17.111111 | 43 | 0.292208 | omkarugale7 |
bbd98f5647e0f85eb95a40172c343e4062d678b9 | 3,683 | cpp | C++ | src/src/CVDecoder.cpp | AydinyanNarek/OpenCV | 202551bd10cbd66f77e8dc008808cb499be21cc3 | [
"MIT"
] | 1 | 2020-06-22T08:48:51.000Z | 2020-06-22T08:48:51.000Z | src/src/CVDecoder.cpp | AydinyanNarek/OpenCV | 202551bd10cbd66f77e8dc008808cb499be21cc3 | [
"MIT"
] | null | null | null | src/src/CVDecoder.cpp | AydinyanNarek/OpenCV | 202551bd10cbd66f77e8dc008808cb499be21cc3 | [
"MIT"
] | null | null | null | #include "../include/CVDecoder.h"
#include "opencv2/videoio/legacy/constants_c.h"
#include "opencv2/video/background_segm.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/video.hpp"
#include <future>
void BaseVideo::registerErrors() {
Errors::ErrorRegister::registerErrors({
{"FileOpenError", "Failed to open input file."},
{"InvalidInputArgumentError", "Invalid input argument."},
{"InvalidFileFormatError", "Output file format not supported."},
{"InvalidCodecError", "Video Encoder not supported or not available for container."},
{"UnregisteredTypeError", "Failed to use the type as it is not supported."}
});
}
CVDecoder::CVDecoder(const std::vector<std::string>& file) : BaseVideo(file), mVideoCap(BaseVideo::CVMAKE<cv::VideoCapture*>(0)) {
try{
initialize();
}
catch(...) {
releaseBuffers();
Errors::ErrorRegister::Throw("FileOpenError");
}
}
CVDecoder::~CVDecoder() {
auto future = std::async(&CVDecoder::releaseFrames, this);
releaseBuffers();
future.get();
}
void CVDecoder::free(std::unique_ptr<typename std::remove_pointer<video>::type, void (*)(video)> ptr) {
if(nullptr != ptr) {
ptr->release();
ptr.reset();
}
}
void CVDecoder::releaseBuffers() {
free(std::move(mVideoCap));
for (auto&& it : mVideoCapturesBuffer) {
free(std::move(it));
}
}
void CVDecoder::releaseFrames() {
for(auto&& overlays : mOverlayBuffer) {
for(auto&& it : overlays) {
it.release();
}
}
for(auto&& it : mBackground) {
it.release();
}
}
void CVDecoder::openFile() {
std::lock_guard<std::mutex>lock(mt);
mVideoCap = BaseVideo::CVMAKE(new cv::VideoCapture(mFile));
if(!mVideoCap->isOpened()) {
Errors::ErrorRegister::Throw("FileOpenError");
}
mFrameRate = mVideoCap->get(CV_CAP_PROP_FPS);
mWidth = mVideoCap->get(CV_CAP_PROP_FRAME_WIDTH);
mHeight = mVideoCap->get(CV_CAP_PROP_FRAME_HEIGHT);
mFrameCount = mVideoCap->get(CV_CAP_PROP_FRAME_COUNT);
}
void CVDecoder::initialize() {
std::thread fileThread(&CVDecoder::openFile, this);
for(auto&& it : mOverlays) {
auto temp = BaseVideo::CVMAKE(new cv::VideoCapture(it));
if(!temp->isOpened()) {
Errors::ErrorRegister::Throw("FileOpenError");
}
mVideoCapturesBuffer.emplace_back(std::move(temp));
}
if (fileThread.joinable()) {
fileThread.join();
}
}
std::vector<cv::Mat> CVDecoder::readVideo(std::unique_ptr<typename std::remove_pointer<video>::type, void (*)(video)> ptr) {
std::lock_guard<std::mutex>lock(mVideoReaderMutex);
std::vector<cv::Mat> temp;
cv::Mat dest;
for(;;) {
cv::Mat frame;
*(ptr) >> frame;
if (frame.empty()) {
break;
}
cv::resize(frame, dest, cv::Size(mWidth, mHeight));
temp.emplace_back(std::move(dest));
frame.release();
dest.release();
}
return temp;
}
void CVDecoder::decode() {
auto future = std::async(&CVDecoder::readVideo, this, std::move(mVideoCap));
for(auto&& it : mVideoCapturesBuffer) {
auto overlay = readVideo(std::move(it));
mOverlayBuffer.emplace_back(std::move(overlay));
}
mBackground = future.get();
}
std::vector<cv::Mat> CVDecoder::resize(const std::vector<cv::Mat>& moveing) {
std::vector<cv::Mat> dest;
dest.resize(moveing.size());
int i = 0;
for (auto & it : moveing) {
cv::resize(it, dest[i], cv::Size(mWidth, mHeight));
++i;
}
return dest;
}
| 29.230159 | 130 | 0.609014 | AydinyanNarek |
bbda226ea166b485f1acf2d086c965e59642a6ae | 1,815 | cpp | C++ | Source/Scene/CommonTool.cpp | hipiPan/effects | d9003f71e6fb485d054fb198cfdf5b944e2e158f | [
"MIT"
] | 2 | 2019-10-14T14:48:29.000Z | 2019-10-14T15:45:25.000Z | Source/Scene/CommonTool.cpp | hipiPan/effects | d9003f71e6fb485d054fb198cfdf5b944e2e158f | [
"MIT"
] | null | null | null | Source/Scene/CommonTool.cpp | hipiPan/effects | d9003f71e6fb485d054fb198cfdf5b944e2e158f | [
"MIT"
] | null | null | null | #include "CommonTool.h"
#include "Core/Utility/Log.h"
#include "UI/UISystem.h"
EFFECTS_NAMESPACE_BEGIN
Camera::Camera(glm::vec3 position, float yaw, float pitch)
{
m_position = position;
m_front = glm::vec3(0, 0, -1);
m_up = glm::vec3(0, 1, 0);
m_yaw = yaw;
m_pitch = pitch;
}
Camera::~Camera()
{
}
void Camera::Move(float wheel)
{
m_position += m_front * wheel * 0.1f;
}
void Camera::Rotate(glm::vec2 offset)
{
m_yaw += offset.x * 0.1f;
m_pitch += -offset.y * 0.1f;
updateVectors();
}
glm::mat4 Camera::getViewMatrix()
{
return glm::lookAt(m_position, m_position + m_front, m_up);
}
glm::mat4 Camera::getProjectionMatrix(int width, int height, float fov, float near, float far)
{
float ratio = width / float(height);
return glm::perspective(glm::radians(fov), ratio, near, far);
}
void Camera::updateVectors()
{
glm::vec3 front;
front.x = cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));
front.y = sin(glm::radians(m_pitch));
front.z = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));
m_front = glm::normalize(front);
m_right = glm::normalize(glm::cross(m_front, glm::vec3(0, 1, 0)));
m_up = glm::normalize(glm::cross(m_right, m_front));
}
Input::Input()
{
memset(m_mouse_button_up, 0, sizeof(m_mouse_button_up));
memset(m_mouse_button_held, 0, sizeof(m_mouse_button_held));
memset(m_mouse_button_down, 0, sizeof(m_mouse_button_down));
m_mouse_scroll_wheel = 0.0;
}
Input::~Input()
{
}
void Input::update()
{
memset(m_mouse_button_up, 0, sizeof(m_mouse_button_up));
memset(m_mouse_button_down, 0, sizeof(m_mouse_button_down));
m_mouse_scroll_wheel = 0.0;
}
Context::Context()
{
}
Context::~Context()
{
}
void Context::update(float t)
{
m_time += t;
m_input->update();
m_ui_system->update();
}
void Context::drawUI()
{
m_ui_system->draw();
}
EFFECTS_NAMESPACE_END | 20.862069 | 94 | 0.699174 | hipiPan |
bbdd15c899c408ad89073c84f54de3654bf7bdec | 131 | hh | C++ | src/Exception/StopPropagationUnsafeException.hh | GroovyCarrot/hhvm-event-dispatcher | 0140f298c06ce60eeb2f07e7cc1f95aeca5ca853 | [
"MIT"
] | null | null | null | src/Exception/StopPropagationUnsafeException.hh | GroovyCarrot/hhvm-event-dispatcher | 0140f298c06ce60eeb2f07e7cc1f95aeca5ca853 | [
"MIT"
] | null | null | null | src/Exception/StopPropagationUnsafeException.hh | GroovyCarrot/hhvm-event-dispatcher | 0140f298c06ce60eeb2f07e7cc1f95aeca5ca853 | [
"MIT"
] | null | null | null | <?hh // strict
namespace GroovyCarrot\Event\Exception;
final class StopPropagationUnsafeException extends \RuntimeException
{
}
| 14.555556 | 68 | 0.80916 | GroovyCarrot |
bbde5f10bf85a778b7cc6e6582601b3d1b8ab41b | 1,522 | cpp | C++ | src/minoru_driver.cpp | srv/minoru_driver | 24718626df4856546c92ba67ec1aa614f10d63f9 | [
"MIT"
] | null | null | null | src/minoru_driver.cpp | srv/minoru_driver | 24718626df4856546c92ba67ec1aa614f10d63f9 | [
"MIT"
] | null | null | null | src/minoru_driver.cpp | srv/minoru_driver | 24718626df4856546c92ba67ec1aa614f10d63f9 | [
"MIT"
] | null | null | null | #include <ros/ros.h>
#include "opencv2/opencv.hpp"
using namespace std;
class MinoruDriver
{
ros::NodeHandle nh_;
ros::NodeHandle nh_private_;
int left_dev_idx_, right_dev_idx_;
public:
MinoruDriver() : nh_private_("~")
{
nh_private_.param("left_dev_idx", left_dev_idx_, 0);
nh_private_.param("right_dev_idx", right_dev_idx_, 1);
}
void stream()
{
// Open left
cv::VideoCapture l_cap(left_dev_idx_);
cv::VideoCapture r_cap(right_dev_idx_);
if(!l_cap.isOpened())
{
ROS_ERROR("Error opening left camera");
return;
}
if(!r_cap.isOpened())
{
ROS_WARN("Error opening right camera");
return;
}
// Setup
l_cap.set(CV_CAP_PROP_FRAME_WIDTH, 320);
l_cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
l_cap.set(CV_CAP_PROP_FPS, 15);
r_cap.set(CV_CAP_PROP_FRAME_WIDTH, 320);
r_cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
r_cap.set(CV_CAP_PROP_FPS, 15);
while(ros::ok())
{
cv::Mat l_frame, r_frame;
// Left frame
l_cap >> l_frame;
ros::Duration(0.5).sleep();
// Right frame
r_cap >> r_frame;
ROS_INFO_STREAM("FRAME PROCESSED: " << l_frame.cols << "x" << l_frame.rows << " | " << r_frame.cols << "x" << r_frame.rows);
}
// the camera will be deinitialized automatically in VideoCapture destructor
return;
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "minoru_driver");
MinoruDriver node;
node.stream();
ros::spin();
return 0;
}
| 20.293333 | 135 | 0.632063 | srv |
bbe2dceeb3a33c2ad9ec4e423208ef9ccfbd0662 | 677 | cpp | C++ | core/fxcodec/jpeg/jpeg_common.cpp | sanarea/pdfium | 632a6cb844457a97dd48b97ad69ab365aeb17491 | [
"Apache-2.0"
] | 25 | 2019-05-07T16:16:40.000Z | 2022-03-30T09:04:00.000Z | core/fxcodec/jpeg/jpeg_common.cpp | sanarea/pdfium | 632a6cb844457a97dd48b97ad69ab365aeb17491 | [
"Apache-2.0"
] | 4 | 2020-10-20T13:09:56.000Z | 2021-04-10T00:23:35.000Z | core/fxcodec/jpeg/jpeg_common.cpp | sanarea/pdfium | 632a6cb844457a97dd48b97ad69ab365aeb17491 | [
"Apache-2.0"
] | 11 | 2019-09-11T20:43:10.000Z | 2022-03-30T09:04:01.000Z | // Copyright 2020 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fxcodec/jpeg/jpeg_common.h"
extern "C" {
void src_do_nothing(jpeg_decompress_struct* cinfo) {}
boolean src_fill_buffer(j_decompress_ptr cinfo) {
return FALSE;
}
boolean src_resync(j_decompress_ptr cinfo, int desired) {
return FALSE;
}
void error_do_nothing(j_common_ptr cinfo) {}
void error_do_nothing_int(j_common_ptr cinfo, int) {}
void error_do_nothing_char(j_common_ptr cinfo, char*) {}
} // extern "C"
| 24.178571 | 80 | 0.763663 | sanarea |
bbe62e6c7c990f0e77c045f19f8681629a5d5230 | 1,112 | cpp | C++ | 1st/binary_tree_maximum_path_sum.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 1st/binary_tree_maximum_path_sum.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 1st/binary_tree_maximum_path_sum.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int maxPathSum(TreeNode* root) {
if (!root)
return 0;
int max = root->val;
maxPathSum(root, max);
return max;
}
int maxPathSum(TreeNode *root, int &max) {
if (!root)
return 0;
int left_max = maxPathSum(root->left, max);
int right_max = maxPathSum(root->right, max);
int tmp = root->val;
if (left_max > 0)
tmp += left_max;
if (right_max > 0)
tmp += right_max;
max = max > tmp ? max : tmp;
int tmp_max = (left_max > right_max ? left_max : right_max) + root->val;
return tmp_max > root->val ? tmp_max : root->val;
}
};
int main(void)
{
TreeNode t1(1);
TreeNode t2(-2);
TreeNode t3(3);
TreeNode t4(3);
t1.left = &t2;
t1.right = &t3;
//t3.left = &t4;
cout << Solution().maxPathSum(&t1) << endl;
return 0;
}
| 20.981132 | 80 | 0.530576 | buptlxb |
bbec70110e809c6967064542c7d91bb44ba9dd5a | 345 | hpp | C++ | src/engine/effects/transition.hpp | Blackhawk-TA/32blit-rpg | eaad46e1eeab6765a6b8f6e31a2d196aeeaba6f9 | [
"MIT"
] | 1 | 2021-12-31T23:52:57.000Z | 2021-12-31T23:52:57.000Z | src/engine/effects/transition.hpp | Blackhawk-TA/GateKeeper | 49a260bf7ba2304f1649b5ed487bc1e55028e672 | [
"MIT"
] | null | null | null | src/engine/effects/transition.hpp | Blackhawk-TA/GateKeeper | 49a260bf7ba2304f1649b5ed487bc1e55028e672 | [
"MIT"
] | null | null | null | //
// Created by daniel on 04.09.21.
//
#pragma once
#include "../../utils/utils.hpp"
namespace transition {
enum TransitionState {
INACTIVE = 0,
FADING_IN = 1,
BLACKED_OUT = 2,
CALLBACK_EXECUTED = 3,
FADING_OUT = 4,
};
bool in_process();
void draw();
void update(uint32_t time);
void start(std::function<void()> callback);
}
| 15.681818 | 44 | 0.657971 | Blackhawk-TA |
bbedf375e29f6763894e3215a28d18a7eeb1c5ac | 622 | cpp | C++ | EJERCICIOS/EJERCICIO C++/Examen II parcial/main.cpp | dianaM182/cpp | 45b0e688b00f5a6f4483aba13904b5d760806726 | [
"MIT"
] | null | null | null | EJERCICIOS/EJERCICIO C++/Examen II parcial/main.cpp | dianaM182/cpp | 45b0e688b00f5a6f4483aba13904b5d760806726 | [
"MIT"
] | null | null | null | EJERCICIOS/EJERCICIO C++/Examen II parcial/main.cpp | dianaM182/cpp | 45b0e688b00f5a6f4483aba13904b5d760806726 | [
"MIT"
] | null | null | null | #include <iostream>
#include <windows.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include "juego.h"
using namespace std;
int main ()
{
char tecla;
int puntos = 0 ;
int xPos = 30 , yPos = 20 ;
inicializarArreglo ();
dificultad ();
gotoxy(50,2);
cout << puntos;
pintar ();
gotoxy (xPos, yPos);
cout << ( char ) 4 ;
while (tecla != 27 && gameover ()) {
proceso (tecla, puntos);
}
if (! gameover ()) {
MessageBox ( NULL , " Has perdido " , " Perdedor " , MB_OK);
system ( " cls " );
}
system ( " pausa> NULO " );
return 0 ;
}
| 16.810811 | 63 | 0.533762 | dianaM182 |
bbf0a7a66b0ee02ead8c4c703ec62112b95514a8 | 880 | hpp | C++ | src/config.hpp | niclasr/crosswrench | 6853721d4915bda559daa8941fcbf268230959e6 | [
"MIT"
] | null | null | null | src/config.hpp | niclasr/crosswrench | 6853721d4915bda559daa8941fcbf268230959e6 | [
"MIT"
] | null | null | null | src/config.hpp | niclasr/crosswrench | 6853721d4915bda559daa8941fcbf268230959e6 | [
"MIT"
] | null | null | null | #if !defined(_SRC_CONFIG_HPP_)
#define _SRC_CONFIG_HPP_
#include <cxxopts.hpp>
#include <map>
#include <string>
namespace crosswrench {
class config
{
public:
static config *instance();
bool setup(cxxopts::ParseResult &);
bool setup(std::map<std::string, std::string> &);
std::string get_value(std::string);
void print_all();
config(const config &) = delete;
config &operator=(const config &) = delete;
std::string dotdatakeydir2config(std::string &);
private:
bool get_algos(cxxopts::ParseResult &);
bool set_python_value(std::string, cxxopts::ParseResult &);
bool verify_python_interpreter(cxxopts::ParseResult &pr);
config();
std::map<std::string, std::string> db;
std::map<std::string, std::string> new_db;
std::map<std::string, std::string> dotdatakeydir2config_map;
};
} // namespace crosswrench
#endif
| 24.444444 | 64 | 0.6875 | niclasr |
bbf5b2c4c0f9c577a3cf2e2b567844544922714c | 2,615 | cpp | C++ | solved_problems/276D.cpp | archit-1997/codeforces | 6f78a3ed5930531159ae22f7b70dc56e37a9e240 | [
"MIT"
] | 1 | 2021-01-27T16:37:31.000Z | 2021-01-27T16:37:31.000Z | solved_problems/276D.cpp | archit-1997/codeforces | 6f78a3ed5930531159ae22f7b70dc56e37a9e240 | [
"MIT"
] | null | null | null | solved_problems/276D.cpp | archit-1997/codeforces | 6f78a3ed5930531159ae22f7b70dc56e37a9e240 | [
"MIT"
] | null | null | null | /*A little girl loves problems on bitwise operations very much. Here's one of
them.
You are given two integers l and r. Let's consider the values of for all pairs
of integers a and b (l ≤ a ≤ b ≤ r). Your task is to find the maximum value
among all considered ones.
Expression means applying bitwise excluding or operation to integers x and y.
The given operation exists in all modern programming languages, for example, in
languages C++ and Java it is represented as "^", in Pascal — as «xor». Input
The single line contains space-separated integers l and r (1 ≤ l ≤ r ≤ 1018).
Please, do not use the %lld specifier to read or write 64-bit integers in С++.
It is preferred to use the cin, cout streams or the %I64d specifier. Output
In a single line print a single integer — the maximum value of for all pairs of
integers a, b (l ≤ a ≤ b ≤ r). Examples Input Copy
1 2
Output
Copy
3
Input
Copy
8 16
Output
Copy
31
Input
Copy
1 1
Output
Copy
0
*/
// Chochu Singh
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define line cout << "-------------" << endl;
#define F first
#define S second
#define P pair<ll, ll>
#define PP pair<pair<ll, ll>, ll>
#define V vector<ll>
#define VP vector<pair<ll, ll>>
#define VS vector<string>
#define VV vector<vector<ll>>
#define VVP vector<vector<pair<ll, ll>>>
#define pb push_back
#define pf push_front
#define PQ priority_queue<ll>
#define PQ_G priority_queue<ll, vector<ll>, greater<ll>>
#define FOR(i, a, b) for (ll i = a; i < b; i++)
#define FAST \
ios_base::sync_with_stdio(false); \
cin.tie(NULL);
string binary(ll n) {
string ans;
while (n != 0) {
ans = ans + to_string(n % 2);
n /= 2;
}
reverse(ans.begin(), ans.end());
return ans;
}
ll decimal(string s) {
reverse(s.begin(), s.end());
ll ans = 0, n = s.size();
FOR(i, 0, n) {
if (s[i] == '1')
ans += pow(2, i);
}
return ans;
}
int main() {
FAST;
ll l, r;
cin >> l >> r;
if (l == r)
cout << 0;
else if (r == l + 1)
cout << (l ^ r);
else {
ll x = l ^ r;
string s = binary(x);
ll n = s.size(), index;
for (ll i = 0; i < n; i++) {
if (s[i] == '1') {
index = i;
break;
}
}
for (ll i = index; i < n; i++)
s[i] = '1';
ll ans = decimal(s);
cout << ans << endl;
}
return 0;
}
| 19.810606 | 81 | 0.555641 | archit-1997 |
bbf775190e7cb605a20e6a75a4f952682d6c5ab7 | 2,597 | cc | C++ | tests/si/rendering.cc | juliusnehring/arcana-samples | b5d71c114f353b278323b96450b1bfcd947336b7 | [
"MIT"
] | null | null | null | tests/si/rendering.cc | juliusnehring/arcana-samples | b5d71c114f353b278323b96450b1bfcd947336b7 | [
"MIT"
] | null | null | null | tests/si/rendering.cc | juliusnehring/arcana-samples | b5d71c114f353b278323b96450b1bfcd947336b7 | [
"MIT"
] | null | null | null | #include <nexus/app.hh>
#include <resource-system/res.hh>
#include <phantasm-renderer/pr.hh>
#include <structured-interface/element_tree.hh>
#include <structured-interface/gui.hh>
#include <structured-interface/layout/aabb_layout.hh>
#include <structured-interface/si.hh>
#include <arcana-incubator/device-abstraction/device_abstraction.hh>
namespace
{
constexpr auto shader_code_clear = R"(
struct vs_in
{
uint vid : SV_VertexID;
};
struct vs_out
{
float4 SV_P : SV_POSITION;
float2 Texcoord : TEXCOORD;
};
vs_out main_vs(vs_in In)
{
vs_out Out;
Out.Texcoord = float2((In.vid << 1) & 2, In.vid & 2);
Out.SV_P = float4(Out.Texcoord * 2.0f + -1.0f, 0.0f, 1.0f);
Out.SV_P.y = -Out.SV_P.y;
return Out;
}
float4 main_ps(vs_out In) : SV_TARGET
{
return float4(0.6,0.6,0.6, 1);
}
)";
}
APP("ui rendering")
{
auto window = inc::da::SDLWindow("structured interface");
auto ctx = pr::Context(pr::backend::vulkan);
auto swapchain = ctx.make_swapchain({window.getSdlWindow()}, window.getSize());
auto vs_clear = ctx.make_shader(shader_code_clear, "main_vs", pr::shader::vertex);
auto ps_clear = ctx.make_shader(shader_code_clear, "main_ps", pr::shader::pixel);
si::gui ui;
while (!window.isRequestingClose())
{
window.pollEvents();
auto r = ui.record([&] {
si::button("press me");
si::text("i'm a test text.");
});
auto tree = si::element_tree::from_record(r);
si::compute_aabb_layout(tree);
auto backbuffer = ctx.acquire_backbuffer(swapchain);
auto frame = ctx.make_frame();
{
auto fb = frame.make_framebuffer(backbuffer);
auto pass = fb.make_pass(pr::graphics_pass({}, vs_clear, ps_clear));
pass.draw(3);
}
frame.present_after_submit(backbuffer, swapchain);
ctx.submit(cc::move(frame));
}
}
| 32.873418 | 93 | 0.471698 | juliusnehring |
bbf8a32a55fd0365ced4e6755b380389560f0481 | 239 | cpp | C++ | Sources/Core/cpp_cli/LinguisticsKernel/AnaphoraResolution.cpp | elzin/SentimentAnalysisService | 41fba2ef49746473535196e89a5e49250439fd83 | [
"MIT"
] | 2 | 2021-07-07T19:39:11.000Z | 2021-12-02T15:54:15.000Z | Sources/Core/cpp_cli/LinguisticsKernel/AnaphoraResolution.cpp | elzin/SentimentAnalysisService | 41fba2ef49746473535196e89a5e49250439fd83 | [
"MIT"
] | null | null | null | Sources/Core/cpp_cli/LinguisticsKernel/AnaphoraResolution.cpp | elzin/SentimentAnalysisService | 41fba2ef49746473535196e89a5e49250439fd83 | [
"MIT"
] | 1 | 2021-12-01T17:48:20.000Z | 2021-12-01T17:48:20.000Z | #include "StdAfx.h"
#include "AnaphoraResolution.h"
namespace SS
{
namespace LinguisticProcessor
{
System::String* CAnaphoraResolution::ResovleAnaphoras(System::String* xmlData)
{
//System::Xml::XmlDocument* xdoc =
return "";
}
}
} | 13.277778 | 78 | 0.732218 | elzin |
bbf8daeb17bf1b808e9e5fcdc0a99a7314a4bba0 | 342 | cpp | C++ | alignment/format/CompareSequencesPrinter.cpp | ggraham/blasr_libcpp | 4abef36585bbb677ebc4acb9d4e44e82331d59f7 | [
"RSA-MD"
] | 4 | 2015-07-03T11:59:54.000Z | 2018-05-17T00:03:22.000Z | alignment/format/CompareSequencesPrinter.cpp | ggraham/blasr_libcpp | 4abef36585bbb677ebc4acb9d4e44e82331d59f7 | [
"RSA-MD"
] | 79 | 2015-06-29T18:07:21.000Z | 2018-09-19T13:38:39.000Z | alignment/format/CompareSequencesPrinter.cpp | ggraham/blasr_libcpp | 4abef36585bbb677ebc4acb9d4e44e82331d59f7 | [
"RSA-MD"
] | 19 | 2015-06-23T08:43:29.000Z | 2021-04-28T18:37:47.000Z | #include <alignment/format/CompareSequencesPrinter.hpp>
void CompareSequencesOutput::PrintHeader(std::ostream &out)
{
out << "qName qLength qStart qEnd qStrand "
<< "tName tLength tStart tEnd tStrand "
<< "score numMatch numMismatch numIns numDel "
<< "mapQV qAlignedSeq matchPattern tAlignedSeq" << std::endl;
}
| 34.2 | 69 | 0.704678 | ggraham |
bbfb4ef8311162faaec0768c6d394198f212dd38 | 1,934 | hpp | C++ | include/codegen/include/UnityEngine/Playables/ScriptPlayableBinding.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/Playables/ScriptPlayableBinding.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/Playables/ScriptPlayableBinding.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:32 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::Playables
namespace UnityEngine::Playables {
// Forward declaring type: PlayableBinding
struct PlayableBinding;
// Forward declaring type: PlayableOutput
struct PlayableOutput;
// Forward declaring type: PlayableGraph
struct PlayableGraph;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Object
class Object;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Type namespace: UnityEngine.Playables
namespace UnityEngine::Playables {
// Autogenerated type: UnityEngine.Playables.ScriptPlayableBinding
class ScriptPlayableBinding : public ::Il2CppObject {
public:
// static public UnityEngine.Playables.PlayableBinding Create(System.String name, UnityEngine.Object key, System.Type type)
// Offset: 0x1403C64
static UnityEngine::Playables::PlayableBinding Create(::Il2CppString* name, UnityEngine::Object* key, System::Type* type);
// static private UnityEngine.Playables.PlayableOutput CreateScriptOutput(UnityEngine.Playables.PlayableGraph graph, System.String name)
// Offset: 0x1403D48
static UnityEngine::Playables::PlayableOutput CreateScriptOutput(UnityEngine::Playables::PlayableGraph graph, ::Il2CppString* name);
}; // UnityEngine.Playables.ScriptPlayableBinding
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Playables::ScriptPlayableBinding*, "UnityEngine.Playables", "ScriptPlayableBinding");
#pragma pack(pop)
| 40.291667 | 140 | 0.751293 | Futuremappermydud |
0107174051aedc2d3deca281915d982f230b7543 | 51 | cpp | C++ | grafi/mst.cpp | malorubiuz/tutorato_olimpiadi2021 | 86736147af5f47da5cc3276bd9a894977bdee073 | [
"Unlicense"
] | null | null | null | grafi/mst.cpp | malorubiuz/tutorato_olimpiadi2021 | 86736147af5f47da5cc3276bd9a894977bdee073 | [
"Unlicense"
] | null | null | null | grafi/mst.cpp | malorubiuz/tutorato_olimpiadi2021 | 86736147af5f47da5cc3276bd9a894977bdee073 | [
"Unlicense"
] | null | null | null | // https://training.olinfo.it/#/task/mst/statement
| 25.5 | 50 | 0.72549 | malorubiuz |
010d96856a034d744699b0f519c2b53f6f22f4f2 | 1,949 | cpp | C++ | examples/BlockOut3000/src/BlockOut.cpp | iboB/maibo | df43ddf82b3c79e00f3d2c8b38db181e5edae264 | [
"MIT"
] | 4 | 2015-08-07T09:11:15.000Z | 2018-01-03T15:47:04.000Z | examples/BlockOut3000/src/BlockOut.cpp | iboB/maibo | df43ddf82b3c79e00f3d2c8b38db181e5edae264 | [
"MIT"
] | null | null | null | examples/BlockOut3000/src/BlockOut.cpp | iboB/maibo | df43ddf82b3c79e00f3d2c8b38db181e5edae264 | [
"MIT"
] | null | null | null | // MaiBo - BlockOut3000
// Copyright(c) 2015 Borislav Stanimirov
//
// Distributed under the MIT Software License
// See accompanying file LICENSE.txt or copy at
// http://opensource.org/licenses/MIT
//
#include "BlockOut.h"
#include <maibo/Resources/ResourceManager.h>
#include <maibo/Common/high_res_clock.h>
#include <maibo/GUI/ImGui/ImGuiManager.h>
#include "LoadAllState.h"
#include "Resources.h"
#include "FigureManager.h"
#include "CubeTemplate.h"
using namespace std;
using namespace maibo;
bool BlockOut::initialize()
{
Application::CreationParameters params;
params.desiredFrameTimeMs = 10;
if (!Application::initialize(params))
{
return false;
}
glEnable(GL_DEPTH_TEST); // z buffer
glEnable(GL_CULL_FACE); // cull back (CW) faces
glClearColor(0.0f, 0.1f, 0.4f, 1); // backbuffer clear color
Resources::createInstance();
CubeTemplate::createInstance();
FigureManager::createInstance();
setState(new LoadAllState);
ImGuiManager::createInstance();
startRunning();
return true;
}
void BlockOut::deinitialize()
{
ImGuiManager::destroyInstance();
FigureManager::destroyInstance();
CubeTemplate::destroyInstance();
Resources::destroyInstance();
Application::deinitialize();
cout << "Total frames: " << totalFrames() << endl;
}
void BlockOut::update()
{
Application::update();
}
void BlockOut::render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Application::render();
}
void BlockOut::onSetStateError(AppState* state)
{
// nothing to do yet
}
// maibo integration
namespace maibo
{
namespace
{
BlockOut* app = nullptr;
}
void Application_CreateInstance(int argc, char* argv[])
{
app = new BlockOut();
}
Application& Application_Instance()
{
return *app;
}
void Application_DestroyInstance(int retCode)
{
delete app;
}
}
| 18.740385 | 64 | 0.675731 | iboB |
012a9a9a9d63054e55210b2b055421000c502c34 | 12,570 | cpp | C++ | Attic/AtomicEditorReference/Source/UI/UIResourceFrame.cpp | honigbeutler123/AtomicGameEngine | c53425f19b216eb21ecd3bda85052aaa1a6f2aaa | [
"Apache-2.0",
"MIT"
] | null | null | null | Attic/AtomicEditorReference/Source/UI/UIResourceFrame.cpp | honigbeutler123/AtomicGameEngine | c53425f19b216eb21ecd3bda85052aaa1a6f2aaa | [
"Apache-2.0",
"MIT"
] | null | null | null | Attic/AtomicEditorReference/Source/UI/UIResourceFrame.cpp | honigbeutler123/AtomicGameEngine | c53425f19b216eb21ecd3bda85052aaa1a6f2aaa | [
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
// Please see LICENSE.md in repository root for license information
// https://github.com/AtomicGameEngine/AtomicGameEngine
#include "AtomicEditor.h"
#include <Atomic/Container/ArrayPtr.h>
#include <Atomic/UI/UI.h>
#include <Atomic/IO/Log.h>
#include <Atomic/IO/File.h>
#include <Atomic/IO/FileSystem.h>
#include <Atomic/Resource/ResourceCache.h>
#include <Atomic/Core/CoreEvents.h>
#include <AtomicJS/Javascript/JSEvents.h>
#include "UIResourceFrame.h"
#include "../Editors/JSResourceEditor.h"
#include "../Editors/SceneEditor3D/SceneEditor3D.h"
#include "../Editors/ModelResourceEditor.h"
#include "../Editors/TextResourceEditor.h"
#include "../AEEvents.h"
#include "../AEEditor.h"
#include "UIIssuesWidget.h"
#include "UIErrorsWidget.h"
#include "UIConsoleWidget.h"
#include "License/AELicenseSystem.h"
#include "Modal/UIModalOps.h"
#include "../Tools/External/AEExternalTooling.h"
using namespace tb;
namespace AtomicEditor
{
ResourceFrame::ResourceFrame(Context* context) :
AEWidget(context),
tabcontainer_(0),
resourceLayout_(0)
{
UI* tbui = GetSubsystem<UI>();
tbui->LoadResourceFile(delegate_, "AtomicEditor/editor/ui/resourceframe.tb.txt");
tabcontainer_ = delegate_->GetWidgetByIDAndType<TBTabContainer>(TBIDC("tabcontainer"));
assert(tabcontainer_);
resourceLayout_ = delegate_->GetWidgetByIDAndType<TBLayout>(TBIDC("resourcelayout"));
assert(resourceLayout_);
delegate_->SetGravity(WIDGET_GRAVITY_ALL);
issueswidget_ = new IssuesWidget(context_);
errorswidget_ = new ErrorsWidget(context_);
consolewidget_ = new ConsoleWidget(context_);
SubscribeToEvent(E_FINDTEXT, HANDLER(ResourceFrame, HandleFindText));
SubscribeToEvent(E_FINDTEXTCLOSE, HANDLER(ResourceFrame, HandleFindTextClose));
SubscribeToEvent(E_EDITORPLAYSTARTED, HANDLER(ResourceFrame, HandlePlayStarted));
SubscribeToEvent(E_EDITORPLAYSTOPPED, HANDLER(ResourceFrame, HandlePlayStopped));
}
ResourceFrame::~ResourceFrame()
{
}
void ResourceFrame::HandleFindText(StringHash eventType, VariantMap& eventData)
{
using namespace FindText;
if (!editors_.Size())
return;
int page = tabcontainer_->GetCurrentPage();
TBWidget* widget = tabcontainer_->GetCurrentPageWidget();
if (editorLookup_.Contains(widget))
editorLookup_[widget]->FindText(eventData[P_TEXT].ToString(),
(unsigned) eventData[P_FLAGS].GetInt());
}
void ResourceFrame::HandleFindTextClose(StringHash eventType, VariantMap& eventData)
{
if (!editors_.Size())
return;
TBWidget* widget = tabcontainer_->GetCurrentPageWidget();
if (editorLookup_.Contains(widget))
return editorLookup_[widget]->FindTextClose();
}
void ResourceFrame::EditResource(const String& fullpath)
{
if (editors_.Contains(fullpath))
{
NavigateToResource(fullpath);
if (GetSubsystem<Editor>()->IsPlayingProject())
{
SendEvent(E_EDITORPLAYSTOP);
}
return;
}
delegate_->SetVisibilility(WIDGET_VISIBILITY_VISIBLE);
String ext = GetExtension(fullpath);
ResourceEditor* editor = NULL;
if (ext == ".js")
{
JSResourceEditor* jse = new JSResourceEditor(context_, fullpath, tabcontainer_);
editor = jse;
}
else if (ext == ".scene")
{
SceneEditor3D* sre = new SceneEditor3D(context_, fullpath, tabcontainer_);
editor = sre;
}
else if (ext == ".xml" || ext == ".txt")
{
//SceneResourceEditor* sre = new SceneResourceEditor(context_, fullpath, tabcontainer_);
TextResourceEditor* tre = new TextResourceEditor(context_, fullpath, tabcontainer_);
editor = tre;
}
else if (ext == ".mdl")
{
//ModelResourceEditor* mre = new ModelResourceEditor(context_, fullpath, tabcontainer_);
//editor = mre;
}
else if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".ogg")
{
FileSystem* fs = GetSubsystem<FileSystem>();
fs->SystemOpen(fullpath);
}
else if (ext == ".tmx")
{
ExternalTooling* tooling = GetSubsystem<ExternalTooling>();
tooling->LaunchOrOpen("AtomicTiled", fullpath);
}
if (editor)
{
// We have a new editor so send a stop playing if we are playing
if (GetSubsystem<Editor>()->IsPlayingProject())
{
SendEvent(E_EDITORPLAYSTOP);
}
editors_[fullpath] = editor;
editorLookup_[editor->GetRootContentWidget()] = editor;
tabcontainer_->SetCurrentPage(tabcontainer_->GetNumPages()-1);
editor->SetFocus();
// BEGIN LICENSE MANAGEMENT
LicenseSystem* licenseSystem = GetSubsystem<LicenseSystem>();
if(licenseSystem->IsStandardLicense())
{
if (ext == ".scene" )
{
UIModalOps* ops = GetSubsystem<UIModalOps>();
ops->ShowInfoModule3D();
}
}
// END LICENSE MANAGEMENT
}
}
void ResourceFrame::FocusCurrentTab()
{
TBWidget* widget = tabcontainer_->GetCurrentPageWidget();
if (widget && editorLookup_.Contains(widget))
return editorLookup_[widget]->SetFocus();
}
bool ResourceFrame::OnEvent(const TBWidgetEvent &ev)
{
if (ev.type == EVENT_TYPE_TAB_CHANGED && ev.target == tabcontainer_)
{
TBWidget* widget = tabcontainer_->GetCurrentPageWidget();
if (widget)
{
if (editorLookup_.Contains(widget))
{
ResourceEditor* editor = editorLookup_[widget];
if (editor != currentResourceEditor_)
{
VariantMap eventData;
eventData[EditorResourceEditorChanged::P_RESOURCEEDITOR] = editor;
SendEvent(E_EDITORRESOURCEEDITORCHANGED, eventData);
currentResourceEditor_ = editor;
}
}
}
return true;
}
if (ev.type == EVENT_TYPE_KEY_DOWN || ev.type == EVENT_TYPE_SHORTCUT
|| ev.type == EVENT_TYPE_CLICK || ev.type == EVENT_TYPE_RIGHT_POINTER_UP)
{
if (!editors_.Size())
return false;
TBWidget* widget = tabcontainer_->GetCurrentPageWidget();
if (editorLookup_.Contains(widget))
return editorLookup_[widget]->OnEvent(ev);
}
return false;
}
bool ResourceFrame::IssuesWidgetVisible()
{
TBWidget *child;
for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext())
{
if (child == issueswidget_->GetWidgetDelegate())
break;
}
return child != NULL;
}
void ResourceFrame::ShowIssuesWidget(bool show)
{
if (show && ErrorsWidgetVisible())
ShowErrorsWidget(false);
if (show && ConsoleWidgetVisible())
ShowConsoleWidget(false);
TBWidget *child;
for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext())
{
if (child == issueswidget_->GetWidgetDelegate())
break;
}
if (show)
{
if (!child)
{
resourceLayout_->AddChild(issueswidget_->GetWidgetDelegate());
}
issueswidget_->UpdateIssues();
}
else
{
if (child)
resourceLayout_->RemoveChild(child);
}
}
bool ResourceFrame::ErrorsWidgetVisible()
{
TBWidget *child;
for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext())
{
if (child == errorswidget_->GetWidgetDelegate())
break;
}
return child != NULL;
}
void ResourceFrame::ShowErrorsWidget(bool show)
{
if (show && ConsoleWidgetVisible())
ShowConsoleWidget(false);
if (show && IssuesWidgetVisible())
ShowIssuesWidget(false);
TBWidget *child;
for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext())
{
if (child == errorswidget_->GetWidgetDelegate())
break;
}
if (show)
{
if (!child)
{
resourceLayout_->AddChild(errorswidget_->GetWidgetDelegate());
}
errorswidget_->UpdateErrors();
}
else
{
if (child)
resourceLayout_->RemoveChild(child);
}
}
bool ResourceFrame::ConsoleWidgetVisible()
{
TBWidget *child;
for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext())
{
if (child == consolewidget_->GetWidgetDelegate())
break;
}
return child != NULL;
}
void ResourceFrame::ShowConsoleWidget(bool show)
{
if (show && ErrorsWidgetVisible())
ShowErrorsWidget(false);
if (show && IssuesWidgetVisible())
ShowIssuesWidget(false);
TBWidget *child;
for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext())
{
if (child == consolewidget_->GetWidgetDelegate())
break;
}
if (show)
{
if (!child)
{
resourceLayout_->AddChild(consolewidget_->GetWidgetDelegate());
}
}
else
{
if (child)
resourceLayout_->RemoveChild(child);
}
}
void ResourceFrame::SendCurrentEditorEvent(const TBWidgetEvent &ev)
{
TBWidget* widget = tabcontainer_->GetCurrentPageWidget();
if (!widget)
return;
if (editorLookup_.Contains(widget))
editorLookup_[widget]->OnEvent(ev);
}
void ResourceFrame::NavigateToResource(const String& fullpath, int lineNumber, int tokenPos)
{
if (!editors_.Contains(fullpath))
return;
ResourceEditor* editor = editors_[fullpath];
TBWidget* root = tabcontainer_->GetContentRoot();
int i = 0;
for (TBWidget *child = root->GetFirstChild(); child; child = child->GetNext(), i++)
{
if (editorLookup_.Contains(child))
{
if (editorLookup_[child] == editor)
{
break;
}
}
}
if (i < tabcontainer_->GetNumPages())
{
tabcontainer_->SetCurrentPage(i);
editor->SetFocus();
// this cast could be better
String ext = GetExtension(fullpath);
if (ext == ".js" && lineNumber != -1)
{
JSResourceEditor* jse = (JSResourceEditor*) editor;
jse->GotoLineNumber(lineNumber);
}
else if (ext == ".js" && tokenPos != -1)
{
JSResourceEditor* jse = (JSResourceEditor*) editor;
jse->GotoTokenPos(tokenPos);
}
}
}
bool ResourceFrame::HasUnsavedModifications()
{
HashMap<String, SharedPtr<ResourceEditor> >::ConstIterator itr;
for (itr = editors_.Begin(); itr != editors_.End(); itr++)
{
if (itr->second_->HasUnsavedModifications())
return true;
}
return false;
}
void ResourceFrame::CloseResourceEditor(ResourceEditor* editor, bool navigateToAvailableResource)
{
assert(editors_.Contains(editor->GetFullPath()));
editors_.Erase(editor->GetFullPath());
TBWidget* root = tabcontainer_->GetContentRoot();
bool found = false;
for (TBWidget *child = root->GetFirstChild(); child; child = child->GetNext())
{
if (editorLookup_.Contains(child))
{
if (editorLookup_[child] == editor)
{
found = true;
root->RemoveChild(child);
editorLookup_.Erase(child);
break;
}
}
}
assert(found);
tabcontainer_->SetCurrentPage(-1);
if (navigateToAvailableResource)
{
if (editors_.Size())
{
HashMap<String, SharedPtr<ResourceEditor> >::ConstIterator itr = editors_.End();
itr--;
NavigateToResource(itr->second_->GetFullPath());
}
}
}
void ResourceFrame::HandlePlayStarted(StringHash eventType, VariantMap& eventData)
{
//delegate_->SetVisibilility(WIDGET_VISIBILITY_INVISIBLE);
//delegate_->SetIgnoreInput(true);
//delegate_->SetState(WIDGET_STATE_DISABLED, true);
}
void ResourceFrame::HandlePlayStopped(StringHash eventType, VariantMap& eventData)
{
//delegate_->SetVisibilility(WIDGET_VISIBILITY_VISIBLE);
//delegate_->SetIgnoreInput(false);
//delegate_->SetState(WIDGET_STATE_DISABLED, false);
}
void ResourceFrame::CloseAllResourceEditors()
{
Vector<SharedPtr<ResourceEditor> > editors = editors_.Values();
for (unsigned i = 0; i < editors.Size(); i++)
editors[i]->Close(false);
}
}
| 25.705521 | 97 | 0.626571 | honigbeutler123 |
012e389215c245c995bada2c7188cf25d9b0c1c2 | 758 | cpp | C++ | examples/cat.cpp | davidwed/sqlrelay_rudiments | 6ccffdfc5fa29f8c0226f3edc2aa888aa1008347 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | examples/cat.cpp | davidwed/sqlrelay_rudiments | 6ccffdfc5fa29f8c0226f3edc2aa888aa1008347 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | examples/cat.cpp | davidwed/sqlrelay_rudiments | 6ccffdfc5fa29f8c0226f3edc2aa888aa1008347 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | #include <rudiments/file.h>
#include <rudiments/stdio.h>
int main(int argc, const char **argv) {
file f;
char buffer[1024];
// for each file specified on the command line...
for (int32_t i=1; i<argc; i++) {
// open the file
if (!f.open(argv[i],O_RDONLY)) {
continue;
}
// read chunks from the file and print each chunk..
ssize_t bytesread=0;
do {
// attempt to read 1024 bytes into the buffer
bytesread=f.read(buffer,1024);
// bytesread will be the number of bytes that were
// actually read, 0 at EOF, or a negative number
// if an error occurred
if (bytesread>0) {
// print the buffer
stdoutput.write(buffer,bytesread);
}
// exit if we read fewer than 1024 bytes
} while (bytesread==1024);
}
}
| 20.486486 | 53 | 0.649077 | davidwed |
01365e9f3734e85a8a8317b257856a288f23c9aa | 278 | cpp | C++ | src/guiobject.cpp | Groogy/derelict | 5ca82ae5a5a553e292e388706a27b53840cf3afa | [
"Zlib"
] | null | null | null | src/guiobject.cpp | Groogy/derelict | 5ca82ae5a5a553e292e388706a27b53840cf3afa | [
"Zlib"
] | null | null | null | src/guiobject.cpp | Groogy/derelict | 5ca82ae5a5a553e292e388706a27b53840cf3afa | [
"Zlib"
] | null | null | null | #include "guiobject.hpp"
GuiObject::~GuiObject()
{
}
void GuiObject::update()
{
for(auto& hook : myUpdateHooks)
{
hook(*this);
}
}
void GuiObject::processEvent(const sf::Event&)
{
}
void GuiObject::attachUpdateHook(UpdateHook hook)
{
myUpdateHooks.push_back(hook);
}
| 11.583333 | 49 | 0.697842 | Groogy |
0136a96208f2b3890c4d90590887df753d7e3658 | 118 | cpp | C++ | app/src/app_main.cpp | Darckore/CmakeTemplate | f2d5ba1a17fd7304518e3b8ededfea1d638f8dc8 | [
"Unlicense"
] | null | null | null | app/src/app_main.cpp | Darckore/CmakeTemplate | f2d5ba1a17fd7304518e3b8ededfea1d638f8dc8 | [
"Unlicense"
] | null | null | null | app/src/app_main.cpp | Darckore/CmakeTemplate | f2d5ba1a17fd7304518e3b8ededfea1d638f8dc8 | [
"Unlicense"
] | null | null | null | #include "libsomething/libsource.h"
int main()
{
something::derpy::init();
something::derpy::msg();
return 0;
} | 14.75 | 35 | 0.661017 | Darckore |
013dc4f0bac66a539b63e706331a85a7f75971f9 | 1,461 | cpp | C++ | NetworkManager/SynchrounousTcp/SyncTcpClient.cpp | lahmer/lbcms | 5910aecae63082f838c7be28316764c3ed3a08f1 | [
"MIT"
] | null | null | null | NetworkManager/SynchrounousTcp/SyncTcpClient.cpp | lahmer/lbcms | 5910aecae63082f838c7be28316764c3ed3a08f1 | [
"MIT"
] | null | null | null | NetworkManager/SynchrounousTcp/SyncTcpClient.cpp | lahmer/lbcms | 5910aecae63082f838c7be28316764c3ed3a08f1 | [
"MIT"
] | null | null | null | //
// Created by lahmer on 8/12/16.
//
#include "SyncTcpClient.h"
namespace lbcms{
namespace network{
SyncTcpClient::SyncTcpClient(std::string ipv4, int port){
m_ios = new boost::asio::io_service();
m_endPoint = new boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string(ipv4),port);
m_socket = new boost::asio::ip::tcp::socket(*m_ios);
m_socket->open(m_endPoint->protocol());
}
void SyncTcpClient::Connect() {
m_socket->connect(*m_endPoint);
}
void SyncTcpClient::Close() {
m_socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
m_socket->close();
}
SyncTcpClient::~SyncTcpClient() {
Close();
delete m_socket;
delete m_ios;
delete m_endPoint;
}
void SyncTcpClient::SendMessage(const std::string& msg) {
std::string result = msg;
if(result.at(result.length()-1) != '\n')
result+='\n';
boost::asio::write(*m_socket , boost::asio::buffer(result));
}
std::string SyncTcpClient::RecieveMessage() {
boost::asio::streambuf buf;
boost::asio::read_until(*m_socket,buf,'\n');
std::istream input(&buf);
std::string response ;
std::getline(input , response);
return response;
}
}
} | 32.466667 | 113 | 0.540041 | lahmer |
0149eb6a10551bf132bfad7527c9f751d3a9a640 | 1,936 | cpp | C++ | src/Evel/Signal.cpp | hleclerc/Evel | c607adda555f417dfc9fb4de310c07c48ea3642f | [
"Apache-2.0"
] | null | null | null | src/Evel/Signal.cpp | hleclerc/Evel | c607adda555f417dfc9fb4de310c07c48ea3642f | [
"Apache-2.0"
] | null | null | null | src/Evel/Signal.cpp | hleclerc/Evel | c607adda555f417dfc9fb4de310c07c48ea3642f | [
"Apache-2.0"
] | null | null | null | #include "System/SocketUtil.h"
#include "EvLoop.h"
#include "Signal.h"
#include <sys/signalfd.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
namespace Evel {
static int make_signal_fd( const int *sigs ) {
// set up a mask
sigset_t mask;
sigemptyset( &mask );
for( int i = 0; sigs[ i ] >= 0; ++i )
sigaddset( &mask, sigs[ i ] );
// block signals
if ( sigprocmask( SIG_BLOCK, &mask, 0 ) == -1 ) {
perror( "sigprocmask" );
return -1;
}
// get a (non blocking) file descriptor
while ( true ) {
int fd = signalfd( -1, &mask, 0 );
if ( fd < 0 ) {
if ( errno == EINTR )
continue;
perror( "signalfd" );
return -1;
}
if ( set_non_block( fd ) < 0 ) {
perror( "non blocking signalfd" );
close( fd );
return -1;
}
return fd;
}
}
Signal::Signal( const int *sigs, bool need_wait ) : Event( make_signal_fd( sigs ), need_wait ) {
}
void Signal::on_inp() {
signalfd_siginfo sig_info;
while ( true ) {
ssize_t s = read( fd, &sig_info, sizeof( sig_info ) );
// end of the connection
if ( s == 0 )
return close();
// error
if ( s < 0 ) {
if ( errno == EINTR )
continue;
if ( errno == EAGAIN or errno == EWOULDBLOCK )
return;
ev_loop->err( "Pb reading signals: {}", strerror( errno ) );
close();
return;
}
if ( s < (ssize_t)sizeof( sig_info ) ) {
ev_loop->err( "TODO: partial read with signals" );
close();
return;
}
signal( sig_info.ssi_signo );
}
}
bool Signal::out_are_sent() const {
return true;
}
bool Signal::may_have_out() const {
return false;
}
} // namespace Evel
| 22 | 96 | 0.496384 | hleclerc |
014bc0069b9e903f3dac59f1bcb180f4f51c96e5 | 2,258 | cpp | C++ | core/unittest/wrapper/test_knowhere.cpp | Gracieeea/milvus | e44e455acd2731ad7c8f645e6fd13dd8f0eeea86 | [
"Apache-2.0"
] | null | null | null | core/unittest/wrapper/test_knowhere.cpp | Gracieeea/milvus | e44e455acd2731ad7c8f645e6fd13dd8f0eeea86 | [
"Apache-2.0"
] | null | null | null | core/unittest/wrapper/test_knowhere.cpp | Gracieeea/milvus | e44e455acd2731ad7c8f645e6fd13dd8f0eeea86 | [
"Apache-2.0"
] | null | null | null | // 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 "server/Config.h"
#include "wrapper/KnowhereResource.h"
#include "wrapper/utils.h"
#include <fiu-local.h>
#include <fiu-control.h>
#include <gtest/gtest.h>
TEST_F(KnowhereTest, KNOWHERE_RESOURCE_TEST) {
std::string config_path(CONFIG_PATH);
config_path += CONFIG_FILE;
milvus::server::Config& config = milvus::server::Config::GetInstance();
milvus::Status s = config.LoadConfigFile(config_path);
ASSERT_TRUE(s.ok());
milvus::engine::KnowhereResource::Initialize();
milvus::engine::KnowhereResource::Finalize();
#ifdef MILVUS_GPU_VERSION
fiu_init(0);
fiu_enable("check_config_gpu_resource_enable_fail", 1, NULL, 0);
s = milvus::engine::KnowhereResource::Initialize();
ASSERT_FALSE(s.ok());
fiu_disable("check_config_gpu_resource_enable_fail");
fiu_enable("KnowhereResource.Initialize.disable_gpu", 1, NULL, 0);
s = milvus::engine::KnowhereResource::Initialize();
ASSERT_TRUE(s.ok());
fiu_disable("KnowhereResource.Initialize.disable_gpu");
fiu_enable("check_gpu_resource_config_build_index_fail", 1, NULL, 0);
s = milvus::engine::KnowhereResource::Initialize();
ASSERT_FALSE(s.ok());
fiu_disable("check_gpu_resource_config_build_index_fail");
fiu_enable("check_gpu_resource_config_search_fail", 1, NULL, 0);
s = milvus::engine::KnowhereResource::Initialize();
ASSERT_FALSE(s.ok());
fiu_disable("check_gpu_resource_config_search_fail");
#endif
}
| 38.271186 | 75 | 0.741364 | Gracieeea |
014caf9301b4fcc559a661bf05d0866733468fc2 | 32,217 | cpp | C++ | src/interpreter/instructions/integer.cpp | lioncash/riscv-emu | e903baf122cbbc2b40f58f4c50ff970893ffe746 | [
"MIT"
] | 1 | 2021-09-17T04:07:26.000Z | 2021-09-17T04:07:26.000Z | src/interpreter/instructions/integer.cpp | lioncash/riscv-emu | e903baf122cbbc2b40f58f4c50ff970893ffe746 | [
"MIT"
] | null | null | null | src/interpreter/instructions/integer.cpp | lioncash/riscv-emu | e903baf122cbbc2b40f58f4c50ff970893ffe746 | [
"MIT"
] | null | null | null | #include <riscy/interpreter/state.hpp>
#include <algorithm>
#include <array>
#include <bit>
#include <type_traits>
#include "common/bit_util.hpp"
#include "interpreter/instructions/helper.hpp"
#include "interpreter/instructions/instructions.hpp"
namespace riscy {
using UnaryBitFn = RISCVState::GPRType (*)(RISCVState::GPRType value);
// For implementing CLZ{W}, CPOP{W}, CTZ{W}, ORC.B, REV8, SEXT.{B, H}, and ZEXT.H
static void UnaryBitInstruction(RISCVState& state, const uint32_t opcode, UnaryBitFn unary_fn) noexcept {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs = Bits<15, 19>(opcode);
const auto input = state.GPR(rs);
const auto result = unary_fn(input);
state.GPR(rd) = result;
}
using BinaryBitFn = RISCVState::GPRType (*)(RISCVState::GPRType lhs, RISCVState::GPRType rhs);
// Handles an instruction that takes two register inputs
static void BinaryBitInstruction(RISCVState& state, const uint32_t opcode, BinaryBitFn binary_fn) noexcept {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs1 = Bits<15, 19>(opcode);
const auto rs2 = Bits<20, 24>(opcode);
const auto lhs = state.GPR(rs1);
const auto rhs = state.GPR(rs2);
const auto result = binary_fn(lhs, rhs);
state.GPR(rd) = result;
}
// Handles an instruction that takes one register input and one immediate input
static void BinaryBitInstructionWithImm(RISCVState& state, const uint32_t opcode, BinaryBitFn binary_fn) noexcept {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs = Bits<15, 19>(opcode);
const auto imm = Bits<20, 25>(opcode);
const auto lhs = state.GPR(rs);
const auto result = binary_fn(lhs, imm);
state.GPR(rd) = result;
}
using ITypeFn = RISCVState::GPRType (*)(RISCVState::GPRType lhs, RISCVState::GPRType imm);
// Handles a RISC-V I-type instruction. Allows injecting different behavior through
// the imm_fn function parameter.
static void ITypeInstruction(RISCVState& state, const uint32_t opcode, ITypeFn imm_fn) noexcept {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs = Bits<15, 19>(opcode);
const auto& s = state.GPR(rs);
const auto imm = SignExtend<12, RISCVState::GPRType>(Bits<20, 31>(opcode));
const auto result = imm_fn(s, imm);
state.GPR(rd) = result;
}
using RTypeFn = RISCVState::GPRType (*)(RISCVState::GPRType lhs, RISCVState::GPRType rhs);
// Handles a RISC-V R-type instruction. Allows injecting different behavior through
// the reg_fn function parameter.
static void RTypeInstruction(RISCVState& state, const uint32_t opcode, RTypeFn reg_fn) noexcept {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs1 = Bits<15, 19>(opcode);
const auto rs2 = Bits<20, 24>(opcode);
const auto& s1 = state.GPR(rs1);
const auto& s2 = state.GPR(rs2);
const auto result = reg_fn(s1, s2);
state.GPR(rd) = result;
}
using CATypeFn = RISCVState::GPRType (*)(RISCVState::GPRType lhs, RISCVState::GPRType rhs);
// Handles a RISC-V CA-type instruction. Allows injecting different behavior through
// the ca_fn function parameter.
static void CATypeInstruction(RISCVState& state, const uint32_t opcode, CATypeFn ca_fn) noexcept {
const auto rds = ExpandCompressedRegisterIndex<7, 9>(opcode);
const auto rs = ExpandCompressedRegisterIndex<2, 4>(opcode);
const auto lhs = state.GPR(rds);
const auto rhs = state.GPR(rs);
const auto result = ca_fn(lhs, rhs);
state.GPR(rds) = result;
}
using CompressedArithImmTypeFn = RISCVState::GPRType (*)(RISCVState::GPRType lhs, RISCVState::GPRType rhs);
static void CompressedArithImmInstruction(RISCVState& state, const uint32_t opcode, CompressedArithImmTypeFn cai_fn) {
const auto rds = ExpandCompressedRegisterIndex<7, 9>(opcode);
const auto shift_amount = Bits<2, 6>(opcode) | (static_cast<uint32_t>(Bit<12>(opcode)) << 5);
const auto value = state.GPR(rds);
const auto result = cai_fn(value, shift_amount);
state.GPR(rds) = result;
}
void ADD(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs + rhs;
});
}
void ADDI(RISCVState& state, const uint32_t opcode) {
ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) {
return lhs + imm;
});
}
void ADDIW(RISCVState& state, const uint32_t opcode) {
ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) {
const auto result = static_cast<uint32_t>(lhs + imm);
return SignExtend<32, RISCVState::GPRType>(result);
});
}
void ADDW(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto result = static_cast<uint32_t>(lhs + rhs);
return SignExtend<32, RISCVState::GPRType>(result);
});
}
void ADD_UW(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return (lhs & 0xFFFFFFFFU) + rhs;
});
}
void AND(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs & rhs;
});
}
void ANDI(RISCVState& state, const uint32_t opcode) {
ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) {
return lhs & imm;
});
}
void ANDN(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs & ~rhs;
});
}
void AUIPC(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto imm = SignExtend<32, RISCVState::GPRType>(opcode & 0xFFFFF000);
const auto offset = imm + state.PC();
state.GPR(rd) = offset;
}
void BCLR(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
constexpr auto mask = BitSize<RISCVState::GPRType>() - 1;
const auto index = rhs & mask;
const auto bit = RISCVState::GPRType{1} << index;
return lhs & ~bit;
});
}
void BCLRI(RISCVState& state, const uint32_t opcode) {
BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto bit = RISCVState::GPRType{1} << rhs;
return lhs & ~bit;
});
}
void BEXT(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
constexpr auto mask = BitSize<RISCVState::GPRType>() - 1;
const auto index = rhs & mask;
const auto bit = lhs >> index;
return bit & 1;
});
}
void BEXTI(RISCVState& state, const uint32_t opcode) {
BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto bit = lhs >> rhs;
return bit & 1;
});
}
void BINV(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
constexpr auto mask = BitSize<RISCVState::GPRType>() - 1;
const auto index = rhs & mask;
const auto bit = RISCVState::GPRType{1} << index;
return lhs ^ bit;
});
}
void BINVI(RISCVState& state, const uint32_t opcode) {
BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto bit = RISCVState::GPRType{1} << rhs;
return lhs ^ bit;
});
}
void BSET(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
constexpr auto mask = BitSize<RISCVState::GPRType>() - 1;
const auto index = rhs & mask;
const auto bit = RISCVState::GPRType{1} << index;
return lhs | bit;
});
}
void BSETI(RISCVState& state, const uint32_t opcode) {
BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto bit = RISCVState::GPRType{1} << rhs;
return lhs | bit;
});
}
void C_ADD(RISCVState& state, const uint32_t opcode) {
const auto rds = Bits<7, 11>(opcode);
const auto rs = Bits<2, 6>(opcode);
const auto lhs = state.GPR(rds);
const auto rhs = state.GPR(rs);
const auto result = lhs + rhs;
state.GPR(rds) = result;
}
void C_ADDI(RISCVState& state, const uint32_t opcode) {
const auto rds = Bits<7, 11>(opcode);
const auto imm = Bits<2, 6>(opcode) | (static_cast<uint32_t>(Bit<12>(opcode)) << 5);
const auto simm = SignExtend<6, RISCVState::GPRType>(imm);
const auto result = state.GPR(rds) + simm;
state.GPR(rds) = result;
}
void C_ADDI4SPN(RISCVState& state, const uint32_t opcode) {
constexpr auto make_imm = [](const uint32_t op) {
// clang-format off
return ((op & 0x0020) >> 2) |
((op & 0x0040) >> 4) |
((op & 0x0780) >> 1) |
((op & 0x1800) >> 7);
// clang-format on
};
const auto rd = ExpandCompressedRegisterIndex<2, 4>(opcode);
const auto increment = make_imm(opcode);
const auto result = state.GPR(2) + increment;
state.GPR(rd) = result;
}
void C_ADDI16SP(RISCVState& state, const uint32_t opcode) {
constexpr auto make_imm = [](const uint32_t op) {
// clang-format off
return ((op & 0x0004) << 3) |
((op & 0x0018) << 4) |
((op & 0x0020) << 1) |
((op & 0x0040) >> 2) |
((op & 0x1000) >> 3);
// clang-format on
};
const auto imm = make_imm(opcode);
const auto increment = SignExtend<10, RISCVState::GPRType>(imm);
state.GPR(2) += increment;
}
void C_ADDIW(RISCVState& state, const uint32_t opcode) {
const auto rds = Bits<7, 11>(opcode);
const auto imm = Bits<2, 6>(opcode) | (static_cast<uint32_t>(Bit<12>(opcode)) << 5);
const auto simm = SignExtend<6, RISCVState::GPRType>(imm);
const auto sum = static_cast<uint32_t>(state.GPR(rds) + simm);
const auto result = SignExtend<32, RISCVState::GPRType>(sum);
state.GPR(rds) = result;
}
void C_ADDW(RISCVState& state, const uint32_t opcode) {
CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto add = static_cast<uint32_t>(lhs + rhs);
return SignExtend<32, RISCVState::GPRType>(add);
});
}
void C_AND(RISCVState& state, const uint32_t opcode) {
CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs & rhs;
});
}
void C_ANDI(RISCVState& state, const uint32_t opcode) {
CompressedArithImmInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs & SignExtend<6, RISCVState::GPRType>(rhs);
});
}
void C_LI(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
const auto imm = Bits<2, 6>(opcode) | (static_cast<uint32_t>(Bit<12>(opcode)) << 5);
const auto simm = SignExtend<6, RISCVState::GPRType>(imm);
state.GPR(rd) = simm;
}
void C_LUI(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
const auto imm = (Bits<2, 6>(opcode) << 12) | (static_cast<uint32_t>(Bit<12>(opcode)) << 17);
const auto simm = SignExtend<18, RISCVState::GPRType>(imm);
state.GPR(rd) = simm;
}
void C_MV(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
const auto rs = Bits<2, 6>(opcode);
state.GPR(rd) = state.GPR(rs);
}
void C_NOP([[maybe_unused]] RISCVState& state, [[maybe_unused]] const uint32_t opcode) {
// Do nothing.
}
void C_OR(RISCVState& state, const uint32_t opcode) {
CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs | rhs;
});
}
void C_SLLI(RISCVState& state, const uint32_t opcode) {
const auto rds = Bits<7, 11>(opcode);
const auto shift_amount = Bits<2, 6>(opcode) | (static_cast<uint32_t>(Bit<12>(opcode)) << 5);
const auto result = state.GPR(rds) << shift_amount;
state.GPR(rds) = result;
}
void C_SRAI(RISCVState& state, const uint32_t opcode) {
CompressedArithImmInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
using Signed = std::make_signed_t<RISCVState::GPRType>;
using Unsigned = RISCVState::GPRType;
const auto result_signed = static_cast<Signed>(lhs) >> rhs;
const auto result_unsigned = static_cast<Unsigned>(result_signed);
return result_unsigned;
});
}
void C_SRLI(RISCVState& state, const uint32_t opcode) {
CompressedArithImmInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs >> rhs;
});
}
void C_SUB(RISCVState& state, const uint32_t opcode) {
CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs - rhs;
});
}
void C_SUBW(RISCVState& state, const uint32_t opcode) {
CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto sub = static_cast<uint32_t>(lhs - rhs);
return SignExtend<32, RISCVState::GPRType>(sub);
});
}
void C_XOR(RISCVState& state, const uint32_t opcode) {
CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs ^ rhs;
});
}
void CLMUL(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
RISCVState::GPRType result{};
constexpr auto bit_size = BitSize<RISCVState::GPRType>();
for (size_t i = 0; i < bit_size; i++) {
if ((rhs & (1ULL << i)) == 0) {
continue;
}
result ^= lhs << i;
}
return result;
});
}
// Functional bits of a reversed carryless multiply.
// This is also used to implement CLMULH, since it's equivalent to performing
// a CLMULR and then shifting the result to the right by 1.
static RISCVState::GPRType CLMULRImpl(const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) noexcept {
RISCVState::GPRType result{};
constexpr auto bit_size = BitSize<RISCVState::GPRType>();
for (size_t i = 0; i < bit_size; i++) {
if ((rhs & (1ULL << i)) == 0) {
continue;
}
result ^= lhs >> (bit_size - i - 1);
}
return result;
}
void CLMULH(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return CLMULRImpl(lhs, rhs) >> 1;
});
}
void CLMULR(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
RISCVState::GPRType result{};
constexpr auto bit_size = BitSize<RISCVState::GPRType>();
for (size_t i = 0; i < bit_size; i++) {
if ((rhs & (1ULL << i)) == 0) {
continue;
}
result ^= lhs >> (bit_size - i - 1);
}
return result;
});
}
void CLZ(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
return static_cast<RISCVState::GPRType>(std::countl_zero(input));
});
}
void CLZW(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
return static_cast<RISCVState::GPRType>(std::countl_zero(static_cast<uint32_t>(input)));
});
}
void CPOP(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
return static_cast<RISCVState::GPRType>(std::popcount(input));
});
}
void CPOPW(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
return static_cast<RISCVState::GPRType>(std::popcount(static_cast<uint32_t>(input)));
});
}
void CTZ(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
return static_cast<RISCVState::GPRType>(std::countr_zero(input));
});
}
void CTZW(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
return static_cast<RISCVState::GPRType>(std::countr_zero(static_cast<uint32_t>(input)));
});
}
void LUI(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto imm = SignExtend<32, RISCVState::GPRType>(opcode & 0xFFFFF000);
state.GPR(rd) = imm;
}
void MAX(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
using Unsigned = RISCVState::GPRType;
using Signed = std::make_signed_t<Unsigned>;
const auto signed_lhs = static_cast<Signed>(lhs);
const auto signed_rhs = static_cast<Signed>(rhs);
const auto max_value = std::max(signed_lhs, signed_rhs);
return static_cast<Unsigned>(max_value);
});
}
void MAXU(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return std::max(lhs, rhs);
});
}
void MIN(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
using Unsigned = RISCVState::GPRType;
using Signed = std::make_signed_t<Unsigned>;
const auto signed_lhs = static_cast<Signed>(lhs);
const auto signed_rhs = static_cast<Signed>(rhs);
const auto max_value = std::min(signed_lhs, signed_rhs);
return static_cast<Unsigned>(max_value);
});
}
void MINU(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return std::min(lhs, rhs);
});
}
void OR(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs | rhs;
});
}
void ORC_B(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
static constexpr std::array byte_masks{
UINT64_C(0x00000000000000FF),
UINT64_C(0x000000000000FF00),
UINT64_C(0x0000000000FF0000),
UINT64_C(0x00000000FF000000),
UINT64_C(0x000000FF00000000),
UINT64_C(0x0000FF0000000000),
UINT64_C(0x00FF000000000000),
UINT64_C(0xFF00000000000000),
};
RISCVState::GPRType result = 0;
constexpr auto num_bytes = sizeof(RISCVState::GPRType);
for (size_t i = 0; i < num_bytes; i++) {
if ((input & byte_masks[i]) == 0) {
continue;
}
result |= byte_masks[i];
}
return result;
});
}
void ORI(RISCVState& state, const uint32_t opcode) {
ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) {
return lhs | imm;
});
}
void ORN(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs | ~rhs;
});
}
void REV8(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
return ByteSwap64(input);
});
}
void ROL(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
constexpr auto mask = BitSize<RISCVState::GPRType>() - 1;
const auto index = static_cast<int32_t>(rhs & mask);
return std::rotl(lhs, index);
});
}
void ROLW(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
constexpr auto mask = BitSize<RISCVState::GPRType>() - 1;
const auto index = static_cast<int32_t>(rhs & mask);
const auto result = std::rotl(static_cast<uint32_t>(lhs), index);
return SignExtend<32, RISCVState::GPRType>(result);
});
}
void ROR(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
constexpr auto mask = BitSize<RISCVState::GPRType>() - 1;
const auto index = static_cast<int32_t>(rhs & mask);
return std::rotr(lhs, index);
});
}
void RORI(RISCVState& state, const uint32_t opcode) {
BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto index = static_cast<int32_t>(rhs);
const auto result = std::rotr(lhs, index);
return result;
});
}
void RORIW(RISCVState& state, const uint32_t opcode) {
BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto index = static_cast<int32_t>(rhs);
const auto result = std::rotr(static_cast<uint32_t>(lhs), index);
return SignExtend<32, RISCVState::GPRType>(result);
});
}
void RORW(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
constexpr auto mask = BitSize<RISCVState::GPRType>() - 1;
const auto index = static_cast<int32_t>(rhs & mask);
const auto result = std::rotr(static_cast<uint32_t>(lhs), index);
return SignExtend<32, RISCVState::GPRType>(result);
});
}
void SEXT_B(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
return SignExtend<8, RISCVState::GPRType>(input & 0xFF);
});
}
void SEXT_H(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
return SignExtend<16, RISCVState::GPRType>(input & 0xFFFF);
});
}
void SH1ADD(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return (lhs << 1U) + rhs;
});
}
void SH1ADD_UW(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto index = RISCVState::GPRType{static_cast<uint32_t>(lhs)};
return (index << 1U) + rhs;
});
}
void SH2ADD(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return (lhs << 2U) + rhs;
});
}
void SH2ADD_UW(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto index = RISCVState::GPRType{static_cast<uint32_t>(lhs)};
return (index << 2U) + rhs;
});
}
void SH3ADD(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return (lhs << 3U) + rhs;
});
}
void SH3ADD_UW(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto index = RISCVState::GPRType{static_cast<uint32_t>(lhs)};
return (index << 3U) + rhs;
});
}
void SLL(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto shift_amount = rhs & 0b111111;
return lhs << shift_amount;
});
}
void SLLI(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs = Bits<15, 19>(opcode);
const auto shift_amount = Bits<20, 25>(opcode);
const auto& s = state.GPR(rs);
const auto result = s << shift_amount;
state.GPR(rd) = result;
}
void SLLIW(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs = Bits<15, 19>(opcode);
const auto shift_amount = Bits<20, 24>(opcode);
const auto& s = state.GPR(rs);
const auto shifted = static_cast<uint32_t>(s) << shift_amount;
const auto result = SignExtend<32, RISCVState::GPRType>(shifted);
state.GPR(rd) = result;
}
void SLLI_UW(RISCVState& state, const uint32_t opcode) {
BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto word = lhs & 0xFFFFFFFF;
return word << rhs;
});
}
void SLLW(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto shift_amount = rhs & 0b11111;
const auto shifted = static_cast<uint32_t>(lhs) << shift_amount;
return SignExtend<32, RISCVState::GPRType>(shifted);
});
}
void SLT(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
using Signed = std::make_signed_t<RISCVState::GPRType>;
using Unsigned = RISCVState::GPRType;
const auto result = static_cast<Signed>(lhs) < static_cast<Signed>(rhs);
return static_cast<Unsigned>(result);
});
}
void SLTI(RISCVState& state, const uint32_t opcode) {
ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) {
using Signed = std::make_signed_t<RISCVState::GPRType>;
const auto result = static_cast<Signed>(lhs) < static_cast<Signed>(imm);
return static_cast<RISCVState::GPRType>(result);
});
}
void SLTIU(RISCVState& state, const uint32_t opcode) {
ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) {
const auto result = lhs < imm;
return static_cast<RISCVState::GPRType>(result);
});
}
void SLTU(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto result = lhs < rhs;
return static_cast<RISCVState::GPRType>(result);
});
}
void SRA(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
using Signed = std::make_signed_t<RISCVState::GPRType>;
using Unsigned = RISCVState::GPRType;
const auto shift_amount = rhs & 0b111111;
const auto result = static_cast<Signed>(lhs) >> shift_amount;
return static_cast<Unsigned>(result);
});
}
void SRAI(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs = Bits<15, 19>(opcode);
const auto shift_amount = Bits<20, 25>(opcode);
using Signed = std::make_signed_t<RISCVState::GPRType>;
using Unsigned = RISCVState::GPRType;
const auto& s = state.GPR(rs);
const auto result = static_cast<Signed>(s) >> shift_amount;
state.GPR(rd) = static_cast<Unsigned>(result);
}
void SRAIW(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs = Bits<15, 19>(opcode);
const auto shift_amount = Bits<20, 25>(opcode);
const auto& s = state.GPR(rs);
const auto shifted = static_cast<uint32_t>(static_cast<int32_t>(s) >> shift_amount);
const auto result = SignExtend<32, RISCVState::GPRType>(shifted);
state.GPR(rd) = result;
}
void SRAW(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto shift_amount = rhs & 0b11111;
const auto shifted = static_cast<uint32_t>(static_cast<int32_t>(lhs) >> shift_amount);
return SignExtend<32, RISCVState::GPRType>(shifted);
});
}
void SRL(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto shift_amount = rhs & 0b111111;
return lhs >> shift_amount;
});
}
void SRLI(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs = Bits<15, 19>(opcode);
const auto shift_amount = Bits<20, 25>(opcode);
const auto& s = state.GPR(rs);
const auto result = s >> shift_amount;
state.GPR(rd) = result;
}
void SRLIW(RISCVState& state, const uint32_t opcode) {
const auto rd = Bits<7, 11>(opcode);
if (rd == 0) [[unlikely]] {
return;
}
const auto rs = Bits<15, 19>(opcode);
const auto shift_amount = Bits<20, 25>(opcode);
const auto& s = state.GPR(rs);
const auto shifted = static_cast<uint32_t>(s) >> shift_amount;
const auto result = SignExtend<32, RISCVState::GPRType>(shifted);
state.GPR(rd) = result;
}
void SRLW(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto shift_amount = rhs & 0b11111;
const auto shift = static_cast<uint32_t>(lhs) >> shift_amount;
return SignExtend<32, RISCVState::GPRType>(shift);
});
}
void SUB(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs - rhs;
});
}
void SUBW(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
const auto sub = static_cast<uint32_t>(lhs - rhs);
return SignExtend<32, RISCVState::GPRType>(sub);
});
}
void XNOR(RISCVState& state, const uint32_t opcode) {
BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return ~(lhs ^ rhs);
});
}
void XOR(RISCVState& state, const uint32_t opcode) {
RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) {
return lhs ^ rhs;
});
}
void XORI(RISCVState& state, const uint32_t opcode) {
ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) {
return lhs ^ imm;
});
}
void ZEXT_H(RISCVState& state, const uint32_t opcode) {
UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) {
return input & 0xFFFF;
});
}
} // namespace riscy
| 34.236982 | 118 | 0.660055 | lioncash |
015443921d65bc1db235a2359a9a93972df22e2d | 1,232 | cpp | C++ | examples/future_types/promises.cpp | alandefreitas/futures | 326957b2bc4238716faecd7a5bff4616d967b4ce | [
"MIT"
] | 10 | 2022-01-07T02:20:54.000Z | 2022-03-11T05:24:13.000Z | examples/future_types/promises.cpp | alandefreitas/futures | 326957b2bc4238716faecd7a5bff4616d967b4ce | [
"MIT"
] | null | null | null | examples/future_types/promises.cpp | alandefreitas/futures | 326957b2bc4238716faecd7a5bff4616d967b4ce | [
"MIT"
] | null | null | null | #include <futures/algorithm.hpp>
#include <futures/futures.hpp>
#include <futures/executor/new_thread_executor.hpp>
#include <iostream>
int
main() {
using namespace futures;
//[inline Inline promise
promise<int> p1;
cfuture<int> f1 = p1.get_future();
p1.set_value(2);
std::cout << f1.get() << '\n';
//]
//[thread Promise set by new thread
promise<int> p2;
cfuture<int> f2 = p2.get_future();
std::thread t2([&p2]() {
p2.set_value(2);
});
std::cout << f2.get() << '\n';
t2.join();
//]
//[thread-executor Promise set by new thread executor
auto f3 = async(make_new_thread_executor(), []() {
return 2;
});
std::cout << f3.get() << '\n';
//]
//[thread_pool Promise set by thread pool
promise<int> p4;
cfuture<int> f4 = p4.get_future();
asio::thread_pool pool(1);
asio::post(pool, [&p4]() {
p4.set_value(2);
});
std::cout << f4.get() << '\n';
//]
//[custom_options Promise with custom options
promise<int, future_options<>> p5;
vfuture<int> f5 = p5.get_future();
std::thread t5([&p5]() {
p5.set_value(2);
});
std::cout << f5.get() << '\n';
t5.join();
//]
} | 23.245283 | 57 | 0.553571 | alandefreitas |
0158305873ffccd56f72565a3b3ed3305923a407 | 370 | cpp | C++ | OJ/PT/PT16.cpp | doan201203/truong_doan | 68350b7a24ea266320cd41e1a4878e8a58b3f707 | [
"Apache-2.0"
] | null | null | null | OJ/PT/PT16.cpp | doan201203/truong_doan | 68350b7a24ea266320cd41e1a4878e8a58b3f707 | [
"Apache-2.0"
] | null | null | null | OJ/PT/PT16.cpp | doan201203/truong_doan | 68350b7a24ea266320cd41e1a4878e8a58b3f707 | [
"Apache-2.0"
] | null | null | null | #include<stdio.h>
int main(){
int N[100000], n, count = 0, kt;
scanf("%d", &n);
for(int i = 1 ; i <= n ; i++ ){
scanf("%d", &N[i]);
}
for(int i = 1 ; i <= n ; i++){
kt = N[i] % 19;
if(kt == 0 || kt == 3 || kt == 6 || kt == 9 || kt == 11 || kt == 14 || kt == 17){
count++;
}
}
printf("%d", count);
} | 24.666667 | 89 | 0.337838 | doan201203 |
0158d2856b65209b7976459ad302259436420369 | 2,278 | hpp | C++ | include/game.hpp | vvbv/AlphaZero-Univalle | eb4ba2253ea266e3c5cad2cee24401ff95073c23 | [
"MIT"
] | null | null | null | include/game.hpp | vvbv/AlphaZero-Univalle | eb4ba2253ea266e3c5cad2cee24401ff95073c23 | [
"MIT"
] | null | null | null | include/game.hpp | vvbv/AlphaZero-Univalle | eb4ba2253ea266e3c5cad2cee24401ff95073c23 | [
"MIT"
] | 1 | 2018-06-20T19:15:14.000Z | 2018-06-20T19:15:14.000Z | #ifndef GAME_HPP_
#define GAME_HPP_
#include "board.hpp"
#include "state_game.hpp"
#include <climits>
#include <tuple>
class Game{
private:
int max_depth;
struct minmax_game_elements {
int pos_max_row;
int pos_max_column;
int pos_min_row;
int pos_min_column;
int min_items_quantity;
int max_items_quantity;
int depth;
Board board;
};
struct index_in_non_dynamic_expansions{
int index;
};
Board board;
int items_to_collect;
int items_collected_by_human;
int items_collected_by_pc;
enum Action { up_right, up_left, left_up, left_down, down_left, down_right, right_down, right_up };
bool compare_minmax_game_elements( minmax_game_elements *a, minmax_game_elements *b );
State_game max_move( State_game state, std::vector < State_game > previous_moves_x );
State_game min_move( State_game state, std::vector < State_game > previous_moves_x );
State_game get_pos_up_right( State_game state, int current_pos[2], bool is_max );
State_game get_pos_up_left( State_game state, int current_pos[2], bool is_max );
State_game get_pos_left_up( State_game state, int current_pos[2], bool is_max );
State_game get_pos_left_down( State_game state, int current_pos[2], bool is_max );
State_game get_pos_down_left( State_game state, int current_pos[2], bool is_max );
State_game get_pos_down_right( State_game state, int current_pos[2], bool is_max );
State_game get_pos_right_down( State_game state, int current_pos[2], bool is_max );
State_game get_pos_right_up( State_game state, int current_pos[2], bool is_max );
bool game_ended( State_game state );
bool states_equals( State_game a, State_game b, bool is_max );
void print_game( State_game game );
public:
Game();
~Game();
void set_board( Board board );
void set_items_to_collect( int items_quantity );
Board get_board();
void start_new_game( Board board, int max_depth );
void start_new_game();
};
#endif | 36.741935 | 108 | 0.64662 | vvbv |
015fb70636b9c7727e0ce79f8acaa0cb0e1496e4 | 5,398 | cpp | C++ | engine/src/Core/AppStatus.cpp | MajesticShekel/Strontium | e672e4f7ee0338ef4e29ac61dad3f10905e8d105 | [
"MIT"
] | null | null | null | engine/src/Core/AppStatus.cpp | MajesticShekel/Strontium | e672e4f7ee0338ef4e29ac61dad3f10905e8d105 | [
"MIT"
] | null | null | null | engine/src/Core/AppStatus.cpp | MajesticShekel/Strontium | e672e4f7ee0338ef4e29ac61dad3f10905e8d105 | [
"MIT"
] | null | null | null | #include "Core/AppStatus.h"
appStatus defaultEditorStatus =
{
{
{ "KEY_UNKNOWN", -1 },
{ "KEY_SPACE", 32 },
{ "KEY_APOSTROPHE", 39 },
{ "KEY_COMMA", 44 },
{ "KEY_MINUS", 45 },
{ "KEY_PERIOD", 46 },
{ "KEY_SLASH", 47 },
{ "KEY_0", 48 },
{ "KEY_1", 49 },
{ "KEY_2", 50 },
{ "KEY_3", 51 },
{ "KEY_4", 52 },
{ "KEY_5", 53 },
{ "KEY_6", 54 },
{ "KEY_7", 55 },
{ "KEY_8", 56 },
{ "KEY_9", 57 },
{ "KEY_SEMICOLON", 59 },
{ "KEY_EQUAL", 61 },
{ "KEY_A", 65 },
{ "KEY_B", 66 },
{ "KEY_C", 67 },
{ "KEY_D", 68 },
{ "KEY_E", 69 },
{ "KEY_F", 70 },
{ "KEY_G", 71 },
{ "KEY_H", 72 },
{ "KEY_I", 73 },
{ "KEY_J", 74 },
{ "KEY_K", 75 },
{ "KEY_L", 76 },
{ "KEY_M", 77 },
{ "KEY_N", 78 },
{ "KEY_O", 79 },
{ "KEY_P", 80 },
{ "KEY_Q", 81 },
{ "KEY_R", 82 },
{ "KEY_S", 83 },
{ "KEY_T", 84 },
{ "KEY_U", 85 },
{ "KEY_V", 86 },
{ "KEY_W", 87 },
{ "KEY_X", 88 },
{ "KEY_Y", 89 },
{ "KEY_Z", 90 },
{ "KEY_LEFT_BRACKET", 91 },
{ "KEY_BACKSLASH", 92 },
{ "KEY_RIGHT_BRACKET", 93 },
{ "KEY_GRAVE_ACCENT", 96 },
{ "KEY_WORLD_1", 161 },
{ "KEY_WORLD_2", 162 },
{ "KEY_ESCAPE", 256 },
{ "KEY_ENTER", 257 },
{ "KEY_TAB", 258 },
{ "KEY_BAKCSPACE", 259 },
{ "KEY_INSERT", 260 },
{ "KEY_DELETE", 261 },
{ "KEY_RIGHT", 262 },
{ "KEY_LEFT", 263 },
{ "KEY_DOWN", 264 },
{ "KEY_UP", 265 },
{ "KEY_PAGE_DOWN", 266 },
{ "KEY_PAGE_UP", 267 },
{ "KEY_HOME", 268 },
{ "KEY_END", 269 },
{ "KEY_CAPS_LOCK", 280 },
{ "KEY_SCROLL_LOCK", 281 },
{ "KEY_NUM_LOCK", 282 },
{ "KEY_PRINT_SCREEN", 283 },
{ "KEY_PAUSE", 284 },
{ "KEY_F1", 290 },
{ "KEY_F2", 291 },
{ "KEY_F3", 292 },
{ "KEY_F4", 293 },
{ "KEY_F5", 294 },
{ "KEY_F6", 295 },
{ "KEY_F7", 296 },
{ "KEY_F8", 297 },
{ "KEY_F9", 298 },
{ "KEY_F10", 299 },
{ "KEY_F11", 300 },
{ "KEY_F12", 301 },
{ "KEY_F13", 302 },
{ "KEY_F14", 303 },
{ "KEY_F15", 304 },
{ "KEY_F16", 305 },
{ "KEY_F17", 306 },
{ "KEY_F18", 307 },
{ "KEY_F19", 308 },
{ "KEY_F20", 309 },
{ "KEY_F21", 310 },
{ "KEY_F22", 311 },
{ "KEY_F23", 312 },
{ "KEY_F24", 313 },
{ "KEY_F25", 314 },
{ "KEY_KP_0", 320 },
{ "KEY_KP_1", 321 },
{ "KEY_KP_2", 322 },
{ "KEY_KP_3", 323 },
{ "KEY_KP_4", 324 },
{ "KEY_KP_5", 325 },
{ "KEY_KP_6", 326 },
{ "KEY_KP_7", 327 },
{ "KEY_KP_8", 328 },
{ "KEY_KP_9", 329 },
{ "KEY_KP_DECIMAL", 330 },
{ "KEY_KP_DIVIDE", 331 },
{ "KEY_KP_MULTIPLY", 332 },
{ "KEY_KP_SUBTRACT", 333 },
{ "KEY_KP_ADD", 334 },
{ "KEY_KP_ENTER", 335 },
{ "KEY_KP_EQUAL", 336 },
{ "KEY_LEFT_SHIFT", 340 },
{ "KEY_LEFT_CONTROL", 341 },
{ "KEY_LEFT_ALT", 342 },
{ "KEY_LEFT_SUPER", 343 },
{ "KEY_RIGHT_SHIFT", 344 },
{ "KEY_RIGHT_CONTROL", 345 },
{ "KEY_RIGHT_ALT", 346 },
{ "KEY_RIGHT_SUPER", 347 },
{ "KEY_MENU", 348 },
{ "KEY_LAST", 348 },
/*! @defgroup mods Modifier key flags
* @brief Modifier key flags.
*
* See [key input](@ref input_key) for how these are used.
*
* @ingroup input
* @{ */
/*! @brief If this bit is set one or more Shift keys were held down.
*
* If this bit is set one or more Shift keys were held down.
*/
{ "MOD_SHIFT", 0x0001 },
/*! @brief If this bit is set one or more Control keys were held down.
*
* If this bit is set one or more Control keys were held down.
*/
{ "MOD_CONTROL", 0x0002 },
/*! @brief If this bit is set one or more Alt keys were held down.
*
* If this bit is set one or more Alt keys were held down.
*/
{ "MOD_ALT", 0x0004 },
/*! @brief If this bit is set one or more Super keys were held down.
*
* If this bit is set one or more Super keys were held down.
*/
{ "MOD_SUPER", 0x0008 },
/*! @brief If this bit is set the Caps Lock key is enabled.
*
* If this bit is set the Caps Lock key is enabled and the @ref
* SR_LOCK_KEY_MODS input mode is set.
*/
{ "MOD_CAPS_LOCK", 0x0010 },
/*! @brief If this bit is set the Num Lock key is enabled.
*
* If this bit is set the Num Lock key is enabled and the @ref
* SR_LOCK_KEY_MODS input mode is set.
*/
{ "MOD_NUM_LOCK", 0x0020 },
/*! @} */
/*! @defgroup buttons Mouse buttons
* @brief Mouse button IDs.
*
* See [mouse button input](@ref input_mouse_button) for how these are used.
*
* @ingroup input
* @{ */
{ "MOUSE_BUTTON_1", 0 },
{ "MOUSE_BUTTON_2", 1 },
{ "MOUSE_BUTTON_3", 2 },
{ "MOUSE_BUTTON_4", 3 },
{ "MOUSE_BUTTON_5", 4 },
{ "MOUSE_BUTTON_6", 5 },
{ "MOUSE_BUTTON_7", 6 },
{ "MOUSE_BUTTON_8", 7 },
{ "MOUSE_BUTTON_LAST", 7 },
{ "MOUSE_BUTTON_LEFT", 0 },
{ "MOUSE_BUTTON_RIGHT", 1 },
{ "MOUSE_BUTTON_MIDDLE", 2 }
},
//windows
{
{ "AssetBrowserWindow", true },
{ "CameraWindow", true },
{ "FileBrowserWindow", true },
{ "GuiWindow", true },
{ "ModelWindow", false },
{ "RendererWindow", true },
{ "ShaderWindow", true },
{ "ViewportWindow", true }
},
//editor camera settings
{
{0, 1, 4},
{0, 0, -1},
90, 0.1, 200, 2.5, 0.1
}
};
appStatus editorStatus = { };
/*std::map<std::string, std::pair<std::any, std::string>> camData::toMap()
{
return
{
{ "Position", position },
{ "Front", front },
{ "FOV", fov },
{ "Near", near },
{ "Far", far },
{ "Speed", speed },
{ "Sensitivity", sens }
};
}*/
| 22.491667 | 79 | 0.524639 | MajesticShekel |
0162b501d7b3cd246245f560572d30c8091d75cc | 1,101 | cpp | C++ | LeetCode/Problems/Algorithms/#658_FindKClosestElements_sol1_binary_search_and_two_pointers_approach_O(logN+K)_time_O(1)_extra_space_32ms_30.8MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#658_FindKClosestElements_sol1_binary_search_and_two_pointers_approach_O(logN+K)_time_O(1)_extra_space_32ms_30.8MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#658_FindKClosestElements_sol1_binary_search_and_two_pointers_approach_O(logN+K)_time_O(1)_extra_space_32ms_30.8MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
const int N = arr.size();
// Step 1: binary search the (lower_bound) position of x in arr
int xPos = lower_bound(arr.begin(), arr.end(), x) - arr.begin();
xPos = min(N - 1, xPos);
if(xPos - 1 >= 0 && xPos <= N - 1 && abs(arr[xPos - 1] - x) <= abs(arr[xPos] - x)){
xPos -= 1;
}
// Step 2 (two pointers approach):
// expand [startPos, endPos] range including closest integers to x
int startPos = xPos;
int endPos = xPos;
while(endPos - startPos + 1 < k){
if(startPos == 0){
endPos += 1;
}else if(endPos == N - 1){
startPos -= 1;
}else if(abs(arr[startPos - 1] - x) <= abs(arr[endPos + 1] - x)){
startPos -= 1;
}else{
endPos += 1;
}
}
return vector<int>(arr.begin() + startPos, arr.begin() + endPos + 1);
}
}; | 35.516129 | 92 | 0.448683 | Tudor67 |
0166081927ed5e32c9e1002953709b8a5d537a90 | 437 | cpp | C++ | PAT/B1008.cpp | iphelf/Programming-Practice | 2a95bb7153957b035427046b250bf7ffc6b00906 | [
"WTFPL"
] | null | null | null | PAT/B1008.cpp | iphelf/Programming-Practice | 2a95bb7153957b035427046b250bf7ffc6b00906 | [
"WTFPL"
] | null | null | null | PAT/B1008.cpp | iphelf/Programming-Practice | 2a95bb7153957b035427046b250bf7ffc6b00906 | [
"WTFPL"
] | null | null | null | #include<stdio.h>
#include<algorithm>
using namespace std;
const int MAXN=100;
int a[MAXN];
int main(void) {
// freopen("in.txt","r",stdin);
int N;
long long M;
scanf("%d%lld",&N,&M);
for(int i=0;i<N;i++) scanf("%d",&a[i]);
M=M%N;
reverse(a,a+N-M);
reverse(a+N-M,a+N);
reverse(a,a+N);
for(int i=0;i<N;i++) printf("%d%c",a[i],i==N-1?'\n':' ');
return 0;
}
/*
6 2
1 2 3 4 5 6
5 6 1 2 3 4
*/
| 15.068966 | 61 | 0.510297 | iphelf |
0166fb1d2f6af68b9d32f6594b2a0ce4cdfa1be2 | 1,041 | hpp | C++ | EasyFramework3d/core/gui/ButtonEvent.hpp | sizilium/FlexChess | f12b94e800ddcb00535067eca3b560519c9122e0 | [
"MIT"
] | null | null | null | EasyFramework3d/core/gui/ButtonEvent.hpp | sizilium/FlexChess | f12b94e800ddcb00535067eca3b560519c9122e0 | [
"MIT"
] | null | null | null | EasyFramework3d/core/gui/ButtonEvent.hpp | sizilium/FlexChess | f12b94e800ddcb00535067eca3b560519c9122e0 | [
"MIT"
] | null | null | null | /**
* @file ButtonEvent.hpp
* @author sizilium
* @date 26.12.2007
* @brief This file is part of the Vision Synthesis Easy Framework.\n
* This file has no copyright; you can change everything.
* Visit www.vision-synthesis.de or www.easy-framework.de for further informations.\n
* If there is a bug please send a mail to bug@vision-synthesis.de. No warranty is given!
*/
#ifndef BUTTON_EVENT_H
#define BUTTON_EVENT_H
// includes
#include <vs/Build.hpp>
#include <vs/base/interfaces/Event.hpp>
#include <string>
namespace vs
{
namespace core
{
namespace gui
{
/** @class ButtonEvent
*
*/
class VS_EXPORT ButtonEvent : public base::interfaces::Event
{
public:
ButtonEvent(const std::string &name, int x, int y)
:base::interfaces::Event(base::interfaces::Event::GuiEvent), name(name), x(x), y(y)
{}
std::string getName() const
{
return name;
}
void getClickCoords(int &x, int &y) const
{
x = this->x;
y = this->y;
}
private:
std::string name;
int x, y;
};
} // gui
} // core
} // vs
#endif // BUTTON_EVENT_H
| 18.263158 | 89 | 0.68684 | sizilium |
016803f139985567256a115aae95e6d70b3971f6 | 550 | hpp | C++ | include/Particles/TriangularPrism.hpp | mtortora/chiralDFT | d5ea5e940d6bc72d96fd9728d042de1e09d3ef85 | [
"MIT"
] | 2 | 2018-01-03T09:33:09.000Z | 2019-06-14T13:29:37.000Z | include/Particles/TriangularPrism.hpp | mtortora/chiralDFT | d5ea5e940d6bc72d96fd9728d042de1e09d3ef85 | [
"MIT"
] | null | null | null | include/Particles/TriangularPrism.hpp | mtortora/chiralDFT | d5ea5e940d6bc72d96fd9728d042de1e09d3ef85 | [
"MIT"
] | null | null | null | #ifndef TRIANGULAR_PRISM_HPP_
#define TRIANGULAR_PRISM_HPP_
#include "rapid2/RAPID.H"
#include "BaseParticle.hpp"
template<typename number>
class TriangularPrism: public BaseParticle<number>
{
public:
TriangularPrism();
~TriangularPrism() {delete Mesh;}
RAPID_model* Mesh;
void Build(int) override;
void Tesselate(const Matrix3X<number>&);
void Parse(std::mt19937_64&, ArrayX<uint>&) override {}
private:
number L_X_;
number L_Y_;
number L_Z_;
number TWIST_;
number GAMMA_;
void SaveMesh(const Matrix3X<number>&);
};
#endif
| 16.666667 | 56 | 0.747273 | mtortora |
6c69bc5b037960781c1885b8ba02cc6577ef3ff3 | 885 | hpp | C++ | stringify/container_traits.hpp | 5cript/SimpleJSON | 878a6341baed91c29630447f6bd480391f563045 | [
"MIT"
] | 4 | 2015-06-25T02:06:13.000Z | 2018-07-11T13:20:24.000Z | stringify/container_traits.hpp | 5cript/SimpleJSON | 878a6341baed91c29630447f6bd480391f563045 | [
"MIT"
] | 14 | 2015-03-29T10:32:21.000Z | 2018-01-25T16:45:08.000Z | stringify/container_traits.hpp | 5cript/SimpleJSON | 878a6341baed91c29630447f6bd480391f563045 | [
"MIT"
] | 2 | 2017-07-16T09:43:22.000Z | 2020-08-30T09:33:40.000Z | #pragma once
// and iterator traits :D
#include <iterator>
#include <type_traits>
template <typename T, template <typename, class = std::allocator <T> > class ContainerT>
struct has_random_access_iterator : std::is_same <
typename std::iterator_traits<typename ContainerT<T>::iterator>::iterator_category
, std::random_access_iterator_tag>
{};
template <typename T, template <typename, class = std::allocator <T> > class ContainerT>
struct has_bidirectional_iterator : std::is_same <
typename std::iterator_traits<typename ContainerT<T>::iterator>::iterator_category
, std::bidirectional_iterator_tag>
{};
template <typename T, template <typename, class = std::allocator <T> > class ContainerT>
struct has_forward_iterator : std::is_same <
typename std::iterator_traits<typename ContainerT<T>::iterator>::iterator_category
, std::forward_iterator_tag>
{};
| 35.4 | 88 | 0.757062 | 5cript |
6c6aaa6a485e39b792983c293ac84c7384ebb0bd | 3,427 | hpp | C++ | include/jwt/error_codes.hpp | ValBaturin/cpp-jwt | 8272256dd0105e2e66838dc081e30e638966ca12 | [
"MIT"
] | 324 | 2017-12-27T09:57:20.000Z | 2022-03-30T15:43:27.000Z | include/jwt/error_codes.hpp | ValBaturin/cpp-jwt | 8272256dd0105e2e66838dc081e30e638966ca12 | [
"MIT"
] | 68 | 2018-01-28T15:08:11.000Z | 2021-10-16T15:59:06.000Z | include/jwt/error_codes.hpp | ValBaturin/cpp-jwt | 8272256dd0105e2e66838dc081e30e638966ca12 | [
"MIT"
] | 100 | 2018-01-04T08:09:14.000Z | 2021-12-02T13:37:37.000Z | /*
Copyright (c) 2017 Arun Muralidharan
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 CPP_JWT_ERROR_CODES_HPP
#define CPP_JWT_ERROR_CODES_HPP
#include <system_error>
namespace jwt {
/**
* All the algorithm errors
*/
enum class AlgorithmErrc
{
SigningErr = 1,
VerificationErr,
KeyNotFoundErr,
InvalidKeyErr,
NoneAlgorithmUsed, // Not an actual error!
};
/**
* Algorithm error conditions
* TODO: Remove it or use it!
*/
enum class AlgorithmFailureSource
{
};
/**
* Decode error conditions
*/
enum class DecodeErrc
{
// No algorithms provided in decode API
EmptyAlgoList = 1,
// The JWT signature has incorrect format
SignatureFormatError,
// The JSON library failed to parse
JsonParseError,
// Algorithm field in header is missing
AlgHeaderMiss,
// Type field in header is missing
TypHeaderMiss,
// Unexpected type field value
TypMismatch,
// Found duplicate claims
DuplClaims,
// Key/Secret not passed as decode argument
KeyNotPresent,
// Key/secret passed as argument for NONE algorithm.
// Not a hard error.
KeyNotRequiredForNoneAlg,
};
/**
* Errors handled during verification process.
*/
enum class VerificationErrc
{
//Algorithms provided does not match with header
InvalidAlgorithm = 1,
//Token is expired at the time of decoding
TokenExpired,
//The issuer specified does not match with payload
InvalidIssuer,
//The subject specified does not match with payload
InvalidSubject,
//The field IAT is not present or is of invalid type
InvalidIAT,
//Checks for the existence of JTI
//if validate_jti is passed in decode
InvalidJTI,
//The audience specified does not match with payload
InvalidAudience,
//Decoded before nbf time
ImmatureSignature,
//Signature match error
InvalidSignature,
// Invalid value type used for known claims
TypeConversionError,
};
/**
*/
std::error_code make_error_code(AlgorithmErrc err);
/**
*/
std::error_code make_error_code(DecodeErrc err);
/**
*/
std::error_code make_error_code(VerificationErrc err);
} // END namespace jwt
/**
* Make the custom enum classes as error code
* adaptable.
*/
namespace std
{
template <>
struct is_error_code_enum<jwt::AlgorithmErrc> : true_type {};
template <>
struct is_error_code_enum<jwt::DecodeErrc>: true_type {};
template <>
struct is_error_code_enum<jwt::VerificationErrc>: true_type {};
}
#include "jwt/impl/error_codes.ipp"
#endif
| 25.014599 | 78 | 0.753137 | ValBaturin |
6c735b5cb0eae44b95032cc897c039a77ac1fa01 | 12,875 | cpp | C++ | Doom/src/Doom/Components/Render3D.cpp | Shturm0weak/OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 126 | 2020-10-20T21:39:53.000Z | 2022-01-25T14:43:44.000Z | Doom/src/Doom/Components/Render3D.cpp | Shturm0weak/2D_OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 2 | 2021-01-07T17:29:19.000Z | 2021-08-14T14:04:28.000Z | Doom/src/Doom/Components/Render3D.cpp | Shturm0weak/2D_OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 16 | 2021-01-09T09:08:40.000Z | 2022-01-25T14:43:46.000Z | #include "../pch.h"
#include "Render3D.h"
#include "../Core/Editor.h"
#include "../Render/Instancing.h"
#include "../Components/PointLight.h"
using namespace Doom;
void Renderer3D::ChangeRenderTechnic(RenderTechnic rt)
{
if (m_IsTransparent) return;
if (rt == RenderTechnic::Instancing)
{
for (auto i = Instancing::GetInstance()->m_InstancedObjects.begin(); i != Instancing::GetInstance()->m_InstancedObjects.end(); i++)
{
if (i->first == m_Mesh)
{
auto iterFind = std::find(i->second.begin(), i->second.end(), this);
if (iterFind == i->second.end())
{
i->second.push_back(this);
auto iter = std::find(Renderer::s_Objects3d.begin(), Renderer::s_Objects3d.end(), this);
if (iter != Renderer::s_Objects3d.end())
Renderer::s_Objects3d.erase(iter);
}
}
}
}
else if (rt == RenderTechnic::Forward)
{
EraseFromInstancing();
auto iter = std::find(Renderer::s_Objects3d.begin(), Renderer::s_Objects3d.end(), this);
if (iter == Renderer::s_Objects3d.end())
{
m_Shader = Shader::Get("Default3D");
Renderer::s_Objects3d.push_back(this);
}
}
m_RenderTechnic = rt;
}
void Renderer3D::LoadMesh(Mesh* mesh)
{
EraseFromInstancing();
m_Mesh = mesh;
ChangeRenderTechnic(m_RenderTechnic);
if (m_Mesh != nullptr && !m_IsSkyBox)
{
CubeCollider3D* cc = m_OwnerOfCom->m_ComponentManager.GetComponent<CubeCollider3D>();
if (cc == nullptr)
{
cc = m_OwnerOfCom->m_ComponentManager.AddComponent<CubeCollider3D>();
cc->m_IsBoundingBox = true;
}
cc->m_MinP = m_Mesh->m_TheLowestPoint;
cc->m_MaxP = m_Mesh->m_TheHighestPoint;
cc->m_Offset = ((cc->m_MaxP - cc->m_MinP) * 0.5f) + cc->m_MinP;
}
m_Tr = m_OwnerOfCom->m_ComponentManager.GetComponent<Transform>();
//std::cout << "offset " << cc->offset.x << " " << cc->offset.y << " " << cc->offset.z << "\n";
//std::cout << "the highest " << mesh->theHighestPoint.x << " " << mesh->theHighestPoint.y << " " << mesh->theHighestPoint.z << "\n";
//std::cout << "the lowest " << mesh->theLowestPoint.x << " " << mesh->theLowestPoint.y << " " << mesh->theLowestPoint.z << "\n";
}
void Renderer3D::operator=(const Renderer3D& rhs)
{
Copy(rhs);
}
void Renderer3D::EraseFromInstancing()
{
if (m_RenderTechnic == RenderTechnic::Instancing)
{
for (auto i = Instancing::GetInstance()->m_InstancedObjects.begin(); i != Instancing::GetInstance()->m_InstancedObjects.end(); i++)
{
if (m_Mesh != nullptr)
{
auto iter = std::find(i->second.begin(), i->second.end(), this);
if (iter != i->second.end())
{
i->second.erase(iter);
m_IsInitializedInInstancing = false;
//m_Mesh = nullptr;
}
}
}
}
}
Renderer3D::Renderer3D(const Renderer3D& rhs)
{
Copy(rhs);
}
Renderer3D::Renderer3D()
{
m_RenderType = RenderType::TYPE_3D;
//SetType(ComponentType::RENDER3D);
m_Shader = Shader::Get("Default3D");
m_DiffuseTexture = Texture::s_WhiteTexture;
m_NormalMapTexture = Texture::Get("InvalidTexture");
}
Renderer3D::~Renderer3D()
{
}
void Renderer3D::Delete()
{
s_FreeMemory.push_back(m_MemoryPoolPtr);
if (m_OwnerOfCom == nullptr) return;
CubeCollider3D* cc = m_OwnerOfCom->m_ComponentManager.GetComponent<CubeCollider3D>();
if (cc != nullptr && cc->m_IsBoundingBox)
m_OwnerOfCom->m_ComponentManager.RemoveComponent(cc); //Fix: could be dangerous if there is more than 1 CubeCollider
if (m_IsTransparent)
{
auto iter = std::find(Renderer::s_Objects3dTransparent.begin(), Renderer::s_Objects3dTransparent.end(), this);
if (iter != Renderer::s_Objects3dTransparent.end())
Renderer::s_Objects3dTransparent.erase(iter);
}
else
{
ChangeRenderTechnic(RenderTechnic::Forward);
auto iter = std::find(Renderer::s_Objects3d.begin(), Renderer::s_Objects3d.end(), this);
if (iter != Renderer::s_Objects3d.end())
Renderer::s_Objects3d.erase(iter);
}
this->Copy(Renderer3D());
}
Component* Renderer3D::Create()
{
char* ptr = Utils::PreAllocateMemory<Renderer3D>(s_MemoryPool, s_FreeMemory);
Renderer3D* component = (Renderer3D*)((void*)ptr);
component->m_MemoryPoolPtr = ptr;
if (component->m_IsTransparent) Renderer::s_Objects3dTransparent.push_back(component);
else Renderer::s_Objects3d.push_back(component);
component->m_Mesh = nullptr;
return component;
}
#include "../Core/Timer.h"
#include "DirectionalLight.h"
void Renderer3D::BakeShadows()
{
if (m_IsCastingShadows && m_Mesh != nullptr && m_Mesh->m_IsInitialized)
{
if (!m_IsSkyBox)
{
Shader* bakeShader = Shader::Get("BakeShadows");
bakeShader->Bind();
glBindTextureUnit(0, m_DiffuseTexture->m_RendererID);
bakeShader->SetUniformMat4f("u_Model", m_Tr->m_PosMat4);
bakeShader->SetUniformMat4f("lightSpaceMatrix", DirectionalLight::GetLightSpaceMatrix());
bakeShader->SetUniformMat4f("u_Scale", m_Tr->m_ScaleMat4);
bakeShader->SetUniformMat4f("u_View", m_Tr->m_ViewMat4);
bakeShader->Bind();
m_Mesh->m_Va.Bind();
m_Mesh->m_Ib.Bind();
m_Mesh->m_Vb.Bind();
Renderer::s_Stats.m_Vertices += m_Mesh->m_IndicesSize;
Renderer::s_Stats.m_DrawCalls++;
glDrawElements(GL_TRIANGLES, m_Mesh->m_Ib.m_count, GL_UNSIGNED_INT, nullptr);
bakeShader->UnBind();
m_Mesh->m_Ib.UnBind();
glBindTextureUnit(0, Texture::s_WhiteTexture->m_RendererID);
}
}
}
void Renderer3D::MakeTransparent()
{
auto iter = std::find(Renderer::s_Objects3d.begin(), Renderer::s_Objects3d.end(), this);
if(iter != Renderer::s_Objects3d.end())
{
EraseFromInstancing();
ChangeRenderTechnic(RenderTechnic::Forward);
Renderer::s_Objects3d.erase(iter);
Renderer::s_Objects3dTransparent.push_back(this);
m_IsTransparent = true;
}
}
void Renderer3D::MakeSolid()
{
auto iter = std::find(Renderer::s_Objects3dTransparent.begin(), Renderer::s_Objects3dTransparent.end(), this);
if (iter != Renderer::s_Objects3dTransparent.end())
{
Renderer::s_Objects3dTransparent.erase(iter);
Renderer::s_Objects3d.push_back(this);
ChangeRenderTechnic(RenderTechnic::Forward);
m_IsTransparent = false;
}
}
void Renderer3D::Render()
{
if (m_RenderTechnic == RenderTechnic::Forward)
{
m_Tr = &(m_OwnerOfCom->m_Transform);
if (m_IsWireMesh)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
ForwardRender(m_Tr->m_PosMat4, m_Tr->m_ViewMat4, m_Tr->m_ScaleMat4, m_Color);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
else
{
ForwardRender(m_Tr->m_PosMat4, m_Tr->m_ViewMat4, m_Tr->m_ScaleMat4, m_Color);
}
}
}
void Renderer3D::Copy(const Renderer3D& rhs)
{
m_FloatUniforms = rhs.m_FloatUniforms;
m_Material = rhs.m_Material;
m_DiffuseTexture = rhs.m_DiffuseTexture;
m_NormalMapTexture = rhs.m_NormalMapTexture;
LoadMesh(rhs.m_Mesh);
m_IsCastingShadows = rhs.m_IsCastingShadows;
m_IsWireMesh = rhs.m_IsWireMesh;
m_IsUsingNormalMap = rhs.m_IsUsingNormalMap;
if (rhs.m_IsTransparent)
MakeTransparent();
m_IsSkyBox = rhs.m_IsSkyBox;
ChangeRenderTechnic(rhs.m_RenderTechnic);
m_Color = rhs.m_Color;
m_Shader = rhs.m_Shader;
m_RenderType = rhs.m_RenderType;
m_Emissive = rhs.m_Emissive;
}
void Renderer3D::ForwardRender(glm::mat4& pos, glm::mat4& view, glm::mat4& scale, glm::vec4& color)
{
if (m_Mesh != nullptr && m_Mesh->m_IsInitialized)
{
if (m_IsSkyBox) {
RenderSkyBox();
return;
}
m_Shader->Bind();
glBindTextureUnit(0, m_DiffuseTexture->m_RendererID);
m_Shader->SetUniformMat4f("u_ViewProjection", Window::GetInstance().GetCamera().GetViewProjectionMatrix());
m_Shader->SetUniformMat4f("u_Model", pos);
m_Shader->SetUniformMat4f("u_View", view);
m_Shader->SetUniformMat4f("u_Scale", scale);
m_Shader->SetUniform4f("u_Color", color[0], color[1], color[2], color[3]);
AdditionalUniformsLoad();
int dlightSize = DirectionalLight::s_DirLights.size();
m_Shader->SetUniform1i("dLightSize", dlightSize);
char buffer[64];
for (int i = 0; i < dlightSize; i++)
{
DirectionalLight* dl = DirectionalLight::s_DirLights[i];
dl->m_Dir = dl->m_OwnerOfCom->m_Transform.m_ViewMat4 * glm::vec4(0, 0, -1, 1);
sprintf(buffer, "dirLights[%i].dir", i);
m_Shader->SetUniform3fv(buffer, dl->m_Dir);
sprintf(buffer, "dirLights[%i].color", i);
m_Shader->SetUniform3fv(buffer, dl->m_Color);
sprintf(buffer, "dirLights[%i].intensity", i);
m_Shader->SetUniform1f(buffer, dl->m_Intensity);
}
int plightSize = PointLight::s_PointLights.size();
m_Shader->SetUniform1i("pLightSize", plightSize);
for (int i = 0; i < plightSize; i++)
{
PointLight* pl = PointLight::s_PointLights[i];
sprintf(buffer, "pointLights[%i].position", i);
m_Shader->SetUniform3fv(buffer, pl->m_OwnerOfCom->GetPosition());
sprintf(buffer, "pointLights[%i].color", i);
m_Shader->SetUniform3fv(buffer, pl->m_Color);
sprintf(buffer, "pointLights[%i].constant", i);
m_Shader->SetUniform1f(buffer, pl->m_Constant);
sprintf(buffer, "pointLights[%i]._linear", i);
m_Shader->SetUniform1f(buffer, pl->m_Linear);
sprintf(buffer, "pointLights[%i].quadratic", i);
m_Shader->SetUniform1f(buffer, pl->m_Quadratic);
}
int slightSize = SpotLight::s_SpotLights.size();
m_Shader->SetUniform1i("sLightSize", slightSize);
for (int i = 0; i < slightSize; i++)
{
SpotLight* sl = SpotLight::s_SpotLights[i];
sprintf(buffer, "spotLights[%i].position", i);
m_Shader->SetUniform3fv(buffer, sl->m_OwnerOfCom->GetPosition());
sprintf(buffer, "spotLights[%i].dir", i);
m_Shader->SetUniform3fv(buffer, sl->m_OwnerOfCom->m_Transform.m_ViewMat4 * glm::vec4(0, 0, -1, 1));
sprintf(buffer, "spotLights[%i].color", i);
m_Shader->SetUniform3fv(buffer, sl->m_Color);
sprintf(buffer, "spotLights[%i].constant", i);
m_Shader->SetUniform1f(buffer, sl->m_Constant);
sprintf(buffer, "spotLights[%i]._linear", i);
m_Shader->SetUniform1f(buffer, sl->m_Linear);
sprintf(buffer, "spotLights[%i].quadratic", i);
m_Shader->SetUniform1f(buffer, sl->m_Quadratic);
sprintf(buffer, "spotLights[%i].innerCutOff", i);
m_Shader->SetUniform1f(buffer, sl->m_InnerCutOff);
sprintf(buffer, "spotLights[%i].outerCutOff", i);
m_Shader->SetUniform1f(buffer, sl->m_OuterCutOff);
}
m_Shader->SetUniform3fv("u_CameraPos", Window::GetInstance().GetCamera().GetPosition());
m_Shader->SetUniform1f("u_Ambient", m_Material.m_Ambient);
m_Shader->SetUniform1f("u_Specular", m_Material.m_Specular);
m_Shader->SetUniformMat4f("u_LightSpaceMatrix", DirectionalLight::GetLightSpaceMatrix());
m_Shader->SetUniform1i("u_DiffuseTexture", 0);
glBindTextureUnit(2, Window::GetInstance().m_FrameBufferShadowMap->m_Textures[0]);
m_Shader->SetUniform1i("u_ShadowTexture", 2);
m_Shader->SetUniform1i("u_PcfRange", Renderer::s_ShadowMap.m_PcfRange);
m_Shader->SetUniform1f("u_ShadowBias", Renderer::s_ShadowMap.m_Bias);
m_Shader->SetUniform1f("u_ScalarTexelSize", Renderer::s_ShadowMap.m_ScalarTexelSize);
m_Shader->SetUniform1f("u_DrawShadows", Renderer::s_ShadowMap.m_DrawShadows);
if (m_IsUsingNormalMap)
{
glBindTextureUnit(1, m_NormalMapTexture->m_RendererID);
m_Shader->SetUniform1i("u_NormalMapTexture", 1);
}
m_Shader->SetUniform1i("u_IsNormalMapping", m_IsUsingNormalMap);
m_Shader->SetUniform1f("u_Brightness", Renderer::s_Bloom.m_Brightness);
m_Shader->SetUniform1i("u_Emissive", m_Emissive);
m_Mesh->m_Va.Bind();
m_Mesh->m_Ib.Bind();
Renderer::s_Stats.m_Vertices += m_Mesh->m_Ib.m_count;
Renderer::s_Stats.m_DrawCalls++;
if (!m_IsCullingFace)
glDisable(GL_CULL_FACE);
glDrawElements(GL_TRIANGLES, m_Mesh->m_Ib.m_count, GL_UNSIGNED_INT, nullptr);
glEnable(GL_CULL_FACE);
m_Shader->UnBind();
m_Mesh->m_Ib.UnBind();
glBindTextureUnit(0, Texture::s_WhiteTexture->m_RendererID);
}
}
void Renderer3D::RenderSkyBox()
{
m_Shader = Shader::Get("SkyBox");
glDepthFunc(GL_LEQUAL);
glActiveTexture(GL_TEXTURE0);
glDisable(GL_CULL_FACE);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_DiffuseTexture->m_RendererID);
m_Shader->Bind();
Window::GetInstance().GetCamera().RecalculateViewMatrix();
m_Shader->SetUniformMat4f("u_ViewProjection", Window::GetInstance().GetCamera().GetProjectionMatrix());
m_Shader->SetUniformMat4f("u_Model", m_Tr->m_PosMat4);
m_Shader->SetUniformMat4f("u_View", glm::mat4(glm::mat3(Window::GetInstance().GetCamera().GetViewMatrix())));
m_Shader->SetUniformMat4f("u_Scale", m_Tr->m_ScaleMat4);
m_Shader->SetUniform1i("u_DiffuseTexture", 0);
m_Shader->SetUniform1f("u_Brightness", Renderer::s_Bloom.m_Brightness);
m_Shader->Bind();
m_Mesh->m_Va.Bind();
m_Mesh->m_Ib.Bind();
m_Mesh->m_Vb.Bind();
Renderer::s_Stats.m_Vertices += m_Mesh->m_Ib.m_count;
Renderer::s_Stats.m_DrawCalls++;
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
m_Shader->UnBind();
m_Mesh->m_Ib.UnBind();
m_DiffuseTexture->UnBind();
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
}
void Renderer3D::AdditionalUniformsLoad()
{
for (auto i = m_FloatUniforms.begin(); i != m_FloatUniforms.end(); i++)
{
m_Shader->SetUniform1f(i->first, i->second);
}
}
| 33.881579 | 134 | 0.71666 | Shturm0weak |
6c739e683ffe3061b2d448fc2a33a103f268d058 | 59,679 | cpp | C++ | source/TheoremProver/ProverExpression.cpp | ubavic/gclc | bf28e4317d4c7a73d39ce3bbdb6f73ea4c6f0c44 | [
"MIT"
] | null | null | null | source/TheoremProver/ProverExpression.cpp | ubavic/gclc | bf28e4317d4c7a73d39ce3bbdb6f73ea4c6f0c44 | [
"MIT"
] | null | null | null | source/TheoremProver/ProverExpression.cpp | ubavic/gclc | bf28e4317d4c7a73d39ce3bbdb6f73ea4c6f0c44 | [
"MIT"
] | null | null | null | #include "ProverExpression.h"
#include "TheoremProver.h"
#include <assert.h>
#include <cmath>
#define EPSILON 0.00001
static unsigned idCounter=0;
Rules CGCLCProverExpression::mRules;
unsigned arity(enum GCLCexperssion_type type) {
switch (type) {
case ep_number:
case ep_point:
case ep_constant:
case ep_unknown:
return 0;
case ep_identical:
case ep_segment:
case ep_equality:
case ep_sum:
case ep_ratio:
case ep_mult:
case ep_diffx:
case ep_diffy:
return 2;
case ep_s3:
case ep_p3:
case ep_collinear:
case ep_midpoint:
case ep_tangens_num:
case ep_tangens_den:
return 3;
case ep_segment_ratio:
case ep_s4:
case ep_p4:
case ep_parallel:
case ep_perpendicular:
case ep_harmonic:
case ep_same_length:
return 4;
default:
return 0;
}
return 0;
}
// --------------------------------------------------------------------------
CGCLCProverExpression::CGCLCProverExpression() {
for (unsigned i = 0; i < ExpressionArgCount; i++)
arg[i] = NULL;
sName = "";
nNumber = 0;
type = ep_unknown;
id = idCounter++;
}
// --------------------------------------------------------------------------
CGCLCProverExpression::~CGCLCProverExpression() { CleanUp(); }
// --------------------------------------------------------------------------
CGCLCProverExpression::CGCLCProverExpression(const CGCLCProverExpression &r) {
type = r.type;
sName = r.sName;
nNumber = r.nNumber;
for (unsigned i = 0; i < arity(type); i++)
arg[i] = new CGCLCProverExpression(r.GetArg(i));
for (unsigned i = arity(type); i < ExpressionArgCount; i++)
arg[i] = NULL;
id = idCounter++;
}
// --------------------------------------------------------------------------
CGCLCProverExpression &CGCLCProverExpression::
operator=(const CGCLCProverExpression &r) {
if (this == &r)
return *this;
CleanUp();
type = r.type;
sName = r.sName;
nNumber = r.nNumber;
for (unsigned i = 0; i < ExpressionArgCount; i++)
if (arg[i])
delete arg[i];
for (unsigned i = 0; i < arity(type); i++)
arg[i] = new CGCLCProverExpression(r.GetArg(i));
for (unsigned i = arity(type); i < ExpressionArgCount; i++)
arg[i] = NULL;
return *this;
}
// --------------------------------------------------------------------------
CGCLCProverExpression &CGCLCProverExpression::operator=(const double n) {
CleanUp();
sName = "";
nNumber = n;
type = ep_number;
for (unsigned i = 0; i < ExpressionArgCount; i++) {
delete arg[i];
arg[i] = NULL;
}
return *this;
}
// --------------------------------------------------------------------------
CGCLCProverExpression::CGCLCProverExpression(GCLCexperssion_type t,
const string &a) {
assert(t == ep_point || t == ep_constant);
type = t;
sName = a;
nNumber = 0;
for (unsigned i = 0; i < ExpressionArgCount; i++)
arg[i] = NULL;
id = idCounter++;
}
// --------------------------------------------------------------------------
CGCLCProverExpression::CGCLCProverExpression(GCLCexperssion_type t,
const string &a0,
const string &a1) {
assert(t == ep_segment || t == ep_diffx || t == ep_diffy);
type = t;
nNumber = 0;
arg[0] = new CGCLCProverExpression(ep_point, a0);
arg[1] = new CGCLCProverExpression(ep_point, a1);
arg[2] = NULL;
arg[3] = NULL;
id = idCounter++;
}
// --------------------------------------------------------------------------
CGCLCProverExpression::CGCLCProverExpression(GCLCexperssion_type t,
const string &a0, const string &a1,
const string &a2) {
assert(t == ep_s3 || t == ep_p3);
type = t;
nNumber = 0;
arg[0] = new CGCLCProverExpression(ep_point, a0);
arg[1] = new CGCLCProverExpression(ep_point, a1);
arg[2] = new CGCLCProverExpression(ep_point, a2);
arg[3] = NULL;
id = idCounter++;
}
// --------------------------------------------------------------------------
CGCLCProverExpression::CGCLCProverExpression(GCLCexperssion_type t,
const string &a0, const string &a1,
const string &a2,
const string &a3) {
assert(t == ep_s4 || t == ep_p4 || t == ep_segment_ratio || t == ep_parallel);
type = t;
nNumber = 0;
arg[0] = new CGCLCProverExpression(ep_point, a0);
arg[1] = new CGCLCProverExpression(ep_point, a1);
arg[2] = new CGCLCProverExpression(ep_point, a2);
arg[3] = new CGCLCProverExpression(ep_point, a3);
id = idCounter++;
}
// --------------------------------------------------------------------------
CGCLCProverExpression::CGCLCProverExpression(const double n) {
type = ep_number;
nNumber = n;
for (unsigned i = 0; i < ExpressionArgCount; i++)
arg[i] = NULL;
id = idCounter++;
}
// --------------------------------------------------------------------------
CGCLCProverExpression::CGCLCProverExpression(
GCLCexperssion_type t, const CGCLCProverExpression &arg0,
const CGCLCProverExpression &arg1) {
assert(arity(t) == 2);
type = t;
nNumber = 0;
arg[0] = new CGCLCProverExpression(arg0);
arg[1] = new CGCLCProverExpression(arg1);
for (unsigned i = 2; i < ExpressionArgCount; i++)
arg[i] = NULL;
id = idCounter++;
}
// --------------------------------------------------------------------------
CGCLCProverExpression CGCLCProverExpression::s3(const string &a0,
const string &a1,
const string &a2) {
CGCLCProverExpression n(ep_s3, a0, a1, a2);
return n;
}
// --------------------------------------------------------------------------
CGCLCProverExpression CGCLCProverExpression::p3(const string &a0,
const string &a1,
const string &a2) {
CGCLCProverExpression n(ep_p3, a0, a1, a2);
return n;
}
// --------------------------------------------------------------------------
CGCLCProverExpression CGCLCProverExpression::s4(const string &a0,
const string &a1,
const string &a2,
const string &a3) {
CGCLCProverExpression n(ep_s4, a0, a1, a2, a3);
return n;
}
// --------------------------------------------------------------------------
CGCLCProverExpression CGCLCProverExpression::p4(const string &a0,
const string &a1,
const string &a2,
const string &a3) {
CGCLCProverExpression n(ep_p4, a0, a1, a2, a3);
return n;
}
// --------------------------------------------------------------------------
CGCLCProverExpression CGCLCProverExpression::sratio(const string &a0,
const string &a1,
const string &a2,
const string &a3) {
CGCLCProverExpression n(ep_segment_ratio, a0, a1, a2, a3);
return n;
}
// --------------------------------------------------------------------------
CGCLCProverExpression CGCLCProverExpression::segment(const string &a0,
const string &a1) {
CGCLCProverExpression n(ep_segment, a0, a1);
return n;
}
// --------------------------------------------------------------------------
CGCLCProverExpression CGCLCProverExpression::
operator*(const CGCLCProverExpression &a) {
CGCLCProverExpression n(ep_mult, *this, a);
return n;
}
// --------------------------------------------------------------------------
CGCLCProverExpression CGCLCProverExpression::
operator+(const CGCLCProverExpression &a) {
CGCLCProverExpression e(ep_sum, *this, a);
return e;
}
// --------------------------------------------------------------------------
CGCLCProverExpression CGCLCProverExpression::
operator/(const CGCLCProverExpression &a) {
CGCLCProverExpression e(ep_ratio, *this, a);
return e;
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::CleanUp() {
// this->PrettyPrint();
// cout << "-------------" << endl;
for (unsigned i = 0; i < ExpressionArgCount; i++) {
if (arg[i])
delete arg[i];
arg[i] = NULL;
}
sName = "";
nNumber = 0;
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::Push(CGCLCProverExpression &left,
CGCLCProverExpression &right,
const CGCLCProverExpression &a) {
assert(type == ep_equality);
left = GetArg(0);
right = GetArg(1);
for (unsigned i = 0; i < 2; i++) {
if (arg[i])
delete arg[i];
arg[i] = new CGCLCProverExpression(a.GetArg(i));
}
SetType(ep_equality);
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::Pop(CGCLCProverExpression &left,
CGCLCProverExpression &right) {
assert(type == ep_equality);
if (arg[0])
delete arg[0];
if (arg[1])
delete arg[1];
arg[0] = new CGCLCProverExpression(left);
arg[1] = new CGCLCProverExpression(right);
SetType(ep_equality);
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::Set(GCLCexperssion_type t,
const CGCLCProverExpression &arg0,
const CGCLCProverExpression &arg1) {
assert(arity(t) == 2);
CleanUp();
type = t;
nNumber = 0;
SetArg(0, CGCLCProverExpression(arg0));
SetArg(1, CGCLCProverExpression(arg1));
for (unsigned i = 2; i < ExpressionArgCount; i++)
arg[i] = NULL;
// id = idCounter++;
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::SetArg(unsigned i, CGCLCProverExpression *a) {
if (arg[i])
delete arg[i];
arg[i] = a;
// arg[i] = new CGCLCProverExpression(*a);
// id = idCounter++;
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::SetArg(unsigned i, const CGCLCProverExpression &a) {
if (arg[i])
delete arg[i];
arg[i] = new CGCLCProverExpression(a);
// id = idCounter++;
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::SetArgName(unsigned i, const string &s) {
assert(type == ep_s3 || type == ep_p3 || type == ep_s4 || type == ep_p4 ||
type == ep_segment_ratio || type == ep_segment ||
type == ep_parallel || type == ep_collinear ||
type == ep_perpendicular || type == ep_midpoint ||
type == ep_harmonic || type == ep_same_length ||
type == ep_tangens_num || type == ep_tangens_den || type == ep_diffx ||
type == ep_diffy || type == ep_identical);
assert(i < arity(type));
arg[i]->SetName(s);
// id = idCounter++;
}
// --------------------------------------------------------------------------
string CGCLCProverExpression::GetArgName(unsigned i) const {
assert(type == ep_s3 || type == ep_p3 || type == ep_s4 || type == ep_p4 ||
type == ep_segment_ratio || type == ep_segment ||
type == ep_parallel || type == ep_collinear ||
type == ep_perpendicular || type == ep_midpoint ||
type == ep_harmonic || type == ep_same_length ||
type == ep_tangens_num || type == ep_tangens_den || type == ep_diffx ||
type == ep_diffy || type == ep_identical);
assert(i < arity(type));
return arg[i]->GetName();
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::operator==(const CGCLCProverExpression &r) const {
return Equal(r);
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::Equal(const CGCLCProverExpression &r) const {
// return (*this) == *r;
if (type != r.type)
return false;
if (type == ep_point)
return (sName == r.sName);
if (type == ep_constant)
return (sName == r.sName);
if (type == ep_number)
return (nNumber == r.nNumber);
for (unsigned i = 0; i < arity(type); i++)
if (!(arg[i]->Equal(*r.arg[i])))
return false;
return true;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::ExistsAtomicExpression(
const CGCLCProverExpression &subexp) const {
switch (GetType()) {
case ep_number:
case ep_point:
case ep_s3:
case ep_segment:
case ep_segment_ratio:
case ep_p3:
case ep_p4:
case ep_s4:
if (*this == subexp)
return true;
break;
case ep_equality:
case ep_sum:
case ep_ratio:
case ep_mult:
if (GetArg(0).ExistsAtomicExpression(subexp))
return true;
if (GetArg(1).ExistsAtomicExpression(subexp))
return true;
break;
default:
break;
}
return false;
}
bool CGCLCProverExpression::GetParentIndex(CGCLCProverExpression &outer,
CGCLCProverExpression *&parent,
int &index) const {
if (*this == outer)
return false;
for (unsigned i = 0; i < arity(outer.GetType()); i++) {
if (*this == outer.GetArg(i)) {
parent = &outer;
index = i;
return true;
}
if (GetParentIndex(outer.GetArg(i), parent, index))
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::Replace(const CGCLCProverExpression &LHS,
const CGCLCProverExpression &RHS) {
/*if (old_expression->Equal(new_expression)) {
delete old_expression;
old_expression = new CGCLCProverExpression(*new_expression);
if (old_expression == NULL)
return false;
else
return true;
}*/
for (unsigned i = 0; i < arity(type); i++)
if (*arg[i] == LHS) {
delete arg[i];
arg[i] = new CGCLCProverExpression(RHS);
if (arg[i] == NULL)
return false;
} else if (!arg[i]->Replace(LHS, RHS))
return false;
return true;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::ApplyAllAlgebraicRules(string &sRuleApplied,
int iExceptLast) {
for (unsigned i = 0; i < mRules.m_nNumberOfRules - iExceptLast; i++)
if (ApplyOneAlgebraicRule(mRules.m_aiRule[i])) {
sRuleApplied = mRules.m_asRuleName[mRules.m_aiRule[i]];
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::ApplyAllSimpleAlgebraicRules(string &sRuleApplied,
int iExceptLast) {
for (unsigned i = 0; i < 14 && i < mRules.m_nNumberOfRules - iExceptLast; i++) {
if (ApplyOneAlgebraicRule(mRules.m_aiRule[i])) {
sRuleApplied = mRules.m_asRuleName[mRules.m_aiRule[i]];
return true;
}
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::ApplyAllComplexAlgebraicRules(string &sRuleApplied,
int iExceptLast) {
for (unsigned i = 14; i < mRules.m_nNumberOfRules - iExceptLast; i++) {
if (ApplyOneAlgebraicRule(mRules.m_aiRule[i])) {
sRuleApplied = mRules.m_asRuleName[mRules.m_aiRule[i]];
return true;
}
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::ApplyOneAlgebraicRule(GCLCalgebraic_rule rule) {
switch (rule) {
case er_RatioCancellation:
if (RatioCancellation())
return true;
break;
case er_MultiplicationOfConstants:
if (MultiplicationOfConstants())
return true;
break;
case er_AdditionWithZero:
if (AdditionWithZero())
return true;
break;
case er_MultiplicationWithOne:
if (MultiplicationWithOne())
return true;
break;
case er_CommutativityWithNumber:
if (CommutativityWithNumber())
return true;
break;
case er_AssociativityAndCommutativity:
if (AssociativityAndCommutativity())
return true;
break;
case er_RightAssoc:
if (RightAssoc())
return true;
break;
case er_MultiplicationOfFractions:
if (MultiplicationOfFractions())
return true;
break;
case er_DistrMultOverAdd:
if (DistrMultOverAdd())
return true;
break;
case er_MultiplicationWithZero:
if (MultiplicationWithZero())
return true;
break;
case er_MultipleFraction:
if (MultipleFraction())
return true;
break;
case er_SumOfFractions:
if (SumOfFractions())
return true;
break;
case er_SimilarSummands:
if (SimilarSummands())
return true;
break;
case er_SimilarSummandsOnTwoSides:
if (SimilarSummandsOnTwoSides())
return true;
break;
case er_ZeroFractionUp:
if (ZeroFractionUp())
return true;
break;
case er_FractionEqualZero:
if (FractionEqualZero())
return true;
break;
case er_FractionWithNumberDenominator:
if (FractionWithNumberDenominator())
return true;
break;
case er_OneSide:
if (OneSide())
return true;
break;
case er_FractionsOnTwoSides:
if (FractionsOnTwoSides())
return true;
break;
case er_EliminateFraction:
if (EliminateFraction())
return true;
break;
default:
break;
}
for (unsigned i = 0; i < ExpressionArgCount; i++)
if (arg[i] != NULL)
if (arg[i]->ApplyOneAlgebraicRule(rule))
return true;
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::MultiplicationOfFractions() {
// (a/b)*(c/d) = (a*c)/(b*d)
if (type == ep_mult && GetArg(0).type == ep_ratio &&
GetArg(1).type == ep_ratio) {
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
CGCLCProverExpression c(GetArg(1).GetArg(0));
CGCLCProverExpression d(GetArg(1).GetArg(1));
*this = ((a * c) / (b * d));
return true;
}
// a*(c/d) = (a*c)/d
if (type == ep_mult && GetArg(1).type == ep_ratio &&
GetArg(0).type != ep_ratio) {
CGCLCProverExpression a(GetArg(0));
CGCLCProverExpression c(GetArg(1).GetArg(0));
CGCLCProverExpression d(GetArg(1).GetArg(1));
*this = ((a * c) / d);
return true;
}
// (a/b)*c = (a*c)/b
if (type == ep_mult && GetArg(0).type == ep_ratio &&
GetArg(1).type != ep_ratio) {
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
CGCLCProverExpression c(GetArg(1));
type = ep_ratio;
*this = ((a * c) / b);
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::MultiplicationWithZero() {
// 0*x -> 0
if (type == ep_mult && GetArg(0).type == ep_number &&
GetArg(0).nNumber == 0.0) {
*this = 0.0;
return true;
}
// x*0 -> 0
if (type == ep_mult && GetArg(1).type == ep_number &&
GetArg(1).nNumber == 0.0) {
*this = 0.0;
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::ZeroFractionUp() {
// 0/x -> 0
if (type == ep_ratio && GetArg(0).type == ep_number &&
GetArg(0).nNumber == 0.0) {
*this = 0.0;
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::FractionEqualZero() {
// a/b = 0 -> a = 0
if (type == ep_equality && GetArg(0).type == ep_ratio &&
(GetArg(1).type == ep_number) && (GetArg(1).nNumber == 0.0)) {
CGCLCProverExpression a(GetArg(0).GetArg(0));
SetArg(0, a);
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::FractionWithNumberDenominator() {
// a/n -> 1/n * a
if (type == ep_ratio)
if (GetArg(0).type != ep_number && GetArg(1).type == ep_number) {
CGCLCProverExpression a(GetArg(0));
if (GetArg(1).nNumber == 1.0) {
*this = a;
return true;
} else {
CGCLCProverExpression m(1 / GetArg(1).nNumber);
*this = (m * a);
return true;
}
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::MultiplicationWithOne() {
// 1*a -> a
if (type == ep_mult && GetArg(0).type == ep_number &&
GetArg(0).nNumber == 1.0) {
CGCLCProverExpression a(GetArg(1));
*this = a;
return true;
}
// a*1 -> a
if (type == ep_mult && GetArg(1).type == ep_number &&
GetArg(1).nNumber == 1.0) {
CGCLCProverExpression a(GetArg(0));
*this = a;
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::AdditionWithZero() {
// a + 0 -> a
if (type == ep_sum && GetArg(1).type == ep_number &&
GetArg(1).nNumber == 0.0) {
CGCLCProverExpression a(GetArg(0));
*this = a;
return true;
}
// 0+a -> a
if (type == ep_sum && GetArg(0).type == ep_number &&
GetArg(0).nNumber == 0.0) {
CGCLCProverExpression a(GetArg(1));
*this = a;
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::MultiplicationOfConstants() {
// n1 * n1 -> m (m is the product)
if (type == ep_mult)
if (GetArg(0).type == ep_number && GetArg(1).type == ep_number) {
double m = GetArg(0).nNumber * GetArg(1).nNumber;
*this = m;
return true;
}
// n1 * (n2 * a) -> m * a (m is the product)
if (type == ep_mult)
if (GetArg(0).type == ep_number && GetArg(1).type == ep_mult &&
(GetArg(1).GetArg(0).type == ep_number)) {
CGCLCProverExpression a(GetArg(1).GetArg(1));
CGCLCProverExpression m(GetArg(0).nNumber * GetArg(1).GetArg(0).nNumber);
*this = (m * a);
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::CommutativityWithNumber() {
if (type == ep_mult)
if (GetArg(0).type != ep_number && GetArg(1).type == ep_number) {
// a*n -> n*a
CGCLCProverExpression a(GetArg(0));
CGCLCProverExpression n(GetArg(1));
*this = (n * a);
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::AssociativityAndCommutativity() {
if (type == ep_mult && GetArg(1).type == ep_mult &&
GetArg(0).type != ep_number && GetArg(1).GetArg(0).type == ep_number) {
// a*(n*b) -> n*(a*b)
CGCLCProverExpression a(GetArg(0));
CGCLCProverExpression n(GetArg(1).GetArg(0));
CGCLCProverExpression b(GetArg(1).GetArg(1));
*this = (n * (a * b));
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::RatioCancellation() {
if (type == ep_segment_ratio) {
// AB/AB -> 1
if (GetArg(0) == GetArg(2) && GetArg(1) == GetArg(3)) {
*this = 1.0;
return true;
}
// AB/BA -> -1
if (GetArg(0) == GetArg(3) && GetArg(1) == GetArg(2)) {
*this = -1.0;
return true;
}
}
if (type == ep_ratio) {
// x/x -> 1
if (GetArg(0) == GetArg(1)) {
*this = 1.0;
return true;
}
if (GetArg(0).CancelPairFirst(GetArg(1)))
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::CancelPairFirst(CGCLCProverExpression &exp2) {
if (type == ep_number)
if (nNumber == 1)
return false;
switch (type) {
case ep_mult:
if (CancelPairSecond(exp2))
return true;
if (GetArg(0).CancelPairFirst(exp2))
return true;
if (GetArg(1).CancelPairFirst(exp2))
return true;
break;
default:
if (CancelPairSecond(exp2))
return true;
break;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::CancelPairSecond(CGCLCProverExpression &exp2) {
switch (exp2.GetType()) {
case ep_mult:
if (CancelPair(exp2))
return true;
if (CancelPairSecond(exp2.GetArg(0)))
return true;
if (CancelPairSecond(exp2.GetArg(1)))
return true;
break;
default:
if (CancelPair(exp2))
return true;
break;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::CancelPair(CGCLCProverExpression &exp2) {
if (*this == exp2) {
*this = 1.0;
exp2 = 1.0;
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::RightAssoc() {
if (type == ep_mult && GetArg(0).type == ep_mult) {
// (a*b)*c -> a*(b*c)
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
CGCLCProverExpression c(GetArg(1));
*this = (a * (b * c));
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::DistrMultOverAdd() {
// n*(a+b) -> n*a+n*b
if (type == ep_mult && GetArg(1).type == ep_sum) {
CGCLCProverExpression n(GetArg(0));
CGCLCProverExpression a(GetArg(1).GetArg(0));
CGCLCProverExpression b(GetArg(1).GetArg(1));
*this = ((n * a) + (n * b));
return true;
}
// (a+b)*n -> n*a+n*b
if (type == ep_mult && GetArg(0).type == ep_sum) {
CGCLCProverExpression n(GetArg(1));
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
*this = ((n * a) + (n * b));
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::MultipleFraction() {
// (a/b)/(c/d) = (a*d)/(b*c)
if (type == ep_ratio && GetArg(0).type == ep_ratio &&
GetArg(1).type == ep_ratio) {
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
CGCLCProverExpression c(GetArg(1).GetArg(0));
CGCLCProverExpression d(GetArg(1).GetArg(1));
*this = ((a * d) / (b * c));
return true;
}
// (a/b)/c -> a/(b*c)
if (type == ep_ratio && GetArg(0).type == ep_ratio &&
GetArg(1).type != ep_ratio) {
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
CGCLCProverExpression c(GetArg(1));
*this = (a / (b * c));
return true;
}
// a/(c/d) = (a*d)/c
if (type == ep_ratio && GetArg(0).type != ep_ratio &&
GetArg(1).type == ep_ratio) {
CGCLCProverExpression a(GetArg(0));
CGCLCProverExpression c(GetArg(1).GetArg(0));
CGCLCProverExpression d(GetArg(1).GetArg(1));
*this = ((a * d) / c);
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::FractionsOnTwoSides() {
// a/b = c/b -> a/1 = c/1
if (type == ep_equality && GetArg(0).type == ep_ratio &&
GetArg(1).type == ep_ratio && GetArg(0).GetArg(1) == GetArg(1).GetArg(1))
if ((GetArg(0).GetArg(1).type != ep_number) ||
(GetArg(0).GetArg(1).nNumber != 1)) {
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(1.0);
CGCLCProverExpression c(GetArg(1).GetArg(0));
Set(ep_equality, a / b, c / b);
return true;
}
// a/b = c/d -> a*d = c*b
if (type == ep_equality && GetArg(0).type == ep_ratio &&
GetArg(1).type == ep_ratio) {
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
CGCLCProverExpression c(GetArg(1).GetArg(0));
CGCLCProverExpression d(GetArg(1).GetArg(1));
Set(ep_equality, a * d, c * b);
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::EliminateFraction() {
// a/b = c -> a = b*c
if (type == ep_equality && GetArg(0).type == ep_ratio) {
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
CGCLCProverExpression c(GetArg(1));
Set(ep_equality, a, b * c);
return true;
}
// a = c/d -> a*d = c
if (type == ep_equality && GetArg(1).type == ep_ratio) {
CGCLCProverExpression a(GetArg(0));
CGCLCProverExpression c(GetArg(1).GetArg(0));
CGCLCProverExpression d(GetArg(1).GetArg(1));
Set(ep_equality, a * d, c);
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::SumOfFractions() {
if (type != ep_sum)
return false;
if (GetArg(0).type == ep_ratio) {
if (GetArg(1).type == ep_ratio) {
if (GetArg(0).GetArg(1) == GetArg(1).GetArg(1)) {
// a/b + c/b = (a+c)/b
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
CGCLCProverExpression c(GetArg(1).GetArg(0));
*this = ((a + c) / b);
return true;
} else { // a/b + c/d = (ad+bc)/bd
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
CGCLCProverExpression c(GetArg(1).GetArg(0));
CGCLCProverExpression d(GetArg(1).GetArg(1));
*this = (((a * d) + (b * c)) / (b * d));
return true;
}
} else { // GetArg(1).type != ep_ratio
// a/b + c = (a+cb)/b
CGCLCProverExpression a(GetArg(0).GetArg(0));
CGCLCProverExpression b(GetArg(0).GetArg(1));
CGCLCProverExpression c(GetArg(1));
*this = ((a + (c * b)) / b);
return true;
}
} else { // GetArg(0).type != ep_ratio
if (GetArg(1).type == ep_ratio) {
// c + a/b = (cb+a)/b
CGCLCProverExpression a(GetArg(1).GetArg(0));
CGCLCProverExpression b(GetArg(1).GetArg(1));
CGCLCProverExpression c(GetArg(0));
*this = (((c * b) + a) / b);
return true;
}
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::CancelationMult(
const CGCLCProverExpression &Factor) {
CGCLCProverExpression **aSummands, **aMultiplicants;
int iMaxIndex = CountTopLevelOperands(ep_sum);
aSummands = new CGCLCProverExpression *[iMaxIndex];
iMaxIndex = 0;
FillTopLevelOperands(ep_sum, aSummands, iMaxIndex);
int j, k;
for (j = 0; j < iMaxIndex; j++) {
aMultiplicants = new CGCLCProverExpression
*[aSummands[j]->CountTopLevelOperands(ep_mult)];
if (aMultiplicants == NULL) {
delete[] aSummands;
return false;
}
int iMaxIndex2 = 0;
aSummands[j]->FillTopLevelOperands(ep_mult, aMultiplicants, iMaxIndex2);
bool bExists = false;
for (k = 0; k < iMaxIndex2 && !bExists; k++) {
if (Factor == *(aMultiplicants[k])) {
*aMultiplicants[k] = 1.0;
bExists = true;
} else {
if (aMultiplicants[k]->GetType() == ep_number)
if (aMultiplicants[k]->GetNumber() == 0)
bExists = true;
}
}
delete[] aMultiplicants;
}
delete[] aSummands;
return true;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::AllSummandsHaveFactor(
const CGCLCProverExpression &Factor) {
CGCLCProverExpression **aSummands;
CGCLCProverExpression **aMultiplicants;
int iMaxIndex = CountTopLevelOperands(ep_sum);
aSummands = new CGCLCProverExpression *[iMaxIndex];
iMaxIndex = 0;
FillTopLevelOperands(ep_sum, aSummands, iMaxIndex);
bool bEverywhere, bExists;
int j, k;
bEverywhere = true;
for (j = 0; j < iMaxIndex && bEverywhere; j++) {
if (aSummands[j]->GetType() != ep_number ||
aSummands[j]->GetNumber() != 0) {
aMultiplicants = new CGCLCProverExpression
*[aSummands[j]->CountTopLevelOperands(ep_mult)];
if (aMultiplicants == NULL) {
delete[] aSummands;
return false;
}
int iMaxIndex2 = 0;
aSummands[j]->FillTopLevelOperands(ep_mult, aMultiplicants, iMaxIndex2);
bExists = false;
for (k = 0; k < iMaxIndex2 && !bExists; k++) {
if (Factor == *(aMultiplicants[k]))
bExists = true;
}
if (!bExists)
bEverywhere = false;
delete[] aMultiplicants;
}
}
delete[] aSummands;
return bEverywhere;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::SimilarSummandsOnTwoSides() {
if (type != ep_equality)
return false;
if (GetArg(0).type == ep_number)
return false;
if (GetArg(1).type == ep_number)
return false;
CGCLCProverExpression **aSummands1, **aSummands2;
int iMaxIndex1 = GetArg(0).CountTopLevelOperands(ep_sum);
int iMaxIndex2 = GetArg(1).CountTopLevelOperands(ep_sum);
aSummands1 = new CGCLCProverExpression *[iMaxIndex1];
iMaxIndex1 = 0;
GetArg(0).FillTopLevelOperands(ep_sum, aSummands1, iMaxIndex1);
aSummands2 = new CGCLCProverExpression *[iMaxIndex2];
iMaxIndex2 = 0;
GetArg(1).FillTopLevelOperands(ep_sum, aSummands2, iMaxIndex2);
int i, j, k, l;
for (i = 0; i < iMaxIndex1; i++) {
CGCLCProverExpression **aMultiplicants1, **aMultiplicants2;
aMultiplicants1 = new CGCLCProverExpression
*[aSummands1[i]->CountTopLevelOperands(ep_mult)];
if (aMultiplicants1 == NULL) {
delete[] aSummands1;
delete[] aSummands2;
return false;
}
int iMaxIndex3 = 0;
aSummands1[i]->FillTopLevelOperands(ep_mult, aMultiplicants1, iMaxIndex3);
for (j = 0; j < iMaxIndex2; j++) {
aMultiplicants2 = new CGCLCProverExpression
*[aSummands2[j]->CountTopLevelOperands(ep_mult)];
if (aMultiplicants2 == NULL) {
delete[] aMultiplicants1;
delete[] aSummands1;
delete[] aSummands2;
return false;
}
int iMaxIndex4 = 0;
aSummands2[j]->FillTopLevelOperands(ep_mult, aMultiplicants2, iMaxIndex4);
int k0 = (aMultiplicants1[0]->type == ep_number ? 1 : 0);
int l0 = (aMultiplicants2[0]->type == ep_number ? 1 : 0);
if ((iMaxIndex3 - k0) != (iMaxIndex4 - l0)) {
delete[] aMultiplicants2;
continue;
}
bool bAllFound = true;
for (k = k0; k < iMaxIndex3 && bAllFound; k++) {
bool bFoundMatching = false;
for (l = l0; l < iMaxIndex4 && !bFoundMatching; l++)
if (aMultiplicants2[l] != NULL)
if (*(aMultiplicants1[k]) == *(aMultiplicants2[l])) {
bFoundMatching = true;
aMultiplicants2[l] = NULL;
}
if (!bFoundMatching)
bAllFound = false;
}
if (bAllFound) {
if (k0 == 1) {
if (l0 == 0)
aMultiplicants1[0]->nNumber -= 1;
else
aMultiplicants1[0]->nNumber -= aMultiplicants2[0]->nNumber;
if (fabs(aMultiplicants1[0]->nNumber) < EPSILON)
aMultiplicants1[0]->nNumber = 0; // changed 22.02.2006.
} else {
double n;
if (l0 == 0)
n = 0;
else
n = 1 - aMultiplicants2[0]->nNumber;
CGCLCProverExpression a(*(aSummands1[i]));
CGCLCProverExpression b(n);
*aSummands1[i] = (b * a);
}
*aSummands2[j] = 0.0;
delete[] aMultiplicants1;
delete[] aMultiplicants2;
delete[] aSummands1;
delete[] aSummands2;
return true;
} else
delete[] aMultiplicants2;
}
delete[] aMultiplicants1;
}
delete[] aSummands1;
delete[] aSummands2;
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::SimilarSummands() {
if (type != ep_sum)
return false;
CGCLCProverExpression **aSummands;
int iMaxIndex = CountTopLevelOperands(ep_sum);
if (iMaxIndex == 1)
return false;
aSummands = new CGCLCProverExpression *[iMaxIndex];
if (aSummands == NULL)
return false;
iMaxIndex = 0;
FillTopLevelOperands(ep_sum, aSummands, iMaxIndex);
int i, j, k, l;
for (i = 0; i < iMaxIndex; i++) {
CGCLCProverExpression **aMultiplicants1, **aMultiplicants2;
aMultiplicants1 = new CGCLCProverExpression
*[aSummands[i]->CountTopLevelOperands(ep_mult)];
if (aMultiplicants1 == NULL) {
delete[] aSummands;
return false;
}
int iMaxIndex1 = 0;
aSummands[i]->FillTopLevelOperands(ep_mult, aMultiplicants1, iMaxIndex1);
for (j = i + 1; j < iMaxIndex; j++) {
aMultiplicants2 = new CGCLCProverExpression
*[aSummands[j]->CountTopLevelOperands(ep_mult)];
if (aMultiplicants2 == NULL) {
delete[] aMultiplicants1;
delete[] aSummands;
return false;
}
int iMaxIndex2 = 0;
aSummands[j]->FillTopLevelOperands(ep_mult, aMultiplicants2, iMaxIndex2);
int k0 = (aMultiplicants1[0]->type == ep_number ? 1 : 0);
int l0 = (aMultiplicants2[0]->type == ep_number ? 1 : 0);
if ((iMaxIndex1 - k0) != (iMaxIndex2 - l0)) {
delete[] aMultiplicants2;
continue;
}
bool bAllFound = true;
for (k = k0; k < iMaxIndex1 && bAllFound; k++) {
bool bFoundMatching = false;
for (l = l0; l < iMaxIndex2 && !bFoundMatching; l++)
if (aMultiplicants2[l] != NULL)
if (*(aMultiplicants1[k]) == *(aMultiplicants2[l])) {
bFoundMatching = true;
aMultiplicants2[l] = NULL;
}
if (!bFoundMatching)
bAllFound = false;
}
if (bAllFound) {
if (k0 == 1) {
if (l0 == 0)
aMultiplicants1[0]->nNumber += 1;
else {
aMultiplicants1[0]->nNumber += aMultiplicants2[0]->nNumber;
if (fabs(aMultiplicants1[0]->nNumber) < EPSILON)
aMultiplicants1[0]->nNumber = 0; // changed 22.02.2006.
}
} else {
double n;
if (l0 == 0)
n = 2;
else
n = 1 + aMultiplicants2[0]->nNumber;
CGCLCProverExpression a(*(aSummands[i]));
CGCLCProverExpression b(n);
*aSummands[i] = (b * a);
}
*aSummands[j] = 0.0;
delete[] aMultiplicants1;
delete[] aMultiplicants2;
delete[] aSummands;
return true;
} else
delete[] aMultiplicants2;
}
delete[] aMultiplicants1;
}
delete[] aSummands;
return false;
}
// --------------------------------------------------------------------------
int CGCLCProverExpression::CountTopLevelOperands(GCLCexperssion_type t) {
if (type != t)
return 1;
else
return GetArg(0).CountTopLevelOperands(t) +
GetArg(1).CountTopLevelOperands(t);
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::FillTopLevelOperands(GCLCexperssion_type t,
CGCLCProverExpression **a,
int &iIndex) {
if (type != t)
a[iIndex++] = this;
else {
GetArg(0).FillTopLevelOperands(t, a, iIndex);
GetArg(1).FillTopLevelOperands(t, a, iIndex);
}
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::OneSide() {
// a = b -> a + -b
// except for b=0 and numbers a,b such that a=b
if (type == ep_equality) {
if (GetArg(1).type == ep_number && GetArg(1).nNumber == 0)
return false;
if (GetArg(0).type == ep_number && GetArg(1).type == ep_number &&
GetArg(0).nNumber == GetArg(1).nNumber)
return false;
CGCLCProverExpression a(GetArg(0));
CGCLCProverExpression b(GetArg(1));
CGCLCProverExpression negOne(-1);
Set(ep_equality, a + (negOne * b), 0.0);
return true;
}
return false;
}
// --------------------------------------------------------------------------
bool CGCLCProverExpression::ToGeometricQuantities() {
CGCLCProverExpression m1, m2;
switch (type) {
case ep_identical:
m1 = p3(GetArgName(0), GetArgName(1), GetArgName(0));
m2 = 0.0;
break;
case ep_collinear:
m1 = s3(GetArgName(0), GetArgName(1), GetArgName(2));
m2 = 0.0;
break;
case ep_midpoint:
m1 = sratio(GetArgName(1), GetArgName(0), GetArgName(0), GetArgName(2));
m2 = 1.0;
break;
case ep_parallel:
m1 = s3(GetArgName(0), GetArgName(2), GetArgName(3));
m2 = s3(GetArgName(1), GetArgName(2), GetArgName(3));
break;
case ep_perpendicular:
m1 = p3(GetArgName(0), GetArgName(2), GetArgName(3));
m2 = p3(GetArgName(1), GetArgName(2), GetArgName(3));
break;
case ep_same_length:
m1 = p3(GetArgName(0), GetArgName(1), GetArgName(0));
m2 = p3(GetArgName(2), GetArgName(3), GetArgName(2));
break;
case ep_harmonic:
m1 = sratio(GetArgName(0), GetArgName(2), GetArgName(2), GetArgName(1));
m2 = sratio(GetArgName(3), GetArgName(0), GetArgName(3), GetArgName(1));
break;
default:
return false;
}
Set(ep_equality, m1, m2);
return true;
}
// --------------------------------------------------------------------------
bool CTheoremProver::GetPointCoordinates(const string &sPoint, double &x,
double &y) const {
for (list<CGCLCProverCommand>::const_iterator it = m_ProverCommands.begin();
it != m_ProverCommands.end(); it++) {
if ((it->type == p_point) || (it->type == p_inter) ||
(it->type == p_pratio) || (it->type == p_tratio) ||
(it->type == p_foot)) {
if (it->arg[0] == sPoint) {
x = it->x;
y = it->y;
return true;
}
}
}
return false;
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::SetType(GCLCexperssion_type t) { type = t; }
// --------------------------------------------------------------------------
int CGCLCProverExpression::Size() {
switch (type) {
case ep_number:
case ep_point:
case ep_constant:
case ep_segment:
case ep_segment_ratio:
case ep_s3:
case ep_s4:
case ep_p3:
case ep_p4:
return 1;
case ep_equality:
case ep_sum:
case ep_ratio:
case ep_mult:
return GetArg(0).Size() + GetArg(1).Size();
default:
return 0;
}
return 0;
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::PrettyPrint() const {
switch (type) {
case ep_number:
if ((double)((int)nNumber) == nNumber)
Print(cout, " " + i2s((int)nNumber) + " ");
else
Print(cout, " " + d2s(nNumber, 2) + " ");
break;
case ep_constant:
Print(cout, sName);
break;
case ep_point:
Print(cout, " " + sName);
break;
case ep_equality:
Print(cout, "(equal ");
break;
case ep_diffx:
Print(cout, "(diffx ");
break;
case ep_diffy:
Print(cout, "(diffy ");
break;
case ep_sum:
Print(cout, "(sum ");
break;
case ep_ratio:
Print(cout, "(ratio ");
break;
case ep_segment:
Print(cout, "(segment ");
break;
case ep_segment_ratio:
Print(cout, "(sratio ");
break;
case ep_mult:
Print(cout, "(ep_mult ");
break;
case ep_s3:
Print(cout, "(signed_area3 ");
break;
case ep_s4:
Print(cout, "(signed_area4 ");
break;
case ep_p3:
Print(cout, "(pythagoras_difference3 ");
break;
case ep_p4:
Print(cout, "(pythagoras_difference4 ");
break;
default:
break;
}
switch (type) {
case ep_point:
break;
case ep_equality:
case ep_sum:
case ep_mult:
case ep_ratio:
case ep_segment:
case ep_diffx:
case ep_diffy:
GetArg(0).PrettyPrint();
GetArg(1).PrettyPrint();
Print(cout, ")");
break;
case ep_s3:
case ep_p3:
GetArg(0).PrettyPrint();
GetArg(1).PrettyPrint();
GetArg(2).PrettyPrint();
Print(cout, ")");
break;
case ep_segment_ratio:
case ep_s4:
case ep_p4:
GetArg(0).PrettyPrint();
GetArg(1).PrettyPrint();
GetArg(2).PrettyPrint();
GetArg(3).PrettyPrint();
Print(cout, ")");
break;
case ep_unknown:
Print(cout, "unkown");
break;
default:
break;
}
cout << flush;
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::PrintLaTeX(ofstream &h) const {
Print(h, sPrintLaTeX(true));
}
// --------------------------------------------------------------------------
string CGCLCProverExpression::sPrintLaTeX(bool hasFractions) const {
string s;
switch (type) {
case ep_point:
s = sName;
break;
case ep_constant:
s = sName;
break;
case ep_number:
if ((double)((int)nNumber) == nNumber)
s = " " + i2s((int)nNumber) + " ";
else {
if (nNumber == 0.5)
s = "\\frac{1}{2} ";
else if (nNumber == -0.5)
s = "-\\frac{1}{2} ";
else if (nNumber == 0.25)
s = "\\frac{1}{4} ";
else if (nNumber == -0.25)
s = "-\\frac{1}{4} ";
else if (nNumber == 0.75)
s = "\\frac{3}{4} ";
else if (nNumber == -0.75)
s = "-\\frac{3}{4} ";
else if (nNumber == 0.125)
s = "\\frac{1}{8} ";
else if (nNumber == -0.125)
s = "-\\frac{1}{8} ";
else
s = d2s(nNumber, -1);
}
break;
case ep_inequality:
s = GetArg(0).sPrintLaTeX(hasFractions) + " \\neq " +
GetArg(1).sPrintLaTeX(hasFractions);
break;
case ep_equality:
s = GetArg(0).sPrintLaTeX(hasFractions) + " = " +
GetArg(1).sPrintLaTeX(hasFractions);
break;
case ep_sum:
s = (hasFractions ? " \\left(" : " (") +
GetArg(0).sPrintLaTeX(hasFractions) + " + " +
GetArg(1).sPrintLaTeX(hasFractions) + (hasFractions ? "\\right)" : ")");
break;
case ep_mult:
s = (hasFractions ? " \\left(" : " (") +
GetArg(0).sPrintLaTeX(hasFractions) + " \\cdot " +
GetArg(1).sPrintLaTeX(hasFractions) + (hasFractions ? "\\right)" : ")");
break;
case ep_ratio:
s = " \\frac{" + GetArg(0).sPrintLaTeX(hasFractions) + "}{" +
GetArg(1).sPrintLaTeX(hasFractions) + "}";
break;
case ep_s3:
s = " S_{" + GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) +
GetArg(2).sPrintLaTeX(hasFractions) + "}";
break;
case ep_p3:
s = " P_{" + GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) +
GetArg(2).sPrintLaTeX(hasFractions) + "}";
break;
case ep_segment:
s = " {" + GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) + "}";
break;
case ep_segment_ratio:
s = " \\frac{\\overrightarrow{" + GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) + "}}{\\overrightarrow{" +
GetArg(2).sPrintLaTeX(hasFractions) +
GetArg(3).sPrintLaTeX(hasFractions) + "}}";
break;
case ep_harmonic:
s = " \\frac{\\overrightarrow{" + GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(2).sPrintLaTeX(hasFractions) + "}}{\\overrightarrow{" +
GetArg(2).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) + "}} \\cdot " +
" \\frac{\\overrightarrow{" + GetArg(3).sPrintLaTeX(hasFractions) +
GetArg(0).sPrintLaTeX(hasFractions) + "}}{\\overrightarrow{" +
GetArg(3).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) + "}} = 1";
break;
case ep_s4:
s = " S_{" + GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) +
GetArg(2).sPrintLaTeX(hasFractions) +
GetArg(3).sPrintLaTeX(hasFractions) + "}";
break;
case ep_p4:
s = " P_{" + GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) +
GetArg(2).sPrintLaTeX(hasFractions) +
GetArg(3).sPrintLaTeX(hasFractions) + "}";
break;
case ep_diffy:
case ep_diffx:
s = (string)(hasFractions ? "\\left(" : " (") +
(type == ep_diffy ? "y" : "x") + (hasFractions ? "\\left(" : "(") +
GetArg(0).sPrintLaTeX(hasFractions) +
(hasFractions ? "\\right) - " : ") - ") +
(type == ep_diffy ? "y" : "x") + (hasFractions ? "\\left(" : "(") +
GetArg(1).sPrintLaTeX(hasFractions) +
(hasFractions ? "\\right)" : ")") + (hasFractions ? "\\right)" : ")");
break;
case ep_algsumzero3:
s = GetArg(0).sPrintLaTeX(hasFractions) + "+" +
GetArg(1).sPrintLaTeX(hasFractions) + "+" +
GetArg(2).sPrintLaTeX(hasFractions) + "=0 ";
break;
case ep_angle:
s = "tan(\\angle " + GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) +
GetArg(2).sPrintLaTeX(hasFractions) + ") ";
break;
case ep_tangens_num:
s = "\\angle " + GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) +
GetArg(2).sPrintLaTeX(hasFractions) + " ";
break;
case ep_tangens_den:
s = "\\frac{1}{\\angle " + GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) +
GetArg(2).sPrintLaTeX(hasFractions) + "} ";
break;
case ep_parallel:
s = GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) + "\\parallel " +
GetArg(2).sPrintLaTeX(hasFractions) +
GetArg(3).sPrintLaTeX(hasFractions) + " ";
break;
case ep_perpendicular:
s = GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) + "\\perp " +
GetArg(2).sPrintLaTeX(hasFractions) +
GetArg(3).sPrintLaTeX(hasFractions) + " ";
break;
case ep_collinear:
s = "collinear( " + GetArg(0).sPrintLaTeX(hasFractions) + ", " +
GetArg(1).sPrintLaTeX(hasFractions) + ", " +
GetArg(2).sPrintLaTeX(hasFractions) + ") ";
break;
case ep_same_length:
s = GetArg(0).sPrintLaTeX(hasFractions) +
GetArg(1).sPrintLaTeX(hasFractions) + "\\cong " +
GetArg(2).sPrintLaTeX(hasFractions) +
GetArg(3).sPrintLaTeX(hasFractions) + " ";
break;
case ep_identical:
s = GetArg(0).sPrintLaTeX(hasFractions) + "\\equiv " +
GetArg(1).sPrintLaTeX(hasFractions) + " ";
break;
default:
Print(cerr, "Output for command " + GetName() + " not implemented!\n");
throw 0;
break;
}
return s;
}
// --------------------------------------------------------------------------
void CGCLCProverExpression::PrintXML(ofstream &h, int indent) const {
Print(h, sPrintXML(indent));
}
// --------------------------------------------------------------------------
string CGCLCProverExpression::sPrintXML(int indent) const {
string s;
switch (type) {
case ep_point:
s = "<point>" + sName + "</point>";
break;
case ep_constant:
s = make_indent(indent) + "<constant>" + sName + "</constant>\n";
break;
case ep_number:
s = make_indent(indent) + "<number>" + d2s(nNumber, -1) + "</number>\n";
break;
case ep_equality:
case ep_identical: // added 25.04.2008
s += make_indent(indent) + "<equality>\n" + make_indent(indent + 1) +
"<expression>\n" + GetArg(0).sPrintXML(indent + 2) +
make_indent(indent + 1) + "</expression>\n" + make_indent(indent + 1) +
"<expression>\n" + GetArg(1).sPrintXML(indent + 2) +
make_indent(indent + 1) + "</expression>\n" + make_indent(indent) +
"</equality>\n";
break;
case ep_sum:
s += make_indent(indent) + "<sum>\n" + make_indent(indent + 1) +
"<expression>\n" + GetArg(0).sPrintXML(indent + 2) +
make_indent(indent + 1) + "</expression>\n" + make_indent(indent + 1) +
"<expression>\n" + GetArg(1).sPrintXML(indent + 2) +
make_indent(indent + 1) + "</expression>\n" + make_indent(indent) +
"</sum>\n";
break;
case ep_mult:
s += make_indent(indent) + "<mult>\n" + make_indent(indent + 1) +
"<expression>\n" + GetArg(0).sPrintXML(indent + 2) +
make_indent(indent + 1) + "</expression>\n" + make_indent(indent + 1) +
"<expression>\n" + GetArg(1).sPrintXML(indent + 2) +
make_indent(indent + 1) + "</expression>\n" + make_indent(indent) +
"</mult>\n";
break;
case ep_ratio:
s += make_indent(indent) + "<fraction>\n" + make_indent(indent + 1) +
"<expression>\n" + GetArg(0).sPrintXML(indent + 2) +
make_indent(indent + 1) + "</expression>\n" + make_indent(indent + 1) +
"<expression>\n" + GetArg(1).sPrintXML(indent + 2) +
make_indent(indent + 1) + "</expression>\n" + make_indent(indent) +
"</fraction>\n";
break;
case ep_s3:
s += make_indent(indent) + "<signed_area3>" +
GetArg(0).sPrintXML(indent + 1) + GetArg(1).sPrintXML(indent + 1) +
GetArg(2).sPrintXML(indent + 1) + "</signed_area3>\n";
break;
case ep_p3:
s += make_indent(indent) + "<pythagoras_difference3>" +
GetArg(0).sPrintXML(indent + 1) + GetArg(1).sPrintXML(indent + 1) +
GetArg(2).sPrintXML(indent + 1) + "</pythagoras_difference3>\n";
break;
case ep_segment:
s += make_indent(indent) + "<segment>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + "</segment>\n";
break;
case ep_segment_ratio:
s += make_indent(indent) + "<segment_ratio><segment>" +
GetArg(0).sPrintXML(indent + 1) + GetArg(1).sPrintXML(indent + 1) +
"</segment>" + "<segment>" + GetArg(2).sPrintXML(indent + 1) +
GetArg(3).sPrintXML(indent + 1) + "</segment></segment_ratio>\n";
break;
case ep_s4:
s += make_indent(indent) + "<signed_area4>" +
GetArg(0).sPrintXML(indent + 1) + GetArg(1).sPrintXML(indent + 1) +
GetArg(2).sPrintXML(indent + 1) + GetArg(3).sPrintXML(indent + 1) +
"</signed_area4>\n";
break;
case ep_p4:
s += make_indent(indent) + "<pythagoras_difference4>" +
GetArg(0).sPrintXML(indent + 1) + GetArg(1).sPrintXML(indent + 1) +
GetArg(2).sPrintXML(indent + 1) + GetArg(3).sPrintXML(indent + 1) +
"</pythagoras_difference4>\n";
break;
case ep_angle:
s += "<angle_tangens>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + GetArg(2).sPrintXML(indent + 1) +
"</angle_tangens>\n";
break;
case ep_algsumzero3:
s += "<algebraic_sum_is_zero>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + GetArg(2).sPrintXML(indent + 1) +
"</algebraic_sum_is_zero>\n";
break;
case ep_collinear:
s += "<collinear>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + GetArg(2).sPrintXML(indent + 1) +
"</collinear>\n";
break;
case ep_diffx:
s += "<x_projection_difference>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + "</x_projection_difference>\n";
break;
case ep_diffy:
s += "<y_projection_difference>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + "</y_projection_difference>\n";
break;
case ep_harmonic:
s += "<harmonic>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + GetArg(2).sPrintXML(indent + 1) +
GetArg(3).sPrintXML(indent + 1) + "</harmonic>\n";
break;
case ep_parallel:
s += "<parallel>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + GetArg(2).sPrintXML(indent + 1) +
GetArg(3).sPrintXML(indent + 1) + "</parallel>\n";
break;
case ep_perpendicular:
s += "<perpendicular>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + GetArg(2).sPrintXML(indent + 1) +
GetArg(3).sPrintXML(indent + 1) + "</perpendicular>\n";
break;
case ep_tangens_den:
s += "<angle_tangens_denominator>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + GetArg(2).sPrintXML(indent + 1) +
"</angle_tangens_denominator>\n";
break;
case ep_tangens_num:
s += "<angle_tangens_numerator>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + GetArg(2).sPrintXML(indent + 1) +
"</angle_tangens_numerator>\n";
break;
case ep_same_length:
s += "<equal_segments> <segment>" + GetArg(0).sPrintXML(indent + 1) +
GetArg(1).sPrintXML(indent + 1) + "</segment>\n<segment>" +
GetArg(2).sPrintXML(indent + 1) + GetArg(3).sPrintXML(indent + 1) +
"</segment>\n</equal_segments>\n";
break;
default:
Print(cerr, "Command " + GetName() + " is not supported for XML output!\n");
throw - 1;
break;
}
return s;
}
| 29.67628 | 83 | 0.516027 | ubavic |
6c787aec2dc1230e4601300a1359407f33d1a329 | 711 | cxx | C++ | reflex/test/implementation/members/GetTest.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 10 | 2018-03-26T07:41:44.000Z | 2021-11-06T08:33:24.000Z | reflex/test/implementation/members/GetTest.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | null | null | null | reflex/test/implementation/members/GetTest.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 1 | 2020-11-17T03:17:00.000Z | 2020-11-17T03:17:00.000Z | // Check getting of members
#include "util/HelperMacros.hpp"
#include "Reflex/Type.h"
#include "Reflex/Member.h"
#include "Get.hpp"
using namespace Reflex;
REFLEX_TEST(test001)
{
// See e.g. https://savannah.cern.ch/bugs/?65759
Type tT = Type::ByName("St<int>::T");
CPPUNIT_ASSERT(tT);
St<int>::A::s = 43;
St<int>::T o;
o.a = 42;
Member mA = tT.DataMemberByName("a");
CPPUNIT_ASSERT(mA);
Object objA = mA.Get(Object::Create(o));
CPPUNIT_ASSERT(objA);
CPPUNIT_ASSERT_EQUAL(42, *(int*)objA.Address());
Member mS = tT.DataMemberByName("s");
CPPUNIT_ASSERT(mS);
Object objS = mS.Get();
CPPUNIT_ASSERT(objS);
CPPUNIT_ASSERT_EQUAL(43, *(int*)objS.Address());
}
| 20.911765 | 51 | 0.652602 | paulwratt |
6c7b4c7e3d4e289295807145a6830bde246f7f86 | 4,130 | cpp | C++ | Map/LRUCache.cpp | UltraProton/Placement-Prepration | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | null | null | null | Map/LRUCache.cpp | UltraProton/Placement-Prepration | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | 3 | 2020-05-08T18:02:51.000Z | 2020-05-09T08:37:35.000Z | Map/LRUCache.cpp | UltraProton/PlacementPrep | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef struct node{
int key;
int val;
node *left;
node *right;
node(int k,int v): key(k), val(v),left(NULL), right(NULL) {};
} Node;
class LRU_Cache{
public:
Node *dummy_head;
Node *dummy_tail;
int size;
int curr_size;
unordered_map<int,Node *> mp;
LRU_Cache(int size){
this->size=size;
curr_size=0;
dummy_head= new Node(-1,-1);
dummy_tail= new Node(-1,-1);
dummy_head->left=NULL;
dummy_tail->right=NULL;
dummy_head->right=dummy_tail;
dummy_tail->left=dummy_head;
}
void set(int key,int val);
int get(int key);
void push_front(Node *x);
void remove(Node *x);
void pop_last();
};
void LRU_Cache:: set(int key,int val){
if(mp.find(key)==mp.end()){
Node *temp= new Node(key,val);
//if cache is full remove the last element
if(curr_size==size){
pop_last();
curr_size--;
}
push_front(temp);
mp.insert(make_pair(key,temp));
curr_size++;
}
else{
mp[key]->val=val;
remove(mp[key]);
push_front(mp[key]);
}
}
int LRU_Cache:: get(int key){
if(mp.find(key)==mp.end()){
return -1;
}
else{
remove(mp[key]);
push_front(mp[key]);
return mp[key]->val;
}
}
void LRU_Cache :: push_front(Node *x){
x->right= dummy_head->right;
x->left=dummy_head;
dummy_head->right=x;
x->right->left= x;
}
void LRU_Cache :: remove(Node *x){
x->left->right=x->right;
x->right->left= x->left;
x->left=NULL;
x->right=NULL;
}
void LRU_Cache :: pop_last(){
//assert(dummy_tail->left);
Node *temp= dummy_tail->left;
temp->left->right=dummy_tail;
dummy_tail->left= temp->left;
//cout<<'x'<<" ";
mp.erase(temp->key);
free(temp);
}
int main(int argc, char const *argv[])
{
LRU_Cache obj(2);
/*
obj.set(1,2);
//cout<<obj.get(1)<<" "<<obj.curr_size<<endl;
obj.set(2,3);
//cout<<obj.get(2)<<" "<<obj.curr_size<<endl;
obj.set(7,5);
//cout<<obj.get(1)<<" "<<obj.curr_size<<endl;
Node *l= obj.dummy_head;
//cout<<l->key<<endl;
//cout<<l->right->key<<endl;
while(l->right!=NULL){
cout<<l->key<<" ";
l=l->right;
}
cout<<endl;
obj.set(9,10);
obj.set(11,12);
obj.set(13,14);
cout<<obj.get(7)<<" "<<obj.curr_size<<endl;
cout<<obj.get(2)<<" "<<obj.curr_size<<endl;
l= obj.dummy_head;
//cout<<l->key<<endl;
//cout<<l->right->key<<endl;
while(l->right!=NULL){
cout<<l->key<<" ";
l=l->right;
}
cout<<endl;
/*
Node *l= obj.dummy_head;
cout<<l->key<<endl;
//cout<<l->right->key<<endl;
while(l->right!=NULL){
cout<<l->key<<" ";
l=l->right;
}
obj.set(7,9);
cout<<obj.get(7)<<" "<<obj.curr_size<<endl;
*/
/*
obj.set(1,5);
obj.set(4,5);
obj.set(6,7);
cout<<obj.get(4)<<endl;
cout<<obj.get(1)<<endl;
*/
//SET 1 2 SET 2 3 SET 1 5 SET 4 5 SET 6 7 GET 4 GET 1
//SET 1 2 SET 2 3 SET 1 5 SET 4 5 SET 6 7 GET 4 GET 1
/*
obj.set(1,2);
obj.set(2,3);
obj.set(1,5);
obj.set(4,5);
obj.set(6,7);
cout<<obj.get(4)<<endl;
cout<<obj.get(1)<<endl;
Node *l= obj.dummy_head;
//cout<<l->key<<endl;
//cout<<l->right->key<<endl;
while(l->right!=NULL){
cout<<l->key<<" ";
l=l->right;
}
*/
//1
//GET 100 GET 26 GET 91 SET 55 40 GET 70 GET 43 GET 98 SET 5 56 GET 12
/*
LRU_Cache obj1(1);
cout<<obj1.get(100)<<endl;
cout<< obj1.get(26)<<endl;
cout<<obj1.get(91)<<endl;
obj1.set(55,40);
cout<<obj1.get(70)<<endl;
cout<<obj1.get(43)<<endl;
cout<<obj1.get(98)<<endl;
obj1.set(5,56);
cout<<obj1.get(12)<<endl;
cout<<obj1.get(29)<<endl;
cout<<obj1.dummy_head->right->key<<endl;
*/
LRU_Cache obj2(2);
//S 2 1 S 1 1 S 2 3 S 4 1 G 1 G 2
obj2.set(2,1);
obj2.set(1,1);
obj2.set(2,3);
obj2.set(4,1);
cout<<obj2.get(1)<<endl;
cout<<obj2.get(2)<<endl;
return 0;
}
| 19.389671 | 71 | 0.528814 | UltraProton |
6c868f01888df62407a66e1492ca2df9ca24907b | 176 | cc | C++ | proc/display-env.cc | DavidCai1993/APUE-exercises | 5c5b74d8042176cc07a73380149c831d20da407e | [
"MIT"
] | null | null | null | proc/display-env.cc | DavidCai1993/APUE-exercises | 5c5b74d8042176cc07a73380149c831d20da407e | [
"MIT"
] | null | null | null | proc/display-env.cc | DavidCai1993/APUE-exercises | 5c5b74d8042176cc07a73380149c831d20da407e | [
"MIT"
] | null | null | null | #include <iostream>
#include "../common.h"
int main (int argc, char** argv, char** envp) {
for (char** env = envp; *env != NULL; env++) {
PRINT(*env)
}
return 0;
}
| 16 | 48 | 0.556818 | DavidCai1993 |
6c89545aac41622e2766c1afe06c61c43012ea11 | 6,396 | cpp | C++ | isaac_variant_caller/src/lib/blt_common/blt_arg_parse_util.cpp | sequencing/isaac_variant_caller | ed24e20b097ee04629f61014d3b81a6ea902c66b | [
"BSL-1.0"
] | 21 | 2015-01-09T01:11:28.000Z | 2019-09-04T03:48:21.000Z | isaac_variant_caller/src/lib/blt_common/blt_arg_parse_util.cpp | sequencing/isaac_variant_caller | ed24e20b097ee04629f61014d3b81a6ea902c66b | [
"BSL-1.0"
] | 4 | 2015-07-23T09:38:39.000Z | 2018-02-01T05:37:26.000Z | isaac_variant_caller/src/lib/blt_common/blt_arg_parse_util.cpp | sequencing/isaac_variant_caller | ed24e20b097ee04629f61014d3b81a6ea902c66b | [
"BSL-1.0"
] | 13 | 2015-01-29T16:41:26.000Z | 2021-06-25T02:42:32.000Z | // -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Copyright (c) 2009-2013 Illumina, Inc.
//
// This software is provided under the terms and conditions of the
// Illumina Open Source Software License 1.
//
// You should have received a copy of the Illumina Open Source
// Software License 1 along with this program. If not, see
// <https://github.com/sequencing/licenses/>
//
/// \file
///
/// \author Chris Saunders
///
#include "blt_common/blt_arg_parse_util.hh"
arg_data::
arg_data(int init_argc,
char* init_argv[],
const prog_info& init_pinfo)
: argmark(init_argc,false)
, argstr(init_argc)
, pinfo(init_pinfo) {
for (int i(0); i<init_argc; ++i) argstr[i]=init_argv[i];
if (argmark.size()) argmark[0]=true;
for (unsigned i(0); i<argstr.size(); ++i) {
if (i) cmdline += ' ';
cmdline += argstr[i];
}
}
arg_data::
arg_data(const std::vector<std::string>& arg,
const prog_info& init_pinfo,
const std::string& init_cmdline)
: argmark(arg.size(),false)
, argstr(arg)
, cmdline(init_cmdline)
, pinfo(init_pinfo) {}
void
arg_data::
finalize_args() {
const unsigned as(size());
for (unsigned i(0); i<as; ++i) {
if (! argmark[i]) pinfo.usage((std::string("Invalid argument: ")+argstr[i]).c_str());
}
}
static
bool
is_valid_xrange(const double val,
bool is_allow_zero,
bool is_no_max_check) {
return (((val > 0.) || (is_allow_zero && (val >= 0.))) && (is_no_max_check || (val <= 1.)));
}
static
void
set_xrange_val(const prog_info& pinfo,
const char* arg_label,
const char* arg,
double& val,
bool is_allow_zero,
bool is_no_max_check) {
bool is_val_invalid(false);
try {
val=boost::lexical_cast<double>(arg);
} catch (boost::bad_lexical_cast&) {
is_val_invalid=true;
}
is_val_invalid = (is_val_invalid || (! is_valid_xrange(val,is_allow_zero,is_no_max_check)));
if (is_val_invalid) {
std::ostringstream oss;
oss << "argument after flag " << arg_label << " (" << arg << ") is not valid";
pinfo.usage(oss.str().c_str());
}
}
void
set_xrange_arg(unsigned& argi,
arg_data& ad,
bool& is_val_set,
double& val,
bool is_allow_zero,
bool is_no_max_check) {
const char* arg_label(ad.argstr[argi].c_str());
ad.argmark[argi] = true;
if (++argi>=ad.argstr.size()) {
ad.pinfo.usage((std::string("no value following ")+arg_label).c_str());
}
if (is_val_set) { ad.pinfo.usage((std::string("multiple ")+arg_label+" arguments").c_str()); }
set_xrange_val(ad.pinfo,arg_label,ad.argstr[argi].c_str(),val,is_allow_zero,is_no_max_check);
is_val_set=true;
}
void
set_filename_arg(unsigned& argi,
arg_data& ad,
bool& is_val_set,
std::string& file) {
const char* arg_label(ad.argstr[argi].c_str());
ad.argmark[argi] = true;
if (++argi>=ad.argstr.size()) {
ad.pinfo.usage((std::string("no value following: ")+arg_label).c_str());
}
if (is_val_set) { ad.pinfo.usage((std::string("multiple ")+arg_label+" arguments").c_str()); }
file=ad.argstr[argi];
if (file.empty()) { ad.pinfo.usage((std::string("empty filename following: ")+arg_label).c_str()); }
is_val_set=true;
}
void
set_win_arg(unsigned& argi,
arg_data& ad,
bool& is_val_set,
int& val1,
unsigned& val2) {
const char* arg_label(ad.argstr[argi].c_str());
ad.argmark[argi] = true;
if (++argi>=ad.argstr.size()) {
ad.pinfo.usage((std::string("two arguments must follow ")+arg_label).c_str());
}
if (is_val_set) { ad.pinfo.usage((std::string("multiple ")+arg_label+" arguments").c_str()); }
set_val(ad.pinfo,arg_label,ad.argstr[argi].c_str(),val1);
ad.argmark[argi] = true;
if (++argi>=ad.argstr.size()) {
ad.pinfo.usage((std::string("two arguments must follow ")+arg_label).c_str());
}
int val2_tmp;
set_val(ad.pinfo,arg_label,ad.argstr[argi].c_str(),val2_tmp);
if (val2_tmp<0) {
ad.pinfo.usage((std::string("second argument following: ")+arg_label+" must be non-negative\n").c_str());
}
val2=val2_tmp;
is_val_set=true;
}
void
set_nploid_arg(unsigned& argi,
arg_data& ad,
bool& is_val_set,
int& val1,
double& val2) {
const char* arg_label(ad.argstr[argi].c_str());
ad.argmark[argi] = true;
if (++argi>=ad.argstr.size()) {
ad.pinfo.usage((std::string("two arguments must follow ")+arg_label).c_str());
}
if (is_val_set) { ad.pinfo.usage((std::string("multiple ")+arg_label+" arguments").c_str()); }
set_val(ad.pinfo,arg_label,ad.argstr[argi].c_str(),val1);
ad.argmark[argi] = true;
if (++argi>=ad.argstr.size()) {
ad.pinfo.usage((std::string("two arguments must follow ")+arg_label).c_str());
}
const bool is_allow_zero(false);
const bool is_no_max_check(false);
set_xrange_val(ad.pinfo,arg_label,ad.argstr[argi].c_str(),val2,is_allow_zero,is_no_max_check);
is_val_set=true;
}
void
set_xrange_win_arg(unsigned& argi,
arg_data& ad,
bool& is_val_set,
double& val1,
unsigned& val2) {
const char* arg_label(ad.argstr[argi].c_str());
ad.argmark[argi] = true;
if (++argi>=ad.argstr.size()) {
ad.pinfo.usage((std::string("two arguments must follow ")+arg_label).c_str());
}
if (is_val_set) { ad.pinfo.usage((std::string("multiple ")+arg_label+" arguments").c_str()); }
const bool is_allow_zero(false);
const bool is_no_max_check(false);
set_xrange_val(ad.pinfo,arg_label,ad.argstr[argi].c_str(),val1,is_allow_zero,is_no_max_check);
ad.argmark[argi] = true;
if (++argi>=ad.argstr.size()) {
ad.pinfo.usage((std::string("two arguments must follow ")+arg_label).c_str());
}
int val2_tmp;
set_val(ad.pinfo,arg_label,ad.argstr[argi].c_str(),val2_tmp);
if (val2_tmp<0) {
ad.pinfo.usage((std::string("second argument following: ")+arg_label+" must be non-negative\n").c_str());
}
val2=val2_tmp;
is_val_set=true;
}
| 27.568966 | 113 | 0.601001 | sequencing |
6c8aa1b3180a2b61d132ea2cf5ffd4c304c7be91 | 480 | cpp | C++ | oops/objectAsArgument.cpp | misrapk/C-Basic-Codes | 4d959576a15b3846f3c1fd5c870c6821d8a90ecc | [
"MIT"
] | null | null | null | oops/objectAsArgument.cpp | misrapk/C-Basic-Codes | 4d959576a15b3846f3c1fd5c870c6821d8a90ecc | [
"MIT"
] | null | null | null | oops/objectAsArgument.cpp | misrapk/C-Basic-Codes | 4d959576a15b3846f3c1fd5c870c6821d8a90ecc | [
"MIT"
] | null | null | null | // pass object as argument
#include<iostream>
using namespace std;
class test{
int var;
public:
test(int i){
var = i;
cout<<"CONSTRUCTING "<<var<<"\n";
}
~test(){
cout<<"Destructing "<<var<<"\n";
}
int get(){
return var;
}
};
void f(test t);
int main(){
test ob1(10);
cout<<"In LOCAL MAIN: "<< ob1.get()<<"\n";
f(ob1);
cout<<"THis is main()\n";
return 0;
}
void f(test t){
cout<<"THis is function test : "<<t.get();
cout<<endl;
}
| 12.307692 | 43 | 0.54375 | misrapk |
6c991a9eb542b7004cce5341ba54b95256aa5e2d | 48 | cpp | C++ | Dechetterie-Librairie/ControlIPBox.cpp | Norskel/Dechetterie | 343c4b97b7ea5f0dbb3394168e2a75d2a6b538e6 | [
"Apache-2.0"
] | 2 | 2018-04-05T11:02:00.000Z | 2019-01-26T17:55:20.000Z | Dechetterie-Librairie/ControlIPBox.cpp | Norskel/Dechetterie | 343c4b97b7ea5f0dbb3394168e2a75d2a6b538e6 | [
"Apache-2.0"
] | null | null | null | Dechetterie-Librairie/ControlIPBox.cpp | Norskel/Dechetterie | 343c4b97b7ea5f0dbb3394168e2a75d2a6b538e6 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "ControlIPBox.h"
| 16 | 26 | 0.708333 | Norskel |
6c9d79ab3ba2a98cbf2dcb57dcf62896e9e7db5e | 1,239 | cpp | C++ | src/IContentProcessor.cpp | RudiBik/flexgrep | d7bb07350693f129481572f41639df95f8a03261 | [
"BSD-3-Clause"
] | 4 | 2022-02-11T18:43:55.000Z | 2022-02-19T09:50:09.000Z | src/IContentProcessor.cpp | RudiBik/flexgrep | d7bb07350693f129481572f41639df95f8a03261 | [
"BSD-3-Clause"
] | null | null | null | src/IContentProcessor.cpp | RudiBik/flexgrep | d7bb07350693f129481572f41639df95f8a03261 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2022, Rudi Bikschentajew
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <ContentProcessors/IContentProcessor.hpp>
// filters
#include <PathFilter/ContentRegexFilter.hpp>
// processors
#include <ContentProcessors/ParallelContentProcessor/ParallelContentProcessor.hpp>
#include <ContentProcessors/SequentialContentProcessor.hpp>
namespace lg {
template<typename OutputIterator>
std::unique_ptr<IContentProcessor>
IContentProcessor::create(OutputIterator oiter,
std::shared_ptr<const Configuration> opt)
{
// Create the content filter
// if regex filter
auto contentFilter =
std::make_shared<ContentRegexFilter>(opt->mRegexContent);
if (!contentFilter) {
// TODO: Throw exception
}
// Create the processor (single- or multi-threaded)
if (opt->mParallelContentFiltering) {
return std::make_unique<ParallelContentProcessor<OutputIterator>>(
oiter, contentFilter);
} else {
return std::make_unique<SequentialContentProcessor<OutputIterator>>(
oiter, contentFilter);
}
}
} // namespace lg
| 29.5 | 82 | 0.722357 | RudiBik |
6c9e5c1b0893a9b1645b1c62b4dde6594351c532 | 25,694 | cpp | C++ | src/compile/BrainfuckCompiler.cpp | nbozidarevic/freud | d16f1930abef0360a8cd0f863a6c003f080b11c3 | [
"MIT"
] | null | null | null | src/compile/BrainfuckCompiler.cpp | nbozidarevic/freud | d16f1930abef0360a8cd0f863a6c003f080b11c3 | [
"MIT"
] | null | null | null | src/compile/BrainfuckCompiler.cpp | nbozidarevic/freud | d16f1930abef0360a8cd0f863a6c003f080b11c3 | [
"MIT"
] | null | null | null | #include "BrainfuckCompiler.h"
using namespace antlr4;
BrainfuckCompiler::BrainfuckCompiler(
istream& input,
ostream& output
):input(input), output(output) {
pointer = 0;
}
void BrainfuckCompiler::run() {
ANTLRInputStream antlrInput(input);
SimpleCLexer lexer(&antlrInput);
CommonTokenStream tokens(&lexer);
SimpleCParser parser(&tokens);
SimpleCParser::CompilationUnitContext* tree = parser.compilationUnit();
// output << endl;
visitCompilationUnit(tree);
output << endl;
// output << endl << tree->toStringTree(&parser) << endl;
return;
}
int BrainfuckCompiler::copyValue(int source, int destination) {
if (source == destination) {
return destination;
}
int helperPointer = memory.getTemporaryCell();
movePointer(helperPointer);
output << "[-]";
movePointer(destination);
output << "[-]";
movePointer(source);
output << "[-";
movePointer(destination);
output << "+";
movePointer(helperPointer);
output << "+";
movePointer(source);
output << "]";
movePointer(helperPointer);
output << "[-";
movePointer(source);
output << "+";
movePointer(helperPointer);
output << "]";
return destination;
}
int BrainfuckCompiler::moveValue(int source, int destination) {
if (source == destination) {
return destination;
}
movePointer(destination);
output << "[-]";
movePointer(source);
output << "[-";
movePointer(destination);
output << "+";
movePointer(source);
output << "]";
return destination;
}
int BrainfuckCompiler::duplicateValue(int source) {
int destination = memory.getTemporaryCell();
copyValue(source, destination);
return destination;
}
int BrainfuckCompiler::setValue(int destination, int value) {
movePointer(destination);
output << "[-]";
for (int i = 0; i < value; ++i) {
output << "+";
}
return destination;
}
void BrainfuckCompiler::movePointer(int destination) {
if (pointer == destination) {
return;
}
unsigned char c = '>';
if (pointer > destination) {
c = '<';
}
for (int i = 0; i < abs(pointer - destination); ++i) {
output << c;
}
pointer = destination;
}
int BrainfuckCompiler::getPointerForConstValue(unsigned char value) {
int pointer = memory.getTemporaryCell();
return setValue(pointer, value);
}
int BrainfuckCompiler::addValues(int a, int b) {
int aCopy = duplicateValue(a);
int bCopy = duplicateValue(b);
int result = memory.getTemporaryCell();
movePointer(result);
output << "[-]";
movePointer(aCopy);
output << "[-";
movePointer(result);
output << "+";
movePointer(aCopy);
output << "]";
movePointer(bCopy);
output << "[-";
movePointer(result);
output << "+";
movePointer(bCopy);
output << "]";
return result;
}
int BrainfuckCompiler::subtractValues(int a, int b) {
int aCopy = duplicateValue(a);
int bCopy = duplicateValue(b);
int result = memory.getTemporaryCell();
movePointer(result);
output << "[-]";
movePointer(aCopy);
output << "[-";
movePointer(result);
output << "+";
movePointer(aCopy);
output << "]";
movePointer(bCopy);
output << "[-";
movePointer(result);
output << "-";
movePointer(bCopy);
output << "]";
return result;
}
int BrainfuckCompiler::multiplyValues(int a, int b) {
int aCopy = duplicateValue(a);
int result = getPointerForConstValue(0);
movePointer(aCopy);
output << "[-";
int newResult = addValues(b, result);
moveValue(newResult, result);
movePointer(aCopy);
output << "]";
return result;
}
int BrainfuckCompiler::divideValues(int a, int b) {
int aCopy = duplicateValue(a);
int result = getPointerForConstValue(0);
performWhile(
[&]() -> int {
return this->greaterThanOrEqual(aCopy, b);
},
[&]() -> void {
this->movePointer(result);
this->output << "+";
this->moveValue(this->subtractValues(aCopy, b), aCopy);
}
);
return result;
}
int BrainfuckCompiler::modValues(int a, int b) {
int result = getPointerForConstValue(0);
moveValue(
subtractValues(
a,
multiplyValues(
divideValues(a, b),
b
)
),
result
);
return result;
}
int BrainfuckCompiler::negate(int a) {
int result = memory.getTemporaryCell();
performIfElse(
a,
[&]() -> void {
this->setValue(result, 0);
},
[&]() -> void {
this->setValue(result, 1);
}
);
return result;
}
int BrainfuckCompiler::isEqual(int a, int b) {
int aCopy = duplicateValue(a);
int bCopy = duplicateValue(b);
int result = getPointerForConstValue(0);
movePointer(aCopy);
output << "[-";
movePointer(bCopy);
output << "-";
movePointer(aCopy);
output << "]";
performIfElse(
negate(aCopy),
[&]() -> void {
this->performIfElse(
this->negate(bCopy),
[&]() -> void {
setValue(result, 1);
},
[]() -> void {}
);
},
[]() -> void {}
);
return result;
}
int BrainfuckCompiler::logicalAnd(int a, int b) {
int result = getPointerForConstValue(0);
performIfElse(
a,
[&]() -> void {
this->performIfElse(
b,
[&]() -> void {
setValue(result, 1);
},
[]() -> void {}
);
},
[]() -> void {}
);
return result;
}
int BrainfuckCompiler::logicalOr(int a, int b) {
int result = getPointerForConstValue(0);
this->performIfElse(
a,
[&]() -> void {
setValue(result, 1);
},
[]() -> void {}
);
this->performIfElse(
b,
[&]() -> void {
setValue(result, 1);
},
[]() -> void {}
);
return result;
}
int BrainfuckCompiler::lessThan(int a, int b) {
int aCopy = duplicateValue(a);
int bCopy = duplicateValue(b);
int result = memory.getTemporaryCell();
movePointer(result);
output << "[-]";
performWhile(
[&]() -> int {
return logicalAnd(aCopy, bCopy);
},
[&]() -> void {
this->movePointer(aCopy);
output << "-";
this->movePointer(bCopy);
output << "-";
}
);
performIfElse(
logicalAnd(negate(aCopy), bCopy),
[&]() -> void {
this->setValue(result, 1);
},
[]() -> void {}
);
return result;
}
int BrainfuckCompiler::lessThanOrEqual(int a, int b) {
return logicalOr(
lessThan(a, b),
isEqual(a, b)
);
}
int BrainfuckCompiler::greaterThan(int a, int b) {
return negate(lessThanOrEqual(a, b));
}
int BrainfuckCompiler::greaterThanOrEqual(int a, int b) {
return negate(lessThan(a, b));
}
void BrainfuckCompiler::performIfElse(int expression, function<void ()> ifFn, function<void ()> elseFn) {
int ifValue = duplicateValue(expression);
int elseValue = getPointerForConstValue(1);
movePointer(ifValue);
output << "[";
setValue(ifValue, 0);
setValue(elseValue, 0);
ifFn();
movePointer(ifValue);
output << "]";
movePointer(elseValue);
output << "[";
setValue(elseValue, 0);
elseFn();
movePointer(elseValue);
output << "]";
}
void BrainfuckCompiler::performWhile(function<int ()> expressionFn, function<void ()> loopFn) {
int expression = expressionFn();
movePointer(expression);
output << "[";
movePointer(expression);
loopFn();
int newExpression = expressionFn();
moveValue(newExpression, expression);
movePointer(expression);
output << "]";
}
void BrainfuckCompiler::performFor(
function<void ()> initFn,
function<int ()> expressionFn,
function<void ()> updateFn,
function<void ()> loopFn
) {
initFn();
performWhile(
expressionFn,
[&]() -> void {
loopFn();
updateFn();
}
);
}
void BrainfuckCompiler::printAsChar(int a) {
movePointer(a);
output << ".";
}
void BrainfuckCompiler::printAsNumber(int a) {
int aCopy = duplicateValue(a);
int digit = duplicateValue(a);
int helperPointer = getPointerForConstValue(0);
int zeroChar = getPointerForConstValue('0');
int nine = getPointerForConstValue(9);
int ten = getPointerForConstValue(10);
int newlyBuilt = getPointerForConstValue(0);
performIfElse(
a,
[&]() -> void {
performWhile(
[&]() -> int {
return this->lessThan(newlyBuilt, a);
},
[&]() -> void {
this->setValue(helperPointer, 1);
this->copyValue(aCopy, digit);
performWhile(
[&]() -> int {
return greaterThan(digit, nine);
},
[&]() -> void {
this->moveValue(this->divideValues(digit, ten), digit);
this->moveValue(this->multiplyValues(helperPointer, ten), helperPointer);
}
);
this->moveValue(
this->addValues(
this->multiplyValues(newlyBuilt, ten),
digit
),
newlyBuilt
);
this->printAsChar(this->addValues(digit, zeroChar));
this->moveValue(
this->subtractValues(aCopy, this->multiplyValues(digit, helperPointer)),
aCopy
);
}
);
},
[&]() -> void {
this->printAsChar(zeroChar);
}
);
}
void BrainfuckCompiler::readAsChar(int a) {
movePointer(a);
output << ",";
}
void BrainfuckCompiler::readAsNumber(int a) {
int reader = getPointerForConstValue(0);
int result = getPointerForConstValue(0);
int zero = getPointerForConstValue('0');
int nine = getPointerForConstValue('9');
int ten = getPointerForConstValue(10);
movePointer(reader);
output << ",";
performWhile(
[&]() -> int {
return this->logicalOr(
this->lessThan(reader, zero),
this->greaterThan(reader, nine)
);
},
[&]() -> void {
this->movePointer(reader);
output << ",";
}
);
performWhile(
[&]() -> int {
return this->logicalAnd(
this->greaterThanOrEqual(reader, zero),
this->lessThanOrEqual(reader, nine)
);
},
[&]() -> void {
this->moveValue(
this->addValues(
this->subtractValues(reader, zero),
this->multiplyValues(
result,
ten
)
),
result
);
this->movePointer(reader);
output << ",";
}
);
moveValue(result, a);
}
void BrainfuckCompiler::printChar(unsigned char c) {
int a = getPointerForConstValue(c);
movePointer(a);
output << ".";
}
antlrcpp::Any BrainfuckCompiler::visitAdditiveExpression(SimpleCParser::AdditiveExpressionContext *ctx) {
if (ctx->children.size() == 1) {
SimpleCParser::MultiplicativeExpressionContext *multiplicativeExpression = dynamic_cast<SimpleCParser::MultiplicativeExpressionContext*>(ctx->children[0]);
if (multiplicativeExpression) {
return visitMultiplicativeExpression(multiplicativeExpression);
}
} else if (ctx->children.size() == 3) {
SimpleCParser::AdditiveExpressionContext *additiveExpression = dynamic_cast<SimpleCParser::AdditiveExpressionContext*>(ctx->children[0]);
SimpleCParser::MultiplicativeExpressionContext *multiplicativeExpression = dynamic_cast<SimpleCParser::MultiplicativeExpressionContext*>(ctx->children[2]);
if (additiveExpression && multiplicativeExpression) {
int firstOperandPointer = visitAdditiveExpression(additiveExpression);
int secondOperandPointer = visitMultiplicativeExpression(multiplicativeExpression);
if (ctx->children[1]->getText() == "+") {
return addValues(firstOperandPointer, secondOperandPointer);
} else if (ctx->children[1]->getText() == "-") {
return subtractValues(firstOperandPointer, secondOperandPointer);
}
}
}
throw "Unsupported additive expression";
}
antlrcpp::Any BrainfuckCompiler::visitArgumentExpressionList(SimpleCParser::ArgumentExpressionListContext *ctx) {
vector<antlrcpp::Any> list;
if (ctx->argumentExpressionList()) {
vector<antlrcpp::Any> preList = ctx->argumentExpressionList()->accept(this);
list.insert(list.end(), preList.begin(), preList.end());
}
list.push_back(ctx->assignmentExpression()->accept(this));
return list;
}
antlrcpp::Any BrainfuckCompiler::visitAssignmentExpression(SimpleCParser::AssignmentExpressionContext *ctx) {
// output << endl << "\"" << ctx->getText() << "\"" << endl;
if (ctx->children.size() == 1) {
SimpleCParser::LogicalOrExpressionContext *logicalOrExpression = dynamic_cast<SimpleCParser::LogicalOrExpressionContext*>(ctx->children[0]);
if (logicalOrExpression) {
return visitLogicalOrExpression(logicalOrExpression);
}
} else if (ctx->children.size() == 3) {
if (ctx->assignmentOperator()->getText() == "=") {
return copyValue(
ctx->assignmentExpression()->accept(this),
ctx->unaryExpression()->accept(this)
);
}
}
// return NULL;
throw "Unsupported assignment expression";
}
antlrcpp::Any BrainfuckCompiler::visitDeclarator(SimpleCParser::DeclaratorContext *ctx) {
return visitDirectDeclarator(ctx->directDeclarator());
}
antlrcpp::Any BrainfuckCompiler::visitDirectDeclarator(SimpleCParser::DirectDeclaratorContext *ctx) {
if (ctx->Identifier()) {
return memory.getVariableCell(ctx->Identifier()->getText());
}
SimpleCParser::DirectDeclaratorContext *directDeclarator = dynamic_cast<SimpleCParser::DirectDeclaratorContext*>(ctx->children[0]);
if (directDeclarator) {
if (ctx->children[1]->getText() == "(" && ctx->children[2]->getText() == ")") {
if (directDeclarator->getText() == "main") {
return true;
}
}
}
throw "Unsupported direct declarator";
}
antlrcpp::Any BrainfuckCompiler::visitEqualityExpression(SimpleCParser::EqualityExpressionContext *ctx) {
if (ctx->children.size() == 1) {
SimpleCParser::RelationalExpressionContext *relationalExpression = dynamic_cast<SimpleCParser::RelationalExpressionContext*>(ctx->children[0]);
if (relationalExpression) {
return visitRelationalExpression(relationalExpression);
}
}
if (ctx->children[1]->getText() == "==") {
return isEqual(
ctx->equalityExpression()->accept(this),
ctx->relationalExpression()->accept(this)
);
}
if (ctx->children[1]->getText() == "!=") {
return negate(isEqual(
ctx->equalityExpression()->accept(this),
ctx->relationalExpression()->accept(this)
));
}
throw "Unsupported equality expression";
}
antlrcpp::Any BrainfuckCompiler::visitFunctionDefinition(SimpleCParser::FunctionDefinitionContext *ctx) {
if (ctx->declarator()->directDeclarator()->directDeclarator()->getText() == "main") {
return ctx->compoundStatement()->accept(this);
}
throw "Unsupported function definition";
}
antlrcpp::Any BrainfuckCompiler::visitInitializer(SimpleCParser::InitializerContext *ctx) {
if (ctx->children.size() == 1) {
SimpleCParser::AssignmentExpressionContext *assignmentExpression = dynamic_cast<SimpleCParser::AssignmentExpressionContext*>(ctx->children[0]);
if (assignmentExpression) {
return visitAssignmentExpression(assignmentExpression);
}
}
throw "Unsupported initializer";
}
antlrcpp::Any BrainfuckCompiler::visitInitDeclarator(SimpleCParser::InitDeclaratorContext *ctx) {
if (ctx->children.size() == 3) {
SimpleCParser::DeclaratorContext *declarator = dynamic_cast<SimpleCParser::DeclaratorContext*>(ctx->children[0]);
SimpleCParser::InitializerContext *initializer = dynamic_cast<SimpleCParser::InitializerContext*>(ctx->children[2]);
if (declarator && ctx->children[1]->getText() == "=" && initializer) {
int dest = visitDeclarator(declarator);
int src = visitInitializer(initializer);
copyValue(src, dest);
return src;
}
}
throw "Unsupported init declarator";
}
antlrcpp::Any BrainfuckCompiler::visitIterationStatement(SimpleCParser::IterationStatementContext *ctx) {
if (ctx->While()) {
performWhile(
[&]() -> int {
return ctx->expression()->accept(this);
},
[&]() -> void {
ctx->statement()->accept(this);
}
);
return NULL;
}
if (ctx->For()) {
SimpleCParser::ForConditionContext *forCondition = dynamic_cast<SimpleCParser::ForConditionContext*>(ctx->forCondition());
function<void ()> initFn = [&]() -> void {};
function<int ()> expressionFn = [&]() -> int {
return 0;
};
function<void ()> updateFn = [&]() -> void {};
int firstPos = 0;
int secondPos = 1;
int thirdPos = 2;
if (forCondition->children[firstPos]->getText() != ";") {
initFn = [&]() -> void {
forCondition->children[firstPos]->accept(this);
};
secondPos = firstPos + 2;
thirdPos = firstPos + 3;
}
if (forCondition->children[secondPos]->getText() != ";") {
expressionFn = [&]() -> int {
return forCondition->children[secondPos]->accept(this);
};
thirdPos = secondPos + 2;
}
if (thirdPos < forCondition->children.size()) {
updateFn = [&]() -> void {
forCondition->children[thirdPos]->accept(this);
};
}
performFor(
initFn,
expressionFn,
updateFn,
[&]() -> void {
ctx->statement()->accept(this);
}
);
return NULL;
}
output << endl << ctx->getText() << endl;
throw "Unsupported iteration statement";
}
antlrcpp::Any BrainfuckCompiler::visitLogicalAndExpression(SimpleCParser::LogicalAndExpressionContext *ctx) {
if (ctx->children.size() == 1) {
SimpleCParser::EqualityExpressionContext *equalityExpression = dynamic_cast<SimpleCParser::EqualityExpressionContext*>(ctx->children[0]);
if (equalityExpression) {
return visitEqualityExpression(equalityExpression);
}
}
return logicalAnd(
ctx->logicalAndExpression()->accept(this),
ctx->equalityExpression()->accept(this)
);
throw "Unsupported logical AND expression";
}
antlrcpp::Any BrainfuckCompiler::visitLogicalOrExpression(SimpleCParser::LogicalOrExpressionContext *ctx) {
if (ctx->children.size() == 1) {
SimpleCParser::LogicalAndExpressionContext *logicalAndExpression = dynamic_cast<SimpleCParser::LogicalAndExpressionContext*>(ctx->children[0]);
if (logicalAndExpression) {
return visitLogicalAndExpression(logicalAndExpression);
}
}
return logicalOr(
ctx->logicalOrExpression()->accept(this),
ctx->logicalAndExpression()->accept(this)
);
throw "Unsupported logical OR expression";
}
antlrcpp::Any BrainfuckCompiler::visitMultiplicativeExpression(SimpleCParser::MultiplicativeExpressionContext *ctx) {
if (ctx->children.size() == 1) {
SimpleCParser::SimpleExpressionContext *simpleExpression = dynamic_cast<SimpleCParser::SimpleExpressionContext*>(ctx->children[0]);
if (simpleExpression) {
return visitSimpleExpression(simpleExpression);
}
} else if (ctx->children.size() == 3) {
SimpleCParser::MultiplicativeExpressionContext *multiplicativeExpression = dynamic_cast<SimpleCParser::MultiplicativeExpressionContext*>(ctx->children[0]);
SimpleCParser::SimpleExpressionContext *simpleExpression = dynamic_cast<SimpleCParser::SimpleExpressionContext*>(ctx->children[2]);
if (multiplicativeExpression && simpleExpression) {
int firstOperandPointer = visitMultiplicativeExpression(multiplicativeExpression);
int secondOperandPointer = visitSimpleExpression(simpleExpression);
if (ctx->children[1]->getText() == "*") {
return multiplyValues(firstOperandPointer, secondOperandPointer);
}
if (ctx->children[1]->getText() == "/") {
return divideValues(firstOperandPointer, secondOperandPointer);
}
if (ctx->children[1]->getText() == "%") {
return modValues(firstOperandPointer, secondOperandPointer);
}
}
}
throw "Unsupported multiplicative expression";
}
antlrcpp::Any BrainfuckCompiler::visitPostfixExpression(SimpleCParser::PostfixExpressionContext *ctx) {
if (ctx->primaryExpression()) {
return visitPrimaryExpression(ctx->primaryExpression());
}
if (ctx->children[1]->getText() == "(") {
if (
ctx->postfixExpression()->getText() == "printf" ||
ctx->postfixExpression()->getText() == "scanf"
) {
vector<antlrcpp::Any> allParams;
if (ctx->argumentExpressionList()) {
vector<antlrcpp::Any> params = ctx->argumentExpressionList()->accept(this);
allParams.insert(allParams.end(), params.begin(), params.end());
}
if (allParams.size() > 0) {
string formatString = allParams[0];
int nextVariable = 1;
int pointer;
for (int i = 1; i < formatString.length() - 1; ++i) {
if (ctx->postfixExpression()->getText() == "printf") {
switch (formatString[i]) {
case '\\':
switch (formatString[i+1]) {
case 'n':
printChar('\n');
break;
case 't':
printChar('\t');
break;
default:
throw "Incorrect backslash in printf";
}
++i;
break;
case '%':
pointer = allParams[nextVariable++];
switch (formatString[i+1]) {
case 'c':
printAsChar(pointer);
break;
case 'd':
printAsNumber(pointer);
break;
default:
throw "Unexpected printf format";
}
++i;
break;
default:
printChar(formatString[i]);
}
} else {
switch (formatString[i]) {
case '%':
pointer = allParams[nextVariable++];
switch (formatString[i+1]) {
case 'c':
readAsChar(pointer);
break;
case 'd':
readAsNumber(pointer);
break;
default:
throw "Unexpected scanf format";
}
++i;
break;
case ' ':
break;
default:
throw "Unexpected scanf format";
}
}
}
}
return NULL;
}
}
throw "Unsupported postfix expression";
}
antlrcpp::Any BrainfuckCompiler::visitPrimaryExpression(SimpleCParser::PrimaryExpressionContext *ctx) {
if (ctx->Constant()) {
// If it is a constant, store it in a temporary memory cell and return its address
string value = ctx->Constant()->getText();
if (value[0] == '\'') {
return getPointerForConstValue(value[1]);
} else {
return getPointerForConstValue(atoi(value.c_str()));
}
} else if (ctx->Identifier()) {
// If it is an identifier, return its mmoery address
string name = ctx->Identifier()->getText();
return memory.getVariableCell(name);
} else if (ctx->StringLiteral()[0]) {
return ctx->StringLiteral()[0]->getText();
}
throw "Unsupported primary expression";
}
antlrcpp::Any BrainfuckCompiler::visitRelationalExpression(SimpleCParser::RelationalExpressionContext *ctx) {
if (ctx->children.size() == 1) {
SimpleCParser::AdditiveExpressionContext *additiveExpression = dynamic_cast<SimpleCParser::AdditiveExpressionContext*>(ctx->children[0]);
if (additiveExpression) {
return visitAdditiveExpression(additiveExpression);
}
}
if (ctx->children[1]->getText() == "<") {
return lessThan(
ctx->relationalExpression()->accept(this),
ctx->additiveExpression()->accept(this)
);
}
if (ctx->children[1]->getText() == "<=") {
return lessThanOrEqual(
ctx->relationalExpression()->accept(this),
ctx->additiveExpression()->accept(this)
);
}
if (ctx->children[1]->getText() == ">") {
return greaterThan(
ctx->relationalExpression()->accept(this),
ctx->additiveExpression()->accept(this)
);
}
if (ctx->children[1]->getText() == ">=") {
return greaterThanOrEqual(
ctx->relationalExpression()->accept(this),
ctx->additiveExpression()->accept(this)
);
}
throw "Unsupported relational expression";
}
antlrcpp::Any BrainfuckCompiler::visitSimpleExpression(SimpleCParser::SimpleExpressionContext *ctx) {
if (ctx->unaryExpression()) {
return visitUnaryExpression(ctx->unaryExpression());
} else if (ctx->DigitSequence()) {
return getPointerForConstValue(atoi(ctx->DigitSequence()->getText().c_str()));
}
throw "Unsupported simple expression";
}
antlrcpp::Any BrainfuckCompiler::visitSelectionStatement(SimpleCParser::SelectionStatementContext *ctx) {
if (ctx->children[0]->getText() == "if") {
SimpleCParser::StatementContext *ifStatement = dynamic_cast<SimpleCParser::StatementContext*>(ctx->children[4]);
SimpleCParser::StatementContext *elseStatement = NULL;
if (ctx->children.size() == 7) {
elseStatement = dynamic_cast<SimpleCParser::StatementContext*>(ctx->children[6]);
}
performIfElse(
ctx->expression()->accept(this),
[&]() -> void {
ifStatement->accept(this);
},
[&]() -> void {
if (elseStatement) {
elseStatement->accept(this);
}
}
);
return NULL;
}
throw "Unsupported selection statement";
}
antlrcpp::Any BrainfuckCompiler::visitUnaryExpression(SimpleCParser::UnaryExpressionContext *ctx) {
if (ctx->postfixExpression()) {
return visitPostfixExpression(ctx->postfixExpression());
}
if (ctx->children[0]->getText() == "!") {
return negate(ctx->unaryExpression()->accept(this));
}
if (ctx->children[0]->getText() == "&") {
return ctx->unaryExpression()->accept(this);
}
throw "Unsupported unary expression";
} | 29.533333 | 159 | 0.625866 | nbozidarevic |
6c9fc41e386bca87f22fcff5268fa39d7a5403ec | 67,288 | cpp | C++ | RenderCore/LightingEngine/SunSourceConfiguration.cpp | djewsbury/XLE | 7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e | [
"MIT"
] | 3 | 2015-12-04T09:16:53.000Z | 2021-05-28T23:22:49.000Z | RenderCore/LightingEngine/SunSourceConfiguration.cpp | djewsbury/XLE | 7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e | [
"MIT"
] | null | null | null | RenderCore/LightingEngine/SunSourceConfiguration.cpp | djewsbury/XLE | 7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e | [
"MIT"
] | 2 | 2015-03-03T05:32:39.000Z | 2015-12-04T09:16:54.000Z | // Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "SunSourceConfiguration.h"
#include "ShadowPreparer.h"
#include "ShadowUniforms.h" // for the attach driver infrastructure
#include "../Techniques/TechniqueUtils.h"
#include "../Techniques/ParsingContext.h"
#include "../Format.h"
#include "../StateDesc.h"
#include "../../ConsoleRig/Console.h"
#include "../../Math/Vector.h"
#include "../../Math/Matrix.h"
#include "../../Math/Transformations.h"
#include "../../Math/ProjectionMath.h"
#include "../../Math/MathSerialization.h"
#include "../../OSServices/Log.h"
#include "../../Utility/BitUtils.h"
#include <sstream>
namespace RenderCore { namespace LightingEngine
{
static Float4x4 MakeWorldToLight(
const Float3& negativeLightDirection,
const Float3& position)
{
return InvertOrthonormalTransform(
MakeCameraToWorld(-negativeLightDirection, Float3(1.f, 0.f, 0.f), position));
}
static const unsigned s_staticMaxSubProjections = 6;
struct OrthoProjections
{
Float4x4 _worldToView;
unsigned _normalProjCount = 0;
IOrthoShadowProjections::OrthoSubProjection _orthSubProjections[s_staticMaxSubProjections];
Float4x4 _limitedMainCameraToProjection;
};
struct ArbitraryProjections
{
unsigned _normalProjCount = 0;
Float4x4 _worldToCamera[s_staticMaxSubProjections];
Float4x4 _cameraToProjection[s_staticMaxSubProjections];
};
static ArbitraryProjections BuildBasicShadowProjections(
const Float3& negativeLightDirection,
const RenderCore::Techniques::ProjectionDesc& mainSceneProjectionDesc,
const SunSourceFrustumSettings& settings)
{
using namespace RenderCore::LightingEngine;
ArbitraryProjections result;
const float shadowNearPlane = 1.f;
const float shadowFarPlane = settings._maxDistanceFromCamera;
static float shadowWidthScale = 3.f;
static float projectionSizePower = 3.75f;
float shadowProjectionDist = shadowFarPlane - shadowNearPlane;
auto cameraPos = ExtractTranslation(mainSceneProjectionDesc._cameraToWorld);
auto cameraForward = ExtractForward_Cam(mainSceneProjectionDesc._cameraToWorld);
// Calculate a simple set of shadow frustums.
// This method is non-ideal, but it's just a place holder for now
result._normalProjCount = 5;
for (unsigned c=0; c<result._normalProjCount; ++c) {
const float projectionWidth = shadowWidthScale * std::pow(projectionSizePower, float(c));
Float3 shiftDirection = cameraForward - negativeLightDirection * Dot(cameraForward, negativeLightDirection);
Float3 focusPoint = cameraPos + (projectionWidth * 0.45f) * shiftDirection;
auto lightViewMatrix = MakeWorldToLight(
negativeLightDirection, focusPoint + (.5f * shadowProjectionDist) * negativeLightDirection);
result._cameraToProjection[c] = OrthogonalProjection(
-.5f * projectionWidth, -.5f * projectionWidth,
.5f * projectionWidth, .5f * projectionWidth,
shadowNearPlane, shadowFarPlane,
GeometricCoordinateSpace::RightHanded,
RenderCore::Techniques::GetDefaultClipSpaceType());
result._worldToCamera[c] = lightViewMatrix;
}
return result;
}
static void CalculateCameraFrustumCornersDirection(
Float3 result[4],
const RenderCore::Techniques::ProjectionDesc& projDesc,
ClipSpaceType clipSpaceType)
{
// For the given camera, calculate 4 vectors that represent the
// the direction from the camera position to the frustum corners
// (there are 8 frustum corners, but the directions to the far plane corners
// are the same as the near plane corners)
Float4x4 projection = projDesc._cameraToProjection;
Float4x4 noTransCameraToWorld = projDesc._cameraToWorld;
SetTranslation(noTransCameraToWorld, Float3(0.f, 0.f, 0.f));
auto trans = Combine(InvertOrthonormalTransform(noTransCameraToWorld), projection);
Float3 corners[8];
CalculateAbsFrustumCorners(corners, trans, clipSpaceType);
for (unsigned c=0; c<4; ++c) {
result[c] = Normalize(corners[4+c]); // use the more distance corners, on the far clip plane
}
}
static std::pair<Float4x4, Float4> BuildCameraAlignedOrthogonalShadowProjection(
const Float3& negativeLightDirection,
const RenderCore::Techniques::ProjectionDesc& mainSceneProjectionDesc,
float depth, float maxDistanceFromCamera)
{
// Build a special "camera aligned" shadow projection.
// This can be used to for especially high resolution shadows very close to the
// near clip plane.
// First, we build a rough projection-to-world based on the camera right direction...
auto projRight = ExtractRight_Cam(mainSceneProjectionDesc._cameraToWorld);
auto projForward = -negativeLightDirection;
auto projUp = Cross(projRight, projForward);
auto adjRight = Cross(projForward, projUp);
auto camPos = ExtractTranslation(mainSceneProjectionDesc._cameraToWorld);
auto projToWorld = MakeCameraToWorld(projForward, Normalize(projUp), Normalize(adjRight), camPos);
auto worldToLightProj = InvertOrthonormalTransform(projToWorld);
// Now we just have to fit the finsl projection around the frustum corners
auto clipSpaceType = RenderCore::Techniques::GetDefaultClipSpaceType();
auto reducedDepthProjection = PerspectiveProjection(
mainSceneProjectionDesc._verticalFov, mainSceneProjectionDesc._aspectRatio,
mainSceneProjectionDesc._nearClip, depth,
GeometricCoordinateSpace::RightHanded, clipSpaceType);
auto worldToReducedDepthProj = Combine(
InvertOrthonormalTransform(mainSceneProjectionDesc._cameraToWorld), reducedDepthProjection);
Float3 frustumCorners[8];
CalculateAbsFrustumCorners(frustumCorners, worldToReducedDepthProj, clipSpaceType);
Float3 shadowViewSpace[8];
Float3 shadowViewMins( std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
Float3 shadowViewMaxs(-std::numeric_limits<float>::max(), -std::numeric_limits<float>::max(), -std::numeric_limits<float>::max());
for (unsigned c = 0; c < 8; c++) {
shadowViewSpace[c] = TransformPoint(worldToLightProj, frustumCorners[c]);
// In our right handed coordinate space, the z coordinate in view space should
// be negative. But we always specify near & far in positive values. So
// we have to swap the sign of z here
shadowViewSpace[c][2] = -shadowViewSpace[c][2];
shadowViewMins[0] = std::min(shadowViewMins[0], shadowViewSpace[c][0]);
shadowViewMins[1] = std::min(shadowViewMins[1], shadowViewSpace[c][1]);
shadowViewMins[2] = std::min(shadowViewMins[2], shadowViewSpace[c][2]);
shadowViewMaxs[0] = std::max(shadowViewMaxs[0], shadowViewSpace[c][0]);
shadowViewMaxs[1] = std::max(shadowViewMaxs[1], shadowViewSpace[c][1]);
shadowViewMaxs[2] = std::max(shadowViewMaxs[2], shadowViewSpace[c][2]);
}
const float shadowNearPlane = -maxDistanceFromCamera;
const float shadowFarPlane = maxDistanceFromCamera;
Float4x4 projMatrix = OrthogonalProjection(
shadowViewMins[0], shadowViewMaxs[1], shadowViewMaxs[0], shadowViewMins[1],
shadowNearPlane, shadowFarPlane,
GeometricCoordinateSpace::RightHanded, clipSpaceType);
auto result = Combine(worldToLightProj, projMatrix);
return std::make_pair(result, ExtractMinimalProjection(projMatrix));
}
static OrthoProjections BuildSimpleOrthogonalShadowProjections(
const Float3& negativeLightDirection,
const RenderCore::Techniques::ProjectionDesc& mainSceneProjectionDesc,
const SunSourceFrustumSettings& settings)
{
// We're going to build some basic adaptive shadow frustums. These frustums
// all fit within the same "definition" orthogonal space. This means that
// cascades can't be rotated or skewed relative to each other. Usually this
// should be fine, (and perhaps might reduce some flickering around the
// cascade edges) but it means that the cascades might not be as tightly
// bound as they might be.
using namespace RenderCore::LightingEngine;
using namespace RenderCore;
OrthoProjections result;
result._normalProjCount = settings._maxFrustumCount;
const float shadowNearPlane = -settings._maxDistanceFromCamera;
const float shadowFarPlane = settings._maxDistanceFromCamera;
auto clipSpaceType = Techniques::GetDefaultClipSpaceType();
float t = 0;
for (unsigned c=0; c<result._normalProjCount; ++c) { t += std::pow(settings._frustumSizeFactor, float(c)); }
Float3 cameraPos = ExtractTranslation(mainSceneProjectionDesc._cameraToWorld);
Float3 focusPoint = cameraPos + settings._focusDistance * ExtractForward_Cam(mainSceneProjectionDesc._cameraToWorld);
auto lightToWorld = MakeCameraToWorld(-negativeLightDirection, ExtractRight_Cam(mainSceneProjectionDesc._cameraToWorld), focusPoint);
Float4x4 worldToView = InvertOrthonormalTransform(lightToWorld);
assert(std::isfinite(worldToView(0,3)) && !std::isnan(worldToView(0,3)));
result._worldToView = worldToView;
// Calculate 4 vectors for the directions of the frustum corners,
// relative to the camera position.
Float3 frustumCornerDir[4];
CalculateCameraFrustumCornersDirection(frustumCornerDir, mainSceneProjectionDesc, clipSpaceType);
// Float3 allCascadesMins( std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
// Float3 allCascadesMaxs(-std::numeric_limits<float>::max(), -std::numeric_limits<float>::max(), -std::numeric_limits<float>::max());
float distanceFromCamera = 0.f;
for (unsigned f=0; f<result._normalProjCount; ++f) {
float camNearPlane = distanceFromCamera;
distanceFromCamera += std::pow(settings._frustumSizeFactor, float(f)) * settings._maxDistanceFromCamera / t;
float camFarPlane = distanceFromCamera;
// Find the frustum corners for this part of the camera frustum,
// and then build a shadow frustum that will contain those corners.
// Potentially not all of the camera frustum is full of geometry --
// if we knew which parts were full, and which were empty, we could
// optimise the shadow frustum further.
Float3 absFrustumCorners[8];
for (unsigned c = 0; c < 4; ++c) {
absFrustumCorners[c] = cameraPos + camNearPlane * frustumCornerDir[c];
absFrustumCorners[4 + c] = cameraPos + camFarPlane * frustumCornerDir[c];
}
// Let's assume that we're not going to rotate the shadow frustum
// during this fitting. Then, this is easy... The shadow projection
// is orthogonal, so we just need to find the AABB in shadow-view space
// for these corners, and the projection parameters will match those very
// closely.
//
// Note that we could potentially get a better result if we rotate the
// shadow frustum projection to better fit around the projected camera.
// It might make shadow texels creep and flicker as the projection changes,
// but perhaps a better implementation of this function could try that out.
Float3 shadowViewSpace[8];
Float3 shadowViewMins( std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
Float3 shadowViewMaxs(-std::numeric_limits<float>::max(), -std::numeric_limits<float>::max(), -std::numeric_limits<float>::max());
for (unsigned c = 0; c < 8; c++) {
shadowViewSpace[c] = TransformPoint(worldToView, absFrustumCorners[c]);
// In our right handed coordinate space, the z coordinate in view space should
// be negative. But we always specify near & far in positive values. So
// we have to swap the sign of z here
shadowViewSpace[c][2] = -shadowViewSpace[c][2];
shadowViewMins[0] = std::min(shadowViewMins[0], shadowViewSpace[c][0]);
shadowViewMins[1] = std::min(shadowViewMins[1], shadowViewSpace[c][1]);
shadowViewMins[2] = std::min(shadowViewMins[2], shadowViewSpace[c][2]);
shadowViewMaxs[0] = std::max(shadowViewMaxs[0], shadowViewSpace[c][0]);
shadowViewMaxs[1] = std::max(shadowViewMaxs[1], shadowViewSpace[c][1]);
shadowViewMaxs[2] = std::max(shadowViewMaxs[2], shadowViewSpace[c][2]);
}
// We have to pull the min depth distance back towards the light
// This is so we can capture geometry that is between the light
// and the frustum
shadowViewMins[2] = shadowNearPlane;
// shadowViewMaxs[2] = shadowFarPlane;
result._orthSubProjections[f]._leftTopFront = shadowViewMins;
result._orthSubProjections[f]._rightBottomBack = shadowViewMaxs;
// allCascadesMins[0] = std::min(allCascadesMins[0], shadowViewMins[0]);
// allCascadesMins[1] = std::min(allCascadesMins[1], shadowViewMins[1]);
// allCascadesMins[2] = std::min(allCascadesMins[2], shadowViewMins[2]);
// allCascadesMaxs[0] = std::max(allCascadesMaxs[0], shadowViewMaxs[0]);
// allCascadesMaxs[1] = std::max(allCascadesMaxs[1], shadowViewMaxs[1]);
// allCascadesMaxs[2] = std::max(allCascadesMaxs[2], shadowViewMaxs[2]);
}
// When building the world to clip matrix, we want some to use some projection
// that projection that will contain all of the shadow frustums.
// We can use allCascadesMins and allCascadesMaxs to find the area of the
// orthogonal space that is actually used. We just have to incorporate these
// mins and maxs into the projection matrix
/*
Float4x4 clippingProjMatrix = OrthogonalProjection(
allCascadesMins[0], allCascadesMaxs[1], allCascadesMaxs[0], allCascadesMins[1],
shadowNearPlane, shadowFarPlane,
GeometricCoordinateSpace::RightHanded, clipSpaceType);
Float4x4 worldToClip = Combine(definitionViewMatrix, clippingProjMatrix);
std::tie(result._specialNearProjection, result._specialNearMinimalProjection) =
BuildCameraAlignedOrthogonalShadowProjection(lightDesc, mainSceneProjectionDesc, 2.5, 30.f);
result._useNearProj = true;
*/
return result;
}
// We can use either Z or W for tests related to depth in the view frustu,
// Z can work for either projection or orthogonal, but W is a lot simplier for perspective
// projections. Using W also isolates us from the inpact of the ReverseZ modes
#define USE_W_FOR_DEPTH_RANGE_COVERED
static bool ClipSpaceFurther(const Float4& lhs, float rhs, ClipSpaceType clipSpaceType)
{
#if !defined(USE_W_FOR_DEPTH_RANGE_COVERED)
// In non-reverseZ modes, lhs is further than rhs if it larger
// In reverseZ mods, lhs is further than rhs if it is smaller
return (clipSpaceType == ClipSpaceType::PositiveRightHanded_ReverseZ || clipSpaceType == ClipSpaceType::Positive_ReverseZ) ^ (lhs[2] > rhs);
#else
return lhs[3] > rhs;
#endif
}
static std::pair<std::vector<Float3>, float> NearestPointNotInsideOrthoProjection(
const Float4x4& cameraWorldToClip,
const Float3* absFrustumCorners,
const Float4x4& orthoViewToWorld,
const IOrthoShadowProjections::OrthoSubProjection& projection,
float depthRangeCovered,
ClipSpaceType clipSpaceType)
{
// We need to test the edges of ortho box against the camera frustum
// and the edges of the ortho box against the frustum
//
// Note that the points in "absFrustumCorners" are actually arranged so first 4 and last 4
// make Z-patterns
const unsigned edges_zpattern[] = {
0, 1,
1, 3,
3, 2,
2, 0,
4, 6,
6, 7,
7, 5,
5, 4,
0, 4,
1, 5,
3, 7,
2, 6
};
auto orthoToClip = Combine(orthoViewToWorld, cameraWorldToClip);
auto orthoWorldToView = InvertOrthonormalTransform(orthoViewToWorld);
std::vector<Float4> intersectionPts;
{
const Float4 clipSpaceCorners[] = {
orthoToClip * Expand(Float3{projection._leftTopFront[0], projection._leftTopFront[1], projection._leftTopFront[2]}, 1.0f),
orthoToClip * Expand(Float3{projection._leftTopFront[0], projection._rightBottomBack[1], projection._leftTopFront[2]}, 1.0f),
orthoToClip * Expand(Float3{projection._rightBottomBack[0], projection._leftTopFront[1], projection._leftTopFront[2]}, 1.0f),
orthoToClip * Expand(Float3{projection._rightBottomBack[0], projection._rightBottomBack[1], projection._leftTopFront[2]}, 1.0f),
orthoToClip * Expand(Float3{projection._leftTopFront[0], projection._leftTopFront[1], projection._rightBottomBack[2]}, 1.0f),
orthoToClip * Expand(Float3{projection._leftTopFront[0], projection._rightBottomBack[1], projection._rightBottomBack[2]}, 1.0f),
orthoToClip * Expand(Float3{projection._rightBottomBack[0], projection._leftTopFront[1], projection._rightBottomBack[2]}, 1.0f),
orthoToClip * Expand(Float3{projection._rightBottomBack[0], projection._rightBottomBack[1], projection._rightBottomBack[2]}, 1.0f)
};
for (unsigned e=0; e<dimof(edges_zpattern); e+=2) {
auto start = clipSpaceCorners[edges_zpattern[e+0]];
auto end = clipSpaceCorners[edges_zpattern[e+1]];
for (unsigned ele=0; ele<2; ++ele) {
if ((start[ele] < -start[3]) != (end[ele] < -end[3])) {
// clip to the [ele] == -w plane
// start[ele] + alpha * (end[ele] - start[ele]) = -start[3] + alpha * (start[3] - end[3])
// alpha * (end[ele] - start[ele]) - alpha * (start[3] - end[3]) = -start[3] - start[ele]
// alpha * ((end[ele] - start[ele]) - (start[3] - end[3])) = -start[3] - start[ele]
// alpha = (-start[3] - start[ele]) / ((end[ele] - start[ele]) - (start[3] - end[3]))
// alpha = (start[3] + start[ele]) / (start[ele] + start[3] - end[ele] - end[3])
auto alpha = (start[3] + start[ele]) / (start[ele] + start[3] - end[ele] - end[3]);
assert(alpha >= 0.f && alpha <= 1.0f);
Float4 intersection = start + (end-start)*alpha;
assert(Equivalent(intersection[ele], -intersection[3], 1e-1f));
if (std::abs(intersection[ele^1]) <= intersection[3] && std::abs(intersection[2]) <= intersection[3] && intersection[2] >= 0) {
if (ClipSpaceFurther(intersection, depthRangeCovered, clipSpaceType)) {
intersectionPts.push_back(intersection);
}
}
}
if ((start[ele] > start[3]) != (end[ele] > end[3])) {
// clip to the [ele] == w plane
// start[ele] + alpha * (end[ele] - start[ele]) = start[3] + alpha * (end[3] - start[3])
// alpha * (end[ele] - start[ele]) - alpha * (end[3] - start[3]) = start[3] - start[ele]
// alpha = (start[3] - start[ele]) / (end[ele] - end[3] - start[ele] + start[3])
auto alpha = (start[3] - start[ele]) / (end[ele] - end[3] - start[ele] + start[3]);
assert(alpha >= 0.f && alpha <= 1.0f);
Float4 intersection = start + (end-start)*alpha;
assert(Equivalent(intersection[ele], intersection[3], 1e-1f));
if (std::abs(intersection[ele^1]) <= intersection[3] && std::abs(intersection[2]) <= intersection[3] && intersection[2] >= 0) {
if (ClipSpaceFurther(intersection, depthRangeCovered, clipSpaceType)) {
intersectionPts.push_back(intersection);
}
}
}
}
}
}
{
assert(projection._leftTopFront[0] < projection._rightBottomBack[0]);
assert(projection._leftTopFront[1] < projection._rightBottomBack[1]);
assert(projection._leftTopFront[2] < projection._rightBottomBack[2]);
for (unsigned e=0; e<dimof(edges_zpattern); e+=2) {
auto start = TransformPoint(orthoWorldToView, absFrustumCorners[edges_zpattern[e+0]]);
auto end = TransformPoint(orthoWorldToView, absFrustumCorners[edges_zpattern[e+1]]);
for (unsigned ele=0; ele<3; ++ele) {
if ((start[ele] < projection._leftTopFront[ele]) != (end[ele] < projection._leftTopFront[ele])) {
float alpha = (projection._leftTopFront[ele] - start[ele]) / (end[ele] - start[ele]);
Float3 intersection = start + (end-start)*alpha;
if (intersection[(ele+1)%3] >= projection._leftTopFront[(ele+1)%3] && intersection[(ele+1)%3] <= projection._rightBottomBack[(ele+1)%3]
&& intersection[(ele+2)%3] >= projection._leftTopFront[(ele+2)%3] && intersection[(ele+2)%3] <= projection._rightBottomBack[(ele+2)%3]) {
Float4 clipSpace = orthoToClip * Expand(intersection, 1.0f);
if (ClipSpaceFurther(clipSpace, depthRangeCovered, clipSpaceType)) {
intersectionPts.push_back(clipSpace);
}
}
}
if ((start[ele] > projection._rightBottomBack[ele]) != (end[ele] > projection._rightBottomBack[ele])) {
float alpha = (projection._rightBottomBack[ele] - start[ele]) / (end[ele] - start[ele]);
Float3 intersection = start + (end-start)*alpha;
if (intersection[(ele+1)%3] >= projection._leftTopFront[(ele+1)%3] && intersection[(ele+1)%3] <= projection._rightBottomBack[(ele+1)%3]
&& intersection[(ele+2)%3] >= projection._leftTopFront[(ele+2)%3] && intersection[(ele+2)%3] <= projection._rightBottomBack[(ele+2)%3]) {
Float4 clipSpace = orthoToClip * Expand(intersection, 1.0f);
if (ClipSpaceFurther(clipSpace, depthRangeCovered, clipSpaceType)) {
intersectionPts.push_back(clipSpace);
}
}
}
}
}
}
if (!intersectionPts.empty()) {
auto clipToWorld = Inverse(cameraWorldToClip);
std::vector<Float3> result;
// sort closest to camera first
#if !defined(USE_W_FOR_DEPTH_RANGE_COVERED)
if (clipSpaceType == ClipSpaceType::PositiveRightHanded_ReverseZ || clipSpaceType == ClipSpaceType::Positive_ReverseZ) {
std::sort(intersectionPts.begin(), intersectionPts.end(), [](const auto& lhs, const auto& rhs) { return lhs[2] > rhs[2]; });
} else
std::sort(intersectionPts.begin(), intersectionPts.end(), [](const auto& lhs, const auto& rhs) { return lhs[2] < rhs[2]; });
const unsigned depthRangeConveredEle = 2;
#else
std::sort(intersectionPts.begin(), intersectionPts.end(), [](const auto& lhs, const auto& rhs) { return lhs[3] < rhs[3]; });
const unsigned depthRangeConveredEle = 3;
#endif
result.reserve(intersectionPts.size());
for (auto& pt:intersectionPts)
result.push_back(Truncate(clipToWorld * pt));
return {std::move(result), intersectionPts[0][depthRangeConveredEle]};
}
return {{}, depthRangeCovered};
}
static Float2 MinAndMaxOrthoSpaceZ(
const Float4x4& cameraWorldToClip,
const Float3* absFrustumCorners,
const Float4x4& orthoViewToWorld,
const Float2& leftTop2D, const Float2& rightBottom2D,
const Float4& cameraMiniProj,
float depthRangeCovered,
ClipSpaceType clipSpaceType)
{
const unsigned edges_zpattern[] = {
0, 1,
1, 3,
3, 2,
2, 0,
4, 6,
6, 7,
7, 5,
5, 4,
0, 4,
1, 5,
3, 7,
2, 6
};
auto orthoToClip = Combine(orthoViewToWorld, cameraWorldToClip);
auto orthoWorldToView = InvertOrthonormalTransform(orthoViewToWorld);
auto clipToWorld = Inverse(cameraWorldToClip);
auto clipToOrthoView = Combine(clipToWorld, orthoWorldToView);
Float2 orthZMinAndMax { FLT_MAX, -FLT_MAX };
for (unsigned c=0; c<8; ++c) {
float z = (orthoWorldToView * Float4{absFrustumCorners[c], 1.0f})[2];
orthZMinAndMax[0] = std::min(orthZMinAndMax[0], z);
orthZMinAndMax[1] = std::max(orthZMinAndMax[1], z);
}
Float2 result { FLT_MAX, -FLT_MAX };
Float3 leftTopFront{leftTop2D[0], leftTop2D[1], orthZMinAndMax[0] - 0.1f};
Float3 rightBottomBack{rightBottom2D[0], rightBottom2D[1], orthZMinAndMax[1] + 0.1f};
{
const Float4 clipSpaceCorners[] = {
orthoToClip * Expand(Float3{leftTopFront[0], leftTopFront[1], leftTopFront[2]}, 1.0f),
orthoToClip * Expand(Float3{leftTopFront[0], rightBottomBack[1], leftTopFront[2]}, 1.0f),
orthoToClip * Expand(Float3{rightBottomBack[0], leftTopFront[1], leftTopFront[2]}, 1.0f),
orthoToClip * Expand(Float3{rightBottomBack[0], rightBottomBack[1], leftTopFront[2]}, 1.0f),
orthoToClip * Expand(Float3{leftTopFront[0], leftTopFront[1], rightBottomBack[2]}, 1.0f),
orthoToClip * Expand(Float3{leftTopFront[0], rightBottomBack[1], rightBottomBack[2]}, 1.0f),
orthoToClip * Expand(Float3{rightBottomBack[0], leftTopFront[1], rightBottomBack[2]}, 1.0f),
orthoToClip * Expand(Float3{rightBottomBack[0], rightBottomBack[1], rightBottomBack[2]}, 1.0f)
};
for (unsigned e=0; e<dimof(edges_zpattern); e+=2) {
auto start = clipSpaceCorners[edges_zpattern[e+0]];
auto end = clipSpaceCorners[edges_zpattern[e+1]];
for (unsigned ele=0; ele<3; ++ele) {
if ((start[ele] < -start[3]) != (end[ele] < -end[3])) {
auto alpha = (start[3] + start[ele]) / (start[ele] + start[3] - end[ele] - end[3]);
assert(alpha >= 0.f && alpha <= 1.0f);
Float4 intersection = start + (end-start)*alpha;
assert(Equivalent(intersection[ele], -intersection[3], 1e-1f));
if (std::abs(intersection[(ele+1)%3]) <= intersection[3] && std::abs(intersection[(ele+2)%3]) <= intersection[3]) {
auto orthoView = clipToOrthoView * intersection;
float z = orthoView[2];
result[0] = std::min(result[0], z);
result[1] = std::max(result[1], z);
}
}
if ((start[ele] > start[3]) != (end[ele] > end[3])) {
auto alpha = (start[3] - start[ele]) / (end[ele] - end[3] - start[ele] + start[3]);
assert(alpha >= 0.f && alpha <= 1.0f);
Float4 intersection = start + (end-start)*alpha;
assert(Equivalent(intersection[ele], intersection[3], 1e-1f));
if (std::abs(intersection[(ele+1)%3]) <= intersection[3] && std::abs(intersection[(ele+2)%3]) <= intersection[3]) {
auto orthoView = clipToOrthoView * intersection;
float z = orthoView[2];
result[0] = std::min(result[0], z);
result[1] = std::max(result[1], z);
}
}
}
// also check against the Z=0 plane (we've already done Z=W above)
if (((start[2] < 0) != (end[2] < 0))) {
auto alpha = (start[2]) / (start[2] - end[2]);
assert(alpha >= 0.f && alpha <= 1.0f);
Float4 intersection = start + (end-start)*alpha;
assert(Equivalent(intersection[2], 0.f, 1e-1f));
if (std::abs(intersection[0]) <= intersection[3] && std::abs(intersection[1]) <= intersection[3]) {
auto orthoView = clipToOrthoView * intersection;
float z = orthoView[2];
result[0] = std::min(result[0], z);
result[1] = std::max(result[1], z);
}
} else {
assert((start[2]<0) == (end[2]<0));
}
}
}
{
assert(leftTopFront[0] < rightBottomBack[0]);
assert(leftTopFront[1] < rightBottomBack[1]);
float f, n;
std::tie(n,f) = CalculateNearAndFarPlane(cameraMiniProj, clipSpaceType);
#if !defined(USE_W_FOR_DEPTH_RANGE_COVERED)
float depthAlphaValue = (depthRangeCovered - cameraMiniProj[3]) / cameraMiniProj[2];
depthAlphaValue = (-depthAlphaValue - n) / f;
#else
float depthAlphaValue = (depthRangeCovered - n) / f;
#endif
for (unsigned e=0; e<dimof(edges_zpattern); e+=2) {
unsigned startPt = edges_zpattern[e+0], endPt = edges_zpattern[e+1];
Float3 start, end;
if (startPt < 4) start = TransformPoint(orthoWorldToView, LinearInterpolate(absFrustumCorners[startPt], absFrustumCorners[startPt+4], depthAlphaValue));
else start = TransformPoint(orthoWorldToView, absFrustumCorners[startPt]);
if (endPt < 4) end = TransformPoint(orthoWorldToView, LinearInterpolate(absFrustumCorners[endPt], absFrustumCorners[endPt+4], depthAlphaValue));
else end = TransformPoint(orthoWorldToView, absFrustumCorners[endPt]);
// points inside of the projection area count
if (start[0] >= leftTopFront[0] && start[1] >= leftTopFront[1] && start[0] <= rightBottomBack[0] && start[1] <= rightBottomBack[1]) {
result[0] = std::min(result[0], start[2]);
result[1] = std::max(result[1], start[2]);
}
if (end[0] >= leftTopFront[0] && end[1] >= leftTopFront[1] && end[0] <= rightBottomBack[0] && end[1] <= rightBottomBack[1]) {
result[0] = std::min(result[0], end[2]);
result[1] = std::max(result[1], end[2]);
}
for (unsigned ele=0; ele<3; ++ele) {
if ((start[ele] < leftTopFront[ele]) != (end[ele] < leftTopFront[ele])) {
float alpha = (leftTopFront[ele] - start[ele]) / (end[ele] - start[ele]);
Float3 intersection = start + (end-start)*alpha;
if ( intersection[(ele+1)%3] >= leftTopFront[(ele+1)%3] && intersection[(ele+1)%3] <= rightBottomBack[(ele+1)%3]
&& intersection[(ele+2)%3] >= leftTopFront[(ele+2)%3] && intersection[(ele+2)%3] <= rightBottomBack[(ele+2)%3]) {
float z = intersection[2];
result[0] = std::min(result[0], z);
result[1] = std::max(result[1], z);
}
}
if ((start[ele] > rightBottomBack[ele]) != (end[ele] > rightBottomBack[ele])) {
float alpha = (rightBottomBack[ele] - start[ele]) / (end[ele] - start[ele]);
Float3 intersection = start + (end-start)*alpha;
if ( intersection[(ele+1)%3] >= leftTopFront[(ele+1)%3] && intersection[(ele+1)%3] <= rightBottomBack[(ele+1)%3]
&& intersection[(ele+2)%3] >= leftTopFront[(ele+2)%3] && intersection[(ele+2)%3] <= rightBottomBack[(ele+2)%3]) {
float z = intersection[2];
result[0] = std::min(result[0], z);
result[1] = std::max(result[1], z);
}
}
}
}
}
if (result[0] < result[1]) {
const float precisionGraceDistance = 1e-3f;
result[0] -= std::abs(result[0]) * precisionGraceDistance;
result[1] += std::abs(result[1]) * precisionGraceDistance;
}
return result;
}
static Float4x4 MakeOrientedShadowViewToWorld(const Float3& lightDirection, const Float3& positiveX, const Float3& focusPoint)
{
Float3 up = Normalize(Cross(positiveX, lightDirection));
Float3 adjustedRight = Normalize(cross(lightDirection, up));
return MakeCameraToWorld(lightDirection, up, adjustedRight, focusPoint);
}
static std::pair<std::optional<IOrthoShadowProjections::OrthoSubProjection>, float> CalculateNextFrustum_UnfilledSpace(
const RenderCore::Techniques::ProjectionDesc& mainSceneProjectionDesc,
const Float3* absFrustumCorners,
const Float4x4& lightViewToWorld,
const IOrthoShadowProjections::OrthoSubProjection& prev,
const Float4& cameraMiniProj,
const float maxProjectionDimsZ,
float depthRangeCovered,
ClipSpaceType clipSpaceType)
{
// Calculate the next frustum for a set of cascades, based on unfilled space
// Find the nearest part of the view frustum that is not included in the previous ortho projection
// & use that to position the new projection starting from that point
auto closestUncoveredPart = NearestPointNotInsideOrthoProjection(
mainSceneProjectionDesc._worldToProjection, absFrustumCorners,
lightViewToWorld,
prev, depthRangeCovered, clipSpaceType);
if (!closestUncoveredPart.first.empty()) {
// We want to position the new projection so that the center point is exactly on the camera forward
// ray, and so that "closestUncoveredPart" is (most likely) exactly on one of the planes of the
// ortho box
//
// This will mean that the new projection begins exactly where the old projection ended. However,
// floating point creep here can add up to more than a pixel in screen space, so we need a little
// bit of tolerance added.
//
// So while the first projection can be configured to be off the center ray of the camera, subsequent
// projections always will be.
//
// We have some flexibility over the size of this new frustum -- in theory we could calculate size
// that would attempt to maintain the same screen space pixel to shadowmap texel ratio -- however,
// for more distant parts of the view frustum, visual importance also drops off; so we
//
// let's do this in ortho space, where it's going to be a lot easier
auto newProjectionDimsXY = 3.f * (prev._rightBottomBack[0] - prev._leftTopFront[0]);
auto newProjectionDimsZ = 3.f * (prev._rightBottomBack[2] - prev._leftTopFront[2]);
newProjectionDimsZ = std::min(newProjectionDimsZ, maxProjectionDimsZ);
auto worldToLightView = InvertOrthonormalTransform(lightViewToWorld);
auto camForwardInOrtho = TransformDirectionVector(worldToLightView, ExtractForward_Cam(mainSceneProjectionDesc._cameraToWorld));
auto camPositionInOrtho = TransformPoint(worldToLightView, ExtractTranslation(mainSceneProjectionDesc._cameraToWorld));
Float3 closestUncoveredPartInOrtho = TransformPoint(worldToLightView, closestUncoveredPart.first[0]);
// Allow for a tiny bit of overlap, both to cover for floating point creep errors, and allow the shader
// to cross-fade. 2% of the distance to the start of the projection, up to quarter unit max
float overlap = std::min(Dot(closestUncoveredPartInOrtho, camForwardInOrtho) * 0.02f, 0.25f);
Float3 focusPositionInOrtho = camPositionInOrtho + (Dot(closestUncoveredPartInOrtho, camForwardInOrtho) - overlap + 0.5f * newProjectionDimsXY) * camForwardInOrtho;
IOrthoShadowProjections::OrthoSubProjection result;
result._leftTopFront = Float3 { focusPositionInOrtho[0] - 0.5f * newProjectionDimsXY, focusPositionInOrtho[1] - 0.5f * newProjectionDimsXY, focusPositionInOrtho[2] - 0.5f * newProjectionDimsZ };
result._rightBottomBack = Float3 { focusPositionInOrtho[0] + 0.5f * newProjectionDimsXY, focusPositionInOrtho[1] + 0.5f * newProjectionDimsXY, focusPositionInOrtho[2] + 0.5f * newProjectionDimsZ };
auto minAndMaxDepth = MinAndMaxOrthoSpaceZ(mainSceneProjectionDesc._worldToProjection, absFrustumCorners, lightViewToWorld, Truncate(result._leftTopFront), Truncate(result._rightBottomBack), cameraMiniProj, closestUncoveredPart.second, clipSpaceType);
if (minAndMaxDepth[0] > minAndMaxDepth[1])
return {{}, closestUncoveredPart.second};
bool entireViewFrustumCovered = (minAndMaxDepth[1] - newProjectionDimsZ) < minAndMaxDepth[0];
if (!entireViewFrustumCovered) {
if (TransformDirectionVector(worldToLightView, ExtractForward_Cam(mainSceneProjectionDesc._cameraToWorld))[2] > 0) {
// This is a little awkward because of the way -Z in camera space is forward; we have to be very careful of polarity in all these equations
result._leftTopFront[2] = minAndMaxDepth[0];
result._rightBottomBack[2] = minAndMaxDepth[0] + newProjectionDimsZ;
} else {
result._leftTopFront[2] = minAndMaxDepth[1] - newProjectionDimsZ;
result._rightBottomBack[2] = minAndMaxDepth[1];
}
} else {
result._leftTopFront[2] = minAndMaxDepth[1] - newProjectionDimsZ;
result._rightBottomBack[2] = minAndMaxDepth[1];
}
assert(result._leftTopFront[2] < result._rightBottomBack[2]);
return {result, closestUncoveredPart.second};
}
return {{}, depthRangeCovered};
}
static Float2 s_normalizedScreenResolution(1920, 1080);
static unsigned ShadowMapDepthResolution(SunSourceFrustumSettings::Flags::BitField flags)
{
if (flags & SunSourceFrustumSettings::Flags::HighPrecisionDepths) {
return (1 << 23) - 1; // high precision depths are a little awkward because it's floating point. But let's just use the size of the mantissa as an underestimate here
} else
return (1 << 16) - 1;
}
static OrthoProjections BuildResolutionNormalizedOrthogonalShadowProjections(
const Float3& negativeLightDirection,
const RenderCore::Techniques::ProjectionDesc& mainSceneProjectionDescInit,
const SunSourceFrustumSettings& settings,
ClipSpaceType clipSpaceType)
{
// settings._resolutionScale is approximately the number of on-screen pixels per shadow map pixel
// in each dimension (ie 2 means a shadow map pixel should cover about a 2x2 on screen pixel area)
// However, we don't adjust the base resolution with the viewport to avoid moving the shadow
// distance back and forth with render resolution changes
const Float2 normalizedScreenResolution = s_normalizedScreenResolution / settings._resolutionScale;
const unsigned shadowMapResolution = settings._textureSize;
auto shadowMapDepthResolution = ShadowMapDepthResolution(settings._flags);
// We remove the camera position from the projection desc, because it's not actually important for
// the calculations, and would just add floating point precision problems. Instead, let's do the
// calculations as if the camera is at the origin, and then translate the results back to the
// camera position at the end
auto mainSceneProjectionDesc = mainSceneProjectionDescInit;
Float3 extractedCameraPos = ExtractTranslation(mainSceneProjectionDesc._cameraToWorld);
SetTranslation(mainSceneProjectionDesc._cameraToWorld, Float3{0.f, 0.f, 0.f});
// Also limit the far clip plane by the _maxDistanceFromCamera setting -- this allows us to set
// a limit on how far in the distance the shadows go
{
auto mainSceneNearAndFar = CalculateNearAndFarPlane(ExtractMinimalProjection(mainSceneProjectionDesc._cameraToProjection), clipSpaceType);
if (mainSceneNearAndFar.second > settings._maxDistanceFromCamera)
ChangeFarClipPlane(mainSceneProjectionDesc._cameraToProjection, settings._maxDistanceFromCamera, clipSpaceType);
}
mainSceneProjectionDesc._worldToProjection =
Combine(InvertOrthonormalTransform(mainSceneProjectionDesc._cameraToWorld), mainSceneProjectionDesc._cameraToProjection);
Float3 cameraForward = ExtractForward_Cam(mainSceneProjectionDesc._cameraToWorld);
Float3 focusPoint = settings._focusDistance * ExtractForward_Cam(mainSceneProjectionDesc._cameraToWorld);
assert(!IsOrthogonalProjection(mainSceneProjectionDesc._cameraToProjection));
auto cameraMiniProj = ExtractMinimalProjection(mainSceneProjectionDesc._cameraToProjection);
// Limit the depth of the shadow projection to some reasonable fixed value. If we allow it to
// get too large, we will get end up with a lot of floating point precision issues when building
// the frustum
// This will have an impact on the correct shadow bias values, etc, though
const float maxProjectionDimsZ = 1.5f * CalculateNearAndFarPlane(cameraMiniProj, clipSpaceType).second;
// find the dimensions in view space for the focus point
auto worldToMainCamera = InvertOrthonormalTransform(mainSceneProjectionDesc._cameraToWorld);
auto viewSpaceFocusPoint = TransformPoint(worldToMainCamera, focusPoint);
auto clipSpaceFocus = mainSceneProjectionDesc._cameraToProjection * Expand(viewSpaceFocusPoint, 1.0f);
float w = clipSpaceFocus[3];
float viewSpaceDimsX = 1.0f / float(normalizedScreenResolution[0]) * 2.0f * w / mainSceneProjectionDesc._cameraToProjection(0,0);
float viewSpaceDimsY = 1.0f / float(normalizedScreenResolution[1]) * 2.0f * w / mainSceneProjectionDesc._cameraToProjection(1,1);
// choose the minimum absolute value so ultra widescreen isn't disadvantaged
float viewSpacePixelDims = std::min(std::abs(viewSpaceDimsX), std::abs(viewSpaceDimsY));
// We want to project the first frustum so that one shadow map texel maps roughly onto one screen pixel
// (also, we want to keep the depth precision roughly inline with X & Y precision, so this will also impact
// the depth range for the shadow projection)
float projectionDimsXY = viewSpacePixelDims * shadowMapResolution;
float projectionDimsZ = viewSpacePixelDims * shadowMapDepthResolution;
projectionDimsZ = std::min(maxProjectionDimsZ, projectionDimsZ);
Float3 shadowAcross = ExtractForward_Cam(mainSceneProjectionDesc._cameraToWorld);
auto lightViewToWorld = MakeOrientedShadowViewToWorld(-negativeLightDirection, shadowAcross, Float3{0.f, 0.f, 0.f});
auto worldToLightView = InvertOrthonormalTransform(lightViewToWorld);
// The first projection must include the near plane of the camera, as well as the focus point
Float3 nearPlaneLightViewMins { FLT_MAX, FLT_MAX, FLT_MAX }, nearPlaneLightViewMaxs { -FLT_MAX, -FLT_MAX, -FLT_MAX };
Float3 focusLightView = TransformPoint(worldToLightView, focusPoint);
Float3 absFrustumCorners[8];
CalculateAbsFrustumCorners(absFrustumCorners, mainSceneProjectionDesc._worldToProjection, clipSpaceType);
for (unsigned c=0; c<4; ++c) {
auto lightView = TransformPoint(worldToLightView, absFrustumCorners[c]);
nearPlaneLightViewMins[0] = std::min(nearPlaneLightViewMins[0], lightView[0]);
nearPlaneLightViewMins[1] = std::min(nearPlaneLightViewMins[1], lightView[1]);
nearPlaneLightViewMins[2] = std::min(nearPlaneLightViewMins[2], lightView[2]);
nearPlaneLightViewMaxs[0] = std::max(nearPlaneLightViewMaxs[0], lightView[0]);
nearPlaneLightViewMaxs[1] = std::max(nearPlaneLightViewMaxs[1], lightView[1]);
nearPlaneLightViewMaxs[2] = std::max(nearPlaneLightViewMaxs[2], lightView[2]);
}
IOrthoShadowProjections::OrthoSubProjection firstSubProjection;
auto camForwardInOrtho = TransformDirectionVector(worldToLightView, ExtractForward_Cam(mainSceneProjectionDesc._cameraToWorld));
Float3 centerProjectOrtho = 0.5f * projectionDimsXY * camForwardInOrtho;
firstSubProjection._leftTopFront[0] = centerProjectOrtho[0] - 0.5f * projectionDimsXY;
firstSubProjection._rightBottomBack[0] = centerProjectOrtho[0] + 0.5f * projectionDimsXY;
firstSubProjection._leftTopFront[1] = centerProjectOrtho[1] - 0.5f * projectionDimsXY;
firstSubProjection._rightBottomBack[1] = centerProjectOrtho[1] + 0.5f * projectionDimsXY;
float depthRangeClosest;
#if !defined(USE_W_FOR_DEPTH_RANGE_COVERED)
if (clipSpaceType == ClipSpaceType::Positive_ReverseZ || clipSpaceType == ClipSpaceType::PositiveRightHanded_ReverseZ) {
float n, f;
std::tie(n,f) = CalculateNearAndFarPlane(cameraMiniProj, clipSpaceType);
depthRangeClosest = (n*n-(n*f)) / (n-f);
} else {
depthRangeClosest = 0.f;
}
#else
depthRangeClosest = 0.f;
#endif
// We're assuming that geometry closer to the light than the view frustum will be clamped
// to zero depth here -- so the shadow projection doesn't need to extend all the way to
// the light
// Most of the time we want the largest Z value to be sitting right on the edge of the view frustum
// and then extend the frustum as far negative as the precision depth allows (recalling that -Z is
// forward in view space). However, if the camera is facing directly into the light (ie, they are in
// opposite directions), that will pin the shadow projection to the far clip and it's possible that
// the shadow frustum won't reach all of the way to the camera. In that case, we pin the positive side
// of the shadow frustum to the view and extend backwards
auto minAndMaxDepth = MinAndMaxOrthoSpaceZ(mainSceneProjectionDesc._worldToProjection, absFrustumCorners, lightViewToWorld, Truncate(firstSubProjection._leftTopFront), Truncate(firstSubProjection._rightBottomBack), cameraMiniProj, depthRangeClosest, clipSpaceType);
assert(projectionDimsZ > 0);
bool entireViewFrustumCovered = (minAndMaxDepth[1] - projectionDimsZ) < minAndMaxDepth[0];
if (!entireViewFrustumCovered) {
if (TransformDirectionVector(worldToLightView, cameraForward)[2] > 0) {
// This is a little awkward because of the way -Z in camera space is forward; we have to be very careful of polarity in all these equations
firstSubProjection._leftTopFront[2] = minAndMaxDepth[0];
firstSubProjection._rightBottomBack[2] = minAndMaxDepth[0] + projectionDimsZ;
} else {
firstSubProjection._leftTopFront[2] = minAndMaxDepth[1] - projectionDimsZ;
firstSubProjection._rightBottomBack[2] = minAndMaxDepth[1];
}
} else {
firstSubProjection._leftTopFront[2] = minAndMaxDepth[1] - projectionDimsZ;
firstSubProjection._rightBottomBack[2] = minAndMaxDepth[1];
}
assert(firstSubProjection._leftTopFront[2] < firstSubProjection._rightBottomBack[2]);
OrthoProjections result;
result._worldToView = worldToLightView;
Combine_IntoRHS(-extractedCameraPos, result._worldToView); // note -- camera position added back here
result._normalProjCount = 1;
result._orthSubProjections[0] = firstSubProjection;
float depthRangeCovered = depthRangeClosest;
while (result._normalProjCount < settings._maxFrustumCount) {
auto next = CalculateNextFrustum_UnfilledSpace(mainSceneProjectionDesc, absFrustumCorners, lightViewToWorld, result._orthSubProjections[result._normalProjCount-1], cameraMiniProj, maxProjectionDimsZ, depthRangeCovered, clipSpaceType);
if (!next.first.has_value()) break;
// Log(Debug) << "DepthRangeCovered: " << depthRangeCovered << std::endl;
result._orthSubProjections[result._normalProjCount] = next.first.value();
++result._normalProjCount;
depthRangeCovered = next.second;
}
for (unsigned c=0; c<result._normalProjCount; ++c) {
std::swap(result._orthSubProjections[c]._leftTopFront[1], result._orthSubProjections[c]._rightBottomBack[1]);
result._orthSubProjections[c]._leftTopFront[2] = -result._orthSubProjections[c]._leftTopFront[2];
result._orthSubProjections[c]._rightBottomBack[2] = -result._orthSubProjections[c]._rightBottomBack[2];
std::swap(result._orthSubProjections[c]._leftTopFront[2], result._orthSubProjections[c]._rightBottomBack[2]);
}
/*
We can calculate how much of the view frustum has been filled, by calling:
auto nearest = NearestPointNotInsideOrthoProjection(
mainSceneProjectionDesc._worldToProjection, absFrustumCorners,
lightViewToWorld, result._orthSubProjections[result._normalProjCount-1],
depthRangeCovered);
if nearest.first.empty(), then the entire view frustum is filled. Otherwise
nearest.second is the deepest Z in clip space for which the entire XY plane
is filled (though shadows may actually go deaper in some parts of the plane)
*/
result._limitedMainCameraToProjection = mainSceneProjectionDesc._cameraToProjection;
return result;
}
namespace Internal
{
std::pair<std::vector<IOrthoShadowProjections::OrthoSubProjection>, Float4x4> TestResolutionNormalizedOrthogonalShadowProjections(
const Float3& negativeLightDirection,
const RenderCore::Techniques::ProjectionDesc& mainSceneProjectionDesc,
const SunSourceFrustumSettings& settings,
ClipSpaceType clipSpaceType)
{
auto midway = BuildResolutionNormalizedOrthogonalShadowProjections(negativeLightDirection, mainSceneProjectionDesc, settings, clipSpaceType);
return {
{midway._orthSubProjections, &midway._orthSubProjections[midway._normalProjCount]},
midway._worldToView};
}
}
ShadowOperatorDesc CalculateShadowOperatorDesc(const SunSourceFrustumSettings& settings)
{
ShadowOperatorDesc result;
result._dominantLight = true;
result._width = settings._textureSize;
result._height = settings._textureSize;
if (settings._flags & SunSourceFrustumSettings::Flags::HighPrecisionDepths) {
// note -- currently having problems in Vulkan with reading from the D24_UNORM_XX format
// might be better to move to 32 bit format now, anyway
result._format = RenderCore::Format::D32_FLOAT;
} else {
result._format = RenderCore::Format::D16_UNORM;
}
if (settings._flags & SunSourceFrustumSettings::Flags::ArbitraryCascades) {
result._normalProjCount = 5;
result._enableNearCascade = false;
result._projectionMode = ShadowProjectionMode::Arbitrary;
} else {
result._normalProjCount = settings._maxFrustumCount;
// result._enableNearCascade = true;
result._projectionMode = ShadowProjectionMode::Ortho;
}
if (settings._flags & SunSourceFrustumSettings::Flags::RayTraced) {
result._resolveType = ShadowResolveType::RayTraced;
} else {
result._resolveType = ShadowResolveType::DepthTexture;
}
if (settings._flags & SunSourceFrustumSettings::Flags::CullFrontFaces) {
result._cullMode = RenderCore::CullMode::Front;
} else {
result._cullMode = RenderCore::CullMode::Back;
}
// We need to know the approximate height in world space units for the first
// projection. This is an approximation of projectionDimsXY in BuildResolutionNormalizedOrthogonalShadowProjections
// Imagine we're looking straight on at a plane in front of the camera, and the is behind and pointing in the
// same direction as the camera.
const Float2 normalizedScreenResolution = s_normalizedScreenResolution / settings._resolutionScale;
const unsigned shadowMapResolution = settings._textureSize;
const float h = XlTan(.5f * settings._expectedVerticalFOV);
float wsFrustumHeight = settings._focusDistance * h * settings._textureSize / s_normalizedScreenResolution[1];
auto shadowMapDepthResolution = ShadowMapDepthResolution(settings._flags);
float projectionDimsXY = wsFrustumHeight;
float projectionDimsZ = wsFrustumHeight * shadowMapDepthResolution / settings._textureSize; // this has an upper range, maxProjectionDimsZ, above -- but it's harder to estimate
// We calculate the radius in world space of the blurring kernel, and compare this to the difference
// in world space between 2 adjacent depth values possible in the depth buffer. Since we're using
// an orthogonal projection, the depth values are equally spaced throughout the entire range.
// From this, we can estimate how much bias we'll need to avoid acne with the given blur range
// A base sloped scaled bias value of 0.5 is often enough to handle cases where there is no blur kernel
// Generally we should have an excess of depth resolution, even without HighPrecisionDepths, when using
// cascades -- since the first cascade tends to end up pretty tightly arranged just in front of the camera
const float wsDepthResolution = projectionDimsZ / float(shadowMapDepthResolution);
const float wsXYRange = settings._maxBlurSearch * wsFrustumHeight / settings._textureSize;
const float ratio0 = wsXYRange / wsDepthResolution;
const float ratio1 = std::sqrt(wsXYRange*wsXYRange + wsXYRange*wsXYRange) / wsDepthResolution;
result._singleSidedBias._depthBias = result._doubleSidedBias._depthBias = (int)-settings._baseBias * std::ceil(ratio1); // note -- negative for ReverseZ modes
result._singleSidedBias._depthBiasClamp = result._doubleSidedBias._depthBiasClamp = 0.f;
result._singleSidedBias._slopeScaledBias = result._doubleSidedBias._slopeScaledBias = settings._slopeScaledBias;
result._filterModel = settings._filterModel;
result._enableContactHardening = settings._enableContactHardening;
result._cullMode = settings._cullMode;
return result;
}
class SunSourceFrustumDriver : public Internal::IShadowProjectionDriver, public ISunSourceShadows, public Internal::ILightBase
{
public:
virtual std::shared_ptr<XLEMath::ArbitraryConvexVolumeTester> UpdateProjections(
const Techniques::ParsingContext& parsingContext,
IPositionalLightSource& lightSource,
IOrthoShadowProjections& destination) override
{
auto mainSceneProjectionDesc = parsingContext.GetProjectionDesc();
if (_fixedCamera)
mainSceneProjectionDesc = _fixedCamera.value();
auto negativeLightDirection = Normalize(ExtractTranslation(lightSource.GetLocalToWorld()));
assert(!(_settings._flags & SunSourceFrustumSettings::Flags::ArbitraryCascades));
auto clipSpaceType = RenderCore::Techniques::GetDefaultClipSpaceType();
auto t = BuildResolutionNormalizedOrthogonalShadowProjections(negativeLightDirection, mainSceneProjectionDesc, _settings, clipSpaceType);
assert(t._normalProjCount);
destination.SetOrthoSubProjections(MakeIteratorRange(t._orthSubProjections, &t._orthSubProjections[t._normalProjCount]));
destination.SetWorldToOrthoView(t._worldToView);
// Generate a clipping volume by extruding the camera frustum along the light direction
// Here, we're assuming that the cascades will fill t._limitedMainCameraToProjection entirely
// Which means the correct culling is to look for objects that can cast a shadow into
// that frustum.
auto eyePosition = ExtractTranslation(mainSceneProjectionDesc._cameraToWorld);
auto cameraToWorldNoTranslation = mainSceneProjectionDesc._cameraToWorld;
SetTranslation(cameraToWorldNoTranslation, Float3(0,0,0));
auto worldToLimitedProj = Combine(InvertOrthonormalTransform(cameraToWorldNoTranslation), t._limitedMainCameraToProjection);
auto extrudedFrustum = ExtrudeFrustumOrthogonally(worldToLimitedProj, eyePosition, negativeLightDirection, _settings._maxDistanceFromCamera, clipSpaceType);
return std::make_shared<XLEMath::ArbitraryConvexVolumeTester>(std::move(extrudedFrustum));
}
SunSourceFrustumSettings GetSettings() const override
{
return _settings;
}
void SetSettings(const SunSourceFrustumSettings&) override
{
assert(0); // not yet implemennted
}
void FixMainSceneCamera(const Techniques::ProjectionDesc& projDesc) override
{
_fixedCamera = projDesc;
}
void UnfixMainSceneCamera() override
{
_fixedCamera = {};
}
virtual void* QueryInterface(uint64_t interfaceTypeCode) override
{
if (interfaceTypeCode == typeid(Internal::IShadowProjectionDriver).hash_code()) {
return (Internal::IShadowProjectionDriver*)this;
} else if (interfaceTypeCode == typeid(ISunSourceShadows).hash_code()) {
return (ISunSourceShadows*)this;
}
return nullptr;
}
SunSourceFrustumDriver(const SunSourceFrustumSettings& settings) : _settings(settings) {}
private:
SunSourceFrustumSettings _settings;
std::optional<Techniques::ProjectionDesc> _fixedCamera;
};
static void ApplyNonFrustumSettings(
ILightScene& lightScene,
ILightScene::ShadowProjectionId shadowProjectionId,
const SunSourceFrustumSettings& settings)
{
auto* preparer = lightScene.TryGetShadowProjectionInterface<IDepthTextureResolve>(shadowProjectionId);
if (preparer) {
IDepthTextureResolve::Desc desc;
desc._worldSpaceResolveBias = settings._worldSpaceResolveBias;
desc._tanBlurAngle = settings._tanBlurAngle;
desc._minBlurSearch = settings._minBlurSearch;
desc._maxBlurSearch = settings._maxBlurSearch;
desc._casterDistanceExtraBias = settings._casterDistanceExtraBias;
preparer->SetDesc(desc);
}
}
ILightScene::ShadowProjectionId CreateSunSourceShadows(
ILightScene& lightScene,
ILightScene::ShadowOperatorId shadowOperatorId,
ILightScene::LightSourceId associatedLightId,
const SunSourceFrustumSettings& settings)
{
auto shadowProjectionId = lightScene.CreateShadowProjection(shadowOperatorId, associatedLightId);
ApplyNonFrustumSettings(lightScene, shadowProjectionId, settings);
auto* attachDriver = lightScene.TryGetShadowProjectionInterface<Internal::IAttachDriver>(shadowProjectionId);
if (attachDriver) {
attachDriver->AttachDriver(
std::make_shared<SunSourceFrustumDriver>(settings));
} else {
assert(0);
}
/*result._shadowGeneratorDesc = CalculateShadowGeneratorDesc(settings);
assert(result._shadowGeneratorDesc._enableNearCascade == result._projections._useNearProj);
assert(result._shadowGeneratorDesc._arrayCount == result._projections.Count());
assert(result._shadowGeneratorDesc._projectionMode == result._projections._mode);
return result;*/
return shadowProjectionId;
}
void ConfigureShadowProjectionImmediately(
ILightScene& lightScene,
ILightScene::ShadowProjectionId shadowProjectionId,
ILightScene::LightSourceId associatedLightId,
const SunSourceFrustumSettings& settings,
const Techniques::ProjectionDesc& mainSceneProjectionDesc)
{
auto* positionalLightSource = lightScene.TryGetLightSourceInterface<IPositionalLightSource>(associatedLightId);
if (!positionalLightSource)
Throw(std::runtime_error("Could not find positional light source information in CreateShadowCascades for a sun light source"));
auto negativeLightDirection = Normalize(ExtractTranslation(positionalLightSource->GetLocalToWorld()));
assert(!(settings._flags & SunSourceFrustumSettings::Flags::ArbitraryCascades));
auto t = BuildResolutionNormalizedOrthogonalShadowProjections(negativeLightDirection, mainSceneProjectionDesc, settings, RenderCore::Techniques::GetDefaultClipSpaceType());
assert(t._normalProjCount);
auto* cascades = lightScene.TryGetShadowProjectionInterface<IOrthoShadowProjections>(shadowProjectionId);
if (cascades) {
cascades->SetOrthoSubProjections(
MakeIteratorRange(t._orthSubProjections, &t._orthSubProjections[t._normalProjCount]));
cascades->SetWorldToOrthoView(t._worldToView);
}
ApplyNonFrustumSettings(lightScene, shadowProjectionId, settings);
}
SunSourceFrustumSettings::SunSourceFrustumSettings()
{
_maxFrustumCount = 5;
_maxDistanceFromCamera = 500.f;
_frustumSizeFactor = 3.8f;
_focusDistance = 3.f;
_resolutionScale = 1.f;
_flags = Flags::HighPrecisionDepths;
_textureSize = 2048;
_expectedVerticalFOV = Deg2Rad(34.8246f);
_worldSpaceResolveBias = 0.025f; // this is world space, so always positive, ReverseZ doesn't matter
_casterDistanceExtraBias = -0.001f; // note that this should be negative for ReverseZ modes, but positive for non-ReverseZ modes
_slopeScaledBias = -0.5f; // also should be native for ReverseZ modes
_baseBias = 1.f; // this multiples the calculated base bias values, so should be positive
_tanBlurAngle = 0.00436f;
_minBlurSearch = 0.5f;
_maxBlurSearch = 25.f;
_filterModel = ShadowFilterModel::PoissonDisc;
_enableContactHardening = false;
_cullMode = CullMode::Back;
}
}}
#include "../Utility/Meta/ClassAccessors.h"
#include "../Utility/Meta/ClassAccessorsImpl.h"
template<> const ClassAccessors& Legacy_GetAccessors<RenderCore::LightingEngine::SunSourceFrustumSettings>()
{
using Obj = RenderCore::LightingEngine::SunSourceFrustumSettings;
static ClassAccessors props(typeid(Obj).hash_code());
static bool init = false;
if (!init) {
props.Add("MaxCascadeCount",
[](const Obj& obj) { return obj._maxFrustumCount; },
[](Obj& obj, unsigned value) { obj._maxFrustumCount = Clamp(value, 1u, RenderCore::LightingEngine::s_staticMaxSubProjections); });
props.Add("MaxDistanceFromCamera", &Obj:: _maxDistanceFromCamera);
props.Add("FrustumSizeFactor", &Obj::_frustumSizeFactor);
props.Add("FocusDistance", &Obj::_focusDistance);
props.Add("ResolutionScale", &Obj::_resolutionScale);
props.Add("Flags", &Obj::_flags);
props.Add("TextureSize",
[](const Obj& obj) { return obj._textureSize; },
[](Obj& obj, unsigned value) { obj._textureSize = 1<<(IntegerLog2(value-1)+1); }); // ceil to a power of two
props.Add("BlurAngleDegrees",
[](const Obj& obj) { return Rad2Deg(XlATan(obj._tanBlurAngle)); },
[](Obj& obj, float value) { obj._tanBlurAngle = XlTan(Deg2Rad(value)); } );
props.Add("MinBlurSearch", &Obj::_minBlurSearch);
props.Add("MaxBlurSearch", &Obj::_maxBlurSearch);
props.Add("HighPrecisionDepths",
[](const Obj& obj) { return !!(obj._flags & Obj::Flags::HighPrecisionDepths); },
[](Obj& obj, bool value) {
if (value) obj._flags |= Obj::Flags::HighPrecisionDepths;
else obj._flags &= ~Obj::Flags::HighPrecisionDepths;
});
props.Add("CasterDistanceExtraBias", &Obj::_casterDistanceExtraBias);
props.Add("WorldSpaceResolveBias", &Obj::_worldSpaceResolveBias);
props.Add("SlopeScaledBias", &Obj::_slopeScaledBias);
props.Add("BaseBias", &Obj::_baseBias);
props.Add("EnableContactHardening", &Obj::_enableContactHardening);
AddStringToEnum<RenderCore::LightingEngine::ShadowFilterModel, RenderCore::LightingEngine::AsString, RenderCore::LightingEngine::AsShadowFilterModel>(props, "FilterModel", &Obj::_filterModel);
AddStringToEnum<RenderCore::CullMode, RenderCore::AsString, RenderCore::AsCullMode>(props, "CullMode", &Obj::_cullMode);
init = true;
}
return props;
}
| 55.518152 | 273 | 0.64918 | djewsbury |
6ca0c40ea75d9eb9f0aa57c35c1debc98de28fc0 | 236 | cpp | C++ | hexmap_qt/hexmap_widgets/layers_widget.cpp | mflagel/asdf_multiplat | 9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015 | [
"MIT"
] | null | null | null | hexmap_qt/hexmap_widgets/layers_widget.cpp | mflagel/asdf_multiplat | 9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015 | [
"MIT"
] | null | null | null | hexmap_qt/hexmap_widgets/layers_widget.cpp | mflagel/asdf_multiplat | 9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015 | [
"MIT"
] | null | null | null | #include "layers_widget.h"
#include "ui_layers_widget.h"
layers_widget::layers_widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::layers_widget)
{
ui->setupUi(this);
}
layers_widget::~layers_widget()
{
delete ui;
}
| 15.733333 | 47 | 0.694915 | mflagel |
6ca180b6b8021c8ae97a451a9e5e3b0b9c7135cf | 3,132 | cpp | C++ | aws-cpp-sdk-discovery/source/model/ConfigurationItemType.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2020-07-16T19:03:13.000Z | 2020-07-16T19:03:13.000Z | aws-cpp-sdk-discovery/source/model/ConfigurationItemType.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 18 | 2018-05-15T16:41:07.000Z | 2018-05-21T00:46:30.000Z | aws-cpp-sdk-discovery/source/model/ConfigurationItemType.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2021-10-01T15:29:44.000Z | 2021-10-01T15:29:44.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/discovery/model/ConfigurationItemType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace ApplicationDiscoveryService
{
namespace Model
{
namespace ConfigurationItemTypeMapper
{
static const int SERVER_HASH = HashingUtils::HashString("SERVER");
static const int PROCESS_HASH = HashingUtils::HashString("PROCESS");
static const int CONNECTION_HASH = HashingUtils::HashString("CONNECTION");
static const int APPLICATION_HASH = HashingUtils::HashString("APPLICATION");
ConfigurationItemType GetConfigurationItemTypeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == SERVER_HASH)
{
return ConfigurationItemType::SERVER;
}
else if (hashCode == PROCESS_HASH)
{
return ConfigurationItemType::PROCESS;
}
else if (hashCode == CONNECTION_HASH)
{
return ConfigurationItemType::CONNECTION;
}
else if (hashCode == APPLICATION_HASH)
{
return ConfigurationItemType::APPLICATION;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<ConfigurationItemType>(hashCode);
}
return ConfigurationItemType::NOT_SET;
}
Aws::String GetNameForConfigurationItemType(ConfigurationItemType enumValue)
{
switch(enumValue)
{
case ConfigurationItemType::SERVER:
return "SERVER";
case ConfigurationItemType::PROCESS:
return "PROCESS";
case ConfigurationItemType::CONNECTION:
return "CONNECTION";
case ConfigurationItemType::APPLICATION:
return "APPLICATION";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return "";
}
}
} // namespace ConfigurationItemTypeMapper
} // namespace Model
} // namespace ApplicationDiscoveryService
} // namespace Aws
| 32.968421 | 92 | 0.650383 | ploki |
6ca55b8172df1983bf31dab2fb2ed597fb9e16f7 | 3,015 | cpp | C++ | src/sigevent.cpp | drcforbin/rwte | e1527369fa46c8ae92cd92269d3820c631771a8b | [
"MIT"
] | 9 | 2017-06-25T03:01:04.000Z | 2022-01-01T19:03:26.000Z | src/sigevent.cpp | drcforbin/rwte | e1527369fa46c8ae92cd92269d3820c631771a8b | [
"MIT"
] | null | null | null | src/sigevent.cpp | drcforbin/rwte | e1527369fa46c8ae92cd92269d3820c631771a8b | [
"MIT"
] | 2 | 2019-03-07T21:18:44.000Z | 2019-08-27T08:44:14.000Z | #include "rw/logging.h"
#include "rwte/sigevent.h"
#include <array>
#include <atomic>
#include <cassert>
#include <cstddef>
#include <errno.h>
#include <signal.h>
#include <sys/eventfd.h>
#include <unistd.h>
#define LOGGER() (rw::logging::get("sigevent"))
// todo: clean up all these exposed errors
static std::atomic_uint64_t SIGS_PENDING = 0;
static std::atomic_int SIGNAL_FD = -1;
extern "C" void sig_handler(int sig)
{
SIGS_PENDING.fetch_or(1 << uint64_t(sig), std::memory_order_relaxed);
int fd = SIGNAL_FD.load(std::memory_order_relaxed);
std::array<unsigned char, 8> buf = {1, 0, 0, 0, 0, 0, 0, 0};
// ignoring write result. there's nothing we
// can do here but panic anyway
write(fd, &buf, buf.size());
}
// todo: de-genericify this or move it to librw...we dont need general purpose
void connect_handler(int sig)
{
// we only have space for 64 signals...
if (sig > 64) {
throw SigEventError(fmt::format("requested sig {}, only 64 signals are supported", sig));
}
sigset_t mask;
sigfillset(&mask);
// todo: do we want SA_NOCLDSTOP / SA_NOCLDWAIT when SIGCHLD,
// we're checking on whether it indicates an exit in the tty
struct sigaction sa;
sa.sa_handler = sig_handler;
sa.sa_mask = mask;
if (sigaction(sig, &sa, nullptr) == -1) {
throw SigEventError(fmt::format("unable to register signal {}, ({}): {}",
sig, errno, strerror(errno)));
}
}
SigEventError::SigEventError(const std::string& arg) :
std::runtime_error(arg)
{}
SigEventError::SigEventError(const char* arg) :
std::runtime_error(arg)
{}
SigEventError::~SigEventError()
{}
SigEvent::SigEvent()
{
// todo: ensure singleton by checking on SIGNAL_FD value
int fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (fd != -1) {
LOGGER()->trace("signal fd: {}", fd);
SIGNAL_FD.store(fd, std::memory_order_relaxed);
m_evfd = fd;
} else {
throw SigEventError(fmt::format("unable to create signal fd ({}): {}",
errno, strerror(errno)));
}
}
SigEvent::~SigEvent()
{
if (m_evfd != -1) {
close(m_evfd);
}
}
uint64_t SigEvent::read()
{
// read the eventfd blob. interrupted or wouldblock result
// can be ignored (and we go around again), other errors should
// result in a stop.
std::array<unsigned char, 8> buf;
ssize_t res = ::read(m_evfd, &buf, 8);
if (res == -1) {
if (errno != EINTR && errno != EWOULDBLOCK) {
LOGGER()->fatal("unable to read signal fd {}, ({}): {}",
m_evfd, errno, strerror(errno));
return 0;
}
}
uint64_t current = 0;
for (;;) {
// strong to avoid spurious signals
if (SIGS_PENDING.compare_exchange_strong(
current,
0,
std::memory_order_relaxed,
std::memory_order_relaxed)) {
break;
}
}
return current;
}
| 25.991379 | 97 | 0.6 | drcforbin |
6ca7a614a69203b0a2b9898b8243b576ad16ad4e | 726 | cpp | C++ | Dynamic Programming/integer-knapsack.cpp | chaitanyarahalkar/Algorithms | 27c7f952645afccab12d89c025d69a427c36550f | [
"MIT"
] | 3 | 2021-07-22T12:43:59.000Z | 2021-07-23T16:34:54.000Z | Dynamic Programming/integer-knapsack.cpp | chaitanyarahalkar/Algorithms | 27c7f952645afccab12d89c025d69a427c36550f | [
"MIT"
] | null | null | null | Dynamic Programming/integer-knapsack.cpp | chaitanyarahalkar/Algorithms | 27c7f952645afccab12d89c025d69a427c36550f | [
"MIT"
] | 1 | 2020-05-03T13:56:55.000Z | 2020-05-03T13:56:55.000Z | #include <iostream>
using std::cout;
using std::max;
int integer_knapsack(int capacity,int weights[],int values[],int n){
int table[n+1][capacity+1];
for(int i = 0; i <= n;i++){
for(int w = 0; w <= capacity; w++){
if(i == 0 || w == 0)
table[i][w] = 0;
else if(weights[i-1] <= w)
table[i][w] = max(values[i-1] + table[i-1][w - weights[i-1]],table[i-1][w]);
else
table[i][w] = table[i-1][w];
}
}
return table[n][capacity];
}
int main(void){
int values[] = {60,100,120};
int weights[] = {10,20,30};
int capacity = 50;
int n = sizeof(values)/sizeof(int);
int result = integer_knapsack(capacity,weights,values,n);
cout << "Maximum profit possible is " << result << "\n";
return 0;
} | 19.105263 | 80 | 0.57989 | chaitanyarahalkar |
6ca9045f3755a0df5d5a0703cf04eb202eb500a9 | 11,222 | cc | C++ | src/formats/bddbinary.cc | nerdling/SBSAT | 6328c6aa105b75693d06bf0dae4a3b5ca220318b | [
"Unlicense"
] | 4 | 2015-03-08T07:56:29.000Z | 2017-10-12T04:19:27.000Z | src/formats/bddbinary.cc | nerdling/SBSAT | 6328c6aa105b75693d06bf0dae4a3b5ca220318b | [
"Unlicense"
] | null | null | null | src/formats/bddbinary.cc | nerdling/SBSAT | 6328c6aa105b75693d06bf0dae4a3b5ca220318b | [
"Unlicense"
] | null | null | null |
/* =========FOR INTERNAL USE ONLY. NO DISTRIBUTION PLEASE ========== */
/*********************************************************************
Copyright 1999-2007, University of Cincinnati. All rights reserved.
By using this software the USER indicates that he or she has read,
understood and will comply with the following:
--- University of Cincinnati hereby grants USER nonexclusive permission
to use, copy and/or modify this software for internal, noncommercial,
research purposes only. Any distribution, including commercial sale
or license, of this software, copies of the software, its associated
documentation and/or modifications of either is strictly prohibited
without the prior consent of University of Cincinnati. Title to copyright
to this software and its associated documentation shall at all times
remain with University of Cincinnati. Appropriate copyright notice shall
be placed on all software copies, and a complete copy of this notice
shall be included in all copies of the associated documentation.
No right is granted to use in advertising, publicity or otherwise
any trademark, service mark, or the name of University of Cincinnati.
--- This software and any associated documentation is provided "as is"
UNIVERSITY OF CINCINNATI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS
OR IMPLIED, INCLUDING THOSE OF MERCHANTABILITY OR FITNESS FOR A
PARTICULAR PURPOSE, OR THAT USE OF THE SOFTWARE, MODIFICATIONS, OR
ASSOCIATED DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS,
TRADEMARKS OR OTHER INTELLECTUAL PROPERTY RIGHTS OF A THIRD PARTY.
University of Cincinnati shall not be liable under any circumstances for
any direct, indirect, special, incidental, or consequential damages
with respect to any claim by USER or any third party on account of
or arising from the use, or inability to use, this software or its
associated documentation, even if University of Cincinnati has been advised
of the possibility of those damages.
*********************************************************************/
#include "sbsat.h"
#include "sbsat_formats.h"
typedef struct {
void *bddtable_start;
int bddtable_pos;
int num_variables;
int num_functions;
} t_sbsat_env;
void
Binary_to_BDD()
{
FILE *fin = NULL;
t_sbsat_env sbsat_env;
void *_bddtable = NULL;
void *_bddtable_start = NULL;
int _bddtable_len = 0;
void *_equalityvble = NULL;
void *_functions = NULL;
void *_functiontype = NULL;
void *_length = NULL;
void *_variablelist = NULL;
void *_independantVars = NULL;
int _numinp = 0;
int _numout = 0;
char tmp_str[32];
strcpy(tmp_str, "sbsatenv.bin");
cerr << "Reading " << tmp_str << endl;
assert(ite_filesize(tmp_str) == sizeof(t_sbsat_env));
fin = fopen(tmp_str, "rb");
if (!fin) return;
fread(&sbsat_env, sizeof(t_sbsat_env), 1, fin);
fclose(fin);
_numinp = sbsat_env.num_variables;
_numout = sbsat_env.num_functions;
_bddtable_len = sbsat_env.bddtable_pos;
_bddtable_start = sbsat_env.bddtable_start;
strcpy(tmp_str, "bddtable.bin");
cerr << "Reading " << tmp_str << endl;
assert(_bddtable_len == (int)(ite_filesize(tmp_str)/sizeof(BDDNode)));
fin = ite_fopen(tmp_str, "rb");
if (!fin) return;
_bddtable = calloc(_bddtable_len, sizeof(BDDNode));
if (fread(_bddtable, sizeof(BDDNode), _bddtable_len, fin) != (size_t)_bddtable_len)
fprintf(stderr, "fread on bddtable failed\n");
fclose(fin);
strcpy(tmp_str, "functions.bin");
cerr << "Reading " << tmp_str << endl;
assert(_numout == (int)(ite_filesize(tmp_str)/sizeof(BDDNode*)));
fin = ite_fopen(tmp_str, "rb");
if (!fin) return;
_functions = calloc(_numout, sizeof(BDDNode*));
if (fread(_functions, sizeof(BDDNode*), _numout , fin) != (size_t)_numout)
fprintf(stderr, "fread on functions failed\n");
fclose(fin);
strcpy(tmp_str, "functiontype.bin");
cerr << "Reading " << tmp_str << endl;
assert(_numout == (int)(ite_filesize(tmp_str)/sizeof(int)));
fin = ite_fopen(tmp_str, "rb");
if (!fin) return;
_functiontype = calloc(_numout, sizeof(int));
if (fread(_functiontype, sizeof(int), _numout , fin) != (size_t)_numout)
fprintf(stderr, "fread on functiontype failed\n");
fclose(fin);
strcpy(tmp_str, "equalityvble.bin");
cerr << "Reading " << tmp_str << endl;
assert(_numout == (int)(ite_filesize(tmp_str)/sizeof(int)));
fin = ite_fopen(tmp_str, "rb");
if (!fin) return;
_equalityvble = calloc(_numout, sizeof(int));
if (fread(_equalityvble, sizeof(int), _numout , fin) != (size_t)_numout)
fprintf(stderr, "fread on equalityvble failed\n");
fclose(fin);
strcpy(tmp_str, "length.bin");
cerr << "Reading " << tmp_str << endl;
assert(_numout == (int)(ite_filesize(tmp_str)/sizeof(int)));
fin = ite_fopen(tmp_str, "rb");
if (!fin) return;
_length = calloc(_numout, sizeof(int));
if (fread(_length, sizeof(int), _numout , fin) != (size_t)_numout)
fprintf(stderr, "fread on length failed\n");
fclose(fin);
strcpy(tmp_str, "variablelist.bin");
cerr << "Reading " << tmp_str << endl;
assert(_numinp+1 == (int)(ite_filesize(tmp_str)/sizeof(varinfo)));
fin = ite_fopen(tmp_str, "rb");
_variablelist = calloc(_numinp+1, sizeof(varinfo));
if (!fin) return;
if (fread(_variablelist, sizeof(varinfo), _numinp+1 , fin) != (size_t)_numinp+1)
fprintf(stderr, "fread on variablelist failed\n");
fclose(fin);
strcpy(tmp_str, "independantVars.bin");
cerr << "Reading " << tmp_str << endl;
assert(_numinp+1 == (int)(ite_filesize(tmp_str)/sizeof(int)));
fin = ite_fopen(tmp_str, "rb");
_independantVars = calloc(_numinp+1, sizeof(int));
if (!fin) return;
if (fread(_independantVars, sizeof(int), _numinp+1 , fin) != (size_t)_numinp+1)
fprintf(stderr, "fread on independantVars failed\n");
fclose(fin);
reload_bdd_circuit(_numinp, _numout,
_bddtable, _bddtable_len,
_bddtable_start,
_equalityvble, _functions,
_functiontype, _length,
_variablelist, _independantVars);
ite_free(&_bddtable);
ite_free(&_equalityvble);
ite_free(&_functions);
ite_free(&_functiontype);
ite_free(&_length);
ite_free(&_variablelist);
ite_free(&_independantVars);
}
void
reload_bdd_circuit(int _numinp, int _numout,
void *_bddtable, int _bddtable_len,
void *_bddtable_start,
void *_equalityvble,
void *_functions,
void *_functiontype,
void *_length,
void *_variablelist,
void *_independantVars)
{
bdd_init();
d2_printf3("Have %d variables and %d functions .. \n",
_numinp, _numout);
d2_printf1("BDD and Circuit Init..\n");
numinp = _numinp;
numout = _numout;
vars_alloc(numinp+1);
functions_alloc(numout);
nmbrFunctions = numout;
ite_free((void**)&length);
length = (int *)ite_calloc(numout+1, sizeof(int), 9, "length");
if (variablelist) delete [] variablelist;
variablelist = new varinfo[numinp + 1];
int shift=0;
bddtable_load(_bddtable, _bddtable_len, _bddtable_start, &shift);
memmove(functions, _functions, sizeof(BDDNode*)*numout);
memmove(functionType, _functiontype, sizeof(int)*numout);
memmove(equalityVble, _equalityvble, sizeof(int)*numout);
memmove(length, _length, sizeof(int)*numout);
memmove(variablelist, _variablelist, sizeof(varinfo)*(numinp+1));
memmove(independantVars, _independantVars, sizeof(int)*(numinp+1));
/* fix functions */
d2_printf1("Fixing functions .. \n");
int i;
for (i=0;i<numout;i++) {
if (functions[i]) functions[i] = (BDDNode*)((char*)(functions[i])+shift);
}
create_all_syms(_numinp);
}
void
get_bdd_circuit(int *_numinp, int *_numout,
void **_bddtable, int *_bddtable_len, int *_bddtable_msize,
void **_equalityvble,
void **_functions, int *_functions_msize,
void **_functiontype,
void **_length,
void **_variablelist, int *_variablelist_msize,
void **_independantVars)
{
*_numinp = numinp;
*_numout = numout;
bddtable_get(_bddtable, _bddtable_len, _bddtable_msize);
*_equalityvble = equalityVble;
*_functions = functions;
*_functions_msize = sizeof(BDDNode*);
*_functiontype = functionType;
*_length = length;
*_variablelist = variablelist;
*_variablelist_msize = sizeof(varinfo);
*_independantVars = independantVars;
}
void
BDD_to_Binary()
{
void *_bddtable;
int _bddtable_len;
int _bddtable_msize;
cerr << "dump_bdd_table ---------------------------------" << endl;
FILE *fout = NULL;
char tmp_str[32];
strcpy(tmp_str, "bddtable.bin");
fout = ite_fopen(tmp_str, "wb");
if (!fout) return;
bddtable_get(&_bddtable, &_bddtable_len, &_bddtable_msize);
fwrite(_bddtable, _bddtable_msize, _bddtable_len, fout);
fclose(fout);
strcpy(tmp_str, "functions.bin");
fout = ite_fopen(tmp_str, "wb");
if (!fout) return;
fwrite(functions, sizeof(BDDNode*), numout , fout);
fclose(fout);
strcpy(tmp_str, "functiontype.bin");
fout = ite_fopen(tmp_str, "wb");
if (!fout) return;
fwrite(functionType, sizeof(int), numout , fout);
fclose(fout);
strcpy(tmp_str, "equalityvble.bin");
fout = ite_fopen(tmp_str, "wb");
if (!fout) return;
fwrite(equalityVble, sizeof(int), numout , fout);
fclose(fout);
strcpy(tmp_str, "length.bin");
fout = ite_fopen(tmp_str, "wb");
if (!fout) return;
fwrite(length, sizeof(int), numout , fout);
fclose(fout);
strcpy(tmp_str, "variablelist.bin");
fout = ite_fopen(tmp_str, "wb");
if (!fout) return;
fwrite(variablelist, sizeof(varinfo), numinp+1 , fout);
fclose(fout);
strcpy(tmp_str, "independantVars.bin");
fout = ite_fopen(tmp_str, "wb");
if (!fout) return;
fwrite(independantVars, sizeof(int), numinp+1 , fout);
fclose(fout);
t_sbsat_env sbsat_env;
sbsat_env.bddtable_start = _bddtable;
sbsat_env.bddtable_pos = _bddtable_len;
sbsat_env.num_variables = numinp;
sbsat_env.num_functions = numout;
fout = fopen("sbsatenv.bin", "wb");
if (!fout) return;
fwrite(&sbsat_env, sizeof(t_sbsat_env), 1, fout);
fclose(fout);
/*
for (char* i=bddmemory_vsb[0].memory;i<bddmemory_vsb[i].memory+curBDDPos;i++)
cout << "Pool is starting at " << bddmemory_vsb[0].memory << endl;
for (int i=0;i<curBDDPos;i++) {
BDDNode *bdd = (bddmemory_vsb[0].memory + i);
cout << "var: " << bdd->variable << endl;
cout << "then: " << bdd->thenCase << " idx: " << bdd->thenCase-bddmemory_vsb[0].memory << endl;
cout << "else: " << bdd->elseCase << " idx: " << bdd->elseCase-bddmemory_vsb[0].memory << endl;
// have to fix next anyway
// cout << "next: " << next << endl;
// must be 0 (NULL)
//int t_var;
//void *var_ptr;
//infer *inferences;
//SmurfFactoryAddons *addons;
}
*/
}
| 35.178683 | 101 | 0.652825 | nerdling |
6cbcef723672032c7692adc6bfce02f9b30c4a79 | 2,116 | cpp | C++ | Solutions/jumpGame.II.cpp | VenkataAnilKumar/LeetCode | df6d9e4b7172266bef4bc1f771fce3abb2216298 | [
"Fair"
] | 1 | 2020-10-30T07:10:23.000Z | 2020-10-30T07:10:23.000Z | Solutions/jumpGame.II.cpp | VenkataAnilKumar/LeetCode | df6d9e4b7172266bef4bc1f771fce3abb2216298 | [
"Fair"
] | null | null | null | Solutions/jumpGame.II.cpp | VenkataAnilKumar/LeetCode | df6d9e4b7172266bef4bc1f771fce3abb2216298 | [
"Fair"
] | null | null | null | // Source : https://oj.leetcode.com/problems/jump-game-ii/
// Author : Venkata Anil Kumar
/**********************************************************************************
*
* Given an array of non-negative integers, you are initially positioned at the first index of the array.
*
* Each element in the array represents your maximum jump length at that position.
*
* Your goal is to reach the last index in the minimum number of jumps.
*
* For example:
* Given array A = [2,3,1,1,4]
*
* The minimum number of jumps to reach the last index is 2.
* (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
*
*
**********************************************************************************/
#include <iostream>
using namespace std;
//Acutally, using the Greedy algorithm can have the answer
int jump(int A[], int n) {
if (n<=1) return 0;
int steps = 0;
int coverPos = 0;
for (int i=0; i<=coverPos&& i<n; ){
if (A[i]==0) return -1;
if(coverPos < A[i]+i){
coverPos = A[i]+i;
steps++;
}
if (coverPos >= n-1){
return steps;
}
//Greedy: find the next place which can have biggest distance
int nextPos=0;
int maxDistance=0;
for(int j=i+1; j<=coverPos; j++){
if ( A[j]+j > maxDistance ) {
maxDistance = A[j]+j;
nextPos = j;
}
}
i = nextPos;
}
return steps;
}
void printArray(int a[], int n){
cout << "{ ";
for(int i=0; i<n; i++){
if(i) cout << ", ";
cout << a[i];
}
cout << " } ";
}
int main()
{
#define TEST(a) printArray(a, sizeof(a)/sizeof(a[0])); cout<<jump(a, sizeof(a)/sizeof(a[0]))<<endl;
int a1[]={0};
TEST(a1);
int a2[]={1};
TEST(a2);
int a3[]={3,2,1,0,4};
TEST(a3);
int a4[]={2,3,1,1,4};
TEST(a4);
int a5[]={1,2,3};
TEST(a5);
// 0 -> 1 -> 4 -> end
int a6[]={2,3,1,1,4,0,1};
TEST(a6);
// 0 -> 1 -> 3 -> end
int a7[]={2,3,1,2,0,1};
TEST(a7);
return 0;
}
| 23.511111 | 104 | 0.469754 | VenkataAnilKumar |
6cbd9aff77171b28f395acf889c57e13e4cc803c | 18,513 | hpp | C++ | TestFile.hpp | tyson3822/IdentifyCardNumberRecognition | ce7885e0de1529d9360427380119b6df49d4cfb9 | [
"Apache-2.0"
] | null | null | null | TestFile.hpp | tyson3822/IdentifyCardNumberRecognition | ce7885e0de1529d9360427380119b6df49d4cfb9 | [
"Apache-2.0"
] | null | null | null | TestFile.hpp | tyson3822/IdentifyCardNumberRecognition | ce7885e0de1529d9360427380119b6df49d4cfb9 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
#define PRINT_COUNT 0
#define PRINT_RESULT 1
#include "opencv2/core/utility.hpp"
#include "opencv2/core/ocl.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
using namespace cv;
class TestFile
{
private:
char * pch;
ifstream _inputFile;
ofstream _outputFile;
ofstream _resultFile;
vector<string> imgBuffer;
vector<string> testBuffer;
vector<string> outputBuffer;
vector<string> resultBuffer;
public:
//初始化文件檔
void InitTestFile(const char* testPath)
{
char inputFileName[100];
char outputFileName[100];
char resultFileName[100];
strcpy(inputFileName, testPath);
strcat(inputFileName, "inputTest.txt");
strcpy(outputFileName, testPath);
strcat(outputFileName, "outputTest.txt");
strcpy(resultFileName, testPath);
strcat(resultFileName, "testResult.txt");
_inputFile.open(inputFileName, std::ifstream::in);
_outputFile.open(outputFileName , ofstream::out | std::ios::trunc);
_resultFile.open(resultFileName, ofstream::out | std::ios::trunc);
InitTestData();
}
//初始化檔案資料&讀取input檔
void InitTestData()
{
const char *delim = ",";
string buffer;
string img;
string test;
char *charBuffer;
while(_inputFile >> buffer)
{
//string to char*
charBuffer = new char[buffer.length() + 1];
strcpy(charBuffer, buffer.c_str());
//strtok and push to vector
pch = strtok(charBuffer, delim);
img = string(pch); //char* to string
imgBuffer.push_back(img);
//cout << "push " << img << " to img vector" << endl;
//strtok and push to vector
pch = strtok(NULL, delim);
test = string(pch); //char* to string
testBuffer.push_back(test);
//cout << "push " << test << " to test vector" << endl;
outputBuffer.resize(imgBuffer.size());
resultBuffer.resize(imgBuffer.size());
}
}
//取得指定index圖片名稱
string GetImgByIndex(int index)
{
return imgBuffer[index];
}
//顯示vector內容//debug用
void ViewVector(char c)
{
switch (c)
{
case 'i':
{
cout << "-list image name vector-" << endl;
for(int i = 0; i < imgBuffer.size(); i++)
{
cout << "image vector " << i << " = " << imgBuffer[i] << endl;
}
break;
}
case 't':
{
cout << "-list test vector-" << endl;
for(int i = 0; i < testBuffer.size(); i++)
{
cout << "test vector " << i << " = " << testBuffer[i] << endl;
}
break;
}
case 'o':
{
cout << "-list output vector-" << endl;
for(int i = 0; i < outputBuffer.size(); i++)
{
if(outputBuffer[i].size() < 1)continue;
cout << "output vector " << i << " = " << outputBuffer[i] << endl;
}
break;
}
case 'r':
{
cout << "-list result vector-" << endl;
for(int i = 0; i < resultBuffer.size(); i++)
{
if(outputBuffer[i].size() < 1)continue;
cout << "result vector " << i << " = " << resultBuffer[i] << endl;
}
break;
}
default:
cout << "default" << endl;
break;
}
}
//把資料寫進output vector中
void WriteToOutput(string str)
{
outputBuffer.push_back(str);
}
//把資料寫進output vector指定Index中
void WriteToOutputByIndex(string str, int index)
{
outputBuffer[index] = str;
}
//把資料寫進文件檔中
void WriteDownOutput()
{
for(int index = 0; index < outputBuffer.size(); index++)
{
if(outputBuffer[index].size() < 1)continue;
_outputFile << outputBuffer[index] << endl;
}
}
//測試結果output
void MatchResult()
{
ViewVector('o');
//ViewVector('t');
char outputCharArr[100];
char testCharArr[100];
for(int index = 0; index < outputBuffer.size(); index++)
{
//String To Char[] 轉型
strcpy(outputCharArr, outputBuffer[index].c_str());
strcpy(testCharArr, testBuffer[index].c_str());
char ignoreChar[10] = "ignore";
int ignoreResultTest = MatchNChar(outputCharArr, ignoreChar, 6);
if(ignoreResultTest == 1)
{
resultBuffer[index] = "ignore";
continue;
}
if(outputBuffer[index].size() < 1)
{
//resultBuffer.push_back("none");
continue;
}
//比對測資與output是否一樣
int result = MatchChar(outputCharArr, testCharArr);
//將結果丟進resultBuffer中
if(result == 1)resultBuffer[index] = "true";
if(result == -1)resultBuffer[index] = "false";
}
//ViewVector('r');
//所有測試結果寫進文件中
for(int index = 0; index < resultBuffer.size(); index++)
{
if(resultBuffer[index].size() < 1)continue;
_resultFile << resultBuffer[index] << endl;
}
}
//列出成功的test
int ListSuccessTest(int mode)
{
int successCount = 0;
vector<int> successListIndex;
vector<string> successListString;
char trueChar[10];
char resultCharArr[100];
strcpy(trueChar, "true");
for(int i = 0; i < resultBuffer.size(); i++)
{
if(resultBuffer[i].size() < 1)continue;//忽略掉沒有輸出的
strcpy(resultCharArr, resultBuffer[i].c_str());
if(MatchChar(resultCharArr, trueChar) != 1)continue;//忽略掉不是true的
successListIndex.push_back(i);
successListString.push_back(outputBuffer[i]);
successCount++;
}
if(mode == PRINT_COUNT)
{
return successCount;
}
if(mode == PRINT_RESULT)
{
if(successCount > 0)
{
cout << endl << "-list the success test-" << endl;
_resultFile << endl << "-list the success test-" << endl;
for(int i = 0; i < successCount; i++)
{
cout << "the result vector index by " << successListIndex[i] << " = " << successListString[i] << " is success." << endl;
_resultFile << "the result vector index by " << successListIndex[i] << " = " << successListString[i] << " is success." << endl;
}
}
}
return 0;
}
//列出失敗的test
int ListFailureTest(int mode)
{
int failureCount = 0;
vector<int> failureListIndex;
vector<string> failureListString;
char falseChar[10];
char ignoreChar[10];
char resultCharArr[100];
char outputCharArr[100];
strcpy(falseChar, "false");
strcpy(ignoreChar, "ignore");
for(int i = 0; i < resultBuffer.size(); i++)
{
if(resultBuffer[i].size() < 1)continue;//忽略掉沒有輸出的
strcpy(resultCharArr, resultBuffer[i].c_str());
if(MatchChar(resultCharArr, falseChar) != 1)continue;//忽略掉不是false的
strncpy(outputCharArr, resultBuffer[i].c_str(), 6);
outputCharArr[6] = '\0';
if(MatchChar(outputCharArr, ignoreChar) == 1)continue;//忽略掉是ignore的
failureListIndex.push_back(i);
failureListString.push_back(outputBuffer[i]);
failureCount++;
}
if(mode == PRINT_COUNT)
{
return failureCount;
}
if(mode ==PRINT_RESULT)
{
if(failureCount > 0)
{
cout << endl << "-list the failure test-" << endl;
_resultFile << endl << "-list the failure test-" << endl;
for(int i = 0; i < failureCount; i++)
{
cout << "the result vector index by " << failureListIndex[i] << " = " << failureListString[i] << " is failure." << endl;
_resultFile << "the result vector index by " << failureListIndex[i] << " = " << failureListString[i] << " is failure." << endl;
}
}
}
return 0;
}
//列出忽略清單
int ListIgnoreTest(int mode)
{
int ignoreCount = 0;
vector<int> ignoreListIndex;
vector<string> ignoreListString;
char ignoreChar[10];
char outputCharArr[100];
strcpy(ignoreChar, "ignore");
for(int i = 0; i < resultBuffer.size(); i++)
{
if(resultBuffer[i].size() < 1)continue;//忽略掉沒有輸出的
strncpy(outputCharArr, resultBuffer[i].c_str(), 6);
outputCharArr[6] = '\0';
// cout << "outputCharArr = " << outputCharArr << endl;
// cout << "ignoreChar = " << ignoreChar << endl;
if(MatchChar(outputCharArr, ignoreChar) != 1)continue;//忽略掉不是ignore的
ignoreListIndex.push_back(i);
ignoreListString.push_back(resultBuffer[i]);
ignoreCount++;
}
if(mode ==PRINT_COUNT)
{
return ignoreCount;
}
if(mode == PRINT_RESULT)
{
if(ignoreCount > 0)
{
cout << endl << "-list the ignore test-" << endl;
_resultFile << endl << "-list the ignore test-" << endl;
for(int i = 0; i < ignoreCount; i++)
{
cout << "the result vector index by " << ignoreListIndex[i] << " is " << ignoreListString[i] << endl;
_resultFile << "the result vector index by " << ignoreListIndex[i] << " is " << ignoreListString[i] << endl;
}
}
}
return 0;
}
//對比文字(Char) 回傳1一樣,回傳-1不一樣
int MatchChar(char *str1, char *str2)//output,test
{
int result = 1;
int charIndex = 0;
char p1 = str1[charIndex];
char p2 = str2[charIndex];
if(p1 == '\0')return -1;
while(p1 != '\0')
{
//cout << "p1 = " << p1 << endl;
//cout << "p2 = " << p2 << endl;
if(p1 != p2)return -1;
if(p2 == '\0')return -1;
charIndex++;
p1 = str1[charIndex];
p2 = str2[charIndex];
}
return result;
}
//對比文字(Char) 回傳1一樣,回傳-1不一樣,用n個字元
int MatchNChar(char *str1, char *str2, int n)//output,test
{
int result = 1;
int charIndex = 0;
char p1 = str1[charIndex];
char p2 = str2[charIndex];
if(p1 == '\0')return -1;
while(p1 != '\0' && charIndex < n)
{
//cout << "p1 = " << p1 << endl;
//cout << "p2 = " << p2 << endl;
if(p1 != p2)return -1;
if(p2 == '\0')return -1;
charIndex++;
p1 = str1[charIndex];
p2 = str2[charIndex];
}
return result;
}
//關閉文字檔
void Close()
{
_inputFile.close();
_outputFile.close();
_resultFile.close();
}
//輸入檔名,取直到'.'前的字做output
char* FileNameWithoutType(char* input)
{
int charIndex = 0;
char p1 = input[charIndex];
char *output;
while(p1 != '.')
{
output[charIndex] = input[charIndex];
cout << "test charIndex = " << charIndex << endl;
cout << "output = " << output << endl;
charIndex++;
p1 = input[charIndex];
}
return output;
}
//修改字串eg. 1-1000修改成0001-1000
char *FillDigit(char *input)
{
int digitalShift = 0;
int zeroShift = 0;
while(input[digitalShift] != '\0')
digitalShift++;
zeroShift = 4 - digitalShift;
char* output;
output = new char[5];
int index = 0;
for(index = 0; index < zeroShift; index++)
output[index] = '0';
for(int digit = 0; digit < digitalShift; digit++)
{
output[index] = input[digit];
index++;
}
output[4] = '\0';
return output;
}
//儲存圖片
void SaveOutputImage(const char* fileName, char* folderPath, Mat& saveMat)
{
char savePath[100];
strcpy(savePath, folderPath);
strcat(savePath, fileName);
imwrite(savePath, saveMat);
}
//顯示數據
void PrintResultData()
{
int successCount = ListSuccessTest(PRINT_COUNT);
int failureCount = ListFailureTest(PRINT_COUNT);
int ignoreCount = ListIgnoreTest(PRINT_COUNT);
int testCount = failureCount + successCount;
int totalCount = failureCount + successCount + ignoreCount;
double successRate = (double)successCount / (double)(testCount);
double failureRate = (double)failureCount / (double)(testCount);
cout << "--print the result data--" << endl;
cout << "the success count = " << successCount << "." << endl;
cout << "the failure count = " << failureCount << "." << endl;
cout << "the test count = " << testCount << "(success+failure)." << endl;
cout << endl;
cout << "the ignore count = " << ignoreCount << "." << endl;
cout << "the total count = " << totalCount << "(success+failure+ignore)." <<endl;
cout << endl;
cout << "the success rate = " << fixed << setprecision(2) << successRate << "(success/success+failure)." << endl;
cout << "the failure rate = " << fixed << setprecision(2) << failureRate << "(failure/success+failure)." << endl;
}
//寫入數據資料
void WriteResultData()
{
int successCount = ListSuccessTest(PRINT_COUNT);
int failureCount = ListFailureTest(PRINT_COUNT);
int ignoreCount = ListIgnoreTest(PRINT_COUNT);
int testCount = failureCount + successCount;
int totalCount = failureCount + successCount + ignoreCount;
double successRate = (double)successCount / (double)(testCount);
double failureRate = (double)failureCount / (double)(testCount);
_resultFile << endl << "--print the result data--" << endl;
_resultFile << "the success count = " << successCount << "." << endl;
_resultFile << "the failure count = " << failureCount << "." << endl;
_resultFile << "the test count = " << testCount << "(success+failure)." << endl;
_resultFile << endl;
_resultFile << "the ignore count = " << ignoreCount << "." << endl;
_resultFile << "the total count = " << totalCount << "(success+failure+ignore)." <<endl;
_resultFile << endl;
_resultFile << "the success rate = " << fixed << setprecision(2) << successRate << "(success/success+failure)." << endl;
_resultFile << "the failure rate = " << fixed << setprecision(2) << failureRate << "(failure/success+failure)." << endl;
}
//複製檔案
void CopyFile(const char* inputPath, const char* outputPath)
{
ifstream _inputFileCopy;
ofstream _outputFileCopy;
_inputFileCopy.open(inputPath, std::ifstream::in);
_outputFileCopy.open(outputPath , ofstream::out | std::ios::trunc);
_outputFileCopy << _inputFileCopy.rdbuf();
_inputFileCopy.close();
_outputFileCopy.close();
}
//儲存input command line
void SaveCommandLine(char* cammandLineChar)
{
_resultFile << endl<< "--the input command line is--";
_resultFile << endl << cammandLineChar << endl;
}
};
//////////////////////////////////////////////////////
//以下是沒使用但日後可以參考或擴增的功能//
//////////////////////////////////////////////////////
// void CopyFile(const char* inputPath, const char* outputPath)
// {
// ifstream _inputFileCopy;
// ofstream _outputFileCopy;
//
// _inputFileCopy.open(inputPath, std::ifstream::in);
// _outputFileCopy.open(outputPath , ofstream::out | std::ios::trunc);
//
// string buffer;
// char *charBuffer;
// while(_inputFileCopy >> buffer)
// {
// charBuffer = new char[buffer.length() + 1];
// strcpy(charBuffer, buffer.c_str());
//
// _outputFileCopy << charBuffer << endl;
// }
//
// _inputFileCopy.close();
// _outputFileCopy.close();
// }
//輸出路徑整歸
// char* ImageOutputPath(char* basePath, char* folderPath, char* fileName)
// {
// char* output;
// output = new char[50];
// strcpy(output, basePath);
// strcat(output, folderPath);
// strcat(output, fileName);
// return output;
// }
//新增以圖片名稱為資料夾名稱的路徑
// char* AddImageFolderPath(char* oldPath, char* imgName)
// {
// char *newPath;
// newPath = new char[50];
// strcpy(newPath, oldPath);
// strcat(newPath, imgName);
// strcat(newPath, "/");
// return newPath;
// }
//字串比對
// int MatchString(string str1, string str2)//output,test
// {
// int result = 1;
// int charIndex = 0;
// char p1 = str1[charIndex];
// char p2 = str2[charIndex];
// if(p1 == '\0')return -1;
// while(p1 != '\0')
// {
// //cout << "p1 = " << p1 << endl;
// //cout << "p2 = " << p2 << endl;
// if(p1 != p2)return -1;
// if(p2 == '\0')return -1;
// charIndex++;
// p1 = str1[charIndex];
// p2 = str2[charIndex];
// }
// return result;
// }
//取得指定index test名稱
// string GetTestByIndex(int index)
// {
// return testBuffer[index];
// }
//取得圖片vector大小
// int GetImgVectorSize()
// {
// return imgBuffer.size();
// }
//
// //取得test vector大小
// int GetTestVectorSize()
// {
// return testBuffer.size();
// }
| 30.499176 | 147 | 0.50975 | tyson3822 |
6cc325f6c9e6a7d552dc0e5498b82c313c0c38fd | 75 | cpp | C++ | render/RenderTest/Main.cpp | don-reba/colors-visualization | fe3937087be79715307127591a06f38b4647254f | [
"BSD-3-Clause"
] | null | null | null | render/RenderTest/Main.cpp | don-reba/colors-visualization | fe3937087be79715307127591a06f38b4647254f | [
"BSD-3-Clause"
] | null | null | null | render/RenderTest/Main.cpp | don-reba/colors-visualization | fe3937087be79715307127591a06f38b4647254f | [
"BSD-3-Clause"
] | null | null | null | #define BOOST_TEST_MODULE Offline Test
#include <boost/test/unit_test.hpp> | 37.5 | 39 | 0.826667 | don-reba |
6cc4ecc5555f7d2798d120ec5260f5544e4061b6 | 1,967 | cpp | C++ | salmap_rv/src/exec_graph.cpp | flyingfalling/salmap_rv | 61827a42f456afcd9c930646de33bc3f9533e3e2 | [
"MIT"
] | 1 | 2022-02-17T03:05:40.000Z | 2022-02-17T03:05:40.000Z | salmap_rv/src/exec_graph.cpp | flyingfalling/salmap_rv | 61827a42f456afcd9c930646de33bc3f9533e3e2 | [
"MIT"
] | null | null | null | salmap_rv/src/exec_graph.cpp | flyingfalling/salmap_rv | 61827a42f456afcd9c930646de33bc3f9533e3e2 | [
"MIT"
] | null | null | null | #include <salmap_rv/include/exec_graph.hpp>
#include <salmap_rv/include/featfilterimpl.hpp>
using namespace salmap_rv;
void salmap_rv::exec_graph::fill_atomic_filters()
{
atomic_filters = deps.atomic_filters();
}
void salmap_rv::exec_graph::clear()
{
deps.clear();
atomic_filters.clear();
avail_filters.clear();
curr_processing.clear();
}
const int64_t salmap_rv::exec_graph::get_max_tdelta() const
{
return deps.get_max_tdelta();
}
salmap_rv::exec_graph::exec_graph()
{
}
void salmap_rv::exec_graph::reset_avail_filters()
{
avail_filters = atomic_filters;
}
void salmap_rv::exec_graph::init( std::map<std::string, FeatFilter>& mymap )
{
deps.init( mymap );
fill_atomic_filters();
reset();
}
void salmap_rv::exec_graph::reset_updated()
{
deps.reset_updated();
}
void salmap_rv::exec_graph::reset_empty()
{
reset();
avail_filters.clear();
}
void salmap_rv::exec_graph::reset()
{
curr_processing.clear();
reset_avail_filters();
reset_updated();
}
size_t salmap_rv::exec_graph::currproc()
{
return curr_processing.size();
}
std::vector<std::string> salmap_rv::exec_graph::get_curr_proc()
{
std::vector<std::string> ret;
for( auto& a : curr_processing )
{
ret.push_back(a->name.c_str());
}
return ret;
}
void salmap_rv::exec_graph::mark_finished( FeatFilterImpl* iter )
{
deps.mark_updated( iter );
curr_processing.remove( iter );
std::list<FeatFilterImpl*> nexts = deps.get_nexts( iter );
avail_filters.splice( avail_filters.end(), nexts );
}
bool salmap_rv::exec_graph::nextfilter( FeatFilterImpl*& iter )
{
if( avail_filters.size() > 0 )
{
iter = avail_filters.front();
avail_filters.pop_front();
curr_processing.push_back( iter );
return true;
}
else
{
return false;
}
}
bool salmap_rv::exec_graph::done()
{
if( avail_filters.empty() && curr_processing.empty() )
{
return true;
}
return false;
}
| 17.5625 | 77 | 0.683274 | flyingfalling |
6cc8ff9a7f7b11f987c8e7bcaf228de007838138 | 1,188 | cpp | C++ | min_steps.cpp | Nik404/Dynamic-Prograamming | e6ba4901107332189d78fb8c426ee6f82bfc99c8 | [
"MIT"
] | 1 | 2020-09-11T05:22:37.000Z | 2020-09-11T05:22:37.000Z | min_steps.cpp | Nik404/Dynamic-Prograamming | e6ba4901107332189d78fb8c426ee6f82bfc99c8 | [
"MIT"
] | null | null | null | min_steps.cpp | Nik404/Dynamic-Prograamming | e6ba4901107332189d78fb8c426ee6f82bfc99c8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <climits>
using namespace std;
int minSteps2(int n,int *arr){
if(n == 1){
return 0;
}
if(arr[n] > 0){
return arr[n];
}
int ans = 1 + minSteps2(n-1,arr);
if(n % 2 == 0){
ans = min(ans,1 + minSteps2(n/2,arr));
}
if(n %3 == 0){
ans = min(ans,1 + minSteps2(n/3,arr));
}
arr[n] = ans;
return ans;
}
int minSteps3(int n){
int *arr = new int[n+1];
arr[1] = 0;
for(int i=2;i<=n;i++){
int ans = 1 + arr[i-1];
if(i%2 == 0){
ans = min(ans,1 + arr[i/2]);
}
if(i%3 == 0){
ans = min(ans,1 + arr[i/3]);
}
arr[i] = ans;
}
int output = arr[n];
delete [] arr;
return output;
}
int minSteps(int n){
if(n == 1){
return 0;
}
int ans = 1 + minSteps(n-1);
if(n % 2 == 0){
ans = min(ans,1 + minSteps(n/2));
}
if(n %3 == 0){
ans = min(ans,1 + minSteps(n/3));
}
return ans;
}
int main(){
int n;
cin >> n;
int *arr = new int[n+1];
for(int i =0;i<=n;i++){
arr[i] = 0;
}
cout<<minSteps(n)<<endl;//not optimized
cout<<minSteps2(n,arr)<<endl;//optimized with extra work i.e. top down
cout<<minSteps3(n)<<endl;//optimized with bottom up
return 0;
} | 17.470588 | 73 | 0.508418 | Nik404 |
6cdd0700835acce3b9f0a7eecc334691a0caa36b | 1,418 | cpp | C++ | master/master_thread.cpp | RickAi/csci5570 | 2814c0a6bf608c73bf81d015d13e63443470e457 | [
"Apache-2.0"
] | 7 | 2019-04-09T16:25:49.000Z | 2021-12-07T10:29:52.000Z | master/master_thread.cpp | RickAi/csci5570 | 2814c0a6bf608c73bf81d015d13e63443470e457 | [
"Apache-2.0"
] | null | null | null | master/master_thread.cpp | RickAi/csci5570 | 2814c0a6bf608c73bf81d015d13e63443470e457 | [
"Apache-2.0"
] | 4 | 2019-08-07T07:43:27.000Z | 2021-05-21T07:54:14.000Z |
//
// Created by aiyongbiao on 2018/11/10.
//
#include <base/node.hpp>
#include "master_thread.hpp"
#include "glog/logging.h"
namespace minips {
void MasterThread::Main() {
Init();
while (serving_) {
Message msg;
work_queue_.WaitAndPop(&msg);
if (msg.meta.flag == Flag::kQuitHeartBeat) {
quit_count_++;
// LOG(INFO) << "MasterThread heartbeat quit serving on process:" << quit_count_;
if (quit_count_ >= heartbeats_.size()) {
serving_ = false;
LOG(INFO) << "[Master] master process quit.";
exit(0);
// return;
}
}
if (msg.meta.flag == Flag::kHeartBeat) {
heartbeats_[msg.meta.sender] = time(NULL);
if (msg.meta.sender == recovering_node_id_) {
LOG(INFO) << "[Master] send rollback message to other nodes.";
SetRecoveringNodeId(-1);
RollBack(msg.meta.sender);
}
LOG(INFO) << "[Master] heartbeat updated on node:" << msg.meta.sender;
}
if (msg.meta.flag == Flag::kScale) {
LOG(INFO) << "[Master] send rollback message to other nodes for scale.";
ScaleRollBack(msg.meta.sender);
}
}
}
} | 30.170213 | 96 | 0.483075 | RickAi |
6cdd5dc76cd908597ac166ac042fbb769a0e0e65 | 3,338 | cpp | C++ | debugger/cinder/blocks/PretzelGui/src/modules/PretzelTextField.cpp | VincentPT/xscript | cea6ee9e8c5af87af75188695ffa89080dce49b8 | [
"MIT"
] | 2 | 2019-03-05T09:57:54.000Z | 2022-02-14T12:42:01.000Z | src/cinder/blocks/PretzelGui/src/modules/PretzelTextField.cpp | VincentPT/buzz | edaaf4b60e8ef94eda63471ddfb1afd285b6ab38 | [
"MIT"
] | null | null | null | src/cinder/blocks/PretzelGui/src/modules/PretzelTextField.cpp | VincentPT/buzz | edaaf4b60e8ef94eda63471ddfb1afd285b6ab38 | [
"MIT"
] | 1 | 2019-12-24T22:24:01.000Z | 2019-12-24T22:24:01.000Z | #include "PretzelTextField.h"
#include "cinder/app/App.h"
#include "cinder/app/Window.h"
#include "cinder/Utilities.h"
//#include "NSCursor.h"
using namespace ci;
using namespace ci::app;
using namespace std;
namespace pretzel{
PretzelTextField::PretzelTextField(BasePretzel *parent, std::string labelText, std::string *variable, bool editable) : BasePretzel() {
mBounds.set(0, 0, 200, 26);
bEditable = editable;
bHover = false;
bEditing = false;
mLabelText = labelText;
mVariable = variable;
mLabelSize = mGlobal->guiFont->measureString(mLabelText);
mInputSize = mGlobal->guiFont->measureString(*variable);
type = WidgetType::TEXTFIELD;
if(bEditable) mGlobal->addSaveParam(labelText, variable);
parent->registerPretzel(this);
}
void PretzelTextField::updateBounds(const ci::vec2 &offset, const ci::Rectf &parentBounds) {
BasePretzel::updateBounds(offset, parentBounds);
// this could be cleaner
mTextFieldBounds = Rectf(mLabelSize.x + 25, mBounds.y1 + 5, mBounds.x2 - 10, mBounds.y2 - 5);
}
void PretzelTextField::mouseDown(const ci::vec2 &pos){
if (bEditable && mTextFieldBounds.contains(pos - mOffset)){
bEditing = true;
}
else{
bEditing = false;
}
}
void PretzelTextField::mouseMoved(const ci::vec2 &pos){
if (bEditable && mTextFieldBounds.contains(pos - mOffset)){
bHover = true;
mGlobal->setCursor( CursorType::IBEAM );
}
else{
if( bHover ){
mGlobal->setCursor( CursorType::ARROW );
}
bHover = false;
}
}
// Mayus and character combinations not working yet
void PretzelTextField::keyDown(const char &key, const int &keyCode){
if (bEditing){
if (keyCode == KeyEvent::KEY_ESCAPE || keyCode == KeyEvent::KEY_RETURN){
bEditing = false;
}
else if (keyCode == KeyEvent::KEY_BACKSPACE && !mVariable->empty()){
mVariable->pop_back();
}
else if (keyCode > 31 && keyCode < 127){ //printable characters
mVariable->push_back(key);
}
mInputSize = mGlobal->guiFont->measureString(*mVariable);
}
}
void PretzelTextField::draw(){
gl::pushMatrices(); {
gl::translate(mOffset);
if(bEditing){
gl::color(mGlobal->P_HOVER_COLOR);
}
else if (bHover){
gl::color(mGlobal->P_TAB_COLOR);
}
else{
gl::color(mGlobal->P_BG_COLOR);
}
PWindow()->drawSolidRect(mTextFieldBounds);
gl::color(mGlobal->P_HIGHLIGHT_COLOR);
PWindow()->drawLine(mTextFieldBounds.getLowerLeft() + vec2(0, 1), mTextFieldBounds.getLowerRight() + vec2(0, 1));
gl::color(mGlobal->P_OUTLINE_COLOR);
PWindow()->drawStrokedRect(mTextFieldBounds);
mGlobal->renderText(mLabelText, mBounds.getUpperLeft() + vec2(12, 5));
mGlobal->renderText(*mVariable, mTextFieldBounds.getUpperLeft() + vec2(2, 0));
// cursor line
if (bEditing && (app::getElapsedSeconds() - (long)app::getElapsedSeconds()) < 0.5 ){
float x = mTextFieldBounds.getUpperLeft().x + mInputSize.x + 4;
gl::color(mGlobal->P_TEXT_COLOR);
PWindow()->drawLine(vec2(x, mTextFieldBounds.y1 + 2), vec2(x, mTextFieldBounds.y2 - 2));
}
}gl::popMatrices();
}
}
| 31.490566 | 135 | 0.632415 | VincentPT |
6ce8248920b7bd8fbccc61129ee19c620424980a | 27,192 | cxx | C++ | dune/xt/data/spherical_quadratures/octant_quadrature/data/order_12.cxx | dune-community/dune-xt-data | 32593bbcd52ed69b0a11963400a9173740089a75 | [
"BSD-2-Clause"
] | 1 | 2020-02-08T04:09:11.000Z | 2020-02-08T04:09:11.000Z | dune/xt/data/spherical_quadratures/octant_quadrature/data/order_12.cxx | dune-community/dune-xt-data | 32593bbcd52ed69b0a11963400a9173740089a75 | [
"BSD-2-Clause"
] | 40 | 2018-08-26T08:34:34.000Z | 2021-09-28T13:01:55.000Z | dune/xt/data/spherical_quadratures/octant_quadrature/data/order_12.cxx | dune-community/dune-xt-data | 32593bbcd52ed69b0a11963400a9173740089a75 | [
"BSD-2-Clause"
] | 1 | 2020-02-08T04:10:14.000Z | 2020-02-08T04:10:14.000Z | // This file is part of the dune-xt-data project:
// https://github.com/dune-community/dune-xt-data
// Copyright 2009-2018 dune-xt-data developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// René Fritze (2018)
// Tobias Leibner (2018 - 2019)
#include "../octant_quadrature_data.hh"
namespace Dune::XT::Data {
template <>
std::vector<std::vector<std::vector<double>>> OctantQuadratureData<12>::get()
{
return {
{{0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525},
{0.013008, 0.013008, 0.013008, 0.013008, 0.013008, 0.013008, 0.013008, 0.013008, 0.067445, 0.067445, 0.067445,
0.067445, 0.067445, 0.067445, 0.067445, 0.067445, 0.16116, 0.16116, 0.16116, 0.16116, 0.16116, 0.16116,
0.16116, 0.16116, 0.28781, 0.28781, 0.28781, 0.28781, 0.28781, 0.28781, 0.28781, 0.28781, 0.43963,
0.43963, 0.43963, 0.43963, 0.43963, 0.43963, 0.43963, 0.43963, 0.60831, 0.60831, 0.60831, 0.60831,
0.60831, 0.60831, 0.60831, 0.60831, 0.7854, 0.7854, 0.7854, 0.7854, 0.7854, 0.7854, 0.7854,
0.7854, 0.96249, 0.96249, 0.96249, 0.96249, 0.96249, 0.96249, 0.96249, 0.96249, 1.1312, 1.1312,
1.1312, 1.1312, 1.1312, 1.1312, 1.1312, 1.1312, 1.283, 1.283, 1.283, 1.283, 1.283,
1.283, 1.283, 1.283, 1.4096, 1.4096, 1.4096, 1.4096, 1.4096, 1.4096, 1.4096, 1.4096,
1.5034, 1.5034, 1.5034, 1.5034, 1.5034, 1.5034, 1.5034, 1.5034, 1.5578, 1.5578, 1.5578,
1.5578, 1.5578, 1.5578, 1.5578, 1.5578},
{3.593e-05, 0.00040765, 0.0013799, 0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262, 8.0995e-05,
0.00091893, 0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 0.00012035, 0.0013654,
0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 0.0001519, 0.0017234, 0.0058336,
0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00017466, 0.0019816, 0.0067075, 0.014239,
0.023359, 0.03234, 0.039464, 0.04339, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185,
0.034868, 0.042548, 0.046781, 0.00019284, 0.0021879, 0.007406, 0.015722, 0.025792, 0.035708,
0.043574, 0.047908, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185, 0.034868, 0.042548,
0.046781, 0.00017466, 0.0019816, 0.0067075, 0.014239, 0.023359, 0.03234, 0.039464, 0.04339,
0.0001519, 0.0017234, 0.0058336, 0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00012035,
0.0013654, 0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 8.0995e-05, 0.00091893,
0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 3.593e-05, 0.00040765, 0.0013799,
0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262}},
{{0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525},
{1.5838, 1.5838, 1.5838, 1.5838, 1.5838, 1.5838, 1.5838, 1.5838, 1.6382, 1.6382, 1.6382, 1.6382, 1.6382,
1.6382, 1.6382, 1.6382, 1.732, 1.732, 1.732, 1.732, 1.732, 1.732, 1.732, 1.732, 1.8586, 1.8586,
1.8586, 1.8586, 1.8586, 1.8586, 1.8586, 1.8586, 2.0104, 2.0104, 2.0104, 2.0104, 2.0104, 2.0104, 2.0104,
2.0104, 2.1791, 2.1791, 2.1791, 2.1791, 2.1791, 2.1791, 2.1791, 2.1791, 2.3562, 2.3562, 2.3562, 2.3562,
2.3562, 2.3562, 2.3562, 2.3562, 2.5333, 2.5333, 2.5333, 2.5333, 2.5333, 2.5333, 2.5333, 2.5333, 2.702,
2.702, 2.702, 2.702, 2.702, 2.702, 2.702, 2.702, 2.8538, 2.8538, 2.8538, 2.8538, 2.8538, 2.8538,
2.8538, 2.8538, 2.9804, 2.9804, 2.9804, 2.9804, 2.9804, 2.9804, 2.9804, 2.9804, 3.0741, 3.0741, 3.0741,
3.0741, 3.0741, 3.0741, 3.0741, 3.0741, 3.1286, 3.1286, 3.1286, 3.1286, 3.1286, 3.1286, 3.1286, 3.1286},
{3.593e-05, 0.00040765, 0.0013799, 0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262, 8.0995e-05,
0.00091893, 0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 0.00012035, 0.0013654,
0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 0.0001519, 0.0017234, 0.0058336,
0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00017466, 0.0019816, 0.0067075, 0.014239,
0.023359, 0.03234, 0.039464, 0.04339, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185,
0.034868, 0.042548, 0.046781, 0.00019284, 0.0021879, 0.007406, 0.015722, 0.025792, 0.035708,
0.043574, 0.047908, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185, 0.034868, 0.042548,
0.046781, 0.00017466, 0.0019816, 0.0067075, 0.014239, 0.023359, 0.03234, 0.039464, 0.04339,
0.0001519, 0.0017234, 0.0058336, 0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00012035,
0.0013654, 0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 8.0995e-05, 0.00091893,
0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 3.593e-05, 0.00040765, 0.0013799,
0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262}},
{{0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525},
{3.1546, 3.1546, 3.1546, 3.1546, 3.1546, 3.1546, 3.1546, 3.1546, 3.209, 3.209, 3.209, 3.209, 3.209,
3.209, 3.209, 3.209, 3.3028, 3.3028, 3.3028, 3.3028, 3.3028, 3.3028, 3.3028, 3.3028, 3.4294, 3.4294,
3.4294, 3.4294, 3.4294, 3.4294, 3.4294, 3.4294, 3.5812, 3.5812, 3.5812, 3.5812, 3.5812, 3.5812, 3.5812,
3.5812, 3.7499, 3.7499, 3.7499, 3.7499, 3.7499, 3.7499, 3.7499, 3.7499, 3.927, 3.927, 3.927, 3.927,
3.927, 3.927, 3.927, 3.927, 4.1041, 4.1041, 4.1041, 4.1041, 4.1041, 4.1041, 4.1041, 4.1041, 4.2728,
4.2728, 4.2728, 4.2728, 4.2728, 4.2728, 4.2728, 4.2728, 4.4246, 4.4246, 4.4246, 4.4246, 4.4246, 4.4246,
4.4246, 4.4246, 4.5512, 4.5512, 4.5512, 4.5512, 4.5512, 4.5512, 4.5512, 4.5512, 4.6449, 4.6449, 4.6449,
4.6449, 4.6449, 4.6449, 4.6449, 4.6449, 4.6994, 4.6994, 4.6994, 4.6994, 4.6994, 4.6994, 4.6994, 4.6994},
{3.593e-05, 0.00040765, 0.0013799, 0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262, 8.0995e-05,
0.00091893, 0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 0.00012035, 0.0013654,
0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 0.0001519, 0.0017234, 0.0058336,
0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00017466, 0.0019816, 0.0067075, 0.014239,
0.023359, 0.03234, 0.039464, 0.04339, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185,
0.034868, 0.042548, 0.046781, 0.00019284, 0.0021879, 0.007406, 0.015722, 0.025792, 0.035708,
0.043574, 0.047908, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185, 0.034868, 0.042548,
0.046781, 0.00017466, 0.0019816, 0.0067075, 0.014239, 0.023359, 0.03234, 0.039464, 0.04339,
0.0001519, 0.0017234, 0.0058336, 0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00012035,
0.0013654, 0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 8.0995e-05, 0.00091893,
0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 3.593e-05, 0.00040765, 0.0013799,
0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262}},
{{0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557,
0.78967, 0.61686, 0.39342, 0.13525, 0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525,
0.99979, 0.99442, 0.96915, 0.90557, 0.78967, 0.61686, 0.39342, 0.13525},
{4.7254, 4.7254, 4.7254, 4.7254, 4.7254, 4.7254, 4.7254, 4.7254, 4.7798, 4.7798, 4.7798, 4.7798, 4.7798,
4.7798, 4.7798, 4.7798, 4.8736, 4.8736, 4.8736, 4.8736, 4.8736, 4.8736, 4.8736, 4.8736, 5.0002, 5.0002,
5.0002, 5.0002, 5.0002, 5.0002, 5.0002, 5.0002, 5.152, 5.152, 5.152, 5.152, 5.152, 5.152, 5.152,
5.152, 5.3207, 5.3207, 5.3207, 5.3207, 5.3207, 5.3207, 5.3207, 5.3207, 5.4978, 5.4978, 5.4978, 5.4978,
5.4978, 5.4978, 5.4978, 5.4978, 5.6749, 5.6749, 5.6749, 5.6749, 5.6749, 5.6749, 5.6749, 5.6749, 5.8436,
5.8436, 5.8436, 5.8436, 5.8436, 5.8436, 5.8436, 5.8436, 5.9954, 5.9954, 5.9954, 5.9954, 5.9954, 5.9954,
5.9954, 5.9954, 6.122, 6.122, 6.122, 6.122, 6.122, 6.122, 6.122, 6.122, 6.2157, 6.2157, 6.2157,
6.2157, 6.2157, 6.2157, 6.2157, 6.2157, 6.2702, 6.2702, 6.2702, 6.2702, 6.2702, 6.2702, 6.2702, 6.2702},
{3.593e-05, 0.00040765, 0.0013799, 0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262, 8.0995e-05,
0.00091893, 0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 0.00012035, 0.0013654,
0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 0.0001519, 0.0017234, 0.0058336,
0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00017466, 0.0019816, 0.0067075, 0.014239,
0.023359, 0.03234, 0.039464, 0.04339, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185,
0.034868, 0.042548, 0.046781, 0.00019284, 0.0021879, 0.007406, 0.015722, 0.025792, 0.035708,
0.043574, 0.047908, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185, 0.034868, 0.042548,
0.046781, 0.00017466, 0.0019816, 0.0067075, 0.014239, 0.023359, 0.03234, 0.039464, 0.04339,
0.0001519, 0.0017234, 0.0058336, 0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00012035,
0.0013654, 0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 8.0995e-05, 0.00091893,
0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 3.593e-05, 0.00040765, 0.0013799,
0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262}},
{{-0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915,
-0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686,
-0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979,
-0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557,
-0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342,
-0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442,
-0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967,
-0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525,
-0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915,
-0.90557, -0.78967, -0.61686, -0.39342, -0.13525},
{0.013008, 0.013008, 0.013008, 0.013008, 0.013008, 0.013008, 0.013008, 0.013008, 0.067445, 0.067445, 0.067445,
0.067445, 0.067445, 0.067445, 0.067445, 0.067445, 0.16116, 0.16116, 0.16116, 0.16116, 0.16116, 0.16116,
0.16116, 0.16116, 0.28781, 0.28781, 0.28781, 0.28781, 0.28781, 0.28781, 0.28781, 0.28781, 0.43963,
0.43963, 0.43963, 0.43963, 0.43963, 0.43963, 0.43963, 0.43963, 0.60831, 0.60831, 0.60831, 0.60831,
0.60831, 0.60831, 0.60831, 0.60831, 0.7854, 0.7854, 0.7854, 0.7854, 0.7854, 0.7854, 0.7854,
0.7854, 0.96249, 0.96249, 0.96249, 0.96249, 0.96249, 0.96249, 0.96249, 0.96249, 1.1312, 1.1312,
1.1312, 1.1312, 1.1312, 1.1312, 1.1312, 1.1312, 1.283, 1.283, 1.283, 1.283, 1.283,
1.283, 1.283, 1.283, 1.4096, 1.4096, 1.4096, 1.4096, 1.4096, 1.4096, 1.4096, 1.4096,
1.5034, 1.5034, 1.5034, 1.5034, 1.5034, 1.5034, 1.5034, 1.5034, 1.5578, 1.5578, 1.5578,
1.5578, 1.5578, 1.5578, 1.5578, 1.5578},
{3.593e-05, 0.00040765, 0.0013799, 0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262, 8.0995e-05,
0.00091893, 0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 0.00012035, 0.0013654,
0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 0.0001519, 0.0017234, 0.0058336,
0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00017466, 0.0019816, 0.0067075, 0.014239,
0.023359, 0.03234, 0.039464, 0.04339, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185,
0.034868, 0.042548, 0.046781, 0.00019284, 0.0021879, 0.007406, 0.015722, 0.025792, 0.035708,
0.043574, 0.047908, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185, 0.034868, 0.042548,
0.046781, 0.00017466, 0.0019816, 0.0067075, 0.014239, 0.023359, 0.03234, 0.039464, 0.04339,
0.0001519, 0.0017234, 0.0058336, 0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00012035,
0.0013654, 0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 8.0995e-05, 0.00091893,
0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 3.593e-05, 0.00040765, 0.0013799,
0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262}},
{{-0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915,
-0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686,
-0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979,
-0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557,
-0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342,
-0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442,
-0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967,
-0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525,
-0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915,
-0.90557, -0.78967, -0.61686, -0.39342, -0.13525},
{1.5838, 1.5838, 1.5838, 1.5838, 1.5838, 1.5838, 1.5838, 1.5838, 1.6382, 1.6382, 1.6382, 1.6382, 1.6382,
1.6382, 1.6382, 1.6382, 1.732, 1.732, 1.732, 1.732, 1.732, 1.732, 1.732, 1.732, 1.8586, 1.8586,
1.8586, 1.8586, 1.8586, 1.8586, 1.8586, 1.8586, 2.0104, 2.0104, 2.0104, 2.0104, 2.0104, 2.0104, 2.0104,
2.0104, 2.1791, 2.1791, 2.1791, 2.1791, 2.1791, 2.1791, 2.1791, 2.1791, 2.3562, 2.3562, 2.3562, 2.3562,
2.3562, 2.3562, 2.3562, 2.3562, 2.5333, 2.5333, 2.5333, 2.5333, 2.5333, 2.5333, 2.5333, 2.5333, 2.702,
2.702, 2.702, 2.702, 2.702, 2.702, 2.702, 2.702, 2.8538, 2.8538, 2.8538, 2.8538, 2.8538, 2.8538,
2.8538, 2.8538, 2.9804, 2.9804, 2.9804, 2.9804, 2.9804, 2.9804, 2.9804, 2.9804, 3.0741, 3.0741, 3.0741,
3.0741, 3.0741, 3.0741, 3.0741, 3.0741, 3.1286, 3.1286, 3.1286, 3.1286, 3.1286, 3.1286, 3.1286, 3.1286},
{3.593e-05, 0.00040765, 0.0013799, 0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262, 8.0995e-05,
0.00091893, 0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 0.00012035, 0.0013654,
0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 0.0001519, 0.0017234, 0.0058336,
0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00017466, 0.0019816, 0.0067075, 0.014239,
0.023359, 0.03234, 0.039464, 0.04339, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185,
0.034868, 0.042548, 0.046781, 0.00019284, 0.0021879, 0.007406, 0.015722, 0.025792, 0.035708,
0.043574, 0.047908, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185, 0.034868, 0.042548,
0.046781, 0.00017466, 0.0019816, 0.0067075, 0.014239, 0.023359, 0.03234, 0.039464, 0.04339,
0.0001519, 0.0017234, 0.0058336, 0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00012035,
0.0013654, 0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 8.0995e-05, 0.00091893,
0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 3.593e-05, 0.00040765, 0.0013799,
0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262}},
{{-0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915,
-0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686,
-0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979,
-0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557,
-0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342,
-0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442,
-0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967,
-0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525,
-0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915,
-0.90557, -0.78967, -0.61686, -0.39342, -0.13525},
{3.1546, 3.1546, 3.1546, 3.1546, 3.1546, 3.1546, 3.1546, 3.1546, 3.209, 3.209, 3.209, 3.209, 3.209,
3.209, 3.209, 3.209, 3.3028, 3.3028, 3.3028, 3.3028, 3.3028, 3.3028, 3.3028, 3.3028, 3.4294, 3.4294,
3.4294, 3.4294, 3.4294, 3.4294, 3.4294, 3.4294, 3.5812, 3.5812, 3.5812, 3.5812, 3.5812, 3.5812, 3.5812,
3.5812, 3.7499, 3.7499, 3.7499, 3.7499, 3.7499, 3.7499, 3.7499, 3.7499, 3.927, 3.927, 3.927, 3.927,
3.927, 3.927, 3.927, 3.927, 4.1041, 4.1041, 4.1041, 4.1041, 4.1041, 4.1041, 4.1041, 4.1041, 4.2728,
4.2728, 4.2728, 4.2728, 4.2728, 4.2728, 4.2728, 4.2728, 4.4246, 4.4246, 4.4246, 4.4246, 4.4246, 4.4246,
4.4246, 4.4246, 4.5512, 4.5512, 4.5512, 4.5512, 4.5512, 4.5512, 4.5512, 4.5512, 4.6449, 4.6449, 4.6449,
4.6449, 4.6449, 4.6449, 4.6449, 4.6449, 4.6994, 4.6994, 4.6994, 4.6994, 4.6994, 4.6994, 4.6994, 4.6994},
{3.593e-05, 0.00040765, 0.0013799, 0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262, 8.0995e-05,
0.00091893, 0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 0.00012035, 0.0013654,
0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 0.0001519, 0.0017234, 0.0058336,
0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00017466, 0.0019816, 0.0067075, 0.014239,
0.023359, 0.03234, 0.039464, 0.04339, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185,
0.034868, 0.042548, 0.046781, 0.00019284, 0.0021879, 0.007406, 0.015722, 0.025792, 0.035708,
0.043574, 0.047908, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185, 0.034868, 0.042548,
0.046781, 0.00017466, 0.0019816, 0.0067075, 0.014239, 0.023359, 0.03234, 0.039464, 0.04339,
0.0001519, 0.0017234, 0.0058336, 0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00012035,
0.0013654, 0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 8.0995e-05, 0.00091893,
0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 3.593e-05, 0.00040765, 0.0013799,
0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262}},
{{-0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915,
-0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686,
-0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979,
-0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557,
-0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342,
-0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442,
-0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967,
-0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525,
-0.99979, -0.99442, -0.96915, -0.90557, -0.78967, -0.61686, -0.39342, -0.13525, -0.99979, -0.99442, -0.96915,
-0.90557, -0.78967, -0.61686, -0.39342, -0.13525},
{4.7254, 4.7254, 4.7254, 4.7254, 4.7254, 4.7254, 4.7254, 4.7254, 4.7798, 4.7798, 4.7798, 4.7798, 4.7798,
4.7798, 4.7798, 4.7798, 4.8736, 4.8736, 4.8736, 4.8736, 4.8736, 4.8736, 4.8736, 4.8736, 5.0002, 5.0002,
5.0002, 5.0002, 5.0002, 5.0002, 5.0002, 5.0002, 5.152, 5.152, 5.152, 5.152, 5.152, 5.152, 5.152,
5.152, 5.3207, 5.3207, 5.3207, 5.3207, 5.3207, 5.3207, 5.3207, 5.3207, 5.4978, 5.4978, 5.4978, 5.4978,
5.4978, 5.4978, 5.4978, 5.4978, 5.6749, 5.6749, 5.6749, 5.6749, 5.6749, 5.6749, 5.6749, 5.6749, 5.8436,
5.8436, 5.8436, 5.8436, 5.8436, 5.8436, 5.8436, 5.8436, 5.9954, 5.9954, 5.9954, 5.9954, 5.9954, 5.9954,
5.9954, 5.9954, 6.122, 6.122, 6.122, 6.122, 6.122, 6.122, 6.122, 6.122, 6.2157, 6.2157, 6.2157,
6.2157, 6.2157, 6.2157, 6.2157, 6.2157, 6.2702, 6.2702, 6.2702, 6.2702, 6.2702, 6.2702, 6.2702, 6.2702},
{3.593e-05, 0.00040765, 0.0013799, 0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262, 8.0995e-05,
0.00091893, 0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 0.00012035, 0.0013654,
0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 0.0001519, 0.0017234, 0.0058336,
0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00017466, 0.0019816, 0.0067075, 0.014239,
0.023359, 0.03234, 0.039464, 0.04339, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185,
0.034868, 0.042548, 0.046781, 0.00019284, 0.0021879, 0.007406, 0.015722, 0.025792, 0.035708,
0.043574, 0.047908, 0.0001883, 0.0021364, 0.0072316, 0.015352, 0.025185, 0.034868, 0.042548,
0.046781, 0.00017466, 0.0019816, 0.0067075, 0.014239, 0.023359, 0.03234, 0.039464, 0.04339,
0.0001519, 0.0017234, 0.0058336, 0.012384, 0.020316, 0.028127, 0.034322, 0.037737, 0.00012035,
0.0013654, 0.0046218, 0.0098116, 0.016096, 0.022284, 0.027193, 0.029898, 8.0995e-05, 0.00091893,
0.0031105, 0.0066033, 0.010833, 0.014997, 0.018301, 0.020122, 3.593e-05, 0.00040765, 0.0013799,
0.0029293, 0.0048055, 0.006653, 0.0081185, 0.0089262}}};
}
} // namespace Dune::XT::Data
| 103 | 117 | 0.585613 | dune-community |
6cf8cefd2d510fe6e1c474dec747ec11b2703926 | 2,006 | cpp | C++ | DeepSpace/src/main/cpp/commands/LineTrackerFollowLine.cpp | NorthernForce/DeepSpace | b8446f0fb732e7df030970332574e13d94e79df9 | [
"MIT"
] | 3 | 2019-01-08T00:09:56.000Z | 2020-03-12T03:05:20.000Z | DeepSpace/src/main/cpp/commands/LineTrackerFollowLine.cpp | NorthernForce/DeepSpace | b8446f0fb732e7df030970332574e13d94e79df9 | [
"MIT"
] | 12 | 2019-01-17T00:33:54.000Z | 2019-06-27T01:56:18.000Z | DeepSpace/src/main/cpp/commands/LineTrackerFollowLine.cpp | NorthernForce/DeepSpace | b8446f0fb732e7df030970332574e13d94e79df9 | [
"MIT"
] | null | null | null | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "commands/LineTrackerFollowLine.h"
#include "Robot.h"
#include "RobotMap.h"
const double LineTrackerFollowLine::k_turnSpeed = 0.2;
LineTrackerFollowLine::LineTrackerFollowLine() : Command("LineTrackerFollowLine") {
Requires(Robot::m_lineTracker.get());
Requires(Robot::m_driveTrain.get());
}
// Called just before this Command runs the first time
void LineTrackerFollowLine::Initialize() {}
// Called repeatedly when this Command is scheduled to run
void LineTrackerFollowLine::Execute() {
double rotation = 0;
switch(Robot::m_lineTracker->getLineSensors()) {
case 0b001: // Right Sensor Detected Line; Turn right
rotation = k_turnSpeed;
break;
case 0b011: // Right & Center Sensor Detected Line; Turn right
rotation = k_turnSpeed;
break;
case 0b100: // Left Sensor Detected Line; Turn Left
rotation = k_turnSpeed * -1;
break;
case 0b110: // Left & Center Sensor Detected Line; Turn left
rotation = k_turnSpeed * -1;
break;
}
Robot::m_driveTrain->arcDrive(Robot::m_oi->getSteeringControls().first, rotation);
}
// Make this return true when this Command no longer needs to run execute()
bool LineTrackerFollowLine::IsFinished() { return false; }
// Called once after isFinished returns true
void LineTrackerFollowLine::End() {
Robot::m_driveTrain->arcDrive(0, 0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void LineTrackerFollowLine::Interrupted() { End(); } | 36.472727 | 84 | 0.631605 | NorthernForce |
6cfa2729a6fedef36192edd39ecd2ceebf9fb4b9 | 22,521 | cpp | C++ | Game/ShipElectricSparks.cpp | sjohal21/Floating-Sandbox | 0170e3696ed4f012f5f17fdbbdaef1af4117f495 | [
"CC-BY-4.0"
] | 44 | 2018-07-08T16:44:53.000Z | 2022-02-06T14:07:30.000Z | Game/ShipElectricSparks.cpp | sjohal21/Floating-Sandbox | 0170e3696ed4f012f5f17fdbbdaef1af4117f495 | [
"CC-BY-4.0"
] | 31 | 2019-03-24T16:00:38.000Z | 2022-02-24T20:23:18.000Z | Game/ShipElectricSparks.cpp | sjohal21/Floating-Sandbox | 0170e3696ed4f012f5f17fdbbdaef1af4117f495 | [
"CC-BY-4.0"
] | 24 | 2018-11-08T21:58:53.000Z | 2022-01-12T12:04:42.000Z | /***************************************************************************************
* Original Author: Gabriele Giuseppini
* Created: 2021-05-29
* Copyright: Gabriele Giuseppini (https://github.com/GabrieleGiuseppini)
***************************************************************************************/
#include "Physics.h"
#include <GameCore/GameRandomEngine.h>
#include <algorithm>
#include <cassert>
namespace Physics {
ShipElectricSparks::ShipElectricSparks(
IShipPhysicsHandler & shipPhysicsHandler,
Points const & points,
Springs const & springs)
: mShipPhysicsHandler(shipPhysicsHandler)
, mIsSpringElectrifiedOld(springs.GetElementCount(), 0, false)
, mIsSpringElectrifiedNew(springs.GetElementCount(), 0, false)
, mPointElectrificationCounter(points.GetElementCount(), 0, std::numeric_limits<std::uint64_t>::max())
, mAreSparksPopulatedBeforeNextUpdate(false)
, mSparksToRender()
{
}
bool ShipElectricSparks::ApplySparkAt(
vec2f const & targetPos,
std::uint64_t counter,
float lengthMultiplier,
float currentSimulationTime,
Points const & points,
Springs const & springs,
GameParameters const & gameParameters)
{
//
// Find closest point, and check whether there _is_ actually a closest point
//
float nearestDistance = 2.0f;
ElementIndex nearestPointIndex = NoneElementIndex;
for (auto pointIndex : points.RawShipPoints()) // No point in visiting ephemeral points
{
vec2f const pointRadius = points.GetPosition(pointIndex) - targetPos;
float const squarePointDistance = pointRadius.squareLength();
if (squarePointDistance < nearestDistance)
{
nearestDistance = squarePointDistance;
nearestPointIndex = pointIndex;
}
}
if (nearestPointIndex != NoneElementIndex)
{
PropagateSparks(
nearestPointIndex,
counter,
lengthMultiplier,
currentSimulationTime,
points,
springs,
gameParameters);
return true;
}
else
{
// No luck
return false;
}
}
void ShipElectricSparks::Update()
{
if (!mAreSparksPopulatedBeforeNextUpdate)
{
mSparksToRender.clear();
}
mAreSparksPopulatedBeforeNextUpdate = false;
}
void ShipElectricSparks::Upload(
Points const & points,
ShipId shipId,
Render::RenderContext & renderContext) const
{
auto & shipRenderContext = renderContext.GetShipRenderContext(shipId);
shipRenderContext.UploadElectricSparksStart(mSparksToRender.size());
for (auto const & electricSpark : mSparksToRender)
{
shipRenderContext.UploadElectricSpark(
points.GetPlaneId(electricSpark.StartPointIndex),
electricSpark.StartPointPosition,
electricSpark.StartSize,
electricSpark.EndPointPosition,
electricSpark.EndSize,
electricSpark.Direction,
electricSpark.PreviousSparkIndex.has_value()
? mSparksToRender[*electricSpark.PreviousSparkIndex].Direction
: electricSpark.Direction,
electricSpark.NextSparkIndex.has_value()
? mSparksToRender[*electricSpark.NextSparkIndex].Direction
: electricSpark.Direction);
}
shipRenderContext.UploadElectricSparksEnd();
}
/// //////////////////////////////////////////////////////////////
void ShipElectricSparks::PropagateSparks(
ElementIndex const initialPointIndex,
std::uint64_t counter,
float lengthMultiplier,
float currentSimulationTime,
Points const & points,
Springs const & springs,
GameParameters const & gameParameters)
{
//
// This algorithm works by running a number of "expansions" at each iteration,
// with each expansion propagating sparks outwardly along springs
//
//
// Constants
//
size_t constexpr InitialArcsMin = 4;
size_t constexpr InitialArcsMax = 6;
float constexpr ForkSpacingMin = 5.0f;
float constexpr ForkSpacingMax = 10.0f;
float const maxEquivalentPathLength =
17.0f // Magic number: max length of arc without tool modifier and default settings
* lengthMultiplier
* (gameParameters.IsUltraViolentMode ? 2.0f : 1.0f);
// The information associated with a point that the next expansion will start from
struct SparkPointToVisit
{
ElementIndex PointIndex;
vec2f PreferredDirection; // Normalized direction that this arc started with
float EquivalentPathLength; // Cumulative equivalent length of path so far, up to the point that the spark starts at
ElementIndex IncomingSpringIndex; // The index of the spring that we traveled to reach this point
size_t IncomingRenderableSparkIndex; // The index of the spark we traveled through to reach this point
float EquivalentPathLengthToNextFork; // We'll fork when the equivalent path length is longer than this
SparkPointToVisit(
ElementIndex pointIndex,
vec2f const & preferredDirection,
float equivalentPathLength,
ElementIndex incomingSpringIndex,
size_t incomingRenderableSparkIndex,
float equivalentPathLengthToNextFork)
: PointIndex(pointIndex)
, PreferredDirection(preferredDirection)
, EquivalentPathLength(equivalentPathLength)
, IncomingSpringIndex(incomingSpringIndex)
, IncomingRenderableSparkIndex(incomingRenderableSparkIndex)
, EquivalentPathLengthToNextFork(equivalentPathLengthToNextFork)
{}
};
//
// Initialize
//
// Prepare IsSpringElectrified buffer
mIsSpringElectrifiedNew.fill(false);
bool * const wasSpringElectrifiedInPreviousInteraction = mIsSpringElectrifiedOld.data();
bool * const isSpringElectrifiedInThisInteraction = mIsSpringElectrifiedNew.data();
// Prepare point electrification flag
if (counter == 0)
{
mPointElectrificationCounter.fill(std::numeric_limits<std::uint64_t>::max());
}
// Clear the sparks that have to be rendered after this step
mSparksToRender.clear();
// Calculate max equivalent path length (total of single-step costs) for this interaction:
// we won't create arcs longer than this at this interaction
float const maxEquivalentPathLengthForThisInteraction = std::min(
static_cast<float>(counter + 1),
maxEquivalentPathLength);
// Functor that calculates size of a spark, given its current path length and the distance of that path
// length from the maximum for this interaction:
// - When we're at the end of the path for this interaction: small size
// - When we're at the beginning of the path for this interaction: large size
auto const calculateSparkSize = [maxEquivalentPathLengthForThisInteraction](float equivalentPathLength)
{
return 0.05f + (1.0f - 0.05f) * (maxEquivalentPathLengthForThisInteraction - equivalentPathLength) / maxEquivalentPathLengthForThisInteraction;
};
//
// 1. Electrify initial point
//
float const initialPointSize = calculateSparkSize(0.0f);
mShipPhysicsHandler.HandleElectricSpark(
initialPointIndex,
initialPointSize, // strength
currentSimulationTime,
gameParameters);
mPointElectrificationCounter[initialPointIndex] = counter;
//
// 2. Jump-start: find the initial springs outgoing from the initial point
//
std::vector<ElementIndex> initialSprings;
{
// Decide number of initial springs for this interaction
size_t const initialArcsCount = GameRandomEngine::GetInstance().GenerateUniformInteger(InitialArcsMin, InitialArcsMax);
//
// 1. Fetch all springs that were electrified in the previous iteration
//
std::vector<std::tuple<ElementIndex, float>> otherSprings;
for (auto const & cs : points.GetConnectedSprings(initialPointIndex).ConnectedSprings)
{
assert(mPointElectrificationCounter[cs.OtherEndpointIndex] != counter);
if (wasSpringElectrifiedInPreviousInteraction[cs.SpringIndex]
&& initialSprings.size() < initialArcsCount)
{
initialSprings.emplace_back(cs.SpringIndex);
}
else
{
otherSprings.emplace_back(
cs.SpringIndex,
points.GetRandomNormalizedUniformPersonalitySeed(cs.OtherEndpointIndex));
}
}
//
// 2. Remaining springs
//
// Sort remaining by random seed
std::sort(
otherSprings.begin(),
otherSprings.end(),
[](auto const & s1, auto const & s2)
{
return std::get<1>(s1) < std::get<1>(s2);
});
// Pick winners
for (size_t s = 0; s < otherSprings.size() && initialSprings.size() < initialArcsCount; ++s)
{
initialSprings.emplace_back(std::get<0>(otherSprings[s]));
}
}
//
// 3. Electrify the initial springs and initialize expansions
//
std::vector<SparkPointToVisit> currentPointsToVisit;
{
auto const initialPointPosition = points.GetPosition(initialPointIndex);
for (ElementIndex const s : initialSprings)
{
ElementIndex const targetEndpointIndex = springs.GetOtherEndpointIndex(s, initialPointIndex);
vec2f const targetEndpointPosition = points.GetPosition(targetEndpointIndex);
vec2f const direction = (targetEndpointPosition - initialPointPosition).normalise();
float const equivalentPathLength = 1.0f; // TODO: material-based
float const endSize = calculateSparkSize(0.0f + equivalentPathLength);
// Note: we don't flag the initial springs as electrified, as they are the only ones who share
// a point in common and thus if they're scooped up at the next interaction, they'll add
// an N-way fork, which could even get compounded by being picked up at the next, and so on...
// Electrify target point
mShipPhysicsHandler.HandleElectricSpark(
targetEndpointIndex,
endSize, // strength
currentSimulationTime,
gameParameters);
// Remember the point is electrified now
assert(mPointElectrificationCounter[targetEndpointIndex] != counter);
mPointElectrificationCounter[targetEndpointIndex] = counter;
// Queue for next expansion
if (equivalentPathLength < maxEquivalentPathLengthForThisInteraction)
{
currentPointsToVisit.emplace_back(
targetEndpointIndex,
direction,
0.0f + equivalentPathLength,
s,
mSparksToRender.size(), // The arc we'll be pushing right now is the predecessor of this point we're pushing now
GameRandomEngine::GetInstance().GenerateUniformReal(ForkSpacingMin, ForkSpacingMax));
}
// Render
mSparksToRender.emplace_back(
initialPointIndex,
initialPointPosition,
initialPointSize,
targetEndpointPosition,
endSize,
direction,
std::nullopt); // No previous spark
}
}
//
// 3. Expand now
//
std::vector<SparkPointToVisit> nextPointsToVisit;
std::vector<ElementIndex> nextSprings; // Allocated once for perf
while (!currentPointsToVisit.empty())
{
assert(nextPointsToVisit.empty());
// Visit all points awaiting expansion
for (auto const & pv : currentPointsToVisit)
{
ElementIndex const startingPointIndex = pv.PointIndex;
vec2f const startingPointPosition = points.GetPosition(startingPointIndex);
// Initialize path length until next fork - we'll eventually reset it if we fork
float equivalentPathLengthToNextFork = pv.EquivalentPathLengthToNextFork;
// Calculate distance to the end of this path in this interaction
float const distanceToInteractionMaxPathLength = (maxEquivalentPathLengthForThisInteraction - pv.EquivalentPathLength) / maxEquivalentPathLengthForThisInteraction;
//
// Of all the outgoing springs that are *not* the incoming spring:
// - Collect the first one that wa electrified in the previous interaction, does not
// lead to a point already electrified in this interaction (so to avoid forks),
// and agrees with alignment
// - Keep the others, ranking them on their alignment
// - We don't check beforehand if these will lead to an already-electrified
// point, so to allow for closing loops (which we won't electrify anyway)
//
nextSprings.clear();
ElementIndex bestCandidateNewSpring1 = NoneElementIndex;
float bestCandidateNewSpringAlignment1 = -1.0f;
ElementIndex bestCandidateNewSpring2 = NoneElementIndex;
float bestCandidateNewSpringAlignment2 = -1.0f;
ElementIndex bestCandidateNewSpring3 = NoneElementIndex;
float bestCandidateNewSpringAlignment3 = -1.0f;
for (auto const & cs : points.GetConnectedSprings(pv.PointIndex).ConnectedSprings)
{
if (cs.SpringIndex != pv.IncomingSpringIndex)
{
vec2f const springDirection = (points.GetPosition(cs.OtherEndpointIndex) - startingPointPosition).normalise();
float const springAlignment = springDirection.dot(pv.PreferredDirection);
if (nextSprings.empty() && wasSpringElectrifiedInPreviousInteraction[cs.SpringIndex])
{
if (mPointElectrificationCounter[cs.OtherEndpointIndex] != counter
&& springAlignment > 0.0f)
{
// We take this one for sure
nextSprings.emplace_back(cs.SpringIndex);
}
}
else
{
// Rank based on alignment
if (springAlignment > bestCandidateNewSpringAlignment1)
{
bestCandidateNewSpring3 = bestCandidateNewSpring2;
bestCandidateNewSpringAlignment3 = bestCandidateNewSpringAlignment2;
bestCandidateNewSpring2 = bestCandidateNewSpring1;
bestCandidateNewSpringAlignment2 = bestCandidateNewSpringAlignment1;
bestCandidateNewSpring1 = cs.SpringIndex;
bestCandidateNewSpringAlignment1 = springAlignment;
}
else if (springAlignment > bestCandidateNewSpringAlignment2)
{
bestCandidateNewSpring3 = bestCandidateNewSpring2;
bestCandidateNewSpringAlignment3 = bestCandidateNewSpringAlignment2;
bestCandidateNewSpring2 = cs.SpringIndex;
bestCandidateNewSpringAlignment2 = springAlignment;
}
else if (springAlignment > bestCandidateNewSpringAlignment3)
{
bestCandidateNewSpring3 = cs.SpringIndex;
bestCandidateNewSpringAlignment3 = springAlignment;
}
}
}
}
if (bestCandidateNewSpring1 != NoneElementIndex)
{
if (nextSprings.empty())
{
//
// Choose one spring out of the best three, with probabilities enforcing a nice zig-zag pattern
//
// Ignore sign of alignment, if we're forced we'll even recoil back
//
float const r = GameRandomEngine::GetInstance().GenerateNormalizedUniformReal();
if (r < 0.25f || bestCandidateNewSpring2 == NoneElementIndex)
{
nextSprings.emplace_back(bestCandidateNewSpring1);
}
else if (r < 0.85f || bestCandidateNewSpring3 == NoneElementIndex)
{
nextSprings.emplace_back(bestCandidateNewSpring2);
}
else
{
nextSprings.emplace_back(bestCandidateNewSpring3);
}
}
else if (nextSprings.size() == 1 && bestCandidateNewSpringAlignment1 >= 0.0f)
{
//
// Decide whether we want to fork or re-route, but always with a positive
// alignment
//
if (pv.EquivalentPathLength >= equivalentPathLengthToNextFork)
{
// Fork
if (bestCandidateNewSpringAlignment3 >= 0.0f)
{
// We have 3, choose second and third then
nextSprings[0] = bestCandidateNewSpring2;
nextSprings.emplace_back(bestCandidateNewSpring3);
}
else if (bestCandidateNewSpringAlignment2 >= 0.0f)
{
nextSprings.emplace_back(bestCandidateNewSpring2);
}
else
{
nextSprings.emplace_back(bestCandidateNewSpring1);
}
equivalentPathLengthToNextFork = pv.EquivalentPathLength + GameRandomEngine::GetInstance().GenerateUniformReal(ForkSpacingMin, ForkSpacingMax);
}
else if (
// Reroute when we're closer to interaction end
GameRandomEngine::GetInstance().GenerateUniformBoolean(0.15f * std::pow(1.0f - distanceToInteractionMaxPathLength, 0.5f)))
{
// Reroute
if (bestCandidateNewSpringAlignment2 >= 0.0f
&& GameRandomEngine::GetInstance().GenerateUniformBoolean(0.5f))
{
nextSprings[0] = bestCandidateNewSpring2;
}
else
{
nextSprings[0] = bestCandidateNewSpring1;
}
}
}
}
//
// Follow all of the new springs
//
for (auto const s : nextSprings)
{
ElementIndex const targetEndpointIndex = springs.GetOtherEndpointIndex(s, pv.PointIndex);
vec2f const targetEndpointPosition = points.GetPosition(targetEndpointIndex);
vec2f const springDirection = (targetEndpointPosition - startingPointPosition).normalise();
float const startEquivalentPathLength = pv.EquivalentPathLength;
float const equivalentStepLength = 1.0f; // TODO: material-based
float const endEquivalentPathLength = startEquivalentPathLength + equivalentStepLength;
float const startSize = calculateSparkSize(startEquivalentPathLength);
size_t const springSparkToRenderIndex = mSparksToRender.size(); // The arc we'll be pushing right now is the arc for this spring
// Render
mSparksToRender.emplace_back(
startingPointIndex,
startingPointPosition,
startSize,
targetEndpointPosition,
calculateSparkSize(endEquivalentPathLength),
springDirection,
pv.IncomingRenderableSparkIndex);
// Connect this renderable spark to its predecessor, if this is the first one
if (!mSparksToRender[pv.IncomingRenderableSparkIndex].NextSparkIndex.has_value())
{
mSparksToRender[pv.IncomingRenderableSparkIndex].NextSparkIndex = springSparkToRenderIndex;
}
// Propagate visit
if (mPointElectrificationCounter[targetEndpointIndex] != counter)
{
// Electrify spring
isSpringElectrifiedInThisInteraction[s] = true;
// Electrify point
mShipPhysicsHandler.HandleElectricSpark(
targetEndpointIndex,
startSize, // strength
currentSimulationTime,
gameParameters);
// Remember this point is not electrified
mPointElectrificationCounter[targetEndpointIndex] = counter;
// Next expansion
if (endEquivalentPathLength < maxEquivalentPathLengthForThisInteraction)
{
nextPointsToVisit.emplace_back(
targetEndpointIndex,
pv.PreferredDirection,
endEquivalentPathLength,
s,
springSparkToRenderIndex, // Predecessor
equivalentPathLengthToNextFork);
}
}
}
}
// Advance expansion
std::swap(currentPointsToVisit, nextPointsToVisit);
nextPointsToVisit.clear();
}
//
// Finalize
//
// Swap IsElectrified buffers
mIsSpringElectrifiedNew.swap(mIsSpringElectrifiedOld);
// Remember that we have populated electric sparks
mAreSparksPopulatedBeforeNextUpdate = true;
}
} | 39.719577 | 175 | 0.588828 | sjohal21 |
6cfe6905c1e4bad62314e1e2b671e04c14fa71fa | 1,009 | hpp | C++ | code/source/game/devlogic.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | 12 | 2015-01-12T00:19:20.000Z | 2021-08-05T10:47:20.000Z | code/source/game/devlogic.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | code/source/game/devlogic.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | #ifndef CLOVER_DEVLOGIC_HPP
#define CLOVER_DEVLOGIC_HPP
#include "build.hpp"
#include "game/editor/editor.hpp"
#include "ui/hid/actionlistener.hpp"
#include "util/dyn_array.hpp"
#include "util/profiler.hpp"
#include "util/string.hpp"
namespace clover {
namespace game {
/// Handles developer-only logic which can be cut out for release
class DevLogic {
public:
struct PerformanceTimerResult {
/// Name of timer
util::Str8 name;
/// In seconds
real32 averageTime;
/// Scale 0-1
real32 percentage;
};
DevLogic();
void update();
const util::DynArray<PerformanceTimerResult>& getLastPerformanceTimerResults() const { return performanceTimerResults; }
editor::Editor& getEditor(){ return editor; }
private:
util::Profiler profiler;
int32 fpsFrameCount;
real32 fpsTimer;
int32 fpsPrintFilter;
util::DynArray<PerformanceTimerResult> performanceTimerResults;
editor::Editor editor;
ui::hid::ActionListener<> profileListener;
};
} // game
} // clover
#endif // CLOVER_DEVLOGIC_HPP
| 20.18 | 121 | 0.751239 | crafn |
9f072564830d0c41c8991fbd4e0106f0aa6bf766 | 430 | cpp | C++ | FullBright.cpp | Apflmus/Rust-Cheat | 7b4a1212cc1b0f46ff8cf510e83ca358b58aeb72 | [
"Apache-2.0"
] | 36 | 2017-10-31T21:52:47.000Z | 2020-01-19T02:32:27.000Z | FullBright.cpp | J0hnDark/Rust-Cheat | 7b4a1212cc1b0f46ff8cf510e83ca358b58aeb72 | [
"Apache-2.0"
] | 2 | 2018-01-03T17:22:53.000Z | 2019-09-25T19:25:29.000Z | FullBright.cpp | J0hnDark/Rust-Cheat | 7b4a1212cc1b0f46ff8cf510e83ca358b58aeb72 | [
"Apache-2.0"
] | 19 | 2020-02-22T02:25:22.000Z | 2022-03-31T15:08:50.000Z | #include "Globals.h"
#include "Utils.h"
float origvalue1;
float origvalue2;
DWORD64 lightColorOrig;
void setToDay()
{
ULONG_PTR objectClass = read<ULONG_PTR>(entity[1].gameObject + 0x30);
ULONG_PTR entityPtr = read<ULONG_PTR>(objectClass + 0x18);
ULONG_PTR skyDome = read<ULONG_PTR>(entityPtr + 0x28);
ULONG_PTR todCycle = read<ULONG_PTR>(skyDome + 0x18);
write<float>(todCycle + 0x10, 12);
}
//(c) Apflmus | 25.294118 | 71 | 0.711628 | Apflmus |
9f079944d0af5b6fee82b73ec3940bde0ff085d1 | 536 | cpp | C++ | HaloTAS/TASDLL/halo_map_data.cpp | s3anyboy/HaloTAS | 9584786f19e1475399298fda2d5783d47623cccd | [
"MIT"
] | 6 | 2019-09-10T19:47:04.000Z | 2020-11-26T08:32:36.000Z | HaloTAS/TASDLL/halo_map_data.cpp | s3anyboy/HaloTAS | 9584786f19e1475399298fda2d5783d47623cccd | [
"MIT"
] | 13 | 2018-11-24T09:37:49.000Z | 2021-10-22T02:29:11.000Z | HaloTAS/TASDLL/halo_map_data.cpp | s3anyboy/HaloTAS | 9584786f19e1475399298fda2d5783d47623cccd | [
"MIT"
] | 3 | 2020-07-28T09:19:14.000Z | 2020-09-02T04:48:49.000Z | #include "halo_map_data.h"
std::string halo::mapdata::tag_entry::tag_class_to_str(uint32_t tag_class)
{
char c[4];
memcpy(&c, &tag_class, 4);
std::reverse(c, c + 4);
std::string str(c, 4);
return str;
}
std::string halo::mapdata::tag_entry::tag_class_str()
{
return tag_class_to_str(tag_class);
}
std::string halo::mapdata::tag_entry::tag_class_secondary_str()
{
return tag_class_to_str(tag_class_secondary);
}
std::string halo::mapdata::tag_entry::tag_class_tertiary_str()
{
return tag_class_to_str(tag_class_tertiary);
}
| 20.615385 | 74 | 0.744403 | s3anyboy |
9f0e1a3c89311ca1a68579fabbe0185299ead107 | 320 | cpp | C++ | Programmers/src/12906/solution.cpp | lstar2397/algorithms | 686ea882079e26111f86b5bd5a7ab1b14ccf0fa2 | [
"MIT"
] | null | null | null | Programmers/src/12906/solution.cpp | lstar2397/algorithms | 686ea882079e26111f86b5bd5a7ab1b14ccf0fa2 | [
"MIT"
] | null | null | null | Programmers/src/12906/solution.cpp | lstar2397/algorithms | 686ea882079e26111f86b5bd5a7ab1b14ccf0fa2 | [
"MIT"
] | null | null | null | #include <vector>
using namespace std;
vector<int> solution(vector<int> arr) {
int prevElement = -1;
vector<int> answer;
for (size_t i = 0; i < arr.size(); i++)
{
int curElement = arr.at(i);
if (prevElement != curElement)
{
answer.push_back(arr.at(i));
prevElement = curElement;
}
}
return answer;
} | 18.823529 | 40 | 0.640625 | lstar2397 |
9f0ffd9712abd9144dc8796567667d9dc8e64b22 | 613 | hpp | C++ | src/atmosphere/Generator.hpp | dat14jpe/mulen | 33beeb8a38e5556ddd44efba909e18aab9a3d401 | [
"MIT"
] | 5 | 2020-01-15T12:49:45.000Z | 2021-11-24T05:15:59.000Z | src/atmosphere/Generator.hpp | dat14jpe/mulen | 33beeb8a38e5556ddd44efba909e18aab9a3d401 | [
"MIT"
] | null | null | null | src/atmosphere/Generator.hpp | dat14jpe/mulen | 33beeb8a38e5556ddd44efba909e18aab9a3d401 | [
"MIT"
] | null | null | null | #pragma once
#include "Common.hpp"
#include "util/Shader.hpp"
namespace Mulen::Atmosphere {
// Atmosphere generator.
class Generator
{
const std::string shaderName;
Util::Shader shader; // brick generation shader
public:
const std::string& GetShaderName() { return shaderName; }
Util::Shader& GetShader() { return shader; }
Generator(const std::string& shaderName)
: shaderName{ shaderName }
{}
// Generate data for a new generation pass (likely in a worker thread).
virtual void Generate(UpdateIteration&);
};
}
| 26.652174 | 79 | 0.628059 | dat14jpe |
9f10972fa8ea326ad5479dd176c28e5e637b17e2 | 1,755 | cpp | C++ | projects/solutions/03/driveController.cpp | RoboJackets-Software-Training-Test/test-project-1-oswinso | 45b8f82477106bae739069f594ff8711cfc47981 | [
"MIT"
] | null | null | null | projects/solutions/03/driveController.cpp | RoboJackets-Software-Training-Test/test-project-1-oswinso | 45b8f82477106bae739069f594ff8711cfc47981 | [
"MIT"
] | null | null | null | projects/solutions/03/driveController.cpp | RoboJackets-Software-Training-Test/test-project-1-oswinso | 45b8f82477106bae739069f594ff8711cfc47981 | [
"MIT"
] | null | null | null | #include <STSL/RJRobot.h>
#include "pid.h"
#include <ctime>
#include <unistd.h>
#include <cstdlib>
int main()
{
PID controller_left(10.0, 0.1, 0, .01, 0.5, 0.25);
PID controller_right(10.0, 0.1, 0, .01, 0.5, 0.25);
float target = 0.5;
float current = 0;
float controller_effort_left, controller_effort_right;
int dt = 10;
RJRobot robot;
RJRobot::EncoderSpeeds speeds;
std::cout << "Starting Loop" << std::endl;
while(std::abs(target - current) > 0.001)
{
std::cout << "In loop" << std::endl;
auto start_time = std::chrono::system_clock::now();
speeds = robot.getEncoderSpeeds(); // Get the encoder speeds
controller_effort_left = controller_left.update(target, speeds.left); // PID on left wheel
controller_effort_right = controller_right.update(target, speeds.right); // PID on right wheel
robot.setDriveMotors(controller_effort_left, -1*controller_effort_right); // Set drive motors
auto end_time = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end_time-start_time; // Can use elapsed time for more accurate dt
robot.wait(std::chrono::duration_cast<std::chrono::microseconds>(operator""ms(dt)));
std::cout << "Left Speed: " << speeds.left << std::endl;
std::cout << " Right Speed: " << speeds.right << std::endl;
current = (speeds.left + speeds.right)/2; // Average the two speeds to get the current velocity
}
/*robot.setDriveMotors(0.375, -0.375);
robot.wait(std::chrono::duration_cast<std::chrono::microseconds>(operator""ms(10000)));*/
robot.stopMotors();
return 0;
} | 35.816327 | 121 | 0.622792 | RoboJackets-Software-Training-Test |
2f57ada990ace2990d12d4e8e9443c6c78a2c7ee | 1,978 | cpp | C++ | cpp/visual studio/CalculatorServer/RerollBotConsole/debug_main.cpp | NiHoel/Anno1800UXEnhancer | b430fdb428696b5218ca65a5e9b977d659cfca01 | [
"Apache-2.0"
] | 27 | 2020-03-29T16:02:09.000Z | 2021-12-18T20:08:51.000Z | cpp/visual studio/CalculatorServer/RerollBotConsole/debug_main.cpp | NiHoel/Anno1800UXEnhancer | b430fdb428696b5218ca65a5e9b977d659cfca01 | [
"Apache-2.0"
] | 22 | 2020-04-03T03:40:59.000Z | 2022-03-29T15:55:28.000Z | cpp/visual studio/CalculatorServer/RerollBotConsole/debug_main.cpp | NiHoel/Anno1800UXEnhancer | b430fdb428696b5218ca65a5e9b977d659cfca01 | [
"Apache-2.0"
] | 2 | 2021-10-17T16:15:46.000Z | 2022-01-10T18:56:49.000Z | #pragma once
#include "reader_trading.hpp"
using namespace reader;
template<typename T>
void print(const std::map<unsigned int, T>& map,
const std::map<unsigned int, std::string>& dictionary = std::map<unsigned int, std::string>())
{
for (const auto& entry : map)
{
if (dictionary.find(entry.first) != dictionary.cend())
std::cout << dictionary.find(entry.first)->second << "\t=\t" << entry.second << std::endl;
else
std::cout << entry.first << "\t=\t" << entry.second << std::endl;
}
}
int main() {
image_recognition recog;
trading_menu reader(recog);
// cv::Mat src = image_recognition::load_image("C:/Users/Nico/Documents/Anno 1800/screenshot/screenshot_2019-12-31-13-03-20.jpg");
// cv::Mat src = image_recognition::load_image("C:/Users/Nico/Pictures/Uplay/Anno 1800/Anno 18002020-1-6-0-32-3.png");
// cv::Mat src = image_recognition::load_image("C:/Users/Nico/Documents/Dokumente/Computer/Softwareentwicklung/AnnoCalculatorServer/calculator-recognition-issues/population_number_slash_issue/screenshot6.png");
// cv::Mat src = image_recognition::load_image("J:/Pictures/Uplay/Anno 1800/Anno 18002020-1-6-0-32-3.png");
cv::Mat src = image_recognition::load_image("test_screenshots/trade_eli_1.png");
reader.update("english", src);
//image_recog.update("german", image_recognition::load_image("C:/Users/Nico/Documents/Dokumente/Computer/Softwareentwicklung/AnnoCalculatorServer/calculator-recognition-issues/island_name_mua/screenshot.png"));
try {
std::cout << "Trader: " << recog.get_dictionary().ui_texts.at(reader.get_open_trader()) << std::endl;
std::cout << "Rerollable: " << reader.has_reroll() << std::endl;
std::cout << "Buyable: " << reader.can_buy() << std::endl;
const auto offerings = reader.get_offerings();
std::cout << "Offerings:" << std::endl;
for (const auto& offering : offerings)
std::cout << offering.index << ": " << offering.price << std::endl;
}
catch (const std::exception & e)
{ }
return 0;
} | 39.56 | 211 | 0.708291 | NiHoel |
2f58f8aec3cf2d351f8cdbc2b76cc4c3a3130f4b | 1,736 | cpp | C++ | source/Library.Shared/DirectXHelper.cpp | ssshammi/real-time-3d-rendering-with-directx-and-hlsl | 05a05c5c26784dafa9a89747276f385252951f2f | [
"MIT"
] | null | null | null | source/Library.Shared/DirectXHelper.cpp | ssshammi/real-time-3d-rendering-with-directx-and-hlsl | 05a05c5c26784dafa9a89747276f385252951f2f | [
"MIT"
] | null | null | null | source/Library.Shared/DirectXHelper.cpp | ssshammi/real-time-3d-rendering-with-directx-and-hlsl | 05a05c5c26784dafa9a89747276f385252951f2f | [
"MIT"
] | null | null | null | #include "pch.h"
#include "DirectXHelper.h"
#include "GameException.h"
using namespace std;
using namespace gsl;
namespace Library
{
void CreateIndexBuffer(not_null<ID3D11Device*> device, const span<const uint16_t>& indices, not_null<ID3D11Buffer**> indexBuffer)
{
D3D11_BUFFER_DESC indexBufferDesc{ 0 };
indexBufferDesc.ByteWidth = narrow<uint32_t>(indices.size_bytes());
indexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
D3D11_SUBRESOURCE_DATA indexSubResourceData{ 0 };
indexSubResourceData.pSysMem = &indices[0];
ThrowIfFailed(device->CreateBuffer(&indexBufferDesc, &indexSubResourceData, indexBuffer), "ID3D11Device::CreateBuffer() failed.");
}
void CreateIndexBuffer(not_null<ID3D11Device*> device, const span<const uint32_t>& indices, not_null<ID3D11Buffer**> indexBuffer)
{
D3D11_BUFFER_DESC indexBufferDesc{ 0 };
indexBufferDesc.ByteWidth = narrow<uint32_t>(indices.size_bytes());
indexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
D3D11_SUBRESOURCE_DATA indexSubResourceData{ 0 };
indexSubResourceData.pSysMem = &indices[0];
ThrowIfFailed(device->CreateBuffer(&indexBufferDesc, &indexSubResourceData, indexBuffer), "ID3D11Device::CreateBuffer() failed.");
}
void CreateConstantBuffer(not_null<ID3D11Device*> device, std::size_t byteWidth, not_null<ID3D11Buffer**> constantBuffer)
{
D3D11_BUFFER_DESC constantBufferDesc{ 0 };
constantBufferDesc.ByteWidth = narrow_cast<uint32_t>(byteWidth);
constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
ThrowIfFailed(device->CreateBuffer(&constantBufferDesc, nullptr, constantBuffer), "ID3D11Device::CreateBuffer() failed.");
}
} | 41.333333 | 132 | 0.797811 | ssshammi |
2f6d66246269188a6ee76958fbda89c343bee662 | 9,206 | cc | C++ | compiler/verify/access_test.cc | asoffer/icarus | 5c9af79d1a39e14d95da1adacbdd7392908eedc5 | [
"Apache-2.0"
] | null | null | null | compiler/verify/access_test.cc | asoffer/icarus | 5c9af79d1a39e14d95da1adacbdd7392908eedc5 | [
"Apache-2.0"
] | null | null | null | compiler/verify/access_test.cc | asoffer/icarus | 5c9af79d1a39e14d95da1adacbdd7392908eedc5 | [
"Apache-2.0"
] | null | null | null | #include "compiler/compiler.h"
#include "compiler/module.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "test/module.h"
namespace compiler {
namespace {
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::IsEmpty;
using ::testing::Pair;
using ::testing::SizeIs;
using ::testing::UnorderedElementsAre;
TEST(Access, EnumSuccess) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
E ::= enum { A \\ B \\ C }
E.A
)");
auto const *enumerator = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(enumerator);
ASSERT_THAT(qts, SizeIs(1));
EXPECT_TRUE(qts[0].type().is<type::Enum>());
EXPECT_EQ(qts[0].quals(), type::Quals::Const());
EXPECT_THAT(infra.diagnostics(), IsEmpty());
}
TEST(Access, EnumMisnamed) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
E ::= enum { A \\ B \\ C }
E.D
)");
auto const *enumerator = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(enumerator);
EXPECT_TRUE(qts[0].type().is<type::Enum>());
EXPECT_EQ(qts[0].quals(), type::Quals::Const());
EXPECT_THAT(
infra.diagnostics(),
UnorderedElementsAre(Pair("type-error", "missing-constant-member")));
}
TEST(Access, FlagsSuccess) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
F ::= flags { A \\ B \\ C }
F.A
)");
auto const *flag = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(flag);
EXPECT_TRUE(qts[0].type().is<type::Flags>());
EXPECT_EQ(qts[0].quals(), type::Quals::Const());
EXPECT_THAT(infra.diagnostics(), IsEmpty());
}
TEST(Access, FlagsMisnamed) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
F ::= flags { A \\ B \\ C }
F.D
)");
auto const *flag = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(flag);
EXPECT_TRUE(qts[0].type().is<type::Flags>());
EXPECT_EQ(qts[0].quals(), type::Quals::Const());
EXPECT_THAT(
infra.diagnostics(),
UnorderedElementsAre(Pair("type-error", "missing-constant-member")));
}
TEST(Access, NonConstantType) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
T := i64
T.something)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts, ElementsAre(type::QualType::Error()));
EXPECT_THAT(infra.diagnostics(),
UnorderedElementsAre(
Pair("type-error", "non-constant-type-member-access")));
}
// TODO: Test covering an evaluation error when accessing a type member.
TEST(Access, TypeHasNoMembers) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
T ::= i64
T.something)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts, ElementsAre(type::QualType::Error()));
EXPECT_THAT(infra.diagnostics(),
UnorderedElementsAre(Pair("type-error", "type-has-no-members")));
}
TEST(Access, AccessStructField) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
S ::= struct {
n: i64
b: bool
}
non_constant: S
constant :: S
non_constant.n
constant.n
)");
auto stmts = mod.module().stmts();
auto const *non_constant = &stmts[stmts.size() - 2]->as<ast::Expression>();
auto const *constant = &stmts[stmts.size() - 1]->as<ast::Expression>();
auto non_constant_qts = mod.context().qual_types(non_constant);
auto constant_qts = mod.context().qual_types(constant);
EXPECT_THAT(infra.diagnostics(), IsEmpty());
EXPECT_THAT(non_constant_qts,
ElementsAre(type::QualType(type::I64, type::Quals::Ref())));
EXPECT_THAT(constant_qts,
UnorderedElementsAre(type::QualType(
type::I64, type::Quals::Ref() | type::Quals::Const())));
}
TEST(Access, NoFieldInStruct) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
S ::= struct {
n: i64
b: bool
}
s: S
s.x
)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts, ElementsAre(type::QualType::Error()));
EXPECT_THAT(infra.diagnostics(),
UnorderedElementsAre(Pair("type-error", "missing-member")));
}
TEST(Access, ConstantSliceLength) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"("abc".length)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts, ElementsAre(type::QualType(
type::U64, type::Quals::Ref() | type::Quals::Const())));
EXPECT_THAT(infra.diagnostics(), IsEmpty());
}
TEST(Access, NonConstantSliceLength) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
s := "abc"
s.length)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts, ElementsAre(type::QualType(type::U64, type::Quals::Ref())));
EXPECT_THAT(infra.diagnostics(), IsEmpty());
}
TEST(Access, NonConstantSliceData) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
s := "abc"
s.data)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts, ElementsAre(type::QualType(type::BufPtr(type::Char),
type::Quals::Ref())));
EXPECT_THAT(infra.diagnostics(), IsEmpty());
}
TEST(Access, SliceInvalidMember) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
s := "abc"
s.size)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts, ElementsAre(type::QualType::Error()));
EXPECT_THAT(infra.diagnostics(),
UnorderedElementsAre(Pair("type-error", "missing-member")));
}
TEST(Access, ArrayLength) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"([3; i64].length)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts,
ElementsAre(type::QualType::Constant(type::Array::LengthType())));
EXPECT_THAT(infra.diagnostics(), IsEmpty());
}
TEST(Access, MultidimensionalArrayLength) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"([3, 2; i64].length)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts,
ElementsAre(type::QualType::Constant(type::Array::LengthType())));
EXPECT_THAT(infra.diagnostics(), IsEmpty());
}
TEST(Access, ArrayElementType) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"([3, 2; i64].element_type)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts, ElementsAre(type::QualType::Constant(type::Type_)));
EXPECT_THAT(infra.diagnostics(), IsEmpty());
}
TEST(Access, ArrayInvalidMember) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"([3; i64].size)");
auto const *expr = mod.get<ast::Expression>();
auto qts = mod.context().qual_types(expr);
EXPECT_THAT(qts, ElementsAre(type::QualType::Error()));
EXPECT_THAT(
infra.diagnostics(),
UnorderedElementsAre(Pair("type-error", "missing-constant-member")));
}
TEST(Access, CrossModuleStructFieldAccess) {
test::CompilerInfrastructure infra;
infra.add_module("imported", R"(
#{export} S ::= struct {
#{export} n: i64
}
)");
auto &mod = infra.add_module(R"(
mod ::= import "imported"
s: mod.S
s.n
)");
EXPECT_THAT(infra.diagnostics(), IsEmpty());
}
TEST(Access, CrossModuleStructFieldError) {
test::CompilerInfrastructure infra;
infra.add_module("imported", R"(
#{export} S ::= struct {
#{export} n: i64
}
)");
auto &mod = infra.add_module(R"(
mod ::= import "imported"
s: mod.S
s.m
)");
EXPECT_THAT(infra.diagnostics(),
UnorderedElementsAre(Pair("type-error", "missing-member")));
}
TEST(Access, Pattern) {
test::CompilerInfrastructure infra;
auto &mod = infra.add_module(R"(
S ::= struct {
n: i64
}
3 ~ (`s).n
)");
EXPECT_THAT(infra.diagnostics(),
UnorderedElementsAre(Pair("pattern-error", "deducing-access")));
}
// TODO: Field not exported from another module.
// TODO: Non-constant module
// TODO: Module evaluation failure
// TODO: Undeclared identifier across module boundaries
// TODO: Type error across module boundaries (other module already generated
// error)
// TODO: Valid access across module boundaries
// TODO: Valid overload set across module boundary
// TODO: Valid scope set across module boundary
// TODO: Valid mix of overloads and scopes across module boundary
// TODO: Invalid overload set across module boundaries
// TODO: Error on accessing incomplete member.
} // namespace
} // namespace compiler
| 30.084967 | 80 | 0.645449 | asoffer |
2f71342ed59b3d5ff423a16576635f4b488dde86 | 2,591 | hpp | C++ | pass/lgraph_to_lnast/pass_lgraph_to_lnast.hpp | maximiliantiao/livehd | 88215f0d6fc395db96e6ed058f00b9205454bd0c | [
"BSD-3-Clause"
] | null | null | null | pass/lgraph_to_lnast/pass_lgraph_to_lnast.hpp | maximiliantiao/livehd | 88215f0d6fc395db96e6ed058f00b9205454bd0c | [
"BSD-3-Clause"
] | null | null | null | pass/lgraph_to_lnast/pass_lgraph_to_lnast.hpp | maximiliantiao/livehd | 88215f0d6fc395db96e6ed058f00b9205454bd0c | [
"BSD-3-Clause"
] | null | null | null | // This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#pragma once
#include "pass.hpp"
#include "lnast.hpp"
#include "lgraph.hpp"
class Pass_lgraph_to_lnast : public Pass {
protected:
uint64_t temp_var_count = 0;
uint64_t seq_count = 0;
void do_trans(LGraph *g, Eprp_var &var, std::string_view module_name);
void initial_tree_coloring(LGraph *g);
void begin_transformation(LGraph *g, Lnast& lnast, Lnast_nid& ln_node);
void handle_output_node(LGraph *lg, Node_pin& pin, Lnast& lnast, Lnast_nid& ln_node);
void handle_source_node(LGraph *lg, Node_pin& pin, Lnast& lnast, Lnast_nid& ln_node);
void attach_to_lnast(Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_output_to_lnast(Lnast& lnast, Lnast_nid& parent_node, const Node_pin &opin);
void attach_sum_node (Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_binaryop_node (Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_not_node (Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_join_node (Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_pick_node (Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_comparison_node(Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_simple_node (Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_mux_node (Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_flop_node (Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_subgraph_node (Lnast& lnast, Lnast_nid& parent_node, const Node_pin &pin);
void attach_children_to_node(Lnast& lnast, Lnast_nid& op_node, const Node_pin &pin);
void attach_child(Lnast& lnast, Lnast_nid& op_node, const Node_pin &dpin);
//void attach_child(Lnast& lnast, Lnast_nid& op_node, const Node_pin &dpin, std::string prefix);
void attach_cond_child(Lnast& lnast, Lnast_nid& op_node, const Node_pin &dpin);
void handle_io(LGraph *g, Lnast_nid& parent_lnast_node, Lnast& lnast);
std::string_view get_driver_of_output(const Node_pin dpin);
std::string_view dpin_get_name(const Node_pin dpin);
std::string_view get_new_seq_name(Lnast& lnast);
public:
static void trans(Eprp_var &var);
Pass_lgraph_to_lnast(const Eprp_var &var);
static void setup();
};
| 49.826923 | 105 | 0.708221 | maximiliantiao |
2f726f13dfbfcaa829a1d4fd3067f2c66e0e51ae | 15,367 | cpp | C++ | OpenMMPlugin/OpenMMPlugin.cpp | MadCatX/molmodel | 5abde979e1780dcc61a4b05affcba6e116250585 | [
"MIT"
] | null | null | null | OpenMMPlugin/OpenMMPlugin.cpp | MadCatX/molmodel | 5abde979e1780dcc61a4b05affcba6e116250585 | [
"MIT"
] | null | null | null | OpenMMPlugin/OpenMMPlugin.cpp | MadCatX/molmodel | 5abde979e1780dcc61a4b05affcba6e116250585 | [
"MIT"
] | null | null | null | /* -------------------------------------------------------------------------- *
* SimTK Molmodel(tm): OpenMM Plugin *
* -------------------------------------------------------------------------- *
* This is part of the SimTK Core biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009-11 Stanford University and the Authors. *
* Authors: Michael Sherman *
* Contributors: *
* *
* 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, CONTRIBUTORS 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. *
* -------------------------------------------------------------------------- */
// Suppress irrelevant warnings from Microsoft's compiler.
#ifdef _MSC_VER
#pragma warning(disable:4996) // sprintf is unsafe
#pragma warning(disable:4251) // no dll interface for some classes
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
#include "SimTKcommon.h"
#include "OpenMMPlugin.h"
#include "DuMMForceFieldSubsystemRep.h"
#include "OpenMM.h"
#include <string>
#include <vector>
#include <exception>
#include <cassert>
using namespace SimTK;
#define STRINGIZE(var) #var
#define MAKE_VERSION_STRING(maj,min,build) STRINGIZE(maj.min.build)
/**
* This is a concrete implementation of the OpenMMPluginInterface class defined
* by Molmodel.
*/
class OpenMMInterface : public OpenMMPluginInterface {
public:
OpenMMInterface(const DuMMForceFieldSubsystemRep& dumm)
: dumm(dumm), openMMSystem(0), openMMContext(0), openMMIntegrator(0) {}
~OpenMMInterface() {deleteOpenMM();}
// This reports the version of Molmodel which was current at the time
// this plugin was compiled.
std::string getMolmodelVersion() const {
return MAKE_VERSION_STRING(SimTK_MOLMODEL_MAJOR_VERSION,
SimTK_MOLMODEL_MINOR_VERSION,
SimTK_MOLMODEL_PATCH_VERSION);
}
// Call this during Molmodel's realizeTopology() method. Return value
// is the selected OpenMM Platform name.
std::string initializeOpenMM(bool allowReferencePlatform,
std::vector<std::string>& logMessages) throw();
// Calculates forces and/or energy and *adds* them into the output
// parameters.
void calcOpenMMNonbondedAndGBSAForces
(const Vector_<Vec3>& includedAtomStation_G,
const Vector_<Vec3>& includedAtomPos_G,
bool wantForces,
bool wantEnergy,
Vector_<SpatialVec>& includedBodyForce_G,
Real& energy) const;
private:
// Put this object back into its just-constructed condition.
void deleteOpenMM() {
delete openMMIntegrator; openMMIntegrator=0;
delete openMMContext; openMMContext=0;
delete openMMSystem; openMMSystem=0;
}
private:
const DuMMForceFieldSubsystemRep& dumm;
OpenMM::System* openMMSystem;
OpenMM::Context* openMMContext;
OpenMM::Integrator* openMMIntegrator; // dummy
};
//-----------------------------------------------------------------------------
// SimTK_createOpenMMPluginInterface
//-----------------------------------------------------------------------------
// This is the exported, non-name-mangled symbol that is called from the loading
// process to get access to this plugin's implementation of the OpenMM plugin
// interface defined by DuMM.
extern "C" EXPORT OpenMMPluginInterface*
SimTK_createOpenMMPluginInterface(const DuMMForceFieldSubsystemRep& dumm) {
return new OpenMMInterface(dumm);
}
//-----------------------------------------------------------------------------
// initializeOpenMM
//-----------------------------------------------------------------------------
std::string OpenMMInterface::
initializeOpenMM(bool allowReferencePlatform,
std::vector<std::string>& logMessages) throw()
{
logMessages.clear();
// Determine whether OpenMM supports all the features we've asked for.
// OpenMM does not support 1-2, 1-3, or 1-5 scaling.
if ( dumm.vdwScale12!=0 || dumm.coulombScale12!=0
|| dumm.vdwScale13!=0 || dumm.coulombScale13!=0
|| dumm.vdwScale15!=1 || dumm.coulombScale15!=1)
{
logMessages.push_back(
"WARNING: Can't use OpenMM: unsupported vdW or Coulomb scaling required.\n");
return "";
}
// Currently OpenMM supports only the Lorentz-Berthelot L-J combining rule
// as used by AMBER and CHARMM.
if ( dumm.vdwGlobalScaleFactor != 0
&& dumm.vdwMixingRule != DuMMForceFieldSubsystem::LorentzBerthelot)
{
logMessages.push_back(
"WARNING: Can't use OpenMM: only the Lorentz-Berthelot"
" (AMBER) Lennard Jones mixing rule is supported.\n");
return "";
}
try {
// OpenMM SYSTEM //
openMMSystem = new OpenMM::System();
for (DuMM::NonbondAtomIndex nax(0); nax < dumm.getNumNonbondAtoms(); ++nax) {
const Element& e = Element::getByAtomicNumber
(dumm.getAtomElementNum(dumm.getAtomIndexOfNonbondAtom(nax)));
openMMSystem->addParticle(e.getMass());
}
// NONBONDED FORCES //
if (dumm.coulombGlobalScaleFactor!=0 || dumm.vdwGlobalScaleFactor!=0) {
OpenMM::NonbondedForce* nonbondedForce = new OpenMM::NonbondedForce();
// Scale charges by sqrt of scale factor so that products of charges
// scale linearly.
const Real sqrtCoulombScale = std::sqrt(dumm.coulombGlobalScaleFactor);
// Here we'll define all the OpenMM particles, one per DuMM nonbond
// atom. We'll also build up the list of all 1-2 bonds between nonbond
// atoms which will be used by OpenMM as an exceptions list, with
// nonbond interactions excluded for 1-2 and 1-3 connections, and
// scaled down for 1-4 connections. Since OpenMM doesn't know about
// bodies, we can't used the stripped-down cross-body bond lists here.
// We will look at all the 1-2 bonds for each nonbond atom and keep
// those that connect to another nonbond atom.
std::vector< std::pair<int, int> > ommBonds;
for (DuMM::NonbondAtomIndex nax(0); nax < dumm.getNumNonbondAtoms();
++nax)
{ const DuMMAtom& a = dumm.getAtom(dumm.getAtomIndexOfNonbondAtom(nax));
const ChargedAtomType& atype = dumm.chargedAtomTypes[a.chargedAtomTypeIndex];
const AtomClass& aclass = dumm.atomClasses[atype.atomClassIx];
const Real charge = atype.partialCharge;
const Real sigma = 2*aclass.vdwRadius*DuMM::Radius2Sigma;
const Real wellDepth = aclass.vdwWellDepth;
// Define particle; particle number will be the same as our
// nonbond index number.
nonbondedForce->addParticle(sqrtCoulombScale*charge, sigma,
dumm.vdwGlobalScaleFactor*wellDepth);
// Collect 1-2 bonds to other nonbond atoms. Note that we
// don't care about bodies here -- every atom is considered
// independent.
for (unsigned short i=0; i < a.bond12.size(); ++i) {
const DuMMAtom& b = dumm.getAtom(a.bond12[i]);
if (!b.nonbondAtomIndex.isValid()) continue;
ommBonds.push_back(std::pair<int,int>(nax,b.nonbondAtomIndex));
}
}
// Register all the 1-2 bonds between nonbond atoms for scaling.
nonbondedForce->createExceptionsFromBonds
(ommBonds, dumm.coulombScale14, dumm.vdwScale14);
// System takes over heap ownership of the force.
openMMSystem->addForce(nonbondedForce);
}
// GBSA //
if (dumm.gbsaGlobalScaleFactor != 0) {
OpenMM::GBSAOBCForce* GBSAOBCForce = new OpenMM::GBSAOBCForce();
GBSAOBCForce->setSolventDielectric(dumm.gbsaSolventDielectric);
GBSAOBCForce->setSoluteDielectric(dumm.gbsaSoluteDielectric);
// Watch the units here. OpenMM works exclusively in MD (nm, kJ/mol).
// CPU GBSA uses Angstrom, kCal/mol.
for (DuMM::NonbondAtomIndex nax(0); nax < dumm.getNumNonbondAtoms();
++nax)
{ GBSAOBCForce->addParticle(dumm.gbsaAtomicPartialCharges[nax],
dumm.gbsaRadii[nax]*OpenMM::NmPerAngstrom,
dumm.gbsaObcScaleFactors[nax]);
}
// System takes over heap ownership of the force.
openMMSystem->addForce(GBSAOBCForce);
}
// OpenMM CONTEXT //
const std::vector<std::string> pluginsLoaded =
OpenMM::Platform::loadPluginsFromDirectory(OpenMM::Platform::getDefaultPluginsDirectory());
logMessages.push_back("NOTE: Loaded " + String(pluginsLoaded.size()) + " OpenMM plugins:");
for (unsigned i=0; i < pluginsLoaded.size(); ++i)
logMessages.back() += " " + pluginsLoaded[i];
const int nPlatforms = OpenMM::Platform::getNumPlatforms();
logMessages.push_back("NOTE: OpenMM has " + String(nPlatforms) + " Platforms registered: ");
for (int i = 0; i < nPlatforms; ++i) {
const OpenMM::Platform& platform = OpenMM::Platform::getPlatform(i);
logMessages.back() += " " + platform.getName();
}
// This is just a dummy to keep OpenMM happy; we're not using it for anything
// so it doesn't matter what kind of integrator we pick.
openMMIntegrator = new OpenMM::VerletIntegrator(0.1);
openMMContext = new OpenMM::Context(*openMMSystem, *openMMIntegrator);
const std::string pname = openMMContext->getPlatform().getName();
const double speed = openMMContext->getPlatform().getSpeed();
if (speed <= 1 && !allowReferencePlatform) {
logMessages.push_back(
"WARNING: DuMM: OpenMM not used: best available platform was "
+ pname + " with relative speed=" + String(speed)
+ ".\nCall setAllowOpenMMReference() if you want to use this anyway.\n");
deleteOpenMM();
return "";
}
return openMMContext->getPlatform().getName();
}
catch (const std::exception& e) {
logMessages.push_back(std::string("ERROR: OpenMM error during initialization: ") + e.what());
deleteOpenMM();
return "";
}
catch (...) {
logMessages.push_back("ERROR: Unknown exception during OpenMM initialization.");
deleteOpenMM();
return "";
}
}
//-----------------------------------------------------------------------------
// calcOpenMMNonbondedAndGBSAForces
//-----------------------------------------------------------------------------
void OpenMMInterface::calcOpenMMNonbondedAndGBSAForces
(const Vector_<Vec3>& includedAtomStation_G,
const Vector_<Vec3>& includedAtomPos_G,
bool wantForces,
bool wantEnergy,
Vector_<SpatialVec>& includedBodyForces_G,
Real& energy) const
{
assert(includedAtomStation_G.size() == dumm.getNumIncludedAtoms());
assert(includedAtomPos_G.size() == dumm.getNumIncludedAtoms());
assert(includedBodyForces_G.size() == dumm.getNumIncludedBodies());
if (!(wantForces || wantEnergy))
return;
if (!openMMContext)
throw std::runtime_error("ERROR: calcOpenMMNonbondedAndGBSAForces(): OpenMM has not been initialized.");
// Positions arrive in an array of all included atoms. Compress that down
// to just nonbond atoms and convert to OpenMM Vec3 type.
std::vector<OpenMM::Vec3> positions(dumm.getNumNonbondAtoms());
for (DuMM::NonbondAtomIndex nax(0); nax < dumm.getNumNonbondAtoms(); ++nax)
{ const Vec3& pos =
includedAtomPos_G[dumm.getIncludedAtomIndexOfNonbondAtom(nax)];
positions[nax] = OpenMM::Vec3(pos[0], pos[1], pos[2]); }
openMMContext->setPositions(positions);
// Ask for energy, forces, or both.
const OpenMM::State openMMState =
openMMContext->getState( (wantForces?OpenMM::State::Forces:0)
| (wantEnergy?OpenMM::State::Energy:0));
if (wantForces) {
const std::vector<OpenMM::Vec3>& openMMForces = openMMState.getForces();
for (DuMM::NonbondAtomIndex nax(0); nax < dumm.getNumNonbondAtoms();
++nax)
{ const DuMM::IncludedAtomIndex iax =
dumm.getIncludedAtomIndexOfNonbondAtom(nax);
const IncludedAtom& a = dumm.getIncludedAtom(iax);
const DuMMIncludedBodyIndex ibx = a.inclBodyIndex;
const OpenMM::Vec3& ommForce = openMMForces[nax];
const Vec3 f(ommForce[0], ommForce[1], ommForce[2]);
includedBodyForces_G[ibx] +=
SpatialVec(includedAtomStation_G[iax] % f, f);
}
}
if (wantEnergy)
energy += openMMState.getPotentialEnergy();
}
| 45.599407 | 113 | 0.573437 | MadCatX |
2f736a6ce93bac0581e2d3fe130792a513fccd8e | 277 | cpp | C++ | 5.14/5_14.cpp | dengxianglong/cplusplusprimerplusstudy | eefc5d7bf5ab31186c04171fadade3552838f4b2 | [
"MIT"
] | null | null | null | 5.14/5_14.cpp | dengxianglong/cplusplusprimerplusstudy | eefc5d7bf5ab31186c04171fadade3552838f4b2 | [
"MIT"
] | null | null | null | 5.14/5_14.cpp | dengxianglong/cplusplusprimerplusstudy | eefc5d7bf5ab31186c04171fadade3552838f4b2 | [
"MIT"
] | 1 | 2018-08-29T07:40:20.000Z | 2018-08-29T07:40:20.000Z | #include<iostream>
#include<ctime>
int main()
{
using namespace std;
cout<<"Enter the time of seconds";
float secs;
cin>>secs;
clock_t delay=secs*CLOCKS_PER_SEC;
cout<<"starting\a\n";
clock_t start=clock();
while(clock()-start<delay)
;
cout<<"done\a\n";
return 0;
} | 17.3125 | 35 | 0.685921 | dengxianglong |
2f74f7047801223f3c2f19e655a7f430ae9e28f9 | 6,947 | cpp | C++ | source/tm/pokemon/substitute.cpp | davidstone/technical-machine | fea3306e58cd026846b8f6c71d51ffe7bab05034 | [
"BSL-1.0"
] | 7 | 2021-03-05T16:50:19.000Z | 2022-02-02T04:30:07.000Z | source/tm/pokemon/substitute.cpp | davidstone/technical-machine | fea3306e58cd026846b8f6c71d51ffe7bab05034 | [
"BSL-1.0"
] | 47 | 2021-02-01T18:54:23.000Z | 2022-03-06T19:06:16.000Z | source/tm/pokemon/substitute.cpp | davidstone/technical-machine | fea3306e58cd026846b8f6c71d51ffe7bab05034 | [
"BSL-1.0"
] | 1 | 2021-01-28T13:10:41.000Z | 2021-01-28T13:10:41.000Z | // Copyright David Stone 2020.
// 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 <tm/pokemon/substitute.hpp>
#include <tm/move/moves.hpp>
#include <tm/move/target.hpp>
#include <tm/generation.hpp>
namespace technicalmachine {
namespace {
auto target_based(Generation const generation, Moves const move) {
switch (move_target(generation, move)) {
case Target::user:
case Target::all_allies:
case Target::adjacent_ally:
case Target::user_team:
case Target::user_field:
case Target::foe_field:
case Target::all:
case Target::field:
return Substitute::bypassed;
case Target::adjacent_foe:
case Target::all_adjacent_foes:
case Target::adjacent:
case Target::any:
case Target::all_adjacent:
return Substitute::absorbs;
case Target::user_or_adjacent_ally:
// TODO: Generation 5 allows it only when used on itself
return generation <= Generation::four ?
Substitute::causes_failure :
Substitute::bypassed;
}
}
constexpr auto gen1_substitute_interaction(Moves const move) {
switch (move) {
case Moves::Disable:
case Moves::Leech_Seed:
case Moves::Super_Fang:
case Moves::Transform:
case Moves::Bind:
case Moves::Clamp:
case Moves::Fire_Spin:
case Moves::Wrap:
return Substitute::bypassed;
default:
return target_based(Generation::one, move);
}
}
constexpr auto gen2_substitute_interaction(Moves const move) {
// Fails if user has Substitute
#if 0
case Moves::Counter:
case Moves::Mirror_Coat:
case Moves::Protect:
case Moves::Detect:
case Moves::Endure:
}
#endif
// Partially blocked
#if 0
switch (move) {
case Moves::Curse: (Ghost, effect only)
case Moves::Swagger: (confusion only)
}
#endif
// Cancel partial trap
// Boost Rage even if Substitute hit
switch (move) {
case Moves::Attract:
case Moves::Disable:
case Moves::Encore:
case Moves::Foresight:
case Moves::Mean_Look:
case Moves::Mimic:
case Moves::Psych_Up:
case Moves::Roar:
case Moves::Spider_Web:
case Moves::Spite:
case Moves::Transform:
case Moves::Whirlwind:
return Substitute::bypassed;
case Moves::Absorb:
case Moves::Dream_Eater:
case Moves::Giga_Drain:
case Moves::Leech_Life:
case Moves::Mega_Drain:
return Substitute::causes_failure;
default:
return target_based(Generation::two, move);
}
}
constexpr auto gen3_substitute_interaction(Moves const move) {
// Fails
#if 0
switch (move) {
case Moves::Curse: (Ghost, effect only)
}
#endif
// Block Intimidate
// Absorb Uproar
switch (move) {
case Moves::Attract:
case Moves::Disable:
case Moves::Encore:
case Moves::Foresight:
case Moves::Odor_Sleuth:
case Moves::Psych_Up:
case Moves::Roar:
case Moves::Role_Play:
case Moves::Skill_Swap:
case Moves::Spite:
case Moves::Taunt:
case Moves::Tickle:
case Moves::Torment:
case Moves::Transform:
case Moves::Whirlwind:
return Substitute::bypassed;
case Moves::Dream_Eater:
return Substitute::causes_failure;
default:
return target_based(Generation::three, move);
}
}
constexpr auto gen4_substitute_interaction(Moves const move) {
// Fails
#if 0
switch (move) {
case Moves::Curse: (Ghost, effect only)
}
#endif
// Block Intimidate
// Block confusion from berries
// Blocks Intimidate even if U-turn breaks the Substitute
// Blocks Toxic Spikes poisoning
// Defog doesn't lower evasiveness
// Absorb Uproar
switch (move) {
case Moves::Attract:
case Moves::Disable:
case Moves::Encore:
case Moves::Foresight:
case Moves::Guard_Swap:
case Moves::Heart_Swap:
case Moves::Miracle_Eye:
case Moves::Odor_Sleuth:
case Moves::Power_Swap:
case Moves::Psych_Up:
case Moves::Roar:
case Moves::Role_Play:
case Moves::Skill_Swap:
case Moves::Spite:
case Moves::Taunt:
case Moves::Torment:
case Moves::Transform:
case Moves::Whirlwind:
return Substitute::bypassed;
case Moves::Dream_Eater:
return Substitute::causes_failure;
default:
return target_based(Generation::four, move);
}
}
constexpr auto gen5_substitute_interaction(Moves const move) {
// Block Intimidate
// Block Imposter
// Absorb Uproar
switch (move) {
case Moves::After_You:
case Moves::Attract:
case Moves::Conversion_2:
case Moves::Disable:
case Moves::Encore:
case Moves::Foresight:
case Moves::Guard_Swap:
case Moves::Heart_Swap:
case Moves::Miracle_Eye:
case Moves::Odor_Sleuth:
case Moves::Power_Swap:
case Moves::Psych_Up:
case Moves::Reflect_Type:
case Moves::Roar:
case Moves::Role_Play:
case Moves::Skill_Swap:
case Moves::Spite:
case Moves::Taunt:
case Moves::Torment:
case Moves::Whirlwind:
return Substitute::bypassed;
default:
return target_based(Generation::five, move);
}
}
constexpr auto latest_substitute_interaction(Generation const generation, Moves const move) {
// Block Intimidate
// Block Imposter
// Absorb Uproar
switch (move) {
case Moves::After_You:
case Moves::Attract:
case Moves::Bestow:
case Moves::Boomburst:
case Moves::Bug_Buzz:
case Moves::Chatter:
case Moves::Clanging_Scales:
case Moves::Clangorous_Soulblaze:
case Moves::Confide:
case Moves::Conversion_2:
case Moves::Disable:
case Moves::Disarming_Voice:
case Moves::Echoed_Voice:
case Moves::Encore:
case Moves::Foresight:
case Moves::Grass_Whistle:
case Moves::Growl:
case Moves::Guard_Swap:
case Moves::Heart_Swap:
case Moves::Hyperspace_Fury:
case Moves::Hyperspace_Hole:
case Moves::Hyper_Voice:
case Moves::Instruct:
case Moves::Metal_Sound:
case Moves::Miracle_Eye:
case Moves::Noble_Roar:
case Moves::Odor_Sleuth:
case Moves::Parting_Shot:
case Moves::Play_Nice:
case Moves::Powder:
case Moves::Power_Swap:
case Moves::Psych_Up:
case Moves::Reflect_Type:
case Moves::Relic_Song:
case Moves::Roar:
case Moves::Role_Play:
case Moves::Round:
case Moves::Screech:
case Moves::Sing:
case Moves::Skill_Swap:
case Moves::Snarl:
case Moves::Snore:
case Moves::Sparkling_Aria:
case Moves::Spectral_Thief:
case Moves::Speed_Swap:
case Moves::Spite:
case Moves::Supersonic:
case Moves::Taunt:
case Moves::Torment:
case Moves::Whirlwind:
return Substitute::bypassed;
default:
return target_based(generation, move);
}
}
} // namespace
auto substitute_interaction(Generation const generation, Moves const move) -> Substitute::Interaction {
switch (generation) {
case Generation::one: return gen1_substitute_interaction(move);
case Generation::two: return gen2_substitute_interaction(move);
case Generation::three: return gen3_substitute_interaction(move);
case Generation::four: return gen4_substitute_interaction(move);
case Generation::five: return gen5_substitute_interaction(move);
default: return latest_substitute_interaction(generation, move);
}
}
} // namespace technicalmachine
| 24.810714 | 103 | 0.727508 | davidstone |
2f7beda12553d4f4497978504718c5f2d671ed2e | 1,462 | hpp | C++ | input/InputHandler.hpp | CaDS-Studentprojects/PixelGames | a1d7b57bdd9699fc36a64f8a86b92fbd61a3c3df | [
"MIT"
] | null | null | null | input/InputHandler.hpp | CaDS-Studentprojects/PixelGames | a1d7b57bdd9699fc36a64f8a86b92fbd61a3c3df | [
"MIT"
] | null | null | null | input/InputHandler.hpp | CaDS-Studentprojects/PixelGames | a1d7b57bdd9699fc36a64f8a86b92fbd61a3c3df | [
"MIT"
] | null | null | null | /*
* InputHandler.hpp
*
* Created on: Mar 5, 2018
* Author: daniel
*/
#ifndef INPUTHANDLER_HPP_
#define INPUTHANDLER_HPP_
#include <iostream>
#include <thread>
#include <memory>
//#include <ncurses.h>
#include "Input.hpp"
using namespace std;
namespace pixelgames {
namespace input {
class InputHandler {
public:
InputHandler(atomic<Input> & player_input)
: player_input_ { player_input }, the_thread_() {
}
~InputHandler() {
isRunning_ = false;
if (the_thread_.joinable()) the_thread_.join();
}
void start() {
isRunning_ = true;
the_thread_ = std::thread(&InputHandler::ThreadMain, this);
}
private:
atomic<Input>& player_input_;
thread the_thread_;
bool isRunning_ = false;
void ThreadMain() {
// initscr();
// printw("Hi!\n");
// refresh();
while (isRunning_) {
char c; // = getchar();
cin >> c;
Input action = c == 'w' ? Input::UP : c == 's' ? Input::DOWN : c == 'a' ? Input::LEFT :
c == 'd' ? Input::RIGHT : Input::COUNT;
if(action == Input::COUNT){
isRunning_ = false;
}
player_input_.store(action);
// Do something useful, e.g:
//std::this_thread::sleep_for( std::chrono::seconds(1) );
}
cout << "Bye!" << endl;
}
};
} /* namespace input */
} /* namespace pixelgames */
#endif /* INPUTHANDLER_HPP_ */
| 19.756757 | 95 | 0.559508 | CaDS-Studentprojects |
2f7cc82989ef7d05398699e3de5904c6d30beaa0 | 7,505 | cpp | C++ | wpb_mani_bringup/src/wpb_mani_dummy.cpp | 6-robot/wpb_mani | 6aa6e2d8713c8d018a422e4665ff8fcd7e299ad0 | [
"BSD-3-Clause"
] | 4 | 2021-02-08T03:55:26.000Z | 2021-12-13T12:06:34.000Z | wpb_mani_bringup/src/wpb_mani_dummy.cpp | 6-robot/wpb_mani | 6aa6e2d8713c8d018a422e4665ff8fcd7e299ad0 | [
"BSD-3-Clause"
] | null | null | null | wpb_mani_bringup/src/wpb_mani_dummy.cpp | 6-robot/wpb_mani | 6aa6e2d8713c8d018a422e4665ff8fcd7e299ad0 | [
"BSD-3-Clause"
] | 1 | 2021-06-08T01:17:54.000Z | 2021-06-08T01:17:54.000Z | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2017-2020, Waterplus http://www.6-robot.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the WaterPlus nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* FOOTPRINTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/*!******************************************************************
@author ZhangWanjie
********************************************************************/
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <geometry_msgs/Pose2D.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/JointState.h>
#include <std_msgs/String.h>
#include <std_msgs/Float64.h>
#include <actionlib/server/simple_action_server.h>
#include <control_msgs/FollowJointTrajectoryAction.h>
#include <control_msgs/GripperCommandAction.h>
#include <math.h>
static int arManiPos[5];
static int arManiSpeed[5];
static float arFakeJointPos[10];
static float arTargetJointPos[10];
static double kAngleToDegree = 18000/3.1415926;
void JointCtrlCallback(const sensor_msgs::JointState::ConstPtr& msg)
{
std_msgs::Float64 joint_pos_msg;
int nNumJoint = msg->position.size();
for(int i=0;i<nNumJoint;i++)
{
if(msg->name[i] == "joint1")
{
arTargetJointPos[6] = msg->position[i];
}
if(msg->name[i] == "joint2")
{
arTargetJointPos[7] = msg->position[i];
}
if(msg->name[i] == "joint3")
{
arTargetJointPos[8] = msg->position[i];
}
if(msg->name[i] == "joint4")
{
arTargetJointPos[9] = msg->position[i];
}
if(msg->name[i] == "gripper")
{
//arTargetJointPos[10] = msg->position[i];
}
}
ROS_INFO("------------------------------");
for(int i=0;i<nNumJoint;i++)
{
ROS_INFO("[wpb_mani] %d - %s = %.2f vel= %.2f ctlr= %d", i, msg->name[i].c_str(),msg->position[i],msg->velocity[i],arManiPos[i]);
}
ROS_INFO("------------------------------");
}
typedef actionlib::SimpleActionServer<control_msgs::FollowJointTrajectoryAction> TrajectoryServer;
// 响应 Move_Group 的轨迹执行
void executeTrajectory(const control_msgs::FollowJointTrajectoryGoalConstPtr& goal, TrajectoryServer* as)
{
int nrOfPoints = goal->trajectory.points.size();
ROS_WARN("Trajectory with %d positions received ", nrOfPoints);
int nExecIndex = nrOfPoints - 1;
int nPos = goal->trajectory.points[nExecIndex].positions.size();
ROS_WARN("Num of Joints = %d ", nPos);
if(nPos > 5) nPos = 5;
for(int i=0;i<nPos;i++)
{
arTargetJointPos[i+6] = goal->trajectory.points[nExecIndex].positions[i];
}
as->setSucceeded();
}
typedef actionlib::SimpleActionServer<control_msgs::GripperCommandAction> GripperServer;
// 响应 GripperCommand 回调函数
void executeGripper(const control_msgs::GripperCommandGoalConstPtr & goal, GripperServer* as)
{
float gapSize = goal->command.position;
float maxEffort = goal->command.max_effort;
// 执行指令
as->setSucceeded();
}
int main(int argc, char** argv)
{
ros::init(argc,argv,"wpb_mani_dummy");
ros::NodeHandle n;
ros::Subscriber mani_ctrl_sub = n.subscribe("/wpb_mani/joint_ctrl",30,&JointCtrlCallback);
TrajectoryServer tserver(n, "wpb_mani_controller/follow_joint_trajectory", boost::bind(&executeTrajectory, _1, &tserver), false);
ROS_INFO("TrajectoryActionServer: Starting");
tserver.start();
GripperServer gserver(n, "wpb_mani_gripper_controller/gripper_command", boost::bind(&executeGripper, _1, &gserver), false);
ROS_INFO("GripperActionServer: Starting");
gserver.start();
ros::Time current_time, last_time;
current_time = ros::Time::now();
last_time = ros::Time::now();
ros::Rate r(30.0);
ros::Publisher joint_state_pub = n.advertise<sensor_msgs::JointState>("/joint_states",100);
sensor_msgs::JointState joint_msg;
std::vector<std::string> joint_name(11);
std::vector<double> joint_pos(11);
for(int i=0;i<5;i++)
{
arManiPos[i] = 0;
arManiSpeed[i] = 2000;
}
for(int i=0;i<11;i++)
{
arFakeJointPos[i] = 0;
arTargetJointPos[i] = 0;
}
ros::NodeHandle n_param("~");
joint_name[0] = "front_left_wheel_joint";
joint_name[1] = "front_right_wheel_joint";
joint_name[2] = "back_right_wheel_joint";
joint_name[3] = "back_left_wheel_joint";
joint_name[4] = "kinect_height";
joint_name[5] = "kinect_pitch";
joint_name[6] = "joint1";
joint_name[7] = "joint2";
joint_name[8] = "joint3";
joint_name[9] = "joint4";
joint_name[10] = "gripper";
joint_pos[0] = 0.0f;
joint_pos[1] = 0.0f;
joint_pos[2] = 0.0f;
joint_pos[3] = 0.0f;
joint_pos[4] = 0.0f;
joint_pos[5] = -0.3f;
joint_pos[6] = 0.0f;
joint_pos[7] = 0.0f;
joint_pos[8] = 0.0f;
joint_pos[9] = 0.0f;
joint_pos[10] = 0.0f;
n_param.getParam("zeros/kinect_height", joint_pos[4]);
n_param.getParam("zeros/kinect_pitch", joint_pos[5]);
while(n.ok())
{
float step = 0.01;
for(int i=0;i<11;i++)
{
if(arFakeJointPos[i] < arTargetJointPos[i])
{
arFakeJointPos[i] += step;
}
if(arFakeJointPos[i] > arTargetJointPos[i])
{
arFakeJointPos[i] -= step;
}
}
joint_msg.header.stamp = ros::Time::now();
joint_msg.header.seq ++;
// wheels tf
for(int i=0;i<4;i++)
{
joint_pos[i] = arFakeJointPos[i];
}
// mani tf
for(int i=0;i<5;i++)
{
joint_pos[i+6] = arFakeJointPos[i+6];
}
joint_msg.name = joint_name;
joint_msg.position = joint_pos;
joint_state_pub.publish(joint_msg);
// ROS_WARN("mani pos pub");
ros::spinOnce();
r.sleep();
}
}
| 33.959276 | 139 | 0.619853 | 6-robot |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.