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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9e8c703ae1d7d8bcea11268ca5310dfacee4ce95
| 5,557
|
cc
|
C++
|
sentinel-core/param/param_flow_slot_test.cc
|
windrunner123/sentinel-cpp
|
7957e692466db0b7b83b7218602757113e9f2d22
|
[
"Apache-2.0"
] | 121
|
2019-02-22T06:50:31.000Z
|
2022-01-22T23:23:42.000Z
|
sentinel-core/param/param_flow_slot_test.cc
|
windrunner123/sentinel-cpp
|
7957e692466db0b7b83b7218602757113e9f2d22
|
[
"Apache-2.0"
] | 24
|
2019-05-07T08:58:38.000Z
|
2022-01-26T02:36:06.000Z
|
sentinel-core/param/param_flow_slot_test.cc
|
windrunner123/sentinel-cpp
|
7957e692466db0b7b83b7218602757113e9f2d22
|
[
"Apache-2.0"
] | 36
|
2019-03-19T09:46:08.000Z
|
2021-11-24T13:20:56.000Z
|
#include <iostream>
#include <memory>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "sentinel-core/test/mock/statistic/node/mock.h"
#include "sentinel-core/common/string_resource_wrapper.h"
#include "sentinel-core/param/param_flow_rule_constants.h"
#include "sentinel-core/param/param_flow_slot.h"
using testing::_;
using testing::InSequence;
using testing::Mock;
using testing::Return;
namespace Sentinel {
namespace Slot {
TEST(ParamFlowSlotTest, ParamFlowControlSingleThreadIntegrationTest) {
Sentinel::Log::Logger::InitDefaultLogger();
std::string resourceName{"testResource"};
std::string anotherResourceName{"anotherTestResource"};
EntryContextSharedPtr context =
std::make_shared<EntryContext>("test_context");
Stat::NodeSharedPtr uselessNode = std::make_shared<Stat::MockNode>();
auto resource =
std::make_shared<StringResourceWrapper>(resourceName, EntryType::OUT);
auto entry = std::make_shared<Entry>(resource, context);
entry->set_cur_node(uselessNode);
std::vector<absl::any> myParams;
ParamFlowSlot slot;
{
// Pass since no rule exists.
auto result = slot.Entry(entry, resource, uselessNode, 1000, 0, myParams);
EXPECT_EQ(TokenStatus::RESULT_STATUS_OK, result->status());
}
Param::ParamFlowRule rule0{resourceName}, rule1{resourceName},
rule2{anotherResourceName}, rule3{resourceName}, rule4{resourceName};
rule0.set_metric_type(Param::ParamFlowMetricType::kQps);
rule0.set_param_idx(0);
rule0.set_threshold(10);
rule0.set_interval_in_ms(5000); // limit 10 Qs in 5s, QPS=2
Param::ParamFlowItem item0(78, Param::ParamItemType::kInt32, 100);
rule0.set_param_flow_item_list({item0});
rule1.set_param_idx(1);
rule1.set_threshold(1);
rule1.set_metric_type(
Param::ParamFlowMetricType::kThreadCount); // limit 10 Qs in 5s, QPS=2
// rule2 should not work (resource name not match)
rule2.set_param_idx(1);
rule2.set_threshold(1);
rule2.set_metric_type(Param::ParamFlowMetricType::kQps);
// rule3 and rule4 are neither valid rule
rule3.set_param_idx(1);
rule3.set_threshold(-1);
rule3.set_metric_type(Param::ParamFlowMetricType::kQps);
rule4.set_param_idx(1);
rule4.set_threshold(1);
rule4.set_sample_count(0);
rule4.set_metric_type(Param::ParamFlowMetricType::kQps);
Param::ParamFlowRuleManager& m = Param::ParamFlowRuleManager::GetInstance();
m.LoadRules({rule0, rule1, rule2, rule3, rule4});
EXPECT_EQ(m.GetRuleOfResource(resourceName)->size(), 2);
EXPECT_EQ(m.GetRuleOfResource(anotherResourceName)->size(), 1);
myParams.push_back(15213);
// NOTE: If the time of invoking Add and Get of counter are unluckly in two
// different windows, the test will fail. Longer window interval can reduce
// but not eliminate this possibility.
// If this occurs, retry until the test passes...
{
EXPECT_EQ(
TokenStatus::RESULT_STATUS_OK,
slot.Entry(entry, resource, uselessNode, 9, 0, myParams)->status());
slot.GetParamMetric(resource->name())->AddPass(9, myParams);
EXPECT_EQ(
TokenStatus::RESULT_STATUS_BLOCKED,
slot.Entry(entry, resource, uselessNode, 2, 0, myParams)->status());
EXPECT_EQ(slot.GetParamMetric(resource->name())
->PassInterval(rule0.metric_key(), myParams[0]),
9);
EXPECT_EQ(slot.GetParamMetric(resource->name())
->BlockInterval(rule0.metric_key(), myParams[0]),
2);
myParams.pop_back();
EXPECT_EQ(
TokenStatus::RESULT_STATUS_OK,
slot.Entry(entry, resource, uselessNode, 100, 0, myParams)->status());
EXPECT_EQ(slot.GetParamMetric(resource->name())
->PassInterval(rule0.metric_key(), 15213),
9);
EXPECT_EQ(slot.GetParamMetric(resource->name())
->BlockInterval(rule0.metric_key(), 15213),
2);
}
{ // Exception hot item rule
myParams.push_back(78);
EXPECT_EQ(
TokenStatus::RESULT_STATUS_OK,
slot.Entry(entry, resource, uselessNode, 50, 0, myParams)->status());
slot.GetParamMetric(resource->name())->AddPass(50, myParams);
EXPECT_EQ(
TokenStatus::RESULT_STATUS_OK,
slot.Entry(entry, resource, uselessNode, 50, 0, myParams)->status());
EXPECT_EQ(
TokenStatus::RESULT_STATUS_BLOCKED,
slot.Entry(entry, resource, uselessNode, 51, 0, myParams)->status());
myParams.pop_back();
}
{ // thread limit
myParams.push_back(13239);
myParams.push_back(std::string("justAnExample"));
EXPECT_EQ(
TokenStatus::RESULT_STATUS_OK,
slot.Entry(entry, resource, uselessNode, 1, 0, myParams)->status());
slot.GetParamMetric(resource->name())->AddThreadCount(myParams);
// Blocked due to thread count exceeded on idx 1
EXPECT_EQ(
TokenStatus::RESULT_STATUS_BLOCKED,
slot.Entry(entry, resource, uselessNode, 1, 0, myParams)->status());
EXPECT_EQ(1, slot.GetParamMetric(resource->name())
->GetThreadCount(1, std::string("justAnExample")));
slot.GetParamMetric(resource->name())->DecreaseThreadCount(myParams);
EXPECT_EQ(0, slot.GetParamMetric(resource->name())
->GetThreadCount(1, std::string("justAnExample")));
// Pass since value on idx 1 has changed
myParams[1] = std::string("anotherExample");
EXPECT_EQ(
TokenStatus::RESULT_STATUS_OK,
slot.Entry(entry, resource, uselessNode, 1, 0, myParams)->status());
}
}
} // namespace Slot
} // namespace Sentinel
| 37.046667
| 78
| 0.694799
|
windrunner123
|
9e8e932f9499023181266c4a013edff4dfdf28d0
| 6,762
|
cpp
|
C++
|
STRIPSp.cpp
|
alexandresoaresilva/STRIPS_prg
|
ada84083a8b4f96036261669092bcf3cb4539e73
|
[
"MIT"
] | null | null | null |
STRIPSp.cpp
|
alexandresoaresilva/STRIPS_prg
|
ada84083a8b4f96036261669092bcf3cb4539e73
|
[
"MIT"
] | null | null | null |
STRIPSp.cpp
|
alexandresoaresilva/STRIPS_prg
|
ada84083a8b4f96036261669092bcf3cb4539e73
|
[
"MIT"
] | null | null | null |
/*
* STRIPSp.cpp
*
* Created on: Jan 10, 2018
* Author: alexa
*/
#include "STRIPSp.h"
STRIPSp::STRIPSp() : STRIPS_tokenizer(), it_is_a_STRIPS_planner(0) {
cout << endl;
cout << "STRIPSp (recognizer) class\n";
cout << ">>>>>>>>>>>>>>>>>>>>>>\n";
STRIPS_tokenizer::print_Vector_of_strg();
it_is_a_STRIPS_planner = STRIPS_program(STRIPS_tokenizer::getVectStrg_Tokenized_STRIPS());
printIsItASTRIPS_planner();
// TODO Auto-generated constructor stub
}
STRIPSp::~STRIPSp() {
// TODO Auto-generated destructor stub
}
void STRIPSp::printIsItASTRIPS_planner(){
if (it_is_a_STRIPS_planner)
cout << "STRIPS planner\n";
else
cout << "NOT a STRIPS planner\n";
}
vector<string> STRIPSp::slice(const vector<string> &s, uint32_t loBound, uint32_t upBound) {
vector<string> sliced;
for (auto i = loBound; i < upBound; i++)
sliced.push_back(s[i]);
return sliced;
}
bool STRIPSp::STRIPS_keyword(const vector<string> &s) {//s needs to be sliced to be used in here
if ( !s.empty()
&& ( s.size() == 1 )
&& ( s[0] == "Initial"
|| s[0] == "state"
|| s[0] == "Goal"
|| s[0] == "Actions"
|| s[0] == "Preconditions"
|| s[0] == "Effects"
|| s[0] == "not"
|| s[0] == "NOT" ) ) //end of if
return true;
return false;
}
bool STRIPSp::symbol(const vector<string> &s) {
return( !s.empty()
&& ( s.size() == 1)
&& !STRIPS_keyword(s) ); //end of return
}
bool STRIPSp::NEsymbol_list(const vector<string> &s) {
if (s.size() == 1 && symbol(slice(s, 0, 1)))
return true;
else if (s.size() >= 3 && symbol(slice(s, 0, 1)) && s[1] == ",")
if ( NEsymbol_list(slice(s, 2, s.size())) )
return true;
return false;
}
bool STRIPSp::symbol_list(const vector<string> &s) {// I don't know if this will actually work
return (s.empty() || NEsymbol_list(s));
}
bool STRIPSp::atomic_statement(const vector<string> &s) {
if (s.size() >= 4)
if (symbol(slice(s, 0, 1)) && s[1] == "(" && s[s.size() - 1] == ")")
if (symbol_list(slice(s, 2, s.size() - 1)))return true;
return false;
}
bool STRIPSp::NEatom_list(const vector<string> &s) {
if (atomic_statement(s)) return true;
else {
for (uint32_t i = 1; i < (s.size() - 1); i++) {
if (s[i] == ",")
if (atomic_statement(slice(s, 0, i)) && NEatom_list(slice(s, i + 1, s.size())))return true;
}
}
return false;
}
bool STRIPSp::atom_list(const vector<string> &s) {// I don't know if this will actually work
for (uint32_t i = 1; i < s.size(); i++) {
if (s.empty() || NEatom_list(s))
return true;
}
return false;
}
bool STRIPSp::literal(const vector<string> &s) {// I don't know if this will actually work
if (atomic_statement(s))return true;
else if (s.size()>0 && (s[0] == "not" || s[0] == "NOT") && atomic_statement(slice(s, 1, s.size())))
return true;
return false;
}
bool STRIPSp::NEliteral_list(const vector<string> &s) {//might need adjustment in loop condition i <=
if (literal(s))return true;
else
for (uint32_t i = 1; i < (s.size() - 1); i++)
if (s[i] == ",")
if (literal(slice(s, 0, i)) && NEliteral_list(slice(s, i + 1, s.size())))return true;
return false;
}
bool STRIPSp::literal_list(const vector<string> &s) {// I don't know if this will actually work
for (uint32_t i = 1; i < s.size(); i++) {
if (s.empty() || NEliteral_list(s))
return true;
}
return false;
}
bool STRIPSp::action_prototype(const vector<string> &s) {
if (s[0] == "_" && s[s.size() - 1] == "_")
if (atomic_statement(slice(s, 1, s.size() - 1)))return true;
return false;
}
bool STRIPSp::effects_declaration(const vector<string> &s) {
if (s.size()>1 && (s[0] == "Effects" && s[1] == ":")) //instead of postconditions
if (literal_list(slice(s, 2, s.size())))return true;
return false;
}
bool STRIPSp::preconditions_declaration(const vector<string> &s) {
if (s.size()>1 && (s[0] == "Preconditions" && s[1] == ":"))
if (literal_list(slice(s, 2, s.size())))return true;
return false;
}
bool STRIPSp::action_declaration(const vector<string> &s) {
if (s.size() >= 3) {
for (uint32_t i = 1; i < s.size(); i++)
if (action_prototype(slice(s, 0, i)))
for (uint32_t j = 2; j < s.size(); j++) //they have to grow separatelly
if (preconditions_declaration(slice(s, i, j)) && effects_declaration(slice(s, j, s.size())))return true;
}
return false;
}
bool STRIPSp::NEaction_list(const vector<string> &s) {//might need adjustment in loop condition i <=
if (s.size()> 0)
{
if (action_declaration(s))return true;
else
{
for (uint32_t i = 1; i < s.size(); i++)
{
if (action_declaration(slice(s, 0, i)) && NEaction_list(slice(s, i, s.size())))return true;
}
}
}
return false;
}
bool STRIPSp::action_set(const vector<string> &s) {//might need adjustment in loop condition i <=
if (s.size() >= 3 && (s[0] == "Actions" && s[1] == ":"))
if (NEaction_list(slice(s, 2, s.size())))return true;
return false;
}
bool STRIPSp::initial_state_declaration(const vector<string> &s) {
if (s.size() >= 3) // size >= 3 to avoid crashing when testing smaller parts of the strips vector
if (s[0] == "Initial" && s[1] == "state" && s[2] == ":" && atom_list(slice(s, 3, s.size())))return true;
return false;
}
bool STRIPSp::goal_declaration(const vector<string> &s) {//NOTE: declaration on the Wikipedia's example is followed by "state"; here, it's not.
if (s.size() >= 2)
if (s[0] == "Goal" && s[1] == ":" && literal_list(slice(s, 2, s.size())))return true;
//if ( s[0] == "Goal" && s[1] == "state" && s[2] == ":" && literal_list(slice(s,3,s.size())) )return true; // WITH "state"
return false;
}
//MAIN function- starts the recursive descent calls
bool STRIPSp::STRIPS_program(const vector<string> &s) {
if (s.size() > 7) // minimum list: (0. "Initial", 1. "state", 2. ":", 3. "Goal",4. ":",5. "Actions",6. ":",7. NEaction_list)
{
int initStateEndIndex(0), goalDeclEndIndex(0);
bool initStateTrue(0), goalDeclTrue(0);
for (uint32_t i = 1; i < (s.size() - 4); i++) //so avoids the minimum list for Goal & Actions
if (initial_state_declaration(slice(s, 0, i)) && s[i] == "Goal") //i and NOT i+1 because slicing happens at i-1
{
initStateEndIndex = i;//it will evaluate to true before reaching
initStateTrue = 1;
break;
}
if (initStateTrue)
for (uint32_t j = initStateEndIndex; j < (s.size() - 2); j++) //s.size()-2 because "Actions",":",NEaction_list
if (goal_declaration(slice(s, initStateEndIndex, j)))
if (s[j] == "Actions")
{
goalDeclEndIndex = j;
goalDeclTrue = 1;
break;
}
if (initStateTrue && goalDeclTrue)
for (uint32_t z = goalDeclEndIndex; z < s.size(); z++)
if (action_set(slice(s, z, s.size())))return true;
}
return false;
}
| 30.876712
| 143
| 0.608104
|
alexandresoaresilva
|
9e8f825752174abf6cd0bdb9372978ddd55d4553
| 1,046
|
cpp
|
C++
|
Engine_Networking/source/NetworkBuffer.cpp
|
subr3v/s-engine
|
d77b9ccd0fff3982a303f14ce809691a570f61a3
|
[
"MIT"
] | 2
|
2016-04-01T21:10:33.000Z
|
2018-02-26T19:36:56.000Z
|
Engine_Networking/source/NetworkBuffer.cpp
|
subr3v/s-engine
|
d77b9ccd0fff3982a303f14ce809691a570f61a3
|
[
"MIT"
] | 1
|
2017-04-05T01:33:08.000Z
|
2017-04-05T01:33:08.000Z
|
Engine_Networking/source/NetworkBuffer.cpp
|
subr3v/s-engine
|
d77b9ccd0fff3982a303f14ce809691a570f61a3
|
[
"MIT"
] | null | null | null |
#include "NetworkBuffer.h"
#include <cassert>
FNetworkBuffer::FNetworkBuffer(u32 BufferSize) : BufferPosition(0)
{
BufferData.Resize(BufferSize);
}
FNetworkBuffer::~FNetworkBuffer()
{
}
void FNetworkBuffer::CopyData(void* Data, u32 BytesCount)
{
if (GetSpaceLeft() < BytesCount)
{
assert(false);
return;
}
memcpy(BufferData.Data(), Data, BytesCount);
IncreaseBytesCount(BytesCount);
}
void FNetworkBuffer::IncreaseBytesCount(u32 BytesCount)
{
BufferPosition += BytesCount;
}
void FNetworkBuffer::DecreaseByteCount(u32 BytesCount)
{
BufferPosition -= BytesCount;
memmove(BufferData.Data(), BufferData.Data() + BytesCount, BufferPosition);
}
void FNetworkBuffer::Reset()
{
BufferPosition = 0;
}
void* FNetworkBuffer::GetCurrentPointerData()
{
return BufferData.Data() + BufferPosition;
}
void* FNetworkBuffer::GetStartPointerData()
{
return BufferData.Data();
}
u32 FNetworkBuffer::GetTotalBytes() const
{
return BufferPosition;
}
u32 FNetworkBuffer::GetSpaceLeft() const
{
return BufferData.Size() - BufferPosition;
}
| 17.433333
| 76
| 0.755258
|
subr3v
|
9e8f85d4b9cb0db03ca88f48a9f304d3b0843d59
| 1,839
|
cpp
|
C++
|
acm-icpc/2015 ACM Amman Collegiate Programming Contest/D.cpp
|
ErickJoestar/competitive-programming
|
76afb766dbc18e16315559c863fbff19a955a569
|
[
"MIT"
] | 1
|
2020-04-23T00:35:38.000Z
|
2020-04-23T00:35:38.000Z
|
acm-icpc/2015 ACM Amman Collegiate Programming Contest/D.cpp
|
ErickJoestar/competitive-programming
|
76afb766dbc18e16315559c863fbff19a955a569
|
[
"MIT"
] | null | null | null |
acm-icpc/2015 ACM Amman Collegiate Programming Contest/D.cpp
|
ErickJoestar/competitive-programming
|
76afb766dbc18e16315559c863fbff19a955a569
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define ENDL '\n'
#define deb(u) cout << #u " : " << (u) << ENDL;
#define deba(alias, u) cout << alias << ": " << (u) << ENDL;
#define debp(u, v) cout << u << " : " << v << ENDL;
#define pb push_back
#define F first
#define S second
#define lli long long
#define pii pair<int, int>
#define pll pair<lli, lli>
#define ALL(a) (a).begin(), (a).end()
#define ALLR(a) (a).rbegin(), (a).rend()
#define FOR(i, a, n) for (int i = (a); i < (n); ++i)
#define FORN(i, a, n) for (int i = (a - 1); i >= (n); --i)
#define IO \
ios_base::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0)
using namespace std;
#define INF 1000;
int n, k;
string s;
vector<int> v;
vector<int> dp;
int solve(int cut)
{
if (dp[cut] != 0)
return dp[cut];
int ans = 0;
if (cut == n - 1)
ans = 0;
else if (cut + v[cut] >= n - 1 && v[cut] <= k)
ans = 0;
else if (v[cut] == 0)
{
ans = solve(cut + 1) + 1;
// cout << "PASS" << ENDL;
}
else
{
ans = INF;
FOR(i, 1, min(k, v[cut] + 1))
{
ans = min(ans, solve(cut + i) + 1);
}
}
// debp(cut, ans);
dp[cut] = ans;
return ans;
}
int main()
{
IO;
int t;
cin >> t;
while (t--)
{
cin >> n >> k >> s;
v = vector<int>(n, 0);
dp = vector<int>(2000, 0);
FORN(i, n - 1, 0)
{
if (s[i] == s[i + 1])
v[i] = v[i + 1] + 1;
}
// cout << ENDL;
// FOR(i, 0, n)
// cout << v[i] << " ";
// cout << ENDL;
int best = INF;
if (k == 1)
best = n - 1;
if (k >= n && v[0] > 0)
best = 0;
else
FOR(i, 0, min(k, v[0] + 1))
{
// debp(i, solve(i));
best = min(best, solve(i));
}
cout << best << ENDL;
}
return 0;
}
/*
4
6 3
111000
5 2
11010
3 3
110
3 3
101
*/
| 18.029412
| 60
| 0.439913
|
ErickJoestar
|
9e90e8989f7e7f4be169d5ec169c984200677a20
| 3,943
|
cpp
|
C++
|
src/tile.cpp
|
lucasfo/robot-environment
|
82141ae06620ab493ff4bc2de366b8149b4fff05
|
[
"MIT"
] | null | null | null |
src/tile.cpp
|
lucasfo/robot-environment
|
82141ae06620ab493ff4bc2de366b8149b4fff05
|
[
"MIT"
] | null | null | null |
src/tile.cpp
|
lucasfo/robot-environment
|
82141ae06620ab493ff4bc2de366b8149b4fff05
|
[
"MIT"
] | null | null | null |
#include <tile.h>
Tile::Tile() {
this->_value = TL_NONE;
this->_color = TLC_WHITE;
this->_flags = 0;
this->_agent = NULL;
this->_pheromone = 0;
}
bool Tile::valid() const {
return (this->_flags & TLF_VALID) > 0;
}
void Tile::valid (const bool valid) {
if (valid) {
this->_flags |= TLF_VALID;
}
else {
this->_flags &= ~TLF_VALID;
}
}
EnTile Tile::value() const {
return this->_value;
}
void Tile::toOutputStream(std::ostream& os) const {
if (this->printable()) {
return;
}
if (!this->valid()) {
os << '?';
}
else if (this->hasAgent()) {
os << 'a';
}
else if (this->hasFood()) {
os << '@';
}
else if (this->hasFootPrint()) {
os << '-';
}
else if (this->hasNest()) {
os << '*';
}
else if (this->_pheromone > 0) {
os << '-';
}
else {
switch (this->_value) {
case TL_FREE:
os << '.';
break;
case TL_WALL:
os << '#';
break;
default:
os << '?';
break;
}
}
}
void Tile::fromInputStream(std::istream& is) {
char c;
is >> c;
this->valid(true);
switch (c) {
case '.':
this->_value = TL_FREE;
break;
case '@':
this->_value = TL_FREE;
this->getFood();
break;
case '#':
this->_value = TL_WALL;
break;
case '*':
this->_value = TL_FREE;
this->getNest();
break;
default:
this->_value = TL_NONE;
this->valid(false);
break;
}
}
bool Tile::hasAgent() const {
return (this->_flags & TLF_AGENT) > 0;
}
void Tile::getAgent(Agent* a) {
this->_flags |= TLF_AGENT;
this->_agent = a;
return;
}
void Tile::loseAgent() {
this->_flags &= ~TLF_AGENT;
this->_agent = NULL;
return;
}
bool Tile::hasFood() const {
return (this->_flags & TLF_FOOD) > 0;
}
void Tile::getFood() {
this->_flags |= TLF_FOOD;
return;
}
void Tile::loseFood() {
this->_flags &= ~TLF_FOOD;
return;
}
bool Tile::hasNest() const {
return (this->_flags & TLF_NEST) > 0;
}
void Tile::getNest() {
this->_flags |= TLF_NEST;
return;
}
void Tile::loseNest() {
this->_flags &= ~TLF_NEST;
return;
}
bool Tile::hasFootPrint() const {
return (this->_flags & TLF_FOOTPRINT) > 0;
}
void Tile::getFootPrint() {
this->_flags |= TLF_FOOTPRINT;
return;
}
void Tile::loseFootPrint() {
this->_flags &= ~TLF_FOOTPRINT;
return;
}
bool Tile::hasDiscovered() const {
return (this->_flags & TLF_DISCOVERED) > 0;
}
void Tile::getDiscovered() {
this->_flags |= TLF_DISCOVERED;
return;
}
void Tile::loseDiscovered() {
this->_flags &= ~TLF_DISCOVERED;
return;
}
int Tile::color() const {
return this->_color;
}
void Tile::color(const int c) {
this->_color = c;
}
bool Tile::printable() const {
return (this->_flags & TLF_NOPRINT) > 0;
}
void Tile::toPrint(bool value) {
if(!value) {
this->_flags |= TLF_NOPRINT;
}
else {
this->_flags &= ~TLF_NOPRINT;
}
}
int Tile::incPheromone(int inc) {
this->_pheromone += inc;
if (this->_pheromone < 0) {
this->_pheromone = 0;
}
return this->_pheromone;
}
Agent* Tile::agent() const {
return this->_agent;
}
std::ostream& operator<<(std::ostream& os, const Tile& tile) {
tile.toOutputStream(os);
return os;
}
std::istream& operator>>(std::istream& is, Tile& tile) {
tile.fromInputStream(is);
return is;
}
int Tile::getNestX() const {
return this->_nestX;
}
int Tile::getNestY() const {
return this->_nestY;
}
void Tile::setNestX(int x) {
this->_nestX = x;
}
void Tile::setNestY(int y) {
this->_nestY = y;
}
| 16.99569
| 62
| 0.519909
|
lucasfo
|
9e932a666b0f3b2dbae8890324e6071f0240fa8b
| 631
|
cpp
|
C++
|
LeetCode/ThousandOne/0343-integer_break.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/ThousandOne/0343-integer_break.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/ThousandOne/0343-integer_break.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
#include "leetcode.hpp"
/* 343. 整数拆分
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。
返回你可以获得的最大乘积。
示例 1:
输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1。
示例 2:
输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
说明: 你可以假设 n 不小于 2 且不大于 58。
*/
// https://leetcode-cn.com/problems/integer-break/solution/343-zheng-shu-chai-fen-tan-xin-by-jyd/
// 抄的
int pow3(int n)
{
int p = 1;
for (; n > 0; --n)
p *= 3;
return p;
}
int integerBreak(int n)
{
if (n <= 3)
return n - 1;
int a = n / 3, b = n % 3;
if (b == 0)
return pow3(a);
if (b == 1)
return pow3(a - 1) * 4;
return pow3(a) * 2;
}
int main()
{
OutExpr(integerBreak(10), "%d");
}
| 13.145833
| 97
| 0.554675
|
Ginkgo-Biloba
|
9e9348c185e94e60c4592f4a77830b3069ad729e
| 8,108
|
cpp
|
C++
|
src/sql/RecorderFile.cpp
|
anthonioez/RecorderBlackBerry10
|
978bfff4a874dbc6a2af0daebce2694855705daa
|
[
"Apache-2.0"
] | null | null | null |
src/sql/RecorderFile.cpp
|
anthonioez/RecorderBlackBerry10
|
978bfff4a874dbc6a2af0daebce2694855705daa
|
[
"Apache-2.0"
] | null | null | null |
src/sql/RecorderFile.cpp
|
anthonioez/RecorderBlackBerry10
|
978bfff4a874dbc6a2af0daebce2694855705daa
|
[
"Apache-2.0"
] | null | null | null |
#include "Recorder.hpp"
#include "RecorderFile.hpp"
#include "utils.hpp"
RecorderFile::RecorderFile(SqlDataAccess *sda)
{
table = "files";
id = 0;
folder = 0;
title = "";
desc = "";
size = 0;
duration = 0;
size = 0;
flags = 0;
stamp = 0;
status = 0;
this->sda = sda;
}
bool RecorderFile::copy(QVariantMap row)
{
id = row[recorder_file_col_id].toLongLong();
folder = row[recorder_file_col_folder].toLongLong();
title = row[recorder_file_col_title].toString();
desc = row[recorder_file_col_desc].toString();
path = row[recorder_file_col_path].toString();
size = row[recorder_file_col_size].toLongLong();
duration = row[recorder_file_col_duration].toLongLong();
flags = row[recorder_file_col_flags].toLongLong();
status = row[recorder_file_col_status].toInt();
stamp = row[recorder_file_col_stamp].toLongLong();
return true;
}
bool RecorderFile::load()
{
QString query = "select * from " + table + " where 1 order by _id desc";
QVariant data = sda->execute(query);
if(!sda->hasError())
{
list = data.value<QVariantList>();
return true;
}
return false;
}
bool RecorderFile::load(const QString &sort, bool asc)
{
QString query = "select * from " + table + " where 1 order by " + sort + " " + (asc ? "asc" : "desc");
QVariant data = sda->execute(query);
if(!sda->hasError())
{
list = data.value<QVariantList>();
return true;
}
return false;
}
bool RecorderFile::loadByFolder(long folder)
{
QString query = "select * from " + table + " where " + recorder_file_col_folder + " = " + QString::number(folder) + " order by _id desc";
QVariant data = sda->execute(query);
if(!sda->hasError())
{
list = data.value<QVariantList>();
return true;
}
return false;
}
bool RecorderFile::loadByFolder(long fid, const QString &sort, bool asc)
{
QString fs = "1";
if(fid != 0) fs = QString("%1 = %2").arg(recorder_file_col_folder).arg(fid);
QString query = "select * from " + table + " where " + fs + " order by " + sort + " " + (asc ? "asc" : "desc");
// qDebug() << "query: " << query;
QVariant data = sda->execute(query);
if(!sda->hasError())
{
list = data.value<QVariantList>();
return true;
}
return false;
}
bool RecorderFile::search(long folder, const QString &phrase, const QString &sort, bool asc)
{
if(phrase.trimmed().isEmpty())
{
return false;
}
QString fquery = "";
if(folder > 0)
{
fquery += recorder_file_col_folder + QString(" = ") + QString::number(folder);
fquery += QString(" AND ");
}
QString lquery = "";
QStringList slist = phrase.split(" ");
for(int i = 0; i < slist.size(); i++)
{
QString phr = slist.at(i);
if(!lquery.isEmpty())
{
lquery += QString(" OR ");
}
lquery += QString("(");
lquery += recorder_file_col_title + QString(" LIKE '%") + phr + QString("%'");
lquery += QString(" OR ");
lquery += recorder_file_col_desc + QString(" LIKE '%") + phr + QString("%'");
lquery += QString(")");
}
QString squery = "";
squery += fquery;
squery += QString("(");
squery += lquery;
squery += QString(")");
QString query = "select * from " + table + " where " + squery + " order by " + sort + " " + (asc ? "asc" : "desc");
QVariant data = sda->execute(query);
if(!sda->hasError())
{
list = data.value<QVariantList>();
return true;
}
return false;
}
bool RecorderFile::get(long id)
{
QString query = "select * from " + table + " where " + recorder_file_col_id + " = " + QString::number(id) + " LIMIT 1";
QVariant data = sda->execute(query);
if(!sda->hasError())
{
QVariantList list = data.value<QVariantList>();
if(list.size() > 0)
{
QVariantMap row = list.at(0).value<QVariantMap>();
if(copy(row))
{
return true;
}
}
}
return false;
}
bool RecorderFile::insert()
{
QVariantList insertValues;
insertValues << QString::number(folder) << title << desc
<< path << QString::number(duration) << QString::number(size)
<< QString::number(flags) << QString::number(stamp) << status;
sda->execute("insert into " + table + " ("
+ recorder_file_col_folder + ", "
+ recorder_file_col_title + ", "
+ recorder_file_col_desc + ", "
+ recorder_file_col_path + ", "
+ recorder_file_col_duration + ", "
+ recorder_file_col_size + ", "
+ recorder_file_col_flags + ", "
+ recorder_file_col_stamp + ", "
+ recorder_file_col_status + ") values (?, ?, ?, ?, ?, ?, ?, ?, ?)", insertValues);
if(!sda->hasError())
{
return true;
}
else
{
return false;
}
}
bool RecorderFile::update()
{
QVariantList updateValues;
updateValues << QString::number(folder) << title << desc
<< path << QString::number(duration) << QString::number(size)
<< QString::number(flags) << QString::number(stamp) << status
<< QString::number(id);
sda->execute("update " + table + " set "
+ recorder_file_col_folder + " = ?, "
+ recorder_file_col_title + " = ?, "
+ recorder_file_col_desc + " = ?, "
+ recorder_file_col_path + " = ?, "
+ recorder_file_col_duration + " = ?, "
+ recorder_file_col_size + " = ?, "
+ recorder_file_col_flags + " = ?, "
+ recorder_file_col_stamp + " = ?, "
+ recorder_file_col_status + " = ? where "
+ recorder_file_col_id + " = ?", updateValues);
if(!sda->hasError())
{
return true;
}
else
{
return false;
}
}
bool RecorderFile::remove(long id)
{
sda->execute("delete from " + table + " where " + QString(recorder_file_col_id) + " = " + QString::number(id));
if(!sda->hasError())
{
return true;
}
else
{
return false;
}
}
bool RecorderFile::removeByFolder(long folder)
{
sda->execute("delete from " + table + " where " + QString(recorder_file_col_folder) + " = " + QString::number(folder));
if(!sda->hasError())
{
return true;
}
else
{
return false;
}
}
bool RecorderFile::removeOnFolder()
{
sda->execute("delete from " + table + " where " + QString(recorder_file_col_folder) + " > 0");
if(!sda->hasError())
{
return true;
}
else
{
return false;
}
}
bool RecorderFile::clear()
{
sda->execute("delete from " + table + " where 1");
if(!sda->hasError())
{
return true;
}
else
{
return false;
}
}
QVariantList RecorderFile::getList()
{
return list;
}
int RecorderFile::getCount()
{
int count = 0;
QString query = "select count(*) as total from " + table + " where 1";
QVariant data = sda->execute(query);
if(!sda->hasError())
{
QVariantList list = data.value<QVariantList>();
if(list.size() > 0)
{
QVariantMap map = list.at(0).value<QVariantMap>();
count = map["total"].toInt();
return count;
}
}
return count;
}
int RecorderFile::getCountByFolder(long folder)
{
int count = 0;
QString query = "select count(*) as total from " + table + " where " + QString(recorder_file_col_folder) + " = " + QString::number(folder);
QVariant data = sda->execute(query);
if(!sda->hasError())
{
QVariantList list = data.value<QVariantList>();
if(list.size() > 0)
{
QVariantMap map = list.at(0).value<QVariantMap>();
count = map["total"].toInt();
return count;
}
}
return count;
}
QString RecorderFile::getSortTable(int index)
{
switch(index)
{
case 0:
return recorder_file_col_title;
case 1:
return recorder_file_col_desc;
case 2:
return recorder_file_col_duration;
case 3:
return recorder_file_col_size;
case 4:
return recorder_file_col_stamp;
case 5:
return recorder_file_col_id;
default:
return recorder_file_col_folder;
}
}
int RecorderFile::removeFolderFiles(long id)
{
int count = 0;
RecorderFile *data = new RecorderFile(recorder->mSda);
if(data->loadByFolder(id))
{
QVariantList list = data->getList();
for(int i = 0; i < list.size(); i++)
{
QVariantMap map = list.at(i).value<QVariantMap>();
RecorderFile *item = new RecorderFile(recorder->mSda);
if(item->copy(map))
{
if(item->remove(item->id))
{
item->removeFile(item->path);
count++;
}
}
}
}
return count;
}
bool RecorderFile::removeFile(const QString &path)
{
QFile file(path);
if(file.exists())
{
if(file.remove())
{
return true;
}
}
return false;
}
| 20.683673
| 140
| 0.628885
|
anthonioez
|
9e9451f0b7c9b6321defeb996ee36a3fcdefbef0
| 1,159
|
hpp
|
C++
|
src/gameengine.hpp
|
zerozez/qt-chess
|
4a066195f656cb57e83f49beeaa9e244796b18d3
|
[
"Apache-2.0"
] | 5
|
2018-05-09T05:09:50.000Z
|
2021-07-30T06:48:21.000Z
|
src/gameengine.hpp
|
zerozez/qt-chess
|
4a066195f656cb57e83f49beeaa9e244796b18d3
|
[
"Apache-2.0"
] | null | null | null |
src/gameengine.hpp
|
zerozez/qt-chess
|
4a066195f656cb57e83f49beeaa9e244796b18d3
|
[
"Apache-2.0"
] | 5
|
2017-11-29T23:49:25.000Z
|
2021-06-10T15:13:07.000Z
|
#ifndef GAMEENGINE_HPP
#define GAMEENGINE_HPP
#include <QAbstractListModel>
#include <QHash>
#include <QMap>
#include <QObject>
#include <QPair>
#include <QQmlListProperty>
#include <QSharedPointer>
/**
* @brief The GameEngine class
*
* Main game engine. Control figures position,
* status of the game and moves history.
*
*/
class ChessModel;
class FigureIntf;
class HistoryModel;
class GameEngine : public QObject {
Q_OBJECT
// Q_PROPERTY(QQmlListProperty<FigureIntf> figures READ figures)
public:
explicit GameEngine(QObject *parent = 0);
virtual ~GameEngine();
Q_INVOKABLE void setupBoard();
Q_INVOKABLE void clean();
Q_INVOKABLE void save();
Q_INVOKABLE void load();
Q_INVOKABLE void move();
Q_INVOKABLE QObject *figures();
Q_INVOKABLE QObject *history();
public Q_SLOTS:
void itemClicked(uint x, uint y);
private:
HistoryModel *m_history; /**< Move history*/
ChessModel *m_figures; /**< Figures on the board */
bool m_isWhite; /**< WHo is going now */
FigureIntf *m_lastClick; /**< Figure to move */
private:
void setFigureWays(FigureIntf *figure);
};
#endif // GAMEENGINE_HPP
| 21.462963
| 66
| 0.709232
|
zerozez
|
9e94d2ca221e4db7d7ed1e2dbf25eedb71052f0f
| 579
|
cpp
|
C++
|
main/src/jumpnrun/system/JumpnRunScreen_TaskList.cpp
|
wonderhorn/mkfj
|
18d2dd290811662d87abefe2fe2e338ba9caf8a5
|
[
"MIT"
] | null | null | null |
main/src/jumpnrun/system/JumpnRunScreen_TaskList.cpp
|
wonderhorn/mkfj
|
18d2dd290811662d87abefe2fe2e338ba9caf8a5
|
[
"MIT"
] | null | null | null |
main/src/jumpnrun/system/JumpnRunScreen_TaskList.cpp
|
wonderhorn/mkfj
|
18d2dd290811662d87abefe2fe2e338ba9caf8a5
|
[
"MIT"
] | null | null | null |
#include"jumpnrun/system/JumpnRunScreen.h"
#include<fstream>
using namespace jnr;
using namespace gfw;
bool JumpnRunScreen::dumpTaskListToFile(const std::string& file_name)
{
std::ofstream ofs(file_name, std::ios::binary);
$P.mutex_tasklist.lock();
ofs.write(this->tl.Buffer(), tl.BUF_SIZE);
$P.mutex_tasklist.unlock();
return true;
}
bool JumpnRunScreen::readTaskListFromFile(const std::string& file_name)
{
std::ifstream ifs(file_name, std::ios::binary);
$P.mutex_tasklist.lock();
ifs.read(this->tl.Buffer(), tl.BUF_SIZE);
$P.mutex_tasklist.unlock();
return true;
}
| 26.318182
| 71
| 0.747841
|
wonderhorn
|
9e96e88d19cdc951c890865649da421ca530b756
| 6,538
|
hh
|
C++
|
src/lunasa/common/GenericSequentialDataBundle.hh
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 2
|
2019-01-25T21:21:07.000Z
|
2021-04-29T17:24:00.000Z
|
src/lunasa/common/GenericSequentialDataBundle.hh
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 8
|
2018-10-09T14:35:30.000Z
|
2020-09-30T20:09:42.000Z
|
src/lunasa/common/GenericSequentialDataBundle.hh
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 2
|
2019-04-23T19:01:36.000Z
|
2021-05-11T07:44:55.000Z
|
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#ifndef FAODEL_GENERICSEQUENTIALBUNDLE_HH
#define FAODEL_GENERICSEQUENTIALBUNDLE_HH
#include <cstdint>
#include <string.h> //memcpy
#include "lunasa/DataObject.hh"
#include "lunasa/common/GenericRandomDataBundle.hh"
namespace lunasa {
/**
* @brief A bundle is a collection of variable length data values, packed into a DataObject
* Often users need a way to ship a large number of variable-length blobs. This
* template provides a way for users to pack a series of (possibly large) items into
* an LDO. Users may insert their own meta data section in the template.
*
* @note: This struct is different than GenericDataBundle in that it is intended
* to hold a large number of large objects that are accessed in a streaming manner.
* It does NOT store a length index in the meta section, so it is slow at anything
* except streaming access. However, it does not have per-item size limits or number
* of items limits (provided the data fits in an LDO).
*/
template<class EXTRA_META_TYPE>
struct GenericSequentialBundle {
uint32_t num_items;
uint32_t pad2; //Reserved for alignment
EXTRA_META_TYPE meta;
unsigned char packed_data[0];
void Init() {
num_items = 0;
}
/**
* @brief Append a new item to the back of the list
* @param max_payload_bytes Maximum amount of data that can be stored in the data section
* @param current_byte_offset Where the system is in the packing
* @param new_data Pointer to the new data
* @param new_data_len How large the new item is
* @retval TRUE Item could fit and was added
* @retval FALSE Item was not added because it would exceed capacity
*/
bool AppendBack(const uint32_t max_payload_bytes, uint32_t ¤t_byte_offset, const unsigned char *new_data, uint32_t new_data_len) {
if(current_byte_offset + new_data_len +sizeof(uint32_t) > max_payload_bytes) return false;
memcpy(&packed_data[current_byte_offset], &new_data_len, sizeof(uint32_t));
current_byte_offset+=sizeof(uint32_t);
if(new_data_len>0) {
memcpy(&packed_data[current_byte_offset], new_data, new_data_len);
current_byte_offset += new_data_len;
}
num_items++;
return true;
}
/**
* @brief Append a new item to the back of the list, using a bundle_offset_t to keep the pointers
* @param bundle_offsets Holds the current pointers into the structure
* @param new_data Pointer to the new data
* @param new_data_len How large the new item is
* @retval TRUE Item could fit and was added
* @retval FALSE Item was not added because it would exceed capacity
*/
bool AppendBack(bundle_offsets_t &bundle_offsets, const unsigned char *new_data, uint32_t new_data_len) {
bool ok= AppendBack(bundle_offsets.max_payload_bytes,
bundle_offsets.current_byte_offset,
new_data, new_data_len);
bundle_offsets.current_id = num_items;
return ok;
}
/**
* @brief Append a new string to the back of the list, using a bundle_offset_t to keep the pointers
* @param bundle_offsets Holds the current pointers into the structure
* @param s The string that should be added
* @retval TRUE Item could fit and was added
* @retval FALSE Item was not added because it would exceed capacity
*/
bool AppendBack(bundle_offsets_t &bundle_offsets, const std::string &s) {
bool ok= AppendBack(bundle_offsets.max_payload_bytes,
bundle_offsets.current_byte_offset,
(const unsigned char *) s.c_str(), s.size() );
bundle_offsets.current_id = num_items;
return ok;
}
/**
* @brief Get the next data pointer from the bundle (and update offsets)
* @param max_payload Maximum capacity of the data section of LDO
* @param current_id ID of next item
* @param current_offset Payload offset for next item
* @param data_ptr Pointer to the item (user must not free. user must not use after ldo deleted)
* @param data_len Returned size of the item
* @retval TRUE Item was valid and returned
* @retval FALSE Item not available in bundle. No data returned
*/
bool GetNext(const uint32_t max_payload, uint32_t ¤t_id, uint32_t ¤t_offset,
unsigned char **data_ptr, uint32_t *data_len) {
if(current_id >= num_items) return false;
if(current_offset+sizeof(uint32_t) > max_payload) return false; //Should really just assert
uint32_t len = (reinterpret_cast<uint32_t *>(&packed_data[current_offset]))[0];
if(current_offset+sizeof(uint32_t)+len > max_payload) return false;
current_offset+=sizeof(uint32_t);
//Pass back
*data_len = len;
*data_ptr = (len==0) ? nullptr : &packed_data[current_offset];
current_offset+=len;
current_id++;
return true;
}
/**
* @brief Get the next data pointer from the bundle (using a bundle_offsets)
* @param bundle_offsets Data structure containing pointers to the next item in this bundle
* @param data_ptr Pointer to the item (user must not free. user must not use after ldo deleted)
* @param data_len Returned size of the item
* @retval TRUE Item was valid and returned
* @retval FALSE Item not available in bundle. No data returned
*/
bool GetNext(bundle_offsets_t &bundle_offsets, unsigned char **data_ptr, uint32_t *data_len) {
return GetNext(bundle_offsets.max_payload_bytes,
bundle_offsets.current_id,
bundle_offsets.current_byte_offset,
data_ptr, data_len);
}
/**
* @brief Get the next data pointer from the bundle (using a bundle_offsets)
* @param bundle_offsets Data structure containing pointers to the next item in this bundle
* @param result_string Next item as a string (if available)
* @retval TRUE Item was valid and returned
* @retval FALSE Item not available in bundle. No data returned
*/
bool GetNext(bundle_offsets_t &bundle_offsets, std::string *result_string) {
uint32_t len;
unsigned char *ptr;
bool ok = GetNext(bundle_offsets.max_payload_bytes,
bundle_offsets.current_id,
bundle_offsets.current_byte_offset,
&ptr, &len);
if(ok) {
result_string->assign((const char *)ptr, len);
}
return ok;
}
};
} //namespace lunasa
#endif //FAODEL_GENERICDATABUNDLE_HH
| 38.233918
| 138
| 0.714439
|
faodel
|
9e98fb2a7bdc65a79183cac9b2461d4f2d70ec09
| 1,284
|
cpp
|
C++
|
solution328.cpp
|
white-shark/leetcode-cpp
|
ba1389d3083ee2a2bb0a232672ee316afc125b58
|
[
"MIT"
] | 31
|
2016-08-18T16:30:59.000Z
|
2022-02-15T11:21:39.000Z
|
solution328.cpp
|
runguanner/Leetcode
|
ba1389d3083ee2a2bb0a232672ee316afc125b58
|
[
"MIT"
] | null | null | null |
solution328.cpp
|
runguanner/Leetcode
|
ba1389d3083ee2a2bb0a232672ee316afc125b58
|
[
"MIT"
] | 22
|
2017-07-17T07:30:00.000Z
|
2022-01-24T08:37:15.000Z
|
/**
* Odd Even Linked List
*
* cpselvis(cpselvis@gmail.com)
* September 9th, 2016
*/
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (head == NULL)
{
return head;
}
ListNode *odd = head;
ListNode *even = head -> next;
ListNode *evenHead = even;
while (even != NULL && even -> next != NULL)
{
ListNode *nextOdd = odd -> next -> next;
ListNode *nextEven = even -> next -> next;
odd -> next = nextOdd;
even -> next = nextEven;
odd = nextOdd;
even = nextEven;
}
odd -> next = evenHead;
return head;
}
};
int main(int argc, char **argv)
{
ListNode *head = new ListNode(1);
head -> next = new ListNode(2);
head -> next -> next = new ListNode(3);
head -> next -> next -> next = new ListNode(4);
head -> next -> next -> next -> next = new ListNode(5);
head -> next -> next -> next -> next -> next = new ListNode(6);
head -> next -> next -> next -> next -> next -> next = new ListNode(7);
Solution s;
ListNode *p = s.oddEvenList(head);
while (p != NULL)
{
cout << p -> val << endl;
p = p -> next;
}
}
| 20.380952
| 73
| 0.556075
|
white-shark
|
9e9a3e2b38069d84c337912e00255a6c972e7b40
| 10,846
|
cpp
|
C++
|
exe/fs123p7/exportd_cc_rules.cpp
|
DEShawResearch/fs123
|
27bee72752fedc54ab493e49c6da96eeb2c6ab6a
|
[
"BSD-3-Clause"
] | 22
|
2019-04-10T18:05:35.000Z
|
2021-12-30T12:26:39.000Z
|
exe/fs123p7/exportd_cc_rules.cpp
|
DEShawResearch/fs123
|
27bee72752fedc54ab493e49c6da96eeb2c6ab6a
|
[
"BSD-3-Clause"
] | 13
|
2019-04-09T00:19:29.000Z
|
2021-11-04T15:57:13.000Z
|
exe/fs123p7/exportd_cc_rules.cpp
|
DEShawResearch/fs123
|
27bee72752fedc54ab493e49c6da96eeb2c6ab6a
|
[
"BSD-3-Clause"
] | 4
|
2019-04-07T16:33:44.000Z
|
2020-07-02T02:58:51.000Z
|
#include "exportd_cc_rules.hpp"
#include <core123/json.hpp>
#include <core123/fdstream.hpp>
#include <core123/unused.hpp>
#include <core123/autoclosers.hpp>
#include <core123/sew.hpp>
#include <core123/scoped_nanotimer.hpp>
#include <core123/diag.hpp>
#include <core123/pathutils.hpp>
#include <core123/stats.hpp>
using namespace core123;
static auto _cc_rules = diag_name("cc_rules");
namespace{
#define CC_RULES_STATISTICS \
STATISTIC(cc_rules_successful_opens) \
STATISTIC(cc_rules_enoents) \
STATISTIC(cc_rules_enotdirs) \
STATISTIC_NANOTIMER(cc_rules_json_parse_sec) \
STATISTIC_NANOTIMER(cc_rules_get_cc_sec)
#define STATS_MACRO_NAME CC_RULES_STATISTICS
#define STATS_STRUCT_TYPENAME cc_rules_stats_t
#include <core123/stats_struct_builder>
#undef CC_RULES_STATISTICS
cc_rules_stats_t stats;
}
cc_rule_cache::exruleset_sp
cc_rule_cache::read_cc_rulesfile(const std::string& relpath) /*private*/{
// open relpath relative to export_root.
// If ENOENT, return {}
// Otherwise read the contents into an exrulest_sp and return it.
DIAGkey(_cc_rules, "read_cc_rulesfile(" << relpath << ")\n");
acfd fd = openat(exrootfd, relpath.c_str(), O_RDONLY);
if(!fd){
if(errno == ENOENT){
stats.cc_rules_enoents++;
return {}; // an expired null pointer.
}
if(errno == ENOTDIR){
// These should be rare. They can happen if a directory
// is deleted, or if a curl request picks a directory "out
// of thin air".
stats.cc_rules_enotdirs++;
return {};
}
throw se("read_cc_rulesfile(" + relpath + ")");
}
stats.cc_rules_successful_opens++;
// read the cc_rules from fd. Expect json like:
// {
// "rulesfile-maxage": 90,
// "re-rules": [
// { "re": ".*\\.stk" , "cc": "max-age=1,stale-while-revalidate=1"},
// { "re": ".*\\.ark" , "cc": "max-age=10,stale-while-revalidate=10"}
// ],
// "cc": "max-age=3600,stale-while-revalidate=1800"
// }
//
// Use Josutis' fdistream to turn our fd into an istream, and use
// N. Lohmann's json::parse to turn the istream into a json
// object. N.b. we're *NOT* dragging in all of boost here.
// Just one file: thirdparty/include/fdstream.hpp
atomic_scoped_nanotimer _t(&stats.cc_rules_json_parse_sec);
auto j = nlohmann::json::parse(boost::fdistream(fd));
auto rulesfile_maxage{default_ttl};
auto p = j.find("rulesfile-maxage");
if( p != j.end())
rulesfile_maxage = std::chrono::seconds(p->get<int>());
ruleset_sp ret = std::make_shared<cc_rule_cache::ruleset>();
if(j.find("re-rules") != j.end()){ // re-rules are optional..
for(auto& jrer : j.at("re-rules")){
ret->rerules.emplace_back();
auto& back = ret->rerules.back();
back.re = std::regex(jrer.at("re").get<std::string>(), std::regex::extended);
back.cc = jrer.at("cc").get<std::string>();
}
}
ret->cc = j.at("cc").get<std::string>();
// json.hpp throws exceptions of type nlohmann::detail::exception,
// derived from std::exception if it's unhappy. So if we get
// here, we have successfully parsed a well-formed json file with
// keys and types as expected. WE DO NOT CHECK FOR UNEXPECTED
// KEYS.
return expiring<ruleset_sp>(rulesfile_maxage, ret);
}
cc_rule_cache::exruleset_sp
cc_rule_cache::get_cc_rules_recursive(const std::string& path) /*private*/{
DIAGkey(_cc_rules, "get_cc_rules_recursive(" << path << ")\n");
exruleset_sp tentative = excache.lookup(path);
if(tentative && !tentative.expired()){
DIAGkey(_cc_rules, str(__func__, "return: ", tentative->cc, "expiring in:", tentative.ttl()));
return tentative;
}
auto fpath = path.empty() ? ".fs123_cc_rules" : path + "/.fs123_cc_rules";
exruleset_sp ret;
try{
ret = read_cc_rulesfile(fpath);
}catch(std::exception& e){
// How should we react to a borked rules-cache?
//
// If we allow the exception to continue unwinding the
// stack, we ultimately return a 503, which has the
// undesirable effect of putting clients in a retry loop
// and tickling failover logic in Varnish.
//
// If we throw_with_nested(http_exception(400,...)), clients
// see an error and the subtree below the borked rules-cache
// becomes unreachable, but the client doesn't desperately
// retry and the server doesn't get declared offline.
//
// If we catch the exception and fall through after
// complaining, it's as if the borked rules file never
// existed. Nothing will get fixed unless somebody notices
// the complaints. But the "breakage" is far less disruptive
// to clients.
//
// June 2018 - let's just complain.
complain(LOG_WARNING, e, "corrupt rules-cache: " + fpath);
}
if(ret){
excache.insert(path, ret);
return ret;
}
ret = path.empty()? fallback_cc : get_cc_rules_recursive(pathsplit(path).first);
excache.insert(path, ret);
return ret;
}
cc_rule_cache::cc_rule_cache(const std::string& export_root, size_t cache_entries, int _default_ttl, const std::string& fb_cc):
excache(cache_entries),
default_ttl(_default_ttl),
fallback_cc(default_ttl, std::make_shared<ruleset>()),
exrootfd(sew::open(export_root.c_str(), O_DIRECTORY|O_RDONLY))
{
fallback_cc->cc = fb_cc;
}
std::string
cc_rule_cache::get_cc(const std::string& path_info, bool directory)try{
DIAGkey(_cc_rules, strfunargs(__func__, path_info, directory));
atomic_scoped_nanotimer _t(&stats.cc_rules_get_cc_sec);
std::string pi = directory? path_info : pathsplit(path_info).first;
ruleset_sp rules = get_cc_rules_recursive(pi);
for(const auto& rer : rules->rerules){
if(std::regex_match(path_info, rer.re))
return rer.cc;
}
return rules->cc;
}catch(std::regex_error& re){
std::throw_with_nested(std::runtime_error("in get_cc(" + path_info + ") with re.code(): " + std::to_string(re.code())));
}
/*static*/ std::string
cc_rule_cache::bounded_max_age(const std::string& cc, const struct stat& sb){
// If the object was recently changed (i.e., sb.mtime is in the
// recent past), then there's a good chance it might change again
// in the near future. So adjust the specified max-age down
// to roughly the time-since-last change. Under no circumstances
// (crazy value in sb.st_mtime, crazy value returned by time(2))
// adjust it below 1 second (but if it started below 1 second,
// that's fine).
//
// FIXME: It's unfortunate that modifying the cc requires
// carefully teasing apart and then reassembling a std::string.
// It would be much better if the cc-rules parser gave us
// numerical values for things like max-age,
// stale-while-revalidate, etc. and we did the final assembly
// here. But that would require a new, externally visible, format
// for the cc_rules files, which is a project for another day.
time_t maxage;
size_t digits_begin;
size_t digits_end;
DIAG(_cc_rules, "adjust_cc(" + cc + ")");
#if 1
// regex - the easy way
static std::regex re("(?:^|,| )max-age\\s*=\\s*(\\d+)");
std::smatch m;
if(!std::regex_search(cc, m, re))
return cc;
digits_begin = m.position(1);
digits_end = digits_begin + m.length(1);
try{
(void)scanint<time_t, 10, true>(cc, &maxage, digits_begin);
}catch(std::exception& e){
// e.g., max-age=99999999999999999999999 would cause scanint to throw
complain(LOG_WARNING, e, str("adjust_cc: scanint threw. set maxage=numeric_limits::max(): cc:", cc, "digits_begin:", digits_begin));
maxage = std::numeric_limits<time_t>::max();
}
#else
// We can do it without regex, but it's a lot more complicated, a
// little less robust, and (maybe) slightly faster (a few tenths
// of a microsecond). It's hard to believe that could matter:
// we've already handled an http request, done a stat and/or a
// read, etc. Simpler is better (until we encounter a case where
// performance actually matters).
//
// Also note - whitespace is handled slightly differently from the
// regex code. The existing unit tests will fail, but that's
// because the tests are too strict about whitespace.
size_t start = 0;
for(;;){ // loop over spurious "hits", e.g., s-max-age=99
auto ma_begin = cc.find("max-age", start);
if(ma_begin == std::string::npos)
return cc; // if there's *nothing* matching max-age, we're done
auto ma_end = ma_begin + sizeof("max-age")-1;
if(ma_begin > 0){
// check the character before "max-age"
auto prev = cc[ma_begin-1];
if(prev != ' ' && prev != ','){
start = ma_end;
continue;
}
}
auto equals = svscan(cc, nullptr, ma_end); // skip whitespace
if(cc[equals] != '='){ // might dereference the terminal '\0'!
start = equals;
continue;
}
digits_begin = equals+1;
try{
digits_end = scanint<time_t, 10, true>(cc, &maxage, digits_begin);
// unlike the regex code, return cc if we see:
// "max-age=-10"
if(maxage < 0)
return cc;
}catch(std::exception&){
// unlike the regex code, return cc if we see:
// "max-age=<EOL>" or "max-age=foo" or
// "max-age=99999999999999999999". The latter is arguably
// a bug, but it's pretty ill-advised. I.e., I wouldn't
// count on proxy-caches handling it correctly either.
return cc;
}
break;
}
#endif
// finally - we've got 'maxage', digits_begin and digits_end, so
// we can reconstruct the cc string around a new value (if
// needed).
auto unchanged = sew::time(nullptr) - sb.st_mtime;
auto maxmaxage = std::max(time_t(1), unchanged);
auto adjusted_age = std::min(maxmaxage, maxage);
if(adjusted_age != maxage){
return cc.substr(0, digits_begin) +
str(adjusted_age) +
cc.substr(digits_end);
}
return cc;
}
std::ostream&
cc_rule_cache::report_stats(std::ostream& os){
os << stats;
os << "cc_cache_size: " << excache.size() << "\n"
<< "cc_cache_evictions: " << excache.evictions() << "\n"
<< "cc_cache_hits: " << excache.hits() << "\n"
<< "cc_cache_expirations: " << excache.expirations() << "\n"
<< "cc_cache_misses: " << excache.misses() << "\n";
return os;
}
| 40.621723
| 141
| 0.626775
|
DEShawResearch
|
9e9a450b4c778fd56f50398af5d0c6099e31f48f
| 3,961
|
inl
|
C++
|
src/include/cjm/numerics/numerics_configuration.inl
|
cpsusie/cjm-numerics
|
9719f4aa7ed0fa157f4705e3f20f069e28a5755f
|
[
"MIT"
] | 2
|
2021-04-18T07:35:56.000Z
|
2021-04-23T07:37:58.000Z
|
src/include/cjm/numerics/numerics_configuration.inl
|
cpsusie/Int128
|
9719f4aa7ed0fa157f4705e3f20f069e28a5755f
|
[
"MIT"
] | 29
|
2020-12-18T00:50:36.000Z
|
2021-03-22T21:35:18.000Z
|
src/include/cjm/numerics/numerics_configuration.inl
|
cpsusie/cjm-numerics
|
9719f4aa7ed0fa157f4705e3f20f069e28a5755f
|
[
"MIT"
] | null | null | null |
// Copyright © 2020-2021 CJM Screws, LLC
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// CJM Screws, LLC is a Maryland Limited Liability Company.
// No copyright claimed to unmodified original work of others.
// The original, unmodified work of others, to the extent included in this library,
// is licensed to you under the same terms under which it was licensed to CJM Screws, LLC.
// For information about copyright and licensing of the original work of others,
// see Notices file in cjm/ folder.
#ifndef CJM_NUMERICS_CONFIGURATION_INL_
#define CJM_NUMERICS_CONFIGURATION_INL_
#include <cjm/numerics/numerics_configuration.hpp>
namespace cjm::numerics
{
namespace internal
{
using enum_type_t = std::underlying_type_t<compiler_used>;
using namespace std::string_view_literals;
constexpr auto compiler_name_lookup = std::array<std::string_view, static_cast<enum_type_t>(max_value) + 1>
{
"Other"sv,
"Microsoft"sv,
"Microsoft-Clang"sv,
"Microsoft-Intel-Classic"sv,
"Microsoft-Intel-LLVM"sv,
"Clang-GCC"sv,
"GCC"sv,
"Clang"sv
};
constexpr auto compiler_name_lookup_wide = std::array<std::wstring_view, static_cast<enum_type_t>(max_value) + 1>
{
L"Other"sv,
L"Microsoft"sv,
L"Microsoft-Clang"sv,
L"Microsoft-Intel-Classic"sv,
L"Microsoft-Intel-LLVM"sv,
L"Clang-GCC"sv,
L"GCC"sv,
L"Clang"sv
};
}
constexpr bool is_value_defined(compiler_used v) noexcept
{
using enum_type_t = std::underlying_type_t<compiler_used>;
const enum_type_t min = static_cast<enum_type_t>(min_value);
const enum_type_t max = static_cast<enum_type_t>(max_value);
const enum_type_t val = static_cast<enum_type_t>(v);
return val >= min && val <= max;
}
constexpr compiler_used value_or_other_ifndef(compiler_used v) noexcept
{
return is_value_defined(v) ? v : compiler_used::other;
}
constexpr std::string_view get_text_narrow(compiler_used v) noexcept
{
return internal::compiler_name_lookup[(static_cast<internal::enum_type_t>(value_or_other_ifndef(v)))];
}
constexpr std::wstring_view get_text_wide(compiler_used v) noexcept
{
return internal::compiler_name_lookup_wide[(static_cast<internal::enum_type_t>(value_or_other_ifndef(v)))];
}
#pragma warning(push)
#pragma warning (disable:4068)
#pragma clang diagnostic push
#pragma ide diagnostic ignored "UnreachableCode"
constexpr uint128_calc_mode init_eval_mode() noexcept
{
if constexpr (cjm::numerics::has_intrinsic_u128)
{
return cjm::numerics::uint128_calc_mode::intrinsic_u128;
}
else if constexpr (cjm::numerics::is_microsoft_windows_x64)
{
return cjm::numerics::uint128_calc_mode::msvc_x64;
}
else if constexpr (cjm::numerics::is_clang_or_intel_llvm_msvc_x64)
{
return uint128_calc_mode::msvc_x64_clang_or_intel_llvm;
}
else
{
return cjm::numerics::uint128_calc_mode::default_eval;
}
}
#pragma clang diagnostic pop
#pragma warning(pop)
}
#endif
| 36.33945
| 150
| 0.757889
|
cpsusie
|
9e9b95bc9d5a9dc4ce9b643caa788df0a5975373
| 79,021
|
cpp
|
C++
|
src/GUST-Graphics/Renderer.cpp
|
ReeCocho/GUST-Engine-3
|
f75ce52f8384a2e6cd7c788286c174ee7bde96f1
|
[
"MIT"
] | 1
|
2018-01-01T23:24:03.000Z
|
2018-01-01T23:24:03.000Z
|
src/GUST-Graphics/Renderer.cpp
|
ReeCocho/GUST-Engine-3
|
f75ce52f8384a2e6cd7c788286c174ee7bde96f1
|
[
"MIT"
] | null | null | null |
src/GUST-Graphics/Renderer.cpp
|
ReeCocho/GUST-Engine-3
|
f75ce52f8384a2e6cd7c788286c174ee7bde96f1
|
[
"MIT"
] | null | null | null |
#include <FileIO.hpp>
#include <iostream>
#include "Renderer.hpp"
namespace gust
{
void Renderer::startup
(
Graphics* graphics,
ResourceAllocator<Mesh>* meshAllocator,
ResourceAllocator<Texture>* textureAllocator,
size_t threadCount
)
{
m_graphics = graphics;
m_threadPool = std::make_unique<ThreadPool>(threadCount);
m_cameraAllocator = std::make_unique<ResourceAllocator<VirtualCamera>>(10);
m_meshAllocator = meshAllocator;
m_textureAllocator = textureAllocator;
initCommandPools();
initRenderPasses();
initSwapchain();
initDepthResources();
initSwapchainBuffers();
initSemaphores();
initLighting();
initDescriptorSetLayouts();
initDescriptorPool();
initDescriptorSets();
initShaders();
initCommandBuffers();
}
void Renderer::shutdown()
{
auto logicalDevice = m_graphics->getLogicalDevice();
// Destroy thread pool
m_threadPool = nullptr;
destroyCommandBuffer(m_commands.skybox);
// Destroy cameras
for(size_t i = 0; i < m_cameraAllocator->getMaxResourceCount(); ++i)
if (m_cameraAllocator->isAllocated(i))
destroyCamera(Handle<VirtualCamera>(m_cameraAllocator.get(), i));
m_cameraAllocator = nullptr;
// Destroy screen quad
m_screenQuad->free();
m_skybox->free();
m_meshAllocator->deallocate(m_screenQuad.getHandle());
m_meshAllocator->deallocate(m_skybox.getHandle());
// Cleanup
logicalDevice.destroyShaderModule(m_lightingShader.vertexShader);
logicalDevice.destroyShaderModule(m_lightingShader.fragmentShader);
logicalDevice.destroyDescriptorSetLayout(m_lightingShader.textureDescriptorSetLayout);
logicalDevice.destroyPipelineLayout(m_lightingShader.graphicsPipelineLayout);
logicalDevice.destroyPipeline(m_lightingShader.graphicsPipeline);
logicalDevice.destroyShaderModule(m_screenShader.vertexShader);
logicalDevice.destroyShaderModule(m_screenShader.fragmentShader);
logicalDevice.destroyDescriptorSetLayout(m_screenShader.textureDescriptorSetLayout);
logicalDevice.destroyPipelineLayout(m_screenShader.graphicsPipelineLayout);
logicalDevice.destroyPipeline(m_screenShader.graphicsPipeline);
logicalDevice.destroyShaderModule(m_skyboxShader.vertexShader);
logicalDevice.destroyShaderModule(m_skyboxShader.fragmentShader);
logicalDevice.destroyDescriptorSetLayout(m_skyboxShader.textureDescriptorSetLayout);
logicalDevice.destroyPipelineLayout(m_skyboxShader.graphicsPipelineLayout);
logicalDevice.destroyPipeline(m_skyboxShader.graphicsPipeline);
logicalDevice.destroyBuffer(m_lightingUniformBuffer.buffer);
logicalDevice.freeMemory(m_lightingUniformBuffer.memory);
logicalDevice.destroyBuffer(m_skyboxUniformBuffer.buffer);
logicalDevice.freeMemory(m_skyboxUniformBuffer.memory);
logicalDevice.destroyDescriptorPool(m_descriptors.descriptorPool);
logicalDevice.destroyDescriptorSetLayout(m_descriptors.descriptorSetLayout);
logicalDevice.destroyDescriptorSetLayout(m_descriptors.screenDescriptorSetLayout);
logicalDevice.destroyDescriptorSetLayout(m_descriptors.lightingDescriptorSetLayout);
logicalDevice.destroyDescriptorSetLayout(m_descriptors.skyboxDescriptorSetLayout);
for(auto commandBuffer : m_commands.rendering)
destroyCommandBuffer(commandBuffer);
logicalDevice.destroyRenderPass(m_renderPasses.onscreen);
logicalDevice.destroyRenderPass(m_renderPasses.offscreen);
logicalDevice.destroyRenderPass(m_renderPasses.lighting);
logicalDevice.destroySemaphore(m_semaphores.imageAvailable);
logicalDevice.destroySemaphore(m_semaphores.renderFinished);
logicalDevice.destroySemaphore(m_semaphores.offscreen);
// Cleanup depth texture
logicalDevice.destroyImageView(m_depthTexture.imageView);
logicalDevice.destroyImage(m_depthTexture.image);
logicalDevice.freeMemory(m_depthTexture.memory);
// Destroy framebuffers and views
for (auto& buffer : m_swapchain.buffers)
{
logicalDevice.destroyFramebuffer(buffer.frameBuffer);
logicalDevice.destroyImageView(buffer.view);
}
// Destroy command pools
for (auto pool : m_commands.pools)
logicalDevice.destroyCommandPool(pool);
// Cleanup swapchain
logicalDevice.destroySwapchainKHR(m_swapchain.swapchain);
}
void Renderer::render()
{
if (m_mainCamera.getResourceAllocator() && m_mainCamera.get())
{
// Submit lighting data
submitLightingData();
// Draw everything to every camera
bool drew = false;
for (size_t i = 0; i < m_cameraAllocator->getMaxResourceCount(); ++i)
if (m_cameraAllocator->isAllocated(i))
{
drawToCamera(Handle<VirtualCamera>(m_cameraAllocator.get(), i));
drew = true;
}
// Return early if we didn't draw anything (No need to present again)
if (!drew)
return;
// Get image to present
uint32_t imageIndex = m_graphics->getLogicalDevice().acquireNextImageKHR
(
m_swapchain.swapchain,
std::numeric_limits<uint64_t>::max(),
m_semaphores.imageAvailable,
{ nullptr }
).value;
std::array<vk::Semaphore, 2> semaphores =
{
m_semaphores.imageAvailable,
m_semaphores.offscreen
};
std::array<vk::PipelineStageFlags, 2> waitStages =
{
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::PipelineStageFlagBits::eColorAttachmentOutput
};
vk::SubmitInfo submitInfo = {};
submitInfo.setWaitSemaphoreCount(static_cast<uint32_t>(semaphores.size()));
submitInfo.setPWaitSemaphores(semaphores.data());
submitInfo.setPWaitDstStageMask(waitStages.data());
submitInfo.setCommandBufferCount(1);
submitInfo.setPCommandBuffers(&m_commands.rendering[imageIndex].buffer);
submitInfo.setSignalSemaphoreCount(1);
submitInfo.setPSignalSemaphores(&m_semaphores.renderFinished);
// Submit draw command
m_graphics->getGraphicsQueue().submit(1, &submitInfo, { nullptr });
vk::PresentInfoKHR presentInfo = {};
presentInfo.setWaitSemaphoreCount(1);
presentInfo.setPWaitSemaphores(&m_semaphores.renderFinished);
presentInfo.setSwapchainCount(1);
presentInfo.setPSwapchains(&m_swapchain.swapchain);
presentInfo.setPImageIndices(&imageIndex);
presentInfo.setPResults(nullptr);
// Present and wait
m_graphics->getPresentationQueue().presentKHR(presentInfo);
m_graphics->getPresentationQueue().waitIdle();
// Clear mesh queue
m_meshes.clear();
}
}
Handle<VirtualCamera> Renderer::createCamera()
{
// Resize the array if necessary
if (m_cameraAllocator->getResourceCount() == m_cameraAllocator->getMaxResourceCount())
m_cameraAllocator->resize(m_cameraAllocator->getMaxResourceCount() + 10, true);
// Allocate camera and call constructor
auto camera = Handle<VirtualCamera>(m_cameraAllocator.get(), m_cameraAllocator->allocate());
::new(camera.get())(VirtualCamera)();
camera->width = m_graphics->getWidth();
camera->height = m_graphics->getHeight();
camera->commandBuffer = createCommandBuffer(vk::CommandBufferLevel::ePrimary);
camera->lightingCommandBuffer = createCommandBuffer(vk::CommandBufferLevel::ePrimary);
// (World space) Positions
FrameBufferAttachment position = createAttachment
(
vk::Format::eR16G16B16A16Sfloat,
vk::ImageUsageFlagBits::eColorAttachment
);
// (World space) Normals
FrameBufferAttachment normals = createAttachment
(
vk::Format::eR16G16B16A16Sfloat,
vk::ImageUsageFlagBits::eColorAttachment
);
// Albedo (color)
FrameBufferAttachment color = createAttachment
(
m_graphics->getSurfaceColorFormat(),
vk::ImageUsageFlagBits::eColorAttachment
);
// Misc
FrameBufferAttachment misc = createAttachment
(
vk::Format::eR16G16B16A16Sfloat,
vk::ImageUsageFlagBits::eColorAttachment
);
// Depth attachment
FrameBufferAttachment depth = createAttachment
(
m_graphics->getDepthFormat(),
vk::ImageUsageFlagBits::eDepthStencilAttachment
);
// Create sampler to sample from the attachments
vk::SamplerCreateInfo sampler = {};
sampler.setMagFilter(vk::Filter::eNearest);
sampler.setMinFilter(vk::Filter::eNearest);
sampler.setMipmapMode(vk::SamplerMipmapMode::eLinear);
sampler.setAddressModeU(vk::SamplerAddressMode::eClampToEdge);
sampler.setAddressModeV(sampler.addressModeU);
sampler.setAddressModeW(sampler.addressModeU);
sampler.setMipLodBias(0.0f);
sampler.setMaxAnisotropy(1.0f);
sampler.setMinLod(0.0f);
sampler.setMaxLod(1.0f);
sampler.setBorderColor(vk::BorderColor::eFloatOpaqueWhite);
// Create samplers
vk::Sampler positionSampler = m_graphics->getLogicalDevice().createSampler(sampler);
vk::Sampler normalSampler = m_graphics->getLogicalDevice().createSampler(sampler);
vk::Sampler colorSampler = m_graphics->getLogicalDevice().createSampler(sampler);
vk::Sampler miscSampler = m_graphics->getLogicalDevice().createSampler(sampler);
vk::Sampler depthSampler = m_graphics->getLogicalDevice().createSampler(sampler);
// Resize allocator if needed
if (m_textureAllocator->getResourceCount() + 5 > m_textureAllocator->getMaxResourceCount())
m_textureAllocator->resize(m_textureAllocator->getMaxResourceCount() + 5, true);
// Create attachments
camera->position = Handle<Texture>(m_textureAllocator, m_textureAllocator->allocate());
camera->normal = Handle<Texture>(m_textureAllocator, m_textureAllocator->allocate());
camera->color = Handle<Texture>(m_textureAllocator, m_textureAllocator->allocate());
camera->misc = Handle<Texture>(m_textureAllocator, m_textureAllocator->allocate());
camera->depth = Handle<Texture>(m_textureAllocator, m_textureAllocator->allocate());
::new(camera->position.get())(Texture)(m_graphics, position.image, position.view, positionSampler, position.memory, camera->width, camera->height);
::new(camera->normal.get())(Texture)(m_graphics, normals.image, normals.view, normalSampler, normals.memory, camera->width, camera->height);
::new(camera->color.get())(Texture)(m_graphics, color.image, color.view, colorSampler, color.memory, camera->width, camera->height);
::new(camera->misc.get())(Texture)(m_graphics, misc.image, misc.view, miscSampler, misc.memory, camera->width, camera->height);
::new(camera->depth.get())(Texture)(m_graphics, depth.image, depth.view, depthSampler, depth.memory, camera->width, camera->height);
std::array<vk::ImageView, 5> attachments;
attachments[0] = camera->position->getImageView();
attachments[1] = camera->normal->getImageView();
attachments[2] = camera->color->getImageView();
attachments[3] = camera->misc->getImageView();
attachments[4] = camera->depth->getImageView();
vk::FramebufferCreateInfo fbufCreateInfo = {};
fbufCreateInfo.setPNext(nullptr);
fbufCreateInfo.setRenderPass(m_renderPasses.offscreen);
fbufCreateInfo.setPAttachments(attachments.data());
fbufCreateInfo.setAttachmentCount(static_cast<uint32_t>(attachments.size()));
fbufCreateInfo.setWidth(camera->width);
fbufCreateInfo.setHeight(camera->height);
fbufCreateInfo.setLayers(1);
// Create framebuffer
camera->frameBuffer = m_graphics->getLogicalDevice().createFramebuffer(fbufCreateInfo);
return camera;
}
void Renderer::initCommandPools()
{
// Create a command pools
auto commandPoolInfo = vk::CommandPoolCreateInfo
(
vk::CommandPoolCreateFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer),
m_graphics->getQueueFamilyIndices().graphicsFamily
);
m_commands.pools.resize(m_threadPool->getWorkerCount());
for (size_t i = 0; i < m_commands.pools.size(); ++i)
m_commands.pools[i] = m_graphics->getLogicalDevice().createCommandPool(commandPoolInfo);
}
void Renderer::initRenderPasses()
{
// Onscreen
{
// Describes color attachment usage
vk::AttachmentDescription colorAttachment = {};
colorAttachment.setFormat(m_graphics->getSurfaceColorFormat());
colorAttachment.setSamples(vk::SampleCountFlagBits::e1);
colorAttachment.setLoadOp(vk::AttachmentLoadOp::eClear);
colorAttachment.setStoreOp(vk::AttachmentStoreOp::eStore);
colorAttachment.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare);
colorAttachment.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare);
colorAttachment.setInitialLayout(vk::ImageLayout::eUndefined);
colorAttachment.setFinalLayout(vk::ImageLayout::ePresentSrcKHR);
vk::AttachmentReference colorAttachmentRef = {};
colorAttachmentRef.setAttachment(0);
colorAttachmentRef.setLayout(vk::ImageLayout::eColorAttachmentOptimal);
vk::SubpassDescription subpass = {};
subpass.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics);
subpass.setColorAttachmentCount(1);
subpass.setPColorAttachments(&colorAttachmentRef);
vk::SubpassDependency dependency = {};
dependency.setSrcSubpass(VK_SUBPASS_EXTERNAL);
dependency.setDstSubpass(0);
dependency.setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput);
dependency.setSrcAccessMask(vk::AccessFlagBits::eMemoryRead);
dependency.setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput);
dependency.setDstAccessMask(vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite);
dependency.setDependencyFlags(vk::DependencyFlagBits::eByRegion);
vk::RenderPassCreateInfo renderPassInfo = {};
renderPassInfo.setAttachmentCount(1);
renderPassInfo.setPAttachments(&colorAttachment);
renderPassInfo.setSubpassCount(1);
renderPassInfo.setPSubpasses(&subpass);
renderPassInfo.setDependencyCount(1);
renderPassInfo.setPDependencies(&dependency);
{
auto check = m_graphics->getLogicalDevice().createRenderPass(&renderPassInfo, nullptr, &m_renderPasses.onscreen);
gAssert(check == vk::Result::eSuccess);
}
}
// Offscreen
{
// Set up separate renderpass with references to the color and depth attachments
std::array<vk::AttachmentDescription, 5> attachmentDescs = {};
// Input attachment properties
for (size_t i = 0; i < attachmentDescs.size(); ++i)
{
attachmentDescs[i].setSamples(vk::SampleCountFlagBits::e1);
attachmentDescs[i].setLoadOp(vk::AttachmentLoadOp::eClear);
attachmentDescs[i].setStoreOp(vk::AttachmentStoreOp::eStore);
attachmentDescs[i].setStencilLoadOp(vk::AttachmentLoadOp::eClear);
attachmentDescs[i].setStencilStoreOp(vk::AttachmentStoreOp::eStore);
if (i == attachmentDescs.size() - 1)
{
attachmentDescs[i].setInitialLayout(vk::ImageLayout::eUndefined);
attachmentDescs[i].setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
}
else
{
attachmentDescs[i].setInitialLayout(vk::ImageLayout::eUndefined);
attachmentDescs[i].setFinalLayout(vk::ImageLayout::eColorAttachmentOptimal);
}
}
// Formats
attachmentDescs[0].setFormat(vk::Format::eR16G16B16A16Sfloat);
attachmentDescs[1].setFormat(vk::Format::eR16G16B16A16Sfloat);
attachmentDescs[2].setFormat(m_graphics->getSurfaceColorFormat());
attachmentDescs[3].setFormat(vk::Format::eR16G16B16A16Sfloat);
attachmentDescs[4].setFormat(m_graphics->getDepthFormat());
std::array<vk::AttachmentReference, 4> colorReferences = {};
colorReferences[0] = { 0, vk::ImageLayout::eColorAttachmentOptimal };
colorReferences[1] = { 1, vk::ImageLayout::eColorAttachmentOptimal };
colorReferences[2] = { 2, vk::ImageLayout::eColorAttachmentOptimal };
colorReferences[3] = { 3, vk::ImageLayout::eColorAttachmentOptimal };
vk::AttachmentReference depthReference = {};
depthReference.setAttachment(4);
depthReference.setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
vk::SubpassDescription subpass = {};
subpass.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics);
subpass.setPColorAttachments(colorReferences.data());
subpass.setColorAttachmentCount(static_cast<uint32_t>(colorReferences.size()));
subpass.setPDepthStencilAttachment(&depthReference);
// Use subpass dependencies for attachment layput transitions
std::array<vk::SubpassDependency, 2> dependencies =
{
vk::SubpassDependency
(
VK_SUBPASS_EXTERNAL,
0,
vk::PipelineStageFlagBits::eBottomOfPipe,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::AccessFlagBits::eMemoryRead,
vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite,
vk::DependencyFlagBits::eByRegion
),
vk::SubpassDependency
(
0,
VK_SUBPASS_EXTERNAL,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::PipelineStageFlagBits::eBottomOfPipe,
vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite,
vk::AccessFlagBits::eMemoryRead,
vk::DependencyFlagBits::eByRegion
)
};
vk::RenderPassCreateInfo renderPassInfo = {};
renderPassInfo.setPAttachments(attachmentDescs.data());
renderPassInfo.setAttachmentCount(static_cast<uint32_t>(attachmentDescs.size()));
renderPassInfo.setSubpassCount(1);
renderPassInfo.setPSubpasses(&subpass);
renderPassInfo.setDependencyCount(static_cast<uint32_t>(dependencies.size()));
renderPassInfo.setPDependencies(dependencies.data());
// Create render pass
m_renderPasses.offscreen = m_graphics->getLogicalDevice().createRenderPass(renderPassInfo);
}
// Lighting
{
// Set up separate renderpass with references to the color and depth attachments
std::array<vk::AttachmentDescription, 5> attachmentDescs = {};
// Input attachment properties
for (size_t i = 0; i < attachmentDescs.size(); ++i)
{
attachmentDescs[i].setSamples(vk::SampleCountFlagBits::e1);
attachmentDescs[i].setLoadOp(vk::AttachmentLoadOp::eLoad);
attachmentDescs[i].setStoreOp(vk::AttachmentStoreOp::eStore);
attachmentDescs[i].setStencilLoadOp(vk::AttachmentLoadOp::eLoad);
attachmentDescs[i].setStencilStoreOp(vk::AttachmentStoreOp::eStore);
if (i == attachmentDescs.size() - 1)
{
attachmentDescs[i].setInitialLayout(vk::ImageLayout::eUndefined);
attachmentDescs[i].setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
}
else
{
attachmentDescs[i].setInitialLayout(vk::ImageLayout::eUndefined);
attachmentDescs[i].setFinalLayout(vk::ImageLayout::eColorAttachmentOptimal);
}
}
// Formats
attachmentDescs[0].setFormat(vk::Format::eR16G16B16A16Sfloat);
attachmentDescs[1].setFormat(vk::Format::eR16G16B16A16Sfloat);
attachmentDescs[2].setFormat(m_graphics->getSurfaceColorFormat());
attachmentDescs[3].setFormat(vk::Format::eR16G16B16A16Sfloat);
attachmentDescs[4].setFormat(m_graphics->getDepthFormat());
std::array<vk::AttachmentReference, 4> colorReferences = {};
colorReferences[0] = { 0, vk::ImageLayout::eColorAttachmentOptimal };
colorReferences[1] = { 1, vk::ImageLayout::eColorAttachmentOptimal };
colorReferences[2] = { 2, vk::ImageLayout::eColorAttachmentOptimal };
colorReferences[3] = { 3, vk::ImageLayout::eColorAttachmentOptimal };
vk::AttachmentReference depthReference = {};
depthReference.setAttachment(4);
depthReference.setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
vk::SubpassDescription subpass = {};
subpass.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics);
subpass.setPColorAttachments(colorReferences.data());
subpass.setColorAttachmentCount(static_cast<uint32_t>(colorReferences.size()));
subpass.setPDepthStencilAttachment(&depthReference);
// Use subpass dependencies for attachment layput transitions
std::array<vk::SubpassDependency, 2> dependencies =
{
vk::SubpassDependency
(
VK_SUBPASS_EXTERNAL,
0,
vk::PipelineStageFlagBits::eBottomOfPipe,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::AccessFlagBits::eMemoryRead,
vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite,
vk::DependencyFlagBits::eByRegion
),
vk::SubpassDependency
(
0,
VK_SUBPASS_EXTERNAL,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::PipelineStageFlagBits::eBottomOfPipe,
vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite,
vk::AccessFlagBits::eMemoryRead,
vk::DependencyFlagBits::eByRegion
)
};
vk::RenderPassCreateInfo renderPassInfo = {};
renderPassInfo.setPAttachments(attachmentDescs.data());
renderPassInfo.setAttachmentCount(static_cast<uint32_t>(attachmentDescs.size()));
renderPassInfo.setSubpassCount(1);
renderPassInfo.setPSubpasses(&subpass);
renderPassInfo.setDependencyCount(static_cast<uint32_t>(dependencies.size()));
renderPassInfo.setPDependencies(dependencies.data());
// Create render pass
m_renderPasses.lighting = m_graphics->getLogicalDevice().createRenderPass(renderPassInfo);
}
}
void Renderer::initSwapchain()
{
// Get surface capabilities, present modes, and size
const auto surfaceCapabilities = m_graphics->getPhysicalDevice().getSurfaceCapabilitiesKHR(m_graphics->getSurface());
const auto surfacePresentModes = m_graphics->getPhysicalDevice().getSurfacePresentModesKHR(m_graphics->getSurface());
// Get best present mode
auto presentMode = vk::PresentModeKHR::eImmediate;
for (auto& pm : surfacePresentModes)
if (pm == vk::PresentModeKHR::eMailbox)
{
presentMode = vk::PresentModeKHR::eMailbox;
break;
}
// Make sure we have enough images
assert(surfaceCapabilities.maxImageCount >= 3);
// Get optimum image count
uint32_t imageCount = surfaceCapabilities.minImageCount + 1;
if (surfaceCapabilities.maxImageCount > 0 && imageCount > surfaceCapabilities.maxImageCount)
imageCount = surfaceCapabilities.maxImageCount;
vk::SwapchainCreateInfoKHR swapchainCreateInfo = {};
swapchainCreateInfo.setSurface(m_graphics->getSurface()); // Surface to create swapchain for
swapchainCreateInfo.setMinImageCount(imageCount); // Minimum number of swapchain images
swapchainCreateInfo.setImageFormat(m_graphics->getSurfaceColorFormat()); // Swapchain images color format
swapchainCreateInfo.setImageColorSpace(m_graphics->getSurfaceColorSpace()); // Swapchain images color space
swapchainCreateInfo.setImageExtent({ m_graphics->getWidth(), m_graphics->getHeight() }); // Size of swapchain images.
swapchainCreateInfo.setImageArrayLayers(1); // I honestly don't know what this does
swapchainCreateInfo.setImageUsage(vk::ImageUsageFlagBits::eColorAttachment); // Type of image
swapchainCreateInfo.setPreTransform(surfaceCapabilities.currentTransform); // Image transformation
swapchainCreateInfo.setCompositeAlpha(vk::CompositeAlphaFlagBitsKHR::eOpaque); // Alpha mode
swapchainCreateInfo.setPresentMode(presentMode); // Presentation mode
swapchainCreateInfo.setClipped(true); // We don't care about the color of obsucured pixels
std::array<uint32_t, 2> qfi =
{
static_cast<uint32_t>(m_graphics->getQueueFamilyIndices().graphicsFamily),
static_cast<uint32_t>(m_graphics->getQueueFamilyIndices().presentFamily)
};
if (qfi[0] != qfi[1])
{
swapchainCreateInfo.setQueueFamilyIndexCount(static_cast<uint32_t>(qfi.size())); // Number of queue family indices
swapchainCreateInfo.setPQueueFamilyIndices(qfi.data()); // Queue family indices
swapchainCreateInfo.setImageSharingMode(vk::SharingMode::eConcurrent); // Sharing mode for images
}
else
{
swapchainCreateInfo.setQueueFamilyIndexCount(0);
swapchainCreateInfo.setPQueueFamilyIndices(nullptr);
swapchainCreateInfo.setImageSharingMode(vk::SharingMode::eExclusive);
}
// Create swapchain
{
auto check = m_graphics->getLogicalDevice().createSwapchainKHR(&swapchainCreateInfo, nullptr, &m_swapchain.swapchain);
gAssert(check == vk::Result::eSuccess);
}
// Get swapchain images
m_swapchain.images = m_graphics->getLogicalDevice().getSwapchainImagesKHR(m_swapchain.swapchain);
}
void Renderer::initDepthResources()
{
// Create depth image data
m_graphics->createImage
(
m_graphics->getWidth(),
m_graphics->getHeight(),
m_graphics->getDepthFormat(),
vk::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eDepthStencilAttachment,
vk::MemoryPropertyFlagBits::eDeviceLocal,
m_depthTexture.image,
m_depthTexture.memory
);
// Create image view
m_depthTexture.imageView = m_graphics->createImageView
(
m_depthTexture.image,
m_graphics->getDepthFormat(),
vk::ImageAspectFlagBits::eDepth | vk::ImageAspectFlagBits::eStencil
);
// Transition layout
m_graphics->transitionImageLayout
(
m_depthTexture.image,
m_graphics->getDepthFormat(),
vk::ImageLayout::eUndefined,
vk::ImageLayout::eDepthStencilAttachmentOptimal
);
}
void Renderer::initSwapchainBuffers()
{
auto logicalDevice = m_graphics->getLogicalDevice();
m_swapchain.buffers.resize(m_swapchain.images.size());
for (size_t i = 0; i < m_swapchain.images.size(); ++i)
{
m_swapchain.buffers[i].image = m_swapchain.images[i];
vk::ImageViewCreateInfo imageView = {};
imageView.setFlags(vk::ImageViewCreateFlags()); // Creation flags
imageView.setImage(m_swapchain.images[i]); // Image to view
imageView.setViewType(vk::ImageViewType::e2D); // Type of image
imageView.setFormat(m_graphics->getSurfaceColorFormat()); // Color format of the image
imageView.setComponents(vk::ComponentMapping()); // I don't know
imageView.setSubresourceRange({ vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1 }); // Resource range
// Color
m_swapchain.buffers[i].view = logicalDevice.createImageView(imageView);
vk::FramebufferCreateInfo framebuffer = {};
framebuffer.setFlags(vk::FramebufferCreateFlags()); // Creation flags
framebuffer.setRenderPass(m_renderPasses.onscreen); // Render pass
framebuffer.setAttachmentCount(1); // Image view count
framebuffer.setPAttachments(&m_swapchain.buffers[i].view); // Image views
framebuffer.setWidth(m_graphics->getWidth()); // Width
framebuffer.setHeight(m_graphics->getHeight()); // Height
framebuffer.setLayers(1); // Layer count
// Framebuffer
m_swapchain.buffers[i].frameBuffer = logicalDevice.createFramebuffer(framebuffer);
}
}
void Renderer::initSemaphores()
{
vk::SemaphoreCreateInfo semaphoreInfo = {};
m_semaphores.imageAvailable = m_graphics->getLogicalDevice().createSemaphore(semaphoreInfo);
m_semaphores.renderFinished = m_graphics->getLogicalDevice().createSemaphore(semaphoreInfo);
m_semaphores.offscreen = m_graphics->getLogicalDevice().createSemaphore(semaphoreInfo);
}
void Renderer::initLighting()
{
// create lighting uniform buffer
m_lightingUniformBuffer = m_graphics->createBuffer
(
static_cast<vk::DeviceSize>(sizeof(LightingData)),
vk::BufferUsageFlagBits::eUniformBuffer,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent
);
// create skybox uniform buffer
m_skyboxUniformBuffer = m_graphics->createBuffer
(
static_cast<vk::DeviceSize>(sizeof(VertexShaderData)),
vk::BufferUsageFlagBits::eUniformBuffer,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent
);
// Create skybox command buffer
m_commands.skybox = createCommandBuffer(vk::CommandBufferLevel::eSecondary);
}
void Renderer::initDescriptorSetLayouts()
{
// Standard material descriptor set layout
{
std::array<vk::DescriptorSetLayoutBinding, 4> bindings = {};
// Vertex bindings
bindings[0].setBinding(0);
bindings[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
bindings[0].setDescriptorCount(1);
bindings[0].setStageFlags(vk::ShaderStageFlagBits::eVertex);
bindings[1].setBinding(1);
bindings[1].setDescriptorType(vk::DescriptorType::eUniformBuffer);
bindings[1].setDescriptorCount(1);
bindings[1].setStageFlags(vk::ShaderStageFlagBits::eVertex);
// Fragment bindings
bindings[2].setBinding(2);
bindings[2].setDescriptorType(vk::DescriptorType::eUniformBuffer);
bindings[2].setDescriptorCount(1);
bindings[2].setStageFlags(vk::ShaderStageFlagBits::eFragment);
bindings[3].setBinding(3);
bindings[3].setDescriptorType(vk::DescriptorType::eUniformBuffer);
bindings[3].setDescriptorCount(1);
bindings[3].setStageFlags(vk::ShaderStageFlagBits::eFragment);
vk::DescriptorSetLayoutCreateInfo createInfo = {};
createInfo.setBindingCount(static_cast<uint32_t>(bindings.size()));
createInfo.setPBindings(bindings.data());
// Create descriptor set layout
m_descriptors.descriptorSetLayout = m_graphics->getLogicalDevice().createDescriptorSetLayout(createInfo);
}
// Lighting descriptor set Layout
{
std::array<vk::DescriptorSetLayoutBinding, 5> bindings = {};
// Lighting
bindings[0].setBinding(0);
bindings[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
bindings[0].setDescriptorCount(1);
bindings[0].setStageFlags(vk::ShaderStageFlagBits::eFragment);
// Position binding
bindings[1].setBinding(1);
bindings[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
bindings[1].setDescriptorCount(1);
bindings[1].setStageFlags(vk::ShaderStageFlagBits::eFragment);
// Normal binding
bindings[2].setBinding(2);
bindings[2].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
bindings[2].setDescriptorCount(1);
bindings[2].setStageFlags(vk::ShaderStageFlagBits::eFragment);
// Color binding
bindings[3].setBinding(3);
bindings[3].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
bindings[3].setDescriptorCount(1);
bindings[3].setStageFlags(vk::ShaderStageFlagBits::eFragment);
// Misc binding
bindings[4].setBinding(4);
bindings[4].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
bindings[4].setDescriptorCount(1);
bindings[4].setStageFlags(vk::ShaderStageFlagBits::eFragment);
vk::DescriptorSetLayoutCreateInfo createInfo = {};
createInfo.setBindingCount(static_cast<uint32_t>(bindings.size()));
createInfo.setPBindings(bindings.data());
// Create descriptor set layout
m_descriptors.lightingDescriptorSetLayout = m_graphics->getLogicalDevice().createDescriptorSetLayout(createInfo);
}
// Screen descriptor set Layout
{
std::array<vk::DescriptorSetLayoutBinding, 1> bindings = {};
// Color binding
bindings[0].setBinding(0);
bindings[0].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
bindings[0].setDescriptorCount(1);
bindings[0].setStageFlags(vk::ShaderStageFlagBits::eFragment);
vk::DescriptorSetLayoutCreateInfo createInfo = {};
createInfo.setBindingCount(static_cast<uint32_t>(bindings.size()));
createInfo.setPBindings(bindings.data());
// Create descriptor set layout
m_descriptors.screenDescriptorSetLayout = m_graphics->getLogicalDevice().createDescriptorSetLayout(createInfo);
}
// Skybox descriptor set Layout
{
std::array<vk::DescriptorSetLayoutBinding, 2> bindings = {};
// Lighting
bindings[0].setBinding(0);
bindings[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
bindings[0].setDescriptorCount(1);
bindings[0].setStageFlags(vk::ShaderStageFlagBits::eVertex);
// Position binding
bindings[1].setBinding(1);
bindings[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
bindings[1].setDescriptorCount(1);
bindings[1].setStageFlags(vk::ShaderStageFlagBits::eFragment);
vk::DescriptorSetLayoutCreateInfo createInfo = {};
createInfo.setBindingCount(static_cast<uint32_t>(bindings.size()));
createInfo.setPBindings(bindings.data());
// Create descriptor set layout
m_descriptors.skyboxDescriptorSetLayout = m_graphics->getLogicalDevice().createDescriptorSetLayout(createInfo);
}
}
void Renderer::initDescriptorPool()
{
std::array<vk::DescriptorPoolSize, 2> poolSizes = {};
poolSizes[0].setDescriptorCount(3);
poolSizes[0].setType(vk::DescriptorType::eUniformBuffer);
poolSizes[1].setDescriptorCount(6);
poolSizes[1].setType(vk::DescriptorType::eCombinedImageSampler);
vk::DescriptorPoolCreateInfo poolInfo = {};
poolInfo.setPoolSizeCount(static_cast<uint32_t>(poolSizes.size()));
poolInfo.setPPoolSizes(poolSizes.data());
poolInfo.setMaxSets(3);
m_descriptors.descriptorPool = m_graphics->getLogicalDevice().createDescriptorPool(poolInfo);
}
void Renderer::initDescriptorSets()
{
// Lighting descriptor set
{
vk::DescriptorSetAllocateInfo allocInfo = {};
allocInfo.setDescriptorPool(m_descriptors.descriptorPool);
allocInfo.setDescriptorSetCount(1);
allocInfo.setPSetLayouts(&m_descriptors.lightingDescriptorSetLayout);
// Allocate descriptor sets
m_descriptors.lightingDescriptorSet = m_graphics->getLogicalDevice().allocateDescriptorSets(allocInfo)[0];
// Lighting
vk::DescriptorBufferInfo bufferInfo = {};
bufferInfo.setBuffer(m_lightingUniformBuffer.buffer);
bufferInfo.setOffset(0);
bufferInfo.setRange(static_cast<VkDeviceSize>(sizeof(LightingData)));
vk::WriteDescriptorSet descWrite = {};
descWrite.setDstSet(m_descriptors.lightingDescriptorSet);
descWrite.setDstBinding(0);
descWrite.setDstArrayElement(0);
descWrite.setDescriptorType(vk::DescriptorType::eUniformBuffer);
descWrite.setDescriptorCount(1);
descWrite.setPBufferInfo(&bufferInfo);
descWrite.setPImageInfo(nullptr);
descWrite.setPTexelBufferView(nullptr);
m_graphics->getLogicalDevice().updateDescriptorSets(1, &descWrite, 0, nullptr);
}
// Screen descriptor set
{
vk::DescriptorSetAllocateInfo allocInfo = {};
allocInfo.setDescriptorPool(m_descriptors.descriptorPool);
allocInfo.setDescriptorSetCount(1);
allocInfo.setPSetLayouts(&m_descriptors.screenDescriptorSetLayout);
// Allocate descriptor sets
m_descriptors.screenDescriptorSet = m_graphics->getLogicalDevice().allocateDescriptorSets(allocInfo)[0];
}
// Skybox descriptor set
{
vk::DescriptorSetAllocateInfo allocInfo = {};
allocInfo.setDescriptorPool(m_descriptors.descriptorPool);
allocInfo.setDescriptorSetCount(1);
allocInfo.setPSetLayouts(&m_descriptors.skyboxDescriptorSetLayout);
// Allocate descriptor sets
m_descriptors.skyboxDescriptorSet = m_graphics->getLogicalDevice().allocateDescriptorSets(allocInfo)[0];
}
}
void Renderer::initShaders()
{
std::vector<uint32_t> inds =
{
0, 2, 1,
2, 3, 1
};
std::vector<glm::vec3> verts =
{
glm::vec3(-1, -1, 0),
glm::vec3(-1, 1, 0),
glm::vec3( 1, -1, 0),
glm::vec3( 1, 1, 0)
};
std::vector<glm::vec2> uvs =
{
glm::vec2(0, 0),
glm::vec2(0, 1),
glm::vec2(1, 0),
glm::vec2(1, 1)
};
// Resize mesh allocator if needed
if (m_meshAllocator->getResourceCount() + 2 > m_meshAllocator->getMaxResourceCount())
m_meshAllocator->resize(m_meshAllocator->getMaxResourceCount() + 2, true);
m_screenQuad = Handle<Mesh>(m_meshAllocator, m_meshAllocator->allocate());
m_skybox = Handle<Mesh>(m_meshAllocator, m_meshAllocator->allocate());
// Make quad
::new(m_screenQuad.get())(Mesh)
(
m_graphics,
inds,
verts,
uvs
);
// Make skybox
::new(m_skybox.get())(Mesh)
(
m_graphics,
GUST_SKYBOX_MESH_PATH
);
// Create screen shader
{
// Load shader byte code
std::vector<char> fragSource = readBinary(GUST_SCREEN_FRAGMENT_SHADER_PATH);
std::vector<char> vertSource = readBinary(GUST_SCREEN_VERTEX_SHADER_PATH);
// Vertex shader module
{
// Align code
std::vector<uint32_t> codeAligned(vertSource.size() / sizeof(uint32_t) + 1);
memcpy(codeAligned.data(), vertSource.data(), vertSource.size());
vk::ShaderModuleCreateInfo createInfo = {};
createInfo.setCodeSize(vertSource.size());
createInfo.setPCode(codeAligned.data());
// Create shader module
m_screenShader.vertexShader = m_graphics->getLogicalDevice().createShaderModule(createInfo);
}
// Fragment shader module
{
// Align code
std::vector<uint32_t> codeAligned(fragSource.size() / sizeof(uint32_t) + 1);
memcpy(codeAligned.data(), fragSource.data(), fragSource.size());
vk::ShaderModuleCreateInfo createInfo = {};
createInfo.setCodeSize(fragSource.size());
createInfo.setPCode(codeAligned.data());
// Create shader module
m_screenShader.fragmentShader = m_graphics->getLogicalDevice().createShaderModule(createInfo);
}
// Vertex shader stage create info
vk::PipelineShaderStageCreateInfo vertShaderStageInfo = {};
vertShaderStageInfo.setStage(vk::ShaderStageFlagBits::eVertex);
vertShaderStageInfo.setModule(m_screenShader.vertexShader);
vertShaderStageInfo.setPName("main");
// Fragment shader stage create info
vk::PipelineShaderStageCreateInfo fragShaderStageInfo = {};
fragShaderStageInfo.setStage(vk::ShaderStageFlagBits::eFragment);
fragShaderStageInfo.setModule(m_screenShader.fragmentShader);
fragShaderStageInfo.setPName("main");
m_screenShader.shaderStages = { vertShaderStageInfo, fragShaderStageInfo };
}
// Create lighting shader
{
// Load shader byte code
std::vector<char> fragSource = readBinary(GUST_LIGHTING_FRAGMENT_SHADER_PATH);
std::vector<char> vertSource = readBinary(GUST_LIGHTING_VERTEX_SHADER_PATH);
// Vertex shader module
{
// Align code
std::vector<uint32_t> codeAligned(vertSource.size() / sizeof(uint32_t) + 1);
memcpy(codeAligned.data(), vertSource.data(), vertSource.size());
vk::ShaderModuleCreateInfo createInfo = {};
createInfo.setCodeSize(vertSource.size());
createInfo.setPCode(codeAligned.data());
// Create shader module
m_lightingShader.vertexShader = m_graphics->getLogicalDevice().createShaderModule(createInfo);
}
// Fragment shader module
{
// Align code
std::vector<uint32_t> codeAligned(fragSource.size() / sizeof(uint32_t) + 1);
memcpy(codeAligned.data(), fragSource.data(), fragSource.size());
vk::ShaderModuleCreateInfo createInfo = {};
createInfo.setCodeSize(fragSource.size());
createInfo.setPCode(codeAligned.data());
// Create shader module
m_lightingShader.fragmentShader = m_graphics->getLogicalDevice().createShaderModule(createInfo);
}
// Vertex shader stage create info
vk::PipelineShaderStageCreateInfo vertShaderStageInfo = {};
vertShaderStageInfo.setStage(vk::ShaderStageFlagBits::eVertex);
vertShaderStageInfo.setModule(m_lightingShader.vertexShader);
vertShaderStageInfo.setPName("main");
// Fragment shader stage create info
vk::PipelineShaderStageCreateInfo fragShaderStageInfo = {};
fragShaderStageInfo.setStage(vk::ShaderStageFlagBits::eFragment);
fragShaderStageInfo.setModule(m_lightingShader.fragmentShader);
fragShaderStageInfo.setPName("main");
m_lightingShader.shaderStages = { vertShaderStageInfo, fragShaderStageInfo };
}
// Create skybox shader
{
// Load shader byte code
std::vector<char> fragSource = readBinary(GUST_SKYBOX_FRAGMENT_SHADER_PATH);
std::vector<char> vertSource = readBinary(GUST_SKYBOX_VERTEX_SHADER_PATH);
// Vertex shader module
{
// Align code
std::vector<uint32_t> codeAligned(vertSource.size() / sizeof(uint32_t) + 1);
memcpy(codeAligned.data(), vertSource.data(), vertSource.size());
vk::ShaderModuleCreateInfo createInfo = {};
createInfo.setCodeSize(vertSource.size());
createInfo.setPCode(codeAligned.data());
// Create shader module
m_skyboxShader.vertexShader = m_graphics->getLogicalDevice().createShaderModule(createInfo);
}
// Fragment shader module
{
// Align code
std::vector<uint32_t> codeAligned(fragSource.size() / sizeof(uint32_t) + 1);
memcpy(codeAligned.data(), fragSource.data(), fragSource.size());
vk::ShaderModuleCreateInfo createInfo = {};
createInfo.setCodeSize(fragSource.size());
createInfo.setPCode(codeAligned.data());
// Create shader module
m_skyboxShader.fragmentShader = m_graphics->getLogicalDevice().createShaderModule(createInfo);
}
// Vertex shader stage create info
vk::PipelineShaderStageCreateInfo vertShaderStageInfo = {};
vertShaderStageInfo.setStage(vk::ShaderStageFlagBits::eVertex);
vertShaderStageInfo.setModule(m_skyboxShader.vertexShader);
vertShaderStageInfo.setPName("main");
// Fragment shader stage create info
vk::PipelineShaderStageCreateInfo fragShaderStageInfo = {};
fragShaderStageInfo.setStage(vk::ShaderStageFlagBits::eFragment);
fragShaderStageInfo.setModule(m_skyboxShader.fragmentShader);
fragShaderStageInfo.setPName("main");
m_skyboxShader.shaderStages = { vertShaderStageInfo, fragShaderStageInfo };
}
// Create lighting graphics pipeline
{
auto bindingDescription = Vertex::getBindingDescription();
auto attributeDescriptions = Vertex::getAttributeDescriptions();
vk::PipelineVertexInputStateCreateInfo vertexInputInfo = {};
vertexInputInfo.setVertexBindingDescriptionCount(1);
vertexInputInfo.setVertexAttributeDescriptionCount(static_cast<uint32_t>(attributeDescriptions.size()));
vertexInputInfo.setPVertexBindingDescriptions(&bindingDescription);
vertexInputInfo.setPVertexAttributeDescriptions(attributeDescriptions.data());
vk::PipelineInputAssemblyStateCreateInfo inputAssembly = {};
inputAssembly.setTopology(vk::PrimitiveTopology::eTriangleList);
inputAssembly.setPrimitiveRestartEnable(false);
vk::Viewport viewport = {};
viewport.setX(0.0f);
viewport.setY(0.0f);
viewport.setWidth((float)m_graphics->getWidth());
viewport.setHeight((float)m_graphics->getHeight());
viewport.setMinDepth(0.0f);
viewport.setMaxDepth(1.0f);
vk::Extent2D extents = {};
extents.setHeight(m_graphics->getHeight());
extents.setWidth(m_graphics->getWidth());
vk::Rect2D scissor = {};
scissor.setOffset({ 0, 0 });
scissor.setExtent(extents);
vk::PipelineViewportStateCreateInfo viewportState = {};
viewportState.setViewportCount(1);
viewportState.setPViewports(&viewport);
viewportState.setScissorCount(1);
viewportState.setPScissors(&scissor);
vk::PipelineRasterizationStateCreateInfo rasterizer = {};
rasterizer.setDepthClampEnable(false);
rasterizer.setRasterizerDiscardEnable(false);
rasterizer.setPolygonMode(vk::PolygonMode::eFill);
rasterizer.setLineWidth(1.0f);
rasterizer.setCullMode(vk::CullModeFlagBits::eBack);
rasterizer.setFrontFace(vk::FrontFace::eClockwise);
rasterizer.setDepthBiasEnable(false);
rasterizer.setDepthBiasConstantFactor(0.0f);
rasterizer.setDepthBiasClamp(0.0f);
rasterizer.setDepthBiasSlopeFactor(0.0f);
vk::PipelineMultisampleStateCreateInfo multisampling = {};
multisampling.setSampleShadingEnable(false);
multisampling.setRasterizationSamples(vk::SampleCountFlagBits::e1);
multisampling.setMinSampleShading(1.0f);
multisampling.setPSampleMask(nullptr);
multisampling.setAlphaToCoverageEnable(false);
multisampling.setAlphaToOneEnable(false);
vk::StencilOpState stencil = {};
stencil.setFailOp(vk::StencilOp::eKeep);
stencil.setPassOp(vk::StencilOp::eReplace);
stencil.setDepthFailOp(vk::StencilOp::eKeep);
stencil.setCompareOp(vk::CompareOp::eEqual);
stencil.setWriteMask(1);
stencil.setReference(1);
stencil.setCompareMask(1);
vk::PipelineDepthStencilStateCreateInfo depthStencil = {};
depthStencil.setDepthTestEnable(false);
depthStencil.setDepthWriteEnable(false);
depthStencil.setDepthCompareOp(vk::CompareOp::eLess);
depthStencil.setDepthBoundsTestEnable(false);
depthStencil.setMinDepthBounds(0.0f);
depthStencil.setMaxDepthBounds(1.0f);
depthStencil.setStencilTestEnable(true);
depthStencil.setFront(stencil);
depthStencil.setBack(stencil);
std::array<vk::PipelineColorBlendAttachmentState, 4> colorBlendAttachments = {};
for (size_t i = 0; i < colorBlendAttachments.size(); ++i)
{
colorBlendAttachments[i].setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA);
colorBlendAttachments[i].setBlendEnable(true);
colorBlendAttachments[i].setSrcColorBlendFactor(vk::BlendFactor::eSrcAlpha);
colorBlendAttachments[i].setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha);
colorBlendAttachments[i].setColorBlendOp(vk::BlendOp::eAdd);
colorBlendAttachments[i].setSrcAlphaBlendFactor(vk::BlendFactor::eOne);
colorBlendAttachments[i].setDstAlphaBlendFactor(vk::BlendFactor::eZero);
colorBlendAttachments[i].setAlphaBlendOp(vk::BlendOp::eAdd);
}
vk::PipelineColorBlendStateCreateInfo colorBlending = {};
colorBlending.setLogicOpEnable(false);
colorBlending.setLogicOp(vk::LogicOp::eCopy);
colorBlending.setAttachmentCount(static_cast<uint32_t>(colorBlendAttachments.size()));
colorBlending.setPAttachments(colorBlendAttachments.data());
colorBlending.setBlendConstants({ 0.0f, 0.0f, 0.0f, 0.0f });
vk::DynamicState dynamicStates[] =
{
vk::DynamicState::eViewport,
vk::DynamicState::eLineWidth
};
vk::PipelineDynamicStateCreateInfo dynamicState = {};
dynamicState.setDynamicStateCount(2);
dynamicState.setPDynamicStates(dynamicStates);
vk::PipelineLayoutCreateInfo pipelineLayoutInfo = {};
pipelineLayoutInfo.setSetLayoutCount(1);
pipelineLayoutInfo.setPSetLayouts(&m_descriptors.lightingDescriptorSetLayout);
// Create pipeline layout
m_lightingShader.graphicsPipelineLayout = m_graphics->getLogicalDevice().createPipelineLayout(pipelineLayoutInfo);
vk::GraphicsPipelineCreateInfo pipelineInfo = {};
pipelineInfo.setStageCount(2);
pipelineInfo.setPStages(m_lightingShader.shaderStages.data());
pipelineInfo.setPVertexInputState(&vertexInputInfo);
pipelineInfo.setPInputAssemblyState(&inputAssembly);
pipelineInfo.setPViewportState(&viewportState);
pipelineInfo.setPRasterizationState(&rasterizer);
pipelineInfo.setPMultisampleState(&multisampling);
pipelineInfo.setPDepthStencilState(nullptr);
pipelineInfo.setPColorBlendState(&colorBlending);
pipelineInfo.setPDynamicState(nullptr);
pipelineInfo.setLayout(m_lightingShader.graphicsPipelineLayout);
pipelineInfo.setRenderPass(m_renderPasses.offscreen);
pipelineInfo.setSubpass(0);
pipelineInfo.setBasePipelineHandle({ nullptr });
pipelineInfo.setBasePipelineIndex(-1);
pipelineInfo.setPDepthStencilState(&depthStencil);
// Create graphics pipeline
m_lightingShader.graphicsPipeline = m_graphics->getLogicalDevice().createGraphicsPipeline({}, pipelineInfo);
}
// Create screen graphics pipeline
{
auto bindingDescription = Vertex::getBindingDescription();
auto attributeDescriptions = Vertex::getAttributeDescriptions();
vk::PipelineVertexInputStateCreateInfo vertexInputInfo = {};
vertexInputInfo.setVertexBindingDescriptionCount(1);
vertexInputInfo.setVertexAttributeDescriptionCount(static_cast<uint32_t>(attributeDescriptions.size()));
vertexInputInfo.setPVertexBindingDescriptions(&bindingDescription);
vertexInputInfo.setPVertexAttributeDescriptions(attributeDescriptions.data());
vk::PipelineInputAssemblyStateCreateInfo inputAssembly = {};
inputAssembly.setTopology(vk::PrimitiveTopology::eTriangleList);
inputAssembly.setPrimitiveRestartEnable(false);
vk::Viewport viewport = {};
viewport.setX(0.0f);
viewport.setY(0.0f);
viewport.setWidth((float)m_graphics->getWidth());
viewport.setHeight((float)m_graphics->getHeight());
viewport.setMinDepth(0.0f);
viewport.setMaxDepth(1.0f);
vk::Extent2D extents = {};
extents.setHeight(m_graphics->getHeight());
extents.setWidth(m_graphics->getWidth());
vk::Rect2D scissor = {};
scissor.setOffset({ 0, 0 });
scissor.setExtent(extents);
vk::PipelineViewportStateCreateInfo viewportState = {};
viewportState.setViewportCount(1);
viewportState.setPViewports(&viewport);
viewportState.setScissorCount(1);
viewportState.setPScissors(&scissor);
vk::PipelineRasterizationStateCreateInfo rasterizer = {};
rasterizer.setDepthClampEnable(false);
rasterizer.setRasterizerDiscardEnable(false);
rasterizer.setPolygonMode(vk::PolygonMode::eFill);
rasterizer.setLineWidth(1.0f);
rasterizer.setCullMode(vk::CullModeFlagBits::eBack);
rasterizer.setFrontFace(vk::FrontFace::eClockwise);
rasterizer.setDepthBiasEnable(false);
rasterizer.setDepthBiasConstantFactor(0.0f);
rasterizer.setDepthBiasClamp(0.0f);
rasterizer.setDepthBiasSlopeFactor(0.0f);
vk::PipelineMultisampleStateCreateInfo multisampling = {};
multisampling.setSampleShadingEnable(false);
multisampling.setRasterizationSamples(vk::SampleCountFlagBits::e1);
multisampling.setMinSampleShading(1.0f);
multisampling.setPSampleMask(nullptr);
multisampling.setAlphaToCoverageEnable(false);
multisampling.setAlphaToOneEnable(false);
vk::PipelineDepthStencilStateCreateInfo depthStencil = {};
depthStencil.setDepthTestEnable(false);
depthStencil.setDepthWriteEnable(false);
depthStencil.setDepthCompareOp(vk::CompareOp::eLess);
depthStencil.setDepthBoundsTestEnable(false);
depthStencil.setMinDepthBounds(0.0f);
depthStencil.setMaxDepthBounds(1.0f);
depthStencil.setStencilTestEnable(false);
depthStencil.setFront({});
depthStencil.setBack({});
vk::PipelineColorBlendAttachmentState colorBlendAttachment = {};
colorBlendAttachment.setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA);
colorBlendAttachment.setBlendEnable(false);
colorBlendAttachment.setSrcColorBlendFactor(vk::BlendFactor::eOne);
colorBlendAttachment.setDstColorBlendFactor(vk::BlendFactor::eZero);
colorBlendAttachment.setColorBlendOp(vk::BlendOp::eAdd);
colorBlendAttachment.setSrcAlphaBlendFactor(vk::BlendFactor::eOne);
colorBlendAttachment.setDstAlphaBlendFactor(vk::BlendFactor::eZero);
colorBlendAttachment.setAlphaBlendOp(vk::BlendOp::eAdd);
vk::PipelineColorBlendStateCreateInfo colorBlending = {};
colorBlending.setLogicOpEnable(false);
colorBlending.setLogicOp(vk::LogicOp::eCopy);
colorBlending.setAttachmentCount(1);
colorBlending.setPAttachments(&colorBlendAttachment);
colorBlending.setBlendConstants({ 0.0f, 0.0f, 0.0f, 0.0f });
vk::DynamicState dynamicStates[] =
{
vk::DynamicState::eViewport,
vk::DynamicState::eLineWidth
};
vk::PipelineDynamicStateCreateInfo dynamicState = {};
dynamicState.setDynamicStateCount(2);
dynamicState.setPDynamicStates(dynamicStates);
vk::PipelineLayoutCreateInfo pipelineLayoutInfo = {};
pipelineLayoutInfo.setSetLayoutCount(1);
pipelineLayoutInfo.setPSetLayouts(&m_descriptors.screenDescriptorSetLayout);
// Create pipeline layout
m_screenShader.graphicsPipelineLayout = m_graphics->getLogicalDevice().createPipelineLayout(pipelineLayoutInfo);
vk::GraphicsPipelineCreateInfo pipelineInfo = {};
pipelineInfo.setStageCount(2);
pipelineInfo.setPStages(m_screenShader.shaderStages.data());
pipelineInfo.setPVertexInputState(&vertexInputInfo);
pipelineInfo.setPInputAssemblyState(&inputAssembly);
pipelineInfo.setPViewportState(&viewportState);
pipelineInfo.setPRasterizationState(&rasterizer);
pipelineInfo.setPMultisampleState(&multisampling);
pipelineInfo.setPDepthStencilState(nullptr);
pipelineInfo.setPColorBlendState(&colorBlending);
pipelineInfo.setPDynamicState(nullptr);
pipelineInfo.setLayout(m_screenShader.graphicsPipelineLayout);
pipelineInfo.setRenderPass(m_renderPasses.onscreen);
pipelineInfo.setSubpass(0);
pipelineInfo.setBasePipelineHandle({ nullptr });
pipelineInfo.setBasePipelineIndex(-1);
pipelineInfo.setPDepthStencilState(&depthStencil);
// Create graphics pipeline
m_screenShader.graphicsPipeline = m_graphics->getLogicalDevice().createGraphicsPipeline({}, pipelineInfo);
}
// Create skybox graphics pipeline
{
auto bindingDescription = Vertex::getBindingDescription();
auto attributeDescriptions = Vertex::getAttributeDescriptions();
vk::PipelineVertexInputStateCreateInfo vertexInputInfo = {};
vertexInputInfo.setVertexBindingDescriptionCount(1);
vertexInputInfo.setVertexAttributeDescriptionCount(static_cast<uint32_t>(attributeDescriptions.size()));
vertexInputInfo.setPVertexBindingDescriptions(&bindingDescription);
vertexInputInfo.setPVertexAttributeDescriptions(attributeDescriptions.data());
vk::PipelineInputAssemblyStateCreateInfo inputAssembly = {};
inputAssembly.setTopology(vk::PrimitiveTopology::eTriangleList);
inputAssembly.setPrimitiveRestartEnable(false);
vk::Viewport viewport = {};
viewport.setX(0.0f);
viewport.setY(0.0f);
viewport.setWidth((float)m_graphics->getWidth());
viewport.setHeight((float)m_graphics->getHeight());
viewport.setMinDepth(0.0f);
viewport.setMaxDepth(1.0f);
vk::Extent2D extents = {};
extents.setHeight(m_graphics->getHeight());
extents.setWidth(m_graphics->getWidth());
vk::Rect2D scissor = {};
scissor.setOffset({ 0, 0 });
scissor.setExtent(extents);
vk::PipelineViewportStateCreateInfo viewportState = {};
viewportState.setViewportCount(1);
viewportState.setPViewports(&viewport);
viewportState.setScissorCount(1);
viewportState.setPScissors(&scissor);
vk::PipelineRasterizationStateCreateInfo rasterizer = {};
rasterizer.setDepthClampEnable(false);
rasterizer.setRasterizerDiscardEnable(false);
rasterizer.setPolygonMode(vk::PolygonMode::eFill);
rasterizer.setLineWidth(1.0f);
rasterizer.setCullMode(vk::CullModeFlagBits::eBack);
rasterizer.setFrontFace(vk::FrontFace::eClockwise);
rasterizer.setDepthBiasEnable(false);
rasterizer.setDepthBiasConstantFactor(0.0f);
rasterizer.setDepthBiasClamp(0.0f);
rasterizer.setDepthBiasSlopeFactor(0.0f);
vk::PipelineMultisampleStateCreateInfo multisampling = {};
multisampling.setSampleShadingEnable(false);
multisampling.setRasterizationSamples(vk::SampleCountFlagBits::e1);
multisampling.setMinSampleShading(1.0f);
multisampling.setPSampleMask(nullptr);
multisampling.setAlphaToCoverageEnable(false);
multisampling.setAlphaToOneEnable(false);
vk::StencilOpState stencil = {};
stencil.setFailOp(vk::StencilOp::eKeep);
stencil.setPassOp(vk::StencilOp::eKeep);
stencil.setDepthFailOp(vk::StencilOp::eKeep);
stencil.setCompareOp(vk::CompareOp::eEqual);
stencil.setWriteMask(0);
stencil.setReference(0);
stencil.setCompareMask(0);
vk::PipelineDepthStencilStateCreateInfo depthStencil = {};
depthStencil.setDepthTestEnable(false);
depthStencil.setDepthWriteEnable(false);
depthStencil.setDepthCompareOp(vk::CompareOp::eLess);
depthStencil.setDepthBoundsTestEnable(false);
depthStencil.setMinDepthBounds(0.0f);
depthStencil.setMaxDepthBounds(1.0f);
depthStencil.setStencilTestEnable(true);
depthStencil.setFront(stencil);
depthStencil.setBack(stencil);
std::array<vk::PipelineColorBlendAttachmentState, 4> colorBlendAttachments = {};
for (size_t i = 0; i < colorBlendAttachments.size(); ++i)
{
colorBlendAttachments[i].setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA);
colorBlendAttachments[i].setBlendEnable(true);
colorBlendAttachments[i].setSrcColorBlendFactor(vk::BlendFactor::eSrcAlpha);
colorBlendAttachments[i].setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha);
colorBlendAttachments[i].setColorBlendOp(vk::BlendOp::eAdd);
colorBlendAttachments[i].setSrcAlphaBlendFactor(vk::BlendFactor::eOne);
colorBlendAttachments[i].setDstAlphaBlendFactor(vk::BlendFactor::eZero);
colorBlendAttachments[i].setAlphaBlendOp(vk::BlendOp::eAdd);
}
vk::PipelineColorBlendStateCreateInfo colorBlending = {};
colorBlending.setLogicOpEnable(false);
colorBlending.setLogicOp(vk::LogicOp::eCopy);
colorBlending.setAttachmentCount(static_cast<uint32_t>(colorBlendAttachments.size()));
colorBlending.setPAttachments(colorBlendAttachments.data());
colorBlending.setBlendConstants({ 0.0f, 0.0f, 0.0f, 0.0f });
vk::DynamicState dynamicStates[] =
{
vk::DynamicState::eViewport,
vk::DynamicState::eLineWidth
};
vk::PipelineDynamicStateCreateInfo dynamicState = {};
dynamicState.setDynamicStateCount(2);
dynamicState.setPDynamicStates(dynamicStates);
vk::PipelineLayoutCreateInfo pipelineLayoutInfo = {};
pipelineLayoutInfo.setSetLayoutCount(1);
pipelineLayoutInfo.setPSetLayouts(&m_descriptors.skyboxDescriptorSetLayout);
// Create pipeline layout
m_skyboxShader.graphicsPipelineLayout = m_graphics->getLogicalDevice().createPipelineLayout(pipelineLayoutInfo);
vk::GraphicsPipelineCreateInfo pipelineInfo = {};
pipelineInfo.setStageCount(2);
pipelineInfo.setPStages(m_skyboxShader.shaderStages.data());
pipelineInfo.setPVertexInputState(&vertexInputInfo);
pipelineInfo.setPInputAssemblyState(&inputAssembly);
pipelineInfo.setPViewportState(&viewportState);
pipelineInfo.setPRasterizationState(&rasterizer);
pipelineInfo.setPMultisampleState(&multisampling);
pipelineInfo.setPDepthStencilState(nullptr);
pipelineInfo.setPColorBlendState(&colorBlending);
pipelineInfo.setPDynamicState(nullptr);
pipelineInfo.setLayout(m_skyboxShader.graphicsPipelineLayout);
pipelineInfo.setRenderPass(m_renderPasses.offscreen);
pipelineInfo.setSubpass(0);
pipelineInfo.setBasePipelineHandle({ nullptr });
pipelineInfo.setBasePipelineIndex(-1);
pipelineInfo.setPDepthStencilState(&depthStencil);
// Create graphics pipeline
m_skyboxShader.graphicsPipeline = m_graphics->getLogicalDevice().createGraphicsPipeline({}, pipelineInfo);
}
}
void Renderer::initCommandBuffers()
{
if (m_mainCamera != Handle<VirtualCamera>::nullHandle())
{
m_commands.rendering.resize(m_swapchain.images.size());
for (size_t i = 0; i < m_commands.rendering.size(); ++i)
{
m_commands.rendering[i] = createCommandBuffer(vk::CommandBufferLevel::ePrimary);
auto commandBuffer = m_commands.rendering[i].buffer;
vk::CommandBufferBeginInfo beginInfo = {};
beginInfo.setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
beginInfo.setPInheritanceInfo(nullptr);
std::array<vk::ClearValue, 2> clearValues = {};
clearValues[0].setColor(std::array<float, 4>{ 0.0f, 0.0f, 0.0f, 0.0f });
clearValues[1].setColor(std::array<float, 4>{ 0.0f, 0.0f, 0.0f, 0.0f });
vk::RenderPassBeginInfo renderPassInfo = {};
renderPassInfo.setRenderPass(m_renderPasses.onscreen);
renderPassInfo.setFramebuffer(m_swapchain.buffers[i].frameBuffer);
renderPassInfo.renderArea.setOffset({ 0, 0 });
renderPassInfo.renderArea.setExtent(vk::Extent2D(m_graphics->getWidth(), m_graphics->getHeight()));
renderPassInfo.setClearValueCount(static_cast<uint32_t>(clearValues.size()));
renderPassInfo.setPClearValues(clearValues.data());
commandBuffer.begin(beginInfo);
commandBuffer.beginRenderPass(renderPassInfo, vk::SubpassContents::eInline);
// Set viewport
vk::Viewport viewport = {};
viewport.setHeight(static_cast<float>(m_graphics->getHeight()));
viewport.setWidth(static_cast<float>(m_graphics->getWidth()));
commandBuffer.setViewport(0, 1, &viewport);
// Set scissor
vk::Rect2D scissor = {};
scissor.setExtent({ m_graphics->getWidth(), m_graphics->getHeight() });
scissor.setOffset({ 0, 0 });
commandBuffer.setScissor(0, 1, &scissor);
// Bind descriptor sets
commandBuffer.bindDescriptorSets
(
vk::PipelineBindPoint::eGraphics,
m_screenShader.graphicsPipelineLayout,
0,
1,
&m_descriptors.screenDescriptorSet,
0,
nullptr
);
// Bind graphics pipeline
commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, m_screenShader.graphicsPipeline);
// Bind vertex and index buffer
vk::Buffer vertexBuffer = m_screenQuad->getVertexUniformBuffer().buffer;
vk::DeviceSize offset = 0;
commandBuffer.bindVertexBuffers(0, 1, &vertexBuffer, &offset);
commandBuffer.bindIndexBuffer(m_screenQuad->getIndexUniformBuffer().buffer, 0, vk::IndexType::eUint32);
// Draw
commandBuffer.drawIndexed(static_cast<uint32_t>(m_screenQuad->getIndexCount()), 1, 0, 0, 0);
commandBuffer.endRenderPass();
commandBuffer.end();
}
}
}
FrameBufferAttachment Renderer::createAttachment(vk::Format format, vk::ImageUsageFlags usage)
{
FrameBufferAttachment newAttachment = {};
vk::ImageAspectFlags aspectMask = (vk::ImageAspectFlagBits)0;
vk::ImageLayout imageLayout;
newAttachment.format = format;
// Get aspect mask and image layout
if (usage & vk::ImageUsageFlagBits::eColorAttachment)
{
aspectMask = vk::ImageAspectFlagBits::eColor;
imageLayout = vk::ImageLayout::eColorAttachmentOptimal;
}
if (usage & vk::ImageUsageFlagBits::eDepthStencilAttachment)
{
aspectMask = vk::ImageAspectFlagBits::eDepth | vk::ImageAspectFlagBits::eStencil;
imageLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
}
vk::ImageCreateInfo image = {};
image.setImageType(vk::ImageType::e2D);
image.setFormat(format);
image.extent.width = m_graphics->getWidth();
image.extent.height = m_graphics->getHeight();
image.extent.depth = 1;
image.setMipLevels(1);
image.setArrayLayers(1);
image.setSamples(vk::SampleCountFlagBits::e1);
image.setTiling(vk::ImageTiling::eOptimal);
image.setUsage(usage | vk::ImageUsageFlagBits::eSampled);
// Create image
newAttachment.image = m_graphics->getLogicalDevice().createImage(image);
vk::MemoryAllocateInfo memAlloc = {};
vk::MemoryRequirements memReqs = m_graphics->getLogicalDevice().getImageMemoryRequirements(newAttachment.image);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = m_graphics->findMemoryType(memReqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal);
// Allocate and bind image memory
newAttachment.memory = m_graphics->getLogicalDevice().allocateMemory(memAlloc);
m_graphics->getLogicalDevice().bindImageMemory(newAttachment.image, newAttachment.memory, 0);
newAttachment.view = m_graphics->createImageView(newAttachment.image, format, aspectMask);
return newAttachment;
}
void Renderer::submitLightingData()
{
// Set camera position
if(m_mainCamera != Handle<VirtualCamera>::nullHandle())
m_lightingData.viewPosition = glm::vec4(m_mainCamera->viewPosition, 1);
// Set light counts
m_lightingData.directionalLightCount = static_cast<uint32_t>(m_directionalLights.size());
m_lightingData.pointLightCount = static_cast<uint32_t>(m_pointLights.size());
m_lightingData.spotLightCount = static_cast<uint32_t>(m_spotLights.size());
// Set point lights
for (size_t i = 0; i < m_lightingData.pointLightCount; ++i)
{
m_lightingData.pointLights[i] = m_pointLights.front();
m_pointLights.pop();
}
// Set directional lights
for (size_t i = 0; i < m_lightingData.directionalLightCount; ++i)
{
m_lightingData.directionalLights[i] = m_directionalLights.front();
m_directionalLights.pop();
}
// Set spot lights
for (size_t i = 0; i < m_lightingData.spotLightCount; ++i)
{
m_lightingData.spotLights[i] = m_spotLights.front();
m_spotLights.pop();
}
// Set lighting data
{
void* cpyData;
m_graphics->getLogicalDevice().mapMemory
(
m_lightingUniformBuffer.memory,
0,
static_cast<vk::DeviceSize>(sizeof(LightingData)),
(vk::MemoryMapFlagBits)0,
&cpyData
);
memcpy(cpyData, &m_lightingData, sizeof(LightingData));
m_graphics->getLogicalDevice().unmapMemory(m_lightingUniformBuffer.memory);
}
}
void Renderer::drawMeshToFramebuffer
(
const MeshData& mesh,
const vk::CommandBufferInheritanceInfo& inheritanceInfo,
size_t threadIndex,
Handle<VirtualCamera> camera
)
{
vk::CommandBufferBeginInfo beginInfo = {};
beginInfo.setFlags(vk::CommandBufferUsageFlagBits::eRenderPassContinue | vk::CommandBufferUsageFlagBits::eSimultaneousUse);
beginInfo.setPInheritanceInfo(&inheritanceInfo);
// Submit vertex data
{
VertexShaderData vData = {};
vData.model = mesh.model;
vData.MVP = camera->projection * camera->view * mesh.model;
void* cpyData;
m_graphics->getLogicalDevice().mapMemory
(
mesh.vertexUniformBuffer.memory,
0,
sizeof(VertexShaderData),
(vk::MemoryMapFlagBits)0,
&cpyData
);
memcpy(cpyData, &vData, sizeof(VertexShaderData));
m_graphics->getLogicalDevice().unmapMemory(mesh.vertexUniformBuffer.memory);
}
// Submit fragment data
{
FragmentShaderData fData = {};
fData.viewPosition = glm::vec4(camera->viewPosition, 1);
void* cpyData;
m_graphics->getLogicalDevice().mapMemory
(
mesh.fragmentUniformBuffer.memory,
0,
sizeof(FragmentShaderData),
(vk::MemoryMapFlagBits)0,
&cpyData
);
memcpy(cpyData, &fData, sizeof(FragmentShaderData));
m_graphics->getLogicalDevice().unmapMemory(mesh.fragmentUniformBuffer.memory);
}
mesh.commandBuffer.buffer.begin(beginInfo);
// Set viewport
vk::Viewport viewport = {};
viewport.setHeight((float)m_graphics->getHeight());
viewport.setWidth((float)m_graphics->getWidth());
viewport.setMinDepth(0);
viewport.setMaxDepth(1);
mesh.commandBuffer.buffer.setViewport(0, 1, &viewport);
// Set scissor
vk::Rect2D scissor = {};
scissor.setExtent({ m_graphics->getWidth(), m_graphics->getHeight() });
scissor.setOffset({ 0, 0 });
mesh.commandBuffer.buffer.setScissor(0, 1, &scissor);
// Bind graphics pipeline
mesh.commandBuffer.buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, mesh.material->getShader()->getGraphicsPipeline());
// Bind descriptor sets
mesh.commandBuffer.buffer.bindDescriptorSets
(
vk::PipelineBindPoint::eGraphics,
mesh.material->getShader()->getGraphicsPipelineLayout(),
0,
static_cast<uint32_t>(mesh.descriptorSets.size()),
mesh.descriptorSets.data(),
0,
nullptr
);
// Bind vertex and index buffer
vk::Buffer vertexBuffer = mesh.mesh->getVertexUniformBuffer().buffer;
vk::DeviceSize offset = 0;
mesh.commandBuffer.buffer.bindVertexBuffers(0, 1, &vertexBuffer, &offset);
mesh.commandBuffer.buffer.bindIndexBuffer(mesh.mesh->getIndexUniformBuffer().buffer, 0, vk::IndexType::eUint32);
// Draw
mesh.commandBuffer.buffer.drawIndexed(static_cast<uint32_t>(mesh.mesh->getIndexCount()), 1, 0, 0, 0);
mesh.commandBuffer.buffer.end();
}
void Renderer::drawToCamera(Handle<VirtualCamera> camera)
{
vk::CommandBufferBeginInfo cmdBufInfo = {};
cmdBufInfo.setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
cmdBufInfo.setPInheritanceInfo(nullptr);
// Begin renderpass
camera->commandBuffer.buffer.begin(cmdBufInfo);
// Clear values for all attachments written in the fragment shader
std::array<vk::ClearValue, 5> clearValues;
clearValues[0].setColor(std::array<float, 4>{ 0.0f, 0.0f, 0.0f, 0.0f });
clearValues[1].setColor(std::array<float, 4>{ 0.0f, 0.0f, 0.0f, 0.0f });
clearValues[2].setColor(std::array<float, 4>{ camera->clearColor.x, camera->clearColor.y, camera->clearColor.z, 0.0f });
clearValues[3].setColor(std::array<float, 4>{ 0.0f, 0.0f, 0.0f, 0.0f });
clearValues[4].setDepthStencil({ 1.0f, 0 });
vk::RenderPassBeginInfo renderPassBeginInfo = {};
renderPassBeginInfo.setRenderPass(m_renderPasses.offscreen);
renderPassBeginInfo.setFramebuffer(camera->frameBuffer);
renderPassBeginInfo.renderArea.setExtent(vk::Extent2D(m_graphics->getWidth(), m_graphics->getHeight()));
renderPassBeginInfo.renderArea.offset = vk::Offset2D(0, 0);
renderPassBeginInfo.setClearValueCount(static_cast<uint32_t>(clearValues.size()));
renderPassBeginInfo.setPClearValues(clearValues.data());
// Inheritance info for the meshes command buffers
vk::CommandBufferInheritanceInfo inheritanceInfo = {};
inheritanceInfo.setRenderPass(m_renderPasses.offscreen);
inheritanceInfo.setFramebuffer(camera->frameBuffer);
camera->commandBuffer.buffer.beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eSecondaryCommandBuffers);
std::vector<vk::CommandBuffer> commandBuffers(m_meshes.size() + (camera->skybox != Handle<Cubemap>::nullHandle() ? 1 : 0));
m_threadPool->wait();
if (camera->skybox != Handle<Cubemap>::nullHandle())
{
// Submit vertex data
{
glm::mat4 model = {};
model = glm::translate(model, camera->viewPosition);
VertexShaderData vData = {};
vData.model = model;
vData.MVP = camera->projection * camera->view * model;
void* cpyData;
m_graphics->getLogicalDevice().mapMemory
(
m_skyboxUniformBuffer.memory,
0,
sizeof(VertexShaderData),
(vk::MemoryMapFlagBits)0,
&cpyData
);
memcpy(cpyData, &vData, sizeof(VertexShaderData));
m_graphics->getLogicalDevice().unmapMemory(m_skyboxUniformBuffer.memory);
}
// Bind descriptor sets
{
std::array<vk::WriteDescriptorSet, 2> writeSets = {};
// Vertex data
vk::DescriptorBufferInfo gustVertexBufferInfo = {};
gustVertexBufferInfo.setBuffer(m_skyboxUniformBuffer.buffer);
gustVertexBufferInfo.setOffset(0);
gustVertexBufferInfo.setRange(static_cast<vk::DeviceSize>(sizeof(VertexShaderData)));
writeSets[0].setDstSet(m_descriptors.skyboxDescriptorSet);
writeSets[0].setDstBinding(0);
writeSets[0].setDstArrayElement(0);
writeSets[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
writeSets[0].setDescriptorCount(1);
writeSets[0].setPBufferInfo(&gustVertexBufferInfo);
writeSets[0].setPImageInfo(nullptr);
writeSets[0].setPTexelBufferView(nullptr);
// GUST fragment buffer
vk::DescriptorImageInfo samplerInfo = {};
samplerInfo.setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
samplerInfo.setImageView(camera->skybox->getImageView());
samplerInfo.setSampler(camera->skybox->getSampler());
writeSets[1].setDstSet(m_descriptors.skyboxDescriptorSet);
writeSets[1].setDstBinding(1);
writeSets[1].setDstArrayElement(0);
writeSets[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
writeSets[1].setDescriptorCount(1);
writeSets[1].setPImageInfo(&samplerInfo);
// Update descriptor sets
m_graphics->getLogicalDevice().updateDescriptorSets(static_cast<uint32_t>(writeSets.size()), writeSets.data(), 0, nullptr);
}
vk::CommandBufferBeginInfo beginInfo = {};
beginInfo.setFlags(vk::CommandBufferUsageFlagBits::eRenderPassContinue | vk::CommandBufferUsageFlagBits::eSimultaneousUse);
beginInfo.setPInheritanceInfo(&inheritanceInfo);
m_commands.skybox.buffer.begin(beginInfo);
// Set viewport
vk::Viewport viewport = {};
viewport.setHeight((float)m_graphics->getHeight());
viewport.setWidth((float)m_graphics->getWidth());
viewport.setMinDepth(0);
viewport.setMaxDepth(1);
m_commands.skybox.buffer.setViewport(0, 1, &viewport);
// Set scissor
vk::Rect2D scissor = {};
scissor.setExtent({ m_graphics->getWidth(), m_graphics->getHeight() });
scissor.setOffset({ 0, 0 });
m_commands.skybox.buffer.setScissor(0, 1, &scissor);
// Bind graphics pipeline
m_commands.skybox.buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, m_skyboxShader.graphicsPipeline);
// Bind descriptor sets
m_commands.skybox.buffer.bindDescriptorSets
(
vk::PipelineBindPoint::eGraphics,
m_skyboxShader.graphicsPipelineLayout,
0,
1,
&m_descriptors.skyboxDescriptorSet,
0,
nullptr
);
// Bind vertex and index buffer
vk::Buffer vertexBuffer = m_skybox->getVertexUniformBuffer().buffer;
vk::DeviceSize offset = 0;
m_commands.skybox.buffer.bindVertexBuffers(0, 1, &vertexBuffer, &offset);
m_commands.skybox.buffer.bindIndexBuffer(m_skybox->getIndexUniformBuffer().buffer, 0, vk::IndexType::eUint32);
// Draw
m_commands.skybox.buffer.drawIndexed(static_cast<uint32_t>(m_skybox->getIndexCount()), 1, 0, 0, 0);
m_commands.skybox.buffer.end();
commandBuffers[0] = m_commands.skybox.buffer;
}
// Loop over meshes
for (size_t i = 0; i < m_meshes.size(); ++i)
{
commandBuffers[i + (camera->skybox != Handle<Cubemap>::nullHandle() ? 1 : 0)] = m_meshes[i].commandBuffer.buffer;
m_threadPool->workers[m_meshes[i].commandBuffer.index]->addJob([this, i, inheritanceInfo, camera]()
{
this->drawMeshToFramebuffer(m_meshes[i], inheritanceInfo, m_meshes[i].commandBuffer.index, camera);
});
}
m_threadPool->wait();
// Execute command buffers and perform lighting
if (commandBuffers.size() > 0)
camera->commandBuffer.buffer.executeCommands(commandBuffers);
camera->commandBuffer.buffer.endRenderPass();
camera->commandBuffer.buffer.end();
vk::SubmitInfo submitInfo = {};
submitInfo.setCommandBufferCount(1);
submitInfo.setPCommandBuffers(&camera->commandBuffer.buffer);
submitInfo.setSignalSemaphoreCount(1);
submitInfo.setPSignalSemaphores(&m_semaphores.offscreen);
// Submit draw command
m_graphics->getGraphicsQueue().submit(1, &submitInfo, { nullptr });
// Do lighting
performCameraLighting(camera);
}
void Renderer::performCameraLighting(Handle<VirtualCamera> camera)
{
std::array<vk::WriteDescriptorSet, 4> sets = {};
vk::DescriptorImageInfo position = {};
position.setImageLayout(vk::ImageLayout::eColorAttachmentOptimal);
position.setImageView(m_mainCamera->position->getImageView());
position.setSampler(m_mainCamera->position->getSampler());
vk::DescriptorImageInfo normal = {};
normal.setImageLayout(vk::ImageLayout::eColorAttachmentOptimal);
normal.setImageView(m_mainCamera->normal->getImageView());
normal.setSampler(m_mainCamera->normal->getSampler());
vk::DescriptorImageInfo color = {};
color.setImageLayout(vk::ImageLayout::eColorAttachmentOptimal);
color.setImageView(m_mainCamera->color->getImageView());
color.setSampler(m_mainCamera->color->getSampler());
vk::DescriptorImageInfo misc = {};
misc.setImageLayout(vk::ImageLayout::eColorAttachmentOptimal);
misc.setImageView(m_mainCamera->misc->getImageView());
misc.setSampler(m_mainCamera->misc->getSampler());
sets[0].setDstSet(m_descriptors.lightingDescriptorSet);
sets[0].setDstBinding(1);
sets[0].setDstArrayElement(0);
sets[0].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
sets[0].setDescriptorCount(1);
sets[0].setPImageInfo(&position);
sets[1].setDstSet(m_descriptors.lightingDescriptorSet);
sets[1].setDstBinding(2);
sets[1].setDstArrayElement(0);
sets[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
sets[1].setDescriptorCount(1);
sets[1].setPImageInfo(&normal);
sets[2].setDstSet(m_descriptors.lightingDescriptorSet);
sets[2].setDstBinding(3);
sets[2].setDstArrayElement(0);
sets[2].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
sets[2].setDescriptorCount(1);
sets[2].setPImageInfo(&color);
sets[3].setDstSet(m_descriptors.lightingDescriptorSet);
sets[3].setDstBinding(4);
sets[3].setDstArrayElement(0);
sets[3].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
sets[3].setDescriptorCount(1);
sets[3].setPImageInfo(&misc);
// Update lighting descriptor set
m_graphics->getLogicalDevice().updateDescriptorSets(static_cast<uint32_t>(sets.size()), sets.data(), 0, nullptr);
vk::CommandBufferBeginInfo cmdBufInfo = {};
cmdBufInfo.setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
cmdBufInfo.setPInheritanceInfo(nullptr);
// Begin renderpass
camera->lightingCommandBuffer.buffer.begin(cmdBufInfo);
vk::RenderPassBeginInfo renderPassBeginInfo = {};
renderPassBeginInfo.setRenderPass(m_renderPasses.lighting);
renderPassBeginInfo.setFramebuffer(camera->frameBuffer);
renderPassBeginInfo.renderArea.setExtent(vk::Extent2D(m_graphics->getWidth(), m_graphics->getHeight()));
renderPassBeginInfo.renderArea.offset = vk::Offset2D(0, 0);
renderPassBeginInfo.setClearValueCount(0);
renderPassBeginInfo.setPClearValues(nullptr);
camera->lightingCommandBuffer.buffer.beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eInline);
// Bind descriptor sets
camera->lightingCommandBuffer.buffer.bindDescriptorSets
(
vk::PipelineBindPoint::eGraphics,
m_lightingShader.graphicsPipelineLayout,
0,
1,
&m_descriptors.lightingDescriptorSet,
0,
nullptr
);
// Bind graphics pipeline
camera->lightingCommandBuffer.buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, m_lightingShader.graphicsPipeline);
// Bind vertex and index buffer
vk::Buffer vertexBuffer = m_screenQuad->getVertexUniformBuffer().buffer;
vk::DeviceSize offset = 0;
camera->lightingCommandBuffer.buffer.bindVertexBuffers(0, 1, &vertexBuffer, &offset);
camera->lightingCommandBuffer.buffer.bindIndexBuffer(m_screenQuad->getIndexUniformBuffer().buffer, 0, vk::IndexType::eUint32);
// Draw
camera->lightingCommandBuffer.buffer.drawIndexed(static_cast<uint32_t>(m_screenQuad->getIndexCount()), 1, 0, 0, 0);
camera->lightingCommandBuffer.buffer.endRenderPass();
camera->lightingCommandBuffer.buffer.end();
vk::PipelineStageFlags flags = vk::PipelineStageFlagBits::eAllGraphics;
vk::SubmitInfo submitInfo = {};
submitInfo.setCommandBufferCount(1);
submitInfo.setPCommandBuffers(&camera->lightingCommandBuffer.buffer);
submitInfo.setWaitSemaphoreCount(1);
submitInfo.setPWaitSemaphores(&m_semaphores.offscreen);
submitInfo.setSignalSemaphoreCount(1);
submitInfo.setPSignalSemaphores(&m_semaphores.offscreen);
submitInfo.setPWaitDstStageMask(&flags);
// Submit draw command
m_graphics->getGraphicsQueue().submit(1, &submitInfo, { nullptr });
}
CommandBuffer Renderer::createCommandBuffer(vk::CommandBufferLevel level)
{
// Allocate command buffer
auto commandBuffer = m_graphics->getLogicalDevice().allocateCommandBuffers
(
vk::CommandBufferAllocateInfo
(
m_commands.pools[m_commands.poolIndex],
level,
1
)
);
size_t poolIndex = m_commands.poolIndex;
m_commands.poolIndex = (m_commands.poolIndex + 1) % m_commands.pools.size();
return { commandBuffer[0], poolIndex };
}
Handle<VirtualCamera> Renderer::setMainCamera(const Handle<VirtualCamera>& camera)
{
m_mainCamera = camera;
vk::WriteDescriptorSet set = {};
vk::DescriptorImageInfo color = {};
color.setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
color.setImageView(m_mainCamera->color->getImageView());
color.setSampler(m_mainCamera->color->getSampler());
set.setDstSet(m_descriptors.screenDescriptorSet);
set.setDstBinding(0);
set.setDstArrayElement(0);
set.setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
set.setDescriptorCount(1);
set.setPImageInfo(&color);
// Update lighting descriptor set
m_graphics->getLogicalDevice().updateDescriptorSets(1, &set, 0, nullptr);
// Destroy old rendering command buffers and create new ones
for (auto commandBuffer : m_commands.rendering)
destroyCommandBuffer(commandBuffer);
initCommandBuffers();
return m_mainCamera;
}
}
| 37.700859
| 178
| 0.758583
|
ReeCocho
|
9e9be1fdb4251a53e47d673e826f4a8c369831ce
| 8,093
|
hpp
|
C++
|
solver/include/decpomdp/discrete/DiscreteSpaces.hpp
|
laurimi/multiagent-prediction-reward
|
b89fa52f78bb49447fc0049a7314a87b2b3e903e
|
[
"MIT"
] | 9
|
2020-10-24T06:14:08.000Z
|
2021-07-13T13:08:30.000Z
|
solver/include/decpomdp/discrete/DiscreteSpaces.hpp
|
laurimi/multiagent-prediction-reward
|
b89fa52f78bb49447fc0049a7314a87b2b3e903e
|
[
"MIT"
] | null | null | null |
solver/include/decpomdp/discrete/DiscreteSpaces.hpp
|
laurimi/multiagent-prediction-reward
|
b89fa52f78bb49447fc0049a7314a87b2b3e903e
|
[
"MIT"
] | null | null | null |
#ifndef DISCRETESPACES_HPP
#define DISCRETESPACES_HPP
#include <algorithm>
#include <iterator>
#include <map>
#include <vector>
#include "DiscreteElements.hpp"
#include "utilities/IndexSpace.hpp"
namespace npgi {
template <typename Index, typename Element>
class DiscreteSpace {
friend class const_iterator;
public:
using local_element_type = Element;
using index_type = Index;
using size_type = std::size_t;
using action_map_type = std::map<index_type, local_element_type>;
using action_map_type_const_iterator =
typename action_map_type::const_iterator;
class const_iterator {
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = Element;
using difference_type = long long;
using pointer = Element*;
using reference = Element&;
using const_reference = const Element&;
const_iterator(const const_iterator& other)
: m_(other.m_), it_(other.it_) {}
const_iterator& operator++() {
if (it_ != m_.end())
++it_;
else
it_ = m_.end();
return *this;
}
const_iterator operator++(int) {
const_iterator ret(*this);
++(*this);
return ret;
}
const_iterator& operator--() {
if (it_ != m_.begin())
--it_;
else
it_ = m_.begin();
return *this;
}
const_iterator operator--(int) {
const_iterator ret(*this);
--(*this);
return ret;
}
static const_iterator make_begin(const action_map_type& m) {
return const_iterator(m, m.begin());
}
static const_iterator make_end(const action_map_type& m) {
return const_iterator(m, m.end());
}
const_reference operator*() const { return it_->second; }
bool operator==(const const_iterator& other) const {
return ((&m_ == &other.m_) && (it_ == other.it_));
}
bool operator!=(const const_iterator& other) const {
return !(*this == other);
}
private:
const_iterator(const action_map_type& m, action_map_type_const_iterator it)
: m_(m), it_(it) {}
const action_map_type& m_;
action_map_type_const_iterator it_;
};
const_iterator begin() const { return const_iterator::make_begin(this->m_); }
const_iterator end() const { return const_iterator::make_end(this->m_); }
void insert(const index_type& index, const local_element_type& x) {
m_.emplace(index, x);
}
size_type size() const { return m_.size(); }
const local_element_type& at(const index_type& i) const { return m_.at(i); }
private:
action_map_type m_;
};
template <typename K, typename V>
std::vector<std::size_t> num_local_elements(const std::map<K, V>& m) {
std::vector<std::size_t> num_local_elements(m.size());
std::transform(m.begin(), m.end(), num_local_elements.begin(),
[](const typename std::map<K, V>::value_type& x) {
return x.second.size();
});
return num_local_elements;
}
template <typename Index, typename LocalElement, typename JointElement>
class JointDiscreteSpace {
friend class const_iterator;
public:
using index_type = Index;
using local_element_type = LocalElement;
using joint_element_type = JointElement;
using agent_type = Agent<index_type>;
using local_space_type = DiscreteSpace<index_type, local_element_type>;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using value_type = joint_element_type;
using pointer = joint_element_type*;
using reference = joint_element_type&;
class const_iterator {
public:
using joint_discrete_set_type =
JointDiscreteSpace<Index, LocalElement, JointElement>;
using joint_element_type =
typename joint_discrete_set_type::joint_element_type;
using iterator_category = std::bidirectional_iterator_tag;
using value_type = joint_element_type;
using difference_type = long long;
using pointer = joint_element_type*;
using const_reference = const joint_element_type&;
const_iterator(const const_iterator& other) : s_(other.s_), e_(other.e_) {}
const_iterator& operator++() {
if (e_.index() < s_.size())
e_ = joint_element_type(Index(e_.index() + 1));
else
set_to_end_();
return *this;
}
const_iterator operator++(int) {
const_iterator ret(*this);
++(*this);
return ret;
}
const_iterator& operator--() {
if (e_.index() > 0)
e_ = joint_element_type(Index(e_.index() - 1));
else
set_to_begin_();
return *this;
}
const_iterator operator--(int) {
const_iterator ret(*this);
--(*this);
return ret;
}
static const_iterator make_begin(const joint_discrete_set_type& s) {
return const_iterator(s, joint_element_type(Index(0)));
}
static const_iterator make_end(const joint_discrete_set_type& s) {
return const_iterator(s, joint_element_type(s.size()));
}
const_reference operator*() const { return e_; }
bool operator==(const const_iterator& other) const {
return ((&s_ == &other.s_) && (e_ == other.e_));
}
bool operator!=(const const_iterator& other) const {
return !(*this == other);
}
private:
const_iterator(const joint_discrete_set_type& s, joint_element_type e)
: s_(s), e_(e) {}
void set_to_end_() { e_ = joint_element_type(Index(s_.size())); }
void set_to_begin_() { e_ = joint_element_type(Index(0)); }
const joint_discrete_set_type& s_;
joint_element_type e_;
};
JointDiscreteSpace(const std::map<agent_type, local_space_type>& local_spaces)
: m_(local_spaces), is_(num_local_elements(local_spaces)) {}
const local_space_type& get_local_space(const agent_type& i) const {
return m_.at(i);
}
const_iterator begin() const { return const_iterator::make_begin(*this); }
const_iterator end() const { return const_iterator::make_end(*this); }
size_type size() const {
if (m_.empty()) return 0;
auto size_prod =
[](std::size_t x,
const typename std::map<agent_type, local_space_type>::value_type&
y) { return x * y.second.size(); };
return std::accumulate(std::next(m_.begin()), m_.cend(),
m_.begin()->second.size(), size_prod);
}
joint_element_type get_joint_element(
const std::map<agent_type, local_element_type>& locals) const {
if (locals.size() != m_.size())
throw std::runtime_error(
"number of local actions in input does not match number of local "
"spaces");
index_type joint_index(0);
for (const auto& x : locals)
joint_index = is_.increment_joint_index(joint_index, x.first.index(),
x.second.index());
return joint_element_type({joint_index, ""});
}
const local_element_type& get_local_element(const joint_element_type& joint,
const agent_type& i) const {
auto local_idx = is_.local_index(joint.index(), i.index());
return m_.at(i).at(local_idx);
}
size_type num_agents() const { return m_.size(); }
private:
std::map<agent_type, local_space_type> m_;
IndexSpace<index_type> is_;
};
template <typename Index = std::size_t>
using DiscreteLocalActionSpace =
DiscreteSpace<Index, DiscreteLocalAction<Index>>;
template <typename Index = std::size_t,
typename LocalElement = DiscreteLocalAction<Index>,
typename JointElement = DiscreteJointAction<Index>>
using DiscreteJointActionSpace =
JointDiscreteSpace<Index, LocalElement, JointElement>;
template <typename Index = std::size_t>
using DiscreteLocalObservationSpace =
DiscreteSpace<Index, DiscreteLocalObservation<Index>>;
template <typename Index = std::size_t,
typename LocalElement = DiscreteLocalObservation<Index>,
typename JointElement = DiscreteJointObservation<Index>>
using DiscreteJointObservationSpace =
JointDiscreteSpace<Index, LocalElement, JointElement>;
} // namespace npgi
#endif // DISCRETESPACES_HPP
| 29.753676
| 80
| 0.666625
|
laurimi
|
9e9cacd9464b864e979f045e027525b7eb822418
| 1,406
|
hpp
|
C++
|
doc/quickbook/oglplus/quickref/enums/debug_output_type_class.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | null | null | null |
doc/quickbook/oglplus/quickref/enums/debug_output_type_class.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | null | null | null |
doc/quickbook/oglplus/quickref/enums/debug_output_type_class.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | null | null | null |
// File doc/quickbook/oglplus/quickref/enums/debug_output_type_class.hpp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/debug_output_type.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2015 Matus Chochlik.
// 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
//
//[oglplus_enums_debug_output_type_class
#if !__OGLPLUS_NO_ENUM_VALUE_CLASSES
namespace enums {
template <typename Base, template<__DebugOutputType> class Transform>
class __EnumToClass<Base, __DebugOutputType, Transform> /*<
Specialization of __EnumToClass for the __DebugOutputType enumeration.
>*/
: public Base
{
public:
EnumToClass(void);
EnumToClass(Base&& base);
Transform<DebugOutputType::Error>
Error;
Transform<DebugOutputType::DeprecatedBehavior>
DeprecatedBehavior;
Transform<DebugOutputType::UndefinedBehavior>
UndefinedBehavior;
Transform<DebugOutputType::Portability>
Portability;
Transform<DebugOutputType::Performance>
Performance;
Transform<DebugOutputType::Marker>
Marker;
Transform<DebugOutputType::PushGroup>
PushGroup;
Transform<DebugOutputType::PopGroup>
PopGroup;
Transform<DebugOutputType::Other>
Other;
Transform<DebugOutputType::DontCare>
DontCare;
};
} // namespace enums
#endif
//]
| 27.038462
| 73
| 0.785917
|
Extrunder
|
9ea4cd0486a2d626afa0db6014ba24bc441d8581
| 7,735
|
hpp
|
C++
|
moe/optimal_learning/cpp/gpp_optimizer_parameters.hpp
|
mikepsinn/MOE
|
fdc2e1318d37c89c54a7b7902c12f8f164f517e8
|
[
"Apache-2.0"
] | null | null | null |
moe/optimal_learning/cpp/gpp_optimizer_parameters.hpp
|
mikepsinn/MOE
|
fdc2e1318d37c89c54a7b7902c12f8f164f517e8
|
[
"Apache-2.0"
] | null | null | null |
moe/optimal_learning/cpp/gpp_optimizer_parameters.hpp
|
mikepsinn/MOE
|
fdc2e1318d37c89c54a7b7902c12f8f164f517e8
|
[
"Apache-2.0"
] | null | null | null |
/*!
\file gpp_optimizer_parameters.hpp
\rst
This file specifies OptimizerParameters structs (e.g., GradientDescent, Newton) for holding values that control the behavior
of the optimizers in gpp_optimization.hpp. For example, max step sizes, number of iterations, step size control, etc. are all
specified through these structs.
These structs also specify multistart behavior pertaining to the multistart optimization code in gpp_math and
gpp_model_selection.
\endrst*/
#ifndef MOE_OPTIMAL_LEARNING_CPP_GPP_OPTIMIZER_PARAMETERS_HPP_
#define MOE_OPTIMAL_LEARNING_CPP_GPP_OPTIMIZER_PARAMETERS_HPP_
#include "gpp_common.hpp"
namespace optimal_learning {
/*!\rst
Enum for the various optimizer types. Convenient for specifying which optimizer to use
in testing and also used by the Python interface to specify the optimizer (e.g., for EI
and hyperparameter optimization).
\endrst*/
enum class OptimizerTypes {
//! NullOptimizer<>, used for evaluating objective at points
kNull = 0,
//! GradientDescentOptimizer<>
kGradientDescent = 1,
//! NewtonOptimizer<>
kNewton = 2,
};
// TODO(GH-167): Remove num_multistarts from ALL OptimizerParameter structs. num_multistarts doesn't
// configure the individual optimizer, it just controls how many times we call that optimizer.
// Then num_multistarts can live in a parameter struct specifically for multistart optimization.
/*!\rst
Empty container for optimizers that do not require any parameters (e.g., the null optimizer).
\endrst*/
struct NullParameters {
};
/*!\rst
Container to hold parameters that specify the behavior of Gradient Descent.
.. Note:: these comments are copied in build_gradient_descent_parameters() in cpp_wrappers/optimizer_parameters.py.
That function wraps this struct's ctor.
**Iterations**
The total number of gradient descent steps is at most ``num_multistarts * max_num_steps * max_num_restarts``
Generally, allowing more iterations leads to a better solution but costs more time.
**Learning Rate**
GD may be implemented using a learning rate: ``pre_mult * (i+1)^{-\gamma}``, where i is the current iteration
Larger gamma causes the GD step size to (artificially) scale down faster.
Smaller pre_mult (artificially) shrinks the GD step size.
Generally, taking a very large number of small steps leads to the most robustness; but it is very slow.
**Tolerances**
Larger relative changes are potentially less robust but lead to faster convergence.
Large tolerances run faster but may lead to high errors or false convergence (e.g., if the tolerance is 1.0e-3 and the learning
rate control forces steps to fall below 1.0e-3 quickly, then GD will quit "successfully" without genuinely converging.)
\endrst*/
struct GradientDescentParameters {
// Users must set parameters explicitly.
GradientDescentParameters() = delete;
/*!\rst
Construct a GradientDescentParameters object. Default, copy, and assignment constructor are disallowed.
INPUTS:
See member declarations below for a description of each parameter.
\endrst*/
GradientDescentParameters(int num_multistarts_in, int max_num_steps_in, int max_num_restarts_in, double gamma_in, double pre_mult_in, double max_relative_change_in, double tolerance_in)
: num_multistarts(num_multistarts_in),
max_num_steps(max_num_steps_in),
max_num_restarts(max_num_restarts_in),
gamma(gamma_in),
pre_mult(pre_mult_in),
max_relative_change(max_relative_change_in),
tolerance(tolerance_in) {
}
GradientDescentParameters(GradientDescentParameters&& OL_UNUSED(other)) = default;
// iteration control
//! number of initial guesses to try in multistarted gradient descent (suggest: a few hundred)
int num_multistarts;
//! maximum number of gradient descent iterations per restart (suggest: 200-1000)
int max_num_steps;
//! maximum number of gradient descent restarts, the we are allowed to call gradient descent. Should be >= 2 as a minimum (suggest: 4-20)
int max_num_restarts;
// learning rate control
//! exponent controlling rate of step size decrease (see struct docs or GradientDescentOptimizer) (suggest: 0.5-0.9)
double gamma;
//! scaling factor for step size (see struct docs or GradientDescentOptimizer) (suggest: 0.1-1.0)
double pre_mult;
// tolerance control
//! max change allowed per GD iteration (as a relative fraction of current distance to wall)
//! (suggest: 0.5-1.0 for less sensitive problems like EI; 0.02 for more sensitive problems like hyperparameter opt)
double max_relative_change;
//! when the magnitude of the gradient falls below this value OR we will not move farther than tolerance
//! (e.g., at a boundary), stop. (suggest: 1.0e-7)
double tolerance;
};
/*!\rst
Container to hold parameters that specify the behavior of Newton.
.. Note:: these comments are copied in build_newton_parameters() in cpp_wrappers/optimizer_parameters.py.
That function wraps this struct's ctor.
**Diagonal dominance control: ``gamma`` and ``time_factor``**
On i-th newton iteration, we add ``1/(time_factor*gamma^{i+1}) * I`` to the Hessian to improve robustness
Choosing a small gamma (e.g., ``1.0 < gamma <= 1.01``) and time_factor (e.g., ``0 < time_factor <= 1.0e-3``)
leads to more consistent/stable convergence at the cost of slower performance (and in fact
for gamma or time_factor too small, gradient descent is preferred). Conversely, choosing more
aggressive values may lead to very fast convergence at the cost of more cases failing to
converge.
``gamma = 1.01``, ``time_factor = 1.0e-3`` should lead to good robustness at reasonable speed. This should be a fairly safe default.
``gamma = 1.05, time_factor = 1.0e-1`` will be several times faster but not as robust.
for "easy" problems, these can be much more aggressive, e.g., ``gamma = 2.0``, ``time_factor = 1.0e1`` or more.
\endrst*/
struct NewtonParameters {
// Users must set parameters explicitly.
NewtonParameters() = delete;
/*!\rst
Construct a NewtonParameters object. Default, copy, and assignment constructor are disallowed.
INPUTS:
See member declarations below for a description of each parameter.
\endrst*/
NewtonParameters(int num_multistarts_in, int max_num_steps_in, double gamma_in, double time_factor_in, double max_relative_change_in, double tolerance_in)
: num_multistarts(num_multistarts_in),
max_num_steps(max_num_steps_in),
gamma(gamma_in),
time_factor(time_factor_in),
max_relative_change(max_relative_change_in),
tolerance(tolerance_in) {
}
NewtonParameters(NewtonParameters&& OL_UNUSED(other)) = default;
// iteration control
//! number of initial guesses for multistarting (suggest: a few hundred)
int num_multistarts;
//! maximum number of newton iterations (per initial guess) (suggest: 100)
int max_num_steps;
//! maximum number of newton restarts (fixed; not used by newton)
const int max_num_restarts = 1;
// diagonal domaince control
//! exponent controlling rate of time_factor growth (see class docs and NewtonOptimizer) (suggest: 1.01-1.1)
double gamma;
//! initial amount of additive diagonal dominance (see class docs and NewtonOptimizer) (suggest: 1.0e-3-1.0e-1)
double time_factor;
// tolerance control
//! max change allowed per update (as a relative fraction of current distance to wall) (Newton may ignore this) (suggest: 1.0)
double max_relative_change;
//! when the magnitude of the gradient falls below this value, stop (suggest: 1.0e-10)
double tolerance;
};
} // end namespace optimal_learning
#endif // MOE_OPTIMAL_LEARNING_CPP_GPP_OPTIMIZER_PARAMETERS_HPP_
| 43.948864
| 187
| 0.753458
|
mikepsinn
|
9eab80dc32e305daacccee883c69fccb3f7a130d
| 1,124
|
cpp
|
C++
|
BookCode/chapters/07lazzariniBOOKexamples/dft_main.cpp
|
mike-normal13/Audio_programming_book_code
|
3d318787d379f232a4edc113b6f7190201084674
|
[
"MIT"
] | 9
|
2018-10-03T19:57:47.000Z
|
2022-01-08T14:37:24.000Z
|
BookCode/chapters/07lazzariniBOOKexamples/dft_main.cpp
|
mike-normal13/Audio_programming_book_code
|
3d318787d379f232a4edc113b6f7190201084674
|
[
"MIT"
] | null | null | null |
BookCode/chapters/07lazzariniBOOKexamples/dft_main.cpp
|
mike-normal13/Audio_programming_book_code
|
3d318787d379f232a4edc113b6f7190201084674
|
[
"MIT"
] | 8
|
2017-11-20T07:52:01.000Z
|
2022-03-29T02:59:10.000Z
|
/////////////////////////////////////////////
// Spectral processing examples
//
// (c) V Lazzarini, 2005
//
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <spec.h>
#include <sndfile.h>
/** simple DFT demonstration program
dft filename
*/
int
main(int argc, char *argv[]){
SNDFILE *fin;
FILE *fout;
SF_INFO input_info;
float *sig, *spec, buf[100], mag, sr;
int size, i, k, read;
if(!(fin = sf_open(argv[1], SFM_READ, &input_info))){
printf("could not open %s\n", argv[1]);
exit(-1);
}
size = input_info.frames;
sr = input_info.samplerate;
sig = new float[size];
spec = new float[size*2];
read = sf_read_float(fin,sig,size);
DFT(sig, spec, size);
fout = fopen("spec.txt","w");
fprintf(fout,"%f\n", sr);
for(i=0, k=0; i<size; i++, k+=2) {
if(i<size/2){
mag = sqrt(spec[k]*spec[k] + spec[k+1]*spec[k+1])*2;
printf("[%.1f] %1.2f\n", i*sr/size, mag);
fprintf(fout,"%f\n", mag);
}
}
sf_close(fin);
fclose(fout);
delete[] sig;
delete[] spec;
return 0;
}
| 20.436364
| 59
| 0.524911
|
mike-normal13
|
9ead773f7de5063aed94fa6c04e6db6eb2edf912
| 13,604
|
cc
|
C++
|
Engine/Source/3rdParty/AssetImporter/AssimpMesh.cc
|
rodrigobmg/YumeEngine
|
67c525c84616a5167b5bae45f36641e90227c281
|
[
"MIT"
] | 129
|
2016-05-05T23:34:44.000Z
|
2022-03-07T20:17:18.000Z
|
Engine/Source/3rdParty/AssetImporter/AssimpMesh.cc
|
rodrigobmg/YumeEngine
|
67c525c84616a5167b5bae45f36641e90227c281
|
[
"MIT"
] | 1
|
2017-05-07T16:09:41.000Z
|
2017-05-08T15:35:50.000Z
|
Engine/Source/3rdParty/AssetImporter/AssimpMesh.cc
|
rodrigobmg/YumeEngine
|
67c525c84616a5167b5bae45f36641e90227c281
|
[
"MIT"
] | 20
|
2016-02-24T20:40:08.000Z
|
2022-02-04T23:48:18.000Z
|
//----------------------------------------------------------------------------
//Yume Engine
//Copyright (C) 2015 arkenthera
//This program is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 2 of the License, or
//(at your option) any later version.
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//You should have received a copy of the GNU General Public License along
//with this program; if not, write to the Free Software Foundation, Inc.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.*/
//----------------------------------------------------------------------------
//
// File : <Filename>
// Date : <Date>
// Comments :
//
//----------------------------------------------------------------------------
#include "YumeHeaders.h"
#include "AssimpMesh.h"
#include <Renderer/YumeVertexBuffer.h>
#include <Renderer/YumeIndexBuffer.h>
#include <Logging/logging.h>
#include <Core/YumeFile.h>
#include <Renderer/YumeRHI.h>
#include <assimp/ProgressHandler.hpp>
#include <iostream>
namespace YumeEngine
{
namespace detail
{
DirectX::XMFLOAT3 aivec_to_dxvec3(aiVector3D v)
{
return DirectX::XMFLOAT3(v.x,v.y,v.z);
}
DirectX::XMFLOAT4 aivec_to_dxvec4(aiColor4D v)
{
return DirectX::XMFLOAT4(v.r,v.g,v.b,v.a);
}
DirectX::XMFLOAT2 aivec_to_dxvec2(aiVector3D v)
{
return DirectX::XMFLOAT2(v.x,v.y);
}
YumeString to_tstring(aiString s)
{
std::string xs(s.data,s.length);
return YumeString(xs.c_str());
}
}
assimp_mesh::assimp_mesh():
importer_(),
mesh_infos_(),
indices_(),
num_faces_(0),
num_vertices_(0)
{
}
const aiScene* const assimp_mesh::assimp_scene() const
{
return importer_.GetScene();
}
void assimp_mesh::destroy()
{
}
size_t assimp_mesh::num_vertices()
{
size_t n = 0;
for(size_t m = 0; m < assimp_scene()->mNumMeshes; ++m)
n += assimp_scene()->mMeshes[m]->mNumVertices;
return n;
}
size_t assimp_mesh::num_faces()
{
size_t n = 0;
for(size_t m = 0; m < assimp_scene()->mNumMeshes; ++m)
n += assimp_scene()->mMeshes[m]->mNumFaces;
return n;
}
struct progress_handler : public Assimp::ProgressHandler
{
virtual bool Update(float percentage)
{
std::cout << "Loading mesh... %" << percentage*100 << std::endl;
return true;
}
};
void assimp_mesh::load(const YumeString& file)
{
YUMELOG_INFO("Loading Assimp Mesh " <<file.c_str());
progress_handler ph;
importer_.SetProgressHandler(&ph);
const aiScene* scene = importer_.ReadFile(file.c_str(),
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_MakeLeftHanded |
aiProcess_JoinIdenticalVertices |
aiProcess_SortByPType |
aiProcess_GenSmoothNormals |
//aiProcess_GenNormals |
aiProcess_RemoveRedundantMaterials |
aiProcess_OptimizeMeshes |
aiProcess_GenUVCoords |
aiProcess_TransformUVCoords);
if(!scene)
{
std::string error = importer_.GetErrorString();
YUMELOG_ERROR("Failed loading " << file.c_str());
return;
}
aiMatrix4x4 m;
load_internal(scene,scene->mRootNode,m);
importer_.SetProgressHandler(nullptr);
//tclog << L"Mesh info: " << std::endl
// << L" - " << mesh_infos_.size() << L" meshes" << std::endl
// << L" - " << "BBOX ("
// << bb_max().x << L", "
// << bb_max().y << L", "
// << bb_max().z << L")"
// << L" - ("
// << bb_min().x << L", "
// << bb_min().y << L", "
// << bb_min().z << L")"
// << std::endl
// << L" - " << num_faces_ << L" faces" << std::endl
// << L" - " << num_vertices_ << L" vertices" << std::endl;
}
void assimp_mesh::load_internal(const aiScene* scene,aiNode* node,aiMatrix4x4 acc_transform)
{
aiMatrix4x4 transform = acc_transform * node->mTransformation;
// store all meshes, one after another
for(size_t a = 0; a < node->mNumMeshes; ++a)
{
const aiMesh* mesh = scene->mMeshes[node->mMeshes[a]];
// store current read num_vertices_ and aiMesh for potential reference
mesh_info m;
m.vstart_index = num_vertices_;
m.istart_index = static_cast<UINT>(indices_.size());
m.num_faces = mesh->mNumFaces;
m.num_vertices = mesh->mNumVertices;
m.material_index = mesh->mMaterialIndex;
num_vertices_ += mesh->mNumVertices;
num_faces_ += mesh->mNumFaces;
// store vertices
for(size_t b = 0; b < mesh->mNumVertices; ++b)
{
assimp_mesh::vertex v;
aiVector3D v_trans = transform * mesh->mVertices[b];
v.position = detail::aivec_to_dxvec3(v_trans);
// if this is the very first vertex
if(m.vstart_index == 0 && b == 0)
init_bb(v.position);
else
update_bb(v.position);
if(mesh->HasNormals())
v.normal = detail::aivec_to_dxvec3(mesh->mNormals[b]);
if(mesh->HasTangentsAndBitangents())
v.tangent = detail::aivec_to_dxvec3(mesh->mTangents[b]);
for(size_t n = 0; n < mesh->GetNumUVChannels(); ++n)
{
v.texcoord[n] = detail::aivec_to_dxvec2(mesh->mTextureCoords[n][b]);
v.texcoord[n].y = 1.f - v.texcoord[n].y;
}
push_back(v);
m.update(v.position,b == 0);
}
// store indices, corrected by startIndex, and attribute
for(size_t b = 0; b < mesh->mNumFaces; ++b)
{
indices_.push_back(mesh->mFaces[b].mIndices[2]);
indices_.push_back(mesh->mFaces[b].mIndices[1]);
indices_.push_back(mesh->mFaces[b].mIndices[0]);
}
mesh_infos_.push_back(m);
}
for(size_t c = 0; c < node->mNumChildren; ++c)
assimp_mesh::load_internal(scene,node->mChildren[c],transform);
}
YumeMesh::YumeMesh()
{
}
YumeMesh::~YumeMesh()
{
}
void YumeMesh::push_back(vertex v)
{
YumeVertex gv;
gv.normal = v.normal;
gv.position = v.position;
gv.texcoord = v.texcoord[0];
gv.tangent = v.tangent;
vertices_.push_back(gv);
}
bool YumeMesh::Load(const YumeString& fileName)
{
assimp_mesh::load(fileName);
file_ = fileName;
if(PrepareMesh())
{
SaveMesh("D:/Arken/C++/Yume/v2/YumeEngine/build/Yume/Engine/Assets/Models/EXPORT/test.yume");
/*LoadFromFile("Models/EXPORT/test.yume");*/
}
return true;
}
bool YumeMesh::PrepareMesh()
{
YumeString path,fileName,extension;
SplitPath(file_,path,fileName,extension);
for(auto i = mesh_infos_.begin(); i != mesh_infos_.end(); ++i)
{
UINT num_vertices = i->num_vertices;
UINT num_faces = i->num_faces;
if(num_faces == 0 || num_vertices == 0)
{
YUMELOG_INFO("Skipping invalid mesh with " <<
num_vertices << " vertices and " <<
num_faces << " faces" << std::endl);
continue;
}
mesh_data mesh;
ZeroMemory(&mesh,sizeof(mesh));
mesh.vertexBuffer = &vertices_[i->vstart_index];
mesh.vertexSize = 44;
mesh.indexBuffer = &indices_[i->istart_index];
mesh.indexSize = sizeof(unsigned);
aiMaterial* mat = assimp_scene()->mMaterials[i->material_index];
SharedPtr<Material> internalMaterial(new Material);
aiColor4D color;
// grab diffuse color
mesh.diffuse_color = DirectX::XMFLOAT4(0.f,0.f,0.f,0.f);
if(mat->Get(AI_MATKEY_COLOR_DIFFUSE,color) == AI_SUCCESS)
mesh.diffuse_color = detail::aivec_to_dxvec4(color);
float opacity = 0;
if(mat->Get(AI_MATKEY_OPACITY,opacity) == AI_SUCCESS)
mesh.diffuse_color.w = opacity;
// grab specular color
mesh.specular_color = DirectX::XMFLOAT4(0.f,0.f,0.f,0.f);
if(mat->Get(AI_MATKEY_COLOR_SPECULAR,color) == AI_SUCCESS)
mesh.specular_color = detail::aivec_to_dxvec4(color);
// grab emissive color
mesh.emissive_color = DirectX::XMFLOAT4(0.f,0.f,0.f,0.f);
if(mat->Get(AI_MATKEY_COLOR_EMISSIVE,color) == AI_SUCCESS)
mesh.emissive_color = detail::aivec_to_dxvec4(color);
// get the shading mode -> abuse as basic material shading map
int shading_mode;
mesh.shading_mode = SHADING_DEFAULT;
if(mat->Get(AI_MATKEY_SHADING_MODEL,shading_mode) == AI_SUCCESS)
{
// convert back, don't care about the specific expected implementation
switch(shading_mode)
{
case 9: mesh.shading_mode = SHADING_OFF; break;
case 3: mesh.shading_mode = SHADING_DEFAULT; break;
case 2: mesh.shading_mode = SHADING_IBL; break;
default: mesh.shading_mode = SHADING_DEFAULT; break;
};
if(mesh.emissive_color.x + mesh.emissive_color.y + mesh.emissive_color.z > 0)
mesh.shading_mode = SHADING_AREA_LIGHT;
}
// get specular exponent
// WARNING: OBJ specifies shininess = Ns * 4
// convert shininess to roughness first
float shininess;
mesh.roughness = 0.0f;
if(mat->Get(AI_MATKEY_SHININESS,shininess) == AI_SUCCESS)
mesh.roughness = std::sqrtf(std::sqrtf(2.0f / (shininess + 2.0f)));
// get refractive index
float refractive_index;
mesh.refractive_index = 1.5;
if(mat->Get(AI_MATKEY_REFRACTI,refractive_index) == AI_SUCCESS)
mesh.refractive_index = refractive_index;
aiString str;
mesh.diffuse_tex_str = "Textures/default.png";
mesh.emissive_tex_str = "Textures/default.png";
mesh.specular_tex_str = "Textures/default.png";
mesh.normal_tex_str = "Textures/default.png";
mesh.alpha_tex_str = "Textures/default.png";
mesh.roughness_tex_str = "Textures/default.png";
str.Clear();
if(mat->Get(AI_MATKEY_TEXTURE_DIFFUSE(0),str) == AI_SUCCESS)
mesh.diffuse_tex_str = (YumeString(str.C_Str()));
str.Clear();
if(mat->Get(AI_MATKEY_TEXTURE_EMISSIVE(0),str) == AI_SUCCESS)
mesh.emissive_tex_str = (YumeString(str.C_Str()));
str.Clear();
if(mat->Get(AI_MATKEY_TEXTURE_SPECULAR(0),str) == AI_SUCCESS)
mesh.specular_tex_str = (YumeString(str.C_Str()));
str.Clear();
if(mat->Get(AI_MATKEY_TEXTURE_SHININESS(0),str) == AI_SUCCESS)
{
mesh.roughness_tex_str = str.C_Str();
}
str.Clear();
//mat->Get(AI_MATKEY_TEXTURE_NORMALS(0), str);
if(mat->Get(AI_MATKEY_TEXTURE_HEIGHT(0),str) == AI_SUCCESS)
mesh.normal_tex_str = (YumeString(str.C_Str()));
str.Clear();
if(mat->Get(AI_MATKEY_TEXTURE_OPACITY(0),str) == AI_SUCCESS)
mesh.alpha_tex_str = (YumeString(str.C_Str()));
materials_.push_back(internalMaterial);
meshes_.push_back(mesh);
}
importer_.FreeScene();
return true;
}
void YumeMesh::SaveMesh(const YumeString& fullPath)
{
YumeString pathName,fileName,extension;
SplitPath(fullPath,pathName,fileName,extension);
SharedPtr<YumeFile> file(new YumeFile(pathName + fileName + ".yume",FILEMODE_WRITE));
SharedPtr<YumeFile> materialFile(new YumeFile(pathName + fileName + ".material",FILEMODE_WRITE));
unsigned meshCount = meshes_.size();
file->WriteFileID("Mesh");
file->WriteUInt(meshCount);
materialFile->WriteFileID("Material");
materialFile->WriteUInt(meshCount);
for(int i=0; i < meshCount; ++i)
{
mesh_info m = mesh_infos_[i];
mesh_data data = meshes_[i];
unsigned vstart = m.vstart_index;
unsigned istart = m.istart_index;
unsigned num_faces = m.num_faces;
unsigned num_vertices = m.num_vertices;
unsigned material_index = m.material_index;
MaterialPtr material = materials_[i];
float bbMaxX = m.bb_max().x;
float bbMaxY = m.bb_max().y;
float bbMaxZ = m.bb_max().z;
float bbMinX = m.bb_min().x;
float bbMinY= m.bb_min().y;
float bbMinZ = m.bb_min().z;
file->WriteUInt(num_vertices);
file->WriteUInt(139);
file->WriteUInt(data.vertexSize);
file->Write(&vertices_[vstart],num_vertices * data.vertexSize);
file->WriteUInt(num_faces * 3);
file->WriteUInt(data.indexSize);
file->Write(&indices_[istart],num_faces * 3 * data.indexSize);
//Write bounding box of this mesh
file->WriteFloat(bbMaxX);
file->WriteFloat(bbMaxY);
file->WriteFloat(bbMaxZ);
file->WriteFloat(bbMinX);
file->WriteFloat(bbMinY);
file->WriteFloat(bbMinZ);
DirectX::XMFLOAT4 diffuseColor = data.diffuse_color;
DirectX::XMFLOAT4 emissiveColor = data.emissive_color;
DirectX::XMFLOAT4 specularColor = data.specular_color;
float shadingmMode = data.shading_mode;
float roughness = data.roughness;
float refractiveIndex = data.refractive_index;
YumeString diffuse_tex = data.diffuse_tex_str;
YumeString alpha_tex = data.alpha_tex_str;
YumeString emissive_tex = data.emissive_tex_str;
YumeString specular_tex = data.specular_tex_str;
YumeString normal_tex = data.normal_tex_str;
YumeString roughness_tex = data.roughness_tex_str;
materialFile->WriteVector4(diffuseColor);
materialFile->WriteVector4(emissiveColor);
materialFile->WriteVector4(specularColor);
materialFile->WriteFloat(shadingmMode);
materialFile->WriteFloat(roughness);
materialFile->WriteFloat(refractiveIndex);
materialFile->WriteString(diffuse_tex);
materialFile->WriteString(alpha_tex);
materialFile->WriteString(emissive_tex);
materialFile->WriteString(specular_tex);
materialFile->WriteString(normal_tex);
materialFile->WriteString(roughness_tex);
}
//Write overall BB
DirectX::XMFLOAT3 bbMin = bb_min_;
DirectX::XMFLOAT3 bbMax = bb_max_;
file->WriteVector3(bbMin);
file->WriteVector3(bbMax);
}
bool YumeMesh::LoadFromFile(const YumeString& fileName)
{
return true;
}
void YumeMesh::Render()
{
}
void YumeMesh::RenderDirect(unsigned index)
{
}
}
| 26.211946
| 99
| 0.666716
|
rodrigobmg
|
9eae3e6261d2baac4f93b0b82eaa0da45f562bd5
| 4,330
|
cpp
|
C++
|
polympc/tests/solvers/sqp/sqp_test.cpp
|
alexandreguerradeoliveira/rocket_gnc
|
164e96daca01d9edbc45bfaac0f6b55fe7324f24
|
[
"MIT"
] | null | null | null |
polympc/tests/solvers/sqp/sqp_test.cpp
|
alexandreguerradeoliveira/rocket_gnc
|
164e96daca01d9edbc45bfaac0f6b55fe7324f24
|
[
"MIT"
] | null | null | null |
polympc/tests/solvers/sqp/sqp_test.cpp
|
alexandreguerradeoliveira/rocket_gnc
|
164e96daca01d9edbc45bfaac0f6b55fe7324f24
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#define SOLVER_DEBUG
#include "solvers/sqp.hpp"
using namespace sqp;
namespace sqp_test {
template <typename _Scalar, int _VAR_SIZE, int _NUM_EQ=0, int _NUM_INEQ=0>
struct ProblemBase {
enum {
VAR_SIZE = _VAR_SIZE,
NUM_EQ = _NUM_EQ,
NUM_INEQ = _NUM_INEQ,
};
using Scalar = double;
using var_t = Eigen::Matrix<Scalar, VAR_SIZE, 1>;
using grad_t = Eigen::Matrix<Scalar, VAR_SIZE, 1>;
using hessian_t = Eigen::Matrix<Scalar, VAR_SIZE, VAR_SIZE>;
using b_eq_t = Eigen::Matrix<Scalar, NUM_EQ, 1>;
using A_eq_t = Eigen::Matrix<Scalar, NUM_EQ, VAR_SIZE>;
using b_ineq_t = Eigen::Matrix<Scalar, NUM_INEQ, 1>;
using A_ineq_t = Eigen::Matrix<Scalar, NUM_INEQ, VAR_SIZE>;
};
struct SimpleNLP_2D {
enum {
VAR_SIZE = 2,
NUM_EQ = 0,
NUM_INEQ = 2,
};
using Scalar = double;
using var_t = Eigen::Vector2d;
using grad_t = Eigen::Vector2d;
using b_eq_t = Eigen::Matrix<Scalar, NUM_EQ, 1>;
using A_eq_t = Eigen::Matrix<Scalar, NUM_EQ, VAR_SIZE>;
using b_ineq_t = Eigen::Matrix<Scalar, NUM_INEQ, 1>;
using A_ineq_t = Eigen::Matrix<Scalar, NUM_INEQ, VAR_SIZE>;
var_t SOLUTION = {1, 1};
void cost(const var_t& x, Scalar &cst)
{
cst = -x(0) -x(1);
}
void cost_linearized(const var_t& x, grad_t &grad, Scalar &cst)
{
cost(x, cst);
grad << -1, -1;
}
void constraint(const var_t& x, b_eq_t& b_eq, b_ineq_t& b_ineq, var_t& lbx, var_t& ubx)
{
const Scalar infinity = std::numeric_limits<Scalar>::infinity();
b_ineq << 1 - x.squaredNorm(), x.squaredNorm() - 2; // 1 <= x0^2 + x1^2 <= 2
lbx << 0, 0; // x0 > 0 and x1 > 0
ubx << infinity, infinity;
}
void constraint_linearized(const var_t& x,
A_eq_t& A_eq,
b_eq_t& b_eq,
A_ineq_t& A_ineq,
b_ineq_t& b_ineq,
var_t& lbx,
var_t& ubx)
{
constraint(x, b_eq, b_ineq, lbx, ubx);
A_ineq << -2*x.transpose(),
2*x.transpose();
}
};
TEST(SQPTestCase, TestSimpleNLP) {
SimpleNLP_2D problem;
SQP<SimpleNLP_2D> solver;
Eigen::Vector2d x;
// feasible initial point
Eigen::Vector2d x0 = {1.2, 0.1};
Eigen::Vector4d y0;
y0.setZero();
solver.settings().max_iter = 100;
solver.solve(problem, x0, y0);
x = solver.primal_solution();
EXPECT_TRUE(x.isApprox(problem.SOLUTION, 1e-2));
EXPECT_LT(solver.info().iter, solver.settings().max_iter);
}
TEST(SQPTestCase, InfeasibleStart) {
SimpleNLP_2D problem;
SQP<SimpleNLP_2D> solver;
Eigen::Vector2d x;
// infeasible initial point
Eigen::Vector2d x0 = {2, -1};
Eigen::Vector4d y0;
y0.setOnes();
solver.settings().max_iter = 100;
solver.solve(problem, x0, y0);
x = solver.primal_solution();
EXPECT_TRUE(x.isApprox(problem.SOLUTION, 1e-2));
EXPECT_LT(solver.info().iter, solver.settings().max_iter);
}
struct SimpleQP : public ProblemBase<double, 2, 1, 0> {
Eigen::Matrix2d P;
Eigen::Vector2d q;
Eigen::Vector2d SOLUTION;
SimpleQP()
{
P << 4, 1,
1, 2;
q << 1, 1;
SOLUTION << 0.3, 0.7;
}
void cost(const var_t& x, Scalar &cst)
{
cst = 0.5 * x.dot(P*x) + q.dot(x);
}
void cost_linearized(const var_t& x, grad_t &grad, Scalar &cst)
{
cost(x, cst);
grad << P*x + q;
}
void constraint(const var_t& x, b_eq_t& b_eq, b_ineq_t& b_ineq, var_t& lbx, var_t& ubx)
{
b_eq << x.sum() - 1; // x1 + x2 = 1
lbx << 0, 0;
ubx << 0.7, 0.7;
}
void constraint_linearized(const var_t& x, A_eq_t& A_eq, b_eq_t& b_eq, A_ineq_t& A_ineq, b_ineq_t& b_ineq, var_t& lbx, var_t& ubx)
{
constraint(x, b_eq, b_ineq, lbx, ubx);
A_eq << 1, 1;
}
};
TEST(SQPTestCase, TestSimpleQP) {
SimpleQP problem;
SQP<SimpleQP> solver;
Eigen::Vector2d x;
solver.solve(problem);
x = solver.primal_solution();
EXPECT_TRUE(x.isApprox(problem.SOLUTION, 1e-2));
EXPECT_LT(solver.info().iter, solver.settings().max_iter);
}
} // sqp_test
| 26.084337
| 134
| 0.575982
|
alexandreguerradeoliveira
|
9eb225ce0a7db6ee80034681222495a287a968f2
| 2,319
|
cpp
|
C++
|
software/tests/sensor/fusion/fusion.cpp
|
jbarry510/slonav
|
acebb8481e5623c3548258fe0e92a983618032a3
|
[
"MIT"
] | null | null | null |
software/tests/sensor/fusion/fusion.cpp
|
jbarry510/slonav
|
acebb8481e5623c3548258fe0e92a983618032a3
|
[
"MIT"
] | null | null | null |
software/tests/sensor/fusion/fusion.cpp
|
jbarry510/slonav
|
acebb8481e5623c3548258fe0e92a983618032a3
|
[
"MIT"
] | 1
|
2020-11-29T17:22:09.000Z
|
2020-11-29T17:22:09.000Z
|
/* @file fusion.h
* This file contains the implementation of a Kalman filter for the SLONav system
*/
//------------------------------------------------------------------------------
#include "fusion.h"
//------------------------------------------------------------------------------
Fusion::Fusion()
{
// Process noise covariance (assume states are uncorrelated)
this->setQ(0, 0, (a_max*dt^2*cos(this->x[4])/2)^2);
this->setQ(1, 1, (a_max*dt^2*sin(this->x[4])/2)^2);
this->setQ(2, 2, (a_max*dt)^2);
this->setQ(3, 3, (jerk_max*dt)^2);
this->setQ(4, 4, (yaw_max*dt)^2);
// Measurement noise covariance (assume measurements are uncorrelated)
this->setR(0, 0, .0001);
this->setR(1, 1, .0001);
this->setR(2, 2, .0001);
this->setR(3, 3, .0001);
this->setR(4, 4, .0001);
this->setR(5, 5, .0001);
}
void Fusion::model(double fx[Nsta], double F[Nsta][Nsta], double hx[Mobs], double H[Mobs][Nsta])
{
// Process model
fx[0] = (this->x[0] + this->x[2]*cos(this->x[4])*dt
+ this->x[3]*1/2*cos(this->x[4])*dt^2); // X position
fx[1] = (this->x[1] + this->x[2]*sin(this->x[4])*dt
this->x[3]*1/2*sin(this->x[4])*dt^2); // Y position
fx[2] = this->x[2] + this->x[3]*dt; // Velocity
fx[3] = this->x[3]; // Acceleration
fx[4] = this->x[4]; // Heading
// Jacobian of process model
F[0][0] = 1;
F[0][2] = -sin(this->x[4])*dt
F[0][3] = -1/2*sin(this->x[4])*dt^2
F[1][1] = 1;
F[1][2] = cos(this->x[4])*dt
F[1][3] = 1/2*cos(this->x[4])*dt^2
F[2][2] = 1;
F[2][3] = dt;
F[3][3] = 1;
F[4][4] = 1;
// Measurement function
hx[0] = this->x[0]; // GPS X position from previous state
hx[1] = this->x[1]; // GPS Y position from previous state
hx[2] = this->x[1]; // Encoder velocity from previous state
hx[3] = this->x[1]; // IMU acceleration from previous state
hx[4] = this->x[1]; // IMU heading from previous state
// Jacobian of measurement function
H[0][0] = 1; // IMU X acceleration from previous state
H[1][1] = 1; // IMU Y acceleration from previous state
H[2][2] = 1; // IMU heading from previous state
H[3][3] = 1; // GPS X position from previous state
H[4][4] = 1; // GPS Y position from previous state
}
| 36.234375
| 96
| 0.511859
|
jbarry510
|
9eb3fd407460f5e8884e50993bda3a44101c4f9c
| 10,078
|
cpp
|
C++
|
qflow/wavefunctions/pywavefunction.cpp
|
johanere/qflow
|
5453cd5c3230ad7f082adf9ec1aea63ab0a4312a
|
[
"MIT"
] | 5
|
2019-07-24T21:46:24.000Z
|
2021-06-11T18:18:24.000Z
|
qflow/wavefunctions/pywavefunction.cpp
|
johanere/qflow
|
5453cd5c3230ad7f082adf9ec1aea63ab0a4312a
|
[
"MIT"
] | 22
|
2019-02-19T10:49:26.000Z
|
2019-07-18T09:42:13.000Z
|
qflow/wavefunctions/pywavefunction.cpp
|
bsamseth/FYS4411
|
72b879e7978364498c48fc855b5df676c205f211
|
[
"MIT"
] | 2
|
2020-11-04T15:17:24.000Z
|
2021-11-03T16:37:38.000Z
|
#include "dnn.hpp"
#include "fixedwavefunction.hpp"
#include "hardspherewavefunction.hpp"
#include "inputsorter.hpp"
#include "jastrowmcmillian.hpp"
#include "jastroworion.hpp"
#include "jastrowpade.hpp"
#include "rbmsymmetricwavefunction.hpp"
#include "rbmwavefunction.hpp"
#include "simplegaussian.hpp"
#include "wavefunction.hpp"
#include "wavefunctionpooling.hpp"
#include "wavefunctionproduct.hpp"
#include <Eigen/Dense>
#include <pybind11/eigen.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
void init_nn(py::module&);
void init_wavefunction(py::module& main)
{
auto m = main.def_submodule("wavefunctions");
m.doc() = R"doc(
Wavefunctions
-------------
The wavefunction module defines a set of pre-built components that can be used to
set up a variety of different trial wavefunctions.
)doc";
init_nn(m);
py::class_<Wavefunction>(m, "Wavefunction", R"doc(
The :class:`Wavefunction` class provides a unified abstraction for all wavefunctions.
All other code expecting a wavefunction instance will take a :class:`Wavefunction` reference.
In this context, a trial wavefunction is defied to be a class that can:
- Have zero or more parameters, :math:`\vec\alpha`
- Evaluate given some system configuraiton :math:`\mathbf{X}`:
.. math::
\text{Evaluation}_\Psi(\mathbf{X} = \Psi(\mathbf{X})
- Compute the gradient w.r.t. each variational parameter, :math:`\vec{\alpha}`:
.. math::
\text{Gradient}_\Psi(\mathbf{X}) = \frac{1}{\Psi(\mathbf{X})}
\frac{\partial \Psi(\mathbf{X})}{\partial\vec\alpha}
- Compute the drift force w.r.t. particle :math:`k`'s dimensions ional coordinate :math:`l`:
.. math::
\text{Drift}_{\Psi(\mathbf{X}), k,l} = \frac{2}{\Psi(\mathbf{X})}
\frac{\partial \Psi(\mathbf{X})}{\partial X_{kl}}
- Compute the laplacian of a system of :math:`N` particles in :math:`D` dimensions:
.. math::
\text{Laplacian}_\Psi(\mathbf{X}) = \sum_{k=1}^N\sum_{l=1}^D
\frac{1}{\Psi(\mathbf{X})}\frac{\partial^2 \Psi(\mathbf{X})}{\partial X_{kl}^2}
.. note::
Wavefunctions are limited to real-valued functions only - there is no
support for complex valued wavefunctions at this time.
)doc")
.def("__call__", &Wavefunction::operator(), py::arg("system"), R"doc(
Return the evaluation of the wavefunction for the given system
.. math::
\text{Evaluation}_\Psi(\mathbf{X} = \Psi(\mathbf{X})
)doc")
.def("gradient", &Wavefunction::gradient, py::arg("system"), R"doc(
Return the gradient w.r.t. each variational parameter, divided by the evaluation:
.. math::
\text{Gradient}_\Psi(\mathbf{X}) = \frac{1}{\Psi(\mathbf{X})}
\frac{\partial \Psi(\mathbf{X})}{\partial\vec\alpha}
)doc")
.def("laplacian", &Wavefunction::laplacian, py::arg("system"), R"doc(
.. math::
\text{Laplacian}_\Psi(\mathbf{X}) = \sum_{k=1}^N\sum_{l=1}^D
\frac{1}{\Psi(\mathbf{X})}\frac{\partial^2 \Psi(\mathbf{X})}{\partial X_{kl}^2}
)doc")
.def("drift_force",
py::overload_cast<const System&, int, int>(&Wavefunction::drift_force),
py::arg("system"),
py::arg("k"),
py::arg("l"),
R"doc(
Return the drift force w.r.t. particle :math:`k`'s dimensions ional coordinate :math:`l`:
.. math::
\text{Drift}_{\Psi(\mathbf{X}), k, l} = \frac{2}{\Psi(\mathbf{X})}
\frac{\partial \Psi(\mathbf{X})}{\partial X_{kl}}
)doc")
.def("drift_force",
py::overload_cast<const System&>(&Wavefunction::drift_force),
py::arg("system"),
R"doc(
Return a list of drift forces for all particles and all dimensions.
The list will be one-dimensional, such that
:math:`\text{Drift}_{\Psi(\mathbf{X}), k,l}` is at index ``k * D + l``.
)doc")
.def("symmetry_metric",
&Wavefunction::symmetry_metric,
py::arg("sampler"),
py::arg("samples"),
py::arg("max_permutations") = 100,
R"doc(
Return an estimate of the symmetry of the wavefunction.
This is defined as follows:
.. math::
S(\Psi) = \frac{\int_{-\infty}^\infty \text{d}\mathbf X\left|\frac{1}{n!}
\sum_{\mathbf\alpha\in \mathcal{P}_n} P_{\mathbf\alpha}\Psi\right|^2}{\int_{-\infty}^\infty\text{d}\mathbf X
\max_{\mathbf\alpha\in \mathcal{P}} \left|P_{\mathbf\alpha}\Psi\right|^2}
Here :math:`P_\mathbf{\alpha}\Psi` denotes applying the permutation
:math:`\mathbf{\alpha}` to the input system before evaluating the wavefunction,
and :math:`\mathcal{P}_n` is the set of all permutations of :math:`n` particles.
Properties of this metric:
- It takes values in :math:`[0, 1]`
- For symmetric wavefunctions, it equals exactly 1
- For anti-symmetric wavefunctions, it equals exactly 0
- Any other function evaluates in :math:`(0, 1)`
This integral will be approximated with Monte Carlo integration using samples from the provided
sampling strategy, and using the specified number of samples. While the integral is defied over all
permutations, a maximum of ``max_permutations`` will be used to make it tractable for large ``N``.
)doc")
.def_property(
"parameters",
py::overload_cast<>(&Wavefunction::get_parameters, py::const_),
py::overload_cast<const RowVector&>(&Wavefunction::set_parameters),
R"doc(
List of all variational parameters. Supports both read and write.
)doc");
py::class_<FixedWavefunction, Wavefunction>(m, "FixedWavefunction", R"doc(
Wrapper for any wavefunction that fixes the variational parameters.
This means that if this wavefunction is used in a optimization call, its
parameters will not change. This is useful if parts of a wavefunction should be
held constant, while another is allowed to be optimized.
)doc")
.def(py::init<Wavefunction&>(), py::arg("wavefunction"));
py::class_<WavefunctionProduct, Wavefunction>(m, "WavefunctionProduct", R"doc(
Defines a wavefunction that acts like the product of two others.
All derivatives will be suitably derived, so this is a simple way to produce
compound expressions.
)doc")
.def(py::init<Wavefunction&, Wavefunction&>(),
py::arg("Psi_1"),
py::arg("Psi_2"));
py::class_<SumPooling, Wavefunction>(m, "SumPooling", R"doc(
This wavefunction expects a wavefunction of two particles,
:math:`f(\mathbf{x}_1, \mathbf{x}_2)`, and represents the following compound
expression:
.. math::
\Psi(\mathbf{X}) = \sum_{i \neq j}^N f(\mathbf{X}_i, \mathbf{X}_j)
This is guaranteed to produce a permutation symmetric wavefunction, given any suitable
inner wavefunction :math:`f`.
)doc")
.def(py::init<Wavefunction&>());
py::class_<InputSorter, Wavefunction>(m, "InputSorter")
.def(py::init<Wavefunction&>());
py::class_<SimpleGaussian, Wavefunction>(m, "SimpleGaussian", R"doc(
A product of gaussians:
.. math::
\Psi(\mathbf{X}) = \prod_{i=1}^N e^{-\alpha ||\mathbf{X}_i||^2}
The only variational parameter is :math:`\alpha`.
For 3D systems, an optional *fixed* parameter :math:`\beta` can be specified, which changes the above definition to:
.. math::
\Psi(\mathbf{X}) = \prod_{i=1}^N e^{-\alpha\left(X_{i,1}^2 + X_{i,2}^2 + \beta X_{i,3}^2\right)}
)doc")
.def(py::init<Real, Real>(), py::arg("alpha") = 0.5, py::arg("beta") = 1);
py::class_<HardSphereWavefunction, SimpleGaussian>(
m, "HardSphereWavefunction", R"doc(
A product of gaussians and pairwise correlation factors:
.. math::
\Psi(\mathbf{X}) = \prod_{i=1}^N e^{-\alpha\left(X_{i,1}^2 + X_{i,2}^2 + \beta X_{i,3}^2\right)}
\prod_{j = i + 1}^{N} \begin{cases} 0 &\text{if}\ \ ||\mathbf{X}_i - \mathbf{X}_j|| \leq a\\
1 - \frac{a}{||\mathbf{X}_i - \mathbf{X}_j||} &\text{otherwise}
\end{cases}
Similarly to :class:`SimpleGaussian`, the only variational parameter is
:math:`\alpha`, while the other two parameters :math:`\beta` and :math:`a` are
assumed constant.
)doc")
.def(py::init<Real, Real, Real>(),
py::arg("alpha") = 0.5,
py::arg("beta") = 1,
py::arg("a") = 0);
py::class_<JastrowPade, Wavefunction>(m, "JastrowPade", R"doc(
A correlation term meant to be suitable for particles in a harmonic oscillator potential with
a repulsive Coulomb force causing interactions:
.. math::
\Psi(\mathbf{X}) = \prod_{i < j}^N e^{\frac{\alpha r_ij}{1 + \beta r_ij}}
)doc")
.def(py::init<Real, Real, bool>(),
py::arg("alpha") = 0.5,
py::arg("beta") = 1,
py::arg("alpha_is_constant") = true);
py::class_<JastrowOrion, Wavefunction>(m, "JastrowOrion", R"doc(
A correlation term meant to be suitable for particles in a harmonic oscillator potential with
a repulsive Coulomb force causing interactions:
.. math::
\Psi(\mathbf{X}) = \prod_{i < j}^N
e^{-\frac{\beta^2}{2}||\mathbf{X_i}-\mathbf{X_j}||^2 +
|\beta\gamma|||\mathbf{X_i}-\mathbf{X_j}||}
)doc")
.def(py::init<Real, Real>(), py::arg("beta") = 1.0, py::arg("gamma") = 0);
py::class_<JastrowMcMillian, Wavefunction>(m, "JastrowMcMillian")
.def(py::init<int, Real, Real>(), py::arg("n"), py::arg("beta"), py::arg("L"));
py::class_<RBMWavefunction, Wavefunction>(m, "RBMWavefunction")
.def(py::init<int, int, Real, Real>(),
py::arg("M"),
py::arg("N"),
py::arg("sigma2") = 1,
py::arg("root_factor") = 1);
py::class_<RBMSymmetricWavefunction, Wavefunction>(m, "RBMSymmetricWavefunction")
.def(py::init<int, int, int, Real, Real>(),
py::arg("M"),
py::arg("N"),
py::arg("f"),
py::arg("sigma2") = 1,
py::arg("root_factor") = 1);
py::class_<Dnn, Wavefunction>(m, "Dnn")
.def(py::init<>())
.def("add_layer", &Dnn::addLayer)
.def_property_readonly("layers", &Dnn::getLayers);
}
| 35.237762
| 116
| 0.630581
|
johanere
|
9eb89a71ac366f3422f0c95b8eebac51ccf311bb
| 332
|
cpp
|
C++
|
bin/barftest/sem/ErrorDummy.cpp
|
vdods/barf
|
5c943ddbd6a0a7624645158b0c85994431dde269
|
[
"Apache-2.0"
] | 1
|
2021-01-16T00:55:45.000Z
|
2021-01-16T00:55:45.000Z
|
bin/barftest/sem/ErrorDummy.cpp
|
vdods/barf
|
5c943ddbd6a0a7624645158b0c85994431dde269
|
[
"Apache-2.0"
] | null | null | null |
bin/barftest/sem/ErrorDummy.cpp
|
vdods/barf
|
5c943ddbd6a0a7624645158b0c85994431dde269
|
[
"Apache-2.0"
] | null | null | null |
// 2018.08.30 - Victor Dods
#include "barftest/sem/ErrorDummy.hpp"
namespace barftest {
namespace sem {
ErrorDummy *ErrorDummy::cloned () const
{
return new ErrorDummy(firange());
}
void ErrorDummy::print (Log &out) const
{
out << "ErrorDummy(" << firange() << ')';
}
} // end namespace sem
} // end namespace barftest
| 16.6
| 45
| 0.662651
|
vdods
|
9ec01dad1bdf440560f80869b2a0153d1d543228
| 525
|
hpp
|
C++
|
libboost-system/include/boost/cerrno.hpp
|
build2-packaging/boost
|
203d505dd3ba04ea50785bc8b247a295db5fc718
|
[
"BSL-1.0"
] | 4
|
2021-02-23T11:24:33.000Z
|
2021-09-11T20:10:46.000Z
|
libboost-system/include/boost/cerrno.hpp
|
build2-packaging/boost
|
203d505dd3ba04ea50785bc8b247a295db5fc718
|
[
"BSL-1.0"
] | null | null | null |
libboost-system/include/boost/cerrno.hpp
|
build2-packaging/boost
|
203d505dd3ba04ea50785bc8b247a295db5fc718
|
[
"BSL-1.0"
] | null | null | null |
// Boost cerrno.hpp header -------------------------------------------------//
// Copyright Beman Dawes 2005.
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See library home page at http://www.boost.org/libs/system
#ifndef BOOST_CERRNO_HPP_INCLUDED
#define BOOST_CERRNO_HPP_INCLUDED
#include <boost/system/detail/cerrno.hpp>
#endif // #ifndef BOOST_CERRNO_HPP_INCLUDED
| 32.8125
| 80
| 0.689524
|
build2-packaging
|
9ec20311eb0c8b01bd03e99d08534c3b08f58391
| 992
|
cpp
|
C++
|
tests/tests-iter-pos/test-bool.cpp
|
eepp/yactfr
|
5cec5680d025d82a4f175ffc19c0704b32ef529f
|
[
"MIT"
] | 7
|
2016-08-26T14:20:06.000Z
|
2022-02-03T21:17:25.000Z
|
tests/tests-iter-pos/test-bool.cpp
|
eepp/yactfr
|
5cec5680d025d82a4f175ffc19c0704b32ef529f
|
[
"MIT"
] | 2
|
2018-05-29T17:43:37.000Z
|
2018-05-30T18:38:39.000Z
|
tests/tests-iter-pos/test-bool.cpp
|
eepp/yactfr
|
5cec5680d025d82a4f175ffc19c0704b32ef529f
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2018-2022 Philippe Proulx <eepp.ca>
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include <limits>
#include <cstring>
#include <sstream>
#include <iostream>
#include <iterator>
#include <vector>
#include <yactfr/yactfr.hpp>
#include <mem-data-src-factory.hpp>
#include <common-trace.hpp>
int main()
{
const auto traceTypeEnvPair = yactfr::fromMetadataText(metadata,
metadata + std::strlen(metadata));
MemDataSrcFactory factory {stream, sizeof stream};
yactfr::ElementSequence seq {*traceTypeEnvPair.first, factory};
const auto it = seq.begin();
yactfr::ElementSequenceIteratorPosition pos;
if (pos) {
std::cerr << "Position is true.\n";
return 1;
}
it.savePosition(pos);
if (!pos) {
std::cerr << "Position is false.\n";
return 1;
}
return 0;
}
| 22.545455
| 93
| 0.623992
|
eepp
|
9ec74801ccc0bf3691b922607dea77d3a155dac3
| 1,099
|
cpp
|
C++
|
Training/day1/Defeat the Enemy.cpp
|
QAQrz/ACM-Code
|
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
|
[
"Unlicense"
] | 2
|
2018-02-24T06:45:56.000Z
|
2018-05-29T04:47:39.000Z
|
Training/day1/Defeat the Enemy.cpp
|
QAQrz/ACM-Code
|
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
|
[
"Unlicense"
] | null | null | null |
Training/day1/Defeat the Enemy.cpp
|
QAQrz/ACM-Code
|
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
|
[
"Unlicense"
] | 2
|
2018-06-28T09:53:27.000Z
|
2022-03-23T13:29:57.000Z
|
#include <bits/stdc++.h>
using namespace std;
#define db(x) cout<<(x)<<endl
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define ms(x,y) memset(x,y,sizeof x)
typedef long long LL;
const LL mod=1e9+7,inf=0x3f3f3f3f,maxn=112345;
struct node{
int a,b;
}a[maxn],b[maxn];
int t,n,m,ans,f,p,s;
inline bool cmp(node a,node b){
return a.a>b.a;
}
inline bool cmpb(node a,node b){
return a.b>b.b;
}
int main(){
ios::sync_with_stdio(false);
cin>>t;
for(int k=1;k<=t;k++){
vector<int>v;
cin>>n>>m;
s=f=0,ans=n;
for(int i=0;i<n;i++)
cin>>a[i].a>>a[i].b;
for(int i=0;i<m;i++)
cin>>b[i].a>>b[i].b;
if(n<m)
ans=-1;
else{
sort(a,a+n,cmp);
sort(b,b+m,cmpb);
for(int i=0;i<m;i++){
while(f<n&&a[f].a>=b[i].b){
v.insert(upper_bound(v.begin(),v.end(),a[f].b),a[f].b);
s++,f++;
}
p=upper_bound(v.begin(),v.end(),b[i].a)-v.begin();
if(p<s){
v.erase(v.begin()+p);
s--;
}
else if(s){
v.erase(v.begin());
s--,ans--;
}
else{
ans=-1;
break;
}
}
}
printf("Case #%d: %d\n",k,ans);
}
return 0;
}
| 18.948276
| 60
| 0.530482
|
QAQrz
|
9ec84656beece08bbfda60dd0ca5d9ec47269b8a
| 596
|
cpp
|
C++
|
solutions/230.kth-smallest-element-in-a-bst.259865536.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | 78
|
2020-10-22T11:31:53.000Z
|
2022-02-22T13:27:49.000Z
|
solutions/230.kth-smallest-element-in-a-bst.259865536.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | null | null | null |
solutions/230.kth-smallest-element-in-a-bst.259865536.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | 26
|
2020-10-23T15:10:44.000Z
|
2021-11-07T16:13:50.000Z
|
/**
* 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 {
int ans;
public:
int kthSmallest(TreeNode *root, int k) {
search(root, k);
return ans;
}
int search(TreeNode *root, int k) {
if (!root)
return NULL;
int leftCount = search(root->left, k);
if (leftCount + 1 == k)
ans = root->val;
int rightCount = search(root->right, k - 1 - leftCount);
return 1 + leftCount + rightCount;
}
};
| 17.529412
| 60
| 0.565436
|
satu0king
|
19b3f12276fa0708fec5b809876f899038e0c9e5
| 2,477
|
cpp
|
C++
|
data-structure-and-algorithm/03-brute-force-search/ABC128-c-bit.cpp
|
tetsuzawa/algorithm
|
556c229c6df8787a118498eab3848b53fb57ebd0
|
[
"MIT"
] | null | null | null |
data-structure-and-algorithm/03-brute-force-search/ABC128-c-bit.cpp
|
tetsuzawa/algorithm
|
556c229c6df8787a118498eab3848b53fb57ebd0
|
[
"MIT"
] | null | null | null |
data-structure-and-algorithm/03-brute-force-search/ABC128-c-bit.cpp
|
tetsuzawa/algorithm
|
556c229c6df8787a118498eab3848b53fb57ebd0
|
[
"MIT"
] | null | null | null |
// N switches, M bulbs,
// 5 switches
// bulb[1] 1, 2, 5: odd =>
// 5 2 1
// (off, off, on)
// (off, on, off)
// (on, off, off)
// (on, on, on)
// bulb[2] 2, 3: even =>
// 2 1
// (on, on)
// (off, off)
// 5, 4, 3, 2, 1 | res
// ------------------
// 0 0 0 0 0 | 0
// 0 0 0 0 1 | 1
// 0 0 0 1 0 | 0
// 0 0 0 1 1 | 0
// 0 0 1 0 0 | 0
// 0 0 1 0 1 | 0
// 0 0 1 1 1 | 0
// 0 1 0 0 0 | 0
// 0 1 0 0 1 | 0
// 0 1 0 1 0 | 0
// 0 1 0 1 1 | 0
// 0 1 1 0 0 | 0
// 0 1 1 0 1 | 0
// 0 1 1 1 0 | 0
// 0 1 1 1 1 | 0
// 1 0 0 0 0 | 1
// 1 0 0 0 1 | 0
// 1 0 0 1 1 | 0
// 1 0 1 0 0 | 1
// 1 0 1 0 1 | 0
// 1 0 1 1 0 | 0
// 1 0 1 1 1 | 1
// 1 1 0 0 0 | 1
// 1 1 0 0 1 | 0
// 1 1 0 1 0 | 0
// 1 1 0 1 1 | 1
// 1 1 1 0 0 | 1
// 1 1 1 0 1 | 0
// 1 1 1 1 0 | 0
// 1 1 1 1 1 | 1
#include <iostream>
#include <bitset>
#include <vector>
using namespace std;
void print_vector(vector <vector<int>> vec) {
for (int i = 0; i < vec.size(); ++i) {
for (int j = 0; j < vec.at(i).size(); j++) {
cout << vec.at(i).at(j) << " ";
}
cout << endl;
}
}
int main() {
int N, M;
cin >> N >> M;
vector <bitset<10>> bulb_switches;
for (int i = 0; i < M; ++i) {
int k;
cin >> k;
bitset<10> switches;
for (int j = 0; j < k; ++j) {
int switch_num;
cin >> switch_num;
switches |= (1 << (switch_num - 1));
}
bulb_switches.push_back(switches);
}
vector<int> bulb_light_up_condition;
for (int i = 0; i < M; ++i) {
int p;
cin >> p;
bulb_light_up_condition.push_back(p);
}
int lightening_bulb_count = 0;
for (int bit = 0; bit < (1 << N); ++bit) {
bool hasNonLighteningBulb = false;
for (int i = 0; i < M; ++i) {
bitset<10> bb (bit);
if ((bulb_switches.at(i) & bb).count() % 2 != bulb_light_up_condition[i]) {
hasNonLighteningBulb = true;
break;
}
}
if (hasNonLighteningBulb) {
continue;
}
lightening_bulb_count++;
}
cout << lightening_bulb_count << endl;
}
| 23.149533
| 87
| 0.377069
|
tetsuzawa
|
19b8090357bfc50064555a63ea81e10929699981
| 2,481
|
cc
|
C++
|
clion/C++ClassObjImpl.cc
|
zuut/cppstarter
|
78dd5a1f52a1272ad26b57c9b5c06a095f340c99
|
[
"Apache-2.0"
] | null | null | null |
clion/C++ClassObjImpl.cc
|
zuut/cppstarter
|
78dd5a1f52a1272ad26b57c9b5c06a095f340c99
|
[
"Apache-2.0"
] | null | null | null |
clion/C++ClassObjImpl.cc
|
zuut/cppstarter
|
78dd5a1f52a1272ad26b57c9b5c06a095f340c99
|
[
"Apache-2.0"
] | null | null | null |
#parse("C++TemplateVariables.template")
#[[#define]]# ${API_EXTERN}
#[[#include]]# "${Header_Filename}"
#[[#include]]# <string>
#[[#include]]# <iostream>
#[[#include]]# <boost/core/demangle.hpp>
${NAMESPACES_OPEN}
// this just holds the class fields in a struct to isolate
// clients from changes to the class structure.
struct ${NAME}::Impl final
{
Impl() :
strProp_(),
primitive_(0)
{
}
std::string strProp_;
int primitive_;
};
${NAME}::${NAME}() :
impl_(std::make_unique<Impl>())
{
}
${NAME}::${NAME}(const ${NAME}& other) :
impl_(other.impl_ ? std::make_unique<Impl>(*other.impl_) : std::make_unique<Impl>())
{
}
${NAME}::${NAME}(${NAME}&& rref) noexcept = default;
// Custom constructor
${NAME}::${NAME}(std::string prop1, int prop2) :
impl_(std::make_unique<Impl>())
{
impl_->strProp_ = prop1;
impl_->primitive_ = prop2;
}
${NAME}::~${NAME}() = default;
${NAME}& ${NAME}::operator = (const ${NAME}& other)
{
// We don't worry about potential object slicing because
// Impl is never subclassed
if (impl_ && other.impl_) {
*this->impl_ = *other.impl_;
} else if (other.impl_) {
impl_ = std::make_unique<Impl>(*other.impl_);
} else {
impl_.reset();
}
return *this;
}
${NAME}& ${NAME}::operator = (${NAME}&& rref) noexcept = default;
std::ostream& operator << (std::ostream& os, const ${NAME}& obj)
{
const std::string className = boost::core::demangle(typeid(&obj).name());
os << "{" << className << ":";
if (obj.impl_ != nullptr) {
#[[#define]]# ofield(nm) #nm << ":" << obj.impl_->nm << " "
os << "address:" << obj.impl_.get() << " "
<< ofield(strProp_)
<< ofield(primitive_);
#[[#undef]]# ofield
} else {
os << "impl_: nullptr";
}
os << "}" << std::endl;
return os;
}
std::string ${NAME}::prop1() const
{
return impl_->strProp_;
}
void ${NAME}::set_prop1(const std::string& val)
{
impl_->strProp_ = val;
}
int ${NAME}::prop2() const
{
return impl_->primitive_;
}
void ${NAME}::set_prop2(const int val)
{
impl_->primitive_ = val;
}
${NAMESPACES_CLOSE}
| 23.855769
| 92
| 0.500605
|
zuut
|
19bd7b5f0699eb5a77d2ef903fb41590a83c769c
| 861
|
cpp
|
C++
|
Stack/Previous_Greater_Element.cpp
|
utkarshkanswal/Data-Strucrure-and-Algorithm
|
5db39daf1403d270dacef06261fbfa62902e05ed
|
[
"MIT"
] | 1
|
2021-11-02T09:33:55.000Z
|
2021-11-02T09:33:55.000Z
|
Stack/Previous_Greater_Element.cpp
|
utkarshkanswal/Data-Strucrure-and-Algorithm
|
5db39daf1403d270dacef06261fbfa62902e05ed
|
[
"MIT"
] | null | null | null |
Stack/Previous_Greater_Element.cpp
|
utkarshkanswal/Data-Strucrure-and-Algorithm
|
5db39daf1403d270dacef06261fbfa62902e05ed
|
[
"MIT"
] | null | null | null |
/* Name: Utkarsh Kumar
Institution: NIT Meghalaya
*/
#include <bits/stdc++.h>
#define mod (1000000007)
#define lli long long int
#define pf push_front
#define pb push_back
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
using namespace std;
//Time Complexity: O(n)
void print_previous_greater(vector<int> arr, int n)
{
stack<int> st;
st.push(arr[0]);
cout << "-1 ";
for (int i = 1; i < n; i++)
{
while (st.empty() == false && st.top() <= arr[i])
st.pop();
int temp_res = st.empty() ? -1 : st.top();
cout << temp_res << " ";
st.push(arr[i]);
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++)
cin >> arr[i];
print_previous_greater(arr, n);
return 0;
}
| 22.657895
| 57
| 0.554007
|
utkarshkanswal
|
19be9d8df571498b388bf7965be33ab3bfd6103c
| 2,070
|
cpp
|
C++
|
Rev/cpp/revMesh.cpp
|
YIMonge/Rev
|
db3b71a27659a2652bdd50069a881702b3ae059e
|
[
"MIT"
] | null | null | null |
Rev/cpp/revMesh.cpp
|
YIMonge/Rev
|
db3b71a27659a2652bdd50069a881702b3ae059e
|
[
"MIT"
] | null | null | null |
Rev/cpp/revMesh.cpp
|
YIMonge/Rev
|
db3b71a27659a2652bdd50069a881702b3ae059e
|
[
"MIT"
] | null | null | null |
#include "revMesh.h"
void revMesh::CreateVertexBufferData()
{
uint32 vertexCount = static_cast<uint32>(vertices.size());
vertexData.clear();
vertexData.reserve(GetSizeOfBytes() / sizeof(f32) * vertexCount);
for (uint32 i = 0; i < vertexCount; ++i) {
vertexData.push_back(vertices[i].x);
vertexData.push_back(vertices[i].y);
vertexData.push_back(vertices[i].z);
if (hasElement(INPUT_ELEMENT_TYPE::NORMAL)) {
vertexData.push_back(normals[i].x);
vertexData.push_back(normals[i].y);
vertexData.push_back(normals[i].z);
}
// TODO:
if (hasElement(INPUT_ELEMENT_TYPE::TANGENT)) {
}
// texcoord
if (hasElement(INPUT_ELEMENT_TYPE::TEXCOORD0)) {
vertexData.push_back(texCoords[0][i].x);
vertexData.push_back(texCoords[0][i].y);
}
if (hasElement(INPUT_ELEMENT_TYPE::TEXCOORD1)) {
vertexData.push_back(texCoords[1][i].x);
vertexData.push_back(texCoords[1][i].y);
}
if (hasElement(INPUT_ELEMENT_TYPE::TEXCOORD2)) {
vertexData.push_back(texCoords[2][i].x);
vertexData.push_back(texCoords[2][i].y);
}
if (hasElement(INPUT_ELEMENT_TYPE::TEXCOORD3)) {
vertexData.push_back(texCoords[3][i].x);
vertexData.push_back(texCoords[3][i].y);
}
if (hasElement(INPUT_ELEMENT_TYPE::COLOR0)) {
vertexData.push_back(colors[0][i].r);
vertexData.push_back(colors[0][i].g);
vertexData.push_back(colors[0][i].b);
vertexData.push_back(colors[0][i].a);
}
if (hasElement(INPUT_ELEMENT_TYPE::COLOR1)) {
vertexData.push_back(colors[1][i].r);
vertexData.push_back(colors[1][i].g);
vertexData.push_back(colors[1][i].b);
vertexData.push_back(colors[1][i].a);
}
if (hasElement(INPUT_ELEMENT_TYPE::COLOR2)) {
vertexData.push_back(colors[2][i].r);
vertexData.push_back(colors[2][i].g);
vertexData.push_back(colors[2][i].b);
vertexData.push_back(colors[2][i].a);
}
if (hasElement(INPUT_ELEMENT_TYPE::COLOR3)) {
vertexData.push_back(colors[3][i].r);
vertexData.push_back(colors[3][i].g);
vertexData.push_back(colors[3][i].b);
vertexData.push_back(colors[3][i].a);
}
}
}
| 29.15493
| 66
| 0.69372
|
YIMonge
|
19c0339d0f72e0573d1a052f3830133f48641eee
| 6,013
|
cpp
|
C++
|
DX12/00 - DX12 Starter/DX12Helper.cpp
|
vixorien/ggp-advanced-demos
|
af803c22f14d63dfcf5d329c7f5adba827f455b8
|
[
"MIT"
] | 1
|
2021-12-19T14:13:38.000Z
|
2021-12-19T14:13:38.000Z
|
DX12/00 - DX12 Starter/DX12Helper.cpp
|
vixorien/ggp-advanced-demos
|
af803c22f14d63dfcf5d329c7f5adba827f455b8
|
[
"MIT"
] | null | null | null |
DX12/00 - DX12 Starter/DX12Helper.cpp
|
vixorien/ggp-advanced-demos
|
af803c22f14d63dfcf5d329c7f5adba827f455b8
|
[
"MIT"
] | 1
|
2021-12-15T22:47:26.000Z
|
2021-12-15T22:47:26.000Z
|
#include "DX12Helper.h"
// Singleton requirement
DX12Helper* DX12Helper::instance;
// --------------------------------------------------------
// Destructor doesn't have much to do since we're using
// ComPtrs for all DX12 objects
// --------------------------------------------------------
DX12Helper::~DX12Helper() { }
// --------------------------------------------------------
// Sets up the helper with required DX12 objects
// --------------------------------------------------------
void DX12Helper::Initialize(
Microsoft::WRL::ComPtr<ID3D12Device> device,
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> commandList,
Microsoft::WRL::ComPtr<ID3D12CommandQueue> commandQueue,
Microsoft::WRL::ComPtr<ID3D12CommandAllocator> commandAllocator)
{
// Save objects
this->device = device;
this->commandList = commandList;
this->commandQueue = commandQueue;
this->commandAllocator = commandAllocator;
// Create the fence for basic synchronization
device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(waitFence.GetAddressOf()));
waitFenceEvent = CreateEventEx(0, 0, 0, EVENT_ALL_ACCESS);
waitFenceCounter = 0;
}
// --------------------------------------------------------
// Helper for creating a static buffer that will get
// data once and remain immutable
//
// dataStride - The size of one piece of data in the buffer (like a vertex)
// dataCount - How many pieces of data (like how many vertices)
// data - Pointer to the data itself
// --------------------------------------------------------
Microsoft::WRL::ComPtr<ID3D12Resource> DX12Helper::CreateStaticBuffer(unsigned int dataStride, unsigned int dataCount, void* data)
{
// The overall buffer we'll be creating
Microsoft::WRL::ComPtr<ID3D12Resource> buffer;
// Describes the final heap
D3D12_HEAP_PROPERTIES props = {};
props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
props.CreationNodeMask = 1;
props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
props.Type = D3D12_HEAP_TYPE_DEFAULT;
props.VisibleNodeMask = 1;
D3D12_RESOURCE_DESC desc = {};
desc.Alignment = 0;
desc.DepthOrArraySize = 1;
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Flags = D3D12_RESOURCE_FLAG_NONE;
desc.Format = DXGI_FORMAT_UNKNOWN;
desc.Height = 1; // Assuming this is a regular buffer, not a texture
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Width = dataStride * dataCount; // Size of the buffer
device->CreateCommittedResource(
&props,
D3D12_HEAP_FLAG_NONE,
&desc,
D3D12_RESOURCE_STATE_COPY_DEST, // Will eventually be "common", but we're copying to it first!
0,
IID_PPV_ARGS(buffer.GetAddressOf()));
// Now create an intermediate upload heap for copying initial data
D3D12_HEAP_PROPERTIES uploadProps = {};
uploadProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
uploadProps.CreationNodeMask = 1;
uploadProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
uploadProps.Type = D3D12_HEAP_TYPE_UPLOAD; // Can only ever be Generic_Read state
uploadProps.VisibleNodeMask = 1;
Microsoft::WRL::ComPtr<ID3D12Resource> uploadHeap;
device->CreateCommittedResource(
&uploadProps,
D3D12_HEAP_FLAG_NONE,
&desc,
D3D12_RESOURCE_STATE_GENERIC_READ,
0,
IID_PPV_ARGS(uploadHeap.GetAddressOf()));
// Do a straight map/memcpy/unmap
void* gpuAddress = 0;
uploadHeap->Map(0, 0, &gpuAddress);
memcpy(gpuAddress, data, dataStride * dataCount);
uploadHeap->Unmap(0, 0);
// Copy the whole buffer from uploadheap to vert buffer
commandList->CopyResource(buffer.Get(), uploadHeap.Get());
// Transition the buffer to generic read for the rest of the app lifetime (presumable)
D3D12_RESOURCE_BARRIER rb = {};
rb.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
rb.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
rb.Transition.pResource = buffer.Get();
rb.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
rb.Transition.StateAfter = D3D12_RESOURCE_STATE_GENERIC_READ;
rb.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
commandList->ResourceBarrier(1, &rb);
// Execute the command list and return the finished buffer
CloseExecuteAndResetCommandList();
return buffer;
}
// --------------------------------------------------------
// Closes the current command list and tells the GPU to
// start executing those commands. We also wait for
// the GPU to finish this work so we can reset the
// command allocator (which CANNOT be reset while the
// GPU is using its commands) and the command list itself.
// --------------------------------------------------------
void DX12Helper::CloseExecuteAndResetCommandList()
{
// Close the current list and execute it as our only list
commandList->Close();
ID3D12CommandList* lists[] = { commandList.Get() };
commandQueue->ExecuteCommandLists(1, lists);
// Always wait before reseting command allocator, as it should not
// be reset while the GPU is processing a command list
// See: https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/nf-d3d12-id3d12commandallocator-reset
WaitForGPU();
commandAllocator->Reset();
commandList->Reset(commandAllocator.Get(), 0);
}
// --------------------------------------------------------
// Makes our C++ code wait for the GPU to finish its
// current batch of work before moving on.
// --------------------------------------------------------
void DX12Helper::WaitForGPU()
{
// Update our ongoing fence value (a unique index for each "stop sign")
// and then place that value into the GPU's command queue
waitFenceCounter++;
commandQueue->Signal(waitFence.Get(), waitFenceCounter);
// Check to see if the most recently completed fence value
// is less than the one we just set.
if (waitFence->GetCompletedValue() < waitFenceCounter)
{
// Tell the fence to let us know when it's hit, and then
// sit an wait until that fence is hit.
waitFence->SetEventOnCompletion(waitFenceCounter, waitFenceEvent);
WaitForSingleObject(waitFenceEvent, INFINITE);
}
}
| 37.117284
| 130
| 0.693996
|
vixorien
|
19c5fac220898779df3b1836432fae310f62740d
| 665
|
cpp
|
C++
|
mio/mio_notify.cpp
|
cheneyfan/MTRpc
|
459684e44db866fb067311ae8dbfaf66f35bed15
|
[
"BSD-3-Clause"
] | 2
|
2021-05-12T14:13:21.000Z
|
2022-03-14T09:11:14.000Z
|
mio/mio_notify.cpp
|
cheneyfan/MTRpc
|
459684e44db866fb067311ae8dbfaf66f35bed15
|
[
"BSD-3-Clause"
] | null | null | null |
mio/mio_notify.cpp
|
cheneyfan/MTRpc
|
459684e44db866fb067311ae8dbfaf66f35bed15
|
[
"BSD-3-Clause"
] | null | null | null |
#include "tcpsocket.h"
#include "mio_notify.h"
#include "mio_poller.h"
#ifdef __x86_64__
#include <sys/eventfd.h>
#elif __i386__
#include <unistd.h>
#endif
namespace mtrpc{
EventNotify::EventNotify():
IOEvent(),
handerNotify(NULL)
{
#ifdef __x86_64__
_fd = eventfd(0, EFD_CLOEXEC|EFD_NONBLOCK);
#elif __i386__
int pipefd[2];
int result = pipe(pipefd);
_fd = pipefd[0];//for read
_fdw = pipefd[1];//for write
TcpSocket::setNoblock(_fd, true);
TcpSocket::setNoblock(_fdw, true);
#endif
}
EventNotify::~EventNotify(){
::close(_fd);
#ifdef __i386__
::close(_fdw);
#endif
delete handerNotify;
}
}
| 14.777778
| 47
| 0.654135
|
cheneyfan
|
19d463d0ae9635593abb5038ca58bb1a9908deea
| 2,750
|
cpp
|
C++
|
src/simpcl/src/filters/icp.cpp
|
senceryazici/point-cloud-filters
|
d5e4e599b493cc2af1517000c012d7936d46cf0f
|
[
"MIT"
] | 17
|
2020-01-08T14:35:05.000Z
|
2021-12-09T12:30:07.000Z
|
src/simpcl/src/filters/icp.cpp
|
senceryazici/point-cloud-filters
|
d5e4e599b493cc2af1517000c012d7936d46cf0f
|
[
"MIT"
] | 2
|
2020-01-31T16:31:48.000Z
|
2022-03-09T12:49:53.000Z
|
src/simpcl/src/filters/icp.cpp
|
senceryazici/point-cloud-filters
|
d5e4e599b493cc2af1517000c012d7936d46cf0f
|
[
"MIT"
] | 7
|
2020-01-08T21:28:58.000Z
|
2021-12-03T06:00:05.000Z
|
// Iterative Closest Point Algorithm
// Import dependencies
#include <ros/ros.h>
#include <string>
#include <iostream>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl_conversions/pcl_conversions.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/registration/icp.h>
// Definitions
ros::Publisher pub;
std::string subscribed_topic;
std::string published_topic;
double max_distance;
int max_iteration;
pcl::PCLPointCloud2* carrier = new pcl::PCLPointCloud2;
pcl::PCLPointCloud2ConstPtr cloudPtrCarry(carrier);
pcl::PointCloud<pcl::PointXYZ> *cloudXYZ_one = new pcl::PointCloud<pcl::PointXYZ>;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloudXYZPtr1(cloudXYZ_one);
pcl::PointCloud<pcl::PointXYZ> *cloudXYZ_two = new pcl::PointCloud<pcl::PointXYZ>;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloudXYZPtr2(cloudXYZ_two);
pcl::PointCloud<pcl::PointXYZ> *cloud_icp = new pcl::PointCloud<pcl::PointXYZ>;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloudPtrFinal(cloud_icp);
// callback
void cloud_cb(const sensor_msgs::PointCloud2ConstPtr& cloud_msg)
{
*cloudXYZPtr1 = *cloudXYZPtr2;
pcl_conversions::toPCL(*cloud_msg, *carrier);
pcl::fromPCLPointCloud2(*carrier, *cloudXYZPtr2);
}
// main
int main(int argc, char **argv)
{
// Initialize ROS
ros::init(argc, argv, "icp");
ros::NodeHandle n;
ros::Rate r(10);
// Load parameters from launch file
ros::NodeHandle nh_private("~");
nh_private.param<std::string>("subscribed_topic", subscribed_topic, "/point_cloud");
nh_private.param<std::string>("published_topic", published_topic, "cloud_icp");
nh_private.param<double>("max_distance", max_distance, 0.1);
nh_private.param<int>("max_iteration", max_iteration, 32);
// Create Subscriber and listen subscribed_topic
ros::Subscriber sub = n.subscribe<sensor_msgs::PointCloud2>(subscribed_topic, 1, cloud_cb);
// Create Publisher
pub = n.advertise<sensor_msgs::PointCloud2>(published_topic, 1);
while(ros::ok())
{
pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;
icp.setInputSource(cloudXYZPtr1);
icp.setInputTarget(cloudXYZPtr2);
icp.setMaxCorrespondenceDistance(max_distance); // Set the max correspondence distance to 10cm
icp.setMaximumIterations(max_iteration); // Set the maximum number of iterations (criterion 1)
icp.setTransformationEpsilon(1e-8); // Set the transformation epsilon (criterion 2)
icp.setEuclideanFitnessEpsilon(1); // Set the euclidean distance difference epsilon (criterion 3)
icp.align(*cloud_icp); // Perform the alignment
pub.publish(*cloud_icp); // Publish
r.sleep();
ros::spinOnce();
}
return 0;
}
| 34.810127
| 105
| 0.725455
|
senceryazici
|
19d6188ce0007ecc8f1942f00ecd592da9f3088e
| 231
|
cpp
|
C++
|
src/Main.cpp
|
Midiman/Midori
|
b97ba1d4dac7e6af9e9b0785747ab9a797caa5c9
|
[
"MIT"
] | null | null | null |
src/Main.cpp
|
Midiman/Midori
|
b97ba1d4dac7e6af9e9b0785747ab9a797caa5c9
|
[
"MIT"
] | null | null | null |
src/Main.cpp
|
Midiman/Midori
|
b97ba1d4dac7e6af9e9b0785747ab9a797caa5c9
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "Game.h"
int main(int argc, char* argv[])
{
Game game(argc, argv);
if( game.Init() ) {
game.Run();
game.End();
}
return 0;
}
| 11.55
| 32
| 0.606061
|
Midiman
|
19da471518b95cfe6d46127bc063ea58c06fdb94
| 1,412
|
cpp
|
C++
|
examples/src/ExamplesMain.cpp
|
eleventigerssc/LabSound
|
0438183d86836abcb16a69dcb8317e9d8cdb0c2d
|
[
"BSD-2-Clause"
] | null | null | null |
examples/src/ExamplesMain.cpp
|
eleventigerssc/LabSound
|
0438183d86836abcb16a69dcb8317e9d8cdb0c2d
|
[
"BSD-2-Clause"
] | null | null | null |
examples/src/ExamplesMain.cpp
|
eleventigerssc/LabSound
|
0438183d86836abcb16a69dcb8317e9d8cdb0c2d
|
[
"BSD-2-Clause"
] | 1
|
2019-05-03T12:46:14.000Z
|
2019-05-03T12:46:14.000Z
|
// License: BSD 2 Clause
// Copyright (C) 2015+, The LabSound Authors. All rights reserved.
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "ExampleBaseApp.h"
#include "Simple.h"
#include "ConnectDisconnect.h"
#include "OfflineRender.h"
#include "ConvolutionReverb.h"
#include "MicrophoneDalek.h"
#include "MicrophoneLoopback.h"
#include "MicrophoneReverb.h"
#include "Rhythm.h"
#include "RhythmAndFilters.h"
#include "PeakCompressor.h"
#include "StereoPanning.h"
#include "Spatialization.h"
#include "Tremolo.h"
#include "RedAlert.h"
#include "InfiniteFM.h"
#include "Groove.h"
#include "Validation.h"
SimpleApp g_simpleExample;
ConnectDisconnectApp g_connectApp;
OfflineRenderApp g_offlineRenderApp;
ConvolutionReverbApp g_convolutionReverbExample;
MicrophoneDalekApp g_microphoneDalekApp;
MicrophoneLoopbackApp g_microphoneLoopback;
MicrophoneReverbApp g_microphoneReverb;
PeakCompressorApp g_peakCompressor;
RedAlertApp g_redAlert;
RhythmApp g_rhythm;
RhythmAndFiltersApp g_rhythmAndFilters;
SpatializationApp g_spatialization;
TremoloApp g_tremolo;
ValidationApp g_validation;
InfiniteFMApp g_infiniteFM;
StereoPanningApp g_stereoPanning;
GrooveApp g_grooveExample;
// Windows users will need to set a valid working directory for the LabSoundExamples project, for instance $(ProjectDir)../../assets
int main (int argc, char *argv[])
{
g_simpleExample.PlayExample();
return 0;
}
| 27.153846
| 132
| 0.815864
|
eleventigerssc
|
19dae989b20eb2778219bc19d70718f774749780
| 16,385
|
cpp
|
C++
|
core/src/ceps_interpreter_nodeset.cpp
|
cepsdev/ceps
|
badd1ac7582034f9b4f000ee93828bd584cf858b
|
[
"MIT"
] | 3
|
2018-09-11T11:40:24.000Z
|
2021-07-02T10:24:36.000Z
|
core/src/ceps_interpreter_nodeset.cpp
|
cepsdev/ceps
|
badd1ac7582034f9b4f000ee93828bd584cf858b
|
[
"MIT"
] | null | null | null |
core/src/ceps_interpreter_nodeset.cpp
|
cepsdev/ceps
|
badd1ac7582034f9b4f000ee93828bd584cf858b
|
[
"MIT"
] | null | null | null |
/*
Copyright 2021 Tomas Prerovsky (cepsdev@hotmail.com).
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ceps_interpreter.hh"
#include "ceps_interpreter_nodeset.hh"
#include "cepsnodeset.hh"
#include "symtab.hh"
extern std::string default_text_representation(ceps::ast::Nodebase_ptr root_node);
static void flatten(ceps::ast::Nodebase_ptr root, std::vector<ceps::ast::Nodebase_ptr>& acc)
{
/*base cases*/
if (root == nullptr)
return;
if (root->kind() != ceps::ast::Ast_node_kind::binary_operator || op(as_binop_ref(root)) != '.' )
{
acc.push_back(root);
return;
}
/*Induction case*/
auto & op = as_binop_ref(root);
flatten(op.children()[0],acc);
flatten(op.children()[1],acc);
}
static void fetch_recursively_symbols(std::vector<ceps::ast::Nodebase_ptr> const & in,std::vector<ceps::ast::Nodebase_ptr> & out);
static void fetch_recursively_symbols(ceps::ast::Nodebase_ptr elem,std::vector<ceps::ast::Nodebase_ptr> & out){
if (elem->kind() == ceps::ast::Ast_node_kind::symbol) out.push_back(elem);
else if (elem->kind() == ceps::ast::Ast_node_kind::structdef){
fetch_recursively_symbols(ceps::ast::as_struct_ref(elem).children(),out);
} else if (elem->kind() == ceps::ast::Ast_node_kind::ifelse){
auto ifelse = ceps::ast::as_ifelse_ptr(elem);
ceps::ast::Nodebase_ptr cond = ifelse->children()[0];
fetch_recursively_symbols(cond,out);
if (ifelse->children().size() > 1) fetch_recursively_symbols(ifelse->children()[1],out);
if (ifelse->children().size() > 2) fetch_recursively_symbols(ifelse->children()[2],out);
} else if (elem->kind() == ceps::ast::Ast_node_kind::binary_operator){
auto & binop = ceps::ast::as_binop_ref(elem);
fetch_recursively_symbols(binop.left(),out);fetch_recursively_symbols(binop.right(),out);
}
}
static void fetch_recursively_symbols(std::vector<ceps::ast::Nodebase_ptr> const & in,std::vector<ceps::ast::Nodebase_ptr> & out){
for(auto e : in)
fetch_recursively_symbols(e,out);
}
extern std::string default_text_representation(std::vector<ceps::ast::Nodebase_ptr> nodes);
ceps::ast::Nodebase_ptr ceps::interpreter::evaluate_nodeset_expr_dot( ceps::ast::Nodebase_ptr lhs,
ceps::ast::Nodebase_ptr rhs ,
ceps::parser_env::Symboltable & sym_table,
ceps::interpreter::Environment& env,
ceps::ast::Nodebase_ptr,
ceps::interpreter::thoroughness_t thoroughness,
bool& symbols_found)
{
//INVARIANT: lhs is a nodeset
if (rhs == nullptr) return lhs;
//std::cout << "######################### RHS:" << *rhs << std::endl << std::endl;
//std::cout << "######################### LHS:" << *lhs << std::endl << std::endl;
std::vector<ceps::ast::Nodebase_ptr> acc;
flatten(rhs, acc);
ceps::ast::Nodeset result{as_ast_nodeset_ref(lhs).children()};
std::string last_identifier;
last_identifier = apply_idx_op_operand(as_ast_nodeset_ref(lhs));
//std::cout <<"----------------------------- "<< result << std::endl;
for (size_t i = 0; i < acc.size(); ++i)
{
std::string method_name;
std::vector<ceps::ast::Nodebase_ptr> args;
if (is_an_identifier(acc[i]))
{
auto id_name = name(as_id_ref(acc[i]));
//std::cout << id_name <<" '"<<last_identifier<<"' "<<"-----" << std::endl;
//std::cout << "before="<< result << std::endl;
if (last_identifier.length() == 0){
result = result[ceps::ast::all{id_name}];
}
else {
result = result[last_identifier][ceps::ast::all{id_name}];
}
last_identifier= id_name;
} else if (is_a_simple_funccall(acc[i],method_name,args)){
auto last_identifier_save = last_identifier;
last_identifier = "";
if (method_name == "select"){
if (args.size() != 1 || args[0]->kind() != ceps::ast::Ast_node_kind::string_literal)
throw ceps::interpreter::semantic_exception{nullptr,"'select' missing/wrong argument."};;
last_identifier = last_identifier_save;
auto id_name = value(as_string_ref(args[0]));
if (last_identifier.length() == 0){
result = result[ceps::ast::all{id_name}];
}
else {
result = result[last_identifier][ceps::ast::all{id_name}];
}
last_identifier= id_name;
} else if (method_name == "content"){
std::vector<ceps::ast::Nodebase_ptr> v;
for(auto pe : result.nodes())
{
if (pe->kind() != ceps::ast::Ast_node_kind::structdef) continue;
for(auto pes: as_struct_ref(pe).children()) v.push_back(pes);
}
result.nodes_ = v;
} else if (method_name == "strip"){
if(result.nodes().size() == 0) return nullptr;
return result.nodes()[0];
} else if (method_name == "size"){
return new ceps::ast::Int(result.nodes().size(),ceps::ast::all_zero_unit(),nullptr,nullptr,nullptr);
} else if (method_name == "first"){
if (result.nodes().size() == 0) result.nodes_.clear();
else{
std::vector<ceps::ast::Nodebase_ptr> v;
v.push_back(result.nodes()[0]);
result.nodes_ = v;
}
} else if (method_name == "contains") {
std::vector<ceps::ast::Nodebase_ptr> v;
for(auto e: args){
if (v.size()) break;
if (is<Ast_node_kind::string_literal>(e)){
auto s = value(as_string_ref(e));
for(auto n:result.nodes()){
if (!is<Ast_node_kind::string_literal>(n)) continue;
if ( s == value(as_string_ref(n)) ){
v = {mk_int_node(1)};
break;
}
}
}
}
if (v.size() == 0) v = {mk_int_node(0)};
result.nodes_ = v;
} else if (method_name == "contains_symbol"){
std::vector<std::string> symbol_kinds;
bool match_any_symbol = symbol_kinds.size() == 0;
auto match_symbol = [&](std::string symbol_kind) -> bool {
for(auto e : symbol_kinds)
if (e == symbol_kind) return true;
return false;
};
std::vector<ceps::ast::Nodebase_ptr> v;
for(auto e : result.nodes())
{
if (ceps::ast::is_leaf(e->kind())) continue;
auto & elements = nlf_ptr(e)->children();
for (auto f: elements){
if ( !is_a_symbol(f) ) continue;
if (match_any_symbol) {
v.push_back(e);break;
} else if (match_symbol( kind(as_symbol_ref(f) )) ){
v.push_back(e);break;
}
}
}
result.nodes_ = v;
} else if (method_name == "second"){
if (result.nodes().size() < 2) result.nodes_.clear();
else{
std::vector<ceps::ast::Nodebase_ptr> v;
v.push_back(result.nodes()[1]);
result.nodes_ = v;
}
} else if (method_name == "slice"){
std::vector<ceps::ast::Nodebase_ptr> t;
if(!args.size()){
// no op
} else if( 1 == args.size()){
auto range_start = is_int(args[0]);
if(!range_start.first) throw ceps::interpreter::semantic_exception{nullptr,"'"+method_name+"' expects integer as parameter."};
if ((size_t)range_start.second < result.nodes().size()){
std::copy(result.nodes().begin()+range_start.second, result.nodes().end(),std::back_inserter(t));
}
result.nodes_ = t;
} else {
auto range_start = is_int(args[0]);
auto range_end = is_int(args[1]);
if(!range_start.first) throw ceps::interpreter::semantic_exception{nullptr,"'"+method_name+"' expects integer as parameter."};
if(!range_end.first) throw ceps::interpreter::semantic_exception{nullptr,"'"+method_name+"' expects integer as parameter."};
if ((size_t)range_start.second < result.nodes().size()){
if (range_start.second <= range_end.second )
{
if((size_t)range_end.second < result.nodes().size())
std::copy(result.nodes().begin()+range_start.second, result.nodes().begin()+range_end.second,std::back_inserter(t));
else
std::copy(result.nodes().begin()+range_start.second, result.nodes().end(),std::back_inserter(t));
}
}
result.nodes_ = t;
}
} else if (method_name == "at" && args.size() == 1){
auto r = is_int(args[0]);
if(!r.first) throw ceps::interpreter::semantic_exception{nullptr,"'"+method_name+"' expects integer as parameter."};
if (result.nodes().size() <= (size_t) r.second) throw ceps::interpreter::semantic_exception{nullptr,"Nodeset method '"+method_name+"': index out of bounds."};
std::vector<ceps::ast::Nodebase_ptr> t;
t.push_back(result.nodes()[r.second]);
result.nodes_=t;
} else if (method_name == "fetch_recursively_symbols") {
std::vector<ceps::ast::Nodebase_ptr> v;
fetch_recursively_symbols(result.nodes_,v);
result.nodes_ = v;
} else if (method_name == "to_text") {
std::vector<ceps::ast::Nodebase_ptr> v;
for(auto p: result.nodes_)
v.push_back(ceps::ast::mk_string(default_text_representation(p)));
result.nodes_ = v;
} else if (method_name == "sort") {
last_identifier = last_identifier_save;
if (args.size () == 0)
std::sort(result.nodes_.begin(),
result.nodes_.end(),
[](ceps::ast::Nodebase_ptr a,ceps::ast::Nodebase_ptr b ) {
return default_text_representation(a) < default_text_representation(b);
});
else if (args.size() == 1 && args[0]->kind() == ceps::ast::Ast_node_kind::string_literal){
auto const & key = ceps::ast::value(ceps::ast::as_string_ref(args[0]));
std::sort(result.nodes_.begin(),
result.nodes_.end(),
[key](ceps::ast::Nodebase_ptr a_,ceps::ast::Nodebase_ptr b_ ) {
using namespace ceps::ast;
if (a_->kind() != ceps::ast::Ast_node_kind::structdef || b_->kind() != ceps::ast::Ast_node_kind::structdef)
throw ceps::interpreter::semantic_exception{nullptr,"'sort' type mismatch."};
auto ans = ceps::ast::Nodeset{as_struct_ref(a_).children()}[key];
auto bns = ceps::ast::Nodeset{as_struct_ref(b_).children()}[key];
/*std::cout << key << std::endl;
std::cout << *a_ << std::endl;
std::cout << *b_ << std::endl;*/
if (ans.nodes().size() == 0 || bns.nodes().size() == 0 )
throw ceps::interpreter::semantic_exception{nullptr,"'sort' illformed key."};
auto a = ans.nodes()[0];auto b = bns.nodes()[0];
if (a->kind() == ceps::ast::Ast_node_kind::int_literal && b->kind() == ceps::ast::Ast_node_kind::int_literal )
return value(as_int_ref(a)) < value(as_int_ref(b));
if (a->kind() == ceps::ast::Ast_node_kind::float_literal && b->kind() == ceps::ast::Ast_node_kind::int_literal )
return value(as_double_ref(a)) < (double)value(as_int_ref(b));
if (a->kind() == ceps::ast::Ast_node_kind::int_literal && b->kind() == ceps::ast::Ast_node_kind::float_literal )
return (double)value(as_int_ref(a)) < value(as_double_ref(a));
if (a->kind() == ceps::ast::Ast_node_kind::float_literal && b->kind() == ceps::ast::Ast_node_kind::float_literal )
return value(as_double_ref(a)) < value(as_double_ref(a));
return default_text_representation(ans.nodes()) < default_text_representation(bns.nodes());
});
}
} else if (method_name == "unique") {
last_identifier = last_identifier_save;
auto it = std::unique(result.nodes_.begin(), result.nodes_.end(),[](ceps::ast::Nodebase_ptr a,ceps::ast::Nodebase_ptr b ) {return default_text_representation(a) == default_text_representation(b); });
result.nodes_.erase(it,result.nodes_.end());
} else if (method_name == "map") {
if (args.size() != 2) throw ceps::interpreter::semantic_exception{nullptr,"'"+method_name+"' wrong number of arguments."};
ceps::ast::Nodebase_ptr r = nullptr;
ceps::ast::Nodebase_ptr a0 = args[0];
ceps::ast::Nodebase_ptr a1 = args[1];
if (a0->kind() == ceps::ast::Ast_node_kind::nodeset)
if (ceps::ast::as_ast_nodeset_ref(a0).children().size())
a0 = ceps::ast::as_ast_nodeset_ref(a0).children()[0];
if (a1->kind() == ceps::ast::Ast_node_kind::nodeset)
if (ceps::ast::as_ast_nodeset_ref(a1).children().size())
a1 = ceps::ast::as_ast_nodeset_ref(a1).children()[0];
for(size_t i = 0; i != result.nodes().size(); i+=2){
auto v = result.nodes()[i];
if (v->kind() != a0->kind()) continue;
if (v->kind() == ceps::ast::Ast_node_kind::identifier)
if (ceps::ast::name(ceps::ast::as_id_ref(v)) == ceps::ast::name(ceps::ast::as_id_ref(a0))){
r = result.nodes()[i+1];
break;
}
}
if (r == nullptr) r = a1;
result.nodes_ = std::vector<ceps::ast::Nodebase_ptr> {r};
} else if (method_name == "is_string") {
std::vector<ceps::ast::Nodebase_ptr> v;
for(auto pe : result.nodes())
{
if (pe->kind() == ceps::ast::Ast_node_kind::string_literal) v.push_back(pe);
}
result.nodes_ = v;
}else if (method_name == "is_struct") {
std::vector<ceps::ast::Nodebase_ptr> v;
for(auto pe : result.nodes())
{
if (pe->kind() == ceps::ast::Ast_node_kind::structdef) v.push_back(pe);
}
result.nodes_ = v;
}else if (method_name == "is_id") {
std::vector<ceps::ast::Nodebase_ptr> v;
for(auto pe : result.nodes())
if (pe->kind() == ceps::ast::Ast_node_kind::identifier) v.push_back(pe);
result.nodes_ = v;
} else if (method_name == "is_kind" && args.size() == 1 && args[0]->kind() == ceps::ast::Ast_node_kind::string_literal){
std::string kind_name = value(as_string_ref(args[0]));
std::vector<ceps::ast::Nodebase_ptr> v;
for(auto pe : result.nodes())
{
if (pe->kind() != ceps::ast::Ast_node_kind::symbol) continue;
if (kind_name == kind(as_symbol_ref(pe))) v.push_back(pe);
}
result.nodes_ = v;
} else if (method_name == "text_value_of_content_equals" && args.size() == 1 && args[0]->kind() == ceps::ast::Ast_node_kind::string_literal){
std::string cv = value(as_string_ref(args[0]));
std::vector<ceps::ast::Nodebase_ptr> v;
for(auto pe : result.nodes())
{
if (pe->kind() == ceps::ast::Ast_node_kind::string_literal) continue;
if (pe->kind() == ceps::ast::Ast_node_kind::int_literal) continue;
if (pe->kind() == ceps::ast::Ast_node_kind::float_literal) continue;
std::string c;
for(auto p: ceps::ast::nlf_ptr(pe)->children()){
c+=default_text_representation(p);
}
if (c!=cv) continue;
v.push_back(pe);
}
result.nodes_ = v;
}
else throw ceps::interpreter::semantic_exception{nullptr,"'"+method_name+"' Unknown method/Invalid parameters for nodeset called."};
}
else
{
auto r_int = is_int(acc[i]);
if(r_int.first)
{
result = result[ceps::ast::nth{r_int.second}];last_identifier = std::string{};
}else {
last_identifier = std::string{};
}
}
}//for
return create_ast_nodeset(last_identifier, result.nodes());
}//ceps::interpreter::evaluate_nodeset_expr_dot
| 43.577128
| 216
| 0.584925
|
cepsdev
|
19ddadeea0af90a56452a997d843c64a791f48c3
| 2,872
|
cpp
|
C++
|
sdk/physx/2.8.3/TrainingPrograms/Programs/Shared_Source/PerfRenderer.cpp
|
daher-alfawares/xr.desktop
|
218a7cff7a9be5865cf786d7cad31da6072f7348
|
[
"Apache-2.0"
] | 1
|
2018-09-20T10:01:30.000Z
|
2018-09-20T10:01:30.000Z
|
sdk/physx/2.8.3/TrainingPrograms/Programs/Shared_Source/PerfRenderer.cpp
|
daher-alfawares/xr.desktop
|
218a7cff7a9be5865cf786d7cad31da6072f7348
|
[
"Apache-2.0"
] | null | null | null |
sdk/physx/2.8.3/TrainingPrograms/Programs/Shared_Source/PerfRenderer.cpp
|
daher-alfawares/xr.desktop
|
218a7cff7a9be5865cf786d7cad31da6072f7348
|
[
"Apache-2.0"
] | null | null | null |
#include <stdio.h>
#include "PerfRenderer.h"
#include "GLFontRenderer.h"
#include "Timing.h"
PerfRenderer::PerfRenderer()
{
m_profilerOn = false;
lastTime=getCurrentTime();
for(int i=0;i<FPS_AVG_FRAMES;i++)
fpsTimes[i]=0.0f;
fpsIndex=0;
}
void PerfRenderer::toggleEnable()
{
m_profilerOn = !m_profilerOn;
}
void PerfRenderer::render(const NxProfileData* prof, int width, int height)
{
if(!m_profilerOn)
return;
GLFontRenderer::setScreenResolution(width, height);
GLFontRenderer::setColor(1.0f, 0.0f, 0.0f, 1.0f);
//position on screen:
float sx = 0.01f;
float sx2= 0.38f;
float col1 = -0.5f/2;
float col2 = -0.2f/5;
float sy = 0.95f;
float fontHeight = 0.018f;
char buf[256];
if(prof != NULL)
{
// display title
sprintf(buf,"Profiler (FPS: %g)",computeFPS());
GLFontRenderer::print(sx, sy, fontHeight, buf, false, 11, true);
//display headings
#ifdef NX_ENABLE_PROFILER_COUNTER
GLFontRenderer::print(sx2, sy, fontHeight, "count %parent %total %self hier self counter");
#else
GLFontRenderer::print(sx2, sy, fontHeight, "count %parent %total %self hier self");
#endif
sy -= 2*fontHeight;
//The total for the top level is the sum of all the top level zones
//(There could be multiple top level zones, eg threading enabled).
float total = 0.0f;
for(unsigned int i=0;i<prof->numZones;i++)
{
if(prof->profileZones[i].recursionLevel==0)
total+=prof->profileZones[i].hierTime;
}
for(unsigned int i=0;i<prof->numZones;i++)
{
NxProfileZone & z = prof->profileZones[i];
if(z.callCount) //skip empty zones
{
float precTotal = total ? z.hierTime * 100.0f / total : 0.0f;
float percSelf = z.hierTime ? z.selfTime * 100.0f / z.hierTime : 0.0f;
#ifdef NX_ENABLE_PROFILER_COUNTER
sprintf(buf, "%4d %4.0f %4.0f %4.0f %6d %6d %7d", z.callCount, z.percent, precTotal, percSelf, z.hierTime, z.selfTime,z.counter);
#else
sprintf(buf, "%4d %4.0f %4.0f %4.0f %10d %10d", z.callCount, z.percent, precTotal, percSelf, z.hierTime, z.selfTime);
#endif
GLFontRenderer::print(sx + 0.012f*z.recursionLevel, sy, fontHeight, z.name+2, false, 11, true);
GLFontRenderer::print(sx2, sy, fontHeight, buf, true, 11, true);
sy -= fontHeight;
}
}
}
else if(m_profilerOn)
{//we can still display frame rate even if NX was not compiled with profiling support.
// display title
sprintf(buf,"FPS: %g",computeFPS());
GLFontRenderer::print(sx, sy, fontHeight, buf, false, 11, true);
}
}
float PerfRenderer::computeFPS()
{
// Calculate frame rate
float currTime=getCurrentTime();
fpsTimes[fpsIndex]=currTime-lastTime;
fpsIndex=(fpsIndex+1)%FPS_AVG_FRAMES;
float avgTime=0.0f;
for(int i=0;i<FPS_AVG_FRAMES;i++)
avgTime+=fpsTimes[i];
avgTime/=FPS_AVG_FRAMES;
lastTime=currTime;
return 1.0f/avgTime;
}
| 24.758621
| 137
| 0.671309
|
daher-alfawares
|
19e4b638c109a9a1e175cf8bf5a368d11f3f0842
| 2,964
|
cpp
|
C++
|
src/components/src/core/health/HealthComponentTest.cpp
|
walter-strazak/chimarrao
|
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
|
[
"MIT"
] | 6
|
2021-04-20T10:32:29.000Z
|
2021-06-05T11:48:56.000Z
|
src/components/src/core/health/HealthComponentTest.cpp
|
walter-strazak/chimarrao
|
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
|
[
"MIT"
] | 1
|
2021-05-18T21:00:12.000Z
|
2021-06-02T07:59:03.000Z
|
src/components/src/core/health/HealthComponentTest.cpp
|
walter-strazak/chimarrao
|
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
|
[
"MIT"
] | 3
|
2020-09-12T08:54:04.000Z
|
2021-04-17T11:16:36.000Z
|
#include "HealthComponent.h"
#include "gtest/gtest.h"
#include "RendererPoolMock.h"
#include "ComponentOwner.h"
using namespace ::testing;
using namespace components::core;
class HealthComponentTest : public Test
{
public:
void deadAction(int& actionVariableInit)
{
actionVariableInit = deadValue;
}
bool deadActionPerformed(int actionVariableInit) const
{
return actionVariableInit == deadValue;
}
int actionVariable{0};
const int deadValue{42};
const utils::Vector2f position{0.0, 11.0};
const unsigned int initialHealthPoints{100};
const unsigned int pointsToAdd1{20};
const unsigned int pointsToAdd2{50};
std::shared_ptr<NiceMock<graphics::RendererPoolMock>> rendererPool =
std::make_shared<NiceMock<graphics::RendererPoolMock>>();
std::shared_ptr<components::core::SharedContext> sharedContext =
std::make_shared<components::core::SharedContext>(rendererPool);
ComponentOwner componentOwner{position, "healthComponentTest", sharedContext};
HealthComponent healthComponent{&componentOwner, initialHealthPoints,
[this] { deadAction(actionVariable); }};
};
TEST_F(HealthComponentTest, initialHealthPoints_shouldMatchWithGivenOne)
{
ASSERT_EQ(healthComponent.getCurrentHealth(), initialHealthPoints);
ASSERT_EQ(healthComponent.getMaximumHealth(), initialHealthPoints);
ASSERT_FALSE(healthComponent.isDead());
ASSERT_FALSE(deadActionPerformed(actionVariable));
}
TEST_F(HealthComponentTest,
addedPointsWithCurrentHealthAreLowerThanMaximumHealth_shouldAddPointsToCurrentHealth)
{
healthComponent.loseHealthPoints(50);
healthComponent.gainHealthPoints(pointsToAdd1);
ASSERT_EQ(healthComponent.getCurrentHealth(), 70);
ASSERT_FALSE(deadActionPerformed(actionVariable));
}
TEST_F(HealthComponentTest,
addedPointsWithCurrentHealthAreHigherThanMaximumHealth_shouldSetCurrentPointsToMaximum)
{
healthComponent.loseHealthPoints(20);
healthComponent.gainHealthPoints(pointsToAdd2);
ASSERT_EQ(healthComponent.getCurrentHealth(), initialHealthPoints);
ASSERT_FALSE(deadActionPerformed(actionVariable));
}
TEST_F(HealthComponentTest, lostPointsWithCurrentHealthAreLowerThanZero_shouldSetCurrentHealthPointsToZero)
{
healthComponent.loseHealthPoints(120);
ASSERT_EQ(healthComponent.getCurrentHealth(), 0);
ASSERT_TRUE(deadActionPerformed(actionVariable));
}
TEST_F(HealthComponentTest,
lostPointsWithCurrentHealthAreHigherThanZero_shouldSubtractPointsFromCurrentHealth)
{
healthComponent.loseHealthPoints(20);
ASSERT_EQ(healthComponent.getCurrentHealth(), 80);
ASSERT_FALSE(deadActionPerformed(actionVariable));
}
TEST_F(HealthComponentTest, givenCurrentHealthEqualZero_shouldReturnDead)
{
healthComponent.loseHealthPoints(100);
ASSERT_TRUE(healthComponent.isDead());
ASSERT_TRUE(deadActionPerformed(actionVariable));
}
| 31.531915
| 107
| 0.779015
|
walter-strazak
|
19e5a38ea5995ee39c3d36d81b9e0d95e73ab255
| 10,746
|
cpp
|
C++
|
inference-engine/tests/unit/vpu/middleend_tests/edges_tests/data_to_shape_edge.cpp
|
evgenytalanin-intel/openvino
|
c3aa866a3318fe9fa8c7ebd3bd333b075bb1cc36
|
[
"Apache-2.0"
] | null | null | null |
inference-engine/tests/unit/vpu/middleend_tests/edges_tests/data_to_shape_edge.cpp
|
evgenytalanin-intel/openvino
|
c3aa866a3318fe9fa8c7ebd3bd333b075bb1cc36
|
[
"Apache-2.0"
] | 1
|
2021-09-09T08:43:57.000Z
|
2021-09-10T12:39:16.000Z
|
inference-engine/tests/unit/vpu/middleend_tests/edges_tests/data_to_shape_edge.cpp
|
evgenytalanin-intel/openvino
|
c3aa866a3318fe9fa8c7ebd3bd333b075bb1cc36
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "graph_transformer_tests.hpp"
namespace vpu {
namespace ie = InferenceEngine;
class DataToShapeEdgeProcessingTests : public GraphTransformerTest {
protected:
void SetUp() override {
ASSERT_NO_FATAL_FAILURE(GraphTransformerTest::SetUp());
ASSERT_NO_FATAL_FAILURE(InitCompileEnv());
_middleEnd = passManager->buildMiddleEnd();
_testModel = CreateTestModel();
}
void setupNetWithNonProcessingShape() {
//
// -> [Shape]
// [Input] -> (ShapeProd) |
// -> [Data] -> (Stage) -> [Output]
//
const auto& dataDesc = DataDesc({800});
const auto& shapeDesc = DataDesc({1});
_testModel.createInputs({dataDesc});
_testModel.createOutputs({dataDesc});
auto shapeParent = _testModel.addStage({InputInfo::fromNetwork()}, {OutputInfo::intermediate(dataDesc),
OutputInfo::intermediate(shapeDesc)});
_testModel.addStage({InputInfo::fromPrevStage(0)}, {OutputInfo::fromNetwork()});
auto model = _testModel.getBaseModel();
model->connectDataWithShape(shapeParent->output(1), shapeParent->output(0));
}
void setupNetWithShapeBeingProcessedOnce() {
//
// -> [Shape] -> (ShapeProc) -> [Shape]
// [Input] -> (ShapeProd) | |
// -> [Data] -> (DataProc) -> [Data] -> (Stage) -> [Output]
//
const auto& dataDesc = DataDesc({800});
const auto& shapeDesc = DataDesc({1});
_testModel.createInputs({dataDesc});
_testModel.createOutputs({dataDesc});
auto model = _testModel.getBaseModel();
auto dataAndShapeParent = _testModel.addStage({InputInfo::fromNetwork()}, {OutputInfo::intermediate(dataDesc),
OutputInfo::intermediate(shapeDesc)});
model->connectDataWithShape(dataAndShapeParent->output(1), dataAndShapeParent->output(0));
auto dataChild = _testModel.addStage({InputInfo::fromPrevStage(0).output(0)}, {OutputInfo::intermediate(dataDesc)});
auto shapeChild = _testModel.addStage({InputInfo::fromPrevStage(0).output(1)}, {OutputInfo::intermediate(shapeDesc)});
_testModel.addStage({InputInfo::fromPrevStage(1)}, {OutputInfo::fromNetwork()});
model->connectDataWithShape(shapeChild->output(0), dataChild->output(0));
}
void setupNetWithShapeBeingProcessedTwice() {
//
// -> [Shape] -> (ShapeProc) -> [Shape] -> (ShapeProc) -> [Shape]
// [Input] -> (ShapeProd) | | |
// -> [Data] -> (DataProc) -> [Data] -> (DataProc) -> [Data] -> (Stage) -> [Output]
//
const auto& dataDesc = DataDesc({800});
const auto& shapeDesc = DataDesc({1});
_testModel.createInputs({dataDesc});
_testModel.createOutputs({dataDesc});
auto model = _testModel.getBaseModel();
auto dataAndShapeParent = _testModel.addStage({InputInfo::fromNetwork()}, {OutputInfo::intermediate(dataDesc),
OutputInfo::intermediate(shapeDesc)});
model->connectDataWithShape(dataAndShapeParent->output(1), dataAndShapeParent->output(0));
auto dataChild = _testModel.addStage({InputInfo::fromPrevStage(0).output(0)}, {OutputInfo::intermediate(dataDesc)});
auto shapeChild = _testModel.addStage({InputInfo::fromPrevStage(0).output(1)}, {OutputInfo::intermediate(shapeDesc)});
model->connectDataWithShape(shapeChild->output(0), dataChild->output(0));
dataChild = _testModel.addStage({InputInfo::fromPrevStage(1).output(0)}, {OutputInfo::intermediate(dataDesc)});
shapeChild = _testModel.addStage({InputInfo::fromPrevStage(2).output(0)}, {OutputInfo::intermediate(shapeDesc)});
model->connectDataWithShape(shapeChild->output(0), dataChild->output(0));
_testModel.addStage({InputInfo::fromPrevStage(3)}, {OutputInfo::fromNetwork()});
}
protected:
TestModel _testModel;
PassSet::Ptr _middleEnd = nullptr;
};
TEST_F(DataToShapeEdgeProcessingTests, ShapeDataWithoutConsumerDoesntThrow) {
setupNetWithNonProcessingShape();
ASSERT_NO_THROW(_middleEnd->run(_testModel.getBaseModel()));
}
TEST_F(DataToShapeEdgeProcessingTests, DataToShapeEdgeSharesMemory) {
setupNetWithNonProcessingShape();
const auto& model = _testModel.getBaseModel();
ASSERT_NO_THROW(_middleEnd->run(model));
Stage shapeProducer = nullptr;
for (const auto& stage : model->getStages()) {
// Find shape produced stage
if (stage->numOutputs() == 2) {
shapeProducer = stage;
}
}
ASSERT_NE(shapeProducer, nullptr);
const auto& data = shapeProducer->output(0);
const auto& shape = shapeProducer->output(1);
const auto& shapeDataLocation = shape->dataLocation();
const auto& dataShapeLocation = data->shapeLocation();
ASSERT_EQ(shapeDataLocation.location, dataShapeLocation.dimsLocation);
ASSERT_EQ(shapeDataLocation.offset, dataShapeLocation.dimsOffset);
}
TEST_F(DataToShapeEdgeProcessingTests, ShapeProcessingOnceDoesntThrow) {
setupNetWithShapeBeingProcessedOnce();
ASSERT_NO_THROW(_middleEnd->run(_testModel.getBaseModel()));
}
TEST_F(DataToShapeEdgeProcessingTests, ShapeProcessingOnceSharesMemory) {
setupNetWithShapeBeingProcessedOnce();
const auto& model = _testModel.getBaseModel();
ASSERT_NO_THROW(_middleEnd->run(model));
Stage shapeProducer = nullptr;
for (const auto& stage : model->getStages()) {
// Find shape produced stage
if (stage->numOutputs() == 2) {
shapeProducer = stage;
}
}
ASSERT_NE(shapeProducer, nullptr);
const auto& data = shapeProducer->output(0);
const auto& shape = shapeProducer->output(1);
const auto& shapeDataLocation = shape->dataLocation();
const auto& dataShapeLocation = data->shapeLocation();
ASSERT_EQ(shapeDataLocation.location, dataShapeLocation.dimsLocation);
ASSERT_EQ(shapeDataLocation.offset, dataShapeLocation.dimsOffset);
const auto& processedData = data->singleConsumer()->output(0);
const auto& processedShape = shape->singleConsumer()->output(0);
const auto& processedShapeDataLocation = processedShape->dataLocation();
const auto& processedDataShapeLocation = processedData->shapeLocation();
ASSERT_EQ(processedShapeDataLocation.location, processedDataShapeLocation.dimsLocation);
ASSERT_EQ(processedShapeDataLocation.offset, processedDataShapeLocation.dimsOffset);
}
TEST_F(DataToShapeEdgeProcessingTests, ShapeProcessingOnceHasCorrectExecutionOrder) {
setupNetWithShapeBeingProcessedOnce();
const auto& model = _testModel.getBaseModel();
ASSERT_NO_THROW(_middleEnd->run(model));
Stage shapeProducer = nullptr;
for (const auto& stage : model->getStages()) {
// Find shape produced stage
if (stage->numOutputs() == 2) {
shapeProducer = stage;
}
}
ASSERT_NE(shapeProducer, nullptr);
const auto dataProcessor = shapeProducer->output(0)->singleConsumer();
const auto shapeProcessor = shapeProducer->output(1)->singleConsumer();
ASSERT_TRUE(checkExecutionOrder(model, {shapeProcessor->id(), dataProcessor->id()}));
}
TEST_F(DataToShapeEdgeProcessingTests, ShapeProcessingTwiceDoesntThrow) {
setupNetWithShapeBeingProcessedTwice();
ASSERT_NO_THROW(_middleEnd->run(_testModel.getBaseModel()));
}
TEST_F(DataToShapeEdgeProcessingTests, ShapeProcessingTwiceSharesMemory) {
setupNetWithShapeBeingProcessedTwice();
const auto& model = _testModel.getBaseModel();
ASSERT_NO_THROW(_middleEnd->run(model));
Stage shapeProducer = nullptr;
for (const auto& stage : model->getStages()) {
// Find shape produced stage
if (stage->numOutputs() == 2) {
shapeProducer = stage;
}
}
ASSERT_NE(shapeProducer, nullptr);
const auto& data = shapeProducer->output(0);
const auto& shape = shapeProducer->output(1);
const auto& shapeDataLocation = shape->dataLocation();
const auto& dataShapeLocation = data->shapeLocation();
ASSERT_EQ(shapeDataLocation.location, dataShapeLocation.dimsLocation);
ASSERT_EQ(shapeDataLocation.offset, dataShapeLocation.dimsOffset);
const auto& dataProcessedOnce = data->singleConsumer()->output(0);
const auto& shapeProcessedOnce = shape->singleConsumer()->output(0);
auto processedShapeDataLocation = shapeProcessedOnce->dataLocation();
auto processedDataShapeLocation = dataProcessedOnce->shapeLocation();
ASSERT_EQ(processedShapeDataLocation.location, processedDataShapeLocation.dimsLocation);
ASSERT_EQ(processedShapeDataLocation.offset, processedDataShapeLocation.dimsOffset);
const auto dataProcessedTwice = dataProcessedOnce->singleConsumer()->output(0);
const auto shapeProcessedTwice = shapeProcessedOnce->singleConsumer()->output(0);
processedShapeDataLocation = shapeProcessedTwice->dataLocation();
processedDataShapeLocation = dataProcessedTwice->shapeLocation();
ASSERT_EQ(processedShapeDataLocation.location, processedDataShapeLocation.dimsLocation);
ASSERT_EQ(processedShapeDataLocation.offset, processedDataShapeLocation.dimsOffset);
}
TEST_F(DataToShapeEdgeProcessingTests, ShapeProcessingTwiceHasCorrectExecutionOrder) {
setupNetWithShapeBeingProcessedTwice();
const auto& model = _testModel.getBaseModel();
ASSERT_NO_THROW(_middleEnd->run(model));
Stage shapeProducer = nullptr;
for (const auto& stage : model->getStages()) {
// Find shape produced stage
if (stage->numOutputs() == 2) {
shapeProducer = stage;
}
}
ASSERT_NE(shapeProducer, nullptr);
const auto dataFirstProcessor = shapeProducer->output(0)->singleConsumer();
const auto shapeFirstProcessor = shapeProducer->output(1)->singleConsumer();
ASSERT_TRUE(checkExecutionOrder(model, {shapeFirstProcessor->id(), dataFirstProcessor->id()}));
const auto dataSecondProcessor = dataFirstProcessor->output(0)->singleConsumer();
const auto shapeSecondProcessor = shapeFirstProcessor->output(0)->singleConsumer();
ASSERT_TRUE(checkExecutionOrder(model, {shapeSecondProcessor->id(), dataSecondProcessor->id()}));
}
} // namespace vpu
| 38.106383
| 126
| 0.675321
|
evgenytalanin-intel
|
19ea980a077156abfb6275e44e77ac8b96d7b983
| 2,600
|
cpp
|
C++
|
source/QtCore/QIODeviceSlots.cpp
|
kenny1818/qt4xhb
|
f62f40d8b17acb93761014317b52da9f919707d0
|
[
"MIT"
] | 1
|
2021-03-07T10:44:03.000Z
|
2021-03-07T10:44:03.000Z
|
source/QtCore/QIODeviceSlots.cpp
|
kenny1818/qt4xhb
|
f62f40d8b17acb93761014317b52da9f919707d0
|
[
"MIT"
] | null | null | null |
source/QtCore/QIODeviceSlots.cpp
|
kenny1818/qt4xhb
|
f62f40d8b17acb93761014317b52da9f919707d0
|
[
"MIT"
] | 2
|
2020-07-19T03:28:08.000Z
|
2021-03-05T18:07:20.000Z
|
/*
Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4
Copyright (C) 2021 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QIODeviceSlots.h"
QIODeviceSlots::QIODeviceSlots( QObject * parent ) : QObject( parent )
{
}
QIODeviceSlots::~QIODeviceSlots()
{
}
void QIODeviceSlots::aboutToClose()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "aboutToClose()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QIODEVICE" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QIODeviceSlots::bytesWritten( qint64 bytes )
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "bytesWritten(qint64)" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QIODEVICE" );
PHB_ITEM pBytes = hb_itemPutNLL( NULL, bytes );
hb_vmEvalBlockV( cb, 2, pSender, pBytes );
hb_itemRelease( pSender );
hb_itemRelease( pBytes );
}
}
void QIODeviceSlots::readChannelFinished()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "readChannelFinished()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QIODEVICE" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QIODeviceSlots::readyRead()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "readyRead()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QIODEVICE" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QIODeviceSlots_connect_signal( const QString & signal, const QString & slot )
{
QIODevice * obj = qobject_cast< QIODevice * >( Qt4xHb::getQObjectPointerFromSelfItem() );
if( obj )
{
QIODeviceSlots * s = QCoreApplication::instance()->findChild<QIODeviceSlots *>();
if( s == NULL )
{
s = new QIODeviceSlots();
s->moveToThread( QCoreApplication::instance()->thread() );
s->setParent( QCoreApplication::instance() );
}
hb_retl( Qt4xHb::Signals_connection_disconnection( s, signal, slot ) );
}
else
{
hb_retl( false );
}
}
| 23.423423
| 92
| 0.647308
|
kenny1818
|
19f337fba6a62dab6ab5658b96d6cfe1f1120842
| 1,939
|
cpp
|
C++
|
azureeyemodule/app/streaming/resolution.cpp
|
hogaku/azure-percept-advanced-development
|
90177b9f1ec96dee1e7c436af5471007c4092655
|
[
"MIT"
] | 52
|
2021-03-02T14:28:37.000Z
|
2022-02-07T20:27:52.000Z
|
azureeyemodule/app/streaming/resolution.cpp
|
hogaku/azure-percept-advanced-development
|
90177b9f1ec96dee1e7c436af5471007c4092655
|
[
"MIT"
] | 29
|
2021-03-03T09:36:33.000Z
|
2022-03-12T00:59:10.000Z
|
azureeyemodule/app/streaming/resolution.cpp
|
hogaku/azure-percept-advanced-development
|
90177b9f1ec96dee1e7c436af5471007c4092655
|
[
"MIT"
] | 30
|
2021-03-02T14:09:14.000Z
|
2022-03-11T05:58:54.000Z
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// Local includes
#include "resolution.hpp"
#include "../util/helper.hpp"
// Standard library includes
#include <assert.h>
#include <string>
namespace rtsp {
std::string resolution_to_string(const Resolution &resolution)
{
switch (resolution)
{
case Resolution::NATIVE:
return "native";
case Resolution::HD1080P:
return "1080p";
case Resolution::HD720P:
return "720p";
default:
util::log_error("Unrecognized resolution type when trying to convert to string.");
assert(false);
return "UNKNOWN";
}
}
bool is_valid_resolution(const std::string &resolution)
{
if (resolution == "native")
{
return true;
}
else if (resolution == "1080p")
{
return true;
}
else if (resolution == "720p")
{
return true;
}
else
{
return false;
}
}
Resolution resolution_string_to_enum(const std::string &resolution)
{
if (resolution == "native")
{
return Resolution::NATIVE;
}
else if (resolution == "1080p")
{
return Resolution::HD1080P;
}
else if (resolution == "720p")
{
return Resolution::HD720P;
}
else
{
throw std::invalid_argument("Invalid resolution string.");
}
}
std::tuple<int, int> get_height_and_width(const Resolution &resolution)
{
switch (resolution)
{
case Resolution::NATIVE:
return {DEFAULT_HEIGHT, DEFAULT_WIDTH};
case Resolution::HD1080P:
return {1080, 1920};
case Resolution::HD720P:
return {720, 1280};
default:
util::log_error("Invalid resolution when trying to get height and width.");
assert(false);
return {DEFAULT_HEIGHT, DEFAULT_WIDTH};
}
}
} // namespace rtsp
| 22.034091
| 94
| 0.587416
|
hogaku
|
19f5c1a2ef2578a7e5bcbbf9cf64dae46919e3cc
| 2,746
|
cpp
|
C++
|
Projects/Editor/Source/GUI/Controls/CCollapsibleButton.cpp
|
tsukoyumi/skylicht-engine
|
3b88d9718e87e552152633ef60e3f889869b71de
|
[
"MIT"
] | 310
|
2019-11-25T04:14:11.000Z
|
2022-03-31T23:39:19.000Z
|
Projects/Editor/Source/GUI/Controls/CCollapsibleButton.cpp
|
tsukoyumi/skylicht-engine
|
3b88d9718e87e552152633ef60e3f889869b71de
|
[
"MIT"
] | 79
|
2019-11-17T07:51:02.000Z
|
2022-03-22T08:49:41.000Z
|
Projects/Editor/Source/GUI/Controls/CCollapsibleButton.cpp
|
tsukoyumi/skylicht-engine
|
3b88d9718e87e552152633ef60e3f889869b71de
|
[
"MIT"
] | 24
|
2020-05-10T09:37:55.000Z
|
2022-03-05T13:19:31.000Z
|
/*
!@
MIT License
Copyright (c) 2020 Skylicht Technology CO., LTD
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.
This file is part of the "Skylicht Engine".
https://github.com/skylicht-lab/skylicht-engine
!#
*/
#include "pch.h"
#include "CCollapsibleButton.h"
#include "GUI/Theme/CThemeConfig.h"
namespace Skylicht
{
namespace Editor
{
namespace GUI
{
CCollapsibleButton::CCollapsibleButton(CBase* parent) :
CButton(parent)
{
setPadding(SPadding(0.0f, 0.0f, -8.0f, 0.0f));
setIcon(GUI::ESystemIcon::SmallTriangleRight);
showIcon(true);
setIsToggle(true);
setColor(CThemeConfig::CollapsibleColor);
setHoverColor(CThemeConfig::ButtonColor);
}
CCollapsibleButton::~CCollapsibleButton()
{
}
void CCollapsibleButton::renderUnder()
{
SGUIColor c = m_color;
bool pressed = m_pressed;
bool hover = isHovered();
bool disable = isDisabled();
if (disable)
{
m_label->setColor(CThemeConfig::ButtonTextDisableColor);
m_icon->setColor(CThemeConfig::ButtonTextDisableColor);
}
else
{
m_label->setColor(m_labelColor);
m_icon->setColor(m_iconColor);
}
if (hover && !disable)
{
if (pressed == true)
c = m_pressColor;
else
c = m_hoverColor;
}
if (!disable && (m_drawBackground || hover))
CRenderer::getRenderer()->drawFillRect(getRenderBounds(), c);
}
void CCollapsibleButton::onMouseClickLeft(float x, float y, bool down)
{
if (down == false)
{
m_toggleStatus = !m_toggleStatus;
if (m_toggleStatus == true)
setIcon(GUI::ESystemIcon::SmallTriangleDown);
else
setIcon(GUI::ESystemIcon::SmallTriangleRight);
}
CButton::onMouseClickLeft(x, y, down);
}
}
}
}
| 27.737374
| 141
| 0.710488
|
tsukoyumi
|
19f682e19646697e513452148ece0f9d501d073d
| 2,096
|
hh
|
C++
|
tamer/channel.hh
|
kohler/tamer
|
0953029ad7fc5c3fd58869227976c359674c670f
|
[
"BSD-3-Clause"
] | 23
|
2015-04-11T06:41:04.000Z
|
2021-11-06T21:34:14.000Z
|
tamer/channel.hh
|
kohler/tamer
|
0953029ad7fc5c3fd58869227976c359674c670f
|
[
"BSD-3-Clause"
] | 2
|
2015-04-15T07:00:31.000Z
|
2016-08-16T13:46:22.000Z
|
tamer/channel.hh
|
kohler/tamer
|
0953029ad7fc5c3fd58869227976c359674c670f
|
[
"BSD-3-Clause"
] | 5
|
2015-08-18T19:24:07.000Z
|
2021-04-18T04:35:35.000Z
|
// -*- mode: c++ -*-
#ifndef TAMER_CHANNEL_HH
#define TAMER_CHANNEL_HH 1
#include <deque>
#include <tamer/event.hh>
namespace tamer {
template <typename T>
class channel {
public:
typedef typename std::deque<T>::size_type size_type;
inline channel();
inline size_type size() const;
inline bool empty() const;
inline size_type wait_size() const;
inline bool wait_empty() const;
inline void push_front(T x);
inline void push_back(T x);
inline void pop_front(tamer::event<T> e);
inline void pop_back(tamer::event<T> e);
private:
std::deque<T> q_;
std::deque<tamer::event<T> > waitq_;
};
template <typename T>
inline channel<T>::channel() {
}
template <typename T>
inline typename channel<T>::size_type channel<T>::size() const {
return q_.size();
}
template <typename T>
inline bool channel<T>::empty() const {
return q_.empty();
}
template <typename T>
inline typename channel<T>::size_type channel<T>::wait_size() const {
return waitq_.size();
}
template <typename T>
inline bool channel<T>::wait_empty() const {
return waitq_.empty();
}
template <typename T>
inline void channel<T>::push_front(T x) {
while (!waitq_.empty() && !waitq_.front())
waitq_.pop_front();
if (!waitq_.empty()) {
waitq_.front()(TAMER_MOVE(x));
waitq_.pop_front();
} else
q_.push_front(TAMER_MOVE(x));
}
template <typename T>
inline void channel<T>::push_back(T x) {
while (!waitq_.empty() && !waitq_.front())
waitq_.pop_front();
if (!waitq_.empty()) {
waitq_.front()(TAMER_MOVE(x));
waitq_.pop_front();
} else
q_.push_back(TAMER_MOVE(x));
}
template <typename T>
inline void channel<T>::pop_front(tamer::event<T> e) {
if (!q_.empty()) {
e(q_.front());
q_.pop_front();
} else
waitq_.push_back(TAMER_MOVE(e));
}
template <typename T>
inline void channel<T>::pop_back(tamer::event<T> e) {
if (!q_.empty()) {
e(q_.back());
q_.pop_back();
} else
waitq_.push_back(TAMER_MOVE(e));
}
}
#endif
| 21.387755
| 69
| 0.627863
|
kohler
|
19f69715dae02406f503fc38cacd9936a9baa8bf
| 5,132
|
hpp
|
C++
|
components/scream/src/share/field/field_repository.hpp
|
AaronDonahue/scream
|
a1e1cc67ac6db87ce6525315a5548d0e7b0f5e97
|
[
"zlib-acknowledgement",
"FTL",
"RSA-MD"
] | null | null | null |
components/scream/src/share/field/field_repository.hpp
|
AaronDonahue/scream
|
a1e1cc67ac6db87ce6525315a5548d0e7b0f5e97
|
[
"zlib-acknowledgement",
"FTL",
"RSA-MD"
] | 3
|
2019-04-25T18:18:33.000Z
|
2019-05-07T16:43:36.000Z
|
components/scream/src/share/field/field_repository.hpp
|
AaronDonahue/scream
|
a1e1cc67ac6db87ce6525315a5548d0e7b0f5e97
|
[
"zlib-acknowledgement",
"FTL",
"RSA-MD"
] | null | null | null |
#ifndef SCREAM_FIELD_REPOSITORY_HPP
#define SCREAM_FIELD_REPOSITORY_HPP
#include "share/scream_types.hpp"
#include "share/scream_assert.hpp"
#include "share/field/field.hpp"
#include <map>
namespace scream
{
/*
* A database for all the persistent fields needed in an atm time step
* We template a field repository over the field value type and over
* the memory space of the views.
*/
template<typename ScalarType, typename Device>
class FieldRepository {
public:
// Public types
using device_type = Device;
using scalar_type = ScalarType;
using field_type = Field<scalar_type,device_type>;
using header_type = typename field_type::header_type;
using identifier_type = typename header_type::identifier_type;
using map_type = std::map<identifier_type,field_type>;
using repo_type = std::map<std::string,map_type>;
// Constructor(s)
FieldRepository ();
// No copies, cause the internal database is not a shared_ptr.
// NOTE: you can change this if you find that copies are needed/useful.
FieldRepository (const FieldRepository&) = delete;
FieldRepository& operator= (const FieldRepository&) = delete;
// Change the state of the database
void registration_begins ();
void registration_ends ();
void clean_up ();
// Deduce the pack size from the scalar type (which must be of type Pack<ScalarType,N>, for some int N>0, or ScalarType)
template<typename RequestedValueType = scalar_type>
void register_field (const identifier_type& identifier);
// Methods to query the database
int size () const { return m_fields.size(); }
bool has_field (const identifier_type& identifier) const;
field_type get_field (const identifier_type& identifier) const;
RepoState repository_state () const { return m_state; }
typename repo_type::const_iterator begin() const { return m_fields.begin(); }
typename repo_type::const_iterator end() const { return m_fields.begin(); }
protected:
// The state of the repository
RepoState m_state;
// The actual repo.
repo_type m_fields;
};
// ============================== IMPLEMENTATION ============================= //
template<typename ScalarType, typename Device>
FieldRepository<ScalarType,Device>::FieldRepository ()
: m_state (RepoState::Clean)
{
// Nothing to be done here
}
template<typename ScalarType, typename Device>
template<typename RequestedValueType>
void FieldRepository<ScalarType,Device>::register_field (const identifier_type& id) {
// Check that ScalarOrPackType is indeed ScalarType or Pack<ScalarType,N>, for some N>0.
static_assert(std::is_same<ScalarType,RequestedValueType>::value ||
std::is_same<ScalarType,typename util::ScalarProperties<RequestedValueType>::scalar_type>::value,
"Error! The template argument 'RequestedValueType' of this function must either match "
"the template argument 'ScalarType' of this class or be a Pack type based on ScalarType.\n");
// Sanity checks
error::runtime_check(m_state==RepoState::Open,"Error! Registration of new fields not started or no longer allowed.\n");
// Get the map of all fields with this name
auto& map = m_fields[id.name()];
// Try to create the field. Allow case where it is already existing.
auto it_bool = map.emplace(id,field_type(id));
// Make sure the field can accommodate the requested value type
it_bool.first->second.get_header().get_alloc_properties().template request_value_type_allocation<RequestedValueType>();
}
template<typename ScalarType, typename Device>
bool FieldRepository<ScalarType,Device>::
has_field (const identifier_type& identifier) const {
auto it = m_fields.find(identifier.name());
return it!=m_fields.end() && it->second.find(identifier)!=it->second.end();
}
template<typename ScalarType, typename Device>
typename FieldRepository<ScalarType,Device>::field_type
FieldRepository<ScalarType,Device>::get_field (const identifier_type& id) const {
error::runtime_check(m_state==RepoState::Closed,"Error! You are not allowed to grab fields from the repo until after the registration phase is completed.\n");
const auto& map = m_fields.find(id.name());
error::runtime_check(map!=m_fields.end(), "Error! Field not found.\n");
auto it = map->second.find(id);
error::runtime_check(it!=map->second.end(), "Error! Field not found.\n");
return it->second;
}
template<typename ScalarType, typename Device>
void FieldRepository<ScalarType,Device>::registration_begins () {
// Update the state of the repo
m_state = RepoState::Open;
}
template<typename ScalarType, typename Device>
void FieldRepository<ScalarType,Device>::registration_ends () {
// Proceed to allocate fields
for (auto& map : m_fields) {
for (auto& it : map.second) {
it.second.allocate_view();
}
}
// Prohibit further registration of fields
m_state = RepoState::Closed;
}
template<typename ScalarType, typename Device>
void FieldRepository<ScalarType,Device>::clean_up() {
m_fields.clear();
m_state = RepoState::Clean;
}
} // namespace scream
#endif // SCREAM_FIELD_REPOSITORY_HPP
| 35.393103
| 160
| 0.73032
|
AaronDonahue
|
19ff01b95e0216119e2fe31f0d5d01dad501fbd4
| 56,887
|
cpp
|
C++
|
src/6502.cpp
|
allender/emulator
|
8310afee84b74cff7d91ecd78f7976264a8df900
|
[
"MIT"
] | 53
|
2017-01-19T08:08:40.000Z
|
2022-01-26T03:01:24.000Z
|
src/6502.cpp
|
allender/emulator
|
8310afee84b74cff7d91ecd78f7976264a8df900
|
[
"MIT"
] | 15
|
2017-03-10T22:55:53.000Z
|
2021-04-14T13:29:38.000Z
|
src/6502.cpp
|
allender/emulator
|
8310afee84b74cff7d91ecd78f7976264a8df900
|
[
"MIT"
] | 1
|
2019-07-09T07:19:53.000Z
|
2019-07-09T07:19:53.000Z
|
/*
MIT License
Copyright (c) 2016-2017 Mark Allender
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.
*/
//#define FUNCTIONAL_TESTS
/*
* Source file for 6502 emulation layer
*/
#include "apple2emu_defs.h"
#include "string.h"
#include "debugger.h"
#include "6502.h"
#include "memory.h"
cpu_6502::opcode_info cpu_6502::m_6502_opcodes[] = {
// 0x00 - 0x0f
{ 'BRK ', 1, 7, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ORA ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'TSB ', 2, 5, addr_mode::INDIRECT_ZP_MODE, &cpu_6502::zero_page_indirect },
{ 'ORA ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'ASL ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'PHP ', 1, 3, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ORA ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'ASL ', 1, 2, addr_mode::ACCUMULATOR_MODE, &cpu_6502::accumulator_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'TSB ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'ORA ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'ASL ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0x10 -
{ 'BPL ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'ORA ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'ORA ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'ASL ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'CLC ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ORA ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'ORA ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'ASL ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0x20 -
{ 'JSR ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'AND ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'BIT ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'AND ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'ROL ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'PLP ', 1, 4, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'AND ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'ROL ', 1, 2, addr_mode::ACCUMULATOR_MODE, &cpu_6502::accumulator_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'BIT ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'AND ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'ROL ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0x30 -
{ 'BMI ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'AND ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'AND ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'ROL ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'SEC ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'AND ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'AND ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'ROL ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0x40 -
{ 'RTI ', 1, 6, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'EOR ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'EOR ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'LSR ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'PHA ', 1, 3, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'EOR ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'LSR ', 1, 2, addr_mode::ACCUMULATOR_MODE, &cpu_6502::accumulator_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'JMP ', 3, 3, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'EOR ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'LSR ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0x50 -
{ 'BVC ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'EOR ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'EOR ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'LSR ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'CLI ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'EOR ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'EOR ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'LSR ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0x60 -
{ 'RTS ', 1, 6, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ADC ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'ADC ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'ROR ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'PLA ', 1, 4, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ADC ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'ROR ', 1, 2, addr_mode::ACCUMULATOR_MODE, &cpu_6502::accumulator_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'JMP ', 3, 5, addr_mode::INDIRECT_MODE, &cpu_6502::indirect_mode },
{ 'ADC ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'ROR ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0x70 -
{ 'BVS ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'ADC ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'ADC ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'ROR ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'SEI ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ADC ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'ADC ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'ROR ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0x80 -
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'STA ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'STY ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'STA ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'STX ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'DEY ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'TXA ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'STY ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'STA ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'STX ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0x90 -
{ 'BCC ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'STA ', 2, 6, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'STY ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'STA ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'STX ', 2, 4, addr_mode::ZP_INDEXED_MODE_Y, &cpu_6502::zero_page_indexed_mode_y },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'TYA ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'STA ', 3, 5, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_mode },
{ 'TXS ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'STA ', 3, 5, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0xa0 -
{ 'LDY ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'LDA ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ 'LDX ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'LDY ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'LDA ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'LDX ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'TAY ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'LDA ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'TAX ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'LDY ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'LDA ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'LDX ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0xb0 -
{ 'BCS ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'LDA ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'LDY ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'LDA ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'LDX ', 2, 4, addr_mode::ZP_INDEXED_MODE_Y, &cpu_6502::zero_page_indexed_mode_y },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'CLV ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'LDA ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ 'TSX ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'LDY ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'LDA ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'LDX ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0xc0 -
{ 'CPY ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'CMP ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'CPY ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'CMP ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'DEC ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'INY ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CMP ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'DEX ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'CPY ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'CMP ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'DEC ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0xd0 -
{ 'BNE ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'CMP ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'CMP ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'DEC ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'CLD ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CMP ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'CMP ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'DEC ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0xe0 -
{ 'CPX ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'SBC ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'CPX ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'SBC ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'INC ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'INX ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'SBC ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'NOP ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'CPX ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'SBC ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'INC ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
// 0xf0 -
{ 'BEQ ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'SBC ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'SBC ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'INC ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'SED ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'SBC ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
{ 'SBC ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'INC ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ ' ', 1, 0, addr_mode::NO_MODE, nullptr },
};
////////////////
// 65c02 opcodes
////////////////
cpu_6502::opcode_info cpu_6502::m_65c02_opcodes[] = {
// 0x00 - 0x0f
{ 'BRK ', 1, 7, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ORA ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ 'NOP ', 2, 2, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'TSB ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'ORA ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'ASL ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'PHP ', 1, 3, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ORA ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'ASL ', 1, 2, addr_mode::ACCUMULATOR_MODE, &cpu_6502::accumulator_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'TSB ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'ORA ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'ASL ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0x10 -
{ 'BPL ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'ORA ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ 'ORA ', 2, 5, addr_mode::INDIRECT_ZP_MODE, &cpu_6502::zero_page_indirect },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'TRB ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'ORA ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'ASL ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CLC ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ORA ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ 'INC ', 1, 2, addr_mode::ACCUMULATOR_MODE, &cpu_6502::accumulator_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'TRB ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'ORA ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'ASL ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0x20 -
{ 'JSR ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'AND ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ 'NOP ', 2, 2, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'BIT ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'AND ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'ROL ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'PLP ', 1, 4, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'AND ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'ROL ', 1, 2, addr_mode::ACCUMULATOR_MODE, &cpu_6502::accumulator_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'BIT ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'AND ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'ROL ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0x30 -
{ 'BMI ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'AND ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ 'AND ', 2, 5, addr_mode::INDIRECT_ZP_MODE, &cpu_6502::zero_page_indirect },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'BIT ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'AND ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'ROL ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'SEC ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'AND ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ 'DEC ', 1, 2, addr_mode::ACCUMULATOR_MODE, &cpu_6502::accumulator_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'BIT ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ 'AND ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'ROL ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0x40 -
{ 'RTI ', 1, 6, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'EOR ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ 'NOP ', 2, 2, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 2, 3, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'EOR ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'LSR ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'PHA ', 1, 3, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'EOR ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'LSR ', 1, 2, addr_mode::ACCUMULATOR_MODE, &cpu_6502::accumulator_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'JMP ', 3, 3, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'EOR ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'LSR ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0x50 -
{ 'BVC ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'EOR ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ 'EOR ', 2, 5, addr_mode::INDIRECT_ZP_MODE, &cpu_6502::zero_page_indirect },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 2, 4, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'EOR ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'LSR ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CLI ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'EOR ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ 'PHY ', 1, 3, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 3, 8, addr_mode::IMPLIED_MODE, &cpu_6502::absolute_mode },
{ 'EOR ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'LSR ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0x60 -
{ 'RTS ', 1, 6, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ADC ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ 'NOP ', 2, 2, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'STZ ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'ADC ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'ROR ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'PLA ', 1, 4, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ADC ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'ROR ', 1, 2, addr_mode::ACCUMULATOR_MODE, &cpu_6502::accumulator_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'JMP ', 3, 5, addr_mode::INDIRECT_MODE, &cpu_6502::indirect_mode },
{ 'ADC ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'ROR ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0x70 -
{ 'BVS ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'ADC ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ 'ADC ', 2, 5, addr_mode::INDIRECT_ZP_MODE, &cpu_6502::zero_page_indirect},
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'STZ ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'ADC ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'ROR ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'SEI ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'ADC ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ 'PLY ', 1, 4, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'JMP ', 3, 6, addr_mode::ABSOLUTE_INDEXED_INDIRECT_MODE, &cpu_6502::absolute_indexed_indirect_mode},
{ 'ADC ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'ROR ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0x80 -
{ 'BRA ', 2, 3, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'STA ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ 'NOP ', 2, 2, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'STY ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'STA ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'STX ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'DEY ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'BIT ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'TXA ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'STY ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'STA ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'STX ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0x90 -
{ 'BCC ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'STA ', 2, 6, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_mode },
{ 'STA ', 2, 5, addr_mode::INDIRECT_ZP_MODE, &cpu_6502::zero_page_indirect },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'STY ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'STA ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'STX ', 2, 4, addr_mode::ZP_INDEXED_MODE_Y, &cpu_6502::zero_page_indexed_mode_y },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'TYA ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'STA ', 3, 5, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_mode },
{ 'TXS ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'STZ ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'STA ', 3, 5, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ 'STZ ', 3, 5, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0xa0 -
{ 'LDY ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'LDA ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ 'LDX ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'LDY ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'LDA ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'LDX ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'TAY ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'LDA ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'TAX ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'LDY ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'LDA ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'LDX ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0xb0 -
{ 'BCS ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'LDA ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ 'LDA ', 2, 5, addr_mode::INDIRECT_ZP_MODE, &cpu_6502::zero_page_indirect },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'LDY ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'LDA ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'LDX ', 2, 4, addr_mode::ZP_INDEXED_MODE_Y, &cpu_6502::zero_page_indexed_mode_y },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CLV ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'LDA ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ 'TSX ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'LDY ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'LDA ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'LDX ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0xc0 -
{ 'CPY ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'CMP ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ 'NOP ', 2, 2, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CPY ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'CMP ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'DEC ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'INY ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CMP ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'DEX ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CPY ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'CMP ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'DEC ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0xd0 -
{ 'BNE ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'CMP ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ 'CMP ', 2, 5, addr_mode::INDIRECT_ZP_MODE, &cpu_6502::zero_page_indirect },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 2, 4, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'CMP ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'DEC ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CLD ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CMP ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ 'PHX ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 3, 4, addr_mode::IMPLIED_MODE, &cpu_6502::absolute_mode },
{ 'CMP ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'DEC ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0xe0 -
{ 'CPX ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'SBC ', 2, 6, addr_mode::INDEXED_INDIRECT_MODE, &cpu_6502::indexed_indirect_mode },
{ 'NOP ', 2, 2, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CPX ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'SBC ', 2, 3, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'INC ', 2, 5, addr_mode::ZERO_PAGE_MODE, &cpu_6502::zero_page_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'INX ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'SBC ', 2, 2, addr_mode::IMMEDIATE_MODE, &cpu_6502::immediate_mode },
{ 'NOP ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'CPX ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'SBC ', 3, 4, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'INC ', 3, 6, addr_mode::ABSOLUTE_MODE, &cpu_6502::absolute_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
// 0xf0 -
{ 'BEQ ', 2, 2, addr_mode::RELATIVE_MODE, &cpu_6502::relative_mode },
{ 'SBC ', 2, 5, addr_mode::INDIRECT_INDEXED_MODE, &cpu_6502::indirect_indexed_check_boundary_mode },
{ 'SBC ', 2, 5, addr_mode::INDIRECT_ZP_MODE, &cpu_6502::zero_page_indirect },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 2, 4, addr_mode::IMPLIED_MODE, &cpu_6502::immediate_mode },
{ 'SBC ', 2, 4, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'INC ', 2, 6, addr_mode::ZP_INDEXED_MODE, &cpu_6502::zero_page_indexed_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'SED ', 1, 2, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'SBC ', 3, 4, addr_mode::Y_INDEXED_MODE, &cpu_6502::absolute_y_check_boundary_mode },
{ 'PLX ', 1, 4, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
{ 'NOP ', 3, 4, addr_mode::IMPLIED_MODE, &cpu_6502::absolute_mode },
{ 'SBC ', 3, 4, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_check_boundary_mode },
{ 'INC ', 3, 7, addr_mode::X_INDEXED_MODE, &cpu_6502::absolute_x_mode },
{ 'NOP ', 1, 1, addr_mode::IMPLIED_MODE, &cpu_6502::implied_mode },
};
void cpu_6502::init(cpu_6502::cpu_mode mode)
{
m_pc = 0;
m_sp = 0xff - 3; // reset pulls 3 values from the stack
m_xindex = 0xff;
m_yindex = 0xff;
m_acc = 0xff;
m_status_register = 0xff;
set_flag(register_bit::DECIMAL_BIT, 0);
set_flag(register_bit::NOT_USED_BIT, 1);
// set the opcodes based on what cpu we are emulating
if (mode == cpu_6502::cpu_mode::CPU_6502) {
m_opcodes = m_6502_opcodes;
} else {
m_opcodes = m_65c02_opcodes;
}
// start vector
set_pc(memory_read(0xfffc) | memory_read(0xfffd) << 8);
}
cpu_6502::opcode_info *cpu_6502::get_opcode(uint8_t val)
{
return &m_opcodes[val];
}
inline int16_t cpu_6502::accumulator_mode()
{
return m_acc;
}
inline int16_t cpu_6502::immediate_mode()
{
return m_pc++;
}
inline int16_t cpu_6502::implied_mode()
{
return 0; // this value won't get used
}
inline int16_t cpu_6502::relative_mode()
{
return m_pc++;
}
inline int16_t cpu_6502::absolute_mode()
{
uint8_t lo = memory_read(m_pc++);
uint8_t hi = memory_read(m_pc++);
return (hi << 8) | lo;
}
inline int16_t cpu_6502::zero_page_mode()
{
uint8_t lo = memory_read(m_pc++);
return lo;
}
inline int16_t cpu_6502::indirect_mode()
{
uint8_t addr_lo = memory_read(m_pc++);
uint8_t addr_hi = memory_read(m_pc++);
uint16_t addr = addr_hi << 8 | addr_lo;
uint16_t return_addr = memory_read(addr) & 0xff;
return_addr |= (memory_read(addr + 1) << 8);
return return_addr;
}
inline int16_t cpu_6502::absolute_x_mode()
{
uint8_t lo = memory_read(m_pc++);
uint8_t hi = memory_read(m_pc++);
return ((hi << 8) | lo) + m_xindex;
}
inline int16_t cpu_6502::absolute_y_mode()
{
uint8_t lo = memory_read(m_pc++);
uint8_t hi = memory_read(m_pc++);
return ((hi << 8) | lo) + m_yindex;
}
inline int16_t cpu_6502::absolute_x_check_boundary_mode()
{
// get the new address
uint8_t lo = memory_read(m_pc++);
uint8_t hi = memory_read(m_pc++);
uint16_t addr = ((hi << 8) | lo) + m_xindex;
if (((addr - m_xindex) ^ addr) >> 8) {
// we have crossed page boundary, so cycle count increases
// by one here
m_extra_cycles += 1;
}
return addr;
}
inline int16_t cpu_6502::absolute_y_check_boundary_mode()
{
// get the new address
uint8_t lo = memory_read(m_pc++);
uint8_t hi = memory_read(m_pc++);
uint16_t addr = ((hi << 8) | lo) + m_yindex;
if (((addr - m_yindex) ^ addr) >> 8) {
// we have crossed page boundary, so cycle count increases
// by one here
m_extra_cycles += 1;
}
return addr;
}
inline int16_t cpu_6502::zero_page_indexed_mode()
{
uint8_t lo = memory_read(m_pc++);
return (lo + m_xindex) & 0xff;
}
inline int16_t cpu_6502::zero_page_indexed_mode_y()
{
uint8_t lo = memory_read(m_pc++);
return (lo + m_yindex) & 0xff;
}
inline int16_t cpu_6502::zero_page_indirect()
{
uint16_t addr_start = memory_read(m_pc++);
uint8_t lo = memory_read(addr_start);
uint8_t hi = memory_read(addr_start + 1);
return (hi << 8) | lo;
}
inline int16_t cpu_6502::indexed_indirect_mode()
{
uint16_t addr_start = (memory_read(m_pc++) + m_xindex) & 0xff;
uint8_t lo = memory_read(addr_start);
uint8_t hi = memory_read(addr_start + 1);
return (hi << 8) | lo;
}
inline int16_t cpu_6502::absolute_indexed_indirect_mode()
{
uint8_t lo = memory_read(m_pc++);
uint8_t hi = memory_read(m_pc++);
uint16_t addr = ((hi << 8) | lo) + m_xindex;
lo = memory_read(addr);
hi = memory_read(addr + 1);
return (hi << 8) | lo;
}
inline int16_t cpu_6502::indirect_indexed_mode()
{
uint16_t addr_start = memory_read(m_pc++);
uint8_t lo = memory_read(addr_start);
uint8_t hi = memory_read(addr_start + 1);
return ((hi << 8) | lo) + m_yindex;
}
inline int16_t cpu_6502::indirect_indexed_check_boundary_mode()
{
uint16_t addr = memory_read(m_pc++);
uint8_t lo = memory_read(addr);
uint8_t hi = memory_read(addr+ 1);
addr = ((hi << 8) | lo) + m_yindex;
// add extra cycle if page boundary crossed
if (((addr - m_yindex) ^ addr) >> 8) {
m_extra_cycles++;
}
return addr;
}
inline void cpu_6502::branch_relative()
{
uint16_t save_pc = m_pc;
uint8_t val = memory_read(m_pc - 1);
m_pc += val;
if (val & 0x80) {
m_pc -= 0x100;
}
// one extra cycle when crossing page boundary
if ((save_pc ^ m_pc) >> 8) {
m_extra_cycles++;
}
// always extra cycle for branching
m_extra_cycles++;
}
//
// main loop for opcode processing
//
uint32_t cpu_6502::process_opcode()
{
m_extra_cycles = 0;
// get the opcode at the program counter and the just figure out what
// to do
uint8_t opcode = memory_read(m_pc++, true);
// get addressing mode and then do appropriate work based on the mode
addr_mode mode = m_opcodes[opcode].m_addr_mode;
SDL_assert(mode != addr_mode::NO_MODE);
SDL_assert(m_opcodes[opcode].m_cycle_count != 0);
SDL_assert(m_opcodes[opcode].m_addr_func != nullptr);
uint16_t src = (this->*m_opcodes[opcode].m_addr_func)();
uint8_t cycles = m_opcodes[opcode].m_cycle_count;
// execute the actual opcode
switch (m_opcodes[opcode].m_mnemonic) {
case 'ADC ':
{
uint8_t val = memory_read(src);
uint32_t carry_bit = get_flag(register_bit::CARRY_BIT);
uint32_t sum = (uint32_t)m_acc + (uint32_t)val + carry_bit;
if (get_flag(register_bit::DECIMAL_BIT)) {
// decimal mode - see http://www.6502.org/tutorials/decimal_mode.html#3.2.2
// for detailed information on BCD and flags. One of the
// most trickieest parts of the opcode set
// set the zero bit flag for 6502 as it is based
// on the binary sum as done before the consitionals
set_flag(register_bit::ZERO_BIT, ((sum & 0xff) == 0));
set_flag(register_bit::OVERFLOW_BIT, ~(m_acc ^ val) & (m_acc ^ sum) & 0x80);
int32_t al = (m_acc & 0xf) + (val & 0xf) + carry_bit;
if (al >= 0x0a) {
al = ((al + 0x06) & 0x0f) + 0x10;
}
sum = (m_acc & 0xf0) + (val & 0xf0) + al;
set_flag(register_bit::SIGN_BIT, (sum & 0x80));
if (sum >= 0xa0) {
sum += 0x60;
}
set_flag(register_bit::CARRY_BIT, (sum >= 0x100));
m_acc = sum & 0xff;
// sign bit is different on 6502 and 65c02
if (m_opcodes == m_65c02_opcodes) {
set_flag(register_bit::ZERO_BIT, ((sum & 0xff) == 0));
set_flag(register_bit::SIGN_BIT, (m_acc & 0x80));
set_flag(register_bit::OVERFLOW_BIT, (sum >= 128));
}
} else {
set_flag(register_bit::CARRY_BIT, sum > 0xff);
set_flag(register_bit::OVERFLOW_BIT, ~(m_acc ^ val) & (m_acc ^ sum) & 0x80);
m_acc = sum & 0xff;
set_flag(register_bit::ZERO_BIT, (m_acc == 0));
set_flag(register_bit::SIGN_BIT, (m_acc & 0x80));
}
break;
}
case 'AND ':
{
m_acc &= memory_read(src);
set_flag(register_bit::SIGN_BIT, (m_acc >> 7));
set_flag(register_bit::ZERO_BIT, (m_acc == 0));
break;
}
case 'ASL ':
{
uint8_t val, old_val;
if (mode == addr_mode::ACCUMULATOR_MODE) {
old_val = m_acc;
}
else {
old_val = memory_read(src);
}
val = old_val << 1;
if (mode == addr_mode::ACCUMULATOR_MODE) {
m_acc = val;
}
else {
memory_write(src, val);
}
set_flag(register_bit::SIGN_BIT, val >> 7);
set_flag(register_bit::ZERO_BIT, val == 0);
set_flag(register_bit::CARRY_BIT, old_val >> 7);
break;
}
case 'BCC ':
{
if (get_flag(register_bit::CARRY_BIT) == 0) {
branch_relative();
}
break;
}
case 'BCS ':
{
if (get_flag(register_bit::CARRY_BIT) == 1) {
branch_relative();
}
break;
}
case 'BEQ ':
{
if (get_flag(register_bit::ZERO_BIT) == 1) {
branch_relative();
}
break;
}
case 'BIT ':
{
int8_t val = memory_read(src);
set_flag(register_bit::ZERO_BIT, ((val & m_acc) == 0));
// immediate mode with BIT only sets the zero flag
if (mode != cpu_6502::addr_mode::IMMEDIATE_MODE) {
set_flag(register_bit::SIGN_BIT, ((val >> 7) & 0x1));
set_flag(register_bit::OVERFLOW_BIT, ((val >> 6) & 0x1));
}
break;
}
case 'BMI ':
{
if (get_flag(register_bit::SIGN_BIT) == 1) {
branch_relative();
}
break;
}
case 'BNE ':
{
if (get_flag(register_bit::ZERO_BIT) == 0) {
branch_relative();
}
break;
}
case 'BPL ':
{
if (get_flag(register_bit::SIGN_BIT) == 0) {
branch_relative();
}
break;
}
case 'BRA ':
{
branch_relative();
break;
}
case 'BRK ':
{
m_pc++;
memory_write(0x100 + m_sp--, (m_pc >> 8));
memory_write(0x100 + m_sp--, (m_pc & 0xff));
uint8_t register_value = m_status_register;
register_value |= (1 << static_cast<uint8_t>(register_bit::NOT_USED_BIT));
register_value |= (1 << static_cast<uint8_t>(register_bit::BREAK_BIT));
memory_write(0x100 + m_sp--, register_value);
set_flag(register_bit::INTERRUPT_BIT, 1);
if (m_opcodes == m_65c02_opcodes) {
set_flag(register_bit::DECIMAL_BIT, 0);
}
// clear decimal flag on break
m_pc = (memory_read(0xfffe) & 0xff) | (memory_read(0xffff) << 8);
break;
}
case 'BVC ':
{
if (get_flag(register_bit::OVERFLOW_BIT) == 0) {
branch_relative();
}
break;
}
case 'BVS ':
{
if (get_flag(register_bit::OVERFLOW_BIT) == 1) {
branch_relative();
}
break;
}
case 'CLC ':
{
set_flag(register_bit::CARRY_BIT, 0);
break;
}
case 'CLD ':
{
set_flag(register_bit::DECIMAL_BIT, 0);
break;
}
case 'CLI ':
{
set_flag(register_bit::INTERRUPT_BIT, 0);
break;
}
case 'CLV ':
{
set_flag(register_bit::OVERFLOW_BIT, 0);
break;
}
case 'CMP ':
{
uint8_t src_val = memory_read(src);
if (m_acc >= src_val) {
set_flag(register_bit::CARRY_BIT, 1);
}
else {
set_flag(register_bit::CARRY_BIT, 0);
}
int8_t val = m_acc - src_val;
set_flag(register_bit::SIGN_BIT, (val >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, val == 0);
break;
}
case 'CPX ':
{
uint8_t src_val = memory_read(src);
if (m_xindex >= src_val) {
set_flag(register_bit::CARRY_BIT, 1);
}
else {
set_flag(register_bit::CARRY_BIT, 0);
}
int8_t val = m_xindex - src_val;
set_flag(register_bit::SIGN_BIT, (val >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, val == 0);
break;
}
case 'CPY ':
{
uint8_t src_val = memory_read(src);
if (m_yindex >= src_val) {
set_flag(register_bit::CARRY_BIT, 1);
}
else {
set_flag(register_bit::CARRY_BIT, 0);
}
int8_t val = m_yindex - src_val;
set_flag(register_bit::SIGN_BIT, (val >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, val == 0);
break;
}
case 'DEC ':
{
uint8_t val;
if (mode == cpu_6502::addr_mode::ACCUMULATOR_MODE) {
m_acc--;
val = m_acc;
} else {
val = memory_read(src) - 1;
memory_write(src, val);
}
set_flag(register_bit::SIGN_BIT, (val >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, val == 0);
break;
}
case 'DEX ':
{
m_xindex--;
set_flag(register_bit::SIGN_BIT, (m_xindex >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, (m_xindex == 0) & 0x1);
break;
}
case 'DEY ':
{
m_yindex--;
set_flag(register_bit::SIGN_BIT, (m_yindex >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, (m_yindex == 0) & 0x1);
break;
}
case 'EOR ':
{
uint8_t val = memory_read(src);
m_acc ^= val;
set_flag(register_bit::SIGN_BIT, (m_acc >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, (m_acc == 0) & 0x1);
break;
}
case 'INC ':
{
uint8_t val;
if (mode == cpu_6502::addr_mode::ACCUMULATOR_MODE) {
m_acc++;
val = m_acc;
} else {
val = memory_read(src) + 1;
memory_write(src, val);
}
set_flag(register_bit::SIGN_BIT, (val >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, val == 0);
break;
}
break;
case 'INX ':
{
m_xindex++;
set_flag(register_bit::SIGN_BIT, (m_xindex >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, (m_xindex == 0) & 0x1);
break;
}
case 'INY ':
{
m_yindex++;
set_flag(register_bit::SIGN_BIT, (m_yindex >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, (m_yindex == 0) & 0x1);
break;
}
case 'JMP ':
{
m_pc = src;
break;
}
case 'JSR ':
{
#if defined(FUNCTIONAL_TESTS)
if (src == 0xf001) {
debugger_print_char_to_console(m_acc);
}
else if (src == 0xf004) {
// m_acc = _getch();
// } else if (src == 0x43bf) {
//debug_break();
} else {
memory_write(0x100 + m_sp--, ((m_pc - 1) >> 8));
memory_write(0x100 + m_sp--, (m_pc - 1) & 0xff);
m_pc = src;
}
#else
memory_write(0x100 + m_sp--, ((m_pc - 1) >> 8));
memory_write(0x100 + m_sp--, (m_pc - 1) & 0xff);
m_pc = src;
#endif
break;
}
case 'LDA ':
{
m_acc = memory_read(src);
set_flag(register_bit::SIGN_BIT, (m_acc >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, (m_acc == 0) & 0x1);
break;
}
case 'LDX ':
{
m_xindex = memory_read(src);
set_flag(register_bit::SIGN_BIT, (m_xindex >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, (m_xindex == 0) & 0x1);
break;
}
case 'LDY ':
{
m_yindex = memory_read(src);
set_flag(register_bit::SIGN_BIT, (m_yindex >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, (m_yindex == 0) & 0x1);
break;
}
case 'LSR ':
{
uint8_t val;
if (mode == addr_mode::ACCUMULATOR_MODE) {
val = m_acc;
}
else {
val = memory_read(src);
}
set_flag(register_bit::CARRY_BIT, val & 1);
val >>= 1;
if (mode == addr_mode::ACCUMULATOR_MODE) {
m_acc = val;
}
else {
memory_write(src, val);
}
set_flag(register_bit::SIGN_BIT, 0);
set_flag(register_bit::ZERO_BIT, val == 0);
break;
}
case 'NOP ':
{
break;
}
case 'ORA ':
{
uint8_t val = memory_read(src);
m_acc |= val;
set_flag(register_bit::SIGN_BIT, (m_acc >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, m_acc == 0);
break;
}
case 'PHA ':
{
memory_write(0x100 + m_sp--, m_acc);
break;
}
case 'PHX ':
{
memory_write(0x100 + m_sp--, m_xindex);
break;
}
case 'PHY ':
{
memory_write(0x100 + m_sp--, m_yindex);
break;
}
case 'PLA ':
{
m_acc = memory_read(0x100 + ++m_sp);
set_flag(register_bit::SIGN_BIT, (m_acc >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, m_acc == 0);
break;
}
case 'PLX ':
{
m_xindex = memory_read(0x100 + ++m_sp);
set_flag(register_bit::SIGN_BIT, (m_xindex >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, m_xindex == 0);
break;
}
case 'PLY ':
{
m_yindex = memory_read(0x100 + ++m_sp);
set_flag(register_bit::SIGN_BIT, (m_yindex >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, m_yindex == 0);
break;
}
case 'PHP ':
{
uint8_t register_value = m_status_register;
register_value |= 1 << (static_cast<uint8_t>(register_bit::BREAK_BIT));
register_value |= 1 << (static_cast<uint8_t>(register_bit::NOT_USED_BIT));
memory_write(0x100 + m_sp--, register_value);
break;
}
case 'PLP ':
{
m_status_register = memory_read(0x100 + ++m_sp);
break;
}
case 'ROL ':
{
uint8_t val;
if (mode == addr_mode::ACCUMULATOR_MODE) {
val = m_acc;
}
else {
val = memory_read(src);
}
uint8_t carry_bit = (val >> 7) & 0x1;
val <<= 1;
val |= get_flag(register_bit::CARRY_BIT);
set_flag(register_bit::CARRY_BIT, carry_bit);
set_flag(register_bit::SIGN_BIT, (val >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, val == 0);
if (mode == addr_mode::ACCUMULATOR_MODE) {
m_acc = val;
}
else {
memory_write(src, val);
}
break;
}
case 'ROR ':
{
uint8_t val;
if (mode == addr_mode::ACCUMULATOR_MODE) {
val = m_acc;
}
else {
val = memory_read(src);
}
uint8_t carry_bit = val & 0x1;
val >>= 1;
val |= (get_flag(register_bit::CARRY_BIT) & 0x1) << 7;
set_flag(register_bit::CARRY_BIT, carry_bit);
set_flag(register_bit::SIGN_BIT, (val >> 7) & 0x1);
set_flag(register_bit::ZERO_BIT, val == 0);
if (mode == addr_mode::ACCUMULATOR_MODE) {
m_acc = val;
}
else {
memory_write(src, val);
}
break;
}
case 'RTI ':
{
m_status_register = memory_read(0x100 + ++m_sp);
m_pc = memory_read(0x100 + ++m_sp);
m_pc = (memory_read(0x100 + ++m_sp) << 8) | m_pc;
break;
}
case 'RTS ':
{
uint16_t addr = memory_read(0x100 + ++m_sp) & 0x00ff;
addr |= (memory_read(0x100 + ++m_sp) << 8);
m_pc = addr;
m_pc++;
break;
}
case 'SBC ':
{
uint8_t val = memory_read(src);
int32_t sum;
uint32_t carry_bit = get_flag(register_bit::CARRY_BIT);
sum = m_acc + (~val & 0xff) + carry_bit;
if (get_flag(register_bit::DECIMAL_BIT)) {
// decimal mode.
// behavior of ADC is slightly different on 6502 and 65c02.
// just split it out into separate conditionals to make code
// easier to understand
if (m_opcodes == m_6502_opcodes) {
set_flag(register_bit::CARRY_BIT, sum > 0xff);
set_flag(register_bit::OVERFLOW_BIT, (m_acc ^ val) & (m_acc ^ sum) & 0x80);
int32_t al = (m_acc & 0x0f) - (val & 0x0f) + carry_bit - 1;
if (al < 0) {
al = ((al - 0x06) & 0x0f) - 0x10;
}
sum = (m_acc & 0xf0) - (val & 0xf0) + al;
if (sum < 0) {
sum = sum - 0x60;
}
m_acc = sum & 0xff;
// flags are set as they are in binary arithmetic mode
set_flag(register_bit::ZERO_BIT, (m_acc == 0));
set_flag(register_bit::SIGN_BIT, (m_acc & 0x80));
} else {
set_flag(register_bit::CARRY_BIT, sum > 0xff);
set_flag(register_bit::OVERFLOW_BIT, (m_acc ^ val) & (m_acc ^ sum) & 0x80);
int32_t al = (m_acc & 0x0f) - (val & 0x0f) + carry_bit - 1;
sum = m_acc - val + carry_bit - 1;
if (sum < 0) {
sum = sum - 0x60;
}
if (al < 0) {
sum = sum - 0x06;
}
m_acc = sum & 0xff;
// flags are set as they are in binary arithmetic mode
set_flag(register_bit::ZERO_BIT, (m_acc == 0));
set_flag(register_bit::SIGN_BIT, (m_acc & 0x80));
}
} else {
set_flag(register_bit::CARRY_BIT, sum > 0xff);
set_flag(register_bit::OVERFLOW_BIT, (m_acc ^ val) & (m_acc ^ sum) & 0x80);
m_acc = sum & 0xff;
set_flag(register_bit::ZERO_BIT, (m_acc == 0));
set_flag(register_bit::SIGN_BIT, (m_acc & 0x80));
}
break;
}
case 'SEC ':
{
set_flag(register_bit::CARRY_BIT, 1);
break;
}
case 'SED ':
{
set_flag(register_bit::DECIMAL_BIT, 1);
break;
}
case 'SEI ':
{
set_flag(register_bit::INTERRUPT_BIT, 1);
break;
}
case 'STA ':
{
memory_write(src, m_acc);
break;
}
case 'STX ':
{
memory_write(src, m_xindex);
break;
}
case 'STY ':
{
memory_write(src, m_yindex);
break;
}
case 'STZ ':
{
memory_write(src, 0);
break;
}
case 'TAX ':
{
m_xindex = m_acc;
set_flag(register_bit::ZERO_BIT, m_xindex == 0);
set_flag(register_bit::SIGN_BIT, m_xindex & 0x80);
break;
}
case 'TRB ':
{
int8_t val = memory_read(src);
set_flag(register_bit::ZERO_BIT, ((val & m_acc) == 0));
// switch bits in accum
memory_write(src, (~m_acc) & val);
break;
}
case 'TSB ':
{
int8_t val = memory_read(src);
set_flag(register_bit::ZERO_BIT, ((val & m_acc) == 0));
// switch bits in accum
memory_write(src, m_acc | val);
break;
}
case 'TXA ':
{
m_acc = m_xindex;
set_flag(register_bit::ZERO_BIT, m_acc == 0);
set_flag(register_bit::SIGN_BIT, m_acc & 0x80);
break;
}
case 'TAY ':
{
m_yindex = m_acc;
set_flag(register_bit::ZERO_BIT, m_yindex == 0);
set_flag(register_bit::SIGN_BIT, m_yindex & 0x80);
break;
}
case 'TYA ':
{
m_acc = m_yindex;
set_flag(register_bit::ZERO_BIT, m_acc == 0);
set_flag(register_bit::SIGN_BIT, m_acc & 0x80);
break;
}
case 'TXS ':
{
m_sp = m_xindex;
break;
}
case 'TSX ':
{
m_xindex = (int8_t)m_sp;
set_flag(register_bit::ZERO_BIT, m_xindex == 0);
set_flag(register_bit::SIGN_BIT, m_xindex & 0x80);
break;
}
default:
{
SDL_assert(0);
}
}
// return the number of cycles that we executed
return cycles + m_extra_cycles;
}
| 38.411209
| 103
| 0.660362
|
allender
|
19ff8c6859b641606da055df0a33de4288195525
| 8,549
|
cpp
|
C++
|
iiwa_controllers/impedance_controller/src/impedance_controller.cpp
|
ICube-RDH/iiwa_ros2
|
7a8c11eff77b37209dbb17d426447641f863059d
|
[
"Apache-2.0"
] | 4
|
2022-03-18T21:09:05.000Z
|
2022-03-31T13:40:12.000Z
|
iiwa_controllers/impedance_controller/src/impedance_controller.cpp
|
ICube-RDH/iiwa_ros2
|
7a8c11eff77b37209dbb17d426447641f863059d
|
[
"Apache-2.0"
] | 1
|
2022-03-31T15:27:27.000Z
|
2022-03-31T15:27:27.000Z
|
iiwa_controllers/impedance_controller/src/impedance_controller.cpp
|
ICube-RDH/iiwa_ros2
|
7a8c11eff77b37209dbb17d426447641f863059d
|
[
"Apache-2.0"
] | 2
|
2022-03-21T08:28:07.000Z
|
2022-03-25T08:32:08.000Z
|
// Copyright 2022, ICube Laboratory, University of Strasbourg
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "impedance_controller/impedance_controller.hpp"
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
#include "rclcpp/logging.hpp"
#include "rclcpp/qos.hpp"
#include "hardware_interface/loaned_command_interface.hpp"
#include "hardware_interface/types/hardware_interface_type_values.hpp"
namespace impedance_controller
{
using hardware_interface::LoanedCommandInterface;
ImpedanceController::ImpedanceController()
: controller_interface::ControllerInterface(),
rt_command_ptr_(nullptr),
joints_command_subscriber_(nullptr)
{
}
CallbackReturn ImpedanceController::on_init()
{
try
{
// definition of the parameters that need to be queried from the
// controller configuration file with default values
auto_declare<std::vector<std::string>>("joints", std::vector<std::string>());
auto_declare<std::vector<double>>("stiffness", std::vector<double>());
auto_declare<std::vector<double>>("damping", std::vector<double>());
auto_declare<std::vector<double>>("mass", std::vector<double>());
}
catch (const std::exception & e)
{
fprintf(stderr, "Exception thrown during init stage with message: %s \n", e.what());
return CallbackReturn::ERROR;
}
return CallbackReturn::SUCCESS;
}
CallbackReturn ImpedanceController::on_configure(
const rclcpp_lifecycle::State & /*previous_state*/)
{
// getting the names of the joints to be controlled
joint_names_ = node_->get_parameter("joints").as_string_array();
if (joint_names_.empty())
{
RCLCPP_ERROR(get_node()->get_logger(), "'joints' parameter was empty");
return CallbackReturn::FAILURE;
}
// getting the impedance parameters
stiffness_ = node_->get_parameter("stiffness").as_double_array();
damping_ = node_->get_parameter("damping").as_double_array();
mass_ = node_->get_parameter("mass").as_double_array();
if(stiffness_.empty())
stiffness_.resize(joint_names_.size(),50.0);
if(damping_.empty())
damping_.resize(joint_names_.size(),10.0);
if(mass_.empty())
mass_.resize(joint_names_.size(),0.0);
if((stiffness_.size() != damping_.size()) || (stiffness_.size() != mass_.size())){
RCLCPP_ERROR(get_node()->get_logger(), "incoherent size of impedance parameters");
return CallbackReturn::FAILURE;
}
for(auto i = 0ul; i < stiffness_.size();i++){
if (stiffness_[i] < 0 || damping_[i] < 0 || mass_[i] < 0)
{
RCLCPP_ERROR(get_node()->get_logger(), "wrong impedance parameters");
return CallbackReturn::FAILURE;
}
}
// the desired position of the proxy point are queried from the proxy topic
// and passed to update via a rt pipe
joints_command_subscriber_ = get_node()->create_subscription<CmdType>(
"~/proxy", rclcpp::SystemDefaultsQoS(),
[this](const CmdType::SharedPtr msg) { rt_command_ptr_.writeFromNonRT(msg); });
RCLCPP_INFO(get_node()->get_logger(), "configure successful");
return CallbackReturn::SUCCESS;
}
// As impedance control targets the effort interface, it can be directly defined here
// without the need of getting as parameter. The effort interface is then affected to
// all controlled joints.
controller_interface::InterfaceConfiguration
ImpedanceController::command_interface_configuration() const
{
controller_interface::InterfaceConfiguration conf;
conf.type = controller_interface::interface_configuration_type::INDIVIDUAL;
conf.names.reserve(joint_names_.size());
for (const auto & joint_name : joint_names_)
{
conf.names.push_back(joint_name + "/" + hardware_interface::HW_IF_EFFORT);
}
return conf;
}
// Impedance control requires both velocity and position states. For this reason
// there can be directly defined here without the need of getting as parameters.
// The state interfaces are then deployed to all targeted joints.
controller_interface::InterfaceConfiguration
ImpedanceController::state_interface_configuration() const
{
controller_interface::InterfaceConfiguration conf;
conf.type = controller_interface::interface_configuration_type::INDIVIDUAL;
conf.names.reserve(joint_names_.size() * 2);
for (const auto & joint_name : joint_names_)
{
conf.names.push_back(joint_name + "/" + hardware_interface::HW_IF_POSITION);
conf.names.push_back(joint_name + "/" + hardware_interface::HW_IF_VELOCITY);
}
return conf;
}
// Fill ordered_interfaces with references to the matching interfaces
// in the same order as in joint_names
template <typename T>
bool get_ordered_interfaces(
std::vector<T> & unordered_interfaces, const std::vector<std::string> & joint_names,
const std::string & interface_type, std::vector<std::reference_wrapper<T>> & ordered_interfaces)
{
for (const auto & joint_name : joint_names)
{
for (auto & command_interface : unordered_interfaces)
{
if (
(command_interface.get_name() == joint_name) &&
(command_interface.get_interface_name() == interface_type))
{
ordered_interfaces.push_back(std::ref(command_interface));
}
}
}
return joint_names.size() == ordered_interfaces.size();
}
CallbackReturn ImpedanceController::on_activate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
std::vector<std::reference_wrapper<LoanedCommandInterface>> ordered_interfaces;
if (
!get_ordered_interfaces(
command_interfaces_, joint_names_, hardware_interface::HW_IF_EFFORT, ordered_interfaces) ||
command_interfaces_.size() != ordered_interfaces.size())
{
RCLCPP_ERROR(
node_->get_logger(), "Expected %zu position command interfaces, got %zu", joint_names_.size(),
ordered_interfaces.size());
return rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn::ERROR;
}
return CallbackReturn::SUCCESS;
}
// When deactivating the controller, the effort command on all joints is set to 0
CallbackReturn ImpedanceController::on_deactivate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
for (auto index = 0ul; index < joint_names_.size(); ++index)
{
command_interfaces_[index].set_value(0.0);
}
return CallbackReturn::SUCCESS;
}
// main control loop function getting the state interface and writing to the command interface
controller_interface::return_type ImpedanceController::update(const rclcpp::Time & time, const rclcpp::Duration & period)
{
// getting the data from the subscriber using the rt pipe
auto proxy = rt_command_ptr_.readFromRT();
// no command received yet
if (!proxy || !(*proxy))
{
return controller_interface::return_type::OK;
}
//checking proxy data validity
if ((*proxy)->joint_names.size() != joint_names_.size() ||
(*proxy)->points[0].positions.size() != joint_names_.size()) {
RCLCPP_ERROR_THROTTLE( get_node()->get_logger(), *node_->get_clock(), 1000,"command size does not match number of interfaces");
return controller_interface::return_type::ERROR;
}
//Impedance control loop
for (auto index = 0ul; index < joint_names_.size(); ++index)
{
// the stats are given in the same order as defines in state_interface_configuration
double q = state_interfaces_[2*index].get_value();
double qv = state_interfaces_[2*index+1].get_value();
double qd = (*proxy)->points[0].positions[index];
double qdv = 0;
if((*proxy)->points[0].velocities.size() == joint_names_.size())
qdv = (*proxy)->points[0].velocities[index];
double qda = 0;
if((*proxy)->points[0].accelerations.size() == joint_names_.size())
qda = (*proxy)->points[0].accelerations[index];
double tau = mass_[index]*qda + stiffness_[index]*(qd-q) + damping_[index]*(qdv-qv);
command_interfaces_[index].set_value(tau);
}
return controller_interface::return_type::OK;
}
} // namespace impedance_controller
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(
impedance_controller::ImpedanceController, controller_interface::ControllerInterface)
| 36.378723
| 131
| 0.731431
|
ICube-RDH
|
c2093913bbdee353f2fb6fd87ce095ba69be9dec
| 54
|
cpp
|
C++
|
IslandMUD/src/NPC/npc_neutral.cpp
|
JimViebke/MUD
|
b3786d0b165e31c28d6d7dd6de7b13c9d3df6d5a
|
[
"MIT"
] | 12
|
2015-05-01T00:16:42.000Z
|
2021-07-16T11:06:04.000Z
|
IslandMUD/src/NPC/npc_neutral.cpp
|
JimViebke/MUD
|
b3786d0b165e31c28d6d7dd6de7b13c9d3df6d5a
|
[
"MIT"
] | 37
|
2015-04-30T19:09:58.000Z
|
2018-07-23T23:39:54.000Z
|
IslandMUD/src/NPC/npc_neutral.cpp
|
JimViebke/MUD
|
b3786d0b165e31c28d6d7dd6de7b13c9d3df6d5a
|
[
"MIT"
] | 3
|
2016-07-15T19:45:09.000Z
|
2020-04-01T04:32:18.000Z
|
/* Jim Viebke
Jun 3 2015 */
#include "npc_neutral.h"
| 10.8
| 24
| 0.666667
|
JimViebke
|
c2152f5e48d0d6adb692f9db5480d045751e7abf
| 452
|
cpp
|
C++
|
src/skipList_demo.cpp
|
Park-ma/Learn-Algorithms
|
b9f6c1c663a3d1c29d913e7a90f3031075c2b7b9
|
[
"MIT"
] | 1
|
2021-01-12T14:27:33.000Z
|
2021-01-12T14:27:33.000Z
|
src/skipList_demo.cpp
|
Park-ma/Learn-Algorithms
|
b9f6c1c663a3d1c29d913e7a90f3031075c2b7b9
|
[
"MIT"
] | null | null | null |
src/skipList_demo.cpp
|
Park-ma/Learn-Algorithms
|
b9f6c1c663a3d1c29d913e7a90f3031075c2b7b9
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "SkipList.h"
#include "shuffle.h"
int main(){
learn_al::skipList<int> list;
int num[100];
for(int i=0;i<100;i++){
num[i] = i;
}
learn_al::shuffle(num,0,100);
for(int i=0;i<100;i++){
list.insert(num[i]);
}
for (int i = 0; i < 50; ++i) {
list.remove(num[i]);
}
std::cout<<list.search(100)<<std::endl;
std::cout<<list.search(1)<<std::endl;
return 0;
}
| 19.652174
| 43
| 0.524336
|
Park-ma
|
c2158382b45a2bc7ca368d7a98b88b8ebeb8ab6b
| 2,708
|
cpp
|
C++
|
src/RESTAPI_default_configuration.cpp
|
shimmy568/wlan-cloud-ucentralgw
|
806e24e1e666c31175c059373440ae029d9fff67
|
[
"BSD-3-Clause"
] | null | null | null |
src/RESTAPI_default_configuration.cpp
|
shimmy568/wlan-cloud-ucentralgw
|
806e24e1e666c31175c059373440ae029d9fff67
|
[
"BSD-3-Clause"
] | null | null | null |
src/RESTAPI_default_configuration.cpp
|
shimmy568/wlan-cloud-ucentralgw
|
806e24e1e666c31175c059373440ae029d9fff67
|
[
"BSD-3-Clause"
] | null | null | null |
//
// License type: BSD 3-Clause License
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
//
// Created by Stephane Bourque on 2021-03-04.
// Arilia Wireless Inc.
//
#include "Poco/JSON/Parser.h"
#include "RESTAPI_default_configuration.h"
#include "uStorageService.h"
#include "RESTAPI_objects.h"
void RESTAPI_default_configuration::handleRequest(Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response)
{
if(!ContinueProcessing(Request,Response))
return;
if(!IsAuthorized(Request,Response))
return;
ParseParameters(Request);
if(Request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET) {
std::string Name = GetBinding("name","0xdeadbeef");
uCentral::Objects::DefaultConfiguration DefConfig;
if(uCentral::Storage::GetDefaultConfiguration(Name,DefConfig))
{
Poco::JSON::Object Obj;
DefConfig.to_json(Obj);
ReturnObject(Obj,Response);
}
else
{
NotFound(Response);
}
} else if(Request.getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE) {
std::string Name = GetBinding("name", "0xdeadbeef");
if (uCentral::Storage::DeleteDefaultConfiguration(Name)) {
OK(Response);
} else {
NotFound(Response);
}
} else if(Request.getMethod() == Poco::Net::HTTPRequest::HTTP_POST) {
std::string Name = GetBinding("name", "0xdeadbeef");
Poco::JSON::Parser IncomingParser;
Poco::JSON::Object::Ptr Obj = IncomingParser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>();
uCentral::Objects::DefaultConfiguration DefConfig;
if(!DefConfig.from_json(Obj))
{
BadRequest(Response);
return;
}
if (uCentral::Storage::CreateDefaultConfiguration(Name,DefConfig)) {
OK(Response);
} else {
BadRequest(Response);
}
} else if(Request.getMethod() == Poco::Net::HTTPRequest::HTTP_PUT) {
std::string Name = GetBinding("name", "0xdeadbeef");
Poco::JSON::Parser IncomingParser;
Poco::JSON::Object::Ptr Obj = IncomingParser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>();
uCentral::Objects::DefaultConfiguration DefConfig;
if(!DefConfig.from_json(Obj))
{
BadRequest(Response);
return;
}
if (uCentral::Storage::UpdateDefaultConfiguration(Name, DefConfig)) {
OK(Response);
} else {
BadRequest(Response);
}
} else {
BadRequest(Response);
}
}
| 31.126437
| 129
| 0.610414
|
shimmy568
|
c2278bb277570559b0056fa6555a911984892c2a
| 2,465
|
cpp
|
C++
|
software/sender.cpp
|
mirounga/darwin
|
36c6c8883fdf9df90ef74c4d51f2e7fa8319ced6
|
[
"MIT"
] | 14
|
2019-07-24T13:20:49.000Z
|
2022-03-24T02:28:31.000Z
|
software/sender.cpp
|
mirounga/darwin
|
36c6c8883fdf9df90ef74c4d51f2e7fa8319ced6
|
[
"MIT"
] | null | null | null |
software/sender.cpp
|
mirounga/darwin
|
36c6c8883fdf9df90ef74c4d51f2e7fa8319ced6
|
[
"MIT"
] | 12
|
2018-11-08T04:18:03.000Z
|
2021-09-16T06:58:38.000Z
|
#include "graph.h"
tbb::reader_writer_lock fpga_writer_lock;
seeder_input reference_sender_body::operator()(seeder_input input)
{
auto &reads = get<0>(input);
size_t token = get<1>(input);
size_t word_size = WORD_SIZE;
size_t max_char_to_send = MAX_CHAR_TO_SEND;
size_t num_bytes_to_send = 0;
//fpga_writer_lock.lock();
for (size_t i = 0; i < reads.size(); i++)
{
Read &read = reads[i];
const size_t read_len = read.seq.size();
char *read_char = (char *)read.seq.data();
size_t dram_start_addr = read_char - g_DRAM->buffer;
// SEND READ
for (size_t j = 0; j < read_len;) {
num_bytes_to_send = std::min(max_char_to_send, read_len - j);
if (num_bytes_to_send % word_size != 0) {
num_bytes_to_send += word_size - (num_bytes_to_send % word_size);
}
assert(num_bytes_to_send % word_size == 0);
InitializeDRAMMessage init_dram_message;
GenerateInitializeMemoryMessage(init_dram_message, read_char, j, dram_start_addr, num_bytes_to_send);
{
InitializeDRAMMessageResponse init_dram_response;
g_InitializeReferenceMemory(0, g_DRAM->buffer, init_dram_message, init_dram_response);
}
dram_start_addr += num_bytes_to_send;
j += num_bytes_to_send;
}
}
//fpga_writer_lock.unlock();
return input;
}
seeder_input read_sender_body::operator()(seeder_input input)
{
auto &reads = get<0>(input);
size_t token = get<1>(input);
size_t word_size = WORD_SIZE;
size_t max_char_to_send = MAX_CHAR_TO_SEND;
size_t num_bytes_to_send = 0;
//fpga_writer_lock.lock();
for (size_t i = 0; i < reads.size(); i++)
{
Read &read = reads[i];
const size_t read_len = read.seq.size();
char *read_char = (char *)read.seq.data();
size_t dram_start_addr = read_char - g_DRAM->buffer;
// SEND READ
for (size_t j = 0; j < read_len;) {
num_bytes_to_send = std::min(max_char_to_send, read_len - j);
if (num_bytes_to_send % word_size != 0) {
num_bytes_to_send += word_size - (num_bytes_to_send % word_size);
}
assert(num_bytes_to_send % word_size == 0);
InitializeDRAMMessage init_dram_message;
GenerateInitializeMemoryMessage(init_dram_message, read_char, j, dram_start_addr, num_bytes_to_send);
{
InitializeDRAMMessageResponse init_dram_response;
g_InitializeReadMemory(0, g_DRAM->buffer, init_dram_message, init_dram_response);
}
dram_start_addr += num_bytes_to_send;
j += num_bytes_to_send;
}
}
//fpga_writer_lock.unlock();
return input;
}
| 25.153061
| 104
| 0.714807
|
mirounga
|
c230e5068f0649c7c6003815746441deb04249e3
| 896
|
cpp
|
C++
|
soj/2049.cpp
|
huangshenno1/project_euler
|
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
|
[
"MIT"
] | null | null | null |
soj/2049.cpp
|
huangshenno1/project_euler
|
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
|
[
"MIT"
] | null | null | null |
soj/2049.cpp
|
huangshenno1/project_euler
|
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <string.h>
char index_string[1000010];
int main()
{
long long index[256];
int exist_index[256];
char str[1010];
long long s;
int t,n,i;
scanf("%d",&t);
getchar();
while (t--)
{
memset(index,0,sizeof(index));
gets(index_string);
for (i=0;index_string[i]!='\0';i++)
{
index[index_string[i]]+=(i+1);
}
scanf("%d",&n);
getchar();
while (n--)
{
memset(exist_index,0,sizeof(exist_index));
gets(str);
s=0;
for (i=0;str[i]!='\0';i++)
{
if (!exist_index[str[i]])
{
exist_index[str[i]]=1;
s+=index[str[i]];
}
}
printf("%lld\n",s);
}
printf("\n");
}
return 0;
}
| 20.837209
| 54
| 0.399554
|
huangshenno1
|
ea4a45cc15eb7b57972a6db213617aed31918c98
| 3,118
|
hpp
|
C++
|
compose.hpp
|
geotz/compose
|
6a3761ef56570c910c9e6984b42a034af8fba36a
|
[
"MIT"
] | null | null | null |
compose.hpp
|
geotz/compose
|
6a3761ef56570c910c9e6984b42a034af8fba36a
|
[
"MIT"
] | null | null | null |
compose.hpp
|
geotz/compose
|
6a3761ef56570c910c9e6984b42a034af8fba36a
|
[
"MIT"
] | null | null | null |
// MIT License
// Copyright (c) 2017 George Tzoumas
// 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 _GT_COMPOSE_HPP_
#define _GT_COMPOSE_HPP_
#include<tuple>
#include<type_traits>
namespace gt
{
template<bool INNERFIRST,class...F>
class Compose
{
static constexpr size_t N= sizeof...(F);
static_assert(N > 0, "need at least one functor");
// <F,G,H>(x) = H(G(F(x))) or F(G(H(x)))
// by default functor order is interpreted as inner-to-outer...
static constexpr size_t B = (INNERFIRST) ? (N-1) : 0; // first
static constexpr size_t L = N-B-1; // last
static constexpr int S = (INNERFIRST) ? -1 : 1; // step
public:
template<class... AF>
// too-perfect forwarding protection tag...
Compose(std::true_type, AF&&... args): _functors( std::forward<AF>(args)... )
{}
template<class... Args>
auto operator()(Args&&... args) const
{
return eval(std::integral_constant<size_t,B>{}, std::forward<Args>(args)... );
}
private:
template<class... Args>
auto eval(std::integral_constant<size_t,L>, Args&&... args) const
{
return std::get<L>(_functors)(std::forward<Args>(args)...);
}
template<size_t K,class... Args>
auto eval(std::integral_constant<size_t,K>, Args&&... args) const
{
return std::get<K>(_functors)( eval(std::integral_constant<size_t,K+S>{}, std::forward<Args>(args)...) );
}
// by using tuples, we get empty-type optimization for free ;)
std::tuple<F...> _functors;
};
template<class...F>
auto compose(F&&... args)
{
// we decay the universal refs, in order to STORE the functors inside the new object,
// either by move (if movable) or copy, and avoid storing (potentially dangling) references...
// if the functor is neither movable nor copyable... well, we could use a std::cref I guess...
// inner to outer composition by default
// we could probably deduce directly a tuple via make_tuple, rather that decaying...
return Compose<true,std::decay_t<F>...>( std::true_type{}, std::forward<F>(args)... );
}
}
#endif
| 34.644444
| 113
| 0.683772
|
geotz
|
ea4b921325ecadd54018b8aafdcb42d94ff2ff1e
| 2,339
|
cpp
|
C++
|
modules/task_3/tashirev_i_monte_carlo/tashirev_i_monte_carlo.cpp
|
stasyurin/pp_2021_spring_informatics
|
dd9136c28cca4c538c5ecc82512fd78ad1fa7bd3
|
[
"BSD-3-Clause"
] | null | null | null |
modules/task_3/tashirev_i_monte_carlo/tashirev_i_monte_carlo.cpp
|
stasyurin/pp_2021_spring_informatics
|
dd9136c28cca4c538c5ecc82512fd78ad1fa7bd3
|
[
"BSD-3-Clause"
] | null | null | null |
modules/task_3/tashirev_i_monte_carlo/tashirev_i_monte_carlo.cpp
|
stasyurin/pp_2021_spring_informatics
|
dd9136c28cca4c538c5ecc82512fd78ad1fa7bd3
|
[
"BSD-3-Clause"
] | 1
|
2021-12-02T22:38:53.000Z
|
2021-12-02T22:38:53.000Z
|
// Copyright 2021 Tashirev Ivan
#include <tbb/tbb.h>
#include <functional>
#include <ctime>
#include <random>
#include <string>
#include <algorithm>
#include <vector>
#include "../../../modules/task_3/tashirev_i_monte_carlo/tashirev_i_monte_carlo.h"
double seqMonteCarlo(double(*f)(const std::vector<double>&),
const std::vector<double>& a,
const std::vector<double>& b, int steps) {
if (steps <= 0)
throw "integral is negative";
double res = 0.0;
std::mt19937 gen;
gen.seed(static_cast<unsigned int>(time(0)));
int mult = a.size();
double S = 1;
for (int i = 0; i < mult; i++)
S *= (b[i] - a[i]);
std::vector<std::uniform_real_distribution<double>> r(mult);
std::vector<double> r1(mult);
for (int i = 0; i < mult; i++)
r[i] = std::uniform_real_distribution<double>(a[i], b[i]);
for (int i = 0; i < steps; ++i) {
for (int j = 0; j < mult; ++j)
r1[j] = r[j](gen);
res += f(r1);
}
res *= S / steps;
return res;
}
double tbbMonteCarlo(double(*f)(const std::vector<double>&),
const std::vector<double>& a,
const std::vector<double>& b, int steps) {
if (steps <= 0)
throw "integral is negative";
double res = 0.0;
int mult = a.size();
std::vector<std::uniform_real_distribution<double>> r(mult);
for (int i = 0; i < mult; i++)
r[i] = std::uniform_real_distribution<double>(a[i], b[i]);
res = tbb::parallel_reduce(
tbb::blocked_range<size_t>(0, steps), 0.0,
[&](tbb::blocked_range<size_t> range, double running_total) {
std::mt19937 gen;
gen.seed(static_cast<unsigned int>(time(0)));
std::vector<double> r1(mult);
for (size_t i = range.begin(); i != range.end(); ++i) {
for (int j = 0; j < mult; ++j)
r1[j] = r[j](gen);
running_total += f(r1);
}
return running_total;
}, std::plus<double>() );
double S = 1;
for (int i = 0; i < mult; i++)
S *= (b[i] - a[i]);
res *= S / steps;
return res;
}
| 32.041096
| 82
| 0.495083
|
stasyurin
|
ea4ccb643ee6e90550f62ea1ea60d2f80e8a1a8b
| 652
|
hpp
|
C++
|
src/parser_worker.hpp
|
skiptirengu/anitomy-js
|
80376cca490c15ce6950f216b2616be6108f1aa8
|
[
"MIT"
] | 19
|
2017-06-06T01:42:33.000Z
|
2022-01-17T02:58:27.000Z
|
src/parser_worker.hpp
|
skiptirengu/anitomy-js
|
80376cca490c15ce6950f216b2616be6108f1aa8
|
[
"MIT"
] | 4
|
2018-05-16T04:33:36.000Z
|
2020-10-03T18:07:37.000Z
|
src/parser_worker.hpp
|
skiptirengu/anitomy-js
|
80376cca490c15ce6950f216b2616be6108f1aa8
|
[
"MIT"
] | 4
|
2017-01-23T00:10:09.000Z
|
2020-04-30T08:46:07.000Z
|
#pragma once
#include "file_parser.hpp"
#include <napi.h>
namespace anitomy_js {
using Napi::Promise;
class ParserWorker : public Napi::AsyncWorker {
public:
ParserWorker(const Napi::Env &env, const Napi::Value &input, const Napi::Value &options)
: AsyncWorker(env, "anitomy_js::ParserWorker"), _parser(env, input, options),
_deferred(Promise::Deferred::New(env)) {
//
}
~ParserWorker() = default;
void Execute() override;
void OnOK() override;
void OnError(Napi::Error const &error) override;
Napi::Promise GetPromise();
private:
FileParser _parser;
Promise::Deferred _deferred;
};
} // namespace anitomy_js
| 21.733333
| 90
| 0.70092
|
skiptirengu
|
ea5d3d61545d03e1829ccd37865378b74613a075
| 2,183
|
hpp
|
C++
|
cppsrc/board.hpp
|
gateship1/RushHour
|
84fce27c7d19037e81eebf8858a89dfb848349ae
|
[
"Apache-2.0"
] | null | null | null |
cppsrc/board.hpp
|
gateship1/RushHour
|
84fce27c7d19037e81eebf8858a89dfb848349ae
|
[
"Apache-2.0"
] | null | null | null |
cppsrc/board.hpp
|
gateship1/RushHour
|
84fce27c7d19037e81eebf8858a89dfb848349ae
|
[
"Apache-2.0"
] | null | null | null |
#ifndef BOARD_HEADER_FILE
#define BOARD_HEADER_FILE
#include <algorithm> // find_if, min
#include <iostream>
#include <map> // map
#include <cmath> // cos, sin
#include <sstream> // stringstream
#include <vector>
#include "vehicle.hpp"
// player vehicle is a global variable and is 'x'
const char player_vehicle_id = 'x';
/* Board class
data structure containing a board state
data elements:
width, width of the playable board (default 6 spaces)
height, height of the playable board (default 6 spaces)
exit_row, the row in which the player vehicle is located (exit on right)
vehicles, the set of vehicles on the board
signature, the string representation (or signature) of the vehicle layout on the board
*/
struct Board {
Board(); // only used for error checking input
Board(const size_t&, const size_t&, const size_t&, const std::map<char, Vehicle>&);
auto is_solution_state() const -> bool;
static auto generate_signature(const size_t&, const size_t&,
const size_t&, const std::map<char, Vehicle>&) -> std::string;
// getters
auto get_exit_row() const -> size_t;
auto get_height() const -> size_t;
auto get_signature() const -> std::string;
auto get_vehicles() const -> std::map<char, Vehicle>;
auto get_width() const -> size_t;
static auto hboard_border(const size_t&) -> std::string;
auto move_down(const Vehicle&, const size_t&) const -> bool;
auto move_left(const Vehicle&, const size_t&) const -> bool;
auto move_right(const Vehicle&, const size_t&) const -> bool;
auto move_up(const Vehicle&, const size_t&) const -> bool;
auto next() const -> std::vector<Board>;
auto next_for_vehicle(const Vehicle&) const -> std::vector<Board>;
static auto print_board_set(const std::vector<Board>&) -> void;
static auto print_path(const std::vector<Board>&, const size_t& n=6) -> void;
friend std::ostream& operator<<(std::ostream&, const Board&);
private:
const size_t width, height, exit_row;
const std::map<char, Vehicle> vehicles;
const std::string signature;
};
#endif // BOARD_HEADER_FILE
| 34.650794
| 90
| 0.677966
|
gateship1
|
ea6907f8667343d4cae1d47ea6ab4e1eb38cedc6
| 5,500
|
cc
|
C++
|
src/stream/audio/alsa/alsa_capture_stream.cc
|
screencloud/screenbox-rockchip--rkmedia
|
d8b09604ab8eb89b9615236ba41a6b049bd0af5c
|
[
"BSD-3-Clause"
] | null | null | null |
src/stream/audio/alsa/alsa_capture_stream.cc
|
screencloud/screenbox-rockchip--rkmedia
|
d8b09604ab8eb89b9615236ba41a6b049bd0af5c
|
[
"BSD-3-Clause"
] | null | null | null |
src/stream/audio/alsa/alsa_capture_stream.cc
|
screencloud/screenbox-rockchip--rkmedia
|
d8b09604ab8eb89b9615236ba41a6b049bd0af5c
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2019 Fuzhou Rockchip Electronics Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "stream.h"
#include <assert.h>
#include <errno.h>
#include "alsa_utils.h"
#include "media_type.h"
#include "utils.h"
#include "buffer.h"
namespace easymedia {
class AlsaCaptureStream : public Stream {
public:
AlsaCaptureStream(const char *param);
virtual ~AlsaCaptureStream();
static const char *GetStreamName() { return "alsa_capture_stream"; }
virtual std::shared_ptr<MediaBuffer> Read();
virtual size_t Read(void *ptr, size_t size, size_t nmemb) final;
virtual int Seek(int64_t offset _UNUSED, int whence _UNUSED) final {
return -1;
}
virtual long Tell() final { return -1; }
virtual size_t Write(const void *ptr _UNUSED, size_t size _UNUSED,
size_t nmemb _UNUSED) final {
return 0;
}
virtual int Open() final;
virtual int Close() final;
private:
SampleInfo sample_info;
std::string device;
snd_pcm_t *alsa_handle;
size_t frame_size;
};
AlsaCaptureStream::AlsaCaptureStream(const char *param)
: alsa_handle(NULL), frame_size(0) {
memset(&sample_info, 0, sizeof(sample_info));
sample_info.fmt = SAMPLE_FMT_NONE;
std::map<std::string, std::string> params;
int ret = ParseAlsaParams(param, params, device, sample_info);
UNUSED(ret);
if (device.empty())
device = "default";
if (SampleInfoIsValid(sample_info))
SetReadable(true);
else
LOG("missing some necessary param\n");
}
AlsaCaptureStream::~AlsaCaptureStream() {
if (alsa_handle)
AlsaCaptureStream::Close();
}
size_t AlsaCaptureStream::Read(void *ptr, size_t size, size_t nmemb) {
size_t buffer_len = size * nmemb;
snd_pcm_sframes_t gotten = 0;
snd_pcm_sframes_t nb_samples =
(size == frame_size ? nmemb : buffer_len / frame_size);
while (nb_samples > 0) {
// SND_PCM_ACCESS_RW_INTERLEAVED
int status = snd_pcm_readi(alsa_handle, ptr, nb_samples);
if (status < 0) {
if (status == -EAGAIN) {
/* Apparently snd_pcm_recover() doesn't handle this case - does it
* assume snd_pcm_wait() above? */
std::this_thread::sleep_for(std::chrono::microseconds(100));
errno = EAGAIN;
break;
}
status = snd_pcm_recover(alsa_handle, status, 0);
if (status < 0) {
/* Hmm, not much we can do - abort */
LOG("ALSA write failed (unrecoverable): %s\n", snd_strerror(status));
errno = EIO;
break;
}
errno = EIO;
break;
}
nb_samples -= status;
gotten += status;
}
return gotten * frame_size / size;
}
std::shared_ptr<MediaBuffer> AlsaCaptureStream::Read() {
int buffer_size = frame_size * sample_info.nb_samples;
int read_cnt = -1;
struct timespec crt_tm = {0, 0};
auto sample_buffer = std::make_shared<easymedia::SampleBuffer>(
MediaBuffer::Alloc2(buffer_size), sample_info);
if (!sample_buffer) {
LOG("Alloc audio frame buffer failed:%d,%d!\n", buffer_size, frame_size);
return nullptr;
}
clock_gettime(CLOCK_MONOTONIC, &crt_tm);
read_cnt = Read(sample_buffer->GetPtr(), frame_size, sample_info.nb_samples);
sample_buffer->SetValidSize(read_cnt * frame_size);
sample_buffer->SetSamples(read_cnt);
sample_buffer->SetUSTimeStamp(crt_tm.tv_sec*1000000LL + crt_tm.tv_nsec/1000);
return sample_buffer;
}
int AlsaCaptureStream::Open() {
snd_pcm_t *pcm_handle = NULL;
snd_pcm_hw_params_t *hwparams = NULL;
if (!Readable())
return -1;
int status = snd_pcm_hw_params_malloc(&hwparams);
if (status < 0) {
LOG("snd_pcm_hw_params_malloc failed\n");
return -1;
}
pcm_handle = AlsaCommonOpenSetHwParams(device.c_str(), SND_PCM_STREAM_CAPTURE,
0, sample_info, hwparams);
if (!pcm_handle)
goto err;
if ((status = snd_pcm_hw_params(pcm_handle, hwparams)) < 0) {
LOG("cannot set parameters (%s)\n", snd_strerror(status));
goto err;
}
#ifndef NDEBUG
/* This is useful for debugging */
do {
unsigned int periods = 0;
snd_pcm_uframes_t period_size = 0;
snd_pcm_uframes_t bufsize = 0;
snd_pcm_hw_params_get_periods(hwparams, &periods, NULL);
snd_pcm_hw_params_get_period_size(hwparams, &period_size, NULL);
snd_pcm_hw_params_get_buffer_size(hwparams, &bufsize);
LOG("ALSA: period size = %ld, periods = %u, buffer size = %lu\n",
period_size, periods, bufsize);
} while (0);
#endif
if ((status = snd_pcm_prepare(pcm_handle)) < 0) {
LOG("cannot prepare audio interface for use (%s)\n", snd_strerror(status));
goto err;
}
/* Switch to blocking mode for capture */
// snd_pcm_nonblock(pcm_handle, 0);
snd_pcm_hw_params_free(hwparams);
frame_size = snd_pcm_frames_to_bytes(pcm_handle, 1);
alsa_handle = pcm_handle;
return 0;
err:
if (hwparams)
snd_pcm_hw_params_free(hwparams);
if (pcm_handle) {
snd_pcm_drain(pcm_handle);
snd_pcm_close(pcm_handle);
}
return -1;
}
int AlsaCaptureStream::Close() {
if (alsa_handle) {
snd_pcm_drop(alsa_handle);
snd_pcm_close(alsa_handle);
alsa_handle = NULL;
LOG("audio capture close done\n");
return 0;
}
return -1;
}
DEFINE_STREAM_FACTORY(AlsaCaptureStream, Stream)
const char *FACTORY(AlsaCaptureStream)::ExpectedInputDataType() {
return nullptr;
}
const char *FACTORY(AlsaCaptureStream)::OutPutDataType() { return AUDIO_PCM; }
} // namespace easymedia
| 28.947368
| 80
| 0.686182
|
screencloud
|
ea690d8d07c492c1629c062a0a69f8314d2a67e0
| 909
|
cpp
|
C++
|
Bonepick/engine/utility/Random.cpp
|
dodgelafnitz/Bonepick
|
1a12193e5d0cf5d4061d0d3cbd1529a206ed38f4
|
[
"MIT"
] | 3
|
2018-10-09T02:08:57.000Z
|
2020-08-12T20:26:29.000Z
|
Bonepick/engine/utility/Random.cpp
|
dodgelafnitz/Bonepick
|
1a12193e5d0cf5d4061d0d3cbd1529a206ed38f4
|
[
"MIT"
] | 1
|
2018-09-30T02:42:39.000Z
|
2018-09-30T02:42:39.000Z
|
Bonepick/engine/utility/Random.cpp
|
dodgelafnitz/Bonepick
|
1a12193e5d0cf5d4061d0d3cbd1529a206ed38f4
|
[
"MIT"
] | null | null | null |
#include "utility/Random.h"
#include <cstdlib>
#include <ctime>
namespace
{
unsigned storedSeed = 0;
}
//##############################################################################
void InitializeRandom(void)
{
InitializeRandom(unsigned(std::time(nullptr)));
}
//##############################################################################
void InitializeRandom(unsigned seed)
{
storedSeed = seed;
std::srand(unsigned(seed));
}
//##############################################################################
unsigned GetRandomSeed(void)
{
return storedSeed;
}
//##############################################################################
unsigned GetRandomNumber(unsigned exclusiveMax)
{
return std::rand() % exclusiveMax;
}
//##############################################################################
float GetRandomNumber(void)
{
return GetRandomNumber(1319) / 1319.0f;
}
| 21.642857
| 80
| 0.40374
|
dodgelafnitz
|
ea6f2a5d306034ca798e1ab578acf6cf776a5180
| 13,143
|
cpp
|
C++
|
test/test_cases2.cpp
|
Arghnews/wordsearch_solver
|
cf25db64ca3d1facd9191aad075654f124f0d580
|
[
"MIT"
] | null | null | null |
test/test_cases2.cpp
|
Arghnews/wordsearch_solver
|
cf25db64ca3d1facd9191aad075654f124f0d580
|
[
"MIT"
] | null | null | null |
test/test_cases2.cpp
|
Arghnews/wordsearch_solver
|
cf25db64ca3d1facd9191aad075654f124f0d580
|
[
"MIT"
] | null | null | null |
#include "test_cases.hpp"
#include "wordsearch_solver/wordsearch_solver.hpp"
#include <catch2/catch.hpp>
#include <fmt/format.h>
#include <range/v3/action/sort.hpp>
#include <range/v3/action/unique.hpp>
#include <range/v3/view/map.hpp>
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
// TODO:
// Currently test fails because of unsorted thing.
// Could try to create some kind of CRTP wrapper that classes implement/inherit
// from to implement the contains/further stuff. So they all get the constructor
// wrappers for free. Also find cmake way to run tests for one. Find cmake
// restructure to have all targets in top level cmakelists and pass that to
// solver with variable (easy) Fork prettyprint.hpp repo and add nice stuff for
// optional configure, and cmake support Nicer way to pass all classes to run
// through from build to program would be awesome really. Need to copy SFINAE
// for string_view -> string construction from set to vector
// To make adding a dictionary implementation less painful, add it to this
// "list", delimited by a comma
// #define WORDSEARCH_DICTIONARY_CLASSES compact_trie::CompactTrie, trie::Trie,
// \
// compact_trie2::CompactTrie2, dictionary_std_vector::DictionaryStdVector, \
// dictionary_std_set::DictionaryStdSet
using namespace std::literals;
namespace fs = std::filesystem;
using ContainsFurther = std::pair<bool, bool>;
template <class Dict>
std::vector<std::pair<bool, bool>> static make_contains_and_further(
const Dict& t, const std::string& stem, const std::string& suffixes) {
std::vector<std::pair<bool, bool>> contains_further;
t.contains_further(stem, suffixes, std::back_inserter(contains_further));
return contains_further;
}
TEMPLATE_TEST_CASE("Test trie constructors", "[construct]",
WORDSEARCH_DICTIONARY_CLASSES) {
std::vector<std::string> v{"hi", "there", "chum"};
std::set<std::string> s{"hi", "there", "chum"};
const auto const_v = v;
const auto const_s = s;
TestType{};
TestType{v};
TestType{const_v};
TestType{std::vector{v}};
TestType{s};
TestType{const_s};
TestType{std::set{s}};
TestType{"a"};
TestType{"a"s};
TestType{"a"sv};
TestType{"a", "b"};
TestType{"a"s, "b"s};
TestType{"a"sv, "b"sv};
TestType{v.begin(), v.end()};
TestType{const_v.begin(), const_v.end()};
TestType{s.begin(), s.end()};
TestType{const_s.begin(), const_s.end()};
TestType{"a", "b", "a"};
TestType{"a"s, "b"s, "a"s};
TestType{"a"sv, "b"sv, "a"sv};
const TestType t{
"a", "act", "acted", "actor", "actors",
};
}
TEMPLATE_TEST_CASE("Simple contains", "[contains]",
WORDSEARCH_DICTIONARY_CLASSES) {
TestType t{"lapland", "laplanc"};
// t.insert("lapland");
// t.insert("laplanc");
// (!t.contains("lap"));
// (!t.contains("laplan"));
// (t.contains("lapland"));
// INFO(fmt::format("DONE\n"));
// return 0;
INFO(fmt::format("\nTrie: {}\n", t));
CHECK(t.size() == 2);
CHECK(!t.contains("lap"));
CHECK(!t.contains("laplan"));
CHECK(t.contains("lapland"));
CHECK(!t.contains("laplanda"));
CHECK(!t.contains("laplandb"));
CHECK(!t.contains("laplandab"));
const auto word = "lapland"s;
const bool found = t.contains(word);
if (found) {
INFO(fmt::format("Found {}\n", word));
} else {
INFO(fmt::format("Not found {}\n", word));
}
INFO(fmt::format("Done with lapland search test\n"));
}
TEMPLATE_TEST_CASE("Contains and further test", "[contains][further]",
WORDSEARCH_DICTIONARY_CLASSES) {
// clang-format off
const std::initializer_list<std::string> inserts{
"act",
"acted",
"acting",
"action",
"actions",
"actor",
"activate",
};
// clang-format on
TestType t{inserts};
CHECK(t.size() == inserts.size());
// INFO(fmt::format("Traversing\n"));
// std::vector<std::string> traverse_words;
// t.traverse([&traverse_words] (const auto& word)
// {
// INFO(fmt::format("{}\n", word));
// traverse_words.push_back(word);
// });
// CHECK(std::is_sorted(traverse_words.begin(), traverse_words.end()));
// CHECK(std::is_permutation(
// traverse_words.begin(), traverse_words.end(),
// inserts.begin(), inserts.end()
// ));
const std::string haystack = "activates";
std::string w;
for (const auto c : haystack) {
w.push_back(c);
bool has = t.contains(w);
INFO(fmt::format("{}\n", t));
bool has_prefix = t.further(w);
INFO(fmt::format("Word: {:{}}, trie has {}: has prefix:{}\n", w,
haystack.size(), has ? u8"✓ " : u8"❌",
has_prefix ? u8"✓ " : u8"❌"));
}
// clang-format off
const std::vector<std::tuple<std::string, bool, bool>> v{
{ "a", false, true, },
{ "ac", false, true, },
{ "act", true, true, },
{ "acti", false, true, },
{ "activ", false, true, },
{ "activa", false, true, },
{ "activat", false, true, },
{ "activate", true, false, },
{ "activates", false, false, },
};
// clang-format on
INFO(fmt::format("Trie: {}\n", t));
for (const auto& [substring, contains_answer, contains_prefix_answer] : v) {
INFO(fmt::format("Izzard: {} {} {}\n", substring, contains_answer,
contains_prefix_answer));
INFO(fmt::format("Contains:\n"));
CHECK(t.contains(substring) == contains_answer);
INFO(fmt::format("Further:\n"));
CHECK(t.further(substring) == contains_prefix_answer);
// ,"substring: {}, expected: {} {}", substring, contains_answer,
// contains_prefix_answer);
}
}
TEMPLATE_TEST_CASE("Contains and further test 2", "[contains][further]",
WORDSEARCH_DICTIONARY_CLASSES) {
// clang-format off
const std::vector<std::string> bla{
"burner",
"zoo",
"zoological",
"ahem",
"ahe",
"ahem",
"boom",
"boomer",
"zoo",
"burn",
"burning",
"burned",
"burner",
"burner",
};
// clang-format on
const TestType t{bla};
// INFO(fmt::format("{}\n", t.as_vector()));
auto bla2 = bla;
std::sort(bla2.begin(), bla2.end());
bla2.erase(std::unique(bla2.begin(), bla2.end()), bla2.end());
INFO(fmt::format("{}\n", bla2));
CHECK(t.size() == bla2.size());
// , "{} vs {}", t.size(), bla2.size());
// CHECK(t.as_vector() == bla2);
for (const auto& word : bla) {
CHECK(t.contains(word));
INFO(fmt::format("{} should be in {}\n", word, t));
}
}
TEMPLATE_TEST_CASE("Simple further", "[further]",
WORDSEARCH_DICTIONARY_CLASSES) {
const std::set<std::string> w{"hi", "there", "chum"};
const TestType t{w.begin(), w.end()};
INFO(fmt::format("Trie: {}\n", t));
// const auto v = t.as_vector();
// CHECK(std::equal(w.begin(), w.end(), v.begin(), v.end()));
CHECK(!t.further("y"));
CHECK(!t.further("yq"));
}
TEMPLATE_TEST_CASE("More complex contains further",
"[contains][further][contains_further]",
WORDSEARCH_DICTIONARY_CLASSES) {
// clang-format off
const std::vector<std::string> bla{
"burner",
"zoo",
"zoological",
"ahem",
"ahe",
"aheaaaaaaaaa",
"ahem",
"boom",
"boomer",
"zoo",
"burn",
"burning",
"burned",
"burner",
"burner",
"bur",
};
// clang-format on
const TestType t{bla};
auto bla2 = bla;
std::sort(bla2.begin(), bla2.end());
bla2.erase(std::unique(bla2.begin(), bla2.end()), bla2.end());
INFO(fmt::format("{}\n", bla2));
CHECK(t.size() == bla2.size());
for (const auto& word : bla) {
CHECK(t.contains(word));
INFO(fmt::format("{} should be in {}\n", word, t));
}
CHECK(!t.contains("burne"));
CHECK(!t.contains("buzn"));
CHECK(!t.contains("ba"));
CHECK(!t.contains("zooz"));
CHECK(!t.contains("x"));
for (const auto c : "abcdefghijklmnopqrstuvwxyz"sv) {
INFO(fmt::format("{}\n", t));
CHECK(!t.contains(std::string{"ahem"} + c));
}
CHECK(t.further("bu"));
CHECK(t.further("aheaa"));
CHECK(t.further("ahe"));
CHECK(t.further("a"));
CHECK(t.further("b"));
CHECK(t.further("z"));
CHECK(t.further("zo"));
CHECK(!t.further("burning"));
CHECK(!t.further("boomer"));
const auto result = make_contains_and_further(t, "burn", "aei");
CHECK(result.size() == 3);
CHECK(result.at(0) == ContainsFurther(false, false));
CHECK(result.at(1) == ContainsFurther(false, true));
CHECK(result.at(2) == ContainsFurther(false, true));
}
TEMPLATE_TEST_CASE("Contains_further test", "[contains_further]",
WORDSEARCH_DICTIONARY_CLASSES) {
INFO(fmt::format("----------------\n"));
// clang-format off
const std::vector<std::string> bla{
"ahem",
"ahe",
"aheaaa",
"ahem",
};
// clang-format on
INFO(fmt::format("Inserting {}\n", bla));
const TestType t{bla};
INFO(fmt::format("Trie: {}\n", t));
{
const auto result = make_contains_and_further(t, "ahe", "amz");
CHECK(result.size() == 3);
CHECK(result.at(0) == ContainsFurther(false, true));
CHECK(result.at(1) == ContainsFurther(true, false));
CHECK(result.at(2) == ContainsFurther(false, false));
INFO(fmt::format("ContainsFurther: {}\n", result));
}
{
const auto result = make_contains_and_further(t, "", "ab");
CHECK(result.size() == 2);
CHECK(result.at(0) == ContainsFurther(false, true));
CHECK(result.at(1) == ContainsFurther(false, false));
}
}
TEMPLATE_TEST_CASE("Test move cons", "[construct][further]",
WORDSEARCH_DICTIONARY_CLASSES) {
const std::set<std::string> w{"hi", "there", "chum"};
TestType t_orig{w.begin(), w.end()};
INFO(fmt::format("Move cons\n"));
const auto t{std::move(t_orig)};
// const auto v = t.as_vector();
// CHECK(std::equal(w.begin(), w.end(), v.begin(), v.end()));
CHECK(!t.further("y"));
CHECK(!t.further("yq"));
}
TEMPLATE_TEST_CASE("Contains and further test 3", "[contains][further]",
WORDSEARCH_DICTIONARY_CLASSES) {
INFO(fmt::format("Start of wadoogey\n"));
// clang-format off
std::vector<std::string> w =
{
"a" ,
"ac" ,
"act" ,
"acti" ,
"activ" ,
"activa" ,
"activat" ,
"activate" ,
"activates",
};
// clang-format on
TestType t{w};
for (auto word : w) {
CHECK(t.contains(word));
}
CHECK(!w.empty());
for (auto i = 0UL; i + 1 < w.size(); ++i) {
CHECK(t.further(w.at(i)));
}
CHECK(!t.further(w.back()));
CHECK(t.size() == 9);
INFO(fmt::format("End of wadoogey\n"));
}
TEMPLATE_TEST_CASE("Empty dict/trie tests", "[contains][further][construct]",
WORDSEARCH_DICTIONARY_CLASSES) {
{
TestType t{};
CHECK(!t.contains("asdf"));
CHECK(!t.further("asdf"));
CHECK(!t.contains("a"));
CHECK(!t.further("a"));
const auto result = make_contains_and_further(t, "", "");
CHECK(result.empty());
}
{
const TestType t{};
CHECK(!t.contains(""));
CHECK(!t.further(""));
}
{
INFO(fmt::format("\nMaking empty trie:\n"));
const TestType t{""};
INFO(fmt::format("Empty trie: {}\n", t));
CHECK(t.contains(""));
CHECK(!t.further(""));
INFO(fmt::format("Trie with empty string as only elem: {}\n", t));
CHECK(t.size() == 1);
}
{
const TestType t{"", "a", "b", "c"};
CHECK(t.contains(""));
CHECK(t.further(""));
CHECK(t.contains("a"));
CHECK(t.contains("b"));
CHECK(t.contains("c"));
CHECK(t.size() == 4);
{
const auto result = make_contains_and_further(t, "", "");
CHECK(result.empty());
}
{
const auto result = make_contains_and_further(t, "", "abcd");
CHECK(result.size() == 4);
CHECK(result.at(0) == ContainsFurther(true, false));
CHECK(result.at(1) == ContainsFurther(true, false));
CHECK(result.at(2) == ContainsFurther(true, false));
CHECK(result.at(3) == ContainsFurther(false, false));
}
}
}
TEMPLATE_TEST_CASE("Further tests", "[further]",
WORDSEARCH_DICTIONARY_CLASSES) {
const TestType t{"aaa", "aab", "aabx", "aaby", "aabz",
"aabxa", "aabxb", "aabyc", "aabyd", "aac"};
INFO(fmt::format("Trie: {}\n", t));
CHECK(!t.further("aaa"));
CHECK(!t.further("aac"));
CHECK(t.further("aabx"));
CHECK(t.further("aaby"));
CHECK(!t.further("aabz"));
CHECK(!t.further("aabyc"));
CHECK(!t.further("aabycd"));
}
TEMPLATE_TEST_CASE("Printable", "[printable]", WORDSEARCH_DICTIONARY_CLASSES) {
const TestType t{};
fmt::format("{}", t);
std::stringstream ss;
ss << t;
}
TEMPLATE_TEST_CASE("Empty and size functions", "[empty][size]",
WORDSEARCH_DICTIONARY_CLASSES) {
{
TestType t{};
CHECK(t.empty());
CHECK(t.size() == 0);
}
{
TestType t{"hi"};
CHECK(!t.empty());
CHECK(t.size() == 1);
}
{
TestType t{"hi", "hi"};
CHECK(!t.empty());
CHECK(t.size() == 1);
}
{
TestType t{"a", "b"};
CHECK(!t.empty());
CHECK(t.size() == 2);
}
}
| 27.96383
| 80
| 0.592254
|
Arghnews
|
ea728ba356cb47a80116e72dfcad0cb201ad67e5
| 3,804
|
cpp
|
C++
|
core/datastructures/geometrydata.cpp
|
hmsgit/campvis
|
d97de6a86323866d6a8f81d2a641e3e0443a6b39
|
[
"ECL-2.0",
"Apache-2.0"
] | 5
|
2018-06-19T06:20:01.000Z
|
2021-07-31T05:54:25.000Z
|
core/datastructures/geometrydata.cpp
|
hmsgit/campvis
|
d97de6a86323866d6a8f81d2a641e3e0443a6b39
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
core/datastructures/geometrydata.cpp
|
hmsgit/campvis
|
d97de6a86323866d6a8f81d2a641e3e0443a6b39
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
// ================================================================================================
//
// This file is part of the CAMPVis Software Framework.
//
// If not explicitly stated otherwise: Copyright (C) 2012-2015, all rights reserved,
// Christian Schulte zu Berge <christian.szb@in.tum.de>
// Chair for Computer Aided Medical Procedures
// Technische Universitaet Muenchen
// Boltzmannstr. 3, 85748 Garching b. Muenchen, Germany
//
// For a full list of authors and contributors, please refer to the file "AUTHORS.txt".
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
// ================================================================================================
#include "geometrydata.h"
#include "cgt/buffer.h"
#include "cgt/logmanager.h"
#include "cgt/glcontextmanager.h"
#include "cgt/vertexarrayobject.h"
namespace campvis {
const std::string GeometryData::loggerCat_ = "CAMPVis.core.datastructures.GeometryData";;
GeometryData::GeometryData()
: AbstractData()
, _buffersDirty(true)
, _verticesBuffer(nullptr)
, _texCoordsBuffer(nullptr)
, _colorsBuffer(nullptr)
, _normalsBuffer(nullptr)
, _pickingBuffer(nullptr)
{
}
GeometryData::GeometryData(const GeometryData& rhs)
: AbstractData(rhs)
, _buffersDirty(true)
, _verticesBuffer(nullptr)
, _texCoordsBuffer(nullptr)
, _colorsBuffer(nullptr)
, _normalsBuffer(nullptr)
, _pickingBuffer(nullptr)
{
}
GeometryData::~GeometryData() {
deleteBuffers();
}
GeometryData& GeometryData::operator=(const GeometryData& rhs) {
if (this == &rhs)
return *this;
AbstractData::operator=(rhs);
// delete old VBOs and null pointers
deleteBuffers();
return *this;
}
void GeometryData::deleteBuffers() const {
for (int i = 0; i < NUM_BUFFERS; ++i) {
delete _buffers[i];
_buffers[i] = nullptr;
}
}
size_t GeometryData::getVideoMemoryFootprint() const {
size_t sum = 0;
if (_verticesBuffer != nullptr)
sum += _verticesBuffer->getBufferSize();
if (_texCoordsBuffer != nullptr)
sum += _texCoordsBuffer->getBufferSize();
if (_colorsBuffer != nullptr)
sum += _colorsBuffer->getBufferSize();
if (_normalsBuffer != nullptr)
sum += _normalsBuffer->getBufferSize();
if (_pickingBuffer != nullptr)
sum += _pickingBuffer->getBufferSize();
return sum;
}
const cgt::BufferObject* GeometryData::getVerticesBuffer() const {
return _verticesBuffer;
}
const cgt::BufferObject* GeometryData::getTextureCoordinatesBuffer() const {
return _texCoordsBuffer;
}
const cgt::BufferObject* GeometryData::getColorsBuffer() const {
return _colorsBuffer;
}
const cgt::BufferObject* GeometryData::getNormalsBuffer() const {
return _normalsBuffer;
}
const cgt::BufferObject* GeometryData::getPickingBuffer() const {
return _pickingBuffer;
}
}
| 32.237288
| 100
| 0.595952
|
hmsgit
|
ea7e3fe1c95282a02611146ab0ff2d1d23084a9b
| 25,604
|
cpp
|
C++
|
src/AnimTimeline/qframeselector.cpp
|
hiergaut/AnimTimeline
|
1998ba097628106607888c4f0871173fe6f281a1
|
[
"Apache-2.0"
] | 14
|
2019-09-29T14:27:53.000Z
|
2021-11-14T11:58:01.000Z
|
src/AnimTimeline/qframeselector.cpp
|
hiergaut/AnimTimeline
|
1998ba097628106607888c4f0871173fe6f281a1
|
[
"Apache-2.0"
] | null | null | null |
src/AnimTimeline/qframeselector.cpp
|
hiergaut/AnimTimeline
|
1998ba097628106607888c4f0871173fe6f281a1
|
[
"Apache-2.0"
] | 5
|
2019-02-16T18:57:02.000Z
|
2021-08-24T00:14:46.000Z
|
//#include <AnimTimeline/animtimeline.h>
#include "FormAnimTimeline.h"
//#include <AnimTimeline/qframeselector.h>
#include "qframeselector.h"
#include <QDebug>
#include <QPainter>
#include <QTimer>
#include <QWheelEvent>
#include <QtGlobal>
QFrameSelector::QFrameSelector(QWidget* parent)
: QFrame(parent)
{
widgetRuler = static_cast<QWidgetRuler*>(parent);
nbInterval = widgetRuler->getNbInterval();
step = widgetRuler->getStep();
pixPerSec = widgetRuler->getPixPerSec();
zero = widgetRuler->getZero();
duration = widgetRuler->getMaxDuration();
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
// qDebug() << "end construct frameSelector, parent : " << parent;
}
QFrameSelector::~QFrameSelector()
{
delete timer;
}
double QFrameSelector::nearestStep(double time) const
{
double deltaT = AnimTimeline::AUTO_SUGGEST_CURSOR_RADIUS / *pixPerSec;
double minDist = durationSpin->maximum();
double dist;
double newCursor = time;
for (double keyPose : keyPoses) {
dist = qAbs(keyPose - time);
if (dist < deltaT && dist < minDist) {
minDist = dist;
newCursor = keyPose;
}
if (time < keyPose)
break;
}
for (int i = 0; i < *nbInterval - 1; ++i) {
double pos = i * *step;
dist = qAbs(pos - time);
if (dist < deltaT && dist < minDist) {
minDist = dist;
newCursor = pos;
}
pos = i * *step + 0.5 * *step;
dist = qAbs(pos - time);
if (dist < deltaT && dist < minDist) {
minDist = dist;
newCursor = pos;
}
if (time < pos)
break;
}
return newCursor;
}
// ------------------------------- PROTECTED ----------------------------------
void QFrameSelector::paintEvent(QPaintEvent*)
{
int w = width();
int h = height();
if (m_rulerChanged) {
leftSpacer->setMinimumWidth(static_cast<int>(*zero) - 3);
rightSpacer->setMinimumWidth(w - (*zero + *duration * *pixPerSec) - 4);
// leftSpacer->resize(200, 0);
redrawPlayZone();
prepareBackground(w, h);
m_rulerChanged = false;
}
// m_rulerChanged = true;
// m_pixmapBackground.fill(Qt::red);
// qDebug() << "QFrameSelector::paintEvent";
// m_pixmapBackground = new QPixmap;
// QPainter painter(m_pixmapBackground);
// painter.drawText(100, 100, "fuck");
QPainter painter(this);
// DRAW CURSOR
painter.setPen(QPen(QColor(0, 0, 255, 255), 3));
int xCursor = static_cast<int>(*zero + cursor * *pixPerSec);
painter.drawLine(xCursor, 0, xCursor, h);
// DRAW KEYPOSES
painter.setPen(QPen(QColor(255, 255, 0, 255), 3));
// int hTemp = h / 4 + 2;
int hTemp = 3 *h / 8;
for (double keyPose : keyPoses) {
int xKeyPose = static_cast<int>(*zero + keyPose * *pixPerSec);
painter.drawLine(xKeyPose, hTemp, xKeyPose, h);
// painter.drawLine(xKeyPose, 0, xKeyPose, hTemp);
}
if (updateKeyPoseFlash > 0) {
if (updateKeyPoseFlash % 2 == 0) {
painter.setPen(QPen(QColor(0, 0, 255, 255), 3));
int xKeyPose = static_cast<int>(*zero + keyPoseFlash * *pixPerSec);
painter.drawLine(xKeyPose, hTemp, xKeyPose, h);
}
if (--updateKeyPoseFlash == 0)
timer->stop();
}
painter.drawPixmap(rect(), *m_pixmapBackground);
// return;
// m_rulerChanged = false;
// } else {
// qDebug() << "QFrameSelector::paintEvent rulerChanged" << paintCounter;
// }
}
//void QFrameSelector::resizeEvent(QResizeEvent* event)
//{
//// qDebug() << "QFrameSelector::resizeEvent " << event;
// QSize size = event->size();
// int w = size.width();
// int h = size.height();
//}
void QFrameSelector::mousePressEvent(QMouseEvent* event)
{
// ---------------------- LEFT CLICK --------------------------------------
if (event->button() == Qt::LeftButton) {
double newCursor = qMax((event->x() - *zero) / *pixPerSec, 0.0);
// move cursor without render
if (*ctrlDown) {
onChangeCursor(newCursor, false);
}
// delete keyPoses between cursor and newCursor
else if (*shiftDown) {
deleteZone(cursor, newCursor);
}
// move cursor and update renderer
else {
onChangeCursor(newCursor);
mouseLeftClicked = true;
}
// ------------------ RIGHT CLICK -------------------------------------
} else if (event->button() == Qt::RightButton) {
double newPose = qMax((event->x() - *zero) / *pixPerSec, 0.0);
auto it = keyPoses.find(cursor);
// if already on keyPose, move current keyPose
// ------------------- CURSOR ON KEYPOSE -----------------------
if (it != keyPoses.end()) {
double nearest = nearestStep(newPose);
// -------------- SINGLE MOVE -------------------------------------
if (*shiftDown) {
// if no keyPose under mouse, move keyPose to newPose
if (keyPoses.find(nearest) == keyPoses.end()) {
if (qAbs(cursor - nearest) > 1e-5) {
cursor = nearest;
size_t id = static_cast<size_t>(std::distance(keyPoses.begin(), it));
keyPoses.erase(it);
keyPoses.insert(cursor);
updateCursorSpin(); // to find keyPose here, yellow spinBox
update();
emit keyPoseMoved(id, cursor); // EXTERNAL SIGNAL
qDebug() << "\033[35mkeyPoseMoved(" << id << ", " << cursor << ")\033[0m";
}
}
// ---------- MULTIPLE MOVE -----------------------------------
} else {
auto itLeft = it;
--itLeft;
double left = (it == keyPoses.begin()) ? (0.0) : (*itLeft);
if (nearest > left) {
double dist = nearest - cursor;
size_t id = static_cast<size_t>(std::distance(keyPoses.begin(), it));
moveKeyPoses(dist, id);
}
}
// ---------------- CURSOR NOT ON KEYPOSE --------------------------
} else {
// if shiftdown, slide first right keypose to the left
// --------------- MOVE RIGHT KEYPOSE TO THE LEFT -----------------
if (*shiftDown) {
auto it = keyPoses.begin();
size_t iRight = 0;
while (it != keyPoses.end() && *it < newPose) {
++it;
++iRight;
}
// if keyPoses on the right, remove or insert time
if (it != keyPoses.end()) {
double right = *it;
double dist = newPose - right;
moveKeyPoses(dist, iRight);
}
// if not shiftdown, slide first left keypose to the right
// ---------------- MOVE LEFT KEYPOSE TO THE RIGHT -----------
} else {
auto it = keyPoses.rbegin();
size_t iLeft = keyPoses.size() - 1;
while (it != keyPoses.rend() && *it > newPose) {
++it;
--iLeft;
}
if (it != keyPoses.rend()) {
double left = *it;
double dist = newPose - left;
moveKeyPoses(dist, iLeft);
}
}
}
// no catch mouse event
} else {
event->ignore();
return;
}
event->accept();
}
void QFrameSelector::mouseMoveEvent(QMouseEvent* event)
{
if (mouseLeftClicked) {
double newCursor = qMax((event->x() - *zero) / *pixPerSec, 0.0);
onChangeCursor(newCursor);
} else {
event->ignore();
}
}
void QFrameSelector::mouseReleaseEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton) {
mouseLeftClicked = false;
event->accept();
} else {
event->ignore();
}
}
// -------------------------- EXTERNAL SLOTS ----------------------------------
// EXTERNAL SLOT
void QFrameSelector::onAddingKeyPose(double time, bool internal /* = true */)
{
// by default (time = -1.0), add keyPose on cursor
if (static_cast<int>(time) == -1)
time = cursor;
int nbKeyPoses = static_cast<int>(keyPoses.size());
keyPoses.insert(time);
// if keyPose not already here
if (static_cast<int>(keyPoses.size()) != nbKeyPoses) {
updateCursorSpin();
update();
if (internal) {
emit keyPoseAdded(time); // EXTERNAL SIGNAL
qDebug() << "\033[35mkeyPoseAdded(" << time << ")\033[0m";
}
nbKeyPosesSpin->setValue(static_cast<int>(keyPoses.size()));
// keyPose already here, change actual keyPose
} else {
auto it = keyPoses.find(time);
size_t id = static_cast<size_t>(std::distance(keyPoses.begin(), it));
if (internal) {
emit keyPoseChanged(id); // EXTERNAL SIGNAL
qDebug() << "\033[35mkeyPoseChanged(" << id << ")\033[0m";
}
updateKeyPoseFlash = 6;
keyPoseFlash = time;
timer->start(50);
update();
}
}
// EXTERNAL SLOT
void QFrameSelector::onClearKeyPoses()
{
keyPoses.clear();
nbKeyPosesSpin->setValue(0);
updateCursorSpin();
update();
}
// EXTERNAL SLOT
void QFrameSelector::onChangeStart(double time, bool internal /* = true */)
{
double newStart = qMax(qMin(time, end), 0.0);
bool out = qAbs(newStart - time) > 1e-5;
bool change = qAbs(newStart - start) > 1e-5;
if (change) {
start = newStart;
updateStartSpin();
redrawPlayZone();
// emit signal if time of emitter is internal changed due of limits
if (internal || out) {
emit startChanged(start); // EXTERNAL SIGNAL
qDebug() << "\033[35mstartChanged(" << start << ")\033[0m";
}
} else {
if (out) {
updateStartSpin();
}
}
}
// EXTERNAL SLOT
void QFrameSelector::onChangeEnd(double time, bool internal /* = true */)
{
double newEnd = qMin(qMax(time, start), *duration);
bool out = qAbs(newEnd - time) > 1e-5;
bool change = qAbs(newEnd - end) > 1e-5;
// emit signal only if new value of end
if (change) {
end = newEnd;
updateEndSpin();
redrawPlayZone();
// update();
if (internal || out) {
emit endChanged(end); // EXTERNAL SIGNAL
qDebug() << "\033[35mendChanged(" << end << ")\033[0m";
}
} else {
if (out) {
updateEndSpin();
}
}
}
// EXTERNAL SLOT (warning on using EXTERNAL SIGNAL)
void QFrameSelector::onChangeCursor(double time, bool internal /* = true */)
{
double newCursor = qMax(0.0, time);
if (internal) {
newCursor = nearestStep(newCursor);
}
bool out = qAbs(newCursor - time) > 1e-5;
bool change = qAbs(newCursor - cursor) > 1e-5;
if (change) {
cursor = newCursor;
updateCursorSpin();
// redrawPlayZone();
update();
if (internal || out) {
emit cursorChanged(cursor); // EXTERNAL SIGNAL
qDebug() << "\033[35mcursorChanged(" << time << ")\033[0m";
}
} else {
if (out) {
updateCursorSpin();
}
}
}
// EXTERNAL SLOT
void QFrameSelector::onChangeDuration(double time, bool internal /* = true */)
{
double newDuration = qMax(time, 0.0);
bool out = qAbs(newDuration - time) > 1e-5;
bool change = qAbs(newDuration - *duration) > 1e-5;
if (change) {
*duration = newDuration;
widgetRuler->drawRuler(widgetRuler->minimumWidth());
updateDurationSpin();
// redrawPlayZone();
// emit signal if time of emitter is internal changed due of limits
if (internal || out) {
emit durationChanged(*duration);
qDebug() << "\033[35mdurationChanged(" << *duration << ")\033[0m";
}
} else {
if (out) {
updateDurationSpin();
}
}
if (*duration < start)
onChangeStart(*duration);
if (*duration < end)
onChangeEnd(*duration);
// auto update
}
void QFrameSelector::prepareBackground(int w, int h)
{
if (m_pixmapBackground != nullptr)
delete m_pixmapBackground;
m_pixmapBackground = new QPixmap(this->size());
m_pixmapBackground->fill(QColor(255, 255, 255, 0));
// m_pixmapBackground->fill(QColor(255, 0, 0, 255));
QPainter painter(m_pixmapBackground);
// int h = height;
// int w = width;
// painter.begin(this);
// painter.drawText(100, 100, "fuck");
// painter.end();
// if (!sliding) {
// redrawPlayZone();
// }
// DRAW FRAME SCALE
// painter.setPen(QPen(Qt::lightGray));
painter.setPen(QPen(QColor(127, 127, 127, 64), 1));
double frameDuration = 1.0 / AnimTimeline::FPS;
int hUp = h / 3;
double nbFrame = *duration / frameDuration;
for (int i = 0; i < nbFrame; i++) {
int x = static_cast<int>(i * frameDuration * *pixPerSec + *zero);
painter.drawLine(x, 0, x, hUp);
}
// DRAW TIME SCALE
// int hDown = 2 * h / 3;
int hDown = h / 2;
painter.setPen(Qt::black);
for (int i = 1; i < *nbInterval; i++) {
int x = static_cast<int>(i * *step * *pixPerSec);
painter.drawLine(x, hDown, x, h);
}
int hDown2 = 3 * h / 4;
painter.setPen(Qt::darkGray);
for (int i = 1; i < *nbInterval - 1; i++) {
int middle = static_cast<int>((i + 0.5) * *step * *pixPerSec);
painter.drawLine(middle, hDown2, middle, h);
}
// DRAW MIDDLE RULER SEPARATOR
// int gap = h / 15;
// painter.setPen(Qt::white);
// // painter.drawLine(0, h / 2 + gap + 2, w, h / 2 + gap + 2);
// painter.drawLine(0, h / 2 + gap + 1, w, h / 2 + gap + 1);
// painter.setPen(Qt::darkGray);
// painter.drawLine(0, h / 2 + gap, w, h / 2 + gap);
// painter.setPen(Qt::black);
// painter.drawLine(0, h / 2 - gap - 1, w, h / 2 - gap - 1);
// // painter.drawLine(0, h / 2 - gap - 2, w, h / 2 - gap - 2);
// QRect rect(0, h / 2 - gap, w, gap + gap / 3);
// QLinearGradient gradient(0, rect.top(), 0, rect.bottom());
// gradient.setColorAt(0, QColor(128, 128, 128, 127));
// gradient.setColorAt(1, QColor(255, 255, 255, 255));
// painter.fillRect(rect, gradient);
// QRect rect2(0, h / 2 + gap / 3, w, 2 * gap / 3 + 1);
// QLinearGradient gradient2(0, rect2.top(), 0, rect2.bottom());
// gradient2.setColorAt(0, QColor(255, 255, 255, 255));
// gradient2.setColorAt(1, QColor(192, 192, 192, 127));
// painter.fillRect(rect2, gradient2);
}
void QFrameSelector::onRulerChange()
{
m_rulerChanged = true;
}
// -------------------------- INTERNAL SLOTS ----------------------------------
void QFrameSelector::onSlideLeftSlider(int deltaX)
{
// qDebug() << "QFrameSelector::onSlideLeftSlider " << deltaX;
// if (!sliding) {
//// leftSlider->setStyleSheet("background-color: #00ff00");
// sliding = true;
// }
// double newStart = start + deltaX / *pixPerSec;
double newStart = (deltaX - *zero) / *pixPerSec;
onChangeStart(newStart); // EXTERNAL SLOT
// leftSpacer->setMinimumWidth(static_cast<int>(*zero + start * *pixPerSec));
// leftSpacer->setMinimumWidth(static_cast<int>(*zero) - 3);
// playZone->setMinimumWidth(static_cast<int>((end - start) * *pixPerSec));
}
void QFrameSelector::onSlideRightSlider(int deltaX)
{
// qDebug() << "QFrameSelector::onSlideRightSlider " << deltaX;
// if (!sliding) {
//// rightSlider->setStyleSheet("background-color: red");
// sliding = true;
// }
// double newEnd = end + deltaX / *pixPerSec;
double newEnd = (deltaX - *zero) / *pixPerSec;
onChangeEnd(newEnd); // EXTERNAL SLOT
// playZone->setMinimumWidth(static_cast<int>((end - start) * *pixPerSec));
// rightSpacer->setMinimumWidth(width() - (*zero + *duration * *pixPerSec) - 3);
}
//void QFrameSelector::onLeftSlideRelease()
//{
// // sliding = false;
//}
//void QFrameSelector::onRightSlideRelease()
//{
// // sliding = false;
//}
void QFrameSelector::onSplitterMove(int pos, int index)
{
// qDebug() << "QFrameSelector::splitterMove " << pos << index;
if (index == 1) {
onSlideLeftSlider(pos);
} else {
onSlideRightSlider(pos);
}
}
void QFrameSelector::onDeleteKeyPose()
{
auto it = keyPoses.find(cursor);
if (it != keyPoses.end()) {
size_t id = static_cast<size_t>(std::distance(keyPoses.begin(), it));
keyPoses.erase(it);
updateCursorSpin();
update();
nbKeyPosesSpin->setValue(static_cast<int>(keyPoses.size()));
emit keyPoseDeleted(id); // EXTERNAL SIGNAL
qDebug() << "\033[35mkeyPoseDeleted(" << id << ")\033[0m";
onSetCursorToNextKeyPose();
}
}
void QFrameSelector::onSetCursorToStart()
{
onChangeCursor(start);
}
void QFrameSelector::onSetCursorToEnd()
{
onChangeCursor(end);
}
void QFrameSelector::onSetCursorToPreviousKeyPose()
{
auto it = keyPoses.rbegin();
while (it != keyPoses.rend() && *it >= cursor)
it++;
if (it != keyPoses.rend()) {
onChangeCursor(*it);
}
}
void QFrameSelector::onSetCursorToNextKeyPose()
{
auto it = keyPoses.begin();
while (it != keyPoses.end() && *it <= cursor)
it++;
if (it != keyPoses.end()) {
onChangeCursor(*it);
}
}
void QFrameSelector::onChangeStartSpin()
{
onChangeStart(startSpin->value());
}
void QFrameSelector::onChangeEndSpin()
{
onChangeEnd(endSpin->value());
}
void QFrameSelector::onChangeCursorSpin()
{
onChangeCursor(cursorSpin->value());
}
void QFrameSelector::onChangeDurationSpin()
{
onChangeDuration(durationSpin->value());
}
// -------------------------- PRIVATE FUNCTIONS -------------------------------
void QFrameSelector::updateCursorSpin()
{
if (keyPoses.find(cursor) != keyPoses.end()) {
cursorSpin->setStyleSheet("background-color: yellow");
removeKeyPoseButton->setEnabled(true);
} else {
cursorSpin->setStyleSheet("background-color: #5555ff");
removeKeyPoseButton->setEnabled(false);
}
cursorSpin->setValue(cursor);
}
void QFrameSelector::updateStartSpin()
{
startSpin->setValue(start);
}
void QFrameSelector::updateEndSpin()
{
endSpin->setValue(end);
}
void QFrameSelector::updateDurationSpin()
{
durationSpin->setValue(*duration);
}
void QFrameSelector::moveKeyPoses(double gap, size_t iFirst)
{
std::set<double> clone;
size_t i = 0;
double first { 0 };
for (double d : keyPoses) {
if (i < iFirst)
clone.insert(d);
else {
if (i == iFirst)
first = d;
clone.insert(d + gap);
}
i++;
}
keyPoses = clone;
double left = (gap > 0) ? (first) : (first + gap);
// emit keyPosesMoved before emitting cursorChanged to render the truly pose on cursor
emit keyPosesMoved(gap, iFirst); // EXTERNAL SIGNAL
qDebug() << "\033[35mkeyPosesMoved(" << gap << ", " << iFirst << ")\033[0m";
if (start >= left) {
// start += gap;
start = qMax(qMin(start + gap, *duration), 0.0);
updateStartSpin();
emit startChanged(start);
qDebug() << "\033[35mstartChanged(" << start << ")\033[0m";
}
if (end >= left) {
// end += gap;
end = qMax(qMin(end + gap, *duration), 0.0);
updateEndSpin();
emit endChanged(end);
qDebug() << "\033[35mendChanged(" << end << ")\033[0m";
}
if (cursor >= left) {
bool cursorOnKeyPose = qAbs(cursor - first) < 1e-5;
cursor = qMax(cursor + gap, 0.0);
updateCursorSpin();
if (!cursorOnKeyPose) {
emit cursorChanged(cursor);
qDebug() << "\033[35mcursorChanged(" << cursor << ")\033[0m";
}
}
update();
}
void QFrameSelector::deleteZone(double time, double time2)
{
double left = qMin(time, time2);
double right = qMax(time, time2);
double dist = right - left;
auto it = keyPoses.begin();
size_t id = 0;
bool first = true;
while (it != keyPoses.end()) {
double keyPose = *it;
if (keyPose >= left) {
keyPoses.erase(it++);
if (keyPose > right) {
if (first) {
emit keyPosesMoved(-dist, id);
qDebug() << "\033[35mkeyPosesMoved(" << -dist << ", " << id << ")\033[0m";
first = false;
}
keyPoses.insert(keyPose - dist);
} else {
emit keyPoseDeleted(id);
qDebug() << "\033[35mkeyPoseDeleted(" << id << ")\033[0m";
}
} else {
++it;
++id;
}
}
nbKeyPosesSpin->setValue(static_cast<int>(keyPoses.size()));
double newStart = qMax(qMax(qMin(start, left), start - dist), 0.0);
if (qAbs(newStart - start) > 1e-5) {
start = newStart;
updateStartSpin();
emit startChanged(start);
qDebug() << "\033[35mstartChanged(" << start << ")\033[0m";
}
double newEnd = qMax(qMax(qMin(end, left), end - dist), 0.0);
if (qAbs(newEnd - end) > 1e-5) {
end = newEnd;
updateEndSpin();
emit endChanged(end);
qDebug() << "\033[35mendChanged(" << end << ")\033[0m";
}
update();
}
void QFrameSelector::setSplitter(QSplitter* splitter)
{
m_splitter = splitter;
}
void QFrameSelector::setRightSpacer(QFrame* value)
{
rightSpacer = value;
}
void QFrameSelector::redrawPlayZone()
{
QList<int> sizes = m_splitter->sizes();
sizes[0] = *zero + start * *pixPerSec - 3;
sizes[1] = (end - start) * *pixPerSec - 3;
sizes[2] = width() - sizes[0] - sizes[1] - 3 - 3 - 3 - 4;
// sizes[2] = 0;
m_splitter->setSizes(sizes);
// m_splitter->setSizes({100, 100});
// leftSpacer->resize(*zero + start * *pixPerSec, h);
// leftSpacer->setMinimumWidth(static_cast<int>(*zero + start * *pixPerSec - leftSlider->width()));
// leftSpacer->setMinimumWidth(static_cast<int>(*zero + start * *pixPerSec));
// playZone->setMinimumWidth(static_cast<int>((end - start) * *pixPerSec));
}
// -------------------------- GETTERS -----------------------------------------
double QFrameSelector::getStart() const
{
return start;
}
double* QFrameSelector::getStart()
{
return &start;
}
double* QFrameSelector::getEnd()
{
return &end;
}
double* QFrameSelector::getCursor()
{
return &cursor;
}
double QFrameSelector::getEnd() const
{
return end;
}
double QFrameSelector::getCursor() const
{
return cursor;
}
int QFrameSelector::getNbKeyPoses() const
{
return static_cast<int>(keyPoses.size());
}
double QFrameSelector::getKeyPose(int id) const
{
auto it = keyPoses.begin();
while (it != keyPoses.end() && id-- > 0)
it++;
return *it;
}
std::set<double> QFrameSelector::getKeyPoses() const
{
return keyPoses;
}
std::set<double>* QFrameSelector::getKeyPoses()
{
return &keyPoses;
}
// -------------------------- SETTERS -----------------------------------------
void QFrameSelector::setCursor(double time)
{
cursor = time;
}
void QFrameSelector::setKeyPoses(const std::set<double>& value)
{
keyPoses = value;
}
void QFrameSelector::setShiftDown(bool* value)
{
shiftDown = value;
}
void QFrameSelector::setStart(double value)
{
start = value;
}
void QFrameSelector::setEnd(double value)
{
end = value;
}
void QFrameSelector::setDuration(double time)
{
*duration = time;
}
//
// -------------------------- REFERENCES SETTERS ------------------------------
void QFrameSelector::setLeftSpacer(QFrame* value)
{
leftSpacer = value;
}
//void QFrameSelector::setLeftSlider(QWidget* value)
//{
// leftSlider = value;
//}
void QFrameSelector::setPlayZone(QFrame* value)
{
playZone = value;
}
//void QFrameSelector::setRightSlider(QWidget* value)
//{
// rightSlider = value;
//}
//
void QFrameSelector::setCursorSpin(QDoubleSpinBox* value)
{
cursorSpin = value;
}
void QFrameSelector::setStartSpin(QDoubleSpinBox* value)
{
startSpin = value;
}
void QFrameSelector::setEndSpin(QDoubleSpinBox* value)
{
endSpin = value;
}
void QFrameSelector::setDurationSpin(QDoubleSpinBox* value)
{
durationSpin = value;
}
void QFrameSelector::setRemoveKeyPoseButton(QToolButton* value)
{
removeKeyPoseButton = value;
}
void QFrameSelector::setStartInc(QDoubleSpinBox* value)
{
startInc = value;
}
void QFrameSelector::setEndInc(QDoubleSpinBox* value)
{
endInc = value;
}
void QFrameSelector::setNbKeyPosesSpin(QSpinBox* value)
{
nbKeyPosesSpin = value;
}
void QFrameSelector::setCtrlDown(bool* value)
{
ctrlDown = value;
}
void QFrameSelector::setMidMouseDown(bool* value)
{
midMouseDown = value;
}
| 26.260513
| 106
| 0.544798
|
hiergaut
|
ea7ef91e43c7ad49d69ea19df26f6d58aa1b27e7
| 320
|
cpp
|
C++
|
etc/dp/e/main.cpp
|
wotsushi/competitive-programming
|
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
|
[
"MIT"
] | 3
|
2019-06-25T06:17:38.000Z
|
2019-07-13T15:18:51.000Z
|
etc/dp/e/main.cpp
|
wotsushi/competitive-programming
|
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
|
[
"MIT"
] | null | null | null |
etc/dp/e/main.cpp
|
wotsushi/competitive-programming
|
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
|
[
"MIT"
] | null | null | null |
#include "template.hpp"
int main() {
ll(N, W);
vll(w, v, N);
ll V = 0;
each(v_i, v) { V += v_i; }
vi dp(V + 1, INF);
dp[0] = 0;
rep(i, N) {
rrepi(j, v[i], V) { chmin(dp[j], dp[j - v[i]] + w[i]); }
}
ll ans;
rrepi(i, V) {
if (dp[i] <= W) {
ans = i;
break;
}
}
out(ans);
}
| 14.545455
| 60
| 0.39375
|
wotsushi
|
ea82bf3e4bb249a5a22a064af19e62a15d4f2315
| 786
|
cpp
|
C++
|
src/fixie_lib/scissor_state.cpp
|
vonture/fixie
|
7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc
|
[
"MIT"
] | 7
|
2015-01-09T22:08:17.000Z
|
2021-10-12T10:32:58.000Z
|
src/fixie_lib/scissor_state.cpp
|
vonture/fixie
|
7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc
|
[
"MIT"
] | 1
|
2015-08-19T07:51:53.000Z
|
2015-08-19T07:51:53.000Z
|
src/fixie_lib/scissor_state.cpp
|
vonture/fixie
|
7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc
|
[
"MIT"
] | 5
|
2015-08-20T07:10:23.000Z
|
2022-03-24T07:09:10.000Z
|
#include "fixie_lib/scissor_state.hpp"
#include "fixie/fixie_gl_es.h"
namespace fixie
{
scissor_state::scissor_state()
: _scissor_test_enabled()
, _scissor()
{
}
GLboolean& scissor_state::scissor_test_enabled()
{
return _scissor_test_enabled;
}
const GLboolean& scissor_state::scissor_test_enabled() const
{
return _scissor_test_enabled;
}
rectangle& scissor_state::scissor()
{
return _scissor;
}
const rectangle& scissor_state::scissor() const
{
return _scissor;
}
scissor_state default_scissor_state()
{
scissor_state state;
state.scissor_test_enabled() = GL_FALSE;
state.scissor() = rectangle(0, 0, 1, 1);
return state;
}
}
| 19.170732
| 64
| 0.62341
|
vonture
|
ea84a60365ee50a2b2c4dac3f1daee10fe1e80e3
| 1,073
|
cpp
|
C++
|
runtime/test/strconv_test.cpp
|
cpp-openapi/runtime
|
18fe7995b810617e8176f84e1bfe1138414e5e1c
|
[
"Apache-2.0"
] | null | null | null |
runtime/test/strconv_test.cpp
|
cpp-openapi/runtime
|
18fe7995b810617e8176f84e1bfe1138414e5e1c
|
[
"Apache-2.0"
] | null | null | null |
runtime/test/strconv_test.cpp
|
cpp-openapi/runtime
|
18fe7995b810617e8176f84e1bfe1138414e5e1c
|
[
"Apache-2.0"
] | null | null | null |
#include "gtest/gtest.h"
#include "openapi/runtime/strconv.h"
#include "openapi/runtime/string.h"
TEST(StrConv_test, basic) {
#ifdef OPENAPI_UTF16_STRINGS
// std::mbstate_t state = std::mbstate_t();
// std::size_t size;
// const char * buf = "";
// ::mbsrtowcs_s(&size, nullptr, 0 /*dst max size*/, &buf, 0, &state);
// ASSERT_EQ(1, size); // counts the null terminator
// const char * mbstr = "hi";
// std::mbstate_t state = std::mbstate_t();
// std::size_t size = std::mbsrtowcs(nullptr, &mbstr, 0, &state);
// ASSERT_EQ(2, size);
ASSERT_EQ(L"", openapi::StringT(""));
ASSERT_EQ(L"hi", openapi::StringT("hi"));
ASSERT_EQ(std::string(""), openapi::ToStdString(L""));
ASSERT_EQ(std::string("hi"), openapi::ToStdString(L"hi"));
#else
ASSERT_EQ("", openapi::StringT(""));
ASSERT_EQ("hi", openapi::StringT("hi"));
ASSERT_EQ(std::string(""), openapi::ToStdString(""));
ASSERT_EQ(std::string("hi"), openapi::ToStdString("hi"));
#endif
}
| 34.612903
| 78
| 0.579683
|
cpp-openapi
|
ea8cdd0c242453cf65d1d3697f8544cd3e07477f
| 588
|
cpp
|
C++
|
Blaze/libraries.cpp
|
Star-Athenaeum/Blaze
|
73f26316e4146596aeb82f77d054cf4e472a2d3d
|
[
"MIT"
] | 1
|
2021-09-29T21:54:54.000Z
|
2021-09-29T21:54:54.000Z
|
Blaze/libraries.cpp
|
Star-Athenaeum/Blaze
|
73f26316e4146596aeb82f77d054cf4e472a2d3d
|
[
"MIT"
] | 44
|
2020-04-17T14:39:36.000Z
|
2020-10-14T04:15:48.000Z
|
Blaze/libraries.cpp
|
Stryxus/Blaze
|
73f26316e4146596aeb82f77d054cf4e472a2d3d
|
[
"MIT"
] | 1
|
2020-09-30T22:56:48.000Z
|
2020-09-30T22:56:48.000Z
|
#include "pch.hpp"
#include "libraries.hpp"
map<string, HMODULE> modules;
void load_libraries(vector<string> library_names)
{
for (string name : library_names)
{
HMODULE m = LoadLibrary(string_to_wstring_copy(name).c_str());
if (m == NULL) Logger::log_last_error();
else modules.emplace(name, m);
}
}
HMODULE get_library(string lib_name)
{
return modules[lib_name];
}
void* get_lib_function(HMODULE lib, string function_name)
{
return (void*)GetProcAddress(lib, function_name.c_str());
}
void free_libraries()
{
for (auto const& [key, val] : modules) FreeLibrary(val);
}
| 20.275862
| 64
| 0.727891
|
Star-Athenaeum
|
ea92a1e17b927a42fa4c3f85a4bf6b4c7f722b71
| 13,160
|
cpp
|
C++
|
AppleIntelWifiAdapter/IWLCtxtInfo.cpp
|
AppleIntelWifi/adapter
|
49698895ab94563de1cff4e9cd6b0c62ca933bc1
|
[
"BSD-3-Clause"
] | 584
|
2020-02-21T23:49:49.000Z
|
2022-03-10T01:49:41.000Z
|
AppleIntelWifiAdapter/IWLCtxtInfo.cpp
|
AppleIntelWifi/adapter
|
49698895ab94563de1cff4e9cd6b0c62ca933bc1
|
[
"BSD-3-Clause"
] | 76
|
2020-02-21T22:48:05.000Z
|
2020-09-24T09:08:36.000Z
|
AppleIntelWifiAdapter/IWLCtxtInfo.cpp
|
AppleIntelWifi/adapter
|
49698895ab94563de1cff4e9cd6b0c62ca933bc1
|
[
"BSD-3-Clause"
] | 64
|
2020-02-23T05:25:44.000Z
|
2022-02-28T19:48:59.000Z
|
//
// IWLCtxtInfo.cpp
// AppleIntelWifiAdapter
//
// Created by 钟先耀 on 2020/2/9.
// Copyright © 2020 IntelWifi for MacOS authors. All rights reserved.
//
#include "IWLCtxtInfo.hpp"
static void *iwl_pcie_ctxt_info_dma_alloc_coherent(IWLTransport *trans,
size_t size,
dma_addr_t *phys,
iwl_dma_ptr **ptr) {
iwl_dma_ptr *buf = allocate_dma_buf(size, trans->dma_mask);
if (!buf) {
return NULL;
}
*ptr = buf;
*phys = buf->dma;
return buf->addr;
}
int IWLTransport::iwl_pcie_ctxt_info_init(const struct fw_img *fw) {
IWL_INFO(0, "iwl_pcie_ctxt_info_init\n");
struct iwl_context_info *ctxt_info;
struct iwl_context_info_rbd_cfg *rx_cfg;
u32 control_flags = 0, rb_size;
dma_addr_t phys;
int ret;
ctxt_info = (struct iwl_context_info *)iwl_pcie_ctxt_info_dma_alloc_coherent(
this, sizeof(*ctxt_info), &phys, &this->ctxt_info_dma_ptr);
if (!ctxt_info) return -ENOMEM;
this->ctxt_info_dma_addr = phys;
ctxt_info->version.version = 0;
ctxt_info->version.mac_id = cpu_to_le16((u16)iwlRead32(CSR_HW_REV));
/* size is in DWs */
ctxt_info->version.size = cpu_to_le16(sizeof(*ctxt_info) / 4);
switch (this->rx_buf_size) {
case IWL_AMSDU_2K:
rb_size = IWL_CTXT_INFO_RB_SIZE_2K;
break;
case IWL_AMSDU_4K:
rb_size = IWL_CTXT_INFO_RB_SIZE_4K;
break;
case IWL_AMSDU_8K:
rb_size = IWL_CTXT_INFO_RB_SIZE_8K;
break;
case IWL_AMSDU_12K:
rb_size = IWL_CTXT_INFO_RB_SIZE_12K;
break;
default:
WARN_ON(1);
rb_size = IWL_CTXT_INFO_RB_SIZE_4K;
}
// TODO two function are not known to convert...
// WARN_ON(RX_QUEUE_CB_SIZE(m_pDevice->cfg->num_rbds) > 12);
// control_flags = IWL_CTXT_INFO_TFD_FORMAT_LONG;
// control_flags |=
// u32_encode_bits(RX_QUEUE_CB_SIZE(m_pDevice->cfg->num_rbds),
// IWL_CTXT_INFO_RB_CB_SIZE);
// control_flags |= u32_encode_bits(rb_size, IWL_CTXT_INFO_RB_SIZE);
// ctxt_info->control.control_flags = cpu_to_le32(control_flags);
/* initialize RX default queue */
rx_cfg = &ctxt_info->rbd_cfg;
rx_cfg->free_rbd_addr = cpu_to_le64(this->rxq->bd_dma);
rx_cfg->used_rbd_addr = cpu_to_le64(this->rxq->used_bd_dma);
rx_cfg->status_wr_ptr = cpu_to_le64(this->rxq->rb_stts_dma);
/* initialize TX command queue */
// ctxt_info->hcmd_cfg.cmd_queue_addr =
// cpu_to_le64(this->txq[this->cmd_queue]->dma_addr);
ctxt_info->hcmd_cfg.cmd_queue_size = 1;
// ctxt_info->hcmd_cfg.cmd_queue_size =
// TFD_QUEUE_CB_SIZE(IWL_CMD_QUEUE_SIZE);
/* allocate ucode sections in dram and set addresses */
ret = iwl_pcie_init_fw_sec(fw, &ctxt_info->dram);
if (ret) {
free_dma_buf(this->ctxt_info_dma_ptr);
this->ctxt_info_dma_ptr = NULL;
this->ctxt_info = NULL;
this->ctxt_info_dma_addr = NULL;
return ret;
}
this->ctxt_info = ctxt_info;
iwl_enable_fw_load_int_ctx_info();
/* kick FW self load */
iwlWrite64(CSR_CTXT_INFO_BA, this->ctxt_info_dma_addr);
iwlWritePRPH(UREG_CPU_INIT_RUN, 1);
/* Context info will be released upon alive or failure to get one */
return 0;
}
int IWLTransport::iwl_pcie_ctxt_info_gen3_init(const struct fw_img *fw) {
IWL_INFO(0, "iwl_pcie_ctxt_info_gen3_init\n");
struct iwl_context_info_gen3 *ctxt_info_gen3;
struct iwl_prph_scratch *prph_scratch;
struct iwl_prph_scratch_ctrl_cfg *prph_sc_ctrl;
struct iwl_prph_info *prph_info;
void *iml_img;
u32 control_flags = 0;
int ret;
int cmdq_size = max_t(u32, IWL_CMD_QUEUE_SIZE, m_pDevice->cfg->min_txq_size);
/* Allocate prph scratch */
iwl_dma_ptr *buf = allocate_dma_buf(sizeof(*prph_scratch), this->dma_mask);
if (!buf) {
return -ENOMEM;
}
this->prph_scratch_dma_ptr = buf;
prph_scratch = (struct iwl_prph_scratch *)buf->addr;
this->prph_scratch_dma_addr = buf->dma;
prph_sc_ctrl = &prph_scratch->ctrl_cfg;
prph_sc_ctrl->version.version = 0;
prph_sc_ctrl->version.mac_id = cpu_to_le16((u16)iwlRead32(CSR_HW_REV));
prph_sc_ctrl->version.size = cpu_to_le16(sizeof(*prph_scratch) / 4);
control_flags = IWL_PRPH_SCRATCH_RB_SIZE_4K | IWL_PRPH_SCRATCH_MTR_MODE |
(IWL_PRPH_MTR_FORMAT_256B & IWL_PRPH_SCRATCH_MTR_FORMAT);
/* initialize RX default queue */
prph_sc_ctrl->rbd_cfg.free_rbd_addr = cpu_to_le64(this->rxq->bd_dma);
// iwl_pcie_ctxt_info_dbg_enable(trans, &prph_sc_ctrl->hwm_cfg,
// &control_flags);
prph_sc_ctrl->control.control_flags = cpu_to_le32(control_flags);
/* allocate ucode sections in dram and set addresses */
ret = iwl_pcie_init_fw_sec(fw, &prph_scratch->dram);
if (ret) goto err_free_prph_scratch;
buf = allocate_dma_buf(sizeof(*prph_info), this->dma_mask);
if (!buf) {
ret = -ENOMEM;
goto err_free_prph_scratch;
}
this->prph_info_dma_ptr = buf;
prph_info = (struct iwl_prph_info *)buf->addr;
prph_info_dma_addr = buf->dma;
/* Allocate context info */
buf = allocate_dma_buf(sizeof(*ctxt_info_gen3), this->dma_mask);
if (!buf) {
ret = -ENOMEM;
goto err_free_prph_info;
}
this->ctxt_info_dma_ptr = buf;
ctxt_info_gen3 = (struct iwl_context_info_gen3 *)buf->addr;
ctxt_info_dma_addr = buf->dma;
ctxt_info_gen3->prph_info_base_addr = cpu_to_le64(this->prph_info_dma_addr);
ctxt_info_gen3->prph_scratch_base_addr =
cpu_to_le64(this->prph_scratch_dma_addr);
ctxt_info_gen3->prph_scratch_size = cpu_to_le32(sizeof(*prph_scratch));
ctxt_info_gen3->cr_head_idx_arr_base_addr =
cpu_to_le64(this->rxq->rb_stts_dma);
ctxt_info_gen3->tr_tail_idx_arr_base_addr =
cpu_to_le64(this->rxq->tr_tail_dma);
ctxt_info_gen3->cr_tail_idx_arr_base_addr =
cpu_to_le64(this->rxq->cr_tail_dma);
ctxt_info_gen3->cr_idx_arr_size = cpu_to_le16(IWL_NUM_OF_COMPLETION_RINGS);
ctxt_info_gen3->tr_idx_arr_size = cpu_to_le16(IWL_NUM_OF_TRANSFER_RINGS);
ctxt_info_gen3->mtr_base_addr =
cpu_to_le64(this->txq[this->cmd_queue]->dma_addr);
ctxt_info_gen3->mcr_base_addr = cpu_to_le64(this->rxq->used_bd_dma);
// TODO
// ctxt_info_gen3->mtr_size =
// cpu_to_le16(TFD_QUEUE_CB_SIZE(cmdq_size));
// ctxt_info_gen3->mcr_size =
// cpu_to_le16(RX_QUEUE_CB_SIZE(m_pDevice->cfg->num_rbds));
this->ctxt_info_gen3 = ctxt_info_gen3;
this->prph_info = prph_info;
this->prph_scratch = prph_scratch;
/* Allocate IML */
buf = allocate_dma_buf(m_pDevice->fw.iml_len, this->dma_mask);
if (!buf) {
return -ENOMEM;
}
this->iml_dma_ptr = buf;
iml_img = buf->addr;
this->iml_dma_addr = buf->dma;
memcpy(iml_img, m_pDevice->fw.iml, m_pDevice->fw.iml_len);
iwl_enable_fw_load_int_ctx_info();
/* kick FW self load */
iwlWrite64(CSR_CTXT_INFO_ADDR, this->ctxt_info_dma_addr);
iwlWrite64(CSR_IML_DATA_ADDR, this->iml_dma_addr);
iwlWrite32(CSR_IML_SIZE_ADDR, m_pDevice->fw.iml_len);
setBit(CSR_CTXT_INFO_BOOT_CTRL, CSR_AUTO_FUNC_BOOT_ENA);
if (m_pDevice->cfg->trans.device_family >= IWL_DEVICE_FAMILY_AX210)
iwlWriteUmacPRPH(UREG_CPU_INIT_RUN, 1);
else
setBit(CSR_GP_CNTRL, CSR_AUTO_FUNC_INIT);
return 0;
err_free_prph_info:
free_dma_buf(this->prph_info_dma_ptr);
this->prph_info_dma_ptr = NULL;
err_free_prph_scratch:
free_dma_buf(this->prph_scratch_dma_ptr);
this->prph_scratch_dma_ptr = NULL;
return ret;
}
void IWLTransport::iwl_pcie_ctxt_info_gen3_free() {
if (!this->ctxt_info_gen3) return;
free_dma_buf(this->ctxt_info_dma_ptr);
this->ctxt_info_dma_ptr = NULL;
this->ctxt_info_dma_addr = 0;
this->ctxt_info_gen3 = NULL;
iwl_pcie_ctxt_info_free_fw_img();
free_dma_buf(this->prph_scratch_dma_ptr);
this->prph_scratch_dma_ptr = NULL;
this->prph_scratch_dma_addr = 0;
this->prph_scratch = NULL;
free_dma_buf(this->prph_info_dma_ptr);
this->prph_info_dma_ptr = NULL;
this->prph_info_dma_addr = 0;
this->prph_info = NULL;
}
void IWLTransport::iwl_enable_fw_load_int_ctx_info() {
IWL_INFO(trans, "Enabling ALIVE interrupt only, msix_enabled=%s\n",
this->msix_enabled ? "true" : "false");
if (!this->msix_enabled) {
/*
* When we'll receive the ALIVE interrupt, the ISR will call
* iwl_enable_fw_load_int_ctx_info again to set the ALIVE
* interrupt (which is not really needed anymore) but also the
* RX interrupt which will allow us to receive the ALIVE
* notification (which is Rx) and continue the flow.
*/
this->inta_mask = CSR_INT_BIT_ALIVE | CSR_INT_BIT_FH_RX;
iwlWrite32(CSR_INT_MASK, this->inta_mask);
} else {
enableHWIntrMskMsix(MSIX_HW_INT_CAUSES_REG_ALIVE);
/*
* Leave all the FH causes enabled to get the ALIVE
* notification.
*/
enableFHIntrMskMsix(this->fh_init_mask);
}
}
int IWLTransport::iwl_pcie_get_num_sections(const struct fw_img *fw,
int start) {
int i = 0;
while (start < fw->num_sec &&
fw->sec[start].offset != CPU1_CPU2_SEPARATOR_SECTION &&
fw->sec[start].offset != PAGING_SEPARATOR_SECTION) {
start++;
i++;
}
return i;
}
static int iwl_pcie_ctxt_info_alloc_dma(IWLTransport *trans,
const struct fw_desc *sec,
struct iwl_dram_data *dram) {
dram->block = iwl_pcie_ctxt_info_dma_alloc_coherent(
trans, sec->len, &dram->physical, &dram->physical_ptr);
if (!dram->block) return -ENOMEM;
dram->size = sec->len;
memcpy(dram->block, sec->data, sec->len);
return 0;
}
int IWLTransport::iwl_pcie_init_fw_sec(
const struct fw_img *fw, struct iwl_context_info_dram *ctxt_dram) {
int i, ret, lmac_cnt, umac_cnt, paging_cnt;
struct iwl_self_init_dram *dram = &this->init_dram;
if (dram->paging) {
IWL_ERR(0, "paging shouldn't already be initialized (%d pages)\n",
dram->paging_cnt);
iwl_pcie_ctxt_info_free_paging();
}
lmac_cnt = iwl_pcie_get_num_sections(fw, 0);
/* add 1 due to separator */
umac_cnt = iwl_pcie_get_num_sections(fw, lmac_cnt + 1);
/* add 2 due to separators */
paging_cnt = iwl_pcie_get_num_sections(fw, lmac_cnt + umac_cnt + 2);
dram->fw =
(struct iwl_dram_data *)kcalloc(umac_cnt + lmac_cnt, sizeof(*dram->fw));
if (!dram->fw) return -ENOMEM;
dram->paging =
(struct iwl_dram_data *)kcalloc(paging_cnt, sizeof(*dram->paging));
if (!dram->paging) return -ENOMEM;
/* initialize lmac sections */
for (i = 0; i < lmac_cnt; i++) {
ret = iwl_pcie_ctxt_info_alloc_dma(this, &fw->sec[i],
&dram->fw[dram->fw_cnt]);
if (ret) return ret;
ctxt_dram->lmac_img[i] = cpu_to_le64(dram->fw[dram->fw_cnt].physical);
dram->fw_cnt++;
}
/* initialize umac sections */
for (i = 0; i < umac_cnt; i++) {
/* access FW with +1 to make up for lmac separator */
ret = iwl_pcie_ctxt_info_alloc_dma(this, &fw->sec[dram->fw_cnt + 1],
&dram->fw[dram->fw_cnt]);
if (ret) return ret;
ctxt_dram->umac_img[i] = cpu_to_le64(dram->fw[dram->fw_cnt].physical);
dram->fw_cnt++;
}
/*
* Initialize paging.
* Paging memory isn't stored in dram->fw as the umac and lmac - it is
* stored separately.
* This is since the timing of its release is different -
* while fw memory can be released on alive, the paging memory can be
* freed only when the device goes down.
* Given that, the logic here in accessing the fw image is a bit
* different - fw_cnt isn't changing so loop counter is added to it.
*/
for (i = 0; i < paging_cnt; i++) {
/* access FW with +2 to make up for lmac & umac separators */
int fw_idx = dram->fw_cnt + i + 2;
ret =
iwl_pcie_ctxt_info_alloc_dma(this, &fw->sec[fw_idx], &dram->paging[i]);
if (ret) return ret;
ctxt_dram->virtual_img[i] = cpu_to_le64(dram->paging[i].physical);
dram->paging_cnt++;
}
return 0;
}
void IWLTransport::iwl_pcie_ctxt_info_free() {
struct iwl_self_init_dram *dram = &this->init_dram;
int i;
if (!dram->paging) {
WARN_ON(dram->paging_cnt);
return;
}
/* free paging*/
for (i = 0; i < dram->paging_cnt; i++) {
free_dma_buf(dram->paging[i].physical_ptr);
}
// IOFree(dram->paging, sizeof(*dram->paging));
dram->paging_cnt = 0;
dram->paging = NULL;
}
void IWLTransport::iwl_pcie_ctxt_info_free_paging() {
struct iwl_self_init_dram *dram = &this->init_dram;
int i;
if (!dram->paging) {
WARN_ON(dram->paging_cnt);
return;
}
/* free paging*/
for (i = 0; i < dram->paging_cnt; i++) {
free_dma_buf(dram->paging[i].physical_ptr);
}
// IOFree(dram->paging, sizeof(*dram->paging));
dram->paging_cnt = 0;
dram->paging = NULL;
}
void IWLTransport::iwl_pcie_ctxt_info_free_fw_img() {
struct iwl_self_init_dram *dram = &this->init_dram;
int i;
if (!dram->fw) {
WARN_ON(dram->fw_cnt);
return;
}
for (i = 0; i < dram->fw_cnt; i++) {
free_dma_buf(dram->fw[i].physical_ptr);
}
// IOFree(dram->fw, sizeof(*dram->fw));
dram->fw_cnt = 0;
dram->fw = NULL;
}
| 32.9
| 79
| 0.681991
|
AppleIntelWifi
|
ea93c088163c57819b7349170eab9d1ae2c6842d
| 1,808
|
cpp
|
C++
|
libgputk/gputkInit.cpp
|
xlmentx/Parallel-Computing
|
0785f18afaabd5daf2efd89607f643845a07b3c0
|
[
"MIT"
] | null | null | null |
libgputk/gputkInit.cpp
|
xlmentx/Parallel-Computing
|
0785f18afaabd5daf2efd89607f643845a07b3c0
|
[
"MIT"
] | null | null | null |
libgputk/gputkInit.cpp
|
xlmentx/Parallel-Computing
|
0785f18afaabd5daf2efd89607f643845a07b3c0
|
[
"MIT"
] | null | null | null |
#include "gputk.h"
#define MB (1 << 20)
#ifndef GPUTK_DEFAULT_HEAP_SIZE
#define GPUTK_DEFAULT_HEAP_SIZE (1024 * MB)
#endif /* GPUTK_DEFAULT_HEAP_SIZE */
static bool _initializedQ = gpuTKFalse;
#ifndef GPUTK_USE_WINDOWS
//__attribute__((__constructor__))
#endif /* GPUTK_USE_WINDOWS */
void gpuTK_init(int *
#ifdef GPUTK_USE_MPI
argc
#endif /* GPUTK_USE_MPI */
,
char ***
#ifdef GPUTK_USE_MPI
argv
#endif /* GPUTK_USE_MPI */
) {
if (_initializedQ == gpuTKTrue) {
return;
}
#ifdef GPUTK_USE_MPI
gpuTKMPI_Init(argc, argv);
#endif /* GPUTK_USE_MPI */
_envSessionId();
#ifdef GPUTK_USE_CUDA
CUresult err = cuInit(0);
/* Select a random GPU */
#ifdef GPUTK_USE_MPI
if (rankCount() > 1) {
int deviceCount;
cudaGetDeviceCount(&deviceCount);
srand(time(NULL));
cudaSetDevice(gpuTKMPI_getRank() % deviceCount);
} else {
int deviceCount;
cudaGetDeviceCount(&deviceCount);
srand(time(NULL));
cudaSetDevice(rand() % deviceCount);
}
#else
{
int deviceCount;
cudaGetDeviceCount(&deviceCount);
srand(time(NULL));
cudaSetDevice(rand() % deviceCount);
}
#endif /* GPUTK_USE_MPI */
cudaDeviceSetLimit(cudaLimitPrintfFifoSize, 1 * MB);
cudaDeviceSetLimit(cudaLimitMallocHeapSize, GPUTK_DEFAULT_HEAP_SIZE);
cudaDeviceSynchronize();
#endif /* GPUTK_USE_CUDA */
#ifdef GPUTK_USE_WINDOWS
QueryPerformanceFrequency((LARGE_INTEGER *)&_hrtime_frequency);
#endif /* _MSC_VER */
_hrtime();
_timer = gpuTKTimer_new();
_logger = gpuTKLogger_new();
_initializedQ = gpuTKTrue;
gpuTKFile_init();
solutionJSON = nullptr;
#ifdef GPUTK_USE_MPI
atexit(gpuTKMPI_Exit);
#else /* GPUTK_USE_MPI */
atexit(gpuTK_atExit);
#endif /* GPUTK_USE_MPI */
}
| 20.781609
| 71
| 0.679204
|
xlmentx
|
ea98b93a2f0f147d7fb42ce52316638ba5487bfa
| 2,553
|
cpp
|
C++
|
126_findLadders.cpp
|
imxiaobo/leetcode-solutions
|
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
|
[
"MIT"
] | null | null | null |
126_findLadders.cpp
|
imxiaobo/leetcode-solutions
|
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
|
[
"MIT"
] | null | null | null |
126_findLadders.cpp
|
imxiaobo/leetcode-solutions
|
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord,
unordered_set<string> &wordList) {
if (beginWord == endWord)
return {{endWord}};
unordered_map<string, vector<string>> graph;
vector<vector<string>> paths;
unordered_set<string> forward{beginWord};
unordered_set<string> backward{endWord};
if (buildGraphBDS(forward, backward, wordList, graph, true)) {
vector<string> path;
getPathsDFS(beginWord, endWord, graph, path, paths);
}
return paths;
}
bool buildGraphBDS(unordered_set<string> &forward,
unordered_set<string> &backward,
unordered_set<string> &wordList,
unordered_map<string, vector<string>> &graph,
bool forwardDirection) {
if (forward.size() > backward.size()) {
swap(forward, backward);
forwardDirection = !forwardDirection;
}
if (forward.empty())
return false;
for (const auto &w : forward)
wordList.erase(w);
for (const auto &w : backward)
wordList.erase(w);
unordered_set<string> next;
bool connect = false;
for (const string &word : forward) {
string nextWord(word);
for (int idx = 0; idx < nextWord.size(); ++idx) {
char original = nextWord[idx];
for (char c = 'a'; c <= 'z'; ++c) {
nextWord[idx] = c;
if (backward.find(nextWord) != backward.end()) {
connect = true;
forwardDirection ? graph[word].push_back(nextWord)
: graph[nextWord].push_back(word);
} else if (!connect && wordList.find(nextWord) != wordList.end()) {
next.insert(nextWord);
forwardDirection ? graph[word].push_back(nextWord)
: graph[nextWord].push_back(word);
}
}
nextWord[idx] = original;
}
}
swap(forward, next);
return connect ||
buildGraphBDS(forward, backward, wordList, graph, forwardDirection);
}
void getPathsDFS(const string &beginWord, const string &endWord,
unordered_map<string, vector<string>> &graph,
vector<string> &path, vector<vector<string>> &allPaths) {
path.push_back(beginWord);
if (beginWord == endWord)
allPaths.push_back(path);
else {
for (const auto &v : graph[beginWord])
getPathsDFS(v, endWord, graph, path, allPaths);
}
path.pop_back();
}
};
| 31.134146
| 79
| 0.57736
|
imxiaobo
|
ea9984b575b3db09626312274a2bd661cd42ba53
| 3,977
|
cpp
|
C++
|
src/notifycontroller_mobike_supported.cpp
|
OpenIKEv2/libopenikev2_impl
|
3c620ca479b20814fe42325cffcfd1d18dbf041c
|
[
"Apache-2.0"
] | 3
|
2017-03-03T17:05:37.000Z
|
2020-06-16T04:50:40.000Z
|
src/notifycontroller_mobike_supported.cpp
|
OpenIKEv2/libopenikev2_impl
|
3c620ca479b20814fe42325cffcfd1d18dbf041c
|
[
"Apache-2.0"
] | 11
|
2017-02-27T09:31:17.000Z
|
2020-03-20T16:31:05.000Z
|
src/notifycontroller_mobike_supported.cpp
|
OpenIKEv2/libopenikev2_impl
|
3c620ca479b20814fe42325cffcfd1d18dbf041c
|
[
"Apache-2.0"
] | null | null | null |
/***************************************************************************
* Copyright (C) 2005 by *
* Alejandro Perez Mendez alex@um.es *
* Pedro J. Fernandez Ruiz pedroj@um.es *
* *
* This software may be modified and distributed under the terms *
* of the Apache license. See the LICENSE file for details. *
***************************************************************************/
#include "notifycontroller_mobike_supported.h"
#include <libopenikev2/log.h>
#include <libopenikev2/boolattribute.h>
namespace openikev2 {
NotifyController_MOBIKE_SUPPORTED::NotifyController_MOBIKE_SUPPORTED()
: NotifyController() {}
NotifyController_MOBIKE_SUPPORTED::~NotifyController_MOBIKE_SUPPORTED() {}
IkeSa::NOTIFY_ACTION NotifyController_MOBIKE_SUPPORTED::processNotify( Payload_NOTIFY & notify, Message & message, IkeSa & ike_sa, ChildSa * child_sa ) {
assert( notify.notification_type == ( Payload_NOTIFY::NOTIFY_TYPE ) 16396 );
// Check notify field correction
if ( notify.protocol_id > Enums::PROTO_IKE || notify.spi_value.get() || notify.notification_data.get() ) {
Log::writeLockedMessage( ike_sa.getLogId(), "INVALID SYNTAX in MOBIKE_SUPPORTED notify. Omitting notify", Log::LOG_ERRO, true );
return IkeSa::NOTIFY_ACTION_CONTINUE;
}
if ( message.exchange_type != Message::IKE_AUTH ) {
Log::writeMessage( ike_sa.getLogId(), "MOBIKE_SUPPORTED notification received in invalid message. Omitting notify", Log::LOG_ERRO, true );
return IkeSa::NOTIFY_ACTION_CONTINUE;
}
// If message is a request
if ( message.message_type == Message::REQUEST ) {
BoolAttribute * attribute = ike_sa.getIkeSaConfiguration().attributemap->getAttribute<BoolAttribute>( "mobike_supported" );
if ( attribute == NULL || !attribute->value ) {
Log::writeMessage( ike_sa.getLogId(), "MOBIKE is not allowed", Log::LOG_WARN, true );
return IkeSa::NOTIFY_ACTION_CONTINUE;
}
Log::writeMessage( ike_sa.getLogId(), "MOBIKE is enabled for this IKE_SA", Log::LOG_INFO, true );
ike_sa.getIkeSaConfiguration().attributemap->addAttribute ( "mobike_enabled", auto_ptr<Attribute> ( new BoolAttribute( true ) ) );
return IkeSa::NOTIFY_ACTION_CONTINUE;
}
// if message is a response
else {
BoolAttribute* attribute = ike_sa.getIkeSaConfiguration().attributemap->getAttribute<BoolAttribute>( "mobike_supported" );
if ( attribute == NULL || !attribute->value ) {
Log::writeMessage( ike_sa.getLogId(), "MOBIKE processing is not allowed", Log::LOG_WARN, true );
return IkeSa::NOTIFY_ACTION_CONTINUE;
}
Log::writeMessage( ike_sa.getLogId(), "MOBIKE is enabled for this IKE_SA", Log::LOG_INFO, true );
ike_sa.getIkeSaConfiguration().attributemap->addAttribute ( "mobike_enabled", auto_ptr<Attribute> ( new BoolAttribute( true ) ) );
return IkeSa::NOTIFY_ACTION_CONTINUE;
}
return IkeSa::NOTIFY_ACTION_CONTINUE;
}
void NotifyController_MOBIKE_SUPPORTED::addNotify( Message & message, IkeSa & ike_sa, ChildSa * child_sa ) {
if ( message.exchange_type != Message::IKE_AUTH )
return ;
BoolAttribute* attribute = ike_sa.getIkeSaConfiguration().attributemap->getAttribute<BoolAttribute>( "mobike_supported" );
if ( attribute == NULL || !attribute->value )
return ;
auto_ptr<Payload_NOTIFY> notify ( new Payload_NOTIFY( ( Payload_NOTIFY::NOTIFY_TYPE ) 16396, Enums::PROTO_NONE ) );
message.addPayloadNotify( notify, true );
}
}
| 47.915663
| 157
| 0.605733
|
OpenIKEv2
|
eaac335138b04a7ce94ca33f15cf70799ca4394c
| 1,211
|
cpp
|
C++
|
trunk/day30/solution.cpp
|
itsjacob/90pp
|
eca71e624d28d216feb06d615e587fc6792c36b6
|
[
"MIT"
] | null | null | null |
trunk/day30/solution.cpp
|
itsjacob/90pp
|
eca71e624d28d216feb06d615e587fc6792c36b6
|
[
"MIT"
] | null | null | null |
trunk/day30/solution.cpp
|
itsjacob/90pp
|
eca71e624d28d216feb06d615e587fc6792c36b6
|
[
"MIT"
] | null | null | null |
class Solution
{
public:
bool possibleBipartition(int n, vector<vector<int>> &dislikes)
{
// create the graph with adjancenty list
std::vector<std::vector<int>> adjList(n + 1);
for (auto const &dislike : dislikes) {
adjList[dislike[0]].push_back(dislike[1]);
// undirected graph so update both vertices
adjList[dislike[1]].push_back(dislike[0]);
}
// 0: uncolored; 1: group 1 color; 2: group 2 color
std::vector<int> colors(n + 1, 0);
for (int ii = 1; ii <= n; ii++) {
if (colors[ii] == 0) {
if (!dfs(adjList, colors, ii, 1)) return false;
}
}
return true;
}
private:
// @return whether the vertex and its neighbors can be colored into two categories
bool dfs(std::vector<std::vector<int>> &adjList, std::vector<int> &colors, int cur, int color)
{
colors[cur] = color;
for (auto const &neighbor : adjList[cur]) {
// conflicts in neighors
if (colors[neighbor] == color) {
return false;
}
// uncolored neighbor, color it with a different color
if (colors[neighbor] == 0) {
if (!dfs(adjList, colors, neighbor, -color)) return false;
}
}
return true;
}
};
| 28.833333
| 96
| 0.599505
|
itsjacob
|
eab3217675395f3932b525f1d67e3e2b3e19c4ec
| 1,001
|
cpp
|
C++
|
include/hydro/compiler/Line.cpp
|
hydraate/hydro
|
42037a8278dcfdca68fb5cceaf6988da861f0eff
|
[
"Apache-2.0"
] | null | null | null |
include/hydro/compiler/Line.cpp
|
hydraate/hydro
|
42037a8278dcfdca68fb5cceaf6988da861f0eff
|
[
"Apache-2.0"
] | null | null | null |
include/hydro/compiler/Line.cpp
|
hydraate/hydro
|
42037a8278dcfdca68fb5cceaf6988da861f0eff
|
[
"Apache-2.0"
] | null | null | null |
//
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
#include "Line.hpp"
namespace hydro::compiler
{
/**
*
*/
Line::Line()
{
}
/**
*
*/
Line::Line(uint32_t lineNumber, std::string lineContent, compilation_status status) : mContent{new line_data{lineNumber, lineContent, status}}
{
}
/**
*
*/
Line::Line(const Line& line) : mContent{line.mContent}
{
}
/**
*
*/
Line::Line(Line&& line) : mContent{line.mContent}
{
}
/**
*
*/
Line::~Line()
{
}
/**
*
*/
Line& Line::operator=(const Line& rhs)
{
mContent = rhs.mContent;
return (*this);
}
/**
*
*/
Line& Line::operator=(Line&& rhs)
{
mContent = rhs.mContent;
return (*this);
}
} // namespace hydro::compiler
| 14.3
| 142
| 0.455544
|
hydraate
|
eab4a65f9ef2c05abd1a40d81e5581d2bc5b8ce7
| 4,283
|
cpp
|
C++
|
source/Driver/SFML/PlatformSFML.cpp
|
tunip3/Super-Haxagon
|
7d1f9c665263e2ea8110bbad5d473f882aa0a441
|
[
"MIT"
] | null | null | null |
source/Driver/SFML/PlatformSFML.cpp
|
tunip3/Super-Haxagon
|
7d1f9c665263e2ea8110bbad5d473f882aa0a441
|
[
"MIT"
] | null | null | null |
source/Driver/SFML/PlatformSFML.cpp
|
tunip3/Super-Haxagon
|
7d1f9c665263e2ea8110bbad5d473f882aa0a441
|
[
"MIT"
] | null | null | null |
#include "../../../include/Driver/SFML/PlatformSFML.hpp"
#include "../../../include/Core/Structs.hpp"
#include "../../../include/Driver/SFML/AudioSFML.hpp"
#include "../../../include/Driver/SFML/FontSFML.hpp"
#include "../../../include/Driver/SFML/PlayerSoundSFML.hpp"
#include <array>
#include <string>
namespace SuperHaxagon {
PlatformSFML::PlatformSFML(const Dbg dbg, sf::VideoMode video) : Platform(dbg) {
_clock.restart();
sf::ContextSettings settings;
settings.antialiasingLevel = 8;
//settings.
_window = std::make_unique<sf::RenderWindow>(video, "Super Haxagon", sf::Style::None, settings);
_window->setVerticalSyncEnabled(true);
_loaded = true;
}
PlatformSFML::~PlatformSFML() = default;
bool PlatformSFML::loop() {
const auto throttle = sf::milliseconds(1);
sf::sleep(throttle);
_delta = _clock.getElapsedTime().asSeconds();
_clock.restart();
sf::Event event{};
while (_window->pollEvent(event)) {
if (event.type == sf::Event::Closed) _window->close();
if (event.type == sf::Event::GainedFocus) _focus = true;
if (event.type == sf::Event::LostFocus) _focus = false;
if (event.type == sf::Event::Resized) {
const auto width = event.size.width > 400 ? event.size.width : 400;
const auto height = event.size.height > 240 ? event.size.height : 240;
if (width != event.size.width || height != event.size.height) {
_window->setSize({ width, height });
}
sf::FloatRect visibleArea(
0.0f,
0.0f,
static_cast<float>(width),
static_cast<float>(height)
);
_window->setView(sf::View(visibleArea));
}
}
return _loaded && _window->isOpen();
}
double PlatformSFML::getDilation() {
// The game was originally designed with 60FPS in mind
const auto dilation = _delta / (1.0 / 60.0);
return dilation > 4.0 ? 4.0 : (dilation < 0.05 ? 0.05 : dilation);
}
std::unique_ptr<Audio> PlatformSFML::loadAudio(const std::string& path, Stream stream) {
return std::make_unique<AudioSFML>(path, stream);
}
std::unique_ptr<Font> PlatformSFML::loadFont(const std::string& path, int size) {
return std::make_unique<FontSFML>(*this, path, size);
}
void PlatformSFML::playSFX(Audio& audio) {
for (auto it = _sfx.begin(); it != _sfx.end();) {
auto& playing = *it;
if (playing->isDone()) {
it = _sfx.erase(it);
} else {
++it;
}
}
auto player = audio.instantiate();
if (!player) return;
player->setLoop(false);
player->play();
_sfx.emplace_back(std::move(player));
}
void PlatformSFML::playBGM(Audio& audio) {
_bgm = audio.instantiate();
if (!_bgm) return;
_bgm->setLoop(true);
_bgm->play();
}
std::string PlatformSFML::getButtonName(const Buttons& button) {
if (button.back) return "ESC";
if (button.select) return "ENTER";
if (button.left) return "LEFT";
if (button.right) return "RIGHT";
if (button.quit) return "DELETE";
return "?";
}
Buttons PlatformSFML::getPressed() {
Buttons buttons{};
if (!_focus) return buttons;
buttons.select = sf::Keyboard::isKeyPressed(sf::Keyboard::Enter);
buttons.back = sf::Keyboard::isKeyPressed(sf::Keyboard::Escape);
buttons.quit = sf::Keyboard::isKeyPressed(sf::Keyboard::Delete);
buttons.left = sf::Keyboard::isKeyPressed(sf::Keyboard::Left) | sf::Keyboard::isKeyPressed(sf::Keyboard::A);
buttons.right = sf::Keyboard::isKeyPressed(sf::Keyboard::Right) | sf::Keyboard::isKeyPressed(sf::Keyboard::D);
return buttons;
}
Point PlatformSFML::getScreenDim() const {
Point point{};
point.x = _window->getSize().x;
point.y = _window->getSize().y;
return point;
}
void PlatformSFML::screenBegin() {
_window->clear(sf::Color::Black);
}
void PlatformSFML::screenSwap() {
// Do nothing, since there is no second screen on a PC
}
void PlatformSFML::screenFinalize() {
_window->display();
}
void PlatformSFML::drawPoly(const Color& color, const std::vector<Point>& points) {
const sf::Color sfColor{ color.r, color.g, color.b, color.a };
sf::ConvexShape convex(points.size());
convex.setPosition(0, 0);
convex.setFillColor(sfColor);
auto index = 0;
for (const auto& point : points) {
convex.setPoint(index++, sf::Vector2f(static_cast<float>(point.x), static_cast<float>(point.y)));
}
_window->draw(convex);
}
}
| 29.335616
| 112
| 0.666589
|
tunip3
|
eabd41e72d247194ce39be33fc415ae575750ac7
| 11,209
|
cpp
|
C++
|
gui/graphs/plot.cpp
|
den-makarov/electronshik
|
8065842ab0e190b51e8a8745ff984b34fb8da82a
|
[
"BSD-3-Clause"
] | null | null | null |
gui/graphs/plot.cpp
|
den-makarov/electronshik
|
8065842ab0e190b51e8a8745ff984b34fb8da82a
|
[
"BSD-3-Clause"
] | null | null | null |
gui/graphs/plot.cpp
|
den-makarov/electronshik
|
8065842ab0e190b51e8a8745ff984b34fb8da82a
|
[
"BSD-3-Clause"
] | null | null | null |
#include <cmath>
#include <QPainter>
#include <QPen>
#include "plot.h"
#include "logger.h"
#include "mathutils.h"
namespace PowerLab {
namespace Gui {
Plot::Plot(int width, int height)
: m_width(width)
, m_height(height)
{
}
int Plot::getWidth() const {
return m_width;
}
void Plot::setWidth(int width) {
m_width = width;
}
int Plot::getHeight() const {
return m_height;
}
void Plot::setHeight(int height) {
m_height = height;
}
void Plot::setArea(int width, int height) {
setWidth(width);
setHeight(height);
}
void Plot::setBorder(bool isBorder) {
m_border = isBorder;
}
int Plot::getMainGridLinesXNumber() const {
return m_autoGrid ? -1 : m_gridXNumber;
}
int Plot::getMainGridLinesYNumber() const {
return m_autoGrid ? -1 : m_gridYNumber;
}
void Plot::setMainGridLinesXNumber(int xNumber) {
if(!m_autoGrid) {
m_gridXNumber = xNumber;
} else {
Logger::log(Message::WARNING_SET_PLOT_GRID_LINES_ON_AUTO_GRID);
}
}
void Plot::setMainGridLinesYNumber(int yNumber) {
if(!m_autoGrid) {
m_gridYNumber = yNumber;
} else {
Logger::log(Message::WARNING_SET_PLOT_GRID_LINES_ON_AUTO_GRID);
}
}
QRectF Plot::getBoundsRect() const {
return QRectF(m_bounds.xMin,
m_bounds.yMin,
m_bounds.xMax - m_bounds.xMin,
m_bounds.yMax - m_bounds.yMin);
}
Plot::ValueBounds Plot::getBounds() const {
return m_bounds;
}
bool Plot::isAutoGrid() const {
return m_autoGrid;
}
void Plot::setAutoGrid(bool enabled) {
m_autoGrid = enabled;
}
void Plot::setBounds(const ValueBounds& boundaries) {
m_bounds = boundaries;
}
void Plot::setAxisXLog(bool isLog) {
m_isXLog = isLog;
}
void Plot::setAxisYLog(bool isLog) {
m_isYLog = isLog;
}
void Plot::setGridColor(QColor color) {
m_gridColor = color;
}
QColor Plot::getGridColor() const {
return m_gridColor;
}
void Plot::setBackground(QColor bgcolor) {
m_bgcolor = bgcolor;
}
QColor Plot::getBackground() const {
return m_bgcolor;
}
void Plot::clearXAxisLabels() {
m_XLabels.clear();
}
void Plot::addXAxisLabel(const std::string& label, QColor textColor) {
m_XLabels.emplace_back(label, textColor);
}
void Plot::clearYAxisLabels() {
m_YLabels.clear();
}
void Plot::addYAxisLabel(const std::string& label, QColor textColor) {
m_YLabels.emplace_back(label, textColor);
}
Plot::ValueBounds Plot::getGridLabelsBounds() const {
ValueBounds bounds;
bounds.xMin = m_gridLabelsRect.left();
bounds.xMax = m_gridLabelsRect.right();
bounds.yMin = m_gridLabelsRect.bottom();
bounds.yMax = m_gridLabelsRect.top();
return bounds;
}
void Plot::setGridLabelsBounds(ValueBounds gridLabels) {
m_gridLabelsRect.setBottomLeft({gridLabels.xMin, gridLabels.yMin});
m_gridLabelsRect.setTopRight({gridLabels.xMax, gridLabels.yMax});
}
void Plot::update(QPainter* painter) {
if(painter == nullptr) {
return;
}
if((m_width - (m_margins.right + m_margins.left)) <= 0
|| (m_height - (m_margins.top + m_margins.bottom)) <= 0) {
return;
}
painter->fillRect(m_margins.left,
m_margins.top,
m_width - (m_margins.right + m_margins.left),
m_height - (m_margins.top + m_margins.bottom),
m_bgcolor);
if(m_autoGrid) {
calculateGridLinesNumber();
}
drawGrid(*painter);
drawBorder(*painter);
drawAxisLabels(*painter);
}
void Plot::drawXAxisLabels(QPainter& painter) const {
if(!m_XLabels.empty()) {
QRect boundingRect;
QRect rect(0,
m_height - m_margins.bottom,
m_width,
painter.font().pixelSize() + 2);
for(auto i = m_XLabels.size(); i != 0; i--) {
auto& label = m_XLabels[i - 1];
auto pen = painter.pen();
pen.setColor(label.textColor);
painter.setPen(pen);
painter.drawText(rect, Qt::AlignRight, QString(label.text.c_str()), &boundingRect);
rect.setWidth(rect.width() - boundingRect.width() - painter.fontMetrics().averageCharWidth() * 2);
}
}
}
void Plot::drawYAxisLabels(QPainter& painter) const {
if(!m_YLabels.empty()) {
QRect boundingRect;
QRect rect(m_margins.left,
0,
m_width,
painter.font().pixelSize() + 2);
for(auto& label : m_YLabels) {
auto pen = painter.pen();
pen.setColor(label.textColor);
painter.setPen(pen);
painter.drawText(rect,
Qt::AlignLeft,
QString(label.text.c_str()),
&boundingRect);
rect.setLeft(rect.left() + boundingRect.width() + painter.fontMetrics().averageCharWidth() * 2);
}
}
}
void Plot::drawAxisLabels(QPainter& painter) const {
QPen pen(Qt::black);
pen.setWidth(1);
painter.setPen(pen);
QFont font;
font.setPixelSize(12);
painter.setFont(font);
drawXAxisLabels(painter);
drawYAxisLabels(painter);
}
void Plot::setMargins(const Margins& margins) {
m_margins = margins;
}
Plot::Margins Plot::getMargins() const {
return m_margins;
}
QRect Plot::getMarginsRect() const {
return QRect(m_margins.left,
m_margins.top,
m_width - (m_margins.right + m_margins.left),
m_height - (m_margins.bottom + m_margins.top));
}
void Plot::drawBorder(QPainter& painter) const {
if(m_border) {
QPen pen(Qt::black);
pen.setWidth(1);
painter.setPen(pen);
painter.drawRect(m_margins.left,
m_margins.top,
m_width - (m_margins.right + m_margins.left),
m_height - (m_margins.top + m_margins.bottom));
}
}
void Plot::calculateGridLinesNumber() {
m_gridLabelsRect.setLeft(m_bounds.xMin);
m_gridLabelsRect.setTop(m_bounds.yMax);
m_gridLabelsRect.setRight(m_bounds.xMax);
m_gridLabelsRect.setBottom(m_bounds.yMin);
m_gridXNumber = 0;
m_gridYNumber = 0;
int plotWidth = m_width - (m_margins.right + m_margins.left);
if(plotWidth > MIN_SPACE_BETWEEN_X_GRID_LINES_PXL) {
auto segments = Utilities::findOptimalRoundedSegments(m_bounds.xMin,
m_bounds.xMax,
plotWidth / MIN_SPACE_BETWEEN_X_GRID_LINES_PXL);
if(!(std::isnan(segments.from) || std::isnan(segments.to) || std::isnan(segments.step))) {
m_gridXNumber = static_cast<int>(std::round((segments.to - segments.from) / segments.step));
m_gridLabelsRect.setLeft(segments.from);
m_gridLabelsRect.setRight(segments.to);
}
}
int plotHeight = m_height - (m_margins.top + m_margins.bottom);
if(plotHeight <= MIN_SPACE_BETWEEN_Y_GRID_LINES_PXL) {
} else {
auto segments = Utilities::findOptimalRoundedSegments(m_bounds.yMin,
m_bounds.yMax,
plotHeight / MIN_SPACE_BETWEEN_Y_GRID_LINES_PXL);
if(!(std::isnan(segments.from) || std::isnan(segments.to) || std::isnan(segments.step))) {
m_gridYNumber = static_cast<int>(std::round((segments.to - segments.from) / segments.step));
m_gridLabelsRect.setBottom(segments.from);
m_gridLabelsRect.setTop(segments.to);
}
}
}
void Plot::drawXGrid(QPainter& painter) const {
if(m_gridXNumber <= 0) {
return;
}
double factor = (m_width - (m_margins.left + m_margins.right) - 1) / (m_bounds.xMax - m_bounds.xMin);
double gridLineDist = factor * m_gridLabelsRect.width() / (m_gridXNumber);
double gridLineLabelStep = m_gridLabelsRect.width() / (m_gridXNumber);
double gridLineLabel = m_gridLabelsRect.left();
double left = (m_gridLabelsRect.left() - m_bounds.xMin) * factor + m_margins.left;
double right = m_gridLabelsRect.right() * factor + m_margins.left;
auto fontSize = painter.fontMetrics().height();
auto yPos = m_height - m_margins.bottom + fontSize / 2;
int cycleLimit = m_gridXNumber;
while(left < right && cycleLimit >= 0) {
auto xPos = static_cast<int>(left);
if(m_margins.left <= xPos && xPos < (m_width - 1) - m_margins.right) {
painter.drawLine(xPos, m_margins.top, xPos, m_height - m_margins.bottom);
xPos = static_cast<int>(left - gridLineDist / 2.0);
QRect textRect(xPos, yPos, static_cast<int>(gridLineDist), fontSize);
drawGridValue(painter, gridLineLabel, textRect, TextAlign::CENTER);
}
left += gridLineDist;
gridLineLabel += gridLineLabelStep;
cycleLimit--;
}
}
void Plot::drawYGrid(QPainter& painter) const {
if(m_gridYNumber <= 0) {
return;
}
double factor = (m_height - (m_margins.top + m_margins.bottom) - 1) / (m_bounds.yMax - m_bounds.yMin);
double gridLineDist = factor * std::abs(m_gridLabelsRect.height()) / m_gridYNumber;
double gridLineLabelStep = std::abs(m_gridLabelsRect.height()) / m_gridYNumber;
double gridLineLabel = m_gridLabelsRect.bottom();
double bottom = (m_bounds.yMin - m_gridLabelsRect.bottom()) * factor + m_height - m_margins.bottom;
double top = m_margins.top;
auto fontSize = painter.fontMetrics().height();
int cycleLimit = m_gridYNumber;
while(bottom > top && cycleLimit >= 0) {
auto yPos = static_cast<int>(bottom);
if(m_margins.top < yPos && yPos < m_height - m_margins.bottom) {
painter.drawLine(m_margins.left, yPos, m_width - m_margins.right, yPos);
QRect textRect(0, yPos - fontSize / 2, m_margins.left - 1, fontSize);
drawGridValue(painter, gridLineLabel, textRect, TextAlign::RIGHT);
}
bottom -= gridLineDist;
gridLineLabel += gridLineLabelStep;
cycleLimit--;
}
}
void Plot::drawGrid(QPainter& painter) const {
QPen pen(m_gridColor);
pen.setWidth(1);
pen.setStyle(Qt::DashDotLine);
painter.setPen(pen);
QFont font;
font.setPixelSize(12);
painter.setFont(font);
drawXGrid(painter);
drawYGrid(painter);
}
void Plot::drawGridValue(QPainter& painter, double number, QRect textRect, TextAlign align) const {
QString str;
if(std::abs(number) <= 10 * std::numeric_limits<double>::epsilon()) {
str = "0";
} else {
str = QString::number(number, 'g', 5);
}
auto textAlign = Qt::AlignLeft;
if(align == TextAlign::CENTER) {
textAlign = Qt::AlignCenter;
} else if(align == TextAlign::RIGHT) {
textAlign = Qt::AlignRight;
}
painter.drawText(textRect, textAlign, str);
}
void Plot::dump(std::ostream& out) const {
out << "Height: " << m_height << " Width: " << m_width;
out << "\nMargins {left, right, top, bottom} : {"
<< m_margins.left << ", "
<< m_margins.right << ", "
<< m_margins.top << ", "
<< m_margins.bottom << "}\n";
out << "Bounds {xMax, xMin, yMax, yMin} : {"
<< m_bounds.xMax << ", "
<< m_bounds.xMin << ", "
<< m_bounds.yMax << ", "
<< m_bounds.yMin << "}\n";
out << "Grid count: Y - " << m_gridYNumber << ", X - " << m_gridXNumber << "\n";
out << "xLabel:";
for(auto& label : m_XLabels) {
out << " " << label.text;
}
out << " yLabel:";
for(auto& label : m_YLabels) {
out << " " << label.text;
}
}
std::ostream& operator<<(std::ostream& out, const Plot& plot) {
plot.dump(out);
return out;
}
} // namespace Gui
} // namespace PowerLab
| 26.561611
| 107
| 0.644661
|
den-makarov
|
eabeecac12f20344a7ba86bb561b081029f5e667
| 335
|
cpp
|
C++
|
cf/r461div2A.cpp
|
meng-jack/competitive-programming
|
f2b4fcec1023e8f827f806dcaa0a2b76117b6c7f
|
[
"MIT"
] | 1
|
2021-11-23T16:44:07.000Z
|
2021-11-23T16:44:07.000Z
|
cf/r461div2A.cpp
|
meng-jack/competitive-programming
|
f2b4fcec1023e8f827f806dcaa0a2b76117b6c7f
|
[
"MIT"
] | 3
|
2021-11-10T19:32:00.000Z
|
2021-11-21T17:24:49.000Z
|
cf/r461div2A.cpp
|
meng-jack/competitive-programming
|
f2b4fcec1023e8f827f806dcaa0a2b76117b6c7f
|
[
"MIT"
] | 1
|
2021-11-10T19:24:22.000Z
|
2021-11-10T19:24:22.000Z
|
#include <bits/stdc++.h>
#define SPEED \
ios_base::sync_with_stdio(false); \
cin.tie(NULL);
using namespace std;
int main() {
SPEED
int x, y;
cin >> x >> y;
if (y > x + 1 || y == 0 || y == 1 && x > 0) {
cout << "NO";
return 0;
}
((y - 1) - x) % 2 == 0 ? cout << "YES" : cout << "NO";
}
| 17.631579
| 56
| 0.435821
|
meng-jack
|
eac83414030e0dd7883aad5501f4dc445e5056db
| 186
|
cpp
|
C++
|
light.cpp
|
atomiccheese/raytracer
|
ad80fe64992275e54db2a86f1c963e5038e6dc87
|
[
"MIT"
] | null | null | null |
light.cpp
|
atomiccheese/raytracer
|
ad80fe64992275e54db2a86f1c963e5038e6dc87
|
[
"MIT"
] | null | null | null |
light.cpp
|
atomiccheese/raytracer
|
ad80fe64992275e54db2a86f1c963e5038e6dc87
|
[
"MIT"
] | null | null | null |
#include "light.hpp"
Light::Light(const color& c) : col(c) {
}
color Light::getColor(const vec3& incoming) const {
return col;
}
bool Light::isInfinitelyFarAway() {
return false;
}
| 14.307692
| 51
| 0.688172
|
atomiccheese
|
eacbe965f36a895928b9b7b6491a72e83245bcab
| 3,421
|
cpp
|
C++
|
Arafat/27. Offset Arrays.cpp
|
AhmedMostafa7474/Codingame-Solutions
|
da696a095c143c5d216bc06f6689ad1c0e25d0e0
|
[
"MIT"
] | 1
|
2022-03-16T08:56:31.000Z
|
2022-03-16T08:56:31.000Z
|
Arafat/27. Offset Arrays.cpp
|
AhmedMostafa7474/Codingame-Solutions
|
da696a095c143c5d216bc06f6689ad1c0e25d0e0
|
[
"MIT"
] | 2
|
2022-03-17T11:27:14.000Z
|
2022-03-18T07:41:00.000Z
|
Arafat/27. Offset Arrays.cpp
|
AhmedMostafa7474/Codingame-Solutions
|
da696a095c143c5d216bc06f6689ad1c0e25d0e0
|
[
"MIT"
] | 6
|
2022-03-13T19:56:11.000Z
|
2022-03-17T12:08:22.000Z
|
//https://www.codingame.com/ide/puzzle/offset-arrays
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
map<char,string>mp;
map<pair<string,string>,string> mp2;
/*
3
A[-1..1] = 1 2 3
B[3..7] = 3 4 5 6 7
C[-2..1] = 1 2 3 4
A[0]
--
1
X[0..3] = 1 3 3 7
X[X[2]]
*/
string solve(string str)
{
// cout<<str;
string name,value;
bool take = true;
for(ll i =0; i<str.size(); i++)//A[A[-1]]
{
if(i == (str.size()-1) ) break;
if(str[i] != '[' && take)
{
name+=str[i];
continue;
}
else if (str[i] == '[' && take)
{
take = false;
continue;
}
else value += str[i];
//cout<<i<<" ";
}
// cout<<name<<"\n";
//cout<<"-->"<<value<<"\n";
string res;
if(mp2.find({name,value}) != mp2.end())
{
//cout<<"NOW";
//cout<< mp2[ {name,value}];
return mp2[ {name,value}];
}
else
{
res = solve(value);
return mp2[ {name,res}];
}
}
void solve2(string str)//A[-1..1] = 1 2 3
{
string name="";
string start="",End ="";
bool take = true, take2 = true, take3 = true;
for(ll i =0; i<str.size(); i++)
{
if(str[i] != '[' && take)
{
name+=str[i];
continue;
}
else if (str[i] == '[')
{
take = false;
continue;
}
if(str[i] != '.' && take2)
{
start += str[i];
continue;
}
else if(str[i] == '.' && take2)
{
take2 = false;
continue;
}
if(str[i] != '.' && str[i] != ']' && take3)
{
End += str[i];
continue;
}
else if(str[i] == ']' && take3)
{
take3 = false;
}
}
//cout<<name<<"->"<<start<<"-->"<<End<<"\n";
vector<string> v1;
for(ll i =0; i<str.size(); i++)
{
if(str[i] == '=')
{
string r ;
for(ll j =i+1; j<str.size(); j++,i++)
{
if(str[j] != ' ') r += str[j];
else if(r.size() && str[j] == ' ')
{
v1.push_back(r);
r="";
}
}
v1.push_back(r);
//cout<<r<<"\n";
}
}
//for(auto it: v1)cout<<it<<"\n";
ll s, e;
istringstream(start) >> s;
istringstream(End) >> e;
//cout<<"here";
ll idx= 0;
for(ll i = s; i<=e; i++)
{
//cout<<i;
string sss = to_string(i);
mp2[ {name,sss}] = v1[idx];
idx++;
}
// for(auto &it:mp2)
// {
// cout<<it.first.first<<" "<<it.first.second <<"-->" << it.second<<"\n";
// }
}
int main()
{
int n;
cin >> n;
cin.ignore();
for (int i = 0; i < n; i++)
{
string assignment;
getline(cin, assignment);
//mp[assignment[i]] = assignment;
solve2(assignment);
}
string x;
getline(cin, x);
string s = solve(x);
// Write an answer using cout. DON'T FORGET THE "<< endl"
// To debug: cerr << "Debug messages..." << endl;
cout<<s;
//cout << "0" << endl;
}
/*
*/
| 21.515723
| 82
| 0.366559
|
AhmedMostafa7474
|
eacc408bcd5ca9f6967fd3555a9393047ef77d55
| 3,820
|
cc
|
C++
|
src/comm/udp.cc
|
Phantomape/paxos
|
d88ab88fa5b6c7d74b508580729c4dea4de6f180
|
[
"MIT"
] | null | null | null |
src/comm/udp.cc
|
Phantomape/paxos
|
d88ab88fa5b6c7d74b508580729c4dea4de6f180
|
[
"MIT"
] | 5
|
2018-05-30T03:09:10.000Z
|
2018-06-02T22:56:05.000Z
|
src/comm/udp.cc
|
Phantomape/paxos
|
d88ab88fa5b6c7d74b508580729c4dea4de6f180
|
[
"MIT"
] | null | null | null |
#include "default_network.h"
#include "udp.h"
#include <arpa/inet.h>
#include <cstring>
#include <poll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
namespace paxos {
UdpRecv::UdpRecv(DefaultNetwork* default_network)
: default_network(default_network), socket_file_descriptor_(-1), is_ended_(false), is_started_(false)
{
}
UdpRecv::~UdpRecv() {
if (socket_file_descriptor_ != -1) {
close(socket_file_descriptor_);
socket_file_descriptor_ = -1;
}
}
void UdpRecv::Stop() {
if (is_started_) {
is_ended_ = true;
Join();
}
}
int UdpRecv::Init(const int port) {
if ((socket_file_descriptor_ = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return -1;
}
struct sockaddr_in addr;
std::memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
int enable = 1;
setsockopt(socket_file_descriptor_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
if (bind(socket_file_descriptor_, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
return -1;
}
return 0;
}
void UdpRecv::Run() {
is_started_ = true;
char buf[65536] = {0};
struct sockaddr_in addr;
socklen_t addr_len = sizeof(struct sockaddr_in);
std::memset(&addr, 0, sizeof(addr));
while (true) {
if (is_ended_) {
return;
}
struct pollfd fd;
int res;
fd.fd = socket_file_descriptor_;
fd.events = POLLIN;
res = poll(&fd, 1, 500);
if (res == 0 || res == -1) {
continue;
}
int recv_len = recvfrom(socket_file_descriptor_, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addr_len);
if (recv_len > 0) {
// default_network->OnReceiveMessage(buf, recv_len);
}
}
}
UdpSend::UdpSend() : socket_file_descriptor_(-1), is_ended_(false), is_started_(false) {}
UdpSend::~UdpSend() {
while (!send_queue.empty()) {
Packet* packet = send_queue.peek();
send_queue.pop();
delete packet;
}
}
int UdpSend::Init() {
if ((socket_file_descriptor_ = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return -1;
}
return 0;
}
void UdpSend::Stop() {
if (is_started_) {
is_ended_ = true;
Join();
}
}
void UdpSend::SendMessage(const std::string& ip, const int port, const std::string& message) {
struct sockaddr_in addr;
int addr_len = sizeof(struct sockaddr_in);
std::memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip.c_str());
int res = sendto(socket_file_descriptor_, message.data(), (int)message.size(), 0, (struct sockaddr*)&addr, addr_len);
if (res > 0) {
}
}
void UdpSend::Run() {
is_started_ = true;
while (true) {
Packet* packet = nullptr;
send_queue.lock();
bool is_succeeded = send_queue.peek(packet, 1000);
if (is_succeeded) {
send_queue.pop();
}
send_queue.unlock();
if (packet != nullptr) {
SendMessage(packet->ip, packet->port, packet->message);
delete packet;
}
if (is_ended_) {
return;
}
}
}
int UdpSend::AddMessage(const std::string& ip, const int port, const std::string& message) {
send_queue.lock();
int UDP_QUEUE_MAX_LEN = 100; // This const need to be stored somewhere else
if ((int)send_queue.size() > UDP_QUEUE_MAX_LEN) {
send_queue.unlock();
return -2;
}
Packet* packet = new Packet;
packet->ip = ip;
packet->port = port;
packet->message = message;
send_queue.add(packet);
send_queue.unlock();
return 0;
}
}
| 22.080925
| 121
| 0.596335
|
Phantomape
|
eaccfca629e57e7db41810ce8dfcc7b73c5d3a5a
| 5,747
|
cpp
|
C++
|
ProjectEuler+/euler-0268.cpp
|
sarvekash/HackerRank_Solutions
|
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
|
[
"Apache-2.0"
] | null | null | null |
ProjectEuler+/euler-0268.cpp
|
sarvekash/HackerRank_Solutions
|
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
|
[
"Apache-2.0"
] | null | null | null |
ProjectEuler+/euler-0268.cpp
|
sarvekash/HackerRank_Solutions
|
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
|
[
"Apache-2.0"
] | 1
|
2021-05-28T11:14:34.000Z
|
2021-05-28T11:14:34.000Z
|
// ////////////////////////////////////////////////////////
// # Title
// Counting numbers with at least four distinct prime factors less than 100
//
// # URL
// https://projecteuler.net/problem=268
// http://euler.stephan-brumme.com/268/
//
// # Problem
// It can be verified that there are 23 positive integers less than 1000 that are divisible by at least four distinct primes less than 100.
//
// Find how many positive integers less than `10^16` are divisible by at least four distinct primes less than 100.
//
// # Solved by
// Stephan Brumme
// September 2017
//
// # Algorithm
// There are 25 primes less than 100.
// I start a loop running from 0 to `2^25`. I multiply all the n-th primes if the n-th bit of the counter (named ''mask'') is set.
// If ''mask'' has at least four bits set then the product of those primes needs to be further analyzed:
// - ''product'' can exceed `10^16` and cause strange results, reject all those large products
// - there are `10^16 / product` numbers divisible by ''product''
//
// I have to be careful to avoid counting the same numbers twice:
// for example 2310 is divisible by 2,3,5,7 and 11 (in fact 2*3*5*7*11 = 2310). But 2310 is also divisible by (2,3,5,7), (2,3,5,11), (2,5,7,11) and (3,5,7,11).
// That means (2,3,5,7,11) "overlaps" all combinations of its primes where I take one prime away.
// The tetrahedral numbers can compute this "overlap" (see https://en.wikipedia.org/wiki/Tetrahedral_number ) together with
// the inclusion-exclusion principle (see https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle ).
//
// In plain English: I add the count of numbers divisible by 4 primes, subtract the count divisible by 5 primes, add 6s, subtract 7s, etc.
// ==> if ''numBits'' is even, then add else subtract, the fast way is just to look at the lowest bit of the ''numBits'' counter
#include <iostream>
#include <vector>
// all 25 primes less than 100
std::vector<unsigned int> primes = { 2, 3, 5, 7, 11,
13, 17, 19, 23, 29,
31, 37, 41, 43, 47,
53, 59, 61, 67, 71,
73, 79, 83, 89, 97 };
// count numbers with at least "minPrimes" prime factors
// slow version - helping me while debugging the fast code below
unsigned int bruteForce(unsigned int limit, unsigned int minPrimes)
{
unsigned int result = 0;
for (unsigned int i = 1; i <= limit; i++)
{
// count distinct prime factors
unsigned int numPrimeFactors = 0;
for (auto p : primes)
if (i % p == 0)
numPrimeFactors++;
// at least four prime factors ?
if (numPrimeFactors >= minPrimes)
result++;
}
return result;
}
// return the n-th tetrahedral number
unsigned int tetrahedral(unsigned int n)
{
// see https://en.wikipedia.org/wiki/Tetrahedral_number
return n * (n + 1) * (n + 2) / 6;
}
int main()
{
// at least 4 primes, search up to 10^16
unsigned int minPrimes = 4;
unsigned int numPrimes = primes.size();
unsigned long long limit = 10000000000000000ULL;
std::cin >> minPrimes >> numPrimes >> limit;
// find result for small limits
//std::cout << bruteForce(limit, minPrimes) << std::endl;
// precompute tetrahedral numbers
std::vector<unsigned long long> count(numPrimes + 1, 0);
for (unsigned int i = minPrimes; i < count.size(); i++)
count[i] = tetrahedral(i - minPrimes + 1); // same as choose(i - 1, minPrimes - 1)
unsigned long long sum = 0;
unsigned int maxMask = (1 << numPrimes) - 1;
for (unsigned int mask = 0; mask < maxMask; mask++)
{
// multiply all primes
unsigned long long product = 1;
// but don't exceed 10^16
bool tooLarge = false;
// at least four bits must be set (=> pick at least four different primes)
unsigned int numBits = 0;
// look at each prime
for (unsigned int current = 0; current < numPrimes; current++)
{
// is this prime used ?
unsigned int bitpos = 1 << current;
if ((mask & bitpos) == 0)
continue;
// include this prime factor
numBits++;
product *= primes[current];
// avoid too large products (beware of 64 bit overflows ...)
if (product > limit)
{
tooLarge = true;
// speed optimization:
// if the next mask has the same number of bits set (or more), then it will exceed the limit as well
// because the primes are getting larger
// => get closer to the next number with the less bits set
// add the lowest set bit to the current number
// => worst case: same number of bits if the last bit is a single bit
// => best case: several bits next to the lowest bit are set to and all flip to zeros (and a zero becomes a one)
auto withLowestBit = mask & (mask - 1);
auto lowestBit = mask - withLowestBit;
mask += lowestBit;
// hope for the best case ...
while (mask & (lowestBit << 1))
{
lowestBit <<= 1;
mask += lowestBit;
}
mask--; // because the for-loop will add 1 in each iteration
break;
}
}
// skip if too few primes or their product became too large
if (tooLarge || numBits < minPrimes)
continue;
// count numbers divisible by the current primes
auto divisible = limit / product;
// they were part of products with less primes, too, hence compute the "overlap"
divisible *= count[numBits];
// add if even number of primes, else subtract (inclusion-exclusion principle)
if (numBits & 1)
sum -= divisible;
else
sum += divisible;
}
// that's it !
std::cout << sum << std::endl;
return 0;
}
| 36.605096
| 159
| 0.623108
|
sarvekash
|
ead1556f3a93d6c8baac6993f5ae967a8582b208
| 962
|
cpp
|
C++
|
example.cpp
|
DoctorBazooka/cpp-itertools
|
0db1276065b456bf571186074a9d19b8d3920f9f
|
[
"MIT"
] | null | null | null |
example.cpp
|
DoctorBazooka/cpp-itertools
|
0db1276065b456bf571186074a9d19b8d3920f9f
|
[
"MIT"
] | null | null | null |
example.cpp
|
DoctorBazooka/cpp-itertools
|
0db1276065b456bf571186074a9d19b8d3920f9f
|
[
"MIT"
] | null | null | null |
#include "cpp-itertools.hpp"
#include <iostream>
#include <vector>
#include <cppcoro/generator.hpp>
int main()
{
std::vector<int> example{2, 4, 6, 8, 10, 12};
std::vector<std::string> example2{"Man", "Woman", "Person", "Camera", "TV"};
std::cout << "\nExample:\n";
for (auto& x : example) {
std::cout << x << "\n";
}
std::cout << "\nReversed:\n";
for (auto& x : itertools::reversed(example)) {
std::cout << x << "\n";
}
std::cout << "\nEnumerated:\n";
for (auto& [i, x] : itertools::enumerate(example)) {
std::cout << i << " -> " << x << "\n";
}
std::cout << "\nEnumerated from 10:\n";
for (auto& [i, x] : itertools::enumerate(example, 10)) {
std::cout << i << " -> " << x << "\n";
}
std::cout << "\nZipped with vector of strings:\n";
for (auto& [left, right] : itertools::zip(example, example2)) {
std::cout << left << ", " << right << "\n";
}
}
| 26
| 80
| 0.503119
|
DoctorBazooka
|
ead4bd8b691194d0f34cac008f8fae9c30fdc578
| 1,524
|
cpp
|
C++
|
099-recover-binary-search-tree/recover-binary-search-tree.cpp
|
nagestx/MyLeetCode
|
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
|
[
"MIT"
] | 3
|
2018-12-15T14:07:12.000Z
|
2020-07-19T23:18:09.000Z
|
099-recover-binary-search-tree/recover-binary-search-tree.cpp
|
yangyangu/MyLeetCode
|
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
|
[
"MIT"
] | null | null | null |
099-recover-binary-search-tree/recover-binary-search-tree.cpp
|
yangyangu/MyLeetCode
|
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
|
[
"MIT"
] | null | null | null |
// Two elements of a binary search tree (BST) are swapped by mistake.
//
// Recover the tree without changing its structure.
//
// Example 1:
//
//
// Input: [1,3,null,null,2]
//
// 1
// /
// 3
// \
// 2
//
// Output: [3,1,null,null,2]
//
// 3
// /
// 1
// \
// 2
//
//
// Example 2:
//
//
// Input: [3,1,4,null,null,2]
//
// 3
// / \
// 1 4
// /
// 2
//
// Output: [2,1,4,null,null,3]
//
// 2
// / \
// 1 4
// /
// 3
//
//
// Follow up:
//
//
// A solution using O(n) space is pretty straight forward.
// Could you devise a constant space solution?
//
//
/**
* 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:
void inorder(vector<TreeNode*> & arr, TreeNode* node){
if(!node){
return;
}
inorder(arr, node->left);
arr.push_back(node);
inorder(arr, node->right);
}
void recoverTree(TreeNode* root) {
if(!root)
return;
vector<TreeNode*> arr;
inorder(arr, root);
vector<int> list;
for(auto &it: arr){
if(it){
list.push_back(it->val);
}
}
sort(list.begin(), list.end());
int cur = 0;
for(auto &it: arr){
if(it){
it->val = list[cur ++];
}
}
}
};
| 16.212766
| 70
| 0.44685
|
nagestx
|
eada45dd9efdabc1437dc5e345565308f9cde2d2
| 1,224
|
cpp
|
C++
|
.LHP/.Lop10/.O.L.P/.T.Van/Colp6/code/DSEQ/DSEQ.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
.LHP/.Lop10/.O.L.P/.T.Van/Colp6/code/DSEQ/DSEQ.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
.LHP/.Lop10/.O.L.P/.T.Van/Colp6/code/DSEQ/DSEQ.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstdio>
#include <algorithm>
#define maxN 100002
#define maxA 1000000001
#define minA -1000000001
#define maxR 1000000000000001
#define minR -1000000000000001
typedef long maxn;
typedef long long maxa;
maxn n;
maxa a[maxN], mn[maxN], mx[maxN], mnv[maxN], mxv[maxN], res;
void Prepare() {
std::cin >> n >> a[0];
maxa sum = a[0];
mn[0] = sum;
mx[0] = sum;
for(maxn i = 1; i < n; i++) {
std::cin >> a[i];
sum += a[i];
mn[i] = std::min(mn[i - 1], sum);
mx[i] = std::max(mx[i - 1], sum);
}
}
maxa abs(maxa x) {
return x < 0 ? -x : x;
}
void Process() {
res = minR;
maxa sumv = a[n - 1];
mxv[n - 1] = a[n - 1];
mnv[n - 1] = a[n - 1];
for(maxn j = n - 2; j >= 0; j--) {
sumv += a[j];
mnv[j] = std::min(mnv[j + 1], sumv);
mxv[j] = std::max(mxv[j + 1], sumv);
}
for(maxn j = 1; j < n; j++) res = std::max(res, std::max(abs(mx[j - 1] - mnv[j]), abs(mxv[j] - mn[j - 1])));
std::cout << res;
}
int main() {
freopen("dseq.inp","r",stdin);
freopen("dseq.out","w",stdout);
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
Prepare();
Process();
}
| 17.73913
| 112
| 0.5
|
sxweetlollipop2912
|
eadd738e6c5b36fb633ad178d353bd277241590d
| 167
|
hpp
|
C++
|
BlasterFirmware/modules/readback_memory.hpp
|
MasterQ32/LPCBlaster
|
1490a6f0b7963e7acc47902d9ea2b1abd1ac4563
|
[
"Zlib"
] | null | null | null |
BlasterFirmware/modules/readback_memory.hpp
|
MasterQ32/LPCBlaster
|
1490a6f0b7963e7acc47902d9ea2b1abd1ac4563
|
[
"Zlib"
] | null | null | null |
BlasterFirmware/modules/readback_memory.hpp
|
MasterQ32/LPCBlaster
|
1490a6f0b7963e7acc47902d9ea2b1abd1ac4563
|
[
"Zlib"
] | null | null | null |
#ifndef READBACK_MEMORY_HPP
#define READBACK_MEMORY_HPP
#include "sysctrl.hpp"
namespace readback_memory
{
sysctrl::state begin();
}
#endif // READBACK_MEMORY_HPP
| 13.916667
| 29
| 0.790419
|
MasterQ32
|
eadea9ec046a64c8ade4360f496de39ea9afce16
| 1,409
|
cpp
|
C++
|
POJ/3624.cpp
|
Superdanby/YEE
|
49a6349dc5644579246623b480777afbf8031fcd
|
[
"MIT"
] | 1
|
2019-09-07T15:56:05.000Z
|
2019-09-07T15:56:05.000Z
|
POJ/3624.cpp
|
Superdanby/YEE
|
49a6349dc5644579246623b480777afbf8031fcd
|
[
"MIT"
] | null | null | null |
POJ/3624.cpp
|
Superdanby/YEE
|
49a6349dc5644579246623b480777afbf8031fcd
|
[
"MIT"
] | null | null | null |
/*
#include <iostream>
using namespace std;
#define quan 3402
#define totw 12880
int dp[quan+1][totw+1]={};
int weight[quan+1];
int charm[quan+1];
int main()
{
int limq, limw;
cin>>limq>>limw;
for(int x=1; x<=limq; x++)
{
cin>>weight[x]>>charm[x];
}
for(int x=1; x<=limq; x++)
cout<<weight[x]<<" ";
cout<<"\n";
for(int x=1; x<=limq; x++)
cout<<charm[x]<<" ";
cout<<"\n";
for(int x=1; x<=limq; x++)
{
for(int y=1; y<=limw; y++)
{
if(y-weight[x]>=0)
dp[x][y]=max(dp[x-1][y-weight[x]]+charm[x], dp[x-1][y]);
else
dp[x][y]=dp[x-1][y];
}
}
for(int x=0; x<=limq; x++)
{
for(int y=0; y<=limw; y++)
cout<<setw(3)<<dp[x][y]<<" ";
cout<<"\n";
}
cout<<dp[limq][limw]<<"\n";
return 0;
}
*/
#include <iostream>
using namespace std;
#define quan 3402
#define totw 12880
int dp[totw+1]={};
int weight[quan+1];
int charm[quan+1];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int limq, limw;
cin>>limq>>limw;
for(int x=1; x<=limq; x++)
{
cin>>weight[x]>>charm[x];
}
for(int x=1; x<=limq; x++)
{
for(int y=limw; y>=weight[x]; y--)
{
dp[y]=max(dp[y-weight[x]]+charm[x], dp[y]);
}
}
cout<<dp[limw]<<"\n";
return 0;
}
| 19.30137
| 72
| 0.450674
|
Superdanby
|
eae3110bbc3e5d622f76fd9cdba14db8df9d0c2c
| 302
|
cpp
|
C++
|
contest/AtCoder/abc169/B.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 7
|
2018-04-14T14:55:51.000Z
|
2022-01-31T10:49:49.000Z
|
contest/AtCoder/abc169/B.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 5
|
2018-04-14T14:28:49.000Z
|
2019-05-11T02:22:10.000Z
|
contest/AtCoder/abc169/B.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | null | null | null |
#include "vector.hpp"
int main() {
int n(in);
Vector<int64_t> a(n, in);
int64_t res = 1;
for (auto i : a) {
if (2e18 / res < i) {
res = 2e18;
} else {
res *= i;
}
}
if (res <= 1000000000000000000) {
cout << res << endl;
} else {
cout << -1 << endl;
}
}
| 15.1
| 35
| 0.460265
|
not522
|
eae64aee4a0dfa55cbc4eaf5a00f73703596f9a8
| 2,492
|
cc
|
C++
|
Code/0335-self-crossing.cc
|
SMartQi/Leetcode
|
9e35c65a48ba1ecd5436bbe07dd65f993588766b
|
[
"MIT"
] | 2
|
2019-12-06T14:08:57.000Z
|
2020-01-15T15:25:32.000Z
|
Code/0335-self-crossing.cc
|
SMartQi/Leetcode
|
9e35c65a48ba1ecd5436bbe07dd65f993588766b
|
[
"MIT"
] | 1
|
2020-01-15T16:29:16.000Z
|
2020-01-26T12:40:13.000Z
|
Code/0335-self-crossing.cc
|
SMartQi/Leetcode
|
9e35c65a48ba1ecd5436bbe07dd65f993588766b
|
[
"MIT"
] | null | null | null |
class Solution {
public:
bool isSelfCrossing(vector<int>& x) {
if (x.size() <= 3) return false;
unordered_map<int, set<pair<int, int>>> mx;
unordered_map<int, set<pair<int, int>>> my;
int currentx = 0;
int currenty = 0;
int direction = 0;
for (int i = 0; i < x.size(); i++) {
if (direction % 2 == 0) {
// vertical
int updatedy = currenty + ((direction == 0) ? x[i] : -x[i]);
for (auto it = my.begin(); it != my.end(); it++)
// horizontal lines
if ((it->first >= min(currenty, updatedy)) && (it->first <= max(currenty, updatedy)) && it->first != currenty)
for (auto it2 = it->second.begin(); it2 != it->second.end(); it2++)
if ((currentx >= min(it2->first, it2->second)) && (currentx <= max(it2->first, it2->second)))
return true;
for (auto it = mx[currentx].begin(); it != mx[currentx].end(); it++)
// vertical lines
if (!((min(it->first, it->second)) > max(currenty, updatedy) || (max(it->first, it->second)) < min(currenty, updatedy)))
return true;
mx[currentx].insert(make_pair(currenty, updatedy));
currenty = updatedy;
} else {
// horizontal
int updatedx = currentx + ((direction == 1) ? -x[i] : x[i]);
for (auto it = mx.begin(); it != mx.end(); it++)
// vertical lines
if ((it->first >= min(currentx, updatedx)) && (it->first <= max(currentx, updatedx)) && it->first != currentx)
for (auto it2 = it->second.begin(); it2 != it->second.end(); it2++)
if ((currenty >= min(it2->first, it2->second)) && (currenty <= max(it2->first, it2->second)))
return true;
for (auto it = my[currenty].begin(); it != my[currenty].end(); it++)
// horizontal lines
if (!((min(it->first, it->second)) > max(currentx, updatedx) || (max(it->first, it->second)) < min(currentx, updatedx))) return true;
my[currenty].insert(make_pair(currentx, updatedx));
currentx = updatedx;
}
direction = (++direction) % 4;
}
return false;
}
};
| 55.377778
| 153
| 0.457063
|
SMartQi
|
eae8144668e4aa21b3f1b114566d3ddccaf35f36
| 22,894
|
cpp
|
C++
|
source/dvp/VisionCam/CSVisionCam.cpp
|
emrainey/DVP
|
1e9649c69d00fb9840876f7608660b6580b15cfa
|
[
"Apache-2.0"
] | 2
|
2015-09-22T16:50:30.000Z
|
2017-03-23T22:49:33.000Z
|
source/dvp/VisionCam/CSVisionCam.cpp
|
emrainey/DVP
|
1e9649c69d00fb9840876f7608660b6580b15cfa
|
[
"Apache-2.0"
] | null | null | null |
source/dvp/VisionCam/CSVisionCam.cpp
|
emrainey/DVP
|
1e9649c69d00fb9840876f7608660b6580b15cfa
|
[
"Apache-2.0"
] | null | null | null |
#include <CSVisionCam.h>
#if defined(ANDROID) && (defined(ICS) || defined(JELLYBEAN))
#ifdef KEY_ZOOM
#undef KEY_ZOOM
#endif
#include <camera/CameraParameters.h>
const char PIXEL_FORMAT_YUV420SP[] = "yuv420sp";
const char PIXEL_FORMAT_YUV422I[] = "yuv422i-yuyv";
const char KEY_SATURATION[] = "saturation";
const char KEY_BRIGHTNESS[] = "brightness";
const char KEY_CONTRAST[] = "contrast";
const char KEY_SHARPNESS[] = "sharpness";
const char * FLICKER_STR[] = {
"FLICKER_OFF",
"FLICKER_AUTO",
"FLICKER_50Hz",
"FLICKER_60Hz"
};
CSVisionCam::CSVisionCam() :
mCamera(NULL),
mSurfaceTexture(NULL),
mFrameIndex(0),
mConnected(false_e),
mFaceDetectionEnabled(false_e),
mWidth(0),
mHeight(0),
mColorSpace(FOURCC_YUY2)
{
memset(&mVfr, 0, sizeof(mVfr));
mContrast = 0;
mSharpness = 0;
mBrightness = 0;
mSaturation = 0;
mEVCompensation = 0;
mFlicker = FLICKER_OFF;
mInited = false_e;
}
CSVisionCam::~CSVisionCam()
{
}
// interface methods
status_e CSVisionCam::init(void *cookie)
{
DVP_PRINT(DVP_ZONE_CAM, "init: cookie= %p\n", cookie);
status_e status = initFrameDescriptors();
if (status != STATUS_SUCCESS)
{
DVP_PRINT(DVP_ZONE_CAM, "init: initFrameDescriptors failed! error= %d\n", status);
return status;
}
mInited = true_e;
return STATUS_SUCCESS;
}
status_e CSVisionCam::deinit()
{
if (mInited == false_e)
return STATUS_INVALID_STATE;
if (mCamera != NULL)
{
if (mConnected == true_e)
{
if (mCamera->previewEnabled())
stopPreview();
mCamera->disconnect();
mConnected = false_e;
}
mCamera->unlock();
mCamera.clear();
mCamera = NULL;
}
deinitFrameDescriptors();
return STATUS_SUCCESS;
}
status_e CSVisionCam::useBuffers(DVP_Image_t *prvBufArr __attribute__((unused)),
uint32_t numPrvBuf __attribute__((unused)),
VisionCamPort_e port __attribute__((unused)))
{
return STATUS_NOT_IMPLEMENTED;
}
status_e CSVisionCam::releaseBuffers(VisionCamPort_e port __attribute__((unused)))
{
return STATUS_NOT_IMPLEMENTED;
}
status_e CSVisionCam::flushBuffers(VisionCamPort_e port __attribute__((unused)))
{
return STATUS_NOT_IMPLEMENTED;
}
status_e CSVisionCam::sendCommand(VisionCamCmd_e cmdId, void *param, uint32_t size, VisionCamPort_e port __attribute__((unused)))
{
status_e status = STATUS_SUCCESS;
DVP_PRINT(DVP_ZONE_CAM, "SEND CMD: 0x%04x, %p, "FMT_SIZE_T"\n", cmdId, param, size);
switch (cmdId)
{
case VCAM_CMD_PREVIEW_START:
status = startPreview();
break;
case VCAM_CMD_PREVIEW_STOP:
status = stopPreview();
break;
case VCAM_EXTRA_DATA_START:
break;
case VCAM_EXTRA_DATA_STOP:
break;
case VCAM_CMD_LOCK_AWB:
status = lockAutoWhitebalance(true_e);
break;
case VCAM_CMD_LOCK_AE:
status = lockAutoExposure(true_e);
break;
case VCAM_CMD_FACE_DETECTION:
status = toggleFaceDetection();
break;
default:
status = STATUS_NOT_IMPLEMENTED;
break;
}
return status;
}
status_e CSVisionCam::setParameter(VisionCamParam_e paramId, void* param, uint32_t size, VisionCamPort_e port __attribute__((unused)))
{
status_e status = STATUS_SUCCESS;
if (param == NULL || size == 0)
{
DVP_PRINT(DVP_ZONE_ERROR, "NULL param pointer passed to %s()\n",__func__);
return STATUS_INVALID_PARAMETER;
}
else
{
DVP_PRINT(DVP_ZONE_CAM, "SET PARAM: 0x%04x, %p, "FMT_SIZE_T" (0x%08x)\n", paramId, param, size, (size==4?*(uint32_t *)param:0));
}
switch (paramId)
{
case VCAM_PARAM_WIDTH:
if (size == sizeof(uint32_t))
{
mWidth = *(uint32_t *)param;
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_HEIGHT:
if (size == sizeof(uint32_t))
{
mHeight = *(uint32_t *)param;
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_FPS_VAR:
if (size == sizeof(VisionCamVarFramerateType))
{
mVfr = *(VisionCamVarFramerateType *)param;
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_COLOR_SPACE_FOURCC:
if (size == sizeof(_fourcc) && colorSpaceToPreviewFormat(*((_fourcc*)param)))
{
mColorSpace = *((_fourcc*)param);
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_SENSOR_SELECT:
if (size == sizeof(VisionCamSensorSelection))
{
mCameraId = *(VisionCamSensorSelection *)param;
status = connect(mCameraId);
if (status != STATUS_SUCCESS)
{
DVP_PRINT(DVP_ZONE_CAM, "Failed to connect to camera %d, error= %d\n",
mCameraId, status);
}
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_PREVIEW_TEXTURE:
if (param != NULL)
{
mSurfaceTexture = reinterpret_cast<SurfaceTexture *>(param);
DVP_PRINT(DVP_ZONE_CAM, "Using SurfaceTexture= %p\n", mSurfaceTexture.get());
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_CONTRAST:
if (size == sizeof(int32_t))
{
mContrast = *(int32_t *)param;
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_SHARPNESS:
if (size == sizeof(int32_t))
{
mSharpness = *(int32_t *)param;
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_BRIGHTNESS:
if (size == sizeof(int32_t))
{
mBrightness = *(int32_t *)param;
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_SATURATION:
if (size == sizeof(int32_t))
{
mSaturation = *(int32_t *)param;
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_FLICKER:
if (size == sizeof(VisionCamFlickerType))
{
status = setFlicker(*(VisionCamFlickerType *)param);
}
else
status = STATUS_INVALID_PARAMETER;
break;
case VCAM_PARAM_EXPOSURE_COMPENSATION:
if (size == sizeof(int32_t))
{
status = setExposureCompensation(*(int32_t *)param);
}
else
status = STATUS_INVALID_PARAMETER;
break;
default:
status = STATUS_NOT_IMPLEMENTED;
break;
}
return status;
}
status_e CSVisionCam::getParameter(VisionCamParam_e paramId, void* param, uint32_t size, VisionCamPort_e port __attribute__((unused)))
{
status_e status = STATUS_SUCCESS;
if (param == NULL || size == 0)
{
DVP_PRINT(DVP_ZONE_ERROR, "NULL param pointer passed to %s\n", __func__);
return STATUS_INVALID_PARAMETER;
}
else
{
DVP_PRINT(DVP_ZONE_CAM, "GET PARAM: 0x%04x, %p, %u (0x%08x)\n", paramId, param, size, (size==4?*(uint32_t *)param:0));
}
switch (paramId)
{
case VCAM_PARAM_WIDTH:
*(uint32_t*)param = mWidth;
break;
case VCAM_PARAM_HEIGHT:
*(uint32_t*)param = mHeight;
break;
case VCAM_PARAM_FPS_VAR:
*(VisionCamVarFramerateType *)param = mVfr;
break;
case VCAM_PARAM_COLOR_SPACE_FOURCC:
*((_fourcc*)param) = mColorSpace;
break;
case VCAM_PARAM_SENSOR_SELECT:
*(VisionCamSensorSelection *)param = mCameraId;
break;
case VCAM_PARAM_CONTRAST:
*(int32_t*)param = mContrast;
break;
case VCAM_PARAM_SHARPNESS:
*(int32_t*)param = mSharpness;
break;
case VCAM_PARAM_BRIGHTNESS:
*(int32_t*)param = mBrightness;
break;
case VCAM_PARAM_SATURATION:
*(int32_t*)param = mSaturation;
break;
case VCAM_PARAM_FLICKER:
*(VisionCamFlickerType *)param = mFlicker;
break;
case VCAM_PARAM_EXPOSURE_COMPENSATION:
*(int32_t*)param = mEVCompensation;
break;
default:
status = STATUS_NOT_IMPLEMENTED;
break;
}
return status;
}
status_e CSVisionCam::returnFrame(VisionCamFrame *cameraFrame)
{
cameraFrame->clear();
return STATUS_SUCCESS;
}
void CSVisionCam::dataCallback(int32_t msgType,
const sp<IMemory> &data,
camera_frame_metadata_t *metadata)
{
VisionCamFrame *cFrame = mFrameDescriptors[mFrameIndex];
mFrameIndex = (mFrameIndex + 1) % MAX_FRAMES;
cFrame->mFrameSource = VCAM_PORT_PREVIEW;
cFrame->mFrameBuff = data->pointer();
cFrame->mLength = data->size();
cFrame->mTimestamp = rtimer_now();
cFrame->mWidth = mWidth;
cFrame->mHeight = mHeight;
cFrame->mCookie = m_cookie;
cFrame->mContext = this;
if (msgType & CAMERA_MSG_PREVIEW_METADATA)
{
if (mFaceDetectionEnabled && (metadata != NULL))
{
cFrame->mDetectedFacesNum = metadata->number_of_faces;
for (int idx = 0 ; idx < metadata->number_of_faces ; idx++)
{
cFrame->mFaces[idx].mScore = metadata->faces[idx].score;
cFrame->mFaces[idx].mFacesCoordinates.mLeft = metadata->faces[idx].rect[0];
cFrame->mFaces[idx].mFacesCoordinates.mTop = metadata->faces[idx].rect[1];
cFrame->mFaces[idx].mFacesCoordinates.mWidth = metadata->faces[idx].rect[2];
cFrame->mFaces[idx].mFacesCoordinates.mHeight = metadata->faces[idx].rect[3];
}
}
}
// make sure IMemory is not freed prematurely !?
if (m_callback != NULL)
{
m_callback(cFrame);
}
else
{
delete cFrame;
}
}
void CSVisionCam::dataCallbackTimestamp(int64_t timestampUs __attribute__((unused)),
int32_t msgType __attribute__((unused)),
const sp<IMemory> &data __attribute__((unused)))
{
}
status_e CSVisionCam::connect(VisionCamSensorSelection cameraId)
{
DVP_PRINT(DVP_ZONE_CAM, "connect: camera %d\n", cameraId);
if ((mConnected == true_e) && (mCamera != NULL))
{
if (mCamera->previewEnabled())
stopPreview();
mCamera->disconnect();
}
mCamera = Camera::connect(cameraId);
if (mCamera == NULL)
{
mConnected = false_e;
return STATUS_FAILURE;
}
mCamera->lock();
initCameraParameters();
mConnected = true_e;
return STATUS_SUCCESS;
}
status_e CSVisionCam::startPreview()
{
status_t err;
if (mCamera == NULL)
{
DVP_PRINT(DVP_ZONE_CAM, "startPreview camera is null\n");
return STATUS_INVALID_STATE;
}
status_e status = setCameraParameters();
if (status != STATUS_SUCCESS)
{
DVP_PRINT(DVP_ZONE_CAM, "startPreview: setParameters failed! status= 0x%x\n", status);
return status;
}
#if defined(JELLYBEAN)
sp<BufferQueue> bufferQueue = NULL;
if (mSurfaceTexture == NULL)
{
DVP_PRINT(DVP_ZONE_CAM, "startPreview: mSurfaceTexture is NULL!\n");
return STATUS_FAILURE;
}
bufferQueue = mSurfaceTexture->getBufferQueue();
err = mCamera->setPreviewTexture(bufferQueue);
#else
err = mCamera->setPreviewTexture(mSurfaceTexture);
#endif
if (err)
{
DVP_PRINT(DVP_ZONE_CAM, "startPreview: setPreviewTexture failed! error= %d\n", err);
return STATUS_FAILURE;
}
mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_CAMERA);
// mCamera->setListener(new VisionCamListener(this));
mCamera->setListener(this);
DVP_PRINT(DVP_ZONE_CAM, "startPreview: starting preview %dx%d:0x%x",
mWidth, mHeight, mColorSpace);
err = mCamera->startPreview();
if (err)
{
DVP_PRINT(DVP_ZONE_CAM, "startPreview: startPreview failed! error= %d\n", err);
return STATUS_FAILURE;
}
return STATUS_SUCCESS;
}
status_e CSVisionCam::stopPreview()
{
if (mCamera == NULL)
return STATUS_INVALID_STATE;
mCamera->stopPreview();
mCamera->setListener(NULL);
mCamera->setPreviewTexture(NULL);
return STATUS_SUCCESS;
}
status_e CSVisionCam::toggleFaceDetection()
{
status_t err;
if (mCamera == NULL)
return STATUS_INVALID_STATE;
DVP_PRINT(DVP_ZONE_CAM, "toggleFaceDetection: %s face detection ...\n",
mFaceDetectionEnabled?"stopping":"starting");
if (mFaceDetectionEnabled)
{
err = mCamera->sendCommand(CAMERA_CMD_STOP_FACE_DETECTION, 0, 0);
}
else
{
err = mCamera->sendCommand(CAMERA_CMD_START_FACE_DETECTION, 0, 0);
}
if (err)
{
DVP_PRINT(DVP_ZONE_CAM, "toggleFaceDetection: %s Face Detection failed! error= %d\n",
mFaceDetectionEnabled?"stopping":"starting", err);
return STATUS_FAILURE;
}
mFaceDetectionEnabled = (bool_e)!mFaceDetectionEnabled;
return STATUS_SUCCESS;
}
status_e CSVisionCam::lockAutoWhitebalance(bool_e lock)
{
status_t err;
CameraParameters params(mCamera->getParameters());
if (lock == true_e)
params.set(android::CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK, android::CameraParameters::TRUE);
else
params.set(android::CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK, android::CameraParameters::FALSE);
err = mCamera->setParameters(params.flatten());
if (err)
{
DVP_PRINT(DVP_ZONE_CAM, "lockAutoWhitebalance: setParameters failed! error= %d\n", err);
return STATUS_FAILURE;
}
return STATUS_SUCCESS;
}
status_e CSVisionCam::lockAutoExposure(bool_e lock)
{
status_t err;
CameraParameters params(mCamera->getParameters());
if (lock == true_e)
params.set(android::CameraParameters::KEY_AUTO_EXPOSURE_LOCK, android::CameraParameters::TRUE);
else
params.set(android::CameraParameters::KEY_AUTO_EXPOSURE_LOCK, android::CameraParameters::FALSE);
err = mCamera->setParameters(params.flatten());
if (err)
{
DVP_PRINT(DVP_ZONE_CAM, "lockAutoExposure: setParameters failed! error= %d\n", err);
return STATUS_FAILURE;
}
return STATUS_SUCCESS;
}
status_e CSVisionCam::setFlicker(VisionCamFlickerType type)
{
status_t err;
CameraParameters params(mCamera->getParameters());
const char *flicker = flickerToAntibanding(type);
if (flicker == NULL)
{
return STATUS_INVALID_PARAMETER;
}
params.set(android::CameraParameters::KEY_ANTIBANDING, flicker);
err = mCamera->setParameters(params.flatten());
if (err)
{
DVP_PRINT(DVP_ZONE_CAM, "setFlicker: setParameters failed! error= %d\n", err);
return STATUS_FAILURE;
}
mFlicker = type;
return STATUS_SUCCESS;
}
status_e CSVisionCam::setExposureCompensation(int32_t compensation)
{
status_t err;
CameraParameters params(mCamera->getParameters());
char tmpBuffer[16];
sprintf(tmpBuffer, "%d", compensation);
params.set(android::CameraParameters::KEY_EXPOSURE_COMPENSATION, tmpBuffer);
err = mCamera->setParameters(params.flatten());
if (err)
{
DVP_PRINT(DVP_ZONE_CAM, "setExposureCompensation: setParameters failed! error= %d\n", err);
return STATUS_FAILURE;
}
mEVCompensation = compensation;
return STATUS_SUCCESS;
}
status_e CSVisionCam::initFrameDescriptors()
{
status_e error = STATUS_SUCCESS;
for (uint32_t i = 0; i < MAX_FRAMES; i++)
{
mFrameDescriptors[i] = new VisionCamFrame();
if (mFrameDescriptors[i])
{
mFrameDescriptors[i]->clear();
}
else
{
while (i)
delete mFrameDescriptors[--i];
error = STATUS_NOT_ENOUGH_MEMORY;
}
}
return error;
}
status_e CSVisionCam::deinitFrameDescriptors()
{
for (uint32_t i = 0; i < MAX_FRAMES; i++)
{
delete mFrameDescriptors[i];
}
return STATUS_SUCCESS;
}
status_e CSVisionCam::initCameraParameters()
{
CameraParameters params(mCamera->getParameters());
params.getPreviewSize((int *)&mWidth, (int *)&mHeight);
params.getPreviewFpsRange((int *)&mVfr.mMin, (int *)&mVfr.mMax);
mColorSpace = previewFormatToColorSpace(params.getPreviewFormat());
mFlicker = antibandingToFlicker(params.get(android::CameraParameters::KEY_ANTIBANDING));
mEVCompensation = (int32_t)params.getInt(android::CameraParameters::KEY_EXPOSURE_COMPENSATION);
mContrast = (int32_t)params.getInt(KEY_CONTRAST);
mSharpness = (int32_t)params.getInt(KEY_SHARPNESS);
mBrightness = (int32_t)params.getInt(KEY_BRIGHTNESS);
mSaturation = (int32_t)params.getInt(KEY_SATURATION);
DVP_PRINT(DVP_ZONE_CAM, "initCameraParameters:\n");
DVP_PRINT(DVP_ZONE_CAM, " Width, Height= %dx%d\n", mWidth, mHeight);
DVP_PRINT(DVP_ZONE_CAM, " Fps Range= %d:%d\n", mVfr.mMin, mVfr.mMax);
DVP_PRINT(DVP_ZONE_CAM, " ColorSpace= %s\n", fourcctostr(mColorSpace));
DVP_PRINT(DVP_ZONE_CAM, " Flicker= %s\n", flickerToString(mFlicker));
DVP_PRINT(DVP_ZONE_CAM, " Exposure Compensation= %d\n", mEVCompensation);
DVP_PRINT(DVP_ZONE_CAM, " Contrast= %d\n", mContrast);
DVP_PRINT(DVP_ZONE_CAM, " Sharpness= %d\n", mSharpness);
DVP_PRINT(DVP_ZONE_CAM, " Brightness= %d\n", mBrightness);
DVP_PRINT(DVP_ZONE_CAM, " Saturation= %d\n", mSaturation);
return STATUS_SUCCESS;
}
status_e CSVisionCam::setCameraParameters()
{
status_t err;
char tmpBuffer[64];
CameraParameters params(mCamera->getParameters());
params.setPreviewSize(mWidth, mHeight);
const char *previewFormat = colorSpaceToPreviewFormat(mColorSpace);
if (previewFormat == NULL)
{
return STATUS_INVALID_PARAMETER;
}
params.setPreviewFormat(previewFormat); // YUY2
const char *flicker = flickerToAntibanding(mFlicker);
if (flicker == NULL)
{
return STATUS_INVALID_PARAMETER;
}
params.set(android::CameraParameters::KEY_ANTIBANDING, flicker);
sprintf(tmpBuffer, "%d", mEVCompensation);
params.set(android::CameraParameters::KEY_EXPOSURE_COMPENSATION, tmpBuffer);
sprintf(tmpBuffer, "%d,%d", mVfr.mMin * 1000, mVfr.mMax * 1000);
params.set(android::CameraParameters::KEY_PREVIEW_FPS_RANGE, tmpBuffer);
sprintf(tmpBuffer, "%d", mContrast);
params.set(KEY_CONTRAST, tmpBuffer);
sprintf(tmpBuffer, "%d", mSharpness);
params.set(KEY_SHARPNESS, tmpBuffer);
sprintf(tmpBuffer, "%d", mBrightness);
params.set(KEY_BRIGHTNESS, tmpBuffer);
sprintf(tmpBuffer, "%d", mSaturation);
params.set(KEY_SATURATION, tmpBuffer);
err = mCamera->setParameters(params.flatten());
if (err)
{
return STATUS_FAILURE;
}
return STATUS_SUCCESS;
}
void CSVisionCam::notify(int32_t msgType, int32_t ext1, int32_t ext2)
{
DVP_PRINT(DVP_ZONE_CAM, "notify(0x%x, %d, %d)", msgType, ext1, ext2);
}
void CSVisionCam::postData(int32_t msgType,
const sp<IMemory> &dataPtr,
camera_frame_metadata_t *metadata)
{
DVP_PRINT(DVP_ZONE_CAM, "postData(0x%x, ptr:%p, size:%d, meta:%p)",
msgType, dataPtr->pointer(), dataPtr->size(), metadata);
if (msgType & CAMERA_MSG_PREVIEW_FRAME)
{
dataCallback(msgType, dataPtr, metadata);
}
}
void CSVisionCam::postDataTimestamp(nsecs_t timestamp,
int32_t msgType,
const sp<IMemory>& dataPtr)
{
DVP_PRINT(DVP_ZONE_CAM, "postDataTimestamp(0x%x, ptr:%p, size:%d)",
msgType, dataPtr->pointer(), dataPtr->size());
dataCallbackTimestamp(timestamp/1000, msgType, dataPtr);
}
const char* CSVisionCam::colorSpaceToPreviewFormat(_fourcc colorSpace)
{
switch (colorSpace)
{
case FOURCC_YUY2:
case FOURCC_UYVY:
return PIXEL_FORMAT_YUV422I;
break;
case FOURCC_NV21:
return PIXEL_FORMAT_YUV420SP;
break;
default:
break;
}
return NULL;
}
_fourcc CSVisionCam::previewFormatToColorSpace(const char* previewFormat)
{
if (!strcmp(previewFormat, PIXEL_FORMAT_YUV422I))
{
return FOURCC_NV21;
}
else if (!strcmp(previewFormat, PIXEL_FORMAT_YUV420SP))
{
return FOURCC_YUY2;
}
return FOURCC_NONE;
}
const char* CSVisionCam::flickerToAntibanding(VisionCamFlickerType type)
{
switch (type)
{
case FLICKER_OFF:
return android::CameraParameters::ANTIBANDING_OFF;
break;
case FLICKER_AUTO:
return android::CameraParameters::ANTIBANDING_AUTO;
break;
case FLICKER_50Hz:
return android::CameraParameters::ANTIBANDING_50HZ;
break;
case FLICKER_60Hz:
return android::CameraParameters::ANTIBANDING_60HZ;
break;
default:
break;
}
return NULL;
}
VisionCamFlickerType CSVisionCam::antibandingToFlicker(const char* antibanding)
{
if (!strcmp(antibanding, android::CameraParameters::ANTIBANDING_AUTO))
{
return FLICKER_AUTO;
}
else if (!strcmp(antibanding, android::CameraParameters::ANTIBANDING_50HZ))
{
return FLICKER_50Hz;
}
else if (!strcmp(antibanding, android::CameraParameters::ANTIBANDING_60HZ))
{
return FLICKER_60Hz;
}
return FLICKER_OFF;
}
const char* CSVisionCam::flickerToString(VisionCamFlickerType flicker)
{
if ((uint32_t)flicker >= sizeof(FLICKER_STR))
return "UNKNOWN";
return FLICKER_STR[flicker];
}
#endif // ANDROID
| 26.902468
| 136
| 0.611601
|
emrainey
|
eaea10784731ca247eea129f7d3f49235614b448
| 10,832
|
hpp
|
C++
|
sugarless.hpp
|
ChanTsune/sugarless
|
9960bf238ab1dc608ed06e26cdafdb552e1d561e
|
[
"MIT"
] | null | null | null |
sugarless.hpp
|
ChanTsune/sugarless
|
9960bf238ab1dc608ed06e26cdafdb552e1d561e
|
[
"MIT"
] | null | null | null |
sugarless.hpp
|
ChanTsune/sugarless
|
9960bf238ab1dc608ed06e26cdafdb552e1d561e
|
[
"MIT"
] | null | null | null |
#pragma once
#ifndef SUGARLESS_HPP
#define SUGARLESS_HPP
#include <map>
#include <string>
#include <vector>
#include <ostream>
namespace sugarless
{
const static std::string empty_str("");
const static std::string short_token("-");
const static std::string connect_token("=");
const static std::string long_token("--");
const static std::string argument_flag("--");
template<class _Elme>
inline size_t partition(std::basic_string<_Elme> target,std::basic_string<_Elme> sep, std::basic_string<_Elme> &dst1, std::basic_string<_Elme> &dst2, std::basic_string<_Elme> &dst3)
{
size_t index = target.find(sep);
if (index == std::basic_string<_Elme>::npos)
{
dst1 = target;
dst2 = empty_str;
dst3 = empty_str;
}
else
{
dst1 = target.substr(0, index);
dst2 = sep;
dst3 = target.substr(index + sep.size());
}
return index;
}
template<class _Elme>
inline bool startswith(const std::basic_string<_Elme> target,const std::basic_string<_Elme> suffix, int start=0, int end=INT_MAX)
{
int len = target.size();
int sublen = suffix.size();
const _Elme *self = target.c_str();
const _Elme *sub = suffix.c_str();
if (start + sublen > len)
{
return false;
}
if (end - start >= sublen)
{
return (!std::memcmp(self + start * sizeof(_Elme), sub, sublen * sizeof(_Elme)));
}
return false;
}
class Flag
{
public:
std::string short_name;
std::string long_name;
std::string argument;
bool require_argument;
bool exist;
Flag(void){};
Flag(const char* short_name,const char * long_name,bool require_argument,const char * argument)
{
if(short_name == NULL)
this->short_name = empty_str;
else
this->short_name = short_name;
if(long_name == NULL)
this->long_name = empty_str;
else
this->long_name = long_name;
this->long_name = long_name;
this->require_argument = require_argument;
this->argument = argument;
this->exist = false;
}
};
enum
{
OK,
MISSING_ARGUMENT,
INVALID_FLAG,
};
const static char * OK_MESSAGE = "parse complete";
const static char * MISSING_ARGUMENT_MESSAGE = "require argument";
const static char * INVALID_FLAG_MESSAGE = " invalid option";
const char * get_error_message(int errornumber)
{
switch (errornumber)
{
case OK:
return OK_MESSAGE;
case MISSING_ARGUMENT:
return MISSING_ARGUMENT_MESSAGE;
case INVALID_FLAG:
return INVALID_FLAG_MESSAGE;
default:
break;
}
return OK_MESSAGE;
}
class Command
{
private:
std::map<std::string,Flag,std::less<>> flags;
std::map<std::string,Command*,std::less<>> sub_commands;
bool exist;
bool is_long_name(std::string &name);
bool is_short_name(std::string &name);
bool is_opt(std::string &name);
public:
std::vector<char *> others;
int parse(int argc,char const* argv[],int position=1);
Command &flag(const char *id, const char *short_name, const char *long_name, bool require_argument=false, const char * default_argument=empty_str.c_str());
Command &flag(const char *id, const char *short_name, const char *long_name, const char * default_argument);
bool has(const char *id);
const char *get(const char *id);
Command &subcommand(const char *command_name,Command &cmd,bool inheritanc=false);
bool has_subcommand(const char*command_name);
Command get_subcommand(const char *command_name);
template <class _Elme, class _Traits>
friend std::basic_ostream<_Elme, _Traits> &operator<<(std::basic_ostream<_Elme, _Traits> &stream, const Command &self);
};
/* operator */
template <class _Elme, class _Traits>
std::basic_ostream<_Elme, _Traits> &operator<<(std::basic_ostream<_Elme, _Traits> &stream, const Command &self)
{
for(auto &&subc:self.sub_commands)
{
stream << std::boolalpha
<< subc.first << " ::: " << std::endl
<< *(subc.second) << std::endl
<< std::noboolalpha;
}
for(auto &&flg: self.flags )
{
stream << std::boolalpha
<< flg.first << " : " << flg.second.exist << std::endl
<< "argumens : " << flg.second.argument << std::endl
<< std::noboolalpha;
}
return stream;
}
/* end operator */
inline bool Command::is_long_name(std::string &name)
{
return startswith(name, long_token);
}
inline bool Command::is_short_name(std::string &name)
{
return startswith(name,short_token);
}
inline bool Command::is_opt(std::string &name)
{
return this->is_short_name(name) || this->is_short_name(name);
}
int Command::parse(int argc,char const* argv[],int position)
{
bool forced_arg = false; // -- がよく前に指定された場合T、次は必ず引数として振る舞うかあるいはothersに突っ込まれる
bool req_arg = false;//直前のオプションが引数を必要とする場合にT
bool maybe_arg = false; // デフォルト引数持ちでかつ引数が指定されてない場合に引数かも知れない
std::string previous_flag_id = empty_str;//直前のオプションが引数を要求する場合のフラグID
for(; position < argc; ++position)
{
std::string strargv(argv[position]);
if(!forced_arg && strargv == argument_flag)
{
forced_arg = true;
continue;
}
if(forced_arg)
{
goto ARGUMENTS;
}
if(this->is_long_name(strargv))
{// long
for(auto&& flg:this->flags)
{
if (flg.second.long_name.empty()) continue;
if (startswith(strargv,flg.second.long_name,long_token.size() ))
{// 引数の先頭がロング名と一致する場合
flg.second.exist = true;
if (flg.second.require_argument)
{// 引数を要求するオプションの場合
//ここで=分割指定と=無し結合指定を探す
std::string l,r,sep;
partition(strargv.substr(long_token.size() ),connect_token,l,sep,r);//--部分を取り除いたコマンドラインからのロング名
if (!r.empty())
{//右側が空でなければそれを引数の値として確定する
flg.second.argument = r;
}// end if
else if (r.empty() && l.size() > flg.second.long_name.size() )
{//右側が空、かつ左がロング名より長い場合は左側の先頭からロング名の長さ分削ったものを引数の値とする
flg.second.argument = l.substr(flg.second.long_name.size());
}// end else if
else
{//綺麗にロング名だけを指定された場合
previous_flag_id = flg.first;
req_arg = true;
if (! flg.second.argument.empty())
{// 引数を要求するオプションでかつ、デフォルト引数が設定されている場合
// この場合は、次がオプション形式の書き方をしていなければその値を引数とする
maybe_arg = true;
}
}// end else
}// end if
break;// ロング名とマッチしているからそれ以上の比較は必要ないためループ終了
}// end if
}// end for
}// end if
else if (this->is_short_name(strargv))// short
{
size_t slen = strargv.size();
bool req_arg_s = false;
for(size_t i = short_token.size(); i < slen; ++i)
{
bool short_muched = false;
for(auto&& flg:this->flags)
{
if (flg.second.short_name.empty()) continue;
if (strargv[i] == flg.second.short_name[0])
{
flg.second.exist = true;
req_arg_s = flg.second.require_argument;
previous_flag_id = flg.first;
short_muched = true;
break;
}
}
if(!short_muched && req_arg_s)
{//直前のオプションが引数をとる場合
// 現在のstrargv[i]が他のショート名に含まれていなければそれ以降を引数とする
this->flags[previous_flag_id].argument = strargv.substr(i);
break;
}
}
req_arg = req_arg_s;
}
else if(req_arg)
{
this->flags[previous_flag_id].argument = strargv;
}
else
{//何のオプションにも該当しない場合
for(auto&& sb:this->sub_commands)
{//いずれのオプションにもマッチしなかった場合にサブコマンドの可能性を探る
if(sb.first==strargv)
{
sb.second->exist = true;
return sb.second->parse(argc,argv,position);
}
}
ARGUMENTS:
if (maybe_arg)
{//直前のオプションが引数を要求しているかつ、デフォルト引数が設定されている場合
if(!this->is_opt(strargv))
{
this->flags[previous_flag_id].argument = strargv;
}
maybe_arg = false;
}
else if (req_arg)
{//直前のオプションが引数を要求する場合
this->flags[previous_flag_id].argument = strargv;
if(!this->is_opt(strargv))
{
return MISSING_ARGUMENT;
}
maybe_arg = false;
req_arg = false;
}
else
{//全てに当てはまらない
char * tmp = const_cast<char*>(argv[position]);
this->others.push_back(tmp);
}
}
}
return OK;
}
Command &Command::flag(const char *id, const char *short_name, const char *long_name, bool require_argument, const char * default_argument)
{
//TODO:NULL chack frase
this->flags[std::string(id)] = Flag(short_name,long_name,require_argument,default_argument);
return *this;
}
Command &Command::flag(const char *id, const char *short_name, const char *long_name, const char * default_argument)
{
this->flags[std::string(id)] = Flag(short_name,long_name,true,default_argument);
return *this;
}
bool Command::has(const char *id)
{
return this->flags[std::string(id)].exist;
}
const char *Command::get(const char *id)
{
return this->flags[std::string(id)].argument.c_str();
}
Command &Command::subcommand(const char *command_name,Command &cmd,bool inheritanc)
{
// TODO: refactor map merge
if (inheritanc) {
for(auto&& flg:this->flags)
{
cmd.flags[flg.first] = flg.second;
}
}
this->sub_commands[std::string(command_name)] = &cmd;
return *this;
}
bool Command::has_subcommand(const char*command_name)
{
return this->sub_commands[std::string(command_name)]->exist;
}
Command Command::get_subcommand(const char *command_name)
{
return *(this->sub_commands[std::string(command_name)]);
}
}// end nemaspace sugarless
#endif //include gard SUGARLESS_HPP
| 30.512676
| 181
| 0.562131
|
ChanTsune
|
eaf4b6169d2dc71d1d86c82080725b2009322b3b
| 9,094
|
cc
|
C++
|
http2/adapter/callback_visitor.cc
|
HsingYun/quiche
|
dc872748c9f7c24adc439eb1ce51e687bc78d502
|
[
"BSD-3-Clause"
] | null | null | null |
http2/adapter/callback_visitor.cc
|
HsingYun/quiche
|
dc872748c9f7c24adc439eb1ce51e687bc78d502
|
[
"BSD-3-Clause"
] | null | null | null |
http2/adapter/callback_visitor.cc
|
HsingYun/quiche
|
dc872748c9f7c24adc439eb1ce51e687bc78d502
|
[
"BSD-3-Clause"
] | null | null | null |
#include "http2/adapter/callback_visitor.h"
#include "http2/adapter/nghttp2_util.h"
#include "third_party/nghttp2/src/lib/includes/nghttp2/nghttp2.h"
#include "common/quiche_endian.h"
// This visitor implementation needs visibility into the
// nghttp2_session_callbacks type. There's no public header, so we'll redefine
// the struct here.
struct nghttp2_session_callbacks {
nghttp2_send_callback send_callback;
nghttp2_recv_callback recv_callback;
nghttp2_on_frame_recv_callback on_frame_recv_callback;
nghttp2_on_invalid_frame_recv_callback on_invalid_frame_recv_callback;
nghttp2_on_data_chunk_recv_callback on_data_chunk_recv_callback;
nghttp2_before_frame_send_callback before_frame_send_callback;
nghttp2_on_frame_send_callback on_frame_send_callback;
nghttp2_on_frame_not_send_callback on_frame_not_send_callback;
nghttp2_on_stream_close_callback on_stream_close_callback;
nghttp2_on_begin_headers_callback on_begin_headers_callback;
nghttp2_on_header_callback on_header_callback;
nghttp2_on_header_callback2 on_header_callback2;
nghttp2_on_invalid_header_callback on_invalid_header_callback;
nghttp2_on_invalid_header_callback2 on_invalid_header_callback2;
nghttp2_select_padding_callback select_padding_callback;
nghttp2_data_source_read_length_callback read_length_callback;
nghttp2_on_begin_frame_callback on_begin_frame_callback;
nghttp2_send_data_callback send_data_callback;
nghttp2_pack_extension_callback pack_extension_callback;
nghttp2_unpack_extension_callback unpack_extension_callback;
nghttp2_on_extension_chunk_recv_callback on_extension_chunk_recv_callback;
nghttp2_error_callback error_callback;
nghttp2_error_callback2 error_callback2;
};
namespace http2 {
namespace adapter {
void CallbackVisitor::OnConnectionError() {
QUICHE_LOG(FATAL) << "Not implemented";
}
void CallbackVisitor::OnFrameHeader(Http2StreamId stream_id,
size_t length,
uint8_t type,
uint8_t flags) {
// The general strategy is to clear |current_frame_| at the start of a new
// frame, accumulate frame information from the various callback events, then
// invoke the on_frame_recv_callback() with the accumulated frame data.
memset(¤t_frame_, 0, sizeof(current_frame_));
current_frame_.hd.stream_id = stream_id;
current_frame_.hd.length = length;
current_frame_.hd.type = type;
current_frame_.hd.flags = flags;
callbacks_->on_begin_frame_callback(nullptr, ¤t_frame_.hd, user_data_);
}
void CallbackVisitor::OnSettingsStart() {}
void CallbackVisitor::OnSetting(Http2Setting setting) {
settings_.push_back({.settings_id = setting.id, .value = setting.value});
}
void CallbackVisitor::OnSettingsEnd() {
current_frame_.settings.niv = settings_.size();
current_frame_.settings.iv = settings_.data();
callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_, user_data_);
settings_.clear();
}
void CallbackVisitor::OnSettingsAck() {
// ACK is part of the flags, which were set in OnFrameHeader().
callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_, user_data_);
}
void CallbackVisitor::OnBeginHeadersForStream(Http2StreamId stream_id) {
auto it = stream_map_.find(stream_id);
if (it == stream_map_.end()) {
auto p = stream_map_.insert({stream_id, absl::make_unique<StreamInfo>()});
it = p.first;
}
if (it->second->received_headers) {
// At least one headers frame has already been received.
current_frame_.headers.cat = NGHTTP2_HCAT_HEADERS;
} else {
switch (perspective_) {
case Perspective::kClient:
current_frame_.headers.cat = NGHTTP2_HCAT_RESPONSE;
break;
case Perspective::kServer:
current_frame_.headers.cat = NGHTTP2_HCAT_REQUEST;
break;
}
}
callbacks_->on_begin_headers_callback(nullptr, ¤t_frame_, user_data_);
it->second->received_headers = true;
}
void CallbackVisitor::OnHeaderForStream(Http2StreamId stream_id,
absl::string_view name,
absl::string_view value) {
callbacks_->on_header_callback(
nullptr, ¤t_frame_, ToUint8Ptr(name.data()), name.size(),
ToUint8Ptr(value.data()), value.size(), NGHTTP2_NV_FLAG_NONE, user_data_);
}
void CallbackVisitor::OnEndHeadersForStream(Http2StreamId stream_id) {
callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_, user_data_);
}
void CallbackVisitor::OnBeginDataForStream(Http2StreamId stream_id,
size_t payload_length) {
// TODO(b/181586191): Interpret padding, subtract padding from
// |remaining_data_|.
remaining_data_ = payload_length;
if (remaining_data_ == 0) {
callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_, user_data_);
}
}
void CallbackVisitor::OnDataForStream(Http2StreamId stream_id,
absl::string_view data) {
callbacks_->on_data_chunk_recv_callback(nullptr, current_frame_.hd.flags,
stream_id, ToUint8Ptr(data.data()),
data.size(), user_data_);
remaining_data_ -= data.size();
if (remaining_data_ == 0) {
callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_, user_data_);
}
}
void CallbackVisitor::OnEndStream(Http2StreamId stream_id) {}
void CallbackVisitor::OnRstStream(Http2StreamId stream_id,
Http2ErrorCode error_code) {
current_frame_.rst_stream.error_code = static_cast<uint32_t>(error_code);
callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_, user_data_);
}
void CallbackVisitor::OnCloseStream(Http2StreamId stream_id,
Http2ErrorCode error_code) {
callbacks_->on_stream_close_callback(
nullptr, stream_id, static_cast<uint32_t>(error_code), user_data_);
}
void CallbackVisitor::OnPriorityForStream(Http2StreamId stream_id,
Http2StreamId parent_stream_id,
int weight,
bool exclusive) {
current_frame_.priority.pri_spec.stream_id = parent_stream_id;
current_frame_.priority.pri_spec.weight = weight;
current_frame_.priority.pri_spec.exclusive = exclusive;
callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_, user_data_);
}
void CallbackVisitor::OnPing(Http2PingId ping_id, bool is_ack) {
uint64_t network_order_opaque_data =
quiche::QuicheEndian::HostToNet64(ping_id);
std::memcpy(current_frame_.ping.opaque_data, &network_order_opaque_data,
sizeof(network_order_opaque_data));
callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_, user_data_);
}
void CallbackVisitor::OnPushPromiseForStream(Http2StreamId stream_id,
Http2StreamId promised_stream_id) {
QUICHE_LOG(FATAL) << "Not implemented";
}
void CallbackVisitor::OnGoAway(Http2StreamId last_accepted_stream_id,
Http2ErrorCode error_code,
absl::string_view opaque_data) {
current_frame_.goaway.last_stream_id = last_accepted_stream_id;
current_frame_.goaway.error_code = static_cast<uint32_t>(error_code);
current_frame_.goaway.opaque_data = ToUint8Ptr(opaque_data.data());
current_frame_.goaway.opaque_data_len = opaque_data.size();
callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_, user_data_);
}
void CallbackVisitor::OnWindowUpdate(Http2StreamId stream_id,
int window_increment) {
current_frame_.window_update.window_size_increment = window_increment;
callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_, user_data_);
}
void CallbackVisitor::OnReadyToSendDataForStream(Http2StreamId stream_id,
char* destination_buffer,
size_t length,
ssize_t* written,
bool* end_stream) {
QUICHE_LOG(FATAL) << "Not implemented";
}
void CallbackVisitor::OnReadyToSendMetadataForStream(Http2StreamId stream_id,
char* buffer,
size_t length,
ssize_t* written) {
QUICHE_LOG(FATAL) << "Not implemented";
}
void CallbackVisitor::OnBeginMetadataForStream(Http2StreamId stream_id,
size_t payload_length) {
QUICHE_LOG(FATAL) << "Not implemented";
}
void CallbackVisitor::OnMetadataForStream(Http2StreamId stream_id,
absl::string_view metadata) {
QUICHE_LOG(FATAL) << "Not implemented";
}
void CallbackVisitor::OnMetadataEndForStream(Http2StreamId stream_id) {
QUICHE_LOG(FATAL) << "Not implemented";
}
} // namespace adapter
} // namespace http2
| 42.101852
| 80
| 0.703101
|
HsingYun
|
eaf4e3dd00b32b751684047362945290f55e3767
| 1,881
|
cpp
|
C++
|
src/editor/tile_selector.cpp
|
nadult/FreeFT
|
f0f63951632d06dd4f6d24ca76b03f38b995cd78
|
[
"Unlicense"
] | 118
|
2015-01-26T12:49:58.000Z
|
2022-03-19T00:02:01.000Z
|
src/editor/tile_selector.cpp
|
nadult/FreeFT
|
f0f63951632d06dd4f6d24ca76b03f38b995cd78
|
[
"Unlicense"
] | 6
|
2015-03-29T14:59:40.000Z
|
2020-08-14T22:04:48.000Z
|
src/editor/tile_selector.cpp
|
nadult/FreeFT
|
f0f63951632d06dd4f6d24ca76b03f38b995cd78
|
[
"Unlicense"
] | 14
|
2015-01-18T13:55:13.000Z
|
2021-11-30T06:56:58.000Z
|
// Copyright (C) Krzysztof Jakubowski <nadult@fastmail.fm>
// This file is part of FreeFT. See license.txt for details.
#include "gfx/drawing.h"
#include "editor/tile_selector.h"
using game::Tile;
namespace ui {
TileSelector::TileSelector(IRect rect) :Window(rect, WindowStyle::gui_dark),
m_tile_list(rect.width(), 2), m_selection(nullptr) {
update();
}
void TileSelector::setModel(PTileListModel model) {
m_tile_list.setModel(model);
setInnerRect(IRect(0, 0, rect().width(), m_tile_list.m_height));
m_selection = nullptr;
}
void TileSelector::update() {
m_tile_list.update();
setInnerRect(IRect(0, 0, rect().width(), m_tile_list.m_height));
}
void TileSelector::setSelection(const game::Tile *tile) {
m_selection = nullptr;
for(int n = 0; n < m_tile_list.size(); n++)
if(m_tile_list[n].tile == tile) {
m_selection = &m_tile_list[n];
return;
}
}
void TileSelector::drawContents(Renderer2D &out) const {
int2 offset = innerOffset();
IRect clip_rect(int2(0, 0), clippedRect().size());
for(int n = 0; n < (int)m_tile_list.size(); n++) {
const Tile *tile = m_tile_list[n].tile;
IRect tile_rect = tile->rect();
int2 pos = m_tile_list[n].pos - tile_rect.min() - offset;
if(areOverlapping(clip_rect, tile_rect + pos))
tile->draw(out, pos);
}
if(m_selection) {
int2 pos = m_selection->pos - offset;
out.setViewPos(-clippedRect().min() - pos + m_selection->tile->rect().min());
IBox box(int3(0, 0, 0), m_selection->tile->bboxSize());
drawBBox(out, box);
// out.addFilledRect(IRect(pos, pos + m_selection->size));
}
}
bool TileSelector::onMouseDrag(const InputState&, int2 start, int2 current, int key, int is_final) {
if(key == 0) {
m_selection = m_tile_list.find(current + innerOffset());
sendEvent(this, Event::element_selected);
return true;
}
return false;
}
}
| 26.492958
| 101
| 0.671983
|
nadult
|
eaf7888539d534b03852aa67044dff2de81c8392
| 680
|
cpp
|
C++
|
01-Recover/LT0283.cpp
|
odeinjul/Solution_New
|
12593def5ae867e8193847184792b7fbe00aeff0
|
[
"MIT"
] | null | null | null |
01-Recover/LT0283.cpp
|
odeinjul/Solution_New
|
12593def5ae867e8193847184792b7fbe00aeff0
|
[
"MIT"
] | null | null | null |
01-Recover/LT0283.cpp
|
odeinjul/Solution_New
|
12593def5ae867e8193847184792b7fbe00aeff0
|
[
"MIT"
] | null | null | null |
class Solution {
public:
void moveZeroes(vector<int>& nums) {
for(int i=nums.size()-1; i > 0; i--){
while(nums[i] != 0 && nums[i-1] == 0){
int a=nums[i];
nums[i-1] = a;
nums[i] = 0;
if(i < nums.size()-1)
i++;
}
}
}
};
/*
void moveZeroes(vector<int>& nums) {
int counter = 0;
for(int i=0; i < nums.size(); i++){
if(nums[i]==0) counter++;
else nums[i - counter] = nums[i];
}
while(counter > 0){
nums[nums.size()-counter]=0;
counter--;
}
}
//wjoker
*/
| 24.285714
| 50
| 0.376471
|
odeinjul
|
46ae29501587636ff96eda36aafa072f014c3879
| 4,560
|
cpp
|
C++
|
ch7/sensor/ch7_msgfltr_cpp/src/selfilter.cpp
|
homalozoa/ros2_for_beginners_code
|
0515621d9cb53cc0c0e2380cf9a52e68ce975e76
|
[
"Apache-2.0"
] | null | null | null |
ch7/sensor/ch7_msgfltr_cpp/src/selfilter.cpp
|
homalozoa/ros2_for_beginners_code
|
0515621d9cb53cc0c0e2380cf9a52e68ce975e76
|
[
"Apache-2.0"
] | null | null | null |
ch7/sensor/ch7_msgfltr_cpp/src/selfilter.cpp
|
homalozoa/ros2_for_beginners_code
|
0515621d9cb53cc0c0e2380cf9a52e68ce975e76
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2022 Homalozoa
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <string>
#include <utility>
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/fluid_pressure.hpp"
#include "sensor_msgs/msg/illuminance.hpp"
class SelFilter : public rclcpp::Node
{
public:
explicit SelFilter(const std::string & node_name)
: Node(node_name)
{
using namespace std::chrono_literals;
this->pressure_.header.frame_id = "pressure_link";
this->illuminance_.header.frame_id = "illuminance_link";
this->pressure_.fluid_pressure = 98000;
pressure_pub_ = this->create_publisher<sensor_msgs::msg::FluidPressure>(
"sync_pressure",
rclcpp::SystemDefaultsQoS());
illuminance_pub_ = this->create_publisher<sensor_msgs::msg::Illuminance>(
"sync_illuminance",
rclcpp::SystemDefaultsQoS());
auto pubtimer_callback =
[&]() -> void {
builtin_interfaces::msg::Time ts(this->get_clock()->now());
// ts.nanosec = 0;
this->pressure_.header.stamp = ts;
this->pressure_.fluid_pressure += 0.01;
ts.sec += 1;
this->illuminance_.header.stamp = ts;
this->illuminance_.illuminance += 0.01;
this->pressure_pub_->publish(std::move(this->pressure_));
this->illuminance_pub_->publish(std::move(this->illuminance_));
};
pub_timer_ = this->create_wall_timer(500ms, pubtimer_callback);
}
private:
rclcpp::TimerBase::SharedPtr pub_timer_;
sensor_msgs::msg::FluidPressure pressure_;
sensor_msgs::msg::Illuminance illuminance_;
rclcpp::Publisher<sensor_msgs::msg::FluidPressure>::SharedPtr pressure_pub_;
rclcpp::Publisher<sensor_msgs::msg::Illuminance>::SharedPtr illuminance_pub_;
};
void message_ts(const std::string & TAG, const builtin_interfaces::msg::Time & ts)
{
RCLCPP_INFO(rclcpp::get_logger(TAG), "sec: %u, nanosec: %u.", ts.sec, ts.nanosec);
}
void illuminance_cb(const sensor_msgs::msg::Illuminance::SharedPtr & illuminance)
{
message_ts("ILLUMIAN_CB", illuminance->header.stamp);
}
void pressure_cb(const sensor_msgs::msg::FluidPressure::SharedPtr & pressure)
{
message_ts("PRESSURE_CB", pressure->header.stamp);
}
void ts_cb(
const sensor_msgs::msg::Illuminance::SharedPtr & illuminance,
const sensor_msgs::msg::FluidPressure::SharedPtr & pressure)
{
message_ts("TS_ILLUMIAN", illuminance->header.stamp);
message_ts("TS_PRESSURE", pressure->header.stamp);
}
#include "message_filters/subscriber.h"
#include "message_filters/cache.h"
#include "message_filters/time_synchronizer.h"
#include "message_filters/sync_policies/approximate_time.h"
#include "message_filters/sync_policies/exact_time.h"
#include "message_filters/synchronizer.h"
int main(int argc, char ** argv)
{
rclcpp::init(argc, argv);
auto node = std::make_shared<SelFilter>("selfilter");
message_filters::Subscriber<sensor_msgs::msg::Illuminance> sub_i(node, "sync_illuminance");
sub_i.registerCallback(illuminance_cb);
// message_filters::Cache<sensor_msgs::msg::Illuminance> cache_i(sub_i, 10);
// cache_i.registerCallback(illuminance_cb);
message_filters::Subscriber<sensor_msgs::msg::FluidPressure> sub_p(node, "sync_pressure");
sub_p.registerCallback(pressure_cb);
// message_filters::Cache<sensor_msgs::msg::FluidPressure> cache_p(10);
// cache_p.connectInput(sub_p);
// message_filters::TimeSynchronizer<
// sensor_msgs::msg::Illuminance,
// sensor_msgs::msg::FluidPressure> time_sync(100);
// time_sync.connectInput(sub_i, sub_p);
// time_sync.registerCallback(ts_cb);
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::msg::Illuminance,
sensor_msgs::msg::FluidPressure> ApproximatedT;
ApproximatedT policy(10);
message_filters::Synchronizer<ApproximatedT> app_sync(policy);
app_sync.connectInput(sub_i, sub_p);
app_sync.registerCallback(ts_cb);
auto executor_ = std::make_unique<rclcpp::executors::StaticSingleThreadedExecutor>();
executor_->add_node(node);
executor_->spin();
rclcpp::shutdown();
return 0;
}
| 35.625
| 93
| 0.736623
|
homalozoa
|
46ba99f86edc0385b589a1f79c91c77e5d64bc62
| 9,319
|
cpp
|
C++
|
src/extern/inventor/lib/database/src/sb/projectors/SbCylinderPlaneProjector.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 2
|
2020-05-21T07:06:07.000Z
|
2021-06-28T02:14:34.000Z
|
src/extern/inventor/lib/database/src/sb/projectors/SbCylinderPlaneProjector.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | null | null | null |
src/extern/inventor/lib/database/src/sb/projectors/SbCylinderPlaneProjector.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 6
|
2016-03-21T19:53:18.000Z
|
2021-06-08T18:06:03.000Z
|
/*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/*
* Copyright (C) 1990,91,92 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 1.1.1.1 $
|
| Classes:
| SbCylinderPlaneProjector
|
| Author(s) : Howard Look
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#include <Inventor/projectors/SbCylinderPlaneProjector.h>
#include <Inventor/errors/SoDebugError.h>
#include <stdio.h>
////////////////////////////////////////////////////////////////////////
//
// Description:
// Constructors
//
// Use: public
//
////////////////////////////////////////////////////////////////////////
SbCylinderPlaneProjector::SbCylinderPlaneProjector(
float tol,
SbBool orient)
: SbCylinderSectionProjector(tol,orient)
{
}
SbCylinderPlaneProjector::SbCylinderPlaneProjector(
const SbCylinder &c,
float,
SbBool orient)
: SbCylinderSectionProjector(c, orient)
{
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Returns an instance that is a copy of this instance. The caller
// is responsible for deleting the copy when done.
//
// Use: public, virtual
//
SbProjector *
SbCylinderPlaneProjector::copy() const
//
////////////////////////////////////////////////////////////////////////
{
SbCylinderPlaneProjector *newProjector = new SbCylinderPlaneProjector;
(*newProjector) = (*this);
return newProjector;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Project the mouse position onto a point on this cylinder.
//
// Use: public
SbVec3f
SbCylinderPlaneProjector::project(const SbVec2f &point)
//
////////////////////////////////////////////////////////////////////////
{
SbVec3f result;
SbLine workingLine = getWorkingLine(point);
if (needSetup)
setupTolerance();
SbVec3f planeIntersection;
if (! tolPlane.intersect(workingLine, planeIntersection))
#ifdef DEBUG
SoDebugError::post("SbCylinderPlaneProjector::project",
"Couldn't intersect working line with plane");
#else
/* Do nothing */;
#endif
SbVec3f cylIntersection, dontCare;
SbBool hitCyl;
if ( intersectFront == TRUE )
hitCyl = cylinder.intersect(workingLine, cylIntersection, dontCare);
else
hitCyl = cylinder.intersect(workingLine, dontCare, cylIntersection);
if (hitCyl == FALSE ) {
// missed the cylinder, so hit the plane
result = planeIntersection;
}
else {
// See if the hit on the cylinder is within tolerance.
// Project it onto the plane, and find the distance to
// the planeLine.
SbLine projectLine(cylIntersection, cylIntersection + planeDir);
SbVec3f projectIntersection;
if (! tolPlane.intersect(projectLine, projectIntersection))
#ifdef DEBUG
SoDebugError::post("SbCylinderPlaneProjector::project",
"Couldn't intersect working line with plane");
#else
/* Do nothing */;
#endif
SbVec3f vecToPoint = projectIntersection -
planeLine.getClosestPoint(projectIntersection);
float dist = vecToPoint.length();
if (dist < tolDist)
result = cylIntersection;
else
result = planeIntersection;
}
lastPoint = result;
return result;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Get a rotation based on two points on this projector.
// Rotations are _always_ about the axis of the cylinder.
//
// Use: virtual protected
//
////////////////////////////////////////////////////////////////////////
SbRotation
SbCylinderPlaneProjector::getRotation(const SbVec3f &p1, const SbVec3f &p2)
{
SbBool tol1 = isWithinTolerance(p1);
SbBool tol2 = isWithinTolerance(p2);
return getRotation(p1, tol1, p2, tol2);
}
SbRotation
SbCylinderPlaneProjector::getRotation(
const SbVec3f &p1, SbBool tol1,
const SbVec3f &p2, SbBool tol2)
{
if (tol1 && tol2) {
// Both points in tolerance, rotate about
// cylinder's axis.
// Find perpendiculars to from cylinder's axis to each
// point.
SbVec3f v1 = p1 - cylinder.getAxis().getClosestPoint(p1);
SbVec3f v2 = p2 - cylinder.getAxis().getClosestPoint(p2);
float cosAngle = v1.dot(v2)/(v1.length()*v2.length());
// prevent numerical instability problems
if ((cosAngle > 1.0) || (cosAngle < -1.0))
return SbRotation::identity();
float angle = acosf(cosAngle);
// This will either be the same as the cylinder's
// axis, or the same but with direction reversed
SbVec3f rotAxis = v1.cross(v2);
return SbRotation(rotAxis, angle);
}
else if (!tol1 && !tol2) {
SbVec3f v1 = p1 - planeLine.getClosestPoint(p1);
SbVec3f v2 = p2 - planeLine.getClosestPoint(p2);
if ( v1.dot( v2 ) < 0.0 ) {
// points are on opposite sides of the cylinder.
// Break this rotation up into 3 parts.
// [1] p1 to ptOnCylP1Side,
// [2] ptOnCylP1Side to ptOnCylP2Side,
// [3] ptOnCylP2Side to p2.
// Find the points on planeLine that are closest to p1 and p2
SbVec3f linePtNearestP1 = planeLine.getClosestPoint(p1);
SbVec3f linePtNearestP2 = planeLine.getClosestPoint(p2);
// Find the directions that go from the points in the line towards
// p1 and p2
SbVec3f dirToP1 = p1 - linePtNearestP1;
SbVec3f dirToP2 = p2 - linePtNearestP2;
dirToP1.normalize();
dirToP2.normalize();
// Find the points on the cylinder nearest p1 and p2.
SbVec3f ptOnCylP1Side = linePtNearestP1 + dirToP1 * tolDist;
SbVec3f ptOnCylP2Side = linePtNearestP2 + dirToP2 * tolDist;
return
getRotation(p1, FALSE, ptOnCylP1Side, FALSE) *
getRotation(ptOnCylP1Side, TRUE, ptOnCylP2Side, TRUE) *
getRotation(ptOnCylP2Side, FALSE, p2, FALSE);
}
else {
// Points are on same side of the cylinder.
// Rotate from one to the other, and only
// keep portion perpendicular to the cylinder's axis.
SbVec3f diff = v2 - v1;
float d = diff.length();
// moving a distance of 2*PI*radius is equivalent to
// rotating through an angle of 2*PI.
// So, (d / 2*PI*radius) = (angle / 2*PI);
// angle = d / radius
float angle = (cylinder.getRadius()==0.0)
? 0 : (d / cylinder.getRadius());
SbVec3f rotAxis = planeDir.cross(v1);
// Moving towards or moving away from cylinder.
if (v2.length() > v1.length())
return SbRotation(rotAxis, angle);
else
return SbRotation(rotAxis, -angle);
}
}
else {
// One point in tolerance, one point out of tolerance.
// (Pretend that the two points lie on a line
// that is perpendicular to the axis of the cyl.)
// Find the point on both the plane and cylinder that
// is on that line.
// Rotate twice:
// (1) from the point on the cylinder to intersection
// (2) from intersection to point off cylinder
// offCylinderPt is the one that isn't within tolerance
SbVec3f offCylinderPt = (tol1) ? p2 : p1;
// Find point on planeLine closest to offCylinderPt
SbVec3f linePtNearest = planeLine.getClosestPoint(offCylinderPt);
// Find direction that goes from linePtNearest towards offCylinderPt
SbVec3f dirToOffCylinderPt = offCylinderPt - linePtNearest;
dirToOffCylinderPt.normalize();
// Find point on the cylinder nearest offCylinderPt
SbVec3f ptOnCylinder = linePtNearest + dirToOffCylinderPt * tolDist;
if (tol1) {
// p1 is on cyl, p2 off - went off cylinder
return
getRotation(p1, TRUE, ptOnCylinder, TRUE) *
getRotation(ptOnCylinder, FALSE, p2, FALSE);
}
else {
// p1 is off cyl, p2 on - came on to cylinder
return
getRotation(p1, FALSE, ptOnCylinder, FALSE) *
getRotation(ptOnCylinder, TRUE, p2, TRUE);
}
}
}
| 29.678344
| 77
| 0.654577
|
OpenXIP
|
46c76b6eedfed9174c71e25aa43e4f37fef0fa21
| 11,955
|
cpp
|
C++
|
src/sources/BuiltinSubroutines.cpp
|
pointbazaar/dracovm-compiler
|
47eaf0bd049b205cc17fefcb7448a088b55d7d83
|
[
"MIT"
] | 5
|
2019-11-30T23:42:03.000Z
|
2020-08-12T07:47:00.000Z
|
src/sources/BuiltinSubroutines.cpp
|
pointbazaar/dracovm-compiler
|
47eaf0bd049b205cc17fefcb7448a088b55d7d83
|
[
"MIT"
] | 4
|
2019-10-17T22:18:46.000Z
|
2020-01-02T18:32:19.000Z
|
src/sources/BuiltinSubroutines.cpp
|
pointbazaar/dracovm-compiler
|
47eaf0bd049b205cc17fefcb7448a088b55d7d83
|
[
"MIT"
] | null | null | null |
#include <map>
#include <iostream>
#include <vector>
#include <numeric>
#include <iterator>
#include <sstream>
#include "BuiltinSubroutines.hpp"
#include "AssemblyCodeGen.hpp"
#include "VMInstr.hpp"
using namespace std;
//https://www.informatik.htw-dresden.de/~beck/ASM/syscall_list.html
//eax values (syscall numbers):
const string SYS_EXIT = "1";
const string SYS_FORK = "2";
const string SYS_READ = "3";
const string SYS_WRITE = "4";
const string SYS_OPEN = "5";
const string SYS_CLOSE = "6";
const string SYS_WAITPID= "7";
const string SYS_CREAT = "8";
//..
const string SYS_TIME = "13";
//..
const string SYS_MMAP = "192";
map<string,vector<string>> compile_builtin_subroutines(){
if(DEBUG){
cout << "BuiltinSubroutines::compile_builtin_subroutines" << endl;
}
map<string,vector<string>> asmcodes = {
{"Builtin_readchar",_readchar()},
{"Builtin_putchar",_putchar()},
{"Builtin_putdigit",_putdigit()},
{"Builtin_new",_new()},
{"Builtin_free",_free()},
{"Builtin_len",_len()},
{"Builtin_abs",_abs()},
{"Builtin_time",_time()},
{"Builtin_fopen",_fopen()},
{"Builtin_fputs",_fputs()}
};
return asmcodes;
}
vector<string> _readchar(){
const vector<string> res={
//TODO: handle errors that could occur
join(subroutine(VMInstr("subroutine Builtin_readchar 0 args 0 locals")),"\n"),
//push a placeholder for the value to read on the stack
"mov eax,0",
"push eax",
//SYSCALL START
"mov eax,"+SYS_READ, //sys_read
"mov ebx,0", //stdin
//print the char on stack
//read into the placeholder DWORD we pushed onto the stack
"mov ecx,esp",
//val length
"mov edx,1",
"int 0x80",
//SYSCALL END
//push return value: we do not need to push a return value,
//as we already pushed a placeholder where our char (which has been read by now)
// should have been placed
//we must swap return value with the return address in order to return
//(i am so dumb. took me so long to find this.)
join(swap(VMInstr("swap")),"\n"),
//return from subroutine
"ret"
};
return res;
}
vector<string> _putchar(){
const vector<string> sub1 = subroutine(VMInstr(
"subroutine Builtin_putchar 0 args 0 locals"
));
const vector<string> push1 = push(VMInstr("push ARG 0"));
//in the vector literal
const vector<string> res = {
//prints the Int on top of stack as char to stdout
join(sub1,"\n"),
//access our argument , ARG 0, by pushing it onto the stack
//push1
join(push1,"\n"),
"mov eax,"+SYS_WRITE, // sys_write syscall
"mov ebx,1", //stdout
"mov ecx,esp", //print the Int on the stack
//val length
"mov edx,1", //: value length
"int 0x80", //call kernel
//pop ARG 0 which we pushed
"pop ecx",
//push return value
"mov edx,0", //: push return value
"push edx", //: push return value
//we must swap return value with the return address in order to return
//(i am so dumb. took me so long to find this.)
//swap
"pop eax",
"pop ebx",
"push eax",
"push ebx",
"ret"
};
return res;
}
vector<string> _putdigit(){
const vector<string> sub1 = subroutine(VMInstr(
"subroutine Builtin_putdigit 0 args 0 locals"
));
const vector<string> push1 = push(VMInstr("push ARG 0"));
//in the vector literal
const vector<string> res = {
//prints the Int on top of stack as char to stdout
join(sub1,"\n"),
//access our argument , ARG 0, by pushing it onto the stack
//push1
join(push1,"\n"),
"mov eax,"+SYS_WRITE, //putdigit: sys_write syscall
"mov ebx,1", //putdigit: stdout
//duplicate the value on stack, add offset to make it a char
"pop ecx",
"push ecx",
"add ecx,48", //putdigit: add offset to make it char
"push ecx",
"mov ecx,esp", //print the Int on the stack
//val length
"mov edx,1", //putdigit: value length
"int 0x80", //call kernel
//pop that value which we pushed
"pop ecx",
//pop ARG 0 which we pushed
"pop ecx",
//push return value
"mov edx,0", //putdigit: push return value
"push edx", //putdigit: push return value
//we must swap return value with the return address in order to return
//(i am so dumb. took me so long to find this.)
//swap
"pop eax",
"pop ebx",
"push eax",
"push ebx",
"ret"
};
return res;
}
vector<string> _new(){
const string byte_offset_32bit="4";
const vector<string> res={
//http://lxr.linux.no/#linux+v3.6/arch/x86/ia32/ia32entry.S#L372
//http://man7.org/linux/man-pages/man2/mmap.2.html
//TODO: handle the error if memory could not be allocated
//malloc receives as an argument the amount of DWORDs to allocate
join(subroutine(VMInstr("subroutine Builtin_new 1 args 0 locals")),"\n"),
//access our argument, push it onto the stack
join(push(VMInstr("push ARG 0")),"\n"),
//this is to multiply by 4, so we allocate 32bit units.
//pop our argument into ecx
//size of segment to be allocated
"pop ecx",
//push our size for the length-prefix later on
//LINKED CODE 2 (they only work together)
"push ecx",
//increment by 1, as our array should be length-prefixed, and we need a place to store the length
"inc ecx",
"mov ecx,"+byte_offset_32bit,
"imul eax,ecx",
"mov ecx,eax",
"mov eax,"+SYS_MMAP,
"xor ebx,ebx", //addr=NULL
"mov edx,0x7", //prot = PROT_READ | PROT_WRITE | PROT_EXEC
"mov esi,0x22", //flags=MAP_PRIVATE | MAP_ANONYMOUS
"mov edi,-1", //fd=-1
//LINKED CODE 1 (they only work together)
"push ebp", //save ebp as we should not mess with it
"mov ebp,0", //offset=0 (4096*0)
"int 0x80",
//LINKED CODE 1 (they only work together)
"pop ebp", //restore ebp as we should not mess with it
//eax should now contain
//the address of the allocated memory segment
//put the length-prefix at the start
//pop our length-prefix
"pop ebx",
//LINKED CODE 2 (they only work together)
//mov [eax],ebx //store the length at index 0
"mov [eax],ebx",
//now we push that pointer on the stack
"push eax",
//we must swap return value with the return address in order to return
//(i am so dumb. took me so long to find this.)
join(swap(VMInstr("swap")),"\n"),
//return from subroutine
"ret"
};
return res;
}
vector<string> _free(){
//TODO
return {};
}
vector<string> _len(){
const vector<string> res={
//returns the length of a length-prefixed memory segment
join(subroutine(VMInstr("subroutine Builtin_len 1 args 0 locals")),"\n"),
//access our argument , ARG 0, by pushing it onto the stack
join(push(VMInstr("push ARG 0")),"\n"),
//pointer is now on stack
"pop eax",
//mov eax,[eax] //get the length stored at that location
"mov eax,[eax]",
//push return value
"push eax",
//we must swap return value with the return address in order to return
//(i am so dumb. took me so long to find this.)
join(swap(VMInstr("swap")),"\n"),
//return from subroutine
"ret"
};
return res;
}
vector<string> _abs(){
//returns the absolute value of an integer
const vector<string> res={
//returns the length of a length-prefixed memory segment
join(subroutine(VMInstr("subroutine Builtin_abs 1 args 0 locals")),"\n"),
//access our argument , ARG 0, by pushing it onto the stack
join(push(VMInstr("push ARG 0")),"\n"),
//valueis now on stack
"pop eax",
"cmp eax,0",
"jl invert",
"jmp end",
"invert:",
"mov ebx,-1",
"imul eax,ebx",
"end:",
//push return value
"push eax",
//we must swap return value with the return address in order to return
//(i am so dumb. took me so long to find this.)
join(swap(VMInstr("swap")),"\n"),
//return from subroutine
"ret"
};
return res;
}
vector<string> _time(){
const vector<string> res={
//time in seconds since the epoch
//https://fresh.flatassembler.net/lscr/
//takes 0 arguments
//returns a PInt
join(subroutine(VMInstr("subroutine Builtin_time 0 args 0 locals")),"\n"),
"mov eax,"+SYS_TIME,
"mov ebx,0", //return time only in eax
"xor ecx,ecx",
"xor edx,edx",
"int 0x80",
//push return value
"push eax",
//we must swap return value with the return address in order to return
//(i am so dumb. took me so long to find this.)
join(swap(VMInstr("swap")),"\n"),
//return from subroutine
"ret"
};
return res;
}
vector<string> _fopen(){
//TODO
/*
// ([Char] filename ,PInt accessmode)~>PInt fopen
//takes 2 arguments: the file name ([Char]), and the access mode (PInt)
//returns a file descriptor (PInt) which can then be used with fputs to write to a file
SubroutineFocusedAssemblyCodeGenerator.compile_subroutine("Builtin_fopen",a);
//access our argument , ARG 1, by pushing it onto the stack
compile_push(VMCompilerPhases.SEGMENT_ARG,1,a);
//access our argument , ARG 0, by pushing it onto the stack
compile_push(VMCompilerPhases.SEGMENT_ARG,0,a);
//stack:
//accessmode
//filename <- esp
a.mov(eax,SYS_OPEN,"fopen: sys_open");
a.pop(ebx,"fopen: get the filename [Char] pointer");
//tood : we should get the syntactic sugar with the strings in dragon
//to insert a nullbyte at the end. or use a specially prepared string with this syscall
//because it is a c-style syscall, it expects a '\0' at the end of the filename probably
//https://stackoverflow.com/questions/8312290/how-to-open-a-file-in-assembler-and-modify-it
a.add(ebx, byte_offset_32bit,"offset to the start, as arrays are length-prefixed in dragon");
//ebx now contains the filename argument
a.pop(ecx,"fopen: access mode");
a.call_kernel();
//push return value
a.push(eax,"fopen: push return value (file descriptor in eax)");
//we must swap return value with the return address in order to return
//(i am so dumb. took me so long to find this.)
compile_swap("swap return address with return value to return",a);
//return from subroutine
SubroutineFocusedAssemblyCodeGenerator.compile_return(a);
*/
return {};
}
vector<string> _fputs(){
//https://www.tutorialspoint.com/c_standard_library/c_function_fputs.htm
//([Char] str, Pint filedescriptor)~>PInt
//arg 0: string to write
//arg 1: filedescriptor of the file to write to
//returns: 0
const string byte_offset_32_bit = "4";
//prints a string to a file
vector<string> sub1=subroutine(VMInstr("subroutine Builtin_fputs 2 args 0 locals"));
//pop pointer to string buffer to write (Arg 0)
const vector<string> push1 = push(VMInstr("push ARG 0"));
//pop file descriptor (Arg 1)
const vector<string> push2 = push(VMInstr("push ARG 1"));
const vector<string> res = {
join(sub1,"\n"),
join(push1,"\n"),
join(push2,"\n"),
"mov eax,"+SYS_WRITE,
"pop ebx",//pop our filedescriptor argument
//print the char on stack
"pop ecx", //pop our string to write argument
"mov edx,ecx", //how many bytes to write
"mov edx,[edx]", //how many bytes to write
"add ecx,"+byte_offset_32_bit,
"int 0x80",
"push 0",
//we must swap return value with the return address in order to return
//(i am so dumb. took me so long to find this.)
//swap
"pop eax",
"pop ebx",
"push eax",
"push ebx",
//return from subroutine
"ret"
};
return res;
}
string join(vector<string> vec, string delim)
{
stringstream res;
for(int i=0;i<vec.size();i++){
res << vec.at(i);
res << delim;
}
return res.str();
}
| 24.90625
| 102
| 0.630197
|
pointbazaar
|
46cfdade48ef91f8149033f6657c4de6a9a31d48
| 1,244
|
cpp
|
C++
|
tests/unittests/HttpsExceptionUnitTest.cpp
|
commshare/easyhttpcpp
|
757ec75679c1cbc5f04c81a30133f4bcd3e780f4
|
[
"MIT"
] | 147
|
2017-10-05T01:42:02.000Z
|
2022-01-21T08:15:05.000Z
|
tests/unittests/HttpsExceptionUnitTest.cpp
|
commshare/easyhttpcpp
|
757ec75679c1cbc5f04c81a30133f4bcd3e780f4
|
[
"MIT"
] | 20
|
2018-05-17T01:55:16.000Z
|
2021-04-20T07:27:00.000Z
|
tests/unittests/HttpsExceptionUnitTest.cpp
|
commshare/easyhttpcpp
|
757ec75679c1cbc5f04c81a30133f4bcd3e780f4
|
[
"MIT"
] | 32
|
2018-05-05T13:04:34.000Z
|
2022-03-25T16:57:11.000Z
|
/*
* Copyright 2017 Sony Corporation
*/
#include "gtest/gtest.h"
#include "easyhttpcpp/HttpException.h"
#include "ExceptionTestUtil.h"
namespace easyhttpcpp {
namespace test {
using easyhttpcpp::common::CoreException;
static const unsigned int HttpIllegalArgumentExceptedtedCode = 100700;
static const unsigned int HttpIllegalStateExceptionExpectedCode = 100701;
static const unsigned int HttpExecutionExceptionExpectedCode = 100702;
static const unsigned int HttpTimeoutExceptionExpectedCode = 100703;
static const unsigned int HttpSslExceptionExpectedCode = 100704;
EASYHTTPCPP_EXCEPTION_UNIT_TEST(CoreException, HttpException, HttpIllegalArgumentException, HttpIllegalArgumentExceptedtedCode)
EASYHTTPCPP_EXCEPTION_UNIT_TEST(CoreException, HttpException, HttpIllegalStateException,
HttpIllegalStateExceptionExpectedCode)
EASYHTTPCPP_EXCEPTION_UNIT_TEST(CoreException, HttpException, HttpExecutionException, HttpExecutionExceptionExpectedCode)
EASYHTTPCPP_EXCEPTION_UNIT_TEST(CoreException, HttpException, HttpTimeoutException, HttpTimeoutExceptionExpectedCode)
EASYHTTPCPP_EXCEPTION_UNIT_TEST(CoreException, HttpException, HttpSslException, HttpSslExceptionExpectedCode)
} /* namespace test */
} /* namespace easyhttpcpp */
| 41.466667
| 127
| 0.860129
|
commshare
|
46daa6f4bf5fd5e1023e5c1d69bdba58845a9ddb
| 5,750
|
cpp
|
C++
|
src/config_parser.cpp
|
corvette-berkeley/precimonious
|
5ac56e145379bc059d686af10c62c3750224edd3
|
[
"BSD-3-Clause"
] | 22
|
2015-08-13T12:57:50.000Z
|
2021-12-29T13:02:07.000Z
|
src/config_parser.cpp
|
huiguoo/precimonious
|
5bc4c7fb522859cddb58743c9a14fab69b3ed8f6
|
[
"BSD-3-Clause"
] | 2
|
2018-05-19T15:09:24.000Z
|
2021-11-23T00:54:21.000Z
|
src/config_parser.cpp
|
huiguoo/precimonious
|
5bc4c7fb522859cddb58743c9a14fab69b3ed8f6
|
[
"BSD-3-Clause"
] | 13
|
2015-10-16T11:06:37.000Z
|
2022-03-28T07:54:26.000Z
|
#include "config_parser.hpp"
#include "vjson/json.h"
#include "vjson/block_allocator.h"
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/raw_ostream.h>
#include <map>
#include <utility>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
using namespace llvm;
void parse_array(char* type, json_value *arr, const char* del) {
int cnt;
cnt = 0;
for (json_value *el = arr->first_child; el; el = el->next_sibling) {
if (cnt > 0) strcat(type, del);
if (el->type == JSON_ARRAY) {
parse_array(type, el, " ");
} else {
strcat(type, el->string_value);
}
cnt++;
}
}
// parse call
void parse_call(json_value *call, map<string, StrChange*> &changes) {
char type[1000] = {'\0'};
char name[100] = {'\0'};
char function[100] = {'\0'};
char id[100] = {'\0'};
char file[100] = {'\0'};
char line[100] = {'\0'};
char swit[100] = {'\0'};
for (json_value *child = call->first_child; child; child = child->next_sibling) {
if (strcmp(child->name, "id") == 0) {
strcpy(id, child->string_value);
} else if (strcmp(child->name, "file") == 0) {
strcpy(file, child->string_value);
} else if (strcmp(child->name, "function") == 0) {
strcpy(function, child->string_value);
} else if (strcmp(child->name, "line") == 0) {
strcpy(line, child->string_value);
} else if (strcmp(child->name, "name") == 0) {
strcpy(name, child->string_value);
} else if (strcmp(child->name, "switch") == 0) {
strcpy(swit, child->string_value);
} else if (strcmp(child->name, "type") == 0) {
if (child->first_child->type == JSON_ARRAY) {
parse_array(type, child, ", ");
} else {
parse_array(type, child, " ");
}
}
}
string idStr(id);
FuncStrChange *change = new FuncStrChange("call", string(type), -1, string(swit));
changes[idStr] = change;
}
// parse op
void parse_op(json_value *op, map<string, StrChange*> &changes) {
char type[100] = {'\0'};
char name[100] = {'\0'};
char function[100] = {'\0'};
char id[100] = {'\0'};
char file[100] = {'\0'};
char line[100] = {'\0'};
for (json_value *child = op->first_child; child; child = child->next_sibling) {
if (strcmp(child->name, "id") == 0) {
strcpy(id, child->string_value);
} else if (strcmp(child->name, "file") == 0) {
strcpy(file, child->string_value);
} else if (strcmp(child->name, "function") == 0) {
strcpy(function, child->string_value);
} else if (strcmp(child->name, "line") == 0) {
strcpy(line, child->string_value);
} else if (strcmp(child->name, "name") == 0) {
strcpy(name, child->string_value);
} else if (strcmp(child->name, "type") == 0) {
if (child->type == JSON_ARRAY) {
parse_array(type, child, ", ");
} else {
strcpy(type, child->string_value);
}
}
}
string idStr(id);
StrChange *change = new StrChange("op", string(type), -1);
changes[idStr] = change;
}
// parse localVar
void parse_local_var(json_value *localVar, map<string, StrChange*> &changes) {
char type[100] = {'\0'};
char id[100] = {'\0'};
char name[100] = {'\0'};
char function[100] = {'\0'};
char field[2] = {'\0'};
int iField = -1;
for (json_value *child = localVar->first_child; child; child = child->next_sibling) {
if (strcmp(child->name, "name") == 0) {
strcpy(name, child->string_value);
} else if (strcmp(child->name, "function") == 0) {
strcpy(function, child->string_value);
} else if (strcmp(child->name, "field") == 0) {
strcpy(field, child->string_value);
iField = atoi(field);
} else if (strcmp(child->name, "type") == 0) {
if (child->type == JSON_ARRAY) {
parse_array(type, child, ", ");
} else {
strcpy(type, child->string_value);
}
}
}
strcpy(id, name);
strcat(id, "@");
strcat(id, function);
string idStr(id);
StrChange *change = new StrChange("localVar", string(type), iField);
changes[idStr] = change;
}
// parse globalVar
void parse_global_var(json_value *globalVar, map<string, StrChange*> &changes) {
char type[100] = {'\0'};
char name[100] = {'\0'};
for (json_value *child = globalVar->first_child; child; child = child->next_sibling) {
if (strcmp(child->name, "name") == 0) {
strcpy(name, child->string_value);
} else if (strcmp(child->name, "type") == 0) {
if (child->type == JSON_ARRAY) {
parse_array(type, child, ", ");
} else {
strcpy(type, child->string_value);
}
}
}
string idStr(name);
StrChange *change = new StrChange("globalVar", string(type), -1);
changes[idStr] = change;
}
// parse json
void parse_json(json_value *root, map<string, StrChange*> &changes) {
for (json_value *child = root->first_child; child; child = child->next_sibling) {
if (strcmp(child->name, "globalVar") == 0) {
parse_global_var(child, changes);
} else if (strcmp(child->name, "localVar") == 0) {
parse_local_var(child, changes);
} else if (strcmp(child->name, "op") == 0) {
parse_op(child, changes);
} else if (strcmp(child->name, "call") == 0) {
parse_call(child, changes);
}
}
}
// parse json
map<string, StrChange*> parse_config(const char* filename) {
// initialize objects used by vjson
map<string, StrChange*> changes;
block_allocator mAllocator(1 << 10);
json_value *root;
// open config file
FILE *fp = fopen(filename, "rb");
// get config file source
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *source = (char *)mAllocator.malloc(size + 1);
size_t r = fread(source, 1, size, fp);
printf("%ld\n", r);
source[size] = 0;
fclose(fp);
// parse the source
char *errorPos = 0;
int errorLine = 0;
root = json_parse(source, &errorPos, &errorLine, &mAllocator);
if (!root)
{
errs() << "Error parsing config file";
} else {
parse_json(root, changes);
}
return changes;
}
| 27.644231
| 87
| 0.623478
|
corvette-berkeley
|
46dcce3972d5abc524f646628c2e30b8ae1f1452
| 4,302
|
cpp
|
C++
|
TicTacToe/src/UI/BoardDisplay.cpp
|
mitos-drg/VoiceTicTacToe
|
8d0a26d00f6185c5743a00373c6a50d7322b8db1
|
[
"BSD-2-Clause"
] | null | null | null |
TicTacToe/src/UI/BoardDisplay.cpp
|
mitos-drg/VoiceTicTacToe
|
8d0a26d00f6185c5743a00373c6a50d7322b8db1
|
[
"BSD-2-Clause"
] | null | null | null |
TicTacToe/src/UI/BoardDisplay.cpp
|
mitos-drg/VoiceTicTacToe
|
8d0a26d00f6185c5743a00373c6a50d7322b8db1
|
[
"BSD-2-Clause"
] | null | null | null |
#include "BoardDisplay.h"
#include <SFML/Graphics/RenderWindow.hpp>
#include "Application/GameStack.h"
#include "Application/GlobalResources.h"
BoardDisplay::BoardDisplay(int posx, int posy, int sizex, int sizey, TTTBoard* board)
: m_positions(), m_rect(posx, posy, sizex, sizey), m_board(board)
{
m_boardColor = { 30, 120, 90, 255 };
m_circleColor = { 15,45, 200,255 };
m_crossColor = { 200,45,15,255 };
m_boardArea.setPosition(posx, posy);
m_boardArea.setSize({ (float)sizex, (float)sizey });
m_boardArea.setTexture(GlobalResources::BoardTexture);
m_boardArea.setFillColor(m_boardColor);
m_circleSprite.setSize({ sizex * 0.3f, sizey * 0.3f });
m_circleSprite.setTexture(GlobalResources::CircleTexture);
m_circleSprite.setFillColor(m_circleColor);
m_crossSprite.setSize({ sizex * 0.3f, sizey * 0.3f });
m_crossSprite.setTexture(GlobalResources::CrossTexture);
m_crossSprite.setFillColor(m_crossColor);
m_positions[0] = { posx + sizex * 0.01f, posy + sizey * 0.01f };
m_positions[1] = { posx + sizex * 0.3375f, posy + sizey * 0.01f };
m_positions[2] = { posx + sizex * 0.675f, posy + sizey * 0.01f };
m_positions[3] = { posx + sizex * 0.01f, posy + sizey * 0.3375f };
m_positions[4] = { posx + sizex * 0.3375f, posy + sizey * 0.3375f };
m_positions[5] = { posx + sizex * 0.675f, posy + sizey * 0.3375f };
m_positions[6] = { posx + sizex * 0.01f, posy + sizey * 0.675f };
m_positions[7] = { posx + sizex * 0.3375f, posy + sizey * 0.675f };
m_positions[8] = { posx + sizex * 0.675f, posy + sizey * 0.675f };
m_line.setSize({ (float)m_rect.width * 1.1f, 10.0f });
}
BoardDisplay::~BoardDisplay()
{
}
void BoardDisplay::Draw()
{
sf::RenderWindow* window = GameStack::GetWindow();
window->draw(m_boardArea);
for (int i = 0; i < 9; ++i)
{
if (m_board->fields[i] == TTTPlayer::Circle)
{
m_circleSprite.setPosition(m_positions[i]);
window->draw(m_circleSprite);
}
else if (m_board->fields[i] == TTTPlayer::Cross)
{
m_crossSprite.setPosition(m_positions[i]);
window->draw(m_crossSprite);
}
}
/*if (!m_hasWinBoard)
{
if ((m_board->circles & winMask[0]) || (m_board->crosses & winMask[0])) // 0 1 2
{
m_line.setPosition(m_rect.left + (float)m_rect.width * 0.1f, m_rect.top + m_rect.height * 0.175f);
m_line.setRotation(0);
m_hasWinBoard = true;
}
else if ((m_board->circles & winMask[1]) || (m_board->crosses & winMask[1])) // 0 3 6
{
m_line.setPosition(m_rect.left + (float)m_rect.width * 0.175f, m_rect.top + m_rect.height * 0.1f);
m_line.setRotation(90);
m_hasWinBoard = true;
}
else if ((m_board->circles & winMask[2]) || (m_board->crosses & winMask[2])) // 0 4 8
{
m_line.setPosition(m_rect.left + (float)m_rect.width * 0.1f, m_rect.top + m_rect.height * 0.1f);
m_line.setSize({ (float)m_rect.width * 1.1f * 1.41f, 10.0f });
m_line.setRotation(45);
m_hasWinBoard = true;
}
else if ((m_board->circles & winMask[3]) || (m_board->crosses & winMask[3])) // 1 4 7
{
m_line.setPosition(m_rect.left + (float)m_rect.width * 0.525f, m_rect.top + m_rect.height * 0.1f);
m_line.setRotation(90);
m_hasWinBoard = true;
}
else if ((m_board->circles & winMask[4]) || (m_board->crosses & winMask[4])) // 3 4 5
{
m_line.setPosition(m_rect.left + (float)m_rect.width * 0.1f, m_rect.top + m_rect.height * 0.525f);
m_line.setRotation(0);
m_hasWinBoard = true;
}
else if ((m_board->circles & winMask[5]) || (m_board->crosses & winMask[5])) // 2 4 6
{
m_line.setPosition(m_rect.left + (float)m_rect.width * 0.9f, m_rect.top + m_rect.height * 0.9f);
m_line.setRotation(-45);
m_line.setSize({ (float)m_rect.width * 1.1f * 1.41f, 10.f });
m_hasWinBoard = true;
}
else if ((m_board->circles & winMask[6]) || (m_board->crosses & winMask[6])) // 2 5 8
{
m_line.setPosition(m_rect.left + (float)m_rect.width * 0.825f, m_rect.top + m_rect.height * 0.1f);
m_line.setRotation(90);
m_hasWinBoard = true;
}
else if ((m_board->circles & winMask[7]) || (m_board->crosses & winMask[7])) // 6 7 8
{
m_line.setPosition(m_rect.left + (float)m_rect.width * 0.1f, m_rect.top + m_rect.height * 0.825f);
m_line.setRotation(0);
m_hasWinBoard = true;
}
}
if (m_hasWinBoard)
{
window->draw(m_line);
}*/
}
void BoardDisplay::Update(float deltaTime)
{
}
| 33.348837
| 101
| 0.658298
|
mitos-drg
|
46de28fe832564296f08b7b82df4191ebf12496f
| 282
|
cpp
|
C++
|
epikjjh/baekjoon/2133.cpp
|
15ers/Solve_Naively
|
23ee4a3aedbedb65b9040594b8c9c6d9cff77090
|
[
"MIT"
] | 3
|
2019-05-19T13:44:39.000Z
|
2019-07-03T11:15:20.000Z
|
epikjjh/baekjoon/2133.cpp
|
15ers/Solve_Naively
|
23ee4a3aedbedb65b9040594b8c9c6d9cff77090
|
[
"MIT"
] | 7
|
2019-05-06T02:37:26.000Z
|
2019-06-29T07:28:02.000Z
|
epikjjh/baekjoon/2133.cpp
|
15ers/Solve_Naively
|
23ee4a3aedbedb65b9040594b8c9c6d9cff77090
|
[
"MIT"
] | 1
|
2019-07-28T06:24:54.000Z
|
2019-07-28T06:24:54.000Z
|
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0),cin.tie(0);
int n;
cin >> n;
vector<int> dp(n+1);
dp[0] = 1;
for(int i=2;i<=n;i+=2){
dp[i] = dp[i-2]*3;
for(int j=4;j<=i;j+=2) dp[i] += dp[i-j]*2;
}
cout << dp[n] << endl;
return 0;
}
| 15.666667
| 44
| 0.528369
|
15ers
|
46e10895fdf12679cd4fdda7311083690c5fb36a
| 117
|
cxx
|
C++
|
TestPrograms/test_x86_avx2.cxx
|
bobsayshilol/cryptopp
|
fc1e98e70d425bc8fd3780c237a43f2facfc1460
|
[
"BSL-1.0"
] | null | null | null |
TestPrograms/test_x86_avx2.cxx
|
bobsayshilol/cryptopp
|
fc1e98e70d425bc8fd3780c237a43f2facfc1460
|
[
"BSL-1.0"
] | null | null | null |
TestPrograms/test_x86_avx2.cxx
|
bobsayshilol/cryptopp
|
fc1e98e70d425bc8fd3780c237a43f2facfc1460
|
[
"BSL-1.0"
] | null | null | null |
#include <immintrin.h>
int main(int argc, char* argv[])
{
__m256i x;
x=_mm256_add_epi64 (x,x);
return 0;
}
| 14.625
| 33
| 0.623932
|
bobsayshilol
|
46ea1e10e03fac29295ff9a71db16c8bf0e91e51
| 3,001
|
cpp
|
C++
|
tests/test_barriers.cpp
|
648trindade/adaptive
|
3cf234ae66167df6ce2b068c4b92765fe47ba148
|
[
"MIT"
] | 1
|
2020-05-06T20:22:58.000Z
|
2020-05-06T20:22:58.000Z
|
tests/test_barriers.cpp
|
648trindade/adaptive
|
3cf234ae66167df6ce2b068c4b92765fe47ba148
|
[
"MIT"
] | 5
|
2020-04-20T02:06:09.000Z
|
2020-05-12T00:26:38.000Z
|
tests/test_barriers.cpp
|
648trindade/adaptive
|
3cf234ae66167df6ce2b068c4b92765fe47ba148
|
[
"MIT"
] | null | null | null |
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#define CATCH_CONFIG_CONSOLE_WIDTH 120
#include "../adaptive/adaptive.hpp"
#include "Catch2/catch.hpp"
#include <chrono>
#include <thread>
using namespace adapt;
void barrier_loop(AtomicBarrier &barrier, size_t iters) {
for (size_t i = 0; i < iters; i++) { barrier.wait(); }
}
void barrier_wait(AtomicBarrier &barrier) { barrier.wait(); };
TEST_CASE("is correctly setting participants") {
AtomicBarrier barrier;
std::thread wait_barrier_0, wait_barrier_1;
// 1 thread
barrier.set_participants(1);
wait_barrier_0 = std::thread(barrier_wait, std::ref(barrier));
wait_barrier_0.join();
REQUIRE(barrier.is_free());
// 2 threads
barrier.set_participants(2);
wait_barrier_0 = std::thread(barrier_wait, std::ref(barrier));
std::this_thread::sleep_for(std::chrono::seconds(1));
REQUIRE(!barrier.is_free());
wait_barrier_1 = std::thread(barrier_wait, std::ref(barrier));
wait_barrier_0.join();
wait_barrier_1.join();
REQUIRE(barrier.is_free());
}
TEST_CASE("do it runs with 1 thread per cpu") {
AtomicBarrier barrier;
const size_t num_threads = adapt::get_num_threads();
const size_t iters = 4000 / num_threads;
std::thread threads[num_threads];
barrier.set_participants(num_threads);
for (size_t i = 0; i < num_threads; i++) { threads[i] = std::thread(barrier_loop, std::ref(barrier), iters); }
for (size_t i = 0; i < num_threads; i++) { threads[i].join(); }
REQUIRE(barrier.is_free());
}
TEST_CASE("does it works inside parallel for") {
AtomicBarrier barrier;
const size_t num_threads = adapt::get_num_threads();
barrier.set_participants(num_threads);
adapt::parallel_for(0ul, num_threads, [&barrier](const size_t b, const size_t e) {
for (int i = 0; i < 100; i++) { barrier.wait(); }
});
REQUIRE(barrier.is_free());
}
TEST_CASE("do it runs with a lot (256) of threads") {
AtomicBarrier barrier;
const size_t num_threads = 256;
const size_t iters = 4000 / num_threads;
std::thread threads[num_threads];
barrier.set_participants(num_threads);
for (size_t i = 0; i < num_threads; i++) { threads[i] = std::thread(barrier_loop, std::ref(barrier), iters); }
for (size_t i = 0; i < num_threads; i++) { threads[i].join(); }
REQUIRE(barrier.is_free());
}
TEST_CASE("is internal resetting counter correctly") {
AtomicBarrier barrier;
const size_t num_threads = 2;
const size_t iters = 1;
std::thread threads[num_threads];
barrier.set_participants(num_threads);
for (size_t i = 0; i < num_threads; i++) { threads[i] = std::thread(barrier_loop, std::ref(barrier), iters); }
for (size_t i = 0; i < num_threads; i++) { threads[i].join(); }
REQUIRE(barrier.is_free());
barrier.reset();
for (size_t i = 0; i < num_threads; i++) { threads[i] = std::thread(barrier_loop, std::ref(barrier), iters); }
for (size_t i = 0; i < num_threads; i++) { threads[i].join(); }
REQUIRE(barrier.is_free());
}
| 36.156627
| 112
| 0.691103
|
648trindade
|
46ee746c5cb8e0a91ea5284fcd798ea21e085964
| 2,734
|
cpp
|
C++
|
bin/libs/systemc-2.3.1/examples/sysc/risc_cpu/paging.cpp
|
buaawj/Research
|
23bf0d0df67f80b7a860f9d2dc3f30b60554c26d
|
[
"OML"
] | 9
|
2019-07-15T10:05:29.000Z
|
2022-03-14T12:55:19.000Z
|
bin/libs/systemc-2.3.1/examples/sysc/risc_cpu/paging.cpp
|
buaawj/Research
|
23bf0d0df67f80b7a860f9d2dc3f30b60554c26d
|
[
"OML"
] | 2
|
2019-11-30T23:27:47.000Z
|
2021-11-02T12:01:05.000Z
|
systemc-2.3.1/examples/sysc/risc_cpu/paging.cpp
|
tianzhuqiao/bsmedit
|
3e443ed6db7b44b3b0da0e4bc024b65dcfe8e7a4
|
[
"MIT"
] | null | null | null |
/*****************************************************************************
The following code is derived, directly or indirectly, from the SystemC
source code Copyright (c) 1996-2014 by all Contributors.
All Rights reserved.
The contents of this file are subject to the restrictions and limitations
set forth in the SystemC Open Source License (the "License");
You may not use this file except in compliance with such restrictions and
limitations. You may obtain instructions on how to receive a copy of the
License at http://www.accellera.org/. Software distributed by Contributors
under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
ANY KIND, either express or implied. See the License for the specific
language governing rights and limitations under the License.
*****************************************************************************/
/*****************************************************************************
paging.cpp -- Instruction Paging Unit.
Original Author: Martin Wang, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#include "paging.h"
#include "directive.h"
void paging::entry()
{
int address=0;
int dataout_tmp =0;
while (true) {
do { wait(); } while ( !(paging_csin == true) );
address = logical_address.read();
if (address >= 5) {
if (paging_wein.read() == true) { // Write operation
paging_dout.write(paging_din.read());
paging_csout.write(true);
paging_weout.write(true);
physical_address.write(logical_address.read());
wait();
paging_csout.write(false);
paging_weout.write(false);
}
else { // Read operation
paging_csout.write(true);
paging_weout.write(false);
physical_address.write(logical_address.read());
wait();
do { wait(); } while ( !(icache_validin == true) );
dataout_tmp = icache_din.read();
if (PRINT_PU){
cout << "-----------------------" << endl;
printf( "PAGE : mem=%x\n",dataout_tmp);
cout << "PAGE : " ;
cout << " at CSIM " << sc_time_stamp() << endl;
cout << "-----------------------" << endl;
}
dataout.write(icache_din.read());
data_valid.write(true);
paging_csout.write(false);
wait();
data_valid.write(false);
wait();
}
}
}
} // end of entry function
| 31.068182
| 79
| 0.539503
|
buaawj
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.