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
108
| 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
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f23a61df028c4bc3fb7cfed62a551939ce5ec547
| 634
|
cpp
|
C++
|
Estrutura de Dados/Sorts/SelectionSort/Source.cpp
|
boveloco/Puc
|
cbc3308fac104098b030dadebdd036fe288bbe0c
|
[
"MIT"
] | null | null | null |
Estrutura de Dados/Sorts/SelectionSort/Source.cpp
|
boveloco/Puc
|
cbc3308fac104098b030dadebdd036fe288bbe0c
|
[
"MIT"
] | null | null | null |
Estrutura de Dados/Sorts/SelectionSort/Source.cpp
|
boveloco/Puc
|
cbc3308fac104098b030dadebdd036fe288bbe0c
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Array.h"
#include "SelectionSort.h"
#include "Inimigos.h"
#include <iostream>
int compararEnergiaInimigos(Inimigos a, Inimigos b);
int main(){
Array<Inimigos> numbs(5);
numbs[0].energia = 13;
numbs[1].energia = 30;
numbs[2].energia = 20;
numbs[3].energia = 10;
numbs[4].energia = 5;
selectionSort<Inimigos>(numbs, compararEnergiaInimigos);
for (int i = 0; i < numbs.Size(); i++){
std::cout << "Numb: " << i << " " << numbs[i].energia << std::endl;
}
system("PAUSE");
return 1;
}
int compararEnergiaInimigos(Inimigos a, Inimigos b){
if (a.energia > b.energia)
return 1;
else
return 0;
}
| 19.212121
| 69
| 0.657729
|
boveloco
|
f2413268101c11fe61c3d43e27f20111c77f31f4
| 5,553
|
cpp
|
C++
|
04_Sample/TowerDefence/Source/Tower.cpp
|
mcodegeeks/OpenKODE-Framework
|
d4382d781da7f488a0e7667362a89e8e389468dd
|
[
"MIT"
] | 2
|
2017-08-03T07:15:00.000Z
|
2018-06-18T10:32:53.000Z
|
04_Sample/TowerDefence/Source/Tower.cpp
|
mcodegeeks/OpenKODE-Framework
|
d4382d781da7f488a0e7667362a89e8e389468dd
|
[
"MIT"
] | null | null | null |
04_Sample/TowerDefence/Source/Tower.cpp
|
mcodegeeks/OpenKODE-Framework
|
d4382d781da7f488a0e7667362a89e8e389468dd
|
[
"MIT"
] | 2
|
2019-03-04T22:57:42.000Z
|
2020-03-06T01:32:26.000Z
|
/* --------------------------------------------------------------------------
*
* File Tower.cpp
* Description
*
* Ported By Young-Hwan Mun
* Contact xmsoft77@gmail.com
*
* Created By Kirill Muzykov on 8/22/13.
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft. All rights reserved.
*
* --------------------------------------------------------------------------
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* -------------------------------------------------------------------------- */
#include "Precompiled.h"
#include "Tower.h"
#include "Enemy.h"
#include "GameLayer.h"
Tower* Tower::create ( const KDchar* szFileName )
{
Tower* pRet = new Tower ( );
if ( pRet && pRet->initWithFile ( szFileName ) )
{
pRet->autorelease ( );
}
else
{
CC_SAFE_DELETE ( pRet );
}
return pRet;
}
KDbool Tower::initWithTexture ( CCTexture2D* pTexture, const CCRect& tRect, KDbool bRotated )
{
if ( !CCSprite::initWithTexture ( pTexture, tRect, bRotated ) )
{
return KD_FALSE;
}
m_fAttackRange = 70;
m_nDamage = 10;
m_fFireRate = 1.0f;
m_pTheGame = KD_NULL;
m_pChosenEnemy = KD_NULL;
this->scheduleUpdate ( );
return KD_TRUE;
}
KDvoid Tower::draw ( KDvoid )
{
// Uncomment to draw attack range circle. For debug purpose only.
CCPoint tPos = CCNode::convertToNodeSpace ( this->getPosition ( ) );
ccDrawColor4B ( 128, 0, 0, 128 );
ccDrawCircle ( tPos, m_fAttackRange, KD_DEG2RAD ( -90 ), 30, KD_TRUE );
CCSprite::draw ( );
}
KDvoid Tower::update ( KDfloat fDelta )
{
CCAssert ( m_pTheGame != NULL, "You should set the game for Tower" );
if ( m_pChosenEnemy )
{
// Finding normalized vector enemy -> tower to calculate angle we should turn tower,
CCPoint tEnemyPos = m_pChosenEnemy->getPosition ( );
CCPoint tMyPos = this->getPosition ( );
CCPoint tNormalized = ccpNormalize ( ccpSub ( tEnemyPos, tMyPos ) );
// Turning tower to face the enemy.
KDfloat fAngle = CC_RADIANS_TO_DEGREES ( kdAtan2f ( tNormalized.y, -tNormalized.x ) ) + 90;
this->setRotation ( fAngle );
// Checking if enemy is still in attack range.
if ( !m_pTheGame->checkCirclesCollide ( this->getPosition ( ), m_fAttackRange, m_pChosenEnemy->getPosition ( ), 1.0f ) )
{
this->lostSightOfEnemy ( );
}
}
else
{
// Currently we're not attaching anyone. Let's look if there are any enemies in our attack range.
CCObject* pObject;
CCARRAY_FOREACH ( &m_pTheGame->getEnemies ( ), pObject )
{
Enemy* pEnemy = (Enemy*) pObject;
if ( m_pTheGame->checkCirclesCollide ( this->getPosition ( ), m_fAttackRange, pEnemy->getPosition ( ), 1.0f ) )
{
// Found enemy in range. Attacking.
this->chosenEnemyForAttack ( pEnemy );
break;
}
}
}
}
KDvoid Tower::chosenEnemyForAttack ( Enemy* pEnemy )
{
m_pChosenEnemy = pEnemy;
this->attackEnemy ( );
pEnemy->getAttacked ( this );
}
KDvoid Tower::attackEnemy ( KDvoid )
{
this->schedule ( schedule_selector ( Tower::shootWeapon ), m_fFireRate );
}
KDvoid Tower::shootWeapon ( KDfloat fDelta )
{
CCAssert ( m_pTheGame != KD_NULL, "You should set the game for Tower" );
CCSprite* pBullet = CCSprite::create ( "bullet.png" );
pBullet->setPosition ( this->getPosition ( ) );
m_pTheGame->addChild ( pBullet );
// Bullet actions: Move from turret to enemy, then make some damage to enemy, and finally remove bullet sprite.
pBullet->runAction
(
CCSequence::create
(
CCMoveTo::create ( 0.1f, m_pChosenEnemy->getPosition ( ) ),
CCCallFunc::create ( this, callfunc_selector ( Tower::damageEnemy ) ),
CCCallFuncN::create ( this, callfuncN_selector ( Tower::removeBullet ) ),
KD_NULL
)
);
}
KDvoid Tower::damageEnemy ( KDvoid )
{
if ( m_pChosenEnemy )
{
m_pChosenEnemy->getDamaged ( m_nDamage );
}
}
KDvoid Tower::removeBullet ( CCNode* pBullet )
{
pBullet->removeFromParentAndCleanup ( KD_TRUE );
}
KDvoid Tower::lostSightOfEnemy ( KDvoid )
{
if ( m_pChosenEnemy )
{
m_pChosenEnemy->gotLostSight ( this );
m_pChosenEnemy = KD_NULL;
}
this->unschedule ( schedule_selector ( Tower::shootWeapon ) );
}
KDvoid Tower::setTheGame ( GameLayer* pGame )
{
m_pTheGame = pGame;
}
KDvoid Tower::targetKilled ( KDvoid )
{
m_pChosenEnemy = KD_NULL;
this->unschedule ( schedule_selector ( Tower::shootWeapon ) );
}
| 29.073298
| 128
| 0.591572
|
mcodegeeks
|
f2460ca1daec1f6e64ac04dc64574fc70288c57d
| 2,121
|
hpp
|
C++
|
include/open-bo-api-crc64.hpp
|
sokoliko/open-bo-api
|
ddcad19163532543ad13a0398f0b0119e55d4c3d
|
[
"MIT"
] | 6
|
2020-02-09T06:40:03.000Z
|
2021-09-08T09:38:19.000Z
|
include/open-bo-api-crc64.hpp
|
sokoliko/open-bo-api
|
ddcad19163532543ad13a0398f0b0119e55d4c3d
|
[
"MIT"
] | 3
|
2020-02-28T11:30:43.000Z
|
2020-06-05T12:50:33.000Z
|
include/open-bo-api-crc64.hpp
|
sokoliko/open-bo-api
|
ddcad19163532543ad13a0398f0b0119e55d4c3d
|
[
"MIT"
] | 7
|
2020-03-24T22:31:25.000Z
|
2021-11-24T17:13:56.000Z
|
/*
* open-bo-api - C++ API for working with binary options brokers
*
* Copyright (c) 2020 Elektro Yar. Email: git.electroyar@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef OPEN_BO_API_CRC64_HPP_INCLUDED
#define OPEN_BO_API_CRC64_HPP_INCLUDED
namespace open_bo_api {
class CRC64 {
public:
inline static const long long poly = 0xC96C5795D7870F42;
inline static long long crc64_table[256];
inline static void generate_table(){
for(int i=0; i<256; ++i) {
long long crc = i;
for(int j=0; j<8; ++j) {
if(crc & 1) {
crc >>= 1;
crc ^= poly;
} else {
crc >>= 1;
}
}
crc64_table[i] = crc;
}
}
inline static long long calc_crc64(long long crc, const unsigned char* stream, int n) {
for(int i=0; i< n; ++i) {
unsigned char index = stream[i] ^ crc;
long long lookup = crc64_table[index];
crc >>= 8;
crc ^= lookup;
}
return crc;
}
inline static long long calc_crc64(const std::string str) {
return calc_crc64(0, (const unsigned char*)str.c_str(), str.size());
}
};
}
#endif // CRC64_HPP_INCLUDED
| 32.630769
| 89
| 0.704856
|
sokoliko
|
f2465b2f9af69a8637fdd2e79279b20b1fc4ee81
| 986
|
cpp
|
C++
|
LeetCode/23. Merge k Sorted Lists/Solution.cpp
|
nik3212/challenges
|
b127bc66ffa27bfdef87ac402dc080f933dad893
|
[
"MIT"
] | 1
|
2021-06-15T12:48:47.000Z
|
2021-06-15T12:48:47.000Z
|
LeetCode/23. Merge k Sorted Lists/Solution.cpp
|
nik3212/challenges
|
b127bc66ffa27bfdef87ac402dc080f933dad893
|
[
"MIT"
] | null | null | null |
LeetCode/23. Merge k Sorted Lists/Solution.cpp
|
nik3212/challenges
|
b127bc66ffa27bfdef87ac402dc080f933dad893
|
[
"MIT"
] | null | null | null |
/*
23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
std::priority_queue<int, std::vector<int>, std::greater<int>> queue;
for (auto& list: lists) {
while (list) {
queue.push(list->val);
list = list->next;
}
}
ListNode* result = new ListNode(0);
ListNode* tmp = result;
while (!queue.empty()) {
int val = queue.top();
queue.pop();
tmp->next = new ListNode(val);
tmp = tmp->next;
}
return result->next;
}
};
| 17.927273
| 98
| 0.51217
|
nik3212
|
f24a6059fe50be8a4a5f21d303f9a8b110248f99
| 233
|
cpp
|
C++
|
src/caller/executor/executor.cpp
|
czhj/caller
|
1f749bc039e731478a2a2f766445b8a14ac13063
|
[
"MIT"
] | 1
|
2022-03-09T01:02:25.000Z
|
2022-03-09T01:02:25.000Z
|
src/caller/executor/executor.cpp
|
czhj/caller
|
1f749bc039e731478a2a2f766445b8a14ac13063
|
[
"MIT"
] | null | null | null |
src/caller/executor/executor.cpp
|
czhj/caller
|
1f749bc039e731478a2a2f766445b8a14ac13063
|
[
"MIT"
] | null | null | null |
#include <caller/executor/executor.hpp>
CALLER_BEGIN
ExecutionContext::ExecutionContext()
{
}
ExecutionContext::~ExecutionContext()
{
}
Executor::Executor()
{
}
Executor::~Executor()
{
}
CALLER_END
| 8.961538
| 40
| 0.643777
|
czhj
|
f24f3f3faf0695de76ce2b2b4d575af04e5f9c12
| 70,427
|
hpp
|
C++
|
Evolutionary_Strategy_Vulkan.hpp
|
Harri-Renney/Survival_of_the_Synthesis-GPU_Accelerated_Frequency_Modulation_Parameter_Matcher
|
c70f8f2f2961148a7639fad05b3cf0d87f895c0c
|
[
"MIT"
] | null | null | null |
Evolutionary_Strategy_Vulkan.hpp
|
Harri-Renney/Survival_of_the_Synthesis-GPU_Accelerated_Frequency_Modulation_Parameter_Matcher
|
c70f8f2f2961148a7639fad05b3cf0d87f895c0c
|
[
"MIT"
] | null | null | null |
Evolutionary_Strategy_Vulkan.hpp
|
Harri-Renney/Survival_of_the_Synthesis-GPU_Accelerated_Frequency_Modulation_Parameter_Matcher
|
c70f8f2f2961148a7639fad05b3cf0d87f895c0c
|
[
"MIT"
] | null | null | null |
#ifndef EVOLUTIONARY_STRATEGY_VULKAN_HPP
#define EVOLUTIONARY_STRATEGY_VULKAN_HPP
#include <math.h>
#include <array>
#include <random>
#include <chrono>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
//Graphic math types and functions//
#include <glm\glm.hpp>
#include "Evolutionary_Strategy.hpp"
#include "Benchmarker.hpp"
#include "Vulkan_Helper.hpp"
//#define CL_HPP_TARGET_OPENCL_VERSION 200
//#define CL_HPP_MINIMUM_OPENCL_VERSION 200
#define CL_HPP_TARGET_OPENCL_VERSION 120
#define CL_HPP_MINIMUM_OPENCL_VERSION 120
#include <CL/cl2.hpp>
#include <clFFT.h>
#ifdef NDEBUG
const bool enableValidationLayers = false;
#else
const bool enableValidationLayers = true;
#endif
struct Evolutionary_Strategy_Vulkan_Arguments
{
//Generic Evolutionary Strategy arguments//
Evolutionary_Strategy_Arguments es_args;
//Shader workgroup details//
uint32_t workgroupX = 32;
uint32_t workgroupY = 1;
uint32_t workgroupZ = 1;
uint32_t workgroupSize = workgroupX * workgroupY * workgroupZ;
uint32_t numWorkgroupsPerParent;
VkPhysicalDeviceType deviceType;
};
struct Specialization_Constants
{
uint32_t workgroupX = 32;
uint32_t workgroupY = 1;
uint32_t workgroupZ = 1;
uint32_t workgroupSize = 32;
uint32_t numDimensions = 4;
uint32_t populationCount = 1536;
uint32_t numWorkgroupsPerParent = 1; //population->num_parents / cl->work_group_size
uint32_t chunkSizeFitness = 1;
uint32_t audioWaveFormSize = 1024;
uint32_t fftOutSize = 1;
uint32_t fftHalfSize = 1;
float fftOneOverSize = 1.0;
float fftOneOverWindowFactor = 1.0;
float mPI = 3.14159265358979323846;
float alpha = 1.4f;
float oneOverAlpha = 1.f / alpha;
float rootTwoOverPi = sqrtf(2.f / (float)mPI);
float betaScale = 1.f / numDimensions; //1.f / (float)population->num_dimensions;
float beta = sqrtf(betaScale);
uint32_t chunksPerWorkgroupSynth = 2;
uint32_t chunkSizeSynth = workgroupSize / chunksPerWorkgroupSynth;
float OneOverSampleRateTimeTwoPi = 0.00014247573;
uint32_t populationSize = 1536 * 4;
} specializationData;
class Evolutionary_Strategy_Vulkan : public Evolutionary_Strategy
{
private:
//Shader workgroup details//
uint32_t globalSize;
uint32_t localSize;
uint32_t workgroupX;
uint32_t workgroupY;
uint32_t workgroupZ;
uint32_t workgroupSize;
uint32_t numWorkgroupsX;
uint32_t numWorkgroupsY;
uint32_t numWorkgroupsZ;
uint32_t chunks;
uint32_t chunkSize;
uint32_t chunkSizeFitness = 1; //@ToDo - Need this? Or just define in shader/kernel. Only important to GPU implementations so in subclass.
float* populationAudioDate;
float* populationFFTData;
//////////
//Vulkan//
//Instance//
VkInstance instance_;
//Physical Device//
VkPhysicalDevice physicalDevice_;
VkPhysicalDeviceType deviceType_;
//Logical Device//
VkDevice logicalDevice_;
//Compute Queue//
VkQueue computeQueue_; //A queue supporting compute operations.
uint32_t queueFamilyIndex_;
//Pipeline//
//FFT comes inbetween applyWindowPopulation & fitnessPopulation//
static const int numPipelines_ = 9;
enum computePipelineNames_ { initPopulation = 0, recombinePopulation, mutatePopulation, synthesisePopulation, applyWindowPopulation, VulkanFFT, fitnessPopulation, sortPopulation, rotatePopulation};
std::vector<std::string> shaderNames_;
VkPipeline computePipelines_[numPipelines_];
VkPipelineLayout computePipelineLayouts_[numPipelines_];
//Command Buffer//
VkCommandPool commandPoolInit_;
VkCommandBuffer commandBufferInit_;
VkQueryPool queryPoolInit_;
VkCommandPool commandPoolESOne_;
VkCommandBuffer commandBufferESOne_;
VkQueryPool queryPoolESOne_[5];
VkCommandPool commandPoolESTwo_;
VkCommandBuffer commandBufferESTwo_;
VkQueryPool queryPoolESTwo_[3];
float shaderExecuteTime_[numPipelines_];
VkCommandPool commandPoolFFT_;
VkCommandBuffer commandBufferFFT_;
//Descriptor//
VkDescriptorPool descriptorPool_;
VkDescriptorSet descriptorSet_;
VkDescriptorSetLayout descriptorSetLayout_;
std::vector<VkDescriptorPool> descriptorPools_;
std::vector<VkDescriptorSetLayout> descriptorSetLayouts_;
std::vector<VkDescriptorSet> descriptorSets_;
VkDescriptorPool descriptorPoolFFT_;
VkDescriptorSet descriptorSetFFT_;
VkDescriptorSetLayout descriptorSetLayoutFFT_;
//Constants//
static const int numSpecializationConstants_ = 23;
void* specializationConstantData_;
std::array<VkSpecializationMapEntry, numSpecializationConstants_> specializationConstantEntries_;
VkSpecializationInfo specializationConstantInfo_;
//Fences//
std::vector<VkFence> fences_;
//Population Buffers//
static const int numBuffers_ = 14;
enum storageBufferNames_ { inputPopulationValueBuffer = 0, inputPopulationStepBuffer, inputPopulationFitnessBuffer, outputPopulationValueBuffer, outputPopulationStepBuffer, outputPopulationFitnessBuffer, randomStatesBuffer, paramMinBuffer, paramMaxBuffer, outputAudioBuffer, inputFFTDataBuffer, inputFFTTargetBuffer, rotationIndexBuffer, wavetableBuffer};
std::array<VkBuffer, numBuffers_> storageBuffers_;
std::array<VkDeviceMemory, numBuffers_> storageBuffersMemory_;
std::array<uint32_t, numBuffers_> storageBufferSizes_;
//Staging Buffer//
VkQueue bufferQueue; //A queue for supporting memory buffer operations.
VkCommandPool commandPoolStaging_;
uint32_t stagingBufferSrcSize_;
VkBuffer stagingBufferSrc;
VkDeviceMemory stagingBufferMemorySrc;
void* stagingBufferSrcPointer;
uint32_t stagingBufferDstSize_;
VkBuffer stagingBufferDst;
VkDeviceMemory stagingBufferMemoryDst;
void* stagingBufferDstPointer;
Benchmarker vkBenchmarker_;
uint32_t rotationIndex_;
//Validation & Debug Variables//
VkDebugReportCallbackEXT debugReportCallback_;
std::vector<const char *> enabledValidationLayers;
static VKAPI_ATTR VkBool32 VKAPI_CALL debugReportCallbackFn(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType,
uint64_t object,
size_t location,
int32_t messageCode,
const char* pLayerPrefix,
const char* pMessage,
void* pUserData)
{
printf("Debug Report: %s: %s\n", pLayerPrefix, pMessage);
return VK_FALSE;
}
void initConstantsVK()
{
//Setup specialization constant entries//
specializationConstantEntries_[0].constantID = 1;
specializationConstantEntries_[0].size = sizeof(specializationData.workgroupX);
specializationConstantEntries_[0].offset = 0;
specializationConstantEntries_[1].constantID = 2;
specializationConstantEntries_[1].size = sizeof(specializationData.workgroupY);
specializationConstantEntries_[1].offset = offsetof(Specialization_Constants, workgroupY);
specializationConstantEntries_[2].constantID = 3;
specializationConstantEntries_[2].size = sizeof(specializationData.workgroupZ);
specializationConstantEntries_[2].offset = offsetof(Specialization_Constants, workgroupZ);
specializationConstantEntries_[3].constantID = 4;
specializationConstantEntries_[3].size = sizeof(specializationData.workgroupSize);
specializationConstantEntries_[3].offset = offsetof(Specialization_Constants, workgroupSize);
specializationConstantEntries_[4].constantID = 5;
specializationConstantEntries_[4].size = sizeof(specializationData.numDimensions);
specializationConstantEntries_[4].offset = offsetof(Specialization_Constants, numDimensions);
specializationConstantEntries_[5].constantID = 6;
specializationConstantEntries_[5].size = sizeof(specializationData.populationCount);
specializationConstantEntries_[5].offset = offsetof(Specialization_Constants, populationCount);
specializationConstantEntries_[6].constantID = 7;
specializationConstantEntries_[6].size = sizeof(specializationData.numWorkgroupsPerParent);
specializationConstantEntries_[6].offset = offsetof(Specialization_Constants, numWorkgroupsPerParent);
specializationConstantEntries_[7].constantID = 8;
specializationConstantEntries_[7].size = sizeof(specializationData.chunkSizeFitness);
specializationConstantEntries_[7].offset = offsetof(Specialization_Constants, chunkSizeFitness);
specializationConstantEntries_[8].constantID = 9;
specializationConstantEntries_[8].size = sizeof(specializationData.audioWaveFormSize);
specializationConstantEntries_[8].offset = offsetof(Specialization_Constants, audioWaveFormSize);
specializationConstantEntries_[9].constantID = 10;
specializationConstantEntries_[9].size = sizeof(specializationData.fftOutSize);
specializationConstantEntries_[9].offset = offsetof(Specialization_Constants, fftOutSize);
specializationConstantEntries_[10].constantID = 11;
specializationConstantEntries_[10].size = sizeof(specializationData.fftHalfSize);
specializationConstantEntries_[10].offset = offsetof(Specialization_Constants, fftHalfSize);
specializationConstantEntries_[11].constantID = 12;
specializationConstantEntries_[11].size = sizeof(specializationData.fftOneOverSize);
specializationConstantEntries_[11].offset = offsetof(Specialization_Constants, fftOneOverSize);
specializationConstantEntries_[12].constantID = 13;
specializationConstantEntries_[12].size = sizeof(specializationData.fftOneOverWindowFactor);
specializationConstantEntries_[12].offset = offsetof(Specialization_Constants, fftOneOverWindowFactor);
specializationConstantEntries_[13].constantID = 14;
specializationConstantEntries_[13].size = sizeof(specializationData.mPI);
specializationConstantEntries_[13].offset = offsetof(Specialization_Constants, mPI);
specializationConstantEntries_[14].constantID = 15;
specializationConstantEntries_[14].size = sizeof(specializationData.alpha);
specializationConstantEntries_[14].offset = offsetof(Specialization_Constants, alpha);
specializationConstantEntries_[15].constantID = 16;
specializationConstantEntries_[15].size = sizeof(specializationData.oneOverAlpha);
specializationConstantEntries_[15].offset = offsetof(Specialization_Constants, oneOverAlpha);
specializationConstantEntries_[16].constantID = 17;
specializationConstantEntries_[16].size = sizeof(specializationData.rootTwoOverPi);
specializationConstantEntries_[16].offset = offsetof(Specialization_Constants, rootTwoOverPi);
specializationConstantEntries_[17].constantID = 18;
specializationConstantEntries_[17].size = sizeof(specializationData.betaScale);
specializationConstantEntries_[17].offset = offsetof(Specialization_Constants, betaScale);
specializationConstantEntries_[18].constantID = 19;
specializationConstantEntries_[18].size = sizeof(specializationData.beta);
specializationConstantEntries_[18].offset = offsetof(Specialization_Constants, beta);
specializationConstantEntries_[19].constantID = 20;
specializationConstantEntries_[19].size = sizeof(specializationData.chunksPerWorkgroupSynth);
specializationConstantEntries_[19].offset = offsetof(Specialization_Constants, chunksPerWorkgroupSynth);
specializationConstantEntries_[20].constantID = 21;
specializationConstantEntries_[20].size = sizeof(specializationData.chunkSizeSynth);
specializationConstantEntries_[20].offset = offsetof(Specialization_Constants, chunkSizeSynth);
specializationConstantEntries_[21].constantID = 22;
specializationConstantEntries_[21].size = sizeof(specializationData.OneOverSampleRateTimeTwoPi);
specializationConstantEntries_[21].offset = offsetof(Specialization_Constants, OneOverSampleRateTimeTwoPi);
specializationConstantEntries_[22].constantID = 23;
specializationConstantEntries_[22].size = sizeof(specializationData.populationSize);
specializationConstantEntries_[22].offset = offsetof(Specialization_Constants, populationSize);
//Setup specialization constant data//
specializationData.workgroupX = workgroupX;
specializationData.workgroupY = workgroupY;
specializationData.workgroupZ = workgroupZ;
specializationData.workgroupSize = workgroupSize;
specializationData.numDimensions = population.numDimensions;
specializationData.populationCount = population.populationLength;
specializationData.numWorkgroupsPerParent = population.numParents / workgroupSize;
specializationData.chunkSizeFitness = workgroupSize / 2;
specializationData.audioWaveFormSize = objective.audioLength;
specializationData.fftOutSize = objective.fftOutSize;
specializationData.fftHalfSize = objective.fftHalfSize;
specializationData.fftOneOverSize = objective.fftOneOverSize;
specializationData.fftOneOverWindowFactor = objective.fftOneOverWindowFactor;
specializationData.mPI = mPI;
specializationData.alpha = alpha;
specializationData.oneOverAlpha = oneOverAlpha;
specializationData.rootTwoOverPi = rootTwoOverPi;
specializationData.betaScale = betaScale;
specializationData.beta = beta;
specializationData.chunksPerWorkgroupSynth = 2;
specializationData.chunkSizeSynth = workgroupSize / specializationData.chunksPerWorkgroupSynth;
specializationData.OneOverSampleRateTimeTwoPi = 0.00014247573;
specializationData.populationSize = population.populationLength * population.numDimensions;
}
//@ToDo - Use local memory buffers correctly//
void initBuffersVK()
{
//Creating each buffer at time//
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[inputPopulationValueBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storageBuffers_[inputPopulationValueBuffer], storageBuffersMemory_[inputPopulationValueBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[inputPopulationStepBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storageBuffers_[inputPopulationStepBuffer], storageBuffersMemory_[inputPopulationStepBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[inputPopulationFitnessBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storageBuffers_[inputPopulationFitnessBuffer], storageBuffersMemory_[inputPopulationFitnessBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[outputPopulationValueBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[outputPopulationValueBuffer], storageBuffersMemory_[outputPopulationValueBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[outputPopulationStepBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[outputPopulationStepBuffer], storageBuffersMemory_[outputPopulationStepBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[outputPopulationFitnessBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[outputPopulationFitnessBuffer], storageBuffersMemory_[outputPopulationFitnessBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[outputAudioBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storageBuffers_[outputAudioBuffer], storageBuffersMemory_[outputAudioBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[randomStatesBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[randomStatesBuffer], storageBuffersMemory_[randomStatesBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[paramMinBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[paramMinBuffer], storageBuffersMemory_[paramMinBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[paramMaxBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[paramMaxBuffer], storageBuffersMemory_[paramMaxBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[inputFFTDataBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[inputFFTDataBuffer], storageBuffersMemory_[inputFFTDataBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[inputFFTTargetBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[inputFFTTargetBuffer], storageBuffersMemory_[inputFFTTargetBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[rotationIndexBuffer], VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, storageBuffers_[rotationIndexBuffer], storageBuffersMemory_[rotationIndexBuffer]);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, storageBufferSizes_[wavetableBuffer], VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storageBuffers_[wavetableBuffer], storageBuffersMemory_[wavetableBuffer]);
//Create Staging Buffer//
stagingBufferSrcSize_ = storageBufferSizes_[inputFFTDataBuffer];
stagingBufferDstSize_ = storageBufferSizes_[inputFFTDataBuffer];
VKHelper::createBuffer(physicalDevice_, logicalDevice_, stagingBufferSrcSize_, VK_BUFFER_USAGE_TRANSFER_SRC_BIT
, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBufferSrc, stagingBufferMemorySrc);
VKHelper::createBuffer(physicalDevice_, logicalDevice_, stagingBufferDstSize_, VK_BUFFER_USAGE_TRANSFER_DST_BIT
, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBufferDst, stagingBufferMemoryDst);
}
void initRandomStateBuffer()
{
//Initialize random numbers in CPU buffer//
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
//std::uniform_int_distribution<int> distribution(0, 2147483647);
std::uniform_int_distribution<int> distribution(0, 32767);
//std::uniform_real_distribution<float> distribution(0.0, 1.0);
glm::uvec2* rand_state = new glm::uvec2[population.populationLength];
for (int i = 0; i < population.populationLength; ++i)
{
rand_state[i].x = distribution(generator);
rand_state[i].y = distribution(generator);
}
void* data;
uint32_t cpySize = population.populationLength * sizeof(glm::uvec2);
vkMapMemory(logicalDevice_, storageBuffersMemory_[randomStatesBuffer], 0, cpySize, 0, &data);
memcpy(data, rand_state, static_cast<size_t>(cpySize));
vkUnmapMemory(logicalDevice_, storageBuffersMemory_[randomStatesBuffer]);
}
void createInstance()
{
std::vector<const char *> enabledExtensions;
/*
By enabling validation layers, Vulkan will emit warnings if the API
is used incorrectly. We shall enable the layer VK_LAYER_LUNARG_standard_validation,
which is basically a collection of several useful validation layers.
*/
if (enableValidationLayers)
{
//Get all supported layers with vkEnumerateInstanceLayerProperties//
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, NULL);
std::vector<VkLayerProperties> layerProperties(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, layerProperties.data());
//Check if VK_LAYER_LUNARG_standard_validation is among supported layers//
bool foundLayer = false;
if (std::find_if(layerProperties.begin(), layerProperties.end(), [](const VkLayerProperties& m) -> bool { return strcmp(m.layerName, "VK_LAYER_KHRONOS_validation"); }) != layerProperties.end())
foundLayer = true;
if (!foundLayer) {
throw std::runtime_error("Layer VK_LAYER_KHRONOS_validation not supported\n");
}
enabledValidationLayers.push_back("VK_LAYER_KHRONOS_validation");
/*
We need to enable an extension named VK_EXT_DEBUG_REPORT_EXTENSION_NAME,
in order to be able to print the warnings emitted by the validation layer.
Check if the extension is among the supported extensions.
*/
uint32_t extensionCount;
vkEnumerateInstanceExtensionProperties(NULL, &extensionCount, NULL);
std::vector<VkExtensionProperties> extensionProperties(extensionCount);
vkEnumerateInstanceExtensionProperties(NULL, &extensionCount, extensionProperties.data());
bool foundExtension = false;
if (std::find_if(extensionProperties.begin(), extensionProperties.end(), [](const VkExtensionProperties& m) -> bool { return strcmp(m.extensionName, VK_EXT_DEBUG_REPORT_EXTENSION_NAME); }) != extensionProperties.end())
foundExtension = true;
if (!foundExtension) {
throw std::runtime_error("Extension VK_EXT_DEBUG_REPORT_EXTENSION_NAME not supported\n");
}
enabledExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
}
//Create Vulkan instance//
VkApplicationInfo applicationInfo = {};
applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
applicationInfo.pApplicationName = "Hello world app";
applicationInfo.applicationVersion = 0;
applicationInfo.pEngineName = "VkSoundMatch";
applicationInfo.engineVersion = 0;
applicationInfo.apiVersion = VK_API_VERSION_1_2;
VkInstanceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.flags = 0;
createInfo.pApplicationInfo = &applicationInfo;
// Give our desired layers and extensions to vulkan.
createInfo.enabledLayerCount = enabledValidationLayers.size();
createInfo.ppEnabledLayerNames = enabledValidationLayers.data();
createInfo.enabledExtensionCount = enabledExtensions.size();
createInfo.ppEnabledExtensionNames = enabledExtensions.data();
/*
Actually create the instance.
Having created the instance, we can actually start using vulkan.
*/
VK_CHECK_RESULT(vkCreateInstance(&createInfo, NULL, &instance_));
/*
Register a callback function for the extension VK_EXT_DEBUG_REPORT_EXTENSION_NAME, so that warnings emitted from the validation
layer are actually printed.
*/
if (enableValidationLayers) {
VkDebugReportCallbackCreateInfoEXT createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
createInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
createInfo.pfnCallback = &debugReportCallbackFn;
// We have to explicitly load this function.
auto vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance_, "vkCreateDebugReportCallbackEXT");
if (vkCreateDebugReportCallbackEXT == nullptr) {
throw std::runtime_error("Could not load vkCreateDebugReportCallbackEXT");
}
// Create and register callback.
VK_CHECK_RESULT(vkCreateDebugReportCallbackEXT(instance_, &createInfo, NULL, &debugReportCallback_));
}
}
//@ToDo - Correctly find the AMD GPU, not use intel one.//
void findPhysicalDevice()
{
//Collect physical devices available to VUlkan//
uint32_t deviceCount;
vkEnumeratePhysicalDevices(instance_, &deviceCount, NULL);
if (deviceCount == 0) {
throw std::runtime_error("could not find a device with vulkan support");
}
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance_, &deviceCount, devices.data());
//Iterate through and choose appropriate device//
for (VkPhysicalDevice device : devices) {
if (true) { // As above stated, we do no feature checks, so just accept.
VkPhysicalDeviceProperties deviceProperties;
VkPhysicalDeviceFeatures deviceFeatures;
vkGetPhysicalDeviceProperties(device, &deviceProperties);
vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
printf("Device found: %s\n", deviceProperties.deviceName);
printf("Device maxDescriptorSetStorageBuffers: %d\n", deviceProperties.limits.maxDescriptorSetStorageBuffers);
if(deviceProperties.deviceType == deviceType_)
{
physicalDevice_ = device;
break;
}
}
}
}
// Returns the index of a queue family that supports compute operations.
uint32_t getComputeQueueFamilyIndex()
{
uint32_t queueFamilyCount;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice_, &queueFamilyCount, NULL);
// Retrieve all queue families.
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice_, &queueFamilyCount, queueFamilies.data());
// Now find a family that supports compute.
uint32_t i = 0;
for (; i < queueFamilies.size(); ++i) {
VkQueueFamilyProperties props = queueFamilies[i];
if (props.queueCount > 0 && (props.queueFlags & VK_QUEUE_COMPUTE_BIT)) {
// found a queue with compute. We're done!
break;
}
}
if (i == queueFamilies.size()) {
throw std::runtime_error("could not find a queue family that supports operations");
}
return i;
}
void createDevice()
{
/*
We create the logical device in this function.
*/
/*
When creating the device, we also specify what queues it has.
*/
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueFamilyIndex_ = getComputeQueueFamilyIndex(); // find queue family with compute capability.
queueCreateInfo.queueFamilyIndex = queueFamilyIndex_;
queueCreateInfo.queueCount = 1; // create one queue in this family. We don't need more.
float queuePriorities = 1.0; // we only have one queue, so this is not that imporant.
queueCreateInfo.pQueuePriorities = &queuePriorities;
/*
Now we create the logical device. The logical device allows us to interact with the physical
device.
*/
VkDeviceCreateInfo deviceCreateInfo = {};
// Specify any desired device features here. We do not need any for this application, though.
VkPhysicalDeviceFeatures deviceFeatures = {};
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.enabledLayerCount = enabledValidationLayers.size(); // need to specify validation layers here as well.
deviceCreateInfo.ppEnabledLayerNames = enabledValidationLayers.data();
deviceCreateInfo.queueCreateInfoCount = 1;
deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo; // when creating the logical device, we also specify what queues it has.
deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
VK_CHECK_RESULT(vkCreateDevice(physicalDevice_, &deviceCreateInfo, NULL, &logicalDevice_)); // create logical device.
// Get a handle to the only member of the queue family.
vkGetDeviceQueue(logicalDevice_, queueFamilyIndex_, 0, &computeQueue_);
}
// find memory type with desired properties.
uint32_t findMemoryType(uint32_t memoryTypeBits, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties memoryProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice_, &memoryProperties);
/*
How does this search work?
See the documentation of VkPhysicalDeviceMemoryProperties for a detailed description.
*/
for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; ++i) {
if ((memoryTypeBits & (1 << i)) &&
((memoryProperties.memoryTypes[i].propertyFlags & properties) == properties))
return i;
}
return -1;
}
void createDescriptorSetLayout()
{
/*
Here we specify a descriptor set layout. This allows us to bind our descriptors to
resources in the shader.
*/
/*
Here we specify a binding of type VK_DESCRIPTOR_TYPE_STORAGE_BUFFER to the binding point
0. This binds to
layout(std140, binding = 0) buffer buf
in the compute shader.
*/
VkDescriptorSetLayoutBinding populationValueLayoutBinding = {};
populationValueLayoutBinding.binding = 0; // binding = 0
populationValueLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
populationValueLayoutBinding.descriptorCount = 1;
populationValueLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding populationStepLayoutBinding = {};
populationStepLayoutBinding.binding = 1; // binding = 0
populationStepLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
populationStepLayoutBinding.descriptorCount = 1;
populationStepLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding populationFitnessLayoutBinding = {};
populationFitnessLayoutBinding.binding = 2; // binding = 0
populationFitnessLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
populationFitnessLayoutBinding.descriptorCount = 1;
populationFitnessLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding populationValueTempLayoutBinding = {};
populationValueTempLayoutBinding.binding = 3; // binding = 0
populationValueTempLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
populationValueTempLayoutBinding.descriptorCount = 1;
populationValueTempLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding populationStepTempLayoutBinding = {};
populationStepTempLayoutBinding.binding = 4; // binding = 0
populationStepTempLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
populationStepTempLayoutBinding.descriptorCount = 1;
populationStepTempLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding populationFitnessTempLayoutBinding = {};
populationFitnessTempLayoutBinding.binding = 5; // binding = 0
populationFitnessTempLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
populationFitnessTempLayoutBinding.descriptorCount = 1;
populationFitnessTempLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding randStateLayoutBinding = {};
randStateLayoutBinding.binding = 6; // binding = 0
randStateLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
randStateLayoutBinding.descriptorCount = 1;
randStateLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding paramMinLayoutBinding = {};
paramMinLayoutBinding.binding = 7; // binding = 0
paramMinLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
paramMinLayoutBinding.descriptorCount = 1;
paramMinLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding paramMaxLayoutBinding = {};
paramMaxLayoutBinding.binding = 8; // binding = 0
paramMaxLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
paramMaxLayoutBinding.descriptorCount = 1;
paramMaxLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding audioWaveLayoutBinding = {};
audioWaveLayoutBinding.binding = 9; // binding = 0
audioWaveLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
audioWaveLayoutBinding.descriptorCount = 1;
audioWaveLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding FFTOutputLayoutBinding = {};
FFTOutputLayoutBinding.binding = 10; // binding = 0
FFTOutputLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
FFTOutputLayoutBinding.descriptorCount = 1;
FFTOutputLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding FFTTargetLayoutBinding = {};
FFTTargetLayoutBinding.binding = 11; // binding = 0
FFTTargetLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
FFTTargetLayoutBinding.descriptorCount = 1;
FFTTargetLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding rotationIndexLayoutBinding = {};
rotationIndexLayoutBinding.binding = 12; // binding = 0
rotationIndexLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
rotationIndexLayoutBinding.descriptorCount = 1;
rotationIndexLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding wavetableLayoutBinding = {};
wavetableLayoutBinding.binding = 13; // binding = 0
wavetableLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
wavetableLayoutBinding.descriptorCount = 1;
wavetableLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
//Layout create information from binding layouts//
std::array<VkDescriptorSetLayoutBinding, numBuffers_> bindings = { populationValueLayoutBinding, populationStepLayoutBinding, populationFitnessLayoutBinding, populationValueTempLayoutBinding, populationStepTempLayoutBinding, populationFitnessTempLayoutBinding, randStateLayoutBinding, paramMinLayoutBinding, paramMaxLayoutBinding, audioWaveLayoutBinding, FFTOutputLayoutBinding, FFTTargetLayoutBinding, rotationIndexLayoutBinding, wavetableLayoutBinding };
VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = {};
descriptorSetLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
descriptorSetLayoutCreateInfo.bindingCount = static_cast<uint32_t>(bindings.size()); // only a single binding in this descriptor set layout.
descriptorSetLayoutCreateInfo.pBindings = bindings.data();
//Create the descriptor set layout//
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(logicalDevice_, &descriptorSetLayoutCreateInfo, NULL, &descriptorSetLayout_));
}
void createDescriptorSet()
{
/*
So we will allocate a descriptor set here.
But we need to first create a descriptor pool to do that.
*/
/*
Our descriptor pool can only allocate a single storage buffer.
*/
std::array<VkDescriptorPoolSize, numBuffers_> poolSizes = {};
poolSizes[0].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[0].descriptorCount = 1;
poolSizes[1].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[1].descriptorCount = 1;
poolSizes[2].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[2].descriptorCount = 1;
poolSizes[3].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[3].descriptorCount = 1;
poolSizes[4].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[4].descriptorCount = 1;
poolSizes[5].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[5].descriptorCount = 1;
poolSizes[6].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[6].descriptorCount = 1;
poolSizes[7].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[7].descriptorCount = 1;
poolSizes[8].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[8].descriptorCount = 1;
poolSizes[9].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[9].descriptorCount = 1;
poolSizes[10].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[10].descriptorCount = 1;
poolSizes[11].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[11].descriptorCount = 1;
poolSizes[12].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[12].descriptorCount = 1;
poolSizes[13].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
poolSizes[13].descriptorCount = 1;
VkDescriptorPoolCreateInfo descriptorPoolCreateInfo = {};
descriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
descriptorPoolCreateInfo.maxSets = 1; // we only need to allocate one descriptor set from the pool.
descriptorPoolCreateInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
descriptorPoolCreateInfo.pPoolSizes = poolSizes.data();
// create descriptor pool.
VK_CHECK_RESULT(vkCreateDescriptorPool(logicalDevice_, &descriptorPoolCreateInfo, NULL, &descriptorPool_));
/*
With the pool allocated, we can now allocate the descriptor set.
*/
VkDescriptorSetAllocateInfo descriptorSetAllocateInfo = {};
descriptorSetAllocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
descriptorSetAllocateInfo.descriptorPool = descriptorPool_; // pool to allocate from.
descriptorSetAllocateInfo.descriptorSetCount = 1; // allocate a single descriptor set.
descriptorSetAllocateInfo.pSetLayouts = &descriptorSetLayout_;
// allocate descriptor set.
VK_CHECK_RESULT(vkAllocateDescriptorSets(logicalDevice_, &descriptorSetAllocateInfo, &descriptorSet_));
/*
Next, we need to connect our actual storage buffer with the descrptor.
We use vkUpdateDescriptorSets() to update the descriptor set.
*/
std::array<VkDescriptorBufferInfo, numBuffers_> descriptorBuffersInfo;
std::array<VkWriteDescriptorSet, numBuffers_> descriptorWrites = {};
for (uint32_t i = 0; i != numBuffers_; ++i)
{
descriptorBuffersInfo[i].buffer = storageBuffers_[i];
descriptorBuffersInfo[i].offset = 0;
descriptorBuffersInfo[i].range = storageBufferSizes_[i];
descriptorWrites[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[i].dstSet = descriptorSet_;
descriptorWrites[i].dstBinding = i;
descriptorWrites[i].dstArrayElement = 0;
descriptorWrites[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
descriptorWrites[i].descriptorCount = 1; //@ToDo - May need higher count.
descriptorWrites[i].pBufferInfo = &(descriptorBuffersInfo[i]);
}
// perform the update of the descriptor set.
vkUpdateDescriptorSets(logicalDevice_, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, NULL);
}
void createComputePipelines() //create pipelines
{
VkSpecializationInfo specializationInfo{};
specializationInfo.dataSize = sizeof(specializationData);
specializationInfo.mapEntryCount = static_cast<uint32_t>(specializationConstantEntries_.size());
specializationInfo.pMapEntries = specializationConstantEntries_.data();
specializationInfo.pData = &specializationData;
VkPushConstantRange pushConstantRange[1] = {};
pushConstantRange[0].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
pushConstantRange[0].offset = 0;
pushConstantRange[0].size = sizeof(uint32_t);
for (uint8_t i = 0; i != numPipelines_; ++i)
{
/*
Now let us actually create the compute pipeline.
A compute pipeline is very simple compared to a graphics pipeline.
It only consists of a single stage with a compute shader.
So first we specify the compute shader stage, and it's entry point(main).
*/
uint32_t filelength;
std::string fileName = "shaders/" + shaderNames_[i];
std::vector<char> code = VKHelper::readFile(fileName);
VkShaderModule shaderModule = VKHelper::createShaderModule(logicalDevice_, code);
VkPipelineShaderStageCreateInfo shaderStageCreateInfo = {};
shaderStageCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStageCreateInfo.stage = VK_SHADER_STAGE_COMPUTE_BIT;
shaderStageCreateInfo.module = shaderModule;
shaderStageCreateInfo.pName = "main";
shaderStageCreateInfo.pSpecializationInfo = &specializationInfo;
/*
The pipeline layout allows the pipeline to access descriptor sets.
So we just specify the descriptor set layout we created earlier.
All pipelines are going to access the same descriptors to start with.
*/
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = {};
pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutCreateInfo.setLayoutCount = 1;
pipelineLayoutCreateInfo.pSetLayouts = &descriptorSetLayout_;
pipelineLayoutCreateInfo.pushConstantRangeCount = 1;
pipelineLayoutCreateInfo.pPushConstantRanges = pushConstantRange;
VK_CHECK_RESULT(vkCreatePipelineLayout(logicalDevice_, &pipelineLayoutCreateInfo, NULL, &(computePipelineLayouts_[i])));
VkComputePipelineCreateInfo pipelineCreateInfo = {};
pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
pipelineCreateInfo.stage = shaderStageCreateInfo;
pipelineCreateInfo.layout = (computePipelineLayouts_[i]);
VK_CHECK_RESULT(vkCreateComputePipelines(logicalDevice_, VK_NULL_HANDLE, 1, &pipelineCreateInfo, NULL, &(computePipelines_[i])));
vkDestroyShaderModule(logicalDevice_, shaderModule, NULL);
std::cout << "Created shader: " << fileName.c_str() << std::endl;
}
}
void createCopyCommandPool()
{
VkCommandPoolCreateInfo commandPoolCreateInfo = {};
commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
commandPoolCreateInfo.flags = 0;
// the queue family of this command pool. All command buffers allocated from this command pool,
// must be submitted to queues of this family ONLY.
commandPoolCreateInfo.queueFamilyIndex = queueFamilyIndex_;
VK_CHECK_RESULT(vkCreateCommandPool(logicalDevice_, &commandPoolCreateInfo, NULL, &commandPoolStaging_));
}
void calculateAudioFFT()
{
//int counter = 0;
//for (uint32_t i = 0; i != population.populationSize * objective.audioLength; i += objective.audioLength)
//{
// objective.calculateFFTSpecial(&populationAudioDate[i], &populationFFTData[counter]);
// counter += objective.fftHalfSize;
//}
executeOpenCLFFT();
}
//@ToDo - Right now pick platform. Can extend to pick best available.
int errorStatus_ = 0;
cl_uint num_platforms, num_devices;
cl::Platform platform_;
cl::Context context_;
cl::Device device_;
cl::CommandQueue commandQueue_;
cl::Program kernelProgram_;
std::string kernelSourcePath_;
cl::NDRange globalws_;
cl::NDRange localws_;
clfftPlanHandle planHandle;
void initContextCL(uint8_t aPlatform, uint8_t aDevice)
{
//Discover platforms//
std::vector <cl::Platform> platforms;
cl::Platform::get(&platforms);
//Create contex properties for first platform//
cl_context_properties contextProperties[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[aPlatform])(), 0 }; //Need to specify platform 3 for dedicated graphics - Harri Laptop.
//Create context context using platform for GPU device//
context_ = cl::Context(CL_DEVICE_TYPE_ALL, contextProperties);
//Get device list from context//
std::vector<cl::Device> devices = context_.getInfo<CL_CONTEXT_DEVICES>();
//Create command queue for first device - Profiling enabled//
commandQueue_ = cl::CommandQueue(context_, devices[aDevice], CL_QUEUE_PROFILING_ENABLE, &errorStatus_); //Need to specify device 1[0] of platform 3[2] for dedicated graphics - Harri Laptop.
if (errorStatus_)
std::cout << "ERROR creating command queue for device. Status code: " << errorStatus_ << std::endl;
globalws_ = cl::NDRange(globalSize);
localws_ = cl::NDRange(workgroupX, workgroupY, workgroupZ);
/* FFT library realted declarations */
clfftDim dim = CLFFT_1D;
size_t clLengths[1] = { objective.audioLength };
/* Setup clFFT. */
clfftSetupData fftSetup;
errorStatus_ = clfftInitSetupData(&fftSetup);
errorStatus_ = clfftSetup(&fftSetup);
/* Create a default plan for a complex FFT. */
errorStatus_ = clfftCreateDefaultPlan(&planHandle, context_(), dim, clLengths);
/* Set plan parameters. */
errorStatus_ = clfftSetPlanPrecision(planHandle, CLFFT_SINGLE);
errorStatus_ = clfftSetLayout(planHandle, CLFFT_REAL, CLFFT_HERMITIAN_INTERLEAVED);
errorStatus_ = clfftSetResultLocation(planHandle, CLFFT_OUTOFPLACE);
errorStatus_ = clfftSetPlanBatchSize(planHandle, (size_t)population.populationLength);
size_t in_strides[1] = { 1 };
size_t out_strides[1] = { 1 };
size_t in_dist = (size_t)objective.audioLength;
size_t out_dist = (size_t)objective.audioLength / 2 + 4;
objective.fftOutSize = out_dist * 2;
objective.fftHalfSize = 1 << (objective.audioLengthLog2 - 1);
storageBufferSizes_[inputFFTDataBuffer] = population.populationLength * objective.fftOutSize * sizeof(float);
storageBufferSizes_[inputFFTTargetBuffer] = objective.fftHalfSize * sizeof(float); //objective.fftSizeHalf
clfftSetPlanInStride(planHandle, dim, in_strides);
clfftSetPlanOutStride(planHandle, dim, out_strides);
clfftSetPlanDistance(planHandle, in_dist, out_dist);
/* Bake the plan. */
errorStatus_ = clfftBakePlan(planHandle, 1, &commandQueue_(), NULL, NULL);
}
cl::Buffer inputBuffer;
cl::Buffer outputBuffer;
void initBuffersCL()
{
inputBuffer = cl::Buffer(context_, CL_MEM_READ_WRITE, storageBufferSizes_[outputAudioBuffer]);
outputBuffer = cl::Buffer(context_, CL_MEM_READ_WRITE, storageBufferSizes_[inputFFTDataBuffer]);
}
public:
Evolutionary_Strategy_Vulkan(uint32_t aNumGenerations, uint32_t aNumParents, uint32_t aNumOffspring, uint32_t aNumDimensions, const std::vector<float> aParamMin, const std::vector<float> aParamMax, uint32_t aAudioLengthLog2) :
Evolutionary_Strategy(aNumGenerations, aNumParents, aNumOffspring, aNumDimensions, aParamMin, aParamMax, aAudioLengthLog2),
vkBenchmarker_("vulkanlog.csv", { "Test_Name", "Total_Time", "Average_Time", "Max_Time", "Min_Time", "Max_Difference", "Average_Difference" }),
shaderNames_({ "initPopulation.spv", "recombinePopulation.spv", "mutatePopulation.spv", "SynthesisePopulation.spv", "applyWindowPopulation.spv", "VulkanFFT.spv", "fitnessPopulation.spv", "sortPopulation.spv", "rotatePopulation.spv" })
{
}
Evolutionary_Strategy_Vulkan(Evolutionary_Strategy_Vulkan_Arguments args) :
Evolutionary_Strategy(args.es_args.numGenerations, args.es_args.pop.numParents, args.es_args.pop.numOffspring, args.es_args.pop.numDimensions, args.es_args.paramMin, args.es_args.paramMax, args.es_args.audioLengthLog2),
vkBenchmarker_("vulkanlog.csv", { "Test_Name", "Total_Time", "Average_Time", "Max_Time", "Min_Time", "Max_Difference", "Average_Difference" }),
shaderNames_({ "initPopulation.spv", "recombinePopulation.spv", "mutatePopulation.spv", "SynthesisePopulation.spv", "applyWindowPopulation.spv", "VulkanFFT.spv", "fitnessPopulation.spv", "sortPopulation.spv", "rotatePopulation.spv" }),
workgroupX(args.workgroupX),
workgroupY(args.workgroupY),
workgroupZ(args.workgroupZ),
workgroupSize(args.workgroupX*args.workgroupY*args.workgroupZ),
globalSize(population.populationLength),
numWorkgroupsX(globalSize / workgroupX),
numWorkgroupsY(1),
numWorkgroupsZ(1),
chunkSizeFitness(workgroupSize / 2),
deviceType_(args.deviceType)
{
for (int i = 0; i != randomStatesBuffer; ++i)
storageBufferSizes_[i] = (population.numParents + population.numOffspring) * population.numDimensions * sizeof(float) * 2;
storageBufferSizes_[randomStatesBuffer] = (population.numParents + population.numOffspring) * sizeof(glm::vec2);
storageBufferSizes_[inputPopulationFitnessBuffer] = (population.numParents + population.numOffspring) * sizeof(float) * 2;
storageBufferSizes_[outputPopulationFitnessBuffer] = (population.numParents + population.numOffspring) * sizeof(float) * 2;
storageBufferSizes_[paramMinBuffer] = population.numDimensions * sizeof(float);
storageBufferSizes_[paramMaxBuffer] = population.numDimensions * sizeof(float);
storageBufferSizes_[outputAudioBuffer] = population.populationLength * objective.audioLength * sizeof(float);
storageBufferSizes_[rotationIndexBuffer] = sizeof(uint32_t);
storageBufferSizes_[wavetableBuffer] = objective.wavetableSize * sizeof(float);
rotationIndex_ = 0;
initContextCL(0, 0);
initBuffersCL();
initCLFFT();
populationAudioDate = new float[population.populationLength * objective.audioLength];
populationFFTData = new float[population.populationLength * objective.fftOutSize];
createInstance();
findPhysicalDevice();
createDevice();
initBuffersVK();
createDescriptorSetLayout();
createDescriptorSet();
initConstantsVK();
createComputePipelines();
createCopyCommandPool();
std::vector<VkPipelineLayout> pipelineLayoutsTemp = { computePipelineLayouts_[initPopulation] };
std::vector<VkPipeline> pipelinesTemp = { computePipelines_[initPopulation] };
createCommandBuffer(commandPoolInit_, commandBufferInit_, pipelineLayoutsTemp, pipelinesTemp, &queryPoolInit_);
pipelineLayoutsTemp = { computePipelineLayouts_[recombinePopulation], computePipelineLayouts_[mutatePopulation], computePipelineLayouts_[synthesisePopulation], computePipelineLayouts_[applyWindowPopulation] };
pipelinesTemp = { computePipelines_[recombinePopulation], computePipelines_[mutatePopulation], computePipelines_[synthesisePopulation], computePipelines_[applyWindowPopulation] };
createCommandBuffer(commandPoolESOne_, commandBufferESOne_, pipelineLayoutsTemp, pipelinesTemp, queryPoolESOne_);
pipelineLayoutsTemp = { computePipelineLayouts_[fitnessPopulation], computePipelineLayouts_[sortPopulation] };
pipelinesTemp = { computePipelines_[fitnessPopulation], computePipelines_[sortPopulation] };
createCommandBuffer(commandPoolESTwo_, commandBufferESTwo_, pipelineLayoutsTemp, pipelinesTemp, queryPoolESTwo_);
//createPopulationInitialiseCommandBuffer();
//createESCommandBufferOne();
//createESCommandBufferTwo();
initRandomStateBuffer();
writeLocalBuffer(storageBuffers_[paramMinBuffer], 4 * sizeof(float), (void*)objective.paramMins.data());
writeLocalBuffer(storageBuffers_[paramMaxBuffer], 4 * sizeof(float), (void*)objective.paramMaxs.data());
VKHelper::writeBuffer(logicalDevice_, storageBufferSizes_[wavetableBuffer], stagingBufferMemorySrc, objective.wavetable);
copyBuffer(stagingBufferSrc, storageBuffers_[wavetableBuffer], storageBufferSizes_[wavetableBuffer]);
}
void initCLFFT()
{
//clFFT Variables//
clfftDim dim = CLFFT_1D;
size_t clLengths[1] = { objective.audioLength };
size_t in_strides[1] = { 1 };
size_t out_strides[1] = { 1 };
size_t in_dist = (size_t)objective.audioLength;
size_t out_dist = (size_t)objective.audioLength / 2 + 4;
//Update member variables with new information//
objective.fftOutSize = out_dist * 2;
storageBufferSizes_[inputFFTDataBuffer] = population.populationLength * objective.fftOutSize * sizeof(float);
storageBufferSizes_[inputFFTTargetBuffer] = objective.fftHalfSize * sizeof(float);
//Setup clFFT//
clfftSetupData fftSetup;
errorStatus_ = clfftInitSetupData(&fftSetup);
errorStatus_ = clfftSetup(&fftSetup);
//Create a default plan for a complex FFT//
errorStatus_ = clfftCreateDefaultPlan(&planHandle, context_(), dim, clLengths);
//Set plan parameters//
errorStatus_ = clfftSetPlanPrecision(planHandle, CLFFT_SINGLE);
errorStatus_ = clfftSetLayout(planHandle, CLFFT_REAL, CLFFT_HERMITIAN_INTERLEAVED);
errorStatus_ = clfftSetResultLocation(planHandle, CLFFT_OUTOFPLACE);
errorStatus_ = clfftSetPlanBatchSize(planHandle, (size_t)population.populationLength);
clfftSetPlanInStride(planHandle, dim, in_strides);
clfftSetPlanOutStride(planHandle, dim, out_strides);
clfftSetPlanDistance(planHandle, in_dist, out_dist);
//Bake clFFT plan//
errorStatus_ = clfftBakePlan(planHandle, 1, &commandQueue_(), NULL, NULL);
if (errorStatus_)
std::cout << "ERROR creating clFFT plan. Status code: " << errorStatus_ << std::endl;
}
void writePopulationData()
{
}
void readTestingData(void* aTestingData, size_t aTestingDataSize)
{
copyBuffer(storageBuffers_[inputPopulationValueBuffer], stagingBufferDst, aTestingDataSize);
VKHelper::readBuffer(logicalDevice_, aTestingDataSize, stagingBufferMemoryDst, aTestingData);
}
void readPopulationData(void* aInputPopulationValueData, void* aOutputPopulationValueData, uint32_t aPopulationValueSize, void* aInputPopulationStepData, void* aOutputPopulationStepData, uint32_t aPopulationStepSize, void* aInputPopulationFitnessData, void* aOutputPopulationFitnessData, uint32_t aPopulationFitnessSize)
{
copyBuffer(storageBuffers_[inputPopulationValueBuffer], stagingBufferDst, aPopulationValueSize);
VKHelper::readBuffer(logicalDevice_, aPopulationValueSize, stagingBufferMemoryDst, aInputPopulationValueData);
copyBuffer(storageBuffers_[inputPopulationStepBuffer], stagingBufferDst, aPopulationStepSize);
VKHelper::readBuffer(logicalDevice_, aPopulationStepSize, stagingBufferMemoryDst, aInputPopulationStepData);
copyBuffer(storageBuffers_[inputPopulationFitnessBuffer], stagingBufferDst, aPopulationFitnessSize);
VKHelper::readBuffer(logicalDevice_, aPopulationFitnessSize, stagingBufferMemoryDst, aInputPopulationFitnessData);
}
void writeSynthesizerData(void* aOutputAudioBuffer, uint32_t aOutputAudioSize, void* aInputFFTDataBuffer, void* aInputFFTTargetBuffer, uint32_t aInputFFTSize)
{
}
void readSynthesizerData(void* aOutputAudioBuffer, uint32_t aOutputAudioSize, void* aInputFFTDataBuffer, void* aInputFFTTargetBuffer, uint32_t aInputFFTSize)
{
VKHelper::readBuffer(logicalDevice_, aOutputAudioSize, storageBuffersMemory_[outputAudioBuffer], aOutputAudioBuffer);
VKHelper::readBuffer(logicalDevice_, aInputFFTSize, storageBuffersMemory_[inputFFTDataBuffer], aInputFFTDataBuffer);
VKHelper::readBuffer(logicalDevice_, aInputFFTSize/2, storageBuffersMemory_[inputFFTTargetBuffer], aInputFFTTargetBuffer);
}
void readParamData()
{
}
void writeParamData(void* aParamMinBuffer, void* aParamMaxBuffer)
{
VKHelper::writeBuffer(logicalDevice_, population.numDimensions*sizeof(float), storageBuffersMemory_[paramMinBuffer], aParamMinBuffer);
VKHelper::writeBuffer(logicalDevice_, population.numDimensions*sizeof(float), storageBuffersMemory_[paramMaxBuffer], aParamMaxBuffer);
}
void executeMutate()
{
//commandQueue_.enqueueNDRangeKernel(kernels_[mutatePopulation], cl::NullRange/*globaloffset*/, globalws_, localws_, NULL);
//commandQueue_.finish();
}
void executeFitness()
{
//commandQueue_.enqueueNDRangeKernel(kernels_[fitnessPopulation], cl::NullRange/*globaloffset*/, globalws_, localws_, NULL);
//commandQueue_.finish();
}
void executeSynthesise()
{
//commandQueue_.enqueueNDRangeKernel(kernels_[synthesisePopulation], cl::NullRange/*globaloffset*/, globalws_, localws_, NULL);
//commandQueue_.finish();
}
void executeGeneration()
{
VKHelper::runCommandBuffer(logicalDevice_, computeQueue_, commandBufferESOne_);
//VKHelper::readBuffer(logicalDevice_, storageBufferSizes_[outputAudioBuffer], storageBuffersMemory_[outputAudioBuffer], populationAudioDate);
//copyBuffer(storageBuffers_[outputAudioBuffer], stagingBufferDst, storageBufferSizes_[outputAudioBuffer]);
//VKHelper::readBuffer(logicalDevice_, storageBufferSizes_[outputAudioBuffer], stagingBufferMemoryDst, populationAudioDate);
std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::steady_clock::now();
readLocalBuffer(storageBuffers_[outputAudioBuffer], storageBufferSizes_[outputAudioBuffer], populationAudioDate);
calculateAudioFFT(); //@ToDo - Work out how to calculate FFT for GPU acceptable format.
writeLocalBuffer(storageBuffers_[inputFFTDataBuffer], storageBufferSizes_[inputFFTDataBuffer], populationFFTData);
auto end = std::chrono::steady_clock::now();
auto diff = end - start;
shaderExecuteTime_[5] += diff.count() / (float)1e6;
//VKHelper::writeBuffer(logicalDevice_, storageBufferSizes_[outputAudioBuffer], stagingBufferMemorySrc, populationAudioDate);
//copyBuffer(stagingBufferSrc, storageBuffers_[outputAudioBuffer], storageBufferSizes_[outputAudioBuffer]);
//VKHelper::writeBuffer(logicalDevice_, storageBufferSizes_[inputFFTDataBuffer], storageBuffersMemory_[inputFFTDataBuffer], populationFFTData);
VKHelper::runCommandBuffer(logicalDevice_, computeQueue_, commandBufferESTwo_);
vkBenchmarker_.startTimer(shaderNames_[8]);
rotationIndex_ = (rotationIndex_ == 0 ? 1 : 0);
VKHelper::writeBuffer(logicalDevice_, sizeof(uint32_t), storageBuffersMemory_[rotationIndexBuffer], &rotationIndex_);
vkBenchmarker_.pauseTimer(shaderNames_[8]);
}
void executeAllGenerations()
{
rotationIndex_ = 0;
for (uint32_t i = 0; i != numGenerations; ++i)
{
executeGeneration();
//*rotationIndex_ = (*rotationIndex_ == 0 ? 1 : 0);
//
//VkCommandBuffer commandBuffer = beginSingleTimeCommands();
//for(uint32_t i = 0; i != numPipelines_; ++i)
// vkCmdPushConstants(commandBuffer, computePipelineLayouts_[i], VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t), rotationIndex_);
////VkCmdPushConstants(commandBufferESOne_, computePipelineLayouts_[0], VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t), rotationIndex_);
//endSingleTimeCommands(commandBuffer);
uint64_t timestamp[2];
vkGetQueryPoolResults(logicalDevice_, queryPoolInit_, 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
vkGetQueryPoolResults(logicalDevice_, queryPoolInit_, 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
uint64_t diff = timestamp[1] - timestamp[0];
shaderExecuteTime_[0] += diff / (float)1e6;
vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[0], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[0], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
diff = timestamp[1] - timestamp[0];
shaderExecuteTime_[1] += diff / (float)1e6;
vkBenchmarker_.addTimer(shaderNames_[1], diff / (float)1e6);
vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[1], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[1], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
diff = timestamp[1] - timestamp[0];
shaderExecuteTime_[2] += diff / (float)1e6;
vkBenchmarker_.addTimer(shaderNames_[2], diff / (float)1e6);
vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[2], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[2], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
diff = timestamp[1] - timestamp[0];
shaderExecuteTime_[3] += diff / (float)1e6;
vkBenchmarker_.addTimer(shaderNames_[3], diff / (float)1e6);
vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[3], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
vkGetQueryPoolResults(logicalDevice_, queryPoolESOne_[3], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
diff = timestamp[1] - timestamp[0];
shaderExecuteTime_[4] += diff / (float)1e6;
vkBenchmarker_.addTimer(shaderNames_[4], diff / (float)1e6);
vkGetQueryPoolResults(logicalDevice_, queryPoolESTwo_[0], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
vkGetQueryPoolResults(logicalDevice_, queryPoolESTwo_[0], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
diff = timestamp[1] - timestamp[0];
shaderExecuteTime_[6] += diff / (float)1e6;
vkBenchmarker_.addTimer(shaderNames_[6], diff / (float)1e6);
vkGetQueryPoolResults(logicalDevice_, queryPoolESTwo_[1], 0, 1, sizeof(uint64_t), &(timestamp[0]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
vkGetQueryPoolResults(logicalDevice_, queryPoolESTwo_[1], 1, 1, sizeof(uint64_t), &(timestamp[1]), 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
diff = timestamp[1] - timestamp[0];
shaderExecuteTime_[7] += diff / (float)1e6;
vkBenchmarker_.addTimer(shaderNames_[7], diff / (float)1e6);
}
float totalKernelRunTime = 0.0;
for (uint32_t i = 0; i != numPipelines_; ++i)
{
//executeTime = executeTime / numGenerations;
std::cout << "Time to complete kernel " << i << ": " << shaderExecuteTime_[i] << "ms\n";
totalKernelRunTime += shaderExecuteTime_[i];
}
std::cout << "Time to complete all kernels for this run: " << totalKernelRunTime << "ms\n";
}
void parameterMatchAudio(float* aTargetAudio, uint32_t aTargetAudioLength)
{
chunkSize = objective.audioLength;
chunks = aTargetAudioLength / chunkSize;
for (int i = 0; i < chunks; i++)
{
setTargetAudio(&aTargetAudio[i*chunkSize], chunkSize);
initPopulationVK();
uint32_t rI = 0;
VKHelper::writeBuffer(logicalDevice_, sizeof(uint32_t), storageBuffersMemory_[rotationIndexBuffer], &rI); //Need this?
executeAllGenerations();
uint32_t tempSize = 4 * sizeof(float);
float* tempData = new float[4];
float tempFitness;
copyBuffer(storageBuffers_[inputPopulationValueBuffer], stagingBufferDst, tempSize);
VKHelper::readBuffer(logicalDevice_, tempSize, stagingBufferMemoryDst, tempData);
//VKHelper::readBuffer(logicalDevice_, tempSize, storageBuffersMemory_[inputPopulationValueBuffer], tempData);
copyBuffer(storageBuffers_[inputPopulationFitnessBuffer], stagingBufferDst, sizeof(float));
VKHelper::readBuffer(logicalDevice_, sizeof(float), stagingBufferMemoryDst, &tempFitness);
//VKHelper::readBuffer(logicalDevice_, sizeof(float), storageBuffersMemory_[inputPopulationFitnessBuffer], &tempFitness);
printf("Generation %d parameters:\n Param0 = %f\n Param1 = %f\n Param2 = %f\n Param3 = %f\nFitness=%f\n\n\n", i, tempData[0] * 3520.0, tempData[1] * 8.0, tempData[2] * 3520.0, tempData[3] * 1.0, tempFitness);
}
vkBenchmarker_.elapsedTimer(shaderNames_[1]);
vkBenchmarker_.elapsedTimer(shaderNames_[2]);
vkBenchmarker_.elapsedTimer(shaderNames_[3]);
vkBenchmarker_.elapsedTimer(shaderNames_[4]);
vkBenchmarker_.elapsedTimer(shaderNames_[5]);
vkBenchmarker_.elapsedTimer(shaderNames_[6]);
vkBenchmarker_.elapsedTimer(shaderNames_[7]);
vkBenchmarker_.elapsedTimer(shaderNames_[8]);
}
void executeOpenCLFFT()
{
commandQueue_.enqueueWriteBuffer(inputBuffer, CL_TRUE, 0, storageBufferSizes_[outputAudioBuffer], populationAudioDate);
/* Execute the plan. */
errorStatus_ = clfftEnqueueTransform(planHandle, CLFFT_FORWARD, 1, &commandQueue_(), 0, NULL, NULL, &inputBuffer(), &outputBuffer(), NULL);
commandQueue_.finish();
commandQueue_.enqueueReadBuffer(outputBuffer, CL_TRUE, 0, storageBufferSizes_[inputFFTDataBuffer], populationFFTData);
}
void setTargetAudio(float* aTargetAudio, uint32_t aTargetAudioLength)
{
float* targetFFT = new float[objective.fftHalfSize];
objective.calculateFFT(aTargetAudio, targetFFT);
//@ToDo - Check this works. Not any problems with passing as values//
VKHelper::writeBuffer(logicalDevice_, objective.fftHalfSize * sizeof(float), storageBuffersMemory_[inputFFTTargetBuffer], targetFFT);
delete(targetFFT);
}
void initPopulationVK()
{
VKHelper::runCommandBuffer(logicalDevice_, computeQueue_, commandBufferInit_);
}
//Command execution functions//
VkCommandBuffer beginSingleTimeCommands()
{
//Memory transfer executed like drawing commands//
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPoolStaging_; //@ToDo - Is this okay to be renderCommandPool only? Or need one for each??
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(logicalDevice_, &allocInfo, &commandBuffer);
//Start recording command buffer//
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
return commandBuffer;
}
void endSingleTimeCommands(VkCommandBuffer aCommandBuffer)
{
vkEndCommandBuffer(aCommandBuffer);
//Execute command buffer to complete transfer - Can use fences for synchronized, simultaneous execution//
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &aCommandBuffer;
vkQueueSubmit(computeQueue_, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(computeQueue_);
//Cleanup used comand pool//
vkFreeCommandBuffers(logicalDevice_, commandPoolStaging_, 1, &aCommandBuffer); //@ToDo - Is this okay to be renderCommandPool only? Or need one for each??
}
void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
{
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPoolStaging_;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(logicalDevice_, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferCopy copyRegion = {};
copyRegion.srcOffset = 0; // Optional
copyRegion.dstOffset = 0; // Optional
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(computeQueue_, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(computeQueue_);
vkFreeCommandBuffers(logicalDevice_, commandPoolStaging_, 1, &commandBuffer);
}
void readLocalBuffer(VkBuffer aBuffer, uint32_t aSize, void* aOutput)
{
copyBuffer(aBuffer, stagingBufferDst, aSize);
VKHelper::readBuffer(logicalDevice_, aSize, stagingBufferMemoryDst, aOutput);
}
void writeLocalBuffer(VkBuffer aBuffer, uint32_t aSize, void* aInput)
{
VKHelper::writeBuffer(logicalDevice_, aSize, stagingBufferMemorySrc, aInput);
copyBuffer(stagingBufferSrc, aBuffer, aSize);
}
void createCommandBuffer(VkCommandPool& aCommandPool, VkCommandBuffer& aCommandBuffer, std::vector<VkPipelineLayout>& aPipelineLayouts, std::vector<VkPipeline>& aPipelines, /*std::vector<VkQueryPool>&*/ VkQueryPool aQueryPools[])
{
//Timestamp initilize//
VkQueryPoolCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
createInfo.pNext = nullptr;
createInfo.queryType = VK_QUERY_TYPE_TIMESTAMP;
createInfo.queryCount = 2;
for (uint32_t i = 0; i != aPipelineLayouts.size(); ++i)
{
VkResult res = vkCreateQueryPool(logicalDevice_, &createInfo, nullptr, &(aQueryPools[i]));
assert(res == VK_SUCCESS);
}
/*
We are getting closer to the end. In order to send commands to the device(GPU),
we must first record commands into a command buffer.
To allocate a command buffer, we must first create a command pool. So let us do that.
*/
VkCommandPoolCreateInfo commandPoolCreateInfo = {};
commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
commandPoolCreateInfo.flags = 0;
// the queue family of this command pool. All command buffers allocated from this command pool,
// must be submitted to queues of this family ONLY.
commandPoolCreateInfo.queueFamilyIndex = queueFamilyIndex_;
VK_CHECK_RESULT(vkCreateCommandPool(logicalDevice_, &commandPoolCreateInfo, NULL, &aCommandPool));
/*
Now allocate a command buffer from the command pool.
*/
VkCommandBufferAllocateInfo commandBufferAllocateInfo = {};
commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
commandBufferAllocateInfo.commandPool = aCommandPool; // specify the command pool to allocate from.
// if the command buffer is primary, it can be directly submitted to queues.
// A secondary buffer has to be called from some primary command buffer, and cannot be directly
// submitted to a queue. To keep things simple, we use a primary command buffer.
commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandBufferAllocateInfo.commandBufferCount = 1; // allocate a single command buffer.
VK_CHECK_RESULT(vkAllocateCommandBuffers(logicalDevice_, &commandBufferAllocateInfo, &aCommandBuffer)); // allocate command buffer.
/*
Now we shall start recording commands into the newly allocated command buffer.
*/
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; // the buffer is only submitted and used once in this application.
VK_CHECK_RESULT(vkBeginCommandBuffer(aCommandBuffer, &beginInfo)); // start recording commands.
for (uint32_t i = 0; i != aPipelineLayouts.size(); ++i)
{
vkCmdResetQueryPool(aCommandBuffer, aQueryPools[i], 0, 2);
/*
We need to bind a pipeline, AND a descriptor set before we dispatch.
The validation layer will NOT give warnings if you forget these, so be very careful not to forget them.
*/
vkCmdBindDescriptorSets(aCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, aPipelineLayouts[i], 0, 1, &descriptorSet_, 0, NULL);
vkCmdBindPipeline(aCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, aPipelines[i]);
//Include loop and update push constants every iteration//
//vkCmdPushConstants(commandBufferInit_, computePipelineLayouts_[initPopulation], VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t), rotationIndex_);
vkCmdWriteTimestamp(aCommandBuffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, aQueryPools[i], 0);
/*
Calling vkCmdDispatch basically starts the compute pipeline, and executes the compute shader.
The number of workgroups is specified in the arguments.
If you are already familiar with compute shaders from OpenGL, this should be nothing new to you.
*/
vkCmdDispatch(aCommandBuffer, numWorkgroupsX, numWorkgroupsY, numWorkgroupsZ);
vkCmdPipelineBarrier(aCommandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, NULL, 0, NULL, 0, NULL, 0, NULL);
vkCmdWriteTimestamp(aCommandBuffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, aQueryPools[i], 1);
}
VK_CHECK_RESULT(vkEndCommandBuffer(aCommandBuffer)); // end recording commands.
}
};
#endif
| 48.738408
| 458
| 0.799906
|
Harri-Renney
|
f25211b062c96bd4607d269177d7eee4e4c09c4a
| 7,227
|
cpp
|
C++
|
Final/Dataset/B2016_Z2_Z3/student4982.cpp
|
Team-PyRated/PyRated
|
1df171c8a5a98977b7a96ee298a288314d1b1b96
|
[
"MIT"
] | null | null | null |
Final/Dataset/B2016_Z2_Z3/student4982.cpp
|
Team-PyRated/PyRated
|
1df171c8a5a98977b7a96ee298a288314d1b1b96
|
[
"MIT"
] | null | null | null |
Final/Dataset/B2016_Z2_Z3/student4982.cpp
|
Team-PyRated/PyRated
|
1df171c8a5a98977b7a96ee298a288314d1b1b96
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <stdexcept>
#include <vector>
#include <deque>
#include <type_traits>
#include <cmath>
#include <algorithm>
#include <iomanip>
int SumaCifara(long long int x)
{
int suma=0;
while(x!=0)
{
suma+=std::abs(x%10);
x=x/10;
}
return suma;
}
int SumaDjelilaca(long long int x)
{
int suma=0;
if(x<0) x=-x;
for(long long int i=1;i<=x;i++)
{
if(x%i==0) suma+=i;
}
return suma;
}
bool DaLiJeProst(long long int x)
{
if(x<=1) return false;
long long int i=0;
for(i=2;i<=(int)sqrt(x);i++)
{
if(x%i==0) return false;
}
if(i==(int)sqrt(x)+1) return true;
}
int BrojProstihFaktora(long long int x)
{
if(x<=1) return 0;
if(DaLiJeProst(x)==true) return 1;
int i=2, suma=0, n=x;
while(1)
{
if(i==x) break;
if(DaLiJeProst(i)==false) i++;
if(DaLiJeProst(i)==true)
{
if(n==1) break;
if(n%i==0)
{
n=n/i;
suma++;
}
else i++;
}
}
return suma;
}
bool DaLiJeSavrsen(long long int x)
{
int suma=0;
for(long long int i=1;i<x;i++) if(x%i==0) suma+=i;
if(suma==x) return true;
else return false;
}
int BrojSavrsenihDjelilaca(long long int x)
{
if(x<0) x=-x;
int broj=0;
for(long long int i=1;i<=x;i++) if(x%i==0 && DaLiJeSavrsen(i)==true) broj++;
return broj;
}
template <typename Tip1, typename Tip2, typename Tip3, typename Tip4>
auto UvrnutiPresjek(Tip1 p1, Tip1 p2, Tip2 p3, Tip2 p4, Tip3 fun(Tip4)) -> std::vector<std::vector<typename std::remove_reference<decltype((*p1)+(*p3))>::type>>
{
typedef typename std::remove_reference<decltype((*p1)+(*p3))>::type Tip;
std::vector<std::vector<Tip>> matrica;
Tip2 poc2=p3;
while(p1!=p2)
{
while(p3!=p4)
{
if(fun(*p1)==fun(*p3))
{
std::vector<Tip> v;
v.push_back(*p1); v.push_back(*p3); v.push_back(fun(*p1));
matrica.push_back(v);
}
p3++;
}
p3=poc2;
p1++;
}
std::sort(matrica.begin(), matrica.end(), [](std::vector<Tip> x, std::vector<Tip> y) { return x[2]<y[2]; } );
if(matrica.size()>1) {
for(int i=0;i<matrica.size()-1;i++)
{
for(int j=i+1;j<matrica.size();j++)
{
if(matrica[i][2]==matrica[j][2]) std::sort(matrica.begin()+i,matrica.begin()+j+1, [](std::vector<Tip> x, std::vector<Tip> y) { return x[0]<y[0];});
}
}
for(int i=0;i<matrica.size()-1;i++)
{
for(int j=i+1;j<matrica.size();j++)
{
if(matrica[i][0]==matrica[j][0]) std::sort(matrica.begin()+i,matrica.begin()+j+1, [](std::vector<Tip> x, std::vector<Tip> y) { return x[1]<y[1];});
}
}
}
return matrica;
}
template <typename Tip1, typename Tip2>
auto UvrnutiPresjek(Tip1 p1, Tip1 p2, Tip2 p3, Tip2 p4) -> std::vector<std::vector<typename std::remove_reference<decltype((*p1)+(*p3))>::type>>
{
typedef typename std::remove_reference<decltype((*p1)+(*p3))>::type Tip;
std::vector<std::vector<Tip>> matrica;
Tip2 poc=p3;
while(p1!=p2)
{
while(p3!=p4)
{
if(*p1==*p3)
{
std::vector<Tip> v1;
v1.push_back(*p1); v1.push_back(0); v1.push_back(0);
matrica.push_back(v1);
}
p3++;
}
p3=poc;
p1++;
}
std::sort(matrica.begin(), matrica.end(), [] (std::vector<Tip> x, std::vector<Tip> y) { return x[0]<y[0]; });
return matrica;
}
template<typename Tip1, typename Tip2, typename Tip3, typename Tip4>
auto UvrnutaRazlika(Tip1 p1, Tip1 p2, Tip2 p3, Tip2 p4, Tip3 fun(Tip4)) -> std::vector<std::vector<typename std::remove_reference<decltype((*p1)+(*p3))>::type>>
{
typedef typename std::remove_reference<decltype((*p1)+(*p3))>::type Tip;
std::vector<std::vector<Tip>> matrica;
Tip1 poc=p1; Tip2 poc2=p3;
while(p1!=p2)
{
bool par=false;
while(p3!=p4)
{
if(fun(*p1)==fun(*p3)) par=true;
p3++;
}
p3=poc2;
if(par==false)
{
std::vector<Tip> v;
v.push_back(*p1); v.push_back(fun(*p1));
matrica.push_back(v);
}
p1++;
}
p1=poc;
p3=poc2;
while(p3!=p4)
{
bool par=false;
while(p1!=p2)
{
if(fun(*p3)==fun(*p1)) par=true;
p1++;
}
p1=poc;
if(par==false)
{
std::vector<Tip> v;
v.push_back(*p3); v.push_back(fun(*p3));
matrica.push_back(v);
}
p3++;
}
std::sort(matrica.begin(),matrica.end(),[] (std::vector<Tip> x, std::vector<Tip> y) {return x[0]>y[0];} );
if(matrica.size()>1) {
for(int i=0;i<matrica.size()-1;i++)
{
for(int j=i+1;j<matrica.size();j++)
{
if(matrica[i][0]==matrica[j][0]) std::sort(matrica.begin()+i,matrica.begin()+j+1, [] (std::vector<Tip> x, std::vector<Tip> y) {return x[1]>y[1];} );
}
}
}
return matrica;
}
template<typename Tip1, typename Tip2>
auto UvrnutaRazlika(Tip1 p1, Tip1 p2, Tip2 p3, Tip2 p4) -> std::vector<std::vector<typename std::remove_reference<decltype((*p1)+(*p3))>::type>>
{
typedef typename std::remove_reference<decltype((*p1)+(*p3))>::type Tip;
std::vector<std::vector<Tip>> matrica;
Tip1 poc=p1; Tip2 poc2=p3;
while(p1!=p2)
{
bool par=false;
while(p3!=p4)
{
if(*p1==*p3) par=true;
p3++;
}
p3=poc2;
if(par==false)
{
std::vector<Tip> v;
v.push_back(*p1); v.push_back(0);
matrica.push_back(v);
}
p1++;
}
p1=poc;
p3=poc2;
while(p3!=p4)
{
bool par=false;
while(p1!=p2)
{
if(*p3==*p1) par=true;
p1++;
}
p1=poc;
if(par==false)
{
std::vector<Tip> v;
v.push_back(*p3); v.push_back(0);
matrica.push_back(v);
}
p3++;
}
std::sort(matrica.begin(),matrica.end(),[](std::vector<Tip> x, std::vector<Tip> y){return x[0]>y[0];});
return matrica;
}
int main ()
{
try {
std::cout<<"Unesite broj elemenata prvog kontejnera: ";
int n;
std::cin>>n;
std::deque<int> d1;
std::cout<<"Unesite elemente prvog kontejnera: ";
while(d1.size()<n)
{
int x;
std::cin>>x;
if(d1.size()==0) d1.push_back(x);
else
{
bool ponavlja_se=false;
for(int i=0;i<d1.size();i++)
{
if(d1[i]==x)
{
ponavlja_se=true; break;
}
}
if(ponavlja_se==false) d1.push_back(x);
}
}
std::cout<<"Unesite broj elemenata drugog kontejnera: ";
std::deque<int> d2; int k;
std::cin>>k;
std::cout<<"Unesite elemente drugog kontejnera: ";
while(d2.size()<k)
{
int x;
std::cin>>x;
if(d2.size()==0) d2.push_back(x);
else
{
bool ponavlja_se=false;
for(int i=0;i<d2.size();i++)
{
if(d2[i]==x)
{
ponavlja_se=true; break;
}
}
if(ponavlja_se==false) d2.push_back(x);
}
}
std::vector<std::vector<int>> matrica=UvrnutiPresjek(d1.begin(),d1.end(),d2.begin(),d2.end(),SumaCifara);
std::vector<std::vector<int>> matrica2=UvrnutaRazlika(d1.begin(),d1.end(),d2.begin(),d2.end(),BrojProstihFaktora);
std::cout<<"Uvrnuti presjek kontejnera:"<<std::endl;
for(std::vector<int> red: matrica)
{
for(int x: red) std::cout<<std::setw(6)<<x<<" ";
std::cout<<std::endl;
}
std::cout<<"Uvrnuta razlika kontejnera:"<<std::endl;
for(std::vector<int> red: matrica2)
{
for(int x: red) std::cout<<std::setw(6)<<x<<" ";
std::cout<<std::endl;
}
std::cout<<"Dovidjenja!";
return 0;
}
catch(...)
{
std::cout<<"Izuzetak: nedovoljno memorije";
}
}
| 22.100917
| 164
| 0.5705
|
Team-PyRated
|
f255aecf55b084a234b0747fedf0e3de15bf4980
| 7,619
|
cpp
|
C++
|
Necromancer/Terrain.cpp
|
myffx36/RenderingEngine
|
38df29966b3126744fb40c2a97775ae44cea92f9
|
[
"MIT"
] | null | null | null |
Necromancer/Terrain.cpp
|
myffx36/RenderingEngine
|
38df29966b3126744fb40c2a97775ae44cea92f9
|
[
"MIT"
] | null | null | null |
Necromancer/Terrain.cpp
|
myffx36/RenderingEngine
|
38df29966b3126744fb40c2a97775ae44cea92f9
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Terrain.h"
const float height_base = 200.0f;
namespace Necromancer {
Terrain::Terrain(const char* file_name, ID3D11Device* device)
{
std::fstream terrain_file;
terrain_file.open(file_name, std::ios::binary | std::ios::in);
terrain_file.seekg(0, std::ios::beg);
auto start_point = terrain_file.tellg();
terrain_file.seekg(0, std::ios::end);
auto end_point = terrain_file.tellg();
unsigned long file_size = end_point;
m_terrain_size = sqrt(file_size / sizeof(float));
unsigned long data_size = file_size / sizeof(float);
m_data = new float[data_size];
terrain_file.seekg(0, std::ios::beg);
terrain_file.read(reinterpret_cast<char*>(m_data), file_size);
terrain_file.close();
//CImage image;
//const size_t cSize = strlen(file_name) + 1;
//wchar_t* wc = new wchar_t[cSize];
//mbstowcs(wc, file_name, cSize);
//image.Load(wc);
//delete[] wc;
//m_terrain_size = image.GetHeight();
//m_data = new float[image.GetHeight() * image.GetWidth()];
//for (int i = 0; i < image.GetWidth(); ++i) {
// for (int j = 0; j < image.GetHeight(); ++j) {
// int index = i * image.GetHeight() + j;
// m_data[index] = (GetRValue(image.GetPixel(i, j))) / 255.0f;
// }
//}
m_position = nullptr;
m_normal = nullptr;
m_indices = nullptr;
generate_position();
generate_indices();
generate_normal();
generate_vb_ib(device);
}
Terrain::~Terrain()
{
delete[] m_data;
if (m_position) delete[] m_position;
if (m_normal) delete[] m_normal;
if (m_indices) delete[] m_indices;
}
void Terrain::generate_position() {
m_position = new Vec3[m_terrain_size * m_terrain_size];
for (unsigned long i = 0; i < m_terrain_size; ++i) {
for (unsigned long j = 0; j < m_terrain_size; ++j) {
unsigned long offset = (i * m_terrain_size + j);
m_position[offset][0] = static_cast<float>(i);
m_position[offset][1] = height_base * m_data[i * m_terrain_size + j];
m_position[offset][2] = static_cast<float>(j);
}
}
}
void Terrain::generate_normal() {
m_normal = new Vec3[m_terrain_size * m_terrain_size];
for (unsigned long i = 0; i < m_terrain_size * m_terrain_size; ++i) {
m_normal[i] = Vec3(0.0f, 0.0f, 0.0f);
}
unsigned long triangle_num = (m_terrain_size - 1) * (m_terrain_size - 1) * 2;
for (unsigned long i = 0; i < triangle_num; ++i) {
unsigned long index_offset = i * 3;
unsigned long i1 = m_indices[index_offset];
unsigned long i2 = m_indices[index_offset + 1];
unsigned long i3 = m_indices[index_offset + 2];
Vec3 p1 = m_position[i1];
Vec3 p2 = m_position[i2];
Vec3 p3 = m_position[i3];
Vec3 l1 = p2 - p1;
Vec3 l2 = p3 - p2;
Vec3 normal = normalize(cross(l2, l1));
m_normal[i1] = m_normal[i1] + normal;
m_normal[i2] = m_normal[i2] + normal;
m_normal[i3] = m_normal[i3] + normal;
}
for (unsigned long i = 0; i < m_terrain_size * m_terrain_size; ++i) {
m_normal[i] = normalize(m_normal[i]);
}
}
void Terrain::generate_indices() {
unsigned long triangle_num = (m_terrain_size - 1) * (m_terrain_size - 1) * 2;
m_index_number = triangle_num * 3;
m_indices = new unsigned long[m_index_number];
for (unsigned long i = 0; i < m_terrain_size - 1; ++i) {
for (unsigned long j = 0; j < m_terrain_size - 1; ++j) {
unsigned long offset = (i * (m_terrain_size - 1) + j) * 6;
unsigned long left_bottom_index = i * m_terrain_size + j;
unsigned long left_top_index = left_bottom_index + 1;
unsigned long right_bottom_index = left_bottom_index + m_terrain_size;
unsigned long right_top_index = right_bottom_index + 1;
m_indices[offset + 0] = left_bottom_index;
m_indices[offset + 1] = right_bottom_index;
m_indices[offset + 2] = left_top_index;
m_indices[offset + 3] = left_top_index;
m_indices[offset + 4] = right_bottom_index;
m_indices[offset + 5] = right_top_index;
}
}
}
void Terrain::generate_vb_ib(ID3D11Device* d3d_device)
{
float *vertices = new float[8 * m_terrain_size * m_terrain_size];
for (unsigned long i = 0; i < m_terrain_size * m_terrain_size; ++i) {
unsigned long vertices_offset = i * 8;
vertices[vertices_offset + 0] = m_position[i].x;
vertices[vertices_offset + 1] = m_position[i].y;
vertices[vertices_offset + 2] = m_position[i].z;
vertices[vertices_offset + 3] = m_normal[i].x;
vertices[vertices_offset + 4] = m_normal[i].y;
vertices[vertices_offset + 5] = m_normal[i].z;
vertices[vertices_offset + 6] = 0.0f;
vertices[vertices_offset + 7] = 0.0f;
}
D3D11_BUFFER_DESC vb_desc;
ZeroMemory(&vb_desc, sizeof(vb_desc));
vb_desc.ByteWidth = 8 * m_terrain_size * m_terrain_size * sizeof(float);
vb_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vb_desc.CPUAccessFlags = 0;
vb_desc.Usage = D3D11_USAGE_DEFAULT;
vb_desc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA vb_init_data;
vb_init_data.pSysMem = vertices;
vb_init_data.SysMemPitch = 0;
vb_init_data.SysMemSlicePitch = 0;
HRESULT hr = d3d_device->CreateBuffer(&vb_desc, &vb_init_data, &m_vertex_buffer);
delete[]vertices;
D3D11_BUFFER_DESC ib_desc;
ZeroMemory(&vb_desc, sizeof(ib_desc));
ib_desc.ByteWidth = m_index_number * sizeof(unsigned long);
ib_desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
ib_desc.CPUAccessFlags = 0;
ib_desc.Usage = D3D11_USAGE_DEFAULT;
ib_desc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA ib_init_data;
ib_init_data.pSysMem = m_indices;
ib_init_data.SysMemPitch = 0;
ib_init_data.SysMemSlicePitch = 0;
hr = d3d_device->CreateBuffer(&ib_desc, &ib_init_data, &m_index_buffer);
char* vs_data;
unsigned long vs_data_size;
std::ifstream vs_file("VertexShader.cso", std::ios::binary | std::ios::ate);
vs_data_size = static_cast<unsigned long>(vs_file.tellg());
vs_file.seekg(std::ios::beg);
vs_data = new char[vs_data_size];
vs_file.read(vs_data, vs_data_size);
vs_file.close();
hr = d3d_device->CreateVertexShader(vs_data, vs_data_size, nullptr, &m_vertex_shader);
char* ps_data;
unsigned long ps_data_size;
std::ifstream ps_file("PixelShader.cso", std::ios::binary | std::ios::ate);
ps_data_size = static_cast<unsigned long>(ps_file.tellg());
ps_file.seekg(std::ios::beg);
ps_data = new char[ps_data_size];
ps_file.read(ps_data, ps_data_size);
ps_file.close();
hr = d3d_device->CreatePixelShader(ps_data, ps_data_size, nullptr, &m_pixel_shader);
D3D11_INPUT_ELEMENT_DESC input_layout_desc[3];
input_layout_desc[0].SemanticName = "POSITION";
input_layout_desc[0].SemanticIndex = 0;
input_layout_desc[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
input_layout_desc[0].InputSlot = 0;
input_layout_desc[0].AlignedByteOffset = 0;
input_layout_desc[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
input_layout_desc[0].InstanceDataStepRate = 0;
input_layout_desc[1].SemanticName = "NORMAL";
input_layout_desc[1].SemanticIndex = 0;
input_layout_desc[1].Format = DXGI_FORMAT_R32G32B32_FLOAT;
input_layout_desc[1].InputSlot = 0;
input_layout_desc[1].AlignedByteOffset = 3 * sizeof(float);
input_layout_desc[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
input_layout_desc[1].InstanceDataStepRate = 0;
input_layout_desc[2].SemanticName = "TEXCOORD";
input_layout_desc[2].SemanticIndex = 0;
input_layout_desc[2].Format = DXGI_FORMAT_R32G32_FLOAT;
input_layout_desc[2].InputSlot = 0;
input_layout_desc[2].AlignedByteOffset = 6 * sizeof(float);
input_layout_desc[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
input_layout_desc[2].InstanceDataStepRate = 0;
hr = d3d_device->CreateInputLayout(input_layout_desc, 3,
vs_data, vs_data_size, &m_input_layout);
}
}
| 35.110599
| 88
| 0.708229
|
myffx36
|
f25c4187bd60703c16fbcb4709293a8ec00f1145
| 101
|
cpp
|
C++
|
code/code-complete/test.cpp
|
peter-can-talk/cpp-london
|
e232bf98f28b1d8b56af3af23d43a3f565221ab0
|
[
"MIT"
] | 3
|
2017-02-20T23:24:47.000Z
|
2019-09-09T19:15:07.000Z
|
code/code-complete/test.cpp
|
peter-can-talk/cpp-london-2017
|
e232bf98f28b1d8b56af3af23d43a3f565221ab0
|
[
"MIT"
] | null | null | null |
code/code-complete/test.cpp
|
peter-can-talk/cpp-london-2017
|
e232bf98f28b1d8b56af3af23d43a3f565221ab0
|
[
"MIT"
] | null | null | null |
struct X {
/**
* foo does things.
*/
void foo(int x) {
}
};
int main() {
X x;
x.
}
| 7.214286
| 21
| 0.405941
|
peter-can-talk
|
f2609badd8ff348904efaae8ae92b3112507f4fc
| 8,628
|
cpp
|
C++
|
PersonDetection/PersonDetector.cpp
|
vohoaiviet/Human-Detection
|
e34acdab5af81fc2e99d686ada470a114ae3de63
|
[
"MIT"
] | 28
|
2015-04-28T08:45:43.000Z
|
2021-11-15T12:10:12.000Z
|
PersonDetection/PersonDetector.cpp
|
vohoaiviet/Human-Detection
|
e34acdab5af81fc2e99d686ada470a114ae3de63
|
[
"MIT"
] | null | null | null |
PersonDetection/PersonDetector.cpp
|
vohoaiviet/Human-Detection
|
e34acdab5af81fc2e99d686ada470a114ae3de63
|
[
"MIT"
] | 28
|
2015-04-07T04:02:07.000Z
|
2019-03-31T17:55:42.000Z
|
#include "StdAfx.h"
#include "PersonDetector.h"
#include <math.h>
PersonDetector::PersonDetector()
{
m_cell = cvSize(8, 8);
m_block = cvSize(2, 2);
m_winSize = cvSize(64, 128);
m_stepOverlap = 1;
classifier.SetParams(m_cell, m_block , m_stepOverlap);
startScale = 1;
scaleStep = 1.5;
m_widthStep = 8;
m_heigthStep = 8;
svmTrainPath = "Dataset/small train/TrainSVM.xml";
}
void PersonDetector::setParams(CvSize cell, CvSize block, float stepOverLap)
{
m_cell = cell;
m_block = block;
m_stepOverlap = stepOverLap;
classifier.SetParams(cell, block , stepOverLap);
}
void PersonDetector::setSVMTrainPath(char* path)
{
svmTrainPath = path;
classifier.loadTrainSVM(path);
}
int PersonDetector::DetectPosWindows(IplImage* img)
{
int nWins = 0;
return nWins;
}
/// Ham detect people multiscale
// Params: srcImgPath: Duong dan toi file anh test
// Return value: so luong nguoi detect duoc
IplImage* PersonDetector::DetectMultiScale(char* srcImgPath)
{
int count = 0;
IplImage* srcImg = cvLoadImage(srcImgPath, 1);
CvSize size = cvGetSize(srcImg);
//
vector<IntegralScale*> integralsScale;
//
if (size.width > 400)
{
//IplImage* dst = cvCreateImage(cvSize((int)(srcImg->width / 2), (int)(srcImg->height / 2)),
// srcImg->depth, srcImg->nChannels);
//cvResize(srcImg, dst);
//cvReleaseImage(&srcImg);
//srcImg = cvCloneImage(dst);
startScale = 2.5;
}
else if (size.width > 300)
{
startScale = 2;
}
// Tinh toan so buoc scale anh
endScale = min((float)size.width / m_winSize.width, (float)size.height / m_winSize.height);
nScaleStep = floor(log(endScale / startScale) / log(scaleStep) + 1);
// Khoi tao kich thuoc scale ban dau
float scale = startScale;
// Duyet qua tat ca cac muc scale
for (int k = 0; k <= nScaleStep; k++)
{
IplImage* input = NULL;
if (k == nScaleStep)
{
// Kiem tra neu buoc scale truoc do da cho ti le anh input bang ti le cua so thi
if ((int)(srcImg->width / scale) == m_winSize.width &&
(int)(srcImg->height / scale) == m_winSize.height)
break;
else // Nguoc lai thuc hien them 1 lan test voi kich thuoc anh scale bang dung kich thuoc cua so
input = cvCreateImage(cvSize((int)(m_winSize.width), (int)(m_winSize.height)),
srcImg->depth, srcImg->nChannels);
}
else
{
input = cvCreateImage(cvSize((int)(srcImg->width / scale), (int)(srcImg->height / scale)),
srcImg->depth, srcImg->nChannels);
}
cvResize(srcImg, input);
int x = 0;
int y = 0;
int nBins = classifier.hog.NumOfBins;
IplImage** integrals = classifier.calcIntegralHOG(input);
// add integral image + scale vao list
IntegralScale *integralScaleImage = new IntegralScale(integrals, scale);
integralsScale.push_back(integralScaleImage);
//
IplImage** integralsInput = (IplImage**)malloc(nBins * sizeof(IplImage*));
while(y + m_winSize.height <= integrals[0]->height)
{
x = 0;
while (x + m_winSize.width <= integrals[0]->width)
{
// set region of interest
for (int i = 0; i < nBins; i++)
{
cvSetImageROI(integrals[i], cvRect(x, y, m_winSize.width + 1, m_winSize.height + 1));
integralsInput[i] = cvCreateImage(cvGetSize(integrals[i]),integrals[i]->depth, integrals[i]->nChannels);
cvCopy(integrals[i], integralsInput[i], NULL);
}
//IplImage *img = cvCreateImage(cvGetSize(input),input->depth, input->nChannels);
// copy subimage
//cvCopy(input, img, NULL);
float weight = classifier.testSVM(svmTrainPath, integralsInput, NULL);
if (weight != 2) // -2.4115036f)
{
ScanWindow *window = new ScanWindow(x, y, scale, 64, 128); // changed 3rd parameter from 1 to scale
window->setWeight(weight);
m_detectedWindows.push_back(window);
}
for (int i = 0; i < nBins; i++)
cvResetImageROI(integrals[i]);
x += m_widthStep;
//cvReleaseImage(&img);
for (int i = 0; i < nBins; i++)
cvReleaseImage(&integralsInput[i]);
}
y += m_heigthStep;
}
for (int i = 0; i < nBins; i++)
cvReleaseImage(&integrals[i]);
free(integrals);
free(integralsInput);
cvReleaseImage(&input);
scale *= scaleStep;
}
// PHAN LOCALIZATION
// Input: tap cac cua so o cac muc scale da detect duoc tren anh test input
// Output: tra ra tap cac cua so da HOI TU
int numberWindows = -1;
OverlappingDetection *overlapDetector;
vector<CvMat*> boundaryList;
while (true)
{
overlapDetector = new OverlappingDetection(&m_detectedWindows);
// cluster nhung cum cua so overlap len nhau
overlapDetector->clusterWindows();
for (int i = 0; i < overlapDetector->_clusteredWindows.size(); i++)
{
// doi voi moi cum, tao ra mot doi tuong localization de localize
ScanWindow** listOverlapped = new ScanWindow*[overlapDetector->_clusteredWindows[i].size()];
for (int j = 0; j < overlapDetector->_clusteredWindows[i].size(); j++)
{
listOverlapped[j] = m_detectedWindows[overlapDetector->_clusteredWindows[i][j]];
}
//Localisation *localize = new Localisation(overlapDetector->_clusteredWindows[i], m_widthStep, m_heigthStep, log(1.03), scaleStep, &classifier, svmTrainPath, srcImg, integralsScale);
Localisation *localize = new Localisation(listOverlapped, m_widthStep, m_heigthStep, log(1.03), scaleStep, &classifier, svmTrainPath, srcImg, integralsScale);
//localize->_detectedWindows = overlapDetector->_clusteredWindows[i];
// tinh toan cua so cuoi cung de tim boundary
localize->localize2(overlapDetector->_clusteredWindows[i].size());
// lay ra boundary
boundaryList.push_back(localize->_finalLocalisationWindow);
for (int j = 0; j < overlapDetector->_clusteredWindows[i].size(); j++)
{
delete listOverlapped[j];
}
delete listOverlapped;
delete localize;
}
if (boundaryList.size() == numberWindows)
{
break;
}
else
{
numberWindows = boundaryList.size();
// huy vung nho
m_detectedWindows.clear();
for (int i = 0; i < boundaryList.size(); i++)
{
float scaleWindow = cvGetReal2D(boundaryList[i], 2, 0);
int x = (int) cvGetReal2D(boundaryList[i], 0, 0);
int y = (int) cvGetReal2D(boundaryList[i], 1, 0);
x = (int) x / scaleWindow;
y = (int) y/ scaleWindow;
ScanWindow* window = new ScanWindow(x, y, scaleWindow, 64, 128);
m_detectedWindows.push_back(window);
}
//
for (int i = 0; i < boundaryList.size(); i++)
{
cvReleaseMat(&boundaryList[i]);
}
free(overlapDetector);
boundaryList.clear();
}
}
// ket thuc phan localization
// Ve Bounding box o day, su dung danh sach boundaryList
// Trong do, cua so thu i bao gom
// x = cvGetReal2D(boundaryList[i], 0, 0)
// y = cvGetReal2D(boundaryList[i], 1, 0)
// scale = cvGetReal2D(boundaryList[i], 2, 0)
IplImage* resultImage = cvCloneImage(srcImg);
float scaleWindow;
int x, y;
float width, height;
for (int i = 0; i < boundaryList.size(); i++)
{
//scaleWindow = pow(10, (float) cvGetReal2D(boundaryList[i], 2, 0));
//scaleWindow = exp((float) cvGetReal2D(boundaryList[i], 2, 0));
scaleWindow = cvGetReal2D(boundaryList[i], 2, 0);
x = (int) cvGetReal2D(boundaryList[i], 0, 0);
y = (int) cvGetReal2D(boundaryList[i], 1, 0);
//
//
width = 64 * scaleWindow;
height = 128 * scaleWindow;
cvRectangle(resultImage, cvPoint(x, y), cvPoint(x + (int) width, y + (int) height), cvScalar(0, 255, 255, 0), 2, 8, 0);
}
//float scaleWindow;
//int x, y;
//int width, height;
//for (int i = 0; i < m_detectedWindows.size(); i++)
//{
// //scaleWindow = pow(10, (float) cvGetReal2D(boundaryList[i], 2, 0));
// scaleWindow = m_detectedWindows[i]->getScale();
// x = (int) m_detectedWindows[i]->getXCoordinate();
// y = (int) m_detectedWindows[i]->getYCoordinate();
// width = 64 * scaleWindow;
// height = 128 * scaleWindow;
// cvRectangle(resultImage, cvPoint(x, y), cvPoint(x + (int) width, y + (int) height), cvScalar(0, 255, 255, 0), 2, 8, 0);
//
//}
/*string sFile(srcImgPath);
int pos = sFile.find_last_of('/');
string sFileOut = sFile.substr(pos + 1, sFile.length() - pos - 1);
sFileOut = "Result/neg/" + sFileOut;
cvSaveImage(sFileOut.c_str(), resultImage, 0);
cvReleaseImage(&resultImage);*/
// ket thuc ve bounding box
//count = m_detectedWindows.size();
count = boundaryList.size();
// huy vung nho
for (int i = 0; i < boundaryList.size(); i++)
{
cvReleaseMat(&boundaryList[i]);
}
if (srcImg != NULL)
cvReleaseImage(&srcImg);
// free vung nho
free(overlapDetector);
boundaryList.clear();
integralsScale.clear();
m_detectedWindows.clear();
return resultImage;
}
| 28.104235
| 186
| 0.663421
|
vohoaiviet
|
f260cce44c1ea4cd63b4a99908bfd536b9922ccb
| 618
|
cpp
|
C++
|
src/game/LevelListLoader.cpp
|
ArthurSonzogni/InTheCube
|
c4a35096d962d23f6211802970ee44f77d29e38a
|
[
"MIT"
] | 4
|
2019-12-31T07:58:54.000Z
|
2021-09-07T18:16:51.000Z
|
src/game/LevelListLoader.cpp
|
ArthurSonzogni/InTheCube
|
c4a35096d962d23f6211802970ee44f77d29e38a
|
[
"MIT"
] | null | null | null |
src/game/LevelListLoader.cpp
|
ArthurSonzogni/InTheCube
|
c4a35096d962d23f6211802970ee44f77d29e38a
|
[
"MIT"
] | 2
|
2020-02-17T12:47:33.000Z
|
2021-09-07T18:16:52.000Z
|
// Copyright 2020 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include "game/LevelListLoader.hpp"
#include <fstream>
#include <iostream>
#include "game/Resource.hpp"
std::vector<std::string> LevelListLoader() {
std::ifstream file(ResourcePath() + "/lvl/LevelList");
if (!file) {
std::cerr << "No level list file" << std::endl;
return {};
}
std::vector<std::string> result;
std::string line;
while (getline(file, line)) {
result.push_back(ResourcePath() + "/lvl/" + line);
}
return result;
}
| 23.769231
| 78
| 0.669903
|
ArthurSonzogni
|
f26663b27836b964aeaa957327dbff9365075dc0
| 12,757
|
cpp
|
C++
|
bin/windows/cpp/obj/src/openfl/display/Tilesheet.cpp
|
DrSkipper/twogames
|
916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b
|
[
"MIT"
] | null | null | null |
bin/windows/cpp/obj/src/openfl/display/Tilesheet.cpp
|
DrSkipper/twogames
|
916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b
|
[
"MIT"
] | null | null | null |
bin/windows/cpp/obj/src/openfl/display/Tilesheet.cpp
|
DrSkipper/twogames
|
916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b
|
[
"MIT"
] | null | null | null |
#include <hxcpp.h>
#ifndef INCLUDED_flash_Lib
#include <flash/Lib.h>
#endif
#ifndef INCLUDED_flash_display_BitmapData
#include <flash/display/BitmapData.h>
#endif
#ifndef INCLUDED_flash_display_Graphics
#include <flash/display/Graphics.h>
#endif
#ifndef INCLUDED_flash_display_IBitmapDrawable
#include <flash/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_flash_geom_Point
#include <flash/geom/Point.h>
#endif
#ifndef INCLUDED_flash_geom_Rectangle
#include <flash/geom/Rectangle.h>
#endif
#ifndef INCLUDED_openfl_display_Tilesheet
#include <openfl/display/Tilesheet.h>
#endif
namespace openfl{
namespace display{
Void Tilesheet_obj::__construct(::flash::display::BitmapData image)
{
HX_STACK_PUSH("Tilesheet::new","openfl/display/Tilesheet.hx",36);
{
HX_STACK_LINE(38)
this->__bitmap = image;
HX_STACK_LINE(39)
this->__handle = ::openfl::display::Tilesheet_obj::lime_tilesheet_create(image->__handle);
HX_STACK_LINE(41)
this->_bitmapWidth = this->__bitmap->get_width();
HX_STACK_LINE(42)
this->_bitmapHeight = this->__bitmap->get_height();
HX_STACK_LINE(44)
this->_tilePoints = Array_obj< ::Dynamic >::__new();
HX_STACK_LINE(45)
this->_tiles = Array_obj< ::Dynamic >::__new();
HX_STACK_LINE(46)
this->_tileUVs = Array_obj< ::Dynamic >::__new();
}
;
return null();
}
Tilesheet_obj::~Tilesheet_obj() { }
Dynamic Tilesheet_obj::__CreateEmpty() { return new Tilesheet_obj; }
hx::ObjectPtr< Tilesheet_obj > Tilesheet_obj::__new(::flash::display::BitmapData image)
{ hx::ObjectPtr< Tilesheet_obj > result = new Tilesheet_obj();
result->__construct(image);
return result;}
Dynamic Tilesheet_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< Tilesheet_obj > result = new Tilesheet_obj();
result->__construct(inArgs[0]);
return result;}
::flash::geom::Rectangle Tilesheet_obj::getTileUVs( int index){
HX_STACK_PUSH("Tilesheet::getTileUVs","openfl/display/Tilesheet.hx",77);
HX_STACK_THIS(this);
HX_STACK_ARG(index,"index");
HX_STACK_LINE(77)
return this->_tileUVs->__get(index).StaticCast< ::flash::geom::Rectangle >();
}
HX_DEFINE_DYNAMIC_FUNC1(Tilesheet_obj,getTileUVs,return )
::flash::geom::Rectangle Tilesheet_obj::getTileRect( int index){
HX_STACK_PUSH("Tilesheet::getTileRect","openfl/display/Tilesheet.hx",73);
HX_STACK_THIS(this);
HX_STACK_ARG(index,"index");
HX_STACK_LINE(73)
return this->_tiles->__get(index).StaticCast< ::flash::geom::Rectangle >();
}
HX_DEFINE_DYNAMIC_FUNC1(Tilesheet_obj,getTileRect,return )
::flash::geom::Point Tilesheet_obj::getTileCenter( int index){
HX_STACK_PUSH("Tilesheet::getTileCenter","openfl/display/Tilesheet.hx",69);
HX_STACK_THIS(this);
HX_STACK_ARG(index,"index");
HX_STACK_LINE(69)
return this->_tilePoints->__get(index).StaticCast< ::flash::geom::Point >();
}
HX_DEFINE_DYNAMIC_FUNC1(Tilesheet_obj,getTileCenter,return )
Void Tilesheet_obj::drawTiles( ::flash::display::Graphics graphics,Array< Float > tileData,hx::Null< bool > __o_smooth,hx::Null< int > __o_flags){
bool smooth = __o_smooth.Default(false);
int flags = __o_flags.Default(0);
HX_STACK_PUSH("Tilesheet::drawTiles","openfl/display/Tilesheet.hx",62);
HX_STACK_THIS(this);
HX_STACK_ARG(graphics,"graphics");
HX_STACK_ARG(tileData,"tileData");
HX_STACK_ARG(smooth,"smooth");
HX_STACK_ARG(flags,"flags");
{
HX_STACK_LINE(62)
graphics->drawTiles(hx::ObjectPtr<OBJ_>(this),tileData,smooth,flags);
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC4(Tilesheet_obj,drawTiles,(void))
int Tilesheet_obj::addTileRect( ::flash::geom::Rectangle rectangle,::flash::geom::Point centerPoint){
HX_STACK_PUSH("Tilesheet::addTileRect","openfl/display/Tilesheet.hx",51);
HX_STACK_THIS(this);
HX_STACK_ARG(rectangle,"rectangle");
HX_STACK_ARG(centerPoint,"centerPoint");
HX_STACK_LINE(53)
this->_tiles->push(rectangle);
HX_STACK_LINE(54)
if (((centerPoint == null()))){
HX_STACK_LINE(54)
this->_tilePoints->push(::openfl::display::Tilesheet_obj::defaultRatio);
}
else{
HX_STACK_LINE(55)
this->_tilePoints->push(::flash::geom::Point_obj::__new((Float(centerPoint->x) / Float(rectangle->width)),(Float(centerPoint->y) / Float(rectangle->height))));
}
HX_STACK_LINE(56)
this->_tileUVs->push(::flash::geom::Rectangle_obj::__new((Float(rectangle->get_left()) / Float(this->_bitmapWidth)),(Float(rectangle->get_top()) / Float(this->_bitmapHeight)),(Float(rectangle->get_right()) / Float(this->_bitmapWidth)),(Float(rectangle->get_bottom()) / Float(this->_bitmapHeight))));
HX_STACK_LINE(57)
return ::openfl::display::Tilesheet_obj::lime_tilesheet_add_rect(this->__handle,rectangle,centerPoint);
}
HX_DEFINE_DYNAMIC_FUNC2(Tilesheet_obj,addTileRect,return )
int Tilesheet_obj::TILE_SCALE;
int Tilesheet_obj::TILE_ROTATION;
int Tilesheet_obj::TILE_RGB;
int Tilesheet_obj::TILE_ALPHA;
int Tilesheet_obj::TILE_TRANS_2x2;
int Tilesheet_obj::TILE_BLEND_NORMAL;
int Tilesheet_obj::TILE_BLEND_ADD;
int Tilesheet_obj::TILE_BLEND_MULTIPLY;
int Tilesheet_obj::TILE_BLEND_SCREEN;
::flash::geom::Point Tilesheet_obj::defaultRatio;
Dynamic Tilesheet_obj::lime_tilesheet_create;
Dynamic Tilesheet_obj::lime_tilesheet_add_rect;
Tilesheet_obj::Tilesheet_obj()
{
}
void Tilesheet_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(Tilesheet);
HX_MARK_MEMBER_NAME(_tileUVs,"_tileUVs");
HX_MARK_MEMBER_NAME(_tiles,"_tiles");
HX_MARK_MEMBER_NAME(_tilePoints,"_tilePoints");
HX_MARK_MEMBER_NAME(_bitmapWidth,"_bitmapWidth");
HX_MARK_MEMBER_NAME(_bitmapHeight,"_bitmapHeight");
HX_MARK_MEMBER_NAME(__handle,"__handle");
HX_MARK_MEMBER_NAME(__bitmap,"__bitmap");
HX_MARK_END_CLASS();
}
void Tilesheet_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(_tileUVs,"_tileUVs");
HX_VISIT_MEMBER_NAME(_tiles,"_tiles");
HX_VISIT_MEMBER_NAME(_tilePoints,"_tilePoints");
HX_VISIT_MEMBER_NAME(_bitmapWidth,"_bitmapWidth");
HX_VISIT_MEMBER_NAME(_bitmapHeight,"_bitmapHeight");
HX_VISIT_MEMBER_NAME(__handle,"__handle");
HX_VISIT_MEMBER_NAME(__bitmap,"__bitmap");
}
Dynamic Tilesheet_obj::__Field(const ::String &inName,bool inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"_tiles") ) { return _tiles; }
break;
case 8:
if (HX_FIELD_EQ(inName,"_tileUVs") ) { return _tileUVs; }
if (HX_FIELD_EQ(inName,"__handle") ) { return __handle; }
if (HX_FIELD_EQ(inName,"__bitmap") ) { return __bitmap; }
break;
case 9:
if (HX_FIELD_EQ(inName,"drawTiles") ) { return drawTiles_dyn(); }
break;
case 10:
if (HX_FIELD_EQ(inName,"getTileUVs") ) { return getTileUVs_dyn(); }
break;
case 11:
if (HX_FIELD_EQ(inName,"getTileRect") ) { return getTileRect_dyn(); }
if (HX_FIELD_EQ(inName,"addTileRect") ) { return addTileRect_dyn(); }
if (HX_FIELD_EQ(inName,"_tilePoints") ) { return _tilePoints; }
break;
case 12:
if (HX_FIELD_EQ(inName,"defaultRatio") ) { return defaultRatio; }
if (HX_FIELD_EQ(inName,"_bitmapWidth") ) { return _bitmapWidth; }
break;
case 13:
if (HX_FIELD_EQ(inName,"getTileCenter") ) { return getTileCenter_dyn(); }
if (HX_FIELD_EQ(inName,"_bitmapHeight") ) { return _bitmapHeight; }
break;
case 21:
if (HX_FIELD_EQ(inName,"lime_tilesheet_create") ) { return lime_tilesheet_create; }
break;
case 23:
if (HX_FIELD_EQ(inName,"lime_tilesheet_add_rect") ) { return lime_tilesheet_add_rect; }
}
return super::__Field(inName,inCallProp);
}
Dynamic Tilesheet_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"_tiles") ) { _tiles=inValue.Cast< Array< ::Dynamic > >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"_tileUVs") ) { _tileUVs=inValue.Cast< Array< ::Dynamic > >(); return inValue; }
if (HX_FIELD_EQ(inName,"__handle") ) { __handle=inValue.Cast< Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"__bitmap") ) { __bitmap=inValue.Cast< ::flash::display::BitmapData >(); return inValue; }
break;
case 11:
if (HX_FIELD_EQ(inName,"_tilePoints") ) { _tilePoints=inValue.Cast< Array< ::Dynamic > >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"defaultRatio") ) { defaultRatio=inValue.Cast< ::flash::geom::Point >(); return inValue; }
if (HX_FIELD_EQ(inName,"_bitmapWidth") ) { _bitmapWidth=inValue.Cast< int >(); return inValue; }
break;
case 13:
if (HX_FIELD_EQ(inName,"_bitmapHeight") ) { _bitmapHeight=inValue.Cast< int >(); return inValue; }
break;
case 21:
if (HX_FIELD_EQ(inName,"lime_tilesheet_create") ) { lime_tilesheet_create=inValue.Cast< Dynamic >(); return inValue; }
break;
case 23:
if (HX_FIELD_EQ(inName,"lime_tilesheet_add_rect") ) { lime_tilesheet_add_rect=inValue.Cast< Dynamic >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void Tilesheet_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_CSTRING("_tileUVs"));
outFields->push(HX_CSTRING("_tiles"));
outFields->push(HX_CSTRING("_tilePoints"));
outFields->push(HX_CSTRING("_bitmapWidth"));
outFields->push(HX_CSTRING("_bitmapHeight"));
outFields->push(HX_CSTRING("__handle"));
outFields->push(HX_CSTRING("__bitmap"));
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
HX_CSTRING("TILE_SCALE"),
HX_CSTRING("TILE_ROTATION"),
HX_CSTRING("TILE_RGB"),
HX_CSTRING("TILE_ALPHA"),
HX_CSTRING("TILE_TRANS_2x2"),
HX_CSTRING("TILE_BLEND_NORMAL"),
HX_CSTRING("TILE_BLEND_ADD"),
HX_CSTRING("TILE_BLEND_MULTIPLY"),
HX_CSTRING("TILE_BLEND_SCREEN"),
HX_CSTRING("defaultRatio"),
HX_CSTRING("lime_tilesheet_create"),
HX_CSTRING("lime_tilesheet_add_rect"),
String(null()) };
static ::String sMemberFields[] = {
HX_CSTRING("getTileUVs"),
HX_CSTRING("getTileRect"),
HX_CSTRING("getTileCenter"),
HX_CSTRING("drawTiles"),
HX_CSTRING("addTileRect"),
HX_CSTRING("_tileUVs"),
HX_CSTRING("_tiles"),
HX_CSTRING("_tilePoints"),
HX_CSTRING("_bitmapWidth"),
HX_CSTRING("_bitmapHeight"),
HX_CSTRING("__handle"),
HX_CSTRING("__bitmap"),
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(Tilesheet_obj::__mClass,"__mClass");
HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_SCALE,"TILE_SCALE");
HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_ROTATION,"TILE_ROTATION");
HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_RGB,"TILE_RGB");
HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_ALPHA,"TILE_ALPHA");
HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_TRANS_2x2,"TILE_TRANS_2x2");
HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_NORMAL,"TILE_BLEND_NORMAL");
HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_ADD,"TILE_BLEND_ADD");
HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_MULTIPLY,"TILE_BLEND_MULTIPLY");
HX_MARK_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_SCREEN,"TILE_BLEND_SCREEN");
HX_MARK_MEMBER_NAME(Tilesheet_obj::defaultRatio,"defaultRatio");
HX_MARK_MEMBER_NAME(Tilesheet_obj::lime_tilesheet_create,"lime_tilesheet_create");
HX_MARK_MEMBER_NAME(Tilesheet_obj::lime_tilesheet_add_rect,"lime_tilesheet_add_rect");
};
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(Tilesheet_obj::__mClass,"__mClass");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_SCALE,"TILE_SCALE");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_ROTATION,"TILE_ROTATION");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_RGB,"TILE_RGB");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_ALPHA,"TILE_ALPHA");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_TRANS_2x2,"TILE_TRANS_2x2");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_NORMAL,"TILE_BLEND_NORMAL");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_ADD,"TILE_BLEND_ADD");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_MULTIPLY,"TILE_BLEND_MULTIPLY");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::TILE_BLEND_SCREEN,"TILE_BLEND_SCREEN");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::defaultRatio,"defaultRatio");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::lime_tilesheet_create,"lime_tilesheet_create");
HX_VISIT_MEMBER_NAME(Tilesheet_obj::lime_tilesheet_add_rect,"lime_tilesheet_add_rect");
};
Class Tilesheet_obj::__mClass;
void Tilesheet_obj::__register()
{
hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("openfl.display.Tilesheet"), hx::TCanCast< Tilesheet_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics, sVisitStatics);
}
void Tilesheet_obj::__boot()
{
TILE_SCALE= (int)1;
TILE_ROTATION= (int)2;
TILE_RGB= (int)4;
TILE_ALPHA= (int)8;
TILE_TRANS_2x2= (int)16;
TILE_BLEND_NORMAL= (int)0;
TILE_BLEND_ADD= (int)65536;
TILE_BLEND_MULTIPLY= (int)131072;
TILE_BLEND_SCREEN= (int)262144;
defaultRatio= ::flash::geom::Point_obj::__new((int)0,(int)0);
lime_tilesheet_create= ::flash::Lib_obj::load(HX_CSTRING("lime"),HX_CSTRING("lime_tilesheet_create"),(int)1);
lime_tilesheet_add_rect= ::flash::Lib_obj::load(HX_CSTRING("lime"),HX_CSTRING("lime_tilesheet_add_rect"),(int)3);
}
} // end namespace openfl
} // end namespace display
| 35.143251
| 300
| 0.767108
|
DrSkipper
|
f26798529f0a2c0bbae58fdf5292113f7510975c
| 431
|
cpp
|
C++
|
src/mesh/mesh.cpp
|
ycjungSubhuman/Kinect-Face
|
b582bd8572e998617b5a0d197b4ac9bd4a9b42be
|
[
"CNRI-Python"
] | 7
|
2018-08-12T22:05:26.000Z
|
2021-05-14T08:39:32.000Z
|
src/mesh/mesh.cpp
|
ycjungSubhuman/Kinect-Face
|
b582bd8572e998617b5a0d197b4ac9bd4a9b42be
|
[
"CNRI-Python"
] | null | null | null |
src/mesh/mesh.cpp
|
ycjungSubhuman/Kinect-Face
|
b582bd8572e998617b5a0d197b4ac9bd4a9b42be
|
[
"CNRI-Python"
] | 2
|
2019-02-14T08:29:16.000Z
|
2019-03-01T07:11:17.000Z
|
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "mesh/mesh.h"
namespace telef::mesh {
void ColorMesh::applyTransform(Eigen::MatrixXf transform) {
Eigen::Map<Eigen::Matrix3Xf> v(position.data(), 3, position.size() / 3);
Eigen::Matrix3Xf result =
(transform * v.colwise().homogeneous()).colwise().hnormalized();
position = Eigen::Map<Eigen::VectorXf>{result.data(), result.size()};
}
} // namespace telef::mesh
| 33.153846
| 74
| 0.698376
|
ycjungSubhuman
|
f26b97db07cd2c2457a94eb2ed16d8becd085010
| 963
|
cpp
|
C++
|
package/statistics/statistics_gateway/deprecated/btp_deprecated_gateway_multiton.cpp
|
mambaru/wfc_core
|
0c3e7fba82a9bb1580582968efae02ef7fabc87a
|
[
"MIT"
] | null | null | null |
package/statistics/statistics_gateway/deprecated/btp_deprecated_gateway_multiton.cpp
|
mambaru/wfc_core
|
0c3e7fba82a9bb1580582968efae02ef7fabc87a
|
[
"MIT"
] | 5
|
2019-12-06T01:01:01.000Z
|
2021-04-20T21:16:34.000Z
|
package/statistics/statistics_gateway/deprecated/btp_deprecated_gateway_multiton.cpp
|
mambaru/wfc_core
|
0c3e7fba82a9bb1580582968efae02ef7fabc87a
|
[
"MIT"
] | null | null | null |
//
// Author: Vladimir Migashko <migashko@gmail.com>, (C) 2013-2015
//
// Copyright: See COPYING file that comes with this distribution
//
#include "btp_deprecated_gateway_multiton.hpp"
#include "btp_deprecated_gateway.hpp"
#include <wfc/module/multiton.hpp>
#include <wfc/module/instance.hpp>
#include <wfc/name.hpp>
namespace wfc{ namespace core{
namespace {
WFC_NAME2(component_name, "btp-deprecated-gateway")
class impl
: public ::wfc::jsonrpc::gateway_multiton<
component_name,
gateway::btp_deprecated_method_list,
gateway::btp_deprecated_interface
>
{
public:
virtual std::string interface_name() const override
{
return std::string("wfc::btp::ibtp");
}
virtual std::string description() const override
{
return "Gateway for BTP system";
}
};
}
btp_deprecated_gateway_multiton::btp_deprecated_gateway_multiton()
: wfc::component( std::make_shared<impl>() )
{
}
}}
| 20.934783
| 66
| 0.695742
|
mambaru
|
f26c536c9a9135d1e2875932cd0d32332bcb451f
| 3,571
|
cpp
|
C++
|
game-emu-common/src/binarytreememorymap.cpp
|
Dudejoe870/game-emu
|
153b7f9b7bc56042cc6d41187688aa1d9a612830
|
[
"MIT"
] | 1
|
2022-03-28T21:03:10.000Z
|
2022-03-28T21:03:10.000Z
|
game-emu-common/src/binarytreememorymap.cpp
|
Dudejoe870/game-emu
|
153b7f9b7bc56042cc6d41187688aa1d9a612830
|
[
"MIT"
] | null | null | null |
game-emu-common/src/binarytreememorymap.cpp
|
Dudejoe870/game-emu
|
153b7f9b7bc56042cc6d41187688aa1d9a612830
|
[
"MIT"
] | null | null | null |
#include <game-emu/common/physicalmemorymap.h>
namespace GameEmu::Common
{
PhysicalMemoryMap::Entry* BinaryTreeMemoryMap::Map(u8* hostReadMemory, u8* hostWriteMemory, u64 size, u64 baseAddress,
Entry::ReadEventFunction readEvent, Entry::WriteEventFunction writeEvent)
{
entries.push_back(Entry(baseAddress &addressMask, hostReadMemory, hostWriteMemory, size, readEvent, writeEvent));
return &entries[entries.size() - 1];
}
void BinaryTreeMemoryMap::Unmap(const Entry* entry)
{
std::vector<Entry>::iterator entryIndex = std::find(entries.begin(), entries.end(), *entry);
if (entryIndex == entries.end()) return;
entries.erase(entryIndex);
}
std::shared_ptr<BinaryTreeMemoryMap::BinaryTree::Node> BinaryTreeMemoryMap::sortedVectorToBinaryTree(std::vector<Entry>& entries, s64 start, s64 end)
{
if (start > end)
return nullptr;
else if (start == end)
return std::make_shared<BinaryTree::Node>(entries[start]);
s64 mid = (start + end) / 2;
std::shared_ptr<BinaryTree::Node> root = std::make_shared<BinaryTree::Node>(entries[mid]);
root->left = sortedVectorToBinaryTree(entries, start, mid - 1);
root->right = sortedVectorToBinaryTree(entries, mid + 1, end);
return root;
}
void BinaryTreeMemoryMap::Update()
{
if (!entries.empty())
{
std::sort(entries.begin(), entries.end());
// Rebalance the Binary Search Tree
tree.root = sortedVectorToBinaryTree(entries, 0, entries.size() - 1);
}
}
/*
8-bit Write
*/
void BinaryTreeMemoryMap::WriteU8(u8 value, u64 address)
{
WriteImpl<u8, std::endian::native>(static_cast<u64>(value), address);
}
/*
8-bit Read
*/
u8 BinaryTreeMemoryMap::ReadU8(u64 address)
{
return static_cast<u8>(ReadImpl<u8, std::endian::native>(address));
}
/*
16-bit Write
*/
void BinaryTreeMemoryMap::WriteU16BigEndianImpl(u16 value, u64 address)
{
WriteImpl<u16, std::endian::big>(static_cast<u64>(value), address);
}
void BinaryTreeMemoryMap::WriteU16LittleEndianImpl(u16 value, u64 address)
{
WriteImpl<u16, std::endian::little>(static_cast<u64>(value), address);
}
/*
16-bit Read
*/
u16 BinaryTreeMemoryMap::ReadU16BigEndianImpl(u64 address)
{
return static_cast<u16>(ReadImpl<u16, std::endian::big>(address));
}
u16 BinaryTreeMemoryMap::ReadU16LittleEndianImpl(u64 address)
{
return static_cast<u16>(ReadImpl<u16, std::endian::little>(address));
}
/*
32-bit Write
*/
void BinaryTreeMemoryMap::WriteU32BigEndianImpl(u32 value, u64 address)
{
WriteImpl<u32, std::endian::big>(static_cast<u64>(value), address);
}
void BinaryTreeMemoryMap::WriteU32LittleEndianImpl(u32 value, u64 address)
{
WriteImpl<u32, std::endian::little>(static_cast<u64>(value), address);
}
/*
32-bit Read
*/
u32 BinaryTreeMemoryMap::ReadU32BigEndianImpl(u64 address)
{
return static_cast<u32>(ReadImpl<u32, std::endian::big>(address));
}
u32 BinaryTreeMemoryMap::ReadU32LittleEndianImpl(u64 address)
{
return static_cast<u32>(ReadImpl<u32, std::endian::little>(address));
}
/*
64-bit Write
*/
void BinaryTreeMemoryMap::WriteU64BigEndianImpl(u64 value, u64 address)
{
WriteImpl<u64, std::endian::big>(value, address);
}
void BinaryTreeMemoryMap::WriteU64LittleEndianImpl(u64 value, u64 address)
{
WriteImpl<u64, std::endian::little>(value, address);
}
/*
64-bit Read
*/
u64 BinaryTreeMemoryMap::ReadU64BigEndianImpl(u64 address)
{
return ReadImpl<u64, std::endian::big>(address);
}
u64 BinaryTreeMemoryMap::ReadU64LittleEndianImpl(u64 address)
{
return ReadImpl<u64, std::endian::little>(address);
}
}
| 25.147887
| 150
| 0.720806
|
Dudejoe870
|
f26e1bf69404f9ff4878ce369c1a86cdd8c60546
| 5,364
|
hpp
|
C++
|
patterns/2020_10_19/prefab/include/prefab/IEntity.hpp
|
liff-engineer/articles
|
ad3386ef9cda5083793f485e309a9f85ab36f664
|
[
"MIT"
] | 2
|
2020-12-01T06:44:41.000Z
|
2021-11-22T06:07:52.000Z
|
patterns/2020_10_19/prefab/include/prefab/IEntity.hpp
|
liff-engineer/articles
|
ad3386ef9cda5083793f485e309a9f85ab36f664
|
[
"MIT"
] | null | null | null |
patterns/2020_10_19/prefab/include/prefab/IEntity.hpp
|
liff-engineer/articles
|
ad3386ef9cda5083793f485e309a9f85ab36f664
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include <tuple>
#include <memory>
#include "IComponent.hpp"
namespace prefab
{
//用来操作tuple的foreach算法
template <typename Tuple, typename F, std::size_t ...Indices>
void for_each_impl(Tuple&& tuple, F&& f, std::index_sequence<Indices...>) {
using swallow = int[];
(void)swallow {
1,
(f(std::get<Indices>(std::forward<Tuple>(tuple))), void(), int{})...
};
}
template <typename Tuple, typename F>
void for_each(Tuple&& tuple, F&& f) {
constexpr std::size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
for_each_impl(std::forward<Tuple>(tuple), std::forward<F>(f),
std::make_index_sequence<N>{});
}
//实体基类
class IEntity
{
public:
virtual ~IEntity() = default;
//实现类型Code
virtual HashedStringLiteral implTypeCode() const noexcept = 0;
//根据类型获取数据组件
virtual IComponentBase* component(HashedStringLiteral typeCode) noexcept = 0;
};
//实体集合基类
class IEntitys
{
public:
virtual ~IEntitys() = default;
//实现类型Code
virtual HashedStringLiteral implTypeCode() const noexcept = 0;
//包含的实体(实体生命周期由集合类管理)
virtual std::vector<IEntity*> entitys() noexcept = 0;
};
//引用语义的实体类,不管理实体生命周期
template<typename... Ts>
class EntityView {
std::tuple<IComponent<Ts>* ...> m_components;
private:
//从实体中获取并设置组件接口
template<typename T>
void setComponentOf(IEntity* entity, IComponent<T>*& component)
{
auto typeCode = HashedTypeNameOf<T>();
auto componentBase = entity->component(typeCode);
if (componentBase == nullptr || componentBase->typeCode() != typeCode) {
component = nullptr;
return;
}
component = static_cast<IComponent<T>*>(componentBase);
}
public:
EntityView() = default;
explicit EntityView(IEntity* entity)
{
if (!entity) return;
for_each(m_components, [&](auto& component) {
this->setComponentOf(entity, component);
});
}
//判断是否所有组件都存在且有效
explicit operator bool() const noexcept {
bool result = true;
for_each(m_components, [&](auto component) {
result &= (component != nullptr);
});
return result;
}
template<typename T>
decltype(auto) component() const noexcept {
return std::get<IComponent<T>*>(m_components);
}
template<typename T>
decltype(auto) component() noexcept {
return std::get<IComponent<T>*>(m_components);
}
template<typename T>
decltype(auto) exist() const noexcept {
return component<T>()->exist();
}
template<typename T>
decltype(auto) view() const {
return component<T>()->view();
}
template<typename T>
decltype(auto) remove() noexcept {
return component<T>()->remove();
}
template<typename T>
decltype(auto) assign(T const& v) noexcept {
return component<T>()->assign(v);
}
template<typename T>
decltype(auto) replace(T const& v) noexcept {
return component<T>()->replace(v);
}
};
class IRepository;
//值语义的实体类,使用智能指针管理实体的生命周期
template<typename... Ts>
class Entity :public EntityView<Ts...>
{
friend class IRepository;
std::unique_ptr<IEntity> m_impl;
public:
Entity() = default;
explicit Entity(std::unique_ptr<IEntity>&& entity)
:EntityView(entity.get()), m_impl(std::move(entity))
{};
};
//实体容器
template<typename... Ts>
class Entitys
{
friend class IRepository;
using entity_t = EntityView<Ts...>;
std::vector<entity_t> m_entitys;
std::unique_ptr<IEntitys> m_impl;
public:
Entitys() = default;
explicit Entitys(std::unique_ptr<IEntitys>&& entitys)
:m_impl(std::move(entitys))
{
if (m_impl == nullptr) return;
auto items = m_impl->entitys();
m_entitys.reserve(items.size());
for (auto e : items) {
m_entitys.emplace_back(entity_t{ e });
}
}
decltype(auto) empty() const noexcept {
return m_entitys.empty();
}
decltype(auto) size() const noexcept {
return m_entitys.size();
}
decltype(auto) at(std::size_t i) const {
return m_entitys.at(i);
}
decltype(auto) operator[](std::size_t i) const noexcept {
return m_entitys[i];
}
decltype(auto) begin() const noexcept {
return m_entitys.begin();
}
decltype(auto) end() const noexcept {
return m_entitys.end();
}
decltype(auto) begin() noexcept {
return m_entitys.begin();
}
decltype(auto) end() noexcept {
return m_entitys.end();
}
explicit operator bool() const noexcept {
return (m_impl != nullptr);
}
};
}
| 27.228426
| 89
| 0.543624
|
liff-engineer
|
f271842da1c802a66058f6006e2a868b865d0c12
| 2,388
|
hpp
|
C++
|
include/Network/Session.hpp
|
Lisoph/MORL
|
f1c4f9a1c16df236495666fd46d76da6ac9a32af
|
[
"MIT"
] | 1
|
2015-05-24T17:20:06.000Z
|
2015-05-24T17:20:06.000Z
|
include/Network/Session.hpp
|
Lisoph/MORL
|
f1c4f9a1c16df236495666fd46d76da6ac9a32af
|
[
"MIT"
] | 1
|
2015-05-15T20:29:58.000Z
|
2015-05-15T20:29:58.000Z
|
include/Network/Session.hpp
|
Lisoph/MORL
|
f1c4f9a1c16df236495666fd46d76da6ac9a32af
|
[
"MIT"
] | null | null | null |
#pragma once
#include "UdpSocket.hpp"
#include "IPEndpoint.hpp"
#include "Network/SessionState.hpp"
#include <cstdint>
#include <functional>
#include <stack>
namespace MORL {
class Game;
namespace Network {
class Session;
class StateNotRunning : public SessionState {
public:
StateNotRunning(Session &session)
: SessionState(session)
{}
void Update() override {}
};
class Session {
public:
static constexpr uint16_t ServerSocketPort = 5666;
using OwnedSessionState = std::unique_ptr<SessionState>;
using SessionStateStack = std::stack<OwnedSessionState>;
Session(MORL::Game &game);
Session(Session const &) = delete;
Session(Session && other);
~Session();
inline UdpSocket &Socket() {
return mSocket;
}
inline MORL::Game &Game() {
return mGame;
}
inline bool IsConnectedToServer() const {
return mConnectedToServer;
}
inline void ConnectedToServer(IPEndpoint const &server) {
mConnectedToServer = true;
mServer = server;
}
inline IPEndpoint const &Server() const {
return mServer;
}
template <typename S>
inline void PushState(S const &state) {
mStates.push(MakeUnique<S>(state));
}
template <typename S>
inline void PushState(S && state) {
mStates.push(MakeUnique<S>(std::move(state)));
}
template <typename S>
inline void ReplaceState(S const &state) {
if(mStates.size() >= 1) {
mStates.pop();
}
mStates.push(MakeUnique<S>(state));
}
template <typename S>
inline void ReplaceState(S && state) {
if(mStates.size() >= 1) {
mStates.pop();
}
mStates.push(MakeUnique<S>(std::move(state)));
}
void GoBack();
/**
* Update internal stuff, call this once a frame
*/
void Update();
private:
inline SessionState &CurrentState() {
return *(mStates.top().get());
}
private:
// How this socket is used varies from server to client side
UdpSocket mSocket;
MORL::Game &mGame;
SessionStateStack mStates;
// Only used by client
IPEndpoint mServer;
// Only used by client
bool mConnectedToServer = false;
};
}
}
| 22.528302
| 66
| 0.588358
|
Lisoph
|
f275bc1ce15ec5440151d3e7013dd7a10fdc3923
| 152
|
cpp
|
C++
|
12_Sorting/HighScoreEntry.cpp
|
alyoshenka/CodeDesign
|
beb8bbf79b14cbf1cad26b1e8f58fd47c417ccdd
|
[
"MIT"
] | null | null | null |
12_Sorting/HighScoreEntry.cpp
|
alyoshenka/CodeDesign
|
beb8bbf79b14cbf1cad26b1e8f58fd47c417ccdd
|
[
"MIT"
] | null | null | null |
12_Sorting/HighScoreEntry.cpp
|
alyoshenka/CodeDesign
|
beb8bbf79b14cbf1cad26b1e8f58fd47c417ccdd
|
[
"MIT"
] | null | null | null |
#include "HighScoreEntry.h"
HighScoreEntry::HighScoreEntry()
{
name = "noName";
score = -1;
level = -1;
}
HighScoreEntry::~HighScoreEntry()
{
}
| 9.5
| 33
| 0.657895
|
alyoshenka
|
f27a190e89511dc1e7eaf4ac352322b7f0cc9244
| 9,108
|
cpp
|
C++
|
src/Player.cpp
|
osbixaodaunb/RGBender-2.0
|
9c5e33cba50541b8288e29f56562820b3d7b0e55
|
[
"MIT"
] | 4
|
2017-05-15T19:33:28.000Z
|
2017-05-15T23:33:04.000Z
|
src/Player.cpp
|
osbixaodaunb/RGBender-2.0
|
9c5e33cba50541b8288e29f56562820b3d7b0e55
|
[
"MIT"
] | 4
|
2017-10-04T14:29:18.000Z
|
2017-10-04T14:43:52.000Z
|
src/Player.cpp
|
unbgames/RGBender
|
9c5e33cba50541b8288e29f56562820b3d7b0e55
|
[
"MIT"
] | 4
|
2017-05-15T19:33:37.000Z
|
2017-08-18T14:12:41.000Z
|
#include "Player.h"
#include "SDLGameObject.h"
#include "LoaderParams.h"
#include "InputHandler.h"
#include "Bullet.h"
#include "Game.h"
#include "Log.h"
#include "Enemy.h"
#include "PlayState.h"
#include "Physics.h"
#include "AudioManager.h"
#include "GameOverState.h"
#include "Childmaiden.h"
#include "Timer.h"
#include <string>
#include <SDL2/SDL.h>
#include <iostream>
#include <cmath>
using namespace std;
using namespace engine;
Player::Player() : SDLGameObject(){
m_fireRate = 500;
m_isShieldActive = false;
m_bulletVenemous = false;
for(int i=1; i<7; i++){
TextureManager::Instance().load("assets/player_health" + to_string(i) + ".png", "health" + to_string(i), Game::Instance().getRenderer());
}
TextureManager::Instance().load("assets/ataque_protagonista_preto.png", "bullet", Game::Instance().getRenderer());
TextureManager::Instance().load("assets/health.png", "health", Game::Instance().getRenderer());
TextureManager::Instance().load("assets/circle.png", "instance", Game::Instance().getRenderer());
TextureManager::Instance().load("assets/Cadeira_frente.png", "chairBullet", Game::Instance().getRenderer());
INFO("Player inicializado");
m_life = 6;
canMove = true;
}
void Player::load(const LoaderParams* pParams){
SDLGameObject::load(pParams);
}
void Player::draw(){
TextureManager::Instance().draw("instance", 100, 600, 100, 100, Game::Instance().getRenderer());
if(m_isShieldActive){
TextureManager::Instance().draw("shield", getPosition().getX()-17, getPosition().getY()-10, 110, 110, Game::Instance().getRenderer());
TextureManager::Instance().draw("brownskill", 110, 610, 80, 80, Game::Instance().getRenderer());
}
if(m_fireRate != 500){
TextureManager::Instance().draw("redskill", 110, 610, 80, 80, Game::Instance().getRenderer());
}
if(bullet!= NULL && bullet->getVenemous() == true){
TextureManager::Instance().draw("greenskill", 110, 610, 80, 80, Game::Instance().getRenderer());
}
TextureManager::Instance().draw("health" +to_string(m_life), 1000, 620, 180, 80, Game::Instance().getRenderer());
SDLGameObject::draw();
}
void Player::update(){
//std::cout << "Player top: " << getPosition().getX() << std::endl;
if(m_life <= 0){
Game::Instance().getStateMachine()->changeState(new GameOverState());
}
if(Game::Instance().getStateMachine()->currentState()->getStateID() == "PLAY"){
PlayState *playState = dynamic_cast<PlayState*>(Game::Instance().getStateMachine()->currentState());
if(playState->getLevel() != NULL && m_boss == NULL){
INFO("Xuxa is set");
m_boss = playState->getLevel()->getXuxa();
}
}
if(!canMove){
int time = Timer::Instance().step() - getStunTime();
if(time >= 700){
canMove = true;
}
rotateTowards();
}
if(shieldHits > 5 && m_isShieldActive){
TextureManager::Instance().clearFromTextureMap("shield");
shieldHits = 0;
m_isShieldActive = false;
}
setPoison();
if(canMove){
handleInput();
}
// if(m_bulletVenemous == true)
// INFO("FOI");
SDLGameObject::update();
}
void Player::setBulletVenemous(bool isVenemous){
m_bulletVenemous = isVenemous;
bullet->setVenemous(isVenemous);
if(isVenemous == false){
uint8_t* pixels = new uint8_t[3];
pixels[0] = 255;
pixels[1] = 255;
pixels[2] = 255;
TheTextureManager::Instance().changeColorPixels(pixels, "RAG");
}
}
void Player::setPoison(){
if(bullet != NULL && bullet->getVenemous() && bullet->isActive()){
if(Timer::Instance().step() <= m_boss->getEnemyTime() && bullet->m_collided){
m_boss->takeDamage(1);
int score = Game::Instance().getScore();
Game::Instance().setScore(score + 5);
TextureManager::Instance().loadText(std::to_string(Game::Instance().getScore()), "assets/fonts/Lato-Regular.ttf", "score", {255,255,255}, 50, Game::Instance().getRenderer());
INFO(m_boss->getHealth());
}else if(Timer::Instance().step() >= m_boss->getEnemyTime()){
//bullet->m_collided = false;
//bullet->setVenemous(false);
}
}
}
void Player::clean(){
SDLGameObject::clean();
}
void Player::handleInput(){
move();
m_numFrames = 4;
m_currentFrame = 1;
if(m_velocity == Vector2D(0, 0)){
rotateTowards();
} else {
Vector2D vec[] = {Vector2D(0,-1), Vector2D(1, -1).norm(), Vector2D(1, 0), Vector2D(1, 1).norm(), Vector2D(0, 1), Vector2D(-1, 1).norm(), Vector2D(-1, 0), Vector2D(-1, -1).norm()};
for(int i=0; i<8; i++){
if(m_velocity.norm() == vec[i]){
changeSprite(i);
}
}
int tmp = m_currentFrame;
m_currentFrame = 1 + int(((SDL_GetTicks() / 100) % (m_numFrames-1)));
}
useSkill();
if(InputHandler::Instance().getMouseButtonState(LEFT, m_fireRate)){
count = Timer::Instance().step() + 300;
AudioManager::Instance().playChunk("assets/sounds/spray.wav");
INFO("FIRE RATE: " + m_fireRate);
Vector2D pivot = Vector2D(m_width/2+m_position.getX(), m_height/2 + m_position.getY());
Vector2D target = InputHandler::Instance().getMousePosition() - pivot;
target = target.norm();
bullet = bulletCreator.create(m_boss);
//bullet->setVenemous(m_bulletVenemous);
bullet->load(target, Vector2D(m_width/2+m_position.getX(), m_height/2 + m_position.getY()));
Game::Instance().getStateMachine()->currentState()->addGameObject(bullet);
}
}
bool inside(double angle, double value){
return value > angle - 22.5 && value < angle + 22.5;
}
void Player::changeSprite(int index){
m_flip = false;
switch(index){
case 0: // UP
m_textureID = "up";
break;
case 1: // UP-RIGHT
m_textureID = "upright";
break;
case 2: // RIGHT
m_flip = true;
m_textureID = "left";
break;
case 3: // DOWN-RIGHT
m_flip = true;
m_textureID = "downleft";
break;
case 4: // DOWN
m_textureID = "down";
break;
case 5: // DOWN-LEFT
m_textureID = "downleft";
break;
case 6: // LEFT
m_textureID = "left";
break;
case 7: // UP-LEFT
m_flip = true;
m_textureID = "upright";
break;
}
if(!canMove){
m_textureID += "stun";
} else if(Timer::Instance().step() < count){
m_textureID += "attack";
}
}
void Player::rotateTowards(){
m_numFrames = 1;
m_currentFrame = 0;
Vector2D pivot = Vector2D(m_width/2+m_position.getX(), m_height/2 + m_position.getY());
Vector2D target = InputHandler::Instance().getMousePosition() - pivot;
target = target.norm();
double angle = Vector2D::angle(target, Vector2D(0, 1));
for(int i=0; i<8; i++){
if(inside(45 * i, angle)){
changeSprite(i);
break;
}
}
}
void Player::move(){
Vector2D movement(0, 0);
if(InputHandler::Instance().isKeyDown("w")){
movement += Vector2D(0, -1);
}
if(InputHandler::Instance().isKeyDown("s")){
movement += Vector2D(0, +1);
}
if(InputHandler::Instance().isKeyDown("d")){
movement += Vector2D(1, 0);
}
if(InputHandler::Instance().isKeyDown("a")){
movement += Vector2D(-1, 0);
}
movement = movement.norm();
if(!m_isDashing){
m_velocity = movement * 2;
}
dash();
if(getPosition().getY() + getHeight() >= 705){
if(m_velocity.getY() > 0)
m_velocity.setY(0);
} else if(getPosition().getY() <= 20){
if(m_velocity.getY() < 0)
m_velocity.setY(0);
}
if(getPosition().getX() + getWidth() >= 1365){
if(m_velocity.getX() > 0)
m_velocity.setX(0);
} else if(getPosition().getX() <= -6){
if(m_velocity.getX() < 0)
m_velocity.setX(0);
}
m_position += m_velocity;
if(Physics::Instance().checkCollision(this, m_boss)){
m_position -= m_velocity;
setLife(m_life - 1);
}
for(auto x: engine::Game::Instance().getStateMachine()->currentState()->getShieldObjects()){
if(Physics::Instance().checkCollision(this, x)){
if(dynamic_cast<Childmaiden*>(x)->getVisibility())
m_position -= m_velocity;
//setLife(m_life - 1);
}
}
}
void Player::useSkill(){
if(InputHandler::Instance().isKeyDown("1", 200)){
m_skillManager.setSkillPair(&m_pSkills, RED, &isFirstSkill);
}
if(InputHandler::Instance().isKeyDown("2", 200)){
m_skillManager.setSkillPair(&m_pSkills, GREEN, &isFirstSkill);
}
if(InputHandler::Instance().isKeyDown("3", 200)){
m_skillManager.setSkillPair(&m_pSkills, BLUE, &isFirstSkill);
}
if(InputHandler::Instance().isKeyDown("r", 100)){
std::map<std::pair<default_inks, default_inks>, bool>::iterator it = m_skillManager.getCoolDownMap()->find(m_pSkills);
if(it != m_skillManager.getCoolDownMap()->end()){
if(it->second == false){
m_skillManager.setCoolDownTrigger(m_pSkills);
if(m_pSkills.first != BLANK and m_pSkills.second != BLANK){
pixelColors = m_skillManager.getSkill(m_pSkills)();
TheTextureManager::Instance().changeColorPixels(pixelColors, "bullet");
//TheTextureManager::Instance().changeColorPixels(pixelColors, "instance");
}
}
else
INFO("TA EM CD");
m_pSkills.first = BLANK;
m_pSkills.second = BLANK;
isFirstSkill = true;
}
}
}
void Player::dash(){
if(InputHandler::Instance().isKeyDown("space", 1000)){
m_dashTime = Timer::Instance().step();
m_velocity = (m_velocity.norm() * 15);
m_isDashing = true;
}
if(m_isDashing && Timer::Instance().step() >= m_dashTime + 100){
m_isDashing = false;
}
}
void Player::setPlayerMoves(bool value){
canMove = value;
}
| 26.553936
| 181
| 0.664361
|
osbixaodaunb
|
f27b60e26acb014e0db888dda596bbfd2c3c660b
| 6,813
|
cpp
|
C++
|
tester/main-db-tester.cpp
|
hihi-dev/linphone
|
45814404943a0c8a4e341dbebf5da71fc6e44b67
|
[
"BSD-2-Clause"
] | null | null | null |
tester/main-db-tester.cpp
|
hihi-dev/linphone
|
45814404943a0c8a4e341dbebf5da71fc6e44b67
|
[
"BSD-2-Clause"
] | null | null | null |
tester/main-db-tester.cpp
|
hihi-dev/linphone
|
45814404943a0c8a4e341dbebf5da71fc6e44b67
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* main-db-tester.cpp
* Copyright (C) 2017 Belledonne Communications SARL
*
* 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/>.
*/
#include "address/address.h"
#include "core/core-p.h"
#include "db/main-db.h"
#include "event-log/events.h"
// TODO: Remove me. <3
#include "private.h"
#include "liblinphone_tester.h"
#include "tools/tester.h"
// =============================================================================
using namespace std;
using namespace LinphonePrivate;
// -----------------------------------------------------------------------------
class MainDbProvider {
public:
MainDbProvider () {
mCoreManager = linphone_core_manager_create("marie_rc");
char *dbPath = bc_tester_res("db/linphone.db");
linphone_config_set_string(linphone_core_get_config(mCoreManager->lc), "storage", "uri", dbPath);
bctbx_free(dbPath);
linphone_core_manager_start(mCoreManager, false);
}
~MainDbProvider () {
linphone_core_manager_destroy(mCoreManager);
}
const MainDb &getMainDb () {
return *L_GET_PRIVATE(mCoreManager->lc->cppPtr)->mainDb;
}
private:
LinphoneCoreManager *mCoreManager;
};
// -----------------------------------------------------------------------------
static void get_events_count () {
MainDbProvider provider;
const MainDb &mainDb = provider.getMainDb();
BC_ASSERT_EQUAL(mainDb.getEventCount(), 5175, int, "%d");
BC_ASSERT_EQUAL(mainDb.getEventCount(MainDb::ConferenceCallFilter), 0, int, "%d");
BC_ASSERT_EQUAL(mainDb.getEventCount(MainDb::ConferenceInfoFilter), 18, int, "%d");
BC_ASSERT_EQUAL(mainDb.getEventCount(MainDb::ConferenceChatMessageFilter), 5157, int, "%d");
BC_ASSERT_EQUAL(mainDb.getEventCount(MainDb::NoFilter), 5175, int, "%d");
}
static void get_messages_count () {
MainDbProvider provider;
const MainDb &mainDb = provider.getMainDb();
BC_ASSERT_EQUAL(mainDb.getChatMessageCount(), 5157, int, "%d");
BC_ASSERT_EQUAL(
mainDb.getChatMessageCount(
ChatRoomId(IdentityAddress("sip:test-3@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org"))
),
861, int, "%d"
);
}
static void get_unread_messages_count () {
MainDbProvider provider;
const MainDb &mainDb = provider.getMainDb();
BC_ASSERT_EQUAL(mainDb.getUnreadChatMessageCount(), 2, int, "%d");
BC_ASSERT_EQUAL(
mainDb.getUnreadChatMessageCount(
ChatRoomId(IdentityAddress("sip:test-3@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org"))
),
0, int, "%d"
);
}
static void get_history () {
MainDbProvider provider;
const MainDb &mainDb = provider.getMainDb();
BC_ASSERT_EQUAL(
mainDb.getHistoryRange(
ChatRoomId(IdentityAddress("sip:test-4@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org")),
0, -1, MainDb::Filter::ConferenceChatMessageFilter
).size(),
54,
int,
"%d"
);
BC_ASSERT_EQUAL(
mainDb.getHistoryRange(
ChatRoomId(IdentityAddress("sip:test-7@sip.linphone.org"), IdentityAddress("sip:test-7@sip.linphone.org")),
0, -1, MainDb::Filter::ConferenceCallFilter
).size(),
0,
int,
"%d"
);
BC_ASSERT_EQUAL(
mainDb.getHistoryRange(
ChatRoomId(IdentityAddress("sip:test-1@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org")),
0, -1, MainDb::Filter::ConferenceChatMessageFilter
).size(),
804,
int,
"%d"
);
BC_ASSERT_EQUAL(
mainDb.getHistory(
ChatRoomId(IdentityAddress("sip:test-1@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org")),
100, MainDb::Filter::ConferenceChatMessageFilter
).size(),
100,
int,
"%d"
);
}
static void get_conference_notified_events () {
MainDbProvider provider;
const MainDb &mainDb = provider.getMainDb();
list<shared_ptr<EventLog>> events = mainDb.getConferenceNotifiedEvents(
ChatRoomId(IdentityAddress("sip:test-44@sip.linphone.org"), IdentityAddress("sip:test-1@sip.linphone.org")),
1
);
BC_ASSERT_EQUAL(events.size(), 3, int, "%d");
if (events.size() != 3)
return;
shared_ptr<EventLog> event;
auto it = events.cbegin();
event = *it;
if (!BC_ASSERT_TRUE(event->getType() == EventLog::Type::ConferenceParticipantRemoved)) return;
{
shared_ptr<ConferenceParticipantEvent> participantEvent = static_pointer_cast<ConferenceParticipantEvent>(event);
BC_ASSERT_TRUE(participantEvent->getChatRoomId().getPeerAddress().asString() == "sip:test-44@sip.linphone.org");
BC_ASSERT_TRUE(participantEvent->getParticipantAddress().asString() == "sip:test-11@sip.linphone.org");
BC_ASSERT_TRUE(participantEvent->getNotifyId() == 2);
}
event = *++it;
if (!BC_ASSERT_TRUE(event->getType() == EventLog::Type::ConferenceParticipantDeviceAdded)) return;
{
shared_ptr<ConferenceParticipantDeviceEvent> deviceEvent = static_pointer_cast<
ConferenceParticipantDeviceEvent
>(event);
BC_ASSERT_TRUE(deviceEvent->getChatRoomId().getPeerAddress().asString() == "sip:test-44@sip.linphone.org");
BC_ASSERT_TRUE(deviceEvent->getParticipantAddress().asString() == "sip:test-11@sip.linphone.org");
BC_ASSERT_TRUE(deviceEvent->getNotifyId() == 3);
BC_ASSERT_TRUE(deviceEvent->getDeviceAddress().asString() == "sip:test-47@sip.linphone.org");
}
event = *++it;
if (!BC_ASSERT_TRUE(event->getType() == EventLog::Type::ConferenceParticipantDeviceRemoved)) return;
{
shared_ptr<ConferenceParticipantDeviceEvent> deviceEvent = static_pointer_cast<
ConferenceParticipantDeviceEvent
>(event);
BC_ASSERT_TRUE(deviceEvent->getChatRoomId().getPeerAddress().asString() == "sip:test-44@sip.linphone.org");
BC_ASSERT_TRUE(deviceEvent->getParticipantAddress().asString() == "sip:test-11@sip.linphone.org");
BC_ASSERT_TRUE(deviceEvent->getNotifyId() == 4);
BC_ASSERT_TRUE(deviceEvent->getDeviceAddress().asString() == "sip:test-47@sip.linphone.org");
}
}
test_t main_db_tests[] = {
TEST_NO_TAG("Get events count", get_events_count),
TEST_NO_TAG("Get messages count", get_messages_count),
TEST_NO_TAG("Get unread messages count", get_unread_messages_count),
TEST_NO_TAG("Get history", get_history),
TEST_NO_TAG("Get conference events", get_conference_notified_events)
};
test_suite_t main_db_test_suite = {
"MainDb", NULL, NULL, liblinphone_tester_before_each, liblinphone_tester_after_each,
sizeof(main_db_tests) / sizeof(main_db_tests[0]), main_db_tests
};
| 34.583756
| 115
| 0.719507
|
hihi-dev
|
f27b70324b23c204b5ef974c72beaadd47255450
| 414
|
cpp
|
C++
|
lecture5/task_6.cpp
|
zaneta-skiba/cpp
|
b02ce4252f9cf894370358fded7cfbfa3a317ead
|
[
"MIT"
] | null | null | null |
lecture5/task_6.cpp
|
zaneta-skiba/cpp
|
b02ce4252f9cf894370358fded7cfbfa3a317ead
|
[
"MIT"
] | null | null | null |
lecture5/task_6.cpp
|
zaneta-skiba/cpp
|
b02ce4252f9cf894370358fded7cfbfa3a317ead
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
int main()
{
string names[4];
cout << "Enter 4 names:" << endl;
for (int i = 0; i < 4; i++) // user enters the names
{
cout << "name " << i+1 <<": ";
cin >> names[i];
}
for (int i = 0; i < 4; i++)
{
cout << names[i] << endl; // display names on the screen
}
return 0;
}
| 15.923077
| 79
| 0.417874
|
zaneta-skiba
|
f27b75f9a9f11ae8ad2f1dd03714e6a1cfdb2357
| 132
|
cpp
|
C++
|
flower_equals_win/logic/Minus.cpp
|
Garoli/flower-equals-win-game
|
c6965b9dfa38de124e3e8991a0d92509a54365df
|
[
"Unlicense",
"MIT"
] | null | null | null |
flower_equals_win/logic/Minus.cpp
|
Garoli/flower-equals-win-game
|
c6965b9dfa38de124e3e8991a0d92509a54365df
|
[
"Unlicense",
"MIT"
] | null | null | null |
flower_equals_win/logic/Minus.cpp
|
Garoli/flower-equals-win-game
|
c6965b9dfa38de124e3e8991a0d92509a54365df
|
[
"Unlicense",
"MIT"
] | null | null | null |
#include "Minus.h"
Minus::Minus(char s) : Operator(s)
{
setImage("../flower_equals_win/meshes/textures/blocks/block_minus.png");
}
| 26.4
| 74
| 0.727273
|
Garoli
|
f27b977245640cf13e6e45289e2901f7b0c05bd8
| 4,087
|
cpp
|
C++
|
Libs/DICOM/Core/Testing/Cpp/ctkDICOMTesterTest1.cpp
|
ntoussaint/CTK
|
fc7a5f78fff4c4394ee5ede2f21975c6a44dfea4
|
[
"Apache-2.0"
] | 515
|
2015-01-13T05:42:10.000Z
|
2022-03-29T03:10:01.000Z
|
Libs/DICOM/Core/Testing/Cpp/ctkDICOMTesterTest1.cpp
|
ntoussaint/CTK
|
fc7a5f78fff4c4394ee5ede2f21975c6a44dfea4
|
[
"Apache-2.0"
] | 425
|
2015-01-06T05:28:38.000Z
|
2022-03-08T19:42:18.000Z
|
Libs/DICOM/Core/Testing/Cpp/ctkDICOMTesterTest1.cpp
|
ntoussaint/CTK
|
fc7a5f78fff4c4394ee5ede2f21975c6a44dfea4
|
[
"Apache-2.0"
] | 341
|
2015-01-08T06:18:17.000Z
|
2022-03-29T21:47:49.000Z
|
/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
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.
=========================================================================*/
// Qt includes
#include <QCoreApplication>
#include <QFileInfo>
// ctkDICOMCore includes
#include "ctkDICOMTester.h"
// STD includes
#include <iostream>
#include <cstdlib>
void printUsage()
{
std::cout << " ctkDICOMTesterTest1 [<dcmqrscp>] [<configfile>]" << std::endl;
}
int ctkDICOMTesterTest1(int argc, char * argv [])
{
QCoreApplication app(argc, argv);
ctkDICOMTester tester;
if (argc > 1)
{
tester.setDCMQRSCPExecutable(argv[1]);
if (tester.dcmqrscpExecutable() != argv[1])
{
std::cerr << __LINE__
<< ": Failed to set dcmqrscp: " << argv[1]
<< " value:" << qPrintable(tester.dcmqrscpExecutable())
<< std::endl;
return EXIT_FAILURE;
}
}
if (argc > 2)
{
tester.setDCMQRSCPConfigFile(argv[2]);
if (tester.dcmqrscpConfigFile() != argv[2])
{
std::cerr << __LINE__
<< ": Failed to set dcmqrscp config file: " << argv[2]
<< " value:" << qPrintable(tester.dcmqrscpConfigFile())
<< std::endl;
return EXIT_FAILURE;
}
}
QString dcmqrscp(tester.dcmqrscpExecutable());
QString dcmqrscpConf(tester.dcmqrscpConfigFile());
if (!QFileInfo(dcmqrscp).exists() ||
!QFileInfo(dcmqrscp).isExecutable())
{
std::cerr << __LINE__
<< ": Wrong dcmqrscp executable: " << qPrintable(dcmqrscp)
<< std::endl;
}
if (!QFileInfo(dcmqrscpConf).exists() ||
!QFileInfo(dcmqrscpConf).isReadable())
{
std::cerr << __LINE__
<< ": Wrong dcmqrscp executable: " << qPrintable(dcmqrscp)
<< std::endl;
}
QProcess* process = tester.startDCMQRSCP();
if (!process)
{
std::cerr << __LINE__
<< ": Failed to start dcmqrscp: " << qPrintable(dcmqrscp)
<< " with config file:" << qPrintable(dcmqrscpConf) << std::endl;
return EXIT_FAILURE;
}
bool res = tester.stopDCMQRSCP();
if (!res)
{
std::cerr << __LINE__
<< ": Failed to stop dcmqrscp: " << qPrintable(dcmqrscp)
<< " with config file:" << qPrintable(dcmqrscpConf) << std::endl;
return EXIT_FAILURE;
}
process = tester.startDCMQRSCP();
if (!process)
{
std::cerr << __LINE__
<< ": Failed to start dcmqrscp: " << qPrintable(dcmqrscp)
<< " with config file:" << qPrintable(dcmqrscpConf)
<< std::endl;
return EXIT_FAILURE;
}
process = tester.startDCMQRSCP();
if (process)
{
std::cerr << __LINE__
<< ": Failed to start dcmqrscp: " << qPrintable(dcmqrscp)
<< " with config file:"<< qPrintable(dcmqrscpConf) << std::endl;
return EXIT_FAILURE;
}
res = tester.stopDCMQRSCP();
if (!res)
{
std::cerr << __LINE__
<< ": Failed to stop dcmqrscp: " << qPrintable(dcmqrscp)
<< " with config file:" << qPrintable(dcmqrscpConf) << std::endl;
return EXIT_FAILURE;
}
// there should be no process to stop
res = tester.stopDCMQRSCP();
if (res)
{
std::cerr << __LINE__
<< ": Failed to stop dcmqrscp: " << qPrintable(dcmqrscp)
<< " with config file:" << qPrintable(dcmqrscpConf) << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 28.985816
| 79
| 0.571324
|
ntoussaint
|
f27be8659b0b452d8f4a3c58fde153b08c488f8c
| 101
|
hpp
|
C++
|
source/windows.hpp
|
phwitti/elevate
|
00e4718bcfbf2d5490a3059451d850d17c30d9b0
|
[
"Unlicense"
] | 4
|
2021-02-24T23:50:18.000Z
|
2021-08-08T11:56:49.000Z
|
src/shared/windows.hpp
|
phwitti/cmdhere
|
a8e7635780b043efb3e220c65366255d8529b615
|
[
"Unlicense"
] | null | null | null |
src/shared/windows.hpp
|
phwitti/cmdhere
|
a8e7635780b043efb3e220c65366255d8529b615
|
[
"Unlicense"
] | null | null | null |
#ifndef __PW_WINDOWS_HPP__
#define __PW_WINDOWS_HPP__
#define NOMINMAX
#include <Windows.h>
#endif
| 12.625
| 26
| 0.811881
|
phwitti
|
f27f8336710722dff65995ed0278c5e1a93f3a07
| 926
|
cpp
|
C++
|
ITK19_Summer_Training _2021/PreQNOI/21_08_21/e.cpp
|
hoanghai1803/CP_Training
|
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
|
[
"MIT"
] | 4
|
2021-08-25T10:53:32.000Z
|
2021-09-30T03:25:50.000Z
|
ITK19_Summer_Training _2021/PreQNOI/21_08_21/e.cpp
|
hoanghai1803/CP_Training
|
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
|
[
"MIT"
] | null | null | null |
ITK19_Summer_Training _2021/PreQNOI/21_08_21/e.cpp
|
hoanghai1803/CP_Training
|
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
long long x, y, l, r;
cin >> x >> y >> l >> r;
long long powX = 1, powY = 1;
vector<long long> vecX, vecY, vecSum;
while (1) {
vecX.push_back(powX);
if (r / x < powX)
break;
powX *= x;
}
while (1) {
vecY.push_back(powY);
if (r / y < powY)
break;
powY *= y;
}
for (auto _x: vecX)
for (auto _y: vecY)
vecSum.push_back(_x + _y);
sort(vecSum.begin(), vecSum.end());
auto it = vecSum.begin();
while (*it < l)
it++;
if (*it >= r) {
cout << (r - l + (*it > r));
return 0;
}
long long res = *it - l;
it++;
for (; it < vecSum.end() && *it < r; it++)
res = max(res, *it - *(it - 1) - 1);
cout << max(res, r - *(it - 1) - (it != vecSum.end() && r == *it)) << "\n";
}
| 21.045455
| 79
| 0.413607
|
hoanghai1803
|
f28194fb10280e78290c1e8fd063a8815c6bae80
| 209
|
cpp
|
C++
|
src/stream/DirectStream.cpp
|
Lyatus/L
|
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
|
[
"Unlicense"
] | 45
|
2018-08-24T12:57:38.000Z
|
2021-11-12T11:21:49.000Z
|
src/stream/DirectStream.cpp
|
Lyatus/L
|
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
|
[
"Unlicense"
] | null | null | null |
src/stream/DirectStream.cpp
|
Lyatus/L
|
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
|
[
"Unlicense"
] | 4
|
2019-09-16T02:48:42.000Z
|
2020-07-10T03:50:31.000Z
|
#include "DirectStream.h"
#include "../container/Buffer.h"
using namespace L;
Buffer DirectStream::read_into_buffer() {
Buffer buffer(size());
seek(0);
read(buffer, buffer.size());
return buffer;
}
| 16.076923
| 41
| 0.69378
|
Lyatus
|
f28b6c86a411b6fa3e1472f751d8e4235d6aa694
| 1,294
|
cpp
|
C++
|
src/Editor/Dynamic/Fields/TexturePathEditor.cpp
|
Tristeon/Tristeon
|
9052e87b743f1122ed4c81952f2bffda96599447
|
[
"MIT"
] | 32
|
2018-06-16T20:50:15.000Z
|
2022-03-26T16:57:15.000Z
|
src/Editor/Dynamic/Fields/TexturePathEditor.cpp
|
Tristeon/Tristeon2D
|
9052e87b743f1122ed4c81952f2bffda96599447
|
[
"MIT"
] | 2
|
2018-10-07T17:41:39.000Z
|
2021-01-08T03:14:19.000Z
|
src/Editor/Dynamic/Fields/TexturePathEditor.cpp
|
Tristeon/Tristeon2D
|
9052e87b743f1122ed4c81952f2bffda96599447
|
[
"MIT"
] | 9
|
2018-06-12T21:00:58.000Z
|
2021-01-08T02:18:30.000Z
|
#include "TexturePathEditor.h"
#include <qboxlayout.h>
#include <qdir.h>
#include <qfiledialog.h>
#include <Settings.h>
#include <AssetManagement/AssetDatabase.h>
namespace TristeonEditor
{
TexturePathEditor::TexturePathEditor(const nlohmann::json& pValue, const std::function<void(nlohmann::json)>& pCallback) : AbstractJsonEditor(pValue, pCallback)
{
const uint32_t guid = _value.value("guid", 0);
_button = new QPushButton(QString(std::to_string(guid).c_str()));
_widget = _button;
QWidget::connect(_button, &QPushButton::clicked,
[=]()
{
QDir const baseDir(Tristeon::Settings::assetPath().c_str());
auto const path = QFileDialog::getOpenFileName(nullptr, QWidget::tr("Find Texture"), Tristeon::Settings::assetPath().c_str(), QWidget::tr("Image Files (*.png *.jpg *.bmp)"));
if (!path.isEmpty())
{
auto const localPath = baseDir.relativeFilePath(path);
auto const fileName = QFileInfo(path).baseName();
_value["guid"] = Tristeon::AssetDatabase::guid("assets://" + localPath.toStdString());
_button->setText(fileName);
_callback(_value);
}
});
}
void TexturePathEditor::setValue(const nlohmann::json& pValue)
{
_value = pValue;
_button->setText(Tristeon::AssetDatabase::path(pValue.value("guid", 0)).c_str());
}
}
| 31.560976
| 178
| 0.697836
|
Tristeon
|
f290e9b9e1dfe6750502d56b139da0c12d11eefb
| 2,707
|
cpp
|
C++
|
competitive_programming_3/2_data_structures_and_libraries/2.3_Non-Linear_DS_with_Built-in_Libraries/map(treemap)/978_Lemmings_Battle.cpp
|
FranciscoPigretti/onlinejudge_solutions
|
ec9368ade1faa403d0d26ad9321b030e128ae099
|
[
"MIT"
] | null | null | null |
competitive_programming_3/2_data_structures_and_libraries/2.3_Non-Linear_DS_with_Built-in_Libraries/map(treemap)/978_Lemmings_Battle.cpp
|
FranciscoPigretti/onlinejudge_solutions
|
ec9368ade1faa403d0d26ad9321b030e128ae099
|
[
"MIT"
] | null | null | null |
competitive_programming_3/2_data_structures_and_libraries/2.3_Non-Linear_DS_with_Built-in_Libraries/map(treemap)/978_Lemmings_Battle.cpp
|
FranciscoPigretti/onlinejudge_solutions
|
ec9368ade1faa403d0d26ad9321b030e128ae099
|
[
"MIT"
] | null | null | null |
#include <iostream> // cin, cout
#include <set>
#include <iterator>
using namespace std;
int main() {
int test_cases;
scanf("%d", &test_cases);
int B, SG, SB, current;
multiset <int, greater <int> > greens, blues;
multiset <int, greater <int> > temp_greens, temp_blues;
multiset <int, greater <int> >::iterator g_it, b_it;
while(test_cases--) {
int number_of_snowflakes;
scanf("%d %d %d", &B, &SG, &SB);
greens.clear();
blues.clear();
while(SG--) {
scanf("%d", ¤t);
greens.insert(current);
}
while(SB--) {
scanf("%d", ¤t);
blues.insert(current);
}
while(true) {
for (int i = 0; i < B; i++) {
// saco de cada uno si hay en ambos
if (greens.size() > 0 && blues.size() > 0) {
g_it = greens.begin();
b_it = blues.begin();
int g = *g_it;
int b = *b_it;
greens.erase(g_it);
blues.erase(b_it);
int res = g - b;
if (res > 0) {
temp_greens.insert(res);
} else if (res < 0) {
temp_blues.insert(-res);
} else {
// empate
}
} else {
break;
}
}
// vuelvo a insertar los ganadores
for (auto x : temp_greens) {
greens.insert(x);
}
for (auto x : temp_blues) {
blues.insert(x);
}
temp_greens.clear();
temp_blues.clear();
// si hay en ambos sigo, sino devuelvo el ganador o empate
if (greens.size() == 0 && blues.size() == 0) {
cout << "green and blue died" << endl << endl;
break;
} else if (greens.size() == 0) {
cout << "blue wins" << endl;
for (auto x : blues) {
cout << x << endl;
}
if (test_cases != 0) {
cout << endl;
}
break;
} else if (blues.size() == 0) {
cout << "green wins" << endl;
for (auto x : greens) {
cout << x << endl;
}
if (test_cases != 0) {
cout << endl;
}
break;
}
}
}
}
| 27.907216
| 70
| 0.362763
|
FranciscoPigretti
|
f294481ff7e6dc8c20b6e4ea9d130ef1c07a09a1
| 12,105
|
cpp
|
C++
|
runtests.cpp
|
fguitton/mdipp
|
a79d207daa3bf6b2b730653d39cd270cf6295859
|
[
"BSD-3-Clause"
] | 2
|
2017-11-01T16:45:16.000Z
|
2021-02-24T08:29:14.000Z
|
runtests.cpp
|
fguitton/mdipp
|
a79d207daa3bf6b2b730653d39cd270cf6295859
|
[
"BSD-3-Clause"
] | null | null | null |
runtests.cpp
|
fguitton/mdipp
|
a79d207daa3bf6b2b730653d39cd270cf6295859
|
[
"BSD-3-Clause"
] | 2
|
2018-03-22T16:40:51.000Z
|
2018-07-16T13:05:10.000Z
|
#include <fstream>
#include <iostream>
#include <memory>
#include <Eigen/Dense>
#include "datatypes.hpp"
#include "utility.hpp"
std::default_random_engine generator;
template<typename T>
void
writeCsvMatrix (std::ostream &fd,
const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &data,
const Eigen::VectorXi &alloc)
{
fd << "cluster";
for (int i = 0; i < data.cols(); i++) {
fd << ",f" << i+1;
}
fd << "\n";
for (int i = 0; i < data.rows(); i++) {
fd << "c" << alloc(i)+1;
for (int j = 0; j < data.cols(); j++) {
fd << "," << data(i,j);
}
fd << "\n";
}
}
template<typename T> void
checkEqualTemplate (T a, T b, const std::string &msg)
{
if (a == b)
return;
std::cerr
<< "Error: " << msg
<< " (expecting " << a << " == " << b << ")"
<< std::endl;
}
void checkEqual(int a, int b, const std::string &msg) {
return checkEqualTemplate(a, b, msg); }
template<typename T> void
checkApproxEqual(const T &a, const T &b,
const std::string &msg,
typename T::Scalar epsilon = 1e-6)
{
// Eigen::Array<bool, T::RowsAtCompileTime, T::ColsAtCompileTime>
// em = (a - b).array() <= a.array().abs().min(b.array().abs()) * epsilon;
if (a.isApprox(b, epsilon))
return;
std::cerr
<< "Error: " << msg
<< " (matrix equality check failed at epsilon=" << epsilon << ")"
<< " differences observed: " << std::endl
<< (a-b).array().abs() << std::endl
<< std::endl;
}
void
checkApproxEqual(const double a, const double b,
const std::string &msg, double epsilon = 1e-6)
{
using std::abs;
using std::min;
epsilon *= min(abs(a),abs(b));
if(abs(a-b) <= epsilon)
return;
std::cerr
<< "Error: " << msg
<< " (expecting ||" << a << " - " << b << "|| <= " << epsilon << ")"
<< std::endl;
}
template<typename T> void
checkProbItemMassGt(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &prob,
int item, T mass, const std::string &msg)
{
// normalise, nans and infinities will propagate!
auto probnorm = prob.array() / prob.sum();
// check all positive
if ((probnorm < 0).any()) {
std::cerr
<< "Error: " << msg
<< " (some probabilities are not positive)\n";
}
if (probnorm(item) < mass) {
std::cerr
<< "Error: " << msg
<< " (mass of item " << item
<< " is " << probnorm(item)
<< ", i.e. < " << mass << ")\n";
}
}
double
nuConditionalAlphaOracle(const Eigen::MatrixXi &alloc)
{
return alloc.rows();
}
double
phiConditionalAlphaOracle(const Eigen::MatrixXi &alloc,
int m, int p)
{
int sum = 0;
for (int i = 0; i < alloc.rows(); i++) {
sum += alloc(i,m) == alloc(i,p);
}
return 1 + sum;
}
double
gammaConditionalAlphaOracle(const Eigen::MatrixXi &alloc,
int m, int jm)
{
int sum = 0;
for (int i = 0; i < alloc.rows(); i++) {
sum += alloc(i,m) == jm;
}
return 1 + sum;
}
/* the following set of functions work by having an @outer function
* that works "down" through the files, setting $j_i$ to the
* appropriate value and then calling the next @outer function. Once
* $j$ has been set for all $K$ files (i.e. @{i == K}), @outer defers
* to @inner and the product for the given $j$ is evaluated.
*/
// See Equation 2 in section "A.2 Normalising Constant" of Kirk et.al 2012
double
nuConditionalBetaOracle(const mdisampler &mdi)
{
const int N = mdi.nclus(), K = mdi.nfiles();
std::vector<int> j(mdi.nfiles());
auto inner = [K,&mdi,&j]() {
long double prod = 1;
for (int k = 0; k < K; k++) {
prod *= mdi.weight(j[k], k);
}
for (int k = 0; k < K-1; k++) {
for (int l = k+1; l < K; l++) {
prod *= 1 + mdi.phi(k, l) * (j[k] == j[l]);
}
}
return prod;
};
std::function<long double(int)> outer = [&outer, &inner, &j, N, K](int i) {
if (i == K)
return inner();
long double sum = 0;
for (j[i] = 0; j[i] < N; j[i]++)
sum += outer(i+1);
return sum;
};
return outer(0);
}
// See Kirk et.al 2012 $b_\phi$ from "Conditional for $\phi_{mp}$"
double
phiConditionalBetaOracle(const mdisampler &mdi,
int m, int p)
{
const int N = mdi.nclus(), K = mdi.nfiles();
std::vector<int> j(mdi.nfiles());
auto inner = [K,&mdi,&j,m,p]() {
long double prod = 1;
for (int k = 0; k < K; k++) {
prod *= mdi.weight(j[k], k);
}
for (int k = 0; k < K-1; k++) {
for (int l = k+1; l < K; l++) {
if (l != p)
prod *= 1 + mdi.phi(k, l) * (j[k] == j[l]);
}
}
for (int k = 0; k < p; k++) {
if (k != m)
prod *= 1 + mdi.phi(k, p) * (j[k] == j[p]);
}
return prod;
};
std::function<long double(int)> outer = [&outer,&inner,&j,N,K,m,p](int i) {
if (i == K)
return inner();
// $j_m$ and $j_p$ are set outside this iteration
if (i == m || i == p)
return outer(i+1);
long double sum = 0;
for (j[i] = 0; j[i] < N; j[i]++)
sum += outer(i+1);
return sum;
};
// iterate over $\sum_{j_m = j_p = 1}^N$
long double sum = 0;
for (int i = 0; i < N; i++) {
j[m] = j[p] = i;
sum += outer(0);
}
return mdi.nu() * sum;
}
// See Kirk et.al 2012 $b_\gamma$ from "Conditional for $\gamma_{j_m m}$"
double
gammaConditionalBetaOracle (const mdisampler &mdi,
const int m, const int jm)
{
const int N = mdi.nclus(), K = mdi.nfiles();
std::vector<int> j(mdi.nfiles());
// within data @m we are interested in cluster @jm
j[m] = jm;
auto inner = [K,m,&mdi,&j]() {
long double prod = 1;
for (int k = 0; k < K; k++) {
if(k != m)
prod *= mdi.weight(j[k], k);
}
for (int k = 0; k < K-1; k++) {
for (int l = k+1; l < K; l++) {
prod *= 1 + mdi.phi(k, l) * (j[k] == j[l]);
}
}
return prod;
};
std::function<long double(int)> outer = [&outer, &inner, &j, N, K, m](int i) {
if (i == K)
return inner();
if (i == m)
return outer(i+1);
long double sum = 0;
for (j[i] = 0; j[i] < N; j[i]++)
sum += outer(i+1);
return sum;
};
return mdi.nu() * outer(0);
}
int
main()
{
/* datatypes
*
* * loading data (CPU)
*
* * summarising data given cluster allocations (CPU GPU)
*
* * sampling cluster parameters given above summary (CPU GPU)
*
* * sampling cluster allocations given cluster parameters (CPU GPU)
*
* MDI prior
*
* * Sampling Nu given [weights and allocations]?
*
* * Sampling weights given [lots!]
*
* * Sampling DPs given weights and nu
*/
generator.seed(1);
// given a single "file" for each datatype, load it in define
// allocations (same for all four files), weights, nu, DP
// concentration
const int
nfiles = 4,
nitems = 5,
nclus = 10,
ngaussfeatures = 3;
// 5 items, cluster allocations [0 0 1 1 2]. one file for each
// datatype
Eigen::MatrixXi alloc(nitems, nfiles);
for (int i = 0; i < nfiles; i++)
alloc.col(i) << 0, 0, 1, 1, 2;
Eigen::MatrixXf
weights = alloc.cast<float>();
Eigen::VectorXf
dpmass = Eigen::VectorXf::Ones(nfiles);
Eigen::MatrixXf data_gaussian(nitems, ngaussfeatures);
data_gaussian <<
-2.1, -2.1, -2.1,
-1.9, -1.9, -1.9,
1.9, 1.9, 1.9,
2.1, 2.1, 2.1,
5.0, 5.0, 5.0;
// write dummy data out, load it back in and make sure it's the same
// as the original data
{
std::ofstream out("data_gauss.txt");
writeCsvMatrix (out, data_gaussian, alloc.col(0));
}
gaussianDatatype dt_gauss("data_gauss.txt");
checkEqual(nitems, dt_gauss.items().size(),
"number of items read from gaussian dataset");
checkEqual(ngaussfeatures, dt_gauss.features().size(),
"number of features read from gaussian dataset");
checkApproxEqual<Eigen::MatrixXf>(data_gaussian.transpose(), dt_gauss.rawdata(),
"gaussian data from file");
// given weights, allocations, nu:
shared shared(nfiles, nclus, nitems);
interdataset inter(nfiles);
mdisampler mdi(inter, nclus);
shared.sampleFromPrior();
mdi.sampleFromPrior();
shared.setAlloc(alloc);
cuda::sampler cuda(nfiles, nitems, nclus,
inter.getPhiOrd(), inter.getWeightOrd());
cuda.setNu(mdi.nu());
cuda.setDpMass(eigenMatrixToStdVector(mdi.dpmass()));
cuda.setAlloc(eigenMatrixToStdVector(alloc));
cuda.setPhis(eigenMatrixToStdVector(mdi.phis()));
cuda.setWeights(eigenMatrixToStdVector(mdi.weights()));
gaussianSampler * gauss_sampler = dt_gauss.newSampler(nclus, &cuda);
// given known allocations, calculate Gaussian summaries
{
gauss_sampler->cudaSampleParameters(alloc.col(0));
gauss_sampler->cudaAccumAllocProbs();
const std::vector<runningstats<> > state(gauss_sampler->accumState(alloc.col(0)));
checkEqual(nclus * ngaussfeatures, state.size(),
"number of accumulated gaussian stats");
// check Gaussian summaries are OK
const runningstats<> rs[nclus] = {{2,-2,0.02},{2,2,0.02},{1,5,0}};
bool ok = true;
for (int j = 0; j < nclus; j++) {
for (int i = 0; i < ngaussfeatures; i++) {
const runningstats<>
&a = state[j * ngaussfeatures + i],
&b = rs[j];
ok &= a.isApprox(b);
}
}
if (!ok) {
std::cout << "Error: some of the accumulated gaussian stats are incorrect\n";
}
}
// given known cluster parameters, ...
{
Eigen::MatrixXf mu(ngaussfeatures, nclus), tau(ngaussfeatures,nclus);
mu.fill(0); tau.fill(20);
mu.col(0).fill(-2);
mu.col(1).fill( 2);
mu.col(2).fill( 5);
gauss_sampler->debug_setMuTau(mu, tau);
}
// ... sample Gaussian cluster association probabilities
{
std::unique_ptr<sampler::item> is(gauss_sampler->newItemSampler());
for (int i = 0; i < nitems; i++) {
Eigen::VectorXf prob((*is)(i));
prob = (prob.array() - prob.maxCoeff()).exp();
checkProbItemMassGt<float>(prob, alloc(i,0), 0.5,
"gaussian cluster allocations");
}
}
{
double
oracle = nuConditionalBetaOracle(mdi);
checkApproxEqual(oracle, mdi.nuConditionalBeta(),
"MDI nu beta conditional, CPU code");
checkApproxEqual(oracle, cuda.collectNuConditionalBeta(),
"MDI nu beta conditional, GPU code");
oracle = nuConditionalAlphaOracle(alloc);
checkApproxEqual(oracle, shared.nuConditionalAlpha(),
"MDI nu alpha conditional, CPU code");
}
{
Eigen::MatrixXf oracle, cpu, gpu;
oracle = cpu = gpu = Eigen::MatrixXf::Zero(nfiles, nfiles);
std::vector<float> gpuv = cuda.collectPhiConditionalsBeta();
for (int k = 0, i = 0; k < nfiles; k++) {
for (int l = k+1; l < nfiles; l++) {
oracle(k,l) = phiConditionalBetaOracle(mdi, k, l);
cpu(k,l) = mdi.phiConditionalBeta(k, l);
gpu(k,l) = gpuv[i++];
}
}
checkApproxEqual(oracle, cpu, "MDI phi beta conditionals, CPU code");
checkApproxEqual(oracle, gpu, "MDI phi beta conditionals, GPU code");
gpuv = cuda.collectPhiConditionalsAlpha();
for (int k = 0, i = 0; k < nfiles; k++) {
for (int l = k+1; l < nfiles; l++) {
oracle(k,l) = phiConditionalAlphaOracle(alloc, k, l);
cpu(k,l) = shared.phiConditionalAlpha(k, l) + 1; // what to do about prior?
gpu(k,l) = gpuv[i++];
}
}
checkApproxEqual(oracle, cpu, "MDI phi alpha conditionals, CPU code");
checkApproxEqual(oracle, gpu, "MDI phi alpha conditionals, GPU code");
}
{
Eigen::MatrixXf oracle, cpu, gpu;
oracle = cpu = Eigen::MatrixXf::Zero(nclus, nfiles);
gpu = stdVectorToEigenMatrix(cuda.collectGammaConditionalsBeta(),
nclus, nfiles);
// take out the prior, not sure what to do about this. I think I
// should be checking priors as well, but conflating it in the
// test unnecessarily seems to make things more difficult to debug
// than it could... hum!
gpu.array() -= 1;
for (int k = 0; k < nfiles; k++) {
for (int j = 0; j < nclus; j++) {
oracle(j,k) = gammaConditionalBetaOracle(mdi, k, j);
cpu(j,k) = mdi.gammaConditionalBeta(k, j);
}
}
checkApproxEqual(oracle, cpu, "MDI gamma beta conditionals, CPU code");
checkApproxEqual(oracle, gpu, "MDI gamma beta conditionals, GPU code");
}
return 0;
}
| 26.546053
| 86
| 0.585378
|
fguitton
|
f295975d8918914e50a1a1e82b5b1f9a728aa1ff
| 254
|
cpp
|
C++
|
ImportantExample/QIconEditorDemo/main.cpp
|
xiaohaijin/Qt
|
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
|
[
"MIT"
] | 3
|
2018-12-24T19:35:52.000Z
|
2022-02-04T14:45:59.000Z
|
ImportantExample/QIconEditorDemo/main.cpp
|
xiaohaijin/Qt
|
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
|
[
"MIT"
] | null | null | null |
ImportantExample/QIconEditorDemo/main.cpp
|
xiaohaijin/Qt
|
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
|
[
"MIT"
] | 1
|
2019-05-09T02:42:40.000Z
|
2019-05-09T02:42:40.000Z
|
#include "iconeditor.h"
#include <QIcon>
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QImage icon(":/images/mouse.png");
IconEditor w;
w.setIconImage(icon);
w.show();
return a.exec();
}
| 16.933333
| 38
| 0.629921
|
xiaohaijin
|
f29fee79be5f44a0dd5e04a95fd2201638ea63c1
| 4,862
|
cpp
|
C++
|
src/ECS/Systems/UpdateEntityPositionSystem.cpp
|
novuscore/NovusCore-World
|
4c0639e251cac9ae0cef601b814c575a1bfb4f2e
|
[
"MIT"
] | null | null | null |
src/ECS/Systems/UpdateEntityPositionSystem.cpp
|
novuscore/NovusCore-World
|
4c0639e251cac9ae0cef601b814c575a1bfb4f2e
|
[
"MIT"
] | null | null | null |
src/ECS/Systems/UpdateEntityPositionSystem.cpp
|
novuscore/NovusCore-World
|
4c0639e251cac9ae0cef601b814c575a1bfb4f2e
|
[
"MIT"
] | 2
|
2021-12-20T22:16:11.000Z
|
2022-03-10T20:59:10.000Z
|
#include "UpdateEntityPositionSystem.h"
#include <entt.hpp>
#include <tracy/Tracy.hpp>
#include <Utils/DebugHandler.h>
#include "../../Utils/ServiceLocator.h"
#include "../Components/Singletons/MapSingleton.h"
#include "../Components/Network/ConnectionComponent.h"
#include <Gameplay/Network/PacketWriter.h>
#include <Gameplay/ECS/Components/Transform.h>
#include <Gameplay/ECS/Components/GameEntity.h>
void UpdateEntityPositionSystem::Update(entt::registry& registry)
{
auto modelView = registry.view<Transform, GameEntity>();
if (modelView.size_hint() == 0)
return;
MapSingleton& mapSingleton = registry.ctx<MapSingleton>();
modelView.each([&](const auto entity, Transform& transform, GameEntity& gameEntity)
{
if (gameEntity.type != GameEntity::Type::Player)
return;
std::vector<Point2D> playersWithinDistance;
Tree2D& entityTress = mapSingleton.GetPlayerTree();
if (!entityTress.GetWithinDistance({transform.position.x, transform.position.y}, 500.f, entity, playersWithinDistance))
return;
std::vector<entt::entity>& seenEntities = gameEntity.seenEntities;
if (seenEntities.size() == 0 && playersWithinDistance.size() == 0)
return;
std::vector<entt::entity> newlySeenEntities(playersWithinDistance.size());
for (u32 i = 0; i < playersWithinDistance.size(); i++)
{
newlySeenEntities[i] = playersWithinDistance[i].GetPayload();
}
ConnectionComponent& connection = registry.get<ConnectionComponent>(entity);
// Send Delete Updates to no longer seen entites
{
for (auto it = seenEntities.begin(); it != seenEntities.end();)
{
entt::entity seenEntity = *it;
auto itr = std::find(newlySeenEntities.begin(), newlySeenEntities.end(), seenEntity);
if (itr != newlySeenEntities.end())
{
newlySeenEntities.erase(itr);
it++;
continue;
}
// Remove SeenEntity
{
it = seenEntities.erase(it);
std::shared_ptr<Bytebuffer> packetBuffer = nullptr;
if (PacketWriter::SMSG_DELETE_ENTITY(packetBuffer, seenEntity))
{
connection.AddPacket(packetBuffer, PacketPriority::IMMEDIATE);
}
else
{
DebugHandler::PrintError("Failed to build SMSG_DELETE_ENTITY");
}
}
}
}
// Send Movement Updates to seenEntities
if (seenEntities.size() > 0 && registry.all_of<TransformIsDirty>(entity))
{
std::shared_ptr<Bytebuffer> packetBuffer = nullptr;
if (PacketWriter::SMSG_UPDATE_ENTITY(packetBuffer, entity, transform))
{
for (u32 i = 0; i < seenEntities.size(); i++)
{
entt::entity& seenEntity = seenEntities[i];
if (!registry.valid(seenEntity))
continue;
const GameEntity& seenGameEntity = registry.get<GameEntity>(seenEntity);
if (seenGameEntity.type != GameEntity::Type::Player)
continue;
ConnectionComponent& seenConnection = registry.get<ConnectionComponent>(seenEntity);
seenConnection.AddPacket(packetBuffer, PacketPriority::IMMEDIATE);
}
}
}
// Check if there are any new entities
if (newlySeenEntities.size() == 0)
return;
// List of new entities within range
if (newlySeenEntities.size() > 0)
{
//DebugHandler::PrintSuccess("Preparing Data for Player (%u)", entt::to_integral(entity));
for (u32 i = 0; i < newlySeenEntities.size(); i++)
{
entt::entity newEntity = newlySeenEntities[i];
if (!registry.valid(newEntity))
continue;
const Transform& newTransform = registry.get<Transform>(newEntity);
const GameEntity& newGameEntity = registry.get<GameEntity>(newEntity);
std::shared_ptr<Bytebuffer> packetBuffer = nullptr;
if (PacketWriter::SMSG_CREATE_ENTITY(packetBuffer, newEntity, newGameEntity, newTransform))
{
connection.AddPacket(packetBuffer, PacketPriority::IMMEDIATE);
}
seenEntities.push_back(newEntity);
}
//DebugHandler::PrintSuccess("Finished Preparing Data for Player (%u)", entt::to_integral(entity));
}
});
}
| 37.4
| 127
| 0.567668
|
novuscore
|
f29feff2635c02f4971e24e5d2cf9f452cda5ce7
| 4,298
|
cc
|
C++
|
gpu/command_buffer/tests/gl_unallocated_texture_unittest.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
gpu/command_buffer/tests/gl_unallocated_texture_unittest.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113
|
2015-05-04T09:58:14.000Z
|
2022-01-31T19:35:03.000Z
|
gpu/command_buffer/tests/gl_unallocated_texture_unittest.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <stddef.h>
#include <stdint.h>
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_lib.h"
#include "gpu/command_buffer/service/gles2_cmd_decoder.h"
#include "gpu/command_buffer/tests/gl_manager.h"
#include "gpu/command_buffer/tests/gl_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gl/gl_share_group.h"
namespace gpu {
class GLUnallocatedTextureTest : public testing::Test {
protected:
void SetUp() override { gl_.Initialize(GLManager::Options()); }
void TearDown() override { gl_.Destroy(); }
GLuint MakeProgram(const char* fragment_shader) {
constexpr const char kVertexShader[] =
"void main() { gl_Position = vec4(0.0, 0.0, 0.0, 1.0); }";
GLuint program = GLTestHelper::LoadProgram(kVertexShader, fragment_shader);
if (!program)
return 0;
glUseProgram(program);
GLint location_sampler = glGetUniformLocation(program, "sampler");
glUniform1i(location_sampler, 0);
return program;
}
// Creates a texture on target, setting up filters but without setting any
// level image.
GLuint MakeUninitializedTexture(GLenum target) {
GLuint texture = 0;
glGenTextures(1, &texture);
glBindTexture(target, texture);
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
return texture;
}
GLManager gl_;
};
// Test that we can render with GL_TEXTURE_2D textures that are unallocated.
// This should not generate errors or assert.
TEST_F(GLUnallocatedTextureTest, RenderUnallocatedTexture2D) {
constexpr const char kFragmentShader[] =
"uniform sampler2D sampler;\n"
"void main() { gl_FragColor = texture2D(sampler, vec2(0.0, 0.0)); }\n";
GLuint program = MakeProgram(kFragmentShader);
ASSERT_TRUE(program);
GLuint texture = MakeUninitializedTexture(GL_TEXTURE_2D);
glDrawArrays(GL_TRIANGLES, 0, 3);
EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError());
glDeleteTextures(1, &texture);
glDeleteProgram(program);
}
// Test that we can render with GL_TEXTURE_EXTERNAL_OES textures that are
// unallocated. This should not generate errors or assert.
TEST_F(GLUnallocatedTextureTest, RenderUnallocatedTextureExternal) {
if (!gl_.GetCapabilities().egl_image_external) {
LOG(INFO) << "GL_OES_EGL_image_external not supported, skipping test";
return;
}
constexpr const char kFragmentShader[] =
"#extension GL_OES_EGL_image_external : enable\n"
"uniform samplerExternalOES sampler;\n"
"void main() { gl_FragColor = texture2D(sampler, vec2(0.0, 0.0)); }\n";
GLuint program = MakeProgram(kFragmentShader);
ASSERT_TRUE(program);
GLuint texture = MakeUninitializedTexture(GL_TEXTURE_EXTERNAL_OES);
glDrawArrays(GL_TRIANGLES, 0, 3);
EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError());
glDeleteTextures(1, &texture);
glDeleteProgram(program);
}
// Test that we can render with GL_TEXTURE_RECTANGLE_ARB textures that are
// unallocated. This should not generate errors or assert.
TEST_F(GLUnallocatedTextureTest, RenderUnallocatedTextureRectange) {
if (!gl_.GetCapabilities().texture_rectangle) {
LOG(INFO) << "GL_ARB_texture_rectangle not supported, skipping test";
return;
}
constexpr const char kFragmentShader[] =
"#extension GL_ARB_texture_rectangle : enable\n"
"uniform sampler2DRect sampler;\n"
"void main() {\n"
" gl_FragColor = texture2DRect(sampler, vec2(0.0, 0.0));\n"
"}\n";
GLuint program = MakeProgram(kFragmentShader);
ASSERT_TRUE(program);
GLuint texture = MakeUninitializedTexture(GL_TEXTURE_RECTANGLE_ARB);
glDrawArrays(GL_TRIANGLES, 0, 3);
EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError());
glDeleteTextures(1, &texture);
glDeleteProgram(program);
}
} // namespace gpu
| 35.520661
| 79
| 0.744067
|
zealoussnow
|
f2a21670e5d0d880491c390727879e089abf1476
| 7,027
|
cpp
|
C++
|
Operations/albaOpImporterLandmark.cpp
|
IOR-BIC/ALBA
|
b574968b05d9a3a2756dd2ac61d015a0d20232a4
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 9
|
2018-11-19T10:15:29.000Z
|
2021-08-30T11:52:07.000Z
|
Operations/albaOpImporterLandmark.cpp
|
IOR-BIC/ALBA
|
b574968b05d9a3a2756dd2ac61d015a0d20232a4
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
Operations/albaOpImporterLandmark.cpp
|
IOR-BIC/ALBA
|
b574968b05d9a3a2756dd2ac61d015a0d20232a4
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 3
|
2018-06-10T22:56:29.000Z
|
2019-12-12T06:22:56.000Z
|
/*=========================================================================
Program: ALBA (Agile Library for Biomedical Applications)
Module: albaOpImporterLandmark
Authors: Daniele Giunchi, Simone Brazzale
Copyright (c) BIC
All rights reserved. See Copyright.txt or
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "albaDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include "albaOpImporterLandmark.h"
#include <wx/busyinfo.h>
#include "albaDecl.h"
#include "albaEvent.h"
#include "albaGUI.h"
#include "albaVME.h"
#include "albaVMELandmarkCloud.h"
#include "albaVMELandmark.h"
#include "albaTagArray.h"
#include "albaSmartPointer.h"
#include <fstream>
#include "albaProgressBarHelper.h"
const bool DEBUG_MODE = true;
//----------------------------------------------------------------------------
albaOpImporterLandmark::albaOpImporterLandmark(wxString label) : albaOp(label)
{
m_OpType = OPTYPE_IMPORTER;
m_Canundo = false;
m_TypeSeparation = 0;
m_VmeCloud = NULL;
m_OnlyCoordinates = false;
}
//----------------------------------------------------------------------------
albaOpImporterLandmark::~albaOpImporterLandmark( )
{
albaDEL(m_VmeCloud);
}
//----------------------------------------------------------------------------
albaOp* albaOpImporterLandmark::Copy()
{
albaOpImporterLandmark *cp = new albaOpImporterLandmark(m_Label);
cp->m_Canundo = m_Canundo;
cp->m_OpType = m_OpType;
cp->m_Listener = m_Listener;
cp->m_Next = NULL;
cp->m_OnlyCoordinates = m_OnlyCoordinates;
cp->m_VmeCloud = m_VmeCloud;
cp->m_TypeSeparation = m_TypeSeparation;
return cp;
}
//----------------------------------------------------------------------------
void albaOpImporterLandmark::OpRun()
{
wxString fileDir;
m_File = "";
wxString pgd_wildc = "Landmark (*.*)|*.*";
fileDir = albaGetLastUserFolder().c_str();
albaString f = albaGetOpenFile(fileDir,pgd_wildc).c_str();
if(f != "")
{
m_File = f;
if (!m_TestMode)
{
m_Gui = new albaGUI(this);
wxString choices[4] = { _("Comma"),_("Space"),_("Semicolon"),_("Tab") };
m_Gui->Radio(ID_TYPE_SEPARATION,"Separator",&m_TypeSeparation,4,choices,1,"");
m_Gui->Divider();
m_Gui->Bool(ID_TYPE_FILE,"Coordinates only",&m_OnlyCoordinates,true,"Check if the format is \"x y z\"");
m_Gui->Divider();
m_Gui->Label("");
m_Gui->Divider(1);
m_Gui->OkCancel();
ShowGui();
}
}
else
{
albaEventMacro(albaEvent(this, OP_RUN_CANCEL));
}
}
//----------------------------------------------------------------------------
void albaOpImporterLandmark:: OnEvent(albaEventBase *alba_event)
{
if (albaEvent *e = albaEvent::SafeDownCast(alba_event))
{
switch (e->GetId())
{
case wxOK:
OpStop(OP_RUN_OK);
break;
case wxCANCEL:
OpStop(OP_RUN_CANCEL);
break;
case ID_TYPE_FILE:
case ID_TYPE_SEPARATION:
break;
default:
albaEventMacro(*e);
}
}
}
//----------------------------------------------------------------------------
void albaOpImporterLandmark::OpDo()
{
Read();
wxString path, name, ext;
wxSplitPath(m_File.c_str(),&path,&name,&ext);
m_VmeCloud->SetName(name);
albaTagItem tag_Nature;
tag_Nature.SetName("VME_NATURE");
tag_Nature.SetValue("NATURAL");
m_VmeCloud->GetTagArray()->SetTag(tag_Nature);
GetLogicManager()->VmeAdd(m_VmeCloud);
}
//----------------------------------------------------------------------------
void albaOpImporterLandmark::OpStop(int result)
{
HideGui();
albaEventMacro(albaEvent(this,result));
}
//----------------------------------------------------------------------------
void albaOpImporterLandmark::Read()
{
// need the number of landmarks for the progress bar
std::ifstream landmarkNumberPromptFileStream(m_File);
int numberOfLines = 0;
char line[512], separator;
double x = 0, y = 0, z = 0, t = 0;
long counter = 0, linesReaded = 0;
wxString name;
while(!landmarkNumberPromptFileStream.fail())
{
landmarkNumberPromptFileStream.getline(line,512);
numberOfLines++;
}
landmarkNumberPromptFileStream.close();
albaNEW(m_VmeCloud);
if (m_TestMode == true)
{
m_VmeCloud->TestModeOn();
}
std::ifstream landmarkFileStream(m_File);
albaProgressBarHelper progressHelper(m_Listener);
progressHelper.SetTextMode(m_TestMode);
progressHelper.InitProgressBar("Reading Landmark Cloud");
switch (m_TypeSeparation) //_("Comma"),_("Space"),_("Semicolon"),_("Tab")
{
case 0:
separator = ',';
break;
case 1:
separator = ' ';
break;
case 2:
separator = ';';
case 3:
separator = '\t';
break;
}
while(!landmarkFileStream.fail())
{
landmarkFileStream.getline(line, 512);
if(line[0] == '#' || albaString(line) == "")
{
//skip comments and empty lines
linesReaded++;
continue;
}
else if(strncmp(line, "Time",4)==0)
{
char *time = line + 5;
t = atof(time);
counter = 0;
linesReaded++;
continue;
}
else
{
ConvertLine(line, counter, separator, name, x, y, z);
if (m_VmeCloud->GetLandmarkIndex(name.c_str()) == -1)
{
//New Landmark
m_VmeCloud->AppendLandmark(x, y, z, name);
if (t != 0)
{
//this landmark is present only
int idx = m_VmeCloud->GetLandmarkIndex(name);
m_VmeCloud->SetLandmarkVisibility(idx, false, 0);
}
}
else
{
//Set an existing landmark
m_VmeCloud->SetLandmark(name, x, y, z, t);
}
bool visibility = !(x == -9999 && y == -9999 && z == -9999);
m_VmeCloud->SetLandmarkVisibility(counter, visibility, t);
counter++;
linesReaded++;
progressHelper.UpdateProgressBar(linesReaded * 100 / numberOfLines);
}
}
m_VmeCloud->Modified();
m_VmeCloud->ReparentTo(m_Input);
landmarkFileStream.close();
m_Output = m_VmeCloud;
}
void albaOpImporterLandmark::ConvertLine(char *line, int count, char separator, wxString &name, double &x, double &y, double &z)
{
wxString str = wxString(line);
if (m_OnlyCoordinates)
{
name = "LM ";
name << count;
}
else
{
name = str.BeforeFirst(separator);
str = str.After(separator);
}
wxString xStr = str.BeforeFirst(separator);
str = str.AfterFirst(separator);
wxString yStr = str.BeforeFirst(separator);
wxString zStr = str.AfterFirst(separator);
xStr.ToDouble(&x);
yStr.ToDouble(&y);
zStr.ToDouble(&z);
}
| 25.18638
| 128
| 0.588587
|
IOR-BIC
|
f2a38d65b98167a68d5ffc9639eab636bee17c11
| 324
|
cpp
|
C++
|
cpp/example/src/ContainerWithMostH2O/containerWithMostH2O.cpp
|
zcemycl/algoTest
|
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
|
[
"MIT"
] | 1
|
2022-01-26T16:33:45.000Z
|
2022-01-26T16:33:45.000Z
|
cpp/example/src/ContainerWithMostH2O/containerWithMostH2O.cpp
|
zcemycl/algoTest
|
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
|
[
"MIT"
] | null | null | null |
cpp/example/src/ContainerWithMostH2O/containerWithMostH2O.cpp
|
zcemycl/algoTest
|
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
|
[
"MIT"
] | 1
|
2022-01-26T16:35:44.000Z
|
2022-01-26T16:35:44.000Z
|
#include "containerWithMostH2O.h"
int containerWithMostH2O::naive(vector<int>& height){
int l=0;int r=height.size()-1;
int maxV = min(height[l],height[r])*r;
while (l<r){
if (height[l]>=height[r])r-=1;
else l+=1;
maxV = max(maxV,min(height[l],height[r])*(r-l));
}
return maxV;
}
| 24.923077
| 56
| 0.57716
|
zcemycl
|
f2a96756f9c5581c82820de3bde9780e0eaad7de
| 3,500
|
cpp
|
C++
|
09/smoke_basin.t.cpp
|
ComicSansMS/AdventOfCode2021
|
60902d14c356c3375266703e85aca991241afc84
|
[
"Unlicense"
] | null | null | null |
09/smoke_basin.t.cpp
|
ComicSansMS/AdventOfCode2021
|
60902d14c356c3375266703e85aca991241afc84
|
[
"Unlicense"
] | null | null | null |
09/smoke_basin.t.cpp
|
ComicSansMS/AdventOfCode2021
|
60902d14c356c3375266703e85aca991241afc84
|
[
"Unlicense"
] | null | null | null |
#include <smoke_basin.hpp>
#include <catch.hpp>
#include <sstream>
TEST_CASE("Smoke Basin")
{
char const sample_input[] = "2199943210" "\n"
"3987894921" "\n"
"9856789892" "\n"
"8767896789" "\n"
"9899965678" "\n";
Heightmap const map = parseInput(sample_input);
SECTION("Parse Input")
{
CHECK(map.width == 10);
CHECK(map.height == 5);
CHECK(map.map.size() == 50);
CHECK(fmt::format("{}", map) == sample_input);
}
SECTION("Lowest in Neighbourhood")
{
CHECK(!isLowerThan4Neighbourhood(map, 0, 0));
CHECK(isLowerThan4Neighbourhood(map, 1, 0));
CHECK(isLowerThan4Neighbourhood(map, 9, 0));
CHECK(!isLowerThan4Neighbourhood(map, 0, 4));
CHECK(!isLowerThan4Neighbourhood(map, 9, 4));
}
SECTION("Point Equality")
{
CHECK(Point{ .x = 1, .y = 2 } == Point{ .x = 1, .y = 2 });
CHECK(!(Point{ .x = 0, .y = 2 } == Point{ .x = 1, .y = 2 }));
CHECK(!(Point{ .x = 1, .y = 0 } == Point{ .x = 1, .y = 2 }));
CHECK(!(Point{ .x = 5, .y = 5 } == Point{ .x = 1, .y = 2 }));
}
SECTION("Get Low Points")
{
auto points = getLowPoints(map);
REQUIRE(points.size() == 4);
CHECK(points[0] == Point{ .x = 1, .y = 0 });
CHECK(points[1] == Point{ .x = 9, .y = 0 });
CHECK(points[2] == Point{ .x = 2, .y = 2 });
CHECK(points[3] == Point{ .x = 6, .y = 4 });
}
SECTION("Result 1")
{
CHECK(result1(map) == 15);
}
SECTION("Partition Basins")
{
auto basins = partitionBasins(map);
REQUIRE(basins.size() == 4);
CHECK(basins[0].points == std::vector{
Point{ .x = 0, .y = 0 },
Point{ .x = 1, .y = 0 },
Point{ .x = 0, .y = 1 },
});
CHECK(basins[1].points == std::vector{
Point{.x = 5, .y = 0 },
Point{.x = 6, .y = 0 },
Point{.x = 7, .y = 0 },
Point{.x = 8, .y = 0 },
Point{.x = 9, .y = 0 },
Point{.x = 6, .y = 1 },
Point{.x = 8, .y = 1 },
Point{.x = 9, .y = 1 },
Point{.x = 9, .y = 2 },
});
CHECK(basins[2].points == std::vector{
Point{.x = 2, .y = 1 },
Point{.x = 3, .y = 1 },
Point{.x = 4, .y = 1 },
Point{.x = 1, .y = 2 },
Point{.x = 2, .y = 2 },
Point{.x = 3, .y = 2 },
Point{.x = 4, .y = 2 },
Point{.x = 5, .y = 2 },
Point{.x = 0, .y = 3 },
Point{.x = 1, .y = 3 },
Point{.x = 2, .y = 3 },
Point{.x = 3, .y = 3 },
Point{.x = 4, .y = 3 },
Point{.x = 1, .y = 4 },
});
CHECK(basins[3].points == std::vector{
Point{.x = 7, .y = 2 },
Point{.x = 6, .y = 3 },
Point{.x = 7, .y = 3 },
Point{.x = 8, .y = 3 },
Point{.x = 5, .y = 4 },
Point{.x = 6, .y = 4 },
Point{.x = 7, .y = 4 },
Point{.x = 8, .y = 4 },
Point{.x = 9, .y = 4 },
});
}
SECTION("Result 2")
{
CHECK(result2(map) == 1134);
}
}
| 31.25
| 69
| 0.369429
|
ComicSansMS
|
f2ae2ff61ab14da82b661a799256e159355fbb26
| 1,054
|
cpp
|
C++
|
Source/PracticeVeter/Characters/Animations/BaseCharacterAnimInstance.cpp
|
mile634/ExperimentalUE
|
20a7b13af43c79e7b53920b25b451da9212429e3
|
[
"MIT"
] | null | null | null |
Source/PracticeVeter/Characters/Animations/BaseCharacterAnimInstance.cpp
|
mile634/ExperimentalUE
|
20a7b13af43c79e7b53920b25b451da9212429e3
|
[
"MIT"
] | null | null | null |
Source/PracticeVeter/Characters/Animations/BaseCharacterAnimInstance.cpp
|
mile634/ExperimentalUE
|
20a7b13af43c79e7b53920b25b451da9212429e3
|
[
"MIT"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "BaseCharacterAnimInstance.h"
#include "PracticeVeter/Characters/BaseCharacter.h"
#include "PracticeVeter/Components/MovementComponents/MyBaseCharacterMovementComponent.h"
void UBaseCharacterAnimInstance::NativeBeginPlay()
{
Super::NativeBeginPlay();
checkf(TryGetPawnOwner()->IsA<ABaseCharacter>(),
TEXT("UBaseCharacterAnimInstance::NativeBeginPlay() can be used only with BaseCharacter"));
CachedBaseCharacter = StaticCast<ABaseCharacter*>(TryGetPawnOwner());
}
void UBaseCharacterAnimInstance::NativeUpdateAnimation(float DeltaSeconds)
{
Super::NativeUpdateAnimation(DeltaSeconds);
if (!CachedBaseCharacter.IsValid())
{
return;
}
UMyBaseCharacterMovementComponent* CharacterMovement = CachedBaseCharacter->GetBaseCharacterMovementComponent();
Speed = CharacterMovement->Velocity.Size();
bIsFalling = CharacterMovement->IsFalling();
bIsCrouching = CharacterMovement->IsCrouching();
bIsSprinting = CharacterMovement->IsSprinting();
}
| 31.939394
| 113
| 0.805503
|
mile634
|
f2b21addfdadd2d17c3507ad5a4b634ba8889390
| 741
|
cpp
|
C++
|
DataStructure/c++/Linked-list/Remove loop in Linked List.cpp
|
Sauradip07/DataStructures-and-Algorithm
|
d782e2e5cf2caedce7202c4aac43ee0ca3a0c285
|
[
"MIT"
] | 17
|
2021-09-13T14:50:29.000Z
|
2022-01-07T10:53:35.000Z
|
DataStructure/c++/Linked-list/Remove loop in Linked List.cpp
|
Manish4Kumar/DataStructures-and-Algorithm
|
7f3b156af8b380a0a2785782e6437a6cc5835448
|
[
"MIT"
] | 15
|
2021-10-01T04:13:32.000Z
|
2021-11-05T07:49:55.000Z
|
DataStructure/c++/Linked-list/Remove loop in Linked List.cpp
|
Manish4Kumar/DataStructures-and-Algorithm
|
7f3b156af8b380a0a2785782e6437a6cc5835448
|
[
"MIT"
] | 11
|
2021-09-23T14:37:03.000Z
|
2021-11-04T13:22:17.000Z
|
Remove loop in Linked List : https://practice.geeksforgeeks.org/problems/remove-loop-in-linked-list/1#
solution:
void removeLoop(Node* head)
{
Node* low=head;
Node* high=head;
while(low!=NULL and high!=NULL and high->next!=NULL){
low=low->next;
high=high->next->next;
if(low==high) break;
}
if(low==head){
while(high->next!=low){
high=high->next;
}
high->next=NULL;
}
else if(low==high){
low=head;
while(low->next!=high->next){
low=low->next;
high=high->next;
}
high->next=NULL;
}
}
| 25.551724
| 102
| 0.453441
|
Sauradip07
|
f2b290c54fb16b4f60d60b2c9d8596e02023abc1
| 2,542
|
cxx
|
C++
|
periphery/gpio.cxx
|
trotill/11parts_CPP
|
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
|
[
"MIT"
] | null | null | null |
periphery/gpio.cxx
|
trotill/11parts_CPP
|
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
|
[
"MIT"
] | null | null | null |
periphery/gpio.cxx
|
trotill/11parts_CPP
|
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
|
[
"MIT"
] | null | null | null |
/*
* gpio.cxx
*
* Created on: 30 июля 2014 г.
* Author: root
*/
#include "gpio.h"
eErrorTp GpioInInit(u8 gpio)
{
string str;
str= "echo \"" + intToString(gpio) + "\"> /sys/class/gpio/export";
printf("%s\n",str.c_str());
system(str.c_str());
str= "echo \"in\" > /sys/class/gpio/gpio"+intToString(gpio)+"/direction";
printf("%s\n",str.c_str());
system(str.c_str());
return NO_ERROR;
}
eErrorTp GpioOutInit(u8 gpio, u8 defval)
{
string str;
str= "echo \"" + intToString(gpio) + "\"> /sys/class/gpio/export";
system(str.c_str());
str= "echo \""+ intToString(defval) +"\" > /sys/class/gpio/gpio"+intToString(gpio)+"/value";
system(str.c_str());
str= "echo \"out\" > /sys/class/gpio/gpio"+intToString(gpio)+"/direction";
system(str.c_str());
return NO_ERROR;
}
u8 GpioInRead(u8 gpio)
{
string res=ExecResult("cat",(char*)string("/sys/class/gpio/gpio"+intToString(gpio)+"/value").c_str());
//printf("res %s\n",res.c_str());
if (res=="1\n")
return 1;
else
return 0;
}
eErrorTp GpioOnOff(u8 gpio,u8 val)
{
string str;
//if (val)
//val=(~val)&0x1;
str= "echo "+ intToString(val) +" > /sys/class/gpio/gpio"+intToString(gpio)+"/value";
system(str.c_str());
printf("%s\n",str.c_str());
return NO_ERROR;
}
gpio::gpio(string num,string direct,string value){
ngpio=num;
int fd = open("/sys/class/gpio/export", O_WRONLY);
write(fd, num.c_str(), num.size());
close(fd);
access=O_RDONLY;
if (direct=="out"){
access=O_WRONLY;
}
fd_val = open(string_format("/sys/class/gpio/gpio%s/value",num.c_str()).c_str(), access);
//write(fd_val, value.c_str(), value.size());
printf("open %s\n",string_format("/sys/class/gpio/gpio%s/value",num.c_str()).c_str());
//printf("Write %s size %d\n",value.c_str(),value.size());
fd_dir = open(string_format("/sys/class/gpio/gpio%s/direction",num.c_str()).c_str(), O_WRONLY);
write(fd_dir, direct.c_str(), direct.size());
if (direct=="out")
set((char*)value.c_str());
//set("1");
//printf("Write %s size %d\n",value.c_str(),value.size());
//sleep(5);
//int fd = open("/sys/class/gpio/gpio23/value", O_WRONLY);
}
gpio::~gpio(void){
close(fd_val);
close(fd_dir);
}
eErrorTp gpio::set(char * val){
write(fd_val, val, 1);
return NO_ERROR;
}
u32 gpio::get(void){
char buf[2]={0};
u32 len=read(fd_val, buf, 1);
//printf("get %d %d len %d\n",buf[0],buf[1],len);
close(fd_val);
fd_val = open(string_format("/sys/class/gpio/gpio%s/value",ngpio.c_str()).c_str(), access);
return atoi(buf);
}
| 21.542373
| 103
| 0.623131
|
trotill
|
f2b73aff2628270efc7aad6f35bc915ff0db6efe
| 791
|
cpp
|
C++
|
test_storage.cpp
|
squeek502/sol2
|
f4434393ce820dca0bcbc3a5e74bd3100dbe51b9
|
[
"MIT"
] | 1
|
2022-01-15T21:38:38.000Z
|
2022-01-15T21:38:38.000Z
|
test_storage.cpp
|
squeek502/sol2
|
f4434393ce820dca0bcbc3a5e74bd3100dbe51b9
|
[
"MIT"
] | null | null | null |
test_storage.cpp
|
squeek502/sol2
|
f4434393ce820dca0bcbc3a5e74bd3100dbe51b9
|
[
"MIT"
] | null | null | null |
#define SOL_CHECK_ARGUMENTS
#include <catch.hpp>
#include <sol.hpp>
TEST_CASE("storage/registry=construction", "ensure entries from the registry can be retrieved") {
const auto& script = R"(
function f()
return 2
end
)";
sol::state lua;
sol::function f = lua["f"];
sol::reference r = lua["f"];
sol::function regf(lua, f);
sol::reference regr(lua, sol::ref_index(f.registry_index()));
bool isequal = f == r;
REQUIRE(isequal);
isequal = f == regf;
REQUIRE(isequal);
isequal = f == regr;
REQUIRE(isequal);
}
TEST_CASE("storage/main-thread", "ensure round-tripping and pulling out thread data even on 5.1 with a backup works") {
sol::state lua;
{
sol::stack_guard g(lua);
lua_State* orig = lua;
lua_State* ts = sol::main_thread(lua, lua);
REQUIRE(ts == orig);
}
}
| 22.6
| 119
| 0.676359
|
squeek502
|
f2bb6efe0f31897af8c8c46b56d5e298bf6d645d
| 385
|
hpp
|
C++
|
library/ATF/tagLITEM.hpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
library/ATF/tagLITEM.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
library/ATF/tagLITEM.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct tagLITEM
{
unsigned int mask;
int iLink;
unsigned int state;
unsigned int stateMask;
wchar_t szID[48];
wchar_t szUrl[2084];
};
END_ATF_NAMESPACE
| 20.263158
| 108
| 0.657143
|
lemkova
|
f2bcb1eb081756a5c394ddceead203a6b2b9a8fe
| 515
|
hpp
|
C++
|
Engine/Code/Engine/Math/Ray2.hpp
|
tonyatpeking/SmuSpecialTopic
|
b61d44e4efacb3c504847deb4d00234601bca49c
|
[
"MIT"
] | null | null | null |
Engine/Code/Engine/Math/Ray2.hpp
|
tonyatpeking/SmuSpecialTopic
|
b61d44e4efacb3c504847deb4d00234601bca49c
|
[
"MIT"
] | null | null | null |
Engine/Code/Engine/Math/Ray2.hpp
|
tonyatpeking/SmuSpecialTopic
|
b61d44e4efacb3c504847deb4d00234601bca49c
|
[
"MIT"
] | 1
|
2019-10-02T01:48:54.000Z
|
2019-10-02T01:48:54.000Z
|
#pragma once
#include "Engine/Math/Vec2.hpp"
class Ray3;
class Ray2
{
public:
// This is not normalized so that the Evaluate T will match with the 3D version
static Ray2 FromRay3XZ( const Ray3& ray3 );
Ray2() {};
Ray2( const Vec2& point, const Vec2& dir );
~Ray2() {};
void SetStartEnd( const Vec2& start, const Vec2& end );
void Normalzie();
Vec2 Evaluate( float t ) const;
bool IsValid() { return direction != Vec2::ZEROS; };
public:
Vec2 start;
Vec2 direction;
};
| 21.458333
| 83
| 0.642718
|
tonyatpeking
|
f2bec613e0307a903f3c93b54430727aa51028ac
| 583
|
cpp
|
C++
|
src/actions/ActionableObject.cpp
|
MiKlTA/Lust_The_Game
|
aabe4a951ffd7305526466d378ba8b6769c555e8
|
[
"MIT"
] | null | null | null |
src/actions/ActionableObject.cpp
|
MiKlTA/Lust_The_Game
|
aabe4a951ffd7305526466d378ba8b6769c555e8
|
[
"MIT"
] | null | null | null |
src/actions/ActionableObject.cpp
|
MiKlTA/Lust_The_Game
|
aabe4a951ffd7305526466d378ba8b6769c555e8
|
[
"MIT"
] | null | null | null |
#include "Action.h"
#include "ActionableObject.h"
namespace lust {
void ActionableObject::addAction(Action *action)
{
m_dependentActions.insert(action);
}
void ActionableObject::removeAction(const Action *action)
{
auto found = std::find(
m_dependentActions.begin(), m_dependentActions.end(), action
);
if (found != m_dependentActions.end())
{
m_dependentActions.erase(found);
}
}
void ActionableObject::invalidate()
{
for (auto da : m_dependentActions)
{
da->invalidate();
}
}
}
| 15.342105
| 76
| 0.620926
|
MiKlTA
|
f2c02db8e7fd5f2bcfd0e65349df14eaf893ed56
| 13,140
|
cpp
|
C++
|
src/parser/parser.cpp
|
toebsen/angreal
|
772f0b2499ef9b121322f80f2dacdb8754180c38
|
[
"MIT"
] | 4
|
2020-08-30T21:10:47.000Z
|
2021-12-28T13:13:21.000Z
|
src/parser/parser.cpp
|
toebsen/angreal
|
772f0b2499ef9b121322f80f2dacdb8754180c38
|
[
"MIT"
] | 12
|
2020-05-14T12:25:54.000Z
|
2021-08-01T11:01:23.000Z
|
src/parser/parser.cpp
|
toebsen/angreal
|
772f0b2499ef9b121322f80f2dacdb8754180c38
|
[
"MIT"
] | null | null | null |
//
// Created by bichlmaier on 07.02.2020.
//
#include "parser.h"
namespace angreal::parser {
Parser::Parser(const error_handler_t& error_handler)
: error_handler_(error_handler) {}
template <typename Type, typename... Args>
std::shared_ptr<Type> Parser::MakeASTNode(Args&&... args) {
{
auto node = std::make_shared<Type>(std::forward<Args>(args)...);
node->SetLine(current_line_number);
return node;
}
}
std::shared_ptr<AST::Program> Parser::parseProgram(
const std::vector<Token>& tokens) {
AST::statements_t statements;
current_token = tokens.begin();
next_token = tokens.begin() + 1;
while (current_token->type() != Token::Type::EndOfProgram &&
current_token != tokens.end()) {
if (auto stmt = parseStatement()) {
statements.push_back(stmt.value());
}
}
return MakeASTNode<AST::Program>(statements);
}
expression_t Parser::parseExpression(const std::vector<Token>& tokens) {
current_token = tokens.begin();
next_token = tokens.begin() + 1;
return parseRelational();
}
void Parser::consume() {
// std::cout << "consuming: " << *next_token << std::endl;
current_token = next_token;
next_token = current_token + 1;
if (current_token->type() == Token::Type::NewLine) {
++current_line_number;
consume();
}
}
void Parser::expectToken(Token::Type t) const {
if (current_token->type() != t) {
std::stringstream ss;
ss << "Expected " << Token::type2str(t)
<< ", but got: " << Token::type2str(current_token->type());
error_handler_->ParserError(ss.str(), *current_token);
}
}
expression_t Parser::parseRelational() {
expression_t expr = parseAdditive();
if (current_token->type() == Token::Type::RelationalOp) {
auto opType = current_token->value();
consume();
auto rhs = parseAdditive();
return MakeASTNode<AST::BinaryOperation>(opType, expr, rhs);
}
return expr;
}
expression_t Parser::parseAdditive() {
expression_t expr = parseMultiplicative();
if (current_token->type() == Token::Type::AdditiveOp ||
current_token->type() == Token::Type::AndStatement) {
auto opType = current_token->value();
consume();
auto rhs = parseMultiplicative();
return MakeASTNode<AST::BinaryOperation>(opType, expr, rhs);
}
return expr;
}
expression_t Parser::parseMultiplicative() {
expression_t expr = parseUnary();
if (current_token->type() == Token::Type::MulOp ||
current_token->type() == Token::Type::DivOp ||
current_token->type() == Token::Type::OrStatement) {
auto opType = current_token->value();
consume();
auto rhs = parsePrimary();
return MakeASTNode<AST::BinaryOperation>(opType, expr, rhs);
}
return expr;
}
expression_t Parser::parseUnary() {
if (current_token->type() == Token::Type::AdditiveOp ||
current_token->type() == Token::Type::Exclamation) {
auto opType = current_token->value();
consume();
AST::expression_t expression = parseRelational();
return MakeASTNode<AST::UnaryOperation>(opType, expression);
}
return parseFunctionCall();
}
AST::expressions_t Parser::parseActualParams() {
AST::expressions_t params;
params.push_back(parseRelational());
while (current_token->type() == Token::Type::Comma) {
consume();
params.push_back(parseRelational());
}
return params;
}
expression_t Parser::parseFunctionCall() {
auto expression = parsePrimary();
while (true) {
if (current_token->type() == Token::Type::LeftBracket) {
consume(); //(
AST::expressions_t args;
if (current_token->type() != Token::Type::RightBracket) {
args = parseActualParams();
}
expectToken(Token::Type::RightBracket);
consume();
expression = MakeASTNode<AST::FunctionCall>(expression, args);
} else if (current_token->type() == Token::Type::Dot) {
consume();
expectToken(Token::Type::Identifier);
auto identifier = current_token->value();
consume();
expression = MakeASTNode<AST::Get>(expression, identifier);
} else {
break;
}
}
return expression;
}
expression_t Parser::parsePrimary() {
if (current_token->type() == Token::Type::Boolean ||
current_token->type() == Token::Type::Integer ||
current_token->type() == Token::Type::Float ||
current_token->type() == Token::Type::String) {
TypeHelper::Type decl =
TypeHelper::mapTokenToLiteralType(current_token->type());
auto value = current_token->value();
consume();
return TypeHelper::mapTypeToLiteral(decl, value);
}
if (current_token->type() == Token::Type::SelfStatement) {
consume();
return MakeASTNode<AST::Self>();
}
if (current_token->type() == Token::Type::Identifier) {
auto value = current_token->value();
consume();
if (value == "super") {
expectToken(Token::Type::Dot);
consume();
expectToken(Token::Type::Identifier);
auto ident = current_token->value();
consume();
return MakeASTNode<AST::Super>(ident);
}
return MakeASTNode<AST::IdentifierLiteral>(value);
}
if (current_token->type() == Token::Type::LeftBracket) {
consume();
auto expression = parseRelational();
expectToken(Token::Type::RightBracket);
consume();
return expression;
}
return nullptr;
}
statement_t Parser::parseVariableDeclaration() {
std::string identifier;
AST::expression_t expression;
consume();
expectToken(Token::Type::Identifier);
identifier = current_token->value();
consume();
expectToken(Token::Type::Equal);
consume();
expression = parseRelational();
return MakeASTNode<AST::Declaration>(identifier, expression);
}
expression_t Parser::parseAssignment(const expression_t& expression) {
expectToken(Token::Type::Equal);
consume();
auto value = parseRelational();
if (auto ident = std::dynamic_pointer_cast<IdentifierLiteral>(expression)) {
return MakeASTNode<AST::Assignment>(ident->name, value);
}
if (auto get = std::dynamic_pointer_cast<Get>(expression)) {
return MakeASTNode<AST::Set>(get->expression, get->identifier, value);
}
return nullptr;
}
AST::formal_parameters Parser::parseFormalParameters() {
AST::formal_parameters parameters;
expectToken(Token::Type::LeftBracket);
consume();
if (current_token->type() != Token::Type::RightBracket) {
while (current_token->type() != Token::Type::RightBracket) {
auto param = parseFormalParameter();
parameters.push_back(param);
if (current_token->type() != Token::Type::RightBracket) {
expectToken(Token::Type::Comma);
consume();
}
}
}
expectToken(Token::Type::RightBracket);
consume();
return parameters;
}
std::shared_ptr<AST::FormalParameter> Parser::parseFormalParameter() {
expectToken(Token::Type::Identifier);
std::string identifier = current_token->value();
consume();
return MakeASTNode<AST::FormalParameter>(identifier);
}
statement_t Parser::parseFunctionDeclaration() {
std::string identifier;
consume();
expectToken(Token::Type::Identifier);
identifier = current_token->value();
consume();
auto parameters = parseFormalParameters();
auto block = std::dynamic_pointer_cast<Block>(parseBlock());
return MakeASTNode<AST::FunctionDeclaration>(identifier, parameters,
block->statements);
}
statement_t Parser::parseBlock() {
AST::statements_t statements;
expectToken(Token::Type::LeftCurlyBracket);
consume();
if (current_token->type() == Token::Type::RightCurlyBracket) {
// don't parse empty block
consume();
return MakeASTNode<AST::Block>(statements);
}
do {
if (auto stmt = parseStatement()) {
statements.push_back(stmt.value());
}
} while (!(current_token->type() == Token::Type::RightCurlyBracket ||
current_token->type() == Token::Type::EndOfProgram));
expectToken(Token::Type::RightCurlyBracket);
consume();
return MakeASTNode<AST::Block>(statements);
}
statement_t Parser::parseReturnDeclaration() {
AST::expression_t expression;
consume();
expression = parseRelational();
return MakeASTNode<AST::Return>(expression);
}
statement_t Parser::parsePrintStatement() {
AST::expressions_t args;
consume(); // identifier
consume(); //(
if (current_token->type() != Token::Type::RightBracket) {
args = parseActualParams();
}
expectToken(Token::Type::RightBracket);
consume();
return MakeASTNode<AST::Print>(args);
}
std::optional<statement_t> Parser::parseStatement() {
current_line_number = current_token->position().line;
if (current_token->type() == Token::Type::VarStatement) {
return parseVariableDeclaration();
}
if (current_token->type() == Token::Type::DefStatement) {
return parseFunctionDeclaration();
}
if (current_token->type() == Token::Type::ClassStatement) {
return parseClassDeclaration();
}
if (current_token->type() == Token::Type::PrintStatement) {
return parsePrintStatement();
}
if (current_token->type() == Token::Type::LeftCurlyBracket) {
return parseBlock();
}
if (current_token->type() == Token::Type::ReturnStatement) {
return parseReturnDeclaration();
}
if (current_token->type() == Token::Type::IfStatement) {
return parseIfStatement();
}
if (current_token->type() == Token::Type::WhileStatement) {
return parseWhileStatement();
}
if (current_token->type() == Token::Type::EndOfProgram) {
return std::nullopt;
}
if (current_token->type() == Token::Type::Comment) {
consume();
return std::nullopt;
}
auto expr = parseRelational();
if (current_token->type() == Token::Type::Equal) {
expr = parseAssignment(expr);
}
if (expr) {
return MakeASTNode<ExpressionStatement>(expr);
}
consume();
return std::nullopt;
}
statement_t Parser::parseIfStatement() {
consume();
expression_t condition = parseRelational();
block_t if_branch = std::dynamic_pointer_cast<Block>(parseBlock());
block_t else_branch;
if (current_token->type() == Token::Type::Identifier &&
current_token->value() == "else") {
consume();
else_branch = std::dynamic_pointer_cast<Block>(parseBlock());
}
return MakeASTNode<AST::IfStatement>(condition, if_branch, else_branch);
}
statement_t Parser::parseWhileStatement() {
consume();
expression_t condition = parseRelational();
block_t block = std::dynamic_pointer_cast<Block>(parseBlock());
return MakeASTNode<AST::WhileStatement>(condition, block);
}
statement_t Parser::parseClassDeclaration() {
consume(); // class
expectToken(Token::Type::Identifier);
auto identifier = *current_token;
consume();
std::optional<identifier_t> superclass;
if (current_token->type() == Token::Type::LeftBracket) {
// optional superclass
consume();
expectToken(Token::Type::Identifier);
superclass = MakeASTNode<IdentifierLiteral>(current_token->value());
consume();
expectToken(Token::Type::RightBracket);
consume();
}
expectToken(Token::Type::LeftCurlyBracket);
consume();
functions_t methods;
while (true) {
if (current_token->type() == Token::Type::RightCurlyBracket) {
break;
}
if (current_token->type() == Token::Type::DefStatement) {
methods.push_back(std::dynamic_pointer_cast<FunctionDeclaration>(
parseFunctionDeclaration()));
} else {
error_handler_->ParserError(
"Only function declarations are allowed inside declaration of "
"class !",
identifier);
break;
}
}
expectToken(Token::Type::RightCurlyBracket);
consume();
return MakeASTNode<AST::ClassDeclaration>(identifier.value(), methods,
superclass);
}
} // namespace angreal::parser
| 31.211401
| 81
| 0.59863
|
toebsen
|
f2c03315b9f772048e9285a63a30d5021f782a3e
| 1,800
|
cpp
|
C++
|
client/src/user_interface/game_over.cpp
|
dima1997/PORTAL_2D_copy
|
7618d970feded3fc05fda0c422a5d76a1d3056c7
|
[
"MIT"
] | null | null | null |
client/src/user_interface/game_over.cpp
|
dima1997/PORTAL_2D_copy
|
7618d970feded3fc05fda0c422a5d76a1d3056c7
|
[
"MIT"
] | null | null | null |
client/src/user_interface/game_over.cpp
|
dima1997/PORTAL_2D_copy
|
7618d970feded3fc05fda0c422a5d76a1d3056c7
|
[
"MIT"
] | null | null | null |
#include "../../includes/user_interface/game_over.h"
#include "ui_GameOver.h"
#include "../../includes/threads/play_result.h"
#include <QWidget>
#include <QDesktopWidget>
#include <string>
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
/*
PRE: Recibe un resultado de juego.
POST:Iniicaliza una ventana de fin de juego.
*/
GameOver::GameOver(PlayResult & playResult, QWidget *parent)
: QWidget(parent)
{
Ui::GameOver gameOver;
gameOver.setupUi(this);
this->setFixedSize(WINDOW_WIDTH, WINDOW_HEIGHT);
this->hide();
this->move(
QApplication::desktop()->screen()->rect().center()
- (this->rect()).center()
);
this->set_game_status(playResult);
this->set_players_status(playResult);
}
/*
PRE: Recibe el resultado de un juego.
POST: Setea la etiqueta de estado del juego.
*/
void GameOver::set_game_status(PlayResult & playResult){
QLabel* gameStatusLabel = findChild<QLabel*>("gameStatusLabel");
GameStatus gameStatus = playResult.get_game_status();
if (gameStatus == GAME_STATUS_WON){
gameStatusLabel->setText("WON");
} else if (gameStatus == GAME_STATUS_LOST){
gameStatusLabel->setText("LOST");
} else {
gameStatusLabel->setText("NOT_FINISHED");
}
gameStatusLabel->setStyleSheet("QLabel { color : white; font-size: 20pt }");
}
/*
PRE: Recibe el resultado de un juego.
POST: Setea el estado de los jugadores en el text browser.
*/
void GameOver::set_players_status(PlayResult & playResult){
QTextBrowser* playersStatusTextBrowser =
findChild<QTextBrowser*>("playersStatusTextBrowser");
std::string playersStatusStr = playResult.get_players_status();
playersStatusTextBrowser->append(playersStatusStr.c_str());
}
/*Destruye ventantana.*/
GameOver::~GameOver() = default;
| 28.571429
| 80
| 0.707778
|
dima1997
|
f2c0b8fb27d8d25f924b9a57f850141d94ee4687
| 9,663
|
cp
|
C++
|
MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Account_Panels/Authentication_Panels/CPrefsAccountAuth.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 12
|
2015-04-21T16:10:43.000Z
|
2021-11-05T13:41:46.000Z
|
MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Account_Panels/Authentication_Panels/CPrefsAccountAuth.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 2
|
2015-11-02T13:32:11.000Z
|
2019-07-10T21:11:21.000Z
|
MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Account_Panels/Authentication_Panels/CPrefsAccountAuth.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 6
|
2015-01-12T08:49:12.000Z
|
2021-03-27T09:11:10.000Z
|
/*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Source for CPrefsAccountAuth class
#include "CPrefsAccountAuth.h"
#include "CAuthPlugin.h"
#include "CCertificateManager.h"
#include "CINETAccount.h"
#include "CMulberryCommon.h"
#include "CPluginManager.h"
#include "CPreferences.h"
#include "CPreferencesDialog.h"
#include "CPrefsAuthPanel.h"
#include "CPrefsAuthPlainText.h"
#include "CPrefsAuthKerberos.h"
#include "CPrefsAuthAnonymous.h"
#include <LCheckBox.h>
#include <LPopupButton.h>
// C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S
// Default constructor
CPrefsAccountAuth::CPrefsAccountAuth()
{
mCurrentPanel = nil;
mCurrentPanelNum = 0;
}
// Constructor from stream
CPrefsAccountAuth::CPrefsAccountAuth(LStream *inStream)
: CPrefsTabSubPanel(inStream)
{
mCurrentPanel = nil;
mCurrentPanelNum = 0;
}
// Default destructor
CPrefsAccountAuth::~CPrefsAccountAuth()
{
}
// O T H E R M E T H O D S ____________________________________________________________________________
// Get details of sub-panes
void CPrefsAccountAuth::FinishCreateSelf(void)
{
// Do inherited
CPrefsTabSubPanel::FinishCreateSelf();
// Get controls
mAuthPopup = (LPopupButton*) FindPaneByID(paneid_AccountAuthPopup);
mAuthSubPanel = (LView*) FindPaneByID(paneid_AccountAuthPanel);
mTLSPopup = (LPopupButton*) FindPaneByID(paneid_AccountTLSPopup);
mUseTLSClientCert = (LCheckBox*) FindPaneByID(paneid_AccountUseTLSClientCert);
mTLSClientCert = (LPopupButton*) FindPaneByID(paneid_AccountTLSClientCert);
BuildCertPopup();
// Link controls to this window
UReanimator::LinkListenerToBroadcasters(this,this,RidL_CPrefsAccountAuthBtns);
// Start with first panel
SetAuthPanel(cdstring::null_str);
}
// Handle buttons
void CPrefsAccountAuth::ListenToMessage(
MessageT inMessage,
void *ioParam)
{
switch (inMessage)
{
case msg_MailAccountAuth:
{
cdstring temp = ::GetPopupMenuItemTextUTF8(mAuthPopup);
SetAuthPanel(temp);
break;
}
case msg_AccountTLSPopup:
TLSItemsState();
break;
case msg_AccountUseTLSClientCert:
TLSItemsState();
break;
}
}
// Toggle display of IC
void CPrefsAccountAuth::ToggleICDisplay(bool IC_on)
{
if (mCurrentPanel)
mCurrentPanel->ToggleICDisplay(IC_on);
}
// Set prefs
void CPrefsAccountAuth::SetData(void* data)
{
CINETAccount* account = (CINETAccount*) data;
// Build popup from panel
BuildAuthPopup(account);
if (mCurrentPanel)
mCurrentPanel->SetAuth(account->GetAuthenticator().GetAuthenticator());
InitTLSItems(account);
mTLSPopup->SetValue(account->GetTLSType() + 1);
mUseTLSClientCert->SetValue(account->GetUseTLSClientCert());
// Match fingerprint in list
for(cdstrvect::const_iterator iter = mCertFingerprints.begin(); iter != mCertFingerprints.end(); iter++)
{
if (account->GetTLSClientCert() == *iter)
{
::SetPopupByName(mTLSClientCert, mCertSubjects.at(iter - mCertFingerprints.begin()));
break;
}
}
TLSItemsState();
}
// Force update of prefs
void CPrefsAccountAuth::UpdateData(void* data)
{
CINETAccount* account = (CINETAccount*) data;
// Copy info from panel into prefs
cdstring temp = ::GetPopupMenuItemTextUTF8(mAuthPopup);
// Special for anonymous
if (mAuthPopup->GetValue() == ::CountMenuItems(mAuthPopup->GetMacMenuH()) - 1)
temp = "None";
account->GetAuthenticator().SetDescriptor(temp);
if (mCurrentPanel)
mCurrentPanel->UpdateAuth(account->GetAuthenticator().GetAuthenticator());
int popup = mTLSPopup->GetValue() - 1;
account->SetTLSType((CINETAccount::ETLSType) (mTLSPopup->GetValue() - 1));
account->SetUseTLSClientCert(mUseTLSClientCert->GetValue());
if (account->GetUseTLSClientCert() && ::CountMenuItems(mTLSClientCert->GetMacMenuH()))
account->SetTLSClientCert(mCertFingerprints.at(mTLSClientCert->GetValue() - 1));
else
account->SetTLSClientCert(cdstring::null_str);
}
// Set auth panel
void CPrefsAccountAuth::SetAuthPanel(const cdstring& auth_type)
{
// Find matching auth plugin
CAuthPlugin* plugin = CPluginManager::sPluginManager.GetAuthPlugin(auth_type);
CAuthPlugin::EAuthPluginUIType ui_type = plugin ? plugin->GetAuthUIType() :
(auth_type == "Plain Text" ? CAuthPlugin::eAuthUserPswd : CAuthPlugin::eAuthAnonymous);
ResIDT panel;
switch(ui_type)
{
case CAuthPlugin::eAuthUserPswd:
panel = paneid_PrefsAuthPlainText;
break;
case CAuthPlugin::eAuthKerberos:
panel = paneid_PrefsAuthKerberos;
break;
case CAuthPlugin::eAuthAnonymous:
panel = paneid_PrefsAuthAnonymous;
break;
}
if (mAuthType != auth_type)
{
mAuthType = auth_type;
// First remove and update any existing panel
mAuthSubPanel->DeleteAllSubPanes();
// Update to new panel id
mCurrentPanelNum = panel;
// Make panel area default so new panel is automatically added to it
if (panel)
{
SetDefaultView(mAuthSubPanel);
mAuthSubPanel->Hide();
CPreferencesDialog* prefs_dlog = (CPreferencesDialog*) mSuperView;
while(prefs_dlog->GetPaneID() != paneid_PreferencesDialog)
prefs_dlog = (CPreferencesDialog*) prefs_dlog->GetSuperView();
LCommander* defCommander;
prefs_dlog->GetSubCommanders().FetchItemAt(1, defCommander);
prefs_dlog->SetDefaultCommander(defCommander);
mCurrentPanel = (CPrefsAuthPanel*) UReanimator::ReadObjects('PPob', mCurrentPanelNum);
mCurrentPanel->FinishCreate();
mAuthSubPanel->Show();
}
else
{
mAuthSubPanel->Refresh();
mCurrentPanel = nil;
}
}
}
void CPrefsAccountAuth::BuildAuthPopup(CINETAccount* account)
{
// Copy info
cdstring set_name;
short set_value = -1;
switch(account->GetAuthenticatorType())
{
case CAuthenticator::eNone:
set_value = -1;
break;
case CAuthenticator::ePlainText:
set_value = 1;
break;
case CAuthenticator::eSSL:
set_value = 0;
break;
case CAuthenticator::ePlugin:
set_name = account->GetAuthenticator().GetDescriptor();
break;
}
// Remove any existing plugin items from main menu
MenuHandle menuH = mAuthPopup->GetMacMenuH();
short num_remove = ::CountMenuItems(menuH) - 4;
for(short i = 0; i < num_remove; i++)
::DeleteMenuItem(menuH, 2);
cdstrvect plugin_names;
CPluginManager::sPluginManager.GetAuthPlugins(plugin_names);
std::sort(plugin_names.begin(), plugin_names.end());
short index = 1;
for(cdstrvect::const_iterator iter = plugin_names.begin(); iter != plugin_names.end(); iter++, index++)
{
::InsertMenuItem(menuH, "\p?", index);
::SetMenuItemTextUTF8(menuH, index + 1, *iter);
if (*iter == set_name)
set_value = index + 1;
}
// Force max/min update
mAuthPopup->SetMenuMinMax();
// Set value
StopListening();
mAuthPopup->SetValue((set_value > 0) ? set_value : index + 3 + set_value);
StartListening();
cdstring temp = ::GetPopupMenuItemTextUTF8(mAuthPopup);
SetAuthPanel(temp);
}
void CPrefsAccountAuth::InitTLSItems(CINETAccount* account)
{
// Enable each item based on what the protocol supports
bool enabled = false;
for(int i = CINETAccount::eNoTLS; i <= CINETAccount::eTLSTypeMax; i++)
{
if (account->SupportsTLSType(static_cast<CINETAccount::ETLSType>(i)))
{
::EnableItem(mTLSPopup->GetMacMenuH(), i + 1);
enabled = true;
}
else
::DisableItem(mTLSPopup->GetMacMenuH(), i + 1);
}
// Hide if no plugin present or none enabled
if (enabled && CPluginManager::sPluginManager.HasSSL())
{
mTLSPopup->Show();
FindPaneByID(paneid_AccountTLSGroup)->Show();
//mUseTLSClientCert->Show();
//mTLSClientCert->Show();
}
else
{
mTLSPopup->Hide();
FindPaneByID(paneid_AccountTLSGroup)->Hide();
//mUseTLSClientCert->Hide();
//mTLSClientCert->Hide();
// Disable the auth item
::DisableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue());
}
}
void CPrefsAccountAuth::BuildCertPopup()
{
// Only if certs are available
if (CCertificateManager::HasCertificateManager())
{
// Get list of private certificates
CCertificateManager::sCertificateManager->GetPrivateCertificates(mCertSubjects, mCertFingerprints);
// Remove any existing items from main menu
MenuHandle menuH = mTLSClientCert->GetMacMenuH();
while(::CountMenuItems(menuH))
::DeleteMenuItem(menuH, 1);
short index = 1;
for(cdstrvect::const_iterator iter = mCertSubjects.begin(); iter != mCertSubjects.end(); iter++, index++)
::AppendItemToMenu(menuH, index, (*iter).c_str());
// Force max/min update
mTLSClientCert->SetMenuMinMax();
}
}
void CPrefsAccountAuth::TLSItemsState()
{
// TLS popup
if (mTLSPopup->GetValue() - 1 == CINETAccount::eNoTLS)
{
mUseTLSClientCert->Disable();
mTLSClientCert->Disable();
if (mAuthPopup->GetValue() == mAuthPopup->GetMaxValue())
mAuthPopup->SetValue(1);
::DisableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue());
}
else
{
mUseTLSClientCert->Enable();
if (mUseTLSClientCert->GetValue())
{
mTLSClientCert->Enable();
::EnableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue());
}
else
{
mTLSClientCert->Disable();
if (mAuthPopup->GetValue() == mAuthPopup->GetMaxValue())
mAuthPopup->SetValue(1);
::DisableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue());
}
}
}
| 26.841667
| 107
| 0.732381
|
mulberry-mail
|
f2c10f99fbebf3fd599e1bcd8fd28bbbfa8ac15a
| 676
|
cpp
|
C++
|
binary-tree/check-if-subtree.cpp
|
Strider-7/code
|
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
|
[
"MIT"
] | null | null | null |
binary-tree/check-if-subtree.cpp
|
Strider-7/code
|
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
|
[
"MIT"
] | null | null | null |
binary-tree/check-if-subtree.cpp
|
Strider-7/code
|
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
Node(int x)
{
data = x;
left = nullptr;
right = nullptr;
}
};
bool isIdentical(Node* T, Node* S) {
if (!T && !S)
return true;
if (!T || !S)
return false;
return T->data == S->data && isIdentical(T->left, S->left) && isIdentical(T->right, S->right);
}
bool isSubTree(Node* T, Node* S) {
if (!S)
return true;
if (!T)
return false;
if (isIdentical(T, S))
return true;
return isSubTree(T->left, S) || isSubTree(T->right, S);
}
| 18.27027
| 99
| 0.486686
|
Strider-7
|
f2c43230a7babcb209a2c7b93636ad6da4111bc2
| 755
|
cpp
|
C++
|
ReeeEngine/src/ReeeEngine/Rendering/Context/SampleState.cpp
|
Lewisscrivens/ReeeEngine
|
abb31ef7e1adb553fafe02c4f9bd60ceb520acbf
|
[
"MIT"
] | null | null | null |
ReeeEngine/src/ReeeEngine/Rendering/Context/SampleState.cpp
|
Lewisscrivens/ReeeEngine
|
abb31ef7e1adb553fafe02c4f9bd60ceb520acbf
|
[
"MIT"
] | null | null | null |
ReeeEngine/src/ReeeEngine/Rendering/Context/SampleState.cpp
|
Lewisscrivens/ReeeEngine
|
abb31ef7e1adb553fafe02c4f9bd60ceb520acbf
|
[
"MIT"
] | null | null | null |
#include "SampleState.h"
namespace ReeeEngine
{
SampleState::SampleState(Graphics& graphics)
{
// Create sampler default options for UV read type.
D3D11_SAMPLER_DESC samplerOptions = {};
samplerOptions.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerOptions.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerOptions.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerOptions.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
// Create sampler state and check/log errors.
HRESULT result = GetDevice(graphics)->CreateSamplerState(&samplerOptions, &sampler);
LOG_DX_ERROR(result);
}
void SampleState::Add(Graphics& graphics) noexcept
{
// Add sampler to rendering pipeline.
GetContext(graphics)->PSSetSamplers(0, 1, sampler.GetAddressOf());
}
}
| 31.458333
| 86
| 0.778808
|
Lewisscrivens
|
f2c4b177991326df24f69a82d0f92a72c44a23c9
| 3,632
|
cpp
|
C++
|
03/minik/src/target_x86/x86_conv.cpp
|
nokia-wroclaw/nokia-book
|
dd397958b5db039a2f53e555c2becfc419065264
|
[
"MIT"
] | 104
|
2015-06-30T07:41:42.000Z
|
2022-02-28T08:56:37.000Z
|
03/minik/src/target_x86/x86_conv.cpp
|
nokia-wroclaw/nokia-book
|
dd397958b5db039a2f53e555c2becfc419065264
|
[
"MIT"
] | null | null | null |
03/minik/src/target_x86/x86_conv.cpp
|
nokia-wroclaw/nokia-book
|
dd397958b5db039a2f53e555c2becfc419065264
|
[
"MIT"
] | 22
|
2015-06-11T14:40:49.000Z
|
2021-12-27T19:13:11.000Z
|
#include "analysis/control_flow_graph.hpp"
#include "analysis/live_variables.hpp"
#include "ir/ir_printer.hpp"
#include "x86_assembler.hpp"
#include "x86_conv.hpp"
#include "utils/headers.hpp"
#include <list>
#include <iostream>
namespace
{
Ir::Block rewrite_block(SymbolTable &st, const Ir::Block &_block)
{
Ir::Block result = _block;
step("live variables");
auto cfg = buildControlFlowGraph(result);
auto lv = LiveVariablesDataFlowAnalysis::analyse(cfg);
LiveVariablesDataFlowAnalysis::dump(std::cerr, cfg, lv);
auto it = result.begin();
std::set<int> visited;
step("input");
std::cerr << to_string(result) << "\n";
step("transformation");
while (it != result.end()) {
if (it->type == Ir::InstructionType::Call and visited.find(it->extra) == visited.end()) {
auto v = it->extra;
auto lv_in = lv.entry[v];
const auto &fdef = st.getFunction(it->arguments[0]);
visited.insert(v);
auto orig_it = it;
std::cerr << "found call: " << to_string(*it) << "\n";
std::cerr << "live variables at entry: " << LiveVariablesDataFlowAnalysis::to_string(lv.entry.at(v)) << "\n";
std::string ret;
for (auto r : fdef.modifiedRegs) {
ret += " ";
ret += to_string(r);
}
std::cerr << "function modifies: " << ret << "\n";
bool hasArguments = false;
do {
--it;
hasArguments |= it->type == Ir::InstructionType::Push;
} while (it->type == Ir::InstructionType::Push);
++it;
std::list<Ir::Argument> saved;
for (auto r : lv_in) {
if (r.is(Ir::ArgumentType::PinnedHardRegister) and fdef.modifiedRegs.find(r) != fdef.modifiedRegs.end()) {
auto helper = Ir::Instruction{Ir::InstructionType::Push, {r}, 0};
result.insert(it, helper);
saved.push_front(r);
}
}
if (saved.size() > 0) {
it = orig_it;
++it;
if (hasArguments) ++it;
for (auto r : saved) {
auto helper = Ir::Instruction{Ir::InstructionType::Pop, {r}, 0};
result.insert(it, helper);
}
}
}
// TODO: temporary remove of Meta instructions CallerSave/CallerRestore
if (it->type == Ir::InstructionType::Meta) {
if (it->arguments[0].content == int(Ir::MetaTag::CallerSave)
or it->arguments[0].content == int(Ir::MetaTag::CallerRestore)) {
it = result.erase(it);
}
} else {
++it;
}
}
step("output");
std::cerr << to_string(result) << "\n";
return result;
}
} // end of anonymous namespace
std::set<Ir::Argument> getAllGeneralPurposeHardRegisters()
{
std::set<Ir::Argument> ir;
for (int i = 0; i < 6; i++) {
ir.insert(Ir::Argument::PinnedHardRegister(i));
}
return ir;
}
void x86_conv(SymbolTable &st)
{
for (auto &p : st.functionsMap) {
if (p.second.predefined) {
p.second.modifiedRegs = getAllGeneralPurposeHardRegisters();
} else {
p.second.modifiedRegs = computeModifiedRegisters(p.second.body);
}
}
for (auto &p : st.functionsMap) {
if (not p.second.predefined) {
subpass("fuction " + p.second.name);
p.second.body = rewrite_block(st, p.second.body);
}
}
}
| 27.725191
| 122
| 0.528359
|
nokia-wroclaw
|
f2c4dc83ec8d1f9807509068206be97a0cce3eb0
| 407
|
cc
|
C++
|
examples/Example3/main.cc
|
stognini/AdePT
|
9a106b83f421938ad8f4d8567d199c84f339e6c9
|
[
"Apache-2.0"
] | null | null | null |
examples/Example3/main.cc
|
stognini/AdePT
|
9a106b83f421938ad8f4d8567d199c84f339e6c9
|
[
"Apache-2.0"
] | null | null | null |
examples/Example3/main.cc
|
stognini/AdePT
|
9a106b83f421938ad8f4d8567d199c84f339e6c9
|
[
"Apache-2.0"
] | null | null | null |
// SPDX-FileCopyrightText: 2020 CERN
// SPDX-License-Identifier: Apache-2.0
#include "common.h"
#include "loop.h"
#include <iostream>
int main(int argc, char **argv)
{
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " nparticles" << std::endl;
return 0;
}
int nparticles = std::atoi(argv[1]);
#ifndef __CUDACC__
simulate(nparticles);
#else
simulate_all(nparticles);
#endif
return 0;
}
| 15.653846
| 66
| 0.653563
|
stognini
|
f2d318974ca25caa783bfda28c4121b7d15a1c02
| 354
|
cpp
|
C++
|
src/L/L1226.cpp
|
wlhcode/lscct
|
7fd112a9d1851ddcf41886d3084381a52e84a3ce
|
[
"MIT"
] | null | null | null |
src/L/L1226.cpp
|
wlhcode/lscct
|
7fd112a9d1851ddcf41886d3084381a52e84a3ce
|
[
"MIT"
] | null | null | null |
src/L/L1226.cpp
|
wlhcode/lscct
|
7fd112a9d1851ddcf41886d3084381a52e84a3ce
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
string s;
string o;
main(){
long long a;
bool first=true;
cin>>a;
s+=to_string(a);
sort(s.begin(),s.end());
for(int i=2;i<=9;i++){
o.clear();
o+=to_string(a*i);
sort(o.begin(),o.end());
if(s==o){
if(!first) cout<<" ";
cout<<i;
first=false;
}
}
if(first) cout<<"NO";
cout<<endl;
}
| 14.16
| 26
| 0.553672
|
wlhcode
|
f2d7680e1d2d38fcd1f235c4d44731acfc3b1834
| 11,285
|
hpp
|
C++
|
src/core/TChem_KineticModelGasConstData.hpp
|
sandialabs/TChem
|
c9d00d7d283c8687a5aa4549161e29a08d3d39d6
|
[
"BSD-2-Clause"
] | 30
|
2020-10-28T08:07:36.000Z
|
2022-03-29T15:22:30.000Z
|
src/core/TChem_KineticModelGasConstData.hpp
|
sandialabs/TChem
|
c9d00d7d283c8687a5aa4549161e29a08d3d39d6
|
[
"BSD-2-Clause"
] | 2
|
2021-02-22T21:47:47.000Z
|
2022-03-16T16:38:07.000Z
|
src/core/TChem_KineticModelGasConstData.hpp
|
sandialabs/TChem
|
c9d00d7d283c8687a5aa4549161e29a08d3d39d6
|
[
"BSD-2-Clause"
] | 10
|
2020-10-28T01:11:41.000Z
|
2021-06-16T08:15:28.000Z
|
/* =====================================================================================
TChem version 2.0
Copyright (2020) NTESS
https://github.com/sandialabs/TChem
Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains
certain rights in this software.
This file is part of TChem. TChem is open source software: you can redistribute it
and/or modify it under the terms of BSD 2-Clause License
(https://opensource.org/licenses/BSD-2-Clause). A copy of the licese is also
provided under the main directory
Questions? Contact Cosmin Safta at <csafta@sandia.gov>, or
Kyungjoo Kim at <kyukim@sandia.gov>, or
Oscar Diaz-Ibarra at <odiazib@sandia.gov>
Sandia National Laboratories, Livermore, CA, USA
===================================================================================== */
#ifndef __TCHEM_KINETIC_MODEL_GAS_CONST_DATA_HPP__
#define __TCHEM_KINETIC_MODEL_GAS_CONST_DATA_HPP__
#include "TChem_Util.hpp"
#include "TChem_KineticModelData.hpp"
namespace TChem {
template<typename DeviceType>
struct KineticModelGasConstData {
public:
using device_type = DeviceType;
using exec_space_type = typename device_type::execution_space;
/// non const
using real_type_0d_view_type = Tines::value_type_0d_view<real_type,device_type>;
using real_type_1d_view_type = Tines::value_type_1d_view<real_type,device_type>;
using real_type_2d_view_type = Tines::value_type_2d_view<real_type,device_type>;
using real_type_3d_view_type = Tines::value_type_3d_view<real_type,device_type>;
using ordinal_type_1d_view = Tines::value_type_1d_view<ordinal_type,device_type>;
using ordinal_type_2d_view = Tines::value_type_2d_view<ordinal_type,device_type>;
using string_type_1d_view_type = Tines::value_type_1d_view<char [LENGTHOFSPECNAME + 1],device_type>;
//// const views
using kmcd_ordinal_type_1d_view = ConstUnmanaged<ordinal_type_1d_view>;
using kmcd_ordinal_type_2d_view = ConstUnmanaged<ordinal_type_2d_view>;
using kmcd_real_type_1d_view = ConstUnmanaged<real_type_1d_view_type>;
using kmcd_real_type_2d_view = ConstUnmanaged<real_type_2d_view_type>;
using kmcd_real_type_3d_view = ConstUnmanaged<real_type_3d_view_type>;
using kmcd_string_type_1d_view =ConstUnmanaged<string_type_1d_view_type>;
real_type rho;
kmcd_string_type_1d_view speciesNames;
// ordinal_type nNASAinter;
// ordinal_type nCpCoef;
// ordinal_type nArhPar;
// ordinal_type nLtPar;
// ordinal_type nJanPar;
// ordinal_type nFit1Par;
// ordinal_type nIonSpec;
// ordinal_type electrIndx;
// ordinal_type nIonEspec;
ordinal_type nElem; // this include all elements from chem.inp
ordinal_type
NumberofElementsGas; // this only include elements present in gas species
ordinal_type nSpec;
ordinal_type nReac;
// ordinal_type nNASA9coef;
ordinal_type nThbReac;
// ordinal_type maxTbInReac;
ordinal_type nFallReac;
ordinal_type nFallPar;
// ordinal_type maxSpecInReac;
ordinal_type maxOrdPar;
ordinal_type nRealNuReac;
ordinal_type nRevReac;
ordinal_type nOrdReac;
ordinal_type nPlogReac;
ordinal_type jacDim;
bool enableRealReacScoef;
real_type Runiv;
real_type Rcal;
real_type Rcgs;
real_type TthrmMin;
real_type TthrmMax;
// kmcd_string_type_1d_view<LENGTHOFSPECNAME+1> sNames ;
// kmcd_ordinal_type_1d_view spec9t;
// kmcd_ordinal_type_1d_view spec9nrng;
// kmcd_ordinal_type_1d_view sigNu;
kmcd_ordinal_type_1d_view reacTbdy;
kmcd_ordinal_type_1d_view reacTbno;
// kmcd_ordinal_type_1d_view reac_to_Tbdy_index;
kmcd_ordinal_type_1d_view reacPfal;
kmcd_ordinal_type_1d_view reacPtype;
kmcd_ordinal_type_1d_view reacPlohi;
kmcd_ordinal_type_1d_view reacPspec;
kmcd_ordinal_type_1d_view isRev;
// kmcd_ordinal_type_1d_view isDup;
kmcd_ordinal_type_1d_view reacAOrd;
// kmcd_ordinal_type_1d_view reacNrp;
kmcd_ordinal_type_1d_view reacNreac;
kmcd_ordinal_type_1d_view reacNprod;
kmcd_ordinal_type_1d_view reacScoef;
kmcd_ordinal_type_1d_view reacRnu;
kmcd_ordinal_type_1d_view reacRev;
kmcd_ordinal_type_1d_view reacHvIdx;
kmcd_ordinal_type_1d_view reacPlogIdx;
kmcd_ordinal_type_1d_view reacPlogPno;
// kmcd_ordinal_type_1d_view sNion;
// kmcd_ordinal_type_1d_view sCharge;
// kmcd_ordinal_type_1d_view sTfit;
// kmcd_ordinal_type_1d_view sPhase;
kmcd_real_type_2d_view NuIJ;
kmcd_ordinal_type_2d_view specTbdIdx;
kmcd_real_type_2d_view reacNuki;
kmcd_ordinal_type_2d_view reacSidx;
kmcd_ordinal_type_2d_view specAOidx;
// kmcd_ordinal_type_2d_view elemCount;
kmcd_real_type_1d_view sMass;
// kmcd_real_type_1d_view Tlo;
kmcd_real_type_1d_view Tmi;
// kmcd_real_type_1d_view Thi;
// kmcd_real_type_1d_view sigRealNu;
// kmcd_real_type_1d_view reacHvPar;
kmcd_real_type_1d_view kc_coeff;
// kmcd_real_type_1d_view eMass;
kmcd_real_type_2d_view RealNuIJ;
kmcd_real_type_2d_view reacArhenFor;
kmcd_real_type_2d_view reacArhenRev;
kmcd_real_type_2d_view specTbdEff;
kmcd_real_type_2d_view reacPpar;
kmcd_real_type_2d_view reacRealNuki;
kmcd_real_type_2d_view specAOval;
kmcd_real_type_2d_view reacPlogPars;
kmcd_real_type_3d_view cppol;
kmcd_real_type_2d_view stoiCoefMatrix;
// kmcd_real_type_3d_view spec9trng;
// kmcd_real_type_3d_view spec9coefs;
};
template<typename DT>
KineticModelGasConstData<DT> createGasKineticModelConstData(const KineticModelData & kmd) {
KineticModelGasConstData<DT> data;
// using DT = typename DeviceType::execution_space;
/// given from non-const kinetic model data
data.rho = real_type(-1); /// there is no minus density if this is minus, rhoset = 0
data.speciesNames = kmd.sNames_.template view<DT>();
// data.nNASAinter = kmd.nNASAinter_;
// data.nCpCoef = kmd.nCpCoef_;
// data.nArhPar = kmd.nArhPar_;
// data.nLtPar = kmd.nLtPar_;
// data.nJanPar = kmd.nJanPar_;
// data.nFit1Par = kmd.nFit1Par_;
// data.nIonSpec = kmd.nIonSpec_;
// data.electrIndx = kmd.electrIndx_;
// data.nIonEspec = kmd.nIonEspec_;
data.nElem = kmd.nElem_; // includes all elements from chem.inp
data.NumberofElementsGas = kmd.NumberofElementsGas_; // only includes elments present in gas phase
data.nSpec = kmd.nSpec_;
data.nReac = kmd.nReac_;
// data.nNASA9coef = kmd.nNASA9coef_;
data.nThbReac = kmd.nThbReac_;
// data.maxTbInReac = kmd.maxTbInReac_;
data.nFallReac = kmd.nFallReac_;
data.nFallPar = kmd.nFallPar_;
// data.maxSpecInReac = kmd.maxSpecInReac_;
data.maxOrdPar = kmd.maxOrdPar_;
data.nRealNuReac = kmd.nRealNuReac_;
data.nRevReac = kmd.nRevReac_;
data.nOrdReac = kmd.nOrdReac_;
data.nPlogReac = kmd.nPlogReac_;
data.jacDim = kmd.nSpec_ + 3; /// rho, temperature and pressure
data.enableRealReacScoef = true;
{
const auto tmp = kmd.reacScoef_.template view<host_exec_space>();
for (ordinal_type i = 0; i < kmd.nReac_; ++i) {
const bool flag = (tmp(i) != -1);
data.enableRealReacScoef &= flag;
}
}
data.Runiv = kmd.Runiv_;
data.Rcal = kmd.Rcal_;
data.Rcgs = kmd.Rcgs_;
data.TthrmMin = kmd.TthrmMin_;
data.TthrmMax = kmd.TthrmMax_;
// data.spec9t = kmd.spec9t_.template view<DT>();
// data.spec9nrng = kmd.spec9nrng_.template view<DT>();
// data.sigNu = kmd.sigNu_.template view<DT>();
data.reacTbdy = kmd.reacTbdy_.template view<DT>();
data.reacTbno = kmd.reacTbno_.template view<DT>();
// data.reac_to_Tbdy_index = kmd.reac_to_Tbdy_index_.template view<DT>();
data.reacPfal = kmd.reacPfal_.template view<DT>();
data.reacPtype = kmd.reacPtype_.template view<DT>();
data.reacPlohi = kmd.reacPlohi_.template view<DT>();
data.reacPspec = kmd.reacPspec_.template view<DT>();
data.isRev = kmd.isRev_.template view<DT>();
// data.isDup = kmd.isDup_.template view<DT>();
data.reacAOrd = kmd.reacAOrd_.template view<DT>();
// data.reacNrp = kmd.reacNrp_.template view<DT>();
data.reacNreac = kmd.reacNreac_.template view<DT>();
data.reacNprod = kmd.reacNprod_.template view<DT>();
data.reacScoef = kmd.reacScoef_.template view<DT>();
data.reacRnu = kmd.reacRnu_.template view<DT>();
data.reacRev = kmd.reacRev_.template view<DT>();
data.reacHvIdx = kmd.reacHvIdx_.template view<DT>();
data.reacPlogIdx = kmd.reacPlogIdx_.template view<DT>();
data.reacPlogPno = kmd.reacPlogPno_.template view<DT>();
// data.sNion = kmd.sNion_.template view<DT>();
// data.sCharge = kmd.sCharge_.template view<DT>();
// data.sTfit = kmd.sTfit_.template view<DT>();
// data.sPhase = kmd.sPhase_.template view<DT>();
data.NuIJ = kmd.NuIJ_.template view<DT>();
data.specTbdIdx = kmd.specTbdIdx_.template view<DT>();
data.reacNuki = kmd.reacNuki_.template view<DT>();
data.reacSidx = kmd.reacSidx_.template view<DT>();
data.specAOidx = kmd.specAOidx_.template view<DT>();
// data.elemCount = kmd.elemCount_.template view<DT>(); // (nSpec_, nElem_)
data.sMass = kmd.sMass_.template view<DT>();
// data.Tlo = kmd.Tlo_.template view<DT>();
data.Tmi = kmd.Tmi_.template view<DT>();
// data.Thi = kmd.Thi_.template view<DT>();
// data.sigRealNu = kmd.sigRealNu_.template view<DT>();
// data.reacHvPar = kmd.reacHvPar_.template view<DT>();
data.kc_coeff = kmd.kc_coeff_.template view<DT>();
// data.eMass = kmd.eMass_.template view<DT>();
data.RealNuIJ = kmd.RealNuIJ_.template view<DT>();
data.reacArhenFor = kmd.reacArhenFor_.template view<DT>();
data.reacArhenRev = kmd.reacArhenRev_.template view<DT>();
data.specTbdEff = kmd.specTbdEff_.template view<DT>();
data.reacPpar = kmd.reacPpar_.template view<DT>();
data.reacRealNuki = kmd.reacRealNuki_.template view<DT>();
data.specAOval = kmd.specAOval_.template view<DT>();
data.reacPlogPars = kmd.reacPlogPars_.template view<DT>();
data.cppol = kmd.cppol_.template view<DT>();
// data.spec9trng = kmd.spec9trng_.template view<DT>();
// data.spec9coefs = kmd.spec9coefs_.template view<DT>();
// data.sNames = kmd.sNames_.template view<DT>();
data.stoiCoefMatrix = kmd.stoiCoefMatrix_.template view<DT>();
return data;
}
template<typename DT>
static inline
Kokkos::View<KineticModelGasConstData<DT>*,DT>
createGasKineticModelConstData(const kmd_type_1d_view_host kmds) {
Kokkos::View<KineticModelGasConstData<DT>*,DT>
r_val(do_not_init_tag("KMCD::gas phase const data objects"),
kmds.extent(0));
auto r_val_host = Kokkos::create_mirror_view(r_val);
Kokkos::parallel_for
(Kokkos::RangePolicy<host_exec_space>(0, kmds.extent(0)),
KOKKOS_LAMBDA(const int i) {
r_val_host(i) = createGasKineticModelConstData<DT>(kmds(i));
});
Kokkos::deep_copy(r_val, r_val_host);
return r_val;
}
/// KK: once code is working, it will be deprecated
template<typename DT>
using KineticModelConstData = KineticModelGasConstData<DT>;
} // namespace TChem
#endif
| 38.780069
| 104
| 0.718121
|
sandialabs
|
f2dddfbc6249d58b917232fc7819daa05d380ca0
| 1,276
|
hpp
|
C++
|
include/tdc/util/lcp.hpp
|
herlez/tdc
|
3b85ae183c21410e65f1e739736287df46c38d1d
|
[
"MIT"
] | 1
|
2021-05-06T13:39:22.000Z
|
2021-05-06T13:39:22.000Z
|
include/tdc/util/lcp.hpp
|
herlez/tdc
|
3b85ae183c21410e65f1e739736287df46c38d1d
|
[
"MIT"
] | 1
|
2020-03-07T08:05:20.000Z
|
2020-03-07T08:05:20.000Z
|
include/tdc/util/lcp.hpp
|
herlez/tdc
|
3b85ae183c21410e65f1e739736287df46c38d1d
|
[
"MIT"
] | 2
|
2020-05-27T07:54:43.000Z
|
2021-11-18T13:29:14.000Z
|
#pragma once
namespace tdc {
/// \brief Computes the LCP array from the suffix array using Kasai's algorithm.
/// \tparam char_t the character type
/// \tparam idx_t the suffix/LCP array entry type
/// \param text the input text, assuming to be zero-terminated
/// \param n the length of the input text including the zero-terminator
/// \param sa the suffix array for the text
/// \param lcp the output LCP array
/// \param plcp an array of size n used as working space -- contains the permuted LCP array after the operation
template<typename char_t, typename idx_t>
static void lcp_kasai(const char_t* text, const size_t n, const idx_t* sa, idx_t* lcp, idx_t* plcp) {
// compute phi array
{
for(size_t i = 1, prev = sa[0]; i < n; i++) {
plcp[sa[i]] = prev;
prev = sa[i];
}
plcp[sa[0]] = sa[n-1];
}
// compute PLCP array
{
for(size_t i = 0, l = 0; i < n - 1; ++i) {
const auto phi_i = plcp[i];
while(text[i + l] == text[phi_i + l]) ++l;
plcp[i] = l;
if(l) --l;
}
}
// compute LCP array
{
lcp[0] = 0;
for(size_t i = 1; i < n; i++) {
lcp[i] = plcp[sa[i]];
}
}
}
} // namespace tdc
| 29
| 111
| 0.554859
|
herlez
|
f2de2cd3f4565129763b927dfd000cad5c946085
| 58
|
hpp
|
C++
|
src/boost_mpl_aux__preprocessed_no_ctps_vector.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_mpl_aux__preprocessed_no_ctps_vector.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_mpl_aux__preprocessed_no_ctps_vector.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/mpl/aux_/preprocessed/no_ctps/vector.hpp>
| 29
| 57
| 0.810345
|
miathedev
|
f2deba7cbaf90053e5c47ad9cee572e1fc63afc3
| 18,693
|
cpp
|
C++
|
src/lua/state.cpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/lua/state.cpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/lua/state.cpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
#include "lcv.hpp"
#include "lvalue.hpp"
#include "../sdl/rw.hpp"
#include "../apppath.hpp"
#include "rewindtop.hpp"
#include "lubee/src/freelist.hpp"
extern "C" {
#include <lauxlib.h>
#include <lualib.h>
}
namespace rev {
// ----------------- LuaState::Exceptions -----------------
LuaState::EBase::EBase(const std::string& typ_msg, const std::string& msg):
std::runtime_error("")
{
std::stringstream ss;
ss << "Error in LuaState:\nCause: " << typ_msg << std::endl << msg;
reinterpret_cast<std::runtime_error&>(*this) = std::runtime_error(ss.str());
}
LuaState::ERun::ERun(const std::string& s):
EBase("Runtime", s)
{}
LuaState::ESyntax::ESyntax(const std::string& s):
EBase("Syntax", s)
{}
LuaState::EMem::EMem(const std::string& s):
EBase("Memory", s)
{}
LuaState::EError::EError(const std::string& s):
EBase("ErrorHandler", s)
{}
LuaState::EGC::EGC(const std::string& s):
EBase("GC", s)
{}
LuaState::EType::EType(lua_State* ls, const LuaType expect, const LuaType actual):
EBase(
"InvalidType",
std::string("[") + STypeName(ls, actual) +
"] to [" + STypeName(ls, expect) + "]"
),
expect(expect),
actual(actual)
{}
// ----------------- LuaState -----------------
const std::string LuaState::cs_fromCpp("FromCpp"),
LuaState::cs_fromLua("FromLua"),
LuaState::cs_mainThreadPtr("MainThreadPtr"),
LuaState::cs_mainThread("MainThread");
void LuaState::Nothing(lua_State* /*ls*/) {}
const LuaState::Deleter LuaState::s_deleter =
[](lua_State* ls){
// これが呼ばれる時はメインスレッドなどが全て削除された時なのでlua_closeを呼ぶ
lua_close(ls);
};
LuaState::Deleter LuaState::_MakeCoDeleter(LuaState* lsp) {
#ifdef DEBUG
return [lsp](lua_State* ls) {
D_Assert0(lsp->getLS() == ls);
#else
return [lsp](lua_State*) {
#endif
lsp->_unregisterCpp();
};
}
void LuaState::_initMainThread() {
const CheckTop ct(getLS());
// メインスレッドの登録 -> global[cs_mainThreadPtr]
push(static_cast<void*>(this));
setGlobal(cs_mainThreadPtr);
pushSelf();
setGlobal(cs_mainThread);
// fromCpp
newTable();
setGlobal(cs_fromCpp);
// fromLua
newTable();
// FromLuaの方は弱参照テーブルにする
newTable();
setField(-1, "__mode", "k");
// [fromLua][mode]
setMetatable(-2);
setGlobal(cs_fromLua);
}
void LuaState::_getThreadTable() {
getGlobal(cs_fromCpp);
getGlobal(cs_fromLua);
D_Assert0(type(-2)==LuaType::Table &&
type(-1)==LuaType::Table);
}
void LuaState::_registerLua() {
D_Assert0(!_bWrap);
const CheckTop ct(getLS());
getGlobal(cs_fromLua);
pushSelf();
getTable(-2);
if(type(-1) == LuaType::Nil) {
pop(1);
MakeUserdataWithDtor(*this, Lua_WP(shared_from_this()));
// [fromLua][Lua_SP]
pushSelf();
pushValue(-2);
// [fromLua][Lua_SP][Thread][Lua_SP]
setTable(-4);
pop(2);
} else {
// [fromLua][Lua_SP]
D_Assert0(type(-1) == LuaType::Userdata);
pop(2);
}
}
void LuaState::_registerCpp() {
D_Assert0(!_bWrap);
const RewindTop rt(getLS());
pushSelf();
getGlobal(cs_fromCpp);
// [Thread][fromCpp]
push(reinterpret_cast<void*>(this));
pushValue(rt.getBase()+1);
// [Thread][fromCpp][LuaState*][Thread]
D_Assert0(type(-1) == LuaType::Thread);
setTable(-3);
}
void LuaState::_unregisterCpp() {
D_Assert0(!_bWrap);
const RewindTop rt(getLS());
getGlobal(cs_fromCpp);
// [fromCpp]
push(reinterpret_cast<void*>(this));
push(LuaNil{});
// [fromCpp][LuaState*][Nil]
setTable(-3);
}
bool LuaState::isLibraryLoaded() {
getGlobal(luaNS::system::Package);
const bool res = type(-1) == LuaType::Table;
pop(1);
return res;
}
bool LuaState::isMainThread() const {
return !static_cast<bool>(_base);
}
void LuaState::addResourcePath(const std::string& path) {
loadLibraries();
const CheckTop ct(getLS());
// パッケージのロードパスにアプリケーションリソースパスを追加
getGlobal(luaNS::system::Package);
getField(-1, luaNS::system::Path);
push(";");
push(path);
// [package][path-str][;][path]
concat(3);
// [package][path-str(new)]
push(luaNS::system::Path);
pushValue(-2);
// [package][path-str(new)][path][path-str(new)]
setTable(-4);
pop(2);
}
LuaState::LuaState(const Lua_SP& spLua) {
_bWrap = false;
lua_State* ls = spLua->getLS();
const CheckTop ct(ls);
_base = spLua->getMainLS_SP();
_lua = ILua_SP(lua_newthread(ls), _MakeCoDeleter(this));
_registerCpp();
D_Assert0(getTop() == 0);
spLua->pop(1);
}
LuaState::LuaState(lua_State* ls, const bool bCheckTop):
_lua(ls, Nothing)
{
_bWrap = true;
if(bCheckTop)
_opCt = spi::construct(ls);
}
LuaState::LuaState(const lua_Alloc f, void* ud) {
_bWrap = false;
_lua = ILua_SP(f ? lua_newstate(f, ud) : luaL_newstate(), s_deleter);
const CheckTop ct(_lua.get());
_initMainThread();
}
LuaState::Reader::Reader(const HRW& hRW):
ops(hRW),
size(ops->size())
{}
Lua_SP LuaState::NewState(const lua_Alloc f, void* ud) {
Lua_SP ret(new LuaState(f, ud));
// スレッドリストにも加える
ret->_registerCpp();
ret->_registerLua();
return ret;
}
// --------------- LuaState::Reader ---------------
void LuaState::Reader::Read(lua_State* ls, const HRW& hRW, const char* chunkName, const char* mode) {
Reader reader(hRW);
const int res = lua_load(
ls,
&Reader::Proc,
&reader,
(chunkName ? chunkName : "(no name present)"),
mode
);
LuaState::CheckError(ls, res);
}
const char* LuaState::Reader::Proc(lua_State* /*ls*/, void* data, std::size_t* size) {
auto* self = reinterpret_cast<Reader*>(data);
auto remain = self->size;
if(remain > 0) {
constexpr decltype(remain) BLOCKSIZE = 2048,
MAX_BLOCK = 4;
int nb, blocksize;
if(remain <= BLOCKSIZE) {
nb = 1;
blocksize = *size = remain;
self->size = 0;
} else {
nb = std::min(MAX_BLOCK, remain / BLOCKSIZE);
blocksize = BLOCKSIZE;
*size = BLOCKSIZE * nb;
self->size -= *size;
}
self->buff.resize(*size);
self->ops->read(self->buff.data(), blocksize, nb);
return reinterpret_cast<const char*>(self->buff.data());
}
*size = 0;
return nullptr;
}
const char* LuaState::cs_defaultmode = "bt";
int LuaState::load(const HRW& hRW, const char* chunkName, const char* mode, const bool bExec) {
Reader::Read(getLS(), hRW, chunkName, mode);
if(bExec) {
// Loadされたチャンクを実行
return call(0, LUA_MULTRET);
}
return 0;
}
int LuaState::loadFromSource(const HRW& hRW, const char* chunkName, const bool bExec) {
return load(hRW, chunkName, "t", bExec);
}
int LuaState::loadFromBinary(const HRW& hRW, const char* chunkName, const bool bExec) {
return load(hRW, chunkName, "b", bExec);
}
int LuaState::loadModule(const std::string& name) {
std::string s("require(\"");
s.append(name);
s.append("\")");
HRW hRW = mgr_rw.fromConstTemporal(s.data(), s.length());
return loadFromSource(hRW, name.c_str(), true);
}
void LuaState::pushSelf() {
lua_pushthread(getLS());
}
void LuaState::loadLibraries() {
if(!isLibraryLoaded())
luaL_openlibs(getLS());
}
void LuaState::push(const LCValue& v) {
v.push(getLS());
}
void LuaState::pushCClosure(const lua_CFunction func, const int nvalue) {
lua_pushcclosure(getLS(), func, nvalue);
}
void LuaState::pushValue(const int idx) {
lua_pushvalue(getLS(), idx);
}
void LuaState::pop(const int n) {
lua_pop(getLS(), n);
}
namespace {
#ifdef DEBUG
bool IsRegistryIndex(const int idx) noexcept {
return idx==LUA_REGISTRYINDEX;
}
#endif
}
int LuaState::absIndex(int idx) const {
idx = lua_absindex(getLS(), idx);
D_Assert0(IsRegistryIndex(idx) || idx>=0);
return idx;
}
void LuaState::arith(const OP op) {
lua_arith(getLS(), static_cast<int>(op));
}
lua_CFunction LuaState::atPanic(const lua_CFunction panicf) {
return lua_atpanic(getLS(), panicf);
}
int LuaState::call(const int nargs, const int nresults) {
D_Scope(call)
const int top = getTop() - 1; // 1は関数の分
const int err = lua_pcall(getLS(), nargs, nresults, 0);
checkError(err);
return getTop() - top;
D_ScopeEnd()
}
int LuaState::callk(const int nargs, const int nresults, lua_KContext ctx, lua_KFunction k) {
D_Scope(callk)
const int top = getTop() - 1; // 1は関数の分
const int err = lua_pcallk(getLS(), nargs, nresults, 0, ctx, k);
checkError(err);
return getTop() - top;
D_ScopeEnd()
}
bool LuaState::checkStack(const int extra) {
return lua_checkstack(getLS(), extra) != 0;
}
bool LuaState::compare(const int idx0, const int idx1, CMP cmp) const {
return lua_compare(getLS(), idx0, idx1, static_cast<int>(cmp)) != 0;
}
void LuaState::concat(const int n) {
lua_concat(getLS(), n);
}
void LuaState::copy(const int from, const int to) {
lua_copy(getLS(), from, to);
}
void LuaState::dump(lua_Writer writer, void* data) {
lua_dump(getLS(), writer, data, 0);
}
void LuaState::error() {
lua_error(getLS());
}
int LuaState::gc(GC what, const int data) {
return lua_gc(getLS(), static_cast<int>(what), data);
}
lua_Alloc LuaState::getAllocf(void** ud) const {
return lua_getallocf(getLS(), ud);
}
void LuaState::getField(int idx, const LCValue& key) {
idx = absIndex(idx);
push(key);
getTable(idx);
}
void LuaState::getGlobal(const LCValue& key) {
pushGlobal();
push(key);
// [Global][key]
getTable(-2);
remove(-2);
}
const char* LuaState::getUpvalue(const int idx, const int n) {
return lua_getupvalue(getLS(), idx, n);
}
void LuaState::getTable(const int idx) {
lua_gettable(getLS(), idx);
}
int LuaState::getTop() const {
return lua_gettop(getLS());
}
void LuaState::getUserValue(const int idx) {
lua_getuservalue(getLS(), idx);
}
void LuaState::getMetatable(const int idx) {
lua_getmetatable(getLS(), idx);
}
void LuaState::insert(const int idx) {
lua_insert(getLS(), idx);
}
bool LuaState::isBoolean(const int idx) const {
return lua_isboolean(getLS(), idx) != 0;
}
bool LuaState::isCFunction(const int idx) const {
return lua_iscfunction(getLS(), idx) != 0;
}
bool LuaState::isLightUserdata(const int idx) const {
return lua_islightuserdata(getLS(), idx) != 0;
}
bool LuaState::isNil(const int idx) const {
return lua_isnil(getLS(), idx) != 0;
}
bool LuaState::isNone(const int idx) const {
return lua_isnone(getLS(), idx) != 0;
}
bool LuaState::isNoneOrNil(const int idx) const {
return lua_isnoneornil(getLS(), idx) != 0;
}
bool LuaState::isNumber(const int idx) const {
return lua_isnumber(getLS(), idx) != 0;
}
bool LuaState::isString(const int idx) const {
return lua_isstring(getLS(), idx) != 0;
}
bool LuaState::isTable(const int idx) const {
return lua_istable(getLS(), idx) != 0;
}
bool LuaState::isThread(const int idx) const {
return lua_isthread(getLS(), idx) != 0;
}
bool LuaState::isUserdata(const int idx) const {
return lua_isuserdata(getLS(), idx) != 0;
}
void LuaState::length(const int idx) {
lua_len(getLS(), idx);
}
int LuaState::getLength(const int idx) {
length(idx);
const int ret = toInteger(-1);
pop(1);
return ret;
}
void LuaState::newTable(const int narr, const int nrec) {
lua_createtable(getLS(), narr, nrec);
}
Lua_SP LuaState::newThread() {
return Lua_SP(new LuaState(shared_from_this()));
}
void* LuaState::newUserData(const std::size_t sz) {
return lua_newuserdata(getLS(), sz);
}
int LuaState::next(const int idx) {
return lua_next(getLS(), idx);
}
bool LuaState::rawEqual(const int idx0, const int idx1) {
return lua_rawequal(getLS(), idx0, idx1) != 0;
}
void LuaState::rawGet(const int idx) {
lua_rawget(getLS(), idx);
}
void LuaState::rawGetField(int idx, const LCValue& key) {
if(idx < 0)
idx = lua_absindex(getLS(), idx);
D_Assert0(idx >= 0);
push(key);
rawGet(idx);
}
std::size_t LuaState::rawLen(const int idx) const {
return lua_rawlen(getLS(), idx);
}
void LuaState::rawSet(const int idx) {
lua_rawset(getLS(), idx);
}
void LuaState::rawSetField(int idx, const LCValue& key, const LCValue& val) {
if(idx < 0)
idx = lua_absindex(getLS(), idx);
D_Assert0(idx >= 0);
push(key);
push(val);
rawSet(idx);
}
void LuaState::remove(const int idx) {
lua_remove(getLS(), idx);
}
void LuaState::replace(const int idx) {
lua_replace(getLS(), idx);
}
std::pair<bool,int> LuaState::resume(const Lua_SP& from, const int narg) {
lua_State *const ls = from ? from->getLS() : nullptr;
const int res = lua_resume(getLS(), ls, narg);
checkError(res);
return std::make_pair(res==LUA_YIELD, getTop());
}
void LuaState::setAllocf(lua_Alloc f, void* ud) {
lua_setallocf(getLS(), f, ud);
}
void LuaState::setField(int idx, const LCValue& key, const LCValue& val) {
idx = absIndex(idx);
push(key);
push(val);
setTable(idx);
}
void LuaState::setGlobal(const LCValue& key) {
pushGlobal();
push(key);
pushValue(-3);
// [value][Global][key][value]
setTable(-3);
pop(2);
}
void LuaState::setMetatable(const int idx) {
lua_setmetatable(getLS(), idx);
}
void LuaState::pushGlobal() {
pushValue(LUA_REGISTRYINDEX);
getField(-1, LUA_RIDX_GLOBALS);
// [Registry][Global]
remove(-2);
}
void LuaState::setTable(const int idx) {
lua_settable(getLS(), idx);
}
void LuaState::setTop(const int idx) {
lua_settop(getLS(), idx);
}
void LuaState::setUservalue(const int idx) {
lua_setuservalue(getLS(), idx);
}
const char* LuaState::setUpvalue(const int funcidx, const int n) {
return lua_setupvalue(getLS(), funcidx, n);
}
void* LuaState::upvalueId(const int funcidx, const int n) {
return lua_upvalueid(getLS(), funcidx, n);
}
void LuaState::upvalueJoin(const int funcidx0, const int n0, const int funcidx1, const int n1) {
lua_upvaluejoin(getLS(), funcidx0, n0, funcidx1, n1);
}
bool LuaState::status() const {
const int res = lua_status(getLS());
checkError(res);
return res != 0;
}
void LuaState::checkType(const int idx, const LuaType typ) const {
const LuaType t = type(idx);
if(t != typ)
throw EType(getLS(), typ, t);
}
void LuaState::CheckType(lua_State* ls, const int idx, const LuaType typ) {
LuaState lsc(ls, true);
lsc.checkType(idx, typ);
}
bool LuaState::toBoolean(const int idx) const {
return LCV<bool>()(idx, getLS(), nullptr);
}
lua_CFunction LuaState::toCFunction(const int idx) const {
return LCV<lua_CFunction>()(idx, getLS(), nullptr);
}
lua_Integer LuaState::toInteger(const int idx) const {
return LCV<lua_Integer>()(idx, getLS(), nullptr);
}
std::string LuaState::toString(const int idx) const {
return LCV<std::string>()(idx, getLS(), nullptr);
}
std::string LuaState::cnvString(int idx) {
idx = absIndex(idx);
getGlobal(luaNS::ToString);
pushValue(idx);
call(1,1);
std::string ret = toString(-1);
pop(1);
return ret;
}
lua_Number LuaState::toNumber(const int idx) const {
return LCV<lua_Number>()(idx, getLS(), nullptr);
}
const void* LuaState::toPointer(const int idx) const {
return lua_topointer(getLS(), idx);
}
Lua_SP LuaState::toThread(const int idx) const {
return LCV<Lua_SP>()(idx, getLS(), nullptr);
}
void* LuaState::toUserData(const int idx) const {
return LCV<void*>()(idx, getLS(), nullptr);
}
LCTable_SP LuaState::toTable(const int idx, LPointerSP* spm) const {
return LCV<LCTable_SP>()(idx, getLS(), spm);
}
LCValue LuaState::toLCValue(const int idx, LPointerSP* spm) const {
return LCV<LCValue>()(idx, getLS(), spm);
}
LuaType LuaState::type(const int idx) const {
return SType(getLS(), idx);
}
LuaType LuaState::SType(lua_State* ls, const int idx) {
const int typ = lua_type(ls, idx);
return static_cast<LuaType::e>(typ);
}
const char* LuaState::typeName(const LuaType typ) const {
return STypeName(getLS(), typ);
}
const char* LuaState::STypeName(lua_State* ls, const LuaType typ) {
return lua_typename(ls,
static_cast<int>(typ));
}
const lua_Number* LuaState::version() const {
return lua_version(getLS());
}
void LuaState::xmove(const Lua_SP& to, const int n) {
lua_xmove(getLS(), to->getLS(), n);
}
int LuaState::yield(const int nresults) {
return lua_yield(getLS(), nresults);
}
int LuaState::yieldk(const int nresults, lua_KContext ctx, lua_KFunction k) {
return lua_yieldk(getLS(), nresults, ctx, k);
}
bool LuaState::prepareTable(const int idx, const LCValue& key) {
getField(idx, key);
if(type(-1) != LuaType::Table) {
// テーブルを作成
pop(1);
newTable();
push(key);
pushValue(-2);
// [Target][NewTable][key][NewTable]
setTable(-4);
return true;
}
return false;
}
bool LuaState::prepareTableGlobal(const LCValue& key) {
pushGlobal();
const bool b = prepareTable(-1, key);
remove(-2);
return b;
}
bool LuaState::prepareTableRegistry(const LCValue& key) {
pushValue(LUA_REGISTRYINDEX);
const bool b = prepareTable(-1, key);
remove(-2);
return b;
}
lua_State* LuaState::getLS() const {
return _lua.get();
}
Lua_SP LuaState::GetLS_SP(lua_State* ls) {
Lua_SP ret;
const RewindTop rt(ls);
LuaState lsc(ls, false);
lsc.getGlobal(cs_fromLua);
lsc.pushSelf();
lsc.getTable(-2);
if(lsc.type(-1) == LuaType::Userdata) {
// [fromLua][LuaState*]
return reinterpret_cast<Lua_WP*>(lsc.toUserData(-1))->lock();
}
lsc.pop(2);
// Cppでのみ生きているスレッド
lsc.getGlobal(cs_fromCpp);
const int idx = lsc.getTop();
// [fromCpp]
lsc.push(LuaNil{});
while(lsc.next(idx) != 0) {
// key=-2 value=-1
D_Assert0(lsc.type(-1) == LuaType::Thread);
if(lua_tothread(ls, -1) == ls)
return reinterpret_cast<LuaState*>(lsc.toUserData(-2))->shared_from_this();
lsc.pop(1);
}
return Lua_SP();
}
Lua_SP LuaState::getLS_SP() {
return shared_from_this();
}
Lua_SP LuaState::getMainLS_SP() {
if(_base)
return _base->getMainLS_SP();
return shared_from_this();
}
Lua_SP LuaState::GetMainLS_SP(lua_State* ls) {
const RewindTop rt(ls);
lua_getglobal(ls, cs_mainThreadPtr.c_str());
void* ptr = lua_touserdata(ls, -1);
return reinterpret_cast<LuaState*>(ptr)->shared_from_this();
}
void LuaState::checkError(const int code) const {
CheckError(getLS(), code);
}
void LuaState::CheckError(lua_State* ls, const int code) {
const CheckTop ct(ls);
if(code!=LUA_OK && code!=LUA_YIELD) {
const char* msg = LCV<const char*>()(-1, ls, nullptr);
switch(code) {
case LUA_ERRRUN:
throw ERun(msg);
case LUA_ERRMEM:
throw EMem(msg);
case LUA_ERRERR:
throw EError(msg);
case LUA_ERRSYNTAX:
throw ESyntax(msg);
case LUA_ERRGCMM:
throw EGC(msg);
}
throw EBase("unknown error-code", msg);
}
}
std::ostream& operator << (std::ostream& os, const LuaState& ls) {
// スタックの値を表示する
const int n = ls.getTop();
for(int i=1 ; i<=n ; i++)
os << "[" << i << "]: " << ls.toLCValue(i) << " (" << ls.type(i).toStr() << ")" << std::endl;
return os;
}
}
| 27.530191
| 102
| 0.658375
|
degarashi
|
f2e7dfd0dc05993a7fe9ccf12d63dcea44e78dc0
| 412
|
cc
|
C++
|
src/code_complete_cache.cc
|
Gei0r/cquery
|
6ff8273e8b8624016f9363f444acfee30c4bbf64
|
[
"MIT"
] | null | null | null |
src/code_complete_cache.cc
|
Gei0r/cquery
|
6ff8273e8b8624016f9363f444acfee30c4bbf64
|
[
"MIT"
] | null | null | null |
src/code_complete_cache.cc
|
Gei0r/cquery
|
6ff8273e8b8624016f9363f444acfee30c4bbf64
|
[
"MIT"
] | null | null | null |
#include "code_complete_cache.h"
void CodeCompleteCache::WithLock(std::function<void()> action) {
std::lock_guard<std::mutex> lock(mutex_);
action();
}
bool CodeCompleteCache::IsCacheValid(lsTextDocumentPositionParams position) {
std::lock_guard<std::mutex> lock(mutex_);
return cached_path_ == position.textDocument.uri.GetAbsolutePath() &&
cached_completion_position_ == position.position;
}
| 34.333333
| 77
| 0.759709
|
Gei0r
|
f2e9881742fc1b942ac3a60416ebf51b41d9dfbe
| 829
|
cpp
|
C++
|
Olamundo/freq_0502/main.cpp
|
tosantos1/LIP
|
7dbc045afa02729f4e2f2f1d3b29baebf5be72ad
|
[
"MIT"
] | null | null | null |
Olamundo/freq_0502/main.cpp
|
tosantos1/LIP
|
7dbc045afa02729f4e2f2f1d3b29baebf5be72ad
|
[
"MIT"
] | null | null | null |
Olamundo/freq_0502/main.cpp
|
tosantos1/LIP
|
7dbc045afa02729f4e2f2f1d3b29baebf5be72ad
|
[
"MIT"
] | null | null | null |
#include <iostream>
/*Ordenação por referência
Complete o programa dado para que com apenas uma chamada
para o procedimento ordenarTres, os valores das variáveis a, b e c sejam colocados em ordem crescente.
Note que nenhuma alteração da função main nem do procedimento ordenarTres é necessária.*/
using namespace std;
int oQueEuFaco (int x, int y );
void oQueEuFaco(int &x, int &y);
void ordenarTres(int &x, int &y, int &z);
int main()
{
int a, b, c;
cin >> a >> b >> c;
ordenarTres(a, b, c);
cout << a << " " << b << " " << c << endl;
return 0;
}
//Este procedimento arranja os valores de x, y e z em ordem crescente
void ordenarTres(int &x, int &y, int &z)
{
oQueEuFaco(x, y);
oQueEuFaco(x, z);
oQueEuFaco(y, z);
}
int oQueEuFaco (int x, int y){
int a;
if ( x>y){
a=x;
x=y;
y=a;
}
}
| 18.840909
| 102
| 0.640531
|
tosantos1
|
f2e9b05f3c16a26d7f319ac7e9a8750d8943d941
| 8,390
|
cpp
|
C++
|
Testbeds/GTests/twEventTest.cpp
|
microqq/TwinkleGraphics
|
e3975dc6dad5b6b8d5db1d54e30e815072db162e
|
[
"MIT"
] | null | null | null |
Testbeds/GTests/twEventTest.cpp
|
microqq/TwinkleGraphics
|
e3975dc6dad5b6b8d5db1d54e30e815072db162e
|
[
"MIT"
] | 1
|
2020-07-03T03:13:39.000Z
|
2020-07-03T03:13:39.000Z
|
Testbeds/GTests/twEventTest.cpp
|
microqq/TwinkleGraphics
|
e3975dc6dad5b6b8d5db1d54e30e815072db162e
|
[
"MIT"
] | null | null | null |
#include <functional>
#include <string>
#include <gtest/gtest.h>
#include "twEventHandler.h"
#include "twEventManager.h"
#include "twConsoleLog.h"
using namespace TwinkleGraphics;
class SampleListener
{
public:
SampleListener(){}
~SampleListener(){}
void OnBaseEvent(Object::Ptr sender, BaseEventArgs::Ptr e) const
{
Console::LogGTestInfo("Add SampleListener OnBaseEvent EventHandler.\n");
}
};
DefMemFuncType(SampleListener);
class SampleEventArgs : public BaseEventArgs
{
public:
typedef std::shared_ptr<SampleEventArgs> Ptr;
static EventId ID;
SampleEventArgs()
: BaseEventArgs()
{
}
virtual ~SampleEventArgs() {}
virtual EventId GetEventId() override
{
return SampleEventArgs::ID;
}
};
EventId SampleEventArgs::ID = std::hash<std::string>{}("SampleEventArgs");
class SampleEventArgsA : public BaseEventArgs
{
public:
typedef std::shared_ptr<SampleEventArgsA> Ptr;
static EventId ID;
SampleEventArgsA()
: BaseEventArgs()
{
}
virtual ~SampleEventArgsA() {}
virtual EventId GetEventId() override
{
return SampleEventArgsA::ID;
}
};
EventId SampleEventArgsA::ID = std::hash<std::string>{}("SampleEventArgsA");
// en.cppreference.com/w/cpp/utility/functional/function/target.html
void f(Object::Ptr, BaseEventArgs::Ptr)
{
Console::LogGTestInfo("Initialise Global f(******) EventHandler.\n");
}
void g(Object::Ptr, BaseEventArgs::Ptr) { }
void test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)> arg)
{
typedef void (*FPTR)(Object::Ptr, BaseEventArgs::Ptr);
// void (*const* ptr)(Object::Ptr, BaseEventArgs::Ptr) =
// arg.target<void(*)(Object::Ptr, BaseEventArgs::Ptr)>();
FPTR* ptr= arg.target<FPTR>();
if (ptr && *ptr == f)
{
Console::LogGTestInfo("it is the function f\n");
}
else if (ptr && *ptr == g)
{
Console::LogGTestInfo("it is the function g\n");
}
else if(ptr)
{
Console::LogGTestInfo("it is not nullptr\n");
}
}
// en.cppreference.com/w/cpp/utility/functional/function.html
struct Foo {
Foo(int num) : num_(num) {}
void print_add(int i) const { Console::LogGTestInfo("Foo: ", num_+i, '\n'); }
int num_;
};
TEST(EventTests, AddEventHandler)
{
//EventHandler(const HandlerFunc& func)
EventHandler handler(
EventHandler::HandlerFunc(
[](Object::Ptr sender, BaseEventArgs::Ptr args) {
Console::LogGTestInfo("Initialise EventHandler.\n");
}
)
);
//Lambda handler function
EventHandler::HandlerFuncPointer lambda =
[](Object::Ptr sender, BaseEventArgs::Ptr args) {
Console::LogGTestInfo("Add Lambda Num(1) EventHandler.\n");
};
EventHandler::HandlerFunc lambdaFunc(lambda);
//EventHandler::operator+=
handler += lambdaFunc;
ASSERT_EQ(handler[1] != nullptr, true);
//EventHandler::operator-=
handler -= lambdaFunc;
ASSERT_EQ(handler.GetHandlerFuncSize(), 1);
// We won't use std::bind binding class member function
SampleListener listener;
// EventHandler::HandlerFunc baseFunc =
// std::bind(&SampleListener::OnBaseEvent, &listener, std::placeholders::_1, std::placeholders::_2);
// handlerRef += baseFunc;
Object::Ptr objectPtr = std::make_shared<Object>();
SampleEventArgs::Ptr sampleEvent1 = std::make_shared<SampleEventArgs>();
SampleEventArgs::Ptr sampleEvent2 = std::make_shared<SampleEventArgs>();
SampleEventArgsA::Ptr sampleEventA = std::make_shared<SampleEventArgsA>();
ASSERT_EQ(sampleEvent1->GetEventId() != -1, true);
ASSERT_EQ(sampleEvent2->GetEventId() != -1, true);
ASSERT_EQ(sampleEventA->GetEventId() != -1, true);
ASSERT_EQ(sampleEventA->GetEventId() != sampleEvent1->GetEventId(), true);
ASSERT_EQ(sampleEvent2->GetEventId() != sampleEvent1->GetEventId(), false);
Console::LogGTestInfo("SampleEvent Instance 1 EventId: ", sampleEvent1->GetEventId(), "\n");
Console::LogGTestInfo("SampleEvent Instance 2 EventId: ", sampleEvent2->GetEventId(), "\n");
Console::LogGTestInfo("SampleEventA EventId: ", sampleEventA->GetEventId(), "\n");
handler.Invoke(objectPtr, sampleEvent1);
};
TEST(EventTests, FireEvent)
{
EventManagerInst eventMgrInst;
SampleEventArgsA::Ptr sampleEventA = std::make_shared<SampleEventArgsA>();
//EventHandler(const HandlerFunc& func)
EventHandler handler(
EventHandler::HandlerFunc(
[](Object::Ptr sender, BaseEventArgs::Ptr args) {
Console::LogGTestInfo("Initialise EventHandler.\n");
}
)
);
//Lambda handler function
EventHandler::HandlerFuncPointer lambda =
[](Object::Ptr sender, BaseEventArgs::Ptr args) {
Console::LogGTestInfo("Add Lambda Num(1) EventHandler.\n");
};
Console::LogGTestInfo("Lambda function address: ", size_t(lambda), "\n");
EventHandler::HandlerFunc lambdaFunc(lambda);
//EventHandler::operator+=
handler += lambdaFunc;
ASSERT_EQ(handler[1] != nullptr, true);
handler += lambdaFunc;
ASSERT_EQ(handler.GetHandlerFuncSize(), 2);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
Console::LogGTestInfo("Fire SampleEventArgsA--------1\n");
eventMgrInst->FireImmediately(nullptr, sampleEventA);
//EventHandler::operator-=
handler -= lambdaFunc;
ASSERT_EQ(handler.GetHandlerFuncSize(), 1);
// handler updated, so first unsubscribe and then subscribe again
eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
Console::LogGTestInfo("Fire SampleEventArgsA--------2\n");
eventMgrInst->FireImmediately(nullptr, sampleEventA);
handler.Remove(0);
handler += lambdaFunc;
ASSERT_EQ(handler.GetHandlerFuncSize(), 1);
eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler);
eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler);
eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
Console::LogGTestInfo("Fire SampleEventArgsA--------3\n");
eventMgrInst->FireImmediately(nullptr, sampleEventA);
//Bind class member function
// SampleListener listener;
// EventHandler::HandlerFunc sampleListenerHFunc = std::bind(&SampleListener::OnBaseEvent, &listener, std::placeholders::_1, std::placeholders::_2);
EventHandler::HandlerFuncPointer lambda2 =
[](Object::Ptr sender, BaseEventArgs::Ptr args){
SampleListener* listener = dynamic_cast<SampleListener*>(sender.get());
listener->OnBaseEvent(sender, args);
};
EventHandler::HandlerFunc lambda2Func(lambda2);
handler += lambda2Func;
handler += lambda2Func;
handler += lambda2Func;
handler -= lambda2Func;
EventHandlerCallBack(lambda3, SampleListener, OnBaseEvent);
RegisterEventHandlerCallBack(handler, lambda3);
UnRegisterEventHandlerCallBack(handler, lambda3);
RegisterEventHandlerCallBack(handler, lambda3);
EventHandler::HandlerFunc lambda3Func(f);
handler += lambda3Func;
handler += lambda3Func;
handler += lambda3Func;
eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
Console::LogGTestInfo("Fire SampleEventArgsA--------4\n");
eventMgrInst->FireImmediately(nullptr, sampleEventA);
// en.cppreference.com/w/cpp/utility/functional/function.html
// std::function<void(const SampleListener&, Object::Ptr, BaseEventArgs::Ptr)> fffFunc = &SampleListener::OnBaseEvent;
std::function<void(const Foo&, int)> f_add_display = &Foo::print_add;
const Foo foo(314159);
f_add_display(foo, 1);
f_add_display(314159, 1);
// en.cppreference.com/w/cpp/utility/functional/function/target.html
test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)>(f));
test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)>(g));
test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)>(lambda3));
}
| 33.031496
| 152
| 0.682956
|
microqq
|
f2edbea3f6ac2b4c696a67227a8cf853d76b3482
| 4,716
|
cpp
|
C++
|
src/vi/vi_db.cpp
|
liulixinkerry/ripple
|
330522a61bcf1cf290c100ce4686ed62dcdc5cab
|
[
"Unlicense"
] | 7
|
2021-01-25T04:28:38.000Z
|
2021-11-20T04:14:14.000Z
|
src/vi/vi_db.cpp
|
Xingquan-Li/ripple
|
330522a61bcf1cf290c100ce4686ed62dcdc5cab
|
[
"Unlicense"
] | 3
|
2021-02-25T08:13:41.000Z
|
2022-02-25T16:37:16.000Z
|
src/vi/vi_db.cpp
|
Xingquan-Li/ripple
|
330522a61bcf1cf290c100ce4686ed62dcdc5cab
|
[
"Unlicense"
] | 8
|
2021-02-27T13:52:25.000Z
|
2021-11-15T08:01:02.000Z
|
#include "../db/db.h"
using namespace db;
#include "vi.h"
using namespace vi;
#include "../ut/utils.h"
void Geometry::draw(Visualizer* v, const Layer& L) const {
if ((L.rIndex >= 0 || L.cIndex >= 0) && layer != L) {
return;
}
if (layer.rIndex >= 0) {
v->setFillColor(v->scheme.metalFill[layer.rIndex]);
v->setLineColor(v->scheme.metalLine[layer.rIndex]);
} else if (layer.cIndex >= 0) {
v->setFillColor(v->scheme.metalFill[layer.cIndex]);
v->setLineColor(v->scheme.metalLine[layer.cIndex]);
}
const int lx = globalX();
const int ly = globalY();
const int hx = globalX() + boundR();
const int hy = globalY() + boundT();
v->drawRect(lx, ly, hx, hy, true, true);
}
void Cell::draw(Visualizer* v) const {
if (!(region->id)) {
v->setFillColor(v->scheme.instanceFill);
v->setLineColor(v->scheme.instanceLine);
} else {
int r = (region->id * 100) % 256;
int g = (region->id * 200) % 256;
v->setFillColor(Color(r, g, 255));
v->setLineColor(Color(r / 2, g / 2, 128));
}
int lx = globalX();
int ly = globalY();
int hx = globalX() + boundR();
int hy = globalY() + boundT();
// printlog(LOG_INFO, "cell : %d %d %d %d", lx, ly, hx, hy);
v->drawRect(lx, ly, hx, hy, true, true);
}
void IOPin::draw(Visualizer* v, Layer& L) const { type->shapes[0].draw(v, L); }
void Pin::draw(Visualizer* v, const Layer& L) const {
for (const Geometry& shape : type->shapes) {
shape.draw(v, L);
}
}
void Net::draw(Visualizer* v, const Layer& L) const {
for (const Pin* pin : pins) {
pin->draw(v, L);
}
}
void SNet::draw(Visualizer* v, Layer& L) const {
for (const Geometry& shape : shapes) {
shape.draw(v, L);
}
for (const Via& via : vias) {
via.draw(v, L);
}
}
void Row::draw(Visualizer* v) const {
v->setFillColor(v->scheme.rowFill);
v->setLineColor(v->scheme.rowLine);
v->drawRect(_x, _y, _x + _xStep * _xNum, _y + _yStep * _yNum, true, true);
}
void Via::draw(Visualizer* v, Layer& L) const {
for (const Geometry& rect : type->rects) {
rect.draw(v);
}
}
void Region::draw(Visualizer* v) const {
int nRects = rects.size();
for (int i = 0; i < nRects; i++) {
v->setFillColor(v->scheme.regionFill);
v->setLineColor(Color(0, 0, 0));
v->drawRect(rects[i].lx, rects[i].ly, rects[i].hx, rects[i].hy, true, true);
}
}
void SiteMap::draw(Visualizer* v) const {
int lx, ly, hx, hy;
for (int x = 0; x < siteNX; x++) {
for (int y = 0; y < siteNY; y++) {
unsigned char regionID = getRegion(x, y);
bool blocked = getSiteMap(x, y, SiteMap::SiteBlocked);
if (blocked) {
v->setFillColor(Color(0, 0, 0));
getSiteBound(x, y, lx, ly, hx, hy);
v->drawRect(lx, ly, hx, hy, true, false);
} else if (regionID == Region::InvalidRegion) {
v->setFillColor(Color(255, 0, 0));
getSiteBound(x, y, lx, ly, hx, hy);
v->drawRect(lx, ly, hx, hy, true, false);
} else if (regionID > 0) {
v->setFillColor(v->scheme.regionFill);
getSiteBound(x, y, lx, ly, hx, hy);
v->drawRect(lx, ly, hx, hy, true, false);
}
}
}
}
void Database::draw(Visualizer* v) const {
v->reset(v->scheme.background);
int nRows = rows.size();
for (int i = 0; i < nRows; i++) {
rows[i]->draw(v);
}
int nCells = cells.size();
for (int i = 0; i < nCells; i++) {
cells[i]->draw(v);
}
/*
int nRegions = regions.size();
for(int i=1; i<nRegions; i++){
regions[i]->draw(v);
}
*/
// siteMap.draw(v);
/* draw metal objects */
unsigned nLayers = layers.size();
for (unsigned i = 0; i != nLayers; ++i) {
const Layer* layer = nullptr;
if (i % 2) {
layer = database.getCLayer(i / 2);
} else {
layer = database.getRLayer(i / 2);
}
if (!layer) {
continue;
}
// printlog(LOG_INFO, "draw layer %s", layer->name.c_str());
for (const Net* net : nets) {
net->draw(v, *layer);
}
}
/*
v->setFillColor(Color(255,0,0));
for(int x=0; x<grGrid.trackNX; x++){
for(int y=0; y<grGrid.trackNY; y++){
int dx = grGrid.trackL + x * grGrid.trackStepX;
int dy = grGrid.trackB + y * grGrid.trackStepY;
if(grGrid.getRGrid(x, y, 2) == (char)1){
v->drawPoint(dx, dy, 1);
}
}
}
*/
}
| 28.756098
| 84
| 0.516327
|
liulixinkerry
|
f2ef082ffdb2d2c0b7d783d0c5183936fe35c4aa
| 543
|
hpp
|
C++
|
OptionsState.hpp
|
nathiss/ticTacToe
|
e51866b66dda3fe92e82450a7732ad175eb1c96c
|
[
"MIT"
] | null | null | null |
OptionsState.hpp
|
nathiss/ticTacToe
|
e51866b66dda3fe92e82450a7732ad175eb1c96c
|
[
"MIT"
] | null | null | null |
OptionsState.hpp
|
nathiss/ticTacToe
|
e51866b66dda3fe92e82450a7732ad175eb1c96c
|
[
"MIT"
] | null | null | null |
#pragma once
#include <array>
#include <SFML/Graphics.hpp>
#include "State.hpp"
#include "SettingsBag.hpp"
#include "MapCell.hpp"
class OptionsState : public State {
public:
OptionsState(std::shared_ptr<sf::RenderWindow>);
~OptionsState();
static uint8_t player;
static uint8_t computer;
virtual void pollEvent() override;
virtual void update() override;
virtual void draw() override;
private:
std::array<sf::Text, 3> orderOption;
std::array<sf::Text, 3> characterOption;
uint8_t optionIdx;
};
| 20.884615
| 52
| 0.694291
|
nathiss
|
f2f3834523da7253561a9831549f255536882d88
| 4,689
|
inl
|
C++
|
include/quadtree.inl
|
MaxAlzner/libtree
|
80501e15fdec77e1f1824b46ebd3ae1c1cedd7f8
|
[
"MIT"
] | null | null | null |
include/quadtree.inl
|
MaxAlzner/libtree
|
80501e15fdec77e1f1824b46ebd3ae1c1cedd7f8
|
[
"MIT"
] | null | null | null |
include/quadtree.inl
|
MaxAlzner/libtree
|
80501e15fdec77e1f1824b46ebd3ae1c1cedd7f8
|
[
"MIT"
] | null | null | null |
#pragma once
template <typename T> inline bool quadnode_t<T>::empty() const
{
return this->_tree == 0 || this->_ring < 0 || this->_branch < 0;
}
template <typename T> inline size_t quadnode_t<T>::index() const
{
return tree_index(this->_ring, this->_branch, 4);
}
template <typename T> inline quaditerator_t<T> quaditerator_t<T>::child(const int32_t quadrant)
{
if (this->_node != 0)
{
switch (quadrant)
{
case 0:
return quaditerator_t<T>(this->_node->_q0);
case 1:
return quaditerator_t<T>(this->_node->_q1);
case 2:
return quaditerator_t<T>(this->_node->_q2);
case 3:
return quaditerator_t<T>(this->_node->_q3);
default:
break;
}
}
return quaditerator_t<T>();
}
template <typename T> inline quaditerator_t<T> quaditerator_t<T>::parent()
{
return this->_node != 0 && this->_node->_up != 0 ? quaditerator_t<T>(this->_node->_up) : quaditerator_t<T>();
}
template <typename T> inline quaditerator_t<T> quaditerator_t<T>::remove()
{
if (this->_node != 0)
{
treereference_t<quadnode_t<T> > prev = this->_node;
if (prev->_up != 0)
{
if (prev->_up->_q0 == prev) { prev->_up->_q0 = -1; }
else if (prev->_up->_q1 == prev) { prev->_up->_q1 = -1; }
else if (prev->_up->_q2 == prev) { prev->_up->_q2 = -1; }
else if (prev->_up->_q3 == prev) { prev->_up->_q3 = -1; }
}
this->_node = prev->_up;
prev->_tree->_registry.remove(prev->index());
if (this->_node != 0)
{
return quaditerator_t<T>(this->_node);
}
}
return quaditerator_t<T>();
}
template <typename T> inline bool quaditerator_t<T>::root() const
{
return this->_node != 0 && this->_node->_parent == 0;
}
template <typename T> inline bool quaditerator_t<T>::leaf() const
{
return this->_node != 0 && this->_node->_left == 0 && this->_node->_right == 0;
}
template <typename T> inline bool quaditerator_t<T>::empty() const
{
return this->_node == 0;
}
template <typename T> inline T& quaditerator_t<T>::operator*() const
{
return *(this->_node->_data);
}
template <typename T> inline quaditerator_t<T> quaditerator_t<T>::operator[](const int32_t quadrant)
{
return this->child(quadrant);
}
template <typename T> inline bool quaditerator_t<T>::operator==(const quaditerator_t<T>& other) const
{
return this->_node == other._node;
}
template <typename T> inline bool quaditerator_t<T>::operator!=(const quaditerator_t<T>& other) const
{
return this->_node != other._node;
}
#include <stdio.h>
template <typename T> inline quaditerator_t<T> quadtree_t<T>::set_root(const T& item)
{
this->_registry.zero();
this->_registry[0] = quadnode_t<T>(*this, 0, 0, item);
return quaditerator_t<T>(treereference_t<quadnode_t<T> >(this->_registry, 0));
}
template <typename T> inline quaditerator_t<T> quadtree_t<T>::search(const T& item)
{
for (size_t i = 0; i < this->_registry.capacity(); i++)
{
treereference_t<quadnode_t<T> > node(this->_registry, i);
if (!node.empty() && !node->empty() && memcmp(&(node->_data), &item, sizeof(T)) == 0)
{
return quaditerator_t<T>(node);
}
}
return quaditerator_t<T>();
}
template <typename T> inline quaditerator_t<T> quadtree_t<T>::root()
{
return quaditerator_t<T>(treereference_t<quadnode_t<T> >(this->_registry, 0));
}
template <typename T> inline quaditerator_t<T> quadtree_t<T>::end() const
{
return quaditerator_t<T>();
}
template <typename T> inline void quadtree_t<T>::each(iterationfunc callback)
{
execute_each(treereference_t<quadnode_t<T> >(this->_registry, 0), callback);
}
template <typename T> inline void quadtree_t<T>::path(iterationfunc callback)
{
execute_path(treereference_t<quadnode_t<T> >(this->_registry, 0), callback);
}
template <typename T> inline void quadtree_t<T>::clear()
{
this->_registry.clear();
}
template <typename T> int32_t quadtree_t<T>::execute_each(const treereference_t<quadnode_t<T> >& node, iterationfunc callback)
{
int32_t result = 1;
if (node != 0 && !node.empty() && !node->empty() && callback != 0)
{
result = callback(node, node->_data);
// if (result != 0)
// {
// result = execute_each(node->_left, callback);
// if (result != 0)
// {
// result = execute_each(node->_right, callback);
// }
// }
}
return result;
}
template <typename T> int32_t quadtree_t<T>::execute_path(const treereference_t<quadnode_t<T> >& node, iterationfunc callback)
{
int32_t result = 0;
if (node != 0 && !node.empty() && !node->empty() && callback != 0)
{
result = callback(node, node->_data);
// if (result != 0)
// {
// if (result > 0)
// {
// return execute_path(node->_left, callback);
// }
// else
// {
// return execute_path(node->_right, callback);
// }
// }
}
return result;
}
| 26.342697
| 126
| 0.656856
|
MaxAlzner
|
f2f99b32899966a08f5aa199583f70adc9ac009d
| 3,575
|
tcc
|
C++
|
src/utils/json/parser.tcc
|
unbornchikken/reflect-cpp
|
1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f
|
[
"BSD-2-Clause"
] | 45
|
2015-03-24T09:35:46.000Z
|
2021-05-06T11:50:34.000Z
|
src/utils/json/parser.tcc
|
unbornchikken/reflect-cpp
|
1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f
|
[
"BSD-2-Clause"
] | null | null | null |
src/utils/json/parser.tcc
|
unbornchikken/reflect-cpp
|
1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f
|
[
"BSD-2-Clause"
] | 11
|
2015-01-27T12:08:21.000Z
|
2020-08-29T16:34:13.000Z
|
/* parser.tcc -*- C++ -*-
Rémi Attab (remi.attab@gmail.com), 12 Apr 2015
FreeBSD-style copyright and disclaimer apply
*/
#include "json.h"
#pragma once
namespace reflect {
namespace json {
/******************************************************************************/
/* GENERIC PARSER */
/******************************************************************************/
void parseNull(Reader& reader)
{
reader.expectToken(Token::Null);
}
bool parseBool(Reader& reader)
{
return reader.expectToken(Token::Bool).asBool();
}
int64_t parseInt(Reader& reader)
{
return reader.expectToken(Token::Int).asInt();
}
double parseFloat(Reader& reader)
{
Token token = reader.nextToken();
if (token.type() == Token::Int);
else reader.assertToken(token, Token::Float);
return token.asFloat();
}
std::string parseString(Reader& reader)
{
return reader.expectToken(Token::String).asString();
}
template<typename Fn>
void parseObject(Reader& reader, const Fn& fn)
{
Token token = reader.nextToken();
if (token.type() == Token::Null) return;
reader.assertToken(token, Token::ObjectStart);
token = reader.peekToken();
if (token.type() == Token::ObjectEnd) {
reader.expectToken(Token::ObjectEnd);
return;
}
while (reader) {
token = reader.expectToken(Token::String);
const std::string& key = token.asString();
token = reader.expectToken(Token::KeySeparator);
fn(key);
token = reader.nextToken();
if (token.type() == Token::ObjectEnd) return;
reader.assertToken(token, Token::Separator);
}
}
template<typename Fn>
void parseArray(Reader& reader, const Fn& fn)
{
Token token = reader.nextToken();
if (token.type() == Token::Null) return;
reader.assertToken(token, Token::ArrayStart);
token = reader.peekToken();
if (token.type() == Token::ArrayEnd) {
reader.expectToken(Token::ArrayEnd);
return;
}
for (size_t i = 0; reader; ++i) {
fn(i);
token = reader.nextToken();
if (token.type() == Token::ArrayEnd) return;
reader.assertToken(token, Token::Separator);
}
}
void skip(Reader& reader)
{
Token token = reader.peekToken();
if (!reader) return;
switch (token.type()) {
case Token::Null:
case Token::Bool:
case Token::Int:
case Token::Float:
case Token::String:
(void) reader.nextToken();
break;
case Token::ArrayStart:
parseArray(reader, [&] (size_t) { skip(reader); });
break;
case Token::ObjectStart:
parseObject(reader, [&] (const std::string&) { skip(reader); });
break;
default:
reader.error("unable to skip token %s", token);
break;
}
}
/******************************************************************************/
/* VALUE PARSER */
/******************************************************************************/
template<typename T>
void parse(Reader& reader, T& value)
{
Value v = cast<Value>(value);
parse(reader, v);
}
template<typename T>
Error parse(std::istream& stream, T& value)
{
Reader reader(stream);
parse(reader, value);
return reader.error();
}
template<typename T>
Error parse(const std::string& str, T& value)
{
std::istringstream stream(str);
return parse(stream, value);
}
} // namespace json
} // namespace reflect
| 23.064516
| 80
| 0.53958
|
unbornchikken
|
f2f9f2b8b37680de67e251215bbab012254aa65a
| 290
|
hpp
|
C++
|
src/Game.hpp
|
ara159/snake
|
c65b25ab50a4b867f941c0a5406a11071ff80b78
|
[
"MIT"
] | null | null | null |
src/Game.hpp
|
ara159/snake
|
c65b25ab50a4b867f941c0a5406a11071ff80b78
|
[
"MIT"
] | null | null | null |
src/Game.hpp
|
ara159/snake
|
c65b25ab50a4b867f941c0a5406a11071ff80b78
|
[
"MIT"
] | null | null | null |
#ifndef GAME_H
#define GAME_H 1
#include "SFML/Graphics.hpp"
#include "Snake.hpp"
using namespace sf;
class Game
{
private:
RenderWindow * window;
void run();
void event_handler();
void draw();
Snake snake;
public:
Game();
~Game();
void start();
};
#endif
| 13.181818
| 28
| 0.627586
|
ara159
|
f2fa9b0bf14591422adab530b477db47bd3dab0a
| 14,020
|
cpp
|
C++
|
Source/Native/MouriOptimizationPlugin/MoManageCompactOS.cpp
|
bryanwills/NSudo
|
54ebd8092c3b2d4a89576d669ed123e23651ae77
|
[
"MIT"
] | 1,363
|
2016-06-30T07:16:09.000Z
|
2022-03-30T09:50:08.000Z
|
Source/Native/MouriOptimizationPlugin/MoManageCompactOS.cpp
|
bryanwills/NSudo
|
54ebd8092c3b2d4a89576d669ed123e23651ae77
|
[
"MIT"
] | 70
|
2017-04-29T11:17:33.000Z
|
2022-03-26T06:31:11.000Z
|
Source/Native/MouriOptimizationPlugin/MoManageCompactOS.cpp
|
bryanwills/NSudo
|
54ebd8092c3b2d4a89576d669ed123e23651ae77
|
[
"MIT"
] | 206
|
2016-07-03T02:22:05.000Z
|
2022-03-25T02:47:24.000Z
|
/*
* PROJECT: Mouri Optimization Plugin
* FILE: MoManageCompactOS.cpp
* PURPOSE: Implementation for Manage Compact OS
*
* LICENSE: The MIT License
*
* DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com)
*/
#include "MouriOptimizationPlugin.h"
#include <string>
#include <vector>
namespace
{
static void CompressFileWorker(
_In_ PNSUDO_CONTEXT Context,
_In_ LPCWSTR RootPath)
{
HANDLE RootHandle = ::MoPrivateCreateFile(
RootPath,
SYNCHRONIZE | FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
nullptr);
if (RootHandle != INVALID_HANDLE_VALUE)
{
Mile::HResult hr = S_OK;
hr = Mile::EnumerateFile(
RootHandle,
[&](
_In_ Mile::PFILE_ENUMERATE_INFORMATION Information) -> BOOL
{
if (Mile::IsDotsName(Information->FileName))
{
return TRUE;
}
{
DWORD& FileAttributes = Information->FileAttributes;
if (FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
{
return TRUE;
}
if (FileAttributes & FILE_ATTRIBUTE_EA)
{
return TRUE;
}
if (FileAttributes & FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS)
{
return TRUE;
}
}
std::wstring CurrentPath = Mile::FormatUtf16String(
L"%s\\%s",
RootPath,
Information->FileName);
if (S_OK == ::PathMatchSpecExW(
CurrentPath.c_str(),
L"*\\WinSxS\\Backup;"
L"*\\WinSxS\\ManifestCache;"
L"*\\WinSxS\\Manifests;"
L"*\\ntldr;"
L"*\\cmldr;"
L"*\\BootMgr;"
L"*\\aow.wim;"
L"*\\boot\\bcd;"
L"*\\boot\\bcd.*;"
L"*\\boot\\bootstat.dat;"
L"*\\config\\drivers;"
L"*\\config\\drivers.*;"
L"*\\config\\system;"
L"*\\config\\system.*;"
L"*\\windows\\bootstat.dat;"
L"*\\winload.e??*;"
L"*\\winresume.e??*;",
PMSF_MULTIPLE))
{
::MoPrivateWriteLine(
Context,
Context->GetTranslation(
Context,
"SkippedText"),
CurrentPath.c_str());
return TRUE;
}
if (Information->FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
::CompressFileWorker(
Context,
CurrentPath.c_str());
return TRUE;
}
HANDLE CurrentHandle = ::MoPrivateCreateFile(
CurrentPath.c_str(),
FILE_READ_DATA | FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_DELETE,
nullptr,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
nullptr);
if (CurrentHandle == INVALID_HANDLE_VALUE)
{
::MoPrivateWriteErrorMessage(
Context,
Mile::HResultFromLastError(FALSE),
L"%s(%s)",
L"CreateFileW",
CurrentPath.c_str());
return TRUE;
}
DWORD CompressionAlgorithm = 0;
hr = Mile::GetWofCompressionAttribute(
CurrentHandle,
&CompressionAlgorithm);
if (hr.IsFailed() ||
CompressionAlgorithm != FILE_PROVIDER_COMPRESSION_XPRESS4K)
{
hr = Mile::SetWofCompressionAttribute(
CurrentHandle,
FILE_PROVIDER_COMPRESSION_XPRESS4K);
if (hr.IsSucceeded())
{
::MoPrivateWriteLine(
Context,
Context->GetTranslation(
Context,
"CompressedText"),
CurrentPath.c_str());
}
else
{
::MoPrivateWriteErrorMessage(
Context,
hr,
L"%s(%s)",
L"Mile::SetWofCompressionAttribute",
CurrentPath.c_str());
}
}
else
{
::MoPrivateWriteLine(
Context,
Context->GetTranslation(
Context,
"SkippedText"),
CurrentPath.c_str());
}
::CloseHandle(CurrentHandle);
return TRUE;
});
if (hr.IsFailed())
{
::MoPrivateWriteErrorMessage(
Context,
hr,
L"%s(%s)",
L"Mile::EnumerateFile",
RootPath);
}
::CloseHandle(RootHandle);
}
else
{
::MoPrivateWriteErrorMessage(
Context,
Mile::HResultFromLastError(FALSE),
L"%s(%s)",
L"CreateFileW",
RootPath);
}
}
static void UncompressFileWorker(
_In_ PNSUDO_CONTEXT Context,
_In_ LPCWSTR RootPath)
{
HANDLE RootHandle = ::MoPrivateCreateFile(
RootPath,
SYNCHRONIZE | FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
nullptr);
if (RootHandle != INVALID_HANDLE_VALUE)
{
Mile::HResult hr = S_OK;
hr = Mile::EnumerateFile(
RootHandle,
[&](
_In_ Mile::PFILE_ENUMERATE_INFORMATION Information) -> BOOL
{
if (Mile::IsDotsName(Information->FileName))
{
return TRUE;
}
std::wstring CurrentPath = Mile::FormatUtf16String(
L"%s\\%s",
RootPath,
Information->FileName);
{
DWORD& FileAttributes = Information->FileAttributes;
if (FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
{
return TRUE;
}
if (FileAttributes & FILE_ATTRIBUTE_EA)
{
return TRUE;
}
if (FileAttributes & FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS)
{
return TRUE;
}
}
if (Information->FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
::UncompressFileWorker(
Context,
CurrentPath.c_str());
return TRUE;
}
HANDLE CurrentHandle = ::MoPrivateCreateFile(
CurrentPath.c_str(),
FILE_READ_DATA | FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_DELETE,
nullptr,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
nullptr);
if (CurrentHandle == INVALID_HANDLE_VALUE)
{
::MoPrivateWriteErrorMessage(
Context,
Mile::HResultFromLastError(FALSE),
L"%s(%s)",
L"CreateFileW",
CurrentPath.c_str());
return TRUE;
}
DWORD CompressionAlgorithm = 0;
hr = Mile::GetWofCompressionAttribute(
CurrentHandle,
&CompressionAlgorithm);
if (hr.IsSucceeded())
{
hr = Mile::RemoveWofCompressionAttribute(CurrentHandle);
if (hr.IsSucceeded())
{
::MoPrivateWriteLine(
Context,
Context->GetTranslation(
Context,
"UncompressedText"),
CurrentPath.c_str());
}
else
{
::MoPrivateWriteErrorMessage(
Context,
hr,
L"%s(%s)",
L"Mile::RemoveWofCompressionAttribute",
CurrentPath.c_str());
}
}
else
{
::MoPrivateWriteLine(
Context,
Context->GetTranslation(
Context,
"SkippedText"),
CurrentPath.c_str());
}
::CloseHandle(CurrentHandle);
return TRUE;
});
if (hr.IsFailed())
{
::MoPrivateWriteErrorMessage(
Context,
hr,
L"%s(%s)",
L"Mile::EnumerateFile",
RootPath);
}
::CloseHandle(RootHandle);
}
else
{
::MoPrivateWriteErrorMessage(
Context,
Mile::HResultFromLastError(FALSE),
L"%s(%s)",
L"CreateFileW",
RootPath);
}
}
}
EXTERN_C HRESULT WINAPI MoManageCompactOS(
_In_ PNSUDO_CONTEXT Context)
{
Mile::HResult hr = S_OK;
HANDLE PreviousContextTokenHandle = INVALID_HANDLE_VALUE;
do
{
if (!::IsWindows10OrGreater())
{
hr = E_NOINTERFACE;
break;
}
DWORD PurgeMode = ::MoPrivateParsePurgeMode(Context);
if (PurgeMode == 0)
{
hr = Mile::HResult::FromWin32(ERROR_CANCELLED);
break;
}
if (PurgeMode != MO_PRIVATE_PURGE_MODE_QUERY &&
PurgeMode != MO_PRIVATE_PURGE_MODE_ENABLE &&
PurgeMode != MO_PRIVATE_PURGE_MODE_DISABLE)
{
hr = E_NOINTERFACE;
break;
}
hr = ::MoPrivateEnableBackupRestorePrivilege(
&PreviousContextTokenHandle);
if (hr.IsFailed())
{
::MoPrivateWriteErrorMessage(
Context,
hr,
L"MoPrivateEnableBackupRestorePrivilege");
break;
}
if (PurgeMode == MO_PRIVATE_PURGE_MODE_QUERY)
{
DWORD DeploymentState = 0;
::MoPrivateWriteLine(
Context,
Context->GetTranslation(
Context,
(Mile::GetCompactOsDeploymentState(
&DeploymentState).IsSucceeded()
&& DeploymentState != FALSE)
? "MoManageCompactOS_EnabledText"
: "MoManageCompactOS_DisabledText"));
}
else if (PurgeMode == MO_PRIVATE_PURGE_MODE_ENABLE)
{
hr = Mile::SetCompactOsDeploymentState(TRUE);
if (hr.IsFailed())
{
::MoPrivateWriteErrorMessage(
Context,
hr,
L"Mile::SetCompactOsDeploymentState");
break;
}
::CompressFileWorker(
Context,
Mile::ExpandEnvironmentStringsW(L"%SystemDrive%\\").c_str());
}
else if (PurgeMode == MO_PRIVATE_PURGE_MODE_DISABLE)
{
::UncompressFileWorker(
Context,
Mile::ExpandEnvironmentStringsW(L"%SystemDrive%\\").c_str());
DWORD DeploymentState = 0;
if (Mile::GetCompactOsDeploymentState(
&DeploymentState).IsSucceeded()
&& DeploymentState != FALSE)
{
hr = Mile::SetCompactOsDeploymentState(FALSE);
if (hr.IsFailed())
{
::MoPrivateWriteErrorMessage(
Context,
hr,
L"Mile::SetCompactOsDeploymentState");
break;
}
}
}
} while (false);
if (PreviousContextTokenHandle != INVALID_HANDLE_VALUE)
{
::SetThreadToken(nullptr, PreviousContextTokenHandle);
::CloseHandle(PreviousContextTokenHandle);
}
::MoPrivateWriteFinalResult(Context, hr);
return hr;
}
| 32.155963
| 79
| 0.414194
|
bryanwills
|
f2ffc7cc13c60374f92699e9abddec3f51196fdc
| 3,184
|
cpp
|
C++
|
dynamic programming/dp3-27 gfg-leetcode/dp3 - 300. Longest Increasing Subsequence.cpp
|
ankithans/dsa
|
32aeeff1b4eeebcc8c18fdb1b95ee1dd123f8443
|
[
"MIT"
] | 1
|
2021-09-16T07:01:46.000Z
|
2021-09-16T07:01:46.000Z
|
dynamic programming/dp3-27 gfg-leetcode/dp3 - 300. Longest Increasing Subsequence.cpp
|
ankithans/dsa
|
32aeeff1b4eeebcc8c18fdb1b95ee1dd123f8443
|
[
"MIT"
] | null | null | null |
dynamic programming/dp3-27 gfg-leetcode/dp3 - 300. Longest Increasing Subsequence.cpp
|
ankithans/dsa
|
32aeeff1b4eeebcc8c18fdb1b95ee1dd123f8443
|
[
"MIT"
] | 1
|
2021-10-19T06:48:48.000Z
|
2021-10-19T06:48:48.000Z
|
// 0 1 2 3 4 5 6 7
// [10,9,2,5,3,7,101,18]
// o/p = 4 [2,3,7,101]
// idx -> f -> LIS
// (0, [])
// 2 (1, [10]) (1, [])
// (2,[10]) (2,[9]) (2,[])
// (3,[10]) (3,[9])
// (4,[10]) (4,[9])
// (5,[10])
// (6,[10,101]) (6,[10])
// (7,[10,101]) (7,[10,18]) (7,[10])
// 22 / 54 test cases passed.
// TLE
class Solution {
public:
int LIShelper(int idx, int lastMax, vector<int> &nums) {
if(idx >= nums.size())
return 0;
int pick = INT_MIN;
if(nums[idx] > lastMax) {
pick = 1 + LIShelper(idx+1, nums[idx], nums);
}
int not_pick = LIShelper(idx+1, lastMax, nums);
return max(pick, not_pick);
}
int lengthOfLIS(vector<int>& nums) {
return LIShelper(0, INT_MIN, nums);
}
};
class Solution {
public:
int LIShelper(vector<int> &nums, int idx, int lastMax, vector<int> &dp) {
if(idx >= nums.size())
return 0;
int pick = INT_MIN;
if(nums[idx] > lastMax) {
if(dp[idx] != -1) pick = dp[idx];
else
dp[idx] = pick = 1 + LIShelper(nums, idx+1, nums[idx], dp);
}
int not_pick = LIShelper(nums, idx+1, lastMax, dp);
return max(pick, not_pick);
}
int lengthOfLIS(vector<int>& nums) {
vector<int> dp(nums.size()+1, -1);
return LIShelper(nums, 0, INT_MIN, dp);
}
};
// https://leetcode.com/problems/longest-increasing-subsequence/discuss/1326552/Optimization-From-Brute-Force-to-Dynamic-Programming-Explained!
class Solution {
public:
vector<vector<int>> dp;
int LIShelper(vector<int> &nums, int idx, int lastMaxInd) {
if(idx >= nums.size())
return 0;
if(dp[idx][lastMaxInd+1] != -1) return dp[idx][lastMaxInd+1];
int pick = INT_MIN;
if(lastMaxInd == -1 || nums[idx] > nums[lastMaxInd]) {
pick = 1 + LIShelper(nums, idx+1, idx);
}
int not_pick = LIShelper(nums, idx+1, lastMaxInd);
return dp[idx][lastMaxInd+1] = max(pick, not_pick);
}
int lengthOfLIS(vector<int>& nums) {
dp.resize(size(nums), vector<int>(1+size(nums), -1));
return LIShelper(nums, 0, -1);
}
};
class Solution {
public:
vector<int> dp;
int LIShelper(vector<int> &nums, int idx, int lastMaxInd) {
if(idx >= nums.size())
return 0;
if(dp[lastMaxInd+1] != -1) return dp[lastMaxInd+1];
int pick = INT_MIN;
if(lastMaxInd == -1 || nums[idx] > nums[lastMaxInd]) {
pick = 1 + LIShelper(nums, idx+1, idx);
}
int not_pick = LIShelper(nums, idx+1, lastMaxInd);
return dp[lastMaxInd+1] = max(pick, not_pick);
}
int lengthOfLIS(vector<int>& nums) {
dp.resize(size(nums)+1, -1);
return LIShelper(nums, 0, -1);
}
};
| 26.983051
| 143
| 0.47142
|
ankithans
|
f2ffca4a66451085ebad8884a6f3a40914c630c0
| 759
|
cpp
|
C++
|
src/506.cpp
|
MoRunChang2015/LeetCode
|
d046083b952811dfbf5f8fb646060836a3e937ce
|
[
"Apache-2.0"
] | null | null | null |
src/506.cpp
|
MoRunChang2015/LeetCode
|
d046083b952811dfbf5f8fb646060836a3e937ce
|
[
"Apache-2.0"
] | null | null | null |
src/506.cpp
|
MoRunChang2015/LeetCode
|
d046083b952811dfbf5f8fb646060836a3e937ce
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
vector<pair<int, int>> v;
for (int i = 0; i < nums.size(); ++i) {
v.push_back({nums[i], i});
}
sort(v.begin(), v.end());
vector<string> ans(nums.size());
for (int i = 0; i < nums.size(); ++i) {
if (i == nums.size() - 1) {
ans[v[i].second] = "Gold Medal";
} else if (i == nums.size() - 2) {
ans[v[i].second] = "Silver Medal";
} else if (i == nums.size() - 3) {
ans[v[i].second] = "Bronze Medal";
} else {
ans[v[i].second] = to_string(nums.size() - i);
}
}
return ans;
}
};
| 31.625
| 62
| 0.417655
|
MoRunChang2015
|
8402cf8233496ce59dc4677557df3e787ed7dc5c
| 7,948
|
cc
|
C++
|
src/comm/communicator_collective.cc
|
akkaze/rdc
|
76e85e3fe441e3ba968a190d9496f467b9d4d2e6
|
[
"BSD-3-Clause"
] | 52
|
2018-10-08T01:56:15.000Z
|
2021-03-14T12:19:51.000Z
|
src/comm/communicator_collective.cc
|
akkaze/rdc
|
76e85e3fe441e3ba968a190d9496f467b9d4d2e6
|
[
"BSD-3-Clause"
] | null | null | null |
src/comm/communicator_collective.cc
|
akkaze/rdc
|
76e85e3fe441e3ba968a190d9496f467b9d4d2e6
|
[
"BSD-3-Clause"
] | 3
|
2019-01-02T05:17:28.000Z
|
2020-01-06T03:53:12.000Z
|
#include "comm/communicator_base.h"
#include "comm/communicator_manager.h"
namespace rdc {
namespace comm {
void Communicator::TryAllreduce(Buffer sendrecvbuf, ReduceFunction reducer) {
if (sendrecvbuf.size_in_bytes() >
CommunicatorManager::Get()->reduce_ring_mincount()) {
return this->TryAllreduceRing(sendrecvbuf, reducer);
} else {
return this->TryAllreduceTree(sendrecvbuf, reducer);
}
}
void Communicator::TryReduceTree(Buffer sendrecvbuf, Buffer reducebuf,
ReduceFunction reducer, int root) {
auto dists_from_root = tree_map_.ShortestDist(root);
auto dist_from_root = dists_from_root[GetRank()];
auto neighbors = tree_map_.GetNeighbors(GetRank());
std::unordered_set<int> recv_from_nodes;
int send_to_node = -1;
for (const auto& neighbor : neighbors) {
if (dists_from_root[neighbor] == dist_from_root + 1) {
recv_from_nodes.insert(neighbor);
} else if (dists_from_root[neighbor] == dist_from_root - 1) {
send_to_node = neighbor;
}
}
for (const auto& recv_from_node : recv_from_nodes) {
auto wc = all_links_[recv_from_node]->IRecv(reducebuf);
wc->Wait();
reducer(reducebuf, sendrecvbuf);
WorkCompletion::Delete(wc);
}
auto chain_wc = ChainWorkCompletion::New();
if (send_to_node != -1) {
auto wc = all_links_[send_to_node]->ISend(sendrecvbuf);
chain_wc->Add(wc);
}
chain_wc->Wait();
ChainWorkCompletion::Delete(chain_wc);
return;
}
void Communicator::TryBroadcast(Buffer sendrecvbuf, int root) {
auto dists_from_root = tree_map_.ShortestDist(root);
auto dist_from_root = dists_from_root[GetRank()];
auto neighbors = tree_map_.GetNeighbors(GetRank());
std::unordered_set<int> send_to_nodes;
int recv_from_node = -1;
for (const auto& neighbor : neighbors) {
if (dists_from_root[neighbor] == dist_from_root + 1) {
send_to_nodes.insert(neighbor);
} else if (dists_from_root[neighbor] == dist_from_root - 1) {
recv_from_node = neighbor;
}
}
auto chain_wc = ChainWorkCompletion::New();
if (recv_from_node != -1) {
auto wc = all_links_[recv_from_node]->IRecv(sendrecvbuf);
chain_wc->Add(wc);
}
for (const auto& send_to_node : send_to_nodes) {
auto wc = all_links_[send_to_node]->ISend(sendrecvbuf);
chain_wc->Add(wc);
}
chain_wc->Wait();
ChainWorkCompletion::Delete(chain_wc);
return;
}
void Communicator::TryAllreduceTree(Buffer sendrecvbuf,
ReduceFunction reducer) {
Buffer reducebuf(sendrecvbuf.size_in_bytes());
reducebuf.AllocTemp(utils::AllocTemp);
TryReduceTree(sendrecvbuf, reducebuf, reducer, 0);
reducebuf.FreeTemp(utils::Free);
TryBroadcast(sendrecvbuf, 0);
}
void Communicator::TryAllgatherRing(std::vector<Buffer> sendrecvbufs) {
// read from next link and send to prev one
auto &prev = ring_prev_, &next = ring_next_;
const size_t count_bufs = GetWorldSize();
const size_t stop_write_idx = count_bufs + GetRank() - 1;
const size_t stop_read_idx = count_bufs + GetRank();
size_t write_idx = GetRank();
size_t read_idx = GetRank() + 1;
while (true) {
bool finished = true;
if (read_idx != stop_read_idx) {
finished = false;
}
if (write_idx != stop_write_idx) {
finished = false;
}
if (finished)
break;
auto chain_wc = ChainWorkCompletion::New();
if (write_idx < read_idx && write_idx != stop_write_idx) {
size_t start = write_idx % count_bufs;
auto wc = prev->ISend(sendrecvbufs[start]);
chain_wc->Add(wc);
write_idx++;
}
if (read_idx != stop_read_idx) {
size_t start = read_idx % count_bufs;
auto wc = next->IRecv(sendrecvbufs[start]);
chain_wc->Add(wc);
// wc.Wait();
read_idx++;
}
chain_wc->Wait();
ChainWorkCompletion::Delete(chain_wc);
}
}
void Communicator::TryReduceScatterRing(Buffer sendrecvbuf, Buffer reducebuf,
ReduceFunction reducer) {
// read from next link and send to prev one
auto &&prev = ring_prev_, &&next = ring_next_;
uint64_t n = static_cast<uint64_t>(GetWorldSize());
const auto& ranges = utils::Split(0, sendrecvbuf.Count(), n);
uint64_t write_idx = GetNextRank();
uint64_t read_idx = GetNextRank() + 1;
uint64_t reduce_idx = read_idx;
// position to stop reading
const uint64_t stop_read_idx = n + GetNextRank();
// position to stop writing
size_t stop_write_idx = n + GetRank();
;
const auto& item_size = sendrecvbuf.item_size();
if (stop_write_idx > stop_read_idx) {
stop_write_idx -= n;
CHECK_F(write_idx <= stop_write_idx, "write ptr boundary check");
}
while (true) {
bool finished = true;
if (read_idx != stop_read_idx) {
finished = false;
}
if (write_idx != stop_write_idx) {
finished = false;
}
if (finished)
break;
auto chain_wc = ChainWorkCompletion::New();
if (write_idx < reduce_idx && write_idx != stop_write_idx) {
uint64_t write_pos = write_idx % n;
uint64_t write_size =
(ranges[write_pos].second - ranges[write_pos].first) *
item_size;
uint64_t write_start = ranges[write_pos].first * item_size;
auto wc = prev->ISend(
sendrecvbuf.Slice(write_start, write_start + write_size));
chain_wc->Add(wc);
write_idx++;
}
if (read_idx != stop_read_idx) {
uint64_t read_pos = read_idx % n;
uint64_t read_start = ranges[read_pos].first * item_size;
uint64_t read_size =
(ranges[read_pos].second - ranges[read_pos].first) *
item_size;
auto wc = next->IRecv(
reducebuf.Slice(read_start, read_start + read_size));
chain_wc->Add(wc);
chain_wc->Wait();
CHECK_F(read_idx <= stop_read_idx, "[%d] read_ptr boundary check",
GetRank());
read_idx++;
size_t reduce_pos = reduce_idx % n;
size_t reduce_start = ranges[reduce_pos].first * item_size;
size_t reduce_size =
(ranges[reduce_pos].second - ranges[reduce_pos].first) *
item_size;
reducer(
reducebuf.Slice(reduce_start, reduce_start + reduce_size),
sendrecvbuf.Slice(reduce_start, reduce_start + reduce_size));
reduce_idx++;
}
ChainWorkCompletion::Delete(chain_wc);
}
return;
}
void Communicator::TryAllreduceRing(Buffer sendrecvbuf,
ReduceFunction reducer) {
Buffer reducebuf(sendrecvbuf.size_in_bytes());
reducebuf.AllocTemp(utils::AllocTemp);
reducebuf.set_item_size(sendrecvbuf.item_size());
TryReduceScatterRing(sendrecvbuf, reducebuf, reducer);
reducebuf.FreeTemp(utils::Free);
uint64_t n = static_cast<uint64_t>(GetWorldSize());
const auto& ranges = utils::Split(0, sendrecvbuf.Count(), n);
// get rank of previous
std::vector<Buffer> sendrecvbufs(n);
for (auto i = 0U; i < n; i++) {
uint64_t begin = ranges[i].first;
uint64_t end = ranges[i].second;
uint64_t size = (end - begin) * sendrecvbuf.item_size();
sendrecvbufs[i].set_size_in_bytes(size);
sendrecvbufs[i].set_addr(utils::IncrVoidPtr(
sendrecvbuf.addr(), begin * sendrecvbuf.item_size()));
}
return TryAllgatherRing(sendrecvbufs);
}
} // namespace comm
} // namespace rdc
| 38.582524
| 78
| 0.612355
|
akkaze
|
8404279ffd536f25360485833c7e0df1f9a555f5
| 2,249
|
cpp
|
C++
|
src/minhook_api.cpp
|
MG4vQIs7Fv/PerformanceOverhaulCyberpunk
|
4fb6e34752ce7c286357cf148d0b4096d4ca32ea
|
[
"MIT"
] | 26
|
2019-10-28T00:14:18.000Z
|
2022-03-05T22:26:46.000Z
|
src/minhook_api.cpp
|
MG4vQIs7Fv/PerformanceOverhaulCyberpunk
|
4fb6e34752ce7c286357cf148d0b4096d4ca32ea
|
[
"MIT"
] | null | null | null |
src/minhook_api.cpp
|
MG4vQIs7Fv/PerformanceOverhaulCyberpunk
|
4fb6e34752ce7c286357cf148d0b4096d4ca32ea
|
[
"MIT"
] | 7
|
2019-10-28T03:21:19.000Z
|
2022-03-25T11:05:43.000Z
|
#include "common.hpp"
#include "minhook_api.hpp"
#include "minhook.h"
namespace minhook_api {
#if defined(USE_MINHOOK) && (USE_MINHOOK == 1)
void init() {
if(MH_Initialize() != MH_OK) {
DEBUG_TRACE("MH_Initialize : failed\n");
}
}
void cleanup() {
MH_Uninitialize();
}
#else
void init() {}
void cleanup() {}
#endif
} // namespace minhook
#if defined(USE_MINHOOK) && (USE_MINHOOK == 1)
#define D(funcname, ...) \
return funcname(__VA_ARGS__); \
__pragma(comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__))
extern "C" MH_STATUS WINAPI MH_Initialize_(void) {
D(MH_Initialize)
}
extern "C" MH_STATUS WINAPI MH_Uninitialize_(void) {
D(MH_Uninitialize);
}
extern "C" MH_STATUS WINAPI MH_CreateHook_(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal) {
D(MH_CreateHook, pTarget, pDetour, ppOriginal);
}
extern "C" MH_STATUS WINAPI MH_CreateHookApi_(LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal) {
D(MH_CreateHookApi, pszModule, pszProcName, pDetour, ppOriginal);
}
extern "C" MH_STATUS WINAPI MH_CreateHookApiEx_(LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget) {
D(MH_CreateHookApiEx, pszModule, pszProcName, pDetour, ppOriginal, ppTarget);
}
extern "C" MH_STATUS WINAPI MH_RemoveHook_(LPVOID pTarget) {
D(MH_RemoveHook, pTarget);
}
extern "C" MH_STATUS WINAPI MH_EnableHook_(LPVOID pTarget) {
D(MH_EnableHook, pTarget);
}
extern "C" MH_STATUS WINAPI MH_DisableHook_(LPVOID pTarget) {
D(MH_DisableHook, pTarget);
}
extern "C" MH_STATUS WINAPI MH_QueueEnableHook_(LPVOID pTarget) {
D(MH_QueueEnableHook, pTarget);
}
extern "C" MH_STATUS WINAPI MH_QueueDisableHook_(LPVOID pTarget) {
D(MH_QueueDisableHook, pTarget);
}
extern "C" MH_STATUS WINAPI MH_ApplyQueued_(void) {
D(MH_ApplyQueued);
}
extern "C" const char * WINAPI MH_StatusToString_(MH_STATUS status) {
D(MH_StatusToString, status);
}
#endif
| 28.833333
| 142
| 0.638061
|
MG4vQIs7Fv
|
8405943d2334623503f09655d041c70e5d8bc794
| 483
|
cpp
|
C++
|
C++ STL Programming/C++_STL_Programming/Operator_Overloading/06_PlusOperatorFuncion.cpp
|
devgunho/Cpp_AtoZ
|
4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc
|
[
"MIT"
] | 1
|
2022-03-25T06:11:06.000Z
|
2022-03-25T06:11:06.000Z
|
C++ STL Programming/C++_STL_Programming/Operator_Overloading/06_PlusOperatorFuncion.cpp
|
devgunho/Cpp_AtoZ
|
4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc
|
[
"MIT"
] | null | null | null |
C++ STL Programming/C++_STL_Programming/Operator_Overloading/06_PlusOperatorFuncion.cpp
|
devgunho/Cpp_AtoZ
|
4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
class Point
{
int x;
int y;
public:
Point(int _x = 0, int _y = 0) :x(_x), y(_y) {}
void Print() const { cout << x << ',' << y << endl; }
const Point operator+(const Point& arg) const
{
Point pt;
pt.x = this->x + arg.x;
pt.y = this->y + arg.y;
return pt;
}
};
int main()
{
Point p1(2, 3), p2(5, 5);
Point p3;
p3 = p1 + p2; // = p1.operator+(p2)
p3.Print();
p3 = p1.operator+(p2); // Direct call
p3.Print();
return 0;
}
| 16.1
| 54
| 0.554865
|
devgunho
|
8406a1d0255cf5abbe189d3c0beeb27a9a93973a
| 389
|
hpp
|
C++
|
src/firmware/src/websocket/socket_server.hpp
|
geaz/tableDisco
|
1f081a0372da835150881da245dc69d97dcaabe3
|
[
"MIT"
] | 1
|
2020-05-26T01:45:04.000Z
|
2020-05-26T01:45:04.000Z
|
src/firmware/src/websocket/socket_server.hpp
|
geaz/tableDisco
|
1f081a0372da835150881da245dc69d97dcaabe3
|
[
"MIT"
] | null | null | null |
src/firmware/src/websocket/socket_server.hpp
|
geaz/tableDisco
|
1f081a0372da835150881da245dc69d97dcaabe3
|
[
"MIT"
] | null | null | null |
#pragma once
#ifndef SOCKETSERVER_H
#define SOCKETSERVER_H
#include <WebSocketsServer.h>
namespace TableDisco
{
class SocketServer
{
public:
SocketServer();
void loop();
void broadcast(String data);
private:
WebSocketsServer webSocket = WebSocketsServer(81);
};
}
#endif // SOCKETSERVER_H
| 17.681818
| 62
| 0.586118
|
geaz
|
8406dca80a0a5d0c040e297255c6eae5b07d4f27
| 2,391
|
cpp
|
C++
|
src/index_handler/index_file_handler.cpp
|
robinren03/database2021
|
50074b6fdab2bcd5d4c95870f247cfb430804081
|
[
"Apache-2.0"
] | null | null | null |
src/index_handler/index_file_handler.cpp
|
robinren03/database2021
|
50074b6fdab2bcd5d4c95870f247cfb430804081
|
[
"Apache-2.0"
] | null | null | null |
src/index_handler/index_file_handler.cpp
|
robinren03/database2021
|
50074b6fdab2bcd5d4c95870f247cfb430804081
|
[
"Apache-2.0"
] | 1
|
2022-01-11T08:20:41.000Z
|
2022-01-11T08:20:41.000Z
|
#include "index_file_handler.h"
#include <assert.h>
IndexFileHandler::IndexFileHandler(BufManager* _bm){
bm = _bm;
header = new IndexFileHeader;
}
void IndexFileHandler::openFile(const char* fileName){
fileID = bm->openFile(fileName);
int headerIndex;
if (fileID == -1){
bm->createFile(fileName);
fileID = bm->openFile(fileName);
/*IndexFileHeader* tempHeader = (IndexFileHeader*)*/bm->allocPage(fileID, 0, headerIndex);
headerChanged = true;
header->rootPageId = 1;
header->pageCount = 1;
header->firstLeaf = 1;
header->lastLeaf = 1;
header->sum = 0;
int index;
BPlusNode* root = (BPlusNode*)bm->allocPage(fileID, 1, index);
root->nextPage = 0;
root->prevPage = 0;
root->nodeType = ix::LEAF;
root->pageId = 1;
root->recs = 0;
bm->markDirty(index);
}
else {
IndexFileHeader* tempHeader = (IndexFileHeader*)bm->getPage(fileID, 0, headerIndex);
memcpy(header, tempHeader, sizeof(IndexFileHeader));
}
}
IndexFileHandler::~IndexFileHandler(){
delete header;
closeFile();
}
void IndexFileHandler::access(int index){
bm->access(index);
}
char* IndexFileHandler::newPage(int &index, bool isOvrflowPage){
// std::cout << "Apply for a new page" << std::endl;
header->pageCount++;
/*if (header->pageCount == 342) {
cout << "Hello World!" << endl;
}
std::cout << "Apply for a new page" << header->pageCount << std::endl;*/
char* res = bm->getPage(fileID, header->pageCount, index);
if(isOvrflowPage) ((BPlusOverflowPage*)res)->pageId = header->pageCount;
else ((BPlusNode*)res)->pageId = header->pageCount;
markPageDirty(index);
markHeaderPageDirty();
return res;
}
char* IndexFileHandler::getPage(int pageID, int& index){
return bm->getPage(fileID, pageID, index);
}
void IndexFileHandler::markHeaderPageDirty(){
headerChanged = true;
}
void IndexFileHandler::markPageDirty(int index){
bm->markDirty(index);
}
void IndexFileHandler::closeFile(){
if (bm != nullptr){
int headerIndex;
IndexFileHeader* tempHeader = (IndexFileHeader*)bm->getPage(fileID, 0, headerIndex);
memcpy(tempHeader, header, sizeof(IndexFileHeader));
this->markPageDirty(headerIndex);
bm->closeFile(fileID);
}
}
| 29.158537
| 98
| 0.634044
|
robinren03
|
840c144708b1a8d9abcb758af72c07ae85187df7
| 2,833
|
cpp
|
C++
|
misc/fexcept/execdump/xxlib/Std/mu_case.cpp
|
MKadaner/FarManager
|
c99a14c12e3481dd25ce71451ecd264656f631bb
|
[
"BSD-3-Clause"
] | 1,256
|
2015-07-07T12:19:17.000Z
|
2022-03-31T18:41:41.000Z
|
misc/fexcept/execdump/xxlib/Std/mu_case.cpp
|
MKadaner/FarManager
|
c99a14c12e3481dd25ce71451ecd264656f631bb
|
[
"BSD-3-Clause"
] | 305
|
2017-11-01T18:58:50.000Z
|
2022-03-22T11:07:23.000Z
|
misc/fexcept/execdump/xxlib/Std/mu_case.cpp
|
MKadaner/FarManager
|
c99a14c12e3481dd25ce71451ecd264656f631bb
|
[
"BSD-3-Clause"
] | 183
|
2017-10-28T11:31:14.000Z
|
2022-03-30T16:46:24.000Z
|
#include <all_lib.h>
#pragma hdrstop
#if defined(__MYPACKAGE__)
#pragma package(smart_init)
#endif
#if !defined(__HWIN__)
static char *lwrChars = "йцукенгшщзхъфывапролджэячсмитьбю";
static char *uprChars = "ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ";
char MYRTLEXP ToUpper( char ch )
{
if ( ch >= 'A' && ch <= 'Z' ) return ch;
if ( ch >= 'a' && ch <= 'z' ) return (char)(ch-'a'+'A');
for( int n = 0; lwrChars[n]; n++ )
if ( lwrChars[n] == ch )
return uprChars[n];
return ch;
}
char MYRTLEXP ToLower( char ch )
{
if ( ch >= 'a' && ch <= 'z' ) return ch;
if ( ch >= 'A' && ch <= 'Z' ) return (char)(ch-'A'+'a');
for( int n = 0; uprChars[n]; n++ )
if ( uprChars[n] == ch )
return lwrChars[n];
return ch;
}
BOOL MYRTLEXP isLower( char ch )
{
if ( ch >= 'a' && ch <= 'z' ) return TRUE;
return StrChr(lwrChars,ch) != NULL;
}
BOOL MYRTLEXP isUpper( char ch )
{
if ( ch >= 'A' && ch <= 'Z' ) return TRUE;
return StrChr(uprChars,ch) != NULL;
}
void MYRTLEXP StrLwr( char *str )
{
for ( int n = 0; str[n]; n++ )
str[n] = ToLower( str[n] );
}
void MYRTLEXP StrUpr( char *str )
{
for ( int n = 0; str[n]; n++ )
str[n] = ToUpper( str[n] );
}
#endif
static const char* sysSpaces= " \t";
BOOL MYRTLEXP isSpace( char ch )
{
return StrChr( sysSpaces,ch ) != NULL;
}
char *MYRTLEXP StrCase( char *str,msCaseTypes type )
{ int n;
if ( !str || *str == 0 ) return str;
switch( type ){
case mscLower: StrLwr( str ); break;
case mscUpper: StrUpr( str ); break;
case mscCapitalize: StrLwr( str );
str[0] = ToUpper(str[0]);
break;
case mscUpLower: for ( n = 0; str[n]; n++ )
if ( isLower(str[n]) ) return str;
return StrCase( str,mscLower );
case mscLoUpper: for ( n = 0; str[n]; n++ )
if ( isUpper(str[n]) ) return str;
return StrCase( str,mscUpper );
case mscInvert: for ( n = 0; str[n]; n++ )
if ( isUpper(str[n]) )
str[n] = ToLower(str[n]);
else
str[n] = ToUpper(str[n]);
break;
}
return str;
}
#if defined(__GNUC__)
static int memicmp(const void *s1, const void *s2, size_t n)
{
LPCBYTE b1 = (LPCBYTE)s1,
b2 = (LPCBYTE)s2;
for( ; n > 0; n--, b1++, b2++ ) {
BYTE ch = *b1 - *b2;
if ( ch )
return (int)(ch);
}
return 0;
}
#endif
BOOL MYRTLEXP BuffCmp( LPBYTE b, LPBYTE b1, DWORD count, BOOL Case )
{
if ( Case )
return memcmp( b,b1,count ) == 0;
else
return memicmp( b,b1,count ) == 0;
}
| 24.850877
| 68
| 0.491705
|
MKadaner
|
840cc9b4774d397c3f63b506e10cd5e32c5a3893
| 655
|
cpp
|
C++
|
test.cpp
|
ZaMaZaN4iK/iex_example
|
57717f34f39ceadf1407bdd6b925f6b8c894533c
|
[
"MIT"
] | 1
|
2020-04-25T14:16:03.000Z
|
2020-04-25T14:16:03.000Z
|
test.cpp
|
ZaMaZaN4iK/iex_example
|
57717f34f39ceadf1407bdd6b925f6b8c894533c
|
[
"MIT"
] | null | null | null |
test.cpp
|
ZaMaZaN4iK/iex_example
|
57717f34f39ceadf1407bdd6b925f6b8c894533c
|
[
"MIT"
] | 1
|
2020-04-25T14:17:49.000Z
|
2020-04-25T14:17:49.000Z
|
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include "CompanyPriceDataStorage.h"
/*
That's a sample test case
*/
TEST_CASE( "Company price data is stored and selecte3d", "[storage]" ) {
CompanyPriceData etalonData{0, "1", "2", "3", "4"}
CompanyPriceDataStorage storage("test.db");
const int id = storage.store(etalonData);
const CompanyPriceData storedData = storage.read(id);
CHECK_THAT(etalonData.symbol, Equals(storedData.symbol));
CHECK_THAT(etalonData.companyName, Equals(storedData.companyName));
CHECK_THAT(etalonData.logo, Equals(storedData.logo));
CHECK_THAT(etalonData.price, Equals(storedData.price));
}
| 32.75
| 72
| 0.732824
|
ZaMaZaN4iK
|
8411ec0587bd6d49d94bee2f8e3e0d32ae5148d6
| 5,231
|
cpp
|
C++
|
source/options/OptionDialog.cpp
|
Mauzerov/wxPacman
|
9fe599b1588d6143ff563ae8a3e5c2f31f69a5c3
|
[
"Unlicense"
] | 1
|
2021-05-02T10:38:03.000Z
|
2021-05-02T10:38:03.000Z
|
source/options/OptionDialog.cpp
|
Mauzerov/wxPacman
|
9fe599b1588d6143ff563ae8a3e5c2f31f69a5c3
|
[
"Unlicense"
] | null | null | null |
source/options/OptionDialog.cpp
|
Mauzerov/wxPacman
|
9fe599b1588d6143ff563ae8a3e5c2f31f69a5c3
|
[
"Unlicense"
] | null | null | null |
#include "OptionDialog.h"
#include <iostream>
//(*InternalHeaders(OptionDialog)
#include <wx/font.h>
#include <wx/intl.h>
#include <wx/settings.h>
#include <wx/string.h>
//*)
//(*IdInit(OptionDialog)
const long OptionDialog::ID_BUTTONSAVE = wxNewId();
const long OptionDialog::ID_KEYCHOICE = wxNewId();
const long OptionDialog::ID_LANGCHOICE = wxNewId();
//*)
BEGIN_EVENT_TABLE(OptionDialog,wxDialog)
//(*EventTable(OptionDialog)
//*)
END_EVENT_TABLE()
OptionDialog::OptionDialog(wxWindow* parent, wxWindowID id, std::string movement, std::string language)
{
//(*Initialize(OptionDialog)
Create(parent, id, _("Options"), wxDefaultPosition, wxDefaultSize, wxCAPTION|wxSYSTEM_MENU, _T("id"));
SetClientSize(wxSize(400,200));
SetForegroundColour(wxColour(255,255,255));
SetBackgroundColour(wxColour(0,0,0));
wxFont thisFont(11,wxFONTFAMILY_MODERN,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL,false,_T("Consolas"),wxFONTENCODING_DEFAULT);
SetFont(thisFont);
GamePausePanel = new wxPanel(this, wxID_ANY, wxPoint(0,0), wxSize(400,30), 0, _T("wxID_ANY"));
GamePauseLabel = new wxStaticText(GamePausePanel, wxID_ANY, _("GAME PAUSED"), wxPoint(0,0), wxSize(400,50), wxALIGN_CENTRE, _T("wxID_ANY"));
GamePauseLabel->SetForegroundColour(wxColour(243,156,18));
GamePauseLabel->SetBackgroundColour(wxColour(16,16,16));
wxFont GamePauseLabelFont(20,wxFONTFAMILY_MODERN,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL,false,_T("Consolas"),wxFONTENCODING_DEFAULT);
GamePauseLabel->SetFont(GamePauseLabelFont);
GamePauseUnderLine = new wxStaticLine(this, wxID_ANY, wxPoint(0,30), wxSize(400,2), wxLI_HORIZONTAL, _T("wxID_ANY"));
GamePauseUnderLine->SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
GamePauseUnderLine->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
SaveOptionBtn = new wxButton(this, ID_BUTTONSAVE, _("Save Options"), wxPoint(100,175), wxSize(200,25), wxBORDER_NONE|wxTRANSPARENT_WINDOW, wxDefaultValidator, _T("ID_BUTTONSAVE"));
SaveOptionBtn->SetForegroundColour(wxColour(255,255,255));
SaveOptionBtn->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
KeyBindsPanel = new wxPanel(this, wxID_ANY, wxPoint(0,40), wxSize(200,50), wxBORDER_SIMPLE, _T("wxID_ANY"));
KeyBindsMoveChoice = new wxChoice(KeyBindsPanel, ID_KEYCHOICE, wxPoint(8,8), wxDefaultSize, 0, 0, 0, wxDefaultValidator, _T("ID_KEYCHOICE"));
KeyBindsMoveChoice->Append(_("Arrows"));
KeyBindsMoveChoice->Append(_("WSAD"));
KeyBindsMoveLabel = new wxStaticText(KeyBindsPanel, wxID_ANY, _("Movement\nKeys"), wxPoint(120,4), wxSize(70,40), wxALIGN_CENTRE, _T("wxID_ANY"));
KeyBindsMoveLabel->SetForegroundColour(wxColour(255,255,255));
GameLangPanel = new wxPanel(this, wxID_ANY, wxPoint(200,40), wxSize(200,50), wxBORDER_SIMPLE, _T("wxID_ANY"));
GameLangChoise = new wxChoice(GameLangPanel, ID_LANGCHOICE, wxPoint(8,8), wxDefaultSize, 0, 0, 0, wxDefaultValidator, _T("ID_LANGCHOICE"));
GameLangChoise->Append(_("Polski"));
GameLangChoise->Append(_("English"));
GameLangLabel = new wxStaticText(GameLangPanel, wxID_ANY, _("Language"), wxPoint(120,12), wxSize(70,40), wxALIGN_CENTRE, _T("wxID_ANY"));
GameLangLabel->SetForegroundColour(wxColour(255,255,255));
SpaceShootLabel = new wxStaticText(this, wxID_ANY, _("Label"), wxPoint(10,100), wxSize(380,20), wxALIGN_CENTRE, _T("wxID_ANY"));
wxFont SpaceShootLabelFont(12,wxFONTFAMILY_MODERN,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL,false,_T("Consolas"),wxFONTENCODING_DEFAULT);
SpaceShootLabel->SetFont(SpaceShootLabelFont);
Center();
Connect(ID_BUTTONSAVE,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&OptionDialog::OnSaveOptionBtnClick);
Connect(wxID_ANY,wxEVT_CLOSE_WINDOW,(wxObjectEventFunction)&OptionDialog::OnDialogClose);
//*)
///TODO Options uising int indexes
this->KeyBindsMoveChoice->Select(this->KeyBindsMoveChoice->FindString(movement)); // Set Current Move Option
this->GameLangChoise->Select(this->GameLangChoise->FindString(language)); // Set Current Language Option
this->GameLangLabel->SetLabel(lang::lang.at(language).at("language_pick")); // Translated Language
this->KeyBindsMoveLabel->SetLabel(lang::lang.at(language).at("movement_pick")); // Translated Movement
this->SaveOptionBtn->SetLabel(lang::lang.at(language).at("save_options")); // Translated Saving Options
this->GamePauseLabel->SetLabel(lang::lang.at(language).at("game_paused")); // Translated Game Paused Label
this->SpaceShootLabel->SetLabel(lang::lang.at(language).at("space_button")); // Translated Game Paused Label
this->movement = movement;
this->language = language;
}
OptionDialog::~OptionDialog( void )
{
//(*Destroy(OptionDialog)
//*)
}
void OptionDialog::OnDialogClose(wxCloseEvent& event)
{
this->Destroy();
}
void OptionDialog::SaveOptions( void )
{
this->movement = std::string(this->KeyBindsMoveChoice->GetStringSelection().mb_str()); // Changing Movement Method
this->language = std::string(this->GameLangChoise->GetStringSelection().mb_str()); // Changing Language
}
void OptionDialog::OnSaveOptionBtnClick(wxCommandEvent& event)
{
this->SaveOptions();
this->Destroy();
}
| 52.31
| 182
| 0.761422
|
Mauzerov
|
8416064ba4d7477f450641def58f3b03edb4f096
| 8,294
|
cpp
|
C++
|
HPCSimulation.cpp
|
iray-tno/hal2015
|
c84643472b31efbcd7622867dcc4e71c80541274
|
[
"FSFAP"
] | null | null | null |
HPCSimulation.cpp
|
iray-tno/hal2015
|
c84643472b31efbcd7622867dcc4e71c80541274
|
[
"FSFAP"
] | null | null | null |
HPCSimulation.cpp
|
iray-tno/hal2015
|
c84643472b31efbcd7622867dcc4e71c80541274
|
[
"FSFAP"
] | null | null | null |
//------------------------------------------------------------------------------
/// @file
/// @brief HPCSimulation.hpp の実装
/// @author ハル研究所プログラミングコンテスト実行委員会
///
/// @copyright Copyright (c) 2015 HAL Laboratory, Inc.
/// @attention このファイルの利用は、同梱のREADMEにある
/// 利用条件に従ってください
//------------------------------------------------------------------------------
#include "HPCSimulation.hpp"
#include <cstring>
#include <cstdlib>
#include "HPCCommon.hpp"
#include "HPCMath.hpp"
#include "HPCTimer.hpp"
namespace {
/// 入力を受けるコマンド
enum Command {
Command_Debug, ///< デバッガ起動
Command_OutputJson, ///< JSON 出力
Command_Exit, ///< 終わる
};
//------------------------------------------------------------------------------
/// 入力を受けます。
Command SelectInput()
{
while (true) {
HPC_PRINT("[d]ebug | output [j]son | [e]xit: ");
// 入力待ち
const char key = getchar();
if (key == 0x0a) {
return Command_Exit;
}
while (getchar() != 0x0a){} // 改行待ち
switch (key)
{
case 'd': return Command_Debug;
case 'j': return Command_OutputJson;
case 'e': return Command_Exit;
default:
break;
}
}
return Command_Exit;
}
/// 入力を受けるコマンド
enum DebugCommand {
DebugCommand_Next, ///< 次へ
DebugCommand_Prev, ///< 前へ
DebugCommand_Jump, ///< 指定番号のステージにジャンプ
DebugCommand_Show, ///< 再度
DebugCommand_Help, ///< ヘルプを表示
DebugCommand_Exit, ///< 終わる
DebugCommand_TERM
};
/// 入力を受けるコマンドのセット
struct DebugCommandSet
{
DebugCommand command;
int arg1;
int arg2;
DebugCommandSet()
: command(DebugCommand_TERM)
, arg1(0)
, arg2(0)
{
}
DebugCommandSet(DebugCommand aCmd, int aArg1, int aArg2)
: command(aCmd)
, arg1(aArg1)
, arg2(aArg2)
{
HPC_ENUM_ASSERT(DebugCommand, aCmd);
}
};
//------------------------------------------------------------------------------
/// 入力を受けます。
///
/// 入力は次の3要素から構成されます。
/// - コマンド
/// - 引数1
/// - 引数2
///
/// 引数1, 引数2 を省略した場合は、0 が設定されます。
DebugCommandSet SelectInputDebugger(int stage)
{
while (true) {
HPC_PRINT("[Stage: %d ('h' for help)]> ", stage);
// 入力待ち
static const int LineBufferSize = 20; // 20文字くらいあれば十分
char line[LineBufferSize];
{
char* ptr = std::fgets(line, LineBufferSize, stdin);
(void)ptr;
}
// コマンドを読む
const char* cmdStr = std::strtok(line, " \n\0");
if (!cmdStr) {
continue;
}
const char* arg1Str = std::strtok(0, " \n\0");
const char* arg2Str = std::strtok(0, " \n\0");
const int arg1 = arg1Str ? std::atoi(arg1Str) : 0;
const int arg2 = arg2Str ? std::atoi(arg2Str) : 0;
switch (cmdStr[0])
{
case 'n': return DebugCommandSet(DebugCommand_Next, arg1, arg2);
case 'p': return DebugCommandSet(DebugCommand_Prev, arg1, arg2);
case 'd': return DebugCommandSet(DebugCommand_Show, arg1, arg2);
case 'j': return DebugCommandSet(DebugCommand_Jump, arg1, arg2);
case 'h': return DebugCommandSet(DebugCommand_Help, arg1, arg2);
case 'e': return DebugCommandSet(DebugCommand_Exit, arg1, arg2);
default:
break;
}
}
return DebugCommandSet(DebugCommand_Next, 0, 0);
}
//------------------------------------------------------------------------------
/// デバッガのヘルプを表示します。
void ShowHelp()
{
HPC_PRINT(" n : Go to the next stage.\n");
HPC_PRINT(" p : Go to the prev stage.\n");
HPC_PRINT(" j [stage=0] : Go to the designated stage.\n");
HPC_PRINT(" d : Show the result of this stage.\n");
HPC_PRINT(" h : Show Help.\n");
HPC_PRINT(" e : Exit debugger.\n");
}
}
namespace hpc {
//------------------------------------------------------------------------------
/// @brief Simulation クラスのインスタンスを生成します。
Simulation::Simulation()
: mRandom()
, mGame(mRandom)
, mTimer(Parameter::GameTimeLimitSec)
{
}
//------------------------------------------------------------------------------
/// @brief ゲームを実行します。
void Simulation::run()
{
// 制限時間と制限ターン数
mTimer.start();
while (mGame.isValidStage()) {
mGame.startStage(mTimer.isInTime());
while (mGame.state() == StageState_Playing && mTimer.isInTime()) {
mGame.runTurn();
}
mGame.onStageDone();
}
}
//------------------------------------------------------------------------------
/// スコアを取得します。
int Simulation::score() const {
return mGame.record().score() / Parameter::RepeatCount;
}
//------------------------------------------------------------------------------
/// 表示用時間を取得します。
double Simulation::pastTimeSecForPrint()const
{
return mTimer.pastSecForPrint() / Parameter::RepeatCount;
}
//------------------------------------------------------------------------------
/// 結果を表示します。
void Simulation::outputResult()const
{
HPC_PRINT("Done.\n");
HPC_PRINT("%8s:%8d\n", "Score", score());
HPC_PRINT("%8s:%8.4f\n", "Time", pastTimeSecForPrint());
}
//------------------------------------------------------------------------------
/// @brief ゲームをデバッグ実行します。
void Simulation::debug()
{
// デバッグ前にデバッグをするかどうかを判断する。
// 入力待ち
switch (SelectInput()) {
case Command_Debug:
runDebugger();
break;
case Command_OutputJson:
// 時間切れの場合は、JSONが不完全になるので出力を行わない。
if (mTimer.isInTime()) {
mGame.record().dumpJson(true);
}
break;
case Command_Exit:
break;
default:
HPC_SHOULD_NOT_REACH_HERE();
break;
}
}
//------------------------------------------------------------------------------
/// JSON データを出力します。
void Simulation::outputJson(bool isCompressed)const
{
// 時間切れの場合は、JSONが不完全になるので出力を行わない。
if (mTimer.isInTime()) {
mGame.record().dumpJson(isCompressed);
}
}
//------------------------------------------------------------------------------
/// デバッグ実行を行います。
void Simulation::runDebugger()
{
int stage = 0;
bool doInput = true; // ステージ終了時に入力待ち するか。
do {
if (doInput) {
const DebugCommandSet commandSet = SelectInputDebugger(stage);
switch(commandSet.command) {
case DebugCommand_Next:
++stage;
break;
case DebugCommand_Prev:
stage = Math::Max(stage - 1, 0);
break;
case DebugCommand_Show:
mGame.record().dumpStage(stage);
break;
case DebugCommand_Jump:
stage = Math::LimitMinMax(commandSet.arg1, 0, Parameter::GameStageCount - 1);
break;
case DebugCommand_Help:
ShowHelp();
break;
case DebugCommand_Exit:
stage = Parameter::GameStageCount;
break;
default:
HPC_SHOULD_NOT_REACH_HERE();
break;
}
}
else {
++stage;
}
} while (stage < Parameter::GameStageCount);
}
}
//------------------------------------------------------------------------------
// EOF
| 29.204225
| 97
| 0.420666
|
iray-tno
|
84192b3897572770dbce377b3e7d0bec703cbff4
| 998
|
cpp
|
C++
|
tests/kernel/globalinit.cpp
|
v8786339/NyuziProcessor
|
34854d333d91dbf69cd5625505fb81024ec4f785
|
[
"Apache-2.0"
] | 1,388
|
2015-02-05T17:16:17.000Z
|
2022-03-31T07:17:08.000Z
|
tests/kernel/globalinit.cpp
|
czvf/NyuziProcessor
|
31f74e43a785fa66d244f1e9744ca0ca9b8a1fad
|
[
"Apache-2.0"
] | 176
|
2015-02-02T02:54:06.000Z
|
2022-02-01T06:00:21.000Z
|
tests/kernel/globalinit.cpp
|
czvf/NyuziProcessor
|
31f74e43a785fa66d244f1e9744ca0ca9b8a1fad
|
[
"Apache-2.0"
] | 271
|
2015-02-18T02:19:04.000Z
|
2022-03-28T13:30:25.000Z
|
//
// Copyright 2016 Jeff Bush
//
// 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 <stdio.h>
//
// Make sure global constructors/destructors are called properly by crt0
//
class Foo
{
public:
Foo()
{
printf("Foo::Foo\n");
}
~Foo()
{
printf("Foo::~Foo\n");
}
};
Foo f;
int main()
{
// CHECK: Foo::Foo
printf("main\n");
// CHECK: main
// CHECK: Foo::~Foo
return 0;
}
// CHECK: init process has exited, shutting down
| 20.791667
| 75
| 0.654309
|
v8786339
|
841a59e25202ef8d5756d6c2ab19834648bbcfb8
| 100,646
|
cpp
|
C++
|
game/tools/guieditor/source/guieditorgui.cpp
|
justinctlam/MarbleStrike
|
64fe36a5a4db2b299983b0e2556ab1cd8126259b
|
[
"MIT"
] | null | null | null |
game/tools/guieditor/source/guieditorgui.cpp
|
justinctlam/MarbleStrike
|
64fe36a5a4db2b299983b0e2556ab1cd8126259b
|
[
"MIT"
] | null | null | null |
game/tools/guieditor/source/guieditorgui.cpp
|
justinctlam/MarbleStrike
|
64fe36a5a4db2b299983b0e2556ab1cd8126259b
|
[
"MIT"
] | 2
|
2019-03-08T03:02:45.000Z
|
2019-05-14T08:41:26.000Z
|
///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version Sep 8 2010)
// http://www.wxformbuilder.org/
//
// PLEASE DO "NOT" EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#include "OGLCanvas.hpp"
#include "timelinewidget.hpp"
#include "guieditorgui.h"
///////////////////////////////////////////////////////////////////////////
GuiEditorGui::GuiEditorGui( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style )
{
this->SetSizeHints( wxSize( 1200,800 ), wxSize( -1,-1 ) );
mMenuBar = new wxMenuBar( 0 );
mMenuFile = new wxMenu();
wxMenuItem* mNewMenuItem;
mNewMenuItem = new wxMenuItem( mMenuFile, wxID_ANY, wxString( wxT("New") ) , wxEmptyString, wxITEM_NORMAL );
mMenuFile->Append( mNewMenuItem );
wxMenuItem* mOpenMenuItem;
mOpenMenuItem = new wxMenuItem( mMenuFile, wxID_ANY, wxString( wxT("Open") ) , wxEmptyString, wxITEM_NORMAL );
mMenuFile->Append( mOpenMenuItem );
wxMenuItem* m_separator1;
m_separator1 = mMenuFile->AppendSeparator();
wxMenuItem* mSaveAsMenuItem;
mSaveAsMenuItem = new wxMenuItem( mMenuFile, wxID_ANY, wxString( wxT("Save As") ) , wxEmptyString, wxITEM_NORMAL );
mMenuFile->Append( mSaveAsMenuItem );
wxMenuItem* mSaveMenuItem;
mSaveMenuItem = new wxMenuItem( mMenuFile, wxID_ANY, wxString( wxT("Save") ) , wxEmptyString, wxITEM_NORMAL );
mMenuFile->Append( mSaveMenuItem );
mMenuBar->Append( mMenuFile, wxT("File") );
mMenuEdit = new wxMenu();
wxMenuItem* m_menuItem23;
m_menuItem23 = new wxMenuItem( mMenuEdit, EDIT_UNDO, wxString( wxT("Undo") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEdit->Append( m_menuItem23 );
wxMenuItem* m_separator2;
m_separator2 = mMenuEdit->AppendSeparator();
wxMenuItem* mMenuItemEditCopy;
mMenuItemEditCopy = new wxMenuItem( mMenuEdit, EDIT_COPY, wxString( wxT("Copy") ) + wxT('\t') + wxT("CTRL+c"), wxEmptyString, wxITEM_NORMAL );
mMenuEdit->Append( mMenuItemEditCopy );
wxMenuItem* mMenuItemEditCut;
mMenuItemEditCut = new wxMenuItem( mMenuEdit, EDIT_CUT, wxString( wxT("Cut") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEdit->Append( mMenuItemEditCut );
wxMenuItem* mMenuItemEditPaste;
mMenuItemEditPaste = new wxMenuItem( mMenuEdit, EDIT_PASTE, wxString( wxT("Paste") ) + wxT('\t') + wxT("CTRL+v"), wxEmptyString, wxITEM_NORMAL );
mMenuEdit->Append( mMenuItemEditPaste );
wxMenuItem* m_separator7;
m_separator7 = mMenuEdit->AppendSeparator();
wxMenuItem* mMenuitemEditCopySize;
mMenuitemEditCopySize = new wxMenuItem( mMenuEdit, EDIT_COPY_SIZE_DATA, wxString( wxT("Copy Size") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEdit->Append( mMenuitemEditCopySize );
wxMenuItem* mMenuitemEditCopyPosition;
mMenuitemEditCopyPosition = new wxMenuItem( mMenuEdit, EDIT_COPY_POSITION_DATA, wxString( wxT("Copy Position") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEdit->Append( mMenuitemEditCopyPosition );
wxMenuItem* mMenuitemEditPasteSize;
mMenuitemEditPasteSize = new wxMenuItem( mMenuEdit, EDIT_PASTE_SIZE_DATA, wxString( wxT("Paste Size") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEdit->Append( mMenuitemEditPasteSize );
wxMenuItem* mMenuitemEditPastePosition;
mMenuitemEditPastePosition = new wxMenuItem( mMenuEdit, EDIT_PASTE_POSITION_DATA, wxString( wxT("Paste Position") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEdit->Append( mMenuitemEditPastePosition );
wxMenuItem* m_separator3;
m_separator3 = mMenuEdit->AppendSeparator();
wxMenuItem* mMenuItemEditDelete;
mMenuItemEditDelete = new wxMenuItem( mMenuEdit, EDIT_DELETE, wxString( wxT("Delete") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEdit->Append( mMenuItemEditDelete );
wxMenuItem* m_separator4;
m_separator4 = mMenuEdit->AppendSeparator();
wxMenuItem* mMenuItemEditShowHide;
mMenuItemEditShowHide = new wxMenuItem( mMenuEdit, EDIT_SHOW_HIDE, wxString( wxT("Show/Hide") ) + wxT('\t') + wxT("CTRL+h"), wxEmptyString, wxITEM_NORMAL );
mMenuEdit->Append( mMenuItemEditShowHide );
mMenuBar->Append( mMenuEdit, wxT("Edit") );
mMenuRenderer = new wxMenu();
wxMenuItem* mMenuItemOpenGL;
mMenuItemOpenGL = new wxMenuItem( mMenuRenderer, MENU_RENDERER_OPENGL, wxString( wxT("OpenGL") ) , wxEmptyString, wxITEM_RADIO );
mMenuRenderer->Append( mMenuItemOpenGL );
wxMenuItem* mMenuItemD3D;
mMenuItemD3D = new wxMenuItem( mMenuRenderer, MENU_RENDERER_D3D, wxString( wxT("Direct3D") ) , wxEmptyString, wxITEM_RADIO );
mMenuRenderer->Append( mMenuItemD3D );
mMenuBar->Append( mMenuRenderer, wxT("Renderer") );
mMenuEditor = new wxMenu();
mMenuScreenSize = new wxMenu();
wxMenuItem* mMenuItemPortrait320x480;
mMenuItemPortrait320x480 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_320_480, wxString( wxT("Portrait (320x480)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemPortrait320x480 );
mMenuItemPortrait320x480->Check( true );
wxMenuItem* mMenuItemLandscape480x320;
mMenuItemLandscape480x320 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_480_320, wxString( wxT("Landscape (480x320)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemLandscape480x320 );
wxMenuItem* mMenuItemPortrait640x960;
mMenuItemPortrait640x960 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_640_960, wxString( wxT("Portrait (640x960)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemPortrait640x960 );
mMenuItemPortrait640x960->Check( true );
wxMenuItem* mMenuItemLandscape960x640;
mMenuItemLandscape960x640 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_960_640, wxString( wxT("Landscape (9640x640)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemLandscape960x640 );
wxMenuItem* mMenuItemPortrait640x1136;
mMenuItemPortrait640x1136 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_640_1136, wxString( wxT("Portrait (640x1136)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemPortrait640x1136 );
mMenuItemPortrait640x1136->Check( true );
wxMenuItem* mMenuItemLandscape1136x640;
mMenuItemLandscape1136x640 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_1136_640, wxString( wxT("Landscape (1136x640)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemLandscape1136x640 );
wxMenuItem* mMenuItemPortrait720x1280;
mMenuItemPortrait720x1280 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_720_1280, wxString( wxT("Portrait (720x1280)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemPortrait720x1280 );
mMenuItemPortrait720x1280->Check( true );
wxMenuItem* mMenuItemLandscape1280x720;
mMenuItemLandscape1280x720 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_1280_720, wxString( wxT("Landscape (1280x720)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemLandscape1280x720 );
wxMenuItem* mMenuItemPortrait768x1024;
mMenuItemPortrait768x1024 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_768_1024, wxString( wxT("Portrait (768x1024)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemPortrait768x1024 );
mMenuItemPortrait768x1024->Check( true );
wxMenuItem* mMenuItemLandscape1024x768;
mMenuItemLandscape1024x768 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_1024_768, wxString( wxT("Landscape (1024x768)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemLandscape1024x768 );
wxMenuItem* mMenuItemPortrait1536x2048;
mMenuItemPortrait1536x2048 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_1536_2048, wxString( wxT("Portrait (1536x2048)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemPortrait1536x2048 );
mMenuItemPortrait1536x2048->Check( true );
wxMenuItem* mMenuItemLandscape2048x1536;
mMenuItemLandscape2048x1536 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_2048_1536, wxString( wxT("Landscape (2048x1536)") ) , wxEmptyString, wxITEM_RADIO );
mMenuScreenSize->Append( mMenuItemLandscape2048x1536 );
mMenuEditor->Append( -1, wxT("Screen Size"), mMenuScreenSize );
wxMenuItem* m_separator5;
m_separator5 = mMenuEditor->AppendSeparator();
wxMenuItem* mMenuInsertStatic;
mMenuInsertStatic = new wxMenuItem( mMenuEditor, EDITOR_MENU_INSERT_STATIC, wxString( wxT("Insert Static") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEditor->Append( mMenuInsertStatic );
wxMenuItem* mMenuInsertButton;
mMenuInsertButton = new wxMenuItem( mMenuEditor, EDITOR_MENU_INSERT_BUTTON, wxString( wxT("Insert Button") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEditor->Append( mMenuInsertButton );
wxMenuItem* mMenuInsertSlider;
mMenuInsertSlider = new wxMenuItem( mMenuEditor, EDITOR_MENU_INSERT_SLIDER, wxString( wxT("Insert Slider") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEditor->Append( mMenuInsertSlider );
wxMenuItem* mMenuInsertSprite;
mMenuInsertSprite = new wxMenuItem( mMenuEditor, EDITOR_MENU_INSERT_SPRITE, wxString( wxT("Insert Sprite") ) , wxEmptyString, wxITEM_NORMAL );
mMenuEditor->Append( mMenuInsertSprite );
wxMenuItem* m_separator6;
m_separator6 = mMenuEditor->AppendSeparator();
wxMenuItem* mMenuMoveBack;
mMenuMoveBack = new wxMenuItem( mMenuEditor, EDITOR_MENU_MOVE_BACK, wxString( wxT("Move Back") ) + wxT('\t') + wxT("CTRL+b"), wxEmptyString, wxITEM_NORMAL );
mMenuEditor->Append( mMenuMoveBack );
wxMenuItem* mMenuMoveFront;
mMenuMoveFront = new wxMenuItem( mMenuEditor, EDITOR_MENU_MOVE_FRONT, wxString( wxT("Move Front") ) + wxT('\t') + wxT("CTRL+f"), wxEmptyString, wxITEM_NORMAL );
mMenuEditor->Append( mMenuMoveFront );
mMenuBar->Append( mMenuEditor, wxT("Editor") );
mMenuAnimation = new wxMenu();
wxMenuItem* mMenuAnimationPlay;
mMenuAnimationPlay = new wxMenuItem( mMenuAnimation, EDITOR_MENU_ANIMATION_PLAY, wxString( wxT("Play") ) , wxEmptyString, wxITEM_NORMAL );
mMenuAnimation->Append( mMenuAnimationPlay );
wxMenuItem* mMenuAnimationStop;
mMenuAnimationStop = new wxMenuItem( mMenuAnimation, EDITOR_MENU_ANIMATION_STOP, wxString( wxT("Stop") ) , wxEmptyString, wxITEM_NORMAL );
mMenuAnimation->Append( mMenuAnimationStop );
wxMenuItem* mMenuAnimationAddKeyFrame;
mMenuAnimationAddKeyFrame = new wxMenuItem( mMenuAnimation, EDITOR_MENU_ANIMATION_ADD_KEYFRAME, wxString( wxT("Add Key Frame") ) , wxEmptyString, wxITEM_NORMAL );
mMenuAnimation->Append( mMenuAnimationAddKeyFrame );
wxMenuItem* mMenuAnimationDeleteKeyFrame;
mMenuAnimationDeleteKeyFrame = new wxMenuItem( mMenuAnimation, EDITOR_MENU_ANIMATION_DELETE_KEYFRAME, wxString( wxT("Delete Key Frame") ) , wxEmptyString, wxITEM_NORMAL );
mMenuAnimation->Append( mMenuAnimationDeleteKeyFrame );
mMenuBar->Append( mMenuAnimation, wxT("Animation") );
this->SetMenuBar( mMenuBar );
wxBoxSizer* bSizer18;
bSizer18 = new wxBoxSizer( wxVERTICAL );
m_panel7 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxFlexGridSizer* fgSizer38;
fgSizer38 = new wxFlexGridSizer( 1, 12, 0, 0 );
fgSizer38->SetFlexibleDirection( wxBOTH );
fgSizer38->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
wxString mRadioBoxTransformChoices[] = { wxT("X"), wxT("Y"), wxT("X-Y") };
int mRadioBoxTransformNChoices = sizeof( mRadioBoxTransformChoices ) / sizeof( wxString );
mRadioBoxTransform = new wxRadioBox( m_panel7, wxID_ANY, wxT("Transform"), wxDefaultPosition, wxDefaultSize, mRadioBoxTransformNChoices, mRadioBoxTransformChoices, 1, wxRA_SPECIFY_ROWS );
mRadioBoxTransform->SetSelection( 2 );
fgSizer38->Add( mRadioBoxTransform, 0, wxALL, 5 );
m_staticline1 = new wxStaticLine( m_panel7, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
fgSizer38->Add( m_staticline1, 0, wxEXPAND | wxALL, 5 );
m_button10 = new wxButton( m_panel7, LAYOUT_VERTICAL_CENTRE, wxT("Centre Vertical"), wxDefaultPosition, wxSize( -1,-1 ), 0 );
fgSizer38->Add( m_button10, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
m_button111 = new wxButton( m_panel7, LAYOUT_HORIZONTAL_CENTRE, wxT("Centre Horizontal"), wxDefaultPosition, wxSize( -1,-1 ), 0 );
fgSizer38->Add( m_button111, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
m_staticline2 = new wxStaticLine( m_panel7, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
fgSizer38->Add( m_staticline2, 0, wxEXPAND | wxALL, 5 );
m_staticText27 = new wxStaticText( m_panel7, wxID_ANY, wxT("Bounding Box Color:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText27->Wrap( -1 );
fgSizer38->Add( m_staticText27, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
mColorPickerBoundingBox = new wxColourPickerCtrl( m_panel7, COLOR_PICK_BOUNDING_BOX, *wxBLACK, wxDefaultPosition, wxSize( -1,-1 ), wxCLRP_DEFAULT_STYLE );
fgSizer38->Add( mColorPickerBoundingBox, 0, wxALIGN_CENTER_VERTICAL, 5 );
m_staticline3 = new wxStaticLine( m_panel7, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
fgSizer38->Add( m_staticline3, 0, wxEXPAND | wxALL, 5 );
m_staticText28 = new wxStaticText( m_panel7, wxID_ANY, wxT("Bounding Box Select Color:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText28->Wrap( -1 );
fgSizer38->Add( m_staticText28, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
mColorPickerBoundingBoxSelect = new wxColourPickerCtrl( m_panel7, COLOR_PICK_BOUNDING_BOX_SELECT, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE );
fgSizer38->Add( mColorPickerBoundingBoxSelect, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_staticText281 = new wxStaticText( m_panel7, wxID_ANY, wxT("Background Color:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText281->Wrap( -1 );
fgSizer38->Add( m_staticText281, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
mColorPickerBackground = new wxColourPickerCtrl( m_panel7, COLOR_PICK_BOUNDING_BOX_SELECT, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE );
fgSizer38->Add( mColorPickerBackground, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_panel7->SetSizer( fgSizer38 );
m_panel7->Layout();
fgSizer38->Fit( m_panel7 );
bSizer18->Add( m_panel7, 0, wxEXPAND, 5 );
wxFlexGridSizer* fgSizer11;
fgSizer11 = new wxFlexGridSizer( 1, 3, 0, 0 );
fgSizer11->AddGrowableCol( 0 );
fgSizer11->AddGrowableRow( 0 );
fgSizer11->SetFlexibleDirection( wxBOTH );
fgSizer11->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
wxBoxSizer* bSizer31;
bSizer31 = new wxBoxSizer( wxVERTICAL );
mNotebook = new wxNotebook( this, wxID_ANY, wxDefaultPosition, wxSize( -1,-1 ), 0 );
m_panel2 = new wxPanel( mNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer* bSizer1;
bSizer1 = new wxBoxSizer( wxVERTICAL );
mSceneGraphTree = new wxTreeCtrl( m_panel2, wxID_ANY, wxDefaultPosition, wxSize( -1,-1 ), wxTR_DEFAULT_STYLE|wxTR_HIDE_ROOT|wxTR_MULTIPLE );
mSceneGraphTree->SetMinSize( wxSize( 250,800 ) );
bSizer1->Add( mSceneGraphTree, 1, wxALL|wxEXPAND, 5 );
m_panel2->SetSizer( bSizer1 );
m_panel2->Layout();
bSizer1->Fit( m_panel2 );
mNotebook->AddPage( m_panel2, wxT("Scene Graph"), false );
bSizer31->Add( mNotebook, 0, 0, 10 );
fgSizer11->Add( bSizer31, 0, 0, 5 );
wxBoxSizer* bSizer7;
bSizer7 = new wxBoxSizer( wxVERTICAL );
mButtonProperties = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL );
mButtonProperties->SetScrollRate( 5, 5 );
mButtonProperties->Hide();
mButtonProperties->SetMinSize( wxSize( 250,800 ) );
wxFlexGridSizer* fgSizer19;
fgSizer19 = new wxFlexGridSizer( 2, 1, 0, 0 );
fgSizer19->SetFlexibleDirection( wxBOTH );
fgSizer19->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
wxStaticBoxSizer* sbSizer7;
sbSizer7 = new wxStaticBoxSizer( new wxStaticBox( mButtonProperties, wxID_ANY, wxEmptyString ), wxVERTICAL );
wxGridSizer* gSizer1;
gSizer1 = new wxGridSizer( 8, 2, 0, 0 );
m_staticText38 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText38->Wrap( -1 );
gSizer1->Add( m_staticText38, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextButtonName = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer1->Add( mTextButtonName, 0, wxALL, 5 );
m_staticText391 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Width:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText391->Wrap( -1 );
gSizer1->Add( m_staticText391, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextButtonWidth = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_WIDTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer1->Add( mTextButtonWidth, 0, wxALL, 5 );
m_staticText3911 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Height:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText3911->Wrap( -1 );
gSizer1->Add( m_staticText3911, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextButtonHeight = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer1->Add( mTextButtonHeight, 0, wxALL, 5 );
m_staticText411 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("x:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText411->Wrap( -1 );
gSizer1->Add( m_staticText411, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextButtonX = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_X, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer1->Add( mTextButtonX, 0, wxALL, 5 );
m_staticText4111 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("y:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText4111->Wrap( -1 );
gSizer1->Add( m_staticText4111, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextButtonY = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_Y, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer1->Add( mTextButtonY, 0, wxALL, 5 );
m_staticText341 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Text:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText341->Wrap( -1 );
gSizer1->Add( m_staticText341, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextButtonText = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_TEXT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer1->Add( mTextButtonText, 0, wxALL, 5 );
m_staticText35 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Colour:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText35->Wrap( -1 );
gSizer1->Add( m_staticText35, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mColorPickerButton = new wxColourPickerCtrl( mButtonProperties, COLOR_PICKER_BUTTON, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE );
gSizer1->Add( mColorPickerButton, 0, wxALL|wxEXPAND, 5 );
m_staticText57 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Transparency:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText57->Wrap( -1 );
gSizer1->Add( m_staticText57, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mSliderButtonAlpha = new wxSlider( mButtonProperties, SLIDER_BUTTON_ALPHA, 255, 0, 255, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL );
gSizer1->Add( mSliderButtonAlpha, 0, wxALL, 5 );
sbSizer7->Add( gSizer1, 0, 0, 5 );
fgSizer19->Add( sbSizer7, 0, wxALL, 5 );
wxStaticBoxSizer* sbSizer61;
sbSizer61 = new wxStaticBoxSizer( new wxStaticBox( mButtonProperties, wxID_ANY, wxEmptyString ), wxVERTICAL );
m_staticText36 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Texture:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText36->Wrap( -1 );
sbSizer61->Add( m_staticText36, 0, wxALL, 5 );
mFilePickButtonTexture = new wxFilePickerCtrl( mButtonProperties, FILE_PICK_BUTTON_TEXTURE, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxSize( -1,-1 ), wxFLP_DEFAULT_STYLE );
sbSizer61->Add( mFilePickButtonTexture, 0, wxALL, 5 );
wxFlexGridSizer* fgSizer1221;
fgSizer1221 = new wxFlexGridSizer( 2, 2, 0, 0 );
fgSizer1221->SetFlexibleDirection( wxBOTH );
fgSizer1221->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
mButtonButtonClearTexture = new wxButton( mButtonProperties, BUTTON_BUTTON_CLEAR_TEXTURE, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer1221->Add( mButtonButtonClearTexture, 0, wxALL, 5 );
mButtonButtonCreateUV = new wxButton( mButtonProperties, BUTTON_BUTTON_CREATE_UV, wxT("Create UV"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer1221->Add( mButtonButtonCreateUV, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
sbSizer61->Add( fgSizer1221, 0, 0, 5 );
mOnPressTextureLabel = new wxStaticText( mButtonProperties, wxID_ANY, wxT("OnPress Texture:"), wxDefaultPosition, wxDefaultSize, 0 );
mOnPressTextureLabel->Wrap( -1 );
sbSizer61->Add( mOnPressTextureLabel, 0, wxALL, 5 );
mFilePickButtonOnPressTexture = new wxFilePickerCtrl( mButtonProperties, FILE_PICK_BUTTON_ONPRESS_TEXTURE, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxDefaultSize, wxFLP_DEFAULT_STYLE );
sbSizer61->Add( mFilePickButtonOnPressTexture, 0, wxALL, 5 );
wxFlexGridSizer* fgSizer12213;
fgSizer12213 = new wxFlexGridSizer( 2, 2, 0, 0 );
fgSizer12213->SetFlexibleDirection( wxBOTH );
fgSizer12213->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
mButtonButtonClearOnPressTexture = new wxButton( mButtonProperties, BUTTON_BUTTON_ONPRESS_CLEAR_TEXTURE, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer12213->Add( mButtonButtonClearOnPressTexture, 0, wxALL, 5 );
mButtonButtonOnPressCreateUV = new wxButton( mButtonProperties, BUTTON_BUTTON_ONPRESS_CREATE_UV, wxT("Create UV"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer12213->Add( mButtonButtonOnPressCreateUV, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
sbSizer61->Add( fgSizer12213, 1, wxEXPAND, 5 );
m_staticText37 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Font:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText37->Wrap( -1 );
sbSizer61->Add( m_staticText37, 0, wxALL, 5 );
mFilePickButtonFont = new wxFilePickerCtrl( mButtonProperties, FILE_PICK_BUTTON_FONT, wxEmptyString, wxT("Select a file"), wxT("*.xml"), wxDefaultPosition, wxDefaultSize, wxFLP_DEFAULT_STYLE );
sbSizer61->Add( mFilePickButtonFont, 0, wxALL, 5 );
wxGridSizer* gSizer51;
gSizer51 = new wxGridSizer( 2, 2, 0, 0 );
m_staticText342 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Font Colour:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText342->Wrap( -1 );
gSizer51->Add( m_staticText342, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mColorPickerButtonFont = new wxColourPickerCtrl( mButtonProperties, COLOR_PICKER_BUTTON_FONT, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE );
gSizer51->Add( mColorPickerButtonFont, 0, wxALL|wxEXPAND, 5 );
m_staticText3521 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Font Size:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText3521->Wrap( -1 );
gSizer51->Add( m_staticText3521, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextButtonFontSize = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_FONT_SIZE, wxEmptyString, wxDefaultPosition, wxSize( 50,-1 ), wxTE_PROCESS_ENTER );
gSizer51->Add( mTextButtonFontSize, 0, wxALL, 5 );
sbSizer61->Add( gSizer51, 0, wxEXPAND, 5 );
wxGridSizer* gSizer81;
gSizer81 = new wxGridSizer( 2, 2, 0, 0 );
wxString mChoiceButtonFontHorizontalChoices[] = { wxT("Left"), wxT("Right"), wxT("Centre") };
int mChoiceButtonFontHorizontalNChoices = sizeof( mChoiceButtonFontHorizontalChoices ) / sizeof( wxString );
mChoiceButtonFontHorizontal = new wxChoice( mButtonProperties, CHOICE_BUTTON_FONT_HORIZONTAL, wxDefaultPosition, wxDefaultSize, mChoiceButtonFontHorizontalNChoices, mChoiceButtonFontHorizontalChoices, 0 );
mChoiceButtonFontHorizontal->SetSelection( 0 );
gSizer81->Add( mChoiceButtonFontHorizontal, 0, wxALL, 5 );
wxString mChoiceButtonFontVerticalChoices[] = { wxT("Top"), wxT("Bottom"), wxT("Centre") };
int mChoiceButtonFontVerticalNChoices = sizeof( mChoiceButtonFontVerticalChoices ) / sizeof( wxString );
mChoiceButtonFontVertical = new wxChoice( mButtonProperties, CHOICE_BUTTON_FONT_VERTICAL, wxDefaultPosition, wxDefaultSize, mChoiceButtonFontVerticalNChoices, mChoiceButtonFontVerticalChoices, 0 );
mChoiceButtonFontVertical->SetSelection( 0 );
gSizer81->Add( mChoiceButtonFontVertical, 0, wxALL, 5 );
sbSizer61->Add( gSizer81, 0, 0, 5 );
fgSizer19->Add( sbSizer61, 0, wxEXPAND|wxALL, 5 );
mButtonProperties->SetSizer( fgSizer19 );
mButtonProperties->Layout();
fgSizer19->Fit( mButtonProperties );
bSizer7->Add( mButtonProperties, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 );
mClearPanel = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL );
mClearPanel->SetScrollRate( 5, 5 );
mClearPanel->Hide();
mClearPanel->SetMinSize( wxSize( 250,800 ) );
bSizer7->Add( mClearPanel, 1, wxEXPAND, 5 );
mSliderProperties = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL );
mSliderProperties->SetScrollRate( 5, 5 );
mSliderProperties->Hide();
mSliderProperties->SetMinSize( wxSize( 250,800 ) );
wxFlexGridSizer* fgSizer192;
fgSizer192 = new wxFlexGridSizer( 2, 1, 0, 0 );
fgSizer192->SetFlexibleDirection( wxBOTH );
fgSizer192->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
wxStaticBoxSizer* sbSizer72;
sbSizer72 = new wxStaticBoxSizer( new wxStaticBox( mSliderProperties, wxID_ANY, wxEmptyString ), wxVERTICAL );
wxGridSizer* gSizer12;
gSizer12 = new wxGridSizer( 8, 2, 0, 0 );
m_staticText381 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText381->Wrap( -1 );
gSizer12->Add( m_staticText381, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextSliderName = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer12->Add( mTextSliderName, 0, wxALL, 5 );
m_staticText3913 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Width:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText3913->Wrap( -1 );
gSizer12->Add( m_staticText3913, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextSliderWidth = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_WIDTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer12->Add( mTextSliderWidth, 0, wxALL, 5 );
m_staticText39112 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Height:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText39112->Wrap( -1 );
gSizer12->Add( m_staticText39112, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextSliderHeight = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer12->Add( mTextSliderHeight, 0, wxALL, 5 );
m_staticText4113 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("x:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText4113->Wrap( -1 );
gSizer12->Add( m_staticText4113, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextSliderX = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_X, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer12->Add( mTextSliderX, 0, wxALL, 5 );
m_staticText41112 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("y:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText41112->Wrap( -1 );
gSizer12->Add( m_staticText41112, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextSliderY = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_Y, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer12->Add( mTextSliderY, 0, wxALL, 5 );
m_staticText81 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Min:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText81->Wrap( -1 );
gSizer12->Add( m_staticText81, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextSliderMin = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_MIN, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer12->Add( mTextSliderMin, 0, wxALL, 5 );
m_staticText82 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Max:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText82->Wrap( -1 );
gSizer12->Add( m_staticText82, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextSliderMax = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_MAX, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer12->Add( mTextSliderMax, 0, wxALL, 5 );
m_staticText83 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Default:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText83->Wrap( -1 );
gSizer12->Add( m_staticText83, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextSliderDefault = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_DEFAULT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer12->Add( mTextSliderDefault, 0, wxALL, 5 );
sbSizer72->Add( gSizer12, 0, 0, 5 );
fgSizer192->Add( sbSizer72, 0, wxALL, 5 );
wxBoxSizer* bSizer181;
bSizer181 = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer* sbSizer612;
sbSizer612 = new wxStaticBoxSizer( new wxStaticBox( mSliderProperties, wxID_ANY, wxEmptyString ), wxVERTICAL );
m_staticText362 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Texture Bar:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText362->Wrap( -1 );
sbSizer612->Add( m_staticText362, 0, wxALL, 5 );
mFilePickSliderTextureBar = new wxFilePickerCtrl( mSliderProperties, FILE_PICK_SLIDER_TEXTURE_BAR, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxSize( -1,-1 ), wxFLP_DEFAULT_STYLE );
sbSizer612->Add( mFilePickSliderTextureBar, 0, wxALL, 5 );
wxFlexGridSizer* fgSizer12212;
fgSizer12212 = new wxFlexGridSizer( 2, 2, 0, 0 );
fgSizer12212->SetFlexibleDirection( wxBOTH );
fgSizer12212->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
mButtonSliderClearTextureBar = new wxButton( mSliderProperties, BUTTON_SLIDER_CLEAR_TEXTURE_BAR, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer12212->Add( mButtonSliderClearTextureBar, 0, wxALL, 5 );
mButtonSliderCreateUVBar = new wxButton( mSliderProperties, BUTTON_SLIDER_CREATE_UV_BAR, wxT("Create UV"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer12212->Add( mButtonSliderCreateUVBar, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
sbSizer612->Add( fgSizer12212, 0, 0, 5 );
m_staticText3621 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Texture Button:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText3621->Wrap( -1 );
sbSizer612->Add( m_staticText3621, 0, wxALL, 5 );
mFilePickSliderTextureButton = new wxFilePickerCtrl( mSliderProperties, FILE_PICK_SLIDER_TEXTURE_BUTTON, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxSize( -1,-1 ), wxFLP_DEFAULT_STYLE );
sbSizer612->Add( mFilePickSliderTextureButton, 0, wxALL, 5 );
wxFlexGridSizer* fgSizer122121;
fgSizer122121 = new wxFlexGridSizer( 2, 2, 0, 0 );
fgSizer122121->SetFlexibleDirection( wxBOTH );
fgSizer122121->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
mButtonSliderClearTextureButton = new wxButton( mSliderProperties, BUTTON_SLIDER_CLEAR_TEXTURE_BUTTON, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer122121->Add( mButtonSliderClearTextureButton, 0, wxALL, 5 );
mButtonSliderCreateUVButton = new wxButton( mSliderProperties, BUTTON_SLIDER_CREATE_UV_BUTTON, wxT("Create UV"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer122121->Add( mButtonSliderCreateUVButton, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
sbSizer612->Add( fgSizer122121, 1, wxEXPAND, 5 );
bSizer181->Add( sbSizer612, 0, wxEXPAND|wxALL, 5 );
fgSizer192->Add( bSizer181, 0, 0, 5 );
mSliderProperties->SetSizer( fgSizer192 );
mSliderProperties->Layout();
fgSizer192->Fit( mSliderProperties );
bSizer7->Add( mSliderProperties, 1, wxEXPAND, 5 );
mSpriteProperties = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL );
mSpriteProperties->SetScrollRate( 5, 5 );
mSpriteProperties->Hide();
mSpriteProperties->SetMinSize( wxSize( 250,800 ) );
wxFlexGridSizer* fgSizer1911;
fgSizer1911 = new wxFlexGridSizer( 2, 1, 0, 0 );
fgSizer1911->SetFlexibleDirection( wxBOTH );
fgSizer1911->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
wxStaticBoxSizer* sbSizer711;
sbSizer711 = new wxStaticBoxSizer( new wxStaticBox( mSpriteProperties, wxID_ANY, wxEmptyString ), wxVERTICAL );
wxGridSizer* gSizer111;
gSizer111 = new wxGridSizer( 8, 2, 0, 0 );
m_staticText3831 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText3831->Wrap( -1 );
gSizer111->Add( m_staticText3831, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextSpriteName = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer111->Add( mTextSpriteName, 0, wxALL, 5 );
m_staticText39121 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Width:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText39121->Wrap( -1 );
gSizer111->Add( m_staticText39121, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextSpriteWidth = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_WIDTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer111->Add( mTextSpriteWidth, 0, wxALL, 5 );
m_staticText391111 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Height:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText391111->Wrap( -1 );
gSizer111->Add( m_staticText391111, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextSpriteHeight = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer111->Add( mTextSpriteHeight, 0, wxALL, 5 );
m_staticText41121 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("x:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText41121->Wrap( -1 );
gSizer111->Add( m_staticText41121, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextSpriteX = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_X, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer111->Add( mTextSpriteX, 0, wxALL, 5 );
m_staticText411111 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("y:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText411111->Wrap( -1 );
gSizer111->Add( m_staticText411111, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextSpriteY = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_Y, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer111->Add( mTextSpriteY, 0, wxALL, 5 );
m_staticText3511 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Colour:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText3511->Wrap( -1 );
gSizer111->Add( m_staticText3511, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mColorPickerSprite = new wxColourPickerCtrl( mSpriteProperties, COLOR_PICKER_SPRITE, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE );
gSizer111->Add( mColorPickerSprite, 0, wxALL|wxEXPAND, 5 );
m_staticText5712 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Transparency:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText5712->Wrap( -1 );
gSizer111->Add( m_staticText5712, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mSliderSpriteAlpha = new wxSlider( mSpriteProperties, SLIDER_SPRITE_ALPHA, 255, 0, 255, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL );
gSizer111->Add( mSliderSpriteAlpha, 0, wxALL, 5 );
sbSizer711->Add( gSizer111, 0, 0, 5 );
fgSizer1911->Add( sbSizer711, 0, wxALL, 5 );
wxStaticBoxSizer* sbSizer6111;
sbSizer6111 = new wxStaticBoxSizer( new wxStaticBox( mSpriteProperties, wxID_ANY, wxEmptyString ), wxVERTICAL );
m_staticText3611 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Sprite Texture:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText3611->Wrap( -1 );
sbSizer6111->Add( m_staticText3611, 0, wxALL, 5 );
mFilePickSpriteTextureFile = new wxFilePickerCtrl( mSpriteProperties, FILE_PICK_SPRITE_TEXTURE_FILE, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxSize( -1,-1 ), wxFLP_DEFAULT_STYLE );
sbSizer6111->Add( mFilePickSpriteTextureFile, 0, wxALL, 5 );
wxFlexGridSizer* fgSizer122111;
fgSizer122111 = new wxFlexGridSizer( 2, 2, 0, 0 );
fgSizer122111->SetFlexibleDirection( wxBOTH );
fgSizer122111->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
mButtonSpriteClearTexture = new wxButton( mSpriteProperties, BUTTON_SPRITE_CLEAR_TEXTURE, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer122111->Add( mButtonSpriteClearTexture, 0, wxALL, 5 );
sbSizer6111->Add( fgSizer122111, 0, 0, 5 );
wxFlexGridSizer* fgSizer17;
fgSizer17 = new wxFlexGridSizer( 1, 2, 0, 0 );
fgSizer17->SetFlexibleDirection( wxBOTH );
fgSizer17->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
m_staticText38311 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Frames Per Second:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText38311->Wrap( -1 );
fgSizer17->Add( m_staticText38311, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextSpriteFPS = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_FPS, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
fgSizer17->Add( mTextSpriteFPS, 0, wxALL, 5 );
sbSizer6111->Add( fgSizer17, 1, wxEXPAND, 5 );
fgSizer1911->Add( sbSizer6111, 0, wxALL, 5 );
mSpriteProperties->SetSizer( fgSizer1911 );
mSpriteProperties->Layout();
fgSizer1911->Fit( mSpriteProperties );
bSizer7->Add( mSpriteProperties, 1, wxEXPAND, 5 );
mStaticProperties = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL );
mStaticProperties->SetScrollRate( 5, 5 );
mStaticProperties->SetMinSize( wxSize( 250,800 ) );
wxFlexGridSizer* fgSizer191;
fgSizer191 = new wxFlexGridSizer( 3, 1, 0, 0 );
fgSizer191->SetFlexibleDirection( wxBOTH );
fgSizer191->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
wxStaticBoxSizer* sbSizer71;
sbSizer71 = new wxStaticBoxSizer( new wxStaticBox( mStaticProperties, wxID_ANY, wxEmptyString ), wxVERTICAL );
wxGridSizer* gSizer11;
gSizer11 = new wxGridSizer( 7, 2, 0, 0 );
m_staticText383 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText383->Wrap( -1 );
gSizer11->Add( m_staticText383, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextStaticName = new wxTextCtrl( mStaticProperties, TEXT_STATIC_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer11->Add( mTextStaticName, 0, wxALL, 5 );
m_staticText3912 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Width:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText3912->Wrap( -1 );
gSizer11->Add( m_staticText3912, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextStaticWidth = new wxTextCtrl( mStaticProperties, TEXT_STATIC_WIDTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer11->Add( mTextStaticWidth, 0, wxALL, 5 );
m_staticText39111 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Height:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText39111->Wrap( -1 );
gSizer11->Add( m_staticText39111, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextStaticHeight = new wxTextCtrl( mStaticProperties, TEXT_STATIC_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer11->Add( mTextStaticHeight, 0, wxALL, 5 );
m_staticText4112 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("x:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText4112->Wrap( -1 );
gSizer11->Add( m_staticText4112, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextStaticX = new wxTextCtrl( mStaticProperties, TEXT_STATIC_X, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer11->Add( mTextStaticX, 0, wxALL, 5 );
m_staticText41111 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("y:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText41111->Wrap( -1 );
gSizer11->Add( m_staticText41111, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextStaticY = new wxTextCtrl( mStaticProperties, TEXT_STATIC_Y, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
gSizer11->Add( mTextStaticY, 0, wxALL, 5 );
m_staticText351 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Colour:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText351->Wrap( -1 );
gSizer11->Add( m_staticText351, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mColorPickerStatic = new wxColourPickerCtrl( mStaticProperties, COLOR_PICKER_STATIC, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE );
gSizer11->Add( mColorPickerStatic, 0, wxALL|wxEXPAND, 5 );
m_staticText571 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Transparency:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText571->Wrap( -1 );
gSizer11->Add( m_staticText571, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mSliderStaticAlpha = new wxSlider( mStaticProperties, SLIDER_STATIC_ALPHA, 255, 0, 255, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL );
gSizer11->Add( mSliderStaticAlpha, 0, wxALL, 5 );
sbSizer71->Add( gSizer11, 0, 0, 5 );
fgSizer191->Add( sbSizer71, 0, wxALL, 5 );
wxStaticBoxSizer* sbSizer9;
sbSizer9 = new wxStaticBoxSizer( new wxStaticBox( mStaticProperties, wxID_ANY, wxEmptyString ), wxVERTICAL );
m_staticText3411 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Text:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText3411->Wrap( -1 );
sbSizer9->Add( m_staticText3411, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
mTextStaticText = new wxTextCtrl( mStaticProperties, TEXT_STATIC_TEXT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_PROCESS_ENTER );
mTextStaticText->SetMinSize( wxSize( -1,70 ) );
sbSizer9->Add( mTextStaticText, 1, wxALL|wxEXPAND, 5 );
fgSizer191->Add( sbSizer9, 1, wxEXPAND, 5 );
wxStaticBoxSizer* sbSizer611;
sbSizer611 = new wxStaticBoxSizer( new wxStaticBox( mStaticProperties, wxID_ANY, wxEmptyString ), wxVERTICAL );
m_staticText361 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Texture:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText361->Wrap( -1 );
sbSizer611->Add( m_staticText361, 0, wxALL, 5 );
mFilePickStaticTexture = new wxFilePickerCtrl( mStaticProperties, FILE_PICK_STATIC_TEXTURE, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxSize( -1,-1 ), wxFLP_DEFAULT_STYLE );
sbSizer611->Add( mFilePickStaticTexture, 0, wxALL, 5 );
wxFlexGridSizer* fgSizer12211;
fgSizer12211 = new wxFlexGridSizer( 2, 2, 0, 0 );
fgSizer12211->SetFlexibleDirection( wxBOTH );
fgSizer12211->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
mButtonStaticClearTexture = new wxButton( mStaticProperties, BUTTON_STATIC_CLEAR_TEXTURE, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer12211->Add( mButtonStaticClearTexture, 0, wxALL, 5 );
mButtonStaticCreateUV = new wxButton( mStaticProperties, BUTTON_STATIC_CREATE_UV, wxT("Create UV"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer12211->Add( mButtonStaticCreateUV, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 );
sbSizer611->Add( fgSizer12211, 0, 0, 5 );
m_staticText371 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Font:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText371->Wrap( -1 );
sbSizer611->Add( m_staticText371, 0, wxALL, 5 );
mFilePickStaticFont = new wxFilePickerCtrl( mStaticProperties, FILE_PICK_STATIC_FONT, wxEmptyString, wxT("Select a file"), wxT("*.xml"), wxDefaultPosition, wxDefaultSize, wxFLP_DEFAULT_STYLE );
sbSizer611->Add( mFilePickStaticFont, 0, wxALL, 5 );
wxGridSizer* gSizer5;
gSizer5 = new wxGridSizer( 3, 2, 0, 0 );
m_staticText34 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Font Colour:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText34->Wrap( -1 );
gSizer5->Add( m_staticText34, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mColorPickerStaticFont = new wxColourPickerCtrl( mStaticProperties, COLOR_PICKER_STATIC_FONT, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE );
gSizer5->Add( mColorPickerStaticFont, 0, wxALL|wxEXPAND, 5 );
m_staticText5711 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Transparency:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText5711->Wrap( -1 );
gSizer5->Add( m_staticText5711, 0, wxALL|wxALIGN_RIGHT, 5 );
mSliderStaticAlphaFont = new wxSlider( mStaticProperties, SLIDER_STATIC_ALPHA_FONT, 255, 0, 255, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL );
gSizer5->Add( mSliderStaticAlphaFont, 0, wxALL, 5 );
m_staticText352 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Font Size:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText352->Wrap( -1 );
gSizer5->Add( m_staticText352, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
mTextStaticFontSize = new wxTextCtrl( mStaticProperties, TEXT_STATIC_FONT_SIZE, wxEmptyString, wxDefaultPosition, wxSize( 50,-1 ), wxTE_PROCESS_ENTER );
gSizer5->Add( mTextStaticFontSize, 0, wxALL, 5 );
sbSizer611->Add( gSizer5, 1, wxEXPAND, 5 );
wxGridSizer* gSizer8;
gSizer8 = new wxGridSizer( 2, 2, 0, 0 );
wxString mChoiceStaticFontHorizontalChoices[] = { wxT("Left"), wxT("Right"), wxT("Centre") };
int mChoiceStaticFontHorizontalNChoices = sizeof( mChoiceStaticFontHorizontalChoices ) / sizeof( wxString );
mChoiceStaticFontHorizontal = new wxChoice( mStaticProperties, CHOICE_STATIC_FONT_HORIZONTAL, wxDefaultPosition, wxDefaultSize, mChoiceStaticFontHorizontalNChoices, mChoiceStaticFontHorizontalChoices, 0 );
mChoiceStaticFontHorizontal->SetSelection( 0 );
gSizer8->Add( mChoiceStaticFontHorizontal, 0, wxALL, 5 );
wxString mChoiceStaticFontVerticalChoices[] = { wxT("Bottom"), wxT("Top"), wxT("Centre") };
int mChoiceStaticFontVerticalNChoices = sizeof( mChoiceStaticFontVerticalChoices ) / sizeof( wxString );
mChoiceStaticFontVertical = new wxChoice( mStaticProperties, CHOICE_STATIC_FONT_VERTICAL, wxDefaultPosition, wxDefaultSize, mChoiceStaticFontVerticalNChoices, mChoiceStaticFontVerticalChoices, 0 );
mChoiceStaticFontVertical->SetSelection( 1 );
gSizer8->Add( mChoiceStaticFontVertical, 0, wxALL, 5 );
sbSizer611->Add( gSizer8, 0, 0, 5 );
fgSizer191->Add( sbSizer611, 0, wxALL, 5 );
mStaticProperties->SetSizer( fgSizer191 );
mStaticProperties->Layout();
fgSizer191->Fit( mStaticProperties );
bSizer7->Add( mStaticProperties, 1, wxEXPAND, 5 );
fgSizer11->Add( bSizer7, 1, wxEXPAND, 5 );
wxBoxSizer* mRightSideBoxSizer;
mRightSideBoxSizer = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* bSizer10;
bSizer10 = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* mAnimationBoxSizer;
mAnimationBoxSizer = new wxBoxSizer( wxVERTICAL );
mAnimationControlsPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxFlexGridSizer* fgSizer15;
fgSizer15 = new wxFlexGridSizer( 1, 10, 0, 0 );
fgSizer15->SetFlexibleDirection( wxBOTH );
fgSizer15->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
m_staticText191 = new wxStaticText( mAnimationControlsPanel, wxID_ANY, wxT("Frame:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText191->Wrap( -1 );
fgSizer15->Add( m_staticText191, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
mTextAnimationFrame = new wxTextCtrl( mAnimationControlsPanel, wxID_ANY, wxT("0"), wxDefaultPosition, wxSize( 50,-1 ), wxTE_PROCESS_ENTER|wxTE_RIGHT );
fgSizer15->Add( mTextAnimationFrame, 0, wxALL, 5 );
m_button9 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_BACK_KEYFRAME, wxT("<"), wxDefaultPosition, wxSize( 20,-1 ), 0 );
fgSizer15->Add( m_button9, 0, wxALL, 5 );
m_button101 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_FORWARD_KEYFRAME, wxT(">"), wxDefaultPosition, wxSize( 20,-1 ), 0 );
fgSizer15->Add( m_button101, 0, wxALL, 5 );
m_button5 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_ADD_KEYFRAME, wxT("+"), wxDefaultPosition, wxSize( 30,-1 ), 0 );
fgSizer15->Add( m_button5, 0, wxALL, 5 );
m_button6 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_DELETE_KEYFRAME, wxT("-"), wxDefaultPosition, wxSize( 30,-1 ), 0 );
fgSizer15->Add( m_button6, 0, wxALL, 5 );
m_button7 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_PLAY, wxT("Play"), wxDefaultPosition, wxSize( 50,-1 ), 0 );
fgSizer15->Add( m_button7, 0, wxALL, 5 );
m_button8 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_STOP, wxT("Stop"), wxDefaultPosition, wxSize( 50,-1 ), 0 );
fgSizer15->Add( m_button8, 0, wxALL, 5 );
mZoomIn = new wxButton( mAnimationControlsPanel, BUTTON_ID_ZOOM_IN, wxT("Zoom (+)"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer15->Add( mZoomIn, 0, wxALL, 5 );
mZoomOut = new wxButton( mAnimationControlsPanel, BUTTON_ID_ZOOM_OUT, wxT("Zoom (-)"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer15->Add( mZoomOut, 0, wxALL, 5 );
mAnimationControlsPanel->SetSizer( fgSizer15 );
mAnimationControlsPanel->Layout();
fgSizer15->Fit( mAnimationControlsPanel );
mAnimationBoxSizer->Add( mAnimationControlsPanel, 0, wxEXPAND, 5 );
m_panel6 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxFlexGridSizer* fgSizer12;
fgSizer12 = new wxFlexGridSizer( 1, 5, 0, 0 );
fgSizer12->SetFlexibleDirection( wxBOTH );
fgSizer12->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
mAddAnimationSequenceButton = new wxButton( m_panel6, BUTTON_ADD_ANIMATION_SEQUENCE, wxT("+"), wxDefaultPosition, wxSize( 20,-1 ), 0 );
fgSizer12->Add( mAddAnimationSequenceButton, 0, wxALL, 5 );
mDeleteAnimationSequenceButton = new wxButton( m_panel6, BUTTON_DELETE_ANIMATION_SEQUENCE, wxT("-"), wxDefaultPosition, wxSize( 20,-1 ), 0 );
fgSizer12->Add( mDeleteAnimationSequenceButton, 0, wxALL, 5 );
mTextAnimationSequenceName = new wxTextCtrl( m_panel6, TEXT_ANIMATION_SEQUENCE_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
fgSizer12->Add( mTextAnimationSequenceName, 0, wxALL, 5 );
mAnimationSelectionLabel = new wxStaticText( m_panel6, wxID_ANY, wxT("Animations:"), wxDefaultPosition, wxDefaultSize, 0 );
mAnimationSelectionLabel->Wrap( -1 );
fgSizer12->Add( mAnimationSelectionLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
wxArrayString mAnimationsChoiceChoices;
mAnimationsChoice = new wxChoice( m_panel6, CHOICE_ANIMATION_SELECTION, wxDefaultPosition, wxDefaultSize, mAnimationsChoiceChoices, 0 );
mAnimationsChoice->SetSelection( 0 );
fgSizer12->Add( mAnimationsChoice, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 );
m_panel6->SetSizer( fgSizer12 );
m_panel6->Layout();
fgSizer12->Fit( m_panel6 );
mAnimationBoxSizer->Add( m_panel6, 1, wxEXPAND, 5 );
mTimeLineControl = new TimeLineWidget( this, wxID_ANY, wxDefaultPosition, wxSize( -1,30 ), wxTAB_TRAVERSAL );
mAnimationBoxSizer->Add( mTimeLineControl, 0, wxALL|wxEXPAND, 1 );
bSizer10->Add( mAnimationBoxSizer, 0, wxEXPAND, 5 );
wxBoxSizer* bSizer9;
bSizer9 = new wxBoxSizer( wxVERTICAL );
mGraphicsPanel = new OGLCanvas( this, wxID_ANY, wxDefaultPosition, wxSize( -1,-1 ), wxTAB_TRAVERSAL );
mGraphicsPanel->SetMinSize( wxSize( 10,-1 ) );
bSizer9->Add( mGraphicsPanel, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5 );
bSizer10->Add( bSizer9, 0, 0, 5 );
mRightSideBoxSizer->Add( bSizer10, 0, 0, 5 );
fgSizer11->Add( mRightSideBoxSizer, 0, 0, 5 );
bSizer18->Add( fgSizer11, 0, 0, 5 );
this->SetSizer( bSizer18 );
this->Layout();
// Connect Events
this->Connect( mNewMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionNew ) );
this->Connect( mOpenMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionOpen ) );
this->Connect( mSaveAsMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionSaveAs ) );
this->Connect( mSaveMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionSave ) );
this->Connect( m_menuItem23->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Connect( mMenuItemEditCopy->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Connect( mMenuItemEditCut->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Connect( mMenuItemEditPaste->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Connect( mMenuitemEditCopySize->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Connect( mMenuitemEditCopyPosition->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Connect( mMenuitemEditPasteSize->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Connect( mMenuitemEditPastePosition->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Connect( mMenuItemEditDelete->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Connect( mMenuItemEditShowHide->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Connect( mMenuItemOpenGL->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionRenderer ) );
this->Connect( mMenuItemD3D->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionRenderer ) );
this->Connect( mMenuItemPortrait320x480->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Connect( mMenuItemLandscape480x320->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Connect( mMenuItemPortrait640x960->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Connect( mMenuItemLandscape960x640->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Connect( mMenuItemPortrait640x1136->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Connect( mMenuItemLandscape1136x640->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Connect( mMenuItemPortrait720x1280->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Connect( mMenuItemLandscape1280x720->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Connect( mMenuItemPortrait768x1024->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Connect( mMenuItemLandscape1024x768->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Connect( mMenuItemPortrait1536x2048->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Connect( mMenuItemLandscape2048x1536->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Connect( mMenuInsertStatic->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Connect( mMenuInsertButton->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Connect( mMenuInsertSlider->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Connect( mMenuInsertSprite->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Connect( mMenuMoveBack->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Connect( mMenuMoveFront->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Connect( mMenuAnimationPlay->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) );
this->Connect( mMenuAnimationStop->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) );
this->Connect( mMenuAnimationAddKeyFrame->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) );
this->Connect( mMenuAnimationDeleteKeyFrame->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) );
mRadioBoxTransform->Connect( wxEVT_COMMAND_RADIOBOX_SELECTED, wxCommandEventHandler( GuiEditorGui::OnRadioBoxTransform ), NULL, this );
m_button10->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickLayout ), NULL, this );
m_button111->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickLayout ), NULL, this );
mColorPickerBoundingBox->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBoundingBox ), NULL, this );
mColorPickerBoundingBoxSelect->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBoundingBox ), NULL, this );
mColorPickerBackground->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBackground ), NULL, this );
mSceneGraphTree->Connect( wxEVT_KEY_DOWN, wxKeyEventHandler( GuiEditorGui::OnKeyDownSceneGraph ), NULL, this );
mSceneGraphTree->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( GuiEditorGui::OnLeftDownTree ), NULL, this );
mSceneGraphTree->Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( GuiEditorGui::OnRightDownTree ), NULL, this );
mSceneGraphTree->Connect( wxEVT_COMMAND_TREE_ITEM_MENU, wxTreeEventHandler( GuiEditorGui::OnTreeItemMenu ), NULL, this );
mTextButtonName->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextButtonName->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextButtonWidth->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextButtonWidth->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextButtonHeight->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextButtonX->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextButtonX->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextButtonY->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextButtonY->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextButtonText->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextButtonText->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mColorPickerButton->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this );
mSliderButtonAlpha->Connect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Connect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Connect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Connect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Connect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Connect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Connect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this );
mFilePickButtonTexture->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonButtonClearTexture->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mButtonButtonCreateUV->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mFilePickButtonOnPressTexture->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonButtonClearOnPressTexture->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mButtonButtonOnPressCreateUV->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mFilePickButtonFont->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mColorPickerButtonFont->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this );
mTextButtonFontSize->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mChoiceButtonFontHorizontal->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this );
mChoiceButtonFontVertical->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this );
mTextSliderName->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderName->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderWidth->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderWidth->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderHeight->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderHeight->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderX->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderX->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderY->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderY->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderMin->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderMin->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderMax->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderMax->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderDefault->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderDefault->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mFilePickSliderTextureBar->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonSliderClearTextureBar->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mButtonSliderCreateUVBar->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mFilePickSliderTextureButton->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonSliderClearTextureButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mButtonSliderCreateUVButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mTextSpriteName->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteName->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSpriteWidth->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteWidth->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSpriteHeight->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteHeight->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSpriteX->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteX->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSpriteY->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteY->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mColorPickerSprite->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this );
mSliderSpriteAlpha->Connect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Connect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Connect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Connect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Connect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Connect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Connect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this );
mFilePickSpriteTextureFile->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonSpriteClearTexture->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mTextSpriteFPS->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteFPS->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextStaticName->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticName->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextStaticWidth->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticWidth->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextStaticHeight->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticHeight->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextStaticX->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticX->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextStaticY->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticY->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mColorPickerStatic->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this );
mSliderStaticAlpha->Connect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Connect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Connect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Connect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Connect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Connect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Connect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this );
mTextStaticText->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticText->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mFilePickStaticTexture->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonStaticClearTexture->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mButtonStaticCreateUV->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mFilePickStaticFont->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mColorPickerStaticFont->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this );
mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this );
mTextStaticFontSize->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mChoiceStaticFontHorizontal->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this );
mChoiceStaticFontVertical->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this );
mTextAnimationFrame->Connect( wxEVT_CHAR, wxKeyEventHandler( GuiEditorGui::OnCharAnimationFrame ), NULL, this );
mTextAnimationFrame->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnterAnimationFrame ), NULL, this );
m_button9->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
m_button101->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
m_button5->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
m_button6->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
m_button7->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
m_button8->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
mZoomIn->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickZoom ), NULL, this );
mZoomOut->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickZoom ), NULL, this );
mAddAnimationSequenceButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mDeleteAnimationSequenceButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mTextAnimationSequenceName->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextAnimationSequenceName->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mAnimationsChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this );
mGraphicsPanel->Connect( wxEVT_KEY_DOWN, wxKeyEventHandler( GuiEditorGui::OnKeyDownGraphicsPanel ), NULL, this );
mGraphicsPanel->Connect( wxEVT_KEY_UP, wxKeyEventHandler( GuiEditorGui::OnKeyUpGraphicsPanel ), NULL, this );
mGraphicsPanel->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( GuiEditorGui::OnLeftDownGraphicsPanel ), NULL, this );
mGraphicsPanel->Connect( wxEVT_LEFT_UP, wxMouseEventHandler( GuiEditorGui::OnLeftUpGraphicsPanel ), NULL, this );
mGraphicsPanel->Connect( wxEVT_MOTION, wxMouseEventHandler( GuiEditorGui::OnMotionGraphicsPanel ), NULL, this );
mGraphicsPanel->Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( GuiEditorGui::OnRightDownGraphicsPanel ), NULL, this );
mGraphicsPanel->Connect( wxEVT_RIGHT_UP, wxMouseEventHandler( GuiEditorGui::OnRightUpGraphicsPanel ), NULL, this );
mGraphicsPanel->Connect( wxEVT_SIZE, wxSizeEventHandler( GuiEditorGui::OnSizeGraphicsPanel ), NULL, this );
}
GuiEditorGui::~GuiEditorGui()
{
// Disconnect Events
this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionNew ) );
this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionOpen ) );
this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionSaveAs ) );
this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionSave ) );
this->Disconnect( EDIT_UNDO, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Disconnect( EDIT_COPY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Disconnect( EDIT_CUT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Disconnect( EDIT_PASTE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Disconnect( EDIT_COPY_SIZE_DATA, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Disconnect( EDIT_COPY_POSITION_DATA, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Disconnect( EDIT_PASTE_SIZE_DATA, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Disconnect( EDIT_PASTE_POSITION_DATA, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Disconnect( EDIT_DELETE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Disconnect( EDIT_SHOW_HIDE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) );
this->Disconnect( MENU_RENDERER_OPENGL, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionRenderer ) );
this->Disconnect( MENU_RENDERER_D3D, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionRenderer ) );
this->Disconnect( SCREEN_SIZE_PORTRAIT_320_480, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Disconnect( SCREEN_SIZE_LANDSCAPE_480_320, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Disconnect( SCREEN_SIZE_PORTRAIT_640_960, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Disconnect( SCREEN_SIZE_LANDSCAPE_960_640, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Disconnect( SCREEN_SIZE_PORTRAIT_640_1136, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Disconnect( SCREEN_SIZE_LANDSCAPE_1136_640, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Disconnect( SCREEN_SIZE_PORTRAIT_720_1280, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Disconnect( SCREEN_SIZE_LANDSCAPE_1280_720, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Disconnect( SCREEN_SIZE_PORTRAIT_768_1024, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Disconnect( SCREEN_SIZE_LANDSCAPE_1024_768, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Disconnect( SCREEN_SIZE_PORTRAIT_1536_2048, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) );
this->Disconnect( SCREEN_SIZE_LANDSCAPE_2048_1536, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) );
this->Disconnect( EDITOR_MENU_INSERT_STATIC, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Disconnect( EDITOR_MENU_INSERT_BUTTON, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Disconnect( EDITOR_MENU_INSERT_SLIDER, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Disconnect( EDITOR_MENU_INSERT_SPRITE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Disconnect( EDITOR_MENU_MOVE_BACK, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Disconnect( EDITOR_MENU_MOVE_FRONT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) );
this->Disconnect( EDITOR_MENU_ANIMATION_PLAY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) );
this->Disconnect( EDITOR_MENU_ANIMATION_STOP, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) );
this->Disconnect( EDITOR_MENU_ANIMATION_ADD_KEYFRAME, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) );
this->Disconnect( EDITOR_MENU_ANIMATION_DELETE_KEYFRAME, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) );
mRadioBoxTransform->Disconnect( wxEVT_COMMAND_RADIOBOX_SELECTED, wxCommandEventHandler( GuiEditorGui::OnRadioBoxTransform ), NULL, this );
m_button10->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickLayout ), NULL, this );
m_button111->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickLayout ), NULL, this );
mColorPickerBoundingBox->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBoundingBox ), NULL, this );
mColorPickerBoundingBoxSelect->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBoundingBox ), NULL, this );
mColorPickerBackground->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBackground ), NULL, this );
mSceneGraphTree->Disconnect( wxEVT_KEY_DOWN, wxKeyEventHandler( GuiEditorGui::OnKeyDownSceneGraph ), NULL, this );
mSceneGraphTree->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( GuiEditorGui::OnLeftDownTree ), NULL, this );
mSceneGraphTree->Disconnect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( GuiEditorGui::OnRightDownTree ), NULL, this );
mSceneGraphTree->Disconnect( wxEVT_COMMAND_TREE_ITEM_MENU, wxTreeEventHandler( GuiEditorGui::OnTreeItemMenu ), NULL, this );
mTextButtonName->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextButtonName->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextButtonWidth->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextButtonWidth->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextButtonHeight->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextButtonX->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextButtonX->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextButtonY->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextButtonY->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextButtonText->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextButtonText->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mColorPickerButton->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this );
mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this );
mFilePickButtonTexture->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonButtonClearTexture->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mButtonButtonCreateUV->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mFilePickButtonOnPressTexture->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonButtonClearOnPressTexture->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mButtonButtonOnPressCreateUV->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mFilePickButtonFont->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mColorPickerButtonFont->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this );
mTextButtonFontSize->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mChoiceButtonFontHorizontal->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this );
mChoiceButtonFontVertical->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this );
mTextSliderName->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderName->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderWidth->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderWidth->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderHeight->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderHeight->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderX->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderX->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderY->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderY->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderMin->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderMin->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderMax->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderMax->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSliderDefault->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSliderDefault->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mFilePickSliderTextureBar->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonSliderClearTextureBar->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mButtonSliderCreateUVBar->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mFilePickSliderTextureButton->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonSliderClearTextureButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mButtonSliderCreateUVButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mTextSpriteName->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteName->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSpriteWidth->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteWidth->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSpriteHeight->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteHeight->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSpriteX->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteX->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextSpriteY->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteY->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mColorPickerSprite->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this );
mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this );
mFilePickSpriteTextureFile->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonSpriteClearTexture->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mTextSpriteFPS->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextSpriteFPS->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextStaticName->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticName->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextStaticWidth->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticWidth->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextStaticHeight->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticHeight->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextStaticX->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticX->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mTextStaticY->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticY->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mColorPickerStatic->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this );
mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this );
mTextStaticText->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextStaticText->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mFilePickStaticTexture->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mButtonStaticClearTexture->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mButtonStaticCreateUV->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mFilePickStaticFont->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this );
mColorPickerStaticFont->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this );
mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this );
mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this );
mTextStaticFontSize->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mChoiceStaticFontHorizontal->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this );
mChoiceStaticFontVertical->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this );
mTextAnimationFrame->Disconnect( wxEVT_CHAR, wxKeyEventHandler( GuiEditorGui::OnCharAnimationFrame ), NULL, this );
mTextAnimationFrame->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnterAnimationFrame ), NULL, this );
m_button9->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
m_button101->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
m_button5->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
m_button6->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
m_button7->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
m_button8->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this );
mZoomIn->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickZoom ), NULL, this );
mZoomOut->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickZoom ), NULL, this );
mAddAnimationSequenceButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mDeleteAnimationSequenceButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this );
mTextAnimationSequenceName->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this );
mTextAnimationSequenceName->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this );
mAnimationsChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this );
mGraphicsPanel->Disconnect( wxEVT_KEY_DOWN, wxKeyEventHandler( GuiEditorGui::OnKeyDownGraphicsPanel ), NULL, this );
mGraphicsPanel->Disconnect( wxEVT_KEY_UP, wxKeyEventHandler( GuiEditorGui::OnKeyUpGraphicsPanel ), NULL, this );
mGraphicsPanel->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( GuiEditorGui::OnLeftDownGraphicsPanel ), NULL, this );
mGraphicsPanel->Disconnect( wxEVT_LEFT_UP, wxMouseEventHandler( GuiEditorGui::OnLeftUpGraphicsPanel ), NULL, this );
mGraphicsPanel->Disconnect( wxEVT_MOTION, wxMouseEventHandler( GuiEditorGui::OnMotionGraphicsPanel ), NULL, this );
mGraphicsPanel->Disconnect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( GuiEditorGui::OnRightDownGraphicsPanel ), NULL, this );
mGraphicsPanel->Disconnect( wxEVT_RIGHT_UP, wxMouseEventHandler( GuiEditorGui::OnRightUpGraphicsPanel ), NULL, this );
mGraphicsPanel->Disconnect( wxEVT_SIZE, wxSizeEventHandler( GuiEditorGui::OnSizeGraphicsPanel ), NULL, this );
}
| 72.721098
| 215
| 0.801701
|
justinctlam
|
841a7e2524ae14ecae06428526799000767f2719
| 1,069
|
cpp
|
C++
|
emulator/src/emu/dinetwork.cpp
|
rjw57/tiw-computer
|
5ef1c79893165b8622d1114d81cd0cded58910f0
|
[
"MIT"
] | 1
|
2022-01-15T21:38:38.000Z
|
2022-01-15T21:38:38.000Z
|
emulator/src/emu/dinetwork.cpp
|
rjw57/tiw-computer
|
5ef1c79893165b8622d1114d81cd0cded58910f0
|
[
"MIT"
] | null | null | null |
emulator/src/emu/dinetwork.cpp
|
rjw57/tiw-computer
|
5ef1c79893165b8622d1114d81cd0cded58910f0
|
[
"MIT"
] | null | null | null |
// license:BSD-3-Clause
// copyright-holders:Carl, Miodrag Milanovic
#include "emu.h"
#include "osdnet.h"
device_network_interface::device_network_interface(const machine_config &mconfig, device_t &device, float bandwidth)
: device_interface(device, "network")
{
m_promisc = false;
m_bandwidth = bandwidth;
set_mac("\0\0\0\0\0\0");
m_intf = 0;
}
device_network_interface::~device_network_interface()
{
}
int device_network_interface::send(u8 *buf, int len) const
{
if(!m_dev) return 0;
return m_dev->send(buf, len);
}
void device_network_interface::recv_cb(u8 *buf, int len)
{
}
void device_network_interface::set_promisc(bool promisc)
{
m_promisc = promisc;
if(m_dev) m_dev->set_promisc(promisc);
}
void device_network_interface::set_mac(const char *mac)
{
memcpy(m_mac, mac, 6);
if(m_dev) m_dev->set_mac(m_mac);
}
void device_network_interface::set_interface(int id)
{
m_dev.reset(open_netdev(id, this, (int)(m_bandwidth*1000000/8.0f/1500)));
if(!m_dev) {
device().logerror("Network interface %d not found\n", id);
id = -1;
}
m_intf = id;
}
| 21.38
| 116
| 0.731525
|
rjw57
|
8421f307b6c36c4060ee159cf7ed771972cd5bbb
| 90
|
cpp
|
C++
|
src/Item.cpp
|
Erick9Thor/Zork
|
43ee99711bb991e0f8c3cf61f18c1d2e373ac2a7
|
[
"MIT"
] | null | null | null |
src/Item.cpp
|
Erick9Thor/Zork
|
43ee99711bb991e0f8c3cf61f18c1d2e373ac2a7
|
[
"MIT"
] | null | null | null |
src/Item.cpp
|
Erick9Thor/Zork
|
43ee99711bb991e0f8c3cf61f18c1d2e373ac2a7
|
[
"MIT"
] | null | null | null |
#include "../include/Item.h"
ItemType Item::GetItemType() const
{
return itemType;
}
| 12.857143
| 34
| 0.677778
|
Erick9Thor
|
84265e8c1625a8e0a499b82c9b1ea02d707ffee2
| 1,259
|
cpp
|
C++
|
vegastrike/src/cmd/bolt_server.cpp
|
Ezeer/VegaStrike_win32FR
|
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
|
[
"MIT"
] | null | null | null |
vegastrike/src/cmd/bolt_server.cpp
|
Ezeer/VegaStrike_win32FR
|
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
|
[
"MIT"
] | null | null | null |
vegastrike/src/cmd/bolt_server.cpp
|
Ezeer/VegaStrike_win32FR
|
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
|
[
"MIT"
] | null | null | null |
#include "bolt.h"
#include "gfxlib.h"
#include "gfx/mesh.h"
#include "gfxlib_struct.h"
#include <vector>
#include <string>
#include <algorithm>
#include "unit_generic.h"
#include "configxml.h"
GFXVertexList*bolt_draw::boltmesh = NULL;
bolt_draw::~bolt_draw()
{
unsigned int i;
for (i = 0; i < balls.size(); i++)
for (int j = balls[i].size()-1; j >= 0; j--)
balls[i][j].Destroy( j );
for (i = 0; i < bolts.size(); i++)
for (int j = balls[i].size()-1; j >= 0; j--)
bolts[i][j].Destroy( j );
}
bolt_draw::bolt_draw()
{
boltmesh = NULL;
boltdecals = NULL;
}
int Bolt::AddTexture( bolt_draw *q, std::string file )
{
int decal = 0;
if ( decal >= (int) q->bolts.size() )
q->bolts.push_back( vector< Bolt > () );
return decal;
}
int Bolt::AddAnimation( bolt_draw *q, std::string file, QVector cur_position )
{
int decal = 0;
if ( decal >= (int) q->balls.size() )
q->balls.push_back( vector< Bolt > () );
return decal;
}
void Bolt::Draw() {}
extern void BoltDestroyGeneric( Bolt *whichbolt, unsigned int index, int decal, bool isBall );
void Bolt::Destroy( unsigned int index )
{
BoltDestroyGeneric( this, index, decal, type->type != weapon_info::BOLT );
}
| 24.686275
| 94
| 0.601271
|
Ezeer
|
842b1dd42b8e6cfb395af85944e7da162dc0a8bc
| 4,385
|
cpp
|
C++
|
cnf_dump/cnf_dump_clo.cpp
|
appu226/FactorGraph
|
26e4de8518874abf2696a167eaf3dbaede5930f8
|
[
"MIT"
] | null | null | null |
cnf_dump/cnf_dump_clo.cpp
|
appu226/FactorGraph
|
26e4de8518874abf2696a167eaf3dbaede5930f8
|
[
"MIT"
] | null | null | null |
cnf_dump/cnf_dump_clo.cpp
|
appu226/FactorGraph
|
26e4de8518874abf2696a167eaf3dbaede5930f8
|
[
"MIT"
] | null | null | null |
/*
Copyright 2019 Parakram Majumdar
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 corresponding header file
#include "cnf_dump_clo.h"
// std includes
#include <stdexcept>
namespace cnf_dump {
//----------------------------------------------------------------
// definitions of members of class CnfDumpClo
//----------------------------------------------------------------
// function CnfDumpClo::create
std::shared_ptr<CnfDumpClo> CnfDumpClo::create(int argc, char const * const * const argv)
{
return std::make_shared<CnfDumpClo>(argc, argv);
}
// function CnfDumpClo::printHelpMessage
// prints help info
void CnfDumpClo::printHelpMessage()
{
std::cout << "cnf_dump:\n"
<< " Utility for converting a blif file into a cnf_dump\n"
<< "\n"
<< "Usage:\n"
<< " cnf_dump <options>\n"
<< "\n"
<< "Options:\n"
<< " --blif_file <input blif file> (MANDATORY)\n"
<< " --cnf_file <output blif file> (MANDATORY)\n"
<< " --num_lo_vars_to_quantify <number of latch output vars to quantify out>, defaults to 0\n"
<< " --verbosity <verbosity> : one of QUIET/ERROR/WARNING/INFO/DEBUG, defaults to ERROR\n"
<< " --help: prints this help message and exits\n"
<< std::endl;
return;
}
// constructor CnfDumpClo::CnfDumpClo
// stub implementation
CnfDumpClo::CnfDumpClo(int argc, char const * const * const argv) :
blif_file(),
output_cnf_file(),
verbosity(blif_solve::ERROR),
num_lo_vars_to_quantify(0),
help(false)
{
char const * const * current_argv = argv + 1;
for (int argnum = 1; argnum < argc; ++argnum, ++current_argv)
{
std::string current_arg(*current_argv);
if (current_arg == "--blif_file")
{
++argnum;
++current_argv;
if (argnum >= argc)
throw std::invalid_argument("Missing <input blif file> after argument --blif_file");
blif_file = *current_argv;
}
else if (current_arg == "--cnf_file")
{
++argnum;
++current_argv;
if (argnum >= argc)
throw std::invalid_argument("Missing <input cnf file> after argument --cnf_file");
output_cnf_file = *current_argv;
}
else if (current_arg == "--verbosity")
{
++argnum;
++current_argv;
if (argnum >= argc)
throw std::invalid_argument("Missing <verbosity> after argument --verbosity");
verbosity = blif_solve::parseVerbosity(*current_argv);
}
else if (current_arg == "--help")
help = true;
else if (current_arg == "--num_lo_vars_to_quantify")
{
++argnum;
++current_argv;
if (argnum >= argc)
throw std::invalid_argument("Missing <number> after argument --num_lo_vars_to_quantify");
num_lo_vars_to_quantify = atoi(*current_argv);
}
else
throw std::invalid_argument(std::string("Unexpected argument '") + *current_argv + "'");
}
if (help)
return;
if (blif_file == "")
throw std::invalid_argument("Missing mandatory argument --blif_file");
if (output_cnf_file == "")
throw std::invalid_argument("Missing mandatory argument --cnf_file");
return;
}
} // end namespace cnf_dump
| 32.242647
| 109
| 0.620753
|
appu226
|
842cc9c6722bc81483b9a34464a134e42c681b75
| 14,748
|
cpp
|
C++
|
src/RotationPricer.cpp
|
sergebisaillon/MerinioScheduler
|
8549ce7f3c1c14817a2eba9d565ca0b56f451e2a
|
[
"MIT"
] | 1
|
2020-05-05T15:51:41.000Z
|
2020-05-05T15:51:41.000Z
|
src/RotationPricer.cpp
|
qiqi789/NurseScheduler
|
8549ce7f3c1c14817a2eba9d565ca0b56f451e2a
|
[
"MIT"
] | null | null | null |
src/RotationPricer.cpp
|
qiqi789/NurseScheduler
|
8549ce7f3c1c14817a2eba9d565ca0b56f451e2a
|
[
"MIT"
] | 1
|
2019-11-11T17:59:23.000Z
|
2019-11-11T17:59:23.000Z
|
/*
* RotationPricer.cpp
*
* Created on: 2015-03-02
* Author: legraina
*/
#include "RotationPricer.h"
#include "BcpModeler.h"
/* namespace usage */
using namespace std;
//////////////////////////////////////////////////////////////
//
// R O T A T I O N P R I C E R
//
//////////////////////////////////////////////////////////////
static char const * baseName = "rotation";
/* Constructs the pricer object. */
RotationPricer::RotationPricer(MasterProblem* master, const char* name, SolverParam param):
MyPricer(name), nbMaxRotationsToAdd_(20), nbSubProblemsToSolve_(15), nursesToSolve_(master->theNursesSorted_),
pMaster_(master), pScenario_(master->pScenario_), nbDays_(master->pDemand_->nbDays_), pModel_(master->getModel()), nb_int_solutions_(0)
{
// Initialize the parameters
initPricerParameters(param);
/* sort the nurses */
// random_shuffle( nursesToSolve_.begin(), nursesToSolve_.end());
}
/* Destructs the pricer object. */
RotationPricer::~RotationPricer() {
for(pair<const Contract*, SubProblem*> p: subProblems_)
delete p.second;
}
void RotationPricer::initPricerParameters(SolverParam param){
// Here: doing a little check to be sure that secondchance is activated only when the parameters are different...
withSecondchance_ = param.sp_withsecondchance_ && (param.sp_default_strategy_ != param.sp_secondchance_strategy_);
nbMaxRotationsToAdd_ = param.sp_nbrotationspernurse_;
nbSubProblemsToSolve_ = param.sp_nbnursestoprice_;
defaultSubprobemStrategy_ = param.sp_default_strategy_;
secondchanceSubproblemStrategy_ = param.sp_secondchance_strategy_;
currentSubproblemStrategy_ = defaultSubprobemStrategy_;
}
/******************************************************
* Perform pricing
******************************************************/
vector<MyVar*> RotationPricer::pricing(double bound, bool before_fathom){
// Reset all rotations, columns, counters, etc.
resetSolutions();
// count and store the nurses whose subproblems produced rotations.
// DBG: why minDualCost? Isn't it more a reduced cost?
double minDualCost = 0;
vector<LiveNurse*> nursesSolved;
for(vector<LiveNurse*>::iterator it0 = nursesToSolve_.begin(); it0 != nursesToSolve_.end();){
// RETRIEVE THE NURSE AND CHECK THAT HE/SHE IS NOT FORBIDDEN
LiveNurse* pNurse = *it0;
bool nurseForbidden = isNurseForbidden(pNurse->id_);
// IF THE NURSE IS NOT FORBIDDEN, SOLVE THE SUBPROBLEM
if(!nurseForbidden){
// BUILD OR RE-USE THE SUBPROBLEM
SubProblem* subProblem = retriveSubproblem(pNurse);
// RETRIEVE DUAL VALUES
vector< vector<double> > workDualCosts(getWorkDualValues(pNurse));
vector<double> startWorkDualCosts(getStartWorkDualValues(pNurse));
vector<double> endWorkDualCosts(getEndWorkDualValues(pNurse));
double workedWeekendDualCost = getWorkedWeekendDualValue(pNurse);
DualCosts dualCosts (workDualCosts, startWorkDualCosts, endWorkDualCosts, workedWeekendDualCost, true);
// UPDATE FORBIDDEN SHIFTS
if (pModel_->getParameters().isColumnDisjoint_) {
addForbiddenShifts();
}
set<pair<int,int> > nurseForbiddenShifts(forbiddenShifts_);
pModel_->addForbiddenShifts(pNurse, nurseForbiddenShifts);
// SET SOLVING OPTIONS
SubproblemParam sp_param (currentSubproblemStrategy_,pNurse);
// DBG ***
// generateRandomForbiddenStartingDays();
// SOLVE THE PROBLEM
++ nbSPTried_;
subProblem->solve(pNurse, &dualCosts, sp_param, nurseForbiddenShifts, forbiddenStartingDays_, true ,
bound);
// RETRIEVE THE GENERATED ROTATIONS
newRotationsForNurse_ = subProblem->getRotations();
// DBG ***
// checkForbiddenStartingDays();
// recordSPStats(subProblem);
// for(Rotation& rot: newRotationsForNurse_){
// rot.checkDualCost(dualCosts);
// }
// ADD THE ROTATIONS TO THE MASTER PROBLEM
addRotationsToMaster();
}
// CHECK IF THE SUBPROBLEM GENERATED NEW ROTATIONS
// If yes, store the nures
if(newRotationsForNurse_.size() > 0 && !nurseForbidden){
++nbSPSolvedWithSuccess_;
if(newRotationsForNurse_[0].dualCost_ < minDualCost)
minDualCost = newRotationsForNurse_[0].dualCost_;
nursesToSolve_.erase(it0);
nursesSolved.push_back(pNurse);
}
// Otherwise (no rotation generated or nurse is forbidden), try the next nurse
else {
++it0;
// If it was the last nurse to search AND no improving column was found AND we may want to solve SP with
// different parameters -> change these parameters and go for another loop of solving
if( it0 == nursesToSolve_.end() && allNewColumns_.empty() && withSecondchance_){
if(currentSubproblemStrategy_ == defaultSubprobemStrategy_){
nursesToSolve_.insert(nursesToSolve_.end(), nursesSolved.begin(), nursesSolved.end());
it0 = nursesToSolve_.begin();
currentSubproblemStrategy_ = secondchanceSubproblemStrategy_;
} else if (currentSubproblemStrategy_ == secondchanceSubproblemStrategy_) {
currentSubproblemStrategy_ = defaultSubprobemStrategy_;
}
}
}
//if the maximum number of subproblem solved is reached, break.
if(nbSPSolvedWithSuccess_ == nbSubProblemsToSolve_)
break;
}
//Add the nurse in nursesSolved at the end
nursesToSolve_.insert(nursesToSolve_.end(), nursesSolved.begin(), nursesSolved.end());
//set statistics
BcpModeler* model = dynamic_cast<BcpModeler*>(pModel_);
if(model){
model->setLastNbSubProblemsSolved(nbSPTried_);
model->setLastMinDualCost(minDualCost);
}
if(allNewColumns_.empty())
print_current_solution_();
// std::cout << "# ------- END ------- Subproblems!" << std::endl;
// return optimal;
return allNewColumns_;
}
/******************************************************
* Get the duals values per day for a nurse
******************************************************/
vector< vector<double> > RotationPricer::getWorkDualValues(LiveNurse* pNurse){
vector< vector<double> > dualValues(nbDays_);
int i = pNurse->id_;
int p = pNurse->pContract_->id_;
/* Min/Max constraints */
double minWorkedDays = pModel_->getDual(pMaster_->minWorkedDaysCons_[i], true);
double maxWorkedDays = pModel_->getDual(pMaster_->maxWorkedDaysCons_[i], true);
double minWorkedDaysAvg = pMaster_->isMinWorkedDaysAvgCons_[i] ? pModel_->getDual(pMaster_->minWorkedDaysAvgCons_[i], true):0.0;
double maxWorkedDaysAvg = pMaster_->isMaxWorkedDaysAvgCons_[i] ? pModel_->getDual(pMaster_->maxWorkedDaysAvgCons_[i], true):0.0;
double minWorkedDaysContractAvg = pMaster_->isMinWorkedDaysContractAvgCons_[p] ?
pModel_->getDual(pMaster_->minWorkedDaysContractAvgCons_[p], true):0.0;
double maxWorkedDaysContractAvg = pMaster_->isMaxWorkedDaysContractAvgCons_[p] ?
pModel_->getDual(pMaster_->maxWorkedDaysContractAvgCons_[p], true):0.0;
for(int k=0; k<nbDays_; ++k){
//initialize vector
vector<double> dualValues2(pScenario_->nbShifts_-1);
for(int s=1; s<pScenario_->nbShifts_; ++s){
/* Min/Max constraints */
dualValues2[s-1] = minWorkedDays + minWorkedDaysAvg + minWorkedDaysContractAvg;
dualValues2[s-1] += maxWorkedDays + maxWorkedDaysAvg + maxWorkedDaysContractAvg;
/* Skills coverage */
dualValues2[s-1] += pModel_->getDual(
pMaster_->numberOfNursesByPositionCons_[k][s-1][pNurse->pPosition_->id_], true);
}
//store vector
dualValues[k] = dualValues2;
}
return dualValues;
}
vector<double> RotationPricer::getStartWorkDualValues(LiveNurse* pNurse){
int i = pNurse->id_;
vector<double> dualValues(nbDays_);
//get dual value associated to the source
dualValues[0] = pModel_->getDual(pMaster_->restFlowCons_[i][0], true);
//get dual values associated to the work flow constraints
//don't take into account the last which is the sink
for(int k=1; k<nbDays_; ++k)
dualValues[k] = pModel_->getDual(pMaster_->workFlowCons_[i][k-1], true);
return dualValues;
}
vector<double> RotationPricer::getEndWorkDualValues(LiveNurse* pNurse){
int i = pNurse->id_;
vector<double> dualValues(nbDays_);
//get dual values associated to the work flow constraints
//don't take into account the first which is the source
//take into account the cost, if the last day worked is k
for(int k=0; k<nbDays_-1; ++k)
dualValues[k] = -pModel_->getDual(pMaster_->restFlowCons_[i][k+1], true);
//get dual value associated to the sink
dualValues[nbDays_-1] = pModel_->getDual(
pMaster_->workFlowCons_[i][nbDays_-1], true);
return dualValues;
}
double RotationPricer::getWorkedWeekendDualValue(LiveNurse* pNurse){
int id = pNurse->id_;
double dualVal = pModel_->getDual(pMaster_->maxWorkedWeekendCons_[id], true);
if (pMaster_->isMaxWorkedWeekendAvgCons_[id]) {
dualVal += pModel_->getDual(pMaster_->maxWorkedWeekendAvgCons_[id], true);
}
if (pMaster_->isMaxWorkedWeekendContractAvgCons_[pNurse->pContract_->id_]) {
dualVal += pModel_->getDual(pMaster_->maxWorkedWeekendContractAvgCons_[pNurse->pContract_->id_], true);
}
return dualVal;
}
/******************************************************
* add some forbidden shifts
******************************************************/
void RotationPricer::addForbiddenShifts(){
//search best rotation
vector<Rotation>::iterator bestRotation;
double bestDualcost = DBL_MAX;
for(vector<Rotation>::iterator it = newRotationsForNurse_.begin(); it != newRotationsForNurse_.end(); ++it)
if(it->dualCost_ < bestDualcost){
bestDualcost = it->dualCost_;
bestRotation = it;
}
//forbid shifts of the best rotation
if(bestDualcost != DBL_MAX)
for(pair<int,int> pair: bestRotation->shifts_)
forbiddenShifts_.insert(pair);
}
// Returns a pointer to the right subproblem
SubProblem* RotationPricer::retriveSubproblem(LiveNurse* pNurse){
SubProblem* subProblem;
map<const Contract*, SubProblem*>::iterator it = subProblems_.find(pNurse->pContract_);
// Each contract has one subproblem. If it has not already been created, create it.
if( it == subProblems_.end() ){
subProblem = new SubProblem(pScenario_, nbDays_, pNurse->pContract_, pMaster_->pInitState_);
subProblems_.insert(it, pair<const Contract*, SubProblem*>(pNurse->pContract_, subProblem));
} else {
subProblem = it->second;
}
return subProblem;
}
// Add the rotations to the master problem
void RotationPricer::addRotationsToMaster(){
// COMPUTE THE COST OF THE ROTATIONS
for(Rotation& rot: newRotationsForNurse_){
rot.computeCost(pScenario_, pMaster_->pPreferences_, pMaster_->theLiveNurses_,nbDays_);
rot.treeLevel_ = pModel_->getCurrentTreeLevel();
}
// SORT THE ROTATIONS
sortNewlyGeneratedRotations();
// SECOND, ADD THE ROTATIONS TO THE MASTER PROBLEM (in the previously computed order)
int nbRotationsAdded = 0;
for(Rotation& rot: newRotationsForNurse_){
allNewColumns_.push_back(pMaster_->addRotation(rot, baseName));
++nbRotationsAdded;
// DBG
//cout << rot.toString(nbDays_) << endl;
if(nbRotationsAdded >= nbMaxRotationsToAdd_)
break;
}
}
// Sort the rotations that just were generated for a nurse. Default option is sort by increasing reduced cost but we
// could try something else (involving disjoint columns for ex.)
void RotationPricer::sortNewlyGeneratedRotations(){
std::stable_sort(newRotationsForNurse_.begin(), newRotationsForNurse_.end(), Rotation::compareDualCost);
}
// Set the subproblem options depending on the parameters
//
//void RotationPricer::setSubproblemOptions(vector<SolveOption>& options, int& maxRotationLengthForSubproblem,
// LiveNurse* pNurse){
//
// // Default option that should be used
// options.push_back(SOLVE_ONE_SINK_PER_LAST_DAY);
//
// // Options are added depending on the chosen parameters
// //
// if (currentPricerParam_.isExhaustiveSearch()) {
// options.push_back(SOLVE_SHORT_ALL);
// maxRotationLengthForSubproblem = LARGE_TIME;
// }
// else if (currentPricerParam_.nonPenalizedRotationsOnly()) {
// options.push_back(SOLVE_SHORT_DAY_0_ONLY);
// maxRotationLengthForSubproblem = pNurse->maxConsDaysWork();
// }
// else {
// if(currentPricerParam_.withShortRotations()) options.push_back(SOLVE_SHORT_ALL);
// maxRotationLengthForSubproblem = currentPricerParam_.maxRotationLength();
// }
//
//}
// ------------------------------------------
//
// PRINT functions
//
// ------------------------------------------
void RotationPricer::print_current_solution_(){
//pMaster_->costsConstrainstsToString();
//pMaster_->allocationToString();
if(nb_int_solutions_ < pMaster_->getModel()->nbSolutions()){
nb_int_solutions_ = pMaster_->getModel()->nbSolutions();
//pMaster_->getModel()->printBestSol();
//pMaster_->costsConstrainstsToString();
}
}
void RotationPricer::printStatSPSolutions(){
double tMeanSubproblems = timeInExSubproblems_ / ((double)nbExSubproblems_);
double tMeanS = timeForS_ / ((double)nbS_);
double tMeanNL = timeForNL_ / ((double)nbNL_);
double tMeanN = timeForN_ / ((double)nbN_);
string sepLine = "+-----------------+------------------------+-----------+\n";
printf("\n");
printf("%s", sepLine.c_str());
printf("| %-15s |%10s %12s |%10s |\n", "type", "time", "number", "mean time");
printf("%s", sepLine.c_str());
printf("| %-15s |%10.2f %12d |%10.4f |\n", "Ex. Subproblems", timeInExSubproblems_, nbExSubproblems_, tMeanSubproblems);
printf("| %-15s |%10.2f %12d |%10.4f |\n", "Short rotations", timeForS_, nbS_, tMeanS);
printf("| %-15s |%10.2f %12d |%10.4f |\n", "NL rotations", timeForNL_, nbNL_, tMeanNL);
printf("%s", sepLine.c_str());
printf("| %-15s |%10.2f %12d |%10.4f |\n", "N rotations", timeForN_, nbN_, tMeanN);
printf("%s", sepLine.c_str());
printf("\n");
}
// ------------------------------------------
//
// DBG functions - may be useful
//
// ------------------------------------------
//void RotationPricer::recordSPStats(SubProblem* sp){
// if (currentPricerParam_.isExhaustiveSearch()) {
// nbExSubproblems_++; nbSubproblems_++; nbS_++; nbNL_++;
// timeForS_ += sp->timeInS_->dSinceStart();
// timeForNL_ += sp->timeInNL_->dSinceStart();
// timeInExSubproblems_ += sp->timeInS_->dSinceStart() + sp->timeInNL_->dSinceStart();
// }
// else if (currentPricerParam_.nonPenalizedRotationsOnly()) {
// nbSubproblems_++; nbN_++;
// timeForN_ += sp->timeInNL_->dSinceStart();
// }
// else {
// }
//}
void RotationPricer::generateRandomForbiddenStartingDays(){
set<int> randomForbiddenStartingDays;
for(int m=0; m<5; m++){
int k = Tools::randomInt(0, nbDays_-1);
randomForbiddenStartingDays.insert(k);
}
forbiddenStartingDays_ = randomForbiddenStartingDays;
}
void RotationPricer::checkForbiddenStartingDays(){
for(Rotation& rot: newRotationsForNurse_){
int startingDay = rot.firstDay_;
if(forbiddenStartingDays_.find(startingDay) != forbiddenStartingDays_.end()){
cout << "# On a généré une rotation qui commence un jour interdit !" << endl;
getchar();
}
}
}
| 34.619718
| 137
| 0.702129
|
sergebisaillon
|
8438b89e25ce446d49d0eda0cc0bc78749c00c74
| 4,741
|
cc
|
C++
|
Samples/PostProcessing/PostProcessing.cc
|
rodrigobmg/YumeEngine
|
67c525c84616a5167b5bae45f36641e90227c281
|
[
"MIT"
] | 129
|
2016-05-05T23:34:44.000Z
|
2022-03-07T20:17:18.000Z
|
Samples/PostProcessing/PostProcessing.cc
|
rodrigobmg/YumeEngine
|
67c525c84616a5167b5bae45f36641e90227c281
|
[
"MIT"
] | 1
|
2017-05-07T16:09:41.000Z
|
2017-05-08T15:35:50.000Z
|
Samples/PostProcessing/PostProcessing.cc
|
rodrigobmg/YumeEngine
|
67c525c84616a5167b5bae45f36641e90227c281
|
[
"MIT"
] | 20
|
2016-02-24T20:40:08.000Z
|
2022-02-04T23:48:18.000Z
|
//--------------------------------------------------------------------------------
//This is a file from Arkengine
//
//
//Copyright (c) arkenthera.All rights reserved.
//
//BasicRenderWindow.cpp
//--------------------------------------------------------------------------------
#include "Core/YumeHeaders.h"
#include "PostProcessing.h"
#include "Logging/logging.h"
#include "Core/YumeMain.h"
#include "Renderer/YumeLPVCamera.h"
#include <boost/shared_ptr.hpp>
#include "Input/YumeInput.h"
#include "Renderer/YumeTexture2D.h"
#include "Renderer/YumeResourceManager.h"
#include "Engine/YumeEngine.h"
#include "UI/YumeDebugOverlay.h"
#include "Renderer/Light.h"
#include "Renderer/StaticModel.h"
#include "Renderer/Scene.h"
#include "Renderer/RenderPass.h"
#include "UI/YumeOptionsMenu.h"
YUME_DEFINE_ENTRY_POINT(YumeEngine::GodRays);
#define TURNOFF 1
//#define NO_MODEL
//#define OBJECTS_CAST_SHADOW
#define NO_SKYBOX
#define NO_PLANE
namespace YumeEngine
{
GodRays::GodRays()
: angle1_(0),
updown1_(0),
leftRight1_(0)
{
REGISTER_ENGINE_LISTENER;
}
GodRays::~GodRays()
{
}
void GodRays::Start()
{
YumeResourceManager* rm_ = gYume->pResourceManager;
YumeMiscRenderer* renderer = gYume->pRenderer;
Scene* scene = renderer->GetScene();
YumeCamera* camera = renderer->GetCamera();
gYume->pInput->AddListener(this);
#ifndef DISABLE_CEF
optionsMenu_ = new YumeOptionsMenu;
gYume->pUI->AddUIElement(optionsMenu_);
optionsMenu_->SetVisible(true);
overlay_ = new YumeDebugOverlay;
gYume->pUI->AddUIElement(overlay_);
overlay_->SetVisible(true);
overlay_->GetBinding("SampleName")->SetValue("Post Processing");
#endif
//Define post processing effects
RenderPass* dp = renderer->GetDefaultPass();
dp->Load("RenderCalls/Bloom.xml",true);
dp->Load("RenderCalls/FXAA.xml",true);
dp->Load("RenderCalls/LensDistortion.xml",true);
dp->Load("RenderCalls/Godrays.xml",true);
dp->Load("RenderCalls/ShowGBuffer.xml",true);
dp->DisableRenderCalls("ShowGBuffer");
dp->DisableRenderCalls("Godrays");
dp->DisableRenderCalls("Bloom");
MaterialPtr emissiveBlue = YumeAPINew Material;
emissiveBlue->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(0,0,1,1));
emissiveBlue->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
emissiveBlue->SetShaderParameter("Roughness",0.001f);
emissiveBlue->SetShaderParameter("ShadingMode",0);
emissiveBlue->SetShaderParameter("has_diffuse_tex",false);
emissiveBlue->SetShaderParameter("has_alpha_tex",false);
emissiveBlue->SetShaderParameter("has_specular_tex",false);
emissiveBlue->SetShaderParameter("has_normal_tex",false);
emissiveBlue->SetShaderParameter("has_roughness_tex",false);
MaterialPtr emissiveRed = YumeAPINew Material;
emissiveRed->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(1,0,0,1));
emissiveRed->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
emissiveRed->SetShaderParameter("Roughness",0.001f);
emissiveRed->SetShaderParameter("ShadingMode",0);
emissiveRed->SetShaderParameter("has_diffuse_tex",false);
emissiveRed->SetShaderParameter("has_alpha_tex",false);
emissiveRed->SetShaderParameter("has_specular_tex",false);
emissiveRed->SetShaderParameter("has_normal_tex",false);
emissiveRed->SetShaderParameter("has_roughness_tex",false);
MaterialPtr emissivePink = YumeAPINew Material;
emissivePink->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(1,0.0784314f,0.576471f,1));
emissivePink->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
emissivePink->SetShaderParameter("Roughness",0.001f);
emissivePink->SetShaderParameter("ShadingMode",0);
emissivePink->SetShaderParameter("has_diffuse_tex",false);
emissivePink->SetShaderParameter("has_alpha_tex",false);
emissivePink->SetShaderParameter("has_specular_tex",false);
emissivePink->SetShaderParameter("has_normal_tex",false);
emissivePink->SetShaderParameter("has_roughness_tex",false);
StaticModel* jeyjeyModel = CreateModel("Models/sponza/sponza.yume");
Light* dirLight = new Light;
dirLight->SetName("DirLight");
dirLight->SetType(LT_DIRECTIONAL);
dirLight->SetPosition(DirectX::XMVectorSet(0,1500,0,0));
dirLight->SetDirection(DirectX::XMVectorSet(0,-1,0,0));
dirLight->SetRotation(DirectX::XMVectorSet(-1,0,0,0));
dirLight->SetColor(YumeColor(1,1,1,0));
scene->AddNode(dirLight);
}
void GodRays::MoveCamera(float timeStep)
{
}
void GodRays::HandleUpdate(float timeStep)
{
}
void GodRays::HandleRenderUpdate(float timeStep)
{
}
void GodRays::Setup()
{
engineVariants_["GI"] = LPV;
engineVariants_["WindowWidth"] = 1024;
engineVariants_["WindowHeight"] = 768;
BaseApplication::Setup();
}
}
| 27.725146
| 95
| 0.730015
|
rodrigobmg
|
843a8013b35ade495a373147057fe382813aa470
| 8,810
|
cpp
|
C++
|
3d_conv/xilinx_prj/lib_gen/__merlinwrapper_conv_3d_kernel.cpp
|
FCS-holding/acc_lib
|
1b6c0bc5467400e2ac678d18426cbbc7d44e8fec
|
[
"Apache-2.0"
] | null | null | null |
3d_conv/xilinx_prj/lib_gen/__merlinwrapper_conv_3d_kernel.cpp
|
FCS-holding/acc_lib
|
1b6c0bc5467400e2ac678d18426cbbc7d44e8fec
|
[
"Apache-2.0"
] | null | null | null |
3d_conv/xilinx_prj/lib_gen/__merlinwrapper_conv_3d_kernel.cpp
|
FCS-holding/acc_lib
|
1b6c0bc5467400e2ac678d18426cbbc7d44e8fec
|
[
"Apache-2.0"
] | null | null | null |
#include "cmost.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <hls_stream.h>
#include "merlin_type_define.h"
#include "__merlinhead_kernel_top.h"
#include <chrono>
#include <iostream>
void __merlinwrapper_conv_3d_kernel(float data_in[DATA_IN_LENGTH],
float filter[FILTER_IN_LENGTH],
float data_out[DATA_OUT_LENGTH]) {
if (filter == 0) {
printf("Error! Detected null pointer 'filter' for external memory.\n");
exit(1);
}
if (data_in == 0) {
printf("Error! Detected null pointer 'data_in' for external memory.\n");
exit(1);
}
if (data_out == 0) {
printf("Error! Detected null pointer 'data_out' for external memory.\n");
exit(1);
}
#ifdef DEBUG
printf("IN_SIZE_TILE = %d, OUT_SIZE_TILE = %d, IN_DEPTH = %d\n", IN_SIZE_TILE, OUT_SIZE_TILE, IN_DEPTH);
printf("IN_SIZE_ONE_CALL = %d, OUT_SIZE_ONE_CALL = %d\n", IN_SIZE_ONE_CALL, OUT_SIZE_ONE_CALL);
printf("LAST_OUT_SIZE_ONE_CALL = %d\n", LAST_OUT_SIZE_ONE_CALL);
#endif
float * data_in_merlin[PE];
float * data_out_merlin[PE];
for (int j = 0; j < PE; j++) {
data_in_merlin[j] = (float *)malloc(IN_SIZE_TILE*sizeof(float));
data_out_merlin[j] = (float *)malloc(OUT_SIZE_TILE*sizeof(float));
}
#ifdef DEBUG
auto start0 = std::chrono::high_resolution_clock::now();
#endif
//for(int i=0; i<IMAGE_SIZE; i++) {
for(int i=0; i<FILTER_SIZE-1; i++) {
for(int j=0; j<IN_DEPTH; j++) {
for(int k=0; k<IMAGE_SIZE; k++) {
data_in_merlin[0][i*IMAGE_SIZE*IN_DEPTH + j*IMAGE_SIZE + k] = data_in[i*IMAGE_SIZE*IMAGE_SIZE + (j+STEP*0)*IMAGE_SIZE + k];
data_in_merlin[1][i*IMAGE_SIZE*IN_DEPTH + j*IMAGE_SIZE + k] = data_in[i*IMAGE_SIZE*IMAGE_SIZE + (j+STEP*1)*IMAGE_SIZE + k];
data_in_merlin[2][i*IMAGE_SIZE*IN_DEPTH + j*IMAGE_SIZE + k] = data_in[i*IMAGE_SIZE*IMAGE_SIZE + (j+STEP*2)*IMAGE_SIZE + k];
data_in_merlin[3][i*IMAGE_SIZE*IN_DEPTH + j*IMAGE_SIZE + k] = data_in[i*IMAGE_SIZE*IMAGE_SIZE + (j+STEP*3)*IMAGE_SIZE + k];
}
}
}
#ifdef DEBUG
auto diff0 = std::chrono::high_resolution_clock::now() - start0;
auto t0 = std::chrono::duration_cast<std::chrono::nanoseconds>(diff0);
std::cout << "Data prepare time: " << t0.count() << std::endl;
#endif
// filter only need to copy once
#ifdef DEBUG
printf("[Merlin Info] Start %s data for %s, data size = %d...\n", "copy in", "filter", FILTER_IN_LENGTH * sizeof(float ));
fflush(stdout);
#endif
for (int j = 0; j < PE; j++) {
m_q[j]->enqueueWriteBuffer(*buffer_filter[j], CL_TRUE,
0,
FILTER_IN_LENGTH * sizeof(float),
filter);
// memcpy(filter_align[j].data(), filter, FILTER_IN_LENGTH*sizeof(float));
// m_q[j]->enqueueMigrateMemObjects({*(buffer_filter[j])}, 0);
}
int flag = 0;
for (int i = 0; i < OUT_IMAGE_SIZE + OVERLAP; i++) {
// for (int i = 0; i < 2 + OVERLAP; i++) {
for (int j = 0; j < PE; j++) {
int queue_index = flag % (OVERLAP*PE);
int overlap_index = (flag/PE) % OVERLAP;
int pe_index = j;
//printf("queue_index = %d, overlap_index = %d, pe_index = %d\n", queue_index, overlap_index, pe_index);
if (i > 1) {
#ifdef DEBUG
//printf("Wait finish for queue %d\n", queue_index);
#endif
m_q[queue_index]->finish();
//printf("memcpy out index = %d, offset = %d, size = %d\n", pe_index, (i-OVERLAP)*OUT_SIZE_TILE, OUT_SIZE_ONE_CALL);
//memcpy(data_out_merlin[pe_index] + (i-OVERLAP)*OUT_SIZE_ONE_CALL, output_align[pe_index][overlap_index].data(), OUT_SIZE_ONE_CALL*sizeof(float));
if (j == PE - 1 ) {
memcpy(data_out + (i-OVERLAP)*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE+j*OUT_SIZE_ONE_CALL,
output_align[pe_index][overlap_index].data(),
LAST_OUT_SIZE_ONE_CALL*sizeof(float));
} else {
memcpy(data_out + (i-OVERLAP)*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE+j*OUT_SIZE_ONE_CALL,
output_align[pe_index][overlap_index].data(),
OUT_SIZE_ONE_CALL*sizeof(float));
}
// memcpy(data_out + (i-OVERLAP)*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE+j*OUT_SIZE_ONE_CALL,
// output_align[pe_index][overlap_index].data(),
// OUT_SIZE_ONE_CALL*sizeof(float));
#ifdef DEBUG
//printf("index = %d, data_out_kernel host[%d] = %15.6f\n", i, 0, (output_align[pe_index][overlap_index].data())[0]);
#endif
}
if (i < OUT_IMAGE_SIZE) {
#ifdef DEBUG
printf("Do compute for one plane %d, on queue %d\n", i, queue_index);
#endif
//printf("memcpy in index = %d, offset = %d, size = %d\n", pe_index, i*IN_DEPTH*IMAGE_SIZE, IN_SIZE_ONE_CALL);
//if(i == 0 && j == 0) {
// for(int k=0; k<IN_SIZE_ONE_CALL; k++) {
// printf("org k = %d, data = %f\n", k, data_in_merlin[pe_index][k]);
// }
//}
//if(i == 0 && j == 0) {
// printf("offset1 = %d, offset2 = %d\n",
// (i+FILTER_SIZE-1)*IN_DEPTH*IMAGE_SIZE,
// (i+FILTER_SIZE-1)*IMAGE_SIZE*IMAGE_SIZE + STEP*j*IMAGE_SIZE);
//}
memcpy(data_in_merlin[pe_index] + (i+FILTER_SIZE-1)*IN_DEPTH*IMAGE_SIZE,
data_in + (i+FILTER_SIZE-1)*IMAGE_SIZE*IMAGE_SIZE + STEP*j*IMAGE_SIZE,
IN_DEPTH*IMAGE_SIZE*sizeof(float));
//if(i == 0 && j == 0) {
// for(int k=0; k<IN_SIZE_ONE_CALL; k++) {
// printf("new k = %d, data = %f\n", k, data_in_merlin[pe_index][k]);
// }
//}
memcpy(input_align[pe_index][overlap_index].data(),
data_in_merlin[pe_index] + i*IN_DEPTH*IMAGE_SIZE,
IN_SIZE_ONE_CALL*sizeof(float));
//if(i == 0 && j == 0) {
//for(int x = 0; x < IN_SIZE_ONE_CALL; x++) {
// printf("input_align[%d] = %f\n", x, (input_align[pe_index][overlap_index].data())[x]);
//}
//}
m_q[queue_index]->enqueueMigrateMemObjects({*(buffer_input[pe_index][overlap_index])}, 0);
conv_kernel[pe_index]->setArg(0, *(buffer_input[pe_index][overlap_index]));
conv_kernel[pe_index]->setArg(1, *(buffer_filter[pe_index]));
conv_kernel[pe_index]->setArg(2, *(buffer_output[pe_index][overlap_index]));
m_q[queue_index]->enqueueTask(*conv_kernel[pe_index]);
m_q[queue_index]->enqueueMigrateMemObjects({*(buffer_output[pe_index][overlap_index])}, CL_MIGRATE_MEM_OBJECT_HOST);
}
flag++;
}
#ifdef DEBUG
printf("\n");
#endif
}
for (int i = 0; i < PE * OVERLAP; i++) {
m_q[i]->finish();
}
/*
printf("Start merge out data\n");
for(int i=0; i<OUT_IMAGE_SIZE; i++) {
for(int j=0; j<OUT_IMAGE_SIZE; j++) {
for(int k=0; k<OUT_IMAGE_SIZE; k++) {
if(j < OUT_DEPTH) {
data_out[i*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE + j*OUT_IMAGE_SIZE + k] \
= data_out_merlin[0][i*OUT_IMAGE_SIZE*STEP + j*OUT_IMAGE_SIZE + k];
} else if(j < OUT_DEPTH * 2) {
data_out[i*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE + j*OUT_IMAGE_SIZE + k] \
= data_out_merlin[1][i*OUT_IMAGE_SIZE*STEP + (j-OUT_DEPTH)*OUT_IMAGE_SIZE + k];
} else if(j < OUT_DEPTH * 3) {
data_out[i*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE + j*OUT_IMAGE_SIZE + k] \
= data_out_merlin[2][i*OUT_IMAGE_SIZE*STEP + (j-OUT_DEPTH*2)*OUT_IMAGE_SIZE + k];
} else {
data_out[i*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE + j*OUT_IMAGE_SIZE + k] \
= data_out_merlin[3][i*OUT_IMAGE_SIZE*STEP + (j-OUT_DEPTH*3)*OUT_IMAGE_SIZE + k];
}
}
}
}
*/
}
void __merlin_conv_3d_kernel(float data_in[LENGTH_IN_TILE],float filter[FILTER_IN_LENGTH],float data_out[LENGTH_OUT_TILE]) {
__merlinwrapper_conv_3d_kernel(data_in,filter,data_out);
}
| 50.056818
| 163
| 0.539955
|
FCS-holding
|
8442f55fa028083cadf0b9d9008b6ee0bc7e20dd
| 49,789
|
cc
|
C++
|
sim/models/actuators/ground_station_v2.cc
|
leozz37/makani
|
c94d5c2b600b98002f932e80a313a06b9285cc1b
|
[
"Apache-2.0"
] | 1,178
|
2020-09-10T17:15:42.000Z
|
2022-03-31T14:59:35.000Z
|
sim/models/actuators/ground_station_v2.cc
|
leozz37/makani
|
c94d5c2b600b98002f932e80a313a06b9285cc1b
|
[
"Apache-2.0"
] | 1
|
2020-05-22T05:22:35.000Z
|
2020-05-22T05:22:35.000Z
|
sim/models/actuators/ground_station_v2.cc
|
leozz37/makani
|
c94d5c2b600b98002f932e80a313a06b9285cc1b
|
[
"Apache-2.0"
] | 107
|
2020-09-10T17:29:30.000Z
|
2022-03-18T09:00:14.000Z
|
// Copyright 2020 Makani Technologies LLC
//
// 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 "sim/models/actuators/ground_station_v2.h"
#include <math.h>
#include <algorithm>
#include <limits>
#include "common/c_math/geometry.h"
#include "common/c_math/mat3.h"
#include "common/c_math/util.h"
#include "control/sensor_util.h"
#include "control/system_params.h"
#include "control/vessel_frame.h"
#include "sim/sim_telemetry.h"
namespace {
// Attenuate a velocity command and apply a dead zone as the position target is
// approached. This corresponds to the McLaren Simulink block "Attenuate
// angular velocity demand as angular target is approached".
static double AttenuateAndApplyDeadZone(double vel_cmd, double pos_error,
double max_accel,
double dead_zone_half_width) {
// The attenuation strategy is based on the standard relationship for a system
// under constant acceleration:
// 2 * a * (x - x_0) = v^2 - v_0^2.
// Our choice of a maximum velocity corresponds to choosing v_0 such that
// pos_error = (x - x_0) will be zero when the velocity is zero if the system
// is decelerated as quickly as allowed.
double v_max = Sqrt(fabs(pos_error) * 2.0 * max_accel);
double modified_cmd = Saturate(vel_cmd, -v_max, v_max);
// This is equivalent to a standard Simulink dead zone:
// https://www.mathworks.com/help/simulink/slref/deadzone.html.
double dead_zone_upper = Sqrt(fabs(dead_zone_half_width) * 2.0 * max_accel);
if (modified_cmd < -dead_zone_upper) {
modified_cmd += dead_zone_upper;
} else if (modified_cmd < dead_zone_upper) {
modified_cmd = 0.0;
} else {
modified_cmd -= dead_zone_upper;
}
return modified_cmd;
}
} // namespace
Gs02ModeController::Gs02ModeController(const std::string &name__, double ts)
: Model(name__, ts),
azi_pos_(new_discrete_state(), "azi_pos", ts_, 0.0),
azi_vel_(new_discrete_state(), "azi_vel", ts_, 0.0),
drum_pos_(new_discrete_state(), "drum_pos", ts_, 0.0),
drum_vel_(new_discrete_state(), "drum_pos", ts_, 0.0),
wing_azi_(new_discrete_state(), "wing_azi", ts_, 0.0),
enabled_(new_discrete_state(), "enabled", ts_, false),
azi_vel_cmd_(new_discrete_state(), "azi_vel_cmd", ts_, 0.0),
drum_vel_cmd_(new_discrete_state(), "drum_vel_cmd", ts_, 0.0) {}
void Gs02ModeController::SetCommonInputs(double t, double azi_pos,
double azi_vel, double drum_pos,
double drum_vel, double wing_azi) {
azi_pos_.DiscreteUpdate(t, azi_pos);
azi_vel_.DiscreteUpdate(t, azi_vel);
drum_pos_.DiscreteUpdate(t, drum_pos);
drum_pos_.DiscreteUpdate(t, drum_vel);
wing_azi_.DiscreteUpdate(t, wing_azi);
}
ReelController::ReelController(const Gs02SimMcLarenControllerParams ¶ms,
double drum_radius)
: Gs02ModeController("Reel controller", params.ts),
params_(params),
drum_radius_(drum_radius),
drum_linear_vel_cmd_from_wing_(new_discrete_state(),
"drum_linear_vel_cmd_from_wing", params.ts,
0.0),
azi_cmd_z_(new_discrete_state(), "azi_cmd_z", params.ts, {{0.0, 0.0}}),
azi_cmd_delay_state_(new_discrete_state(), "azi_cmd_delay_state",
params.ts, 0.0),
azi_cmd_dead_zone_(new_discrete_state(), "azi_cmd_dead_zone", params.ts,
0.0),
azi_in_dead_zone_z1_(new_discrete_state(), "azi_in_dead_zone_z1",
params.ts, false),
azi_delay_state_(new_discrete_state(), "azi_delay_state", params.ts, 0.0),
azi_rate_limit_state_(new_discrete_state(), "azi_rate_limit_state",
params.ts, 0.0),
drum_vel_rate_limit_state_(new_discrete_state(),
"drum_vel_rate_limit_state", params.ts, 0.0),
levelwind_engaged_(new_discrete_state(), "levelwind_engaged", params.ts,
true) {
SetupDone();
}
void ReelController::DiscreteStepHelper(double t) {
if (!enabled_.val()) {
azi_cmd_z_.DiscreteUpdate(t, azi_cmd_z_.val());
azi_cmd_delay_state_.DiscreteUpdate(t, azi_cmd_delay_state_.val());
azi_delay_state_.DiscreteUpdate(t, azi_vel_.val());
azi_rate_limit_state_.DiscreteUpdate(t, azi_vel_.val());
drum_vel_rate_limit_state_.DiscreteUpdate(t, drum_vel_.val());
return;
}
{ // Generate azimuth velocity command.
const double target_pos =
wing_azi_.val() + params_.reel.azi_offset_from_wing;
// Unwrap the target position toward the state of the command filter.
// This prevents the perch from taking the long way around the circle when
// the target azimuth goes through a 2*pi discontinuity.
double unwrapped_target_pos = azi_cmd_delay_state_.val();
double twopimoddiff =
fmod(azi_cmd_delay_state_.val() - target_pos, 2.0 * PI);
if (twopimoddiff > PI) {
unwrapped_target_pos -= twopimoddiff - 2.0 * PI;
} else {
unwrapped_target_pos -= twopimoddiff;
}
// Apply the 2nd order command filter.
std::array<double, 2> azi_cmd_z = azi_cmd_z_.val();
double azi_cmd =
Lpf2(unwrapped_target_pos, params_.reel.azi_cmd_filter_omega / 2.0 / PI,
params_.reel.azi_cmd_filter_zeta, params_.ts, azi_cmd_z.data());
azi_cmd_z_.DiscreteUpdate(t, azi_cmd_z);
// Acquire the delayed value, and then update it.
double output_cmd = azi_delay_state_.val();
double azi_vel_cmd = (azi_cmd - azi_cmd_delay_state_.val()) / params_.ts;
azi_cmd_delay_state_.DiscreteUpdate(t, azi_cmd);
double pos_error = Wrap(azi_cmd - azi_pos_.val(), -PI, PI);
// Apply dead zone. The "effective dead zone" controls the azimuth to within
// a tight envelope around the target (as a fraction of the commanded dead
// zone), then expands the envelope to the full specified dead zone. Doing
// this prevents jitter at the edges of the dead zone.
double effective_dead_zone =
azi_in_dead_zone_z1_.val()
? azi_cmd_dead_zone_.val()
: azi_cmd_dead_zone_.val() * params_.reel.little_dead_zone;
if (fabs(pos_error) <= effective_dead_zone) {
azi_in_dead_zone_z1_.DiscreteUpdate(t, true);
pos_error = 0.0;
} else {
azi_in_dead_zone_z1_.DiscreteUpdate(t, false);
}
double pos_error_saturated = Saturate(
pos_error, -params_.reel.azi_error_max, params_.reel.azi_error_max);
azi_delay_state_.DiscreteUpdate(
t, params_.reel.azi_vel_cmd_kp * pos_error_saturated +
params_.reel.azi_vel_cmd_ff_gain * azi_vel_cmd);
// Apply the rate limit.
double cmd_z1 = azi_rate_limit_state_.val();
output_cmd =
RateLimit(output_cmd, -params_.reel.azi_vel_cmd_rate_limit,
params_.reel.azi_vel_cmd_rate_limit, params_.ts, &cmd_z1);
azi_rate_limit_state_.DiscreteUpdate(t, cmd_z1);
azi_vel_cmd_.DiscreteUpdate(t, output_cmd);
}
{ // Generate drum velocity command.
double cmd = drum_linear_vel_cmd_from_wing_.val() / drum_radius_;
if (!levelwind_engaged_.val()) {
// Stop the winch if the levelwind disengages.
cmd = 0.0;
}
double pos_error;
if (cmd > 0.0) {
pos_error = params_.reel.drum_angle_upper_limit - drum_pos_.val();
} else {
pos_error = -std::numeric_limits<double>::infinity();
}
// Clip the velocity command if it's in the wrong direction.
if (cmd * pos_error < 0) cmd = 0.0;
cmd = AttenuateAndApplyDeadZone(
cmd, params_.reel.drum_angle_upper_limit - drum_pos_.val(),
params_.reel.max_drum_accel, 0.0);
// Apply the rate limit.
double cmd_z1 = drum_vel_rate_limit_state_.val();
cmd = RateLimit(cmd, -params_.reel.max_drum_accel,
params_.reel.max_drum_accel, params_.ts, &cmd_z1);
drum_vel_rate_limit_state_.DiscreteUpdate(t, cmd_z1);
drum_vel_cmd_.DiscreteUpdate(t, cmd);
}
}
TransformController::TransformController(
const Gs02SimMcLarenControllerParams ¶ms)
: Gs02ModeController("Transform controller", params.ts),
params_(params.transform),
azi_rate_limit_state_(new_discrete_state(), "azi_rate_limit_state",
params.ts, 0.0),
winch_rate_limit_state_(new_discrete_state(), "winch_rate_limit_state",
params.ts, 0.0),
detwist_pos_cmd_(new_discrete_state(), "detwist_pos_cmd", ts_, 0.0),
unpause_transform_(new_discrete_state(), "unpause_transform", params.ts,
false),
transform_stage_(new_discrete_state(), "transform_stage", params.ts, 0),
ht2reel_(new_discrete_state(), "ht2reel", params.ts, false),
transform_complete_(new_discrete_state(), "transform_complete", params.ts,
false) {
SetupDone();
}
void TransformController::Publish() const {
sim_telem.gs02.transform_stage = transform_stage_.val();
}
void TransformController::DiscreteStepHelper(double t) {
if (!enabled_.val()) {
azi_rate_limit_state_.DiscreteUpdate(t, azi_vel_.val());
winch_rate_limit_state_.DiscreteUpdate(t, drum_vel_.val());
transform_complete_.DiscreteUpdate(t, false);
transform_stage_.DiscreteUpdate(t, 0);
return;
}
const int32_t s = transform_stage_.val();
bool azi_target_satisfied;
{ // Azimuth
double target = wing_azi_.val() + params_.azi_offset_from_wing;
double tol;
if (ht2reel_.val()) {
target += params_.azi_targets_ht2reel[s];
tol = params_.azi_tols_ht2reel[s];
} else {
target += params_.azi_targets_reel2ht[s];
tol = params_.azi_tols_reel2ht[s];
}
double pos_error = Wrap(target - azi_pos_.val(), -PI, PI);
double vel_cmd = Sign(pos_error) * params_.azi_nominal_vel;
vel_cmd = AttenuateAndApplyDeadZone(
vel_cmd, pos_error, params_.azi_decel_ratio * params_.azi_max_accel,
params_.azi_dead_zone_half_width);
double cmd_z1 = azi_rate_limit_state_.val();
vel_cmd = RateLimit(vel_cmd, -params_.azi_max_accel, params_.azi_max_accel,
ts_, &cmd_z1);
azi_rate_limit_state_.DiscreteUpdate(t, vel_cmd);
azi_vel_cmd_.DiscreteUpdate(t, vel_cmd);
azi_target_satisfied = -tol < pos_error && pos_error < tol;
}
bool winch_target_satisfied;
{ // Winch
double target, tol;
if (ht2reel_.val()) {
target = params_.winch_targets_ht2reel[transform_stage_.val()];
tol = params_.winch_tols_ht2reel[transform_stage_.val()];
} else {
target = params_.winch_targets_reel2ht[transform_stage_.val()];
tol = params_.winch_tols_reel2ht[transform_stage_.val()];
}
double pos_error = target - drum_pos_.val();
double vel_cmd = Sign(pos_error) * params_.winch_nominal_vel;
vel_cmd = AttenuateAndApplyDeadZone(
vel_cmd, pos_error, params_.winch_decel_ratio * params_.winch_max_accel,
params_.winch_dead_zone_half_width);
double cmd_z1 = winch_rate_limit_state_.val();
vel_cmd = RateLimit(vel_cmd, -params_.winch_max_accel,
params_.winch_max_accel, ts_, &cmd_z1);
winch_rate_limit_state_.DiscreteUpdate(t, vel_cmd);
drum_vel_cmd_.DiscreteUpdate(t, vel_cmd);
winch_target_satisfied =
target - tol < drum_pos_.val() && drum_pos_.val() < target + tol;
}
{ // Generate detwist position command.
double target;
if (ht2reel_.val()) {
target = params_.detwist_targets_ht2reel[transform_stage_.val()];
} else {
target = params_.detwist_targets_reel2ht[transform_stage_.val()];
}
detwist_pos_cmd_.DiscreteUpdate(t, target);
}
// Update the transform stage and determine if the transform is complete.
bool stage_complete = azi_target_satisfied && winch_target_satisfied;
int32_t next_stage, last_stage;
if (ht2reel_.val()) {
// HighTension to Reel: Stage progression is 0, 1, 2, 3, 4.
last_stage = 4;
next_stage = std::min(s + 1, last_stage);
// Wait at the end of stages 1 and 2 unless unpaused.
if (!unpause_transform() && (s == 1 || s == 2)) {
stage_complete = false;
}
} else {
// Reel to HighTension: Stage progression is 0, 4, 3, 2, 1.
last_stage = 1;
next_stage = s == 0 ? 4 : std::max(s - 1, last_stage);
// Wait at the end of stage 3 unless unpaused.
if (!unpause_transform() && s == 3) {
stage_complete = false;
}
}
transform_complete_.DiscreteUpdate(t, s == last_stage && stage_complete);
transform_stage_.DiscreteUpdate(t, stage_complete ? next_stage : s);
}
void TransformController::StartTransform(double t, bool ht2reel) {
transform_stage_.DiscreteUpdate(t, 0);
ht2reel_.DiscreteUpdate(t, ht2reel);
transform_complete_.DiscreteUpdate(t, false);
}
HighTensionController::HighTensionController(
const Gs02SimMcLarenControllerParams ¶ms)
: Gs02ModeController("High tension controller", params.ts),
params_(params.high_tension),
active_braking_first_entry_(true),
active_braking_t0_(0.0),
angular_rate_tol_(1.7e-4),
hpu_cmd_change_t0_(0.0),
hpu_delay_(0.4),
ht_ts_(params.ts),
brake_torque_(new_discrete_state(), "brake_torque", params.ts, 0.0),
tether_torque_(new_discrete_state(), "tether_torque", params.ts, 0.0),
brake_torque_cmd_(new_discrete_state(), "brake_torque_cmd", params.ts,
0.0),
n_hpu_mode_demand_(new_discrete_state(), "n_hpu_mode_demand", params.ts,
kBrakesOn),
azi_velocity_dir_(new_discrete_state(), "azi_velocity_dir", params.ts,
0.0),
n_state_machine_(new_discrete_state(), "n_state_machine", params.ts,
kBaseCase),
total_torque_(new_discrete_state(), "total_torque", params.ts, 0.0),
n_hpu_mode_(new_discrete_state(), "n_hpu_mode", params.ts, kBrakesOn),
n_hpu_mode_last_(new_discrete_state(), "n_hpu_mode_last", params.ts,
kBrakesOn),
a_error_(new_discrete_state(), "azimuth_error", params.ts, 0.0),
detwist_pos_cmd_(new_discrete_state(), "detwist_pos_cmd", ts_, 0.0),
detwist_pos_cmd_from_wing_(new_discrete_state(),
"detwist_pos_cmd_from_wing", params.ts, 0.0) {
SetupDone();
}
// The high-tension controller uses a brake plus the tether torque to
// semi-actively control the ground station aziumth in the high-tension mode
// i.e. when the kite is in crosswind flight.
void HighTensionController::DiscreteStepHelper(double t) {
// Run the controller state logic which emulates the GS02 Simulink code.
RunControlSwitchingLogic(t);
// Run the GS02 azimuth control laws and update the HPU and brake models.
RunControlLaw(t);
// Generate detwist position command.
detwist_pos_cmd_.DiscreteUpdate(t, detwist_pos_cmd_from_wing_.val());
}
// The high-tension controller switching logic as implemented in the GS02
// Simulink state-flow code.
void HighTensionController::RunControlSwitchingLogic(double t) {
// n_state_machine_val keeps track of the current state machine case.
static SwitchingLogicState n_state_machine_val = kBaseCase;
// a_error is the error between the flight circle center azimuth and the GS02
// azimuth less Pi i.e. the GS needs to be pointed -Pi from its reference
// azimuth in crosswind.
a_error_.DiscreteUpdate(
t, Wrap(wing_azi_.val() - azi_pos_.val() - M_PI, -PI, PI));
switch (n_state_machine()) {
case kBaseCase:
azi_velocity_dir_.DiscreteUpdate(t, 0.0);
n_hpu_mode_demand_.DiscreteUpdate(t, kBrakesOn);
if ((tether_torque() > params_.m_max_azi_ht) &&
(a_error() > params_.a_control_threshold_azi_ht)) {
n_state_machine_val = kWaitForPositiveTetherOverload;
}
if ((tether_torque() < -params_.m_max_azi_ht) &&
(a_error() < -params_.a_control_threshold_azi_ht)) {
n_state_machine_val = kWaitForNegativeTetherOverload;
}
n_state_machine_.DiscreteUpdate(t, n_state_machine_val);
break;
case kWaitForPositiveTetherOverload:
azi_velocity_dir_.DiscreteUpdate(t, 0.0);
n_hpu_mode_demand_.DiscreteUpdate(t, kBrakesOn);
if (tether_torque() > params_.m_control_threshold_azi_ht) {
n_state_machine_val = kWaitForHpuPositive;
}
n_state_machine_.DiscreteUpdate(t, n_state_machine_val);
break;
case kWaitForHpuPositive:
azi_velocity_dir_.DiscreteUpdate(t, 0.0);
n_hpu_mode_demand_.DiscreteUpdate(t, kBrakesRegulated);
if (n_hpu_mode() == kBrakesRegulated) {
n_state_machine_val = kAzimuthPositiveRotation;
}
if (tether_torque() < params_.m_control_threshold_azi_ht) {
n_state_machine_val = kWaitForPositiveTetherOverload;
}
n_state_machine_.DiscreteUpdate(t, n_state_machine_val);
break;
case kAzimuthPositiveRotation:
azi_velocity_dir_.DiscreteUpdate(t, params_.n_demand_azi_ht);
// Command zero azimuth rate when close to the commanded azimuth.
if ((fabs(a_error()) < params_.a_control_tolerance_azi_ht) ||
a_error() < 0.0) {
n_state_machine_val = kActiveBraking;
active_braking_first_entry_ = true;
} else if (a_error() < 0.0) {
n_state_machine_val = kAzimuthNegativeRotation;
}
n_state_machine_.DiscreteUpdate(t, n_state_machine_val);
break;
case kActiveBraking:
azi_velocity_dir_.DiscreteUpdate(t, 0.0);
if (active_braking_first_entry_) {
active_braking_first_entry_ = false;
active_braking_t0_ = t;
}
// Command the brakes fully on if the azimuth rate is small enough.
if (fabs(azi_vel_.val()) < params_.n_control_tolerance_azi_ht) {
n_state_machine_val = kBaseCase;
}
// Command the brakes fully on if time in this mode is large enough.
if (t > (active_braking_t0_ + params_.t_threshold_wait_azi_ht)) {
n_state_machine_val = kBaseCase;
}
n_state_machine_.DiscreteUpdate(t, n_state_machine_val);
break;
case kWaitForNegativeTetherOverload:
azi_velocity_dir_.DiscreteUpdate(t, 0.0);
n_hpu_mode_demand_.DiscreteUpdate(t, kBrakesOn);
if (tether_torque() < -params_.m_control_threshold_azi_ht) {
n_state_machine_val = kWaitForHpuNegative;
}
n_state_machine_.DiscreteUpdate(t, n_state_machine_val);
break;
case kWaitForHpuNegative:
azi_velocity_dir_.DiscreteUpdate(t, 0.0);
n_hpu_mode_demand_.DiscreteUpdate(t, kBrakesRegulated);
if (tether_torque() > -params_.m_control_threshold_azi_ht) {
n_state_machine_val = kWaitForNegativeTetherOverload;
}
if (n_hpu_mode() == kBrakesRegulated) {
n_state_machine_val = kAzimuthNegativeRotation;
}
n_state_machine_.DiscreteUpdate(t, n_state_machine_val);
break;
case kAzimuthNegativeRotation:
azi_velocity_dir_.DiscreteUpdate(t, -params_.n_demand_azi_ht);
// Command zero azimuth rate when close to the commanded azimuth.
if ((fabs(a_error()) < params_.a_control_tolerance_azi_ht) ||
a_error() > 0.0) {
n_state_machine_val = kActiveBraking;
active_braking_first_entry_ = true;
} else if (a_error() > 0.0) {
n_state_machine_val = kAzimuthPositiveRotation;
}
n_state_machine_.DiscreteUpdate(t, n_state_machine_val);
break;
default: {};
}
}
void HighTensionController::RunBrakeModel(double t) {
double brake_torque_val = brake_torque_cmd();
double total_torque_val = 0.0;
// Check if the brake torque is the same sign as the tether torque
// (this is not physical). If so, then set the brake torque to zero. The
// controller sign will eventually change.
// Additionally, check that the brake torque is not higher than the tether
// torque. This would not be a phisically possible scenario.
if (tether_torque() * brake_torque_val > 0.0) {
brake_torque_val = 0.0;
} else if (fabs(brake_torque_val) > fabs(tether_torque())) {
brake_torque_val = -tether_torque();
}
// Keep the brake torque on for a few hundred milliseconds after
// n_state_machine goes to zero to kill the residual angular rate (we cannot
// instantaneously set it to zero because we only have finite brake torque).
if ((n_state_machine() == kBaseCase) && (n_hpu_mode() == kBrakesRegulated)) {
// Still have some residual rate so hold the last total torque.
if (fabs(azi_vel_.val()) > angular_rate_tol_) {
brake_torque_val = total_torque() - tether_torque();
} else { // Residual rate is small but n_hpu_mode != 0 yet so lock the
// brake.
brake_torque_val = -tether_torque();
}
} else { // Update last total torque value.
total_torque_val = tether_torque() + brake_torque_val;
}
brake_torque_.DiscreteUpdate(t, brake_torque_val);
total_torque_.DiscreteUpdate(t, total_torque_val);
}
// This function is a simple model of the ground station HPU controller. The
// model is a time delay between the command and state.
void HighTensionController::RunHpuModel(double t) {
if (n_hpu_mode_last_.val() != n_hpu_mode_demand()) { // HPU demand changed.
hpu_cmd_change_t0_ = t;
}
if (t > hpu_cmd_change_t0_ + hpu_delay_) { // Update HPU mode after delay.
n_hpu_mode_.DiscreteUpdate(t, n_hpu_mode_demand());
}
n_hpu_mode_last_.DiscreteUpdate(t, n_hpu_mode_demand());
}
// Run the high-tension closed-loop controller.
void HighTensionController::RunControlLaw(double t) {
double brake_torque_cmd_val = 0.0; // Brake torque command [N-m].
double azi_omega_cmd = 0.0; // Azimuth angular rate command [rad/s].
double k_omega = 0.0; // Angular rate loop gain [Nm/(rad/s)].
double total_torque_cmd = 0.0; // Total torque command [N-m].
// Brakes reguated mode i.e. closed loop control on speed.
if (n_hpu_mode_demand() == kBrakesRegulated) {
if (fabs(azi_velocity_dir()) < params_.test_threshold) {
azi_omega_cmd = 0.0;
k_omega = params_.k_stop;
} else if (fabs(azi_velocity_dir() - params_.n_demand_azi_ht) <
params_.test_threshold) {
azi_omega_cmd = params_.omega_nom;
k_omega = params_.k_spin;
} else if (fabs(azi_velocity_dir() + params_.n_demand_azi_ht) <
params_.test_threshold) {
azi_omega_cmd = -params_.omega_nom;
k_omega = params_.k_spin;
} else {
azi_omega_cmd = 0.0;
k_omega = params_.k_stop;
}
// Compute the brake torque command based on this control law.
total_torque_cmd = k_omega * (azi_omega_cmd - azi_vel_.val());
brake_torque_cmd_val = total_torque_cmd - tether_torque();
} else { // Do not allow net torque on the azimuth as brakes are fully on.
brake_torque_cmd_val = -tether_torque();
}
// Update brake torque command.
brake_torque_cmd_.DiscreteUpdate(t, brake_torque_cmd_val);
// Run a model of the GS02 brake.
RunBrakeModel(t);
// Run a simple model of the GS02 HPU (Hydraulic Power Unit).
RunHpuModel(t);
// Update azimuth and drum velocity commands.
azi_vel_cmd_.DiscreteUpdate(
t, total_torque() / mclarenparams().Iz_gndstation * ht_ts_);
drum_vel_cmd_.DiscreteUpdate(t, 0.0);
}
GroundStationV2Base::GroundStationV2Base(const ReferenceFrame &ned_frame,
const ReferenceFrame &parent_frame,
const Gs02Params ¶ms,
const Gs02SimParams &sim_params__)
: Actuator("GS02"),
params_(params),
sim_params_(sim_params__),
racetrack_integrator_(params, sim_params__),
ned_frame_(ned_frame),
parent_frame_(parent_frame),
azi_cmd_target_(new_derived_value(), "azi_cmd_target"),
azi_cmd_dead_zone_(new_derived_value(), "azi_cmd_dead_zone"),
drum_linear_vel_cmd_from_wing_(new_derived_value(),
"drum_linear_vel_cmd_from_wing"),
detwist_pos_cmd_from_wing_(new_derived_value(),
"detwist_pos_cmd_from_wing"),
mode_cmd_(new_derived_value(), "mode_cmd"),
tether_force_g_(new_derived_value(), "tether_force_g"),
unpause_transform_(new_derived_value(), "unpause_transform"),
levelwind_engaged_(new_derived_value(), "levelwind_engaged"),
tether_force_p_(kVec3Zero),
gsg_pos_p_(kVec3Zero),
mode_(new_discrete_state(), "mode", 0.0, kGroundStationModeReel),
transform_stage_(new_discrete_state(), "transform_stage", 0.0, 0),
platform_frame_(new_derived_value(), "platform_frame"),
dcm_v2p_(new_derived_value(), "dcm_v2p"),
wd0_frame_(new_derived_value(), "wd_frame"),
wd_frame_(new_derived_value(), "wd_frame"),
gsg0_frame_(new_derived_value(), "gsg0_frame"),
panel_frame_(new_derived_value(), "panel_frame"),
panel_surface_(this->panel_frame_.val_unsafe(), nullptr) {
panel_surface_.set_collision_func(
[this](const Vec3 &contactor_pos_panel, Vec3 *collision_pos) -> bool {
return ContactPerchPanel(contactor_pos_panel, platform_frame_.val(),
panel_frame_.val(), sim_params().panel,
collision_pos);
});
}
void GroundStationV2::Init(double azimuth, double drum_angle__) {
platform_azi_.Clear();
platform_azi_.set_val(azimuth);
drum_angle_.Clear();
drum_angle_.set_val(drum_angle__);
ClearDerivedValues();
UpdateDerivedStates();
}
void GroundStationV2Base::SetLevelwindEngaged(double tether_elevation) {
bool is_engaged = false;
bool levelwind_in_use = false;
switch (mode()) {
case kGroundStationModeReel:
case kGroundStationModeManual:
levelwind_in_use = true;
break;
case kGroundStationModeTransform:
// TODO: It is also in use when transform stage == 0 during
// transform up.
levelwind_in_use = transform_stage() == 4;
break;
case kGroundStationModeHighTension:
break;
case kNumGroundStationModes:
default:
LOG(FATAL) << "Bad GS02 mode: " << static_cast<int32_t>(mode());
}
if (levelwind_in_use &&
tether_elevation >=
sim_params().min_levelwind_angle_for_tether_engagement) {
is_engaged = true;
}
levelwind_engaged_.set_val(is_engaged);
}
void GroundStationV2Base::SetFromAvionicsPackets(
const AvionicsPackets &avionics_packets) {
const ControllerCommandMessage &cmd = avionics_packets.command_message;
// The actual ground station reads from TetherDownMessage, so this isn't quite
// proper. But the benefit of simulating the core switches assembling
// TetherDownMessage is dubious.
azi_cmd_target_.set_val(cmd.gs_azi_target);
azi_cmd_dead_zone_.set_val(cmd.gs_azi_dead_zone);
drum_linear_vel_cmd_from_wing_.set_val(cmd.winch_velocity);
detwist_pos_cmd_from_wing_.set_val(cmd.detwist_position);
mode_cmd_.set_val(static_cast<GroundStationMode>(cmd.gs_mode_request));
unpause_transform_.set_val(cmd.gs_unpause_transform);
}
void GroundStationV2Base::UpdateDerivedStates() {
Mat3 dcm_vessel_to_platform;
// The GSv2 platform azimuth is defined as a heading with respect to the
// x-axis of the vessel frame.
// The parameter azi_ref_offset is defined to be exactly zero.
DCHECK_EQ(GetSystemParams()->ground_station.azi_ref_offset, 0.0);
AngleToDcm(platform_azi(), 0.0, 0.0, kRotationOrderZyx,
&dcm_vessel_to_platform);
Vec3 platform_omega;
Vec3Scale(&kVec3Z, platform_azi_vel(), &platform_omega);
platform_frame_.set_val(ReferenceFrame(parent_frame_, kVec3Zero, kVec3Zero,
dcm_vessel_to_platform,
platform_omega));
dcm_v2p_.set_val(dcm_vessel_to_platform);
// The winch drum frame's (wd) axes are aligned with the platform frame when
// the drum angle is zero.
wd0_frame_.set_val(ReferenceFrame(platform_frame_.val(),
params_.drum_origin_p, kMat3Identity));
Mat3 dcm_wd0_to_wd;
AngleToDcm(0.0, 0.0, drum_angle(), kRotationOrderZyx, &dcm_wd0_to_wd);
Vec3 drum_omega_vector;
Vec3Scale(&kVec3X, drum_omega(), &drum_omega_vector);
wd_frame_.set_val(ReferenceFrame(wd0_frame_.val(), kVec3Zero, kVec3Zero,
dcm_wd0_to_wd, drum_omega_vector));
Mat3 dcm_wd_to_gsg0;
CalcDcmWdToGsg0(params_.detwist_elevation, detwist_angle(), &dcm_wd_to_gsg0);
gsg0_frame_.set_val(
ReferenceFrame(wd_frame_.val(), params_.gsg_pos_drum, dcm_wd_to_gsg0));
panel_frame_.set_val(ReferenceFrame(platform_frame_.val(),
sim_params().panel.origin_pos_p,
sim_params().panel.dcm_p2panel));
}
void GroundStationV2::UpdateModeControllerCommands() {
switch (mode()) {
case kGroundStationModeReel:
azi_vel_cmd_.set_val(reel_controller_.azi_vel_cmd());
drum_vel_cmd_.set_val(reel_controller_.drum_vel_cmd());
detwist_vel_.set_val(0.0);
break;
case kGroundStationModeTransform:
azi_vel_cmd_.set_val(transform_controller_.azi_vel_cmd());
drum_vel_cmd_.set_val(transform_controller_.drum_vel_cmd());
detwist_vel_.set_val(
Saturate(sim_params().detwist_angle_kp *
(Wrap(Saturate(-drum_angle(), 0.0,
sim_params().mclaren.detwist_setpoint) -
detwist_angle(),
-PI, PI)),
-transform_controller_.detwist_max_vel(),
transform_controller_.detwist_max_vel()));
break;
case kGroundStationModeHighTension:
azi_vel_cmd_.set_val(high_tension_controller_.azi_vel_cmd());
drum_vel_cmd_.set_val(high_tension_controller_.drum_vel_cmd());
detwist_vel_.set_val(Saturate(
sim_params().detwist_angle_kp *
(Wrap(
high_tension_controller_.detwist_pos_cmd() - detwist_angle(),
-PI, PI)),
-high_tension_controller_.detwist_max_vel(),
high_tension_controller_.detwist_max_vel()));
break;
case kGroundStationModeManual:
case kNumGroundStationModes:
default:
LOG(FATAL) << "Bad GS02 mode: " << static_cast<int32_t>(mode());
}
}
void GroundStationV2::AddInternalConnections(ConnectionStore *connections) {
connections->Add(1, [this](double /*t*/) {
UpdateModeControllerCommands();
UpdateDerivedStates();
});
}
double GroundStationV2Base::CalcTetherFreeLength() const {
return CalcTetherFreeLengthInternal(drum_angle());
}
double GroundStationV2Base::CalcTetherFreeLengthInternal(
double drum_angle__) const {
double length = g_sys.tether->length;
const Gs02DrumAngles &angles =
GetSystemParams()->ground_station.gs02.drum_angles;
// Racetrack.
if (drum_angle__ < angles.racetrack_high) {
length -= racetrack_integrator_.WrappedLength(drum_angle__);
}
// Wide wrap section.
const double wide_wrap_high = angles.racetrack_low;
if (drum_angle__ < wide_wrap_high) {
length -= (wide_wrap_high - fmax(angles.wide_wrap_low, drum_angle__)) *
Sqrt(Square(sim_params().dx_dtheta_wide_wrap) +
Square(params_.drum_radius));
}
// Main wrap section.
const double main_wrap_high = angles.wide_wrap_low;
if (drum_angle__ < main_wrap_high) {
length -= (main_wrap_high - drum_angle__) *
Sqrt(Square(sim_params().dx_dtheta_main_wrap) +
Square(params_.drum_radius));
}
DCHECK(length >= 0.0);
return length;
}
double GroundStationV2Base::MinDrumAngle() const {
const Gs02DrumAngles &drum_angles =
GetSystemParams()->ground_station.gs02.drum_angles;
double main_wrap_length =
CalcTetherFreeLengthInternal(drum_angles.wide_wrap_low);
double main_wrap_dtheta =
main_wrap_length / Sqrt(Square(sim_params().dx_dtheta_main_wrap) +
Square(params_.drum_radius));
return drum_angles.wide_wrap_low - main_wrap_dtheta;
}
void GroundStationV2Base::CalcTetherAnchorPosVelNed(Vec3 *pos_ned,
Vec3 *vel_ned) const {
const Gs02DrumAngles &angles =
GetSystemParams()->ground_station.gs02.drum_angles;
// If the drum angle is above racetrack_high, the anchor point is the GSG.
if (drum_angle() > angles.racetrack_high) {
wd_frame_.val().TransformTo(ned_frame_, ReferenceFrame::kPosition,
params_.gsg_pos_drum, pos_ned);
ReferenceFrame at_gsg(wd_frame_.val(), params_.gsg_pos_drum);
at_gsg.TransformTo(ned_frame_, ReferenceFrame::kVelocity, kVec3Zero,
vel_ned);
return;
}
// We'll start at the GSG, and move along the wrapping.
const double inner_radius =
hypot(params_.gsg_pos_drum.y, params_.gsg_pos_drum.z);
Vec3 pos_wd0 = {params_.gsg_pos_drum.x, 0.0, -inner_radius};
Vec3 vel_wd0 = kVec3Zero;
// Racetrack.
if (drum_angle() < angles.racetrack_high) {
const double dx_dtheta =
(params_.gsg_pos_drum.x - sim_params().wrap_start_posx_drum) /
(angles.racetrack_high - angles.racetrack_low);
const double dz_dtheta = (-inner_radius + params_.drum_radius) /
(angles.racetrack_high - angles.racetrack_low);
const double dtheta =
fmax(drum_angle(), angles.racetrack_low) - angles.racetrack_high;
pos_wd0.x += dx_dtheta * dtheta;
pos_wd0.z += dz_dtheta * dtheta;
vel_wd0.x = dx_dtheta * drum_omega();
vel_wd0.z = dz_dtheta * drum_omega();
}
// Wide wrapping.
const double wide_wrap_high = angles.racetrack_low;
if (drum_angle() < wide_wrap_high) {
const double dtheta =
fmax(drum_angle(), angles.wide_wrap_low) - wide_wrap_high;
pos_wd0.x += sim_params().dx_dtheta_wide_wrap * dtheta;
vel_wd0.x = sim_params().dx_dtheta_wide_wrap * drum_omega();
vel_wd0.z = 0.0;
}
// Main wrapping.
const double main_wrap_high = angles.wide_wrap_low;
if (drum_angle() < main_wrap_high) {
pos_wd0.x +=
sim_params().dx_dtheta_main_wrap * (drum_angle() - main_wrap_high);
vel_wd0.x = sim_params().dx_dtheta_main_wrap;
vel_wd0.z = 0.0;
}
wd0_frame_.val().TransformTo(ned_frame_, ReferenceFrame::kPosition, pos_wd0,
pos_ned);
ReferenceFrame anchor_frame(wd0_frame_.val(), pos_wd0);
anchor_frame.TransformTo(ned_frame_, ReferenceFrame::kVelocity, vel_wd0,
vel_ned);
}
void GroundStationV2Base::TetherDirToAngles(const Vec3 &tether_dir_v,
double *tether_ele_v,
double *tether_azi_v,
double *gsg_yoke,
double *gsg_termination) const {
// TODO: Calibrate with real test data about where is the reference
// angle (yoke=termination=0) pointing to.
// Currently, the tether points away from the detwist plane along the -Z axis
// of gsg0 frame when GSG yoke and termination are 0.0. +yoke rotates around
// X axis and +termination rotates around Y axis.
// The local frame (X'Y'Z') rotates the gsg0 frame (XYZ) by 90 deg
// around Y-axis, so that the spherical azimuth (yoke) and elevation
// (termination) are phi and -theta, where (phi, theta, 0) are euler angles
// to rotate gsg0 frame to gsg2 frame in XYZ order.
// X' Tether
// X(Z') | /
// \ | /
// \ | /
// \|/_____ Y(Y')
// |
// |
// Z
*tether_ele_v = VecVToElevation(&tether_dir_v);
*tether_azi_v = VecVToAzimuth(&tether_dir_v);
Mat3 dcm_gsg0_to_local;
AngleToDcm(0.0, 0.5 * PI, 0.0, kRotationOrderZyx, &dcm_gsg0_to_local);
ReferenceFrame local_frame(gsg0_frame(), kVec3Zero, dcm_gsg0_to_local);
Vec3 tether_dir_local;
parent_frame_.RotateTo(local_frame, tether_dir_v, &tether_dir_local);
double r_unused;
CartToSph(&tether_dir_local, gsg_yoke, gsg_termination, &r_unused);
// The spherical elevation has the opposite sign of the rotational angle
// around Y-axis.
*gsg_termination = -*gsg_termination;
}
void GroundStationV2Base::Publish() const {
sim_telem.gs02.azimuth = platform_azi();
sim_telem.gs02.azimuth_vel = platform_azi_vel();
sim_telem.gs02.dcm_v2p = dcm_v2p();
sim_telem.gs02.drum_angle = drum_angle();
sim_telem.gs02.drum_omega = drum_omega();
sim_telem.gs02.levelwind_engaged = levelwind_engaged();
}
void GroundStationV2::Publish() const {
GroundStationV2Base::Publish();
sim_telem.gs02.mclaren_azi_vel_cmd = azi_vel_cmd_.val();
sim_telem.gs02.mclaren_drum_vel_cmd = drum_vel_cmd_.val();
sim_telem.gs02.mode = static_cast<int32_t>(mode());
sim_telem.gs02.detwist_vel = detwist_vel_.val();
sim_telem.gs02.detwist_angle =
Wrap(detwist_angle_.val(), 0,
PI * 2.0 * static_cast<double>(TETHER_DETWIST_REVS));
sim_telem.gs02.n_state_machine = high_tension_controller_.n_state_machine();
sim_telem.gs02.n_hpu_mode = high_tension_controller_.n_hpu_mode();
sim_telem.gs02.brake_torque = high_tension_controller_.brake_torque();
sim_telem.gs02.brake_torque_cmd = high_tension_controller_.brake_torque_cmd();
sim_telem.gs02.tether_torque = high_tension_controller_.tether_torque();
sim_telem.gs02.total_torque = high_tension_controller_.total_torque();
sim_telem.gs02.azi_velocity_dir = high_tension_controller_.azi_velocity_dir();
sim_telem.gs02.a_error = high_tension_controller_.a_error();
sim_telem.gs02.wing_azi = high_tension_controller_.wing_azi_val();
sim_telem.gs02.gs_azi = high_tension_controller_.azi_pos_val();
for (const Model *m : sub_models_) {
m->Publish();
}
}
GroundStationV2::GroundStationV2(const ReferenceFrame &ned_frame,
const ReferenceFrame &parent_frame,
const Gs02Params ¶ms,
const Gs02SimParams &sim_params__)
: GroundStationV2Base(ned_frame, parent_frame, params, sim_params__),
reel_controller_(sim_params__.mclaren, params.drum_radius),
transform_controller_(sim_params__.mclaren),
high_tension_controller_(sim_params__.mclaren),
platform_azi_(new_continuous_state(), "platform_azi", 0.0),
platform_azi_vel_(new_continuous_state(), "platform_azi_vel", 0.0),
drum_angle_(new_continuous_state(), "drum_angle", 0.0),
detwist_angle_(new_continuous_state(), "detwist_angle",
sim_params__.mclaren.detwist_setpoint),
drum_omega_(new_continuous_state(), "drum_omega", 0.0),
ddrum_omega_dt_(new_continuous_state(), "ddrum_omega_dt", 0.0),
azi_vel_cmd_(new_derived_value(), "azi_vel_cmd"),
drum_vel_cmd_(new_derived_value(), "drum_vel_cmd"),
detwist_vel_(new_derived_value(), "detwist_vel"),
mode_z1_(new_discrete_state(), "mode_z1", 0.0, kGroundStationModeReel),
ht2reel_(new_discrete_state(), "ht2reel", 0.0, false),
prox_sensor_active_(new_discrete_state(), "prox_sensor_active", 0.0,
false) {
set_sub_models(
{&reel_controller_, &transform_controller_, &high_tension_controller_});
UpdateDerivedStates();
SetupDone();
}
void GroundStationV2::CalcDerivHelper(double /*t*/) {
platform_azi_.set_deriv(platform_azi_vel());
platform_azi_vel_.set_deriv(sim_params().azi_accel_kp *
(azi_vel_cmd_.val() - platform_azi_vel()));
const double omega_n = sim_params().winch_drive_natural_freq;
const double zeta = sim_params().winch_drive_damping_ratio;
ddrum_omega_dt_.set_deriv(Square(omega_n) *
(drum_vel_cmd_.val() - drum_omega()) -
2.0 * zeta * omega_n * ddrum_omega_dt_.val());
drum_omega_.set_deriv(ddrum_omega_dt_.val());
drum_angle_.set_deriv(drum_omega());
detwist_angle_.set_deriv(detwist_vel_.val());
}
void GroundStationV2::DiscreteStepHelper(double t) {
// Update mode.
switch (mode()) {
case kGroundStationModeReel:
if (mode_cmd() == kGroundStationModeHighTension) {
set_mode(t, kGroundStationModeTransform);
ht2reel_.DiscreteUpdate(t, false);
}
break;
case kGroundStationModeHighTension:
if (mode_cmd() == kGroundStationModeReel) {
set_mode(t, kGroundStationModeTransform);
ht2reel_.DiscreteUpdate(t, true);
}
break;
case kGroundStationModeTransform:
if (transform_controller_.transform_complete()) {
set_mode(t, ht2reel_.val() ? kGroundStationModeReel
: kGroundStationModeHighTension);
}
break;
case kGroundStationModeManual:
case kNumGroundStationModes:
default:
LOG(FATAL) << "Bad GS02 mode: " << static_cast<int32_t>(mode());
}
DCHECK(azi_cmd_target() >= 0.0 && azi_cmd_target() <= 2.0 * M_PI);
reel_controller_.SetCommonInputs(t, platform_azi(), platform_azi_vel(),
drum_angle(), drum_omega(),
azi_cmd_target());
transform_controller_.SetCommonInputs(t, platform_azi(), platform_azi_vel(),
drum_angle(), drum_omega(),
azi_cmd_target());
high_tension_controller_.SetCommonInputs(t, platform_azi(),
platform_azi_vel(), drum_angle(),
drum_omega(), azi_cmd_target());
// Apply mode- and controller-specific inputs.
switch (mode()) {
case kGroundStationModeReel:
reel_controller_.Enable(t);
transform_controller_.Disable(t);
high_tension_controller_.Disable(t);
reel_controller_.set_azi_cmd_dead_zone(t, azi_cmd_dead_zone());
reel_controller_.set_drum_linear_vel_cmd_from_wing(
t, drum_linear_vel_cmd_from_wing());
reel_controller_.set_levelwind_engaged(t, levelwind_engaged());
set_transform_stage(t, 0);
break;
case kGroundStationModeTransform:
transform_controller_.Enable(t);
reel_controller_.Disable(t);
high_tension_controller_.Disable(t);
set_transform_stage(t, transform_controller_.stage());
transform_controller_.set_unpause_transform(t, unpause_transform());
if (mode() != mode_z1_.val()) {
transform_controller_.StartTransform(t, ht2reel_.val());
}
break;
case kGroundStationModeHighTension:
high_tension_controller_.set_tether_torque(t, gsg_pos_p(),
tether_force_p());
high_tension_controller_.Enable(t);
transform_controller_.Disable(t);
reel_controller_.Disable(t);
high_tension_controller_.set_detwist_pos_cmd_from_wing(
t, Wrap(detwist_pos_cmd_from_wing(), -PI, PI));
set_transform_stage(t, 0);
break;
case kGroundStationModeManual:
case kNumGroundStationModes:
default:
LOG(FATAL) << "Bad GS02 mode: " << static_cast<int32_t>(mode());
}
mode_z1_.DiscreteUpdate(t, mode());
// The proximity sensor activates when a sufficient portion of the tether has
// been reeled in.
prox_sensor_active_.DiscreteUpdate(
t, CalcTetherFreeLength() < sim_params().prox_sensor_tether_free_length);
}
HitlGroundStationV2::HitlGroundStationV2(const ReferenceFrame &ned_frame,
const ReferenceFrame &parent_frame,
const Gs02Params ¶ms,
const Gs02SimParams &sim_params__)
: GroundStationV2Base(ned_frame, parent_frame, params, sim_params__),
platform_azi_(new_continuous_state(), "platform_azi", 0.0),
platform_azi_vel_(new_continuous_state(), "platform_azi_vel", 0.0),
dplatform_azi_(new_discrete_state(), "dplatform_azi", 0.0, 0.0),
dplatform_azi_vel_(new_discrete_state(), "dplatform_azi_vel", 0.0, 0.0),
int_err_platform_azi_(new_discrete_state(), "int_err_platform_azi", 0.0,
0.0),
drum_angle_(new_continuous_state(), "drum_angle", 0.0),
drum_angle_vel_(new_continuous_state(), "drum_angle_vel", 0.0),
ddrum_angle_(new_discrete_state(), "ddrum_angle", 0.0, 0.0),
ddrum_angle_vel_(new_discrete_state(), "ddrum_angle_vel", 0.0, 0.0),
detwist_angle_vel_(new_continuous_state(), "detwist_angle_vel", 0.0),
ddetwist_angle_(new_discrete_state(), "ddetwist_angle", 0.0, 0.0),
ddetwist_angle_vel_(new_discrete_state(), "ddetwist_angle_vel", 0.0, 0.0),
int_err_drum_angle_(new_discrete_state(), "int_err_drum_angle", 0.0, 0.0),
detwist_angle_(new_continuous_state(), "detwist_angle", 0.0),
prox_sensor_active_(new_discrete_state(), "prox_sensor_active", 0.0,
false),
actual_mode_(new_derived_value(), "actual_mode", kGroundStationModeReel),
actual_transform_stage_(new_derived_value(), "actual_transform_stage", 0),
actual_platform_azi_(new_derived_value(), "actual_platform_azi", 0.0),
actual_drum_angle_(new_derived_value(), "actual_drum_angle", 0.0),
actual_detwist_angle_(new_derived_value(), "actual_detwist_angle", 0.0),
actual_prox_sensor_active_(new_derived_value(),
"actual_prox_sensor_active", 0.0) {
UpdateDerivedStates();
SetupDone();
}
void HitlGroundStationV2::Init(double azimuth, double drum_angle__) {
platform_azi_.Clear();
platform_azi_.set_val(azimuth);
platform_azi_vel_.Clear();
platform_azi_vel_.set_val(0.0);
drum_angle_.Clear();
drum_angle_.set_val(drum_angle__);
drum_angle_vel_.Clear();
drum_angle_vel_.set_val(0.0);
detwist_angle_.Clear();
detwist_angle_.set_val(0.0);
detwist_angle_vel_.Clear();
detwist_angle_vel_.set_val(0.0);
ClearDerivedValues();
UpdateDerivedStates();
}
void HitlGroundStationV2::SetFromAvionicsPackets(
const AvionicsPackets &avionics_packets) {
GroundStationV2Base::SetFromAvionicsPackets(avionics_packets);
if (avionics_packets.ground_station_status_valid) {
const auto &gs = avionics_packets.ground_station_status.status;
actual_mode_.set_val(static_cast<GroundStationMode>(gs.mode));
actual_transform_stage_.set_val(gs.transform_stage);
actual_platform_azi_.set_val(gs.azimuth.position);
actual_drum_angle_.set_val(gs.winch.position);
actual_prox_sensor_active_.set_val(gs.bridle_proximity.proximity);
actual_detwist_angle_.set_val(gs.detwist.position);
} else {
// The ground station status is not valid if we've never received it. In
// that event, set the "actual" value to the current model values, so we
// don't attempt to control a signal to a bogus data point.
actual_mode_.set_val(mode());
actual_transform_stage_.set_val(transform_stage());
actual_platform_azi_.set_val(platform_azi_.val());
actual_drum_angle_.set_val(drum_angle_.val());
actual_prox_sensor_active_.set_val(prox_sensor_active());
actual_detwist_angle_.set_val(detwist_angle());
}
}
void HitlGroundStationV2::DiscreteStepHelper(double t) {
set_mode(t, actual_mode_.val());
set_transform_stage(t, actual_transform_stage_.val());
// The model's platform azimuth and drum angle both track the actual signals
// by way of a simple second-order transfer function. Doing so keeps
// derivatives of these quantities reasonable as the simulator tracks reality.
//
// The transfer function is artifical, so we encode it here rather than
// parameterizing it in a config file.
double wn = 50.0;
double zeta = 1.0;
{ // Platform azimuth.
double err = actual_platform_azi_.val() - platform_azi_.val();
dplatform_azi_.DiscreteUpdate(t, platform_azi_vel_.val());
dplatform_azi_vel_.DiscreteUpdate(
t, err * wn * wn - 2.0 * zeta * wn * platform_azi_vel_.val());
}
{ // Drum angle.
double err = actual_drum_angle_.val() - drum_angle_.val();
ddrum_angle_.DiscreteUpdate(t, drum_angle_vel_.val());
ddrum_angle_vel_.DiscreteUpdate(
t, err * wn * wn - 2.0 * zeta * wn * drum_angle_vel_.val());
}
{ // Detwist angle.
double err = actual_detwist_angle_.val() - detwist_angle_.val();
ddetwist_angle_.DiscreteUpdate(t, detwist_angle_vel_.val());
ddetwist_angle_vel_.DiscreteUpdate(
t, err * wn * wn - 2.0 * zeta * wn * detwist_angle_vel_.val());
}
prox_sensor_active_.DiscreteUpdate(t, actual_prox_sensor_active_.val());
}
void HitlGroundStationV2::CalcDerivHelper(double /*t*/) {
platform_azi_.set_deriv(dplatform_azi_.val());
platform_azi_vel_.set_deriv(dplatform_azi_vel_.val());
drum_angle_.set_deriv(ddrum_angle_.val());
drum_angle_vel_.set_deriv(ddrum_angle_vel_.val());
detwist_angle_.set_deriv(ddetwist_angle_.val());
detwist_angle_vel_.set_deriv(ddetwist_angle_vel_.val());
}
void HitlGroundStationV2::AddInternalConnections(ConnectionStore *connections) {
connections->Add(1, [this](double /*t*/) { UpdateDerivedStates(); });
}
| 41.387365
| 80
| 0.685834
|
leozz37
|
84459f68a60fdf2e0000ed96d3ea03669d0acbe6
| 4,547
|
cpp
|
C++
|
Sankore-3.1/src/domain/UBItem.cpp
|
eaglezzb/rsdc
|
cce881f6542ff206bf286cf798c8ec8da3b51d50
|
[
"MIT"
] | null | null | null |
Sankore-3.1/src/domain/UBItem.cpp
|
eaglezzb/rsdc
|
cce881f6542ff206bf286cf798c8ec8da3b51d50
|
[
"MIT"
] | null | null | null |
Sankore-3.1/src/domain/UBItem.cpp
|
eaglezzb/rsdc
|
cce881f6542ff206bf286cf798c8ec8da3b51d50
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2010-2013 Groupement d'Intérêt Public pour l'Education Numérique en Afrique (GIP ENA)
*
* This file is part of Open-Sankoré.
*
* Open-Sankoré 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, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré 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 Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/
#include "UBItem.h"
#include "core/memcheck.h"
#include "domain/UBGraphicsPixmapItem.h"
#include "domain/UBGraphicsTextItem.h"
#include "domain/UBGraphicsSvgItem.h"
#include "domain/UBGraphicsMediaItem.h"
#include "domain/UBGraphicsStrokesGroup.h"
#include "domain/UBGraphicsGroupContainerItem.h"
#include "domain/UBGraphicsWidgetItem.h"
#include "domain/UBEditableGraphicsPolygonItem.h"
#include "domain/UBEditableGraphicsRegularShapeItem.h"
#include "domain/UBGraphicsEllipseItem.h"
#include "domain/UBGraphicsRectItem.h"
#include "domain/UBGraphicsLineItem.h"
#include "domain/UBGraphicsFreehandItem.h"
#include "tools/UBGraphicsCurtainItem.h"
UBItem::UBItem()
: mUuid(QUuid())
, mRenderingQuality(UBItem::RenderingQualityNormal)
{
// NOOP
}
UBItem::~UBItem()
{
// NOOP
}
UBGraphicsItem::~UBGraphicsItem()
{
if (mDelegate!=NULL){
delete mDelegate;
mDelegate = NULL;
}
}
void UBGraphicsItem::setDelegate(UBGraphicsItemDelegate* delegate)
{
Q_ASSERT(mDelegate==NULL);
mDelegate = delegate;
}
void UBGraphicsItem::assignZValue(QGraphicsItem *item, qreal value)
{
item->setZValue(value);
item->setData(UBGraphicsItemData::ItemOwnZValue, value);
}
bool UBGraphicsItem::isFlippable(QGraphicsItem *item)
{
return item->data(UBGraphicsItemData::ItemFlippable).toBool();
}
bool UBGraphicsItem::isRotatable(QGraphicsItem *item)
{
return item->data(UBGraphicsItemData::ItemRotatable).toBool();
}
bool UBGraphicsItem::isLocked(QGraphicsItem *item)
{
return item->data(UBGraphicsItemData::ItemLocked).toBool();
}
QUuid UBGraphicsItem::getOwnUuid(QGraphicsItem *item)
{
QString idCandidate = item->data(UBGraphicsItemData::ItemUuid).toString();
return idCandidate == QUuid().toString() ? QUuid() : QUuid(idCandidate);
}
qreal UBGraphicsItem::getOwnZValue(QGraphicsItem *item)
{
return item->data(UBGraphicsItemData::ItemOwnZValue).toReal();
}
void UBGraphicsItem::remove(bool canUndo)
{
if (Delegate() && !Delegate()->isLocked())
Delegate()->remove(canUndo);
}
UBGraphicsItemDelegate *UBGraphicsItem::Delegate(QGraphicsItem *pItem)
{
UBGraphicsItemDelegate *result = 0;
switch (static_cast<int>(pItem->type())) {
case UBGraphicsPixmapItem::Type :
result = (static_cast<UBGraphicsPixmapItem*>(pItem))->Delegate();
break;
case UBGraphicsTextItem::Type :
result = (static_cast<UBGraphicsTextItem*>(pItem))->Delegate();
break;
case UBGraphicsSvgItem::Type :
result = (static_cast<UBGraphicsSvgItem*>(pItem))->Delegate();
break;
case UBGraphicsMediaItem::Type:
result = (static_cast<UBGraphicsMediaItem*>(pItem))->Delegate();
break;
case UBGraphicsStrokesGroup::Type :
result = (static_cast<UBGraphicsStrokesGroup*>(pItem))->Delegate();
break;
case UBGraphicsGroupContainerItem::Type :
result = (static_cast<UBGraphicsGroupContainerItem*>(pItem))->Delegate();
break;
case UBGraphicsWidgetItem::Type :
result = (static_cast<UBGraphicsWidgetItem*>(pItem))->Delegate();
break;
case UBGraphicsCurtainItem::Type :
result = (static_cast<UBGraphicsCurtainItem*>(pItem))->Delegate();
break;
case UBEditableGraphicsRegularShapeItem::Type :
case UBEditableGraphicsPolygonItem::Type :
case UBGraphicsFreehandItem::Type :
case UBGraphicsItemType::GraphicsShapeItemType :
UBAbstractGraphicsItem* item = dynamic_cast<UBAbstractGraphicsItem*>(pItem);
if (item)
result = item->Delegate();
break;
}
return result;
}
| 30.516779
| 102
| 0.720475
|
eaglezzb
|
844620b796aba499ce01fcbcbd13774f592a3af7
| 1,917
|
cpp
|
C++
|
src/renderer/components/RectComponent.cpp
|
artfulbytes/sumobot_simulator
|
f2784d2ff506759019d7d5e840bd7aed591a0add
|
[
"MIT"
] | null | null | null |
src/renderer/components/RectComponent.cpp
|
artfulbytes/sumobot_simulator
|
f2784d2ff506759019d7d5e840bd7aed591a0add
|
[
"MIT"
] | null | null | null |
src/renderer/components/RectComponent.cpp
|
artfulbytes/sumobot_simulator
|
f2784d2ff506759019d7d5e840bd7aed591a0add
|
[
"MIT"
] | null | null | null |
#include "components/RectComponent.h"
#include "Renderer.h"
#include "components/Transforms.h"
#include "TexCoords.h"
#include "Texture.h"
#include "SpriteAnimation.h"
RectComponent::RectComponent(const RectTransform *transform, const glm::vec4& color) :
m_quadTransform(transform),
m_color(color)
{
}
RectComponent::RectComponent(const RectTransform *transform, const std::string &textureName, SpriteAnimation *spriteAnimation) :
m_quadTransform(transform),
m_texture(std::make_unique<Texture>(textureName)),
m_texCoords(std::make_unique<TexCoords>()),
m_spriteAnimation(spriteAnimation)
{
}
RectComponent::RectComponent(const CircleTransform *transform, const std::string &textureName, SpriteAnimation *spriteAnimation) :
m_circleTransform(transform),
m_texture(std::make_unique<Texture>(textureName)),
m_texCoords(std::make_unique<TexCoords>()),
m_spriteAnimation(spriteAnimation)
{
}
RectComponent::~RectComponent()
{
}
void RectComponent::onFixedUpdate()
{
if (m_enabled == false) {
return;
}
if (m_spriteAnimation != nullptr) {
m_spriteAnimation->onFixedUpdate();
m_spriteAnimation->computeTexCoords(*m_texCoords);
}
glm::vec2 size;
glm::vec2 position;
float rotation = 0.0f;
if (m_quadTransform != nullptr) {
size = m_quadTransform->size;
position = m_quadTransform->position;
rotation = m_quadTransform->rotation;
} else if (m_circleTransform != nullptr) {
size = glm::vec2{ 2 * m_circleTransform->radius, 2 * m_circleTransform->radius };
position = m_circleTransform->position;
rotation = m_circleTransform->rotation;
} else {
assert(0);
}
if (m_texture) {
Renderer::drawRect(position, size, rotation, *m_texture.get(), m_texCoords.get());
} else {
Renderer::drawRect(position, size, rotation, m_color);
}
}
| 29.045455
| 130
| 0.695357
|
artfulbytes
|
8446b534ea042ba69efdfb5ac4c427e47710ad33
| 5,067
|
cpp
|
C++
|
src/imports/cvkb/vkbquickmodel.cpp
|
CELLINKAB/qtcvkb
|
5b870f8ea4b42480eb678b065778de5dab36b199
|
[
"MIT"
] | null | null | null |
src/imports/cvkb/vkbquickmodel.cpp
|
CELLINKAB/qtcvkb
|
5b870f8ea4b42480eb678b065778de5dab36b199
|
[
"MIT"
] | null | null | null |
src/imports/cvkb/vkbquickmodel.cpp
|
CELLINKAB/qtcvkb
|
5b870f8ea4b42480eb678b065778de5dab36b199
|
[
"MIT"
] | null | null | null |
/*
* The MIT License (MIT)
*
* Copyright (C) 2020 CELLINK AB <info@cellink.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "vkbquickmodel.h"
#include "vkbquickdelegate.h"
#include "vkbquicklayout.h"
#include "vkbquickpopup.h"
#include <QtQml/qqmlcomponent.h>
#include <QtQml/qqmlcontext.h>
#include <QtQml/qqmlengine.h>
#include <QtQuickTemplates2/private/qquickabstractbutton_p.h>
VkbQuickModel::VkbQuickModel(QObject *parent) : QObject(parent)
{
}
QQmlListProperty<VkbQuickDelegate> VkbQuickModel::delegates()
{
return QQmlListProperty<VkbQuickDelegate>(this, nullptr, delegates_append, delegates_count, delegates_at, delegates_clear);
}
VkbQuickDelegate *VkbQuickModel::findDelegate(Qt::Key key) const
{
auto it = std::find_if(m_delegates.cbegin(), m_delegates.cend(), [&key](VkbQuickDelegate *delegate) { return delegate->key() == key; });
if (it != m_delegates.cend())
return *it;
if (key != Qt::Key_unknown)
return findDelegate(Qt::Key_unknown);
return nullptr;
}
template <typename T>
static T *beginCreate(const VkbInputKey &key, QQmlComponent *component, QObject *parent)
{
if (!component)
return nullptr;
QQmlContext *creationContext = component->creationContext();
if (!creationContext)
creationContext = qmlContext(parent);
QQmlContext *context = new QQmlContext(creationContext, parent);
QObject *instance = component->beginCreate(context);
T *object = qobject_cast<T *>(instance);
if (!object) {
delete instance;
return nullptr;
}
VkbQuickLayoutAttached *attached = VkbQuickLayout::qmlAttachedPropertiesObject(instance);
if (attached)
attached->setInputKey(key);
return object;
}
QQuickAbstractButton *VkbQuickModel::createButton(const VkbInputKey &key, QQuickItem *parent) const
{
VkbQuickDelegate *delegate = findDelegate(key.key);
if (!delegate)
return nullptr;
QQmlComponent *component = delegate->button();
QQuickAbstractButton *button = beginCreate<QQuickAbstractButton>(key, component, parent);
if (!button) {
qWarning() << "VkbQuickModel::createButton: button delegate for" << key.key << "is not a Button";
return nullptr;
}
button->setParentItem(parent);
button->setFocusPolicy(Qt::NoFocus);
button->setAutoRepeat(key.autoRepeat);
button->setCheckable(key.checkable);
if (key.checked)
button->setChecked(true);
component->completeCreate();
return button;
}
VkbQuickPopup *VkbQuickModel::createPopup(const VkbInputKey &key, QQuickAbstractButton *button) const
{
VkbQuickDelegate *delegate = findDelegate(key.key);
if (!delegate)
return nullptr;
QQmlComponent *component = delegate->popup();
VkbQuickPopup *popup = beginCreate<VkbQuickPopup>(key, component, button);
if (!popup) {
qWarning() << "VkbQuickModel::createPopup: popup delegate for" << key.key << "is not an InputPopup";
return nullptr;
}
popup->setParentItem(button);
popup->setAlt(key.alt);
component->completeCreate();
return popup;
}
void VkbQuickModel::delegates_append(QQmlListProperty<VkbQuickDelegate> *property, VkbQuickDelegate *delegate)
{
VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object);
that->m_delegates.append(delegate);
emit that->delegatesChanged();
}
int VkbQuickModel::delegates_count(QQmlListProperty<VkbQuickDelegate> *property)
{
VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object);
return that->m_delegates.count();
}
VkbQuickDelegate *VkbQuickModel::delegates_at(QQmlListProperty<VkbQuickDelegate> *property, int index)
{
VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object);
return that->m_delegates.value(index);
}
void VkbQuickModel::delegates_clear(QQmlListProperty<VkbQuickDelegate> *property)
{
VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object);
that->m_delegates.clear();
emit that->delegatesChanged();
}
| 34.705479
| 140
| 0.727452
|
CELLINKAB
|
84497ae9875b5463168efd697efe59406a255318
| 13,416
|
cc
|
C++
|
pigasus/software/src/file_api/file_identifier.cc
|
zhipengzhaocmu/fpga2022_artifact
|
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
pigasus/software/src/file_api/file_identifier.cc
|
zhipengzhaocmu/fpga2022_artifact
|
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
pigasus/software/src/file_api/file_identifier.cc
|
zhipengzhaocmu/fpga2022_artifact
|
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
//--------------------------------------------------------------------------
// Copyright (C) 2014-2018 Cisco and/or its affiliates. All rights reserved.
// Copyright (C) 2012-2013 Sourcefire, Inc.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License Version 2 as published
// by the Free Software Foundation. You may not use, modify or distribute
// this program under any other version of the GNU General Public License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//--------------------------------------------------------------------------
/*
** Author(s): Hui Cao <huica@cisco.com>
**
** NOTES
** 5.25.2012 - Initial Source Code. Hcao
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "file_identifier.h"
#include <algorithm>
#include <cassert>
#include "log/messages.h"
#include "utils/util.h"
#ifdef UNIT_TEST
#include "catch/snort_catch.h"
#endif
using namespace snort;
struct MergeNode
{
IdentifierNode* shared_node; /*the node that is shared*/
IdentifierNode* append_node; /*the node that is added*/
} ;
void FileMagicData::clear()
{
content_str.clear();
content.clear();
offset = 0;
}
void FileMagicRule::clear()
{
rev = 0;
message.clear();
type.clear();
id = 0;
category.clear();
version.clear();
groups.clear();
file_magics.clear();
}
void FileIdentifier::init_merge_hash()
{
identifier_merge_hash = snort::ghash_new(1000, sizeof(MergeNode), 0, nullptr);
assert(identifier_merge_hash);
}
FileIdentifier::~FileIdentifier()
{
/*Release memory used for identifiers*/
for (auto mem_block:id_memory_blocks)
{
snort_free(mem_block);
}
if (identifier_merge_hash != nullptr)
{
ghash_delete(identifier_merge_hash);
}
}
void* FileIdentifier::calloc_mem(size_t size)
{
void* ret = snort_calloc(size);
memory_used += size;
/*For memory management*/
id_memory_blocks.emplace_back(ret);
return ret;
}
void FileIdentifier::set_node_state_shared(IdentifierNode* start)
{
unsigned int i;
if (!start)
return;
if (start->state == ID_NODE_SHARED)
return;
if (start->state == ID_NODE_USED)
start->state = ID_NODE_SHARED;
else
start->state = ID_NODE_USED;
for (i = 0; i < MAX_BRANCH; i++)
set_node_state_shared(start->next[i]);
}
/*Clone a trie*/
IdentifierNode* FileIdentifier::clone_node(IdentifierNode* start)
{
unsigned int index;
IdentifierNode* node;
if (!start)
return nullptr;
node = (IdentifierNode*)calloc_mem(sizeof(*node));
node->offset = start->offset;
node->type_id = start->type_id;
for (index = 0; index < MAX_BRANCH; index++)
{
if (start->next[index])
{
node->next[index] = start->next[index];
}
}
return node;
}
IdentifierNode* FileIdentifier::create_trie_from_magic(FileMagicRule& rule, uint32_t type_id)
{
IdentifierNode* current;
IdentifierNode* root = nullptr;
if (rule.file_magics.empty() || !type_id)
return nullptr;
/* Content magics are sorted based on offset, this
* will help compile the file magic trio
*/
std::sort(rule.file_magics.begin(),rule.file_magics.end());
current = (IdentifierNode*)calloc_mem(sizeof(*current));
current->state = ID_NODE_NEW;
root = current;
for (auto magic:rule.file_magics)
{
unsigned int i;
current->offset = magic.offset;
for (i = 0; i < magic.content.size(); i++)
{
IdentifierNode* node = (IdentifierNode*)calloc_mem(sizeof(*node));
uint8_t index = magic.content[i];
node->offset = magic.offset + i + 1;
node->state = ID_NODE_NEW;
current->next[index] = node;
current = node;
}
}
/*Last node has type name*/
current->type_id = type_id;
return root;
}
/*This function examines whether to update the trie based on shared state*/
bool FileIdentifier::update_next(IdentifierNode* start,IdentifierNode** next_ptr,
IdentifierNode* append)
{
IdentifierNode* next = (*next_ptr);
MergeNode merge_node;
IdentifierNode* result;
if (!append || (next == append))
return false;
merge_node.append_node = append;
merge_node.shared_node = next;
if (!next)
{
/*reuse the append*/
*next_ptr = append;
set_node_state_shared(append);
return false;
}
else if ((result = (IdentifierNode*)ghash_find(identifier_merge_hash, &merge_node)))
{
/*the same pointer has been processed, reuse it*/
*next_ptr = result;
set_node_state_shared(result);
return false;
}
else
{
if ((start->offset < append->offset) && (next->offset > append->offset))
{
/*offset could have gap when non 0 offset is allowed */
unsigned int index;
IdentifierNode* node = (IdentifierNode*)calloc_mem(sizeof(*node));
merge_node.shared_node = next;
merge_node.append_node = append;
node->offset = append->offset;
for (index = 0; index < MAX_BRANCH; index++)
{
node->next[index] = next;
}
set_node_state_shared(next);
next = node;
ghash_add(identifier_merge_hash, &merge_node, next);
}
else if (next->state == ID_NODE_SHARED)
{
/*shared, need to clone one*/
IdentifierNode* current_next = next;
merge_node.shared_node = current_next;
merge_node.append_node = append;
next = clone_node(current_next);
set_node_state_shared(next);
ghash_add(identifier_merge_hash, &merge_node, next);
}
*next_ptr = next;
}
return true;
}
/*
* Append magic to existing trie
*/
void FileIdentifier::update_trie(IdentifierNode* start, IdentifierNode* append)
{
unsigned int i;
if ((!start )||(!append)||(start == append))
return;
if (start->offset == append->offset )
{
/* when we come here, make sure this tree is not shared
* Update start trie using append information*/
assert(start->state != ID_NODE_SHARED);
if (append->type_id)
{
if (start->type_id)
ParseWarning(WARN_RULES, "Duplicated type definition '%u -> %u at offset %u",
start->type_id, append->type_id, append->offset);
start->type_id = append->type_id;
}
for (i = 0; i < MAX_BRANCH; i++)
{
if (update_next(start,&start->next[i], append->next[i]))
{
update_trie(start->next[i], append->next[i]);
}
}
}
else if (start->offset < append->offset )
{
for (i = 0; i < MAX_BRANCH; i++)
{
if (update_next(start,&start->next[i], append))
update_trie(start->next[i], append);
}
}
}
void FileIdentifier::insert_file_rule(FileMagicRule& rule)
{
IdentifierNode* node;
if (!identifier_root)
{
identifier_root = (IdentifierNode*)calloc_mem(sizeof(*identifier_root));
init_merge_hash();
}
if (rule.id >= FILE_ID_MAX)
{
ParseError("file type: rule id %u exceeds max id of %d", rule.id, FILE_ID_MAX-1);
return;
}
if (file_magic_rules[rule.id].id > 0)
{
ParseError("file type: duplicated rule id %u defined", rule.id);
return;
}
file_magic_rules[rule.id] = rule;
node = create_trie_from_magic(rule, rule.id);
update_trie(identifier_root, node);
}
/*
* This is the main function to find file type
* Find file type is to traverse the tries.
* Context is saved to continue file type identification as data becomes available
*/
uint32_t FileIdentifier::find_file_type_id(const uint8_t* buf, int len, uint64_t file_offset,
void** context)
{
uint32_t file_type_id = SNORT_FILE_TYPE_CONTINUE;
assert(context);
if ( !buf || len <= 0 )
return SNORT_FILE_TYPE_CONTINUE;
if (!(*context))
*context = (void*)(identifier_root);
IdentifierNode* current = (IdentifierNode*)(*context);
uint64_t end = file_offset + len;
while (current && (current->offset >= file_offset))
{
/*Found file id, save and continue*/
if (current->type_id)
{
file_type_id = current->type_id;
}
if ( current->offset >= end )
{
/* Save current state */
*context = current;
if (file_type_id)
return file_type_id;
else
return SNORT_FILE_TYPE_CONTINUE;
}
/*Move to the next level*/
current = current->next[buf[current->offset - file_offset ]];
}
/*Either end of magics or passed the current offset*/
*context = nullptr;
if ( file_type_id == SNORT_FILE_TYPE_CONTINUE )
file_type_id = SNORT_FILE_TYPE_UNKNOWN;
return file_type_id;
}
FileMagicRule* FileIdentifier::get_rule_from_id(uint32_t id)
{
if ((id < FILE_ID_MAX) && (file_magic_rules[id].id > 0))
{
return (&(file_magic_rules[id]));
}
else
return nullptr;
}
void FileIdentifier::get_magic_rule_ids_from_type(const std::string& type,
const std::string& version, snort::FileTypeBitSet& ids_set)
{
ids_set.reset();
for (uint32_t i = 0; i < FILE_ID_MAX; i++)
{
if (type == file_magic_rules[i].type)
{
if (version.empty() or version == file_magic_rules[i].version)
{
ids_set.set(file_magic_rules[i].id);
}
}
}
}
//--------------------------------------------------------------------------
// unit tests
//--------------------------------------------------------------------------
#ifdef UNIT_TEST
TEST_CASE ("FileIdMemory", "[FileMagic]")
{
FileIdentifier rc;
CHECK(rc.memory_usage() == 0);
}
TEST_CASE ("FileIdRulePDF", "[FileMagic]")
{
FileMagicData magic;
magic.content = "PDF";
magic.offset = 0;
FileMagicRule rule;
rule.type = "pdf";
rule.file_magics.emplace_back(magic);
rule.id = 1;
FileIdentifier rc;
rc.insert_file_rule(rule);
const char* data = "PDF";
void* context = nullptr;
CHECK(rc.find_file_type_id((const uint8_t*)data, strlen(data), 0, &context) == 1);
}
TEST_CASE ("FileIdRuleUnknow", "[FileMagic]")
{
FileMagicData magic;
magic.content = "PDF";
magic.offset = 0;
FileMagicRule rule;
rule.type = "pdf";
rule.file_magics.emplace_back(magic);
rule.id = 1;
FileIdentifier rc;
rc.insert_file_rule(rule);
const char* data = "DDF";
void* context = nullptr;
CHECK((rc.find_file_type_id((const uint8_t*)data, strlen(data), 0, &context) ==
SNORT_FILE_TYPE_UNKNOWN));
}
TEST_CASE ("FileIdRuleEXE", "[FileMagic]")
{
FileMagicData magic;
magic.content = "PDF";
magic.offset = 0;
FileMagicRule rule;
rule.type = "exe";
rule.file_magics.emplace_back(magic);
rule.id = 1;
FileIdentifier rc;
rc.insert_file_rule(rule);
magic.clear();
magic.content = "EXE";
magic.offset = 0;
rule.clear();
rule.type = "exe";
rule.file_magics.emplace_back(magic);
rule.id = 3;
rc.insert_file_rule(rule);
const char* data = "PDFooo";
void* context = nullptr;
CHECK(rc.find_file_type_id((const uint8_t*)data, strlen(data), 0, &context) == 1);
}
TEST_CASE ("FileIdRulePDFEXE", "[FileMagic]")
{
FileMagicData magic;
magic.content = "PDF";
magic.offset = 0;
FileMagicRule rule;
rule.type = "exe";
rule.file_magics.emplace_back(magic);
rule.id = 1;
FileIdentifier rc;
rc.insert_file_rule(rule);
magic.clear();
magic.content = "EXE";
magic.offset = 3;
rule.clear();
rule.type = "exe";
rule.file_magics.emplace_back(magic);
rule.id = 3;
rc.insert_file_rule(rule);
const char* data = "PDFEXE";
void* context = nullptr;
// Match the last one
CHECK((rc.find_file_type_id((const uint8_t*)data, strlen(data), 0, &context) == 3));
}
TEST_CASE ("FileIdRuleFirst", "[FileMagic]")
{
FileMagicData magic;
magic.content = "PDF";
magic.offset = 0;
FileMagicRule rule;
rule.type = "exe";
rule.file_magics.emplace_back(magic);
rule.id = 1;
FileIdentifier rc;
rc.insert_file_rule(rule);
magic.clear();
magic.content = "EXE";
magic.offset = 3;
rule.clear();
rule.type = "exe";
rule.file_magics.emplace_back(magic);
rule.id = 3;
rc.insert_file_rule(rule);
const char* data = "PDF";
void* context = nullptr;
CHECK(rc.find_file_type_id((const uint8_t*)data, strlen(data), 0, &context) == 1);
}
#endif
| 24.172973
| 93
| 0.60003
|
zhipengzhaocmu
|
e0fe61b355cc89c9ca6d6501a2aaa5278a998e4f
| 539
|
cpp
|
C++
|
notes/code4/GTX.cpp
|
suryaavala/advancedcpp
|
84c1847bf42ff744f99b4c0f94b77cfa71ca00d8
|
[
"MIT"
] | null | null | null |
notes/code4/GTX.cpp
|
suryaavala/advancedcpp
|
84c1847bf42ff744f99b4c0f94b77cfa71ca00d8
|
[
"MIT"
] | null | null | null |
notes/code4/GTX.cpp
|
suryaavala/advancedcpp
|
84c1847bf42ff744f99b4c0f94b77cfa71ca00d8
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <algorithm>
class GTx {
public:
GTx(size_t val = 0): bound{val} {}
bool operator()(const std::string &s) { return s.size() >= bound; }
private:
std::string::size_type bound;
};
int main() {
std::vector<std::string> words{"function","objects","are","fun"};
std::cout << std::count_if(words.begin(), words.end(), GTx{6})
<< " words have 6 characters or longer; "
<< std::count_if(words.begin(), words.end(), GTx{3})
<< " words have 3 characters or longer." << std::endl;
}
| 25.666667
| 69
| 0.628942
|
suryaavala
|
460071945d8a1109cb33f18a22a10552fabac77c
| 1,052
|
cpp
|
C++
|
src/dynamic_load.cpp
|
cgilmour/dd-opentracing-cpp
|
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
|
[
"Apache-2.0"
] | null | null | null |
src/dynamic_load.cpp
|
cgilmour/dd-opentracing-cpp
|
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
|
[
"Apache-2.0"
] | null | null | null |
src/dynamic_load.cpp
|
cgilmour/dd-opentracing-cpp
|
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
|
[
"Apache-2.0"
] | null | null | null |
#include <opentracing/dynamic_load.h>
#include <iostream>
#include "tracer.h"
#include "tracer_factory.h"
#include "version_check.h"
int OpenTracingMakeTracerFactory(const char* opentracing_version, const void** error_category,
void** tracer_factory) try {
if (!datadog::opentracing::equal_or_higher_version(std::string(opentracing_version),
std::string(OPENTRACING_VERSION))) {
std::cerr << "version mismatch: " << std::string(opentracing_version)
<< " != " << std::string(OPENTRACING_VERSION) << std::endl;
*error_category = static_cast<const void*>(&opentracing::dynamic_load_error_category());
return opentracing::incompatible_library_versions_error.value();
}
*tracer_factory = new datadog::opentracing::TracerFactory<datadog::opentracing::Tracer>{};
return 0;
} catch (const std::bad_alloc&) {
*error_category = static_cast<const void*>(&std::generic_category());
return static_cast<int>(std::errc::not_enough_memory);
}
| 47.818182
| 94
| 0.681559
|
cgilmour
|
4604097af0b164349f1049831f710259fb25a9af
| 12,410
|
cc
|
C++
|
mysql-server/mysys/crypt_genhash_impl.cc
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
mysql-server/mysys/crypt_genhash_impl.cc
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
mysql-server/mysys/crypt_genhash_impl.cc
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
/* Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
Without limiting anything contained in the foregoing, this file,
which is part of C Driver for MySQL (Connector/C), is also subject to the
Universal FOSS Exception, version 1.0, a copy of which can be found at
http://oss.oracle.com/licenses/universal-foss-exception.
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, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file mysys/crypt_genhash_impl.cc
*/
// First include (the generated) my_config.h, to get correct platform defines.
#include "my_config.h"
#include <sys/types.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "crypt_genhash_impl.h"
#include "m_string.h"
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#include <errno.h>
#ifdef _WIN32
#include <malloc.h>
#endif
#define DIGEST_CTX EVP_MD_CTX
#define DIGEST_LEN SHA256_DIGEST_LENGTH
static void DIGESTCreate(DIGEST_CTX **ctx) {
if (ctx != nullptr) {
*ctx = EVP_MD_CTX_create();
}
}
static void DIGESTInit(DIGEST_CTX *ctx) {
EVP_DigestInit_ex(ctx, EVP_sha256(), nullptr);
}
static void DIGESTUpdate(DIGEST_CTX *ctx, const void *plaintext, int len) {
EVP_DigestUpdate(ctx, plaintext, len);
}
static void DIGESTFinal(void *txt, DIGEST_CTX *ctx) {
EVP_DigestFinal_ex(ctx, (unsigned char *)txt, nullptr);
}
static void DIGESTDestroy(DIGEST_CTX **ctx) {
if (ctx != nullptr) {
EVP_MD_CTX_destroy(*ctx);
*ctx = nullptr;
}
}
static const char crypt_alg_magic[] = "$5";
#ifndef MAX
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef MIN
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef HAVE_STRLCAT
/**
Size-bounded string copying and concatenation
This is a replacement for STRLCPY(3)
*/
static size_t strlcat(char *dst, const char *src, size_t siz) {
char *d = dst;
const char *s = src;
size_t n = siz;
size_t dlen;
/* Find the end of dst and adjust bytes left but don't go past end */
while (n-- != 0 && *d != '\0') d++;
dlen = d - dst;
n = siz - dlen;
if (n == 0) return (dlen + siz);
while (*s != '\0') {
if (n != 1) {
*d++ = *s;
n--;
}
s++;
}
*d = '\0';
return (dlen + (s - src)); /* count does not include NUL */
}
#endif
static const int crypt_alg_magic_len = sizeof(crypt_alg_magic) - 1;
static unsigned char b64t[] = /* 0 ... 63 => ascii - 64 */
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
#define b64_from_24bit(B2, B1, B0, N) \
{ \
uint32_t w = ((B2) << 16) | ((B1) << 8) | (B0); \
int n = (N); \
while (--n >= 0 && ctbufflen > 0) { \
*p++ = b64t[w & 0x3f]; \
w >>= 6; \
ctbufflen--; \
} \
}
#define ROUNDS "rounds="
#define ROUNDSLEN (sizeof(ROUNDS) - 1)
/**
Get the integer value after rounds= where ever it occurs in the string.
if the last char after the int is a , or $ that is fine anything else is an
error.
*/
static uint getrounds(const char *s) {
const char *r;
const char *p;
char *e;
long val;
if (s == nullptr) return (0);
if ((r = strstr(s, ROUNDS)) == nullptr) {
return (0);
}
if (strncmp(r, ROUNDS, ROUNDSLEN) != 0) {
return (0);
}
p = r + ROUNDSLEN;
errno = 0;
val = strtol(p, &e, 10);
/*
An error occurred or there is non-numeric stuff at the end
which isn't one of the crypt(3c) special chars ',' or '$'
*/
if (errno != 0 || val < 0 || !(*e == '\0' || *e == ',' || *e == '$')) {
return (0);
}
return ((uint32_t)val);
}
/**
Finds the interval which envelopes the user salt in a crypt password
The crypt format is assumed to be $a$bbbb$cccccc\0 and the salt is found
by counting the delimiters and marking begin and end.
@param [in,out] salt_begin As input, pointer to start of crypt passwd,
as output, pointer to first byte of the salt
@param [in,out] salt_end As input, pointer to the last byte in passwd,
as output, pointer to the byte immediatly following
the salt ($)
@return The size of the salt identified
*/
int extract_user_salt(const char **salt_begin, const char **salt_end) {
const char *it = *salt_begin;
int delimiter_count = 0;
while (it != *salt_end) {
if (*it == '$') {
++delimiter_count;
if (delimiter_count == 2) {
*salt_begin = it + 1;
}
if (delimiter_count == 3) break;
}
++it;
}
*salt_end = it;
return *salt_end - *salt_begin;
}
/*
* Portions of the below code come from crypt_bsdmd5.so (bsdmd5.c) :
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <phk@login.dknet.dk> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
* ----------------------------------------------------------------------------
*
* $FreeBSD: crypt.c,v 1.5 1996/10/14 08:34:02 phk Exp $
*
*/
/*
* The below code implements the specification from:
*
* From http://people.redhat.com/drepper/SHA-crypt.txt
*
* Portions of the code taken from inspired by or verified against the
* source in the above document which is licensed as:
*
* "Released into the Public Domain by Ulrich Drepper <drepper@redhat.com>."
*/
/*
Due to a Solaris namespace bug DS is a reserved word. To work around this
DS is undefined.
*/
#undef DS
/* ARGSUSED4 */
char *my_crypt_genhash(char *ctbuffer, size_t ctbufflen, const char *plaintext,
size_t plaintext_len, const char *switchsalt,
const char **, unsigned int *num_rounds) /* = NULL */
{
int salt_len;
size_t i;
char *salt;
unsigned char A[DIGEST_LEN];
unsigned char B[DIGEST_LEN];
unsigned char DP[DIGEST_LEN];
unsigned char DS[DIGEST_LEN];
DIGEST_CTX *ctxA, *ctxB, *ctxC, *ctxDP, *ctxDS = nullptr;
unsigned int rounds =
num_rounds && (*num_rounds <= ROUNDS_MAX && *num_rounds >= ROUNDS_MIN)
? *num_rounds
: ROUNDS_DEFAULT;
int srounds = 0;
bool custom_rounds = false;
char *p;
char *P, *Pp;
char *S, *Sp;
/* Create Digest context. */
DIGESTCreate(&ctxA);
DIGESTCreate(&ctxB);
DIGESTCreate(&ctxC);
DIGESTCreate(&ctxDP);
DIGESTCreate(&ctxDS);
if (num_rounds) *num_rounds = rounds;
/* Refine the salt */
salt = const_cast<char *>(switchsalt);
/* skip our magic string */
if (strncmp(salt, crypt_alg_magic, crypt_alg_magic_len) == 0) {
salt += crypt_alg_magic_len + 1;
}
srounds = getrounds(salt);
if (srounds != 0) {
rounds = MAX(ROUNDS_MIN, MIN(srounds, ROUNDS_MAX));
custom_rounds = true;
p = strchr(salt, '$');
if (p != nullptr) salt = p + 1;
}
salt_len = MIN(strcspn(salt, "$"), CRYPT_SALT_LENGTH);
// plaintext_len = strlen(plaintext);
/* 1. */
DIGESTInit(ctxA);
/* 2. The password first, since that is what is most unknown */
DIGESTUpdate(ctxA, plaintext, plaintext_len);
/* 3. Then the raw salt */
DIGESTUpdate(ctxA, salt, salt_len);
/* 4. - 8. */
DIGESTInit(ctxB);
DIGESTUpdate(ctxB, plaintext, plaintext_len);
DIGESTUpdate(ctxB, salt, salt_len);
DIGESTUpdate(ctxB, plaintext, plaintext_len);
DIGESTFinal(B, ctxB);
/* 9. - 10. */
for (i = plaintext_len; i > MIXCHARS; i -= MIXCHARS)
DIGESTUpdate(ctxA, B, MIXCHARS);
DIGESTUpdate(ctxA, B, i);
/* 11. */
for (i = plaintext_len; i > 0; i >>= 1) {
if ((i & 1) != 0) {
DIGESTUpdate(ctxA, B, MIXCHARS);
} else {
DIGESTUpdate(ctxA, plaintext, plaintext_len);
}
}
/* 12. */
DIGESTFinal(A, ctxA);
/* 13. - 15. */
DIGESTInit(ctxDP);
for (i = 0; i < plaintext_len; i++)
DIGESTUpdate(ctxDP, plaintext, plaintext_len);
DIGESTFinal(DP, ctxDP);
/* 16. */
Pp = P = (char *)alloca(plaintext_len);
for (i = plaintext_len; i >= MIXCHARS; i -= MIXCHARS) {
Pp = (char *)(memcpy(Pp, DP, MIXCHARS)) + MIXCHARS;
}
(void)memcpy(Pp, DP, i);
/* 17. - 19. */
DIGESTInit(ctxDS);
for (i = 0; i < 16U + (uint8_t)A[0]; i++) DIGESTUpdate(ctxDS, salt, salt_len);
DIGESTFinal(DS, ctxDS);
/* 20. */
Sp = S = (char *)alloca(salt_len);
for (i = salt_len; i >= MIXCHARS; i -= MIXCHARS) {
Sp = (char *)(memcpy(Sp, DS, MIXCHARS)) + MIXCHARS;
}
(void)memcpy(Sp, DS, i);
/* 21. */
for (i = 0; i < rounds; i++) {
DIGESTInit(ctxC);
if ((i & 1) != 0) {
DIGESTUpdate(ctxC, P, plaintext_len);
} else {
if (i == 0)
DIGESTUpdate(ctxC, A, MIXCHARS);
else
DIGESTUpdate(ctxC, DP, MIXCHARS);
}
if (i % 3 != 0) {
DIGESTUpdate(ctxC, S, salt_len);
}
if (i % 7 != 0) {
DIGESTUpdate(ctxC, P, plaintext_len);
}
if ((i & 1) != 0) {
if (i == 0)
DIGESTUpdate(ctxC, A, MIXCHARS);
else
DIGESTUpdate(ctxC, DP, MIXCHARS);
} else {
DIGESTUpdate(ctxC, P, plaintext_len);
}
DIGESTFinal(DP, ctxC);
}
/* 22. Now make the output string */
if (custom_rounds) {
(void)snprintf(ctbuffer, ctbufflen, "%s$rounds=%zu$", crypt_alg_magic,
(size_t)rounds);
} else {
(void)snprintf(ctbuffer, ctbufflen, "%s$", crypt_alg_magic);
}
(void)strncat(ctbuffer, (const char *)salt, salt_len);
(void)strlcat(ctbuffer, "$", ctbufflen);
p = ctbuffer + strlen(ctbuffer);
ctbufflen -= strlen(ctbuffer);
b64_from_24bit(DP[0], DP[10], DP[20], 4);
b64_from_24bit(DP[21], DP[1], DP[11], 4);
b64_from_24bit(DP[12], DP[22], DP[2], 4);
b64_from_24bit(DP[3], DP[13], DP[23], 4);
b64_from_24bit(DP[24], DP[4], DP[14], 4);
b64_from_24bit(DP[15], DP[25], DP[5], 4);
b64_from_24bit(DP[6], DP[16], DP[26], 4);
b64_from_24bit(DP[27], DP[7], DP[17], 4);
b64_from_24bit(DP[18], DP[28], DP[8], 4);
b64_from_24bit(DP[9], DP[19], DP[29], 4);
b64_from_24bit(0, DP[31], DP[30], 3);
*p = '\0';
(void)memset(A, 0, sizeof(A));
(void)memset(B, 0, sizeof(B));
(void)memset(DP, 0, sizeof(DP));
(void)memset(DS, 0, sizeof(DS));
/* 23. Clearing the context */
DIGESTDestroy(&ctxA);
DIGESTDestroy(&ctxB);
DIGESTDestroy(&ctxC);
DIGESTDestroy(&ctxDP);
DIGESTDestroy(&ctxDS);
return (ctbuffer);
}
/**
Generate a random string using ASCII characters but avoid seperator character.
Stdlib rand and srand are used to produce pseudo random numbers between
with about 7 bit worth of entropty between 1-127.
*/
void generate_user_salt(char *buffer, int buffer_len) {
char *end = buffer + buffer_len - 1;
RAND_bytes((unsigned char *)buffer, buffer_len);
/* Sequence must be a legal UTF8 string */
for (; buffer < end; buffer++) {
*buffer &= 0x7f;
if (*buffer == '\0' || *buffer == '$') *buffer = *buffer + 1;
}
/* Make sure the buffer is terminated properly */
*end = '\0';
}
void xor_string(char *to, int to_len, char *pattern, int pattern_len) {
int loop = 0;
while (loop <= to_len) {
*(to + loop) ^= *(pattern + loop % pattern_len);
++loop;
}
}
| 27.88764
| 80
| 0.609347
|
silenc3502
|
4604dc0789f87eabd6425248d8f7f211dcb9baed
| 6,663
|
cpp
|
C++
|
src/future/flexer.cpp
|
rasfmar/future
|
189a996f7e2c6401626d11ca6d8f11243dd0b737
|
[
"MIT"
] | null | null | null |
src/future/flexer.cpp
|
rasfmar/future
|
189a996f7e2c6401626d11ca6d8f11243dd0b737
|
[
"MIT"
] | null | null | null |
src/future/flexer.cpp
|
rasfmar/future
|
189a996f7e2c6401626d11ca6d8f11243dd0b737
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <string>
#include "internal/_ftoken.hpp"
#include "fstate.hpp"
#include "flexer.hpp"
void flexer::lex(fstate *state, fparser &parser) {
lex(state, parser.tokens);
}
void flexer::lex(fstate *state, std::vector<_ftoken*> &tokens) {
std::stack<_ftoken*> fstack;
bool die = false;
for (_ftoken *token : tokens) {
// if it's an operator
if (token->type >= _FPLUS) {
switch(token->type) {
case _FPLUS: {
// todo error handling
if (fstack.size() < 2) {
die = true;
break;
}
_ftoken* second_operand = fstack.top();
fstack.pop();
_ftoken* first_operand = fstack.top();
fstack.pop();
// todo assert that second operand is of same type as first
_27: switch (first_operand->type) {
case _FINT32: {
int32_t first_operand_val = *(int32_t *)first_operand->val;
if (second_operand->type == _FID) {
// todo stop assuming dEFINED
std::string second_operand_val = *(std::string *)second_operand->val;
if (!state->definitions.count(second_operand_val)) {
// error
die = true;
break;
}
_ftoken *definition = state->definitions[second_operand_val];
second_operand->type = definition->type;
second_operand->val = definition->val;
}
if (second_operand->type != _FINT32) {
// error!
fstack.push(new _ftoken());
break;
}
int32_t second_operand_val = *(int32_t *)second_operand->val;
int32_t *result = new int32_t(first_operand_val + second_operand_val);
fstack.push(new _ftoken(result));
// delete first_operand;
// delete second_operand;
break;
}
case _FSTRING: {
std::string first_operand_val = *(std::string *)first_operand->val;
std::string second_operand_val = *(std::string *)second_operand->val;
std::string *result = new std::string(first_operand_val + second_operand_val);
fstack.push(new _ftoken(result));
// delete first_operand;
// delete second_operand;
break;
}
case _FID: {
// todo stop assuming its defined
std::string first_operand_val = *(std::string *)first_operand->val;
if (!state->definitions.count(first_operand_val)) {
// error
die = true;
break;
}
_ftoken *definition = state->definitions[first_operand_val];
first_operand->type = definition->type;
first_operand->val = definition->val;
goto _27;
}
default:
fstack.push(new _ftoken());
break;
}
break;
}
case _FMINUS: {
// todo error handling
if (fstack.size() < 2) {
die = true;
break;
}
_ftoken* second_operand = fstack.top();
fstack.pop();
_ftoken* first_operand = fstack.top();
fstack.pop();
// todo assert that second operand is of same type as first
_60: switch (first_operand->type) {
case _FINT32: {
int32_t first_operand_val = *(int32_t *)first_operand->val;
if (second_operand->type == _FID) {
// todo stop assuming dEFINED
std::string second_operand_val = *(std::string *)second_operand->val;
if (!state->definitions.count(second_operand_val)) {
// error
die = true;
break;
}
_ftoken *definition = state->definitions[second_operand_val];
second_operand->type = definition->type;
second_operand->val = definition->val;
}
if (second_operand->type != _FINT32) {
// error!
fstack.push(new _ftoken());
break;
}
int32_t second_operand_val = *(int32_t *)second_operand->val;
int32_t *result = new int32_t(first_operand_val - second_operand_val);
fstack.push(new _ftoken(result));
// delete first_operand;
// delete second_operand;
break;
}
case _FID: {
// todo stop assuming its defined
std::string first_operand_val = *(std::string *)first_operand->val;
if (!state->definitions.count(first_operand_val)) {
// error
die = true;
break;
}
_ftoken *definition = state->definitions[first_operand_val];
first_operand->type = definition->type;
first_operand->val = definition->val;
goto _60;
}
default:
fstack.push(new _ftoken());
break;
}
break;
}
case _FEQUALS: {
// todo error handling for empty stack
if (fstack.size() < 2) {
die = true;
break;
}
_ftoken* second_operand = fstack.top();
fstack.pop();
_ftoken* first_operand = fstack.top();
fstack.pop();
// todo error if first operand is not an identifier
std::string first_operand_val = *(std::string *)first_operand->val;
// setting this directly to second_operand could be a problem
state->definitions[first_operand_val] = second_operand->clone();
// delete first_operand;
// delete second_operand;
break;
}
case _FPRINT: {
if (fstack.size() < 1) {
die = true;
break;
}
_ftoken* first_operand = fstack.top();
fstack.pop();
if (first_operand->type == _FID) {
std::string first_operand_val = *(std::string *)first_operand->val;
if (!state->definitions.count(first_operand_val)) {
die = true;
break;
}
_ftoken *definition = state->definitions[first_operand_val];
first_operand->type = definition->type;
first_operand->val = definition->val;
}
std::cout << first_operand->valstr() << std::endl;
break;
}
case _FINPUT: {
std::string *in = new std::string("");
std::getline(std::cin, *in);
_ftoken *token = new _ftoken(in);
fstack.push(token);
break;
}
default:
break;
}
} else {
fstack.push(token);
}
if (die)
break;
}
tokens.clear();
while (!fstack.empty()) {
std::cout << (fstack.top())->str() << std::endl;
fstack.pop();
}
}
| 31.880383
| 88
| 0.540147
|
rasfmar
|
46054b06a51fe0732a8681424f05cfcf5161c13e
| 1,212
|
cpp
|
C++
|
test/communicator_broadcast.cpp
|
correaa/b-mpi3
|
161e52a28ab9043be9ef33acd8f31dbeae483b61
|
[
"BSL-1.0"
] | null | null | null |
test/communicator_broadcast.cpp
|
correaa/b-mpi3
|
161e52a28ab9043be9ef33acd8f31dbeae483b61
|
[
"BSL-1.0"
] | null | null | null |
test/communicator_broadcast.cpp
|
correaa/b-mpi3
|
161e52a28ab9043be9ef33acd8f31dbeae483b61
|
[
"BSL-1.0"
] | null | null | null |
#if COMPILATION_INSTRUCTIONS
mpic++ -O3 -std=c++14 -Wall -Wfatal-errors $0 -o $0x.x && time mpirun -n 2 $0x.x $@ && rm -f $0x.x; exit
#endif
// © Copyright Alfredo A. Correa 2018-2020
#include "../../mpi3/main.hpp"
#include "../../mpi3/communicator.hpp"
namespace mpi3 = boost::mpi3;
int mpi3::main(int, char*[], mpi3::communicator world){
std::vector<std::size_t> sizes = {100, 64*1024};//, 128*1024}; // TODO check larger number (fails with openmpi 4.0.5)
int NUM_REPS = 5;
using value_type = int;
std::vector<value_type> buf(128*1024);
for(std::size_t n=0; n != sizes.size(); ++n){
// if(world.root()) cout<<"bcasting "<< sizes[n] <<" ints "<< NUM_REPS <<" times.\n";
for(int reps = 0; reps != NUM_REPS; ++reps){
if(world.root())
for(std::size_t i = 0; i != sizes[n]; ++i){
buf[i] = 1000000.*(n * NUM_REPS + reps) + i;
}
else
for(std::size_t i = 0; i != sizes[n]; ++i){
buf[i] = -(n * NUM_REPS + reps) - 1;
}
world.broadcast_n(buf.begin(), sizes[n]);
// world.broadcast(buf.begin(), buf.begin() + sizes[n], 0);
for(std::size_t i = 0; i != sizes[n]; ++i)
assert( fabs(buf[i] - (1000000.*(n * NUM_REPS + reps) + i)) < 1e-4 );
}
}
return 0;
}
| 27.545455
| 118
| 0.575908
|
correaa
|
460819731d1f58a91ad128467d955be784f981e0
| 764
|
hpp
|
C++
|
libs/resource_tree/include/sge/resource_tree/detail/strip_path_prefix.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
libs/resource_tree/include/sge/resource_tree/detail/strip_path_prefix.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
libs/resource_tree/include/sge/resource_tree/detail/strip_path_prefix.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// 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)
#ifndef SGE_RESOURCE_TREE_DETAIL_STRIP_PATH_PREFIX_HPP_INCLUDED
#define SGE_RESOURCE_TREE_DETAIL_STRIP_PATH_PREFIX_HPP_INCLUDED
#include <sge/resource_tree/path_fwd.hpp>
#include <sge/resource_tree/detail/base_path.hpp>
#include <sge/resource_tree/detail/sub_path.hpp>
#include <sge/resource_tree/detail/symbol.hpp>
namespace sge::resource_tree::detail
{
SGE_RESOURCE_TREE_DETAIL_SYMBOL
sge::resource_tree::path strip_path_prefix(
sge::resource_tree::detail::base_path const &, sge::resource_tree::detail::sub_path const &);
}
#endif
| 31.833333
| 97
| 0.784031
|
cpreh
|
4608b94ee463cd53b6600c1666ac954f0d0ee380
| 3,114
|
cpp
|
C++
|
Drivers/SelfTests/Boundaries/InsertionBoundarySelfTest.cpp
|
gustavo-castillo-bautista/Mercury
|
eeb402ccec8e487652229d4595c46ec84f6aefbb
|
[
"BSD-3-Clause"
] | null | null | null |
Drivers/SelfTests/Boundaries/InsertionBoundarySelfTest.cpp
|
gustavo-castillo-bautista/Mercury
|
eeb402ccec8e487652229d4595c46ec84f6aefbb
|
[
"BSD-3-Clause"
] | null | null | null |
Drivers/SelfTests/Boundaries/InsertionBoundarySelfTest.cpp
|
gustavo-castillo-bautista/Mercury
|
eeb402ccec8e487652229d4595c46ec84f6aefbb
|
[
"BSD-3-Clause"
] | null | null | null |
//Copyright (c) 2013-2020, The MercuryDPM Developers Team. All rights reserved.
//For the list of developers, see <http://www.MercuryDPM.org/Team>.
//
//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 MercuryDPM 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 MERCURYDPM DEVELOPERS TEAM 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 <iostream>
#include "Mercury3D.h"
#include "Boundaries/CubeInsertionBoundary.h"
#include "Boundaries/PeriodicBoundary.h"
#include "Species/LinearViscoelasticSpecies.h"
#include "Walls/InfiniteWall.h"
class InsertionBoundarySelfTest : public Mercury3D
{
public:
void setupInitialConditions() override {
setName("InsertionBoundarySelfTest");
setSystemDimensions(3);
setGravity(Vec3D(0, 0, 0));
setTimeStep(1e-4);
dataFile.setSaveCount(10);
setTimeMax(2e-2);
setHGridMaxLevels(2);
setMin(Vec3D(0, 0, 0));
setMax(Vec3D(1, 1, 1));
LinearViscoelasticSpecies species;
species.setDensity(2000);
species.setStiffness(10000);
speciesHandler.copyAndAddObject(species);
SphericalParticle insertionBoundaryParticle;
insertionBoundaryParticle.setSpecies(speciesHandler.getObject(0));
CubeInsertionBoundary insertionBoundary;
insertionBoundary.set(&insertionBoundaryParticle,1,getMin(),getMax(),Vec3D(1,0,0),Vec3D(1,0,0),0.025,0.05);
boundaryHandler.copyAndAddObject(insertionBoundary);
}
void printTime() const override
{
logger(INFO,"t=%, tMax=%, N=%", getTime(),getTimeMax(), particleHandler.getSize());
}
};
int main(int argc UNUSED, char *argv[] UNUSED)
{
logger(INFO,"Simple box for creating particles");
InsertionBoundarySelfTest insertionBoundary_problem;
insertionBoundary_problem.solve();
}
| 39.923077
| 115
| 0.738279
|
gustavo-castillo-bautista
|
460ad4d2f8b2dec3cb9b937daa8937e88710138c
| 1,572
|
cc
|
C++
|
solutions/mrJudge/base/main.cc
|
zwliew/ctci
|
871f4fc957be96c6d0749d205549b7b35dc53d9e
|
[
"MIT"
] | 4
|
2020-11-07T14:38:02.000Z
|
2022-01-03T19:02:36.000Z
|
solutions/mrJudge/base/main.cc
|
zwliew/ctci
|
871f4fc957be96c6d0749d205549b7b35dc53d9e
|
[
"MIT"
] | 1
|
2019-04-17T06:55:14.000Z
|
2019-04-17T06:55:14.000Z
|
solutions/mrJudge/base/main.cc
|
zwliew/ctci
|
871f4fc957be96c6d0749d205549b7b35dc53d9e
|
[
"MIT"
] | null | null | null |
// #include <bits/stdc++.h>
#include <algorithm>
#include <cmath>
#include <deque>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
#define FOR(i, j, k, l) for (s32 i = j; i < k; i += l)
#define RFOR(i, j, k, l) for (s32 i = j; i >= k; i -= l)
#define REP(i, j) FOR(i, 0, j, 1)
#define RREP(i, j) RFOR(i, j, 0, 1)
#define ALL(x) x.begin(), x.end()
#define MEAN(a, b) min(a, b) + (abs(b - a) / 2)
#define FASTIO() \
cin.tie(nullptr); \
ios::sync_with_stdio(false);
typedef int64_t s64;
typedef uint64_t u64;
typedef int32_t s32;
typedef uint32_t u32;
typedef float f32;
typedef double f64;
inline long long pw(long long i, long long p) {
return !p ? 1 : p >> 1 ? pw(i * i, p >> 1) * (p % 2 ? i : 1) : i;
}
int main() {
// Don't collapse the block
FASTIO();
string x;
s64 a, b;
cin >> x >> a >> b;
if (a == b || x == "0") {
cout << x;
return 0;
}
s64 b10 = 0;
if (a == 10) {
b10 = stoi(x);
} else {
REP(i, x.size()) {
s64 c;
if (isdigit(x[i])) {
c = x[i] - '0';
} else {
c = x[i] - 'A' + 10;
}
b10 += c * pw(a, x.size() - 1 - i);
}
if (b == 10) {
cout << b10;
return 0;
}
}
string r;
while (b10) {
s64 c;
c = b10 % b;
if (c >= 10) {
c += 'A' - 10;
} else {
c += '0';
}
// cout << b10 << ' ' << b10 / b << ' ' << c << '\n';
r.push_back(c);
b10 /= b;
}
reverse(r.begin(), r.end());
cout << r;
}
| 18.494118
| 67
| 0.48028
|
zwliew
|
460e73849e3611b85524258bf2aaa70644de2b5f
| 22,430
|
cpp
|
C++
|
scatterplot.cpp
|
fadel/msc-pm
|
bedf6936885694688ddb8bd3452f6bd68ef8d29c
|
[
"MIT"
] | null | null | null |
scatterplot.cpp
|
fadel/msc-pm
|
bedf6936885694688ddb8bd3452f6bd68ef8d29c
|
[
"MIT"
] | null | null | null |
scatterplot.cpp
|
fadel/msc-pm
|
bedf6936885694688ddb8bd3452f6bd68ef8d29c
|
[
"MIT"
] | null | null | null |
#include "scatterplot.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <QSGGeometryNode>
#include <QSGSimpleRectNode>
#include "continuouscolorscale.h"
#include "geometry.h"
// Glyphs settings
static const QColor DEFAULT_GLYPH_COLOR(255, 255, 255);
static const float DEFAULT_GLYPH_SIZE = 8.0f;
static const qreal GLYPH_OPACITY = 1.0;
static const qreal GLYPH_OPACITY_SELECTED = 1.0;
static const float GLYPH_OUTLINE_WIDTH = 2.0f;
static const QColor GLYPH_OUTLINE_COLOR(0, 0, 0);
static const QColor GLYPH_OUTLINE_COLOR_SELECTED(20, 255, 225);
// Brush settings
static const float BRUSHING_MAX_DIST = 20.0f;
static const float CROSSHAIR_LENGTH = 8.0f;
static const float CROSSHAIR_THICKNESS1 = 1.0f;
static const float CROSSHAIR_THICKNESS2 = 0.5f;
static const QColor CROSSHAIR_COLOR1(255, 255, 255);
static const QColor CROSSHAIR_COLOR2(0, 0, 0);
// Selection settings
static const QColor SELECTION_COLOR(128, 128, 128, 96);
// Mouse buttons
static const Qt::MouseButton NORMAL_BUTTON = Qt::LeftButton;
static const Qt::MouseButton SPECIAL_BUTTON = Qt::RightButton;
class QuadTree
{
public:
QuadTree(const QRectF &bounds);
~QuadTree();
bool insert(float x, float y, int value);
int query(float x, float y) const;
void query(const QRectF &rect, std::vector<int> &result) const;
int nearestTo(float x, float y) const;
private:
bool subdivide();
void nearestTo(float x, float y, int &nearest, float &dist) const;
QRectF m_bounds;
float m_x, m_y;
int m_value;
QuadTree *m_nw, *m_ne, *m_sw, *m_se;
};
Scatterplot::Scatterplot(QQuickItem *parent)
: QQuickItem(parent)
, m_glyphSize(DEFAULT_GLYPH_SIZE)
, m_colorScale(0)
, m_autoScale(true)
, m_sx(0, 1, 0, 1)
, m_sy(0, 1, 0, 1)
, m_anySelected(false)
, m_brushedItem(-1)
, m_interactionState(StateNone)
, m_dragEnabled(false)
, m_shouldUpdateGeometry(false)
, m_shouldUpdateMaterials(false)
, m_quadtree(0)
{
setClip(true);
setFlag(QQuickItem::ItemHasContents);
}
Scatterplot::~Scatterplot()
{
if (m_quadtree) {
delete m_quadtree;
}
}
void Scatterplot::setColorScale(const ColorScale *colorScale)
{
m_colorScale = colorScale;
if (m_colorData.n_elem > 0) {
m_shouldUpdateMaterials = true;
update();
}
}
arma::mat Scatterplot::XY() const
{
return m_xy;
}
void Scatterplot::setXY(const arma::mat &xy)
{
if (xy.n_cols != 2) {
return;
}
m_xy = xy;
emit xyChanged(m_xy);
if (m_autoScale) {
autoScale();
}
updateQuadTree();
if (m_selection.size() != m_xy.n_rows) {
m_selection.assign(m_xy.n_rows, false);
}
if (m_opacityData.n_elem != m_xy.n_rows) {
// Reset opacity data
m_opacityData.resize(xy.n_rows);
m_opacityData.fill(GLYPH_OPACITY);
emit opacityDataChanged(m_opacityData);
}
m_shouldUpdateGeometry = true;
update();
}
void Scatterplot::setColorData(const arma::vec &colorData)
{
if (m_xy.n_rows > 0
&& (colorData.n_elem > 0 && colorData.n_elem != m_xy.n_rows)) {
return;
}
m_colorData = colorData;
emit colorDataChanged(m_colorData);
m_shouldUpdateMaterials = true;
update();
}
void Scatterplot::setOpacityData(const arma::vec &opacityData)
{
if (m_xy.n_rows > 0 && opacityData.n_elem != m_xy.n_rows) {
return;
}
m_opacityData = opacityData;
emit opacityDataChanged(m_opacityData);
update();
}
void Scatterplot::setScale(const LinearScale<float> &sx, const LinearScale<float> &sy)
{
m_sx = sx;
m_sy = sy;
emit scaleChanged(m_sx, m_sy);
updateQuadTree();
m_shouldUpdateGeometry = true;
update();
}
void Scatterplot::setAutoScale(bool autoScale)
{
m_autoScale = autoScale;
if (autoScale) {
this->autoScale();
}
}
void Scatterplot::autoScale()
{
m_sx.setDomain(m_xy.col(0).min(), m_xy.col(0).max());
m_sy.setDomain(m_xy.col(1).min(), m_xy.col(1).max());
emit scaleChanged(m_sx, m_sy);
}
void Scatterplot::setGlyphSize(float glyphSize)
{
if (m_glyphSize == glyphSize || glyphSize < 2.0f) {
return;
}
m_glyphSize = glyphSize;
emit glyphSizeChanged(m_glyphSize);
m_shouldUpdateGeometry = true;
update();
}
QSGNode *Scatterplot::newSceneGraph()
{
// NOTE:
// The hierarchy in the scene graph is as follows:
// root [[splatNode] [glyphsRoot [glyph [...]]] [selectionNode]]
QSGNode *root = new QSGNode;
QSGNode *glyphTreeRoot = newGlyphTree();
if (glyphTreeRoot) {
root->appendChildNode(glyphTreeRoot);
}
QSGSimpleRectNode *selectionRectNode = new QSGSimpleRectNode;
selectionRectNode->setColor(SELECTION_COLOR);
root->appendChildNode(selectionRectNode);
QSGTransformNode *brushNode = new QSGTransformNode;
QSGGeometryNode *whiteCrossHairNode = new QSGGeometryNode;
QSGGeometry *whiteCrossHairGeom = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 12);
whiteCrossHairGeom->setDrawingMode(GL_POLYGON);
whiteCrossHairGeom->setVertexDataPattern(QSGGeometry::DynamicPattern);
updateCrossHairGeometry(whiteCrossHairGeom, 0, 0, CROSSHAIR_THICKNESS1, CROSSHAIR_LENGTH);
QSGFlatColorMaterial *whiteCrossHairMaterial = new QSGFlatColorMaterial;
whiteCrossHairMaterial->setColor(CROSSHAIR_COLOR1);
whiteCrossHairNode->setGeometry(whiteCrossHairGeom);
whiteCrossHairNode->setMaterial(whiteCrossHairMaterial);
whiteCrossHairNode->setFlags(QSGNode::OwnsGeometry | QSGNode::OwnsMaterial);
brushNode->appendChildNode(whiteCrossHairNode);
QSGGeometryNode *blackCrossHairNode = new QSGGeometryNode;
QSGGeometry *blackCrossHairGeom = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 12);
blackCrossHairGeom->setDrawingMode(GL_POLYGON);
blackCrossHairGeom->setVertexDataPattern(QSGGeometry::DynamicPattern);
updateCrossHairGeometry(blackCrossHairGeom, 0, 0, CROSSHAIR_THICKNESS2, CROSSHAIR_LENGTH);
QSGFlatColorMaterial *blackCrossHairMaterial = new QSGFlatColorMaterial;
blackCrossHairMaterial->setColor(CROSSHAIR_COLOR2);
blackCrossHairNode->setGeometry(blackCrossHairGeom);
blackCrossHairNode->setMaterial(blackCrossHairMaterial);
blackCrossHairNode->setFlags(QSGNode::OwnsGeometry | QSGNode::OwnsMaterial);
brushNode->appendChildNode(blackCrossHairNode);
root->appendChildNode(brushNode);
return root;
}
QSGNode *Scatterplot::newGlyphTree()
{
// NOTE:
// The glyph graph is structured as:
// root [opacityNode [outlineNode fillNode] ...]
if (m_xy.n_rows < 1) {
return 0;
}
QSGNode *node = new QSGNode;
int vertexCount = calculateCircleVertexCount(m_glyphSize);
for (arma::uword i = 0; i < m_xy.n_rows; i++) {
QSGGeometry *glyphOutlineGeometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), vertexCount);
glyphOutlineGeometry->setDrawingMode(GL_POLYGON);
glyphOutlineGeometry->setVertexDataPattern(QSGGeometry::DynamicPattern);
QSGGeometryNode *glyphOutlineNode = new QSGGeometryNode;
glyphOutlineNode->setGeometry(glyphOutlineGeometry);
glyphOutlineNode->setFlag(QSGNode::OwnsGeometry);
QSGFlatColorMaterial *material = new QSGFlatColorMaterial;
material->setColor(GLYPH_OUTLINE_COLOR);
glyphOutlineNode->setMaterial(material);
glyphOutlineNode->setFlag(QSGNode::OwnsMaterial);
QSGGeometry *glyphGeometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), vertexCount);
glyphGeometry->setDrawingMode(GL_POLYGON);
glyphGeometry->setVertexDataPattern(QSGGeometry::DynamicPattern);
QSGGeometryNode *glyphNode = new QSGGeometryNode;
glyphNode->setGeometry(glyphGeometry);
glyphNode->setFlag(QSGNode::OwnsGeometry);
material = new QSGFlatColorMaterial;
material->setColor(DEFAULT_GLYPH_COLOR);
glyphNode->setMaterial(material);
glyphNode->setFlag(QSGNode::OwnsMaterial);
// Place the glyph geometry node under an opacity node
QSGOpacityNode *glyphOpacityNode = new QSGOpacityNode;
glyphOpacityNode->appendChildNode(glyphOutlineNode);
glyphOpacityNode->appendChildNode(glyphNode);
node->appendChildNode(glyphOpacityNode);
}
return node;
}
QSGNode *Scatterplot::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
QSGNode *root = oldNode ? oldNode : newSceneGraph();
if (m_xy.n_rows < 1) {
return root;
}
// This keeps track of where we are in the scene when updating
QSGNode *node = root->firstChild();
updateGlyphs(node);
node = node->nextSibling();
if (m_shouldUpdateGeometry) {
m_shouldUpdateGeometry = false;
}
if (m_shouldUpdateMaterials) {
m_shouldUpdateMaterials = false;
}
// Selection
QSGSimpleRectNode *selectionNode = static_cast<QSGSimpleRectNode *>(node);
if (m_interactionState == StateSelecting) {
selectionNode->setRect(QRectF(m_dragOriginPos, m_dragCurrentPos));
selectionNode->markDirty(QSGNode::DirtyGeometry);
} else {
// Hide selection rect
selectionNode->setRect(QRectF(-1, -1, 0, 0));
}
node = node->nextSibling();
// Brushing
updateBrush(node);
node = node->nextSibling();
return root;
}
void Scatterplot::updateGlyphs(QSGNode *glyphsNode)
{
qreal x, y, tx, ty, moveTranslationF;
if (!m_shouldUpdateGeometry && !m_shouldUpdateMaterials) {
return;
}
if (m_interactionState == StateMoving) {
tx = m_dragCurrentPos.x() - m_dragOriginPos.x();
ty = m_dragCurrentPos.y() - m_dragOriginPos.y();
} else {
tx = ty = 0;
}
m_sx.setRange(PADDING, width() - PADDING);
m_sy.setRange(height() - PADDING, PADDING);
QSGNode *node = glyphsNode->firstChild();
for (arma::uword i = 0; i < m_xy.n_rows; i++) {
const arma::rowvec &row = m_xy.row(i);
bool isSelected = m_selection[i];
QSGOpacityNode *glyphOpacityNode = static_cast<QSGOpacityNode *>(node);
glyphOpacityNode->setOpacity(m_opacityData[i]);
QSGGeometryNode *glyphOutlineNode = static_cast<QSGGeometryNode *>(node->firstChild());
QSGGeometryNode *glyphNode = static_cast<QSGGeometryNode *>(node->firstChild()->nextSibling());
if (m_shouldUpdateGeometry) {
moveTranslationF = isSelected ? 1.0 : 0.0;
x = m_sx(row[0]) + tx * moveTranslationF;
y = m_sy(row[1]) + ty * moveTranslationF;
QSGGeometry *geometry = glyphOutlineNode->geometry();
updateCircleGeometry(geometry, m_glyphSize, x, y);
glyphOutlineNode->markDirty(QSGNode::DirtyGeometry);
geometry = glyphNode->geometry();
updateCircleGeometry(geometry, m_glyphSize - 2*GLYPH_OUTLINE_WIDTH, x, y);
glyphNode->markDirty(QSGNode::DirtyGeometry);
}
if (m_shouldUpdateMaterials) {
QSGFlatColorMaterial *material = static_cast<QSGFlatColorMaterial *>(glyphOutlineNode->material());
material->setColor(isSelected ? GLYPH_OUTLINE_COLOR_SELECTED
: GLYPH_OUTLINE_COLOR);
glyphOutlineNode->markDirty(QSGNode::DirtyMaterial);
material = static_cast<QSGFlatColorMaterial *>(glyphNode->material());
if (m_colorData.n_elem > 0) {
material->setColor(m_colorScale->color(m_colorData[i]));
} else {
material->setColor(DEFAULT_GLYPH_COLOR);
}
glyphNode->markDirty(QSGNode::DirtyMaterial);
}
node = node->nextSibling();
}
// XXX: Beware: QSGNode::DirtyForceUpdate is undocumented
//
// This causes the scene graph to correctly update the materials of glyphs,
// even though we individually mark dirty materials. Used to work in Qt 5.5,
// though.
glyphsNode->markDirty(QSGNode::DirtyForceUpdate);
}
void Scatterplot::updateBrush(QSGNode *node)
{
QMatrix4x4 transform;
if (m_brushedItem < 0
|| (m_interactionState != StateNone
&& m_interactionState != StateSelected)) {
transform.translate(-width(), -height());
} else {
const arma::rowvec &row = m_xy.row(m_brushedItem);
transform.translate(m_sx(row[0]), m_sy(row[1]));
}
QSGTransformNode *brushNode = static_cast<QSGTransformNode *>(node);
brushNode->setMatrix(transform);
}
void Scatterplot::mousePressEvent(QMouseEvent *event)
{
switch (m_interactionState) {
case StateNone:
case StateSelected:
switch (event->button()) {
case NORMAL_BUTTON:
if (event->modifiers() == Qt::ShiftModifier && m_dragEnabled) {
m_interactionState = StateMoving;
m_dragOriginPos = event->localPos();
m_dragCurrentPos = m_dragOriginPos;
} else {
// We say 'brushing', but we mean 'selecting the current brushed
// item'
m_interactionState = StateBrushing;
}
break;
case SPECIAL_BUTTON:
m_interactionState = StateNone;
m_selection.assign(m_selection.size(), false);
emit selectionInteractivelyChanged(m_selection);
m_shouldUpdateMaterials = true;
update();
break;
}
break;
case StateBrushing:
case StateSelecting:
case StateMoving:
// Probably shouldn't reach these
break;
}
}
void Scatterplot::mouseMoveEvent(QMouseEvent *event)
{
switch (m_interactionState) {
case StateBrushing:
// Move while brushing becomes selecting, hence the 'fall through'
m_interactionState = StateSelecting;
m_dragOriginPos = event->localPos();
// fall through
case StateSelecting:
m_dragCurrentPos = event->localPos();
update();
break;
case StateMoving:
m_dragCurrentPos = event->localPos();
m_shouldUpdateGeometry = true;
update();
break;
case StateNone:
case StateSelected:
break;
}
}
void Scatterplot::mouseReleaseEvent(QMouseEvent *event)
{
bool mergeSelection = (event->modifiers() == Qt::ControlModifier);
switch (m_interactionState) {
case StateBrushing:
// Mouse clicked with brush target; set new selection or append to
// current
if (!mergeSelection) {
m_selection.assign(m_selection.size(), false);
}
if (m_brushedItem == -1) {
m_interactionState = StateNone;
if (m_anySelected && !mergeSelection) {
m_anySelected = false;
emit selectionInteractivelyChanged(m_selection);
m_shouldUpdateMaterials = true;
update();
}
} else {
m_interactionState = StateSelected;
m_selection[m_brushedItem] = !m_selection[m_brushedItem];
if (m_selection[m_brushedItem]) {
m_anySelected = true;
}
emit selectionInteractivelyChanged(m_selection);
m_shouldUpdateMaterials = true;
update();
}
break;
case StateSelecting:
{
// Selecting points and mouse is now released; update selection and
// brush
interactiveSelection(mergeSelection);
m_interactionState = m_anySelected ? StateSelected : StateNone;
QPoint pos = event->pos();
m_brushedItem = m_quadtree->nearestTo(pos.x(), pos.y());
emit itemInteractivelyBrushed(m_brushedItem);
m_shouldUpdateMaterials = true;
update();
}
break;
case StateMoving:
// Moving points and now stopped; apply manipulation
m_interactionState = StateSelected;
applyManipulation();
m_shouldUpdateGeometry = true;
update();
m_dragOriginPos = m_dragCurrentPos;
break;
case StateNone:
case StateSelected:
break;
}
}
void Scatterplot::hoverEnterEvent(QHoverEvent *event)
{
QPointF pos = event->posF();
m_brushedItem = m_quadtree->nearestTo(pos.x(), pos.y());
emit itemInteractivelyBrushed(m_brushedItem);
update();
}
void Scatterplot::hoverMoveEvent(QHoverEvent *event)
{
QPointF pos = event->posF();
m_brushedItem = m_quadtree->nearestTo(pos.x(), pos.y());
emit itemInteractivelyBrushed(m_brushedItem);
update();
}
void Scatterplot::hoverLeaveEvent(QHoverEvent *event)
{
m_brushedItem = -1;
emit itemInteractivelyBrushed(m_brushedItem);
update();
}
void Scatterplot::interactiveSelection(bool mergeSelection)
{
if (!mergeSelection) {
m_selection.assign(m_selection.size(), false);
}
std::vector<int> selected;
m_quadtree->query(QRectF(m_dragOriginPos, m_dragCurrentPos), selected);
for (auto i: selected) {
m_selection[i] = true;
}
for (auto isSelected: m_selection) {
if (isSelected) {
m_anySelected = true;
break;
}
}
emit selectionInteractivelyChanged(m_selection);
}
void Scatterplot::setSelection(const std::vector<bool> &selection)
{
if (m_selection.size() != selection.size()) {
return;
}
m_selection = selection;
emit selectionChanged(m_selection);
m_shouldUpdateMaterials = true;
update();
}
void Scatterplot::brushItem(int item)
{
m_brushedItem = item;
update();
}
void Scatterplot::applyManipulation()
{
m_sx.inverse();
m_sy.inverse();
LinearScale<float> rx = m_sx;
LinearScale<float> ry = m_sy;
m_sy.inverse();
m_sx.inverse();
float tx = m_dragCurrentPos.x() - m_dragOriginPos.x();
float ty = m_dragCurrentPos.y() - m_dragOriginPos.y();
for (std::vector<bool>::size_type i = 0; i < m_selection.size(); i++) {
if (m_selection[i]) {
arma::rowvec row = m_xy.row(i);
row[0] = rx(m_sx(row[0]) + tx);
row[1] = ry(m_sy(row[1]) + ty);
m_xy.row(i) = row;
}
}
updateQuadTree();
emit xyInteractivelyChanged(m_xy);
}
void Scatterplot::updateQuadTree()
{
m_sx.setRange(PADDING, width() - PADDING);
m_sy.setRange(height() - PADDING, PADDING);
if (m_quadtree) {
delete m_quadtree;
}
m_quadtree = new QuadTree(QRectF(x(), y(), width(), height()));
for (arma::uword i = 0; i < m_xy.n_rows; i++) {
const arma::rowvec &row = m_xy.row(i);
m_quadtree->insert(m_sx(row[0]), m_sy(row[1]), (int) i);
}
}
QuadTree::QuadTree(const QRectF &bounds)
: m_bounds(bounds)
, m_value(-1)
, m_nw(0), m_ne(0), m_sw(0), m_se(0)
{
}
QuadTree::~QuadTree()
{
if (m_nw) {
delete m_nw;
delete m_ne;
delete m_sw;
delete m_se;
}
}
bool QuadTree::subdivide()
{
float halfWidth = m_bounds.width() / 2;
float halfHeight = m_bounds.height() / 2;
m_nw = new QuadTree(QRectF(m_bounds.x(),
m_bounds.y(),
halfWidth,
halfHeight));
m_ne = new QuadTree(QRectF(m_bounds.x() + halfWidth,
m_bounds.y(),
halfWidth,
halfHeight));
m_sw = new QuadTree(QRectF(m_bounds.x(),
m_bounds.y() + halfHeight,
halfWidth,
halfHeight));
m_se = new QuadTree(QRectF(m_bounds.x() + halfWidth,
m_bounds.y() + halfHeight,
halfWidth,
halfHeight));
int value = m_value;
m_value = -1;
return m_nw->insert(m_x, m_y, value)
|| m_ne->insert(m_x, m_y, value)
|| m_sw->insert(m_x, m_y, value)
|| m_se->insert(m_x, m_y, value);
}
bool QuadTree::insert(float x, float y, int value)
{
if (!m_bounds.contains(x, y)) {
return false;
}
if (m_nw) {
return m_nw->insert(x, y, value)
|| m_ne->insert(x, y, value)
|| m_sw->insert(x, y, value)
|| m_se->insert(x, y, value);
}
if (m_value >= 0) {
subdivide();
return insert(x, y, value);
}
m_x = x;
m_y = y;
m_value = value;
return true;
}
int QuadTree::nearestTo(float x, float y) const
{
if (!m_bounds.contains(x, y)) {
return -1;
}
int q;
if (m_nw) {
q = m_nw->nearestTo(x, y);
if (q >= 0) return q;
q = m_ne->nearestTo(x, y);
if (q >= 0) return q;
q = m_sw->nearestTo(x, y);
if (q >= 0) return q;
q = m_se->nearestTo(x, y);
if (q >= 0) return q;
}
float dist = std::numeric_limits<float>::infinity();
nearestTo(x, y, q, dist);
if (dist < BRUSHING_MAX_DIST * BRUSHING_MAX_DIST)
return q;
return -1;
}
void QuadTree::nearestTo(float x, float y, int &nearest, float &dist) const
{
if (m_nw) {
m_nw->nearestTo(x, y, nearest, dist);
m_ne->nearestTo(x, y, nearest, dist);
m_sw->nearestTo(x, y, nearest, dist);
m_se->nearestTo(x, y, nearest, dist);
} else if (m_value >= 0) {
float d = (m_x - x)*(m_x - x) + (m_y - y)*(m_y - y);
if (d < dist) {
nearest = m_value;
dist = d;
}
}
}
int QuadTree::query(float x, float y) const
{
if (!m_bounds.contains(x, y)) {
// There is no way we could find the point
return -1;
}
if (m_nw) {
int q = -1;
q = m_nw->query(x, y);
if (q >= 0) return q;
q = m_ne->query(x, y);
if (q >= 0) return q;
q = m_sw->query(x, y);
if (q >= 0) return q;
q = m_se->query(x, y);
return q;
}
return m_value;
}
void QuadTree::query(const QRectF &rect, std::vector<int> &result) const
{
if (!m_bounds.intersects(rect)) {
return;
}
if (m_nw) {
m_nw->query(rect, result);
m_ne->query(rect, result);
m_sw->query(rect, result);
m_se->query(rect, result);
} else if (rect.contains(m_x, m_y) && m_value != -1) {
result.push_back(m_value);
}
}
| 28.609694
| 115
| 0.626973
|
fadel
|
4612f6436bee91d7c6b0cfc94f22418164a6900d
| 2,187
|
cpp
|
C++
|
排序/交换排序/P324.6.cpp
|
Ruvikm/Wangdao-Data-Structures
|
e00494f40c0be9d81229062bf69fe1e12e340773
|
[
"MIT"
] | 103
|
2021-01-07T13:03:57.000Z
|
2022-03-31T03:10:35.000Z
|
排序/交换排序/P324.6.cpp
|
fu123567/Wangdao-Data-Structures
|
e00494f40c0be9d81229062bf69fe1e12e340773
|
[
"MIT"
] | null | null | null |
排序/交换排序/P324.6.cpp
|
fu123567/Wangdao-Data-Structures
|
e00494f40c0be9d81229062bf69fe1e12e340773
|
[
"MIT"
] | 23
|
2021-04-10T07:53:03.000Z
|
2022-03-31T00:33:05.000Z
|
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
using namespace std;
#pragma region 建立顺序存储的线性表
#define MAX 30
#define _for(i,a,b) for( int i=(a); i<(b); ++i)
#define _rep(i,a,b) for( int i=(a); i<=(b); ++i)
typedef struct {
int data[MAX];
int length;
}List;
void swap(int& a, int& b) {
int t;
t = a;
a = b;
b = t;
}
//给定一个List,传入List的大小,要逆转的起始位置
void Reserve(List& list, int start, int end, int size) {
if (end <= start || end >= size) {
return;
}
int mid = (start + end) / 2;
_rep(i, 0, mid - start) {
swap(list.data[start + i], list.data[end - i]);
}
}
void PrintList(List list) {
_for(i, 0, list.length) {
cout << list.data[i] << " ";
}
cout << endl;
}
void BuildList(List& list, int Len, int Data[]) {
list.length = Len;
_for(i, 0, list.length)
list.data[i] = Data[i];
}
#pragma endregion
//P323.6
//〖2016统考真题】已知由n(n≥2)个正整数构成的集合A = { ak|0 ≤ k ≤ n }, 将其划分为两
//个不相交的子集A1和A2, 元素个数分别是n1和n2, A1和A2中的元素之和分别为S1和S2
//设计一个尽可能高效的划分算法, 满足|n1 - n2|最小且| S1 - S1|最大。要求
//1)给出算法的基本设计思想
//2)根据设计思想, 采用C或C++语言描述算法, 关键之处给出注释
//3)说明你所设计算法的平均时间复杂度和空间复杂度
int Partiton(List& list) {
int low = 0, low0 = 0, high = list.length - 1, high0 = list.length - 1, k = list.length / 2;
bool NoFind = true;
while (NoFind) {
int pivot = list.data[low];
while (low < high) {
while (low < high && list.data[high] >= pivot)
high--;
if (low != high)
list.data[low] = list.data[high];
while (low < high && list.data[low] <= pivot)
low++;
if (low != high)
list.data[high] = list.data[low];
}
list.data[low] = pivot;
if (low == k - 1)
NoFind = false;
else {
if (low < k - 1) {
low0 = ++low;
high = high0;
}
else {
high0 = --high;
low = low0;
}
}
}
int s1 = 0, s2 = 0;
_for(i, 0, k)
s1 += list.data[i];
_for(i, k, list.length)
s2 += list.data[i];
return s2 - s1;
}
int main()
{
List list;
int Data[] = { 1,43,22,12,14,24,18,54,32,81 };
BuildList(list, 10, Data);
cout << "list为:" << endl;
PrintList(list);
cout << "排序后:" << endl;
sort(list.data, list.data + 10);
PrintList(list);
cout << "S2-S1最大值为:" << Partiton(list) << endl;
return 0;
}
| 19.184211
| 93
| 0.581619
|
Ruvikm
|
4615023df5a596ca4b465687e621a84d88042a86
| 359
|
cpp
|
C++
|
module02/ex02/main.cpp
|
JLL32/piscine-cpp
|
d1d3296d8e25a1c33f7c92df4f61e6f76b8dab8c
|
[
"MIT"
] | null | null | null |
module02/ex02/main.cpp
|
JLL32/piscine-cpp
|
d1d3296d8e25a1c33f7c92df4f61e6f76b8dab8c
|
[
"MIT"
] | null | null | null |
module02/ex02/main.cpp
|
JLL32/piscine-cpp
|
d1d3296d8e25a1c33f7c92df4f61e6f76b8dab8c
|
[
"MIT"
] | null | null | null |
#include "Fixed.hpp"
int main() {
Fixed a;
Fixed const b(Fixed(5.05f) * Fixed(2));
std::cout << a << std::endl;
std::cout << ++a << std::endl;
std::cout << a << std::endl;
std::cout << a++ << std::endl;
std::cout << a << std::endl;
std::cout << b << std::endl;
std::cout << Fixed::max(a, b) << std::endl;
return 0;
}
| 22.4375
| 47
| 0.487465
|
JLL32
|
4617cf0f44153d1785df9b344a815585abe10e79
| 1,569
|
cpp
|
C++
|
Codeforces/MailRu/2018/Round1/C.cpp
|
Mindjolt2406/Competitive-Programming
|
d000d98bf7005ee4fb809bcea2f110e4c4793b80
|
[
"MIT"
] | 2
|
2018-12-11T14:37:24.000Z
|
2022-01-23T18:11:54.000Z
|
Codeforces/MailRu/2018/Round1/C.cpp
|
Mindjolt2406/Competitive-Programming
|
d000d98bf7005ee4fb809bcea2f110e4c4793b80
|
[
"MIT"
] | null | null | null |
Codeforces/MailRu/2018/Round1/C.cpp
|
Mindjolt2406/Competitive-Programming
|
d000d98bf7005ee4fb809bcea2f110e4c4793b80
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1000000001
#define MOD 1000000007
#define ll long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long int>
#define sc(n) scanf("%d",&n);
#define scll(n) scanf("%lld",&n);
#define scld(n) scanf("%Lf",&n);
#define scr(s) {char temp[1000000];scanf("%s",temp);s = temp;}
using namespace std;
int main()
{
int n;
sc(n);
int*l = new int[n];
int*r = new int[n];
for(int i=0;i<n;i++) sc(l[i]);
for(int i=0;i<n;i++) sc(r[i]);
vector<int> v;
set<int> s;
int max1 = -1;
for(int i=0;i<n;i++)
{
if(l[i]>i || r[i]>n-1-i) {cout<<"NO"<<endl;return 0;}
else {v.pu(n-l[i]-r[i]);s.insert(n-l[i]-r[i]);max1 = max(max1,l[i]+r[i]);}
}
// cout<<s.size()<<en dl;
// for(int i=0;i<n;i++)
// {
// for(int j=i+1;j<n;j++)
// {
// if(l[i]+r[i]<l[j]+r[j] && r[i]<r[j]) {cout<<"NO"<<endl;return 0;}
// if(l[i]+r[i]<l[j]+r[j] && l[i]>l[j]) {cout<<"NO"<<endl;return 0;}
// }
// }
// map<int,int> dl,dr;
// int maxl,maxr
for(int i=0;i<n;i++)
{
// cout<<"i: "<<i<<endl;
int count = 0;
for(int j=i+1;j<n;j++)
{
if(l[j]+r[j]<l[i]+r[i]) count++;
}
if(count>r[i]) {cout<<"NO"<<endl;return 0;}
}
for(int i=n-1;i>=0;i--)
{
int count = 0;
for(int j=i-1;j>=0;j--)
{
if(l[j]+r[j]<l[i]+r[i]) count++;
}
if(count>l[i]) {cout<<"NO"<<endl;return 0;}
}
cout<<"YES"<<endl;
for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl;
return 0;
}
| 22.73913
| 78
| 0.50478
|
Mindjolt2406
|