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
82fc7cf3155ac30eb2a42e2d690d5be36b76e689
1,816
cpp
C++
trainings/2015-11-03-Changsha-2013/I.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-11-03-Changsha-2013/I.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-11-03-Changsha-2013/I.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> using namespace std; const int N = 100005; int n, X, Y, tot = 0; int value[N], S[N], P[N], F[N]; int start[N]; pair<int, int> f[N][2]; struct Node { int x, y, next; } road[N << 1]; void build(int x, int y) { tot++; road[tot].x = x, road[tot].y = y, road[tot].next = start[x], start[x] = tot; } pair<int, int> add(pair<int, int> x, pair<int, int> y) { return make_pair(x.first + y.first, x.second + y.second); } pair<int, int> uni(pair<int, int> x, pair<int, int> y) { return make_pair(max(x.first, y.first), min(x.second, y.second)); } void dfs(int x, int fa, int flag) { flag ^= S[x]; int now_value = value[x]; if ((flag ^ P[x]) == 1) { now_value *= -1; } pair<int, int> current = make_pair(now_value, now_value); f[x][0] = current; for (int i = start[x]; i; i = road[i].next) { int to = road[i].y; if (to == fa) { continue; } dfs(to, x, flag); f[x][0] = add(f[x][0], uni(f[to][0], f[to][1])); } f[x][1] = make_pair(-f[x][0].second, -f[x][0].first); int delta = 0; if (S[x]) { delta = Y; } else { delta = X; } f[x][1].first -= delta; f[x][1].second += delta; return; } void work() { tot = 0; for (int i = 1; i <= n + 1; i++) { start[i] = 0; } for (int i = 2; i <= n + 1; i++) { scanf("%d%d%d%d", &value[i], &F[i], &S[i], &P[i]); F[i]++; build(F[i], i); } dfs(1, 0, 0); if (f[1][0].first < 0) { puts("HAHAHAOMG"); } else { printf("%d\n", f[1][0].first); } return; } int main() { while (scanf("%d%d%d", &n, &X, &Y) == 3) { work(); } return 0; }
20.873563
80
0.467511
HcPlu
82fccde8b90c432f1a32fadf9a0ec364c7aeb791
8,385
cpp
C++
src/gl9_scene/player.cpp
andsulavik/ppgso
44385aa9d8ee5f9a2951dfeb5e7c3e605377c68b
[ "MIT" ]
null
null
null
src/gl9_scene/player.cpp
andsulavik/ppgso
44385aa9d8ee5f9a2951dfeb5e7c3e605377c68b
[ "MIT" ]
null
null
null
src/gl9_scene/player.cpp
andsulavik/ppgso
44385aa9d8ee5f9a2951dfeb5e7c3e605377c68b
[ "MIT" ]
null
null
null
#include "player.h" #include "scene.h" #include "road.h" #include "Pipe.h" #include "Monster.h" #include "shadow.h" #include <shaders/diffuse_vert_glsl.h> #include <shaders/diffuse_frag_glsl.h> // shared resources std::unique_ptr<ppgso::Mesh> Player::mesh; std::unique_ptr<ppgso::Texture> Player::texture; std::unique_ptr<ppgso::Shader> Player::shader; Player::Player() { // Scale the default model scale *= 3.0f; position.y = 4.0f; // Initialize static resources if needed if (!shader) shader = std::make_unique<ppgso::Shader>(diffuse_vert_glsl, diffuse_frag_glsl); if (!texture) { texture = std::make_unique<ppgso::Texture>(ppgso::image::loadBMP("Toot_Braustein.bmp")); } if (!mesh) mesh = std::make_unique<ppgso::Mesh>("Toot_Braustein.obj"); } bool decrease, increase = true, death = false, intangibleL = true, intangibleR = true, monsterKill = false, pipe = false; float dist1 = 0, dist2 = 0; bool Player::update(Scene &scene, float dt) { // Fire delay increment fireDelay += dt; float closestDist = 0; for (auto &obj : scene.objects) { // Ignore self in scene if (obj.get() == this) continue; // We only need to collide with asteroids and projectiles, ignore other objects auto road = dynamic_cast<Road*>(obj.get()); // dynamic_pointer_cast<Road>(obj); auto pipe = dynamic_cast<Pipe*>(obj.get()); auto monster = dynamic_cast<Monster*>(obj.get()); if (!road and !pipe and !monster) continue; // When colliding with other asteroids make sure the object is older than .5s // This prevents excessive collisions when asteroids explode. // if (asteroid && age < 0.5f) continue; // Compare distance to approximate size of the asteroid estimated from scale.y if(closestDist != 0 and closestDist > distance(position, obj->position)){ closestRd = road; closestDist = distance(position, obj->position); } else if(closestDist == 0){ closestRd = road; closestDist = distance(position, obj->position); } } if((closestRd->monster != nullptr) and !monsterKill and ((closestRd->monster->position.x + 5.5f >= position.x and closestRd->monster->position.x <= position.x) or (closestRd->monster->position.x - 5.5f <= position.x and closestRd->monster->position.x >= position.x)) and abs(abs(closestRd->monster->position.y)-abs(position.y)) < 9.5f){ position.y += 10.6f; monsterKill = true; } if((position.y <= closestRd->position.y + 4.f and position.y >= closestRd->position.y-17.f) and (position.x < closestRd->position.x-2.f or position.x > closestRd->position.x+2.f)){ intangibleL = true; intangibleR = true; if(position.x > closestRd->position.x - 30.f and (position.x < closestRd->position.x)){ intangibleR = false; intangibleL = true; } else if(position.x < closestRd->position.x + 30.f and (position.x > closestRd->position.x)){ intangibleL = false; intangibleR = true; } } else{ intangibleL = true; intangibleR = true; } if (glm::length(closestRd->position.x - position.x) < (closestRd->scale.x + scale.x)*0.6 and distance(position, closestRd->position) < (closestRd->scale.y + scale.y) *2.f ) { death = false; } else{ death = true; } if(monsterKill == true){ position.y -= 1.6f; rotation.x -= 0.05f; rotation.z -= 0.005f; rotation.y -= 0.005f; scene.camera->position.y -= 1.6f; if(position.y <= -50){ monsterKill = false; return false; } } else { if(closestRd->pipe != nullptr){ if(closestRd->right){ position.x -= 0.6f; scene.camera->position.x -= 0.6f; } else{ position.x += 0.6f; scene.camera->position.x += 0.6f; } } if (position.y >= dist1 + 45.f) { increase = false; decrease = true; } if (increase) { position.y += 1.6f; scene.camera->position.y += 1.6f; } else if (decrease or (decrease and increase)) { if (closestRd->pipe != nullptr and position.x <= closestRd->pipe->position.x + 11.f and position.x >= closestRd->pipe->position.x - 11.f and position.y <= closestRd->pipe->position.y + 1.f and position.y >= closestRd->pipe->position.y - 0.5f) { pipe = true; if(closestRd->pipe->cactus->position.y > closestRd->pipe->position.y +1.f){ monsterKill = true; pipe = death = increase = decrease = false; } } else{ pipe = false; position.y -= 1.6f; scene.camera->position.y -= 1.6f; } } else if (death) { increase = false; decrease = true; position.y -= 1.6f; scene.camera->position.y -= 1.6f; } if ((position.y >= closestRd->position.y + 4.f and position.y <= closestRd->position.y + 4.8f) and !death) { decrease = increase = false; } if (position.y <= -50 and death) { death = false; increase = true; return false; } if (rotation.z == NULL) { //rotation.z = 4.4f; rotation.z = 9; } // Keyboard controls if (scene.keyboard[GLFW_KEY_LEFT]) { if (increase or decrease) { if (intangibleR) { position.x += 10 * 8 * dt; scene.camera->position.x += 10 * 8 * dt; } } else { if (intangibleR) { position.x += 10 * 6 * dt; scene.camera->position.x += 10 * 6 * dt; } } rotation.z = -4.8f; if (scene.keyboard[GLFW_KEY_SPACE] and !death and !increase and !decrease or (scene.keyboard[GLFW_KEY_SPACE] and !increase and pipe)) { if(pipe){ dist1 = closestRd->pipe->position.y; } else{ dist1 = closestRd->position.y; } increase = true; } } else if (scene.keyboard[GLFW_KEY_RIGHT]) { if (increase or decrease) { if (intangibleL) { position.x -= 10 * 8 * dt; scene.camera->position.x -= 10 * 8 * dt; } } else { if (intangibleL) { position.x -= 10 * 6 * dt; scene.camera->position.x -= 10 * 6 * dt; } } rotation.z = 4.8f; if (scene.keyboard[GLFW_KEY_SPACE] and !death and !increase and !decrease or (scene.keyboard[GLFW_KEY_SPACE] and !increase and pipe)) { increase = true; if(pipe){ dist1 = closestRd->pipe->position.y; } else{ dist1 = closestRd->position.y; } } } else if (scene.keyboard[GLFW_KEY_SPACE] and !death and !increase and !decrease or (scene.keyboard[GLFW_KEY_SPACE] and pipe)) { increase = true; if(pipe){ dist1 = closestRd->pipe->position.y; } else{ dist1 = closestRd->position.y; } } } if(shadow != nullptr){ shadow->posPlayerX = position.x; shadow->posPlayerY = closestRd->position.y+5.f; shadow->update(scene, dt); } generateModelMatrix(); return true; } void Player::render(Scene &scene) { shader->use(); if(shadow != nullptr and !death ){ if(position.x <= closestRd->position.x + 10.5f){ shadow->render(scene); } } // Set up light shader->setUniform("LightDirection", scene.lightDirection); // use camera shader->setUniform("ProjectionMatrix", scene.camera->projectionMatrix); shader->setUniform("ViewMatrix", scene.camera->viewMatrix); // render mesh shader->setUniform("ModelMatrix", modelMatrix); shader->setUniform("Texture", *texture); mesh->render(); } void Player::onClick(Scene &scene) { std::cout << "Player has been clicked!" << std::endl; }
35.231092
339
0.545021
andsulavik
82fd78c9bf8f1f535b4665f06a6c897b2ea7553f
2,646
cpp
C++
ogsr_engine/xrCore/cpuid.cpp
WarezzK/OGSE-WarezzKCZ-Engine
9d5a594edd7d8f2edf5e1d831f380bc817400e17
[ "Apache-2.0" ]
3
2019-09-10T13:37:08.000Z
2021-05-18T14:53:29.000Z
ogsr_engine/xrCore/cpuid.cpp
Rikoshet-234/rebirth_engine
7ad4e8a711434e8346b7c97b3a82447695418344
[ "Apache-2.0" ]
null
null
null
ogsr_engine/xrCore/cpuid.cpp
Rikoshet-234/rebirth_engine
7ad4e8a711434e8346b7c97b3a82447695418344
[ "Apache-2.0" ]
2
2020-06-26T11:50:59.000Z
2020-12-30T11:07:31.000Z
#include "stdafx.h" #include "cpuid.h" #include <intrin.h> decltype(auto) countSetBits(ULONG_PTR bitMask) { DWORD LSHIFT = sizeof(ULONG_PTR) * 8 - 1; DWORD bitSetCount = 0; auto bitTest = static_cast<ULONG_PTR>(1) << LSHIFT; DWORD i; for (i = 0; i <= LSHIFT; ++i) { bitSetCount += ((bitMask & bitTest) ? 1 : 0); bitTest /= 2; } return bitSetCount; } _processor_info::_processor_info() { int cpinfo[4]; // detect cpu vendor __cpuid(cpinfo, 0); memcpy(vendor, &(cpinfo[1]), sizeof(int)); memcpy(vendor + sizeof(int), &(cpinfo[3]), sizeof(int)); memcpy(vendor + 2 * sizeof(int), &(cpinfo[2]), sizeof(int)); // detect cpu model __cpuid(cpinfo, 0x80000002); memcpy(brand, cpinfo, sizeof(cpinfo)); __cpuid(cpinfo, 0x80000003); memcpy(brand + sizeof(cpinfo), cpinfo, sizeof(cpinfo)); __cpuid(cpinfo, 0x80000004); memcpy(brand + 2 * sizeof(cpinfo), cpinfo, sizeof(cpinfo)); // detect cpu main features __cpuid(cpinfo, 1); stepping = cpinfo[0] & 0xf; model = (u8)((cpinfo[0] >> 4) & 0xf) | ((u8)((cpinfo[0] >> 16) & 0xf) << 4); family = (u8)((cpinfo[0] >> 8) & 0xf) | ((u8)((cpinfo[0] >> 20) & 0xff) << 4); m_f1_ECX = cpinfo[2]; m_f1_EDX = cpinfo[3]; __cpuid(cpinfo, 7); m_f7_EBX = cpinfo[1]; m_f7_ECX = cpinfo[2]; // and check 3DNow! support __cpuid(cpinfo, 0x80000001); m_f81_ECX = cpinfo[2]; m_f81_EDX = cpinfo[3]; // get version of OS DWORD dwMajorVersion = 0; DWORD dwVersion = 0; dwVersion = GetVersion(); dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); if (dwMajorVersion <= 5) // XP don't support SSE3+ instruction sets { m_f1_ECX[0] = 0; m_f1_ECX[9] = 0; m_f1_ECX[19] = 0; m_f1_ECX[20] = 0; m_f81_ECX[6] = 0; m_f1_ECX[28] = 0; m_f7_EBX[5] = 0; } // Calculate available processors DWORD returnedLength = 0; DWORD byteOffset = 0; GetLogicalProcessorInformation(nullptr, &returnedLength); auto buffer = std::make_unique<u8[]>(returnedLength); auto ptr = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION>(buffer.get()); GetLogicalProcessorInformation(ptr, &returnedLength); auto processorCoreCount = 0u; auto logicalProcessorCount = 0u; while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnedLength) { switch (ptr->Relationship) { case RelationProcessorCore: processorCoreCount++; // A hyperthreaded core supplies more than one logical processor. logicalProcessorCount += countSetBits(ptr->ProcessorMask); break; default: break; } byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ptr++; } // All logical processors coresCount = processorCoreCount; threadCount = logicalProcessorCount; }
25.442308
86
0.685563
WarezzK
82ffd34e6213c3599aab61f248440f88097cc972
252
cpp
C++
src/examples/04_module/01_while/main.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Grecia1813
f356c1ed8f6e75b9e9d6164747a5c199bead8c95
[ "MIT" ]
null
null
null
src/examples/04_module/01_while/main.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Grecia1813
f356c1ed8f6e75b9e9d6164747a5c199bead8c95
[ "MIT" ]
null
null
null
src/examples/04_module/01_while/main.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Grecia1813
f356c1ed8f6e75b9e9d6164747a5c199bead8c95
[ "MIT" ]
null
null
null
#include "while.h" #include<iostream> using std::cout; using std::cin; int main() { char choice = 'y'; while (choice == 'y' || choice == 'Y') { cout << "Enter y to continue, any other char to exit: "; cin >> choice; } return 0; }
14
60
0.563492
acc-cosc-1337-fall-2020
d2016de542aef1d6c665c2f8b9aa17391c792f1a
12,458
hpp
C++
ares/component/processor/sh2/sh7604/sh7604.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ares/component/processor/sh2/sh7604/sh7604.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
176
2020-07-25T19:11:23.000Z
2021-10-04T17:11:32.000Z
ares/component/processor/sh2/sh7604/sh7604.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#pragma once //Hitachi SH7604 //struct SH2 { enum : u32 { Byte, Word, Long }; struct Area { enum : u32 { Cached = 0, Uncached = 1, Purge = 2, Address = 3, Data = 6, IO = 7, };}; //bus.cpp auto readByte(u32 address) -> u32; auto readWord(u32 address) -> u32; auto readLong(u32 address) -> u32; auto writeByte(u32 address, u32 data) -> void; auto writeWord(u32 address, u32 data) -> void; auto writeLong(u32 address, u32 data) -> void; //io.cpp auto internalReadByte(u32 address, n8 data = 0) -> n8; auto internalWriteByte(u32 address, n8 data) -> void; struct Cache { maybe<SH2&> self; //cache.cpp template<u32 Size> auto read(u32 address) -> u32; template<u32 Size> auto write(u32 address, u32 data) -> void; template<u32 Size> auto readData(u32 address) -> u32; template<u32 Size> auto writeData(u32 address, u32 data) -> void; auto readAddress(u32 address) -> u32; auto writeAddress(u32 address, u32 data) -> void; auto purge(u32 address) -> void; template<u32 Ways> auto purge() -> void; auto power() -> void; //serialization.cpp auto serialize(serializer&) -> void; enum : u32 { Way0 = 0 * 64, Way1 = 1 * 64, Way2 = 2 * 64, Way3 = 3 * 64, Invalid = 1 << 19, }; union Line { u8 bytes[16]; u16 words[8]; u32 longs[4]; }; u8 lrus[64]; u32 tags[4 * 64]; Line lines[4 * 64]; n1 enable; n1 disableCode; n1 disableData; n2 twoWay; //0 = 4-way, 2 = 2-way (forces ways 2 and 3) n2 waySelect; //internal: n2 lruSelect[64]; n6 lruUpdate[4][64]; } cache; //interrupt controller struct INTC { maybe<SH2&> self; //interrupts.cpp auto run() -> void; //serialization.cpp auto serialize(serializer&) -> void; struct ICR { //interrupt control register n1 vecmd; //IRL interrupt vector mode select n1 nmie; //NMI edge select n1 nmil; //NMI input level } icr; struct IPRA { //interrupt priority level setting register A n4 wdtip; //WDT interrupt priority n4 dmacip; //DMAC interrupt priority n4 divuip; //DIVU interrupt priority } ipra; struct IPRB { //interrupt priority level setting register B n4 frtip; //FRT interrupt priority n4 sciip; //SCI interrupt priority } iprb; struct VCRA { //vector number setting register A n7 srxv; //SCI receive data full interrupt vector number n7 serv; //SCI receive error interrupt vector number } vcra; struct VCRB { //vector number setting register B n7 stev; //SCI transmit end interrupt vector number n7 stxv; //SCI transmit data empty interrupt vector number } vcrb; struct VCRC { //vector number setting register C n7 focv; //FRT output compare interrupt vector number n7 ficv; //FRT input capture interrupt vector number } vcrc; struct VCRD { //vector number setting register D n7 fovv; //FRT overflow interrupt vector number } vcrd; struct VCRWDT { //vector number setting register WDT n4 bcmv; //BSC compare match interrupt vector number n4 witv; //WDT interval interrupt vector number } vcrwdt; } intc; //DMA controller struct DMAC { maybe<SH2&> self; //dma.cpp auto run() -> void; auto transfer(bool c) -> void; //serialization.cpp auto serialize(serializer&) -> void; n32 sar[2]; //DMA source address registers n32 dar[2]; //DMA destination address registers n24 tcr[2]; //DMA transfer count registers struct CHCR { //DMA channel control registers n1 de; //DMA enable n1 te; //transfer end flag n1 ie; //interrupt enable n1 ta; //transfer address mode n1 tb; //transfer bus mode n1 dl; //DREQn level bit n1 ds; //DREQn select bit n1 al; //acknowledge level bit n1 am; //acknowledge/transfer mode bit n1 ar; //auto request mode bit n2 ts; //transfer size n2 sm; //source address mode n2 dm; //destination address mode } chcr[2]; n8 vcrdma[2]; //DMA vector number registers n2 drcr[2]; //DMA request/response selection control registers struct DMAOR { //DMA operation register n1 dme; //DMA master enable bit n1 nmif; //NMI flag bit n1 ae; //address error flag bit n1 pr; //priority mode bit } dmaor; //internal: n1 dreq; n2 pendingIRQ; } dmac; //serial communication interface struct SCI { maybe<SH2&> self; maybe<SH2&> link; //serial.cpp auto run() -> void; //serialization.cpp auto serialize(serializer&) -> void; struct SMR { //serial mode register n2 cks; //clock select n1 mp; //multi-processor mode n1 stop; //stop bit length n1 oe; //parity mode n1 pe; //parity enable n1 chr; //character length n1 ca; //communication mode } smr; struct SCR { //serial control register n2 cke; //clock enable n1 teie; //transmit end interrupt enable n1 mpie; //multi-processor interrupt enable n1 re; //receive enable n1 te; //transmit enable n1 rie; //receive interrupt enable n1 tie; //transmit interrupt enable } scr; struct SSR { //serial status register n1 mpbt; //multi-processor bit transfer n1 mpb; //multi-processor bit n1 tend = 1; //transmit end n1 per; //parity error n1 fer; //framing error n1 orer; //overrun error n1 rdrf; //receive data register full n1 tdre; //transmit data register empty } ssr; n8 brr = 0xff; //bit rate register n8 tdr = 0xff; //transmit data register n8 rdr = 0x00; //receive data register //internal: n1 pendingTransmitEmptyIRQ; n1 pendingReceiveFullIRQ; } sci; //watchdog timer struct WDT { //serialization.cpp auto serialize(serializer&) -> void; struct WTCSR { //watchdog timer control/status register n3 cks; //clock select n1 tme; //timer enable n1 wtit; //timer mode select n1 ovf; //overflow flag } wtcsr; struct RSTCSR { //reset control/status register n1 rsts; //reset select n1 rste; //reset enable n1 wovf; //watchdog timer overflow flag } rstcsr; n8 wtcnt; //watchdog timer counter } wdt; //user break controller struct UBC { //serialization.cpp auto serialize(serializer&) -> void; n32 bara; //break address register A n32 bamra; //break address mask register A struct BBRA { //break bus register A n2 sza; //operand size select A n2 rwa; //read/write select A n2 ida; //instruction fetch/data access select A n2 cpa; //CPU cycle/peripheral cycle select A } bbra; n32 barb; //break address register B n32 bamrb; //break address mask register B struct BBRB { //break bus register B n2 szb; //operand size select B n2 rwb; //read/write select B n2 idb; //instruction fetch/data access select B n2 cpb; //CPU cycle/peripheral cycle select B } bbrb; n32 bdrb; //break data register B n32 bdmrb; //break data mask register B struct BRCR { //break control register n1 pcbb; //instruction break select B n1 dbeb; //data break enable B n1 seq; //sequence condition select n1 cmfpb; //peripheral condition match flag B n1 cmfcb; //CPU condition match flag B n1 pcba; //PC break select A n1 umd; //UBC mode n1 ebbe; //external bus break enable n1 cmfpa; //peripheral condition match flag A n1 cmfca; //CPU condition match flag A } brcr; } ubc; //16-bit free-running timer struct FRT { maybe<SH2&> self; //timer.cpp auto run() -> void; //serialization.cpp auto serialize(serializer&) -> void; struct TIER { //timer interrupt enable register n1 ovie; //timer overflow interrupt enable n1 ociae; //output compare interrupt enable A n1 ocibe; //output compare interrupt enable B n1 icie; //input capture interrupt enable } tier; struct FTCSR { //free-running timer control/status register n1 cclra; //counter clear A n1 ovf; //timer overflow flag n1 ocfa; //output compare flag A n1 ocfb; //output compare flag B n1 icf; //input capture flag } ftcsr; n16 frc; //free-running counter n16 ocra; //output compare register A n16 ocrb; //output compare register B struct TCR { //timer control register n2 cks; //clock select n1 iedg; //input edge select } tcr; struct TOCR { //timer output compare control register n1 olvla; //output level A n1 olvlb; //output level B n1 ocrs; //output compare register select } tocr; n16 ficr; //input capture register //internal: n32 counter; n1 pendingOutputIRQ; } frt; //bus state controller struct BSC { //serialization.cpp auto serialize(serializer&) -> void; struct BCR1 { //bus control register 1 n3 dram; //enable for DRAM and other memory n2 a0lw; //long wait specification for area 0 n2 a1lw; //long wait specification for area 1 n2 ahlw; //long wait specification for ares 2 and 3 n1 pshr; //partial space share specification n1 bstrom; //area 0 burst ROM enable n1 a2endian; //endian specification for area 2 n1 master; //bus arbitration (0 = master; 1 = slave) } bcr1; struct BCR2 { //bus control register 2 n2 a1sz; //bus size specification for area 1 n2 a2sz; //bus size specification for area 2 n2 a3sz; //bus size specification for area 3 } bcr2; struct WCR { //wait control register n2 w0; //wait control for area 0 n2 w1; //wait control for area 1 n2 w2; //wait control for area 2 n2 w3; //wait control for area 3 n2 iw0; //idles between cycles for area 0 n2 iw1; //idles between cycles for area 1 n2 iw2; //idles between cycles for area 2 n2 iw3; //idles between cycles for area 3 } wcr; struct MCR { //individual memory control register n1 rcd; //RAS-CAS delay n1 trp; //RSA precharge time n1 rmode; //refresh mode n1 rfsh; //refresh control n3 amx; //address multiplex n1 sz; //memory data size n1 trwl; //write-precharge delay n1 rasd; //bank active mode n1 be; //burst enable n2 tras; //CAS before RAS refresh RAS assert time } mcr; struct RTCSR { //refresh timer control/status register n3 cks; //clock select n1 cmie; //compare match interrupt enable n1 cmf; //compare match flag } rtcsr; n8 rtcnt; //refresh timer counter n8 rtcor; //refresh time constant register } bsc; //standby control register struct SBYCR { //serialization.cpp auto serialize(serializer&) -> void; n1 sci; //SCI halted n1 frt; //FRT halted n1 divu; //DIVU halted n1 mult; //MULT halted n1 dmac; //DMAC halted n1 hiz; //port high impedance n1 sby; //standby } sbycr; //division unit struct DIVU { //serialization.cpp auto serialize(serializer&) -> void; n32 dvsr; //divisor register struct DVCR { //division control register n1 ovf; //overflow flag n1 ovfie; //overflow interrupt enable } dvcr; n7 vcrdiv; //vector number setting register n32 dvdnth; //dividend register H n32 dvdntl; //dividend register L } divu; //};
32.025707
70
0.581153
CasualPokePlayer
d203bf517b9b61576aa40c7c8c7f8827b60d7bb8
12,034
cpp
C++
MEX/src/cpp/vision/features/low_level/self_similarity.cpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
47
2016-07-25T00:48:59.000Z
2021-02-17T09:19:03.000Z
MEX/src/cpp/vision/features/low_level/self_similarity.cpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
5
2016-09-17T19:40:46.000Z
2018-11-07T06:49:02.000Z
MEX/src/cpp/vision/features/low_level/self_similarity.cpp
iqbalu/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
35
2016-07-21T09:13:15.000Z
2019-05-13T14:11:37.000Z
/* * self_similarity.cpp * * Created on: Jan 25, 2012 * Author: lbossard */ #include "self_similarity.hpp" #include <boost/math/constants/constants.hpp> #include <boost/foreach.hpp> namespace vision { namespace features { SelfSimilarityExtractor::SelfSimilarityExtractor( bool color_ssd, unsigned int patch_size, unsigned int window_radius, unsigned int radius_bin_count, unsigned int angle_bin_count, float var_noise, unsigned int auto_var_radius) { color_ssd_ = color_ssd; this->setSelfSimilarityParameters( patch_size, window_radius, radius_bin_count, angle_bin_count, var_noise, auto_var_radius); } void SelfSimilarityExtractor::setSelfSimilarityParameters( unsigned int patch_size, unsigned int window_radius, unsigned int radius_bin_count, unsigned int angle_bin_count, float var_noise, unsigned int auto_var_radius) { self_similarity_.setParameters(patch_size, window_radius, radius_bin_count, angle_bin_count, var_noise, auto_var_radius); } /*virtual*/ SelfSimilarityExtractor::~SelfSimilarityExtractor() { } /*virtual*/ cv::Mat_<float> SelfSimilarityExtractor::denseExtract( const cv::Mat& input_image, std::vector<cv::Point>& locations, const cv::Mat_<uchar>& mask ) const { const unsigned int radius = 5; // generate locations locations.clear(); LowLevelFeatureExtractor::generateGridLocations( input_image.size(), cv::Size(radius, radius), radius, radius, locations, mask); if (locations.size() == 0) { return cv::Mat_<float>(); } // convert to gray if necessary cv::Mat image = input_image; if (!color_ssd_ && image.type() != CV_8U) { cv::cvtColor(image, image, CV_BGR2GRAY); } // allocate memroy cv::Mat_<float> features(locations.size(), descriptorLength()); // loop over locations and compute descriptors std::size_t point_idx = 0; BOOST_FOREACH(const cv::Point& p, locations) { cv::Mat_<float> descriptor = features.row(point_idx); if (self_similarity_.extract(image, p, descriptor)) { ++point_idx; } } if (point_idx == 0) { return cv::Mat_<float>(); } features.resize(point_idx); return features; } /*virtual*/ unsigned int SelfSimilarityExtractor::descriptorLength() const { return self_similarity_.descriptorLength(); } //////////////////////////////////////////////////////////////////////////////// /** * * @param patch_size odd * @param window_radius even * @param radius_bin_count * @param angle_bin_count * @param var_noise * @param auto_var_radius */ SelfSimilarity::SelfSimilarity( unsigned int patch_size, unsigned int window_radius, unsigned int radius_bin_count, unsigned int angle_bin_count, float var_noise, unsigned int auto_var_radius) { setParameters(patch_size, window_radius, radius_bin_count, angle_bin_count, var_noise, auto_var_radius); } /*virtual*/ SelfSimilarity::~SelfSimilarity() { } void SelfSimilarity::setParameters(unsigned int patch_size, unsigned int window_radius, unsigned int radius_bin_count, unsigned int angle_bin_count, float var_noise, unsigned int auto_var_radius) { // set parameters patch_size_ = patch_size; window_radius_ = window_radius; radius_bin_count_ = radius_bin_count; angle_bin_count_ = angle_bin_count; var_noise_ = var_noise; // precompute binning and autovar indices const int window_size = 2 * window_radius_ + 1; bin_map_= -cv::Mat_<int>::ones(window_size, window_size); // init to -1 autovar_indices_.clear(); autovar_indices_.reserve((2*auto_var_radius + 1)*(2*auto_var_radius + 1)); // upper bound double angle = 0.f; double radius = 0.f; int angle_bin = 0; int radius_bin = 0; int bin_id = 0; for (int y = -window_radius_; y < window_size; ++y) { for (int x = -window_radius_; x < window_size; ++x) { /* * scale log(y) to (bin_count - 1)...0 */ radius = std::sqrt(static_cast<float>(x * x + y * y)); if (radius > window_radius_ || radius == 0.) { continue; } radius_bin = static_cast<int>( ( std::log(radius)) / std::log(window_radius_+.5) * radius_bin_count_); /* * \alpha \in [ -\pi ... +\pi ] * bin_id \in [0 ... (bin_count - 1) ] * bin_id = floor( (\alpha + \pi) / ( 2 \pi) * bin_count ) * = floor( \alpha bin_count / ( 2 \pi) + bin_count/2 ) */ angle = std::atan2(y, x); // [-pi ... pi] angle_bin = static_cast<int>( ((angle * angle_bin_count_) / ( boost::math::constants::two_pi<double>())) + angle_bin_count_/2.) % angle_bin_count; // atan2 gives [-pi ... pi] and not (-pi ... pi] that's why we mod bin_id = angle_bin * radius_bin_count + radius_bin; bin_map_(y + window_radius_, x + window_radius_) = bin_id; if (radius <= auto_var_radius && radius > 0) { autovar_indices_.push_back(cv::Point(y + window_radius_, x + window_radius_)); } } } } bool SelfSimilarity::extract(const cv::Mat& image, const cv::Point& location, cv::Mat_<float>& descriptor) const { // compute the distance surface cv::Mat_<float> distance_surface; compute_distance_surface(image, location, distance_surface); if (distance_surface.rows == 0 || distance_surface.cols == 0) { return false; } // put it into the logpolar descriptor compute_descriptor(distance_surface, descriptor); return true; } //void showmat(const std::string titile, const cv::Mat& mat, int size) //{ // cv::Mat scaled; // cv::resize(mat, scaled, cv::Size(mat.rows * size, mat.cols * size), 0, 0, cv::INTER_AREA); // cv::imshow(titile, scaled); //} void SelfSimilarity::compute_distance_surface(const cv::Mat& image, const cv::Point& loaction, cv::Mat_<float>& distance_surface) const { const int patch_radius = patch_size_ / 2; const int window_size = window_radius_ * 2 + 1; // check boundaries if ( (loaction.x - (int)window_radius_ - patch_radius) < 0 || (loaction.y - (int)window_radius_ - patch_radius) < 0 || (loaction.x + (int)window_radius_ + patch_size_) >= image.cols || (loaction.y + (int)window_radius_ + patch_size_) >= image.rows) { distance_surface = cv::Mat_<float>(); return; } // allocate memory and precompute some structures distance_surface.create(window_size, window_size); const cv::Mat inner_patch = image( cv::Range(loaction.y - patch_radius, loaction.y + patch_radius + 1), cv::Range(loaction.x - patch_radius, loaction.x + patch_radius + 1)); // assert(distance_surface.rows == window_size); // assert(distance_surface.cols == window_size); for (unsigned int r = 0; r < window_size; ++r) { const int y_window_patch_start = loaction.y - window_radius_ + r - patch_radius ; const cv::Range y_window_range( y_window_patch_start, y_window_patch_start + patch_size_); for (unsigned int c = 0; c < window_size; ++c) { // const int bin_idx = bin_map_(r,c); // if (bin_idx < 0) // { // continue; // } const int x_window_patch_start = loaction.x - window_radius_ + c - patch_radius; const cv::Range x_window_range( x_window_patch_start, x_window_patch_start + patch_size_); const cv::Mat window_patch = image(y_window_range, x_window_range); if (image.channels() == 3) { distance_surface(r, c) = ssd3(inner_patch, window_patch); } else { distance_surface(r, c) = ssd1(inner_patch, window_patch); } // showmat("inner", inner_patch, 100); // showmat("window_patch", window_patch, 100); // cv::Mat d = image.clone(); // // window_patch // cv::rectangle(d, // cv::Point(x_window_range.start, y_window_range.start), // cv::Point(x_window_range.end-1, y_window_range.end-1), // CV_RGB(0,255,255) // ); // // center_patch // cv::rectangle(d, // cv::Point(loaction.x - patch_radius, loaction.y - patch_radius), // cv::Point(loaction.x + patch_radius, loaction.y + patch_radius), // CV_RGB(255,0,255) // ); // // whole window // cv::rectangle(d, // cv::Point( // loaction.x - window_radius_, // loaction.y - window_radius_), // cv::Point( // loaction.x + window_radius_, // loaction.y + window_radius_), // CV_RGB(255,0,255) // ); // showmat("all", d, 5); // cv::waitKey(); } } } void SelfSimilarity::compute_descriptor(const cv::Mat_<float>& distance_surface, cv::Mat_<float>& descriptor) const { // allocate log-polar descriptor. we init it with -1 as the e^-x is // always > 0 for x < \inf const int descriptor_length = radius_bin_count_*angle_bin_count_; descriptor.create(1, descriptor_length); descriptor = -1; // compute auto noise (like original paper matlab implementation): // find max ssd at the autovar_indices (<- places with within radius 1) float variance = var_noise_; for (unsigned int i = 0; i < autovar_indices_.size(); ++i) { const cv::Point& p = autovar_indices_[i]; variance = std::max(variance, distance_surface(p.y, p.x)); } // compute finally the descriptor float min_correlation = std::numeric_limits<float>::max(); float max_correlation = std::numeric_limits<float>::min(); for (int r = 0; r < distance_surface.rows; ++r) { for (int c = 0; c < distance_surface.cols; ++c) { const int bin_idx = bin_map_(r,c); if (bin_idx < 0) { continue; } // compute S_q(x,y) float correlation = std::exp(-distance_surface(r, c) / variance); // we store only the max ssd const float current_value = descriptor(bin_idx); if (current_value < correlation) { descriptor(bin_idx) = correlation; min_correlation = std::min(correlation, min_correlation); max_correlation = std::max(correlation, max_correlation); } } } // finally: normalize to [0 ... 1] //XXX: Note: in the original implementation, there would be only stretching to max without substracting min // however, the paper states "normalized by linearly streticht its values to the range [0...1]" // descriptor = (descriptor - min_correlation) / (max_correlation - min_correlation); //XXX: strange enough: "correct" normalization gives a segfault while clustering descriptor = descriptor / max_correlation; // normalisation from the paper implementation } } /* namespace features */ } /* namespace vision */
32.524324
135
0.575453
umariqb
d2083f4db1d876becc56a5bad6bee2ad78e4305a
1,491
hpp
C++
include/tinycoro/Algorithms.hpp
asmei1/tinycoro
5b6d3dc9412c8c9e369f652707894a586a8bd9a8
[ "MIT" ]
7
2020-12-21T02:16:33.000Z
2022-03-18T23:57:05.000Z
include/tinycoro/Algorithms.hpp
asmei1/tinycoro
5b6d3dc9412c8c9e369f652707894a586a8bd9a8
[ "MIT" ]
null
null
null
include/tinycoro/Algorithms.hpp
asmei1/tinycoro
5b6d3dc9412c8c9e369f652707894a586a8bd9a8
[ "MIT" ]
null
null
null
// // Created by Asmei on 11/25/2020. // #ifndef TINYCORO_ALGORITHMS_HPP #define TINYCORO_ALGORITHMS_HPP #include "FireAndForget.hpp" #include "Generator.hpp" namespace tinycoro { /* * Create endless stream, yielding objects from begin (inclusive). */ template <std::incrementable T> tinycoro::Generator<T> range(T begin) { while(true) { co_yield begin++; } } /* * Yield objects from begin (inclusive) to end (enxclusive) with incremental. */ template <std::incrementable T> tinycoro::Generator<T> range(T begin, T end) { while(begin != end) { co_yield begin++; } } /* * Yield objects from begin (inclusive) to end (enxclusive) with given step. */ template <typename T, typename Step> requires requires (T x, Step s) { x + s; } tinycoro::Generator<T> range(T begin, T end, Step step) { while(begin < end) { co_yield begin; begin += step; } } /* * Helper function to execute any coroutine as fire and forget function. * It could receive any awaitable object or coroutine function. */ template <typename T> FireAndForget fireAndForget(T t) { if constexpr(std::is_invocable_v<T>) { co_await t(); } else { co_await std::move(t); } } } #endif // TINYCORO_ALGORITHMS_HPP
21.926471
81
0.564051
asmei1
d20de518295a56f0fefa5c15bd74d41f867164d3
1,282
cpp
C++
test/echd/jsonrpc/eth_client.cpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
2
2020-06-01T00:30:12.000Z
2020-06-05T18:41:48.000Z
test/echd/jsonrpc/eth_client.cpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
null
null
null
test/echd/jsonrpc/eth_client.cpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
1
2020-06-05T18:33:28.000Z
2020-06-05T18:33:28.000Z
#include "catch2/catch.hpp" // Project includes #include "echd/jsonrpc/eth_client.hpp" using namespace ech; using Catch::Matchers::Equals; TEST_CASE("eth jsonrpc client leading zeroes empty", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::removeLeadingZeroes(std::string("")); REQUIRE(std::string_view("0") == s); } TEST_CASE("eth jsonrpc client leading zeroes zero", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::removeLeadingZeroes(std::string("0")); REQUIRE(std::string_view("0") == s); } TEST_CASE("eth jsonrpc client leading zeroes padded zero", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::removeLeadingZeroes(std::string("0000")); REQUIRE(std::string_view("0") == s); } TEST_CASE("eth jsonrpc client leading zeroes non-zero", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::removeLeadingZeroes(std::string("10")); REQUIRE(std::string_view("10") == s); } TEST_CASE("eth jsonrpc client leading zeroes padded non-zero", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::removeLeadingZeroes(std::string("0010")); REQUIRE(std::string_view("10") == s); } TEST_CASE("eth jsonrpc client 0x", "[daemon][jsonrpc]") { const auto s = eth::JsonHelper::formatHex(std::string("42")); REQUIRE(std::string_view("0x42") == s); }
26.163265
83
0.697348
adlerjohn
d20f99fe44a1a5a905bd94ecf7da6d4ec4d8bbbf
403
cpp
C++
BASIC c++/templetes/overloading_template_function.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/templetes/overloading_template_function.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/templetes/overloading_template_function.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
// // Created by rahul on 17/8/19. // #include <iostream> #include <string> using namespace std; template <class T> void display(T x) { cout<<"template display" << x<< '\n'; } void display(int x) { cout<<"explicit display"<<x<<'\n'; } void ccode(char ch) { int code; code=ch; cout<<code<<endl; } int main() { display(100); display(12.34); display('c'); ccode('A'); }
13.896552
41
0.575682
jattramesh
d210dfdab9fff4b7cffd630368c58ae205af467c
39,299
cpp
C++
samsung/hardware/exynos4/hal/libhwcomposer/SecHWCUtils.cpp
DrDoubt/android_device_samsung_universal9810-common-1
5a937d2994044c041c3c19192d7744200a036cc8
[ "Apache-2.0" ]
null
null
null
samsung/hardware/exynos4/hal/libhwcomposer/SecHWCUtils.cpp
DrDoubt/android_device_samsung_universal9810-common-1
5a937d2994044c041c3c19192d7744200a036cc8
[ "Apache-2.0" ]
null
null
null
samsung/hardware/exynos4/hal/libhwcomposer/SecHWCUtils.cpp
DrDoubt/android_device_samsung_universal9810-common-1
5a937d2994044c041c3c19192d7744200a036cc8
[ "Apache-2.0" ]
2
2021-07-04T19:41:36.000Z
2021-07-29T12:59:47.000Z
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Revision History: * - 2011/03/11 : Rama, Meka(v.meka@samsung.com) * Initial version * * - 2011/12/07 : Jeonghee, Kim(jhhhh.kim@samsung.com) * Add V4L2_PIX_FMT_YUV420M V4L2_PIX_FMT_NV12M * */ #include "SecHWCUtils.h" #define V4L2_BUF_TYPE_OUTPUT V4L2_BUF_TYPE_VIDEO_OUTPUT #define V4L2_BUF_TYPE_CAPTURE V4L2_BUF_TYPE_VIDEO_CAPTURE #define EXYNOS4_ALIGN( value, base ) (((value) + ((base) - 1)) & ~((base) - 1)) //#define CHECK_FPS #ifdef CHECK_FPS #include <sys/time.h> #include <unistd.h> #define CHK_FRAME_CNT 57 void check_fps() { static struct timeval tick, tick_old; static int total = 0; static int cnt = 0; int FPS; cnt++; gettimeofday(&tick, NULL); if (cnt > 10) { if (tick.tv_sec > tick_old.tv_sec) total += ((tick.tv_usec/1000) + (tick.tv_sec - tick_old.tv_sec)*1000 - (tick_old.tv_usec/1000)); else total += ((tick.tv_usec - tick_old.tv_usec)/1000); memcpy(&tick_old, &tick, sizeof(timeval)); if (cnt == (10 + CHK_FRAME_CNT)) { FPS = 1000*CHK_FRAME_CNT/total; ALOGE("[FPS]:%d\n", FPS); total = 0; cnt = 10; } } else { memcpy(&tick_old, &tick, sizeof(timeval)); total = 0; } } #endif struct yuv_fmt_list yuv_list[] = { { "V4L2_PIX_FMT_NV12", "YUV420/2P/LSB_CBCR", V4L2_PIX_FMT_NV12, 12, 2 }, { "V4L2_PIX_FMT_NV12T", "YUV420/2P/LSB_CBCR", V4L2_PIX_FMT_NV12T, 12, 2 }, { "V4L2_PIX_FMT_NV21", "YUV420/2P/LSB_CRCB", V4L2_PIX_FMT_NV21, 12, 2 }, { "V4L2_PIX_FMT_NV21X", "YUV420/2P/MSB_CBCR", V4L2_PIX_FMT_NV21X, 12, 2 }, { "V4L2_PIX_FMT_NV12X", "YUV420/2P/MSB_CRCB", V4L2_PIX_FMT_NV12X, 12, 2 }, { "V4L2_PIX_FMT_YUV420", "YUV420/3P", V4L2_PIX_FMT_YUV420, 12, 3 }, { "V4L2_PIX_FMT_YUYV", "YUV422/1P/YCBYCR", V4L2_PIX_FMT_YUYV, 16, 1 }, { "V4L2_PIX_FMT_YVYU", "YUV422/1P/YCRYCB", V4L2_PIX_FMT_YVYU, 16, 1 }, { "V4L2_PIX_FMT_UYVY", "YUV422/1P/CBYCRY", V4L2_PIX_FMT_UYVY, 16, 1 }, { "V4L2_PIX_FMT_VYUY", "YUV422/1P/CRYCBY", V4L2_PIX_FMT_VYUY, 16, 1 }, { "V4L2_PIX_FMT_UV12", "YUV422/2P/LSB_CBCR", V4L2_PIX_FMT_NV16, 16, 2 }, { "V4L2_PIX_FMT_UV21", "YUV422/2P/LSB_CRCB", V4L2_PIX_FMT_NV61, 16, 2 }, { "V4L2_PIX_FMT_UV12X", "YUV422/2P/MSB_CBCR", V4L2_PIX_FMT_NV16X, 16, 2 }, { "V4L2_PIX_FMT_UV21X", "YUV422/2P/MSB_CRCB", V4L2_PIX_FMT_NV61X, 16, 2 }, { "V4L2_PIX_FMT_YUV422P", "YUV422/3P", V4L2_PIX_FMT_YUV422P, 16, 3 }, }; int window_open(struct hwc_win_info_t *win, int id) { int fd = 0; char name[64]; int vsync = 1; int real_id = id; char const * const device_template = "/dev/graphics/fb%u"; // window & FB maping // fb0 -> win-id : 2 // fb1 -> win-id : 3 // fb2 -> win-id : 4 // fb3 -> win-id : 0 // fb4 -> win_id : 1 // it is pre assumed that ...win0 or win1 is used here.. switch (id) { case 0: real_id = 3; break; case 1: real_id = 4; break; case 2: real_id = 0; break; case 3: real_id = 1; break; case 4: real_id = 2; break; default: SEC_HWC_Log(HWC_LOG_ERROR, "%s::id(%d) is weird", __func__, id); goto error; } // 0/10 // snprintf(name, 64, device_template, id + 3); // 5/10 // snprintf(name, 64, device_template, id + 0); // 0/10 // snprintf(name, 64, device_template, id + 1); snprintf(name, 64, device_template, real_id); win->fd = open(name, O_RDWR); if (win->fd <= 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Failed to open window device (%s) : %s", __func__, strerror(errno), name); goto error; } #ifdef ENABLE_FIMD_VSYNC if (ioctl(win->fd, S3CFB_SET_VSYNC_INT, &vsync) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::S3CFB_SET_VSYNC_INT fail", __func__); goto error; } #endif return 0; error: if (0 < win->fd) close(win->fd); win->fd = 0; return -1; } int window_close(struct hwc_win_info_t *win) { int ret = 0; if (0 < win->fd) { #ifdef ENABLE_FIMD_VSYNC int vsync = 0; if (ioctl(win->fd, S3CFB_SET_VSYNC_INT, &vsync) < 0) SEC_HWC_Log(HWC_LOG_ERROR, "%s::S3CFB_SET_VSYNC_INT fail", __func__); #endif ret = close(win->fd); } win->fd = 0; return ret; } int window_set_pos(struct hwc_win_info_t *win) { struct s3cfb_user_window window; //before changing the screen configuration...powerdown the window if (window_hide(win) != 0) return -1; SEC_HWC_Log(HWC_LOG_DEBUG, "%s:: x(%d), y(%d)", __func__, win->rect_info.x, win->rect_info.y); win->var_info.xres_virtual = (win->lcd_info.xres + 15) & ~ 15; win->var_info.yres_virtual = win->lcd_info.yres * NUM_OF_WIN_BUF; win->var_info.xres = win->rect_info.w; win->var_info.yres = win->rect_info.h; win->var_info.activate &= ~FB_ACTIVATE_MASK; win->var_info.activate |= FB_ACTIVATE_FORCE; if (ioctl(win->fd, FBIOPUT_VSCREENINFO, &(win->var_info)) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::FBIOPUT_VSCREENINFO(%d, %d) fail", __func__, win->rect_info.w, win->rect_info.h); return -1; } window.x = win->rect_info.x; window.y = win->rect_info.y; if (ioctl(win->fd, S3CFB_WIN_POSITION, &window) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::S3CFB_WIN_POSITION(%d, %d) fail", __func__, window.x, window.y); return -1; } return 0; } int window_get_info(struct hwc_win_info_t *win, int win_num) { int temp_size = 0; if (ioctl(win->fd, FBIOGET_FSCREENINFO, &win->fix_info) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "FBIOGET_FSCREENINFO failed : %s", strerror(errno)); goto error; } win->size = win->fix_info.line_length * win->var_info.yres; for (int j = 0; j < NUM_OF_WIN_BUF; j++) { temp_size = win->size * j; win->addr[j] = win->fix_info.smem_start + temp_size; SEC_HWC_Log(HWC_LOG_DEBUG, "%s::win-%d add[%d] %x ", __func__, win_num, j, win->addr[j]); } return 0; error: win->fix_info.smem_start = 0; return -1; } int window_pan_display(struct hwc_win_info_t *win) { struct fb_var_screeninfo *lcd_info = &(win->lcd_info); #ifdef ENABLE_FIMD_VSYNC if (ioctl(win->fd, FBIO_WAITFORVSYNC, 0) < 0) SEC_HWC_Log(HWC_LOG_ERROR, "%s::FBIO_WAITFORVSYNC fail(%s)", __func__, strerror(errno)); #endif lcd_info->yoffset = lcd_info->yres * win->buf_index; if (ioctl(win->fd, FBIOPAN_DISPLAY, lcd_info) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::FBIOPAN_DISPLAY(%d / %d / %d) fail(%s)", __func__, lcd_info->yres, win->buf_index, lcd_info->yres_virtual, strerror(errno)); return -1; } return 0; } int window_show(struct hwc_win_info_t *win) { if (win->power_state == 0) { if (ioctl(win->fd, FBIOBLANK, FB_BLANK_UNBLANK) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::FBIOBLANK failed : (%d:%s)", __func__, win->fd, strerror(errno)); return -1; } win->power_state = 1; } return 0; } int window_hide(struct hwc_win_info_t *win) { if (win->power_state == 1) { if (ioctl(win->fd, FBIOBLANK, FB_BLANK_POWERDOWN) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::FBIOBLANK failed : (%d:%s)", __func__, win->fd, strerror(errno)); return -1; } win->power_state = 0; } return 0; } int window_get_global_lcd_info(struct hwc_context_t *ctx) { if (ioctl(ctx->global_lcd_win.fd, FBIOGET_VSCREENINFO, &ctx->lcd_info) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "FBIOGET_VSCREENINFO failed : %s", strerror(errno)); return -1; } if (ctx->lcd_info.xres == 0) { SEC_HWC_Log(HWC_LOG_ERROR, "ATTENTION: XRES IS 0"); } if (ctx->lcd_info.yres == 0) { SEC_HWC_Log(HWC_LOG_ERROR, "ATTENTION: YRES IS 0"); } if (ctx->lcd_info.bits_per_pixel == 0) { SEC_HWC_Log(HWC_LOG_ERROR, "ATTENTION: BPP IS 0"); } return 0; } int fimc_v4l2_set_src(int fd, unsigned int hw_ver, s5p_fimc_img_info *src) { struct v4l2_format fmt; struct v4l2_cropcap cropcap; struct v4l2_crop crop; struct v4l2_requestbuffers req; fmt.fmt.pix.width = src->full_width; fmt.fmt.pix.height = src->full_height; fmt.fmt.pix.pixelformat = src->color_space; fmt.fmt.pix.field = V4L2_FIELD_NONE; fmt.type = V4L2_BUF_TYPE_OUTPUT; if (ioctl(fd, VIDIOC_S_FMT, &fmt) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::VIDIOC_S_FMT failed : errno=%d (%s)" " : fd=%d\n", __func__, errno, strerror(errno), fd); return -1; } /* crop input size */ crop.type = V4L2_BUF_TYPE_OUTPUT; crop.c.width = src->width; crop.c.height = src->height; if (0x50 <= hw_ver) { crop.c.left = src->start_x; crop.c.top = src->start_y; } else { crop.c.left = 0; crop.c.top = 0; } if (ioctl(fd, VIDIOC_S_CROP, &crop) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_CROP :" "crop.c.left : (%d), crop.c.top : (%d), crop.c.width : (%d), crop.c.height : (%d)", __func__, crop.c.left, crop.c.top, crop.c.width, crop.c.height); return -1; } /* input buffer type */ req.count = 1; req.memory = V4L2_MEMORY_USERPTR; req.type = V4L2_BUF_TYPE_OUTPUT; if (ioctl(fd, VIDIOC_REQBUFS, &req) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in VIDIOC_REQBUFS", __func__); return -1; } return 0; } int fimc_v4l2_set_dst(int fd, s5p_fimc_img_info *dst, int rotation, int hflip, int vflip, unsigned int addr) { struct v4l2_format sFormat; struct v4l2_control vc; struct v4l2_framebuffer fbuf; int ret; /* set rotation configuration */ vc.id = V4L2_CID_ROTATION; vc.value = rotation; ret = ioctl(fd, VIDIOC_S_CTRL, &vc); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_CTRL - rotation (%d)" "vc.id : (%d), vc.value : (%d)", __func__, ret, vc.id, vc.value); return -1; } vc.id = V4L2_CID_HFLIP; vc.value = hflip; ret = ioctl(fd, VIDIOC_S_CTRL, &vc); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_CTRL - hflip (%d)" "vc.id : (%d), vc.value : (%d)", __func__, ret, vc.id, vc.value); return -1; } vc.id = V4L2_CID_VFLIP; vc.value = vflip; ret = ioctl(fd, VIDIOC_S_CTRL, &vc); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_CTRL - vflip (%d)" "vc.id : (%d), vc.value : (%d)", __func__, ret, vc.id, vc.value); return -1; } /* set size, format & address for destination image (DMA-OUTPUT) */ ret = ioctl(fd, VIDIOC_G_FBUF, &fbuf); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_G_FBUF (%d)", __func__, ret); return -1; } fbuf.base = (void *)addr; fbuf.fmt.width = dst->full_width; fbuf.fmt.height = dst->full_height; fbuf.fmt.pixelformat = dst->color_space; ret = ioctl(fd, VIDIOC_S_FBUF, &fbuf); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_FBUF (%d)", __func__, ret); return -1; } /* set destination window */ sFormat.type = V4L2_BUF_TYPE_VIDEO_OVERLAY; sFormat.fmt.win.w.left = dst->start_x; sFormat.fmt.win.w.top = dst->start_y; sFormat.fmt.win.w.width = dst->width; sFormat.fmt.win.w.height = dst->height; ret = ioctl(fd, VIDIOC_S_FMT, &sFormat); if (ret < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_S_FMT (%d)", __func__, ret); return -1; } return 0; } int fimc_v4l2_stream_on(int fd, enum v4l2_buf_type type) { if (-1 == ioctl(fd, VIDIOC_STREAMON, &type)) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_STREAMON\n"); return -1; } return 0; } int fimc_v4l2_queue(int fd, struct fimc_buf *fimc_buf, enum v4l2_buf_type type, int index) { struct v4l2_buffer buf; int ret; buf.length = 0; buf.m.userptr = (unsigned long)fimc_buf; buf.memory = V4L2_MEMORY_USERPTR; buf.index = index; buf.type = type; ret = ioctl(fd, VIDIOC_QBUF, &buf); if (0 > ret) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_QBUF : (%d)", ret); return -1; } return 0; } int fimc_v4l2_dequeue(int fd, struct fimc_buf *fimc_buf, enum v4l2_buf_type type) { struct v4l2_buffer buf; buf.memory = V4L2_MEMORY_USERPTR; buf.type = type; if (-1 == ioctl(fd, VIDIOC_DQBUF, &buf)) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_DQBUF\n"); return -1; } return buf.index; } int fimc_v4l2_stream_off(int fd, enum v4l2_buf_type type) { if (-1 == ioctl(fd, VIDIOC_STREAMOFF, &type)) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_STREAMOFF\n"); return -1; } return 0; } int fimc_v4l2_clr_buf(int fd, enum v4l2_buf_type type) { struct v4l2_requestbuffers req; req.count = 0; req.memory = V4L2_MEMORY_USERPTR; req.type = type; if (ioctl(fd, VIDIOC_REQBUFS, &req) == -1) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_REQBUFS"); } return 0; } int fimc_v4l2_S_ctrl(int fd) { struct v4l2_control vc; vc.id = V4L2_CID_CACHEABLE; vc.value = 1; if (ioctl(fd, VIDIOC_S_CTRL, &vc) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Error in VIDIOC_S_CTRL"); return -1; } return 0; } int fimc_handle_oneshot(int fd, struct fimc_buf *fimc_src_buf, struct fimc_buf *fimc_dst_buf) { #ifdef CHECK_FPS check_fps(); #endif if (fimc_v4l2_stream_on(fd, V4L2_BUF_TYPE_OUTPUT) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Fail : SRC v4l2_stream_on()"); return -5; } if (fimc_v4l2_queue(fd, fimc_src_buf, V4L2_BUF_TYPE_OUTPUT, 0) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Fail : SRC v4l2_queue()"); goto STREAM_OFF; } if (fimc_v4l2_dequeue(fd, fimc_src_buf, V4L2_BUF_TYPE_OUTPUT) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Fail : SRC v4l2_dequeue()"); return -6; } STREAM_OFF: if (fimc_v4l2_stream_off(fd, V4L2_BUF_TYPE_OUTPUT) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Fail : SRC v4l2_stream_off()"); return -8; } if (fimc_v4l2_clr_buf(fd, V4L2_BUF_TYPE_OUTPUT) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "Fail : SRC v4l2_clr_buf()"); return -10; } return 0; } static int memcpy_rect(void *dst, void *src, int fullW, int fullH, int realW, int realH, int format) { unsigned char *srcCb, *srcCr; unsigned char *dstCb, *dstCr; unsigned char *srcY, *dstY; int srcCbOffset, srcCrOffset; int dstCbOffset, dstFrameOffset, dstCrOffset; int cbFullW, cbRealW, cbFullH, cbRealH; int ySrcFW, ySrcFH, ySrcRW, ySrcRH; int planes; int i; SEC_HWC_Log(HWC_LOG_DEBUG, "++memcpy_rect()::" "dst(0x%x),src(0x%x),f.w(%d),f.h(%d),r.w(%d),r.h(%d),format(0x%x)", (unsigned int)dst, (unsigned int)src, fullW, fullH, realW, realH, format); // Set dst Y, Cb, Cr address for FIMC { cbFullW = fullW >> 1; cbRealW = realW >> 1; cbFullH = fullH >> 1; cbRealH = realH >> 1; dstFrameOffset = fullW * fullH; dstCrOffset = cbFullW * cbFullH; dstY = (unsigned char *)dst; dstCb = (unsigned char *)dst + dstFrameOffset; dstCr = (unsigned char *)dstCb + dstCrOffset; } // Get src Y, Cb, Cr address for source buffer. // Each address is aligned by 16's multiple for GPU both width and height. { ySrcFW = fullW; ySrcFH = fullH; ySrcRW = realW; ySrcRH = realH; srcCbOffset = EXYNOS4_ALIGN(ySrcRW,16)* EXYNOS4_ALIGN(ySrcRH,16); srcCrOffset = EXYNOS4_ALIGN(cbRealW,16)* EXYNOS4_ALIGN(cbRealH,16); srcY = (unsigned char *)src; srcCb = (unsigned char *)src + srcCbOffset; srcCr = (unsigned char *)srcCb + srcCrOffset; } SEC_HWC_Log(HWC_LOG_DEBUG, "--memcpy_rect()::\n" "dstY(0x%x),dstCb(0x%x),dstCr(0x%x) \n" "srcY(0x%x),srcCb(0x%x),srcCr(0x%x) \n" "cbRealW(%d),cbRealH(%d)", (unsigned int)dstY,(unsigned int)dstCb,(unsigned int)dstCr, (unsigned int)srcY,(unsigned int)srcCb,(unsigned int)srcCr, cbRealW, cbRealH); if (format == HAL_PIXEL_FORMAT_YV12) { //YV12(Y,Cr,Cv) planes = 3; //This is code for VE, deleted temporory by SSONG 2011.09.22 // This will be enabled later. /* //as defined in hardware.h, cb & cr full_width should be aligned to 16. ALIGN(y_stride/2, 16). ////Alignment is hard coded to 16. ////for example...check frameworks/media/libvideoeditor/lvpp/VideoEditorTools.cpp file for UV stride cal cbSrcFW = (cbSrcFW + 15) & (~15); srcCbOffset = ySrcFW * fullH; srcCrOffset = srcCbOffset + ((cbSrcFW * fullH) >> 1); srcY = (unsigned char *)src; srcCb = (unsigned char *)src + srcCbOffset; srcCr = (unsigned char *)src + srcCrOffset; */ } else if ((format == HAL_PIXEL_FORMAT_YCbCr_420_P)) { planes = 3; } else if (format == HAL_PIXEL_FORMAT_YCbCr_420_SP || format == HAL_PIXEL_FORMAT_YCrCb_420_SP) { planes = 2; } else { SEC_HWC_Log(HWC_LOG_ERROR, "use default memcpy instead of memcpy_rect"); return -1; } //#define CHECK_PERF #ifdef CHECK_PERF struct timeval start, end; gettimeofday(&start, NULL); #endif for (i = 0; i < realH; i++) memcpy(dstY + fullW * i, srcY + ySrcFW * i, ySrcRW); if (planes == 2) { for (i = 0; i < cbRealH; i++) memcpy(dstCb + ySrcFW * i, srcCb + ySrcFW * i, ySrcRW); } else if (planes == 3) { for (i = 0; i < cbRealH; i++) memcpy(dstCb + cbFullW * i, srcCb + cbFullW * i, cbRealW); for (i = 0; i < cbRealH; i++) memcpy(dstCr + cbFullW * i, srcCr + cbFullW * i, cbRealW); } #ifdef CHECK_PERF gettimeofday(&end, NULL); SEC_HWC_Log(HWC_LOG_ERROR, "[COPY]=%d,",(end.tv_sec - start.tv_sec)*1000+(end.tv_usec - start.tv_usec)/1000); #endif return 0; } /*****************************************************************************/ static int get_src_phys_addr(struct hwc_context_t *ctx, sec_img *src_img, sec_rect *src_rect) { s5p_fimc_t *fimc = &ctx->fimc; unsigned int src_virt_addr = 0; unsigned int src_phys_addr = 0; unsigned int src_frame_size = 0; ADDRS * addr; // error check routine if (0 == src_img->base && !(src_img->usage & GRALLOC_USAGE_HW_FIMC1)) { SEC_HWC_Log(HWC_LOG_ERROR, "%s invalid src image base\n", __func__); return 0; } switch (src_img->mem_type) { case HWC_PHYS_MEM_TYPE: src_phys_addr = src_img->base + src_img->offset; break; case HWC_VIRT_MEM_TYPE: case HWC_UNKNOWN_MEM_TYPE: switch (src_img->format) { case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP_TILED: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_SP: addr = (ADDRS *)(src_img->base); fimc->params.src.buf_addr_phy_rgb_y = addr->addr_y; fimc->params.src.buf_addr_phy_cb = addr->addr_cbcr; src_phys_addr = fimc->params.src.buf_addr_phy_rgb_y; if (0 == src_phys_addr) { SEC_HWC_Log(HWC_LOG_ERROR, "%s address error " "(format=CUSTOM_YCbCr/YCrCb_420_SP Y-addr=0x%x " "CbCr-Addr=0x%x)", __func__, fimc->params.src.buf_addr_phy_rgb_y, fimc->params.src.buf_addr_phy_cb); return 0; } break; case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_I: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CbYCrY_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CrYCbY_422_I: addr = (ADDRS *)(src_img->base + src_img->offset); fimc->params.src.buf_addr_phy_rgb_y = addr->addr_y; src_phys_addr = fimc->params.src.buf_addr_phy_rgb_y; if (0 == src_phys_addr) { SEC_HWC_Log(HWC_LOG_ERROR, "%s address error " "(format=CUSTOM_YCbCr/CbYCrY_422_I Y-addr=0x%x)", __func__, fimc->params.src.buf_addr_phy_rgb_y); return 0; } break; default: if (src_img->usage & GRALLOC_USAGE_HW_FIMC1) { fimc->params.src.buf_addr_phy_rgb_y = src_img->paddr; fimc->params.src.buf_addr_phy_cb = src_img->paddr + src_img->uoffset; fimc->params.src.buf_addr_phy_cr = src_img->paddr + src_img->uoffset + src_img->voffset; src_phys_addr = fimc->params.src.buf_addr_phy_rgb_y; } else { SEC_HWC_Log(HWC_LOG_ERROR, "%s::\nformat = 0x%x : Not " "GRALLOC_USAGE_HW_FIMC1 can not supported\n", __func__, src_img->format); } break; } } return src_phys_addr; } static inline int rotateValueHAL2PP(unsigned char transform) { int rotate_flag = transform & 0x7; switch (rotate_flag) { case HAL_TRANSFORM_ROT_90: return 90; case HAL_TRANSFORM_ROT_180: return 180; case HAL_TRANSFORM_ROT_270: return 270; case HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90: return 90; case HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90: return 90; case HAL_TRANSFORM_FLIP_H: return 0; case HAL_TRANSFORM_FLIP_V: return 0; } return 0; } static inline int hflipValueHAL2PP(unsigned char transform) { int flip_flag = transform & 0x7; switch (flip_flag) { case HAL_TRANSFORM_FLIP_H: case HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90: return 1; case HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90: case HAL_TRANSFORM_ROT_90: case HAL_TRANSFORM_ROT_180: case HAL_TRANSFORM_ROT_270: case HAL_TRANSFORM_FLIP_V: break; } return 0; } static inline int vflipValueHAL2PP(unsigned char transform) { int flip_flag = transform & 0x7; switch (flip_flag) { case HAL_TRANSFORM_FLIP_V: case HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90: return 1; case HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90: case HAL_TRANSFORM_ROT_90: case HAL_TRANSFORM_ROT_180: case HAL_TRANSFORM_ROT_270: case HAL_TRANSFORM_FLIP_H: break; } return 0; } static inline int multipleOf2(int number) { if (number % 2 == 1) return (number - 1); else return number; } static inline int multipleOf4(int number) { int remain_number = number % 4; if (remain_number != 0) return (number - remain_number); else return number; } static inline int multipleOf8(int number) { int remain_number = number % 8; if (remain_number != 0) return (number - remain_number); else return number; } static inline int multipleOf16(int number) { int remain_number = number % 16; if (remain_number != 0) return (number - remain_number); else return number; } static inline int widthOfPP(unsigned int ver, int pp_color_format, int number) { if (0x50 <= ver) { switch (pp_color_format) { /* 422 1/2/3 plane */ case V4L2_PIX_FMT_YUYV: case V4L2_PIX_FMT_UYVY: case V4L2_PIX_FMT_NV61: case V4L2_PIX_FMT_NV16: case V4L2_PIX_FMT_YUV422P: /* 420 2/3 plane */ case V4L2_PIX_FMT_NV21: case V4L2_PIX_FMT_NV12: case V4L2_PIX_FMT_NV12T: case V4L2_PIX_FMT_YUV420: return multipleOf2(number); default : return number; } } else { switch (pp_color_format) { case V4L2_PIX_FMT_RGB565: return multipleOf8(number); case V4L2_PIX_FMT_RGB32: return multipleOf4(number); case V4L2_PIX_FMT_YUYV: case V4L2_PIX_FMT_UYVY: return multipleOf4(number); case V4L2_PIX_FMT_NV61: case V4L2_PIX_FMT_NV16: return multipleOf8(number); case V4L2_PIX_FMT_YUV422P: return multipleOf16(number); case V4L2_PIX_FMT_NV21: case V4L2_PIX_FMT_NV12: case V4L2_PIX_FMT_NV12T: return multipleOf8(number); case V4L2_PIX_FMT_YUV420: return multipleOf16(number); default : return number; } } return number; } static inline int heightOfPP(int pp_color_format, int number) { switch (pp_color_format) { case V4L2_PIX_FMT_NV21: case V4L2_PIX_FMT_NV12: case V4L2_PIX_FMT_NV12T: case V4L2_PIX_FMT_YUV420: return multipleOf2(number); default : return number; break; } return number; } static unsigned int get_yuv_bpp(unsigned int fmt) { int i, sel = -1; for (i = 0; i < (int)(sizeof(yuv_list) / sizeof(struct yuv_fmt_list)); i++) { if (yuv_list[i].fmt == fmt) { sel = i; break; } } if (sel == -1) return sel; else return yuv_list[sel].bpp; } static unsigned int get_yuv_planes(unsigned int fmt) { int i, sel = -1; for (i = 0; i < (int)(sizeof(yuv_list) / sizeof(struct yuv_fmt_list)); i++) { if (yuv_list[i].fmt == fmt) { sel = i; break; } } if (sel == -1) return sel; else return yuv_list[sel].planes; } static int runFimcCore(struct hwc_context_t *ctx, unsigned int src_phys_addr, sec_img *src_img, sec_rect *src_rect, uint32_t src_color_space, unsigned int dst_phys_addr, sec_img *dst_img, sec_rect *dst_rect, uint32_t dst_color_space, int transform) { s5p_fimc_t * fimc = &ctx->fimc; s5p_fimc_params_t * params = &(fimc->params); struct fimc_buf fimc_src_buf; int src_bpp, src_planes; unsigned int frame_size = 0; bool src_cbcr_order = true; int rotate_value = rotateValueHAL2PP(transform); int hflip = 0; int vflip = 0; /* 1. param(fimc config)->src information * - src_img,src_rect => s_fw,s_fh,s_w,s_h,s_x,s_y */ params->src.full_width = src_img->f_w; params->src.full_height = src_img->f_h; params->src.width = src_rect->w; params->src.height = src_rect->h; params->src.start_x = src_rect->x; params->src.start_y = src_rect->y; params->src.color_space = src_color_space; params->src.buf_addr_phy_rgb_y = src_phys_addr; /* check src minimum */ if (src_rect->w < 16 || src_rect->h < 8) { SEC_HWC_Log(HWC_LOG_ERROR, "%s src size is not supported by fimc : f_w=%d f_h=%d " "x=%d y=%d w=%d h=%d (ow=%d oh=%d) format=0x%x", __func__, params->src.full_width, params->src.full_height, params->src.start_x, params->src.start_y, params->src.width, params->src.height, src_rect->w, src_rect->h, params->src.color_space); return -1; } /* 2. param(fimc config)->dst information * - dst_img,dst_rect,rot => d_fw,d_fh,d_w,d_h,d_x,d_y */ switch (rotate_value) { case 0: hflip = hflipValueHAL2PP(transform); vflip = vflipValueHAL2PP(transform); params->dst.full_width = dst_img->f_w; params->dst.full_height = dst_img->f_h; params->dst.start_x = dst_rect->x; params->dst.start_y = dst_rect->y; params->dst.width = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->w); params->dst.height = heightOfPP(dst_color_space, dst_rect->h); break; case 90: hflip = vflipValueHAL2PP(transform); vflip = hflipValueHAL2PP(transform); params->dst.full_width = dst_img->f_h; params->dst.full_height = dst_img->f_w; params->dst.start_x = dst_rect->y; params->dst.start_y = dst_img->f_w - (dst_rect->x + dst_rect->w); params->dst.width = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->h); params->dst.height = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->w); if (0x50 > fimc->hw_ver) params->dst.start_y += (dst_rect->w - params->dst.height); break; case 180: params->dst.full_width = dst_img->f_w; params->dst.full_height = dst_img->f_h; params->dst.start_x = dst_img->f_w - (dst_rect->x + dst_rect->w); params->dst.start_y = dst_img->f_h - (dst_rect->y + dst_rect->h); params->dst.width = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->w); params->dst.height = heightOfPP(dst_color_space, dst_rect->h); break; case 270: params->dst.full_width = dst_img->f_h; params->dst.full_height = dst_img->f_w; params->dst.start_x = dst_img->f_h - (dst_rect->y + dst_rect->h); params->dst.start_y = dst_rect->x; params->dst.width = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->h); params->dst.height = widthOfPP(fimc->hw_ver, dst_color_space, dst_rect->w); if (0x50 > fimc->hw_ver) params->dst.start_y += (dst_rect->w - params->dst.height); break; } params->dst.color_space = dst_color_space; SEC_HWC_Log(HWC_LOG_DEBUG, "runFimcCore()::" "SRC f.w(%d),f.h(%d),x(%d),y(%d),w(%d),h(%d)=>" "DST f.w(%d),f.h(%d),x(%d),y(%d),w(%d),h(%d)", params->src.full_width, params->src.full_height, params->src.start_x, params->src.start_y, params->src.width, params->src.height, params->dst.full_width, params->dst.full_height, params->dst.start_x, params->dst.start_y, params->dst.width, params->dst.height); /* check dst minimum */ if (dst_rect->w < 8 || dst_rect->h < 4) { SEC_HWC_Log(HWC_LOG_ERROR, "%s dst size is not supported by fimc : f_w=%d f_h=%d " "x=%d y=%d w=%d h=%d (ow=%d oh=%d) format=0x%x", __func__, params->dst.full_width, params->dst.full_height, params->dst.start_x, params->dst.start_y, params->dst.width, params->dst.height, dst_rect->w, dst_rect->h, params->dst.color_space); return -1; } /* check scaling limit * the scaling limie must not be more than MAX_RESIZING_RATIO_LIMIT */ if (((src_rect->w > dst_rect->w) && ((src_rect->w / dst_rect->w) > MAX_RESIZING_RATIO_LIMIT)) || ((dst_rect->w > src_rect->w) && ((dst_rect->w / src_rect->w) > MAX_RESIZING_RATIO_LIMIT))) { SEC_HWC_Log(HWC_LOG_ERROR, "%s over scaling limit : src.w=%d dst.w=%d (limit=%d)", __func__, src_rect->w, dst_rect->w, MAX_RESIZING_RATIO_LIMIT); return -1; } /* 3. Set configuration related to destination (DMA-OUT) * - set input format & size * - crop input size * - set input buffer * - set buffer type (V4L2_MEMORY_USERPTR) */ if (fimc_v4l2_set_dst(fimc->dev_fd, &params->dst, rotate_value, hflip, vflip, dst_phys_addr) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "fimc_v4l2_set_dst is failed\n"); return -1; } /* 4. Set configuration related to source (DMA-INPUT) * - set input format & size * - crop input size * - set input buffer * - set buffer type (V4L2_MEMORY_USERPTR) */ if (fimc_v4l2_set_src(fimc->dev_fd, fimc->hw_ver, &params->src) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "fimc_v4l2_set_src is failed\n"); return -1; } /* 5. Set input dma address (Y/RGB, Cb, Cr) * - zero copy : mfc, camera */ switch (src_img->format) { case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP_TILED: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_SP: /* for video contents zero copy case */ fimc_src_buf.base[0] = params->src.buf_addr_phy_rgb_y; fimc_src_buf.base[1] = params->src.buf_addr_phy_cb; break; case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_I: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CbYCrY_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CrYCbY_422_I: case HAL_PIXEL_FORMAT_RGB_565: case HAL_PIXEL_FORMAT_YV12: default: if (src_img->format == HAL_PIXEL_FORMAT_YV12){ src_cbcr_order = false; } if (src_img->usage & GRALLOC_USAGE_HW_FIMC1) { fimc_src_buf.base[0] = params->src.buf_addr_phy_rgb_y; if (src_cbcr_order == true) { fimc_src_buf.base[1] = params->src.buf_addr_phy_cb; fimc_src_buf.base[2] = params->src.buf_addr_phy_cr; } else { fimc_src_buf.base[2] = params->src.buf_addr_phy_cb; fimc_src_buf.base[1] = params->src.buf_addr_phy_cr; } SEC_HWC_Log(HWC_LOG_DEBUG, "runFimcCore - Y=0x%X, U=0x%X, V=0x%X\n", fimc_src_buf.base[0], fimc_src_buf.base[1],fimc_src_buf.base[2]); break; } } /* 6. Run FIMC * - stream on => queue => dequeue => stream off => clear buf */ if (fimc_handle_oneshot(fimc->dev_fd, &fimc_src_buf, NULL) < 0) { ALOGE("fimcrun fail"); fimc_v4l2_clr_buf(fimc->dev_fd, V4L2_BUF_TYPE_OUTPUT); return -1; } return 0; } int createFimc(s5p_fimc_t *fimc) { struct v4l2_capability cap; struct v4l2_format fmt; struct v4l2_control vc; // open device file if (fimc->dev_fd <= 0) fimc->dev_fd = open(PP_DEVICE_DEV_NAME, O_RDWR); if (fimc->dev_fd <= 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Post processor open error (%d)", __func__, errno); goto err; } // check capability if (ioctl(fimc->dev_fd, VIDIOC_QUERYCAP, &cap) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "VIDIOC_QUERYCAP failed"); goto err; } if (!(cap.capabilities & V4L2_CAP_STREAMING)) { SEC_HWC_Log(HWC_LOG_ERROR, "%d has no streaming support", fimc->dev_fd); goto err; } if (!(cap.capabilities & V4L2_CAP_VIDEO_OUTPUT)) { SEC_HWC_Log(HWC_LOG_ERROR, "%d is no video output", fimc->dev_fd); goto err; } /* * malloc fimc_outinfo structure */ fmt.type = V4L2_BUF_TYPE_OUTPUT; if (ioctl(fimc->dev_fd, VIDIOC_G_FMT, &fmt) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_G_FMT", __func__); goto err; } vc.id = V4L2_CID_FIMC_VERSION; vc.value = 0; if (ioctl(fimc->dev_fd, VIDIOC_G_CTRL, &vc) < 0) { SEC_HWC_Log(HWC_LOG_ERROR, "%s::Error in video VIDIOC_G_CTRL", __func__); goto err; } fimc->hw_ver = vc.value; return 0; err: if (0 < fimc->dev_fd) close(fimc->dev_fd); fimc->dev_fd =0; return -1; } int destroyFimc(s5p_fimc_t *fimc) { if (fimc->out_buf.virt_addr != NULL) { fimc->out_buf.virt_addr = NULL; fimc->out_buf.length = 0; } // close if (0 < fimc->dev_fd) close(fimc->dev_fd); fimc->dev_fd = 0; return 0; } int runFimc(struct hwc_context_t *ctx, struct sec_img *src_img, struct sec_rect *src_rect, struct sec_img *dst_img, struct sec_rect *dst_rect, uint32_t transform) { s5p_fimc_t * fimc = &ctx->fimc; unsigned int src_phys_addr = 0; unsigned int dst_phys_addr = 0; int rotate_value = 0; int32_t src_color_space; int32_t dst_color_space; /* 1. source address and size */ src_phys_addr = get_src_phys_addr(ctx, src_img, src_rect); if (0 == src_phys_addr) return -1; /* 2. destination address and size */ dst_phys_addr = dst_img->base; if (0 == dst_phys_addr) return -2; /* 3. check whether fimc supports the src format */ src_color_space = HAL_PIXEL_FORMAT_2_V4L2_PIX(src_img->format); if (0 > src_color_space) return -3; dst_color_space = HAL_PIXEL_FORMAT_2_V4L2_PIX(dst_img->format); if (0 > dst_color_space) return -4; /* 4. FIMC: src_rect of src_img => dst_rect of dst_img */ if (runFimcCore(ctx, src_phys_addr, src_img, src_rect, (uint32_t)src_color_space, dst_phys_addr, dst_img, dst_rect, (uint32_t)dst_color_space, transform) < 0) return -5; return 0; } int check_yuv_format(unsigned int color_format) { switch (color_format) { case HAL_PIXEL_FORMAT_YV12: case HAL_PIXEL_FORMAT_YCbCr_422_SP: case HAL_PIXEL_FORMAT_YCrCb_420_SP: case HAL_PIXEL_FORMAT_YCbCr_422_I: case HAL_PIXEL_FORMAT_YCbCr_422_P: case HAL_PIXEL_FORMAT_YCbCr_420_P: case HAL_PIXEL_FORMAT_YCbCr_420_I: case HAL_PIXEL_FORMAT_CbYCrY_422_I: case HAL_PIXEL_FORMAT_CbYCrY_420_I: case HAL_PIXEL_FORMAT_YCbCr_420_SP: case HAL_PIXEL_FORMAT_YCrCb_422_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_420_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP_TILED: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_SP: case HAL_PIXEL_FORMAT_CUSTOM_YCbCr_422_I: case HAL_PIXEL_FORMAT_CUSTOM_YCrCb_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CbYCrY_422_I: case HAL_PIXEL_FORMAT_CUSTOM_CrYCbY_422_I: return 1; default: return 0; } }
30.702344
113
0.600906
DrDoubt
d21f36e288f9158449eec0a8719f3bb6bfe590ec
337
cpp
C++
Core/radio/RadioHardware.cpp
ji3gab/ExtIO_sddc
ff82dddc75ee9a1af3d5ca0d882a81b5ee78410d
[ "MIT" ]
24
2018-01-24T22:05:14.000Z
2022-03-28T00:46:09.000Z
Core/radio/RadioHardware.cpp
ji3gab/ExtIO_sddc
ff82dddc75ee9a1af3d5ca0d882a81b5ee78410d
[ "MIT" ]
106
2020-11-09T01:25:33.000Z
2022-03-15T08:32:26.000Z
Core/radio/RadioHardware.cpp
ji3gab/ExtIO_sddc
ff82dddc75ee9a1af3d5ca0d882a81b5ee78410d
[ "MIT" ]
18
2020-10-09T20:15:53.000Z
2022-03-27T07:29:20.000Z
#include "RadioHandler.h" bool RadioHardware::FX3SetGPIO(uint32_t mask) { gpios |= mask; return Fx3->Control(GPIOFX3, gpios); } bool RadioHardware::FX3UnsetGPIO(uint32_t mask) { gpios &= ~mask; return Fx3->Control(GPIOFX3, gpios); } RadioHardware::~RadioHardware() { if (Fx3) { FX3SetGPIO(SHDWN); } }
15.318182
47
0.652819
ji3gab
d22068426ebeea0934b49c935dde4027ca611721
1,144
cpp
C++
Emissions/Set_Link_List.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
Emissions/Set_Link_List.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
Emissions/Set_Link_List.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Set_Link_List.cpp - process the link equivalence data //********************************************************* #include "Emissions.hpp" //--------------------------------------------------------- // Set_Link_List //--------------------------------------------------------- void Emissions::Set_Link_List (void) { int i, num, link, lnk, dir; Link_Data *link_ptr; Integer_List *group; num = link_equiv.Max_Group (); for (i=1; i <= num; i++) { group = link_equiv.Group_List (i); if (group == NULL) continue; //---- process each link in the link group ---- for (link = group->First (); link != 0; link = group->Next ()) { if (vol_spd_flag) { dir = abs (link); } else { lnk = abs (link); link_ptr = link_data.Get (lnk); if (link_ptr == NULL) continue; if (link < 0) { dir = link_ptr->BA_Dir (); } else { dir = link_ptr->AB_Dir (); } } //---- add to the link list ---- if (link_list.Get_Index (dir) == 0) { if (!link_list.Add (dir)) { Error ("Adding Link to the Link List"); } } } } }
20.8
66
0.447552
kravitz
d221f39e2027e747d0dd2236eeee8d3c71a3e497
483
hpp
C++
src/crypto/Bip32.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/crypto/Bip32.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/crypto/Bip32.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
// Copyright (c) 2018 The Open-Transactions developers // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once #include "Internal.hpp" #include "opentxs/crypto/Bip32.hpp" namespace opentxs::crypto::implementation { class Bip32 : virtual public opentxs::crypto::Bip32 { }; } // namespace opentxs::crypto::implementation
26.833333
70
0.73913
nopdotcom
d2267f043aec24676ea34be8e9b74b96faefc809
1,849
cc
C++
SampleMgr/test/samplegrp_test.cc
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
SampleMgr/test/samplegrp_test.cc
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
SampleMgr/test/samplegrp_test.cc
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
/******************************************************************************* * * Filename : samplegrp_test.cc * Description : Unit testing for Sample group class * Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ] * *******************************************************************************/ #include "ManagerUtils/Common/interface/ConfigReader.hpp" #include "ManagerUtils/SampleMgr/interface/SampleGroup.hpp" #include <iostream> using namespace std; using namespace mgr; void DumpInfo( const SampleGroup& ); int main(int argc, char* argv[]) { cout << "=====[UNIT TESTING FOR SAMPLEGROUP CLASS]=====" << endl; ConfigReader cfg( "./group.json" ); cout << "=====[SUBSET GROUP TESTING]=====" << endl; SampleMgr::InitStaticFromFile("./sample_static.json"); SampleMgr::SetFilePrefix("./"); SampleGroup subset( "SubSetInFile" ); subset.InitFromReader( cfg ); DumpInfo( subset ); SampleGroup subset_default( "SubSetInFile_WithDefault" ); subset_default.InitFromReader( cfg ); DumpInfo( subset_default ); cout << "=====[FILE BASED GROUP TESTING]=====" << endl; SampleGroup whole_file( "AllGroupsInFiles", cfg ); DumpInfo( whole_file ); cout << "=====[SINGLE SAMPLE TESTING]=====" << endl; SampleGroup single_in_file( "TTJets2" ); single_in_file.InitFromReader( cfg ); DumpInfo( single_in_file ); cout << "=====[SINGLE SAMPLE TESTING]=====" << endl; SampleGroup single_default( "TTJets" ); single_default.InitFromReader( cfg ); DumpInfo( single_default ); return 0; } void DumpInfo( const SampleGroup& x ) { cout << x.Name() << " " << x.LatexName() << endl; for( const auto& sample : x.SampleList() ){ cout << " > " << sample.Name() << " " << sample.LatexName() << sample.ExpectedYield() << endl; } }
29.349206
80
0.581395
NTUHEP-Tstar
d22896ef2b14f1c790d7a201fd476e336b53d5a5
14,888
cpp
C++
src/Source.cpp
fencl/Crs
902f6f293bcf33ff71ca6cfc306d8b833d1e0e63
[ "MIT" ]
null
null
null
src/Source.cpp
fencl/Crs
902f6f293bcf33ff71ca6cfc306d8b833d1e0e63
[ "MIT" ]
null
null
null
src/Source.cpp
fencl/Crs
902f6f293bcf33ff71ca6cfc306d8b833d1e0e63
[ "MIT" ]
null
null
null
#include "Source.hpp" #include <iostream> #include <fstream> #include <ctype.h> #include <algorithm> #include <string> #include <string_view> #include "CompileContext.hpp" #include "Error.hpp" #include "ConstantManager.hpp" #include "Compiler.hpp" #include "Ast.hpp" #include "Statement.hpp" #ifdef WINDOWS #include <windows.h> #endif #ifdef LINUX #include <cstdlib> #include <cstdio> #include <cstring> #endif namespace Crs { bool operator < (const SourceRange& l, const SourceRange& r) { return l.offset+l.length <= r.offset; } bool operator == (const SourceRange& l, const SourceRange& r) { return l.offset <= r.offset + r.length && r.offset <= l.offset+l.length; } std::size_t Cursor::line() const { if (src == nullptr) return 0; return src->get_line(*this); } std::size_t Source::get_line(Cursor c) const { if (c.src != this) { return 0; } SourceRange range; range.length = c.length; range.offset = c.offset; return lines.at(range); } void Source::register_debug() { if (debug_id == UINT16_MAX) { debug_id = Compiler::current()->global_module()->register_debug_source(name); } std::size_t l = 0; std::size_t off = 0; std::string_view src = data(); bool next = true; while (next) { std::size_t pos = src.find("\n", off); if (pos == src.npos) { pos = src.length()-1; next = false; } else { ++pos; } SourceRange range; range.length = pos - off; range.offset = off; if (range.length > 0) { lines[range] = l; } ++l; off = pos; } } const std::string_view Source::data() const { return std::string_view(buffer); } void Source::load(const char* file) { std::ifstream in(file, std::ios::in | std::ios::binary); if (in) { in.seekg(0, std::ios::end); const unsigned int buf_size = (const unsigned int)in.tellg(); buffer.resize(buf_size); in.seekg(0, std::ios::beg); in.read(&buffer[0], buffer.size()); in.close(); } else { throw string_exception("File not found"); } name = file; const std::size_t last_slash_idx = name.find_last_of("\\/"); if (std::string::npos != last_slash_idx) { name.erase(0, last_slash_idx + 1); } } void Source::load_data(const char* new_data, const char* nm) { buffer = new_data; name = nm; } void Source::read_after(Cursor& out, const Cursor& c) const { read(out, c.offset + c.length,c.x,c.y); } Cursor Source::read_first() { Cursor c; read(c, 0, 0, 0); return c; } bool operator < (const Cursor& c1, const Cursor& c2) { if (c1.src < c2.src) return true; if (c1.src > c2.src) return false; if (c1.offset < c2.offset) return true; return false; } std::string_view Cursor::buffer() const { return src->data().substr(offset, length); } Cursor Cursor::next() const { Cursor c; ((Crs::Source*)src)->read_after(c, *this); return c; } void Cursor::move() { ((Crs::Source*)src)->read_after(*this, *this); } void Source::read(Cursor& out, std::size_t offset, std::size_t x, std::size_t y) const { while (true) { while (offset < buffer.size() && isspace(buffer[offset])) { if (buffer[offset] == '\n') { x = 0; y++; } offset++; } if (offset < buffer.size() - 1 && buffer[offset] == '/' && buffer[offset + 1] == '*') { offset += 3; while (offset < buffer.size() && (buffer[offset] != '/' || buffer[offset - 1] != '*')) { if (buffer[offset] == '\n') { x = 0; y++; } offset++; } offset++; } else if (offset < buffer.size() - 1 && buffer[offset] == '/' && buffer[offset + 1] == '/') { offset += 2; while (offset < buffer.size()) { if (buffer[offset] == '\n') { x = 0; y++; break; } offset++; } offset++; } else break; } if (offset < buffer.size()) { if (isalpha(buffer[offset]) || buffer[offset] == '_') { std::size_t start = offset; std::size_t start_x = x; while (isalnum(buffer[offset]) || buffer[offset] == '_') { offset++; x++; } out.x = start_x; out.y = y; out.src = this; out.offset = start; out.length = offset - start; out.tok = RecognizedToken::Symbol; return; } else if (isdigit(buffer[offset])) { bool floatt = false; bool doublet = false; bool islong = false; bool isusg = false; std::size_t start = offset; std::size_t start_x = x; while (isdigit(buffer[offset]) || buffer[offset] == '.') { if (buffer[offset] == '.') floatt = true; offset++; x++; } if (buffer[offset] == 'd' && floatt) { doublet = true; offset++; x++; } if (buffer[offset] == 'u' && !floatt) { isusg = true; offset++; x++; } if (buffer[offset] == 'l' && !floatt) { islong = true; offset++; x++; } out.src = this; out.offset = start; out.length = offset - start; out.y = y; out.x = start_x; if (floatt) { if (doublet) out.tok = (RecognizedToken::DoubleNumber); else out.tok = (RecognizedToken::FloatNumber); } else if (islong) { if (isusg) out.tok = (RecognizedToken::UnsignedLongNumber); else out.tok = (RecognizedToken::LongNumber); } else { if (isusg) out.tok = (RecognizedToken::UnsignedNumber); else out.tok = (RecognizedToken::Number); } return; } else if (buffer[offset] == '"') { std::size_t start = offset; std::size_t start_x = x; bool escaped = false; while (true) { offset++; char boff = buffer[offset]; if (offset >= buffer.size() || boff == '\n') { out.src = this; out.offset = start; out.length = offset - start; out.x = start_x; out.y = y; throw_specific_error(out, "String literal not closed"); } else if (boff == '"' && !escaped) { break; } if (boff == '\\' && !escaped) { escaped = true; } else { escaped = false; } } offset++; x += offset-start; out.tok = RecognizedToken::String; out.src = this; out.offset = start; out.length = offset - start; out.x = start_x; out.y = y; } else { std::size_t start = offset; std::size_t start_x = x; char c = buffer[offset++]; char nc = '\0'; if (offset < buffer.size()) { nc = buffer[offset]; } switch (c) { case '@': out.tok = (RecognizedToken::At); break; case '[': out.tok = (RecognizedToken::OpenBracket); break; case ']': out.tok = (RecognizedToken::CloseBracket); break; case '{': out.tok = (RecognizedToken::OpenBrace); break; case '}': out.tok = (RecognizedToken::CloseBrace); break; case '(': out.tok = (RecognizedToken::OpenParenthesis); break; case ')': out.tok = (RecognizedToken::CloseParenthesis); break; case '+': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::PlusEquals); break; default: out.tok = (RecognizedToken::Plus); break; } break; case '-': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::MinusEquals); break; case '>': offset++; out.tok = (RecognizedToken::Arrow); break; default: out.tok = (RecognizedToken::Minus); break; }break; case '*': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::StarEquals); break; default: out.tok = (RecognizedToken::Star); break; } break; case '/': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::SlashEquals); break; default: out.tok = (RecognizedToken::Slash); break; } break; case ';': out.tok = (RecognizedToken::Semicolon); break; case ',': out.tok = (RecognizedToken::Comma); break; case '.': switch (nc) { case '.': offset++; out.tok = (RecognizedToken::DoubleDot); break; default: out.tok = (RecognizedToken::Dot); break; } break; case '%': out.tok = (RecognizedToken::Percent); break; case '^': out.tok = (RecognizedToken::Xor); break; case '\\': out.tok = (RecognizedToken::Backslash); break; case '?': out.tok = (RecognizedToken::QestionMark); break; case '!': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::NotEquals); break; default: out.tok = (RecognizedToken::ExclamationMark); break; } break; case '>': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::GreaterOrEqual); break; default: out.tok = (RecognizedToken::GreaterThan); break; }break; case '<': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::LessOrEqual); break; case '-': offset++; out.tok = (RecognizedToken::BackArrow); break; default: out.tok = (RecognizedToken::LessThan); break; }break; case ':': switch (nc) { case ':': offset++; out.tok = (RecognizedToken::DoubleColon); break; case '=': offset++; out.tok = (RecognizedToken::ColonEquals); break; default: out.tok = (RecognizedToken::Colon); break; }break; case '|': switch (nc) { case '|': offset++; out.tok = (RecognizedToken::DoubleOr); break; default: out.tok = (RecognizedToken::Or); break; }break; case '&': switch (nc) { case '&': offset++; out.tok = (RecognizedToken::DoubleAnd); break; default: out.tok = (RecognizedToken::And); break; }break; case '=': switch (nc) { case '=': offset++; out.tok = (RecognizedToken::DoubleEquals); break; default: out.tok = (RecognizedToken::Equals); break; }break; default: out.tok = (RecognizedToken::Unknown); break; } x+= offset - start; out.src = this; out.offset = start; out.length = offset - start; out.x = start_x; out.y = y; return; } } else { out.tok = RecognizedToken::Eof; out.src = this; out.offset = offset+1; out.x = x+1; out.y = y; out.length = 0; } } void Cursor::move_matching() { if (src != nullptr && (tok == RecognizedToken::OpenBrace || tok == RecognizedToken::OpenParenthesis)) { src->move_matching(*this); if (tok == RecognizedToken::OpenBrace) tok = RecognizedToken::CloseBrace; if (tok == RecognizedToken::OpenParenthesis) tok = RecognizedToken::CloseParenthesis; } } void Source::move_matching(Cursor& c) const { c = token_pair.find(c.offset)->second; } errvoid Source::pair_tokens() { Cursor c = read_first(); int level_braces = 0; int level_parenthesies = 0; std::vector<Cursor> open_braces; std::vector<Cursor> open_parenthesies; while (c.tok != RecognizedToken::Eof) { switch (c.tok) { case RecognizedToken::OpenBrace: open_braces.push_back(c); level_braces++; break; case RecognizedToken::OpenParenthesis: open_parenthesies.push_back(c); level_parenthesies++; break; case RecognizedToken::CloseBrace: if (level_braces > 0) { token_pair[open_braces.back().offset] = c; open_braces.pop_back(); level_braces--; } else { return throw_specific_error(c, "There was no '}' to match this brace"); } break; case RecognizedToken::CloseParenthesis: if (level_parenthesies > 0) { token_pair[open_parenthesies.back().offset] = c; open_parenthesies.pop_back(); level_parenthesies--; } else { return throw_specific_error(c, "There was no ')' to match this parenthesis"); } break; } c.move(); } if (level_braces != 0) { return throw_specific_error(open_braces.back(), "There was no '}' to close this block"); } if (level_parenthesies != 0) { return throw_specific_error(open_parenthesies.back(), "There was no ')' to close this block"); } return err::ok; } ILBytecodeFunction* compile_build_block(Cursor& c) { Compiler* compiler = Compiler::current(); compiler->types()->t_build_script->compile(); auto func = compiler->global_module()->create_function(ILContext::compile); func->decl_id = compiler->types()->t_build_script->il_function_decl; ILBlock* b = func->create_and_append_block(); auto scope = ScopeState().function(func, compiler->types()->t_void).context(ILContext::compile).stack().compiler_stack(); Statement::parse_inner_block_start(b); Cursor name = c; BlockTermination term; c.move(); Statement::parse_inner_block(c, term, true, &name); return func; } std::string_view parent_path(std::string_view path) { std::size_t off=0; off = path.find_last_of("\\/"); if (off != std::string_view::npos) { return path.substr(0, off); }else { return "."; } } #ifdef WINDOWS std::string abs_path(std::string path) { char full[MAX_PATH]; GetFullPathNameA(path.c_str(), MAX_PATH, full, nullptr); return std::string(full); } #endif #ifdef LINUX std::string abs_path(std::string path) { char* abs = realpath(path.c_str(), nullptr); std::string res(abs); std::free(abs); return std::move(res); } #endif errvoid Source::require(std::string_view file, Source* src) { Compiler* compiler = Compiler::current(); std::string abs; if (src) { abs = parent_path(src->path); #ifdef WINDOWS abs += "\\"; #else abs += "/"; #endif abs += file; } else { abs = file; } { std::ifstream f(abs.c_str()); if (!f.good()) { std::string msg = "Required file \"" + std::string(abs) + "\" does not exist"; return throw_runtime_exception(compiler->evaluator(), msg); } } abs = abs_path(abs); auto f = compiler->included_sources.find(abs); if (f == compiler->included_sources.end()) { auto new_src = std::make_unique<Source>(); new_src->path = abs; new_src->load(abs.c_str()); new_src->register_debug(); if (!new_src->pair_tokens()) return err::fail; auto ptr = new_src.get(); compiler->included_sources[std::move(abs)] = std::move(new_src); std::unique_ptr<AstRootNode> node; if (!AstRootNode::parse(node,ptr)) return err::fail; ptr->root_node = std::move(node); if (!ptr->root_node->populate()) return err::fail; compiler->source_stack.push_back(ptr); for (auto&& r : ptr->root_node->compile) { auto scope = ScopeState().context(ILContext::compile).compiler_stack().function(nullptr,nullptr); Cursor c = load_cursor(r, ptr); BlockTermination termination; if (!Statement::parse(c, termination, ForceCompile::single)) return err::fail; } compiler->source_stack.pop_back(); } return err::ok; } void Source::require_wrapper(dword_t slice) { std::basic_string_view<char> data_string((char*)slice.p1, (std::size_t)slice.p2); if (!Source::require(data_string, Compiler::current()->source())) { ILEvaluator::ex_throw(); return; } } }
24.12966
123
0.592558
fencl
d22e959e01a66ccdc2bd90337a1e1e811f83ffaf
2,119
hpp
C++
src/3rd party/boost/boost/numeric/interval/compare/set.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/boost/boost/numeric/interval/compare/set.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/boost/boost/numeric/interval/compare/set.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
/* Boost interval/compare/set.hpp template implementation file * * Copyright Guillaume Melquiond 2002-2003 * Permission to use, copy, modify, sell, and distribute this software * is hereby granted without fee provided that the above copyright notice * appears in all copies and that both that copyright notice and this * permission notice appear in supporting documentation, * * None of the above authors make any representation about the * suitability of this software for any purpose. It is provided "as * is" without express or implied warranty. * * $Id: set.hpp,v 1.2 2003/02/05 17:34:31 gmelquio Exp $ */ #ifndef BOOST_NUMERIC_INTERVAL_COMPARE_SET_HPP #define BOOST_NUMERIC_INTERVAL_COMPARE_SET_HPP #include <boost/numeric/interval/detail/interval_prototype.hpp> #include <boost/numeric/interval/utility.hpp> namespace boost { namespace numeric { namespace interval_lib { namespace compare { namespace set { template<class T, class Policies1, class Policies2> inline bool operator<(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return proper_subset(x, y); } template<class T, class Policies1, class Policies2> inline bool operator<=(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return subset(x, y); } template<class T, class Policies1, class Policies2> inline bool operator>(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return proper_subset(y, x); } template<class T, class Policies1, class Policies2> inline bool operator>=(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return subset(y, x); } template<class T, class Policies1, class Policies2> inline bool operator==(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return equal(y, x); } template<class T, class Policies1, class Policies2> inline bool operator!=(const interval<T, Policies1>& x, const interval<T, Policies2>& y) { return !equal(y, x); } } // namespace set } // namespace compare } // namespace interval_lib } // namespace numeric } // namespace boost #endif // BOOST_NUMERIC_INTERVAL_COMPARE_SET_HPP
29.84507
81
0.754129
OLR-xray
d2339c2a2e67c474fcc62c9003793232129366b0
355
cpp
C++
ejercicio2/main.cpp
matbentancur/pav
df556249e342863286ad1c991a5613bd63e09902
[ "MIT" ]
null
null
null
ejercicio2/main.cpp
matbentancur/pav
df556249e342863286ad1c991a5613bd63e09902
[ "MIT" ]
1
2018-04-05T15:06:04.000Z
2018-04-15T21:46:44.000Z
ejercicio2/main.cpp
matbentancur/pav
df556249e342863286ad1c991a5613bd63e09902
[ "MIT" ]
null
null
null
#include <iostream> #include "A.h" #include "B.h" #include "C.h" using namespace std; int main(){ ClassA msg_a; msg_a = ClassA(); ClassB msg_b; msg_b = ClassB(); ClassC msg_c; msg_c = ClassC(); cout<<msg_a.getA()<<endl; cout<<msg_b.getB()<<endl; cout<<msg_c.getC()<<endl; return 0; }
14.2
30
0.535211
matbentancur
d2398630f54d13522c03b861d8d20976fa9aebdb
5,937
hpp
C++
RegNRecon/jly_sorting.hpp
MrJia1997/RenderKinect
6cc6d6a56ce6a925920e155db5aa6f5239c563e8
[ "MIT" ]
null
null
null
RegNRecon/jly_sorting.hpp
MrJia1997/RenderKinect
6cc6d6a56ce6a925920e155db5aa6f5239c563e8
[ "MIT" ]
null
null
null
RegNRecon/jly_sorting.hpp
MrJia1997/RenderKinect
6cc6d6a56ce6a925920e155db5aa6f5239c563e8
[ "MIT" ]
null
null
null
/******************************************************************** Sorting/Selection functions for the Go-ICP Algorithm Last modified: Jan 27, 2015 "Go-ICP: Solving 3D Registration Efficiently and Globally Optimally" Jiaolong Yang, Hongdong Li, Yunde Jia International Conference on Computer Vision (ICCV), 2013 Copyright (C) 2013 Jiaolong Yang (BIT and ANU) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *********************************************************************/ #ifndef JLY_SORING_HPP #define JLY_SORING_HPP #define INTRO_K 5 #define INSERTION_NUM 5 //sorting in ascending order template <typename T> inline size_t median_of_st_mid_en(T * data, size_t st, size_t en) { size_t mid = (st+en)/2; if(data[st] < data[en]) { if(data[mid] < data[st])//median is data[st] return st; else if(data[mid] < data[en]) //median is data[md] return mid; else //median is data[en] return en; } else // data[en] <= data[st] { if(data[mid] < data[en])//median is data[en] return en; else if(data[mid] < data[st]) //median is data[md] return mid; else //median is data[st] return st; } } //median of 3 numbers template <typename T> inline size_t median_of_3(T * data, size_t st) { T* data_ = data + st; if(data_[0] < data_[2]) { if(data_[1] < data_[0])//median is data[0] return st; else if(data_[1] < data_[2]) //median is data[1] return st + 1; else //median is data[2] return st + 2; } else // data[2] <= data[0] { if(data[1] < data[2])//median is data[2] return st + 2; else if(data[1] < data[0]) //median is data[1] return st + 1; else //median is data[0] return st; } } //median of 5 numbers with 6 comparisons template <typename T> inline size_t median_of_5(T * data, size_t st) { T* data_ = data + st; T tmp; if(data_[0] > data_[1]) { tmp = data_[0]; data_[0] = data_[1]; data_[1] = tmp; } if(data_[2] > data_[3]) { tmp = data_[2]; data_[2] = data_[3]; data_[3] = tmp; } if(data_[0] < data_[2]) { tmp = data_[4]; data_[4] = data_[0]; if(tmp < data_[1]) data_[0] = tmp; else { data_[0] = data_[1]; data_[1] = tmp; } } else { tmp = data_[4]; data_[4] = data_[2]; if(tmp < data_[3]) data_[2] = tmp; else { data_[2] = data_[3]; data_[3] = tmp; } } if(data_[0] < data_[2]) { if(data_[1] < data_[2]) return st + 1; else return st + 2; } else { if(data_[0] < data_[3]) return st; else return st + 3; } } template <typename T> size_t median_of_medians(T * data, size_t st, size_t en) { size_t l = en-st+1; size_t numof5 = l / 5; if(l % 5 != 0) numof5 ++; T tmp; size_t subst = st, suben = st + 4; size_t i, medind; //fist (numof5 - 1) groups for(i = 0; i < numof5 - 1; i++, subst += 5, suben += 5) { medind = median_of_5(data, subst); tmp = data[st+i]; data[st+i] = data[medind]; data[medind] = tmp; } //last group { switch(en-subst+1) { case 3: // 3 elements case 4: // 4 elements medind = median_of_3(data, subst); break; case 5: // 5 elements medind = median_of_5(data, subst); break; default: // 1 or 2 elements medind = subst; break; } tmp = data[st+i]; data[st+i] = data[medind]; data[medind] = tmp; } //median of medians if(numof5 > 5) return median_of_medians(data, st, st + numof5-1); else { switch(numof5) { case 3: // 3 elements case 4: // 4 elements return median_of_3(data, st); break; case 5: // 5 elements return median_of_5(data, st); break; default: // 1 or 2 elements return st; break; } } } template <typename T> void insertion_sort(T * data, size_t st, size_t en) { T tmp; size_t i, j; for(i = st+1; i <= en; i++) for(j = i; j > st && data[j-1] > data[j]; j--) { tmp = data[j-1]; data[j-1] = data[j]; data[j] = tmp; } } // Sort the given array in ascending order // Stop immediately after the array is splitted into k small numbers and n-k large numbers template <typename T> void intro_select(T * data, size_t st, size_t en, size_t k) { T pivot; T tmp; //for(; st < en && data[st] > 0; st++); size_t l_pre = en-st+1; size_t l; size_t medind; bool quickselect = true; size_t i = 0; while(1) { if(st >= en) break; if(en - st <= INSERTION_NUM) { insertion_sort(data, st, en); return; } if(quickselect && i++ == INTRO_K) { // switch to 'median of medians' if INTRO_K partations of quickselect fail to half the size l = en-st+1; if(l*2 > l_pre) quickselect = false; l_pre = l; i = 0; } if(quickselect) //medind = st; medind = median_of_st_mid_en(data, st, en); else medind = median_of_medians(data, st, en); if(medind != st) { tmp = data[st]; data[st] = data[medind]; data[medind] = tmp; } size_t p = st; size_t left = st+1; size_t right = en; pivot = data[p]; while(1) { while (left < right && pivot >= data[left]) ++left; while (left < right && pivot <= data[right]) --right; if (left >= right) break; //swap left & right tmp = data[left]; data[left] = data[right]; data[right] = tmp; } size_t s = left-1; if(data[left] < pivot) s = left; //swap p & s data[p] = data[s]; data[s] = pivot; if(s < k) st = s+1; else if(s > k) en = s-1; else //s == k break; } } #endif
18.787975
95
0.593397
MrJia1997
d23e8ce8d08e98652ed7d04b5bdfdd9855ff24b6
407
hpp
C++
include/CompareVersionNumbers.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
include/CompareVersionNumbers.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
include/CompareVersionNumbers.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#ifndef COMPARE_VERSION_NUMBERS_HPP_ #define COMPARE_VERSION_NUMBERS_HPP_ #include <string> #include <vector> using namespace std; class CompareVersionNumbers { public: int compareVersion(string version1, string version2); private: int compareDigitsString(string num1, string num2); void tokenize(const string &version, vector<string> &versions); }; #endif // COMPARE_VERSION_NUMBERS_HPP_
20.35
67
0.786241
yanzhe-chen
d240095031c8d3e133801299163fc595b6244045
1,090
cpp
C++
tests/char_set/test_single.cpp
FrancoisChabot/abulafia
4aeefd8d388d68994f9d73bb0f586517737a5174
[ "BSL-1.0" ]
42
2017-09-21T16:51:12.000Z
2020-03-12T09:44:32.000Z
tests/char_set/test_single.cpp
FrancoisChabot/abulafia
4aeefd8d388d68994f9d73bb0f586517737a5174
[ "BSL-1.0" ]
32
2017-09-21T06:31:08.000Z
2017-10-20T00:52:58.000Z
tests/char_set/test_single.cpp
FrancoisChabot/abulafia
4aeefd8d388d68994f9d73bb0f586517737a5174
[ "BSL-1.0" ]
3
2018-10-30T11:29:18.000Z
2019-07-18T08:19:51.000Z
// Copyright 2017 Francois Chabot // (francois.chabot.dev@gmail.com) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "abulafia/abulafia.h" #include "gtest/gtest.h" using namespace abu; static_assert(char_set::is_char_set<char>::value == false); static_assert(char_set::is_char_set<char_set::Single<char>>::value == true); static_assert( char_set::is_char_set<decltype(char_set::to_char_set('a'))>::value == true); TEST(test_single, simple_test) { auto c_set = char_set::single('a'); static_assert(char_set::is_char_set<decltype(c_set)>::value, "must be a valid char set"); using char_set_type = decltype(c_set); static_assert(is_same<char_set_type::char_t, char>::value, "type inference failure"); EXPECT_TRUE(c_set.is_valid('a')); EXPECT_FALSE(c_set.is_valid('b')); EXPECT_FALSE(c_set.is_valid('g')); EXPECT_FALSE(c_set.is_valid('A')); EXPECT_FALSE(c_set.is_valid(' ')); EXPECT_FALSE(c_set.is_valid('\0')); }
31.142857
80
0.704587
FrancoisChabot
d240ed2bde9c335bdd5f4a52c127bd3a9fa677eb
4,246
hpp
C++
include/shz/math/frustum.hpp
TraxNet/ShadingZenCpp
46860da3249900259941bf64f4a46347500b65fb
[ "MIT" ]
3
2015-04-30T15:41:51.000Z
2018-12-28T05:47:18.000Z
include/shz/math/frustum.hpp
TraxNet/ShadingZenCpp
46860da3249900259941bf64f4a46347500b65fb
[ "MIT" ]
null
null
null
include/shz/math/frustum.hpp
TraxNet/ShadingZenCpp
46860da3249900259941bf64f4a46347500b65fb
[ "MIT" ]
null
null
null
#ifndef __SHZ_MATH_FRUSTUM__ #define __SHZ_MATH_FRUSTUM__ #include <array> #include <shz/math/matrix.hpp> #include <shz/math/plane.hpp> namespace shz{ namespace math{ template <typename T> struct frustum { static const size_t num_planes = 6; frustum(){} frustum(const shz::math::matrix<T, 4, 4>& clip){ generate_planes_from_projection(clip); } bool is_point_inside(T x, T y, T z){ for(size_t i=0; i < num_planes; ++i){ if(planes[i].is_point_behind(x, y, z)) return false; } } bool is_point_inside(const vector<T, 3>& p){ for(size_t i=0; i < num_planes; ++i){ if(planes[i].is_point_behind(p)) return false; } } bool is_point_inside(const vector<T, 4>& p){ for(size_t i=0; i < num_planes; ++i){ if(planes[i].is_point_behind(p)) return false; } } bool is_sphere_inside(T x, T y, T z, T radius) { for(size_t i=0; i < num_planes; ++i){ if(planes[i].is_sphere_behind(x, y, z, radius)) return false; } return true; } /* public boolean is_bbox_inside(BBox bbox) { for(int index=0; index < 6; index++){ Plane plane = planes[index]; Vector3 mins = bbox.getMins(); Vector3 maxs = bbox.getMaxs(); T x, y, z; x = mins.x; y = mins.y; z = mins.z; if(!plane.isPointBehind(x, y, z)) continue; x = maxs.x; y = mins.y; z = mins.z; if(!plane.isPointBehind(x, y, z)) continue; x = mins.x; y = maxs.y; z = mins.z; if(!plane.isPointBehind(x, y, z)) continue; x = maxs.x; y = maxs.y; z = mins.z; if(!plane.isPointBehind(x, y, z)) continue; x = mins.x; y = mins.y; z = maxs.z; if(!plane.isPointBehind(x, y, z)) continue; x = maxs.x; y = mins.y; z = maxs.z; if(!plane.isPointBehind(x, y, z)) continue; x = mins.x; y = maxs.y; z = maxs.z; if(!plane.isPointBehind(x, y, z)) continue; x = maxs.x; y = maxs.y; z = maxs.z; if(!plane.isPointBehind(x, y, z)) continue; return false; } return true; }*/ enum plane_names{ REAR = 0, FRONT, RIGHT, LEFT, TOP, BOTTOM }; void generate_planes_from_projection(const matrix<T, 4, 4>& clip){ shz::math::plane<T>* plane = &planes[plane_names::RIGHT]; plane->eq[0] = clip[3] - clip[0]; plane->eq[1] = clip[7] - clip[4]; plane->eq[2] = clip[11] - clip[8]; plane->eq[3] = clip[15] - clip[12]; T t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; plane = &planes[plane_names::LEFT]; plane->eq[0] = clip[3] + clip[0]; plane->eq[1] = clip[7] + clip[4]; plane->eq[2] = clip[11] + clip[8]; plane->eq[3] = clip[15] + clip[12]; t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; plane = &planes[plane_names::BOTTOM]; plane->eq[0] = clip[3] + clip[1]; plane->eq[1] = clip[7] + clip[5]; plane->eq[2] = clip[11] + clip[9]; plane->eq[3] = clip[15] + clip[13]; t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; plane = &planes[plane_names::TOP]; plane->eq[0] = clip[3] - clip[1]; plane->eq[1] = clip[7] - clip[5]; plane->eq[2] = clip[11] - clip[9]; plane->eq[3] = clip[15] - clip[13]; t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; plane = &planes[plane_names::FRONT]; plane->eq[0] = clip[3] - clip[2]; plane->eq[1] = clip[7] - clip[6]; plane->eq[2] = clip[11] - clip[10]; plane->eq[3] = clip[15] - clip[14]; t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; plane = &planes[plane_names::REAR]; plane->eq[0] = clip[3] + clip[2]; plane->eq[1] = clip[7] + clip[6]; plane->eq[2] = clip[11] + clip[10]; plane->eq[3] = clip[15] + clip[14]; t = plane->inv_length(); plane->eq[0] *= t; plane->eq[1] *= t; plane->eq[2] *= t; plane->eq[3] *= t; } std::array<shz::math::plane<T>, num_planes> planes; }; } } #endif // __SHZ_MATH_FRUSTUM__
20.512077
68
0.537447
TraxNet
d240f6b09f2be76740fce5c84508a4a01ed2a6e3
664
hpp
C++
higan/sfc/coprocessor/coprocessor.hpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
null
null
null
higan/sfc/coprocessor/coprocessor.hpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
null
null
null
higan/sfc/coprocessor/coprocessor.hpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
null
null
null
#include <sfc/coprocessor/icd2/icd2.hpp> #include <sfc/coprocessor/mcc/mcc.hpp> #include <sfc/coprocessor/nss/nss.hpp> #include <sfc/coprocessor/event/event.hpp> #include <sfc/coprocessor/sa1/sa1.hpp> #include <sfc/coprocessor/superfx/superfx.hpp> #include <sfc/coprocessor/armdsp/armdsp.hpp> #include <sfc/coprocessor/hitachidsp/hitachidsp.hpp> #include <sfc/coprocessor/necdsp/necdsp.hpp> #include <sfc/coprocessor/epsonrtc/epsonrtc.hpp> #include <sfc/coprocessor/sharprtc/sharprtc.hpp> #include <sfc/coprocessor/spc7110/spc7110.hpp> #include <sfc/coprocessor/sdd1/sdd1.hpp> #include <sfc/coprocessor/obc1/obc1.hpp> #include <sfc/coprocessor/msu1/msu1.hpp>
31.619048
52
0.789157
mp-lee
d2440f26f0465d0ebef1db5e21cbdd7ce5349b8a
2,725
cpp
C++
trainer/MemoryManager.cpp
thefinalstarman/DolphinTrainer
f3d615f35b21986cc2078028311306207fe00801
[ "MIT" ]
1
2017-11-19T17:02:34.000Z
2017-11-19T17:02:34.000Z
trainer/MemoryManager.cpp
thefinalstarman/DolphinTrainer
f3d615f35b21986cc2078028311306207fe00801
[ "MIT" ]
null
null
null
trainer/MemoryManager.cpp
thefinalstarman/DolphinTrainer
f3d615f35b21986cc2078028311306207fe00801
[ "MIT" ]
null
null
null
/* * MemoryManager.cpp * * Created on: Jan 24, 2018 * Author: Jordan Richards */ #include <trainer/MemoryManager.h> #include <algorithm> #include <vector> #include <exception> #include <functional> namespace xtrainer{ Page::Page(PageInfo&& p, int expiration): expirationTime(expiration){ size = p.size(); addr = (size_t)p.startAddr; data = new char[size]; } Page::~Page(){ delete [] data; } size_t Page::read(size_t addr, void* buffer, size_t n){ char* str = (char*)buffer; size_t k = 0; for(int i = addr - this->addr; i < addr - this->addr + n && i < size; i++){ str[i] = data[i]; k++; }return k; } void Page::update(Process* proc){ proc->readBytes((void*)addr, data, size); lastUpdated = time(0); } MemoryManager::MemoryManager(Process* p): parent(p) {} void MemoryManager::addPage(PageInfo&& pageInfo, int expiration){ pages.insert(Page(std::move(pageInfo),expiration)); } const Page* MemoryManager::findPage(size_t addr){ if(!pages.size())return nullptr; auto page = std::lower_bound(pages.begin(), pages.end(), addr); if(page == pages.end() || (page != pages.begin() && page->getStartAddress() > addr))page--; if(page->getStartAddress() + page->getSize() < addr)return &*page; return nullptr; } size_t MemoryManager::read(size_t addr, void* buffer, size_t n, bool forceUpdate){ Page* p = const_cast<Page*>(findPage(addr)); if(p == nullptr){ return parent->readBytes((void*)addr, buffer, n); } if(allExpired || forceUpdate || p->isExpired()) p->update(parent); allExpired = false; return p->read(addr, buffer, n); } size_t MemoryManager::write(size_t addr, void* str, size_t n){ allExpired = true; return parent->writeBytes((void*)addr, str, n); } void dfs(int i, int* visited, std::vector<Property*> in, std::function<void(Property*)> callback){ if(visited[i] == 2)return; if(visited[i] == 1)throw std::runtime_error("Circular dependency while processing property."); visited[i] = 1; if(in[i]->dependency() != nullptr){ auto it = std::find(in.begin(), in.end(), in[i]->dependency()); if(it == in.end())throw std::runtime_error("Required property not found."); dfs(it - in.begin(), visited, in, callback); } visited[i] = 2; callback(in[i]); } void MemoryManager::updateProperties(std::set<Property*> in){ std::vector<Property*> v(in.begin(), in.end()); int* visited = new int[v.size()]; for(int i = 0; i < v.size(); i++){ dfs(i, visited, v, [](Property* p){ p->update(); }); } delete [] visited; } void MemoryManager::updateModules(){ std::set<Property*> props; for(auto it = mods.begin(); it != mods.end(); it++){ it->second->getProperties(std::inserter(props,props.begin())); } updateProperties(props); } }//namespace xtrainer
24.772727
98
0.659817
thefinalstarman
d2447e0884454edf39881ca6dfc42381c63e3d72
16,498
cpp
C++
src/main.cpp
Faaux/DingoEngine
05c8ae59816befaaa203e8d5310c4e17da89bb7b
[ "MIT" ]
null
null
null
src/main.cpp
Faaux/DingoEngine
05c8ae59816befaaa203e8d5310c4e17da89bb7b
[ "MIT" ]
null
null
null
src/main.cpp
Faaux/DingoEngine
05c8ae59816befaaa203e8d5310c4e17da89bb7b
[ "MIT" ]
null
null
null
/** * @file main.cpp * @author Faaux (github.com/Faaux) * @date 11 February 2018 */ #include "main.h" #include <ImGuizmo.h> #include <SDL.h> #include "components/SceneComponent.h" #include "components/StaticMeshComponent.h" #include "engine/Messaging.h" #include "engine/Types.h" #include "engine/WorldEditor.h" #include "graphics/FrameData.h" #include "graphics/GameWorldWindow.h" #include "graphics/GraphicsSystem.h" #include "graphics/Renderer.h" #include "imgui/DG_Imgui.h" #include "imgui/imgui_dock.h" #include "imgui/imgui_impl_sdl_gl3.h" #include "memory/Memory.h" #include "physics/Physics.h" #include "platform/ConditionVariable.h" #include "platform/InputSystem.h" #include "platform/Job.h" #include "platform/SDLHelper.h" #include "platform/StringIdCRC32.h" namespace DG { #if _DEBUG StringHashTable<2048> g_StringHashTable; #endif GameMemory Memory; GameState* Game; Managers* g_Managers; bool InitWindow() { Game->RenderState->Window = SDL_CreateWindow("Dingo", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (Game->RenderState->Window == nullptr) { SDL_LogCritical(SDL_LOG_CATEGORY_VIDEO, "Window could not be created! SDL Error: %s\n", SDL_GetError()); return false; } return true; } bool InitImgui() { ImGui_ImplSdlGL3_Init(Game->RenderState->Window); ImGui::StyleColorsDark(); ImGui::LoadDock(); InitInternalImgui(); return true; } bool InitWorkerThreads() { // Register Main Thread JobSystem::RegisterWorker(); // Create Worker Threads for (int i = 0; i < SDL_GetCPUCount() - 1; ++i) { JobSystem::CreateAndRegisterWorker(); } return true; } bool InitMemory() { // Grab a 1GB of memory const u32 TotalMemorySize = 1 * 1024 * 1024 * 1024; // 1 GB // ToDo: Get rid of this! u8* memory = (u8*)VirtualAlloc(0, TotalMemorySize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!memory) { SDL_LogError(0, "Couldn't allocate game memory."); return false; } // Assign 50 MB to Persistent, rest is transient const u32 PersistentMemorySize = 50 * 1024 * 1024; // 50 MB Memory.PersistentMemory.Init(memory, PersistentMemorySize); const u32 TransientMemorySize = TotalMemorySize - PersistentMemorySize; Memory.TransientMemory.Init(memory + PersistentMemorySize, TransientMemorySize); return true; } void Cleanup() { // PhysX Cleanup Game->WorldEdit->Shutdown(); ShutdownPhysics(); ImGui_ImplSdlGL3_Shutdown(); SDL_Quit(); } void AttachDebugListenersToMessageSystem() {} u64 GetFrameBufferIndex(u64 frameIndex, u64 size) { s64 index = (s64)frameIndex; if (index < 0) { return (size - (-index % size)); } return frameIndex % size; } template <typename T> void CopyImVector(ImVector<T>* dest, ImVector<T>* src, StackAllocator& allocator) { dest->Size = src->Size; dest->Capacity = src->Capacity; u32 memSize = src->Capacity * sizeof(T); dest->Data = (T*)allocator.Push(memSize, 4); memcpy(dest->Data, src->Data, memSize); } } // namespace DG int main(int, char* []) { using namespace DG; if (!InitMemory()) return -1; if (!InitSDL()) return -1; if (!InitWorkerThreads()) return -1; InitClocks(); // Initialize Resource Managers g_Managers = Memory.TransientMemory.PushAndConstruct<Managers>(); g_Managers->ModelManager = Memory.TransientMemory.PushAndConstruct<ModelManager>(); g_Managers->GLTFSceneManager = Memory.TransientMemory.PushAndConstruct<graphics::GLTFSceneManager>(); g_Managers->ShaderManager = Memory.TransientMemory.PushAndConstruct<graphics::ShaderManager>(); // Initialize Game const u32 playModeSize = 4 * 1024 * 1024; // 4MB Game = Memory.PersistentMemory.Push<GameState>(); Game->GameIsRunning = true; Game->PlayModeStack.Init(Memory.TransientMemory.Push(playModeSize, 4), playModeSize); Game->RawInputSystem = Memory.TransientMemory.PushAndConstruct<RawInputSystem>(); // Init Messaging // ToDo(Faaux)(Messaging): Messaging runs on real time clock? What if we pause the game? g_MessagingSystem.Initialize(&Memory.TransientMemory, &g_RealTimeClock); // Init RenderState Game->RenderState = Memory.TransientMemory.PushAndConstruct<graphics::RenderState>(); Game->RenderState->RenderMemory.Init(Memory.TransientMemory.Push(playModeSize, 4), playModeSize); // Create Window on main thread if (!InitWindow()) return -1; // This will boot up opengl on another thread if (!graphics::StartRenderThread(Game->RenderState)) return -1; if (!InitImgui()) return -1; if (!InitPhysics()) return -1; Game->WorldEdit = Memory.TransientMemory.PushAndConstruct<WorldEdit>(); Game->WorldEdit->Startup(&Memory.TransientMemory); Game->ActiveWorld = Game->WorldEdit->GetWorld(); AttachDebugListenersToMessageSystem(); u64 currentTime = SDL_GetPerformanceCounter(); f32 cpuFrequency = (f32)(SDL_GetPerformanceFrequency()); // Init FrameRingBuffer graphics::FrameData* frames = Memory.TransientMemory.Push<graphics::FrameData>(5); for (int i = 0; i < 5; ++i) { const u32 frameDataSize = 16 * 1024 * 1024; // 16MB u8* base = Memory.TransientMemory.Push(frameDataSize, 4); frames[i].FrameMemory.Init(base, frameDataSize); frames[i].Reset(); frames[i].IsPreRenderDone = true; frames[i].RenderDone.Create(); frames[i].DoubleBufferDone.Create(); } // Signal once, this opens the gate for the first frame to pass! frames[4].RenderDone.Signal(); // Stop clocks depending on edit mode if (Game->Mode == GameState::GameMode::EditMode) g_InGameClock.SetPaused(true); else if (Game->Mode == GameState::GameMode::PlayMode) g_EditingClock.SetPaused(true); // ToDo: This is not the right place for this to live.... graphics::GameWorldWindow mainGameWindow; mainGameWindow.Initialize("EditWindow", Game->WorldEdit->GetWorld()); while (!Game->RawInputSystem->IsQuitRequested()) { static bool isWireframe = false; TWEAKER_CAT("OpenGL", CB, "Wireframe", &isWireframe); // Frame Data Setup graphics::FrameData& previousFrameData = frames[GetFrameBufferIndex(Game->CurrentFrameIdx - 1, 5)]; graphics::FrameData& currentFrameData = frames[GetFrameBufferIndex(Game->CurrentFrameIdx, 5)]; currentFrameData.Reset(); // For now assume one world only currentFrameData.WorldRenderDataCount = 1; currentFrameData.WorldRenderData = currentFrameData.FrameMemory.PushAndConstruct<graphics::WorldRenderData*>(); currentFrameData.WorldRenderData[0] = currentFrameData.FrameMemory.PushAndConstruct<graphics::WorldRenderData>(); currentFrameData.WorldRenderData[0]->RenderCTX = currentFrameData.FrameMemory.PushAndConstruct<graphics::RenderContext>(); currentFrameData.WorldRenderData[0]->DebugRenderCTX = currentFrameData.FrameMemory.PushAndConstruct<graphics::DebugRenderContext>(); graphics::g_DebugRenderContext = currentFrameData.WorldRenderData[0]->DebugRenderCTX; currentFrameData.WorldRenderData[0]->RenderCTX->IsWireframe = isWireframe; // Update Phase! { // Poll Events and Update Input accordingly Game->RawInputSystem->Update(); // Measure time and update clocks! const u64 lastTime = currentTime; currentTime = SDL_GetPerformanceCounter(); f32 dtSeconds = (f32)(currentTime - lastTime) / cpuFrequency; // This usually happens once we hit a breakpoint when debugging if (dtSeconds > 0.25f) dtSeconds = 1.0f / TargetFrameRate; // Update Clocks g_RealTimeClock.Update(dtSeconds); g_EditingClock.Update(dtSeconds); g_InGameClock.Update(dtSeconds); // Imgui ImGui_ImplSdlGL3_NewFrame(Game->RenderState->Window); ImGuizmo::BeginFrame(); ImVec2 mainBarSize; // Main Menu Bar if (ImGui::BeginMainMenuBar()) { mainBarSize = ImGui::GetWindowSize(); if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Save layout")) { ImGui::SaveDock(); } if (ImGui::MenuItem("Exit")) { Game->RawInputSystem->RequestClose(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Shader")) { if (ImGui::MenuItem("Reload changed shaders")) { auto it = g_Managers->ShaderManager->begin(); auto end = g_Managers->ShaderManager->end(); while (it != end) { it->ReloadShader(); ++it; } } ImGui::EndMenu(); } if (Game->Mode == GameState::GameMode::EditMode) { if (ImGui::MenuItem("Start Playmode")) { Game->Mode = GameState::GameMode::PlayMode; g_EditingClock.SetPaused(true); g_InGameClock.SetPaused(false); // Cleanup PlayMode stack Game->PlayModeStack.Reset(); Game->ActiveWorld = Game->PlayModeStack.Push<GameWorld>(); // Copy World from Edit mode over // CopyGameWorld(Game->ActiveWorld, Game->WorldEdit->GetWorld()); } } else if (Game->Mode == GameState::GameMode::PlayMode) { if (ImGui::MenuItem("Stop Playmode")) { Game->Mode = GameState::GameMode::EditMode; g_EditingClock.SetPaused(false); g_InGameClock.SetPaused(true); Game->ActiveWorld->Shutdown(); Game->ActiveWorld->~GameWorld(); Game->ActiveWorld = Game->WorldEdit->GetWorld(); } } if (ImGui::MenuItem("Spawn Duck Actor")) { auto actor = Game->ActiveWorld->CreateActor<Actor>(); auto staticMesh = actor->RegisterComponent<StaticMeshComponent>("DuckModel", Transform()); /*std::ofstream o("pretty.json"); nlohmann::json j; actor->Serialize(j); o << std::setw(4) << j << std::endl;*/ } // Shift all the way to the right ImGui::SameLine(ImGui::GetWindowWidth() - 200); ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::EndMainMenuBar(); } // Create Main Window vec2 adjustedDisplaySize = ImGui::GetIO().DisplaySize; adjustedDisplaySize.y -= mainBarSize.y; ImGui::SetNextWindowPos(ImVec2(0, mainBarSize.y)); ImGui::SetNextWindowSize(adjustedDisplaySize, ImGuiCond_Always); bool isContentVisible = ImGui::Begin("###content", 0, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoInputs); Assert(isContentVisible); ImGui::BeginDockspace(); // Imgui Window for MainViewport mainGameWindow.AddToImgui(); // Game Logic g_MessagingSystem.Update(); mainGameWindow.Update(dtSeconds); // Also updates the world Game->WorldEdit->Update(); AddImguiTweakers(); ImGui::EndDockspace(); ImGui::End(); ImGui::Render(); // Just generates statements to be rendered, doesnt actually render! } // PreRender Phase! { // Copying imgui render data to context ImDrawData* drawData = currentFrameData.FrameMemory.Push<ImDrawData>(); *drawData = *ImGui::GetDrawData(); ImDrawList** newList = currentFrameData.FrameMemory.Push<ImDrawList*>(drawData->CmdListsCount); // Create copies of cmd lists for (int i = 0; i < drawData->CmdListsCount; ++i) { // Copy this list! ImDrawList* drawList = drawData->CmdLists[i]; newList[i] = currentFrameData.FrameMemory.Push<ImDrawList>(); ImDrawList* copiedDrawList = newList[i]; // Create copies of copiedDrawList->CmdBuffer = ImVector<ImDrawCmd>(); CopyImVector<ImDrawCmd>(&copiedDrawList->CmdBuffer, &drawList->CmdBuffer, currentFrameData.FrameMemory); copiedDrawList->IdxBuffer = ImVector<ImDrawIdx>(); CopyImVector<ImDrawIdx>(&copiedDrawList->IdxBuffer, &drawList->IdxBuffer, currentFrameData.FrameMemory); copiedDrawList->VtxBuffer = ImVector<ImDrawVert>(); CopyImVector<ImDrawVert>(&copiedDrawList->VtxBuffer, &drawList->VtxBuffer, currentFrameData.FrameMemory); } drawData->CmdLists = newList; // Set Imgui Render Data currentFrameData.ImOverlayDrawData = drawData; graphics::RenderQueue* rq = currentFrameData.FrameMemory.Push<graphics::RenderQueue>(); // ToDo(Faaux)(Graphics): This needs to be a dynamic amount of renderables rq->Renderables = currentFrameData.FrameMemory.Push<graphics::Renderable>(250); rq->Count = 0; // Get all actors that need to be drawn for (auto& actor : Game->ActiveWorld->GetAllActors()) { // Check if we have a Mesh associated auto staticMeshes = actor->GetComponentsOfType(StaticMeshComponent::GetClassType()); for (auto& sm : staticMeshes) { auto staticMesh = (StaticMeshComponent*)sm; auto model = g_Managers->ModelManager->Exists(staticMesh->GetRenderable()); Assert(model); Assert(!rq->Shader || rq->Shader == &model->shader); rq->Shader = &model->shader; rq->Renderables[rq->Count].Model = model; rq->Renderables[rq->Count].ModelMatrix = staticMesh->GetGlobalModelMatrix(); rq->Count++; } } if (rq->Count != 0) currentFrameData.WorldRenderData[0]->RenderCTX->AddRenderQueue(rq); currentFrameData.WorldRenderData[0]->Window = &mainGameWindow; currentFrameData.IsPreRenderDone = true; } // Render Phase { previousFrameData.RenderDone.WaitAndReset(); Game->RenderState->FrameDataToRender = &currentFrameData; Game->RenderState->RenderCondition.Signal(); currentFrameData.DoubleBufferDone.WaitAndReset(); } Game->CurrentFrameIdx++; } Game->GameIsRunning = false; g_JobQueueShutdownRequested = true; Cleanup(); return 0; }
35.403433
100
0.582798
Faaux
d244ca6df6310dae68ec5d4d358bbb96b796fe5e
7,257
hxx
C++
src/mirrage/asset/include/mirrage/asset/asset_manager.hxx
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
14
2017-10-26T08:45:54.000Z
2021-04-06T11:44:17.000Z
src/mirrage/asset/include/mirrage/asset/asset_manager.hxx
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
17
2017-10-09T20:11:58.000Z
2018-11-08T22:05:14.000Z
src/mirrage/asset/include/mirrage/asset/asset_manager.hxx
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
1
2018-09-26T23:10:06.000Z
2018-09-26T23:10:06.000Z
#pragma once #ifndef MIRRAGE_ASSETMANAGER_INCLUDED #include "asset_manager.hpp" #endif #ifndef __clang_analyzer__ #include <async++.h> #endif namespace mirrage::asset { template <class R> auto Ptr<R>::get_blocking() const -> const R& { if(_cached_result) return *_cached_result; return *(_cached_result = &_task.get()); } template <class R> auto Ptr<R>::get_if_ready() const -> util::maybe<const R&> { if(_cached_result) return util::justPtr(_cached_result); return ready() ? util::nothing : util::maybe<const R&>(get_blocking()); } template <class R> auto Ptr<R>::ready() const -> bool { return _task.valid() && _task.ready(); } template <class R> void Ptr<R>::reset() { _aid = {}; _task = {}; _cached_result = nullptr; } namespace detail { template <class T> struct has_reload { private: typedef char one; typedef long two; template <typename C> static one test(decltype(std::declval<Loader<C>>().reload(std::declval<istream>(), std::declval<C&>()))*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(nullptr)) == sizeof(char) }; }; template <class T> constexpr auto has_reload_v = has_reload<T>::value; template <class TaskType, class T> constexpr auto is_task_v = std::is_same_v<T, ::async::task<TaskType>> || std::is_same_v<T, ::async::shared_task<TaskType>>; template <typename T> auto Asset_container<T>::load(AID aid, const std::string& path, bool cache) -> Ptr<T> { auto lock = std::scoped_lock{_container_mutex}; auto found = _assets.find(path); if(found != _assets.end()) return {aid, found->second.task}; // not found => load // clang-format off auto loading = async::spawn([path = std::string(path), aid, this] { return Loader<T>::load(_manager._open(aid, path)); }).share(); // clang-format on if(cache) _assets.try_emplace(path, Asset{aid, loading, _manager._last_modified(path)}); return {aid, loading}; } template <typename T> void Asset_container<T>::save(const AID& aid, const std::string& name, const T& obj) { auto lock = std::scoped_lock{_container_mutex}; Loader<T>::save(_manager._open_rw(aid, name), obj); auto found = _assets.find(name); if(found != _assets.end() && &found.value().task.get() != &obj) { _reload_asset(found.value(), found.key()); // replace existing value } } template <typename T> void Asset_container<T>::shrink_to_fit() noexcept { auto lock = std::scoped_lock{_container_mutex}; util::erase_if(_assets, [](const auto& v) { return v.second.task.refcount() <= 1; }); } template <typename T> void Asset_container<T>::reload() { auto lock = std::scoped_lock{_container_mutex}; for(auto&& entry : _assets) { auto last_mod = _manager._last_modified(entry.first); if(last_mod > entry.second.last_modified) { _reload_asset(const_cast<Asset&>(entry.second), entry.first); } } } // TODO: test if this actually works template <typename T> void Asset_container<T>::_reload_asset(Asset& asset, const std::string& path) { auto& old_value = const_cast<T&>(asset.task.get()); asset.last_modified = _manager._last_modified(path); if constexpr(has_reload_v<T>) { Loader<T>::reload(_manager._open(asset.aid, path), old_value); } else { auto new_value = Loader<T>::load(_manager._open(asset.aid, path)); if constexpr(std::is_same_v<decltype(new_value), async::task<T>>) { old_value = std::move(new_value.get()); } else if constexpr(std::is_same_v<decltype(new_value), async::shared_task<T>>) { old_value = std::move(const_cast<T&>(new_value.get())); } else { old_value = std::move(new_value); } } // TODO: notify other systems about change } } // namespace detail template <typename T> auto Asset_manager::load(const AID& id, bool cache) -> Ptr<T> { auto path = resolve(id); if(path.is_nothing()) throw std::system_error(Asset_error::resolve_failed, id.str()); auto&& container = _find_container<T>(); if(container.is_nothing()) throw std::system_error(Asset_error::stateful_loader_not_initialized, util::type_name<T>()); return container.get_or_throw().load(id, path.get_or_throw(), cache); } template <typename T> auto Asset_manager::load_maybe(const AID& id, bool cache) -> util::maybe<Ptr<T>> { auto path = resolve(id); if(path.is_nothing()) return util::nothing; return _find_container<T>().process([&](detail::Asset_container<T>& container) { return container.load(id, path.get_or_throw(), cache); }); } template <typename T> void Asset_manager::save(const AID& id, const T& asset) { auto path = resolve(id, false); if(path.is_nothing()) throw std::system_error(Asset_error::resolve_failed, id.str()); auto container = _find_container<T>(); if(container.is_nothing()) throw std::system_error(Asset_error::stateful_loader_not_initialized, id.str()); container.get_or_throw().save(id, path.get_or_throw(), asset); } template <typename T> void Asset_manager::save(const Ptr<T>& asset) { save(asset.aid(), *asset); } template <typename T, typename... Args> void Asset_manager::create_stateful_loader(Args&&... args) { auto key = util::type_uid_of<T>(); auto lock = std::scoped_lock{_containers_mutex}; auto container = _containers.find(key); if(container == _containers.end()) { _containers.emplace( key, std::make_unique<detail::Asset_container<T>>(*this, std::forward<Args>(args)...)); } } template <typename T> void Asset_manager::remove_stateful_loader() { auto lock = std::scoped_lock{_containers_mutex}; _containers.erase(util::type_uid_of<T>()); } template <typename T> auto Asset_manager::load_stream(asset::istream stream) -> Ptr<T> { auto container = _find_container<T>(); if(container.is_nothing()) throw std::system_error(Asset_error::stateful_loader_not_initialized, util::type_name<T>()); auto new_value = container.get_or_throw().load(std::move(stream)); if constexpr(std::is_same_v<decltype(new_value), async::task<T>>) return Ptr<T>(stream.aid(), new_value.share()); else if constexpr(std::is_same_v<decltype(new_value), async::shared_task<T>>) return Ptr<T>(stream.aid(), std::move(new_value)); else return Ptr<T>(stream.aid(), async::make_task(std::move(new_value)).share()); } template <typename T> auto Asset_manager::_find_container() -> util::maybe<detail::Asset_container<T>&> { auto key = util::type_uid_of<T>(); auto lock = std::scoped_lock{_containers_mutex}; auto container = _containers.find(key); if(container != _containers.end()) { return util::justPtr(static_cast<detail::Asset_container<T>*>(&*container->second)); } // no container for T, yet if constexpr(std::is_default_constructible_v<Loader<T>>) { container = _containers.emplace(key, std::make_unique<detail::Asset_container<T>>(*this)).first; return util::justPtr(static_cast<detail::Asset_container<T>*>(&*container->second)); } else { return util::nothing; } } } // namespace mirrage::asset
27.384906
103
0.668596
lowkey42
d24aa6ef3cc44a99bd9fb72d93286b63ff625193
2,605
cpp
C++
Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/TestEuropeanOptionPriceCurve.cpp
bondxue/Option-Pricing-Model
5f22df0ff31e90fd536eb216c5af19c697fb87b2
[ "MIT" ]
null
null
null
Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/TestEuropeanOptionPriceCurve.cpp
bondxue/Option-Pricing-Model
5f22df0ff31e90fd536eb216c5af19c697fb87b2
[ "MIT" ]
null
null
null
Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/TestEuropeanOptionPriceCurve.cpp
bondxue/Option-Pricing-Model
5f22df0ff31e90fd536eb216c5af19c697fb87b2
[ "MIT" ]
null
null
null
//TestEuropeanOptionPriceCurve.cpp //purpose: source file to display European Put and Call option prices on one Excel sheet //author: bondxue //version: 1.0 21/01/2017 #include <iostream> #include <cmath> #include <list> #include <string> #include <iostream> #include "EuropeanOption.hpp" #include "Mesher.hpp" #include "ExcelDriverLite.hpp" #include "Utilities.hpp" using namespace std; using namespace OPTION; using namespace OPTION::EUROPEANOPTION; int main() { //// Batch 1 data //double T = 0.25; //double K = 65.0; //double sig = 0.30; //double r = 0.08; //double b = r; // b = r for stock option model //double S = 60.0; //// Batch 2 data //double T = 1.0; //double K = 100.0; //double sig = 0.20; //double r = 0.0; //double b = r; // b = r for stock option model //double S = 100.0; //// Batch 3 data //double T = 1.0; //double K = 10.0; //double sig = 0.50; //double r = 0.12; //double b = r; // b = r for stock option model //double S = 5.0; // Batch 4 data double T = 30.0; double K = 100.0; double sig = 0.30; double r = 0.08; double b = r; // b = r for stock option model double S = 100.0; EuropeanOption Batch(Euro_OptionData(S, K, T, r, sig, b), EuroCall); // create an European call option object double start_S = Batch.S() * 0.5; // set the start value as 0.05 times of stock price of the batch double end_S = start_S * 5.0; // set the end value as 5 times of initial value int num_S = 40; // set the number of stock prices we need vector<double> S_vec = CreateMesh(start_S, end_S, num_S); // create a vector of of monotonically increasing stock prices cout << "stock price vector: " << endl; print(S_vec); // print the stock price vector cout << endl; vector<double> C_vec = Batch.Price_S(S_vec); // create a vector to store a sequence of call prices Batch.Type(EuroPut); // set the option type as European put vector<double> P_vec = Batch.Price_S(S_vec); // create a vector to store a sequence of put prices long N = 40; ExcelDriver xl; xl.MakeVisible(true); xl.CreateChart(S_vec, C_vec, "Call price"); xl.CreateChart(S_vec, P_vec, "Put price"); // C++11 style initializer lists // std::list<std::string> labels{ "Call price", "Put price" }; std::list<std::string> labels; labels.push_back("Call price"); labels.push_back("Put price"); // C++11 style initializer lists // std::list<std::vector<double>> curves{ C_vec, P_vec }; std::list<std::vector<double>> curves; curves.push_back(C_vec); curves.push_back(P_vec); xl.CreateChart(S_vec, labels, curves, "Option Prices", "S", "V"); return 0; }
28.626374
121
0.667946
bondxue
d24d90941574c88a92f21570307214a2bf5acb18
4,903
cpp
C++
path.cpp
Ocisra/file_manager
cfb88aac368a789c1330b5d9fc8c3d0703b60c2b
[ "MIT" ]
null
null
null
path.cpp
Ocisra/file_manager
cfb88aac368a789c1330b5d9fc8c3d0703b60c2b
[ "MIT" ]
null
null
null
path.cpp
Ocisra/file_manager
cfb88aac368a789c1330b5d9fc8c3d0703b60c2b
[ "MIT" ]
null
null
null
#include "path.hpp" #include "config.hpp" #include "miller.hpp" #include <filesystem> #include <set> #include <ncurses.h> #include "libft-detect.hpp" /** * Populate the content of a directory * * @param content: content to populate * @param path: path tracked by the content */ static void populateContent(Content *content, const fs::path &path) { if (fs::is_empty(path)) { content->addVirtual("empty"); return; } for (auto &p : fs::directory_iterator(path)) { Entry *entry = new Entry; entry->path = p.path(); entry->filetype = ft_finder->getFiletype(p.path()); content->entries.emplace(entry); } } Entry::~Entry() { delete filetype; } void Content::addVirtual(std::string text) { Entry *entry = new Entry; entry->filetype = nullptr; entry->isVirtual = true; entry->path = text; entries.emplace(entry); } /** * Get the filetype of the Nth element * * @param n: element of which to find the filetype */ lft::filetype *Content::getFileType(unsigned int n) { return ft_finder->getFiletype(getNthElement(entries, n)->path); } /** * Get the file at a specific line */ Entry *Content::getFileByLine(unsigned int line) { return getNthElement(entries, line); } /** * Get the Nth element of a set * * @param s: set to query * @param n: number of the element */ Entry *Content::getNthElement(std::set<Entry *, decltype(contentSort)> &s, unsigned int n) { typename std::set<Entry *>::iterator it = s.begin(); for (unsigned i = 0; i < n; i++) it++; return *it; } Content::~Content() { for (auto &e : entries) { delete e; } } Path::Path(fs::path start_path) { if (start_path.string().ends_with('/') && start_path.string() != "/") setPath(start_path.parent_path()); else setPath(start_path); setCurrent(new Content); setChild(new Content); populateContent(current(), path()); populateContent(child(), current()->getFileByLine(0)->path); if (path().string() != "/") { setParent(new Content); populateContent(parent(), path().parent_path()); } else setParent(nullptr); } Path::~Path() { if (parent() != nullptr) delete parent(); delete current(); delete child(); } /** * Go up a directory */ bool Path::goUp() { setPath(path().parent_path()); delete child(); setChild(current()); setCurrent(parent()); if (path().string() != "/") { setParent(new Content); populateContent(parent(), path().parent_path()); return true; } else { setParent(nullptr); return false; } } /** * Go down a directory */ void Path::goDown() { setPath(current()->getFileByLine(miller->middle()->line())->path); Content *tmp = parent(); setParent(current()); setCurrent(child()); setChild(new Content); try { // This line is dangerous because the function need access to the content of a // directory we are not sure exists or is readable populateContent(child(), path()); delete tmp; } catch (const fs::filesystem_error &e) { log->debug(e.what()); setPath(path().parent_path()); delete child(); setChild(current()); setCurrent(parent()); setParent(tmp); } } /** * Preview the child directory in the right panel * * @param win: window in which to preview */ void Path::previewChild(Window *win) { wclear(win->win); delete child(); setChild(new Content); auto setWindow = [](Window *win, int sizey, int startx, int starty) { win->sizey = sizey; win->startx = startx; win->starty = starty; wresize(win->win, win->sizey > win->vsizey ? win->sizey : win->vsizey + 1, win->sizex > win->vsizex ? win->sizex : win->vsizex); }; try { if (fs::is_directory(current()->getFileByLine(miller->middle()->line())->path)) { populateContent(child(), current()->getFileByLine(miller->middle()->line())->path); } } catch (const fs::filesystem_error &e) { child()->addVirtual("not accessible"); log->debug(e.what()); } setWindow(win, child()->numOfEntries(), 0, 0); win->display(child()); prefresh(win->win, win->starty, win->startx, win->posy, win->posx, win->vsizey + win->posy, win->vsizex + win->posx); } /** * Find the index of the specified path */ int Path::find(Content *content, fs::path p) { return getIndex(content->entries, p); } /** * Get the index of an element * * @param s: set to query * @param p: element to find */ int Path::getIndex(std::set<Entry *, decltype(contentSort)> &s, fs::path p) { int c = 0; for (auto &e : s) { if (e->path == p) return c; c++; } return -1; }
24.034314
95
0.587599
Ocisra
d25542995768c153bea9ec40493608959bf66467
11,764
hpp
C++
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSail_Parent_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSail_Parent_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSail_Parent_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItem_Spawner_HoverSail_Parent_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass PrimalItem_Spawner_HoverSail_Parent.PrimalItem_Spawner_HoverSail_Parent_C // 0x0180 (0x0E68 - 0x0CE8) class UPrimalItem_Spawner_HoverSail_Parent_C : public UPrimalItem_DinoSpawner_Base_C { public: int NumSpawnAttempts; // 0x0CE8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData00[0x4]; // 0x0CEC(0x0004) MISSED OFFSET class AShooterCharacter* CraftingShooterChar; // 0x0CF0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData01[0x8]; // 0x0CF8(0x0008) MISSED OFFSET struct UObject_FTransform SpawnTransform; // 0x0D00(0x0030) (Edit, BlueprintVisible, DisableEditOnInstance, IsPlainOldData) class FString SkiffSpawnString; // 0x0D30(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) class APrimalDinoCharacter* spawned_dino; // 0x0D40(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData) float allowed_distance_to_despawn_hoversail; // 0x0D48(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool should_have_a_spawned_dino; // 0x0D4C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData) unsigned char UnknownData02[0x3]; // 0x0D4D(0x0003) MISSED OFFSET class FString lost_reference_string; // 0x0D50(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) bool could_find_a_valid_location_next_to_target; // 0x0D60(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData03[0x7]; // 0x0D61(0x0007) MISSED OFFSET class FString usetofollowstring; // 0x0D68(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) class FString use_to_deploy_string; // 0x0D78(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) class FString use_to_put_away_string; // 0x0D88(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) bool show_appropriate_item_description_based_on_state___not_working_on_dedi;// 0x0D98(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool CallFunc_GetDinoColorizationData_HasAnyColorData; // 0x0D99(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData04[0x6]; // 0x0D9A(0x0006) MISSED OFFSET TArray<unsigned char> CallFunc_GetDinoColorizationData_ColorData; // 0x0DA0(0x0010) (ZeroConstructor, Transient, DuplicateTransient) int Temp_int_Variable; // 0x0DB0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char CallFunc_Conv_IntToByte_ReturnValue; // 0x0DB4(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_IsValid_ReturnValue; // 0x0DB5(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char CallFunc_GetValidIndex_ReturnValue; // 0x0DB6(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) TEnumAsByte<ENetworkModeResult> CallFunc_IsRunningOnServer_OutNetworkMode; // 0x0DB7(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) int CallFunc_Conv_ByteToInt_ReturnValue; // 0x0DB8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool K2Node_SwitchEnum_CmpSuccess; // 0x0DBC(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_LessEqual_IntInt_ReturnValue; // 0x0DBD(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData05[0x2]; // 0x0DBE(0x0002) MISSED OFFSET int CallFunc_GetDinoStat_NumDinoLevels; // 0x0DC0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) int CallFunc_GetDinoStat_StatMapIndexUsed; // 0x0DC4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_GetDinoStat_Success; // 0x0DC8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData06[0x3]; // 0x0DC9(0x0003) MISSED OFFSET int CallFunc_Add_IntInt_ReturnValue; // 0x0DCC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) int CallFunc_MakeLiteralInt_ReturnValue; // 0x0DD0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FVector CallFunc_BreakTransform_Location; // 0x0DD4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FRotator CallFunc_BreakTransform_Rotation; // 0x0DE0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FVector CallFunc_BreakTransform_Scale; // 0x0DEC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_Less_IntInt_ReturnValue; // 0x0DF8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData07[0x7]; // 0x0DF9(0x0007) MISSED OFFSET class UWorld* CallFunc_K2_GetWorld_ReturnValue; // 0x0E00(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class AController* CallFunc_GetCharacterController_ReturnValue; // 0x0E08(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class AShooterPlayerController* K2Node_DynamicCast_AsShooterPlayerController; // 0x0E10(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool K2Node_DynamicCast_CastSuccess; // 0x0E18(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData08[0x7]; // 0x0E19(0x0007) MISSED OFFSET class AActor* CallFunc_GetOwner_ReturnValue; // 0x0E20(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class APrimalDinoCharacter* CallFunc_SpawnCustomDino_ReturnValue; // 0x0E28(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class AGameState* CallFunc_GetGameState_ReturnValue; // 0x0E30(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FVector CallFunc_K2_GetActorLocation_ReturnValue; // 0x0E38(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_IsValid_ReturnValue2; // 0x0E44(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData09[0x3]; // 0x0E45(0x0003) MISSED OFFSET struct FVector CallFunc_FindValidLocationNextToTarget_OutLocation; // 0x0E48(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_FindValidLocationNextToTarget_ReturnValue; // 0x0E54(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_K2_SetActorLocation_ReturnValue; // 0x0E55(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData10[0x2]; // 0x0E56(0x0002) MISSED OFFSET float CallFunc_RandomFloatInRange_ReturnValue; // 0x0E58(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FRotator CallFunc_MakeRot_ReturnValue; // 0x0E5C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItem_Spawner_HoverSail_Parent.PrimalItem_Spawner_HoverSail_Parent_C"); return ptr; } class FString BPGetItemDescription(class FString* InDescription, bool* bGetLongDescription, class AShooterPlayerController** ForPC); void notify_hoversail_destroyed(); void Delaymount(); bool BPCanUse(bool* bIgnoreCooldown); void SpawnCraftedSkiff(); void ExecuteUbergraph_PrimalItem_Spawner_HoverSail_Parent(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
116.475248
231
0.562734
2bite
d259620e891f8515d136f8a63fab93fdf75ca5c7
902
cpp
C++
NativeLibrary/WriteStream.cpp
Const-me/ComLightInterop
3968aee5e1b61c71cb70245c93a1b05f00df2cb8
[ "MIT" ]
22
2019-08-27T13:59:26.000Z
2022-02-18T07:40:36.000Z
NativeLibrary/WriteStream.cpp
Const-me/ComLightInterop
3968aee5e1b61c71cb70245c93a1b05f00df2cb8
[ "MIT" ]
2
2021-04-14T13:07:48.000Z
2021-10-16T16:32:20.000Z
NativeLibrary/WriteStream.cpp
Const-me/ComLightInterop
3968aee5e1b61c71cb70245c93a1b05f00df2cb8
[ "MIT" ]
2
2019-10-10T00:14:08.000Z
2022-02-03T03:42:36.000Z
#include "stdafx.h" #include "WriteStream.h" HRESULT WriteStream::write( const void* lpBuffer, int nNumberOfBytesToWrite ) { if( nullptr == m_file ) return OLE_E_BLANK; if( nNumberOfBytesToWrite < 0 ) return E_INVALIDARG; const size_t cb = (size_t)nNumberOfBytesToWrite; const size_t written = fwrite( lpBuffer, 1, cb, m_file ); if( cb == written ) return S_OK; return CTL_E_DEVICEIOERROR; } HRESULT WriteStream::flush() { if( nullptr == m_file ) return OLE_E_BLANK; if( 0 == fflush( m_file ) ) return S_OK; return CTL_E_DEVICEIOERROR; } HRESULT WriteStream::createFile( LPCTSTR path ) { if( nullptr != m_file ) { fclose( m_file ); m_file = nullptr; } #ifdef _MSC_VER const auto e = _wfopen_s( &m_file, path, L"wb" ); return ( 0 == e ) ? S_OK : CTL_E_DEVICEIOERROR; #else m_file = fopen( path, "wb" ); return ( nullptr != m_file ) ? S_OK : CTL_E_DEVICEIOERROR; #endif }
22.55
77
0.694013
Const-me
d25c22d9c0902ad11ab22ba6494471bb44d17a26
1,077
cpp
C++
src/quiz/quiz01a.cpp
msu-csc232-fa20/lectures
194a93cef456e29099c99147fbb1f645df07fc69
[ "MIT" ]
null
null
null
src/quiz/quiz01a.cpp
msu-csc232-fa20/lectures
194a93cef456e29099c99147fbb1f645df07fc69
[ "MIT" ]
null
null
null
src/quiz/quiz01a.cpp
msu-csc232-fa20/lectures
194a93cef456e29099c99147fbb1f645df07fc69
[ "MIT" ]
null
null
null
/** * CSC232 - Data Structures * Missouri State University, Fall 2020 * * Quiz 1 * * @author Jim Daehn <jdaehn@missouristate.edu> * @file quiz01.cpp */ #include <cstdlib> #include <iostream> #define FALSE 0 #define TRUE 1 #define USE_CODE_ON_QUIZ TRUE #define USE_ANSWER FALSE int main() { // These were the assumptions listed in Question 1 const int ARRAY_SIZE = 4; int i; int n; int data[ARRAY_SIZE]; #if USE_CODE_ON_QUIZ // To reveal the answer to Question 1, we repeat the code // in Question 2 here... for (i = 0, n = 4; i < n; ++i) { std::cout << "Enter data[" << i << "]: "; std::cin >> data[i]; } #endif // the following macro-guard is not part of the answer; it's // just here prevent this code from executing #if USE_ANSWER // an equivalent while loop is shown below (Question 2) i = 0; n = 4; while (i < n) { std::cout << "Enter data[" << i << "]: "; std::cin >> data[i]; ++i; } #endif // And now we're done return EXIT_SUCCESS; }
18.568966
61
0.581244
msu-csc232-fa20
d25f7144b9c0a7df5bf6730782097d00adeb27ee
779
cpp
C++
TabGraph/src/Common.cpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
1
2020-08-28T09:35:18.000Z
2020-08-28T09:35:18.000Z
TabGraph/src/Common.cpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
null
null
null
TabGraph/src/Common.cpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
1
2020-10-08T11:21:13.000Z
2020-10-08T11:21:13.000Z
/* * @Author: gpinchon * @Date: 2020-08-27 18:48:19 * @Last Modified by: gpinchon * @Last Modified time: 2021-01-11 08:42:39 */ #include "Common.hpp" #include <glm/vec3.hpp> static glm::vec3 s_up(0, 1, 0); static glm::vec3 s_forward(0, 0, -1); static glm::vec3 s_right(1, 0, 0); static glm::vec3 s_gravity(0, -9.81, 0); glm::vec3 Common::Up() { return s_up; } void Common::SetUp(glm::vec3 up) { s_up = up; } glm::vec3 Common::Forward() { return s_forward; } void Common::SetForward(glm::vec3 up) { s_forward = up; } glm::vec3 Common::Right() { return s_right; } void Common::SetRight(glm::vec3 up) { s_right = up; } glm::vec3 Common::Gravity() { return s_gravity; } void Common::SetGravity(glm::vec3 gravity) { s_gravity = gravity; }
14.425926
42
0.634146
Gpinchon
d921e987a4979cd17b7dbbe1bed47efc0f2d1827
9,434
cc
C++
src/Scanner.cc
avartak/KAZM
4b08bf47bf5412f435eb7b129f4aa6eeddb31a42
[ "MIT" ]
null
null
null
src/Scanner.cc
avartak/KAZM
4b08bf47bf5412f435eb7b129f4aa6eeddb31a42
[ "MIT" ]
null
null
null
src/Scanner.cc
avartak/KAZM
4b08bf47bf5412f435eb7b129f4aa6eeddb31a42
[ "MIT" ]
null
null
null
// src/Scanner.cc generated by reflex 2.1.5 from src/lexer.l #define REFLEX_VERSION "2.1.5" //////////////////////////////////////////////////////////////////////////////// // // // OPTIONS USED // // // //////////////////////////////////////////////////////////////////////////////// #define REFLEX_OPTION_header_file "include/Scanner.h" #define REFLEX_OPTION_lex scan #define REFLEX_OPTION_lexer Scanner #define REFLEX_OPTION_namespace kazm #define REFLEX_OPTION_noline true #define REFLEX_OPTION_outfile "src/Scanner.cc" #define REFLEX_OPTION_token_type kazm::Token //////////////////////////////////////////////////////////////////////////////// // // // SECTION 1: %top user code // // // //////////////////////////////////////////////////////////////////////////////// #include <Token.h> //////////////////////////////////////////////////////////////////////////////// // // // REGEX MATCHER // // // //////////////////////////////////////////////////////////////////////////////// #include <reflex/matcher.h> //////////////////////////////////////////////////////////////////////////////// // // // ABSTRACT LEXER CLASS // // // //////////////////////////////////////////////////////////////////////////////// #include <reflex/abslexer.h> //////////////////////////////////////////////////////////////////////////////// // // // LEXER CLASS // // // //////////////////////////////////////////////////////////////////////////////// namespace kazm { class Scanner : public reflex::AbstractLexer<reflex::Matcher> { public: typedef reflex::AbstractLexer<reflex::Matcher> AbstractBaseLexer; Scanner( const reflex::Input& input = reflex::Input(), std::ostream& os = std::cout) : AbstractBaseLexer(input, os) { } static const int INITIAL = 0; virtual kazm::Token scan(void); kazm::Token scan(const reflex::Input& input) { in(input); return scan(); } kazm::Token scan(const reflex::Input& input, std::ostream *os) { in(input); if (os) out(*os); return scan(); } }; } // namespace kazm //////////////////////////////////////////////////////////////////////////////// // // // SECTION 1: %{ user code %} // // // //////////////////////////////////////////////////////////////////////////////// #include <iostream> #define RETURN(x) return Token(x, str(), lineno()) //////////////////////////////////////////////////////////////////////////////// // // // SECTION 2: rules // // // //////////////////////////////////////////////////////////////////////////////// kazm::Token kazm::Scanner::scan(void) { static const char *REGEX_INITIAL = "(?m)((?:[\\x09-\\x0d\\x20])+)|((?:\\Q//\\E).*)|((?:\\QOPENQASM\\E)(?:[\\x09\\x20])+(?:(?:(?:\\Q0\\E)|[1-9]+(?:[0-9])*))(?:\\Q.\\E)(?:(?:(?:\\Q0\\E)|[1-9]+(?:[0-9])*))(?:[\\x09\\x20])*(?:\\Q;\\E))|((?:\\Q{\\E))|((?:\\Q}\\E))|((?:\\Q[\\E))|((?:\\Q]\\E))|((?:\\Q(\\E))|((?:\\Q)\\E))|((?:\\Q,\\E))|((?:\\Q;\\E))|((?:\\Q+\\E))|((?:\\Q-\\E))|((?:\\Q*\\E))|((?:\\Q/\\E))|((?:\\Q^\\E))|((?:\\Q->\\E))|((?:\\Q==\\E))|((?:\\Qif\\E))|((?:\\Qpi\\E))|((?:\\Qsin\\E))|((?:\\Qcos\\E))|((?:\\Qtan\\E))|((?:\\Qexp\\E))|((?:\\Qln\\E))|((?:\\Qsqrt\\E))|((?:\\Qqreg\\E))|((?:\\Qcreg\\E))|((?:\\Qgate\\E))|((?:\\Qopaque\\E))|((?:\\Qbarrier\\E))|((?:\\Qmeasure\\E))|((?:\\Qreset\\E))|((?:\\QU\\E))|((?:\\QCX\\E))|((?:\\Qinclude\\E))|((?:(?:(?:\\Q0\\E)|[1-9]+(?:[0-9])*)))|((?:[0-9])+(?:(?:[Ee][\\x2b\\x2d]?(?:[0-9])+)))|((?:[0-9])+(?:\\Q.\\E)(?:[0-9])*(?:(?:[Ee][\\x2b\\x2d]?(?:[0-9])+))?)|((?:[0-9])*(?:\\Q.\\E)(?:[0-9])+(?:(?:[Ee][\\x2b\\x2d]?(?:[0-9])+))?)|([a-z][0-9A-Z_a-z]*)|(\"[^\"]+\")|(.)"; static const reflex::Pattern PATTERN_INITIAL(REGEX_INITIAL); if (!has_matcher()) { matcher(new Matcher(PATTERN_INITIAL, stdinit(), this)); } while (true) { switch (matcher().scan()) { case 0: if (matcher().at_end()) { { RETURN(0); } } else { out().put(matcher().input()); } break; case 1: // rule src/lexer.l:21: {W}+ : break; case 2: // rule src/lexer.l:22: "//".* : break; case 3: // rule src/lexer.l:24: "OPENQASM"{S}+{I}"."{I}{S}*";" : { RETURN(T_HEADER); } break; case 4: // rule src/lexer.l:26: "{" : { RETURN('{'); } break; case 5: // rule src/lexer.l:27: "}" : { RETURN('}'); } break; case 6: // rule src/lexer.l:28: "[" : { RETURN('['); } break; case 7: // rule src/lexer.l:29: "]" : { RETURN(']'); } break; case 8: // rule src/lexer.l:30: "(" : { RETURN('('); } break; case 9: // rule src/lexer.l:31: ")" : { RETURN(')'); } break; case 10: // rule src/lexer.l:32: "," : { RETURN(','); } break; case 11: // rule src/lexer.l:33: ";" : { RETURN(';'); } break; case 12: // rule src/lexer.l:34: "+" : { RETURN('+'); } break; case 13: // rule src/lexer.l:35: "-" : { RETURN('-'); } break; case 14: // rule src/lexer.l:36: "*" : { RETURN('*'); } break; case 15: // rule src/lexer.l:37: "/" : { RETURN('/'); } break; case 16: // rule src/lexer.l:38: "^" : { RETURN('^'); } break; case 17: // rule src/lexer.l:39: "->" : { RETURN(T_YIELDS); } break; case 18: // rule src/lexer.l:40: "==" : { RETURN(T_EQUALS); } break; case 19: // rule src/lexer.l:41: "if" : { RETURN(T_IF); } break; case 20: // rule src/lexer.l:42: "pi" : { RETURN(T_PI); } break; case 21: // rule src/lexer.l:43: "sin" : { RETURN(T_SIN); } break; case 22: // rule src/lexer.l:44: "cos" : { RETURN(T_COS); } break; case 23: // rule src/lexer.l:45: "tan" : { RETURN(T_TAN); } break; case 24: // rule src/lexer.l:46: "exp" : { RETURN(T_EXP); } break; case 25: // rule src/lexer.l:47: "ln" : { RETURN(T_LN); } break; case 26: // rule src/lexer.l:48: "sqrt" : { RETURN(T_SQRT); } break; case 27: // rule src/lexer.l:49: "qreg" : { RETURN(T_QREG); } break; case 28: // rule src/lexer.l:50: "creg" : { RETURN(T_CREG); } break; case 29: // rule src/lexer.l:51: "gate" : { RETURN(T_GATE); } break; case 30: // rule src/lexer.l:52: "opaque" : { RETURN(T_OPAQUE); } break; case 31: // rule src/lexer.l:53: "barrier" : { RETURN(T_BARRIER); } break; case 32: // rule src/lexer.l:54: "measure" : { RETURN(T_MEASURE); } break; case 33: // rule src/lexer.l:55: "reset" : { RETURN(T_RESET); } break; case 34: // rule src/lexer.l:56: "U" : { RETURN(T_U); } break; case 35: // rule src/lexer.l:57: "CX" : { RETURN(T_CX); } break; case 36: // rule src/lexer.l:58: "include" : { RETURN(T_INCLUDE); } break; case 37: // rule src/lexer.l:60: {I} : { RETURN(T_NNINTEGER); } break; case 38: // rule src/lexer.l:61: {D}+{E} : { RETURN(T_REAL); } break; case 39: // rule src/lexer.l:62: {D}+"."{D}*{E}? : { RETURN(T_REAL); } break; case 40: // rule src/lexer.l:63: {D}*"."{D}+{E}? : { RETURN(T_REAL); } break; case 41: // rule src/lexer.l:64: [a-z][a-zA-Z_0-9]* : { RETURN(T_ID); } break; case 42: // rule src/lexer.l:65: \"[^\"]+\" : { RETURN(T_FILENAME); } break; case 43: // rule src/lexer.l:67: . : { RETURN(T_UNDEF); } break; } } }
36.42471
1,015
0.321391
avartak
d928f48d649ebe372fe54378d0f88e54c952de03
576
cpp
C++
ABC/ABC247/A/abc247-a.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
ABC/ABC247/A/abc247-a.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
ABC/ABC247/A/abc247-a.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
/** * @file abc247-a.cpp * @brief ABC247 Problem A - Move Right * @author Keitaro Naruse * @date 2022-04-10 * @copyright MIT License * @details https://atcoder.jp/contests/abc247/tasks/abc247_a */ // # Solution #include <iostream> #include <string> int main() { // Read | S | = [ 1, 10^6 ] std::string S; std::cin >> S; // Main const int N = 4; std::string T( N, ' ' ); T.at( 0 ) = '0'; T.at( 1 ) = S.at( 0 ); T.at( 2 ) = S.at( 1 ); T.at( 3 ) = S.at( 2 ); std::cout << T << std::endl; // Finalize return( 0 ); }
17.454545
60
0.508681
keitaronaruse
d92a44e01d39b0743eb29ac2627ba0403bbe3358
1,155
cpp
C++
NPSVisor/tools/svMaker/source/pObject/svmHistory.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/tools/svMaker/source/pObject/svmHistory.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/tools/svMaker/source/pObject/svmHistory.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
//-------------------- svmHistory.cpp -------------------------- //----------------------------------------------------------- #include "precHeader.h" //----------------------------------------------------------- #include "svmHistory.h" #include "svmObject.h" //----------------------------------------------------------- static PRect getObjRect(svmBaseObject* obj) { svmObject* o = dynamic_cast<svmObject*>(obj); if(o) return o->getRect(); return PRect(); } //----------------------------------------------------------- static int getObjId(svmBaseObject* obj) { svmObject* o = dynamic_cast<svmObject*>(obj); if(o) return o->getId(); return 0; } //----------------------------------------------------------- svmObjHistory::svmObjHistory(svmBaseObject* obj, svmObjHistory::typeOfAction action, svmBaseObject* prev) : Curr(obj), Action(action), Prev(prev), Rect(getObjRect(obj)), Id(getObjId(obj)), Next(0), Cloned(0) {} //----------------------------------------------------------- svmObjHistory::~svmObjHistory() { if(Group != Action) delete Cloned; } //-----------------------------------------------------------
35
84
0.401732
NPaolini
d92ca35877a6024fce9849069d63a77850dcb12c
11,476
cpp
C++
Arch(C&C++)/eb189527d6ecb920cd6dc02651c9af01/DevconCmd.cpp
bhbk/3as8kpsf
7da56a0f125c59104bc80950792c1c904b2a12f1
[ "Apache-2.0" ]
1
2019-01-12T15:30:46.000Z
2019-01-12T15:30:46.000Z
Arch(C&C++)/eb189527d6ecb920cd6dc02651c9af01/DevconCmd.cpp
bhbk/3as8kpsf
7da56a0f125c59104bc80950792c1c904b2a12f1
[ "Apache-2.0" ]
null
null
null
Arch(C&C++)/eb189527d6ecb920cd6dc02651c9af01/DevconCmd.cpp
bhbk/3as8kpsf
7da56a0f125c59104bc80950792c1c904b2a12f1
[ "Apache-2.0" ]
null
null
null
#include "Devcon.h" #include "DevconDump.h" #include "DevconDumpMsg.h" #include "DevconCmd.h" int CmdClassDeviceList(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[], LPTSTR* rslts[]) /*++ Routine Description: LISTCLASS <name>.... lists all devices for each specified class there can be more than one physical class for a class name (shouldn't be though) in such cases, list each class if machine given, list devices for that machine Arguments: BaseName - name of executable Machine - if non-NULL, remote machine argc/argv - remaining parameters - list of class names Return Value: EXIT_xxxx --*/ { BOOL classListed = FALSE; BOOL devListed = FALSE; DWORD reqGuids = 16; int argIndex; int failcode = EXIT_FAIL; LPGUID guids = NULL; HDEVINFO devs = INVALID_HANDLE_VALUE; if(!argc) { return EXIT_USAGE; } guids = new GUID[reqGuids]; if(!guids) { goto final; } for(argIndex = 0; argIndex < argc; argIndex++) { DWORD numGuids; DWORD index; if(!(argv[argIndex] && argv[argIndex][0])) { continue; } // there could be one to many name to GUID mapping while(!SetupDiClassGuidsFromNameEx(argv[argIndex],guids,reqGuids,&numGuids,Machine,NULL)) { if(GetLastError() != ERROR_INSUFFICIENT_BUFFER) { goto final; } delete [] guids; reqGuids = numGuids; guids = new GUID[reqGuids]; if(!guids) { goto final; } } if(numGuids == 0) { FormatToStream(stdout,Machine?MSG_LISTCLASS_NOCLASS:MSG_LISTCLASS_NOCLASS_LOCAL,argv[argIndex],Machine); continue; } for(index = 0; index < numGuids; index++) { TCHAR className[MAX_CLASS_NAME_LEN]; TCHAR classDesc[LINE_LEN]; DWORD devCount = 0; SP_DEVINFO_DATA devInfo; DWORD devIndex; devs = SetupDiGetClassDevsEx(&guids[index],NULL,NULL,DIGCF_PRESENT,NULL,Machine,NULL); if(devs != INVALID_HANDLE_VALUE) { // count number of devices devInfo.cbSize = sizeof(devInfo); while(SetupDiEnumDeviceInfo(devs, devCount, &devInfo)) { devCount++; } } if(!SetupDiClassNameFromGuidEx(&guids[index], className, MAX_CLASS_NAME_LEN, NULL, Machine, NULL)) { lstrcpyn(className,TEXT("?"),MAX_CLASS_NAME_LEN); } if(!SetupDiGetClassDescriptionEx(&guids[index], classDesc, LINE_LEN, NULL, Machine, NULL)) { lstrcpyn(classDesc,className,LINE_LEN); } // how many devices? if (!devCount) { FormatToStream(stdout,Machine?MSG_LISTCLASS_HEADER_NONE:MSG_LISTCLASS_HEADER_NONE_LOCAL,className,classDesc,Machine); } else { FormatToStream(stdout,Machine?MSG_LISTCLASS_HEADER:MSG_LISTCLASS_HEADER_LOCAL,devCount,className,classDesc,Machine); for(devIndex = 0; SetupDiEnumDeviceInfo(devs, devIndex, &devInfo); devIndex++) { rslts[devIndex] = (LPTSTR*)GetDeviceWithInfo(devs, &devInfo); // DumpDevice(devs, &devInfo); } } if(devs != INVALID_HANDLE_VALUE) { SetupDiDestroyDeviceInfoList(devs); devs = INVALID_HANDLE_VALUE; } } } failcode = 0; final: if(guids) { delete [] guids; } if(devs != INVALID_HANDLE_VALUE) { SetupDiDestroyDeviceInfoList(devs); } return failcode; } int CmdClasses(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[], LPTSTR* rslts[]) /*++ Routine Description: CLASSES command lists classes on (optionally) specified machine format as <name>: <destination> Arguments: BaseName - name of executable Machine - if non-NULL, remote machine argc/argv - remaining parameters - ignored Return Value: EXIT_xxxx --*/ { DWORD reqGuids = 128; DWORD numGuids; LPGUID guids = NULL; DWORD index; int failcode = EXIT_FAIL; guids = new GUID[reqGuids]; if(!guids) { goto final; } if(!SetupDiBuildClassInfoListEx(0, guids, reqGuids, &numGuids, Machine, NULL)) { do { if(GetLastError() != ERROR_INSUFFICIENT_BUFFER) { goto final; } delete [] guids; reqGuids = numGuids; guids = new GUID[reqGuids]; if(!guids) { goto final; } } while(!SetupDiBuildClassInfoListEx(0, guids, reqGuids, &numGuids, Machine, NULL)); } FormatToStream(stdout,Machine?MSG_CLASSES_HEADER:MSG_CLASSES_HEADER_LOCAL,numGuids,Machine); for(index = 0; index < numGuids; index++) { TCHAR className[MAX_CLASS_NAME_LEN]; TCHAR classDesc[LINE_LEN]; if(!SetupDiClassNameFromGuidEx(&guids[index], className, MAX_CLASS_NAME_LEN, NULL, Machine, NULL)) { lstrcpyn(className,TEXT("?"),MAX_CLASS_NAME_LEN); } if(!SetupDiGetClassDescriptionEx(&guids[index], classDesc, LINE_LEN, NULL, Machine, NULL)) { lstrcpyn(classDesc,className,LINE_LEN); } _tprintf(TEXT("%-20s: %s\n"), className, classDesc); } failcode = EXIT_OK; final: if(guids) { delete [] guids; } return failcode; } int CmdDeviceEnable(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[]) /*++ Routine Description: ENABLE <id> ... use EnumerateDevices to do hardwareID matching for each match, attempt to enable global, and if needed, config specific Arguments: BaseName - name of executable Machine - must be NULL (local machine only) argc/argv - remaining parameters - passed into EnumerateDevices Return Value: EXIT_xxxx (EXIT_REBOOT if reboot is required) --*/ { GenericContext context; TCHAR strEnable[80]; TCHAR strReboot[80]; TCHAR strFail[80]; int failcode = EXIT_FAIL; if(!argc) { // arguments required return EXIT_USAGE; } if(Machine) { // must be local machine as we need to involve class/co installers return EXIT_USAGE; } /* if(!LoadString(NULL,IDS_ENABLED,strEnable,ARRAYSIZE(strEnable))) { return EXIT_FAIL; } if(!LoadString(NULL,IDS_ENABLED_REBOOT,strReboot,ARRAYSIZE(strReboot))) { return EXIT_FAIL; } if(!LoadString(NULL,IDS_ENABLE_FAILED,strFail,ARRAYSIZE(strFail))) { return EXIT_FAIL; } */ context.control = DICS_ENABLE; // DICS_PROPCHANGE DICS_ENABLE DICS_DISABLE context.reboot = FALSE; context.count = 0; context.strReboot = strReboot; context.strSuccess = strEnable; context.strFail = strFail; failcode = EnumerateDevices(BaseName,Machine,DIGCF_PRESENT,argc,argv,ControlCallback,&context); if(failcode == EXIT_OK) { if(!context.count) { FormatToStream(stdout,MSG_ENABLE_TAIL_NONE); } else if(!context.reboot) { FormatToStream(stdout,MSG_ENABLE_TAIL,context.count); } else { FormatToStream(stdout,MSG_ENABLE_TAIL_REBOOT,context.count); failcode = EXIT_REBOOT; } } return failcode; } int CmdDeviceDisable(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[]) /*++ Routine Description: DISABLE <id> ... use EnumerateDevices to do hardwareID matching for each match, attempt to disable global Arguments: BaseName - name of executable Machine - must be NULL (local machine only) argc/argv - remaining parameters - passed into EnumerateDevices Return Value: EXIT_xxxx (EXIT_REBOOT if reboot is required) --*/ { GenericContext context; TCHAR strDisable[80]; TCHAR strReboot[80]; TCHAR strFail[80]; int failcode = EXIT_FAIL; // UNREFERENCED_PARAMETER(Flags); if(!argc) { // arguments required return EXIT_USAGE; } if(Machine) { // must be local machine as we need to involve class/co installers return EXIT_USAGE; } /* if(!LoadString(NULL,IDS_DISABLED,strDisable,ARRAYSIZE(strDisable))) { return EXIT_FAIL; } if(!LoadString(NULL,IDS_DISABLED_REBOOT,strReboot,ARRAYSIZE(strReboot))) { return EXIT_FAIL; } if(!LoadString(NULL,IDS_DISABLE_FAILED,strFail,ARRAYSIZE(strFail))) { return EXIT_FAIL; } */ context.control = DICS_DISABLE; // DICS_PROPCHANGE DICS_ENABLE DICS_DISABLE context.reboot = FALSE; context.count = 0; context.strReboot = strReboot; context.strSuccess = strDisable; context.strFail = strFail; failcode = EnumerateDevices(BaseName,Machine,DIGCF_PRESENT,argc,argv,ControlCallback,&context); if(failcode == EXIT_OK) { if(!context.count) { FormatToStream(stdout,MSG_DISABLE_TAIL_NONE); } else if(!context.reboot) { FormatToStream(stdout,MSG_DISABLE_TAIL,context.count); } else { FormatToStream(stdout,MSG_DISABLE_TAIL_REBOOT,context.count); failcode = EXIT_REBOOT; } } return failcode; } int CmdDeviceStatus(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[]) /*++ Routine Description: STATUS <id> ... use EnumerateDevices to do hardwareID matching for each match, dump status to stdout note that we only enumerate present devices Arguments: BaseName - name of executable Machine - if non-NULL, remote machine argc/argv - remaining parameters - passed into EnumerateDevices Return Value: EXIT_xxxx --*/ { GenericContext context; int failcode; if(!argc) { return EXIT_USAGE; } context.count = 0; context.control = FIND_DEVICE | FIND_STATUS; failcode = EnumerateDevices(BaseName,Machine,DIGCF_PRESENT,argc,argv,FindCallback,&context); if(failcode == EXIT_OK) { if(!context.count) { FormatToStream(stdout,Machine?MSG_FIND_TAIL_NONE:MSG_FIND_TAIL_NONE_LOCAL,Machine); } else { FormatToStream(stdout,Machine?MSG_FIND_TAIL:MSG_FIND_TAIL_LOCAL,context.count,Machine); } } return failcode; } int CmdFind(LPCTSTR BaseName, LPCTSTR Machine, int argc, TCHAR* argv[], LPTSTR* rslts[]) /*++ Routine Description: FIND <id> ... use EnumerateDevices to do hardwareID matching for each match, dump to stdout note that we only enumerate present devices Arguments: BaseName - name of executable Machine - if non-NULL, remote machine argc/argv - remaining parameters - passed into EnumerateDevices Return Value: EXIT_xxxx --*/ { GenericContext context; int failcode; if(!argc) { return EXIT_USAGE; } context.count = 0; context.control = 0; failcode = EnumerateDevices(BaseName, Machine, DIGCF_PRESENT, argc, argv, FindCallback, &context); if(failcode == EXIT_OK) { if(!context.count) { FormatToStream(stdout,Machine?MSG_FIND_TAIL_NONE:MSG_FIND_TAIL_NONE_LOCAL,Machine); } else { FormatToStream(stdout,Machine?MSG_FIND_TAIL:MSG_FIND_TAIL_LOCAL,context.count,Machine); } } return failcode; }
28.834171
133
0.629313
bhbk
d92ef2f2876440f6b057ff0051e235de10df37d9
6,724
cpp
C++
src/renderer.cpp
baines/engine
d26339c780e4c9accec0ed7a60d2c3bcc33171d3
[ "WTFPL" ]
4
2015-03-04T19:22:55.000Z
2020-01-06T02:31:48.000Z
src/renderer.cpp
baines/engine
d26339c780e4c9accec0ed7a60d2c3bcc33171d3
[ "WTFPL" ]
null
null
null
src/renderer.cpp
baines/engine
d26339c780e4c9accec0ed7a60d2c3bcc33171d3
[ "WTFPL" ]
null
null
null
#include "renderer.h" #include "engine.h" #include "enums.h" #include "config.h" #include "cli.h" #include "texture.h" #include "sampler.h" #include <math.h> #include <climits> #define GLM_FORCE_RADIANS #include <glm/gtc/matrix_transform.hpp> Renderer::Renderer(Engine& e, const char* name) : renderables () , render_state () , gl_debug (e.cfg->addVar<CVarBool> ("gl_debug", true)) , gl_fwd_compat (e.cfg->addVar<CVarBool> ("gl_fwd_compat", true)) , gl_core_profile (e.cfg->addVar<CVarBool> ("gl_core_profile", true)) , libgl (e.cfg->addVar<CVarString> ("gl_library", "")) , window_width (e.cfg->addVar<CVarInt> ("vid_width" , 640, 320, INT_MAX)) , window_height (e.cfg->addVar<CVarInt> ("vid_height", 480, 240, INT_MAX)) , vsync (e.cfg->addVar<CVarInt> ("vid_vsync", 1, -2, 2)) , fov (e.cfg->addVar<CVarInt> ("vid_fov", 90, 45, 135)) , display_index (e.cfg->addVar<CVarInt> ("vid_display_index", 0, 0, 100)) , fullscreen (e.cfg->addVar<CVarBool> ("vid_fullscreen", false)) , resizable (e.cfg->addVar<CVarBool> ("vid_resizable", true)) , window_title (name) , window (nullptr) , main_uniforms () , window_w (window_width->val) , window_h (window_height->val) { SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); if(SDL_InitSubSystem(SDL_INIT_VIDEO) != 0){ log(logging::fatal, "Couldn't initialize SDL video subsystem (%s).", SDL_GetError()); } e.cfg->addVar<CVarFunc>("vid_reload", [&](const alt::StrRef&){ reload(e); return true; }); std::initializer_list<CVar*> reload_vars = { gl_debug, gl_fwd_compat, gl_core_profile, libgl, window_width, window_height, vsync, fov, display_index, fullscreen, resizable }; for(auto* v : reload_vars){ v->setReloadVar("vid_reload"); } e.cfg->addVar<CVarFunc>("vid_display_info", [&](const alt::StrRef&){ char buf[80] = {}; SDL_Rect r; e.cli->echo("Displays:"); int num_disp = SDL_GetNumVideoDisplays(); for(int i = 0; i < num_disp; ++i){ SDL_GetDisplayBounds(i, &r); const char* name = SDL_GetDisplayName(i); snprintf(buf, sizeof(buf), " %d: [%dx%d+%d+%d] '%s'", i, r.w, r.h, r.x, r.y, name ? name : "(no name)" ); e.cli->echo(reinterpret_cast<const char*>(buf)); } return true; }, "Show info about available displays / monitors"); reload(e); } void Renderer::reload(Engine& e){ //TODO: check if we can get away with just using SDL_SetWindow{Size, Position} e.t.c. // instead of destroying the window & GL context. gl.deleteContext(); if(window){ SDL_DestroyWindow(window); window = nullptr; } SDL_GL_UnloadLibrary(); if(SDL_GL_LoadLibrary(libgl->str.empty() ? nullptr : libgl->str.c_str()) < 0){ log(logging::fatal, "Couldn't load OpenGL library! (%s).", SDL_GetError()); } render_state = {}; SDL_GL_SetAttribute(SDL_GL_RED_SIZE , 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE , 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE , 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE , 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER , 1); constexpr struct glversion { int maj, min; } ctx_versions[] = { { 4, 5 }, { 4, 4 }, { 4, 3 }, { 4, 2 }, { 4, 1 }, { 4, 0 }, { 3, 3 }, { 3, 2 }, { 3, 1 }, { 3, 0 }, { 2, 1 }, { 2, 0 } }; bool created = false; for(auto& v : ctx_versions){ #ifndef __EMSCRIPTEN__ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, v.maj); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, v.min); if(gl_core_profile->val && v.maj >= 3){ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); } else { SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); } int ctx_flags = 0; if(gl_debug->val){ ctx_flags |= SDL_GL_CONTEXT_DEBUG_FLAG; } if(gl_fwd_compat->val && v.maj >= 3){ ctx_flags |= SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, ctx_flags); #endif int window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN; if(fullscreen->val){ window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; } if(resizable->val){ window_flags |= SDL_WINDOW_RESIZABLE; } display_index->val = std::min(display_index->val, SDL_GetNumVideoDisplays()-1); window = SDL_CreateWindow( window_title, SDL_WINDOWPOS_CENTERED_DISPLAY(display_index->val), SDL_WINDOWPOS_CENTERED_DISPLAY(display_index->val), window_width->val, window_height->val, window_flags ); if((created = gl.createContext(e, window))){ break; } else { if(window) SDL_DestroyWindow(window); } } if(!created){ log(logging::fatal, "Couldn't get an OpenGL context of any version!"); } SDL_SetWindowMinimumSize(window, window_width->min, window_height->min); SDL_ShowWindow(window); gl.Enable(GL_BLEND); SDL_GL_SetSwapInterval(vsync->val); handleResize(window_width->val, window_height->val); } void Renderer::handleResize(float w, float h){ window_width->val = w; window_height->val = h; if(gl.initialized()){ gl.Viewport(0, 0, w, h); main_uniforms.setUniform("u_ortho", { glm::ortho(0.f, w, h, 0.f) }); const float half_angle = (fov->val / 360.f) * M_PI; const float x_dist = tan(half_angle); const float y_dist = x_dist * (h/w); main_uniforms.setUniform("u_perspective", { glm::frustum(-x_dist, x_dist, -y_dist, y_dist, 1.0f, 1000.0f) }); } } void Renderer::drawFrame(){ gl.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); for(auto i = renderables.begin(), j = renderables.end(); i != j; ++i){ auto* r = *i; VertexState* v = r->vertex_state; if(!v) continue; r->blend_mode.bind(render_state); if(ShaderProgram* s = r->shader){ s->bind(render_state); s->setAttribs(render_state, *v); s->setUniforms(main_uniforms); if(ShaderUniforms* u = r->uniforms){ s->setUniforms(*u); } } for(size_t i = 0; i < r->textures.size(); ++i){ if(const Texture* t = r->textures[i]){ t->bind(i, render_state); } if(const Sampler* s = r->samplers[i]){ s->bind(i, render_state); } } v->bind(render_state); if(IndexBuffer* ib = v->getIndexBuffer()){ gl.DrawElements(r->prim_type, r->count, ib->getType(), reinterpret_cast<GLvoid*>(r->offset)); } else { gl.DrawArrays(r->prim_type, r->offset, r->count); } } SDL_GL_SwapWindow(window); renderables.clear(); } void Renderer::addRenderable(Renderable& r){ renderables.push_back(&r); } Renderer::~Renderer(){ gl.deleteContext(); if(window){ SDL_DestroyWindow(window); } SDL_GL_UnloadLibrary(); SDL_QuitSubSystem(SDL_INIT_VIDEO); }
26.896
96
0.654819
baines
d9377566991fcc98197f718a02819e663ee27093
855
cpp
C++
src/main/native/cpp/Util.cpp
KyleQ1/Characterization-Robot-2020
f28bb07fab05587e7462937ce3e0f9fe40a5f014
[ "BSD-3-Clause" ]
null
null
null
src/main/native/cpp/Util.cpp
KyleQ1/Characterization-Robot-2020
f28bb07fab05587e7462937ce3e0f9fe40a5f014
[ "BSD-3-Clause" ]
null
null
null
src/main/native/cpp/Util.cpp
KyleQ1/Characterization-Robot-2020
f28bb07fab05587e7462937ce3e0f9fe40a5f014
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "sysid/Util.h" #include <sstream> #include <string> #include <vector> #include <imgui.h> void sysid::CreateTooltip(const char* text) { ImGui::SameLine(); ImGui::TextDisabled(" (?)"); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); ImGui::TextUnformatted(text); ImGui::PopTextWrapPos(); ImGui::EndTooltip(); } } std::vector<std::string> sysid::Split(const std::string& s, char c) { std::vector<std::string> result; std::stringstream ss(s); std::string item; while (std::getline(ss, item, c)) { result.push_back(item); } return result; }
23.108108
74
0.676023
KyleQ1
d937915bb1a35782e9a8914bb04dc600518feb56
6,423
cpp
C++
reference/matrix/hybrid_kernels.cpp
JakubTrzcskni/ginkgo
8a9988b9c3f8c4ff59fae30050575311f230065e
[ "BSD-3-Clause" ]
null
null
null
reference/matrix/hybrid_kernels.cpp
JakubTrzcskni/ginkgo
8a9988b9c3f8c4ff59fae30050575311f230065e
[ "BSD-3-Clause" ]
null
null
null
reference/matrix/hybrid_kernels.cpp
JakubTrzcskni/ginkgo
8a9988b9c3f8c4ff59fae30050575311f230065e
[ "BSD-3-Clause" ]
null
null
null
/*******************************<GINKGO LICENSE>****************************** Copyright (c) 2017-2022, the Ginkgo authors 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 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************<GINKGO LICENSE>*******************************/ #include "core/matrix/hybrid_kernels.hpp" #include <ginkgo/core/base/exception_helpers.hpp> #include <ginkgo/core/base/math.hpp> #include <ginkgo/core/matrix/coo.hpp> #include <ginkgo/core/matrix/csr.hpp> #include <ginkgo/core/matrix/dense.hpp> #include <ginkgo/core/matrix/ell.hpp> #include "core/components/format_conversion_kernels.hpp" #include "core/components/prefix_sum_kernels.hpp" #include "core/matrix/ell_kernels.hpp" namespace gko { namespace kernels { namespace reference { /** * @brief The Hybrid matrix format namespace. * @ref Hybrid * @ingroup hybrid */ namespace hybrid { void compute_coo_row_ptrs(std::shared_ptr<const DefaultExecutor> exec, const Array<size_type>& row_nnz, size_type ell_lim, int64* coo_row_ptrs) { for (size_type row = 0; row < row_nnz.get_num_elems(); row++) { if (row_nnz.get_const_data()[row] <= ell_lim) { coo_row_ptrs[row] = 0; } else { coo_row_ptrs[row] = row_nnz.get_const_data()[row] - ell_lim; } } components::prefix_sum(exec, coo_row_ptrs, row_nnz.get_num_elems() + 1); } void compute_row_nnz(std::shared_ptr<const DefaultExecutor> exec, const Array<int64>& row_ptrs, size_type* row_nnzs) { for (size_type i = 0; i < row_ptrs.get_num_elems() - 1; i++) { row_nnzs[i] = row_ptrs.get_const_data()[i + 1] - row_ptrs.get_const_data()[i]; } } template <typename ValueType, typename IndexType> void fill_in_matrix_data(std::shared_ptr<const DefaultExecutor> exec, const device_matrix_data<ValueType, IndexType>& data, const int64* row_ptrs, const int64*, matrix::Hybrid<ValueType, IndexType>* result) { const auto num_rows = result->get_size()[0]; const auto ell_max_nnz = result->get_ell_num_stored_elements_per_row(); const auto values = data.get_const_values(); const auto row_idxs = data.get_const_row_idxs(); const auto col_idxs = data.get_const_col_idxs(); size_type coo_nz{}; for (size_type row = 0; row < num_rows; row++) { size_type ell_nz{}; for (auto nz = row_ptrs[row]; nz < row_ptrs[row + 1]; nz++) { if (ell_nz < ell_max_nnz) { result->ell_col_at(row, ell_nz) = col_idxs[nz]; result->ell_val_at(row, ell_nz) = values[nz]; ell_nz++; } else { result->get_coo_row_idxs()[coo_nz] = row_idxs[nz]; result->get_coo_col_idxs()[coo_nz] = col_idxs[nz]; result->get_coo_values()[coo_nz] = values[nz]; coo_nz++; } } for (; ell_nz < ell_max_nnz; ell_nz++) { result->ell_col_at(row, ell_nz) = 0; result->ell_val_at(row, ell_nz) = zero<ValueType>(); } } } GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_HYBRID_FILL_IN_MATRIX_DATA_KERNEL); template <typename ValueType, typename IndexType> void convert_to_csr(std::shared_ptr<const ReferenceExecutor> exec, const matrix::Hybrid<ValueType, IndexType>* source, const IndexType*, const IndexType*, matrix::Csr<ValueType, IndexType>* result) { auto csr_val = result->get_values(); auto csr_col_idxs = result->get_col_idxs(); auto csr_row_ptrs = result->get_row_ptrs(); const auto ell = source->get_ell(); const auto max_nnz_per_row = ell->get_num_stored_elements_per_row(); const auto coo_val = source->get_const_coo_values(); const auto coo_col = source->get_const_coo_col_idxs(); const auto coo_row = source->get_const_coo_row_idxs(); const auto coo_nnz = source->get_coo_num_stored_elements(); csr_row_ptrs[0] = 0; size_type csr_idx = 0; size_type coo_idx = 0; for (IndexType row = 0; row < source->get_size()[0]; row++) { // Ell part for (IndexType col = 0; col < max_nnz_per_row; col++) { const auto val = ell->val_at(row, col); if (is_nonzero(val)) { csr_val[csr_idx] = val; csr_col_idxs[csr_idx] = ell->col_at(row, col); csr_idx++; } } // Coo part (row should be ascending) while (coo_idx < coo_nnz && coo_row[coo_idx] == row) { csr_val[csr_idx] = coo_val[coo_idx]; csr_col_idxs[csr_idx] = coo_col[coo_idx]; csr_idx++; coo_idx++; } csr_row_ptrs[row + 1] = csr_idx; } } GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE( GKO_DECLARE_HYBRID_CONVERT_TO_CSR_KERNEL); } // namespace hybrid } // namespace reference } // namespace kernels } // namespace gko
38.005917
78
0.656391
JakubTrzcskni
d9399880189f27bd5e1d4eb31ece04c6f4fd198e
1,820
cc
C++
src/q_1301_1350/q1309.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
null
null
null
src/q_1301_1350/q1309.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
2
2021-12-15T10:51:15.000Z
2022-01-26T17:03:16.000Z
src/q_1301_1350/q1309.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <iostream> #include <string> using namespace std; /** * This file is generated by leetcode_add.py * * 1309. * Decrypt String from Alphabet to Integer Mapping * * ––––––––––––––––––––––––––––– Description ––––––––––––––––––––––––––––– * * You are given a string ‘s’ formed by digits and ‘'#'’ . We want to map * ‘s’ to English lowercase characters as * - Characters ( ‘'a'’ to ‘'i')’ are represented by ( ‘'1'’ to ‘'9'’ * ) * - Characters ( ‘'j'’ to ‘'z')’ are represented by ( ‘'10#'’ to * ‘'26#'’ ) * Return “the string formed after mapping” * The test cases are generated so that a unique mapping will always * exist. * * ––––––––––––––––––––––––––––– Constraints ––––––––––––––––––––––––––––– * * • ‘1 ≤ s.length ≤ 1000’ * • ‘s’ consists of digits and the ‘'#'’ letter. * • ‘s’ will be a valid string such that mapping is always possible. * */ struct q1309 : public ::testing::Test { // Leetcode answer here class Solution { public: string freqAlphabets(string s) { string res; for (int i = s.size() - 1; i >= 0; --i) { if (s[i] == '#') { res.push_back(stoi(s.substr(i - 2, 2)) - 10 + 'j'); -- --i; } else { res.push_back(s[i] - '1' + 'a'); } } reverse(res.begin(), res.end()); return res; } }; class Solution *solution; }; TEST_F(q1309, sample_input01) { solution = new Solution(); string s = "10#11#12"; string exp = "jkab"; string act = solution->freqAlphabets(s); EXPECT_EQ(act, exp); delete solution; } TEST_F(q1309, sample_input02) { solution = new Solution(); string s = "1326#"; string exp = "acz"; string act = solution->freqAlphabets(s); EXPECT_EQ(act, exp); delete solution; }
25.277778
75
0.535165
vNaonLu
d93f27f778a565a45c114b985a25a601b82867f6
3,865
hpp
C++
SDK/ARKSurvivalEvolved_DinoTamedInventoryComponent_Beetle_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_DinoTamedInventoryComponent_Beetle_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_DinoTamedInventoryComponent_Beetle_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoTamedInventoryComponent_Beetle_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.CraftItem struct UDinoTamedInventoryComponent_Beetle_C_CraftItem_Params { int ItemToCraftIndex; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.BPInventoryRefresh struct UDinoTamedInventoryComponent_Beetle_C_BPInventoryRefresh_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.BPInitializeInventory struct UDinoTamedInventoryComponent_Beetle_C_BPInitializeInventory_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.CheckIfAnythingNewCanBeCrafted struct UDinoTamedInventoryComponent_Beetle_C_CheckIfAnythingNewCanBeCrafted_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.Initial Set Crafting Times struct UDinoTamedInventoryComponent_Beetle_C_Initial_Set_Crafting_Times_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.TryToCraft struct UDinoTamedInventoryComponent_Beetle_C_TryToCraft_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.UnsetAll struct UDinoTamedInventoryComponent_Beetle_C_UnsetAll_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.HasEnoughResources struct UDinoTamedInventoryComponent_Beetle_C_HasEnoughResources_Params { int IndexClassToCheck; // (Parm, ZeroConstructor, IsPlainOldData) bool hasEnough; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int NumberOfTimesCanCraft; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.RemoveUncraftable struct UDinoTamedInventoryComponent_Beetle_C_RemoveUncraftable_Params { }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.BPNotifyItemAdded struct UDinoTamedInventoryComponent_Beetle_C_BPNotifyItemAdded_Params { class UPrimalItem** anItem; // (Parm, ZeroConstructor, IsPlainOldData) bool* bEquipItem; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.BPNotifyItemRemoved struct UDinoTamedInventoryComponent_Beetle_C_BPNotifyItemRemoved_Params { class UPrimalItem** anItem; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function DinoTamedInventoryComponent_Beetle.DinoTamedInventoryComponent_Beetle_C.ExecuteUbergraph_DinoTamedInventoryComponent_Beetle struct UDinoTamedInventoryComponent_Beetle_C_ExecuteUbergraph_DinoTamedInventoryComponent_Beetle_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
42.944444
161
0.686158
2bite
d93fdb9f6e0fdeebf1f4d05913e9536ebe9b383c
1,055
hpp
C++
src/boost/atomic/detail/wait_caps_dragonfly_umtx.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
null
null
null
src/boost/atomic/detail/wait_caps_dragonfly_umtx.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
1
2021-08-30T18:02:49.000Z
2021-08-30T18:02:49.000Z
src/boost/atomic/detail/wait_caps_dragonfly_umtx.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
null
null
null
/* * 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) * * Copyright (c) 2020 Andrey Semashev */ /*! * \file atomic/detail/wait_caps_dragonfly_umtx.hpp * * This header defines waiting/notifying operations capabilities macros. */ #ifndef BOOST_ATOMIC_DETAIL_WAIT_CAPS_DRAGONFLY_UMTX_HPP_INCLUDED_ #define BOOST_ATOMIC_DETAIL_WAIT_CAPS_DRAGONFLY_UMTX_HPP_INCLUDED_ #include "boost/atomic/detail/config.hpp" #include "boost/atomic/detail/capabilities.hpp" #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif // DragonFly BSD umtx_sleep/umtx_wakeup use physical address to the atomic object as a key, which means it should support address-free operations. // https://man.dragonflybsd.org/?command=umtx&section=2 #define BOOST_ATOMIC_HAS_NATIVE_INT32_WAIT_NOTIFY BOOST_ATOMIC_INT32_LOCK_FREE #define BOOST_ATOMIC_HAS_NATIVE_INT32_IPC_WAIT_NOTIFY BOOST_ATOMIC_INT32_LOCK_FREE #endif // BOOST_ATOMIC_DETAIL_WAIT_CAPS_DRAGONFLY_UMTX_HPP_INCLUDED_
34.032258
146
0.824645
107-systems
d9409cbbe2b6fa384db0888d8d6ee9a87ab578d0
42,365
cpp
C++
framework/hpp_api_vulkan_sample.cpp
jwinarske/Vulkan-Samples
11a0eeffa223e3c049780fd783900da0bfe50431
[ "Apache-2.0" ]
20
2020-03-25T17:57:32.000Z
2022-03-12T08:16:10.000Z
framework/hpp_api_vulkan_sample.cpp
JasonWinston/Vulkan-Samples
fe3fd6435e5f209b00d72a85004f189d01debee4
[ "Apache-2.0" ]
1
2020-02-18T07:08:52.000Z
2020-02-18T07:08:52.000Z
framework/hpp_api_vulkan_sample.cpp
JasonWinston/Vulkan-Samples
fe3fd6435e5f209b00d72a85004f189d01debee4
[ "Apache-2.0" ]
1
2020-04-12T16:23:18.000Z
2020-04-12T16:23:18.000Z
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 the "License"; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <hpp_api_vulkan_sample.h> #include <common/hpp_vk_common.h> #include <core/hpp_buffer.h> #include <hpp_gltf_loader.h> // Instantiate the default dispatcher VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE bool HPPApiVulkanSample::prepare(vkb::platform::HPPPlatform &platform) { if (!HPPVulkanSample::prepare(platform)) { return false; } // initialize function pointers for C++-bindings static vk::DynamicLoader dl; VULKAN_HPP_DEFAULT_DISPATCHER.init(dl.getProcAddress<PFN_vkGetInstanceProcAddr>("vkGetInstanceProcAddr")); VULKAN_HPP_DEFAULT_DISPATCHER.init(get_instance().get_handle()); VULKAN_HPP_DEFAULT_DISPATCHER.init(get_device().get_handle()); depth_format = vkb::common::get_suitable_depth_format(get_device().get_gpu().get_handle()); // Create synchronization objects // Create a semaphore used to synchronize image presentation // Ensures that the current swapchain render target has completed presentation and has been released by the presentation engine, ready for rendering semaphores.acquired_image_ready = get_device().get_handle().createSemaphore({}); // Create a semaphore used to synchronize command submission // Ensures that the image is not presented until all commands have been sumbitted and executed semaphores.render_complete = get_device().get_handle().createSemaphore({}); // Set up submit info structure // Semaphores will stay the same during application lifetime // Command buffer submission info is set by each example submit_info = vk::SubmitInfo(); submit_info.pWaitDstStageMask = &submit_pipeline_stages; if (platform.get_window().get_window_mode() != vkb::Window::Mode::Headless) { submit_info.setWaitSemaphores(semaphores.acquired_image_ready); submit_info.setSignalSemaphores(semaphores.render_complete); } queue = get_device().get_suitable_graphics_queue().get_handle(); create_swapchain_buffers(); create_command_pool(); create_command_buffers(); create_synchronization_primitives(); setup_depth_stencil(); setup_render_pass(); create_pipeline_cache(); setup_framebuffer(); extent = get_render_context().get_surface_extent(); gui = std::make_unique<vkb::Gui>(*this, platform.get_window(), /*stats=*/nullptr, 15.0f, true); gui->prepare(pipeline_cache, render_pass, {load_shader("uioverlay/uioverlay.vert", vk::ShaderStageFlagBits::eVertex), load_shader("uioverlay/uioverlay.frag", vk::ShaderStageFlagBits::eFragment)}); return true; } void HPPApiVulkanSample::update(float delta_time) { if (view_updated) { view_updated = false; view_changed(); } update_overlay(delta_time); render(delta_time); camera.update(delta_time); if (camera.moving()) { view_updated = true; } get_platform().on_post_draw(get_render_context()); } bool HPPApiVulkanSample::resize(const uint32_t, const uint32_t) { if (!prepared) { return false; } get_render_context().handle_surface_changes(); // Don't recreate the swapchain if the dimensions haven't changed if (extent == get_render_context().get_surface_extent()) { return false; } extent = get_render_context().get_surface_extent(); prepared = false; // Ensure all operations on the device have been finished before destroying resources get_device().wait_idle(); create_swapchain_buffers(); // Recreate the frame buffers get_device().get_handle().destroyImageView(depth_stencil.view); get_device().get_handle().destroyImage(depth_stencil.image); get_device().get_handle().freeMemory(depth_stencil.mem); setup_depth_stencil(); for (uint32_t i = 0; i < framebuffers.size(); i++) { get_device().get_handle().destroyFramebuffer(framebuffers[i]); framebuffers[i] = nullptr; } setup_framebuffer(); if (extent.width && extent.height && gui) { gui->resize(extent.width, extent.height); } // Command buffers need to be recreated as they may store // references to the recreated frame buffer destroy_command_buffers(); create_command_buffers(); build_command_buffers(); get_device().wait_idle(); if (extent.width && extent.height) { camera.update_aspect_ratio((float) extent.width / (float) extent.height); } // Notify derived class view_changed(); prepared = true; return true; } void HPPApiVulkanSample::create_render_context(vkb::Platform &platform) { HPPVulkanSample::create_render_context(platform, {{vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear}, {vk::Format::eR8G8B8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear}, {vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}, {vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}}); } void HPPApiVulkanSample::prepare_render_context() { HPPVulkanSample::prepare_render_context(); } void HPPApiVulkanSample::input_event(const vkb::InputEvent &input_event) { HPPVulkanSample::input_event(input_event); bool gui_captures_event = false; if (gui) { gui_captures_event = gui->input_event(input_event); } if (!gui_captures_event) { if (input_event.get_source() == vkb::EventSource::Mouse) { const auto &mouse_button = static_cast<const vkb::MouseButtonInputEvent &>(input_event); handle_mouse_move(static_cast<int32_t>(mouse_button.get_pos_x()), static_cast<int32_t>(mouse_button.get_pos_y())); if (mouse_button.get_action() == vkb::MouseAction::Down) { switch (mouse_button.get_button()) { case vkb::MouseButton::Left: mouse_buttons.left = true; break; case vkb::MouseButton::Right: mouse_buttons.right = true; break; case vkb::MouseButton::Middle: mouse_buttons.middle = true; break; default: break; } } else if (mouse_button.get_action() == vkb::MouseAction::Up) { switch (mouse_button.get_button()) { case vkb::MouseButton::Left: mouse_buttons.left = false; break; case vkb::MouseButton::Right: mouse_buttons.right = false; break; case vkb::MouseButton::Middle: mouse_buttons.middle = false; break; default: break; } } } else if (input_event.get_source() == vkb::EventSource::Touchscreen) { const auto &touch_event = static_cast<const vkb::TouchInputEvent &>(input_event); if (touch_event.get_action() == vkb::TouchAction::Down) { touch_down = true; touch_pos.x = static_cast<int32_t>(touch_event.get_pos_x()); touch_pos.y = static_cast<int32_t>(touch_event.get_pos_y()); mouse_pos.x = touch_event.get_pos_x(); mouse_pos.y = touch_event.get_pos_y(); mouse_buttons.left = true; } else if (touch_event.get_action() == vkb::TouchAction::Up) { touch_pos.x = static_cast<int32_t>(touch_event.get_pos_x()); touch_pos.y = static_cast<int32_t>(touch_event.get_pos_y()); touch_timer = 0.0; touch_down = false; camera.keys.up = false; mouse_buttons.left = false; } else if (touch_event.get_action() == vkb::TouchAction::Move) { bool handled = false; if (gui) { ImGuiIO &io = ImGui::GetIO(); handled = io.WantCaptureMouse; } if (!handled) { int32_t eventX = static_cast<int32_t>(touch_event.get_pos_x()); int32_t eventY = static_cast<int32_t>(touch_event.get_pos_y()); float deltaX = (float) (touch_pos.y - eventY) * rotation_speed * 0.5f; float deltaY = (float) (touch_pos.x - eventX) * rotation_speed * 0.5f; camera.rotate(glm::vec3(deltaX, 0.0f, 0.0f)); camera.rotate(glm::vec3(0.0f, -deltaY, 0.0f)); rotation.x += deltaX; rotation.y -= deltaY; view_changed(); touch_pos.x = eventX; touch_pos.y = eventY; } } } else if (input_event.get_source() == vkb::EventSource::Keyboard) { const auto &key_button = static_cast<const vkb::KeyInputEvent &>(input_event); if (key_button.get_action() == vkb::KeyAction::Down) { switch (key_button.get_code()) { case vkb::KeyCode::W: camera.keys.up = true; break; case vkb::KeyCode::S: camera.keys.down = true; break; case vkb::KeyCode::A: camera.keys.left = true; break; case vkb::KeyCode::D: camera.keys.right = true; break; case vkb::KeyCode::P: paused = !paused; break; default: break; } } else if (key_button.get_action() == vkb::KeyAction::Up) { switch (key_button.get_code()) { case vkb::KeyCode::W: camera.keys.up = false; break; case vkb::KeyCode::S: camera.keys.down = false; break; case vkb::KeyCode::A: camera.keys.left = false; break; case vkb::KeyCode::D: camera.keys.right = false; break; default: break; } } } } } void HPPApiVulkanSample::handle_mouse_move(int32_t x, int32_t y) { int32_t dx = (int32_t) mouse_pos.x - x; int32_t dy = (int32_t) mouse_pos.y - y; bool handled = false; if (gui) { ImGuiIO &io = ImGui::GetIO(); handled = io.WantCaptureMouse; } mouse_moved((float) x, (float) y, handled); if (handled) { mouse_pos = glm::vec2((float) x, (float) y); return; } if (mouse_buttons.left) { rotation.x += dy * 1.25f * rotation_speed; rotation.y -= dx * 1.25f * rotation_speed; camera.rotate(glm::vec3(dy * camera.rotation_speed, -dx * camera.rotation_speed, 0.0f)); view_updated = true; } if (mouse_buttons.right) { zoom += dy * .005f * zoom_speed; camera.translate(glm::vec3(-0.0f, 0.0f, dy * .005f * zoom_speed)); view_updated = true; } if (mouse_buttons.middle) { camera_pos.x -= dx * 0.01f; camera_pos.y -= dy * 0.01f; camera.translate(glm::vec3(-dx * 0.01f, -dy * 0.01f, 0.0f)); view_updated = true; } mouse_pos = glm::vec2((float) x, (float) y); } void HPPApiVulkanSample::mouse_moved(double x, double y, bool &handled) {} bool HPPApiVulkanSample::check_command_buffers() { for (auto &command_buffer : draw_cmd_buffers) { if (command_buffer) { return false; } } return true; } void HPPApiVulkanSample::create_command_buffers() { // Create one command buffer for each swap chain image and reuse for rendering vk::CommandBufferAllocateInfo allocate_info( cmd_pool, vk::CommandBufferLevel::ePrimary, static_cast<uint32_t>(get_render_context().get_render_frames().size())); draw_cmd_buffers = get_device().get_handle().allocateCommandBuffers(allocate_info); } void HPPApiVulkanSample::destroy_command_buffers() { get_device().get_handle().freeCommandBuffers(cmd_pool, draw_cmd_buffers); } void HPPApiVulkanSample::create_pipeline_cache() { pipeline_cache = get_device().get_handle().createPipelineCache({}); } vk::PipelineShaderStageCreateInfo HPPApiVulkanSample::load_shader(const std::string &file, vk::ShaderStageFlagBits stage) { shader_modules.push_back(vkb::common::load_shader(file.c_str(), get_device().get_handle(), stage)); assert(shader_modules.back()); return vk::PipelineShaderStageCreateInfo({}, stage, shader_modules.back(), "main"); } void HPPApiVulkanSample::update_overlay(float delta_time) { if (gui) { gui->show_simple_window(get_name(), vkb::to_u32(1.0f / delta_time), [this]() { on_update_ui_overlay(gui->get_drawer()); }); gui->update(delta_time); if (gui->update_buffers() || gui->get_drawer().is_dirty()) { build_command_buffers(); gui->get_drawer().clear(); } } } void HPPApiVulkanSample::draw_ui(const vk::CommandBuffer command_buffer) { if (gui) { command_buffer.setViewport(0, vk::Viewport(0.0f, 0.0f, static_cast<float>(extent.width), static_cast<float>(extent.height), 0.0f, 1.0f)); command_buffer.setScissor(0, vk::Rect2D({0, 0}, extent)); gui->draw(command_buffer); } } void HPPApiVulkanSample::prepare_frame() { if (get_render_context().has_swapchain()) { handle_surface_changes(); // Acquire the next image from the swap chain // Shows how to filter an error code from a vulkan function, which is mapped to an exception but should be handled here! vk::Result result; try { result = get_render_context().get_swapchain().acquire_next_image(current_buffer, semaphores.acquired_image_ready); } catch (const vk::SystemError &e) { if (e.code() == vk::Result::eErrorOutOfDateKHR) { result = vk::Result::eErrorOutOfDateKHR; } else { throw; } } // Recreate the swapchain if it's no longer compatible with the surface (eErrorOutOfDateKHR) or no longer optimal for // presentation (eSuboptimalKHR) if ((result == vk::Result::eErrorOutOfDateKHR) || (result == vk::Result::eSuboptimalKHR)) { resize(extent.width, extent.height); } } } void HPPApiVulkanSample::submit_frame() { if (get_render_context().has_swapchain()) { const auto &queue = get_device().get_queue_by_present(0); vk::SwapchainKHR swapchain = get_render_context().get_swapchain().get_handle(); vk::PresentInfoKHR present_info({}, swapchain, current_buffer); // Check if a wait semaphore has been specified to wait for before presenting the image if (semaphores.render_complete) { present_info.setWaitSemaphores(semaphores.render_complete); } // Shows how to filter an error code from a vulkan function, which is mapped to an exception but should be handled here! vk::Result present_result; try { present_result = queue.present(present_info); } catch (const vk::SystemError &e) { if (e.code() == vk::Result::eErrorOutOfDateKHR) { // Swap chain is no longer compatible with the surface and needs to be recreated resize(extent.width, extent.height); return; } else { // rethrow this error throw; } } } // DO NOT USE // vkDeviceWaitIdle and vkQueueWaitIdle are extremely expensive functions, and are used here purely for demonstrating the vulkan API // without having to concern ourselves with proper syncronization. These functions should NEVER be used inside the render loop like this (every frame). get_device().get_queue_by_present(0).wait_idle(); } HPPApiVulkanSample::~HPPApiVulkanSample() { if (get_device().get_handle()) { get_device().wait_idle(); // Clean up Vulkan resources get_device().get_handle().destroyDescriptorPool(descriptor_pool); destroy_command_buffers(); get_device().get_handle().destroyRenderPass(render_pass); for (auto &framebuffer : framebuffers) { get_device().get_handle().destroyFramebuffer(framebuffer); } for (auto &swapchain_buffer : swapchain_buffers) { get_device().get_handle().destroyImageView(swapchain_buffer.view); } for (auto &shader_module : shader_modules) { get_device().get_handle().destroyShaderModule(shader_module); } get_device().get_handle().destroyImageView(depth_stencil.view); get_device().get_handle().destroyImage(depth_stencil.image); get_device().get_handle().freeMemory(depth_stencil.mem); get_device().get_handle().destroyPipelineCache(pipeline_cache); get_device().get_handle().destroyCommandPool(cmd_pool); get_device().get_handle().destroySemaphore(semaphores.acquired_image_ready); get_device().get_handle().destroySemaphore(semaphores.render_complete); for (auto &fence : wait_fences) { get_device().get_handle().destroyFence(fence); } } gui.reset(); } void HPPApiVulkanSample::view_changed() {} void HPPApiVulkanSample::build_command_buffers() {} void HPPApiVulkanSample::create_synchronization_primitives() { // Wait fences to sync command buffer access vk::FenceCreateInfo fence_create_info(vk::FenceCreateFlagBits::eSignaled); wait_fences.resize(draw_cmd_buffers.size()); for (auto &fence : wait_fences) { fence = get_device().get_handle().createFence(fence_create_info); } } void HPPApiVulkanSample::create_command_pool() { uint32_t queue_family_index = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics | vk::QueueFlagBits::eCompute, 0).get_family_index(); vk::CommandPoolCreateInfo command_pool_info(vk::CommandPoolCreateFlagBits::eResetCommandBuffer, queue_family_index); cmd_pool = get_device().get_handle().createCommandPool(command_pool_info); } void HPPApiVulkanSample::setup_depth_stencil() { vk::ImageCreateInfo image_create_info; image_create_info.imageType = vk::ImageType::e2D; image_create_info.format = depth_format; image_create_info.extent = vk::Extent3D(get_render_context().get_surface_extent().width, get_render_context().get_surface_extent().height, 1); image_create_info.mipLevels = 1; image_create_info.arrayLayers = 1; image_create_info.samples = vk::SampleCountFlagBits::e1; image_create_info.tiling = vk::ImageTiling::eOptimal; image_create_info.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransferSrc; depth_stencil.image = get_device().get_handle().createImage(image_create_info); vk::MemoryRequirements memReqs = get_device().get_handle().getImageMemoryRequirements(depth_stencil.image); vk::MemoryAllocateInfo memory_allocation(memReqs.size, get_device().get_memory_type(memReqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal)); depth_stencil.mem = get_device().get_handle().allocateMemory(memory_allocation); get_device().get_handle().bindImageMemory(depth_stencil.image, depth_stencil.mem, 0); vk::ImageViewCreateInfo image_view_create_info; image_view_create_info.viewType = vk::ImageViewType::e2D; image_view_create_info.image = depth_stencil.image; image_view_create_info.format = depth_format; image_view_create_info.subresourceRange.baseMipLevel = 0; image_view_create_info.subresourceRange.levelCount = 1; image_view_create_info.subresourceRange.baseArrayLayer = 0; image_view_create_info.subresourceRange.layerCount = 1; image_view_create_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eDepth; // Stencil aspect should only be set on depth + stencil formats (vk::Format::eD16UnormS8Uint..vk::Format::eD32SfloatS8Uint if (vk::Format::eD16UnormS8Uint <= depth_format) { image_view_create_info.subresourceRange.aspectMask |= vk::ImageAspectFlagBits::eStencil; } depth_stencil.view = get_device().get_handle().createImageView(image_view_create_info); } void HPPApiVulkanSample::setup_framebuffer() { std::array<vk::ImageView, 2> attachments; // Depth/Stencil attachment is the same for all frame buffers attachments[1] = depth_stencil.view; vk::FramebufferCreateInfo framebuffer_create_info( {}, render_pass, attachments, get_render_context().get_surface_extent().width, get_render_context().get_surface_extent().height, 1); // Delete existing frame buffers for (auto &framebuffer : framebuffers) { get_device().get_handle().destroyFramebuffer(framebuffer); } framebuffers.clear(); // Create frame buffers for every swap chain image framebuffers.reserve(swapchain_buffers.size()); for (auto &buffer : swapchain_buffers) { attachments[0] = buffer.view; framebuffers.push_back(get_device().get_handle().createFramebuffer(framebuffer_create_info)); } } void HPPApiVulkanSample::setup_render_pass() { std::array<vk::AttachmentDescription, 2> attachments; // Color attachment attachments[0].format = get_render_context().get_format(); attachments[0].samples = vk::SampleCountFlagBits::e1; attachments[0].loadOp = vk::AttachmentLoadOp::eClear; attachments[0].storeOp = vk::AttachmentStoreOp::eStore; attachments[0].stencilLoadOp = vk::AttachmentLoadOp::eDontCare; attachments[0].stencilStoreOp = vk::AttachmentStoreOp::eDontCare; attachments[0].initialLayout = vk::ImageLayout::eUndefined; attachments[0].finalLayout = vk::ImageLayout::ePresentSrcKHR; // Depth attachment attachments[1].format = depth_format; attachments[1].samples = vk::SampleCountFlagBits::e1; attachments[1].loadOp = vk::AttachmentLoadOp::eClear; attachments[1].storeOp = vk::AttachmentStoreOp::eDontCare; attachments[1].stencilLoadOp = vk::AttachmentLoadOp::eClear; attachments[1].stencilStoreOp = vk::AttachmentStoreOp::eDontCare; attachments[1].initialLayout = vk::ImageLayout::eUndefined; attachments[1].finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal; vk::AttachmentReference color_reference(0, vk::ImageLayout::eColorAttachmentOptimal); vk::AttachmentReference depth_reference(1, vk::ImageLayout::eDepthStencilAttachmentOptimal); vk::SubpassDescription subpass_description({}, vk::PipelineBindPoint::eGraphics, {}, color_reference, {}, &depth_reference); // Subpass dependencies for layout transitions std::array<vk::SubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = vk::PipelineStageFlagBits::eBottomOfPipe; dependencies[0].dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; dependencies[0].srcAccessMask = vk::AccessFlagBits::eMemoryRead; dependencies[0].dstAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite; dependencies[0].dependencyFlags = vk::DependencyFlagBits::eByRegion; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; dependencies[1].dstStageMask = vk::PipelineStageFlagBits::eBottomOfPipe; dependencies[1].srcAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite; dependencies[1].dstAccessMask = vk::AccessFlagBits::eMemoryRead; dependencies[1].dependencyFlags = vk::DependencyFlagBits::eByRegion; vk::RenderPassCreateInfo render_pass_create_info({}, attachments, subpass_description, dependencies); render_pass = get_device().get_handle().createRenderPass(render_pass_create_info); } void HPPApiVulkanSample::update_render_pass_flags(RenderPassCreateFlags flags) { get_device().get_handle().destroyRenderPass(render_pass); vk::AttachmentLoadOp color_attachment_load_op = vk::AttachmentLoadOp::eClear; vk::ImageLayout color_attachment_image_layout = vk::ImageLayout::eUndefined; // Samples can keep the color attachment contents, e.g. if they have previously written to the swap chain images if (flags & RenderPassCreateFlags::ColorAttachmentLoad) { color_attachment_load_op = vk::AttachmentLoadOp::eLoad; color_attachment_image_layout = vk::ImageLayout::ePresentSrcKHR; } std::array<vk::AttachmentDescription, 2> attachments = {}; // Color attachment attachments[0].format = get_render_context().get_format(); attachments[0].samples = vk::SampleCountFlagBits::e1; attachments[0].loadOp = color_attachment_load_op; attachments[0].storeOp = vk::AttachmentStoreOp::eStore; attachments[0].stencilLoadOp = vk::AttachmentLoadOp::eDontCare; attachments[0].stencilStoreOp = vk::AttachmentStoreOp::eDontCare; attachments[0].initialLayout = color_attachment_image_layout; attachments[0].finalLayout = vk::ImageLayout::ePresentSrcKHR; // Depth attachment attachments[1].format = depth_format; attachments[1].samples = vk::SampleCountFlagBits::e1; attachments[1].loadOp = vk::AttachmentLoadOp::eClear; attachments[1].storeOp = vk::AttachmentStoreOp::eDontCare; attachments[1].stencilLoadOp = vk::AttachmentLoadOp::eClear; attachments[1].stencilStoreOp = vk::AttachmentStoreOp::eDontCare; attachments[1].initialLayout = vk::ImageLayout::eUndefined; attachments[1].finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal; vk::AttachmentReference color_reference(0, vk::ImageLayout::eColorAttachmentOptimal); vk::AttachmentReference depth_reference(1, vk::ImageLayout::eDepthStencilAttachmentOptimal); vk::SubpassDescription subpass_description({}, vk::PipelineBindPoint::eGraphics, {}, color_reference, {}, &depth_reference); // Subpass dependencies for layout transitions std::array<vk::SubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = vk::PipelineStageFlagBits::eBottomOfPipe; dependencies[0].dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; dependencies[0].srcAccessMask = vk::AccessFlagBits::eMemoryWrite; dependencies[0].dstAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite; dependencies[0].dependencyFlags = vk::DependencyFlagBits::eByRegion; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; dependencies[1].dstStageMask = vk::PipelineStageFlagBits::eBottomOfPipe; dependencies[1].srcAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite; dependencies[1].dstAccessMask = vk::AccessFlagBits::eMemoryRead; dependencies[1].dependencyFlags = vk::DependencyFlagBits::eByRegion; vk::RenderPassCreateInfo render_pass_create_info({}, attachments, subpass_description, dependencies); render_pass = get_device().get_handle().createRenderPass(render_pass_create_info); } void HPPApiVulkanSample::on_update_ui_overlay(vkb::Drawer &drawer) {} void HPPApiVulkanSample::create_swapchain_buffers() { if (get_render_context().has_swapchain()) { auto &images = get_render_context().get_swapchain().get_images(); // Get the swap chain buffers containing the image and imageview for (auto &swapchain_buffer : swapchain_buffers) { get_device().get_handle().destroyImageView(swapchain_buffer.view); } swapchain_buffers.clear(); swapchain_buffers.reserve(images.size()); for (auto &image : images) { vk::ImageViewCreateInfo color_attachment_view; color_attachment_view.image = image; color_attachment_view.viewType = vk::ImageViewType::e2D; color_attachment_view.format = get_render_context().get_swapchain().get_format(); color_attachment_view.components = {vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA}; color_attachment_view.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; color_attachment_view.subresourceRange.baseMipLevel = 0; color_attachment_view.subresourceRange.levelCount = 1; color_attachment_view.subresourceRange.baseArrayLayer = 0; color_attachment_view.subresourceRange.layerCount = 1; swapchain_buffers.push_back({image, get_device().get_handle().createImageView(color_attachment_view)}); } } else { auto &frames = get_render_context().get_render_frames(); // Get the swap chain buffers containing the image and imageview swapchain_buffers.clear(); swapchain_buffers.reserve(frames.size()); for (auto &frame : frames) { auto &image_view = *frame->get_render_target().get_views().begin(); swapchain_buffers.push_back({image_view.get_image().get_handle(), image_view.get_handle()}); } } } void HPPApiVulkanSample::update_swapchain_image_usage_flags(std::set<vk::ImageUsageFlagBits> const &image_usage_flags) { get_render_context().update_swapchain(image_usage_flags); create_swapchain_buffers(); setup_framebuffer(); } void HPPApiVulkanSample::handle_surface_changes() { vk::SurfaceCapabilitiesKHR surface_properties = get_device().get_gpu().get_handle().getSurfaceCapabilitiesKHR(get_render_context().get_swapchain().get_surface()); if (surface_properties.currentExtent != get_render_context().get_surface_extent()) { resize(surface_properties.currentExtent.width, surface_properties.currentExtent.height); } } HPPTexture HPPApiVulkanSample::load_texture(const std::string &file) { HPPTexture texture; texture.image = vkb::scene_graph::components::HPPImage::load(file, file); texture.image->create_vk_image(get_device()); const auto &queue = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics, 0); vk::CommandBuffer command_buffer = get_device().create_command_buffer(vk::CommandBufferLevel::ePrimary, true); vkb::core::HPPBuffer stage_buffer{get_device(), texture.image->get_data().size(), vk::BufferUsageFlagBits::eTransferSrc, VMA_MEMORY_USAGE_CPU_ONLY}; stage_buffer.update(texture.image->get_data()); // Setup buffer copy regions for each mip level std::vector<vk::BufferImageCopy> bufferCopyRegions; auto &mipmaps = texture.image->get_mipmaps(); for (size_t i = 0; i < mipmaps.size(); i++) { vk::BufferImageCopy buffer_copy_region; buffer_copy_region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; buffer_copy_region.imageSubresource.mipLevel = vkb::to_u32(i); buffer_copy_region.imageSubresource.baseArrayLayer = 0; buffer_copy_region.imageSubresource.layerCount = 1; buffer_copy_region.imageExtent.width = texture.image->get_extent().width >> i; buffer_copy_region.imageExtent.height = texture.image->get_extent().height >> i; buffer_copy_region.imageExtent.depth = 1; buffer_copy_region.bufferOffset = mipmaps[i].offset; bufferCopyRegions.push_back(buffer_copy_region); } vk::ImageSubresourceRange subresource_range(vk::ImageAspectFlagBits::eColor, 0, vkb::to_u32(mipmaps.size()), 0, 1); // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy vkb::common::set_image_layout( command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, subresource_range); // Copy mip levels from staging buffer command_buffer.copyBufferToImage( stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, bufferCopyRegions); // Change texture image layout to shader read after all mip levels have been copied vkb::common::set_image_layout(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); // Create a defaultsampler vk::SamplerCreateInfo sampler_create_info; sampler_create_info.magFilter = vk::Filter::eLinear; sampler_create_info.minFilter = vk::Filter::eLinear; sampler_create_info.mipmapMode = vk::SamplerMipmapMode::eLinear; sampler_create_info.addressModeU = vk::SamplerAddressMode::eRepeat; sampler_create_info.addressModeV = vk::SamplerAddressMode::eRepeat; sampler_create_info.addressModeW = vk::SamplerAddressMode::eRepeat; sampler_create_info.mipLodBias = 0.0f; sampler_create_info.compareOp = vk::CompareOp::eNever; sampler_create_info.minLod = 0.0f; // Max level-of-detail should match mip level count sampler_create_info.maxLod = static_cast<float>(mipmaps.size()); // Only enable anisotropic filtering if enabled on the device // Note that for simplicity, we will always be using max. available anisotropy level for the current device // This may have an impact on performance, esp. on lower-specced devices // In a real-world scenario the level of anisotropy should be a user setting or e.g. lowered for mobile devices by default sampler_create_info.maxAnisotropy = get_device().get_gpu().get_features().samplerAnisotropy ? (get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy) : 1.0f; sampler_create_info.anisotropyEnable = get_device().get_gpu().get_features().samplerAnisotropy; sampler_create_info.borderColor = vk::BorderColor::eFloatOpaqueWhite; texture.sampler = get_device().get_handle().createSampler(sampler_create_info); return texture; } HPPTexture HPPApiVulkanSample::load_texture_array(const std::string &file) { HPPTexture texture{}; texture.image = vkb::scene_graph::components::HPPImage::load(file, file); texture.image->create_vk_image(get_device(), vk::ImageViewType::e2DArray); const auto &queue = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics, 0); vk::CommandBuffer command_buffer = get_device().create_command_buffer(vk::CommandBufferLevel::ePrimary, true); vkb::core::HPPBuffer stage_buffer{get_device(), texture.image->get_data().size(), vk::BufferUsageFlagBits::eTransferSrc, VMA_MEMORY_USAGE_CPU_ONLY}; stage_buffer.update(texture.image->get_data()); // Setup buffer copy regions for each mip level std::vector<vk::BufferImageCopy> buffer_copy_regions; auto & mipmaps = texture.image->get_mipmaps(); const auto &layers = texture.image->get_layers(); auto &offsets = texture.image->get_offsets(); for (uint32_t layer = 0; layer < layers; layer++) { for (size_t i = 0; i < mipmaps.size(); i++) { vk::BufferImageCopy buffer_copy_region; buffer_copy_region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; buffer_copy_region.imageSubresource.mipLevel = vkb::to_u32(i); buffer_copy_region.imageSubresource.baseArrayLayer = layer; buffer_copy_region.imageSubresource.layerCount = 1; buffer_copy_region.imageExtent.width = texture.image->get_extent().width >> i; buffer_copy_region.imageExtent.height = texture.image->get_extent().height >> i; buffer_copy_region.imageExtent.depth = 1; buffer_copy_region.bufferOffset = offsets[layer][i]; buffer_copy_regions.push_back(buffer_copy_region); } } vk::ImageSubresourceRange subresource_range(vk::ImageAspectFlagBits::eColor, 0, vkb::to_u32(mipmaps.size()), 0, layers); // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy vkb::common::set_image_layout( command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, subresource_range); // Copy mip levels from staging buffer command_buffer.copyBufferToImage( stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, buffer_copy_regions); // Change texture image layout to shader read after all mip levels have been copied vkb::common::set_image_layout(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); // Create a defaultsampler vk::SamplerCreateInfo sampler_create_info; sampler_create_info.magFilter = vk::Filter::eLinear; sampler_create_info.minFilter = vk::Filter::eLinear; sampler_create_info.mipmapMode = vk::SamplerMipmapMode::eLinear; sampler_create_info.addressModeU = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.addressModeV = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.addressModeW = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.mipLodBias = 0.0f; sampler_create_info.compareOp = vk::CompareOp::eNever; sampler_create_info.minLod = 0.0f; // Max level-of-detail should match mip level count sampler_create_info.maxLod = static_cast<float>(mipmaps.size()); // Only enable anisotropic filtering if enabled on the devicec sampler_create_info.maxAnisotropy = get_device().get_gpu().get_features().samplerAnisotropy ? get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy : 1.0f; sampler_create_info.anisotropyEnable = get_device().get_gpu().get_features().samplerAnisotropy; sampler_create_info.borderColor = vk::BorderColor::eFloatOpaqueWhite; texture.sampler = get_device().get_handle().createSampler(sampler_create_info); return texture; } HPPTexture HPPApiVulkanSample::load_texture_cubemap(const std::string &file) { HPPTexture texture{}; texture.image = vkb::scene_graph::components::HPPImage::load(file, file); texture.image->create_vk_image(get_device(), vk::ImageViewType::eCube, vk::ImageCreateFlagBits::eCubeCompatible); const auto &queue = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics, 0); vk::CommandBuffer command_buffer = get_device().create_command_buffer(vk::CommandBufferLevel::ePrimary, true); vkb::core::HPPBuffer stage_buffer{get_device(), texture.image->get_data().size(), vk::BufferUsageFlagBits::eTransferSrc, VMA_MEMORY_USAGE_CPU_ONLY}; stage_buffer.update(texture.image->get_data()); // Setup buffer copy regions for each mip level std::vector<vk::BufferImageCopy> buffer_copy_regions; auto & mipmaps = texture.image->get_mipmaps(); const auto &layers = texture.image->get_layers(); auto &offsets = texture.image->get_offsets(); for (uint32_t layer = 0; layer < layers; layer++) { for (size_t i = 0; i < mipmaps.size(); i++) { vk::BufferImageCopy buffer_copy_region; buffer_copy_region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; buffer_copy_region.imageSubresource.mipLevel = vkb::to_u32(i); buffer_copy_region.imageSubresource.baseArrayLayer = layer; buffer_copy_region.imageSubresource.layerCount = 1; buffer_copy_region.imageExtent.width = texture.image->get_extent().width >> i; buffer_copy_region.imageExtent.height = texture.image->get_extent().height >> i; buffer_copy_region.imageExtent.depth = 1; buffer_copy_region.bufferOffset = offsets[layer][i]; buffer_copy_regions.push_back(buffer_copy_region); } } vk::ImageSubresourceRange subresource_range(vk::ImageAspectFlagBits::eColor, 0, vkb::to_u32(mipmaps.size()), 0, layers); // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy vkb::common::set_image_layout( command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, subresource_range); // Copy mip levels from staging buffer command_buffer.copyBufferToImage( stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, buffer_copy_regions); // Change texture image layout to shader read after all mip levels have been copied vkb::common::set_image_layout(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); // Create a defaultsampler vk::SamplerCreateInfo sampler_create_info; sampler_create_info.magFilter = vk::Filter::eLinear; sampler_create_info.minFilter = vk::Filter::eLinear; sampler_create_info.mipmapMode = vk::SamplerMipmapMode::eLinear; sampler_create_info.addressModeU = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.addressModeV = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.addressModeW = vk::SamplerAddressMode::eClampToEdge; sampler_create_info.mipLodBias = 0.0f; sampler_create_info.compareOp = vk::CompareOp::eNever; sampler_create_info.minLod = 0.0f; // Max level-of-detail should match mip level count sampler_create_info.maxLod = static_cast<float>(mipmaps.size()); // Only enable anisotropic filtering if enabled on the devicec sampler_create_info.maxAnisotropy = get_device().get_gpu().get_features().samplerAnisotropy ? get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy : 1.0f; sampler_create_info.anisotropyEnable = get_device().get_gpu().get_features().samplerAnisotropy; sampler_create_info.borderColor = vk::BorderColor::eFloatOpaqueWhite; texture.sampler = get_device().get_handle().createSampler(sampler_create_info); return texture; } std::unique_ptr<vkb::scene_graph::components::HPPSubMesh> HPPApiVulkanSample::load_model(const std::string &file, uint32_t index) { vkb::HPPGLTFLoader loader{get_device()}; std::unique_ptr<vkb::scene_graph::components::HPPSubMesh> model = loader.read_model_from_file(file, index); if (!model) { LOGE("Cannot load model from file: {}", file.c_str()); throw std::runtime_error("Cannot load model from: " + file); } return model; } void HPPApiVulkanSample::draw_model(std::unique_ptr<vkb::scene_graph::components::HPPSubMesh> &model, vk::CommandBuffer command_buffer) { vk::DeviceSize offset = 0; const auto &vertex_buffer = model->get_vertex_buffer("vertex_buffer"); auto & index_buffer = model->get_index_buffer(); command_buffer.bindVertexBuffers(0, vertex_buffer.get_handle(), offset); command_buffer.bindIndexBuffer(index_buffer.get_handle(), 0, model->get_index_type()); command_buffer.drawIndexed(model->vertex_indices, 1, 0, 0, 0); } void HPPApiVulkanSample::with_command_buffer(const std::function<void(vk::CommandBuffer command_buffer)> &f, vk::Semaphore signalSemaphore) { vk::CommandBuffer command_buffer = get_device().create_command_buffer(vk::CommandBufferLevel::ePrimary, true); f(command_buffer); get_device().flush_command_buffer(command_buffer, queue, true, signalSemaphore); }
38.063792
164
0.734167
jwinarske
d94b5d651e1fc92e91e4fa3aa375144b3e673f8c
1,674
hpp
C++
common/rendersystem.hpp
Mikko-Finell/bullet
0aa08008c58d4c6fb2c4e12322a8925257cecc1c
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-08-12T22:52:22.000Z
2020-08-12T22:52:22.000Z
common/rendersystem.hpp
Mikko-Finell/bullet
0aa08008c58d4c6fb2c4e12322a8925257cecc1c
[ "Naumen", "Condor-1.1", "MS-PL" ]
3
2019-06-19T19:15:26.000Z
2019-06-19T19:15:27.000Z
common/rendersystem.hpp
Mikko-Finell/bullet
0aa08008c58d4c6fb2c4e12322a8925257cecc1c
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#ifndef rendersystem_hpp #define rendersystem_hpp #include "sprite.hpp" #include "stl.hpp" #include "sfml.hpp" /** * RenderSystem * Base class for rendering gameobjects. */ class RenderSystem { protected: std::unordered_set<SpriteImpl *> sprites; sf::Texture & texture; std::vector<sf::Vertex> vs; public: virtual ~RenderSystem() {} RenderSystem(sf::Texture & tex); virtual void add(SpriteImpl * sprite, const std::string & caller); inline void add(SpriteImpl & sprite, const std::string & caller) { add(&sprite, caller); } // removes the sprite from set of sprites, preventing it from being drawn virtual void remove(SpriteImpl * sprite); virtual void draw(sf::RenderWindow & window) = 0; }; /** * WorldRender * RenderSystem that knows about the isometric tile * layering used in Bullet. */ class WorldRender : public RenderSystem { std::vector<SpriteImpl *> visible_sprites; public: using RenderSystem::RenderSystem; void remove(SpriteImpl * sprite) override; inline void remove(SpriteImpl & sprite) { remove(&sprite); } void draw(sf::RenderWindow & window) override; }; /** * UIRender * RenderSystem that uses simple layering appropriate * for UI. */ class UIRender : public RenderSystem { std::vector<SpriteImpl *> sorted_sprites; bool sorted = false; public: using RenderSystem::RenderSystem; void add(SpriteImpl * sprite, const std::string & caller) override; void remove(SpriteImpl * sprite) override; inline void remove(SpriteImpl & sprite) { remove(&sprite); } void draw(sf::RenderWindow & window) override; }; #endif
24.26087
77
0.685185
Mikko-Finell
d94c9ecc0a9d01b3e1c7f66f9a48abe0555e2c87
685
cpp
C++
ParallelEngine/animation.cpp
Archiving/ParallelEngine
53f287d6e71bcf323cfdad763c6b6818795ada7c
[ "MIT" ]
4
2019-07-29T14:35:17.000Z
2019-08-06T04:35:18.000Z
ParallelEngine/animation.cpp
Archiving/ParallelEngine
53f287d6e71bcf323cfdad763c6b6818795ada7c
[ "MIT" ]
6
2019-07-28T22:34:54.000Z
2019-08-29T07:18:04.000Z
ParallelEngine/animation.cpp
Archiving/ParallelEngine
53f287d6e71bcf323cfdad763c6b6818795ada7c
[ "MIT" ]
null
null
null
#include "animation.h" #include <iostream> Animation::Animation(ALLEGRO_BITMAP * img, int frameWidth, int frameHeight, int frameDelay, int maxFrames, int x, int y) : image(img), width(frameWidth), height(frameHeight), delay(frameDelay), numFrames(maxFrames) { currentFrame = 0; frameCount = 0; this->x = x; this->y = y; } Animation::~Animation() {} void Animation::update() { if (delay <= 0) return; frameCount++; if (frameCount >= delay) { frameCount = 0; currentFrame++; if (currentFrame >= numFrames) currentFrame = 0; } } void Animation::render(int x, int y) { al_draw_bitmap_region(image, this->x + currentFrame * width, this->y, width, height, x, y, 0); }
24.464286
123
0.681752
Archiving
d9539fbedcadbb7e5d6485aa4a514acb0adcf5f2
5,674
cpp
C++
sort/src/tracker.cpp
AsakusaRinne/tensorrt_yolov5_tracker
b9a3a6fc94710e8291d6a614ed2b04cbc4c56599
[ "MIT" ]
22
2021-03-03T10:16:37.000Z
2022-01-05T14:47:38.000Z
sort/src/tracker.cpp
AsakusaRinne/tensorrt_yolov5_tracker
b9a3a6fc94710e8291d6a614ed2b04cbc4c56599
[ "MIT" ]
3
2021-05-27T01:52:16.000Z
2021-07-13T08:49:30.000Z
sort/src/tracker.cpp
AsakusaRinne/tensorrt_yolov5_tracker
b9a3a6fc94710e8291d6a614ed2b04cbc4c56599
[ "MIT" ]
5
2021-03-23T07:13:05.000Z
2022-02-18T09:10:17.000Z
#include "tracker.h" Tracker::Tracker() { id_ = 0; } float Tracker::CalculateIou(const cv::Rect& det, const Track& track) { auto trk = track.GetStateAsBbox(); // get min/max points auto xx1 = std::max(det.tl().x, trk.tl().x); auto yy1 = std::max(det.tl().y, trk.tl().y); auto xx2 = std::min(det.br().x, trk.br().x); auto yy2 = std::min(det.br().y, trk.br().y); auto w = std::max(0, xx2 - xx1); auto h = std::max(0, yy2 - yy1); // calculate area of intersection and union float det_area = det.area(); float trk_area = trk.area(); auto intersection_area = w * h; float union_area = det_area + trk_area - intersection_area; auto iou = intersection_area / union_area; return iou; } void Tracker::HungarianMatching(const std::vector<std::vector<float>>& iou_matrix, size_t nrows, size_t ncols, std::vector<std::vector<float>>& association) { Matrix<float> matrix(nrows, ncols); // Initialize matrix with IOU values for (size_t i = 0 ; i < nrows ; i++) { for (size_t j = 0 ; j < ncols ; j++) { // Multiply by -1 to find max cost if (iou_matrix[i][j] != 0) { matrix(i, j) = -iou_matrix[i][j]; } else { // TODO: figure out why we have to assign value to get correct result matrix(i, j) = 1.0f; } } } // // Display begin matrix state. // for (size_t row = 0 ; row < nrows ; row++) { // for (size_t col = 0 ; col < ncols ; col++) { // std::cout.width(10); // std::cout << matrix(row,col) << ","; // } // std::cout << std::endl; // } // std::cout << std::endl; // Apply Kuhn-Munkres algorithm to matrix. Munkres<float> m; m.solve(matrix); // // Display solved matrix. // for (size_t row = 0 ; row < nrows ; row++) { // for (size_t col = 0 ; col < ncols ; col++) { // std::cout.width(2); // std::cout << matrix(row,col) << ","; // } // std::cout << std::endl; // } // std::cout << std::endl; for (size_t i = 0 ; i < nrows ; i++) { for (size_t j = 0 ; j < ncols ; j++) { association[i][j] = matrix(i, j); } } } void Tracker::AssociateDetectionsToTrackers(const std::vector<cv::Rect>& detection, std::map<int, Track>& tracks, std::map<int, cv::Rect>& matched, std::vector<cv::Rect>& unmatched_det, float iou_threshold) { // Set all detection as unmatched if no tracks existing if (tracks.empty()) { for (const auto& det : detection) { unmatched_det.push_back(det); } return; } std::vector<std::vector<float>> iou_matrix; // resize IOU matrix based on number of detection and tracks iou_matrix.resize(detection.size(), std::vector<float>(tracks.size())); std::vector<std::vector<float>> association; // resize association matrix based on number of detection and tracks association.resize(detection.size(), std::vector<float>(tracks.size())); // row - detection, column - tracks for (size_t i = 0; i < detection.size(); i++) { size_t j = 0; for (const auto& trk : tracks) { iou_matrix[i][j] = CalculateIou(detection[i], trk.second); j++; } } // Find association HungarianMatching(iou_matrix, detection.size(), tracks.size(), association); for (size_t i = 0; i < detection.size(); i++) { bool matched_flag = false; size_t j = 0; for (const auto& trk : tracks) { if (0 == association[i][j]) { // Filter out matched with low IOU if (iou_matrix[i][j] >= iou_threshold) { matched[trk.first] = detection[i]; matched_flag = true; } // It builds 1 to 1 association, so we can break from here break; } j++; } // if detection cannot match with any tracks if (!matched_flag) { unmatched_det.push_back(detection[i]); } } } void Tracker::Run(const std::vector<cv::Rect>& detections) { /*** Predict internal tracks from previous frame ***/ for (auto &track : tracks_) { track.second.Predict(); } // Hash-map between track ID and associated detection bounding box std::map<int, cv::Rect> matched; // vector of unassociated detections std::vector<cv::Rect> unmatched_det; // return values - matched, unmatched_det if (!detections.empty()) { AssociateDetectionsToTrackers(detections, tracks_, matched, unmatched_det); } /*** Update tracks with associated bbox ***/ for (const auto &match : matched) { const auto &ID = match.first; tracks_[ID].Update(match.second); } /*** Create new tracks for unmatched detections ***/ for (const auto &det : unmatched_det) { Track tracker; tracker.Init(det); // Create new track and generate new ID tracks_[id_++] = tracker; } /*** Delete lose tracked tracks ***/ for (auto it = tracks_.begin(); it != tracks_.end();) { if (it->second.coast_cycles_ > kMaxCoastCycles) { it = tracks_.erase(it); } else { it++; } } } std::map<int, Track> Tracker::GetTracks() { return tracks_; }
31.348066
85
0.527846
AsakusaRinne
d9561e5b654f0f2d887ec447b96bb9c62e313b7e
5,729
cpp
C++
pybindings/pyhdbscan.cpp
wangyiqiu/hdbscan
0f21522a4d34db040dd0cd6c6506ad39ed6f2a9e
[ "MIT" ]
7
2021-03-29T05:54:11.000Z
2021-12-28T04:13:10.000Z
pybindings/pyhdbscan.cpp
wangyiqiu/hdbscan
0f21522a4d34db040dd0cd6c6506ad39ed6f2a9e
[ "MIT" ]
1
2021-09-16T05:38:33.000Z
2021-09-16T22:18:26.000Z
pybindings/pyhdbscan.cpp
wangyiqiu/hdbscan
0f21522a4d34db040dd0cd6c6506ad39ed6f2a9e
[ "MIT" ]
3
2021-07-13T23:42:47.000Z
2021-12-05T12:55:20.000Z
#include "hdbscan/hdbscan.h" #include "hdbscan/point.h" #include "hdbscan/edge.h" #include <string> #include <limits> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/numpy.h> namespace py = pybind11; using namespace parlay; template<class T, class Seq> py::array_t<T> wrapArray2d(Seq& result_vec, ssize_t cols) { ssize_t rows = (ssize_t) result_vec.size() * (ssize_t) sizeof(typename Seq::value_type) / (ssize_t) sizeof(T); rows /= cols; std::vector<ssize_t> shape = { rows, cols }; std::vector<ssize_t> strides = { (ssize_t) sizeof(T) * cols, (ssize_t) sizeof(T) }; return py::array(py::buffer_info(result_vec.data(), /* data as contiguous array */ sizeof(T), /* size of one scalar */ py::format_descriptor<T>::format(), /* data type */ 2, /* number of dimensions */ shape, /* shape of the matrix */ strides /* strides for each axis */ )); } py::array_t<double> py_hdbscan(py::array_t<double, py::array::c_style | py::array::forcecast> array, size_t minPts) { if (array.ndim() != 2) throw std::runtime_error("Input should be 2-D NumPy array"); if (sizeof(pargeo::point<2>) != 16) throw std::runtime_error("sizeof(pargeo::point<2>) != 16, check point.h"); int dim = array.shape()[1]; size_t n = array.size() / dim; parlay::sequence<pargeo::dirEdge> result_vec; sequence<pargeo::wghEdge> E; if (dim == 2) { parlay::sequence<pargeo::point<2>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<2>(P, minPts); } else if (dim == 3) { parlay::sequence<pargeo::point<3>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<3>(P, minPts); } else if (dim == 4) { parlay::sequence<pargeo::point<4>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<4>(P, minPts); } else if (dim == 5) { parlay::sequence<pargeo::point<5>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<5>(P, minPts); } else if (dim == 6) { parlay::sequence<pargeo::point<6>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<6>(P, minPts); } else if (dim == 7) { parlay::sequence<pargeo::point<7>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<7>(P, minPts); } else if (dim == 8) { parlay::sequence<pargeo::point<8>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<8>(P, minPts); } else if (dim == 9) { parlay::sequence<pargeo::point<9>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<9>(P, minPts); } else if (dim == 10) { parlay::sequence<pargeo::point<10>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<10>(P, minPts); } else if (dim == 11) { parlay::sequence<pargeo::point<11>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<11>(P, minPts); } else if (dim == 12) { parlay::sequence<pargeo::point<12>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<12>(P, minPts); } else if (dim == 13) { parlay::sequence<pargeo::point<13>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<13>(P, minPts); } else if (dim == 14) { parlay::sequence<pargeo::point<14>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<14>(P, minPts); } else if (dim == 15) { parlay::sequence<pargeo::point<15>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<15>(P, minPts); } else if (dim == 16) { parlay::sequence<pargeo::point<16>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<16>(P, minPts); } else if (dim == 17) { parlay::sequence<pargeo::point<17>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<17>(P, minPts); } else if (dim == 18) { parlay::sequence<pargeo::point<18>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<18>(P, minPts); } else if (dim == 19) { parlay::sequence<pargeo::point<19>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<19>(P, minPts); } else if (dim == 20) { parlay::sequence<pargeo::point<20>> P(n); std::memcpy(P.data(), array.data(), array.size() * sizeof(double)); E = pargeo::hdbscan<20>(P, minPts); } else { throw std::runtime_error("Only dimensions 2-20 is supported at the moment"); } sequence<pargeo::dendroNode> dendro = pargeo::dendrogram(E, n); sequence<double> A(dendro.size()*4); parlay::parallel_for(0, dendro.size(), [&](size_t i){ A[i*4+0] = std::get<0>(dendro[i]); A[i*4+1] = std::get<1>(dendro[i]); A[i*4+2] = std::get<2>(dendro[i]); A[i*4+3] = std::get<3>(dendro[i]);}); return wrapArray2d<double>(A, 4); } PYBIND11_MODULE(pyhdbscan, m) { m.doc() = "Fast Parallel Algorithms for HDBSCAN*"; m.def("HDBSCAN", &py_hdbscan, "Hierarchical DBSCAN*", py::arg("array"), py::arg("minPts")); }
40.062937
117
0.579857
wangyiqiu
d9569c3daae5ab2508857810be13e24070662b22
6,383
hpp
C++
libraries/fc/include/fc/container/flat.hpp
theenemys/oasischain_inter
db968d4d0bd1a487f4edb4cb673fda481d24a06c
[ "MIT" ]
37
2018-06-14T07:17:36.000Z
2022-02-18T18:03:42.000Z
libraries/fc/include/fc/container/flat.hpp
theenemys/oasischain_inter
db968d4d0bd1a487f4edb4cb673fda481d24a06c
[ "MIT" ]
36
2018-07-14T16:18:20.000Z
2021-12-24T01:45:26.000Z
libraries/fc/include/fc/container/flat.hpp
theenemys/oasischain_inter
db968d4d0bd1a487f4edb4cb673fda481d24a06c
[ "MIT" ]
131
2017-05-31T02:15:02.000Z
2022-03-23T12:19:35.000Z
#pragma once #include <fc/container/flat_fwd.hpp> #include <fc/container/container_detail.hpp> #include <boost/container/flat_map.hpp> #include <boost/container/flat_set.hpp> #include <fc/crypto/hex.hpp> namespace fc { namespace raw { template<typename Stream, typename T, typename A> void pack( Stream& s, const boost::container::vector<T, A>& value ) { FC_ASSERT( value.size() <= MAX_NUM_ARRAY_ELEMENTS ); pack( s, unsigned_int((uint32_t)value.size()) ); if( !std::is_fundamental<T>::value ) { for( const auto& item : value ) { pack( s, item ); } } else if( value.size() ) { s.write( (const char*)value.data(), value.size() ); } } template<typename Stream, typename T, typename A> void unpack( Stream& s, boost::container::vector<T, A>& value ) { unsigned_int size; unpack( s, size ); FC_ASSERT( size.value <= MAX_NUM_ARRAY_ELEMENTS ); value.clear(); value.resize( size.value ); if( !std::is_fundamental<T>::value ) { for( auto& item : value ) { unpack( s, item ); } } else if( value.size() ) { s.read( (char*)value.data(), value.size() ); } } template<typename Stream, typename A> void pack( Stream& s, const boost::container::vector<char, A>& value ) { FC_ASSERT( value.size() <= MAX_SIZE_OF_BYTE_ARRAYS ); pack( s, unsigned_int((uint32_t)value.size()) ); if( value.size() ) s.write( (const char*)value.data(), value.size() ); } template<typename Stream, typename A> void unpack( Stream& s, boost::container::vector<char, A>& value ) { unsigned_int size; unpack( s, size ); FC_ASSERT( size.value <= MAX_SIZE_OF_BYTE_ARRAYS ); value.clear(); value.resize( size.value ); if( value.size() ) s.read( (char*)value.data(), value.size() ); } template<typename Stream, typename T, typename... U> void pack( Stream& s, const flat_set<T, U...>& value ) { detail::pack_set( s, value ); } template<typename Stream, typename T, typename... U> void unpack( Stream& s, flat_set<T, U...>& value ) { detail::unpack_flat_set( s, value ); } template<typename Stream, typename T, typename... U> void pack( Stream& s, const flat_multiset<T, U...>& value ) { detail::pack_set( s, value ); } template<typename Stream, typename T, typename... U> void unpack( Stream& s, flat_multiset<T, U...>& value ) { detail::unpack_flat_set( s, value ); } template<typename Stream, typename K, typename V, typename... U> void pack( Stream& s, const flat_map<K, V, U...>& value ) { detail::pack_map( s, value ); } template<typename Stream, typename K, typename V, typename... U> void unpack( Stream& s, flat_map<K, V, U...>& value ) { detail::unpack_flat_map( s, value ); } template<typename Stream, typename K, typename V, typename... U> void pack( Stream& s, const flat_multimap<K, V, U...>& value ) { detail::pack_map( s, value ); } template<typename Stream, typename K, typename V, typename... U> void unpack( Stream& s, flat_multimap<K, V, U...>& value ) { detail::unpack_flat_map( s, value ); } } // namespace raw template<typename T, typename... U> void to_variant( const boost::container::vector<T, U...>& vec, fc::variant& vo ) { FC_ASSERT( vec.size() <= MAX_NUM_ARRAY_ELEMENTS ); variants vars; vars.reserve( vec.size() ); for( const auto& item : vec ) { vars.emplace_back( item ); } vo = std::move(vars); } template<typename T, typename... U> void from_variant( const fc::variant& v, boost::container::vector<T, U...>& vec ) { const variants& vars = v.get_array(); FC_ASSERT( vars.size() <= MAX_NUM_ARRAY_ELEMENTS ); vec.clear(); vec.resize( vars.size() ); for( uint32_t i = 0; i < vars.size(); ++i ) { from_variant( vars[i], vec[i] ); } } template<typename... U> void to_variant( const boost::container::vector<char, U...>& vec, fc::variant& vo ) { FC_ASSERT( vec.size() <= MAX_SIZE_OF_BYTE_ARRAYS ); if( vec.size() ) vo = variant( fc::to_hex( vec.data(), vec.size() ) ); else vo = ""; } template<typename... U> void from_variant( const fc::variant& v, boost::container::vector<char, U...>& vec ) { const auto& str = v.get_string(); FC_ASSERT( str.size() <= 2*MAX_SIZE_OF_BYTE_ARRAYS ); // Doubled because hex strings needs two characters per byte vec.resize( str.size() / 2 ); if( vec.size() ) { size_t r = fc::from_hex( str, vec.data(), vec.size() ); FC_ASSERT( r == vec.size() ); } } template<typename T, typename... U> void to_variant( const flat_set< T, U... >& s, fc::variant& vo ) { detail::to_variant_from_set( s, vo ); } template<typename T, typename... U> void from_variant( const fc::variant& v, flat_set< T, U... >& s ) { detail::from_variant_to_flat_set( v, s ); } template<typename T, typename... U> void to_variant( const flat_multiset< T, U... >& s, fc::variant& vo ) { detail::to_variant_from_set( s, vo ); } template<typename T, typename... U> void from_variant( const fc::variant& v, flat_multiset< T, U... >& s ) { detail::from_variant_to_flat_set( v, s ); } template<typename K, typename V, typename... U > void to_variant( const flat_map< K, V, U... >& m, fc::variant& vo ) { detail::to_variant_from_map( m, vo ); } template<typename K, typename V, typename... U> void from_variant( const variant& v, flat_map<K, V, U...>& m ) { detail::from_variant_to_flat_map( v, m ); } template<typename K, typename V, typename... U > void to_variant( const flat_multimap< K, V, U... >& m, fc::variant& vo ) { detail::to_variant_from_map( m, vo ); } template<typename K, typename V, typename... U> void from_variant( const variant& v, flat_multimap<K, V, U...>& m ) { detail::from_variant_to_flat_map( v, m ); } }
34.13369
120
0.574025
theenemys
d95d2faee17dced9b66de9809813caec1c08cbc9
2,348
hh
C++
include/matrix.hh
KPO-2020-2021/zad3-Szymon-Sobczak
57a6409da5bd2971b71f93f4118d2e8c52b0f83d
[ "Unlicense" ]
null
null
null
include/matrix.hh
KPO-2020-2021/zad3-Szymon-Sobczak
57a6409da5bd2971b71f93f4118d2e8c52b0f83d
[ "Unlicense" ]
null
null
null
include/matrix.hh
KPO-2020-2021/zad3-Szymon-Sobczak
57a6409da5bd2971b71f93f4118d2e8c52b0f83d
[ "Unlicense" ]
null
null
null
#pragma once #include "size.hh" #include "vector.hh" #include <iostream> #include <cstdlib> #include <cmath> /************************************************************************************* | Klasa modelujaca w programie pojecie macierzy. | | Klasa posiada prywatne pole "value", stanowi ono zbior wartosci macierzy rotacji. | | Jest to tablica dwuwymiarowa dla warosci typu double. | | Klasa posiada publiczny interfejs pozwalajacy na wprowazdanie, | | zmiane i odczytywanie danych z macierzy rotacji. | | Klasa zawiera publiczne przeciazenia operatorow funkcyjnych opowiedzialnych | | za wprowadzanie i odczytywanie wartosci z macierzy rotacji, oraz przeciazenie | | operatora mnozenia macierzy razy wetkor i przeciazenia operatora dodawania | | dwoch macierzy. | | Klasa posiada metode inicjujaca macierz wartosciami funkcji trygonometrycznych | | dla zadanego konta obrotu. | | W roli modyfikacji zadania, dodano metode wyznaczajaca wyznacznik macierzy. | */ class Matrix{ private: double value[SIZE][SIZE]; /* Wartosci macierzy */ public: Matrix(); /* Bezparametryczny konstruktor klasy */ Matrix(double [SIZE][SIZE]); /* Konstruktor klasy z parametrem */ Vector operator * (Vector const &tmp); /* Operator mnożenia przez wektor */ Matrix operator + (Matrix const &tmp); /* Operator dodwania dwoch macierzy */ Matrix Fill_matrix (double const angle); /* Wypenienie macierzy wartosciami funkcji tryg. dla zadanego kąta obrotu */ double determinant_of_the_matrix() const; /* Obliczenie wyznacznika macierzy */ double & operator () (unsigned int row, unsigned int column); /* Przeciazenia operatora funkcyjnego */ const double & operator () (unsigned int row, unsigned int column) const; }; std::ostream & operator << (std::ostream &out, Matrix const &mat); /* Przeciazenie operatora << sluzace wyswietlaniu macierzy */ std::istream & operator >> (std::istream &in, Matrix &mat); /* Przeciazenie operatora >> sluzace wczytywaniu wartosci do macierzy */
55.904762
140
0.611584
KPO-2020-2021
d960c6dd1f2255bbe3434f92e1c3c1893370a74c
153
hpp
C++
src/source/util/bytestream.hpp
mvpwizard/DLA
5ead2574e61e619ca3a93f1e771e3988fc144928
[ "MIT" ]
1
2019-03-24T12:07:46.000Z
2019-03-24T12:07:46.000Z
src/source/util/bytestream.hpp
nepitdev/DLA
5ead2574e61e619ca3a93f1e771e3988fc144928
[ "MIT" ]
10
2019-03-06T20:27:39.000Z
2019-11-27T08:28:12.000Z
src/source/util/bytestream.hpp
openepit/DLA
5ead2574e61e619ca3a93f1e771e3988fc144928
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <cinttypes> namespace dla { class bytestream { public: virtual uint8_t next() = 0; }; }
11.769231
35
0.594771
mvpwizard
d960e1141f07857795002d6608cc9b2bfdcf3aa4
18,824
cpp
C++
Sample001/src/main.cpp
Monsho/D3D12Samples
4624fd64b57c12fee1085ecfba1f770f802a236c
[ "MIT" ]
32
2017-10-11T00:23:17.000Z
2022-01-02T14:08:56.000Z
Sample001/src/main.cpp
Monsho/D3D12Samples
4624fd64b57c12fee1085ecfba1f770f802a236c
[ "MIT" ]
null
null
null
Sample001/src/main.cpp
Monsho/D3D12Samples
4624fd64b57c12fee1085ecfba1f770f802a236c
[ "MIT" ]
6
2019-01-18T13:16:01.000Z
2021-09-07T09:43:20.000Z
#include <sl12/device.h> #include <sl12/swapchain.h> #include <sl12/command_queue.h> #include <sl12/command_list.h> #include <sl12/descriptor_heap.h> #include <sl12/descriptor.h> #include <sl12/texture.h> #include <sl12/texture_view.h> #include <sl12/sampler.h> #include <sl12/fence.h> #include <sl12/buffer.h> #include <sl12/buffer_view.h> #include <sl12/root_signature.h> #include <sl12/pipeline_state.h> #include <sl12/descriptor_set.h> #include <sl12/shader.h> #include <DirectXTex.h> #include "file.h" namespace { static const wchar_t* kWindowTitle = L"D3D12Sample"; static const int kWindowWidth = 1920; static const int kWindowHeight = 1080; //static const DXGI_FORMAT kDepthBufferFormat = DXGI_FORMAT_R32G8X24_TYPELESS; //static const DXGI_FORMAT kDepthViewFormat = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; static const DXGI_FORMAT kDepthBufferFormat = DXGI_FORMAT_R32_TYPELESS; static const DXGI_FORMAT kDepthViewFormat = DXGI_FORMAT_D32_FLOAT; HWND g_hWnd_; sl12::Device g_Device_; sl12::CommandList g_mainCmdList_; sl12::CommandList g_mainCmdLists_[sl12::Swapchain::kMaxBuffer]; sl12::CommandList* g_pNextCmdList_ = nullptr; sl12::CommandList g_copyCmdList_; sl12::Texture g_RenderTarget_; sl12::RenderTargetView g_RenderTargetView_; sl12::TextureView g_RenderTargetTexView_; sl12::Texture g_DepthBuffer_; sl12::DepthStencilView g_DepthBufferView_; sl12::TextureView g_DepthBufferTexView_; static const uint32_t kMaxCBs = sl12::Swapchain::kMaxBuffer * 2; sl12::Buffer g_CBScenes_[kMaxCBs]; void* g_pCBSceneBuffers_[kMaxCBs] = { nullptr }; sl12::ConstantBufferView g_CBSceneViews_[kMaxCBs]; sl12::Buffer g_vbuffers_[3]; sl12::VertexBufferView g_vbufferViews_[3]; sl12::Buffer g_ibuffer_; sl12::IndexBufferView g_ibufferView_; sl12::Texture g_texture_; sl12::TextureView g_textureView_; sl12::Sampler g_sampler_; sl12::Shader g_VShader_, g_PShader_; sl12::Shader g_VSScreenShader_, g_PSDispDepthShader_; sl12::RootSignature g_rootSig_; sl12::GraphicsPipelineState g_psoWriteS_; sl12::GraphicsPipelineState g_psoUseS_; sl12::DescriptorSet g_descSet_; } // Window Proc LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { // Handle destroy/shutdown messages. switch (message) { case WM_DESTROY: PostQuitMessage(0); return 0; } // Handle any messages the switch statement didn't. return DefWindowProc(hWnd, message, wParam, lParam); } // Windowの初期化 void InitWindow(HINSTANCE hInstance, int nCmdShow) { // Initialize the window class. WNDCLASSEX windowClass = { 0 }; windowClass.cbSize = sizeof(WNDCLASSEX); windowClass.style = CS_HREDRAW | CS_VREDRAW; windowClass.lpfnWndProc = WindowProc; windowClass.hInstance = hInstance; windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); windowClass.lpszClassName = L"WindowClass1"; RegisterClassEx(&windowClass); RECT windowRect = { 0, 0, kWindowWidth, kWindowHeight }; AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE); // Create the window and store a handle to it. g_hWnd_ = CreateWindowEx(NULL, L"WindowClass1", kWindowTitle, WS_OVERLAPPEDWINDOW, 300, 300, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, NULL, // We have no parent window, NULL. NULL, // We aren't using menus, NULL. hInstance, NULL); // We aren't using multiple windows, NULL. ShowWindow(g_hWnd_, nCmdShow); } bool InitializeAssets() { ID3D12Device* pDev = g_Device_.GetDeviceDep(); g_copyCmdList_.Reset(); // レンダーターゲットを作成 { sl12::TextureDesc texDesc; texDesc.dimension = sl12::TextureDimension::Texture2D; texDesc.width = kWindowWidth; texDesc.height = kWindowHeight; texDesc.format = DXGI_FORMAT_R16G16B16A16_FLOAT; texDesc.clearColor[0] = 0.0f; texDesc.clearColor[1] = 0.6f; texDesc.clearColor[2] = 0.0f; texDesc.clearColor[3] = 1.0f; texDesc.isRenderTarget = true; if (!g_RenderTarget_.Initialize(&g_Device_, texDesc)) { return false; } if (!g_RenderTargetView_.Initialize(&g_Device_, &g_RenderTarget_)) { return false; } if (!g_RenderTargetTexView_.Initialize(&g_Device_, &g_RenderTarget_)) { return false; } } // 深度バッファを作成 { sl12::TextureDesc texDesc; texDesc.dimension = sl12::TextureDimension::Texture2D; texDesc.width = kWindowWidth; texDesc.height = kWindowHeight; texDesc.format = kDepthViewFormat; texDesc.isDepthBuffer = true; if (!g_DepthBuffer_.Initialize(&g_Device_, texDesc)) { return false; } if (!g_DepthBufferView_.Initialize(&g_Device_, &g_DepthBuffer_)) { return false; } if (!g_DepthBufferTexView_.Initialize(&g_Device_, &g_DepthBuffer_)) { return false; } } // 定数バッファを作成 { D3D12_HEAP_PROPERTIES prop{}; prop.Type = D3D12_HEAP_TYPE_UPLOAD; prop.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; prop.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; prop.CreationNodeMask = 1; prop.VisibleNodeMask = 1; D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Alignment = 0; desc.Width = 256; desc.Height = 1; desc.DepthOrArraySize = 1; desc.MipLevels = 1; desc.Format = DXGI_FORMAT_UNKNOWN; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; for (int i = 0; i < _countof(g_CBScenes_); i++) { if (!g_CBScenes_[i].Initialize(&g_Device_, sizeof(DirectX::XMFLOAT4X4) * 3, 1, sl12::BufferUsage::ConstantBuffer, true, false)) { return false; } if (!g_CBSceneViews_[i].Initialize(&g_Device_, &g_CBScenes_[i])) { return false; } g_pCBSceneBuffers_[i] = g_CBScenes_[i].Map(&g_mainCmdList_); } } // 頂点バッファを作成 { { float positions[] = { -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, }; if (!g_vbuffers_[0].Initialize(&g_Device_, sizeof(positions), sizeof(float) * 3, sl12::BufferUsage::VertexBuffer, false, false)) { return false; } if (!g_vbufferViews_[0].Initialize(&g_Device_, &g_vbuffers_[0])) { return false; } g_vbuffers_[0].UpdateBuffer(&g_Device_, &g_copyCmdList_, positions, sizeof(positions)); } { uint32_t colors[] = { 0xff0000ff, 0xff00ff00, 0xffff0000, 0xffffffff }; if (!g_vbuffers_[1].Initialize(&g_Device_, sizeof(colors), sizeof(sl12::u32), sl12::BufferUsage::VertexBuffer, false, false)) { return false; } if (!g_vbufferViews_[1].Initialize(&g_Device_, &g_vbuffers_[1])) { return false; } g_vbuffers_[1].UpdateBuffer(&g_Device_, &g_copyCmdList_, colors, sizeof(colors)); } { float uvs[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f }; if (!g_vbuffers_[2].Initialize(&g_Device_, sizeof(uvs), sizeof(float) * 2, sl12::BufferUsage::VertexBuffer, false, false)) { return false; } if (!g_vbufferViews_[2].Initialize(&g_Device_, &g_vbuffers_[2])) { return false; } g_vbuffers_[2].UpdateBuffer(&g_Device_, &g_copyCmdList_, uvs, sizeof(uvs)); } } // インデックスバッファを作成 { uint32_t indices[] = { 0, 1, 2, 1, 3, 2 }; if (!g_ibuffer_.Initialize(&g_Device_, sizeof(indices), sizeof(sl12::u32), sl12::BufferUsage::IndexBuffer, false, false)) { return false; } if (!g_ibufferView_.Initialize(&g_Device_, &g_ibuffer_)) { return false; } g_ibuffer_.UpdateBuffer(&g_Device_, &g_copyCmdList_, indices, sizeof(indices)); } // テクスチャロード { File texFile("data/icon.tga"); if (!g_texture_.InitializeFromTGA(&g_Device_, &g_copyCmdList_, texFile.GetData(), texFile.GetSize(), 1, false)) { return false; } if (!g_textureView_.Initialize(&g_Device_, &g_texture_)) { return false; } } // サンプラ作成 { D3D12_SAMPLER_DESC desc{}; desc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP; desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; if (!g_sampler_.Initialize(&g_Device_, desc)) { return false; } } g_copyCmdList_.Close(); g_copyCmdList_.Execute(); sl12::Fence fence; fence.Initialize(&g_Device_); fence.Signal(g_copyCmdList_.GetParentQueue()); fence.WaitSignal(); fence.Destroy(); // シェーダロード if (!g_VShader_.Initialize(&g_Device_, sl12::ShaderType::Vertex, "data/VSSample.cso")) { return false; } if (!g_PShader_.Initialize(&g_Device_, sl12::ShaderType::Pixel, "data/PSSample.cso")) { return false; } if (!g_VSScreenShader_.Initialize(&g_Device_, sl12::ShaderType::Vertex, "data/VSScreen.cso")) { return false; } if (!g_PSDispDepthShader_.Initialize(&g_Device_, sl12::ShaderType::Pixel, "data/PSDispDepth.cso")) { return false; } // ルートシグネチャを作成 { if (!g_rootSig_.Initialize(&g_Device_, &g_VShader_, &g_PShader_, nullptr, nullptr, nullptr)) { return false; } } // PSOを作成 { D3D12_INPUT_ELEMENT_DESC elementDescs[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 2, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; sl12::GraphicsPipelineStateDesc desc{}; desc.rasterizer.fillMode = D3D12_FILL_MODE_SOLID; desc.rasterizer.cullMode = D3D12_CULL_MODE_NONE; desc.rasterizer.isFrontCCW = false; desc.rasterizer.isDepthClipEnable = true; desc.multisampleCount = 1; desc.blend.sampleMask = UINT_MAX; desc.blend.rtDesc[0].isBlendEnable = false; desc.blend.rtDesc[0].srcBlendColor = D3D12_BLEND_ONE; desc.blend.rtDesc[0].dstBlendColor = D3D12_BLEND_ZERO; desc.blend.rtDesc[0].blendOpColor = D3D12_BLEND_OP_ADD; desc.blend.rtDesc[0].srcBlendAlpha = D3D12_BLEND_ONE; desc.blend.rtDesc[0].dstBlendAlpha = D3D12_BLEND_ZERO; desc.blend.rtDesc[0].blendOpAlpha = D3D12_BLEND_OP_ADD; desc.blend.rtDesc[0].writeMask = D3D12_COLOR_WRITE_ENABLE_ALL; desc.depthStencil.isDepthEnable = true; desc.depthStencil.isDepthWriteEnable = true; desc.depthStencil.depthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL; desc.pRootSignature = &g_rootSig_; desc.pVS = &g_VShader_; desc.pPS = &g_PShader_; desc.primTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; desc.inputLayout.numElements = _countof(elementDescs); desc.inputLayout.pElements = elementDescs; desc.numRTVs = 0; desc.rtvFormats[desc.numRTVs++] = g_RenderTarget_.GetTextureDesc().format; desc.dsvFormat = g_DepthBuffer_.GetTextureDesc().format; if (!g_psoWriteS_.Initialize(&g_Device_, desc)) { return false; } desc.inputLayout.numElements = 0; desc.inputLayout.pElements = nullptr; desc.pVS = &g_VSScreenShader_; desc.pPS = &g_PSDispDepthShader_; desc.depthStencil.isDepthEnable = false; desc.numRTVs = 0; desc.rtvFormats[desc.numRTVs++] = DXGI_FORMAT_R8G8B8A8_UNORM; desc.dsvFormat = DXGI_FORMAT_UNKNOWN; if (!g_psoUseS_.Initialize(&g_Device_, desc)) { return false; } } return true; } void DestroyAssets() { g_psoWriteS_.Destroy(); g_psoUseS_.Destroy(); g_rootSig_.Destroy(); g_VSScreenShader_.Destroy(); g_PSDispDepthShader_.Destroy(); g_VShader_.Destroy(); g_PShader_.Destroy(); g_sampler_.Destroy(); g_textureView_.Destroy(); g_texture_.Destroy(); for (auto& v : g_vbufferViews_) { v.Destroy(); } for (auto& v : g_vbuffers_) { v.Destroy(); } g_ibufferView_.Destroy(); g_ibuffer_.Destroy(); for (auto& v : g_CBSceneViews_) { v.Destroy(); } for (auto& v : g_CBScenes_) { v.Unmap(); v.Destroy(); } g_DepthBufferTexView_.Destroy(); g_DepthBufferView_.Destroy(); g_DepthBuffer_.Destroy(); g_RenderTargetTexView_.Destroy(); g_RenderTargetView_.Destroy(); g_RenderTarget_.Destroy(); } void RenderScene() { if (g_pNextCmdList_) g_pNextCmdList_->Execute(); g_Device_.SyncKillObjects(); int32_t frameIndex = (g_Device_.GetSwapchain().GetFrameIndex() + 1) % sl12::Swapchain::kMaxBuffer; g_pNextCmdList_ = &g_mainCmdLists_[frameIndex]; g_pNextCmdList_->Reset(); static bool s_InitFrame = true; if (s_InitFrame) { g_pNextCmdList_->TransitionBarrier(&g_texture_, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); for (auto& v : g_vbuffers_) { g_pNextCmdList_->TransitionBarrier(&v, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); } g_pNextCmdList_->TransitionBarrier(&g_ibuffer_, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER); s_InitFrame = false; } auto scTex = g_Device_.GetSwapchain().GetCurrentTexture(1); D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_Device_.GetSwapchain().GetCurrentDescHandle(1); D3D12_CPU_DESCRIPTOR_HANDLE rtvOffHandle = g_RenderTargetView_.GetDescInfo().cpuHandle; D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = g_DepthBufferView_.GetDescInfo().cpuHandle; ID3D12GraphicsCommandList* pCmdList = g_pNextCmdList_->GetCommandList(); g_pNextCmdList_->TransitionBarrier(scTex, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); g_pNextCmdList_->TransitionBarrier(&g_RenderTarget_, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_RENDER_TARGET); g_pNextCmdList_->TransitionBarrier(&g_DepthBuffer_, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_DEPTH_WRITE); // 画面クリア const float kClearColor[] = { 0.0f, 0.0f, 0.6f, 1.0f }; pCmdList->ClearRenderTargetView(rtvHandle, kClearColor, 0, nullptr); pCmdList->ClearRenderTargetView(rtvOffHandle, g_RenderTarget_.GetTextureDesc().clearColor, 0, nullptr); pCmdList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, g_DepthBuffer_.GetTextureDesc().clearDepth, g_DepthBuffer_.GetTextureDesc().clearStencil, 0, nullptr); // Viewport + Scissor設定 D3D12_VIEWPORT viewport{ 0.0f, 0.0f, (float)kWindowWidth, (float)kWindowHeight, 0.0f, 1.0f }; D3D12_RECT scissor{ 0, 0, kWindowWidth, kWindowHeight }; pCmdList->RSSetViewports(1, &viewport); pCmdList->RSSetScissorRects(1, &scissor); // Scene定数バッファを更新 auto&& cbScene = g_CBSceneViews_[frameIndex]; auto&& cbPrevScene = g_CBSceneViews_[frameIndex + sl12::Swapchain::kMaxBuffer]; { static float sAngle = 0.0f; void* p0 = g_pCBSceneBuffers_[frameIndex]; DirectX::XMFLOAT4X4* pMtxs = reinterpret_cast<DirectX::XMFLOAT4X4*>(p0); DirectX::XMMATRIX mtxW = DirectX::XMMatrixRotationY(sAngle * DirectX::XM_PI / 180.0f); DirectX::FXMVECTOR eye = DirectX::XMLoadFloat3(&DirectX::XMFLOAT3(0.0f, 5.0f, 10.0f)); DirectX::FXMVECTOR focus = DirectX::XMLoadFloat3(&DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f)); DirectX::FXMVECTOR up = DirectX::XMLoadFloat3(&DirectX::XMFLOAT3(0.0f, 1.0f, 0.0f)); DirectX::XMMATRIX mtxV = DirectX::XMMatrixLookAtRH(eye, focus, up); DirectX::XMMATRIX mtxP = DirectX::XMMatrixPerspectiveFovRH(60.0f * DirectX::XM_PI / 180.0f, (float)kWindowWidth / (float)kWindowHeight, 1.0f, 100000.0f); DirectX::XMStoreFloat4x4(pMtxs + 0, mtxW); DirectX::XMStoreFloat4x4(pMtxs + 1, mtxV); DirectX::XMStoreFloat4x4(pMtxs + 2, mtxP); void* p1 = g_pCBSceneBuffers_[frameIndex + sl12::Swapchain::kMaxBuffer]; memcpy(p1, p0, sizeof(DirectX::XMFLOAT4X4) * 3); pMtxs = reinterpret_cast<DirectX::XMFLOAT4X4*>(p1); mtxW = DirectX::XMMatrixTranslation(0.5f, 0.0f, 0.5f) * DirectX::XMMatrixScaling(4.0f, 2.0f, 1.0f); DirectX::XMStoreFloat4x4(pMtxs + 0, mtxW); sAngle += 1.0f; } { // レンダーターゲット設定 pCmdList->OMSetRenderTargets(1, &rtvOffHandle, false, &dsvHandle); pCmdList->SetPipelineState(g_psoWriteS_.GetPSO()); g_descSet_.Reset(); g_descSet_.SetVsCbv(0, cbScene.GetDescInfo().cpuHandle); g_descSet_.SetPsSrv(0, g_textureView_.GetDescInfo().cpuHandle); g_descSet_.SetPsSampler(0, g_sampler_.GetDescInfo().cpuHandle); g_pNextCmdList_->SetGraphicsRootSignatureAndDescriptorSet(&g_rootSig_, &g_descSet_); // DrawCall D3D12_VERTEX_BUFFER_VIEW views[] = { g_vbufferViews_[0].GetView(), g_vbufferViews_[1].GetView(), g_vbufferViews_[2].GetView() }; pCmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); pCmdList->IASetVertexBuffers(0, _countof(views), views); pCmdList->IASetIndexBuffer(&g_ibufferView_.GetView()); pCmdList->DrawIndexedInstanced(6, 1, 0, 0, 0); } g_pNextCmdList_->TransitionBarrier(&g_RenderTarget_, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_GENERIC_READ); g_pNextCmdList_->TransitionBarrier(&g_DepthBuffer_, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_GENERIC_READ); { // レンダーターゲット設定 pCmdList->OMSetRenderTargets(1, &rtvHandle, false, nullptr); //pCmdList->OMSetRenderTargets(1, &rtvHandle, false, &dsvHandle); pCmdList->SetPipelineState(g_psoUseS_.GetPSO()); pCmdList->OMSetStencilRef(0xf); g_descSet_.Reset(); g_descSet_.SetVsCbv(0, cbPrevScene.GetDescInfo().cpuHandle); g_descSet_.SetPsSrv(0, g_DepthBufferTexView_.GetDescInfo().cpuHandle); g_descSet_.SetPsSampler(0, g_sampler_.GetDescInfo().cpuHandle); g_pNextCmdList_->SetGraphicsRootSignatureAndDescriptorSet(&g_rootSig_, &g_descSet_); // DrawCall D3D12_VERTEX_BUFFER_VIEW views[] = { g_vbufferViews_[0].GetView(), g_vbufferViews_[1].GetView(), g_vbufferViews_[2].GetView() }; pCmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); pCmdList->IASetVertexBuffers(0, _countof(views), views); pCmdList->IASetIndexBuffer(&g_ibufferView_.GetView()); pCmdList->DrawIndexedInstanced(6, 1, 0, 0, 0); } g_pNextCmdList_->TransitionBarrier(scTex, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); g_pNextCmdList_->Close(); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow) { InitWindow(hInstance, nCmdShow); std::array<uint32_t, D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES> kDescNums { 100, 100, 20, 10 }; auto ret = g_Device_.Initialize(g_hWnd_, kWindowWidth, kWindowHeight, kDescNums); assert(ret); ret = g_mainCmdList_.Initialize(&g_Device_, &g_Device_.GetGraphicsQueue()); assert(ret); for (int i = 0; i < _countof(g_mainCmdLists_); ++i) { ret = g_mainCmdLists_[i].Initialize(&g_Device_, &g_Device_.GetGraphicsQueue()); assert(ret); } ret = g_copyCmdList_.Initialize(&g_Device_, &g_Device_.GetCopyQueue()); assert(ret); ret = InitializeAssets(); assert(ret); // メインループ MSG msg = { 0 }; while (true) { // Process any messages in the queue. if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_QUIT) break; } g_Device_.WaitPresent(); RenderScene(); g_Device_.Present(); g_Device_.WaitDrawDone(); } g_Device_.WaitDrawDone(); DestroyAssets(); g_copyCmdList_.Destroy(); for (int i = 0; i < _countof(g_mainCmdLists_); ++i) { g_mainCmdLists_[i].Destroy(); } g_mainCmdList_.Destroy(); g_Device_.Destroy(); return static_cast<char>(msg.wParam); }
29.184496
197
0.740703
Monsho
d9632bf50b6a41f647f6954a10d20645a2a9c57c
18,384
hpp
C++
src/sim-driver/SimCallbacks.hpp
LoganBarnes/SimulationDriver
25b68b653afa81f3b55681513d3dd99fd36f6a5e
[ "MIT" ]
null
null
null
src/sim-driver/SimCallbacks.hpp
LoganBarnes/SimulationDriver
25b68b653afa81f3b55681513d3dd99fd36f6a5e
[ "MIT" ]
1
2018-02-24T11:47:26.000Z
2018-02-24T11:47:26.000Z
src/sim-driver/SimCallbacks.hpp
LoganBarnes/SimulationDriver
25b68b653afa81f3b55681513d3dd99fd36f6a5e
[ "MIT" ]
null
null
null
#pragma once #include <sim-driver/CallbackWrapper.hpp> #include <sim-driver/SimData.hpp> #include <memory> #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> namespace sim { template <size_t N> struct priority_tag : public priority_tag<N - 1> { }; template <> struct priority_tag<0> { }; template <typename C = EmptyCallbacks> class SimCallbacks { public: explicit SimCallbacks(SimData *pSimData, C *pCallbacks = nullptr); void framebufferSizeCallback(GLFWwindow *pWindow, int width, int height); void windowFocusCallback(GLFWwindow *pWindow, int focus); void mouseButtonCallback(GLFWwindow *pWindow, int button, int action, int mods); void keyCallback(GLFWwindow *pWindow, int key, int scancode, int action, int mods); void cursorPosCallback(GLFWwindow *pWindow, double xpos, double ypos); void scrollCallback(GLFWwindow *pWindow, double xoffset, double yoffset); void charCallback(GLFWwindow *pWindow, unsigned codepoint); bool isLeftMouseDown() const; bool isRightMouseDown() const; bool isShiftDown() const; bool isCtrlDown() const; private: SimData *pSimData_; C *pCallbacks_; sim::priority_tag<2> p_; bool leftMouseDown_{false}; bool rightMouseDown_{false}; bool shiftDown_{false}; bool ctrlDown_{false}; double prevX_; double prevY_; template <typename T> auto framebufferSizeCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int width, int height, priority_tag<2> p) -> decltype(callbacks.framebufferSizeCallback(window, width, height, parent), void()); template <typename T> auto framebufferSizeCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int width, int height, priority_tag<1> p) -> decltype(callbacks.framebufferSizeCallback(window, width, height), void()); template <typename T> void framebufferSizeCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int width, int height, priority_tag<0> p); template <typename T> auto windowFocusCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int focus, priority_tag<2> p) -> decltype(callbacks.windowFocusCallback(window, focus, parent), void()); template <typename T> auto windowFocusCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int focus, priority_tag<1> p) -> decltype(callbacks.windowFocusCallback(window, focus), void()); template <typename T> void windowFocusCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int focus, priority_tag<0> p); template <typename T> auto mouseButtonCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int button, int action, int mods, priority_tag<2> p) -> decltype(callbacks.mouseButtonCallback(window, button, action, mods, parent), void()); template <typename T> auto mouseButtonCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int button, int action, int mods, priority_tag<1> p) -> decltype(callbacks.mouseButtonCallback(window, button, action, mods), void()); template <typename T> void mouseButtonCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int button, int action, int mods, priority_tag<0> p); template <typename T> auto keyCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int key, int scancode, int action, int mods, priority_tag<2> p) -> decltype(callbacks.keyCallback(window, key, scancode, action, mods, parent), void()); template <typename T> auto keyCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int key, int scancode, int action, int mods, priority_tag<1> p) -> decltype(callbacks.keyCallback(window, key, scancode, action, mods), void()); template <typename T> void keyCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int key, int scancode, int action, int mods, priority_tag<0> p); template <typename T> auto cursorPosCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xpos, double ypos, priority_tag<2> p) -> decltype(callbacks.cursorPosCallback(window, xpos, ypos, parent), void()); template <typename T> auto cursorPosCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xpos, double ypos, priority_tag<1> p) -> decltype(callbacks.cursorPosCallback(window, xpos, ypos), void()); template <typename T> void cursorPosCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xpos, double ypos, priority_tag<0> p); template <typename T> auto scrollCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xoffset, double yoffset, priority_tag<2> p) -> decltype(callbacks.scrollCallback(window, xoffset, yoffset, parent), void()); template <typename T> auto scrollCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xoffset, double yoffset, priority_tag<1> p) -> decltype(callbacks.scrollCallback(window, xoffset, yoffset), void()); template <typename T> void scrollCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xoffset, double yoffset, priority_tag<0> p); template <typename T> auto charCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, unsigned codepoint, priority_tag<2> p) -> decltype(callbacks.charCallback(window, codepoint, parent), void()); template <typename T> auto charCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, unsigned codepoint, priority_tag<1> p) -> decltype(callbacks.charCallback(window, codepoint), void()); template <typename T> void charCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, unsigned codepoint, priority_tag<0> p); }; template <typename C> SimCallbacks<C>::SimCallbacks(SimData *pSimData, C *pCallbacks) : pSimData_{pSimData}, pCallbacks_(pCallbacks) { } template <typename C> void SimCallbacks<C>::framebufferSizeCallback(GLFWwindow *pWindow, int width, int height) { if (pSimData_) { pSimData_->camera().setAspectRatio(static_cast<float>(width) / height); } if (pCallbacks_) { framebufferSizeCallback(*pCallbacks_, *this, pWindow, width, height, p_); } } template <typename C> void SimCallbacks<C>::windowFocusCallback(GLFWwindow *pWindow, int focus) { if (pCallbacks_) { windowFocusCallback(*pCallbacks_, *this, pWindow, focus, p_); } } template <typename C> void SimCallbacks<C>::mouseButtonCallback(GLFWwindow *pWindow, int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_1) { if (action == GLFW_PRESS) { leftMouseDown_ = true; glfwGetCursorPos(pWindow, &prevX_, &prevY_); } else if (action == GLFW_RELEASE) { leftMouseDown_ = false; } } else if (button == GLFW_MOUSE_BUTTON_2) { if (action == GLFW_PRESS) { rightMouseDown_ = true; glfwGetCursorPos(pWindow, &prevX_, &prevY_); } else if (action == GLFW_RELEASE) { rightMouseDown_ = false; } } if (pCallbacks_) { mouseButtonCallback(*pCallbacks_, *this, pWindow, button, action, mods, p_); } } template <typename C> void SimCallbacks<C>::keyCallback(GLFWwindow *pWindow, int key, int scancode, int action, int mods) { switch (key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(pWindow, GLFW_TRUE); break; case GLFW_KEY_S: if (action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) { // save something? } break; case GLFW_KEY_P: if (pSimData_ && action == GLFW_RELEASE) { pSimData_->paused = !(pSimData_->paused); } default: break; } shiftDown_ = (mods == GLFW_MOD_SHIFT); ctrlDown_ = (mods == GLFW_MOD_CONTROL); if (pCallbacks_) { keyCallback(*pCallbacks_, *this, pWindow, key, scancode, action, mods, p_); } } template <typename C> void SimCallbacks<C>::cursorPosCallback(GLFWwindow *pWindow, double xpos, double ypos) { if (pSimData_) { if (leftMouseDown_) { pSimData_->cameraMover.pitch(static_cast<float>(prevY_ - ypos)); pSimData_->cameraMover.yaw(static_cast<float>(prevX_ - xpos)); } else if (rightMouseDown_) { pSimData_->cameraMover.zoom(static_cast<float>(prevY_ - ypos)); } } prevX_ = xpos; prevY_ = ypos; if (pCallbacks_) { cursorPosCallback(*pCallbacks_, *this, pWindow, xpos, ypos, p_); } } template <typename C> void SimCallbacks<C>::scrollCallback(GLFWwindow *pWindow, double xoffset, double yoffset) { if (pSimData_) { pSimData_->cameraMover.zoom(static_cast<float>(-yoffset)); } if (pCallbacks_) { scrollCallback(*pCallbacks_, *this, pWindow, xoffset, yoffset, p_); } } template <typename C> void SimCallbacks<C>::charCallback(GLFWwindow *pWindow, unsigned codepoint) { if (pCallbacks_) { charCallback(*pCallbacks_, *this, pWindow, codepoint, p_); } } /////////////////////////////////////// Private implementation functions /////////////////////////////////////// template <typename C> template <typename T> auto SimCallbacks<C>::framebufferSizeCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int width, int height, priority_tag<2>) -> decltype(callbacks.framebufferSizeCallback(window, width, height, parent), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.framebufferSizeCallback(window, width, height, parent); } template <typename C> template <typename T> auto SimCallbacks<C>::framebufferSizeCallback( T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, int width, int height, priority_tag<1>) -> decltype(callbacks.framebufferSizeCallback(window, width, height), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.framebufferSizeCallback(window, width, height); } template <typename C> template <typename T> auto SimCallbacks<C>::windowFocusCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int focus, priority_tag<2>) -> decltype(callbacks.windowFocusCallback(window, focus, parent), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.windowFocusCallback(window, focus, parent); } template <typename C> template <typename T> auto SimCallbacks<C>::windowFocusCallback( T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, int focus, priority_tag<1>) -> decltype(callbacks.windowFocusCallback(window, focus), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.windowFocusCallback(window, focus); } template <typename C> template <typename T> auto SimCallbacks<C>::mouseButtonCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int button, int action, int mods, priority_tag<2>) -> decltype(callbacks.mouseButtonCallback(window, button, action, mods, parent), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.mouseButtonCallback(window, button, action, mods, parent); } template <typename C> template <typename T> auto SimCallbacks<C>::mouseButtonCallback( T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, int button, int action, int mods, priority_tag<1>) -> decltype(callbacks.mouseButtonCallback(window, button, action, mods), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.mouseButtonCallback(window, button, action, mods); } template <typename C> template <typename T> auto SimCallbacks<C>::keyCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int key, int scancode, int action, int mods, priority_tag<2>) -> decltype(callbacks.keyCallback(window, key, scancode, action, mods, parent), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.keyCallback(window, key, scancode, action, mods, parent); } template <typename C> template <typename T> auto SimCallbacks<C>::keyCallback(T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, int key, int scancode, int action, int mods, priority_tag<1>) -> decltype(callbacks.keyCallback(window, key, scancode, action, mods), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.keyCallback(window, key, scancode, action, mods); } template <typename C> template <typename T> auto SimCallbacks<C>::cursorPosCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xpos, double ypos, priority_tag<2>) -> decltype(callbacks.cursorPosCallback(window, xpos, ypos, parent), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.cursorPosCallback(window, xpos, ypos, parent); } template <typename C> template <typename T> auto SimCallbacks<C>::cursorPosCallback( T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, double xpos, double ypos, priority_tag<1>) -> decltype(callbacks.cursorPosCallback(window, xpos, ypos), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.cursorPosCallback(window, xpos, ypos); } template <typename C> template <typename T> auto SimCallbacks<C>::scrollCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xoffset, double yoffset, priority_tag<2>) -> decltype(callbacks.scrollCallback(window, xoffset, yoffset, parent), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.scrollCallback(window, xoffset, yoffset, parent); } template <typename C> template <typename T> auto SimCallbacks<C>::scrollCallback( T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, double xoffset, double yoffset, priority_tag<1>) -> decltype(callbacks.scrollCallback(window, xoffset, yoffset), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.scrollCallback(window, xoffset, yoffset); } template <typename C> template <typename T> auto SimCallbacks<C>::charCallback( T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, unsigned codepoint, priority_tag<2>) -> decltype(callbacks.charCallback(window, codepoint, parent), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.charCallback(window, codepoint, parent); } template <typename C> template <typename T> auto SimCallbacks<C>::charCallback( T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, unsigned codepoint, priority_tag<1>) -> decltype(callbacks.charCallback(window, codepoint), void()) { static_assert(std::is_same<T, C>::value, ""); callbacks.charCallback(window, codepoint); } /////////////////////////////////////// Empty implementation functions /////////////////////////////////////// template <typename C> template <typename T> void SimCallbacks<C>::framebufferSizeCallback(T &, const SimCallbacks<T> &, GLFWwindow *, int, int, priority_tag<0>) { } template <typename C> template <typename T> void SimCallbacks<C>::windowFocusCallback(T &, const SimCallbacks<T> &, GLFWwindow *, int, priority_tag<0>) { } template <typename C> template <typename T> void SimCallbacks<C>::mouseButtonCallback(T &, const SimCallbacks<T> &, GLFWwindow *, int, int, int, priority_tag<0>) { } template <typename C> template <typename T> void SimCallbacks<C>::keyCallback(T &, const SimCallbacks<T> &, GLFWwindow *, int, int, int, int, priority_tag<0>) { } template <typename C> template <typename T> void SimCallbacks<C>::cursorPosCallback(T &, const SimCallbacks<T> &, GLFWwindow *, double, double, priority_tag<0>) { } template <typename C> template <typename T> void SimCallbacks<C>::scrollCallback(T &, const SimCallbacks<T> &, GLFWwindow *, double, double, priority_tag<0>) { } template <typename C> template <typename T> void SimCallbacks<C>::charCallback(T &, const SimCallbacks<T> &, GLFWwindow *, unsigned, priority_tag<0>) { } template <typename C> bool SimCallbacks<C>::isLeftMouseDown() const { return leftMouseDown_; } template <typename C> bool SimCallbacks<C>::isRightMouseDown() const { return rightMouseDown_; } template <typename C> bool SimCallbacks<C>::isShiftDown() const { return shiftDown_; } template <typename C> bool SimCallbacks<C>::isCtrlDown() const { return ctrlDown_; } } // namespace sim
36.260355
120
0.631364
LoganBarnes
d96cf49e6730cb56c4d72e6b5a8efcb85d7a8ad9
6,513
cpp
C++
OPERA-LG/src/GapCorrecter.cpp
lorenzgerber/OPERA-MS
bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f
[ "MIT" ]
81
2018-03-22T15:01:08.000Z
2022-01-17T17:52:31.000Z
OPERA-LG/src/GapCorrecter.cpp
lorenzgerber/OPERA-MS
bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f
[ "MIT" ]
68
2017-09-14T08:17:53.000Z
2022-03-09T18:56:12.000Z
OPERA-LG/src/GapCorrecter.cpp
lorenzgerber/OPERA-MS
bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f
[ "MIT" ]
21
2017-09-14T06:15:18.000Z
2021-09-30T03:19:22.000Z
#include "GapCorrecter.h" GapCorrecter::GapCorrecter(void){ m_gapList = new vector<Gap*>; } GapCorrecter::GapCorrecter( int max, int min, int contigLength, int mean, int std, int readLength, vector<double> *pos ){ m_gapList = new vector<Gap*>(); m_contigLength = 0; m_contigLength = contigLength; m_maxGapSize = max; // should be the max insert size - read length m_minGapSize = 0; m_minGapSize = min; m_mean = mean; m_std = std; m_possibility = pos; m_readLength = 0; m_readLength = readLength; m_useNormalDistribution = true; int sum = 0; for( int i = 0; i < (int) pos->size(); i++ ){ sum += pos->at( i ); } if( sum <= 100000 ){ //cerr<<"use normal distribution\n"; m_useNormalDistribution = true; } else m_useNormalDistribution = false; Init(); } GapCorrecter::~GapCorrecter(void){ for( int i = 0; i < (int) m_gapList->size(); i++ ){ delete m_gapList->at( i ); } m_gapList->clear(); delete m_gapList; } void GapCorrecter::Init(){ for( int i = 0; i <= m_maxGapSize; i++ ){ Gap *newGap = new Gap(); newGap->m_realGapSize = i; m_gapList->push_back( newGap ); } } // construct the relationship between real gap size and estimated gap size void GapCorrecter::CalculateTable(){ //cerr<<"mean: "<<m_mean<<endl; m_minEstimatedGapSize = 0; m_maxEstimatedGapSize = 0; //bool startIsZero = true; //bool endIsZero = false; // for gap = 0, // calculate summation of i*P(i) from g to g+c // calculate summation of P(i) from g to g+c double numerator = 0; double denominator = 0; for( int i = m_readLength; i <= m_contigLength; i++ ){ double possibility = CalculatePossibility( i ); //double possibility = m_possibility->at( i ); numerator += i * possibility; denominator += possibility; } // calculate new mu double newMu; if( denominator == 0 ) newMu = 0; else newMu = numerator / denominator; // calculate estimated gap size // g_head = g - mu_head + mu double newGapSize; if( m_contigLength >= m_minGapSize ) newGapSize = 0 - newMu + m_mean; else newGapSize = 0; m_gapList->at( 0 )->m_estimatedGapSize = newGapSize; m_gapList->at( 0 )->m_newMu = newMu; if( newGapSize != 0 ) m_minEstimatedGapSize = newGapSize; if( newGapSize > m_maxEstimatedGapSize ) m_maxEstimatedGapSize = newGapSize; // for gap g from 1 to max for( int i = 1; i < (int) m_gapList->size(); i++ ){ double possibilityGM1 = CalculatePossibility( i - 1 + m_readLength); double possibilityGPC = CalculatePossibility( i + m_contigLength ); //double possibilityGM1 = m_possibility->at( i - 1 ); //double possibilityGPC = m_possibility->at( i + m_contigLength ); // update i*P(i): minus (g-1)P(g-1), plus (g+c)P(g+c) numerator -= (i - 1 + m_readLength) * possibilityGM1; numerator += (i + m_contigLength) * possibilityGPC; // update P(i): minus P(g-1), plus P(g+c) denominator -= possibilityGM1; denominator += possibilityGPC; // calculate new mu if( denominator > 0 ) newMu = numerator / denominator; else newMu = 0; // calculate estimated gap size double newGapSize; if( denominator > 0 ) newGapSize = i - newMu + m_mean; else newGapSize = 0; if( newGapSize > m_maxEstimatedGapSize ) m_maxEstimatedGapSize = newGapSize; if( m_minEstimatedGapSize == 0 && newGapSize != 0 ) m_minEstimatedGapSize = newGapSize; m_gapList->at( i )->m_estimatedGapSize = newGapSize; m_gapList->at( i )->m_newMu = newMu; } } // calculate the possibility of a certain value double GapCorrecter::CalculatePossibility( int value ){ if( m_useNormalDistribution ){ // use normal distribution double result = exp( -pow(value - m_mean, 2)/(2 * m_std * m_std) ); return result * 10000; } else{ double result; if( value >= (int) m_possibility->size() ) result = 0; else result = m_possibility->at( value ); return result; } } // print the constructed table int GapCorrecter::PrintTable( string fileName ){ ofstream tableWriter( (Configure::OUTPUT_FOLDER + fileName).c_str() ); if( tableWriter.fail() ){ cout<<"ERROR: Cannot open "<<(Configure::OUTPUT_FOLDER + fileName)<<" file"<<endl; return -1; } string results; results = "read_gap_size\testimated_gap_size\tnew_mean\n"; for( int i = 0; i < (int) m_gapList->size(); i++ ){ results.append( itos( i ) + "\t" + itos( m_gapList->at( i )->m_estimatedGapSize ) + "\t" + itos( m_gapList->at( i )->m_newMu ) + "\n" ); } tableWriter.write( results.c_str(), results.length() ); tableWriter.close(); return 1; } // get the corresponding real gap size of a given estimated gap size int GapCorrecter::GetRealGapSize( double estimatedGapSize ) { //cout<<"Estimated gap size is: "<<estimatedGapSize<<endl; //cerr<<"Get real gaps size\n"; // if the value is too small if( estimatedGapSize < m_minEstimatedGapSize ) return estimatedGapSize; // if the value is too big if( estimatedGapSize > m_maxEstimatedGapSize ){ // bigger than the tail value, just use the tail value //int number = 0; //double sum = 0; for( int i = m_gapList->size() - 1; i >= 0; i-- ){ if( i == 0 ){ continue; } if( m_gapList->at( i )->m_estimatedGapSize > 0 ){ //== m_maxEstimatedGapSize ){ return i; //number++; //sum += i; } //else // break; } //double realValue = sum / number; //return realValue; return estimatedGapSize; } // search for the right position int max = m_gapList->size() - 1; int min = 0; int middle = -1; while( min != max ){ middle = (min + max)/2; if( m_gapList->at( middle )->m_estimatedGapSize == estimatedGapSize ){ // find the exact value, exit break; } if( middle == min || middle == max ) break; if( m_gapList->at( middle )->m_estimatedGapSize < estimatedGapSize ){ min = middle; } else{ max = middle; } } middle = (min+max)/2; // collect all the possible gap sizes int number = 1; double sum = middle; // check the one before middle for( int i = middle - 1; i >= 0; i-- ){ if( m_gapList->at( i )->m_estimatedGapSize == m_gapList->at( middle )->m_estimatedGapSize ){ number++; sum += i; } else break; } // check the one after middle for( int i = middle + 1; i < (int) m_gapList->size(); i++ ){ if( m_gapList->at( i )->m_estimatedGapSize == m_gapList->at( middle )->m_estimatedGapSize ){ number++; sum += i; } else break; } //cerr<<"find the value\n"; double realValue = sum / number; return realValue; }
24.393258
121
0.647014
lorenzgerber
d96dd08a6b14a3eaf66076413dcb98ef5c003663
2,716
cpp
C++
Cpp_Data_Structures_And_Algorithms/HashTableOpenAddressing.cpp
AnthonyDas/Cpp_Data_Structures_And_Algorithms
4ba834803dde0285ee2695b7ef97afbcdcf0484a
[ "MIT" ]
null
null
null
Cpp_Data_Structures_And_Algorithms/HashTableOpenAddressing.cpp
AnthonyDas/Cpp_Data_Structures_And_Algorithms
4ba834803dde0285ee2695b7ef97afbcdcf0484a
[ "MIT" ]
null
null
null
Cpp_Data_Structures_And_Algorithms/HashTableOpenAddressing.cpp
AnthonyDas/Cpp_Data_Structures_And_Algorithms
4ba834803dde0285ee2695b7ef97afbcdcf0484a
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include "HashTableOpenAddressing.h" HashTableOpenAddressing::HashTableOpenAddressing() { // Initialize current size as 0 currentSize = 0; // Initialize table arr = new HashElement *[TABLE_SIZE]; for (int i = 0; i < TABLE_SIZE; ++i) arr[i] = nullptr; // Specify deleted node content deletedElement = new HashElement(-1, ""); } int HashTableOpenAddressing::HashFunction(int key) { return key % TABLE_SIZE; } void HashTableOpenAddressing::Insert(int key, std::string value) { // It's impossible to store a new element // if hash table doesn't have free space if (currentSize >= TABLE_SIZE) return; // Create a temporary element // to be inserted to hash table HashElement * temp = new HashElement(key, value); // Get hash key from hash function int hashIndex = HashFunction(key); // Find next free space // using linear probing while (arr[hashIndex] != nullptr && arr[hashIndex]->Key != key && arr[hashIndex]->Key != -1) { ++hashIndex; hashIndex %= TABLE_SIZE; } // If there's new element to be inserted // then increase the current size if (arr[hashIndex] == nullptr || arr[hashIndex]->Key == -1) { ++currentSize; arr[hashIndex] = temp; } } std::string HashTableOpenAddressing::Search(int key) { // Get hash key from hash function int hashIndex = HashFunction(key); // Find the element with given key while (arr[hashIndex] != nullptr && arr[hashIndex]->Key != deletedElement->Key) { // If element is found // then return its value if (arr[hashIndex]->Key == key) return arr[hashIndex]->Value; // Keep looking for the key // using linear probing ++hashIndex; hashIndex %= TABLE_SIZE; } // If not found return null return ""; } void HashTableOpenAddressing::Remove(int key) { // Get hash key from hash function int hashIndex = HashFunction(key); // Find the element with given key while (arr[hashIndex] != nullptr) { // If element is found then mark the cell as deletedElement if (arr[hashIndex]->Key == key) { arr[hashIndex] = deletedElement; // Reduce size --currentSize; // No need to search anymore return; } // Keep looking for the key // using linear probing ++hashIndex; hashIndex %= TABLE_SIZE; } // Note: if key is not found just do nothing } bool HashTableOpenAddressing::IsEmpty() { return currentSize == 0; } void HashTableOpenAddressing::PrintHashTableOpenAddressing() { // Iterate through array for (int i = 0; i < currentSize; ++i) { // Just print the element if it exist if (arr[i] != nullptr && arr[i]->Key != -1) { std::cout << "Cell: " << i << " Key: " << arr[i]->Key; std::cout << " Value: " << arr[i]->Value << std::endl; } } }
24.468468
95
0.672312
AnthonyDas
d96eb2f9ec5a7d60f38c0f83da3303802db86ac1
1,710
cpp
C++
Source.cpp
UFFFF/TicTacToe
7ba20567f9d71c07f2a67a9e5d55aa1521ccd0fb
[ "CC0-1.0" ]
null
null
null
Source.cpp
UFFFF/TicTacToe
7ba20567f9d71c07f2a67a9e5d55aa1521ccd0fb
[ "CC0-1.0" ]
null
null
null
Source.cpp
UFFFF/TicTacToe
7ba20567f9d71c07f2a67a9e5d55aa1521ccd0fb
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <SFML/Graphics.hpp> #include "Visual.h" #include "Field.h" int main() { bool game_over = false; int a = 0; WinCon w; Field f; sf::RenderWindow window(sf::VideoMode(620, 620), "TicTacToe"); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { sf::Vector2i p = sf::Mouse::getPosition(window); std::pair<int,int> s_s = f.containsfield(p.x, p.y); std::cout << s_s.first << " " << s_s.second << std::endl; if (a % 2 == 0 && (f.available(p.x, p.y)) && !game_over) { f.append_Kreis(s_s.first, s_s.second); w.append_kreis(f.get_number(p.x, p.y)); if (w.won()) { std::cout << "KREIS HAT GEWONNEN" << std::endl; game_over = true; } a++; } else if(a % 2 != 0 && (f.available(p.x, p.y)) && !game_over){ f.append_Kreuz(s_s.first, s_s.second); w.append_kreuz(f.get_number(p.x, p.y)); if (w.won()) { std::cout << "KREUZ HAT GEWONNEN" << std::endl; game_over = true; } a++; } } if (event.type == sf::Event::Closed) window.close(); } window.clear(); Visual v(window); f.update(window); window.display(); } return 0; }
34.897959
78
0.415205
UFFFF
d96f5dbe62d74dea33ddf962164768b362ec2e26
440
hpp
C++
src/visum/events/repeats/Weekdays.hpp
Mokon/visum
53f602fcf22eadd60f446d04a26b4a6e7217c052
[ "RSA-MD" ]
null
null
null
src/visum/events/repeats/Weekdays.hpp
Mokon/visum
53f602fcf22eadd60f446d04a26b4a6e7217c052
[ "RSA-MD" ]
null
null
null
src/visum/events/repeats/Weekdays.hpp
Mokon/visum
53f602fcf22eadd60f446d04a26b4a6e7217c052
[ "RSA-MD" ]
null
null
null
/* Copyright (C) 2013-2016 David 'Mokon' Bond, All Rights Reserved */ #pragma once enum Weekdays : uint8_t { Sunday = 0x01, Monday = 0x02, Tuesday = 0x04, Wednesday = 0x08, Thursday = 0x10, Friday = 0x20, Saturday = 0x40, }; inline Weekdays operator|(Weekdays a, Weekdays b) { return static_cast<Weekdays>(static_cast<uint8_t>(a)| static_cast<uint8_t>(b)); }
20
69
0.588636
Mokon
d97165b8ba5d737885033466a61556bf7b114470
2,800
cpp
C++
src/scene.cpp
teamprova/ProvaEngine-CPP
0ba9b4b0d73a5a261194d5333e5a572c40c0c21f
[ "Unlicense" ]
null
null
null
src/scene.cpp
teamprova/ProvaEngine-CPP
0ba9b4b0d73a5a261194d5333e5a572c40c0c21f
[ "Unlicense" ]
null
null
null
src/scene.cpp
teamprova/ProvaEngine-CPP
0ba9b4b0d73a5a261194d5333e5a572c40c0c21f
[ "Unlicense" ]
null
null
null
#include <SDL.h> #include <math.h> #include <map> #include "scene.hpp" #include "entity.hpp" #include "screen.hpp" #include "collider2d.hpp" #include "vector2.hpp" #include "vector4.hpp" #include "rect.hpp" using namespace Prova; void Scene::EnableDebug() { _debug = true; } void Scene::DisableDebug() { _debug = false; } bool Scene::IsDebugEnabled() { return _debug; } void Scene::AddEntity(Entity& entity) { entities.push_back(&entity); entity.scene = this; _collider2DMap.AddColliders(entity); if(!entity._setup) { entity.Setup(); entity._setup = true; } entity.Start(); } void Scene::RemoveEntity(Entity& entity) { entities.remove(&entity); if(entity.scene == this) entity.scene = nullptr; _collider2DMap.RemoveColliders(entity); } // finds the closest entity to this entity Entity& Scene::FindClosestEntity(Entity& myEntity) { float closestDistance = -1; Entity* closestEntity = nullptr; for(Entity* entity : entities) { // dont count yourself if(entity == &myEntity) continue; float distance = entity->position.DistanceFrom(myEntity.position); if(distance < closestDistance || closestDistance == -1) { closestDistance = distance; closestEntity = entity; } } return *closestEntity; } Entity& Scene::FindClosestEntity(Entity& myEntity, int tag) { float closestDistance = -1; Entity* closestEntity = nullptr; for(Entity* entity : entities) { // match tags and make sure we aren't matching with self if(entity == &myEntity || !entity->HasTag(tag)) continue; float distance = entity->position.DistanceFrom(myEntity.position); if(distance < closestDistance || closestDistance == -1) { closestDistance = distance; closestEntity = entity; } } return *closestEntity; } void Scene::Setup() { } void Scene::Start() { } void Scene::Update() { EntityUpdate(); Collider2DUpdate(); } void Scene::Collider2DUpdate() { _collider2DMap.MapColliders(); _collider2DMap.FindCollisions(); _collider2DMap.ResolveCollisions(); } void Scene::EntityUpdate() { for(Entity* entity : entities) { entity->Update(); entity->position += entity->velocity; } } void Scene::Draw(Screen& screen) { std::multimap<float, Entity*> sorted; for(Entity* entity : entities) { float distance; if(camera.sortingMethod == SortingMethod::Distance) distance = entity->position.DistanceFrom(camera.position); else distance = camera.position.z - entity->position.z; sorted.emplace(distance, entity); } for(auto it = sorted.rbegin(); it != sorted.rend(); ++it) { Entity& entity = *it->second; entity.Draw(screen); } if(IsDebugEnabled()) _collider2DMap.Draw(*game->screen); }
18.421053
70
0.666786
teamprova
d9745592d0b182ef1da12e586ee31f913dac15a4
2,160
cpp
C++
source/gtpBullet/gtCollisionShapeImpl.cpp
lineCode/gost.engine
5f69216b97fc638663b6a38bee3cacfea2abf7ba
[ "MIT" ]
null
null
null
source/gtpBullet/gtCollisionShapeImpl.cpp
lineCode/gost.engine
5f69216b97fc638663b6a38bee3cacfea2abf7ba
[ "MIT" ]
null
null
null
source/gtpBullet/gtCollisionShapeImpl.cpp
lineCode/gost.engine
5f69216b97fc638663b6a38bee3cacfea2abf7ba
[ "MIT" ]
2
2020-01-22T08:45:44.000Z
2020-02-15T20:08:41.000Z
#include "common.h" gtCollisionShapeImpl::gtCollisionShapeImpl(gtPhysicsBullet * ps): m_ps( ps ), m_shape( nullptr ), m_shapeBase( nullptr ) {} gtCollisionShapeImpl::~gtCollisionShapeImpl(){ if( m_shape ){ m_ps->_removeShape( m_shape ); } } bool gtCollisionShapeImpl::initBox( const v3f& size ){ m_shape = new btBoxShape(btVector3(size.x, size.y, size.z)); if( !m_shape ) return false; m_shapeBase = (btPolyhedralConvexShape*)m_shape; m_ps->_addShape( m_shape ); return true; } btCollisionShape * gtCollisionShapeImpl::getBulletShape(){ return m_shape; } u32 gtCollisionShapeImpl::getNumVertices(){ return (u32)m_shapeBase->getNumVertices(); } void gtCollisionShapeImpl::getVertex( u32 index, v3f& vertex ){ btVector3 v; m_shapeBase->getVertex( (s32)index, v ); vertex.set(v[0],v[1],v[2]); } u32 gtCollisionShapeImpl::getNumEdges(){ return (u32)m_shapeBase->getNumEdges(); } void gtCollisionShapeImpl::getEdge( u32 index, v3f& v1, v3f& v2 ){ btVector3 pa, pb; m_shapeBase->getEdge( (s32)index, pa, pb ); v1.set(pa[0],pa[1],pa[2]); v2.set(pb[0],pb[1],pb[2]); } /* Copyright (c) 2018 532235 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. */
31.764706
126
0.753704
lineCode
d976167f2d2eb026e00b5a036c28b9a3a44a8230
3,894
cpp
C++
fboss/agent/hw/benchmarks/HwTxSlowPathBenchmark.cpp
bkoray/fboss
31ba4fab15b61ee36b7a117a80c7d55bb4dc70c0
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/hw/benchmarks/HwTxSlowPathBenchmark.cpp
bkoray/fboss
31ba4fab15b61ee36b7a117a80c7d55bb4dc70c0
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/hw/benchmarks/HwTxSlowPathBenchmark.cpp
bkoray/fboss
31ba4fab15b61ee36b7a117a80c7d55bb4dc70c0
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/Platform.h" #include "fboss/agent/hw/test/ConfigFactory.h" #include "fboss/agent/hw/test/HwSwitchEnsemble.h" #include "fboss/agent/hw/test/HwSwitchEnsembleFactory.h" #include "fboss/agent/hw/test/HwTestPacketUtils.h" #include "fboss/agent/test/EcmpSetupHelper.h" #include <folly/IPAddressV6.h> #include <folly/dynamic.h> #include <folly/init/Init.h> #include <folly/json.h> #include "common/time/Time.h" #include <chrono> #include <iostream> #include <thread> DEFINE_bool(json, true, "Output in json form"); namespace facebook::fboss { std::pair<uint64_t, uint64_t> getOutPktsAndBytes( HwSwitchEnsemble* ensemble, PortID port) { auto stats = ensemble->getLatestPortStats({port})[port]; return {stats.outUnicastPkts_, stats.outBytes_}; } void runTxSlowPathBenchmark() { constexpr int kEcmpWidth = 1; auto ensemble = createHwEnsemble(HwSwitch::FeaturesDesired::LINKSCAN_DESIRED); auto hwSwitch = ensemble->getHwSwitch(); auto portUsed = ensemble->masterLogicalPortIds()[0]; auto config = utility::oneL3IntfConfig(hwSwitch, portUsed); ensemble->applyInitialConfigAndBringUpPorts(config); auto ecmpHelper = utility::EcmpSetupAnyNPorts6(ensemble->getProgrammedState()); auto ecmpRouteState = ecmpHelper.setupECMPForwarding( ecmpHelper.resolveNextHops(ensemble->getProgrammedState(), kEcmpWidth), kEcmpWidth); ensemble->applyNewState(ecmpRouteState); auto cpuMac = ensemble->getPlatform()->getLocalMac(); std::atomic<bool> packetTxDone{false}; std::thread t([cpuMac, hwSwitch, &config, &packetTxDone]() { const auto kSrcIp = folly::IPAddressV6("2620:0:1cfe:face:b00c::3"); const auto kDstIp = folly::IPAddressV6("2620:0:1cfe:face:b00c::4"); while (!packetTxDone) { for (auto i = 0; i < 1'000; ++i) { // Send packet auto txPacket = utility::makeUDPTxPacket( hwSwitch, VlanID(config.vlanPorts[0].vlanID), cpuMac, cpuMac, kSrcIp, kDstIp, 8000, 8001); hwSwitch->sendPacketSwitchedAsync(std::move(txPacket)); } } }); auto [pktsBefore, bytesBefore] = getOutPktsAndBytes(ensemble.get(), PortID(portUsed)); auto timeBefore = std::chrono::steady_clock::now(); constexpr auto kBurnIntevalMs = 5000; // Let the packet flood warm up WallClockMs::Burn(kBurnIntevalMs); auto [pktsAfter, bytesAfter] = getOutPktsAndBytes(ensemble.get(), PortID(portUsed)); auto timeAfter = std::chrono::steady_clock::now(); packetTxDone = true; t.join(); std::chrono::duration<double, std::milli> durationMillseconds = timeAfter - timeBefore; uint32_t pps = (static_cast<double>(pktsAfter - pktsBefore) / durationMillseconds.count()) * 1000; uint32_t bytesPerSec = (static_cast<double>(bytesAfter - bytesBefore) / durationMillseconds.count()) * 1000; if (FLAGS_json) { folly::dynamic cpuTxRateJson = folly::dynamic::object; cpuTxRateJson["cpu_tx_pps"] = pps; cpuTxRateJson["cpu_tx_bytes_per_sec"] = bytesPerSec; std::cout << toPrettyJson(cpuTxRateJson) << std::endl; } else { XLOG(INFO) << " Pkts before: " << pktsBefore << " Pkts after: " << pktsAfter << " interval ms: " << durationMillseconds.count() << " pps: " << pps << " bytes per sec: " << bytesPerSec; } } } // namespace facebook::fboss int main(int argc, char* argv[]) { folly::init(&argc, &argv, true); facebook::fboss::runTxSlowPathBenchmark(); return 0; }
34.460177
80
0.678223
bkoray
d97784a53ebaad89cdbcc8c73ea7f1034b620173
483
cpp
C++
src/Files/main.cpp
bbkane/Sandbox
848030da315045888fd8542ddee49b929fa2e64a
[ "Unlicense" ]
null
null
null
src/Files/main.cpp
bbkane/Sandbox
848030da315045888fd8542ddee49b929fa2e64a
[ "Unlicense" ]
null
null
null
src/Files/main.cpp
bbkane/Sandbox
848030da315045888fd8542ddee49b929fa2e64a
[ "Unlicense" ]
null
null
null
#include <fstream> #include <iostream> #include <stdio.h> /* defines FILENAME_MAX */ #ifdef _WIN32 #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif int main() { char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { return errno; } cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */ printf("The current working directory is\n %s\n", cCurrentPath); }
20.125
73
0.722567
bbkane
d979215a6c8f2f05746a09d0f4d5f6a81360e3db
25,932
cpp
C++
src/Regard3DFeatures.cpp
RichardQZeng/Regard3D
2822275259e9ca140b77b89c1edeccf72bc45f07
[ "MIT" ]
213
2015-06-14T03:29:16.000Z
2022-03-25T17:42:43.000Z
src/Regard3DFeatures.cpp
RichardQZeng/Regard3D
2822275259e9ca140b77b89c1edeccf72bc45f07
[ "MIT" ]
45
2015-10-25T16:59:24.000Z
2022-02-08T22:44:52.000Z
src/Regard3DFeatures.cpp
RichardQZeng/Regard3D
2822275259e9ca140b77b89c1edeccf72bc45f07
[ "MIT" ]
49
2015-07-02T05:28:15.000Z
2022-01-23T06:37:31.000Z
/** * Copyright (C) 2015 Roman Hiestand * * 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 "CommonIncludes.h" #include "Regard3DFeatures.h" #include <memory> #include <boost/locale.hpp> #if defined(R3D_HAVE_OPENMP) # include <omp.h> #endif #if defined(R3D_HAVE_TBB) // && !defined(R3D_HAVE_OPENMP) #define R3D_USE_TBB_THREADING 1 # include <tbb/tbb.h> #endif #undef R3D_USE_TBB_THREADING #undef R3D_HAVE_TBB #undef R3D_HAVE_OPENMP #undef R3D_HAVE_VLFEAT #if defined(R3D_HAVE_VLFEAT) // VLFEAT extern "C" { #include "vlfeat/covdet.h" #include "vlfeat/mser.h" } #endif // LIOP (copied from VLFEAT) extern "C" { #include "vl_liop.h" } // OpenCV Includes #include "opencv2/core/eigen.hpp" //To Convert Eigen matrix to cv matrix #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/features2d.hpp" // AKAZE #include "AKAZE.h" // Fast-AKAZE #include "features2d_akaze2.hpp" // OpenMVG #include "features/tbmr/tbmr.hpp" #include "openMVG/features/feature.hpp" // Helper class for locking the AKAZE semaphore (based on wxMutexLocker) class AKAZESemaLocker { public: // lock the mutex in the ctor AKAZESemaLocker() : isOK_(false) { if(pAKAZESemaphore_ != NULL) isOK_ = (pAKAZESemaphore_->Wait() == wxSEMA_NO_ERROR); } // returns true if mutex was successfully locked in ctor bool IsOk() const { return isOK_; } // unlock the mutex in dtor ~AKAZESemaLocker() { if(IsOk() && pAKAZESemaphore_ != NULL) pAKAZESemaphore_->Post(); } // Initializes the semaphore with the amount of allowed simultaneous threads static bool initialize(int count) { if(pAKAZESemaphore_ != NULL) delete pAKAZESemaphore_; pAKAZESemaphore_ = new wxSemaphore(count, 0); if(pAKAZESemaphore_->IsOk()) return true; delete pAKAZESemaphore_; return false; } static void uninitialize() { if(pAKAZESemaphore_ != NULL) delete pAKAZESemaphore_; pAKAZESemaphore_ = NULL; } private: // no assignment operator nor copy ctor AKAZESemaLocker(const AKAZESemaLocker&); AKAZESemaLocker& operator=(const AKAZESemaLocker&); bool isOK_; static wxSemaphore *pAKAZESemaphore_; }; wxSemaphore *AKAZESemaLocker::pAKAZESemaphore_ = NULL; Regard3DFeatures::R3DFParams::R3DFParams() : threshold_(0.001), nFeatures_(20000), distRatio_(0.6), computeHomographyMatrix_(true), computeFundalmentalMatrix_(true), computeEssentialMatrix_(true) { keypointDetectorList_.push_back( std::string("Fast-AKAZE") ); //keypointDetectorList_.push_back( std::string("TBMR") ); } Regard3DFeatures::R3DFParams::R3DFParams(const Regard3DFeatures::R3DFParams &o) { copy(o); } Regard3DFeatures::R3DFParams::~R3DFParams() { } Regard3DFeatures::R3DFParams &Regard3DFeatures::R3DFParams::copy(const Regard3DFeatures::R3DFParams &o) { keypointDetectorList_ = o.keypointDetectorList_; threshold_ = o.threshold_; nFeatures_ = o.nFeatures_; distRatio_ = o.distRatio_; computeHomographyMatrix_ = o.computeHomographyMatrix_; computeFundalmentalMatrix_ = o.computeFundalmentalMatrix_; computeEssentialMatrix_ = o.computeEssentialMatrix_; return *this; } Regard3DFeatures::R3DFParams & Regard3DFeatures::R3DFParams::operator=(const Regard3DFeatures::R3DFParams &o) { return copy(o); } Regard3DFeatures::Regard3DFeatures() { } Regard3DFeatures::~Regard3DFeatures() { } bool Regard3DFeatures::initAKAZESemaphore(int count) { return AKAZESemaLocker::initialize(count); } void Regard3DFeatures::uninitializeAKAZESemaphore() { AKAZESemaLocker::uninitialize(); } std::vector<std::string> Regard3DFeatures::getKeypointDetectors() { std::vector<std::string> ret; ret.push_back( std::string( "AKAZE" ) ); // Own ret.push_back( std::string( "Fast-AKAZE" ) ); // Own ret.push_back( std::string( "MSER" ) ); // OpenCV ret.push_back( std::string( "ORB" ) ); // OpenCV ret.push_back( std::string( "BRISK" ) ); // OpenCV ret.push_back( std::string( "GFTT" ) ); // OpenCV #if defined(R3D_HAVE_VLFEAT) ret.push_back( std::string( "DOG" ) ); // VLFEAT #endif return ret; } std::vector<std::string> Regard3DFeatures::getFeatureExtractors() { std::vector<std::string> ret; ret.push_back( std::string( "LIOP" ) ); return ret; } void Regard3DFeatures::detectAndExtract(const openMVG::image::Image<float> &img, Regard3DFeatures::FeatsR3D &feats, Regard3DFeatures::DescsR3D &descs, const Regard3DFeatures::R3DFParams &params) { std::vector< cv::KeyPoint > vec_keypoints; // Iterate over all keypoint detectors std::vector<std::string>::const_iterator iter = params.keypointDetectorList_.begin(); for(;iter != params.keypointDetectorList_.end(); iter++) { std::string keypointDetector = *iter; vec_keypoints.clear(); detectKeypoints(img, vec_keypoints, keypointDetector, params); float kpSizeFactor = getKpSizeFactor(keypointDetector); extractLIOPFeatures(img, vec_keypoints, kpSizeFactor, feats, descs); } /* cv::Mat cvimg; cv::eigen2cv(img.GetMat(), cvimg); cv::Mat img_uchar; cvimg.convertTo(img_uchar, CV_8U, 255.0, 0); std::vector<openMVG::features::AffinePointFeature> features; openMVG::image::Image<unsigned char> imaChar; imaChar = Eigen::Map<openMVG::image::Image<unsigned char>::Base>(img_uchar.ptr<unsigned char>(0), img_uchar.rows, img_uchar.cols); bool bUpRight = false; using namespace openMVG::features; std::unique_ptr<Image_describer> image_describer; image_describer.reset(new AKAZE_Image_describer (AKAZE_Image_describer::Params(AKAZE::Params(), AKAZE_LIOP), !bUpRight)); image_describer->Set_configuration_preset(EDESCRIBER_PRESET::HIGH_PRESET); // Compute features and descriptors std::unique_ptr<Regions> regions; image_describer->Describe(imaChar, regions, nullptr); */ } void Regard3DFeatures::detectAndExtract_NLOPT(const openMVG::image::Image<unsigned char> &img, Regard3DFeatures::FeatsR3D &feats, Regard3DFeatures::DescsR3D &descs, double kpSizeFactorIn) { std::vector< cv::KeyPoint > vec_keypoints; Regard3DFeatures::R3DFParams params; params.nFeatures_ = 10000; params.threshold_ = 0.0007; std::string keypointDetector("AKAZE"); vec_keypoints.clear(); // detectKeypoints(img, vec_keypoints, keypointDetector, params); // extractLIOPFeatures(img, vec_keypoints, kpSizeFactorIn, feats, descs); } /** * Detect keypoints using MSER from OpenCV and create LIOP descriptors. * * Make sure DescriptorR3D is set to 144 floats. */ void Regard3DFeatures::detectAndExtractVLFEAT_MSER_LIOP(const openMVG::image::Image<unsigned char> &img, Regard3DFeatures::FeatsR3D &feats, Regard3DFeatures::DescsR3D &descs) { // Convert image to OpenCV data cv::Mat cvimg; cv::eigen2cv(img.GetMat(), cvimg); std::vector< cv::KeyPoint > vec_keypoints; cv::Mat m_desc; // cv::Ptr<cv::FeatureDetector> fd(cv::FeatureDetector::create(std::string("MSER"))); int nrPixels = img.Width() * img.Height(); int maxArea = static_cast<int>(nrPixels * 0.75); /* fd->setInt("delta", 5); fd->setInt("minArea", 3); fd->setInt("maxArea", maxArea); fd->setDouble("maxVariation", 0.25); fd->setDouble("minDiversity", 0.2); fd->detect(cvimg, vec_keypoints); */ std::vector<std::vector<cv::Point> > contours; std::vector<cv::Rect> bboxes; cv::Ptr<cv::MSER> mser = cv::MSER::create(); //(5, 3, maxArea, 0.25, 0.2); mser->detectRegions(cvimg, contours, bboxes); double expandPatchFactor = 2.0; // This expands the extracted patch around the found MSER. Seems to help... int patchResolution = 20; vl_size patchSize = 2*patchResolution + 1; std::vector<float> patch(patchSize * patchSize); // Prepare LIOP descriptor VlLiopDesc * liop = r3d_vl_liopdesc_new_basic((vl_size)patchSize); vl_size dimension = r3d_vl_liopdesc_get_dimension(liop); assert(dimension == DescriptorR3D::static_size); // Make sure descriptor sizes match std::vector<float> desc(dimension); DescriptorR3D descriptor; for(size_t i = 0; i < contours.size(); i++) { // Find enclosing rectangle for all points in the contour const std::vector<cv::Point> &curContour = contours[i]; int minx = img.Width() - 1, maxx = 0; int miny = img.Height() - 1, maxy = 0; for(size_t j = 0; j < curContour.size(); j++) { int curX = curContour[j].x; int curY = curContour[j].y; minx = std::min(minx, curX); maxx = std::max(maxx, curX); miny = std::min(miny, curY); maxy = std::max(maxy, curY); } if(expandPatchFactor > 0) { int minxnew = static_cast<int>( ((1.0 - expandPatchFactor)*maxx + (1.0 + expandPatchFactor)*minx ) / 2.0 ); int maxxnew = static_cast<int>( ((1.0 + expandPatchFactor)*maxx + (1.0 - expandPatchFactor)*minx ) / 2.0 ); int minynew = static_cast<int>( ((1.0 - expandPatchFactor)*maxy + (1.0 + expandPatchFactor)*miny ) / 2.0 ); int maxynew = static_cast<int>( ((1.0 + expandPatchFactor)*maxy + (1.0 - expandPatchFactor)*miny ) / 2.0 ); minx = minxnew; maxx = maxxnew; miny = minynew; maxy = maxynew; } // Extract patch from image int x = minx, y = miny; int width = maxx - minx + 1, height = maxy - miny + 1; if(x >= 0 && y >= 0 && (x + width) < cvimg.cols && (y + height) < cvimg.rows && width > 2 && height > 2) { cv::Rect keyPointRect(x, y, width, height); cv::Mat patch(cvimg, keyPointRect); int matType = patch.type(); cv::Mat patchF_tmp, patchF; patch.convertTo(patchF_tmp, CV_32F); cv::resize(patchF_tmp, patchF, cv::Size(patchSize, patchSize)); float *patchPtr = NULL; std::vector<float> patchVec; if(patch.isContinuous()) { patchPtr = patchF.ptr<float>(0); } else { patchVec.resize(patchSize*patchSize); for(int i = 0; i < patchSize; i++) { float *rowPtr = patchF.ptr<float>(i); for(int j = 0; j < patchSize; j++) patchVec[i * patchSize + j] = *(rowPtr++); } patchPtr = &(patchVec[0]); } r3d_vl_liopdesc_process(liop, &(desc[0]), patchPtr); // Convert to OpenMVG keypoint and descriptor openMVG::features::SIOPointFeature fp; fp.x() = minx + (width/2); fp.y() = miny + (height/2); fp.scale() = std::sqrt(static_cast<float>(width*width + height*height)) / 2.0f; fp.orientation() = 0; for(int j = 0; j < dimension; j++) descriptor[j] = desc[j]; descs.push_back(descriptor); feats.push_back(fp); } } /* for(std::vector< cv::KeyPoint >::const_iterator i_keypoint = vec_keypoints.begin(); i_keypoint != vec_keypoints.end(); ++i_keypoint) { const cv::KeyPoint &kp = *(i_keypoint); // int x = static_cast<int>(kp.pt.x + 0.5f) - patchResolution; // int y = static_cast<int>(kp.pt.y + 0.5f) - patchResolution; int keypointSize = static_cast<int>(kp.size + 0.5f); // Although kp.size is diameter, use it as radius for extracting the patch for LIOP int x = static_cast<int>(kp.pt.x + 0.5f) - keypointSize; int y = static_cast<int>(kp.pt.y + 0.5f) - keypointSize; //int width = patchSize, height = patchSize; int width = 2*keypointSize + 1, height = 2*keypointSize+1; if(x >= 0 && y >= 0 && (x + width) < cvimg.cols && (y + height) < cvimg.rows && keypointSize > 2) { cv::Rect keyPointRect(x, y, width, height); cv::Mat patch(cvimg, keyPointRect); int matType = patch.type(); cv::Mat patchF_tmp, patchF; patch.convertTo(patchF_tmp, CV_32F); cv::resize(patchF_tmp, patchF, cv::Size(patchSize, patchSize)); float *patchPtr = NULL; std::vector<float> patchVec; if(patch.isContinuous()) { patchPtr = patchF.ptr<float>(0); } else { patchVec.resize(patchSize*patchSize); for(int i = 0; i < patchSize; i++) { float *rowPtr = patchF.ptr<float>(i); for(int j = 0; j < patchSize; j++) patchVec[i * patchSize + j] = *(rowPtr++); } patchPtr = &(patchVec[0]); } vl_liopdesc_process(liop, &(desc[0]), patchPtr); // Convert to OpenMVG keypoint and descriptor openMVG::features::SIOPointFeature fp; fp.x() = kp.pt.x; fp.y() = kp.pt.y; fp.scale() = kp.size/2.0f; // kp.size is diameter, convert to radius fp.orientation() = kp.angle; for(int j = 0; j < dimension; j++) descriptor[j] = desc[j]; descs.push_back(descriptor); feats.push_back(fp); } } */ } /** * Detect keypoints using covariant feature detectors from VLFEAT and create LIOP descriptors. * * Make sure DescriptorR3D is set to 144 floats. */ void Regard3DFeatures::detectAndExtractVLFEAT_CoV_LIOP(const openMVG::image::Image<unsigned char> &img, Regard3DFeatures::FeatsR3D &feats, Regard3DFeatures::DescsR3D &descs) { #if defined(R3D_HAVE_VLFEAT) // Convert image float openMVG::image::Image<float> imgFloat( img.GetMat().cast<float>() ); int w = img.Width(), h = img.Height(); int octaveResolution = 2; double peakThreshold = 0.01; double edgeThreshold = 10.0; double boundaryMargin = 2.0; int patchResolution = 20; double patchRelativeExtent = 4.0; double patchRelativeSmoothing = 1.2; //0.5; bool doubleImage = false; double smoothBeforeDetection = 0; //1.0; // VL_COVDET_METHOD_DOG // VL_COVDET_METHOD_MULTISCALE_HARRIS VlCovDet * covdet = vl_covdet_new(VL_COVDET_METHOD_DOG); vl_covdet_set_first_octave(covdet, doubleImage ? -1 : 0); vl_covdet_set_octave_resolution(covdet, octaveResolution); vl_covdet_set_peak_threshold(covdet, peakThreshold); vl_covdet_set_edge_threshold(covdet, edgeThreshold); // Smooth image if(smoothBeforeDetection > 0) vl_imsmooth_f(imgFloat.data(), w, imgFloat.data(), w, h, w, smoothBeforeDetection, smoothBeforeDetection); // process the image and run the detector vl_covdet_put_image(covdet, imgFloat.data(), w, h); vl_covdet_detect(covdet); // drop features on the margin vl_covdet_drop_features_outside(covdet, boundaryMargin); // compute the affine shape of the features vl_covdet_extract_affine_shape(covdet); // compute the orientation of the features // vl_covdet_extract_orientations(covdet); // get feature frames back vl_size numFeatures = vl_covdet_get_num_features(covdet) ; VlCovDetFeature const *feature = reinterpret_cast<VlCovDetFeature const *>(vl_covdet_get_features(covdet)); // get normalized feature appearance patches vl_size patchSize = 2*patchResolution + 1; std::vector<float> patch(patchSize * patchSize); // Prepare LIOP descriptor VlLiopDesc * liop = r3d_vl_liopdesc_new_basic((vl_size)patchSize); vl_size dimension = r3d_vl_liopdesc_get_dimension(liop); assert(dimension == DescriptorR3D::static_size); // Make sure descriptor sizes match std::vector<float> desc(dimension); DescriptorR3D descriptor; for (int i = 0 ; i < numFeatures ; i++) { vl_covdet_extract_patch_for_frame(covdet, &(patch[0]), patchResolution, patchRelativeExtent, patchRelativeSmoothing, feature[i].frame); /* vl_size numOrientations = 0; VlCovDetFeatureOrientation *featOrient = vl_covdet_extract_orientations_for_frame(covdet, &numOrientations, feature[i].frame); double angle1 = featOrient->angle; // double angle2 = std::atan2(feature[i].frame.a11, feature[i].frame.a12); // double angle3 = std::atan2(feature[i].frame.a21, feature[i].frame.a22); double angle2 = std::atan2(feature[i].frame.a11, feature[i].frame.a21); double angle3 = std::atan2(feature[i].frame.a12, feature[i].frame.a22); **/ double scale = 0; { double a11 = feature[i].frame.a11; double a12 = feature[i].frame.a12; double a21 = feature[i].frame.a21; double a22 = feature[i].frame.a22; double a = std::sqrt(a11*a11 + a21*a21); double b = std::sqrt(a21*a21 + a22*a22); scale = std::sqrt(a*a + b*b); } // Calculate LIOP descriptor r3d_vl_liopdesc_process(liop, &(desc[0]), &(patch[0])); // Convert to OpenMVG keypoint and descriptor openMVG::features::SIOPointFeature fp; fp.x() = feature[i].frame.x; fp.y() = feature[i].frame.y; fp.scale() = static_cast<float>(scale); fp.orientation() = 0.0f; // TODO //siftDescToFloat(descr, descriptor, bRootSift); for(int j = 0; j < dimension; j++) descriptor[j] = desc[j]; descs.push_back(descriptor); feats.push_back(fp); } // Clean up r3d_vl_liopdesc_delete(liop); vl_covdet_delete(covdet); #endif } void Regard3DFeatures::detectKeypoints(const openMVG::image::Image<float> &img, std::vector< cv::KeyPoint > &vec_keypoints, const std::string &fdname, const Regard3DFeatures::R3DFParams &params) { if(fdname == std::string("AKAZE")) { AKAZESemaLocker akazeLocker; // Only allow one thread in this area // Convert image to OpenCV data cv::Mat cvimg; cv::eigen2cv(img.GetMat(), cvimg); cv::Ptr<cv::FeatureDetector> akazeDetector(cv::AKAZE::create(cv::AKAZE::DESCRIPTOR_MLDB, 0, 3, params.threshold_, 4, 4, cv::KAZE::DIFF_PM_G2)); akazeDetector->detect(cvimg, vec_keypoints); } else if(fdname == std::string("Fast-AKAZE")) { AKAZESemaLocker akazeLocker; // Only allow one thread in this area // Convert image to OpenCV data cv::Mat cvimg; cv::eigen2cv(img.GetMat(), cvimg); // cv::Mat img_32; // cvimg.convertTo(img_32, CV_32F, 1.0/255.0, 0); // Convert to float, value range 0..1 cv::Ptr<cv::AKAZE2> fd = cv::AKAZE2::create(); fd->setThreshold(params.threshold_); fd->detect(cvimg, vec_keypoints); for(int i = 0; i < static_cast<int>(vec_keypoints.size()); i++) { // Convert from radians to degrees (vec_keypoints[i].angle) *= 180.0 / CV_PI; vec_keypoints[i].angle += 90.0f; while(vec_keypoints[i].angle < 0) vec_keypoints[i].angle += 360.0f; while(vec_keypoints[i].angle > 360.0f) vec_keypoints[i].angle -= 360.0f; } } else if(fdname == std::string("DOG")) // VLFEAT { } else if(fdname == std::string( "TBMR" )) { cv::Mat cvimg; cv::eigen2cv(img.GetMat(), cvimg); cv::Mat img_uchar; cvimg.convertTo(img_uchar, CV_8U, 255.0, 0); std::vector<openMVG::features::AffinePointFeature> features; openMVG::image::Image<unsigned char> imaChar; imaChar = Eigen::Map<openMVG::image::Image<unsigned char>::Base>(img_uchar.ptr<unsigned char>(0), img_uchar.rows, img_uchar.cols); openMVG::features::tbmr::Extract_tbmr(imaChar, features); vec_keypoints.resize(features.size()); for(size_t i = 0; i < features.size(); i++) { const auto &f = features[i]; vec_keypoints[i].pt.x = f.coords().x(); vec_keypoints[i].pt.y = f.coords().y(); vec_keypoints[i].size = std::sqrt(f.l1()*f.l1() + f.l2()*f.l2()); vec_keypoints[i].angle = 180.0 * f.orientation() / M_PI; } } else // OpenCV { // Convert image to OpenCV data cv::Mat cvimg; cv::eigen2cv(img.GetMat(), cvimg); // Convert string to C locale // std::string fdname_cloc = boost::locale::conv::from_utf(fdname, "C"); //cv::Ptr<cv::FeatureDetector> fd(cv::FeatureDetector::create(fdname)); cv::Ptr<cv::FeatureDetector> fd; //assert(!fd.empty()); if(fdname == std::string( "MSER" )) { fd = cv::MSER::create(); /*int nrPixels = img.Width() * img.Height(); int maxArea = static_cast<int>(nrPixels * 0.75); fd->setInt("delta", 5); fd->setInt("minArea", 3); fd->setInt("maxArea", maxArea); fd->setDouble("maxVariation", 0.25); fd->setDouble("minDiversity", 0.2);*/ } else if(fdname == std::string( "ORB" )) { // fd->setInt("nFeatures", params.nFeatures_); fd = cv::ORB::create(params.nFeatures_); } else if(fdname == std::string( "BRISK" )) { // fd->setInt("thres", static_cast<int>(params.threshold_)); fd = cv::BRISK::create(); } else if(fdname == std::string( "GFTT" )) { //fd->setInt("nfeatures", params.nFeatures_); fd = cv::GFTTDetector::create(params.nFeatures_); } // fd->setDouble("edgeThreshold", 0.01); // for SIFT fd->detect(cvimg, vec_keypoints); } } /** * Return the factor from keypoint size to feature size. * * Those factors have been determined with nlopt. */ float Regard3DFeatures::getKpSizeFactor(const std::string &fdname) { float retVal = 1.0f; if(fdname == std::string("AKAZE")) retVal = 8.0f; if(fdname == std::string("Fast-AKAZE")) retVal = 8.0f; else if(fdname == std::string("DOG")) retVal = 0.25f; else if(fdname == std::string( "MSER" )) retVal = 0.08; else if(fdname == std::string( "ORB" )) retVal = 0.025f; else if(fdname == std::string( "BRISK" )) retVal = 0.15f; else if(fdname == std::string( "GFTT" )) retVal = 0.13f; else if(fdname == std::string( "HARRIS" )) retVal = 0.25f; else if(fdname == std::string( "SimpleBlob" )) retVal = 1.0f; // No working parameters found else if(fdname == std::string("TBMR")) retVal = 1.0f; return retVal; } void Regard3DFeatures::extractLIOPFeatures(const openMVG::image::Image<float> &img, std::vector< cv::KeyPoint > &vec_keypoints, float kpSizeFactor, FeatsR3D &feats, DescsR3D &descs) { // Convert image to OpenCV data cv::Mat cvimg; cv::eigen2cv(img.GetMat(), cvimg); const int patchResolution = 20; const double patchRelativeExtent = 4.0; const double patchRelativeSmoothing = 1.2; vl_size patchSize = 2*patchResolution + 1; #if defined(R3D_USE_TBB_THREADING) tbb::mutex critSectionMutex; tbb::parallel_for(tbb::blocked_range<size_t>(0, vec_keypoints.size()), [=, &critSectionMutex, &vec_keypoints, &descs, &feats](const tbb::blocked_range<size_t>& r) // Use lambda notation #else #if defined(R3D_HAVE_OPENMP) #pragma omp parallel #endif #endif { // Initialisation of (in OpenMP or TBB case: per-thread) variables/structures std::vector<float> patchvec(patchSize * patchSize); // Prepare LIOP descriptor VlLiopDesc * liop = r3d_vl_liopdesc_new_basic((vl_size)patchSize); vl_size dimension = r3d_vl_liopdesc_get_dimension(liop); assert(dimension == DescriptorR3D::static_size); // Must be equal to the size of DescriptorR3D std::vector<float> desc(dimension); DescriptorR3D descriptor; cv::Mat M(2, 3, CV_32F); // 2x3 matrix // Prepare patch cv::Mat patchcv; patchcv.create(patchSize, patchSize, CV_32F); #if defined(R3D_USE_TBB_THREADING) for(size_t i = r.begin(); i != r.end(); ++i) #else #if defined(R3D_HAVE_OPENMP) #pragma omp for schedule(static) #endif for (int i = 0 ; i < static_cast<int>(vec_keypoints.size()); i++) #endif { const cv::KeyPoint &kp = vec_keypoints[i]; float x = kp.pt.x; float y = kp.pt.y; // LIOP is rotationally invariant, so angle is not improving much float angle = -90.0f-kp.angle; // angle in degrees float kpsize = kp.size; // diameter float scale = kpsize / static_cast<float>(patchSize) * kpSizeFactor; // Extract patch TODO: Detect corner case /* cv::Mat M_rot, M, M_trans; M_trans = cv::Mat::eye(3, 3, CV_64F); // Identity matrix: rows, columns, type M_trans.at<double>(0, 2) = x - static_cast<double>(patchResolution); M_trans.at<double>(1, 2) = y - static_cast<double>(patchResolution); M_rot = cv::getRotationMatrix2D(cv::Point2f(x, y), angle, scale); M_rot.resize(3, cv::Scalar(0)); // Set number of rows to 3 (-> 3x3 matrix) M_rot.at<double>(2, 2) = 1.0; M = M_rot * M_trans; M.resize(2); // Reduce one row to 2x3 matrix */ float alpha = scale * std::cos( angle * CV_PI / 180.0f ); float beta = scale * std::sin( angle * CV_PI / 180.0f ); float trans_x = x - static_cast<float>(patchResolution); float trans_y = y - static_cast<float>(patchResolution); M.at<float>(0, 0) = alpha; M.at<float>(0, 1) = beta; M.at<float>(0, 2) = beta*trans_y + alpha*trans_x - beta*y + (1.0f - alpha)*x; M.at<float>(1, 0) = -beta; M.at<float>(1, 1) = alpha; M.at<float>(1, 2) = alpha*trans_y - beta*trans_x + beta*x + (1.0f - alpha)*y; // Extract patch, rotate and resize it to patchSize * patchSize cv::warpAffine(cvimg, patchcv, M, cv::Size(patchSize, patchSize), cv::INTER_LINEAR | cv::WARP_INVERSE_MAP); // Gauss filter for smoothing (suggested by LIOP paper) if(patchRelativeSmoothing > 1.0) cv::GaussianBlur(patchcv, patchcv, cv::Size(0, 0), patchRelativeSmoothing); float *patchPtr = NULL; if(patchcv.isContinuous()) { patchPtr = patchcv.ptr<float>(0); } else { patchvec.resize(patchSize*patchSize); for(int i = 0; i < patchSize; i++) { float *rowPtr = patchcv.ptr<float>(i); for(int j = 0; j < patchSize; j++) patchvec[i * patchSize + j] = *(rowPtr++); } patchPtr = &(patchvec[0]); } // Calculate LIOP descriptor r3d_vl_liopdesc_process(liop, &(desc[0]), patchPtr); { // Convert to OpenMVG keypoint and descriptor openMVG::features::SIOPointFeature fp; fp.x() = kp.pt.x; fp.y() = kp.pt.y; fp.scale() = kp.size/2.0f; // kp.size is diameter, convert to radius fp.orientation() = kp.angle; for(int j = 0; j < dimension; j++) descriptor[j] = desc[j]; #if defined(R3D_USE_TBB_THREADING) #elif defined(USE_OPENMP) #pragma omp critical #endif { #if defined(R3D_USE_TBB_THREADING) tbb::mutex::scoped_lock lock(critSectionMutex); #endif descs.push_back(descriptor); feats.push_back(fp); } } } r3d_vl_liopdesc_delete(liop); } #if defined(R3D_USE_TBB_THREADING) ); #endif // Clean up //r3d_vl_liopdesc_delete(liop); }
30.048667
138
0.691771
RichardQZeng
d9805e6f15e837c1ebb5c6b571337cb7cdbce9a8
7,562
cpp
C++
src/server_main/engine/scripting/character_script.cpp
snowmeltarcade/projectfarm
6a35330f63bff06465c4ee1a0fbc5277c0d22982
[ "MIT" ]
null
null
null
src/server_main/engine/scripting/character_script.cpp
snowmeltarcade/projectfarm
6a35330f63bff06465c4ee1a0fbc5277c0d22982
[ "MIT" ]
7
2021-05-30T21:52:39.000Z
2021-06-25T22:35:28.000Z
src/server_main/engine/scripting/character_script.cpp
snowmeltarcade/projectfarm
6a35330f63bff06465c4ee1a0fbc5277c0d22982
[ "MIT" ]
null
null
null
#include "character_script.h" #include "character_script_object.h" #include "engine/entities/character.h" #include "engine/world/world.h" #include "api/logging/logging.h" namespace projectfarm::engine::scripting { std::vector<std::pair<shared::scripting::FunctionTypes, bool>> CharacterScript::GetFunctions() const noexcept { return { { shared::scripting::FunctionTypes::Update, true }, { shared::scripting::FunctionTypes::Init, true }, }; } void CharacterScript::SetupGlobalTemplate(v8::Local<v8::ObjectTemplate>& globalTemplate) noexcept { globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "set_update_interval").ToLocalChecked(), v8::FunctionTemplate::New(this->_isolate, &CharacterScript::SetUpdateInterval)); globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "move").ToLocalChecked(), v8::FunctionTemplate::New(this->_isolate, &CharacterScript::Move)); globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "move_to").ToLocalChecked(), v8::FunctionTemplate::New(this->_isolate, &CharacterScript::MoveTo)); globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "get_position_x").ToLocalChecked(), v8::FunctionTemplate::New(this->_isolate, &CharacterScript::GetPositionX)); globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "get_position_y").ToLocalChecked(), v8::FunctionTemplate::New(this->_isolate, &CharacterScript::GetPositionY)); globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "world_get_characters_within_distance").ToLocalChecked(), v8::FunctionTemplate::New(this->_isolate, &CharacterScript::GetCharactersWithinDistance)); } void CharacterScript::SetUpdateInterval(const v8::FunctionCallbackInfo<v8::Value>& args) { using namespace std::literals::string_literals; auto isolate = args.GetIsolate(); auto context = isolate->GetCurrentContext(); v8::HandleScope handScope(isolate); auto self = args.Holder(); auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1)); auto character = static_cast<entities::Character*>(wrap->Value()); if (args.Length() != 1) { shared::api::logging::Log("Invalid number of arguments for 'SetUpdateInterval'."); return; } auto interval = args[0]->Uint32Value(context).FromMaybe(0); if (interval == 0) { shared::api::logging::Log("Ignoring value - possibly invalid."); return; } character->SetScriptUpdateInterval(interval); } void CharacterScript::Move(const v8::FunctionCallbackInfo<v8::Value>& args) { using namespace std::literals::string_literals; auto isolate = args.GetIsolate(); auto context = isolate->GetCurrentContext(); v8::HandleScope handScope(isolate); auto self = args.Holder(); auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1)); auto character = static_cast<entities::Character*>(wrap->Value()); if (args.Length() != 4) { shared::api::logging::Log("Invalid number of arguments for 'Move'."); return; } v8::String::Utf8Value action(isolate, args[0]); auto x = args[1]->NumberValue(context).FromMaybe(character->GetLocation().first); auto y = args[2]->NumberValue(context).FromMaybe(character->GetLocation().second); auto distance = args[3]->NumberValue(context).FromMaybe(0.0f); if (distance == 0.0f) { shared::api::logging::Log("Ignoring distance - possibly invalid."); return; } character->ScriptMove(*action, static_cast<float>(x), static_cast<float>(y), static_cast<float>(distance)); } void CharacterScript::MoveTo(const v8::FunctionCallbackInfo<v8::Value>& args) { using namespace std::literals::string_literals; auto isolate = args.GetIsolate(); auto context = isolate->GetCurrentContext(); v8::HandleScope handScope(isolate); auto self = args.Holder(); auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1)); auto character = static_cast<entities::Character*>(wrap->Value()); if (args.Length() != 3) { shared::api::logging::Log("Invalid number of arguments for 'MoveTo'."); return; } v8::String::Utf8Value action(isolate, args[0]); auto x = args[1]->NumberValue(context).FromMaybe(0.0f); auto y = args[2]->NumberValue(context).FromMaybe(0.0f); character->ScriptMoveTo(*action, static_cast<float>(x), static_cast<float>(y)); } void CharacterScript::GetPositionX(const v8::FunctionCallbackInfo<v8::Value>& args) { using namespace std::literals::string_literals; auto isolate = args.GetIsolate(); v8::HandleScope handScope(isolate); auto self = args.Holder(); auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1)); auto character = static_cast<entities::Character*>(wrap->Value()); args.GetReturnValue().Set(character->GetLocation().first); } void CharacterScript::GetPositionY(const v8::FunctionCallbackInfo<v8::Value>& args) { using namespace std::literals::string_literals; auto isolate = args.GetIsolate(); v8::HandleScope handScope(isolate); auto self = args.Holder(); auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1)); auto character = static_cast<entities::Character*>(wrap->Value()); args.GetReturnValue().Set(character->GetLocation().second); } void CharacterScript::GetCharactersWithinDistance(const v8::FunctionCallbackInfo<v8::Value>& args) { using namespace std::literals::string_literals; auto isolate = args.GetIsolate(); auto context = isolate->GetCurrentContext(); v8::HandleScope handScope(isolate); auto self = args.Holder(); auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1)); auto thisCharacter = static_cast<entities::Character*>(wrap->Value()); if (args.Length() != 1) { shared::api::logging::Log("Invalid number of arguments for 'GetCharactersWithinDistance'."); return; } auto distance = static_cast<float>(args[0]->NumberValue(context).FromMaybe(0.0f)); if (distance == 0.0f) { auto emptyArray = v8::Array::New(isolate, 0); args.GetReturnValue().Set(emptyArray); return; } auto& world = thisCharacter->GetCurrentWorld(); auto charactersWithinDistance = world->GetCharactersWithinDistance(thisCharacter->GetEntityId(), distance); v8::Local<v8::Array> result = v8::Array::New(isolate, static_cast<int>(charactersWithinDistance.size())); auto index = 0u; for (const auto& character : charactersWithinDistance) { auto objectInstance = CharacterScriptObject::GetObjectTemplateInstance(isolate, character.get()); result->Set(context, index++, objectInstance).Check(); } args.GetReturnValue().Set(result); } }
36.887805
125
0.626686
snowmeltarcade
d99150de49d2059391a435d301295a0d27fea848
6,834
hpp
C++
src/asio_cares/include/asio_cares/channel.hpp
RobertLeahy/ASIO-C-ARES
f62150d4c5467396ac79fade11c6885cd5fe942c
[ "Unlicense" ]
5
2019-03-30T17:42:31.000Z
2021-07-02T18:48:05.000Z
src/asio_cares/include/asio_cares/channel.hpp
RobertLeahy/ASIO-C-ARES
f62150d4c5467396ac79fade11c6885cd5fe942c
[ "Unlicense" ]
null
null
null
src/asio_cares/include/asio_cares/channel.hpp
RobertLeahy/ASIO-C-ARES
f62150d4c5467396ac79fade11c6885cd5fe942c
[ "Unlicense" ]
3
2019-01-30T03:43:58.000Z
2020-03-04T04:01:55.000Z
/** * \file */ #pragma once #include <ares.h> #include <boost/asio/deadline_timer.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/strand.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ip/udp.hpp> #include <boost/system/error_code.hpp> #include <mpark/variant.hpp> #include <utility> #include <vector> namespace asio_cares { /** * Encapsulates a libcares channel and the state * required for it to interoperate with Boost.Asio. */ class channel { public: channel () = delete; channel (const channel &) = delete; channel (channel &&) = delete; channel & operator = (const channel &) = delete; channel & operator = (channel &&) = delete; /** * Creates a new channel object by calling * `ares_init`. * * \param [in] ios * The `io_service` which shall be used for * asynchronous operations. This reference must * remain valid for the lifetime of the object. */ explicit channel (boost::asio::io_service & ios); /** * Creates a new channel object by calling * `ares_init_options`. * * \param [in] options * An `ares_options` object giving the options * to pass as the second argument to `ares_init_options`. * \param [in] optmask * An integer giving the mask to pass as the * third argument to `ares_init_options`. * \param [in] ios * The `io_service` which shall be used for * asynchronous operations. This reference must * remain valid for the lifetime of the object. */ channel (const ares_options & options, int optmask, boost::asio::io_service & ios); /** * Cleans up a channel object. */ ~channel () noexcept; /** * Retrieves the managed `io_service`. * * \return * A reference to an `io_service` object. */ boost::asio::io_service & get_io_service () noexcept; /** * All operations on a channel are conceptually * operations on the underlying `ares_channel` * which are not thread safe, accordingly a * `boost::asio::strand` is used to ensure the * `ares_channel` is only accessed by one thread * of execution at a time. This method retrieves * that `boost::asio::strand` object. * * \return * A reference to a `strand`. */ boost::asio::strand & get_strand () noexcept; /** * Operations on a channel have timeouts. This * method retrieves the `boost::asio::deadline_timer` * used to track those timeouts. * * \return * A reference to a `deadline_timer`. */ boost::asio::deadline_timer & get_timer () noexcept; private: using socket_type = mpark::variant<boost::asio::ip::tcp::socket, boost::asio::ip::udp::socket>; template <typename Function> static constexpr auto is_nothrow_invocable = noexcept(std::declval<Function>()(std::declval<boost::asio::ip::tcp::socket &>())) && noexcept(std::declval<Function>()(std::declval<boost::asio::ip::udp::socket &>())); public: /** * The type used to represent a socket when * it is acquired. * * In addition to making a certain socket * accessible alse releases the socket back * to the associated \ref channel once its * lifetime ends. */ class socket_guard { public: socket_guard () = delete; socket_guard (const socket_guard &) = delete; socket_guard & operator = (const socket_guard &) = delete; socket_guard & operator = (socket_guard &&) = delete; socket_guard (socket_type &, channel &) noexcept; socket_guard (socket_guard &&) noexcept; ~socket_guard () noexcept; /** * Provides access to the underlying Boost.Asio * socket object by invoking a provided function * object with the socket as its sole argument. * * Since libcares sockets may be TCP or UDP * the provided function object must accept * either `boost::asio::ip::tcp::socket` or * `boost::asio::ip::udp::socket`. * * \tparam Function * The type of function object. * * \param [in] function * The function object. */ template <typename Function> void unwrap (Function && function) noexcept(is_nothrow_invocable<Function>) { assert(socket_); mpark::visit(function, *socket_); } private: socket_type * socket_; channel * channel_; }; /** * Acquires a socket. * * Acquiring a socket which has already been acquired * and not yet released results in undefined behavior. * * Once a socket has been acquired it cannot be closed * by libcares until it is released. If libcares attempts * to close it while it is acquired the closure shall be * deferred until it is released. * * \param [in] socket * The libcares handle for the socket to acquire. * * \return * A \ref socket_guard which shall release the * socket when it goes out of scope and through * which the socket may be accessed. */ socket_guard acquire_socket (ares_socket_t socket) noexcept; /** * Retrieves the managed `ares_channel` object. * * \return * An `ares_channel` object. */ operator ares_channel () noexcept; /** * Invokes a certain function object for each * socket currently in use by the channel. * * Due to the fact libcares uses both TCP and * UDP sockets the provided function object must * be invocable with both `boost::asio::ip::tcp::socket` * and `boost::asio::ip::udp::socket` objects. * * \tparam Function * The type of function object to invoke. * * \param [in] function * The function object to invoke. */ template <typename Function> void for_each_socket (Function && function) noexcept(is_nothrow_invocable<Function>) { for (auto && state : sockets_) mpark::visit(function, state.socket); } private: class socket_state { public: socket_state () = delete; socket_state (const socket_state &) = delete; socket_state (socket_state &&) = default; socket_state & operator = (const socket_state &) = delete; socket_state & operator = (socket_state &&) = default; explicit socket_state (socket_type); socket_type socket; bool acquired; bool closed; }; void release_socket (int) noexcept; using sockets_collection_type = std::vector<socket_state>; template <typename T> sockets_collection_type::iterator insertion_point (const T &) noexcept; template <typename T> sockets_collection_type::iterator find (const T &) noexcept; boost::asio::ip::tcp::socket tcp_socket (bool, boost::system::error_code &) noexcept; boost::asio::ip::udp::socket udp_socket (bool, boost::system::error_code &) noexcept; socket_type socket (bool, bool, boost::system::error_code &) noexcept; static ares_socket_t socket (int, int, int, void *) noexcept; static int close (ares_socket_t, void *) noexcept; void init () noexcept; ares_socket_functions funcs_; ares_channel channel_; boost::asio::strand strand_; sockets_collection_type sockets_; boost::asio::deadline_timer timer_; }; }
31.348624
131
0.68803
RobertLeahy
d996397acbfa59e9d565c769b6c8f268a3d6b245
17,758
cpp
C++
lib/hip_surgery/xregPAOVolAfterRepo.cpp
rg2/xreg
c06440d7995f8a441420e311bb7b6524452843d3
[ "MIT" ]
30
2020-09-29T18:36:13.000Z
2022-03-28T09:25:13.000Z
lib/hip_surgery/xregPAOVolAfterRepo.cpp
gaocong13/Orthopedic-Robot-Navigation
bf36f7de116c1c99b86c9ba50f111c3796336af0
[ "MIT" ]
3
2020-10-09T01:21:27.000Z
2020-12-10T15:39:44.000Z
lib/hip_surgery/xregPAOVolAfterRepo.cpp
rg2/xreg
c06440d7995f8a441420e311bb7b6524452843d3
[ "MIT" ]
8
2021-05-25T05:14:48.000Z
2022-02-26T12:29:50.000Z
/* * MIT License * * Copyright (c) 2020 Robert Grupp * * 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 "xregPAOVolAfterRepo.h" #include <itkNearestNeighborInterpolateImageFunction.h> #include <itkBSplineInterpolateImageFunction.h> #include <itkImageRegionIteratorWithIndex.h> #include <itkBinaryBallStructuringElement.h> #include <itkGrayscaleDilateImageFilter.h> #include "xregAssert.h" #include "xregITKBasicImageUtils.h" #include "xregITKLabelUtils.h" #include "xregSampleUtils.h" #include "xregMetalObjSampling.h" #include "xregITKCropPadUtils.h" #include "xregITKResampleUtils.h" void xreg::UpdateVolAfterRepos::operator()() { using ITKIndex = Vol::IndexType; using ContinuousIndexType = itk::ContinuousIndex<double,3>; using NNInterp = itk::NearestNeighborInterpolateImageFunction<LabelVol>; using VolInterp = itk::BSplineInterpolateImageFunction<Vol>; using VolIt = itk::ImageRegionIteratorWithIndex<Vol>; using LabelVolIt = itk::ImageRegionIteratorWithIndex<LabelVol>; xregASSERT(ImagesHaveSameCoords(labels.GetPointer(), src_vol.GetPointer())); std::mt19937 rng_eng; std::normal_distribution<VolScalar> norm_dist(0,add_rand_to_default_val_std_dev); const bool add_rand = add_rand_to_default_val_std_dev > 0; if (add_rand) { SeedRNGEngWithRandDev(&rng_eng); } const VolScalar tmp_default_val = default_val; auto replacement_intensity = [add_rand, &rng_eng, &norm_dist, tmp_default_val] () { return tmp_default_val + (add_rand ? norm_dist(rng_eng) : VolScalar(0)); }; std::normal_distribution<VolScalar> air_normal_dist(0,10); auto air_intensity = [add_rand,&rng_eng,&air_normal_dist]() { return -1000 + (add_rand ? air_normal_dist(rng_eng) : VolScalar(0)); }; const FrameTransform itk_idx_to_phys_pt = ITKImagePhysicalPointTransformsAsEigen(src_vol.GetPointer()); const FrameTransform phys_pt_to_itk_idx = itk_idx_to_phys_pt.inverse(); auto vol_interp_fn = VolInterp::New(); vol_interp_fn->SetSplineOrder(3); dst_vol = ITKImageDeepCopy(src_vol.GetPointer()); if (!labels_of_air.empty()) { for (const auto l : labels_of_air) { VolIt dst_it(dst_vol, dst_vol->GetLargestPossibleRegion()); LabelVolIt label_it(labels, labels->GetLargestPossibleRegion()); for (dst_it.GoToBegin(), label_it.GoToBegin(); !dst_it.IsAtEnd(); ++dst_it, ++label_it) { if (label_it.Value() == l) { dst_it.Value() = air_intensity(); } } } // we want to interpolate as if the cuts have already been made vol_interp_fn->SetInputImage(ITKImageDeepCopy(dst_vol.GetPointer())); } else { // no cuts incorporated, just use the source volume vol_interp_fn->SetInputImage(src_vol); } const bool do_dilate = labels_dilate_rad; auto label_interp = NNInterp::New(); if (!do_dilate) { // we can look directly into the original labelmap if we are not // dilating it label_interp->SetInputImage(labels); } Pt3 tmp_idx; ContinuousIndexType tmp_itk_idx; const unsigned long num_repo_objs = labels_of_repo_objs.size(); xregASSERT(num_repo_objs == repo_objs_xforms.size()); for (unsigned long obj_idx = 0; obj_idx < num_repo_objs; ++obj_idx) { const LabelScalar cur_label = labels_of_repo_objs[obj_idx]; if (do_dilate) { using MorphKernel = itk::BinaryBallStructuringElement<LabelScalar,3>; using DilateFilter = itk::GrayscaleDilateImageFilter<LabelVol,LabelVol,MorphKernel>; LabelVolPtr cur_labels = ApplyMaskToITKImage(labels.GetPointer(), labels.GetPointer(), cur_label, LabelScalar(0)); MorphKernel kern; kern.SetRadius(labels_dilate_rad); kern.CreateStructuringElement(); auto dilate_fn = DilateFilter::New(); dilate_fn->SetInput(cur_labels); dilate_fn->SetKernel(kern); dilate_fn->Update(); label_interp->SetInputImage(dilate_fn->GetOutput()); } const FrameTransform obj_warp = repo_objs_xforms[obj_idx].inverse(); VolIt dst_it(dst_vol, dst_vol->GetLargestPossibleRegion()); LabelVolIt label_it(labels, labels->GetLargestPossibleRegion()); for (dst_it.GoToBegin(), label_it.GoToBegin(); !dst_it.IsAtEnd(); ++dst_it, ++label_it) { // First find out if this location now belongs to the current repositioned object const ITKIndex& cur_idx = dst_it.GetIndex(); tmp_idx[0] = cur_idx[0]; tmp_idx[1] = cur_idx[1]; tmp_idx[2] = cur_idx[2]; // continuous index before repositioning tmp_idx = phys_pt_to_itk_idx * obj_warp * itk_idx_to_phys_pt * tmp_idx; tmp_itk_idx[0] = tmp_idx[0]; tmp_itk_idx[1] = tmp_idx[1]; tmp_itk_idx[2] = tmp_idx[2]; if (label_interp->IsInsideBuffer(tmp_itk_idx) && (label_interp->EvaluateAtContinuousIndex(tmp_itk_idx) == cur_label)) { // this location should be set to an intensity value from the repositioned object dst_it.Value() = vol_interp_fn->EvaluateAtContinuousIndex(tmp_itk_idx); } else if (label_it.Value() == cur_label) { // this location was, but no longer corresponds to the repositioned object, // fill the intensity with a default value, e.g. air dst_it.Value() = replacement_intensity(); } } } } namespace { using namespace xreg; struct PtInObjVisitor : public boost::static_visitor<bool> { Pt3 p; bool operator()(const NaiveScrewModel& s) const { return PointInNaiveScrew(s, p); } bool operator()(const NaiveKWireModel& w) const { return PointInNaiveKWire(w, p); } }; } // un-named void xreg::AddPAOScrewKWireToVol::operator()() { const size_type num_objs = obj_start_pts.size(); xregASSERT(num_objs == obj_end_pts.size()); screw_models.clear(); screw_models.reserve(num_objs); screw_poses_wrt_vol.clear(); screw_poses_wrt_vol.reserve(num_objs); kwire_models.clear(); kwire_models.reserve(num_objs); kwire_poses_wrt_vol.clear(); kwire_poses_wrt_vol.reserve(num_objs); CreateRandScrew create_rand_screws; CreateRandKWire create_rand_kwires; create_rand_kwires.set_debug_output_stream(*this); std::uniform_real_distribution<double> obj_dist(0,1); std::uniform_real_distribution<PixelScalar> screw_hu_dist(14000, 16000); std::uniform_real_distribution<PixelScalar> kwire_hu_dist(14000, 26000); using ObjVar = boost::variant<NaiveScrewModel,NaiveKWireModel>; using ObjVarList = std::vector<ObjVar>; ObjVarList objs; objs.reserve(num_objs); FrameTransformList obj_to_vol_poses; obj_to_vol_poses.reserve(num_objs); std::vector<PixelScalar> obj_hu_vals; obj_hu_vals.reserve(num_objs); std::vector<BoundBox3> obj_bbs; obj_bbs.reserve(num_objs); // for each object for (size_type obj_idx = 0; obj_idx < num_objs; ++obj_idx) { this->dout() << "creating object model: " << obj_idx << std::endl; if (obj_dist(create_rand_screws.rng_eng) < prob_screw) { this->dout() << " a screw..." << std::endl; obj_hu_vals.push_back(screw_hu_dist(create_rand_screws.rng_eng)); NaiveScrewModel s; FrameTransform screw_to_vol_xform; // create random screw model and get pose in volume this->dout() << "creating random screw model..." << std::endl; std::tie(s,screw_to_vol_xform) = create_rand_screws(obj_start_pts[obj_idx], obj_end_pts[obj_idx]); screw_models.push_back(s); screw_poses_wrt_vol.push_back(screw_to_vol_xform); obj_bbs.push_back(ComputeBoundingBox(s)); objs.push_back(s); obj_to_vol_poses.push_back(screw_to_vol_xform); } else { this->dout() << "a K-Wire..." << std::endl; // insert a K-Wire obj_hu_vals.push_back(kwire_hu_dist(create_rand_screws.rng_eng)); NaiveKWireModel s; FrameTransform kwire_to_vol_xform; // create random screw model and get pose in volume this->dout() << "creating random K-Wire model..." << std::endl; std::tie(s,kwire_to_vol_xform) = create_rand_kwires(obj_start_pts[obj_idx], obj_end_pts[obj_idx]); kwire_models.push_back(s); kwire_poses_wrt_vol.push_back(kwire_to_vol_xform); obj_bbs.push_back(ComputeBoundingBox(s)); objs.push_back(s); obj_to_vol_poses.push_back(kwire_to_vol_xform); } } // end for each obj BoundBox3 all_objs_bb_wrt_vol = TransformBoundBox(obj_bbs[0], obj_to_vol_poses[0]); for (size_type obj_idx = 1; obj_idx < num_objs; ++obj_idx) { all_objs_bb_wrt_vol = CombineBoundBoxes(all_objs_bb_wrt_vol, TransformBoundBox(obj_bbs[obj_idx], obj_to_vol_poses[obj_idx])); } orig_vol_start_pad = { 0, 0, 0 }; orig_vol_end_pad = { 0, 0, 0 }; { this->dout() << "determing if additional padding is needed to fit objects in volume..." << std::endl; const FrameTransform orig_vol_inds_to_phys_pts = ITKImagePhysicalPointTransformsAsEigen(orig_vol.GetPointer()); const FrameTransform phys_pts_to_orig_vol_inds = orig_vol_inds_to_phys_pts.inverse(); const BoundBox3 all_objs_bb_wrt_vol_idx = TransformBoundBox(all_objs_bb_wrt_vol, phys_pts_to_orig_vol_inds); const auto orig_vol_itk_reg = orig_vol->GetLargestPossibleRegion(); const auto orig_vol_itk_size = orig_vol_itk_reg.GetSize(); for (size_type i = 0; i < 3; ++i) { const CoordScalar lower_round = std::floor(all_objs_bb_wrt_vol_idx.lower(i)); orig_vol_start_pad[i] = (lower_round < 0) ? static_cast<size_type>(-lower_round) : size_type(0); const CoordScalar upper_round = std::ceil(all_objs_bb_wrt_vol_idx.upper(i)); orig_vol_end_pad[i] = (upper_round > orig_vol_itk_size[i]) ? static_cast<size_type>(upper_round - orig_vol_itk_size[i]) : size_type(0); } bool need_to_pad = false; for (size_type i = 0; i < 3; ++i) { if (orig_vol_start_pad[i] || orig_vol_end_pad[i]) { need_to_pad = true; break; } } if (need_to_pad) { this->dout() << "padding volume..." << std::endl; orig_vol_pad = ITKPadImage(orig_vol.GetPointer(), orig_vol_start_pad, orig_vol_end_pad, PixelScalar(-1000)); } else { this->dout() << "no padding required..." << std::endl; orig_vol_pad = ITKImageDeepCopy(orig_vol.GetPointer()); } } VolPtr vol_sup; if (std::abs(super_sample_factor - 1.0) > 1.0e-3) { // super sample the original volume this->dout() << "super sampling (padded) original volume..." << std::endl; vol_sup = DownsampleImageNNInterp(orig_vol_pad.GetPointer(), super_sample_factor, 0.0); } else { this->dout() << "no super-sampling..." << std::endl; vol_sup = ITKImageDeepCopy(orig_vol_pad.GetPointer()); } const FrameTransform vol_inds_to_phys_pts = ITKImagePhysicalPointTransformsAsEigen(vol_sup.GetPointer()); const FrameTransform phys_pts_to_vol_inds = vol_inds_to_phys_pts.inverse(); // keep track of voxels that are marked as belonging to a screw, we'll downsample // this back to the original resolution and only update the screw voxels // in the final output VolPtr voxels_modified_sup = MakeITKNDVol<PixelScalar>(vol_sup->GetLargestPossibleRegion()); const auto itk_size = vol_sup->GetLargestPossibleRegion().GetSize(); // for each object for (size_type obj_idx = 0; obj_idx < num_objs; ++obj_idx) { this->dout() << "inserting object: " << obj_idx << std::endl; const FrameTransform& obj_to_vol_xform = obj_to_vol_poses[obj_idx]; const FrameTransform obj_to_vol_idx = phys_pts_to_vol_inds * obj_to_vol_xform; const auto obj_bb_wrt_inds = TransformBoundBox(obj_bbs[obj_idx], obj_to_vol_idx); const std::array<size_type,3> start_inds = { static_cast<size_type>(std::max(CoordScalar(0), std::floor(obj_bb_wrt_inds.lower(0)))), static_cast<size_type>(std::max(CoordScalar(0), std::floor(obj_bb_wrt_inds.lower(1)))), static_cast<size_type>(std::max(CoordScalar(0), std::floor(obj_bb_wrt_inds.lower(2)))) }; const std::array<size_type,3> stop_inds = { static_cast<size_type>(std::min(CoordScalar(itk_size[0]), std::ceil(obj_bb_wrt_inds.upper(0)))), static_cast<size_type>(std::min(CoordScalar(itk_size[1]), std::ceil(obj_bb_wrt_inds.upper(1)))), static_cast<size_type>(std::min(CoordScalar(itk_size[2]), std::ceil(obj_bb_wrt_inds.upper(2)))) }; const std::array<size_type,3> num_inds_to_check = { stop_inds[0] - start_inds[0] + 1, stop_inds[1] - start_inds[1] + 1, stop_inds[2] - start_inds[2] + 1 }; const size_type xy_num_inds_to_check = num_inds_to_check[0] * num_inds_to_check[1]; const size_type tot_num_inds_to_check = xy_num_inds_to_check * num_inds_to_check[2]; // now fill intersecting voxels const FrameTransform vol_to_obj_xform = obj_to_vol_xform.inverse(); const FrameTransform vol_idx_to_obj_pts = vol_to_obj_xform * vol_inds_to_phys_pts; const PixelScalar obj_hu = obj_hu_vals[obj_idx]; ObjVar& obj = objs[obj_idx]; auto insert_obj_intens_fn = [&] (const RangeType& r) { Vol::IndexType itk_idx; PtInObjVisitor pt_in_obj; Pt3 idx; size_type cur_idx_1d = r.begin(); // these indices need to be offset by the start_inds[] size_type z_idx = cur_idx_1d / xy_num_inds_to_check; const size_type tmp = cur_idx_1d - (z_idx * xy_num_inds_to_check); size_type y_idx = tmp / num_inds_to_check[0]; size_type x_idx = tmp - (y_idx * num_inds_to_check[0]); for (; cur_idx_1d < r.end(); ++cur_idx_1d) { itk_idx[0] = start_inds[0] + x_idx; itk_idx[1] = start_inds[1] + y_idx; itk_idx[2] = start_inds[2] + z_idx; idx[0] = itk_idx[0]; idx[1] = itk_idx[1]; idx[2] = itk_idx[2]; pt_in_obj.p = vol_idx_to_obj_pts * idx; if (boost::apply_visitor(pt_in_obj, obj)) { vol_sup->SetPixel(itk_idx, obj_hu); voxels_modified_sup->SetPixel(itk_idx, 1); } // increment ++x_idx; if (x_idx == num_inds_to_check[0]) { x_idx = 0; ++y_idx; if (y_idx == num_inds_to_check[1]) { y_idx = 0; ++z_idx; } } } }; this->dout() << "running parallel for over all indices to check..." << std::endl; ParallelFor(insert_obj_intens_fn, RangeType(0, tot_num_inds_to_check)); } // end for each obj // downsample back to original resolution this->dout() << "downsampling from super-sampled..." << std::endl; // -1 --> smooth before downsampling and choose the kernel size automatically VolPtr vol_tmp_ds = DownsampleImageNNInterp(vol_sup.GetPointer(), 1.0 / super_sample_factor, -1.0); VolPtr modified_ds = DownsampleImageLinearInterp(voxels_modified_sup.GetPointer(), 1.0 / super_sample_factor, -1.0); // adding in screw voxels in the original volume resolution this->dout() << "updating original volume intensities where necessary and creating label map..." << std::endl; obj_vol = ITKImageDeepCopy(orig_vol_pad.GetPointer()); obj_labels = LabelVol::New(); obj_labels->SetDirection(obj_vol->GetDirection()); obj_labels->SetSpacing(obj_vol->GetSpacing()); obj_labels->SetOrigin(obj_vol->GetOrigin()); obj_labels->SetRegions(obj_vol->GetLargestPossibleRegion()); obj_labels->Allocate(); obj_labels->FillBuffer(0); itk::ImageRegionIteratorWithIndex<Vol> mod_ds_it(modified_ds, modified_ds->GetLargestPossibleRegion()); while (!mod_ds_it.IsAtEnd()) { if (mod_ds_it.Value() > 1.0e-6) { const auto idx = mod_ds_it.GetIndex(); obj_vol->SetPixel(idx, vol_tmp_ds->GetPixel(idx)); obj_labels->SetPixel(idx, 1); } ++mod_ds_it; } }
33.192523
115
0.661843
rg2
d2664dc46a98979d200eefbe15b199bf717c247d
36,291
hpp
C++
src/axom/mint/execution/internal/for_all_faces.hpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
null
null
null
src/axom/mint/execution/internal/for_all_faces.hpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
null
null
null
src/axom/mint/execution/internal/for_all_faces.hpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #ifndef MINT_FOR_ALL_FACES_HPP_ #define MINT_FOR_ALL_FACES_HPP_ // Axom core includes #include "axom/config.hpp" // compile time definitions #include "axom/core/execution/execution_space.hpp" // for execution_space traits #include "axom/core/execution/for_all.hpp" // for axom::for_all // mint includes #include "axom/mint/execution/xargs.hpp" // for xargs #include "axom/mint/config.hpp" // for compile-time definitions #include "axom/mint/mesh/Mesh.hpp" // for Mesh #include "axom/mint/mesh/StructuredMesh.hpp" // for StructuredMesh #include "axom/mint/mesh/UniformMesh.hpp" // for UniformMesh #include "axom/mint/mesh/RectilinearMesh.hpp" // for RectilinearMesh #include "axom/mint/mesh/CurvilinearMesh.hpp" // for CurvilinearMesh #include "axom/mint/execution/internal/helpers.hpp" // for for_all_coords #include "axom/mint/execution/internal/structured_exec.hpp" #include "axom/core/numerics/Matrix.hpp" // for Matrix #ifdef AXOM_USE_RAJA #include "RAJA/RAJA.hpp" #endif namespace axom { namespace mint { namespace internal { namespace helpers { //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_I_faces(xargs::ij, const StructuredMesh& m, KernelType&& kernel) { SLIC_ERROR_IF(m.getDimension() != 2, "Mesh must be 2D."); const IndexType INodeResolution = m.getNodeResolution(I_DIRECTION); const IndexType Ni = INodeResolution; const IndexType Nj = m.getCellResolution(J_DIRECTION); #ifdef AXOM_USE_RAJA RAJA::RangeSegment i_range(0, Ni); RAJA::RangeSegment j_range(0, Nj); using exec_pol = typename structured_exec<ExecPolicy>::loop2d_policy; RAJA::kernel<exec_pol>( RAJA::make_tuple(i_range, j_range), AXOM_LAMBDA(IndexType i, IndexType j) { const IndexType faceID = i + j * INodeResolution; kernel(faceID, i, j); }); #else constexpr bool is_serial = std::is_same<ExecPolicy, axom::SEQ_EXEC>::value; AXOM_STATIC_ASSERT(is_serial); for(IndexType j = 0; j < Nj; ++j) { const IndexType offset = j * INodeResolution; for(IndexType i = 0; i < Ni; ++i) { const IndexType faceID = i + offset; kernel(faceID, i, j); } } #endif } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_I_faces(xargs::ijk, const StructuredMesh& m, KernelType&& kernel) { SLIC_ERROR_IF(m.getDimension() != 3, "Mesh must be a 3D."); const IndexType INodeResolution = m.getNodeResolution(I_DIRECTION); const IndexType numIFacesInKSlice = INodeResolution * m.getCellResolution(J_DIRECTION); const IndexType Ni = INodeResolution; const IndexType Nj = m.getCellResolution(J_DIRECTION); const IndexType Nk = m.getCellResolution(K_DIRECTION); #ifdef AXOM_USE_RAJA RAJA::RangeSegment i_range(0, Ni); RAJA::RangeSegment j_range(0, Nj); RAJA::RangeSegment k_range(0, Nk); using exec_pol = typename structured_exec<ExecPolicy>::loop3d_policy; RAJA::kernel<exec_pol>( RAJA::make_tuple(i_range, j_range, k_range), AXOM_LAMBDA(IndexType i, IndexType j, IndexType k) { const IndexType faceID = i + j * INodeResolution + k * numIFacesInKSlice; kernel(faceID, i, j, k); }); #else constexpr bool is_serial = std::is_same<ExecPolicy, axom::SEQ_EXEC>::value; AXOM_STATIC_ASSERT(is_serial); for(IndexType k = 0; k < Nk; ++k) { const IndexType k_offset = k * numIFacesInKSlice; for(IndexType j = 0; j < Nj; ++j) { const IndexType offset = j * INodeResolution + k_offset; for(IndexType i = 0; i < Ni; ++i) { const IndexType faceID = i + offset; kernel(faceID, i, j, k); } } } #endif } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_J_faces(xargs::ij, const StructuredMesh& m, KernelType&& kernel) { SLIC_ERROR_IF(m.getDimension() != 2, "Mesh must be 2D."); const IndexType ICellResolution = m.getCellResolution(I_DIRECTION); const IndexType numIFaces = m.getTotalNumFaces(I_DIRECTION); const IndexType Ni = ICellResolution; const IndexType Nj = m.getNodeResolution(J_DIRECTION); #ifdef AXOM_USE_RAJA RAJA::RangeSegment i_range(0, Ni); RAJA::RangeSegment j_range(0, Nj); using exec_pol = typename structured_exec<ExecPolicy>::loop2d_policy; RAJA::kernel<exec_pol>( RAJA::make_tuple(i_range, j_range), AXOM_LAMBDA(IndexType i, IndexType j) { const IndexType faceID = numIFaces + i + j * ICellResolution; kernel(faceID, i, j); }); #else constexpr bool is_serial = std::is_same<ExecPolicy, axom::SEQ_EXEC>::value; AXOM_STATIC_ASSERT(is_serial); for(IndexType j = 0; j < Nj; ++j) { const IndexType offset = numIFaces + j * ICellResolution; for(IndexType i = 0; i < Ni; ++i) { const IndexType faceID = i + offset; kernel(faceID, i, j); } } #endif } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_J_faces(xargs::ijk, const StructuredMesh& m, KernelType&& kernel) { SLIC_ERROR_IF(m.getDimension() != 3, "Mesh must be 3D."); const IndexType numIFaces = m.getTotalNumFaces(I_DIRECTION); const IndexType ICellResolution = m.getCellResolution(I_DIRECTION); const IndexType numJFacesInKSlice = ICellResolution * m.getNodeResolution(J_DIRECTION); const IndexType Ni = ICellResolution; const IndexType Nj = m.getNodeResolution(J_DIRECTION); const IndexType Nk = m.getCellResolution(K_DIRECTION); #ifdef AXOM_USE_RAJA RAJA::RangeSegment i_range(0, Ni); RAJA::RangeSegment j_range(0, Nj); RAJA::RangeSegment k_range(0, Nk); using exec_pol = typename structured_exec<ExecPolicy>::loop3d_policy; RAJA::kernel<exec_pol>( RAJA::make_tuple(i_range, j_range, k_range), AXOM_LAMBDA(IndexType i, IndexType j, IndexType k) { const IndexType jp = j * ICellResolution; const IndexType kp = k * numJFacesInKSlice; const IndexType faceID = numIFaces + i + jp + kp; kernel(faceID, i, j, k); }); #else constexpr bool is_serial = std::is_same<ExecPolicy, axom::SEQ_EXEC>::value; AXOM_STATIC_ASSERT(is_serial); for(IndexType k = 0; k < Nk; ++k) { const IndexType k_offset = k * numJFacesInKSlice + numIFaces; for(IndexType j = 0; j < Nj; ++j) { const IndexType offset = j * ICellResolution + k_offset; for(IndexType i = 0; i < Ni; ++i) { const IndexType faceID = i + offset; kernel(faceID, i, j, k); } } } #endif } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_K_faces(xargs::ijk, const StructuredMesh& m, KernelType&& kernel) { SLIC_ERROR_IF(m.getDimension() != 3, "Mesh must be 3D."); const IndexType numIJFaces = m.getTotalNumFaces(I_DIRECTION) + m.getTotalNumFaces(J_DIRECTION); const IndexType ICellResolution = m.getCellResolution(I_DIRECTION); const IndexType cellKp = m.cellKp(); const IndexType Ni = ICellResolution; const IndexType Nj = m.getCellResolution(J_DIRECTION); const IndexType Nk = m.getNodeResolution(K_DIRECTION); #ifdef AXOM_USE_RAJA RAJA::RangeSegment i_range(0, Ni); RAJA::RangeSegment j_range(0, Nj); RAJA::RangeSegment k_range(0, Nk); using exec_pol = typename structured_exec<ExecPolicy>::loop3d_policy; RAJA::kernel<exec_pol>( RAJA::make_tuple(i_range, j_range, k_range), AXOM_LAMBDA(IndexType i, IndexType j, IndexType k) { const IndexType jp = j * ICellResolution; const IndexType kp = k * cellKp; const IndexType faceID = numIJFaces + i + jp + kp; kernel(faceID, i, j, k); }); #else constexpr bool is_serial = std::is_same<ExecPolicy, axom::SEQ_EXEC>::value; AXOM_STATIC_ASSERT(is_serial); for(IndexType k = 0; k < Nk; ++k) { const IndexType k_offset = k * cellKp + numIJFaces; for(IndexType j = 0; j < Nj; ++j) { const IndexType offset = j * ICellResolution + k_offset; for(IndexType i = 0; i < Ni; ++i) { const IndexType faceID = i + offset; kernel(faceID, i, j, k); } } } #endif } } /* namespace helpers */ //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces_impl(xargs::index, const Mesh& m, KernelType&& kernel) { const IndexType numFaces = m.getNumberOfFaces(); axom::for_all<ExecPolicy>(numFaces, std::forward<KernelType>(kernel)); } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces(xargs::index, const Mesh& m, KernelType&& kernel) { return for_all_faces_impl<ExecPolicy>(xargs::index(), m, std::forward<KernelType>(kernel)); } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces_impl(xargs::nodeids, const StructuredMesh& m, KernelType&& kernel) { const IndexType dimension = m.getDimension(); const IndexType* offsets = m.getCellNodeOffsetsArray(); const IndexType cellNodeOffset3 = offsets[3]; if(dimension == 2) { const IndexType numIFaces = m.getTotalNumFaces(I_DIRECTION); helpers::for_all_I_faces<ExecPolicy>( xargs::ij(), m, AXOM_LAMBDA(IndexType faceID, IndexType AXOM_UNUSED_PARAM(i), IndexType AXOM_UNUSED_PARAM(j)) { IndexType nodes[2]; nodes[0] = faceID; nodes[1] = nodes[0] + cellNodeOffset3; kernel(faceID, nodes, 2); }); helpers::for_all_J_faces<ExecPolicy>( xargs::ij(), m, AXOM_LAMBDA(IndexType faceID, IndexType AXOM_UNUSED_PARAM(i), IndexType j) { const IndexType shiftedID = faceID - numIFaces; IndexType nodes[2]; nodes[0] = shiftedID + j; nodes[1] = nodes[0] + 1; kernel(faceID, nodes, 2); }); } else { SLIC_ERROR_IF(dimension != 3, "for_all_faces is only valid for 2 or 3D meshes."); const IndexType numIFaces = m.getTotalNumFaces(I_DIRECTION); const IndexType numIJFaces = numIFaces + m.getTotalNumFaces(J_DIRECTION); const IndexType INodeResolution = m.getNodeResolution(I_DIRECTION); const IndexType JNodeResolution = m.getNodeResolution(J_DIRECTION); const IndexType KFaceNodeStride = m.getCellResolution(I_DIRECTION) + m.getCellResolution(J_DIRECTION) + 1; const IndexType cellNodeOffset2 = offsets[2]; const IndexType cellNodeOffset4 = offsets[4]; const IndexType cellNodeOffset5 = offsets[5]; const IndexType cellNodeOffset7 = offsets[7]; helpers::for_all_I_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType AXOM_UNUSED_PARAM(i), IndexType AXOM_UNUSED_PARAM(j), IndexType k) { IndexType nodes[4]; nodes[0] = faceID + k * INodeResolution; nodes[1] = nodes[0] + cellNodeOffset4; nodes[2] = nodes[0] + cellNodeOffset7; nodes[3] = nodes[0] + cellNodeOffset3; kernel(faceID, nodes, 4); }); helpers::for_all_J_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType AXOM_UNUSED_PARAM(i), IndexType j, IndexType k) { const IndexType shiftedID = faceID - numIFaces; IndexType nodes[4]; nodes[0] = shiftedID + j + k * JNodeResolution; nodes[1] = nodes[0] + 1; nodes[2] = nodes[0] + cellNodeOffset5; nodes[3] = nodes[0] + cellNodeOffset4; kernel(faceID, nodes, 4); }); helpers::for_all_K_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType AXOM_UNUSED_PARAM(i), IndexType j, IndexType k) { const IndexType shiftedID = faceID - numIJFaces; IndexType nodes[4]; nodes[0] = shiftedID + j + k * KFaceNodeStride; nodes[1] = nodes[0] + 1; nodes[2] = nodes[0] + cellNodeOffset2; nodes[3] = nodes[0] + cellNodeOffset3; kernel(faceID, nodes, 4); }); } } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces_impl(xargs::nodeids, const UnstructuredMesh<SINGLE_SHAPE>& m, KernelType&& kernel) { SLIC_ERROR_IF(m.getNumberOfFaces() <= 0, "No faces in the mesh, perhaps you meant to call " << "UnstructuredMesh::initializeFaceConnectivity first."); const IndexType* faces_to_nodes = m.getFaceNodesArray(); const IndexType num_nodes = m.getNumberOfFaceNodes(); for_all_faces_impl<ExecPolicy>( xargs::index(), m, AXOM_LAMBDA(IndexType faceID) { kernel(faceID, faces_to_nodes + faceID * num_nodes, num_nodes); }); } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces_impl(xargs::nodeids, const UnstructuredMesh<MIXED_SHAPE>& m, KernelType&& kernel) { SLIC_ERROR_IF(m.getNumberOfFaces() <= 0, "No faces in the mesh, perhaps you meant to call " << "UnstructuredMesh::initializeFaceConnectivity first."); const IndexType* faces_to_nodes = m.getFaceNodesArray(); const IndexType* offsets = m.getFaceNodesOffsetsArray(); for_all_faces_impl<ExecPolicy>( xargs::index(), m, AXOM_LAMBDA(IndexType faceID) { const IndexType num_nodes = offsets[faceID + 1] - offsets[faceID]; kernel(faceID, faces_to_nodes + offsets[faceID], num_nodes); }); } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces(xargs::nodeids, const Mesh& m, KernelType&& kernel) { SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3); if(m.isStructured()) { const StructuredMesh& sm = static_cast<const StructuredMesh&>(m); for_all_faces_impl<ExecPolicy>(xargs::nodeids(), sm, std::forward<KernelType>(kernel)); } else if(m.hasMixedCellTypes()) { const UnstructuredMesh<MIXED_SHAPE>& um = static_cast<const UnstructuredMesh<MIXED_SHAPE>&>(m); for_all_faces_impl<ExecPolicy>(xargs::nodeids(), um, std::forward<KernelType>(kernel)); } else { const UnstructuredMesh<SINGLE_SHAPE>& um = static_cast<const UnstructuredMesh<SINGLE_SHAPE>&>(m); for_all_faces_impl<ExecPolicy>(xargs::nodeids(), um, std::forward<KernelType>(kernel)); } } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces_impl(xargs::cellids, const StructuredMesh& m, KernelType&& kernel) { const IndexType ICellResolution = m.getCellResolution(I_DIRECTION); const IndexType JCellResolution = m.getCellResolution(J_DIRECTION); const IndexType cellJp = m.cellJp(); const int dimension = m.getDimension(); if(dimension == 2) { helpers::for_all_I_faces<ExecPolicy>( xargs::ij(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) { IndexType cellIDTwo = i + j * cellJp; IndexType cellIDOne = cellIDTwo - 1; if(i == 0) { cellIDOne = cellIDTwo; cellIDTwo = -1; } else if(i == ICellResolution) { cellIDTwo = -1; } kernel(faceID, cellIDOne, cellIDTwo); }); helpers::for_all_J_faces<ExecPolicy>( xargs::ij(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) { IndexType cellIDTwo = i + j * cellJp; IndexType cellIDOne = cellIDTwo - cellJp; if(j == 0) { cellIDOne = cellIDTwo; cellIDTwo = -1; } else if(j == JCellResolution) { cellIDTwo = -1; } kernel(faceID, cellIDOne, cellIDTwo); }); } else { SLIC_ERROR_IF(dimension != 3, "for_all_faces only valid for 2 or 3D meshes."); const IndexType KCellResolution = m.getCellResolution(K_DIRECTION); const IndexType cellKp = m.cellKp(); helpers::for_all_I_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) { IndexType cellIDTwo = i + j * cellJp + k * cellKp; IndexType cellIDOne = cellIDTwo - 1; if(i == 0) { cellIDOne = cellIDTwo; cellIDTwo = -1; } else if(i == ICellResolution) { cellIDTwo = -1; } kernel(faceID, cellIDOne, cellIDTwo); }); helpers::for_all_J_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) { IndexType cellIDTwo = i + j * cellJp + k * cellKp; IndexType cellIDOne = cellIDTwo - cellJp; if(j == 0) { cellIDOne = cellIDTwo; cellIDTwo = -1; } else if(j == JCellResolution) { cellIDTwo = -1; } kernel(faceID, cellIDOne, cellIDTwo); }); helpers::for_all_K_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) { IndexType cellIDTwo = i + j * cellJp + k * cellKp; IndexType cellIDOne = cellIDTwo - cellKp; if(k == 0) { cellIDOne = cellIDTwo; cellIDTwo = -1; } else if(k == KCellResolution) { cellIDTwo = -1; } kernel(faceID, cellIDOne, cellIDTwo); }); } } //------------------------------------------------------------------------------ template <typename ExecPolicy, Topology TOPO, typename KernelType> inline void for_all_faces_impl(xargs::cellids, const UnstructuredMesh<TOPO>& m, KernelType&& kernel) { SLIC_ERROR_IF(m.getNumberOfFaces() <= 0, "No faces in the mesh, perhaps you meant to call " << "UnstructuredMesh::initializeFaceConnectivity first."); const IndexType* faces_to_cells = m.getFaceCellsArray(); for_all_faces_impl<ExecPolicy>( xargs::index(), m, AXOM_LAMBDA(IndexType faceID) { const IndexType offset = 2 * faceID; kernel(faceID, faces_to_cells[offset], faces_to_cells[offset + 1]); }); } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces(xargs::cellids, const Mesh& m, KernelType&& kernel) { SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3); if(m.isStructured()) { const StructuredMesh& sm = static_cast<const StructuredMesh&>(m); for_all_faces_impl<ExecPolicy>(xargs::cellids(), sm, std::forward<KernelType>(kernel)); } else if(m.hasMixedCellTypes()) { const UnstructuredMesh<MIXED_SHAPE>& um = static_cast<const UnstructuredMesh<MIXED_SHAPE>&>(m); for_all_faces_impl<ExecPolicy>(xargs::cellids(), um, std::forward<KernelType>(kernel)); } else { const UnstructuredMesh<SINGLE_SHAPE>& um = static_cast<const UnstructuredMesh<SINGLE_SHAPE>&>(m); for_all_faces_impl<ExecPolicy>(xargs::cellids(), um, std::forward<KernelType>(kernel)); } } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces_impl(xargs::coords, const UniformMesh& m, KernelType&& kernel) { constexpr bool NO_COPY = true; SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3); const int dimension = m.getDimension(); const double* origin = m.getOrigin(); const double* spacing = m.getSpacing(); const IndexType nodeJp = m.nodeJp(); const IndexType nodeKp = m.nodeKp(); const double x0 = origin[0]; const double dx = spacing[0]; const double y0 = origin[1]; const double dy = spacing[1]; const double z0 = origin[2]; const double dz = spacing[2]; if(dimension == 2) { helpers::for_all_I_faces<ExecPolicy>( xargs::ij(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) { const IndexType n0 = i + j * nodeJp; const IndexType nodeIDs[2] = {n0, n0 + nodeJp}; double coords[4] = {x0 + i * dx, y0 + j * dy, x0 + i * dx, y0 + (j + 1) * dy}; numerics::Matrix<double> coordsMatrix(dimension, 2, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); helpers::for_all_J_faces<ExecPolicy>( xargs::ij(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) { const IndexType n0 = i + j * nodeJp; const IndexType nodeIDs[2] = {n0, n0 + 1}; double coords[4] = {x0 + i * dx, y0 + j * dy, x0 + (i + 1) * dx, y0 + j * dy}; numerics::Matrix<double> coordsMatrix(dimension, 2, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); } else { helpers::for_all_I_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) { const IndexType n0 = i + j * nodeJp + k * nodeKp; const IndexType nodeIDs[4] = {n0, n0 + nodeKp, n0 + nodeJp + nodeKp, n0 + nodeJp}; double coords[12] = {x0 + i * dx, y0 + j * dy, z0 + k * dz, x0 + i * dx, y0 + j * dy, z0 + (k + 1) * dz, x0 + i * dx, y0 + (j + 1) * dy, z0 + (k + 1) * dz, x0 + i * dx, y0 + (j + 1) * dy, z0 + k * dz}; numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); helpers::for_all_J_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) { const IndexType n0 = i + j * nodeJp + k * nodeKp; const IndexType nodeIDs[4] = {n0, n0 + 1, n0 + 1 + nodeKp, n0 + nodeKp}; double coords[12] = {x0 + i * dx, y0 + j * dy, z0 + k * dz, x0 + (i + 1) * dx, y0 + j * dy, z0 + k * dz, x0 + (i + 1) * dx, y0 + j * dy, z0 + (k + 1) * dz, x0 + i * dx, y0 + j * dy, z0 + (k + 1) * dz}; numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); helpers::for_all_K_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) { const IndexType n0 = i + j * nodeJp + k * nodeKp; const IndexType nodeIDs[4] = {n0, n0 + 1, n0 + 1 + nodeJp, n0 + nodeJp}; double coords[12] = {x0 + i * dx, y0 + j * dy, z0 + k * dz, x0 + (i + 1) * dx, y0 + j * dy, z0 + k * dz, x0 + (i + 1) * dx, y0 + (j + 1) * dy, z0 + k * dz, x0 + i * dx, y0 + (j + 1) * dy, z0 + k * dz}; numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); } } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces_impl(xargs::coords, const RectilinearMesh& m, KernelType&& kernel) { constexpr bool NO_COPY = true; SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3); const int dimension = m.getDimension(); const IndexType nodeJp = m.nodeJp(); const IndexType nodeKp = m.nodeKp(); const double* x = m.getCoordinateArray(X_COORDINATE); const double* y = m.getCoordinateArray(Y_COORDINATE); if(dimension == 2) { helpers::for_all_I_faces<ExecPolicy>( xargs::ij(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) { const IndexType n0 = i + j * nodeJp; const IndexType nodeIDs[2] = {n0, n0 + nodeJp}; double coords[4] = {x[i], y[j], x[i], y[j + 1]}; numerics::Matrix<double> coordsMatrix(dimension, 2, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); helpers::for_all_J_faces<ExecPolicy>( xargs::ij(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) { const IndexType n0 = i + j * nodeJp; const IndexType nodeIDs[2] = {n0, n0 + 1}; double coords[4] = {x[i], y[j], x[i + 1], y[j]}; numerics::Matrix<double> coordsMatrix(dimension, 2, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); } else { const double* z = m.getCoordinateArray(Z_COORDINATE); helpers::for_all_I_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) { const IndexType n0 = i + j * nodeJp + k * nodeKp; const IndexType nodeIDs[4] = {n0, n0 + nodeKp, n0 + nodeJp + nodeKp, n0 + nodeJp}; double coords[12] = {x[i], y[j], z[k], x[i], y[j], z[k + 1], x[i], y[j + 1], z[k + 1], x[i], y[j + 1], z[k]}; numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); helpers::for_all_J_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) { const IndexType n0 = i + j * nodeJp + k * nodeKp; const IndexType nodeIDs[4] = {n0, n0 + 1, n0 + 1 + nodeKp, n0 + nodeKp}; double coords[12] = {x[i], y[j], z[k], x[i + 1], y[j], z[k], x[i + 1], y[j], z[k + 1], x[i], y[j], z[k + 1]}; numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); helpers::for_all_K_faces<ExecPolicy>( xargs::ijk(), m, AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) { const IndexType n0 = i + j * nodeJp + k * nodeKp; const IndexType nodeIDs[4] = {n0, n0 + 1, n0 + 1 + nodeJp, n0 + nodeJp}; double coords[12] = {x[i], y[j], z[k], x[i + 1], y[j], z[k], x[i + 1], y[j + 1], z[k], x[i], y[j + 1], z[k]}; numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); } } //------------------------------------------------------------------------------ struct for_all_face_nodes_functor { template <typename ExecPolicy, typename MeshType, typename KernelType> inline void operator()(ExecPolicy AXOM_UNUSED_PARAM(policy), const MeshType& m, KernelType&& kernel) const { constexpr bool valid_mesh_type = std::is_base_of<Mesh, MeshType>::value; AXOM_STATIC_ASSERT(valid_mesh_type); for_all_faces_impl<ExecPolicy>(xargs::nodeids(), m, std::forward<KernelType>(kernel)); } }; //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces_impl(xargs::coords, const CurvilinearMesh& m, KernelType&& kernel) { SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3); const int dimension = m.getDimension(); if(dimension == 2) { for_all_coords<ExecPolicy, 2, 2>(for_all_face_nodes_functor(), m, std::forward<KernelType>(kernel)); } else { for_all_coords<ExecPolicy, 3, 4>(for_all_face_nodes_functor(), m, std::forward<KernelType>(kernel)); } } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType, Topology TOPO> inline void for_all_faces_impl(xargs::coords, const UnstructuredMesh<TOPO>& m, KernelType&& kernel) { constexpr bool NO_COPY = true; SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3); const int dimension = m.getDimension(); const double* x = m.getCoordinateArray(X_COORDINATE); const double* y = m.getCoordinateArray(Y_COORDINATE); if(dimension == 2) { for_all_faces_impl<ExecPolicy>( xargs::nodeids(), m, AXOM_LAMBDA(IndexType faceID, const IndexType* nodeIDs, IndexType numNodes) { double coords[2 * MAX_FACE_NODES]; for(int i = 0; i < numNodes; ++i) { const IndexType nodeID = nodeIDs[i]; coords[2 * i] = x[nodeID]; coords[2 * i + 1] = y[nodeID]; } numerics::Matrix<double> coordsMatrix(dimension, 2, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); } else { const double* z = m.getCoordinateArray(Z_COORDINATE); for_all_faces_impl<ExecPolicy>( xargs::nodeids(), m, AXOM_LAMBDA(IndexType faceID, const IndexType* nodeIDs, IndexType numNodes) { double coords[3 * MAX_FACE_NODES]; for(int i = 0; i < numNodes; ++i) { const IndexType nodeID = nodeIDs[i]; coords[3 * i] = x[nodeID]; coords[3 * i + 1] = y[nodeID]; coords[3 * i + 2] = z[nodeID]; } numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY); kernel(faceID, coordsMatrix, nodeIDs); }); } } //------------------------------------------------------------------------------ template <typename ExecPolicy, typename KernelType> inline void for_all_faces(xargs::coords, const Mesh& m, KernelType&& kernel) { SLIC_ERROR_IF(m.getDimension() <= 1 || m.getDimension() > 3, "Invalid dimension"); if(m.getMeshType() == STRUCTURED_UNIFORM_MESH) { const UniformMesh& um = static_cast<const UniformMesh&>(m); for_all_faces_impl<ExecPolicy>(xargs::coords(), um, std::forward<KernelType>(kernel)); } else if(m.getMeshType() == STRUCTURED_RECTILINEAR_MESH) { const RectilinearMesh& rm = static_cast<const RectilinearMesh&>(m); for_all_faces_impl<ExecPolicy>(xargs::coords(), rm, std::forward<KernelType>(kernel)); } else if(m.getMeshType() == STRUCTURED_CURVILINEAR_MESH) { const CurvilinearMesh& cm = static_cast<const CurvilinearMesh&>(m); for_all_faces_impl<ExecPolicy>(xargs::coords(), cm, std::forward<KernelType>(kernel)); } else if(m.getMeshType() == UNSTRUCTURED_MESH) { if(m.hasMixedCellTypes()) { const UnstructuredMesh<MIXED_SHAPE>& um = static_cast<const UnstructuredMesh<MIXED_SHAPE>&>(m); for_all_faces_impl<ExecPolicy>(xargs::coords(), um, std::forward<KernelType>(kernel)); } else { const UnstructuredMesh<SINGLE_SHAPE>& um = static_cast<const UnstructuredMesh<SINGLE_SHAPE>&>(m); for_all_faces_impl<ExecPolicy>(xargs::coords(), um, std::forward<KernelType>(kernel)); } } else { SLIC_ERROR("Unknown mesh type."); } } } /* namespace internal */ } /* namespace mint */ } /* namespace axom */ #endif /* MINT_FOR_ALL_FACES_HPP_ */
34.333964
86
0.525034
bmhan12
d266b8077013c9ffe750c9f6e334bf630be5fae3
4,056
cpp
C++
src/Seasons.cpp
powerof3/SeasonsOfSkyrim
6a35bf36e6c1d808eea6a77a485eb267e0b36236
[ "MIT" ]
6
2022-01-25T04:15:38.000Z
2022-03-04T13:02:30.000Z
src/Seasons.cpp
alandtse/SeasonsOfSkyrim
b26893a9bfb82bdcf655d0cbd6551d43e195f651
[ "MIT" ]
null
null
null
src/Seasons.cpp
alandtse/SeasonsOfSkyrim
b26893a9bfb82bdcf655d0cbd6551d43e195f651
[ "MIT" ]
4
2022-01-25T04:15:42.000Z
2022-03-14T02:53:59.000Z
#include "Seasons.h" void Season::LoadSettings(CSimpleIniA& a_ini, bool a_writeComment) { const auto& [seasonType, suffix] = ID; logger::info("{}", seasonType); INI::get_value(a_ini, validWorldspaces, seasonType.c_str(), "Worldspaces", a_writeComment ? ";Valid worldspaces." : ";"); INI::get_value(a_ini, swapActivators, seasonType.c_str(), "Activators", a_writeComment ? ";Swap objects of these types for seasonal variants." : ";"); INI::get_value(a_ini, swapFurniture, seasonType.c_str(), "Furniture", nullptr); INI::get_value(a_ini, swapMovableStatics, seasonType.c_str(), "Movable Statics", nullptr); INI::get_value(a_ini, swapStatics, seasonType.c_str(), "Statics", nullptr); INI::get_value(a_ini, swapTrees, seasonType.c_str(), "Trees", nullptr); INI::get_value(a_ini, swapFlora, seasonType.c_str(), "Flora", nullptr); INI::get_value(a_ini, swapVFX, seasonType.c_str(), "Visual Effects", nullptr); INI::get_value(a_ini, swapObjectLOD, seasonType.c_str(), "Object LOD", a_writeComment ? ";Seasonal LOD must be generated using DynDOLOD Alpha 67/SSELODGen Beta 88 or higher.\n;See https://dyndolod.info/Help/Seasons for more info" : ";"); INI::get_value(a_ini, swapTerrainLOD, seasonType.c_str(), "Terrain LOD", nullptr); INI::get_value(a_ini, swapTreeLOD, seasonType.c_str(), "Tree LOD", nullptr); INI::get_value(a_ini, swapGrass, seasonType.c_str(), "Grass", a_writeComment ? ";Enable seasonal grass types (eg. snow grass in winter)." : ";"); //make sure LOD has been generated! No need to check form swaps const auto check_if_lod_exists = [&](bool& a_swaplod, std::string_view a_lodType, std::string_view a_folderName) { if (a_swaplod) { const auto folderPath = fmt::format(a_folderName, "Tamriel"); bool exists = false; try { if (std::filesystem::exists(folderPath)) { for (const auto& entry : std::filesystem::directory_iterator(folderPath)) { if (entry.exists() && entry.is_regular_file() && entry.path().string().contains(suffix)) { exists = true; break; } } } } catch (...) {} if (!exists) { a_swaplod = false; logger::warn(" {} LOD files not found! Default LOD will be used instead", a_lodType); } else { logger::info(" {} LOD files found", a_lodType); } } }; check_if_lod_exists(swapTerrainLOD, "Terrain", R"(Data\Meshes\Terrain\{})"); check_if_lod_exists(swapObjectLOD, "Object", R"(Data\Meshes\Terrain\{}\Objects)"); check_if_lod_exists(swapTreeLOD, "Tree", R"(Data\Meshes\Terrain\{}\Trees)"); } bool Season::CanApplySnowShader() const { return season == SEASON::kWinter && is_in_valid_worldspace(); } bool Season::CanSwapForm(RE::FormType a_formType) const { return is_valid_swap_type(a_formType) && is_in_valid_worldspace(); } bool Season::CanSwapLandscape() const { return is_in_valid_worldspace(); } bool Season::CanSwapLOD(const LOD_TYPE a_type) const { if (!is_in_valid_worldspace()) { return false; } switch (a_type) { case LOD_TYPE::kTerrain: return swapTerrainLOD; case LOD_TYPE::kObject: return swapObjectLOD; case LOD_TYPE::kTree: return swapTreeLOD; default: return false; } } const SEASON_ID& Season::GetID() const { return ID; } SEASON Season::GetType() const { return season; } FormSwapMap& Season::GetFormSwapMap() { return formMap; } void Season::LoadData(const CSimpleIniA& a_ini) { formMap.LoadFormSwaps(a_ini); if (const auto values = a_ini.GetSection("Grass"); values && !values->empty()) { useAltGrass = true; } if (const auto values = a_ini.GetSection("Worldspaces"); values && !values->empty()) { std::ranges::transform(*values, std::back_inserter(validWorldspaces), [&](const auto& val) { return val.first.pItem; }); } } void Season::SaveData(CSimpleIniA& a_ini) { std::ranges::sort(validWorldspaces); validWorldspaces.erase(std::ranges::unique(validWorldspaces).begin(), validWorldspaces.end()); INI::set_value(a_ini, validWorldspaces, ID.type.c_str(), "Worldspaces", ";Valid worldspaces"); } bool Season::GetUseAltGrass() const { return useAltGrass; }
31.44186
238
0.709073
powerof3
d26a2c70c3317556e82aa4db4c2d9767e6e90a97
1,300
hpp
C++
src/accel/bvh.hpp
jkrueger/phosphorus_mk2
f26330fc2d013ca875d68de78ea9f92f344ddf4e
[ "MIT" ]
2
2019-12-12T04:59:41.000Z
2020-09-15T12:57:35.000Z
src/accel/bvh.hpp
jkrueger/phosphorus_mk2
f26330fc2d013ca875d68de78ea9f92f344ddf4e
[ "MIT" ]
1
2020-09-15T12:58:42.000Z
2020-09-15T12:58:42.000Z
src/accel/bvh.hpp
jkrueger/phosphorus_mk2
f26330fc2d013ca875d68de78ea9f92f344ddf4e
[ "MIT" ]
null
null
null
#pragma once #include "../triangle.hpp" #include "bvh/node.hpp" #include "bvh/builder.hpp" #include "math/simd.hpp" namespace accel { namespace triangle { template<int N> struct moeller_trumbore_t; } /* this models a regular bounding volume hierarchy, but with n-wide * nodes, which allows to do multiple bounding volume intersections * at the same time */ struct mbvh_t { static const uint32_t width = SIMD_WIDTH; typedef triangle::moeller_trumbore_t<width> triangle_t; typedef bvh::builder_t<mbvh::node_t<width>, ::triangle_t> builder_t; struct details_t; details_t* details; // pointer to the beginning of the bvh data structure. this is // ultimately a flat array of nodes, which represents a linearized // tree of nodes mbvh::node_t<width>* root; // the number of nodes in the tree uint32_t num_nodes; // the optimized triangle data structures in the tree. nodes point into this // array, if they are leaf nodes triangle_t* triangles; // number of triangles in the tree uint32_t num_triangles; mbvh_t(); ~mbvh_t(); /** clear all data from the bvh */ void reset(); builder_t* builder(); // the bounds of the mesh data in this accelerator Imath::Box3f bounds() const; }; }
25.490196
80
0.685385
jkrueger
d26a321fcfeac98248db1d9c69c4a84976c46354
6,814
hpp
C++
sources/SceneGraph/Collision/spCollisionConfigTypes.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/SceneGraph/Collision/spCollisionConfigTypes.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/SceneGraph/Collision/spCollisionConfigTypes.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2016-10-31T06:08:44.000Z
2019-08-02T16:12:33.000Z
/* * Collision configuration types header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_COLLISION_CONFIG_TYPES_H__ #define __SP_COLLISION_CONFIG_TYPES_H__ #include "Base/spStandard.hpp" #include "Base/spMeshBuffer.hpp" #include "SceneGraph/spSceneMesh.hpp" namespace sp { namespace scene { /* * Pre-declerations */ class CollisionMaterial; class CollisionNode; class CollisionSphere; class CollisionCapsule; class CollisionCylinder; class CollisionCone; class CollisionBox; class CollisionPlane; class CollisionMesh; /* * Enumerations */ //! Collision models. enum ECollisionModels { COLLISION_NONE = 0, //!< No collision model. COLLISION_SPHERE, //!< Collision sphere with position and radius. COLLISION_CAPSULE, //!< Collision capsule with position, rotation, radius and height. COLLISION_CYLINDER, //!< Collision cylinder with position, rotation, radius and height. COLLISION_CONE, //!< Collision cone with position, rotation, radius and height. COLLISION_BOX, //!< Collision box with position, rotation and axis-alined-bounding-box. COLLISION_PLANE, //!< Collision plane with position and normal vector. COLLISION_MESH, //!< Collision mesh using kd-Tree. }; //! Flags for collision detection. enum ECollisionFlags { COLLISIONFLAG_NONE = 0x00, //!< No collision detection, resolving and intersection tests will be performed. COLLISIONFLAG_DETECTION = 0x01, //!< Collision detection is performed. COLLISIONFLAG_RESOLVE = 0x02 | COLLISIONFLAG_DETECTION, //!< Collision resolving is performed. COLLISIONFLAG_INTERSECTION = 0x04, //!< Intersection tests are performed. COLLISIONFLAG_PERMANENT_UPDATE = 0x08, //!< Collision detection will be performed every frame. Otherwise only when the object has been moved. //! Collision resolving and intersection tests are performed. COLLISIONFLAG_FULL = COLLISIONFLAG_RESOLVE | COLLISIONFLAG_INTERSECTION | COLLISIONFLAG_PERMANENT_UPDATE, }; //! Flags for collision detection support to rival collision nodes. enum ECollisionSupportFlags { COLLISIONSUPPORT_NONE = 0x00, //!< Collision to no rival collision node is supported. COLLISIONSUPPORT_SPHERE = 0x01, //!< Collision to sphere is supported. COLLISIONSUPPORT_CAPSULE = 0x02, //!< Collision to capsule is supported. COLLISIONSUPPORT_CYLINDER = 0x04, //!< Collision to cylinder is supported. COLLISIONSUPPORT_CONE = 0x08, //!< Collision to cone is supported. COLLISIONSUPPORT_BOX = 0x10, //!< Collision to box is supported. COLLISIONSUPPORT_PLANE = 0x20, //!< Collision to plane is supported. COLLISIONSUPPORT_MESH = 0x40, //!< Collision to mesh is supported. COLLISIONSUPPORT_ALL = ~0, //!< COllision to any rival collision node is supported. }; /* * Structures */ struct SCollisionFace { SCollisionFace() : Mesh (0), Surface (0), Index (0) { } SCollisionFace( scene::Mesh* InitMesh, u32 InitSurface, u32 InitIndex, const dim::triangle3df &InitTriangle) : Mesh (InitMesh ), Surface (InitSurface ), Index (InitIndex ), Triangle(InitTriangle ) { } ~SCollisionFace() { } /* === Functions === */ //! Returns true if the specified inverse point is on the back side of this face's triangle. inline bool isBackFaceCulling(const video::EFaceTypes CollFace, const dim::vector3df &InversePoint) const { if (CollFace != video::FACE_BOTH) { bool isPointFront = dim::plane3df(Triangle).isPointFrontSide(InversePoint); if ( ( CollFace == video::FACE_FRONT && !isPointFront ) || ( CollFace == video::FACE_BACK && isPointFront ) ) { return true; } } return false; } //! Returns true if the specified inverse point is on the back side of this face's triangle. inline bool isBackFaceCulling(const video::EFaceTypes CollFace, const dim::line3df &InverseLine) const { if (CollFace != video::FACE_BOTH) { bool isPointFrontA = dim::plane3df(Triangle).isPointFrontSide(InverseLine.Start); bool isPointFrontB = dim::plane3df(Triangle).isPointFrontSide(InverseLine.End); if ( ( CollFace == video::FACE_FRONT && !isPointFrontA && !isPointFrontB ) || ( CollFace == video::FACE_BACK && isPointFrontA && isPointFrontB ) ) { return true; } } return false; } /* Members */ scene::Mesh* Mesh; u32 Surface; //!< Surface index. u32 Index; //!< Triangle index. dim::triangle3df Triangle; //!< Triangle face construction. }; struct SContactBase { SContactBase() : Impact (0.0f ), Face (0 ) { } virtual ~SContactBase() { } /* Members */ dim::vector3df Point; //!< Contact point onto the rival collision-node. dim::vector3df Normal; //!< Contact normal. Normal vector from the rival collision-node to the source collision-node. f32 Impact; //!< Contact impact distance. dim::triangle3df Triangle; //!< Triangle face construction. Only used for mesh contacts. SCollisionFace* Face; //!< Contact triangle. Only used for mesh contacts. }; struct SIntersectionContact : public SContactBase { SIntersectionContact() : SContactBase( ), Object (0 ), DistanceSq (0.0f ) { } ~SIntersectionContact() { } /* Operators */ inline bool operator == (const SIntersectionContact &Other) const { return Object == Other.Object && Face == Other.Face; } /* Members */ const CollisionNode* Object; //!< Constant collision object. f32 DistanceSq; //!< Squared distance used for internal sorting. }; struct SCollisionContact : public SContactBase { SCollisionContact() : SContactBase() { } ~SCollisionContact() { } /* Operators */ inline bool operator == (const SCollisionContact &Other) const { return Face == Other.Face; } }; } // /namespace scene } // /namespace sp #endif // ================================================================================
30.150442
174
0.612709
rontrek
d270709304d1c91565917bfd4d0c1c804bb31c9d
2,565
hpp
C++
modules/core/include/facekit/core/utils/proto.hpp
cecabert/FaceKit
766a32fc7f65ae5deceeba5628c225631986c4d8
[ "Apache-2.0" ]
null
null
null
modules/core/include/facekit/core/utils/proto.hpp
cecabert/FaceKit
766a32fc7f65ae5deceeba5628c225631986c4d8
[ "Apache-2.0" ]
null
null
null
modules/core/include/facekit/core/utils/proto.hpp
cecabert/FaceKit
766a32fc7f65ae5deceeba5628c225631986c4d8
[ "Apache-2.0" ]
1
2017-11-29T12:03:08.000Z
2017-11-29T12:03:08.000Z
/** * @file proto.hpp * @brief Utility function for dealing with protocol buffer object * @ingroup core * * @author Christophe Ecabert * @date 01.03.18 * Copyright © 2018 Christophe Ecabert. All rights reserved. */ #ifndef __FACEKIT_PROTO__ #define __FACEKIT_PROTO__ #include <string> #include "facekit/core/library_export.hpp" /** * @namespace FaceKit * @brief Development space */ namespace FaceKit { /** * @name AddVarInt32 * @fn void AddVarInt32(const uint32_t& value, std::string* str) * @brief Convert a given value into its varint representation and add it to * a given string * @param[in] value Value to convert to add * @param[out] str Buffer in which to add representation */ void FK_EXPORTS AddVarInt32(const uint32_t& value, std::string* str); /** * @name RetrieveVarInt32 * @fn bool RetrieveVarInt32(std::string* str, uint32_t* value) * @brief Extract a value from its varint representation stored in a given * array * @param[in,out] str Array storing the varints representation * @param[out] value Extracted value * @return True if conversion was successfull, false otherwise */ bool FK_EXPORTS RetrieveVarInt32(std::string* str, uint32_t* value); /** * @name EncodeStringList * @fn void EncodeStringList(const std::string* list, const size_t& n, std::string* str) * @brief Convert array of strings into a single string that can be saved * into a protobuf object * @param[in] list Array of string to convert * @param[in] n Array dimension * @param[out] str Encoded string * @ingroup core */ void FK_EXPORTS EncodeStringList(const std::string* list, const size_t& n, std::string* str); /** * @name DecodeStringList * @fn bool DecodeStringList(const std::string& in, const size_t& n, std::string* str) * @brief Split a given string `str` into the corresponding piece stored * as array. Concatenated comes from protobuf object * @param[in] in Concatenated string * @param[in] n Number of string to store in the array * @param[in,out] str Array of strings * @return True if successfully decoded, false otherwise */ bool FK_EXPORTS DecodeStringList(const std::string& in, const size_t& n, std::string* str); } // namespace FaceKit #endif /* __FACEKIT_PROTO__ */
32.468354
78
0.634308
cecabert
d27350e83f6abfe6deec2e7ab9dbdec631d6aea1
3,442
hpp
C++
Recorder/src/WaitEventThread.hpp
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
1
2015-03-26T02:35:13.000Z
2015-03-26T02:35:13.000Z
Recorder/src/WaitEventThread.hpp
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
null
null
null
Recorder/src/WaitEventThread.hpp
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
null
null
null
// // Recorder - a GPS logger app for Windows Mobile // Copyright (C) 2006-2019 Michael Fink // /// \file WaitEventThread.hpp WaitEvent() thread // #pragma once #include "WorkerThread.hpp" #include <boost/bind.hpp> /// \brief class that implements a worker thread that waits on a serial port for read/write events /// the class is mainly written for Windows CE when no overlapped support is available; waiting /// for events is simulated using calling WaitCommEvent() in another thread waiting for an event /// that gets set when the call returns. class CWaitEventThread { public: /// ctor CWaitEventThread(HANDLE hPort) :m_hPort(hPort), m_hEventReady(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset m_hEventWait(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset m_hEventContinue(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset m_hEventStop(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset m_workerThread(boost::bind(&CWaitEventThread::Run, this)) { } ~CWaitEventThread() { // stop background thread StopThread(); m_workerThread.Join(); CloseHandle(m_hEventReady); CloseHandle(m_hEventWait); CloseHandle(m_hEventContinue); CloseHandle(m_hEventStop); } /// \todo only in ready state? void SetPort(HANDLE hPort) { // TODO only in "ready" state? m_hPort = hPort; } /// \todo thread-safe exchange? void SetMask(DWORD dwEventMask) { //ATLTRACE(_T("T1: setting new mask, %08x\n"), dwEventMask); // TODO thread-safe exchange? only do in "ready" thread state? m_dwEventMask = dwEventMask; } /// waits for thead to be ready to wait for comm event void WaitForThreadReady() { WaitForSingleObject(m_hEventReady, INFINITE); ResetEvent(m_hEventReady); } /// tells thread to continue waiting void ContinueWait() { SetEvent(m_hEventContinue); } /// \todo wait for ready thread state void StopThread() { // TODO wait for "ready" thread state //ATLTRACE(_T("T1: stopping worker thread\n")); ::SetEvent(m_hEventStop); if (FALSE == ::SetCommMask(m_hPort, 0)) { DWORD dw = GetLastError(); dw++; } //ATLTRACE(_T("T1: stopped worker thread\n")); } bool WaitComm(); int Run(); /// returns wait event handle HANDLE GetWaitEventHandle() const { return m_hEventWait; } /// returns event result mask DWORD GetEventResult() { // wait event must be set //ATLTRACE(_T("T2: testing wait event\n")); DWORD dwTest = ::WaitForSingleObject(m_hEventWait, 0); //ATLASSERT(WAIT_OBJECT_0 == dwTest); // note: m_dwEventResult can be accessed without protection from the worker // thread because it is set when WaitCommEvent() returned. return m_dwEventResult; } private: DWORD m_dwEventMask; DWORD m_dwEventResult; HANDLE m_hPort; /// when event is set, the wait thread is ready to do a next "wait" task HANDLE m_hEventReady; /// when event is set, the WaitCommEvent call returned successfully HANDLE m_hEventWait; /// when event is set, the wait thread is allowed to continue with a WaitCommEvent call HANDLE m_hEventContinue; /// when event is set, the wait thread should exit HANDLE m_hEventStop; /// worker thread WorkerThread m_workerThread; };
27.536
98
0.663277
vividos
d27d1696d8ed42ec726e940b9cf9f5dfc88a00fb
7,762
cc
C++
src/corbaExample/src/cpp/RemoteFileServerSK.cc
jahlborn/rmiio
58c05f29e6dbc44c0f18c9a2247aff113d487c71
[ "Apache-2.0" ]
7
2016-04-05T15:58:01.000Z
2020-10-30T18:38:05.000Z
src/corbaExample/src/cpp/RemoteFileServerSK.cc
jahlborn/rmiio
58c05f29e6dbc44c0f18c9a2247aff113d487c71
[ "Apache-2.0" ]
2
2016-07-04T01:32:56.000Z
2020-12-11T02:54:56.000Z
src/corbaExample/src/cpp/RemoteFileServerSK.cc
jahlborn/rmiio
58c05f29e6dbc44c0f18c9a2247aff113d487c71
[ "Apache-2.0" ]
6
2016-04-05T15:58:16.000Z
2020-04-27T21:45:47.000Z
// This file is generated by omniidl (C++ backend)- omniORB_4_1. Do not edit. #include "RemoteFileServer.hh" #include <omniORB4/IOP_S.h> #include <omniORB4/IOP_C.h> #include <omniORB4/callDescriptor.h> #include <omniORB4/callHandle.h> #include <omniORB4/objTracker.h> OMNI_USING_NAMESPACE(omni) static const char* _0RL_library_version = omniORB_4_1; examples::iiop::RemoteFileServer_ptr examples::iiop::RemoteFileServer_Helper::_nil() { return ::examples::iiop::RemoteFileServer::_nil(); } CORBA::Boolean examples::iiop::RemoteFileServer_Helper::is_nil(::examples::iiop::RemoteFileServer_ptr p) { return CORBA::is_nil(p); } void examples::iiop::RemoteFileServer_Helper::release(::examples::iiop::RemoteFileServer_ptr p) { CORBA::release(p); } void examples::iiop::RemoteFileServer_Helper::marshalObjRef(::examples::iiop::RemoteFileServer_ptr obj, cdrStream& s) { ::examples::iiop::RemoteFileServer::_marshalObjRef(obj, s); } examples::iiop::RemoteFileServer_ptr examples::iiop::RemoteFileServer_Helper::unmarshalObjRef(cdrStream& s) { return ::examples::iiop::RemoteFileServer::_unmarshalObjRef(s); } void examples::iiop::RemoteFileServer_Helper::duplicate(::examples::iiop::RemoteFileServer_ptr obj) { if( obj && !obj->_NP_is_nil() ) omni::duplicateObjRef(obj); } examples::iiop::RemoteFileServer_ptr examples::iiop::RemoteFileServer::_duplicate(::examples::iiop::RemoteFileServer_ptr obj) { if( obj && !obj->_NP_is_nil() ) omni::duplicateObjRef(obj); return obj; } examples::iiop::RemoteFileServer_ptr examples::iiop::RemoteFileServer::_narrow(CORBA::Object_ptr obj) { if( !obj || obj->_NP_is_nil() || obj->_NP_is_pseudo() ) return _nil(); _ptr_type e = (_ptr_type) obj->_PR_getobj()->_realNarrow(_PD_repoId); return e ? e : _nil(); } examples::iiop::RemoteFileServer_ptr examples::iiop::RemoteFileServer::_unchecked_narrow(CORBA::Object_ptr obj) { if( !obj || obj->_NP_is_nil() || obj->_NP_is_pseudo() ) return _nil(); _ptr_type e = (_ptr_type) obj->_PR_getobj()->_uncheckedNarrow(_PD_repoId); return e ? e : _nil(); } examples::iiop::RemoteFileServer_ptr examples::iiop::RemoteFileServer::_nil() { #ifdef OMNI_UNLOADABLE_STUBS static _objref_RemoteFileServer _the_nil_obj; return &_the_nil_obj; #else static _objref_RemoteFileServer* _the_nil_ptr = 0; if( !_the_nil_ptr ) { omni::nilRefLock().lock(); if( !_the_nil_ptr ) { _the_nil_ptr = new _objref_RemoteFileServer; registerNilCorbaObject(_the_nil_ptr); } omni::nilRefLock().unlock(); } return _the_nil_ptr; #endif } const char* examples::iiop::RemoteFileServer::_PD_repoId = "RMI:examples.iiop.RemoteFileServer:0000000000000000"; examples::iiop::_objref_RemoteFileServer::~_objref_RemoteFileServer() { } examples::iiop::_objref_RemoteFileServer::_objref_RemoteFileServer(omniIOR* ior, omniIdentity* id) : omniObjRef(::examples::iiop::RemoteFileServer::_PD_repoId, ior, id, 1) { _PR_setobj(this); } void* examples::iiop::_objref_RemoteFileServer::_ptrToObjRef(const char* id) { if( id == ::examples::iiop::RemoteFileServer::_PD_repoId ) return (::examples::iiop::RemoteFileServer_ptr) this; if( id == ::CORBA::Object::_PD_repoId ) return (::CORBA::Object_ptr) this; if( omni::strMatch(id, ::examples::iiop::RemoteFileServer::_PD_repoId) ) return (::examples::iiop::RemoteFileServer_ptr) this; if( omni::strMatch(id, ::CORBA::Object::_PD_repoId) ) return (::CORBA::Object_ptr) this; return 0; } // Proxy call descriptor class. Mangled signature: // void_i_ccom_mhealthmarketscience_mrmiio_mRemoteInputStream_e_cjava_mio_mIOEx class _0RL_cd_5EAB75CAD9A547B4_00000000 : public omniCallDescriptor { public: inline _0RL_cd_5EAB75CAD9A547B4_00000000(LocalCallFn lcfn,const char* op_,size_t oplen,_CORBA_Boolean upcall=0): omniCallDescriptor(lcfn, op_, oplen, 0, _user_exns, 1, upcall) { } void marshalArguments(cdrStream&); void unmarshalArguments(cdrStream&); void userException(cdrStream&,_OMNI_NS(IOP_C)*,const char*); static const char* const _user_exns[]; com::healthmarketscience::rmiio::RemoteInputStream_var arg_0_; com::healthmarketscience::rmiio::RemoteInputStream_ptr arg_0; }; void _0RL_cd_5EAB75CAD9A547B4_00000000::marshalArguments(cdrStream& _n) { com::healthmarketscience::rmiio::RemoteInputStream_Helper::marshalObjRef(arg_0,_n); } void _0RL_cd_5EAB75CAD9A547B4_00000000::unmarshalArguments(cdrStream& _n) { arg_0_ = com::healthmarketscience::rmiio::RemoteInputStream_Helper::unmarshalObjRef(_n); arg_0 = arg_0_.in(); } const char* const _0RL_cd_5EAB75CAD9A547B4_00000000::_user_exns[] = { java::io::IOEx::_PD_repoId }; void _0RL_cd_5EAB75CAD9A547B4_00000000::userException(cdrStream& s, _OMNI_NS(IOP_C)* iop_client, const char* repoId) { if ( omni::strMatch(repoId, java::io::IOEx::_PD_repoId) ) { java::io::IOEx _ex; _ex <<= s; if (iop_client) iop_client->RequestCompleted(); throw _ex; } else { if (iop_client) iop_client->RequestCompleted(1); OMNIORB_THROW(UNKNOWN,UNKNOWN_UserException, (CORBA::CompletionStatus)s.completion()); } } // Local call call-back function. static void _0RL_lcfn_5EAB75CAD9A547B4_10000000(omniCallDescriptor* cd, omniServant* svnt) { _0RL_cd_5EAB75CAD9A547B4_00000000* tcd = (_0RL_cd_5EAB75CAD9A547B4_00000000*)cd; examples::iiop::_impl_RemoteFileServer* impl = (examples::iiop::_impl_RemoteFileServer*) svnt->_ptrToInterface(examples::iiop::RemoteFileServer::_PD_repoId); #ifdef HAS_Cplusplus_catch_exception_by_base impl->sendFile(tcd->arg_0); #else if (!cd->is_upcall()) impl->sendFile(tcd->arg_0); else { try { impl->sendFile(tcd->arg_0); } catch(java::io::IOEx& ex) { throw omniORB::StubUserException(ex._NP_duplicate()); } } #endif } void examples::iiop::_objref_RemoteFileServer::sendFile(com::healthmarketscience::rmiio::RemoteInputStream_ptr arg0) { _0RL_cd_5EAB75CAD9A547B4_00000000 _call_desc(_0RL_lcfn_5EAB75CAD9A547B4_10000000, "sendFile", 9); _call_desc.arg_0 = arg0; _invoke(_call_desc); } examples::iiop::_pof_RemoteFileServer::~_pof_RemoteFileServer() {} omniObjRef* examples::iiop::_pof_RemoteFileServer::newObjRef(omniIOR* ior, omniIdentity* id) { return new ::examples::iiop::_objref_RemoteFileServer(ior, id); } CORBA::Boolean examples::iiop::_pof_RemoteFileServer::is_a(const char* id) const { if( omni::ptrStrMatch(id, ::examples::iiop::RemoteFileServer::_PD_repoId) ) return 1; return 0; } const examples::iiop::_pof_RemoteFileServer _the_pof_examples_miiop_mRemoteFileServer; examples::iiop::_impl_RemoteFileServer::~_impl_RemoteFileServer() {} CORBA::Boolean examples::iiop::_impl_RemoteFileServer::_dispatch(omniCallHandle& _handle) { const char* op = _handle.operation_name(); if( omni::strMatch(op, "sendFile") ) { _0RL_cd_5EAB75CAD9A547B4_00000000 _call_desc(_0RL_lcfn_5EAB75CAD9A547B4_10000000, "sendFile", 9, 1); _handle.upcall(this,_call_desc); return 1; } return 0; } void* examples::iiop::_impl_RemoteFileServer::_ptrToInterface(const char* id) { if( id == ::examples::iiop::RemoteFileServer::_PD_repoId ) return (::examples::iiop::_impl_RemoteFileServer*) this; if( id == ::CORBA::Object::_PD_repoId ) return (void*) 1; if( omni::strMatch(id, ::examples::iiop::RemoteFileServer::_PD_repoId) ) return (::examples::iiop::_impl_RemoteFileServer*) this; if( omni::strMatch(id, ::CORBA::Object::_PD_repoId) ) return (void*) 1; return 0; } const char* examples::iiop::_impl_RemoteFileServer::_mostDerivedRepoId() { return ::examples::iiop::RemoteFileServer::_PD_repoId; } POA_examples::iiop::RemoteFileServer::~RemoteFileServer() {}
27.820789
159
0.741304
jahlborn
d2817fdc1cecd6818bc37383ccb537ab035c409e
32,675
cpp
C++
Classes/HelloWorldScene.cpp
otakuidoru/Reflection
05d55655a75813c7d4f0f5dee4d69a2c05476396
[ "MIT" ]
null
null
null
Classes/HelloWorldScene.cpp
otakuidoru/Reflection
05d55655a75813c7d4f0f5dee4d69a2c05476396
[ "MIT" ]
null
null
null
Classes/HelloWorldScene.cpp
otakuidoru/Reflection
05d55655a75813c7d4f0f5dee4d69a2c05476396
[ "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org 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 <cmath> #include <sstream> #include <sqlite3.h> #include "LevelSelectScene.h" #include "HelloWorldScene.h" #include "BackArrow.h" #include "ResetButton.h" #include "Indicator.h" #define BACKGROUND_LAYER -1 #define LASER_LAYER 1 #define OBJECT_LAYER 2 #define BACK_ARROW_LAYER 255 #define RESET_LAYER 253 #define INTRO_LAYER 254 USING_NS_CC; static const float DEGTORAD = 0.0174532925199432957f; static const float RADTODEG = 57.295779513082320876f; /** * */ Scene* HelloWorld::createScene(const std::string& levelFilename, int levelId, int worldId) { return HelloWorld::create(levelFilename, levelId, worldId); } /** * Print useful error message instead of segfaulting when files are not there. */ static void problemLoading(const char* filename) { log("Error while loading: %s\n", filename); log("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n"); } /** * */ static int levelUnlockCallback(void* object, int argc, char** data, char** azColName) { return 0; } /** * */ HelloWorld* HelloWorld::create(const std::string& levelFilename, int levelId, int worldId) { HelloWorld* ret = new (std::nothrow) HelloWorld(); if (ret && ret->init(levelFilename, levelId, worldId)) { ret->autorelease(); return ret; } else { CC_SAFE_DELETE(ret); return nullptr; } } /** * on "init" you need to initialize your instance */ bool HelloWorld::init(const std::string& levelFilename, int levelId, int worldId) { ////////////////////////////// // 1. super init first if (!Scene::init()) { return false; } const Size visibleSize = Director::getInstance()->getVisibleSize(); const Vec2 origin = Director::getInstance()->getVisibleOrigin(); const float scale = std::min(visibleSize.width/1536.0f, visibleSize.height/2048.0f); this->levelId = levelId; this->worldId = worldId; this->levelFilename = levelFilename; this->introLayers = IntroLayerMultiplex::create(); //this->introLayers->setPosition(Vec2(origin.x + visibleSize.width/2.0f, origin.y + visibleSize.height/2.0f)); this->addChild(this->introLayers, 255); ///////////////////////////// // 2. add your codes below... strToColorTypeMap = { {"NONE", ColorType::NONE}, {"RED", ColorType::RED}, {"GREEN", ColorType::GREEN}, {"BLUE", ColorType::BLUE}, {"YELLOW", ColorType::YELLOW}, {"ORANGE", ColorType::ORANGE}, {"PURPLE", ColorType::PURPLE}, {"WHITE", ColorType::WHITE}, {"BLACK", ColorType::BLACK} }; colorTypeToObjectColor3BMap = { {ColorType::NONE, Color3B(255, 255, 255)}, {ColorType::RED, Color3B(255, 153, 153)}, {ColorType::GREEN, Color3B(153, 255, 153)}, {ColorType::BLUE, Color3B(153, 153, 255)}, {ColorType::YELLOW, Color3B(255, 255, 255)}, // TODO {ColorType::ORANGE, Color3B(255, 255, 255)}, // TODO {ColorType::PURPLE, Color3B(255, 255, 255)}, // TODO {ColorType::WHITE, Color3B(255, 255, 255)}, {ColorType::BLACK, Color3B( 0, 0, 0)} }; colorTypeToLaserColor3BMap = { {ColorType::NONE, Color3B(255, 255, 255)}, {ColorType::RED, Color3B(255, 0, 0)}, {ColorType::GREEN, Color3B(0, 255, 0)}, {ColorType::BLUE, Color3B(0, 0, 255)}, {ColorType::YELLOW, Color3B(255, 255, 0)}, {ColorType::ORANGE, Color3B(251, 139, 35)}, {ColorType::PURPLE, Color3B(148, 0, 211)}, {ColorType::WHITE, Color3B(255, 255, 255)}, {ColorType::BLACK, Color3B( 0, 0, 0)} }; strToDirectionMap = { {"NORTH", Direction::NORTH }, {"NORTHEAST", Direction::NORTHEAST}, {"EAST", Direction::EAST }, {"SOUTHEAST", Direction::SOUTHEAST}, {"SOUTH", Direction::SOUTH }, {"SOUTHWEST", Direction::SOUTHWEST}, {"WEST", Direction::WEST }, {"NORTHWEST", Direction::NORTHWEST}, }; auto background = LayerGradient::create(Color4B(253, 158, 246, 255), Color4B(255, 255, 255, 255), Vec2(1.0f, 1.0f)); this->addChild(background, BACKGROUND_LAYER); #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #define PATH_SEPARATOR "\\" #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #define PATH_SEPARATOR "/" #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #define PATH_SEPARATOR "\/" #endif std::stringstream source; source << this->levelFilename; //log("com.zenprogramming.reflection: Source Filename = %s", source.str().c_str()); std::stringstream target; target << FileUtils::getInstance()->getWritablePath() << "level.xml"; //log("com.zenprogramming.reflection: Target Filename = %s", target.str().c_str()); // copy the file to the writable area on the device // (have to do this for TinyXML to read the file) FileUtils::getInstance()->writeStringToFile(FileUtils::getInstance()->getStringFromFile(source.str()), target.str()); this->createLevel(target.str()); if (!this->introLayers->isEmpty()) { this->introLayers->switchTo(0); } // create the back arrow auto backArrow = BackArrow::create(); backArrow->onClick = [&]() { auto levelSelectScene = LevelSelect::create(this->worldId); Director::getInstance()->replaceScene(TransitionFade::create(0.5f, levelSelectScene, Color3B(0, 0, 0))); }; backArrow->setColor(Color3B(255, 255, 255)); backArrow->setScale(visibleSize.width / 1536.0f); backArrow->setPosition(Vec2(origin.x + backArrow->getContentSize().width / 2.0f, origin.y + backArrow->getContentSize().height / 2.0f)); this->addChild(backArrow, BACK_ARROW_LAYER); // create the reset button auto resetButton = ResetButton::create(); resetButton->onClick = [&]() { auto levelScene = HelloWorld::createScene(this->levelFilename, this->levelId, this->worldId); Director::getInstance()->replaceScene(TransitionFade::create(0.5f, levelScene, Color3B(0, 0, 0))); }; resetButton->setColor(Color3B(255, 255, 255)); resetButton->setScale(visibleSize.width / 1536.0f); resetButton->setPosition(Vec2(origin.x + visibleSize.width - resetButton->getContentSize().width / 2.0f, origin.y + resetButton->getContentSize().height / 2.0f)); this->addChild(resetButton, RESET_LAYER); ////////////////////////////////////////////////////////////////////////////// // // Create a "one by one" touch event listener (processes one touch at a time) // ////////////////////////////////////////////////////////////////////////////// auto touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); // triggered when pressed touchListener->onTouchBegan = [&](Touch* touch, Event* event) -> bool { bool consuming = false; if (this->introLayers->getEnabledLayerIndex() < this->introLayers->getNumLayers()) { consuming = true; this->introLayers->getEnabledLayer()->runAction(Sequence::create( FadeOut::create(1.0f), CallFunc::create([&]() { if (this->introLayers->getEnabledLayerIndex() < this->introLayers->getNumLayers()-1) { this->introLayers->switchTo(this->introLayers->getEnabledLayerIndex()+1); } else if (this->introLayers->getEnabledLayerIndex() == this->introLayers->getNumLayers()-1) { this->introLayers->removeFromParent(); } }), nullptr )); } return consuming; }; // triggered when moving touch touchListener->onTouchMoved = [&](Touch* touch, Event* event) {}; // triggered when released touchListener->onTouchEnded = [&](Touch* touch, Event* event) {}; // add listener this->introLayers->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this->introLayers); ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// this->ready = true; this->scheduleUpdate(); return true; } /** * */ void HelloWorld::addEmitters(tinyxml2::XMLElement* const emittersElement, float scale) { if (emittersElement) { tinyxml2::XMLElement* emitterElement = emittersElement->FirstChildElement("emitter"); const Size visibleSize = Director::getInstance()->getVisibleSize(); const Vec2 origin = Director::getInstance()->getVisibleOrigin(); while (emitterElement) { // id int id; emitterElement->QueryIntAttribute("id", &id); // color type std::string colorTypeStr(emitterElement->FirstChildElement("colortype")->GetText()); const ColorType colorType = this->strToColorTypeMap[colorTypeStr]; // create emitter auto emitter = Emitter::create(id, colorType); emitter->onAfterActivate = [&]() {}; this->emitters.insert(emitter); this->objects.insert(emitter); // set emitter color const Color3B color = colorTypeToObjectColor3BMap[colorType]; emitter->setColor(color); // set emitter scale emitter->setScale(scale); // set emitter position float x, y; tinyxml2::XMLElement* positionElement = emitterElement->FirstChildElement("position"); positionElement->QueryFloatAttribute("x", &x); positionElement->QueryFloatAttribute("y", &y); emitter->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y)); // set emitter direction std::string directionStr(emitterElement->FirstChildElement("direction")->GetText()); emitter->setDirection(strToDirectionMap[directionStr]); // set emitter active std::string activeStr = emitterElement->FirstChildElement("active")->GetText(); emitter->setActive(!activeStr.compare("true")); // add the emitter to the scene this->addChild(emitter, OBJECT_LAYER); emitterElement = emitterElement->NextSiblingElement("emitter"); } } } /** * */ void HelloWorld::addMirrors(tinyxml2::XMLElement* const mirrorsElement, float scale) { if (mirrorsElement) { tinyxml2::XMLElement* mirrorElement = mirrorsElement->FirstChildElement("mirror"); const Size visibleSize = Director::getInstance()->getVisibleSize(); const Vec2 origin = Director::getInstance()->getVisibleOrigin(); while (mirrorElement) { // id int id; mirrorElement->QueryIntAttribute("id", &id); // create mirror auto mirror = Mirror::create(id); mirror->onBeforeRotate = [&]() {}; mirror->onAfterRotate = [&]() {}; this->mirrors.insert(mirror); this->objects.insert(mirror); // set mirror scale mirror->setScale(scale); // set mirror position float x, y; tinyxml2::XMLElement* positionElement = mirrorElement->FirstChildElement("position"); positionElement->QueryFloatAttribute("x", &x); positionElement->QueryFloatAttribute("y", &y); mirror->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y)); // set mirror direction std::string directionStr(mirrorElement->FirstChildElement("direction")->GetText()); mirror->setDirection(strToDirectionMap[directionStr]); // add the mirror to the scene this->addChild(mirror, OBJECT_LAYER); mirrorElement = mirrorElement->NextSiblingElement("mirror"); } } } /** * */ void HelloWorld::addReceptors(tinyxml2::XMLElement* const receptorsElement, float scale) { if (receptorsElement) { tinyxml2::XMLElement* receptorElement = receptorsElement->FirstChildElement("receptor"); const Size visibleSize = Director::getInstance()->getVisibleSize(); const Vec2 origin = Director::getInstance()->getVisibleOrigin(); while (receptorElement) { // id int id; receptorElement->QueryIntAttribute("id", &id); // color type std::string colorTypeStr(receptorElement->FirstChildElement("colortype")->GetText()); const ColorType colorType = this->strToColorTypeMap[colorTypeStr]; // create receptor auto receptor = Receptor::create(id, colorType); this->receptors.insert(receptor); this->objects.insert(receptor); // set receptor color const Color3B color = colorTypeToObjectColor3BMap[colorType]; receptor->setColor(color); // set receptor scale receptor->setScale(scale); // set receptor position float x, y; tinyxml2::XMLElement* positionElement = receptorElement->FirstChildElement("position"); positionElement->QueryFloatAttribute("x", &x); positionElement->QueryFloatAttribute("y", &y); receptor->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y)); // set receptor direction std::string directionStr(receptorElement->FirstChildElement("direction")->GetText()); receptor->setDirection(strToDirectionMap[directionStr]); // add the receptor to the scene this->addChild(receptor, OBJECT_LAYER); receptorElement = receptorElement->NextSiblingElement("receptor"); } } } /** * */ void HelloWorld::addBlocks(tinyxml2::XMLElement* const blocksElement, float scale) { if (blocksElement) { tinyxml2::XMLElement* blockElement = blocksElement->FirstChildElement("block"); const Size visibleSize = Director::getInstance()->getVisibleSize(); const Vec2 origin = Director::getInstance()->getVisibleOrigin(); while (blockElement) { // id int id; blockElement->QueryIntAttribute("id", &id); // create block auto block = Block::create(id); this->blocks.insert(block); this->objects.insert(block); // set block scale block->setScale(scale); // set block position float x, y; tinyxml2::XMLElement* positionElement = blockElement->FirstChildElement("position"); positionElement->QueryFloatAttribute("x", &x); positionElement->QueryFloatAttribute("y", &y); block->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y)); // add the block to the scene this->addChild(block, OBJECT_LAYER); blockElement = blockElement->NextSiblingElement("block"); } } } /** * */ void HelloWorld::addBonusStars(tinyxml2::XMLElement* const bonusStarsElement, float scale) { if (bonusStarsElement) { tinyxml2::XMLElement* bonusStarElement = bonusStarsElement->FirstChildElement("bonusstar"); const Size visibleSize = Director::getInstance()->getVisibleSize(); const Vec2 origin = Director::getInstance()->getVisibleOrigin(); while (bonusStarElement) { // id int id; bonusStarElement->QueryIntAttribute("id", &id); // create block auto bonusStar = BonusStar::create(id); this->bonusStars.insert(bonusStar); this->objects.insert(bonusStar); // set block scale bonusStar->setScale(scale); // set block position float x, y; tinyxml2::XMLElement* positionElement = bonusStarElement->FirstChildElement("position"); positionElement->QueryFloatAttribute("x", &x); positionElement->QueryFloatAttribute("y", &y); bonusStar->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y)); // add the block to the scene this->addChild(bonusStar, OBJECT_LAYER); bonusStarElement = bonusStarElement->NextSiblingElement("bonusstar"); } } } /** * */ void HelloWorld::createLevel(const std::string& filename) { const Size visibleSize = Director::getInstance()->getVisibleSize(); const Vec2 origin = Director::getInstance()->getVisibleOrigin(); const float scale = std::min(visibleSize.width/1536.0f, visibleSize.height/2048.0f); tinyxml2::XMLDocument document; tinyxml2::XMLError error = document.LoadFile(filename.c_str()); //log("com.zenprogramming.reflection: error = %d", error); ////////////////////////////////////////////////////////////////////////////// // // Add the initial objects // ////////////////////////////////////////////////////////////////////////////// this->addEmitters(document.RootElement()->FirstChildElement("setup")->FirstChildElement("emitters"), scale); this->addMirrors(document.RootElement()->FirstChildElement("setup")->FirstChildElement("mirrors"), scale); this->addReceptors(document.RootElement()->FirstChildElement("setup")->FirstChildElement("receptors"), scale); this->addBlocks(document.RootElement()->FirstChildElement("setup")->FirstChildElement("blocks"), scale); this->addBonusStars(document.RootElement()->FirstChildElement("setup")->FirstChildElement("bonusstars"), scale); ////////////////////////////////////////////////////////////////////////////// // // Create the intro layers // ////////////////////////////////////////////////////////////////////////////// // get the <intro> element tinyxml2::XMLElement* introElement = document.RootElement()->FirstChildElement("intro"); if (introElement) { tinyxml2::XMLElement* layerElement = introElement->FirstChildElement("layer"); const Size visibleSize = Director::getInstance()->getVisibleSize(); const Vec2 origin = Director::getInstance()->getVisibleOrigin(); while (layerElement) { // auto layer = LayerGradient::create(Color4B(255, 255, 255, 64), Color4B(255, 255, 255, 64)); Layer* layer = Layer::create(); const std::string text = layerElement->FirstChildElement("text")->GetText(); //log("com.zenprogramming.reflection: %s", text.c_str()); auto label = Label::createWithTTF(text, "fonts/centurygothic_bold.ttf", 160); if (label == nullptr) { problemLoading("'fonts/centurygothic_bold.ttf'"); } else { // position the label on the top center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2.0f, origin.y + visibleSize.height*3.0f/4.0f)); label->setScale(scale); label->setColor(Color3B(0, 0, 0)); Sprite* background = Sprite::create("intro_layer.png"); background->setPosition(label->getPosition()); background->setScaleX(scale); layer->addChild(background, INTRO_LAYER); // add the label as a child to this layer layer->addChild(label, INTRO_LAYER); layer->setCascadeOpacityEnabled(true); Label* continueLabel = Label::createWithTTF("Touch to continue", "fonts/centurygothic_bold.ttf", 60); continueLabel->setPosition(Vec2(background->getPositionX(), background->getPositionY() - background->getContentSize().height/2.0f + continueLabel->getContentSize().height)); continueLabel->setScale(scale); continueLabel->setColor(Color3B(0, 0, 0)); layer->addChild(continueLabel, INTRO_LAYER); } tinyxml2::XMLElement* indicatorElement = layerElement->FirstChildElement("indicator"); if (indicatorElement) { // set indicator position float x, y; tinyxml2::XMLElement* positionElement = indicatorElement->FirstChildElement("position"); positionElement->QueryFloatAttribute("x", &x); positionElement->QueryFloatAttribute("y", &y); Indicator* indicator = Indicator::create(); indicator->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y)); indicator->setColor(Color3B(0, 0, 255)); // indicator->setOnEnterCallback([&]() { // indicator->runAction(ScaleTo::create(2.0f, 0.0f)); // }); layer->addChild(indicator); indicator->runAction(RepeatForever::create( Sequence::create( ScaleTo::create(2.0f, 0.0f), ScaleTo::create(2.0f, 1.0f), nullptr ) )); } this->introLayers->addLayer(layer); layerElement = layerElement->NextSiblingElement("layer"); } } ////////////////////////////////////////////////////////////////////////////// // // Add the win conditions // ////////////////////////////////////////////////////////////////////////////// // get the <winconditions> element tinyxml2::XMLElement* winConditionsElement = document.RootElement()->FirstChildElement("winconditions"); if (winConditionsElement) { // get the <wincondition> element tinyxml2::XMLElement* winConditionElement = winConditionsElement->FirstChildElement("wincondition"); if (winConditionElement) { std::shared_ptr<WinCondition> winCondition(new WinCondition()); { // parse the win condition - emitters tinyxml2::XMLElement* winConditionEmittersElement = winConditionElement->FirstChildElement("emitters"); if (winConditionEmittersElement) { tinyxml2::XMLElement* winConditionEmitterElement = winConditionEmittersElement->FirstChildElement("emitter"); while (winConditionEmitterElement) { // get emitter id int emitterId; winConditionEmitterElement->QueryIntAttribute("id", &emitterId); // get emitter activity const std::string emitterActiveStr(winConditionEmitterElement->Attribute("active")); const bool emitterActive = !emitterActiveStr.compare("true"); for (auto emitter : this->emitters) { if (emitter->getId() == emitterId) { winCondition->addEmitterActivation(emitter, emitterActive); } } winConditionEmitterElement = winConditionEmitterElement->NextSiblingElement("emitter"); } } } { // parse the win condition - mirrors tinyxml2::XMLElement* winConditionMirrorsElement = winConditionElement->FirstChildElement("mirrors"); if (winConditionMirrorsElement) { tinyxml2::XMLElement* winConditionMirrorElement = winConditionMirrorsElement->FirstChildElement("mirror"); while (winConditionMirrorElement) { // get mirror id int mirrorId; winConditionMirrorElement->QueryIntAttribute("id", &mirrorId); // get mirror direction const std::string mirrorDirectionStr(winConditionMirrorElement->Attribute("direction")); const Direction mirrorDirection = strToDirectionMap[mirrorDirectionStr]; for (auto mirror : this->mirrors) { if (mirror->getId() == mirrorId) { winCondition->addMirrorDirection(mirror, mirrorDirection); } } winConditionMirrorElement = winConditionMirrorElement->NextSiblingElement("mirror"); } } } this->winConditions.push_back(winCondition); } } } /** * https://math.stackexchange.com/questions/13261/how-to-get-a-reflection-vector */ Vec3 HelloWorld::getReflectionVector(const Plane& plane, const Ray& ray) { //log("com.zenprogramming.reflection: BEGIN getReflectionVector"); const Vec3 d = ray._direction; const Vec3 n = plane.getNormal(); const Vec3 reflectionVector = d - 2 * (d.dot(n)) * n; //log("com.zenprogramming.reflection: reflectionVector = (%f, %f, %f)", reflectionVector.x, reflectionVector.y, reflectionVector.z); //log("com.zenprogramming.reflection: END getReflectionVector"); return reflectionVector; } /** * */ void HelloWorld::activateLaserChain(const Ray& originRay, const Vec3& origLaserStartingPoint, const Plane& originPlane, ColorType colorType) { //log("com.zenprogramming.reflection: BEGIN activateLaserChain"); const Vec3 reflectionVector = this->getReflectionVector(originPlane, originRay); const float angle = -std::atan2(reflectionVector.y, reflectionVector.x) * RADTODEG; const Ray reflectionRay(origLaserStartingPoint, reflectionVector); // create and add a laser Laser* const laser = this->addLaser(angle, Vec2(origLaserStartingPoint.x, origLaserStartingPoint.y), colorTypeToLaserColor3BMap[colorType]); std::shared_ptr<Intersection> intersection = this->getClosestIntersection(reflectionRay); if (intersection.get()) { laser->setScaleX(intersection->getDistance()); if (intersection->isPlaneReflective()) { this->activateLaserChain(laser->getRay(), intersection->getPoint(), intersection->getPlane(), colorType); } } //log("com.zenprogramming.reflection: END activateLaserChain"); } /** * */ std::shared_ptr<Intersection> HelloWorld::getClosestIntersection(const Ray& ray) { //log("com.zenprogramming.reflection: BEGIN getClosestIntersection"); std::shared_ptr<Intersection> intersection; float minDistance = 2560.0f; //log("com.zenprogramming.reflection: ray = origin (%f, %f, %f), direction (%f, %f, %f)", ray._origin.x, ray._origin.y, ray._origin.z, ray._direction.x, ray._direction.y, ray._direction.z); // check each object for (auto object : this->objects) { //log("com.zenprogramming.reflection: checking object[%d]...", object->getId()); // get the AABB for the object const Rect objectBoundingBox = object->getBoundingBox(); const AABB objectAABB(Vec3(objectBoundingBox.getMinX(), objectBoundingBox.getMinY(), 0.0f), Vec3(objectBoundingBox.getMaxX(), objectBoundingBox.getMaxY(), 0.0f)); //log("com.zenprogramming.reflection: object[%d] AABB = (%f, %f, %f, %f), width = %f, height = %f", object->getId(), objectBoundingBox.getMinX(), objectBoundingBox.getMinY(), objectBoundingBox.getMaxX(), objectBoundingBox.getMaxY(), objectBoundingBox.getMaxX() - objectBoundingBox.getMinX(), objectBoundingBox.getMaxY() - objectBoundingBox.getMinY()); for (int planeIndex=0; planeIndex<object->getNumPlanes(); ++planeIndex) { const Plane plane = object->getPlane(planeIndex); const Vec3 intersectionPoint = ray.intersects(plane); const float intersectionDist = intersectionPoint.distance(ray._origin); const bool intersects = ray.intersects(objectAABB); //log("com.zenprogramming.reflection: intersects? %d, dist = %f", intersects, intersectionDist); if (!intersectionPoint.isZero() && ray.intersects(objectAABB) && objectBoundingBox.containsPoint(Vec2(intersectionPoint.x, intersectionPoint.y))) { // ray intersects plane in the object's bounding box if (intersectionDist < minDistance) { minDistance = intersectionDist; intersection.reset(new Intersection(plane, intersectionPoint, plane.getSide(ray._origin), object->isPlaneReflective(planeIndex), intersectionDist)); //log("com.zenprogramming.reflection: laser hits object[%d] at distance = %f at point (%f, %f, %f)", object->getId(), intersectionDist, intersectionPoint.x, intersectionPoint.y, intersectionPoint.z); //log("com.zenprogramming.reflection: closest object is now %d", object->getId()); } } } } //log("com.zenprogramming.reflection: END getClosestIntersection"); return intersection; } /** * */ bool HelloWorld::checkWinConditions() { //log("com.zenprogramming.reflection: BEGIN checkWinConditions"); if (this->ready) { //////////////////////////////////////////////////////////////////////////// // // Check all objects for their win condition // //////////////////////////////////////////////////////////////////////////// std::shared_ptr<WinCondition> currentWinCondition = nullptr; for (auto winCondition : this->winConditions) { if (!winCondition->evaluate()) { return false; } currentWinCondition = winCondition; } // // remove all bonus stars // for (auto bonusStar : currentWinCondition->getBonusStars()) { // bonusStar->removeFromParent(); // } // player has won, so set the ready to false this->ready = false; //////////////////////////////////////////////////////////////////////////// // // Copy the scene to a RenderTexture // //////////////////////////////////////////////////////////////////////////// // create and copy the scene to a RenderTexture RenderTexture* renderTexture = RenderTexture::create(this->getBoundingBox().size.width, this->getBoundingBox().size.height, PixelFormat::RGBA8888); renderTexture->begin(); this->visit(); renderTexture->end(); renderTexture->setPositionNormalized(Vec2(0.5f, 0.5f)); this->addChild(renderTexture, 250); //////////////////////////////////////////////////////////////////////////// // // Play the win animation // //////////////////////////////////////////////////////////////////////////// Sprite* const winBanner = Sprite::create("well_done.png"); winBanner->setPositionNormalized(Vec2(0.5f, 0.5f)); winBanner->setOpacity(0); winBanner->setScale(5.0f); this->addChild(winBanner, 255); winBanner->runAction(Sequence::create( CallFunc::create([&]() { auto emitter = ParticleExplosion::create(); emitter->setPositionNormalized(Vec2(0.5f, 0.5f)); // set the duration // emitter->setDuration(ParticleSystem::DURATION_INFINITY); // // radius mode // emitter->setEmitterMode(ParticleSystem::Mode::RADIUS); // radius mode: 100 pixels from center emitter->setStartRadius(0); emitter->setStartRadiusVar(0); emitter->setEndRadius(ParticleSystem::START_RADIUS_EQUAL_TO_END_RADIUS); emitter->setEndRadiusVar(500); // not used when start == end this->addChild(emitter, 254); }), DelayTime::create(1.0f), // pause Spawn::create( FadeIn::create(0.5f), ScaleTo::create(0.5f, 1.75f), nullptr ), nullptr )); // remove all objects from the scene //for (auto object : this->objects) { // object->removeFromParent(); //} //this->objects.clear(); // TODO: do sand blowing away animation ////////////////////////////////////////////////////////////////////////////// // // Update the database to unlock the next level // ////////////////////////////////////////////////////////////////////////////// sqlite3* db; char* errMsg = 0; int rc; // open the database std::stringstream dbPath; dbPath << FileUtils::getInstance()->getWritablePath() << "levels.db"; rc = sqlite3_open(dbPath.str().c_str(), &db); if (rc) { log("com.zenprogramming.reflection: Can't open database: %s", sqlite3_errmsg(db)); sqlite3_close(db); return false; } std::stringstream sql; sql << "UPDATE game_levels SET locked = 0 WHERE id = (SELECT next_level_id FROM game_levels WHERE id = " << this->levelId << ")"; rc = sqlite3_exec(db, sql.str().c_str(), levelUnlockCallback, static_cast<void*>(this), &errMsg); if (rc != SQLITE_OK) { log("com.zenprogramming.reflection: SQL error: %s", errMsg); sqlite3_free(errMsg); } // close the database rc = sqlite3_close(db); } //log("com.zenprogramming.reflection: END checkWinConditions"); return true; } /** * */ Laser* HelloWorld::addLaser(float angle, const Vec2& position, const Color3B& color) { // create and add a laser Laser* const laser = Laser::create(color); laser->setPosition(position); laser->setRotation(angle); laser->setAnchorPoint(Vec2(0.0f, 0.5f)); laser->setScaleX(2560.0f); this->addChild(laser, LASER_LAYER); this->lasers.insert(laser); return laser; } /** * */ void HelloWorld::update(float dt) { //log("com.zenprogramming.reflection: BEGIN update"); if (ready) { // remove all lasers from the board for (auto laser : this->lasers) { laser->removeFromParent(); } this->lasers.clear(); // regenerate lasers on the board for (auto emitter : this->emitters) { if (emitter->isActive()) { const Vec2 emitterWorldPos = emitter->getParent()->convertToWorldSpace(emitter->getPosition()); // create and add a laser Laser* const laser = this->addLaser(emitter->getRotation(), emitterWorldPos, colorTypeToLaserColor3BMap[emitter->getColorType()]); // find the closest intersection for the emitter laser std::shared_ptr<Intersection> intersection = this->getClosestIntersection(laser->getRay()); if (intersection.get()) { laser->setScaleX(intersection->getDistance()); //log("com.zenprogramming.reflection: laser origin (%f, %f), direction (%f, %f, %f), length = %f", laser->getRay()._origin.x, laser->getRay()._origin.y, laser->getRay()._direction.x, laser->getRay()._direction.y, laser->getRay()._direction.z, laser->getScaleX()); //log("com.zenprogramming.reflection: intersection at (%f, %f, %f) side = %d, reflective = %d, distance = %f", intersection->getPoint().x, intersection->getPoint().y, intersection->getPoint().z, intersection->getPointSide(), intersection->isPlaneReflective(), intersection->getDistance()); if (intersection->isPlaneReflective()) { this->activateLaserChain(laser->getRay(), intersection->getPoint(), intersection->getPlane(), emitter->getColorType()); } } } } this->checkWinConditions(); } //log("com.zenprogramming.reflection: END update"); }
35.867179
353
0.673298
otakuidoru
d28713ecd5b2df494c956cf82d037b165648833a
545
hpp
C++
hoibase/include/hoibase/helper/library.hpp
openhoi/openhoi
5705ea8456ac526645f943b78b37bb993d44320c
[ "BSD-2-Clause", "MIT" ]
2
2022-02-11T17:28:38.000Z
2022-03-17T00:57:40.000Z
hoibase/include/hoibase/helper/library.hpp
openhoi/openhoi
5705ea8456ac526645f943b78b37bb993d44320c
[ "BSD-2-Clause", "MIT" ]
1
2019-03-07T09:51:18.000Z
2019-03-07T09:51:18.000Z
hoibase/include/hoibase/helper/library.hpp
openhoi/openhoi
5705ea8456ac526645f943b78b37bb993d44320c
[ "BSD-2-Clause", "MIT" ]
6
2019-10-03T13:26:53.000Z
2022-03-20T14:33:22.000Z
// Copyright 2018-2019 the openhoi authors. See COPYING.md for legal info. #pragma once #if defined(_MSC_VER) // Microsoft Visual Studio # define OPENHOI_LIB_EXPORT __declspec(dllexport) # define OPENHOI_LIB_IMPORT __declspec(dllimport) #elif defined(__GNUC__) // GCC # define OPENHOI_LIB_EXPORT __attribute__((visibility("default"))) # define OPENHOI_LIB_IMPORT #else // do nothing and hope for the best? # define OPENHOI_LIB_EXPORT # define OPENHOI_LIB_IMPORT # pragma warning Unknown dynamic link import / export semantics. #endif
30.277778
74
0.783486
openhoi
d2877dd17038f63f0aee5411151cf78462356faf
2,048
cpp
C++
test/lexer.cpp
sethitow/stc
28894bda001f00828613941d1a6da7cc3720dd52
[ "MIT" ]
null
null
null
test/lexer.cpp
sethitow/stc
28894bda001f00828613941d1a6da7cc3720dd52
[ "MIT" ]
3
2021-07-24T23:06:37.000Z
2021-08-21T03:24:58.000Z
test/lexer.cpp
sethitow/stc
28894bda001f00828613941d1a6da7cc3720dd52
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "../src/lexer.hpp" #include "../src/token.hpp" TEST(Lexer, Function) { std::string input = "FUNCTION F_Sample : INT" " VAR_INPUT" " x : INT;" " y : INT;" " END_VAR" " F_Sample := x + y;" "END_FUNCTION;"; auto tokens = tokenize(input); auto tok_vec = tokens.to_vec(); std::vector<Token> expected_tok_vec{ Token("KEYWORD", "FUNCTION"), Token("IDENTIFIER", "F_Sample"), Token("SPECIAL_CHARACTER", ":"), Token("IDENTIFIER", "INT"), Token("KEYWORD", "VAR_INPUT"), Token("IDENTIFIER", "x"), Token("SPECIAL_CHARACTER", ":"), Token("IDENTIFIER", "INT"), Token("SPECIAL_CHARACTER", ";"), Token("IDENTIFIER", "y"), Token("SPECIAL_CHARACTER", ":"), Token("IDENTIFIER", "INT"), Token("SPECIAL_CHARACTER", ";"), Token("KEYWORD", "END_VAR"), Token("IDENTIFIER", "F_Sample"), Token("OPERATOR", ":="), Token("IDENTIFIER", "x"), Token("OPERATOR", "+"), Token("IDENTIFIER", "y"), Token("SPECIAL_CHARACTER", ";"), Token("KEYWORD", "END_FUNCTION"), Token("SPECIAL_CHARACTER", ";"), }; ASSERT_EQ(tok_vec.size(), expected_tok_vec.size()); for (int i = 0; i < tok_vec.size(); ++i) { EXPECT_EQ(tok_vec[i], expected_tok_vec[i]) << "Vectors x and y differ at index " << i; } } TEST(Lexer, Assignment) { auto tokens = tokenize(":="); auto tok_vec = tokens.to_vec(); std::vector<Token> expected_tok_vec{Token("OPERATOR", ":=")}; ASSERT_EQ(tok_vec.size(), expected_tok_vec.size()); for (int i = 0; i < tok_vec.size(); ++i) { EXPECT_EQ(tok_vec[i], expected_tok_vec[i]) << "Vectors x and y differ at index " << i; } }
30.117647
94
0.487793
sethitow
d28dff0987dbb8ae6edb9bcb56c0f3199a19a8da
1,606
cpp
C++
ext/stub/javax/swing/JComponent_ReadObjectCallback-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/javax/swing/JComponent_ReadObjectCallback-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/javax/swing/JComponent_ReadObjectCallback-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #include <javax/swing/JComponent_ReadObjectCallback.hpp> #include <javax/swing/JComponent.hpp> extern void unimplemented_(const char16_t* name); javax::swing::JComponent_ReadObjectCallback::JComponent_ReadObjectCallback(JComponent *JComponent_this, const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) , JComponent_this(JComponent_this) { clinit(); } javax::swing::JComponent_ReadObjectCallback::JComponent_ReadObjectCallback(JComponent *JComponent_this, ::java::io::ObjectInputStream* s) : JComponent_ReadObjectCallback(JComponent_this, *static_cast< ::default_init_tag* >(0)) { ctor(s); } void ::javax::swing::JComponent_ReadObjectCallback::ctor(::java::io::ObjectInputStream* s) { /* stub */ /* super::ctor(); */ unimplemented_(u"void ::javax::swing::JComponent_ReadObjectCallback::ctor(::java::io::ObjectInputStream* s)"); } /* private: void javax::swing::JComponent_ReadObjectCallback::registerComponent(JComponent* c) */ void javax::swing::JComponent_ReadObjectCallback::validateObject() { /* stub */ unimplemented_(u"void javax::swing::JComponent_ReadObjectCallback::validateObject()"); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* javax::swing::JComponent_ReadObjectCallback::class_() { static ::java::lang::Class* c = ::class_(u"javax.swing.JComponent.ReadObjectCallback", 41); return c; } java::lang::Class* javax::swing::JComponent_ReadObjectCallback::getClass0() { return class_(); }
34.913043
137
0.750311
pebble2015
d2904c04e891f05dddd6b2eaf3574eaa05531979
1,178
cpp
C++
TEST_C++/Test_env/src/robot-config.cpp
Asik007/1526B-VEX-code
69dc0187001b70793afa7a395be563daf303d163
[ "MIT" ]
1
2021-11-02T20:27:41.000Z
2021-11-02T20:27:41.000Z
TEST_C++/Test_env/src/robot-config.cpp
Asik007/1526B-VEX-code
69dc0187001b70793afa7a395be563daf303d163
[ "MIT" ]
null
null
null
TEST_C++/Test_env/src/robot-config.cpp
Asik007/1526B-VEX-code
69dc0187001b70793afa7a395be563daf303d163
[ "MIT" ]
1
2021-09-05T19:06:36.000Z
2021-09-05T19:06:36.000Z
#include "vex.h" using namespace vex; using signature = vision::signature; using code = vision::code; // A global instance of brain used for printing to the V5 Brain screen brain Brain; // VEXcode device constructors encoder EncoderA = encoder(Brain.ThreeWirePort.A); encoder EncoderB = encoder(Brain.ThreeWirePort.C); encoder EncoderC = encoder(Brain.ThreeWirePort.E); controller Controller1 = controller(primary); motor leftMotorA = motor(PORT1, ratio18_1, false); motor leftMotorB = motor(PORT2, ratio18_1, false); motor_group LeftDriveSmart = motor_group(leftMotorA, leftMotorB); motor rightMotorA = motor(PORT3, ratio18_1, true); motor rightMotorB = motor(PORT4, ratio18_1, true); motor_group RightDriveSmart = motor_group(rightMotorA, rightMotorB); gyro DrivetrainGyro = gyro(Brain.ThreeWirePort.H); smartdrive Drivetrain = smartdrive(LeftDriveSmart, RightDriveSmart, DrivetrainGyro, 319.19, 320, 40, mm, 2.3333333333333335); // VEXcode generated functions /** * Used to initialize code/tasks/devices added using tools in VEXcode Pro. * * This should be called at the start of your int main function. */ void vexcodeInit( void ) { // nothing to initialize }
33.657143
125
0.774194
Asik007
d2909926506b3d7751e7378311fa03c544095476
700
cpp
C++
CPP-BasicToAdvanced/CPP-BasicToAdvanced/Math.cpp
JCharlieDev/CPP-Intro
3d4888d413a09ae3579ef9079eaf1982a10c0d05
[ "MIT" ]
null
null
null
CPP-BasicToAdvanced/CPP-BasicToAdvanced/Math.cpp
JCharlieDev/CPP-Intro
3d4888d413a09ae3579ef9079eaf1982a10c0d05
[ "MIT" ]
null
null
null
CPP-BasicToAdvanced/CPP-BasicToAdvanced/Math.cpp
JCharlieDev/CPP-Intro
3d4888d413a09ae3579ef9079eaf1982a10c0d05
[ "MIT" ]
null
null
null
// #define INTEGER int // Stuff about how the compiler works and how to read the output files in the properties menu of the project. // How to set up the optimization and how it affects the code // How header files work and use them to generate and replace code. #include <iostream> #include "Log.h" //// Optimized version //const char* Log(const char* message) //{ // return message; //} //void Log(const char* message) //{ // std::cout << message << std::endl; //} int MultiplyNum(int a, int b) { Log("Multiplication"); return Multiply(a, b); } inline int Multiply(int a, int b) { return a * b; } // #include "EndBrace.h" // Literally copies the code of the header file into the cpp file
21.212121
109
0.69
JCharlieDev
d293c5755c27c9cb0da3e2df7cf15417ee7552a0
724
hpp
C++
src/mirrage/graphic/src/ktx_parser.hpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
14
2017-10-26T08:45:54.000Z
2021-04-06T11:44:17.000Z
src/mirrage/graphic/src/ktx_parser.hpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
17
2017-10-09T20:11:58.000Z
2018-11-08T22:05:14.000Z
src/mirrage/graphic/src/ktx_parser.hpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
1
2018-09-26T23:10:06.000Z
2018-09-26T23:10:06.000Z
#pragma once #include <mirrage/asset/stream.hpp> #include <mirrage/graphic/vk_wrapper.hpp> #include <mirrage/utils/maybe.hpp> #include <vulkan/vulkan.hpp> namespace mirrage::graphic { // https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ struct Ktx_header { std::uint32_t width; std::uint32_t height; std::uint32_t depth; std::uint32_t layers; bool cubemap; std::uint32_t mip_levels; std::uint32_t size; vk::Format format; Image_type type; }; // reads the KTX header and advances the read position to the beginning of the actual data extern auto parse_header(asset::istream&, const std::string& filename) -> util::maybe<Ktx_header>; } // namespace mirrage::graphic
24.965517
99
0.723757
lowkey42
d295da490be9ad3d3473fe46d9ca69bd4f30687d
21,046
cpp
C++
src/cmd/kits/row.cpp
caetanosauer/fineline-zero
74490df94728e513c2dd41f3edb8200698548b78
[ "Spencer-94" ]
12
2018-12-14T08:57:05.000Z
2021-12-14T17:37:44.000Z
src/cmd/kits/row.cpp
caetanosauer/fineline-zero
74490df94728e513c2dd41f3edb8200698548b78
[ "Spencer-94" ]
null
null
null
src/cmd/kits/row.cpp
caetanosauer/fineline-zero
74490df94728e513c2dd41f3edb8200698548b78
[ "Spencer-94" ]
2
2019-08-04T21:39:12.000Z
2019-11-09T03:18:48.000Z
/* -*- mode:C++; c-basic-offset:4 -*- Shore-kits -- Benchmark implementations for Shore-MT Copyright (c) 2007-2009 Data Intensive Applications and Systems Labaratory (DIAS) Ecole Polytechnique Federale de Lausanne All Rights Reserved. Permission to use, copy, modify and distribute this software and its documentation is hereby granted, provided that both the copyright notice and this permission notice appear in all copies of the software, derivative works or modified versions, and any portions thereof, and that both notices appear in supporting documentation. This 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. THE AUTHORS DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. */ /** @file: row.cpp * * @brief: Implementation of the base class for records (rows) of tables in Shore * * @author: Ippokratis Pandis, January 2008 * @author: Caetano Sauer, April 2015 * */ #include "row.h" #include "table_desc.h" #include "index_desc.h" #define VAR_SLOT(start, offset) ((start)+(offset)) #define SET_NULL_FLAG(start, offset) \ (*(char*)((start)+((offset)>>3))) &= (1<<((offset)>>3)) #define IS_NULL_FLAG(start, offset) \ (*(char*)((start)+((offset)>>3)))&(1<<((offset)>>3)) /****************************************************************** * * @struct: rep_row_t * * @brief: A scratchpad for writing the disk format of a tuple * ******************************************************************/ rep_row_t::rep_row_t() : _dest(NULL), _bufsz(0), _pts(NULL) { } rep_row_t::rep_row_t(blob_pool* apts) : _dest(NULL), _bufsz(0), _pts(apts) { assert (_pts); } rep_row_t::~rep_row_t() { if (_dest) { _pts->destroy(_dest); _dest = NULL; } } /****************************************************************** * * @fn: set * * @brief: Set new buffer size * ******************************************************************/ void rep_row_t::set(const unsigned nsz) { if ((!_dest) || (_bufsz < nsz)) { char* tmp = _dest; // Using the trash stack assert (_pts); //_dest = new(*_pts) char(nsz); w_assert1(nsz <= _pts->nbytes()); _dest = (char*)_pts->acquire(); assert (_dest); // Failed to allocate such a big buffer if (tmp) { // delete [] tmp; _pts->destroy(tmp); tmp = NULL; } _bufsz = _pts->nbytes(); } // in any case, clean up the buffer memset (_dest, 0, nsz); } /****************************************************************** * * @fn: set_ts * * @brief: Set new trash stack and buffer size * ******************************************************************/ void rep_row_t::set_ts(blob_pool* apts, const unsigned nsz) { assert(apts); _pts = apts; set(nsz); } /****************************************************************** * * @class: table_row_t * * @brief: The (main-memory) record representation in kits * ******************************************************************/ table_row_t::table_row_t() : _ptable(NULL), _field_cnt(0), _is_setup(false), _pvalues(NULL), _fixed_offset(0),_var_slot_offset(0),_var_offset(0),_null_count(0), _rep(NULL), _rep_key(NULL) { } table_row_t::~table_row_t() { freevalues(); } /****************************************************************** * * @fn: setup() * * @brief: Setups the row (tuple main-memory representation) according * to its table description. This setup will be done only * *once*. When this row will be initialized in the row cache. * ******************************************************************/ int table_row_t::setup(table_desc_t* ptd) { assert (ptd); // if it is already setup for this table just reset it if ((_ptable == ptd) && (_pvalues != NULL) && (_is_setup)) { reset(); return (1); } // else do the normal setup _ptable = ptd; _field_cnt = ptd->field_count(); assert (_field_cnt>0); _pvalues = new field_value_t[_field_cnt]; unsigned var_count = 0; unsigned fixed_size = 0; // setup each field and calculate offsets along the way for (unsigned i=0; i<_field_cnt; i++) { _pvalues[i].setup(ptd->desc(i)); // count variable- and fixed-sized fields if (_pvalues[i].is_variable_length()) var_count++; else fixed_size += _pvalues[i].maxsize(); // count null-able fields if (_pvalues[i].field_desc()->allow_null()) _null_count++; } // offset for fixed length field values _fixed_offset = 0; if (_null_count) _fixed_offset = ((_null_count-1) >> 3) + 1; // offset for variable length field slots _var_slot_offset = _fixed_offset + fixed_size; // offset for variable length field values _var_offset = _var_slot_offset + sizeof(offset_t)*var_count; _is_setup = true; return (0); } /****************************************************************** * * @fn: size() * * @brief: Return the actual size of the tuple in disk format * ******************************************************************/ unsigned table_row_t::size() const { assert (_is_setup); unsigned size = 0; /* for a fixed length field, it just takes as much as the * space for the value itself to store. * for a variable length field, we store as much as the data * and the offset to tell the length of the data. * Of course, there is a bit for each nullable field. */ for (unsigned i=0; i<_field_cnt; i++) { if (_pvalues[i]._pfield_desc->allow_null()) { if (_pvalues[i].is_null()) continue; } if (_pvalues[i].is_variable_length()) { size += _pvalues[i].realsize(); size += sizeof(offset_t); } else size += _pvalues[i].maxsize(); } if (_null_count) size += (_null_count >> 3) + 1; return (size); } void _load_signed_int(char* dest, char* src, size_t nbytes) { // invert sign bit and reverse endianness size_t lsb = nbytes - 1; for (size_t i = 0; i < nbytes; i++) { dest[i] = src[lsb - i]; } dest[lsb] ^= 0x80; } void table_row_t::load_key(char* data, index_desc_t* pindex) { char buffer[8]; char* pos = data; #ifdef USE_LEVELDB if (pindex) { // In LevelDB storage, first byte of key is the StoreID auto stid = static_cast<StoreID>(*data); w_assert1(stid > 0 && stid < 128); w_assert1(stid == pindex->stid()); pos++; } #endif unsigned field_cnt = pindex ? pindex->field_count() : _field_cnt; for (unsigned j = 0; j < field_cnt; j++) { unsigned i = pindex ? pindex->key_index(j) : j; field_value_t& field = _pvalues[i]; field_desc_t* fdesc = field._pfield_desc; w_assert1(field.is_setup()); if (fdesc->allow_null()) { bool is_null = (*pos == true); field.set_null(is_null); pos++; if (is_null) { continue; } } switch (fdesc->type()) { case SQL_BIT: { field.set_bit_value(*pos); pos++; break; } case SQL_SMALLINT: { memcpy(buffer, pos, 2); _load_signed_int(buffer, pos, 2); field.set_smallint_value(*(int16_t*) buffer); pos += 2; break; } case SQL_INT: { memcpy(buffer, pos, 4); _load_signed_int(buffer, pos, 4); field.set_int_value(*(int32_t*) buffer); pos += 4; break; } case SQL_LONG: { memcpy(buffer, pos, 8); _load_signed_int(buffer, pos, 8); field.set_long_value(*(int64_t*) buffer); pos += 8; break; } case SQL_FLOAT: { memcpy(buffer, pos, 8); // invert endianness and handle sign bit if (buffer[0] & 0x80) { // inverted sign bit == 1 -> positive // invert only sign bit for (int i = 0; i < 8; i++) { buffer[i] = pos[7 - i]; } buffer[7] ^= 0x80; } else { // otherwise invert all bits for (int i = 0; i < 8; i++) { buffer[i] = pos[7 - i] ^ 0x80; } } field.set_float_value(*(double*) buffer); pos += 8; break; } case SQL_CHAR: field.set_char_value(*pos); pos++; break; case SQL_FIXCHAR: { size_t len = strlen(pos); field.set_fixed_string_value(pos, len); pos += len + 1; break; } case SQL_VARCHAR: { size_t len = strlen(pos); field.set_var_string_value(pos, len); pos += len + 1; break; } default: throw runtime_error("Serialization not supported for the \ given type"); } } } void table_row_t::load_value(char* data, index_desc_t* pindex) { // Read the data field by field assert (data); // 1. Get the pre-calculated offsets // current offset for fixed length field values offset_t fixed_offset = get_fixed_offset(); // current offset for variable length field slots offset_t var_slot_offset = get_var_slot_offset(); // current offset for variable length field values offset_t var_offset = get_var_offset(); // 2. Read the data field by field int null_index = -1; for (unsigned i=0; i<_ptable->field_count(); i++) { if (pindex) { bool skip = false; // skip key fields for (unsigned j = 0; j < pindex->field_count(); j++) { if ((int) i == pindex->key_index(j)) { skip = true; break; } } if (skip) continue; } // Check if the field can be NULL. // If it can be NULL, increase the null_index, // and check if the bit in the null_flags bitmap is set. // If it is set, set the corresponding value in the tuple // as null, and go to the next field, ignoring the rest if (_pvalues[i].field_desc()->allow_null()) { null_index++; if (IS_NULL_FLAG(data, null_index)) { _pvalues[i].set_null(); continue; } } // Check if the field is of VARIABLE length. // If it is, copy the offset of the value from the offset part of the // buffer (pointed by var_slot_offset). Then, copy that many chars from // the variable length part of the buffer (pointed by var_offset). // Then increase by one offset index, and offset of the pointer of the // next variable value if (_pvalues[i].is_variable_length()) { offset_t var_len; memcpy(&var_len, VAR_SLOT(data, var_slot_offset), sizeof(offset_t)); _pvalues[i].set_value(data+var_offset, var_len); var_offset += var_len; var_slot_offset += sizeof(offset_t); } else { // If it is of FIXED length, copy the data from the fixed length // part of the buffer (pointed by fixed_offset), and the increase // the fixed offset by the (fixed) size of the field _pvalues[i].set_value(data+fixed_offset, _pvalues[i].maxsize()); fixed_offset += _pvalues[i].maxsize(); } } } void _store_signed_int(char* dest, char* src, size_t nbytes) { // reverse endianness and invert sign bit size_t lsb = nbytes - 1; for (size_t i = 0; i < nbytes; i++) { dest[i] = src[lsb - i]; } dest[0] ^= 0x80; } void table_row_t::store_key(char* data, size_t& length, index_desc_t* pindex) { size_t req_size = 0; char buffer[8]; char* pos = data; #ifdef USE_LEVELDB // In LevelDB storage, first byte of key is the StoreID if (pindex) { auto stid = pindex->stid(); w_assert1(stid > 0 && stid < 128); *pos = static_cast<char>(stid); pos++; req_size++; w_assert1(data[0] != 0); } #endif unsigned field_cnt = pindex ? pindex->field_count() : _field_cnt; for (unsigned j = 0; j < field_cnt; j++) { unsigned i = pindex ? pindex->key_index(j) : j; field_value_t& field = _pvalues[i]; field_desc_t* fdesc = field._pfield_desc; w_assert1(field.is_setup()); req_size += field.realsize(); if (fdesc->allow_null()) { req_size++; } if (length < req_size) { throw runtime_error("Tuple does not fit on given buffer"); } if (fdesc->allow_null()) { if (field.is_null()) { // copy a zero byte to the output and proceed *pos = 0x00; pos++; continue; } else { // non-null nullable fields require a 1 prefix *pos = 0xFF; pos++; } } switch (fdesc->type()) { case SQL_BIT: { bool v = field.get_bit_value(); *pos = v ? 0xFF : 0x00; break; } case SQL_SMALLINT: { field.copy_value(buffer); _store_signed_int(pos, buffer, 2); pos += 2; break; } case SQL_INT: { field.copy_value(buffer); _store_signed_int(pos, buffer, 4); pos += 4; break; } case SQL_LONG: { field.copy_value(buffer); _store_signed_int(pos, buffer, 8); pos += 8; break; } case SQL_FLOAT: { field.copy_value(buffer); // invert endianness and handle sign bit if (buffer[0] & 0x80) { // if negative, invert all bits for (int i = 0; i < 8; i++) { pos[i] = buffer[7 - i] ^ 0xFF; } } else { // otherwise invert only sign bit for (int i = 0; i < 8; i++) { pos[i] = buffer[7 - i]; } pos[0] ^= 0x80; } pos += 8; break; } case SQL_CHAR: *pos = field.get_char_value(); pos++; break; case SQL_FIXCHAR: case SQL_VARCHAR: // Assumption is that strings already include the terminating zero field.copy_value(pos); pos += field.realsize(); w_assert1(*(pos - 1) == 0); break; default: throw runtime_error("Serialization not supported for the \ given type"); } } length = req_size; w_assert1(pos - data == (long) length); } void table_row_t::store_value(char* data, size_t& length, index_desc_t* pindex) { // 1. Get the pre-calculated offsets // current offset for fixed length field values offset_t fixed_offset = get_fixed_offset(); // current offset for variable length field slots offset_t var_slot_offset = get_var_slot_offset(); // current offset for variable length field values offset_t var_offset = get_var_offset(); // 2. calculate the total space of the tuple // (tupsize) : total space of the tuple int tupsize = 0; int null_count = get_null_count(); int fixed_size = get_var_slot_offset() - get_fixed_offset(); // loop over all the variable-sized fields and add their real size (set at ::set()) for (unsigned i=0; i<_ptable->field_count(); i++) { if (_pvalues[i].is_variable_length()) { // If it is of VARIABLE length, then if the value is null // do nothing, else add to the total tuple length the (real) // size of the value plus the size of an offset. if (_pvalues[i].is_null()) continue; tupsize += _pvalues[i].realsize(); tupsize += sizeof(offset_t); } // If it is of FIXED length, then increase the total tuple // length, as well as, the size of the fixed length part of // the tuple by the fixed size of this type of field. // IP: The length of the fixed-sized fields is added after the loop } // Add up the length of the fixed-sized fields tupsize += fixed_size; // In the total tuple length add the size of the bitmap that // shows which fields can be NULL if (null_count) tupsize += (null_count >> 3) + 1; assert (tupsize); if ((long) length < tupsize) { throw runtime_error("Tuple does not fit on allocated buffer"); } length = tupsize; // 4. Copy the fields to the array, field by field int null_index = -1; // iterate over all fields for (unsigned i=0; i<_ptable->field_count(); i++) { // skip fields which are part of the given index if (pindex) { bool skip = false; for (unsigned j=0; j<pindex->field_count(); j++) { if ((int) i == pindex->key_index(j)) { skip = true; break; } } if (skip) continue; } // Check if the field can be NULL. // If it can be NULL, increase the null_index, and // if it is indeed NULL set the corresponding bit if (_pvalues[i].field_desc()->allow_null()) { null_index++; if (_pvalues[i].is_null()) { SET_NULL_FLAG(data, null_index); } } // Check if the field is of VARIABLE length. // If it is, copy the field value to the variable length part of the // buffer, to position (buffer + var_offset) // and increase the var_offset. if (_pvalues[i].is_variable_length()) { _pvalues[i].copy_value(data + var_offset); int offset = _pvalues[i].realsize(); var_offset += offset; // set the offset offset_t len = offset; memcpy(VAR_SLOT(data, var_slot_offset), &len, sizeof(offset_t)); var_slot_offset += sizeof(offset_t); } else { // If it is of FIXED length, then copy the field value to the // fixed length part of the buffer, to position // (buffer + fixed_offset) // and increase the fixed_offset _pvalues[i].copy_value(data + fixed_offset); fixed_offset += _pvalues[i].maxsize(); } } } /* ----------------- */ /* --- debugging --- */ /* ----------------- */ /* For debug use only: print the value of all the fields of the tuple */ void table_row_t::print_values(ostream& os) { assert (_is_setup); // cout << "Number of fields: " << _field_count << endl; for (unsigned i=0; i<_field_cnt; i++) { _pvalues[i].print_value(os); if (i != _field_cnt-1) os << DELIM_CHAR; } os << ROWEND_CHAR << endl; } /* For debug use only: print the tuple */ void table_row_t::print_tuple() { assert (_is_setup); char* sbuf = NULL; int sz = 0; for (unsigned i=0; i<_field_cnt; i++) { sz = _pvalues[i].get_debug_str(sbuf); if (sbuf) { TRACE( TRACE_TRX_FLOW, "%d. %s (%d)\n", i, sbuf, sz); delete [] sbuf; sbuf = NULL; } } } /* For debug use only: print the tuple without tracing */ void table_row_t::print_tuple_no_tracing() { assert (_is_setup); char* sbuf = NULL; int sz = 0; for (unsigned i=0; i<_field_cnt; i++) { sz = _pvalues[i].get_debug_str(sbuf); if (sbuf) { fprintf( stderr, "%d. %s (%d)\n", i, sbuf, sz); delete [] sbuf; sbuf = NULL; } } } #include <sstream> char const* db_pretty_print(table_row_t const* rec, int /* i=0 */, char const* /* s=0 */) { static char data[1024]; std::stringstream inout(data,stringstream::in | stringstream::out); //std::strstream inout(data, sizeof(data)); ((table_row_t*)rec)->print_values(inout); inout << std::ends; return data; }
29.311978
89
0.518483
caetanosauer
d297aeafc8dcbdcc08449980c5e500b23432f323
5,171
cpp
C++
platform/mbedtls/network.cpp
jflynn129/aws-iot-device-sdk-mbed-c
3248e6ea5467aaa2fc5f66ee6baca9f50095daa8
[ "Apache-2.0" ]
null
null
null
platform/mbedtls/network.cpp
jflynn129/aws-iot-device-sdk-mbed-c
3248e6ea5467aaa2fc5f66ee6baca9f50095daa8
[ "Apache-2.0" ]
null
null
null
platform/mbedtls/network.cpp
jflynn129/aws-iot-device-sdk-mbed-c
3248e6ea5467aaa2fc5f66ee6baca9f50095daa8
[ "Apache-2.0" ]
null
null
null
/* * TCP/IP or UDP/IP networking functions * * This version of net_sockets.c is setup to use ARM easy-connect for network connectivity * * * 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 "mbed.h" #include "easy-connect.h" #define MBEDTLS_FS_IO 1 #include <stdbool.h> #include <string.h> #include <timer_platform.h> #include <network_interface.h> #include "mbedtls/platform.h" #include "mbedtls/ssl.h" #include "mbedtls/entropy.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/error.h" #include "mbedtls/x509_crt.h" #include "mbedtls/pk.h" #if DEBUG_LEVEL > 0 #include "mbedtls/debug.h" #endif #include "aws_iot_error.h" #include "aws_iot_log.h" #include "network_interface.h" #include "network_platform.h" #include "awscerts.h" NetworkInterface *network = NULL; TCPSocket mbedtls_socket; bool network_connected = false; /* * Initialize a context */ void mbedtls_aws_init( mbedtls_net_context *ctx ) { FUNC_ENTRY; if( network != NULL ) network->disconnect(); //disconnect from the current network network_connected = false; network = easy_connect(true); if (!network) { IOT_DEBUG("Network Connection Failed!"); return; } IOT_DEBUG("Modem SW Revision: %s", FIRMWARE_REV(network)); network_connected = true; ctx->fd = 1; } /* * Initiate a TCP connection with host:port and the given protocol * return 0 if success, otherwise error is returned */ int mbedtls_aws_connect( mbedtls_net_context *ctx, const char *host, uint16_t port, int proto ) { FUNC_ENTRY; if( !network_connected ) { IOT_DEBUG("No network connection"); FUNC_EXIT_RC(NETWORK_ERR_NET_CONNECT_FAILED); } int ret = mbedtls_socket.open(network) || mbedtls_socket.connect(host,port); if( ret != 0 ){ IOT_DEBUG("Socket Open Failed - %d",ret); } FUNC_EXIT_RC(ret); } /* * Create a listening socket on bind_ip:port */ int mbedtls_aws_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto ) { FUNC_EXIT_RC(MBEDTLS_ERR_NET_BIND_FAILED); } /* * Accept a connection from a remote client */ int mbedtls_aws_accept( mbedtls_net_context *bind_ctx, mbedtls_net_context *client_ctx, void *client_ip, size_t buf_size, size_t *ip_len ) { FUNC_ENTRY; FUNC_EXIT_RC(MBEDTLS_ERR_NET_ACCEPT_FAILED ); } /* * Set the socket blocking or non-blocking */ int mbedtls_aws_set_block( mbedtls_net_context *ctx ) { mbedtls_socket.set_blocking(true); return 0; } int mbedtls_aws_set_nonblock( mbedtls_net_context *ctx ) { mbedtls_socket.set_blocking(false); return 0; } /* * Portable usleep helper */ void mbedtls_aws_usleep( unsigned long usec ) { FUNC_ENTRY; Timer t; t.start(); while( t.read_us() < (int)usec ) /* wait here */ ; } /* * Read at most 'len' characters */ int mbedtls_aws_recv( void *ctx, unsigned char *buf, size_t len ) { int ret; int fd = ((mbedtls_net_context *) ctx)->fd; FUNC_ENTRY; if( fd < 0 ) FUNC_EXIT_RC(MBEDTLS_ERR_NET_INVALID_CONTEXT ); ret = (int) mbedtls_socket.recv( buf, len ); if( ret == NSAPI_ERROR_WOULD_BLOCK ) ret = MBEDTLS_ERR_SSL_WANT_READ; FUNC_EXIT_RC(ret ); } /* * Read at most 'len' characters, blocking for at most 'timeout' ms */ int mbedtls_aws_recv_timeout( void *ctx, unsigned char *buf, size_t len, uint32_t timeout ) { int ret, ttime; Timer t; FUNC_ENTRY; t.start(); do { ret = mbedtls_aws_recv( ctx, buf, len ); ttime = t.read_ms(); } while( ttime < (int)timeout && ret < 0 ); if( ret < 0 && ttime >= (int)timeout ) ret = MBEDTLS_ERR_SSL_TIMEOUT; FUNC_EXIT_RC(ret); } /* * Write at most 'len' characters */ int mbedtls_aws_send( void *ctx, const unsigned char *buf, size_t len ) { int ret = NSAPI_ERROR_WOULD_BLOCK; Timer t; int fd = ((mbedtls_net_context *) ctx)->fd; FUNC_ENTRY; if( fd < 0 ) FUNC_EXIT_RC(NETWORK_PHYSICAL_LAYER_DISCONNECTED); t.start(); while( ret == NSAPI_ERROR_WOULD_BLOCK && t.read_ms() < 100) ret = mbedtls_socket.send(buf, len); if( ret < 0 ) ret = MBEDTLS_ERR_NET_SEND_FAILED; FUNC_EXIT_RC( ret ); } /* * Gracefully close the connection */ void mbedtls_aws_free( mbedtls_net_context *ctx ) { FUNC_ENTRY; if( !network_connected || ctx->fd < 0 ) { FUNC_EXIT; } mbedtls_socket.close(); network->disconnect(); //disconnect from the current network ctx->fd = -1; FUNC_EXIT; }
23.188341
98
0.662928
jflynn129
d29f5e0ba91821cf5241b47ddb346d3a89d8fe18
477
cpp
C++
src/RE/Scaleform/GAtomic/GAtomic.cpp
thallada/CommonLibSSE
b092c699c3ccd1af6d58d05f677f2977ec054cfe
[ "MIT" ]
1
2021-08-30T20:33:43.000Z
2021-08-30T20:33:43.000Z
src/RE/Scaleform/GAtomic/GAtomic.cpp
thallada/CommonLibSSE
b092c699c3ccd1af6d58d05f677f2977ec054cfe
[ "MIT" ]
null
null
null
src/RE/Scaleform/GAtomic/GAtomic.cpp
thallada/CommonLibSSE
b092c699c3ccd1af6d58d05f677f2977ec054cfe
[ "MIT" ]
1
2020-10-08T02:48:33.000Z
2020-10-08T02:48:33.000Z
#include "RE/Scaleform/GAtomic/GAtomic.h" namespace RE { GLock::Locker::Locker(GLock* a_lock) { lock = a_lock; lock->Lock(); } GLock::Locker::~Locker() { lock->Unlock(); } GLock::GLock(std::uint32_t a_spinCount) { ::InitializeCriticalSectionAndSpinCount(&cs, a_spinCount); } GLock::~GLock() { ::DeleteCriticalSection(&cs); } void GLock::Lock() { ::EnterCriticalSection(&cs); } void GLock::Unlock() { ::LeaveCriticalSection(&cs); } }
11.357143
60
0.637317
thallada
d2a1120223d31252ef287252028181cb58f0bdf7
533
cc
C++
CMC040/smg/lbr_get_record.cc
khandy21yo/aplus
3b4024a2a8315f5dcc78479a24100efa3c4a6504
[ "MIT" ]
1
2018-10-17T08:53:17.000Z
2018-10-17T08:53:17.000Z
CMC040/smg/lbr_get_record.cc
khandy21yo/aplus
3b4024a2a8315f5dcc78479a24100efa3c4a6504
[ "MIT" ]
null
null
null
CMC040/smg/lbr_get_record.cc
khandy21yo/aplus
3b4024a2a8315f5dcc78479a24100efa3c4a6504
[ "MIT" ]
null
null
null
//! \file //! \brief Get Record //! #include <string> #include "smg/lbr.h" //! //! \brief Get Record //! long lbr$get_record( lbr_index_cdd &lr_index, std::string &text) { // // Nothing left // if (lr_index.datum.size() == 0) { text = ""; return 0; } // // Pull off one line of text // int pos = lr_index.datum.find('\n'); if (pos == std::string::npos) { text = lr_index.datum; lr_index.datum.empty(); } else { text = lr_index.datum.substr(0, pos); lr_index.datum.erase(0, pos + 1); } return 1; }
12.690476
39
0.581614
khandy21yo
d2b1af3211a02523576f5d63fe617aea84a3a3fb
1,786
hpp
C++
CfgLoadouts.hpp
TheeProTag/Atropia_Free
0988c6addaf7cd2334e0d8d553d61ed50dd6faa5
[ "Unlicense" ]
null
null
null
CfgLoadouts.hpp
TheeProTag/Atropia_Free
0988c6addaf7cd2334e0d8d553d61ed50dd6faa5
[ "Unlicense" ]
null
null
null
CfgLoadouts.hpp
TheeProTag/Atropia_Free
0988c6addaf7cd2334e0d8d553d61ed50dd6faa5
[ "Unlicense" ]
null
null
null
class CfgLoadouts { //Use POTATO to run gear assignment usePotato = 1; //Fast, Easy Settings to change loadouts without touching the arrays. For TVT Balancing. //Allow Zoomed Optics (1 is true, 0 is false) <Anything like a HAMR (4x) optic won't be added, "red dot" would be fine> allowMagnifiedOptics = 0; //Do Vehicle Loadouts //(1 will run normaly, 0 will leave them to vanilla defaults, -1 will clear and leave empty) setVehicleLoadouts = -1; //Fallback: use a basic soldiers loadout when the unit's classname isn't found (for Alive spawning random units) useFallback = 1; //Shared items #include "Loadouts\common.hpp" // DO NOT COMMENT OUT, WILL BREAK EVERYTHING //Only include one hpp per faction; use (//) to comment out other files //BLUFOR FACTION (blu_f): #include "Loadouts\blu_us_m4_ucp.hpp" // US: M4 - Gray/Green // #include "Loadouts\blu_us_m4_ocp.hpp" // US: M4 - Tan // #include "Loadouts\blu_brit_l85_mtp.hpp" // British: L86 - Multi-Terrain Pattern // #include "Loadouts\blu_ger_g36_fleck.hpp" // German: G36 - Flecktarn Camo //INDFOR FACTION (ind_f): #include "Loadouts\ind_ukr_ak74_ttsko.hpp" // Ukraine: AK74 - TTskO // #include "Loadouts\ind_ukr_ak74_ddpm.hpp" // "Ukraine": AK74 - Desert DPM // #include "Loadouts\ind_reb_ak47_desert.hpp" // Rebel: AK47 - Mixed Desert // #include "Loadouts\ind_ger_g36_tropen.hpp" // German: G36 - Tropen Camo //OPFOR FACTION (opf_f): #include "Loadouts\opf_ru_ak74_floral.hpp" // Russian: AK74 - Floral // #include "Loadouts\opf_reb_ak47_desert.hpp" // Rebel: AK47 - Mixed Desert //Civilians (mainly for RP missions) #include "Loadouts\civilians.hpp" //Bare example of doing civilian loadouts };
44.65
121
0.68869
TheeProTag
d2b2eb6cf3915ec8d95adbc664266f87372bc5c2
367
cpp
C++
docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_39.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_39.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_39.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
// typedef CStringT<TCHAR, StrTraitATL<TCHAR, ChTraitsCRT<TCHAR>>> CAtlString; CAtlString str(_T("%First Second#Third")); CAtlString resToken; int curPos = 0; resToken= str.Tokenize(_T("% #"),curPos); while (resToken != _T("")) { _tprintf_s(_T("Resulting token: %s\n"), resToken); resToken = str.Tokenize(_T("% #"), curPos); };
33.363636
81
0.615804
bobbrow
d2b61e4b76cb18e954f0173aade99523bd7bbcde
320
cpp
C++
src/widgets/fonteditor.cpp
Eggbertx/QtSphere-IDE
7ae7ed840fcef7a79fb47a6903afb95ca23838ca
[ "BSD-2-Clause" ]
12
2017-05-04T16:58:07.000Z
2021-06-09T03:08:29.000Z
src/widgets/fonteditor.cpp
Eggbertx/QtSphere-IDE
7ae7ed840fcef7a79fb47a6903afb95ca23838ca
[ "BSD-2-Clause" ]
1
2017-06-19T03:30:22.000Z
2018-04-09T21:35:00.000Z
src/widgets/fonteditor.cpp
Eggbertx/QtSphere-IDE
7ae7ed840fcef7a79fb47a6903afb95ca23838ca
[ "BSD-2-Clause" ]
1
2018-09-04T00:27:54.000Z
2018-09-04T00:27:54.000Z
#include "fonteditor.h" #include "ui_fonteditor.h" // This doesn't do anything yet, and with the direction // I'm planning on taking QSI, it might be removed. FontEditor::FontEditor(QWidget *parent): QWidget(parent), ui(new Ui::FontEditor) { ui->setupUi(this); } FontEditor::~FontEditor() { delete ui; }
24.615385
83
0.69375
Eggbertx
d2bf610f8676af660ad0a6574d700801e15affce
3,078
cpp
C++
src/plugins/sb2/tabunhidelistview.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
1
2017-01-12T07:05:45.000Z
2017-01-12T07:05:45.000Z
src/plugins/sb2/tabunhidelistview.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/sb2/tabunhidelistview.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "tabunhidelistview.h" #if QT_VERSION < 0x050000 #include <QGraphicsObject> #else #include <QQuickItem> #endif #include <QtDebug> #include <util/util.h> #include <util/qml/unhidelistmodel.h> namespace LeechCraft { namespace SB2 { TabUnhideListView::TabUnhideListView (const QList<TabClassInfo>& tcs, ICoreProxy_ptr proxy, QWidget *parent) : UnhideListViewBase (proxy, [&tcs] (QStandardItemModel *model) { for (const auto& tc : tcs) { auto item = new QStandardItem; item->setData (tc.TabClass_, Util::UnhideListModel::Roles::ItemClass); item->setData (tc.VisibleName_, Util::UnhideListModel::Roles::ItemName); item->setData (tc.Description_, Util::UnhideListModel::Roles::ItemDescription); item->setData (Util::GetAsBase64Src (tc.Icon_.pixmap (32, 32).toImage ()), Util::UnhideListModel::Roles::ItemIcon); model->appendRow (item); } }, parent) { connect (rootObject (), SIGNAL (itemUnhideRequested (QString)), this, SLOT (unhide (QString)), Qt::QueuedConnection); } void TabUnhideListView::unhide (const QString& idStr) { const auto& id = idStr.toUtf8 (); emit unhideRequested (id); for (int i = 0; i < Model_->rowCount (); ++i) if (Model_->item (i)->data (Util::UnhideListModel::Roles::ItemClass).toByteArray () == id) { Model_->removeRow (i); break; } if (!Model_->rowCount ()) deleteLater (); } } }
35.790698
93
0.690058
MellonQ
d2c158a5d6b3e21981c3908c958902651f26de91
2,146
hpp
C++
decompiler/exe.hpp
WastedMeerkat/gm81decompiler
80040ac74f95af03b4b6649b0f5be11a7d13700b
[ "MIT" ]
40
2017-07-31T22:20:49.000Z
2022-01-28T14:57:44.000Z
decompiler/exe.hpp
nkrapivin/gm81decompiler
bae1f8c3f52ed80c50319555c96752d087520821
[ "MIT" ]
null
null
null
decompiler/exe.hpp
nkrapivin/gm81decompiler
bae1f8c3f52ed80c50319555c96752d087520821
[ "MIT" ]
15
2015-12-29T16:36:28.000Z
2021-12-19T09:04:54.000Z
/* * exe.hpp * GM EXE Abstraction */ #ifndef __EXE_HPP #define __EXE_HPP #include <iostream> #include <string> #include "gmk.hpp" #define SWAP_TABLE_SIZE 256 // Icon headers #pragma pack(push, 1) typedef struct { unsigned char bWidth; // Width, in pixels, of the image unsigned char bHeight; // Height, in pixels, of the image unsigned char bColorCount; // Number of colors in image (0 if >=8bpp) unsigned char bReserved; // Reserved ( must be 0) unsigned short wPlanes; // Color Planes unsigned short wBitCount; // Bits per pixel unsigned int dwBytesInRes; // How many bytes in this resource? unsigned int dwImageOffset; // Where in the file is this image? } ICONDIRENTRY, *LPICONDIRENTRY; typedef struct { unsigned short idReserved; // Reserved (must be 0) unsigned short idType; // Resource Type (1 for icons) unsigned short idCount; // How many images? ICONDIRENTRY idEntries[1]; // An entry for each image (idCount of 'em) } ICONDIR, *LPICONDIR; #pragma pack(pop) class GmExe { private: std::string exeFilename; unsigned int version; GmkStream* exeHandle; Gmk* gmkHandle; // GMK support -- Technically shouldn't be here void RTAddItem(const std::string& name, int rtId, int index); bool DecryptGameData(); GmkStream* GetIconData(); void ReadAction(GmkStream* stream, ObjectAction* action); bool ReadSettings(); bool ReadWrapper(); bool ReadExtensions(); bool ReadTriggers(); bool ReadConstants(); bool ReadSounds(); bool ReadSprites(); bool ReadBackgrounds(); bool ReadPaths(); bool ReadScripts(); bool ReadFonts(); bool ReadTimelines(); bool ReadObjects(); bool ReadRooms(); bool ReadIncludes(); bool ReadGameInformation(); public: GmExe() : exeHandle(new GmkStream()), version(0), exeFilename("") { } ~GmExe() { delete exeHandle; } // Interface functions bool Load(const std::string& filename, Gmk* gmk, unsigned int ver); const unsigned int GetExeVersion() const { return version; } }; #endif
26.493827
84
0.66123
WastedMeerkat
d2c20f256d5fd0bec41871a5c726c73f480ca8b6
2,802
cpp
C++
mfcc/Feature/mathtool.cpp
wengsht/cuda-mfcc-gmm
83587058e3b023060de15f05d848d730add2fe65
[ "MIT", "Unlicense" ]
9
2015-07-07T11:56:20.000Z
2021-02-11T01:31:02.000Z
mfcc/Feature/mathtool.cpp
wengsht/cuda-mfcc-gmm
83587058e3b023060de15f05d848d730add2fe65
[ "MIT", "Unlicense" ]
1
2015-07-25T14:04:00.000Z
2015-07-25T14:04:00.000Z
mfcc/Feature/mathtool.cpp
wengsht/cuda-mfcc-gmm
83587058e3b023060de15f05d848d730add2fe65
[ "MIT", "Unlicense" ]
5
2015-04-23T12:30:48.000Z
2019-02-11T06:53:43.000Z
// // mathtool.cpp // SpeechRecongnitionSystem // // Created by Admin on 9/11/14. // Copyright (c) 2014 Admin. All rights reserved. // #include "mathtool.h" #include <assert.h> #include <iostream> #include "math.h" #include "Feature.h" using namespace std; const int MAXN = 1000; // fft(a, n, 1) -- dft // fft(a, n, -1) -- idft // n should be 2^k void fft(cp *a,int n,int f) { // assert(MAXN > n); cp *b = new cp[n]; double arg = PI; for(int k = n>>1;k;k>>=1,arg*=0.5){ cp wm = std::polar(1.0,f*arg),w(1,0); for(int i = 0;i<n;i+=k,w*=wm){ int p = i << 1; if(p>=n) p-= n; for(int j = 0;j<k;++j){ b[i+j] = a[p+j] + w*a[p+k+j]; } } for(int i = 0;i<n;++i) a[i] = b[i]; } delete []b; } // use to check fft is right void dft(cp *a,int n,int f) { cp *b = new cp[n]; for(int i = 0;i < n;i++) { b[i] = cp(0, 0); for(int j = 0;j < n;j++) { b[i] += cp(std::real(a[j])*cos(-2.0*PI*j*i/n), std::real(a[j])*sin(-2.0*PI*j*i/n)); } } for(int i = 0;i<n;++i) a[i] = b[i]; delete []b; } // a's size should be more then 2*n void dct(double *a,int n,int f) { cp *b = new cp[2*n]; for(int i = n-1;i >= 0;i--) { b[n-i-1] = b[n+i] = cp(a[i], 0); } dft(b, 2*n, f); for(int i = 0;i < 2*n;i++) a[i] = std::real(b[i]); delete [] b; } void dct2(double *a, int n) { double *b = new double[n]; for(int i = 0;i < n;i++) { b[i] = 0.0; for(int j = 0;j < n;j++) b[i] += a[j] * cos(PI*i*(j+1.0/2)/n); } for(int i = 0;i < n;i++) a[i] = b[i] * sqrt(2.0/n) / sqrt(2.0); delete [] b; } // -log(x+y) a = -log(x) b = -log(y) double logInsideSum(double a, double b) { if(a >= b) std::swap(a, b); // printf("%lf %lf %lf\n", a, b,a - log(1.0 + pow(e, a-b))); return a - log(1.0 + pow(e, a-b)); } // -log((abs(x-y)) a = -log(x) b = -log(y) double logInsideDist(double a, double b) { if(a >= b) std::swap(a, b); // printf("%lf %lf %lf\n", a, b,a - log(1.0 + pow(e, a-b))); return a - log(1.0 - pow(e, a-b)); } // probability to cost double p2cost(double p) { if(p <= 0) return Feature::IllegalDist; return - log(p); } double cost2p(double cost) { return pow(e, -cost); } void matrix2vector(const Matrix<double> & data, double *vec){ int rowSize=data[0].size(); for(int i=0; i<data.size(); i++){ for(int j=0; j<rowSize; j++){ *vec = data[i][j]; vec++; } } } void vector2matrix(double *vec, Matrix<double> & data){ for(int i=0; i< data.size(); i++){ for(int j=0; j<data[0].size(); j++){ data[i][j] = *vec; vec++; } } }
22.780488
95
0.457173
wengsht
d2c49949e6e8fcbcc67831349a64f1862e838466
13,978
cpp
C++
examples/platforms/utils/settings.cpp
mostafanfs/openthread
28c049f2ce0b664abf2f85562cfd9b79b4680389
[ "BSD-3-Clause" ]
null
null
null
examples/platforms/utils/settings.cpp
mostafanfs/openthread
28c049f2ce0b664abf2f85562cfd9b79b4680389
[ "BSD-3-Clause" ]
null
null
null
examples/platforms/utils/settings.cpp
mostafanfs/openthread
28c049f2ce0b664abf2f85562cfd9b79b4680389
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2016, The OpenThread Authors. * 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 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements the OpenThread platform abstraction for non-volatile storage of settings. * */ #include <stdlib.h> #include <stddef.h> #include <string.h> #include <assert.h> #include <openthread-types.h> #include <openthread-core-config.h> #include <common/code_utils.hpp> #include <platform/settings.h> #include "flash.h" #ifdef __cplusplus extern "C" { #endif enum { kBlockAddBeginFlag = 0x1, kBlockAddCompleteFlag = 0x02, kBlockDeleteFlag = 0x04, kBlockIndex0Flag = 0x08, }; enum { kSettingsFlagSize = 4, kSettingsBlockDataSize = 255, kSettingsInSwap = 0xbe5cc5ef, kSettingsInUse = 0xbe5cc5ee, kSettingsNotUse = 0xbe5cc5ec, }; OT_TOOL_PACKED_BEGIN struct settingsBlock { uint16_t key; uint16_t flag; uint16_t length; uint16_t reserved; } OT_TOOL_PACKED_END; /** * @def SETTINGS_CONFIG_BASE_ADDRESS * * The base address of settings. * */ #ifndef SETTINGS_CONFIG_BASE_ADDRESS #define SETTINGS_CONFIG_BASE_ADDRESS 0x39000 #endif // SETTINGS_CONFIG_BASE_ADDRESS /** * @def SETTINGS_CONFIG_PAGE_SIZE * * The page size of settings. * */ #ifndef SETTINGS_CONFIG_PAGE_SIZE #define SETTINGS_CONFIG_PAGE_SIZE 0x800 #endif // SETTINGS_CONFIG_PAGE_SIZE /** * @def SETTINGS_CONFIG_PAGE_NUM * * The page number of settings. * */ #ifndef SETTINGS_CONFIG_PAGE_NUM #define SETTINGS_CONFIG_PAGE_NUM 2 #endif // SETTINGS_CONFIG_PAGE_NUM static uint32_t sSettingsBaseAddress; static uint32_t sSettingsUsedSize; static uint16_t getAlignLength(uint16_t length) { return (length + 3) & 0xfffc; } static void setSettingsFlag(uint32_t aBase, uint32_t aFlag) { utilsFlashWrite(aBase, reinterpret_cast<uint8_t *>(&aFlag), sizeof(aFlag)); } static void initSettings(uint32_t aBase, uint32_t aFlag) { uint32_t address = aBase; uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ? SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 : SETTINGS_CONFIG_PAGE_SIZE; while (address < (aBase + settingsSize)) { utilsFlashErasePage(address); utilsFlashStatusWait(1000); address += SETTINGS_CONFIG_PAGE_SIZE; } setSettingsFlag(aBase, aFlag); } static uint32_t swapSettingsBlock(otInstance *aInstance) { uint32_t oldBase = sSettingsBaseAddress; uint32_t swapAddress = oldBase; uint32_t usedSize = sSettingsUsedSize; uint8_t pageNum = SETTINGS_CONFIG_PAGE_NUM; uint32_t settingsSize = pageNum > 1 ? SETTINGS_CONFIG_PAGE_SIZE * pageNum / 2 : SETTINGS_CONFIG_PAGE_SIZE; (void)aInstance; VerifyOrExit(pageNum > 1, ;); sSettingsBaseAddress = (swapAddress == SETTINGS_CONFIG_BASE_ADDRESS) ? (swapAddress + settingsSize) : SETTINGS_CONFIG_BASE_ADDRESS; initSettings(sSettingsBaseAddress, static_cast<uint32_t>(kSettingsInSwap)); sSettingsUsedSize = kSettingsFlagSize; swapAddress += kSettingsFlagSize; while (swapAddress < (oldBase + usedSize)) { OT_TOOL_PACKED_BEGIN struct addSettingsBlock { struct settingsBlock block; uint8_t data[kSettingsBlockDataSize]; } OT_TOOL_PACKED_END addBlock; bool valid = true; utilsFlashRead(swapAddress, reinterpret_cast<uint8_t *>(&addBlock.block), sizeof(struct settingsBlock)); swapAddress += sizeof(struct settingsBlock); if (!(addBlock.block.flag & kBlockAddCompleteFlag) && (addBlock.block.flag & kBlockDeleteFlag)) { uint32_t address = swapAddress + getAlignLength(addBlock.block.length); while (address < (oldBase + usedSize)) { struct settingsBlock block; utilsFlashRead(address, reinterpret_cast<uint8_t *>(&block), sizeof(block)); if (!(block.flag & kBlockAddCompleteFlag) && (block.flag & kBlockDeleteFlag) && !(block.flag & kBlockIndex0Flag) && (block.key == addBlock.block.key)) { valid = false; break; } address += (getAlignLength(block.length) + sizeof(struct settingsBlock)); } if (valid) { utilsFlashRead(swapAddress, addBlock.data, getAlignLength(addBlock.block.length)); utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize, reinterpret_cast<uint8_t *>(&addBlock), getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock)); sSettingsUsedSize += (sizeof(struct settingsBlock) + getAlignLength(addBlock.block.length)); } } else if (addBlock.block.flag == 0xff) { break; } swapAddress += getAlignLength(addBlock.block.length); } setSettingsFlag(sSettingsBaseAddress, static_cast<uint32_t>(kSettingsInUse)); setSettingsFlag(oldBase, static_cast<uint32_t>(kSettingsNotUse)); exit: return settingsSize - sSettingsUsedSize; } static ThreadError addSetting(otInstance *aInstance, uint16_t aKey, bool aIndex0, const uint8_t *aValue, uint16_t aValueLength) { ThreadError error = kThreadError_None; OT_TOOL_PACKED_BEGIN struct addSettingsBlock { struct settingsBlock block; uint8_t data[kSettingsBlockDataSize]; } OT_TOOL_PACKED_END addBlock; uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ? SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 : SETTINGS_CONFIG_PAGE_SIZE; addBlock.block.flag = 0xff; addBlock.block.key = aKey; if (aIndex0) { addBlock.block.flag &= (~kBlockIndex0Flag); } addBlock.block.flag &= (~kBlockAddBeginFlag); addBlock.block.length = aValueLength; if ((sSettingsUsedSize + getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock)) >= settingsSize) { VerifyOrExit(swapSettingsBlock(aInstance) >= (getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock)), error = kThreadError_NoBufs); } utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize, reinterpret_cast<uint8_t *>(&addBlock.block), sizeof(struct settingsBlock)); memset(addBlock.data, 0xff, kSettingsBlockDataSize); memcpy(addBlock.data, aValue, addBlock.block.length); utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize + sizeof(struct settingsBlock), reinterpret_cast<uint8_t *>(addBlock.data), getAlignLength(addBlock.block.length)); addBlock.block.flag &= (~kBlockAddCompleteFlag); utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize, reinterpret_cast<uint8_t *>(&addBlock.block), sizeof(struct settingsBlock)); sSettingsUsedSize += (sizeof(struct settingsBlock) + getAlignLength(addBlock.block.length)); exit: return error; } // settings API void otPlatSettingsInit(otInstance *aInstance) { uint8_t index; uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ? SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 : SETTINGS_CONFIG_PAGE_SIZE; (void)aInstance; sSettingsBaseAddress = SETTINGS_CONFIG_BASE_ADDRESS; utilsFlashInit(); for (index = 0; index < 2; index++) { uint32_t blockFlag; sSettingsBaseAddress += settingsSize * index; utilsFlashRead(sSettingsBaseAddress, reinterpret_cast<uint8_t *>(&blockFlag), sizeof(blockFlag)); if (blockFlag == kSettingsInUse) { break; } } if (index == 2) { initSettings(sSettingsBaseAddress, static_cast<uint32_t>(kSettingsInUse)); } sSettingsUsedSize = kSettingsFlagSize; while (sSettingsUsedSize < settingsSize) { struct settingsBlock block; utilsFlashRead(sSettingsBaseAddress + sSettingsUsedSize, reinterpret_cast<uint8_t *>(&block), sizeof(block)); if (!(block.flag & kBlockAddBeginFlag)) { sSettingsUsedSize += (getAlignLength(block.length) + sizeof(struct settingsBlock)); } else { break; } } } ThreadError otPlatSettingsBeginChange(otInstance *aInstance) { (void)aInstance; return kThreadError_None; } ThreadError otPlatSettingsCommitChange(otInstance *aInstance) { (void)aInstance; return kThreadError_None; } ThreadError otPlatSettingsAbandonChange(otInstance *aInstance) { (void)aInstance; return kThreadError_None; } ThreadError otPlatSettingsGet(otInstance *aInstance, uint16_t aKey, int aIndex, uint8_t *aValue, uint16_t *aValueLength) { ThreadError error = kThreadError_NotFound; uint32_t address = sSettingsBaseAddress + kSettingsFlagSize; int index = 0; (void)aInstance; while (address < (sSettingsBaseAddress + sSettingsUsedSize)) { struct settingsBlock block; utilsFlashRead(address, reinterpret_cast<uint8_t *>(&block), sizeof(block)); if (block.key == aKey) { if (!(block.flag & kBlockIndex0Flag)) { index = 0; } if (!(block.flag & kBlockAddCompleteFlag) && (block.flag & kBlockDeleteFlag)) { if (index == aIndex) { error = kThreadError_None; if (aValueLength) { *aValueLength = block.length; } if (aValue) { VerifyOrExit(aValueLength, error = kThreadError_InvalidArgs); utilsFlashRead(address + sizeof(struct settingsBlock), aValue, block.length); } } index++; } } address += (getAlignLength(block.length) + sizeof(struct settingsBlock)); } exit: return error; } ThreadError otPlatSettingsSet(otInstance *aInstance, uint16_t aKey, const uint8_t *aValue, uint16_t aValueLength) { return addSetting(aInstance, aKey, true, aValue, aValueLength); } ThreadError otPlatSettingsAdd(otInstance *aInstance, uint16_t aKey, const uint8_t *aValue, uint16_t aValueLength) { uint16_t length; bool index0; index0 = (otPlatSettingsGet(aInstance, aKey, 0, NULL, &length) == kThreadError_NotFound ? true : false); return addSetting(aInstance, aKey, index0, aValue, aValueLength); } ThreadError otPlatSettingsDelete(otInstance *aInstance, uint16_t aKey, int aIndex) { ThreadError error = kThreadError_NotFound; uint32_t address = sSettingsBaseAddress + kSettingsFlagSize; int index = 0; (void)aInstance; while (address < (sSettingsBaseAddress + sSettingsUsedSize)) { struct settingsBlock block; utilsFlashRead(address, reinterpret_cast<uint8_t *>(&block), sizeof(block)); if (block.key == aKey) { if (!(block.flag & kBlockIndex0Flag)) { index = 0; } if (!(block.flag & kBlockAddCompleteFlag) && (block.flag & kBlockDeleteFlag)) { if (aIndex == index || aIndex == -1) { error = kThreadError_None; block.flag &= (~kBlockDeleteFlag); utilsFlashWrite(address, reinterpret_cast<uint8_t *>(&block), sizeof(block)); } if (index == 1 && aIndex == 0) { block.flag &= (~kBlockIndex0Flag); utilsFlashWrite(address, reinterpret_cast<uint8_t *>(&block), sizeof(block)); } index++; } } address += (getAlignLength(block.length) + sizeof(struct settingsBlock)); } return error; } void otPlatSettingsWipe(otInstance *aInstance) { initSettings(sSettingsBaseAddress, static_cast<uint32_t>(kSettingsInUse)); otPlatSettingsInit(aInstance); } #ifdef __cplusplus }; #endif
30.453159
124
0.645443
mostafanfs
d2c6555ef3950ab04bf037f26f7c58a15c32538f
1,014
cpp
C++
Source/OpenTournament/OpenTournament.cpp
HAARP-art/OpenTournament
1bb188983ba4d013a8ce00bbe1a333f2952814e8
[ "OML" ]
97
2020-05-24T23:09:26.000Z
2022-01-22T13:35:58.000Z
Source/OpenTournament/OpenTournament.cpp
HAARP-art/OpenTournament
1bb188983ba4d013a8ce00bbe1a333f2952814e8
[ "OML" ]
165
2020-05-26T02:42:54.000Z
2022-03-29T11:01:11.000Z
Source/OpenTournament/OpenTournament.cpp
HAARP-art/OpenTournament
1bb188983ba4d013a8ce00bbe1a333f2952814e8
[ "OML" ]
78
2020-05-24T23:10:29.000Z
2022-03-14T13:54:09.000Z
// Copyright (c) 2019-2020 Open Tournament Project, All Rights Reserved. ///////////////////////////////////////////////////////////////////////////////////////////////// #include "OpenTournament.h" #include "Modules/ModuleManager.h" ///////////////////////////////////////////////////////////////////////////////////////////////// IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, OpenTournament, "OpenTournament" ); ///////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_LOG_CATEGORY(Game); DEFINE_LOG_CATEGORY(GameUI); DEFINE_LOG_CATEGORY(Net); DEFINE_LOG_CATEGORY(LogWeapon); ///////////////////////////////////////////////////////////////////////////////////////////////// FCollisionResponseParams WorldResponseParams = []() { FCollisionResponseParams Response(ECR_Ignore); Response.CollisionResponse.WorldStatic = ECR_Block; Response.CollisionResponse.WorldDynamic = ECR_Block; return Response; }();
34.965517
98
0.466469
HAARP-art
d2c83b39d7219d090d32fd1079c275a0d301ff43
357
hh
C++
c++/gtest_tryout/corba_proxy.hh
jdmichaud/snippets
1af85cf25156231165838b309860586f62bf43e2
[ "Apache-2.0" ]
null
null
null
c++/gtest_tryout/corba_proxy.hh
jdmichaud/snippets
1af85cf25156231165838b309860586f62bf43e2
[ "Apache-2.0" ]
null
null
null
c++/gtest_tryout/corba_proxy.hh
jdmichaud/snippets
1af85cf25156231165838b309860586f62bf43e2
[ "Apache-2.0" ]
null
null
null
#ifndef __CORBA_PROXY__ #define __CORBA_PROXY__ #include <iostream> class CorbaProxy { public: CorbaProxy() {} virtual ~CorbaProxy() {} virtual void corba_call_1(unsigned int i) { std::cout << "corba_call_1 " << i << std::endl; } virtual void corba_call_2() { std::cout << "corba_call_2" << std::endl; } }; #endif // __CORBA_PROXY__
17.85
51
0.661064
jdmichaud
d2cbdf2f76ae487e03495662b7b82b3948c23860
1,949
hh
C++
extern/polymesh/src/polymesh/attributes/fast_clear_attribute.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/polymesh/src/polymesh/attributes/fast_clear_attribute.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/polymesh/src/polymesh/attributes/fast_clear_attribute.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once #include <polymesh/attributes.hh> #include <polymesh/primitives.hh> namespace polymesh { template <class T, class tag, class gen_t = int> struct fast_clear_attribute; template <class T, class gen_t = int, class mesh_ptr, class tag, class iterator> fast_clear_attribute<T, tag, gen_t> make_fast_clear_attribute(smart_collection<mesh_ptr, tag, iterator> const& c, T const& clear_value = {}); /** * A wrapper around a pm::attribute that provides a O(1) clear operation * * Internally, each primitive holds a generation counter. * When accessing the attribute, the value is cleared in a lazy manner if the generation mismatches */ template <class T, class tag, class gen_t> struct fast_clear_attribute { using index_t = typename primitive<tag>::index; fast_clear_attribute(Mesh const& m, T const& clear_value) : _values(m), _clear_value(clear_value) {} void clear(T const& new_value = {}) { ++_gen; POLYMESH_ASSERT(_gen != 0 && "generation got wrapped around!"); _clear_value = new_value; } T& operator[](index_t i) { auto& e = _values[i]; if (e.gen != _gen) { e.value = _clear_value; e.gen = _gen; } return e.value; } T const& operator[](index_t i) const { auto const& e = _values[i]; return e.gen != _gen ? _clear_value : e.value; } T& operator()(index_t i) { return operator[](i); } T const& operator()(index_t i) const { return operator[](i); } private: struct entry { T value; gen_t gen = 0; }; primitive_attribute<tag, entry> _values; gen_t _gen = 1; T _clear_value; }; template <class T, class gen_t, class mesh_ptr, class tag, class iterator> fast_clear_attribute<T, tag, gen_t> make_fast_clear_attribute(smart_collection<mesh_ptr, tag, iterator> const& c, T const& clear_value) { return {c.mesh(), clear_value}; } }
27.842857
141
0.654182
rovedit
d2cc8c0bca403ffbe14591ae09841c606490bdb7
2,298
cpp
C++
src/application.qt.objectview/ObjectViewPlugin.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
src/application.qt.objectview/ObjectViewPlugin.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
src/application.qt.objectview/ObjectViewPlugin.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
#include "ObjectViewPlugin.h" #include <application.qt/PluginContainer.h> #include "ui_objectview.h" #include <application.qt/DataBinding.h> #include <core.utilities.h> using namespace std; using namespace nspace; void ObjectViewPlugin::objectDoubleClicked(QListWidgetItem * qobject){ auto data= qobject->data(Qt::UserRole); void * value =data.value<void*>(); Object * object = static_cast<Object*>(value); _objectPropertyView->setCurrentObject(object); } void ObjectViewPlugin::install(PluginContainer & container){ PluginWindow * window = new PluginWindow(); window->setWindowTitle(tr("Object View")); QWidget * w = new QWidget(); _ui= new Ui_ObjectView(); _ui->setupUi(w); _objectPropertyView = new ObjectPropertyView(); //QGridLayout * gridLayout = _ui->gridLayout; QSplitter * splitter = _ui->splitter; auto binding = new LineEditDataBinding(); binding->setSource(this); binding->setTarget(_ui->searchTextBox); binding->setPropertyName("SearchString"); //gridLayout->addWidget(_objectPropertyView,0,1,2,1); splitter->addWidget(_objectPropertyView); connect(_ui->listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)),this, SLOT(objectDoubleClicked(QListWidgetItem*))); window->setWidget(w); container.setPluginWindow(window); container.toggleWindow(true); } void ObjectViewPlugin::itemAdded(Object * , Objects){ } void ObjectViewPlugin::itemRemoved(Object * , Objects){ } void ObjectViewPlugin::onPropertyChanged(const std::string &name){ if(name!="SearchString"){return;} updateObjectList(); } void ObjectViewPlugin::updateListView(){ if(_ui)_ui->listWidget->clear(); Objects().foreachElement([this](Object * object){ string n = nspace::name(object); QListWidgetItem * item=new QListWidgetItem(tr(n.c_str())); QVariant variant = QVariant::fromValue<void*>(object); item->setData(Qt::UserRole,variant); if(_ui)_ui->listWidget->addItem(item); }); } void ObjectViewPlugin::updateObjectList(){ auto search = getSearchString(); if(search==""){ Objects()=*this; }else{ Objects()=subset([&search](Object * object){ return nspace::stringtools::containsIgnoreCase(nspace::name(object),search); }); } updateListView(); }
32.828571
124
0.707572
toeb
d2cff4f2cf7446839d32cb58f32ea78ce3b379d0
5,749
cpp
C++
PolarisEngine/src/Rendering/Camera.cpp
Delunado/PolarisEngine
9de5cb1a3c576f4908dae7b0122f6dd1dab0f7f1
[ "Apache-2.0" ]
2
2021-01-12T21:24:24.000Z
2021-02-19T15:06:23.000Z
PolarisEngine/src/Rendering/Camera.cpp
Delunado/PolarisEngine
9de5cb1a3c576f4908dae7b0122f6dd1dab0f7f1
[ "Apache-2.0" ]
2
2021-03-10T19:16:38.000Z
2021-12-01T22:47:13.000Z
PolarisEngine/src/Rendering/Camera.cpp
Delunado/PolarisEngine
9de5cb1a3c576f4908dae7b0122f6dd1dab0f7f1
[ "Apache-2.0" ]
null
null
null
#include <GL/glew.h> #include <iostream> #include <glm/glm.hpp> #include <glm/ext.hpp> #include <glm/gtc/matrix_transform.hpp> #include "Camera.h" namespace Render { Camera::Camera(glm::vec3 position, glm::vec3 lookAtPoint, GLfloat aspectRel) : position(position), lookAtPoint(lookAtPoint), aspectRel(aspectRel), worldUp(glm::vec3(0, 1, 0)), fovX(7.5f), zNear(0.1f), zFar(200.0f) { CalculateVisionAngle(); CalculateLocalVectors(); CalculateVisionMatrix(); CalculateProjectionMatrix(); } Camera::Camera(const Camera& other) { this->aspectRel = other.aspectRel; this->fovX = other.fovX; this->fovY = other.fovY; this->front = other.front; this->right = other.right; this->up = other.up; this->worldUp = other.worldUp; this->lookAtPoint = other.lookAtPoint; this->position = other.position; this->zFar = other.zFar; this->zNear = other.zNear; this->visionMatrix = other.visionMatrix; this->projectionMatrix = other.projectionMatrix; } Camera::~Camera() { } Camera* Camera::CreateCamera(glm::vec3 position, glm::vec3 lookAtPoint, GLfloat aspectRel) { Camera* camera = new Camera(position, lookAtPoint, aspectRel); return camera; } #pragma region CONTROL void Camera::Move(CAMERA_MOV_DIR movement, GLfloat speed) { glm::vec3 direction = glm::vec3(0.0f); switch (movement) { case CAMERA_MOV_DIR::FORWARD: direction = -front * speed; break; case CAMERA_MOV_DIR::RIGHTWARD: direction = right * speed; break; case CAMERA_MOV_DIR::UPWARD: direction = glm::vec3(0.0f, 1.0f, 0.0f) * speed; break; default: break; } glm::mat4 translation = glm::translate(glm::mat4(1.0f), direction); position = translation * glm::vec4(position, 1.0f); lookAtPoint = translation * glm::vec4(lookAtPoint, 1.0f); CalculateVisionMatrix(); } void Camera::Zoom(GLfloat zoom) { fovX -= zoom; fovX = glm::clamp(fovX, 0.01f, 2.0f); CalculateVisionAngle(); CalculateProjectionMatrix(); } void Camera::Rotate(GLfloat degreesX, GLfloat degreesY) { glm::mat4 rotationTilt = glm::rotate(glm::mat4(1.0f), glm::radians(degreesY), right); glm::mat4 rotationPan = glm::rotate(glm::mat4(1.0f), glm::radians(-degreesX), up); glm::mat4 transformation = glm::translate(glm::mat4(1.0f), position) * rotationTilt * rotationPan * glm::translate(glm::mat4(1.0f), -position); lookAtPoint = transformation * glm::vec4(lookAtPoint, 1.0f); CalculateLocalVectors(); CalculateVisionMatrix(); } void Camera::RotateAround(GLfloat degreesX, GLfloat degreesY, glm::vec3 rotationPoint) { glm::mat4 rotationMatrixX = glm::rotate(glm::mat4(1.0f), glm::radians(degreesX), glm::normalize(up)); glm::mat4 rotationMatrixY = glm::rotate(glm::mat4(1.0f), glm::radians(degreesY), glm::normalize(right)); glm::mat4 transformation = glm::translate(glm::mat4(1.0f), rotationPoint) * rotationMatrixY * rotationMatrixX * glm::translate(glm::mat4(1.0f), -rotationPoint); position = transformation * glm::vec4(position, 1.0f); CalculateLocalVectors(); CalculateVisionMatrix(); } #pragma endregion #pragma region GETTERS glm::vec3 Camera::GetPosition() { return position; } glm::vec3 Camera::GetLookAtPoint() { return lookAtPoint; } glm::vec3 Camera::GetWorldUp() { return worldUp; } glm::vec3 Camera::GetFront() { return front; } glm::vec3 Camera::GetRight() { return right; } glm::vec3 Camera::GetUp() { return up; } GLfloat Camera::GetFieldOfViewY() { return fovY; } GLfloat Camera::GetFieldOfViewX() { return fovX; } GLfloat Camera::GetZNear() { return zNear; } GLfloat Camera::GetZFar() { return zFar; } glm::mat4 Camera::GetVisionMatrix() { return visionMatrix; } glm::mat4 Camera::GetProjectionMatrix() { return projectionMatrix; } GLfloat Camera::GetAspectRel() { return aspectRel; } #pragma endregion #pragma region SETTERS void Camera::SetPosition(glm::vec3 position) { this->position = position; CalculateLocalVectors(); CalculateVisionMatrix(); } void Camera::SetLookAtPoint(glm::vec3 lookAtPoint) { this->lookAtPoint = lookAtPoint; CalculateLocalVectors(); CalculateVisionMatrix(); } void Camera::SetWorldUp(glm::vec3 worldUp) { this->worldUp = worldUp; CalculateLocalVectors(); CalculateVisionMatrix(); } void Camera::SetFieldOfViewX(GLfloat fovX) { this->fovX = fovX; CalculateVisionAngle(); CalculateProjectionMatrix(); } void Camera::SetFieldOfViewY(GLfloat fovY) { this->fovY = fovY; CalculateProjectionMatrix(); } void Camera::SetZNear(GLfloat zNear) { this->zNear = zNear; CalculateProjectionMatrix(); } void Camera::SetZFar(GLfloat zFar) { this->zFar = zFar; CalculateProjectionMatrix(); } void Camera::SetAspectRel(GLfloat aspecRel) { this->aspectRel = aspecRel; CalculateProjectionMatrix(); } #pragma endregion #pragma region CALCULATIONS void Camera::CalculateVisionAngle() { fovY = 2 * glm::atan(glm::tan(fovX / 2) / aspectRel); } void Camera::CalculateLocalVectors() { front = -glm::normalize((lookAtPoint - position)); right = glm::normalize(glm::cross(VectorUp(), front)); up = glm::normalize(glm::cross(front, right)); } void Camera::CalculateVisionMatrix() { visionMatrix = glm::lookAt(position, lookAtPoint, up); } void Camera::CalculateProjectionMatrix() { projectionMatrix = glm::perspective(fovY, aspectRel, zNear, zFar); } glm::vec3 Camera::VectorUp() { glm::vec3 currentUp = worldUp; if (glm::all(glm::epsilonEqual(front, worldUp, 0.001f))) currentUp = glm::vec3(0, 0, 1); else if (glm::all(glm::epsilonEqual(front, -worldUp, 0.001f))) currentUp = glm::vec3(0, 0, -1); return currentUp; } #pragma endregion }
21.214022
162
0.69299
Delunado
d2d1b51c836e4bc7fac9141910f2eb66fcc9d4d9
733
cpp
C++
class/inheritance.cpp
learnMachining/cplus2test
8cc0048627724bb967f27d5cd9860dbb5804a7d9
[ "Apache-2.0" ]
null
null
null
class/inheritance.cpp
learnMachining/cplus2test
8cc0048627724bb967f27d5cd9860dbb5804a7d9
[ "Apache-2.0" ]
null
null
null
class/inheritance.cpp
learnMachining/cplus2test
8cc0048627724bb967f27d5cd9860dbb5804a7d9
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <time.h> using namespace std; class B0 { public: B0(int n) { nV = n; cout<<"constructing B0"<<endl; } int nV; void fun() { cout<<"member of B0 "<<nV<<endl; } }; class B1:virtual public B0 { public: B1(int a):B0(a) { cout<<"constructing B1"<<endl; } int nV1; }; class B2:virtual public B0 { public: B2(int a):B0(a) { cout<<"constructing B2"<<endl; } int nV2; }; class D1:public B1, public B2 { public: D1(int a):B0(a), B1(a), B2(a) { } int nVd; void fund() { cout<<"member of D1"<<endl; } }; int main() { D1 d1(1); d1.fun(); d1.nV = 2; d1.fun(); return 0; }
11.822581
40
0.491132
learnMachining
d2d85d784771d7da94b3474e8be152c7dbed7b53
3,063
cpp
C++
project-code/PictureDecoder/Slice/Slice.cpp
Bho007/MPEG-2-TS-Decoder
6021af80f9a79b241da1db158b87ed3fe53f8e61
[ "MIT" ]
null
null
null
project-code/PictureDecoder/Slice/Slice.cpp
Bho007/MPEG-2-TS-Decoder
6021af80f9a79b241da1db158b87ed3fe53f8e61
[ "MIT" ]
null
null
null
project-code/PictureDecoder/Slice/Slice.cpp
Bho007/MPEG-2-TS-Decoder
6021af80f9a79b241da1db158b87ed3fe53f8e61
[ "MIT" ]
null
null
null
// // Created by elnsa on 2019-12-29. // #include "Slice.h" Slice::Slice(Slice::initializerStruct init) { stream_id = init.stream_id; packet_type = ESPacket::start_code::slice; slice_vertical_position_extension = init.slice_vertical_position_extension; quantiser_scale_code = init.quantiser_scale_code; slice_extension_flag = init.slice_extension_flag; intra_slice = init.intra_slice; slice_picture_id_enable = init.slice_picture_id_enable; slice_picture_id = init.slice_picture_id; numMacroblocks = init.numMacroblocks; macroblocks = init.macroblocks; } void Slice::print() { printf("Slice: id = %hhx, vpe = %hhu, qsc = %hhu, sef = %hhu, is = %hhu, spide = %hhu, spid = %hhu, numMacroblocks = %u\n", stream_id, slice_vertical_position_extension, quantiser_scale_code, slice_extension_flag, intra_slice, slice_picture_id_enable, slice_picture_id, numMacroblocks); // for (size_t i = 0; i < numMacroblocks; i++) { // macroblocks[i].print(); // } } bool Slice::operator==(const Slice &rhs) const { bool eq = stream_id == rhs.stream_id && packet_type == rhs.packet_type && slice_vertical_position_extension == rhs.slice_vertical_position_extension && quantiser_scale_code == rhs.quantiser_scale_code && slice_extension_flag == rhs.slice_extension_flag && intra_slice == rhs.intra_slice && slice_picture_id_enable == rhs.slice_picture_id && slice_picture_id == rhs.slice_picture_id && numMacroblocks == rhs.numMacroblocks; if (!eq)return eq; for (int i = 0; i < numMacroblocks; i++) { if (*macroblocks[i] != *rhs.macroblocks[i])return false; } return true; } bool Slice::operator!=(const Slice &rhs) const { return !(rhs == *this); } Slice::~Slice() { for (int i = 0; i < numMacroblocks; i++) { delete (macroblocks[i]); } } unsigned int Slice::getNumMacroblocks() const { return numMacroblocks; } void Slice::setNumMacroblocks(unsigned int num) { numMacroblocks = num; } Macroblock **Slice::getMacroblocks() const { return macroblocks; } void Slice::setMacroblocks(Macroblock **m) { macroblocks = m; } unsigned char Slice::getQuantiserScaleCode() const { return quantiser_scale_code; } /** * This function only handles chroma format 4:2:0 */ void Slice::insertZeroVectorMacroblock(size_t index) { Macroblock::initializerStruct init = {}; init.forwardMotionVectors = MotionVectors::buildZeroVectors(0); // NOLINT(modernize-use-bool-literals) init.block_count = 6; init.macroBlockModes = new MacroblockModes(MacroblockModes::initializerStruct{false, true}); init.macroBlockModes->setFrameMotionType(0b10); numMacroblocks++; macroblocks = (Macroblock **) realloc(macroblocks, sizeof(void *) * numMacroblocks); for (size_t i = numMacroblocks - 2; i >= index; i--) { macroblocks[i + 1] = macroblocks[i]; } macroblocks[index] = new Macroblock(init); }
33.293478
127
0.677114
Bho007
d2d9c93538a0b3c819e97e696dfa2d7d54d06e05
3,307
cpp
C++
src/betomnita/gameplay/Vehicle.cpp
bilbosz/Betomnita
23c4679a591bc64c40193fe0e661f35eec85f1b7
[ "MIT" ]
null
null
null
src/betomnita/gameplay/Vehicle.cpp
bilbosz/Betomnita
23c4679a591bc64c40193fe0e661f35eec85f1b7
[ "MIT" ]
1
2018-04-14T08:12:58.000Z
2018-04-14T08:12:58.000Z
src/betomnita/gameplay/Vehicle.cpp
bilbosz/Betomnita
23c4679a591bc64c40193fe0e661f35eec85f1b7
[ "MIT" ]
null
null
null
#include "betomnita/gameplay/Vehicle.hpp" #include "betomnita/gameplay/GamePlayLogic.hpp" #include "betomnita/gameplay/Projectile.hpp" #include "betomnita/gameplay/ProjectilePrototype.hpp" #include "betomnita/gameplay/PrototypeDict.hpp" #include "betomnita/gameplay/World.hpp" #include "game/utils/Utils.hpp" namespace Betomnita::GamePlay { Vehicle::Vehicle() { } void Vehicle::InitPhysics() { Chassis.InitPhysics(); Gun.InitPhysics(); } void Vehicle::Render( sf::RenderTarget& target, const sf::Transform& transform ) { Chassis.Render( target, transform ); Gun.Render( target, transform ); } void Vehicle::Update( const sf::Time& dt ) { if( m_id == 1 ) { auto physicalBody = Chassis.GetPhysicalBody(); float impulse = 370'000.0f * dt.asSeconds(); auto angle = physicalBody->GetAngle() + Game::Consts::Pi * 0.5f; if( sf::Keyboard::isKeyPressed( sf::Keyboard::W ) ) { physicalBody->ApplyLinearImpulseToCenter( b2Vec2( -impulse * cosf( angle ), -impulse * sinf( angle ) ), true ); } if( sf::Keyboard::isKeyPressed( sf::Keyboard::S ) ) { physicalBody->ApplyLinearImpulseToCenter( b2Vec2( impulse * cosf( angle ), impulse * sinf( angle ) ), true ); } if( sf::Keyboard::isKeyPressed( sf::Keyboard::A ) ) { physicalBody->ApplyAngularImpulse( -impulse, true ); } if( sf::Keyboard::isKeyPressed( sf::Keyboard::D ) ) { physicalBody->ApplyAngularImpulse( impulse, true ); } if( sf::Keyboard::isKeyPressed( sf::Keyboard::Num0 ) ) { physicalBody->SetAngularVelocity( 0.0f ); physicalBody->SetLinearVelocity( b2Vec2( 0.0f, 0.0f ) ); } if( sf::Keyboard::isKeyPressed( sf::Keyboard::Left ) ) { Gun.SetDirection( Gun.GetDirection() - 1.0f * dt.asSeconds() ); } if( sf::Keyboard::isKeyPressed( sf::Keyboard::Right ) ) { Gun.SetDirection( Gun.GetDirection() + 1.0f * dt.asSeconds() ); } } Chassis.Update( dt ); Gun.Update( dt ); } void Vehicle::Shot() { auto projectile = World->AddProjectile( std::make_unique< Projectile >() ); projectile->LoadFromPrototype( World->GetCurrentLogic()->GetPrototypeDict().GetPrototypeByName( "res/vehicles/projectiles/armor-piercing.svg" ) ); projectile->AssignShooter( this ); projectile->World = World; float angle = Chassis.GetPhysicalBody()->GetAngle() + Gun.GetDirection(); float impulse = 4'000.0f; sf::Transform t; t.rotate( angle * Game::Consts::RadToDeg ); projectile->SetInitialPosition( Gun.GetShotDirection().Destination - t.transformPoint( projectile->GetShotDirection().Source ) ); projectile->SetInitialAngle( angle ); projectile->InitPhysics(); angle += Game::Consts::Pi * 0.5f; projectile->GetPhysicalBody()->ApplyLinearImpulseToCenter( b2Vec2( -impulse * cosf( angle ), -impulse * sinf( angle ) ), true ); } }
36.340659
154
0.580284
bilbosz
d2dcd4c2633801db322269d367ba024fb961ad47
384
cpp
C++
string_array/string_array/main.cpp
silentShadow/C-plus-plus
fb0108beb83f69d0c207f75dc29fae8c1657121c
[ "MIT" ]
null
null
null
string_array/string_array/main.cpp
silentShadow/C-plus-plus
fb0108beb83f69d0c207f75dc29fae8c1657121c
[ "MIT" ]
null
null
null
string_array/string_array/main.cpp
silentShadow/C-plus-plus
fb0108beb83f69d0c207f75dc29fae8c1657121c
[ "MIT" ]
null
null
null
// // main.cpp // string_array // // Created by Jonathan Reiter on 6/3/16. // Copyright © 2016 Jonathan Reiter. All rights reserved. // #include <iostream> #include <string> using namespace std; int main() { string members[] = {"Jonny", "Paul", "Ben", "Ringo"}; for (int i = 0; i < 4; i++) { cout << members[i] << " " << endl; } return 0; }
15.36
58
0.541667
silentShadow
d2df115b253d364d5896a77c6d1692ca58081a1d
8,957
cpp
C++
track_odometry/test/src/test_track_odometry.cpp
fangzheng81/neonavigation
1251ac6dfcb7fa102a21925863ff930a3fc03111
[ "BSD-3-Clause" ]
1
2019-09-26T01:13:02.000Z
2019-09-26T01:13:02.000Z
track_odometry/test/src/test_track_odometry.cpp
DiaS-77/neonavigation
486e0b34d0c5601e3a8517c71ba329535e641b6b
[ "BSD-3-Clause" ]
null
null
null
track_odometry/test/src/test_track_odometry.cpp
DiaS-77/neonavigation
486e0b34d0c5601e3a8517c71ba329535e641b6b
[ "BSD-3-Clause" ]
2
2019-10-05T12:27:54.000Z
2020-07-23T10:42:47.000Z
/* * Copyright (c) 2018-2019, the neonavigation authors * 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. */ #include <string> #include <vector> #include <ros/ros.h> #include <nav_msgs/Odometry.h> #include <sensor_msgs/Imu.h> #include <tf2/utils.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <gtest/gtest.h> class TrackOdometryTest : public ::testing::TestWithParam<const char*> { protected: std::vector<nav_msgs::Odometry> odom_msg_buffer_; public: void initializeNode(const std::string& ns) { ros::NodeHandle nh(ns); pub_odom_ = nh.advertise<nav_msgs::Odometry>("odom_raw", 10); pub_imu_ = nh.advertise<sensor_msgs::Imu>("imu/data", 10); sub_odom_ = nh.subscribe("odom", 10, &TrackOdometryTest::cbOdom, this); } bool initializeTrackOdometry( nav_msgs::Odometry& odom_raw, sensor_msgs::Imu& imu) { ros::Duration(0.1).sleep(); ros::Rate rate(100); odom_ = nullptr; for (int i = 0; i < 100 && ros::ok(); ++i) { odom_raw.header.stamp = ros::Time::now(); imu.header.stamp = odom_raw.header.stamp + ros::Duration(0.0001); pub_odom_.publish(odom_raw); pub_imu_.publish(imu); rate.sleep(); ros::spinOnce(); if (odom_ && i > 50) break; } return static_cast<bool>(odom_); } bool run( nav_msgs::Odometry& odom_raw, sensor_msgs::Imu& imu, const float dt, const int steps) { ros::Rate rate(1.0 / dt); int cnt(0); while (ros::ok()) { tf2::Quaternion quat_odom; tf2::fromMsg(odom_raw.pose.pose.orientation, quat_odom); odom_raw.pose.pose.orientation = tf2::toMsg( quat_odom * tf2::Quaternion(tf2::Vector3(0.0, 0.0, 1.0), dt * odom_raw.twist.twist.angular.z)); tf2::Quaternion quat_imu; tf2::fromMsg(imu.orientation, quat_imu); imu.orientation = tf2::toMsg( quat_imu * tf2::Quaternion(tf2::Vector3(0.0, 0.0, 1.0), dt * imu.angular_velocity.z)); const double yaw = tf2::getYaw(odom_raw.pose.pose.orientation); odom_raw.pose.pose.position.x += cos(yaw) * dt * odom_raw.twist.twist.linear.x; odom_raw.pose.pose.position.y += sin(yaw) * dt * odom_raw.twist.twist.linear.x; stepAndPublish(odom_raw, imu, dt); rate.sleep(); ros::spinOnce(); if (++cnt >= steps) break; } flushOdomMsgs(); return ros::ok(); } void stepAndPublish( nav_msgs::Odometry& odom_raw, sensor_msgs::Imu& imu, const float dt) { odom_raw.header.stamp += ros::Duration(dt); imu.header.stamp += ros::Duration(dt); pub_imu_.publish(imu); // Buffer odom message to add delay and jitter. // Send odometry in half rate of IMU. ++odom_cnt_; if (odom_cnt_ % 2 == 0) odom_msg_buffer_.push_back(odom_raw); if (odom_msg_buffer_.size() > 10) { flushOdomMsgs(); } } void flushOdomMsgs() { for (nav_msgs::Odometry& o : odom_msg_buffer_) { pub_odom_.publish(o); } odom_msg_buffer_.clear(); } void waitAndSpinOnce() { ros::Duration(0.1).sleep(); ros::spinOnce(); } protected: ros::Publisher pub_odom_; ros::Publisher pub_imu_; ros::Subscriber sub_odom_; nav_msgs::Odometry::ConstPtr odom_; size_t odom_cnt_; void cbOdom(const nav_msgs::Odometry::ConstPtr& msg) { odom_ = msg; }; }; TEST_F(TrackOdometryTest, OdomImuFusion) { initializeNode(""); const float dt = 0.01; const int steps = 200; nav_msgs::Odometry odom_raw; odom_raw.header.frame_id = "odom"; odom_raw.pose.pose.orientation.w = 1; sensor_msgs::Imu imu; imu.header.frame_id = "base_link"; imu.orientation.w = 1; imu.linear_acceleration.z = 9.8; ASSERT_TRUE(initializeTrackOdometry(odom_raw, imu)); // Go forward for 1m odom_raw.twist.twist.linear.x = 0.5; ASSERT_TRUE(run(odom_raw, imu, dt, steps)); odom_raw.twist.twist.linear.x = 0.0; stepAndPublish(odom_raw, imu, dt); flushOdomMsgs(); waitAndSpinOnce(); ASSERT_NEAR(odom_->pose.pose.position.x, 1.0, 1e-3); ASSERT_NEAR(odom_->pose.pose.position.y, 0.0, 1e-3); ASSERT_NEAR(odom_->pose.pose.position.z, 0.0, 1e-3); ASSERT_NEAR(tf2::getYaw(odom_->pose.pose.orientation), 0.0, 1e-3); // Turn 90 degrees with 10% of odometry errors imu.angular_velocity.z = M_PI * 0.25; odom_raw.twist.twist.angular.z = imu.angular_velocity.z * 1.1; // Odometry with error ASSERT_TRUE(run(odom_raw, imu, dt, steps)); imu.angular_velocity.z = 0; odom_raw.twist.twist.angular.z = 0; imu.orientation = tf2::toMsg(tf2::Quaternion(tf2::Vector3(0.0, 0.0, 1.0), M_PI / 2)); stepAndPublish(odom_raw, imu, dt); flushOdomMsgs(); waitAndSpinOnce(); ASSERT_NEAR(odom_->pose.pose.position.x, 1.0, 1e-2); ASSERT_NEAR(odom_->pose.pose.position.y, 0.0, 1e-2); ASSERT_NEAR(odom_->pose.pose.position.z, 0.0, 1e-2); ASSERT_NEAR(tf2::getYaw(odom_->pose.pose.orientation), M_PI / 2, 1e-2); // Go forward for 1m odom_raw.twist.twist.linear.x = 0.5; ASSERT_TRUE(run(odom_raw, imu, dt, steps)); odom_raw.twist.twist.linear.x = 0.0; stepAndPublish(odom_raw, imu, dt); flushOdomMsgs(); waitAndSpinOnce(); ASSERT_NEAR(odom_->pose.pose.position.x, 1.0, 5e-2); ASSERT_NEAR(odom_->pose.pose.position.y, 1.0, 5e-2); ASSERT_NEAR(odom_->pose.pose.position.z, 0.0, 5e-2); ASSERT_NEAR(tf2::getYaw(odom_->pose.pose.orientation), M_PI / 2, 1e-2); } TEST_P(TrackOdometryTest, ZFilterOff) { const std::string ns_postfix(GetParam()); initializeNode("no_z_filter" + ns_postfix); const float dt = 0.01; const int steps = 200; nav_msgs::Odometry odom_raw; odom_raw.header.frame_id = "odom"; odom_raw.pose.pose.orientation.w = 1; sensor_msgs::Imu imu; imu.header.frame_id = "base_link"; imu.orientation.y = sin(-M_PI / 4); imu.orientation.w = cos(-M_PI / 4); imu.linear_acceleration.x = -9.8; ASSERT_TRUE(initializeTrackOdometry(odom_raw, imu)); // Go forward for 1m odom_raw.twist.twist.linear.x = 0.5; ASSERT_TRUE(run(odom_raw, imu, dt, steps)); odom_raw.twist.twist.linear.x = 0.0; stepAndPublish(odom_raw, imu, dt); flushOdomMsgs(); waitAndSpinOnce(); ASSERT_NEAR(odom_->pose.pose.position.x, 0.0, 1e-3); ASSERT_NEAR(odom_->pose.pose.position.y, 0.0, 1e-3); ASSERT_NEAR(odom_->pose.pose.position.z, 1.0, 1e-3); } TEST_P(TrackOdometryTest, ZFilterOn) { const std::string ns_postfix(GetParam()); initializeNode("z_filter" + ns_postfix); const float dt = 0.01; const int steps = 200; nav_msgs::Odometry odom_raw; odom_raw.header.frame_id = "odom"; odom_raw.pose.pose.orientation.w = 1; sensor_msgs::Imu imu; imu.header.frame_id = "base_link"; imu.orientation.y = sin(-M_PI / 4); imu.orientation.w = cos(-M_PI / 4); imu.linear_acceleration.x = -9.8; ASSERT_TRUE(initializeTrackOdometry(odom_raw, imu)); // Go forward for 1m odom_raw.twist.twist.linear.x = 0.5; ASSERT_TRUE(run(odom_raw, imu, dt, steps)); odom_raw.twist.twist.linear.x = 0.0; stepAndPublish(odom_raw, imu, dt); flushOdomMsgs(); waitAndSpinOnce(); ASSERT_NEAR(odom_->pose.pose.position.z, 1.0 - 1.0 / M_E, 5e-2); } INSTANTIATE_TEST_CASE_P( TrackOdometryTestInstance, TrackOdometryTest, ::testing::Values("", "_old_param")); int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "test_track_odometry"); return RUN_ALL_TESTS(); }
30.057047
97
0.67824
fangzheng81
d2e326ff3d07283e34d6306577e70363005bcd0e
122
cpp
C++
code/engine.vc2008/xrManagedEngineLib/CallbackTypes.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/engine.vc2008/xrManagedEngineLib/CallbackTypes.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/engine.vc2008/xrManagedEngineLib/CallbackTypes.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
3
2020-10-12T18:04:42.000Z
2020-10-12T18:04:59.000Z
#include "stdafx.h" #include "FunctionInvoker.h" FunctionInvoker<unsigned int> Shedule_Update_Invoker("shedule_update");
24.4
71
0.811475
Rikoshet-234
5e4865e4ce97666c6f0b4d7ad91dd0e387932c87
3,077
cpp
C++
src/cosmoscout/main.cpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
src/cosmoscout/main.cpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
src/cosmoscout/main.cpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of CosmoScout VR // // and may be used under the terms of the MIT license. See the LICENSE file for details. // // Copyright: (c) 2019 German Aerospace Center (DLR) // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "../cs-core/SolarSystem.hpp" #include "../cs-gui/gui.hpp" #include "../cs-utils/CommandLine.hpp" #include "Application.hpp" #include <VistaOGLExt/VistaShaderRegistry.h> //////////////////////////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { // launch gui child processes cs::gui::executeChildProcess(argc, argv); // parse program options std::string settingsFile = "../share/config/simple_desktop.json"; bool printHelp = false; bool printVistaHelp = false; // First configure all possible command line options. cs::utils::CommandLine args("Welcome to CosmoScout VR! Here are the available options:"); args.addArgument({"-s", "--settings"}, &settingsFile, "JSON file containing settings (default: " + settingsFile + ")"); args.addArgument({"-h", "--help"}, &printHelp, "Print this help."); args.addArgument({"-v", "--vistahelp"}, &printVistaHelp, "Print help for vista options."); // The do the actual parsing. try { args.parse(argc, argv); } catch (std::runtime_error const& e) { std::cout << e.what() << std::endl; return -1; } // When printHelp was set to true, we print a help message and exit. if (printHelp) { args.printHelp(); return 0; } // When printVistaHelp was set to true, we print a help message and exit. if (printVistaHelp) { VistaSystem::ArgHelpMsg(argv[0], &std::cout); return 0; } // read settings cs::core::Settings settings; try { settings = cs::core::Settings::read(settingsFile); } catch (std::exception& e) { std::cerr << "Failed to read settings: " << e.what() << std::endl; return 1; } // start application try { std::list<std::string> liSearchPath; liSearchPath.emplace_back("../share/config/vista"); VistaShaderRegistry::GetInstance().AddSearchDirectory("../share/resources/shaders"); auto pVistaSystem = new VistaSystem(); pVistaSystem->SetIniSearchPaths(liSearchPath); cs::core::SolarSystem::init(settings.mSpiceKernel); Application app(settings); pVistaSystem->SetFrameLoop(&app, true); if (pVistaSystem->Init(argc, argv)) { pVistaSystem->Run(); } cs::core::SolarSystem::cleanup(); } catch (VistaExceptionBase& e) { e.PrintException(); return 1; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; return 1; } return 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////
33.086022
100
0.542411
bernstein