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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a4a3f959d7315d280fa90acc6d0289d2cce27e5e
| 1,028
|
cpp
|
C++
|
src/Math/PathFinding/IndexedPriorityQueue.cpp
|
scemino/EnggeFramework
|
6526bff3c4e6e9ed2cad102f1e3a37d3ce19ef37
|
[
"MIT"
] | 2
|
2021-11-02T06:47:50.000Z
|
2021-12-16T09:55:06.000Z
|
src/Math/PathFinding/IndexedPriorityQueue.cpp
|
scemino/EnggeFramework
|
6526bff3c4e6e9ed2cad102f1e3a37d3ce19ef37
|
[
"MIT"
] | 2
|
2021-02-07T00:04:30.000Z
|
2021-02-09T23:23:21.000Z
|
src/Math/PathFinding/IndexedPriorityQueue.cpp
|
scemino/EnggeFramework
|
6526bff3c4e6e9ed2cad102f1e3a37d3ce19ef37
|
[
"MIT"
] | null | null | null |
#include <utility>
#include "IndexedPriorityQueue.h"
namespace ngf {
IndexedPriorityQueue::IndexedPriorityQueue(std::vector<float> &keys)
: _keys(keys) {
}
void IndexedPriorityQueue::insert(int index) {
_data.push_back(index);
reorderUp();
}
int IndexedPriorityQueue::pop() {
int r = _data[0];
_data[0] = _data[_data.size() - 1];
_data.pop_back();
reorderDown();
return r;
}
void IndexedPriorityQueue::reorderUp() {
if (_data.empty())
return;
size_t a = _data.size() - 1;
while (a > 0) {
if (_keys[_data[a]] >= _keys[_data[a - 1]])
return;
int tmp = _data[a];
_data[a] = _data[a - 1];
_data[a - 1] = tmp;
a--;
}
}
void IndexedPriorityQueue::reorderDown() {
if (_data.empty())
return;
for (int a = 0; a < static_cast<int>(_data.size() - 1); a++) {
if (_keys[_data[a]] <= _keys[_data[a + 1]])
return;
int tmp = _data[a];
_data[a] = _data[a + 1];
_data[a + 1] = tmp;
}
}
bool IndexedPriorityQueue::isEmpty() {
return _data.empty();
}
}
| 20.156863
| 68
| 0.600195
|
scemino
|
a4b2aba75b02c06c37d5e6fe0930b469e1916cd7
| 1,540
|
cpp
|
C++
|
2019.7.2/D_Persona5.cpp
|
wang2470616413/MyCode
|
23f4d6c12d0475e67e892ce39745bcada9c10197
|
[
"MIT"
] | 1
|
2019-04-20T09:52:50.000Z
|
2019-04-20T09:52:50.000Z
|
2019.7.2/D_Persona5.cpp
|
wang2470616413/MyCode
|
23f4d6c12d0475e67e892ce39745bcada9c10197
|
[
"MIT"
] | null | null | null |
2019.7.2/D_Persona5.cpp
|
wang2470616413/MyCode
|
23f4d6c12d0475e67e892ce39745bcada9c10197
|
[
"MIT"
] | null | null | null |
#include<stdio.h>
#include<string.h>
#define ll long long
#define mmset(a,b) memset(a,b,sizeof(a))
#define error printf("error\n")
using namespace std;
const int N = 1e6 + 10;
const ll MOD = 1e9 + 7;
ll F[N];
ll data[N];
ll res = 1;
ll aux = 0;
void init(ll p)
{
F[0] = 1;
for(int i = 1;i <= p;i++)
F[i] = F[i-1]*i % (MOD);
}
ll inv(ll a,ll m)
{
if(a == 1)return 1;
return inv(m%a,m)*(m-m/a)%m;
}
ll pow(ll a, ll n, ll p) //快速幂 a^n % p
{
ll ans = 1;
while(n)
{
if(n & 1) ans = ans * a % p;
a = a * a % p;
n >>= 1;
}
return ans;
}
ll niYuan(ll a, ll b) //费马小定理求逆元
{
return pow(a, b - 2, b);
}
ll C(ll a, ll b) //计算C(a, b)
{
return F[a] * niYuan(F[b], MOD) % MOD
* niYuan(F[a - b], MOD) % MOD;
}
ll Lucas(ll a, ll b)
{
if(a < MOD && b < MOD)
return C(a, b);
return
C(a % MOD, b % MOD) * Lucas(a / MOD, b / MOD);
}
ll modmul(ll ans,ll a)
{
ll t=0;
while (a)
{
if(a&1)
t=(t+ans)%MOD;
ans=(ans+ans)%MOD;
a=a>>1;
}
return t;
}
/*
3
1 1 1
3
1 2 3
*/
int main()
{
int n;
while(~scanf("%d",&n))
{
res = 1, aux = 0;
for(int i = 1; i <= n; i++)
{
scanf("%d",&data[i]);
aux += data[i];
}
init(aux + 5);
for(int i = 1; i <= n - 1; i++)
{
res = modmul(res,(Lucas(aux,data[i])));
aux -= data[i];
}
printf("%lld\n",res);
}
return 0;
}
| 16.210526
| 54
| 0.416234
|
wang2470616413
|
8a54e356bad832914b1ba3bc3cb2424e0312b24f
| 753
|
cpp
|
C++
|
Sources/Scene/Component/SyrinxRenderer.cpp
|
LeptusHe/SyrinxEngine
|
5ecdfdd53eb421bdfba61ed183a1ac688d117b97
|
[
"MIT"
] | 3
|
2020-04-24T07:58:52.000Z
|
2021-11-17T11:08:46.000Z
|
Sources/Scene/Component/SyrinxRenderer.cpp
|
LeptusHe/SyrinxEngine
|
5ecdfdd53eb421bdfba61ed183a1ac688d117b97
|
[
"MIT"
] | null | null | null |
Sources/Scene/Component/SyrinxRenderer.cpp
|
LeptusHe/SyrinxEngine
|
5ecdfdd53eb421bdfba61ed183a1ac688d117b97
|
[
"MIT"
] | 2
|
2019-10-02T01:49:46.000Z
|
2021-11-16T15:25:59.000Z
|
#include "Component/SyrinxRenderer.h"
#include <Common/SyrinxAssert.h>
namespace Syrinx {
Renderer::Renderer() : mMesh(nullptr), mMaterial(nullptr)
{
SYRINX_ENSURE(!mMesh);
SYRINX_ENSURE(!mMaterial);
}
void Renderer::setMesh(Mesh *mesh)
{
mMesh = mesh;
SYRINX_ENSURE(mMesh);
SYRINX_ENSURE(mMesh == mesh);
}
void Renderer::setMaterial(Material *material)
{
mMaterial = material;
SYRINX_ENSURE(mMaterial);
SYRINX_ENSURE(mMaterial == material);
}
const Mesh* Renderer::getMesh() const
{
return mMesh;
}
const Material* Renderer::getMaterial() const
{
return mMaterial;
}
bool Renderer::isValid() const
{
return mMesh && mMaterial;
}
} // namespace Syrinx
| 16.369565
| 58
| 0.652058
|
LeptusHe
|
8a5556acd077257946ce0108e924e6374f0a176b
| 9,252
|
cpp
|
C++
|
lib/MagnetRTD/MagnetRTD.cpp
|
greenspaceexplorer/MagnetHSK
|
41ab4758a21ecf7f980032ee0f2f569b120f8ebf
|
[
"MIT"
] | null | null | null |
lib/MagnetRTD/MagnetRTD.cpp
|
greenspaceexplorer/MagnetHSK
|
41ab4758a21ecf7f980032ee0f2f569b120f8ebf
|
[
"MIT"
] | null | null | null |
lib/MagnetRTD/MagnetRTD.cpp
|
greenspaceexplorer/MagnetHSK
|
41ab4758a21ecf7f980032ee0f2f569b120f8ebf
|
[
"MIT"
] | null | null | null |
#include "MagnetRTD.h"
MagnetRTD::MagnetRTD(SPIClass *mySPI, uint8_t clock, uint8_t chip_select){
// Set internal variables
thisSPI = mySPI;
clk = clock;
cs = chip_select;
}
//------------------------------------------------------------------------------
MagnetRTD::~MagnetRTD(){}
//------------------------------------------------------------------------------
void MagnetRTD::setup(){
// Initialize SPI communication on the housekeeping board
pinMode(clk,OUTPUT);
digitalWrite(clk,1);
thisSPI->begin();
pinMode(cs,OUTPUT);
configure_channels();
configure_memory_table();
configure_global_parameters();
}
//------------------------------------------------------------------------------
sMagnetRTD MagnetRTD::readTemp(uint8_t cmd)
{
sMagnetRTD out;
switch (cmd)
{
case eTopStackRTDcels:
{
out.value = this->returnTemperature(cs,TopStack);
break;
}
case eTopNonStackRTDcels:
{
out.value = this->returnTemperature(cs,TopNonStack);
break;
}
case eBottomStackRTDcels:
{
out.value = this->returnTemperature(cs,BottomStack);
break;
}
case eBottomNonStackRTDcels:
{
out.value = this->returnTemperature(cs,BottomNonStack);
break;
}
case eShieldRTD1cels:
{
out.value = this->returnTemperature(cs,Shield1);
break;
}
case eShieldRTD2cels:
{
out.value = this->returnTemperature(cs,Shield2);
break;
}
default:
{
out.value = -1.0; // invalid command
break;
}
}
return out;
}
//------------------------------------------------------------------------------
sMagnetRTD MagnetRTD::readResist(uint8_t cmd)
{
sMagnetRTD out;
switch (cmd)
{
case eTopStackRTDohms:
{
out.value = this->returnResistance(cs,TopStack);
break;
}
case eTopNonStackRTDohms:
{
out.value = this->returnResistance(cs,TopNonStack);
break;
}
case eBottomStackRTDohms:
{
out.value = this->returnResistance(cs,BottomStack);
break;
}
case eBottomNonStackRTDohms:
{
out.value = this->returnResistance(cs,BottomNonStack);
break;
}
case eShieldRTD1ohms:
{
out.value = this->returnResistance(cs,Shield1);
break;
}
case eShieldRTD2ohms:
{
out.value = this->returnResistance(cs,Shield2);
break;
}
default:
{
out.value = -1.0; // invalid command
break;
}
}
return out;
}
//------------------------------------------------------------------------------
sMagnetRTDAll MagnetRTD::readAll(uint8_t cmd)
{
sMagnetRTDAll out;
if (cmd == eRTDallCels)
{
out.top_stack = this->readTemp(eTopStackRTDcels).value;
out.top_nonstack = this->readTemp(eTopNonStackRTDcels).value;
out.btm_stack = this->readTemp(eBottomStackRTDcels).value;
out.btm_nonstack = this->readTemp(eBottomNonStackRTDcels).value;
out.shield1 = this->readTemp(eShieldRTD1cels).value;
out.shield2 = this->readTemp(eShieldRTD2cels).value;
}
else if (cmd == eRTDallOhms)
{
out.top_stack = this->readResist(eTopStackRTDohms).value;
out.top_nonstack = this->readResist(eTopNonStackRTDohms).value;
out.btm_stack = this->readResist(eBottomStackRTDohms).value;
out.btm_nonstack = this->readResist(eBottomNonStackRTDohms).value;
out.shield1 = this->readResist(eShieldRTD1ohms).value;
out.shield2 = this->readResist(eShieldRTD2ohms).value;
}
else
{
out.top_stack = -1.;
out.top_nonstack = -1.;
out.btm_stack = -1.;
out.btm_nonstack = -1.;
out.shield1 = -1.;
out.shield2 = -1.;
}
return out;
}
//------------------------------------------------------------------------------
int MagnetRTD::wait_for_process_to_finish(uint8_t chip_select)
{
uint8_t process_finished = 0;
uint8_t data;
int goAhead = 1;
// unsigned long CurrentTime;
// unsigned long ElapsedTime;
unsigned long StartTime = millis();
while (process_finished == 0)
{
data =
this->transfer_byte(chip_select, READ_FROM_RAM, COMMAND_STATUS_REGISTER, 0);
process_finished = data & 0x40;
if ((millis() - StartTime) > MaxWaitSpi)
{
goAhead = 0;
return goAhead;
}
}
// Serial.print(" t=");
// Serial.print(millis() - StartTime);
// Serial.print(" ");
return goAhead;
}
//------------------------------------------------------------------------------
uint16_t MagnetRTD::get_start_address(uint16_t base_address, uint8_t channel_number)
{
return base_address + 4 * (channel_number-1);
}
//------------------------------------------------------------------------------
uint8_t MagnetRTD::transfer_byte(uint8_t chip_select, uint8_t ram_read_or_write,
uint16_t start_address, uint8_t input_data)
{
uint8_t tx[4], rx[4];
tx[3] = ram_read_or_write;
tx[2] = (uint8_t)(start_address >> 8);
tx[1] = (uint8_t)start_address;
tx[0] = input_data;
this->spi_transfer_block(chip_select, tx, rx, 4);
return rx[0];
}
//------------------------------------------------------------------------------
bool MagnetRTD::is_number_in_array(uint8_t number, uint8_t *array, uint8_t array_length)
// Find out if a number is an element in an array
{
bool found = false;
for (uint8_t i=0; i< array_length; i++)
{
if (number == array[i])
{
found = true;
}
}
return found;
}
//------------------------------------------------------------------------------
uint32_t MagnetRTD::transfer_four_bytes(uint8_t chip_select, uint8_t ram_read_or_write,
uint16_t start_address, uint32_t input_data)
{
uint32_t output_data;
uint8_t tx[7], rx[7];
tx[6] = ram_read_or_write;
tx[5] = highByte(start_address);
tx[4] = lowByte(start_address);
tx[3] = (uint8_t)(input_data >> 24);
tx[2] = (uint8_t)(input_data >> 16);
tx[1] = (uint8_t)(input_data >> 8);
tx[0] = (uint8_t)input_data;
this->spi_transfer_block(chip_select, tx, rx, 7);
output_data = (uint32_t)rx[3] << 24 | (uint32_t)rx[2] << 16 |
(uint32_t)rx[1] << 8 | (uint32_t)rx[0];
return output_data;
}
//------------------------------------------------------------------------------
// Reads and sends a byte array
void MagnetRTD::spi_transfer_block(uint8_t cs_pin, uint8_t *tx, uint8_t *rx,
uint8_t length)
{
int8_t i;
output_low(cs_pin); //! 1) Pull CS low
for (i = (length - 1); i >= 0; i--)
rx[i] = thisSPI->transfer(tx[i]); //! 2) Read and send byte array
output_high(cs_pin); //! 3) Pull CS high
}
//------------------------------------------------------------------------------
float MagnetRTD::returnResistance(uint8_t chip_select, uint8_t channel_number)
{
int goAhead;
goAhead = convert_channel(chip_select, channel_number);
if (goAhead == 1)
{
int32_t raw_data;
float voltage_or_resistance_result;
uint16_t start_address = this->get_start_address(VOUT_CH_BASE, channel_number);
raw_data =
this->transfer_four_bytes(chip_select, READ_FROM_RAM, start_address, 0);
voltage_or_resistance_result = (float)raw_data / 1024;
return voltage_or_resistance_result;
}
else
{
return Nonsense;
}
}
//------------------------------------------------------------------------------
float MagnetRTD::returnTemperature(uint8_t chip_select, uint8_t channel_number)
{
int goAhead;
goAhead = convert_channel(chip_select, channel_number);
if (goAhead == 1)
{
uint32_t raw_data;
uint8_t fault_data;
uint16_t start_address =
this->get_start_address(CONVERSION_RESULT_MEMORY_BASE, channel_number);
uint32_t raw_conversion_result;
int32_t signed_data;
float scaled_result;
raw_data =
this->transfer_four_bytes(chip_select, READ_FROM_RAM, start_address, 0);
// 24 LSB's are conversion result
raw_conversion_result = raw_data & 0xFFFFFF;
signed_data = raw_conversion_result;
// Convert the 24 LSB's into a signed 32-bit integer
if (signed_data & 0x800000)
signed_data = signed_data | 0xFF000000;
scaled_result = float(signed_data) / 1024;
return scaled_result;
}
else
{
return -9999;
}
}
//------------------------------------------------------------------------------
int MagnetRTD::convert_channel(uint8_t chip_select, uint8_t channel_number)
{
// Start conversion
this->transfer_byte(chip_select, WRITE_TO_RAM, COMMAND_STATUS_REGISTER,
CONVERSION_CONTROL_BYTE | channel_number);
int goAhead;
goAhead = this->wait_for_process_to_finish(chip_select);
return goAhead;
}
| 27.535714
| 88
| 0.540208
|
greenspaceexplorer
|
8a57390a40c4eecd165993b213e765472047d571
| 10,553
|
cpp
|
C++
|
src/hash_value.cpp
|
MiguelBel/natalie
|
8439d45982b0edb14e51cd1958a865bb7f540b2d
|
[
"MIT"
] | null | null | null |
src/hash_value.cpp
|
MiguelBel/natalie
|
8439d45982b0edb14e51cd1958a865bb7f540b2d
|
[
"MIT"
] | null | null | null |
src/hash_value.cpp
|
MiguelBel/natalie
|
8439d45982b0edb14e51cd1958a865bb7f540b2d
|
[
"MIT"
] | null | null | null |
#include "natalie.hpp"
namespace Natalie {
// this is used by the hashmap library and assumes that obj->env has been set
size_t HashValue::hash(const void *key) {
return static_cast<const HashValue::Key *>(key)->hash;
}
// this is used by the hashmap library to compare keys
int HashValue::compare(const void *a, const void *b) {
Key *a_p = (Key *)a;
Key *b_p = (Key *)b;
// NOTE: Only one of the keys will have a relevant Env, i.e. the one with a non-null global_env.
// This is a bit of a hack to get around the fact that we can't pass any extra args to hashmap_* functions.
// TODO: Write our own hashmap implementation that passes Env around. :^)
Env *env = a_p->env.global_env() ? &a_p->env : &b_p->env;
assert(env);
assert(env->global_env());
return a_p->key->send(env, "eql?", 1, &b_p->key)->is_truthy() ? 0 : 1; // return 0 for exact match
}
Value *HashValue::get(Env *env, Value *key) {
Key key_container;
key_container.key = key;
key_container.env = *env;
key_container.hash = key->send(env, "hash")->as_integer()->to_int64_t();
Val *container = static_cast<Val *>(hashmap_get(&m_hashmap, &key_container));
Value *val = container ? container->val : nullptr;
return val;
}
Value *HashValue::get_default(Env *env, Value *key) {
if (m_default_block) {
Value *args[2] = { this, key };
return NAT_RUN_BLOCK_WITHOUT_BREAK(env, m_default_block, 2, args, nullptr);
} else {
return m_default_value;
}
}
void HashValue::put(Env *env, Value *key, Value *val) {
NAT_ASSERT_NOT_FROZEN(this);
Key key_container;
key_container.key = key;
key_container.env = *env;
key_container.hash = key->send(env, "hash")->as_integer()->to_int64_t();
Val *container = static_cast<Val *>(hashmap_get(&m_hashmap, &key_container));
if (container) {
container->key->val = val;
container->val = val;
} else {
if (m_is_iterating) {
NAT_RAISE(env, "RuntimeError", "can't add a new key into hash during iteration");
}
container = static_cast<Val *>(malloc(sizeof(Val)));
container->key = key_list_append(env, key, val);
container->val = val;
hashmap_put(&m_hashmap, container->key, container);
// NOTE: env must be current and relevant at all times
// See note on hashmap_compare for more details
container->key->env = {};
}
}
Value *HashValue::remove(Env *env, Value *key) {
Key key_container;
key_container.key = key;
key_container.env = *env;
key_container.hash = key->send(env, "hash")->as_integer()->to_int64_t();
Val *container = static_cast<Val *>(hashmap_remove(&m_hashmap, &key_container));
if (container) {
key_list_remove_node(container->key);
Value *val = container->val;
free(container);
return val;
} else {
return nullptr;
}
}
Value *HashValue::default_proc(Env *env) {
return ProcValue::from_block_maybe(env, m_default_block);
}
Value *HashValue::default_value(Env *env) {
if (m_default_value)
return m_default_value;
return env->nil_obj();
}
HashValue::Key *HashValue::key_list_append(Env *env, Value *key, Value *val) {
if (m_key_list) {
Key *first = m_key_list;
Key *last = m_key_list->prev;
Key *new_last = static_cast<Key *>(malloc(sizeof(Key)));
new_last->key = key;
new_last->val = val;
// <first> ... <last> <new_last> -|
// ^______________________________|
new_last->prev = last;
new_last->next = first;
new_last->env = Env::new_detatched_block_env(env);
new_last->hash = key->send(env, "hash")->as_integer()->to_int64_t();
new_last->removed = false;
first->prev = new_last;
last->next = new_last;
return new_last;
} else {
Key *node = static_cast<Key *>(malloc(sizeof(Key)));
node->key = key;
node->val = val;
node->prev = node;
node->next = node;
node->env = Env::new_detatched_block_env(env);
node->hash = key->send(env, "hash")->as_integer()->to_int64_t();
node->removed = false;
m_key_list = node;
return node;
}
}
void HashValue::key_list_remove_node(Key *node) {
Key *prev = node->prev;
Key *next = node->next;
// <prev> <-> <node> <-> <next>
if (node == next) {
// <node> -|
// ^_______|
node->prev = nullptr;
node->next = nullptr;
node->removed = true;
m_key_list = nullptr;
return;
} else if (m_key_list == node) {
// starting point is the node to be removed, so shift them forward by one
m_key_list = next;
}
// remove the node
node->removed = true;
prev->next = next;
next->prev = prev;
}
Value *HashValue::initialize(Env *env, Value *default_value, Block *block) {
if (block) {
if (default_value) {
NAT_RAISE(env, "ArgumentError", "wrong number of arguments (given 1, expected 0)");
}
set_default_block(block);
} else if (default_value) {
set_default_value(default_value);
}
return this;
}
// Hash[]
Value *HashValue::square_new(Env *env, ssize_t argc, Value **args) {
if (argc == 0) {
return new HashValue { env };
} else if (argc == 1) {
Value *value = args[0];
if (value->type() == Value::Type::Hash) {
return value;
} else if (value->type() == Value::Type::Array) {
HashValue *hash = new HashValue { env };
for (auto &pair : *value->as_array()) {
if (pair->type() != Value::Type::Array) {
NAT_RAISE(env, "ArgumentError", "wrong element in array to Hash[]");
}
ssize_t size = pair->as_array()->size();
if (size < 1 || size > 2) {
NAT_RAISE(env, "ArgumentError", "invalid number of elements (%d for 1..2)", size);
}
Value *key = (*pair->as_array())[0];
Value *value = size == 1 ? env->nil_obj() : (*pair->as_array())[1];
hash->put(env, key, value);
}
return hash;
}
}
if (argc % 2 != 0) {
NAT_RAISE(env, "ArgumentError", "odd number of arguments for Hash");
}
HashValue *hash = new HashValue { env };
for (ssize_t i = 0; i < argc; i += 2) {
Value *key = args[i];
Value *value = args[i + 1];
hash->put(env, key, value);
}
return hash;
}
Value *HashValue::inspect(Env *env) {
StringValue *out = new StringValue { env, "{" };
ssize_t last_index = size() - 1;
ssize_t index = 0;
for (HashValue::Key &node : *this) {
StringValue *key_repr = node.key->send(env, "inspect")->as_string();
out->append_string(env, key_repr);
out->append(env, "=>");
StringValue *val_repr = node.val->send(env, "inspect")->as_string();
out->append_string(env, val_repr);
if (index < last_index) {
out->append(env, ", ");
}
index++;
}
out->append_char(env, '}');
return out;
}
Value *HashValue::ref(Env *env, Value *key) {
Value *val = get(env, key);
if (val) {
return val;
} else {
return get_default(env, key);
}
}
Value *HashValue::refeq(Env *env, Value *key, Value *val) {
put(env, key, val);
return val;
}
Value *HashValue::delete_key(Env *env, Value *key) {
NAT_ASSERT_NOT_FROZEN(this);
Value *val = remove(env, key);
if (val) {
return val;
} else {
return env->nil_obj();
}
}
Value *HashValue::size(Env *env) {
assert(size() <= NAT_MAX_INT);
return new IntegerValue { env, static_cast<int64_t>(size()) };
}
Value *HashValue::eq(Env *env, Value *other_value) {
if (!other_value->is_hash()) {
return env->false_obj();
}
HashValue *other = other_value->as_hash();
if (size() != other->size()) {
return env->false_obj();
}
Value *other_val;
for (HashValue::Key &node : *this) {
other_val = other->get(env, node.key);
if (!other_val) {
return env->false_obj();
}
if (!node.val->send(env, "==", 1, &other_val, nullptr)->is_truthy()) {
return env->false_obj();
}
}
return env->true_obj();
}
#define NAT_RUN_BLOCK_AND_POSSIBLY_BREAK_WHILE_ITERATING_HASH(env, the_block, argc, args, block, hash) ({ \
Value *_result = the_block->_run(env, argc, args, block); \
if (_result->has_break_flag()) { \
_result->remove_break_flag(); \
hash->set_is_iterating(false); \
return _result; \
} \
_result; \
})
Value *HashValue::each(Env *env, Block *block) {
NAT_ASSERT_BLOCK(); // TODO: return Enumerator when no block given
Value *block_args[2];
for (HashValue::Key &node : *this) {
block_args[0] = node.key;
block_args[1] = node.val;
NAT_RUN_BLOCK_AND_POSSIBLY_BREAK_WHILE_ITERATING_HASH(env, block, 2, block_args, nullptr, this);
}
return this;
}
Value *HashValue::keys(Env *env) {
ArrayValue *array = new ArrayValue { env };
for (HashValue::Key &node : *this) {
array->push(node.key);
}
return array;
}
Value *HashValue::values(Env *env) {
ArrayValue *array = new ArrayValue { env };
for (HashValue::Key &node : *this) {
array->push(node.val);
}
return array;
}
Value *HashValue::sort(Env *env) {
ArrayValue *ary = new ArrayValue { env };
for (HashValue::Key &node : *this) {
ArrayValue *pair = new ArrayValue { env };
pair->push(node.key);
pair->push(node.val);
ary->push(pair);
}
return ary->sort(env);
}
Value *HashValue::has_key(Env *env, Value *key) {
Value *val = get(env, key);
if (val) {
return env->true_obj();
} else {
return env->false_obj();
}
}
}
| 32.773292
| 111
| 0.548659
|
MiguelBel
|
8a5c3c9f98f315765a9fd560976ac5d593fff95e
| 17,111
|
cpp
|
C++
|
NULL Engine/Source/E_Inspector.cpp
|
xsiro/NULL_Engine
|
bb8da3de7f507b27d895cf8066a03faa115ff3c6
|
[
"MIT"
] | null | null | null |
NULL Engine/Source/E_Inspector.cpp
|
xsiro/NULL_Engine
|
bb8da3de7f507b27d895cf8066a03faa115ff3c6
|
[
"MIT"
] | null | null | null |
NULL Engine/Source/E_Inspector.cpp
|
xsiro/NULL_Engine
|
bb8da3de7f507b27d895cf8066a03faa115ff3c6
|
[
"MIT"
] | null | null | null |
#include "MathGeoTransform.h"
#include "Color.h"
#include "Application.h"
#include "M_Renderer3D.h"
#include "M_Editor.h"
#include "GameObject.h"
#include "Component.h"
#include "C_Transform.h"
#include "C_Mesh.h"
#include "C_Material.h"
#include "C_Light.h"
#include "C_Camera.h"
#include "E_Inspector.h"
#define MAX_VALUE 100000
#define MIN_VALUE -100000
E_Inspector::E_Inspector() : EditorPanel("Inspector"),
show_delete_component_popup (false),
component_type (0),
map_to_display (0),
component_to_delete (nullptr)
{
}
E_Inspector::~E_Inspector()
{
component_to_delete = nullptr;
}
bool E_Inspector::Draw(ImGuiIO& io)
{
bool ret = true;
ImGui::Begin("Inspector");
SetIsHovered();
GameObject* selected = App->editor->GetSelectedGameObjectThroughEditor();
if (selected != nullptr && !selected->is_master_root && !selected->is_scene_root)
{
DrawGameObjectInfo(selected);
DrawComponents(selected);
ImGui::Separator();
AddComponentCombo(selected);
if (show_delete_component_popup)
{
DeleteComponentPopup(selected);
}
}
//ImGui::Text("WantCaptureMouse: %d", io.WantCaptureMouse);
//ImGui::Text("WantCaptureKeyboard: %d", io.WantCaptureKeyboard);
//ImGui::Text("WantTextInput: %d", io.WantTextInput);
//ImGui::Text("WantSetMousePos: %d", io.WantSetMousePos);
//ImGui::Text("NavActive: %d, NavVisible: %d", io.NavActive, io.NavVisible);
ImGui::End();
return ret;
}
bool E_Inspector::CleanUp()
{
bool ret = true;
return ret;
}
// --- INSPECTOR METHODS ---
void E_Inspector::DrawGameObjectInfo(GameObject* selected_game_object)
{
// --- IS ACTIVE ---
bool game_object_is_active = selected_game_object->IsActive();
if (ImGui::Checkbox("Is Active", &game_object_is_active))
{
selected_game_object->SetIsActive(game_object_is_active);
}
ImGui::SameLine();
// --- GAME OBJECT'S NAME ---
ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.33f);
static char buffer[64];
strcpy_s(buffer, selected_game_object->GetName());
if (ImGui::InputText("Name", buffer, IM_ARRAYSIZE(buffer), ImGuiInputTextFlags_EnterReturnsTrue))
{
selected_game_object->SetName(buffer);
}
ImGui::SameLine(); HelpMarker("Press ENTER to Rename");
ImGui::SameLine();
// --- IS STATIC ---
//bool is_static = selected_game_object->IsStatic();
bool is_static = true;
if (ImGui::Checkbox("Is Static", &is_static))
{
selected_game_object->SetIsStatic(is_static);
}
// --- TAG ---
ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.33f);
static char tag_combo[64] = { "Untagged\0Work\0In\0Progress" };
static int current_tag = 0;
ImGui::Combo("Tag", ¤t_tag, tag_combo);
ImGui::SameLine(218.0f);
// --- LAYER ---
ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.33f);
static char layer_combo[64] = { "Default\0Work\0In\0Progress" };
static int current_layer = 0;
ImGui::Combo("Layer", ¤t_layer, layer_combo);
ImGui::Separator();
}
void E_Inspector::DrawComponents(GameObject* selected_game_object)
{
if (selected_game_object == nullptr)
{
LOG("[ERROR] Editor Inspector: Could not draw the selected GameObject's components! Error: Selected GameObject was nullptr.");
return;
}
for (uint i = 0; i < selected_game_object->components.size(); ++i)
{
Component* component = selected_game_object->components[i];
if (component == nullptr)
{
continue;
}
COMPONENT_TYPE type = component->GetType();
switch (type)
{
case COMPONENT_TYPE::TRANSFORM: { DrawTransformComponent((C_Transform*)component); } break;
case COMPONENT_TYPE::MESH: { DrawMeshComponent((C_Mesh*)component); } break;
case COMPONENT_TYPE::MATERIAL: { DrawMaterialComponent((C_Material*)component); } break;
case COMPONENT_TYPE::LIGHT: { DrawLightComponent((C_Light*)component); } break;
case COMPONENT_TYPE::CAMERA: { DrawCameraComponent((C_Camera*)component); } break;
}
if (type == COMPONENT_TYPE::NONE)
{
LOG("[WARNING] Selected GameObject %s has a non-valid component!", selected_game_object->GetName());
}
}
}
void E_Inspector::DrawTransformComponent(C_Transform* c_transform)
{
bool show = true; // Dummy bool to delete the component related with the collpsing header.
if (ImGui::CollapsingHeader("Transform", &show, ImGuiTreeNodeFlags_DefaultOpen))
{
if (c_transform != nullptr)
{
// --- IS ACTIVE ---
bool transform_is_active = c_transform->IsActive();
if (ImGui::Checkbox("Transform Is Active", &transform_is_active))
{
//transform->SetIsActive(transform_is_active);
c_transform->SetIsActive(transform_is_active);
}
ImGui::Separator();
// --- POSITION ---
ImGui::Text("Position");
ImGui::SameLine(100.0f);
float3 position = c_transform->GetLocalPosition();
if (ImGui::DragFloat3("P", (float*)&position, 0.05f, 0.0f, 0.0f, "%.3f", NULL))
{
c_transform->SetLocalPosition(position);
}
// --- ROTATION ---
ImGui::Text("Rotation");
ImGui::SameLine(100.0f);
/*float3 rotation = transform->GetLocalEulerRotation();
if (ImGui::DragFloat3("R", (float*)&rotation, 1.0f, 0.0f, 0.0f, "%.3f", NULL))
{
transform->SetLocalEulerRotation(rotation);
}*/
float3 rotation = c_transform->GetLocalEulerRotation() * RADTODEG;
if (ImGui::DragFloat3("R", (float*)&rotation, 1.0f, 0.0f, 0.0f, "%.3f", NULL))
{
c_transform->SetLocalRotation(rotation * DEGTORAD);
}
// --- SCALE ---
ImGui::Text("Scale");
ImGui::SameLine(100.0f);
float3 scale = c_transform->GetLocalScale();
if (ImGui::DragFloat3("S", (float*)&scale, 0.05f, 0.0f, 0.0f, "%.3f", NULL))
{
c_transform->SetLocalScale(scale);
}
}
if (!show)
{
LOG("[ERROR] Transform components cannot be deleted!");
}
ImGui::Separator();
}
}
void E_Inspector::DrawMeshComponent(C_Mesh* c_mesh)
{
bool show = true;
if (ImGui::CollapsingHeader("Mesh", &show, ImGuiTreeNodeFlags_DefaultOpen))
{
if (c_mesh != nullptr)
{
// --- IS ACTIVE ---
bool mesh_is_active = c_mesh->IsActive();
if (ImGui::Checkbox("Mesh Is Active", &mesh_is_active))
{
c_mesh->SetIsActive(mesh_is_active);
}
ImGui::Separator();
// --- FILE PATH ---
ImGui::Text("File:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.0f, 1.0f, 0.0f, 1.0f), "%s", c_mesh->GetMeshFile());
ImGui::Separator();
// --- MESH DATA ---
ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Mesh Data:");
uint num_vertices = 0;
uint num_normals = 0;
uint num_tex_coords = 0;
uint num_indices = 0;
c_mesh->GetMeshData(num_vertices, num_normals, num_tex_coords, num_indices);
ImGui::Text("Vertices:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %u", num_vertices);
ImGui::Text("Normals:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %u", num_normals);
ImGui::Text("Tex Coords:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%u", num_tex_coords);
ImGui::Text("Indices:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %u", num_indices);
ImGui::Separator();
// --- DRAW MODE ---
ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Draw Mode:");
bool show_wireframe = c_mesh->GetShowWireframe();
if (ImGui::Checkbox("Show Wireframe", &show_wireframe))
{
c_mesh->SetShowWireframe(show_wireframe);
}
bool show_bounding_box = c_mesh->GetShowBoundingBox();
if (ImGui::Checkbox("Show Bounding Box", &show_bounding_box))
{
c_mesh->SetShowBoundingBox(show_bounding_box);
c_mesh->GetOwner()->show_bounding_boxes = show_bounding_box;
}
bool draw_vert_normals = c_mesh->GetDrawVertexNormals();
if (ImGui::Checkbox("Draw Vertex Normals", &draw_vert_normals))
{
c_mesh->SetDrawVertexNormals(draw_vert_normals);
}
bool draw_face_normals = c_mesh->GetDrawFaceNormals();
if (ImGui::Checkbox("Draw Face Normals", &draw_face_normals))
{
c_mesh->SetDrawFaceNormals(draw_face_normals);
}
}
else
{
LOG("[ERROR] Could not get the Mesh Component from %s Game Object!", c_mesh->GetOwner()->GetName());
}
if (!show)
{
component_to_delete = c_mesh;
show_delete_component_popup = true;
}
ImGui::Separator();
}
}
void E_Inspector::DrawMaterialComponent(C_Material* c_material)
{
bool show = true;
if (ImGui::CollapsingHeader("Material", &show, ImGuiTreeNodeFlags_DefaultOpen))
{
if (c_material != nullptr)
{
bool material_is_active = c_material->IsActive();
if (ImGui::Checkbox("Material Is Active", &material_is_active))
{
c_material->SetIsActive(material_is_active);
}
ImGui::Separator();
// --- MATERIAL PATH ---
ImGui::Text("File:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.0f, 1.0f, 0.0f, 1.0f), "%s", c_material->GetTextureFile());
ImGui::Separator();
// --- MATERIAL COLOR & ALPHA ---
ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Material Data:");
Color color = c_material->GetMaterialColour();
if (ImGui::ColorEdit3("Diffuse Color", (float*)&color, ImGuiColorEditFlags_NoAlpha))
{
c_material->SetMaterialColour(color);
}
if (ImGui::SliderFloat("Diffuse Alpha", (float*)&color.a, 0.0f, 1.0f, "%.3f"))
{
c_material->SetMaterialColour(color);
}
ImGui::Separator();
// --- TEXTURE DATA ---
DisplayTextureData(c_material);
ImGui::Separator();
// --- MAIN MAPS ---
ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Main Maps:");
if (ImGui::Combo("Textures(WIP)", &map_to_display, "Diffuse\0Specular\0Ambient\0Height\0Normal\0"))
{
LOG("[SCENE] Changed to map %d", map_to_display);
}
bool use_checkered_tex = c_material->UseDefaultTexture();
if (ImGui::Checkbox("Use Default Texture", &use_checkered_tex))
{
c_material->SetUseDefaultTexture(use_checkered_tex);
}
// --- TEXTURE DISPLAY ---
TextureDisplay(c_material);
}
else
{
LOG("[ERROR] Could not get the Material Component from %s Game Object!", c_material->GetOwner()->GetName());
}
if (!show)
{
component_to_delete = c_material;
show_delete_component_popup = true;
}
ImGui::Separator();
}
}
void E_Inspector::DrawLightComponent(C_Light* c_light)
{
bool show = true;
if (ImGui::CollapsingHeader("Light", &show, ImGuiTreeNodeFlags_DefaultOpen))
{
if (c_light != nullptr)
{
bool light_is_active = c_light->IsActive();
if (ImGui::Checkbox("Light Is Active", &light_is_active))
{
c_light->SetIsActive(light_is_active);
}
ImGui::Separator();
ImGui::Text("WORK IN PROGRESS");
}
if (!show)
{
component_to_delete = c_light;
show_delete_component_popup = true;
}
ImGui::Separator();
}
}
void E_Inspector::DrawCameraComponent(C_Camera* c_camera)
{
bool show = true;
if (ImGui::CollapsingHeader("Camera", &show, ImGuiTreeNodeFlags_DefaultOpen))
{
if (c_camera != nullptr)
{
bool camera_is_active = c_camera->IsActive();
if (ImGui::Checkbox("Camera Is Active", &camera_is_active))
{
c_camera->SetIsActive(camera_is_active);
}
ImGui::Separator();
ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Camera Flags:");
bool camera_is_culling = c_camera->IsCulling();
if (ImGui::Checkbox("Culling", &camera_is_culling))
{
c_camera->SetIsCulling(camera_is_culling);
}
bool camera_is_orthogonal = c_camera->OrthogonalView();
if (ImGui::Checkbox("Orthogonal", &camera_is_orthogonal))
{
c_camera->SetOrthogonalView(camera_is_orthogonal);
}
bool frustum_is_hidden = c_camera->FrustumIsHidden();
if (ImGui::Checkbox("Hide Frustum", &frustum_is_hidden))
{
c_camera->SetFrustumIsHidden(frustum_is_hidden);
}
ImGui::Separator();
ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Frustum Settings:");
float near_plane_distance = c_camera->GetNearPlaneDistance();
if (ImGui::SliderFloat("Near Plane", &near_plane_distance, 0.1f, 1000.0f, "%.3f", 0))
{
c_camera->SetNearPlaneDistance(near_plane_distance);
}
float far_plane_distance = c_camera->GetFarPlaneDistance();
if (ImGui::SliderFloat("Far Plane", &far_plane_distance, 0.1f, 1000.0f, "%.3f", 0))
{
c_camera->SetFarPlaneDistance(far_plane_distance);
}
int fov = (int)c_camera->GetVerticalFOV();
uint min_fov = 0;
uint max_fov = 0;
c_camera->GetMinMaxFOV(min_fov, max_fov);
if (ImGui::SliderInt("FOV", &fov, min_fov, max_fov, "%d"))
{
c_camera->SetVerticalFOV((float)fov);
}
ImGui::Separator();
ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Camera Selection:");
if (ImGui::Button("Set as Current Camera"))
{
App->editor->SetCurrentCameraThroughEditor(c_camera);
}
if (ImGui::Button("Return to Master Camera"))
{
App->editor->SetMasterCameraThroughEditor();
}
}
if (!show)
{
component_to_delete = c_camera;
show_delete_component_popup = true;
}
ImGui::Separator();
}
}
void E_Inspector::AddComponentCombo(GameObject* selected_game_object)
{
ImGui::Combo("##", &component_type, "Add Component\0Transform\0Mesh\0Material\0Light\0Camera");
ImGui::SameLine();
if ((ImGui::Button("ADD")))
{
if (component_type != (int)COMPONENT_TYPE::NONE)
{
selected_game_object->CreateComponent((COMPONENT_TYPE)component_type);
}
}
}
void E_Inspector::DeleteComponentPopup(GameObject* selected_game_object)
{
std::string title = "Delete "; // Generating the specific string for the Popup title.
title += component_to_delete->GetNameFromType(); // The string will be specific to the component to delete.
title += " Component?"; // -------------------------------------------------------
ImGui::OpenPopup(title.c_str());
bool show = true; // Dummy bool to close the popup without having to click the "CONFIRM" or "CANCEL" Buttons.
if (ImGui::BeginPopupModal(title.c_str(), &show))
{
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 1.0f, 0.0f, 0.25f));
if (ImGui::Button("CONFIRM")) // CONFIRM Button. Will delete the component to delete.
{
selected_game_object->DeleteComponent(component_to_delete);
component_to_delete = nullptr;
show_delete_component_popup = false;
ImGui::CloseCurrentPopup();
}
ImGui::PopStyleColor();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(1.0f, 0.0f, 0.0f, 0.25f));
if (ImGui::Button("CANCEL")) // CANCEL Button. Will close the Popup.
{
component_to_delete = nullptr;
show_delete_component_popup = false;
ImGui::CloseCurrentPopup();
}
ImGui::PopStyleColor();
if (!show) // Popup cross. Will close the Popup. UX.
{
component_to_delete = nullptr;
show_delete_component_popup = false;
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
void E_Inspector::DisplayTextureData(C_Material* c_material)
{
ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Texture Data:");
uint id = 0;
uint width = 0;
uint height = 0;
uint depth = 0;
uint bpp = 0;
uint size = 0;
std::string format = "NONE";
bool compressed = 0;
c_material->GetTextureInfo(id, width, height, depth, bpp, size, format, compressed);
ImGui::Text("Texture ID:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%u", id);
ImGui::Text("Width:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %upx", width);
ImGui::Text("Height:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %upx", height);
ImGui::Text("Depth:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %u", depth);
ImGui::Text("Bpp:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %uB", bpp);
ImGui::Text("Size:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %uB", size);
ImGui::Text("Format:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %s", format.c_str());
ImGui::Text("Compressed:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%s", compressed ? "True" : "False");
}
void E_Inspector::TextureDisplay(C_Material* c_material)
{
ImTextureID tex_id = 0;
ImVec2 display_size = { ImGui::GetWindowWidth() * 0.925f , ImGui::GetWindowWidth() * 0.925f }; // Display Size will be 7.5% smaller than the Window Width.
ImVec4 tint = { 1.0f, 1.0f, 1.0f, 1.0f };
ImVec4 border_color = { 0.0f, 1.0f, 0.0f, 1.0f };
if (c_material->UseDefaultTexture())
{
//tex_id = (ImTextureID)App->renderer->GetDebugTextureID();
tex_id = (ImTextureID)App->renderer->GetSceneRenderTexture();
}
else
{
tex_id = (ImTextureID)c_material->GetTextureID();
}
if (tex_id != 0)
{
ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Texture Display:");
ImGui::Spacing();
ImGui::Image(tex_id, display_size, ImVec2(1.0f, 0.0f), ImVec2(0.0f, 1.0f), tint, border_color); // ImGui has access to OpenGL's buffers, so only the Texture Id is required.
}
}
| 28.143092
| 176
| 0.664952
|
xsiro
|
8a5f3971feb316dccd0cd8ae58e8d869d2235c68
| 317
|
cpp
|
C++
|
shared/test/common/helpers/kernel_binary_helper_hash_value.cpp
|
mattcarter2017/compute-runtime
|
1f52802aac02c78c19d5493dd3a2402830bbe438
|
[
"Intel",
"MIT"
] | null | null | null |
shared/test/common/helpers/kernel_binary_helper_hash_value.cpp
|
mattcarter2017/compute-runtime
|
1f52802aac02c78c19d5493dd3a2402830bbe438
|
[
"Intel",
"MIT"
] | null | null | null |
shared/test/common/helpers/kernel_binary_helper_hash_value.cpp
|
mattcarter2017/compute-runtime
|
1f52802aac02c78c19d5493dd3a2402830bbe438
|
[
"Intel",
"MIT"
] | null | null | null |
/*
* Copyright (C) 2020-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/test/common/helpers/kernel_binary_helper.h"
const std::string KernelBinaryHelper::BUILT_INS("7998916142903730155");
const std::string KernelBinaryHelper::BUILT_INS_WITH_IMAGES("16526264370178379440_images");
| 26.416667
| 91
| 0.785489
|
mattcarter2017
|
8a63695aa047f3e4cb64fc8067433206277554de
| 794
|
cpp
|
C++
|
examples/src/vertices.cpp
|
311Volt/axxegro
|
61d7a1fb48f9bb581e0f4171d58499cf8c543728
|
[
"MIT"
] | null | null | null |
examples/src/vertices.cpp
|
311Volt/axxegro
|
61d7a1fb48f9bb581e0f4171d58499cf8c543728
|
[
"MIT"
] | null | null | null |
examples/src/vertices.cpp
|
311Volt/axxegro
|
61d7a1fb48f9bb581e0f4171d58499cf8c543728
|
[
"MIT"
] | null | null | null |
#include <axxegro/axxegro.hpp>
/**
* @file
*
* a quick example on how to create custom vertex declarations
* and use them to draw primitives
*/
struct MyVertex {
float x,y;
float u,v;
};
struct MyVertexDecl: public al::CustomVertexDecl<MyVertex> {
AXXEGRO_VERTEX_ATTR_BEGIN()
AXXEGRO_VERTEX_ATTR(x, ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2)
AXXEGRO_VERTEX_ATTR(u, ALLEGRO_PRIM_TEX_COORD_PIXEL, ALLEGRO_PRIM_FLOAT_2)
};
int main()
{
al::FullInit();
al::Display disp(800, 600);
al::TargetBitmap.clearToColor(al::RGB(100,100,100));
al::Bitmap bg("data/bg.jpg");
std::vector<MyVertex> vtxs{
{1,1, 0,0},
{2,2, 0,1000},
{3,1, 1000,0}
};
al::Transform().scale({100, 100}).use();
al::DrawPrim<MyVertexDecl>(vtxs, bg);
al::CurrentDisplay.flip();
al::Sleep(2.0);
}
| 19.365854
| 75
| 0.695214
|
311Volt
|
8a6e329244309279560096772ea5c94eb91d0c85
| 524
|
hpp
|
C++
|
include/RED4ext/Scripting/Natives/Generated/ink/StreetSignsLayer.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 42
|
2020-12-25T08:33:00.000Z
|
2022-03-22T14:47:07.000Z
|
include/RED4ext/Scripting/Natives/Generated/ink/StreetSignsLayer.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 38
|
2020-12-28T22:36:06.000Z
|
2022-02-16T11:25:47.000Z
|
include/RED4ext/Scripting/Natives/Generated/ink/StreetSignsLayer.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 20
|
2020-12-28T22:17:38.000Z
|
2022-03-22T17:19:01.000Z
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/ink/WorldFluffLayer.hpp>
namespace RED4ext
{
namespace ink {
struct StreetSignsLayer : ink::WorldFluffLayer
{
static constexpr const char* NAME = "inkStreetSignsLayer";
static constexpr const char* ALIAS = NAME;
uint8_t unk1F8[0x250 - 0x1F8]; // 1F8
};
RED4EXT_ASSERT_SIZE(StreetSignsLayer, 0x250);
} // namespace ink
} // namespace RED4ext
| 23.818182
| 70
| 0.751908
|
jackhumbert
|
8a7302d7adb35de5efc2c033185697fdc3d159ff
| 2,586
|
hpp
|
C++
|
src/SingleLayerOptics/src/BSDFLayerMaker.hpp
|
bakonyidani/Windows-CalcEngine
|
afa4c4a9f88199c6206af8bc994a073931fc8b91
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
src/SingleLayerOptics/src/BSDFLayerMaker.hpp
|
bakonyidani/Windows-CalcEngine
|
afa4c4a9f88199c6206af8bc994a073931fc8b91
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
src/SingleLayerOptics/src/BSDFLayerMaker.hpp
|
bakonyidani/Windows-CalcEngine
|
afa4c4a9f88199c6206af8bc994a073931fc8b91
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
#ifndef BSDFLAYERMAKER_H
#define BSDFLAYERMAKER_H
#include <memory>
namespace SingleLayerOptics
{
enum class DistributionMethod
{
UniformDiffuse,
DirectionalDiffuse
};
class ICellDescription;
class CMaterial;
class CBSDFHemisphere;
class CBSDFLayer;
class CBaseCell;
// Class to simplify interface for BSDF layer creation
class CBSDFLayerMaker
{
public:
static std::shared_ptr<CBSDFLayer>
getSpecularLayer(const std::shared_ptr<CMaterial> & t_Material,
const CBSDFHemisphere & t_BSDF);
static std::shared_ptr<CBSDFLayer>
getCircularPerforatedLayer(const std::shared_ptr<CMaterial> & t_Material,
const CBSDFHemisphere & t_BSDF,
double x,
double y,
double thickness,
double radius);
static std::shared_ptr<CBSDFLayer>
getRectangularPerforatedLayer(const std::shared_ptr<CMaterial> & t_Material,
const CBSDFHemisphere & t_BSDF,
double x,
double y,
double thickness,
double xHole,
double yHole);
static std::shared_ptr<CBSDFLayer>
getVenetianLayer(const std::shared_ptr<CMaterial> & t_Material,
const CBSDFHemisphere & t_BSDF,
double slatWidth,
double slatSpacing,
double slatTiltAngle,
double curvatureRadius,
size_t numOfSlatSegments,
DistributionMethod method = DistributionMethod::DirectionalDiffuse);
static std::shared_ptr<CBSDFLayer>
getPerfectlyDiffuseLayer(const std::shared_ptr<CMaterial> & t_Material,
const CBSDFHemisphere & t_BSDF);
static std::shared_ptr<CBSDFLayer>
getWovenLayer(const std::shared_ptr<CMaterial> & t_Material,
const CBSDFHemisphere & t_BSDF,
double diameter,
double spacing);
private:
std::shared_ptr<CBSDFLayer> m_Layer;
std::shared_ptr<CBaseCell> m_Cell;
};
} // namespace SingleLayerOptics
#endif
| 35.424658
| 95
| 0.518948
|
bakonyidani
|
8a7fa64f68af68fa23cb3485066944c421347107
| 4,200
|
cpp
|
C++
|
src/concat_filter.cpp
|
shotahirama/velodyne_concat_filter
|
999e4c1ebeef9918a7ae2dc568eda1bee858a502
|
[
"Apache-2.0"
] | 1
|
2020-01-02T10:49:58.000Z
|
2020-01-02T10:49:58.000Z
|
src/concat_filter.cpp
|
shotahirama/velodyne_concat_filter
|
999e4c1ebeef9918a7ae2dc568eda1bee858a502
|
[
"Apache-2.0"
] | null | null | null |
src/concat_filter.cpp
|
shotahirama/velodyne_concat_filter
|
999e4c1ebeef9918a7ae2dc568eda1bee858a502
|
[
"Apache-2.0"
] | 1
|
2020-01-02T10:49:31.000Z
|
2020-01-02T10:49:31.000Z
|
/*
* Copyright 2019 Shota Hirama
*
* 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 <velodyne_concat_filter/concat_filter.h>
namespace velodyne_concat_filter
{
ConcatFilter::ConcatFilter() : private_nh_("~"), tf_listener_(tf_buffer_), running_(false) {}
ConcatFilter::ConcatFilter(ros::NodeHandle &nh, ros::NodeHandle &private_nh) : tf_listener_(tf_buffer_), running_(false)
{
nh_ = nh;
private_nh_ = private_nh;
}
ConcatFilter::~ConcatFilter()
{
if (running_) {
ROS_INFO("shutting thread");
running_ = false;
topic_monitor_thread_->join();
ROS_INFO("thread shutdown");
}
}
void ConcatFilter::initialize()
{
if (!private_nh_.getParam("velodyne_topics", topics_)) {
topics_ = {"/velodyne_front/velodyne_points", "/velodyne_rear/velodyne_points", "/velodyne_right/velodyne_points", "/velodyne_left/velodyne_points", "/velodyne_top/velodyne_points"};
}
assert(topics_.size() > 0);
if (!private_nh_.getParam("topic_monitor_rate", topic_monitor_rate_)) {
topic_monitor_rate_ = 10;
}
query_duration_ = ros::Duration(1.0 / topic_monitor_rate_);
if (!private_nh_.getParam("target_frame", target_frame_)) {
target_frame_ = "base_link";
}
concat_point_pub_ = nh_.advertise<sensor_msgs::PointCloud2>("concat_points", 1);
pointcloud2_vec_.resize(topics_.size());
callback_stamps_.resize(topics_.size());
for (int i = 0; i < topics_.size(); i++) {
pointcloud2_vec_[i].reset(new sensor_msgs::PointCloud2);
subs_.emplace_back(nh_.subscribe<sensor_msgs::PointCloud2>(topics_[i], 1, boost::bind(&ConcatFilter::callback, this, _1, i)));
}
running_ = true;
topic_monitor_thread_ = std::make_shared<std::thread>(&ConcatFilter::topic_monitor, this);
topic_monitor_thread_->detach();
}
void ConcatFilter::callback(const sensor_msgs::PointCloud2ConstPtr &msg, int i)
{
pointcloud2_vec_[i] = msg;
}
void ConcatFilter::topic_monitor()
{
ros::Rate rate(topic_monitor_rate_);
while (running_) {
PointCloudT::Ptr concat_cloud = boost::make_shared<PointCloudT>();
std::vector<PointCloudT::Ptr> clouds(topics_.size());
try {
for (size_t i = 0; i < topics_.size(); i++) {
clouds[i] = boost::make_shared<PointCloudT>();
if (!pointcloud2_vec_[i]->data.empty()) {
sensor_msgs::PointCloud2 pc = *pointcloud2_vec_[i];
auto diff = ros::Duration(pc.header.stamp.toSec() - old_time_.toSec()) + query_duration_;
if (diff.toNSec() > 0) {
std::string source_frame = pc.header.frame_id;
if (source_frame[0] == '/') {
source_frame.erase(source_frame.begin());
}
const geometry_msgs::TransformStamped transformStamped = tf_buffer_.lookupTransform(target_frame_, source_frame, ros::Time(0), ros::Duration(0.01));
sensor_msgs::PointCloud2 transform_cloud;
pcl_ros::transformPointCloud(tf2::transformToEigen(transformStamped.transform).matrix().cast<float>(), pc, transform_cloud);
pcl::fromROSMsg(transform_cloud, *clouds[i]);
*concat_cloud += *clouds[i];
} else {
ROS_WARN("drop points frame_id: %s", pointcloud2_vec_[i]->header.frame_id.c_str());
}
}
}
} catch (tf2::TransformException &ex) {
ROS_ERROR("%s", ex.what());
continue;
}
if (concat_cloud->points.size() > 0) {
sensor_msgs::PointCloud2 pubmsg;
pcl::toROSMsg(*concat_cloud, pubmsg);
pubmsg.header.stamp = ros::Time::now();
pubmsg.header.frame_id = target_frame_;
concat_point_pub_.publish(pubmsg);
}
old_time_ = ros::Time::now();
rate.sleep();
}
}
} // namespace velodyne_concat_filter
| 37.5
| 186
| 0.683333
|
shotahirama
|
8a820fcfc3bd86b8e71d8ad96dea49c5d181718b
| 1,638
|
hpp
|
C++
|
jitstmt/StmtMatmul.hpp
|
cjang/chai
|
7faba752cc4491d1b30590abef21edc4efffa0f6
|
[
"Unlicense"
] | 11
|
2015-06-12T19:54:14.000Z
|
2021-11-26T10:45:18.000Z
|
jitstmt/StmtMatmul.hpp
|
cjang/chai
|
7faba752cc4491d1b30590abef21edc4efffa0f6
|
[
"Unlicense"
] | null | null | null |
jitstmt/StmtMatmul.hpp
|
cjang/chai
|
7faba752cc4491d1b30590abef21edc4efffa0f6
|
[
"Unlicense"
] | null | null | null |
// Copyright 2012 Chris Jang (fastkor@gmail.com) under The Artistic License 2.0
#ifndef _CHAI_STMT_MATMUL_HPP_
#define _CHAI_STMT_MATMUL_HPP_
#include "VisitAst.hpp"
#include "StmtMatmulBase.hpp"
namespace chai_internal {
////////////////////////////////////////
// matrix multiplication
// (all cases except outer product)
class StmtMatmul : public StmtMatmulBase,
public VisitAst
{
// RHS
AstMatmulMM* _rhsMatmulMM;
AstMatmulMV* _rhsMatmulMV;
AstMatmulVM* _rhsMatmulVM;
// recursive visiting down AST tree
void descendAst(BaseAst&);
public:
StmtMatmul(AstVariable* lhs, AstMatmulMM* rhs);
StmtMatmul(AstVariable* lhs, AstMatmulMV* rhs);
StmtMatmul(AstVariable* lhs, AstMatmulVM* rhs);
void accept(VisitStmt&);
AstMatmulMM* matmulPtr(void) const;
AstMatmulMV* matvecPtr(void) const;
AstMatmulVM* vecmatPtr(void) const;
void visit(AstAccum&);
void visit(AstArrayMem&);
void visit(AstCond&);
void visit(AstConvert&);
void visit(AstDotprod&);
void visit(AstExtension&);
void visit(AstFun1&);
void visit(AstFun2&);
void visit(AstFun3&);
void visit(AstGather&);
void visit(AstIdxdata&);
void visit(AstLitdata&);
void visit(AstMakedata&);
void visit(AstMatmulMM&);
void visit(AstMatmulMV&);
void visit(AstMatmulVM&);
void visit(AstMatmulVV&);
void visit(AstOpenCL&);
void visit(AstReadout&);
void visit(AstRNGnormal&);
void visit(AstRNGuniform&);
void visit(AstScalar&);
void visit(AstTranspose&);
void visit(AstVariable&);
};
}; // namespace chai_internal
#endif
| 24.818182
| 79
| 0.675214
|
cjang
|
8a8952a551dfb9ad624e5e2246991539738e0ecc
| 2,604
|
cxx
|
C++
|
AD/ADrec/AliADQAParam.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | null | null | null |
AD/ADrec/AliADQAParam.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 2
|
2016-11-25T08:40:56.000Z
|
2019-10-11T12:29:29.000Z
|
AD/ADrec/AliADQAParam.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | null | null | null |
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliADQAParam.h"
ClassImp(AliADQAParam)
//_____________________________________________________________________________
AliADQAParam::AliADQAParam():
fNTdcTimeBins(3062),
fTdcTimeMin(0.976562),
fTdcTimeMax(300.0),
fNTdcTimeBinsFlag(410),
fTdcTimeMinBGFlag(50.0),
fTdcTimeMaxBGFlag(90.039062),
fTdcTimeMinBBFlag(170.0),
fTdcTimeMaxBBFlag(210.039062),
fNTdcTimeRatioBins(300),
fTdcTimeRatioMin(1),
fTdcTimeRatioMax(301),
fNTdcWidthBins(153),
fTdcWidthMin(2.343750),
fTdcWidthMax(121.875000),
fNChargeChannelBins(1000),
fChargeChannelMin(0),
fChargeChannelMax(1000),
fChargeChannelZoomMin(0),
fChargeChannelZoomMax(50),
fNChargeSideBins(500),
fChargeSideMin(1),
fChargeSideMax(5000),
fNChargeCorrBins(101),
fChargeCorrMin(1),
fChargeCorrMax(1001),
fNPairTimeCorrBins(306),
fPairTimeCorrMin(0.976562),
fPairTimeCorrMax(299.804688),
fNPairTimeDiffBins(154),
fPairTimeDiffMin(-15.039062),
fPairTimeDiffMax(15.039062),
fNMeanTimeCorrBins(306),
fMeanTimeCorrMin(50.976562),
fMeanTimeCorrMax(349.804688),
fChargeTrendMin(0),
fChargeTrendMax(1000),
fSatMed(0.1),
fSatHigh(0.3),
fSatHuge(0.5),
fMaxPedDiff(1),
fMaxPedWidth(1.5),
fMaxNoTimeRate(10e-4),
fMaxNoFlagRate(10e-3),
fMaxBBVariation(0.1),
fMaxBGVariation(0.1),
fAsynchronBB(0.5),
fAsynchronBG(0.5)
{
//
// constructor
//
}
//_____________________________________________________________________________
AliADQAParam::~AliADQAParam()
{
//
// destructor
//
}
| 30.635294
| 79
| 0.637097
|
AllaMaevskaya
|
8a8fa5d0fc42b3a992a444ac8dcb44420a2cd8ac
| 20,359
|
cpp
|
C++
|
language-extensions/python/test/src/PythonExecuteTests.cpp
|
rabryst/sql-server-language-extensions
|
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
|
[
"MIT"
] | 82
|
2019-05-24T00:36:57.000Z
|
2022-02-21T23:51:46.000Z
|
language-extensions/python/test/src/PythonExecuteTests.cpp
|
rabryst/sql-server-language-extensions
|
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
|
[
"MIT"
] | 20
|
2019-07-05T06:12:28.000Z
|
2022-03-31T20:48:30.000Z
|
language-extensions/python/test/src/PythonExecuteTests.cpp
|
rabryst/sql-server-language-extensions
|
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
|
[
"MIT"
] | 35
|
2019-05-24T01:44:07.000Z
|
2022-02-28T13:29:44.000Z
|
//*************************************************************************************************
// Copyright (C) Microsoft Corporation.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
// @File: PythonExecuteTests.cpp
//
// Purpose:
// Tests the PythonExtension's implementation of the external language Execute API.
//
//*************************************************************************************************
#include <sstream>
#include "PythonExtensionApiTests.h"
#include "PythonTestUtilities.h"
using namespace std;
namespace bp = boost::python;
namespace ExtensionApiTest
{
// Name: ExecuteIntegerColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of Integer columns.
//
TEST_F(PythonExtensionApiTests, ExecuteIntegerColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_integerInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLINTEGER, SQL_C_SLONG>(m_integerInfo.get());
TestExecute<SQLINTEGER, SQL_C_SLONG>(
ColumnInfo<SQLINTEGER>::sm_rowsNumber,
(*m_integerInfo).m_dataSet.data(),
(*m_integerInfo).m_strLen_or_Ind.data(),
(*m_integerInfo).m_columnNames);
}
// Name: ExecuteBooleanColumnsTest
//
// Description:
// Test Execute using an InputDataSet of Boolean columns.
//
TEST_F(PythonExtensionApiTests, ExecuteBooleanColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_booleanInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLCHAR, SQL_C_BIT>(m_booleanInfo.get());
TestExecute<SQLCHAR, SQL_C_BIT>(
ColumnInfo<SQLCHAR>::sm_rowsNumber,
(*m_booleanInfo).m_dataSet.data(),
(*m_booleanInfo).m_strLen_or_Ind.data(),
(*m_booleanInfo).m_columnNames);
}
// Name: ExecuteRealColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of Real columns.
//
TEST_F(PythonExtensionApiTests, ExecuteRealColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_realInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLREAL, SQL_C_FLOAT>(m_realInfo.get());
TestExecute<SQLREAL, SQL_C_FLOAT>(
ColumnInfo<SQLREAL>::sm_rowsNumber,
(*m_realInfo).m_dataSet.data(),
(*m_realInfo).m_strLen_or_Ind.data(),
(*m_realInfo).m_columnNames);
}
// Name: ExecuteDoubleColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of Double columns.
//
TEST_F(PythonExtensionApiTests, ExecuteDoubleColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_doubleInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLDOUBLE, SQL_C_DOUBLE>(m_doubleInfo.get());
TestExecute<SQLDOUBLE, SQL_C_DOUBLE>(
ColumnInfo<SQLDOUBLE>::sm_rowsNumber,
(*m_doubleInfo).m_dataSet.data(),
(*m_doubleInfo).m_strLen_or_Ind.data(),
(*m_doubleInfo).m_columnNames);
}
// Name: ExecuteBigIntColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of BigInteger columns.
//
TEST_F(PythonExtensionApiTests, ExecuteBigIntColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_bigIntInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLBIGINT, SQL_C_SBIGINT>(m_bigIntInfo.get());
TestExecute<SQLBIGINT, SQL_C_SBIGINT>(
ColumnInfo<SQLBIGINT>::sm_rowsNumber,
(*m_bigIntInfo).m_dataSet.data(),
(*m_bigIntInfo).m_strLen_or_Ind.data(),
(*m_bigIntInfo).m_columnNames);
}
// Name: ExecuteSmallIntColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of SmallInt columns.
//
TEST_F(PythonExtensionApiTests, ExecuteSmallIntColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_smallIntInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLSMALLINT, SQL_C_SSHORT>(m_smallIntInfo.get());
TestExecute<SQLSMALLINT, SQL_C_SSHORT>(
ColumnInfo<SQLSMALLINT>::sm_rowsNumber,
(*m_smallIntInfo).m_dataSet.data(),
(*m_smallIntInfo).m_strLen_or_Ind.data(),
(*m_smallIntInfo).m_columnNames);
}
// Name: ExecuteTinyIntColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of TinyInt columns.
//
TEST_F(PythonExtensionApiTests, ExecuteTinyIntColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_tinyIntInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLCHAR, SQL_C_UTINYINT>(m_tinyIntInfo.get());
TestExecute<SQLCHAR, SQL_C_UTINYINT>(
ColumnInfo<SQLCHAR>::sm_rowsNumber,
(*m_tinyIntInfo).m_dataSet.data(),
(*m_tinyIntInfo).m_strLen_or_Ind.data(),
(*m_tinyIntInfo).m_columnNames);
}
// Name: ExecuteStringColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of string columns.
//
TEST_F(PythonExtensionApiTests, ExecuteStringColumnsTest)
{
SQLUSMALLINT inputSchemaColumnsNumber = 3;
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
inputSchemaColumnsNumber,
m_scriptString);
string stringColumn1Name = "StringColumn1";
InitializeColumn(0, stringColumn1Name, SQL_C_CHAR, m_CharSize);
string stringColumn2Name = "StringColumn2";
InitializeColumn(1, stringColumn2Name, SQL_C_CHAR, m_CharSize);
string stringColumn3Name = "StringColumn3";
InitializeColumn(2, stringColumn3Name, SQL_C_CHAR, m_CharSize);
vector<const char*> stringCol1{ "Hello", "test", "data", "World", "-123" };
vector<const char*> stringCol2{ "", 0, nullptr, "verify", "-1" };
vector<SQLINTEGER> strLenOrIndCol1 =
{ static_cast<SQLINTEGER>(strlen(stringCol1[0])),
static_cast<SQLINTEGER>(strlen(stringCol1[1])),
static_cast<SQLINTEGER>(strlen(stringCol1[2])),
static_cast<SQLINTEGER>(strlen(stringCol1[3])),
static_cast<SQLINTEGER>(strlen(stringCol1[4])) };
vector<SQLINTEGER> strLenOrIndCol2 =
{ 0, SQL_NULL_DATA, SQL_NULL_DATA,
static_cast<SQLINTEGER>(strlen(stringCol2[3])),
static_cast<SQLINTEGER>(strlen(stringCol2[4])) };
vector<SQLINTEGER*> strLen_or_Ind{ strLenOrIndCol1.data(),
strLenOrIndCol2.data(), nullptr };
// Coalesce the arrays of each row of each column
// into a contiguous array for each column.
//
vector<char> stringCol1Data = GenerateContiguousData<char>(stringCol1, strLenOrIndCol1.data());
vector<char> stringCol2Data = GenerateContiguousData<char>(stringCol2, strLenOrIndCol2.data());
void* dataSet[] = { stringCol1Data.data(),
stringCol2Data.data(),
nullptr };
int rowsNumber = stringCol1.size();
vector<string> columnNames{ stringColumn1Name, stringColumn2Name, stringColumn3Name };
TestExecute<SQLCHAR, SQL_C_CHAR>(
rowsNumber,
dataSet,
strLen_or_Ind.data(),
columnNames);
}
// Name: ExecuteWStringColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of wstring columns.
//
TEST_F(PythonExtensionApiTests, ExecuteWStringColumnsTest)
{
SQLUSMALLINT inputSchemaColumnsNumber = 3;
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
inputSchemaColumnsNumber,
m_scriptString);
string wstringColumn1Name = "WStringColumn1";
InitializeColumn(0, wstringColumn1Name, SQL_C_WCHAR, m_WCharSize);
string wstringColumn2Name = "WStringColumn2";
InitializeColumn(1, wstringColumn2Name, SQL_C_WCHAR, m_WCharSize);
string wstringColumn3Name = "WStringColumn3";
InitializeColumn(2, wstringColumn3Name, SQL_C_WCHAR, m_WCharSize);
vector<const wchar_t*> wstringCol1{ L"Hello", L"test", L"data", L"World", L"你好" };
vector<const wchar_t*> wstringCol2{ L"", 0, nullptr, L"verify", L"-1" };
vector<SQLINTEGER> strLenOrIndCol1 =
{ static_cast<SQLINTEGER>(5 * sizeof(wchar_t)),
static_cast<SQLINTEGER>(4 * sizeof(wchar_t)),
static_cast<SQLINTEGER>(4 * sizeof(wchar_t)),
static_cast<SQLINTEGER>(5 * sizeof(wchar_t)),
static_cast<SQLINTEGER>(2 * sizeof(wchar_t)) };
vector<SQLINTEGER> strLenOrIndCol2 =
{ 0, SQL_NULL_DATA, SQL_NULL_DATA,
static_cast<SQLINTEGER>(6 * sizeof(wchar_t)),
static_cast<SQLINTEGER>(2 * sizeof(wchar_t)) };
vector<SQLINTEGER*> strLen_or_Ind{ strLenOrIndCol1.data(),
strLenOrIndCol2.data(), nullptr };
// Coalesce the arrays of each row of each column
// into a contiguous array for each column.
//
vector<wchar_t> wstringCol1Data = GenerateContiguousData<wchar_t>(wstringCol1, strLenOrIndCol1.data());
vector<wchar_t> wstringCol2Data = GenerateContiguousData<wchar_t>(wstringCol2, strLenOrIndCol2.data());
void* dataSet[] = { wstringCol1Data.data(),
wstringCol2Data.data(),
nullptr };
int rowsNumber = wstringCol1.size();
vector<string> columnNames{ wstringColumn1Name, wstringColumn2Name, wstringColumn3Name };
TestExecute<wchar_t, SQL_C_WCHAR>(
rowsNumber,
dataSet,
strLen_or_Ind.data(),
columnNames);
}
// Name: ExecuteRawColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of binary columns.
//
TEST_F(PythonExtensionApiTests, ExecuteRawColumnsTest)
{
SQLUSMALLINT inputSchemaColumnsNumber = 3;
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
inputSchemaColumnsNumber,
m_scriptString);
const SQLCHAR BinaryValue1[] = { 0x01, 0x01, 0xe2, 0x40 };
const SQLCHAR BinaryValue2[] = { 0x04, 0x05, 0xe1 };
const SQLCHAR BinaryValue3[] = { 0x00, 0x00, 0x00, 0x01 };
const SQLCHAR BinaryValue4[] = { 0xff };
const SQLCHAR BinaryValue5[] = { 0x00 };
const SQLCHAR BinaryValue6[] = { 0xff, 0xff, 0xff, 0xff };
const SQLCHAR BinaryValue7[] = { 0x00, 0x12, 0xd2, 0xff, 0x00, 0x12, 0xd2, 0xff, 0x00, 0x12, 0xd2, 0xff };
string binaryColumn1Name = "BinaryColumn1";
InitializeColumn(0, binaryColumn1Name, SQL_C_BINARY, m_BinarySize);
string binaryColumn2Name = "BinaryColumn2";
InitializeColumn(1, binaryColumn2Name, SQL_C_BINARY, m_BinarySize);
string binaryColumn3Name = "BinaryColumn3";
InitializeColumn(2, binaryColumn3Name, SQL_C_BINARY, m_BinarySize);
vector<const SQLCHAR*> binaryCol1{ BinaryValue1, BinaryValue2, BinaryValue3, BinaryValue4 };
vector<const SQLCHAR*> binaryCol2{ BinaryValue5, BinaryValue6, nullptr, BinaryValue7};
SQLINTEGER strLenOrIndCol1[] =
{
static_cast<SQLINTEGER>(sizeof(BinaryValue1) / m_BinarySize),
static_cast<SQLINTEGER>(sizeof(BinaryValue2) / m_BinarySize),
static_cast<SQLINTEGER>(sizeof(BinaryValue3) / m_BinarySize),
static_cast<SQLINTEGER>(sizeof(BinaryValue4) / m_BinarySize)
};
SQLINTEGER strLenOrIndCol2[] =
{
SQL_NULL_DATA,
static_cast<SQLINTEGER>(sizeof(BinaryValue6) / m_BinarySize),
SQL_NULL_DATA,
static_cast<SQLINTEGER>(sizeof(BinaryValue7) / m_BinarySize)
};
vector<SQLINTEGER*> strLen_or_Ind{ strLenOrIndCol1, strLenOrIndCol2, nullptr };
// Coalesce the arrays of each row of each column
// into a contiguous array for each column.
//
int rowsNumber = binaryCol1.size();
vector<SQLCHAR> binaryCol1Data = GenerateContiguousData<SQLCHAR>(binaryCol1, strLenOrIndCol1);
vector<SQLCHAR> binaryCol2Data = GenerateContiguousData<SQLCHAR>(binaryCol2, strLenOrIndCol2);
void* dataSet[] = { binaryCol1Data.data(),
binaryCol2Data.data(),
nullptr };
vector<string> columnNames{ binaryColumn1Name, binaryColumn2Name, binaryColumn3Name };
TestExecute<SQLCHAR, SQL_C_BINARY>(
rowsNumber,
dataSet,
strLen_or_Ind.data(),
columnNames);
}
// Name: ExecuteDifferentColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of different column types.
//
TEST_F(PythonExtensionApiTests, ExecuteDifferentColumnsTest)
{
SQLUSMALLINT inputSchemaColumnsNumber = 3;
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
inputSchemaColumnsNumber,
m_scriptString);
string integerColumnName = "IntegerColumn";
InitializeColumn(0, integerColumnName, SQL_C_SLONG, m_IntSize);
string doubleColumnName = "DoubleColumn";
InitializeColumn(1, doubleColumnName, SQL_C_DOUBLE, m_DoubleSize);
string stringColumnName = "StringColumn";
InitializeColumn(2, stringColumnName, SQL_C_CHAR, m_CharSize);
vector<SQLINTEGER> intColData{ m_MaxInt, m_MinInt, 0, 1320, -1 };
vector<SQLDOUBLE> doubleColData{ m_MinDouble, 1.33, 83.98, 72.45, m_MaxDouble };
vector<const char*> stringCol{ "Hello", "test", "data", "World", "-123" };
SQLINTEGER strLenOrIndCol1[] = { 0, 0, SQL_NULL_DATA, SQL_NULL_DATA, 0 };
SQLINTEGER strLenOrIndCol3[] =
{ static_cast<SQLINTEGER>(strlen(stringCol[0])),
static_cast<SQLINTEGER>(strlen(stringCol[1])),
static_cast<SQLINTEGER>(strlen(stringCol[2])),
static_cast<SQLINTEGER>(strlen(stringCol[3])),
static_cast<SQLINTEGER>(strlen(stringCol[4])) };
vector<SQLINTEGER*> strLen_or_Ind{ strLenOrIndCol1, nullptr, strLenOrIndCol3 };
int rowsNumber = intColData.size();
vector<char> stringColData = GenerateContiguousData<char>(stringCol, strLenOrIndCol3);
vector<void *> dataSet{ intColData.data(), doubleColData.data(), stringColData.data() };
testing::internal::CaptureStdout();
SQLUSMALLINT outputschemaColumnsNumber = 0;
SQLRETURN result = Execute(
*m_sessionId,
m_taskId,
rowsNumber,
dataSet.data(),
strLen_or_Ind.data(),
&outputschemaColumnsNumber);
ASSERT_EQ(result, SQL_SUCCESS);
// Test print message was printed correctly
//
string output = testing::internal::GetCapturedStdout();
cout << output;
ASSERT_TRUE(output.find(m_printMessage) != string::npos);
try {
string createDictScript = m_inputDataNameString + ".to_dict()";
bp::dict inputDataSet = bp::extract<bp::dict>(bp::eval(createDictScript.c_str(), m_mainNamespace));
createDictScript = m_outputDataNameString + ".to_dict()";
bp::dict outputDataSet = bp::extract<bp::dict>(bp::eval(createDictScript.c_str(), m_mainNamespace));
for(bp::dict ds : {inputDataSet, outputDataSet})
{
bp::dict intColumn = bp::extract<bp::dict>(ds.get(integerColumnName));
CheckColumnEquality<SQLINTEGER>(
rowsNumber,
intColumn,
dataSet[0],
strLen_or_Ind[0]);
bp::dict numericColumn = bp::extract<bp::dict>(ds.get(doubleColumnName));
CheckColumnEquality<SQLDOUBLE>(
rowsNumber,
numericColumn,
dataSet[1],
strLen_or_Ind[1]);
bp::dict stringColumn = bp::extract<bp::dict>(ds.get(stringColumnName));
CheckStringColumnEquality(
rowsNumber,
stringColumn,
dataSet[2],
strLen_or_Ind[2]);
}
}
catch (bp::error_already_set &)
{
string pyError = PythonTestUtilities::ParsePythonException();
throw runtime_error("Error running python:\n" + pyError);
}
}
// Name: ExecuteDateTimeColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of DateTime columns.
//
TEST_F(PythonExtensionApiTests, ExecuteDateTimeColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_dateTimeInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQL_TIMESTAMP_STRUCT, SQL_C_TYPE_TIMESTAMP>(m_dateTimeInfo.get());
TestExecute<SQL_TIMESTAMP_STRUCT, SQL_C_TYPE_TIMESTAMP>(
ColumnInfo<SQL_TIMESTAMP_STRUCT>::sm_rowsNumber,
(*m_dateTimeInfo).m_dataSet.data(),
(*m_dateTimeInfo).m_strLen_or_Ind.data(),
(*m_dateTimeInfo).m_columnNames);
}
// Name: ExecuteDateColumnsTest
//
// Description:
// Test Execute with default script using an InputDataSet of Date columns.
//
TEST_F(PythonExtensionApiTests, ExecuteDateColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_dateInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQL_DATE_STRUCT, SQL_C_TYPE_DATE>(m_dateInfo.get());
TestExecute<SQL_DATE_STRUCT, SQL_C_TYPE_DATE>(
ColumnInfo<SQL_DATE_STRUCT>::sm_rowsNumber,
(*m_dateInfo).m_dataSet.data(),
(*m_dateInfo).m_strLen_or_Ind.data(),
(*m_dateInfo).m_columnNames);
}
// Name: TestExecute
//
// Description:
// Template function to Test Execute with default script that assigns Input to Output.
// It tests the correctness of the:
// 1. Executed script,
// 2. InputDataSet and
// 3. OutputDataSet
// This can also be run without the validation steps by setting "validate" to false.
//
template<class SQLType, SQLSMALLINT dataType>
void PythonExtensionApiTests::TestExecute(
SQLULEN rowsNumber,
void **dataSet,
SQLINTEGER **strLen_or_Ind,
vector<string> columnNames,
bool validate)
{
testing::internal::CaptureStdout();
SQLUSMALLINT outputschemaColumnsNumber = 0;
SQLRETURN result = Execute(
*m_sessionId,
m_taskId,
rowsNumber,
dataSet,
strLen_or_Ind,
&outputschemaColumnsNumber);
ASSERT_EQ(result, SQL_SUCCESS);
string output = testing::internal::GetCapturedStdout();
cout << output;
if (validate)
{
// Verify print message was printed correctly
//
ASSERT_TRUE(output.find(m_printMessage) != string::npos);
try {
string createDictScript = m_inputDataNameString + ".to_dict()";
bp::dict inputDataSet = bp::extract<bp::dict>(bp::eval(createDictScript.c_str(), m_mainNamespace));
createDictScript = m_outputDataNameString + ".to_dict()";
bp::dict outputDataSet = bp::extract<bp::dict>(bp::eval(createDictScript.c_str(), m_mainNamespace));
for (SQLUSMALLINT columnIndex = 0; columnIndex < columnNames.size(); columnIndex++)
{
bp::dict inputColumnToTest = bp::extract<bp::dict>(inputDataSet.get(columnNames[columnIndex]));
bp::dict outputColumnToTest = bp::extract<bp::dict>(outputDataSet.get(columnNames[columnIndex]));
for (bp::dict column : { inputColumnToTest, outputColumnToTest })
{
CheckColumnEqualityFnMap::const_iterator it = sm_FnCheckColumnEqualityMap.find(dataType);
if (it == sm_FnCheckColumnEqualityMap.end())
{
throw runtime_error("Unsupported column type encountered when testing column equality");
}
(this->*it->second)(
rowsNumber,
column,
dataSet[columnIndex],
strLen_or_Ind[columnIndex]);
}
}
}
catch (bp::error_already_set &)
{
string pyError = PythonTestUtilities::ParsePythonException();
throw runtime_error("Error running python:\n" + pyError);
}
}
}
}
| 33.37541
| 109
| 0.707599
|
rabryst
|
8a945dfae0f130f1327ae1476642b45a88b5c71a
| 597
|
hpp
|
C++
|
include/epiworld/location-bones.hpp
|
gvegayon/world-epi
|
197d8cc0e8fb86c06ec1ac2df6316e89d4857218
|
[
"MIT"
] | null | null | null |
include/epiworld/location-bones.hpp
|
gvegayon/world-epi
|
197d8cc0e8fb86c06ec1ac2df6316e89d4857218
|
[
"MIT"
] | null | null | null |
include/epiworld/location-bones.hpp
|
gvegayon/world-epi
|
197d8cc0e8fb86c06ec1ac2df6316e89d4857218
|
[
"MIT"
] | null | null | null |
#ifndef EPIWORLD_LOCATION_BONES_HPP
#define EPIWORLD_LOCATION_BONES_HPP
template<typename TSeq>
class Person;
template<typename TSeq>
class Location {
private:
int capacity;
std::string location_name;
int id;
std::vector< Person<TSeq> * >;
/**
* @brief Spatial location parameters
*
*/
///@{
epiworld_double longitude = 0.0;
epiworld_double latitude = 0.0;
epiworld_double altitude = 0.0;
///@}
public:
add_person(Person<TSeq> & p);
add_person(Person<TSeq> * p);
size_t count() const;
void reset();
};
#endif
| 15.710526
| 41
| 0.633166
|
gvegayon
|
8a9dba15b91951c2a56486d36a5d2695ef2f2944
| 244
|
cpp
|
C++
|
fillingdiamonds.cpp
|
AaryamanBhardwaj/Codeforces-Solutions
|
d33c75bfa493b16a3c1dfc67e52b578a40872199
|
[
"MIT"
] | 1
|
2021-04-29T20:06:55.000Z
|
2021-04-29T20:06:55.000Z
|
fillingdiamonds.cpp
|
AaryamanBhardwaj/Competitive-Programming-Solutions
|
d33c75bfa493b16a3c1dfc67e52b578a40872199
|
[
"MIT"
] | null | null | null |
fillingdiamonds.cpp
|
AaryamanBhardwaj/Competitive-Programming-Solutions
|
d33c75bfa493b16a3c1dfc67e52b578a40872199
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio;
cin.tie(NULL);
cout.tie(NULL);
int t,n;
cin>>t;
for(int i=0;i<t;i++)
{
cin>>n;
cout<<n<<endl;
}
}
| 16.266667
| 31
| 0.479508
|
AaryamanBhardwaj
|
8aa27cdb4afdade9c5a921ddd8fcc678afff5575
| 8,236
|
cpp
|
C++
|
src/Services/RenderService/DecoderRenderImageLoader.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 39
|
2016-04-21T03:25:26.000Z
|
2022-01-19T14:16:38.000Z
|
src/Services/RenderService/DecoderRenderImageLoader.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 23
|
2016-06-28T13:03:17.000Z
|
2022-02-02T10:11:54.000Z
|
src/Services/RenderService/DecoderRenderImageLoader.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 14
|
2016-06-22T20:45:37.000Z
|
2021-07-05T12:25:19.000Z
|
#include "DecoderRenderImageLoader.h"
#include "Interface/PrefetcherServiceInterface.h"
#include "Interface/CodecServiceInterface.h"
#include "Interface/MemoryServiceInterface.h"
#include "Kernel/Logger.h"
#include "Kernel/DocumentHelper.h"
#include "Kernel/FileStreamHelper.h"
#include "Kernel/Assertion.h"
#include "Kernel/AssertionMemoryPanic.h"
#include "Kernel/TextureHelper.h"
#include "Kernel/PixelFormatHelper.h"
#include "Kernel/DocumentableHelper.h"
#include "Kernel/FileGroupHelper.h"
#include "stdex/memorycopy.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
DecoderRenderImageLoader::DecoderRenderImageLoader()
: m_codecFlags( 0 )
{
}
//////////////////////////////////////////////////////////////////////////
DecoderRenderImageLoader::~DecoderRenderImageLoader()
{
}
//////////////////////////////////////////////////////////////////////////
bool DecoderRenderImageLoader::initialize( const FileGroupInterfacePtr & _fileGroup, const FilePath & _filePath, const ConstString & _codecType, uint32_t _codecFlags )
{
ImageDecoderInterfacePtr decoder;
if( PREFETCHER_SERVICE()
->getImageDecoder( _fileGroup, _filePath, &decoder ) == false )
{
decoder = this->createImageDecoder_( _fileGroup, _filePath, _codecType );
MENGINE_ASSERTION_MEMORY_PANIC( decoder, "invalid create decoder '%s' codec '%s' (doc: %s)"
, Helper::getFileGroupFullPath( _fileGroup, _filePath )
, _codecType.c_str()
, MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" )
);
}
else
{
if( decoder->rewind() == false )
{
LOGGER_ERROR( "invalid rewind decoder '%s' codec '%s' (doc: %s)"
, Helper::getFileGroupFullPath( _fileGroup, _filePath )
, _codecType.c_str()
, MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" )
);
return false;
}
}
m_decoder = decoder;
m_codecFlags = _codecFlags;
return true;
}
//////////////////////////////////////////////////////////////////////////
void DecoderRenderImageLoader::getImageDesc( RenderImageDesc * const _desc ) const
{
const ImageCodecDataInfo * dataInfo = m_decoder->getCodecDataInfo();
_desc->mipmaps = dataInfo->mipmaps;
_desc->width = dataInfo->width;
_desc->height = dataInfo->height;
_desc->format = dataInfo->format;
}
//////////////////////////////////////////////////////////////////////////
bool DecoderRenderImageLoader::load( const RenderImageInterfacePtr & _image ) const
{
uint32_t image_width = _image->getHWWidth();
uint32_t image_height = _image->getHWHeight();
uint32_t mipmap = 0;
Rect rect;
rect.left = 0;
rect.top = 0;
rect.right = image_width;
rect.bottom = image_height;
RenderImageLockedInterfacePtr locked = _image->lock( 0, rect, false );
size_t pitch = 0;
void * textureBuffer = locked->getBuffer( &pitch );
MENGINE_ASSERTION_MEMORY_PANIC( textureBuffer, "invalid lock mipmap %u rect %u:%u-%u:%u"
, 0
, rect.left
, rect.top
, rect.right
, rect.bottom
);
size_t mipmap_size = pitch * image_height;
EPixelFormat HWPixelFormat = _image->getHWPixelFormat();
ImageDecoderData data;
data.buffer = textureBuffer;
data.size = mipmap_size;
data.pitch = pitch;
data.format = HWPixelFormat;
data.mipmap = mipmap;
data.flags = m_codecFlags;
if( m_decoder->decode( &data ) == 0 )
{
LOGGER_ERROR( "invalid decode for" );
_image->unlock( locked, 0, false );
return false;
}
if( _image->getUpscalePow2() == true )
{
uint32_t mipmap_width = image_width >> mipmap;
uint32_t mipmap_height = image_height >> mipmap;
uint32_t pixel_size = Helper::getPixelFormatChannels( HWPixelFormat );
const ImageCodecDataInfo * dataInfo = m_decoder->getCodecDataInfo();
// copy pixels on the edge for better image quality
if( dataInfo->width != mipmap_width )
{
uint8_t * image_data = static_cast<uint8_t *>(textureBuffer);
for( uint32_t j = 0; j != dataInfo->height; ++j )
{
stdex::memorycopy( image_data, dataInfo->width * pixel_size, image_data + (dataInfo->width - 1) * pixel_size, pixel_size );
image_data += pitch;
}
}
if( dataInfo->height != mipmap_height )
{
uint8_t * image_data = static_cast<uint8_t *>(textureBuffer);
stdex::memorycopy( image_data, dataInfo->height * pitch, image_data + (dataInfo->height - 1) * pitch, dataInfo->width * pixel_size );
}
}
_image->unlock( locked, 0, true );
return true;
}
//////////////////////////////////////////////////////////////////////////
MemoryInterfacePtr DecoderRenderImageLoader::getMemory( uint32_t _codecFlags, const DocumentPtr & _doc ) const
{
MemoryBufferInterfacePtr memory = MEMORY_SERVICE()
->createMemoryBuffer( _doc );
MENGINE_ASSERTION_MEMORY_PANIC( memory );
const ImageCodecDataInfo * dataInfo = m_decoder->getCodecDataInfo();
uint32_t channels = Helper::getPixelFormatChannels( dataInfo->format );
size_t pitch = dataInfo->width * channels;
size_t dataSize = pitch * dataInfo->height;
void * buffer = memory->newBuffer( dataSize );
ImageDecoderData data;
data.buffer = buffer;
data.size = dataSize;
data.pitch = pitch;
data.format = dataInfo->format;
data.flags = _codecFlags;
data.mipmap = 0;
if( m_decoder->decode( &data ) == 0 )
{
LOGGER_ERROR( "invalid decode for" );
return nullptr;
}
return memory;
}
//////////////////////////////////////////////////////////////////////////
ImageDecoderInterfacePtr DecoderRenderImageLoader::createImageDecoder_( const FileGroupInterfacePtr & _fileGroup, const FilePath & _filePath, const ConstString & _codecType ) const
{
InputStreamInterfacePtr stream = Helper::openInputStreamFile( _fileGroup, _filePath, false, false, MENGINE_DOCUMENT_FACTORABLE );
MENGINE_ASSERTION_MEMORY_PANIC( stream, "invalid open stream '%s' codec '%s' (doc: %s)"
, Helper::getFileGroupFullPath( _fileGroup, _filePath )
, _codecType.c_str()
, MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" )
);
MENGINE_ASSERTION_FATAL( stream->size() != 0, "empty stream '%s' codec '%s' (doc: %s)"
, Helper::getFileGroupFullPath( _fileGroup, _filePath )
, _codecType.c_str()
, MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" )
);
ImageDecoderInterfacePtr decoder = CODEC_SERVICE()
->createDecoder( _codecType, MENGINE_DOCUMENT_FACTORABLE );
MENGINE_ASSERTION_MEMORY_PANIC( decoder, "invalid create decoder '%s' codec '%s' (doc: %s)"
, Helper::getFileGroupFullPath( _fileGroup, _filePath )
, _codecType.c_str()
, MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" )
);
if( decoder->prepareData( stream ) == false )
{
LOGGER_ERROR( "invalid prepare data '%s' codec '%s' (doc: %s)"
, Helper::getFileGroupFullPath( _fileGroup, _filePath )
, _codecType.c_str()
, MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" )
);
return nullptr;
}
return decoder;
}
//////////////////////////////////////////////////////////////////////////
}
| 35.65368
| 184
| 0.559131
|
irov
|
8aac52f4140b0956ea099c9c6df0d59fb4333113
| 7,572
|
hpp
|
C++
|
include/MAS.hpp
|
arqueffe/cmapf-solver
|
30f38f72ae278bdc6ca5cc6efc8cd53dbf13f119
|
[
"MIT"
] | null | null | null |
include/MAS.hpp
|
arqueffe/cmapf-solver
|
30f38f72ae278bdc6ca5cc6efc8cd53dbf13f119
|
[
"MIT"
] | 1
|
2021-07-29T15:13:42.000Z
|
2021-07-29T15:13:42.000Z
|
include/MAS.hpp
|
arqueffe/cmapf-solver
|
30f38f72ae278bdc6ca5cc6efc8cd53dbf13f119
|
[
"MIT"
] | null | null | null |
/* Copyright (c) 2021 Arthur Queffelec
*
* 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.
*/
#pragma once
#include <map>
#include <stack>
#include <limits>
#include <vector>
#include <set>
#include <memory>
#include <utility>
#include <Solver.hpp>
#include <LowLevel.hpp>
namespace decoupled {
template <class GraphMove, class GraphComm>
class MAS : public Solver<GraphMove, GraphComm> {
private:
std::map<std::pair<Node, size_t>, float> pheromone_map_;
decoupled::low_level::NegativeAStar<GraphMove, GraphComm> astar;
float evaporation_ = 0.8f;
int max_iteration_ = 200;
public:
MAS(const Instance<GraphMove, GraphComm>& instance, const Objective& objective)
: Solver<GraphMove, GraphComm>(instance, objective), astar(this->instance_) {
Execution exec;
for (Agent agt = 0; agt < static_cast<Agent>(this->instance_.nb_agents()); agt++) {
Path p = astar.ComputeShortestPath(this->instance_.start()[agt], this->instance_.goal()[agt]);
exec.PushBack(std::make_shared<const Path>(p));
}
this->execution_ = exec;
UpdatePheromoneMap(exec);
}
void UpdatePheromoneMap(const Execution& exec) {
std::map<std::pair<Node, size_t>, int> count_map;
for (Agent i = 0; i < static_cast<Agent>(this->instance_.nb_agents()); i++) {
auto path_i = exec.get_path(i);
for (size_t time = 0; time < path_i->size(); time++) {
Node pos_i = path_i->GetAtTimeOrLast(time);
const std::set<Node>& neighbors = this->instance_.graph().communication().get_neighbors(pos_i);
for (Node n : neighbors) {
auto found = count_map.find(std::make_pair(n, time));
if (found != count_map.end())
found->second++;
else
count_map.insert(std::make_pair(std::make_pair(n, time), 1));
}
}
}
// Evaporate
for (auto& pair : pheromone_map_) {
pair.second = (1 - evaporation_) * pair.second;
}
// Lay now pheromones
for (auto& pair : count_map) {
auto found = pheromone_map_.find(pair.first);
if (found != pheromone_map_.end())
found->second += pair.second;
else
pheromone_map_.insert(std::make_pair(pair.first, static_cast<float>(pair.second)));
}
}
Node SelectStep(Agent agt, Node current, size_t time) {
size_t good_strategy = (size_t)rand() % 2;
const std::set<Node>& neighbors = this->instance_.graph().movement().get_neighbors(current);
if (good_strategy == 0) {
double choice = static_cast<double>(rand() / std::numeric_limits<int>::max());
float sum_pheromone = 0.0f;
for (auto n : neighbors) {
auto found = pheromone_map_.find(std::make_pair(n, time));
if (found != pheromone_map_.end())
sum_pheromone += found->second *
(1 / (this->instance_.graph().movement().get_distance(n, this->instance_.goal()[agt]) + 1));
}
float current_pheromone = 0.0f;
for (auto n : neighbors) {
auto found = pheromone_map_.find(std::make_pair(n, time));
float pheromone_value = current_pheromone;
if (found != pheromone_map_.end())
pheromone_value +=
found->second *
(1 / (this->instance_.graph().movement().get_distance(n, this->instance_.goal()[agt]) + 1)) /
sum_pheromone;
if (choice <= pheromone_value) return n;
current_pheromone = pheromone_value;
}
} else {
Path p = astar.ComputeShortestPath(current, this->instance_.goal()[agt]);
return p[1];
}
// No pheromone pick random
size_t random_strategy = (size_t)rand() % 2;
if (random_strategy == 0) {
Node min_node = std::numeric_limits<Node>::max();
size_t min_dist = std::numeric_limits<size_t>::max();
for (auto n : neighbors) {
size_t current_dist = this->instance_.graph().movement().get_distance(n, this->instance_.goal()[agt]);
if (current_dist < min_dist) {
min_dist = current_dist;
min_node = n;
}
}
if (min_node == std::numeric_limits<Node>::max()) throw "Potential error of node selection";
return min_node;
} else {
size_t default_choice = (size_t)rand() % neighbors.size();
auto it = neighbors.begin();
std::advance(it, default_choice);
return *it;
}
}
size_t CountDisconnection(const Execution& exec) {
size_t count = 0;
size_t exec_max_size = 0;
for (Agent agt = 0; agt < static_cast<Agent>(this->instance_.nb_agents()); agt++)
if (exec_max_size < exec.get_path(agt)->size()) exec_max_size = exec.get_path(agt)->size();
for (size_t time = 0; time < exec_max_size; time++) {
size_t agent_count = 0;
std::stack<Agent> agent_stack;
std::vector<bool> agent_treated = std::vector<bool>(this->instance_.nb_agents(), false);
agent_stack.push(0);
while (!agent_stack.empty()) {
Agent a = agent_stack.top();
agent_stack.pop();
if (agent_treated[a]) continue;
agent_treated[a] = true;
agent_count++;
Node aPos = exec.get_path(a)->GetAtTimeOrLast(time);
for (Agent b = 0; b < static_cast<Agent>(this->instance_.nb_agents()); ++b) {
if (a != b && !agent_treated[b]) {
Node bPos = exec.get_path(b)->GetAtTimeOrLast(b);
const std::set<Node>& neighbors = this->instance_.graph().communication().get_neighbors(aPos);
if (neighbors.find(bPos) != neighbors.end()) {
agent_stack.push(b);
}
}
}
}
if (agent_count != this->instance_.nb_agents()) count++;
}
return count;
}
bool StepCompute() override {
Execution exec;
size_t previous_disc = CountDisconnection(this->execution_);
if (previous_disc == 0) return true;
for (Agent agt = 0; agt < static_cast<Agent>(this->instance_.nb_agents()); agt++) {
Path path_agt;
path_agt.PushBack(this->instance_.start()[agt]);
while (path_agt[path_agt.size() - 1] != this->instance_.goal()[agt]) {
Node next_node = SelectStep(agt, path_agt[path_agt.size() - 1], path_agt.size());
path_agt.PushBack(next_node);
}
exec.PushBack(std::make_shared<const Path>(path_agt));
}
if (this->objective_.cost(exec) < this->objective_.cost(this->execution_) ||
CountDisconnection(exec) < previous_disc) {
std::cout << "Iteration: " << max_iteration_ << std::endl;
std::cout << "Execution Size: " << this->objective_.cost(exec) << std::endl;
std::cout << "Disconnection Count: " << CountDisconnection(exec) << std::endl;
this->execution_ = exec;
}
UpdatePheromoneMap(exec);
max_iteration_--;
if (max_iteration_ == 0) return true;
return false;
}
};
} // namespace decoupled
| 37.86
| 120
| 0.612388
|
arqueffe
|
8aad8ca5d1849658a70c74ae1cc57250cc6efad7
| 3,350
|
cpp
|
C++
|
test/unit/testEkf.cpp
|
tmcg0/bioslam
|
d59f07733cb3a9a1de8e6dea4b1fb745d706da09
|
[
"MIT"
] | 6
|
2021-01-26T19:31:46.000Z
|
2022-03-10T15:33:49.000Z
|
test/unit/testEkf.cpp
|
tmcg0/bioslam
|
d59f07733cb3a9a1de8e6dea4b1fb745d706da09
|
[
"MIT"
] | 8
|
2021-01-26T16:12:22.000Z
|
2021-08-12T18:39:36.000Z
|
test/unit/testEkf.cpp
|
tmcg0/bioslam
|
d59f07733cb3a9a1de8e6dea4b1fb745d706da09
|
[
"MIT"
] | 1
|
2021-05-02T18:47:42.000Z
|
2021-05-02T18:47:42.000Z
|
// -------------------------------------------------------------------- //
// (c) Copyright 2021 Massachusetts Institute of Technology //
// Author: Tim McGrath //
// All rights reserved. See LICENSE file for license information. //
// -------------------------------------------------------------------- //
// testing of EKF implementations against APDM manufacturer UKF for the Opal v2
#include "imuPoseEstimator.h"
#include "VarStrToCharMap.h"
#include "testutils.h"
#include "mathutils.h"
int main(){
// --- settings --- //
double tolDeg=5.0;
// ---------------- //
// setup stuff
VarStrToCharMap::clear();
//std::string dataFileToUse=testutils::getTestDataFile("20170719-113432-Y13_TUG_13.h5");
std::string dataFileToUse=testutils::getTestDataFile("20170411-154746-Y1_TUG_6.h5");
std::map<std::string,imu> ImuMap=imu::getImuMapFromDataFile(dataFileToUse);
// imu::printLabelsInFile(dataFileToUse);
std::string imuLabel="Right Thigh";
imu testImu=ImuMap[imuLabel];
testutils::runtime_assert(testImu.length()>0);
std::cout<<"test imu contains "<<testImu.length()<<" measurements ("<<testImu.relTimeSec[testImu.length()-1]<<" seconds)"<<std::endl;
imuPoseEstimator poseProblem(testImu, "unitTest");
// get APDM orientatioon
std::vector<gtsam::Rot3> rAPDM=gtsamutils::imuOrientation(testImu); // get APDM orientation as a gtsam::Rot3 set
// remember that APDM orientation and my EKF is [N->B]
// get orientation according to EKF
Eigen::MatrixXd q_B_to_N=mathutils::simpleImuOrientationForwardBackwardEkfWrapper(gtsamutils::gyroMatrix(poseProblem.m_imu), gtsamutils::accelMatrix(poseProblem.m_imu), poseProblem.m_imu.getDeltaT(), 4);
std::vector<gtsam::Rot3> rEKF(q_B_to_N.rows()), rRel(q_B_to_N.rows());
std::vector<double> yawSqErr(rAPDM.size()), pitchSqErr(rAPDM.size()), rollSqErr(rAPDM.size());
for(uint k=0;k<q_B_to_N.rows();k++){
// convert into a vector of rot3
rEKF[k]=gtsam::Rot3(q_B_to_N(k,0),q_B_to_N(k,1),q_B_to_N(k,2),q_B_to_N(k,3));
rRel[k]=rAPDM[k]*rEKF[k].inverse(); // R[EKF->APDM]=R[N->APDM]*R[N->EKF]'
//std::cout<<"relative orientation ["<<k<<"] rpy()="<<rRel[k].rpy().transpose()<<std::endl;
gtsam::Vector3 rpyErr=rRel[k].rpy();
yawSqErr[k]=pow(rpyErr[2],2);
pitchSqErr[k]=pow(rpyErr[1],2);
rollSqErr[k]=pow(rpyErr[0],2);
}
// now compute RMSEs
double yawRMSE = sqrt((std::accumulate(yawSqErr.begin(), yawSqErr.end(), 0.0))/yawSqErr.size());
double pitchRMSE = sqrt((std::accumulate(pitchSqErr.begin(), pitchSqErr.end(), 0.0))/pitchSqErr.size());
double rollRMSE = sqrt((std::accumulate(rollSqErr.begin(), rollSqErr.end(), 0.0))/rollSqErr.size());
std::cout<<"[roll, pitch, yaw] RMSE = ["<<rollRMSE<<", "<<pitchRMSE<<", "<<yawRMSE<<"]"<<std::endl;
// assess if these errors are good enough
if(pitchRMSE*180.0/M_PI>tolDeg){
std::cerr<<"error: pitch rmse ("<<pitchRMSE*180.0/M_PI<<" deg) greater than tolerance ("<<tolDeg<<" deg)"<<std::endl;
return 1;
}
if(rollRMSE*180.0/M_PI>tolDeg){
std::cerr<<"error: roll rmse ("<<rollRMSE*180.0/M_PI<<" deg) greater than tolerance ("<<tolDeg<<" deg)"<<std::endl;
return 1;
}
return 0;
}
| 53.174603
| 207
| 0.61791
|
tmcg0
|
8aae41844ee5e21fe31f4a1c2e2131d05b24499d
| 4,686
|
cpp
|
C++
|
shaders/src/sib_color_hls_adjust.cpp
|
caron/sitoa
|
52a0a4b35f51bccb6223a8206d04b40edc80071c
|
[
"Apache-2.0"
] | 34
|
2018-02-01T16:13:48.000Z
|
2021-07-16T07:37:47.000Z
|
shaders/src/sib_color_hls_adjust.cpp
|
625002974/sitoa
|
46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589
|
[
"Apache-2.0"
] | 72
|
2018-02-16T17:30:41.000Z
|
2021-11-22T11:41:45.000Z
|
shaders/src/sib_color_hls_adjust.cpp
|
625002974/sitoa
|
46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589
|
[
"Apache-2.0"
] | 15
|
2018-02-15T15:36:58.000Z
|
2021-04-14T03:54:25.000Z
|
/************************************************************************************************************************************
Copyright 2017 Autodesk, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
************************************************************************************************************************************/
#include "color_utils.h"
AI_SHADER_NODE_EXPORT_METHODS(SIBColorHLSAdjustMethods);
enum SIBColorHLSAdjustParams
{
p_color,
p_master_h,
p_master_l,
p_master_s,
p_red_h,
p_red_l,
p_red_s,
p_green_h,
p_green_l,
p_green_s,
p_blue_h,
p_blue_l,
p_blue_s,
p_cyan_h,
p_cyan_l,
p_cyan_s,
p_yellow_h,
p_yellow_l,
p_yellow_s,
p_magenta_h,
p_magenta_l,
p_magenta_s
};
node_parameters
{
AiParameterRGBA( "color" , 1.0f , 1.0f , 1.0f, 1.0f );
AiParameterFlt ( "master_h" , 0.0f );
AiParameterFlt ( "master_l" , 0.0f );
AiParameterFlt ( "master_s" , 0.0f );
AiParameterFlt ( "red_h" , 0.0f );
AiParameterFlt ( "red_l" , 0.0f );
AiParameterFlt ( "red_s" , 0.0f );
AiParameterFlt ( "green_h" , 0.0f );
AiParameterFlt ( "green_l" , 0.0f );
AiParameterFlt ( "green_s" , 0.0f );
AiParameterFlt ( "blue_h" , 0.0f );
AiParameterFlt ( "blue_l" , 0.0f );
AiParameterFlt ( "blue_s" , 0.0f );
AiParameterFlt ( "cyan_h" , 0.0f );
AiParameterFlt ( "cyan_l" , 0.0f );
AiParameterFlt ( "cyan_s" , 0.0f );
AiParameterFlt ( "yellow_h" , 0.0f );
AiParameterFlt ( "yellow_l" , 0.0f );
AiParameterFlt ( "yellow_s" , 0.0f );
AiParameterFlt ( "magenta_h", 0.0f );
AiParameterFlt ( "magenta_l", 0.0f );
AiParameterFlt ( "magenta_s", 0.0f );
}
namespace {
typedef struct
{
float master_h;
float master_l;
float master_s;
float red_h;
float red_l;
float red_s;
float green_h;
float green_l;
float green_s;
float blue_h;
float blue_l;
float blue_s;
float cyan_h;
float cyan_l;
float cyan_s;
float yellow_h;
float yellow_l;
float yellow_s;
float magenta_h;
float magenta_l;
float magenta_s;
} ShaderData;
}
node_initialize
{
AiNodeSetLocalData(node, AiMalloc(sizeof(ShaderData)));
}
node_update
{
ShaderData* data = (ShaderData*)AiNodeGetLocalData(node);
data->master_h = AiNodeGetFlt(node, "master_h");
data->master_l = AiNodeGetFlt(node, "master_l");
data->master_s = AiNodeGetFlt(node, "master_s");
data->red_h = AiNodeGetFlt(node, "red_h");
data->red_l = AiNodeGetFlt(node, "red_l");
data->red_s = AiNodeGetFlt(node, "red_s");
data->green_h = AiNodeGetFlt(node, "green_h");
data->green_l = AiNodeGetFlt(node, "green_l");
data->green_s = AiNodeGetFlt(node, "green_s");
data->blue_h = AiNodeGetFlt(node, "blue_h");
data->blue_l = AiNodeGetFlt(node, "blue_l");
data->blue_s = AiNodeGetFlt(node, "blue_s");
data->cyan_h = AiNodeGetFlt(node, "cyan_h");
data->cyan_l = AiNodeGetFlt(node, "cyan_l");
data->cyan_s = AiNodeGetFlt(node, "cyan_s");
data->yellow_h = AiNodeGetFlt(node, "yellow_h");
data->yellow_l = AiNodeGetFlt(node, "yellow_l");
data->yellow_s = AiNodeGetFlt(node, "yellow_s");
data->magenta_h = AiNodeGetFlt(node, "magenta_h");
data->magenta_l = AiNodeGetFlt(node, "magenta_l");
data->magenta_s = AiNodeGetFlt(node, "magenta_s");
}
node_finish
{
AiFree(AiNodeGetLocalData(node));
}
shader_evaluate
{
ShaderData* data = (ShaderData*)AiNodeGetLocalData(node);
AtRGBA result = AiShaderEvalParamRGBA(p_color);
// r3D February 16 2011 This shader is not finished!
// HLS Corrections
if (data->master_h!=0.0f || data->master_s!=0.0f || data->master_l!=0.0f)
{
AtRGBA hls = RGBAtoHLS(result);
// H
hls.r += (hls.r*360.0f) + data->master_h;
hls.r /= 360.0f;
// L
hls.b += (hls.b*200.0f) + data->master_s;
hls.b /= 200.0f;
hls.b = AiClamp(hls.b, 0.0f ,1.0f);
// S
hls.g += (hls.g*200.0f) + data->master_l;
hls.g /= 200.0f;
hls.g = AiClamp(hls.g, 0.0f, 1.0f);
result = HLStoRGBA(hls);
}
sg->out.RGBA() = result;
}
| 28.748466
| 134
| 0.611182
|
caron
|
8ab23b0cdc6b4efac8499f43265a76b33cf15f04
| 4,638
|
cpp
|
C++
|
SGPLibraryCode/modules/sgp_core/common/sgp_Colour.cpp
|
phoenixzz/VoronoiMapGen
|
5afd852f8bb0212baba9d849178eb135f62df903
|
[
"MIT"
] | 11
|
2017-03-03T03:31:15.000Z
|
2019-03-01T17:09:12.000Z
|
SGPLibraryCode/modules/sgp_core/common/sgp_Colour.cpp
|
phoenixzz/VoronoiMapGen
|
5afd852f8bb0212baba9d849178eb135f62df903
|
[
"MIT"
] | null | null | null |
SGPLibraryCode/modules/sgp_core/common/sgp_Colour.cpp
|
phoenixzz/VoronoiMapGen
|
5afd852f8bb0212baba9d849178eb135f62df903
|
[
"MIT"
] | 2
|
2017-03-03T03:31:17.000Z
|
2021-05-27T21:50:43.000Z
|
namespace ColourHelpers
{
static uint8 floatToUInt8 (const float n) noexcept
{
return n <= 0.0f ? 0 : (n >= 1.0f ? 255 : (uint8) (n * 255.0f));
}
}
Colour BLACKCOLOR(0,0,0);
Colour WHITECOLOR(255,255,255);
Colour REDCOLOR(255,0,0);
Colour GREENCOLOR(0,255,0);
Colour BLUECOLOR(0,0,255);
//==============================================================================
Colour::Colour() noexcept
: red(0), green(0), blue(0), alpha(0)
{
}
Colour::Colour (const Colour& other) noexcept
: red(other.red), green(other.green), blue(other.blue), alpha(other.alpha)
{
}
Colour& Colour::operator= (const Colour& other) noexcept
{
red = other.red;
green = other.green;
blue = other.blue;
alpha = other.alpha;
return *this;
}
bool Colour::operator== (const Colour& other) const noexcept
{
return (red == other.red) && (green == other.green) && (blue == other.blue) &&
(alpha == other.alpha);
}
bool Colour::operator!= (const Colour& other) const noexcept
{
return (red != other.red) || (green != other.green) || (blue != other.blue) ||
(alpha != other.alpha);
}
//==============================================================================
Colour::Colour (const uint32 _argb) noexcept
{
alpha = uint8((_argb & 0xFF000000) >> 24);
red = uint8((_argb & 0x00FF0000) >> 16);
green = uint8((_argb & 0x0000FF00) >> 8);
blue = uint8(_argb & 0x000000FF);
}
Colour::Colour (const uint8 _red, const uint8 _green, const uint8 _blue) noexcept
{
alpha = 0xff;
red = _red;
green = _green;
blue = _blue;
}
Colour Colour::fromRGB (const uint8 _red, const uint8 _green, const uint8 _blue) noexcept
{
return Colour (_red, _green, _blue);
}
Colour::Colour (const uint8 _red, const uint8 _green, const uint8 _blue, const uint8 _alpha) noexcept
{
red = _red;
green = _green;
blue = _blue;
alpha = _alpha;
}
Colour Colour::fromRGBA (const uint8 _red, const uint8 _green, const uint8 _blue, const uint8 _alpha) noexcept
{
return Colour (_red, _green, _blue, _alpha);
}
Colour::Colour (const uint8 _red, const uint8 _green, const uint8 _blue, const float _alpha) noexcept
{
alpha = ColourHelpers::floatToUInt8 (_alpha);
red = _red;
green = _green;
blue = _blue;
}
Colour Colour::fromFloatRGBA (const float _red, const float _green, const float _blue, const float _alpha) noexcept
{
return Colour (ColourHelpers::floatToUInt8 (_red), ColourHelpers::floatToUInt8 (_green), ColourHelpers::floatToUInt8 (_blue), _alpha);
}
Colour::~Colour() noexcept
{
}
float Colour::getFloatRed() const noexcept { return getRed() / 255.0f; }
float Colour::getFloatGreen() const noexcept { return getGreen() / 255.0f; }
float Colour::getFloatBlue() const noexcept { return getBlue() / 255.0f; }
float Colour::getFloatAlpha() const noexcept { return getAlpha() / 255.0f; }
uint32 Colour::getARGB() const noexcept
{
return uint32((alpha << 24) | (red << 16) | (green << 8) | blue);
}
uint32 Colour::getRGBA() const noexcept
{
return uint32((red << 24) | (green << 16) | (blue << 8) | alpha);
}
//==============================================================================
bool Colour::isTransparent() const noexcept
{
return getAlpha() == 0;
}
bool Colour::isOpaque() const noexcept
{
return getAlpha() == 0xff;
}
void Colour::setAlpha (const uint8 newAlpha) noexcept
{
alpha = newAlpha;
}
void Colour::setAlpha (const float newAlpha) noexcept
{
jassert (newAlpha >= 0 && newAlpha <= 1.0f);
alpha = ColourHelpers::floatToUInt8 (newAlpha);
}
//==============================================================================
Colour Colour::greyLevel (const float brightness) noexcept
{
const uint8 level = ColourHelpers::floatToUInt8 (brightness);
return Colour (level, level, level);
}
//==============================================================================
String Colour::toString() const
{
return String::toHexString ((int)getARGB());
}
Colour Colour::fromString (const String& encodedColourString)
{
return Colour ((uint32) encodedColourString.getHexValue32());
}
String Colour::toDisplayStringRGBA (const bool includeAlphaValue) const
{
return String::toHexString ((int) (getRGBA() & (includeAlphaValue ? 0xffffffff : 0xffffff00)))
.dropLastCharacters ( includeAlphaValue ? 0 : 2)
.toUpperCase();
}
String Colour::toDisplayStringARGB (const bool includeAlphaValue) const
{
return String::toHexString ((int) (getARGB() & (includeAlphaValue ? 0xffffffff : 0x00ffffff)))
.paddedLeft ('0', includeAlphaValue ? 8 : 6)
.toUpperCase();
}
| 28.109091
| 138
| 0.614489
|
phoenixzz
|
8ab4082a9063f74963159b25e5eb8dd16bab086c
| 21,375
|
hpp
|
C++
|
Nostra Utils/src/header/nostrautils/core/StdIncludes.hpp
|
Lehks/NostraUtils
|
ef1b2d492a1358775752a2a7621c714d86bf96b2
|
[
"MIT"
] | 10
|
2018-01-07T01:00:11.000Z
|
2021-09-16T14:08:45.000Z
|
NostraUtils/Nostra Utils/src/header/nostrautils/core/StdIncludes.hpp
|
Lehks/NostraEngine
|
0d610dcd97ba482fd8f183795140c38728c3a6b3
|
[
"MIT"
] | 107
|
2018-04-06T10:15:47.000Z
|
2018-09-28T07:13:46.000Z
|
NostraUtils/Nostra Utils/src/header/nostrautils/core/StdIncludes.hpp
|
Lehks/NostraEngine
|
0d610dcd97ba482fd8f183795140c38728c3a6b3
|
[
"MIT"
] | null | null | null |
#ifndef NOU_CORE_STD_INCLUDES_HPP
#define NOU_CORE_STD_INCLUDES_HPP
#include <cstddef>
#include <cstdint>
#include <type_traits>
#if __has_include("Config.hpp")
#include "Config.hpp"
#endif
/**
\file core/StdIncludes.hpp
\author Lukas Reichmann
\version 1.0.1
\since 1.0.0
\brief A file that should be included in all other header files of NOU. This provides, along other things, the
namespace macros and the primitive types.
*/
/**
\brief The name of the main namespace of NOU. All components of NOU are nested in sub-namespaces of this
namespace.
*/
#ifndef NOU
#define NOU nostra::utils
#endif
/**
\brief The name of the namespace that contains all core-components of NOU.
*/
#ifndef NOU_CORE
#define NOU_CORE core
#endif
/**
\brief The name of the namespace that contains all components that are related to data structures and/or
algorithms.
*/
#ifndef NOU_DAT_ALG
#define NOU_DAT_ALG dat_alg
#endif
/**
\brief The name of the namespace that contains all components that are related to file management.
*/
#ifndef NOU_FILE_MNGT
#define NOU_FILE_MNGT file_mngt
#endif
/**
\brief The name of the namespace that contains all components that are related to math.
*/
#ifndef NOU_MATH
#define NOU_MATH math
#endif
/**
\brief The name of the namespace that contains all components that are related to memory management.
*/
#ifndef NOU_MEM_MNGT
#define NOU_MEM_MNGT mem_mngt
#endif
/**
\brief The name of the namespace that contains all components that are related to threading.
*/
#ifndef NOU_THREAD
#define NOU_THREAD thread
#endif
/**
\brief The operating system identifier for Microsoft Windows.
\details
The operating system identifier for Microsoft Windows. This macro is always defined, to check if the current
operating system is Windows, use
\code{.cpp}
#if NOU_OS == NOU_OS_WINDOWS
\endcode
*/
#ifndef NOU_OS_WINDOWS
#define NOU_OS_WINDOWS 0
#endif
/**
\brief The operating system identifier for Linux.
\details
The operating system identifier for Linux. This macro is always defined, to check if the current operating
system is Linux, use
\code{.cpp}
#if NOU_OS == NOU_OS_LINUX
\endcode
*/
#ifndef NOU_OS_LINUX
#define NOU_OS_LINUX 1
#endif
/**
\brief The operating system identifier for Unix.
\details
The operating system identifier for Unix. This macro is always defined, to check if the current operating
system is Unix, use
\code{.cpp}
#if NOU_OS == NOU_OS_UNIX
\endcode
*/
#ifndef NOU_OS_UNIX
#define NOU_OS_UNIX 2
#endif
/**
\brief The operating system identifier for Macintosh.
\details
The operating system identifier for Apple Macintosh. This macro is always defined, to check if the current
operating system is Macintosh, use
\code{.cpp}
#if NOU_OS == NOU_OS_MAC
\endcode
*/
#ifndef NOU_OS_MAC
#define NOU_OS_MAC 2
#endif
/**
\brief The operating system identifier for an unknown system.
\details
The operating system identifier for an unknown system. This macro is always defined, to check if the current
operating system is unknown, use
\code{.cpp}
#if NOU_OS == NOU_OS_UNKNOWN
\endcode
An unknown operating system does not cause an error per-se, however, it may cause major problems (e.g. the
value for NOU_OS_LIBRARY will not be set properly).
*/
#ifndef NOU_OS_UNKNOWN
#define NOU_OS_UNKNOWN 3
#endif
/**
\brief The operating system identifier for the Doxygen documentation.
\details
The operating system identifier for an Doxygen documentation. This macro is always defined, but it does not
serve any purpose when using the library. In the documentation files NOU_OS will be defined as this
identifier.
*/
#ifndef NOU_OS_DOXYGEN
#define NOU_OS_DOXYGEN 4
#endif
/**
\brief Defined as the identifier of the current operating system.
\details
This macro is defined as the identifier of the current operating system. To check for a certain operating
system, use
\code{.cpp}
#if NOU_OS == NOU_OS_*
\endcode
and replace * with the os name.
If the current os is unknown, the value will be NOU_OS_UNKNOWN.
An unknown operating system does not cause an error per se, however, it may cause major problems (e.g. the
value for NOU_OS_LIBRARY will not be set properly).
*/
#ifndef NOU_OS
# ifdef _WIN32
# define NOU_OS NOU_OS_WINDOWS
# elif defined __linux__
# define NOU_OS NOU_OS_LINUX
# elif defined __unix__
# define NOU_OS NOU_OS_UNIX
# elif defined __APPLE__
# define NOU_OS NOU_OS_MAC
# elif defined __DOXYGEN__ //__DOXYGEN__ is defined in the Doxyfile
# define NOU_OS NOU_OS_DOXYGEN
# else
# define NOU_OS NOU_OS_UNKNOWN
# endif
#endif
/**
\brief This macro should be defined by a user if the library is used as a dynamically linked library
(<tt>.dll</tt>) on MS Windows.
\details
For optimization purposes, functions that will be imported from a DLL should be marked with
<tt>__declspec(dllimport)</tt> on MS Windows when using the Visual C++ compiler. If this macro is defined, all
symbols that were exported into a DLL will be marked for import.
\note
This macro will never be defined on itself, this must always be done by a user before any of NOU files are
included.
*/
#ifndef NOU_DLL
# if NOU_OS == NOU_OS_DOXYGEN //Define NOU_DLL to make it appear in the doc
# define NOU_DLL
# else
//Do not define
# endif
#endif
/**
\brief The library system identifier for the Windows.h.
\details
The library system identifier for the Windows.h. This macro is always defined, to check if the current
operating system supports the Windows.h, use
\code{.cpp}
#if NOU_OS_LIBRARY == NOU_OS_LIBRARY_WIN_H
\endcode
*/
#ifndef NOU_OS_LIBRARY_WIN_H
#define NOU_OS_LIBRARY_WIN_H 0
#endif
/**
\brief The library system identifier for a the POSIX library.
\details
The library system identifier for a the POSIX library. This macro is always defined, to check if the current
operating system supports the POSIX library, use
\code{.cpp}
#if NOU_OS_LIBRARY == NOU_OS_LIBRARY_POSIX
\endcode
*/
#ifndef NOU_OS_LIBRARY_POSIX
#define NOU_OS_LIBRARY_POSIX 1
#endif
/**
\brief The system library identifier for the Doxygen documentation.
\details
The system library identifier for an Doxygen documentation. This macro is always defined, but it does not
serve any purpose when using the library. In the documentation files NOU_OS_LIBRARY will show up defined as
this identifier.
*/
#ifndef NOU_OS_LIBRARY_DOXYGEN
#define NOU_OS_LIBRARY_DOXYGEN 2
#endif
/**
\brief Defined as the identifier of the current supported os library.
\details
This macro is defined as the identifier of the current supported os library. To check for a certain library,
use
\code{.cpp}
#if NOU_OS_LIBRARY == NOU_OS_LIBRARY_*
\endcode
and replace * with the library name.
If there is no appropriate library available, a \#error directive will be triggered.
\todo Verify!
*/
#ifndef NOU_OS_LIBRARY
# if NOU_OS == NOU_OS_WINDOWS
# define NOU_OS_LIBRARY NOU_OS_LIBRARY_WIN_H
# elif NOU_OS == NOU_OS_LINUX || NOU_OS == NOU_OS_UNIX || NOU_OS == NOU_OS_MAC
# define NOU_OS_LIBRARY NOU_OS_LIBRARY_POSIX
# elif NOU_OS == NOU_OS_DOXYGEN
# define NOU_OS_LIBRARY NOU_OS_LIBRARY_DOXYGEN
# else
# error Both Windows.h and POSIX are not supported.
# endif
#endif
/**
\brief The compiler identifier for Visual C++.
\details
The compiler identifier for Visual C++. This macro is always defined, to check if the current compiler is
Visual C++, use
\code{.cpp}
#if NOU_COMPILER == NOU_COMPILER_VISUAL_CPP
\endcode
*/
#ifndef NOU_COMPILER_VISUAL_CPP
#define NOU_COMPILER_VISUAL_CPP 0
#endif
/**
\brief The compiler identifier for GNU GCC or g++.
\details
The compiler identifier for GNU GCC or g++. This macro is always defined, to check if the current compiler is
GNU GCC or g++, use
\code{.cpp}
#if NOU_COMPILER == NOU_COMPILER_GCC
\endcode
*/
#ifndef NOU_COMPILER_GCC
#define NOU_COMPILER_GCC 1
#endif
/**
\brief The compiler identifier for Clang.
\details
The compiler identifier for Clang. This macro is always defined, to check if the current compiler is Clang,
use
\code{.cpp}
#if NOU_COMPILER == NOU_COMPILER_CLANG
\endcode
*/
#ifndef NOU_COMPILER_CLANG
#define NOU_COMPILER_CLANG 2
#endif
/**
\brief The compiler identifier for Intel C++.
\details
The compiler identifier for Intel C++. This macro is always defined, to check if the current compiler is
Intel C++, use
\code{.cpp}
#if NOU_COMPILER == NOU_COMPILER_INTEL_CPP
\endcode
*/
#ifndef NOU_COMPILER_INTEL_CPP
#define NOU_COMPILER_INTEL_CPP 3
#endif
/**
\brief The compiler identifier for MinGW.
\details
The compiler identifier for MinGW. This macro is always defined, to check if the current compiler is MinGW,
use
\code{.cpp}
#if NOU_COMPILER == NOU_COMPILER_MIN_GW
\endcode
*/
#ifndef NOU_COMPILER_MIN_GW
#define NOU_COMPILER_MIN_GW 4
#endif
/**
\brief The compiler identifier for an unknown compiler.
\details
The compiler identifier for an unknown compiler. This macro is always defined, to check if the current
compiler is unknown, use
\code{.cpp}
#if NOU_COMPILER == NOU_COMPILER_UNKNOWN
\endcode
An unknown compiler does not cause an error per-se, however, it may cause major problems (e.g. the
value of NOU_FUNC will not be set properly).
*/
#ifndef NOU_COMPILER_UNKNOWN
#define NOU_COMPILER_UNKNOWN 5
#endif
/**
\brief The compiler identifier for the Doxygen documentation.
\details
The compiler identifier for an Doxygen documentation. This macro is always defined, but it does not serve any
purpose when using the library. In the documentation files, NOU_COMPILER will be defined as this identifier.
*/
#ifndef NOU_COMPILER_DOXYGEN
#define NOU_COMPILER_DOXYGEN 6
#endif
/**
\brief Defined as the identifier of the current compiler.
\details
This macro is defined as the identifier of the current compiler. To check for a certain compiler, use
\code{.cpp}
#if NOU_COMPILER == NOU_COMPILER_*
\endcode
and replace * with the compiler name.
\todo Verify!
*/
#ifndef NOU_COMPILER
# ifdef __clang__ //This has to be placed first (b/c Clang also defines __GNUC__ and _MSC_VER)
# define NOU_COMPILER NOU_COMPILER_CLANG
# elif defined _MSC_VER
# define NOU_COMPILER NOU_COMPILER_VISUAL_CPP
# elif defined __GNUC__
# define NOU_COMPILER NOU_COMPILER_GCC
# elif defined __INTEL_COMPILER
# define NOU_COMPILER NOU_COMPILER_INTEL_CPP
# elif defined __MINGW32__
# define NOU_COMPILER NOU_COMPILER_MIN_GW
# elif defined __DOXYGEN__
# define NOU_COMPILER NOU_COMPILER_DOXYGEN
# else
# define NOU_COMPILER NOU_COMPILER_UNKNOWN
# endif
#endif
/**
\brief A macro that is used to export functions into libraries.
\todo Verify (esp. with other compilers)
*/
#ifndef NOU_EXPORT_FUNC
# if NOU_COMPILER == NOU_COMPILER_VISUAL_CPP
# define NOU_EXPORT_FUNC __declspec(dllexport)
# else
# define NOU_EXPORT_FUNC
# endif
#endif
/**
\brief A macro that is used to import functions a function from a library.
\todo Verify (esp. with other compilers)
*/
#ifndef NOU_IMPORT_FUNC
# if NOU_COMPILER == NOU_COMPILER_VISUAL_CPP
# define NOU_IMPORT_FUNC __declspec(dllimport)
# else
# define NOU_IMPORT_FUNC
# endif
#endif
/**
\brief A macro that either exports or imports a function from a library.
\details
A macro that either exports or imports a function from a library.
This macro will import, if NOU_DLL is defined and export if it is not. NOU_DLL definitions should always be
correctly handled by CMake and does not need user-interaction.
*/
#ifndef NOU_FUNC
# ifdef NOU_DLL
# define NOU_FUNC NOU_IMPORT_FUNC
# else
# define NOU_FUNC NOU_EXPORT_FUNC
# endif
#endif
/**
\param major The major part of the version.
\param minor The minor part of the version.
\param patch The patch part of the version.
\brief Creates a 32 bit version number.
\details
Creates a 32 bit version number (more precisely a nou::uint32) that consists of the passed parameters. The
format is major.minor.patch.
E.g:
NOU_MAKE_VERSION(1, 2, 3) creates the version 1.2.3.
Versions made by this macro can be compared using the usual operators (<, >, <=, >=, ==, !=).
The single parts can be read from a version using NOU_VERSION_MAJOR, NOU_VERSION_MINOR and NOU_VERSION_PATCH
respectively.
The sizes of the single parts in bit are:
Part | Size | Maximum value
----- | ---- | -------------
major | 8 | 255
minor | 9 | 511
patch | 15 | 32.767
\warning
These values should never be overflowed since in this case bits will be cut off.
*/
#ifndef NOU_MAKE_VERSION
#define NOU_MAKE_VERSION(major, minor, patch) \
static_cast<NOU::uint32> \
(((major << 24) & 0b11111111000000000000000000000000) | \
((minor << 15) & 0b00000000111111111000000000000000) | \
(patch & 0b00000000000000000111111111111111))
#endif
/**
\param version The version to retrieve the major part from.
\brief Retrieves the major part of a version that was made using NOU_MAKE_VERSION.
*/
#ifndef NOU_VERSION_MAJOR
#define NOU_VERSION_MAJOR(version) static_cast<NOU::uint32> \
((version & 0b11111111000000000000000000000000) >> (24))
#endif
/**
\param version The version to retrieve the major part from.
\brief Retrieves the minor part of a version that was made using NOU_MAKE_VERSION.
*/
#ifndef NOU_VERSION_MINOR
#define NOU_VERSION_MINOR(version) static_cast<NOU::uint32> \
((version & 0b00000000111111111000000000000000) >> (15))
#endif
/**
\param version The version to retrieve the major part from.
\brief Retrieves the patch part of a version that was made using NOU_MAKE_VERSION.
*/
#ifndef NOU_VERSION_PATCH
#define NOU_VERSION_PATCH(version) static_cast<NOU::uint32>(version & 0b00000000000000000111111111111111)
#endif
/**
\brief The maximum value of the major part of a version when creating a version with NOU_MAKE_VERSION.
*/
#ifndef NOU_VERSION_MAJOR_MAX
#define NOU_VERSION_MAJOR_MAX static_cast<NOU::uint32>(255)
#endif
/**
\brief The maximum value of the minor part of a version when creating a version with NOU_MAKE_VERSION.
*/
#ifndef NOU_VERSION_MINOR_MAX
#define NOU_VERSION_MINOR_MAX static_cast<NOU::uint32>(511)
#endif
/**
\brief The maximum value of the patch part of a version when creating a version with NOU_MAKE_VERSION.
*/
#ifndef NOU_VERSION_PATCH_MAX
#define NOU_VERSION_PATCH_MAX static_cast<NOU::uint32>(32767)
#endif
/**
\brief The first version of NOU.
*/
#ifndef NOU_VERSION_1_0_0
#define NOU_VERSION_1_0_0 NOU_MAKE_VERSION(1, 0, 0)
#endif
/**
\brief The first patch for version 1.0.0 of NOU.
*/
#ifndef NOU_VERSION_1_0_1
#define NOU_VERSION_1_0_1 NOU_MAKE_VERSION(1, 0, 1)
#endif
/**
\brief The current version of NOU.
*/
//This will be configured by Config.hpp, which is generated by CMake. There is the default-versiob 0.0.0 to
//stop IDEs from generating errors because of undefined macros.
#ifdef NOU_IS_CONFIG_FILE_PRESENT
# ifndef NOU_VERSION
# define NOU_VERSION NOU_MAKE_VERSION(NOU_INTERNAL_VERSION_MAJOR, \
NOU_INTERNAL_VERSION_MINOR, \
NOU_INTERNAL_VERSION_PATCH)
# endif
#else
# ifndef NOU_VERSION
# define NOU_VERSION NOU_MAKE_VERSION(0, 0, 0)
# endif
#endif
/**
\brief The version of the compiler in a normalized form.
\todo Verify!
*/
#ifndef NOU_COMPILER_VERSION
# if NOU_COMPILER == NOU_COMPILER_VISUAL_CPP
# if defined _MSC_FULL_VER
//From this version on, an additional bit is used to determine the version
# if _MSC_FULL_VER >= 150030729
# define NOU_COMPILER_VERSION NOU_MAKE_VERSION((_MSC_FULL_VER % 1'00'00'00000) / 1'00'00000, \
(_MSC_FULL_VER % 1'00'00000) / 1'00000, _MSC_FULL_VER % 1'00000)
# else
# define NOU_COMPILER_VERSION NOU_MAKE_VERSION((_MSC_FULL_VER % 100'00'0000) / 100'0000, \
(_MSC_FULL_VER % 100'0000) / 10000, _MSC_FULL_VER % 1000)
# endif
# else
# define NOU_COMPILER_VERSION NOU_MAKE_VERSION(((_MSC_VER % 10000) / 100), (_MSC_VER % 100), 0)
# endif
# elif NOU_COMPILER == NOU_COMPILER_GCC
# if defined __GNUC_PATCHLEVEL__
# define NOU_COMPILER_VERSION NOU_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
# else
# define NOU_COMPILER_VERSION NOU_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, 0)
# endif
# elif NOU_COMPILER == NOU_COMPILER_CLANG
# define NOU_COMPILER_VERSION NOU_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__)
# elif NOU_COMPILER == NOU_COMPILER_INTEL_CPP
# define NOU_COMPILER_VERSION NOU_MAKE_VERSION(((__INTEL_COMPILER % 10000) / 100), \
(__INTEL_COMPILER % 100), 0)
# elif NOU_COMPILER == NOU_COMPILER_MIN_GW
# define NOU_COMPILER_VERSION NOU_MAKE_VERSION(__MINGW32_MAJOR_VERSION, __MINGW32_MINOR_VERSION, 0)
# elif NOU_COMPILER == NOU_COMPILER_DOXYGEN
# define NOU_COMPILER_VERSION NOU_VERSION_MIN
# elif NOU_COMPILER == NOU_COMPILER_UNKNOWN
# define NOU_COMPILER_VERSION NOU_VERSION_MAX
# endif
#endif
/**
\param ... The expression to convert.
\brief Converts any expression into a const char*.
*/
#ifndef NOU_STRINGIFY
#define NOU_STRINGIFY(...) #__VA_ARGS__
#endif
/**
\brief Returns the result of __LINE__ as a c-string (NOU_STRINGIFY(__LINE__) would not work).
*/
#ifndef NOU_LINE_STRING
#define NOU_LINE_STRING_HELPER(str) NOU_STRINGIFY(str)
#define NOU_LINE_STRING NOU_LINE_STRING_HELPER(__LINE__)
#endif
/**
\brief Expands to a string literal with the function signature of the function that this macro was placed in.
\note
Although this macro is platform independent, it is not guaranteed that using this macro in the same function
on different platforms also produces the same result.
*/
#ifndef NOU_FUNC_NAME
# if NOU_COMPILER == NOU_COMPILER_VISUAL_CPP
# define NOU_FUNC_NAME __FUNCSIG__
# elif NOU_COMPILER == NOU_COMPILER_GCC
# define NOU_FUNC_NAME NOU_STRINGIFY(__PRETTY_FUNCTION__)
# elif NOU_COMPILER == NOU_COMPILER_CLANG
# define NOU_FUNC_NAME NOU_STRINGIFY(__PRETTY_FUNCTION__)
# elif NOU_COMPILER == NOU_COMPILER_INTEL_CPP
# define NOU_FUNC_NAME __func__ ///\Todo check
# elif NOU_COMPILER == NOU_COMPILER_MIN_GW
# define NOU_FUNC_NAME __func__ ///\Todo check
# elif NOU_COMPILER == NOU_COMPILER_DOXYGEN
# define NOU_FUNC_NAME __FUNCSIG__
# else
# define NOU_FUNC_NAME __func__
# endif
#endif
/**
\brief A macro that is only defined if the library should be compiled in C++14 compatiblity mode.
\details
A macro that is only defined if the library should be compiled in C++14 compatiblity mode.
Usually, this is defined by CMake.
*/
#if NOU_COMPILER == NOU_COMPILER_DOXYGEN //Only present for Doxygen
#define NOU_CPP14_COMPATIBILITY
#endif
namespace NOU::NOU_CORE
{
/**
\return (In the member type "type") The type that was chosen.
\brief Chooses from the available floating point types <tt>float</tt>, <tt>float</tt> and <tt>long
double</tt> one that has a size of 32 bit. If none of the have a size of 32 bit, long double will
be chosen.
*/
struct ChooseFloat32 :
std::conditional<sizeof(float) == 4,
float,
typename std::conditional_t<sizeof(double) == 4,
double,
long double
>
> {};
/**
\return (In the member type "type") The type that was chosen.
\brief Chooses from the available floating point types <tt>float</tt>, <tt>float</tt> and <tt>long
double</tt> one that has a size of 64 bit. If none of the have a size of 32 bit, long double will
be chosen.
*/
struct ChooseFloat64 :
std::conditional<sizeof(float) == 8,
float,
typename std::conditional_t<sizeof(double) == 8,
double,
long double
>
> {};
}
namespace NOU
{
/**
\brief A signed integer type with a width of 8 bit.
*/
using int8 = std::int8_t;
/**
\brief An unsigned integer type with a width of 8 bit.
*/
using uint8 = std::uint8_t;
/**
\brief A signed integer type with a width of 16 bit.
*/
using int16 = std::int16_t;
/**
\brief An unsigned integer type with a width of 16 bit.
*/
using uint16 = std::uint16_t;
/**
\brief A signed integer type with a width of 32 bit.
*/
using int32 = std::int32_t;
/**
\brief An unsigned integer type with a width of 32 bit.
*/
using uint32 = std::uint32_t;
/**
\brief A signed integer type with a width of 64 bit.
*/
using int64 = std::int64_t;
/**
\brief An unsigned integer type with a width of 64 bit.
*/
using uint64 = std::uint64_t;
/**
\brief An unsigned integer type that is defined as the integer that is the maximum size of any object.
*/
using sizeType = std::size_t;
/**
\brief A boolean type.
*/
using boolean = bool;
/**
\brief A type that is one byte.
*/
using byte = unsigned char;
/**
\brief A character type with a width of 8 bit.
*/
using char8 = char;
/**
\brief A character type with a width of 16 bit.
*/
using char16 = char16_t;
/**
\brief A character type with a width of 32 bit.
*/
using char32 = char32_t;
/**
\brief A floating point type with a width of 32 bit.
\note If the compiler does not support a 32 bit float, this will be the largest floating point type
available.
*/
using float32 = NOU_CORE::ChooseFloat32::type;
/**
\brief A floating point type with a width of 64 bit.
\note If the compiler does not support a 64 bit float, this will be the largest floating point type
available.
*/
using float64 = NOU_CORE::ChooseFloat64::type;
}
#endif
| 25.753012
| 110
| 0.744281
|
Lehks
|
8ac9405fe0d63a0013f2279d0aa7667fec81f3d8
| 13,292
|
cpp
|
C++
|
DBProCompiler/DBPCompiler/StructTable.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 231
|
2018-01-28T00:06:56.000Z
|
2022-03-31T21:39:56.000Z
|
DBProCompiler/DBPCompiler/StructTable.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 9
|
2016-02-10T10:46:16.000Z
|
2017-12-06T17:27:51.000Z
|
DBProCompiler/DBPCompiler/StructTable.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 66
|
2018-01-28T21:54:52.000Z
|
2022-02-16T22:50:57.000Z
|
// StructTable.cpp: implementation of the CStructTable class.
//
//////////////////////////////////////////////////////////////////////
// Common Includes
#define _CRT_SECURE_NO_DEPRECATE
#pragma warning(disable : 4996)
#include "StructTable.h"
// Special access to global pointer to struct table (so can do full scan)
extern CStructTable* g_pStructTable;
#ifdef __AARON_STRUCPERF__
# define ALLOWED_LOWER "abcdefghijklmnopqrstuvwxyz"
# define ALLOWED_UPPER "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# define ALLOWED_ALPHA ALLOWED_LOWER ALLOWED_UPPER
# define ALLOWED_DIGIT "0123456789"
# define ALLOWED_ALNUM ALLOWED_ALPHA ALLOWED_DIGIT
# define ALLOWED_IDENT ALLOWED_ALNUM "_"
# define ALLOWED_TYPES "#$%"
# define ALLOWED_SCOPE ":"
# define ALLOWED_INTRN "&@ "
# define ALLOWED_MISCL ALLOWED_TYPES ALLOWED_INTRN ALLOWED_SCOPE
# define ALLOWED_DBVAR ALLOWED_IDENT ALLOWED_MISCL
typedef db3::TDictionary<CStructTable> map_type;
typedef db3::TDictionary<CStructTable>::SEntry entry_type;
map_type CStructTable::g_Table(ALLOWED_DBVAR, map_type::Insensitive, map_type::DeleteEntries);
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CStructTable::CStructTable()
{
m_dwTypeMode=0;
m_dwTypeValue=0;
m_pTypeName=NULL;
m_cTypeChar=0;
m_dwSize=0;
m_pDecChain=NULL;
m_pDecBlock=NULL;
m_pNext=NULL;
}
CStructTable::~CStructTable()
{
SAFE_DELETE(m_pTypeName);
SAFE_DELETE(m_pDecChain);
SAFE_DELETE(m_pDecBlock);
}
void CStructTable::Free(void)
{
CStructTable* pCurrent = this;
while(pCurrent)
{
CStructTable* pNext = pCurrent->GetNext();
delete pCurrent;
pCurrent = pNext;
}
}
void CStructTable::Add(CStructTable* pNew)
{
CStructTable* pCurrent = this;
while(pCurrent->m_pNext)
{
pCurrent=pCurrent->GetNext();
}
pCurrent->m_pNext=pNew;
}
void CStructTable::SetStructDefaults(void)
{
// Default datatypes and sizes
SetStruct(1, "integer", 'L', 4);
AddStruct(2, "float", 'F', 4);
AddStruct(3, "string", 'S', 4);
AddStruct(4, "boolean", 'B', 1);
AddStruct(5, "byte", 'Y', 1);
AddStruct(6, "word", 'W', 2);
AddStruct(7, "dword", 'D', 4);
AddStruct(8, "double float", 'O', 8);
AddStruct(9, "double integer", 'R', 8);
AddStruct(10,"label", 'P', 4);
AddStruct(20,"dabel", 'Q', 4);
AddStruct(101, "integer array", 'm', 4);
AddStruct(102, "float array", 'g', 4);
AddStruct(103, "string array", 't', 4);
AddStruct(104, "boolean array", 'c', 4);
AddStruct(105, "byte array", 'z', 4);
AddStruct(106, "word array", 'x', 4);
AddStruct(107, "dword array", 'e', 4);
AddStruct(108, "double float array", 'u', 4);
AddStruct(109, "double integer array", 'v', 4);
AddStruct(501, "anytype non casted", 'X', 4);
AddStruct(1001, "userdefined var ptr", 'E', 4);
AddStruct(1101, "userdefined array ptr",'e', 4);
}
bool CStructTable::SetStruct(DWORD dwValue, LPSTR pStructName, unsigned char cStructChar, DWORD dwSize)
{
// Set Struct Data
CStr* pStrTypeName = new CStr(pStructName);
SetTypeMode(0);
SetTypeValue(dwValue);
SetTypeName(pStrTypeName);
SetTypeChar(cStructChar);
SetTypeSize(dwSize);
#ifdef __AARON_STRUCPERF__
entry_type *entry = g_Table.Lookup(pStructName);
assert_msg(!!entry, "g_Table.Lookup() failed!");
assert_msg(!entry->P, "Struct already exists");
entry->P = this;
#endif
return true;
}
bool CStructTable::AddStruct(DWORD dwValue, LPSTR pStructName, unsigned char cStructChar, DWORD dwSize)
{
// Create structure
CStructTable* pNewType = new CStructTable;
// Set Struct Data
CStr* pStrTypeName = new CStr(pStructName);
pNewType->SetTypeMode(0);
pNewType->SetTypeValue(dwValue);
pNewType->SetTypeName(pStrTypeName);
pNewType->SetTypeChar(cStructChar);
pNewType->SetTypeSize(dwSize);
pNewType->SetDecChain(NULL);
pNewType->SetTypeBlock(NULL);
#ifdef __AARON_STRUCPERF__
entry_type *entry = g_Table.Lookup(pStructName);
assert_msg(!!entry, "g_Table.Lookup() failed!");
assert_msg(!entry->P, "Struct already exists");
entry->P = pNewType;
#endif
// Add Struct to list
Add(pNewType);
// Complete
return true;
}
bool CStructTable::AddStructUserType(DWORD dwMode, LPSTR pStructName, unsigned char cStructChar, CDeclaration* pDecChain, CStatement* pTypeBlock, DWORD dwStructTypeMode, bool* pbReportError, DWORD dwParamInUserFunction )
{
// Only add if unique
if(DoesTypeEvenExist(pStructName)!=NULL)
return false;
// lee - 150206 - u60 - add only if known type at this point (typeA before typeB if typeB uses typeA)
CDeclaration* pCurrent = pDecChain;
if ( pCurrent )
{
// check all dec types
while ( pCurrent )
{
if ( strcmp ( pCurrent->GetType()->GetStr(), "" )!=NULL )
{
if ( g_pStructTable->DoesTypeEvenExist ( pCurrent->GetType()->GetStr() )==false )
{
// fail here as type is unknown and so cannot create a struct based on an unknown type
if ( pbReportError ) *pbReportError = true;
return false;
}
}
pCurrent = pCurrent->GetNext();
}
}
// Create structure
CStructTable* pNewType = new CStructTable;
// When get a zero mode
if(dwMode==0)
{
// Generate unique type value for it (starting at 1001...)
dwMode=1001;
}
// Set Struct Data
CStr* pStrTypeName = new CStr(pStructName);
pNewType->SetTypeMode(dwStructTypeMode);
pNewType->SetTypeValue(dwMode);
pNewType->SetTypeName(pStrTypeName);
pNewType->SetTypeChar(cStructChar);
pNewType->SetTypeSize(0);
pNewType->SetDecChain(pDecChain);
pNewType->SetTypeBlock(pTypeBlock);
#ifdef __AARON_STRUCPERF__
entry_type *entry = g_Table.Lookup(pStructName);
assert_msg(!!entry, "g_Table.Lookup() failed!");
assert_msg(!entry->P, "Struct already exists");
entry->P = pNewType;
#endif
// U73 - 230309 - added param count for Diggory (new debugger)
pNewType->SetParamInUserFunction ( dwParamInUserFunction );
// Add Struct to list
Add(pNewType);
// Complete
return true;
}
bool CStructTable::AddStructUserType(DWORD dwMode, LPSTR pStructName, unsigned char cStructChar, CDeclaration* pDecChain, CStatement* pTypeBlock, DWORD dwStructTypeMode, bool* pbReportError )
{
return AddStructUserType( dwMode, pStructName, cStructChar, pDecChain, pTypeBlock, dwStructTypeMode, pbReportError, 0 );
}
bool CStructTable::AddStructUserType(DWORD dwMode, LPSTR pStructName, unsigned char cStructChar, CDeclaration* pDecChain, CStatement* pTypeBlock, DWORD dwStructTypeMode )
{
return AddStructUserType( dwMode, pStructName, cStructChar, pDecChain, pTypeBlock, dwStructTypeMode, NULL );
}
bool CStructTable::CalculateAllSizes(void)
{
DWORD dwAttempts=0;
DWORD dwStructuresMax=0;
bool bKeepGoing=true;
while(bKeepGoing)
{
bKeepGoing=false;
DWORD dwCountStructures=0;
CStructTable* pCurrent = this;
while(pCurrent)
{
dwCountStructures++;
if(dwCountStructures>dwStructuresMax)
dwStructuresMax=dwCountStructures;
if(pCurrent->CalculateSize()==false)
bKeepGoing=true;
pCurrent = pCurrent->GetNext();
}
// Drop out with error if cannot resolve type sizes
if(dwAttempts>dwStructuresMax)
{
g_pErrorReport->AddErrorString("Failed to 'CalculateAllSizes::dwAttempts>dwStructuresMax'");
return false;
}
dwAttempts++;
}
// Complete
return true;
}
bool CStructTable::CalculateSize(void)
{
// Calculate sizes of dec chain if have one
if(m_pDecChain)
{
bool bSecondPass = true;
while ( bSecondPass )
{
// do first pass
bSecondPass = false;
// calculate size
DWORD dwCumilitiveSize=0;
CDeclaration* pDec = m_pDecChain;
while(pDec)
{
if(pDec->GetName())
{
if(g_pStructTable->DoesTypeEvenExist(pDec->GetType()->GetStr()))
{
//leefix - 300305 - bytes must be stored in DWORDS (as they are passed onto stack as such)
DWORD dwSize=g_pStructTable->GetSizeOfType(pDec->GetType()->GetStr());
if ( dwSize <4 ) dwSize=4;
if(pDec->GetArrFlag()==1) dwSize=4;
if(dwSize>0)
{
// Calculate full size of field using array value
DWORD dwArraySize = (DWORD)pDec->GetArrValue()->GetValue();
if(dwArraySize>0)
{
// Array determines final field size
dwSize*=dwArraySize;
}
// Set Offset within declaration for struct-field-offset reference
pDec->SetOffset(dwCumilitiveSize);
pDec->SetDataSize(dwSize);
dwCumilitiveSize+=dwSize;
}
else
{
g_pErrorReport->AddErrorString("Failed to 'CalculateSize::dwSize>0'");
return false;
}
}
else
{
DWORD LineNumber = pDec->GetLineNumber();
g_pErrorReport->SetError(LineNumber, ERR_SYNTAX+35, pDec->GetType()->GetStr());
return false;
}
}
pDec = pDec->GetNext();
}
// leefix - 220604 - u54 - If not on DWORD boundary
int iRemainder = dwCumilitiveSize % 4;
if ( iRemainder > 0 )
{
// NOT DWORD boundary - add fillers
iRemainder = 4-iRemainder;
for ( int i=0; i<iRemainder; i++ )
{
CDeclaration* pNewDec = new CDeclaration;
pNewDec->SetDecData(0, "", "___filler", "byte", "", 0);
m_pDecChain->Add ( pNewDec );
}
// do again
bSecondPass = true;
}
else
{
// Assign total to size member of
SetTypeSize(dwCumilitiveSize);
}
}
}
// Complete
return true;
}
CStructTable* CStructTable::DoesTypeEvenExist(LPSTR pName)
{
#ifdef __AARON_STRUCPERF__
entry_type *entry = g_Table.Lookup(pName);
if (!entry)
return NULL;
return (CStructTable *)entry->P;
#else
if(GetTypeName())
if(stricmp(pName, GetTypeName()->GetStr())==NULL)
return this;
if(GetNext())
return GetNext()->DoesTypeEvenExist(pName);
return NULL;
#endif
}
DWORD CStructTable::GetSizeOfType(LPSTR pName)
{
if(GetTypeName())
if(stricmp(pName, GetTypeName()->GetStr())==NULL)
return GetTypeSize();
if(GetNext())
return GetNext()->GetSizeOfType(pName);
return 0;
}
CDeclaration* CStructTable::FindDecInType(LPSTR pTypename, LPSTR pFieldname)
{
#ifdef __AARON_STRUCPERF__
CStructTable *struc;
CDeclaration *dec;
entry_type *entry;
entry = g_Table.Lookup(pTypename);
if (!entry || !entry->P)
return NULL;
struc = (CStructTable *)entry->P;
for(dec=struc->m_pDecChain; dec; dec=dec->GetNext()) {
if (stricmp(dec->GetName()->GetStr(), pFieldname)==0)
break;
}
return dec;
#else
if(stricmp(GetTypeName()->GetStr(), pTypename)==NULL)
{
if(m_pDecChain)
{
CDeclaration* pDec = m_pDecChain;
while(pDec)
{
if(stricmp(pDec->GetName()->GetStr(), pFieldname)==NULL)
{
return pDec;
}
pDec = pDec->GetNext();
}
}
return NULL;
}
if(GetNext())
return GetNext()->FindDecInType(pTypename, pFieldname);
else
return NULL;
#endif
}
CDeclaration* CStructTable::FindFieldInType(LPSTR pTypename, LPSTR pFieldname, LPSTR* pReturnType, DWORD* pdwArrFlag, DWORD* pdwOffset)
{
CDeclaration* pDec = FindDecInType(pTypename, pFieldname);
if(pDec)
{
// Create string and copy typename of field
*pReturnType = new char[pDec->GetType()->Length()+1];
strcpy(*pReturnType, pDec->GetType()->GetStr());
*pdwArrFlag=pDec->GetArrFlag();
*pdwOffset=pDec->GetOffset();
return pDec;
}
// Not found soft fail
return NULL;
}
bool CStructTable::FindOffsetFromField(LPSTR pTypename, LPSTR pFieldname, DWORD* pReturnOffset, DWORD* pdwSizeData)
{
CDeclaration* pDec = FindDecInType(pTypename, pFieldname);
if(pDec)
{
// Extract offset data from dec in type struct
*pReturnOffset = pDec->GetOffset();
*pdwSizeData = pDec->GetDataSize();
return true;
}
// Not found soft fail
return false;
}
int CStructTable::FindIndex(LPSTR pTypename)
{
int iIndex = 0;
CStructTable* pCurrent = this;
while(pCurrent)
{
// if find type, exit now to retain iIndex
if ( stricmp ( pCurrent->GetTypeName()->GetStr(), pTypename )==NULL )
break;
// next structure
pCurrent = pCurrent->GetNext();
iIndex++;
}
// return found index
return iIndex;
}
bool CStructTable::WriteDBMHeader(void)
{
// Blank Line
CStr strDBMBlank(1);
if(g_pDBMWriter->OutputDBM(&strDBMBlank)==false) return false;
// Title
CStr strDBMLine(256);
strDBMLine.SetText("DEBUG:");
if(g_pDBMWriter->OutputDBM(&strDBMLine)==false) return false;
return true;
}
bool CStructTable::WriteDBM(void)
{
// Write out text
CStr strDBMLine(256);
// Structure Type
if(GetTypeMode()==0)
{
strDBMLine.SetText("STRUCT@");
}
if(GetTypeMode()==1)
{
strDBMLine.SetText("USERSTRUCT@");
}
if(GetTypeMode()==2)
{
strDBMLine.SetText("FS@");
}
strDBMLine.AddText(m_pTypeName);
strDBMLine.AddText(" Overall Size:");
strDBMLine.AddNumericText(m_dwSize);
// U73 - 230309 - added for Diggory Debugger
if(GetTypeMode()==2)
{
strDBMLine.AddText(" Parameter Count:");
strDBMLine.AddNumericText(m_dwParamInUserFunction);
}
// User Types has a blank to make reading easier
if(m_pDecChain)
{
CStr strDBMBlank(1);
if(g_pDBMWriter->OutputDBM(&strDBMBlank)==false) return false;
}
// Output type details
if(g_pDBMWriter->OutputDBM(&strDBMLine)==false) return false;
// Write out fields of type
if(m_pDecChain)
{
if(m_pDecChain->WriteDBM()==false) return false;
}
// Write next one
if(GetNext())
{
if((GetNext()->WriteDBM())==false) return false;
}
// Complete
return true;
}
| 24.167273
| 220
| 0.68703
|
domydev
|
8acc45474017e9ba601ad3c32c234ded9cf26a09
| 3,163
|
hpp
|
C++
|
Examples/OpcPlcManager/src/OpcPlcManagerComponent.hpp
|
Siddu96/CppExamples
|
7b890a7e387a6a1504982f610f8a886312d49854
|
[
"MIT"
] | 18
|
2019-02-22T14:24:19.000Z
|
2022-01-24T12:41:41.000Z
|
Examples/OpcPlcManager/src/OpcPlcManagerComponent.hpp
|
Siddu96/CppExamples
|
7b890a7e387a6a1504982f610f8a886312d49854
|
[
"MIT"
] | 25
|
2019-06-12T12:20:38.000Z
|
2022-02-09T07:57:28.000Z
|
Examples/OpcPlcManager/src/OpcPlcManagerComponent.hpp
|
Siddu96/CppExamples
|
7b890a7e387a6a1504982f610f8a886312d49854
|
[
"MIT"
] | 18
|
2019-03-14T08:41:33.000Z
|
2022-01-27T01:36:18.000Z
|
#pragma once
#include "Arp/System/Core/Arp.h"
#include "Arp/System/Acf/ComponentBase.hpp"
#include "Arp/System/Acf/IApplication.hpp"
#include "Arp/Plc/Commons/Meta/MetaComponentBase.hpp"
#include "Arp/System/Commons/Logging.h"
#include "Arp/System/Commons/Threading/WorkerThread.hpp"
#include "Arp/Plc/Domain/Services/IPlcManagerService2.hpp"
namespace OpcPlcManager
{
using namespace Arp;
using namespace Arp::System::Acf;
using namespace Arp::Plc::Commons::Meta;
using namespace Arp::Plc::Domain::Services;
//#acfcomponent
class OpcPlcManagerComponent : public ComponentBase, public MetaComponentBase, private Loggable<OpcPlcManagerComponent>
{
public: // typedefs
public: // construction/destruction
OpcPlcManagerComponent(IApplication& application, const String& name);
virtual ~OpcPlcManagerComponent() = default;
public: // IComponent operations
void Initialize() override;
void SubscribeServices()override;
void LoadSettings(const String& settingsPath)override;
void SetupSettings()override;
void PublishServices()override;
void LoadConfig() override;
void SetupConfig() override;
void ResetConfig() override;
void Dispose()override;
void PowerDown()override;
public: // MetaComponentBase operations
void RegisterComponentPorts() override;
private: // methods
OpcPlcManagerComponent(const OpcPlcManagerComponent& arg) = delete;
OpcPlcManagerComponent& operator= (const OpcPlcManagerComponent& arg) = delete;
public: // static factory operations
static IComponent::Ptr Create(Arp::System::Acf::IApplication& application, const String& name);
private: // fields
WorkerThread workerThreadInstance;
IPlcManagerService2::Ptr plcManagerService2Ptr = nullptr;
private: // methods
void workerThreadBody(void);
public: // ports
// One struct is defined for each OPC UA method
// Each struct contains the method input and output parameters,
// and two special UA_* variables.
struct GET_PLC_STATE
{
//#attributes(Input|Opc)
Arp::int16 UA_MethodState = 0;
//#attributes(Output|Opc)
Arp::uint32 state = 0;
//#attributes(Output|Opc)
Arp::uint32 UA_StatusCode = 0;
};
struct START
{
//#attributes(Input|Opc)
Arp::uint8 startKind = 0;
//#attributes(Input|Opc)
Arp::boolean async = false;
//#attributes(Input|Opc)
Arp::int16 UA_MethodState = 0;
//#attributes(Output|Opc)
Arp::uint32 UA_StatusCode = 0;
};
struct STOP
{
//#attributes(Input|Opc)
Arp::boolean async = false;
//#attributes(Input|Opc)
Arp::int16 UA_MethodState = 0;
//#attributes(Output|Opc)
Arp::uint32 UA_StatusCode = 0;
};
// Now the port variables themselves
//#port
GET_PLC_STATE GetPlcState;
//#port
START Start;
//#port
STOP Stop;
};
inline IComponent::Ptr OpcPlcManagerComponent::Create(Arp::System::Acf::IApplication& application, const String& name)
{
return IComponent::Ptr(new OpcPlcManagerComponent(application, name));
}
} // end of namespace OpcPlcManager
| 27.99115
| 119
| 0.69902
|
Siddu96
|
8ace25887d25917d2cdfb7b38d3adfc887ad773d
| 2,611
|
cpp
|
C++
|
tsplp/src/LinearVariableComposition.cpp
|
sebrockm/mtsp-vrp
|
28955855d253f51fcb9397a0b22c6774f66f8d55
|
[
"MIT"
] | null | null | null |
tsplp/src/LinearVariableComposition.cpp
|
sebrockm/mtsp-vrp
|
28955855d253f51fcb9397a0b22c6774f66f8d55
|
[
"MIT"
] | null | null | null |
tsplp/src/LinearVariableComposition.cpp
|
sebrockm/mtsp-vrp
|
28955855d253f51fcb9397a0b22c6774f66f8d55
|
[
"MIT"
] | null | null | null |
#include "LinearVariableComposition.hpp"
#include "Variable.hpp"
#include <algorithm>
tsplp::LinearVariableComposition tsplp::operator*(double factor, LinearVariableComposition linearComp)
{
for (auto& coef : linearComp.m_coefficients)
coef *= factor;
linearComp.m_constant *= factor;
return linearComp;
}
tsplp::LinearVariableComposition tsplp::operator+(LinearVariableComposition lhs, LinearVariableComposition rhs)
{
auto& biggerOne = lhs.m_coefficients.size() > rhs.m_coefficients.size() ? lhs : rhs;
const auto& smallerOne = lhs.m_coefficients.size() > rhs.m_coefficients.size() ? rhs : lhs;
return std::move(biggerOne += smallerOne);
}
tsplp::LinearVariableComposition tsplp::operator+(LinearVariableComposition lhs, double rhs)
{
lhs.m_constant += rhs;
return lhs;
}
tsplp::LinearVariableComposition& tsplp::operator+=(LinearVariableComposition& lhs, LinearVariableComposition const& rhs)
{
for (size_t i = 0; i < rhs.m_variables.size(); ++i)
{
const auto iter = std::upper_bound(lhs.m_variables.begin(), lhs.m_variables.end(), rhs.m_variables[i], VariableLess{});
if (iter != lhs.m_variables.end() && iter->GetId() == rhs.m_variables[i].GetId())
{
const auto id = static_cast<size_t>(iter - lhs.m_variables.begin());
lhs.m_coefficients[id] += rhs.m_coefficients[i];
}
else
{
const auto coefIter = lhs.m_coefficients.begin() + (iter - lhs.m_variables.begin());
lhs.m_variables.insert(iter, rhs.m_variables[i]);
lhs.m_coefficients.insert(coefIter, rhs.m_coefficients[i]);
}
}
lhs.m_constant += rhs.m_constant;
return lhs;
}
tsplp::LinearVariableComposition tsplp::operator-(LinearVariableComposition operand)
{
for (auto& coef : operand.m_coefficients)
coef *= -1.0;
operand.m_constant *= -1.0;
return operand;
}
tsplp::LinearVariableComposition tsplp::operator-(LinearVariableComposition lhs, LinearVariableComposition rhs)
{
return std::move(lhs) + (-std::move(rhs));
}
tsplp::LinearVariableComposition::LinearVariableComposition(double constant)
: m_constant(constant)
{
}
tsplp::LinearVariableComposition::LinearVariableComposition(const Variable& variable)
: m_variables{ variable }, m_coefficients{ 1 }
{
}
double tsplp::LinearVariableComposition::Evaluate(const Model& model) const
{
double result = m_constant;
for (size_t i = 0; i < m_coefficients.size(); ++i)
result += m_coefficients[i] * m_variables[i].GetObjectiveValue(model);
return result;
}
| 30.011494
| 127
| 0.695136
|
sebrockm
|
8acfa0924b6d75af5d6a02806fa3522c2625cab5
| 12,242
|
cpp
|
C++
|
src/linereader.cpp
|
px86/hush
|
a8837bd99799757395417cf2ec48ebf56107b145
|
[
"MIT"
] | null | null | null |
src/linereader.cpp
|
px86/hush
|
a8837bd99799757395417cf2ec48ebf56107b145
|
[
"MIT"
] | 2
|
2022-02-28T05:24:22.000Z
|
2022-02-28T06:38:46.000Z
|
src/linereader.cpp
|
px86/hush
|
a8837bd99799757395417cf2ec48ebf56107b145
|
[
"MIT"
] | null | null | null |
#include <cctype>
#include <fstream>
#include <iostream>
#include <string>
#include <sys/ioctl.h>
#include <unistd.h>
#include "linereader.hpp"
// Word delimeters
const char *delimeters = " \t\n:-_'\"()[]{}";
TermHandle::TermHandle()
{
m_raw_mode_enabled = false;
// Save default termios.
if (tcgetattr(STDIN_FILENO, &m_orig_termios)) {
perror("Error: tcgetattr failed");
exit(EXIT_FAILURE);
}
// Settings for raw mode.
m_raw_termios.c_iflag &=
~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
m_raw_termios.c_oflag &= ~OPOST;
m_raw_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
m_raw_termios.c_cflag &= ~(CSIZE | PARENB);
m_raw_termios.c_cflag |= CS8;
// minimum number of bytes to read before returning
m_raw_termios.c_cc[VMIN] = 1;
// timeout in deci-seconds (1/10) (Does it matter now?)
m_raw_termios.c_cc[VTIME] = 1;
}
inline void TermHandle::enable_raw_mode()
{
if (m_raw_mode_enabled) return;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &m_raw_termios)) {
perror("Error: tcsetattr failed while trying to enable raw mode");
exit(EXIT_FAILURE);
}
m_raw_mode_enabled = true;
}
inline void TermHandle::disable_raw_mode()
{
if (!m_raw_mode_enabled) return;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &m_orig_termios)) {
perror("Error: tcsetattr failed while trying to disable raw mode");
exit(EXIT_FAILURE);
}
m_raw_mode_enabled = false;
}
auto LineReader::readline(const char *prompt) -> std::string
{
m_term.enable_raw_mode();
// Add a new string to m_history.
m_history.push_back("");
m_line = m_history.rbegin();
m_insert_char_at = 0;
m_cursor_position = m_term.get_cursor_position();
m_last_was_yank = false;
auto draw_line = [this, prompt]() {
std::cout << "\x1b["
<< m_cursor_position.row << ';'
<< m_cursor_position.col << 'H';
// Clear the screen from current line to the bottom
std::cout << "\r\x1b[J" << prompt << *m_line;
// Put the cursor at the current insertion position
auto cols_left = m_line->size() - m_insert_char_at;
if (cols_left > 0) std::cout << "\x1b[" << cols_left << "D";
std::cout.flush();
};
bool done = false;
while (!done) {
draw_line();
int32_t key = m_term.read_key();
if (key == -1) {
perror("Error: read_key returned '-1'");
continue;
}
else done = process_key(key);
}
m_term.disable_raw_mode();
return *m_line;
}
inline auto TermHandle::read_key() const -> std::int32_t
{
auto read_byte = []() {
char byte;
if (read(STDIN_FILENO, &byte, 1) != 1) {
perror("Error: read failed while trying to read a byte");
exit(EXIT_FAILURE);
} else return byte;
};
char seq[4];
seq[0] = read_byte();
if (seq[0] != '\x1b') return seq[0];
seq[1] = read_byte();
switch (seq[1]) {
case 'f' : return ALT_f;
case 'b' : return ALT_b;
case 'd' : return ALT_d;
case 'l' : return ALT_l;
case 'u' : return ALT_u;
case 'c' : return ALT_c;
case 't' : return ALT_t;
case 'y' : return ALT_y;
case '[' :
seq[2] = read_byte();
if (seq[2]>='0' && seq[2]<='9')
{
seq[3] = read_byte();
if (seq[3] == '~') {
// \x1b [ ? ~
switch (seq[2]) {
case '1': return HOME_KEY;
case '3': return DEL_KEY;
case '4': return END_KEY;
case '5': return PAGE_UP;
case '6': return PAGE_DOWN;
case '7': return HOME_KEY;
case '8': return END_KEY;
}
}
}
else {
// \x1b [ ?
switch (seq[2]) {
case 'A': return ARROW_UP;
case 'B': return ARROW_DOWN;
case 'C': return ARROW_RIGHT;
case 'D': return ARROW_LEFT;
case 'H': return HOME_KEY;
case 'F': return END_KEY;
}
}
default: return '\x1b';
}
}
inline auto TermHandle::get_cursor_position() const -> Position
{
char buff[32];
size_t pos = 0;
// \x1b[6n query for cursor position.
if (write(STDOUT_FILENO, "\x1b[6n", 4) < 4) {
perror("Error: write failed in get_cursor_position");
exit(EXIT_FAILURE);
}
while (pos < sizeof(buff)) {
if (read(STDIN_FILENO, buff + pos, 1) == -1) {
perror("Error: read failed in get_cursor_position");
exit(EXIT_FAILURE);
}
if (buff[pos++] == 'R') break;
}
buff[pos] = '\0';
Position cursor_pos;
sscanf(buff, "\x1b[%ud;%udR", &cursor_pos.row, &cursor_pos.col);
return cursor_pos;
}
inline auto LineReader::process_key(int key) -> bool
{
// Return 'true' to quit, 'false' to continue processing more keys.
if (key != CTRL_KEY('y') && key != ALT_y)
m_last_was_yank = false;
switch (key) {
case ENTER_KEY:
if (m_line->empty()) {
m_history.pop_back();
m_cursor_position = m_term.get_cursor_position();
}
// return from readline
std::cout << "\r\n";
return true;
case CTRL_KEY('h'):
case BACKSPACE:
if (m_insert_char_at > 0)
m_line->erase(--m_insert_char_at, 1);
break;
case DEL_KEY:
case CTRL_KEY('d'):
if (m_line->empty()) {
m_good = false;
m_term.disable_raw_mode();
close(STDIN_FILENO);
return true; // end the loop
}
if (m_insert_char_at < m_line->size())
m_line->erase(m_insert_char_at, 1);
break;
case CTRL_KEY('c'):
// Discard the current line.
std::cout << "\x1b[31m" "^C" "\x1b[m\n";
m_cursor_position = m_term.get_cursor_position();
m_line->clear();
m_insert_char_at = 0;
break;
case CTRL_KEY('l'):
m_cursor_position.row = 1;
break;
case HOME_KEY:
case CTRL_KEY('a'):
m_insert_char_at = 0;
break;
case END_KEY:
case CTRL_KEY('e'):
m_insert_char_at = m_line->size();
break;
case ARROW_LEFT:
case CTRL_KEY('b'):
if (m_insert_char_at > 0)
--m_insert_char_at;
break;
case ARROW_RIGHT:
case CTRL_KEY('f'):
if (m_insert_char_at < m_line->size())
++m_insert_char_at;
break;
case ARROW_DOWN:
case CTRL_KEY('n'):
if (m_line != m_history.rbegin()) {
--m_line;
m_insert_char_at = m_line->size();
}
break;
case ARROW_UP:
case CTRL_KEY('p'):
if (m_line != m_history.rend()-1) {
++m_line;
m_insert_char_at = m_line->size();
}
break;
case ALT_f:
{
auto i = m_line->find_first_not_of(delimeters, m_insert_char_at);
if (i != std::string::npos)
i = m_line->find_first_of(delimeters, i+1);
m_insert_char_at = (i != std::string::npos) ? i:m_line->size();
}
break;
case ALT_b:
{
if (m_insert_char_at == 0) break;
auto i = m_line->find_last_not_of(delimeters, m_insert_char_at - 1);
if (i != std::string::npos)
i = m_line->find_last_of(delimeters, i);
m_insert_char_at = (i != std::string::npos) ? ++i : 0;
}
break;
case ALT_d:
{
auto i = m_line->find_first_not_of(delimeters, m_insert_char_at);
if (i != std::string::npos)
i = m_line->find_first_of(delimeters, i+1);
auto j = (i != std::string::npos) ? i:m_line->size();
m_line->erase(m_insert_char_at, j-m_insert_char_at);
}
break;
case ALT_l:
{
auto i = m_line->find_first_not_of(delimeters, m_insert_char_at);
if (i == std::string::npos)
break;
auto j = m_line->find_first_of(delimeters, i+1);
if (j == std::string::npos) j = m_line->size();
for (auto t=i; t<j; ++t) {m_line->at(t) = tolower(m_line->at(t));};
m_insert_char_at = j;
}
break;
case ALT_u:
{
auto i = m_line->find_first_not_of(delimeters, m_insert_char_at);
if (i == std::string::npos)
break;
auto j = m_line->find_first_of(delimeters, i+1);
if (j == std::string::npos) j = m_line->size();
for (auto t=i; t<j; ++t) {m_line->at(t) = toupper(m_line->at(t));};
m_insert_char_at = j;
}
break;
case ALT_c:
{
auto i = m_line->find_first_not_of(delimeters, m_insert_char_at);
if (i == std::string::npos)
break;
m_line->at(i) = toupper(m_line->at(i));
auto j = m_line->find_first_of(delimeters, i+1);
if (j == std::string::npos) j = m_line->size();
for (auto t=i+1; t<j; ++t) {m_line->at(t) = tolower(m_line->at(t));};
m_insert_char_at = j;
}
break;
case CTRL_KEY('t'):
if (m_insert_char_at != 0 && m_line->size() > 1) {
if (m_insert_char_at == m_line->size()) {
char c = m_line->at(m_insert_char_at-2);
m_line->at(m_insert_char_at - 2) = m_line->at(m_insert_char_at - 1);
m_line->at(m_insert_char_at - 1) = c;
} else {
char c = m_line->at(m_insert_char_at-1);
m_line->at(m_insert_char_at - 1) = m_line->at(m_insert_char_at);
m_line->at(m_insert_char_at) = c;
++m_insert_char_at;
}
}
break;
case ALT_t:
if (m_insert_char_at != 0 && m_insert_char_at != m_line->size() &&
m_line->size() > 2) {
// r for right, and l for left hand side word
size_t r_start, r_end, l_start, l_end;
if (std::isspace(m_line->at(m_insert_char_at))) {
r_start = m_line->find_first_not_of(delimeters, m_insert_char_at);
if (r_start == std::string::npos) break;
} else {
r_start = m_line->find_last_of(delimeters, m_insert_char_at);
if (r_start == std::string::npos) break;
else r_start++;
}
r_end = m_line->find_first_of(delimeters, r_start);
if (r_end == std::string::npos) r_end = m_line->size();
else r_end--;
l_end = m_line->find_last_not_of(delimeters, r_start-1);
if (l_end == std::string::npos) break;
l_start = m_line->find_last_of(delimeters, l_end);
if (l_start == std::string::npos) l_start = 0;
else l_start++;
auto wr = m_line->substr(r_start, r_end - r_start + 1);
auto wl = m_line->substr(l_start, l_end - l_start + 1);
m_line->erase(r_start, wr.size());
m_line->insert(r_start, wl, 0, wl.size());
m_line->erase(l_start, wl.size());
m_line->insert(l_start, wr, 0, wr.size());
m_insert_char_at = r_start + wr.size();
}
break;
case CTRL_KEY('k'):
{
auto killed_text =
m_line->substr(m_insert_char_at, m_line->size() - m_insert_char_at);
m_killring.push_back(killed_text);
m_current_kill = m_killring.rbegin();
m_line->erase(m_insert_char_at, m_line->size() - m_insert_char_at);
}
break;
case CTRL_KEY('u'):
{
auto killed_text = m_line->substr(0, m_insert_char_at);
m_killring.push_back(killed_text);
m_current_kill = m_killring.rbegin();
m_line->erase(0, m_insert_char_at);
m_insert_char_at = 0;
}
break;
case CTRL_KEY('y'):
if (m_killring.empty()) break;
m_line->insert(m_insert_char_at, *m_current_kill);
m_insert_char_at += m_current_kill->size();
m_last_was_yank = true;
break;
case ALT_y:
if (!m_last_was_yank || m_killring.size() == 1)
break;
m_insert_char_at -= m_current_kill->size();
m_line->erase(m_insert_char_at, m_current_kill->size());
++m_current_kill;
if (m_current_kill == m_killring.rend())
m_current_kill = m_killring.rbegin();
m_line->insert(m_insert_char_at, *m_current_kill);
m_insert_char_at += m_current_kill->size();
break;
default:
// Insert non-control characters to the current line at 'm_insert_char_at' position.
if (!iscntrl(key)) {
if (m_insert_char_at >= 0 and m_insert_char_at < m_line->size()) {
m_line->insert(m_line->begin() + m_insert_char_at, key);
} else if (m_insert_char_at == m_line->size()) {
m_line->push_back(key);
}
m_insert_char_at++;
}
}
return false;
}
LineReader::LineReader(const char *historypath) {
m_historypath = historypath;
auto history_file = std::ifstream(historypath);
if (history_file) {
std::string hist_line;
while (history_file) {
std::getline(history_file, hist_line);
if (!hist_line.empty()) m_history.push_back(hist_line);
}
}
}
LineReader::~LineReader() {
if (m_historypath != nullptr) {
auto history_file = std::ofstream(m_historypath);
if (history_file) {
for (const auto& hist_lin: m_history)
history_file << hist_lin << '\n';
history_file.close();
}
}
}
| 26.440605
| 88
| 0.611746
|
px86
|
8ad24bf0de4c4a683c9d6568ba43b091a7658883
| 3,500
|
cpp
|
C++
|
tests/operators/glob.cpp
|
shlyamster/sqlite_orm
|
a6c07b588a173f93c9a818371dd07c199442791d
|
[
"BSD-3-Clause"
] | 1
|
2021-12-27T15:23:13.000Z
|
2021-12-27T15:23:13.000Z
|
tests/operators/glob.cpp
|
shlyamster/sqlite_orm
|
a6c07b588a173f93c9a818371dd07c199442791d
|
[
"BSD-3-Clause"
] | null | null | null |
tests/operators/glob.cpp
|
shlyamster/sqlite_orm
|
a6c07b588a173f93c9a818371dd07c199442791d
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* Obtained from here https://www.tutlane.com/tutorial/sqlite/sqlite-glob-operator
*/
#include <sqlite_orm/sqlite_orm.h>
#include <catch2/catch.hpp>
#include <vector> // std::vector
#include <algorithm> // std::find_if, std::count
using namespace sqlite_orm;
TEST_CASE("Glob") {
struct Employee {
int id = 0;
std::string firstName;
std::string lastName;
float salary = 0;
int deptId = 0;
};
auto storage = make_storage({},
make_table("emp_master",
make_column("emp_id", &Employee::id, primary_key(), autoincrement()),
make_column("first_name", &Employee::firstName),
make_column("last_name", &Employee::lastName),
make_column("salary", &Employee::salary),
make_column("dept_id", &Employee::deptId)));
storage.sync_schema();
std::vector<Employee> employees = {
Employee{1, "Honey", "Patel", 10100, 1},
Employee{2, "Shweta", "Jariwala", 19300, 2},
Employee{3, "Vinay", "Jariwala", 35100, 3},
Employee{4, "Jagruti", "Viras", 9500, 2},
Employee{5, "Shweta", "Rana", 12000, 3},
Employee{6, "sonal", "Menpara", 13000, 1},
Employee{7, "Yamini", "Patel", 10000, 2},
Employee{8, "Khyati", "Shah", 500000, 3},
Employee{9, "Shwets", "Jariwala", 19400, 2},
};
storage.replace_range(employees.begin(), employees.end());
auto expectIds = [](const std::vector<Employee> &employees, const std::vector<decltype(Employee::id)> ids) {
for(auto expectedId: ids) {
REQUIRE(find_if(employees.begin(), employees.end(), [expectedId](auto &employee) {
return employee.id == expectedId;
}) != employees.end());
}
return false;
};
{
auto employees = storage.get_all<Employee>(where(glob(&Employee::salary, "1*")));
REQUIRE(employees.size() == 6);
expectIds(employees, {1, 2, 5, 6, 7, 9});
}
{
auto employees = storage.get_all<Employee>(where(glob(&Employee::firstName, "Shwet?")));
REQUIRE(employees.size() == 3);
expectIds(employees, {2, 5, 9});
}
{
auto employees = storage.get_all<Employee>(where(glob(&Employee::lastName, "[A-J]*")));
REQUIRE(employees.size() == 3);
expectIds(employees, {2, 3, 9});
}
{
auto employees = storage.get_all<Employee>(where(glob(&Employee::lastName, "[^A-J]*")));
REQUIRE(employees.size() == 6);
expectIds(employees, {1, 4, 5, 6, 7, 8});
}
{
auto rows = storage.select(glob(&Employee::firstName, "S*"));
REQUIRE(rows.size() == 9);
auto trueValuesCount = std::count(rows.begin(), rows.end(), true);
REQUIRE(trueValuesCount == 3);
}
{
auto rows = storage.select(glob(distinct(&Employee::firstName), "S*"));
REQUIRE(rows.size() == 2);
auto trueValuesCount = std::count(rows.begin(), rows.end(), true);
REQUIRE(trueValuesCount == 1);
}
{
auto rows = storage.select(columns(not glob(&Employee::firstName, "S*")));
REQUIRE(rows.size() == 9);
auto trueValuesCount = std::count(rows.begin(), rows.end(), std::tuple<bool>{true});
REQUIRE(trueValuesCount == 6);
}
}
| 39.325843
| 112
| 0.542
|
shlyamster
|
e9d732db267539b08f646e55fea4cf543af7a048
| 1,785
|
cc
|
C++
|
daemon/cmdline.cc
|
BenHuddleston/kv_engine
|
78123c9aa2c2feb24b7c31eecc862bf2ed6325e4
|
[
"MIT",
"BSD-3-Clause"
] | 104
|
2017-05-22T20:41:57.000Z
|
2022-03-24T00:18:34.000Z
|
daemon/cmdline.cc
|
BenHuddleston/kv_engine
|
78123c9aa2c2feb24b7c31eecc862bf2ed6325e4
|
[
"MIT",
"BSD-3-Clause"
] | 3
|
2017-11-14T08:12:46.000Z
|
2022-03-03T11:14:17.000Z
|
daemon/cmdline.cc
|
BenHuddleston/kv_engine
|
78123c9aa2c2feb24b7c31eecc862bf2ed6325e4
|
[
"MIT",
"BSD-3-Clause"
] | 71
|
2017-05-22T20:41:59.000Z
|
2022-03-29T10:34:32.000Z
|
/*
* Copyright 2021-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#include "cmdline.h"
#include "config_parse.h"
#include "memcached.h"
#include "settings.h"
#include <getopt.h>
#include <iostream>
#include <vector>
static std::string config_file;
static void usage() {
std::cerr << "memcached " << get_server_version() << R"(
-C file Read configuration from file
-h print this help and exit
)";
}
void parse_arguments(int argc, char** argv) {
const std::vector<option> options = {
{"config", required_argument, nullptr, 'C'},
{"help", no_argument, nullptr, 'h'},
{nullptr, 0, nullptr, 0}};
int cmd;
// Tell getopt to restart the parsing (if we used getopt before calling
// this method)
optind = 1;
while ((cmd = getopt_long(argc, argv, "C:h", options.data(), nullptr)) !=
EOF) {
switch (cmd) {
case 'C':
config_file = optarg;
break;
case 'h':
usage();
std::exit(EXIT_SUCCESS);
default:
usage();
std::exit(EXIT_FAILURE);
}
}
if (config_file.empty()) {
std::cerr << "Configuration file must be specified with -C"
<< std::endl;
std::exit(EXIT_FAILURE);
}
load_config_file(config_file, Settings::instance());
}
const std::string& get_config_file() {
return config_file;
}
| 25.869565
| 78
| 0.594398
|
BenHuddleston
|
e9d89881e76248c58c7aaedebc10be0c0534fc2e
| 934
|
cpp
|
C++
|
LiberoEngine/src/IComponent.cpp
|
Kair0z/LiberoEngine2D
|
79fb93d7bbb5f5e6b805da6826c64ffa520989c3
|
[
"MIT"
] | null | null | null |
LiberoEngine/src/IComponent.cpp
|
Kair0z/LiberoEngine2D
|
79fb93d7bbb5f5e6b805da6826c64ffa520989c3
|
[
"MIT"
] | null | null | null |
LiberoEngine/src/IComponent.cpp
|
Kair0z/LiberoEngine2D
|
79fb93d7bbb5f5e6b805da6826c64ffa520989c3
|
[
"MIT"
] | null | null | null |
#include "PCH.h"
#include "IComponent.h"
#include "LiberoECS_EntityMaster.h"
namespace Libero
{
const ComponentID IComponent::GetID() const
{
return m_ID;
}
const EntityID IComponent::GetOwner() const
{
return m_Owner;
}
IEntity* IComponent::GetOwnerEntity() const
{
if (!m_pEntityMasterRef) return nullptr;
return m_pEntityMasterRef->GetEntity(GetOwner());
}
void IComponent::SetActive(bool active)
{
m_IsActive = active;
}
bool IComponent::IsActive() const
{
return m_IsActive;
}
const bool IComponent::operator==(const IComponent& other) const
{
return !(*this != other);
}
const bool IComponent::operator!=(const IComponent& other) const
{
if (m_ID != other.m_ID) return true;
if (m_Owner != other.m_Owner) return true;
return false;
}
std::ofstream& IComponent::ToFile(std::ofstream& ofs) const
{
ofs << "- Unwritten Component: TODO... \n";
ofs << "\n";
return ofs;
}
}
| 17.622642
| 65
| 0.687366
|
Kair0z
|
e9defe1ad3ba9ffbca335060dec63dec5ac82040
| 1,671
|
cpp
|
C++
|
demboyz/netmessages/svc_getcvarvalue.cpp
|
juniorsgithub/demboyz
|
73ba4f105e5670ab07334e867a3f57fb1de2ff55
|
[
"MIT"
] | 42
|
2015-09-24T01:14:26.000Z
|
2021-12-25T14:28:40.000Z
|
demboyz/netmessages/svc_getcvarvalue.cpp
|
juniorsgithub/demboyz
|
73ba4f105e5670ab07334e867a3f57fb1de2ff55
|
[
"MIT"
] | 3
|
2015-10-11T17:51:07.000Z
|
2018-07-14T01:04:05.000Z
|
demboyz/netmessages/svc_getcvarvalue.cpp
|
juniorsgithub/demboyz
|
73ba4f105e5670ab07334e867a3f57fb1de2ff55
|
[
"MIT"
] | 12
|
2015-07-16T02:26:34.000Z
|
2021-09-13T23:29:36.000Z
|
#include "svc_getcvarvalue.h"
#include "base/bitfile.h"
#include "base/jsonfile.h"
namespace NetHandlers
{
bool SVC_GetCvarValue_BitRead_Internal(BitRead& bitbuf, SourceGameContext& context, NetMsg::SVC_GetCvarValue* data)
{
data->cookie = bitbuf.ReadSBitLong(32);
bitbuf.ReadString(data->cvarName, sizeof(data->cvarName));
return !bitbuf.IsOverflowed();
}
bool SVC_GetCvarValue_BitWrite_Internal(BitWrite& bitbuf, const SourceGameContext& context, NetMsg::SVC_GetCvarValue* data)
{
bitbuf.WriteSBitLong(data->cookie, 32);
bitbuf.WriteString(data->cvarName);
return !bitbuf.IsOverflowed();
}
bool SVC_GetCvarValue_JsonRead_Internal(JsonRead& jsonbuf, SourceGameContext& context, NetMsg::SVC_GetCvarValue* data)
{
base::JsonReaderObject reader = jsonbuf.ParseObject();
assert(!reader.HasReadError());
data->cookie = reader.ReadInt32("cookie");
reader.ReadString("cvarName", data->cvarName, sizeof(data->cvarName));
return !reader.HasReadError();
}
bool SVC_GetCvarValue_JsonWrite_Internal(JsonWrite& jsonbuf, const SourceGameContext& context, NetMsg::SVC_GetCvarValue* data)
{
jsonbuf.Reset();
jsonbuf.StartObject();
jsonbuf.WriteInt32("cookie", data->cookie);
jsonbuf.WriteString("cvarName", data->cvarName);
jsonbuf.EndObject();
return jsonbuf.IsComplete();
}
void SVC_GetCvarValue_ToString_Internal(std::ostringstream& out, NetMsg::SVC_GetCvarValue* data)
{
out << "svc_GetCvarValue: cvar: " << data->cvarName
<< ", cookie: " << data->cookie;
}
}
| 35.553191
| 130
| 0.681029
|
juniorsgithub
|
e9e063d717b44e77c25c9861ddaa856f0258c513
| 768
|
cpp
|
C++
|
source/circle.cpp
|
Vani4ka/programmiersprachen_aufgabenblatt_4
|
f1171f2c274f2d503691932a20fd0a31bc2f6ded
|
[
"MIT"
] | null | null | null |
source/circle.cpp
|
Vani4ka/programmiersprachen_aufgabenblatt_4
|
f1171f2c274f2d503691932a20fd0a31bc2f6ded
|
[
"MIT"
] | null | null | null |
source/circle.cpp
|
Vani4ka/programmiersprachen_aufgabenblatt_4
|
f1171f2c274f2d503691932a20fd0a31bc2f6ded
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "circle.hpp"
#include <math.h>
#include <cmath>
Circle::Circle(Vec2 const& c, float r):
center_{c},
radius_{r},
color_{{0.0}}
{}
Circle::Circle(Vec2 const& c, float r, Color const& col):
center_{c},
radius_{r},
color_{col}
{}
Vec2 Circle::getCenter() const {
return center_;
}
float Circle::getRadius() const {
return radius_;
}
bool operator<( Circle const& c1 , Circle const& c2 ) {
if(c1.getRadius()<c2.getRadius()) {
return true;
}
else return false;
}
bool operator>( Circle const& c1 , Circle const& c2 ) {
if(c1.getRadius()>c2.getRadius()) {
return true;
}
else return false;
}
bool operator==( Circle const& c1 , Circle const& c2 ) {
if (c1.getRadius()==c2.getRadius())
{
return true;
}
else return false;
}
| 17.066667
| 57
| 0.66276
|
Vani4ka
|
e9e254b9a80e5608f03e319cceb11e38dedd2cdb
| 7,869
|
hpp
|
C++
|
src/include/libmath/CVector2.hpp
|
pedrospeixoto/sweet
|
224248181e92615467c94b4e163596017811b5eb
|
[
"MIT"
] | null | null | null |
src/include/libmath/CVector2.hpp
|
pedrospeixoto/sweet
|
224248181e92615467c94b4e163596017811b5eb
|
[
"MIT"
] | null | null | null |
src/include/libmath/CVector2.hpp
|
pedrospeixoto/sweet
|
224248181e92615467c94b4e163596017811b5eb
|
[
"MIT"
] | 1
|
2019-03-27T01:17:59.000Z
|
2019-03-27T01:17:59.000Z
|
/*
* Copyright 2010 Martin Schreiber
*
* 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.
*
* Author: Martin Schreiber (schreiberx@gmail.com)
*/
/*
* CHANGELOG:
*
* 2008-02-27: martin schreiber
* dist2();
*
* 2008-10-22: martin schreiber
* made some modifications to use generic vector CVector
*
*/
#ifndef __CVECTOR_HH
#error "dont include CVector3.hpp directly!"
#endif
#ifndef __CVECTOR2_HH
#define __CVECTOR2_HH
#include <iostream>
#include <cmath>
/**
* \brief 2D Vector handler
*/
template <typename T>
class CVector<2,T>
{
public:
T data[2]; ///< vector data
/**
* default constructor
*/
inline CVector()
{
setZero();
}
/**
* initialize vector with (x0, x1)
*/
inline CVector(const T x0, const T x1)
{
data[0] = x0;
data[1] = x1;
}
/**
* initialize all vector components with the scalar value 'x'
*/
inline CVector(const T x)
{
data[0] = x;
data[1] = x;
}
/**
* initialize vector components with the array 'v'
*/
inline CVector(const T v[2])
{
data[0] = v[0];
data[1] = v[1];
}
/**
* set all components of vector to 0
*/
inline void setZero()
{
data[0] = T(0);
data[1] = T(0);
}
/**
* return normalized (length=1) vector
*/
inline CVector getNormal()
{
CVector<2,T> v = *this;
T inv_length = 1.0f/sqrtf(v[0]*v[0] + v[1]*v[1]);
v[0] *= inv_length;
v[1] *= inv_length;
return v;
}
/**
* compute and return the dot product of this vector and 'v'
* \return dot product
*/
inline T getDotProd(const CVector<2,T> &v)
{
return v.data[0]*data[0] + v.data[1]*data[1];
}
/**
* compute and return the cross product of this vector and 'a'
* \return cross product
*/
inline T getCrossProd(CVector<2,T> &a)
{
return data[0]*a.data[1] - data[1]*a.data[0];
}
/**
* return elements in cube.
* e.g. if the vector components give the resolution of a cube, this function returns the number of cells
*/
inline T elements()
{
return (data[0]*data[1]);
}
/**
* return length of vector
*/
inline T length()
{
return std::sqrt(data[0]*data[0] + data[1]*data[1]);
}
/**
* return (length*length) of vector
*/
inline T length2()
{
return data[0]*data[0] + data[1]*data[1];
}
/**
* return square distance to other point
*/
inline T dist2(const CVector<2,T> &v)
{
CVector<2,T> d = CVector<2,T>(v.data[0] - data[0], v.data[1] - data[1]);
return (d[0]*d[0] + d[1]*d[1]);
}
/**
* return distance to other point
*/
inline T dist(const CVector<2,T> &v)
{
CVector<2,T> d = CVector<2,T>(v.data[0] - data[0], v.data[1] - data[1]);
return sqrtf(d[0]*d[0] + d[1]*d[1]);
}
/**
* normalize the vector
*/
inline void normalize()
{
T il = 1/length();
data[0] *= il;
data[1] *= il;
}
/**
* clamp to values -1 and 1
*/
inline void clamp1_1()
{
data[0] = (data[0] < -1 ? -1 : (data[0] > 1 ? 1 : data[0]));
data[1] = (data[1] < -1 ? -1 : (data[1] > 1 ? 1 : data[1]));
}
/*******************
* OPERATORS
*******************/
/// assign values of a[2] to this vector and return reference to this vector
inline CVector<2,T>& operator=(const T a[2]) { data[0] = a[0]; data[1] = a[1]; return *this; };
/// assign values of vector a to this vector and return reference to this vector
inline CVector<2,T>& operator=(CVector<2,T> const& a) { data[0] = a.data[0]; data[1] = a.data[1]; return *this; };
/// return negative of this vector
inline CVector<2,T> operator-() { return CVector<2,T>(-data[0], -data[1]); }
/// return new vector (this+a)
inline CVector<2,T> operator+(const T a) { return CVector<2,T>(data[0]+a, data[1]+a); }
/// return new vector (this-a)
inline CVector<2,T> operator-(const T a) { return CVector<2,T>(data[0]-a, data[1]-a); }
/// return new vector with component wise (this*a)
inline CVector<2,T> operator*(const T a) { return CVector<2,T>(data[0]*a, data[1]*a); }
/// return new vector with component wise (this/a)
inline CVector<2,T> operator/(const T a) { return CVector<2,T>(data[0]/a, data[1]/a); }
/// add a to this vector and return reference to this vector
inline CVector<2,T>& operator+=(const T a) { data[0] += a; data[1] += a; return *this; }
/// subtract a from this vector and return reference to this vector
inline CVector<2,T>& operator-=(const T a) { data[0] -= a; data[1] -= a; return *this; }
/// multiply each component of this vector with scalar a and return reference to this vector
inline CVector<2,T>& operator*=(const T a) { data[0] *= a; data[1] *= a; return *this; }
/// divide each component of this vector by scalar a and return reference to this vector
inline CVector<2,T>& operator/=(const T a) { data[0] /= a; data[1] /= a; return *this; }
// CVector
/// return new vector with sum of this vector and v
inline CVector<2,T> operator+(const CVector<2,T> &v) { return CVector<2,T>(data[0]+v.data[0], data[1]+v.data[1]); }
/// return new vector with subtraction of vector v from this vector
inline CVector<2,T> operator-(const CVector<2,T> &v) { return CVector<2,T>(data[0]-v.data[0], data[1]-v.data[1]); }
/// return new vector with values of this vector multiplied component wise with vector v
inline CVector<2,T> operator*(const CVector<2,T> &v) { return CVector<2,T>(data[0]*v.data[0], data[1]*v.data[1]); }
/// return new vector with values of this vector divided component wise by components of vector v
inline CVector<2,T> operator/(const CVector<2,T> &v) { return CVector<2,T>(data[0]/v.data[0], data[1]/v.data[1]); }
/// return this vector after adding v
inline CVector<2,T>& operator+=(const CVector<2,T> &v) { data[0] += v.data[0]; data[1] += v.data[1]; return *this; }
/// return this vector after subtracting v
inline CVector<2,T>& operator-=(const CVector<2,T> &v) { data[0] -= v.data[0]; data[1] -= v.data[1]; return *this; }
/// return true, if each component of the vector is equal to the corresponding component of vector v
inline bool operator==(const CVector<2,T> &v) { return bool(data[0] == v.data[0] && data[1] == v.data[1]); }
/// return true, if at lease component of the vector is not equal to the corresponding component of vector v
inline bool operator!=(const CVector<2,T> &v) { return bool(data[0] != v.data[0] || data[1] != v.data[1]); }
/**
* access element i
*/
inline T& operator[](const int i)
{
#if DEBUG
if (i < 0 || i >= 2)
{
std::cerr << "OUT OF ARRAY ACCESS!!! creating null exception..." << std::endl;
*((int*)(0)) = 0;
}
#endif
return data[i];
}
/**
* \brief compare set for sort operation
*/
struct compareSet
{
/**
* compare set operator
*/
inline bool operator()(CVector<2,T> *v1, CVector<2,T> *v2)
{
if ((*v1)[0] != (*v2)[0])
return (*v1)[0] < (*v2)[0];
if ((*v1)[1] != (*v2)[1])
return (*v1)[1] < (*v2)[1];
return false;
}
/**
* compare set operator
*/
inline bool operator()(const CVector<2,T> &v1, const CVector<2,T> &v2)
{
if (v1.data[0] != v2.data[0])
return v1.data[0] < v2.data[0];
if (v1.data[1] != v2.data[1])
return v1.data[1] < v2.data[1];
return false;
}
};
};
typedef CVector<2,double> vec2d;
typedef CVector<2,float> vec2f;
typedef CVector<2,int> vec2i;
template <class T>
inline
::std::ostream&
operator<<(::std::ostream &co, const CVector<2,T> &v)
{
return co << "[" << v.data[0] << ", " << v.data[1] << "]";
}
#endif
| 26.674576
| 118
| 0.617868
|
pedrospeixoto
|
e9e4e388634e975ce798ef203d17f703330834ee
| 2,061
|
hpp
|
C++
|
include/wui/theme/theme_impl.hpp
|
ud84/wui
|
354260df9882c3e582c2a337a4bbb8be6e030e13
|
[
"BSL-1.0"
] | 1
|
2021-12-18T16:38:30.000Z
|
2021-12-18T16:38:30.000Z
|
include/wui/theme/theme_impl.hpp
|
ud84/wui
|
354260df9882c3e582c2a337a4bbb8be6e030e13
|
[
"BSL-1.0"
] | null | null | null |
include/wui/theme/theme_impl.hpp
|
ud84/wui
|
354260df9882c3e582c2a337a4bbb8be6e030e13
|
[
"BSL-1.0"
] | null | null | null |
//
// Copyright (c) 2021-2022 Anton Golovkov (udattsk at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/ud84/wui
//
#pragma once
#include <wui/theme/i_theme.hpp>
#include <map>
namespace wui
{
class theme_impl : public i_theme
{
public:
theme_impl(const std::string &name);
virtual std::string get_name() const;
virtual void set_color(const std::string &control, const std::string &value, color color_);
virtual color get_color(const std::string &control, const std::string &value) const;
virtual void set_dimension(const std::string &control, const std::string &value, int32_t dimension);
virtual int32_t get_dimension(const std::string &control, const std::string &value) const;
virtual void set_string(const std::string &control, const std::string &value, const std::string &str);
virtual const std::string &get_string(const std::string &control, const std::string &value) const;
virtual void set_font(const std::string &control, const std::string &value, const font &font_);
virtual font get_font(const std::string &control, const std::string &value) const;
virtual void set_image(const std::string &name, const std::vector<uint8_t> &data);
virtual const std::vector<uint8_t> &get_image(const std::string &name);
#ifdef _WIN32
virtual void load_resource(int32_t resource_index, const std::string &resource_section);
#endif
virtual void load_json(const std::string &json);
virtual void load_file(const std::string &file_name);
virtual void load_theme(const i_theme &theme_);
virtual bool is_ok() const;
private:
std::string name;
std::map<std::string, int32_t> ints;
std::map<std::string, std::string> strings;
std::map<std::string, font> fonts;
std::map<std::string, std::vector<uint8_t>> imgs;
std::string dummy_string;
std::vector<uint8_t> dummy_image;
bool ok;
};
}
| 31.707692
| 106
| 0.716157
|
ud84
|
e9e5000faa8a69367e000cbb2c571573836a9eda
| 1,179
|
cpp
|
C++
|
30.substring-with-concatenation-of-all-words.161398902.ac.cpp
|
blossom2017/Leetcode
|
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
|
[
"Apache-2.0"
] | null | null | null |
30.substring-with-concatenation-of-all-words.161398902.ac.cpp
|
blossom2017/Leetcode
|
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
|
[
"Apache-2.0"
] | null | null | null |
30.substring-with-concatenation-of-all-words.161398902.ac.cpp
|
blossom2017/Leetcode
|
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> ans;
if(s.length()==0||words.size()==0)return ans;
int len = words[0].length();
unordered_map<string,int>mp;
for(int i=0;i<words.size();i++)mp[words[i]]++;
int n = s.length();
int num = words.size();
for(int i=0;i<n-len*num+1;i++)
{
unordered_map<string,int> seen;
int j=0;
// cout<<"nnn"<<endl;
while(j<num)
{
string t = s.substr(i+j*len,len);
// cout<<t<<endl;
if(mp.find(t)!=mp.end())
{
// cout<<"hhh";
seen[t]++;
// cout<<seen[t]<<" ";
if(seen[t]>mp[t])break;
}
else
{
// cout<<"jjjj";
break;
}
j++;
}
if(j==num)ans.push_back(i);
}
return ans;
}
};
| 24.5625
| 64
| 0.336726
|
blossom2017
|
e9e62f7c86944755dd76b27b8f9776653deb0b4c
| 4,630
|
cpp
|
C++
|
SharedMemory_ut.cpp
|
jfern2011/SharedMemory
|
4b481b437159b6832c3095b49a182088e801cb74
|
[
"MIT"
] | null | null | null |
SharedMemory_ut.cpp
|
jfern2011/SharedMemory
|
4b481b437159b6832c3095b49a182088e801cb74
|
[
"MIT"
] | null | null | null |
SharedMemory_ut.cpp
|
jfern2011/SharedMemory
|
4b481b437159b6832c3095b49a182088e801cb74
|
[
"MIT"
] | null | null | null |
#include <csignal>
#include <cstdlib>
#include <iostream>
#include <utility>
#include <vector>
#include "util.h"
#include "SharedMemory.h"
bool sigint_raised = false;
void sig_hander(int num)
{
std::printf("caught signal [%d]. exiting...\n", num);
std::fflush(stdout);
sigint_raised = true;
}
namespace SharedMemory
{
class MemoryManger_ut
{
public:
MemoryManger_ut()
{
}
~MemoryManger_ut()
{
}
int allocate(size_t size)
{
int id = _manager.allocate(size);
if (id == -1)
{
std::printf("Not enough space. \n");
std::fflush(stdout);
}
else
print();
return id;
}
void free(int id)
{
if (!_manager.free(id))
{
std::printf("Invalid ID: %d\n", id);
std::fflush(stdout);
}
else
print();
}
bool init(void* addr, size_t size)
{
AbortIfNot(_manager.init(addr, size),
false);
_buf_size = size;
return true;
}
void print()
{
auto in_use = _manager._in_use;
auto vacant = _manager._vacant;
auto all = in_use;
all.insert(all.end(), vacant.begin(), vacant.end());
for (auto iter = all.begin(), end = all.end();
iter != end; ++iter)
{
std::printf(" | %2d: %2lu",iter->id,iter->size);
}
std::printf(" |\n");
std::fflush(stdout);
}
bool run()
{
while (true)
{
std::cout << "> "; std::fflush(stdout);
char _input[256];
std::cin.getline(_input, 256);
std::string input(_input);
Util::str_v args;
Util::split(input, args);
if (Util::trim(args[0]) == "allocate")
{
if (args.size() < 2)
std::cout << "usage: allocate <size>" << std::endl;
else
{
int size = Util::str_to_int32(args[1],10);
if (errno == 0)
{
allocate(static_cast<size_t>(size));
}
else
{
std::cout << "cannot convert " << args[1]
<< std::endl;
errno = 0;
}
}
}
else if (Util::trim(args[0]) == "free")
{
if (args.size() < 2)
std::cout << "usage: free <id>" << std::endl;
else
{
int id = Util::str_to_int32(args[1],10);
if (errno == 0)
{
free(id);
}
else
{
std::cout << "cannot convert " << args[1]
<< std::endl;
errno = 0;
}
}
}
else if (Util::trim(args[0]) == "quit")
break;
else
std::cout << "unknown command: " << args[0]
<< std::endl;
}
return true;
}
private:
size_t _buf_size;
SharedMemory::MemoryManager
_manager;
};
}
bool run_MemoryManager_ut(int argc, char** argv)
{
SharedMemory::MemoryManger_ut test;
void* addr = NULL;
if (argc > 1)
{
int size = Util::str_to_int32(argv[1],10);
if (errno == 0)
{
addr = std::malloc(size);
if (addr == NULL)
std::cout << "error: malloc()" << std::endl;
else
{
test.init(addr, size);
test.run();
std::free(addr);
}
}
else
std::cout << "errno = " << errno
<< std::endl;
}
else
std::cout << "usage: " << argv[0] << " <pool size>"
<< std::endl;
return true;
}
int main(int argc, char** argv)
{
//run_MemoryManager_ut(argc, argv);
SharedMemory::RemoteMemory remote1, remote2;
AbortIfNot(remote1.create("test1",
SharedMemory::read_write,
10),
false);
AbortIfNot(remote2.create("test2",
SharedMemory::read_only,
10),
false);
//std::signal(SIGINT, &sig_hander);
while (!sigint_raised)
{
std::cout << "> "; std::fflush(stdout);
char _input[256];
std::cin.getline(_input, 256);
std::string input(_input);
Util::str_v args;
Util::split(input, args);
if (Util::trim(args[0]) == "write")
{
if (args.size() < 2)
std::cout << "usage: write <data>" << std::endl;
else
{
// Clients read from this
AbortIfNot(remote2.write(args[1].c_str(),
args[1].size()), 1);
}
}
else if (Util::trim(args[0]) == "read")
{
if (args.size() < 2)
std::cout << "usage: read <data>" << std::endl;
else
{
int size = Util::str_to_int32(args[1],10);
if (errno == 0)
{
char *data = static_cast<char*>(std::malloc(size+1));
AbortIf(data == NULL, 1);
// Clients write to this
AbortIfNot(remote1.read(data, size), 1);
data[size] = '\0';
std::printf("received '%s'\n", data);
std::fflush(stdout);
std::free(data);
}
else
{
std::cout << "cannot convert " << args[1]
<< std::endl;
errno = 0;
}
}
}
else if (Util::trim(args[0]) == "quit")
{
break;
}
else
std::cout << "unknown command: " << args[0]
<< std::endl;
}
return 0;
}
| 17.471698
| 58
| 0.534125
|
jfern2011
|
e9e702d3b43f911b547cbb1a5951222ae323cc31
| 645
|
cpp
|
C++
|
1400/50/1459a.cpp
|
actium/cf
|
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
|
[
"Unlicense"
] | 1
|
2020-07-03T15:55:52.000Z
|
2020-07-03T15:55:52.000Z
|
1400/50/1459a.cpp
|
actium/cf
|
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
|
[
"Unlicense"
] | null | null | null |
1400/50/1459a.cpp
|
actium/cf
|
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
|
[
"Unlicense"
] | 3
|
2020-10-01T14:55:28.000Z
|
2021-07-11T11:33:58.000Z
|
#include <iostream>
#include <string>
void answer(size_t v)
{
constexpr const char* s[3] = { "EQUAL", "BLUE", "RED" };
std::cout << s[v] << '\n';
}
void solve(const std::string& r, const std::string& b)
{
const size_t n = r.length();
unsigned kr = 0, kb = 0;
for (size_t i = 0; i < n; ++i) {
kr += (r[i] > b[i]);
kb += (b[i] > r[i]);
}
answer((kr != kb) + (kr > kb));
}
void test_case()
{
size_t n;
std::cin >> n;
std::string r, b;
std::cin >> r >> b;
solve(r, b);
}
int main()
{
size_t t;
std::cin >> t;
while (t-- > 0)
test_case();
return 0;
}
| 14.333333
| 60
| 0.458915
|
actium
|
e9e9385a5a8431fa61ce9b7951c11f58af218a45
| 22,672
|
cpp
|
C++
|
nfc/src/DOOM/neo/renderer/RenderWorld_defs.cpp
|
1337programming/leviathan
|
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
|
[
"Apache-2.0"
] | null | null | null |
nfc/src/DOOM/neo/renderer/RenderWorld_defs.cpp
|
1337programming/leviathan
|
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
|
[
"Apache-2.0"
] | null | null | null |
nfc/src/DOOM/neo/renderer/RenderWorld_defs.cpp
|
1337programming/leviathan
|
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
|
[
"Apache-2.0"
] | null | null | null |
/*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code 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 Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#pragma hdrstop
#include "../idlib/precompiled.h"
#include "tr_local.h"
/*
=================================================================================
ENTITY DEFS
=================================================================================
*/
/*
=================
R_DeriveEntityData
=================
*/
void R_DeriveEntityData( idRenderEntityLocal * entity ) {
R_AxisToModelMatrix( entity->parms.axis, entity->parms.origin, entity->modelMatrix );
idRenderMatrix::CreateFromOriginAxis( entity->parms.origin, entity->parms.axis, entity->modelRenderMatrix );
// calculate the matrix that transforms the unit cube to exactly cover the model in world space
idRenderMatrix::OffsetScaleForBounds( entity->modelRenderMatrix, entity->localReferenceBounds, entity->inverseBaseModelProject );
// calculate the global model bounds by inverse projecting the unit cube with the 'inverseBaseModelProject'
idRenderMatrix::ProjectedBounds( entity->globalReferenceBounds, entity->inverseBaseModelProject, bounds_unitCube, false );
}
/*
===================
R_FreeEntityDefDerivedData
Used by both FreeEntityDef and UpdateEntityDef
Does not actually free the entityDef.
===================
*/
void R_FreeEntityDefDerivedData( idRenderEntityLocal *def, bool keepDecals, bool keepCachedDynamicModel ) {
// demo playback needs to free the joints, while normal play
// leaves them in the control of the game
if ( common->ReadDemo() ) {
if ( def->parms.joints ) {
Mem_Free16( def->parms.joints );
def->parms.joints = NULL;
}
if ( def->parms.callbackData ) {
Mem_Free( def->parms.callbackData );
def->parms.callbackData = NULL;
}
for ( int i = 0; i < MAX_RENDERENTITY_GUI; i++ ) {
if ( def->parms.gui[ i ] ) {
delete def->parms.gui[ i ];
def->parms.gui[ i ] = NULL;
}
}
}
// free all the interactions
while ( def->firstInteraction != NULL ) {
def->firstInteraction->UnlinkAndFree();
}
def->dynamicModelFrameCount = 0;
// clear the dynamic model if present
if ( def->dynamicModel ) {
def->dynamicModel = NULL;
}
if ( !keepDecals ) {
R_FreeEntityDefDecals( def );
R_FreeEntityDefOverlay( def );
}
if ( !keepCachedDynamicModel ) {
delete def->cachedDynamicModel;
def->cachedDynamicModel = NULL;
}
// free the entityRefs from the areas
areaReference_t * next = NULL;
for ( areaReference_t * ref = def->entityRefs; ref != NULL; ref = next ) {
next = ref->ownerNext;
// unlink from the area
ref->areaNext->areaPrev = ref->areaPrev;
ref->areaPrev->areaNext = ref->areaNext;
// put it back on the free list for reuse
def->world->areaReferenceAllocator.Free( ref );
}
def->entityRefs = NULL;
}
/*
===================
R_FreeEntityDefDecals
===================
*/
void R_FreeEntityDefDecals( idRenderEntityLocal *def ) {
def->decals = NULL;
}
/*
===================
R_FreeEntityDefFadedDecals
===================
*/
void R_FreeEntityDefFadedDecals( idRenderEntityLocal *def, int time ) {
if ( def->decals != NULL ) {
def->decals->RemoveFadedDecals( time );
}
}
/*
===================
R_FreeEntityDefOverlay
===================
*/
void R_FreeEntityDefOverlay( idRenderEntityLocal *def ) {
def->overlays = NULL;
}
/*
===============
R_CreateEntityRefs
Creates all needed model references in portal areas,
chaining them to both the area and the entityDef.
Bumps tr.viewCount, which means viewCount can change many times each frame.
===============
*/
void R_CreateEntityRefs( idRenderEntityLocal *entity ) {
if ( entity->parms.hModel == NULL ) {
entity->parms.hModel = renderModelManager->DefaultModel();
}
// if the entity hasn't been fully specified due to expensive animation calcs
// for md5 and particles, use the provided conservative bounds.
if ( entity->parms.callback != NULL ) {
entity->localReferenceBounds = entity->parms.bounds;
} else {
entity->localReferenceBounds = entity->parms.hModel->Bounds( &entity->parms );
}
// some models, like empty particles, may not need to be added at all
if ( entity->localReferenceBounds.IsCleared() ) {
return;
}
if ( r_showUpdates.GetBool() &&
( entity->localReferenceBounds[1][0] - entity->localReferenceBounds[0][0] > 1024.0f ||
entity->localReferenceBounds[1][1] - entity->localReferenceBounds[0][1] > 1024.0f ) ) {
common->Printf( "big entityRef: %f,%f\n", entity->localReferenceBounds[1][0] - entity->localReferenceBounds[0][0],
entity->localReferenceBounds[1][1] - entity->localReferenceBounds[0][1] );
}
// derive entity data
R_DeriveEntityData( entity );
// bump the view count so we can tell if an
// area already has a reference
tr.viewCount++;
// push the model frustum down the BSP tree into areas
entity->world->PushFrustumIntoTree( entity, NULL, entity->inverseBaseModelProject, bounds_unitCube );
}
/*
=================================================================================
LIGHT DEFS
=================================================================================
*/
/*
========================
R_ComputePointLightProjectionMatrix
Computes the light projection matrix for a point light.
========================
*/
static float R_ComputePointLightProjectionMatrix( idRenderLightLocal * light, idRenderMatrix & localProject ) {
assert( light->parms.pointLight );
// A point light uses a box projection.
// This projects into the 0.0 - 1.0 texture range instead of -1.0 to 1.0 clip space range.
localProject.Zero();
localProject[0][0] = 0.5f / light->parms.lightRadius[0];
localProject[1][1] = 0.5f / light->parms.lightRadius[1];
localProject[2][2] = 0.5f / light->parms.lightRadius[2];
localProject[0][3] = 0.5f;
localProject[1][3] = 0.5f;
localProject[2][3] = 0.5f;
localProject[3][3] = 1.0f; // identity perspective
return 1.0f;
}
static const float SPOT_LIGHT_MIN_Z_NEAR = 8.0f;
static const float SPOT_LIGHT_MIN_Z_FAR = 16.0f;
/*
========================
R_ComputeSpotLightProjectionMatrix
Computes the light projection matrix for a spot light.
========================
*/
static float R_ComputeSpotLightProjectionMatrix( idRenderLightLocal * light, idRenderMatrix & localProject ) {
const float targetDistSqr = light->parms.target.LengthSqr();
const float invTargetDist = idMath::InvSqrt( targetDistSqr );
const float targetDist = invTargetDist * targetDistSqr;
const idVec3 normalizedTarget = light->parms.target * invTargetDist;
const idVec3 normalizedRight = light->parms.right * ( 0.5f * targetDist / light->parms.right.LengthSqr() );
const idVec3 normalizedUp = light->parms.up * ( -0.5f * targetDist / light->parms.up.LengthSqr() );
localProject[0][0] = normalizedRight[0];
localProject[0][1] = normalizedRight[1];
localProject[0][2] = normalizedRight[2];
localProject[0][3] = 0.0f;
localProject[1][0] = normalizedUp[0];
localProject[1][1] = normalizedUp[1];
localProject[1][2] = normalizedUp[2];
localProject[1][3] = 0.0f;
localProject[3][0] = normalizedTarget[0];
localProject[3][1] = normalizedTarget[1];
localProject[3][2] = normalizedTarget[2];
localProject[3][3] = 0.0f;
// Set the falloff vector.
// This is similar to the Z calculation for depth buffering, which means that the
// mapped texture is going to be perspective distorted heavily towards the zero end.
const float zNear = Max( light->parms.start * normalizedTarget, SPOT_LIGHT_MIN_Z_NEAR );
const float zFar = Max( light->parms.end * normalizedTarget, SPOT_LIGHT_MIN_Z_FAR );
const float zScale = ( zNear + zFar ) / zFar;
localProject[2][0] = normalizedTarget[0] * zScale;
localProject[2][1] = normalizedTarget[1] * zScale;
localProject[2][2] = normalizedTarget[2] * zScale;
localProject[2][3] = - zNear * zScale;
// now offset to the 0.0 - 1.0 texture range instead of -1.0 to 1.0 clip space range
idVec4 projectedTarget;
localProject.TransformPoint( light->parms.target, projectedTarget );
const float ofs0 = 0.5f - projectedTarget[0] / projectedTarget[3];
localProject[0][0] += ofs0 * localProject[3][0];
localProject[0][1] += ofs0 * localProject[3][1];
localProject[0][2] += ofs0 * localProject[3][2];
localProject[0][3] += ofs0 * localProject[3][3];
const float ofs1 = 0.5f - projectedTarget[1] / projectedTarget[3];
localProject[1][0] += ofs1 * localProject[3][0];
localProject[1][1] += ofs1 * localProject[3][1];
localProject[1][2] += ofs1 * localProject[3][2];
localProject[1][3] += ofs1 * localProject[3][3];
return 1.0f / ( zNear + zFar );
}
/*
========================
R_ComputeParallelLightProjectionMatrix
Computes the light projection matrix for a parallel light.
========================
*/
static float R_ComputeParallelLightProjectionMatrix( idRenderLightLocal * light, idRenderMatrix & localProject ) {
assert( light->parms.parallel );
// A parallel light uses a box projection.
// This projects into the 0.0 - 1.0 texture range instead of -1.0 to 1.0 clip space range.
localProject.Zero();
localProject[0][0] = 0.5f / light->parms.lightRadius[0];
localProject[1][1] = 0.5f / light->parms.lightRadius[1];
localProject[2][2] = 0.5f / light->parms.lightRadius[2];
localProject[0][3] = 0.5f;
localProject[1][3] = 0.5f;
localProject[2][3] = 0.5f;
localProject[3][3] = 1.0f; // identity perspective
return 1.0f;
}
/*
=================
R_DeriveLightData
Fills everything in based on light->parms
=================
*/
static void R_DeriveLightData( idRenderLightLocal * light ) {
// decide which light shader we are going to use
if ( light->parms.shader != NULL ) {
light->lightShader = light->parms.shader;
} else if ( light->lightShader == NULL ) {
if ( light->parms.pointLight ) {
light->lightShader = tr.defaultPointLight;
} else {
light->lightShader = tr.defaultProjectedLight;
}
}
// get the falloff image
light->falloffImage = light->lightShader->LightFalloffImage();
if ( light->falloffImage == NULL ) {
// use the falloff from the default shader of the correct type
const idMaterial * defaultShader;
if ( light->parms.pointLight ) {
defaultShader = tr.defaultPointLight;
// Touch the default shader. to make sure it's decl has been parsed ( it might have been purged ).
declManager->Touch( static_cast< const idDecl *>( defaultShader ) );
light->falloffImage = defaultShader->LightFalloffImage();
} else {
// projected lights by default don't diminish with distance
defaultShader = tr.defaultProjectedLight;
// Touch the light shader. to make sure it's decl has been parsed ( it might have been purged ).
declManager->Touch( static_cast< const idDecl *>( defaultShader ) );
light->falloffImage = defaultShader->LightFalloffImage();
}
}
// ------------------------------------
// compute the light projection matrix
// ------------------------------------
idRenderMatrix localProject;
float zScale = 1.0f;
if ( light->parms.parallel ) {
zScale = R_ComputeParallelLightProjectionMatrix( light, localProject );
} else if ( light->parms.pointLight ) {
zScale = R_ComputePointLightProjectionMatrix( light, localProject );
} else {
zScale = R_ComputeSpotLightProjectionMatrix( light, localProject );
}
// set the old style light projection where Z and W are flipped and
// for projected lights lightProject[3] is divided by ( zNear + zFar )
light->lightProject[0][0] = localProject[0][0];
light->lightProject[0][1] = localProject[0][1];
light->lightProject[0][2] = localProject[0][2];
light->lightProject[0][3] = localProject[0][3];
light->lightProject[1][0] = localProject[1][0];
light->lightProject[1][1] = localProject[1][1];
light->lightProject[1][2] = localProject[1][2];
light->lightProject[1][3] = localProject[1][3];
light->lightProject[2][0] = localProject[3][0];
light->lightProject[2][1] = localProject[3][1];
light->lightProject[2][2] = localProject[3][2];
light->lightProject[2][3] = localProject[3][3];
light->lightProject[3][0] = localProject[2][0] * zScale;
light->lightProject[3][1] = localProject[2][1] * zScale;
light->lightProject[3][2] = localProject[2][2] * zScale;
light->lightProject[3][3] = localProject[2][3] * zScale;
// transform the lightProject
float lightTransform[16];
R_AxisToModelMatrix( light->parms.axis, light->parms.origin, lightTransform );
for ( int i = 0; i < 4; i++ ) {
idPlane temp = light->lightProject[i];
R_LocalPlaneToGlobal( lightTransform, temp, light->lightProject[i] );
}
// adjust global light origin for off center projections and parallel projections
// we are just faking parallel by making it a very far off center for now
if ( light->parms.parallel ) {
idVec3 dir = light->parms.lightCenter;
if ( dir.Normalize() == 0.0f ) {
// make point straight up if not specified
dir[2] = 1.0f;
}
light->globalLightOrigin = light->parms.origin + dir * 100000.0f;
} else {
light->globalLightOrigin = light->parms.origin + light->parms.axis * light->parms.lightCenter;
}
// Rotate and translate the light projection by the light matrix.
// 99% of lights remain axis aligned in world space.
idRenderMatrix lightMatrix;
idRenderMatrix::CreateFromOriginAxis( light->parms.origin, light->parms.axis, lightMatrix );
idRenderMatrix inverseLightMatrix;
if ( !idRenderMatrix::Inverse( lightMatrix, inverseLightMatrix ) ) {
idLib::Warning( "lightMatrix invert failed" );
}
// 'baseLightProject' goes from global space -> light local space -> light projective space
idRenderMatrix::Multiply( localProject, inverseLightMatrix, light->baseLightProject );
// Invert the light projection so we can deform zero-to-one cubes into
// the light model and calculate global bounds.
if ( !idRenderMatrix::Inverse( light->baseLightProject, light->inverseBaseLightProject ) ) {
idLib::Warning( "baseLightProject invert failed" );
}
// calculate the global light bounds by inverse projecting the zero to one cube with the 'inverseBaseLightProject'
idRenderMatrix::ProjectedBounds( light->globalLightBounds, light->inverseBaseLightProject, bounds_zeroOneCube, false );
}
/*
====================
R_FreeLightDefDerivedData
Frees all references and lit surfaces from the light
====================
*/
void R_FreeLightDefDerivedData( idRenderLightLocal *ldef ) {
// remove any portal fog references
for ( doublePortal_t *dp = ldef->foggedPortals; dp != NULL; dp = dp->nextFoggedPortal ) {
dp->fogLight = NULL;
}
// free all the interactions
while ( ldef->firstInteraction != NULL ) {
ldef->firstInteraction->UnlinkAndFree();
}
// free all the references to the light
areaReference_t * nextRef = NULL;
for ( areaReference_t * lref = ldef->references; lref != NULL; lref = nextRef ) {
nextRef = lref->ownerNext;
// unlink from the area
lref->areaNext->areaPrev = lref->areaPrev;
lref->areaPrev->areaNext = lref->areaNext;
// put it back on the free list for reuse
ldef->world->areaReferenceAllocator.Free( lref );
}
ldef->references = NULL;
}
/*
===============
WindingCompletelyInsideLight
===============
*/
static bool WindingCompletelyInsideLight( const idWinding *w, const idRenderLightLocal *ldef ) {
for ( int i = 0; i < w->GetNumPoints(); i++ ) {
if ( idRenderMatrix::CullPointToMVP( ldef->baseLightProject, (*w)[i].ToVec3(), true ) ) {
return false;
}
}
return true;
}
/*
======================
R_CreateLightDefFogPortals
When a fog light is created or moved, see if it completely
encloses any portals, which may allow them to be fogged closed.
======================
*/
static void R_CreateLightDefFogPortals( idRenderLightLocal *ldef ) {
ldef->foggedPortals = NULL;
if ( !ldef->lightShader->IsFogLight() ) {
return;
}
// some fog lights will explicitly disallow portal fogging
if ( ldef->lightShader->TestMaterialFlag( MF_NOPORTALFOG ) ) {
return;
}
for ( areaReference_t * lref = ldef->references; lref != NULL; lref = lref->ownerNext ) {
// check all the models in this area
portalArea_t * area = lref->area;
for ( portal_t * prt = area->portals; prt != NULL; prt = prt->next ) {
doublePortal_t * dp = prt->doublePortal;
// we only handle a single fog volume covering a portal
// this will never cause incorrect drawing, but it may
// fail to cull a portal
if ( dp->fogLight ) {
continue;
}
if ( WindingCompletelyInsideLight( prt->w, ldef ) ) {
dp->fogLight = ldef;
dp->nextFoggedPortal = ldef->foggedPortals;
ldef->foggedPortals = dp;
}
}
}
}
/*
=================
R_CreateLightRefs
=================
*/
void R_CreateLightRefs( idRenderLightLocal * light ) {
// derive light data
R_DeriveLightData( light );
// determine the areaNum for the light origin, which may let us
// cull the light if it is behind a closed door
// it is debatable if we want to use the entity origin or the center offset origin,
// but we definitely don't want to use a parallel offset origin
light->areaNum = light->world->PointInArea( light->globalLightOrigin );
if ( light->areaNum == -1 ) {
light->areaNum = light->world->PointInArea( light->parms.origin );
}
// bump the view count so we can tell if an
// area already has a reference
tr.viewCount++;
// if we have a prelight model that includes all the shadows for the major world occluders,
// we can limit the area references to those visible through the portals from the light center.
// We can't do this in the normal case, because shadows are cast from back facing triangles, which
// may be in areas not directly visible to the light projection center.
if ( light->parms.prelightModel != NULL && r_useLightPortalFlow.GetBool() && light->lightShader->LightCastsShadows() ) {
light->world->FlowLightThroughPortals( light );
} else {
// push the light frustum down the BSP tree into areas
light->world->PushFrustumIntoTree( NULL, light, light->inverseBaseLightProject, bounds_zeroOneCube );
}
R_CreateLightDefFogPortals( light );
}
/*
=================================================================================
WORLD MODEL & LIGHT DEFS
=================================================================================
*/
/*
===================
R_FreeDerivedData
ReloadModels and RegenerateWorld call this
===================
*/
void R_FreeDerivedData() {
for ( int j = 0; j < tr.worlds.Num(); j++ ) {
idRenderWorldLocal * rw = tr.worlds[j];
for ( int i = 0; i < rw->entityDefs.Num(); i++ ) {
idRenderEntityLocal * def = rw->entityDefs[i];
if ( def == NULL ) {
continue;
}
R_FreeEntityDefDerivedData( def, false, false );
}
for ( int i = 0; i < rw->lightDefs.Num(); i++ ) {
idRenderLightLocal * light = rw->lightDefs[i];
if ( light == NULL ) {
continue;
}
R_FreeLightDefDerivedData( light );
}
}
}
/*
===================
R_CheckForEntityDefsUsingModel
===================
*/
void R_CheckForEntityDefsUsingModel( idRenderModel *model ) {
for ( int j = 0; j < tr.worlds.Num(); j++ ) {
idRenderWorldLocal * rw = tr.worlds[j];
for ( int i = 0; i < rw->entityDefs.Num(); i++ ) {
idRenderEntityLocal * def = rw->entityDefs[i];
if ( !def ) {
continue;
}
if ( def->parms.hModel == model ) {
//assert( 0 );
// this should never happen but Radiant messes it up all the time so just free the derived data
R_FreeEntityDefDerivedData( def, false, false );
}
}
}
}
/*
===================
R_ReCreateWorldReferences
ReloadModels and RegenerateWorld call this
===================
*/
void R_ReCreateWorldReferences() {
// let the interaction generation code know this
// shouldn't be optimized for a particular view
tr.viewDef = NULL;
for ( int j = 0; j < tr.worlds.Num(); j++ ) {
idRenderWorldLocal * rw = tr.worlds[j];
for ( int i = 0; i < rw->entityDefs.Num(); i++ ) {
idRenderEntityLocal * def = rw->entityDefs[i];
if ( def == NULL ) {
continue;
}
// the world model entities are put specifically in a single
// area, instead of just pushing their bounds into the tree
if ( i < rw->numPortalAreas ) {
rw->AddEntityRefToArea( def, &rw->portalAreas[i] );
} else {
R_CreateEntityRefs( def );
}
}
for ( int i = 0; i < rw->lightDefs.Num(); i++ ) {
idRenderLightLocal * light = rw->lightDefs[i];
if ( light == NULL ) {
continue;
}
renderLight_t parms = light->parms;
light->world->FreeLightDef( i );
rw->UpdateLightDef( i, &parms );
}
}
}
/*
====================
R_ModulateLights_f
Modifies the shaderParms on all the lights so the level
designers can easily test different color schemes
====================
*/
void R_ModulateLights_f( const idCmdArgs &args ) {
if ( !tr.primaryWorld ) {
return;
}
if ( args.Argc() != 4 ) {
common->Printf( "usage: modulateLights <redFloat> <greenFloat> <blueFloat>\n" );
return;
}
float modulate[3];
for ( int i = 0; i < 3; i++ ) {
modulate[i] = atof( args.Argv( i+1 ) );
}
int count = 0;
for ( int i = 0; i < tr.primaryWorld->lightDefs.Num(); i++ ) {
idRenderLightLocal * light = tr.primaryWorld->lightDefs[i];
if ( light != NULL ) {
count++;
for ( int j = 0; j < 3; j++ ) {
light->parms.shaderParms[j] *= modulate[j];
}
}
}
common->Printf( "modulated %i lights\n", count );
}
| 32.067893
| 366
| 0.663065
|
1337programming
|
e9edde5b50c9f3d89fa09922086f558dba2df378
| 645
|
cpp
|
C++
|
atcoder/abc089_c.cpp
|
Doarakko/competitive-programming
|
5ae78c501664af08a3f16c81dbd54c68310adec8
|
[
"MIT"
] | 1
|
2017-07-11T16:47:29.000Z
|
2017-07-11T16:47:29.000Z
|
atcoder/abc089_c.cpp
|
Doarakko/Competitive-Programming
|
10642a4bd7266c828dd2fc6e311284e86bdf2968
|
[
"MIT"
] | 1
|
2021-02-07T09:10:26.000Z
|
2021-02-07T09:10:26.000Z
|
atcoder/abc089_c.cpp
|
Doarakko/Competitive-Programming
|
10642a4bd7266c828dd2fc6e311284e86bdf2968
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
int N;
cin >> N;
char c;
int a[4] = {0, 0, 0, 0};
for (int i = 0; i < N; i++) {
cin >> c;
if (c == 'P') {
a[0] = 1;
}else if (c == 'W'){
a[1] = 1;
}else if (c == 'G'){
a[2] = 1;
}else if (c == 'Y'){
a[3] = 1;
}
}
int cnt = 0;
for (int i = 0; i < 4; i++) {
if (a[i] == 1) {
cnt++;
}
}
if (cnt == 3) {
cout << "Three" << endl;
}else{
cout << "Four" << endl;
}
return 0;
}
| 19.545455
| 41
| 0.316279
|
Doarakko
|
e9ef881c8e5e58f168fe21988c1c3f1530fcdc88
| 13,862
|
cc
|
C++
|
util/ssc_planner/src/ssc_planner/ssc_visualizer.cc
|
GallopWind/epsilon-learn
|
74dc723fbc9797f3bd05bee30f6f9b9acceeec17
|
[
"MIT"
] | 186
|
2020-09-22T10:57:57.000Z
|
2022-03-30T15:52:15.000Z
|
util/ssc_planner/src/ssc_planner/ssc_visualizer.cc
|
Yufei-Wei/EPSILON
|
155f1b1c4dae3ae29287d5b0b967d7d6ce230c73
|
[
"MIT"
] | 16
|
2020-10-19T02:55:49.000Z
|
2022-01-14T08:17:06.000Z
|
util/ssc_planner/src/ssc_planner/ssc_visualizer.cc
|
Yufei-Wei/EPSILON
|
155f1b1c4dae3ae29287d5b0b967d7d6ce230c73
|
[
"MIT"
] | 66
|
2020-09-28T01:51:57.000Z
|
2022-03-25T08:39:04.000Z
|
/**
* @file ssc_visualizer.cc
* @author HKUST Aerial Robotics Group
* @brief implementation for ssc visualizer
* @version 0.1
* @date 2019-02
* @copyright Copyright (c) 2019
*/
#include "ssc_planner/ssc_visualizer.h"
namespace planning {
SscVisualizer::SscVisualizer(ros::NodeHandle nh, int node_id)
: nh_(nh), node_id_(node_id) {
std::cout << "node_id_ = " << node_id_ << std::endl;
std::string ssc_map_vis_topic = std::string("/vis/agent_") +
std::to_string(node_id_) +
std::string("/ssc/map_vis");
std::string ego_vehicle_vis_topic = std::string("/vis/agent_") +
std::to_string(node_id_) +
std::string("/ssc/ego_fs_vis");
std::string forward_trajs_vis_topic = std::string("/vis/agent_") +
std::to_string(node_id_) +
std::string("/ssc/forward_trajs_vis");
std::string sur_vehicle_trajs_vis_topic =
std::string("/vis/agent_") + std::to_string(node_id_) +
std::string("/ssc/sur_vehicle_trajs_vis");
std::string corridor_vis_topic = std::string("/vis/agent_") +
std::to_string(node_id_) +
std::string("/ssc/corridor_vis");
std::string qp_vis_topic = std::string("/vis/agent_") +
std::to_string(node_id_) +
std::string("/ssc/qp_vis");
ssc_map_pub_ =
nh_.advertise<visualization_msgs::MarkerArray>(ssc_map_vis_topic, 1);
qp_pub_ = nh_.advertise<visualization_msgs::MarkerArray>(qp_vis_topic, 1);
ego_vehicle_pub_ =
nh_.advertise<visualization_msgs::MarkerArray>(ego_vehicle_vis_topic, 1);
forward_trajs_pub_ = nh_.advertise<visualization_msgs::MarkerArray>(
forward_trajs_vis_topic, 1);
sur_vehicle_trajs_pub_ = nh_.advertise<visualization_msgs::MarkerArray>(
sur_vehicle_trajs_vis_topic, 1);
corridor_pub_ =
nh_.advertise<visualization_msgs::MarkerArray>(corridor_vis_topic, 1);
}
void SscVisualizer::VisualizeDataWithStamp(const ros::Time &stamp,
const SscPlanner &planner) {
start_time_ = planner.time_origin();
// std::cout << "[SscMapTime]Sys time stamp = " << stamp << std::endl;
VisualizeSscMap(stamp, planner.p_ssc_map());
VisualizeEgoVehicleInSscSpace(stamp, planner.fs_ego_vehicle());
VisualizeForwardTrajectoriesInSscSpace(stamp, planner.forward_trajs_fs(),
planner.p_ssc_map());
VisualizeSurroundingVehicleTrajInSscSpace(
stamp, planner.surround_forward_trajs_fs(), planner.p_ssc_map());
VisualizeCorridorsInSscSpace(
stamp, planner.p_ssc_map()->driving_corridor_vec(), planner.p_ssc_map());
VisualizeQpTrajs(stamp, planner.qp_trajs());
}
void SscVisualizer::VisualizeQpTrajs(
const ros::Time &stamp, const vec_E<common::BezierSpline<5, 2>> &trajs) {
if (trajs.empty()) {
printf("[SscQP]No valid qp trajs.\n");
return;
}
int id = 0;
visualization_msgs::MarkerArray traj_mk_arr;
for (int i = 0; i < static_cast<int>(trajs.size()); i++) {
visualization_msgs::Marker traj_mk;
traj_mk.type = visualization_msgs::Marker::LINE_STRIP;
traj_mk.action = visualization_msgs::Marker::MODIFY;
traj_mk.id = id++;
Vecf<2> pos;
for (decimal_t t = trajs[i].begin(); t < trajs[i].end() + kEPS; t += 0.02) {
if (trajs[i].evaluate(t, 0, &pos) == kSuccess) {
geometry_msgs::Point pt;
pt.x = pos[0];
pt.y = pos[1];
pt.z = t - start_time_;
traj_mk.points.push_back(pt);
}
}
common::VisualizationUtil::FillScaleColorInMarker(
Vec3f(0.2, 0.2, 0.2), common::cmap.at("magenta"), &traj_mk);
traj_mk_arr.markers.push_back(traj_mk);
}
int num_markers = static_cast<int>(traj_mk_arr.markers.size());
common::VisualizationUtil::FillHeaderIdInMarkerArray(
stamp, std::string("ssc_map"), last_qp_traj_mk_cnt, &traj_mk_arr);
qp_pub_.publish(traj_mk_arr);
last_qp_traj_mk_cnt = num_markers;
}
void SscVisualizer::VisualizeSscMap(const ros::Time &stamp,
const SscMap *p_ssc_map) {
visualization_msgs::MarkerArray map_marker_arr;
visualization_msgs::Marker map_marker;
common::VisualizationUtil::GetRosMarkerCubeListUsingGripMap3D(
p_ssc_map->p_3d_grid(), stamp, "ssc_map", Vec3f(0, 0, 0), &map_marker);
auto origin = p_ssc_map->p_3d_grid()->origin();
decimal_t s_len =
p_ssc_map->config().map_resolution[0] * p_ssc_map->config().map_size[0];
decimal_t x = s_len / 2 - p_ssc_map->config().s_back_len + origin[0];
decimal_t y = 0;
// decimal_t z = t_len / 2;
std::array<decimal_t, 3> aabb_coord = {x, y, 0};
std::array<decimal_t, 3> aabb_len = {s_len, 3.5, 0.01};
common::AxisAlignedBoundingBoxND<3> map_aabb(aabb_coord, aabb_len);
visualization_msgs::Marker map_aabb_marker;
map_aabb_marker.header.frame_id = "ssc_map";
map_aabb_marker.header.stamp = stamp;
map_aabb_marker.id = 1;
common::VisualizationUtil::GetRosMarkerCubeUsingAxisAlignedBoundingBox3D(
map_aabb, common::ColorARGB(0.2, 1, 0, 1), &map_aabb_marker);
map_marker_arr.markers.push_back(map_marker);
map_marker_arr.markers.push_back(map_aabb_marker);
ssc_map_pub_.publish(map_marker_arr);
}
void SscVisualizer::VisualizeEgoVehicleInSscSpace(
const ros::Time &stamp, const common::FsVehicle &fs_ego_vehicle) {
if (fs_ego_vehicle.vertices.empty()) return;
visualization_msgs::MarkerArray ego_vehicle_mks;
visualization_msgs::Marker ego_contour_marker;
common::ColorARGB color(0.8, 1.0, 0.0, 0.0);
decimal_t dt = fs_ego_vehicle.frenet_state.time_stamp - start_time_;
vec_E<Vec2f> contour = fs_ego_vehicle.vertices;
contour.push_back(contour.front());
common::VisualizationUtil::GetRosMarkerLineStripUsing2DofVecWithOffsetZ(
contour, color, Vec3f(0.3, 0.3, 0.3), dt, 0, &ego_contour_marker);
ego_contour_marker.header.frame_id = "ssc_map";
ego_contour_marker.header.stamp = stamp;
ego_vehicle_mks.markers.push_back(ego_contour_marker);
visualization_msgs::Marker ego_fs_mk;
common::VisualizationUtil::GetRosMarkerSphereUsingPoint(
Vec3f(fs_ego_vehicle.frenet_state.vec_s[0],
fs_ego_vehicle.frenet_state.vec_dt[0], dt),
common::cmap.at("red"), Vec3f(0.3, 0.3, 0.3), 1, &ego_fs_mk);
ego_fs_mk.header.frame_id = "ssc_map";
ego_fs_mk.header.stamp = stamp;
ego_vehicle_mks.markers.push_back(ego_fs_mk);
ego_vehicle_pub_.publish(ego_vehicle_mks);
}
void SscVisualizer::VisualizeForwardTrajectoriesInSscSpace(
const ros::Time &stamp, const vec_E<vec_E<common::FsVehicle>> &trajs,
const SscMap *p_ssc_map) {
if (trajs.empty()) return;
visualization_msgs::MarkerArray trajs_markers;
int id_cnt = 0;
// common::ColorARGB color = common::cmap.at("gold");
// color.a = 0.4;
for (int i = 0; i < static_cast<int>(trajs.size()); ++i) {
if (trajs[i].empty()) continue;
for (int k = 0; k < static_cast<int>(trajs[i].size()); ++k) {
visualization_msgs::Marker vehicle_marker;
vec_E<Vec2f> contour = trajs[i][k].vertices;
bool is_valid = true;
for (const auto v : contour) {
if (v(0) <= 0) {
is_valid = false;
break;
}
}
if (!is_valid) {
continue;
}
common::ColorARGB color = common::GetJetColorByValue(
static_cast<decimal_t>(k),
static_cast<decimal_t>(trajs[i].size() - 1), 0.0);
contour.push_back(contour.front());
decimal_t dt = trajs[i][k].frenet_state.time_stamp - start_time_;
common::VisualizationUtil::GetRosMarkerLineStripUsing2DofVecWithOffsetZ(
contour, color, Vec3f(0.1, 0.1, 0.1), dt, id_cnt++, &vehicle_marker);
trajs_markers.markers.push_back(vehicle_marker);
visualization_msgs::Marker fs_mk;
auto fs = trajs[i][k].frenet_state;
decimal_t x = fs.vec_s[0];
decimal_t y = fs.vec_dt[0];
common::VisualizationUtil::GetRosMarkerSphereUsingPoint(
Vec3f(x, y, dt), common::cmap.at("cyan"), Vec3f(0.2, 0.2, 0.2),
id_cnt++, &fs_mk);
trajs_markers.markers.push_back(fs_mk);
}
}
int num_markers = static_cast<int>(trajs_markers.markers.size());
common::VisualizationUtil::FillHeaderIdInMarkerArray(
stamp, std::string("ssc_map"), last_forward_traj_mk_cnt, &trajs_markers);
forward_trajs_pub_.publish(trajs_markers);
last_forward_traj_mk_cnt = num_markers;
}
void SscVisualizer::VisualizeSurroundingVehicleTrajInSscSpace(
const ros::Time &stamp,
const vec_E<std::unordered_map<int, vec_E<common::FsVehicle>>> &trajs_set,
const SscMap *p_ssc_map) {
visualization_msgs::MarkerArray trajs_markers;
if (!trajs_set.empty()) {
auto trajs = trajs_set.front();
if (!trajs.empty()) {
int id_cnt = 0;
for (auto it = trajs.begin(); it != trajs.end(); ++it) {
if (it->second.empty()) continue;
for (int k = 0; k < static_cast<int>(it->second.size()); ++k) {
visualization_msgs::Marker vehicle_marker;
common::ColorARGB color = common::GetJetColorByValue(
static_cast<decimal_t>(k),
static_cast<decimal_t>(it->second.size() - 1), 0.0);
vec_E<Vec2f> contour = it->second[k].vertices;
bool is_valid = true;
for (const auto v : contour) {
if (v(0) <= 0) {
is_valid = false;
break;
}
}
if (!is_valid) {
continue;
}
contour.push_back(contour.front());
decimal_t dt = it->second[k].frenet_state.time_stamp - start_time_;
common::VisualizationUtil::
GetRosMarkerLineStripUsing2DofVecWithOffsetZ(
contour, color, Vec3f(0.1, 0.1, 0.1), dt, id_cnt++,
&vehicle_marker);
vehicle_marker.header.frame_id = "ssc_map";
vehicle_marker.header.stamp = stamp;
trajs_markers.markers.push_back(vehicle_marker);
}
}
}
}
int num_markers = static_cast<int>(trajs_markers.markers.size());
common::VisualizationUtil::FillHeaderIdInMarkerArray(
stamp, std::string("ssc_map"), last_sur_vehicle_traj_mk_cnt,
&trajs_markers);
sur_vehicle_trajs_pub_.publish(trajs_markers);
last_sur_vehicle_traj_mk_cnt = num_markers;
}
void SscVisualizer::VisualizeCorridorsInSscSpace(
const ros::Time &stamp, const vec_E<common::DrivingCorridor> corridor_vec,
const SscMap *p_ssc_map) {
if (corridor_vec.empty()) return;
visualization_msgs::MarkerArray corridor_vec_marker;
int id_cnt = 0;
for (const auto &corridor : corridor_vec) {
// if (corridor.is_valid) continue;
int cube_cnt = 0;
for (const auto &driving_cube : corridor.cubes) {
// * Show seeds
common::ColorARGB color = common::GetJetColorByValue(
cube_cnt, corridor.cubes.size() - 1, -kEPS);
for (const auto &seed : driving_cube.seeds) {
visualization_msgs::Marker seed_marker;
decimal_t s_x, s_y, s_z;
p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(seed(0), 0,
&s_x);
p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(seed(1), 1,
&s_y);
p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(seed(2), 2,
&s_z);
common::VisualizationUtil::GetRosMarkerSphereUsingPoint(
Vec3f(s_x, s_y, s_z - start_time_), color, Vec3f(0.3, 0.3, 0.3),
id_cnt++, &seed_marker);
corridor_vec_marker.markers.push_back(seed_marker);
}
// * Show driving cube
decimal_t x_max, x_min;
decimal_t y_max, y_min;
decimal_t z_max, z_min;
p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(
driving_cube.cube.upper_bound[0], 0, &x_max);
p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(
driving_cube.cube.lower_bound[0], 0, &x_min);
p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(
driving_cube.cube.upper_bound[1], 1, &y_max);
p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(
driving_cube.cube.lower_bound[1], 1, &y_min);
p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(
driving_cube.cube.upper_bound[2], 2, &z_max);
p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(
driving_cube.cube.lower_bound[2], 2, &z_min);
decimal_t dx = x_max - x_min;
decimal_t dy = y_max - y_min;
decimal_t dz = z_max - z_min;
decimal_t x = x_min + dx / 2.0;
decimal_t y = y_min + dy / 2.0;
decimal_t z = z_min - start_time_ + dz / 2.0;
std::array<decimal_t, 3> aabb_coord = {x, y, z};
std::array<decimal_t, 3> aabb_len = {dx, dy, dz};
common::AxisAlignedBoundingBoxND<3> map_aabb(aabb_coord, aabb_len);
visualization_msgs::Marker map_aabb_marker;
map_aabb_marker.id = id_cnt++;
common::VisualizationUtil::GetRosMarkerCubeUsingAxisAlignedBoundingBox3D(
map_aabb, common::ColorARGB(0.15, 0.3, 1.0, 0.3), &map_aabb_marker);
corridor_vec_marker.markers.push_back(map_aabb_marker);
++cube_cnt;
}
}
int num_markers = static_cast<int>(corridor_vec_marker.markers.size());
common::VisualizationUtil::FillHeaderIdInMarkerArray(
ros::Time::now(), std::string("ssc_map"), last_corridor_mk_cnt,
&corridor_vec_marker);
corridor_pub_.publish(corridor_vec_marker);
last_corridor_mk_cnt = num_markers;
}
} // namespace planning
| 42.391437
| 80
| 0.65171
|
GallopWind
|
e9f04c5099fe4f84319edcfc163033dcf4bf189d
| 11,669
|
cpp
|
C++
|
tests/Move_strategies_test.cpp
|
mjcaisse/CDT-plusplus
|
fa11dd19c806a96afbb48e406234e82cae62029a
|
[
"BSD-3-Clause"
] | null | null | null |
tests/Move_strategies_test.cpp
|
mjcaisse/CDT-plusplus
|
fa11dd19c806a96afbb48e406234e82cae62029a
|
[
"BSD-3-Clause"
] | null | null | null |
tests/Move_strategies_test.cpp
|
mjcaisse/CDT-plusplus
|
fa11dd19c806a96afbb48e406234e82cae62029a
|
[
"BSD-3-Clause"
] | null | null | null |
/// Causal Dynamical Triangulations in C++ using CGAL
///
/// Copyright © 2015-2020 Adam Getchell
///
/// Checks that Metropolis algorithm runs properly.
/// @file Move_strategies_test.cpp
/// @brief Tests for the Metropolis-Hastings algorithm
/// @author Adam Getchell
#include "Move_always.hpp"
//#include "Metropolis.hpp"
#include <catch2/catch.hpp>
using namespace std;
// bool IsProbabilityRange(CGAL::Gmpzf const& arg) { return arg > 0 && arg <= 1;
// }
SCENARIO("MoveStrategy<MOVE_ALWAYS> special member and swap properties",
"[move strategies]")
{
GIVEN("A Move always move strategy.")
{
WHEN("Special members are examined.")
{
THEN("It is no-throw destructible.")
{
REQUIRE(is_nothrow_destructible_v<MoveAlways3>);
REQUIRE(is_nothrow_destructible_v<MoveAlways4>);
}
THEN("It is no-throw default constructible.")
{
CHECK(is_nothrow_default_constructible_v<MoveAlways3>);
CHECK(is_nothrow_default_constructible_v<MoveAlways4>);
}
THEN("It is no-throw copy constructible.")
{
CHECK(is_nothrow_copy_constructible_v<MoveAlways3>);
CHECK(is_nothrow_copy_constructible_v<MoveAlways4>);
}
THEN("It is no-throw copy assignable.")
{
CHECK(is_nothrow_copy_assignable_v<MoveAlways3>);
CHECK(is_nothrow_copy_assignable_v<MoveAlways4>);
}
THEN("It is no-throw move constructible.")
{
CHECK(is_nothrow_move_constructible_v<MoveAlways3>);
CHECK(is_nothrow_move_constructible_v<MoveAlways4>);
}
THEN("It is no-throw move assignable.")
{
CHECK(is_nothrow_move_assignable_v<MoveAlways3>);
CHECK(is_nothrow_move_assignable_v<MoveAlways4>);
}
THEN("It is no-throw swappable.")
{
REQUIRE(is_nothrow_swappable_v<MoveAlways3>);
REQUIRE(is_nothrow_swappable_v<MoveAlways4>);
}
THEN("It is constructible from 2 parameters.")
{
REQUIRE(is_constructible_v<MoveAlways3, Int_precision, Int_precision>);
REQUIRE(is_constructible_v<MoveAlways4, Int_precision, Int_precision>);
}
}
}
}
SCENARIO("Using the Move always algorithm", "[move strategies]")
{
GIVEN("A correctly-constructed Manifold3.")
{
auto constexpr simplices = static_cast<Int_precision>(640);
auto constexpr timeslices = static_cast<Int_precision>(4);
Manifold3 manifold(simplices, timeslices);
REQUIRE(manifold.is_correct());
WHEN("A MoveStrategy3 is constructed.")
{
auto constexpr passes = static_cast<Int_precision>(10);
auto constexpr checkpoint = static_cast<Int_precision>(5);
MoveAlways3 mover(passes, checkpoint);
THEN("The correct passes and checkpoints are instantiated.")
{
CHECK(mover.passes() == passes);
CHECK(mover.checkpoint() == checkpoint);
}
THEN("Attempted moves and successful moves are zero-initialized.")
{
CHECK(mover.get_attempted().two_three_moves<3>() == 0);
CHECK(mover.get_successful().two_three_moves<3>() == 0);
CHECK(mover.get_attempted().three_two_moves<3>() == 0);
CHECK(mover.get_successful().three_two_moves<3>() == 0);
CHECK(mover.get_attempted().two_six_moves<3>() == 0);
CHECK(mover.get_successful().two_six_moves<3>() == 0);
CHECK(mover.get_attempted().six_two_moves<3>() == 0);
CHECK(mover.get_successful().six_two_moves<3>() == 0);
CHECK(mover.get_attempted().four_four_moves<3>() == 0);
CHECK(mover.get_successful().four_four_moves<3>() == 0);
}
}
WHEN("A MoveAlways3 algorithm is used.")
{
auto constexpr passes = static_cast<Int_precision>(1);
auto constexpr checkpoint = static_cast<Int_precision>(1);
MoveAlways3 mover(passes, checkpoint);
THEN("The correct passes and checkpoints are instantiated.")
{
CHECK(mover.passes() == passes);
CHECK(mover.checkpoint() == checkpoint);
}
THEN("Attempted moves and successful moves are zero-initialized.")
{
CHECK(mover.get_attempted().two_three_moves<3>() == 0);
CHECK(mover.get_successful().two_three_moves<3>() == 0);
CHECK(mover.get_attempted().three_two_moves<3>() == 0);
CHECK(mover.get_successful().three_two_moves<3>() == 0);
CHECK(mover.get_attempted().two_six_moves<3>() == 0);
CHECK(mover.get_successful().two_six_moves<3>() == 0);
CHECK(mover.get_attempted().six_two_moves<3>() == 0);
CHECK(mover.get_successful().six_two_moves<3>() == 0);
CHECK(mover.get_attempted().four_four_moves<3>() == 0);
CHECK(mover.get_successful().four_four_moves<3>() == 0);
}
THEN("A lot of moves are made.")
{
// auto result = mover(manifold);
// CHECK(result.is_valid());
}
}
}
GIVEN("A 4D manifold.")
{
WHEN("A MoveStrategy4 is constructed.")
{
auto constexpr passes = static_cast<Int_precision>(1);
auto constexpr checkpoint = static_cast<Int_precision>(1);
MoveAlways4 mover(passes, checkpoint);
THEN("The correct passes and checkpoints are instantiated.")
{
CHECK(mover.passes() == passes);
CHECK(mover.checkpoint() == checkpoint);
}
THEN("Attempted moves and successful moves are zero-initialized.")
{
CHECK(mover.get_attempted().two_four_moves<4>() == 0);
CHECK(mover.get_successful().two_four_moves<4>() == 0);
}
}
}
}
// SCENARIO("Using the Metropolis algorithm", "[metropolis][!mayfail][!hide]")
//{
// constexpr auto Alpha = static_cast<long double>(0.6);
// constexpr auto K = static_cast<long double>(1.1);
// constexpr auto Lambda = static_cast<long double>(0.1);
// constexpr auto passes = static_cast<Int_precision>(10);
// constexpr auto output_every_n_passes = static_cast<Int_precision>(1);
// GIVEN("A correctly-constructed SimplicialManifold.")
// {
// constexpr auto simplices = static_cast<Int_precision>(640);
// constexpr auto timeslices = static_cast<Int_precision>(4);
// SimplicialManifold universe(make_triangulation(simplices, timeslices));
// // It is correctly constructed
// CHECK(universe.triangulation);
// CHECK(universe.geometry->number_of_cells() ==
// universe.triangulation->number_of_finite_cells());
// CHECK(universe.geometry->number_of_edges() ==
// universe.triangulation->number_of_finite_edges());
// CHECK(universe.geometry->N0() ==
// universe.triangulation->number_of_vertices());
// CHECK(universe.triangulation->dimension() == 3);
// CHECK(fix_timeslices(universe.triangulation));
// CHECK(universe.triangulation->is_valid());
// CHECK(universe.triangulation->tds().is_valid());
// WHEN("A Metropolis function object is constructed.")
// {
// Metropolis testrun(Alpha, K, Lambda, passes, output_every_n_passes);
// THEN("The Metropolis function object is initialized correctly.")
// {
// CHECK(testrun.Alpha() == Alpha);
// CHECK(testrun.K() == K);
// CHECK(testrun.Lambda() == Lambda);
// CHECK(testrun.Passes() == passes);
// CHECK(testrun.Checkpoint() == output_every_n_passes);
// CHECK(testrun.TwoThreeMoves() == 0);
// CHECK(testrun.SuccessfulTwoThreeMoves() == 0);
// CHECK(testrun.ThreeTwoMoves() == 0);
// CHECK(testrun.SuccessfulThreeTwoMoves() == 0);
// CHECK(testrun.TwoSixMoves() == 0);
// CHECK(testrun.SuccessfulTwoSixMoves() == 0);
// CHECK(testrun.SixTwoMoves() == 0);
// CHECK(testrun.SuccessfulSixTwoMoves() == 0);
// CHECK(testrun.FourFourMoves() == 0);
// CHECK(testrun.SuccessfulFourFourMoves() == 0);
// }
// }
// WHEN("The Metropolis functor is called.")
// {
// // Initialize Metropolis function object with passes and checkpoints = 1
// Metropolis testrun(Alpha, K, Lambda, 1, 1);
// // Call function object
// auto result = std::move(testrun(universe));
// std::cout << "Results:\n";
// std::cout << "N1_TL = " << result.geometry->N1_TL() << "\n";
// std::cout << "N3_31 = " << result.geometry->N3_31() << "\n";
// std::cout << "N3_22 = " << result.geometry->N3_22() << "\n";
// std::cout << "There were " << testrun.TwoThreeMoves()
// << " attempted (2,3) moves and "
// << testrun.SuccessfulTwoThreeMoves()
// << " successful (2,3) moves.\n";
// std::cout << "There were " << testrun.ThreeTwoMoves()
// << " attempted (3,2) moves and "
// << testrun.SuccessfulThreeTwoMoves()
// << " successful (3,2) moves.\n";
// std::cout << "There were " << testrun.TwoSixMoves()
// << " attempted (2,6) moves and "
// << testrun.SuccessfulTwoSixMoves()
// << " successful (2,6) moves.\n";
// std::cout << "There were " << testrun.SixTwoMoves()
// << " attempted (6,2) moves and "
// << testrun.SuccessfulSixTwoMoves()
// << " successful (6,2) moves.\n";
// THEN("The result is a valid SimplicialManifold.")
// {
// CHECK(result.triangulation);
// CHECK(result.geometry->number_of_cells() ==
// result.triangulation->number_of_finite_cells());
// CHECK(result.geometry->number_of_edges() ==
// result.triangulation->number_of_finite_edges());
// CHECK(result.geometry->N0() ==
// result.triangulation->number_of_vertices());
// CHECK(result.triangulation->dimension() == 3);
// CHECK(fix_timeslices(result.triangulation));
// CHECK(result.triangulation->tds().is_valid());
//
// VolumePerTimeslice(result);
//
// CHECK(result.geometry->max_timevalue().get() == timeslices);
// CHECK(result.geometry->min_timevalue().get() == 1);
// }
//
// THEN("A1 is calculated for each move.")
// {
// auto A1_23 = testrun.CalculateA1(move_type::TWO_THREE);
// auto A1_32 = testrun.CalculateA1(move_type::THREE_TWO);
// auto A1_26 = testrun.CalculateA1(move_type::TWO_SIX);
// auto A1_62 = testrun.CalculateA1(move_type::SIX_TWO);
//
// CHECK(IsProbabilityRange(A1_23));
// std::cout << "A1 for (2,3) moves is: " << A1_23 << '\n';
// CHECK(IsProbabilityRange(A1_32));
// std::cout << "A1 for (3,2) moves is: " << A1_32 << '\n';
// CHECK(IsProbabilityRange(A1_26));
// std::cout << "A1 for (2,6) moves is: " << A1_26 << '\n';
// CHECK(IsProbabilityRange(A1_62));
// std::cout << "A1 for (6,2) moves is: " << A1_62 << '\n';
// }
// THEN("A2 is calculated for each move.")
// {
// auto A2_23 = testrun.CalculateA2(move_type::TWO_THREE);
// auto A2_32 = testrun.CalculateA2(move_type::THREE_TWO);
// auto A2_26 = testrun.CalculateA2(move_type::TWO_SIX);
// auto A2_62 = testrun.CalculateA2(move_type::SIX_TWO);
//
// CHECK(IsProbabilityRange(A2_23));
// std::cout << "A2 for (2,3) moves is: " << A2_23 << '\n';
// CHECK(IsProbabilityRange(A2_32));
// std::cout << "A2 for (2,3) moves is: " << A2_32 << '\n';
// CHECK(IsProbabilityRange(A2_26));
// std::cout << "A2 for (2,6) moves is: " << A2_26 << '\n';
// CHECK(IsProbabilityRange(A2_62));
// std::cout << "A2 for (6,2) moves is: " << A2_62 << '\n';
// }
// }
// }
//}
| 41.675
| 80
| 0.607421
|
mjcaisse
|
e9f138b66379a299ac02d00c229cfbe3bc482fda
| 3,071
|
cpp
|
C++
|
unit/src/RemovePlanarityTest.cpp
|
volkerschmidts/titania
|
1ad441a7f9481392e21216a2be86b20b1d090a97
|
[
"MIT"
] | null | null | null |
unit/src/RemovePlanarityTest.cpp
|
volkerschmidts/titania
|
1ad441a7f9481392e21216a2be86b20b1d090a97
|
[
"MIT"
] | 1
|
2022-03-24T03:54:06.000Z
|
2022-03-25T15:32:09.000Z
|
unit/src/RemovePlanarityTest.cpp
|
volkerschmidts/titania
|
1ad441a7f9481392e21216a2be86b20b1d090a97
|
[
"MIT"
] | null | null | null |
#include "RemovePlanarityTest.hpp"
#include "StanIPC.h"
#include "main.h"
#include <Atom.hpp>
#include <Declarations.hpp>
#include <LinAlg.hpp>
#include <Molecule.hpp>
#include <Output.hpp>
#include <Structure.hpp>
#include <StructureSimulator.hpp>
CPPUNIT_TEST_SUITE_REGISTRATION(RemovePlanarityTest);
RemovePlanarityTest::RemovePlanarityTest()
{
CurrMol = ipcStan();
for (Atom *CurrAtom = CurrMol->getHeadStruc()->getHeadAtom(); CurrAtom;
CurrAtom = CurrAtom->getNext())
{
Eigen::Vector3d coord =
CurrAtom->Coordinates2Eigen(StructureOptions::Initial);
// flatten initial coordinates along z-axis
coord(2) = 0.0;
CurrAtom->setCoordinates(coord, StructureOptions::Initial);
}
Flags flags;
Sim = new StructureSimulator(CurrMol->getHeadStruc(), flags);
}
RemovePlanarityTest::~RemovePlanarityTest()
{
delete Sim;
delete CurrMol;
}
void
RemovePlanarityTest::testRemovePlanarity()
{
// fix random seed to something we know works, otherwise the
// constraints might be too strict for a randomly large displacement
srand(1632403515);
BasicInformation baseInformation;
Structure *CurrStruc = CurrMol->getHeadStruc();
std::string titania_unit_path = TITANIA_UNIT_TESTS_DIR__;
baseInformation.xyzFile.open(
(titania_unit_path +
"/systems/cppunit_input.tna.out.removePlanarity.xyz"),
std::ios::binary | std::ios::out | std::ios::trunc);
outputXYZ(CurrStruc->getHeadAtom(), baseInformation,
StructureOptions::Initial, "flattened structure");
removePlanarity(CurrStruc, *Sim, baseInformation);
// For the IPC geometry with all z-coordinates set to 0.0 (see constructor
// above), the initial eigensystem of the inertia tensor is:
//
// Moments of Inertia
// 174.659920 415.561870 590.221790
//
// After the coordinates are mangled by the Simplex Minimizer called by
// removePlanarity() the moments of inertia will no longer satisfy the
// planarity condition (I_z = Ix + Iy).
// The actual values of the moments of inertia will be different for each
// diastereoisomer, and as the function uses rand() to mutate the initial
// planar geometry, we don't know at which diastereoisomer the minimizer
// will arrive.
//
// The threshold in this test is set to a relaxed / optimized
// value of 200. For a proper, relaxed IPC geometry, a value around
// I_z - (Ix + Iy) = -232 is expected. With the limited constraints imposed
// in removePlanarity(), this may not be reached. Manual calculations with
// the current implementation and the above seed yield a value of -221.068025.
//
double MINIMUM_PLANARITY_VIOLATION = 200;
Tensor *ITensor =
CurrStruc->CalculateInertiaTensor(StructureOptions::Initial);
Eigen::Vector3d MomentsOfInertia = ITensor->getEvals();
outputXYZ(CurrStruc->getHeadAtom(), baseInformation,
StructureOptions::Initial, "de-flattened structure");
CPPUNIT_ASSERT(
fabs(MomentsOfInertia(2) - (MomentsOfInertia(1) + MomentsOfInertia(0))) >
MINIMUM_PLANARITY_VIOLATION);
}
| 33.747253
| 80
| 0.727125
|
volkerschmidts
|
e9f2b90b29c56da8ae57cf0ed91c7ab47f6a8ba1
| 36,069
|
hpp
|
C++
|
src/cpp_json/cpp_json__document.hpp
|
mrange/cppjson
|
553795705eeda5e2add18dd3345a4c01a9b4de99
|
[
"Apache-2.0"
] | null | null | null |
src/cpp_json/cpp_json__document.hpp
|
mrange/cppjson
|
553795705eeda5e2add18dd3345a4c01a9b4de99
|
[
"Apache-2.0"
] | null | null | null |
src/cpp_json/cpp_json__document.hpp
|
mrange/cppjson
|
553795705eeda5e2add18dd3345a4c01a9b4de99
|
[
"Apache-2.0"
] | null | null | null |
// ----------------------------------------------------------------------------------------------
// Copyright 2015 Mårten Rånge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------------------
#ifndef CPP_JSON__DOCUMENT_H
#define CPP_JSON__DOCUMENT_H
#include <algorithm>
#include <array>
#include <cmath>
#include <cwchar>
#include <cstdio>
#include <deque>
#include <memory>
#include <string>
#include <type_traits>
#include <vector>
#include <utility>
#include <tuple>
#include "cpp_json__parser.hpp"
#define CPP_JSON__NO_COPY_MOVE(name) \
name (name const &) = delete; \
name (name && ) = delete; \
name & operator= (name const &) = delete; \
name & operator= (name && ) = delete;
namespace cpp_json { namespace document
{
using doc_string_type = std::wstring ;
using doc_strings_type = std::vector<doc_string_type>;
using doc_char_type = doc_string_type::value_type ;
using doc_iter_type = doc_char_type const * ;
namespace details
{
constexpr auto default_size = 16U;
constexpr auto window_size = 70U;
constexpr auto hwindow_size = window_size / 2;
struct json_element__null ;
struct json_element__bool ;
struct json_element__number ;
struct json_element__string ;
struct json_element__array ;
struct json_element__object ;
struct json_element__error ;
struct json_document__impl ;
}
// Implement json_element_visitor to traverse the JSON DOM using 'apply' method
struct json_element_visitor
{
using ptr = std::shared_ptr<json_element_visitor> ;
json_element_visitor () = default;
virtual ~json_element_visitor () = default;
CPP_JSON__NO_COPY_MOVE (json_element_visitor);
virtual bool visit (details::json_element__null const & v) = 0;
virtual bool visit (details::json_element__bool const & v) = 0;
virtual bool visit (details::json_element__number const & v) = 0;
virtual bool visit (details::json_element__string const & v) = 0;
virtual bool visit (details::json_element__object const & v) = 0;
virtual bool visit (details::json_element__array const & v) = 0;
virtual bool visit (details::json_element__error const & v) = 0;
};
struct json_element
{
using ptr = json_element const *;
json_element () = default;
virtual ~json_element () = default;
CPP_JSON__NO_COPY_MOVE (json_element);
// Returns the number of children (object/array)
virtual std::size_t size () const = 0;
// Returns the child at index (object/array)
// if out of bounds returns an error DOM element
virtual ptr at (std::size_t idx) const = 0;
// Returns the child with name (object)
// if not found returns an error DOM element
virtual ptr get (doc_string_type const & name) const = 0;
// Returns all member names (object)
// May contain duplicates, is in order
virtual doc_strings_type names () const = 0;
// Returns true if DOM element represents an error
virtual bool is_error () const = 0;
// Returns true if DOM element represents an scalar
virtual bool is_scalar () const = 0;
// Returns true if DOM element represents a null value
virtual bool is_null () const = 0;
// Converts the value to a boolean value
virtual bool as_bool () const = 0;
// Converts the value to a double value
virtual double as_number () const = 0;
// Converts the value to a string value
virtual doc_string_type as_string () const = 0;
// Applies the JSON element visitor to the element
virtual bool apply (json_element_visitor & v) const = 0;
};
struct json_document
{
using ptr = std::shared_ptr<json_document> ;
json_document () = default;
virtual ~json_document () = default;
CPP_JSON__NO_COPY_MOVE (json_document);
// Gets the root element of the JSON document
virtual json_element::ptr root () const = 0;
// Creates a string from a JSON document
virtual doc_string_type to_string () const = 0;
};
namespace details
{
using array_members = std::vector<json_element::ptr> ;
using object_members = std::vector<std::tuple<doc_string_type, json_element::ptr>> ;
inline void to_string (doc_string_type & value, double d)
{
if (std::isnan (d))
{
value += L"\"NaN\"";
}
else if (std::isinf (d) && d < 0)
{
value += L"\"-Inf\"";
}
else if (std::isinf (d))
{
value += L"\"+Inf\"";
}
else
{
constexpr auto bsz = 64U;
wchar_t buffer[bsz];
std::swprintf (buffer, bsz, L"%G", d);
value += buffer;
}
}
struct json_non_printable_chars
{
using non_printable_char = std::array<doc_char_type , 8 >;
using non_printable_chars = std::array<non_printable_char , 32>;
json_non_printable_chars ()
{
for (auto iter = 0U; iter < table.size (); ++iter)
{
auto && v = table[iter];
std::fill (v.begin (), v.end (), 0);
auto fmt = L"\\u%04x";
switch (iter)
{
case '\b':
fmt = L"\\b";
break;
case '\f':
fmt = L"\\f";
break;
case '\n':
fmt = L"\\n";
break;
case '\r':
fmt = L"\\r";
break;
case '\t':
fmt = L"\\t";
break;
}
std::swprintf (v.data (), v.size (), fmt, iter);
}
}
static json_non_printable_chars const & get ()
{
// TODO: Race condition issue (until compilers widely support magic statics)
static json_non_printable_chars non_printable_chars;
return non_printable_chars;
}
inline void append (doc_string_type & s, doc_char_type ch) const noexcept
{
if (ch < table.size ())
{
auto p = table[ch].data ();
while (*p)
{
s += *p++;
}
}
else
{
s += ch;
}
}
private:
non_printable_chars table;
};
struct json_element__base : json_element
{
json_document__impl const * doc;
inline explicit json_element__base (json_document__impl const * doc)
: doc (doc)
{
}
ptr error_element () const;
ptr null_element () const;
};
struct json_element__scalar : json_element__base
{
inline explicit json_element__scalar (json_document__impl const * doc)
: json_element__base (doc)
{
}
std::size_t size () const override
{
return 0;
}
ptr at (std::size_t /*idx*/) const override
{
return error_element ();
}
ptr get (doc_string_type const & /*name*/) const override
{
return error_element ();
}
doc_strings_type names () const override
{
return doc_strings_type ();
}
bool is_error () const override
{
return false;
}
bool is_scalar () const override
{
return true;
}
};
struct json_element__null : json_element__scalar
{
inline explicit json_element__null (json_document__impl const * doc)
: json_element__scalar (doc)
{
}
bool is_null () const override
{
return true;
}
bool as_bool () const override
{
return false;
}
double as_number () const override
{
return 0.0;
}
doc_string_type as_string () const
{
return L"null";
}
bool apply (json_element_visitor & v) const
{
return v.visit (*this);
}
};
struct json_element__bool : json_element__scalar
{
bool const value;
inline explicit json_element__bool (json_document__impl const * doc, bool v)
: json_element__scalar (doc)
, value (v)
{
}
bool is_null () const override
{
return false;
}
bool as_bool () const override
{
return value;
}
double as_number () const override
{
return value ? 1.0 : 0.0;
}
doc_string_type as_string () const override
{
return value
? L"true"
: L"false"
;
}
bool apply (json_element_visitor & v) const
{
return v.visit (*this);
}
};
struct json_element__number : json_element__scalar
{
double const value;
inline explicit json_element__number (json_document__impl const * doc, double v)
: json_element__scalar (doc)
, value (v)
{
}
bool is_null () const override
{
return false;
}
bool as_bool () const override
{
return value != 0.0;
}
double as_number () const override
{
return value;
}
doc_string_type as_string () const override
{
doc_string_type result;
result.reserve (default_size);
to_string (result, value);
return result;
}
bool apply (json_element_visitor & v) const
{
return v.visit (*this);
}
};
struct json_element__string : json_element__scalar
{
doc_string_type const value;
inline explicit json_element__string (json_document__impl const * doc, doc_string_type v)
: json_element__scalar (doc)
, value (std::move (v))
{
}
bool is_null () const override
{
return false;
}
bool as_bool () const override
{
return !value.empty ();
}
double as_number () const override
{
doc_char_type * e = nullptr;
return std::wcstof (value.c_str (), &e);
}
doc_string_type as_string () const override
{
return value;
}
bool apply (json_element_visitor & v) const
{
return v.visit (*this);
}
};
struct json_element__container : json_element__base
{
inline explicit json_element__container (json_document__impl const * doc)
: json_element__base (doc)
{
}
bool is_error () const override
{
return false;
}
bool is_scalar () const override
{
return false;
}
bool is_null () const override
{
return false;
}
bool as_bool () const override
{
return false;
}
double as_number () const override
{
return 0.0;
}
doc_string_type as_string () const override
{
return doc_string_type ();
}
};
struct json_element__array : json_element__container
{
array_members members;
inline explicit json_element__array (
json_document__impl const * doc
, array_members && members
)
: json_element__container (doc)
, members (std::move (members))
{
}
std::size_t size () const override
{
return members.size ();
}
ptr at (std::size_t idx) const override
{
if (idx < members.size ())
{
return members[idx];
}
else
{
return error_element ();
}
}
ptr get (doc_string_type const & /*name*/) const override
{
return error_element ();
}
doc_strings_type names () const override
{
return doc_strings_type ();
}
bool apply (json_element_visitor & v) const
{
return v.visit (*this);
}
};
struct json_element__object : json_element__container
{
object_members members;
inline explicit json_element__object (
json_document__impl const * doc
, object_members && members
)
: json_element__container (doc)
, members (std::move (members))
{
}
std::size_t size () const override
{
return members.size ();
}
ptr at (std::size_t idx) const override
{
if (idx < size ())
{
return std::get<1> (members[idx]);
}
else
{
return error_element ();
}
}
ptr get (doc_string_type const & name) const override
{
for (auto && kv : members)
{
if (std::get<0> (kv) == name)
{
return std::get<1> (kv);
}
}
return error_element ();
}
doc_strings_type names () const override
{
doc_strings_type result;
result.reserve (members.size ());
for (auto && kv : members)
{
result.push_back (std::get<0> (kv));
}
return result;
}
bool apply (json_element_visitor & v) const
{
return v.visit (*this);
}
};
struct json_element__error : json_element__base
{
inline explicit json_element__error (json_document__impl const * doc)
: json_element__base (doc)
{
}
std::size_t size () const override
{
return 0;
}
ptr at (std::size_t /*idx*/) const override
{
return error_element ();
}
ptr get (doc_string_type const & /*name*/) const override
{
return error_element ();
}
doc_strings_type names () const override
{
return doc_strings_type ();
}
bool is_error () const override
{
return true;
}
bool is_scalar () const override
{
return true;
}
bool is_null () const override
{
return false;
}
bool as_bool () const override
{
return false;
}
double as_number () const override
{
return 0.0;
}
doc_string_type as_string () const override
{
return L"\"error\"";
}
bool apply (json_element_visitor & v) const
{
return v.visit (*this);
}
};
struct json_element_visitor__to_string : json_element_visitor
{
doc_string_type value;
inline void ch (doc_char_type c)
{
switch (c)
{
case '\"':
value += L"\\\"";
break;
case '\\':
value += L"\\\\";
break;
case '/':
value += L"\\/";
break;
default:
json_non_printable_chars::get ().append (value, c);
break;
}
}
inline void str (doc_string_type const & s)
{
value += L'"';
for (auto && c : s)
{
ch (c);
}
value += L'"';
}
bool visit (json_element__null const & /*v*/) override
{
value += L"null";
return true;
}
bool visit (json_element__bool const & v) override
{
value += (v.value ? L"true" : L"false");
return true;
}
bool visit (json_element__number const & v) override
{
to_string (value, v.value);
return true;
}
bool visit (json_element__string const & v) override
{
str (v.value);
return true;
}
bool visit (json_element__array const & v) override
{
value += L'[';
auto b = 0;
auto e = v.size ();
for (auto iter = b; iter < e; ++iter)
{
if (iter > b)
{
value += L", ";
}
auto && c = v.members[iter];
if (c)
{
c->apply (*this);
}
else
{
value += L"null";
}
}
value += L']';
return true;
}
bool visit (json_element__object const & v) override
{
value += L'{';
auto b = 0;
auto e = v.size ();
for (auto iter = b; iter < e; ++iter)
{
if (iter > b)
{
value += L", ";
}
auto && kv = v.members[iter];
auto && k = std::get<0> (kv);
auto && c = std::get<1> (kv);
str (k);
value += L':';
if (c)
{
c->apply (*this);
}
else
{
value += L"null";
}
}
value += L'}';
return true;
}
bool visit (json_element__error const & v) override
{
str (v.as_string ());
return true;
}
};
struct json_document__impl : json_document
{
using tptr = std::shared_ptr<json_document__impl> ;
json_element__null const null_value ;
json_element__bool const true_value ;
json_element__bool const false_value ;
json_element__error const error_value ;
std::deque<json_element__number> number_values ;
std::deque<json_element__string> string_values ;
std::deque<json_element__object> object_values ;
std::deque<json_element__array > array_values ;
json_element::ptr root_value ;
json_document__impl ()
: null_value (this)
, true_value (this, true)
, false_value (this, false)
, error_value (this)
, root_value (&null_value)
{
}
json_element::ptr root () const override
{
return root_value;
}
doc_string_type to_string () const override
{
details::json_element_visitor__to_string visitor;
CPP_JSON__ASSERT (root_value);
root_value->apply (visitor);
return std::move (visitor.value);
}
details::json_element__number * create_number (double v)
{
number_values.emplace_back (this, v);
return & number_values.back ();
}
details::json_element__string * create_string (doc_string_type && v)
{
string_values.emplace_back (this, std::move (v));
return & string_values.back ();
}
details::json_element__array * create_array (array_members && members)
{
array_values.emplace_back (this, std::move (members));
return & array_values.back ();
}
details::json_element__object * create_object (object_members && members)
{
object_values.emplace_back (this, std::move (members));
return & object_values.back ();
}
};
struct json_element_context : std::enable_shared_from_this<json_element_context>
{
using ptr = std::shared_ptr<json_element_context> ;
using ptrs = std::vector<ptr> ;
json_document__impl & document;
inline json_element_context (json_document__impl & doc)
: document (doc)
{
}
virtual ~json_element_context () = default;
CPP_JSON__NO_COPY_MOVE (json_element_context);
virtual bool add_value (json_element::ptr const & json ) = 0;
virtual bool set_key (doc_string_type && key ) = 0;
virtual json_element::ptr create_element (
ptrs & array_contexts
, ptrs & object_contexts
) = 0;
};
using json_element_contexts = json_element_context::ptrs;
struct json_element_context__root : json_element_context
{
inline json_element_context__root (json_document__impl & doc)
: json_element_context (doc)
{
}
virtual bool add_value (json_element::ptr const & json) override
{
CPP_JSON__ASSERT (json);
document.root_value = json;
return true;
}
virtual bool set_key (doc_string_type && /*key*/) override
{
CPP_JSON__ASSERT (false);
return true;
}
virtual json_element::ptr create_element (
json_element_contexts & /*array_contexts */
, json_element_contexts & /*object_contexts*/
) override
{
return document.root_value;
}
};
struct json_element_context__array : json_element_context
{
array_members values;
inline json_element_context__array (json_document__impl & doc)
: json_element_context (doc)
{
}
virtual bool add_value (json_element::ptr const & json) override
{
CPP_JSON__ASSERT (json);
values.push_back (json);
return true;
}
virtual bool set_key (doc_string_type && /*key*/) override
{
CPP_JSON__ASSERT (false);
return true;
}
virtual json_element::ptr create_element (
json_element_contexts & array_contexts
, json_element_contexts & /*object_contexts*/
) override
{
auto cap = values.capacity ();
values.shrink_to_fit ();
auto result = document.create_array (std::move (values));
array_contexts.push_back (shared_from_this ());
values.reserve (cap);
return result;
}
};
struct json_element_context__object : json_element_context
{
doc_string_type key ;
object_members values;
inline json_element_context__object (json_document__impl & doc)
: json_element_context (doc)
{
}
virtual bool add_value (json_element::ptr const & json) override
{
CPP_JSON__ASSERT (json);
values.push_back (std::make_tuple (std::move (key), json));
return true;
}
virtual bool set_key (doc_string_type && k) override
{
key = std::move (k);
return true;
}
virtual json_element::ptr create_element (
json_element_contexts & /*array_contexts */
, json_element_contexts & object_contexts
) override
{
auto cap = values.capacity ();
values.shrink_to_fit ();
auto result = document.create_object (std::move (values));
object_contexts.push_back (shared_from_this ());
values.reserve (cap);
return result;
}
};
// string_builder is used to build json strings as it has a slightly lower overhead than std::vector
// (on VS2015 RTM). It gives a measureable benefit as JSON documents often has lot of string values
template<typename TChar>
struct string_builder
{
using char_type = TChar;
static_assert (std::is_pod<char_type>::value, "char_type must be POD type");
inline string_builder () noexcept
: cap (default_size)
, sz (0)
, str (static_cast<char_type *> (std::malloc (cap * sizeof (char_type))))
{
CPP_JSON__ASSERT (str);
}
CPP_JSON__NO_COPY_MOVE (string_builder);
inline ~string_builder () noexcept
{
free (str);
}
inline void clear () noexcept
{
sz = 0;
}
inline void push_back (char_type ch) noexcept
{
if (sz >= cap)
{
cap <<= 1;
str = static_cast<char_type *> (std::realloc (str, cap * sizeof (char_type)));
CPP_JSON__ASSERT (str);
CPP_JSON__ASSERT (sz < cap);
}
str[sz] = ch;
++sz;
}
inline std::basic_string<char_type> create_string () const
{
return std::basic_string<char_type> (str, sz);
}
private:
std::size_t cap ;
std::size_t sz ;
char_type * str ;
};
struct builder_json_context
{
using string_type = doc_string_type ;
using char_type = doc_char_type ;
using iter_type = doc_iter_type ;
json_document__impl::tptr document ;
string_builder<char_type> current_string ;
json_element_contexts element_context ;
json_element_contexts array_contexts ;
json_element_contexts object_contexts ;
inline builder_json_context ()
: document (std::make_shared<json_document__impl> ())
{
element_context.reserve (default_size);
element_context.reserve (default_size);
element_context.reserve (default_size);
element_context.push_back (std::make_shared<json_element_context__root> (*document));
}
CPP_JSON__NO_COPY_MOVE (builder_json_context);
inline void expected_char (std::size_t /*pos*/, char_type /*ch*/) noexcept
{
}
inline void expected_chars (std::size_t /*pos*/, string_type const & /*chs*/) noexcept
{
}
inline void expected_token (std::size_t /*pos*/, string_type const & /*token*/) noexcept
{
}
inline void unexpected_token (std::size_t /*pos*/, string_type const & /*token*/) noexcept
{
}
inline void clear_string ()
{
current_string.clear ();
}
inline void push_char (char_type ch)
{
current_string.push_back (ch);
}
inline void push_wchar_t (wchar_t ch)
{
current_string.push_back (ch);
}
inline string_type get_string ()
{
return current_string.create_string ();
}
inline bool pop ()
{
CPP_JSON__ASSERT (!element_context.empty ());
auto back = element_context.back ();
CPP_JSON__ASSERT (back);
element_context.pop_back ();
CPP_JSON__ASSERT (!element_context.empty ());
auto && next = element_context.back ();
CPP_JSON__ASSERT (next);
auto && element = back->create_element (array_contexts, object_contexts);
CPP_JSON__ASSERT (element);
next->add_value (element);
return true;
}
bool array_begin ()
{
if (array_contexts.empty ())
{
element_context.push_back (std::make_shared<json_element_context__array> (*document));
}
else
{
element_context.push_back (array_contexts.back ());
array_contexts.pop_back ();
}
return true;
}
bool array_end ()
{
return pop ();
}
bool object_begin ()
{
if (object_contexts.empty ())
{
element_context.push_back (std::make_shared<json_element_context__object> (*document));
}
else
{
element_context.push_back (object_contexts.back ());
object_contexts.pop_back ();
}
return true;
}
bool member_key (string_type && s)
{
CPP_JSON__ASSERT (!element_context.empty ());
auto && back = element_context.back ();
CPP_JSON__ASSERT (back);
back->set_key (std::move (s));
return true;
}
bool object_end ()
{
return pop ();
}
bool bool_value (bool b)
{
auto v = b
? &document->true_value
: &document->false_value
;
CPP_JSON__ASSERT (!element_context.empty ());
auto && back = element_context.back ();
CPP_JSON__ASSERT (back);
back->add_value (v);
return true;
}
bool null_value ()
{
auto v = &document->null_value;
CPP_JSON__ASSERT (!element_context.empty ());
auto && back = element_context.back ();
CPP_JSON__ASSERT (back);
back->add_value (v);
return true;
}
bool string_value (string_type && s)
{
auto v = document->create_string (std::move (s));
CPP_JSON__ASSERT (!element_context.empty ());
auto && back = element_context.back ();
CPP_JSON__ASSERT (back);
back->add_value (v);
return true;
}
bool number_value (double d)
{
auto v = document->create_number (d);
CPP_JSON__ASSERT (!element_context.empty ());
auto && back = element_context.back ();
CPP_JSON__ASSERT (back);
back->add_value (v);
return true;
}
};
struct error_json_context
{
using string_type = doc_string_type ;
using char_type = doc_char_type ;
using iter_type = doc_iter_type ;
std::size_t error_pos ;
string_type current_string;
std::vector<char_type> exp_chars ;
std::vector<string_type> exp_tokens ;
std::vector<string_type> unexp_tokens ;
inline error_json_context ()
: error_pos (0)
{
exp_chars.reserve (default_size);
exp_tokens.reserve (default_size);
unexp_tokens.reserve (default_size);
}
CPP_JSON__NO_COPY_MOVE (error_json_context);
void expected_char (std::size_t pos, char_type ch)
{
if (error_pos == pos)
{
exp_chars.push_back (ch);
}
}
void expected_chars (std::size_t pos, string_type const & chs)
{
if (error_pos == pos)
{
for (auto && ch : chs)
{
expected_char (pos, ch);
}
}
}
void expected_token (std::size_t pos, string_type const & token)
{
if (error_pos == pos)
{
exp_tokens.push_back (token);
}
}
void unexpected_token (std::size_t pos, string_type const & token)
{
if (error_pos == pos)
{
unexp_tokens.push_back (token);
}
}
inline void clear_string ()
{
}
inline void push_char (char_type /*ch*/)
{
}
inline void push_wchar_t (wchar_t /*ch*/)
{
}
inline string_type const & get_string () noexcept
{
return current_string;
}
inline bool array_begin ()
{
return true;
}
inline bool array_end ()
{
return true;
}
inline bool object_begin ()
{
return true;
}
inline bool member_key (string_type const & /*s*/)
{
return true;
}
inline bool object_end ()
{
return true;
}
inline bool bool_value (bool /*b*/)
{
return true;
}
inline bool null_value ()
{
return true;
}
inline bool string_value (string_type const & /*s*/)
{
return true;
}
inline bool number_value (double /*d*/)
{
return true;
}
};
inline json_element::ptr json_element__base::error_element () const
{
return & doc->error_value;
}
inline json_element::ptr json_element__base::null_element () const
{
return & doc->null_value;
}
}
struct json_parser
{
// Parses a JSON string into a JSON document 'result' if successful.
// 'pos' indicates the first non-consumed character (which may lay beyond the last character in the input string)
static bool parse (doc_string_type const & json, std::size_t & pos, json_document::ptr & result)
{
auto begin = json.data () ;
auto end = begin + json.size ();
cpp_json::parser::json_parser<details::builder_json_context> jp (begin, end);
if (jp.try_parse__json ())
{
pos = jp.pos ();
result = jp.document;
return true;
}
else
{
pos = jp.pos ();
result.reset ();
return false;
}
}
// Parses a JSON string into a JSON document 'result' if successful.
// If parse fails 'error' contains an error description.
// 'pos' indicates the first non-consumed character (which may lay beyond the last character in the input string)
static bool parse (doc_string_type const & json, std::size_t & pos, json_document::ptr & result, doc_string_type & error)
{
auto begin = json.data () ;
auto end = begin + json.size ();
cpp_json::parser::json_parser<details::builder_json_context> jp (begin, end);
if (jp.try_parse__json ())
{
pos = jp.pos ();
result = jp.document;
return true;
}
else
{
pos = jp.pos ();
result.reset ();
cpp_json::parser::json_parser<details::error_json_context> ejp (begin, end);
ejp.error_pos = jp.pos ();
auto eresult = ejp.try_parse__json ();
CPP_JSON__ASSERT (!eresult);
auto sz = ejp.exp_chars.size () + ejp.exp_tokens.size ();
std::vector<doc_string_type> expected = std::move (ejp.exp_tokens);
std::vector<doc_string_type> unexpected = std::move (ejp.unexp_tokens);
expected.reserve (sz);
for (auto ch : ejp.exp_chars)
{
details::error_json_context::char_type token[] = {'\'', ch, '\'', 0};
expected.push_back (doc_string_type (token));
}
std::sort (expected.begin (), expected.end ());
std::sort (unexpected.begin (), unexpected.end ());
expected.erase (std::unique (expected.begin (), expected.end ()), expected.end ());
unexpected.erase (std::unique (unexpected.begin (), unexpected.end ()), unexpected.end ());
doc_string_type msg;
auto newline = [&msg] ()
{
msg += L'\n';
};
msg += L"Failed to parse input as JSON";
newline ();
auto left = pos < details::hwindow_size ? 0U : pos - details::hwindow_size;
auto right = std::min (json.size (), left + details::window_size);
auto apos = pos - left;
for (auto iter = left; iter < right; ++iter)
{
auto c = json[iter];
if (c < ' ')
{
msg += ' ';
}
else
{
msg += c;
}
}
newline ();
for (auto iter = 0U; iter < apos; ++iter)
{
msg += L'-';
}
msg += L"^ Pos: ";
{
constexpr auto bsz = 12U;
wchar_t spos[bsz] = {};
std::swprintf (spos, bsz, L"%zd", pos);
msg += spos;
}
auto append = [&msg, &newline] (wchar_t const * prepend, std::vector<doc_string_type> const & vs)
{
CPP_JSON__ASSERT (prepend);
if (!vs.empty ())
{
newline ();
msg += prepend;
auto sz = vs.size();
for (auto iter = 0U; iter < sz; ++iter)
{
if (iter == 0U)
{
}
else if (iter + 1U == sz)
{
msg += L" or ";
}
else
{
msg += L", ";
}
msg += vs[iter];
}
}
};
append (L"Expected: " , expected);
append (L"Unexpected: " , unexpected);
error = std::move (msg);
return false;
}
}
};
} }
#endif // CPP_JSON__DOCUMENT_H
| 24.420447
| 125
| 0.535723
|
mrange
|
e9f3df48926e0b921adc4f4b77206fb004842a8c
| 4,726
|
cpp
|
C++
|
src/desktop/app/ComponentManager.cpp
|
varunamachi/tanyatu
|
ce055e0fb0b688054fe19ef39b09a6ca655e2457
|
[
"MIT"
] | 1
|
2018-01-07T18:11:04.000Z
|
2018-01-07T18:11:04.000Z
|
src/desktop/app/ComponentManager.cpp
|
varunamachi/tanyatu
|
ce055e0fb0b688054fe19ef39b09a6ca655e2457
|
[
"MIT"
] | null | null | null |
src/desktop/app/ComponentManager.cpp
|
varunamachi/tanyatu
|
ce055e0fb0b688054fe19ef39b09a6ca655e2457
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
* Copyright (c) 2014 Varuna L Amachi. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
#include <QHBoxLayout>
#include <QSplitter>
#include <QIcon>
#include "ComponentManager.h"
using namespace GreenChilli;
ComponentManager *ComponentManager::s_instance = 0;
void ComponentManager::destroy()
{
if( s_instance ) {
delete s_instance;
}
}
ComponentManager* ComponentManager::get()
{
if( ! s_instance ) {
s_instance = new ComponentManager();
}
return s_instance;
}
ComponentManager::ComponentManager( QWidget *parent ) :
QWidget( parent )
{
setupUi();
}
ComponentManager::~ComponentManager()
{
m_nameToIndex.clear();
qDeleteAll( m_components.begin(), m_components.end() );
}
void ComponentManager::setupUi()
{
m_mainWidget = new QStackedWidget( this );
m_buttonLayout = new QHBoxLayout();
QHBoxLayout *topLayout = new QHBoxLayout();
m_buttonLayout->addStretch();
topLayout->addLayout( m_buttonLayout );
topLayout->addStretch();
QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addLayout( topLayout );
mainLayout->addWidget( m_mainWidget );
mainLayout->setContentsMargins( QMargins() );
mainLayout->setSpacing( 0 );
m_mainWidget->setContentsMargins( QMargins() );
m_buttonLayout->setContentsMargins( 4, 2, 0, 0 );
m_buttonLayout->setSpacing( 5 );
this->setLayout( mainLayout );
}
QList< ChilliComponent *> ComponentManager::allComponents() const
{
return m_components.values();
}
const ChilliComponent* ComponentManager::component( QString componentId ) const
{
return m_components.value( componentId );
}
const ChilliComponent *ComponentManager::currentComponent() const
{
QWidget *widget = m_mainWidget->currentWidget();
if( widget ) {
return static_cast< ChilliComponent *>( widget );
}
return 0;
}
void ComponentManager::addComponent( GreenChilli::ChilliComponent *component )
{
if( component && ! m_components.contains( component->componentId() )) {
m_components.insert( component->componentId(), component );
IndexButton *button = new IndexButton( m_components.size() - 1,
component->componentName(),
this );
m_buttons.append( button );
m_nameToIndex.insert( component->componentId(),
m_components.size() - 1 );
m_buttonLayout->insertWidget( m_buttonLayout->count() - 1, button );
connect( button, SIGNAL( activated( int )),
this, SLOT( onIndexSelected( int )));
m_mainWidget->addWidget( component );
component->setContentsMargins( QMargins() );
emit componentAdded( component );
if( m_components.size() == 1 ) {
button->setChecked( true );
m_mainWidget->setCurrentIndex( 0 );
}
}
}
void ComponentManager::selectComponent( QString componentId )
{
if( m_nameToIndex.contains( componentId )) {
int index = m_nameToIndex.value( componentId );
m_buttons.at( m_mainWidget->currentIndex() )->setChecked( false );
m_buttons.at( index )->setChecked( true );
m_mainWidget->setCurrentIndex( index );
emit componentSelected( m_components.value( componentId ));
}
}
void ComponentManager::onIndexSelected( int row )
{
m_buttons.at( m_mainWidget->currentIndex() )->setChecked( false );
m_mainWidget->setCurrentIndex( row );
}
| 30.688312
| 80
| 0.655946
|
varunamachi
|
e9f788748cb58234056260f15c69225482563ced
| 29,958
|
hpp
|
C++
|
lighter_int.hpp
|
snake5/lighter
|
dfaaaeadf00d2a9302f937c9b8138202b4e58ef5
|
[
"MIT"
] | 5
|
2015-08-31T15:37:47.000Z
|
2020-09-30T11:57:24.000Z
|
lighter_int.hpp
|
snake5/lighter
|
dfaaaeadf00d2a9302f937c9b8138202b4e58ef5
|
[
"MIT"
] | null | null | null |
lighter_int.hpp
|
snake5/lighter
|
dfaaaeadf00d2a9302f937c9b8138202b4e58ef5
|
[
"MIT"
] | null | null | null |
#pragma once
#define _USE_MATH_DEFINES
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <float.h>
#include <vector>
#include <string>
#include <algorithm>
#include "lighter.h"
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# undef _WIN32_WINNT
# define _WIN32_WINNT 0x0600
# undef WINVER
# define WINVER 0x0600
# include <windows.h>
# define ltrthread_sleep( ms ) Sleep( (DWORD) ms )
# define ltrmutex_t CRITICAL_SECTION
# define ltrcondvar_t CONDITION_VARIABLE
# define ltrthread_t HANDLE
# define threadret_t DWORD __stdcall
# define threadarg_t void*
# define ltrthread_create( toT, func, data ) toT = CreateThread( NULL, 1024, func, data, 0, NULL )
# define ltrthread_self() GetCurrentThread()
# define ltrthread_join( T ) for(;;){ WaitForMultipleObjects( 1, &T, TRUE, INFINITE ); CloseHandle( T ); break; }
# define ltrthread_equal( T1, T2 ) (T1 == T2)
# define ltrmutex_init( M ) InitializeCriticalSection( &M )
# define ltrmutex_destroy( M ) DeleteCriticalSection( &M )
# define ltrmutex_lock( M ) EnterCriticalSection( &M )
# define ltrmutex_unlock( M ) LeaveCriticalSection( &M )
# define ltrcondvar_init( CV ) InitializeConditionVariable( &(CV) )
# define ltrcondvar_destroy( CV )
# define ltrcondvar_sleep( CV, M ) SleepConditionVariableCS( &(CV), &(M), INFINITE )
# define ltrcondvar_wakeall( CV ) WakeAllConditionVariable( &(CV) )
static int ltrnumcpus()
{
SYSTEM_INFO sysinfo;
GetSystemInfo( &sysinfo );
return sysinfo.dwNumberOfProcessors;
}
#else
# include <unistd.h>
# include <pthread.h>
static void ltrthread_sleep( uint32_t ms )
{
if( ms >= 1000 )
{
sleep( ms / 1000 );
ms %= 1000;
}
if( ms > 0 )
{
usleep( ms * 1000 );
}
}
# define ltrmutex_t pthread_mutex_t
# define ltrcondvar_t pthread_cond_t
# define ltrthread_t pthread_t
# define threadret_t void*
# define threadarg_t void*
# define ltrthread_create( toT, func, data ) pthread_create( &toT, NULL, func, data )
# define ltrthread_self() pthread_self()
# define ltrthread_join( T ) pthread_join( T, NULL )
# define ltrthread_equal( T1, T2 ) pthread_equal( T1, T2 )
# define ltrmutex_init( M ) pthread_mutex_init( &M, NULL )
# define ltrmutex_destroy( M ) pthread_mutex_destroy( &M )
# define ltrmutex_lock( M ) pthread_mutex_lock( &M )
# define ltrmutex_unlock( M ) pthread_mutex_unlock( &M )
# define ltrcondvar_init( CV ) pthread_cond_init( &(CV), NULL )
# define ltrcondvar_destroy( CV ) pthread_cond_destroy( &(CV) )
# define ltrcondvar_sleep( CV, M ) pthread_cond_wait( &(CV), &(M) )
# define ltrcondvar_wakeall( CV ) pthread_cond_broadcast( &(CV) )
static int ltrnumcpus()
{
return sysconf( _SC_NPROCESSORS_ONLN );
}
#endif
#ifndef FORCEINLINE
#ifdef _MSC_VER
#define FORCEINLINE __forceinline
#else
#define FORCEINLINE inline __attribute__((__always_inline__))
#endif
#endif
struct LTRMutex
{
LTRMutex(){ ltrmutex_init( mutex ); }
~LTRMutex(){ ltrmutex_destroy( mutex ); }
void Lock(){ ltrmutex_lock( mutex ); }
void Unlock(){ ltrmutex_unlock( mutex ); }
void SleepCV( ltrcondvar_t* cv ){ ltrcondvar_sleep( *cv, mutex ); }
ltrmutex_t mutex;
};
struct LTRMutexLock
{
LTRMutexLock( LTRMutex& m ) : mutex( m ){ m.Lock(); }
~LTRMutexLock(){ mutex.Unlock(); }
LTRMutex& mutex;
};
struct LTRWorker
{
struct IO
{
void* shared;
void* item;
size_t i;
};
typedef void (*WorkProc) (IO*);
LTRWorker() :
m_shared( NULL ),
m_items( NULL ),
m_itemSize( 0 ),
m_itemCount( 0 ),
m_nextItem( 0 ),
m_numDone( 0 ),
m_workProc( NULL ),
m_exit( false )
{
ltrcondvar_init( m_hasWork );
ltrcondvar_init( m_hasDone );
}
~LTRWorker()
{
m_exit = true;
ltrcondvar_wakeall( m_hasWork );
for( size_t i = 0; i < m_threads.size(); ++i )
{
ltrthread_join( m_threads[ i ] );
}
ltrcondvar_destroy( m_hasWork );
ltrcondvar_destroy( m_hasDone );
}
void Init( int nt = ltrnumcpus() )
{
if( m_threads.size() )
return;
m_threads.resize( nt );
for( int i = 0; i < nt; ++i )
{
ltrthread_create( m_threads[ i ], threadproc, this );
}
}
void WaitForEnd()
{
m_mutex.Lock();
while( m_numDone < m_itemCount )
{
m_mutex.SleepCV( &m_hasDone );
}
m_shared = NULL;
m_items = NULL;
m_itemSize = 0;
m_itemCount = 0;
m_nextItem = 0;
m_numDone = 0;
m_workProc = NULL;
m_mutex.Unlock();
}
void DoWork( void* shared, void* items, size_t size, size_t count, WorkProc wp, bool stay = true )
{
m_mutex.Lock();
m_shared = shared;
m_items = (char*) items;
m_itemSize = size;
m_itemCount = count;
m_nextItem = 0;
m_numDone = 0;
m_workProc = wp;
ltrcondvar_wakeall( m_hasWork );
m_mutex.Unlock();
if( stay )
WaitForEnd();
}
void IntProcess()
{
m_mutex.Lock();
while( !m_exit )
{
if( m_nextItem < m_itemCount )
{
size_t myitem = m_nextItem++;
m_mutex.Unlock();
IO io = { m_shared, m_items + myitem * m_itemSize, myitem };
m_workProc( &io );
m_mutex.Lock();
m_numDone++;
if( m_numDone < m_itemCount )
continue; // there may be more work
}
ltrcondvar_wakeall( m_hasDone );
m_mutex.SleepCV( &m_hasWork );
}
m_mutex.Unlock();
}
static threadret_t threadproc( threadarg_t arg )
{
LTRWorker* w = (LTRWorker*) arg;
w->IntProcess();
return 0;
}
void* m_shared;
char* m_items;
size_t m_itemSize;
size_t m_itemCount;
size_t m_nextItem;
size_t m_numDone;
WorkProc m_workProc;
std::vector< ltrthread_t > m_threads;
LTRMutex m_mutex;
volatile bool m_exit;
ltrcondvar_t m_hasWork;
ltrcondvar_t m_hasDone;
};
#define SMALL_FLOAT 0.001f
// #define LTR_DEBUG 1
#ifdef LTR_DEBUG
#define DBG( x ) x
#else
#define DBG( x )
#endif
FORCEINLINE float randf(){ return (float) rand() / (float) RAND_MAX; }
FORCEINLINE float safe_fdiv( float x, float d ){ return d ? x / d : 0; }
double ltr_gettime();
template< class T > FORCEINLINE T TMIN( const T& a, const T& b ){ return a < b ? a : b; }
template< class T > FORCEINLINE T TMAX( const T& a, const T& b ){ return a > b ? a : b; }
template< class T > FORCEINLINE void TMEMSET( T* a, size_t c, const T& v )
{
for( size_t i = 0; i < c; ++i )
a[ i ] = v;
}
template< class T > FORCEINLINE void TMEMCOPY( T* a, const T* src, size_t c ){ memcpy( a, src, c * sizeof(T) ); }
template< class T, class S > FORCEINLINE T TLERP( const T& a, const T& b, const S& s ){ return a * ( S(1) - s ) + b * s; }
template< class T > FORCEINLINE typename T::value_type* VDATA( T& vec, size_t at = 0 ){ return ( vec.size() ? &vec[0] : (typename T::value_type*) NULL ) + at; }
struct Vec2
{
float x, y;
static Vec2 Create( float x ){ Vec2 v = { x, x }; return v; }
static Vec2 Create( float x, float y ){ Vec2 v = { x, y }; return v; }
FORCEINLINE Vec2 operator + () const { return *this; }
FORCEINLINE Vec2 operator - () const { Vec2 v = { -x, -y }; return v; }
FORCEINLINE Vec2 operator + ( const Vec2& o ) const { Vec2 v = { x + o.x, y + o.y }; return v; }
FORCEINLINE Vec2 operator - ( const Vec2& o ) const { Vec2 v = { x - o.x, y - o.y }; return v; }
FORCEINLINE Vec2 operator * ( const Vec2& o ) const { Vec2 v = { x * o.x, y * o.y }; return v; }
FORCEINLINE Vec2 operator / ( const Vec2& o ) const { Vec2 v = { x / o.x, y / o.y }; return v; }
FORCEINLINE Vec2 operator + ( float f ) const { Vec2 v = { x + f, y + f }; return v; }
FORCEINLINE Vec2 operator - ( float f ) const { Vec2 v = { x - f, y - f }; return v; }
FORCEINLINE Vec2 operator * ( float f ) const { Vec2 v = { x * f, y * f }; return v; }
FORCEINLINE Vec2 operator / ( float f ) const { Vec2 v = { x / f, y / f }; return v; }
FORCEINLINE Vec2& operator += ( const Vec2& o ){ x += o.x; y += o.y; return *this; }
FORCEINLINE Vec2& operator -= ( const Vec2& o ){ x -= o.x; y -= o.y; return *this; }
FORCEINLINE Vec2& operator *= ( const Vec2& o ){ x *= o.x; y *= o.y; return *this; }
FORCEINLINE Vec2& operator /= ( const Vec2& o ){ x /= o.x; y /= o.y; return *this; }
FORCEINLINE Vec2& operator += ( float f ){ x += f; y += f; return *this; }
FORCEINLINE Vec2& operator -= ( float f ){ x -= f; y -= f; return *this; }
FORCEINLINE Vec2& operator *= ( float f ){ x *= f; y *= f; return *this; }
FORCEINLINE Vec2& operator /= ( float f ){ x /= f; y /= f; return *this; }
FORCEINLINE bool operator == ( const Vec2& o ) const { return x == o.x && y == o.y; }
FORCEINLINE bool operator != ( const Vec2& o ) const { return x != o.x || y != o.y; }
FORCEINLINE Vec2 Perp() const { Vec2 v = { y, -x }; return v; }
FORCEINLINE float LengthSq() const { return x * x + y * y; }
FORCEINLINE float Length() const { return sqrtf( LengthSq() ); }
FORCEINLINE Vec2 Normalized() const
{
float lensq = LengthSq();
if( lensq == 0 )
{
Vec2 v = { 0, 0 };
return v;
}
float invlen = 1.0f / sqrtf( lensq );
Vec2 v = { x * invlen, y * invlen };
return v;
}
void Dump( FILE* f ) const
{
fprintf( f, "Vec2 ( %.2f %.2f )\n", x, y );
}
};
static FORCEINLINE Vec2 V2( float x, float y ){ Vec2 o = { x, y }; return o; }
FORCEINLINE float Vec2Dot( const Vec2& v1, const Vec2& v2 ){ return v1.x * v2.x + v1.y * v2.y; }
FORCEINLINE float Vec2Cross( const Vec2& v1, const Vec2& v2 )
{
return ( v1.x * v2.y ) - ( v1.y * v2.x );
}
struct Vec3
{
float x, y, z;
static FORCEINLINE Vec3 Create( float x ){ Vec3 v = { x, x, x }; return v; }
static FORCEINLINE Vec3 Create( float x, float y, float z ){ Vec3 v = { x, y, z }; return v; }
static FORCEINLINE Vec3 CreateFromPtr( const float* x ){ Vec3 v = { x[0], x[1], x[2] }; return v; }
static FORCEINLINE Vec3 CreateRandomVector( float maxdist )
{
float a = randf() * (float)M_PI * 2;
float b = randf() * (float)M_PI;
float d = randf() * maxdist;
float ac = cos( a ), as = sin( a );
float bc = cos( b ), bs = sin( b );
Vec3 v = { ac * bs * d, as * bs * d, bc * d };
return v;
}
static FORCEINLINE Vec3 CreateRandomVectorDirDvg( const Vec3& dir, float dvg );
static FORCEINLINE Vec3 CreateSpiralDirVector( const Vec3& dir, float randoff, int i, int sample_count );
static FORCEINLINE Vec3 Min( const Vec3& a, const Vec3& b ){ return Create( TMIN( a.x, b.x ), TMIN( a.y, b.y ), TMIN( a.z, b.z ) ); }
static FORCEINLINE Vec3 Max( const Vec3& a, const Vec3& b ){ return Create( TMAX( a.x, b.x ), TMAX( a.y, b.y ), TMAX( a.z, b.z ) ); }
FORCEINLINE Vec3 operator + () const { return *this; }
FORCEINLINE Vec3 operator - () const { Vec3 v = { -x, -y, -z }; return v; }
FORCEINLINE Vec3 operator + ( const Vec3& o ) const { Vec3 v = { x + o.x, y + o.y, z + o.z }; return v; }
FORCEINLINE Vec3 operator - ( const Vec3& o ) const { Vec3 v = { x - o.x, y - o.y, z - o.z }; return v; }
FORCEINLINE Vec3 operator * ( const Vec3& o ) const { Vec3 v = { x * o.x, y * o.y, z * o.z }; return v; }
FORCEINLINE Vec3 operator / ( const Vec3& o ) const { Vec3 v = { x / o.x, y / o.y, z / o.z }; return v; }
FORCEINLINE Vec3 operator + ( float f ) const { Vec3 v = { x + f, y + f, z + f }; return v; }
FORCEINLINE Vec3 operator - ( float f ) const { Vec3 v = { x - f, y - f, z - f }; return v; }
FORCEINLINE Vec3 operator * ( float f ) const { Vec3 v = { x * f, y * f, z * f }; return v; }
FORCEINLINE Vec3 operator / ( float f ) const { Vec3 v = { x / f, y / f, z / f }; return v; }
FORCEINLINE Vec3& operator += ( const Vec3& o ){ x += o.x; y += o.y; z += o.z; return *this; }
FORCEINLINE Vec3& operator -= ( const Vec3& o ){ x -= o.x; y -= o.y; z -= o.z; return *this; }
FORCEINLINE Vec3& operator *= ( const Vec3& o ){ x *= o.x; y *= o.y; z *= o.z; return *this; }
FORCEINLINE Vec3& operator /= ( const Vec3& o ){ x /= o.x; y /= o.y; z /= o.z; return *this; }
FORCEINLINE Vec3& operator += ( float f ){ x += f; y += f; z += f; return *this; }
FORCEINLINE Vec3& operator -= ( float f ){ x -= f; y -= f; z -= f; return *this; }
FORCEINLINE Vec3& operator *= ( float f ){ x *= f; y *= f; z *= f; return *this; }
FORCEINLINE Vec3& operator /= ( float f ){ x /= f; y /= f; z /= f; return *this; }
FORCEINLINE bool operator == ( const Vec3& o ) const { return x == o.x && y == o.y && z == o.z; }
FORCEINLINE bool operator != ( const Vec3& o ) const { return x != o.x || y != o.y || z != o.z; }
FORCEINLINE bool IsZero() const { return x == 0 && y == 0 && z == 0; }
FORCEINLINE bool NearZero() const { return fabs(x) < SMALL_FLOAT && fabs(y) < SMALL_FLOAT && fabs(z) < SMALL_FLOAT; }
FORCEINLINE float LengthSq() const { return x * x + y * y + z * z; }
FORCEINLINE float Length() const { return sqrtf( LengthSq() ); }
FORCEINLINE Vec3 Normalized() const
{
float lensq = LengthSq();
if( lensq == 0 )
{
Vec3 v = { 0, 0, 0 };
return v;
}
float invlen = 1.0f / sqrtf( lensq );
Vec3 v = { x * invlen, y * invlen, z * invlen };
return v;
}
void Dump( FILE* f ) const
{
fprintf( f, "Vec3 ( %.2f %.2f %.2f )\n", x, y, z );
}
};
FORCEINLINE Vec3 operator + ( float f, const Vec3& v ){ Vec3 out = { f + v.x, f + v.y, f + v.z }; return out; }
FORCEINLINE Vec3 operator - ( float f, const Vec3& v ){ Vec3 out = { f - v.x, f - v.y, f - v.z }; return out; }
FORCEINLINE Vec3 operator * ( float f, const Vec3& v ){ Vec3 out = { f * v.x, f * v.y, f * v.z }; return out; }
FORCEINLINE Vec3 operator / ( float f, const Vec3& v ){ Vec3 out = { f / v.x, f / v.y, f / v.z }; return out; }
static FORCEINLINE Vec3 V3( float x ){ Vec3 o = { x, x, x }; return o; }
static FORCEINLINE Vec3 V3( float x, float y, float z ){ Vec3 o = { x, y, z }; return o; }
static FORCEINLINE Vec3 V3P( const float* x ){ Vec3 o = { x[0], x[1], x[2] }; return o; }
FORCEINLINE float Vec3Dot( const Vec3& v1, const Vec3& v2 ){ return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; }
FORCEINLINE Vec3 Vec3Cross( const Vec3& v1, const Vec3& v2 )
{
Vec3 out =
{
v1.y * v2.z - v1.z * v2.y,
v1.z * v2.x - v1.x * v2.z,
v1.x * v2.y - v1.y * v2.x,
};
return out;
}
Vec3 Vec3::CreateRandomVectorDirDvg( const Vec3& dir, float dvg )
{
float a = randf() * (float)M_PI * 2;
float b = randf() * (float)M_PI * dvg;
float ac = cos( a ), as = sin( a );
float bc = cos( b ), bs = sin( b );
Vec3 diffvec = { dir.y, -dir.z, dir.x };
Vec3 up = Vec3Cross( dir, diffvec ).Normalized();
Vec3 rt = Vec3Cross( dir, up );
return ac * bs * rt + as * bs * up + bc * dir;
}
#define DEG2RAD( x ) ((x)/180.0f*(float)M_PI)
Vec3 Vec3::CreateSpiralDirVector( const Vec3& dir, float randoff, int i, int sample_count )
{
float q = ( i + 0.5f ) / sample_count;
float cos_side = sqrt( q );
float sin_side = sin( acos( cos_side ) );
float angle = ( i + randoff ) * DEG2RAD( 137.508f );
float cos_around = cos( angle );
float sin_around = sin( angle );
Vec3 diffvec = { dir.y, -dir.z, dir.x };
Vec3 up = Vec3Cross( dir, diffvec ).Normalized();
Vec3 rt = Vec3Cross( dir, up );
return cos_around * sin_side * rt + sin_around * sin_side * up + cos_side * dir;
}
struct Vec4
{
float x, y, z, w;
FORCEINLINE Vec4 operator + ( const Vec4& o ) const { Vec4 v = { x + o.x, y + o.y, z + o.z, w + o.w }; return v; }
FORCEINLINE Vec4 operator - ( const Vec4& o ) const { Vec4 v = { x - o.x, y - o.y, z - o.z, w - o.w }; return v; }
FORCEINLINE Vec4 operator * ( float f ) const { Vec4 v = { x * f, y * f, z * f, w * f }; return v; }
Vec3 ToVec3() const { return Vec3::Create( x, y, z ); }
};
static FORCEINLINE Vec4 V4( float x ){ Vec4 o = { x, x, x, x }; return o; }
static FORCEINLINE Vec4 V4( float x, float y, float z, float w ){ Vec4 o = { x, y, z, w }; return o; }
static FORCEINLINE Vec4 V4( const Vec3& v, float w ){ Vec4 o = { v.x, v.y, v.z, w }; return o; }
struct Mat4
{
union
{
float a[16];
float m[4][4];
};
void SetIdentity()
{
for( int i = 0; i < 4; ++i )
for( int j = 0; j < 4; ++j )
m[i][j] = i == j;
}
static Mat4 CreateIdentity()
{
Mat4 m;
m.SetIdentity();
return m;
}
FORCEINLINE Vec3 Transform( const Vec3& v, float w ) const
{
Vec3 out =
{
v.x * m[0][0] + v.y * m[1][0] + v.z * m[2][0] + m[3][0] * w,
v.x * m[0][1] + v.y * m[1][1] + v.z * m[2][1] + m[3][1] * w,
v.x * m[0][2] + v.y * m[1][2] + v.z * m[2][2] + m[3][2] * w,
};
return out;
}
FORCEINLINE Vec3 TransformPos( const Vec3& pos ) const { return Transform( pos, 1.0f ); }
FORCEINLINE Vec3 TransformNormal( const Vec3& nrm ) const { return Transform( nrm, 0.0f ); }
bool InvertTo( Mat4& out );
FORCEINLINE void Transpose()
{
std::swap( m[1][0], m[0][1] );
std::swap( m[2][0], m[0][2] );
std::swap( m[3][0], m[0][3] );
std::swap( m[2][1], m[1][2] );
std::swap( m[3][1], m[1][3] );
std::swap( m[3][2], m[2][3] );
}
void GenNormalMatrix( Mat4& out ) const
{
out.m[0][0] = m[0][0]; out.m[0][1] = m[0][1]; out.m[0][2] = m[0][2];
out.m[1][0] = m[1][0]; out.m[1][1] = m[1][1]; out.m[1][2] = m[1][2];
out.m[2][0] = m[2][0]; out.m[2][1] = m[2][1]; out.m[2][2] = m[2][2];
out.m[0][3] = out.m[1][3] = out.m[2][3] = 0;
out.m[3][0] = out.m[3][1] = out.m[3][2] = 0;
out.m[3][3] = 1;
out.InvertTo( out );
out.Transpose();
}
void Dump( FILE* f ) const
{
fprintf( f, "Mat4 (\n" );
fprintf( f, " %.2f %.2f %.2f %.2f\n", m[0][0], m[0][1], m[0][2], m[0][3] );
fprintf( f, " %.2f %.2f %.2f %.2f\n", m[1][0], m[1][1], m[1][2], m[1][3] );
fprintf( f, " %.2f %.2f %.2f %.2f\n", m[2][0], m[2][1], m[2][2], m[2][3] );
fprintf( f, " %.2f %.2f %.2f %.2f\n", m[3][0], m[3][1], m[3][2], m[3][3] );
fprintf( f, ")\n" );
}
};
typedef std::vector< u32 > U32Vector;
typedef std::vector< float > FloatVector;
typedef std::vector< Vec2 > Vec2Vector;
typedef std::vector< Vec3 > Vec3Vector;
typedef std::vector< Vec4 > Vec4Vector;
typedef std::vector< Mat4 > Mat4Vector;
typedef std::vector< ltr_WorkOutput > WorkOutputVector;
float TriangleArea( const Vec3& P1, const Vec3& P2, const Vec3& P3 );
float CalculateSampleArea( const Vec2& tex1, const Vec2& tex2, const Vec2& tex3, const Vec3& pos1, const Vec3& pos2, const Vec3& pos3 );
void TransformPositions( Vec3* out, Vec3* arr, size_t count, const Mat4& matrix );
void TransformNormals( Vec3* out, Vec3* arr, size_t count, const Mat4& matrix );
void RasterizeTriangle2D( Vec3* image, i32 width, i32 height, const Vec2& p1, const Vec2& p2, const Vec2& p3, const Vec3& v1, const Vec3& v2, const Vec3& v3 );
void RasterizeTriangle2D_x2_ex( Vec3* img1, Vec3* img2, Vec4* img3, i32 width, i32 height, float margin,
const Vec2& p1, const Vec2& p2, const Vec2& p3,
const Vec3& va1, const Vec3& va2, const Vec3& va3,
const Vec3& vb1, const Vec3& vb2, const Vec3& vb3,
const Vec4& vc1, const Vec4& vc2, const Vec4& vc3 );
void Generate_Gaussian_Kernel( float* out, int ext, float radius );
void Convolve_Transpose( float* src, float* dst, u32 width, u32 height, int blur_ext, float* kernel, float* tmp );
void Downsample2X( float* dst, unsigned dstW, unsigned dstH, float* src, unsigned srcW, unsigned srcH );
// BSP tree
// - best split plane is chosen by triangle normals and general direction of vertex positions (longest projection)
// - triangles are split to fit in the node
struct AABB3
{
Vec3 bbmin;
Vec3 bbmax;
FORCEINLINE bool Valid() const { return bbmin.x <= bbmax.x && bbmin.y <= bbmax.y && bbmin.z <= bbmax.z; }
FORCEINLINE Vec3 Center() const { return ( bbmin + bbmax ) * 0.5f; }
FORCEINLINE float Volume() const { return ( bbmax.x - bbmin.x ) * ( bbmax.y - bbmin.y ) * ( bbmax.z - bbmin.z ); }
};
struct Triangle
{
Vec3 P1, P2, P3;
bool CheckIsUseful() const
{
Vec3 e1 = P2 - P1, e2 = P3 - P1;
return !Vec3Cross( e1, e2 ).NearZero();
}
void GetAABB( AABB3& out ) const
{
out.bbmin = V3( TMIN( P1.x, TMIN( P2.x, P3.x ) ), TMIN( P1.y, TMIN( P2.y, P3.y ) ), TMIN( P1.z, TMIN( P2.z, P3.z ) ) );
out.bbmax = V3( TMAX( P1.x, TMAX( P2.x, P3.x ) ), TMAX( P1.y, TMAX( P2.y, P3.y ) ), TMAX( P1.z, TMAX( P2.z, P3.z ) ) );
}
Vec3 GetNormal() const
{
return Vec3Cross( P3 - P1, P2 - P1 ).Normalized();
}
};
typedef std::vector< Triangle > TriVector;
struct BSPNode
{
BSPNode() : front_node( NULL ), back_node( NULL ){}
~BSPNode()
{
if( front_node ) delete front_node;
if( back_node ) delete back_node;
}
void Split( int depth );
void AddTriangleSplit( Triangle* tri );
float IntersectRay( const Vec3& from, const Vec3& to, Vec3* outnormal );
bool PickSplitPlane();
void Dump( FILE* f, int lev = 0, const char* pfx = "" )
{
for( int i = 0; i < lev; ++i )
fputc( ' ', f );
fprintf( f, "%sNODE [%g;%g;%g](%g), tris=%d\n", pfx, N.x, N.y, N.z, D, (int) triangles.size() );
fprintf( f, "{\n" );
for( size_t i = 0; i < triangles.size(); ++i )
{
fprintf( f, " " ); triangles[i].P1.Dump( stdout );
fprintf( f, " " ); triangles[i].P2.Dump( stdout );
fprintf( f, " " ); triangles[i].P3.Dump( stdout );
}
if( front_node )
front_node->Dump( f, lev + 1, "F " );
if( back_node )
back_node->Dump( f, lev + 1, "B " );
}
Vec3 N;
float D;
BSPNode *front_node, *back_node;
TriVector triangles;
};
struct BSPTree
{
BSPTree() : root( new BSPNode() ){}
~BSPTree(){ delete root; }
FORCEINLINE void SetTriangles( Triangle* tris, size_t count )
{
root->triangles.resize( count );
TMEMCOPY( &root->triangles[0], tris, count );
root->Split( 0 );
}
FORCEINLINE float IntersectRay( const Vec3& from, const Vec3& to, Vec3* outnormal = NULL ){ return root->IntersectRay( from, to, outnormal ); }
BSPNode* root;
};
struct BaseRayQuery
{
Vec3 ray_origin;
float ray_len;
Vec3 _ray_inv_dir;
void SetRayDir( Vec3 dir )
{
dir = dir.Normalized();
_ray_inv_dir = V3
(
safe_fdiv( 1, dir.x ),
safe_fdiv( 1, dir.y ),
safe_fdiv( 1, dir.z )
);
}
void SetRay( const Vec3& r0, const Vec3& r1 )
{
ray_origin = r0;
ray_len = ( r1 - r0 ).Length();
SetRayDir( r1 - r0 );
}
};
bool RayAABBTest( const Vec3& ro, const Vec3& inv_n, float len, const Vec3& bbmin, const Vec3& bbmax );
struct AABBTree
{
struct Node // size = 8(3+3+2) * 4(float/int32)
{
Vec3 bbmin;
Vec3 bbmax;
int32_t ch; // ch0 = node + 1, ch1 = ch
int32_t ido; // item data offset
};
// AABBs must be stored manually if necessary
void SetAABBs( AABB3* aabbs, size_t count );
void _printdepth( int depth )
{
for( int i = 0; i < depth; ++i )
printf( " " );
}
void Dump( int32_t node = 0, int depth = 0 )
{
AABBTree::Node& N = m_nodes[ node ];
_printdepth(depth); printf( "node #%d (%d items, %.2f;%.2f;%.2f -> %.2f;%.2f;%.2f)",
int(node), N.ido != -1 ? int(m_itemidx[ N.ido ]) : 0,
N.bbmin.x, N.bbmin.y, N.bbmin.z, N.bbmax.x, N.bbmax.y, N.bbmax.z );
if( N.ch != -1 )
{
printf( " {\n" );
depth++;
Dump( node + 1, depth );
Dump( N.ch, depth );
depth--;
_printdepth(depth); printf( "}\n" );
}
else printf( "\n" );
}
template< class T > bool RayQuery( T& rq, int32_t node = 0 )
{
AABBTree::Node& N = m_nodes[ node ];
if( RayAABBTest( rq.ray_origin, rq._ray_inv_dir, rq.ray_len, N.bbmin, N.bbmax ) == false )
return true;
if( N.ido != -1 )
{
if( rq( &m_itemidx[ N.ido + 1 ], m_itemidx[ N.ido ] ) == false )
return false;
}
// child nodes
if( N.ch != -1 )
{
if( RayQuery( rq, node + 1 ) == false ) return false;
if( RayQuery( rq, N.ch ) == false ) return false;
}
return true;
}
template< class T > void DynBBQuery( T& bbq, int32_t node = 0 )
{
AABBTree::Node& N = m_nodes[ node ];
if( bbq.bbmin.x > N.bbmax.x || bbq.bbmax.x < N.bbmin.x ||
bbq.bbmin.y > N.bbmax.y || bbq.bbmax.y < N.bbmin.y ||
bbq.bbmin.z > N.bbmax.z || bbq.bbmax.z < N.bbmin.z )
return;
// items
if( N.ido != -1 )
{
bbq( &m_itemidx[ N.ido + 1 ], m_itemidx[ N.ido ] );
}
// child nodes
if( N.ch != -1 )
{
DynBBQuery( bbq, node + 1 );
DynBBQuery( bbq, N.ch );
}
}
template< class T > void Query( const Vec3& qmin, const Vec3& qmax, T& out, int32_t node = 0 )
{
AABBTree::Node& N = m_nodes[ node ];
if( qmin.x > N.bbmax.x || qmax.x < N.bbmin.x ||
qmin.y > N.bbmax.y || qmax.y < N.bbmin.y ||
qmin.z > N.bbmax.z || qmax.z < N.bbmin.z )
return;
// items
if( N.ido != -1 )
{
out( &m_itemidx[ N.ido + 1 ], m_itemidx[ N.ido ] );
}
// child nodes
if( N.ch != -1 )
{
Query( qmin, qmax, out, node + 1 );
Query( qmin, qmax, out, N.ch );
}
}
template< class T > void GetAll( T& out )
{
for( size_t i = 0; i < m_itemidx.size(); i += 1 + m_itemidx[ i ] )
{
out( &m_itemidx[ i + 1 ], m_itemidx[ i ] );
}
}
void _MakeNode( int32_t node, AABB3* aabbs, int32_t* sampidx_data, size_t sampidx_count, int depth );
// BVH
std::vector< Node > m_nodes;
std::vector< int32_t > m_itemidx; // format: <count> [ <item> x count ], ...
};
struct TriTree
{
void SetTris( Triangle* tris, size_t count );
bool IntersectRay( const Vec3& from, const Vec3& to );
float IntersectRayDist( const Vec3& from, const Vec3& to, int32_t* outtid );
float GetDistance( const Vec3& p, float dist );
void OffsetSample( Vec3& P, const Vec3& N, float dist );
AABBTree m_bbTree;
std::vector< Triangle > m_tris;
};
struct ltr_MeshPart
{
u32 m_vertexCount;
u32 m_vertexOffset;
u32 m_indexCount;
u32 m_indexOffset;
int m_shadow;
};
typedef std::vector< ltr_MeshPart > MeshPartVector;
struct ltr_Mesh
{
ltr_Mesh( ltr_Scene* s ) : m_scene( s ){}
ltr_Scene* m_scene;
std::string m_ident;
Vec3Vector m_vpos;
Vec3Vector m_vnrm;
Vec2Vector m_vtex1;
Vec2Vector m_vtex2;
U32Vector m_indices;
MeshPartVector m_parts;
};
typedef std::vector< ltr_Mesh* > MeshPtrVector;
struct ltr_LightContribSample
{
Vec3 normal;
int32_t sid;
};
typedef std::vector< ltr_LightContribSample > LightContribVector;
struct ltr_TmpContribSum
{
Vec3 normal;
float mindot;
int32_t count;
};
struct ltr_MeshInstance
{
// input
ltr_Mesh* mesh;
std::string m_ident;
float m_importance;
Mat4 matrix;
u32 lm_width;
u32 lm_height;
bool m_shadow;
bool m_samplecont;
// tmp
Vec3Vector m_vpos;
Vec3Vector m_vnrm;
Vec2Vector m_vtex;
Vec2Vector m_ltex;
// output
BSPTree m_bspTree;
TriTree m_triTree;
Vec3Vector m_samples_pos;
Vec3Vector m_samples_nrm;
U32Vector m_samples_loc;
Vec4Vector m_samples_radinfo;
Vec3Vector m_lightmap;
LightContribVector m_contrib;
};
typedef std::vector< ltr_MeshInstance* > MeshInstPtrVector;
struct ltr_Light
{
void QueryMeshInsts( AABBTree& tree, std::vector< int32_t >& out );
u32 type;
Vec3 position;
Vec3 direction;
Vec3 up_direction;
Vec3 color_rgb;
float range;
float power;
float light_radius;
int shadow_sample_count;
float spot_angle_out;
float spot_angle_in;
float spot_curve;
// positions for point/spot, directions for directional lights
std::vector< Vec3 > samples;
};
typedef std::vector< ltr_Light > LightVector;
FORCEINLINE float CalcBrightness( Vec3 color ){ return ( color.x + color.y + color.z ) * (1.0f/3.0f); }
typedef std::vector< ltr_SampleInfo > SampleVector;
struct ltr_RadSampleGeom
{
Vec3 pos;
Vec3 normal;
};
typedef std::vector< ltr_RadSampleGeom > RadSampleGeomVector;
struct ltr_RadSampleColors
{
Vec3 diffuseColor;
Vec3 totalLight;
Vec3 outputEnergy;
Vec3 inputEnergy;
float area;
};
typedef std::vector< ltr_RadSampleColors > RadSampleColorsVector;
struct ltr_RadLink
{
uint32_t other;
float factor;
};
typedef std::vector< ltr_RadLink > RadLinkVector;
struct dw_lmrender_data
{
std::vector<ltr_LightContribSample>* contribs;
ltr_MeshInstance* mi;
ltr_Light* light;
float angle_out_rad;
float angle_in_rad;
float angle_diff;
};
#define MAX_PENUMBRA_SIZE 2.0f
// #define MAX_PENUMBRA_STEP 0.1f
#define MAX_PENUMBRA_STEP 1.0f
#define SAMPLE_SHADOW_OFFSET 0.005f
struct ltr_Scene
{
ltr_Scene() : m_workStage( "not started" ), m_workCompletion(0), m_num_cpus( ltrnumcpus() )
{
ltr_GetConfig( &config, NULL );
m_sampleMI.m_samplecont = true;
m_sampleMI.mesh = NULL;
m_sampleMI.m_importance = 0;
m_sampleMI.lm_width = 0;
m_sampleMI.lm_height = 0;
m_meshInstances.push_back( &m_sampleMI );
}
~ltr_Scene()
{
for( size_t i = 1; i < m_meshInstances.size(); ++i )
delete m_meshInstances[i];
for( size_t i = 0; i < m_meshes.size(); ++i )
delete m_meshes[i];
for( size_t i = 0; i < m_workOutput.size(); ++i )
{
delete [] m_workOutput[i].lightmap_rgb;
if( m_workOutput[i].normals_xyzf )
delete [] m_workOutput[i].normals_xyzf;
}
}
void Job_PreXForm_Inner( ltr_MeshInstance* mi );
static void Job_PreXForm( LTRWorker::IO* io );
void Job_ColInfo_Inner( ltr_MeshInstance* mi );
static void Job_ColInfo( LTRWorker::IO* io );
void Job_Samples_Inner( ltr_Scene* S, ltr_MeshInstance* mi );
static void Job_Samples( LTRWorker::IO* io );
void Job_LMRender_Point_Inner( size_t i, dw_lmrender_data* data );
void Job_LMRender_Spot_Inner( size_t i, dw_lmrender_data* data );
void Job_LMRender_Direct_Inner( size_t i, dw_lmrender_data* data );
static void Job_LMRender_Point( LTRWorker::IO* io );
static void Job_LMRender_Spot( LTRWorker::IO* io );
static void Job_LMRender_Direct( LTRWorker::IO* io );
void Int_LMRender( ltr_Light& light, ltr_MeshInstance* mi );
void Int_RDGenLinks();
void Int_RDBounce();
void Job_AORender_Inner( ltr_MeshInstance* mi, size_t i );
static void Job_AORender( LTRWorker::IO* io );
void Int_Finalize();
static void Job_MainProc( LTRWorker::IO* io );
bool VisibilityTest( const Vec3& A, const Vec3& B );
float Distance( const Vec3& p );
float CalcInvShadowFactor( const Vec3& from, const Vec3& to, float k ); // k = penumbra factor
float DistanceTest( const Vec3& A, const Vec3& B, Vec3* outnormal = NULL );
float DistanceTestBBT( const Vec3& A, const Vec3& B );
ltr_Config config;
MeshPtrVector m_meshes;
MeshInstPtrVector m_meshInstances;
LightVector m_lights;
ltr_MeshInstance m_sampleMI;
SampleVector m_samples;
RadSampleGeomVector m_radSampleGeoms;
RadSampleColorsVector m_radSampleColors;
RadLinkVector m_radLinks;
U32Vector m_radLinkMap;
AABBTree m_instTree;
WorkOutputVector m_workOutput;
const char* m_workStage;
float m_workCompletion;
int m_num_cpus;
LTRWorker m_worker;
LTRWorker m_rootWorker;
};
| 28.42315
| 160
| 0.629047
|
snake5
|
e9fc439729c3b1ac4817d0477d1e5c14bafa54f7
| 761
|
cpp
|
C++
|
hackerrank/problemSolving/caesarCipher.cpp
|
ravikiranmara/ProgrammingChallenges
|
dcd0e0b3997f05115fc1fab414818b7d9add54c4
|
[
"MIT"
] | null | null | null |
hackerrank/problemSolving/caesarCipher.cpp
|
ravikiranmara/ProgrammingChallenges
|
dcd0e0b3997f05115fc1fab414818b7d9add54c4
|
[
"MIT"
] | null | null | null |
hackerrank/problemSolving/caesarCipher.cpp
|
ravikiranmara/ProgrammingChallenges
|
dcd0e0b3997f05115fc1fab414818b7d9add54c4
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
// Complete the caesarCipher function below.
string caesarCipher(string s, int k) {
for (int i=0; i<s.size(); i++) {
if (islower(s[i]))
s[i] = 'a' + (k+s[i]-'a')%26;
else if (isupper(s[i]))
s[i] = 'A' + (k+s[i]-'A')%26;
}
return s;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string s;
getline(cin, s);
int k;
cin >> k;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string result = caesarCipher(s, k);
fout << result << "\n";
fout.close();
return 0;
}
// https://www.hackerrank.com/challenges/caesar-cipher-1
| 17.697674
| 56
| 0.532194
|
ravikiranmara
|
e9fdb5b02e274f8866dd1289c472aa2e46358793
| 19,976
|
cpp
|
C++
|
src/input/InputManager.cpp
|
MicahMartin/asdf
|
d430777603a6906b7117e422885c949b539865cf
|
[
"MIT"
] | null | null | null |
src/input/InputManager.cpp
|
MicahMartin/asdf
|
d430777603a6906b7117e422885c949b539865cf
|
[
"MIT"
] | null | null | null |
src/input/InputManager.cpp
|
MicahMartin/asdf
|
d430777603a6906b7117e422885c949b539865cf
|
[
"MIT"
] | null | null | null |
#include "input/InputManager.h"
#include "input/VirtualController.h"
#include <iostream>
#include <fstream>
#include <sstream>
// input manager is gonna get all input events from SDL for all devices
// keep a map with input keycodes as the key and tuple of player number actual 'button code' as the value
// so lets say the map has {key: SDL_CODE, val: {playerNum:1, buttonVal: 0x1}} with the bits on the buttonVal byte corresponding to InputManager::Input
void InputManager::init() {
if( SDL_NumJoysticks() < 1 ) {
printf( "Warning: No joysticks connected!\n" );
}
else {
//Load joystick
p1SDLController = SDL_JoystickOpen( 0 );
p2SDLController = SDL_JoystickOpen( 1 );
if( p1SDLController == NULL ) {
printf( "Warning: Unable to open game controller 1! SDL Error: %s\n", SDL_GetError() );
} else {
printf("SDL Controller 1 initialized\n");
}
if( p2SDLController == NULL ) {
printf( "Warning: Unable to open game controller 2! SDL Error: %s\n", SDL_GetError() );
} else {
printf("SDL Controller 2 initialized\n");
}
}
initConfig("../data/buttonconf.json", &bConf, &configJson);
initConfig("../data/p1buttonconf.json", &p1bConf, &p1configJson);
initConfig("../data/p2buttonconf.json", &p2bConf, &p2configJson);
}
void InputManager::initConfig(const char* fileName, ConfT* config, nlohmann::json* confJson) {
// load the config(s)
std::ifstream configFile(fileName);
nlohmann::json newJson;
configFile >> newJson;
config->reserve(32);
config->clear();
for(auto& item : newJson.items()){
// TODO: Check for too much configItems
// the 'value' is gonna be the button value for corresponding device
// std::cout << item.attribute("value").as_int() << std::endl;
// the node text is gonna be the bit for said button
// std::cout << std::bitset<16>(item.text().as_int()) << std::endl;
ConfItem myItem;
myItem.user = item.value()["user"].get<uint8_t>();
myItem.inputBit = (Input)std::stoi(item.value()["input"].get<std::string>(), 0 ,16);
(*config)[std::stoi(item.key())] = myItem;
}
configFile.close();
*confJson = newJson;
}
void InputManager::update() {
SDL_Event event;
for (VirtualController* controller : controllers) {
if (controller->playbackMode) {
if (controllers[0]->copyModeSlot == 1) {
InputFrameT currentFrame = controllers[0]->inputHistoryCopy[controller->playbackCounter];
controller->inputHistory.push_front(currentFrame);
controller->currentState = controllers[0]->inputStateCopy[controller->playbackCounter];
controller->playbackCounter++;
} else {
InputFrameT currentFrame = controllers[0]->inputHistoryCopyTwo[controller->playbackCounter];
controller->inputHistory.push_front(currentFrame);
controller->currentState = controllers[0]->inputStateCopyTwo[controller->playbackCounter];
controller->playbackCounter++;
}
} else {
// controller->prevState = controller->currentState;
controller->update();
}
}
while(SDL_PollEvent(&event) != 0){
if (!keySelectionMode) {
// printf("got an event %d\n", event.type);
switch (event.type) {
case SDL_KEYDOWN: {
if(event.key.repeat == 0){
if(bConf.find(event.key.keysym.sym) != bConf.end()){
ConfItem* item = &bConf.at(event.key.keysym.sym);
VirtualController* controller = controllers.at(item->user - 1);
Input* inputBit = &item->inputBit;
if (!controller->playbackMode) {
// is cardinal?
if (*inputBit <= 8) {
// printf("isCardinal!\n");
bool isXAxis = *inputBit <= 2;
if (isXAxis) {
*inputBit == RIGHT ? controller->xAxis++ : controller->xAxis--;
} else {
*inputBit == UP ? controller->yAxis++ : controller->yAxis--;
}
// this calls setBit
controller->updateAxis(isXAxis);
} else {
controller->setBit(*inputBit);
}
}
} else {
// item not found
}
}
break;
}
case SDL_KEYUP: {
if (event.key.keysym.sym == SDLK_5) {
controllers[0]->copyModeSlot = 1;
controllers[0]->copyMode ? controllers[0]->stopCopyMode() : controllers[0]->startCopyMode();
printf("copyMode toggled to %d, copySize:%ld\n", controllers[0]->copyMode, controllers[0]->inputHistoryCopy.size());
};
if (event.key.keysym.sym == SDLK_6) {
controllers[0]->copyModeSlot = 2;
controllers[0]->copyMode ? controllers[0]->stopCopyMode() : controllers[0]->startCopyMode();
printf("copyMode slot 2 toggled to %d, copySize:%ld\n", controllers[0]->copyMode, controllers[0]->inputHistoryCopyTwo.size());
};
if (event.key.keysym.sym == SDLK_e) {
notifyOne("game", "ADVANCE_STATE");
};
if (event.key.keysym.sym == SDLK_t) {
notifyOne("game", "RESUME_REQUEST");
};
if (event.key.keysym.sym == SDLK_r) {
notifyOne("game", "LOAD_STATE");
}
if (event.key.keysym.sym == SDLK_1) {
if (controllers[0]->copyMode) {
controllers[0]->stopCopyMode();
}
printf("setting input history to the copy %ld\n", controllers[0]->inputHistoryCopy.size());
controllers[0]->copyModeSlot = 1;
controllers[1]->playbackMode = true;
};
// if (event.key.keysym.sym == SDLK_2) {
// if (controllers[0]->copyMode) {
// controllers[0]->stopCopyMode();
// }
// printf("setting input history to the copy %ld\n", controllers[0]->inputHistoryCopy.size());
// controllers[0]->copyModeSlot = 2;
// controllers[1]->playbackMode = true;
// };
// if (event.key.keysym.sym == SDLK_3) {
// if (controllers[0]->copyMode) {
// controllers[0]->stopCopyMode();
// }
// srand (time(NULL));
// controllers[0]->copyModeSlot = rand() % 2 + 1;
// printf("setting input history to randomly 1 or 2 %d\n", controllers[0]->copyModeSlot);
// controllers[1]->playbackMode = true;
// };
if (bConf.find(event.key.keysym.sym) != bConf.end()) {
ConfItem* item = &bConf.at(event.key.keysym.sym);
VirtualController* controller = controllers.at(item->user - 1);
if (!controller->playbackMode) {
Input* inputBit = &item->inputBit;
// is cardinal?
if (*inputBit <= 8) {
// printf("isCardinal! clearing\n");
bool isXAxis = *inputBit <= 2;
if (isXAxis) {
*inputBit == RIGHT ? controller->xAxis-- : controller->xAxis++;
} else {
*inputBit == UP ? controller->yAxis-- : controller->yAxis++;
}
// this calls clearBit
controller->updateAxis(isXAxis);
} else {
controller->clearBit(*inputBit);
}
}
}
if (event.key.keysym.sym == SDLK_ESCAPE) {
notifyOne("game", "RESTART_REQUEST");
}
if (event.key.keysym.sym == SDLK_v) {
notifyOne("game", "VOLUME_DOWN_REQUEST");
}
if (event.key.keysym.sym == SDLK_b) {
notifyOne("game", "VOLUME_UP_REQUEST");
}
if (event.key.keysym.sym == SDLK_c) {
notifyOne("game", "VIEW_CBOXES_TOGGLE");
}
if (event.key.keysym.sym == SDLK_q) {
notifyOne("game", "PAUSE_REQUEST");
}
if (event.key.keysym.sym == SDLK_w) {
notifyOne("game", "SAVE_STATE");
}
break;
}
case SDL_JOYBUTTONDOWN: {
SDL_JoyHatEvent* jhatEvent = &event.jhat;
printf("joy button down %d\n", &event.jbutton.button);
SDL_Joystick* stick = SDL_JoystickFromInstanceID(jhatEvent->which);
VirtualController* controller = stickToVC[stick];
if (!controller->playbackMode) {
ConfT* conf;
if(controller->controllerIndex == 1){
conf = &p1bConf;
} else if(controller->controllerIndex == 2){
conf = &p2bConf;
}
if(conf != NULL && conf->count(event.jbutton.button)){
ConfItem* item = &conf->at(event.jbutton.button);
Input* inputBit = &item->inputBit;
printf("found item from jbutton %d with val: %d\n", event.jbutton.button, *inputBit);
controller->setBit(*inputBit);
} else if (conf != NULL && (event.jbutton.button >= 11 && event.jbutton.button <= 14)){
// UDLR
int inputBit = event.jbutton.button - 10;
printf("isCardinal! the inputBit:%d\n", inputBit);
// printf("isCardinal!\n");
bool isXAxis = inputBit >= 3;
if (isXAxis) {
inputBit == CONTROLLER_RIGHT ? controller->xAxis++ : controller->xAxis--;
} else {
inputBit == CONTROLLER_UP ? controller->yAxis++ : controller->yAxis--;
}
// this calls setBit
controller->updateAxis(isXAxis);
}
}
break;
}
case SDL_JOYBUTTONUP: {
SDL_JoyHatEvent* jhatEvent = &event.jhat;
SDL_Joystick* stick = SDL_JoystickFromInstanceID(jhatEvent->which);
VirtualController* controller = stickToVC[stick];
if (!controller->playbackMode) {
ConfT* conf;
if(controller->controllerIndex == 1){
conf = &p1bConf;
} else if(controller->controllerIndex == 2){
conf = &p2bConf;
}
if(conf != NULL && conf->count(event.jbutton.button)){
ConfItem* item = &conf->at(event.jbutton.button);
Input* inputBit = &item->inputBit;
// printf("clearing item from jbutton %d with val: %d\n", event.jbutton.button, *inputBit);
controller->clearBit(*inputBit);
} else if (conf != NULL && (event.jbutton.button >= 11 && event.jbutton.button <= 14)){
// UDLR
int inputBit = event.jbutton.button - 10;
bool isXAxis = inputBit >= 3;
if (isXAxis) {
inputBit == CONTROLLER_RIGHT ? controller->xAxis-- : controller->xAxis++;
} else {
inputBit == CONTROLLER_UP ? controller->yAxis-- : controller->yAxis++;
}
// this calls setBit
controller->updateAxis(isXAxis);
}
}
break;
}
case SDL_JOYHATMOTION: {
printf("hat motion\n");
SDL_JoyHatEvent* jhatEvent = &event.jhat;
SDL_Joystick* stick = SDL_JoystickFromInstanceID(jhatEvent->which);
VirtualController* controller = stickToVC[stick];
if (controller != NULL && !controller->playbackMode) {
switch (jhatEvent->value) {
case SDL_HAT_CENTERED:
controller->setAxis(NOINPUT);
printf("setting axis to noinput\n");
break;
case SDL_HAT_RIGHT:
controller->setAxis(RIGHT);
printf("setting axis to right\n");
break;
case SDL_HAT_LEFT:
controller->setAxis(LEFT);
printf("setting axis to left\n");
break;
case SDL_HAT_UP:
controller->setAxis(UP);
printf("setting axis to up\n");
break;
case SDL_HAT_DOWN:
controller->setAxis(DOWN);
printf("setting axis to down\n");
break;
case SDL_HAT_RIGHTDOWN:
controller->setAxis(DOWNRIGHT);
printf("setting axis to downright\n");
break;
case SDL_HAT_RIGHTUP:
controller->setAxis(UPRIGHT);
printf("setting axis to rightup\n");
break;
case SDL_HAT_LEFTDOWN:
controller->setAxis(DOWNLEFT);
printf("setting axis to leftdown\n");
break;
case SDL_HAT_LEFTUP:
controller->setAxis(UPLEFT);
printf("setting axis to leftup\n");
break;
default:
break;
}
}
break;
}
case SDL_JOYAXISMOTION: {
if (event.jaxis.value < 8000 || event.jaxis.value > 8000) {
switch (event.jaxis.axis) {
case 4:
if (event.jaxis.value > 10000 && !leftTrigger) {
printf("left trigger pressed\n");
leftTrigger = true;
} else if (event.jaxis.value < 10000 && leftTrigger) {
printf("left trigger released\n");
leftTrigger = false;
}
break;
case 5:
if (event.jaxis.value < 8000 && !rightTrigger) {
printf("right trigger pressed\n");
rightTrigger = true;
} else if (event.jaxis.value > 8000 && rightTrigger) {
printf("right trigger released\n");
rightTrigger = false;
}
break;
default:
break;
}
}
break;
}
case SDL_JOYBALLMOTION: {
printf("joy ball motion\n");
break;
}
case SDL_QUIT:
notifyOne("game", "QUIT_REQUEST");
break;
default:
break;
}
} else {
switch (event.type) {
case SDL_KEYDOWN: {
if(event.key.repeat == 0){
printf("configuring item:%d, the sdl keycode for the thing just released : %d\n", configCounter, event.key.keysym.sym);
if (bConf.find(event.key.keysym.sym) != bConf.end()) {
configCounter++;
ConfItem* item = &bConf.at(event.key.keysym.sym);
Input* inputBit = &item->inputBit;
if (*inputBit == MK) {
keySelectionMode = false;
configCounter = 0;
}
}
break;
}
case SDL_KEYUP: {
}
break;
}
case SDL_JOYBUTTONDOWN: {
printf("configuring item:%d, the button keycode for the thing just released : %d\n", configCounter, event.jbutton.button);
buttonConfigArray[configCounter] = event.jbutton.button;
configCounter++;
if (configCounter == 4) {
configCounter = 0;
printf("writing button config\n");
keySelectionMode = false;
writeButtonConfig();
}
break;
}
case SDL_JOYBUTTONUP: {
break;
}
case SDL_JOYAXISMOTION: {
printf("joy axis motion\n");
break;
}
case SDL_JOYBALLMOTION: {
printf("joy ball motion\n");
break;
}
case SDL_JOYHATMOTION: {
break;
}
case SDL_QUIT:
keySelectionMode = false;
break;
default:
break;
}
}
}
if(controllers[0]->copyMode){
// printf("pushing input history to inputHistoryCopy\n");
if (controllers[0]->copyModeSlot == 1) {
controllers[0]->inputHistoryCopy.push_back(controllers[0]->inputHistory.front());
controllers[0]->inputStateCopy.push_back(controllers[0]->currentState);
} else if(controllers[0]->copyModeSlot == 2){
controllers[0]->inputHistoryCopyTwo.push_back(controllers[0]->inputHistory.front());
controllers[0]->inputStateCopyTwo.push_back(controllers[0]->currentState);
}
}
if (controllers[1]->playbackMode) {
int correctSize = controllers[0]->copyModeSlot == 1 ? controllers[0]->inputHistoryCopy.size() : controllers[0]->inputHistoryCopyTwo.size();
if (controllers[1]->playbackCounter == correctSize) {
controllers[1]->playbackCounter = 0;
controllers[1]->playbackMode = false;
printf("stopping playback mode from slot %d\n", controllers[0]->copyModeSlot);
}
}
}
void InputManager::writeConfig(){
int itemCounter = 0;
std::vector<std::string> removalKeys;
for (auto i : configJson.items()) {
int user = i.value().at("user");
std::string str = i.key();
const char* ptr = str.c_str();
printf("the key:%s the user for this item: %d\n", ptr, user);
if(user == userBeingConfig){
removalKeys.push_back(i.key());
}
}
for (auto i : removalKeys) {
configJson.erase(i);
printf("removalKey:%s \n", i.c_str());
}
for(auto input : inputTemplate){
nlohmann::json obj = nlohmann::json::object();
obj["user"] = userBeingConfig;
std::stringstream stream;
stream << std::hex << input;
std::string result( stream.str() );
obj["input"] = "0x" + result;
printf("the input:%x\n", input);
configJson[std::to_string(configArray[itemCounter])] = obj;
itemCounter++;
if(itemCounter == 8){
break;
}
}
std::ofstream newConfigFile("../data/buttonconf.json");
configJson >> newConfigFile;
newConfigFile.close();
init();
}
void InputManager::writeButtonConfig(){
int itemCounter = 0;
nlohmann::json* currentConfig = userBeingConfig == 1 ? &p1configJson : &p2configJson;
std::vector<std::string> removalKeys;
for (auto i : currentConfig->items()) {
std::string str = i.key();
const char* ptr = str.c_str();
printf("the key:%s the user for this item: %d\n", ptr, userBeingConfig);
removalKeys.push_back(i.key());
}
for (auto i : removalKeys) {
currentConfig->erase(i);
printf("removalKey:%s \n", i.c_str());
}
for(auto input : buttonTemplate){
nlohmann::json obj = nlohmann::json::object();
obj["user"] = userBeingConfig;
std::stringstream stream;
stream << std::hex << input;
std::string result( stream.str() );
obj["input"] = "0x" + result;
printf("the input:%x\n", input);
(*currentConfig)[std::to_string(buttonConfigArray[itemCounter])] = obj;
itemCounter++;
if(itemCounter == 4){
printf("breaking button conf\n");
break;
}
}
const char* confPath = userBeingConfig == 1 ? "../data/p1buttonconf.json" : "../data/p2buttonconf.json";
std::ofstream newConfigFile(confPath);
(*currentConfig) >> newConfigFile;
newConfigFile.close();
init();
}
// Subject
void InputManager::addObserver(const char* observerName, Observer* observer){
printf("Observer added to inputManager \n");
observerList.insert(std::make_pair(observerName, observer));
};
void InputManager::removeObserver(const char* observerName){
observerList.erase(observerName);
};
void InputManager::notifyAll(const char* eventName){
for( const auto& [key, observer] : observerList ){
observer->onNotify(eventName);
}
};
void InputManager::addVirtualController(VirtualController* controller){
controllers.push_back(controller);
}
VirtualController* InputManager::getVirtualController(int index){
return controllers.at(index);
}
void InputManager::notifyOne(const char* observerName, const char* eventName){
Observer* observer = observerList.at(observerName);
observer->onNotify(eventName);
}
| 36.720588
| 151
| 0.550511
|
MicahMartin
|
e9ffd7f0dd51dd1290181cd72dcd37c847186388
| 4,617
|
cpp
|
C++
|
apps/visualizer.cpp
|
aquibrash87/RecoridingTool
|
1af39f7e6eb5bea2c649157003d7848b1f9cf4d8
|
[
"Apache-2.0"
] | null | null | null |
apps/visualizer.cpp
|
aquibrash87/RecoridingTool
|
1af39f7e6eb5bea2c649157003d7848b1f9cf4d8
|
[
"Apache-2.0"
] | null | null | null |
apps/visualizer.cpp
|
aquibrash87/RecoridingTool
|
1af39f7e6eb5bea2c649157003d7848b1f9cf4d8
|
[
"Apache-2.0"
] | null | null | null |
/****************************************************************
** **
** Copyright(C) 2016 Quanergy Systems. All Rights Reserved. **
** Contact: http://www.quanergy.com **
** **
****************************************************************/
// visualization module
#include "visualizer_module.h"
#include "filesave_module.h"
// console parser
#include <pcl/console/parse.h>
#include <quanergy/client/sensor_client.h>
// parsers for the data packets we want to support
#include <quanergy/parsers/data_packet_parser_00.h>
#include <quanergy/parsers/data_packet_parser_01.h>
#include <quanergy/parsers/data_packet_parser_04.h>
#include <quanergy/parsers/variadic_packet_parser.h>
// module to apply encoder correction
#include <quanergy/modules/encoder_angle_calibration.h>
// conversion module from polar to Cartesian
#include <quanergy/modules/polar_to_cart_converter.h>
namespace
{
static const std::string MANUAL_CORRECT{"--manual-correct"};
static const std::string CALIBRATE_STR{"--calibrate"};
static const std::string AMPLITUDE_STR{"--amplitude"};
static const std::string PHASE_STR{"--phase"};
}
void usage(char** argv)
{
std::cout << "usage: " << argv[0]
<< " --host <host> [-h | --help] [" << CALIBRATE_STR << "][" << MANUAL_CORRECT << " " << AMPLITUDE_STR << " <value> " << PHASE_STR << " <value>]" << std::endl << std::endl
<< " --host hostname or IP address of the sensor" << std::endl
<< "-h, --help show this help and exit" << std::endl;
return;
}
typedef quanergy::client::SensorClient ClientType;
typedef quanergy::client::VariadicPacketParser<quanergy::PointCloudHVDIRPtr, // return type
quanergy::client::DataPacketParser00, // PARSER_00_INDEX
quanergy::client::DataPacketParser01, // PARSER_00_INDEX
quanergy::client::DataPacketParser04> ParserType; // PARSER_04_INDEX
enum
{
PARSER_00_INDEX = 0,
PARSER_01_INDEX = 1,
PARSER_04_INDEX = 2
};
typedef quanergy::client::PacketParserModule<ParserType> ParserModuleType;
typedef quanergy::calibration::EncoderAngleCalibration CalibrationType;
typedef quanergy::client::PolarToCartConverter ConverterType;
int main(int argc, char** argv)
{
int max_num_args = 8;
// get host
if (argc < 2 || argc > max_num_args || pcl::console::find_switch(argc, argv, "-h") ||
pcl::console::find_switch(argc, argv, "--help") || !pcl::console::find_switch(argc, argv, "--host"))
{
usage (argv);
return (0);
}
std::string host;
std::string port = "4141";
pcl::console::parse_argument(argc, argv, "--host", host);
// create modules
ClientType client(host, port, 100);
ParserModuleType parser;
ConverterType converter;
VisualizerModule visualizer;
FilesaveModule filesaver(FilesaveModule::DataType::Binary, "pcldata", FilesaveModule::TimestampType::System); //Binary oder Text
CalibrationType calibrator;
// setup modules
parser.get<PARSER_00_INDEX>().setFrameId("quanergy");
parser.get<PARSER_00_INDEX>().setReturnSelection(0);
parser.get<PARSER_00_INDEX>().setDegreesOfSweepPerCloud(360.0);
parser.get<PARSER_01_INDEX>().setFrameId("quanergy");
parser.get<PARSER_04_INDEX>().setFrameId("quanergy");
// connect modules
std::vector<boost::signals2::connection> connections;
connections.push_back(client.connect([&parser](const ClientType::ResultType& pc){ parser.slot(pc); }));
connections.push_back(parser.connect([&converter](const ParserModuleType::ResultType& pc){ converter.slot(pc); }));
connections.push_back(converter.connect([&visualizer](const ConverterType::ResultType& pc){ visualizer.slot(pc); }));
connections.push_back(converter.connect([&filesaver](const ConverterType::ResultType& pc){ filesaver.slot(pc);}));
// run the client with the calibrator and wait for a signal from the
// calibrator that a successful calibration has been performed
std::thread client_thread([&client, &visualizer]
{
try
{
client.run();
}
catch (std::exception& e)
{
std::cerr << "Terminating after catching exception: " << e.what() << std::endl;
visualizer.stop();
}
});
// start visualizer (blocks until stopped)
visualizer.run();
// clean up
client.stop();
connections.clear();
client_thread.join();
return (0);
}
| 35.790698
| 177
| 0.635911
|
aquibrash87
|
1802e73bc9e102d64403cb942ccd1d9490c89b66
| 1,548
|
cpp
|
C++
|
io2d/src/device.cpp
|
cristianadam/N3888_RefImpl
|
d7975633ad0e66e32c2dea70b0952d48ed777e9b
|
[
"MIT"
] | 52
|
2016-02-28T23:00:45.000Z
|
2021-11-28T06:13:02.000Z
|
io2d/src/device.cpp
|
cristianadam/N3888_RefImpl
|
d7975633ad0e66e32c2dea70b0952d48ed777e9b
|
[
"MIT"
] | null | null | null |
io2d/src/device.cpp
|
cristianadam/N3888_RefImpl
|
d7975633ad0e66e32c2dea70b0952d48ed777e9b
|
[
"MIT"
] | 6
|
2018-01-08T08:21:11.000Z
|
2022-03-11T03:18:54.000Z
|
#include "io2d.h"
#include "xio2dhelpers.h"
#include "xcairoenumhelpers.h"
using namespace std;
using namespace std::experimental::io2d;
device::native_handle_type device::native_handle() const noexcept {
return _Device.get();
}
device::device(device::native_handle_type nh) : _Device() {
_Device = shared_ptr<cairo_device_t>(nh, &cairo_device_destroy);
_Throw_if_failed_cairo_status_t(cairo_device_status(_Device.get()));
}
device::device(device::native_handle_type nh, error_code& ec) noexcept : _Device() {
_Device = shared_ptr<cairo_device_t>(nh, &cairo_device_destroy);
if (cairo_device_status(_Device.get()) != CAIRO_STATUS_SUCCESS) {
ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_DEVICE_ERROR);
}
else {
ec.clear();
}
}
device::device(device&& other) noexcept {
_Device = move(other._Device);
other._Device = nullptr;
}
device& device::operator=(device&& other) noexcept {
if (this != &other) {
_Device = move(other._Device);
other._Device = nullptr;
}
return *this;
}
void device::flush() noexcept {
cairo_device_flush(_Device.get());
}
void device::lock() {
_Throw_if_failed_cairo_status_t(cairo_device_acquire(_Device.get()));
}
void device::lock(error_code& ec) noexcept {
if (cairo_device_acquire(_Device.get()) != CAIRO_STATUS_SUCCESS) {
ec = make_error_code(errc::resource_unavailable_try_again);
}
else {
ec.clear();
}
}
void device::unlock() {
cairo_device_release(_Device.get());
}
void device::unlock(error_code& ec) noexcept {
cairo_device_release(_Device.get());
ec.clear();
}
| 23.815385
| 84
| 0.739664
|
cristianadam
|
18070b669def585ee9fa55b3d2a3fc5333c9f3ef
| 1,158
|
cpp
|
C++
|
Bridge/Cpp/main.cpp
|
john29917958/Design-Patterns
|
86b0139d67769552a9b97d1d436b9915a513871c
|
[
"MIT"
] | null | null | null |
Bridge/Cpp/main.cpp
|
john29917958/Design-Patterns
|
86b0139d67769552a9b97d1d436b9915a513871c
|
[
"MIT"
] | null | null | null |
Bridge/Cpp/main.cpp
|
john29917958/Design-Patterns
|
86b0139d67769552a9b97d1d436b9915a513871c
|
[
"MIT"
] | null | null | null |
#include "character.h"
int main()
{
std::unique_ptr<character> character = std::make_unique<human>(0, "Jack", 100, 100);
character->cast_spell();
character->set_spell(std::make_shared<fire_spell>(30, 100, 20));
character->cast_spell();
character->set_spell(std::make_shared<ice_spell>(30, 50, 20));
character->cast_spell();
character->set_spell(std::make_shared<curse_spell>(40, 60, 20));
character->cast_spell();
character = std::make_unique<orc>(1, "Gary", 100, 100);
character->cast_spell();
character->set_spell(std::make_shared<fire_spell>(30, 100, 20));
character->cast_spell();
character->set_spell(std::make_shared<ice_spell>(30, 50, 20));
character->cast_spell();
character->set_spell(std::make_shared<curse_spell>(40, 60, 20));
character->cast_spell();
character = std::make_unique<vampire>(3, "Prince", 100, 100);
character->cast_spell();
character->set_spell(std::make_shared<fire_spell>(30, 100, 20));
character->cast_spell();
character->set_spell(std::make_shared<ice_spell>(30, 50, 20));
character->cast_spell();
character->set_spell(std::make_shared<curse_spell>(40, 60, 20));
character->cast_spell();
return 0;
}
| 35.090909
| 85
| 0.721071
|
john29917958
|
1807818d667d2cbb291b49973ad6412d87550fc6
| 490
|
cpp
|
C++
|
Sphere_Online_Judge_soj/Classical/math_is_love.cpp
|
mushahadur/Competitive-Programming-Problem-Solving-Online-Judge
|
66b49ee2564b85d7b42d91a977f3d57d437e43d5
|
[
"Apache-2.0"
] | 1
|
2021-08-25T06:49:16.000Z
|
2021-08-25T06:49:16.000Z
|
Sphere_Online_Judge_soj/Classical/math_is_love.cpp
|
mushahadur/Competitive-Programming-Problem-Solving-Online-Judge
|
66b49ee2564b85d7b42d91a977f3d57d437e43d5
|
[
"Apache-2.0"
] | null | null | null |
Sphere_Online_Judge_soj/Classical/math_is_love.cpp
|
mushahadur/Competitive-Programming-Problem-Solving-Online-Judge
|
66b49ee2564b85d7b42d91a977f3d57d437e43d5
|
[
"Apache-2.0"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
long long int y,sum=0,i,arr[100],arry[1000];
for(i=0; i<10; i++)
{
sum=sum+i;
arr[i]=sum;
arry[sum]=i;
}
cout<<"check : "<<arr[6]<<endl;
cout<<"check 2 : "<<arry[21]<<endl;
cin>>t;
while(t--)
{
cin>>y;
if(arry[y]!=0){
cout<<arry[y]<<endl;
}
else
{
cout<<"NUL"<<endl;
}
}
return 0;
}
| 16.333333
| 48
| 0.408163
|
mushahadur
|
18079d3658ce78314386c430ddb2cf88e2c3866b
| 1,234
|
inl
|
C++
|
LibImagics/Images/Wm5Lattice.inl
|
CRIMSONCardiovascularModelling/WildMagic5
|
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
|
[
"BSL-1.0"
] | 1
|
2021-02-18T10:25:42.000Z
|
2021-02-18T10:25:42.000Z
|
LibImagics/Images/Wm5Lattice.inl
|
CRIMSONCardiovascularModelling/WildMagic5
|
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
|
[
"BSL-1.0"
] | null | null | null |
LibImagics/Images/Wm5Lattice.inl
|
CRIMSONCardiovascularModelling/WildMagic5
|
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
|
[
"BSL-1.0"
] | null | null | null |
// Geometric Tools, LLC
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
//----------------------------------------------------------------------------
inline int Lattice::GetDimensions () const
{
return mNumDimensions;
}
//----------------------------------------------------------------------------
inline const int* Lattice::GetBounds () const
{
return mBounds;
}
//----------------------------------------------------------------------------
inline int Lattice::GetBound (int i) const
{
return mBounds[i];
}
//----------------------------------------------------------------------------
inline int Lattice::GetQuantity () const
{
return mQuantity;
}
//----------------------------------------------------------------------------
inline const int* Lattice::GetOffsets () const
{
return mOffsets;
}
//----------------------------------------------------------------------------
inline int Lattice::GetOffset (int i) const
{
return mOffsets[i];
}
//----------------------------------------------------------------------------
| 30.85
| 78
| 0.388169
|
CRIMSONCardiovascularModelling
|
18121f2661b46c9ef94060e23bf73aa36410076e
| 14,098
|
cpp
|
C++
|
src/terminal_renderer/DecorationRenderer.cpp
|
christianparpart/libterminal
|
0e6d75a2042437084c9f9880a5c8b5661a02da07
|
[
"Apache-2.0"
] | 4
|
2019-08-14T22:29:57.000Z
|
2019-09-19T08:57:15.000Z
|
src/terminal_renderer/DecorationRenderer.cpp
|
christianparpart/libterminal
|
0e6d75a2042437084c9f9880a5c8b5661a02da07
|
[
"Apache-2.0"
] | 69
|
2019-08-17T18:57:16.000Z
|
2019-09-22T23:25:49.000Z
|
src/terminal_renderer/DecorationRenderer.cpp
|
christianparpart/libterminal
|
0e6d75a2042437084c9f9880a5c8b5661a02da07
|
[
"Apache-2.0"
] | null | null | null |
/**
* This file is part of the "contour" project.
* Copyright (c) 2020 Christian Parpart <christian@parpart.family>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 <terminal_renderer/DecorationRenderer.h>
#include <terminal_renderer/GridMetrics.h>
#include <terminal_renderer/Pixmap.h>
#include <terminal_renderer/shared_defines.h>
#include <crispy/times.h>
#include <crispy/utils.h>
#include <array>
#include <cmath>
#include <iostream>
#include <optional>
#include <utility>
using crispy::each_element;
using crispy::Size;
using std::array;
using std::ceil;
using std::clamp;
using std::floor;
using std::get;
using std::max;
using std::min;
using std::move;
using std::nullopt;
using std::optional;
using std::pair;
using std::string;
namespace terminal::renderer
{
namespace
{
auto constexpr CellFlagDecorationMappings = array {
pair { CellFlags::Underline, Decorator::Underline },
pair { CellFlags::DoublyUnderlined, Decorator::DoubleUnderline },
pair { CellFlags::CurlyUnderlined, Decorator::CurlyUnderline },
pair { CellFlags::DottedUnderline, Decorator::DottedUnderline },
pair { CellFlags::DashedUnderline, Decorator::DashedUnderline },
pair { CellFlags::Overline, Decorator::Overline },
pair { CellFlags::CrossedOut, Decorator::CrossedOut },
pair { CellFlags::Framed, Decorator::Framed },
pair { CellFlags::Encircled, Decorator::Encircle },
};
}
DecorationRenderer::DecorationRenderer(GridMetrics const& _gridMetrics,
Decorator _hyperlinkNormal,
Decorator _hyperlinkHover):
Renderable { _gridMetrics }, hyperlinkNormal_ { _hyperlinkNormal }, hyperlinkHover_ { _hyperlinkHover }
{
}
constexpr inline uint32_t DirectMappedDecorationCount = std::numeric_limits<Decorator>::count();
void DecorationRenderer::setRenderTarget(RenderTarget& renderTarget,
DirectMappingAllocator& directMappingAllocator)
{
Renderable::setRenderTarget(renderTarget, directMappingAllocator);
_directMapping = directMappingAllocator.allocate(DirectMappedDecorationCount);
clearCache();
}
void DecorationRenderer::setTextureAtlas(TextureAtlas& atlas)
{
Renderable::setTextureAtlas(atlas);
initializeDirectMapping();
}
void DecorationRenderer::clearCache()
{
}
void DecorationRenderer::initializeDirectMapping()
{
Require(_textureAtlas);
for (Decorator const decoration: each_element<Decorator>())
{
auto const tileIndex = _directMapping.toTileIndex(static_cast<uint32_t>(decoration));
auto const tileLocation = _textureAtlas->tileLocation(tileIndex);
TextureAtlas::TileCreateData tileData = createTileData(decoration, tileLocation);
_textureAtlas->setDirectMapping(tileIndex, move(tileData));
}
}
void DecorationRenderer::inspect(std::ostream& /*output*/) const
{
}
void DecorationRenderer::renderLine(RenderLine const& line)
{
for (auto const& mapping: CellFlagDecorationMappings)
if (line.textAttributes.flags & mapping.first)
renderDecoration(mapping.second,
_gridMetrics.map(CellLocation { line.lineOffset }),
line.usedColumns,
line.textAttributes.decorationColor);
}
void DecorationRenderer::renderCell(RenderCell const& _cell)
{
for (auto const& mapping: CellFlagDecorationMappings)
if (_cell.attributes.flags & mapping.first)
renderDecoration(mapping.second,
_gridMetrics.map(_cell.position),
ColumnCount(1),
_cell.attributes.decorationColor);
}
auto DecorationRenderer::createTileData(Decorator decoration, atlas::TileLocation tileLocation)
-> TextureAtlas::TileCreateData
{
auto const width = _gridMetrics.cellSize.width;
auto tileData = TextureAtlas::TileCreateData {};
// NB: To be filled below: bitmapSize, bitmap.
tileData.bitmapFormat = atlas::Format::Red;
tileData.metadata.x = {};
tileData.metadata.y = {};
auto const create = [this, tileLocation](ImageSize bitmapSize,
auto createBitmap) -> TextureAtlas::TileCreateData {
return createTileData(tileLocation,
createBitmap(),
atlas::Format::Red,
bitmapSize,
RenderTileAttributes::X { 0 },
RenderTileAttributes::Y { 0 },
FRAGMENT_SELECTOR_GLYPH_ALPHA);
};
switch (decoration)
{
case Decorator::Encircle:
// TODO (default to Underline for now)
[[fallthrough]];
case Decorator::Underline: {
auto const thickness_half = max(1u, unsigned(ceil(underlineThickness() / 2.0)));
auto const thickness = thickness_half * 2;
auto const y0 = max(0u, unsigned(underlinePosition()) - thickness_half);
auto const height = Height(y0 + thickness);
auto const imageSize = ImageSize { width, height };
return create(imageSize, [&]() -> atlas::Buffer {
auto image = atlas::Buffer(imageSize.area(), 0);
for (unsigned y = 1; y <= thickness; ++y)
for (unsigned x = 0; x < unbox<unsigned>(width); ++x)
image[(*height - y0 - y) * *width + x] = 0xFF;
return image;
});
}
case Decorator::DoubleUnderline: {
auto const thickness = max(1u, unsigned(ceil(double(underlineThickness()) * 2.0) / 3.0));
auto const y1 = max(0u, unsigned(underlinePosition()) + thickness);
auto const y0 = max(0u, y1 - 3 * thickness);
auto const height = Height(y1 + thickness);
auto const imageSize = ImageSize { width, height };
return create(imageSize, [&]() -> atlas::Buffer {
auto image = atlas::Buffer(imageSize.area(), 0);
for (unsigned y = 1; y <= thickness; ++y)
{
for (unsigned x = 0; x < unbox<unsigned>(width); ++x)
{
image[(*height - y1 - y) * *width + x] = 0xFF; // top line
image[(*height - y0 - y) * *width + x] = 0xFF; // bottom line
}
}
return image;
});
}
case Decorator::CurlyUnderline: {
auto const height = Height::cast_from(_gridMetrics.baseline);
auto const h2 = max(unbox<int>(height) / 2, 1);
auto const yScalar = h2 - 1;
auto const xScalar = 2 * M_PI / *width;
auto const yBase = h2;
auto const imageSize = ImageSize { width, height };
auto block = blockElement(imageSize);
return create(block.downsampledSize(), [&]() -> atlas::Buffer {
auto const thickness_half = max(1, int(ceil(underlineThickness() / 2.0)));
for (int x = 0; x < unbox<int>(width); ++x)
{
// Using Wu's antialiasing algorithm to paint the curved line.
// See: https://www-users.mat.umk.pl//~gruby/teaching/lgim/1_wu.pdf
auto const y = yScalar * cos(xScalar * x);
auto const y1 = static_cast<int>(floor(y));
auto const y2 = static_cast<int>(ceil(y));
auto const intensity = static_cast<uint8_t>(255 * fabs(y - y1));
// block.paintOver(x, yBase + y1, 255 - intensity);
// block.paintOver(x, yBase + y2, intensity);
block.paintOverThick(x, yBase + y1, uint8_t(255 - intensity), thickness_half, 0);
block.paintOverThick(x, yBase + y2, intensity, thickness_half, 0);
}
return block.take();
});
}
case Decorator::DottedUnderline: {
auto const dotHeight = (unsigned) _gridMetrics.underline.thickness;
auto const dotWidth = dotHeight;
auto const height = Height::cast_from((unsigned) _gridMetrics.underline.position + dotHeight);
auto const y0 = (unsigned) _gridMetrics.underline.position - dotHeight;
auto const x0 = 0u;
auto const x1 = unbox<unsigned>(width) / 2;
auto block = blockElement(ImageSize { width, height });
return create(block.downsampledSize(), [&]() -> atlas::Buffer {
for (unsigned y = 0; y < dotHeight; ++y)
{
for (unsigned x = 0; x < dotWidth; ++x)
{
block.paint(int(x + x0), int(y + y0));
block.paint(int(x + x1), int(y + y0));
}
}
return block.take();
});
}
case Decorator::DashedUnderline: {
// Devides a grid cell's underline in three sub-ranges and only renders first and third one,
// whereas the middle one is being skipped.
auto const thickness_half = max(1u, unsigned(ceil(underlineThickness() / 2.0)));
auto const thickness = max(1u, thickness_half * 2);
auto const y0 = max(0u, unsigned(underlinePosition()) - thickness_half);
auto const height = Height(y0 + thickness);
auto const imageSize = ImageSize { width, height };
return create(imageSize, [&]() -> atlas::Buffer {
auto image = atlas::Buffer(unbox<size_t>(width) * unbox<size_t>(height), 0);
for (unsigned y = 1; y <= thickness; ++y)
for (unsigned x = 0; x < unbox<unsigned>(width); ++x)
if (fabsf(float(x) / float(*width) - 0.5f) >= 0.25f)
image[(*height - y0 - y) * *width + x] = 0xFF;
return image;
});
}
case Decorator::Framed: {
auto const cellHeight = _gridMetrics.cellSize.height;
auto const thickness = max(1u, unsigned(underlineThickness()) / 2);
auto const imageSize = ImageSize { width, cellHeight };
return create(imageSize, [&]() -> atlas::Buffer {
auto image = atlas::Buffer(unbox<size_t>(width) * unbox<size_t>(cellHeight), 0);
auto const gap = 0; // thickness;
// Draws the top and bottom horizontal lines
for (unsigned y = gap; y < thickness + gap; ++y)
for (unsigned x = gap; x < unbox<unsigned>(width) - gap; ++x)
{
image[y * *width + x] = 0xFF;
image[(*cellHeight - 1 - y) * *width + x] = 0xFF;
}
// Draws the left and right vertical lines
for (unsigned y = gap; y < unbox<unsigned>(cellHeight) - gap; y++)
for (unsigned x = gap; x < thickness + gap; ++x)
{
image[y * *width + x] = 0xFF;
image[y * *width + (*width - 1 - x)] = 0xFF;
}
return image;
});
}
case Decorator::Overline: {
auto const cellHeight = _gridMetrics.cellSize.height;
auto const thickness = (unsigned) underlineThickness();
auto const imageSize = ImageSize { width, cellHeight };
return create(imageSize, [&]() -> atlas::Buffer {
auto image = atlas::Buffer(unbox<size_t>(width) * unbox<size_t>(cellHeight), 0);
for (unsigned y = 0; y < thickness; ++y)
for (unsigned x = 0; x < unbox<unsigned>(width); ++x)
image[(*cellHeight - y - 1) * *width + x] = 0xFF;
return image;
});
}
case Decorator::CrossedOut: {
auto const height = Height(*_gridMetrics.cellSize.height / 2);
auto const thickness = (unsigned) underlineThickness();
auto const imageSize = ImageSize { width, height };
return create(imageSize, [&]() -> atlas::Buffer {
auto image = atlas::Buffer(unbox<size_t>(width) * unbox<size_t>(height), 0);
for (unsigned y = 1; y <= thickness; ++y)
for (unsigned x = 0; x < unbox<unsigned>(width); ++x)
image[(*height - y) * *width + x] = 0xFF;
return image;
});
}
}
Require(false && "Unhandled case.");
return {};
}
void DecorationRenderer::renderDecoration(Decorator decoration,
crispy::Point pos,
ColumnCount columnCount,
RGBColor const& color)
{
for (auto i = ColumnCount(0); i < columnCount; ++i)
{
auto const tileIndex = _directMapping.toTileIndex(static_cast<uint32_t>(decoration));
auto const tileLocation = _textureAtlas->tileLocation(tileIndex);
TextureAtlas::TileCreateData tileData = createTileData(decoration, tileLocation);
AtlasTileAttributes const& tileAttributes = _textureAtlas->directMapped(tileIndex);
renderTile({ pos.x + unbox<int>(i) * unbox<int>(_gridMetrics.cellSize.width) },
{ pos.y },
color,
tileAttributes);
}
}
} // namespace terminal::renderer
| 43.782609
| 107
| 0.563839
|
christianparpart
|
1812243c839f98ba54f28bd5d6e08ccbd812977c
| 4,280
|
cc
|
C++
|
libfabric/prov/sstmac/src/sstmac_wait.cc
|
sstsimulator/sst-transports
|
6561e1ab001b3ee8ece1b97ee89360258cd4c75c
|
[
"BSD-3-Clause"
] | null | null | null |
libfabric/prov/sstmac/src/sstmac_wait.cc
|
sstsimulator/sst-transports
|
6561e1ab001b3ee8ece1b97ee89360258cd4c75c
|
[
"BSD-3-Clause"
] | 1
|
2021-08-05T17:24:36.000Z
|
2021-08-05T17:24:36.000Z
|
libfabric/prov/sstmac/src/sstmac_wait.cc
|
sstsimulator/sst-transports
|
6561e1ab001b3ee8ece1b97ee89360258cd4c75c
|
[
"BSD-3-Clause"
] | 2
|
2021-08-05T17:25:14.000Z
|
2021-11-10T02:48:04.000Z
|
/**
Copyright 2009-2020 National Technology and Engineering Solutions of Sandia,
LLC (NTESS). Under the terms of Contract DE-NA-0003525, the U.S. Government
retains certain rights in this software.
Sandia National Laboratories is a multimission laboratory managed and operated
by National Technology and Engineering Solutions of Sandia, LLC., a wholly
owned subsidiary of Honeywell International, Inc., for the U.S. Department of
Energy's National Nuclear Security Administration under contract DE-NA0003525.
Copyright (c) 2009-2020, NTESS
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Questions? Contact sst-macro-help@sandia.gov
*/
#include <stdlib.h>
#include <signal.h>
#include "sstmac.h"
#include "sstmac_wait.h"
#include <sprockit/errors.h>
#include <vector>
static int sstmac_wait_control(struct fid *wait, int command, void *arg);
extern "C" int sstmac_wait_close(struct fid *wait);
extern "C" DIRECT_FN int sstmac_wait_wait(struct fid_wait *wait, int timeout);
extern "C" DIRECT_FN int sstmac_wait_open(struct fid_fabric *fabric,
struct fi_wait_attr *attr,
struct fid_wait **waitset);
static struct fi_ops sstmac_fi_ops = {
.size = sizeof(struct fi_ops),
.close = sstmac_wait_close,
.bind = fi_no_bind,
.control = sstmac_wait_control,
.ops_open = fi_no_ops_open
};
static struct fi_ops_wait sstmac_wait_ops = {
.size = sizeof(struct fi_ops_wait),
.wait = sstmac_wait_wait
};
struct sstmac_fid_wait_obj {
};
struct sstmac_fid_wait_set {
struct fid_wait wait;
struct fid_fabric *fabric;
enum fi_cq_wait_cond cond_type;
enum fi_wait_obj type;
std::vector<fid*> listeners;
};
static int sstmac_wait_control(struct fid *wait, int command, void *arg)
{
/*
struct fid_wait *wait_fid_priv;
SSTMAC_TRACE(WAIT_SUB, "\n");
wait_fid_priv = container_of(wait, struct fid_wait, fid);
*/
switch (command) {
case FI_GETWAIT:
return -FI_ENOSYS;
default:
return -FI_EINVAL;
}
}
extern "C" void sstmaci_add_wait(struct fid_wait *wait, struct fid *wait_obj)
{
sstmac_fid_wait_set* waitset = (sstmac_fid_wait_set*) wait;
waitset->listeners.push_back(wait_obj);
}
extern "C" DIRECT_FN int sstmac_wait_wait(struct fid_wait *wait, int timeout)
{
int err = 0, ret;
char c;
spkt_abort_printf("unimplemented: sstmac_wait_wait for wait set");
return FI_SUCCESS;
}
extern "C" int sstmac_wait_close(struct fid *wait)
{
free(wait);
return FI_SUCCESS;
}
DIRECT_FN int sstmac_wait_open(struct fid_fabric *fabric,
struct fi_wait_attr *attr,
struct fid_wait **waitset)
{
struct sstmac_fid_wait_set* waiter = (struct sstmac_fid_wait_set*) calloc(1,sizeof(struct sstmac_fid_wait_set));
waiter->wait.fid.fclass = FI_CLASS_WAIT;
waiter->wait.fid.ops = &sstmac_fi_ops;
waiter->fabric = fabric;
*waitset = (fid_wait*) waiter;
return FI_SUCCESS;
}
| 31.703704
| 114
| 0.764953
|
sstsimulator
|
181290adcdcadb00e1457986b03d3982e0cbba0f
| 5,759
|
hpp
|
C++
|
include/cadence/async/streamsocket.hpp
|
abbyssoul/libcadence
|
c9a49d95df608497e9551f7d62169d0c78a48737
|
[
"Apache-2.0"
] | 2
|
2020-04-24T15:07:33.000Z
|
2020-06-12T07:01:53.000Z
|
include/cadence/async/streamsocket.hpp
|
abbyssoul/libcadence
|
c9a49d95df608497e9551f7d62169d0c78a48737
|
[
"Apache-2.0"
] | null | null | null |
include/cadence/async/streamsocket.hpp
|
abbyssoul/libcadence
|
c9a49d95df608497e9551f7d62169d0c78a48737
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) Ivan Ryabov - All Rights Reserved
*
* Unauthorized copying of this file, via any medium is strictly prohibited.
* Proprietary and confidential.
*
* Written by Ivan Ryabov <abbyssoul@gmail.com>
*/
/*******************************************************************************
* libcadence: Async Stream Sockets
* @file cadence/async/streamsocket.hpp
* @author $LastChangedBy$
* @date $LastChangedDate$
* ID: $Id$
******************************************************************************/
#pragma once
#ifndef CADENCE_ASYNC_STREAMSOCKET_HPP
#define CADENCE_ASYNC_STREAMSOCKET_HPP
#include "cadence/async/channel.hpp"
#include "cadence/networkEndpoint.hpp"
namespace cadence { namespace async {
/**
* Base class for stream-oriented sockets
*/
class StreamSocket :
public Channel {
public:
using Channel::size_type;
~StreamSocket() override;
StreamSocket(StreamSocket const &) = delete;
StreamSocket& operator= (StreamSocket const& ) = delete;
StreamSocket(StreamSocket&& rhs) = default;
StreamSocket& operator= (StreamSocket&& rhs) noexcept = default;
StreamSocket& swap(StreamSocket& rhs) noexcept {
using std::swap;
swap(_pimpl, rhs._pimpl);
return *this;
}
using Channel::asyncRead;
using Channel::asyncWrite;
using Channel::read;
using Channel::write;
/**
* Post an async read request to read specified amount of data from this IO object into the given buffer.
*
* @param dest The provided destination buffer to read data into.
* @param bytesToRead Amount of data (in bytes) to read from this IO object.
* @return A future that will be resolved one the scpecified number of bytes has been read.
*
* @note If the provided destination buffer is too small to hold requested amount of data - an exception is raised.
*/
Solace::Future<void> asyncRead(Solace::ByteWriter& dest, size_type bytesToRead) override;
/**
* Post an async write request to write specified amount of data into this IO object.
*
* @param src The provided source buffer to read data from.
* @param bytesToWrite Amount of data (in bytes) to write from the buffer into this IO object.
* @return A future that will be resolved one the scpecified number of bytes has been written into the IO object.
*
* @note If the provided source buffer does not have requested amount of data - an exception is raised.
*/
Solace::Future<void> asyncWrite(Solace::ByteReader& src, size_type bytesToWrite) override;
/** @see Channel::cancel */
void cancel() override;
/** @see Channel::close */
void close() override;
/** @see Channel::isOpen */
bool isOpen() const override;
/** @see Channel::isClosed */
bool isClosed() const override;
/** @see Channel::read */
Solace::Result<void, Solace::Error> read(Solace::ByteWriter& dest, size_type bytesToRead) override;
/** @see Channel::write */
Solace::Result<void, Solace::Error> write(Solace::ByteReader& src, size_type bytesToWrite) override;
/**
* Get the local endpoint of the socket.
* @return Local endpoint this socket is bound to.
*/
NetworkEndpoint getLocalEndpoint() const;
/**
* Get the remote endpoint of the socket.
* @return Remote endpoint this socket is connected to if any.
*/
NetworkEndpoint getRemoteEndpoint() const;
/**
* Disable sends or receives on the socket.
*/
void shutdown();
/**
* Start an syncronous connection to the given endpoint.
* This call will block until a connection is complete (either successfully or in an error)
* @param endpoint An endpoint to connect to.
*/
Solace::Result<void, Solace::Error> connect(NetworkEndpoint const& endpoint);
/**
* Start an asynchronous connection to the given endpoint.
* @param endpoint An endpoint to connect to.
* @return Future that is resolved when connection is establised or an error occured.
*/
Solace::Future<void> asyncConnect(NetworkEndpoint const& endpoint);
public:
class StreamSocketImpl {
public:
virtual ~StreamSocketImpl();
virtual
Solace::Future<void>
asyncRead(Solace::ByteWriter& dest, size_type bytesToRead) = 0;
virtual
Solace::Future<void>
asyncWrite(Solace::ByteReader& src, size_type bytesToWrite) = 0;
virtual
Solace::Result<void, Solace::Error>
read(Solace::ByteWriter& dest, size_type bytesToRead) = 0;
virtual
Solace::Result<void, Solace::Error>
write(Solace::ByteReader& src, size_type bytesToWrite) = 0;
virtual
void cancel() = 0;
virtual
void close() = 0;
virtual
bool isOpen() const = 0;
virtual
bool isClosed() const = 0;
virtual
NetworkEndpoint getLocalEndpoint() const = 0;
virtual
NetworkEndpoint getRemoteEndpoint() const = 0;
virtual
void shutdown() = 0;
virtual Solace::Future<void>
asyncConnect(NetworkEndpoint const& endpoint) = 0;
virtual Solace::Result<void, Solace::Error>
connect(NetworkEndpoint const& endpoint) = 0;
};
StreamSocket(EventLoop& ioContext, std::unique_ptr<StreamSocketImpl> impl);
private:
std::unique_ptr<StreamSocketImpl> _pimpl;
};
inline void swap(StreamSocket& lhs, StreamSocket& rhs) noexcept {
lhs.swap(rhs);
}
StreamSocket createTCPSocket(EventLoop& loop);
StreamSocket createUnixSocket(EventLoop& loop);
} // End of namespace async
} // End of namespace cadence
#endif // CADENCE_ASYNC_STREAMSOCKET_HPP
| 28.092683
| 119
| 0.650113
|
abbyssoul
|
181c4ea39274ab564324aa2056b36512a31cec36
| 6,911
|
cpp
|
C++
|
addjobdiag.cpp
|
dayuanyuan1989/RemoteBinder
|
6c07896828187bbb890115fa1326f9db4fbd7b68
|
[
"MIT"
] | null | null | null |
addjobdiag.cpp
|
dayuanyuan1989/RemoteBinder
|
6c07896828187bbb890115fa1326f9db4fbd7b68
|
[
"MIT"
] | null | null | null |
addjobdiag.cpp
|
dayuanyuan1989/RemoteBinder
|
6c07896828187bbb890115fa1326f9db4fbd7b68
|
[
"MIT"
] | null | null | null |
#include "addjobdiag.h"
#include "ui_addjobdiag.h"
#include <QSize>
#include <QString>
#include <QStringList>
#include <QTime>
#include <QDate>
#include <QColor>
#include <QFontDatabase>
#include <QDebug>
AddJobDiag::AddJobDiag(QWidget *parent) :
QWidget(parent),
ui(new Ui::AddJobDiag)
{
ui->setupUi(this);
init();
m_sizeMap["1280 × 720"] = QSize(1280, 720);
m_sizeMap["1280 × 960"] = QSize(1280, 960);
m_sizeMap["1920 × 1080"] = QSize(1920, 1080);
m_sizeMap["1920 × 1200"] = QSize(1920, 1200);
m_sizeMap["2048 × 1748"] = QSize(2048, 1748);
m_sizeMap["2560 × 1600"] = QSize(2560, 1600);
m_sizeMap["3840 × 2160"] = QSize(3840, 2160);
m_sizeMap["4960 × 2790"] = QSize(4960, 2790);
m_sizeMap["4960 × 3508"] = QSize(4960, 3508);
m_sizeMap["7680 × 4320"] = QSize(7680, 4320);
m_sizeMap["7680 × 4800"] = QSize(7680, 4800);
ui->comboBox->clear();
QStringList items;
items.append(m_sizeMap.keys());
ui->comboBox->addItems(items);
ui->fontsizecombox->setCurrentText("36");
ui->textedit->clear();
ui->textedit->setPlainText("Sample Text");
}
AddJobDiag::~AddJobDiag()
{
final();
delete ui;
}
void AddJobDiag::init()
{
SetFontSizeCombox(QFont());
// connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, SIGNAL(fontFamilyChanged(QFont)));
connect(ui->fontboldbtn, SIGNAL(toggled(bool)), this, SIGNAL(BoldStateChanged(bool)));
connect(ui->fontitalicbtn, SIGNAL(toggled(bool)), this, SIGNAL(ItalyStateChanged(bool)));
connect(ui->watermarkchkbox, SIGNAL(toggled(bool)), this, SIGNAL(WaterMarkVisibleChanged(bool)));
}
void AddJobDiag::final()
{
// disconnect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, SIGNAL(fontFamilyChanged(QFont)));
disconnect(ui->fontboldbtn, SIGNAL(toggled(bool)), this, SIGNAL(BoldStateChanged(bool)));
disconnect(ui->fontitalicbtn, SIGNAL(toggled(bool)), this, SIGNAL(ItalyStateChanged(bool)));
disconnect(ui->watermarkchkbox, SIGNAL(toggled(bool)), this, SIGNAL(WaterMarkVisibleChanged(bool)));
}
QByteArray AddJobDiag::GetAddRenderTaskString()
{
RenderData data;
QString fileName;
data.size = m_sizeMap[ui->comboBox->currentText()];
if(ui->mediumBtn->isChecked()) {
fileName.append("MEDIUM");
data.quality = 0;
} else if (ui->highBtn->isChecked()) {
fileName.append("HIGH");
data.quality = 1;
} else if (ui->veryHighBtn->isChecked()) {
fileName.append("VERY HIGH");
data.quality = 2;
} else {
fileName.append("MEDIUM");
data.quality = 0;
}
fileName.append("_");
fileName.append(QString::number(data.size.width()));
fileName.append("_");
fileName.append(QString::number(data.size.height()));
fileName.append("_");
fileName.append(QDateTime::currentDateTime().date().toString("yyyyMMdd"));
fileName.append("_");
fileName.append(QDateTime::currentDateTime().time().toString("hhmmsszzz"));
if(ui->jpgBtn->isChecked()) {
data.format = 0;
fileName.append(".jpg");
} else if(ui->tifBtn->isChecked()) {
fileName.append(".tif");
data.format = 1;
} else if(ui->pngBtn->isChecked()){
fileName.append(".png");
data.format = 2;
} else {
fileName.append(".jpg");
data.format = 0;
}
qDebug() << fileName;
data.fileName = fileName;
QByteArray str("AddRenderTask:");
unsigned uSize = 0x00;
uSize = data.size.width();
uSize = uSize << 16;
uSize |= data.size.height();
str.append(QString("FileName:%1;").arg(data.fileName));
str.append(QString("SIZE:%1;").arg(uSize));
str.append(QString("FORMAT:%1;").arg(data.format));
str.append(QString("QUALITY:%1;").arg(data.quality));
return str;
}
void AddJobDiag::on_addTaskBtn_clicked()
{
RenderData data;
QString fileName;
data.size = m_sizeMap[ui->comboBox->currentText()];
if(ui->mediumBtn->isChecked()) {
fileName.append("MEDIUM");
data.quality = 0;
} else if (ui->highBtn->isChecked()) {
fileName.append("HIGH");
data.quality = 1;
} else if (ui->veryHighBtn->isChecked()) {
fileName.append("VERY HIGH");
data.quality = 2;
} else {
fileName.append("MEDIUM");
data.quality = 0;
}
fileName.append("_");
fileName.append(QString::number(data.size.width()));
fileName.append("_");
fileName.append(QString::number(data.size.height()));
fileName.append("_");
fileName.append(QDateTime::currentDateTime().date().toString("yyyyMMdd"));
fileName.append("_");
fileName.append(QDateTime::currentDateTime().time().toString("hhmmsszzz"));
if(ui->jpgBtn->isChecked()) {
data.format = 0;
fileName.append(".jpg");
} else if(ui->tifBtn->isChecked()) {
fileName.append(".tif");
data.format = 1;
} else if(ui->pngBtn->isChecked()){
fileName.append(".png");
data.format = 2;
} else {
fileName.append(".jpg");
data.format = 0;
}
data.fileName = fileName;
unsigned uSize = 0x00;
uSize = data.size.width();
uSize = uSize << 16;
uSize |= data.size.height();
emit AddNewTask(data);
}
void AddJobDiag::on_colorlineEdit_editingFinished()
{
QString colorStr = ui->colorlineEdit->text();
if(colorStr.startsWith("#")) {
QString colorDataStr = colorStr.mid(1, 6);
bool ok = false;
uint ucolordata = colorDataStr.toUInt(&ok, 16);
if(ok) {
QColor color(ucolordata);
ui->colorbglabel->setStyleSheet(QString("background-color: rgba(%1, %2, %3, %4);").arg(color.red()).arg(color.green()).arg(color.blue()).arg(color.alpha()));
emit TextColorChanged(color);
}
}
}
void AddJobDiag::on_fontsizecombox_currentIndexChanged(const QString &arg1)
{
bool ok = false;
uint size = arg1.toUInt(&ok);
if(ok) {
emit fontSizeChanged(size);
}
}
void AddJobDiag::on_textedit_textChanged()
{
emit TextChanged(ui->textedit->toPlainText());
}
void AddJobDiag::on_fontComboBox_currentFontChanged(const QFont &f)
{
SetFontSizeCombox(f);
ui->fontboldbtn->setChecked(false);
ui->fontitalicbtn->setChecked(false);
ui->fontsizecombox->setCurrentText("36");
emit fontFamilyChanged(f);
emit fontSizeChanged(36);
}
void AddJobDiag::SetFontSizeCombox(const QFont& f)
{
QFontDatabase database;
QList<int> list = database.pointSizes(f.family());
ui->fontsizecombox->clear();
foreach(int size, list) {
ui->fontsizecombox->addItem(QString::number(size));
}
}
| 30.444934
| 170
| 0.610476
|
dayuanyuan1989
|
1820eb9ae60047891661d8c8f9e02f9470c2d92a
| 1,520
|
hpp
|
C++
|
zooTycoon.hpp
|
bolym/C-ZooGame
|
33a66a4e7e3cccc731520471c2641cd8f901ae02
|
[
"MIT"
] | null | null | null |
zooTycoon.hpp
|
bolym/C-ZooGame
|
33a66a4e7e3cccc731520471c2641cd8f901ae02
|
[
"MIT"
] | null | null | null |
zooTycoon.hpp
|
bolym/C-ZooGame
|
33a66a4e7e3cccc731520471c2641cd8f901ae02
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <algorithm>
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
using namespace std;
class Animal{
protected:
int age;
int price;
int numBabies;
int foodCost;
int revenue;
public:
Animal();
int getAge();
int getPrice();
int getNumBabies();
int getFoodCost();
int getRevenue();
void incrementAge();
};
class Sloth : public Animal {
protected:
public:
Sloth();
Sloth(int days);
};
class SeaOtter : public Animal {
protected:
public:
SeaOtter();
SeaOtter(int days);
};
class Monkey : public Animal {
protected:
public:
Monkey();
Monkey(int days);
};
class Zoo{
protected:
int bankAccount;
int numAnimals;
int numMonkey;
Monkey* monkeys;
int numSeaOtter;
SeaOtter* seaOtters;
int numSloth;
Sloth* sloths;
int baseFoodCost;
bool bankrupt;
public:
Zoo();
~Zoo();
void displayGame();
void ageAnimals();
int checkInput(string question, string valid);
void buyAnimal();
void addMonkey(int age);
void addSeaOtter(int age);
void addSloth(int age);
void feedAnimals();
Animal* getRandAnimal();
void specialEvent();
void makeSick();
void makeBirth();
void makeBoom();
void makeRevenue();
void beginGame();
};
| 17.882353
| 56
| 0.576974
|
bolym
|
18218a4cb185430f140c18184eeea8088d3aea79
| 2,013
|
cpp
|
C++
|
torch/csrc/distributed/c10d/Ops.cpp
|
qqaatw/pytorch
|
44764f131b040a41a6dcf1304bb635c574bf5a3b
|
[
"Intel"
] | null | null | null |
torch/csrc/distributed/c10d/Ops.cpp
|
qqaatw/pytorch
|
44764f131b040a41a6dcf1304bb635c574bf5a3b
|
[
"Intel"
] | null | null | null |
torch/csrc/distributed/c10d/Ops.cpp
|
qqaatw/pytorch
|
44764f131b040a41a6dcf1304bb635c574bf5a3b
|
[
"Intel"
] | null | null | null |
#include <torch/csrc/distributed/c10d/Ops.hpp>
#include <ATen/core/dispatch/Dispatcher.h>
#include <torch/library.h>
namespace c10d {
namespace {
c10::intrusive_ptr<ProcessGroup::Work> broadcast(
const c10::intrusive_ptr<ProcessGroup>& process_group,
at::TensorList tensors,
int64_t root_rank = 0,
int64_t root_tensor = 0,
int64_t timeout = -1) {
auto tensor_vec = tensors.vec();
return process_group->broadcast(
tensor_vec,
BroadcastOptions{
root_rank, root_tensor, std::chrono::milliseconds(timeout)});
}
TORCH_LIBRARY(c10d, m) {
// The following ProcessGroup and Work definations are more like declarations.
// They don't expose the details of the two classes into TorchScript.
m.class_<ProcessGroup>("ProcessGroup").def(torch::init<int64_t, int64_t>());
m.class_<ProcessGroup::Work>("Work").def(torch::init<>());
// It's important to register the op to the CompositeExplicitAutograd key to
// enable
// __torch_dispatch__.
m.def(
"broadcast",
dispatch(c10::DispatchKey::CompositeExplicitAutograd, broadcast));
}
} // namespace
namespace ops {
c10::intrusive_ptr<ProcessGroup::Work> broadcast(
const c10::intrusive_ptr<ProcessGroup>& process_group,
at::TensorList tensors,
const BroadcastOptions& opts) {
auto op = c10::Dispatcher::singleton()
.findSchemaOrThrow("c10d::broadcast", "")
.typed<c10::intrusive_ptr<::c10d::ProcessGroup::Work>(
const c10::intrusive_ptr<::c10d::ProcessGroup>&,
at::TensorList,
int64_t,
int64_t,
int64_t)>();
// It's awakward to unbox the opts here and box them again in the custom C++
// op. But it's also complicated to make opts as a CustomClassHolder. Leave it
// as it is now.
return op.call(
process_group,
tensors,
opts.rootRank,
opts.rootTensor,
opts.timeout.count());
}
} // namespace ops
} // namespace c10d
| 32.467742
| 80
| 0.660209
|
qqaatw
|
18228eca0c71619b74e7395225bdc2da6e71e6d8
| 11,390
|
cpp
|
C++
|
src/stringarray.cpp
|
Sneedd/rush
|
a07eef74d1757f1995ea4f6ceafb7c328719f08d
|
[
"MIT"
] | null | null | null |
src/stringarray.cpp
|
Sneedd/rush
|
a07eef74d1757f1995ea4f6ceafb7c328719f08d
|
[
"MIT"
] | null | null | null |
src/stringarray.cpp
|
Sneedd/rush
|
a07eef74d1757f1995ea4f6ceafb7c328719f08d
|
[
"MIT"
] | null | null | null |
/*
* stringarray.cpp - Implementation of StringArray class
*
* This file is part of the rush utility library.
* Licenced unter the terms of Lesser GPL v3.0 (see licence.txt).
* Copyright 2011-2012 - Steffen Ott
*
*/
#include <rush/stringarray.h>
#include <rush/log.h>
#include <rush/buildinexpect.h>
#include <rush/macros.h>
namespace rush {
//-----------------------------------------------------------------------------
StringArray::StringArray()
/**
* \brief Standardconstructor, initializes the StringArray object.
* Initialcapacity is 16 strings.
**/
{
m_capacity = 16;
m_count = 0;
m_items = new String*[m_capacity];
memset(m_items, 0, m_capacity*sizeof(String*));
}
//-----------------------------------------------------------------------------
StringArray::StringArray(size_t capacity)
/**
* \brief Constructor, initializes the StringArray object with the
* given capacity.
* \param capacity Initial capacity of the array.
**/
{
if (unlikely(capacity < 4)) {
capacity = 4;
}
m_capacity = capacity;
m_count = 0;
m_items = new String*[m_capacity];
memset(m_items, 0, m_capacity*sizeof(String*));
}
//-----------------------------------------------------------------------------
StringArray::StringArray(const StringArray& array)
/**
* \brief Copyconstructor, shallow copies the given array to this.
* Note, that the copy will not contain copied strings, if you want a
* full or deep copy, use Copy().
**/
{
m_capacity = array.m_count;
m_count = array.m_count;
m_items = new String*[m_capacity];
m_items = (String**)memcpy(m_items, array.m_items, sizeof(String*)*m_capacity);
}
//-----------------------------------------------------------------------------
StringArray::~StringArray()
/**
* \brief Destructor. Frees all allocated memory.
**/
{
if (likely(m_items != NULL))
{
for (size_t i=0; i<m_count; ++i)
{
if (m_items[i] != NULL)
{
delete m_items[i];
}
}
delete [] m_items;
}
}
//-----------------------------------------------------------------------------
StringArray& StringArray::operator=(const StringArray& array)
/**
* \brief Assigment operator, copies the given array to this.
* \param array String array to copy into this array.
* \return This array.
**/
{
if (likely(m_items != NULL))
{
for (size_t i=0; i<m_count; ++i)
{
if (m_items[i] != NULL)
{
delete m_items[i];
m_items[i] = NULL;
}
}
delete [] m_items;
}
m_capacity = array.m_count;
m_count = array.m_count;
m_items = new String*[m_capacity];
for (size_t i=0; i<m_capacity; ++i)
{
m_items[i] = new String(*(array.m_items[i]));
}
return (*this);
}
//-----------------------------------------------------------------------------
String& StringArray::operator[](size_t index)
/**
* \brief Returns the string at the given index.
* \param index Index.
* \return String at the index.
**/
{
if (unlikely(index >= m_count))
{
Log::Error(_T("[StringArray::operator[]] Index out of range."));
return (*m_items[index]);
}
return (*m_items[index]);
}
//-----------------------------------------------------------------------------
const String& StringArray::operator[](size_t index) const
/**
* \brief Returns the string at the given index.
* \param index Index.
* \return String at the index.
**/
{
if (unlikely(index >= m_count))
{
Log::Error(_T("[StringArray::operator[]] Index out of range."));
return (*m_items[index]);
}
return (*m_items[index]);
}
//-----------------------------------------------------------------------------
String& StringArray::Item(size_t index)
/**
* \brief Returns the string at the given index.
* \param index Index.
* \return String at the index.
**/
{
if (unlikely(index >= m_count))
{
Log::Error(_T("[StringArray::operator[]] Index out of range."));
return (*m_items[index]);
}
return (*m_items[index]);
}
//-----------------------------------------------------------------------------
const String& StringArray::Item(size_t index) const
/**
* \brief Returns the string at the given index.
* \param index Index.
* \return String at the index.
**/
{
if (unlikely(index >= m_count))
{
Log::Error(_T("[StringArray::operator[]] Index out of range."));
return (*m_items[index]);
}
return (*m_items[index]);
}
//-----------------------------------------------------------------------------
int StringArray::IndexOf(const String& strg) const
/**
* \brief Searches for a string in the array and returning its index.
* \param strg String to search for.
* \return Index in the array or -1 if the string is not in the array.
**/
{
for (size_t i=0; i<m_count; ++i)
{
if (m_items[i] != NULL)
{
if (*(m_items[i]) == strg)
{
return (i);
}
}
}
return (-1);
}
//-----------------------------------------------------------------------------
StringArray& StringArray::Add(const String& strg)
/**
* \brief Adds a string to the array.
* \param strg String.
* \return This array.
**/
{
if (unlikely(m_count >= m_capacity))
{
this->Alloc(m_capacity*2);
}
m_items[m_count] = new String(strg);
m_count++;
return (*this);
}
//-----------------------------------------------------------------------------
StringArray& StringArray::AddFormat(const String& format, ...)
/**
* \brief Adds a formated string to the array. See printf() for format options.
* \param format Format string.
* \return This array.
**/
{
va_list args;
va_start(args,format);
this->Add(String::FormatV(format, args));
return (*this);
}
//-----------------------------------------------------------------------------
bool StringArray::Insert(size_t index, const String& strg)
/**
* \brief Inserts a string at the given index.
* \param index Index.
* \param strg String.
* \return True, if string was successful inserted; otherwise false.
**/
{
if (unlikely(index > m_count))
{
Log::Error(_T("[PrimitiveArray::Insert] Index out of range."));
return (false);
}
if (unlikely(index == m_count))
{
this->Add(strg);
return (true);
}
if (unlikely(m_capacity <= m_count))
{
this->Alloc(m_capacity*2);
}
memmove(m_items+index+1, m_items+index, (m_count-index)*sizeof(String*));
m_items[index] = new String(strg);
m_count++;
return (true);
}
//-----------------------------------------------------------------------------
bool StringArray::Remove(size_t index)
/**
* \brief Removes a string from the given index.
* \param index Index.
* \return True, if string was successful removed; otherwise false.
**/
{
if (unlikely(index >= m_count))
{
Log::Error(_T("[PrimitiveArray::Remove] Index out of range."));
return (false);
}
if (m_items[index] != NULL)
{
delete m_items[index];
}
m_items[index] = NULL;
memmove(m_items+index, m_items+index+1, (m_count-index)*sizeof(String*));
m_count--;
return (true);
}
//-----------------------------------------------------------------------------
void StringArray::Clear()
/**
* \brief Clears the array and eventually reduces capacity.
* Reduces capacity only if the current capacity is bigger than 64.
**/
{
// Shrinks the array if capacity is to big
if (unlikely(m_capacity > 64)) {
this->Alloc(64);
}
// Free allocated memory
for (size_t i=0; i<m_count; ++i)
{
if (m_items[i] != NULL)
{
delete m_items[i];
m_items[i] = NULL;
}
}
// Empties array
m_count = 0;
}
//-----------------------------------------------------------------------------
void StringArray::Shrink()
/**
* \brief Shrinks the capacity to the number of strings in the array.
**/
{
this->Alloc(m_count);
}
//-----------------------------------------------------------------------------
void StringArray::Alloc(size_t capacity)
/**
* \brief Allocates the array capacity, can extend or shrink the array.
* \param capacity Capacity.
**/
{
if (unlikely(capacity < 4)) {
capacity = 4;
}
if (likely(capacity > m_capacity))
{
// Extend array
String** temp = new String*[capacity];
temp = (String**)memcpy(temp, m_items, m_capacity*sizeof(String*));
delete [] m_items;
m_items = temp;
m_capacity = capacity;
}
else
{
if (likely(capacity != m_capacity))
{
// Shrink array
String** temp = new String*[capacity];
memcpy(temp, m_items, capacity*sizeof(String*));
for (size_t i=capacity; i<m_count; ++i)
{
if (m_items[i] != NULL) {
delete m_items[i]; // Free dropping objects
}
}
delete [] m_items;
m_items = temp;
m_capacity = capacity;
m_count = ((m_count < capacity) ? m_count:capacity);
}
}
}
//-----------------------------------------------------------------------------
StringArray* StringArray::Split(const String& strg, const String& separator, StringSplitOptions options)
/**
* \brief Splits a string with the given separator by the given options.
* Note: The returning string array must be destroyed by the caller.
* \param strg The string which should be splitted.
* \param separator The separator string.
* \param options The split options.
* \return String array with the splitted strings.
**/
{
StringArray* array = new StringArray();
String split = _T("");
for (size_t index=0; index<strg.Length(); ++index)
{
if (strg[index] == separator[0])
{
bool endString = true;
for (size_t i=1; i<separator.Length(); ++i)
{
if (strg[index+i] != separator[i]) {
endString = false;
break;
}
if (separator.Length()-1 <= i) {
break;
}
}
if (endString) {
index += separator.Length()-1;
if ((options & StringSplitOptions::Trim) == StringSplitOptions::Trim) {
split.Trim();
}
if ((options & StringSplitOptions::RemoveEmptyEntries) == StringSplitOptions::RemoveEmptyEntries) {
if (split.Length() > 0) array->Add(split);
} else {
array->Add(split);
}
split.Clear();
}
else
{
split.Append(strg[index]);
}
}
else
{
split.Append(strg[index]);
}
}
if ((options & StringSplitOptions::Trim) == StringSplitOptions::Trim) {
split.Trim();
}
if ((options & StringSplitOptions::RemoveEmptyEntries) == StringSplitOptions::RemoveEmptyEntries) {
if (split.Length() > 0) array->Add(split);
} else {
array->Add(split);
}
array->Shrink();
return (array);
}
} // namespace rush
| 25.311111
| 115
| 0.502809
|
Sneedd
|
182c4afc4644b7470626e4dda738c6446a7e2cd2
| 4,547
|
cpp
|
C++
|
C/Lista03.cpp
|
IzaacBaptista/ads-senac
|
2a2fe89a88e2ac5a776302f464695e2537c2cd69
|
[
"MIT"
] | 2
|
2021-03-14T13:27:28.000Z
|
2021-09-29T19:09:37.000Z
|
C/Lista03.cpp
|
IzaacBaptista/ads-senac
|
2a2fe89a88e2ac5a776302f464695e2537c2cd69
|
[
"MIT"
] | null | null | null |
C/Lista03.cpp
|
IzaacBaptista/ads-senac
|
2a2fe89a88e2ac5a776302f464695e2537c2cd69
|
[
"MIT"
] | null | null | null |
// ************************************************************
//
// Exemplo de Estruturas Encadeadas
//
// ************************************************************
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
// define a estrutura do nodo
typedef struct Temp
{
int info;
struct Temp *prox;
}TNODO;
// cria o inicio da lista
TNODO *inicio=NULL;
//--------------------------------------------------------
// Funcao que define a lista como vazia.
void CriaLista()
{
inicio = NULL;
}
//--------------------------------------------------------
// Funcao que insere um elemento do inicio da lista.
// Retorna:
// 0 - se nao ha' memoria para inserir
// 1 - se conseguiu inserir
int Insere(int dado)
{
TNODO *p;
p = (TNODO *) malloc(sizeof(TNODO));
if (p==NULL)
{
printf("Erro de alocacao\n");
return 0;
}
p->info = dado;
p->prox = NULL;
if (inicio==NULL)
inicio = p;
else {
p->prox = inicio;
inicio = p;
}
return 1;
}
//--------------------------------------------------------
// Funcao que remove um elemento do inicio da lista.
// Retorna:
// 0 - se a lista ja' estava vazia
// 1 - se conseguiu remover
int RemoveDoInicio()
{
TNODO *ptr;
if (inicio==NULL)
return 0;
else
{
ptr = inicio;
inicio = inicio->prox;
free(ptr);
return 1;
}
}
//--------------------------------------------------------
// Funcao que imprime toda a lista.
//
void Imprime()
{
TNODO *ptr;
if (inicio == NULL)
{
printf("--- fim da lista ---\n\n");
return;
}
// Caso a lista nao esteja vazia
ptr = inicio;
while (ptr !=NULL) {
printf("Info = %d\n",ptr->info);
ptr = ptr->prox;
}
printf("--- fim da lista ---\n\n");
}
//--------------------------------------------------------
// Funcao que busca um elemento na lista.
// Retorna:
// - NULL caso nao encontre
// - ponteiro para o NODO onde esta' o dado, se conseguir encontrar
TNODO *BuscaDado(int dado)
{
TNODO *ptr;
if (inicio == NULL)
{
return NULL; // Lista Vazia
}
// Caso a lista nao esteja vazia
ptr = inicio;
while (ptr !=NULL) {
if (ptr->info == dado) // achou !!
return (ptr); // retorna um ponteiro para
//o inicio da lista
else ptr = ptr->prox;
}
return NULL;
}
//--------------------------------------------------------
// Funcao que remove um elemento especificado por 'dado'
// Retorna:
// 0 - se nao conseguiu achar
// 1 - se conseguiu remover
int RemoveDado(int dado)
{
TNODO *ptr, *antes;
if (inicio==NULL)
{
return 0; // Lista vazia !!!
}
else
{ // Caso a lista nao esteja vazia
ptr = inicio;
antes = inicio;
while (ptr !=NULL)
{
if (ptr->info == dado) // achou !!
{
if (ptr == inicio) // se esta removendo o primeiro da lista
{
inicio = inicio->prox;
free(ptr);
return 1; // removeu !!
}
else // esta removendo do meio da lista
{
antes->prox = ptr->prox; // Refaz o encadeamento
free(ptr); // Libera a area do nodo
return 1; // removeu !!
}
}
else // continua procurando no prox. nodo
{
antes = ptr;
ptr = ptr->prox;
}
}
return 0; // Nao achou !!!
}
}
//--------------------------------------------------
main()
{
int i, ret;
TNODO *aux;
CriaLista();
// Insere na lista os numeros 2, 4, 6, 8, 10, 12, 14, 16, 18 e 20
for (i=1; i<=10;i++)
Insere(i*2);
Imprime();
getch();
// Busca dados de -2 a 25
for (i=-2; i<=25;i++)
{
aux = BuscaDado(i);
if (aux != NULL)
printf("+++Achou o %d\n", aux->info);
else printf("---Nao achou o %d\n", i);
}
getch();
printf("Antes da remocao do primeiro nodo\n");
Imprime();
printf("Apos a remocao dos dois primeiros nodos\n");
// Remove os dois primeiros nodos
RemoveDoInicio();
RemoveDoInicio();
Imprime();
getch();
// Remove um elemento do meio da lista
// Tenta remover -3, 0, 3, 6, 9, 12, 15, 18, 21
printf("Remocao no meio da lista\n");
for (i=-3; i<=21;i+=3)
{
ret = RemoveDado(i);
if (ret == 1)
printf("+++Removeu o %d\n",i);
else printf("---Nao achou o %d\n", i);
}
printf("Apos a remocao\n");
Imprime();
getch();
// Remove Toda a Lista
ret = 1;
while (ret == 1)
{
ret = RemoveDoInicio();
}
printf("Apos a remocao de todos os nodos\n");
Imprime();
getch();
}
| 22.509901
| 68
| 0.485155
|
IzaacBaptista
|
1836e4e72fea2754d0112fa86bd8af8e9ab6e35b
| 13,095
|
hpp
|
C++
|
sources/SceneGraph/spSceneLight.hpp
|
rontrek/softpixel
|
73a13a67e044c93f5c3da9066eedbaf3805d6807
|
[
"Zlib"
] | 14
|
2015-08-16T21:05:20.000Z
|
2019-08-21T17:22:01.000Z
|
sources/SceneGraph/spSceneLight.hpp
|
rontrek/softpixel
|
73a13a67e044c93f5c3da9066eedbaf3805d6807
|
[
"Zlib"
] | null | null | null |
sources/SceneGraph/spSceneLight.hpp
|
rontrek/softpixel
|
73a13a67e044c93f5c3da9066eedbaf3805d6807
|
[
"Zlib"
] | 3
|
2016-10-31T06:08:44.000Z
|
2019-08-02T16:12:33.000Z
|
/*
* Light scene node header
*
* This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
* See "SoftPixelEngine.hpp" for license information.
*/
#ifndef __SP_SCENE_LIGHT_H__
#define __SP_SCENE_LIGHT_H__
#include "Base/spStandard.hpp"
#include "Base/spDimensionMatrix4.hpp"
#include "SceneGraph/spRenderNode.hpp"
namespace sp
{
namespace scene
{
/*
* Macros
*/
static const s32 MAX_COUNT_OF_SCENELIGHTS = 0x0D31;
class SceneGraph;
/*
* Structures
*/
/*
Light attenuation configuration structure.
\since Version 3.3
*/
struct SLightAttenuation
{
SLightAttenuation(f32 Cnst = 1.0f, f32 Lin = 0.1f, f32 Quad = 0.4f) :
Constant (Cnst ),
Linear (Lin ),
Quadratic (Quad )
{
}
~SLightAttenuation()
{
}
/* Functions */
inline void setRadius(f32 Radius)
{
if (Radius > math::ROUNDING_ERROR)
{
Constant = 1.0f;
Linear = 1.0f / Radius;
Quadratic = 1.0f / Radius;
}
}
inline f32 getRadius() const
{
return 1.0f / Linear;
}
/* Members */
f32 Constant;
f32 Linear;
f32 Quadratic;
};
/**
Spot light cone structure. It contains the inner and outer cone angles.
\since Version 3.3
*/
struct SP_EXPORT SLightCone
{
SLightCone(f32 Inner = 30.0f, f32 Outer = 60.0f) :
InnerAngle(Inner),
OuterAngle(Outer)
{
}
~SLightCone()
{
}
/* Members */
f32 InnerAngle;
f32 OuterAngle;
};
/**
Light color structured. It contains an ambient, a diffuse and a specular color.
\since Version 3.3
*/
struct SLightColor
{
SLightColor(
const video::color &Ambt = 255, const video::color &Diff = 200, const video::color Spec = 0) :
Ambient (Ambt),
Diffuse (Diff),
Specular(Spec)
{
}
~SLightColor()
{
}
/* Members */
video::color Ambient;
video::color Diffuse;
video::color Specular;
};
/**
Lights can be created for dynamic lighting and shading technics. But you will only see a maximum of 8 lights
because more are not supported by the current graphics cards! But you can create much more then 8.
But be aware of that you will only see 8 of them ;-). The engine is able to manage the lighting system good enough
that these ones who are near by the camera will be visible. Directional lights (scene::LIGHT_DIRECTIONAL)
have a priority in this sort process because they are never volumetric but endless visible.
*/
class SP_EXPORT Light : public SceneNode
{
public:
Light(const ELightModels Type = LIGHT_DIRECTIONAL);
virtual ~Light();
/* === Functions === */
/**
Sets the new light color.
\see SLightColor
\since Version 3.3
*/
void setColor(const SLightColor &Color);
/**
Sets the light's colors.
\param Diffuse: Diffuse color. This is the 'main' lighting color which is multiplied by each vertex's color.
\param Ambient: Ambient color. This is the darkest color. Also if the color is full bright it will not let the object
be complete white.
\param Specular: Specular color. If this color is not bright enough each shininess value for the Entity objects
will not cause any shine.
\depreacted Use setColor instead.
*/
void setLightingColor(const video::color &Diffuse, const video::color &Ambient = 255, const video::color &Specular = 0);
//! \deprecated Use "getColor" instead.
void getLightingColor(video::color &Diffuse, video::color &Ambient, video::color &Specular) const;
//! \deprecated Use the new "setSpotCone" function instead.
void setSpotCone(const f32 InnerConeAngle, const f32 OuterConeAngle);
//! \deprecated Use the new "getSpotCone" function instead.
void getSpotCone(f32 &InnerConeAngle, f32 &OuterConeAngle) const;
void setSpotConeInner(f32 Angle);
void setSpotConeOuter(f32 Angle);
/**
Sets the new spot light cone angles.
\see SLightCone
\since Version 3.3
*/
void setSpotCone(const SLightCone &SpotCone);
/**
Returns a view frustum if this is a spot light.
\param[out] Frustum Specifies the resulting view frustum. Although the spot light is actual a cone,
the resulting model is a frustum which can be used to render a shadow map from the light's point of view.
\param[out] GlobalPosition Specifies the global position which can be computed on the fly.
This can be used for frustum/frustum culling tests.
\return True if the frustum could be computed. This requires that this light is a spot light. Otherwise false.
*/
bool getSpotFrustum(scene::ViewFrustum &Frustum, dim::vector3df &GlobalPosition) const;
/**
Enables or disables the volumetric technic for lighting. This technic is only usable when the light
is a Point or a Spot light. Three parameters called "Attenuation" are used for this computation.
*/
void setVolumetric(bool IsVolumetric);
/**
Sets the volumetric radius. This function computes the threee attenuation
parameters automatically by only one value: the Radius.
*/
void setVolumetricRadius(f32 Radius);
f32 getVolumetricRadius() const;
/**
Sets the volumetric range or the three attenuation values.
Here you have to compute your own attenuations.
\deprecated Use "setAttenuation" instead.
*/
void setVolumetricRange(f32 Constant, f32 Linear, f32 Quadratic);
//! \deprecated Use "getAttenuation" instead.
void getVolumetricRange(f32 &Constant, f32 &Linear, f32 &Quadratic) const;
//! Sets the light's direction. Only usable for Directional or Spot lights.
void setDirection(const dim::vector3df &Direction);
void setDirection(const dim::matrix4f &Matrix);
//! Enables or disables the light
void setVisible(bool isVisible);
//! Copies the light objects and returns the pointer to the new instance. Don't forget to delete this object!
Light* copy() const;
/**
Updates the light. This function is called in the "renderScene" function of the SceneManager class.
You do not have to call this function.
*/
virtual void render();
/* === Static functions === */
/**
Sets the render-context usage for fixed-function light sources.
\param[in] UseAllRCs Specifies whether all render-contexts are to be used or only the active one.
By default all render contexts are affected.
\note Disable this state when you change light states (color, visiblity etc.) every frame
and you have several render contexts!
*/
static void setRCUsage(bool UseAllRCs);
/* === Inline functions === */
//! Sets the light shading model.
inline void setLightModel(const ELightModels Type)
{
LightModel_ = Type;
}
//! Returns the light shading model.
inline ELightModels getLightModel() const
{
return LightModel_;
}
//! Sets the diffuse light color.
inline void setDiffuseColor(const video::color &Color)
{
setLightingColor(Color, Color_.Ambient, Color_.Specular);
}
//! Returns the diffuse light color.
inline const video::color& getDiffuseColor() const
{
return Color_.Diffuse;
}
//! Sets the ambient light color.
inline void setAmbientColor(const video::color &Color)
{
setLightingColor(Color_.Diffuse, Color, Color_.Specular);
}
//! Returns the ambient light color.
inline const video::color& getAmbientColor() const
{
return Color_.Ambient;
}
//! Sets the specular light color.
inline void setSpecularColor(const video::color &Color)
{
setLightingColor(Color_.Diffuse, Color_.Ambient, Color);
}
//! Returns the specular light color.
inline const video::color& getSpecularColor() const
{
return Color_.Specular;
}
/**
Returns the light color
\see SLightColor
\since Version 3.3
*/
inline const SLightColor& getColor() const
{
return Color_;
}
/**
Sets the new light attenuation settings.
\see SLightAttenuation
\since Version 3.3
*/
inline void setAttenuation(const SLightAttenuation &Attn)
{
Attn_ = Attn;
}
/**
Returns the light attenuation settings
\see SLightAttenuation
\since Version 3.3
*/
inline const SLightAttenuation& getAttenuation() const
{
return Attn_;
}
/**
Returns the spot light cone angles.
\see SLightCone
\since Version 3.3
*/
inline const SLightCone& getSpotCone() const
{
return SpotCone_;
}
/**
Returns the inner spot cone angle (in degrees).
\deprecated Use getSpotCone() instead.
*/
inline f32 getSpotConeInner() const
{
return SpotCone_.InnerAngle;
}
/**
Returns the outer spot cone angle (in degrees).
\deprecated Use getSpotCone() instead.
*/
inline f32 getSpotConeOuter() const
{
return SpotCone_.OuterAngle;
}
//! Returns true if this is a volumetric light. By default false.
inline bool getVolumetric() const
{
return IsVolumetric_;
}
/**
Enables or disables shadow mapping.
\param[in] Enable Specifies whether shadow mapping is to be enabled or disabled for this light source. By default false.
\note This can only be used in combination with the integrated advanced-renderer.
\see video::AdvancedRenderer
\since Version 3.2
*/
inline void setShadow(bool Enable)
{
IsShadowMapping_ = Enable;
}
/**
Returns true if shadow mapping is enabled for this light source.
\since Version 3.2
*/
inline bool getShadow() const
{
return IsShadowMapping_;
}
/**
Enables or disables global illumiation.
\param[in] Enable Specifies whether global illumination is to be enabled or disabled for this light source. By default false.
\note This can only be used in combination with the integrated advanced-renderer.
\see video::AdvancedRenderer
\since Version 3.3
*/
inline void setGlobalIllumination(bool Enable)
{
IsGlobalIllumination_ = Enable;
}
//! Returns true if global illumination is enabled for this light source.
inline bool getGlobalIllumination() const
{
return IsGlobalIllumination_;
}
//! Returns the light's direction. This is only used for spot- and directional lights (LIGHT_SPOT, LIGHT_DIRECTIONAL).
inline dim::vector3df getDirection() const
{
return Direction_;
}
//! Returns the projection matrix. This is only used for spot-lights (LIGHT_SPOT).
inline dim::matrix4f getProjectionMatrix() const
{
return ProjectionMatrix_;
}
protected:
friend class SceneGraph;
/* === Members ===*/
u32 LightID_; //!< Renderer ID number for this light.
ELightModels LightModel_; //!< Lighting model: Directional, Point, Spot.
SLightColor Color_; //!< Light color (ambient, diffuse, specular).
dim::vector3df Direction_; //!< Spot- and directional light direction.
SLightCone SpotCone_; //!< Spot light cone angles.
dim::matrix4f ProjectionMatrix_;
bool IsVolumetric_;
bool IsShadowMapping_;
bool IsGlobalIllumination_;
SLightAttenuation Attn_;
private:
/* === Functions === */
void registerLight();
void updateProjectionMatrix();
/* === Members === */
static bool UseAllRCs_;
};
} // /namespace scene
} // /namespace sp
#endif
// ================================================================================
| 30.524476
| 133
| 0.590302
|
rontrek
|
1842df48aab0e75398e4ea449f3a5329268189d3
| 388
|
cpp
|
C++
|
if.cpp
|
yanfeng1012/CPlusPlusProgramList
|
16dae9ece99407e2213b82bf6910202f07a4b6a3
|
[
"Apache-2.0"
] | null | null | null |
if.cpp
|
yanfeng1012/CPlusPlusProgramList
|
16dae9ece99407e2213b82bf6910202f07a4b6a3
|
[
"Apache-2.0"
] | null | null | null |
if.cpp
|
yanfeng1012/CPlusPlusProgramList
|
16dae9ece99407e2213b82bf6910202f07a4b6a3
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
char ch;
int spaces, total = 0;
cin.get(ch);
while (ch != '.') {
if (ch == ' ') {
++spaces;
} else {
cout << ++ch;
}
++total;
cin.get(ch);
}
cout << spaces << " spaces, " << total;
cout << " characters total in sentence\n";
return 0;
}
| 17.636364
| 46
| 0.427835
|
yanfeng1012
|
18460dd8a23bad1b4e94b484815a94caa2881627
| 5,443
|
cc
|
C++
|
bench/add.cc
|
ajtulloch/XNNPACK
|
7e955979fd57fff70b9208b82b3bb13d971b182d
|
[
"BSD-3-Clause"
] | 1
|
2019-11-26T06:26:29.000Z
|
2019-11-26T06:26:29.000Z
|
bench/add.cc
|
Maratyszcza/XNNPACK
|
791d01da82cecbc259eb396a19822f8f6a8b8219
|
[
"BSD-3-Clause"
] | null | null | null |
bench/add.cc
|
Maratyszcza/XNNPACK
|
791d01da82cecbc259eb396a19822f8f6a8b8219
|
[
"BSD-3-Clause"
] | 1
|
2019-10-10T00:49:20.000Z
|
2019-10-10T00:49:20.000Z
|
// Copyright (c) Facebook, Inc. and its affiliates.
// All rights reserved.
//
// Copyright 2019 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <algorithm>
#include <cmath>
#include <functional>
#include <random>
#include <vector>
#include <xnnpack.h>
#include <benchmark/benchmark.h>
#include "bench/utils.h"
static void add_nc_q8(benchmark::State& state) {
const size_t batch_size = static_cast<size_t>(state.range(0));
const size_t channels = static_cast<size_t>(state.range(1));
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto u8rng = std::bind(std::uniform_int_distribution<uint8_t>(), rng);
std::vector<uint8_t> a(batch_size * channels);
std::vector<uint8_t> b(batch_size * channels);
std::vector<uint8_t> y(batch_size * channels);
std::generate(a.begin(), a.end(), std::ref(u8rng));
std::generate(b.begin(), b.end(), std::ref(u8rng));
xnn_status status = xnn_initialize();
if (status != xnn_status_success) {
state.SkipWithError("failed to initialize XNNPACK");
return;
}
xnn_operator_t add_op = nullptr;
status = xnn_create_add_nc_q8(
channels, channels /* a_stride */, channels /* b_stride */, channels /* sum_stride */,
127 /* a:zero point */, 1.0f /* a:scale */,
127 /* b:zero point */, 1.0f /* b:scale */,
127 /* y:zero point */, 1.0f /* y:scale */,
1 /* y:min */, 254 /* y:max */,
0 /* flags */, &add_op);
if (status != xnn_status_success || add_op == nullptr) {
state.SkipWithError("failed to create Q8 Add operator");
return;
}
status = xnn_setup_add_nc_q8(
add_op,
batch_size,
a.data(), b.data(), y.data(),
nullptr /* thread pool */);
if (status != xnn_status_success) {
state.SkipWithError("failed to setup Q8 Add operator");
return;
}
for (auto _ : state) {
status = xnn_run_operator(add_op, nullptr /* thread pool */);
if (status != xnn_status_success) {
state.SkipWithError("failed to run Q8 Add operator");
return;
}
}
status = xnn_delete_operator(add_op);
if (status != xnn_status_success) {
state.SkipWithError("failed to delete Q8 Add operator");
return;
}
state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency();
const size_t elements_per_iteration = batch_size * channels;
state.counters["elements"] =
benchmark::Counter(uint64_t(state.iterations()) * elements_per_iteration, benchmark::Counter::kIsRate);
const size_t bytes_per_iteration = 3 * elements_per_iteration * sizeof(uint8_t);
state.counters["bytes"] =
benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate);
}
static void add_nc_q8_inplace(benchmark::State& state) {
const size_t batch_size = static_cast<size_t>(state.range(0));
const size_t channels = static_cast<size_t>(state.range(1));
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto u8rng = std::bind(std::uniform_int_distribution<uint8_t>(), rng);
std::vector<uint8_t> a(batch_size * channels);
std::vector<uint8_t> y(batch_size * channels);
std::generate(a.begin(), a.end(), std::ref(u8rng));
xnn_status status = xnn_initialize();
if (status != xnn_status_success) {
state.SkipWithError("failed to initialize XNNPACK");
return;
}
xnn_operator_t add_op = nullptr;
status = xnn_create_add_nc_q8(
channels, channels /* a_stride */, channels /* b_stride */, channels /* sum_stride */,
127 /* a:zero point */, 1.0f /* a:scale */,
127 /* b:zero point */, 1.0f /* b:scale */,
127 /* y:zero point */, 1.0f /* y:scale */,
1 /* y:min */, 254 /* y:max */,
0 /* flags */, &add_op);
if (status != xnn_status_success || add_op == nullptr) {
state.SkipWithError("failed to create Q8 Add operator");
return;
}
status = xnn_setup_add_nc_q8(
add_op,
batch_size,
a.data(), y.data(), y.data(),
nullptr /* thread pool */);
if (status != xnn_status_success) {
state.SkipWithError("failed to setup Q8 Add operator");
return;
}
for (auto _ : state) {
status = xnn_run_operator(add_op, nullptr /* thread pool */);
if (status != xnn_status_success) {
state.SkipWithError("failed to run Q8 Add operator");
return;
}
}
status = xnn_delete_operator(add_op);
if (status != xnn_status_success) {
state.SkipWithError("failed to delete Q8 Add operator");
return;
}
state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency();
const size_t elements_per_iteration = batch_size * channels;
state.counters["elements"] =
benchmark::Counter(uint64_t(state.iterations()) * elements_per_iteration, benchmark::Counter::kIsRate);
const size_t bytes_per_iteration = 3 * elements_per_iteration * sizeof(uint8_t);
state.counters["bytes"] =
benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate);
}
static void CharacteristicArguments(benchmark::internal::Benchmark* b)
{
b->ArgNames({"N", "C"});
int32_t c = 16;
for (int32_t n = 224; n >= 7; n /= 2) {
b->Args({n * n, c});
c *= 2;
}
}
BENCHMARK(add_nc_q8)->Apply(CharacteristicArguments)->UseRealTime();
BENCHMARK(add_nc_q8_inplace)->Apply(CharacteristicArguments)->UseRealTime();
#ifndef XNNPACK_BENCHMARK_NO_MAIN
BENCHMARK_MAIN();
#endif
| 31.645349
| 107
| 0.67573
|
ajtulloch
|
184778e301bbd85ff50db12d846587406413f17e
| 207
|
cpp
|
C++
|
win64/w_pch.cpp
|
Fjellstedt/dk30
|
b9fea347620fafe2d9994b4be6e20be0b2cee6f2
|
[
"MIT"
] | null | null | null |
win64/w_pch.cpp
|
Fjellstedt/dk30
|
b9fea347620fafe2d9994b4be6e20be0b2cee6f2
|
[
"MIT"
] | null | null | null |
win64/w_pch.cpp
|
Fjellstedt/dk30
|
b9fea347620fafe2d9994b4be6e20be0b2cee6f2
|
[
"MIT"
] | null | null | null |
/* ========================================================================
$Creator: Patrik Fjellstedt $
======================================================================== */
#include "w_pch.h"
| 41.4
| 78
| 0.173913
|
Fjellstedt
|
184cfe058c3c3d71170ebad1942e2f05f49a85f1
| 20,162
|
cpp
|
C++
|
XRADGUI/Sources/GUI/MathFunctionGUI.cpp
|
Center-of-Diagnostics-and-Telemedicine/xrad
|
ec2dd3f1dcd164787e2a192cd1f2b78c3217f9ed
|
[
"BSD-3-Clause"
] | 1
|
2021-04-02T16:47:00.000Z
|
2021-04-02T16:47:00.000Z
|
XRADGUI/Sources/GUI/MathFunctionGUI.cpp
|
Center-of-Diagnostics-and-Telemedicine/xrad
|
ec2dd3f1dcd164787e2a192cd1f2b78c3217f9ed
|
[
"BSD-3-Clause"
] | null | null | null |
XRADGUI/Sources/GUI/MathFunctionGUI.cpp
|
Center-of-Diagnostics-and-Telemedicine/xrad
|
ec2dd3f1dcd164787e2a192cd1f2b78c3217f9ed
|
[
"BSD-3-Clause"
] | 3
|
2021-08-30T11:26:23.000Z
|
2021-09-23T09:39:56.000Z
|
/*
Copyright (c) 2021, Moscow Center for Diagnostics & Telemedicine
All rights reserved.
This file is licensed under BSD-3-Clause license. See LICENSE file for details.
*/
#include "pre.h"
#include "MathFunctionGUI.h"
#include "XRADGUI.h"
#include "GraphSet.h"
#include <XRADBasic/Sources/SampleTypes/HLSColorSample.h>
#include <XRADBasic/FFT1D.h>
#include <XRADGUI/Sources/GUI/DynamicDialog.h>
XRAD_BEGIN
namespace NS_DisplayMathFunctionHelpers
{
// вспомогательные процедуры получения режимов отображения
complex_function_oscillation AskOscillation()
{
return Decide(L"Choose oscillation type",
{
MakeButton(L"None", no_oscillation),
MakeButton(L"Positive", positive_oscillation),
MakeButton(L"Negative", negative_oscillation)
});
}
vector<Button<window_function_e>> CreateWindowFunctionsButtons()
{
auto window_types =
{
e_constant_window,
e_triangular_window,
e_cos2_window,
e_hamming_window,
e_nuttall_window,
e_blackman_harris_window,
e_blackman_nuttall_window,
e_flat_top_window
};
vector<Button<window_function_e>> buttons;
for(auto type: window_types)
{
buttons.push_back(MakeButton(GetWindowFunctionName(type), type));
}
return buttons;
}
//! Поворот массива с нечетным числом отсчетов считается по-разному в зависимости от того, оригинал это или спектр.
const bool preferred_data_roll_direction = false;
const bool preferred_spectrum_roll_direction = true;
void ShowWindowFunction(size_t n, window_function_e wfe, bool roll_before)
{
SafeExecute([&]()
{
ComplexFunctionF32 window_function(n, complexF32(1));
ApplyWindowFunction(window_function, wfe);
DisplayMathFunction(window_function, 0, 1,
ssprintf("Window function: %s",
EnsureType<const char*>(GetWindowFunctionName(wfe).c_str())));
if(roll_before)
{
window_function.roll_half(preferred_data_roll_direction);
DisplayMathFunction(window_function, 0, 1,
ssprintf("Window function rolled: %s",
EnsureType<const char*>(GetWindowFunctionName(wfe).c_str())));
}
});
}
// вспомогательные процедуры получения компонентов комплексной функции
ComplexFunctionF64 Derivative(const ComplexFunctionF64 &f, complex_function_oscillation osc)
{
ComplexFunctionF64 result(f.size());
for(size_t i=0; i<f.size(); ++i) result[i] = f.d_dx(i, osc);
return result;
}
RealFunctionF64 PhaseDerivative(const ComplexFunctionF64 &f, complex_function_oscillation osc)
{
size_t s = f.size();
size_t interpolation_factor = 128;
RealFunctionF64 buffer(interpolation_factor);
complexF64 previous = f.in(0, osc);
RealFunctionF64 result(s);
for(size_t i = 0; i < s; ++i)
{
for(size_t j = 0; j < interpolation_factor; ++j)
{
double x = i + double(j)/interpolation_factor;
complexF64 current = f.in(x, osc);
buffer[j] = arg(current%previous);
previous=current;
}
result[i] = AverageValue(buffer)*interpolation_factor;
}
return result;
}
RealFunctionF64 LinearMagnitude(const ComplexFunctionF64 &f)
{
RealFunctionF64 result(f.size());
CopyData(result, f, Functors::assign_f1(Functors::absolute_value()));
return result;
}
RealFunctionF64 LogMagnitude(const ComplexFunctionF64 &f, double minDB)
{
RealFunctionF64 result(f.size());
CopyData(result, f, [](double &r, const complexF64 &v) { r = cabs2(v); });
// double max_value = MaxValue(result);
auto it = result.begin();
for(size_t i=0; i<f.size(); ++it, ++i) // normalized dB's
{
double value = *it;
if(value)
{
// делалась нормировка, максимальное значение устанавливалось в 0 дБ. неинформативно.
// отменено, показывается логарифм как есть. 2016_04_11 KNS
// *it = max(10.0*log10(value/max_value), -minDB);
*it = max(10.0*log10(value), -minDB);
}
else
{
*it = -minDB;
}
}
return result;
}
// RealFunctionF64 LogMagnitudeAbs(const ComplexFunctionF64 &f, double dynamic_range_min, double dynamic_range_max)
// {
// RealFunctionF64 result(f.size());
// CopyData(result, f, cabs_functor<double, complexF64>());
//
// for(size_t i=0; i<f.size(); i++)
// {
// if(!result[i])
// result[i] = dynamic_range_min;
// else
// {
// result[i] = range(20.0*log10(result[i]), dynamic_range_min, dynamic_range_max);
// }
// }
// return result;
// }
RealFunctionF64 PhaseContinued(const ComplexFunctionF64 &f, complex_function_oscillation osc)
{
RealFunctionF64 result(PhaseDerivative(f, osc));
result[0] = arg(f[0]);
for(size_t i=1; i<f.size(); i++)
{
result[i] += result[i-1];
}
return result;
}
RealFunctionF64 PhaseCut(const ComplexFunctionF64 &f)
{
RealFunctionF64 result(f.size());
CopyData(result, f, [](double &r, const complexF64 &v) { r = arg(v); });
return result;
}
void grafreal(const RealFunctionF64 &mf, const wstring &title,
const value_legend &vlegend,
const axis_legend & xlegend,
bool b_is_stopped)
{
DataArray<double> buffer;
MakeCopy(buffer, mf, get_display_value());
GraphSet gs(title, vlegend.label, xlegend.label);
gs.AddGraphUniform(buffer, xlegend.min_value, xlegend.step, title);
gs.Display(b_is_stopped);
}
void grafc(const ComplexFunctionF64 &data, const wstring &data_title,
const value_legend &vlegend,
const axis_legend &xlegend,
bool)
{
bool upsample_fragment = false;
bool phase_radians = true;
bool phase_continuous = true;
bool log_magnitude = true;
static const double log_magnitude_dynamic_range = 2000;
bool derivative_per_samples = false;
wstring option_title = ssprintf(L"Display '%Ls'", data_title.c_str());
for (;;)
{
enum display_options
{
linear_magnitude_option,
real_option,
log_magnitude_option,
phase_cut_option,
phase_deriv_option,
roll_option,
cancel_phase_option,
spectrum_option,
polar_option,
real_imag_option,
imag_option,
magnitude_phase_option,
phase_continued_option,
derivative_option,
flip_phase_option,
cancel_magnitude_option,
fragment_option,
cancel_option
};
auto option = GetButtonDecision(option_title,
{
MakeButton(L"Linear magnitude", linear_magnitude_option),
MakeButton(L"Real part", real_option),
MakeButton(L"Log. magnitude", log_magnitude_option),
MakeButton(L"Phase cut", phase_cut_option),
MakeButton(L"Phase derivative", phase_deriv_option),
MakeButton(L"Roll data ->", roll_option),
MakeButton(L"Cancel phase ->", cancel_phase_option),
MakeButton(L"Spectrum ->", spectrum_option),
MakeButton(L"Real/Imaginary (polar)", polar_option),
MakeButton(L"Real/Imaginary", real_imag_option),
MakeButton(L"Imaginary part", imag_option),
MakeButton(L"Magnitude/Phase", magnitude_phase_option),
MakeButton(L"Phase continued", phase_continued_option),
MakeButton(L"Derivative ->", derivative_option),
MakeButton(L"Flip phase ->", flip_phase_option),
MakeButton(L"Cancel magnitude ->", cancel_magnitude_option),
MakeButton(L"Fragment ->", fragment_option),
MakeButton(L"Exit display", cancel_option)
});
if (option == cancel_option)
break;
SafeExecute([&]()
{
complex_function_oscillation phase_oscillation = no_oscillation;
switch(option)
{
case log_magnitude_option:
log_magnitude = true;
break;
case linear_magnitude_option:
log_magnitude = false;
break;
case magnitude_phase_option:
case cancel_phase_option:
log_magnitude = Decide2("Magnitude display mode", "Linear", "Log", log_magnitude? 1: 0) == 1;
break;
}
if(option == magnitude_phase_option || option == phase_cut_option ||
option == phase_continued_option || option == cancel_magnitude_option || option == phase_deriv_option)
{
switch(option)
{
case magnitude_phase_option:
case cancel_magnitude_option:
phase_continuous = Decide2("Phase compute algorithm", "Cut", "Continuous", phase_continuous? 1: 0) == 1;
break;
case phase_cut_option:
phase_continuous = false;
break;
case phase_continued_option:
phase_continuous = true;
break;
case phase_deriv_option:
derivative_per_samples = Decide2("Derivative argument", "Natural", "Sample", derivative_per_samples? 1: 0) == 1;
phase_continuous = true;
break;
};
phase_oscillation = phase_continuous ? AskOscillation() : no_oscillation;
phase_radians = Decide2("Phase units", "Degrees", "Radians", phase_radians? 1: 0) == 1;
}
if(option==derivative_option)
{
phase_oscillation = AskOscillation();
derivative_per_samples = Decide2("Derivative argument", "Natural", "Sample", derivative_per_samples? 1: 0) == 1;
}
wstring derivative_divisor_label = derivative_per_samples ? L"/sample" : wstring(L"/") + (xlegend.label.size() ? xlegend.label:L"x unit");
wstring phase_unit_label = phase_radians ? L"radians" : L"degrees";
double phase_factor = phase_radians ? 1. : 180./pi();
wstring magnitude_unit_label = log_magnitude ? L"dB" : vlegend.label;
RealFunctionF64 phase = (phase_continuous ? PhaseContinued(data, phase_oscillation) : PhaseCut(data)) * phase_factor;
RealFunctionF64 magnitude = log_magnitude ? LogMagnitude(data, log_magnitude_dynamic_range) : LinearMagnitude(data);
switch(option)
{
case magnitude_phase_option:
{
GraphSet gs(data_title, L"", xlegend.label);
gs.AddGraphUniform(phase, xlegend.min_value, xlegend.step, ssprintf(L"phase(%Ls)", phase_unit_label.c_str()));
gs.AddGraphUniform(magnitude, xlegend.min_value, xlegend.step, (magnitude_unit_label.size() ? ssprintf(L"magnitude(%Ls)", magnitude_unit_label.c_str()) : L"magnitude(linear)"));
gs.Display();
}
break;
case real_option:
{
DisplayMathFunction(real(data), xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Real part>", data_title.c_str()), vlegend.label, xlegend.label);
}
break;
case imag_option:
{
DisplayMathFunction(imag(data), xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Imaginary part>", data_title.c_str()), vlegend.label, xlegend.label);
}
break;
case linear_magnitude_option:
case log_magnitude_option:
{
wstring magnitude_title = log_magnitude ? ssprintf(L"%Ls <Log. magnitude>", data_title.c_str()) : ssprintf(L"%Ls <Linear magnitude>", data_title.c_str());
DisplayMathFunction(magnitude, xlegend.min_value, xlegend.step, magnitude_title, magnitude_unit_label, xlegend.label);
}
break;
case phase_continued_option:
case phase_cut_option:
{
DisplayMathFunction(phase, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Phase>", data_title.c_str()), phase_unit_label, xlegend.label);
}
break;
case phase_deriv_option:
{
RealFunctionF64 phase_derivative = PhaseDerivative(data, phase_oscillation) * phase_factor;
if(!derivative_per_samples)
{
phase_derivative /= xlegend.step;
}
DisplayMathFunction(phase_derivative, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Phase derivative>", data_title.c_str()), phase_unit_label + derivative_divisor_label, xlegend.label);
}
break;
case roll_option:
{
ComplexFunctionF64 rolled_data(data);
rolled_data.roll_half(preferred_data_roll_direction);
DisplayMathFunction(rolled_data, xlegend.min_value-xlegend.step*data.size()/2., xlegend.step, ssprintf(L"%Ls <Rolled>", data_title.c_str()), vlegend.label, xlegend.label);
}
break;
case spectrum_option:
{
auto dialog = DynamicDialog::OKCancelDialog::Create(L"Display spectrum options");
bool inverse_ft_direction = false;
bool roll_data_before_ft = false;
bool roll_spectrum_after_ft = false;
bool view_window_function = false;
window_function_e wfe = e_constant_window;
auto window_selection = DynamicDialog::EnumRadioButtonChoice::Create(L"Window function",
CreateWindowFunctionsButtons(),
MakeGUIValue(&wfe, saved_default_value));
auto fft_options = make_shared<DynamicDialog::ControlContainer>(DynamicDialog::Layout::Vertical);
fft_options->AddControl(make_shared<DynamicDialog::ValueCheckBox>(L"Inverse FT", SavedGUIValue(&inverse_ft_direction)));
fft_options->AddControl(make_shared<DynamicDialog::ValueCheckBox>(L"Roll before FT", SavedGUIValue(&roll_data_before_ft)));
fft_options->AddControl(make_shared<DynamicDialog::ValueCheckBox>(L"Roll after FT", SavedGUIValue(&roll_spectrum_after_ft)));
fft_options->AddControl(make_shared<DynamicDialog::ValueCheckBox>(L"View window function", SavedGUIValue(&view_window_function)));
auto layout = make_shared<DynamicDialog::ControlContainer>(DynamicDialog::Layout::Horizontal);
layout->AddControl(fft_options);
layout->AddControl(window_selection);
dialog->AddControl(layout);
dialog->Show();
if(dialog->Choice() != DynamicDialog::OKCancelDialog::Result::OK) throw canceled_operation("Show spectrum canceled");
if(view_window_function)ShowWindowFunction(data.size(), wfe, roll_data_before_ft);
ComplexFunctionF64 spectrum(data);
ApplyWindowFunction(spectrum, wfe);
if(roll_data_before_ft) spectrum.roll_half(preferred_data_roll_direction);
if(!inverse_ft_direction) FT(spectrum, ftForward);
else FT(spectrum, ftReverse);
if(roll_spectrum_after_ft) spectrum.roll_half(preferred_spectrum_roll_direction);
double dx = 2.*pi()/(xlegend.step*data.size());
double x0 = roll_spectrum_after_ft ?
-dx*(data.size()/2):
0;
wstring frequency_label(L"");
if(xlegend.label.size())
{
frequency_label = ssprintf(L"2*pi/(%Ls)", xlegend.label.c_str());
}
DisplayMathFunction(spectrum, x0, dx, ssprintf(L"%Ls <Spectrum>", data_title.c_str()), vlegend.label, frequency_label); // 2*PI
}
break;
case polar_option:
{
GraphSet gs(data_title, vlegend.label + L"<imag>", vlegend.label + L" <real>");
gs.AddGraphParametric(imag(data), real(data), ssprintf(L"%Ls <Polar>", data_title.c_str()));
gs.Display();
}
break;
case real_imag_option:
{
GraphSet gs(data_title, vlegend.label, xlegend.label);
gs.AddGraphUniform(real(data), xlegend.min_value, xlegend.step, "Real part");
gs.AddGraphUniform(imag(data), xlegend.min_value, xlegend.step, "Imag part");
gs.Display();
}
break;
case flip_phase_option:
{
ComplexFunctionF64 flipped_phase(data.size());
for(size_t i=0; i<data.size(); ++i)
{
flipped_phase[i] = i%2 ? -data[i] : data[i];
}
DisplayMathFunction(flipped_phase, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Flip phase>", data_title.c_str()), vlegend.label, xlegend.label);
}
break;
case cancel_phase_option:
{
ComplexFunctionF64 magnitude_c(magnitude);
DisplayMathFunction(magnitude_c, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Magnitude>", data_title.c_str()), vlegend.label, xlegend.label);
}
break;
case cancel_magnitude_option:
{
ComplexFunctionF64 phase_c(data.size());
for(size_t i=0; i<data.size(); i++)
{
phase_c[i] = polar(1., phase[i]);
}
DisplayMathFunction(phase_c, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Phase only>", data_title.c_str()), L"", xlegend.label);
}
break;
case derivative_option:
{
ComplexFunctionF64 derivative = Derivative(data, phase_oscillation);
if(!derivative_per_samples)
{
derivative /= xlegend.step;
}
wstring y_label_derivative = vlegend.label.size() ? vlegend.label + derivative_divisor_label : L"y unit" + derivative_divisor_label;
DisplayMathFunction(derivative, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Derivative>", data_title.c_str()), y_label_derivative, xlegend.label);
}
break;
case fragment_option:
{
double x_max = xlegend.min_value + xlegend.step*data.size();
double x_min = GetFloating("Fragment start", xlegend.min_value, xlegend.min_value, x_max);
x_max = GetFloating("Fragment end", x_max, x_min, x_max);
upsample_fragment = YesOrNo("Upsample fragment?", false);
size_t fragment_size = (x_max - x_min)/xlegend.step;
size_t fragment_start = (x_min - xlegend.min_value)/xlegend.step;
if(fragment_start + fragment_size > data.size()-1) fragment_size = data.size() - fragment_start;
if(fragment_size < 2) break;
printf("\n fragment_start = %du, fragEnd = %du, size = %du", int(fragment_start), int(fragment_start + fragment_size), int(data.size()));
ComplexFunctionF64 fragment;
size_t upsample_ratio;
if(upsample_fragment)
{
upsample_ratio = GetUnsigned("Upsample ratio", 2, 1, 1024);
complex_function_oscillation oscillation = AskOscillation();
fragment.realloc(fragment_size*upsample_ratio);
for(size_t i = 0; i < fragment_size*upsample_ratio; i++)
{
fragment[i] = data.in(fragment_start + double(i)/upsample_ratio, oscillation);
}
}
else
{
upsample_ratio = 1;
fragment.realloc(fragment_size);
std::copy(data.begin() + fragment_start, data.begin() + fragment_start+fragment_size, fragment.begin());
}
DisplayMathFunction(fragment, x_min, xlegend.step/upsample_ratio, ssprintf(L"%Ls <Fragment %g--%g>", data_title.c_str(), x_min, x_max), vlegend.label, xlegend.label);
}
break;
default:
break;
}
});
}
}
void grafrgb(const ColorFunctionF64 &data, const wstring &data_title,
const value_legend &vlegend,
const axis_legend &xlegend,
bool stop)
{
wstring option_title = ssprintf(L"Display '%Ls'",
EnsureType<const wchar_t*>(data_title.c_str()));
for (;;)
{
enum display_options
{
rgb,
red,
green,
blue,
hue,
lightness,
saturation,
cancel_option
};
auto answer = GetButtonDecision(convert_to_string(option_title),
{
MakeButton(L"RGB graph", rgb),
MakeButton(L"Red graph", red),
MakeButton(L"Green graph", green),
MakeButton(L"Blue graph", blue),
MakeButton(L"Hue graph", hue),
MakeButton(L"Lightness graph", lightness),
MakeButton(L"Saturation graph", saturation),
MakeButton(L"Exit display", cancel_option)
});
if (answer == cancel_option)
break;
switch(answer)
{
case rgb:
{
GraphSet gs(data_title, vlegend.label, xlegend.label);
gs.AddGraphUniform(data.green(), xlegend.min_value, xlegend.step, "green");
gs.AddGraphUniform(data.blue(), xlegend.min_value, xlegend.step, "blue");
gs.AddGraphUniform(data.red(), xlegend.min_value, xlegend.step, "red");
gs.Display(stop);
}
break;
case red:
DisplayMathFunction(data.red(), xlegend.min_value, xlegend.step, data_title + L" red", vlegend.label, xlegend.label, stop);
break;
case green:
DisplayMathFunction(data.green(), xlegend.min_value, xlegend.step, data_title + L" green", vlegend.label, xlegend.label, stop);
break;
case blue:
DisplayMathFunction(data.blue(), xlegend.min_value, xlegend.step, data_title + L" blue", vlegend.label, xlegend.label, stop);
break;
case hue:
{
RealFunctionF32 H;
H.MakeCopy(data, [](float &x, const HLSColorSample &s){return x=s.H;});
DisplayMathFunction(H, xlegend.min_value, xlegend.step, data_title + L" 'hue'", vlegend.label, xlegend.label, stop);
}
break;
case lightness:
{
RealFunctionF32 L;
L.MakeCopy(data, [](float &x, const HLSColorSample &s){return x=s.L;});
DisplayMathFunction(L, xlegend.min_value, xlegend.step, data_title + L" 'lightness'", vlegend.label, xlegend.label, stop);
}
break;
case saturation:
{
RealFunctionF32 S;
S.MakeCopy(data, [](float &x, const HLSColorSample &s){return x=s.S;});
DisplayMathFunction(S, xlegend.min_value, xlegend.step, data_title + L" 'saturation'", vlegend.label, xlegend.label, stop);
}
break;
}
}
}
}//namespace NS_DisplayMathFunctionHelpers
XRAD_END
| 30.828746
| 194
| 0.694624
|
Center-of-Diagnostics-and-Telemedicine
|
184e07ea0495ab0b128ff5034b7c8da951c262d2
| 1,060
|
cpp
|
C++
|
YorozuyaGSLib/source/_chat_lock_inform_zoclDetail.cpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
YorozuyaGSLib/source/_chat_lock_inform_zoclDetail.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
YorozuyaGSLib/source/_chat_lock_inform_zoclDetail.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
#include <_chat_lock_inform_zoclDetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Detail
{
Info::_chat_lock_inform_zoclsize2_ptr _chat_lock_inform_zoclsize2_next(nullptr);
Info::_chat_lock_inform_zoclsize2_clbk _chat_lock_inform_zoclsize2_user(nullptr);
int _chat_lock_inform_zoclsize2_wrapper(struct _chat_lock_inform_zocl* _this)
{
return _chat_lock_inform_zoclsize2_user(_this, _chat_lock_inform_zoclsize2_next);
};
::std::array<hook_record, 1> _chat_lock_inform_zocl_functions =
{
_hook_record {
(LPVOID)0x14011f1f0L,
(LPVOID *)&_chat_lock_inform_zoclsize2_user,
(LPVOID *)&_chat_lock_inform_zoclsize2_next,
(LPVOID)cast_pointer_function(_chat_lock_inform_zoclsize2_wrapper),
(LPVOID)cast_pointer_function((int(_chat_lock_inform_zocl::*)())&_chat_lock_inform_zocl::size)
},
};
}; // end namespace Detail
END_ATF_NAMESPACE
| 37.857143
| 110
| 0.682075
|
lemkova
|
184fea8bfef2f72570a06334c56751cda187a273
| 2,949
|
cpp
|
C++
|
NAS2D/Xml/XmlMemoryBuffer.cpp
|
Brett208/nas2d-core
|
f9506540f32d34f3c60bc83b87b34460d582ae81
|
[
"Zlib"
] | null | null | null |
NAS2D/Xml/XmlMemoryBuffer.cpp
|
Brett208/nas2d-core
|
f9506540f32d34f3c60bc83b87b34460d582ae81
|
[
"Zlib"
] | null | null | null |
NAS2D/Xml/XmlMemoryBuffer.cpp
|
Brett208/nas2d-core
|
f9506540f32d34f3c60bc83b87b34460d582ae81
|
[
"Zlib"
] | null | null | null |
// ==================================================================================
// = NAS2D
// = Copyright © 2008 - 2020 New Age Software
// ==================================================================================
// = NAS2D is distributed under the terms of the zlib license. You are free to copy,
// = modify and distribute the software under the terms of the zlib license.
// =
// = Acknowledgement of your use of NAS2D is appriciated but is not required.
// ==================================================================================
// = Originally based on TinyXML. See Xml.h for additional details.
// ==================================================================================
#include "XmlMemoryBuffer.h"
#include "XmlAttribute.h"
#include "XmlAttributeSet.h"
#include "XmlComment.h"
#include "XmlDocument.h"
#include "XmlElement.h"
#include "XmlText.h"
#include "XmlUnknown.h"
using namespace NAS2D::Xml;
inline void indent(int depth, const std::string& indent, std::string& buffer)
{
for (int i = 0; i < depth; ++i)
{
buffer += indent;
}
}
inline void line_break(const std::string& linebreak, std::string& buffer)
{
buffer += linebreak;
}
XmlMemoryBuffer::XmlMemoryBuffer() : depth(0), _indent("\t"), _lineBreak("\n")
{}
bool XmlMemoryBuffer::visitEnter(const XmlElement& element, const XmlAttribute* firstAttribute)
{
indent(depth, _indent, _buffer);
_buffer += "<";
_buffer += element.value();
for (const XmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->next())
{
_buffer += " ";
attrib->write(_buffer, 0);
}
if (!element.firstChild())
{
_buffer += " />";
line_break(_lineBreak, _buffer);
}
else
{
_buffer += ">";
line_break(_lineBreak, _buffer);
}
++depth;
return true;
}
bool XmlMemoryBuffer::visitExit(const XmlElement& element)
{
--depth;
if (element.firstChild())
{
indent(depth, _indent, _buffer);
_buffer += "</";
_buffer += element.value();
_buffer += ">";
line_break(_lineBreak, _buffer);
}
return true;
}
bool XmlMemoryBuffer::visit(const XmlText& text)
{
if (text.CDATA())
{
indent(depth, _indent, _buffer);
_buffer += "<![CDATA[";
_buffer += text.value();
_buffer += "]]>";
line_break(_lineBreak, _buffer);
}
else
{
indent(depth, _indent, _buffer);
std::string str;
_buffer += text.value();
line_break(_lineBreak, _buffer);
}
return true;
}
bool XmlMemoryBuffer::visit(const XmlComment& comment)
{
indent(depth, _indent, _buffer);
_buffer += "<!--";
_buffer += comment.value();
_buffer += "-->";
line_break(_lineBreak, _buffer);
return true;
}
bool XmlMemoryBuffer::visit(const XmlUnknown& unknown)
{
indent(depth, _indent, _buffer);
_buffer += "<";
_buffer += unknown.value();
_buffer += ">";
line_break(_lineBreak, _buffer);
return true;
}
std::size_t XmlMemoryBuffer::size()
{
return _buffer.size();
}
const std::string& XmlMemoryBuffer::buffer()
{
return _buffer;
}
| 21.215827
| 95
| 0.597491
|
Brett208
|
18510d8907f8dee50b3fec59d629ad531ad02c5a
| 8,449
|
hpp
|
C++
|
examples/pppbayestree/gpstk/FFTextStream.hpp
|
shaolinbit/minisam_lib
|
e2e904d1b6753976de1dee102f0b53e778c0f880
|
[
"BSD-3-Clause"
] | 104
|
2019-06-23T14:45:20.000Z
|
2022-03-20T12:45:29.000Z
|
examples/pppbayestree/gpstk/FFTextStream.hpp
|
shaolinbit/minisam_lib
|
e2e904d1b6753976de1dee102f0b53e778c0f880
|
[
"BSD-3-Clause"
] | 2
|
2019-06-28T08:23:23.000Z
|
2019-07-17T02:37:08.000Z
|
examples/pppbayestree/gpstk/FFTextStream.hpp
|
shaolinbit/minisam_lib
|
e2e904d1b6753976de1dee102f0b53e778c0f880
|
[
"BSD-3-Clause"
] | 28
|
2019-06-23T14:45:19.000Z
|
2022-03-20T12:45:24.000Z
|
#pragma ident "$Id$"
/**
* @file FFTextStream.hpp
* An FFStream for text files
*/
#ifndef GPSTK_FFTEXTSTREAM_HPP
#define GPSTK_FFTEXTSTREAM_HPP
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include "FFStream.hpp"
namespace gpstk
{
/** @addtogroup formattedfile */
//@{
/**
* An FFStream is meant for reading text. This also includes an
* internal line count and a read line method. When reading and
* using the formattedGetLine() call, the lineNumber automatically
* increments. However, any other read and all write calls do not
* update the line number - the derived class or programmer
* needs to make sure that the reader or writer increments
* lineNumber in these cases.
*/
class FFTextStream : public FFStream
{
public:
/// Destructor
virtual ~FFTextStream() {};
/// Default constructor
FFTextStream()
: lineNumber(0) {};
/** Common constructor.
*
* @param fn file name.
* @param mode file open mode (std::ios)
*/
FFTextStream( const char* fn,
std::ios::openmode mode=std::ios::in )
: FFStream(fn, mode), lineNumber(0)
{};
/** Common constructor.
*
* @param fn file name.
* @param mode file open mode (std::ios)
*/
FFTextStream( const std::string& fn,
std::ios::openmode mode=std::ios::in )
: FFStream( fn.c_str(), mode ), lineNumber(0)
{};
/// Overrides open to reset the line number.
virtual void open( const char* fn,
std::ios::openmode mode )
{
FFStream::open(fn, mode);
lineNumber = 0;
};
/// Overrides open to reset the line number.
virtual void open( const std::string& fn,
std::ios::openmode mode )
{
open(fn.c_str(), mode);
};
/// The internal line count. When writing, make sure
/// to increment this.
unsigned int lineNumber;
/**
* Like std::istream::getline but checks for EOF and removes '/r'.
* Also increments lineNumber. When \a expectEOF is true and EOF
* is found, an gpstk::EndOfFile exception is thrown. If
* \a expectEOF is false and an EOF is encountered, an
* gpstk::FFStreamError is thrown.
* @param line is set to the value of the line read from the file.
* @param expectEOF set true if finding EOF on this read is acceptable.
* @throw EndOfFile if \a expectEOF is true and an EOF is encountered.
* @throw FFStreamError if EOF is found and \a expectEOF is false
* @throw gpstk::StringUtils::StringException when a string error occurs
* or if any other error happens.
* @warning There is a maximum line length of 1500 characters when
* using this function.
*/
inline void formattedGetLine( std::string& line,
const bool expectEOF = false )
throw(EndOfFile, FFStreamError, gpstk::StringUtils::StringException);
protected:
/// calls FFStream::tryFFStreamGet and adds line number information
virtual void tryFFStreamGet(FFData& rec)
throw(FFStreamError, gpstk::StringUtils::StringException)
{
unsigned int initialLineNumber = lineNumber;
try
{
FFStream::tryFFStreamGet(rec);
}
catch(gpstk::Exception& e)
{
e.addText( std::string("Near file line ") +
gpstk::StringUtils::asString(lineNumber) );
lineNumber = initialLineNumber;
mostRecentException = e;
conditionalThrow();
}
};
/// calls FFStream::tryFFStreamPut and adds line number information
virtual void tryFFStreamPut(const FFData& rec)
throw(FFStreamError, gpstk::StringUtils::StringException)
{
unsigned int initialLineNumber = lineNumber;
try
{
FFStream::tryFFStreamPut(rec);
}
catch(gpstk::Exception& e)
{
e.addText( std::string("Near file line ") +
gpstk::StringUtils::asString(lineNumber) );
lineNumber = initialLineNumber;
mostRecentException = e;
conditionalThrow();
}
}
}; // End of class 'FFTextStream'
// the reason for checking ffs.eof() in the try AND catch block is
// because if the user enabled exceptions on the stream with exceptions()
// then eof could throw an exception, in which case we need to catch it
// and rethrow an EOF or FFStream exception. In any event, EndOfFile
// gets thrown whenever there's an EOF and expectEOF is true
void FFTextStream::formattedGetLine( std::string& line,
const bool expectEOF )
throw(EndOfFile, FFStreamError, gpstk::StringUtils::StringException)
{
try
{
// The following constant used to be 256, but with the change to
// RINEX3 formats the possible length of a line increased
// considerably. A RINEX3 observation file line for Galileo may
// be 1277 characters long (taking into account all the possible
// types of observations available, plus the end of line
// characters), so this constant was conservatively set to
// 1500 characters. Dagoberto Salazar.
const int MAX_LINE_LENGTH = 1500;
char templine[MAX_LINE_LENGTH + 1];
getline(templine, MAX_LINE_LENGTH);
lineNumber++;
//check if line was longer than 256 characters, if so error
if(fail() && !eof())
{
FFStreamError err("Line too long");
GPSTK_THROW(err);
}
line = templine;
gpstk::StringUtils::stripTrailing(line, '\r');
// catch EOF when stream exceptions are disabled
if ((gcount() == 0) && eof())
{
if (expectEOF)
{
EndOfFile err("EOF encountered");
GPSTK_THROW(err);
}
else
{
FFStreamError err("Unexpected EOF encountered");
GPSTK_THROW(err);
}
}
}
catch(std::exception &e)
{
// catch EOF when exceptions are enabled
if ( (gcount() == 0) && eof())
{
if (expectEOF)
{
EndOfFile err("EOF encountered");
GPSTK_THROW(err);
}
else
{
FFStreamError err("Unexpected EOF");
GPSTK_THROW(err);
}
}
else
{
FFStreamError err("Critical file error: " +
std::string(e.what()));
GPSTK_THROW(err);
} // End of 'if ( (gcount() == 0) && eof())'
} // End of 'try-catch' block
} // End of method 'FFTextStream::formattedGetLine()'
//@}
} // End of namespace gpstk
#endif // GPSTK_FFTEXTSTREAM_HPP
| 30.835766
| 79
| 0.586578
|
shaolinbit
|
4c757cadf9f87fcd5866150038316d3a5d1b37db
| 159
|
cpp
|
C++
|
source/ThreadControl.cpp
|
Gavin-Lijy/STAR
|
4571190968fc134aa4bd0d4d7065490253b1a4c5
|
[
"MIT"
] | 1,315
|
2015-01-07T02:03:15.000Z
|
2022-03-30T09:48:17.000Z
|
source/ThreadControl.cpp
|
Gavin-Lijy/STAR
|
4571190968fc134aa4bd0d4d7065490253b1a4c5
|
[
"MIT"
] | 1,429
|
2015-01-08T00:09:17.000Z
|
2022-03-31T08:12:14.000Z
|
source/ThreadControl.cpp
|
Gavin-Lijy/STAR
|
4571190968fc134aa4bd0d4d7065490253b1a4c5
|
[
"MIT"
] | 495
|
2015-01-23T20:00:45.000Z
|
2022-03-31T13:24:50.000Z
|
#include "ThreadControl.h"
ThreadControl::ThreadControl() {
chunkInN=0;
chunkOutN=0;
// chunkOutBAMposition=new uint [MAX_chunkOutBAMposition];
};
| 22.714286
| 62
| 0.72327
|
Gavin-Lijy
|
4c762507c5a648221606a37bed8ab1360f98ec9b
| 15,886
|
cpp
|
C++
|
src/det/scope.cpp
|
alta-lang/alta-core
|
290ebcd94b4b2956fd34f5cd0e516e756d4fc219
|
[
"MIT"
] | null | null | null |
src/det/scope.cpp
|
alta-lang/alta-core
|
290ebcd94b4b2956fd34f5cd0e516e756d4fc219
|
[
"MIT"
] | 6
|
2019-03-04T01:37:27.000Z
|
2019-09-07T20:12:36.000Z
|
src/det/scope.cpp
|
alta-lang/alta-core
|
290ebcd94b4b2956fd34f5cd0e516e756d4fc219
|
[
"MIT"
] | null | null | null |
#include "../../include/altacore/det/scope.hpp"
#include "../../include/altacore/det/function.hpp"
#include "../../include/altacore/det/module.hpp"
#include "../../include/altacore/det/alias.hpp"
#include "../../include/altacore/det/namespace.hpp"
#include "../../include/altacore/det/variable.hpp"
#include "../../include/altacore/det/class.hpp"
#include "../../include/altacore/util.hpp"
const AltaCore::DET::NodeType AltaCore::DET::Scope::nodeType() {
return NodeType::Scope;
};
std::shared_ptr<AltaCore::DET::Node> AltaCore::DET::Scope::clone() {
return std::make_shared<Scope>(*this);
};
std::shared_ptr<AltaCore::DET::Node> AltaCore::DET::Scope::deepClone() {
auto self = std::dynamic_pointer_cast<Scope>(clone());
self->items.clear();
for (auto& item: items) {
auto newItem = std::dynamic_pointer_cast<ScopeItem>(item->deepClone());
newItem->parentScope = self;
self->items.push_back(newItem);
}
return self;
};
auto AltaCore::DET::Scope::makeWithParentScope(std::shared_ptr<Scope> parent) -> std::shared_ptr<Scope> {
auto scope = std::make_shared<Scope>(parent);
parent->childScopes.push_back(scope);
return scope;
};
AltaCore::DET::Scope::Scope() {};
AltaCore::DET::Scope::Scope(std::shared_ptr<AltaCore::DET::Scope> _parent):
parent(_parent),
relativeID(_parent->nextChildID)
{
_parent->nextChildID++;
noRuntime = _parent->noRuntime;
};
AltaCore::DET::Scope::Scope(std::shared_ptr<AltaCore::DET::Module> _parentModule):
parentModule(_parentModule)
{};
AltaCore::DET::Scope::Scope(std::shared_ptr<AltaCore::DET::Function> _parentFunction):
parentFunction(_parentFunction)
{
if (auto parent = parentFunction.lock()->parentScope.lock()) {
noRuntime = parent->noRuntime;
}
};
AltaCore::DET::Scope::Scope(std::shared_ptr<AltaCore::DET::Namespace> _parentNamespace):
parentNamespace(_parentNamespace)
{
if (auto parent = parentNamespace.lock()->parentScope.lock()) {
noRuntime = parent->noRuntime;
}
};
AltaCore::DET::Scope::Scope(std::shared_ptr<AltaCore::DET::Class> _parentClass):
parentClass(_parentClass)
{
if (auto parent = parentClass.lock()->parentScope.lock()) {
noRuntime = parent->noRuntime;
}
};
std::vector<std::shared_ptr<AltaCore::DET::ScopeItem>> AltaCore::DET::Scope::findAll(std::string name, std::vector<std::shared_ptr<Type>> excludeTypes, bool searchParents, std::shared_ptr<Scope> originScope) {
std::vector<std::shared_ptr<ScopeItem>> results;
std::vector<std::shared_ptr<Type>> funcTypes;
std::shared_ptr<ScopeItem> first = nullptr;
bool allFunctions = true;
for (auto& item: items) {
if (item->name == name) {
if (originScope && !originScope->canSee(item)) {
continue;
}
auto trueItem = item;
while (trueItem->nodeType() == NodeType::Alias) {
trueItem = std::dynamic_pointer_cast<Alias>(item)->target;
}
if (trueItem->nodeType() != NodeType::Function || std::dynamic_pointer_cast<Function>(trueItem)->isAccessor) {
if (allFunctions && first) {
// we've already found a non-function scope item with that name
throw std::runtime_error("found non-function scope item with same name as another scope item; this is a conflict");
} else if (allFunctions && results.size() == 0) {
// we don't have a first item yet, and allFunctions is still true and there's no functions found.
// this means we found the first (and hopefully only) item
first = trueItem;
} else if (allFunctions) {
// we've found functions with that name (since `results.size() > 0` here)
throw std::runtime_error("found non-function scope item with same name as a function; this is a conflict");
}
allFunctions = false;
} else if (!allFunctions) {
// it is a function, but we already found a non-function item with that name
throw std::runtime_error("found function scope item with same name as a non-function scope item; this is a conflict");
} else {
auto type = Type::getUnderlyingType(trueItem);
bool ok = true;
if (type && excludeTypes.size() > 0) {
for (auto& excl: excludeTypes) {
if (type->isExactlyCompatibleWith(*excl)) {
ok = false;
break;
}
}
}
if (ok) {
results.push_back(trueItem);
funcTypes.push_back(type);
}
}
}
}
std::shared_ptr<Scope> parentScope = nullptr;
if (!parent.expired()) {
parentScope = parent.lock();
} else if (!parentFunction.expired() && !parentFunction.lock()->parentScope.expired()) {
parentScope = parentFunction.lock()->parentScope.lock();
} else if (!parentNamespace.expired() && !parentNamespace.lock()->parentScope.expired()) {
parentScope = parentNamespace.lock()->parentScope.lock();
} else if (!parentClass.expired() && !parentClass.lock()->parentScope.expired()) {
parentScope = parentClass.lock()->parentScope.lock();
}
if (searchParents && parentScope != nullptr && (allFunctions || !first)) {
// here, allFunctions being true means that either all the scope items found were functions
// (in which case, we're free to search for overloads in parent scopes)
// OR no items were found (which is fine, too, since we can also search parent scopes in that case)
funcTypes.insert(funcTypes.end(), excludeTypes.begin(), excludeTypes.end());
auto otherResults = parentScope->findAll(name, funcTypes);
if (otherResults.size() == 1) {
if (otherResults[0]->nodeType() == NodeType::Function) {
results.push_back(otherResults[0]);
} else if (!first) {
first = otherResults[0];
}
// otherwise, ignore the result if it's not a function
} else {
results.insert(results.end(), otherResults.begin(), otherResults.end());
}
}
if (first) {
return { first };
} else {
return results;
}
};
void AltaCore::DET::Scope::hoist(std::shared_ptr<AltaCore::DET::ScopeItem> item) {
if (auto ns = std::dynamic_pointer_cast<DET::Namespace>(item)) {
if (!ns->underlyingEnumerationType)
return;
}
if (item->nodeType() == NodeType::Type) {
auto type = std::dynamic_pointer_cast<DET::Type>(item);
if (type->name.empty()) {
if (type->isFunction) {
for (auto& param: type->parameters) {
hoist(std::get<1>(param));
}
hoist(type->returnType);
} else if (type->isUnion()) {
for (auto& member: type->unionOf) {
hoist(member);
}
} else if (type->isOptional) {
hoist(type->optionalTarget);
} else {
if (type->klass) {
hoist(type->klass);
}
return;
}
}
}
if (item->nodeType() == NodeType::Variable) {
if (auto parent = item->parentScope.lock()) {
if (auto func = Util::getFunction(parent).lock()) {
return;
} if (auto klass = parent->parentClass.lock()) {
return;
}
}
}
// this is weird, we shouldn't need this but it covers some functions being weird
if (auto func = std::dynamic_pointer_cast<Function>(item)) {
for (auto& param: func->parameters) {
if (auto type = std::get<1>(param)) {
hoist(type);
}
}
if (func->returnType) {
hoist(func->returnType);
}
}
if (auto mod = parentModule.lock()) {
mod->hoistedItems.push_back(item);
} else if (auto func = parentFunction.lock()) {
func->privateHoistedItems.push_back(item);
} else if (auto klass = parentClass.lock()) {
klass->privateHoistedItems.push_back(item);
} else if (auto ns = parentNamespace.lock()) {
if (auto scope = ns->parentScope.lock()) {
scope->hoist(item);
} else {
throw std::runtime_error("failed to hoist item anywhere");
}
} else if (auto scope = parent.lock()) {
scope->hoist(item);
} else {
throw std::runtime_error("failed to hoist item anywhere");
}
if (auto mod = Util::getModule(this).lock()) {
if (auto otherMod = Util::getModule(item->parentScope.lock().get()).lock()) {
otherMod->dependents.push_back(mod);
if (item->genericParameterCount > 0) {
mod->genericsUsed.push_back(item);
}
}
}
};
void AltaCore::DET::Scope::unhoist(std::shared_ptr<AltaCore::DET::ScopeItem> item) {
if (item->nodeType() == NodeType::Namespace) return;
if (auto mod = parentModule.lock()) {
for (size_t i = 0; i < mod->hoistedItems.size(); i++) {
if (mod->hoistedItems[i]->id == item->id) {
mod->hoistedItems.erase(mod->hoistedItems.begin() + i);
break;
}
}
} else if (auto func = parentFunction.lock()) {
for (size_t i = 0; i < func->privateHoistedItems.size(); i++) {
if (func->privateHoistedItems[i]->id == item->id) {
func->privateHoistedItems.erase(func->privateHoistedItems.begin() + i);
break;
}
}
} else if (auto klass = parentClass.lock()) {
for (size_t i = 0; i < klass->privateHoistedItems.size(); i++) {
if (klass->privateHoistedItems[i]->id == item->id) {
klass->privateHoistedItems.erase(klass->privateHoistedItems.begin() + i);
break;
}
}
} else if (auto ns = parentNamespace.lock()) {
if (auto scope = ns->parentScope.lock()) {
scope->unhoist(item);
}
} else if (auto scope = parent.lock()) {
scope->unhoist(item);
}
if (item->genericParameterCount > 0) {
if (auto mod = Util::getModule(this).lock()) {
for (size_t i = 0; i < mod->genericsUsed.size(); i++) {
if (mod->genericsUsed[i]->id == item->id) {
mod->genericsUsed.erase(mod->genericsUsed.begin() + i);
break;
}
}
}
}
};
std::shared_ptr<AltaCore::DET::Scope> AltaCore::DET::Scope::getMemberScope(std::shared_ptr<AltaCore::DET::ScopeItem> item) {
auto detType = item->nodeType();
if (detType == NodeType::Namespace) {
auto ns = std::dynamic_pointer_cast<Namespace>(item);
return ns->scope;
} else if (detType == NodeType::Function) {
auto func = std::dynamic_pointer_cast<Function>(item);
return func->scope;
} else if (detType == NodeType::Variable) {
auto var = std::dynamic_pointer_cast<Variable>(item);
if (var->type->bitfield) return var->type->bitfield->scope;
if (var->type->isNative || var->type->isUnion()) return nullptr;
return var->type->klass->scope;
}
return nullptr;
};
bool AltaCore::DET::Scope::hasParent(std::shared_ptr<Scope> lookup) const {
// `s` for `strong` (i.e. locked)
if (auto sParent = parent.lock()) {
if (sParent->id == lookup->id) return true;
return sParent->hasParent(lookup);
} else if (auto sModule = parentModule.lock()) {
return false;
} else if (auto sFunction = parentFunction.lock()) {
if (auto sParent = sFunction->parentScope.lock()) {
if (sParent->id == lookup->id) return true;
return sParent->hasParent(lookup);
}
} else if (auto sNamespace = parentNamespace.lock()) {
if (auto sParent = sNamespace->parentScope.lock()) {
if (sParent->id == lookup->id) return true;
return sParent->hasParent(lookup);
}
} else if (auto sClass = parentClass.lock()) {
if (auto sParent = sClass->parentScope.lock()) {
if (sParent->id == lookup->id) return true;
return sParent->hasParent(lookup);
}
}
return false;
};
bool AltaCore::DET::Scope::canSee(std::shared_ptr<ScopeItem> item) const {
if (item->visibility == Visibility::Private) {
auto itemScope = item->parentScope.lock();
if (itemScope && id != itemScope->id && !hasParent(itemScope)) {
return false;
}
} else if (item->visibility == Visibility::Protected) {
auto itemClass = Util::getClass(item->parentScope.lock()).lock();
auto thisClass = Util::getClass(shared_from_this()).lock();
if (!itemClass || !thisClass) {
return false;
}
if (thisClass->id != itemClass->id && !thisClass->hasParent(itemClass)) {
return false;
}
} else if (item->visibility == Visibility::Module) {
auto itemModule = Util::getModule(item->parentScope.lock().get()).lock();
auto thisModule = Util::getModule(this).lock();
if (!itemModule || !thisModule) {
return false;
}
if (itemModule->id != thisModule->id) {
return false;
}
} else if (item->visibility == Visibility::Package) {
auto itemModule = Util::getModule(item->parentScope.lock().get()).lock();
auto thisModule = Util::getModule(this).lock();
if (!itemModule || !thisModule) {
return false;
}
if (!(itemModule->packageInfo.root == thisModule->packageInfo.root)) {
return false;
}
}
return true;
};
std::weak_ptr<AltaCore::DET::Scope> AltaCore::DET::Scope::findTry() {
std::weak_ptr<AltaCore::DET::Scope> result;
if (auto scope = parent.lock()) {
if (auto func = scope->parentFunction.lock()) {
func->throws(true);
scope->isTry = true;
}
if (scope->isTry) {
result = scope;
return result;
}
return scope->findTry();
}
return result;
};
void AltaCore::DET::Scope::addPossibleError(std::shared_ptr<Type> errorType) {
if (isTry) {
typesThrown.insert(errorType);
} else if (auto func = parentFunction.lock()) {
func->throws(true);
isTry = true;
typesThrown.insert(errorType);
} else {
auto tgt = findTry().lock();
if (tgt) {
tgt->addPossibleError(errorType);
} else {
throw std::runtime_error("Couldn't annotate error anywhere!");
}
}
};
bool AltaCore::DET::Scope::contains(std::shared_ptr<ScopeItem> item) {
auto lockedParent = item->parentScope.lock();
if (!lockedParent) return false;
if (id == lockedParent->id) return true;
return lockedParent->hasParent(shared_from_this());
};
std::shared_ptr<AltaCore::DET::Function> AltaCore::DET::Scope::findParentLambda() {
if (auto func = parentFunction.lock()) {
if (func->isLambda) {
return func;
}
} else if (auto scope = parent.lock()) {
return scope->findParentLambda();
}
return nullptr;
};
std::string AltaCore::DET::Scope::toString() const {
std::string result;
result = "<scope#" + std::to_string(relativeID) + '>';
if (auto pScope = parent.lock()) {
result = pScope->toString() + result;
}
if (auto pMod = parentModule.lock()) {
result = '[' + pMod->toString() + "]." + result;
} else if (auto pFunc = parentFunction.lock()) {
auto str = pFunc->toString();
auto pos = str.find_last_of('.');
result = str.substr(0, pos) + ".[" + str.substr(pos + 1) + "]." + result;
} else if (auto pClass = parentClass.lock()) {
result = pClass->toString() + '.' + result;
} else if (auto pNamespace = parentNamespace.lock()) {
result = pNamespace->toString() + '.' + result;
}
return result;
};
std::shared_ptr<AltaCore::DET::Class> AltaCore::DET::Scope::findParentCaptureClass() {
if (auto klass = parentClass.lock()) {
if (klass->isCaptureClass()) {
return klass;
}
} else if (auto scope = parent.lock()) {
return scope->findParentCaptureClass();
} else if (auto func = parentFunction.lock()) {
if (auto scope = func->parentScope.lock()) {
return scope->findParentCaptureClass();
}
}
return nullptr;
};
auto AltaCore::DET::Scope::findClosestParentScope() -> std::shared_ptr<Scope> {
if (auto sParent = parent.lock()) {
return sParent;
} else if (auto sFunction = parentFunction.lock()) {
if (auto sParent = sFunction->parentScope.lock()) {
return sParent;
}
} else if (auto sNamespace = parentNamespace.lock()) {
if (auto sParent = sNamespace->parentScope.lock()) {
return sParent;
}
} else if (auto sClass = parentClass.lock()) {
if (auto sParent = sClass->parentScope.lock()) {
return sParent;
}
}
return nullptr;
};
| 34.534783
| 209
| 0.629422
|
alta-lang
|
4c81875806e2ac936f9db43c67ac6ff124a06eba
| 7,709
|
cxx
|
C++
|
PWGLF/STRANGENESS/Lifetimes/selectors/MiniV0efficiency.cxx
|
Tingchenxi/AliPhysics
|
16ea676341c0d417efa849673baa54bed717cd54
|
[
"BSD-3-Clause"
] | null | null | null |
PWGLF/STRANGENESS/Lifetimes/selectors/MiniV0efficiency.cxx
|
Tingchenxi/AliPhysics
|
16ea676341c0d417efa849673baa54bed717cd54
|
[
"BSD-3-Clause"
] | null | null | null |
PWGLF/STRANGENESS/Lifetimes/selectors/MiniV0efficiency.cxx
|
Tingchenxi/AliPhysics
|
16ea676341c0d417efa849673baa54bed717cd54
|
[
"BSD-3-Clause"
] | 1
|
2018-09-22T01:09:25.000Z
|
2018-09-22T01:09:25.000Z
|
#define MiniV0efficiency_cxx
#include <TGraph.h>
#include "MiniV0efficiency.h"
#include <TH2.h>
#include <TAxis.h>
#include <TStyle.h>
#include <TF1.h>
#include <AliPDG.h>
#include "MiniV0.h"
#include "MCparticle.h"
#include "HyperTriton2Body.h"
#include "Riostream.h"
using namespace Lifetimes;
using namespace std;
MiniV0efficiency::MiniV0efficiency(TTree *) :
fChain{nullptr},
fOutputFileName{"MiniV0efficiency_Acceptance.root"} {}
void MiniV0efficiency::Begin(TTree * /*tree*/) {
// The Begin() function is called at the start of the query.
// When running with PROOF Begin() is only called on the client.
// The tree argument is deprecated (on PROOF 0 is passed).
TString option = GetOption();
}
void MiniV0efficiency::SlaveBegin(TTree * /*tree*/) {
// The SlaveBegin() function is called after the Begin() function.
// When running with PROOF SlaveBegin() is called on each slave server.
// The tree argument is deprecated (on PROOF 0 is passed).
////////////////////////////////////////
TString option = GetOption();
////
////Kaon
fHistV0ptData[0] =
new TH1D("fHistV0ptDataK", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 4.);
fHistV0ptMC[0] =
new TH1D("fHistV0ptMCK", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 4.);
fHistV0ctData[0] =
new TH1D("fHistV0ctDataK", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 20.);
fHistV0ctMC[0] =
new TH1D("fHistV0ctMCK", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 20.);
ctAnalysis[0]=new TH2D("ctAnalysisK","K_ct_Analysis",40,-1.,1.,40,0.,20.);
ctAnalysis[0]->SetXTitle("ctRec-ctGen(#it{cm})");
ctAnalysis[0]->SetYTitle("ctGen(#it{cm})");
////Lambda
fHistV0ptData[1] =
new TH1D("fHistV0ptDataL", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 4.);
fHistV0ptMC[1] =
new TH1D("fHistV0ptMCL", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 4.);
fHistV0ctData[1] =
new TH1D("fHistV0ctDataL", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 40.);
fHistV0ctMC[1] =
new TH1D("fHistV0ctMCL", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 40.);
ctAnalysis[1]=new TH2D("ctAnalysisL","L_ct_Analysis",40,-1.,1.,40,0.,40.);
ctAnalysis[1]->SetXTitle("ctRec-ctGen(#it{cm})");
ctAnalysis[1]->SetYTitle("ctGen(#it{cm})");
///Hypertriton
fHistV0ptData[2] =
new TH1D("fHistV0ptDataH", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 10.);
fHistV0ptMC[2] =
new TH1D("fHistV0ptMCH", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 10.);
fHistV0ctData[2] =
new TH1D("fHistV0ctDataH", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 40.);
fHistV0ctMC[2] =
new TH1D("fHistV0ctMCH", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 40.);
ptAnalysisH = new TH2D("ptAnalysisH","H_pt_Analysis",40,-1.,1.,40,0.,10.);
ctAnalysis[2]=new TH2D("ctAnalysisH","H_ct_Analysis",40,-2.,2.,40,0.,40.);
ctAnalysis[2]->SetXTitle("ctRec-ctGen(#it{cm})");
ctAnalysis[2]->SetYTitle("ctGen(#it{cm})");
AliPDG::AddParticlesToPdgDataBase();
////
}
Bool_t MiniV0efficiency::Process(Long64_t entry) {
// The Process() function is called for each entry in the tree (or possibly
// keyed object in the case of PROOF) to be processed. The entry argument
// specifies which entry in the currently loaded tree is to be processed.
// When processing keyed objects with PROOF, the object is already loaded
// and is available via the fObject pointer.
//
// This function should contain the \"body\" of the analysis. It can contain
// simple or elaborate selection criteria, run algorithms on the data
// of the event and typically fill histograms.
//
// The processing can be stopped by calling Abort().
//
// Use fStatus to set the return value of TTree::Process().
//
// The return value is currently not used.
fReader.SetEntry(entry);
int p_vec[3]={310,3122,1010010030};
for(int i=0;i<(static_cast<int>(MCparticles.GetSize()));i++){
auto& miniMC=MCparticles[i];
if(miniMC.IsPrimary()){
int part=miniMC.GetPDGcode();
int ind=miniMC.GetRecoIndex();
for (int j=0;j<3;j++){
if(p_vec[j]==part){
float MCmass=miniMC.GetMass();
if(miniMC.GetNBodies()==2 || part!=p_vec[2]){
fHistV0ptMC[j]->Fill(miniMC.GetPt());
fHistV0ctMC[j]->Fill(MCmass*(miniMC.GetDistOverP()));
}
if(ind>=0){
if(miniMC.GetNBodies()==2 && part==p_vec[2] && miniMC.IsHyperCandidate()==true){
auto& minihyper= V0Hyper[ind];
if(minihyper.GetCandidateInvMass()!=-1){
fHistV0ptData[2]->Fill(minihyper.GetV0pt());
fHistV0ctData[2]->Fill(MCmass*(minihyper.GetDistOverP()));
ctAnalysis[2]->Fill(MCmass*(minihyper.GetDistOverP())-MCmass*(miniMC.GetDistOverP()),MCmass*(miniMC.GetDistOverP()));
ptAnalysisH->Fill(miniMC.GetPt()-minihyper.GetV0pt(),miniMC.GetPt());
}
}
else if(part!=p_vec[2] && miniMC.IsHyperCandidate()==false ){
auto& minidata= V0s[ind];
fHistV0ptData[j]->Fill(minidata.GetV0pt());
fHistV0ctData[j]->Fill(MCmass*(minidata.GetDistOverP()));
ctAnalysis[j]->Fill(MCmass*(minidata.GetDistOverP())-MCmass*(miniMC.GetDistOverP()),MCmass*(miniMC.GetDistOverP()));
}
}
}
}
}
}
return kTRUE;
}
void MiniV0efficiency::SlaveTerminate() {
// The SlaveTerminate() function is called after all entries or objects
// have been processed. When running with PROOF SlaveTerminate() is called
// on each slave server.
}
void MiniV0efficiency::Terminate() {
// The Terminate() function is the last function to be called during
// a query. It always runs on the client, it can be used to present
// the results graphically or save the results to file.
string vec[]={"K","L","H"};
for(int j=0;j<3;j++){
GetOutputList()->Add(fHistV0ptData[j]);
GetOutputList()->Add(fHistV0ptMC[j]);
GetOutputList()->Add(fHistV0ctData[j]);
GetOutputList()->Add(fHistV0ctMC[j]);
EffvsPt[j]=(TH1D*)fHistV0ptData[j]->Clone(Form("EffvsPt%s",vec[j].data()));
EffvsPt[j]->Divide(fHistV0ptMC[j]);
EffvsPt[j]->SetTitle(Form("%s",vec[j].data()));
EffvsPt[j]->SetYTitle("MiniV0efficiency x Acceptance");
GetOutputList()->Add(EffvsPt[j]);
Effvsct[j]=(TH1D*)fHistV0ctData[j]->Clone(Form("Effvsct%s",vec[j].data()));
Effvsct[j]->SetTitle(Form("%s",vec[j].data()));
Effvsct[j]->Divide(fHistV0ctMC[j]);
Effvsct[j]->SetYTitle("MiniV0efficiency x Acceptance");
GetOutputList()->Add(Effvsct[j]);
GetOutputList()->Add(ctAnalysis[j]);
}
GetOutputList()->Add(ptAnalysisH);
TFile output(Form("results/%s", fOutputFileName.data()),"RECREATE");
GetOutputList()->Write();
output.Close();
}
void MiniV0efficiency::Init(TTree *tree) {
// The Init() function is called when the selector needs to initialize
// a new tree or chain. Typically here the reader is initialized.
// It is normally not necessary to make changes to the generated
// code, but the routine can be extended by the user if needed.
// Init() will be called many times when running on PROOF
// (once per file to be processed).
fReader.SetTree(tree);
}
Bool_t MiniV0efficiency::Notify() {
// The Notify() function is called when a new file is opened. This
// can be either for a new TTree in a TChain or when when a new TTree
// is started when using PROOF. It is normally not necessary to make changes
// to the generated code, but the routine can be extended by the
// user if needed. The return value is currently not used.
return kTRUE;
}
| 35.200913
| 133
| 0.632767
|
Tingchenxi
|
4c85f35e4c49fdb180f8827821bb25dcaa73bc6a
| 357
|
cpp
|
C++
|
src/sim/missile/flight.cpp
|
Terebinth/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 117
|
2015-01-13T14:48:49.000Z
|
2022-03-16T01:38:19.000Z
|
src/sim/missile/flight.cpp
|
darongE/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 4
|
2015-05-01T13:09:53.000Z
|
2017-07-22T09:11:06.000Z
|
src/sim/missile/flight.cpp
|
darongE/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 78
|
2015-01-13T09:27:47.000Z
|
2022-03-18T14:39:09.000Z
|
#include "stdhdr.h"
#include "missile.h"
#include "drawable.h"
void MissileClass::Flight(void)
{
if (inputData->displayType not_eq DisplayHTS and display)
{
display->DisplayExit();
display = NULL;
}
Atmosphere();
FlightControlSystem();
Aerodynamics();
Engine();
Accelerometers();
EquationsOfMotion();
}
| 17.85
| 61
| 0.633053
|
Terebinth
|
4c869658add13503aa2fb39346360ba3bc499304
| 1,329
|
cpp
|
C++
|
20_Sources/IpcAdapter/Core/src/SimplePipelineFrame.cpp
|
ssproessig/ipc-adapter
|
466b9c12aa15561e75742b61b88ce5732eb505af
|
[
"MIT"
] | 1
|
2019-12-04T08:06:52.000Z
|
2019-12-04T08:06:52.000Z
|
20_Sources/IpcAdapter/Core/src/SimplePipelineFrame.cpp
|
ssproessig/ipc-adapter
|
466b9c12aa15561e75742b61b88ce5732eb505af
|
[
"MIT"
] | 16
|
2019-09-06T18:38:21.000Z
|
2019-10-20T18:34:38.000Z
|
20_Sources/IpcAdapter/Core/src/SimplePipelineFrame.cpp
|
ssproessig/ipc-adapter
|
466b9c12aa15561e75742b61b88ce5732eb505af
|
[
"MIT"
] | null | null | null |
#include "Core/api/SimplePipelineFrame.h"
#include <QByteArray>
#include <QMap>
#include <QString>
#include <QVariant>
using IpcAdapter::Core::IPipelineFrame;
using IpcAdapter::Core::SimplePipelineFrame;
struct SimplePipelineFrame::Data
{
IPipelineFrame::MetaDataMap metaData;
IPipelineFrame::RawData rawData;
};
SimplePipelineFrame::SimplePipelineFrame(): d(std::make_unique<Data>()) {}
SimplePipelineFrame::SimplePipelineFrame(IPipelineFrame::RawData const& anInitialDataBuffer)
: d(std::make_unique<Data>())
{
d->rawData = anInitialDataBuffer;
}
SimplePipelineFrame::SimplePipelineFrame
(std::shared_ptr<IPipelineFrame> const& anotherPipelineFrame)
: d(std::make_unique<Data>())
{
d->rawData = anotherPipelineFrame->getData();
d->metaData = anotherPipelineFrame->getMetaData();
}
SimplePipelineFrame::~SimplePipelineFrame() = default;
IPipelineFrame::RawData const& SimplePipelineFrame::getData() const
{
return d->rawData;
}
IPipelineFrame::MetaDataMap const& SimplePipelineFrame::getMetaData() const
{
return d->metaData;
}
void SimplePipelineFrame::setData(IPipelineFrame::RawData const& aRawDataBuffer)
{
d->rawData = aRawDataBuffer;
}
void SimplePipelineFrame::updateMetaData(QString const& aKey, QVariant const& aValue)
{
d->metaData[aKey] = aValue;
}
| 19.835821
| 92
| 0.753198
|
ssproessig
|
4c8842c49ecfa8362ef045f676e4899280e94206
| 4,443
|
cpp
|
C++
|
src/libtextmode/textmode.cpp
|
joelpob/ansilove-term
|
2842c41bc2429a98d51e02e2d6eb55254afa79bb
|
[
"BSD-3-Clause"
] | null | null | null |
src/libtextmode/textmode.cpp
|
joelpob/ansilove-term
|
2842c41bc2429a98d51e02e2d6eb55254afa79bb
|
[
"BSD-3-Clause"
] | null | null | null |
src/libtextmode/textmode.cpp
|
joelpob/ansilove-term
|
2842c41bc2429a98d51e02e2d6eb55254afa79bb
|
[
"BSD-3-Clause"
] | null | null | null |
#include "textmode.h"
#include "file_formats/ansi.h"
#include "file_formats/ansiedit.h"
#include "file_formats/artworx.h"
#include "file_formats/ascii.h"
#include "file_formats/binary_text.h"
#include "file_formats/ice_draw.h"
#include "file_formats/pc_board.h"
#include "file_formats/tundra_draw.h"
#include "file_formats/xbin.h"
#include <cstring>
textmode_t::textmode_t(const std::string& filename)
: sauce(filename)
{
this->filename = filename;
options = sauce.get_options();
if(!sauce.title.empty()) {
title = sauce.title;
}
if(!sauce.author.empty()) {
author = sauce.author;
}
if(!sauce.group.empty()) {
group = sauce.group;
}
}
inline bool extension_test(std::string& extension, const char* extension_suffix)
{
return strcasecmp(extension.c_str(), extension_suffix) == 0;
}
textmode_type_t check_extension(const std::string& filename)
{
size_t pos = filename.rfind(".");
if(pos == std::string::npos) {
return textmode_type_t::undefined;
}
std::string extension = filename.substr(pos + 1);
if(extension_test(extension, "ans")) {
return textmode_type_t::ansi;
} else if(extension_test(extension, "ansiedit")) {
return textmode_type_t::ansiedit;
} else if(extension_test(extension, "adf")) {
return textmode_type_t::artworx;
} else if(extension_test(extension, "asc") ||
extension_test(extension, "diz") ||
extension_test(extension, "nfo") ||
extension_test(extension, "txt")) {
return textmode_type_t::ascii;
} else if(extension_test(extension, "bin")) {
return textmode_type_t::binary_text;
} else if(extension_test(extension, "idf")) {
return textmode_type_t::ice_draw;
} else if(extension_test(extension, "pcb")) {
return textmode_type_t::pc_board;
} else if(extension_test(extension, "tnd")) {
return textmode_type_t::tundra_draw;
} else if(extension_test(extension, "xb")) {
return textmode_type_t::xbin;
}
return textmode_type_t::undefined;
}
textmode_t load_artwork(std::string filename)
{
auto textmode_type = check_extension(filename);
switch(textmode_type) {
case textmode_type_t::ansiedit:
return ansiedit_t(filename);
case textmode_type_t::artworx:
return artworx_t(filename);
case textmode_type_t::binary_text:
return binary_text_t(filename);
case textmode_type_t::ice_draw:
return ice_draw_t(filename);
case textmode_type_t::pc_board:
return pc_board_t(filename);
case textmode_type_t::tundra_draw:
return tundra_draw_t(filename);
case textmode_type_t::xbin:
return xbin_t(filename);
case textmode_type_t::ansi:
return ansi_t(filename);
case textmode_type_t::ascii:
return ascii_t(filename);
case textmode_type_t::undefined:
default:
throw file_format_not_recognized_t();
}
}
std::ostream& operator<<(std::ostream& ostream, const textmode_type_t& type)
{
switch(type) {
case textmode_type_t::ansi:
ostream << "ANSi";
break;
case textmode_type_t::ansiedit:
ostream << "AnsiEdit";
break;
case textmode_type_t::artworx:
ostream << "Artworx";
break;
case textmode_type_t::ascii:
ostream << "ASCii (8-Bit)";
break;
case textmode_type_t::binary_text:
ostream << "Binary Text";
break;
case textmode_type_t::ice_draw:
ostream << "Ice Draw";
break;
case textmode_type_t::pc_board:
ostream << "PC Board";
break;
case textmode_type_t::tundra_draw:
ostream << "Tundra Draw";
break;
case textmode_type_t::xbin:
ostream << "XBIN";
break;
case textmode_type_t::undefined:
ostream << "Undefined";
break;
}
return ostream;
}
std::ostream& operator<<(std::ostream& ostream, textmode_t& artwork)
{
ostream << " Columns: " << artwork.image_data.columns << std::endl;
ostream << " Rows: " << artwork.image_data.rows << std::endl;
ostream << " Type: " << artwork.type << std::endl;
ostream << " Title: " << artwork.title << std::endl;
ostream << " Author: " << artwork.author << std::endl;
ostream << " Group: " << artwork.group << std::endl;
return ostream;
}
| 30.854167
| 80
| 0.635607
|
joelpob
|
4c889cd5d67439f9e8986c192c2f06c0adc81485
| 26
|
cpp
|
C++
|
source/pch/stdafx.cpp
|
chillpert/renderer
|
9c953cef10ebec7a2c8fe5763a2c10105729deab
|
[
"Zlib"
] | 2
|
2020-11-18T18:20:12.000Z
|
2020-12-18T19:24:00.000Z
|
source/pch/stdafx.cpp
|
chillpert/rayex
|
9c953cef10ebec7a2c8fe5763a2c10105729deab
|
[
"Zlib"
] | null | null | null |
source/pch/stdafx.cpp
|
chillpert/rayex
|
9c953cef10ebec7a2c8fe5763a2c10105729deab
|
[
"Zlib"
] | null | null | null |
#include "pch/stdafx.hpp"
| 13
| 25
| 0.730769
|
chillpert
|
4c8bbaf097e4c8fad91a90bf07dc5236a213b0d7
| 8,009
|
hpp
|
C++
|
Source/AllProjects/SecureUtils/CIDCrypto/CIDCrypto_BlockEncrypt.hpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | 216
|
2019-03-09T06:41:28.000Z
|
2022-02-25T16:27:19.000Z
|
Source/AllProjects/SecureUtils/CIDCrypto/CIDCrypto_BlockEncrypt.hpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | 9
|
2020-09-27T08:00:52.000Z
|
2021-07-02T14:27:31.000Z
|
Source/AllProjects/SecureUtils/CIDCrypto/CIDCrypto_BlockEncrypt.hpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | 29
|
2019-03-09T10:12:24.000Z
|
2021-03-03T22:25:29.000Z
|
//
// FILE NAME: CIDCrypto_BlockEncrypt.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 10/21/1997
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the abstract base class TBlockEncrypter, which is
// the base abstraction for all block based encryption schemes. This allows
// many different block encryption schemes to be manipulated via this basic
// interface.
//
// Actually most of the work is done here. The derived classes just have
// to provide the basic ability to encrypt/decrypt blocks of data upon our
// request. We handle the various block encryption modes for them. This is
// slower, but drastically reduces the likelihood of error.
//
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TBlockEncrypter
// PREFIX: cryp
// ---------------------------------------------------------------------------
class CIDCRYPTEXP TBlockEncrypter : public TObject
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TBlockEncrypter() = delete;
TBlockEncrypter(const TBlockEncrypter&) = delete;
~TBlockEncrypter();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TBlockEncrypter& operator=(const TBlockEncrypter&) = delete;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TCard4 c4BlockSize() const
{
return m_c4BlockSize;
}
tCIDLib::TCard4 c4Decrypt
(
const TMemBuf& mbufCypher
, TMemBuf& mbufPlain
, const tCIDLib::TCard4 c4CypherBytes
, const tCIDLib::TCard1* const pc1IV = nullptr
);
tCIDLib::TCard4 c4Decrypt
(
const tCIDLib::TCard1* const pc1Cypher
, TMemBuf& mbufPlain
, const tCIDLib::TCard4 c4CypherBytes
, const tCIDLib::TCard1* const pc1IV = nullptr
);
tCIDLib::TCard4 c4Decrypt
(
const TMemBuf& mbufCypher
, TString& strPlain
, const tCIDLib::TCard4 c4CypherBytes
, const tCIDLib::TCard1* const pc1IV = nullptr
);
tCIDLib::TCard4 c4Decrypt
(
const tCIDLib::TCard1* const pc1Cypher
, tCIDLib::TCard1* const pc1Plain
, const tCIDLib::TCard4 c4CypherBytes
, const tCIDLib::TCard4 c4MaxOutBytes
, const tCIDLib::TCard1* const pc1IV = nullptr
);
tCIDLib::TCard4 c4Encrypt
(
const TMemBuf& mbufPlain
, TMemBuf& mbufCypher
, const tCIDLib::TCard4 c4PlainBytes
, const tCIDLib::TCard1* const pc1IV = nullptr
);
tCIDLib::TCard4 c4Encrypt
(
const tCIDLib::TCard1* const pc1Plain
, TMemBuf& mbufCypher
, const tCIDLib::TCard4 c4PlainBytes
, const tCIDLib::TCard1* const pc1IV = nullptr
);
tCIDLib::TCard4 c4Encrypt
(
const TString& strPlain
, TMemBuf& mbufCypher
, const tCIDLib::TCard1* const pc1IV = nullptr
);
tCIDLib::TCard4 c4Encrypt
(
const tCIDLib::TCard1* const pc1Plain
, tCIDLib::TCard1* const pc1Cypher
, const tCIDLib::TCard4 c4PlainBytes
, const tCIDLib::TCard4 c4MaxOutBytes
, const tCIDLib::TCard1* const pc1IV = nullptr
);
tCIDCrypto::EBlockModes eMode() const;
tCIDCrypto::EBlockModes eMode
(
const tCIDCrypto::EBlockModes eNewMode
);
tCIDLib::TVoid Reset();
protected :
// -------------------------------------------------------------------
// Hidden constructors and operators
// -------------------------------------------------------------------
TBlockEncrypter
(
const tCIDLib::TCard4 c4BlockSize
, const tCIDCrypto::EBlockModes eMode
);
// -------------------------------------------------------------------
// Protected, virtual methods
// -------------------------------------------------------------------
virtual tCIDLib::TVoid DecryptImpl
(
const tCIDLib::TCard1* const pc1Cypher
, tCIDLib::TCard1* const pc1Plain
) = 0;
virtual tCIDLib::TVoid EncryptImpl
(
const tCIDLib::TCard1* const pc1Plain
, tCIDLib::TCard1* const pc1CypherBuf
) = 0;
virtual tCIDLib::TVoid ResetImpl() = 0;
// -------------------------------------------------------------------
// Protected, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TCard4 c4ECBDecrypt
(
const tCIDLib::TCard1* const pc1Cypher
, const tCIDLib::TCard4 c4CypherBytes
, TMemBuf& mbufPlainBuf
);
tCIDLib::TCard4 c4ECBEncrypt
(
const tCIDLib::TCard1* const pc1Plain
, const tCIDLib::TCard4 c4PlainBytes
, TMemBuf& mbufCypherBuf
);
tCIDLib::TCard4 c4CBCDecrypt
(
const tCIDLib::TCard1* const pc1Cypher
, const tCIDLib::TCard4 c4CypherBytes
, TMemBuf& mbufPlainBuf
, const tCIDLib::TCard1* const pac1IV
);
tCIDLib::TCard4 c4CBCEncrypt
(
const tCIDLib::TCard1* const pc1Plain
, const tCIDLib::TCard4 c4PlainBytes
, TMemBuf& mbufCypherBuf
, const tCIDLib::TCard1* const pc1IV
);
tCIDLib::TCard4 c4OFBProcess
(
const tCIDLib::TCard1* const pc1Input
, const tCIDLib::TCard4 c4InputBytes
, TMemBuf& mbufOut
, const tCIDLib::TCard1* const pc1IV
);
private :
// -------------------------------------------------------------------
// Private data members
//
// m_c4BlockSize
// The block size used by the derived class. It is passed to the
// protected constructor by the derived class and we just store
// it and provide access to it.
//
// m_eMode
// The block encryption mode to use.
// -------------------------------------------------------------------
tCIDLib::TCard4 m_c4BlockSize;
tCIDCrypto::EBlockModes m_eMode;
// -------------------------------------------------------------------
// Do any needed magic macros
// -------------------------------------------------------------------
RTTIDefs(TBlockEncrypter,TObject)
};
#pragma CIDLIB_POPPACK
| 33.095041
| 78
| 0.443251
|
MarkStega
|
4c8c3eacfd4266cf60ba08a480bd518f47e422ac
| 266
|
hpp
|
C++
|
Code/Class_headers/Collision.hpp
|
EnderRayquaza/DeltaEngine
|
1f1c456d221c27e1a6e49095fe2819dca7994f13
|
[
"MIT"
] | 2
|
2021-10-16T22:37:03.000Z
|
2021-11-08T21:46:27.000Z
|
Code/Class_headers/Collision.hpp
|
EnderRayquaza/DeltaEngine
|
1f1c456d221c27e1a6e49095fe2819dca7994f13
|
[
"MIT"
] | null | null | null |
Code/Class_headers/Collision.hpp
|
EnderRayquaza/DeltaEngine
|
1f1c456d221c27e1a6e49095fe2819dca7994f13
|
[
"MIT"
] | 2
|
2021-11-13T10:48:38.000Z
|
2021-11-13T10:50:14.000Z
|
#pragma once
#include "../config.hpp"
namespace DeltaEngine
{
enum class moveType
{
Static,
Kinematic,
Dynamic
};
enum class collisionType
{
Nothing,
Decor,
Ground,
ObjectA,
ObjectB
};
typedef std::vector<collisionType> collisionTargets;
}
| 11.083333
| 53
| 0.691729
|
EnderRayquaza
|
4c8cf098b8628b570079b11ae7da2495560f2084
| 2,336
|
cpp
|
C++
|
GenesisX/dsa1Engine/Bullet.cpp
|
mray2014/GenesisX
|
5bede0340c4c44f7217d4ffe1bde7e879aedfe2d
|
[
"MIT"
] | null | null | null |
GenesisX/dsa1Engine/Bullet.cpp
|
mray2014/GenesisX
|
5bede0340c4c44f7217d4ffe1bde7e879aedfe2d
|
[
"MIT"
] | null | null | null |
GenesisX/dsa1Engine/Bullet.cpp
|
mray2014/GenesisX
|
5bede0340c4c44f7217d4ffe1bde7e879aedfe2d
|
[
"MIT"
] | null | null | null |
#include "Bullet.h"
#include "Renderer.h"
Bullet::Bullet()
{
}
Bullet::Bullet(float s, std::string file, Renderer* r)
{
speed = s;
glm::vec3 camPos = ((Renderer*)r)->cam->camCenter;
glm::vec3 foward = ((Renderer*)r)->cam->foward;
glm::vec4 color = glm::vec4(glm::normalize(glm::vec3(Engine::Random(), Engine::Random(), Engine::Random())), 1);
bulletTime = 0.0f;
bulletLifeSpan = 3.0f;
bulletModel = new GameEntity("my bullet",file,Mesh::SingleMesh, "",r);
bulletLight = new Light("my bullet light", 1.0, camPos, glm::vec3(0, 0, 0), r);
r->RemoveFromRenderer(bulletLight->sphere->rendID);
bulletLight->myLight.color = color;
bulletModel->SetTag("Bullet");
bulletModel->Translate(camPos);
bulletModel->color = color;
bulletModel->applyGrav = true;
bulletModel->ApplyForce(foward * (glm::vec3(1)*speed));
}
Bullet::Bullet(float s, Mesh &myMesh, Renderer* r)
{
speed = s;
glm::vec3 camPos = ((Renderer*)r)->cam->camCenter;
glm::vec3 foward = ((Renderer*)r)->cam->foward;
glm::vec4 color = glm::vec4(glm::normalize(glm::vec3(Engine::Random(), Engine::Random(), Engine::Random())), 1);
bulletTime = 0.0f;
bulletLifeSpan = 3.0f;
bulletModel = new GameEntity("my bullet", myMesh, r);
bulletLight = new Light("my bullet light", 1.0, camPos, glm::vec3(0, 0, 0), r);
r->RemoveFromRenderer(bulletLight->sphere->rendID);
bulletLight->myLight.color = color;
bulletModel->SetTag("Bullet");
bulletModel->Translate(camPos + foward);
//bulletModel->ridgidBody.mass = 0.5f;
bulletModel->color = color;
//bulletModel->applyGrav = true;
bulletModel->ApplyForce(foward * (glm::vec3(1)*speed));
}
Bullet::~Bullet()
{
//if (bulletModel != nullptr) { delete bulletModel; bulletModel = nullptr; }
//if (bulletLight != nullptr) { delete bulletLight; bulletLight = nullptr; }
}
void Bullet::Update()
{
bulletModel->Update();
//printf("x: %.3f, y: %.3f, z: %.3f\n", bulletModel->ridgidBody.velocity.x, bulletModel->ridgidBody.velocity.y, bulletModel->ridgidBody.velocity.z);
//bulletLight->myLight.lightPos = bulletModel->transform.position;
//bulletLight->sphere->transform.position = bulletModel->transform.position;
//bulletLight->sphere->SetWorldPos();
bulletLight->Move(bulletModel->ridgidBody.velocity);
bulletTime += Engine::time.dt;
if (bulletTime > bulletLifeSpan) {
destroyBullet = true;
}
}
| 29.948718
| 149
| 0.693065
|
mray2014
|
4c923e6a432823beda6c4a28a439b548a343fbeb
| 514
|
hpp
|
C++
|
code/src/mupen64plus-rsp-paraLLEl/debug_jit.hpp
|
OotinnyoO1/N64Wasm
|
1cc12b643e5f4a3ea8f499d21f08723cdf1d6c4b
|
[
"MIT"
] | 335
|
2021-10-16T14:56:14.000Z
|
2022-03-31T15:50:11.000Z
|
code/src/mupen64plus-rsp-paraLLEl/debug_jit.hpp
|
OotinnyoO1/N64Wasm
|
1cc12b643e5f4a3ea8f499d21f08723cdf1d6c4b
|
[
"MIT"
] | 10
|
2021-11-09T19:20:34.000Z
|
2022-03-14T13:17:47.000Z
|
code/src/mupen64plus-rsp-paraLLEl/debug_jit.hpp
|
OotinnyoO1/N64Wasm
|
1cc12b643e5f4a3ea8f499d21f08723cdf1d6c4b
|
[
"MIT"
] | 29
|
2021-10-19T00:38:18.000Z
|
2022-03-31T19:03:47.000Z
|
#ifndef DEBUG_JIT_HPP__
#define DEBUG_JIT_HPP__
#include <memory>
#include <stdint.h>
#include <string>
#include <unordered_map>
namespace JIT
{
using Func = void (*)(void *, void *);
class DebugBlock
{
public:
DebugBlock(const std::unordered_map<std::string, uint64_t> &symbol_table);
~DebugBlock();
bool compile(uint64_t hash, const std::string &source);
Func get_func() const
{
return block;
}
private:
struct Impl;
std::unique_ptr<Impl> impl;
Func block = nullptr;
};
} // namespace JIT
#endif
| 16.0625
| 75
| 0.715953
|
OotinnyoO1
|
4c94a5851eaf7f12aba8316d5fa94c19056a780c
| 2,074
|
cpp
|
C++
|
Gogaman/src/Platform/Vulkan/RenderHardwareInterface/VulkanDescriptorGroupLayout.cpp
|
FeodorVolguine/Gogaman
|
fb29d7f7924fecb5a31b04e8187689ecef46d347
|
[
"Apache-2.0"
] | null | null | null |
Gogaman/src/Platform/Vulkan/RenderHardwareInterface/VulkanDescriptorGroupLayout.cpp
|
FeodorVolguine/Gogaman
|
fb29d7f7924fecb5a31b04e8187689ecef46d347
|
[
"Apache-2.0"
] | null | null | null |
Gogaman/src/Platform/Vulkan/RenderHardwareInterface/VulkanDescriptorGroupLayout.cpp
|
FeodorVolguine/Gogaman
|
fb29d7f7924fecb5a31b04e8187689ecef46d347
|
[
"Apache-2.0"
] | 1
|
2020-05-02T19:25:44.000Z
|
2020-05-02T19:25:44.000Z
|
#include "pch.h"
#include "VulkanDescriptorGroupLayout.h"
#include "Gogaman/RenderHardwareInterface/Device.h"
namespace Gogaman
{
namespace RHI
{
DescriptorGroupLayout::DescriptorGroupLayout(const uint32_t bindingCount, Binding *bindings, const Shader::StageFlag shaderVisibilityFlags)
: AbstractDescriptorGroupLayout(bindingCount, bindings, shaderVisibilityFlags)
{
GM_DEBUG_ASSERT(m_BindingCount, "Failed to construct descriptor group layout | Invalid bindings");
VkDescriptorSetLayoutBinding *descriptorSetLayoutBindingDescriptors = new VkDescriptorSetLayoutBinding[m_BindingCount];
for(uint32_t i = 0; i < m_BindingCount; i++)
{
const auto &binding = m_Bindings[i];
descriptorSetLayoutBindingDescriptors[i] = {};
descriptorSetLayoutBindingDescriptors[i].binding = i;
descriptorSetLayoutBindingDescriptors[i].descriptorType = DescriptorHeap::GetNativeType(binding.type);
descriptorSetLayoutBindingDescriptors[i].descriptorCount = binding.descriptorCount;
descriptorSetLayoutBindingDescriptors[i].stageFlags = Shader::GetNativeStageFlags(m_ShaderVisibilityFlags);
descriptorSetLayoutBindingDescriptors[i].pImmutableSamplers = nullptr;
}
VkDescriptorSetLayoutCreateInfo descriptorSetLayoutDescriptor = {};
descriptorSetLayoutDescriptor.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
descriptorSetLayoutDescriptor.bindingCount = m_BindingCount;
descriptorSetLayoutDescriptor.pBindings = descriptorSetLayoutBindingDescriptors;
if(vkCreateDescriptorSetLayout(g_Device->GetNativeData().vulkanDevice, &descriptorSetLayoutDescriptor, nullptr, &m_NativeData.vulkanDescriptorSetLayout) != VK_SUCCESS)
GM_DEBUG_ASSERT(false, "Failed to construct descriptor group layout | Failed to create Vulkan descriptor set");
delete[] descriptorSetLayoutBindingDescriptors;
}
DescriptorGroupLayout::~DescriptorGroupLayout()
{
vkDestroyDescriptorSetLayout(g_Device->GetNativeData().vulkanDevice, m_NativeData.vulkanDescriptorSetLayout, nullptr);
}
}
}
| 47.136364
| 170
| 0.804243
|
FeodorVolguine
|
4c983eb39f3003249805a1b1ba90e527c274b912
| 10,405
|
cpp
|
C++
|
src/cruxhom.cpp
|
Junology/khover
|
1970689d4505ddd0887ec4f44888f91af816eae0
|
[
"BSD-2-Clause"
] | 2
|
2021-05-19T06:48:04.000Z
|
2021-05-19T06:50:39.000Z
|
src/cruxhom.cpp
|
Junology/khover
|
1970689d4505ddd0887ec4f44888f91af816eae0
|
[
"BSD-2-Clause"
] | null | null | null |
src/cruxhom.cpp
|
Junology/khover
|
1970689d4505ddd0887ec4f44888f91af816eae0
|
[
"BSD-2-Clause"
] | null | null | null |
/*!
* \file cruxhom.hpp
* \author Jun Yoshida
* \copyright (c) 2020 Jun Yoshida.
* The project is released under the 2-clause BSD License.
* \date August, 2020: created
*/
#include <thread>
#include "states.hpp"
#include "khovanov.hpp"
#include "enhancements.hpp"
#include "debug/debug.hpp"
using namespace khover;
using matrix_t = ChainIntegral::matrix_t;
//! Provide zero map for cubes
//! \param cube_dom The domain cube.
//! \param cube_cod The codomain cube.
//! \pre cube_dom.dim() == cube_cod.dim()
template <template <class...> class C1, template <class...> class C2>
static
std::vector<matrix_t>
zero_on_cubes(
Cube<C1> const& cube_dom,
std::vector<EnhancementProperty> enhprop_dom,
Cube<C2> const& cube_cod,
std::vector<EnhancementProperty> enhprop_cod
) noexcept
{
auto mindeg = std::min(cube_dom.mincohdeg(), cube_cod.mincohdeg());
auto maxdeg = std::max(cube_dom.maxcohdeg(), cube_cod.maxcohdeg());
std::vector<matrix_t> homs{};
for(auto i = maxdeg; i >= mindeg; --i) {
std::size_t rk_cod, rk_dom;
if(i >= cube_dom.mincohdeg() && i <= cube_dom.maxcohdeg()) {
std::size_t maxst_dom = cube_dom.maxState(
i-cube_dom.mincohdeg()).to_ulong();
rk_dom = enhprop_dom[maxst_dom].headidx
+ binom(cube_dom[maxst_dom].ncomp, enhprop_dom[maxst_dom].xcnt);
}
else
rk_dom = 0;
if(i >= cube_cod.mincohdeg() && i <= cube_cod.maxcohdeg()) {
std::size_t maxst_cod = cube_cod.maxState(
i-cube_cod.mincohdeg()).to_ulong();
rk_cod = enhprop_cod[maxst_cod].headidx
+ binom(cube_cod[maxst_cod].ncomp, enhprop_cod[maxst_cod].xcnt);
}
else
rk_cod = 0;
homs.push_back(matrix_t::Zero(rk_cod, rk_dom));
}
return homs;
}
/*****************
*** Morphisms ***
*****************/
//! The chain contratcion theta
template<template <class...> class C1, template <class...> class C2>
static
ChainIntegral::Hom
theta(
LinkDiagram diagram,
std::size_t dblpt,
Cube<C1> const& cube_dom,
std::vector<EnhancementProperty> enhprop_dom,
Cube<C2> const& cube_cod,
std::vector<EnhancementProperty> enhprop_cod
) noexcept
{
std::vector<matrix_t> homs = zero_on_cubes(
cube_dom, enhprop_dom, cube_cod, enhprop_cod);
for(std::size_t st = 0; st < cube_dom.size(); ++st) {
auto urcomp_dom = cube_dom[st].arccomp[diagram.getURArc(dblpt)];
auto dlcomp_dom = cube_dom[st].arccomp[diagram.getDLArc(dblpt)];
auto urcomp_cod = cube_cod[st].arccomp[diagram.getURArc(dblpt)];
auto dlcomp_cod = cube_cod[st].arccomp[diagram.getDLArc(dblpt)];
auto rk = binom(cube_dom[st].ncomp, enhprop_dom[st].xcnt);
for(std::size_t e = 0; e < rk; ++e) {
auto enh = std::make_optional<enhancement_t>(
bitsWithPop<max_components>(
enhprop_dom[st].xcnt, e)
);
// eta \circ epsilon
if(urcomp_dom != dlcomp_dom && urcomp_cod != dlcomp_cod) {
if (enh->test(urcomp_dom))
enh->set(urcomp_dom,false);
else
enh.reset();
}
// eta
else if (urcomp_dom == dlcomp_dom && urcomp_cod != dlcomp_cod) {
bool aux = enh->test(urcomp_dom);
*enh = insertBit(
*enh,
urcomp_dom == urcomp_cod ? dlcomp_cod : urcomp_cod,
false);
enh->set(dlcomp_cod, aux);
enh->set(urcomp_cod, false);
}
// epsilon
else if (urcomp_dom != dlcomp_dom && urcomp_cod == dlcomp_cod) {
if (enh->test(urcomp_dom))
*enh = purgeBit(
*enh,
urcomp_dom == urcomp_cod ? dlcomp_cod : urcomp_cod
);
else
enh.reset();
}
// Write
if(enh) {
auto e_cod = bitsIndex(*enh);
homs[state_t{st}.count()].coeffRef(
enhprop_cod[st].headidx + e_cod,
enhprop_dom[st].headidx + e
) = 1;
}
}
}
return ChainIntegral::Hom(-1,std::move(homs));
}
// Compute the morphism PhiHat.
std::optional<ChainIntegral::Hom>
khover::crossPhiHat(
LinkDiagram const& diagram,
std::size_t crossing,
SmoothCube const& cube_neg,
std::vector<EnhancementProperty> const& enhprop_neg,
SmoothCube const& cube_pos,
std::vector<EnhancementProperty> const& enhprop_pos
) noexcept
{
std::vector<matrix_t> homs
= zero_on_cubes(cube_neg, enhprop_neg, cube_pos, enhprop_pos);
std::size_t nstates = 1u << (cube_neg.dim()-1);
for(std::size_t st = 0; st < nstates; ++st) {
auto stbit_neg = insertBit(state_t{st}, crossing, true);
auto stbit_pos = insertBit(state_t{st}, crossing, false);
std::size_t st_neg = stbit_neg.to_ulong();
std::size_t st_pos = stbit_pos.to_ulong();
auto urcomp_neg = cube_neg[st_neg].arccomp[diagram.getURArc(crossing)];
auto dlcomp_neg = cube_neg[st_neg].arccomp[diagram.getDLArc(crossing)];
// Skip the cases where the double point is adjacent to a single component.
if (urcomp_neg == dlcomp_neg)
continue;
// Compute the coefficients of the matrix.
auto rk = binom(cube_neg[st_neg].ncomp, enhprop_neg[st_neg].xcnt);
for(std::size_t e = 0; e < rk; ++e) {
auto enh = bitsWithPop<max_components>(enhprop_neg[st_neg].xcnt, e);
// 1⊗1 -> 1⊗x - x⊗1
if(!enh.test(urcomp_neg) && !enh.test(dlcomp_neg)) {
// 1*x
enh.set(urcomp_neg);
homs[cube_pos.dim()-stbit_pos.count()].coeffRef(
enhprop_pos[st_pos].headidx + bitsIndex(enh),
enhprop_neg[st_neg].headidx + e
) = 1;
enh.set(urcomp_neg, false);
enh.set(dlcomp_neg);
// -x⊗1
enh.set(dlcomp_neg);
homs[cube_pos.dim()-stbit_pos.count()].coeffRef(
enhprop_pos[st_pos].headidx + bitsIndex(enh),
enhprop_neg[st_neg].headidx + e
) = -1;
}
// x⊗1 -> x⊗x
else if(!enh.test(urcomp_neg)) {
enh.set(urcomp_neg);
homs[cube_pos.dim()-stbit_pos.count()].coeffRef(
enhprop_pos[st_pos].headidx + bitsIndex(enh),
enhprop_neg[st_neg].headidx + e
) = 1;
}
// 1⊗x -> -x⊗x
else if(!enh.test(dlcomp_neg)) {
enh.set(dlcomp_neg);
homs[cube_pos.dim()-stbit_pos.count()].coeffRef(
enhprop_pos[st_pos].headidx + bitsIndex(enh),
enhprop_neg[st_neg].headidx + e
) = -1;
}
// x*x -> 0; omitted.
}
}
return ChainIntegral::Hom(
-cube_pos.maxcohdeg(),
std::move(homs));
}
std::optional<ChainIntegral::Hom>
khover::cruxXi(
LinkDiagram const& diagram,
CruxCube const& cubeCrx,
LinkDiagram const& diagV,
SmoothCube const& cubeV,
LinkDiagram const& diagW,
SmoothCube const& cubeW,
std::size_t dblpt,
int qdeg
) noexcept
{
std::optional<ChainIntegral> chV_neg, chV_pos, chW_neg, chW_pos;
std::optional<std::vector<EnhancementProperty>> propC_dom, propC_cod;
std::optional<std::vector<EnhancementProperty>> propV_neg, propV_pos;
std::optional<std::vector<EnhancementProperty>> propW_neg, propW_pos;
// Compute Khovanov homologies.
{
std::thread thC(
[&diagram, &cubeCrx, &propC_dom, &propC_cod, dblpt, q=qdeg]() {
propC_dom = get_enhancement_prop(
diagram, cubeCrx,
diagram.getSign(dblpt) > 0 ? q-2 : q-4);
propC_cod = get_enhancement_prop(
diagram, cubeCrx,
diagram.getSign(dblpt) > 0 ? q+4 : q+2);
});
std::thread thV_neg(
[&diagV, &cubeV, &chV_neg, &propV_neg, q=qdeg]() {
propV_neg = get_enhancement_prop(diagV, cubeV, q+1);
if(propV_neg)
chV_neg = khChain(diagV, cubeV, *propV_neg);
});
std::thread thV_pos(
[&diagV, &cubeV, &chV_pos, &propV_pos, q=qdeg]() {
propV_pos = get_enhancement_prop(diagV, cubeV, q-1);
if(propV_pos)
chV_pos = khChain(diagV, cubeV, *propV_pos);
});
std::thread thW_neg(
[&diagW, &cubeW, &chW_neg, &propW_neg, q=qdeg]() {
propW_neg = get_enhancement_prop(diagW, cubeW, q+2);
if(propW_neg)
chW_neg = khChain(diagW, cubeW, *propW_neg);
});
std::thread thW_pos(
[&diagW, &cubeW, &chW_pos, &propW_pos, q=qdeg]() {
propW_pos = get_enhancement_prop(diagW, cubeW, q-2);
if(propW_pos)
chW_pos = khChain(diagW, cubeW, *propW_pos);
});
thC.join();
thV_neg.join();
thV_pos.join();
thW_neg.join();
thW_pos.join();
}
if(!propC_dom || !propC_cod
|| !propV_neg || !chV_neg || !propV_pos || !chV_pos
|| !propW_neg || !chW_neg || !propW_pos || !chW_pos
)
{
return std::nullopt;
}
ChainIntegral::Hom result = theta(
diagram, dblpt,
cubeW, *propW_neg,
cubeCrx, *propC_cod) << 3;
result *= chW_neg->diffAsHom() << 2;
result *= theta(diagram, dblpt, cubeV, *propV_neg, cubeW, *propW_neg) << 2;
result *= chV_neg->diffAsHom() << 1;
result *= theta(diagram, dblpt, cubeV, *propV_pos, cubeV, *propV_neg) << 1;
result *= chV_pos->diffAsHom();
result *= theta(diagram, dblpt, cubeW, *propW_pos, cubeV, *propV_pos);
result *= chW_pos->diffAsHom() << -1;
result *= theta(diagram, dblpt, cubeCrx, *propC_dom, cubeW, *propW_pos) << -1;
return std::make_optional(std::move(result));
}
| 34.916107
| 83
| 0.547525
|
Junology
|
4c9a87344fbb7166a3209ccf49e0a1471e9dc3ce
| 282
|
cpp
|
C++
|
problems/baekjoon/p10871.cpp
|
yejun614/algorithm-solve
|
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
|
[
"MIT"
] | null | null | null |
problems/baekjoon/p10871.cpp
|
yejun614/algorithm-solve
|
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
|
[
"MIT"
] | null | null | null |
problems/baekjoon/p10871.cpp
|
yejun614/algorithm-solve
|
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
|
[
"MIT"
] | null | null | null |
/**
* (210929) X보다 작은 수
* https://www.acmicpc.net/problem/10871
*/
#include <cstdio>
int main() {
int N, X;
scanf("%d %d", &N, &X);
int buf;
for (int i=0; i<N; i++) {
scanf("%d",&buf);
if (buf < X)
printf("%d ", buf);
}
printf("\n");
return 0;
}
| 12.26087
| 40
| 0.468085
|
yejun614
|
4c9c3e8cc01a154e7ed32f1279c0b721dd58cb7b
| 38,428
|
cc
|
C++
|
ion/remote/resourcehandler.cc
|
mdemoret/Snapshot
|
987b3d45532f3644d35d858e036542d5691953ce
|
[
"Apache-2.0"
] | null | null | null |
ion/remote/resourcehandler.cc
|
mdemoret/Snapshot
|
987b3d45532f3644d35d858e036542d5691953ce
|
[
"Apache-2.0"
] | null | null | null |
ion/remote/resourcehandler.cc
|
mdemoret/Snapshot
|
987b3d45532f3644d35d858e036542d5691953ce
|
[
"Apache-2.0"
] | null | null | null |
/**
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#if !ION_PRODUCTION
#include "ion/remote/resourcehandler.h"
#include <sstream>
#include <string>
#include <vector>
#include "ion/base/allocator.h"
#include "ion/base/invalid.h"
#include "ion/base/stringutils.h"
#include "ion/base/zipassetmanager.h"
#include "ion/base/zipassetmanagermacros.h"
#include "ion/gfx/image.h"
#include "ion/gfx/resourcemanager.h"
#include "ion/gfx/tracinghelper.h"
#include "ion/gfxutils/resourcecallback.h"
#include "ion/image/conversionutils.h"
#include "ion/image/renderutils.h"
ION_REGISTER_ASSETS(IonRemoteResourcesRoot);
namespace ion {
namespace remote {
namespace {
using gfx::AttributeArray;
using gfx::BufferObject;
using gfx::CubeMapTexture;
using gfx::CubeMapTexturePtr;
using gfx::FramebufferObject;
using gfx::Image;
using gfx::ImagePtr;
using gfx::Renderer;
using gfx::RendererPtr;
using gfx::ResourceManager;
using gfx::Sampler;
using gfx::Shader;
using gfx::ShaderProgram;
using gfx::TextureBase;
using gfx::Texture;
using gfx::TexturePtr;
using gfxutils::ArrayCallback;
using gfxutils::BufferCallback;
using gfxutils::FramebufferCallback;
using gfxutils::PlatformCallback;
using gfxutils::ProgramCallback;
using gfxutils::SamplerCallback;
using gfxutils::ShaderCallback;
using gfxutils::TextureCallback;
using gfxutils::TextureImageCallback;
using std::bind;
using std::placeholders::_1;
typedef ResourceManager::ArrayInfo ArrayInfo;
typedef ResourceManager::BufferInfo BufferInfo;
typedef ResourceManager::FramebufferInfo FramebufferInfo;
typedef ResourceManager::RenderbufferInfo RenderbufferInfo;
typedef ResourceManager::PlatformInfo PlatformInfo;
typedef ResourceManager::ProgramInfo ProgramInfo;
typedef ResourceManager::SamplerInfo SamplerInfo;
typedef ResourceManager::ShaderInfo ShaderInfo;
typedef ResourceManager::TextureImageInfo TextureImageInfo;
typedef ResourceManager::TextureInfo TextureInfo;
//-----------------------------------------------------------------------------
//
// Helper class for consistent indentation.
//
//-----------------------------------------------------------------------------
class Indent {
public:
explicit Indent(size_t spaces) : indent_(spaces, ' '), spaces_(spaces) {}
// Outputs the indentation held by this indent to the stream.
friend std::ostream& operator<<(std::ostream& out, const Indent& indent) {
out << indent.indent_;
return out;
}
// The + operator increases the indentation.
friend const Indent operator+(const Indent& indent, size_t spaces) {
return Indent(indent.spaces_ + spaces);
}
private:
const std::string indent_;
const size_t spaces_;
};
// Escapes ", \, and \n.
static const std::string EscapeJson(const std::string& str) {
std::string ret = base::ReplaceString(str, "\\", "\\\\");
ret = base::ReplaceString(ret, "\"", "\\\"");
ret = base::EscapeNewlines(ret);
return ret;
}
//-----------------------------------------------------------------------------
//
// Helper class derived from TextureImageCallback that first renders textures
// into images so that the images show up correctly regardless of whether the
// textures' images had data wiped.
//
//-----------------------------------------------------------------------------
class RenderTextureCallback : public TextureImageCallback {
public:
typedef base::ReferentPtr<RenderTextureCallback>::Type RefPtr;
RenderTextureCallback(const RendererPtr& renderer, bool do_wait)
: TextureImageCallback(do_wait),
renderer_(renderer) {}
// Renders texture images and then calls the version in the base class.
void Callback(const std::vector<TextureImageInfo>& data);
private:
// The constructor is private because this class is derived from Referent.
~RenderTextureCallback() override {}
// Each of these uses the renderer to render images from a Texture or
// CubeMapTexture in the passed TextureImageInfo, replacing the images in it.
void RenderTextureImage(const RendererPtr& renderer, TextureImageInfo* info);
void RenderCubeMapTextureImages(const RendererPtr& renderer,
TextureImageInfo* info);
// Renderer used to render images.
const RendererPtr& renderer_;
};
void RenderTextureCallback::Callback(
const std::vector<TextureImageInfo>& data) {
// Keep this instance from being deleted when Callback() finishes.
RefPtr holder(this);
// Make sure the Renderer doesn't try to process this (unfinished)
// request before rendering the image.
const bool flag_was_set =
renderer_->GetFlags().test(Renderer::kProcessInfoRequests);
renderer_->ClearFlag(Renderer::kProcessInfoRequests);
// If any of the returned images is missing data, render it into an image.
std::vector<TextureImageInfo> new_data = data;
const size_t data_count = new_data.size();
for (size_t i = 0; i < data_count; ++i) {
TextureImageInfo* info = &new_data[i];
if (info->texture.Get()) {
if (info->texture->GetTextureType() == TextureBase::kTexture)
RenderTextureImage(renderer_, info);
else
RenderCubeMapTextureImages(renderer_, info);
}
}
if (flag_was_set)
renderer_->SetFlag(Renderer::kProcessInfoRequests);
// Let the base class do its work.
TextureImageCallback::Callback(new_data);
}
void RenderTextureCallback::RenderTextureImage(
const RendererPtr& renderer, TextureImageInfo* info) {
DCHECK(info);
DCHECK_EQ(info->texture->GetTextureType(), TextureBase::kTexture);
DCHECK_EQ(info->images.size(), 1U);
const ImagePtr& input_image = info->images[0];
if (input_image.Get()) {
TexturePtr tex(static_cast<Texture*>(info->texture.Get()));
const base::AllocatorPtr& sta =
tex->GetAllocator()->GetAllocatorForLifetime(base::kShortTerm);
ImagePtr output_image = image::RenderTextureImage(
tex, input_image->GetWidth(), input_image->GetHeight(), renderer, sta);
if (output_image.Get())
info->images[0] = output_image;
}
}
void RenderTextureCallback::RenderCubeMapTextureImages(
const RendererPtr& renderer, TextureImageInfo* info) {
DCHECK(info);
DCHECK_EQ(info->texture->GetTextureType(), TextureBase::kCubeMapTexture);
DCHECK_EQ(info->images.size(), 6U);
CubeMapTexturePtr tex(static_cast<CubeMapTexture*>(info->texture.Get()));
const base::AllocatorPtr& sta =
tex->GetAllocator()->GetAllocatorForLifetime(base::kShortTerm);
for (int i = 0; i < 6; ++i) {
const ImagePtr& input_image = info->images[i];
const CubeMapTexture::CubeFace face =
static_cast<CubeMapTexture::CubeFace>(i);
ImagePtr output_image =
image::RenderCubeMapTextureFaceImage(
tex, face, input_image->GetWidth(), input_image->GetHeight(),
renderer, sta);
if (output_image.Get())
info->images[i] = output_image;
}
}
//-----------------------------------------------------------------------------
//
// Helper functions.
//
//-----------------------------------------------------------------------------
// Returns a JSON string representation of a FramebufferInfo::Attachment.
static const std::string ConvertAttachmentToJson(
const Indent& indent,
const FramebufferInfo::Attachment& info,
const RenderbufferInfo& rb_info) {
gfx::TracingHelper helper;
std::ostringstream str;
const Indent indent2 = indent + 2;
str << indent << "\"type\": \""
<< (info.type ? helper.ToString("GLenum", info.type) : "GL_NONE")
<< "\",\n";
str << indent;
if (info.type == GL_TEXTURE)
str << "\"texture_glid\": " << info.value << ",\n";
else
str << "\"value\": " << info.value << ",\n";
str << indent << "\"mipmap_level\": " << info.level << ",\n";
str << indent << "\"cube_face\": \""
<< (info.cube_face ? helper.ToString("GLenum", info.cube_face)
: "GL_NONE") << "\",\n";
str << indent << "\"renderbuffer\": {\n";
str << indent2 << "\"object_id\": " << rb_info.id << ",\n";
str << indent2 << "\"label\": " << "\"" << rb_info.label << "\",\n";
str << indent2 << "\"width\": " << rb_info.width << ",\n";
str << indent2 << "\"height\": " << rb_info.height << ",\n";
str << indent2 << "\"internal_format\": \""
<< helper.ToString("GLenum", rb_info.internal_format) << "\",\n";
str << indent2 << "\"red_size\": " << rb_info.red_size << ",\n";
str << indent2 << "\"green_size\": " << rb_info.green_size << ",\n";
str << indent2 << "\"blue_size\": " << rb_info.blue_size << ",\n";
str << indent2 << "\"alpha_size\": " << rb_info.alpha_size << ",\n";
str << indent2 << "\"depth_size\": " << rb_info.depth_size << ",\n";
str << indent2 << "\"stencil_size\": " << rb_info.stencil_size << "\n";
str << indent << "}\n";
return str.str();
}
const std::string ConvertEnumVectorToJson(const std::vector<GLenum>& vec) {
gfx::TracingHelper helper;
std::ostringstream str;
const size_t count = vec.size();
for (size_t i = 0; i < count; ++i) {
if (i)
str << ", ";
str << helper.ToString("GLenum", vec[i]);
}
return str.str();
}
// Returns a JSON string representation of a ProgramInfo shader input.
template <typename T>
static const std::string ConvertShaderInputToJson(const Indent& indent,
const T& input) {
gfx::TracingHelper helper;
std::ostringstream str;
str << indent << "\"name\": \"" << input.name << "\",\n";
str << indent << "\"index\": " << input.index << ",\n";
str << indent << "\"size\": " << input.size << ",\n";
str << indent << "\"type\": \"" << helper.ToString("GLenum", input.type)
<< "\"\n";
return str.str();
}
// Returns a JSON string representation of a ProgramInfo::Attribute.
static const std::string ConvertProgramAttributesToJson(
const Indent& indent, const std::vector<ProgramInfo::Attribute>& attrs) {
gfx::TracingHelper helper;
std::ostringstream str;
const size_t count = attrs.size();
for (size_t i = 0; i < count; ++i) {
str << indent << "{\n";
str << ConvertShaderInputToJson(indent + 2, attrs[i]);
str << indent << "}" << (i < count - 1U ? "," : "") << "\n";
}
return str.str();
}
// Outputs the passed uniform to a stream.
template <typename T>
static void StreamProgramUniform(const ProgramInfo::Uniform& uniform,
std::ostream& str) { // NOLINT
str << "\"";
if (uniform.size > 1) {
str << "[";
for (GLint i = 0; i < uniform.size; i++) {
if (i)
str << ", ";
str << uniform.value.GetValueAt<T>(i);
}
str << "]";
} else {
str << uniform.value.Get<T>();
}
str << "\"";
}
// Outputs the passed uniform vector to a stream.
template <typename T>
static void StreamProgramUniformVector(const ProgramInfo::Uniform& uniform,
std::ostream& str) { // NOLINT
str << "\"";
if (uniform.size > 1) {
str << "[";
for (GLint i = 0; i < uniform.size; i++) {
if (i)
str << ", ";
uniform.value.GetValueAt<T>(i).Print(str, 'V');
}
str << "]";
} else {
uniform.value.Get<T>().Print(str, 'V');
}
str << "\"";
}
// Returns a JSON string representation of a ProgramInfo::Uniform.
static const std::string ConvertProgramUniformsToJson(
const Indent& indent, const std::vector<ProgramInfo::Uniform>& uniforms) {
gfx::TracingHelper helper;
std::ostringstream str;
const Indent indent2 = indent + 2;
const size_t count = uniforms.size();
for (size_t i = 0; i < count; ++i) {
const ProgramInfo::Uniform& u = uniforms[i];
str << indent << "{\n";
str << indent2 << "\"value\": ";
switch (u.type) {
case GL_FLOAT:
StreamProgramUniform<float>(u, str);
break;
case GL_FLOAT_VEC2:
StreamProgramUniformVector<math::VectorBase2f>(u, str);
break;
case GL_FLOAT_VEC3:
StreamProgramUniformVector<math::VectorBase3f>(u, str);
break;
case GL_FLOAT_VEC4:
StreamProgramUniformVector<math::VectorBase4f>(u, str);
break;
case GL_INT:
case GL_INT_SAMPLER_1D:
case GL_INT_SAMPLER_1D_ARRAY:
case GL_INT_SAMPLER_2D:
case GL_INT_SAMPLER_2D_ARRAY:
case GL_INT_SAMPLER_3D:
case GL_INT_SAMPLER_CUBE:
case GL_INT_SAMPLER_CUBE_MAP_ARRAY:
case GL_SAMPLER_1D:
case GL_SAMPLER_1D_ARRAY:
case GL_SAMPLER_1D_ARRAY_SHADOW:
case GL_SAMPLER_1D_SHADOW:
case GL_SAMPLER_2D:
case GL_SAMPLER_2D_ARRAY:
case GL_SAMPLER_2D_ARRAY_SHADOW:
case GL_SAMPLER_2D_MULTISAMPLE:
case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
case GL_SAMPLER_2D_SHADOW:
case GL_SAMPLER_3D:
case GL_SAMPLER_CUBE:
case GL_SAMPLER_CUBE_MAP_ARRAY:
case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW:
case GL_SAMPLER_CUBE_SHADOW:
case GL_SAMPLER_EXTERNAL_OES:
case GL_UNSIGNED_INT_SAMPLER_1D:
case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY:
case GL_UNSIGNED_INT_SAMPLER_2D:
case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
case GL_UNSIGNED_INT_SAMPLER_3D:
case GL_UNSIGNED_INT_SAMPLER_CUBE:
case GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY:
StreamProgramUniform<int>(u, str);
break;
case GL_INT_VEC2:
StreamProgramUniformVector<math::VectorBase2i>(u, str);
break;
case GL_INT_VEC3:
StreamProgramUniformVector<math::VectorBase3i>(u, str);
break;
case GL_INT_VEC4:
StreamProgramUniformVector<math::VectorBase4i>(u, str);
break;
case GL_UNSIGNED_INT:
StreamProgramUniform<uint32>(u, str);
break;
case GL_UNSIGNED_INT_VEC2:
StreamProgramUniformVector<math::VectorBase2ui>(u, str);
break;
case GL_UNSIGNED_INT_VEC3:
StreamProgramUniformVector<math::VectorBase3ui>(u, str);
break;
case GL_UNSIGNED_INT_VEC4:
StreamProgramUniformVector<math::VectorBase4ui>(u, str);
break;
case GL_FLOAT_MAT2:
StreamProgramUniform<math::Matrix2f>(u, str);
break;
case GL_FLOAT_MAT3:
StreamProgramUniform<math::Matrix3f>(u, str);
break;
case GL_FLOAT_MAT4:
StreamProgramUniform<math::Matrix4f>(u, str);
break;
#if !defined(ION_COVERAGE) // COV_NF_START
default:
break;
#endif // COV_NF_END
}
str << ",\n";
str << ConvertShaderInputToJson(indent + 2, u);
str << indent << "}" << (i < count - 1U ? "," : "") << "\n";
}
return str.str();
}
// The below functions convert various structs into JSON parseable strings
// suitable for reconstruction by a web browser.
//
// Default unspecialized version which should never be called.
template <typename InfoType>
static const std::string ConvertInfoToJson(const Indent& indent,
const InfoType& info) {
CHECK(false) << "Unspecialized ConvertInfoToJson() called.";
return std::string();
}
template <>
const std::string ConvertInfoToJson(const Indent& indent,
const PlatformInfo& info) {
std::ostringstream str;
const Indent indent2 = indent + 2;
const Indent indent4 = indent + 4;
str << indent << "\"renderer\": \"" << info.renderer << "\",\n";
str << indent << "\"vendor\": \"" << info.vendor << "\",\n";
str << indent << "\"version_string\": \"" << info.version_string << "\",\n";
str << indent << "\"gl_version\": " << info.major_version << "."
<< info.minor_version << ",\n";
str << indent << "\"glsl_version\": " << info.glsl_version << ",\n";
str << indent << "\"aliased_line_width_range\": \""
<< info.aliased_line_width_range[0] << " - "
<< info.aliased_line_width_range[1] << "\",\n";
str << indent << "\"aliased_point_size_range\": \""
<< info.aliased_point_size_range[0] << " - "
<< info.aliased_point_size_range[1] << "\",\n";
str << indent << "\"max_color_attachments\": "
<< info.max_color_attachments << ",\n";
str << indent << "\"max_combined_texture_image_units\": "
<< info.max_combined_texture_image_units << ",\n";
str << indent << "\"max_cube_map_texture_size\": "
<< info.max_cube_map_texture_size << ",\n";
str << indent << "\"max_draw_buffers\": "
<< info.max_draw_buffers << ",\n";
str << indent << "\"max_fragment_uniform_vectors\": "
<< info.max_fragment_uniform_vectors << ",\n";
str << indent << "\"max_renderbuffer_size\": " << info.max_renderbuffer_size
<< ",\n";
str << indent << "\"max_texture_image_units\": "
<< info.max_texture_image_units << ",\n";
str << indent << "\"max_texture_size\": " << info.max_texture_size << ",\n";
str << indent << "\"max_transform_feedback_buffers\": "
<< info.max_transform_feedback_buffers << ",\n";
str << indent << "\"max_transform_feedback_interleaved_components\": "
<< info.max_transform_feedback_interleaved_components << ",\n";
str << indent << "\"max_transform_feedback_separate_attribs\": "
<< info.max_transform_feedback_separate_attribs << ",\n";
str << indent << "\"max_transform_feedback_separate_components\": "
<< info.max_transform_feedback_separate_components << ",\n";
str << indent << "\"max_varying_vectors\": " << info.max_varying_vectors
<< ",\n";
str << indent << "\"max_vertex_attribs\": " << info.max_vertex_attribs
<< ",\n";
str << indent << "\"max_vertex_texture_image_units\": "
<< info.max_vertex_texture_image_units << ",\n";
str << indent << "\"max_vertex_uniform_vectors\": "
<< info.max_vertex_uniform_vectors << ",\n";
str << indent << "\"max_viewport_dims\": \"" << info.max_viewport_dims[0]
<< " x " << info.max_viewport_dims[1] << "\",\n";
str << indent << "\"transform_feedback_varying_max_length\": "
<< info.transform_feedback_varying_max_length << ",\n";
str << indent << "\"compressed_texture_formats\": \""
<< ConvertEnumVectorToJson(info.compressed_texture_formats) << "\",\n";
str << indent << "\"shader_binary_formats\": \""
<< ConvertEnumVectorToJson(info.shader_binary_formats) << "\",\n";
str << indent << "\"extensions\": \"" << info.extensions << "\"\n";
return str.str();
}
template <>
const std::string ConvertInfoToJson(const Indent& indent,
const ArrayInfo& info) {
gfx::TracingHelper helper;
std::ostringstream str;
const Indent indent2 = indent + 2;
const Indent indent4 = indent + 4;
str << indent << "\"object_id\": " << info.id << ",\n";
str << indent << "\"label\": " << "\"" << info.label << "\",\n";
str << indent << "\"vertex_count\": " << info.vertex_count << ",\n";
str << indent << "\"attributes\": [\n";
const size_t count = info.attributes.size();
for (size_t i = 0; i < count; ++i) {
str << indent2 << "{\n";
str << indent4 << "\"buffer_glid\": " << info.attributes[i].buffer << ",\n";
str << indent4 << "\"enabled\": \""
<< helper.ToString("GLboolean", info.attributes[i].enabled) << "\",\n";
str << indent4 << "\"size\": " << info.attributes[i].size << ",\n";
str << indent4 << "\"stride\": " << info.attributes[i].stride << ",\n";
str << indent4 << "\"type\": \""
<< helper.ToString("GLenum", info.attributes[i].type) << "\",\n";
str << indent4 << "\"normalized\": \""
<< helper.ToString("GLboolean", info.attributes[i].normalized)
<< "\",\n";
str << indent4 << "\"pointer_or_offset\": \""
<< helper.ToString("GLvoid*", info.attributes[i].pointer) << "\",\n";
str << indent4 << "\"value\": \"" << info.attributes[i].value << "\"\n";
str << indent2 << "}" << (i < count - 1U ? "," : "") << "\n";
}
str << indent << "]\n";
return str.str();
}
template <>
const std::string ConvertInfoToJson(const Indent& indent,
const BufferInfo& info) {
gfx::TracingHelper helper;
std::ostringstream str;
str << indent << "\"object_id\": " << info.id << ",\n";
str << indent << "\"label\": " << "\"" << info.label << "\",\n";
str << indent << "\"size\": " << info.size << ",\n";
str << indent << "\"usage\": \"" << helper.ToString("GLenum", info.usage)
<< "\",\n";
str << indent << "\"mapped_pointer\": \""
<< helper.ToString("GLvoid*", info.mapped_data) << "\",\n";
str << indent << "\"target\": \"" << helper.ToString("GLenum", info.target)
<< "\"\n";
return str.str();
}
template <>
const std::string ConvertInfoToJson(const Indent& indent,
const FramebufferInfo& info) {
std::ostringstream str;
const Indent indent2 = indent + 2;
str << indent << "\"object_id\": " << info.id << ",\n";
str << indent << "\"label\": " << "\"" << info.label << "\",\n";
str << indent << "\"attachment_color0\": {\n";
str << ConvertAttachmentToJson(
indent2, info.color0, info.color0_renderbuffer);
str << indent << "},\n";
str << indent << "\"attachment_depth\": {\n";
str << ConvertAttachmentToJson(indent2, info.depth, info.depth_renderbuffer);
str << indent << "},\n";
str << indent << "\"attachment_stencil\": {\n";
str << ConvertAttachmentToJson(
indent2, info.stencil, info.stencil_renderbuffer);
str << indent << "}\n";
return str.str();
}
template <>
const std::string ConvertInfoToJson(const Indent& indent,
const ProgramInfo& info) {
gfx::TracingHelper helper;
std::ostringstream str;
const Indent indent2 = indent + 2;
str << indent << "\"object_id\": " << info.id << ",\n";
str << indent << "\"label\": " << "\"" << info.label << "\",\n";
str << indent << "\"vertex_shader_glid\": " << info.vertex_shader << ",\n";
str << indent << "\"fragment_shader_glid\": " << info.fragment_shader
<< ",\n";
str << indent << "\"delete_status\": \""
<< helper.ToString("GLboolean", info.delete_status) << "\",\n";
str << indent << "\"link_status\": \""
<< helper.ToString("GLboolean", info.link_status) << "\",\n";
str << indent << "\"validate_status\": \""
<< helper.ToString("GLboolean", info.validate_status) << "\",\n";
str << indent << "\"attributes\": [\n";
str << ConvertProgramAttributesToJson(indent2, info.attributes);
str << indent << "],\n";
str << indent << "\"uniforms\": [\n";
str << ConvertProgramUniformsToJson(indent2, info.uniforms);
str << indent << "],\n";
str << indent << "\"info_log\": \"" << EscapeJson(info.info_log)
<< "\"\n";
return str.str();
}
template <>
const std::string ConvertInfoToJson(const Indent& indent,
const SamplerInfo& info) {
gfx::TracingHelper helper;
std::ostringstream str;
str << indent << "\"object_id\": " << info.id << ",\n";
str << indent << "\"label\": " << "\"" << info.label << "\",\n";
str << indent << "\"compare_function\": \""
<< helper.ToString("GLtextureenum", info.compare_func) << "\",\n";
str << indent << "\"compare_mode\": \""
<< helper.ToString("GLtextureenum", info.compare_mode) << "\",\n";
str << indent << "\"max_anisotropy\": " << info.max_anisotropy << ",\n";
str << indent << "\"min_lod\": " << info.min_lod << ",\n";
str << indent << "\"max_lod\": " << info.max_lod << ",\n";
str << indent << "\"min_filter\": \""
<< helper.ToString("GLenum", info.min_filter) << "\",\n";
str << indent << "\"mag_filter\": \""
<< helper.ToString("GLenum", info.mag_filter) << "\",\n";
str << indent << "\"wrap_r\": \"" << helper.ToString("GLenum", info.wrap_r)
<< "\",\n";
str << indent << "\"wrap_s\": \"" << helper.ToString("GLenum", info.wrap_s)
<< "\",\n";
str << indent << "\"wrap_t\": \"" << helper.ToString("GLenum", info.wrap_t)
<< "\"\n";
return str.str();
}
template <>
const std::string ConvertInfoToJson(const Indent& indent,
const ShaderInfo& info) {
gfx::TracingHelper helper;
std::ostringstream str;
str << indent << "\"object_id\": " << info.id << ",\n";
str << indent << "\"label\": " << "\"" << info.label << "\",\n";
str << indent << "\"type\": \"" << helper.ToString("GLenum", info.type)
<< "\",\n";
str << indent << "\"delete_status\": \""
<< helper.ToString("GLboolean", info.delete_status) << "\",\n";
str << indent << "\"compile_status\": \""
<< helper.ToString("GLboolean", info.compile_status) << "\",\n";
str << indent << "\"source\": \""
<< base::MimeBase64EncodeString("<pre><code>" + info.source +
"</code></pre>") << "\",\n";
str << indent << "\"info_log\": \"" << EscapeJson(info.info_log)
<< "\"\n";
return str.str();
}
template <>
const std::string ConvertInfoToJson(const Indent& indent,
const TextureInfo& info) {
gfx::TracingHelper helper;
std::ostringstream str;
str << indent << "\"object_id\": " << info.id << ",\n";
str << indent << "\"label\": " << "\"" << info.label << "\",\n";
str << indent << "\"width\": " << info.width << ",\n";
str << indent << "\"height\": " << info.height<< ",\n";
str << indent << "\"format\": \"" << Image::GetFormatString(info.format)
<< "\",\n";
str << indent << "\"sampler_glid\": " << info.sampler << ",\n";
str << indent << "\"base_level\": " << info.base_level << ",\n";
str << indent << "\"max_level\": " << info.max_level << ",\n";
str << indent << "\"compare_function\": \""
<< helper.ToString("GLtextureenum", info.compare_func) << "\",\n";
str << indent << "\"compare_mode\": \""
<< helper.ToString("GLtextureenum", info.compare_mode) << "\",\n";
str << indent << "\"max_anisotropy\": " << info.max_anisotropy << ",\n";
str << indent << "\"min_lod\": " << info.min_lod << ",\n";
str << indent << "\"max_lod\": " << info.max_lod << ",\n";
str << indent << "\"min_filter\": \""
<< helper.ToString("GLenum", info.min_filter) << "\",\n";
str << indent << "\"mag_filter\": \""
<< helper.ToString("GLenum", info.mag_filter) << "\",\n";
str << indent << "\"swizzle_red\": \""
<< helper.ToString("GLtextureenum", info.swizzle_r) << "\",\n";
str << indent << "\"swizzle_green\": \""
<< helper.ToString("GLtextureenum", info.swizzle_g) << "\",\n";
str << indent << "\"swizzle_blue\": \""
<< helper.ToString("GLtextureenum", info.swizzle_b) << "\",\n";
str << indent << "\"swizzle_alpha\": \""
<< helper.ToString("GLtextureenum", info.swizzle_a) << "\",\n";
str << indent << "\"wrap_r\": \"" << helper.ToString("GLenum", info.wrap_r)
<< "\",\n";
str << indent << "\"wrap_s\": \"" << helper.ToString("GLenum", info.wrap_s)
<< "\",\n";
str << indent << "\"wrap_t\": \"" << helper.ToString("GLenum", info.wrap_t)
<< "\",\n";
str << indent << "\"target\": \"" << helper.ToString("GLenum", info.target)
<< "\",\n";
str << indent << "\"last_image_unit\": \""
<< helper.ToString("GLenum", info.unit) << "\"\n";
return str.str();
}
// Uses the passed ResourceManager to request information about OpenGL
// resources.
template <typename ResourceType, typename InfoType>
void RequestInfo(
ResourceManager* manager,
const typename gfxutils::ResourceCallback<InfoType>::RefPtr& callback) {
manager->RequestAllResourceInfos<ResourceType, InfoType>(std::bind(
&gfxutils::ResourceCallback<InfoType>::Callback, callback.Get(), _1));
}
// Specialization for PlatformInfo, which does not require a ResourceType and
// has a different function signature in the ResourceManager.
template <>
void RequestInfo<PlatformInfo, PlatformInfo>(
ResourceManager* manager,
const gfxutils::ResourceCallback<PlatformInfo>::RefPtr& callback) {
manager->RequestPlatformInfo(std::bind(
&gfxutils::ResourceCallback<PlatformInfo>::Callback, callback.Get(), _1));
}
// Builds and returns a JSOn struct for the named resource type.
template <typename ResourceType, typename InfoType>
const std::string BuildJsonStruct(const RendererPtr& renderer,
const std::string& name, const Indent& indent,
const bool wait_for_completion) {
// Get resource information out of the Renderer's ResourceManager.
ResourceManager* manager = renderer->GetResourceManager();
typedef gfxutils::ResourceCallback<InfoType> Callback;
typename Callback::RefPtr callback(new Callback(wait_for_completion));
RequestInfo<ResourceType, InfoType>(manager, callback);
// Only explicitly ask the renderer to process the requests if we are not
// willing to block. This should only be used for tests, since the handler
// will be executed on a thread other than the Renderer's.
if (!wait_for_completion)
renderer->ProcessResourceInfoRequests();
std::vector<InfoType> infos;
callback->WaitForCompletion(&infos);
std::ostringstream str;
const Indent indent2 = indent + 2;
const Indent indent4 = indent + 4;
// Start the array.
str << indent << "\"" << name << "\": [\n";
const size_t count = infos.size();
for (size_t i = 0; i < count; ++i) {
str << indent2 << "{\n";
str << ConvertInfoToJson<InfoType>(indent4, infos[i]);
str << indent2 << "}" << (i < count - 1U ? "," : "") << "\n";
}
// End the array.
str << indent << "]";
return str.str();
}
// Returns a string containing a JSON object containing lists of JSON structs
// for the types queried in the "types" argument in args.
static const std::string GetResourceList(const RendererPtr& renderer,
const HttpServer::QueryMap& args) {
const bool wait_for_completion = args.find("nonblocking") == args.end();
HttpServer::QueryMap::const_iterator it = args.find("types");
std::ostringstream str;
if (it != args.end()) {
str << "{\n";
const Indent indent(2);
const std::vector<std::string> types = base::SplitString(it->second, ",");
const size_t count = types.size();
for (size_t i = 0; i < count; ++i) {
if (types[i] == "platform") {
str << BuildJsonStruct<PlatformInfo, PlatformInfo>(
renderer, "platform", indent, wait_for_completion);
} else if (types[i] == "buffers") {
str << BuildJsonStruct<BufferObject, BufferInfo>(
renderer, "buffers", indent, wait_for_completion);
} else if (types[i] == "framebuffers") {
str << BuildJsonStruct<FramebufferObject, FramebufferInfo>(
renderer, "framebuffers", indent, wait_for_completion);
} else if (types[i] == "programs") {
str << BuildJsonStruct<ShaderProgram, ProgramInfo>(
renderer, "programs", indent, wait_for_completion);
} else if (types[i] == "samplers") {
str << BuildJsonStruct<Sampler, SamplerInfo>(
renderer, "samplers", indent, wait_for_completion);
} else if (types[i] == "shaders") {
str << BuildJsonStruct<Shader, ShaderInfo>(renderer, "shaders", indent,
wait_for_completion);
} else if (types[i] == "textures") {
str << BuildJsonStruct<TextureBase, TextureInfo>(
renderer, "textures", indent, wait_for_completion);
} else if (types[i] == "vertex_arrays") {
str << BuildJsonStruct<AttributeArray, ArrayInfo>(
renderer, "vertex_arrays", indent, wait_for_completion);
} else {
// Ignore invalid labels.
continue;
}
// Every struct but the last requires a trailing comma.
if (i < count - 1)
str << ",\n";
else
str << "\n";
}
str << "}\n";
}
return str.str();
}
static const std::string GetBufferData(const RendererPtr& renderer,
const HttpServer::QueryMap& args) {
// TODO(user): Map the buffer read-only given only the id, and return the
// data.
return std::string();
}
// Writes a face of a cube map into the map at the passed offsets. This inverts
// the Y coordinate to counteract OpenGL rendering.
static void WriteFaceIntoCubeMap(uint32 x_offset,
uint32 y_offset,
const ImagePtr& face,
const ImagePtr& cubemap) {
const uint32 x_offset_bytes = x_offset * 3;
const uint32 face_height = face->GetHeight();
const uint32 face_row_bytes = face->GetWidth() * 3;
const uint32 cube_row_bytes = cubemap->GetWidth() * 3;
const uint8* in = face->GetData()->GetData<uint8>();
uint8* out = cubemap->GetData()->GetMutableData<uint8>();
DCHECK(in);
DCHECK(out);
for (uint32 row = 0; row < face_height; ++row) {
const uint32 y = face_height - row - 1;
memcpy(&out[(y_offset + y) * cube_row_bytes + x_offset_bytes],
&in[y * face_row_bytes], face_row_bytes);
}
}
// Returns a string that contains PNG data for the ID passed as a query arg.
static const std::string GetTextureData(const RendererPtr& renderer,
const HttpServer::QueryMap& args,
bool wait_for_completion) {
std::string data;
HttpServer::QueryMap::const_iterator id_it = args.find("id");
if (id_it != args.end()) {
if (GLuint id = static_cast<GLuint>(base::StringToInt32(id_it->second))) {
// Request the info.
ResourceManager* manager = renderer->GetResourceManager();
RenderTextureCallback::RefPtr callback(
new RenderTextureCallback(renderer, wait_for_completion));
manager->RequestTextureImage(
id, std::bind(&RenderTextureCallback::Callback, callback.Get(), _1));
if (!wait_for_completion)
renderer->ProcessResourceInfoRequests();
// Wait for the callback to be triggered.
std::vector<TextureImageInfo> infos;
callback->WaitForCompletion(&infos);
// There should only be one info, and it contains the texture image.
if (infos.size() && infos[0].images.size()) {
if (infos[0].images.size() == 1U) {
// Convert the image to png. Flip Y to counteract OpenGL rendering.
const std::vector<uint8> png_data = image::ConvertToExternalImageData(
infos[0].images[0], image::kPng, true);
data = base::MimeBase64EncodeString(
std::string(png_data.begin(), png_data.end()));
} else {
// Make a vertical cube map cross image.
DCHECK_EQ(6U, infos[0].images.size());
uint32 face_width = 0;
uint32 face_height = 0;
for (int i = 0; i < 6; ++i) {
face_width = std::max(face_width, infos[0].images[0]->GetWidth());
face_height =
std::max(face_height, infos[0].images[0]->GetHeight());
}
// Allocate the data.
ImagePtr cubemap(new Image);
const uint32 num_bytes = face_width * 3U * face_height * 4U * 3U;
base::DataContainerPtr cubemap_data =
base::DataContainer::CreateOverAllocated<uint8>(
num_bytes, NULL, cubemap->GetAllocator());
cubemap->Set(
Image::kRgb888, face_width * 3U, face_height * 4U, cubemap_data);
memset(cubemap_data->GetMutableData<uint8>(), 0, num_bytes);
// Copy the images into the cubemap. The output map should look like:
// ----
// |+Y|
// ----------
// |-X|+Z|+X|
// ----------
// |-Y|
// ----
// |-Z|
// ----
WriteFaceIntoCubeMap(face_width, 0U, infos[0].images[4], cubemap);
WriteFaceIntoCubeMap(0U, face_height, infos[0].images[0], cubemap);
WriteFaceIntoCubeMap(
face_width, face_height, infos[0].images[5], cubemap);
WriteFaceIntoCubeMap(
face_width * 2U, face_height, infos[0].images[3], cubemap);
WriteFaceIntoCubeMap(
face_width, face_height * 2U, infos[0].images[1], cubemap);
WriteFaceIntoCubeMap(
face_width, face_height * 3U, infos[0].images[2], cubemap);
// Send the image back.
const std::vector<uint8> png_data =
image::ConvertToExternalImageData(cubemap, image::kPng, false);
data = base::MimeBase64EncodeString(
std::string(png_data.begin(), png_data.end()));
}
}
}
}
return data;
}
} // anonymous namespace
//-----------------------------------------------------------------------------
//
// ResourceHandler functions.
//
//-----------------------------------------------------------------------------
ResourceHandler::ResourceHandler(const gfx::RendererPtr& renderer)
: HttpServer::RequestHandler("/ion/resources"),
renderer_(renderer) {
IonRemoteResourcesRoot::RegisterAssetsOnce();
}
ResourceHandler::~ResourceHandler() {}
const std::string ResourceHandler::HandleRequest(
const std::string& path_in, const HttpServer::QueryMap& args,
std::string* content_type) {
const std::string path = path_in.empty() ? "index.html" : path_in;
if (path == "buffer_data") {
return GetBufferData(renderer_, args);
} else if (path == "resources_by_type") {
*content_type = "application/json";
return GetResourceList(renderer_, args);
} else if (path == "texture_data") {
*content_type = "image/png";
return GetTextureData(
renderer_, args, args.find("nonblocking") == args.end());
} else {
const std::string& data = base::ZipAssetManager::GetFileData(
"ion/resources/" + path);
if (base::IsInvalidReference(data)) {
return std::string();
} else {
// Ensure the content type is set if the editor HTML is requested.
if (base::EndsWith(path, "html"))
*content_type = "text/html";
return data;
}
}
}
} // namespace remote
} // namespace ion
#endif
| 38.934144
| 80
| 0.605496
|
mdemoret
|
4c9d960feb65756eb35282dde7b24bdf61bb3e8b
| 9,492
|
cpp
|
C++
|
platforms/linux/TTYLib.cpp
|
ICESat2-SlideRule/sliderule
|
90776d7e174e151c5806077001f5f9c21ef81f48
|
[
"BSD-3-Clause"
] | 2
|
2021-05-06T19:56:26.000Z
|
2021-05-27T16:41:56.000Z
|
platforms/linux/TTYLib.cpp
|
ICESat2-SlideRule/sliderule
|
90776d7e174e151c5806077001f5f9c21ef81f48
|
[
"BSD-3-Clause"
] | 54
|
2021-03-30T18:45:12.000Z
|
2022-03-17T20:13:04.000Z
|
platforms/linux/TTYLib.cpp
|
ICESat2-SlideRule/sliderule
|
90776d7e174e151c5806077001f5f9c21ef81f48
|
[
"BSD-3-Clause"
] | 1
|
2021-05-14T16:34:08.000Z
|
2021-05-14T16:34:08.000Z
|
/*
* Copyright (c) 2021, University of Washington
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the University of Washington nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF WASHINGTON AND CONTRIBUTORS
* “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF WASHINGTON OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/******************************************************************************
* INCLUDES
******************************************************************************/
#include "OsApi.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <limits.h>
#include <assert.h>
#include <unistd.h>
#include <signal.h>
#include <ctype.h>
#include <fcntl.h>
#include <errno.h>
#include <poll.h>
#include <termios.h>
#include <sys/sysinfo.h>
/******************************************************************************
* PUBLIC METHODS
******************************************************************************/
/*----------------------------------------------------------------------------
* init
*----------------------------------------------------------------------------*/
void TTYLib::init()
{
}
/*----------------------------------------------------------------------------
* deinit
*----------------------------------------------------------------------------*/
void TTYLib::deinit(void)
{
}
/*----------------------------------------------------------------------------
* ttyopen
*----------------------------------------------------------------------------*/
int TTYLib::ttyopen(const char* _device, int _baud, char _parity)
{
int fd = INVALID_RC;
int baud = 0;
int parity = 0;
/* Set Parity */
if(_parity == 'N' || _parity == 'n')
{
parity = 0; // no parity
}
else if(_parity == 'O' || _parity == 'o')
{
parity = PARENB | PARODD; // odd parity
}
else if(_parity == 'E' || _parity == 'e')
{
parity = PARENB; // event parity
}
/* Set Baud */
switch(_baud)
{
case 50: baud = B50; break;
case 75: baud = B75; break;
case 110: baud = B110; break;
case 134: baud = B134; break;
case 150: baud = B150; break;
case 200: baud = B200; break;
case 300: baud = B300; break;
case 600: baud = B600; break;
case 1200: baud = B1200; break;
case 1800: baud = B1800; break;
case 2400: baud = B2400; break;
case 4800: baud = B4800; break;
case 9600: baud = B9600; break;
case 19200: baud = B19200; break;
case 38400: baud = B38400; break;
case 115200: baud = B115200; break;
case 230400: baud = B230400; break;
case 460800: baud = B460800; break;
case 500000: baud = B500000; break;
case 576000: baud = B576000; break;
case 921600: baud = B921600; break;
case 1000000: baud = B1000000; break;
case 1152000: baud = B1152000; break;
default: baud = B0; break;
}
/* Set Device */
if(_device)
{
/* Set File Descriptor */
fd = open(_device, O_RDWR | O_NOCTTY | O_NDELAY);
if(fd < 0)
{
dlog("Failed (%d) to open %s: %s", errno, _device, strerror(errno));
fd = INVALID_RC;
}
else
{
struct termios tty;
memset(&tty, 0, sizeof(tty));
if(tcgetattr (fd, &tty) != 0)
{
dlog("Failed (%d) tcgetattr for %s: %s", errno, _device, strerror(errno));
fd = INVALID_RC;
}
else
{
cfsetospeed (&tty, baud);
cfsetispeed (&tty, baud);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_iflag &= ~(INLCR | ICRNL | IUCLC); // no remapping on input
tty.c_lflag = 0; // no signaling chars, no echo
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read is non-blocking
tty.c_cc[VTIME] = 0; // no read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |= (CLOCAL | CREAD); // ignore modem controls
tty.c_cflag &= ~(PARENB | PARODD); // initialize parity to off
tty.c_cflag |= parity; // set parity
tty.c_cflag &= ~CSTOPB; // send one stop bit
tty.c_cflag &= ~CRTSCTS; // no hardware flow control
if(tcsetattr (fd, TCSANOW, &tty) != 0)
{
dlog("Failed (%d) tcsetattr for %s: %s", errno, _device, strerror(errno));
fd = INVALID_RC;
}
}
}
}
/* Return Descriptor */
return fd;
}
/*----------------------------------------------------------------------------
* ttyclose
*----------------------------------------------------------------------------*/
void TTYLib::ttyclose(int fd)
{
close(fd);
}
/*----------------------------------------------------------------------------
* ttywrite
*----------------------------------------------------------------------------*/
int TTYLib::ttywrite(int fd, const void* buf, int size, int timeout)
{
unsigned char* cbuf = (unsigned char*)buf;
int activity = 1;
int revents = POLLOUT;
/* Check Device */
if(fd == INVALID_RC)
{
if(timeout != IO_CHECK) LocalLib::performIOTimeout();
return TIMEOUT_RC;
}
/* Send Data */
int c = 0;
while(c >= 0 && c < size)
{
/* Perform Poll if not Checking */
if(timeout != IO_CHECK)
{
/* Build Poll Structure */
struct pollfd polllist[1];
polllist[0].fd = fd;
polllist[0].events = POLLOUT | POLLHUP;
polllist[0].revents = 0;
/* Poll */
do activity = poll(polllist, 1, timeout);
while(activity == -1 && (errno == EINTR || errno == EAGAIN));
/* Check Activity */
if(activity <= 0) break;
revents = polllist[0].revents;
}
/* Perform Send */
if(revents & POLLHUP)
{
c = SHUTDOWN_RC;
}
else if(revents & POLLOUT)
{
int ret = write(fd, &cbuf[c], size - c);
if(ret > 0) c += ret;
else if(ret <= 0) c = TTY_ERR_RC;
}
}
/* Return Results */
return c;
}
/*----------------------------------------------------------------------------
* ttyread
*----------------------------------------------------------------------------*/
int TTYLib::ttyread(int fd, void* buf, int size, int timeout)
{
int c = TIMEOUT_RC;
int revents = POLLIN;
/* Check Device */
if(fd == INVALID_RC)
{
if(timeout != IO_CHECK) LocalLib::performIOTimeout();
return TIMEOUT_RC;
}
/* Perform Poll if not Checking */
if(timeout != IO_CHECK)
{
struct pollfd polllist[1];
polllist[0].fd = fd;
polllist[0].events = POLLIN | POLLHUP;
polllist[0].revents = 0;
int activity = 1;
do activity = poll(polllist, 1, timeout);
while(activity == -1 && (errno == EINTR || errno == EAGAIN));
revents = polllist[0].revents;
}
/* Perform Receive */
if(revents & POLLIN)
{
c = read(fd, buf, size);
if(c <= 0) c = TTY_ERR_RC;
}
else if(revents & POLLHUP)
{
c = SHUTDOWN_RC;
}
/* Return Results*/
return c;
}
| 33.659574
| 98
| 0.455225
|
ICESat2-SlideRule
|
4ca622cf63d1b2b43c3daf5161c35c4a64d8b9c5
| 55
|
hpp
|
C++
|
include/scapin/scapin.hpp
|
sbrisard/gollum
|
25d5b9aea63a8f2812c4b41850450fcbead64da7
|
[
"BSD-3-Clause"
] | null | null | null |
include/scapin/scapin.hpp
|
sbrisard/gollum
|
25d5b9aea63a8f2812c4b41850450fcbead64da7
|
[
"BSD-3-Clause"
] | 4
|
2020-09-24T07:32:21.000Z
|
2020-12-01T08:06:00.000Z
|
include/scapin/scapin.hpp
|
sbrisard/gollum
|
25d5b9aea63a8f2812c4b41850450fcbead64da7
|
[
"BSD-3-Clause"
] | 1
|
2020-02-02T18:05:15.000Z
|
2020-02-02T18:05:15.000Z
|
#pragma once
#include "core.hpp"
#include "hooke.hpp"
| 11
| 20
| 0.709091
|
sbrisard
|
4ca7939ee1f48050997521e86ce834c26a8bd999
| 222
|
cpp
|
C++
|
HDUOJ/2107.cpp
|
LzyRapx/Competitive-Programming
|
6b0eea727f9a6444700a6966209397ac7011226f
|
[
"Apache-2.0"
] | 81
|
2018-06-03T04:27:45.000Z
|
2020-09-13T09:04:12.000Z
|
HDUOJ/2107.cpp
|
Walkerlzy/Competitive-algorithm
|
6b0eea727f9a6444700a6966209397ac7011226f
|
[
"Apache-2.0"
] | null | null | null |
HDUOJ/2107.cpp
|
Walkerlzy/Competitive-algorithm
|
6b0eea727f9a6444700a6966209397ac7011226f
|
[
"Apache-2.0"
] | 21
|
2018-07-11T04:02:38.000Z
|
2020-07-18T20:31:14.000Z
|
#include <stdio.h>
int main()
{
int t,a,max;
while(scanf("%d",&t)!=EOF &&t!=0)
{
max=0;
while(t--)
{
scanf("%d",&a);
if(a>max)
{
max=a;
}
}
printf("%d\n",max);
}
return 0;
}
| 11.684211
| 35
| 0.405405
|
LzyRapx
|
4cac1a7f4b7e0ef3200dd3a2e1bda64bde60bf7b
| 1,841
|
cpp
|
C++
|
2018/cpp/src/day23.cpp
|
Chrinkus/advent-of-code
|
b2ae137dc7a1d6fc9e20f29549e891404591c47f
|
[
"MIT"
] | 1
|
2021-12-04T20:55:02.000Z
|
2021-12-04T20:55:02.000Z
|
2018/cpp/src/day23.cpp
|
Chrinkus/advent-of-code
|
b2ae137dc7a1d6fc9e20f29549e891404591c47f
|
[
"MIT"
] | null | null | null |
2018/cpp/src/day23.cpp
|
Chrinkus/advent-of-code
|
b2ae137dc7a1d6fc9e20f29549e891404591c47f
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <get_input.hpp>
class Nanobot {
private:
int xx, yy, zz, rr;
public:
Nanobot() = default;
Nanobot(int x, int y, int z, int r)
: xx{x}, yy{y}, zz{z}, rr{r} { }
int x() const { return xx; }
int y() const { return yy; }
int z() const { return zz; }
int r() const { return rr; }
bool is_in_range(const Nanobot& nb) const;
};
int distance(const Nanobot& a, const Nanobot& b)
{
return std::abs(a.x() - b.x()) +
std::abs(a.y() - b.y()) +
std::abs(a.z() - b.z());
}
bool Nanobot::is_in_range(const Nanobot& other) const
{
return distance(*this, other) <= rr;
}
std::istream& operator>>(std::istream& is, Nanobot& n)
{
char ch;
while (is >> ch && ch != '<')
;
int x, y, z;
is >> x >> ch >> y >> ch >> z;
while (is >> ch && ch != '=')
;
int r;
is >> r;
Nanobot nn { x, y, z, r };
n = nn;
return is;
}
auto parse_input(const std::string& input)
{
std::vector<Nanobot> vnb;
std::istringstream iss { input };
for (Nanobot nb; iss >> nb; )
vnb.emplace_back(nb);
return vnb;
}
int in_range_of_strongest(const std::vector<Nanobot>& vnb)
{
auto it = std::max_element(std::begin(vnb), std::end(vnb),
[](const auto& a, const auto& b) { return a.r() < b.r(); });
return std::count_if(std::begin(vnb), std::end(vnb),
[&it](const auto& nb) { return it->is_in_range(nb); });
}
int main(int argc, char* argv[])
{
std::cout << "AoC 2018 Day 23 - Experimental Emergency Teleportation\n";
auto input = utils::get_input_string(argc, argv, "23");
auto vnb = parse_input(input);
auto part1 = in_range_of_strongest(vnb);
std::cout << "Part 1: " << part1 << '\n';
}
| 21.658824
| 76
| 0.552417
|
Chrinkus
|
4cb6bb1a8df280830bf45e94a50807501bdfce34
| 11,650
|
cpp
|
C++
|
src/matOptimize/transpose_vcf/transposed_vcf_to_fa.cpp
|
abschneider/usher
|
2ebfe7013d69097427cce59585a3ee2edd98773b
|
[
"MIT"
] | 67
|
2020-09-18T23:10:37.000Z
|
2022-02-02T17:58:19.000Z
|
src/matOptimize/transpose_vcf/transposed_vcf_to_fa.cpp
|
abschneider/usher
|
2ebfe7013d69097427cce59585a3ee2edd98773b
|
[
"MIT"
] | 132
|
2020-09-21T03:11:29.000Z
|
2022-03-31T23:19:14.000Z
|
src/matOptimize/transpose_vcf/transposed_vcf_to_fa.cpp
|
abschneider/usher
|
2ebfe7013d69097427cce59585a3ee2edd98773b
|
[
"MIT"
] | 22
|
2020-09-18T20:28:21.000Z
|
2022-03-24T12:17:33.000Z
|
#include "../mutation_annotated_tree.hpp"
#include "src/matOptimize/tree_rearrangement_internal.hpp"
#include "transpose_vcf.hpp"
#include <algorithm>
#include <boost/program_options.hpp>
#include <boost/program_options/value_semantic.hpp>
#include <climits>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <fstream>
#include <iostream>
#include <iterator>
#include <mutex>
#include <string>
#include <tbb/blocked_range.h>
#include <tbb/concurrent_vector.h>
#include <tbb/enumerable_thread_specific.h>
#include <tbb/parallel_for.h>
#include <tbb/pipeline.h>
#include <tbb/task_scheduler_init.h>
#include <unistd.h>
#include <unordered_map>
#include <utility>
#include <vector>
#include <zlib.h>
std::string chrom;
std::string ref;
struct Pos_Mut {
int position;
uint8_t mut;
Pos_Mut(int position, uint8_t mut) : position(position), mut(mut) {}
bool operator<(const Pos_Mut &other) const {
return position < other.position;
}
};
struct Sample_Pos_Mut {
std::string name;
std::vector<Pos_Mut> not_Ns;
std::vector<std::pair<int, int>> Ns;
Sample_Pos_Mut(std::string &&name) : name(std::move(name)) {}
};
struct Sample_Pos_Mut_Printer {
std::vector<Pos_Mut>::const_iterator not_Ns_iter;
const std::vector<Pos_Mut>::const_iterator not_Ns_end;
std::vector<std::pair<int, int>>::const_iterator Ns_iter;
const std::vector<std::pair<int, int>>::const_iterator Ns_end;
Sample_Pos_Mut_Printer(const Sample_Pos_Mut &in)
: not_Ns_iter(in.not_Ns.begin()), not_Ns_end(in.not_Ns.end()),
Ns_iter(in.Ns.begin()), Ns_end(in.Ns.end()) {}
int print(uint8_t *out) {
int end;
if (not_Ns_iter == not_Ns_end ||
(Ns_iter != Ns_end && Ns_iter->first < not_Ns_iter->position)) {
memset(out, 'N', Ns_iter->second - Ns_iter->first + 1);
end = Ns_iter->second;
Ns_iter++;
} else {
*out = Mutation_Annotated_Tree::get_nuc(not_Ns_iter->mut);
end = not_Ns_iter->position;
not_Ns_iter++;
}
assert(not_Ns_iter<=not_Ns_end&&Ns_iter<=Ns_end);
return end;
}
int next_pos() const {
auto next_pos=std::min(not_Ns_end == not_Ns_iter ? INT_MAX
: not_Ns_iter->position,
Ns_end == Ns_iter ? INT_MAX : Ns_iter->first);
assert(next_pos!=INT_MAX);
return (next_pos);
}
operator bool() const {
return (Ns_iter != Ns_end) || (not_Ns_iter != not_Ns_end);
}
};
struct Sample_Pos_Mut_Wrap {
Sample_Pos_Mut &content;
void add_Not_N(int position, uint8_t allele) {
content.not_Ns.emplace_back(position-1, allele);
}
void add_N(int first, int second) {
content.Ns.emplace_back(first-1, second-1);
}
};
typedef tbb::enumerable_thread_specific<std::vector<Sample_Pos_Mut>>
sample_pos_mut_local_t;
sample_pos_mut_local_t sample_pos_mut_local;
struct All_Sample_Appender {
Sample_Pos_Mut_Wrap set_name(std::string &&name) {
sample_pos_mut_local_t::reference my_sample_pos_mut_local =
sample_pos_mut_local.local();
my_sample_pos_mut_local.emplace_back(std::move(name));
return Sample_Pos_Mut_Wrap{my_sample_pos_mut_local.back()};
}
};
void load_reference(const char *ref_path, std::string &seq_name,
std::string &reference) {
std::ifstream fasta_f(ref_path);
std::string temp;
std::getline(fasta_f, temp);
seq_name = temp.substr(1, 50);
while (fasta_f) {
std::getline(fasta_f, temp);
reference += temp;
}
}
namespace po = boost::program_options;
size_t write_sample(uint8_t *out, const Sample_Pos_Mut &in,
const std::string &seq) {
out[0] = '>';
memcpy(out + 1, in.name.c_str(), in.name.size());
out[1 + in.name.size()] = '\n';
auto start_offset = 2 + in.name.size();
int last_print = 0;
Sample_Pos_Mut_Printer printer(in);
while (printer) {
auto next = printer.next_pos();
assert(next<seq.size());
auto ref_print_siz = next - last_print;
memcpy(out + last_print + start_offset, seq.data() + last_print,
ref_print_siz);
last_print = printer.print(out + next + start_offset) + 1;
assert(last_print<seq.size());
}
memcpy(out + last_print + start_offset, seq.data() + last_print,
seq.size() - last_print);
out[start_offset + seq.size()] = '\n';
return start_offset + seq.size() + 1;
}
#define OUT_BUF_SIZ 0x100000
struct Batch_Printer {
const std::vector<Sample_Pos_Mut> ∈
const std::string &seq;
const size_t inbuf_siz;
const int fd;
std::mutex& out_mutex;
mutable z_stream stream;
mutable uint8_t *inbuf;
mutable uint8_t *outbuf;
Batch_Printer(const std::vector<Sample_Pos_Mut> &in, const std::string &seq,
size_t inbuf_siz,int fd,std::mutex& out_mutex)
: in(in), seq(seq), inbuf_siz(inbuf_siz),fd(fd),out_mutex(out_mutex), inbuf(nullptr),
outbuf(nullptr) {
stream.opaque = nullptr;
stream.zalloc = nullptr;
stream.zfree = nullptr;
}
Batch_Printer(const Batch_Printer &other)
: in(other.in), seq(other.seq), inbuf_siz(other.inbuf_siz),fd(other.fd), out_mutex(other.out_mutex),inbuf(nullptr),
outbuf(nullptr) {
stream.opaque = nullptr;
stream.zalloc = nullptr;
stream.zfree = nullptr;
}
void init() const {
if (!inbuf) {
inbuf=(uint8_t*) malloc(inbuf_siz);
outbuf=(uint8_t*) malloc(OUT_BUF_SIZ);
//auto err =
deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
15 | 16, 9, Z_DEFAULT_STRATEGY);
//assert(err==Z_OK);
} else {
//auto err=
deflateReset(&stream);
//assert(err==Z_OK);
}
stream.avail_out=OUT_BUF_SIZ;
stream.next_out=outbuf;
}
void output()const {
if (stream.avail_out<OUT_BUF_SIZ/2) {
//auto err =
deflate(&stream, Z_FINISH);
//assert(err==Z_STREAM_END);
out_mutex.lock();
auto out=write(fd,outbuf,stream.next_out-outbuf);
if (out!=stream.next_out-outbuf) {
fprintf(stderr, "Couldn't output\n");
exit(EXIT_FAILURE);
}
out_mutex.unlock();
deflateReset(&stream);
stream.avail_out=OUT_BUF_SIZ;
stream.next_out=outbuf;
}
}
void operator()(tbb::blocked_range<size_t> range) const {
//fprintf(stderr, "%zu ",range.size());
init();
stream.avail_out = OUT_BUF_SIZ;
stream.next_out = outbuf;
for (size_t samp_idx = range.begin(); samp_idx < range.end();
samp_idx++) {
auto bytes_written=write_sample(inbuf, in[samp_idx], seq);
stream.next_in=inbuf;
stream.avail_in=bytes_written;
auto err = deflate(&stream, Z_NO_FLUSH);
assert(stream.avail_out);
if (err!=Z_OK) {
fprintf(stderr, "%d\n",err);
}
assert(err==Z_OK);
output();
}
//auto err =
deflate(&stream, Z_FINISH);
//assert(err==Z_STREAM_END);
out_mutex.lock();
auto written_bytes=write(fd, outbuf, stream.next_out-outbuf);
if (written_bytes!=stream.next_out-outbuf) {
fprintf(stderr, "Couldn't output\n");
exit(EXIT_FAILURE);
}
out_mutex.unlock();
}
~Batch_Printer() {
if (inbuf) {
free(inbuf);
free(outbuf);
deflateEnd(&stream);
}
}
};
int main(int argc, char **argv) {
po::options_description desc{"Options"};
uint32_t num_cores = tbb::task_scheduler_init::default_num_threads();
std::string output_fa_file;
std::string input_path;
std::string rename_file;
uint32_t num_threads;
std::string reference;
std::string num_threads_message = "Number of threads to use when possible "
"[DEFAULT uses all available cores, " +
std::to_string(num_cores) +
" detected on this machine]";
desc.add_options()(
"fa,o", po::value<std::string>(&output_fa_file)->required(),
"Output FASTA file (in uncompressed or gzip-compressed .gz format) ")(
"threads,T",
po::value<uint32_t>(&num_threads)->default_value(num_cores),
num_threads_message
.c_str())("reference,r",
po::value<std::string>(&reference)->required(),
"Reference file")("samples,s",
po::value<std::string>(&rename_file),
"rename file")("output_path,i",
po::value<std::string>(
&input_path)
->required(),
"Load transposed VCF");
po::options_description all_options;
all_options.add(desc);
po::variables_map vm;
try {
po::store(
po::command_line_parser(argc, argv).options(all_options).run(), vm);
po::notify(vm);
} catch (std::exception &e) {
std::cerr << desc << std::endl;
// Return with error code 1 unless the user specifies help
if (vm.count("help"))
return 0;
else
return 1;
}
std::unordered_map<std::string, std::string> rename_mapping;
if (rename_file != "") {
parse_rename_file(rename_file, rename_mapping);
}
tbb::task_scheduler_init init(num_threads);
load_reference(reference.c_str(), chrom, ref);
All_Sample_Appender appender;
load_mutations(input_path.c_str(), 80, appender);
std::vector<Sample_Pos_Mut> all_samples;
if (rename_mapping.empty()) {
for (auto &sample_block : sample_pos_mut_local) {
all_samples.insert(all_samples.end(),
std::make_move_iterator(sample_block.begin()),
std::make_move_iterator(sample_block.end()));
}
} else {
all_samples.reserve(rename_mapping.size());
for (auto &sample_block : sample_pos_mut_local) {
for (const auto &sample : sample_block) {
auto iter = rename_mapping.find(sample.name);
if (iter != rename_mapping.end()) {
all_samples.push_back(std::move(sample));
all_samples.back().name = iter->second;
rename_mapping.erase(iter);
}
}
sample_block.clear();
}
}
for (const auto &name : rename_mapping) {
fprintf(stderr, "sample %s not found \n", name.first.c_str());
}
size_t max_name_len=0;
for(const auto& samp:all_samples) {
max_name_len=std::max(max_name_len,samp.name.size());
}
auto inbuf_size=max_name_len+ref.size()+8;
auto out_fd=open(output_fa_file.c_str(),O_WRONLY|O_CREAT|O_TRUNC,S_IRWXU|S_IRWXG|S_IRWXO);
std::mutex f_mutex;
tbb::parallel_for(tbb::blocked_range<size_t>(0,all_samples.size(),all_samples.size()/num_threads), Batch_Printer{all_samples,ref,inbuf_size,out_fd,f_mutex});
close(out_fd);
}
| 36.984127
| 161
| 0.587039
|
abschneider
|
4cb793464cc29ff53929ee5a538f85ec609d9828
| 3,614
|
cpp
|
C++
|
src/cpp/event/PeriodicEventHandler.cpp
|
rockstarartist/DDS-Router
|
245099e5e1be584e9d37e9b16648183ab383d727
|
[
"Apache-2.0"
] | 1
|
2021-11-15T08:16:58.000Z
|
2021-11-15T08:16:58.000Z
|
src/cpp/event/PeriodicEventHandler.cpp
|
rockstarartist/DDS-Router
|
245099e5e1be584e9d37e9b16648183ab383d727
|
[
"Apache-2.0"
] | 18
|
2021-08-30T09:19:30.000Z
|
2021-11-16T07:17:38.000Z
|
src/cpp/event/PeriodicEventHandler.cpp
|
rockstarartist/DDS-Router
|
245099e5e1be584e9d37e9b16648183ab383d727
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/**
* @file PeriodicEventHandler.cpp
*
*/
#include <ddsrouter/types/Log.hpp>
#include <ddsrouter/event/PeriodicEventHandler.hpp>
#include <ddsrouter/exceptions/InitializationException.hpp>
namespace eprosima {
namespace ddsrouter {
namespace event {
PeriodicEventHandler::PeriodicEventHandler(
Duration_ms period_time)
: EventHandler<>()
, period_time_(period_time)
, timer_active_(false)
{
// In case period time is set to 0, the object is not created
if (period_time <= 0)
{
throw InitializationException("Periodic Event Handler could no be created with period time 0");
}
logDebug(
DDSROUTER_PERIODICHANDLER,
"Periodic Event Handler created with period time " << period_time_ << " .");
}
PeriodicEventHandler::PeriodicEventHandler(
std::function<void()> callback,
Duration_ms period_time)
: PeriodicEventHandler(period_time)
{
set_callback(callback);
}
PeriodicEventHandler::~PeriodicEventHandler()
{
unset_callback();
}
void PeriodicEventHandler::period_thread_routine_() noexcept
{
while (timer_active_.load())
{
std::unique_lock<std::mutex> lock(periodic_wait_mutex_);
// Wait for period time or awake if object has been disabled
wait_condition_variable_.wait_for(
lock,
std::chrono::milliseconds(period_time_),
[this]
{
// Exit if number of events is bigger than expected n
// or if callback is no longer set
return !timer_active_.load();
});
if (!timer_active_.load())
{
break;
}
event_occurred_();
}
}
void PeriodicEventHandler::start_period_thread_nts_() noexcept
{
{
std::unique_lock<std::mutex> lock(periodic_wait_mutex_);
timer_active_.store(true);
}
period_thread_ = std::thread(
&PeriodicEventHandler::period_thread_routine_, this);
logDebug(
DDSROUTER_PERIODICHANDLER,
"Periodic Event Handler thread starts with period time " << period_time_ << " .");
}
void PeriodicEventHandler::stop_period_thread_nts_() noexcept
{
// Set timer as inactive and awake thread so it stops
{
std::unique_lock<std::mutex> lock(periodic_wait_mutex_);
timer_active_.store(false);
}
periodic_wait_condition_variable_.notify_one();
// Wait for the periodic thread to finish as it will skip sleep due to the condition variable
period_thread_.join();
logDebug(
DDSROUTER_PERIODICHANDLER,
"Periodic Event Handler thread stops.");
}
void PeriodicEventHandler::callback_set_nts_() noexcept
{
if (!timer_active_)
{
start_period_thread_nts_();
}
}
void PeriodicEventHandler::callback_unset_nts_() noexcept
{
if (timer_active_)
{
stop_period_thread_nts_();
}
}
} /* namespace event */
} /* namespace ddsrouter */
} /* namespace eprosima */
| 26.573529
| 103
| 0.676259
|
rockstarartist
|
4cb9fbf799d1276b3e2e8c3c7446c741e780dcf1
| 7,204
|
cpp
|
C++
|
hash.cpp
|
grasslog/HashFile
|
e584a0920037ef80dd155142dc39b03e38071430
|
[
"MIT"
] | 3
|
2019-08-28T14:59:21.000Z
|
2019-09-11T20:01:21.000Z
|
hash.cpp
|
grasslog/HashFile
|
e584a0920037ef80dd155142dc39b03e38071430
|
[
"MIT"
] | null | null | null |
hash.cpp
|
grasslog/HashFile
|
e584a0920037ef80dd155142dc39b03e38071430
|
[
"MIT"
] | 1
|
2022-01-03T07:21:59.000Z
|
2022-01-03T07:21:59.000Z
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h> // access()
#include <string.h>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <regex>
#define HASH_FILE_PATH "/home/grasslog/tmp/IP/ip_data.dat"
#define HASH_GENERATION_PATH "/home/grasslog/tmp/hashfile"
#define BUFFER_SIZE 20
const int num = 100000000; // url number
const int TOP_URL_NUMBER = 100;
const int HASH_FILE_NUMBER = 1000;
node top_heap[TOP_URL_NUMBER];
bool is_top_heap = false;
unsigned int iton(char *ip);
void ntoi(unsigned int num, char *ip);
int fileexist(char *path); // judge file exit
void fclose_all(FILE **t); // close all files
int random_write(const char *path); // random generation url address
// calculate top IP address
void count(char *hashfile, unsigned int *data, unsigned int *num);
void sort(unsigned int *max, unsigned int *ip, int n); // sort url
inline unsigned int hash(unsigned int ip) // hash function
{ return (ip % HASH_FILE_NUMBER); }
void swap(node &a, node &b); // local swap struct node function
typedef struct node // storage struct node
{
std::string ip; // IP
unsigned int n; // occurrence number
node(std::string _ip, unsigned int _n):ip(_ip),n(_n) {}
node():ip(""),n(0) {}
}node;
// min root heap
void insert_heap(node *a, int n, int m);
void make_heap(node *a, int m);
int main(void)
{
FILE *in = NULL;
FILE *tmpfile[HASH_FILE_NUMBER];
const char *path = HASH_FILE_PATH;
char hashfile[HASH_FILE_NUMBER];
char buf[BUFFER_SIZE];
unsigned int add, data, n;
unsigned int ip[TOP_URL_NUMBER], max[TOP_URL_NUMBER]; // top 10 IP
unsigned int t1, t2, s, e; // record the time
int i, j, len, now; // IP number
node top_heap[TOP_URL_NUMBER];
bool is_top_heap = false;
printf("Generating data %s\n\n", path);
if (!random_write(path)) return 0; // random generation IP log file
// judge file exit, access() == 0 exit
if (access(HASH_GENERATION_PATH, 0) == 0)
system("rm -r HASH_GENERATION_PATH");
system("mkdir HASH_GENERATION_PATH"); // mkdir /home/grasslog/tmp/hashfile working drectory
//system("attrib +h /home/grasslog/tmp/hashfile");
in = fopen(path, "rt"); // open IP log file
if (in == NULL) return 0;
for (i=0; i<TOP_URL_NUMBER; i++) tmpfile[i] = NULL;
// make 1000000000 IP hash in 1005 small files
printf("\r hashing %s\n\n", "/home/grasslog/tmp/hashfile");
e = s = t1 = clock(); // start time
now = 0;
while (fscanf(in, "%s", buf) != EOF)
{
if(!is_IPAddress_valid(buf)) continue;
data = iton(buf); // IP digitization
add = hash(data); // math hash address
sprintf(hashfile, "/home/grasslog/tmp/hashfile/hashfile_%u.dat", add);
if (tmpfile[add] == NULL)
tmpfile[add] = fopen(hashfile, "a");
sprintf(buf, "%u\n", data);
len = strlen(buf);
// write IP in files, I/O just be the bottlenneck
fwrite(buf, len, 1, tmpfile[add]);
now++;
e = clock();
if (e - s > 1000) // calculate rate of progress
{
printf("\rProcessing progress %0.2f %%\t", (now * 100.0) / num);
s = e;
}
}
fclose(in);
fclose_all(tmpfile);
remove(path);
// calculate top IP in each small files
for (i=0; i<10; i++) max[i] = 0;
for (i=0; i<HASH_FILE_NUMBER; i++)
{
sprintf(hashfile, "/home/grasslog/tmp/hashfile/hashfile_%d.dat", i);
if (fileexist(hashfile))
{
printf("\rProcessing hashfile_%d.dat\t", i);
count(hashfile, &data, &n);
unsigned int min = 0xFFFFFFFF, pos;
for (j=0; j<10; j++)
{
if (max[j] < min)
{
min = max[j];
pos = j;
}
}
if (n > min)
{
max[pos] = n;
ip[pos] = data;
}
}
}
t2 = clock(); // end time
sort(max, ip, 10);
FILE *log = NULL; // record in /home/grasslog/tmp/hashfile/ip_result.txt
log = fopen("/home/grasslog/tmp/hashfile/ip_result.txt", "wt");
fprintf(log, "\ntop 10 IP:\n\n");
fprintf(log, " %-15s%s\n", "IP", "Visits");
printf("\n\ntop 10 IP:\n\n");
printf(" %-15s%s\n", "IP", "Visits");
for (i=0; i<10; i++)
{
ntoi(ip[i], buf); // decord
printf(" %-20s%u\n", buf, max[i]);
fprintf(log, " %-20s%u\n", buf, max[i]);
}
fprintf(log, "\n--- spent %0.3f second\n", (t2 - t1) / 1000.0);
printf("\n--- spent %0.3f second\n\n", (t2 - t1) / 1000.0);
fclose(log);
return 0;
}
void fclose_all(FILE **t) // close all files
{
int i;
for (i=0; i<TOP_URL_NUMBER; i++)
{
if (t[i])
{
fclose(t[i]);
t[i] = NULL;
}
}
}
// random generation url address
int random_write(const char *path)
{
FILE *out = NULL;
int i, j, b;
char buf[20];
char *cur;
unsigned int s, e;
out = fopen(path, "wt");
if (out == NULL) return 0;
srand(time(NULL));
e = s = clock();
for (i=0; i<num; i++)
{
e = clock();
if (e - s > 1000) // calculate rate of progress
{
printf("\rProcessing progress %0.2f %%\t", (i * 100.0) / num);
s = e;
}
for (j=0; j<BUFFER_SIZE; j++) buf[j] = '\0';
cur = buf;
for (j=0; j<4; j++)
{
b = rand() % 256;
sprintf(cur, "%d.", b);
while (*cur != '\0') cur++;
}
*(cur - 1) = '\n';
fwrite(buf, cur-(char *)buf, 1, out);
}
fclose(out); // close IO stream
return 1;
}
// calculate top IP in hashfile
void count(char *hashfile)
{
FILE *in = NULL;
std::string ip;
std::unordered_map<std::string,int> ump;
in = fopen(hashfile, "rt");
while(fscanf(in, "%s", &ip) != EOF)
{
ump[ip]++;
}
std::vector<node> vec_node;
typedef std::unordered_map<std::string,int>::iterator ump_iterator;
for(ump_iterator it=ump.begin(); it!=ump.end(); ++it)
{
node t(it->first,it->second);
vec_node.push_back(t);
}
fclose(in);
if(!is_top_heap)
{
is_top_heap = !is_top_heap;
memcpy(top_heap,&vec_node,sizeof(struct node)*TOP_URL_NUMBER);
make_heap(top_heap,TOP_URL_NUMBER);
for(int i=100; i<vec_node.size(); i++)
{
node t = vec_node[i];
int w = top_heap[0].n;
if(t.n > w)
{
swap(t,top_heap[0]); // local swap function
}
insert_heap(top_heap,0,TOP_URL_NUMBER);
}
}
else
{
for(int i=0; i<vec_node.size(); i++)
{
node t = vec_node[i];
int w = top_heap[0].n;
if(t.n > w)
{
swap(t, top_heap[0]);
}
insert_heap(top_heap,0,TOP_URL_NUMBER);
}
}
}
void insert_heap(node *heap, int n, int m)
{
node t = heap[n];
int w = t.n;
int i = n;
int j = 2 * i + 1;
while(j < m)
{
if(j+1<m && heap[j+1].n<heap[j].n)
++j;
if(heap[j].n < w)
heap[i] = heap[j];
else break;
i = j;
j = 2 * i + 1;
}
heap[j] = t;
}
void make_heap(node *heap, int m)
{
for(int i=m/2; i>=0; i--)
{
insert_heap(heap,i,m);
}
}
// judge file exist
int fileexist(char *path)
{
FILE *fp = NULL;
fp = fopen(path, "rt");
if (fp)
{
fclose(fp);
return 1;
}
else return 0;
}
// IP to int
unsigned int iton(char *ip)
{
unsigned int r = 0;
unsigned int t;
int i, j;
for (j=i=0; i<4; i++)
{
sscanf(ip + j, "%d", &t);
if (i < 3)
while (ip[j++] != '.');
r = r << 8;
r += t;
}
return r;
}
// bool url address legal
bool is_IPAddress_valid(const std::string& ipaddress)
{
const std::regex pattern("(\\d{1,3}).(\\d{1,3}).(\\d{1,3}).(\\d{1,3})");
std:: match_results<std::string::const_iterator> result;
bool valid = std::regex_match(ipaddress, result, pattern);
return valid;
}
| 22.09816
| 94
| 0.605636
|
grasslog
|
4cc172bcf8fda07b80f44d708011859e28dac03d
| 3,615
|
cpp
|
C++
|
source/fir/Types/UnionType.cpp
|
zhiayang/flax
|
a7ead8ad3ff4ea377297495751bd4802f809547b
|
[
"Apache-2.0"
] | 1
|
2021-02-07T08:42:06.000Z
|
2021-02-07T08:42:06.000Z
|
source/fir/Types/UnionType.cpp
|
zhiayang/flax
|
a7ead8ad3ff4ea377297495751bd4802f809547b
|
[
"Apache-2.0"
] | null | null | null |
source/fir/Types/UnionType.cpp
|
zhiayang/flax
|
a7ead8ad3ff4ea377297495751bd4802f809547b
|
[
"Apache-2.0"
] | null | null | null |
// UnionType.cpp
// Copyright (c) 2014 - 2016, zhiayang@gmail.com
// Licensed under the Apache License Version 2.0.
#include "errors.h"
#include "ir/type.h"
#include "pts.h"
namespace fir
{
// structs
UnionType::UnionType(const Identifier& name, const std::unordered_map<std::string, std::pair<size_t, Type*>>& mems)
: Type(TypeKind::Union)
{
this->unionName = name;
this->setBody(mems);
}
static std::unordered_map<Identifier, UnionType*> typeCache;
UnionType* UnionType::create(const Identifier& name, const std::unordered_map<std::string, std::pair<size_t, Type*>>& mems)
{
if(auto it = typeCache.find(name); it != typeCache.end())
error("Union with name '%s' already exists", name.str());
else
return (typeCache[name] = new UnionType(name, mems));
}
UnionType* UnionType::createWithoutBody(const Identifier& name)
{
return UnionType::create(name, { });
}
// various
std::string UnionType::str()
{
return "union(" + this->unionName.name + ")";
}
std::string UnionType::encodedStr()
{
return this->unionName.str();
}
bool UnionType::isTypeEqual(Type* other)
{
if(other->kind != TypeKind::Union)
return false;
return (this->unionName == other->toUnionType()->unionName);
}
// struct stuff
Identifier UnionType::getTypeName()
{
return this->unionName;
}
size_t UnionType::getVariantCount()
{
return this->variants.size();
}
size_t UnionType::getIdOfVariant(const std::string& name)
{
if(auto it = this->variants.find(name); it != this->variants.end())
return it->second->variantId;
else
error("no variant with name '%s'", name);
}
std::unordered_map<std::string, UnionVariantType*> UnionType::getVariants()
{
return this->variants;
}
bool UnionType::hasVariant(const std::string& name)
{
return this->variants.find(name) != this->variants.end();
}
UnionVariantType* UnionType::getVariant(size_t id)
{
if(auto it = this->indexMap.find(id); it != this->indexMap.end())
return it->second;
else
error("no variant with id %d", id);
}
UnionVariantType* UnionType::getVariant(const std::string& name)
{
if(auto it = this->variants.find(name); it != this->variants.end())
return it->second;
else
error("no variant named '%s' in union '%s'", name, this->getTypeName().str());
}
void UnionType::setBody(const std::unordered_map<std::string, std::pair<size_t, Type*>>& members)
{
for(const auto& [ n, p ] : members)
{
auto uvt = new UnionVariantType(this, p.first, n, p.second);
this->variants[n] = uvt;
this->indexMap[p.first] = uvt;
}
}
fir::Type* UnionType::substitutePlaceholders(const std::unordered_map<Type*, Type*>& subst)
{
if(this->containsPlaceholders())
error("not supported!");
return this;
}
std::string UnionVariantType::str()
{
return this->parent->str() + "." + this->name;
}
std::string UnionVariantType::encodedStr()
{
return this->parent->encodedStr() + "." + this->name;
}
bool UnionVariantType::isTypeEqual(Type* other)
{
if(auto uvt = dcast(UnionVariantType, other))
return uvt->parent == this->parent && uvt->name == this->name;
return false;
}
fir::Type* UnionVariantType::substitutePlaceholders(const std::unordered_map<fir::Type*, fir::Type*>& subst)
{
if(this->containsPlaceholders())
error("not supported!");
return this;
}
UnionVariantType::UnionVariantType(UnionType* p, size_t id, const std::string& name, Type* actual) : Type(TypeKind::UnionVariant)
{
this->parent = p;
this->name = name;
this->variantId = id;
this->interiorType = actual;
}
}
| 18.634021
| 130
| 0.665007
|
zhiayang
|
4cc6d8d77fb76a8f2098c58bd1faa240ff981ee2
| 333
|
hpp
|
C++
|
example/include/my_components.hpp
|
wtfsystems/wtengine
|
0fb56d6eb2ac6359509e7a52876c8656da6b3ce0
|
[
"MIT"
] | 7
|
2020-06-16T18:47:35.000Z
|
2021-08-25T13:41:13.000Z
|
example/include/my_components.hpp
|
wtfsystems/wtengine
|
0fb56d6eb2ac6359509e7a52876c8656da6b3ce0
|
[
"MIT"
] | 15
|
2020-07-23T14:03:39.000Z
|
2022-01-28T02:32:07.000Z
|
example/include/my_components.hpp
|
wtfsystems/wtengine
|
0fb56d6eb2ac6359509e7a52876c8656da6b3ce0
|
[
"MIT"
] | null | null | null |
/*
* WTEngine Demo
* By: Matthew Evans
* File: my_components.hpp
*
* See LICENSE.txt for copyright information
*
* Include all custom components here.
*/
#ifndef MY_COMPONENTS_HPP
#define MY_COMPONENTS_HPP
#include "damage.hpp"
#include "energy.hpp"
#include "health.hpp"
#include "size.hpp"
#include "stars.hpp"
#endif
| 15.857143
| 44
| 0.720721
|
wtfsystems
|
4cc7b5ebae3b2887407e1c7365e42cefabdf25f6
| 13,970
|
cpp
|
C++
|
src/bckp/08-12/a/waves.cpp
|
antocreo/BYO_Master
|
d92e049f10775d99fc6ef8aab7093c923142e664
|
[
"MIT"
] | null | null | null |
src/bckp/08-12/a/waves.cpp
|
antocreo/BYO_Master
|
d92e049f10775d99fc6ef8aab7093c923142e664
|
[
"MIT"
] | 1
|
2017-02-12T15:28:29.000Z
|
2017-02-23T10:34:04.000Z
|
src/bckp/08-12/a/waves.cpp
|
antocreo/BYO_Master
|
d92e049f10775d99fc6ef8aab7093c923142e664
|
[
"MIT"
] | null | null | null |
//
// Mfcc_obj.cpp
// OculusRenderingBasic
//
// Created by Let it Brain on 28/03/2015.
//
//
#include "Mfcc_obj.h"
#include "maximilian.h"/* include the lib */
#include "time.h"
//-------------------------------------------------------------
Mfcc_obj::Mfcc_obj() {
}
//-------------------------------------------------------------
Mfcc_obj::~Mfcc_obj() {
}
//--------------------------------------------------------------
void Mfcc_obj::setup(){
/* some standard setup stuff*/
// ofEnableAlphaBlending();
// ofSetupScreen();
// ofBackground(0, 0, 0);
// ofSetFrameRate(60);
// ofSetVerticalSync(true);
/* This is stuff you always need.*/
sampleRate = 44100; /* Sampling Rate */
initialBufferSize = 512; /* Buffer Size. you have to fill this buffer with sound*/
lAudioOut = new float[initialBufferSize];/* outputs */
rAudioOut = new float[initialBufferSize];
lAudioIn = new float[initialBufferSize];/* inputs */
rAudioIn = new float[initialBufferSize];
/* This is a nice safe piece of code */
memset(lAudioOut, 0, initialBufferSize * sizeof(float));
memset(rAudioOut, 0, initialBufferSize * sizeof(float));
memset(lAudioIn, 0, initialBufferSize * sizeof(float));
memset(rAudioIn, 0, initialBufferSize * sizeof(float));
fftSize = 1024;
mfft.setup(fftSize, 512, 256);
ifft.setup(fftSize, 512, 256);
nAverages = 13;
oct.setup(sampleRate, fftSize/2, nAverages);
mfccs = (double*) malloc(sizeof(double) * nAverages);
vowel = (double*) malloc(sizeof(double) * nAverages);
mfcc.setup(512, 56, nAverages, 20, 20000, sampleRate);
ofxMaxiSettings::setup(sampleRate, 2, initialBufferSize);
// ofSoundStreamSetup(2,2, this, sampleRate, initialBufferSize, 4);/* Call this last ! *///this is the original one contains "this" that is not accepted here.... why???
//i repleaced it with this line.
ofSoundStreamSetup(2,2, sampleRate, initialBufferSize, 4);/* Call this last ! */
//
mousePos.set(ofGetMouseX(), ofGetMouseY());
//setting boolean all to false
recording, recordingEnded = false;
recordingA,recordingE,recordingI,recordingO,recordingU =false;
//GL
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
ofVec3f dummyPos(0,0,0);
for (int i=0; i<nAverages; i++) {
mesh.addVertex(dummyPos);
mesh2.addVertex(dummyPos);
}
// strip.getMesh() = meshWarped;
// = ofMesh::sphere(200,300);
centroid2 = mesh2.getCentroid();
centroid1 = mesh.getCentroid();
}
//--------------------------------------------------------------
void Mfcc_obj::update(){
for (int i=0; i<meshPoints.size(); i++) {
if (mfccs[0]>1.2 ) {
//this is the displacement factor vector that I will multiply on the original vector strip.getMesh.getVert
displacementVec.set(mfccs[i+0], mfccs[i+1], mfccs[i+2]);
//once I get the displacement vec I need to multiply (getCrossed) with the original vector.getMesh.getVert
ofVec3f rmsvec(rms,rms,rms);
meshPoints[i] = (meshPoints[i] + displacementVec + rms);
// meshPoints[i] += displacementVec.getCrossed(rmsvec);
// meshPoints[i] = meshPoints[i] + mesh.getVertex(i);
// meshPoints[i] = meshPoints[i].interpolate((meshPoints[i].getCrossed(displacementVec)),1);
newCentr1 = centroid1;
newCentr2 = centroid2;
} else {
meshPoints[i] = originalMesh[i];
}
}
}
//--------------------------------------------------------------
void Mfcc_obj::draw(){
//grid
// ofPushStyle();
// ofSetColor(100, 0, 0,100);
// ofDrawGrid(ofGetHeight(), 50.0f, false, false, false, true);
// ofPopStyle();
//end grid
//show bitmap info
// bitmapInfo();
// draw MFcc bar chart
// drawMfccBars( 10, 100);
// draw RMS
// drawRms(10, 50);
/*---------------------------*/
//polygon and centroid
if (mfccs[0]>1.2) {
distancentroids1 = centroid1.distance(newCentr1);
distancentroids2 = centroid2.distance(newCentr2);
// doodle lines
ofPushStyle();
ofNoFill();
ofPushMatrix();
mesh.setMode(OF_PRIMITIVE_LINE_LOOP);
ofTranslate(ofGetWidth()/2, ofGetHeight()/2);
int scaleFactor = 50;
for (int i=0; i<nAverages; i++) {
mesh.addVertex(ofVec2f(mfccs[i+1]*scaleFactor,mfccs[i]*scaleFactor));
mesh.addColor(255);
}
mesh.draw();
//centroid
centroid1 = mesh.getCentroid();
ofDrawBitmapStringHighlight("centroid1 - " + ofToString( centroid1 ), 100,70);
ofSetColor(255,0,0);
ofCircle(centroid1.x, centroid1.y, mfccs[0]*2);
mesh.clear();
ofPopMatrix();
ofPopStyle();
/*---------------------------*/
//graph
ofPushStyle();
ofPushMatrix();
// mesh2.setMode(OF_PRIMITIVE_LINE_LOOP);
// mesh2.setMode(OF_PRIMITIVE_TRIANGLE_STRIP );
mesh2.setMode(OF_PRIMITIVE_TRIANGLE_FAN );
ofTranslate(0, ofGetHeight()/2-100);
int scaleFactor2 = 30;
for (int i=0; i<nAverages; i++) {
mesh2.addVertex(ofVec2f(mfccs[0]*scaleFactor2*i,mfccs[i]*scaleFactor2));
mesh2.addColor(255);
}
// mesh2.addVertex(ofVec2f(mfccs[nAverages]*scaleFactor2,mfccs[0]*scaleFactor2*nAverages));
mesh2.draw();
//centroid
centroid2 = mesh2.getCentroid();
ofDrawBitmapStringHighlight("centroid2 - " + ofToString( centroid2 ), 100,70);
ofSetColor(255,0,0);
ofSetCircleResolution(100);
ofCircle(centroid2.x, centroid2.y, mfccs[0]*scaleFactor/4);
mesh2.clear();
ofPopMatrix();
ofPopStyle();
}
/*---------------------------*/
glEnable(GL_DEPTH_TEST);
for(int i = 0; i < meshPoints.size(); i++){
ofDrawBitmapStringHighlight(ofToString( meshPoints.size() ), 10,50);
ofDrawBitmapStringHighlight(ofToString( sizeof(mfccs) ), 10,80);
ofDrawBitmapStringHighlight(ofToString( ofToString( mfccs[i] ) ), 10,110);
ofDrawBitmapStringHighlight(ofToString( ofToString( displacementVec ) ), 10, 140);
ofDrawBitmapStringHighlight(ofToString( ofToString( mesh.getNumVertices() ) ), 10, 160);
glDisable(GL_DEPTH_TEST);
strip.generate(meshPoints, 5+mfccs[i%nAverages], ofPoint (0,0.5,0.5) );
float colorvoice = 100*(meshPoints.size()%255 * mfccs[i%nAverages]);
ofSetColor(200, 0,0 );
// ofQuaternion orientation(90, 0, 0, 0);
// cam.setOrientation(orientation);
// cam.setTarget(meshPoints[i]);
// cam.setPosition(cam.worldToScreen(meshPoints[i]));
}
// cam.begin();
strip.getMesh().draw();
// cam.end();
}
//--------------------------------------------------------------
void Mfcc_obj::audioRequested (float * output, int bufferSize, int nChannels){
// static double tm;
for (int i = 0; i < bufferSize; i++){
wave = lAudioIn[i];
//get fft
if (mfft.process(wave)) {
mfcc.mfcc(mfft.magnitudes, mfccs);
//cout << mfft.spectralFlatness() << ", " << mfft.spectralCentroid() << endl;
}
}
getVowel();
}
//--------------------------------------------------------------
void Mfcc_obj::audioReceived (float * input, int bufferSize, int nChannels){
//rms
// calculate a rough volume
/* You can just grab this input and stick it in a double, then use it above to create output*/
for (int i = 0; i < bufferSize; i++){
/* you can also grab the data out of the arrays*/
lAudioIn[i] = input[i*2];
rAudioIn[i] = input[i*2+1];
// cout << lAudioIn[i] << endl;
rms =sqrt( (lAudioIn[i]*lAudioIn[i])+(lAudioIn[i]*lAudioIn[i])/bufferSize );
// cout << rms << endl;
}
}
//--------------------------------------------------------------
void Mfcc_obj::getRms(){
// alternative code
rms = 0.0;
int numCounted = 0;
for (int i = 0; i < initialBufferSize; i++){
float leftSample = lAudioIn[i] * 0.5;
float rightSample = rAudioIn[i] * 0.5;
rms += leftSample * leftSample;
rms += rightSample * rightSample;
numCounted += 2;
}
rms /= (float)numCounted;
rms = sqrt(rms);
// rms is now calculated
}
//--------------------------------------------------------------
void Mfcc_obj::getVowel(){
//checking that the coeff[0] > 0 and therefore there is someone speaking
//until there is voice assign the values of mfcc to vowel
for (int i=0; i<nAverages; i++) {
if (mfccs[0]>=1.2) {
vowel[i]=mfccs[i];
storing.push_back(mfccs[i]);
// vowel.push_back(mfccs[i]);
}
}
}
//--------------------------------------------------------------
void Mfcc_obj::drawMfccBars( float x, float y){
ofPushMatrix();
ofTranslate( x, y);
// cout << "\nMFCCS: ";
ofSetColor(255, 0, 0,100);
float xinc = 900.0 / nAverages;
for(int i=0; i < nAverages; i++) {
float height = mfccs[i]*250;
height = ofClamp(height, 0, 250);
ofRect(10 + (i*xinc),600 - height,40, height);
// cout << mfccs[i] << ",";
if (vowel[0]>1) {
// ofRect(ofGetWidth()/2, ofGetHeight()/2, 100, 100);
}
}
// cout << "\n-------" << endl;
// cout << callTime << endl;
ofPopMatrix();
}
//--------------------------------------------------------------
void Mfcc_obj::drawRms(float x, float y){
// rms peak
for(int i=0; i < initialBufferSize; i++) {
ofRect(x, y, rms*1000.0f, 100);
}
}
//--------------------------------------------------------------
void Mfcc_obj::bitmapInfo(){
/// bitmap info
ofPushStyle();
for(int i=0; i < nAverages; i++) {
ofDrawBitmapStringHighlight("rms " + ofToString( rms ),10,30);
ofDrawBitmapStringHighlight("mfcc elem [" +ofToString(i) +"] " + ofToString( mfccs[i] ),300,50+20*i);
// ofDrawBitmapStringHighlight("vowel elem [" +ofToString(i) +"] " + ofToString( vowel[i] ),10,50+20*i);
// if (storing.size()>0) {
// ofDrawBitmapStringHighlight("storing elem [" +ofToString(i) +"] " + ofToString( storing[i] ),10,50+20*i);
// ofDrawBitmapStringHighlight("storing size" + ofToString(storing.size()),10,50+20*i+20);
// }
if (mfccComponent.size()>0) {
ofDrawBitmapStringHighlight("component elem [" +ofToString(i) +"] " + ofToString( mfccComponent[i] ),10,50+20*i);
ofDrawBitmapStringHighlight("component size" + ofToString(mfccComponent.size()),10,50+20*i+20);
}
}
ofPopStyle();
}
//--------------------------------------------------------------
void Mfcc_obj::tempStorage(vector<double> tempVec){
}
//--------------------------------------------------------------
void Mfcc_obj::keyPressed(int key){
if (key == ' ') {
recording = ! recording;
if (recording==true) {
}
}
if (key ==OF_KEY_BACKSPACE) {
meshPoints.clear();
polyMesh.clear();
}
}
//--------------------------------------------------------------
void Mfcc_obj::keyReleased(int key){
}
//--------------------------------------------------------------
void Mfcc_obj::mouseMoved(int x, int y ){
ofVec3f mouseP(x,y);
if (x>1 && y >1) {
meshPoints.push_back(mouseP);
originalMesh = meshPoints;
}
}
//--------------------------------------------------------------
void Mfcc_obj::mouseDragged(int x, int y, int button){
// ofVec3f mouseP(x,y);
// if (x>1 && y >1) {
// meshPoints.push_back(mouseP);
// originalMesh = meshPoints;
//
//
// }
}
//--------------------------------------------------------------
void Mfcc_obj::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void Mfcc_obj::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void Mfcc_obj::windowResized(int w, int h){
}
//--------------------------------------------------------------
void Mfcc_obj::eucliDistanc(){
/*euclidean distance
the first value of the mfcc od actually the pwer of the voice. if I say that mfcc[0]< some value (i need to map it) the I can start detecting the single value)
*/
// for(int i=0; i < nAverages; i++) {
// eucliDist = sqrt(mfcc[i] )
//
// }
}
| 26.358491
| 175
| 0.475734
|
antocreo
|
4cc7f3eb8d7ef3b806956583b7acec23cb238b21
| 2,133
|
cpp
|
C++
|
CmdPacketDownload.cpp
|
lotusczp/XcpMaster
|
47cf2df7e111e823525347faf1cc6cbca6ec3c5d
|
[
"MIT"
] | 1
|
2021-09-04T12:23:20.000Z
|
2021-09-04T12:23:20.000Z
|
CmdPacketDownload.cpp
|
lotusczp/XcpMaster
|
47cf2df7e111e823525347faf1cc6cbca6ec3c5d
|
[
"MIT"
] | null | null | null |
CmdPacketDownload.cpp
|
lotusczp/XcpMaster
|
47cf2df7e111e823525347faf1cc6cbca6ec3c5d
|
[
"MIT"
] | 1
|
2021-11-16T06:57:56.000Z
|
2021-11-16T06:57:56.000Z
|
#include "CmdPacketDownload.h"
CmdPacketDownload::CmdPacketDownload()
: CmdPacket()
{
m_idField.append(CTO::DOWNLOAD);
m_dataField.resize(5);
}
void CmdPacketDownload::setNumberOfDataElements(uint8_t a_byNum)
{
m_dataField[0] = a_byNum;
}
uint8_t CmdPacketDownload::getNumberOfDataElements()
{
return m_dataField[0];
}
uint32_t CmdPacketDownload::getDataElements(bool a_bIsLittleEndian)
{
if(a_bIsLittleEndian) {
return (((uint32_t)m_dataField[4]) << 24) | (((uint32_t)m_dataField[3]) << 16) | (((uint32_t)m_dataField[2]) << 8) | m_dataField[1];
}
else {
//do byte-swap
return (((uint32_t)m_dataField[1]) << 24) | (((uint32_t)m_dataField[2]) << 16) | (((uint32_t)m_dataField[3]) << 8) | m_dataField[4];
}
}
void CmdPacketDownload::setDataElements(uint32_t a_dwData, bool a_bIsLittleEndian)
{
uint8_t i1, i2, i3, i4;
i1 = a_dwData & 0xFF;
i2 = (a_dwData >> 8) & 0xFF;
i3 = (a_dwData >> 16) & 0xFF;
i4 = (a_dwData >> 24) & 0xFF;
if(a_bIsLittleEndian) {
if(m_dataField[0] == 4) {
m_dataField[1] = i1;
m_dataField[2] = i2;
m_dataField[3] = i3;
m_dataField[4] = i4;
}
else if(m_dataField[0] == 2) {
m_dataField[1] = i1;
m_dataField[2] = i2;
m_dataField[3] = 0;
m_dataField[4] = 0;
}
else if(m_dataField[0] == 1) {
m_dataField[1] = i1;
m_dataField[2] = 0;
m_dataField[3] = 0;
m_dataField[4] = 0;
}
}
else {
if(m_dataField[0] == 4) {
m_dataField[1] = i4;
m_dataField[2] = i3;
m_dataField[3] = i2;
m_dataField[4] = i1;
}
else if(m_dataField[0] == 2) {
m_dataField[1] = i2;
m_dataField[2] = i1;
m_dataField[3] = 0;
m_dataField[4] = 0;
}
else if(m_dataField[0] == 1) {
m_dataField[1] = i1;
m_dataField[2] = 0;
m_dataField[3] = 0;
m_dataField[4] = 0;
}
}
}
| 26.6625
| 141
| 0.524144
|
lotusczp
|
4cc7f41de52bf5dc37c2db2d46827347bc049e87
| 7,047
|
cpp
|
C++
|
src/BabylonCpp/src/cameras/inputs/follow_camera_keyboard_move_input.cpp
|
samdauwe/BabylonCpp
|
eea9f761a49bb460ff1324c20e4674ef120e94f1
|
[
"Apache-2.0"
] | 277
|
2017-05-18T08:27:10.000Z
|
2022-03-26T01:31:37.000Z
|
src/BabylonCpp/src/cameras/inputs/follow_camera_keyboard_move_input.cpp
|
samdauwe/BabylonCpp
|
eea9f761a49bb460ff1324c20e4674ef120e94f1
|
[
"Apache-2.0"
] | 77
|
2017-09-03T15:35:02.000Z
|
2022-03-28T18:47:20.000Z
|
src/BabylonCpp/src/cameras/inputs/follow_camera_keyboard_move_input.cpp
|
samdauwe/BabylonCpp
|
eea9f761a49bb460ff1324c20e4674ef120e94f1
|
[
"Apache-2.0"
] | 37
|
2017-03-30T03:36:24.000Z
|
2022-01-28T08:28:36.000Z
|
#include <babylon/cameras/inputs/follow_camera_keyboard_move_input.h>
#include <babylon/engines/engine.h>
#include <babylon/engines/scene.h>
#include <babylon/events/keyboard_event_types.h>
namespace BABYLON {
FollowCameraKeyboardMoveInput::FollowCameraKeyboardMoveInput()
: keysHeightOffsetModifierAlt{false}
, keysHeightOffsetModifierCtrl{false}
, keysHeightOffsetModifierShift{false}
, keysRotationOffsetModifierAlt{false}
, keysRotationOffsetModifierCtrl{false}
, keysRotationOffsetModifierShift{false}
, keysRadiusModifierAlt{false}
, keysRadiusModifierCtrl{false}
, keysRadiusModifierShift{false}
, heightSensibility{1.f}
, rotationSensibility{1.f}
, radiusSensibility{1.f}
, _noPreventDefault{false}
, _onCanvasBlurObserver{nullptr}
, _onKeyboardObserver{nullptr}
, _engine{nullptr}
, _scene{nullptr}
{
keysHeightOffsetIncr.emplace_back(38);
keysHeightOffsetDecr.emplace_back(40);
keysRotationOffsetIncr.emplace_back(37);
keysRotationOffsetDecr.emplace_back(39);
keysRadiusIncr.emplace_back(40);
keysRadiusDecr.emplace_back(38);
}
FollowCameraKeyboardMoveInput::~FollowCameraKeyboardMoveInput() = default;
void FollowCameraKeyboardMoveInput::attachControl(bool noPreventDefault)
{
if (_onCanvasBlurObserver) {
return;
}
_noPreventDefault = noPreventDefault;
_scene = camera->getScene();
_engine = _scene->getEngine();
_onCanvasBlurObserver
= _engine->onCanvasBlurObservable.add([this](Engine*, EventState&) { _keys.clear(); });
_onKeyboardObserver = _scene->onKeyboardObservable.add([this](KeyboardInfo* info, EventState&) {
const auto& evt = info->event;
if (!evt.metaKey) {
if (info->type == KeyboardEventTypes::KEYDOWN) {
_ctrlPressed = evt.ctrlKey;
_altPressed = evt.altKey;
_shiftPressed = evt.shiftKey;
const auto keyCode = evt.keyCode;
if ((std::find(keysHeightOffsetIncr.begin(), keysHeightOffsetIncr.end(), keyCode)
!= keysHeightOffsetIncr.end())
|| (std::find(keysHeightOffsetDecr.begin(), keysHeightOffsetDecr.end(), keyCode)
!= keysHeightOffsetDecr.end())
|| (std::find(keysRotationOffsetIncr.begin(), keysRotationOffsetIncr.end(), keyCode)
!= keysRotationOffsetIncr.end())
|| (std::find(keysRotationOffsetDecr.begin(), keysRotationOffsetDecr.end(), keyCode)
!= keysRotationOffsetDecr.end())
|| (std::find(keysRadiusIncr.begin(), keysRadiusIncr.end(), keyCode)
!= keysRadiusIncr.end())
|| (std::find(keysRadiusDecr.begin(), keysRadiusDecr.end(), keyCode)
!= keysRadiusDecr.end())) {
if (std::find(_keys.begin(), _keys.end(), keyCode) == _keys.end()) {
_keys.emplace_back(keyCode);
}
if (!_noPreventDefault) {
evt.preventDefault();
}
}
}
else {
const auto keyCode = evt.keyCode;
if ((std::find(keysHeightOffsetIncr.begin(), keysHeightOffsetIncr.end(), keyCode)
!= keysHeightOffsetIncr.end())
|| (std::find(keysHeightOffsetDecr.begin(), keysHeightOffsetDecr.end(), keyCode)
!= keysHeightOffsetDecr.end())
|| (std::find(keysRotationOffsetIncr.begin(), keysRotationOffsetIncr.end(), keyCode)
!= keysRotationOffsetIncr.end())
|| (std::find(keysRotationOffsetDecr.begin(), keysRotationOffsetDecr.end(), keyCode)
!= keysRotationOffsetDecr.end())
|| (std::find(keysRadiusIncr.begin(), keysRadiusIncr.end(), keyCode)
!= keysRadiusIncr.end())
|| (std::find(keysRadiusDecr.begin(), keysRadiusDecr.end(), keyCode)
!= keysRadiusDecr.end())) {
_keys.erase(std::remove(_keys.begin(), _keys.end(), keyCode), _keys.end());
if (!_noPreventDefault) {
evt.preventDefault();
}
}
}
}
});
}
void FollowCameraKeyboardMoveInput::detachControl(ICanvas* /*ignored*/)
{
if (_scene) {
if (_onKeyboardObserver) {
_scene->onKeyboardObservable.remove(_onKeyboardObserver);
}
if (_onCanvasBlurObserver) {
_engine->onCanvasBlurObservable.remove(_onCanvasBlurObserver);
}
_onKeyboardObserver = nullptr;
_onCanvasBlurObserver = nullptr;
}
_keys.clear();
}
void FollowCameraKeyboardMoveInput::checkInputs()
{
if (_onKeyboardObserver) {
for (auto keyCode : _keys) {
if ((std::find(keysHeightOffsetIncr.begin(), keysHeightOffsetIncr.end(), keyCode)
!= keysHeightOffsetIncr.end())
&& _modifierHeightOffset()) {
camera->heightOffset += heightSensibility;
}
else if ((std::find(keysHeightOffsetDecr.begin(), keysHeightOffsetDecr.end(), keyCode)
!= keysHeightOffsetDecr.end())
&& _modifierHeightOffset()) {
camera->heightOffset -= heightSensibility;
}
else if ((std::find(keysRotationOffsetIncr.begin(), keysRotationOffsetIncr.end(), keyCode)
!= keysRotationOffsetIncr.end())
&& _modifierRotationOffset()) {
camera->rotationOffset += rotationSensibility;
camera->rotationOffset = std::fmod(camera->rotationOffset, 360.f);
}
else if ((std::find(keysRotationOffsetDecr.begin(), keysRotationOffsetDecr.end(), keyCode)
!= keysRotationOffsetDecr.end())
&& _modifierRotationOffset()) {
camera->rotationOffset -= rotationSensibility;
camera->rotationOffset = std::fmod(camera->rotationOffset, 360.f);
}
else if ((std::find(keysRadiusIncr.begin(), keysRadiusIncr.end(), keyCode)
!= keysRadiusIncr.end())
&& _modifierRadius()) {
camera->radius += radiusSensibility;
}
else if ((std::find(keysRadiusDecr.begin(), keysRadiusDecr.end(), keyCode)
!= keysRadiusDecr.end())
&& _modifierRadius()) {
camera->radius -= radiusSensibility;
}
}
}
}
std::string FollowCameraKeyboardMoveInput::getClassName() const
{
return "FollowCameraKeyboardMoveInput";
}
std::string FollowCameraKeyboardMoveInput::getSimpleName() const
{
return "keyboard";
}
bool FollowCameraKeyboardMoveInput::_modifierHeightOffset() const
{
return (keysHeightOffsetModifierAlt == _altPressed && keysHeightOffsetModifierCtrl == _ctrlPressed
&& keysHeightOffsetModifierShift == _shiftPressed);
}
bool FollowCameraKeyboardMoveInput::_modifierRotationOffset() const
{
return (keysRotationOffsetModifierAlt == _altPressed
&& keysRotationOffsetModifierCtrl == _ctrlPressed
&& keysRotationOffsetModifierShift == _shiftPressed);
}
bool FollowCameraKeyboardMoveInput::_modifierRadius() const
{
return (keysRadiusModifierAlt == _altPressed && keysRadiusModifierCtrl == _ctrlPressed
&& keysRadiusModifierShift == _shiftPressed);
}
} // end of namespace BABYLON
| 35.954082
| 100
| 0.660849
|
samdauwe
|
4cc87792db2800736bc48a6d16c62a5c8d2498e5
| 9,957
|
cpp
|
C++
|
p1-path-planning/class-quizzes/behavior-planner/behavior-planner/src/vehicle.cpp
|
Deborah-Digges/SDC-ND-term-3
|
23e879b6d6d0c2b3a3bb78802c50f6b023ba2076
|
[
"Apache-2.0"
] | 1
|
2018-02-22T08:49:31.000Z
|
2018-02-22T08:49:31.000Z
|
p1-path-planning/class-quizzes/behavior-planner/behavior-planner/src/vehicle.cpp
|
Deborah-Digges/SDC-ND-term-3
|
23e879b6d6d0c2b3a3bb78802c50f6b023ba2076
|
[
"Apache-2.0"
] | null | null | null |
p1-path-planning/class-quizzes/behavior-planner/behavior-planner/src/vehicle.cpp
|
Deborah-Digges/SDC-ND-term-3
|
23e879b6d6d0c2b3a3bb78802c50f6b023ba2076
|
[
"Apache-2.0"
] | 4
|
2017-10-12T16:32:20.000Z
|
2020-07-27T09:01:43.000Z
|
#include <iostream>
#include "vehicle.h"
#include <iostream>
#include <math.h>
#include <map>
#include <string>
#include <iterator>
/**
* Initializes Vehicle
*/
Vehicle::Vehicle(int lane, int s, int v, int a) {
this->lane = lane;
this->s = s;
this->v = v;
this->a = a;
state = "CS";
max_acceleration = -1;
}
Vehicle::~Vehicle() {}
vector<string> find_possible_next_states(string current_state) {
if(current_state == "KL") {
return {"KL", "PLCL", "PLCR"};
}
if(current_state == "LCL") {
return {"LCL", "KL"};
}
if(current_state == "LCR") {
return {"LCR", "KL"};
}
if(current_state == "PLCL") {
return {"KL", "LCL"};
}
if(current_state == "PLCR") {
return {"KL", "LCR"};
}
}
// TODO - Implement this method.
void Vehicle::update_state(map<int,vector < vector<int> > > predictions) {
/*
Updates the "state" of the vehicle by assigning one of the
following values to 'self.state':
"KL" - Keep Lane
- The vehicle will attempt to drive its target speed, unless there is
traffic in front of it, in which case it will slow down.
"LCL" or "LCR" - Lane Change Left / Right
- The vehicle will IMMEDIATELY change lanes and then follow longitudinal
behavior for the "KL" state in the new lane.
"PLCL" or "PLCR" - Prepare for Lane Change Left / Right
- The vehicle will find the nearest vehicle in the adjacent lane which is
BEHIND itself and will adjust speed to try to get behind that vehicle.
INPUTS
- predictions
A dictionary. The keys are ids of other vehicles and the values are arrays
where each entry corresponds to the vehicle's predicted location at the
corresponding timestep. The FIRST element in the array gives the vehicle's
current position. Example (showing a car with id 3 moving at 2 m/s):
{
3 : [
{"s" : 4, "lane": 0},
{"s" : 6, "lane": 0},
{"s" : 8, "lane": 0},
{"s" : 10, "lane": 0},
]
}
*/
vector<string> states = find_possible_next_states(this->state);
//vector<string> states = {"KL", "LCL", "LCR", "PLCL", "PLCR"};
vector<double> costs;
double cost;
for (string test_state : states) {
cost = 0;
// create copy of our vehicle
Vehicle test_v = Vehicle(this->lane, this->s, this->v, this->a);
test_v.state = test_state;
test_v.realize_state(predictions);
// predict one step into future, for selected state
vector<int> test_v_state = test_v.state_at(1);
int pred_lane = test_v_state[0];
int pred_s = test_v_state[1];
int pred_v = test_v_state[2];
int pred_a = test_v_state[3];
//cout << "pred lane: " << pred_lane << " s: " << pred_s << " v: " << pred_v << " a: " << pred_a << endl;
cout << "tested state: " << test_state << endl;
// check for collisions
map<int, vector<vector<int> > >::iterator it = predictions.begin();
vector<vector<vector<int> > > in_front;
while(it != predictions.end())
{
int index = it->first;
vector<vector<int>> v = it->second;
// check predictions one step in future as well
if ((v[1][0] == pred_lane) && (abs(v[1][1] - pred_s) <= L) && index != -1) {
cout << "coll w/ car: " << index << ", "
<< v[1][0] << " " << pred_lane << ", "
<< v[1][1] << " " << pred_s << endl;
cost += 1000;
}
it++;
}
cost += 1*(10 - pred_v);
cost += 1*(pow(3 - pred_lane, 2));
//cost += 10*(1 - exp(-abs(pred_lane - 3)/(300 - (double)pred_s)));
if (pred_lane < 0 || pred_lane > 3) {
cost += 1000;
}
cout << "cost: " << cost << endl;
costs.push_back(cost);
}
double min_cost = 9999999;
int min_cost_index = 0;
for (int i = 0; i < costs.size(); i++) {
//cout << "cost[" << i << "]: " << costs[i] << endl;
if (costs[i] < min_cost) {
min_cost = costs[i];
min_cost_index = i;
}
}
state = states[min_cost_index];
//state = "LCR";
cout << "chosen state: " << state << endl;
}
void Vehicle::configure(vector<int> road_data)
{
target_speed = road_data[0];
lanes_available = road_data[1];
goal_s = road_data[2];
goal_lane = road_data[3];
max_acceleration = road_data[4];
}
string Vehicle::display() {
ostringstream oss;
oss << "s: " << this->s << "\n";
oss << "lane: " << this->lane << "\n";
oss << "v: " << this->v << "\n";
oss << "a: " << this->a << "\n";
return oss.str();
}
void Vehicle::increment(int dt = 1) {
this->s += this->v * dt;
this->v += this->a * dt;
}
vector<int> Vehicle::state_at(int t) {
/*
Predicts state of vehicle in t seconds (assuming constant acceleration)
*/
int s = this->s + this->v * t + this->a * t * t / 2;
int v = this->v + this->a * t;
return {this->lane, s, v, this->a};
}
bool Vehicle::collides_with(Vehicle other, int at_time) {
/*
Simple collision detection.
*/
vector<int> check1 = state_at(at_time);
vector<int> check2 = other.state_at(at_time);
return (check1[0] == check2[0]) && (abs(check1[1]-check2[1]) <= L);
}
Vehicle::collider Vehicle::will_collide_with(Vehicle other, int timesteps) {
Vehicle::collider collider_temp;
collider_temp.collision = false;
collider_temp.time = -1;
for (int t = 0; t < timesteps+1; t++)
{
if( collides_with(other, t) )
{
collider_temp.collision = true;
collider_temp.time = t;
return collider_temp;
}
}
return collider_temp;
}
void Vehicle::realize_state(map<int,vector < vector<int> > > predictions) {
/*
Given a state, realize it by adjusting acceleration and lane.
Note - lane changes happen instantaneously.
*/
string state = this->state;
if(state.compare("CS") == 0)
{
realize_constant_speed();
}
else if(state.compare("KL") == 0)
{
realize_keep_lane(predictions);
}
else if(state.compare("LCL") == 0)
{
realize_lane_change(predictions, "L");
}
else if(state.compare("LCR") == 0)
{
realize_lane_change(predictions, "R");
}
else if(state.compare("PLCL") == 0)
{
realize_prep_lane_change(predictions, "L");
}
else if(state.compare("PLCR") == 0)
{
realize_prep_lane_change(predictions, "R");
}
}
void Vehicle::realize_constant_speed() {
a = 0;
}
int Vehicle::_max_accel_for_lane(map<int,vector<vector<int> > > predictions, int lane, int s) {
int delta_v_til_target = target_speed - v;
int max_acc = min(max_acceleration, delta_v_til_target);
map<int, vector<vector<int> > >::iterator it = predictions.begin();
vector<vector<vector<int> > > in_front;
while(it != predictions.end())
{
int v_id = it->first;
vector<vector<int> > v = it->second;
if((v[0][0] == lane) && (v[0][1] > s))
{
in_front.push_back(v);
}
it++;
}
if(in_front.size() > 0)
{
int min_s = 1000;
vector<vector<int>> leading = {};
for(int i = 0; i < in_front.size(); i++)
{
if((in_front[i][0][1]-s) < min_s)
{
min_s = (in_front[i][0][1]-s);
leading = in_front[i];
}
}
int next_pos = leading[1][1];
int my_next = s + this->v;
int separation_next = next_pos - my_next;
int available_room = separation_next - preferred_buffer;
max_acc = min(max_acc, available_room);
}
return max_acc;
}
void Vehicle::realize_keep_lane(map<int,vector< vector<int> > > predictions) {
this->a = _max_accel_for_lane(predictions, this->lane, this->s);
}
void Vehicle::realize_lane_change(map<int,vector< vector<int> > > predictions, string direction) {
int delta = -1;
if (direction.compare("L") == 0)
{
delta = 1;
}
this->lane += delta;
int lane = this->lane;
int s = this->s;
this->a = _max_accel_for_lane(predictions, lane, s);
}
void Vehicle::realize_prep_lane_change(map<int,vector<vector<int> > > predictions, string direction) {
int delta = -1;
if (direction.compare("L") == 0)
{
delta = 1;
}
int lane = this->lane + delta;
map<int, vector<vector<int> > >::iterator it = predictions.begin();
vector<vector<vector<int> > > at_behind;
while(it != predictions.end())
{
int v_id = it->first;
vector<vector<int> > v = it->second;
if((v[0][0] == lane) && (v[0][1] <= this->s))
{
at_behind.push_back(v);
}
it++;
}
if(at_behind.size() > 0)
{
int max_s = -1000;
vector<vector<int> > nearest_behind = {};
for(int i = 0; i < at_behind.size(); i++)
{
if((at_behind[i][0][1]) > max_s)
{
max_s = at_behind[i][0][1];
nearest_behind = at_behind[i];
}
}
int target_vel = nearest_behind[1][1] - nearest_behind[0][1];
int delta_v = this->v - target_vel;
int delta_s = this->s - nearest_behind[0][1];
if(delta_v != 0)
{
int time = -2 * delta_s/delta_v;
int a;
if (time == 0)
{
a = this->a;
}
else
{
a = delta_v/time;
}
if(a > this->max_acceleration)
{
a = this->max_acceleration;
}
if(a < -this->max_acceleration)
{
a = -this->max_acceleration;
}
this->a = a;
}
else
{
int my_min_acc = max(-this->max_acceleration,-delta_s);
this->a = my_min_acc;
}
}
}
vector<vector<int> > Vehicle::generate_predictions(int horizon = 10) {
vector<vector<int> > predictions;
for( int i = 0; i < horizon; i++)
{
vector<int> check1 = state_at(i);
vector<int> lane_s = {check1[0], check1[1]};
predictions.push_back(lane_s);
}
return predictions;
}
| 25.335878
| 113
| 0.559506
|
Deborah-Digges
|
4cc95a026a02849a021e18ca1cf64d57ffdbea9f
| 10,635
|
cpp
|
C++
|
src/RShaders.cpp
|
chilingg/Redopera
|
a898eb269d5d3eba9ba5b14ef9b4209f615f4547
|
[
"MIT"
] | null | null | null |
src/RShaders.cpp
|
chilingg/Redopera
|
a898eb269d5d3eba9ba5b14ef9b4209f615f4547
|
[
"MIT"
] | null | null | null |
src/RShaders.cpp
|
chilingg/Redopera
|
a898eb269d5d3eba9ba5b14ef9b4209f615f4547
|
[
"MIT"
] | null | null | null |
#include <RShaders.h>
#include <RDebug.h>
#include <stdexcept>
using namespace Redopera;
thread_local GLuint RRPI::current = 0;
thread_local int RRPI::count = 0;
RRPI::~RRPI()
{
--count;
if(count == 0)
{
glUseProgram(0);
current = 0;
}
}
void RRPI::setUniform(GLint loc, GLfloat v1) const
{
glUniform1f(loc, v1);
}
void RRPI::setUniform(GLint loc, GLfloat v1, GLfloat v2) const
{
glUniform2f(loc, v1, v2);
}
void RRPI::setUniform(GLint loc, GLfloat v1, GLfloat v2, GLfloat v3) const
{
glUniform3f(loc, v1, v2, v3);
}
void RRPI::setUniform(GLint loc, GLfloat v1, GLfloat v2, GLfloat v3, GLfloat v4) const
{
glUniform4f(loc, v1, v2, v3, v4);
}
void RRPI::setUniform(GLint loc, glm::vec3 vec) const
{
glUniform3f(loc, vec.x, vec.y, vec.z);
}
void RRPI::setUniform(GLint loc, glm::vec4 vec) const
{
glUniform4f(loc, vec.x, vec.y, vec.z, vec.w);
}
void RRPI::setUniform(GLint loc, GLint v1) const
{
glUniform1i(loc, v1);
}
void RRPI::setUniform(GLint loc, GLint v1, GLint v2) const
{
glUniform2i(loc, v1, v2);
}
void RRPI::setUniform(GLint loc, GLint v1, GLint v2, GLint v3) const
{
glUniform3i(loc, v1, v2, v3);
}
void RRPI::setUniform(GLint loc, GLint v1, GLint v2, GLint v3, GLint v4) const
{
glUniform4i(loc, v1, v2, v3, v4);
}
void RRPI::setUniform(GLint loc, glm::ivec3 vec) const
{
glUniform3i(loc, vec.x, vec.y, vec.z);
}
void RRPI::setUniform(GLint loc, glm::ivec4 vec) const
{
glUniform4i(loc, vec.x, vec.y, vec.z, vec.w);
}
void RRPI::setUniform(GLint loc, GLuint v1) const
{
glUniform1ui(loc, v1);
}
void RRPI::setUniform(GLint loc, GLuint v1, GLuint v2) const
{
glUniform2ui(loc, v1, v2);
}
void RRPI::setUniform(GLint loc, GLuint v1, GLuint v2, GLuint v3) const
{
glUniform3ui(loc, v1, v2, v3);
}
void RRPI::setUniform(GLint loc, GLuint v1, GLuint v2, GLuint v3, GLuint v4) const
{
glUniform4ui(loc, v1, v2, v3, v4);
}
void RRPI::setUniform(GLint loc, glm::uvec3 vec) const
{
glUniform3ui(loc, vec.x, vec.y, vec.z);
}
void RRPI::setUniform(GLint loc, glm::uvec4 vec) const
{
glUniform4ui(loc, vec.x, vec.y, vec.z, vec.w);
}
void RRPI::setUniform(GLint loc, GLsizei size, GLfloat *vp, GLsizei count) const
{
switch(size) {
case 1:
glUniform1fv(loc, count, vp);
break;
case 2:
glUniform2fv(loc, count, vp);
break;
case 3:
glUniform3fv(loc, count, vp);
break;
case 4:
glUniform4fv(loc, count, vp);
break;
default:
throw std::invalid_argument("Set Invalid size argument for Uniform" + std::to_string(size) + "fv");
}
}
void RRPI::setUniform(GLint loc, GLsizei size, GLint *vp, GLsizei count) const
{
switch(size) {
case 1:
glUniform1iv(loc, count, vp);
break;
case 2:
glUniform2iv(loc, count, vp);
break;
case 3:
glUniform3iv(loc, count, vp);
break;
case 4:
glUniform4iv(loc, count, vp);
break;
default:
throw std::invalid_argument("Invalid size argument for Uniform" + std::to_string(size) + "iv");
break;
}
}
void RRPI::setUniform(GLint loc, GLsizei size, GLuint *vp, GLsizei count) const
{
switch(size) {
case 1:
glUniform1uiv(loc, count, vp);
break;
case 2:
glUniform2uiv(loc, count, vp);
break;
case 3:
glUniform3uiv(loc, count, vp);
break;
case 4:
glUniform4uiv(loc, count, vp);
break;
default:
throw std::invalid_argument("Invalid size argument for Uniform" + std::to_string(size) + "uiv");
break;
}
}
void RRPI::setUniform(GLint loc, glm::vec3 *vec, GLsizei count) const
{
glUniform3fv(loc, count, &vec->x);
}
void RRPI::setUniform(GLint loc, glm::vec4 *vec, GLsizei count) const
{
glUniform4fv(loc, count, &vec->x);
}
void RRPI::setUniform(GLint loc, glm::ivec3 *vec, GLsizei count) const
{
glUniform3iv(loc, count, &vec->x);
}
void RRPI::setUniform(GLint loc, glm::ivec4 *vec, GLsizei count) const
{
glUniform4iv(loc, count, &vec->x);
}
void RRPI::setUniform(GLint loc, glm::uvec3 *vec, GLsizei count) const
{
glUniform3uiv(loc, count, &vec->x);
}
void RRPI::setUniform(GLint loc, glm::uvec4 *vec, GLsizei count) const
{
glUniform4uiv(loc, count, &vec->x);
}
void RRPI::setUniformMat(GLint loc, const glm::mat2 &mat) const
{
glUniformMatrix2fv(loc, 1, GL_FALSE, glm::value_ptr(mat));
}
void RRPI::setUniformMat(GLint loc, const glm::mat3 &mat) const
{
glUniformMatrix3fv(loc, 1, GL_FALSE, glm::value_ptr(mat));
}
void RRPI::setUniformMat(GLint loc, const glm::mat4 &mat) const
{
glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(mat));
}
void RRPI::setUniformMat(GLint loc, const glm::dmat2 &mat) const
{
glUniformMatrix2dv(loc, 1, GL_FALSE, glm::value_ptr(mat));
}
void RRPI::setUniformMat(GLint loc, const glm::dmat3 &mat) const
{
glUniformMatrix3dv(loc, 1, GL_FALSE, glm::value_ptr(mat));
}
void RRPI::setUniformMat(GLint loc, const glm::dmat4 &mat) const
{
glUniformMatrix4dv(loc, 1, GL_FALSE, glm::value_ptr(mat));
}
void RRPI::setUniformMat(GLint loc, const glm::mat2 *mat, GLsizei count) const
{
glUniformMatrix2fv(loc, count, GL_FALSE, glm::value_ptr(*mat));
}
void RRPI::setUniformMat(GLint loc, const glm::mat3 *mat, GLsizei count) const
{
glUniformMatrix3fv(loc, count, GL_FALSE, glm::value_ptr(*mat));
}
void RRPI::setUniformMat(GLint loc, const glm::mat4 *mat, GLsizei count) const
{
glUniformMatrix4fv(loc, count, GL_FALSE, glm::value_ptr(*mat));
}
void RRPI::setUniformMat(GLint loc, const glm::dmat2 *mat, GLsizei count) const
{
glUniformMatrix2dv(loc, count, GL_FALSE, glm::value_ptr(*mat));
}
void RRPI::setUniformMat(GLint loc, const glm::dmat3 *mat, GLsizei count) const
{
glUniformMatrix3dv(loc, count, GL_FALSE, glm::value_ptr(*mat));
}
void RRPI::setUniformMat(GLint loc, const glm::dmat4 *mat, GLsizei count) const
{
glUniformMatrix4dv(loc, count, GL_FALSE, glm::value_ptr(*mat));
}
void RRPI::setUniformMat(GLint loc, GLsizei order, GLfloat *vp, GLsizei count, GLboolean transpose) const
{
switch(order) {
case 2:
glUniformMatrix2fv(loc, count, transpose, vp);
break;
case 3:
glUniformMatrix3fv(loc, count, transpose, vp);
break;
case 4:
glUniformMatrix4fv(loc, count, transpose, vp);
break;
default:
throw std::invalid_argument("Invalid size argument for UniformMatrix" + std::to_string(order) + "fv");
break;
}
}
void RRPI::setUniformMat(GLint loc, GLsizei order, GLdouble *vp, GLsizei count, GLboolean transpose) const
{
switch(order) {
case 2:
glUniformMatrix2dv(loc, count, transpose, vp);
break;
case 3:
glUniformMatrix3dv(loc, count, transpose, vp);
break;
case 4:
glUniformMatrix4dv(loc, count, transpose, vp);
break;
default:
throw std::invalid_argument("Invalid size argument for UniformMatrix" + std::to_string(order) + "dv");
break;
}
}
void RRPI::setUniformSubroutines(RShader::Type type, GLsizei count, const GLuint *indices)
{
glUniformSubroutinesuiv(static_cast<GLenum>(type), count, indices);
}
void RRPI::release()
{
if(count != 1)
throw std::logic_error("The current thread has other <RRPI> is using!");
current = 0;
}
RRPI::RRPI(GLuint id)
{
if(current)
{
if(current != id)
throw std::logic_error("The current thread has other <RRPI> is using!");
else
++count;
}
else
{
current = id;
++count;
glUseProgram(id);
}
}
RShaders::RShaders(std::initializer_list<RShader> list)
{
for(auto &shader : list)
stages_.emplace(shader.type(), shader);
linkProgram();
}
RShaders::RShaders(const RShaders &program):
id_(program.id_),
stages_(program.stages_)
{
}
RShaders::RShaders(const RShaders &&program):
id_(std::move(program.id_)),
stages_(std::move(program.stages_))
{
}
RShaders &RShaders::operator=(RShaders program)
{
swap(program);
return *this;
}
void RShaders::swap(RShaders &program)
{
id_.swap(program.id_);
stages_.swap(program.stages_);
}
bool RShaders::isValid() const
{
return id_ != nullptr;
}
bool RShaders::isAttachedShader(RShader::Type type) const
{
return stages_.count(type);
}
GLuint RShaders::id() const
{
return *id_;
}
RRPI RShaders::use() const
{
return RRPI(*id_);
}
GLint RShaders::getUniformLoc(const std::string &name) const
{
GLint loc = glGetUniformLocation(*id_, name.c_str());
#ifndef NDEBUG
rCheck(loc < 0, "Invalid locale <" + name + '>');
#endif
return loc;
}
GLint RShaders::getSubroutineUniformLoc(RShader::Type type, const std::string &name) const
{
GLint loc = glGetSubroutineUniformLocation(*id_, static_cast<GLenum>(type), name.c_str());
#ifndef NDEBUG
rCheck(loc < 0, "Invalid subroutine locale <" + name + '>');
#endif
return loc;
}
GLuint RShaders::getSubroutineIndex(RShader::Type type, const std::string &name) const
{
GLuint i = glGetSubroutineIndex(*id_, static_cast<GLenum>(type), name.c_str());
#ifndef NDEBUG
rCheck(i == GL_INVALID_INDEX, "Invalid subroutine index <" + name + '>');
#endif
return i;
}
void RShaders::attachShader(const RShader &shader)
{
stages_.emplace(shader.type(), shader);
}
void RShaders::attachShader(std::initializer_list<RShader> list)
{
for(auto &shader : list)
stages_.emplace(shader.type(), shader);
}
void RShaders::detachShader(RShader::Type type)
{
stages_.erase(type);
}
bool RShaders::linkProgram()
{
std::shared_ptr<GLuint> id(std::shared_ptr<GLuint>(new GLuint(glCreateProgram()), deleteShaderProgram));
for(auto& shader: stages_)
glAttachShader(*id, shader.second.id());
glLinkProgram(*id);
int success;
glGetProgramiv(*id, GL_LINK_STATUS, &success);
if(rCheck(!success, "Failed to link shader program"))
{
char infoLog[256];
glGetProgramInfoLog(*id, sizeof(infoLog), nullptr, infoLog);
rPrError(infoLog);
return false;
}
id_.swap(id);
releaseShader();
return true;
}
void RShaders::reLinkProgram()
{
glLinkProgram(*id_);
}
void RShaders::releaseShader()
{
std::map<RShader::Type, RShader> temp;
stages_.swap(temp);
}
void RShaders::release()
{
id_.reset();
}
void RShaders::deleteShaderProgram(GLuint *id)
{
glDeleteProgram(*id);
delete id;
}
void swap(RShaders &prog1, RShaders &prog2)
{
prog1.swap(prog2);
}
| 22.484144
| 110
| 0.653597
|
chilingg
|
4ccae1f6e170f819e22815cfdbf2b8839a4908f3
| 3,861
|
cpp
|
C++
|
GUIDialogs/HoldupsEditor/HoldupsEditor.cpp
|
FlowsheetSimulation/Dyssol-open
|
557d57d959800868e1b3fd161b26cad16481382b
|
[
"BSD-3-Clause"
] | 7
|
2020-12-02T02:54:31.000Z
|
2022-03-08T20:37:46.000Z
|
GUIDialogs/HoldupsEditor/HoldupsEditor.cpp
|
FlowsheetSimulation/Dyssol-open
|
557d57d959800868e1b3fd161b26cad16481382b
|
[
"BSD-3-Clause"
] | 33
|
2021-03-26T12:20:18.000Z
|
2022-02-23T11:37:56.000Z
|
GUIDialogs/HoldupsEditor/HoldupsEditor.cpp
|
FlowsheetSimulation/Dyssol-open
|
557d57d959800868e1b3fd161b26cad16481382b
|
[
"BSD-3-Clause"
] | 6
|
2020-07-17T08:17:37.000Z
|
2022-02-24T13:45:16.000Z
|
/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */
#include "HoldupsEditor.h"
#include "Flowsheet.h"
#include "BaseUnit.h"
#include "BaseStream.h"
CHoldupsEditor::CHoldupsEditor(CFlowsheet* _pFlowsheet, CMaterialsDatabase* _materialsDB, QWidget *parent) :
QDialog(parent),
m_pFlowsheet{ _pFlowsheet },
m_pSelectedModel{ nullptr },
m_nLastModel{ 0 },
m_nLastHoldup{ 0 }
{
ui.setupUi(this);
ui.widgetHoldupsEditor->SetFlowsheet(_pFlowsheet, _materialsDB);
setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint);
}
void CHoldupsEditor::InitializeConnections() const
{
connect(ui.modelsList, &QTableWidget::itemSelectionChanged, this, &CHoldupsEditor::UpdateHoldupsList);
connect(ui.holdupsList, &QTableWidget::itemSelectionChanged, this, &CHoldupsEditor::NewHoldupSelected);
connect(ui.widgetHoldupsEditor, &CBasicStreamEditor::DataChanged, this, &CHoldupsEditor::ChangeData);
}
void CHoldupsEditor::UpdateWholeView()
{
UpdateUnitsList();
UpdateHoldupsList();
}
void CHoldupsEditor::UpdateHoldupsList()
{
QSignalBlocker blocker(ui.holdupsList);
const auto oldPos = ui.modelsList->CurrentCellPos();
ui.holdupsList->setColumnCount(1);
ui.holdupsList->setRowCount(0);
m_pSelectedModel = ui.modelsList->currentRow() != -1 ? m_pFlowsheet->GetUnit(ui.modelsList->GetItemUserData(ui.modelsList->currentRow(), 0).toStdString()) : nullptr;
if (m_pSelectedModel && m_pSelectedModel->GetModel())
{
for (const auto& stream : m_pSelectedModel->GetModel()->GetStreamsManager().GetAllInit())
{
ui.holdupsList->insertRow(ui.holdupsList->rowCount());
ui.holdupsList->SetItemNotEditable(ui.holdupsList->rowCount() - 1, 0, stream->GetName());
}
}
ui.holdupsList->RestoreSelectedCell(oldPos);
NewHoldupSelected();
}
void CHoldupsEditor::UpdateUnitsList() const
{
QSignalBlocker blocker(ui.modelsList);
const auto oldPos = ui.modelsList->CurrentCellPos();
ui.modelsList->setColumnCount(1);
ui.modelsList->setRowCount(0);
for (const auto& unit : m_pFlowsheet->GetAllUnits())
{
if (unit && unit->GetModel() && !unit->GetModel()->GetStreamsManager().GetAllInit().empty())
{
ui.modelsList->insertRow(ui.modelsList->rowCount());
ui.modelsList->SetItemNotEditable(ui.modelsList->rowCount() - 1, 0, unit->GetName(), QString::fromStdString(unit->GetKey()));
}
}
ui.modelsList->RestoreSelectedCell(oldPos);
}
void CHoldupsEditor::setVisible( bool _bVisible )
{
QDialog::setVisible(_bVisible);
if (_bVisible)
{
UpdateWholeView();
LoadViewState();
}
else
SaveViewState();
}
void CHoldupsEditor::SaveViewState()
{
m_nLastModel = ui.modelsList->currentRow() == -1 ? 0 : ui.modelsList->currentRow();
m_nLastHoldup = ui.holdupsList->currentRow() == -1 ? 0 : ui.holdupsList->currentRow();
}
void CHoldupsEditor::LoadViewState() const
{
QApplication::setOverrideCursor(Qt::WaitCursor);
if (m_nLastModel < ui.modelsList->rowCount())
ui.modelsList->setCurrentCell(m_nLastModel, 0);
if (m_nLastHoldup < ui.holdupsList->rowCount())
ui.holdupsList->setCurrentCell(m_nLastHoldup, 0);
QApplication::restoreOverrideCursor();
}
void CHoldupsEditor::NewHoldupSelected() const
{
CBaseStream* pSelectedHoldup = nullptr;
if (m_pSelectedModel != nullptr)
if (ui.holdupsList->currentRow() >= 0 && m_pSelectedModel->GetModel() && int(m_pSelectedModel->GetModel()->GetStreamsManager().GetAllInit().size()) > ui.holdupsList->currentRow())
pSelectedHoldup = m_pSelectedModel->GetModel()->GetStreamsManager().GetAllInit()[ui.holdupsList->currentRow()];
ui.widgetHoldupsEditor->SetStream(pSelectedHoldup);
}
void CHoldupsEditor::ChangeData()
{
emit DataChanged();
}
| 32.445378
| 182
| 0.72805
|
FlowsheetSimulation
|
4ccfeefe86cf13c8d9689491d05a34f89814a36e
| 518
|
cpp
|
C++
|
LZL/Solution/codeforces/ok/A.cpp
|
xiyoulinuxgroup-2019-summer/TeamF
|
7a661b172f7410583bd11335a3b049f9df8797a3
|
[
"MIT"
] | null | null | null |
LZL/Solution/codeforces/ok/A.cpp
|
xiyoulinuxgroup-2019-summer/TeamF
|
7a661b172f7410583bd11335a3b049f9df8797a3
|
[
"MIT"
] | null | null | null |
LZL/Solution/codeforces/ok/A.cpp
|
xiyoulinuxgroup-2019-summer/TeamF
|
7a661b172f7410583bd11335a3b049f9df8797a3
|
[
"MIT"
] | 1
|
2019-07-15T06:28:11.000Z
|
2019-07-15T06:28:11.000Z
|
#include<iostream>
#include<algorithm>
#include<string>
#include<map>
#include<set>
#include<unordered_map>
#include<list>
#include<vector>
#include<cstdlib>
#include<utility>
#include<cstring>
const int maxn=1010;
using namespace std;
map<int,int>mp;
int m,n,tmp;
int book[maxn];
int main()
{
cin >> m >> n;
for(int i=0;i<m;i++)
{
cin >> tmp;
mp[tmp]++;
}
int ans=0;
int tmep=0;
for(int i=1;i<=n;i++)
{
ans+=((mp[i]/2));
}
cout << ((m+1)/2-ans)+ans*2;
}
| 16.1875
| 32
| 0.567568
|
xiyoulinuxgroup-2019-summer
|
4cd0d1b5223f8d472a242c18bec54efeb8e4b809
| 5,783
|
cpp
|
C++
|
test/src/tello/tello_test.cpp
|
LucaRitz/tello
|
3874db477cc2ad6a7127494d4321baac440ac88e
|
[
"Apache-2.0"
] | 3
|
2021-01-05T15:49:12.000Z
|
2021-06-30T12:42:04.000Z
|
test/src/tello/tello_test.cpp
|
LucaRitz/tello
|
3874db477cc2ad6a7127494d4321baac440ac88e
|
[
"Apache-2.0"
] | 2
|
2020-08-15T09:47:44.000Z
|
2020-08-29T12:52:17.000Z
|
test/src/tello/tello_test.cpp
|
LucaRitz/tello
|
3874db477cc2ad6a7127494d4321baac440ac88e
|
[
"Apache-2.0"
] | 2
|
2021-01-12T12:00:14.000Z
|
2021-02-11T12:50:42.000Z
|
#include <gtest/gtest.h>
#include <tello/tello.hpp>
#include <future>
#include <tello/response/query_response.hpp>
#define TELLO_IP_ADDRESS (ip_address)0xC0A80A01 // 192.168.10.1
using tello::Command;
using tello::Tello;
using tello::Response;
using tello::QueryResponse;
using tello::Status;
using std::string;
using std::promise;
using std::future;
using tello::QueryResponse;
TEST(Tello, BasicFlightCommands) {
Tello tello(TELLO_IP_ADDRESS);
future<Response> command_future = tello.command();
command_future.wait();
ASSERT_NE(Status::FAIL, command_future.get().status());
future<QueryResponse> wifi_future = tello.read_wifi();
wifi_future.wait();
ASSERT_NE(Status::FAIL, wifi_future.get().status());
future<Response> takeoff_future = tello.takeoff();
takeoff_future.wait();
ASSERT_NE(Status::FAIL, takeoff_future.get().status());
future<Response> up_future = tello.up(30);
up_future.wait();
ASSERT_NE(Status::FAIL, up_future.get().status());
future<Response> down_future = tello.down(30);
down_future.wait();
ASSERT_NE(Status::FAIL, down_future.get().status());
future<Response> left_future = tello.left(30);
left_future.wait();
ASSERT_NE(Status::FAIL, left_future.get().status());
future<Response> right_future = tello.right(30);
right_future.wait();
ASSERT_NE(Status::FAIL, right_future.get().status());
future<Response> forward_future = tello.forward(30);
forward_future.wait();
ASSERT_NE(Status::FAIL, forward_future.get().status());
future<Response> back_future = tello.back(30);
back_future.wait();
ASSERT_NE(Status::FAIL, back_future.get().status());
future<Response> clockwise_turn_future = tello.clockwise_turn(180);
clockwise_turn_future.wait();
ASSERT_NE(Status::FAIL, clockwise_turn_future.get().status());
future<Response> counter_clockwise_turn_future = tello.counterclockwise_turn(180);
counter_clockwise_turn_future.wait();
ASSERT_NE(Status::FAIL, counter_clockwise_turn_future.get().status());
future<Response> land_future = tello.land();
land_future.wait();
ASSERT_NE(Status::FAIL, land_future.get().status());
}
TEST(Tello, SpeedCommands) {
Tello tello(TELLO_IP_ADDRESS);
future<Response> command_future = tello.command();
command_future.wait();
ASSERT_NE(Status::FAIL, command_future.get().status());
//Read default speed
future<QueryResponse> get_speed_future = tello.read_speed();
get_speed_future.wait();
QueryResponse get_speed_default_response = get_speed_future.get();
ASSERT_NE(Status::FAIL, get_speed_default_response.status());
int defaultVelocity = get_speed_default_response.value();
//Set speed to max 100
int maxVelocity = 100;
future<Response> set_speed_future= tello.set_speed(maxVelocity);
set_speed_future.wait();
ASSERT_NE(Status::FAIL, set_speed_future.get().status());
//Read that speed is max
get_speed_future = tello.read_speed();
get_speed_future.wait();
QueryResponse get_speed_response = get_speed_future.get();
ASSERT_NE(Status::FAIL, get_speed_response.status());
ASSERT_EQ(maxVelocity, get_speed_response.value());
//Reset speed to default speed
set_speed_future = tello.set_speed(defaultVelocity);
set_speed_future.wait();
ASSERT_NE(Status::FAIL, set_speed_future.get().status());
//Check if speed was rested to default speed
get_speed_future = tello.read_speed();
get_speed_future.wait();
QueryResponse get_speed_future_reset_response = get_speed_future.get();
ASSERT_NE(Status::FAIL, get_speed_future_reset_response.status());
ASSERT_EQ(defaultVelocity, get_speed_future_reset_response.value());
}
TEST(Tello, RCControlCommandFlyCircle) {
Tello tello(TELLO_IP_ADDRESS);
future<Response> command_future = tello.command();
command_future.wait();
ASSERT_EQ(Status::OK, command_future.get().status());
future<Response> takeoff_future = tello.takeoff();
takeoff_future.wait();
ASSERT_EQ(Status::OK, takeoff_future.get().status());
future<Response> rc_control_future1 = tello.rc_control(10, -10, 0, 0);
rc_control_future1.wait();
ASSERT_EQ(Status::UNKNOWN, rc_control_future1.get().status());
future<Response> rc_control_future2 = tello.rc_control(0, -10, 0, 0);
rc_control_future2.wait();
ASSERT_EQ(Status::UNKNOWN, rc_control_future2.get().status());
future<Response> rc_control_future3 = tello.rc_control(-10, -10, 0, 0);
rc_control_future3.wait();
ASSERT_EQ(Status::UNKNOWN, rc_control_future3.get().status());
future<Response> rc_control_future4 = tello.rc_control(-10, 0, 0, 0);
rc_control_future4.wait();
ASSERT_EQ(Status::UNKNOWN, rc_control_future4.get().status());
future<Response> rc_control_future5 = tello.rc_control(-10, 10, 0, 0);
rc_control_future5.wait();
ASSERT_EQ(Status::UNKNOWN, rc_control_future5.get().status());
future<Response> rc_control_future6 = tello.rc_control(0, 10, 0, 0);
rc_control_future6.wait();
ASSERT_EQ(Status::UNKNOWN, rc_control_future6.get().status());
future<Response> rc_control_future7 = tello.rc_control(10, 10, 0, 0);
rc_control_future7.wait();
ASSERT_EQ(Status::UNKNOWN, rc_control_future7.get().status());
future<Response> rc_control_future8 = tello.rc_control(10, 0, 0, 0);
rc_control_future8.wait();
ASSERT_EQ(Status::UNKNOWN, rc_control_future8.get().status());
future<Response> rc_control_future9 = tello.rc_control(0, 0, 0, 0);
rc_control_future9.wait();
ASSERT_EQ(Status::UNKNOWN, rc_control_future9.get().status());
future<Response> land_future = tello.land();
land_future.wait();
ASSERT_EQ(Status::OK, land_future.get().status());
}
| 36.14375
| 86
| 0.721771
|
LucaRitz
|
4cd592b82e5b2735686d0fc75528e0e179d03dea
| 3,570
|
cpp
|
C++
|
samples/GuiAPI_PropertyWin/PropertyWin.cpp
|
odayibasi/swengine
|
ef07b7c9125d01596837a423a9f3dcbced1f5aa7
|
[
"Zlib",
"MIT"
] | 3
|
2021-03-01T20:41:13.000Z
|
2021-07-10T13:45:47.000Z
|
samples/GuiAPI_PropertyWin/PropertyWin.cpp
|
odayibasi/swengine
|
ef07b7c9125d01596837a423a9f3dcbced1f5aa7
|
[
"Zlib",
"MIT"
] | null | null | null |
samples/GuiAPI_PropertyWin/PropertyWin.cpp
|
odayibasi/swengine
|
ef07b7c9125d01596837a423a9f3dcbced1f5aa7
|
[
"Zlib",
"MIT"
] | null | null | null |
#include "../../include/SWEngine.h"
#pragma comment (lib,"../../lib/SWUtil.lib")
#pragma comment (lib,"../../lib/SWTypes.lib")
#pragma comment (lib,"../../lib/SWCore.lib")
#pragma comment (lib,"../../lib/SWEngine.lib")
#pragma comment (lib,"../../lib/SWGame.lib")
#pragma comment (lib,"../../lib/SWGui.lib")
#pragma comment (lib,"../../lib/SWServices.lib")
swApplication propertyWinApp;
int windowID=-1;
int windowTexID=-1;
swRect window={0,0,800,600};
typedef enum _eBoundaryStyle{
BOUNDARY_POINT,
BOUNDARY_LINE,
}eBoundaryStyle;
//Boundary
int boundaryStyle=BOUNDARY_LINE;
swColor boundaryColor={1,0,0,0};
float boundarySize=5;
//Inner
swColor innerColor={0,1,0,0};
//Elips
swPoint elipsPos={400,300};
swDimension elipsDim={250,150};
int elipsSmoothness=60;
swKeyboardState keybState;
swMouseState mousState;
char lineName[5]="line";
char pointName[6]="point";
//-------------------------------------------------------------------------------------------
void GameLoop(){
swInputListenKeyboard(&keybState);
swInputListenMouse(&mousState);
swInteractionManagerExecute(&keybState,&mousState);
swGraphicsBeginScene();
swGraphicsSetBgColor1(0,0,0,0);
//Fill Elips
swGraphicsSetColor1(&innerColor);
swGraphicsRenderSolidElips1(&elipsPos,&elipsDim,elipsSmoothness);
//Draw Elips Boundary
swGraphicsSetColor1(&boundaryColor);
if(boundaryStyle==BOUNDARY_POINT){
swGraphicsRenderPointElips1(&elipsPos,&elipsDim,elipsSmoothness,boundarySize);
}else if(boundaryStyle==BOUNDARY_LINE){
swGraphicsRenderLineElips1(&elipsPos,&elipsDim,elipsSmoothness,boundarySize);
}
//Manage GUI System
swDispManagerExecute();
//Display Cursor
//swGraphicsSetColor1(&SWCOLOR_BLUE);
//swGraphicsRenderPoint0(mousState.x,mousState.y,10);
swGraphicsEndScene();
if(keybState.keyESCAPE){
swEngineExit();
}
}
//-------------------------------------------------------------------------------------------
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
//Application Settings
propertyWinApp.hInstance=hInstance;
propertyWinApp.fullScreen=false;
propertyWinApp.cursor=true;
propertyWinApp.width=800;
propertyWinApp.height=600;
propertyWinApp.title="PropertyWin";
propertyWinApp.path="\\rsc\\PropertyWin\\";
propertyWinApp.appRun=GameLoop;
//Application Execution
swEngineInit(&propertyWinApp);
//Set Resource Path (Logo, Font, IconSet)
swNumPropWinSetPath("NumPropWinRsc\\");
//CreateEnumList
int enumList=swLinkedListCreate();
swLinkedListAdd(enumList,lineName);
swLinkedListAdd(enumList,pointName);
//Create Windows
int winID=swNumPropWinCreate("Elips Property",200,200,300,4);
int winElipsPosID=swNumPropPointWinCreate("Center",300,300,&elipsPos);
int winElipsDimID=swNumPropDimWinCreate("Size",300,300,&elipsDim);
int winInnerColorID=swNumPropColorWinCreate("Fill Color",300,300,&innerColor);
int winBoundaryColorID=swNumPropColorWinCreate("Boundary Color",300,300,&boundaryColor);
//Add Property To WinID(Elips Property Win)
swNumPropWinAddInt(winID,"Smooth",&elipsSmoothness,3,100,1);
swNumPropWinAddEnum(winID,"BoundaryType",&boundaryStyle,enumList);
swNumPropWinAddFloat(winID,"BoundarySize",&boundarySize,0.0f,10.0f,1.0f);
swNumPropWinAddSubWin(winID,winElipsPosID);
swNumPropWinAddSubWin(winID,winElipsDimID);
swNumPropWinAddSubWin(winID,winInnerColorID);
swNumPropWinAddSubWin(winID,winBoundaryColorID);
swNumPropWinSetVisible(winID,true);
swEngineRun();
swEngineExit();
return 0;
}
| 27.045455
| 93
| 0.721289
|
odayibasi
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.