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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3315e71bb76a9986841cd5c493beee6dcfe223bb | 5,774 | cpp | C++ | drivers/windows/drv_ndis_intermediate/notifyObj/src/dllmain.cpp | openPOWERLINK-Team/openPOWERLINK_V2 | 048650a80db37fa372330c3a900d2c8edb327e47 | [
"BSD-3-Clause"
] | 100 | 2016-05-18T06:38:44.000Z | 2022-03-30T13:53:58.000Z | drivers/windows/drv_ndis_intermediate/notifyObj/src/dllmain.cpp | openPOWERLINK-Team/openPOWERLINK_V2 | 048650a80db37fa372330c3a900d2c8edb327e47 | [
"BSD-3-Clause"
] | 238 | 2016-03-31T06:52:57.000Z | 2019-10-17T13:35:03.000Z | drivers/windows/drv_ndis_intermediate/notifyObj/src/dllmain.cpp | openPOWERLINK-Team/openPOWERLINK_V2 | 048650a80db37fa372330c3a900d2c8edb327e47 | [
"BSD-3-Clause"
] | 72 | 2016-04-04T07:29:24.000Z | 2022-03-13T05:26:54.000Z | /**
********************************************************************************
\file dllmain.cpp
\brief Main file for notify object dll for Windows NDIS intermediate driver
This file implements the DLL access routines for notify object.
\ingroup module_notify_ndisim
*******************************************************************************/
/*------------------------------------------------------------------------------
Copyright (c) 2015, Kalycito Infotech Private Limited
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holders 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 COPYRIGHT HOLDERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------*/
//------------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------------
#include "stdafx.h"
#include "resource.h"
#include "notifyObj_i.h"
#include "dllmain.h"
#include "notify.h"
#include <netcfgn.h>
#include "common.h"
//============================================================================//
// G L O B A L D E F I N I T I O N S //
//============================================================================//
//------------------------------------------------------------------------------
// const defines
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// module global vars
//------------------------------------------------------------------------------
CNotifyObjModule _AtlModule;
BEGIN_OBJECT_MAP(ObjectMap)
OBJECT_ENTRY(CLSID_CNotify, CNotify)
END_OBJECT_MAP()
//------------------------------------------------------------------------------
// global function prototypes
//------------------------------------------------------------------------------
//============================================================================//
// P R I V A T E D E F I N I T I O N S //
//============================================================================//
//------------------------------------------------------------------------------
// const defines
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// local types
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// local vars
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// local function prototypes
//------------------------------------------------------------------------------
//============================================================================//
// P U B L I C F U N C T I O N S //
//============================================================================//
//------------------------------------------------------------------------------
// DLL Entry Point
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/**
\brief DLL main routine
The function implements openPOWERLINK Windows kernel driver initialization callback.
OS calls this routine on driver registration.
\ingroup module_notify_ndisim
*/
//------------------------------------------------------------------------------
extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance_p, DWORD reason_p, LPVOID pReserved_p)
{
TRACE(L"DllMain.\n");
if (reason_p == DLL_PROCESS_ATTACH)
{
TRACE(L" Reason: Attach.\n");
DisableThreadLibraryCalls(hInstance_p);
}
else
{
if (reason_p == DLL_PROCESS_DETACH)
{
TRACE(L" Reason: Detach.\n");
}
}
return _AtlModule.DllMain(reason_p, pReserved_p);
}
//============================================================================//
// P R I V A T E F U N C T I O N S //
//============================================================================//
/// \name Private Functions
/// \{
/// \}
| 42.77037 | 89 | 0.38275 | openPOWERLINK-Team |
331a4498f388bf0383c2bb52e6f39639392d9312 | 3,630 | cc | C++ | src/yb/rpc/strand.cc | impira/yugabyte-db | dd979c24856ae0c55d872e2488a15147b75d7821 | [
"Apache-2.0",
"CC0-1.0"
] | 3,702 | 2019-09-17T13:49:56.000Z | 2022-03-31T21:50:59.000Z | src/yb/rpc/strand.cc | impira/yugabyte-db | dd979c24856ae0c55d872e2488a15147b75d7821 | [
"Apache-2.0",
"CC0-1.0"
] | 9,291 | 2019-09-16T21:47:07.000Z | 2022-03-31T23:52:28.000Z | src/yb/rpc/strand.cc | impira/yugabyte-db | dd979c24856ae0c55d872e2488a15147b75d7821 | [
"Apache-2.0",
"CC0-1.0"
] | 673 | 2019-09-16T21:27:53.000Z | 2022-03-31T22:23:59.000Z | // Copyright (c) YugaByte, 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
//
// 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 "yb/rpc/strand.h"
#include <thread>
#include "yb/util/flag_tags.h"
DEFINE_test_flag(int32, strand_done_inject_delay_ms, 0,
"Inject into Strand::Done after resetting running flag.");
using namespace std::literals;
namespace yb {
namespace rpc {
namespace {
const Status& StrandAbortedStatus() {
static const Status result = STATUS(Aborted, "Strand shutdown");
return result;
}
}
Strand::Strand(ThreadPool* thread_pool) : thread_pool_(*thread_pool) {}
Strand::~Strand() {
const auto running = running_.load();
const auto closing = closing_.load();
const auto active_tasks = active_tasks_.load();
LOG_IF(DFATAL, running || !closing || active_tasks) << Format(
"Strand $0 has not been fully shut down, running: $1, closing: $2, active_tasks: $3",
static_cast<void*>(this), running, closing, active_tasks);
}
void Strand::Enqueue(StrandTask* task) {
if (closing_.load(std::memory_order_acquire)) {
task->Done(STATUS(Aborted, "Strand closing"));
return;
}
active_tasks_.fetch_add(1, std::memory_order_release);
queue_.Push(task);
bool expected = false;
if (running_.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
thread_pool_.Enqueue(this);
}
}
void Strand::Shutdown() {
bool expected = false;
if (!closing_.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
LOG(DFATAL) << "Strand already closed";
return;
}
while (active_tasks_.load(std::memory_order_acquire) ||
running_.load(std::memory_order_acquire)) {
// We expected shutdown to happen rarely, so just use busy wait here.
std::this_thread::sleep_for(1ms);
}
}
void Strand::Run() {
// Actual work is performed in Done.
// Because we need `Status`, i.e. if `Strand` task aborted, because of thread pool shutdown.
// We should abort all enqueued tasks.
}
void Strand::Done(const Status& status) {
for (;;) {
size_t tasks_fetched = 0;
while (StrandTask *task = queue_.Pop()) {
++tasks_fetched;
const auto& actual_status =
!closing_.load(std::memory_order_acquire) ? status : StrandAbortedStatus();
if (actual_status.ok()) {
task->Run();
}
task->Done(actual_status);
}
running_.store(false, std::memory_order_release);
if (FLAGS_TEST_strand_done_inject_delay_ms > 0) {
std::this_thread::sleep_for(FLAGS_TEST_strand_done_inject_delay_ms * 1ms);
}
// Decrease active_tasks_ and check whether tasks have been added while we were setting running
// to false.
if (active_tasks_.fetch_sub(tasks_fetched) > tasks_fetched) {
// Got more operations, try stay in the loop.
bool expected = false;
if (running_.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
continue;
}
// If someone else has flipped running_ to true, we can safely exit this function because
// another task is already submitted to thread pool.
}
break;
}
}
} // namespace rpc
} // namespace yb
| 31.025641 | 100 | 0.695041 | impira |
331d1320163fcdd3e94818383e320fde159c64ad | 1,911 | cpp | C++ | sources/Engine/App.cpp | LukasBanana/ForkENGINE | 8b575bd1d47741ad5025a499cb87909dbabc3492 | [
"BSD-3-Clause"
] | 13 | 2017-03-21T22:46:18.000Z | 2020-07-30T01:31:57.000Z | sources/Engine/App.cpp | LukasBanana/ForkENGINE | 8b575bd1d47741ad5025a499cb87909dbabc3492 | [
"BSD-3-Clause"
] | null | null | null | sources/Engine/App.cpp | LukasBanana/ForkENGINE | 8b575bd1d47741ad5025a499cb87909dbabc3492 | [
"BSD-3-Clause"
] | 2 | 2018-07-23T19:56:41.000Z | 2020-07-30T01:32:01.000Z | /*
* Engine app file
*
* This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "Engine/App.h"
#include "IO/Core/Log.h"
#include "IO/Core/Console.h"
namespace Fork
{
namespace Engine
{
static App* appInstance = nullptr;
App::App()
{
appInstance = this;
}
App::~App()
{
}
void App::OnInit(int numArgs, char** args)
{
IO::Log::AddDefaultEventHandler();
OnInit();
}
void App::OnInit()
{
// dummy
}
void App::OnMain()
{
while (!IsQuit())
{
OnUpdate();
OnRender();
engine.UpdateFrameStates();
}
}
void App::OnUpdate()
{
// dummy
}
void App::OnRender()
{
// dummy
}
void App::OnCleanUp()
{
// dummy
}
void App::OnUnhandledException(const DefaultException& err)
{
IO::Log::ClearEventHandlers();
IO::Log::AddDefaultEventHandler();
IO::Log::Error(err);
IO::Console::Wait();
}
void App::OnUnhandledException(const std::exception& err)
{
IO::Log::ClearEventHandlers();
IO::Log::AddDefaultEventHandler();
IO::Log::Error(err.what());
IO::Console::Wait();
}
void App::OnExit()
{
// dummy
}
int App::RunApp(App* app, int numArgs, char** args)
{
if (app)
{
try
{
app->OnInit(numArgs, args);
app->OnMain();
app->OnCleanUp();
}
catch (const DefaultException& err)
{
app->OnUnhandledException(err);
}
catch (const std::exception& err)
{
app->OnUnhandledException(err);
}
/*catch (...)
{
abort();
}*/
app->OnExit();
}
return 0;
}
App* App::Instance()
{
return appInstance;
}
/*
* ======= Protected: =======
*/
bool App::IsQuit()
{
return true;
}
} // /namespace Engine
} // /namespace Fork
// ======================== | 14.051471 | 79 | 0.537938 | LukasBanana |
331d7bfe9da030abc8be507cfc44b2476b7e031e | 26,670 | cpp | C++ | LambdaEngine/Source/Rendering/ParticleRenderer.cpp | IbexOmega/CrazyCanvas | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 18 | 2020-09-04T08:00:54.000Z | 2021-08-29T23:04:45.000Z | LambdaEngine/Source/Rendering/ParticleRenderer.cpp | IbexOmega/LambdaEngine | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 32 | 2020-09-12T19:24:50.000Z | 2020-12-11T14:29:44.000Z | LambdaEngine/Source/Rendering/ParticleRenderer.cpp | IbexOmega/LambdaEngine | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 2 | 2020-12-15T15:36:13.000Z | 2021-03-27T14:27:02.000Z | #include "Rendering/ParticleRenderer.h"
#include "Rendering/Core/API/CommandAllocator.h"
#include "Rendering/Core/API/CommandList.h"
#include "Rendering/Core/API/DescriptorHeap.h"
#include "Rendering/Core/API/DescriptorSet.h"
#include "Rendering/Core/API/PipelineState.h"
#include "Rendering/Core/API/TextureView.h"
#include "Rendering/ParticleManager.h"
#include "Rendering/RenderAPI.h"
namespace LambdaEngine
{
ParticleRenderer* ParticleRenderer::s_pInstance = nullptr;
ParticleRenderer::ParticleRenderer()
{
VALIDATE(s_pInstance == nullptr);
s_pInstance = this;
m_ParticleCount = 0;
m_EmitterCount = 1;
}
ParticleRenderer::~ParticleRenderer()
{
VALIDATE(s_pInstance != nullptr);
s_pInstance = nullptr;
if (m_Initilized)
{
for (uint32 b = 0; b < m_BackBufferCount; b++)
{
SAFERELEASE(m_ppGraphicCommandLists[b]);
SAFERELEASE(m_ppGraphicCommandAllocators[b]);
}
SAFEDELETE_ARRAY(m_ppGraphicCommandLists);
SAFEDELETE_ARRAY(m_ppGraphicCommandAllocators);
}
}
bool LambdaEngine::ParticleRenderer::CreatePipelineLayout()
{
DescriptorBindingDesc perFrameBufferBindingDesc = {};
perFrameBufferBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_CONSTANT_BUFFER;
perFrameBufferBindingDesc.DescriptorCount = 1;
perFrameBufferBindingDesc.Binding = 0;
perFrameBufferBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_ALL;
DescriptorBindingDesc textureBindingDesc0 = {};
textureBindingDesc0.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
textureBindingDesc0.DescriptorCount = 100;
textureBindingDesc0.Binding = 0;
textureBindingDesc0.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
textureBindingDesc0.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND;
DescriptorBindingDesc textureBindingDesc1 = {};
textureBindingDesc1.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
textureBindingDesc1.DescriptorCount = 1;
textureBindingDesc1.Binding = 1;
textureBindingDesc1.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
textureBindingDesc1.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND;
DescriptorBindingDesc textureBindingDesc2 = {};
textureBindingDesc2.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
textureBindingDesc2.DescriptorCount = 100;
textureBindingDesc2.Binding = 2;
textureBindingDesc2.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
textureBindingDesc2.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND;
DescriptorBindingDesc verticesBindingDesc = {};
verticesBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
verticesBindingDesc.DescriptorCount = 1;
verticesBindingDesc.Binding = 0;
verticesBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER;
DescriptorBindingDesc instanceBindingDesc = {};
instanceBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
instanceBindingDesc.DescriptorCount = 1;
instanceBindingDesc.Binding = 1;
instanceBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER;
DescriptorBindingDesc emitterBindingDesc = {};
emitterBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
emitterBindingDesc.DescriptorCount = 1;
emitterBindingDesc.Binding = 2;
emitterBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER;
DescriptorBindingDesc emitterIndexBindingDesc = {};
emitterIndexBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
emitterIndexBindingDesc.DescriptorCount = 1;
emitterIndexBindingDesc.Binding = 3;
emitterIndexBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER;
DescriptorBindingDesc lightBufferBindingDesc = {};
lightBufferBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
lightBufferBindingDesc.DescriptorCount = 1;
lightBufferBindingDesc.Binding = 4;
lightBufferBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
DescriptorBindingDesc atlasDataBindingDesc = {};
atlasDataBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
atlasDataBindingDesc.DescriptorCount = 1;
atlasDataBindingDesc.Binding = 0;
atlasDataBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER;
DescriptorSetLayoutDesc descriptorSetLayoutDesc1 = {};
descriptorSetLayoutDesc1.DescriptorBindings = { perFrameBufferBindingDesc };
DescriptorSetLayoutDesc descriptorSetLayoutDesc2 = {};
descriptorSetLayoutDesc2.DescriptorBindings = { textureBindingDesc0, textureBindingDesc1, textureBindingDesc2 };
DescriptorSetLayoutDesc descriptorSetLayoutDesc3 = {};
descriptorSetLayoutDesc3.DescriptorBindings = { verticesBindingDesc, instanceBindingDesc, emitterBindingDesc, emitterIndexBindingDesc, lightBufferBindingDesc };
DescriptorSetLayoutDesc descriptorSetLayoutDesc4 = {};
descriptorSetLayoutDesc4.DescriptorBindings = { atlasDataBindingDesc };
PipelineLayoutDesc pipelineLayoutDesc = { };
pipelineLayoutDesc.DebugName = "Particle Renderer Pipeline Layout";
pipelineLayoutDesc.DescriptorSetLayouts = { descriptorSetLayoutDesc1, descriptorSetLayoutDesc2, descriptorSetLayoutDesc3, descriptorSetLayoutDesc4 };
m_PipelineLayout = RenderAPI::GetDevice()->CreatePipelineLayout(&pipelineLayoutDesc);
return m_PipelineLayout != nullptr;
}
bool LambdaEngine::ParticleRenderer::CreateDescriptorSets()
{
DescriptorHeapInfo descriptorCountDesc = { };
descriptorCountDesc.SamplerDescriptorCount = 0;
descriptorCountDesc.TextureDescriptorCount = 0;
descriptorCountDesc.TextureCombinedSamplerDescriptorCount = 1;
descriptorCountDesc.ConstantBufferDescriptorCount = 1;
descriptorCountDesc.UnorderedAccessBufferDescriptorCount = 5;
descriptorCountDesc.UnorderedAccessTextureDescriptorCount = 0;
descriptorCountDesc.AccelerationStructureDescriptorCount = 0;
DescriptorHeapDesc descriptorHeapDesc = { };
descriptorHeapDesc.DebugName = "Particle Renderer Descriptor Heap";
descriptorHeapDesc.DescriptorSetCount = 64;
descriptorHeapDesc.DescriptorCount = descriptorCountDesc;
m_DescriptorHeap = RenderAPI::GetDevice()->CreateDescriptorHeap(&descriptorHeapDesc);
if (!m_DescriptorHeap)
{
return false;
}
m_PerFrameBufferDescriptorSet = RenderAPI::GetDevice()->CreateDescriptorSet("Particle Buffer Descriptor Set 0", m_PipelineLayout.Get(), 0, m_DescriptorHeap.Get());
if (m_PerFrameBufferDescriptorSet == nullptr)
{
LOG_ERROR("[ParticleRenderer]: Failed to create PerFrameBuffer Descriptor Set 0");
return false;
}
return true;
}
bool LambdaEngine::ParticleRenderer::CreateShaders()
{
bool success = true;
if (m_MeshShaders)
{
m_MeshShaderGUID = ResourceManager::LoadShaderFromFile("/Particles/Particle.mesh", FShaderStageFlag::SHADER_STAGE_FLAG_MESH_SHADER, EShaderLang::SHADER_LANG_GLSL);
success &= m_MeshShaderGUID != GUID_NONE;
}
else
{
m_VertexShaderGUID = ResourceManager::LoadShaderFromFile("/Particles/Particle.vert", FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER, EShaderLang::SHADER_LANG_GLSL);
success &= m_VertexShaderGUID != GUID_NONE;
}
m_PixelShaderGUID = ResourceManager::LoadShaderFromFile("/Particles/Particle.frag", FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER, EShaderLang::SHADER_LANG_GLSL);
success &= m_PixelShaderGUID != GUID_NONE;
return success;
}
bool LambdaEngine::ParticleRenderer::CreateCommandLists()
{
m_ppGraphicCommandAllocators = DBG_NEW CommandAllocator * [m_BackBufferCount];
m_ppGraphicCommandLists = DBG_NEW CommandList * [m_BackBufferCount];
for (uint32 b = 0; b < m_BackBufferCount; b++)
{
m_ppGraphicCommandAllocators[b] = RenderAPI::GetDevice()->CreateCommandAllocator("Particle Renderer Graphics Command Allocator " + std::to_string(b), ECommandQueueType::COMMAND_QUEUE_TYPE_GRAPHICS);
if (!m_ppGraphicCommandAllocators[b])
{
return false;
}
CommandListDesc commandListDesc = {};
commandListDesc.DebugName = "Particle Renderer Graphics Command List " + std::to_string(b);
commandListDesc.CommandListType = ECommandListType::COMMAND_LIST_TYPE_PRIMARY;
commandListDesc.Flags = FCommandListFlag::COMMAND_LIST_FLAG_ONE_TIME_SUBMIT;
m_ppGraphicCommandLists[b] = RenderAPI::GetDevice()->CreateCommandList(m_ppGraphicCommandAllocators[b], &commandListDesc);
if (!m_ppGraphicCommandLists[b])
{
return false;
}
}
return true;
}
bool LambdaEngine::ParticleRenderer::CreateRenderPass(RenderPassAttachmentDesc* pColorAttachmentDesc, RenderPassAttachmentDesc* pDepthStencilAttachmentDesc)
{
RenderPassAttachmentDesc colorAttachmentDesc = {};
colorAttachmentDesc.Format = EFormat::FORMAT_R8G8B8A8_UNORM;
colorAttachmentDesc.SampleCount = 1;
colorAttachmentDesc.LoadOp = ELoadOp::LOAD_OP_CLEAR;
colorAttachmentDesc.StoreOp = EStoreOp::STORE_OP_STORE;
colorAttachmentDesc.StencilLoadOp = ELoadOp::LOAD_OP_DONT_CARE;
colorAttachmentDesc.StencilStoreOp = EStoreOp::STORE_OP_DONT_CARE;
colorAttachmentDesc.InitialState = pColorAttachmentDesc->InitialState;
colorAttachmentDesc.FinalState = pColorAttachmentDesc->FinalState;
RenderPassAttachmentDesc depthAttachmentDesc = {};
depthAttachmentDesc.Format = EFormat::FORMAT_D24_UNORM_S8_UINT;
depthAttachmentDesc.SampleCount = 1;
depthAttachmentDesc.LoadOp = ELoadOp::LOAD_OP_LOAD;
depthAttachmentDesc.StoreOp = EStoreOp::STORE_OP_STORE;
depthAttachmentDesc.StencilLoadOp = ELoadOp::LOAD_OP_DONT_CARE;
depthAttachmentDesc.StencilStoreOp = EStoreOp::STORE_OP_DONT_CARE;
depthAttachmentDesc.InitialState = pDepthStencilAttachmentDesc->InitialState;
depthAttachmentDesc.FinalState = pDepthStencilAttachmentDesc->FinalState;
RenderPassSubpassDesc subpassDesc = {};
subpassDesc.RenderTargetStates = { ETextureState::TEXTURE_STATE_RENDER_TARGET };
subpassDesc.DepthStencilAttachmentState = ETextureState::TEXTURE_STATE_DEPTH_STENCIL_ATTACHMENT;
RenderPassSubpassDependencyDesc subpassDependencyDesc = {};
subpassDependencyDesc.SrcSubpass = EXTERNAL_SUBPASS;
subpassDependencyDesc.DstSubpass = 0;
subpassDependencyDesc.SrcAccessMask = 0;
subpassDependencyDesc.DstAccessMask = FMemoryAccessFlag::MEMORY_ACCESS_FLAG_MEMORY_READ | FMemoryAccessFlag::MEMORY_ACCESS_FLAG_MEMORY_WRITE;
subpassDependencyDesc.SrcStageMask = FPipelineStageFlag::PIPELINE_STAGE_FLAG_RENDER_TARGET_OUTPUT;
subpassDependencyDesc.DstStageMask = FPipelineStageFlag::PIPELINE_STAGE_FLAG_RENDER_TARGET_OUTPUT;
RenderPassDesc renderPassDesc = {};
renderPassDesc.DebugName = "Particle Renderer Render Pass";
renderPassDesc.Attachments = { colorAttachmentDesc, depthAttachmentDesc };
renderPassDesc.Subpasses = { subpassDesc };
renderPassDesc.SubpassDependencies = { subpassDependencyDesc };
m_RenderPass = RenderAPI::GetDevice()->CreateRenderPass(&renderPassDesc);
return true;
}
bool LambdaEngine::ParticleRenderer::CreatePipelineState()
{
ManagedGraphicsPipelineStateDesc pipelineStateDesc = {};
pipelineStateDesc.DebugName = "Particle Pipeline State";
pipelineStateDesc.RenderPass = m_RenderPass;
pipelineStateDesc.PipelineLayout = m_PipelineLayout;
pipelineStateDesc.InputAssembly.PrimitiveTopology = EPrimitiveTopology::PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
pipelineStateDesc.RasterizerState.LineWidth = 1.f;
pipelineStateDesc.RasterizerState.PolygonMode = EPolygonMode::POLYGON_MODE_FILL;
pipelineStateDesc.RasterizerState.CullMode = ECullMode::CULL_MODE_NONE;
pipelineStateDesc.DepthStencilState = {};
pipelineStateDesc.DepthStencilState.DepthTestEnable = true;
pipelineStateDesc.DepthStencilState.DepthWriteEnable = true;
pipelineStateDesc.BlendState.BlendAttachmentStates =
{
{
.BlendOp = EBlendOp::BLEND_OP_ADD,
.SrcBlend = EBlendFactor::BLEND_FACTOR_SRC_ALPHA,
.DstBlend = EBlendFactor::BLEND_FACTOR_INV_SRC_ALPHA,
.BlendOpAlpha = EBlendOp::BLEND_OP_ADD,
.SrcBlendAlpha = EBlendFactor::BLEND_FACTOR_SRC_ALPHA,
.DstBlendAlpha = EBlendFactor::BLEND_FACTOR_INV_SRC_ALPHA,
.RenderTargetComponentMask = COLOR_COMPONENT_FLAG_R | COLOR_COMPONENT_FLAG_G | COLOR_COMPONENT_FLAG_B | COLOR_COMPONENT_FLAG_A,
.BlendEnabled = true
}
};
pipelineStateDesc.VertexShader.ShaderGUID = m_VertexShaderGUID;
pipelineStateDesc.PixelShader.ShaderGUID = m_PixelShaderGUID;
m_PipelineStateID = PipelineStateManager::CreateGraphicsPipelineState(&pipelineStateDesc);
return true;
}
bool LambdaEngine::ParticleRenderer::Init()
{
m_BackBufferCount = BACK_BUFFER_COUNT;
m_ParticleCount = 0;
if (!CreatePipelineLayout())
{
LOG_ERROR("[ParticleRenderer]: Failed to create PipelineLayout");
return false;
}
if (!CreateDescriptorSets())
{
LOG_ERROR("[ParticleRenderer]: Failed to create DescriptorSet");
return false;
}
if (!CreateShaders())
{
LOG_ERROR("[ParticleRenderer]: Failed to create Shaders");
return false;
}
return true;
}
bool LambdaEngine::ParticleRenderer::RenderGraphInit(const CustomRendererRenderGraphInitDesc* pPreInitDesc)
{
VALIDATE(pPreInitDesc);
VALIDATE(pPreInitDesc->pColorAttachmentDesc != nullptr);
VALIDATE(pPreInitDesc->pDepthStencilAttachmentDesc != nullptr);
if (!m_Initilized)
{
if (!CreateCommandLists())
{
LOG_ERROR("[ParticleRenderer]: Failed to create render command lists");
return false;
}
if (!CreateRenderPass(pPreInitDesc->pColorAttachmentDesc, pPreInitDesc->pDepthStencilAttachmentDesc))
{
LOG_ERROR("[ParticleRenderer]: Failed to create RenderPass");
return false;
}
if (!CreatePipelineState())
{
LOG_ERROR("[ParticleRenderer]: Failed to create PipelineState");
return false;
}
// Create a initial particle atlas descriptor set and set the content to a default texture.
m_AtlasTexturesDescriptorSet = m_DescriptorCache.GetDescriptorSet("Particle Atlas texture Descriptor Set", m_PipelineLayout.Get(), 1, m_DescriptorHeap.Get());
if (m_AtlasTexturesDescriptorSet != nullptr)
{
TextureView* textureView = ResourceManager::GetTextureView(GUID_TEXTURE_DEFAULT_COLOR_MAP);
Sampler* sampler = Sampler::GetLinearSampler();
m_AtlasTexturesDescriptorSet->WriteTextureDescriptors(
&textureView,
&sampler,
ETextureState::TEXTURE_STATE_SHADER_READ_ONLY,
0,
1,
EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER,
true
);
}
else
{
LOG_ERROR("[ParticleRenderer]: Failed to update DescriptorSet[%d]", 0);
}
m_Initilized = true;
}
return true;
}
void ParticleRenderer::Update(Timestamp delta, uint32 modFrameIndex, uint32 backBufferIndex)
{
UNREFERENCED_VARIABLE(delta);
UNREFERENCED_VARIABLE(backBufferIndex);
m_DescriptorCache.HandleUnavailableDescriptors(modFrameIndex);
}
void ParticleRenderer::UpdateTextureResource(const String& resourceName, const TextureView* const* ppPerImageTextureViews, const TextureView* const* ppPerSubImageTextureViews, const Sampler* const* ppPerImageSamplers, uint32 imageCount, uint32 subImageCount, bool backBufferBound)
{
UNREFERENCED_VARIABLE(ppPerSubImageTextureViews);
UNREFERENCED_VARIABLE(subImageCount);
UNREFERENCED_VARIABLE(backBufferBound);
if (resourceName == "PARTICLE_IMAGE")
{
if (imageCount == 1)
{
m_RenderTarget = MakeSharedRef(ppPerImageTextureViews[0]);
}
else
{
LOG_ERROR("[ParticleRenderer]: Failed to update Render Target Resource");
}
}
else if (resourceName == SCENE_PARTICLE_ATLAS_IMAGES)
{
constexpr uint32 setIndex = 1U;
constexpr uint32 setBinding = 0U;
m_AtlasTexturesDescriptorSet = m_DescriptorCache.GetDescriptorSet("Particle Atlas texture Descriptor Set", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_AtlasTexturesDescriptorSet != nullptr)
{
m_AtlasTexturesDescriptorSet->WriteTextureDescriptors(
ppPerImageTextureViews,
ppPerImageSamplers,
ETextureState::TEXTURE_STATE_SHADER_READ_ONLY,
setBinding,
imageCount,
EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER,
true
);
}
else
{
LOG_ERROR("[ParticleRenderer]: Failed to update m_AtlasTexturesDescriptorSet");
}
}
else if (resourceName == "DIRL_SHADOWMAP")
{
constexpr uint32 setIndex = 1U;
constexpr uint32 setBinding = 1U;
m_AtlasTexturesDescriptorSet = m_DescriptorCache.GetDescriptorSet("Particle Point Lights texture Descriptor Set", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_AtlasTexturesDescriptorSet != nullptr)
{
m_AtlasTexturesDescriptorSet->WriteTextureDescriptors(
ppPerImageTextureViews,
ppPerImageSamplers,
ETextureState::TEXTURE_STATE_SHADER_READ_ONLY,
setBinding,
imageCount,
EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER,
false
);
}
else
{
LOG_ERROR("[ParticleRenderer]: Failed to update m_AtlasTexturesDescriptorSet");
}
}
else if (resourceName == SCENE_POINT_SHADOWMAPS)
{
constexpr uint32 setIndex = 1U;
constexpr uint32 setBinding = 2U;
m_AtlasTexturesDescriptorSet = m_DescriptorCache.GetDescriptorSet("Particle Point Lights texture Descriptor Set", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_AtlasTexturesDescriptorSet != nullptr)
{
//Sampler* pSampler = Sampler::GetLinearSampler();
m_AtlasTexturesDescriptorSet->WriteTextureDescriptors(
ppPerImageTextureViews,
ppPerImageSamplers,
ETextureState::TEXTURE_STATE_SHADER_READ_ONLY,
setBinding,
imageCount,
EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER,
false
);
}
else
{
LOG_ERROR("[ParticleRenderer]: Failed to update m_AtlasTexturesDescriptorSet");
}
}
else if (resourceName == "G_BUFFER_DEPTH_STENCIL")
{
if (imageCount == 1)
{
m_DepthStencil = MakeSharedRef(ppPerImageTextureViews[0]);
}
else
{
LOG_ERROR("[ParticleRenderer]: Failed to update Depth Stencil Resource");
}
}
}
void ParticleRenderer::UpdateBufferResource(const String& resourceName, const Buffer* const* ppBuffers, uint64* pOffsets, uint64* pSizesInBytes, uint32 count, bool backBufferBound)
{
UNREFERENCED_VARIABLE(resourceName);
UNREFERENCED_VARIABLE(ppBuffers);
UNREFERENCED_VARIABLE(pOffsets);
UNREFERENCED_VARIABLE(pSizesInBytes);
UNREFERENCED_VARIABLE(count);
UNREFERENCED_VARIABLE(backBufferBound);
if (resourceName == PER_FRAME_BUFFER)
{
constexpr uint32 setIndex = 0U;
constexpr uint32 setBinding = 0U;
m_PerFrameBufferDescriptorSet = m_DescriptorCache.GetDescriptorSet("Per Frame Buffer Descriptor Set 0 Binding 0", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_PerFrameBufferDescriptorSet != nullptr)
{
m_PerFrameBufferDescriptorSet->WriteBufferDescriptors(
ppBuffers,
pOffsets,
pSizesInBytes,
setBinding,
count,
EDescriptorType::DESCRIPTOR_TYPE_CONSTANT_BUFFER
);
}
else
{
LOG_ERROR("[ParticleRenderer]: Failed to update m_PerFrameBufferDescriptorSet");
}
}
if (resourceName == SCENE_PARTICLE_VERTEX_BUFFER)
{
if (count == 1)
{
constexpr uint32 setIndex = 2U;
constexpr uint32 setBinding = 0U;
m_VertexInstanceDescriptorSet = m_DescriptorCache.GetDescriptorSet("Vertex Instance Buffer Descriptor Set 2 Binding 0", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_VertexInstanceDescriptorSet != nullptr)
{
m_VertexInstanceDescriptorSet->WriteBufferDescriptors(ppBuffers, pOffsets, pSizesInBytes, setBinding, 1, EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER);
}
else
{
LOG_ERROR("[ParticleRenderer]: Failed to update VertexInstanceDescriptorSet");
}
}
}
else if (resourceName == SCENE_PARTICLE_INSTANCE_BUFFER)
{
if (count == 1)
{
constexpr uint32 setIndex = 2U;
constexpr uint32 setBinding = 1U;
m_VertexInstanceDescriptorSet = m_DescriptorCache.GetDescriptorSet("Particle Instance Buffer Descriptor Set 2 Binding 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_VertexInstanceDescriptorSet != nullptr)
{
m_VertexInstanceDescriptorSet->WriteBufferDescriptors(ppBuffers, pOffsets, pSizesInBytes, setBinding, 1, EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER);
}
else
{
LOG_ERROR("[ParticleRenderer]: Failed to update VertexInstanceDescriptorSet");
}
}
}
else if (resourceName == SCENE_EMITTER_INSTANCE_BUFFER)
{
constexpr uint32 setIndex = 2U;
constexpr uint32 setBinding = 2U;
m_VertexInstanceDescriptorSet = m_DescriptorCache.GetDescriptorSet("Emitter Instance Buffer Descriptor Set 2 Binding 2", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_VertexInstanceDescriptorSet != nullptr)
{
m_VertexInstanceDescriptorSet->WriteBufferDescriptors(
ppBuffers,
pOffsets,
pSizesInBytes,
setBinding,
count,
EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER
);
}
else
{
LOG_ERROR("[ParticleUpdater]: Failed to update DescriptorSet[%d]", 0);
}
}
else if (resourceName == SCENE_EMITTER_INDEX_BUFFER)
{
constexpr uint32 setIndex = 2U;
constexpr uint32 setBinding = 3U;
m_VertexInstanceDescriptorSet = m_DescriptorCache.GetDescriptorSet("Emitter Index Buffer Descriptor Set 2 Binding 3", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_VertexInstanceDescriptorSet != nullptr)
{
m_VertexInstanceDescriptorSet->WriteBufferDescriptors(
ppBuffers,
pOffsets,
pSizesInBytes,
setBinding,
count,
EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER
);
}
else
{
LOG_ERROR("[ParticleUpdater]: Failed to update DescriptorSet[%d]", 0);
}
}
else if (resourceName == SCENE_LIGHTS_BUFFER)
{
constexpr uint32 setIndex = 2U;
constexpr uint32 setBinding = 4U;
m_VertexInstanceDescriptorSet = m_DescriptorCache.GetDescriptorSet("Emitter Index Buffer Descriptor Set 2 Binding 4", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_VertexInstanceDescriptorSet != nullptr)
{
m_VertexInstanceDescriptorSet->WriteBufferDescriptors(
ppBuffers,
pOffsets,
pSizesInBytes,
setBinding,
count,
EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER
);
}
else
{
LOG_ERROR("[ParticleUpdater]: Failed to update DescriptorSet[%d]", 0);
}
}
if (resourceName == SCENE_PARTICLE_INDEX_BUFFER)
{
if (count == 1)
{
m_pIndexBuffer = ppBuffers[0];
}
}
if (resourceName == SCENE_PARTICLE_INDIRECT_BUFFER)
{
if (count == 1)
{
m_pIndirectBuffer = ppBuffers[0];
}
}
if (resourceName == SCENE_PARTICLE_ATLAS_INFO_BUFFER)
{
if (count == 1)
{
constexpr uint32 setIndex = 3U;
constexpr uint32 setBinding = 0U;
m_AtlasInfoBufferDescriptorSet = m_DescriptorCache.GetDescriptorSet("Atlas Info Buffer Descriptor Set 3 Binding 0", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_AtlasInfoBufferDescriptorSet != nullptr)
{
m_AtlasInfoBufferDescriptorSet->WriteBufferDescriptors(ppBuffers, pOffsets, pSizesInBytes, setBinding, 1, EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER);
}
else
{
LOG_ERROR("[ParticleRenderer]: Failed to update m_AtlasInfoBufferDescriptorSet");
}
}
}
}
void ParticleRenderer::Render(uint32 modFrameIndex, uint32 backBufferIndex, CommandList** ppFirstExecutionStage, CommandList** ppSecondaryExecutionStage, bool Sleeping)
{
UNREFERENCED_VARIABLE(modFrameIndex);
UNREFERENCED_VARIABLE(backBufferIndex);
UNREFERENCED_VARIABLE(ppFirstExecutionStage);
UNREFERENCED_VARIABLE(ppSecondaryExecutionStage);
CommandList* pCommandList = m_ppGraphicCommandLists[modFrameIndex];
m_ppGraphicCommandAllocators[modFrameIndex]->Reset();
pCommandList->Begin(nullptr);
pCommandList->BindGraphicsPipeline(PipelineStateManager::GetPipelineState(m_PipelineStateID));
TSharedRef<const TextureView> renderTarget = m_RenderTarget;
uint32 width = renderTarget->GetDesc().pTexture->GetDesc().Width;
uint32 height = renderTarget->GetDesc().pTexture->GetDesc().Height;
Viewport viewport = {};
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.Width = (float32)width;
viewport.Height = -(float32)height;
viewport.x = 0.0f;
viewport.y = (float32)height;
pCommandList->SetViewports(&viewport, 0, 1);
ScissorRect scissorRect = {};
scissorRect.Width = width;
scissorRect.Height = height;
pCommandList->SetScissorRects(&scissorRect, 0, 1);
ClearColorDesc clearColors[1] = {};
clearColors[0].Color[0] = 0.f;
clearColors[0].Color[1] = 0.f;
clearColors[0].Color[2] = 0.f;
clearColors[0].Color[3] = 0.f;
pCommandList->BindDescriptorSetGraphics(m_PerFrameBufferDescriptorSet.Get(), m_PipelineLayout.Get(), 0);
pCommandList->BindDescriptorSetGraphics(m_AtlasTexturesDescriptorSet.Get(), m_PipelineLayout.Get(), 1);
pCommandList->BindDescriptorSetGraphics(m_VertexInstanceDescriptorSet.Get(), m_PipelineLayout.Get(), 2);
pCommandList->BindDescriptorSetGraphics(m_AtlasInfoBufferDescriptorSet.Get(), m_PipelineLayout.Get(), 3);
pCommandList->BindIndexBuffer(m_pIndexBuffer, 0, EIndexType::INDEX_TYPE_UINT32);
BeginRenderPassDesc beginRenderPassDesc = {};
beginRenderPassDesc.pRenderPass = m_RenderPass.Get();
beginRenderPassDesc.ppRenderTargets = renderTarget.GetAddressOf();
beginRenderPassDesc.RenderTargetCount = 1;
beginRenderPassDesc.pDepthStencil = m_DepthStencil.Get();
beginRenderPassDesc.Width = width;
beginRenderPassDesc.Height = height;
beginRenderPassDesc.Flags = FRenderPassBeginFlag::RENDER_PASS_BEGIN_FLAG_INLINE;
beginRenderPassDesc.pClearColors = clearColors;
beginRenderPassDesc.ClearColorCount = 1;
beginRenderPassDesc.Offset.x = 0;
beginRenderPassDesc.Offset.y = 0;
pCommandList->BeginRenderPass(&beginRenderPassDesc);
if (!Sleeping)
{
if (m_EmitterCount > 0)
{
pCommandList->DrawIndexedIndirect(m_pIndirectBuffer, 0, m_EmitterCount, sizeof(IndirectData));
}
}
pCommandList->EndRenderPass();
pCommandList->End();
(*ppFirstExecutionStage) = pCommandList;
}
} | 36.534247 | 281 | 0.78069 | IbexOmega |
3320a464742bbba3054ed7baf26c678d1d330e56 | 5,355 | cpp | C++ | Tests/TranslationAdapterTests.cpp | garmin/ActiveCaptainCommunitySDK-common | a7574a3b85b77771ceb47e5fc9a99fd31a10d47a | [
"Apache-2.0"
] | null | null | null | Tests/TranslationAdapterTests.cpp | garmin/ActiveCaptainCommunitySDK-common | a7574a3b85b77771ceb47e5fc9a99fd31a10d47a | [
"Apache-2.0"
] | null | null | null | Tests/TranslationAdapterTests.cpp | garmin/ActiveCaptainCommunitySDK-common | a7574a3b85b77771ceb47e5fc9a99fd31a10d47a | [
"Apache-2.0"
] | null | null | null | /*------------------------------------------------------------------------------
Copyright 2021 Garmin Ltd. or its subsidiaries.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
------------------------------------------------------------------------------*/
/**
@file
@brief Regression tests for the TranslationAdapter
Copyright 2019-2020 by Garmin Ltd. or its subsidiaries.
*/
#define DBG_MODULE "ACDB"
#define DBG_TAG "TranslationAdapterTests"
#include "Acdb/Tests/DatabaseUtil.hpp"
#include "Acdb/Tests/TranslationUtil.hpp"
#include "Acdb/TextHandle.hpp"
#include "Acdb/TextTranslator.hpp"
#include "Acdb/TranslationAdapter.hpp"
#include "DBG_pub.h"
#include "TF_pub.h"
namespace Acdb {
namespace Test {
//----------------------------------------------------------------
//!
//! @public
//! @detail
//! Test getting TextTranslator.
//!
//----------------------------------------------------------------
TF_TEST("acdb.translationadapter.get") {
// ----------------------------------------------------------
// Arrange
// ----------------------------------------------------------
auto database = CreateDatabase(state);
TranslationUtil translationUtil{state};
TextTranslator::GetInstance().Clear();
TranslationAdapter translationAdapter{database};
PopulateTranslationsTable(state, database);
std::vector<std::string> expected = {"en_US [1]", "en_US [2]", "en_US [3]", "en_US [4]",
"MISSING STRING! [5]"};
std::vector<std::string> actual;
// ----------------------------------------------------------
// Act
// ----------------------------------------------------------
translationAdapter.InitTextTranslator("en_US");
for (int i = 1; i <= 5; i++) {
actual.push_back(TextTranslator::GetInstance().Find(i));
}
// ----------------------------------------------------------
// Assert
// ----------------------------------------------------------
TF_assert_msg(state, expected == actual, "TranslationAdapter: Get");
}
//----------------------------------------------------------------
//!
//! @public
//! @detail
//! Test getting TextTranslator (partially translated
//! language, use English for missing strings).
//!
//----------------------------------------------------------------
TF_TEST("acdb.translationadapter.get_partial") {
// ----------------------------------------------------------
// Arrange
// ----------------------------------------------------------
auto database = CreateDatabase(state);
TranslationUtil translationUtil{state};
TextTranslator::GetInstance().Clear();
TranslationAdapter translationAdapter{database};
PopulateTranslationsTable(state, database);
std::vector<std::string> expected = {"pt_BR [1]", "pt_BR [2]", "en_US [3]", "en_US [4]",
"MISSING STRING! [5]"};
std::vector<std::string> actual;
// ----------------------------------------------------------
// Act
// ----------------------------------------------------------
translationAdapter.InitTextTranslator("pt_BR");
for (int i = 1; i <= 5; i++) {
actual.push_back(TextTranslator::GetInstance().Find(i));
}
// ----------------------------------------------------------
// Assert
// ----------------------------------------------------------
TF_assert_msg(state, expected == actual, "TranslationAdapter: Get Partial");
}
//----------------------------------------------------------------
//!
//! @public
//! @detail
//! Test getting TextTranslator (nonexistent language,
//! fallback to English).
//!
//----------------------------------------------------------------
TF_TEST("acdb.translationadapter.get_fallback") {
// ----------------------------------------------------------
// Arrange
// ----------------------------------------------------------
auto database = CreateDatabase(state);
TranslationUtil translationUtil{state};
TextTranslator::GetInstance().Clear();
TranslationAdapter translationAdapter{database};
PopulateTranslationsTable(state, database);
std::vector<std::string> expected = {"en_US [1]", "en_US [2]", "en_US [3]", "en_US [4]",
"MISSING STRING! [5]"};
std::vector<std::string> actual;
// ----------------------------------------------------------
// Act
// ----------------------------------------------------------
translationAdapter.InitTextTranslator("xx_YY");
for (int i = 1; i <= 5; i++) {
actual.push_back(TextTranslator::GetInstance().Find(i));
}
// ----------------------------------------------------------
// Assert
// ----------------------------------------------------------
TF_assert_msg(state, expected == actual, "TranslationAdapter: Get Fallback");
}
} // end of namespace Test
} // end of namespace Acdb
| 33.055556 | 90 | 0.461064 | garmin |
3323a3e19530d845d8d07fe37aae1399682c80cf | 8,585 | hpp | C++ | ivarp/include/ivarp/number/exact_less_than.hpp | phillip-keldenich/squares-in-disk | 501ebeb00b909b9264a9611fd63e082026cdd262 | [
"MIT"
] | null | null | null | ivarp/include/ivarp/number/exact_less_than.hpp | phillip-keldenich/squares-in-disk | 501ebeb00b909b9264a9611fd63e082026cdd262 | [
"MIT"
] | null | null | null | ivarp/include/ivarp/number/exact_less_than.hpp | phillip-keldenich/squares-in-disk | 501ebeb00b909b9264a9611fd63e082026cdd262 | [
"MIT"
] | null | null | null | // The code is open source under the MIT license.
// Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group
// https://ibr.cs.tu-bs.de/alg
//
// 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.
//
// Created by Phillip Keldenich on 28.10.19.
//
#pragma once
/**
* @file exact_less_than.hpp
* Implementation of \f$a < b\f$ or \f$a > b\f$
* that is guaranteed to return the correct result,
* for the following situations with builtin number types:
* \f$a\f$ integral and \f$b\f$ floating-point (or vice-versa),
* \f$a\f$ and \f$b\f$ floating-point.
* Also works if any involved type is rational.
*
* The problem with the builtin operators is that the comparison is
* implemented as if by casting the integer to the floating-point type
* before the conversion, which is not exact for large integers and
* can thus lead to incorrect results.
*/
namespace ivarp {
namespace impl {
template<bool GreaterThan, typename IntType> static IVARP_HD inline bool exact_comp_pos(IntType a, double b) {
constexpr int int_bits = std::numeric_limits<IntType>::digits;
const double max_exact = IVARP_NOCUDA_USE_STD ldexp(1., std::numeric_limits<double>::digits);
const double larger_than_max_int = IVARP_NOCUDA_USE_STD ldexp(1., int_bits);
if(b <= max_exact) {
return GreaterThan;
}
// b is an integral number > max_exact
if(b >= larger_than_max_int) {
return !GreaterThan;
}
// we can exactly convert b to our integer type
auto ib = static_cast<IntType>(b);
return GreaterThan ? a > ib : a < ib;
}
template<bool GreaterThan, typename IntType> static IVARP_HD inline bool exact_comp_neg(IntType a, double b) {
// a is below -max_exact
constexpr int int_bits = std::numeric_limits<IntType>::digits;
const double max_exact = IVARP_NOCUDA_USE_STD ldexp(1., std::numeric_limits<double>::digits);
const double min_int = IVARP_NOCUDA_USE_STD ldexp(-1., int_bits);
if(b >= -max_exact) {
return !GreaterThan;
}
// b is integral.
if(b < min_int) {
// b is below any integer values
return GreaterThan;
}
// b is integral and in range.
auto ib = static_cast<IntType>(b);
return GreaterThan ? a > ib : a < ib;
}
template<bool GreaterThan, typename UIntType> static inline IVARP_HD
std::enable_if_t<std::is_unsigned<UIntType>::value, bool>
exact_comp(UIntType a, double b) noexcept
{
constexpr UIntType max_exact = UIntType(1u) << unsigned(std::numeric_limits<double>::digits);
// an overflowing int should be rare, therefore a jump is probably good to predict
if(BOOST_LIKELY(a <= max_exact)) {
auto da = static_cast<double>(a);
return GreaterThan ? da > b : da < b;
}
return exact_comp_pos<GreaterThan>(a, b);
}
template<bool GreaterThan, typename IntType> static inline IVARP_HD
std::enable_if_t<std::is_signed<IntType>::value, bool>
exact_comp(IntType a, double b) noexcept
{
constexpr IntType max_exact = IntType(1) << unsigned(std::numeric_limits<double>::digits);
IntType absa = a < 0 ? -a : a; // the only case where this returns negative is exactly representable
// an overflowing int should be rare
if(BOOST_LIKELY(absa <= max_exact)) {
auto da = static_cast<double>(a);
return GreaterThan ? da > b : da < b;
}
if(a < 0) {
return exact_comp_neg<GreaterThan>(a, b);
} else {
return exact_comp_pos<GreaterThan>(a, b);
}
}
/// Handling the case where the int does not necessarily fit into a double's mantissa.
template<typename Int, typename Float, bool GreaterThan,
bool FitsFloat = (std::numeric_limits<Int>::digits <= std::numeric_limits<Float>::digits),
bool FitsDouble = (std::numeric_limits<Int>::digits <= std::numeric_limits<double>::digits)>
struct ExactCompIntFloat {
IVARP_HD static bool compare(Int i, Float f) {
return exact_comp<GreaterThan>(i, f);
}
};
/// Handling the case where the int fits into the float's mantissa.
template<typename Int, typename Float, bool GreaterThan, bool FD>
struct ExactCompIntFloat<Int,Float,GreaterThan,true,FD>
{
IVARP_HD static bool compare(Int i, Float f) noexcept {
auto floati = static_cast<Float>(i);
return GreaterThan ? floati > f : floati < f;
}
};
/// Handling the case where the int fits into a double's mantissa.
template<typename Int, typename Float, bool GreaterThan>
struct ExactCompIntFloat<Int,Float,GreaterThan,false,true>
{
IVARP_HD static bool compare(Int i, Float f) noexcept {
auto doublei = static_cast<double>(i);
double doublef(f);
return GreaterThan ? doublei > doublef : doublei < doublef;
}
};
}
/// Handling the int/float case.
template<typename T1, typename T2> static inline IVARP_HD
std::enable_if_t<std::is_integral<BareType<T1>>::value &&
std::is_floating_point<BareType<T2>>::value, bool>
exact_less_than(T1 a, T2 b) noexcept
{
return impl::ExactCompIntFloat<T1, T2, false>::compare(a,b);
}
/// Handling the float/int case.
template<typename T1, typename T2> static inline IVARP_HD
std::enable_if_t<std::is_integral<BareType<T2>>::value &&
std::is_floating_point<BareType<T1>>::value, bool>
exact_less_than(T1 a, T2 b) noexcept
{
return impl::ExactCompIntFloat<T2, T1, true>::compare(b, a);
}
/// Easy case: both are already floating point.
template<typename T1, typename T2> static inline IVARP_HD
std::enable_if_t<std::is_floating_point<BareType<T1>>::value &&
std::is_floating_point<BareType<T2>>::value, bool>
exact_less_than(T1 a, T2 b) noexcept
{
return a < b;
}
/// Handle the case where at least one is rational and the other is not floating-point.
template<typename T1, typename T2> static inline IVARP_H
std::enable_if_t<(IsRational<T1>::value && !std::is_floating_point<T2>::value) || (!std::is_floating_point<T1>::value && IsRational<T2>::value), bool>
exact_less_than(const T1& a, const T2& b)
{
return a < b;
}
/// Handle the case where one argument is rational and one is floating-point.
template<typename T1, typename T2> static inline IVARP_H
std::enable_if_t<IsRational<T1>::value && std::is_floating_point<T2>::value, bool>
exact_less_than(const T1& a, T2 b)
{
if(b == std::numeric_limits<T2>::infinity()) {
return true;
} else if(b == -std::numeric_limits<T2>::infinity()) {
return false;
} else {
return a < b;
}
}
template<typename T1, typename T2> static inline IVARP_H
std::enable_if_t<IsRational<T2>::value && std::is_floating_point<T1>::value, bool>
exact_less_than(T1 a, const T2& b)
{
if(a == std::numeric_limits<T1>::infinity()) {
return false;
} else if(a == -std::numeric_limits<T1>::infinity()) {
return true;
} else {
return a < b;
}
}
}
| 39.74537 | 158 | 0.639371 | phillip-keldenich |
332481d7162d8778bee2027dc26d914d313eb59e | 1,070 | cpp | C++ | src/medGui/database/medDatabaseNavigatorItemOverlay.cpp | ocommowi/medInria-public | 9074e40c886881666e7a52c53309d8d28e35c0e6 | [
"BSD-4-Clause"
] | null | null | null | src/medGui/database/medDatabaseNavigatorItemOverlay.cpp | ocommowi/medInria-public | 9074e40c886881666e7a52c53309d8d28e35c0e6 | [
"BSD-4-Clause"
] | null | null | null | src/medGui/database/medDatabaseNavigatorItemOverlay.cpp | ocommowi/medInria-public | 9074e40c886881666e7a52c53309d8d28e35c0e6 | [
"BSD-4-Clause"
] | null | null | null | /*=========================================================================
medInria
Copyright (c) INRIA 2013. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include <medDatabaseNavigatorItemOverlay.h>
// /////////////////////////////////////////////////////////////////
// medDatabaseNavigatorItemOverlay
// /////////////////////////////////////////////////////////////////
class medDatabaseNavigatorItemOverlayPrivate
{
};
medDatabaseNavigatorItemOverlay::medDatabaseNavigatorItemOverlay(QGraphicsItem *parent)
: QObject(), QGraphicsPixmapItem(parent), d(new medDatabaseNavigatorItemOverlayPrivate)
{
}
medDatabaseNavigatorItemOverlay::~medDatabaseNavigatorItemOverlay(void)
{
delete d;
d = NULL;
}
void medDatabaseNavigatorItemOverlay::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
emit clicked();
}
| 26.75 | 91 | 0.581308 | ocommowi |
33250e1fa4466a4185959a8a159ef4ad0e6639f3 | 1,330 | cpp | C++ | UVA/11753.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 3 | 2020-11-01T06:31:30.000Z | 2022-02-21T20:37:51.000Z | UVA/11753.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | null | null | null | UVA/11753.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 1 | 2021-05-05T18:56:31.000Z | 2021-05-05T18:56:31.000Z | /**
* author: MaGnsi0
* created: 20/09/2021 23:24:38
**/
#include <bits/stdc++.h>
using namespace std;
int n, k;
vector<int> v;
int dp(int i, int j, int curk) {
if (curk > k || i >= j) {
return curk;
}
if (v[i] == v[j]) {
return dp(i + 1, j - 1, curk);
} else {
return min(dp(i + 1, j, curk + 1), dp(i, j - 1, curk + 1));
}
}
int main() {
ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0);
int T;
cin >> T;
for (int t = 1; t <= T; ++t) {
cin >> n >> k;
v = vector<int>(n);
for (int i = 0; i < n; ++i) {
cin >> v[i];
}
int res = dp(0, n - 1, 0);
cout << "Case " << t << ": ";
if (res == 0) {
cout << "Too easy\n";
} else if (res <= k) {
cout << res << "\n";
} else {
cout << "Too difficult\n";
}
}
}
/* EDITORIAL :-
*
* as (1 <= n <= 10000) we can't do normal O(n^2) longest palindromic subsequence algorithm.
* so we have to take advantage of small k (1 <= k <= 20)
* if we go normal recursion without memoization with state (i, j, curk)
* : i(starting index), j(ending index), (curk)number of insertions made so far.
* we can't go no more than max(n, 2^k) different states wich is an acceptable complexity.
*/
| 25.576923 | 92 | 0.478947 | MaGnsio |
332739f0474c055ee1cf954bac6dd2c7e3068798 | 13,663 | cpp | C++ | Tools/TestWebKitAPI/Tests/WebCore/CtapRequestTest.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Tools/TestWebKitAPI/Tests/WebCore/CtapRequestTest.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Tools/TestWebKitAPI/Tests/WebCore/CtapRequestTest.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Copyright (C) 2018 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#if ENABLE(WEB_AUTHN)
#include "FidoTestData.h"
#include "PlatformUtilities.h"
#include <WebCore/DeviceRequestConverter.h>
#include <WebCore/FidoConstants.h>
#include <WebCore/Pin.h>
#include <WebCore/PublicKeyCredentialCreationOptions.h>
#include <WebCore/PublicKeyCredentialRequestOptions.h>
#include <wtf/text/Base64.h>
namespace TestWebKitAPI {
using namespace WebCore;
using namespace fido;
// Leveraging example 2 of section 6.1 of the spec
// https://fidoalliance.org/specs/fido-v2.0-ps-20170927/fido-client-to-authenticator-protocol-v2.0-ps-20170927.html
TEST(CTAPRequestTest, TestConstructMakeCredentialRequestParam)
{
PublicKeyCredentialCreationOptions::RpEntity rp;
rp.name = "Acme";
rp.id = "acme.com";
PublicKeyCredentialCreationOptions::UserEntity user;
user.name = "johnpsmith@example.com";
user.icon = "https://pics.acme.com/00/p/aBjjjpqPb.png";
user.idVector.append(TestData::kUserId, sizeof(TestData::kUserId));
user.displayName = "John P. Smith";
Vector<PublicKeyCredentialCreationOptions::Parameters> params { { PublicKeyCredentialType::PublicKey, 7 }, { PublicKeyCredentialType::PublicKey, 257 } };
PublicKeyCredentialCreationOptions::AuthenticatorSelectionCriteria selection { PublicKeyCredentialCreationOptions::AuthenticatorAttachment::Platform, true, UserVerificationRequirement::Preferred };
PublicKeyCredentialCreationOptions options { rp, user, { }, params, WTF::nullopt, { }, selection, AttestationConveyancePreference::None, WTF::nullopt };
Vector<uint8_t> hash;
hash.append(TestData::kClientDataHash, sizeof(TestData::kClientDataHash));
auto serializedData = encodeMakeCredenitalRequestAsCBOR(hash, options, AuthenticatorSupportedOptions::UserVerificationAvailability::kSupportedButNotConfigured);
EXPECT_EQ(serializedData.size(), sizeof(TestData::kCtapMakeCredentialRequest));
EXPECT_EQ(memcmp(serializedData.data(), TestData::kCtapMakeCredentialRequest, serializedData.size()), 0);
}
TEST(CTAPRequestTest, TestConstructMakeCredentialRequestParamNoUVNoRK)
{
PublicKeyCredentialCreationOptions::RpEntity rp;
rp.name = "Acme";
rp.id = "acme.com";
PublicKeyCredentialCreationOptions::UserEntity user;
user.name = "johnpsmith@example.com";
user.icon = "https://pics.acme.com/00/p/aBjjjpqPb.png";
user.idVector.append(TestData::kUserId, sizeof(TestData::kUserId));
user.displayName = "John P. Smith";
Vector<PublicKeyCredentialCreationOptions::Parameters> params { { PublicKeyCredentialType::PublicKey, 7 }, { PublicKeyCredentialType::PublicKey, 257 } };
PublicKeyCredentialCreationOptions::AuthenticatorSelectionCriteria selection { PublicKeyCredentialCreationOptions::AuthenticatorAttachment::Platform, false, UserVerificationRequirement::Discouraged };
PublicKeyCredentialCreationOptions options { rp, user, { }, params, WTF::nullopt, { }, selection, AttestationConveyancePreference::None, WTF::nullopt };
Vector<uint8_t> hash;
hash.append(TestData::kClientDataHash, sizeof(TestData::kClientDataHash));
auto serializedData = encodeMakeCredenitalRequestAsCBOR(hash, options, AuthenticatorSupportedOptions::UserVerificationAvailability::kSupportedButNotConfigured);
EXPECT_EQ(serializedData.size(), sizeof(TestData::kCtapMakeCredentialRequestShort));
EXPECT_EQ(memcmp(serializedData.data(), TestData::kCtapMakeCredentialRequestShort, serializedData.size()), 0);
}
TEST(CTAPRequestTest, TestConstructMakeCredentialRequestParamWithPin)
{
PublicKeyCredentialCreationOptions::RpEntity rp;
rp.name = "Acme";
rp.id = "acme.com";
PublicKeyCredentialCreationOptions::UserEntity user;
user.name = "johnpsmith@example.com";
user.icon = "https://pics.acme.com/00/p/aBjjjpqPb.png";
user.idVector.append(TestData::kUserId, sizeof(TestData::kUserId));
user.displayName = "John P. Smith";
Vector<PublicKeyCredentialCreationOptions::Parameters> params { { PublicKeyCredentialType::PublicKey, 7 }, { PublicKeyCredentialType::PublicKey, 257 } };
PublicKeyCredentialCreationOptions::AuthenticatorSelectionCriteria selection { PublicKeyCredentialCreationOptions::AuthenticatorAttachment::Platform, true, UserVerificationRequirement::Preferred };
PinParameters pin;
pin.protocol = pin::kProtocolVersion;
pin.auth.append(TestData::kCtap2PinAuth, sizeof(TestData::kCtap2PinAuth));
PublicKeyCredentialCreationOptions options { rp, user, { }, params, WTF::nullopt, { }, selection, AttestationConveyancePreference::None, WTF::nullopt };
Vector<uint8_t> hash;
hash.append(TestData::kClientDataHash, sizeof(TestData::kClientDataHash));
auto serializedData = encodeMakeCredenitalRequestAsCBOR(hash, options, AuthenticatorSupportedOptions::UserVerificationAvailability::kSupportedButNotConfigured, pin);
EXPECT_EQ(serializedData.size(), sizeof(TestData::kCtapMakeCredentialRequestWithPin));
EXPECT_EQ(memcmp(serializedData.data(), TestData::kCtapMakeCredentialRequestWithPin, serializedData.size()), 0);
}
TEST(CTAPRequestTest, TestConstructGetAssertionRequest)
{
PublicKeyCredentialRequestOptions options;
options.rpId = "acme.com";
PublicKeyCredentialDescriptor descriptor1;
descriptor1.type = PublicKeyCredentialType::PublicKey;
const uint8_t id1[] = {
0xf2, 0x20, 0x06, 0xde, 0x4f, 0x90, 0x5a, 0xf6, 0x8a, 0x43, 0x94,
0x2f, 0x02, 0x4f, 0x2a, 0x5e, 0xce, 0x60, 0x3d, 0x9c, 0x6d, 0x4b,
0x3d, 0xf8, 0xbe, 0x08, 0xed, 0x01, 0xfc, 0x44, 0x26, 0x46, 0xd0,
0x34, 0x85, 0x8a, 0xc7, 0x5b, 0xed, 0x3f, 0xd5, 0x80, 0xbf, 0x98,
0x08, 0xd9, 0x4f, 0xcb, 0xee, 0x82, 0xb9, 0xb2, 0xef, 0x66, 0x77,
0xaf, 0x0a, 0xdc, 0xc3, 0x58, 0x52, 0xea, 0x6b, 0x9e };
descriptor1.idVector.append(id1, sizeof(id1));
options.allowCredentials.append(descriptor1);
PublicKeyCredentialDescriptor descriptor2;
descriptor2.type = PublicKeyCredentialType::PublicKey;
const uint8_t id2[] = {
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03 };
descriptor2.idVector.append(id2, sizeof(id2));
options.allowCredentials.append(descriptor2);
options.userVerification = UserVerificationRequirement::Required;
Vector<uint8_t> hash;
hash.append(TestData::kClientDataHash, sizeof(TestData::kClientDataHash));
auto serializedData = encodeGetAssertionRequestAsCBOR(hash, options, AuthenticatorSupportedOptions::UserVerificationAvailability::kSupportedButNotConfigured);
EXPECT_EQ(serializedData.size(), sizeof(TestData::kTestComplexCtapGetAssertionRequest));
EXPECT_EQ(memcmp(serializedData.data(), TestData::kTestComplexCtapGetAssertionRequest, serializedData.size()), 0);
}
TEST(CTAPRequestTest, TestConstructGetAssertionRequestNoUV)
{
PublicKeyCredentialRequestOptions options;
options.rpId = "acme.com";
PublicKeyCredentialDescriptor descriptor1;
descriptor1.type = PublicKeyCredentialType::PublicKey;
const uint8_t id1[] = {
0xf2, 0x20, 0x06, 0xde, 0x4f, 0x90, 0x5a, 0xf6, 0x8a, 0x43, 0x94,
0x2f, 0x02, 0x4f, 0x2a, 0x5e, 0xce, 0x60, 0x3d, 0x9c, 0x6d, 0x4b,
0x3d, 0xf8, 0xbe, 0x08, 0xed, 0x01, 0xfc, 0x44, 0x26, 0x46, 0xd0,
0x34, 0x85, 0x8a, 0xc7, 0x5b, 0xed, 0x3f, 0xd5, 0x80, 0xbf, 0x98,
0x08, 0xd9, 0x4f, 0xcb, 0xee, 0x82, 0xb9, 0xb2, 0xef, 0x66, 0x77,
0xaf, 0x0a, 0xdc, 0xc3, 0x58, 0x52, 0xea, 0x6b, 0x9e };
descriptor1.idVector.append(id1, sizeof(id1));
options.allowCredentials.append(descriptor1);
PublicKeyCredentialDescriptor descriptor2;
descriptor2.type = PublicKeyCredentialType::PublicKey;
const uint8_t id2[] = {
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03 };
descriptor2.idVector.append(id2, sizeof(id2));
options.allowCredentials.append(descriptor2);
options.userVerification = UserVerificationRequirement::Discouraged;
Vector<uint8_t> hash;
hash.append(TestData::kClientDataHash, sizeof(TestData::kClientDataHash));
auto serializedData = encodeGetAssertionRequestAsCBOR(hash, options, AuthenticatorSupportedOptions::UserVerificationAvailability::kSupportedButNotConfigured);
EXPECT_EQ(serializedData.size(), sizeof(TestData::kTestComplexCtapGetAssertionRequestShort));
EXPECT_EQ(memcmp(serializedData.data(), TestData::kTestComplexCtapGetAssertionRequestShort, serializedData.size()), 0);
}
TEST(CTAPRequestTest, TestConstructGetAssertionRequestWithPin)
{
PublicKeyCredentialRequestOptions options;
options.rpId = "acme.com";
PublicKeyCredentialDescriptor descriptor1;
descriptor1.type = PublicKeyCredentialType::PublicKey;
const uint8_t id1[] = {
0xf2, 0x20, 0x06, 0xde, 0x4f, 0x90, 0x5a, 0xf6, 0x8a, 0x43, 0x94,
0x2f, 0x02, 0x4f, 0x2a, 0x5e, 0xce, 0x60, 0x3d, 0x9c, 0x6d, 0x4b,
0x3d, 0xf8, 0xbe, 0x08, 0xed, 0x01, 0xfc, 0x44, 0x26, 0x46, 0xd0,
0x34, 0x85, 0x8a, 0xc7, 0x5b, 0xed, 0x3f, 0xd5, 0x80, 0xbf, 0x98,
0x08, 0xd9, 0x4f, 0xcb, 0xee, 0x82, 0xb9, 0xb2, 0xef, 0x66, 0x77,
0xaf, 0x0a, 0xdc, 0xc3, 0x58, 0x52, 0xea, 0x6b, 0x9e };
descriptor1.idVector.append(id1, sizeof(id1));
options.allowCredentials.append(descriptor1);
PublicKeyCredentialDescriptor descriptor2;
descriptor2.type = PublicKeyCredentialType::PublicKey;
const uint8_t id2[] = {
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03 };
descriptor2.idVector.append(id2, sizeof(id2));
options.allowCredentials.append(descriptor2);
options.userVerification = UserVerificationRequirement::Required;
PinParameters pin;
pin.protocol = pin::kProtocolVersion;
pin.auth.append(TestData::kCtap2PinAuth, sizeof(TestData::kCtap2PinAuth));
Vector<uint8_t> hash;
hash.append(TestData::kClientDataHash, sizeof(TestData::kClientDataHash));
auto serializedData = encodeGetAssertionRequestAsCBOR(hash, options, AuthenticatorSupportedOptions::UserVerificationAvailability::kSupportedButNotConfigured, pin);
EXPECT_EQ(serializedData.size(), sizeof(TestData::kTestComplexCtapGetAssertionRequestWithPin));
EXPECT_EQ(memcmp(serializedData.data(), TestData::kTestComplexCtapGetAssertionRequestWithPin, serializedData.size()), 0);
}
TEST(CTAPRequestTest, TestConstructCtapAuthenticatorRequestParam)
{
static constexpr uint8_t kSerializedGetInfoCmd = 0x04;
static constexpr uint8_t kSerializedGetNextAssertionCmd = 0x08;
static constexpr uint8_t kSerializedResetCmd = 0x07;
auto serializedData1 = encodeEmptyAuthenticatorRequest(CtapRequestCommand::kAuthenticatorGetInfo);
EXPECT_EQ(serializedData1.size(), 1u);
EXPECT_EQ(memcmp(serializedData1.data(), &kSerializedGetInfoCmd, 1), 0);
auto serializedData2 = encodeEmptyAuthenticatorRequest(CtapRequestCommand::kAuthenticatorGetNextAssertion);
EXPECT_EQ(serializedData2.size(), 1u);
EXPECT_EQ(memcmp(serializedData2.data(), &kSerializedGetNextAssertionCmd, 1), 0);
auto serializedData3 = encodeEmptyAuthenticatorRequest(CtapRequestCommand::kAuthenticatorReset);
EXPECT_EQ(serializedData3.size(), 1u);
EXPECT_EQ(memcmp(serializedData3.data(), &kSerializedResetCmd, 1), 0);
}
} // namespace TestWebKitAPI
#endif // ENABLE(WEB_AUTHN)
| 52.752896 | 204 | 0.751372 | jacadcaps |
3328aa544b910a5f67ec39956221eab6b40e8fda | 3,641 | cpp | C++ | libminifi/src/utils/HTTPClient.cpp | msharee9/nifi-minifi-cpp | 7143121ff87dfb67f9234daab330b1df996bce11 | [
"Apache-2.0"
] | 1 | 2021-04-12T20:36:24.000Z | 2021-04-12T20:36:24.000Z | libminifi/src/utils/HTTPClient.cpp | msharee9/nifi-minifi-cpp | 7143121ff87dfb67f9234daab330b1df996bce11 | [
"Apache-2.0"
] | 1 | 2021-01-12T14:00:12.000Z | 2021-01-12T14:00:12.000Z | libminifi/src/utils/HTTPClient.cpp | msharee9/nifi-minifi-cpp | 7143121ff87dfb67f9234daab330b1df996bce11 | [
"Apache-2.0"
] | 1 | 2020-07-17T15:27:37.000Z | 2020-07-17T15:27:37.000Z | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "utils/HTTPClient.h"
#include <string>
namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace utils {
std::string get_token(utils::BaseHTTPClient *client, std::string username, std::string password) {
if (nullptr == client) {
return "";
}
std::string token;
client->setContentType("application/x-www-form-urlencoded");
client->set_request_method("POST");
std::string payload = "username=" + username + "&" + "password=" + password;
client->setPostFields(client->escape(payload));
client->submit();
if (client->submit() && client->getResponseCode() == 200) {
const std::string &response_body = std::string(client->getResponseBody().data(), client->getResponseBody().size());
if (!response_body.empty()) {
token = "Bearer " + response_body;
}
}
return token;
}
void parse_url(const std::string *url, std::string *host, int *port, std::string *protocol) {
static std::string http("http://");
static std::string https("https://");
if (url->compare(0, http.size(), http) == 0)
*protocol = http;
if (url->compare(0, https.size(), https) == 0)
*protocol = https;
if (!protocol->empty()) {
size_t pos = url->find_first_of(":", protocol->size());
if (pos == std::string::npos) {
pos = url->size();
}
*host = url->substr(protocol->size(), pos - protocol->size());
if (pos < url->size() && (*url)[pos] == ':') {
size_t ppos = url->find_first_of("/", pos);
if (ppos == std::string::npos) {
ppos = url->size();
}
std::string portStr(url->substr(pos + 1, ppos - pos - 1));
if (portStr.size() > 0) {
*port = std::stoi(portStr);
}
} else {
// In case the host contains no port, the first part is needed only
// For eg.: nifi.io/nifi
size_t ppos = host->find_first_of("/");
if (ppos != std::string::npos) {
*host = host->substr(0, ppos);
}
}
}
}
void parse_url(const std::string *url, std::string *host, int *port, std::string *protocol, std::string *path, std::string *query) {
int temp_port = -1;
parse_url(url, host, &temp_port, protocol);
if (host->empty() || protocol->empty()) {
return;
}
size_t base_len = host->size() + protocol->size();
if (temp_port != -1) {
*port = temp_port;
base_len += std::to_string(temp_port).size() + 1; // +1 for the :
}
auto query_loc = url->find_first_of("?", base_len);
if (query_loc < url->size()) {
*path = url->substr(base_len + 1, query_loc - base_len - 1);
*query = url->substr(query_loc + 1, url->size() - query_loc - 1);
} else {
*path = url->substr(base_len + 1, url->size() - base_len - 1);
}
}
} /* namespace utils */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */
| 30.341667 | 132 | 0.628948 | msharee9 |
332aa0fef8ee76ee418f2033edb2ff24f5dfbd71 | 2,497 | cpp | C++ | processor/src/ComponentTreeNode.cpp | mballance-sf/open-ps | a5ed44ce30bfe59462801ca7de4361d16950bcd2 | [
"Apache-2.0"
] | null | null | null | processor/src/ComponentTreeNode.cpp | mballance-sf/open-ps | a5ed44ce30bfe59462801ca7de4361d16950bcd2 | [
"Apache-2.0"
] | null | null | null | processor/src/ComponentTreeNode.cpp | mballance-sf/open-ps | a5ed44ce30bfe59462801ca7de4361d16950bcd2 | [
"Apache-2.0"
] | null | null | null | /*
* ComponentTreeNode.cpp
*
* 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.
*
* Created on: Jan 31, 2018
* Author: ballance
*/
#include "ComponentTreeNode.h"
namespace qpssc {
ComponentTreeNode::ComponentTreeNode(
ComponentTreeNode *parent,
const std::string &name,
IComponent *comp,
uint32_t id) {
m_parent = parent;
m_name = name;
m_component = comp;
m_id = id;
}
ComponentTreeNode::~ComponentTreeNode() {
// TODO Auto-generated destructor stub
}
std::string ComponentTreeNode::toString() {
std::string ret;
toString(ret, "");
return ret;
}
void ComponentTreeNode::toString(
std::string &str,
const std::string &ind) {
str.append(ind + m_name + " : " + m_component->getName() + "\n");
for (std::vector<ComponentTreeNode *>::const_iterator it=m_children.begin();
it!=m_children.end(); it++) {
(*it)->toString(str, (ind + " "));
}
}
ComponentTreeNode *ComponentTreeNode::build(
IModel *model,
IComponent *comp) {
uint32_t id = 0;
return build(model, 0, comp->getName(), comp, id);
}
ComponentTreeNode *ComponentTreeNode::build(
IModel *model,
ComponentTreeNode *parent,
const std::string &name,
IComponent *comp,
uint32_t &id) {
ComponentTreeNode *node = new ComponentTreeNode(
parent, name, comp, id++);
if (parent) {
parent->m_children.push_back(node);
}
// TODO: find binds and assess their impact
// TODO: iterate through actions at this level
// Traverse sub-component instances
for (std::vector<IBaseItem *>::const_iterator it=comp->getItems().begin();
it != comp->getItems().end(); it++) {
if ((*it)->getType() == IBaseItem::TypeField) {
IField *field = dynamic_cast<IField *>(*it);
if (dynamic_cast<IComponent *>(field->getDataType())) {
// This is a component-type field
build(model, node,
field->getName(),
dynamic_cast<IComponent *>(field->getDataType()),
id);
}
}
}
return node;
}
} /* namespace qpssc */
| 23.780952 | 77 | 0.670404 | mballance-sf |
332b05dab42636fbb8920123ff41da8ce1582eff | 23,059 | cc | C++ | tests/bench/fdb_bench.cc | hundredbag/forestdb-io_uring | bb2f49ec889d3fa2db7b3d7057e20dcb6fd4d822 | [
"Apache-2.0"
] | 6 | 2020-11-12T07:18:46.000Z | 2020-11-17T01:46:30.000Z | tests/bench/fdb_bench.cc | rundun159/forestdb-io_uring | bb2f49ec889d3fa2db7b3d7057e20dcb6fd4d822 | [
"Apache-2.0"
] | null | null | null | tests/bench/fdb_bench.cc | rundun159/forestdb-io_uring | bb2f49ec889d3fa2db7b3d7057e20dcb6fd4d822 | [
"Apache-2.0"
] | 3 | 2020-11-12T07:18:50.000Z | 2020-11-16T05:03:04.000Z | #include <stdio.h>
#include "config.h"
#include "timing.h"
#include "libforestdb/forestdb.h"
#include "test.h"
struct thread_context {
fdb_kvs_handle *handle;
ts_nsec latency1;
ts_nsec latency2;
float avg_latency1;
float avg_latency2;
};
void print_stat(const char *name, float latency){
printf("%-15s %f\n", name, latency);
}
void print_stats(fdb_file_handle *h){
TEST_INIT();
int i;
fdb_status status;
fdb_latency_stat stat;
const char *name;
for (i=0;i<FDB_LATENCY_NUM_STATS;i++){
memset(&stat, 0, sizeof(fdb_latency_stat));
status = fdb_get_latency_stats(h, &stat, i);
TEST_CHK(status == FDB_RESULT_SUCCESS);
if(stat.lat_count==0){
continue;
}
name = fdb_latency_stat_name(i);
printf("%-15s %u\n", name, stat.lat_avg);
}
}
void print_stats_aggregate(fdb_file_handle **dbfiles, int nfiles){
TEST_INIT();
int i,j;
uint32_t cnt, sum, avg = 0;
fdb_status status;
fdb_latency_stat stat;
const char *name;
for (i=0;i<FDB_LATENCY_NUM_STATS;i++){
cnt = 0; sum = 0;
// avg of each stat across dbfiles
for(j=0;j<nfiles;j++){
memset(&stat, 0, sizeof(fdb_latency_stat));
status = fdb_get_latency_stats(dbfiles[j], &stat, i);
TEST_CHK(status == FDB_RESULT_SUCCESS);
cnt += stat.lat_count;
sum += stat.lat_avg;
}
if(cnt > 0){
name = fdb_latency_stat_name(i);
avg = sum/nfiles;
printf("%-15s %u\n", name, avg);
}
}
}
void str_gen(char *s, const int len) {
int i = 0;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
size_t n_ch = strlen(alphanum);
if (len < 1){
return;
}
// return same ordering of chars
while(i<len){
s[i] = alphanum[i%n_ch];
i++;
}
s[len-1] = '\0';
}
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(fdb_kvs_handle *kv, char *a, int l, int r)
{
int i;
char keybuf[256], metabuf[256], bodybuf[512];
fdb_doc *doc = NULL;
str_gen(bodybuf, 64);
if (l == r) {
sprintf(keybuf, a, l);
sprintf(metabuf, "meta%d", r);
fdb_doc_create(&doc, (void*)keybuf, strlen(keybuf),
(void*)metabuf, strlen(metabuf), (void*)bodybuf, strlen(bodybuf));
fdb_set(kv, doc);
fdb_doc_free(doc);
} else {
for (i = l; i <= r; i++) {
swap((a+l), (a+i));
permute(kv, a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
void setup_db(fdb_file_handle **fhandle, fdb_kvs_handle **kv){
int r;
char cmd[64];
fdb_status status;
fdb_config config;
fdb_kvs_config kvs_config;
kvs_config = fdb_get_default_kvs_config();
config = fdb_get_default_config();
config.durability_opt = FDB_DRB_ASYNC;
config.compaction_mode = FDB_COMPACTION_MANUAL;
// cleanup first
sprintf(cmd, SHELL_DEL" %s*>errorlog.txt", BENCHDB_NAME);
r = system(cmd);
(void)r;
status = fdb_open(fhandle, BENCHDB_NAME, &config);
assert(status == FDB_RESULT_SUCCESS);
status = fdb_kvs_open(*fhandle, kv, BENCHKV_NAME , &kvs_config);
assert(status == FDB_RESULT_SUCCESS);
}
void sequential_set(bool walflush){
TEST_INIT();
int i, n = NDOCS;
ts_nsec latency, latency_tot = 0, latency_tot2 = 0;
float latency_avg = 0;
char keybuf[256], metabuf[256], bodybuf[512];
fdb_file_handle *fhandle;
fdb_status status;
fdb_kvs_handle *kv, *snap_kv;
fdb_doc *doc = NULL;
fdb_iterator *iterator;
printf("\nBENCH-SEQUENTIAL_SET-WALFLUSH-%d \n", walflush);
// setup
setup_db(&fhandle, &kv);
str_gen(bodybuf, 64);
// create
for (i=0;i<n;++i){
sprintf(keybuf, "key%d", i);
sprintf(metabuf, "meta%d", i);
fdb_doc_create(&doc, (void*)keybuf, strlen(keybuf),
(void*)metabuf, strlen(metabuf), (void*)bodybuf, strlen(bodybuf));
status = fdb_set(kv, doc);
TEST_CHK(status == FDB_RESULT_SUCCESS);
fdb_doc_free(doc);
doc = NULL;
}
// commit
status = fdb_commit(fhandle, FDB_COMMIT_MANUAL_WAL_FLUSH);
TEST_CHK(status == FDB_RESULT_SUCCESS);
// create an iterator for full range
latency = timed_fdb_iterator_init(kv, &iterator);
print_stat(ST_ITR_INIT, latency);
for (i=0;i<n;++i){
// sum time of all gets
latency = timed_fdb_iterator_get(iterator, &doc);
if(latency == ERR_NS){ break; }
latency_tot += latency;
// sum time of calls to next
latency = timed_fdb_iterator_next(iterator);
if(latency == ERR_NS){ break; }
latency_tot2 += latency;
fdb_doc_free(doc);
doc = NULL;
}
latency_avg = float(latency_tot)/float(n);
print_stat(ST_ITR_GET, latency_avg);
latency_avg = float(latency_tot2)/float(n);
print_stat(ST_ITR_NEXT, latency_avg);
latency = timed_fdb_iterator_close(iterator);
print_stat(ST_ITR_CLOSE, latency);
// get
for (i=0;i<n;++i){
sprintf(keybuf, "key%d", i);
fdb_doc_create(&doc, keybuf, strlen(keybuf), NULL, 0, NULL, 0);
status = fdb_get(kv, doc);
TEST_CHK(status == FDB_RESULT_SUCCESS);
fdb_doc_free(doc);
doc = NULL;
}
// snapshot
status = fdb_snapshot_open(kv, &snap_kv, FDB_SNAPSHOT_INMEM);
TEST_CHK(status == FDB_RESULT_SUCCESS);
// compact
status = fdb_compact(fhandle, NULL);
TEST_CHK(status == FDB_RESULT_SUCCESS);
// delete
latency_tot = 0;
for (i=0;i<n;++i){
sprintf(keybuf, "key%d", i);
fdb_doc_create(&doc, keybuf, strlen(keybuf), NULL, 0, NULL, 0);
latency = timed_fdb_delete(kv, doc);
latency_tot += latency;
fdb_doc_free(doc);
doc = NULL;
}
latency_avg = float(latency_tot)/float(n);
print_stat(ST_DELETE, latency_avg);
print_stats(fhandle);
latency = timed_fdb_kvs_close(snap_kv);
print_stat(ST_SNAP_CLOSE, latency);
latency = timed_fdb_kvs_close(kv);
print_stat(ST_KV_CLOSE, latency);
latency = timed_fdb_close(fhandle);
print_stat(ST_FILE_CLOSE, latency);
latency = timed_fdb_shutdown();
print_stat(ST_SHUTDOWN, latency);
}
void permutated_keyset()
{
TEST_INIT();
char str[] = "abc123";
int n = strlen(str);
ts_nsec latency, latency_tot = 0, latency_tot2 = 0;
float latency_avg = 0;
fdb_doc *rdoc = NULL;
fdb_file_handle *fhandle;
fdb_iterator *iterator;
fdb_kvs_handle *kv;
fdb_status status;
printf("\nBENCH-PERMUTATED_KEYSET\n");
// setup
setup_db(&fhandle, &kv);
// load permuated keyset
permute(kv, str, 0, n-1);
status = fdb_commit(fhandle, FDB_COMMIT_MANUAL_WAL_FLUSH);
TEST_CHK(status == FDB_RESULT_SUCCESS);
// create an iterator for full range
latency = timed_fdb_iterator_init(kv, &iterator);
print_stat(ST_ITR_INIT, latency);
// repeat until fail
do {
// sum time of all gets
latency = timed_fdb_iterator_get(iterator, &rdoc);
fdb_doc_free(rdoc);
rdoc = NULL;
if(latency == ERR_NS){ break; }
latency_tot += latency;
// sum time of calls to next
latency = timed_fdb_iterator_next(iterator);
if(latency == ERR_NS){ break; }
latency_tot2 += latency;
} while (latency != ERR_NS);
latency_avg = float(latency_tot)/float(n);
print_stat(ST_ITR_GET, latency_avg);
latency_avg = float(latency_tot2)/float(n);
print_stat(ST_ITR_NEXT, latency_avg);
latency = timed_fdb_iterator_close(iterator);
print_stat(ST_ITR_CLOSE, latency);
print_stats(fhandle);
latency = timed_fdb_kvs_close(kv);
print_stat(ST_KV_CLOSE, latency);
latency = timed_fdb_close(fhandle);
print_stat(ST_FILE_CLOSE, latency);
latency = timed_fdb_shutdown();
print_stat(ST_SHUTDOWN, latency);
}
void *writer_thread(void *args){
TEST_INIT();
thread_context *ctx= (thread_context*)args;
fdb_kvs_handle *db = ctx->handle;
char keybuf[KEY_SIZE];
// load a permutated keyset
str_gen(keybuf, KEY_SIZE);
permute(db, keybuf, 0, PERMUTED_BYTES);
return NULL;
}
void *reader_thread(void *args){
TEST_INIT();
thread_context *ctx= (thread_context*)args;
fdb_kvs_handle *db = ctx->handle;
fdb_iterator *iterator;
fdb_doc *rdoc = NULL;
ts_nsec latency = 0;
float a_latency1 = 0.0, a_latency2 = 0.0;
int samples = 0;
latency = timed_fdb_iterator_init(db, &iterator);
ctx->latency1 = latency;
// repeat until fail
do {
// sum time of all gets
latency = timed_fdb_iterator_get(iterator, &rdoc);
fdb_doc_free(rdoc);
rdoc = NULL;
if(latency == ERR_NS){ break; }
a_latency1 += latency;
// sum time of calls to next
latency = timed_fdb_iterator_next(iterator);
if(latency == ERR_NS){ break; }
a_latency2 += latency;
samples++;
} while (latency != ERR_NS);
a_latency1 = a_latency1/samples;
a_latency2 = a_latency2/samples;
// get latency
ctx->avg_latency1 = a_latency1;
// seek latency
ctx->avg_latency2 = a_latency2;
// close latency
latency = timed_fdb_iterator_close(iterator);
ctx->latency2 = latency;
return NULL;
}
void single_file_single_kvs(int n_threads){
printf("\nBENCH-SINGLE_FILE_SINGLE_KVS\n");
TEST_INIT();
memleak_start();
int i, r;
ts_nsec latency =0, latency2= 0;
float a_latency1 = 0, a_latency2 = 0;
char cmd[64];
fdb_status status;
fdb_kvs_config kvs_config = fdb_get_default_kvs_config();
fdb_config fconfig = fdb_get_default_config();
thread_t *tid = alca(thread_t, n_threads);
void **thread_ret = alca(void *, n_threads);
thread_context *ctx = alca(thread_context, n_threads);
sprintf(cmd, SHELL_DEL" bench* > errorlog.txt");
r = system(cmd);
(void)r;
// init db with flags
fdb_file_handle *dbfile;
fdb_kvs_handle **db = alca(fdb_kvs_handle*, n_threads);
fdb_kvs_handle **snap_db = alca(fdb_kvs_handle*, n_threads);
fconfig.compaction_mode = FDB_COMPACTION_MANUAL;
fconfig.auto_commit = false;
status = fdb_open(&dbfile, "bench1", &fconfig);
TEST_CHK(status == FDB_RESULT_SUCCESS);
for (i=0;i<n_threads;++i){
status = fdb_kvs_open(dbfile, &db[i], "db1", &kvs_config);
TEST_CHK(status == FDB_RESULT_SUCCESS);
ctx[i].handle = db[i];
thread_create(&tid[i], writer_thread, (void*)&ctx[i]);
}
for (i=0;i<n_threads;++i){
thread_join(tid[i], &thread_ret[i]);
}
status = fdb_commit(dbfile, FDB_COMMIT_MANUAL_WAL_FLUSH);
TEST_CHK(status == FDB_RESULT_SUCCESS);
// compact
status = fdb_compact(dbfile, NULL);
TEST_CHK(status == FDB_RESULT_SUCCESS);
// snapshot
for (i=0;i<n_threads;++i){
status = fdb_snapshot_open(db[i], &snap_db[i], FDB_SNAPSHOT_INMEM);
TEST_CHK(status == FDB_RESULT_SUCCESS);
}
// n concurrent readers with snap_db
latency = 0; latency2 = 0; a_latency1 = 0; a_latency2 = 0;
for (i=0;i<n_threads;++i){
ctx[i].handle = snap_db[i];
thread_create(&tid[i], reader_thread, (void*)&ctx[i]);
}
for (i=0;i<n_threads;++i){
thread_join(tid[i], &thread_ret[i]);
latency += ctx[i].latency1;
latency2 += ctx[i].latency2;
a_latency1 += ctx[i].avg_latency1;
a_latency2 += ctx[i].avg_latency2;
}
latency = latency/n_threads;
print_stat(ST_ITR_INIT, latency);
a_latency1 = a_latency1/n_threads;
print_stat(ST_ITR_GET, a_latency1);
a_latency2 = a_latency2/n_threads;
print_stat(ST_ITR_NEXT, a_latency2);
latency2 = latency2/n_threads;
print_stat(ST_ITR_CLOSE, latency2);
// close snap and db
latency = 0;
for (i=0;i<n_threads;++i){
latency += timed_fdb_kvs_close(snap_db[i]);
}
latency = latency/n_threads;
print_stat(ST_SNAP_CLOSE, latency);
print_stats(dbfile);
// close
latency = 0;
for (i=0;i<n_threads;++i){
latency += timed_fdb_kvs_close(db[i]);
}
latency = latency/n_threads;
print_stat(ST_KV_CLOSE, latency);
latency = timed_fdb_close(dbfile);
print_stat(ST_FILE_CLOSE, latency);
latency = timed_fdb_shutdown();
print_stat(ST_SHUTDOWN, latency);
memleak_end();
}
void single_file_multi_kvs(int n_threads){
printf("\nBENCH-SINGLE_FILE_MULTI_KVS\n");
TEST_INIT();
memleak_start();
int i, r;
char cmd[64], db_name[64];
ts_nsec latency =0, latency2= 0;
float a_latency1 = 0, a_latency2 = 0;
fdb_status status;
fdb_kvs_config kvs_config = fdb_get_default_kvs_config();
fdb_config fconfig = fdb_get_default_config();
thread_t *tid = alca(thread_t, n_threads);
void **thread_ret = alca(void *, n_threads);
thread_context *ctx = alca(thread_context, n_threads);
sprintf(cmd, SHELL_DEL" bench* > errorlog.txt");
r = system(cmd);
(void)r;
// init db with flags
fdb_file_handle *dbfile;
fdb_kvs_handle **db = alca(fdb_kvs_handle*, n_threads);
fdb_kvs_handle **snap_db = alca(fdb_kvs_handle*, n_threads);
fconfig.compaction_mode = FDB_COMPACTION_MANUAL;
fconfig.auto_commit = false;
status = fdb_open(&dbfile, "bench1", &fconfig);
TEST_CHK(status == FDB_RESULT_SUCCESS);
for (i=0;i<n_threads;++i){
sprintf(db_name, "db%d", i);
status = fdb_kvs_open(dbfile, &db[i], db_name, &kvs_config);
TEST_CHK(status == FDB_RESULT_SUCCESS);
ctx[i].handle = db[i];
thread_create(&tid[i], writer_thread, (void*)&ctx[i]);
}
for (i=0;i<n_threads;++i){
thread_join(tid[i], &thread_ret[i]);
}
status = fdb_commit(dbfile, FDB_COMMIT_MANUAL_WAL_FLUSH);
TEST_CHK(status == FDB_RESULT_SUCCESS);
// compact
status = fdb_compact(dbfile, NULL);
TEST_CHK(status == FDB_RESULT_SUCCESS);
// snapshot
for (i=0;i<n_threads;++i){
status = fdb_snapshot_open(db[i], &snap_db[i], FDB_SNAPSHOT_INMEM);
TEST_CHK(status == FDB_RESULT_SUCCESS);
}
// readers
latency = 0; latency2 = 0; a_latency1 = 0; a_latency2 = 0;
for (i=0;i<n_threads;++i){
ctx[i].handle = snap_db[i];
thread_create(&tid[i], reader_thread, (void*)&ctx[i]);
}
for (i=0;i<n_threads;++i){
thread_join(tid[i], &thread_ret[i]);
latency += ctx[i].latency1;
latency2 += ctx[i].latency2;
a_latency1 += ctx[i].avg_latency1;
a_latency2 += ctx[i].avg_latency2;
}
latency = latency/n_threads;
print_stat(ST_ITR_INIT, latency);
a_latency1 = a_latency1/n_threads;
print_stat(ST_ITR_GET, a_latency1);
a_latency2 = a_latency2/n_threads;
print_stat(ST_ITR_NEXT, a_latency2);
latency2 = latency2/n_threads;
print_stat(ST_ITR_CLOSE, latency2);
// close snap and db
latency = 0;
for (i=0;i<n_threads;++i){
latency += timed_fdb_kvs_close(snap_db[i]);
}
latency = latency/n_threads;
print_stat(ST_SNAP_CLOSE, latency);
print_stats(dbfile);
// close
latency = 0;
for (i=0;i<n_threads;++i){
latency += timed_fdb_kvs_close(db[i]);
}
latency = latency/n_threads;
print_stat(ST_KV_CLOSE, latency);
latency = timed_fdb_close(dbfile);
print_stat(ST_FILE_CLOSE, latency);
latency = timed_fdb_shutdown();
print_stat(ST_SHUTDOWN, latency);
memleak_end();
}
void multi_file_single_kvs(int n_threads){
printf("\nBENCH-MULTI_FILE_SINGLE_KVS\n");
TEST_INIT();
memleak_start();
int i, r;
char cmd[64], fname[64];
ts_nsec latency =0, latency2= 0;
float a_latency1 = 0, a_latency2 = 0;
fdb_status status;
fdb_kvs_config kvs_config = fdb_get_default_kvs_config();
fdb_config fconfig = fdb_get_default_config();
thread_t *tid = alca(thread_t, n_threads);
void **thread_ret = alca(void *, n_threads);
thread_context *ctx = alca(thread_context, n_threads);
sprintf(cmd, SHELL_DEL" bench* > errorlog.txt");
r = system(cmd);
(void)r;
// init db with flags
fdb_file_handle **dbfile = alca(fdb_file_handle*, n_threads);
fdb_kvs_handle **db = alca(fdb_kvs_handle*, n_threads);
fdb_kvs_handle **snap_db = alca(fdb_kvs_handle*, n_threads);
fconfig.compaction_mode = FDB_COMPACTION_MANUAL;
fconfig.auto_commit = false;
for (i=0;i<n_threads;++i){
sprintf(fname, "bench%d",i);
status = fdb_open(&dbfile[i], fname, &fconfig);
TEST_CHK(status == FDB_RESULT_SUCCESS);
// all same kv='db1'
status = fdb_kvs_open(dbfile[i], &db[i],
"db1", &kvs_config);
TEST_CHK(status == FDB_RESULT_SUCCESS);
ctx[i].handle = db[i];
thread_create(&tid[i], writer_thread, (void*)&ctx[i]);
}
for (i=0;i<n_threads;++i){
thread_join(tid[i], &thread_ret[i]);
}
// commit
for (i=0;i<n_threads;++i){
status = fdb_commit(dbfile[i], FDB_COMMIT_MANUAL_WAL_FLUSH);
TEST_CHK(status == FDB_RESULT_SUCCESS);
}
// compact
for (i=0;i<n_threads;++i){
status = fdb_compact(dbfile[i], NULL);
TEST_CHK(status == FDB_RESULT_SUCCESS);
}
// snapshot
for (i=0;i<n_threads;++i){
status = fdb_snapshot_open(db[i], &snap_db[i], FDB_SNAPSHOT_INMEM);
TEST_CHK(status == FDB_RESULT_SUCCESS);
}
// readers
latency = 0; latency2 = 0; a_latency1 = 0; a_latency2 = 0;
for (i=0;i<n_threads;++i){
ctx[i].handle = snap_db[i];
thread_create(&tid[i], reader_thread, (void*)&ctx[i]);
}
for (i=0;i<n_threads;++i){
thread_join(tid[i], &thread_ret[i]);
latency += ctx[i].latency1;
latency2 += ctx[i].latency2;
a_latency1 += ctx[i].avg_latency1;
a_latency2 += ctx[i].avg_latency2;
}
latency = latency/n_threads;
print_stat(ST_ITR_INIT, latency);
a_latency1 = a_latency1/n_threads;
print_stat(ST_ITR_GET, a_latency1);
a_latency2 = a_latency2/n_threads;
print_stat(ST_ITR_NEXT, a_latency2);
latency2 = latency2/n_threads;
print_stat(ST_ITR_CLOSE, latency2);
// close snap and db
latency = 0;
for (i=0;i<n_threads;++i){
latency += timed_fdb_kvs_close(snap_db[i]);
}
latency = latency/n_threads;
print_stat(ST_SNAP_CLOSE, latency);
print_stats_aggregate(dbfile, n_threads);
// close
latency = 0;
for (i=0;i<n_threads;++i){
latency += timed_fdb_kvs_close(db[i]);
}
latency = latency/n_threads;
print_stat(ST_KV_CLOSE, latency);
for (i=0;i<n_threads;++i){
latency = timed_fdb_close(dbfile[i]);
}
latency = latency/n_threads;
print_stat(ST_FILE_CLOSE, latency);
latency = timed_fdb_shutdown();
print_stat(ST_SHUTDOWN, latency);
memleak_end();
}
void multi_file_multi_kvs(int n_threads){
printf("\nBENCH-MULTI_FILE_MULTI_KVS\n");
TEST_INIT();
memleak_start();
int i, j, r;
char cmd[64], fname[64], dbname[64];
int n2_threads = n_threads*n_threads;
ts_nsec latency =0, latency2= 0;
float a_latency1 = 0, a_latency2 = 0;
fdb_status status;
fdb_kvs_config kvs_config = fdb_get_default_kvs_config();
fdb_config fconfig = fdb_get_default_config();
thread_t *tid = alca(thread_t, n2_threads);
void **thread_ret = alca(void *, n2_threads);
thread_context *ctx = alca(thread_context, n2_threads);
sprintf(cmd, SHELL_DEL" bench* > errorlog.txt");
r = system(cmd);
(void)r;
// init db with flags
fdb_file_handle **dbfile = alca(fdb_file_handle*, n_threads);
fdb_kvs_handle **db = alca(fdb_kvs_handle*, n2_threads);
fdb_kvs_handle **snap_db = alca(fdb_kvs_handle*, n2_threads);
fconfig.compaction_mode = FDB_COMPACTION_MANUAL;
fconfig.auto_commit = false;
for (i=0; i < n_threads; ++i){
sprintf(fname, "bench%d",i);
status = fdb_open(&dbfile[i], fname, &fconfig);
TEST_CHK(status == FDB_RESULT_SUCCESS);
for (j=i*n_threads; j < (i*n_threads + n_threads); ++j){
sprintf(dbname, "db%d",j);
status = fdb_kvs_open(dbfile[i], &db[j],
dbname, &kvs_config);
TEST_CHK(status == FDB_RESULT_SUCCESS);
ctx[j].handle = db[j];
thread_create(&tid[j], writer_thread, (void*)&ctx[j]);
}
}
for (i=0;i<n2_threads;++i){
thread_join(tid[i], &thread_ret[i]);
}
// commit
for (i=0;i<n_threads;++i){
status = fdb_commit(dbfile[i], FDB_COMMIT_MANUAL_WAL_FLUSH);
TEST_CHK(status == FDB_RESULT_SUCCESS);
}
// compact
for (i=0;i<n_threads;++i){
status = fdb_compact(dbfile[i], NULL);
TEST_CHK(status == FDB_RESULT_SUCCESS);
}
// snapshot
latency = 0;
for (i=0;i<n2_threads;++i){
status = fdb_snapshot_open(db[i], &snap_db[i], FDB_SNAPSHOT_INMEM);
TEST_CHK(status == FDB_RESULT_SUCCESS);
}
// readers
latency = 0; latency2 = 0; a_latency1 = 0; a_latency2 = 0;
for (i=0;i<n2_threads;++i){
ctx[i].handle = snap_db[i];
thread_create(&tid[i], reader_thread, (void*)&ctx[i]);
}
for (i=0;i<n2_threads;++i){
thread_join(tid[i], &thread_ret[i]);
latency += ctx[i].latency1;
latency2 += ctx[i].latency2;
a_latency1 += ctx[i].avg_latency1;
a_latency2 += ctx[i].avg_latency2;
}
latency = latency/n2_threads;
print_stat(ST_ITR_INIT, latency);
a_latency1 = a_latency1/n2_threads;
print_stat(ST_ITR_GET, a_latency1);
a_latency2 = a_latency2/n2_threads;
print_stat(ST_ITR_NEXT, a_latency2);
latency2 = latency2/n2_threads;
print_stat(ST_ITR_CLOSE, latency2);
// close snap and db
latency = 0;
for (i=0;i<n2_threads;++i){
latency += timed_fdb_kvs_close(snap_db[i]);
}
latency = latency/n2_threads;
print_stat(ST_SNAP_CLOSE, latency);
print_stats_aggregate(dbfile, n_threads);
// close
latency = 0;
for (i=0;i<n2_threads;++i){
latency += timed_fdb_kvs_close(db[i]);
}
latency = latency/n2_threads;
print_stat(ST_KV_CLOSE, latency);
for (i=0;i<n_threads;++i){
latency = timed_fdb_close(dbfile[i]);
}
latency = latency/n_threads;
print_stat(ST_FILE_CLOSE, latency);
latency = timed_fdb_shutdown();
print_stat(ST_SHUTDOWN, latency);
memleak_end();
}
int main(int argc, char* args[])
{
sequential_set(true);
sequential_set(false);
permutated_keyset();
// threaded
single_file_single_kvs(10);
single_file_multi_kvs(10);
multi_file_single_kvs(10);
multi_file_multi_kvs(10);
}
| 26.906651 | 78 | 0.624442 | hundredbag |
06a33a4cfa6cdb28bdf60b636539b38a7f9cc0ce | 1,359 | cpp | C++ | Problems/Hackerrank/rotateArray.cpp | pedrotorreao/DSA | 31f9dffbed5275590d5c7b7f6a73fd6dea411564 | [
"MIT"
] | 1 | 2021-07-08T01:02:06.000Z | 2021-07-08T01:02:06.000Z | Problems/Hackerrank/rotateArray.cpp | pedrotorreao/DSA | 31f9dffbed5275590d5c7b7f6a73fd6dea411564 | [
"MIT"
] | null | null | null | Problems/Hackerrank/rotateArray.cpp | pedrotorreao/DSA | 31f9dffbed5275590d5c7b7f6a73fd6dea411564 | [
"MIT"
] | null | null | null | /************************************************************/
/*Problem: Rotate Array (HR) ********/
/************************************************************/
/*
-- Summary:
A left rotation operation on an array shifts each of the array's elements 1 unit to the left.
For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would
become [3,4,5,1,2]. Note that the lowest index item moves to the highest index in a rotation.
This is called a circular array. Given an array 'a' of integers and a number, d, perform d left
rotations on the array. Return the updated array to be printed as a single line of space-separated
integers.
-- Input(s):
a: array containing n integers
d: the number of rotations
-- Expected output(s):
a': rotated array
-- Constraints:
(1 ≤ n ≤ 10^6), (1 ≤ d ≤ n), (1 ≤ a[i] ≤ 10^6)
*/
#include <iostream>
#include <vector>
#include <algorithm>
void rotLeft(std::vector<int> a, int d)
{
if (a.size() == d)
{
return;
}
std::rotate(a.begin(), a.begin() + d, a.end());
for (auto i : a)
{
std::cout << i << " ";
}
std::cout << "\n";
}
int main()
{
std::vector<int> a1{1, 2, 3, 4, 5};
std::vector<int> a2{0, 0, 0, 0, 1};
int d1{4};
int d2{3};
rotLeft(a1, d1);
rotLeft(a2, d2);
return 0;
} | 26.134615 | 101 | 0.534216 | pedrotorreao |
06a4cc5b66aa8f7b8b4106f25c53297268a8bd29 | 456 | hpp | C++ | engine/time/include/SpecialDayObserver.hpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | engine/time/include/SpecialDayObserver.hpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | engine/time/include/SpecialDayObserver.hpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #pragma once
#include "ITimeObserver.hpp"
#include "Map.hpp"
#include "Calendar.hpp"
class SpecialDayObserver : public ITimeObserver
{
public:
void notify(const ulonglong minutes_elapsed) override;
std::unique_ptr<ITimeObserver> clone() override;
protected:
void check_special_day(const std::map<int, CalendarDay>& calendar_days, const Calendar& calendar);
private:
ClassIdentifier internal_class_identifier() const override;
};
| 22.8 | 102 | 0.760965 | prolog |
06a6d2e1a71286edf3abf664abcce0a1ef1a08cc | 3,155 | hh | C++ | src/operators/Op_Face_CellBndFace.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/operators/Op_Face_CellBndFace.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/operators/Op_Face_CellBndFace.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /*
Operators
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Ethan Coon (ecoon@lanl.gov)
*/
#ifndef AMANZI_OP_FACE_CELLFACE_HH_
#define AMANZI_OP_FACE_CELLFACE_HH_
#include <vector>
#include "DenseMatrix.hh"
#include "Operator.hh"
#include "Op.hh"
/*
Op classes are small structs that play two roles:
1. They provide a class name to the schema, enabling visitor patterns.
2. They are a container for local matrices.
This Op class is for storing local matrices of length nfaces and with dofs
on cells, i.e. for Advection or for TPFA.
*/
namespace Amanzi {
namespace Operators {
class Op_Face_CellBndFace : public Op {
public:
Op_Face_CellBndFace(std::string& name,
const Teuchos::RCP<const AmanziMesh::Mesh> mesh) :
Op(OPERATOR_SCHEMA_BASE_FACE |
OPERATOR_SCHEMA_DOFS_CELL | OPERATOR_SCHEMA_DOFS_FACE | OPERATOR_SCHEMA_DOFS_BNDFACE,
name, mesh) {
WhetStone::DenseMatrix null_matrix;
nfaces_owned = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::Parallel_type::OWNED);
matrices.resize(nfaces_owned, null_matrix);
matrices_shadow = matrices;
}
virtual void ApplyMatrixFreeOp(const Operator* assembler,
const CompositeVector& X, CompositeVector& Y) const {
assembler->ApplyMatrixFreeOp(*this, X, Y);
}
virtual void SymbolicAssembleMatrixOp(const Operator* assembler,
const SuperMap& map, GraphFE& graph,
int my_block_row, int my_block_col) const {
assembler->SymbolicAssembleMatrixOp(*this, map, graph, my_block_row, my_block_col);
}
virtual void AssembleMatrixOp(const Operator* assembler,
const SuperMap& map, MatrixFE& mat,
int my_block_row, int my_block_col) const {
assembler->AssembleMatrixOp(*this, map, mat, my_block_row, my_block_col);
}
virtual void Rescale(const CompositeVector& scaling) {
if ((scaling.HasComponent("cell"))&&(scaling.HasComponent("boundary_face"))) {
const Epetra_MultiVector& s_c = *scaling.ViewComponent("cell",true);
const Epetra_MultiVector& s_bnd = *scaling.ViewComponent("boundary_face",true);
AmanziMesh::Entity_ID_List cells;
for (int f = 0; f != matrices.size(); ++f) {
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
if (cells.size() > 1) {
matrices[f](0,0) *= s_c[0][cells[0]];
matrices[f](0,1) *= s_c[0][cells[1]];
matrices[f](1,0) *= s_c[0][cells[0]];
matrices[f](1,1) *= s_c[0][cells[1]];
}else if (cells.size()==1) {
int bf = mesh_->exterior_face_map(false).LID(mesh_->face_map(false).GID(f));
matrices[f](0,0) *= s_c[0][cells[0]];
matrices[f](1,0) *= s_c[0][cells[0]];
matrices[f](0,1) *= s_bnd[0][bf];
matrices[f](1,1) *= s_bnd[0][bf];
}
}
}
}
protected:
int nfaces_owned;
};
} // namespace Operators
} // namespace Amanzi
#endif
| 32.525773 | 94 | 0.662758 | fmyuan |
06ab4ecf497c08409419ef5ce091635a41fd8f17 | 5,145 | cpp | C++ | OwnCode/KeepingSettingModify/MappingSettingConfigFile.cpp | mosxuqian/CodeCollection | 40622739f7fcb7326ee85db3bf5ecf1148c3aa08 | [
"Apache-2.0"
] | 1 | 2021-10-09T03:31:49.000Z | 2021-10-09T03:31:49.000Z | OwnCode/KeepingSettingModify/MappingSettingConfigFile.cpp | zzilla/CodeCollection | 40622739f7fcb7326ee85db3bf5ecf1148c3aa08 | [
"Apache-2.0"
] | null | null | null | OwnCode/KeepingSettingModify/MappingSettingConfigFile.cpp | zzilla/CodeCollection | 40622739f7fcb7326ee85db3bf5ecf1148c3aa08 | [
"Apache-2.0"
] | 4 | 2017-05-20T02:52:51.000Z | 2019-04-03T01:01:47.000Z | #include <algorithm>
#include <iostream>
#include <stdio.h>
#include "Log/LogC.h"
#include "logSettings.h"
#include "ThreadMutex.h"
#include "MappingSettingConfigFile.h"
#include "SensitiveParamFiltering.h"
using namespace std;
/**
* @Func: addConfigFile
* @Param: file, type:: std::string
* @Return: bool
*
**/
bool MappingSettingConfigFile::addConfigFile(std::string file)
{
if(file.empty()){
settingsLogError("file[%s] cannot empty, ERROR.\n", file.c_str());
return false;
}
m_cfgFileList.push_back(file);
return true;
}
/**
* @Func: deleteConfigFile
* @Param: file, type:: std::string&
* @Return: bool
*
**/
bool MappingSettingConfigFile::deleteConfigFile(std::string file)
{
if(file.empty()){
settingsLogError("file[%s] cannot empty, ERROR.\n", file.c_str());
return false;
}
m_cfgFileList.erase(std::find(m_cfgFileList.begin(), m_cfgFileList.end(), file));
return true;
}
/**
* @Func: loadConfigFileParam
* ps. : 从 m_cfgFileList 文件列表中包含的文件里加载到 m_paramConfigFileMap
* @Param:
* @Return: int
*
**/
int MappingSettingConfigFile::loadConfigFileParam()
{
FILE *fp = NULL;
char ch;
std::string line("");
std::string tag("");
std::string value("");
std::vector<std::string>::iterator cfgFileListIt;
std::string::size_type position;
for (cfgFileListIt = m_cfgFileList.begin(); cfgFileListIt != m_cfgFileList.end(); ++cfgFileListIt){
settingsLogVerbose("I will load \"%s\".\n", (*cfgFileListIt).c_str());
fp = fopen((*cfgFileListIt).c_str(), "rb");
if (!fp) {
settingsLogError("Open file error!\n");
return -1;
}
while((ch = fgetc(fp)) != (char)EOF || !line.empty()) {
if(ch != '\n' && ch != (char)EOF) {
line += ch;
continue;
}
position = line.find('=');
if (position == std::string::npos) {
settingsLogWarning("Not found \"=\", line=[%s]\n", line.c_str());
line.clear();
continue;
}
tag = line.substr(0, position);
value = line.substr(position + 1);
updateConfigFileParamMap(tag, value);
line.clear();
}
fclose(fp);
fp = NULL;
settingsLogVerbose("load \"%s\" ok.\n", (*cfgFileListIt).c_str());
}
settingsLogVerbose("Has load ConfigFile OK.\n");
return 0;
}
/**
* @Func: updateConfigFileParamMap
* ps. : 将解析到的 添加到 m_paramConfigFileMap
* @Param: name, type:: std::string&
* value, type:: std::string&
* @Return: int
*
**/
int MappingSettingConfigFile::updateConfigFileParamMap(std::string& name, std::string& value)
{
if(name.empty()){
settingsLogError("name[%s] is NULL.\n", name.c_str());
return -1;
}
std::map<std::string, std::string>::iterator cfgFileMapIt = m_paramConfigFileMap.find(name);
settingsLogVerbose("INPUT: name[%s] value[%s].\n", name.c_str(), value.c_str());
if (gSensitiveParamFilter.filteringSensitiveParam(name)) {
if (cfgFileMapIt != m_paramConfigFileMap.end())
cfgFileMapIt->second = "";
else
m_paramConfigFileMap[name] = "";
} else {
if (cfgFileMapIt != m_paramConfigFileMap.end())
cfgFileMapIt->second = value;
else
m_paramConfigFileMap[name] = value;
}
settingsLogVerbose("Has update OK.\n");
return 0;
}
/**
* @Func: unloadConfigFileParam
* @Param:
* @Return: int
*
**/
int MappingSettingConfigFile::unloadConfigFileParam()
{
if(m_paramConfigFileMap.empty()) {
settingsLogError("unloadConfigFileParam:: m_paramConfigFileMap has been empty.\n");
return -1;
}
m_paramConfigFileMap.erase(m_paramConfigFileMap.begin(), m_paramConfigFileMap.end()); //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合
settingsLogVerbose("Has unload ConfigFile OK.\n");
return 0;
}
/**
* @Func: getConfigFileParamValue
* ps. :从 m_paramConfigFileMap 获取参数的旧值
* @Param: name, type:: std::string&
* @Return: std::string
*
**/
std::string MappingSettingConfigFile::getConfigFileParamValue(std::string name)
{
std::map<std::string, std::string>::iterator cfgFileMapIt;
std::string value("");
cfgFileMapIt = m_paramConfigFileMap.find(name);
if (cfgFileMapIt != m_paramConfigFileMap.end())
value = cfgFileMapIt->second;
settingsLogVerbose("GET: name[%s] value[%s].\n", name.c_str(), value.c_str());
return value;
}
/**
* @Func: paramConfigFileMapOutput
* @Param:
* @Return: int
*
**/
int MappingSettingConfigFile::paramConfigFileMapOutput()
{
std::map<std::string, std::string>::iterator cfgFileMapIt;
for(cfgFileMapIt = m_paramConfigFileMap.begin();cfgFileMapIt != m_paramConfigFileMap.end(); ++cfgFileMapIt){
cout << "paramConfigFileMapOutput:: key: "<< cfgFileMapIt->first << " value: " << cfgFileMapIt->second <<endl;
}
return 0;
}
| 24.383886 | 126 | 0.600583 | mosxuqian |
06ad2d57518d6ac0fd882a3007d74d58686cd711 | 2,390 | cpp | C++ | projects/DetectRedObject/DetectRedObject.cpp | trevstanhope/scratch-Cpp | f6a0db5a7aeb388a852180dc0be749c1e7c2e318 | [
"MIT"
] | null | null | null | projects/DetectRedObject/DetectRedObject.cpp | trevstanhope/scratch-Cpp | f6a0db5a7aeb388a852180dc0be749c1e7c2e318 | [
"MIT"
] | null | null | null | projects/DetectRedObject/DetectRedObject.cpp | trevstanhope/scratch-Cpp | f6a0db5a7aeb388a852180dc0be749c1e7c2e318 | [
"MIT"
] | null | null | null | #include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
int main(int argc, char **argv) {
VideoCapture cap(0); // capture the video from web cam
if (!cap.isOpened()) // if not success, exit program
{
cout << "Cannot open the web cam" << endl;
return -1;
}
namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
int iLowH = 0;
int iHighH = 179;
int iLowS = 0;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
//Create trackbars in "Control" window
cvCreateTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
cvCreateTrackbar("HighH", "Control", &iHighH, 179);
cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
cvCreateTrackbar("HighS", "Control", &iHighS, 255);
cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
cvCreateTrackbar("HighV", "Control", &iHighV, 255);
while (true) {
Mat imgOriginal;
bool bSuccess = cap.read(imgOriginal); // read a new frame from video
if (!bSuccess) // if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
Mat imgHSV;
cvtColor(imgOriginal, imgHSV,
COLOR_BGR2HSV); // Convert the captured frame from BGR to HSV
Mat imgThresholded;
inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV),
imgThresholded); // Threshold the image
// morphological opening (remove small objects from the foreground)
erode(imgThresholded, imgThresholded,
getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
dilate(imgThresholded, imgThresholded,
getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
// morphological closing (fill small holes in the foreground)
dilate(imgThresholded, imgThresholded,
getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
erode(imgThresholded, imgThresholded,
getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
imshow("Thresholded Image", imgThresholded); // show the thresholded image
imshow("Original", imgOriginal); // show the original image
if (waitKey(30) == 27) // wait for 'esc' key press for 30ms. If 'esc' key is
// pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
| 29.146341 | 82 | 0.664854 | trevstanhope |
06ad574224ad027a6116bff88722c86540a0b880 | 2,419 | cpp | C++ | tan/samples/src/FileToHeader/stdafx.cpp | amono/TAN | 690ed6a92c594f4ba3a26d1c8b77dbff386c9b04 | [
"MIT"
] | 128 | 2016-08-17T21:57:05.000Z | 2022-03-30T17:44:36.000Z | tan/samples/src/FileToHeader/stdafx.cpp | amono/TAN | 690ed6a92c594f4ba3a26d1c8b77dbff386c9b04 | [
"MIT"
] | 8 | 2016-08-18T18:39:12.000Z | 2021-11-12T19:10:30.000Z | tan/samples/src/FileToHeader/stdafx.cpp | isabella232/TAN | 690ed6a92c594f4ba3a26d1c8b77dbff386c9b04 | [
"MIT"
] | 30 | 2016-08-18T19:36:06.000Z | 2022-03-30T17:28:31.000Z | //
// MIT license
//
// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// stdafx.cpp : source file that includes just the standard includes
// CLKernelPreprocessor.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
#if !defined(_WIN32) && defined( __GNUC__ )
#include <cassert>
#include <cerrno>
#include <cerrno>
#include <cwchar>
#include <cstdlib>
/*inline std::string narrow(std::wstring const& text)
{
std::locale const loc("");
wchar_t const* from = text.c_str();
std::size_t const len = text.size();
std::vector<char> buffer(len + 1);
std::use_facet<std::ctype<wchar_t> >(loc).narrow(from, from + len, '_', &buffer[0]);
return std::string(&buffer[0], &buffer[len]);
}
std::string w2s(const std::wstring &var)
{
static std::locale loc("");
auto &facet = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(loc);
return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).to_bytes(var);
}
std::wstring s2w(const std::string &var)
{
static std::locale loc("");
auto &facet = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(loc);
return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).from_bytes(var);
}*/
#endif | 39.016129 | 110 | 0.724266 | amono |
06b09ea60d30ace1f4d18be2244f7f9b3d31af8f | 3,950 | cpp | C++ | graph-source-code/450-D/12227770.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/450-D/12227770.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/450-D/12227770.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++11
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <list>
#include <algorithm>
using namespace std;
#define nln puts("") ///prLLInewline
#define getLLI(a) scanf("%d",&a);
#define max3(a,b,c) max(a,max(b,c)) ///3 ta theke max
#define min3(a,b,c) min(a,min(b,c)) ///3 ta theke min
#define FOR1(i,n) for(LLI i=1;i<=n;i++)
#define FOR0(i,n) for(LLI i=0;i<n;i++) ///looping
#define FORR(i,n) for(LLI i=n-1;i>=0;i--)
#define ALL(p) p.begin(),p.end()
#define SET(p) memset(p,-1,sizeof(p))
#define CLR(p) memset(p,0,sizeof(p)) ///memset
#define MEM(p,v) memset(p,v,sizeof(p))
#define READ(f) freopen(f, "r", stdin) /// file
#define WRITE(f) freopen(f, "w", stdout)
#define SZ(c) (LLI)c.size()
#define PB(x) push_back(x) ///STL defines
#define MP(x,y) make_pair(x,y)
#define ff first
#define ss second
#define LI long LLI
#define LLI long long
#define f64 long double
#define PI acos(-1.0) ///PI er value
#define mx 300005
#define ll long long
#define inf 1e10
vector<LLI>G[mx],dis[mx];
void CI(LLI &_x)
{
scanf("%I64d",&_x);
}
map<pair<LLI,LLI>,LLI>train_route;
struct node
{
ll city,cost;
bool operator <(const node& p)const
{
return cost>p.cost;
}
};
//vector<ll>G[mx],dis[mx];
LLI col[mx];
ll d[mx];
ll path[mx];
ll djs(ll src)
{
for(ll i=0; i<mx; i++)
d[i]=inf,path[i]=-1;
d[src]=0;
node a;
a.city=src,a.cost=0;
priority_queue<node>Q;
Q.push(a);
while(!Q.empty())
{
a=Q.top();
Q.pop();
ll u=a.city;
if(col[u]==1)continue;
col[u]=1;
// if(des==u)
// {
// // puts("ffffffffff");
// return d[u];
//
// }
for(ll i=0; i<G[u].size(); i++)
{
ll v=G[u][i];
// cout<<v<<" ";
//cout<<d[u]<<" "<<dis[u][i]<<endl;
if(d[u]+dis[u][i]<d[v])
{
//puts("ffffffffff");
d[v]=d[u]+dis[u][i];
path[v]=u;
a.city=v;
a.cost=d[v];
Q.push(a);
}
}
}
return -1;
}
LLI used[mx];
int main()
{
LLI n,m,k;
// cin>>n>>m>>k;
CI(n);
CI(m);
CI(k);
LLI u,v,w;
FOR0(i,m)
{
LLI u,v,w;
// cin>>u>>v>>w;
CI(u);
CI(v);
CI(w);
// if(found[MP(min(u,v),max(u,v))]==0)
// found[MP(min(u,v),max(u,v))]=1<<30;
// found[MP(min(u,v),max(u,v))]=min(w,found[MP(min(u,v),max(u,v))]);
G[u].PB(v);
G[v].PB(u);
dis[u].PB(w);
dis[v].PB(w);
}
vector<LLI>V;
memset(col,-1,sizeof col);
LLI kount=0;
FOR0(i,k)
{
LLI s,y;
// cin>>s>>y;
CI(s);
CI(y);
V.PB(s);
G[1].PB(s);
dis[1].PB(y);
}
djs(1);
FOR0(i,k)
{
G[1].pop_back();
dis[1].pop_back();
}
for(LLI i=1; i<=n; i++)
for(LLI j=0; j<G[i].size(); j++)
{
LLI u=i,v=G[i][j];
if(d[v]==d[u]+dis[i][j])
used[v]=1;
}
// LLI kount=0;
for(LLI i=0; i<V.size(); i++)
{
if(used[V[i]]==1){
}
else{
kount++;
used[V[i]]=1;
}
}
cout<<k-kount<<"\n";
}
| 19.849246 | 79 | 0.409114 | AmrARaouf |
06b21d0c50b3170c8005dd1f7526ac9c737040c6 | 1,209 | cpp | C++ | src/tower/targetSelect/RandomSelection.cpp | chanjeff2/GroupProject | 4ca9e8b6e62727ae7dd4e7e9e9fd0ecab8cda6b0 | [
"MIT"
] | null | null | null | src/tower/targetSelect/RandomSelection.cpp | chanjeff2/GroupProject | 4ca9e8b6e62727ae7dd4e7e9e9fd0ecab8cda6b0 | [
"MIT"
] | null | null | null | src/tower/targetSelect/RandomSelection.cpp | chanjeff2/GroupProject | 4ca9e8b6e62727ae7dd4e7e9e9fd0ecab8cda6b0 | [
"MIT"
] | null | null | null | #include "RandomSelection.h"
#include "src/enemy/IEnemy.h"
#include <random>
#include <algorithm>
using namespace std;
RandomSelection::RandomSelection() {};
vector<IEnemy*> RandomSelection::selectTarget(set<IEnemy*> enemiesInRange, set<EnemyType> effectiveTowards,
set<EnemyType> weakTowards, set<IEnemy*> focusedEnemies) {
// remove enemy that weak towards
// erase_if hardcode
for (auto it = enemiesInRange.begin(); it != enemiesInRange.end(); /*nothing*/) {
// check if exist in weakTowards
if (weakTowards.find((*it)->getEnemyType()) != weakTowards.end()) {
it = enemiesInRange.erase(it);
} else {
++it;
}
}
vector<IEnemy*> selectedTarget;
// directly return empty vector if no new enemy
if (enemiesInRange.empty()) {
return selectedTarget;
}
// remove focused enemy
if (!focusedEnemies.empty()) {
set_difference(enemiesInRange.begin(), enemiesInRange.end(), focusedEnemies.begin(), focusedEnemies.end(), back_inserter(selectedTarget));
} else {
copy(enemiesInRange.begin(), enemiesInRange.end(), back_inserter(selectedTarget));
}
// randomize
shuffle(selectedTarget.begin(), selectedTarget.end(), default_random_engine());
return selectedTarget;
}
| 29.487805 | 140 | 0.721257 | chanjeff2 |
06b41a5ea007dc3b23dc70c96d092fa876523fdb | 17,745 | cpp | C++ | trview.app.tests/ItemsWindowTests.cpp | chreden/trview | e2a5e3539036f27adfa54fc7fcf4c3537b99a221 | [
"MIT"
] | 20 | 2018-10-17T02:00:03.000Z | 2022-03-24T09:37:20.000Z | trview.app.tests/ItemsWindowTests.cpp | chreden/trview | e2a5e3539036f27adfa54fc7fcf4c3537b99a221 | [
"MIT"
] | 396 | 2018-07-22T16:11:47.000Z | 2022-03-29T11:57:03.000Z | trview.app.tests/ItemsWindowTests.cpp | chreden/trview | e2a5e3539036f27adfa54fc7fcf4c3537b99a221 | [
"MIT"
] | 8 | 2018-07-25T21:31:06.000Z | 2021-11-01T14:36:26.000Z | #include <trview.app/Windows/ItemsWindow.h>
#include <trview.tests.common/Window.h>
#include <trview.ui/Button.h>
#include <trview.ui/Checkbox.h>
#include <trview.common/Size.h>
#include <trview.app/Elements/Types.h>
#include <trview.graphics/mocks/IDeviceWindow.h>
#include <trview.ui.render/Mocks/IRenderer.h>
#include <trview.common/Mocks/Windows/IClipboard.h>
#include <trview.ui/Mocks/Input/IInput.h>
#include <trview.app/Mocks/Elements/ITrigger.h>
#include <trview.app/Mocks/UI/IBubble.h>
using namespace trview;
using namespace trview::tests;
using namespace trview::graphics;
using namespace trview::graphics::mocks;
using namespace trview::ui;
using namespace trview::ui::mocks;
using namespace trview::ui::render;
using namespace trview::ui::render::mocks;
using namespace trview::mocks;
namespace
{
auto register_test_module()
{
struct test_module
{
IDeviceWindow::Source device_window_source{ [](auto&&...) { return std::make_unique<MockDeviceWindow>(); } };
IRenderer::Source renderer_source{ [](auto&&...) { return std::make_unique<MockRenderer>(); } };
IInput::Source input_source{ [](auto&&...) { return std::make_unique<MockInput>(); } };
trview::Window window{ create_test_window(L"ItemsWindowTests") };
std::shared_ptr<IClipboard> clipboard{ std::make_shared<MockClipboard>() };
IBubble::Source bubble_source{ [](auto&&...) { return std::make_unique<MockBubble>(); } };
test_module& with_bubble_source(const IBubble::Source& source)
{
this->bubble_source = source;
return *this;
}
std::unique_ptr<ItemsWindow> build()
{
return std::make_unique<ItemsWindow>(device_window_source, renderer_source, input_source, window, clipboard, bubble_source);
}
};
return test_module {};
}
}
TEST(ItemsWindow, AddToRouteEventRaised)
{
auto window = register_test_module().build();
std::optional<Item> raised_item;
auto token = window->on_add_to_route += [&raised_item](const auto& item) { raised_item = item; };
std::vector<Item> items
{
Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
window->set_selected_item(items[1]);
auto button = window->root_control()->find<ui::Button>(ItemsWindow::Names::add_to_route_button);
ASSERT_NE(button, nullptr);
button->clicked(Point());
ASSERT_TRUE(raised_item.has_value());
ASSERT_EQ(raised_item.value().number(), 1);
}
TEST(ItemsWindow, ClearSelectedItemClearsSelection)
{
auto window = register_test_module().build();
std::optional<Item> raised_item;
auto token = window->on_item_selected += [&raised_item](const auto& item) { raised_item = item; };
auto trigger = std::make_shared<MockTrigger>();
std::vector<Item> items
{
Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 0, 0, L"Type", 0, 0, { trigger }, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
window->set_triggers({ trigger });
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#");
ASSERT_NE(cell, nullptr);
cell->clicked(Point());
ASSERT_TRUE(raised_item.has_value());
ASSERT_EQ(raised_item.value().number(), 1);
auto stats_list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::stats_listbox);
ASSERT_NE(stats_list, nullptr);
auto stats_items = stats_list->items();
ASSERT_NE(stats_items.size(), 0);
auto triggers_list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::triggers_listbox);
ASSERT_NE(triggers_list, nullptr);
auto triggers_items = triggers_list->items();
ASSERT_NE(triggers_items.size(), 0);
window->clear_selected_item();
stats_items = stats_list->items();
ASSERT_EQ(stats_items.size(), 0);
triggers_items = triggers_list->items();
ASSERT_EQ(triggers_items.size(), 0);
}
TEST(ItemsWindow, ItemSelectedNotRaisedWhenSyncItemDisabled)
{
auto window = register_test_module().build();
std::optional<Item> raised_item;
auto token = window->on_item_selected += [&raised_item](const auto& item) { raised_item = item; };
std::vector<Item> items
{
Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
auto sync = window->root_control()->find<ui::Checkbox>(ItemsWindow::Names::sync_item_checkbox);
ASSERT_NE(sync, nullptr);
sync->clicked(Point());
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#");
ASSERT_NE(cell, nullptr);
cell->clicked(Point());
ASSERT_FALSE(raised_item.has_value());
}
TEST(ItemsWindow, ItemSelectedRaisedWhenSyncItemEnabled)
{
auto window = register_test_module().build();
std::optional<Item> raised_item;
auto token = window->on_item_selected += [&raised_item](const auto& item) { raised_item = item; };
std::vector<Item> items
{
Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#");
ASSERT_NE(cell, nullptr);
cell->clicked(Point());
ASSERT_TRUE(raised_item.has_value());
ASSERT_EQ(raised_item.value().number(), 1);
}
TEST(ItemsWindow, ItemVisibilityRaised)
{
auto window = register_test_module().build();
std::optional<std::tuple<Item, bool>> raised_item;
auto token = window->on_item_visibility += [&raised_item](const auto& item, bool state) { raised_item = { item, state }; };
std::vector<Item> items
{
Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Checkbox>(ui::Listbox::Row::Names::cell_name_format + "Hide");
ASSERT_NE(cell, nullptr);
cell->clicked(Point());
ASSERT_TRUE(raised_item.has_value());
ASSERT_FALSE(std::get<1>(raised_item.value()));
ASSERT_EQ(std::get<0>(raised_item.value()).number(), 1);
}
TEST(ItemsWindow, ItemsListNotFilteredWhenRoomSetAndTrackRoomDisabled)
{
auto window = register_test_module().build();
std::optional<Item> raised_item;
auto token = window->on_item_selected += [&raised_item](const auto& item) { raised_item = item; };
std::vector<Item> items
{
Item(0, 55, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 78, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
window->set_current_room(78);
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "0");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#");
ASSERT_NE(cell, nullptr);
cell->clicked(Point());
ASSERT_TRUE(raised_item.has_value());
ASSERT_EQ(raised_item.value().number(), 0);
}
TEST(ItemsWindow, ItemsListFilteredWhenRoomSetAndTrackRoomEnabled)
{
auto window = register_test_module().build();
std::optional<Item> raised_item;
auto token = window->on_item_selected += [&raised_item](const auto& item) { raised_item = item; };
std::vector<Item> items
{
Item(0, 55, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 78, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
window->set_current_room(78);
auto track = window->root_control()->find<ui::Checkbox>(ItemsWindow::Names::track_room_checkbox);
ASSERT_NE(track, nullptr);
track->clicked(Point());
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "0");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#");
ASSERT_NE(cell, nullptr);
cell->clicked(Point());
ASSERT_TRUE(raised_item.has_value());
ASSERT_EQ(raised_item.value().number(), 1);
}
TEST(ItemsWindow, ItemsListPopulatedOnSet)
{
auto window = register_test_module().build();
std::vector<Item> items
{
Item(0, 55, 0, L"Lara", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 78, 0, L"Winston", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
for (auto i = 0; i < items.size(); ++i)
{
const auto& item = items[i];
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + std::to_string(i));
ASSERT_NE(row, nullptr);
auto number_cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#");
ASSERT_NE(number_cell, nullptr);
ASSERT_EQ(number_cell->text(), std::to_wstring(item.number()));
auto room_cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "Room");
ASSERT_NE(room_cell, nullptr);
ASSERT_EQ(room_cell->text(), std::to_wstring(item.room()));
auto type_cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "Type");
ASSERT_NE(type_cell, nullptr);
ASSERT_EQ(type_cell->text(), item.type());
}
}
TEST(ItemsWindow, ItemsListUpdatedWhenFiltered)
{
auto window = register_test_module().build();
std::vector<Item> items
{
Item(0, 55, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 78, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
window->set_current_room(78);
auto track = window->root_control()->find<ui::Checkbox>(ItemsWindow::Names::track_room_checkbox);
ASSERT_NE(track, nullptr);
track->clicked(Point());
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "0");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Checkbox>(ui::Listbox::Row::Names::cell_name_format + "Hide");
ASSERT_NE(cell, nullptr);
ASSERT_FALSE(cell->state());
items[1].set_visible(false);
window->update_items(items);
cell = row->find<ui::Checkbox>(ui::Listbox::Row::Names::cell_name_format + "Hide");
ASSERT_TRUE(cell->state());
}
TEST(ItemsWindow, ItemsListUpdatedWhenNotFiltered)
{
auto window = register_test_module().build();
std::vector<Item> items
{
Item(0, 55, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 78, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Checkbox>(ui::Listbox::Row::Names::cell_name_format + "Hide");
ASSERT_NE(cell, nullptr);
ASSERT_FALSE(cell->state());
items[1].set_visible(false);
window->update_items(items);
cell = row->find<ui::Checkbox>(ui::Listbox::Row::Names::cell_name_format + "Hide");
ASSERT_TRUE(cell->state());
}
TEST(ItemsWindow, SelectionSurvivesFiltering)
{
auto window = register_test_module().build();
std::vector<Item> items
{
Item(0, 55, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 78, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
window->set_current_room(78);
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#");
ASSERT_NE(cell, nullptr);
cell->clicked(Point());
auto track = window->root_control()->find<ui::Checkbox>(ItemsWindow::Names::track_room_checkbox);
ASSERT_NE(track, nullptr);
track->clicked(Point());
auto now_selected = list->selected_item();
ASSERT_TRUE(now_selected.has_value());
ASSERT_EQ(now_selected.value().value(L"#"), L"1");
}
TEST(ItemsWindow, TriggersLoadedForItem)
{
auto window = register_test_module().build();
auto trigger1 = std::make_shared<MockTrigger>()->with_number(0);
auto trigger2 = std::make_shared<MockTrigger>()->with_number(1);
std::vector<Item> items
{
Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 0, 0, L"Type", 0, 0, { trigger1, trigger2 }, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
window->set_triggers({ trigger1, trigger2 });
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#");
ASSERT_NE(cell, nullptr);
cell->clicked(Point());
auto triggers_list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::triggers_listbox);
ASSERT_NE(triggers_list, nullptr);
auto triggers_items = triggers_list->items();
ASSERT_EQ(triggers_items.size(), 2);
ASSERT_EQ(triggers_items[0].value(L"#"), L"0");
ASSERT_EQ(triggers_items[1].value(L"#"), L"1");
}
TEST(ItemsWindow, TriggerSelectedEventRaised)
{
auto window = register_test_module().build();
std::optional<std::weak_ptr<ITrigger>> raised_trigger;
auto token = window->on_trigger_selected += [&raised_trigger](const auto& trigger) { raised_trigger = trigger; };
auto trigger = std::make_shared<MockTrigger>();
std::vector<Item> items
{
Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero),
Item(1, 0, 0, L"Type", 0, 0, { trigger }, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
window->set_triggers({ trigger });
auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox);
ASSERT_NE(list, nullptr);
auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1");
ASSERT_NE(row, nullptr);
auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#");
ASSERT_NE(row, nullptr);
cell->clicked(Point());
auto triggers_list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::triggers_listbox);
ASSERT_NE(triggers_list, nullptr);
auto triggers_row = triggers_list->find<ui::Control>(ui::Listbox::Names::row_name_format + "0");
ASSERT_NE(triggers_row, nullptr);
auto triggers_cell = triggers_row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#");
ASSERT_NE(triggers_cell, nullptr);
triggers_cell->clicked(Point());
ASSERT_TRUE(raised_trigger.has_value());
ASSERT_EQ(raised_trigger.value().lock(), trigger);
}
TEST(ItemsWindow, ClickStatShowsBubble)
{
auto bubble = std::make_unique<MockBubble>();
EXPECT_CALL(*bubble, show(testing::A<const Point&>())).Times(1);
auto window = register_test_module().with_bubble_source([&](auto&&...) { return std::move(bubble); }).build();
std::vector<Item> items
{
Item(0, 0, 0, L"Test Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero)
};
window->set_items(items);
window->set_selected_item(items[0]);
auto stats = window->root_control()->find<Listbox>(ItemsWindow::Names::stats_listbox);
ASSERT_NE(stats, nullptr);
auto first_stat = stats->find<ui::Control>(Listbox::Names::row_name_format + "0");
ASSERT_NE(first_stat, nullptr);
auto value = first_stat->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "Value");
ASSERT_NE(value, nullptr);
value->clicked(Point());
}
| 35.561122 | 140 | 0.656579 | chreden |
06b53436f8e7f59b21421be3ae9870e15b0c2e65 | 2,410 | cpp | C++ | moses/mert/PerScorer.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 3 | 2018-01-25T00:51:56.000Z | 2022-01-07T15:09:38.000Z | moses/mert/PerScorer.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 1 | 2020-06-23T08:29:09.000Z | 2020-06-24T12:11:47.000Z | moses/mert/PerScorer.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 3 | 2018-06-08T08:36:27.000Z | 2021-12-26T20:36:16.000Z | #include "PerScorer.h"
#include <fstream>
#include <stdexcept>
#include "ScoreStats.h"
#include "Util.h"
using namespace std;
namespace MosesTuning
{
PerScorer::PerScorer(const string& config)
: StatisticsBasedScorer("PER",config) {}
PerScorer::~PerScorer() {}
void PerScorer::setReferenceFiles(const vector<string>& referenceFiles)
{
// For each line in the reference file, create a multiset of
// the word ids.
if (referenceFiles.size() != 1) {
throw runtime_error("PER only supports a single reference");
}
m_ref_tokens.clear();
m_ref_lengths.clear();
ifstream in(referenceFiles[0].c_str());
if (!in) {
throw runtime_error("Unable to open " + referenceFiles[0]);
}
string line;
int sid = 0;
while (getline(in,line)) {
line = this->preprocessSentence(line);
vector<int> tokens;
TokenizeAndEncode(line, tokens);
m_ref_tokens.push_back(multiset<int>());
for (size_t i = 0; i < tokens.size(); ++i) {
m_ref_tokens.back().insert(tokens[i]);
}
m_ref_lengths.push_back(tokens.size());
if (sid > 0 && sid % 100 == 0) {
TRACE_ERR(".");
}
++sid;
}
TRACE_ERR(endl);
}
void PerScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry)
{
if (sid >= m_ref_lengths.size()) {
stringstream msg;
msg << "Sentence id (" << sid << ") not found in reference set";
throw runtime_error(msg.str());
}
string sentence = this->preprocessSentence(text);
// Calculate correct, output_length and ref_length for
// the line and store it in entry
vector<int> testtokens;
TokenizeAndEncode(sentence, testtokens);
multiset<int> testtokens_all(testtokens.begin(),testtokens.end());
set<int> testtokens_unique(testtokens.begin(),testtokens.end());
int correct = 0;
for (set<int>::iterator i = testtokens_unique.begin();
i != testtokens_unique.end(); ++i) {
int token = *i;
correct += min(m_ref_tokens[sid].count(token), testtokens_all.count(token));
}
ostringstream stats;
stats << correct << " " << testtokens.size() << " " << m_ref_lengths[sid] << " " ;
string stats_str = stats.str();
entry.set(stats_str);
}
float PerScorer::calculateScore(const vector<int>& comps) const
{
float denom = comps[2];
float num = comps[0] - max(0,comps[1]-comps[2]);
if (denom == 0) {
// This shouldn't happen!
return 0.0;
} else {
return num/denom;
}
}
}
| 25.104167 | 84 | 0.655602 | anshsarkar |
06b5513bc4e7284568518b584e99f7af1ea05f72 | 5,280 | cpp | C++ | totp.cpp | jbreams/gonepass | 3da5cfa120b4e530092d9cda5634e72f22b048d8 | [
"BSL-1.0",
"Apache-2.0"
] | 165 | 2015-03-06T14:59:52.000Z | 2020-12-15T22:03:02.000Z | totp.cpp | jbreams/gonepass | 3da5cfa120b4e530092d9cda5634e72f22b048d8 | [
"BSL-1.0",
"Apache-2.0"
] | 21 | 2015-03-15T20:03:50.000Z | 2018-07-20T17:44:42.000Z | totp.cpp | jbreams/gonepass | 3da5cfa120b4e530092d9cda5634e72f22b048d8 | [
"BSL-1.0",
"Apache-2.0"
] | 19 | 2015-03-10T20:38:36.000Z | 2020-12-15T22:03:14.000Z | #include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <regex>
#include <string>
#include <unordered_map>
#include <vector>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
namespace {
std::vector<uint8_t> base32Decode(const std::string& encoded) {
std::vector<uint8_t> ret;
unsigned int curByte = 0;
int bits = 0;
for (auto ch : encoded) {
if (ch >= 'A' && ch <= 'Z') {
ch -= 'A';
} else if (ch >= '2' && ch <= '7') {
ch -= '2';
ch += 26;
}
curByte = (curByte << 5) | ch;
bits += 5;
if (bits >= 8) {
ret.push_back((curByte >> (bits - 8)) & 255);
bits -= 8;
}
}
return std::move(ret);
}
class HMACWrapper {
private:
std::function<void(HMAC_CTX*)> hmacFreeFn = [](HMAC_CTX* ptr) {
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
abort();
#else
HMAC_CTX_free(ptr);
#endif
};
public:
HMACWrapper(const EVP_MD* digest, const std::vector<uint8_t>& key) {
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
ctx = std::unique_ptr<HMAC_CTX>(new HMAC_CTX);
HMAC_CTX_init(ctx.get());
#else
ctx = std::unique_ptr<HMAC_CTX, decltype(hmacFreeFn)>(HMAC_CTX_new(), hmacFreeFn);
#endif
HMAC_Init_ex(ctx.get(), key.data(), key.size(), digest, nullptr);
}
void update(const std::vector<uint8_t>& s) {
HMAC_Update(ctx.get(),
reinterpret_cast<const unsigned char*>(s.data()),
static_cast<unsigned int>(s.size()));
}
std::vector<uint8_t> finalize() {
std::vector<uint8_t> finalHash(HMAC_size(ctx.get()));
unsigned int size;
HMAC_Final(ctx.get(), finalHash.data(), &size);
if (size != finalHash.size()) {
throw std::runtime_error("Overflow while finalizing HMAC");
}
return std::move(finalHash);
}
private:
std::unique_ptr<HMAC_CTX, decltype(hmacFreeFn)> ctx;
};
std::string calculateTOTPInternal(const EVP_MD* algo,
uint64_t counter,
int digits,
const std::vector<uint8_t>& key) {
std::vector<uint8_t> counterArr(8);
for (int i = 7; i >= 0; i--) {
counterArr[i] = counter & 0xff;
counter >>= 8;
}
HMACWrapper hmac(algo, key);
hmac.update(counterArr);
auto finalHmac = hmac.finalize();
const auto offset = finalHmac[19] & 0xf;
uint32_t truncated = (finalHmac[offset] & 0x7f) << 24 | (finalHmac[offset + 1] & 0xff) << 16 |
(finalHmac[offset + 2] & 0xff) << 8 | (finalHmac[offset + 3] & 0xff);
std::stringstream ss;
const int digitsPow = pow(10, digits);
ss << std::setw(digits) << std::setfill('0') << truncated % digitsPow;
return ss.str();
}
const auto kURIPattern = "otpauth://(totp|hotp)/(?:[^\\?]+)\\?((?:(?:[^=]+)=(?:[^\\&]+)\\&?)+)";
const auto kURIRegex = std::regex(kURIPattern, std::regex::ECMAScript | std::regex::optimize);
const auto kQueryComponentPattern = "([^=]+)=([^\\&]+)&?";
const auto kQueryComponentRegex =
std::regex(kQueryComponentPattern, std::regex::ECMAScript | std::regex::optimize);
} // namespace
bool isTOTPURI(const std::string& uri) {
std::smatch match;
return std::regex_match(uri, match, kURIRegex);
}
std::string calculateTOTP(const std::string& uri) {
std::smatch match;
if (!std::regex_match(uri, match, kURIRegex)) {
throw std::runtime_error("Error parsing OTP URI");
}
const auto type = match[1].str();
if (type != "totp") {
std::stringstream ss;
ss << "Unsupported OTP format: " << type;
throw std::runtime_error(ss.str());
}
const auto query = match[2].str();
auto begin = std::sregex_iterator(query.begin(), query.end(), kQueryComponentRegex);
const auto end = std::sregex_iterator();
std::unordered_map<std::string, std::string> params;
for (auto it = begin; it != end; ++it) {
auto curParam = *it;
params.emplace(curParam[1], curParam[2]);
}
if (params.find("secret") == params.end()) {
throw std::runtime_error("OTP URI is missing a key");
}
const EVP_MD* algo = EVP_sha1();
if (params.find("algorithm") != params.end()) {
const auto& algoStr = params["algorithm"];
if (algoStr == "SHA256") {
algo = EVP_sha256();
} else if (algoStr == "SHA512") {
algo = EVP_sha512();
} else if (algoStr != "SHA1") {
std::stringstream ss;
ss << "Unsurpported algorithm in OTP URI: " << algoStr;
throw std::runtime_error(ss.str());
}
}
auto now = std::time(nullptr);
int period = 30;
if (params.find("period") != params.end()) {
period = std::stoi(params["period"]);
}
const auto key = base32Decode(params["secret"]);
uint64_t counter = now / period;
int digits = 6;
if (params.find("digits") != params.end()) {
digits = std::stoi(params["digits"]);
}
return calculateTOTPInternal(algo, counter, digits, key);
}
| 30 | 98 | 0.573295 | jbreams |
06c23d1725d489d827b15bf1889a6b3c62707a06 | 694 | hpp | C++ | CamelusMips/Timer.hpp | MForever78/CamelusMips | fd55f00e70bee448ad25951013cc1fdad3d3b456 | [
"MIT"
] | null | null | null | CamelusMips/Timer.hpp | MForever78/CamelusMips | fd55f00e70bee448ad25951013cc1fdad3d3b456 | [
"MIT"
] | 1 | 2016-05-02T05:23:08.000Z | 2016-05-02T05:24:01.000Z | CamelusMips/Timer.hpp | MForever78/CamelusMips | fd55f00e70bee448ad25951013cc1fdad3d3b456 | [
"MIT"
] | null | null | null | //
// Created by MForever78 on 16/4/19.
//
#ifndef TIMER_HPP
#define TIMER_HPP
#include "Device.hpp"
class Timer: Device {
public:
inline void set(const std::uint32_t data) override {
counting = true;
reverseCount = data;
}
inline std::uint32_t get() const override {
return clock;
};
void tick() {
clock++;
timeSlice++;
if (counting) reverseCount--;
if (reverseCount == 0) {
counting = false;
interrupting = true;
}
}
private:
std::uint32_t clock = 0;
bool counting = false;
std::uint32_t reverseCount = 0;
std::uint32_t timeSlice = 0;
};
#endif //TIMER_HPP
| 17.794872 | 56 | 0.569164 | MForever78 |
06d02c7c4e8dc590c433c9111fd27d9385257673 | 1,567 | cpp | C++ | Lab6/orange_sorting.cpp | NLaDuke/CSIII-Labs | 8f2658d6fcf6cc838bbef17bc5110a10c742bf0e | [
"MIT"
] | null | null | null | Lab6/orange_sorting.cpp | NLaDuke/CSIII-Labs | 8f2658d6fcf6cc838bbef17bc5110a10c742bf0e | [
"MIT"
] | null | null | null | Lab6/orange_sorting.cpp | NLaDuke/CSIII-Labs | 8f2658d6fcf6cc838bbef17bc5110a10c742bf0e | [
"MIT"
] | null | null | null | #include <iostream>
#include <ctime>
#include <cstdlib>
#include <map>
#include <vector>
#include <string>
using std::cin; using std::cout; using std::endl;
using std::string; using std::multimap; using std::vector;
//----------------------------
// File: orange_sorting.cpp
// By: Nolan LaDuke
// Date: 2/23/2021
//------------------------------------------------------------------------------
// Function: Generates random 'fruits', then prints out the color of each
// orange separated by a ' '. Implemented using a multimap
//------------------------------------------------------------------------------
// Based on a file provided by Mikhal Nesterenko, KSU
//------------------------------------------------------------------------------
// Setup to convert random-integers into usable data
enum class Variety {orange, pear, apple};
vector<string> colors = {"red", "green", "yellow"};
int main(){
// Set seed
srand(time(nullptr));
// Set up variables:
multimap<Variety, string> tree; // Structure to contain generated fruit
int numOfFruits = (rand()%100+1); // Number of fruits to generate
for(int i = 0; i < numOfFruits; i++){
// Generate fruit pair and add it to tree
tree.emplace(std::make_pair(static_cast<Variety>(rand() % 3),
colors[rand() % 3]));
}
cout << "Colors of the oranges: ";
// Iterate through oranges and print out the color of each
for(auto f=tree.lower_bound(Variety(0)); f!=tree.upper_bound(Variety(0));++f)
cout << f->second << " ";
cout << endl;
}
| 33.340426 | 80 | 0.539247 | NLaDuke |
06d21d1741189ec6c382b5a3d0365b620cf94559 | 3,158 | hpp | C++ | include/mandelmaths.hpp | zeFresk/mandelbrot | 18dd60aefd067c8f26315f44ceaae30bca025cba | [
"MIT"
] | null | null | null | include/mandelmaths.hpp | zeFresk/mandelbrot | 18dd60aefd067c8f26315f44ceaae30bca025cba | [
"MIT"
] | null | null | null | include/mandelmaths.hpp | zeFresk/mandelbrot | 18dd60aefd067c8f26315f44ceaae30bca025cba | [
"MIT"
] | null | null | null | #pragma once
/*
Mandelbrot math related functions
zeFresk
*/
#include <complex>
namespace mandelbrot {
// ###############################
// ### normalization functions ###
// ###############################
// NOTE: All the following takes the index at which we diverged and the maxium number of iterations used along with last computed value. They then returns a real number
// identity function, returns index as is
template <typename Floating_Type>
float identity(size_t index, size_t max_iterations, std::complex<Floating_Type> const& last) {
return static_cast<float>(index);
}
// Smooth coloring function, as in https://www.codingame.com/playgrounds/2358/how-to-plot-the-mandelbrot-set/adding-some-colors
template <typename Floating_Type>
inline float smooth_coloring(size_t index, size_t max_iterations, std::complex<Floating_Type> const& last) {
if (index == max_iterations)
return static_cast<float>(index);
return index + 1 - std::log(std::log2(std::abs(z)))
}
// simply normalize output between 0 and 1
template <typename Floating_Type>
inline float one(size_t index, size_t max_iterations, std::complex<Floating_Type> const& last) {
if (index == max_iterations)
return 1.f;
return static_cast<float>(index) / static_cast<float>(max_iterations);
}
// Trait to get associated normalized function type given Floating_type
template <typename Floating_Type>
using normalized_function_type = float (*)(size_t, size_t, std::complex<Floating_Type> const&);
// ###############################
// #### computation functions ####
// ###############################
// Iterate through mandelbrot function (zn=zn-1+c) up to 'iterations' times.
// Returns iteration at which we diverged.
template <typename Floating_Type>
size_t compute(std::complex<Floating_Type> const& c, size_t iterations) {
// optimizations
// detection of cardioid
decltype(c) z = (std::real(c) - 0.25) * (std::real(c) - 0.25) + std::imag(c) * std::imag(c);
if (z * (z + std::real(c) - 0.25) <= 0.25 * std::imag(c) * std::imag(c)) { // inside cardioid
return iterations;
}
// main computation
z = 0.;
for (size_t i = 0; i < iterations, ++i) {
z = z * z + c;
if (std::abs(z) > 2)
return i;
}
return iterations;
}
// Iterate through mandelbrot function but normalize output with the f function
// see mandelbrot::compute
template <typename Floating_Type>
float compute_normalized(std::complex<Floating_Type> const& c, size_t iterations, normalized_function_type<Floating_Type> f = one) {
// optimizations
// detection of cardioid
Floating_Type q = (std::real(c) - 0.25) * (std::real(c) - 0.25) + std::imag(c) * std::imag(c);
if (q * (q + std::real(c) - 0.25 ) <= 0.25 * std::imag(c) * std::imag(c)) { // inside cardioid
return f(iterations, iterations, complex_t{ 0,0 });
}
// main computation
auto z = complex_t{ 0,0 };
for (size_t i = 0; i < iterations; ++i) {
z = z * z + c;
if (std::abs(z) > 2)
return f(i, iterations, z);
}
return f(iterations, iterations, z);
}
} | 36.298851 | 170 | 0.638379 | zeFresk |
06d5dfc2c7dd31fc4be1b00c490ad9746a9298e2 | 2,382 | cpp | C++ | TestApp1/DragTextUI.cpp | EndofDeath/Duilib_adrival | 2fc0a4cc2a6ea2a6d945baf16e41d252c1417be3 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | TestApp1/DragTextUI.cpp | EndofDeath/Duilib_adrival | 2fc0a4cc2a6ea2a6d945baf16e41d252c1417be3 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | TestApp1/DragTextUI.cpp | EndofDeath/Duilib_adrival | 2fc0a4cc2a6ea2a6d945baf16e41d252c1417be3 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | #include "stdafx.h"
#include "DragTextUI.h"
LPCTSTR UI_DRAGTEXT = _T("DragText");
CDragTextUI::CDragTextUI()
{
}
CDragTextUI::~CDragTextUI()
{
}
LPCTSTR CDragTextUI::GetClass() const
{
return UI_DRAGTEXT;
}
LPVOID CDragTextUI::GetInterface(LPCTSTR pstrName)
{
if (_tcscmp(pstrName, UI_DRAGTEXT) == 0) return static_cast<CDragTextUI*>(this);
return CTextUI::GetInterface(pstrName);
}
void CDragTextUI::DoEvent(TEventUI& event)
{
{
if (event.Type == UIEVENT_BUTTONDOWN && IsEnabled())
{
m_ptLastMouse = event.ptMouse;
m_rcNewPos = m_rcItem;
if (m_pManager) m_pManager->AddPostPaint(this);
return;
}
if (event.Type == UIEVENT_BUTTONUP)
{
RECT rcParent = m_pParent->GetPos();
m_rcNewPos.left -= rcParent.left;
m_rcNewPos.right -= rcParent.left;
m_rcNewPos.top -= rcParent.top;
m_rcNewPos.bottom -= rcParent.top;
SetPos(m_rcNewPos);
if (m_pManager) m_pManager->RemovePostPaint(this);
NeedParentUpdate();
return;
}
if (event.Type == UIEVENT_MOUSEMOVE)
{
{
LONG cx = event.ptMouse.x - m_ptLastMouse.x;
LONG cy = event.ptMouse.y - m_ptLastMouse.y;
m_ptLastMouse = event.ptMouse;
RECT rc = m_rcNewPos;
rc.left += cx;
rc.right += cx;
rc.top += cy;
rc.bottom += cy;
CDuiRect rcInvalidate = m_rcNewPos;
m_rcNewPos = rc;
rcInvalidate.Join(m_rcNewPos);
if (m_pManager) m_pManager->Invalidate(rcInvalidate);
return;
}
}
if (event.Type == UIEVENT_SETCURSOR)
{
if (IsEnabled()) {
::SetCursor(::LoadCursor(NULL, IDC_HAND));
return;
}
}
}
CTextUI::DoEvent(event);
}
void CDragTextUI::DoPostPaint(HDC hDC, const RECT& rcPaint)
{
int nWidth = GetWidth();
int nHeight = GetHeight();
RECT rcDropPos = m_rcNewPos;
RECT rcParent = m_pParent->GetPos();
if (m_rcNewPos.left < rcParent.left)
{
rcDropPos.left = rcParent.left;
rcDropPos.right = rcDropPos.left + nWidth;
}
if (m_rcNewPos.right > rcParent.right)
{
rcDropPos.right = rcParent.right;
rcDropPos.left = rcDropPos.right - nWidth;
}
if (m_rcNewPos.top < rcParent.top)
{
rcDropPos.top = rcParent.top;
rcDropPos.bottom = rcDropPos.top + nHeight;
}
if (m_rcNewPos.bottom > rcParent.bottom)
{
rcDropPos.bottom = rcParent.bottom;
rcDropPos.top = rcDropPos.bottom - nHeight;
}
CRenderEngine::DrawColor(hDC, rcDropPos, 0xAA000000);
m_rcNewPos = rcDropPos;
} | 21.853211 | 81 | 0.680101 | EndofDeath |
06d9989f42d8e7f9301a9654d13ed390ecb3768c | 1,072 | cpp | C++ | Doom/src/Doom/Components/PointLight.cpp | Shturm0weak/OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 126 | 2020-10-20T21:39:53.000Z | 2022-01-25T14:43:44.000Z | Doom/src/Doom/Components/PointLight.cpp | Shturm0weak/2D_OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 2 | 2021-01-07T17:29:19.000Z | 2021-08-14T14:04:28.000Z | Doom/src/Doom/Components/PointLight.cpp | Shturm0weak/2D_OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 16 | 2021-01-09T09:08:40.000Z | 2022-01-25T14:43:46.000Z | #include "../pch.h"
#include "PointLight.h"
using namespace Doom;
void Doom::PointLight::Copy(const PointLight& rhs)
{
m_Constant = rhs.m_Constant;
m_Linear = rhs.m_Linear;
m_Quadratic = rhs.m_Quadratic;
m_Color = rhs.m_Color;
}
void Doom::PointLight::operator=(const PointLight& rhs)
{
Copy(rhs);
}
Component* Doom::PointLight::Create()
{
return new PointLight();
}
Doom::PointLight::PointLight(const PointLight& rhs)
{
Copy(rhs);
}
Doom::PointLight::PointLight()
{
std::function<void()>* f = new std::function<void()>([=] {
SpriteRenderer* sr = m_OwnerOfCom->GetComponent<SpriteRenderer>();
if (sr == nullptr)
sr = m_OwnerOfCom->AddComponent<SpriteRenderer>();
sr->m_DisableRotation = true;
sr->m_Texture = Texture::Get("src/UIimages/Lamp.png");
s_PointLights.push_back(this);
});
EventSystem::GetInstance().SendEvent(EventType::ONMAINTHREADPROCESS, nullptr, f);
}
Doom::PointLight::~PointLight()
{
auto iter = std::find(s_PointLights.begin(), s_PointLights.end(), this);
if (iter != s_PointLights.end())
s_PointLights.erase(iter);
}
| 22.333333 | 82 | 0.70709 | Shturm0weak |
06d9b77f21da6028dd3a77a8f09b80d91cad2736 | 11,697 | cpp | C++ | WitchEngine3/src/WE3/math/WEMatrix2.cpp | jadnohra/World-Of-Football | fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc | [
"MIT"
] | 3 | 2018-12-02T14:09:22.000Z | 2021-11-22T07:14:05.000Z | WitchEngine3/src/WE3/math/WEMatrix2.cpp | jadnohra/World-Of-Football | fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc | [
"MIT"
] | 1 | 2018-12-03T22:54:38.000Z | 2018-12-03T22:54:38.000Z | WitchEngine3/src/WE3/math/WEMatrix2.cpp | jadnohra/World-Of-Football | fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc | [
"MIT"
] | 2 | 2020-09-22T21:04:14.000Z | 2021-05-24T09:43:28.000Z | #include "WEMatrix2.h"
#include "../WEMacros.h"
#include "../WEAssert.h"
#include "WEMathUtil.h"
namespace WE {
Matrix2x2::Matrix2x2() {
}
Matrix2x2::Matrix2x2(bool setIdentity) {
if (setIdentity) {
identity();
}
}
void diagonal(Matrix2x2& mat, float value) {
mat.m11 = value; mat.m12 = 0.0f;
mat.m21 = 0.0f; mat.m22 = value;
}
void Matrix2x2::identity() {
WE::diagonal(*this, 1.0f);
}
void Matrix2x2::diagonal(float value) {
WE::diagonal(*this, value);
}
void Matrix2x2::transpose() {
float temp;
swapt<float>(m12, m21, temp);
}
void Matrix2x2::transpose(Matrix2x2& result) {
result.m11 = m11;
result.m12 = m21;
result.m21 = m12;
result.m22 = m22;
}
void Matrix2x2::scale(float multiplier) {
row[0].mul(multiplier);
row[1].mul(multiplier);
}
void mul(const Matrix2x2 &a, const Matrix2x2 &b, Matrix2x2 &r) {
// Compute the upper 3x3 (linear transformation) portion
r.m11 = a.m11*b.m11 + a.m12*b.m21;
r.m12 = a.m11*b.m12 + a.m12*b.m22;
r.m21 = a.m21*b.m11 + a.m22*b.m21;
r.m22 = a.m21*b.m12 + a.m22*b.m22;
}
void mul(const Matrix2x2& a, const Matrix2x2& b, Matrix2x2& r, bool transFirst, bool transSecond) {
if (transFirst) {
if (transSecond) {
//TODO
assrt(false);
} else {
//TODO
assrt(false);
}
} else {
if (transSecond) {
r.m11 = a.m11*b.m11 + a.m12*b.m12;
r.m12 = a.m11*b.m21 + a.m12*b.m22;
r.m21 = a.m21*b.m11 + a.m22*b.m12;
r.m22 = a.m21*b.m21 + a.m22*b.m22;
} else {
r.m11 = a.m11*b.m11 + a.m12*b.m21;
r.m12 = a.m11*b.m12 + a.m12*b.m22;
r.m21 = a.m21*b.m11 + a.m22*b.m21;
r.m22 = a.m21*b.m12 + a.m22*b.m22;
}
}
}
void Matrix2x2::setupRotation(float theta, bool leftHanded, bool inverse) {
float s, c;
sinCos(&s, &c, theta, leftHanded);
// Set the matrix elements. There is still a little more
// opportunity for optimization due to the many common
// subexpressions. We'll let the compiler handle that...
if (inverse == false) {
m11 = c;
m12 = -s;
m21 = s;
m22 = c;
} else {
m11 = -c;
m21 = s;
m12 = -s;
m22 = -c;
}
}
void Matrix2x2::moveOrientation(Matrix2x2& rot) {
Matrix2x2 temp = *this;
mul(temp, rot, *this);
}
void mul(const Matrix2x2& mat, const Vector2 &v, Vector2& result, bool inverse) {
if (inverse == false) {
result.x = mat.m11*v.x + mat.m21*v.y;
result.y = mat.m12*v.x + mat.m22*v.y;
} else {
result.x = mat.m11*v.x + mat.m12*v.y;
result.y = mat.m21*v.x + mat.m22*v.y;
}
}
void Matrix2x2::transform(const Vector2& vector, Vector2& result, bool inverse) const {
mul(*this, vector, result, inverse);
}
void Matrix2x2::transform(Vector2& vector, bool inverse) const {
WE::Vector2 temp = vector;
mul(*this, temp, vector, inverse);
}
void identity(Matrix3x2& mat, bool rot, bool trans) {
if (rot) {
mat.m11 = 1.0f; mat.m12 = 0.0f;
mat.m21 = 0.0f; mat.m22 = 1.0f;
}
if (trans) {
mat.tx = mat.ty = 0.0f;
}
}
inline float _mulDimNoTrans(const float &p, const Matrix3x2 &m, short dim) {
return p * m.row[dim].x + p * m.row[dim].y;
}
inline float _mulDim(const float &p, const Matrix3x2 &m, short dim) {
return p * m.row[dim].x + p * m.row[dim].y + m.row[2].el[dim];
}
void mul(const Matrix3x2 &a, const Matrix3x2 &b, Matrix3x2 &r) {
// Compute the upper 3x3 (linear transformation) portion
r.m11 = a.m11*b.m11 + a.m12*b.m21;
r.m12 = a.m11*b.m12 + a.m12*b.m22;
r.m21 = a.m21*b.m11 + a.m22*b.m21;
r.m22 = a.m21*b.m12 + a.m22*b.m22;
// Compute the translation portion
r.tx = a.tx*b.m11 + a.ty*b.m21 + b.tx;
r.ty = a.tx*b.m12 + a.ty*b.m22 + b.ty;
}
void mul(const Vector2 &p, const Matrix3x2 &m, Vector2& result) {
// Grind through the linear algebra.
result.x = p.x*m.m11 + p.y*m.m21 + m.tx;
result.y = p.x*m.m12 + p.y*m.m22 + m.ty;
}
void mulNoTrans(const Vector2 &p, const Matrix3x2 &m, Vector2& result) {
// Grind through the linear algebra.
result.x = p.x*m.m11 + p.y*m.m21;
result.y = p.x*m.m12 + p.y*m.m22;
}
Matrix3x2::Matrix3x2() {
}
Matrix3x2::Matrix3x2(bool identity) {
WE::identity(*this, true, true);
}
Matrix2x2& Matrix3x2::castToMatrix2x2() {
return *((Matrix2x2*) ((Matrix3x2*) this));
}
const Matrix2x2& Matrix3x2::castToCtMatrix2x2() const {
return *((Matrix2x2*) ((Matrix3x2*) this));
}
void Matrix3x2::copy3x3BaseTo(Matrix2x2& mat) const {
memcpy(mat.row, row, sizeof(mat));
}
void Matrix3x2::simpleInvTransformVector(const Vector2& vector, Vector2& result) const {
castToCtMatrix2x2().transform(vector, result, true);
}
void Matrix3x2::invTransformVector(const Vector2& vector, Vector2& result) const {
Matrix3x2 inv;
inverse(*this, inv);
inv.transformVector(vector, result);
}
void Matrix3x2::invTransformPoint(const Vector2& point, Vector2& result) const {
Matrix3x2 inv;
inverse(*this, inv);
inv.transformPoint(point, result);
Vector2 temp1 = result;
Vector2 temp2;
transformPoint(temp1, temp2);
}
void Matrix3x2::transformPoint(const Vector2& point, Vector2& result) const {
mul(point, *this, result);
}
void Matrix3x2::transformPointDim(const float& point, short dim, float& result) const {
result = _mulDim(point, *this, dim);
}
float Matrix3x2::transformPointDim(const float& point, short dim) const {
return _mulDim(point, *this, dim);
}
void Matrix3x2::transformVector(const Vector2& vector, Vector2& result) const {
mulNoTrans(vector, *this, result);
}
void Matrix3x2::transformVectorDim(const float& vector, short dim, float& result) const {
result = _mulDimNoTrans(vector, *this, dim);
}
float Matrix3x2::transformVectorDim(const float& vector, short dim) const {
return _mulDimNoTrans(vector, *this, dim);
}
void Matrix3x2::transformPoint(Vector2& point) const {
Vector2 temp = point;
mul(temp, *this, point);
}
void Matrix3x2::transformVector(Vector2& vector) const {
Vector2 temp = vector;
mulNoTrans(temp, *this, vector);
}
void Matrix3x2::identity() {
WE::identity(*this, true, true);
}
void RigidMatrix3x2::zeroTranslation() {
WE::identity(*this, false, true);
}
void RigidMatrix3x2::setTranslation(const Vector2 &d) {
tx = d.x; ty = d.y;
}
void RigidMatrix3x2::setupTranslation(const Vector2 &d) {
WE::identity(*this, true, false);
// Set the translation portion
tx = d.x; ty = d.y;
}
void _setRotate(RigidMatrix3x2& mat, const Vector2 &eulerAngles, bool leftHanded, bool setToTranspose) {
// Fetch sine and cosine of angles
float sh,ch, sp,cp, sb,cb;
sinCos(&sh, &ch, eulerAngles.el[0], leftHanded);
sinCos(&sp, &cp, eulerAngles.el[1], leftHanded);
sinCos(&sb, &cb, eulerAngles.el[2], leftHanded);
// Fill in the matrix elements
if (setToTranspose == false) {
mat.m11 = ch * cb + sh * sp * sb;
mat.m12 = -ch * sb + sh * sp * cb;
mat.m21 = sb * cp;
mat.m22 = cb * cp;
} else {
mat.m11 = ch * cb + sh * sp * sb;
mat.m21 = -ch * sb + sh * sp * cb;
mat.m12 = sb * cp;
mat.m22 = cb * cp;
}
}
inline void _setRotate(RigidMatrix3x2& mat, RigidMatrix3x2::CardinalAxis axis, float theta, bool leftHanded, bool setToTranspose) {
// Get sin and cosine of rotation angle
float s, c;
sinCos(&s, &c, theta, leftHanded);
// Check which axis they are rotating about
switch (axis) {
case RigidMatrix3x2::Axis_X: // Rotate about the x-axis
if (setToTranspose == false) {
mat.m11 = c; mat.m12 = -s;
mat.m21 = s; mat.m22 = c;
} else {
mat.m11 = c; mat.m21 = s;
mat.m12 = -s; mat.m22 = c;
}
break;
default: //case RigidMatrix3x2::Axis_Y: Rotate about the y-axis
if (setToTranspose == false) {
mat.m11 = s; mat.m12 = -c;
mat.m21 = c; mat.m22 = s;
} else {
mat.m11 = s; mat.m21 = c;
mat.m12 = -c; mat.m22 = s;
}
break;
}
}
void _setRotate(RigidMatrix3x2& mat, const Vector2& _axis, float theta, bool isNormalized, bool leftHanded, bool setToTranspose) {
// Quick sanity check to make sure they passed in a unit vector
// to specify the axis
//assrt(fabs(axis*axis - 1.0f) < .01f);
// Get sin and cosine of rotation angle
Vector2 axis = _axis;
if (isNormalized == false) {
axis.normalize();
}
float s, c;
sinCos(&s, &c, theta, leftHanded);
// Compute 1 - cos(theta) and some common subexpressions
float a = 1.0f - c;
float ax = a * axis.x;
float ay = a * axis.y;
// Set the matrix elements. There is still a little more
// opportunity for optimization due to the many common
// subexpressions. We'll let the compiler handle that...
if (setToTranspose == false) {
mat.m11 = ax*axis.x + c;
mat.m12 = ax*axis.y + s;
mat.m21 = ay*axis.x - s;
mat.m22 = ay*axis.y + c;
} else {
mat.m11 = ax*axis.x + c;
mat.m21 = ax*axis.y + s;
mat.m12 = ay*axis.x - s;
mat.m22 = ay*axis.y + c;
}
}
void RigidMatrix3x2::zeroRotation() {
WE::identity(*this, true, false);
}
void RigidMatrix3x2::setRotate(CardinalAxis axis, float theta, bool leftHanded, bool setToTranspose) {
_setRotate(*this, axis, theta, leftHanded, setToTranspose);
}
void RigidMatrix3x2::setRotate(const Vector2 &axis, float theta, bool isNormalized, bool leftHanded, bool setToTranspose) {
_setRotate(*this, axis, theta, isNormalized, leftHanded, setToTranspose);
}
void RigidMatrix3x2::setRotate(const Vector2 &eulerAngles, bool leftHanded, bool setToTranspose) {
_setRotate(*this, eulerAngles, leftHanded, setToTranspose);
}
void RigidMatrix3x2::setupRotation(CardinalAxis axis, float theta, bool leftHanded, bool setToTranspose) {
_setRotate(*this, axis, theta, leftHanded, setToTranspose);
WE::identity(*this, false, true);
}
void RigidMatrix3x2::setupRotation(const Vector2 &axis, float theta, bool isNormalized, bool leftHanded, bool setToTranspose) {
_setRotate(*this, axis, theta, isNormalized, leftHanded, setToTranspose);
WE::identity(*this, false, true);
}
void RigidMatrix3x2::setupRotation(const Vector2 &eulerAngles, bool leftHanded, bool setToTranspose) {
_setRotate(*this, eulerAngles, leftHanded, setToTranspose);
WE::identity(*this, false, true);
}
void Matrix3x2::__setScale(const Vector2 &s) {
// Set the matrix elements. Pretty straightforward
m11 *= s.x;
m22 *= s.y;
}
void Matrix3x2::__setupScale(const Vector2 &s) {
// Set the matrix elements. Pretty straightforward
m11 = s.x; m12 = 0.0f;
m21 = 0.0f; m22 = s.y;
// Reset the translation portion
WE::identity(*this, false, true);
}
float determinant(const Matrix3x2 &m) {
return
m.m11 * (m.m22)
+ m.m12 * (- m.m21);
}
void inverse(const Matrix3x2 &m, Matrix3x2 &r) {
// Compute the determinant
float det = determinant(m);
// If we're singular, then the determinant is zero and there's
// no inverse
assrt(fabs(det) > 0.000001f);
// Compute one over the determinant, so we divide once and
// can *multiply* per element
float oneOverDet = 1.0f / det;
// Compute the 2x2 portion of the inverse, by
// dividing the adjoint by the determinant
r.m11 = (m.m22 ) * oneOverDet;
r.m12 = (- m.m12) * oneOverDet;
r.m21 = (- m.m21) * oneOverDet;
r.m22 = (m.m11) * oneOverDet;
// Compute the translation portion of the inverse
r.tx = -(m.tx*r.m11 + m.ty*r.m21);
r.ty = -(m.tx*r.m12 + m.ty*r.m22);
}
} | 21 | 132 | 0.626656 | jadnohra |
06e82ce46e53badcce22a05eec8cc34cfad94f59 | 579 | cpp | C++ | quests/dziwne_sumowanie/dziwne_sumowanie/dziwne_sumowanie.cpp | Donkrzawayan/DECODE-IT_pracuj_pl | a09daa973d32d46d9dc8e7dec284821f52a10607 | [
"Apache-2.0"
] | 1 | 2021-01-06T22:15:09.000Z | 2021-01-06T22:15:09.000Z | quests/dziwne_sumowanie/dziwne_sumowanie/dziwne_sumowanie.cpp | Donkrzawayan/DECODE-IT_pracuj_pl | a09daa973d32d46d9dc8e7dec284821f52a10607 | [
"Apache-2.0"
] | null | null | null | quests/dziwne_sumowanie/dziwne_sumowanie/dziwne_sumowanie.cpp | Donkrzawayan/DECODE-IT_pracuj_pl | a09daa973d32d46d9dc8e7dec284821f52a10607 | [
"Apache-2.0"
] | null | null | null | //
#include <iostream>
#include <vector>
#include <cstdint>
#include <string>
void processString() {
unsigned n;
std::cin >> n;
std::cin.get(); //clear input
std::vector<uint_fast8_t> str(4 * n);
for (unsigned j = 0; j < 4 * n; ++j)
str[j] = std::cin.get() - '0';
std::cin.get(); //clear input
std::string answer;
for (unsigned j = 0; j < 4 * n; j += 4)
answer += (str[j] * 10 + str[j + 2]) + (str[j + 1] * 10 + str[j + 3]);
std::cout << answer << "\n";
}
int main()
{
unsigned t;
std::cin >> t;
for (unsigned i = 0; i < t; ++i)
processString();
}
// 100
| 18.09375 | 72 | 0.542314 | Donkrzawayan |
06e9f05fba4fd522479cff255bd0739a90440b1d | 30,542 | cc | C++ | lib/memoro/memoro_interceptors.cc | epfl-vlsc/compiler-rt | 8d8b3f33c09f637f3fbe406eebf38280e9ee7340 | [
"MIT"
] | 2 | 2020-02-04T15:21:22.000Z | 2020-02-05T08:20:25.000Z | lib/memoro/memoro_interceptors.cc | epfl-vlsc/compiler-rt | 8d8b3f33c09f637f3fbe406eebf38280e9ee7340 | [
"MIT"
] | 1 | 2019-11-05T13:08:01.000Z | 2019-11-05T13:08:01.000Z | lib/memoro/memoro_interceptors.cc | epfl-vlsc/compiler-rt | 8d8b3f33c09f637f3fbe406eebf38280e9ee7340 | [
"MIT"
] | null | null | null | //=-- memoro_interceptors.cc ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of Memoro.
// Stuart Byma, EPFL.
//
// Interceptors for Memoro.
//
//===----------------------------------------------------------------------===//
#include "memoro_interceptors.h"
#include "interception/interception.h"
#include "memoro.h"
#include "memoro_allocator.h"
#include "memoro_flags.h"
#include "memoro_thread.h"
#include "sanitizer_common/sanitizer_allocator.h"
#include "sanitizer_common/sanitizer_allocator_checks.h"
#include "sanitizer_common/sanitizer_platform_interceptors.h"
#include "sanitizer_common/sanitizer_posix.h"
#include "sanitizer_common/sanitizer_tls_get_addr.h"
#include <stddef.h>
using namespace __memoro;
// Fake std::nothrow_t and std::align_val_t to avoid including <new>.
namespace std {
struct nothrow_t {};
enum class align_val_t: size_t {};
} // namespace std
extern "C" {
int pthread_attr_init(void *attr);
int pthread_attr_destroy(void *attr);
// int pthread_attr_getdetachstate(void *attr, int *v);
int pthread_key_create(unsigned *key, void (*destructor)(void *v));
int pthread_setspecific(unsigned key, const void *v);
}
///// Malloc/free interceptors. /////
namespace std {
struct nothrow_t;
}
DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr)
DECLARE_REAL_AND_INTERCEPTOR(void, free, void *)
#if !SANITIZER_MAC
static uptr allocated_for_dlsym;
static const uptr kDlsymAllocPoolSize = 1024 * 1024;
static uptr alloc_memory_for_dlsym[kDlsymAllocPoolSize];
static bool IsInDlsymAllocPool(const void *ptr) {
uptr off = (uptr)ptr - (uptr)alloc_memory_for_dlsym;
return off < sizeof(alloc_memory_for_dlsym);
}
static void *AllocateFromLocalPool(uptr size_in_bytes) {
uptr size_in_words = RoundUpTo(size_in_bytes, kWordSize) / kWordSize;
void *mem = (void*)&alloc_memory_for_dlsym[allocated_for_dlsym];
allocated_for_dlsym += size_in_words;
CHECK_LT(allocated_for_dlsym, kDlsymAllocPoolSize);
return mem;
}
INTERCEPTOR(void *, malloc, uptr size) {
if (UNLIKELY(!memoro_inited))
// Hack: dlsym calls malloc before REAL(malloc) is retrieved from dlsym.
return AllocateFromLocalPool(size);
ENSURE_MEMORO_INITED();
GET_STACK_TRACE_MALLOC;
return memoro_malloc(size, stack);
}
INTERCEPTOR(void, free, void *p) {
if (UNLIKELY(IsInDlsymAllocPool(p)))
return;
ENSURE_MEMORO_INITED();
memoro_free(p);
}
INTERCEPTOR(void *, calloc, uptr nmemb, uptr size) {
if (UNLIKELY(!memoro_inited))
// Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym.
return AllocateFromLocalPool(nmemb * size);
ENSURE_MEMORO_INITED();
GET_STACK_TRACE_MALLOC;
return memoro_calloc(nmemb, size, stack);
}
INTERCEPTOR(void *, realloc, void *ptr, uptr size) {
GET_STACK_TRACE_MALLOC;
if (UNLIKELY(IsInDlsymAllocPool(ptr))) {
uptr offset = (uptr)ptr - (uptr)alloc_memory_for_dlsym;
uptr copy_size = Min(size, kDlsymAllocPoolSize - offset);
void *new_ptr = memoro_malloc(size, stack);
internal_memcpy(new_ptr, ptr, copy_size);
return new_ptr;
}
ENSURE_MEMORO_INITED();
return memoro_realloc(ptr, size, stack);
}
INTERCEPTOR(int, posix_memalign, void **memptr, uptr alignment, uptr size) {
ENSURE_MEMORO_INITED();
GET_STACK_TRACE_MALLOC;
*memptr = memoro_memalign(alignment, size, stack);
// FIXME: Return ENOMEM if user requested more than max alloc size.
return 0;
}
INTERCEPTOR(void *, valloc, uptr size) {
ENSURE_MEMORO_INITED();
GET_STACK_TRACE_MALLOC;
return memoro_valloc(size, stack);
}
#endif
#if SANITIZER_INTERCEPT_MEMALIGN
INTERCEPTOR(void *, memalign, uptr alignment, uptr size) {
ENSURE_MEMORO_INITED();
GET_STACK_TRACE_MALLOC;
return memoro_memalign(alignment, size, stack);
}
#define MEMORO_MAYBE_INTERCEPT_MEMALIGN INTERCEPT_FUNCTION(memalign)
INTERCEPTOR(void *, __libc_memalign, uptr alignment, uptr size) {
ENSURE_MEMORO_INITED();
GET_STACK_TRACE_MALLOC;
void *res = memoro_memalign(alignment, size, stack);
DTLS_on_libc_memalign(res, size);
return res;
}
#define MEMORO_MAYBE_INTERCEPT___LIBC_MEMALIGN \
INTERCEPT_FUNCTION(__libc_memalign)
#else
#define MEMORO_MAYBE_INTERCEPT_MEMALIGN
#define MEMORO_MAYBE_INTERCEPT___LIBC_MEMALIGN
#endif // SANITIZER_INTERCEPT_MEMALIGN
#if SANITIZER_INTERCEPT_ALIGNED_ALLOC
INTERCEPTOR(void *, aligned_alloc, uptr alignment, uptr size) {
ENSURE_MEMORO_INITED();
GET_STACK_TRACE_MALLOC;
return memoro_memalign(alignment, size, stack);
}
#define MEMORO_MAYBE_INTERCEPT_ALIGNED_ALLOC INTERCEPT_FUNCTION(aligned_alloc)
#else
#define MEMORO_MAYBE_INTERCEPT_ALIGNED_ALLOC
#endif
#if SANITIZER_INTERCEPT_MALLOC_USABLE_SIZE
INTERCEPTOR(uptr, malloc_usable_size, void *ptr) {
ENSURE_MEMORO_INITED();
return GetMallocUsableSize(ptr);
}
#define MEMORO_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE \
INTERCEPT_FUNCTION(malloc_usable_size)
#else
#define MEMORO_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE
#endif
#if SANITIZER_INTERCEPT_MALLOPT_AND_MALLINFO
struct fake_mallinfo {
int x[10];
};
INTERCEPTOR(struct fake_mallinfo, mallinfo, void) {
struct fake_mallinfo res;
internal_memset(&res, 0, sizeof(res));
return res;
}
#define MEMORO_MAYBE_INTERCEPT_MALLINFO INTERCEPT_FUNCTION(mallinfo)
INTERCEPTOR(int, mallopt, int cmd, int value) { return -1; }
#define MEMORO_MAYBE_INTERCEPT_MALLOPT INTERCEPT_FUNCTION(mallopt)
#else
#define MEMORO_MAYBE_INTERCEPT_MALLINFO
#define MEMORO_MAYBE_INTERCEPT_MALLOPT
#endif // SANITIZER_INTERCEPT_MALLOPT_AND_MALLINFO
#if SANITIZER_INTERCEPT_PVALLOC
INTERCEPTOR(void *, pvalloc, uptr size) {
ENSURE_MEMORO_INITED();
GET_STACK_TRACE_MALLOC;
uptr PageSize = GetPageSizeCached();
size = RoundUpTo(size, PageSize);
if (size == 0) {
// pvalloc(0) should allocate one page.
size = PageSize;
}
return Allocate(stack, size, GetPageSizeCached(), kAlwaysClearMemory);
}
#define MEMORO_MAYBE_INTERCEPT_PVALLOC INTERCEPT_FUNCTION(pvalloc)
#else
#define MEMORO_MAYBE_INTERCEPT_PVALLOC
#endif // SANITIZER_INTERCEPT_PVALLOC
#if SANITIZER_INTERCEPT_CFREE
INTERCEPTOR(void, cfree, void *p) ALIAS(WRAPPER_NAME(free));
#define MEMORO_MAYBE_INTERCEPT_CFREE INTERCEPT_FUNCTION(cfree)
#else
#define MEMORO_MAYBE_INTERCEPT_CFREE
#endif // SANITIZER_INTERCEPT_CFREE
#define OPERATOR_NEW_BODY \
ENSURE_MEMORO_INITED(); \
GET_STACK_TRACE_MALLOC; \
return Allocate(stack, size, 1, kAlwaysClearMemory);
#define OPERATOR_NEW_BODY_ALIGN \
ENSURE_MEMORO_INITED(); \
GET_STACK_TRACE_MALLOC; \
return Allocate(stack, size, (uptr)align, kAlwaysClearMemory);
INTERCEPTOR_ATTRIBUTE
void *operator new(size_t size) { OPERATOR_NEW_BODY; }
INTERCEPTOR_ATTRIBUTE
void *operator new[](size_t size) { OPERATOR_NEW_BODY; }
INTERCEPTOR_ATTRIBUTE
void *operator new(size_t size, std::nothrow_t const &) { OPERATOR_NEW_BODY; }
INTERCEPTOR_ATTRIBUTE
void *operator new[](size_t size, std::nothrow_t const &) { OPERATOR_NEW_BODY; }
INTERCEPTOR_ATTRIBUTE
void *operator new(size_t size, std::align_val_t align)
{ OPERATOR_NEW_BODY_ALIGN; }
INTERCEPTOR_ATTRIBUTE
void *operator new[](size_t size, std::align_val_t align)
{ OPERATOR_NEW_BODY_ALIGN; }
INTERCEPTOR_ATTRIBUTE
void *operator new(size_t size, std::align_val_t align, std::nothrow_t const&)
{ OPERATOR_NEW_BODY_ALIGN; }
INTERCEPTOR_ATTRIBUTE
void *operator new[](size_t size, std::align_val_t align, std::nothrow_t const&)
{ OPERATOR_NEW_BODY_ALIGN; }
#define OPERATOR_DELETE_BODY \
ENSURE_MEMORO_INITED(); \
Deallocate(ptr);
INTERCEPTOR_ATTRIBUTE
void operator delete(void *ptr)NOEXCEPT { OPERATOR_DELETE_BODY; }
INTERCEPTOR_ATTRIBUTE
void operator delete[](void *ptr) NOEXCEPT { OPERATOR_DELETE_BODY; }
INTERCEPTOR_ATTRIBUTE
void operator delete(void *ptr, std::nothrow_t const &) {
OPERATOR_DELETE_BODY;
}
INTERCEPTOR_ATTRIBUTE
void operator delete[](void *ptr, std::nothrow_t const &) {
OPERATOR_DELETE_BODY;
}
INTERCEPTOR_ATTRIBUTE
void operator delete(void *ptr, size_t size) NOEXCEPT
{ OPERATOR_DELETE_BODY; }
INTERCEPTOR_ATTRIBUTE
void operator delete[](void *ptr, size_t size) NOEXCEPT
{ OPERATOR_DELETE_BODY; }
INTERCEPTOR_ATTRIBUTE
void operator delete(void *ptr, std::align_val_t align) NOEXCEPT
{ OPERATOR_DELETE_BODY; }
INTERCEPTOR_ATTRIBUTE
void operator delete[](void *ptr, std::align_val_t align) NOEXCEPT
{ OPERATOR_DELETE_BODY; }
INTERCEPTOR_ATTRIBUTE
void operator delete(void *ptr, std::align_val_t align, std::nothrow_t const&)
{ OPERATOR_DELETE_BODY; }
INTERCEPTOR_ATTRIBUTE
void operator delete[](void *ptr, std::align_val_t align, std::nothrow_t const&)
{ OPERATOR_DELETE_BODY; }
INTERCEPTOR_ATTRIBUTE
void operator delete(void *ptr, size_t size, std::align_val_t align) NOEXCEPT
{ OPERATOR_DELETE_BODY; }
INTERCEPTOR_ATTRIBUTE
void operator delete[](void *ptr, size_t size, std::align_val_t align) NOEXCEPT
{ OPERATOR_DELETE_BODY; }
#define MEMORO_READ_RANGE(ctx, offset, size) \
processRangeAccess(GET_CALLER_PC(), (uptr)offset, size, false)
#define MEMORO_WRITE_RANGE(ctx, offset, size) \
processRangeAccess(GET_CALLER_PC(), (uptr)offset, size, true)
// Behavior of functions like "memcpy" or "strcpy" is undefined
// if memory intervals overlap. We report error in this case.
// Macro is used to avoid creation of new frames.
static inline bool RangesOverlap(const char *offset1, uptr length1,
const char *offset2, uptr length2) {
return !((offset1 + length1 <= offset2) || (offset2 + length2 <= offset1));
}
#define CHECK_RANGES_OVERLAP(name, _offset1, length1, _offset2, length2) \
do { \
const char *offset1 = (const char *)_offset1; \
const char *offset2 = (const char *)_offset2; \
if (RangesOverlap(offset1, length1, offset2, length2)) { \
GET_STACK_TRACE_FATAL; \
Printf("Ranges overlap wtf\n"); \
} \
} while (0)
#define MEMORO_MEMCPY_IMPL(ctx, to, from, size) \
do { \
if (UNLIKELY(!memoro_inited)) \
return internal_memcpy(to, from, size); \
if (memoro_init_is_running) { \
return REAL(memcpy)(to, from, size); \
} \
ENSURE_MEMORO_INITED(); \
if (getFlags()->replace_intrin) { \
if (to != from) { \
CHECK_RANGES_OVERLAP("memcpy", to, size, from, size); \
} \
MEMORO_READ_RANGE(ctx, from, size); \
MEMORO_WRITE_RANGE(ctx, to, size); \
} \
return REAL(memcpy)(to, from, size); \
} while (0)
// memset is called inside Printf.
#define MEMORO_MEMSET_IMPL(ctx, block, c, size) \
do { \
if (UNLIKELY(!memoro_inited)) \
return internal_memset(block, c, size); \
if (memoro_init_is_running) { \
return REAL(memset)(block, c, size); \
} \
ENSURE_MEMORO_INITED(); \
if (getFlags()->replace_intrin) { \
MEMORO_WRITE_RANGE(ctx, block, size); \
} \
return REAL(memset)(block, c, size); \
} while (0)
#define MEMORO_MEMMOVE_IMPL(ctx, to, from, size) \
do { \
if (UNLIKELY(!memoro_inited)) \
return internal_memmove(to, from, size); \
ENSURE_MEMORO_INITED(); \
if (getFlags()->replace_intrin) { \
MEMORO_READ_RANGE(ctx, from, size); \
MEMORO_WRITE_RANGE(ctx, to, size); \
} \
return internal_memmove(to, from, size); \
} while (0)
void SetThreadName(const char *name) {
u32 t = GetCurrentThread();
if (t)
memoroThreadRegistry().SetThreadName(t, name);
}
// should this direct to the main OnExit in memoro_interface.cc?
int OnExit() { return 0; }
struct MemoroInterceptorContext {
const char *interceptor_name;
};
#define MEMORO_INTERCEPTOR_ENTER(ctx, func) \
MemoroInterceptorContext _ctx = {#func}; \
ctx = (void *)&_ctx; \
(void)ctx;
#define COMMON_INTERCEPT_FUNCTION(name) MEMORO_INTERCEPT_FUNC(name)
#define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \
MEMORO_INTERCEPT_FUNC_VER(name, ver)
#define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
MEMORO_WRITE_RANGE(ctx, ptr, size)
#define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
MEMORO_READ_RANGE(ctx, ptr, size)
#define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \
MEMORO_INTERCEPTOR_ENTER(ctx, func); \
do { \
if (memoro_init_is_running) \
return REAL(func)(__VA_ARGS__); \
if (SANITIZER_MAC && UNLIKELY(!memoro_inited)) \
return REAL(func)(__VA_ARGS__); \
ENSURE_MEMORO_INITED(); \
} while (false)
#define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
do { \
} while (false)
#define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
do { \
} while (false)
#define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
do { \
} while (false)
#define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
do { \
} while (false)
#define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) SetThreadName(name)
// Should be memoroThreadRegistry().SetThreadNameByUserId(thread, name)
// But memoro does not remember UserId's for threads (pthread_t);
// and remembers all ever existed threads, so the linear search by UserId
// can be slow.
#define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
do { \
} while (false)
#define COMMON_INTERCEPTOR_BLOCK_REAL(name) REAL(name)
// Strict init-order checking is dlopen-hostile:
// https://github.com/google/sanitizers/issues/178
#define COMMON_INTERCEPTOR_ON_DLOPEN(filename, flag) \
{}
#define COMMON_INTERCEPTOR_ON_EXIT(ctx) OnExit()
#define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \
{}
#define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \
{}
#define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED (!memoro_inited)
#define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \
if (ThreadContext *t = CurrentThreadContext()) { \
*begin = t->tls_begin(); \
*end = t->tls_end(); \
} else { \
*begin = *end = 0; \
}
#define COMMON_INTERCEPTOR_MEMMOVE_IMPL(ctx, to, from, size) \
do { \
MEMORO_INTERCEPTOR_ENTER(ctx, memmove); \
MEMORO_MEMMOVE_IMPL(ctx, to, from, size); \
} while (false)
#define COMMON_INTERCEPTOR_MEMCPY_IMPL(ctx, to, from, size) \
do { \
MEMORO_INTERCEPTOR_ENTER(ctx, memcpy); \
MEMORO_MEMCPY_IMPL(ctx, to, from, size); \
} while (false)
#define COMMON_INTERCEPTOR_MEMSET_IMPL(ctx, block, c, size) \
do { \
MEMORO_INTERCEPTOR_ENTER(ctx, memset); \
MEMORO_MEMSET_IMPL(ctx, block, c, size); \
} while (false)
// realpath interceptor does something weird with wrapped malloc on mac OS
#undef SANITIZER_INTERCEPT_REALPATH
#undef SANITIZER_INTERCEPT_TLS_GET_ADDR
#include "sanitizer_common/sanitizer_common_interceptors.inc"
///// Thread initialization and finalization. /////
static unsigned g_thread_finalize_key;
static void thread_finalize(void *v) {
uptr iter = (uptr)v;
if (iter > 1) {
if (pthread_setspecific(g_thread_finalize_key, (void *)(iter - 1))) {
Report("LeakSanitizer: failed to set thread key.\n");
Die();
}
return;
}
ThreadFinish();
}
struct ThreadParam {
void *(*callback)(void *arg);
void *param;
atomic_uintptr_t tid;
};
extern "C" void *__memoro_thread_start_func(void *arg) {
ThreadParam *p = (ThreadParam *)arg;
void *(*callback)(void *arg) = p->callback;
void *param = p->param;
// Wait until the last iteration to maximize the chance that we are the last
// destructor to run.
if (pthread_setspecific(g_thread_finalize_key,
(void *)GetPthreadDestructorIterations())) {
Report("Memoro: failed to set thread key.\n");
Die();
}
u32 tid = 0;
while ((tid = (u32)atomic_load(&p->tid, memory_order_acquire)) == 0)
internal_sched_yield();
SetCurrentThread(tid);
ThreadStart(tid, GetTid());
atomic_store(&p->tid, 0, memory_order_release);
return callback(param);
}
INTERCEPTOR(int, pthread_create, void *th, void *attr,
void *(*callback)(void *), void *param) {
ENSURE_MEMORO_INITED();
EnsureMainThreadIDIsCorrect();
__sanitizer_pthread_attr_t myattr;
if (!attr) {
pthread_attr_init(&myattr);
attr = &myattr;
}
AdjustStackSize(attr);
int detached = 0;
pthread_attr_getdetachstate(attr, &detached);
ThreadParam p;
p.callback = callback;
p.param = param;
atomic_store(&p.tid, 0, memory_order_relaxed);
int res;
{
// Ignore all allocations made by pthread_create: thread stack/TLS may be
// stored by pthread for future reuse even after thread destruction, and
// the linked list it's stored in doesn't even hold valid pointers to the
// objects, the latter are calculated by obscure pointer arithmetic.
// stuart: for memoro this may be an unneeded relic
ScopedInterceptorDisabler disabler;
res = REAL(pthread_create)(th, attr, __memoro_thread_start_func, &p);
}
if (res == 0) {
int tid = ThreadCreate(GetCurrentThread(), *(uptr *)th,
/*detached == PTHREAD_CREATE_DETACHED*/ false);
CHECK_NE(tid, 0);
atomic_store(&p.tid, tid, memory_order_release);
while (atomic_load(&p.tid, memory_order_acquire) != 0)
internal_sched_yield();
}
if (attr == &myattr)
pthread_attr_destroy(&myattr);
return res;
}
INTERCEPTOR(int, pthread_join, void *th, void **ret) {
ENSURE_MEMORO_INITED();
u32 tid = ThreadTid((uptr)th);
int res = REAL(pthread_join)(th, ret);
if (res == 0)
ThreadJoin(tid);
return res;
}
#define MEMORO_READ_STRING_OF_LEN(ctx, s, len, n) \
MEMORO_READ_RANGE((ctx), (s), \
common_flags()->strict_string_checks ? (len) + 1 : (n))
#define MEMORO_READ_STRING(ctx, s, n) \
MEMORO_READ_STRING_OF_LEN((ctx), (s), REAL(strlen)(s), (n))
static inline uptr MaybeRealStrnlen(const char *s, uptr maxlen) {
#if SANITIZER_INTERCEPT_STRNLEN
if (REAL(strnlen)) {
return REAL(strnlen)(s, maxlen);
}
#endif
return internal_strnlen(s, maxlen);
}
// For both strcat() and strncat() we need to check the validity of |to|
// argument irrespective of the |from| length.
INTERCEPTOR(char *, strcat, char *to, const char *from) { // NOLINT
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, strcat); // NOLINT
ENSURE_MEMORO_INITED();
if (getFlags()->replace_str) {
uptr from_length = REAL(strlen)(from);
MEMORO_READ_RANGE(ctx, from, from_length + 1);
uptr to_length = REAL(strlen)(to);
MEMORO_READ_STRING_OF_LEN(ctx, to, to_length, to_length);
MEMORO_WRITE_RANGE(ctx, to + to_length, from_length + 1);
// If the copying actually happens, the |from| string should not overlap
// with the resulting string starting at |to|, which has a length of
// to_length + from_length + 1.
if (from_length > 0) {
CHECK_RANGES_OVERLAP("strcat", to, from_length + to_length + 1, from,
from_length + 1);
}
}
return REAL(strcat)(to, from); // NOLINT
}
INTERCEPTOR(char *, strncat, char *to, const char *from, uptr size) {
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, strncat);
ENSURE_MEMORO_INITED();
if (getFlags()->replace_str) {
uptr from_length = MaybeRealStrnlen(from, size);
uptr copy_length = Min(size, from_length + 1);
MEMORO_READ_RANGE(ctx, from, copy_length);
uptr to_length = REAL(strlen)(to);
MEMORO_READ_STRING_OF_LEN(ctx, to, to_length, to_length);
MEMORO_WRITE_RANGE(ctx, to + to_length, from_length + 1);
if (from_length > 0) {
CHECK_RANGES_OVERLAP("strncat", to, to_length + copy_length + 1, from,
copy_length);
}
}
return REAL(strncat)(to, from, size);
}
INTERCEPTOR(char *, strcpy, char *to, const char *from) { // NOLINT
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, strcpy); // NOLINT
#if SANITIZER_MAC
if (UNLIKELY(!memoro_inited))
return REAL(strcpy)(to, from); // NOLINT
#endif
// strcpy is called from malloc_default_purgeable_zone()
// in __memoro::ReplaceSystemAlloc() on Mac.
if (memoro_init_is_running) {
return REAL(strcpy)(to, from); // NOLINT
}
ENSURE_MEMORO_INITED();
if (getFlags()->replace_str) {
uptr from_size = REAL(strlen)(from) + 1;
CHECK_RANGES_OVERLAP("strcpy", to, from_size, from, from_size);
MEMORO_READ_RANGE(ctx, from, from_size);
MEMORO_WRITE_RANGE(ctx, to, from_size);
}
return REAL(strcpy)(to, from); // NOLINT
}
INTERCEPTOR(char *, strdup, const char *s) {
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, strdup);
if (UNLIKELY(!memoro_inited))
return internal_strdup(s);
ENSURE_MEMORO_INITED();
uptr length = REAL(strlen)(s);
if (getFlags()->replace_str) {
MEMORO_READ_RANGE(ctx, s, length + 1);
}
GET_STACK_TRACE_MALLOC;
void *new_mem = memoro_malloc(length + 1, stack);
MEMORO_WRITE_RANGE(ctx, new_mem, length + 1);
REAL(memcpy)(new_mem, s, length + 1);
return reinterpret_cast<char *>(new_mem);
}
#if MEMORO_INTERCEPT___STRDUP
INTERCEPTOR(char *, __strdup, const char *s) {
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, strdup);
if (UNLIKELY(!memoro_inited))
return internal_strdup(s);
ENSURE_MEMORO_INITED();
uptr length = REAL(strlen)(s);
if (getFlags()->replace_str) {
MEMORO_READ_RANGE(ctx, s, length + 1);
}
GET_STACK_TRACE_MALLOC;
void *new_mem = memoro_malloc(length + 1, stack);
REAL(memcpy)(new_mem, s, length + 1);
return reinterpret_cast<char *>(new_mem);
}
#endif // MEMORO_INTERCEPT___STRDUP
INTERCEPTOR(char *, strncpy, char *to, const char *from, uptr size) {
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, strncpy);
ENSURE_MEMORO_INITED();
if (getFlags()->replace_str) {
uptr from_size = Min(size, MaybeRealStrnlen(from, size) + 1);
CHECK_RANGES_OVERLAP("strncpy", to, from_size, from, from_size);
MEMORO_READ_RANGE(ctx, from, from_size);
MEMORO_WRITE_RANGE(ctx, to, size);
}
return REAL(strncpy)(to, from, size);
}
INTERCEPTOR(long, strtol, const char *nptr, // NOLINT
char **endptr, int base) {
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, strtol);
ENSURE_MEMORO_INITED();
if (!getFlags()->replace_str) {
return REAL(strtol)(nptr, endptr, base);
}
char *real_endptr;
long result = REAL(strtol)(nptr, &real_endptr, base); // NOLINT
StrtolFixAndCheck(ctx, nptr, endptr, real_endptr, base);
return result;
}
INTERCEPTOR(int, atoi, const char *nptr) {
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, atoi);
#if SANITIZER_MAC
if (UNLIKELY(!memoro_inited))
return REAL(atoi)(nptr);
#endif
ENSURE_MEMORO_INITED();
if (!getFlags()->replace_str) {
return REAL(atoi)(nptr);
}
char *real_endptr;
// "man atoi" tells that behavior of atoi(nptr) is the same as
// strtol(nptr, 0, 10), i.e. it sets errno to ERANGE if the
// parsed integer can't be stored in *long* type (even if it's
// different from int). So, we just imitate this behavior.
int result = REAL(strtol)(nptr, &real_endptr, 10);
FixRealStrtolEndptr(nptr, &real_endptr);
MEMORO_READ_STRING(ctx, nptr, (real_endptr - nptr) + 1);
return result;
}
INTERCEPTOR(long, atol, const char *nptr) { // NOLINT
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, atol);
#if SANITIZER_MAC
if (UNLIKELY(!memoro_inited))
return REAL(atol)(nptr);
#endif
ENSURE_MEMORO_INITED();
if (!getFlags()->replace_str) {
return REAL(atol)(nptr);
}
char *real_endptr;
long result = REAL(strtol)(nptr, &real_endptr, 10); // NOLINT
FixRealStrtolEndptr(nptr, &real_endptr);
MEMORO_READ_STRING(ctx, nptr, (real_endptr - nptr) + 1);
return result;
}
#if MEMORO_INTERCEPT_ATOLL_AND_STRTOLL
INTERCEPTOR(long long, strtoll, const char *nptr, // NOLINT
char **endptr, int base) {
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, strtoll);
ENSURE_MEMORO_INITED();
if (!getFlags()->replace_str) {
return REAL(strtoll)(nptr, endptr, base);
}
char *real_endptr;
long long result = REAL(strtoll)(nptr, &real_endptr, base); // NOLINT
StrtolFixAndCheck(ctx, nptr, endptr, real_endptr, base);
return result;
}
INTERCEPTOR(long long, atoll, const char *nptr) { // NOLINT
void *ctx;
MEMORO_INTERCEPTOR_ENTER(ctx, atoll);
ENSURE_MEMORO_INITED();
if (!getFlags()->replace_str) {
return REAL(atoll)(nptr);
}
char *real_endptr;
long long result = REAL(strtoll)(nptr, &real_endptr, 10); // NOLINT
FixRealStrtolEndptr(nptr, &real_endptr);
MEMORO_READ_STRING(ctx, nptr, (real_endptr - nptr) + 1);
return result;
}
#endif // MEMORO_INTERCEPTA_ATOLL_AND_STRTOLL
namespace __memoro {
void InitializeInterceptors() {
static bool was_called_once;
CHECK(!was_called_once);
was_called_once = true;
InitializeCommonInterceptors();
// Intercept str* functions.
MEMORO_INTERCEPT_FUNC(strcat); // NOLINT
MEMORO_INTERCEPT_FUNC(strcpy); // NOLINT
MEMORO_INTERCEPT_FUNC(wcslen);
MEMORO_INTERCEPT_FUNC(strncat);
MEMORO_INTERCEPT_FUNC(strncpy);
MEMORO_INTERCEPT_FUNC(strdup);
#if MEMORO_INTERCEPT___STRDUP
MEMORO_INTERCEPT_FUNC(__strdup);
#endif
#if MEMORO_INTERCEPT_INDEX && MEMORO_USE_ALIAS_ATTRIBUTE_FOR_INDEX
MEMORO_INTERCEPT_FUNC(index);
#endif
MEMORO_INTERCEPT_FUNC(atoi);
MEMORO_INTERCEPT_FUNC(atol);
MEMORO_INTERCEPT_FUNC(strtol);
#if MEMORO_INTERCEPT_ATOLL_AND_STRTOLL
MEMORO_INTERCEPT_FUNC(atoll);
MEMORO_INTERCEPT_FUNC(strtoll);
#endif
INTERCEPT_FUNCTION(malloc);
INTERCEPT_FUNCTION(free);
MEMORO_MAYBE_INTERCEPT_CFREE;
INTERCEPT_FUNCTION(calloc);
INTERCEPT_FUNCTION(realloc);
INTERCEPT_FUNCTION(puts);
INTERCEPT_FUNCTION(fread);
INTERCEPT_FUNCTION(fwrite);
MEMORO_MAYBE_INTERCEPT_MEMALIGN;
MEMORO_MAYBE_INTERCEPT___LIBC_MEMALIGN;
MEMORO_MAYBE_INTERCEPT_ALIGNED_ALLOC;
INTERCEPT_FUNCTION(posix_memalign);
INTERCEPT_FUNCTION(valloc);
MEMORO_MAYBE_INTERCEPT_PVALLOC;
MEMORO_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE;
MEMORO_MAYBE_INTERCEPT_MALLINFO;
MEMORO_MAYBE_INTERCEPT_MALLOPT;
INTERCEPT_FUNCTION(pthread_create);
INTERCEPT_FUNCTION(pthread_join);
if (pthread_key_create(&g_thread_finalize_key, &thread_finalize)) {
Report("Memoro: failed to create thread key.\n");
Die();
}
}
} // namespace __memoro
| 37.799505 | 80 | 0.611715 | epfl-vlsc |
06ebf1308d3f100bbd83cdc9f2dc2db14ccb6bf8 | 10,681 | cpp | C++ | icusegments/icusegments.cpp | srl295/icu | 7c7f805b917476f269babc853fb1eb3e0a17a88b | [
"ICU",
"Unlicense"
] | 1 | 2018-07-24T21:03:12.000Z | 2018-07-24T21:03:12.000Z | icusegments/icusegments.cpp | srl295/icu | 7c7f805b917476f269babc853fb1eb3e0a17a88b | [
"ICU",
"Unlicense"
] | null | null | null | icusegments/icusegments.cpp | srl295/icu | 7c7f805b917476f269babc853fb1eb3e0a17a88b | [
"ICU",
"Unlicense"
] | 1 | 2018-07-13T15:52:46.000Z | 2018-07-13T15:52:46.000Z | /*
Copyright (C) 1999-2014, International Business Machines
Corporation and others. All Rights Reserved.
ICU Segments Demo
*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "unicode/utypes.h"
#include "unicode/ubrk.h"
#include "unicode/brkiter.h"
#include "unicode/ustring.h"
#include "unicode/uloc.h"
#include "unicode/localpointer.h"
#include "unicode/filteredbrk.h"
#include "demo_settings.h"
#include "demoutil.h"
//#include "ulibrk.h"
#include "json.hxx"
static const char *htmlHeader=
"Content-Type: text/html; charset=utf-8\n"
"\n"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
"<head>\n";
static const char endHeaderBeginBody[] =
"</head>\n"
"<body>\n";
static const char breadCrumbMainHeader[]=
DEMO_BREAD_CRUMB_BAR
"<h1>ICU Segments</h1>\n";
static const char defaultHeader[]=
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
"<title>ICU Segments (Error: can't load icusegments-header.html!)</title>\n";
static const char *htmlFooter=
"</body>\n"
"</html>";
/**
* path, mimetype,
* path, mimetype,
* NULL, NULL
*/
const char *statics[] = {
"/icusegments.js", "application/javascript",
"/icusegments.css", "text/css",
"/icusegments-dojo.js", "application/javascript",
NULL, NULL
};
static void doJSON(const char *pi);
UErrorCode uliStatus = U_BRK_INTERNAL_ERROR;
int main(void)
{
const char *rm = getenv("REQUEST_METHOD");
// static files
const char *pi = getenv("PATH_INFO");
if(!rm) rm = "GET";
if(!strcmp(rm,"GET") && pi && *pi) { /* static */
if(!strcmp(pi, "/ulitest")) {
printf("Content-type: text/plain\n\n");
printf("N/A");
//ulibrk_test();
return 0;
} else {
if(serveStaticFile(statics, pi)) return 0;
printf("Status: 404 Not Found\nContent-type: text/plain\n\nError: no file at this location.\n");
return 0;
}
} else if(strcmp(rm,"POST")) { /* homepage */
//const char *script=getenv("SCRIPT_NAME"); //"/cgi-bin/nbrowser"
puts(htmlHeader);
if (FALSE || !printHTMLFragment(NULL, NULL, DEMO_COMMON_DIR "icusegments-header.html")) {
puts(defaultHeader);
}
puts(endHeaderBeginBody);
if (printHTMLFragment(NULL, NULL, DEMO_COMMON_MASTHEAD)) {
puts(DEMO_BEGIN_LEFT_NAV);
printHTMLFragment(NULL, NULL, DEMO_COMMON_LEFTNAV "2");
puts(DEMO_END_LEFT_NAV);
puts(DEMO_BEGIN_CONTENT);
}
puts(breadCrumbMainHeader);
if (!printHTMLFragment(NULL, NULL, DEMO_COMMON_DIR "icusegments-body.html")) {
puts("<h1>Error: Could not load icusegments-body.html</h1>");
}
puts(DEMO_END_CONTENT);
printHTMLFragment(NULL, NULL, DEMO_COMMON_FOOTER);
puts(htmlFooter);
} else {
// POST.
//uliStatus = U_ZERO_ERROR;
//ulibrk_install(uliStatus);
doJSON(pi);
}
return 0;
}
static int json_setUString(struct json *J, const UChar* s, const char *path) {
char tmp[2048];
UErrorCode status = U_ZERO_ERROR; // TODO check
int err = json_setstring(J, u_strToUTF8(tmp, 2048, NULL, s, -1, &status), path);
if(U_FAILURE(status)) return -1;
return err;
}
static void doJSON(const char *pi) {
int error = 0;
UErrorCode status = U_ZERO_ERROR;
// read input JSON
json *ji = json_open(0, &error); // input
json *j = json_open(0, &error); // output
// for now - assume processes utf-8 ok?
{
char inbuf[4096];
int inSize=-1;
const char *contentLength = getenv("CONTENT_LENGTH");
if(!contentLength||!*contentLength ||
!sscanf(contentLength, "%d", &inSize) || inSize==0) {
// no contentlength?!
json_setnumber(ji, 0, "err.contentLength");
json_setstring(j, "No ContentLength", "err.message");
} else {
int sizeLeft=inSize;
int thisSize=-1;
json_setnumber(j, inSize, "debug.contentLength");
while(sizeLeft>0&&!feof(stdin)&&(thisSize=fread(inbuf,1,sizeof(inbuf)/sizeof(inbuf[0]),stdin))) {
sizeLeft-=thisSize;
json_setnumber(j, thisSize, "debug.lastReadOk");
//if((error=json_parse(ji,inbuf,thisSize))) { TODO: why doesn't json_parse work?
if((error=json_loadlstring(ji,inbuf,thisSize))) {
json_setnumber(ji, error, "err.reading");
json_setnumber(j, error, "err.reading");
char tmp[200];
sprintf(tmp,"Error reading: %s at byte %d", json_strerror(error), inSize-sizeLeft);
json_setstring(j, tmp, "err.message");
json_setstring(ji, tmp, "err.message");
break;
}
}
if(error==0 && sizeLeft>0) {
json_setnumber(ji, sizeLeft, "err.shortRead");
json_setnumber(j, sizeLeft, "err.shortRead");
json_setboolean(j, feof(stdin), "debug.feof");
json_setstring(j, "Error short read", "err.message");
}
}
}
// now, the reply
if(!strcmp(pi,"/version")) {
json_setstring(j, U_ICU_VERSION, "icu.version");
//json_setstring(j, u_errorName(uliStatus), "icu.ulistatus");
// put a list of all break iterators available
//int32_t a = ubrk_countAvailable();
LocalPointer<StringEnumeration> availLocs(BreakIterator::getAvailableLocales());
const char *s;
for(int32_t i=0; (s=availLocs->next(NULL, status)); i++) {
char tmp[200];
sprintf(tmp, "brks.%s", s);
UChar tmp2[2048] = {(UChar)0x0};
uloc_getDisplayName(s, NULL, tmp2,2048,&status);
json_setUString(j, tmp2, tmp);
}
// HACK - need a way to list these
const char *uliLocs[] = { "de",
"en",
"es",
"fr",
"it",
"pt",
"ru",
NULL
};
for(int32_t i =0;uliLocs[i];i++) {
char tmp[200];
char s[200];
sprintf(s, "%s__ULI", uliLocs[i]);
sprintf(tmp, "brks.%s", s);
UChar tmp2[2048] = {(UChar)0x0};
uloc_getDisplayName(s, NULL, tmp2,2048,&status);
json_setUString(j, tmp2, tmp);
}
// add types
{
#define ADD_TYPE(x) json_setstring(j, #x, "types.#", (int) UBRK_ ## x)
ADD_TYPE(CHARACTER);
ADD_TYPE(WORD);
ADD_TYPE(LINE);
ADD_TYPE(SENTENCE);
#undef ADD_TYPE
}
} else if(!strcmp(pi,"/break")) {
const char *bLocale = json_string(ji, "settings.bLocale");
//const char *dLocale = json_string(ji, "settings.dLocale");
const char *str = json_string(ji, "param.str");
const char *tstr = json_string(ji, "settings.type"); // TODO: json_number failed us here.
int type =-1;
if(!sscanf(tstr, "%d", &type)) {
type=-1;
}
//UChar ustr[2048];
UErrorCode status = U_ZERO_ERROR;
UnicodeString ustr(str, "utf-8");
//LocalUTextPointer utxt(utext_openUTF8(NULL,str, -1, &status));
json_setarray(j, "breaks.idx");
int n = 0;
int32_t next;
//LocalUBreakIteratorPointer brk(ubrk_open((UBreakIteratorType)type, bLocale, NULL, 0, &status));
#if 1
// Argh. Have to use C++. Filed #9764
LocalPointer<BreakIterator> brk;
Locale bLocId(bLocale);
// pointless duplication of ubrk.cpp
switch(type) {
case UBRK_CHARACTER:
brk.adoptInstead(BreakIterator::createCharacterInstance(bLocId,status));
break;
case UBRK_WORD:
brk.adoptInstead(BreakIterator::createWordInstance(bLocId,status));
break;
case UBRK_SENTENCE:
brk.adoptInstead(BreakIterator::createSentenceInstance(bLocId,status));
if(strcmp(bLocId.getVariant(),"ULI") == 0) {
// TODO: using _ULI is a hack here anyways.
// should include keywords here.
// TODO: worse than that. _ULI is a territory..
Locale locId(bLocId.getLanguage(), bLocId.getCountry(), NULL, NULL);
LocalPointer<FilteredBreakIteratorBuilder> builder;
builder.adoptInstead(FilteredBreakIteratorBuilder::createInstance(locId,
status));
fprintf(stderr, "%s -> %s\n", locId.getBaseName(), u_errorName(status));
json_setstring(j, locId.getBaseName(), "_dbg.locid");
json_setstring(j, u_errorName(status), "_dbg.status");
brk.adoptInstead(builder->build(brk.orphan(), status)); // adopt filtered
} else {
json_setstring(j, bLocId.getCountry(), "_dbg.variant");
}
break;
case UBRK_LINE:
brk.adoptInstead(BreakIterator::createLineInstance(bLocId,status));
break;
}
brk->setText(ustr);
json_setnumber(j, brk->current(), "breaks.idx[#]", n++);
while((next=brk->next())!=UBRK_DONE) {
json_setnumber(j, next, "breaks.idx[#]", n++); // "next" would give us the UChar index.
}
#else
// Text comes in as UTF-8 - however, JavaScript will operate in UTF-16 (UCS-2?) chunks. So, go via UnicodeString
LocalUBreakIteratorPointer brk(ubrk_open((UBreakIteratorType)type, bLocale, ustr.getTerminatedBuffer(), ustr.length(), &status));
//ubrk_setUText(brk.getAlias(), utxt.getAlias(), &status);
json_setnumber(j, ubrk_current(brk.getAlias()), "breaks.idx[#]", n++);
//json_setnumber(j, utext_getNativeIndex(utxt.getAlias()), "breaks.idx[#]", n++); // ubrk_current would give us the UChar index.
while((next=ubrk_next(brk.getAlias()))!=UBRK_DONE) {
json_setnumber(j, next, "breaks.idx[#]", n++); // "next" would give us the UChar index.
//json_setnumber(j, utext_getNativeIndex(utxt.getAlias()), "breaks.idx[#]", n++); // "next" would give us the UChar index.
}
#endif
//json_setnumber(j, utext_nativeLength(utxt.getAlias()), "debug.nativeLength");
json_setnumber(j, strlen(str), "debug.strlen");
json_setstring(j, bLocale, "debug.bLocale");
json_setnumber(j, type, "debug.type");
if(U_FAILURE(status)) {
json_setstring(j, u_errorName(status), "err.message");
}
} else {
json_setstring(j, "Unknown path!","err.message");
}
printf("Content-type: application/json\n");
printf("\n");
if((error=json_printfile(j, stdout, 0))) {
printf(" /* ERROR %d */\n", error);
}
printf(" /* end JSON for %s */\n", pi);
}
| 33.907937 | 135 | 0.601161 | srl295 |
06ec65d32c239b027ce1f0031338c963e524d595 | 51,921 | cpp | C++ | Engine/Source/Runtime/Renderer/Private/DistanceFieldObjectManagement.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Renderer/Private/DistanceFieldObjectManagement.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Renderer/Private/DistanceFieldObjectManagement.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
DistanceFieldSurfaceCacheLighting.cpp
=============================================================================*/
#include "CoreMinimal.h"
#include "Stats/Stats.h"
#include "HAL/IConsoleManager.h"
#include "RHI.h"
#include "RenderResource.h"
#include "ShaderParameters.h"
#include "RendererInterface.h"
#include "Shader.h"
#include "SceneUtils.h"
#include "GlobalShader.h"
#include "DeferredShadingRenderer.h"
#include "ScenePrivate.h"
#include "DistanceFieldLightingShared.h"
#include "DistanceFieldAmbientOcclusion.h"
float GAOMaxObjectBoundingRadius = 50000;
FAutoConsoleVariableRef CVarAOMaxObjectBoundingRadius(
TEXT("r.AOMaxObjectBoundingRadius"),
GAOMaxObjectBoundingRadius,
TEXT("Objects larger than this will not contribute to AO calculations, to improve performance."),
ECVF_RenderThreadSafe
);
int32 GAOLogObjectBufferReallocation = 0;
FAutoConsoleVariableRef CVarAOLogObjectBufferReallocation(
TEXT("r.AOLogObjectBufferReallocation"),
GAOLogObjectBufferReallocation,
TEXT(""),
ECVF_RenderThreadSafe
);
// Must match equivalent shader defines
int32 FDistanceFieldObjectBuffers::ObjectDataStride = 18;
int32 FDistanceFieldCulledObjectBuffers::ObjectDataStride = 16;
int32 FDistanceFieldCulledObjectBuffers::ObjectBoxBoundsStride = 5;
// In float4's. Must match corresponding usf definition
int32 UploadObjectDataStride = 1 + FDistanceFieldObjectBuffers::ObjectDataStride;
class FDistanceFieldUploadDataResource : public FRenderResource
{
public:
FCPUUpdatedBuffer UploadData;
FDistanceFieldUploadDataResource()
{
// PS4 volatile only supports 8Mb, switch to volatile once that is fixed.
UploadData.bVolatile = false;
UploadData.Format = PF_A32B32G32R32F;
UploadData.Stride = UploadObjectDataStride;
}
virtual void InitDynamicRHI() override
{
UploadData.Initialize();
}
virtual void ReleaseDynamicRHI() override
{
UploadData.Release();
}
};
TGlobalResource<FDistanceFieldUploadDataResource> GDistanceFieldUploadData;
class FDistanceFieldUploadIndicesResource : public FRenderResource
{
public:
FCPUUpdatedBuffer UploadIndices;
FDistanceFieldUploadIndicesResource()
{
// PS4 volatile only supports 8Mb, switch to volatile once that is fixed.
UploadIndices.bVolatile = false;
UploadIndices.Format = PF_R32_UINT;
UploadIndices.Stride = 1;
}
virtual void InitDynamicRHI() override
{
UploadIndices.Initialize();
}
virtual void ReleaseDynamicRHI() override
{
UploadIndices.Release();
}
};
TGlobalResource<FDistanceFieldUploadIndicesResource> GDistanceFieldUploadIndices;
class FDistanceFieldRemoveIndicesResource : public FRenderResource
{
public:
FCPUUpdatedBuffer RemoveIndices;
FDistanceFieldRemoveIndicesResource()
{
RemoveIndices.Format = PF_R32G32B32A32_UINT;
RemoveIndices.Stride = 1;
}
virtual void InitDynamicRHI() override
{
RemoveIndices.Initialize();
}
virtual void ReleaseDynamicRHI() override
{
RemoveIndices.Release();
}
};
TGlobalResource<FDistanceFieldRemoveIndicesResource> GDistanceFieldRemoveIndices;
const uint32 UpdateObjectsGroupSize = 64;
class FUploadObjectsToBufferCS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FUploadObjectsToBufferCS,Global)
public:
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment);
OutEnvironment.SetDefine(TEXT("UPDATEOBJECTS_THREADGROUP_SIZE"), UpdateObjectsGroupSize);
}
FUploadObjectsToBufferCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
NumUploadOperations.Bind(Initializer.ParameterMap, TEXT("NumUploadOperations"));
UploadOperationIndices.Bind(Initializer.ParameterMap, TEXT("UploadOperationIndices"));
UploadOperationData.Bind(Initializer.ParameterMap, TEXT("UploadOperationData"));
ObjectBufferParameters.Bind(Initializer.ParameterMap);
}
FUploadObjectsToBufferCS()
{
}
void SetParameters(FRHICommandList& RHICmdList, const FScene* Scene, uint32 NumUploadOperationsValue, FShaderResourceViewRHIParamRef InUploadOperationIndices, FShaderResourceViewRHIParamRef InUploadOperationData)
{
FComputeShaderRHIParamRef ShaderRHI = GetComputeShader();
SetShaderValue(RHICmdList, ShaderRHI, NumUploadOperations, NumUploadOperationsValue);
SetSRVParameter(RHICmdList, ShaderRHI, UploadOperationIndices, InUploadOperationIndices);
SetSRVParameter(RHICmdList, ShaderRHI, UploadOperationData, InUploadOperationData);
ObjectBufferParameters.Set(RHICmdList, ShaderRHI, *(Scene->DistanceFieldSceneData.ObjectBuffers), Scene->DistanceFieldSceneData.NumObjectsInBuffer, true);
}
void UnsetParameters(FRHICommandList& RHICmdList, const FScene* Scene)
{
ObjectBufferParameters.UnsetParameters(RHICmdList, GetComputeShader(), *(Scene->DistanceFieldSceneData.ObjectBuffers), true);
const FDistanceFieldObjectBuffers& ObjectBuffers = *(Scene->DistanceFieldSceneData.ObjectBuffers);
FUnorderedAccessViewRHIParamRef OutUAVs[2];
OutUAVs[0] = ObjectBuffers.Bounds.UAV;
OutUAVs[1] = ObjectBuffers.Data.UAV;
RHICmdList.TransitionResources(EResourceTransitionAccess::EReadable, EResourceTransitionPipeline::EComputeToCompute, OutUAVs, ARRAY_COUNT(OutUAVs));
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << NumUploadOperations;
Ar << UploadOperationIndices;
Ar << UploadOperationData;
Ar << ObjectBufferParameters;
return bShaderHasOutdatedParameters;
}
private:
FShaderParameter NumUploadOperations;
FShaderResourceParameter UploadOperationIndices;
FShaderResourceParameter UploadOperationData;
FDistanceFieldObjectBufferParameters ObjectBufferParameters;
};
IMPLEMENT_SHADER_TYPE(,FUploadObjectsToBufferCS,TEXT("/Engine/Private/DistanceFieldObjectCulling.usf"),TEXT("UploadObjectsToBufferCS"),SF_Compute);
class FCopyObjectBufferCS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FCopyObjectBufferCS,Global)
public:
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment);
OutEnvironment.SetDefine(TEXT("UPDATEOBJECTS_THREADGROUP_SIZE"), UpdateObjectsGroupSize);
}
FCopyObjectBufferCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
CopyObjectBounds.Bind(Initializer.ParameterMap, TEXT("CopyObjectBounds"));
CopyObjectData.Bind(Initializer.ParameterMap, TEXT("CopyObjectData"));
ObjectBufferParameters.Bind(Initializer.ParameterMap);
}
FCopyObjectBufferCS()
{
}
void SetParameters(FRHICommandList& RHICmdList, FDistanceFieldObjectBuffers& ObjectBuffersSource, FDistanceFieldObjectBuffers& ObjectBuffersDest, int32 NumObjectsValue)
{
FComputeShaderRHIParamRef ShaderRHI = GetComputeShader();
FUnorderedAccessViewRHIParamRef OutUAVs[2];
OutUAVs[0] = ObjectBuffersDest.Bounds.UAV;
OutUAVs[1] = ObjectBuffersDest.Data.UAV;
RHICmdList.TransitionResources(EResourceTransitionAccess::ERWBarrier, EResourceTransitionPipeline::EComputeToCompute, OutUAVs, ARRAY_COUNT(OutUAVs));
CopyObjectBounds.SetBuffer(RHICmdList, ShaderRHI, ObjectBuffersDest.Bounds);
CopyObjectData.SetBuffer(RHICmdList, ShaderRHI, ObjectBuffersDest.Data);
ObjectBufferParameters.Set(RHICmdList, ShaderRHI, ObjectBuffersSource, NumObjectsValue);
}
void UnsetParameters(FRHICommandList& RHICmdList, FDistanceFieldObjectBuffers& ObjectBuffersDest)
{
ObjectBufferParameters.UnsetParameters(RHICmdList, GetComputeShader(), ObjectBuffersDest);
CopyObjectBounds.UnsetUAV(RHICmdList, GetComputeShader());
CopyObjectData.UnsetUAV(RHICmdList, GetComputeShader());
FUnorderedAccessViewRHIParamRef OutUAVs[2];
OutUAVs[0] = ObjectBuffersDest.Bounds.UAV;
OutUAVs[1] = ObjectBuffersDest.Data.UAV;
RHICmdList.TransitionResources(EResourceTransitionAccess::EReadable, EResourceTransitionPipeline::EComputeToCompute, OutUAVs, ARRAY_COUNT(OutUAVs));
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << CopyObjectBounds;
Ar << CopyObjectData;
Ar << ObjectBufferParameters;
return bShaderHasOutdatedParameters;
}
private:
FRWShaderParameter CopyObjectBounds;
FRWShaderParameter CopyObjectData;
FDistanceFieldObjectBufferParameters ObjectBufferParameters;
};
IMPLEMENT_SHADER_TYPE(,FCopyObjectBufferCS,TEXT("/Engine/Private/DistanceFieldObjectCulling.usf"),TEXT("CopyObjectBufferCS"),SF_Compute);
class FCopySurfelBufferCS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FCopySurfelBufferCS,Global)
public:
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldGI(Platform);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment);
OutEnvironment.SetDefine(TEXT("UPDATEOBJECTS_THREADGROUP_SIZE"), UpdateObjectsGroupSize);
}
FCopySurfelBufferCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
CopyInterpolatedVertexData.Bind(Initializer.ParameterMap, TEXT("CopyInterpolatedVertexData"));
CopySurfelData.Bind(Initializer.ParameterMap, TEXT("CopySurfelData"));
SurfelBufferParameters.Bind(Initializer.ParameterMap);
NumSurfels.Bind(Initializer.ParameterMap, TEXT("NumSurfels"));
}
FCopySurfelBufferCS()
{
}
void SetParameters(FRHICommandList& RHICmdList, const FSurfelBuffers& SurfelBuffersSource, const FInstancedSurfelBuffers& InstancedSurfelBuffersSource, FSurfelBuffers& SurfelBuffersDest, int32 NumSurfelsValue)
{
FComputeShaderRHIParamRef ShaderRHI = GetComputeShader();
FUnorderedAccessViewRHIParamRef OutUAVs[2];
OutUAVs[0] = SurfelBuffersDest.InterpolatedVertexData.UAV;
OutUAVs[1] = SurfelBuffersDest.Surfels.UAV;
RHICmdList.TransitionResources(EResourceTransitionAccess::ERWBarrier, EResourceTransitionPipeline::EComputeToCompute, OutUAVs, ARRAY_COUNT(OutUAVs));
CopyInterpolatedVertexData.SetBuffer(RHICmdList, ShaderRHI, SurfelBuffersDest.InterpolatedVertexData);
CopySurfelData.SetBuffer(RHICmdList, ShaderRHI, SurfelBuffersDest.Surfels);
SurfelBufferParameters.Set(RHICmdList, ShaderRHI, SurfelBuffersSource, InstancedSurfelBuffersSource);
SetShaderValue(RHICmdList, ShaderRHI, NumSurfels, NumSurfelsValue);
}
void UnsetParameters(FRHICommandList& RHICmdList, FSurfelBuffers& SurfelBuffersDest)
{
SurfelBufferParameters.UnsetParameters(RHICmdList, GetComputeShader());
CopyInterpolatedVertexData.UnsetUAV(RHICmdList, GetComputeShader());
CopySurfelData.UnsetUAV(RHICmdList, GetComputeShader());
FUnorderedAccessViewRHIParamRef OutUAVs[2];
OutUAVs[0] = SurfelBuffersDest.InterpolatedVertexData.UAV;
OutUAVs[1] = SurfelBuffersDest.Surfels.UAV;
RHICmdList.TransitionResources(EResourceTransitionAccess::EReadable, EResourceTransitionPipeline::EComputeToCompute, OutUAVs, ARRAY_COUNT(OutUAVs));
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << CopyInterpolatedVertexData;
Ar << CopySurfelData;
Ar << SurfelBufferParameters;
Ar << NumSurfels;
return bShaderHasOutdatedParameters;
}
private:
FRWShaderParameter CopyInterpolatedVertexData;
FRWShaderParameter CopySurfelData;
FSurfelBufferParameters SurfelBufferParameters;
FShaderParameter NumSurfels;
};
IMPLEMENT_SHADER_TYPE(,FCopySurfelBufferCS,TEXT("/Engine/Private/SurfelTree.usf"),TEXT("CopySurfelBufferCS"),SF_Compute);
class FCopyVPLFluxBufferCS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FCopyVPLFluxBufferCS,Global)
public:
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment);
OutEnvironment.SetDefine(TEXT("UPDATEOBJECTS_THREADGROUP_SIZE"), UpdateObjectsGroupSize);
}
FCopyVPLFluxBufferCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
CopyVPLFlux.Bind(Initializer.ParameterMap, TEXT("CopyVPLFlux"));
SurfelBufferParameters.Bind(Initializer.ParameterMap);
NumSurfels.Bind(Initializer.ParameterMap, TEXT("NumSurfels"));
}
FCopyVPLFluxBufferCS()
{
}
void SetParameters(FRHICommandList& RHICmdList, const FSurfelBuffers& SurfelBuffersSource, const FInstancedSurfelBuffers& InstancedSurfelBuffersSource, FInstancedSurfelBuffers& InstancedSurfelBuffersDest, int32 NumSurfelsValue)
{
FComputeShaderRHIParamRef ShaderRHI = GetComputeShader();
RHICmdList.TransitionResource(EResourceTransitionAccess::ERWBarrier, EResourceTransitionPipeline::EComputeToCompute, InstancedSurfelBuffersDest.VPLFlux.UAV);
CopyVPLFlux.SetBuffer(RHICmdList, ShaderRHI, InstancedSurfelBuffersDest.VPLFlux);
SurfelBufferParameters.Set(RHICmdList, ShaderRHI, SurfelBuffersSource, InstancedSurfelBuffersSource);
SetShaderValue(RHICmdList, ShaderRHI, NumSurfels, NumSurfelsValue);
}
void UnsetParameters(FRHICommandList& RHICmdList, FInstancedSurfelBuffers& InstancedSurfelBuffersDest)
{
SurfelBufferParameters.UnsetParameters(RHICmdList, GetComputeShader());
CopyVPLFlux.UnsetUAV(RHICmdList, GetComputeShader());
RHICmdList.TransitionResource(EResourceTransitionAccess::EReadable, EResourceTransitionPipeline::EComputeToCompute, InstancedSurfelBuffersDest.VPLFlux.UAV);
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << CopyVPLFlux;
Ar << SurfelBufferParameters;
Ar << NumSurfels;
return bShaderHasOutdatedParameters;
}
private:
FRWShaderParameter CopyVPLFlux;
FSurfelBufferParameters SurfelBufferParameters;
FShaderParameter NumSurfels;
};
IMPLEMENT_SHADER_TYPE(,FCopyVPLFluxBufferCS,TEXT("/Engine/Private/SurfelTree.usf"),TEXT("CopyVPLFluxBufferCS"),SF_Compute);
template<bool bRemoveFromSameBuffer>
class TRemoveObjectsFromBufferCS : public FGlobalShader
{
DECLARE_SHADER_TYPE(TRemoveObjectsFromBufferCS,Global)
public:
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment);
OutEnvironment.SetDefine(TEXT("UPDATEOBJECTS_THREADGROUP_SIZE"), UpdateObjectsGroupSize);
OutEnvironment.SetDefine(TEXT("REMOVE_FROM_SAME_BUFFER"), bRemoveFromSameBuffer);
}
TRemoveObjectsFromBufferCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
NumRemoveOperations.Bind(Initializer.ParameterMap, TEXT("NumRemoveOperations"));
RemoveOperationIndices.Bind(Initializer.ParameterMap, TEXT("RemoveOperationIndices"));
ObjectBufferParameters.Bind(Initializer.ParameterMap);
ObjectBounds2.Bind(Initializer.ParameterMap, TEXT("ObjectBounds2"));
ObjectData2.Bind(Initializer.ParameterMap, TEXT("ObjectData2"));
}
TRemoveObjectsFromBufferCS()
{
}
void SetParameters(
FRHICommandList& RHICmdList,
const FScene* Scene,
uint32 NumRemoveOperationsValue,
FShaderResourceViewRHIParamRef InRemoveOperationIndices,
FShaderResourceViewRHIParamRef InObjectBounds2,
FShaderResourceViewRHIParamRef InObjectData2)
{
FComputeShaderRHIParamRef ShaderRHI = GetComputeShader();
SetShaderValue(RHICmdList, ShaderRHI, NumRemoveOperations, NumRemoveOperationsValue);
SetSRVParameter(RHICmdList, ShaderRHI, RemoveOperationIndices, InRemoveOperationIndices);
ObjectBufferParameters.Set(RHICmdList, ShaderRHI, *(Scene->DistanceFieldSceneData.ObjectBuffers), Scene->DistanceFieldSceneData.NumObjectsInBuffer, true);
SetSRVParameter(RHICmdList, ShaderRHI, ObjectBounds2, InObjectBounds2);
SetSRVParameter(RHICmdList, ShaderRHI, ObjectData2, InObjectData2);
}
void UnsetParameters(FRHICommandList& RHICmdList, const FScene* Scene)
{
ObjectBufferParameters.UnsetParameters(RHICmdList, GetComputeShader(), *(Scene->DistanceFieldSceneData.ObjectBuffers), true);
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << NumRemoveOperations;
Ar << RemoveOperationIndices;
Ar << ObjectBufferParameters;
Ar << ObjectBounds2;
Ar << ObjectData2;
return bShaderHasOutdatedParameters;
}
private:
FShaderParameter NumRemoveOperations;
FShaderResourceParameter RemoveOperationIndices;
FDistanceFieldObjectBufferParameters ObjectBufferParameters;
FShaderResourceParameter ObjectBounds2;
FShaderResourceParameter ObjectData2;
};
IMPLEMENT_SHADER_TYPE(template<>,TRemoveObjectsFromBufferCS<true>,TEXT("/Engine/Private/DistanceFieldObjectCulling.usf"),TEXT("RemoveObjectsFromBufferCS"),SF_Compute);
IMPLEMENT_SHADER_TYPE(template<>,TRemoveObjectsFromBufferCS<false>,TEXT("/Engine/Private/DistanceFieldObjectCulling.usf"),TEXT("RemoveObjectsFromBufferCS"),SF_Compute);
void FSurfelBufferAllocator::RemovePrimitive(const FPrimitiveSceneInfo* Primitive)
{
FPrimitiveSurfelAllocation Allocation;
if (Allocations.RemoveAndCopyValue(Primitive, Allocation))
{
bool bMergedWithExisting = false;
FPrimitiveSurfelFreeEntry FreeEntry(Allocation.Offset, Allocation.GetTotalNumSurfels());
// Note: only does one merge
//@todo - keep free list sorted then can binary search
for (int32 FreeIndex = 0; FreeIndex < FreeList.Num(); FreeIndex++)
{
if (FreeList[FreeIndex].Offset == FreeEntry.Offset + FreeEntry.NumSurfels)
{
FreeList[FreeIndex].Offset = FreeEntry.Offset;
FreeList[FreeIndex].NumSurfels += FreeEntry.NumSurfels;
bMergedWithExisting = true;
break;
}
else if (FreeList[FreeIndex].Offset + FreeList[FreeIndex].NumSurfels == FreeEntry.Offset)
{
FreeList[FreeIndex].NumSurfels += FreeEntry.NumSurfels;
bMergedWithExisting = true;
break;
}
}
if (!bMergedWithExisting)
{
FreeList.Add(FreeEntry);
}
}
}
void FSurfelBufferAllocator::AddPrimitive(const FPrimitiveSceneInfo* PrimitiveSceneInfo, int32 PrimitiveLOD0Surfels, int32 PrimitiveNumSurfels, int32 NumInstances)
{
int32 BestFreeAllocationIndex = -1;
for (int32 FreeIndex = 0; FreeIndex < FreeList.Num(); FreeIndex++)
{
const FPrimitiveSurfelFreeEntry& CurrentFreeEntry = FreeList[FreeIndex];
if (CurrentFreeEntry.NumSurfels >= PrimitiveNumSurfels * NumInstances
&& (BestFreeAllocationIndex == -1
|| CurrentFreeEntry.NumSurfels < FreeList[BestFreeAllocationIndex].NumSurfels))
{
BestFreeAllocationIndex = FreeIndex;
}
}
if (BestFreeAllocationIndex != -1)
{
FPrimitiveSurfelFreeEntry FreeEntry = FreeList[BestFreeAllocationIndex];
if (FreeEntry.NumSurfels == PrimitiveNumSurfels * NumInstances)
{
// Existing allocation matches exactly, remove it from the free list
FreeList.RemoveAtSwap(BestFreeAllocationIndex);
}
else
{
// Replace with the remaining free range
FreeList[BestFreeAllocationIndex] = FPrimitiveSurfelFreeEntry(FreeEntry.Offset + PrimitiveNumSurfels * NumInstances, FreeEntry.NumSurfels - PrimitiveNumSurfels * NumInstances);
}
Allocations.Add(PrimitiveSceneInfo, FPrimitiveSurfelAllocation(FreeEntry.Offset, PrimitiveLOD0Surfels, PrimitiveNumSurfels, NumInstances));
}
else
{
// Add a new allocation to the end of the buffer
Allocations.Add(PrimitiveSceneInfo, FPrimitiveSurfelAllocation(NumSurfelsInBuffer, PrimitiveLOD0Surfels, PrimitiveNumSurfels, NumInstances));
NumSurfelsInBuffer += PrimitiveNumSurfels * NumInstances;
}
}
void UpdateGlobalDistanceFieldObjectRemoves(FRHICommandListImmediate& RHICmdList, FScene* Scene)
{
FDistanceFieldSceneData& DistanceFieldSceneData = Scene->DistanceFieldSceneData;
TArray<FIntRect> RemoveObjectIndices;
FDistanceFieldObjectBuffers* TemporaryCopySourceBuffers = NULL;
if (DistanceFieldSceneData.PendingRemoveOperations.Num() > 0)
{
TArray<int32, SceneRenderingAllocator> PendingRemoveOperations;
for (int32 RemoveIndex = 0; RemoveIndex < DistanceFieldSceneData.PendingRemoveOperations.Num(); RemoveIndex++)
{
// Can't dereference the primitive here, it has already been deleted
const FPrimitiveSceneInfo* Primitive = DistanceFieldSceneData.PendingRemoveOperations[RemoveIndex].Primitive;
DistanceFieldSceneData.SurfelAllocations.RemovePrimitive(Primitive);
DistanceFieldSceneData.InstancedSurfelAllocations.RemovePrimitive(Primitive);
const TArray<int32, TInlineAllocator<1>>& DistanceFieldInstanceIndices = DistanceFieldSceneData.PendingRemoveOperations[RemoveIndex].DistanceFieldInstanceIndices;
for (int32 RemoveInstanceIndex = 0; RemoveInstanceIndex < DistanceFieldInstanceIndices.Num(); RemoveInstanceIndex++)
{
const int32 InstanceIndex = DistanceFieldInstanceIndices[RemoveInstanceIndex];
// InstanceIndex will be -1 with zero scale meshes
if (InstanceIndex >= 0)
{
FGlobalDFCacheType CacheType = DistanceFieldSceneData.PendingRemoveOperations[RemoveIndex].bOftenMoving ? GDF_Full : GDF_MostlyStatic;
DistanceFieldSceneData.PrimitiveModifiedBounds[CacheType].Add(DistanceFieldSceneData.PrimitiveInstanceMapping[InstanceIndex].BoundingSphere);
PendingRemoveOperations.Add(InstanceIndex);
}
}
}
DistanceFieldSceneData.PendingRemoveOperations.Reset();
if (PendingRemoveOperations.Num() > 0)
{
check(DistanceFieldSceneData.NumObjectsInBuffer >= PendingRemoveOperations.Num());
// Sort from smallest to largest
PendingRemoveOperations.Sort();
// We have multiple remove requests enqueued in PendingRemoveOperations, can only use the RemoveAtSwap version when there won't be collisions
const bool bUseRemoveAtSwap = PendingRemoveOperations.Last() < DistanceFieldSceneData.NumObjectsInBuffer - PendingRemoveOperations.Num();
if (bUseRemoveAtSwap)
{
// Remove everything in parallel in the same buffer with a RemoveAtSwap algorithm
for (int32 RemovePrimitiveIndex = 0; RemovePrimitiveIndex < PendingRemoveOperations.Num(); RemovePrimitiveIndex++)
{
DistanceFieldSceneData.NumObjectsInBuffer--;
const int32 RemoveIndex = PendingRemoveOperations[RemovePrimitiveIndex];
const int32 MoveFromIndex = DistanceFieldSceneData.NumObjectsInBuffer;
check(RemoveIndex != MoveFromIndex);
// Queue a compute shader move
RemoveObjectIndices.Add(FIntRect(RemoveIndex, MoveFromIndex, 0, 0));
// Fixup indices of the primitive that is being moved
FPrimitiveAndInstance& PrimitiveAndInstanceBeingMoved = DistanceFieldSceneData.PrimitiveInstanceMapping[MoveFromIndex];
check(PrimitiveAndInstanceBeingMoved.Primitive && PrimitiveAndInstanceBeingMoved.Primitive->DistanceFieldInstanceIndices.Num() > 0);
PrimitiveAndInstanceBeingMoved.Primitive->DistanceFieldInstanceIndices[PrimitiveAndInstanceBeingMoved.InstanceIndex] = RemoveIndex;
DistanceFieldSceneData.PrimitiveInstanceMapping.RemoveAtSwap(RemoveIndex);
}
}
else
{
const double StartTime = FPlatformTime::Seconds();
// Have to copy the object data to allow parallel removing
TemporaryCopySourceBuffers = DistanceFieldSceneData.ObjectBuffers;
DistanceFieldSceneData.ObjectBuffers = new FDistanceFieldObjectBuffers();
DistanceFieldSceneData.ObjectBuffers->MaxObjects = TemporaryCopySourceBuffers->MaxObjects;
DistanceFieldSceneData.ObjectBuffers->Initialize();
TArray<FPrimitiveAndInstance> OriginalPrimitiveInstanceMapping = DistanceFieldSceneData.PrimitiveInstanceMapping;
DistanceFieldSceneData.PrimitiveInstanceMapping.Reset();
const int32 NumDestObjects = DistanceFieldSceneData.NumObjectsInBuffer - PendingRemoveOperations.Num();
int32 SourceIndex = 0;
int32 NextPendingRemoveIndex = 0;
for (int32 DestinationIndex = 0; DestinationIndex < NumDestObjects; DestinationIndex++)
{
while (NextPendingRemoveIndex < PendingRemoveOperations.Num()
&& PendingRemoveOperations[NextPendingRemoveIndex] == SourceIndex)
{
NextPendingRemoveIndex++;
SourceIndex++;
}
// Queue a compute shader move
RemoveObjectIndices.Add(FIntRect(DestinationIndex, SourceIndex, 0, 0));
// Fixup indices of the primitive that is being moved
FPrimitiveAndInstance& PrimitiveAndInstanceBeingMoved = OriginalPrimitiveInstanceMapping[SourceIndex];
check(PrimitiveAndInstanceBeingMoved.Primitive && PrimitiveAndInstanceBeingMoved.Primitive->DistanceFieldInstanceIndices.Num() > 0);
PrimitiveAndInstanceBeingMoved.Primitive->DistanceFieldInstanceIndices[PrimitiveAndInstanceBeingMoved.InstanceIndex] = DestinationIndex;
check(DistanceFieldSceneData.PrimitiveInstanceMapping.Num() == DestinationIndex);
DistanceFieldSceneData.PrimitiveInstanceMapping.Add(PrimitiveAndInstanceBeingMoved);
SourceIndex++;
}
DistanceFieldSceneData.NumObjectsInBuffer = NumDestObjects;
if (GAOLogObjectBufferReallocation)
{
const float ElapsedTime = (float)(FPlatformTime::Seconds() - StartTime);
UE_LOG(LogDistanceField,Warning,TEXT("Global object buffer realloc %.3fs"), ElapsedTime);
}
/*
// Have to remove one at a time while any entries to remove are at the end of the buffer
DistanceFieldSceneData.NumObjectsInBuffer--;
const int32 RemoveIndex = DistanceFieldSceneData.PendingRemoveOperations[ParallelConflictIndex];
const int32 MoveFromIndex = DistanceFieldSceneData.NumObjectsInBuffer;
if (RemoveIndex != MoveFromIndex)
{
// Queue a compute shader move
RemoveObjectIndices.Add(FIntRect(RemoveIndex, MoveFromIndex, 0, 0));
// Fixup indices of the primitive that is being moved
FPrimitiveAndInstance& PrimitiveAndInstanceBeingMoved = DistanceFieldSceneData.PrimitiveInstanceMapping[MoveFromIndex];
check(PrimitiveAndInstanceBeingMoved.Primitive && PrimitiveAndInstanceBeingMoved.Primitive->DistanceFieldInstanceIndices.Num() > 0);
PrimitiveAndInstanceBeingMoved.Primitive->DistanceFieldInstanceIndices[PrimitiveAndInstanceBeingMoved.InstanceIndex] = RemoveIndex;
}
DistanceFieldSceneData.PrimitiveInstanceMapping.RemoveAtSwap(RemoveIndex);
DistanceFieldSceneData.PendingRemoveOperations.RemoveAtSwap(ParallelConflictIndex);
*/
}
PendingRemoveOperations.Reset();
if (RemoveObjectIndices.Num() > 0)
{
if (RemoveObjectIndices.Num() > GDistanceFieldRemoveIndices.RemoveIndices.MaxElements)
{
GDistanceFieldRemoveIndices.RemoveIndices.MaxElements = RemoveObjectIndices.Num() * 5 / 4;
GDistanceFieldRemoveIndices.RemoveIndices.Release();
GDistanceFieldRemoveIndices.RemoveIndices.Initialize();
}
void* LockedBuffer = RHILockVertexBuffer(GDistanceFieldRemoveIndices.RemoveIndices.Buffer, 0, GDistanceFieldRemoveIndices.RemoveIndices.Buffer->GetSize(), RLM_WriteOnly);
const uint32 MemcpySize = RemoveObjectIndices.GetTypeSize() * RemoveObjectIndices.Num();
check(GDistanceFieldRemoveIndices.RemoveIndices.Buffer->GetSize() >= MemcpySize);
FPlatformMemory::Memcpy(LockedBuffer, RemoveObjectIndices.GetData(), MemcpySize);
RHIUnlockVertexBuffer(GDistanceFieldRemoveIndices.RemoveIndices.Buffer);
if (bUseRemoveAtSwap)
{
check(!TemporaryCopySourceBuffers);
TShaderMapRef<TRemoveObjectsFromBufferCS<true> > ComputeShader(GetGlobalShaderMap(Scene->GetFeatureLevel()));
RHICmdList.SetComputeShader(ComputeShader->GetComputeShader());
ComputeShader->SetParameters(RHICmdList, Scene, RemoveObjectIndices.Num(), GDistanceFieldRemoveIndices.RemoveIndices.BufferSRV, NULL, NULL);
DispatchComputeShader(RHICmdList, *ComputeShader, FMath::DivideAndRoundUp<uint32>(RemoveObjectIndices.Num(), UpdateObjectsGroupSize), 1, 1);
ComputeShader->UnsetParameters(RHICmdList, Scene);
}
else
{
check(TemporaryCopySourceBuffers);
TShaderMapRef<TRemoveObjectsFromBufferCS<false> > ComputeShader(GetGlobalShaderMap(Scene->GetFeatureLevel()));
RHICmdList.SetComputeShader(ComputeShader->GetComputeShader());
ComputeShader->SetParameters(RHICmdList, Scene, RemoveObjectIndices.Num(), GDistanceFieldRemoveIndices.RemoveIndices.BufferSRV, TemporaryCopySourceBuffers->Bounds.SRV, TemporaryCopySourceBuffers->Data.SRV);
DispatchComputeShader(RHICmdList, *ComputeShader, FMath::DivideAndRoundUp<uint32>(RemoveObjectIndices.Num(), UpdateObjectsGroupSize), 1, 1);
ComputeShader->UnsetParameters(RHICmdList, Scene);
}
}
// make sure to delete the temporary buffer (even if RemoveObjectIndices is empty)
if (TemporaryCopySourceBuffers)
{
check(bUseRemoveAtSwap == false);
TemporaryCopySourceBuffers->Release();
delete TemporaryCopySourceBuffers;
TemporaryCopySourceBuffers = nullptr;
}
}
}
}
/** Gathers the information needed to represent a single object's distance field and appends it to the upload buffers. */
void ProcessPrimitiveUpdate(
bool bIsAddOperation,
FRHICommandListImmediate& RHICmdList,
FSceneRenderer& SceneRenderer,
FPrimitiveSceneInfo* PrimitiveSceneInfo,
int32 OriginalNumObjects,
FVector InvTextureDim,
bool bPrepareForDistanceFieldGI,
TArray<FMatrix>& ObjectLocalToWorldTransforms,
TArray<uint32>& UploadObjectIndices,
TArray<FVector4>& UploadObjectData)
{
FScene* Scene = SceneRenderer.Scene;
FDistanceFieldSceneData& DistanceFieldSceneData = Scene->DistanceFieldSceneData;
ObjectLocalToWorldTransforms.Reset();
FBox LocalVolumeBounds;
FVector2D DistanceMinMax;
FIntVector BlockMin;
FIntVector BlockSize;
bool bBuiltAsIfTwoSided;
bool bMeshWasPlane;
float SelfShadowBias;
PrimitiveSceneInfo->Proxy->GetDistancefieldAtlasData(LocalVolumeBounds, DistanceMinMax, BlockMin, BlockSize, bBuiltAsIfTwoSided, bMeshWasPlane, SelfShadowBias, ObjectLocalToWorldTransforms);
if (BlockMin.X >= 0
&& BlockMin.Y >= 0
&& BlockMin.Z >= 0
&& ObjectLocalToWorldTransforms.Num() > 0)
{
const float BoundingRadius = PrimitiveSceneInfo->Proxy->GetBounds().SphereRadius;
const FGlobalDFCacheType CacheType = PrimitiveSceneInfo->Proxy->IsOftenMoving() ? GDF_Full : GDF_MostlyStatic;
// Proxy bounds are only useful if single instance
if (ObjectLocalToWorldTransforms.Num() > 1 || BoundingRadius < GAOMaxObjectBoundingRadius)
{
FPrimitiveSurfelAllocation Allocation;
FPrimitiveSurfelAllocation InstancedAllocation;
if (bPrepareForDistanceFieldGI)
{
const FPrimitiveSurfelAllocation* AllocationPtr = Scene->DistanceFieldSceneData.SurfelAllocations.FindAllocation(PrimitiveSceneInfo);
const FPrimitiveSurfelAllocation* InstancedAllocationPtr = Scene->DistanceFieldSceneData.InstancedSurfelAllocations.FindAllocation(PrimitiveSceneInfo);
if (AllocationPtr)
{
checkSlow(InstancedAllocationPtr && InstancedAllocationPtr->NumInstances == ObjectLocalToWorldTransforms.Num());
Allocation = *AllocationPtr;
InstancedAllocation = *InstancedAllocationPtr;
extern void GenerateSurfelRepresentation(FRHICommandListImmediate& RHICmdList, FSceneRenderer& Renderer, FViewInfo& View, FPrimitiveSceneInfo* PrimitiveSceneInfo, const FMatrix& Instance0Transform, FPrimitiveSurfelAllocation& Allocation);
// @todo - support surfel generation without a view
GenerateSurfelRepresentation(RHICmdList, SceneRenderer, SceneRenderer.Views[0], PrimitiveSceneInfo, ObjectLocalToWorldTransforms[0], Allocation);
if (Allocation.NumSurfels == 0)
{
InstancedAllocation.NumSurfels = 0;
InstancedAllocation.NumInstances = 0;
InstancedAllocation.NumLOD0 = 0;
}
}
}
if (bIsAddOperation)
{
PrimitiveSceneInfo->DistanceFieldInstanceIndices.Empty(ObjectLocalToWorldTransforms.Num());
PrimitiveSceneInfo->DistanceFieldInstanceIndices.AddZeroed(ObjectLocalToWorldTransforms.Num());
}
for (int32 TransformIndex = 0; TransformIndex < ObjectLocalToWorldTransforms.Num(); TransformIndex++)
{
FMatrix LocalToWorld = ObjectLocalToWorldTransforms[TransformIndex];
const float MaxScale = LocalToWorld.GetMaximumAxisScale();
// Skip degenerate primitives
if (MaxScale > 0)
{
uint32 UploadIndex;
if (bIsAddOperation)
{
UploadIndex = OriginalNumObjects + UploadObjectIndices.Num();
DistanceFieldSceneData.NumObjectsInBuffer++;
}
else
{
UploadIndex = PrimitiveSceneInfo->DistanceFieldInstanceIndices[TransformIndex];
}
UploadObjectIndices.Add(UploadIndex);
if (bMeshWasPlane)
{
FVector LocalScales = LocalToWorld.GetScaleVector();
FVector AbsLocalScales(FMath::Abs(LocalScales.X), FMath::Abs(LocalScales.Y), FMath::Abs(LocalScales.Z));
float MidScale = FMath::Min(AbsLocalScales.X, AbsLocalScales.Y);
float ScaleAdjust = FMath::Sign(LocalScales.Z) * MidScale / AbsLocalScales.Z;
// The mesh was determined to be a plane flat in Z during the build process, so we can change the Z scale
// Helps in cases with modular ground pieces with scales of (10, 10, 1) and some triangles just above Z=0
LocalToWorld.SetAxis(2, LocalToWorld.GetScaledAxis(EAxis::Z) * ScaleAdjust);
}
const FMatrix VolumeToWorld = FScaleMatrix(LocalVolumeBounds.GetExtent())
* FTranslationMatrix(LocalVolumeBounds.GetCenter())
* LocalToWorld;
const FVector4 ObjectBoundingSphere(VolumeToWorld.GetOrigin(), VolumeToWorld.GetScaleVector().Size());
UploadObjectData.Add(ObjectBoundingSphere);
const float MaxExtent = LocalVolumeBounds.GetExtent().GetMax();
const FMatrix UniformScaleVolumeToWorld = FScaleMatrix(MaxExtent)
* FTranslationMatrix(LocalVolumeBounds.GetCenter())
* LocalToWorld;
const FVector InvBlockSize(1.0f / BlockSize.X, 1.0f / BlockSize.Y, 1.0f / BlockSize.Z);
//float3 VolumeUV = (VolumePosition / LocalPositionExtent * .5f * UVScale + .5f * UVScale + UVAdd;
const FVector LocalPositionExtent = LocalVolumeBounds.GetExtent() / FVector(MaxExtent);
const FVector UVScale = FVector(BlockSize) * InvTextureDim;
const float VolumeScale = UniformScaleVolumeToWorld.GetMaximumAxisScale();
const FMatrix WorldToVolume = UniformScaleVolumeToWorld.Inverse();
// WorldToVolume
UploadObjectData.Add(*(FVector4*)&WorldToVolume.M[0]);
UploadObjectData.Add(*(FVector4*)&WorldToVolume.M[1]);
UploadObjectData.Add(*(FVector4*)&WorldToVolume.M[2]);
UploadObjectData.Add(*(FVector4*)&WorldToVolume.M[3]);
// Clamp to texel center by subtracting a half texel in the [-1,1] position space
// LocalPositionExtent
UploadObjectData.Add(FVector4(LocalPositionExtent - InvBlockSize, 0));
// UVScale, VolumeScale and sign gives bGeneratedAsTwoSided
const float WSign = bBuiltAsIfTwoSided ? -1 : 1;
UploadObjectData.Add(FVector4(FVector(BlockSize) * InvTextureDim * .5f / LocalPositionExtent, WSign * VolumeScale));
// UVAdd
UploadObjectData.Add(FVector4(FVector(BlockMin) * InvTextureDim + .5f * UVScale, SelfShadowBias));
// DistanceFieldMAD
// [0, 1] -> [MinVolumeDistance, MaxVolumeDistance]
UploadObjectData.Add(FVector4(DistanceMinMax.Y - DistanceMinMax.X, DistanceMinMax.X, 0, 0));
UploadObjectData.Add(*(FVector4*)&UniformScaleVolumeToWorld.M[0]);
UploadObjectData.Add(*(FVector4*)&UniformScaleVolumeToWorld.M[1]);
UploadObjectData.Add(*(FVector4*)&UniformScaleVolumeToWorld.M[2]);
UploadObjectData.Add(*(FVector4*)&LocalToWorld.M[0]);
UploadObjectData.Add(*(FVector4*)&LocalToWorld.M[1]);
UploadObjectData.Add(*(FVector4*)&LocalToWorld.M[2]);
UploadObjectData.Add(*(FVector4*)&LocalToWorld.M[3]);
UploadObjectData.Add(FVector4(Allocation.Offset, Allocation.NumLOD0, Allocation.NumSurfels, InstancedAllocation.Offset + InstancedAllocation.NumSurfels * TransformIndex));
UploadObjectData.Add(FVector4(LocalVolumeBounds.Min, 0));
// Box bounds
const float OftenMovingWSign = CacheType == GDF_Full ? 1.0f : -1.0f;
UploadObjectData.Add(FVector4(LocalVolumeBounds.Max, OftenMovingWSign));
checkSlow(UploadObjectData.Num() % UploadObjectDataStride == 0);
if (bIsAddOperation)
{
const int32 AddIndex = UploadIndex;
DistanceFieldSceneData.PrimitiveInstanceMapping.Add(FPrimitiveAndInstance(ObjectBoundingSphere, PrimitiveSceneInfo, TransformIndex));
PrimitiveSceneInfo->DistanceFieldInstanceIndices[TransformIndex] = AddIndex;
}
else
{
// InstanceIndex will be -1 with zero scale meshes
const int32 InstanceIndex = PrimitiveSceneInfo->DistanceFieldInstanceIndices[TransformIndex];
if (InstanceIndex >= 0)
{
// For an update transform we have to dirty the previous bounds and the new bounds, in case of large movement (teleport)
DistanceFieldSceneData.PrimitiveModifiedBounds[CacheType].Add(DistanceFieldSceneData.PrimitiveInstanceMapping[InstanceIndex].BoundingSphere);
DistanceFieldSceneData.PrimitiveInstanceMapping[InstanceIndex].BoundingSphere = ObjectBoundingSphere;
}
}
DistanceFieldSceneData.PrimitiveModifiedBounds[CacheType].Add(ObjectBoundingSphere);
extern int32 GAOLogGlobalDistanceFieldModifiedPrimitives;
if (GAOLogGlobalDistanceFieldModifiedPrimitives)
{
UE_LOG(LogDistanceField,Log,TEXT("Global Distance Field %s primitive %s %s %s bounding radius %.1f"), PrimitiveSceneInfo->Proxy->IsOftenMoving() ? TEXT("CACHED") : TEXT("Movable"), (bIsAddOperation ? TEXT("add") : TEXT("update")), *PrimitiveSceneInfo->Proxy->GetOwnerName().ToString(), *PrimitiveSceneInfo->Proxy->GetResourceName().ToString(), BoundingRadius);
}
}
else if (bIsAddOperation)
{
// Set to -1 for zero scale meshes
PrimitiveSceneInfo->DistanceFieldInstanceIndices[TransformIndex] = -1;
}
}
}
else
{
UE_LOG(LogDistanceField,Log,TEXT("Primitive %s %s excluded due to bounding radius %f"), *PrimitiveSceneInfo->Proxy->GetOwnerName().ToString(), *PrimitiveSceneInfo->Proxy->GetResourceName().ToString(), BoundingRadius);
}
}
}
void FDeferredShadingSceneRenderer::UpdateGlobalDistanceFieldObjectBuffers(FRHICommandListImmediate& RHICmdList)
{
FDistanceFieldSceneData& DistanceFieldSceneData = Scene->DistanceFieldSceneData;
if (GDistanceFieldVolumeTextureAtlas.VolumeTextureRHI
&& (DistanceFieldSceneData.HasPendingOperations() || DistanceFieldSceneData.AtlasGeneration != GDistanceFieldVolumeTextureAtlas.GetGeneration()))
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_UpdateObjectData);
SCOPED_DRAW_EVENT(RHICmdList, UpdateSceneObjectData);
if (!DistanceFieldSceneData.ObjectBuffers)
{
DistanceFieldSceneData.ObjectBuffers = new FDistanceFieldObjectBuffers();
}
if (!DistanceFieldSceneData.SurfelBuffers)
{
DistanceFieldSceneData.SurfelBuffers = new FSurfelBuffers();
}
if (!DistanceFieldSceneData.InstancedSurfelBuffers)
{
DistanceFieldSceneData.InstancedSurfelBuffers = new FInstancedSurfelBuffers();
}
if (DistanceFieldSceneData.AtlasGeneration != GDistanceFieldVolumeTextureAtlas.GetGeneration())
{
DistanceFieldSceneData.AtlasGeneration = GDistanceFieldVolumeTextureAtlas.GetGeneration();
for (int32 PrimitiveInstanceIndex = 0; PrimitiveInstanceIndex < DistanceFieldSceneData.PrimitiveInstanceMapping.Num(); PrimitiveInstanceIndex++)
{
FPrimitiveAndInstance& PrimitiveInstance = DistanceFieldSceneData.PrimitiveInstanceMapping[PrimitiveInstanceIndex];
// Queue an update of all primitives, since the atlas layout has changed
if (PrimitiveInstance.InstanceIndex == 0
&& !DistanceFieldSceneData.HasPendingRemovePrimitive(PrimitiveInstance.Primitive)
&& !DistanceFieldSceneData.PendingAddOperations.Contains(PrimitiveInstance.Primitive)
&& !DistanceFieldSceneData.PendingUpdateOperations.Contains(PrimitiveInstance.Primitive))
{
DistanceFieldSceneData.PendingUpdateOperations.Add(PrimitiveInstance.Primitive);
}
}
}
// Process removes before adds, as the adds will overwrite primitive allocation info in DistanceFieldSceneData.SurfelAllocations
UpdateGlobalDistanceFieldObjectRemoves(RHICmdList, Scene);
extern int32 GVPLMeshGlobalIllumination;
TArray<uint32> UploadObjectIndices;
TArray<FVector4> UploadObjectData;
const bool bPrepareForDistanceFieldGI = GVPLMeshGlobalIllumination && SupportsDistanceFieldGI(Scene->GetFeatureLevel(), Scene->GetShaderPlatform());
if (DistanceFieldSceneData.PendingAddOperations.Num() > 0 || DistanceFieldSceneData.PendingUpdateOperations.Num() > 0)
{
TArray<FMatrix> ObjectLocalToWorldTransforms;
const int32 NumUploadOperations = DistanceFieldSceneData.PendingAddOperations.Num() + DistanceFieldSceneData.PendingUpdateOperations.Num();
UploadObjectData.Empty(NumUploadOperations * UploadObjectDataStride);
UploadObjectIndices.Empty(NumUploadOperations);
const int32 NumTexelsOneDimX = GDistanceFieldVolumeTextureAtlas.GetSizeX();
const int32 NumTexelsOneDimY = GDistanceFieldVolumeTextureAtlas.GetSizeY();
const int32 NumTexelsOneDimZ = GDistanceFieldVolumeTextureAtlas.GetSizeZ();
const FVector InvTextureDim(1.0f / NumTexelsOneDimX, 1.0f / NumTexelsOneDimY, 1.0f / NumTexelsOneDimZ);
int32 OriginalNumObjects = DistanceFieldSceneData.NumObjectsInBuffer;
int32 OriginalNumSurfels = DistanceFieldSceneData.SurfelAllocations.GetNumSurfelsInBuffer();
int32 OriginalNumInstancedSurfels = DistanceFieldSceneData.InstancedSurfelAllocations.GetNumSurfelsInBuffer();
if (bPrepareForDistanceFieldGI)
{
for (int32 UploadPrimitiveIndex = 0; UploadPrimitiveIndex < DistanceFieldSceneData.PendingAddOperations.Num(); UploadPrimitiveIndex++)
{
FPrimitiveSceneInfo* PrimitiveSceneInfo = DistanceFieldSceneData.PendingAddOperations[UploadPrimitiveIndex];
int32 NumInstances = 0;
float BoundsSurfaceArea = 0;
PrimitiveSceneInfo->Proxy->GetDistanceFieldInstanceInfo(NumInstances, BoundsSurfaceArea);
extern void ComputeNumSurfels(float BoundsSurfaceArea, int32& PrimitiveNumSurfels, int32& PrimitiveLOD0Surfels);
int32 PrimitiveNumSurfels;
int32 PrimitiveLOD0Surfels;
ComputeNumSurfels(BoundsSurfaceArea, PrimitiveNumSurfels, PrimitiveLOD0Surfels);
if (PrimitiveNumSurfels > 0 && NumInstances > 0)
{
const int32 PrimitiveTotalNumSurfels = PrimitiveNumSurfels * NumInstances;
if (PrimitiveNumSurfels > 5000)
{
UE_LOG(LogDistanceField,Warning,TEXT("Primitive %s %s used %u Surfels"), *PrimitiveSceneInfo->Proxy->GetOwnerName().ToString(), *PrimitiveSceneInfo->Proxy->GetResourceName().ToString(), PrimitiveNumSurfels);
}
DistanceFieldSceneData.SurfelAllocations.AddPrimitive(PrimitiveSceneInfo, PrimitiveLOD0Surfels, PrimitiveNumSurfels, 1);
DistanceFieldSceneData.InstancedSurfelAllocations.AddPrimitive(PrimitiveSceneInfo, PrimitiveLOD0Surfels, PrimitiveNumSurfels, NumInstances);
}
}
if (DistanceFieldSceneData.SurfelBuffers->MaxSurfels < DistanceFieldSceneData.SurfelAllocations.GetNumSurfelsInBuffer())
{
if (DistanceFieldSceneData.SurfelBuffers->MaxSurfels > 0)
{
// Realloc
FSurfelBuffers* NewSurfelBuffers = new FSurfelBuffers();
NewSurfelBuffers->MaxSurfels = DistanceFieldSceneData.SurfelAllocations.GetNumSurfelsInBuffer() * 5 / 4;
NewSurfelBuffers->Initialize();
{
TShaderMapRef<FCopySurfelBufferCS> ComputeShader(GetGlobalShaderMap(Scene->GetFeatureLevel()));
RHICmdList.SetComputeShader(ComputeShader->GetComputeShader());
ComputeShader->SetParameters(RHICmdList, *(DistanceFieldSceneData.SurfelBuffers), *(DistanceFieldSceneData.InstancedSurfelBuffers), *NewSurfelBuffers, OriginalNumSurfels);
DispatchComputeShader(RHICmdList, *ComputeShader, FMath::DivideAndRoundUp<uint32>(OriginalNumSurfels, UpdateObjectsGroupSize), 1, 1);
ComputeShader->UnsetParameters(RHICmdList, *NewSurfelBuffers);
}
DistanceFieldSceneData.SurfelBuffers->Release();
delete DistanceFieldSceneData.SurfelBuffers;
DistanceFieldSceneData.SurfelBuffers = NewSurfelBuffers;
}
else
{
// First time allocate
DistanceFieldSceneData.SurfelBuffers->MaxSurfels = DistanceFieldSceneData.SurfelAllocations.GetNumSurfelsInBuffer() * 5 / 4;
DistanceFieldSceneData.SurfelBuffers->Initialize();
}
}
if (DistanceFieldSceneData.InstancedSurfelBuffers->MaxSurfels < DistanceFieldSceneData.InstancedSurfelAllocations.GetNumSurfelsInBuffer())
{
if (DistanceFieldSceneData.InstancedSurfelBuffers->MaxSurfels > 0)
{
// Realloc
FInstancedSurfelBuffers* NewInstancedSurfelBuffers = new FInstancedSurfelBuffers();
NewInstancedSurfelBuffers->MaxSurfels = DistanceFieldSceneData.InstancedSurfelAllocations.GetNumSurfelsInBuffer() * 5 / 4;
NewInstancedSurfelBuffers->Initialize();
{
TShaderMapRef<FCopyVPLFluxBufferCS> ComputeShader(GetGlobalShaderMap(Scene->GetFeatureLevel()));
RHICmdList.SetComputeShader(ComputeShader->GetComputeShader());
ComputeShader->SetParameters(RHICmdList, *(DistanceFieldSceneData.SurfelBuffers), *(DistanceFieldSceneData.InstancedSurfelBuffers), *NewInstancedSurfelBuffers, OriginalNumInstancedSurfels);
DispatchComputeShader(RHICmdList, *ComputeShader, FMath::DivideAndRoundUp<uint32>(OriginalNumInstancedSurfels, UpdateObjectsGroupSize), 1, 1);
ComputeShader->UnsetParameters(RHICmdList, *NewInstancedSurfelBuffers);
}
DistanceFieldSceneData.InstancedSurfelBuffers->Release();
delete DistanceFieldSceneData.InstancedSurfelBuffers;
DistanceFieldSceneData.InstancedSurfelBuffers = NewInstancedSurfelBuffers;
}
else
{
// First time allocate
DistanceFieldSceneData.InstancedSurfelBuffers->MaxSurfels = DistanceFieldSceneData.InstancedSurfelAllocations.GetNumSurfelsInBuffer() * 5 / 4;
DistanceFieldSceneData.InstancedSurfelBuffers->Initialize();
}
}
}
for (int32 UploadPrimitiveIndex = 0; UploadPrimitiveIndex < DistanceFieldSceneData.PendingAddOperations.Num(); UploadPrimitiveIndex++)
{
FPrimitiveSceneInfo* PrimitiveSceneInfo = DistanceFieldSceneData.PendingAddOperations[UploadPrimitiveIndex];
ProcessPrimitiveUpdate(
true,
RHICmdList,
*this,
PrimitiveSceneInfo,
OriginalNumObjects,
InvTextureDim,
bPrepareForDistanceFieldGI,
ObjectLocalToWorldTransforms,
UploadObjectIndices,
UploadObjectData);
}
for (TSet<FPrimitiveSceneInfo*>::TIterator It(DistanceFieldSceneData.PendingUpdateOperations); It; ++It)
{
FPrimitiveSceneInfo* PrimitiveSceneInfo = *It;
ProcessPrimitiveUpdate(
false,
RHICmdList,
*this,
PrimitiveSceneInfo,
OriginalNumObjects,
InvTextureDim,
bPrepareForDistanceFieldGI,
ObjectLocalToWorldTransforms,
UploadObjectIndices,
UploadObjectData);
}
DistanceFieldSceneData.PendingAddOperations.Reset();
DistanceFieldSceneData.PendingUpdateOperations.Empty();
if (DistanceFieldSceneData.ObjectBuffers->MaxObjects < DistanceFieldSceneData.NumObjectsInBuffer)
{
if (DistanceFieldSceneData.ObjectBuffers->MaxObjects > 0)
{
// Realloc
FDistanceFieldObjectBuffers* NewObjectBuffers = new FDistanceFieldObjectBuffers();
NewObjectBuffers->MaxObjects = DistanceFieldSceneData.NumObjectsInBuffer * 5 / 4;
NewObjectBuffers->Initialize();
{
TShaderMapRef<FCopyObjectBufferCS> ComputeShader(GetGlobalShaderMap(Scene->GetFeatureLevel()));
RHICmdList.SetComputeShader(ComputeShader->GetComputeShader());
ComputeShader->SetParameters(RHICmdList, *(DistanceFieldSceneData.ObjectBuffers), *NewObjectBuffers, OriginalNumObjects);
DispatchComputeShader(RHICmdList, *ComputeShader, FMath::DivideAndRoundUp<uint32>(OriginalNumObjects, UpdateObjectsGroupSize), 1, 1);
ComputeShader->UnsetParameters(RHICmdList, *NewObjectBuffers);
}
DistanceFieldSceneData.ObjectBuffers->Release();
delete DistanceFieldSceneData.ObjectBuffers;
DistanceFieldSceneData.ObjectBuffers = NewObjectBuffers;
}
else
{
// First time allocate
DistanceFieldSceneData.ObjectBuffers->MaxObjects = DistanceFieldSceneData.NumObjectsInBuffer * 5 / 4;
DistanceFieldSceneData.ObjectBuffers->Initialize();
}
}
}
if (UploadObjectIndices.Num() > 0)
{
if (UploadObjectIndices.Num() > GDistanceFieldUploadIndices.UploadIndices.MaxElements
// Shrink if very large
|| (GDistanceFieldUploadIndices.UploadIndices.MaxElements > 1000 && GDistanceFieldUploadIndices.UploadIndices.MaxElements > UploadObjectIndices.Num() * 2))
{
GDistanceFieldUploadIndices.UploadIndices.MaxElements = UploadObjectIndices.Num() * 5 / 4;
GDistanceFieldUploadIndices.UploadIndices.Release();
GDistanceFieldUploadIndices.UploadIndices.Initialize();
GDistanceFieldUploadData.UploadData.MaxElements = UploadObjectIndices.Num() * 5 / 4;
GDistanceFieldUploadData.UploadData.Release();
GDistanceFieldUploadData.UploadData.Initialize();
}
void* LockedBuffer = RHILockVertexBuffer(GDistanceFieldUploadIndices.UploadIndices.Buffer, 0, GDistanceFieldUploadIndices.UploadIndices.Buffer->GetSize(), RLM_WriteOnly);
const uint32 MemcpySize = UploadObjectIndices.GetTypeSize() * UploadObjectIndices.Num();
check(GDistanceFieldUploadIndices.UploadIndices.Buffer->GetSize() >= MemcpySize);
FPlatformMemory::Memcpy(LockedBuffer, UploadObjectIndices.GetData(), MemcpySize);
RHIUnlockVertexBuffer(GDistanceFieldUploadIndices.UploadIndices.Buffer);
LockedBuffer = RHILockVertexBuffer(GDistanceFieldUploadData.UploadData.Buffer, 0, GDistanceFieldUploadData.UploadData.Buffer->GetSize(), RLM_WriteOnly);
const uint32 MemcpySize2 = UploadObjectData.GetTypeSize() * UploadObjectData.Num();
check(GDistanceFieldUploadData.UploadData.Buffer->GetSize() >= MemcpySize2);
FPlatformMemory::Memcpy(LockedBuffer, UploadObjectData.GetData(), MemcpySize2);
RHIUnlockVertexBuffer(GDistanceFieldUploadData.UploadData.Buffer);
{
TShaderMapRef<FUploadObjectsToBufferCS> ComputeShader(GetGlobalShaderMap(Scene->GetFeatureLevel()));
RHICmdList.SetComputeShader(ComputeShader->GetComputeShader());
ComputeShader->SetParameters(RHICmdList, Scene, UploadObjectIndices.Num(), GDistanceFieldUploadIndices.UploadIndices.BufferSRV, GDistanceFieldUploadData.UploadData.BufferSRV);
DispatchComputeShader(RHICmdList, *ComputeShader, FMath::DivideAndRoundUp<uint32>(UploadObjectIndices.Num(), UpdateObjectsGroupSize), 1, 1);
ComputeShader->UnsetParameters(RHICmdList, Scene);
}
}
check(DistanceFieldSceneData.NumObjectsInBuffer == DistanceFieldSceneData.PrimitiveInstanceMapping.Num());
DistanceFieldSceneData.VerifyIntegrity();
}
}
FString GetObjectBufferMemoryString()
{
return FString::Printf(TEXT("Temp object buffers %.3fMb"),
(GDistanceFieldUploadIndices.UploadIndices.GetSizeBytes() + GDistanceFieldUploadData.UploadData.GetSizeBytes() + GDistanceFieldRemoveIndices.RemoveIndices.GetSizeBytes()) / 1024.0f / 1024.0f);
}
| 41.939418 | 366 | 0.792011 | windystrife |
06f271876201a7a7e8e76e4e4187f749b5fbbfc6 | 1,070 | cpp | C++ | datasets/github_cpp_10/10/42.cpp | yijunyu/demo-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 1 | 2019-05-03T19:27:45.000Z | 2019-05-03T19:27:45.000Z | datasets/github_cpp_10/10/42.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | datasets/github_cpp_10/10/42.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null |
#include "StringEditDistance.hpp"
int stringEditDistance(string s, string t) {
int editDistance[s.length() + 1][t.length() + 1];
editDistance[0][0] = 0;
for(int i = 1; i <= s.length(); i++) {
editDistance[0][i] = i;
}
for(int i = 1; i <= t.length(); i++) {
editDistance[i][0] = i;
}
for(int i = 1; i <= s.length(); i++) {
for(int j = 1; j <= t.length(); j++) {
if(s.at(i-1) == t.at(j-1)) {
editDistance[i][j] = min(min(editDistance[i-1][j-1], editDistance[i][j-1]), editDistance[i-1][j]);
}
else {
editDistance[i][j] = min(min(editDistance[i-1][j-1], editDistance[i][j-1]), editDistance[i-1][j]) + 1;
}
}
}
return editDistance[s.length()][t.length()];
}
void stringEditDistanceTest() {
string s;
string t;
cin >> s;
cin >> t;
cout << stringEditDistance(s, t) << endl;
} | 16.984127 | 114 | 0.433645 | yijunyu |
06f423e627d457ea94533dac88ec2f557cc37268 | 1,079 | hxx | C++ | opencascade/PrsDim_KindOfSurface.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 37 | 2020-01-20T21:50:21.000Z | 2022-02-09T13:01:09.000Z | opencascade/PrsDim_KindOfSurface.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 66 | 2019-12-20T16:07:36.000Z | 2022-03-15T21:56:10.000Z | opencascade/PrsDim_KindOfSurface.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 22 | 2020-04-03T21:59:52.000Z | 2022-03-06T18:43:35.000Z | // Created on: 1996-12-11
// Created by: Robert COUBLANC
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _PrsDim_KindOfSurface_HeaderFile
#define _PrsDim_KindOfSurface_HeaderFile
enum PrsDim_KindOfSurface
{
PrsDim_KOS_Plane,
PrsDim_KOS_Cylinder,
PrsDim_KOS_Cone,
PrsDim_KOS_Sphere,
PrsDim_KOS_Torus,
PrsDim_KOS_Revolution,
PrsDim_KOS_Extrusion,
PrsDim_KOS_OtherSurface
};
#endif // _PrsDim_KindOfSurface_HeaderFile
| 32.69697 | 81 | 0.794254 | valgur |
06f619f19ec9f06694abad962b796c00f80d5e3c | 6,238 | cpp | C++ | emulator/src/cpu/Cpu65816.cpp | mike42/65816-computer | 9250b6dedc4757e8548d8dd6defce34ca6e03a8f | [
"CC-BY-4.0"
] | null | null | null | emulator/src/cpu/Cpu65816.cpp | mike42/65816-computer | 9250b6dedc4757e8548d8dd6defce34ca6e03a8f | [
"CC-BY-4.0"
] | null | null | null | emulator/src/cpu/Cpu65816.cpp | mike42/65816-computer | 9250b6dedc4757e8548d8dd6defce34ca6e03a8f | [
"CC-BY-4.0"
] | null | null | null | /*
* This file is part of the 65816 Emulator Library.
* Copyright (c) 2018 Francesco Rigoni.
*
* https://github.com/FrancescoRigoni/Lib65816
*
* 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, version 3.
*
* 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 "Cpu65816.h"
#include <utility>
#ifdef EMU_65C02
#define LOG_TAG "Cpu65C02"
#else
#define LOG_TAG (mCpuStatus.emulationFlag() ? "Cpu6502" : "Cpu65816")
#endif
Cpu65816::Cpu65816(SystemBus &systemBus, std::shared_ptr<InterruptStatus> nmi, std::shared_ptr<InterruptStatus> irq) :
mSystemBus(systemBus),
mStack(&mSystemBus),
nmi(nmi),
irq(irq) {
mPins.NMI = nmi->get();
}
void Cpu65816::setXL(uint8_t x) {
mX = x;
}
void Cpu65816::setYL(uint8_t y) {
mY = y;
}
void Cpu65816::setX(uint16_t x) {
mX = x;
}
void Cpu65816::setY(uint16_t y) {
mY = y;
}
void Cpu65816::setA(uint16_t a) {
mA = a;
}
uint16_t Cpu65816::getA() {
return mA;
}
Address Cpu65816::getProgramAddress() {
return mProgramAddress;
}
Stack *Cpu65816::getStack() {
return &mStack;
}
CpuStatus *Cpu65816::getCpuStatus() {
return &mCpuStatus;
}
/**
* Resets the cpu to its initial state.
* */
void Cpu65816::reset() {
setRESPin(true);
mCpuStatus.setEmulationFlag();
mCpuStatus.setAccumulatorWidthFlag();
mCpuStatus.setIndexWidthFlag();
mX &= 0xFF;
mY &= 0xFF;
mD = 0x0;
mStack = Stack(&mSystemBus);
mProgramAddress = Address(0x00, mSystemBus.readTwoBytes(Address(0x00, INTERRUPT_VECTOR_EMULATION_RESET)));
}
void Cpu65816::setRESPin(bool value) {
if (value == false && mPins.RES == true) {
reset();
}
mPins.RES = value;
}
void Cpu65816::setRDYPin(bool value) {
mPins.RDY = value;
}
bool Cpu65816::executeNextInstruction() {
if (mPins.RES) {
return false;
}
if ((irq->get()) && (!mCpuStatus.interruptDisableFlag())) {
/*
The program bank register (PB, the A16-A23 part of the address bus) is pushed onto the hardware stack (65C816/65C802 only when operating in native mode).
The most significant byte (MSB) of the program counter (PC) is pushed onto the stack.
The least significant byte (LSB) of the program counter is pushed onto the stack.
The status register (SR) is pushed onto the stack.
The interrupt disable flag is set in the status register.
PB is loaded with $00 (65C816/65C802 only when operating in native mode).
PC is loaded from the relevant vector (see tables).
*/
if (!mCpuStatus.emulationFlag()) {
mStack.push8Bit(mProgramAddress.getBank());
mStack.push16Bit(mProgramAddress.getOffset());
mStack.push8Bit(mCpuStatus.getRegisterValue());
mCpuStatus.setInterruptDisableFlag();
mProgramAddress = Address(0x00, mSystemBus.readTwoBytes(Address(0x00, INTERRUPT_VECTOR_NATIVE_IRQ)));
} else {
mStack.push16Bit(mProgramAddress.getOffset());
mStack.push8Bit(mCpuStatus.getRegisterValue());
mCpuStatus.setInterruptDisableFlag();
mProgramAddress = Address(0x00, mSystemBus.readTwoBytes(Address(0x00, INTERRUPT_VECTOR_EMULATION_BRK_IRQ)));
}
}
// Edge detect NMI
bool newNmi = nmi->get();
if(!newNmi && mPins.NMI) {
// De-activated
mPins.NMI = false;
} else if(newNmi && !mPins.NMI) {
// Activated
mPins.NMI = true;
if (!mCpuStatus.emulationFlag()) {
mStack.push8Bit(mProgramAddress.getBank());
mStack.push16Bit(mProgramAddress.getOffset());
mStack.push8Bit(mCpuStatus.getRegisterValue());
mCpuStatus.setInterruptDisableFlag();
mProgramAddress = Address(0x00, mSystemBus.readTwoBytes(Address(0x00, INTERRUPT_VECTOR_NATIVE_NMI)));
} else {
mStack.push16Bit(mProgramAddress.getOffset());
mStack.push8Bit(mCpuStatus.getRegisterValue());
mCpuStatus.setInterruptDisableFlag();
mProgramAddress = Address(0x00, mSystemBus.readTwoBytes(Address(0x00, INTERRUPT_VECTOR_EMULATION_NMI)));
}
}
// Fetch the instruction
const uint8_t instruction = mSystemBus.readByte(mProgramAddress);
OpCode opCode = OP_CODE_TABLE[instruction];
// Execute it
return opCode.execute(*this);
}
bool Cpu65816::accumulatorIs8BitWide() {
// Accumulator is always 8 bit in emulation mode.
if (mCpuStatus.emulationFlag()) return true;
// Accumulator width set to one means 8 bit accumulator.
else return mCpuStatus.accumulatorWidthFlag();
}
bool Cpu65816::accumulatorIs16BitWide() {
return !accumulatorIs8BitWide();
}
bool Cpu65816::indexIs8BitWide() {
// Index is always 8 bit in emulation mode.
if (mCpuStatus.emulationFlag()) return true;
// Index width set to one means 8 bit accumulator.
else return mCpuStatus.indexWidthFlag();
}
bool Cpu65816::indexIs16BitWide() {
return !indexIs8BitWide();
}
void Cpu65816::addToCycles(int cycles) {
mTotalCyclesCounter += cycles;
mSystemBus.clockTick(cycles);
}
void Cpu65816::subtractFromCycles(int cycles) {
mTotalCyclesCounter -= cycles;
}
void Cpu65816::addToProgramAddress(int bytes) {
mProgramAddress.incrementOffsetBy(bytes);
}
void Cpu65816::addToProgramAddressAndCycles(int bytes, int cycles) {
addToCycles(cycles);
addToProgramAddress(bytes);
}
uint16_t Cpu65816::indexWithXRegister() {
return indexIs8BitWide() ? Binary::lower8BitsOf(mX) : mX;
}
uint16_t Cpu65816::indexWithYRegister() {
return indexIs8BitWide() ? Binary::lower8BitsOf(mY) : mY;
}
void Cpu65816::setProgramAddress(const Address &address) {
mProgramAddress = address;
}
| 29.990385 | 161 | 0.679224 | mike42 |
06fb1bcc1d69479e99dbdd3a5726c5fd7cecae81 | 11,905 | cpp | C++ | src/misc/jfontload.cpp | akmed772/dosvax | 878a4187d3a126b93a6ae8f79f28267b83d323e5 | [
"MIT"
] | 1 | 2022-03-16T08:50:16.000Z | 2022-03-16T08:50:16.000Z | src/misc/jfontload.cpp | akmed772/dosvax | 878a4187d3a126b93a6ae8f79f28267b83d323e5 | [
"MIT"
] | null | null | null | src/misc/jfontload.cpp | akmed772/dosvax | 878a4187d3a126b93a6ae8f79f28267b83d323e5 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2016-2022 akm
All rights reserved.
This content is under the MIT License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dosbox.h"
#include "control.h"
#include "support.h"
#include "jsupport.h"
//#include "jega.h"//for AX
//#include "ps55.h"//for PS/55
using namespace std;
#define SBCS 0
#define DBCS 1
#define ID_LEN 6
#define NAME_LEN 8
Bit8u jfont_sbcs_19[SBCS19_LEN];//256 * 19( * 8 bit)
Bit8u jfont_dbcs_16[DBCS16_LEN];//65536 * 16 * (16 bit)
//Bit16u jfont_sbcs_24[SBCS24_LEN];//256 * 24 * (16 bit)
Bit8u ps55font_24[DBCS24_LEN];//65536 * 24 * (24 bit)
typedef struct {
char id[ID_LEN];
char name[NAME_LEN];
unsigned char width;
unsigned char height;
unsigned char type;
} fontx_h;
typedef struct {
Bit16u start;
Bit16u end;
} fontxTbl;
Bit16u chrtosht(FILE *fp)
{
Bit16u i, j;
i = (Bit8u)getc(fp);
j = (Bit8u)getc(fp) << 8;
return(i | j);
}
/*
--------------------------------81=====9F---------------E0=====FC-: High byte of SJIS
----------------40=========7E-80===============================FC-: Low byte of SJIS
00=====1E1F=====3B------------------------------------------------: High byte of IBMJ
00=========3839===============================FB------------------: Low byte of IBMJ
A B C
2ADC, 2C5F, +5524 --> 8000
2614, 2673, +90EC --> B700
2384, 2613, +906C --> B3F0
0682, 1F7D, +0000
*/
//convert Shift JIS code to PS/55 internal char code
Bit16u SJIStoIBMJ(Bit16u knj)
{
//verify code
if (knj < 0x8140 || knj > 0xfc4b) return 0xffff;
Bitu knj1 = (knj >> 8) & 0xff;// = FCh - 40h //higher code (ah)
Bitu knj2 = knj & 0xff;//lower code (al)
knj1 -= 0x81;
if (knj1 > 0x5E) knj1 -= 0x40;
knj2 -= 0x40;
if (knj2 > 0x3F) knj2--;
knj1 *= 0xBC;
knj = knj1 + knj2;
knj += 0x100;
//shift code out of JIS standard
if (knj >= 0x2ADC && knj <= 0x2C5F)
knj += 0x5524;
else if (knj >= 0x2384 && knj <= 0x2613)
knj += 0x906c;
else if (knj >= 0x2614 && knj <= 0x2673)
knj += 0x90ec;
return knj;
}
//Convert internal char code to Shift JIS code (obsolete)
Bit16u IBMJtoSJIS(Bit16u knj)
{
//verify code
if (knj < 0x100) return 0xffff;
knj -= 0x100;
if (knj <= 0x1f7d)
;//do nothing
else if(knj >= 0xb700 && knj <= 0xb75f) {
knj -= 0x90ec;
}
else if (knj >= 0xb3f0 && knj <= 0xb67f) {
knj -= 0x906c;
}
else if (knj >= 0x8000 && knj <= 0x8183)
{
knj -= 0x5524;
}
else
return 0xffff;
Bitu knj1 = knj / 0xBC;// = FCh - 40h //higher code (ah)
Bitu knj2 = knj - (knj1 * 0xBC);//lower code (al)
//knj1 = knj >> 8;//higher code (ah)
knj1 += 0x81;
if (knj1 > 0x9F) knj1 += 0x40;
knj2 += 0x40;
if (knj2 > 0x7E) knj2++;
//verify code
if (!isKanji1(knj1)) return 0xffff;
if (!isKanji2(knj2)) return 0xffff;
knj = knj1 << 8;
knj |= knj2;
return knj;
}
Bitu getfontx2header(FILE *fp, fontx_h *header)
{
fread(header->id, ID_LEN, 1, fp);
if (strncmp(header->id, "FONTX2", ID_LEN) != 0) {
return 1;
}
fread(header->name, NAME_LEN, 1, fp);
header->width = (Bit8u)getc(fp);
header->height = (Bit8u)getc(fp);
header->type = (Bit8u)getc(fp);
return 0;
}
void readfontxtbl(fontxTbl *table, Bitu size, FILE *fp)
{
while (size > 0) {
table->start = chrtosht(fp);
table->end = chrtosht(fp);
++table;
--size;
}
}
static Bitu LoadFontxFile(const char * fname) {
fontx_h head;
fontxTbl *table;
Bit8u buf;
Bitu code;
Bit8u size;
Bitu font;
Bitu ibmcode;
if (!fname) return 127;
if(*fname=='\0') return 127;
FILE * mfile=fopen(fname,"rb");
if (!mfile) {
LOG_MSG("MSG: Can't open FONTX2 file: %s",fname);
return 127;
}
if (getfontx2header(mfile, &head) != 0) {
fclose(mfile);
LOG_MSG("MSG: FONTX2 header is incorrect\n");
return 1;
}
// switch whether the font is DBCS or not
if (head.type == DBCS) {
if (head.width == 16 && head.height == 16) {//for JEGA (AX)
size = getc(mfile);
table = (fontxTbl *)calloc(size, sizeof(fontxTbl));
readfontxtbl(table, size, mfile);
for (Bitu i = 0; i < size; i++)
for (code = table[i].start; code <= table[i].end; code++)
fread(&jfont_dbcs_16[(code * 32)], sizeof(Bit8u), 32, mfile);
} else if (head.width == 24 && head.height == 24) {//for PS/55
size = getc(mfile);
table = (fontxTbl *)calloc(size, sizeof(fontxTbl));
readfontxtbl(table, size, mfile);
for (Bitu i = 0; i < size; i++)
for (code = table[i].start; code <= table[i].end; code++) {
ibmcode = SJIStoIBMJ(code);
if (ibmcode >= 0x8000 && ibmcode <= 0x8183)//IBM extensions
ibmcode -= 0x6000;
if (ibmcode > DBCS24_CHARS) {//address is out of memory
LOG_MSG("MSG: FONTX2 DBCS code point %X may be wrong\n", code);
continue;
}
fread(&ps55font_24[(ibmcode * 72)], sizeof(Bit8u), 72, mfile);
}
}
else {
fclose(mfile);
LOG_MSG("MSG: FONTX2 DBCS font size is not correct\n");
return 4;
}
}
else {
if (head.width == 8 && head.height == 19) {
fread(jfont_sbcs_19, sizeof(Bit8u), SBCS19_LEN, mfile);
}
else if (head.width == 12 && head.height == 24) {
//fread(jfont_sbcs_24, sizeof(Bit16u), SBCS24_LEN, mfile);
//fread(&jfont_dbcs_24[72 * 0x2780], sizeof(Bit8u), SBCS24_LEN, mfile);
for (Bitu i = 0; i < SBCS24_CHARS; i++) {
ps55font_24[0x98000 + i * 64] = 0;
ps55font_24[0x98000 + i * 64 + 1] = 0;
ps55font_24[0x98000 + i * 64 + 2] = 0;
ps55font_24[0x98000 + i * 64 + 3] = 0;
ps55font_24[0x98000 + i * 64 + 52] = 0;
ps55font_24[0x98000 + i * 64 + 53] = 0;
ps55font_24[0x98000 + i * 64 + 54] = 0;
ps55font_24[0x98000 + i * 64 + 55] = 0;
ps55font_24[0x98000 + i * 64 + 56] = 0;
ps55font_24[0x98000 + i * 64 + 57] = 0;
for (Bitu line = 2 + 0; line < 2 + 24; line++)
{
fread(&buf, sizeof(Bit8u), 1, mfile);
font = buf << 8;
fread(&buf, sizeof(Bit8u), 1, mfile);
font |= buf;
font >> 1;
ps55font_24[0x98000 + i * 64 + line * 2 + 1] = font & 0xff;
ps55font_24[0x98000 + i * 64 + line * 2] = (font >> 8) & 0xff;
}
}
}
else {
fclose(mfile);
LOG_MSG("MSG: FONTX2 SBCS font size is not correct\n");
return 4;
}
}
fclose(mfile);
return 0;
}
/*
Font specification
BF800h
24 x 24
Font data 120 (78h) bytes
FF FF FF F8
xxxx xxxx, xxxx xxxx, xxxx xxxx, xxxx x000
width 29 pixels ?
height 30 pixels ?
footer? 8 (8h) bytes
00 00 00 00 20 07 20 00
$JPNHZ24.FNT
12 x 24
Font data 48 bytes
FF F, F FF
$SYSHN24.FNT
13 x 30
Font data 60 (3Ch) bytes
FF F8
xxxx xxxx, xxxx x000
width 13 pixels
height 30 pixels ?
need to exclude 0x81-90, 0xE0-FC
*/
//Font Loader for $JPNHN24.FNT included in DOS/V
static Bitu LoadDOSVHNFontFile(const char* fname) {
Bit8u buf;
Bitu code = 0;
Bit8u size;
Bitu font;
Bitu fsize;
if (!fname) return 127;
if (*fname == '\0') return 127;
FILE* mfile = fopen(fname, "rb");
if (!mfile) {
LOG_MSG("MSG: Can't open IBM font file: %s", fname);
return 127;
}
fseek(mfile, 0, SEEK_END);
fsize = ftell(mfile);//get filesize
fseek(mfile, 0, SEEK_SET);
if (fsize != 12288) {
//LOG_MSG("The size of font file is incorrect \n");
fclose(mfile);
return 1;
}
Bitu j = 0;
while (ftell(mfile) < fsize) {
fread(&buf, sizeof(Bit8u), 1, mfile);
font = buf << 7;
fread(&buf, sizeof(Bit8u), 1, mfile);
font |= (buf & 0xf0) >> 1;
ps55font_24[0x98000 + code * 64] = 0;
ps55font_24[0x98000 + code * 64 + 1] = 0;
ps55font_24[0x98000 + code * 64 + 2] = 0;
ps55font_24[0x98000 + code * 64 + 3] = 0;
ps55font_24[0x98000 + code * 64 + 52] = 0;
ps55font_24[0x98000 + code * 64 + 53] = 0;
ps55font_24[0x98000 + code * 64 + 54] = 0;
ps55font_24[0x98000 + code * 64 + 55] = 0;
ps55font_24[0x98000 + code * 64 + 56] = 0;
ps55font_24[0x98000 + code * 64 + 57] = 0;
ps55font_24[0x98000 + code * 64 + j + 4] = font >> 8;//a b
j++;
ps55font_24[0x98000 + code * 64 + j + 4] = font & 0xff;//a b
j++;
font = (buf & 0x0f) << 11;
fread(&buf, sizeof(Bit8u), 1, mfile);
font |= buf << 3;
ps55font_24[0x98000 + code * 64 + j + 4] = font >> 8;//a b
j++;
ps55font_24[0x98000 + code * 64 + j + 4] = font & 0xff;//a b
j++;
if (j >= 48) {
code++;
j = 0;
}
}
return 0;
}
//Font Loader for $SYSHN24.FNT included in DOS K3.3
static Bitu LoadIBMHN24Font(const char* fname) {
Bit8u buf;
Bitu code = 0;
Bitu fsize;
if (!fname) return 127;
if (*fname == '\0') return 127;
FILE* mfile = fopen(fname, "rb");
if (!mfile) {
LOG_MSG("MSG: Can't open IBM font file: %s", fname);
return 127;
}
fseek(mfile, 0, SEEK_END);
fsize = ftell(mfile);//get filesize
fseek(mfile, 0, SEEK_SET);
if (fsize != 11760) {
//LOG_MSG("The size of font file is incorrect \n");
fclose(mfile);
return 1;
}
Bitu j = 0;
while (ftell(mfile) < fsize) {
if (isKanji1(code)) {
code++;
continue;
}
fread(&buf, sizeof(Bit8u), 1, mfile);
ps55font_24[0x98000 + code * 64 + j] = buf;//a b
j++;
if (j >= 60) {
code++;
j = 0;
}
}
return 0;
}
//Font Loader for $SYSEX24.FNT included in DOS K3.3
static Bitu LoadIBMEX24Font(const char* fname) {
Bit8u buf;
Bitu code = 0;
Bitu fsize;
if (!fname) return 127;
if (*fname == '\0') return 127;
FILE* mfile = fopen(fname, "rb");
if (!mfile) {
LOG_MSG("MSG: Can't open IBM font file: %s", fname);
return 127;
}
fseek(mfile, 0, SEEK_END);
fsize = ftell(mfile);//get filesize
fseek(mfile, 0, SEEK_SET);
if (fsize != 15360) {
//LOG_MSG("The size of font file is incorrect \n");
fclose(mfile);
return 1;
}
Bitu j = 0;
while (ftell(mfile) < fsize) {
fread(&buf, sizeof(Bit8u), 1, mfile);
ps55font_24[0xb0000 + code * 64 + j] = buf;//a b
j++;
if (j >= 60) {
code++;
j = 0;
}
}
return 0;
}
static void LoadAnyFontFile(const char* fname)
{
if (LoadFontxFile(fname) != 1) return;
if (LoadDOSVHNFontFile(fname) != 1) return;
if (LoadIBMHN24Font(fname) != 1) return;
if (LoadIBMEX24Font(fname) != 1) return;
LOG_MSG("MSG: The font file is incorrect or broken.\n");
}
//#define TESLENG 64
void JFONT_Init(Section_prop * section) {
std::string file_name;
Prop_path* pathprop = section->Get_path("jfontsbcs");
//initialize memory array
memset(jfont_sbcs_19, 0xff, SBCS19_LEN);
memset(jfont_dbcs_16, 0xff, DBCS16_LEN);
memset(ps55font_24, 0xff, DBCS24_LEN);
//for (int i = 0; i < DBCS24_LEN / TESLENG; i++) {//for test
// jfont_dbcs_24[i * TESLENG + 2] = i & 0xff;
// jfont_dbcs_24[i * TESLENG + 4] = (i >> 8) & 0xff;
// jfont_dbcs_24[i * TESLENG + 6] = (i >> 16) & 0xff;
// jfont_dbcs_24[i * TESLENG + 8] = (i >> 24) & 0xff;
// jfont_dbcs_24[i * TESLENG + 10] = 0xaa;//1010 1010
// jfont_dbcs_24[i * TESLENG + 12] = 0xcc;//1100 1100
// jfont_dbcs_24[i * TESLENG + 14] = 0xf0;//1111 0000
//}
if (pathprop) LoadFontxFile(pathprop->realpath.c_str());
else LOG_MSG("MSG: SBCS font file path is not specified.\n");
pathprop = section->Get_path("jfontdbcs");
if(pathprop) LoadFontxFile(pathprop->realpath.c_str());
else LOG_MSG("MSG: DBCS font file path is not specified.\n");
pathprop = section->Get_path("jfont24sbcs");
if (pathprop) LoadAnyFontFile(pathprop->realpath.c_str());
else LOG_MSG("MSG: SBCS24 font file path is not specified.\n");
pathprop = section->Get_path("jfont24dbcs");
if (pathprop) LoadFontxFile(pathprop->realpath.c_str());
else LOG_MSG("MSG: DBCS24 font file path is not specified.\n");
pathprop = section->Get_path("jfont24sbex");
if (pathprop) LoadAnyFontFile(pathprop->realpath.c_str());
//else LOG_MSG("MSG: SBEX24 font file path is not specified.\n");
}
| 27.880562 | 86 | 0.584292 | akmed772 |
06fb99b73c5854ff64505f1495ea8d32e2bf8cd1 | 101 | cc | C++ | .ccls-cache/@Users@clp@id@idl/lg@src@main.cc | clpi/idx | fe86a22e090685d55774101dff132407f593fd9e | [
"MIT"
] | null | null | null | .ccls-cache/@Users@clp@id@idl/lg@src@main.cc | clpi/idx | fe86a22e090685d55774101dff132407f593fd9e | [
"MIT"
] | null | null | null | .ccls-cache/@Users@clp@id@idl/lg@src@main.cc | clpi/idx | fe86a22e090685d55774101dff132407f593fd9e | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ncurses.h>
class Lexer {
};
| 9.181818 | 20 | 0.653465 | clpi |
06fddfe7aa3897e8a65c6843c54556b0e41eed4c | 6,108 | cpp | C++ | src/flow_table/tests/flow_table_test.cpp | AlexandrePieroux/DNFC | 53756f5ec98409357407d4730dca2344ffb256d3 | [
"MIT"
] | 2 | 2017-04-25T23:48:01.000Z | 2017-06-12T14:20:41.000Z | src/flow_table/tests/flow_table_test.cpp | AlexandrePieroux/DNFC | 53756f5ec98409357407d4730dca2344ffb256d3 | [
"MIT"
] | null | null | null | src/flow_table/tests/flow_table_test.cpp | AlexandrePieroux/DNFC | 53756f5ec98409357407d4730dca2344ffb256d3 | [
"MIT"
] | null | null | null | #define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
extern "C"
{
#include "../flow_table.h"
#include "../../memory_management/memory_management.h"
}
#include <gtest/gtest.h>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#define NB_NUMBERS 1000000
#define NB_THREADS 64
#define HEADER_LENGTH 16
#define HEADER_BIT_L 320
struct arguments_t
{
u_char** numbers;
uint32_t* index;
uint32_t size;
hash_table** table;
};
uint32_t *get_random_numbers(uint32_t min, uint32_t max);
void* job_insert(void* args);
void* job_get(void* args);
void* job_remove(void* args);
void init(arguments_t*** args);
TEST (FlowTable, Insert)
{
arguments_t** args;
threadpool_t* pool = new_threadpool(NB_THREADS);
init(&args);
for (uint32_t i = 0; i < NB_THREADS; ++i)
threadpool_add_work(pool, job_insert, args[i]);
threadpool_wait(pool);
free_threadpool(pool);
hash_table_free(args[0]->table);
}
TEST (FlowTable, Get)
{
arguments_t** args;
threadpool_t* pool = new_threadpool(NB_THREADS);
init(&args);
for (uint32_t i = 0; i < NB_NUMBERS; ++i)
put_flow(*(*args)->table, (*args)->numbers[i], &(*args)->numbers[i]);
for (uint32_t i = 0; i < NB_THREADS; ++i)
threadpool_add_work(pool, job_get, args[i]);
threadpool_wait(pool);
free_threadpool(pool);
hash_table_free(args[0]->table);
}
TEST (FlowTable, Remove)
{
arguments_t** args;
threadpool_t* pool = new_threadpool(NB_THREADS);
init(&args);
for (uint32_t i = 0; i < NB_NUMBERS; ++i)
put_flow(*(*args)->table, (*args)->numbers[i], &(*args)->numbers[i]);
for (uint32_t i = 0; i < NB_THREADS; ++i)
threadpool_add_work(pool, job_remove, args[i]);
threadpool_wait(pool);
free_threadpool(pool);
hash_table_free(args[0]->table);
}
int main(int argc, char **argv)
{
srand(time(NULL));
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
uint32_t *get_random_numbers(uint32_t min, uint32_t max)
{
uint32_t size = max - min;
uint32_t *result = new uint32_t[size];
bool is_used[max];
for (uint32_t i = 0; i < size; i++)
{
is_used[i] = false;
}
uint32_t im = 0;
for (uint32_t in = min; in < max && im < size; ++in)
{
uint32_t r = rand() % (in + 1); /* generate a random number 'r' */
if (is_used[r]) /* we already have 'r' */
r = in; /* use 'in' instead of the generated number */
result[im++] = r + min;
is_used[r] = true;
}
return result;
}
void init(arguments_t*** args)
{
// Get random unique flows
uint32_t* source_address = get_random_numbers(0, NB_NUMBERS);
uint32_t* destination_address = get_random_numbers(NB_NUMBERS, (NB_NUMBERS * 2));
uint32_t* source_port = get_random_numbers(0, 65535);
uint32_t* destination_port = get_random_numbers(0, 65535);
u_char** keys = new u_char*[NB_NUMBERS];
uint32_t j = 0;
uint32_t* nb = new uint32_t;
uint8_t zero = 0;
uint8_t ihl = 5;
uint8_t version = 4;
uint8_t TCP_p = 6;
u_short eth_type = 2048;
for(uint32_t i = 0; i < NB_NUMBERS; i++){
key_type tmp = new_byte_stream();
// Ethernet type
for(uint32_t j = 0; j < 12; j++)
append_bytes(tmp, &zero, 1);
append_bytes(tmp, ð_type, 2);
// IHL IPv4 field
append_bytes(tmp, &ihl, 1);
// Version IPv4 field
append_bytes(tmp, &version, 1);
// Put the offset of port (9 bytes)
for(uint32_t j = 0; j < 7; j++)
append_bytes(tmp, &zero, 1);
// Put the TCP protocol number
append_bytes(tmp, &TCP_p, 1);
// Put the offset of the addresses (2 bytes)
for(uint32_t j = 0; j < 2; j++)
append_bytes(tmp, &zero, 1);
// Put the source address
*nb = source_address[i];
append_bytes(tmp, nb, 4);
// Put the destination address
*nb = destination_address[i];
append_bytes(tmp, nb, 4);
// Put the offset of the source ports (16 bytes)
for(uint32_t j = 0; j < 16; j++)
append_bytes(tmp, &zero, 1);
// Put the source port
*nb = source_port[(i % 65536)];
append_bytes(tmp, nb, 2);
// Put the destination port
*nb = destination_port[(i % 65536)];
append_bytes(tmp, nb, 2);
// Get the uint8_t array that form the header
keys[j++] = tmp->stream;
}
// Preparing the structure
*args = new arguments_t*[NB_THREADS];
hash_table** table = new hash_table*;
*table = new_hash_table(FNV_1, NB_THREADS);
// We distribute the work per threads
uint32_t divider = NB_NUMBERS / NB_THREADS;
uint32_t remain = NB_NUMBERS % NB_THREADS;
uint32_t* indexes = new uint32_t[NB_NUMBERS];
for (uint32_t i = 0; i < NB_NUMBERS; i++)
indexes[i] = i;
for (uint32_t p = 0; p < NB_THREADS; ++p)
{
(*args)[p] = new arguments_t;
(*args)[p]->numbers = &keys[p * divider];
(*args)[p]->index = &(indexes[p * divider]);
if(p != (NB_THREADS - 1))
(*args)[p]->size = divider;
else
(*args)[p]->size = divider + remain;
(*args)[p]->table = table;
}
}
void* job_insert(void* args)
{
arguments_t* args_cast = (arguments_t*)args;
for (uint32_t i = 0; i < args_cast->size; ++i){
bool result = put_flow(*args_cast->table, args_cast->numbers[i], &args_cast->numbers[i]);
EXPECT_TRUE(result);
}
return NULL;
}
void* job_get(void* args)
{
arguments_t* args_cast = (arguments_t*)args;
for (uint32_t i = 0; i < args_cast->size; ++i){
if (args_cast->numbers[i])
EXPECT_EQ(get_flow(*args_cast->table, args_cast->numbers[i]), &args_cast->numbers[i]);
}
return NULL;
}
void* job_remove(void* args)
{
arguments_t* args_cast = (arguments_t*)args;
for(uint32_t i = 0; i < args_cast->size; ++i){
bool result = remove_flow(*args_cast->table, args_cast->numbers[i]);
EXPECT_TRUE(result);
}
return NULL;
}
| 24.728745 | 95 | 0.599869 | AlexandrePieroux |
660445d356b337943caa6087fe5f1ef00456eb71 | 19,468 | cpp | C++ | src/graphics/VoxelRenderer.cpp | Retro52/Minecraft-Clone | 6417ad7f77978d71f90bb6db20e518ad467a3c83 | [
"Unlicense"
] | null | null | null | src/graphics/VoxelRenderer.cpp | Retro52/Minecraft-Clone | 6417ad7f77978d71f90bb6db20e518ad467a3c83 | [
"Unlicense"
] | null | null | null | src/graphics/VoxelRenderer.cpp | Retro52/Minecraft-Clone | 6417ad7f77978d71f90bb6db20e518ad467a3c83 | [
"Unlicense"
] | null | null | null | #include "VoxelRenderer.h"
#include "mesh.h"
#include "../voxels/voxel.h"
#include "../voxels/Block.h"
#include "../lighting/Lightmap.h"
#define VERTEX_SIZE (3 + 2 + 4)
#define CDIV(X,A) (((X) < 0) ? ((X) / (A) - 1) : ((X) / (A)))
#define LOCAL_NEG(X, SIZE) (((X) < 0) ? ((SIZE)+(X)) : (X))
#define LOCAL(X, SIZE) ((X) >= (SIZE) ? ((X) - (SIZE)) : LOCAL_NEG(X, SIZE))
#define IS_CHUNK(X,Y,Z) (GET_CHUNK(X,Y,Z) != nullptr)
#define GET_CHUNK(X,Y,Z) (chunks[((CDIV(Y, CHUNK_H)+1) * 3 + CDIV(Z, CHUNK_D) + 1) * 3 + CDIV(X, CHUNK_W) + 1])
#define LIGHT(X,Y,Z, CHANNEL) (IS_CHUNK(X,Y,Z) ? GET_CHUNK(X,Y,Z)->lightmap->get(LOCAL(X, CHUNK_W), LOCAL(Y, CHUNK_H), LOCAL(Z, CHUNK_D), (CHANNEL)) : 0)
#define VOXEL(X,Y,Z) (GET_CHUNK(X,Y,Z)->voxels[(LOCAL(Y, CHUNK_H) * CHUNK_D + LOCAL(Z, CHUNK_D)) * CHUNK_W + LOCAL(X, CHUNK_W)])
#define IS_BLOCKED(X,Y,Z,GROUP) ((!IS_CHUNK(X, Y, Z)) || Block::blocks[VOXEL(X, Y, Z).id]->drawGroup == (GROUP))
#define VERTEX(INDEX, X,Y,Z, U,V, R,G,B,S) buffer[INDEX+0] = (X);\
buffer[INDEX+1] = (Y);\
buffer[INDEX+2] = (Z);\
buffer[INDEX+3] = (U);\
buffer[INDEX+4] = (V);\
buffer[INDEX+5] = (R);\
buffer[INDEX+6] = (G);\
buffer[INDEX+7] = (B);\
buffer[INDEX+8] = (S);\
INDEX += VERTEX_SIZE;
#define SETUP_UV(INDEX) float u1 = ((INDEX) % 32) * uvsize;\
float v1 = 1-((1 + (INDEX) / 32) * uvsize);\
float u2 = u1 + uvsize;\
float v2 = v1 + uvsize;
int chunk_attrs[] = {3,2,4, 0};
VoxelRenderer::VoxelRenderer(size_t capacity) : capacity(capacity)
{
buffer = new float[capacity * VERTEX_SIZE * 6];
}
VoxelRenderer::~VoxelRenderer(){
delete[] buffer;
}
Mesh* VoxelRenderer::render(Chunk* chunk, const Chunk** chunks)
{
size_t index = 0;
for (int y = 0; y < CHUNK_H; y++)
{
for (int z = 0; z < CHUNK_D; z++)
{
for (int x = 0; x < CHUNK_W; x++)
{
voxel vox = chunk->voxels[(y * CHUNK_D + z) * CHUNK_W + x];
unsigned int id = vox.id;
if (!id)
{
continue;
}
float l;
float uvsize = 1.0f/32.0f;
Block* block = Block::blocks[id];
unsigned char group = block->drawGroup;
if (!IS_BLOCKED(x,y+1,z,group))
{
l = 1.0f;
SETUP_UV(block->textureFaces[3]);
float lr = LIGHT(x,y+1,z, 0) / 15.0f;
float lg = LIGHT(x,y+1,z, 1) / 15.0f;
float lb = LIGHT(x,y+1,z, 2) / 15.0f;
float ls = LIGHT(x,y+1,z, 3) / 15.0f;
float lr0 = (LIGHT(x-1,y+1,z,0) + lr*30 + LIGHT(x-1,y+1,z-1,0) + LIGHT(x,y+1,z-1,0)) / 5.0f / 15.0f;
float lr1 = (LIGHT(x-1,y+1,z,0) + lr*30 + LIGHT(x-1,y+1,z+1,0) + LIGHT(x,y+1,z+1,0)) / 5.0f / 15.0f;
float lr2 = (LIGHT(x+1,y+1,z,0) + lr*30 + LIGHT(x+1,y+1,z+1,0) + LIGHT(x,y+1,z+1,0)) / 5.0f / 15.0f;
float lr3 = (LIGHT(x+1,y+1,z,0) + lr*30 + LIGHT(x+1,y+1,z-1,0) + LIGHT(x,y+1,z-1,0)) / 5.0f / 15.0f;
float lg0 = (LIGHT(x-1,y+1,z,1) + lg*30 + LIGHT(x-1,y+1,z-1,1) + LIGHT(x,y+1,z-1,1)) / 5.0f / 15.0f;
float lg1 = (LIGHT(x-1,y+1,z,1) + lg*30 + LIGHT(x-1,y+1,z+1,1) + LIGHT(x,y+1,z+1,1)) / 5.0f / 15.0f;
float lg2 = (LIGHT(x+1,y+1,z,1) + lg*30 + LIGHT(x+1,y+1,z+1,1) + LIGHT(x,y+1,z+1,1)) / 5.0f / 15.0f;
float lg3 = (LIGHT(x+1,y+1,z,1) + lg*30 + LIGHT(x+1,y+1,z-1,1) + LIGHT(x,y+1,z-1,1)) / 5.0f / 15.0f;
float lb0 = (LIGHT(x-1,y+1,z,2) + lb*30 + LIGHT(x-1,y+1,z-1,2) + LIGHT(x,y+1,z-1,2)) / 5.0f / 15.0f;
float lb1 = (LIGHT(x-1,y+1,z,2) + lb*30 + LIGHT(x-1,y+1,z+1,2) + LIGHT(x,y+1,z+1,2)) / 5.0f / 15.0f;
float lb2 = (LIGHT(x+1,y+1,z,2) + lb*30 + LIGHT(x+1,y+1,z+1,2) + LIGHT(x,y+1,z+1,2)) / 5.0f / 15.0f;
float lb3 = (LIGHT(x+1,y+1,z,2) + lb*30 + LIGHT(x+1,y+1,z-1,2) + LIGHT(x,y+1,z-1,2)) / 5.0f / 15.0f;
float ls0 = (LIGHT(x-1,y+1,z,3) + ls*30 + LIGHT(x-1,y+1,z-1,3) + LIGHT(x,y+1,z-1,3)) / 5.0f / 15.0f;
float ls1 = (LIGHT(x-1,y+1,z,3) + ls*30 + LIGHT(x-1,y+1,z+1,3) + LIGHT(x,y+1,z+1,3)) / 5.0f / 15.0f;
float ls2 = (LIGHT(x+1,y+1,z,3) + ls*30 + LIGHT(x+1,y+1,z+1,3) + LIGHT(x,y+1,z+1,3)) / 5.0f / 15.0f;
float ls3 = (LIGHT(x+1,y+1,z,3) + ls*30 + LIGHT(x+1,y+1,z-1,3) + LIGHT(x,y+1,z-1,3)) / 5.0f / 15.0f;
VERTEX(index, x-0.5f, y+0.5f, z-0.5f, u2,v1, lr0, lg0, lb0, ls0);
VERTEX(index, x-0.5f, y+0.5f, z+0.5f, u2,v2, lr1, lg1, lb1, ls1);
VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u1,v2, lr2, lg2, lb2, ls2);
VERTEX(index, x-0.5f, y+0.5f, z-0.5f, u2,v1, lr0, lg0, lb0, ls0);
VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u1,v2, lr2, lg2, lb2, ls2);
VERTEX(index, x+0.5f, y+0.5f, z-0.5f, u1,v1, lr3, lg3, lb3, ls3);
}
if (!IS_BLOCKED(x,y-1,z,group)){
l = 0.75f;
SETUP_UV(block->textureFaces[2]);
float lr = LIGHT(x,y-1,z, 0) / 15.0f;
float lg = LIGHT(x,y-1,z, 1) / 15.0f;
float lb = LIGHT(x,y-1,z, 2) / 15.0f;
float ls = LIGHT(x,y-1,z, 3) / 15.0f;
float lr0 = (LIGHT(x-1,y-1,z-1,0) + lr*30 + LIGHT(x-1,y-1,z,0) + LIGHT(x,y-1,z-1,0)) / 5.0f / 15.0f;
float lr1 = (LIGHT(x+1,y-1,z+1,0) + lr*30 + LIGHT(x+1,y-1,z,0) + LIGHT(x,y-1,z+1,0)) / 5.0f / 15.0f;
float lr2 = (LIGHT(x-1,y-1,z+1,0) + lr*30 + LIGHT(x-1,y-1,z,0) + LIGHT(x,y-1,z+1,0)) / 5.0f / 15.0f;
float lr3 = (LIGHT(x+1,y-1,z-1,0) + lr*30 + LIGHT(x+1,y-1,z,0) + LIGHT(x,y-1,z-1,0)) / 5.0f / 15.0f;
float lg0 = (LIGHT(x-1,y-1,z-1,1) + lg*30 + LIGHT(x-1,y-1,z,1) + LIGHT(x,y-1,z-1,1)) / 5.0f / 15.0f;
float lg1 = (LIGHT(x+1,y-1,z+1,1) + lg*30 + LIGHT(x+1,y-1,z,1) + LIGHT(x,y-1,z+1,1)) / 5.0f / 15.0f;
float lg2 = (LIGHT(x-1,y-1,z+1,1) + lg*30 + LIGHT(x-1,y-1,z,1) + LIGHT(x,y-1,z+1,1)) / 5.0f / 15.0f;
float lg3 = (LIGHT(x+1,y-1,z-1,1) + lg*30 + LIGHT(x+1,y-1,z,1) + LIGHT(x,y-1,z-1,1)) / 5.0f / 15.0f;
float lb0 = (LIGHT(x-1,y-1,z-1,2) + lb*30 + LIGHT(x-1,y-1,z,2) + LIGHT(x,y-1,z-1,2)) / 5.0f / 15.0f;
float lb1 = (LIGHT(x+1,y-1,z+1,2) + lb*30 + LIGHT(x+1,y-1,z,2) + LIGHT(x,y-1,z+1,2)) / 5.0f / 15.0f;
float lb2 = (LIGHT(x-1,y-1,z+1,2) + lb*30 + LIGHT(x-1,y-1,z,2) + LIGHT(x,y-1,z+1,2)) / 5.0f / 15.0f;
float lb3 = (LIGHT(x+1,y-1,z-1,2) + lb*30 + LIGHT(x+1,y-1,z,2) + LIGHT(x,y-1,z-1,2)) / 5.0f / 15.0f;
float ls0 = (LIGHT(x-1,y-1,z-1,3) + ls*30 + LIGHT(x-1,y-1,z,3) + LIGHT(x,y-1,z-1,3)) / 5.0f / 15.0f;
float ls1 = (LIGHT(x+1,y-1,z+1,3) + ls*30 + LIGHT(x+1,y-1,z,3) + LIGHT(x,y-1,z+1,3)) / 5.0f / 15.0f;
float ls2 = (LIGHT(x-1,y-1,z+1,3) + ls*30 + LIGHT(x-1,y-1,z,3) + LIGHT(x,y-1,z+1,3)) / 5.0f / 15.0f;
float ls3 = (LIGHT(x+1,y-1,z-1,3) + ls*30 + LIGHT(x+1,y-1,z,3) + LIGHT(x,y-1,z-1,3)) / 5.0f / 15.0f;
VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u1,v1, lr0,lg0,lb0,ls0);
VERTEX(index, x+0.5f, y-0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1);
VERTEX(index, x-0.5f, y-0.5f, z+0.5f, u1,v2, lr2,lg2,lb2,ls2);
VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u1,v1, lr0,lg0,lb0,ls0);
VERTEX(index, x+0.5f, y-0.5f, z-0.5f, u2,v1, lr3,lg3,lb3,ls3);
VERTEX(index, x+0.5f, y-0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1);
}
if (!IS_BLOCKED(x+1,y,z,group)){
l = 0.95f;
SETUP_UV(block->textureFaces[1]);
float lr = LIGHT(x+1,y,z, 0) / 15.0f;
float lg = LIGHT(x+1,y,z, 1) / 15.0f;
float lb = LIGHT(x+1,y,z, 2) / 15.0f;
float ls = LIGHT(x+1,y,z, 3) / 15.0f;
float lr0 = (LIGHT(x+1,y-1,z-1,0) + lr*30 + LIGHT(x+1,y,z-1,0) + LIGHT(x+1,y-1,z,0)) / 5.0f / 15.0f;
float lr1 = (LIGHT(x+1,y+1,z-1,0) + lr*30 + LIGHT(x+1,y,z-1,0) + LIGHT(x+1,y+1,z,0)) / 5.0f / 15.0f;
float lr2 = (LIGHT(x+1,y+1,z+1,0) + lr*30 + LIGHT(x+1,y,z+1,0) + LIGHT(x+1,y+1,z,0)) / 5.0f / 15.0f;
float lr3 = (LIGHT(x+1,y-1,z+1,0) + lr*30 + LIGHT(x+1,y,z+1,0) + LIGHT(x+1,y-1,z,0)) / 5.0f / 15.0f;
float lg0 = (LIGHT(x+1,y-1,z-1,1) + lg*30 + LIGHT(x+1,y,z-1,1) + LIGHT(x+1,y-1,z,1)) / 5.0f / 15.0f;
float lg1 = (LIGHT(x+1,y+1,z-1,1) + lg*30 + LIGHT(x+1,y,z-1,1) + LIGHT(x+1,y+1,z,1)) / 5.0f / 15.0f;
float lg2 = (LIGHT(x+1,y+1,z+1,1) + lg*30 + LIGHT(x+1,y,z+1,1) + LIGHT(x+1,y+1,z,1)) / 5.0f / 15.0f;
float lg3 = (LIGHT(x+1,y-1,z+1,1) + lg*30 + LIGHT(x+1,y,z+1,1) + LIGHT(x+1,y-1,z,1)) / 5.0f / 15.0f;
float lb0 = (LIGHT(x+1,y-1,z-1,2) + lb*30 + LIGHT(x+1,y,z-1,2) + LIGHT(x+1,y-1,z,2)) / 5.0f / 15.0f;
float lb1 = (LIGHT(x+1,y+1,z-1,2) + lb*30 + LIGHT(x+1,y,z-1,2) + LIGHT(x+1,y+1,z,2)) / 5.0f / 15.0f;
float lb2 = (LIGHT(x+1,y+1,z+1,2) + lb*30 + LIGHT(x+1,y,z+1,2) + LIGHT(x+1,y+1,z,2)) / 5.0f / 15.0f;
float lb3 = (LIGHT(x+1,y-1,z+1,2) + lb*30 + LIGHT(x+1,y,z+1,2) + LIGHT(x+1,y-1,z,2)) / 5.0f / 15.0f;
float ls0 = (LIGHT(x+1,y-1,z-1,3) + ls*30 + LIGHT(x+1,y,z-1,3) + LIGHT(x+1,y-1,z,3)) / 5.0f / 15.0f;
float ls1 = (LIGHT(x+1,y+1,z-1,3) + ls*30 + LIGHT(x+1,y,z-1,3) + LIGHT(x+1,y+1,z,3)) / 5.0f / 15.0f;
float ls2 = (LIGHT(x+1,y+1,z+1,3) + ls*30 + LIGHT(x+1,y,z+1,3) + LIGHT(x+1,y+1,z,3)) / 5.0f / 15.0f;
float ls3 = (LIGHT(x+1,y-1,z+1,3) + ls*30 + LIGHT(x+1,y,z+1,3) + LIGHT(x+1,y-1,z,3)) / 5.0f / 15.0f;
VERTEX(index, x+0.5f, y-0.5f, z-0.5f, u2,v1, lr0,lg0,lb0,ls0);
VERTEX(index, x+0.5f, y+0.5f, z-0.5f, u2,v2, lr1,lg1,lb1,ls1);
VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u1,v2, lr2,lg2,lb2,ls2);
VERTEX(index, x+0.5f, y-0.5f, z-0.5f, u2,v1, lr0,lg0,lb0,ls0);
VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u1,v2, lr2,lg2,lb2,ls2);
VERTEX(index, x+0.5f, y-0.5f, z+0.5f, u1,v1, lr3,lg3,lb3,ls3);
}
if (!IS_BLOCKED(x-1,y,z,group)){
l = 0.85f;
SETUP_UV(block->textureFaces[0]);
float lr = LIGHT(x-1,y,z, 0) / 15.0f;
float lg = LIGHT(x-1,y,z, 1) / 15.0f;
float lb = LIGHT(x-1,y,z, 2) / 15.0f;
float ls = LIGHT(x-1,y,z, 3) / 15.0f;
float lr0 = (LIGHT(x-1,y-1,z-1,0) + lr*30 + LIGHT(x-1,y,z-1,0) + LIGHT(x-1,y-1,z,0)) / 5.0f / 15.0f;
float lr1 = (LIGHT(x-1,y+1,z+1,0) + lr*30 + LIGHT(x-1,y,z+1,0) + LIGHT(x-1,y+1,z,0)) / 5.0f / 15.0f;
float lr2 = (LIGHT(x-1,y+1,z-1,0) + lr*30 + LIGHT(x-1,y,z-1,0) + LIGHT(x-1,y+1,z,0)) / 5.0f / 15.0f;
float lr3 = (LIGHT(x-1,y-1,z+1,0) + lr*30 + LIGHT(x-1,y,z+1,0) + LIGHT(x-1,y-1,z,0)) / 5.0f / 15.0f;
float lg0 = (LIGHT(x-1,y-1,z-1,1) + lg*30 + LIGHT(x-1,y,z-1,1) + LIGHT(x-1,y-1,z,1)) / 5.0f / 15.0f;
float lg1 = (LIGHT(x-1,y+1,z+1,1) + lg*30 + LIGHT(x-1,y,z+1,1) + LIGHT(x-1,y+1,z,1)) / 5.0f / 15.0f;
float lg2 = (LIGHT(x-1,y+1,z-1,1) + lg*30 + LIGHT(x-1,y,z-1,1) + LIGHT(x-1,y+1,z,1)) / 5.0f / 15.0f;
float lg3 = (LIGHT(x-1,y-1,z+1,1) + lg*30 + LIGHT(x-1,y,z+1,1) + LIGHT(x-1,y-1,z,1)) / 5.0f / 15.0f;
float lb0 = (LIGHT(x-1,y-1,z-1,2) + lb*30 + LIGHT(x-1,y,z-1,2) + LIGHT(x-1,y-1,z,2)) / 5.0f / 15.0f;
float lb1 = (LIGHT(x-1,y+1,z+1,2) + lb*30 + LIGHT(x-1,y,z+1,2) + LIGHT(x-1,y+1,z,2)) / 5.0f / 15.0f;
float lb2 = (LIGHT(x-1,y+1,z-1,2) + lb*30 + LIGHT(x-1,y,z-1,2) + LIGHT(x-1,y+1,z,2)) / 5.0f / 15.0f;
float lb3 = (LIGHT(x-1,y-1,z+1,2) + lb*30 + LIGHT(x-1,y,z+1,2) + LIGHT(x-1,y-1,z,2)) / 5.0f / 15.0f;
float ls0 = (LIGHT(x-1,y-1,z-1,3) + ls*30 + LIGHT(x-1,y,z-1,3) + LIGHT(x-1,y-1,z,3)) / 5.0f / 15.0f;
float ls1 = (LIGHT(x-1,y+1,z+1,3) + ls*30 + LIGHT(x-1,y,z+1,3) + LIGHT(x-1,y+1,z,3)) / 5.0f / 15.0f;
float ls2 = (LIGHT(x-1,y+1,z-1,3) + ls*30 + LIGHT(x-1,y,z-1,3) + LIGHT(x-1,y+1,z,3)) / 5.0f / 15.0f;
float ls3 = (LIGHT(x-1,y-1,z+1,3) + ls*30 + LIGHT(x-1,y,z+1,3) + LIGHT(x-1,y-1,z,3)) / 5.0f / 15.0f;
VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u1,v1, lr0,lg0,lb0,ls0);
VERTEX(index, x-0.5f, y+0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1);
VERTEX(index, x-0.5f, y+0.5f, z-0.5f, u1,v2, lr2,lg2,lb2,ls2);
VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u1,v1, lr0,lg0,lb0,ls0);
VERTEX(index, x-0.5f, y-0.5f, z+0.5f, u2,v1, lr3,lg3,lb3,ls3);
VERTEX(index, x-0.5f, y+0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1);
}
if (!IS_BLOCKED(x,y,z+1,group)){
l = 0.9f;
SETUP_UV(block->textureFaces[5]);
float lr = LIGHT(x,y,z+1, 0) / 15.0f;
float lg = LIGHT(x,y,z+1, 1) / 15.0f;
float lb = LIGHT(x,y,z+1, 2) / 15.0f;
float ls = LIGHT(x,y,z+1, 3) / 15.0f;
float lr0 = l*(LIGHT(x-1,y-1,z+1,0) + lr*30 + LIGHT(x,y-1,z+1,0) + LIGHT(x-1,y,z+1,0)) / 5.0f / 15.0f;
float lr1 = l*(LIGHT(x+1,y+1,z+1,0) + lr*30 + LIGHT(x,y+1,z+1,0) + LIGHT(x+1,y,z+1,0)) / 5.0f / 15.0f;
float lr2 = l*(LIGHT(x-1,y+1,z+1,0) + lr*30 + LIGHT(x,y+1,z+1,0) + LIGHT(x-1,y,z+1,0)) / 5.0f / 15.0f;
float lr3 = l*(LIGHT(x+1,y-1,z+1,0) + lr*30 + LIGHT(x,y-1,z+1,0) + LIGHT(x+1,y,z+1,0)) / 5.0f / 15.0f;
float lg0 = l*(LIGHT(x-1,y-1,z+1,1) + lg*30 + LIGHT(x,y-1,z+1,1) + LIGHT(x-1,y,z+1,1)) / 5.0f / 15.0f;
float lg1 = l*(LIGHT(x+1,y+1,z+1,1) + lg*30 + LIGHT(x,y+1,z+1,1) + LIGHT(x+1,y,z+1,1)) / 5.0f / 15.0f;
float lg2 = l*(LIGHT(x-1,y+1,z+1,1) + lg*30 + LIGHT(x,y+1,z+1,1) + LIGHT(x-1,y,z+1,1)) / 5.0f / 15.0f;
float lg3 = l*(LIGHT(x+1,y-1,z+1,1) + lg*30 + LIGHT(x,y-1,z+1,1) + LIGHT(x+1,y,z+1,1)) / 5.0f / 15.0f;
float lb0 = l*(LIGHT(x-1,y-1,z+1,2) + lb*30 + LIGHT(x,y-1,z+1,2) + LIGHT(x-1,y,z+1,2)) / 5.0f / 15.0f;
float lb1 = l*(LIGHT(x+1,y+1,z+1,2) + lb*30 + LIGHT(x,y+1,z+1,2) + LIGHT(x+1,y,z+1,2)) / 5.0f / 15.0f;
float lb2 = l*(LIGHT(x-1,y+1,z+1,2) + lb*30 + LIGHT(x,y+1,z+1,2) + LIGHT(x-1,y,z+1,2)) / 5.0f / 15.0f;
float lb3 = l*(LIGHT(x+1,y-1,z+1,2) + lb*30 + LIGHT(x,y-1,z+1,2) + LIGHT(x+1,y,z+1,2)) / 5.0f / 15.0f;
float ls0 = l*(LIGHT(x-1,y-1,z+1,3) + ls*30 + LIGHT(x,y-1,z+1,3) + LIGHT(x-1,y,z+1,3)) / 5.0f / 15.0f;
float ls1 = l*(LIGHT(x+1,y+1,z+1,3) + ls*30 + LIGHT(x,y+1,z+1,3) + LIGHT(x+1,y,z+1,3)) / 5.0f / 15.0f;
float ls2 = l*(LIGHT(x-1,y+1,z+1,3) + ls*30 + LIGHT(x,y+1,z+1,3) + LIGHT(x-1,y,z+1,3)) / 5.0f / 15.0f;
float ls3 = l*(LIGHT(x+1,y-1,z+1,3) + ls*30 + LIGHT(x,y-1,z+1,3) + LIGHT(x+1,y,z+1,3)) / 5.0f / 15.0f;
VERTEX(index, x-0.5f, y-0.5f, z+0.5f, u1,v1, lr0,lg0,lb0,ls0);
VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1);
VERTEX(index, x-0.5f, y+0.5f, z+0.5f, u1,v2, lr2,lg2,lb2,ls2);
VERTEX(index, x-0.5f, y-0.5f, z+0.5f, u1,v1, lr0,lg0,lb0,ls0);
VERTEX(index, x+0.5f, y-0.5f, z+0.5f, u2,v1, lr3,lg3,lb3,ls3);
VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1);
}
if (!IS_BLOCKED(x,y,z-1,group)){
l = 0.8f;
SETUP_UV(block->textureFaces[4]);
float lr = LIGHT(x,y,z-1, 0) / 15.0f;
float lg = LIGHT(x,y,z-1, 1) / 15.0f;
float lb = LIGHT(x,y,z-1, 2) / 15.0f;
float ls = LIGHT(x,y,z-1, 3) / 15.0f;
float lr0 = l*(LIGHT(x-1,y-1,z-1,0) + lr*30 + LIGHT(x,y-1,z-1,0) + LIGHT(x-1,y,z-1,0)) / 5.0f / 15.0f;
float lr1 = l*(LIGHT(x-1,y+1,z-1,0) + lr*30 + LIGHT(x,y+1,z-1,0) + LIGHT(x-1,y,z-1,0)) / 5.0f / 15.0f;
float lr2 = l*(LIGHT(x+1,y+1,z-1,0) + lr*30 + LIGHT(x,y+1,z-1,0) + LIGHT(x+1,y,z-1,0)) / 5.0f / 15.0f;
float lr3 = l*(LIGHT(x+1,y-1,z-1,0) + lr*30 + LIGHT(x,y-1,z-1,0) + LIGHT(x+1,y,z-1,0)) / 5.0f / 15.0f;
float lg0 = l*(LIGHT(x-1,y-1,z-1,1) + lg*30 + LIGHT(x,y-1,z-1,1) + LIGHT(x-1,y,z-1,1)) / 5.0f / 15.0f;
float lg1 = l*(LIGHT(x-1,y+1,z-1,1) + lg*30 + LIGHT(x,y+1,z-1,1) + LIGHT(x-1,y,z-1,1)) / 5.0f / 15.0f;
float lg2 = l*(LIGHT(x+1,y+1,z-1,1) + lg*30 + LIGHT(x,y+1,z-1,1) + LIGHT(x+1,y,z-1,1)) / 5.0f / 15.0f;
float lg3 = l*(LIGHT(x+1,y-1,z-1,1) + lg*30 + LIGHT(x,y-1,z-1,1) + LIGHT(x+1,y,z-1,1)) / 5.0f / 15.0f;
float lb0 = l*(LIGHT(x-1,y-1,z-1,2) + lb*30 + LIGHT(x,y-1,z-1,2) + LIGHT(x-1,y,z-1,2)) / 5.0f / 15.0f;
float lb1 = l*(LIGHT(x-1,y+1,z-1,2) + lb*30 + LIGHT(x,y+1,z-1,2) + LIGHT(x-1,y,z-1,2)) / 5.0f / 15.0f;
float lb2 = l*(LIGHT(x+1,y+1,z-1,2) + lb*30 + LIGHT(x,y+1,z-1,2) + LIGHT(x+1,y,z-1,2)) / 5.0f / 15.0f;
float lb3 = l*(LIGHT(x+1,y-1,z-1,2) + lb*30 + LIGHT(x,y-1,z-1,2) + LIGHT(x+1,y,z-1,2)) / 5.0f / 15.0f;
float ls0 = l*(LIGHT(x-1,y-1,z-1,3) + ls*30 + LIGHT(x,y-1,z-1,3) + LIGHT(x-1,y,z-1,3)) / 5.0f / 15.0f;
float ls1 = l*(LIGHT(x-1,y+1,z-1,3) + ls*30 + LIGHT(x,y+1,z-1,3) + LIGHT(x-1,y,z-1,3)) / 5.0f / 15.0f;
float ls2 = l*(LIGHT(x+1,y+1,z-1,3) + ls*30 + LIGHT(x,y+1,z-1,3) + LIGHT(x+1,y,z-1,3)) / 5.0f / 15.0f;
float ls3 = l*(LIGHT(x+1,y-1,z-1,3) + ls*30 + LIGHT(x,y-1,z-1,3) + LIGHT(x+1,y,z-1,3)) / 5.0f / 15.0f;
VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u2,v1, lr0,lg0,lb0,ls0);
VERTEX(index, x-0.5f, y+0.5f, z-0.5f, u2,v2, lr1,lg1,lb1,ls1);
VERTEX(index, x+0.5f, y+0.5f, z-0.5f, u1,v2, lr2,lg2,lb2,ls2);
VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u2,v1, lr0,lg0,lb0,ls0);
VERTEX(index, x+0.5f, y+0.5f, z-0.5f, u1,v2, lr2,lg2,lb2,ls2);
VERTEX(index, x+0.5f, y-0.5f, z-0.5f, u1,v1, lr3,lg3,lb3,ls3);
}
}
}
}
return new Mesh(buffer, index / VERTEX_SIZE, chunk_attrs);
} | 63.829508 | 153 | 0.441494 | Retro52 |
66071db6d513feee136d2db82c8850adcaa6f32c | 15,033 | hpp | C++ | include/mimkl/kernels_handler.hpp | vishalbelsare/mimkl | 53a5a9db5aa09c6e8808ba5b845601c5768d23e2 | [
"MIT"
] | 31 | 2019-05-28T23:18:50.000Z | 2022-03-27T20:00:03.000Z | include/mimkl/kernels_handler.hpp | vishalbelsare/mimkl | 53a5a9db5aa09c6e8808ba5b845601c5768d23e2 | [
"MIT"
] | 4 | 2019-05-18T13:21:59.000Z | 2022-03-19T22:20:55.000Z | include/mimkl/kernels_handler.hpp | vishalbelsare/mimkl | 53a5a9db5aa09c6e8808ba5b845601c5768d23e2 | [
"MIT"
] | 9 | 2019-07-24T09:39:41.000Z | 2020-06-29T14:40:27.000Z | #ifndef INCLUDE_MIMKL_KERNELS_KERNELS_HANDLER_HPP_
#define INCLUDE_MIMKL_KERNELS_KERNELS_HANDLER_HPP_
#include <functional>
#include <memory>
#include <mimkl/definitions.hpp>
#include <mimkl/linear_algebra.hpp>
#include <mimkl/utilities.hpp>
#include <spdlog/spdlog.h>
#include <stdexcept>
using mimkl::definitions::Index;
namespace mimkl
{
namespace kernels_handler
{
static std::shared_ptr<spdlog::logger> logger =
spdlog::stdout_color_mt("KernelsHandler");
template <typename Scalar, typename Kernel>
class KernelsHandler
{
private:
typedef MATRIX(Scalar) Matrix;
typedef COLUMN(Scalar) Column;
std::shared_ptr<spdlog::logger> _logger = spdlog::get("KernelsHandler");
bool _precompute;
bool _trace_normalization;
Index _number_of_kernels = 0;
std::shared_ptr<Matrix> _lhs_ptr = nullptr;
std::shared_ptr<Matrix> _rhs_ptr = nullptr;
Index _lhs_size = 0;
Index _rhs_size = 0;
std::vector<Kernel> _kernel_functions;
std::vector<Matrix> _kernel_matrices;
std::vector<Scalar> _trace_factors;
// defining aggregational behaviour
std::function<Matrix(const Index)> _square_brakets;
std::function<Matrix()> _sum;
std::function<Matrix(const Column &)> _weighted_sum;
void precompute_kernel_matrices(const bool, const bool);
void set_lambdas_to_throw();
void set_lambdas(const bool, const bool, const bool);
public:
// constructors
KernelsHandler() = default;
KernelsHandler(const std::vector<Kernel> &kernel_functions,
const bool precompute = true,
const bool trace_normalization = true)
: _precompute(precompute), _trace_normalization(trace_normalization)
{
set_lambdas_to_throw();
if (kernel_functions.size() > 0)
set_functions(kernel_functions, trace_normalization);
}
KernelsHandler(const std::vector<Matrix> &kernel_matrices,
const bool precompute = true,
const bool trace_normalization = true)
: _trace_normalization(trace_normalization)
{
set_lambdas_to_throw();
_precompute = true;
if (kernel_matrices.size() > 0)
set_matrices(kernel_matrices, trace_normalization);
}
// getters
bool get_precompute() const;
bool get_trace_normalization() const;
Index get_number_of_kernels() const;
Matrix get_lhs() const;
Index get_lhs_size() const;
Index get_rhs_size() const;
std::vector<Kernel> get_functions() const;
std::vector<Matrix> get_matrices() const;
std::vector<Scalar> get_trace_factors() const;
// setters
void set_lhs(const Matrix &);
void set_rhs(const Matrix &);
void
set_matrices(const std::vector<Matrix> &, const bool learning_mode = false);
void set_functions(const std::vector<Kernel> &,
const bool learning_mode = false);
void set_trace_factors(const std::vector<Scalar> &);
Matrix operator[](const Index i) { return _square_brakets(i); }
Matrix sum() { return _sum(); }
Matrix sum(const Column &kernels_weights)
{
return _weighted_sum(kernels_weights);
}
Column get_corrected_kernels_weights(Column kernels_weights)
{
for (Index i = 0; i < _trace_factors.size(); ++i)
{
kernels_weights(i) /= _trace_factors[i];
}
return kernels_weights;
}
};
template <typename Scalar, typename Kernel>
void KernelsHandler<Scalar, Kernel>::set_lambdas_to_throw()
{
_logger->debug("set_lambdas_to_throw() start");
_square_brakets = [](const Index i) {
throw std::logic_error("Kernels are not available");
return Matrix();
};
_sum = []() {
throw std::logic_error("Kernels are not available");
return Matrix();
};
_weighted_sum = [](const Column &c) {
throw std::logic_error("Kernels are not available");
return Matrix();
};
_logger->debug("set_lambdas_to_throw() done");
}
template <typename Scalar, typename Kernel>
void KernelsHandler<Scalar, Kernel>::set_lambdas(const bool precompute,
const bool trace_normalization,
const bool learning_mode)
{
_logger->debug("set_lambdas() start");
_logger->debug("lhs samples: {}",
(_lhs_ptr != nullptr) ? _lhs_ptr->rows() : 0);
_logger->debug("rhs samples: {}",
(_rhs_ptr != nullptr) ? _rhs_ptr->rows() : 0);
if (precompute)
{ // trace_normalization or not already applied
_square_brakets = [this](const Index i) { return _kernel_matrices[i]; };
_sum = [this]() {
return mimkl::linear_algebra::sum_matrices(_kernel_matrices);
};
_weighted_sum = [this](const Column &kernels_weights) {
return mimkl::linear_algebra::sum_weighted_matrices(_kernel_matrices,
kernels_weights);
};
}
else
{ // "lazy", compute (and trace_normalization) anew on each access
if (trace_normalization)
{
if (learning_mode)
{ // learn trace_factor
_trace_factors.resize(_number_of_kernels);
_square_brakets = [this](const Index i) {
Matrix K = _kernel_functions[i](*_lhs_ptr, *_rhs_ptr);
_trace_factors[i] = mimkl::linear_algebra::trace_normalize(K);
return K;
};
}
else
{ // apply learned trace_normalization
if (_trace_factors.size() != _number_of_kernels)
throw std::logic_error("The trace_factors have not been "
"learned. Sizes don't match");
_square_brakets = [this](const Index i)
-> Matrix { // enforce return type because deduction
// can't be done in the body
return _kernel_functions[i](*_lhs_ptr, *_rhs_ptr) /
_trace_factors[i];
};
}
_sum = [this, learning_mode]() {
return mimkl::linear_algebra::aggregate_trace_normalized_kernels(
*_lhs_ptr, *_rhs_ptr, _kernel_functions, _trace_factors,
learning_mode);
};
_weighted_sum = [this, learning_mode](const Column &kernels_weights) {
return mimkl::linear_algebra::aggregate_weighted_trace_normalized_kernels(
*_lhs_ptr, *_rhs_ptr, _kernel_functions, _trace_factors,
learning_mode, kernels_weights);
};
}
else
{ // no trace_normalization
_square_brakets = [this](const Index i) {
return _kernel_functions[i](*_lhs_ptr, *_rhs_ptr);
};
_sum = [this]() {
return mimkl::linear_algebra::aggregate_kernels(
*_lhs_ptr, *_rhs_ptr, _kernel_functions);
};
_weighted_sum = [this](const Column &kernels_weights) {
return mimkl::linear_algebra::aggregate_weighted_kernels(
*_lhs_ptr, *_rhs_ptr, _kernel_functions, kernels_weights);
};
}
}
_logger->debug("set_lambdas() done");
}
template <typename Scalar, typename Kernel>
void KernelsHandler<Scalar, Kernel>::precompute_kernel_matrices(
const bool trace_normalization, const bool learning_mode)
{
_logger->debug("precompute_kernel_matrices() start");
if (trace_normalization && !learning_mode &&
_trace_factors.size() != _number_of_kernels)
throw std::logic_error("The trace_factors must first be learned");
_kernel_matrices.resize(_number_of_kernels);
if (trace_normalization)
{
if (learning_mode)
{ // learn and apply trace_factors
_trace_factors.resize(_number_of_kernels);
_logger->debug("trace_normalization true, is_symmetric true");
for (Index i = 0; i < _number_of_kernels; ++i)
{
_kernel_matrices[i] = _kernel_functions[i](*_lhs_ptr, *_rhs_ptr);
_trace_factors[i] =
mimkl::linear_algebra::trace_normalize(_kernel_matrices[i]);
_logger->trace("precomputed kernel {}, trace is {}, "
"trace_factor is {}",
i, _kernel_matrices[i].trace(), _trace_factors[i]);
}
}
else
{ // apply learned trace_factors
_logger->debug("trace_normalization true, is_symmetric false");
for (Index i = 0; i < _number_of_kernels; ++i)
{
_kernel_matrices[i] = _kernel_functions[i](*_lhs_ptr, *_rhs_ptr);
_kernel_matrices[i] /= _trace_factors[i];
_logger->trace("precomputed kernel {}, trace is {}, corrected "
"by factor {}",
i, _kernel_matrices[i].trace(), _trace_factors[i]);
}
}
}
else
{
_logger->debug("trace_normalization false");
for (Index i = 0; i < _number_of_kernels; ++i)
{
_kernel_matrices[i] = _kernel_functions[i](*_lhs_ptr, *_rhs_ptr);
_logger->trace("precomputed kernel {}, trace is {}", i,
_kernel_matrices[i].trace());
}
}
_logger->debug("precompute_kernel_matrices() done");
}
template <typename Scalar, typename Kernel>
typename KernelsHandler<Scalar, Kernel>::Matrix
KernelsHandler<Scalar, Kernel>::get_lhs() const
{
return (_lhs_ptr != nullptr) ? Matrix(*_lhs_ptr.get()) : Matrix();
}
template <typename Scalar, typename Kernel>
Index KernelsHandler<Scalar, Kernel>::get_lhs_size() const
{
return _lhs_size;
}
template <typename Scalar, typename Kernel>
Index KernelsHandler<Scalar, Kernel>::get_rhs_size() const
{
return _rhs_size;
}
template <typename Scalar, typename Kernel>
bool KernelsHandler<Scalar, Kernel>::get_precompute() const
{
return _precompute;
}
template <typename Scalar, typename Kernel>
bool KernelsHandler<Scalar, Kernel>::get_trace_normalization() const
{
return _trace_normalization;
}
template <typename Scalar, typename Kernel>
Index KernelsHandler<Scalar, Kernel>::get_number_of_kernels() const
{
return _number_of_kernels;
}
template <typename Scalar, typename Kernel>
std::vector<Kernel> KernelsHandler<Scalar, Kernel>::get_functions() const
{
return _kernel_functions;
}
template <typename Scalar, typename Kernel>
std::vector<typename KernelsHandler<Scalar, Kernel>::Matrix>
KernelsHandler<Scalar, Kernel>::get_matrices() const
{
return _kernel_matrices;
}
template <typename Scalar, typename Kernel>
std::vector<Scalar> KernelsHandler<Scalar, Kernel>::get_trace_factors() const
{
return _trace_factors;
}
template <typename Scalar, typename Kernel>
void KernelsHandler<Scalar, Kernel>::set_lhs(const Matrix &lhs)
{
_logger->debug("set_lhs() start");
if (_kernel_functions.size() == 0)
throw std::logic_error("Kernel functions were not provided");
if (_kernel_functions.size() != _number_of_kernels)
throw std::logic_error(
"Kernel functions are not matching the number of kernels");
// make sure both sides are released
_lhs_ptr.reset();
_rhs_ptr.reset();
_lhs_ptr = std::make_shared<Matrix>(lhs);
_rhs_ptr = std::shared_ptr<Matrix>(_lhs_ptr);
_lhs_size = lhs.rows();
_rhs_size = lhs.rows();
precompute_kernel_matrices(_trace_normalization, _trace_normalization);
set_lambdas(_precompute, _trace_normalization, _trace_normalization);
_logger->debug("set_lhs() done");
}
template <typename Scalar, typename Kernel>
void KernelsHandler<Scalar, Kernel>::set_rhs(const Matrix &rhs)
{
_logger->debug("set_rhs() start");
if (_kernel_functions.size() == 0)
throw std::logic_error("Kernel functions were not provided");
if (_kernel_functions.size() != _number_of_kernels)
throw std::logic_error(
"Kernel functions are not matching the number of kernels");
// make sure the old object is released
_rhs_ptr.reset();
_rhs_ptr = std::make_shared<Matrix>(rhs);
_rhs_size = rhs.rows();
if (_lhs_ptr == nullptr)
{
set_lambdas_to_throw();
return;
}
precompute_kernel_matrices(_trace_normalization, false);
set_lambdas(_precompute, _trace_normalization, false);
_logger->debug("set_rhs() done");
}
template <typename Scalar, typename Kernel>
void KernelsHandler<Scalar, Kernel>::set_matrices(
const std::vector<Matrix> &kernel_matrices, const bool learning_mode)
{
_logger->debug("set_matrices() start");
if (learning_mode && kernel_matrices[0].rows() != kernel_matrices[0].cols())
throw std::logic_error("The matrices must be squared");
// NOTE: think about the reset
// reset functions
// std::vector<Kernel>().swap(_kernel_functions);
_kernel_matrices = kernel_matrices;
_number_of_kernels = _kernel_matrices.size();
_lhs_size = _kernel_matrices[0].rows();
_rhs_size = _kernel_matrices[0].cols();
if (_trace_normalization)
{
if (learning_mode)
{
// learn trace_factors and apply
_trace_factors.resize(_number_of_kernels);
for (Index i = 0; i < _number_of_kernels; ++i)
{
_trace_factors[i] =
mimkl::linear_algebra::trace_normalize(_kernel_matrices[i]);
}
}
else
{
if (_trace_factors.size() != _number_of_kernels)
throw std::logic_error(
"The trace_factors have not been learned. Sizes don't match");
// apply trace_factors
for (Index i = 0; i < _number_of_kernels; ++i)
{
_kernel_matrices[i] /= _trace_factors[i];
}
}
}
set_lambdas(true, _trace_normalization, learning_mode);
_logger->debug("set_matrices() done");
}
template <typename Scalar, typename Kernel>
void KernelsHandler<Scalar, Kernel>::set_functions(
const std::vector<Kernel> &kernel_functions, const bool learning_mode)
{
_logger->debug("set_functions() start");
// NOTE: think about the reset
// reset matrices
// std::vector<Matrix>().swap(_kernel_matrices);
_kernel_functions = kernel_functions;
_number_of_kernels = _kernel_functions.size();
_lhs_size = 0;
_rhs_size = 0;
set_lambdas(_precompute, _trace_normalization, learning_mode);
_logger->debug("set_functions() done");
}
template <typename Scalar, typename Kernel>
void KernelsHandler<Scalar, Kernel>::set_trace_factors(
const std::vector<Scalar> &trace_factors)
{
_trace_factors = trace_factors;
}
} // namespace kernels_handler
} // namespace mimkl
#endif /* INCLUDE_MIMKL_KERNELS_KERNELS_HANDLER_HPP_ \
*/
| 34.960465 | 90 | 0.634271 | vishalbelsare |
6607510ee1374469ca0b67fd5bc57e30cbf19175 | 4,400 | hxx | C++ | win32/include/QUANTA/QUANTAnet_rbudpReceiver_c.hxx | benyaboy/sage-graphics | 090640167329ace4b6ad266d47db5bb2b0394232 | [
"Unlicense"
] | null | null | null | win32/include/QUANTA/QUANTAnet_rbudpReceiver_c.hxx | benyaboy/sage-graphics | 090640167329ace4b6ad266d47db5bb2b0394232 | [
"Unlicense"
] | null | null | null | win32/include/QUANTA/QUANTAnet_rbudpReceiver_c.hxx | benyaboy/sage-graphics | 090640167329ace4b6ad266d47db5bb2b0394232 | [
"Unlicense"
] | 1 | 2021-07-02T10:31:03.000Z | 2021-07-02T10:31:03.000Z | /******************************************************************************
* QUANTA - A toolkit for High Performance Data Sharing
* Copyright (C) 2003 Electronic Visualization Laboratory,
* University of Illinois at Chicago
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either Version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser Public License along
* with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Direct questions, comments etc about Quanta to cavern@evl.uic.edu
*****************************************************************************/
#ifndef _QUANTAPLUS_RBUDPRECEIVER_C
#define _QUANTAPLUS_RBUDPRECEIVER_C
#include <QUANTA/QUANTAnet_rbudpBase_c.hxx>
/**
RBUDP Receiver class. This class implements the receiver part of RBUDP protocol. First, instantiate the QUANTAnet_rbudpReceiver_c class. Then
call this object's init() method with the host name or IP address of the
sender as parameter. After the connection is established, you should
immediately call this object's receive(buffer, sizeofBuffer,
sizeofPacket) to receive a buffer. After you finish receiving all buffers,
you can call this object's close() to close this session.
*/
class QUANTAnet_rbudpReceiver_c : public QUANTAnet_rbudpBase_c
{
private:
struct msghdr msgRecv;
struct iovec iovRecv[2];
struct _rbudpHeader recvHeader;
void udpReceiveReadv();
void udpReceivevReadv();
void udpReceive();
void udpReceivev();
int initReceiveRudp(void* buffer, int bufSize, int pSize);
int initReceivevRbudp(QUANTA_iovec *iov, int iovcnt, int pSize);
public:
/** Constructor by telling which TCP and UDP ports we are going to use.
@ param port the TCP server port and UDP local and remote ports will be calculated based on it.
*/
QUANTAnet_rbudpReceiver_c(int port = 38000) {tcpPort = port;
udpLocalPort = port + 1;
udpRemotePort = port;
hasTcpSock = 0;
}
/** Constructor when we want to reuse exising TCP socket.
@ param tcpsock the TCP socket we are going to use in RBUDP.
@ param port UDP local and remote ports will be calculated based on it.
*/
QUANTAnet_rbudpReceiver_c(int tcpsock, int port) {
hasTcpSock = 1;
tcpSockfd = tcpsock;
udpLocalPort = port;
udpRemotePort = port;
}
~QUANTAnet_rbudpReceiver_c() {};
/** Receive a block of memory from the sender using RBUDP protocol.
@param buffer the pointer of the buffer you put the received data into.
@param bufSize the size of the received data. It has to be consistent with the sender.
@param packetSize payload size of each UDP packet, suggest 1460 considering the Ethernet MTU restriction and the header size. It has to be consistent with the sender.
*/
void receive(void * buffer, int bufSize, int packetSize);
/** Receive a list of blocks of memory from the sender using RBUDP protocol.
@param iov the starting pointer of the iovec struct
@param iovcnt the number of memory blocks.
@param packetSize payload size of each UDP packet, suggest 1460 considering the Ethernet MTU restriction and the header size. It has to be consistent with the sender.
*/
void receivev(QUANTA_iovec * iov, int iovcnt, int packetSize);
/** Receive a file from the sender using RBUDP protocol.
@param origFName the name of the file you want to get in sender side.
@param destFName the name of the file you want to save as in receiver side.
@param packetSize payload size of each UDP packet.
*/
int getfile(char * origFName, char * destFName, int packetSize);
/** Initialize a RBUDP session in the receiving side
@param remoteHost the name of the sending host.
*/
void init(char *remoteHost);
/// Close the RBUDP session.
void close();
};
#endif
| 42.718447 | 170 | 0.697727 | benyaboy |
660a6aa65cf0765eef4a5a396a834b4ac89e3cc1 | 6,780 | cpp | C++ | tech/Game/BeamWeapon.cpp | nbtdev/teardrop | fa9cc8faba03a901d1d14f655a04167e14cd08ee | [
"MIT"
] | null | null | null | tech/Game/BeamWeapon.cpp | nbtdev/teardrop | fa9cc8faba03a901d1d14f655a04167e14cd08ee | [
"MIT"
] | null | null | null | tech/Game/BeamWeapon.cpp | nbtdev/teardrop | fa9cc8faba03a901d1d14f655a04167e14cd08ee | [
"MIT"
] | null | null | null | /******************************************************************************
Copyright (c) 2015 Teardrop Games
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 "BeamWeapon.h"
#include "Component_Render.h"
#include "Component_Audio.h"
#include "Component_EquipmentSlot.h"
#include "Gfx/Mesh.h"
#include "Gfx/Submesh.h"
//#include "Gfx/VertexData.h"
//#include "Gfx/IndexData.h"
//#include "Gfx/VertexFormat.h"
#include "Gfx/Material.h"
#include "Gfx/ShaderConstantTable.h"
#include "Gfx/ShaderConstant.h"
//#include "Gfx/Util.h"
#include "Math/Matrix44.h"
#include "Math/MathUtil.h"
#include "Util/Environment.h"
using namespace Teardrop;
//---------------------------------------------------------------------------
TD_CLASS_IMPL(BeamWeapon);
//---------------------------------------------------------------------------
BeamWeapon::BeamWeapon()
{
m_pMountTransformConstant = 0;
m_animationTimeRemaining = 0;
m_recycleTimeRemaining = 0;
}
//---------------------------------------------------------------------------
BeamWeapon::~BeamWeapon()
{
}
//---------------------------------------------------------------------------
bool BeamWeapon::_initialize()
{
#if 0
// TODO: do this a different way
if (Environment::get().isServer)
return true;
m_inst.m_pProceduralMesh = TD_NEW GfxMesh;
m_inst.m_pProceduralMesh->initialize();
Gfx::Submesh* pSubmesh = m_inst.m_pProceduralMesh->createSubMesh();
pSubmesh->setPrimitiveType(TRISTRIP);
// beam vertex format: positions and single set of texcoord
GfxVertexFormat fmt;
GfxVertexFormat::Element elem;
elem.setSource(0);
elem.setUsage(0);
elem.offset = 0;
elem.semantic = POSITION;
elem.type = FLOAT3;
fmt.addElement(elem);
elem.semantic = TEXCOORD;
elem.type = FLOAT2;
elem.offset = (unsigned char)GfxUtil::getSizeOf(FLOAT3);
fmt.addElement(elem);
// beam is in the shape of a cylinder, 18 quads (36 tris) total in a
// tristrip, for a total of 38 verts
m_pVertexData = TD_NEW Vertex[38];
Vertex* pData = m_pVertexData;
// organize the vertex data into a cylinder, around the Z axis,
// 18 faces (so step around a circle by 20 degrees). Cylinder is
// 1 unit in length (length is along the +Z axis), with a radius
// of 0.1
float oo360 = 1.f / 360.f;
for (float d=360; d>=0; d-=20)
{
float i = d * oo360;
float r = i * MathUtil::PI;
float s = MathUtil::sin(r);
float c = MathUtil::cos(r);
float x = c * 0.1f;
float y = s * 0.1f;
// "near" point
pData->pz = 0;
pData->px = x;
pData->py = y;
pData->tx = i;
pData->ty = 0;
pData++;
// "far" point
pData->pz = -float(getRange());
pData->px = x;
pData->py = y;
pData->tx = i;
pData->ty = 1;
pData++;
}
size_t stream;
pSubmesh->createVertexData(
stream,
Environment::get(),
fmt.getVertexSize(),
38,
(GfxVertexData::CreationFlags)(GfxVertexData::STATIC|GfxVertexData::WRITE_ONLY),
m_pVertexData);
pSubmesh->setVertexFormat(Environment::get(), fmt);
// make a basic material for this mesh
GfxMaterial* pMtl = TD_NEW GfxMaterial;
pMtl->initialize();
pSubmesh->setMaterial(pMtl, true);
//pMtl->setEmissive(GfxUtil::makePackedColor(0,1,0,1));
pMtl->setEmissive(Vector4(0,1,0,1));
// set up shader constant(s) on the RenderComponent
RenderComponent* pComp;
if (findComponents(RenderComponent::getClassDef(), (Component**)&pComp))
{
GfxShaderConstantTable& constants = pComp->getShaderConstants();
constants.begin();
m_pMountTransformConstant = constants.addFloatConstant("mountTransform", 4);
constants.end();
}
#endif
return true;
}
//---------------------------------------------------------------------------
bool BeamWeapon::_destroy()
{
#if 0
if (m_inst.m_pProceduralMesh)
{
m_inst.m_pProceduralMesh->destroy();
delete m_inst.m_pProceduralMesh;
m_inst.m_pProceduralMesh = 0;
}
#endif
return true;
}
//---------------------------------------------------------------------------
bool BeamWeapon::_update(float deltaT)
{
m_recycleTimeRemaining -= deltaT;
m_animationTimeRemaining -= deltaT;
// do double-duty here -- update our components and at the same time, look
// for a RenderComponent
RenderComponent* pComp=0;
for (Components::iterator it = m_components.begin();
it != m_components.end(); ++it)
{
if (it->second->getDerivedClassDef() == RenderComponent::getClassDef())
{
pComp = static_cast<RenderComponent*>(it->second);
// turn off rendering if we are below zero in anim time remaining
pComp->setEnabled(m_animationTimeRemaining > 0);
}
// update component
it->second->update(deltaT);
}
if (m_animationTimeRemaining < 0 && m_recycleTimeRemaining < 0)
{
// early-out, we are entirely idle
return true;
}
#if 0
if (m_pMountTransformConstant)
{
const Matrix44& xform = m_pSlot->getTransform();
Matrix44 tmp;
xform.transpose(tmp);
// update shader constant(s) on the RenderComponent
m_pMountTransformConstant->setValue((Vector4*)&tmp);
}
if (pComp)
{
m_inst.setTransform(getTransformWS());
pComp->setMeshInstance(m_inst);
}
#endif
return true;
}
//---------------------------------------------------------------------------
void BeamWeapon::fire()
{
// only bother if we are recycled and ready
if (m_recycleTimeRemaining < 0)
{
// then we can turn on rendering by restarting these timers
m_recycleTimeRemaining = getRecycleTime();
m_animationTimeRemaining = getAnimationTime();
// and then play the internal fire sfx
AudioComponent* pAudio;
if (findComponents(AudioComponent::getClassDef(), (Component**)&pAudio))
{
// play the fire sound
pAudio->play2D(getFireSfx_Internal());
// and also line up the recycle sound
pAudio->play2D(getRecycleSfx(), getRecycleTime(), true);
}
}
}
| 29.478261 | 82 | 0.64823 | nbtdev |
660ae7a6f3d6dc183db47b9ec80d91bca9f86cd4 | 27,592 | ipp | C++ | include/External/stlib/packages/numerical/optimization/QuasiNewtonLBFGS.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/numerical/optimization/QuasiNewtonLBFGS.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/numerical/optimization/QuasiNewtonLBFGS.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | // -*- C++ -*-
/*
* C library of Limited memory BFGS (L-BFGS).
*
* Copyright (c) 1990, Jorge Nocedal
* Copyright (c) 2007,2008,2009 Naoaki Okazaki
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#if !defined(__QuasiNewtonLBFGS_ipp__)
#error This file is an implementation detail of the class QuasiNewtonLBFGS.
#endif
namespace numerical {
template<class _Function>
inline
typename QuasiNewtonLBFGS<_Function>::Number
QuasiNewtonLBFGS<_Function>::
minimize(Vector* x) {
if (_areThrowingExceptions) {
if (_areThrowingMaxComputationExceptions) {
return _minimize(x);
}
else {
try {
return _minimize(x);
}
catch (OptMaxComputationError&) {
_function.resetNumFunctionCalls();
Vector g(x->size());
return _function(*x, &g);
}
}
}
else {
try {
return _minimize(x);
}
catch (OptError&) {
_function.resetNumFunctionCalls();
Vector g(x->size());
return _function(*x, &g);
}
}
}
template<class _Function>
inline
typename QuasiNewtonLBFGS<_Function>::Number
QuasiNewtonLBFGS<_Function>::
_minimize(Vector* x) {
// Start the timer.
_timer.reset();
_timer.start();
const std::size_t n = x->size();
Number ys, yy;
Number beta;
Number fx = 0.;
Number rate = 0.;
/* Check the input parameters for errors. */
assert(n != 0);
_function.resetNumFunctionCalls();
/* Allocate working space. */
Vector xp(n, 0.), g(n, 0.), gp(n, 0.), d(n, 0.);
/* Allocate limited memory storage. */
std::vector<IterationData> lm(_m, IterationData(n));
/* Allocate an array for storing previous values of the objective function. */
Vector pf(_past, 0.);
/* Evaluate the function value and its gradient. */
fx = _function(*x, &g);
/* Store the initial value of the objective function. */
if (! pf.empty()) {
pf[0] = fx;
}
/*
Compute the direction;
we assume the initial hessian matrix H_0 is the identity matrix.
*/
for (std::size_t i = 0; i != d.size(); ++i) {
d[i] = -g[i];
}
// Make sure that the initial variables are not a minimizer.
if (hasGradientConverged(*x, g)) {
return fx;
}
// Compute the initial step.
Number step = 1. / std::sqrt(dot(d, d));
std::size_t j;
std::size_t k = 1;
std::size_t end = 0;
for (;;) {
/* Store the current position and gradient vectors. */
std::copy(x->begin(), x->end(), xp.begin());
std::copy(g.begin(), g.end(), gp.begin());
/* Search for an optimal step. */
try {
lineSearch(x, &fx, &g, d, &step, xp);
}
catch (OptError&) {
/* Revert to the previous point. */
std::copy(xp.begin(), xp.end(), x->begin());
std::copy(gp.begin(), gp.end(), g.begin());
throw;
}
// Check for gradient convergence.
if (hasGradientConverged(*x, g)) {
break;
}
/*
Test for stopping criterion.
The criterion is given by the following formula:
(f(past_x) - f(x)) / f(x) < \delta
*/
if (! pf.empty()) {
/* We don't test the stopping criterion while k < past. */
if (_past <= k) {
/* Compute the relative improvement from the past. */
rate = (pf[k % _past] - fx) / fx;
/* The stopping criterion. */
if (rate < _delta) {
break;
}
}
/* Store the current value of the objective function. */
pf[k % _past] = fx;
}
if (_maxIterations != 0 && _maxIterations < k+1) {
throw OptMaxIterationsError("In QuasiNewtonLBFGS::_minimize(): Maximum number of iterations reached.");
}
// Check if we have exceeded the maximum allowed time.
_timer.stop();
if (_timer > _maxTime) {
throw OptMaxTimeError("In QuasiNewtonLBFGS::_minimize(): The maximum allowed time has been exceeded.");
}
_timer.start();
{
/*
Update vectors s and y:
s_{k+1} = x_{k+1} - x_{k} = \step * d_{k}.
y_{k+1} = g_{k+1} - g_{k}.
*/
IterationData& it = lm[end];
for (std::size_t i = 0; i != it.s.size(); ++i) {
it.s[i] = (*x)[i] - xp[i];
it.y[i] = g[i] - gp[i];
}
/*
Compute scalars ys and yy:
ys = y^t \cdot s = 1 / \rho.
yy = y^t \cdot y.
Notice that yy is used for scaling the hessian matrix H_0
(Cholesky factor).
*/
ys = dot(it.y, it.s);
yy = dot(it.y, it.y);
it.ys = ys;
}
/*
Recursive formula to compute dir = -(H \cdot g).
This is described in page 779 of:
Jorge Nocedal.
Updating Quasi-Newton Matrices with Limited Storage.
Mathematics of Computation, Vol. 35, No. 151,
pp. 773--782, 1980.
*/
const std::size_t bound = (_m <= k) ? _m : k;
++k;
end = (end + 1) % _m;
/* Compute the steepest direction. */
/* Compute the negative of gradients. */
for (std::size_t i = 0; i != d.size(); ++i) {
d[i] = -g[i];
}
j = end;
for (std::size_t i = 0; i != bound; ++i) {
j = (j + _m - 1) % _m; /* if (--j == -1) j = _m-1; */
IterationData& it = lm[j];
/* \alpha_{j} = \rho_{j} s^{t}_{j} \cdot q_{k+1}. */
it.alpha = dot(it.s, d);
it.alpha /= it.ys;
/* q_{i} = q_{i+1} - \alpha_{i} y_{i}. */
for (std::size_t i = 0; i != d.size(); ++i) {
d[i] -= it.alpha * it.y[i];
}
}
d *= ys / yy;
for (std::size_t i = 0; i != bound; ++i) {
IterationData& it = lm[j];
/* \beta_{j} = \rho_{j} y^t_{j} \cdot \gamma_{i}. */
beta = dot(it.y, d);
beta /= it.ys;
/* \gamma_{i+1} = \gamma_{i} + (\alpha_{j} - \beta_{j}) s_{j}. */
for (std::size_t i = 0; i != d.size(); ++i) {
d[i] += (it.alpha - beta) * it.s[i];
}
j = (j + 1) % _m; /* if (++j == _m) j = 0; */
}
/*
Now the search direction d is ready. We try step = 1 first.
*/
step = 1.0;
}
return fx;
}
template<class _Function>
inline
typename QuasiNewtonLBFGS<_Function>::Number
QuasiNewtonLBFGS<_Function>::
minimizeIllConditioned(Vector* x, const std::size_t groupSize) {
if (_areThrowingExceptions) {
if (_areThrowingMaxComputationExceptions) {
return _minimizeIllConditioned(x, groupSize);
}
else {
try {
return _minimizeIllConditioned(x, groupSize);
}
catch (OptMaxComputationError&) {
_function.resetNumFunctionCalls();
Vector g(x->size());
return _function(*x, &g);
}
}
}
else {
try {
return _minimizeIllConditioned(x, groupSize);
}
catch (OptError&) {
_function.resetNumFunctionCalls();
Vector g(x->size());
return _function(*x, &g);
}
}
}
template<class _Function>
inline
typename QuasiNewtonLBFGS<_Function>::Number
QuasiNewtonLBFGS<_Function>::
_minimizeIllConditioned(Vector* x, const std::size_t groupSize) {
typedef FunctionOfSelectedCoordinates<ObjectiveFunction<Function> > Fosc;
assert(groupSize > 0 && x->size() % groupSize == 0);
std::size_t oldGroup = x->size() / groupSize;
for (std::size_t i = 0; i != _maxResetIllConditioned; ++i) {
try {
// Return the minima if we can calculate it.
return _minimize(x);
}
catch (OptError&) {
// Determine the group with the maximum gradient.
std::size_t group = findGroupWithMaximumGradient(*x, groupSize);
// If it is the same group as last time then the last attempt to
// improve the condition was not sufficient.
if (group == oldGroup) {
throw OptError("In QuasiNewtonLBFGS::minimizeIllConditioned(): Unable to substantially improve an ill-conditioned problem.");
}
oldGroup = group;
// Select the coordinates in the group.
std::vector<std::size_t> indices(groupSize);
Vector y(groupSize);
for (std::size_t j = 0; j != groupSize; ++j) {
indices[j] = group * groupSize + j;
y[j] = (*x)[indices[j]];
}
// Perform a minimization on those coordinates.
Fosc f(_function, *x, indices);
ConjugateGradient<Fosc> opt(f);
try {
// Minimize on the selected coordinates.
opt.minimize(&y);
// Update the selected coordinates.
for (std::size_t j = 0; j != groupSize; ++j) {
(*x)[indices[j]] = y[j];
}
}
catch (OptError& error) {
throw OptError(std::string("In QuasiNewtonLBFGS::minimizeIllConditioned(): Failed minimization on selected coordinates of an ill-conditioned problem. ") + error.what());
}
}
}
throw OptMaxIterationsError("In QuasiNewtonLBFGS::minimizeIllConditioned(): Maximum number of resets for an ill-conditioned problem has been exceeded.");
return 0;
}
template<class _Function>
inline
bool
QuasiNewtonLBFGS<_Function>::
hasGradientConverged(const Vector& x, const Vector& g) const {
/* Compute x and g norms. */
const Number xnorm = std::max(std::sqrt(dot(x, x)), 1.);
const Number gnorm = std::sqrt(dot(g, g));
/*
Relative gradient convergence test.
The criterion is given by the following formula:
|g(x)| / \max(1, |x|) < \epsilon
*/
if (gnorm <= _relativeGradientTolerance * xnorm) {
/* Convergence. */
return true;
}
// RMS gradient convergence test.
// ||g|| / sqrt(n) < epsilon
// Formulate to avoid the square root and division.
if (gnorm * gnorm <
_rmsGradientTolerance * _rmsGradientTolerance * g.size()) {
return true;
}
// If we are checking the maximum component of the gradient.
if (_maxGradientTolerance != 0) {
Number maximum = 0;
Number magnitude;
for (std::size_t i = 0; i != g.size(); ++i) {
magnitude = std::abs(g[i]);
if (magnitude > maximum) {
maximum = magnitude;
}
}
if (maximum < _maxGradientTolerance) {
return true;
}
}
return false;
}
template<class _Function>
inline
std::size_t
QuasiNewtonLBFGS<_Function>::
findGroupWithMaximumGradient(const Vector& x, const std::size_t groupSize) {
Vector gradient(x.size());
_function(x, &gradient);
const std::size_t numGroups = x.size() / groupSize;
std::size_t maxGroup = 0;
Number maxSquaredGradient = 0;
for (std::size_t g = 0; g != numGroups; ++g) {
Number s = 0;
for (std::size_t i = 0; i != groupSize; ++i) {
s += gradient[g * groupSize + i] * gradient[g * groupSize + i];
}
if (s > maxSquaredGradient) {
maxGroup = g;
maxSquaredGradient = s;
}
}
return maxGroup;
}
template<class _Function>
inline
void
QuasiNewtonLBFGS<_Function>::
lineSearch(Vector* x,
Number* f,
Vector* g,
const Vector& s, // The search direction.
Number* stp,
const Vector& xp) {
std::size_t count = 0;
Number dg;
Number stx, fx, dgx;
Number sty, fy, dgy;
Number fxm, dgxm, fym, dgym, fm, dgm;
Number finit, ftest1, dgtest;
Number width, previousWidth;
Number stmin, stmax;
/* Check the input parameters for errors. */
if (*stp <= 0.) {
throw OptStepError("In QuasiNewtonLBFGS::lineSearch(): Non-positive step size.");
}
/* Compute the initial gradient in the search direction. */
Number dginit = dot(*g, s);
/* Make sure that s points to a descent direction. */
if (0 < dginit) {
throw OptStepError("In QuasiNewtonLBFGS::lineSearch(): Bad descent direction.");
}
/* Initialize local variables. */
bool isBracketed = false;
bool stage1 = true;
finit = *f;
dgtest = _ftol * dginit;
width = _maxStep - _minStep;
previousWidth = 2.0 * width;
/*
The variables stx, fx, dgx contain the values of the step,
function, and directional derivative at the best step.
The variables sty, fy, dgy contain the value of the step,
function, and derivative at the other endpoint of
the interval of uncertainty.
The variables stp, f, dg contain the values of the step,
function, and derivative at the current step.
*/
stx = sty = 0.;
fx = fy = finit;
dgx = dgy = dginit;
for (;;) {
/*
Set the minimum and maximum steps to correspond to the
present interval of uncertainty.
*/
if (isBracketed) {
stmin = std::min(stx, sty);
stmax = std::max(stx, sty);
}
else {
stmin = stx;
stmax = *stp + 4.0 * (*stp - stx);
}
/* Clip the step in the range of [stpmin, stpmax]. */
if (*stp < _minStep) {
*stp = _minStep;
}
if (_maxStep < *stp) {
*stp = _maxStep;
}
/*
If an unusual termination is to occur then let
stp be the lowest point obtained so far.
*/
if ((isBracketed && ((*stp <= stmin || stmax <= *stp) || _maxLinesearch <= count + 1)) || (isBracketed && (stmax - stmin <= _xtol * stmax))) {
*stp = stx;
}
/*
Compute the current value of x:
x <- x + (*stp) * s.
*/
for (std::size_t i = 0; i != x->size(); ++i) {
(*x)[i] = xp[i] + *stp * s[i];
}
/* Evaluate the function and gradient values. */
*f = _function(*x, g);
dg = dot(*g, s);
ftest1 = finit + *stp * dgtest;
++count;
/* Test for errors and convergence. */
if (isBracketed && (*stp <= stmin || stmax <= *stp)) {
throw OptError("In QuasiNewtonLBFGS::lineSearch(): Rounding errors prevent further progress.");
}
if (*stp == _maxStep && *f <= ftest1 && dg <= dgtest) {
throw OptStepError("In QuasiNewtonLBFGS::lineSearch(): The step is the maximum value.");
}
if (*stp == _minStep && (ftest1 < *f || dgtest <= dg)) {
std::ostringstream message;
message << "In QuasiNewtonLBFGS::lineSearch():\n"
<< " The step is the minimum value.\n"
<< " *stp = " << *stp << '\n'
<< " _minStep = " << _minStep << '\n';
throw OptStepError(message.str());
}
if (isBracketed && (stmax - stmin) <= _xtol * stmax) {
throw OptError("In QuasiNewtonLBFGS::lineSearch(): Relative width of the interval of uncertainty is too small.");
}
if (_maxLinesearch <= count) {
throw OptMaxIterationsError("In QuasiNewtonLBFGS::lineSearch(): Maximum number of iterations.");
}
if (*f <= ftest1 && std::abs(dg) <= _gtol * (-dginit)) {
/* The sufficient decrease condition and the directional derivative condition hold. */
break;
}
/*
In the first stage we seek a step for which the modified
function has a nonpositive value and nonnegative derivative.
*/
if (stage1 && *f <= ftest1 && std::min(_ftol, _gtol) * dginit <= dg) {
stage1 = false;
}
/*
A modified function is used to predict the step only if
we have not obtained a step for which the modified
function has a nonpositive function value and nonnegative
derivative, and if a lower function value has been
obtained but the decrease is not sufficient.
*/
if (stage1 && ftest1 < *f && *f <= fx) {
/* Define the modified function and derivative values. */
fm = *f - *stp * dgtest;
fxm = fx - stx * dgtest;
fym = fy - sty * dgtest;
dgm = dg - dgtest;
dgxm = dgx - dgtest;
dgym = dgy - dgtest;
/*
Call updateTrialInterval() to update the interval of
uncertainty and to compute the new step.
*/
updateTrialInterval(&stx, &fxm, &dgxm,
&sty, &fym, &dgym,
stp, &fm, &dgm,
stmin, stmax, &isBracketed);
/* Reset the function and gradient values for f. */
fx = fxm + stx * dgtest;
fy = fym + sty * dgtest;
dgx = dgxm + dgtest;
dgy = dgym + dgtest;
}
else {
/*
Call update_trial_interval() to update the interval of
uncertainty and to compute the new step.
*/
updateTrialInterval(&stx, &fx, &dgx,
&sty, &fy, &dgy,
stp, f, &dg,
stmin, stmax, &isBracketed);
}
/*
Force a sufficient decrease in the interval of uncertainty.
*/
if (isBracketed) {
if (0.66 * previousWidth <= std::abs(sty - stx)) {
*stp = stx + 0.5 * (sty - stx);
}
previousWidth = width;
width = std::abs(sty - stx);
}
}
}
template<class _Function>
inline
void
QuasiNewtonLBFGS<_Function>::
updateTrialInterval(Number* x, Number* fx, Number* dx,
Number* y, Number* fy, Number* dy,
Number* t, Number* ft, Number* dt,
const Number tmin, const Number tmax, bool* isBracketed) {
const bool dsign = *dt * (*dx / std::abs(*dx)) < 0.;
/* Check the input parameters for errors. */
if (*isBracketed) {
if (*t <= std::min(*x, *y) || std::max(*x, *y) <= *t) {
throw OptError("In QuasiNewtonLBFGS::updateTrialInterval: The trival value t is out of the interval.");
}
if (0. <= *dx * (*t - *x)) {
throw OptError("In QuasiNewtonLBFGS::updateTrialInterval: The function must decrease from x.");
}
if (tmax < tmin) {
throw OptError("In QuasiNewtonLBFGS::updateTrialInterval: Incorrect tmin and tmax specified.");
}
}
bool bound;
Number mc; /* minimizer of an interpolated cubic. */
Number mq; /* minimizer of an interpolated quadratic. */
Number newt; /* new trial value. */
/*
Trial value selection.
*/
if (*fx < *ft) {
/*
Case 1: a higher function value.
The minimum is bracketed. If the cubic minimizer is closer
to x than the quadratic one, the cubic one is taken, else
the average of the minimizers is taken.
*/
*isBracketed = true;
bound = true;
mc = cubicMinimizer(*x, *fx, *dx, *t, *ft, *dt);
mq = quadraticMinimizer(*x, *fx, *dx, *t, *ft);
if (std::abs(mc - *x) < std::abs(mq - *x)) {
newt = mc;
}
else {
newt = mc + 0.5 * (mq - mc);
}
}
else if (dsign) {
/*
Case 2: a lower function value and derivatives of
opposite sign. The minimum is bracketed. If the cubic
minimizer is closer to x than the quadratic (secant) one,
the cubic one is taken, else the quadratic one is taken.
*/
*isBracketed = true;
bound = false;
mc = cubicMinimizer(*x, *fx, *dx, *t, *ft, *dt);
mq = quadraticMinimizer(*x, *dx, *t, *dt);
if (std::abs(mc - *t) > std::abs(mq - *t)) {
newt = mc;
}
else {
newt = mq;
}
}
else if (std::abs(*dt) < std::abs(*dx)) {
/*
Case 3: a lower function value, derivatives of the
same sign, and the magnitude of the derivative decreases.
The cubic minimizer is only used if the cubic tends to
infinity in the direction of the minimizer or if the minimum
of the cubic is beyond t. Otherwise the cubic minimizer is
defined to be either tmin or tmax. The quadratic (secant)
minimizer is also computed and if the minimum is bracketed
then the the minimizer closest to x is taken, else the one
farthest away is taken.
*/
bound = true;
mc = cubicMinimizer(*x, *fx, *dx, *t, *ft, *dt, tmin, tmax);
mq = quadraticMinimizer(*x, *dx, *t, *dt);
if (*isBracketed) {
if (std::abs(*t - mc) < std::abs(*t - mq)) {
newt = mc;
}
else {
newt = mq;
}
}
else {
if (std::abs(*t - mc) > std::abs(*t - mq)) {
newt = mc;
}
else {
newt = mq;
}
}
}
else {
/*
Case 4: a lower function value, derivatives of the
same sign, and the magnitude of the derivative does
not decrease. If the minimum is not bracketed, the step
is either tmin or tmax, else the cubic minimizer is taken.
*/
bound = false;
if (*isBracketed) {
newt = cubicMinimizer(*t, *ft, *dt, *y, *fy, *dy);
}
else if (*x < *t) {
newt = tmax;
}
else {
newt = tmin;
}
}
/*
Update the interval of uncertainty. This update does not
depend on the new step or the case analysis above.
- Case a: if f(x) < f(t),
x <- x, y <- t.
- Case b: if f(t) <= f(x) && f'(t)*f'(x) > 0,
x <- t, y <- y.
- Case c: if f(t) <= f(x) && f'(t)*f'(x) < 0,
x <- t, y <- x.
*/
if (*fx < *ft) {
/* Case a */
*y = *t;
*fy = *ft;
*dy = *dt;
}
else {
/* Case c */
if (dsign) {
*y = *x;
*fy = *fx;
*dy = *dx;
}
/* Cases b and c */
*x = *t;
*fx = *ft;
*dx = *dt;
}
/* Clip the new trial value in [tmin, tmax]. */
if (tmax < newt) {
newt = tmax;
}
if (newt < tmin) {
newt = tmin;
}
/*
Redefine the new trial value if it is close to the upper bound
of the interval.
*/
if (*isBracketed && bound) {
mq = *x + 0.66 * (*y - *x);
if (*x < *y) {
if (mq < newt) {
newt = mq;
}
}
else {
if (newt < mq) {
newt = mq;
}
}
}
// Record the new trial value.
*t = newt;
}
template<class _Function>
inline
typename QuasiNewtonLBFGS<_Function>::Number
QuasiNewtonLBFGS<_Function>::
quadraticMinimizer(const Number u, const Number fu, const Number du,
const Number v, const Number fv) const {
const Number a = v - u;
return u + du / ((fu - fv) / a + du) / 2 * a;
}
/**
* Find a minimizer of an interpolated quadratic function.
* @param u The value of one point, u.
* @param du The value of f'(u).
* @param v The value of another point, v.
* @param dv The value of f'(v).
* @return The minimizer of the interpolated quadratic.
*/
template<class _Function>
inline
typename QuasiNewtonLBFGS<_Function>::Number
QuasiNewtonLBFGS<_Function>::
quadraticMinimizer(const Number u, const Number du, const Number v,
const Number dv) const {
const Number a = u - v;
return v + dv / (dv - du) * a;
}
/**
* Find a minimizer of an interpolated cubic function.
* @param u The value of one point, u.
* @param fu The value of f(u).
* @param du The value of f'(u).
* @param v The value of another point, v.
* @param fv The value of f(v).
* @param du The value of f'(v).
* @return The minimizer of the interpolated cubic.
*/
template<class _Function>
inline
typename QuasiNewtonLBFGS<_Function>::Number
QuasiNewtonLBFGS<_Function>::
cubicMinimizer(const Number u, const Number fu, const Number du,
const Number v, const Number fv, const Number dv) const {
const Number d = v - u;
const Number theta = (fu - fv) * 3 / d + du + dv;
Number p = std::abs(theta);
Number q = std::abs(du);
Number r = std::abs(dv);
const Number s = std::max(std::max(p, q), r);
/* gamma = s*sqrt((theta/s)**2 - (du/s) * (dv/s)) */
const Number a = theta / s;
Number gamma = s * std::sqrt(a * a - (du / s) * (dv / s));
if (v < u) {
gamma = -gamma;
}
p = gamma - du + theta;
q = gamma - du + gamma + dv;
r = p / q;
return u + r * d;
}
/**
* Find a minimizer of an interpolated cubic function.
* @param u The value of one point, u.
* @param fu The value of f(u).
* @param du The value of f'(u).
* @param v The value of another point, v.
* @param fv The value of f(v).
* @param du The value of f'(v).
* @param xmin The minimum value.
* @param xmax The maximum value.
* @return The minimizer of the interpolated cubic.
*/
template<class _Function>
inline
typename QuasiNewtonLBFGS<_Function>::Number
QuasiNewtonLBFGS<_Function>::
cubicMinimizer(const Number u, const Number fu, const Number du,
const Number v, const Number fv, const Number dv,
const Number xmin, const Number xmax) const {
const Number d = v - u;
const Number theta = (fu - fv) * 3 / d + du + dv;
Number p = std::abs(theta);
Number q = std::abs(du);
Number r = std::abs(dv);
const Number s = std::max(std::max(p, q), r);
/* gamma = s*sqrt((theta/s)**2 - (du/s) * (dv/s)) */
const Number a = theta / s;
Number gamma = s * std::sqrt(std::max(0., a * a - (du / s) * (dv / s)));
if (u < v) {
gamma = -gamma;
}
p = gamma - dv + theta;
q = gamma - dv + gamma + du;
r = p / q;
Number result;
if (r < 0. && gamma != 0.) {
result = v - r * d;
}
else if (a < 0) {
result = xmax;
}
else {
result = xmin;
}
return result;
}
} // namespace numerical
| 31.142212 | 182 | 0.532546 | bxl295 |
66106032c782c181eb5d898791ab9905580eca3f | 6,351 | cpp | C++ | src/bl_loader/test/src/main.cpp | dettmann/bolero | fa88be1a1d4ab1e2855d20f5429ac83ed5eb4925 | [
"BSD-3-Clause"
] | 51 | 2017-05-19T13:33:29.000Z | 2022-01-21T10:59:57.000Z | src/bl_loader/test/src/main.cpp | dettmann/bolero | fa88be1a1d4ab1e2855d20f5429ac83ed5eb4925 | [
"BSD-3-Clause"
] | 94 | 2017-05-19T19:44:07.000Z | 2021-12-15T13:40:59.000Z | src/bl_loader/test/src/main.cpp | dettmann/bolero | fa88be1a1d4ab1e2855d20f5429ac83ed5eb4925 | [
"BSD-3-Clause"
] | 31 | 2017-05-19T19:41:39.000Z | 2021-08-25T14:14:19.000Z | #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include <catch/catch.hpp>
#include <LoadableBehavior.h>
#include <BLLoader.h>
#include <Optimizer.h>
#include <Environment.h>
#include <BehaviorSearch.h>
#include <PythonInterpreter.hpp>
#include <configmaps/ConfigData.h>
using namespace bolero;
using namespace bolero::bl_loader;
using namespace std;
TEST_CASE( "io", "[PythonInterpreter]" ) {
const PythonInterpreter& python = PythonInterpreter::instance();
shared_ptr<Module> functions = python.import("functions");
int intResult = functions->function("produce_int").call().returnObject()->asInt();
REQUIRE(intResult == 9);
double doubleResult = functions->function("produce_double").call().returnObject()->asDouble();
REQUIRE(doubleResult == 8.0);
bool boolResult = functions->function("produce_bool").call().returnObject()->asBool();
REQUIRE(boolResult == true);
std::string stringResult = functions->function("produce_string").call().returnObject()->asString();
REQUIRE(stringResult == "Test string");
functions->function("take_int").pass(bl_loader::INT).call(intResult);
functions->function("take_double").pass(bl_loader::DOUBLE).call(doubleResult);
functions->function("take_bool").pass(bl_loader::BOOL).call(boolResult);
functions->function("take_string").pass(bl_loader::STRING).call(&stringResult);
shared_ptr<ListBuilder> list = python.listBuilder();
list->pass(bl_loader::DOUBLE).build(1.0);
list->pass(bl_loader::DOUBLE).build(2.0);
list->pass(bl_loader::DOUBLE).build(3.0);
shared_ptr<std::vector<double> > vector = list->build()->as1dArray();
REQUIRE(vector->at(0) == 1.0);
REQUIRE(vector->at(1) == 2.0);
REQUIRE(vector->at(2) == 3.0);
}
TEST_CASE( "init test", "[PyLoadableBehavior]" ) {
bl_loader::BLLoader loader;
LoadableBehavior* behav = loader.acquireBehavior("TestBehavior");
REQUIRE_NOTHROW(behav->initialize("init.yaml"));
REQUIRE_NOTHROW(behav->init(3, 3));
REQUIRE(behav->getNumInputs() == 3);
REQUIRE(behav->getNumOutputs() == 3);
}
TEST_CASE( "configure and stepping", "[PyLoadableBehavior]" ) {
bl_loader::BLLoader loader;
LoadableBehavior* behav = loader.acquireBehavior("TestBehavior");
REQUIRE_NOTHROW(behav->initialize("init.yaml"));
REQUIRE_NOTHROW(behav->configure("config.yaml"));
REQUIRE_NOTHROW(behav->init(3, 3));
for(int i = 0; i < 5; ++i)
{
REQUIRE(behav->canStep());
double data[3] = {1, 2, 3}; //the test_behavior expects these inputs
behav->setInputs(data, 3);
behav->step();
behav->getOutputs(data, 3);
//step multiplies the data with the multiplier specified in the config file, in this case -1
REQUIRE(data[0] == -1);
REQUIRE(data[1] == -2);
REQUIRE(data[2] == -3);
data[0] = 1;
data[1] = 2;
data[2] = 3;
}
//The test behavior only allows 5 steps
REQUIRE(!behav->canStep());
}
TEST_CASE("loading and releasing", "[PyLoadableBehavior]") {
bl_loader::BLLoader loader;
REQUIRE_NOTHROW(loader.acquireBehavior("TestBehavior"));
REQUIRE_NOTHROW(loader.releaseLibrary("TestBehavior"));
}
TEST_CASE("acquire twice", "[PyLoadableBehavior]") {
bl_loader::BLLoader loader;
LoadableBehavior* b = loader.acquireBehavior("TestBehavior");
LoadableBehavior* b2 = loader.acquireBehavior("TestBehavior");
REQUIRE(b == b2);
}
TEST_CASE( "optimize", "[PyOptimizer]" ) {
// Load optimizer that is defined by "learning_config.yml"
bl_loader::BLLoader loader;
Optimizer* opt = loader.acquireOptimizer("Python");
int n_params = 3;
double params[n_params];
int n_feedbacks = 2;
double feedback[n_feedbacks];
// Required step: initialize optimizer
configmaps::ConfigMap map = configmaps::ConfigMap::fromYamlFile(
"learning_config.yml", true);
std::string config = map.toYamlString();
opt->init(n_params, config);
for(int i = 0; i < 200; i++)
{
REQUIRE(!opt->isBehaviorLearningDone());
// Required step: generate next possible solution
opt->getNextParameters(params, n_params);
// Compute feedback
feedback[0] = 10.0 - (params[0] + params[1]);
feedback[0] *= -feedback[0];
feedback[1] = 5.0 - params[2];
feedback[1] *= -feedback[1];
// Required step: tell the optimizer the performance of the solution
opt->setEvaluationFeedback(feedback, n_feedbacks);
}
opt->getBestParameters(params, n_params);
}
TEST_CASE( "environment", "[PyEnvironment]" ) {
// Load environment that is defined by "learning_config.yml"
bl_loader::BLLoader loader;
Environment* env = loader.acquireEnvironment("Python");
configmaps::ConfigMap map = configmaps::ConfigMap::fromYamlFile(
"learning_config.yml", true);
std::string config = map.toYamlString();
REQUIRE_NOTHROW(env->init(config));
REQUIRE_NOTHROW(env->reset());
REQUIRE(!env->isEvaluationDone());
REQUIRE(env->getNumInputs() == 3);
REQUIRE(env->getNumOutputs() == 0);
double params[3] = {0.0, 0.0, 0.0};
REQUIRE_NOTHROW(env->setInputs(params, 3));
REQUIRE_NOTHROW(env->stepAction());
double result[0];
REQUIRE_NOTHROW(env->getOutputs(result, 0));
REQUIRE(env->isEvaluationDone());
double feedback[1];
const int numFeedbacks = env->getFeedback(feedback);
REQUIRE(numFeedbacks == 1);
REQUIRE(Approx(-589729.9344730391) == feedback[0]);
REQUIRE(!env->isBehaviorLearningDone());
}
TEST_CASE( "behavior_search", "[PyBehaviorSearch]" ) {
// Load behavior search that is defined by "learning_config.yml"
bl_loader::BLLoader loader;
BehaviorSearch* bs = loader.acquireBehaviorSearch("Python");
configmaps::ConfigMap map = configmaps::ConfigMap::fromYamlFile(
"learning_config.yml", true);
std::string config = map.toYamlString();
REQUIRE_NOTHROW(bs->init(0, 3, config));
Behavior* beh = bs->getNextBehavior();
double outputs[3];
REQUIRE_NOTHROW(beh->getOutputs(outputs, 3));
REQUIRE(outputs[0] == Approx(1.764052346));
REQUIRE(outputs[1] == Approx(0.4001572084));
REQUIRE(outputs[2] == Approx(0.9787379841));
double feedback[1] = {0.0};
bs->setEvaluationFeedback(feedback, 1);
beh = bs->getBestBehavior();
REQUIRE_NOTHROW(beh->getOutputs(outputs, 3));
REQUIRE(outputs[0] == Approx(1.764052346));
REQUIRE(outputs[1] == Approx(0.4001572084));
REQUIRE(outputs[2] == Approx(0.9787379841));
REQUIRE(!bs->isBehaviorLearningDone());
}
| 36.291429 | 101 | 0.702724 | dettmann |
6614f85317377db14d1072c0519a80afa3ff5bc3 | 2,228 | cpp | C++ | Stp/Base/Thread/NativeThreadLinux.cpp | markazmierczak/Polonite | 240f099cafc5c38dc1ae1cc6fc5773e13f65e9de | [
"MIT"
] | 1 | 2019-07-11T12:47:52.000Z | 2019-07-11T12:47:52.000Z | Stp/Base/Thread/NativeThreadLinux.cpp | Polonite/Polonite | 240f099cafc5c38dc1ae1cc6fc5773e13f65e9de | [
"MIT"
] | null | null | null | Stp/Base/Thread/NativeThreadLinux.cpp | Polonite/Polonite | 240f099cafc5c38dc1ae1cc6fc5773e13f65e9de | [
"MIT"
] | 1 | 2019-07-11T12:47:53.000Z | 2019-07-11T12:47:53.000Z | // Copyright 2017 Polonite Authors. All rights reserved.
// Distributed under MIT license that can be found in the LICENSE file.
#include "Base/Thread/NativeThread.h"
#include "Base/String/StringSpan.h"
#if !OS(ANDROID)
# include <sched.h>
#endif
#if !OS(FREEBSD)
# include <sys/prctl.h>
#endif
namespace stp {
#if !OS(ANDROID)
ErrorCode NativeThread::SetPriority(NativeThreadObject thread, ThreadPriority priority) {
#ifdef SCHED_IDLE
if (priority == ThreadPriority::Idle) {
sched_param param = { 0 };
ErrorCode error = static_cast<PosixErrorCode>(
pthread_setschedparam(thread, SCHED_IDLE, ¶m));
if (!isOk(error)) {
// Unable to set idle policy for thread.
return error;
}
return ErrorCode();
}
#endif
if (priority == ThreadPriority::RealtimeAudio)
priority = ThreadPriority::TimeCritical;
int policy = SCHED_RR;
int min = sched_get_priority_min(policy);
int max = sched_get_priority_max(policy);
ASSERT(min != -1 && max != -1);
constexpr int MaxPriority = static_cast<int>(ThreadPriority::TimeCritical);
ASSERT(static_cast<int>(priority) <= MaxPriority);
int p = min + (max - min) * static_cast<int>(priority) / MaxPriority;
sched_param param = { p };
return static_cast<PosixErrorCode>(pthread_setschedparam(thread, policy, ¶m));
}
#endif // OS(*)
#if !OS(FREEBSD)
ErrorCode NativeThread::SetName(const char* name_cstr) {
// From spec:
// The name can be up to 16 bytes long, including the terminating null byte.
// (If the length of the string, including the terminating null byte,
// exceeds 16 bytes, the string is silently truncated.)
//
// Sometimes the name of thread begins with organization prefix, like:
// org.polonite.MyThread
//
constexpr int MaxNameLength = 16 - 1; // 1 for null character
auto name = StringSpan::fromCString(name_cstr);
if (name.length() > MaxNameLength) {
int dot_index = name.lastIndexOf('.');
if (dot_index >= 0)
name.removePrefix(dot_index + 1);
}
ASSERT(*(name.data() + name.length()) == '\0');
int rv = prctl(PR_SET_NAME, name.data());
if (rv != 0)
return getLastPosixErrorCode();
return ErrorCode();
}
#endif // OS(*)
} // namespace stp
| 28.564103 | 89 | 0.687163 | markazmierczak |
6615b6da69e0365ef7fd46868673ba7d440e2218 | 4,679 | cc | C++ | src/models/tests/bpsr_model.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | src/models/tests/bpsr_model.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | src/models/tests/bpsr_model.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | // -*- Mode: c++ -*-
// copyright (c) 2009 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com>
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/** Test that the BPSR model predicts the next observations well.
The BPSRModel gives probabilities of next observations.
It needs a full history of observations and actions to predict
the next observation.
However, it always has observations up to x_t and actions
up to a_{t-1}.
The BayesianPredictiveStateRepresentation shares the same
problem. The main difficulty is that the context in the BPSR
is defined via Factored Markov Chains.
The context in a FMC is the observation-action history from time
t-D to time t. It is necessary to have the context in the FMC in
order to find the right node in the context tree.
*/
#ifdef MAKE_MAIN
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include "BPSRModel.h"
#include "MersenneTwister.h"
#include "POMDPGridworld.h"
int main(int argc, char** argv) {
if (argc != 8) {
fprintf(stderr,
"Usage: bpsr_model n_obs tree_depth horizon maze_filename "
"maze_height maze_width model_type\n - model_type: BVMM CTW "
"FMC\n");
return -1;
}
#if 0
std::vector<real> rewards(4);
rewards[0] = -1.0;
rewards[1] = -0.1;
rewards[2] = 0.0;
rewards[3] = 1.0;
#else
std::vector<real> rewards(1);
rewards[0] = 0.0;
#endif
int n_actions = 4;
real random = 0.0;
int n_obs = atoi(argv[1]);
int tree_depth = atoi(argv[2]);
int T = atoi(argv[3]);
// std::string homedir(getenv("HOME"));
// std::string maze = homedir + "/projects/beliefbox/dat/maze5c";
std::string maze = argv[4];
int arg_maze_height = atoi(argv[5]);
int arg_maze_width = atoi(argv[6]);
POMDPGridworld environment(maze.c_str(), n_obs, arg_maze_height,
arg_maze_width, random);
if (n_obs != environment.getNObs()) {
Serror("Environment has %d obs instead of %d\n", environment.getNObs(),
n_obs);
}
// - select the model type -
std::string model_type_string = argv[7];
BPSRModel::ModelType model_type;
if (!model_type_string.compare("BVMM")) {
model_type = BPSRModel::BVMM;
} else if (!model_type_string.compare("CTW")) {
model_type = BPSRModel::CTW;
} else if (!model_type_string.compare("FMC")) {
model_type = BPSRModel::FACTORED_CHAIN;
} else {
Serror("Unknown model_type %s\n", model_type_string.c_str());
exit(-1);
}
// initialise model
BPSRModel model(n_obs, n_actions, rewards, tree_depth, model_type);
// initialise RNG
MersenneTwisterRNG mersenne_twister;
RandomNumberGenerator& rng = mersenne_twister;
rng.seed();
// start experiment
int observation = environment.getObservation();
model.Observe(observation, 0.0);
int prev_action = 0;
for (int t = 0; t < T; ++t) {
// environment.Show();
int state = environment.getState();
int action = rng.discrete_uniform(n_actions);
bool terminate = environment.Act(action);
observation = environment.getObservation();
real reward = environment.getReward();
real probability =
model.getTransitionProbability(action, observation, reward);
real sumP = 0;
printf("P: ");
for (int i = 0; i < n_obs; i++) {
for (int j = 0; j < (int)rewards.size(); j++) {
real P = model.getTransitionProbability(action, i, rewards[j]);
printf("%f ", P);
sumP += P;
}
}
printf(" | %f\n", sumP);
SMART_ASSERT(fabs(sumP - 1.0) < 10e-6)(sumP);
#if 1
real prob2 = model.Observe(action, observation, reward);
#else
real prob2;
if (action == prev_action) {
prob2 = model.Observe(action, 0, rewards[0]); // observation, reward);
} else {
prob2 = model.Observe(action, 1, rewards[0]); // observation, reward);
}
#endif
prev_action = action;
printf("%d %d %d %f %f %f # LOG\n", state, observation, action, reward,
probability, prob2);
if (terminate) {
environment.Reset();
}
}
}
#endif
| 31.193333 | 80 | 0.597564 | litlpoet |
6615cab18681d47a134aa425dc3414c6c8d1a9ba | 2,325 | cpp | C++ | src/gausskernel/cbb/instruments/slow_query/instr_slow_query_log.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 360 | 2020-06-30T14:47:34.000Z | 2022-03-31T15:21:53.000Z | src/gausskernel/cbb/instruments/slow_query/instr_slow_query_log.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 4 | 2020-06-30T15:09:16.000Z | 2020-07-14T06:20:03.000Z | src/gausskernel/cbb/instruments/slow_query/instr_slow_query_log.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 133 | 2020-06-30T14:47:36.000Z | 2022-03-25T15:29:00.000Z | /*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* instr_slow_query_log.cpp
*
* IDENTIFICATION
* src/gausskernel/cbb/instruments/slow_query/instr_slow_query_log.cpp
*
* -------------------------------------------------------------------------
*/
#include "c.h"
#include "postgres.h"
#include "knl/knl_variable.h"
#include "postmaster/syslogger.h"
#include "instruments/instr_slow_query_log.h"
static void write_slow_log_chunks(char *data, int len, bool end)
{
LogPipeProtoChunk p;
int fd = fileno(stderr);
int rc;
Assert(len > 0);
p.proto.nuls[0] = p.proto.nuls[1] = '\0';
p.proto.pid = t_thrd.proc_cxt.MyProcPid;
p.proto.logtype = LOG_TYPE_PLAN_LOG;
p.proto.magic = PROTO_HEADER_MAGICNUM;
/* write all but the last chunk */
while (len > LOGPIPE_MAX_PAYLOAD) {
p.proto.is_last = 'F';
p.proto.len = LOGPIPE_MAX_PAYLOAD;
rc = memcpy_s(p.proto.data, LOGPIPE_MAX_PAYLOAD, data, LOGPIPE_MAX_PAYLOAD);
securec_check(rc, "\0", "\0");
rc = write(fd, &p, LOGPIPE_HEADER_SIZE + LOGPIPE_MAX_PAYLOAD);
(void) rc;
data += LOGPIPE_MAX_PAYLOAD;
len -= LOGPIPE_MAX_PAYLOAD;
}
/* write the last chunk */
p.proto.is_last = end ? 'T' : 'F';
p.proto.len = len;
rc = memcpy_s(p.proto.data, LOGPIPE_MAX_PAYLOAD, data, len);
securec_check(rc, "\0", "\0");
rc = write(fd, &p, LOGPIPE_HEADER_SIZE + len);
(void) rc;
}
void write_local_slow_log(char *data, int len, bool end)
{
// send data to syslogger
if (t_thrd.role == SYSLOGGER || !t_thrd.postmaster_cxt.redirection_done) {
write_syslogger_file(data, len, LOG_DESTINATION_QUERYLOG);
} else {
write_slow_log_chunks(data, len, end);
}
}
| 31.418919 | 87 | 0.623226 | opengauss-mirror |
6618b29423eeb2e49c37bcc9cfc69cdd293210a0 | 3,024 | cpp | C++ | Monopoly/GameState.cpp | dragonly/Monopoly | 1dc013aed2bb49dd7c0c610df697f2bdfe282a8f | [
"MIT"
] | 3 | 2018-06-24T13:44:50.000Z | 2019-11-18T09:49:41.000Z | Monopoly/GameState.cpp | dragonly/Monopoly | 1dc013aed2bb49dd7c0c610df697f2bdfe282a8f | [
"MIT"
] | null | null | null | Monopoly/GameState.cpp | dragonly/Monopoly | 1dc013aed2bb49dd7c0c610df697f2bdfe282a8f | [
"MIT"
] | null | null | null | //
// GameState.cpp
// Monopoly
//
// Created by Dragonly on 4/27/16.
// Copyright © 2016 Dragonly. All rights reserved.
//
#include "GameState.hpp"
namespace monopoly {
GameState::GameState()
: today(2016, 5, 1), stockMarket() {
Land lands[] = { // this is just for initializing, don't do logic on it!!!
{"land", 0, 0, 0}, {"land", 0, 1, 0}, {"land", 0, 2, 0}, {"land", 0, 3, 0}, {"land", 0, 4, 0},
{"land", 0, 5, 0}, {"land", 0, 6, 0}, {"land", 0, 7, 0}, {"land", 1, 7, 1}, {"land", 1, 8, 1},
{"land", 1, 9, 1}, {"news", 1, 10, 1}, {"land", 2, 10, 1}, {"land", 3, 10, 1}, {"land", 4, 10, 1},
{"land", 4, 11, 2}, {"land", 4, 12, 2}, {"bank", 4, 13, 2}, {"land", 4, 14, 2}, {"land", 3, 14, 2},
{"land", 2, 14, 2}, {"land", 1, 14, 2}, {"land", 0, 14, 2}, {"lottery", 0, 15, 3}, {"land", 0, 16, 3},
{"land", 0, 17, 3}, {"land", 0, 18, 3}, {"coupon", 0, 19, 3}, {"land", 1, 19, 3}, {"land", 2, 19, 3},
{"land", 3, 19, 3}, {"land", 4, 19, 3}, {"land", 5, 19, 3}, {"land", 6, 19, 4}, {"land", 6, 18, 4},
{"blank", 6, 17, 4}, {"land", 6, 16, 4}, {"land", 7, 16, 4}, {"land", 8, 16, 4}, {"land", 8, 15, 4},
{"land", 8, 14, 4}, {"toolStore", 7, 14, 5}, {"land", 6, 14, 5}, {"land", 6, 13, 5}, {"land", 6, 12, 5},
{"land", 7, 12, 5}, {"land", 8, 12, 5}, {"gift", 9, 12, 5}, {"land", 9, 11, 5}, {"land", 9, 10, 5},
{"land", 9, 9, 5}, {"land", 8, 9, 6}, {"land", 7, 9, 6}, {"news", 6, 9, 6}, {"land", 6, 8, 6},
{"land", 6, 7, 6}, {"land", 6, 6, 6}, {"land", 5, 6, 6}, {"land", 5, 5, 6}, {"bank", 5, 4, 6},
{"land", 5, 3, 6}, {"land", 5, 2, 6}, {"land", 4, 2, 7}, {"land", 3, 2, 7}, {"land", 2, 2, 7},
{"lottery", 2, 1, 7}, {"land", 2, 0, 7}, {"land", 1, 0, 7}};
for (int i = 0; i < sizeof(lands)/sizeof(lands[0]); i++) {
road.push_back(Land(lands[i]));
streets[road[i].street].push_back(i);
}
state = GS::normal;
error = false;
gameover = false;
message = "";
errMsg = "";
playerIndex = 0;
lastRoll = -1;
}
Player& GameState::currentPlayer() {
return players[playerIndex];
}
Player& GameState::getPlayerByName(string name) {
for (int i = 0; i < players.size(); i++) {
if (players[i].name == name) {
return players[i];
}
}
return players[0]; // this is bad :( , but no fix for now
}
int GameState::streetPenalty(int streetNum, string owner) {
int ret = 0;
int x, y;
// road 本身的owner信息不可靠, 不用于判断, 只用于存储对应board位置和街道信息
for (auto i : streets[streetNum]) {
x = road[i].pos.first;
y = road[i].pos.second;
if (board[x][y].owner == owner) {
ret += road[i].basePrice * road[i].level;
}
}
ret *= 0.1;
return ret;
}
} | 43.2 | 116 | 0.425265 | dragonly |
6618cfd9989132492363adea803188e368724840 | 6,768 | cc | C++ | pigasus/software/tools/snort2lua/config_states/config_binding.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | pigasus/software/tools/snort2lua/config_states/config_binding.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | pigasus/software/tools/snort2lua/config_states/config_binding.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.
//
// 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.
//--------------------------------------------------------------------------
// config_binding.cc author Josh Rosenbaum <jrosenba@cisco.com>
#include <sstream>
#include <vector>
#include <stdexcept>
#include "conversion_state.h"
#include "helpers/converter.h"
#include "helpers/s2l_util.h"
#include "helpers/util_binder.h"
#include "helpers/parse_cmd_line.h"
#include "data/data_types/dt_comment.h"
#include <stdexcept>
namespace config
{
namespace
{
class Binding : public ConversionState
{
public:
Binding(Converter& c) : ConversionState(c) { }
bool convert(std::istringstream& data_stream) override;
private:
void add_vlan(const std::string& vlan, Binder&);
void add_policy_id(const std::string& id, Binder&);
void add_net(const std::string& net, Binder&);
};
} // namespace
typedef void (Binding::* binding_func)(const std::string&, Binder&);
void Binding::add_vlan(const std::string& vlan,
Binder& bind)
{
const std::size_t init_pos = vlan.find_first_of('-');
if (init_pos == std::string::npos)
{
std::size_t bad_char_pos;
const int vlan_id = std::stoi(vlan, &bad_char_pos);
if (bad_char_pos != vlan.size())
{
throw std::invalid_argument("Only numbers are allowed in "
"vlan IDs!! vlan " + vlan + "is invalid");
}
bind.add_when_vlan(std::to_string(vlan_id));
}
else
{
if (init_pos == 0 ||
init_pos != vlan.find_last_of('-') ||
(init_pos+1) == vlan.size())
{
throw std::invalid_argument("Vlan must be in the range [0,4095]");
}
std::size_t vlan1_pos;
const int vlan1 = std::stoi(vlan.substr(0, init_pos), &vlan1_pos);
std::size_t vlan2_pos;
const std::string vlan2_str = vlan.substr(init_pos+1);
const int vlan2 = std::stoi(vlan2_str, &vlan2_pos);
if ((vlan1_pos != init_pos) ||
(vlan2_pos != vlan2_str.size()))
{
throw std::invalid_argument("Only numbers are allowed in "
"vlan IDs!! vlan range " + vlan + "is invalid");
}
if (vlan1 < 0 || vlan2 > 4095 || vlan1 > vlan2)
{
throw std::out_of_range("Vlan must be in the range [0,4095]");
}
for (int i = vlan1; i <= vlan2; ++i)
bind.add_when_vlan(std::to_string(i));
}
}
void Binding::add_policy_id(const std::string& id,
Binder& bind)
{
std::size_t bad_char_pos;
const int policy_id = std::stoi(id, &bad_char_pos);
if (bad_char_pos != id.size())
{
throw std::invalid_argument("only numbers are allowed in Policy "
"IDs, but policy_id is " + id);
}
bind.set_when_ips_policy_id(policy_id);
}
void Binding::add_net(const std::string& net,
Binder& bind)
{
bind.add_when_net(net);
}
bool Binding::convert(std::istringstream& data_stream)
{
std::string binding_type;
std::string file;
std::string val;
binding_func func;
if ((!(data_stream >> file)) ||
(!(data_stream >> binding_type)))
return false;
if (binding_type == "policy_id")
func = &Binding::add_policy_id;
else if (binding_type == "vlan")
func = &Binding::add_vlan;
else if (binding_type == "net")
func = &Binding::add_net;
else
return false;
// we need at least one argument
if (!util::get_string(data_stream, val, ","))
return false;
auto& bind = cv.make_binder();
auto& net_bind = cv.make_binder();
net_bind.print_binding(false);
bool rc = true;
do
{
try
{
(this->*func)(val, bind);
(this->*func)(val, net_bind);
}
catch (const std::invalid_argument& e)
{
data_api.failed_conversion(data_stream, val + " -- " + e.what());
rc = false;
}
catch (const std::out_of_range& e)
{
data_api.failed_conversion(data_stream, val + " -- " + e.what());
rc = false;
}
}
while (util::get_string(data_stream, val, ","));
if (cv.get_parse_includes())
{
std::string full_name = data_api.expand_vars(file);
std::string full_path = full_name;
if (!util::file_exists(full_path))
full_path = parser::get_conf_dir() + full_name;
if (util::file_exists(full_path))
{
Converter bind_cv;
// This will ensure that the final output file contains
// lua syntax - even if there are only rules in the file
bind_cv.get_table_api().open_top_level_table("ips");
bind_cv.get_table_api().close_table();
//file = file + ".lua"; FIXIT-L file names should contain their original variables
file = full_path + ".lua";
if (bind_cv.convert(full_path, file, file, full_path + ".rej") < 0)
rc = false;
}
else
{
rc = false;
}
}
bool is_ips;
if ( cv.get_ips_pattern().empty() )
is_ips = false;
else if ( file.find(cv.get_ips_pattern()) != std::string::npos )
is_ips = true;
else
is_ips = false;
bind.set_use_file(file, is_ips ? Binder::IT_IPS : Binder::IT_FILE);
// FIXIT-H this resets network config by forcing network policy to swap with ips selection
if ( is_ips )
{
net_bind.set_use_file(file, Binder::IT_NETWORK);
net_bind.print_binding(true);
}
return rc;
}
/**************************
******* A P I ***********
**************************/
static ConversionState* ctor(Converter& c)
{ return new Binding(c); }
static const ConvertMap binding_api =
{
"binding",
ctor,
};
const ConvertMap* binding_map = &binding_api;
} // namespace config
| 28.082988 | 95 | 0.586879 | zhipengzhaocmu |
661975ec91a71aeb0ec9c0dd1429f627de00d2a9 | 12,852 | cpp | C++ | source/cpu/exec/exec.cpp | zhiayang/z86 | 708aa48f981dbba8025c83ae10918d42163da753 | [
"Apache-2.0"
] | 3 | 2020-10-12T15:52:20.000Z | 2021-02-07T08:40:03.000Z | source/cpu/exec/exec.cpp | zhiayang/z86 | 708aa48f981dbba8025c83ae10918d42163da753 | [
"Apache-2.0"
] | null | null | null | source/cpu/exec/exec.cpp | zhiayang/z86 | 708aa48f981dbba8025c83ae10918d42163da753 | [
"Apache-2.0"
] | null | null | null | // exec.cpp
// Copyright (c) 2020, zhiayang
// Licensed under the Apache License Version 2.0.
#include "defs.h"
#include "cpu/cpu.h"
#include "cpu/exec.h"
namespace z86
{
using Operand = instrad::x86::Operand;
using Register = instrad::x86::Register;
using Instruction = instrad::x86::Instruction;
using InstrMods = instrad::x86::InstrModifiers;
// jump.cpp
void op_jcxz(CPU& cpu, const InstrMods& mods, const Operand& dst);
void op_jo(CPU& cpu, const Operand& dst, bool check);
void op_js(CPU& cpu, const Operand& dst, bool check);
void op_ja(CPU& cpu, const Operand& dst, bool check);
void op_jz(CPU& cpu, const Operand& dst, bool check);
void op_jp(CPU& cpu, const Operand& dst, bool check);
void op_jl(CPU& cpu, const Operand& dst, bool check);
void op_jg(CPU& cpu, const Operand& dst, bool check);
void op_jc(CPU& cpu, const Operand& dst, bool check);
void op_jmp(CPU& cpu, const Operand& dst);
// jump.cpp
void op_call(CPU& cpu, const InstrMods& mods, const Operand& dst);
void op_retf(CPU& cpu, const Instruction& instr);
void op_ret(CPU& cpu, const Instruction& instr);
// arithmetic.cpp
void op_inc_dec(CPU& cpu, const instrad::x86::Op& op, const InstrMods& mods, const Operand& dst);
void op_arithmetic(CPU& cpu, const instrad::x86::Op& op, const InstrMods& mods, const Operand& dst, const Operand& src);
// adjust.cpp
void op_daa(CPU& cpu);
void op_das(CPU& cpu);
void op_aaa(CPU& cpu);
void op_aas(CPU& cpu);
void op_aad(CPU& cpu, uint8_t base);
void op_aam(CPU& cpu, uint8_t base);
static void op_xchg(CPU& cpu, const InstrMods& mods, const Operand& dst, const Operand& src);
static void op_mov(CPU& cpu, const InstrMods& mods, const Operand& dst, const Operand& src);
static void op_pop(CPU& cpu, const InstrMods& mods, const Operand& dst);
static void op_push(CPU& cpu, const InstrMods& mods, const Operand& src);
void Executor::execute(const Instruction& instr)
{
using namespace instrad::x86;
if(instr.lockPrefix())
m_cpu.memLock();
auto& op = instr.op();
switch(op.id())
{
case ops::ADD.id():
case ops::ADC.id():
case ops::SUB.id():
case ops::SBB.id():
case ops::AND.id():
case ops::OR.id():
case ops::XOR.id():
case ops::CMP.id():
case ops::TEST.id():
op_arithmetic(m_cpu, op, instr.mods(), instr.dst(), instr.src());
break;
case ops::INC.id():
case ops::DEC.id():
op_inc_dec(m_cpu, op, instr.mods(), instr.dst());
break;
case ops::CALL.id(): op_call(m_cpu, instr.mods(), instr.dst()); break;
case ops::RETF.id(): op_retf(m_cpu, instr); break;
case ops::RET.id(): op_ret(m_cpu, instr); break;
case ops::MOV.id(): op_mov(m_cpu, instr.mods(), instr.dst(), instr.src()); break;
case ops::PUSH.id(): op_push(m_cpu, instr.mods(), instr.dst()); break;
case ops::POP.id(): op_pop(m_cpu, instr.mods(), instr.dst()); break;
case ops::XCHG.id(): op_xchg(m_cpu, instr.mods(), instr.dst(), instr.src()); break;
case ops::DAA.id(): op_daa(m_cpu); break;
case ops::DAS.id(): op_das(m_cpu); break;
case ops::AAA.id(): op_aaa(m_cpu); break;
case ops::AAS.id(): op_aas(m_cpu); break;
case ops::AAM.id(): op_aam(m_cpu, instr.dst().imm() & 0xFF); break;
case ops::AAD.id(): op_aad(m_cpu, instr.dst().imm() & 0xFF); break;
case ops::JMP.id(): op_jmp(m_cpu, instr.dst()); break;
case ops::JO.id(): op_jo(m_cpu, instr.dst(), true); break;
case ops::JNO.id(): op_jo(m_cpu, instr.dst(), false); break;
case ops::JS.id(): op_js(m_cpu, instr.dst(), true); break;
case ops::JNS.id(): op_js(m_cpu, instr.dst(), false); break;
case ops::JZ.id(): op_jz(m_cpu, instr.dst(), true); break;
case ops::JNZ.id(): op_jz(m_cpu, instr.dst(), false); break;
case ops::JB.id(): op_jc(m_cpu, instr.dst(), true); break;
case ops::JNB.id(): op_jc(m_cpu, instr.dst(), false); break;
case ops::JA.id(): op_ja(m_cpu, instr.dst(), true); break;
case ops::JNA.id(): op_ja(m_cpu, instr.dst(), false); break;
case ops::JL.id(): op_jl(m_cpu, instr.dst(), true); break;
case ops::JGE.id(): op_jl(m_cpu, instr.dst(), false); break;
case ops::JG.id(): op_jg(m_cpu, instr.dst(), true); break;
case ops::JLE.id(): op_jg(m_cpu, instr.dst(), false); break;
case ops::JP.id(): op_jp(m_cpu, instr.dst(), true); break;
case ops::JNP.id(): op_jp(m_cpu, instr.dst(), false); break;
case ops::JCXZ.id(): op_jcxz(m_cpu, instr.mods(), instr.dst()); break;
// TODO: check privs
case ops::STI.id(): m_cpu.flags().setIF(true); break;
case ops::CLI.id(): m_cpu.flags().clearIF(); break;
case ops::CMC.id(): m_cpu.flags().setCF(!m_cpu.flags().CF()); break;
case ops::STC.id(): m_cpu.flags().setCF(true); break;
case ops::STD.id(): m_cpu.flags().setDF(true); break;
case ops::CLC.id(): m_cpu.flags().clearCF(); break;
case ops::CLD.id(): m_cpu.flags().clearDF(); break;
case ops::LAHF.id(): m_cpu.ah() = m_cpu.flags().flags() & 0xFF; break;
case ops::SAHF.id(): m_cpu.flags().setFrom(m_cpu.ah()); break;
case ops::PUSHF.id(): {
if(m_cpu.mode() == CPUMode::Long)
{
if(instr.mods().operandSizeOverride)
m_cpu.push16(m_cpu.flags().flags());
else
m_cpu.push64(m_cpu.flags().rflags() & 0xFFFF'FFFF'FFFC'0000);
}
else
{
switch(get_operand_size(m_cpu, instr.mods()))
{
case 16: m_cpu.push16(m_cpu.flags().flags()); break;
case 32: m_cpu.push32(m_cpu.flags().eflags() & 0xFFFC'0000); break;
default: assert(false);
}
}
} break;
case ops::POPF.id(): {
assert(m_cpu.mode() == CPUMode::Real);
switch(get_operand_size(m_cpu, instr.mods()))
{
case 16: m_cpu.flags().setFrom(m_cpu.pop16()); break;
case 32: m_cpu.flags().setFrom(m_cpu.pop32()); break;
default: assert(false);
}
} break;
default:
lg::fatal("exec", "invalid opcode: {}", print_att(instr, m_cpu.ip(), 0, 1));
break;
}
if(instr.lockPrefix())
m_cpu.memUnlock();
}
int get_operand_size(CPU& cpu, const InstrMods& mods, bool default64)
{
// TODO: i think this is broken for 64-bit.
if(cpu.mode() == CPUMode::Real)
{
return mods.operandSizeOverride
? 32
: 16;
}
else if(cpu.mode() == CPUMode::Prot || cpu.mode() == CPUMode::Long)
{
if(mods.operandSizeOverride) return 16;
else if(mods.rex.W()) return 64;
else return 32;
}
else
{
assert(false && "invalid cpu mode");
}
assert(false && "invalid operand size");
return 0;
}
int get_address_size(CPU& cpu, const InstrMods& mods)
{
if(cpu.mode() == CPUMode::Real)
{
return mods.addressSizeOverride
? 32
: 16;
}
else if(cpu.mode() == CPUMode::Prot || cpu.mode() == CPUMode::Long)
{
if(mods.addressSizeOverride) return 16;
else if(mods.rex.W()) return 64;
else return 32;
}
else
{
assert(false && "invalid cpu mode");
}
assert(false && "invalid address size");
return 0;
}
static SegReg convert_sreg(const Register& reg)
{
auto idx = reg.index();
assert(idx & instrad::x86::regs::REG_FLAG_SEGMENT);
return static_cast<SegReg>(idx & 0x7);
}
std::pair<SegReg, uint64_t> resolve_memory_access(CPU& cpu, const instrad::x86::MemoryRef& mem)
{
auto seg = SegReg::DS;
uint64_t ofs = 0;
uint64_t idx = 0;
if(mem.segment().present())
seg = convert_sreg(mem.segment());
if(cpu.mode() == CPUMode::Real)
{
ofs += mem.base().present() ? cpu.reg16(mem.base()) : 0;
idx = mem.index().present() ? cpu.reg16(mem.index()) : 0;
}
else if(cpu.mode() == CPUMode::Prot)
{
ofs += mem.base().present() ? cpu.reg32(mem.base()) : 0;
idx = mem.index().present() ? cpu.reg32(mem.index()) : 0;
}
else if(cpu.mode() == CPUMode::Long)
{
ofs += mem.base().present() ? cpu.reg64(mem.base()) : 0;
idx = mem.index().present() ? cpu.reg64(mem.index()) : 0;
}
else
{
assert(false && "invalid cpu mode");
}
ofs += mem.displacement();
ofs += idx * mem.scale();
// a little gross to repeat it here, but whatever...
if(cpu.mode() == CPUMode::Real) ofs &= 0xFFFF;
else if(cpu.mode() == CPUMode::Prot) ofs &= 0xFFFF'FFFF;
else if(cpu.mode() == CPUMode::Long) ofs &= 0xFFFF'FFFF'FFFF'FFFF;
else assert(false && "invalid cpu mode");
return { seg, ofs };
}
Value get_operand(CPU& cpu, const InstrMods& mods, const Operand& op)
{
if(op.isRegister())
{
switch(op.reg().width())
{
case 8: return cpu.reg8(op.reg());
case 16: return cpu.reg16(op.reg());
case 32: return cpu.reg32(op.reg());
case 64: return cpu.reg64(op.reg());
}
}
else if(op.isImmediate())
{
switch(op.immediateSize())
{
case 8: return Value(static_cast<uint8_t>(op.imm()));
case 16: return Value(static_cast<uint16_t>(op.imm()));
case 32: return Value(static_cast<uint32_t>(op.imm()));
case 64: return Value(static_cast<uint64_t>(op.imm()));
}
}
else if(op.isMemory())
{
auto [ seg, ofs ] = resolve_memory_access(cpu, op.mem());
switch(op.mem().bits())
{
case 8: return cpu.read8(seg, ofs);
case 16: return cpu.read16(seg, ofs);
case 32: return cpu.read32(seg, ofs);
case 64: return cpu.read64(seg, ofs);
}
}
// note: i'm deliberately *NOT* handling FarOffset here,
// because it's a little complicated, and in particular we might need to
// return 80-bit values, so it's better to just let the (small) handful of
// instructions that need it to handle it themselves.
assert(false && "invalid operand kind");
return static_cast<uint64_t>(0);
}
void set_operand(CPU& cpu, const InstrMods& mods, const Operand& op, Value value)
{
if(op.isRegister())
{
switch(op.reg().width())
{
case 8: {
uint8_t x = value.u8();
cpu.reg8(op.reg()) = x;
return;
}
case 16: cpu.reg16(op.reg()) = value.u16(); return;
case 32: cpu.reg32(op.reg()) = value.u32(); return;
case 64: cpu.reg64(op.reg()) = value.u64(); return;
}
}
else if(op.isMemory())
{
auto [ seg, ofs ] = resolve_memory_access(cpu, op.mem());
switch(op.mem().bits())
{
case 8: cpu.write8(seg, ofs, value.u8()); return;
case 16: cpu.write16(seg, ofs, value.u16()); return;
case 32: cpu.write32(seg, ofs, value.u32()); return;
case 64: cpu.write64(seg, ofs, value.u64()); return;
}
}
assert(false && "invalid destination operand kind");
}
static void op_xchg(CPU& cpu, const InstrMods& mods, const Operand& dst, const Operand& src)
{
// xchg always asserts the lock signal
cpu.memLock();
auto s = get_operand(cpu, mods, src);
auto d = get_operand(cpu, mods, dst);
set_operand(cpu, mods, dst, s);
set_operand(cpu, mods, src, d);
cpu.memUnlock();
}
static void op_push(CPU& cpu, const InstrMods& mods, const Operand& src)
{
auto src_val = get_operand(cpu, mods, src);
switch(src_val.bits())
{
case 8: return cpu.push8(src_val.u8());
case 16: return cpu.push16(src_val.u16());
case 32: return cpu.push32(src_val.u32());
case 64: return cpu.push64(src_val.u64());
}
assert(false && "owo");
}
static void op_pop(CPU& cpu, const InstrMods& mods, const Operand& dst)
{
auto bits = get_operand_size(cpu, mods) / 8;
switch(bits)
{
case 8: set_operand(cpu, mods, dst, cpu.pop8());
case 16: set_operand(cpu, mods, dst, cpu.pop16());
case 32: set_operand(cpu, mods, dst, cpu.pop32());
case 64: set_operand(cpu, mods, dst, cpu.pop64());
}
assert(false && "owo");
}
static void op_mov(CPU& cpu, const InstrMods& mods, const Operand& dst, const Operand& src)
{
auto src_val = get_operand(cpu, mods, src);
set_operand(cpu, mods, dst, src_val);
}
}
| 32.372796 | 121 | 0.569561 | zhiayang |
661ca9a24bd10b1c9fe0ba16796b698d9c94a3cc | 14,415 | cpp | C++ | Source/Teme/Tema1/Tema1.cpp | adinasm/EGC | 01b51ed98790635bcec723253a771d8b98c09b4b | [
"MIT"
] | null | null | null | Source/Teme/Tema1/Tema1.cpp | adinasm/EGC | 01b51ed98790635bcec723253a771d8b98c09b4b | [
"MIT"
] | null | null | null | Source/Teme/Tema1/Tema1.cpp | adinasm/EGC | 01b51ed98790635bcec723253a771d8b98c09b4b | [
"MIT"
] | null | null | null | #include "Tema1.h"
#include <vector>
#include <iostream>
#include <Core/Engine.h>
#include "Transform2D.h"
#include "Objects2D.h"
Tema1::Tema1()
{
angularStep = 0.f;
translateX = 0.f;
translateY = 0.f;
acceleration = -3500.f;
jumpAcceleration = 10000.f;
maxJumpY = 30.f;
currentJumpY = 0.f;
totalJumpY = 0.f;
jumping = false;
textureCount = 5;
playing = true;
score = 0;
scoreboardX = 0.f;
scoreboardY = 0.f;
first = true;
maxFloatAngle = (float)M_PI / 8;
minFloatAngle = -(float)M_PI / 8;
floatStep = 0.0f;
floatUp = true;
wingScaleY = 1.f;
maxWingScaleY = 2.f;
minWingScaleY = -2.f;
wingUp = true;
obstacleScale = 0.f;
maxObstacleScale = 1.f;
minObstacleScale = -1.f;
growObstacle = true;
}
Tema1::~Tema1()
{
}
void Tema1::Init()
{
glm::ivec2 resolution = window->GetResolution();
auto camera = GetSceneCamera();
camera->SetOrthographic(0, (float)resolution.x, 0, (float)resolution.y, 0.01f, 400);
camera->SetPosition(glm::vec3(0, 0, 50));
camera->SetRotation(glm::vec3(0, 0, 0));
camera->Update();
GetCameraInput()->SetActive(false);
acceleration = -(float)resolution.y * 5;
jumpAcceleration = (float)resolution.y * 14;
maxJumpY = (float)resolution.y / 21;
scoreboardX = (float)resolution.x / 4;
scoreboardY = (float)resolution.y / 4;
// Create meshes for obstacles, digits and the bird.
obstacles.initializeObstacles(meshes, (float)resolution.x, (float)resolution.y, textureCount);
digits.initializeDigits(meshes);
bird.createBird(meshes);
createTextures();
// Create mesh for the scoreboard.
Mesh* scoreboard = Objects2D::CreateScoreboard("scoreboard", glm::vec3(0.f, 0.f, 0.f), 100.f,
glm::vec3(0.078431f, 0.149019, 0.223529));
meshes[scoreboard->GetMeshID()] = scoreboard;
}
// Loads the textures and creates the shader for the obstacles.
void Tema1::createTextures()
{
const std::string textureLoc = "Source/Teme/Tema1/Textures/";
// Load textures.
for (int i = 0; i < textureCount; ++i)
{
Texture2D* texture = new Texture2D();
texture->Load2D((textureLoc + "crystal" + std::to_string(i) + ".jpg").c_str(), GL_REPEAT);
mapTextures["crystal" + std::to_string(i)] = texture;
}
{
Texture2D* texture = new Texture2D();
texture->Load2D((textureLoc + "background.jpg").c_str(), GL_REPEAT);
mapTextures["background"] = texture;
}
// Create a shader program.
{
Shader* shader = new Shader("ShaderT1");
shader->AddShader("Source/Teme/Tema1/Shaders/VertexShader.glsl", GL_VERTEX_SHADER);
shader->AddShader("Source/Teme/Tema1/Shaders/FragmentShader.glsl", GL_FRAGMENT_SHADER);
shader->CreateAndLink();
shaders[shader->GetName()] = shader;
}
}
void Tema1::FrameStart()
{
// clears the color buffer (using the previously set color) and depth buffer
glClearColor(0.607843f, 0.607843f, 0.607843f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::ivec2 resolution = window->GetResolution();
// sets the screen area where to draw
glViewport(0, 0, resolution.x, resolution.y);
}
void Tema1::Update(float deltaTimeSeconds)
{
// Does not apply any transformations on the objects from the first frame.
if (first)
{
first = false;
deltaTimeSeconds = 0.f;
}
// Prints the score if the player lost the game.
if (!playing)
{
printScore();
}
// Renders the obstacles and the bird.
updateStalactitesAndStalagmites(deltaTimeSeconds);
updateBird(deltaTimeSeconds);
// Renders the background.
glm::mat3 mm = Transform2D::Scale((float)window->GetResolution().x / 100.f, (float)window->GetResolution().y / 100.f);
glm::mat4 model = glm::mat4(
mm[0][0], mm[0][1], mm[0][2], 0.f,
mm[1][0], mm[1][1], mm[1][2], 0.f,
0.f, 0.f, mm[2][2], 0.f,
mm[2][0], mm[2][1], 0.f, 1.f);
RenderSimpleMesh(meshes["square"], shaders["ShaderT1"], model, mapTextures["background"]);
}
// Prints the score on the scoreboard.
void Tema1::printScore() {
glm::ivec2 resolution = window->GetResolution();
int c = score;
modelMatrix = Transform2D::Translate(scoreboardX * 3, scoreboardY * 2);
modelMatrix *= Transform2D::Scale(10.f, 10.f);
if (!c)
{
modelMatrix *= Transform2D::Translate(-10.f, 0.f);
RenderMesh2D(meshes[std::to_string(c)], shaders["VertexColor"], modelMatrix);
}
while (c)
{
modelMatrix *= Transform2D::Translate(-10.f, 0.f);
RenderMesh2D(meshes[std::to_string(c % 10)], shaders["VertexColor"], modelMatrix);
c /= 10;
}
float side = obstacles.getSquareSide();
modelMatrix = Transform2D::Translate(scoreboardX, scoreboardY);
modelMatrix *= Transform2D::Scale(2.f * scoreboardX / side, 2.f * scoreboardY / side);
RenderMesh2D(meshes["scoreboard"], shaders["VertexColor"], modelMatrix);
}
// Updates the position of the bird, flaps its wing and moves its tail.
void Tema1::updateBird(float deltaTimeSeconds)
{
updateBody();
updateHead();
if (playing)
{
translateY += acceleration * deltaTimeSeconds * deltaTimeSeconds / 2.f + currentJumpY;
angularStep += acceleration * deltaTimeSeconds / 10000.f;
updateJump(deltaTimeSeconds);
moveTail(deltaTimeSeconds);
moveWing(deltaTimeSeconds);
}
}
// Updates the position of the body, rotates the tail around the body and flaps the wing.
void Tema1::updateBody()
{
for (int i = -1; i < 2; ++i)
{
updateTailComponent("featherCircle", bird.getCircleCoordinates(), i);
updateTailComponent("feather", bird.getTailCoordinates(), i);
}
updateBirdComponent("wing", bird.getWingCoordinates());
updateBirdComponent("body", bird.getBodyCoordinates());
}
// Updates the positions of the head and its components.
void Tema1::updateHead()
{
updateBirdComponent("headDecoration", bird.getHeadDecorationCoordinates());
updateBirdComponent("iris", bird.getEyeCoordinates());
updateBirdComponent("eyeBall", bird.getEyeCoordinates());
updateBirdComponent("beak", bird.getBeakCoordinates());
updateBirdComponent("head", bird.getHeadCoordinates());
}
// Updates the position of a tail component and rotates it around the body of the bird.
void Tema1::updateTailComponent(std::string name, glm::vec3 currentCoordinates, int index)
{
modelMatrix = Transform2D::Translate(currentCoordinates.x, currentCoordinates.y + translateY);
modelMatrix *= Transform2D::Translate(bird.getBodyCoordinates().x - currentCoordinates.x, 0.f);
modelMatrix *= Transform2D::Rotate(index * (float)M_PI / 12 + floatStep);
modelMatrix *= Transform2D::Translate(currentCoordinates.x - bird.getBodyCoordinates().x, 0.f);
modelMatrix *= bird.rotateAroundBody(currentCoordinates, angularStep);
RenderMesh(meshes[name], shaders["VertexColor"], modelMatrix);
}
// Updates the position of the given bird component. In case the component is the wing, it is scaled
// in order to mimic the flapping of a wing.
void Tema1::updateBirdComponent(std::string name, glm::vec3 currentCoordinates)
{
modelMatrix = Transform2D::Translate(currentCoordinates.x, currentCoordinates.y + translateY);
if (name == "wing")
{
float offsetX = bird.getBodyCoordinates().x - currentCoordinates.x;
float offsetY = bird.getBodyCoordinates().y - currentCoordinates.y;
modelMatrix *= Transform2D::Translate(offsetX, offsetY);
modelMatrix *= Transform2D::Rotate(angularStep);
modelMatrix *= Transform2D::Scale(1.f, wingScaleY);
modelMatrix *= Transform2D::Translate(-offsetX, -offsetY);
}
else
{
modelMatrix *= bird.rotateAroundBody(currentCoordinates, angularStep);
}
if (name == "body")
{
bodyCoordinates = modelMatrix[2];
}
else if (name == "head")
{
headCoordinates = modelMatrix[2];
}
RenderMesh(meshes[name], shaders["VertexColor"], modelMatrix);
// Loses the game if the bird is no longer on the screen.
if (modelMatrix[2].y < 0.f || modelMatrix[2].y >(float)window->GetResolution().y)
{
playing = false;
}
}
// Computes the position on the OY axis if the bird is jumping, as well as the rotation of the bird
// around its center, based on the jump acceleration.
void Tema1::updateJump(float deltaTimeSeconds)
{
if (jumping)
{
currentJumpY = jumpAcceleration * deltaTimeSeconds * deltaTimeSeconds / 2;
angularStep += jumpAcceleration * deltaTimeSeconds / 10000;
totalJumpY += currentJumpY;
if (totalJumpY >= maxJumpY)
{
jumping = false;
currentJumpY = 0.f;
totalJumpY = 0.f;
}
}
if (angularStep > M_PI / 4)
{
angularStep = (float)M_PI / 4;
}
if (angularStep < -M_PI / 4)
{
angularStep = -(float)M_PI / 4;
}
}
// Rotates the tail around the body.
void Tema1::moveTail(float deltaTimeSeconds)
{
if (floatUp)
{
floatStep -= deltaTimeSeconds / 2;
if (floatStep < minFloatAngle)
{
floatUp = false;
}
}
else
{
floatStep += deltaTimeSeconds / 2;
if (floatStep > maxFloatAngle)
{
floatUp = true;
}
}
}
// Flaps the wing by scaling it on the OY axis.
void Tema1::moveWing(float deltaTimeSeconds) {
if (wingUp)
{
wingScaleY += 2 * deltaTimeSeconds;
if (wingScaleY >= maxWingScaleY)
{
wingUp = false;
}
}
else
{
wingScaleY -= 2 * deltaTimeSeconds;
if (wingScaleY <= minWingScaleY)
{
wingUp = true;
}
}
}
// Modifies the scales of all the obstacles.
void Tema1::scaleObstacle(float deltaTimeSeconds)
{
if (growObstacle)
{
obstacleScale += deltaTimeSeconds / 2;
if (obstacleScale >= maxObstacleScale)
{
growObstacle = false;
}
}
else
{
obstacleScale -= deltaTimeSeconds / 2;
if (obstacleScale <= minObstacleScale)
{
growObstacle = true;
}
}
}
// Renders the obstacles and updates the score.
void Tema1::updateStalactitesAndStalagmites(float deltaTimeSeconds)
{
if (playing)
{
translateX -= deltaTimeSeconds / 2;
if (score > 30)
{
scaleObstacle(deltaTimeSeconds);
}
// The score is incremented when an obstacle's OX position is less than 0.
if (obstacles.updateFirst(translateX))
{
++score;
std::cout << "Current score: " << score << "!\n";
}
}
glm::mat3 stalagmitePosition = obstacles.getPosition();
glm::mat3 stalactitePosition;
for (int i = 0; i < obstacles.getObstacleCount(); ++i)
{
int currentIndex = (i + obstacles.getFirst()) % obstacles.getObstacleCount();
// The position of the current stalagmite and stalactite is computed based on the
// current index and the position of the leftmost obstacle.
obstacles.createObstacles(currentIndex, stalagmitePosition, stalactitePosition, obstacleScale);
// Renders only the obstacles that can be seen.
if (stalagmitePosition[2][0] < (float)window->GetResolution().x)
{
glm::mat3 currentStalagmite = stalagmitePosition;
currentStalagmite *= Transform2D::Scale(1.f, obstacles.getScale(currentIndex) + obstacleScale);
RenderObstacle(currentStalagmite, currentIndex);
RenderObstacle(stalactitePosition, currentIndex);
// Checks for existing collisions.
if (playing)
{
checkCollision(currentStalagmite[2], stalactitePosition[2], currentIndex);
}
}
}
}
// Renders an obstacle using the randomly assigned texture.
void Tema1::RenderObstacle(glm::mat3& mm, int index)
{
glm::mat4 model = glm::mat4(
mm[0][0], mm[0][1], mm[0][2], 0.f,
mm[1][0], mm[1][1], mm[1][2], 0.f,
0.f, 0.f, mm[2][2], 0.f,
mm[2][0], mm[2][1], 0.f, 1.f);
RenderSimpleMesh(meshes["square"], shaders["ShaderT1"], model,
mapTextures[obstacles.getObstacleTexture(index)]);
}
// If the bird is situated near the current obstacles, then collision checking is performed.
void Tema1::checkCollision(glm::vec3& stalagmite, glm::vec3& stalactite, int currentIndex)
{
float headRadius = bird.getHeadRadius();
float bodyRadius = bird.getBodyRadius();
bool headCollision = false;
bool bodyCollision = false;
if (headCoordinates.x + headRadius >= stalagmite.x
&& headCoordinates.x - headRadius <= stalagmite.x + obstacles.getSquareSide())
{
headCollision = obstacles.checkCollisions(headCoordinates, headRadius,
currentIndex, stalactite, stalagmite, obstacleScale);
}
if (bodyCoordinates.x + bodyRadius >= stalagmite.x
&& bodyCoordinates.x - bodyRadius <= stalagmite.x + obstacles.getSquareSide())
{
bodyCollision = obstacles.checkCollisions(bodyCoordinates, bodyRadius,
currentIndex, stalactite, stalagmite, obstacleScale);
}
if (headCollision || bodyCollision)
{
playing = false;
}
}
void Tema1::RenderSimpleMesh(Mesh* mesh, Shader* shader, const glm::mat4& modelMatrix, Texture2D* texture)
{
if (!mesh || !shader || !shader->GetProgramID())
return;
// render an object using the specified shader and the specified position
glUseProgram(shader->program);
// Bind model matrix
GLint loc_model_matrix = glGetUniformLocation(shader->program, "Model");
glUniformMatrix4fv(loc_model_matrix, 1, GL_FALSE, glm::value_ptr(modelMatrix));
// Bind view matrix
glm::mat4 viewMatrix = GetSceneCamera()->GetViewMatrix();
int loc_view_matrix = glGetUniformLocation(shader->program, "View");
glUniformMatrix4fv(loc_view_matrix, 1, GL_FALSE, glm::value_ptr(viewMatrix));
// Bind projection matrix
glm::mat4 projectionMatrix = GetSceneCamera()->GetProjectionMatrix();
int loc_projection_matrix = glGetUniformLocation(shader->program, "Projection");
glUniformMatrix4fv(loc_projection_matrix, 1, GL_FALSE, glm::value_ptr(projectionMatrix));
if (texture)
{
// Activate texture location 0
glActiveTexture(GL_TEXTURE0);
// Bind the texture1 ID
glBindTexture(GL_TEXTURE_2D, texture->GetTextureID());
// Send texture uniform value
glUniform1i(glGetUniformLocation(shader->program, "texture"), 0);
}
// Draw the object
glBindVertexArray(mesh->GetBuffers()->VAO);
glDrawElements(mesh->GetDrawMode(), static_cast<int>(mesh->indices.size()), GL_UNSIGNED_SHORT, 0);
}
void Tema1::FrameEnd()
{
}
void Tema1::OnInputUpdate(float deltaTime, int mods)
{
// The bird starts jumping when the spacebar is pressed.
if (window->KeyHold(GLFW_KEY_SPACE)) {
jumping = true;
}
}
void Tema1::OnKeyPress(int key, int mods)
{
// add key press event
}
void Tema1::OnKeyRelease(int key, int mods)
{
// add key release event
}
void Tema1::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY)
{
// add mouse move event
}
void Tema1::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods)
{
// add mouse button press event
}
void Tema1::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods)
{
// add mouse button release event
}
void Tema1::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY)
{
}
void Tema1::OnWindowResize(int width, int height)
{
}
| 26.498162 | 119 | 0.709192 | adinasm |
661d9a8cee03742eb789a8296cd9e4ca155e9b2e | 934 | cxx | C++ | src/MonteCarlo/McEventStructure.cxx | fermi-lat/Event | 2e9e8ee117f61c4b1abde69828a97f94ff84630a | [
"BSD-3-Clause"
] | null | null | null | src/MonteCarlo/McEventStructure.cxx | fermi-lat/Event | 2e9e8ee117f61c4b1abde69828a97f94ff84630a | [
"BSD-3-Clause"
] | null | null | null | src/MonteCarlo/McEventStructure.cxx | fermi-lat/Event | 2e9e8ee117f61c4b1abde69828a97f94ff84630a | [
"BSD-3-Clause"
] | null | null | null | /**
* @class McEventStructure
*
* @brief Implements the methods described in McEventStructure.h
*
* @author Tracy Usher
*
* $Header: /nfs/slac/g/glast/ground/cvs/Event/src/MonteCarlo/McEventStructure.cxx,v 1.2 2004/02/18 19:02:27 usher Exp $
*/
#include "Event/MonteCarlo/McEventStructure.h"
//Event::McEventStructure::McEventStructure() : m_classification(0)
//{
// // clear refvec's (just in case)
// m_primary = 0;
// m_secondaries.clear();
// m_associated.clear();
//
// return;
//}
/*
Event::McEventStructure::McEventStructure(Event::McParticle* mcPart, unsigned long classBits) :
m_primary(mcPart),
m_classification(classBits)
{
// clear refvec's (just in case)
m_secondaries.clear();
m_associated.clear();
return;
}
*/
//Event::McEventStructure::~McEventStructure()
//{
// return;
//}
| 23.948718 | 120 | 0.611349 | fermi-lat |
662078f2d9bfcbb447007249e862c143c63ef57d | 214 | cpp | C++ | code/math/berlekamp-massey/debug.cpp | tonowak/acmlib | ec295b8c76c588914475ad42cff81a64a6f2ebd5 | [
"MIT"
] | 6 | 2019-06-25T14:07:08.000Z | 2022-01-04T12:28:55.000Z | code/math/berlekamp-massey/debug.cpp | tonowak/acmlib | ec295b8c76c588914475ad42cff81a64a6f2ebd5 | [
"MIT"
] | null | null | null | code/math/berlekamp-massey/debug.cpp | tonowak/acmlib | ec295b8c76c588914475ad42cff81a64a6f2ebd5 | [
"MIT"
] | 1 | 2021-11-12T01:40:38.000Z | 2021-11-12T01:40:38.000Z | #include "../../utils/headers/main.cpp"
#include "main.cpp"
int main()
{
int n;
cin >> n;
vector<int> x(n);
REP(i, n) cin >> x[i];
BerlekampMassey<int(1e9 + 696969)> bm(x);
REP(k, 10) debug(k, bm.get(k));
}
| 16.461538 | 42 | 0.579439 | tonowak |
6621b9369acd878e03a26978ba8d86434b0dea51 | 2,663 | cpp | C++ | TRex-Server/src/Util/Logging.cpp | espv/trex-plus-wrapper | bbef6d27715cf35bc1faa8ec2d9eeb3099df337d | [
"Apache-2.0"
] | null | null | null | TRex-Server/src/Util/Logging.cpp | espv/trex-plus-wrapper | bbef6d27715cf35bc1faa8ec2d9eeb3099df337d | [
"Apache-2.0"
] | null | null | null | TRex-Server/src/Util/Logging.cpp | espv/trex-plus-wrapper | bbef6d27715cf35bc1faa8ec2d9eeb3099df337d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2011 Francesco Feltrinelli <first_name DOT last_name AT gmail DOT com>
*
* 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 "Logging.hpp"
using namespace concept::util;
namespace logging = boost::log;
namespace sinks = boost::log::sinks;
namespace src = boost::log::sources;
namespace attrs = boost::log::attributes;
namespace keywords = boost::log::keywords;
namespace expr = boost::log::expressions;
# if BOOST_VERSION < 105500
namespace boost {
using null_deleter = log::null_deleter;
}
# endif
// init static logger
src::severity_logger< severity_level > Logging::logger;
void Logging::init(){
// Construct the sink (frontend)
typedef sinks::synchronous_sink< sinks::text_ostream_backend > text_sink;
boost::shared_ptr< text_sink > pSink = boost::make_shared< text_sink >();
// Get a thread-safe pointer to sink backend
text_sink::locked_backend_ptr pBackend = pSink->locked_backend();
// Automatically flush streams after each record
pBackend->auto_flush(true);
// Add a stream to log to console
boost::shared_ptr< std::ostream > pConsoleStream(&std::cout, boost::null_deleter());
pBackend->add_stream(pConsoleStream);
// Add a stream to log to file
boost::shared_ptr< std::ofstream > pFileStream(new std::ofstream("session.log"));
pBackend->add_stream(pFileStream);
// Register the sink in the logging core
logging::core::get()->add_sink(pSink);
// And a global timestamp attribute
// boost::shared_ptr< logging::attribute > pTimeStamp(new attrs::local_clock());
// logging::core::get()->add_global_attribute("TimeStamp", pTimeStamp);
logging::core::get()->add_global_attribute("TimeStamp", attrs::local_clock());
// Describe how to format logs
pSink->set_formatter(
expr::format("%1% %2%")
% expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%d.%m.%Y %H:%M:%S")
% expr::smessage
);
// Add a filter on severity level:
// Write all records with "info" severity or higher
// pSink->set_filter(
// logging::trivial::severity >= logging::trivial::info
// );
}
| 33.708861 | 87 | 0.727375 | espv |
6622435f34c754ba5066588df2344014e217b585 | 4,999 | cc | C++ | test/random/curand/CurandPerformance.test.cc | whokion/celeritas | 9e1cf3ec6b7b5a15c5bc197959f105d6a02e6612 | [
"Apache-2.0",
"MIT"
] | 22 | 2020-03-31T14:18:22.000Z | 2022-01-10T09:43:06.000Z | test/random/curand/CurandPerformance.test.cc | whokion/celeritas | 9e1cf3ec6b7b5a15c5bc197959f105d6a02e6612 | [
"Apache-2.0",
"MIT"
] | 261 | 2020-04-29T15:14:29.000Z | 2022-03-31T19:07:14.000Z | test/random/curand/CurandPerformance.test.cc | whokion/celeritas | 9e1cf3ec6b7b5a15c5bc197959f105d6a02e6612 | [
"Apache-2.0",
"MIT"
] | 15 | 2020-05-01T19:47:19.000Z | 2021-12-25T06:12:09.000Z | //----------------------------------*-C++-*----------------------------------//
// Copyright 2020 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file CurandPerformance.test.cc
//---------------------------------------------------------------------------//
#include "CurandPerformance.test.hh"
#include "base/Range.hh"
#include "random/RngData.hh"
#include "random/DiagnosticRngEngine.hh"
#include "random/distributions/GenerateCanonical.hh"
#include "celeritas_test.hh"
using namespace celeritas_test;
using celeritas::range;
//---------------------------------------------------------------------------//
// TEST HARNESS
//---------------------------------------------------------------------------//
class CurandTest : public celeritas::Test
{
protected:
void SetUp() override
{
// Test parameters on the host
test_params.nsamples = 1.e+7;
test_params.nblocks = 1;
test_params.nthreads = 1;
test_params.seed = 12345u;
test_params.tolerance = 1.0e-3;
}
template<typename T>
void check_mean_host()
{
T devStates;
curand_init(test_params.seed, 0, 0, &devStates);
double sum = 0;
double sum2 = 0;
for (CELER_MAYBE_UNUSED auto i : range(test_params.nsamples))
{
double u01 = curand_uniform(&devStates);
sum += u01;
sum2 += u01 * u01;
}
double mean = sum / test_params.nsamples;
double variance = sum2 / test_params.nsamples - mean * mean;
EXPECT_SOFT_NEAR(mean, 0.5, test_params.tolerance);
EXPECT_SOFT_NEAR(variance, 1 / 12., test_params.tolerance);
}
protected:
// Test parameters
TestParams test_params;
};
//---------------------------------------------------------------------------//
// HOST TESTS
//---------------------------------------------------------------------------//
#if CELERITAS_USE_CUDA
TEST_F(CurandTest, curand_xorwow_host)
{
// XORWOW (default) generator
this->check_mean_host<curandState>();
}
TEST_F(CurandTest, curand_mrg32k3a_host)
{
// MRG32k3a generator
this->check_mean_host<curandStateMRG32k3a>();
}
TEST_F(CurandTest, curand_philox4_32_10_host)
{
// Philox4_32_10 generator
this->check_mean_host<curandStatePhilox4_32_10_t>();
}
#endif
TEST_F(CurandTest, std_mt19937_host)
{
// Mersenne Twister generator
auto rng = DiagnosticRngEngine<std::mt19937>();
double sum = 0;
double sum2 = 0;
for (CELER_MAYBE_UNUSED auto i : range(test_params.nsamples))
{
double u01 = celeritas::generate_canonical<double>(rng);
sum += u01;
sum2 += u01 * u01;
}
double mean = sum / test_params.nsamples;
double variance = sum2 / test_params.nsamples - mean * mean;
EXPECT_SOFT_NEAR(mean, 0.5, test_params.tolerance);
EXPECT_SOFT_NEAR(variance, 1 / 12., test_params.tolerance);
}
//---------------------------------------------------------------------------//
// DEVICE TESTS
//---------------------------------------------------------------------------//
#if CELERITAS_USE_CUDA
class CurandDeviceTest : public CurandTest
{
void SetUp() override
{
// Test parameters on the device (100 * host nsamples)
test_params.nsamples = 1.e+9;
test_params.nblocks = 64;
test_params.nthreads = 256;
test_params.seed = 12345u;
test_params.tolerance = 1.0e-3;
}
public:
void check_mean_device(TestOutput result)
{
double sum_total = 0;
double sum2_total = 0;
for (auto i : range(test_params.nblocks * test_params.nthreads))
{
sum_total += result.sum[i];
sum2_total += result.sum2[i];
}
double mean = sum_total / test_params.nsamples;
double variance = sum2_total / test_params.nsamples - mean * mean;
EXPECT_SOFT_NEAR(mean, 0.5, test_params.tolerance);
EXPECT_SOFT_NEAR(variance, 1 / 12., test_params.tolerance);
}
};
TEST_F(CurandDeviceTest, curand_xorwow_device)
{
// XORWOW (default) generator
auto output = curand_test<curandState>(test_params);
this->check_mean_device(output);
}
TEST_F(CurandDeviceTest, curand_mrg32k3a_device)
{
// MRG32k3a generator
auto output = curand_test<curandStateMRG32k3a>(test_params);
this->check_mean_device(output);
}
TEST_F(CurandDeviceTest, curand_philox4_32_10_t_device)
{
// Philox4_32_10 generator
auto output = curand_test<curandStatePhilox4_32_10_t>(test_params);
this->check_mean_device(output);
}
TEST_F(CurandDeviceTest, curand_mtgp32_device)
{
// MTGP32-11213 (Mersenne Twister RNG for the GPU)
auto output = curand_test<curandStateMtgp32>(test_params);
this->check_mean_device(output);
}
#endif
| 29.405882 | 79 | 0.572515 | whokion |
6626884e716c12e8f453565c75b52c851941e1f3 | 1,312 | cpp | C++ | Cmds/baseFeatures.cpp | jli860/tnvme | 208943be96c0fe073ed97a7098c0b00a2776ebf9 | [
"Apache-2.0"
] | 34 | 2015-03-09T17:54:24.000Z | 2022-02-03T03:40:08.000Z | Cmds/baseFeatures.cpp | jli860/tnvme | 208943be96c0fe073ed97a7098c0b00a2776ebf9 | [
"Apache-2.0"
] | 13 | 2015-05-20T02:21:09.000Z | 2019-02-13T19:57:20.000Z | Cmds/baseFeatures.cpp | jli860/tnvme | 208943be96c0fe073ed97a7098c0b00a2776ebf9 | [
"Apache-2.0"
] | 53 | 2015-03-13T02:46:24.000Z | 2021-11-17T07:34:04.000Z | /*
* Copyright (c) 2011, Intel Corporation.
*
* 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 "baseFeatures.h"
#include "featureDefs.h"
#define ZZ(a,b) b,
const uint8_t FID[] = {
FEATURE_TABLE
FID_FENCE // always must be the last element
};
const uint32_t FID_RES[] = {
FEATURE_RESERVE_TABLE
FID_FENCE
};
#undef ZZ
BaseFeatures::BaseFeatures() : Cmd(Trackable::OBJTYPE_FENCE)
{
// This constructor will throw
}
BaseFeatures::BaseFeatures(Trackable::ObjType objBeingCreated) :
Cmd(objBeingCreated)
{
}
BaseFeatures::~BaseFeatures()
{
}
void
BaseFeatures::SetFID(uint8_t fid)
{
LOG_NRM("Setting FID: 0x%02X", fid);
SetByte(fid, 10, 0);
}
uint8_t
BaseFeatures::GetFID() const
{
LOG_NRM("Getting FID");
return GetByte(10, 0);
}
| 20.5 | 76 | 0.700457 | jli860 |
662a77ee12f2fab6f581345e5df9f7cdca42c605 | 2,261 | hpp | C++ | thread_util.hpp | yamanalab/MCMalloc | 699066fc4fc64e1e52144e10902e2e986a275760 | [
"Apache-2.0"
] | 3 | 2018-06-30T14:01:27.000Z | 2020-02-01T08:09:45.000Z | thread_util.hpp | yamanalab/MCMalloc | 699066fc4fc64e1e52144e10902e2e986a275760 | [
"Apache-2.0"
] | null | null | null | thread_util.hpp | yamanalab/MCMalloc | 699066fc4fc64e1e52144e10902e2e986a275760 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017 Yamana Laboratory, Waseda University
* Supported by JST CREST Grant Number JPMJCR1503, Japan.
*
* 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.
*/
#pragma once
#include <cstddef>
#include <thread>
#include "debug.hpp"
#include "misc.hpp"
#include "myprintf.hpp"
// TODO: It is not essential but we should make below defination variable.
#define N_THREAD_MAX 256
namespace {
int64_t get_thread_id() {
static_assert(sizeof(std::thread::id) == sizeof(int64_t),
"this function only works if size of thead::id is equal to the "
"size of uint64_t");
auto id = std::this_thread::get_id();
int64_t *ptr = (int64_t *)&id;
return (*ptr);
}
} // namespace
namespace threadutil {
// NOTE: # of Main Thread is 0
// NOTE: assumption: one thread call only once
const int64_t MAIN_THREAD_ID = get_thread_id();
pthread_mutex_t _mtx = PTHREAD_MUTEX_INITIALIZER;
int64_t threadFlags[N_THREAD_MAX] = {};
inline int NewCurrentThreadIndex() {
int64_t id = get_thread_id();
if (id == MAIN_THREAD_ID) return 0;
{
SCOPED_LOCK(_mtx);
// NOTE: zero means new one mode
int startIndex = 0;
for (int i = 0; i < N_THREAD_MAX - 1; i++) {
int index = (startIndex + i) % N_THREAD_MAX + 1;
// NOTE: current thread is not 0
if (threadFlags[index] <= 0) {
threadFlags[index] = id;
return index;
}
}
}
return -1;
}
inline bool DeleteCurrentThreadIndex() {
int64_t id = get_thread_id();
if (id == MAIN_THREAD_ID) return true;
{
SCOPED_LOCK(_mtx);
for (int i = 1; i < N_THREAD_MAX; i++) {
if (threadFlags[i] == id) {
threadFlags[i] = -1;
return true;
}
}
}
return false;
}
} // namespace threadutil
| 27.240964 | 80 | 0.665192 | yamanalab |
662fcd4bc7ee63a550178422787435d8cf592569 | 7,290 | hpp | C++ | src/mem_datasource.hpp | calvinmetcalf/node-mapnik | 3d26f2089dee3cfc901965f6646d50004a0e0e56 | [
"BSD-3-Clause"
] | null | null | null | src/mem_datasource.hpp | calvinmetcalf/node-mapnik | 3d26f2089dee3cfc901965f6646d50004a0e0e56 | [
"BSD-3-Clause"
] | null | null | null | src/mem_datasource.hpp | calvinmetcalf/node-mapnik | 3d26f2089dee3cfc901965f6646d50004a0e0e56 | [
"BSD-3-Clause"
] | null | null | null | #ifndef __NODE_MAPNIK_MEM_DATASOURCE_H__
#define __NODE_MAPNIK_MEM_DATASOURCE_H__
#include <v8.h>
#include <node.h>
#include <node_object_wrap.h>
using namespace v8;
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/query.hpp>
#include <mapnik/params.hpp>
#include <mapnik/sql_utils.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/value_types.hpp>
// boost
#include <boost/scoped_ptr.hpp>
// stl
#include <vector>
#include <algorithm>
class js_datasource : public mapnik::datasource
{
friend class js_featureset;
public:
js_datasource(const mapnik::parameters ¶ms, Local<Value> cb);
virtual ~js_datasource();
mapnik::datasource::datasource_t type() const;
mapnik::featureset_ptr features(const mapnik::query& q) const;
mapnik::featureset_ptr features_at_point(mapnik::coord2d const& pt) const;
mapnik::box2d<double> envelope() const;
boost::optional<mapnik::datasource::geometry_t> get_geometry_type() const;
mapnik::layer_descriptor get_descriptor() const;
size_t size() const;
Persistent<Function> cb_;
private:
mutable mapnik::layer_descriptor desc_;
mapnik::box2d<double> ext_;
};
js_datasource::js_datasource(const mapnik::parameters ¶ms, Local<Value> cb)
: datasource (params),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8"))
{
cb_ = Persistent<Function>::New(Handle<Function>::Cast(cb));
boost::optional<std::string> ext = params.get<std::string>("extent");
if (ext)
ext_.from_string(*ext);
else
throw mapnik::datasource_exception("JSDatasource missing <extent> parameter");
}
js_datasource::~js_datasource()
{
cb_.Dispose();
}
mapnik::datasource::datasource_t js_datasource::type() const
{
return mapnik::datasource::Vector;
}
mapnik::box2d<double> js_datasource::envelope() const
{
return ext_;
}
boost::optional<mapnik::datasource::geometry_t> js_datasource::get_geometry_type() const
{
return boost::optional<mapnik::datasource::geometry_t>();
}
mapnik::layer_descriptor js_datasource::get_descriptor() const
{
return mapnik::layer_descriptor("in-memory js datasource","utf-8");
}
size_t js_datasource::size() const
{
return 0;//features_.size();
}
class js_featureset : public mapnik::Featureset
{
public:
js_featureset( const mapnik::query& q, const js_datasource* ds)
: q_(q),
feature_id_(1),
tr_(new mapnik::transcoder("utf-8")),
ds_(ds),
obj_(Object::New())
{
Local<Array> a = Array::New(4);
mapnik::box2d<double> const& e = q_.get_bbox();
a->Set(0, Number::New(e.minx()));
a->Set(1, Number::New(e.miny()));
a->Set(2, Number::New(e.maxx()));
a->Set(3, Number::New(e.maxy()));
obj_->Set(String::NewSymbol("extent"), a);
}
virtual ~js_featureset() {}
mapnik::feature_ptr next()
{
HandleScope scope;
TryCatch try_catch;
Local<Value> argv[2] = { Integer::New(feature_id_), obj_ };
Local<Value> val = ds_->cb_->Call(Context::GetCurrent()->Global(), 2, argv);
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
else
{
if (!val->IsUndefined())
{
if (val->IsObject())
{
Local<Object> obj = val->ToObject();
if (obj->Has(String::New("x")) && obj->Has(String::New("y")))
{
Local<Value> x = obj->Get(String::New("x"));
Local<Value> y = obj->Get(String::New("y"));
if (!x->IsUndefined() && x->IsNumber() && !y->IsUndefined() && y->IsNumber())
{
mapnik::geometry_type * pt = new mapnik::geometry_type(mapnik::Point);
pt->move_to(x->NumberValue(),y->NumberValue());
mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>();
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,feature_id_));
++feature_id_;
feature->add_geometry(pt);
if (obj->Has(String::New("properties")))
{
Local<Value> props = obj->Get(String::New("properties"));
if (props->IsObject())
{
Local<Object> p_obj = props->ToObject();
Local<Array> names = p_obj->GetPropertyNames();
unsigned int i = 0;
unsigned int a_length = names->Length();
while (i < a_length)
{
Local<Value> name = names->Get(i)->ToString();
// if name in q.property_names() ?
Local<Value> value = p_obj->Get(name);
if (value->IsString()) {
mapnik::value_unicode_string ustr = tr_->transcode(TOSTR(value));
feature->put_new(TOSTR(name),ustr);
} else if (value->IsNumber()) {
double num = value->NumberValue();
// todo - round
if (num == value->IntegerValue()) {
int integer = value->IntegerValue();
feature->put_new(TOSTR(name),integer);
} else {
double dub_val = value->NumberValue();
feature->put_new(TOSTR(name),dub_val);
}
}
i++;
}
}
}
return feature;
}
}
}
}
}
return mapnik::feature_ptr();
}
private:
mapnik::query const& q_;
unsigned int feature_id_;
boost::scoped_ptr<mapnik::transcoder> tr_;
const js_datasource* ds_;
Local<Object> obj_;
};
mapnik::featureset_ptr js_datasource::features(const mapnik::query& q) const
{
return mapnik::featureset_ptr(new js_featureset(q,this));
}
mapnik::featureset_ptr js_datasource::features_at_point(mapnik::coord2d const& pt) const
{
/*
box2d<double> box = box2d<double>(pt.x, pt.y, pt.x, pt.y);
#ifdef MAPNIK_DEBUG
std::clog << "box=" << box << ", pt x=" << pt.x << ", y=" << pt.y << "\n";
#endif
return featureset_ptr(new memory_featureset(box,*this));
*/
return mapnik::featureset_ptr();
}
#endif // __NODE_MAPNIK_MEM_DATASOURCE_H__
| 33.906977 | 109 | 0.510562 | calvinmetcalf |
66317a8c0d391f473cfc537c75d00f2dffd6d0a9 | 5,583 | cpp | C++ | examples/bloom_filter/src/BloomFilter.cpp | swoole/phpx | 3beb558f4ebed4660f0795fd98b193a350f924f6 | [
"Apache-2.0"
] | 213 | 2018-08-25T05:43:40.000Z | 2021-05-04T11:40:19.000Z | examples/bloom_filter/src/BloomFilter.cpp | swoole/phpx | 3beb558f4ebed4660f0795fd98b193a350f924f6 | [
"Apache-2.0"
] | 25 | 2018-09-09T05:54:59.000Z | 2021-02-22T05:09:54.000Z | examples/bloom_filter/src/BloomFilter.cpp | swoole/phpx | 3beb558f4ebed4660f0795fd98b193a350f924f6 | [
"Apache-2.0"
] | 41 | 2018-08-29T08:34:07.000Z | 2021-03-08T15:12:27.000Z | #include "phpx.h"
#include "ext/swoole/include/swoole.h"
#include "ext/swoole/include/swoole_lock.h"
#include "ext/swoole/include/swoole_file.h"
#include "ext/swoole/ext-src/php_swoole.h"
extern "C" {
extern void MurmurHash3_x64_128(const void *key, const int len, const uint32_t seed, void *out);
extern void SpookyHash128(
const void *key, size_t len, uint64_t seed1, uint64_t seed2, uint64_t *hash1, uint64_t *hash2);
}
BEGIN_EXTERN_C()
#if PHP_VERSION_ID < 80000
#include "BloomFilter_arginfo.h"
#else
#include "BloomFilter_arginfo.h"
#endif
END_EXTERN_C()
#include <iostream>
using namespace php;
using namespace std;
using swoole::File;
using swoole::RWLock;
struct BloomFilterObject {
size_t capacity;
char *array;
uint32_t k_num;
uint64_t bit_num;
uint64_t *hashes;
RWLock *lock;
};
#define RESOURCE_NAME "BloomFilterResource"
#define PROPERTY_NAME "ptr"
static void compute_hashes(uint32_t k_num, char *key, size_t len, uint64_t *hashes) {
uint64_t out[2];
MurmurHash3_x64_128(key, len, 0, out);
hashes[0] = out[0];
hashes[1] = out[1];
uint64_t *hash1 = out;
uint64_t *hash2 = hash1 + 1;
SpookyHash128(key, len, 0, 0, hash1, hash2);
hashes[2] = out[0];
hashes[3] = out[1];
for (uint32_t i = 4; i < k_num; i++) {
hashes[i] = hashes[1] + ((i * hashes[3]) % 18446744073709551557U);
}
}
static void BloomFilterResDtor(zend_resource *res) {
BloomFilterObject *bf = static_cast<BloomFilterObject *>(res->ptr);
efree(bf->hashes);
delete bf->lock;
sw_shm_free(bf);
}
PHPX_METHOD(BloomFilter, __construct) {
long capacity = args[0].toInt();
if (capacity <= 0) {
capacity = 65536;
}
uint32_t k_num = 2;
if (args.exists(1)) {
k_num = (uint32_t) args[1].toInt();
}
BloomFilterObject *bf = (BloomFilterObject *) sw_shm_malloc(sizeof(BloomFilterObject) + capacity);
if (bf == NULL) {
throwException("RuntimeException", "sw_shm_malloc() failed.");
}
bf->capacity = capacity;
bf->array = (char *) (bf + 1);
bzero(bf->array, bf->capacity);
bf->hashes = (uint64_t *) ecalloc(k_num, sizeof(uint64_t));
if (bf->hashes == NULL) {
throwException("RuntimeException", "ecalloc() failed.");
}
bf->bit_num = bf->capacity * 8;
bf->k_num = k_num;
bf->lock = new RWLock(1);
_this.oSet(PROPERTY_NAME, RESOURCE_NAME, bf);
}
PHPX_METHOD(BloomFilter, has) {
BloomFilterObject *bf = _this.oGet<BloomFilterObject>(PROPERTY_NAME, RESOURCE_NAME);
auto key = args[0];
compute_hashes(bf->k_num, key.toCString(), key.length(), bf->hashes);
uint32_t i;
uint32_t n;
bool miss;
bf->lock->lock_rd();
for (i = 0; i < bf->k_num; i++) {
n = bf->hashes[i] % bf->bit_num;
miss = !(bf->array[n / 8] & (1 << (n % 8)));
if (miss) {
bf->lock->unlock();
retval = false;
return;
}
}
bf->lock->unlock();
retval = true;
}
PHPX_METHOD(BloomFilter, add) {
BloomFilterObject *bf = _this.oGet<BloomFilterObject>(PROPERTY_NAME, RESOURCE_NAME);
auto key = args[0];
compute_hashes(bf->k_num, key.toCString(), key.length(), bf->hashes);
uint32_t i;
uint32_t n;
bf->lock->lock();
for (i = 0; i < bf->k_num; i++) {
n = bf->hashes[i] % bf->bit_num;
bf->array[n / 8] |= (1 << (n % 8));
}
bf->lock->unlock();
}
PHPX_METHOD(BloomFilter, clear) {
BloomFilterObject *bf = _this.oGet<BloomFilterObject>(PROPERTY_NAME, RESOURCE_NAME);
bf->lock->lock();
bzero(bf->array, bf->capacity);
bf->lock->unlock();
}
PHPX_METHOD(BloomFilter, dump) {
BloomFilterObject *bf = _this.oGet<BloomFilterObject>(PROPERTY_NAME, RESOURCE_NAME);
auto file = args[0].toCString();
bf->lock->lock();
File fp(file, File::CREATE | File::WRITE, 0644);
if (!fp.ready()) {
fail:
bf->lock->unlock();
retval = false;
return;
}
if (fp.write(&bf->capacity, sizeof(bf->capacity)) == 0) {
goto fail;
}
if (fp.write(bf->array, bf->capacity) == 0) {
goto fail;
}
bf->lock->unlock();
retval = true;
}
PHPX_METHOD(BloomFilter, load) {
auto file = args[0].toCString();
File fp(file, File::READ);
if (!fp.ready()) {
fail:
retval = false;
return;
}
size_t capacity = 0;
if (fp.read(&capacity, sizeof(capacity)) == 0) {
goto fail;
}
long filesize = fp.get_size();
if (filesize < 0 || filesize < capacity + sizeof(capacity)) {
goto fail;
}
auto o = newObject("BloomFilter", (long) capacity);
BloomFilterObject *bf = o.oGet<BloomFilterObject>(PROPERTY_NAME, RESOURCE_NAME);
if (fp.read(bf->array, capacity) == 0) {
goto fail;
}
retval = o;
}
PHPX_EXTENSION() {
Extension *extension = new Extension("BloomFilter", "1.0.2");
extension->onStart = [extension]() noexcept {
extension->registerConstant("BLOOMFILTER_VERSION", 10002);
Class *c = new Class("BloomFilter");
c->registerFunctions(class_BloomFilter_methods);
extension->registerClass(c);
extension->registerResource(RESOURCE_NAME, BloomFilterResDtor);
};
extension->require("swoole");
extension->info({"BloomFilter support", "enabled"},
{
{"author", "Tianfeng Han"},
{"version", extension->version},
{"date", "2021-02-07"},
});
return extension;
}
| 26.211268 | 102 | 0.602543 | swoole |
663326bad6c4a5ef5b0707933481815f73e11698 | 1,802 | cpp | C++ | src/gbtoolsUtils/gbtoolsUtils.cpp | Ensembl/gbtools | d0097eac4b363678391bf85fd76690c7342c772e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/gbtoolsUtils/gbtoolsUtils.cpp | Ensembl/gbtools | d0097eac4b363678391bf85fd76690c7342c772e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/gbtoolsUtils/gbtoolsUtils.cpp | Ensembl/gbtools | d0097eac4b363678391bf85fd76690c7342c772e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /* File: gbtoolsUtils.cpp
* Author: Gemma Barson, 2015-03-24
* Copyright (c) 2006-2017 Genome Research Ltd
* ---------------------------------------------------------------------------
* 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.
* ---------------------------------------------------------------------------
* This file is part of the gbtools genome browser tools library,
* originally written by:
*
* Ed Griffiths (Sanger Institute, UK) edgrif@sanger.ac.uk
* Roy Storey (Sanger Institute, UK) rds@sanger.ac.uk
* Malcolm Hinsley (Sanger Institute, UK) mh17@sanger.ac.uk
* Gemma Guest (Sanger Institute, UK) gb10@sanger.ac.uk
* Steve Miller (Sanger Institute, UK) sm23@sanger.ac.uk
*
* Description: See gbtoolsUtils.hpp
*----------------------------------------------------------------------------
*/
#include <gbtools/gbtoolsUtils.hpp>
#include <config.h>
#include <gtk/gtk.h>
#include <string.h>
namespace gbtools
{
/* Returns a string representing the Version.Release.Update of the gbtools code. */
const char *UtilsGetVersionString()
{
return GBTOOLS_VERSION ;
}
/* Returns a string containing the library name and version */
const char *UtilsGetVersionTitle()
{
return "gbtools - " GBTOOLS_VERSION ;
}
} /* gbtools namespace */
| 34 | 83 | 0.626526 | Ensembl |
6636fcb78f0da9773abd1c90dfae28a58bedb03f | 401 | cpp | C++ | Sources/thread-oop/main.cpp | igarcerant/curso_cpp_2021 | 97c4a44fda2917d159e4ae809cc0c2a7e4fb9d16 | [
"MIT"
] | null | null | null | Sources/thread-oop/main.cpp | igarcerant/curso_cpp_2021 | 97c4a44fda2917d159e4ae809cc0c2a7e4fb9d16 | [
"MIT"
] | null | null | null | Sources/thread-oop/main.cpp | igarcerant/curso_cpp_2021 | 97c4a44fda2917d159e4ae809cc0c2a7e4fb9d16 | [
"MIT"
] | null | null | null | #include <iostream>
#include <thread>
#include <string>
class Salutator
{
public:
void saludar(std::string name, int times);
};
void Salutator::saludar(std::string name, int times)
{
for(int i=0; i<times; i++) {
std::cout << i << ": hello, " << name << "!" << std::endl;
}
}
auto main() -> int
{
Salutator salut;
std::thread th(&Salutator::saludar, salut, "mexico", 5);
th.join();
}
| 13.827586 | 60 | 0.605985 | igarcerant |
663797e7995b05f9aaa50f86293786e3fd6d91bf | 773 | cpp | C++ | _0707_div2/C_Going_Home.cpp | mingweihe/codeforces | 8395d68a09373775009b76dbde189ce5bbba58ae | [
"MIT"
] | null | null | null | _0707_div2/C_Going_Home.cpp | mingweihe/codeforces | 8395d68a09373775009b76dbde189ce5bbba58ae | [
"MIT"
] | null | null | null | _0707_div2/C_Going_Home.cpp | mingweihe/codeforces | 8395d68a09373775009b76dbde189ce5bbba58ae | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int n;
int a[200001], x[5000001], y[5000001];
// pigeonhole principle, O(n) time return for qualified input data
void solve(){
cin >> n;
for(int i = 1; i <= n; ++i) cin >> a[i];
memset(x, 0, sizeof(x));
memset(y, 0, sizeof(y));
for(int i = 1; i < n; ++i){
for(int j = i+1; j <= n; ++j){
int s = a[i] + a[j];
if(x[s] && x[s] != i && x[s] != j && y[s] != i && y[s] != j){
cout << "YES" << '\n';
cout << x[s] << ' ' << y[s] << ' ' << i << ' ' << j << '\n';
return;
}
x[s] = i, y[s] = j;
}
}
cout << "NO" << '\n';
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
solve();
}
| 24.15625 | 76 | 0.384217 | mingweihe |
6638bc982330359bb30b8a85784390c740183080 | 69,680 | cpp | C++ | src/api/mysql/mysql.cpp | laigor/sqlrelay-non-english-fixes- | 7803f862ddbf88bca078c50d621c64c22fc0a405 | [
"PHP-3.01",
"CC-BY-3.0"
] | null | null | null | src/api/mysql/mysql.cpp | laigor/sqlrelay-non-english-fixes- | 7803f862ddbf88bca078c50d621c64c22fc0a405 | [
"PHP-3.01",
"CC-BY-3.0"
] | null | null | null | src/api/mysql/mysql.cpp | laigor/sqlrelay-non-english-fixes- | 7803f862ddbf88bca078c50d621c64c22fc0a405 | [
"PHP-3.01",
"CC-BY-3.0"
] | null | null | null | // Copyright (c) 1999-2018 David Muse
// See the file COPYING for more information
#include <sqlrelay/sqlrclient.h>
#include <rudiments/charstring.h>
#include <rudiments/character.h>
#include <rudiments/stringbuffer.h>
#include <rudiments/bytestring.h>
#include <rudiments/environment.h>
#include <rudiments/dictionary.h>
#include <rudiments/file.h>
#include <rudiments/memorypool.h>
#include <rudiments/datetime.h>
#include <rudiments/stdio.h>
//#define DEBUG_MESSAGES
#include <rudiments/debugprint.h>
#include <locale.h>
#define NEED_DATATYPESTRING 1
#define NEED_IS_NUMBER_TYPE_CHAR 1
#define NEED_IS_UNSIGNED_TYPE_CHAR 1
#define NEED_IS_BINARY_TYPE_CHAR 1
#include <datatypes.h>
#include <defines.h>
extern "C" {
#define CR_UNKNOWN_ERROR 2000
#define MYSQL_NO_DATA 100
#define REFRESH_GRANT 1
#define REFRESH_LOG 2
#define REFRESH_TABLES 4
#define REFRESH_HOSTS 8
#define REFRESH_STATUS 16
#define REFRESH_THREADS 32
#define REFRESH_SLAVE 64
#define REFRESH_MASTER 128
typedef unsigned long long my_ulonglong;
typedef bool my_bool;
typedef my_ulonglong * MYSQL_ROW_OFFSET;
typedef unsigned int MYSQL_FIELD_OFFSET;
enum enum_mysql_set_option {
MYSQL_SET_OPTION_UNKNOWN_OPTION
};
enum mysql_option {
MYSQL_OPTION_UNKNOWN_OPTION
};
// Taken directly from mysql_com.h version 5.something
// Back-compatible with all previous versions.
enum enum_field_types {
MYSQL_TYPE_DECIMAL,
MYSQL_TYPE_TINY,
MYSQL_TYPE_SHORT,
MYSQL_TYPE_LONG,
MYSQL_TYPE_FLOAT,
MYSQL_TYPE_DOUBLE,
MYSQL_TYPE_NULL,
MYSQL_TYPE_TIMESTAMP,
MYSQL_TYPE_LONGLONG,
MYSQL_TYPE_INT24,
MYSQL_TYPE_DATE,
MYSQL_TYPE_TIME,
MYSQL_TYPE_DATETIME,
MYSQL_TYPE_YEAR,
MYSQL_TYPE_NEWDATE,
MYSQL_TYPE_VARCHAR,
MYSQL_TYPE_BIT,
MYSQL_TYPE_TIMESTAMP2,
MYSQL_TYPE_DATETIME2,
MYSQL_TYPE_TIME2,
MYSQL_TYPE_NEWDECIMAL=246,
MYSQL_TYPE_ENUM=247,
MYSQL_TYPE_SET=248,
MYSQL_TYPE_TINY_BLOB=249,
MYSQL_TYPE_MEDIUM_BLOB=250,
MYSQL_TYPE_LONG_BLOB=251,
MYSQL_TYPE_BLOB=252,
MYSQL_TYPE_VAR_STRING=253,
MYSQL_TYPE_STRING=254,
MYSQL_TYPE_GEOMETRY=255
};
enum enum_stmt_attr_type {
STMT_ATTR_UPDATE_MAX_LENGTH,
STMT_ATTR_CURSOR_TYPE,
STMT_ATTR_PREFETCH_ROWS
};
#ifdef COMPAT_MYSQL_3
// taken directly from mysql.h - 3.23.58
struct MYSQL_FIELD {
char *name; /* Name of column */
char *table; /* Table of column if column was a field */
char *def; /* Default value (set by mysql_list_fields) */
enum enum_field_types type; /* Type of field. Se mysql_com.h for types */
unsigned int length; /* Width of column */
unsigned int max_length; /* Max width of selected set */
unsigned int flags; /* Div flags */
unsigned int decimals; /* Number of decimals in field */
};
#endif
#ifdef COMPAT_MYSQL_4_0
// taken directly from mysql.h - 4.0.17
struct MYSQL_FIELD {
char *name; /* Name of column */
char *table; /* Table of column if column was a field */
char *org_table; /* Org table name if table was an alias */
char *db; /* Database for table */
char *def; /* Default value (set by mysql_list_fields) */
unsigned long length; /* Width of column */
unsigned long max_length; /* Max width of selected set */
unsigned int flags; /* Div flags */
unsigned int decimals; /* Number of decimals in field */
enum enum_field_types type; /* Type of field. Se mysql_com.h for types */
};
#endif
#if defined(COMPAT_MYSQL_4_1) || \
defined(COMPAT_MYSQL_5_0) || \
defined(COMPAT_MYSQL_5_1)
// taken directly from mysql.h - 4.1.1-alpha (5.0.0-alpha is the same)
struct MYSQL_FIELD {
char *name; /* Name of column */
char *org_name; /* Original column name, if an alias */
char *table; /* Table of column if column was a field */
char *org_table; /* Org table name, if table was an alias */
char *db; /* Database for table */
char *catalog; /* Catalog for table */
char *def; /* Default value (set by mysql_list_fields) */
unsigned long length; /* Width of column */
unsigned long max_length; /* Max width of selected set */
unsigned int name_length;
unsigned int org_name_length;
unsigned int table_length;
unsigned int org_table_length;
unsigned int db_length;
unsigned int catalog_length;
unsigned int def_length;
unsigned int flags; /* Div flags */
unsigned int decimals; /* Number of decimals in field */
unsigned int charsetnr; /* Character set */
enum enum_field_types type; /* Type of field. See mysql_com.h for types */
#ifdef COMPAT_MYSQL_5_1
// taken directly from mysql.h - 5.1.22
void *extension;
#endif
};
#endif
#ifdef COMPAT_MYSQL_5_1
// taken from mysql.h - 5.1.22, modified
typedef struct st_mysql_bind {
unsigned long *length; /* output length pointer */
my_bool *is_null; /* Pointer to null indicator */
//void *buffer; /* buffer to get/put data */
char *buffer;
/* set this if you want to track data truncations happened during fetch */
my_bool *error;
unsigned char *row_ptr; /* for the current data position */
//void (*store_param_func)(NET *net, struct st_mysql_bind *param);
void (*store_param_func)(void *net, struct st_mysql_bind *param);
void (*fetch_result)(struct st_mysql_bind *, MYSQL_FIELD *,
unsigned char **row);
void (*skip_result)(struct st_mysql_bind *, MYSQL_FIELD *,
unsigned char **row);
/* output buffer length, must be set when fetching str/binary */
unsigned long buffer_length;
unsigned long offset; /* offset position for char/binary fetch */
unsigned long length_value; /* Used if length is 0 */
unsigned int param_number; /* For null count and error messages */
unsigned int pack_length; /* Internal length for packed data */
enum enum_field_types buffer_type; /* buffer type */
my_bool error_value; /* used if error is 0 */
my_bool is_unsigned; /* set if integer type is unsigned */
my_bool long_data_used; /* If used with mysql_send_long_data */
my_bool is_null_value; /* Used if is_null is 0 */
void *extension;
} MYSQL_BIND;
#else
// taken directly from mysql.h - 5.0
struct MYSQL_BIND {
unsigned long *length; /* output length pointer */
my_bool *is_null; /* Pointer to null indicators */
char *buffer; /* buffer to get/put data */
enum enum_field_types buffer_type; /* buffer type */
unsigned long buffer_length; /* buffer length, must be set for str/binary */
/* Following are for internal use. Set by mysql_bind_param */
unsigned char *inter_buffer; /* for the current data position */
unsigned long offset; /* offset position for char/binary fetch */
unsigned long internal_length; /* Used if length is 0 */
unsigned int param_number; /* For null count and error messages */
my_bool long_data_used; /* If used with mysql_send_long_data */
my_bool binary_data; /* data buffer is binary */
my_bool null_field; /* NULL data cache flag */
my_bool internal_is_null; /* Used if is_null is 0 */
void *store_param_func;/*(NET *net, struct MYSQL_BIND *param);*/
void *fetch_result;/*(struct MYSQL_BIND *, unsigned char **row);*/
};
#endif
struct MYSQL_PARAMETERS {
unsigned long *p_max_allowed_packet;
unsigned long *p_net_buffer_length;
};
enum enum_mysql_timestamp_type {
MYSQL_TIMESTAMP_NONE=-2,
MYSQL_TIMESTAMP_ERROR=-1,
MYSQL_TIMESTAMP_DATE=0,
MYSQL_TIMESTAMP_DATETIME=1,
MYSQL_TIMESTAMP_TIME=2
};
struct MYSQL_TIME {
unsigned int year;
unsigned int month;
unsigned int day;
unsigned int hour;
unsigned int minute;
unsigned int second;
unsigned long second_part;
my_bool neg;
enum enum_mysql_timestamp_type time_type;
};
// This is the same for all versions of mysql that I've ever seen
typedef char **MYSQL_ROW;
struct MYSQL_STMT;
struct MYSQL_RES {
sqlrcursor *sqlrcur;
// don't call this errno, some systems have a macro for errno
// which will get substituted in for all errno references and give
// undesirable results
unsigned int errorno;
my_ulonglong previousrow;
my_ulonglong currentrow;
uint32_t fieldcount;
MYSQL_FIELD_OFFSET currentfield;
MYSQL_FIELD *fields;
unsigned long *lengths;
MYSQL_STMT *stmtbackptr;
linkedlist< my_ulonglong > rowcache;
};
struct MYSQL;
struct MYSQL_STMT {
MYSQL_RES *result;
MYSQL_BIND *resultbinds;
MYSQL *mysql;
memorypool bindvarnames;
};
struct MYSQL {
const char *host;
unsigned int port;
const char *unix_socket;
sqlrconnection *sqlrcon;
MYSQL_STMT *currentstmt;
bool deleteonclose;
char *error;
int errorno;
dictionary< int64_t, unsigned int > *errormap;
bool backendchecked;
bool backendismysql;
};
#define NOT_NULL_FLAG 1
#define PRI_KEY_FLAG 2
#define UNIQUE_KEY_FLAG 4
#define MULTIPLE_KEY_FLAG 8
#define BLOB_FLAG 16
#define UNSIGNED_FLAG 32
#define ZEROFILL_FLAG 64
#define BINARY_FLAG 128
#define ENUM_FLAG 256
#define AUTO_INCREMENT_FLAG 512
#define TIMESTAMP_FLAG 1024
#define ON_UPDATE_NOW_FLAG 8192
#define SET_FLAG 2048
#define NUM_FLAG 32768
unsigned int mysql_thread_safe();
MYSQL *mysql_init(MYSQL *mysql);
int mysql_set_server_option(MYSQL *mysql, enum enum_mysql_set_option option);
int mysql_options(MYSQL *mysql, enum mysql_option option, const char *arg);
int mysql_ssl_set(MYSQL *mysql, const char *key, const char *cert,
const char *ca, const char *capath,
const char *cipher);
MYSQL *mysql_connect(MYSQL *mysql, const char *host,
const char *user, const char *passwd);
MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user,
const char *passwd, const char *db,
unsigned int port, const char *unix_socket,
unsigned long client_flag);
void mysql_close(MYSQL *mysql);
int mysql_ping(MYSQL *mysql);
const char *mysql_stat(MYSQL *mysql);
int mysql_shutdown(MYSQL *mysql);
int mysql_reload(MYSQL *mysql);
int mysql_refresh(MYSQL *mysql, unsigned int refresh_options);
unsigned long mysql_thread_id(MYSQL *mysql);
MYSQL_RES *mysql_list_processes(MYSQL *mysql);
int mysql_kill(MYSQL *mysql, unsigned long pid);
const char *mysql_get_client_info();
unsigned long mysql_get_client_version();
const char *mysql_get_host_info(MYSQL *mysql);
unsigned int mysql_get_proto_info(MYSQL *mysql);
const char *mysql_get_server_info(MYSQL *mysql);
unsigned long mysql_get_server_version(MYSQL *mysql);
my_bool mysql_change_user(MYSQL *mysql, const char *user,
const char *password, const char *db);
const char *mysql_character_set_name(MYSQL *mysql);
int mysql_set_character_set(MYSQL *mysql, const char *csname);
void mysql_debug(const char *debug);
int mysql_dump_debug_info(MYSQL *mysql);
int mysql_create_db(MYSQL *mysql, const char *db);
int mysql_select_db(MYSQL *mysql, const char *db);
int mysql_drop_db(MYSQL *mysql, const char *db);
MYSQL_RES *mysql_list_dbs(MYSQL *mysql, const char *wild);
MYSQL_RES *mysql_list_tables(MYSQL *mysql, const char *wild);
MYSQL_RES *mysql_list_fields(MYSQL *mysql, const char *table, const char *wild);
unsigned long mysql_escape_string(char *to, const char *from,
unsigned long length);
char *mysql_odbc_escape_string(MYSQL *mysql, char *to,
unsigned long to_length,
const char *from,
unsigned long from_length,
void *param,
char *(*extend_buffer)
(void *, char *to,
unsigned long *length));
void myodbc_remove_escape(MYSQL *mysql, char *name);
int mysql_query(MYSQL *mysql, const char *query);
int mysql_send_query(MYSQL *mysql, const char *query, unsigned int length);
int mysql_read_query_result(MYSQL *mysql);
unsigned long mysql_real_escape_string(MYSQL *mysql, char *to,
const char *from,
unsigned long length);
int mysql_real_query(MYSQL *mysql, const char *query, unsigned long length);
const char *mysql_info(MYSQL *mysql);
my_ulonglong mysql_insert_id(MYSQL *mysql);
MYSQL_RES *mysql_store_result(MYSQL *mysql);
MYSQL_RES *mysql_use_result(MYSQL *mysql);
void mysql_free_result(MYSQL_RES *result);
my_bool mysql_more_results(MYSQL *mysql);
int mysql_next_result(MYSQL *mysql);
unsigned int mysql_num_fields(MYSQL_RES *result);
MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result);
MYSQL_FIELD *mysql_fetch_fields(MYSQL_RES *result);
MYSQL_FIELD *mysql_fetch_field_direct(MYSQL_RES *result, unsigned int fieldnr);
unsigned long *mysql_fetch_lengths(MYSQL_RES *result);
unsigned int mysql_field_count(MYSQL *mysql);
MYSQL_FIELD_OFFSET mysql_field_seek(MYSQL_RES *result,
MYSQL_FIELD_OFFSET offset);
MYSQL_FIELD_OFFSET mysql_field_tell(MYSQL_RES *result);
my_ulonglong mysql_num_rows(MYSQL_RES *result);
my_ulonglong mysql_affected_rows(MYSQL *mysql);
MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET offset);
MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result);
void mysql_data_seek(MYSQL_RES *result, my_ulonglong offset);
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result);
my_bool mysql_eof(MYSQL_RES *result);
unsigned int mysql_warning_count(MYSQL *mysql);
unsigned int mysql_errno(MYSQL *mysql);
const char *mysql_error(MYSQL *mysql);
const char *mysql_sqlstate(MYSQL *mysql);
my_bool mysql_commit(MYSQL *mysql);
my_bool mysql_rollback(MYSQL *mysql);
my_bool mysql_autocommit(MYSQL *mysql, my_bool mode);
MYSQL_STMT *mysql_prepare(MYSQL *mysql, const char *query,
unsigned long length);
my_bool mysql_bind_param(MYSQL_STMT *stmt, MYSQL_BIND *bind);
my_bool mysql_bind_result(MYSQL_STMT *stmt, MYSQL_BIND *bind);
int mysql_execute(MYSQL_STMT *stmt);
static void processFields(MYSQL_STMT *stmt);
enum enum_field_types map_col_type(const char *columntype, int64_t scale);
unsigned long mysql_param_count(MYSQL_STMT *stmt);
MYSQL_RES *mysql_param_result(MYSQL_STMT *stmt);
int mysql_fetch(MYSQL_STMT *stmt);
int mysql_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind,
unsigned int column, unsigned long offset);
MYSQL_RES *mysql_get_metadata(MYSQL_STMT *stmt);
my_bool mysql_send_long_data(MYSQL_STMT *stmt,
unsigned int parameternumber,
const char *data, unsigned long length);
MYSQL_STMT *mysql_stmt_init(MYSQL *mysql);
int mysql_stmt_prepare(MYSQL_STMT *stmt,
const char *query,
unsigned long length);
int mysql_stmt_execute(MYSQL_STMT *stmt);
int mysql_stmt_fetch(MYSQL_STMT *stmt);
int mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bindarg,
unsigned int column,
unsigned long offset);
int mysql_stmt_store_result(MYSQL_STMT *stmt);
unsigned long mysql_stmt_param_count(MYSQL_STMT * stmt);
my_bool mysql_stmt_attr_set(MYSQL_STMT *stmt,
enum enum_stmt_attr_type attrtype,
const void *attr);
my_bool mysql_stmt_attr_get(MYSQL_STMT *stmt,
enum enum_stmt_attr_type attrtype,
void *attr);
my_bool mysql_stmt_bind_param(MYSQL_STMT * stmt, MYSQL_BIND * bnd);
my_bool mysql_stmt_bind_result(MYSQL_STMT * stmt, MYSQL_BIND * bnd);
my_bool mysql_stmt_send_long_data(MYSQL_STMT *stmt,
unsigned int paramnumber,
const char *data,
unsigned long length);
MYSQL_RES *mysql_stmt_result_metadata(MYSQL_STMT *stmt);
MYSQL_RES *mysql_stmt_param_metadata(MYSQL_STMT *stmt);
my_ulonglong mysql_stmt_num_rows(MYSQL_STMT *stmt);
my_ulonglong mysql_stmt_affected_rows(MYSQL_STMT *stmt);
MYSQL_ROW_OFFSET mysql_stmt_row_seek(MYSQL_STMT *stmt,
MYSQL_ROW_OFFSET offset);
MYSQL_ROW_OFFSET mysql_stmt_row_tell(MYSQL_STMT *stmt);
void mysql_stmt_data_seek(MYSQL_STMT *stmt, my_ulonglong offset);
unsigned int mysql_stmt_errno(MYSQL_STMT *stmt);
const char *mysql_stmt_error(MYSQL_STMT *stmt);
my_ulonglong mysql_stmt_insert_id(MYSQL_STMT *stmt);
unsigned int mysql_stmt_field_count(MYSQL_STMT *stmt);
const char *mysql_stmt_sqlstate(MYSQL_STMT *stmt);
my_bool mysql_stmt_free_result(MYSQL_STMT *stmt);
my_bool mysql_stmt_reset(MYSQL_STMT *stmt);
my_bool mysql_stmt_close(MYSQL_STMT *stmt);
void mysql_library_init(int argc, char **argv, char **groups);
void mysql_server_end();
void mysql_library_end();
static int unknownError(MYSQL *mysql);
static void setMySQLError(MYSQL *mysql,
const char *error, unsigned int errorno);
static unsigned int mapErrorNumber(MYSQL *mysql, int64_t errorno);
static void loadErrorMap(MYSQL *mysql, const char *errormap);
unsigned int mysql_thread_safe() {
debugFunction();
return 1;
}
static MYSQL_PARAMETERS mysql_parameters;
static unsigned long p_max_allowed_packet=1024;
static unsigned long p_net_buffer_length=1024;
my_bool my_init() {
debugFunction();
mysql_parameters.p_max_allowed_packet=&p_max_allowed_packet;
mysql_parameters.p_net_buffer_length=&p_net_buffer_length;
return 0;
}
MYSQL_PARAMETERS *mysql_get_parameters() {
debugFunction();
debugPrintf("p_max_allowed_packet=%ld\n",
*mysql_parameters.p_max_allowed_packet);
debugPrintf("p_net_buffer_length=%ld\n",
*mysql_parameters.p_net_buffer_length);
return &mysql_parameters;
}
MYSQL *mysql_init(MYSQL *mysql) {
debugFunction();
my_init();
if (mysql) {
bytestring::zero(mysql,sizeof(MYSQL));
return mysql;
} else {
MYSQL *retval=new MYSQL;
bytestring::zero(retval,sizeof(MYSQL));
return retval;
}
}
int mysql_set_server_option(MYSQL *mysql, enum enum_mysql_set_option option) {
debugFunction();
return 0;
}
int mysql_options(MYSQL *mysql, enum mysql_option option, const char *arg) {
debugFunction();
return 0;
}
int mysql_ssl_set(MYSQL *mysql, const char *key, const char *cert,
const char *ca, const char *capath,
const char *cipher) {
debugFunction();
return 0;
}
const char *mysql_get_ssl_cipher(MYSQL *mysql) {
debugFunction();
return "";
}
my_bool mysql_thread_init(void) {
debugFunction();
return 0;
}
void mysql_thread_end(void) {
debugFunction();
}
MYSQL *mysql_connect(MYSQL *mysql, const char *host,
const char *user, const char *passwd) {
debugFunction();
return mysql_real_connect(mysql,host,user,passwd,NULL,9000,NULL,0);
}
MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user,
const char *passwd, const char *db,
unsigned int port, const char *unix_socket,
unsigned long client_flag) {
debugFunction();
mysql->host=host;
mysql->port=port;
mysql->unix_socket=unix_socket;
mysql->sqlrcon=new sqlrconnection(host,port,unix_socket,
user,passwd,0,1,true);
mysql->errormap=NULL;
const char *errormap=environment::getValue("SQLR_MYSQL_ERROR_MAP");
if (charstring::length(errormap)) {
loadErrorMap(mysql,errormap);
}
mysql->backendchecked=false;
mysql->backendismysql=false;
mysql->currentstmt=NULL;
mysql_select_db(mysql,db);
return mysql;
}
void mysql_close(MYSQL *mysql) {
debugFunction();
if (mysql) {
mysql_stmt_close(mysql->currentstmt);
delete mysql->sqlrcon;
setMySQLError(mysql,NULL,0);
if (mysql->deleteonclose) {
delete[] mysql->error;
delete mysql->errormap;
delete mysql;
}
}
}
int mysql_ping(MYSQL *mysql) {
debugFunction();
return !mysql->sqlrcon->ping();
}
const char *mysql_stat(MYSQL *mysql) {
debugFunction();
return "Uptime: 0 Threads: 0 Questions: 0 "
"Slow queries: 0 Opens: 0 Flush tables: 0 "
"Open tables: 0 Queries per second avg: 0.0";
}
int mysql_shutdown(MYSQL *mysql) {
debugFunction();
sqlrcursor sqlrcur(mysql->sqlrcon);
return !sqlrcur.sendQuery("SHUTDOWN");
}
int mysql_refresh(MYSQL *mysql, unsigned int refresh_options) {
debugFunction();
const char *query=NULL;
switch (refresh_options) {
case REFRESH_GRANT:
query="FLUSH PRIVILEGES";
break;
case REFRESH_LOG:
query="FLUSH LOGS";
break;
case REFRESH_TABLES:
query="FLUSH TABLES";
break;
case REFRESH_HOSTS:
query="FLUSH HOSTS";
break;
case REFRESH_STATUS:
query="FLUSH STATUS";
break;
case REFRESH_THREADS:
// FIXME: do something?
return 0;
case REFRESH_SLAVE:
query="RESET SLAVE";
break;
case REFRESH_MASTER:
query="RESET MASTER";
break;
}
sqlrcursor sqlrcur(mysql->sqlrcon);
return !sqlrcur.sendQuery(query);
}
int mysql_reload(MYSQL *mysql) {
debugFunction();
return mysql_refresh(mysql,REFRESH_GRANT);
}
unsigned long mysql_thread_id(MYSQL *mysql) {
debugFunction();
return 0;
}
MYSQL_RES *mysql_list_processes(MYSQL *mysql) {
debugFunction();
mysql_stmt_close(mysql->currentstmt);
mysql->currentstmt=new MYSQL_STMT;
mysql->currentstmt->result=new MYSQL_RES;
mysql->currentstmt->result->stmtbackptr=NULL;
mysql->currentstmt->result->sqlrcur=new sqlrcursor(mysql->sqlrcon,true);
mysql->currentstmt->result->errorno=0;
mysql->currentstmt->result->fields=NULL;
mysql->currentstmt->result->lengths=NULL;
mysql->currentstmt->result->sqlrcur->sendQuery("SHOW PROCESSLIST");
processFields(mysql->currentstmt);
mysql->currentstmt->result->currentfield=0;
MYSQL_RES *retval=mysql->currentstmt->result;
mysql->currentstmt->result=NULL;
return retval;
}
int mysql_kill(MYSQL *mysql, unsigned long pid) {
debugFunction();
sqlrcursor sqlrcur(mysql->sqlrcon);
stringbuffer query;
query.append("KILL ")->append((uint64_t)pid);
return !sqlrcur.sendQuery(query.getString());
}
const char *mysql_get_client_info() {
debugFunction();
// Returns a string that represents the client library version.
#ifdef COMPAT_MYSQL_3
return "3.23.58";
#endif
#ifdef COMPAT_MYSQL_4_0
return "4.0.17";
#endif
#ifdef COMPAT_MYSQL_4_1
return "4.1.1";
#endif
#ifdef COMPAT_MYSQL_5_0
return "5.0.0";
#endif
#ifdef COMPAT_MYSQL_5_1
return "5.1.22";
#endif
}
unsigned long mysql_get_client_version() {
debugFunction();
// Returns an integer that represents the client library version.
// The value has the format XYYZZ where X is the major version, YY is
// the release level, and ZZ is the version number within the release
// level. For example, a value of 40102 represents a client library
// version of 4.1.2.
#ifdef COMPAT_MYSQL_3
return 32358;
#endif
#ifdef COMPAT_MYSQL_4_0
return 40017;
#endif
#ifdef COMPAT_MYSQL_4_1
return 40101;
#endif
#ifdef COMPAT_MYSQL_5_0
return 50000;
#endif
#ifdef COMPAT_MYSQL_5_1
return 50122;
#endif
}
const char *mysql_get_host_info(MYSQL *mysql) {
debugFunction();
// Returns a string describing the type of connection in use,
// including the server host name.
// Should be "host via [unix|inet] socket"
return "";
}
unsigned int mysql_get_proto_info(MYSQL *mysql) {
debugFunction();
// Returns the protocol version used by current connection.
#ifdef COMPAT_MYSQL_3
return 10;
#endif
#ifdef COMPAT_MYSQL_4_0
return 12;
#endif
#ifdef COMPAT_MYSQL_4_1
return 14;
#endif
#ifdef COMPAT_MYSQL_5_0
return 14;
#endif
#ifdef COMPAT_MYSQL_5_1
return 10;
#endif
}
const char *mysql_get_server_info(MYSQL *mysql) {
debugFunction();
// Returns a string that represents the server version number.
#ifdef COMPAT_MYSQL_3
return "3.23.58";
#endif
#ifdef COMPAT_MYSQL_4_0
return "4.0.17";
#endif
#ifdef COMPAT_MYSQL_4_1
return "4.1.1";
#endif
#ifdef COMPAT_MYSQL_5_0
return "5.0.0";
#endif
#ifdef COMPAT_MYSQL_5_1
return "5.1.22";
#endif
}
unsigned long mysql_get_server_version(MYSQL *mysql) {
debugFunction();
// A number that represents the MySQL server version in format:
// main_version*10000 + minor_version *100 + sub_version
// For example, 4.1.0 is returned as 40100.
#ifdef COMPAT_MYSQL_3
return 32358;
#endif
#ifdef COMPAT_MYSQL_4_0
return 40017;
#endif
#ifdef COMPAT_MYSQL_4_1
return 40101;
#endif
#ifdef COMPAT_MYSQL_5_0
return 50000;
#endif
#ifdef COMPAT_MYSQL_5_1
return 50122;
#endif
}
my_bool mysql_change_user(MYSQL *mysql, const char *user,
const char *password, const char *db) {
debugFunction();
if (!mysql->sqlrcon->rollback()) {
return 1;
}
mysql_stmt_close(mysql->currentstmt);
delete mysql->sqlrcon;
return (mysql_real_connect(mysql,mysql->host,user,password,db,
mysql->port,mysql->unix_socket,0))?0:1;
}
const char *mysql_character_set_name(MYSQL *mysql) {
debugFunction();
return "latin1";
}
int mysql_set_character_set(MYSQL *mysql, const char *csname) {
debugFunction();
// FIXME: implement this somehow
return 0;
}
struct MY_CHARSET_INFO;
void mysql_get_character_set_info(MYSQL *mysql, MY_CHARSET_INFO *charset) {
debugFunction();
// FIXME: implement this somehow
}
void mysql_debug(const char *debug) {
// don't do anything...
}
int mysql_dump_debug_info(MYSQL *mysql) {
debugFunction();
return unknownError(mysql);
}
int mysql_create_db(MYSQL *mysql, const char *db) {
debugFunction();
return unknownError(mysql);
}
int mysql_select_db(MYSQL *mysql, const char *db) {
debugFunction();
return !mysql->sqlrcon->selectDatabase(db);
}
int mysql_drop_db(MYSQL *mysql, const char *db) {
debugFunction();
return unknownError(mysql);
}
MYSQL_RES *mysql_list_dbs(MYSQL *mysql, const char *wild) {
debugFunction();
mysql_stmt_close(mysql->currentstmt);
mysql->currentstmt=new MYSQL_STMT;
mysql->currentstmt->result=new MYSQL_RES;
mysql->currentstmt->result->stmtbackptr=NULL;
mysql->currentstmt->result->sqlrcur=new sqlrcursor(mysql->sqlrcon,true);
mysql->currentstmt->result->errorno=0;
mysql->currentstmt->result->fields=NULL;
mysql->currentstmt->result->lengths=NULL;
mysql->currentstmt->result->sqlrcur->getDatabaseList(wild,
SQLRCLIENTLISTFORMAT_MYSQL);
processFields(mysql->currentstmt);
mysql->currentstmt->result->currentfield=0;
MYSQL_RES *retval=mysql->currentstmt->result;
mysql->currentstmt->result=NULL;
return retval;
}
MYSQL_RES *mysql_list_tables(MYSQL *mysql, const char *wild) {
debugFunction();
mysql_stmt_close(mysql->currentstmt);
mysql->currentstmt=new MYSQL_STMT;
mysql->currentstmt->result=new MYSQL_RES;
mysql->currentstmt->result->stmtbackptr=NULL;
mysql->currentstmt->result->sqlrcur=new sqlrcursor(mysql->sqlrcon,true);
mysql->currentstmt->result->errorno=0;
mysql->currentstmt->result->fields=NULL;
mysql->currentstmt->result->lengths=NULL;
mysql->currentstmt->result->sqlrcur->getTableList(wild,
SQLRCLIENTLISTFORMAT_MYSQL,
DB_OBJECT_TABLE|DB_OBJECT_VIEW|
DB_OBJECT_ALIAS|DB_OBJECT_SYNONYM);
processFields(mysql->currentstmt);
mysql->currentstmt->result->currentfield=0;
MYSQL_RES *retval=mysql->currentstmt->result;
mysql->currentstmt->result=NULL;
return retval;
}
bool isTrue(const char *value) {
return (value &&
(value[0]=='y' ||
value[0]=='Y' ||
value[0]=='t' ||
value[0]=='T' ||
value[0]=='1'));
}
MYSQL_RES *mysql_list_fields(MYSQL *mysql,
const char *table, const char *wild) {
debugFunction();
debugPrintf("%s\n",table);
mysql_stmt_close(mysql->currentstmt);
MYSQL_STMT *stmt=new MYSQL_STMT;
mysql->currentstmt=stmt;
stmt->result=new MYSQL_RES;
stmt->result->stmtbackptr=NULL;
stmt->result->sqlrcur=new sqlrcursor(mysql->sqlrcon,true);
stmt->result->errorno=0;
stmt->result->fields=NULL;
stmt->result->lengths=NULL;
stmt->result->sqlrcur->getColumnList(table,wild,
SQLRCLIENTLISTFORMAT_MYSQL);
// translate the rows into fields...
delete[] stmt->result->fields;
delete[] stmt->result->lengths;
sqlrcursor *sqlrcur=stmt->result->sqlrcur;
uint32_t colcount=sqlrcur->rowCount();
if (colcount) {
MYSQL_FIELD *fields=new MYSQL_FIELD[colcount];
stmt->result->fields=fields;
stmt->result->lengths=new unsigned long[colcount];
for (uint32_t i=0; i<colcount; i++) {
fields[i].name=const_cast<char *>(
sqlrcur->getField(i,(uint32_t)0));
fields[i].table=const_cast<char *>(table);
const char *def=sqlrcur->getField(i,(uint32_t)7);
fields[i].def=(charstring::isNullOrEmpty(def))?
NULL:(char *)def;
#if defined(COMPAT_MYSQL_4_0) || \
defined(COMPAT_MYSQL_4_1) || \
defined(COMPAT_MYSQL_5_0) || \
defined(COMPAT_MYSQL_5_1)
fields[i].org_table=fields[i].table;
fields[i].db=(char *)"";
#if defined(COMPAT_MYSQL_4_1) || \
defined(COMPAT_MYSQL_5_0) || \
defined(COMPAT_MYSQL_5_1)
fields[i].catalog=(char *)"def";
fields[i].org_name=(char *)"";
fields[i].name_length=
charstring::length(fields[i].name);
fields[i].org_name_length=
charstring::length(fields[i].org_name);
fields[i].table_length=
charstring::length(fields[i].table);
fields[i].org_table_length=
charstring::length(fields[i].org_table);
fields[i].db_length=
charstring::length(fields[i].db);
fields[i].catalog_length=
charstring::length(fields[i].catalog);
fields[i].def_length=
charstring::length(fields[i].def);
// FIXME: need a character set number here
fields[i].charsetnr=0;
#endif
#endif
// figure out the column type
const char *columntypestring=
sqlrcur->getField(i,1);
const char *lengthstring=
sqlrcur->getField(i,2);
int64_t prec=sqlrcur->getFieldAsInteger(i,3);
int64_t scale=sqlrcur->getFieldAsInteger(i,4);
const char *nullable=sqlrcur->getField(i,5);
const char *key=sqlrcur->getField(i,6);
const char *extra=sqlrcur->getField(i,8);
enum enum_field_types columntype=
map_col_type(columntypestring,scale);
fields[i].type=columntype;
// determine the length...
unsigned int len=0;
if (!charstring::isNullOrEmpty(lengthstring)) {
len=charstring::toInteger(lengthstring);
} else {
switch (columntype) {
case MYSQL_TYPE_DECIMAL:
len=prec+2;
break;
case MYSQL_TYPE_TINY:
len=4;
break;
case MYSQL_TYPE_SHORT:
len=6;
break;
case MYSQL_TYPE_LONG:
len=11;
break;
case MYSQL_TYPE_FLOAT:
len=12;
break;
case MYSQL_TYPE_DOUBLE:
len=22;
break;
case MYSQL_TYPE_TIMESTAMP:
len=19;
break;
case MYSQL_TYPE_LONGLONG:
len=20;
break;
case MYSQL_TYPE_INT24:
len=9;
break;
case MYSQL_TYPE_DATE:
len=10;
break;
case MYSQL_TYPE_TIME:
len=10;
break;
case MYSQL_TYPE_DATETIME:
len=19;
break;
case MYSQL_TYPE_YEAR:
len=4;
break;
case MYSQL_TYPE_NEWDATE:
len=10;
break;
case MYSQL_TYPE_BIT:
len=1;
break;
case MYSQL_TYPE_TIMESTAMP2:
len=19;
break;
case MYSQL_TYPE_DATETIME2:
len=19;
break;
case MYSQL_TYPE_TIME2:
len=10;
break;
case MYSQL_TYPE_NEWDECIMAL:
len=sqlrcur->getFieldAsInteger(
i,(uint32_t)3)+2;
break;
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
case MYSQL_TYPE_GEOMETRY:
// FIXME: not really sure
// about these
len=8;
break;
default:
// fall back to 50
len=50;
break;
}
}
fields[i].length=len;
// it looks like this is always 0
fields[i].max_length=0;
// figure out the flags
unsigned int flags=0;
if (!isTrue(nullable)) {
flags|=NOT_NULL_FLAG;
}
if (!charstring::compareIgnoringCase(key,"pri")) {
flags|=PRI_KEY_FLAG;
}
if (!charstring::compareIgnoringCase(key,"uni")) {
flags|=UNIQUE_KEY_FLAG;
}
if (!charstring::isNullOrEmpty(key)) {
flags|=MULTIPLE_KEY_FLAG;
}
if (columntype==MYSQL_TYPE_TINY_BLOB ||
columntype==MYSQL_TYPE_MEDIUM_BLOB ||
columntype==MYSQL_TYPE_LONG_BLOB ||
columntype==MYSQL_TYPE_BLOB) {
flags|=BLOB_FLAG;
}
// FIXME: the "unsigned" test won't work with most db's
if (charstring::contains(columntypestring,"unsigned") ||
isUnsignedTypeChar(columntypestring)) {
flags|=UNSIGNED_FLAG;
}
// FIXME: there are probably other
// types that are zero-filled
if (columntype==MYSQL_TYPE_YEAR) {
flags|=ZEROFILL_FLAG;
}
if (isBinaryTypeChar(columntypestring)) {
flags|=BINARY_FLAG;
}
if (columntype==MYSQL_TYPE_ENUM) {
flags|=ENUM_FLAG;
}
if (charstring::contains(extra,"auto_increment")) {
flags|=AUTO_INCREMENT_FLAG;
}
if (columntype==MYSQL_TYPE_TIMESTAMP ||
columntype==MYSQL_TYPE_TIMESTAMP2) {
flags|=TIMESTAMP_FLAG|ON_UPDATE_NOW_FLAG;
}
if (columntype==MYSQL_TYPE_SET) {
flags|=SET_FLAG;
}
if (isNumberTypeChar(columntypestring)) {
flags|=NUM_FLAG;
}
fields[i].flags=flags;
// set the number of decimal places (scale)
fields[i].decimals=scale;
}
// set the field count
stmt->result->fieldcount=colcount;
} else {
stmt->result->fields=NULL;
stmt->result->lengths=NULL;
stmt->result->fieldcount=0;
}
stmt->result->currentfield=0;
// set rowcount beyond the end so no rows can be fetched
stmt->result->currentrow=sqlrcur->rowCount()+1;
MYSQL_RES *retval=stmt->result;
stmt->result=NULL;
return retval;
}
unsigned long mysql_escape_string(char *to, const char *from,
unsigned long length) {
debugFunction();
return mysql_real_escape_string(NULL,to,from,length);
}
char *mysql_odbc_escape_string(MYSQL *mysql, char *to,
unsigned long to_length,
const char *from,
unsigned long from_length,
void *param,
char *(*extend_buffer)
(void *, char *to,
unsigned long *length)) {
debugFunction();
// FIXME: implement this
return NULL;
}
void myodbc_remove_escape(MYSQL *mysql, char *name) {
debugFunction();
// FIXME: implement this
}
unsigned long mysql_real_escape_string(MYSQL *mysql, char *to,
const char *from,
unsigned long length) {
debugFunction();
if (mysql && charstring::compare(mysql->sqlrcon->identify(),"mysql")) {
bytestring::copy(to,from,length);
to[length]='\0';
return length;
}
unsigned long fromindex=0;
unsigned long toindex=0;
while (fromindex<length) {
if (from[fromindex]=='\'') {
to[toindex++]='\\';
to[toindex++]='\'';
} else if (from[fromindex]=='\"') {
to[toindex++]='\\';
to[toindex++]='"';
} else if (from[fromindex]=='\n') {
to[toindex++]='\\';
to[toindex++]='n';
} else if (from[fromindex]=='\r') {
to[toindex++]='\\';
to[toindex++]='r';
} else if (from[fromindex]=='\\') {
to[toindex++]='\\';
to[toindex++]='\\';
} else if (from[fromindex]==26) {
to[toindex++]='\\';
to[toindex++]='Z';
} else {
to[toindex++]=from[fromindex];
}
fromindex++;
}
to[toindex]='\0';
return toindex;
}
int mysql_query(MYSQL *mysql, const char *query) {
debugFunction();
return mysql_real_query(mysql,query,charstring::length(query));
}
int mysql_send_query(MYSQL *mysql, const char *query, unsigned int length) {
debugFunction();
// FIXME: looks like this sends a query in the background then returns
// so we can do something else in the foreground.
return mysql_real_query(mysql,query,length);
}
int mysql_read_query_result(MYSQL *mysql) {
debugFunction();
// FIXME: looks like this checks to see if a query sent with
// mysql_send_query has finished or not
return 0;
}
int mysql_real_query(MYSQL *mysql, const char *query, unsigned long length) {
debugFunction();
mysql_stmt_close(mysql->currentstmt);
mysql->currentstmt=mysql_prepare(mysql,query,length);
return mysql_stmt_execute(mysql->currentstmt);
}
const char *mysql_info(MYSQL *mysql) {
debugFunction();
return NULL;
}
my_ulonglong mysql_insert_id(MYSQL *mysql) {
debugFunction();
return mysql->sqlrcon->getLastInsertId();
}
MYSQL_RES *mysql_store_result(MYSQL *mysql) {
debugFunction();
MYSQL_RES *retval=mysql->currentstmt->result;
mysql->currentstmt->result=NULL;
return retval;
}
MYSQL_RES *mysql_use_result(MYSQL *mysql) {
debugFunction();
return mysql_store_result(mysql);
}
void mysql_free_result(MYSQL_RES *result) {
debugFunction();
if (result) {
delete result->sqlrcur;
if (result->fields) {
delete[] result->fields;
delete[] result->lengths;
}
// if the result is attached to a stmt then set the stmt's
// result pointer to NULL, that way if someone calls
// mysql_free_result, followed by mysql_stmt_close then
// a double free won't occur but calling mysql_stmt_close on
// its own will free the result and close the stmt
if (result->stmtbackptr) {
result->stmtbackptr->result=NULL;
}
delete result;
}
}
my_bool mysql_more_results(MYSQL *mysql) {
debugFunction();
return 0;
}
int mysql_next_result(MYSQL *mysql) {
return -1;
}
unsigned int mysql_num_fields(MYSQL_RES *result) {
debugFunction();
unsigned int retval=result->fieldcount;
debugPrintf("num fields: %d\n",retval);
return retval;
}
MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result) {
debugFunction();
if (result->currentfield>=(MYSQL_FIELD_OFFSET)result->fieldcount) {
return NULL;
}
debugPrintf("name: \"%s\"\n",
result->fields[result->currentfield].name);
return &result->fields[result->currentfield++];
}
MYSQL_FIELD *mysql_fetch_fields(MYSQL_RES *result) {
debugFunction();
result->currentfield=0;
return result->fields;
}
MYSQL_FIELD *mysql_fetch_field_direct(MYSQL_RES *result, unsigned int fieldnr) {
debugFunction();
if (fieldnr>(unsigned int)result->fieldcount) {
return NULL;
}
// FIXME: it's possible that we shouldn't increment the fieldnr here
result->currentfield=fieldnr+1;
return &result->fields[fieldnr];
}
unsigned long *mysql_fetch_lengths(MYSQL_RES *result) {
debugFunction();
uint32_t *lengths=result->sqlrcur->
getRowLengths(result->previousrow);
for (uint32_t i=0; i<result->fieldcount; i++) {
result->lengths[i]=(unsigned long)lengths[i];
}
return result->lengths;
}
unsigned int mysql_field_count(MYSQL *mysql) {
debugFunction();
return mysql_num_fields(mysql->currentstmt->result);
}
MYSQL_FIELD_OFFSET mysql_field_seek(MYSQL_RES *result,
MYSQL_FIELD_OFFSET offset) {
debugFunction();
MYSQL_FIELD_OFFSET oldoffset=result->currentfield;
result->currentfield=offset;
return oldoffset;
}
MYSQL_FIELD_OFFSET mysql_field_tell(MYSQL_RES *result) {
debugFunction();
return result->currentfield;
}
my_ulonglong mysql_num_rows(MYSQL_RES *result) {
debugFunction();
return result->sqlrcur->rowCount();
}
my_ulonglong mysql_affected_rows(MYSQL *mysql) {
debugFunction();
return mysql_stmt_affected_rows(mysql->currentstmt);
}
MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET offset) {
debugFunction();
MYSQL_ROW_OFFSET currentoffset=mysql_row_tell(result);
result->previousrow=result->currentrow;
result->currentrow=
((linkedlistnode< my_ulonglong > *)offset)->getValue();
return (MYSQL_ROW_OFFSET)currentoffset;
}
MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result) {
debugFunction();
linkedlistnode< my_ulonglong > *rowcachenode=
new linkedlistnode< my_ulonglong >(result->currentrow);
result->rowcache.append(rowcachenode);
return (MYSQL_ROW_OFFSET)rowcachenode;
}
void mysql_data_seek(MYSQL_RES *result, my_ulonglong offset) {
debugFunction();
result->previousrow=result->currentrow;
result->currentrow=offset;
}
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result) {
debugFunction();
MYSQL_ROW retval=
(MYSQL_ROW)result->sqlrcur->getRow(result->currentrow);
if (retval) {
result->previousrow=result->currentrow;
result->currentrow++;
}
return retval;
}
my_bool mysql_eof(MYSQL_RES *result) {
debugFunction();
my_ulonglong rowcount=(my_ulonglong)result->sqlrcur->rowCount();
return (!rowcount || result->currentrow>=rowcount);
}
unsigned int mysql_warning_count(MYSQL *mysql) {
debugFunction();
return 0;
}
unsigned int mysql_errno(MYSQL *mysql) {
debugFunction();
debugPrintf("errno: %d\n",mysql->errorno);
return mysql->errorno;
}
const char *mysql_error(MYSQL *mysql) {
debugFunction();
debugPrintf("error: %s\n",mysql->error);
return (mysql->error)?mysql->error:"";
}
const char *mysql_sqlstate(MYSQL *mysql) {
debugFunction();
return mysql_stmt_sqlstate(mysql->currentstmt);
}
my_bool mysql_commit(MYSQL *mysql) {
debugFunction();
return mysql->sqlrcon->commit();
}
my_bool mysql_rollback(MYSQL *mysql) {
debugFunction();
return mysql->sqlrcon->rollback();
}
my_bool mysql_autocommit(MYSQL *mysql, my_bool mode) {
debugFunction();
return (mode)?mysql->sqlrcon->autoCommitOn():
mysql->sqlrcon->autoCommitOff();
}
MYSQL_STMT *mysql_prepare(MYSQL *mysql, const char *query,
unsigned long length) {
debugFunction();
MYSQL_STMT *stmt=mysql_stmt_init(mysql);
if (!mysql_stmt_prepare(stmt,query,length)) {
return stmt;
}
mysql_stmt_close(stmt);
return NULL;
}
my_bool mysql_bind_param(MYSQL_STMT *stmt, MYSQL_BIND *bind) {
debugFunction();
return mysql_stmt_bind_param(stmt,bind);
}
my_bool mysql_bind_result(MYSQL_STMT *stmt, MYSQL_BIND *bind) {
debugFunction();
return mysql_stmt_bind_result(stmt,bind);
}
static enum enum_field_types mysqltypemap[]={
// "UNKNOWN"
MYSQL_TYPE_NULL,
// addded by freetds
// "CHAR"
MYSQL_TYPE_STRING,
// "INT"
MYSQL_TYPE_LONG,
// "SMALLINT"
MYSQL_TYPE_SHORT,
// "TINYINT"
MYSQL_TYPE_TINY,
// "MONEY"
MYSQL_TYPE_NEWDECIMAL,
// "DATETIME"
MYSQL_TYPE_DATETIME,
// "NUMERIC"
MYSQL_TYPE_NEWDECIMAL,
// "DECIMAL"
MYSQL_TYPE_NEWDECIMAL,
// "SMALLDATETIME"
MYSQL_TYPE_DATETIME,
// "SMALLMONEY"
MYSQL_TYPE_NEWDECIMAL,
// "IMAGE"
MYSQL_TYPE_BLOB,
// "BINARY"
MYSQL_TYPE_BLOB,
// "BIT"
MYSQL_TYPE_TINY,
// "REAL"
MYSQL_TYPE_DECIMAL,
// "FLOAT"
MYSQL_TYPE_FLOAT,
// "TEXT"
MYSQL_TYPE_BLOB,
// "VARCHAR"
MYSQL_TYPE_VAR_STRING,
// "VARBINARY"
MYSQL_TYPE_BLOB,
// "LONGCHAR"
MYSQL_TYPE_BLOB,
// "LONGBINARY"
MYSQL_TYPE_BLOB,
// "LONG"
MYSQL_TYPE_BLOB,
// "ILLEGAL"
MYSQL_TYPE_NULL,
// "SENSITIVITY"
MYSQL_TYPE_STRING,
// "BOUNDARY"
MYSQL_TYPE_STRING,
// "VOID"
MYSQL_TYPE_NULL,
// "USHORT"
MYSQL_TYPE_SHORT,
// added by lago
// "UNDEFINED"
MYSQL_TYPE_NULL,
// "DOUBLE"
MYSQL_TYPE_DOUBLE,
// "DATE"
MYSQL_TYPE_DATE,
// "TIME"
MYSQL_TYPE_TIME,
// "TIMESTAMP"
MYSQL_TYPE_TIMESTAMP,
// added by msql
// "UINT"
MYSQL_TYPE_LONG,
// "LASTREAL"
MYSQL_TYPE_DECIMAL,
// added by mysql
// "STRING"
MYSQL_TYPE_STRING,
// "VARSTRING"
MYSQL_TYPE_VAR_STRING,
// "LONGLONG"
MYSQL_TYPE_LONGLONG,
// "MEDIUMINT"
MYSQL_TYPE_INT24,
// "YEAR"
MYSQL_TYPE_YEAR,
// "NEWDATE"
MYSQL_TYPE_NEWDATE,
// "NULL"
MYSQL_TYPE_NULL,
// "ENUM"
MYSQL_TYPE_ENUM,
// "SET"
MYSQL_TYPE_SET,
// "TINYBLOB"
MYSQL_TYPE_TINY_BLOB,
// "MEDIUMBLOB"
MYSQL_TYPE_MEDIUM_BLOB,
// "LONGBLOB"
MYSQL_TYPE_LONG_BLOB,
// "BLOB"
MYSQL_TYPE_BLOB,
// added by oracle
// "VARCHAR2"
MYSQL_TYPE_VAR_STRING,
// "NUMBER"
MYSQL_TYPE_NEWDECIMAL,
// "ROWID"
MYSQL_TYPE_LONGLONG,
// "RAW"
MYSQL_TYPE_BLOB,
// "LONG_RAW"
MYSQL_TYPE_BLOB,
// "MLSLABEL"
MYSQL_TYPE_BLOB,
// "CLOB"
MYSQL_TYPE_BLOB,
// "BFILE"
MYSQL_TYPE_BLOB,
// added by odbc
// "BIGINT"
MYSQL_TYPE_LONGLONG,
// "INTEGER"
MYSQL_TYPE_LONG,
// "LONGVARBINARY"
MYSQL_TYPE_BLOB,
// "LONGVARCHAR"
MYSQL_TYPE_BLOB,
// added by db2
// "GRAPHIC"
MYSQL_TYPE_BLOB,
// "VARGRAPHIC"
MYSQL_TYPE_BLOB,
// "LONGVARGRAPHIC"
MYSQL_TYPE_BLOB,
// "DBCLOB"
MYSQL_TYPE_BLOB,
// "DATALINK"
MYSQL_TYPE_STRING,
// "USER_DEFINED_TYPE"
MYSQL_TYPE_STRING,
// "SHORT_DATATYPE"
MYSQL_TYPE_SHORT,
// "TINY_DATATYPE"
MYSQL_TYPE_TINY,
// added by firebird
// "D_FLOAT"
MYSQL_TYPE_DOUBLE,
// "ARRAY"
MYSQL_TYPE_SET,
// "QUAD"
MYSQL_TYPE_SET,
// "INT64"
MYSQL_TYPE_LONGLONG,
// "DOUBLE PRECISION"
MYSQL_TYPE_DOUBLE,
// added by postgresql
// "BOOL"
MYSQL_TYPE_TINY,
// "BYTEA"
MYSQL_TYPE_BLOB,
// "NAME"
MYSQL_TYPE_STRING,
// "INT8"
MYSQL_TYPE_LONG,
// "INT2"
MYSQL_TYPE_SHORT,
// "INT2VECTOR"
MYSQL_TYPE_SET,
// "INT4"
MYSQL_TYPE_LONG,
// "REGPROC"
MYSQL_TYPE_LONG,
// "OID"
MYSQL_TYPE_LONG,
// "TID"
MYSQL_TYPE_LONG,
// "XID"
MYSQL_TYPE_LONG,
// "CID"
MYSQL_TYPE_LONG,
// "OIDVECTOR"
MYSQL_TYPE_SET,
// "SMGR"
MYSQL_TYPE_STRING,
// "POINT"
MYSQL_TYPE_STRING,
// "LSEG"
MYSQL_TYPE_STRING,
// "PATH"
MYSQL_TYPE_STRING,
// "BOX"
MYSQL_TYPE_STRING,
// "POLYGON"
MYSQL_TYPE_STRING,
// "LINE"
MYSQL_TYPE_STRING,
// "LINE_ARRAY"
MYSQL_TYPE_SET,
// "FLOAT4"
MYSQL_TYPE_FLOAT,
// "FLOAT8"
MYSQL_TYPE_DOUBLE,
// "ABSTIME"
MYSQL_TYPE_LONG,
// "RELTIME"
MYSQL_TYPE_LONG,
// "TINTERVAL"
MYSQL_TYPE_LONG,
// "CIRCLE"
MYSQL_TYPE_STRING,
// "CIRCLE_ARRAY"
MYSQL_TYPE_SET,
// "MONEY_ARRAY"
MYSQL_TYPE_SET,
// "MACADDR"
MYSQL_TYPE_STRING,
// "INET"
MYSQL_TYPE_STRING,
// "CIDR"
MYSQL_TYPE_STRING,
// "BOOL_ARRAY"
MYSQL_TYPE_SET,
// "BYTEA_ARRAY"
MYSQL_TYPE_SET,
// "CHAR_ARRAY"
MYSQL_TYPE_SET,
// "NAME_ARRAY"
MYSQL_TYPE_SET,
// "INT2_ARRAY"
MYSQL_TYPE_SET,
// "INT2VECTOR_ARRAY"
MYSQL_TYPE_SET,
// "INT4_ARRAY"
MYSQL_TYPE_SET,
// "REGPROC_ARRAY"
MYSQL_TYPE_SET,
// "TEXT_ARRAY"
MYSQL_TYPE_SET,
// "OID_ARRAY"
MYSQL_TYPE_SET,
// "TID_ARRAY"
MYSQL_TYPE_SET,
// "XID_ARRAY"
MYSQL_TYPE_SET,
// "CID_ARRAY"
MYSQL_TYPE_SET,
// "OIDVECTOR_ARRAY"
MYSQL_TYPE_SET,
// "BPCHAR_ARRAY"
MYSQL_TYPE_SET,
// "VARCHAR_ARRAY"
MYSQL_TYPE_SET,
// "INT8_ARRAY"
MYSQL_TYPE_SET,
// "POINT_ARRAY"
MYSQL_TYPE_SET,
// "LSEG_ARRAY"
MYSQL_TYPE_SET,
// "PATH_ARRAY"
MYSQL_TYPE_SET,
// "BOX_ARRAY"
MYSQL_TYPE_SET,
// "FLOAT4_ARRAY"
MYSQL_TYPE_SET,
// "FLOAT8_ARRAY"
MYSQL_TYPE_SET,
// "ABSTIME_ARRAY"
MYSQL_TYPE_SET,
// "RELTIME_ARRAY"
MYSQL_TYPE_SET,
// "TINTERVAL_ARRAY"
MYSQL_TYPE_SET,
// "POLYGON_ARRAY"
MYSQL_TYPE_SET,
// "ACLITEM"
MYSQL_TYPE_SET,
// "ACLITEM_ARRAY"
MYSQL_TYPE_SET,
// "MACADDR_ARRAY"
MYSQL_TYPE_SET,
// "INET_ARRAY"
MYSQL_TYPE_SET,
// "CIDR_ARRAY"
MYSQL_TYPE_SET,
// "BPCHAR"
MYSQL_TYPE_STRING,
// "TIMESTAMP_ARRAY"
MYSQL_TYPE_SET,
// "DATE_ARRAY"
MYSQL_TYPE_SET,
// "TIME_ARRAY"
MYSQL_TYPE_SET,
// "TIMESTAMPTZ"
MYSQL_TYPE_STRING,
// "TIMESTAMPTZ_ARRAY"
MYSQL_TYPE_SET,
// "INTERVAL"
MYSQL_TYPE_LONG,
// "INTERVAL_ARRAY"
MYSQL_TYPE_SET,
// "NUMERIC_ARRAY"
MYSQL_TYPE_SET,
// "TIMETZ"
MYSQL_TYPE_STRING,
// "TIMETZ_ARRAY"
MYSQL_TYPE_SET,
// "BIT_ARRAY"
MYSQL_TYPE_SET,
// "VARBIT"
MYSQL_TYPE_STRING,
// "VARBIT_ARRAY"
MYSQL_TYPE_SET,
// "REFCURSOR"
MYSQL_TYPE_LONG,
// "REFCURSOR_ARRAY"
MYSQL_TYPE_SET,
// "REGPROCEDURE"
MYSQL_TYPE_LONG,
// "REGOPER"
MYSQL_TYPE_LONG,
// "REGOPERATOR"
MYSQL_TYPE_LONG,
// "REGCLASS"
MYSQL_TYPE_LONG,
// "REGTYPE"
MYSQL_TYPE_LONG,
// "REGPROCEDURE_ARRAY"
MYSQL_TYPE_SET,
// "REGOPER_ARRAY"
MYSQL_TYPE_SET,
// "REGOPERATOR_ARRAY"
MYSQL_TYPE_SET,
// "REGCLASS_ARRAY"
MYSQL_TYPE_SET,
// "REGTYPE_ARRAY"
MYSQL_TYPE_SET,
// "RECORD"
MYSQL_TYPE_SET,
// "CSTRING"
MYSQL_TYPE_STRING,
// "ANY"
MYSQL_TYPE_STRING,
// "ANYARRAY"
MYSQL_TYPE_SET,
// "TRIGGER"
MYSQL_TYPE_STRING,
// "LANGUAGE_HANDLER"
MYSQL_TYPE_STRING,
// "INTERNAL"
MYSQL_TYPE_STRING,
// "OPAQUE"
MYSQL_TYPE_STRING,
// "ANYELEMENT"
MYSQL_TYPE_STRING,
// "PG_TYPE"
MYSQL_TYPE_STRING,
// "PG_ATTRIBUTE"
MYSQL_TYPE_STRING,
// "PG_PROC"
MYSQL_TYPE_STRING,
// "PG_CLASS"
MYSQL_TYPE_STRING,
// none added by sqlite
// added by sqlserver
// "UBIGINT"
MYSQL_TYPE_LONGLONG,
// "UNIQUEIDENTIFIER"
MYSQL_TYPE_STRING,
// added by informix
// "SMALLFLOAT"
MYSQL_TYPE_FLOAT,
// "BYTE"
MYSQL_TYPE_BLOB,
// "BOOLEAN"
MYSQL_TYPE_TINY,
// "TINYTEXT"
MYSQL_TYPE_BLOB,
// "MEDIUMTEXT"
MYSQL_TYPE_BLOB,
// "LONGTEXT"
MYSQL_TYPE_BLOB,
// "JSON"
MYSQL_TYPE_BLOB,
// "GEOMETRY"
MYSQL_TYPE_BLOB,
// "SDO_GEOMETRY"
MYSQL_TYPE_BLOB,
// "NCHAR"
MYSQL_TYPE_STRING,
// "NVARCHAR"
MYSQL_TYPE_VAR_STRING,
// "NTEXT"
MYSQL_TYPE_BLOB,
// "XML"
MYSQL_TYPE_BLOB,
// "DATETIMEOFFSET"
MYSQL_TYPE_DATETIME
};
enum enum_field_types map_col_type(const char *columntype, int64_t scale) {
debugFunction();
size_t columntypelen=charstring::length(columntype);
// sometimes column types have parentheses, like CHAR(40)
const char *leftparen=charstring::findFirst(columntype,"(");
if (leftparen) {
columntypelen=leftparen-columntype;
}
for (int index=0; datatypestring[index]; index++) {
// compare "columntypelen" bytes but also make sure that the
// byte afterward is a NULL, we don't want "DATE" to match
// "DATETIME" for example
if (!charstring::compareIgnoringCase(
datatypestring[index],
columntype,columntypelen) &&
datatypestring[index][columntypelen]=='\0') {
enum_field_types retval=mysqltypemap[index];
// Some DB's, like oracle, don't distinguish between
// decimal and integer types, they just have a numeric
// field which may or may not have decimal points.
// Those fields types get translated to "decimal"
// but if there are 0 decimal points, then we need to
// translate them to an integer type here.
if ((retval==MYSQL_TYPE_DECIMAL ||
retval==MYSQL_TYPE_NEWDECIMAL) && !scale) {
retval=MYSQL_TYPE_LONG;
}
// Some DB's, like oracle, don't have separate DATE
// and DATETIME types. Rather, a DATE can store the
// date and time, but which components it reports
// depends on something like the NLS_DATE_FORMAT. By
// default, we map DATE to MYSQL_TYPE_DATE, but we also
// provide the option of mapping it to
// MYSQL_TYPE_DATETIME.
if (retval==MYSQL_TYPE_DATE &&
charstring::isYes(
environment::getValue(
"SQLR_MYSQL_MAP_DATE_TO_DATETIME"))) {
retval=MYSQL_TYPE_DATETIME;
}
return retval;
}
}
return MYSQL_TYPE_NULL;
}
int mysql_execute(MYSQL_STMT *stmt) {
debugFunction();
return mysql_stmt_execute(stmt);
}
static void getDate(const char *field, uint32_t length, MYSQL_BIND *bind) {
// result variables
MYSQL_TIME *tm=(MYSQL_TIME *)bind->buffer;
int16_t year=-1;
int16_t month=-1;
int16_t day=-1;
int16_t hour=-1;
int16_t minute=-1;
int16_t second=-1;
int32_t usec=-1;
bool isnegative=false;
// copy into a buffer (to make sure it's null-terminated)
char *buffer=new char[length+1];
charstring::copy(buffer,field,length);
buffer[length]='\0';
// parse
bool ddmm=charstring::isYes(environment::getValue(
"SQLR_MYSQL_DATE_DDMM"));
bool yyyyddmm=ddmm;
const char *yyyyddmmstr=environment::getValue(
"SQLR_MYSQL_DATE_YYYYDDMM");
if (yyyyddmmstr) {
yyyyddmm=charstring::isYes(yyyyddmmstr);
}
datetime::parse(buffer,ddmm,yyyyddmm,
"/-:",&year,&month,&day,
&hour,&minute,&second,
&usec,&isnegative);
// copy back data
tm->year=(year!=-1)?year:0;
tm->month=(month!=-1)?month:0;
tm->day=(day!=-1)?day:0;
tm->hour=(hour!=-1)?hour:0;
tm->minute=(minute!=-1)?minute:0;
tm->second=(second!=-1)?second:0;
tm->neg=isnegative;
// clean up
delete[] buffer;
}
void fixDecimalPoint(char *str) {
struct lconv *l=localeconv();
for (char *c=str; *c; c++) {
if (*c=='.') {
*c=*(l->decimal_point);
}
}
}
int mysql_stmt_fetch(MYSQL_STMT *stmt) {
debugFunction();
// run the query
MYSQL_ROW row=mysql_fetch_row(stmt->result);
if (!row) {
return MYSQL_NO_DATA;
}
// if there are no result binds, just return
if (!stmt->resultbinds) {
return 0;
}
// copy data into result binds
uint32_t *lengths=stmt->result->sqlrcur->
getRowLengths(stmt->result->previousrow);
for (uint32_t i=0; i<stmt->result->fieldcount; i++) {
// Some apps bind fewer bind buffers than there are columns
// in the result set and "NULL" terminate the list with a
// bind buffer containing all zeros. The buffer, length and
// is_null components are all settable. If we find bind
// buffer with those values NULL then assume we've hit the
// NULL terminator.
if (charstring::isYes(environment::getValue(
"SQLR_MYSQL_NULL_TERMINATED_RESULT_BINDS")) &&
!stmt->resultbinds[i].buffer &&
!stmt->resultbinds[i].length &&
!stmt->resultbinds[i].is_null) {
break;
}
// make sure there's something to fetch the data into
if (!&(stmt->resultbinds[i])) {
continue;
}
if (!charstring::length(row[i])) {
// set the null indicator (if we can)
if (stmt->resultbinds[i].is_null) {
*(stmt->resultbinds[i].is_null)=true;
}
} else {
// set the null indicator (if we can)
if (stmt->resultbinds[i].is_null) {
*(stmt->resultbinds[i].is_null)=false;
}
// copy data into the buffer...
switch (stmt->resultbinds[i].buffer_type) {
case MYSQL_TYPE_NULL:
stmt->resultbinds[i].buffer=NULL;
break;
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB: {
// initialize len to the buffer size
unsigned long len=stmt->
resultbinds[i].
buffer_length;
// if the column itself is shorter than
// the buffer size, then reset len
if (lengths[i]<stmt->
resultbinds[i].buffer_length) {
len=lengths[i];
// add 1 for the null terminator
if (stmt->resultbinds[i].
buffer_type==
MYSQL_TYPE_VAR_STRING ||
stmt->resultbinds[i].
buffer_type==
MYSQL_TYPE_STRING) {
len++;
}
}
// set the output length (if we can)
if (stmt->resultbinds[i].length) {
*(stmt->resultbinds[i].
length)=len;
}
// copy data into the buffer (if we can)
if (stmt->resultbinds[i].buffer) {
bytestring::copy(
stmt->resultbinds[i].buffer,
row[i],len);
}
}
break;
case MYSQL_TYPE_TIMESTAMP:
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_NEWDATE:
if (stmt->resultbinds[i].buffer) {
getDate(row[i],lengths[i],
&(stmt->resultbinds[i]));
}
break;
case MYSQL_TYPE_TINY:
if (stmt->resultbinds[i].buffer) {
*((char *)stmt->
resultbinds[i].buffer)=
(char)charstring::
toInteger(row[i]);
}
break;
case MYSQL_TYPE_SHORT:
if (stmt->resultbinds[i].buffer) {
*((uint16_t *)stmt->
resultbinds[i].buffer)=
(uint16_t)charstring::
toInteger(row[i]);
}
break;
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_YEAR:
if (stmt->resultbinds[i].buffer) {
*((uint32_t *)stmt->
resultbinds[i].buffer)=
(uint32_t)charstring::
toInteger(row[i]);
}
break;
case MYSQL_TYPE_LONGLONG:
case MYSQL_TYPE_INT24:
if (stmt->resultbinds[i].buffer) {
*((uint64_t *)stmt->
resultbinds[i].buffer)=
(uint64_t)charstring::
toInteger(row[i]);
}
break;
case MYSQL_TYPE_FLOAT:
if (stmt->resultbinds[i].buffer) {
fixDecimalPoint(row[i]);
*((float *)stmt->
resultbinds[i].buffer)=
(float)charstring::
toFloatC(row[i]);
}
break;
case MYSQL_TYPE_NEWDECIMAL:
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_DOUBLE:
if (stmt->resultbinds[i].buffer) {
fixDecimalPoint(row[i]);
*((double *)stmt->
resultbinds[i].buffer)=
(double)charstring::
toFloatC(row[i]);
}
break;
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
case MYSQL_TYPE_GEOMETRY:
// FIXME: I'm not sure what
// to do with these types
//break;
default:
if (stmt->resultbinds[i].length) {
*(stmt->resultbinds[i].
length)=0;
}
}
}
}
return 0;
}
int mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind,
unsigned int column,
unsigned long offset) {
debugFunction();
// according to the mysql 5.6 docs, this function is:
// "To be added."
return 1;
}
static void processFields(MYSQL_STMT *stmt) {
debugFunction();
delete[] stmt->result->fields;
delete[] stmt->result->lengths;
sqlrcursor *sqlrcur=stmt->result->sqlrcur;
uint32_t colcount=sqlrcur->colCount();
if (colcount) {
MYSQL_FIELD *fields=new MYSQL_FIELD[colcount];
stmt->result->fields=fields;
stmt->result->lengths=new unsigned long[colcount];
for (uint32_t i=0; i<colcount; i++) {
fields[i].name=const_cast<char *>(
sqlrcur->getColumnName(i));
fields[i].table=(char *)"";
fields[i].def=(char *)"";
#if defined(COMPAT_MYSQL_4_0) || \
defined(COMPAT_MYSQL_4_1) || \
defined(COMPAT_MYSQL_5_0) || \
defined(COMPAT_MYSQL_5_1)
fields[i].org_table=(char *)"";
fields[i].db=(char *)"";
#if defined(COMPAT_MYSQL_4_1) || \
defined(COMPAT_MYSQL_5_0) || \
defined(COMPAT_MYSQL_5_1)
fields[i].catalog=(char *)"def";
fields[i].org_name=(char *)"";
fields[i].name_length=
charstring::length(fields[i].name);
fields[i].org_name_length=
charstring::length(fields[i].org_name);
fields[i].table_length=
charstring::length(fields[i].table);
fields[i].org_table_length=
charstring::length(fields[i].org_table);
fields[i].db_length=
charstring::length(fields[i].db);
fields[i].catalog_length=
charstring::length(fields[i].catalog);
fields[i].def_length=
charstring::length(fields[i].def);
// FIXME: need a character set number here
fields[i].charsetnr=0;
#endif
#endif
// figure out the column type
const char *columntypestring=
sqlrcur->getColumnType(i);
int64_t precision=sqlrcur->getColumnPrecision(i);
// Occasionally an integer column will come back with a
// length and scale but no precision. This has got to
// be some kind of error. It causes the column to be
// defined as a decimal and causes various cascading
// problems later. In those cases, also setting the
// scale to 0 is probably the best course of action.
// The column will remain an integer and the length
// instead of precision to size it.
int64_t scale=(precision)?sqlrcur->getColumnScale(i):0;
enum enum_field_types columntype=
map_col_type(columntypestring,scale);
fields[i].type=columntype;
fields[i].length=sqlrcur->getColumnLength(i);
fields[i].max_length=sqlrcur->getLongest(i);
// figure out the flags
unsigned int flags=0;
if (sqlrcur->getColumnIsNullable(i)) {
flags|=NOT_NULL_FLAG;
}
if (sqlrcur->getColumnIsPrimaryKey(i)) {
flags|=PRI_KEY_FLAG;
}
if (sqlrcur->getColumnIsUnique(i)) {
flags|=UNIQUE_KEY_FLAG;
}
if (sqlrcur->getColumnIsPartOfKey(i)) {
flags|=MULTIPLE_KEY_FLAG;
}
if (columntype==MYSQL_TYPE_TINY_BLOB ||
columntype==MYSQL_TYPE_MEDIUM_BLOB ||
columntype==MYSQL_TYPE_LONG_BLOB ||
columntype==MYSQL_TYPE_BLOB) {
flags|=BLOB_FLAG;
}
// FIXME: the "unsigned" test won't work with most db's
if (charstring::contains(columntypestring,"unsigned") ||
sqlrcur->getColumnIsUnsigned(i) ||
isUnsignedTypeChar(columntypestring)) {
flags|=UNSIGNED_FLAG;
}
if (sqlrcur->getColumnIsZeroFilled(i)) {
flags|=ZEROFILL_FLAG;
}
if (sqlrcur->getColumnIsBinary(i) ||
isBinaryTypeChar(columntypestring)) {
flags|=BINARY_FLAG;
}
if (columntype==MYSQL_TYPE_ENUM) {
flags|=ENUM_FLAG;
}
if (sqlrcur->getColumnIsAutoIncrement(i)) {
flags|=AUTO_INCREMENT_FLAG;
}
if (columntype==MYSQL_TYPE_TIMESTAMP ||
columntype==MYSQL_TYPE_TIMESTAMP2) {
flags|=TIMESTAMP_FLAG|ON_UPDATE_NOW_FLAG;
}
if (columntype==MYSQL_TYPE_SET) {
flags|=SET_FLAG;
}
if (isNumberTypeChar(columntypestring)) {
flags|=NUM_FLAG;
}
fields[i].flags=flags;
fields[i].decimals=scale;
}
// set the field count
stmt->result->fieldcount=colcount;
} else {
stmt->result->fields=NULL;
stmt->result->lengths=NULL;
stmt->result->fieldcount=0;
}
}
unsigned long mysql_param_count(MYSQL_STMT *stmt) {
debugFunction();
return mysql_stmt_param_count(stmt);
}
MYSQL_RES *mysql_param_result(MYSQL_STMT *stmt) {
debugFunction();
// FIXME: The MySQL docs don't even explain this one
return NULL;
}
int mysql_fetch(MYSQL_STMT *stmt) {
debugFunction();
return mysql_stmt_fetch(stmt);
}
int mysql_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind,
unsigned int column, unsigned long offset) {
debugFunction();
return mysql_stmt_fetch_column(stmt,bind,column,offset);
}
MYSQL_RES *mysql_get_metadata(MYSQL_STMT *stmt) {
debugFunction();
return mysql_stmt_result_metadata(stmt);
}
my_bool mysql_send_long_data(MYSQL_STMT *stmt,
unsigned int parameternumber,
const char *data, unsigned long length) {
debugFunction();
return mysql_stmt_send_long_data(stmt,parameternumber,data,length);
}
MYSQL_STMT *mysql_stmt_init(MYSQL *mysql) {
debugFunction();
MYSQL_STMT *stmt=new MYSQL_STMT;
stmt->mysql=mysql;
stmt->result=new MYSQL_RES;
stmt->result->stmtbackptr=stmt;
stmt->result->sqlrcur=new sqlrcursor(mysql->sqlrcon,true);
stmt->result->errorno=0;
stmt->result->fields=NULL;
stmt->result->lengths=NULL;
return stmt;
}
int mysql_stmt_prepare(MYSQL_STMT *stmt,
const char *query,
unsigned long length) {
debugFunction();
debugPrintf(query);
debugPrintf("\n");
stmt->resultbinds=NULL;
stmt->result->sqlrcur->prepareQuery(query,length);
return 0;
}
int mysql_stmt_execute(MYSQL_STMT *stmt) {
debugFunction();
setMySQLError(stmt->mysql,NULL,0);
stmt->result->previousrow=0;
stmt->result->currentrow=0;
stmt->result->currentfield=0;
stmt->result->rowcache.clear();
sqlrcursor *sqlrcur=stmt->result->sqlrcur;
int retval=!sqlrcur->executeQuery();
processFields(stmt);
if (retval) {
setMySQLError(stmt->mysql,
sqlrcur->errorMessage(),
mapErrorNumber(stmt->mysql,
sqlrcur->errorNumber()));
}
return retval;
}
my_ulonglong mysql_stmt_num_rows(MYSQL_STMT *stmt) {
debugFunction();
return mysql_num_rows(stmt->result);
}
my_ulonglong mysql_stmt_affected_rows(MYSQL_STMT *stmt) {
debugFunction();
return stmt->result->sqlrcur->affectedRows();
}
MYSQL_ROW_OFFSET mysql_stmt_row_seek(MYSQL_STMT *stmt,
MYSQL_ROW_OFFSET offset) {
debugFunction();
return mysql_row_seek(stmt->result,offset);
}
MYSQL_ROW_OFFSET mysql_stmt_row_tell(MYSQL_STMT *stmt) {
debugFunction();
return mysql_row_tell(stmt->result);
}
void mysql_stmt_data_seek(MYSQL_STMT *stmt, my_ulonglong offset) {
debugFunction();
mysql_data_seek(stmt->result,offset);
}
my_bool mysql_stmt_close(MYSQL_STMT *stmt) {
debugFunction();
if (stmt) {
mysql_free_result(stmt->result);
delete stmt;
}
return 0;
}
unsigned int mysql_stmt_errno(MYSQL_STMT *stmt) {
debugFunction();
return mysql_errno(stmt->mysql);
}
const char *mysql_stmt_error(MYSQL_STMT *stmt) {
debugFunction();
return mysql_error(stmt->mysql);
}
my_ulonglong mysql_stmt_insert_id(MYSQL_STMT *stmt) {
debugFunction();
return stmt->mysql->sqlrcon->getLastInsertId();
}
unsigned int mysql_stmt_field_count(MYSQL_STMT *stmt) {
debugFunction();
return mysql_num_fields(stmt->result);
}
const char *mysql_stmt_sqlstate(MYSQL_STMT *stmt) {
debugFunction();
// FIXME:
return "";
}
int mysql_stmt_store_result(MYSQL_STMT *stmt) {
debugFunction();
return 0;
}
unsigned long mysql_stmt_param_count(MYSQL_STMT * stmt) {
debugFunction();
return stmt->result->sqlrcur->countBindVariables();
}
my_bool mysql_stmt_attr_set(MYSQL_STMT *stmt,
enum enum_stmt_attr_type attrtype,
const void *attr) {
debugFunction();
switch (attrtype) {
case STMT_ATTR_UPDATE_MAX_LENGTH:
break;
case STMT_ATTR_CURSOR_TYPE:
break;
case STMT_ATTR_PREFETCH_ROWS:
const unsigned long *val=
(const unsigned long *)attr;
stmt->result->sqlrcur->
setResultSetBufferSize((uint64_t)(*val));
break;
}
return 0;
}
my_bool mysql_stmt_attr_get(MYSQL_STMT *stmt,
enum enum_stmt_attr_type attrtype,
void *attr) {
debugFunction();
switch (attrtype) {
case STMT_ATTR_UPDATE_MAX_LENGTH:
break;
case STMT_ATTR_CURSOR_TYPE:
break;
case STMT_ATTR_PREFETCH_ROWS:
unsigned long *val=(unsigned long *)attr;
*val=(unsigned long)stmt->result->sqlrcur->
getResultSetBufferSize();
break;
}
return 0;
}
my_bool mysql_stmt_bind_param(MYSQL_STMT *stmt, MYSQL_BIND *bind) {
debugFunction();
stmt->bindvarnames.clear();
unsigned long paramcount=mysql_param_count(stmt);
for (unsigned long i=0; i<paramcount; i++) {
// use 1-based index for variable names
size_t buffersize=charstring::integerLength((uint32_t)i+1)+1;
char *variable=
(char *)stmt->bindvarnames.allocate(buffersize);
charstring::printf(variable,buffersize,"%ld",i+1);
// get the cursor
sqlrcursor *cursor=stmt->result->sqlrcur;
// handle null's first
if (*(bind[i].is_null)) {
cursor->inputBind(variable,(char *)NULL);
continue;
}
// handle various datatypes
switch (bind[i].buffer_type) {
case MYSQL_TYPE_NULL: {
cursor->inputBind(variable,(char *)NULL);
break;
}
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING: {
char *value=(char *)bind[i].buffer;
cursor->inputBind(variable,value);
break;
}
case MYSQL_TYPE_DATE: {
MYSQL_TIME *tm=
(MYSQL_TIME *)bind[i].buffer;
cursor->inputBind(variable,
tm->year,
tm->month,
tm->day,
-1,
-1,
-1,
-1,
NULL,
tm->neg);
break;
}
case MYSQL_TYPE_TIME: {
MYSQL_TIME *tm=
(MYSQL_TIME *)bind[i].buffer;
cursor->inputBind(variable,
-1,
-1,
((tm->neg)?-1:1)*tm->day,
tm->hour,
tm->minute,
tm->second,
0,
NULL,
tm->neg);
break;
}
case MYSQL_TYPE_TIMESTAMP:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_NEWDATE: {
MYSQL_TIME *tm=
(MYSQL_TIME *)bind[i].buffer;
cursor->inputBind(variable,
tm->year,
tm->month,
tm->day,
tm->hour,
tm->minute,
tm->second,
0,
NULL,
tm->neg);
break;
}
case MYSQL_TYPE_NEWDECIMAL:
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_FLOAT:
case MYSQL_TYPE_DOUBLE: {
double value=*((double *)bind[i].buffer);
cursor->inputBind(variable,value,0,0);
break;
}
case MYSQL_TYPE_TINY: {
int8_t value=*((int8_t *)bind[i].buffer);
cursor->inputBind(variable,value);
break;
}
case MYSQL_TYPE_SHORT: {
int64_t value=*((int16_t *)bind[i].buffer);
cursor->inputBind(variable,value);
break;
}
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_YEAR: {
int64_t value=*((int32_t *)bind[i].buffer);
cursor->inputBind(variable,value);
break;
}
case MYSQL_TYPE_LONGLONG:
case MYSQL_TYPE_INT24: {
int64_t value=*((int64_t *)bind[i].buffer);
cursor->inputBind(variable,value);
break;
}
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB: {
char *value=(char *)bind[i].buffer;
unsigned long size=*(bind[i].length);
cursor->inputBindBlob(variable,value,size);
break;
}
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
case MYSQL_TYPE_GEOMETRY: {
// FIXME: what should I do here?
return 1;
}
default: {
// FIXME: what should I do here?
return 1;
}
}
}
return 0;
}
my_bool mysql_stmt_bind_result(MYSQL_STMT *stmt, MYSQL_BIND *bind) {
debugFunction();
stmt->resultbinds=bind;
return 0;
}
my_bool mysql_stmt_send_long_data(MYSQL_STMT *stmt,
unsigned int paramnumber,
const char *data,
unsigned long length) {
debugFunction();
return 1;
}
MYSQL_RES *mysql_stmt_result_metadata(MYSQL_STMT *stmt) {
debugFunction();
return stmt->result;
}
MYSQL_RES *mysql_stmt_param_metadata(MYSQL_STMT *stmt) {
debugFunction();
// according to the mysql 5.6 docs:
// "This function currently does nothing."
return NULL;
}
my_bool mysql_stmt_free_result(MYSQL_STMT *stmt) {
debugFunction();
mysql_free_result(stmt->result);
return 0;
}
my_bool mysql_stmt_reset(MYSQL_STMT *stmt) {
debugFunction();
stmt->result->sqlrcur->clearBinds();
return 0;
}
int mysql_server_init(int argc, char **argv, char **groups) {
debugFunction();
mysql_library_init(argc,argv,groups);
return 0;
}
void mysql_library_init(int argc, char **argv, char **groups) {
debugFunction();
my_init();
}
void mysql_server_end() {
debugFunction();
mysql_library_end();
}
void mysql_library_end() {
debugFunction();
}
my_bool mysql_embedded() {
debugFunction();
return 0;
}
int unknownError(MYSQL *mysql) {
setMySQLError(mysql,"Unknown MySQL error",CR_UNKNOWN_ERROR);
return CR_UNKNOWN_ERROR;
}
void setMySQLError(MYSQL *mysql, const char *error, unsigned int errorno) {
debugFunction();
mysql->errorno=errorno;
delete[] mysql->error;
mysql->error=charstring::duplicate(error);
}
unsigned int mapErrorNumber(MYSQL *mysql, int64_t errorno) {
debugFunction();
unsigned int retval=CR_UNKNOWN_ERROR;
if (mysql->errormap) {
mysql->errormap->getValue(errorno,&retval);
} else {
if (!mysql->backendchecked) {
mysql->backendismysql=
!charstring::compare(
mysql->sqlrcon->identify(),"mysql");
mysql->backendchecked=true;
}
if (mysql->backendismysql) {
retval=errorno;
}
}
return retval;
}
void loadErrorMap(MYSQL *mysql, const char *errormap) {
debugFunction();
debugPrintf("error map file: %s\n",errormap);
// parse the error map file
file mapfile;
if (!mapfile.open(errormap,O_RDONLY)) {
debugPrintf("failed to open error map file\n");
return;
}
// create a new errormap
mysql->errormap=new dictionary< int64_t, unsigned int >;
// run through the file, line-by line...
char *line=NULL;
ssize_t linelength=0;
for (;;) {
// clean up after the previous line
delete[] line;
// get a line
linelength=mapfile.read(&line,"\n");
if (linelength<1) {
return;
}
// ignore lines that start with #'s (comments)
if (line[0]=='#') {
continue;
}
// it should be in <native code>:<mysql code> format...
const char *colon=charstring::findFirst(line,':');
if (colon) {
int64_t nativecode=charstring::toInteger(line);
unsigned int mysqlcode=
(unsigned int)charstring::toInteger(colon+1);
mysql->errormap->setValue(nativecode,mysqlcode);
}
}
}
}
| 25.255527 | 83 | 0.703315 | laigor |
6643314eb2e52bc8a69dca09ab2e2ef51cf5e11c | 1,160 | hpp | C++ | plugins/terrain_plugin/include/TerrainQuadtree.hpp | fuchstraumer/Caelestis | 9c4b76288220681bb245d84e5d7bf8c7f69b2716 | [
"MIT"
] | 5 | 2018-08-16T00:55:33.000Z | 2020-06-19T14:30:17.000Z | plugins/terrain_plugin/include/TerrainQuadtree.hpp | fuchstraumer/Caelestis | 9c4b76288220681bb245d84e5d7bf8c7f69b2716 | [
"MIT"
] | null | null | null | plugins/terrain_plugin/include/TerrainQuadtree.hpp | fuchstraumer/Caelestis | 9c4b76288220681bb245d84e5d7bf8c7f69b2716 | [
"MIT"
] | null | null | null | #pragma once
#ifndef TERRAIN_PLUGIN_QUADTREE_HPP
#define TERRAIN_PLUGIN_QUADTREE_HPP
#include "ForwardDecl.hpp"
#include "glm/vec3.hpp"
#include "glm/mat4x4.hpp"
#include <unordered_map>
#include <memory>
#include <vulkan/vulkan.h>
class HeightNode;
class TerrainNode;
class TerrainQuadtree {
TerrainQuadtree(const TerrainQuadtree&) = delete;
TerrainQuadtree& operator=(const TerrainQuadtree&) = delete;
public:
TerrainQuadtree(const vpr::Device* device, const float& split_factor, const size_t& max_detail_level, const double& root_side_length, const glm::vec3& root_tile_position);
void SetupNodePipeline(const VkRenderPass& renderpass, const glm::mat4& projection);
void UpdateQuadtree(const glm::vec3 & camera_position, const glm::mat4& view);
void RenderNodes(VkCommandBuffer& graphics_cmd, VkCommandBufferBeginInfo& begin_info, const glm::mat4& view, const glm::vec3& camera_pos, const VkViewport& viewport, const VkRect2D& rect);
private:
std::unique_ptr<TerrainNode> root;
std::unordered_map<glm::ivec3, std::shared_ptr<HeightNode>> cachedHeightData;
size_t MaxLOD;
};
#endif // !TERRAIN_PLUGIN_QUADTREE_HPP
| 34.117647 | 192 | 0.776724 | fuchstraumer |
6643f8daf3ed7a59e05d29becc0c3db22161fc59 | 8,700 | cpp | C++ | sta-src/Astro-Core/cartesianTOrotating.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 6 | 2018-09-05T12:41:59.000Z | 2021-07-01T05:34:23.000Z | sta-src/Astro-Core/cartesianTOrotating.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-02-07T19:09:21.000Z | 2015-08-14T03:15:42.000Z | sta-src/Astro-Core/cartesianTOrotating.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-03-25T15:50:31.000Z | 2017-12-06T12:16:47.000Z |
/*
This program 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 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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
------ Copyright (C) 2009 European Space Agency (space.trajectory.analysis AT gmail.com) ----
------------------ Author: Valentino Zuccarelli -------------------------------------------------
------------------ E-mail: (Valentino.Zuccarelli@gmail.com) ----------------------------
*/
#include "cartesianTOrotating.h"
#include "stabody.h"
#include "stamath.h"
#include "threebodyParametersComputation.h"
#include "ascendingNode.h"
#include <QDebug>
/* this subroutine allows to go from the inertial body centred (usually: Sun or Earth)
to the normalized co-rotating r.f. defined in the 3b-problem.
*/
sta::StateVector
cartesianTOrotating (int mode, const StaBody* firstbody, const StaBody* secondbody, sta::StateVector cartesian, double JD)
{
sta::StateVector rotating;
const StaBody* sun = STA_SOLAR_SYSTEM->sun();
double mu1=getGravParam_user(sun->mu(), secondbody->mu());
double mu2=getGravParam_user(firstbody->mu(),secondbody->mu());
//double velocity1=secondbody->linearV();
double velocity1=sqrt(sun->mu()/secondbody->distance());
//ephemerides of the 2nd body relative to the Sun
Eigen::Vector3d positionBody2 = secondbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).position;
Eigen::Vector3d velocityBody2 = secondbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).velocity;
velocity1=velocityBody2.norm();
//velocity1=secondbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).velocity.norm();
double distance1=positionBody2.norm();
double i;
double alfa=0; double beta=0;
Eigen::Vector3d baricenter;
//coefficients for coming computations
//double A, B, a, b, c;
if (firstbody != sun) //we are considering a system like Earth-Moon or Saturn-Titan (the Sun is NOT the first body!)
{
//qDebug()<<"CASE 1: NO SUN";
//velocity1=sqrt(firstbody->mu()/secondbody->distance());
Eigen::Vector3d positionBody1 = firstbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).position;
Eigen::Vector3d positionBody1_Body2 = positionBody2 - positionBody1;
//distance1=secondbody->distance()-firstbody->distance();
distance1=positionBody1_Body2.norm();
Eigen::Vector3d velocityBody1 = firstbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).velocity;
Eigen::Vector3d velocityBody2 = secondbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).velocity;
Eigen::Vector3d velocityBody1_Body2 = velocityBody2 - velocityBody1;
velocity1=velocityBody1_Body2.norm();
//alfa = acos (positionBody1_Body2.z()/distance2);
double nodeJD;
ascendingNodeAngle (firstbody, secondbody, JD, nodeJD, alfa);
beta=trueAnomalyFromAscNode (firstbody, secondbody, JD, nodeJD, alfa);
//beta = atan2 (sqrt(pow(positionBody1_Body2.x(),2.0)+pow(positionBody1_Body2.y(),2.0)),positionBody1_Body2.z());
//alfa = atan2 (positionBody1_Body2.y(), positionBody1_Body2.x());
Eigen::Vector3d velocityCart=secondbody->stateVector(JD, firstbody, sta::COORDSYS_EME_J2000).velocity;
Eigen::Vector3d crossProd=positionBody1_Body2.cross(velocityCart);
//double inclinationReq;
i=acos(crossProd(2)/crossProd.norm());
//qDebug()<<sta::radToDeg(i);
//mu1=mu2;
if (mode==0 || mode==1 || mode==3) //the initial orbit was around the 1st body
{
baricenter(0)= (-mu2);//*cos(beta)*sin(alfa); baricenter(1)= (mu2)*sin(beta)*sin(alfa); baricenter(2)= (mu2)*cos(alfa);
//a=b=c=0;
}
else if (mode==2 || mode==4) //the initial orbit was around the 2nd body
{
baricenter(0)= (+1-mu2);//*cos(beta)*sin(alfa); baricenter(1)= (-1+mu2)*sin(beta)*sin(alfa); baricenter(2)= (-1+mu2)*cos(alfa);
//a=b=c=0;
}
//A=-1/cos(alfa)*((cartesian.position.x()/distance1-baricenter(0))*cos(beta)+(cartesian.position.y()/distance1-baricenter(1))*sin(beta));
//B=1/(cos(beta)*sin(alfa))*((cartesian.position.y()/distance1-baricenter(1))*sin(alfa)+(cartesian.position.z()/distance1-baricenter(2))*sin(beta)*cos(alfa));
rotating.position.x()=(cartesian.position.x()*(cos(alfa)*cos(beta)-cos(i)*sin(alfa)*sin(beta))+cartesian.position.y()*(cos(alfa)*sin(beta)*cos(i)+sin(alfa)*cos(beta))+cartesian.position.z()*sin(i)*sin(beta))/distance1+baricenter(0);
rotating.position.y()=(cartesian.position.x()*(-cos(i)*sin(alfa)*cos(beta)-cos(alfa)*sin(beta))+cartesian.position.y()*(cos(i)*cos(alfa)*cos(beta)-sin(alfa)*sin(beta))+cartesian.position.z()*(sin(i)*cos(beta)))/distance1;
rotating.position.z()=(cartesian.position.x()*(sin(i)*sin(alfa))-cartesian.position.y()*(sin(i)*cos(alfa))+cartesian.position.z()*cos(i))/distance1;
}
else
{
//same transformation applied to a Sun-body system. This has to be done in any case
//position of body 2 relative to body1
//qDebug()<<"CASE 2: SUN";
//alfa = acos (positionBody2.z()/distance1);
double nodeJD;
ascendingNodeAngle (firstbody, secondbody, JD, nodeJD, alfa);
beta=trueAnomalyFromAscNode (firstbody, secondbody, JD, nodeJD, alfa);
Eigen::Vector3d velocityCart=secondbody->stateVector(JD, firstbody, sta::COORDSYS_EME_J2000).velocity;
Eigen::Vector3d crossProd=positionBody2.cross(velocityCart);
//double inclinationReq;
i=acos(crossProd(2)/crossProd.norm());
if (mode==0 || mode==1 || mode==3) //the initial orbit was around the 1st body
{
baricenter(0)= (-mu1);//*cos(beta)*sin(alfa); baricenter(1)= (mu1)*sin(beta)*sin(alfa); baricenter(2)= (mu1)*cos(alfa);
//a=b=c=0;
}
else if (mode==2 || mode==4) //the initial orbit was around the 2nd body
{
baricenter(0)= (+1-mu1);//*cos(beta)*sin(alfa); baricenter(1)= (-1+mu1)*sin(beta)*sin(alfa); baricenter(2)= (-1+mu1)*cos(alfa);
//a=b=c=0;
}
//A=-1/cos(alfa)*((cartesian.position.x()/distance1-baricenter(0))*cos(beta)+(cartesian.position.y()/distance1-baricenter(1))*sin(beta));
//B=1/(cos(beta)*sin(alfa))*((cartesian.position.y()/distance1-baricenter(1))*sin(alfa)+(cartesian.position.z()/distance1-baricenter(2))*sin(beta)*cos(alfa));
rotating.position.x()=(cartesian.position.x()*(cos(alfa)*cos(beta)-cos(i)*sin(alfa)*sin(beta))+cartesian.position.y()*(cos(alfa)*sin(beta)*cos(i)+sin(alfa)*cos(beta))+cartesian.position.z()*sin(i)*sin(beta))/distance1+baricenter(0);
rotating.position.y()=(cartesian.position.x()*(-cos(i)*sin(alfa)*cos(beta)-cos(alfa)*sin(beta))+cartesian.position.y()*(cos(i)*cos(alfa)*cos(beta)-sin(alfa)*sin(beta))+cartesian.position.z()*(sin(i)*cos(beta)))/distance1;
rotating.position.z()=(cartesian.position.x()*(sin(i)*sin(alfa))-cartesian.position.y()*(sin(i)*cos(alfa))+cartesian.position.z()*cos(i))/distance1;
}
//A=-1/cos(alfa)*((cartesian.velocity.x()/velocity1)*cos(beta)+(cartesian.velocity.y()/velocity1)*sin(beta));
//B=1/(cos(beta)*sin(alfa))*((cartesian.velocity.y()/velocity1)*sin(alfa)+(cartesian.velocity.z()/velocity1)*sin(beta)*cos(alfa));
rotating.velocity.x()=(cartesian.velocity.x()*(cos(alfa)*cos(beta)-cos(i)*sin(alfa)*sin(beta))+cartesian.velocity.y()*(cos(alfa)*sin(beta)*cos(i)+sin(alfa)*cos(beta))+cartesian.velocity.z()*sin(i)*sin(beta))/velocity1;
rotating.velocity.y()=(cartesian.velocity.x()*(-cos(i)*sin(alfa)*cos(beta)-cos(alfa)*sin(beta))+cartesian.velocity.y()*(cos(i)*cos(alfa)*cos(beta)-sin(alfa)*sin(beta))+cartesian.velocity.z()*(sin(i)*cos(beta)))/velocity1;
rotating.velocity.z()=(cartesian.velocity.x()*(sin(i)*sin(alfa))-cartesian.velocity.y()*(sin(i)*cos(alfa))+cartesian.velocity.z()*cos(i))/velocity1;
return rotating;
}
| 58.783784 | 240 | 0.661034 | hoehnp |
66466076d3c21cacd2d367ed0ca33b82af0d74b8 | 36,780 | cpp | C++ | CLucene/core/CLucene/index/SegmentInfos.cpp | asheeshv/CLucene-iOS-Android-Win8 | 46d3728178c59842472d43ebbb814375713ca7fa | [
"Apache-1.1"
] | 2 | 2015-06-23T13:22:17.000Z | 2019-04-28T06:35:02.000Z | CLucene/core/CLucene/index/SegmentInfos.cpp | asheeshv/CLucene-iOS-Android-Win8 | 46d3728178c59842472d43ebbb814375713ca7fa | [
"Apache-1.1"
] | null | null | null | CLucene/core/CLucene/index/SegmentInfos.cpp | asheeshv/CLucene-iOS-Android-Win8 | 46d3728178c59842472d43ebbb814375713ca7fa | [
"Apache-1.1"
] | null | null | null | /*------------------------------------------------------------------------------
* Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team
*
* Distributable under the terms of either the Apache License (Version 2.0) or
* the GNU Lesser General Public License, as specified in the COPYING file.
------------------------------------------------------------------------------*/
#include "CLucene/_ApiHeader.h"
#include "_SegmentInfos.h"
#include "_IndexFileNames.h"
#include "_SegmentHeader.h"
#include "MultiReader.h"
#include <assert.h>
#include <iostream>
#include "CLucene/store/Directory.h"
#include "CLucene/util/Misc.h"
CL_NS_USE(store)
CL_NS_USE(util)
CL_NS_DEF(index)
SegmentInfo::SegmentInfo(const char* _name, const int32_t _docCount, CL_NS(store)::Directory* _dir,
bool _isCompoundFile, bool _hasSingleNormFile,
int32_t _docStoreOffset, const char* _docStoreSegment, bool _docStoreIsCompoundFile)
:
docCount(_docCount),
preLockless(false),
delGen(SegmentInfo::NO),
isCompoundFile(_isCompoundFile ? SegmentInfo::YES : SegmentInfo::NO),
hasSingleNormFile(_hasSingleNormFile),
_sizeInBytes(-1),
docStoreOffset(_docStoreOffset),
docStoreSegment( _docStoreSegment == NULL ? "" : _docStoreSegment ),
docStoreIsCompoundFile(_docStoreIsCompoundFile)
{
CND_PRECONDITION(docStoreOffset == -1 || !docStoreSegment.empty(), "failed testing for (docStoreOffset == -1 || docStoreSegment != NULL)");
this->name = _name;
this->dir = _dir;
}
string SegmentInfo::segString(Directory* dir) {
string cfs;
try {
if (getUseCompoundFile())
cfs = "c";
else
cfs = "C";
} catch (CLuceneError& ioe) {
if ( ioe.number() != CL_ERR_IO ) throw ioe;
cfs = "?";
}
string docStore;
if (docStoreOffset != -1)
docStore = string("->") + docStoreSegment;
else
docStore = "";
return string(name) + ":" +
cfs +
string(this->dir == dir ? "" : "x") +
Misc::toString(docCount) + docStore;
}
SegmentInfo::SegmentInfo(CL_NS(store)::Directory* _dir, int32_t format, CL_NS(store)::IndexInput* input):
_sizeInBytes(-1)
{
this->dir = _dir;
{
char aname[CL_MAX_PATH];
input->readString(aname, CL_MAX_PATH);
this->name = aname;
}
docCount = input->readInt();
if (format <= SegmentInfos::FORMAT_LOCKLESS) {
delGen = input->readLong();
if (format <= SegmentInfos::FORMAT_SHARED_DOC_STORE) {
docStoreOffset = input->readInt();
if (docStoreOffset != -1) {
char aname[CL_MAX_PATH];
input->readString(aname, CL_MAX_PATH);
docStoreSegment = aname;
docStoreIsCompoundFile = (1 == input->readByte());
} else {
docStoreSegment = name;
docStoreIsCompoundFile = false;
}
} else {
docStoreOffset = -1;
docStoreSegment = name;
docStoreIsCompoundFile = false;
}
if (format <= SegmentInfos::FORMAT_SINGLE_NORM_FILE) {
hasSingleNormFile = (1 == input->readByte());
} else {
hasSingleNormFile = false;
}
int32_t numNormGen = input->readInt();
normGen.deleteValues();
if (numNormGen == NO) {
// normGen is already NULL, we'll just set normGenLen to 0
} else {
normGen.values = _CL_NEWARRAY(int64_t, numNormGen);
normGen.length = numNormGen;
for(int32_t j=0;j<numNormGen;j++) {
normGen.values[j] = input->readLong();
}
}
isCompoundFile = input->readByte();
preLockless = (isCompoundFile == CHECK_DIR);
} else {
delGen = CHECK_DIR;
//normGen=NULL; normGenLen=0;
isCompoundFile = CHECK_DIR;
preLockless = true;
hasSingleNormFile = false;
docStoreOffset = -1;
docStoreIsCompoundFile = false;
}
}
void SegmentInfo::reset(const SegmentInfo* src) {
clearFiles();
this->name = src->name;
docCount = src->docCount;
dir = src->dir;
preLockless = src->preLockless;
delGen = src->delGen;
docStoreOffset = src->docStoreOffset;
docStoreIsCompoundFile = src->docStoreIsCompoundFile;
if (src->normGen.values == NULL) {
this->normGen.deleteValues();
}else{
// optimized case to allocate new array only if current memory buffer is too small
if (this->normGen.length < src->normGen.length) {
normGen.resize(src->normGen.length);
}else{
this->normGen.length = src->normGen.length;
}
memcpy(this->normGen.values, src->normGen.values, sizeof(int64_t) * this->normGen.length);
}
isCompoundFile = src->isCompoundFile;
hasSingleNormFile = src->hasSingleNormFile;
}
SegmentInfo::~SegmentInfo(){
normGen.deleteValues();
}
void SegmentInfo::setNumFields(const int32_t numFields) {
if (normGen.values == NULL) {
// normGen is null if we loaded a pre-2.1 segment
// file, or, if this segments file hasn't had any
// norms set against it yet:
normGen.resize(numFields);
if (preLockless) {
// Do nothing: thus leaving normGen[k]==CHECK_DIR (==0), so that later we know
// we have to check filesystem for norm files, because this is prelockless.
} else {
// This is a FORMAT_LOCKLESS segment, which means
// there are no separate norms:
for(int32_t i=0;i<numFields;i++) {
normGen.values[i] = NO;
}
}
}
}
/** Returns total size in bytes of all of files used by
* this segment. */
int64_t SegmentInfo::sizeInBytes(){
if (_sizeInBytes == -1) {
const vector<string>& __files = files();
size_t size = __files.size();
_sizeInBytes = 0;
for(size_t i=0;i<size;i++) {
const char* fileName = __files[i].c_str();
// We don't count bytes used by a shared doc store
// against this segment:
if (docStoreOffset == -1 || !IndexFileNames::isDocStoreFile(fileName))
_sizeInBytes += dir->fileLength(fileName);
}
}
return _sizeInBytes;
}
void SegmentInfo::addIfExists(std::vector<std::string>& files, const std::string& fileName){
if (dir->fileExists(fileName.c_str()))
files.push_back(fileName);
}
const vector<string>& SegmentInfo::files(){
if (!_files.empty()) {
// Already cached:
return _files;
}
bool useCompoundFile = getUseCompoundFile();
if (useCompoundFile) {
_files.push_back( string(name) + "." + IndexFileNames::COMPOUND_FILE_EXTENSION);
} else {
ConstValueArray<const char*>& exts = IndexFileNames::NON_STORE_INDEX_EXTENSIONS();
for(size_t i=0;i<exts.length;i++){
addIfExists(_files, name + "." + exts[i]);
}
}
if (docStoreOffset != -1) {
// We are sharing doc stores (stored fields, term
// vectors) with other segments
assert (!docStoreSegment.empty());
if (docStoreIsCompoundFile) {
_files.push_back(docStoreSegment + "." + IndexFileNames::COMPOUND_FILE_STORE_EXTENSION);
} else {
ConstValueArray<const char*>& exts = IndexFileNames::STORE_INDEX_EXTENSIONS();
for(size_t i=0;i<exts.length;i++)
addIfExists(_files, docStoreSegment + "." + exts[i]);
}
} else if (!useCompoundFile) {
// We are not sharing, and, these files were not
// included in the compound file
ConstValueArray<const char*>& exts = IndexFileNames::STORE_INDEX_EXTENSIONS();
for(size_t i=0;i<exts.length;i++)
addIfExists(_files, name + "." + exts[i]);
}
string delFileName = IndexFileNames::fileNameFromGeneration(name.c_str(), (string(".") + IndexFileNames::DELETES_EXTENSION).c_str(), delGen);
if ( !delFileName.empty() && (delGen >= YES || dir->fileExists(delFileName.c_str()))) {
_files.push_back(delFileName);
}
// Careful logic for norms files
if (normGen.values != NULL) {
for(size_t i=0;i<normGen.length;i++) {
int64_t gen = normGen[i];
if (gen >= YES) {
// Definitely a separate norm file, with generation:
string gens = string(".") + IndexFileNames::SEPARATE_NORMS_EXTENSION;
gens += Misc::toString((int64_t)i);
_files.push_back(IndexFileNames::fileNameFromGeneration(name.c_str(), gens.c_str(), gen));
} else if (NO == gen) {
// No separate norms but maybe plain norms
// in the non compound file case:
if (!hasSingleNormFile && !useCompoundFile) {
string fileName = name + "." + IndexFileNames::PLAIN_NORMS_EXTENSION;
fileName += i;
if (dir->fileExists(fileName.c_str())) {
_files.push_back(fileName);
}
}
} else if (CHECK_DIR == gen) {
// Pre-2.1: we have to check file existence
string fileName;
if (useCompoundFile) {
fileName = name + "." + IndexFileNames::SEPARATE_NORMS_EXTENSION;
fileName += Misc::toString((int64_t)i);
} else if (!hasSingleNormFile) {
fileName = name + "." + IndexFileNames::PLAIN_NORMS_EXTENSION;
fileName += Misc::toString((int64_t)i);
}
if ( !fileName.empty() && dir->fileExists(fileName.c_str())) {
_files.push_back(fileName);
}
}
}
} else if (preLockless || (!hasSingleNormFile && !useCompoundFile)) {
// Pre-2.1: we have to scan the dir to find all
// matching _X.sN/_X.fN files for our segment:
string prefix;
if (useCompoundFile)
prefix = name + "." + IndexFileNames::SEPARATE_NORMS_EXTENSION;
else
prefix = name + "." + IndexFileNames::PLAIN_NORMS_EXTENSION;
size_t prefixLength = prefix.length();
vector<string> allFiles;
if (dir->list(allFiles) == false ){
string err = "cannot read directory ";
err += dir->toString();
err += ": list() returned null";
_CLTHROWA(CL_ERR_IO, err.c_str());
}
for(size_t i=0;i<allFiles.size();i++) {
string& fileName = allFiles[i];
if (fileName.length() > prefixLength && _istdigit(fileName[prefixLength]) && fileName.compare(0,prefix.length(),prefix)==0 ) {
_files.push_back(fileName);
}
}
}
return _files;
}
bool SegmentInfo::hasDeletions() const {
// Cases:
//
// delGen == NO: this means this segment was written
// by the LOCKLESS code and for certain does not have
// deletions yet
//
// delGen == CHECK_DIR: this means this segment was written by
// pre-LOCKLESS code which means we must check
// directory to see if .del file exists
//
// delGen >= YES: this means this segment was written by
// the LOCKLESS code and for certain has
// deletions
//
if (delGen == NO) {
return false;
} else if (delGen >= YES) {
return true;
} else {
return dir->fileExists(getDelFileName().c_str());
}
}
void SegmentInfo::advanceDelGen() {
// delGen 0 is reserved for pre-LOCKLESS format
if (delGen == NO) {
delGen = YES;
} else {
delGen++;
}
clearFiles();
}
void SegmentInfo::clearDelGen() {
delGen = NO;
clearFiles();
}
SegmentInfo* SegmentInfo::clone () {
SegmentInfo* si = _CLNEW SegmentInfo(name.c_str(), docCount, dir);
si->isCompoundFile = isCompoundFile;
si->delGen = delGen;
si->preLockless = preLockless;
si->hasSingleNormFile = hasSingleNormFile;
if (this->normGen.values != NULL) {
si->normGen.resize(this->normGen.length);
memcpy(si->normGen.values, this->normGen.values, sizeof(int64_t) * this->normGen.length);
}
si->docStoreOffset = docStoreOffset;
si->docStoreSegment = docStoreSegment;
si->docStoreIsCompoundFile = docStoreIsCompoundFile;
return si;
}
string SegmentInfo::getDelFileName() const {
if (delGen == NO) {
// In this case we know there is no deletion filename
// against this segment
return NULL;
} else {
// If delGen is CHECK_DIR, it's the pre-lockless-commit file format
return IndexFileNames::fileNameFromGeneration(name.c_str(), (string(".") + IndexFileNames::DELETES_EXTENSION).c_str(), delGen);
}
}
bool SegmentInfo::hasSeparateNorms(const int32_t fieldNumber) const {
if ((normGen.values == NULL && preLockless) || (normGen.values != NULL && normGen[fieldNumber] == CHECK_DIR)) {
// Must fallback to directory file exists check:
return dir->fileExists( (name + string(".s") + Misc::toString(fieldNumber)).c_str() );
} else if (normGen.values == NULL || normGen[fieldNumber] == NO) {
return false;
} else {
return true;
}
}
bool SegmentInfo::hasSeparateNorms() const {
if (normGen.values == NULL) {
if (!preLockless) {
// This means we were created w/ LOCKLESS code and no
// norms are written yet:
return false;
} else {
// This means this segment was saved with pre-LOCKLESS
// code. So we must fallback to the original
// directory list check:
vector<string> result;
if ( !dir->list(result) ) {
_CLTHROWA(CL_ERR_IO, (string("cannot read directory: ") + dir->toString() + string(" list() returned NULL")).c_str() );
}
string pattern = name + string(".s");
for ( vector<string>::iterator itr = result.begin();
itr != result.end() ; itr ++ ){
if(strncmp(itr->c_str(), pattern.c_str(), pattern.length() ) == 0 &&
isdigit( (*itr)[pattern.length()])) {
return true;
}
}
return false;
}
} else {
// This means this segment was saved with LOCKLESS
// code so we first check whether any normGen's are >= 1
// (meaning they definitely have separate norms):
for(size_t i=0;i<normGen.length;i++) {
if (normGen[i] >= YES) {
return true;
}
}
// Next we look for any == 0. These cases were
// pre-LOCKLESS and must be checked in directory:
for(size_t j=0;j<normGen.length;j++) {
if (normGen[j] == CHECK_DIR) {
if (hasSeparateNorms(j)) {
return true;
}
}
}
}
return false;
}
void SegmentInfo::advanceNormGen(const int32_t fieldIndex) {
if (normGen[fieldIndex] == NO) {
normGen.values[fieldIndex] = YES;
} else {
normGen.values[fieldIndex]++;
}
clearFiles();
}
string SegmentInfo::getNormFileName(const int32_t number) const {
char prefix[10];
int64_t gen;
if (normGen.values == NULL) {
gen = CHECK_DIR;
} else {
gen = normGen[number];
}
if (hasSeparateNorms(number)) {
// case 1: separate norm
cl_sprintf(prefix, 10, ".s%d", number);
return IndexFileNames::fileNameFromGeneration(name.c_str(), prefix, gen);
}
if (hasSingleNormFile) {
// case 2: lockless (or nrm file exists) - single file for all norms
cl_sprintf(prefix, 10, ".%s", IndexFileNames::NORMS_EXTENSION);
return IndexFileNames::fileNameFromGeneration(name.c_str(), prefix, WITHOUT_GEN);
}
// case 3: norm file for each field
cl_sprintf(prefix, 10, ".f%d", number);
return IndexFileNames::fileNameFromGeneration(name.c_str(), prefix, WITHOUT_GEN);
}
void SegmentInfo::setUseCompoundFile(const bool isCompoundFile) {
if (isCompoundFile) {
this->isCompoundFile = YES;
} else {
this->isCompoundFile = NO;
}
clearFiles();
}
bool SegmentInfo::getUseCompoundFile() const {
if (isCompoundFile == NO) {
return false;
} else if (isCompoundFile == YES) {
return true;
} else {
return dir->fileExists( ((string)name + "." + IndexFileNames::COMPOUND_FILE_EXTENSION).c_str() );
}
}
int32_t SegmentInfo::getDocStoreOffset() const { return docStoreOffset; }
bool SegmentInfo::getDocStoreIsCompoundFile() const { return docStoreIsCompoundFile; }
void SegmentInfo::setDocStoreIsCompoundFile(const bool v) {
docStoreIsCompoundFile = v;
clearFiles();
}
const string& SegmentInfo::getDocStoreSegment() const {
return docStoreSegment;
}
void SegmentInfo::setDocStoreOffset(const int32_t offset) {
docStoreOffset = offset;
clearFiles();
}
void SegmentInfo::write(CL_NS(store)::IndexOutput* output) {
output->writeString(name);
output->writeInt(docCount);
output->writeLong(delGen);
output->writeInt(docStoreOffset);
if (docStoreOffset != -1) {
output->writeString(docStoreSegment);
output->writeByte(static_cast<uint8_t>(docStoreIsCompoundFile ? 1:0));
}
output->writeByte(static_cast<uint8_t>(hasSingleNormFile ? 1:0));
if (normGen.values == NULL) {
output->writeInt(NO);
} else {
output->writeInt(normGen.length);
for(size_t j = 0; j < normGen.length; j++) {
output->writeLong(normGen[j]);
}
}
output->writeByte(isCompoundFile);
}
void SegmentInfo::clearFiles() {
_files.clear();
_sizeInBytes = -1;
}
/** We consider another SegmentInfo instance equal if it
* has the same dir and same name. */
bool SegmentInfo::equals(const SegmentInfo* obj) {
return (obj->dir == this->dir && obj->name.compare(this->name) == 0 );
}
std::ostream* SegmentInfos::infoStream = NULL;
/** If non-null, information about retries when loading
* the segments file will be printed to this.
*/
void SegmentInfos::setInfoStream(std::ostream* infoStream) {
SegmentInfos::infoStream = infoStream;
}
/**
* @see #setInfoStream
*/
std::ostream* SegmentInfos::getInfoStream() {
return infoStream;
}
SegmentInfos::SegmentInfos(bool deleteMembers, int32_t reserveCount) :
generation(0),lastGeneration(0), infos(deleteMembers) {
//Func - Constructor
//Pre - deleteMembers indicates if the instance to be created must delete
// all SegmentInfo instances it manages when the instance is destroyed or not
// true -> must delete, false may not delete
//Post - An instance of SegmentInfos has been created.
//initialize counter to 0
counter = 0;
version = Misc::currentTimeMillis();
if (reserveCount > 1)
infos.reserve(reserveCount);
}
SegmentInfos::~SegmentInfos(){
//Func - Destructor
//Pre - true
//Post - The instance has been destroyed. Depending on the constructor used
// the SegmentInfo instances that this instance managed have been deleted or not.
//Clear the list of SegmentInfo instances - make sure everything is deleted
infos.clear();
}
SegmentInfo* SegmentInfos::info(int32_t i) const {
//Func - Returns a reference to the i-th SegmentInfo in the list.
//Pre - i >= 0
//Post - A reference to the i-th SegmentInfo instance has been returned
CND_PRECONDITION(i >= 0 && i < infos.size(), "i is out of bounds");
//Get the i-th SegmentInfo instance
SegmentInfo *ret = infos[i];
//Condition check to see if the i-th SegmentInfo has been retrieved
CND_CONDITION(ret != NULL,"No SegmentInfo instance found");
return ret;
}
int64_t SegmentInfos::getCurrentSegmentGeneration( std::vector<std::string>& files ) {
if ( files.size() == 0 ) {
return -1;
}
int64_t max = -1;
vector<string>::iterator itr = files.begin();
const char* file;
size_t seglen = strlen(IndexFileNames::SEGMENTS);
while ( itr != files.end() ) {
file = itr->c_str();
if ( strncmp( file, IndexFileNames::SEGMENTS, seglen ) == 0 && strcmp( file, IndexFileNames::SEGMENTS_GEN ) != 0 ) {
int64_t gen = generationFromSegmentsFileName( file );
if ( gen > max ) {
max = gen;
}
}
itr++;
}
return max;
}
int64_t SegmentInfos::getCurrentSegmentGeneration( const CL_NS(store)::Directory* directory ) {
vector<string> files;
if ( !directory->list(&files) ){
_CLTHROWA(CL_ERR_IO, (string("cannot read directory ") + directory->toString() + string(": list() returned NULL")).c_str() );
}
int64_t gen = getCurrentSegmentGeneration( files );
return gen;
}
string SegmentInfos::getCurrentSegmentFileName( vector<string>& files ) {
return IndexFileNames::fileNameFromGeneration( IndexFileNames::SEGMENTS, "", getCurrentSegmentGeneration( files ));
}
std::string SegmentInfos::getCurrentSegmentFileName( CL_NS(store)::Directory* directory ) {
return IndexFileNames::fileNameFromGeneration( IndexFileNames::SEGMENTS, "", getCurrentSegmentGeneration( directory ));
}
std::string SegmentInfos::getCurrentSegmentFileName() {
return IndexFileNames::fileNameFromGeneration( IndexFileNames::SEGMENTS, "", lastGeneration );
}
int64_t SegmentInfos::generationFromSegmentsFileName( const char* fileName ) {
if ( strcmp( fileName, IndexFileNames::SEGMENTS ) == 0 ) {
return 0;
} else if ( strncmp( fileName, IndexFileNames::SEGMENTS, strlen(IndexFileNames::SEGMENTS) ) == 0 ) {
return CL_NS(util)::Misc::base36ToLong( fileName + strlen( IndexFileNames::SEGMENTS )+1 );
} else {
TCHAR err[CL_MAX_PATH + 35];
_sntprintf(err,CL_MAX_PATH + 35,_T("fileName \"%s\" is not a segments file"), fileName);
_CLTHROWA(CL_ERR_IllegalArgument, err);
return 0;
}
}
std::string SegmentInfos::getNextSegmentFileName() {
int64_t nextGeneration = 0;
if ( generation == -1 ) {
nextGeneration = 1;
} else {
nextGeneration = generation+1;
}
std::string retVal = IndexFileNames::fileNameFromGeneration( IndexFileNames::SEGMENTS, "", nextGeneration );
return retVal;
}
void SegmentInfos::clearto(size_t from, size_t end){
size_t range = end - from;
if ( (infos.size() - from) >= range) { // Make sure we actually need to remove
segmentInfosType::iterator itr,bitr=infos.begin()+from,eitr=infos.end();
size_t count = 0;
for(itr=bitr;itr!=eitr && count < range;++itr, count++) {
_CLLDELETE((*itr));
}
infos.erase(bitr,bitr + count);
}
}
void SegmentInfos::add(SegmentInfo* info, int32_t pos){
if ( pos == -1 ){
infos.push_back(info);
}else{
if ( pos < 0 || pos >= (int32_t)infos.size()+1 ) _CLTHROWA(CL_ERR_IllegalArgument, "pos is out of range");
infos.insert( infos.begin()+pos, info );
}
}
int32_t SegmentInfos::size() const{
return infos.size();
}
SegmentInfo* SegmentInfos::elementAt(int32_t pos) {
return infos.at(pos);
}
void SegmentInfos::setElementAt(SegmentInfo* si, int32_t pos) {
infos.set(pos, si);
}
void SegmentInfos::clear() { infos.clear(); }
void SegmentInfos::insert(SegmentInfos* _infos, bool takeMemory){
infos.insert(infos.end(),_infos->infos.begin(),_infos->infos.end());
if ( takeMemory ){
while (_infos->infos.size() > 0 )
_infos->infos.remove(_infos->infos.begin(), true );
}
}
void SegmentInfos::insert(SegmentInfo* info){
infos.push_back(info);
}
int32_t SegmentInfos::indexOf(const SegmentInfo* info) const{
segmentInfosType::const_iterator itr = infos.begin();
int32_t c=-1;
while ( itr != infos.end()){
c++;
if ( *itr == info ){
return c;
}
itr++;
}
return -1;
}
void SegmentInfos::range(size_t from, size_t to, SegmentInfos& ret) const{
segmentInfosType::const_iterator itr = infos.begin();
itr+= from;
for (size_t i=from;i<to && itr != infos.end();i++){
ret.infos.push_back(*itr);
itr++;
}
}
void SegmentInfos::remove(size_t index, bool dontDelete){
infos.remove(index, dontDelete);
}
void SegmentInfos::read(Directory* directory, const char* segmentFileName){
bool success = false;
// Clear any previous segments:
clear();
IndexInput* input = directory->openInput(segmentFileName);
CND_CONDITION(input != NULL,"input == NULL");
generation = generationFromSegmentsFileName( segmentFileName );
lastGeneration = generation;
try {
int32_t format = input->readInt();
if(format < 0){ // file contains explicit format info
// check that it is a format we can understand
if (format < CURRENT_FORMAT){
char err[30];
cl_sprintf(err,30,"Unknown format version: %d", format);
_CLTHROWA(CL_ERR_CorruptIndex, err);
}
version = input->readLong(); // read version
counter = input->readInt(); // read counter
}
else{ // file is in old format without explicit format info
counter = format;
}
for (int32_t i = input->readInt(); i > 0; i--) { // read segmentInfos
infos.push_back( _CLNEW SegmentInfo(directory, format, input) );
}
if(format >= 0){ // in old format the version number may be at the end of the file
if (input->getFilePointer() >= input->length())
version = CL_NS(util)::Misc::currentTimeMillis(); // old file format without version number
else
version = input->readLong(); // read version
}
success = true;
} _CLFINALLY({
input->close();
_CLDELETE(input);
if (!success) {
// Clear any segment infos we had loaded so we
// have a clean slate on retry:
clear();
}
});
}
void SegmentInfos::read(Directory* directory) {
generation = lastGeneration = -1;
FindSegmentsRead find(directory, this);
find.run();
}
void SegmentInfos::write(Directory* directory){
//Func - Writes a new segments file based upon the SegmentInfo instances it manages
//Pre - directory is a valid reference to a Directory
//Post - The new segment has been written to disk
string segmentFileName = getNextSegmentFileName();
// Always advance the generation on write:
if (generation == -1) {
generation = 1;
} else {
generation++;
}
IndexOutput* output = directory->createOutput(segmentFileName.c_str());
bool success = false;
try {
output->writeInt(CURRENT_FORMAT); // write FORMAT
output->writeLong(++version); // every write changes
// the index
output->writeInt(counter); // write counter
output->writeInt(size()); // write infos
for (int32_t i = 0; i < size(); i++) {
info(i)->write(output);
}
}_CLFINALLY (
try {
output->close();
_CLDELETE(output);
success = true;
} _CLFINALLY (
if (!success) {
// Try not to leave a truncated segments_N file in
// the index:
directory->deleteFile(segmentFileName.c_str());
}
)
)
try {
output = directory->createOutput(IndexFileNames::SEGMENTS_GEN);
try {
output->writeInt(FORMAT_LOCKLESS);
output->writeLong(generation);
output->writeLong(generation);
} _CLFINALLY(
output->close();
_CLDELETE(output);
)
} catch (CLuceneError& e) {
if ( e.number() != CL_ERR_IO ) throw e;
// It's OK if we fail to write this file since it's
// used only as one of the retry fallbacks.
}
lastGeneration = generation;
}
SegmentInfos* SegmentInfos::clone() const{
SegmentInfos* sis = _CLNEW SegmentInfos(true, infos.size());
for(size_t i=0;i<infos.size();i++) {
sis->setElementAt(infos[i]->clone(), i);
}
return sis;
}
int64_t SegmentInfos::getVersion() const { return version; }
int64_t SegmentInfos::getGeneration() const { return generation; }
int64_t SegmentInfos::getLastGeneration() const { return lastGeneration; }
int64_t SegmentInfos::readCurrentVersion(Directory* directory){
FindSegmentsVersion find(directory);
return find.run();
}
//void SegmentInfos::setDefaultGenFileRetryCount(const int32_t count) { defaultGenFileRetryCount = count; }
int32_t SegmentInfos::getDefaultGenFileRetryCount() { return defaultGenFileRetryCount; }
//void SegmentInfos::setDefaultGenFileRetryPauseMsec(const int32_t msec) { defaultGenFileRetryPauseMsec = msec; }
int32_t SegmentInfos::getDefaultGenFileRetryPauseMsec() { return defaultGenFileRetryPauseMsec; }
//void SegmentInfos::setDefaultGenLookaheadCount(const int32_t count) { defaultGenLookaheadCount = count;}
int32_t SegmentInfos::getDefaultGenLookahedCount() { return defaultGenLookaheadCount; }
void SegmentInfos::_FindSegmentsFile::doRun(){
string segmentFileName;
int64_t lastGen = -1;
int64_t gen = 0;
int32_t genLookaheadCount = 0;
bool retry = false;
CLuceneError exc; //saved exception
int32_t method = 0;
// Loop until we succeed in calling doBody() without
// hitting an IOException. An IOException most likely
// means a commit was in process and has finished, in
// the time it took us to load the now-old infos files
// (and segments files). It's also possible it's a
// true error (corrupt index). To distinguish these,
// on each retry we must see "forward progress" on
// which generation we are trying to load. If we
// don't, then the original error is real and we throw
// it.
// We have three methods for determining the current
// generation. We try the first two in parallel, and
// fall back to the third when necessary.
while( true ) {
if ( 0 == method ) {
// Method 1: list the directory and use the highest
// segments_N file. This method works well as long
// as there is no stale caching on the directory
// contents (NOTE: NFS clients often have such stale
// caching):
vector<string> files;
int64_t genA = -1;
if (directory != NULL){
if (directory->list(&files)) {
genA = getCurrentSegmentGeneration( files );
files.clear();
}
}
if ( infoStream ){
(*infoStream) << "[SIS]: directory listing genA=" << genA << "\n";
}
// Method 2: open segments.gen and read its
// contents. Then we take the larger of the two
// gen's. This way, if either approach is hitting
// a stale cache (NFS) we have a better chance of
// getting the right generation.
int64_t genB = -1;
if (directory != NULL) {
CLuceneError e;
for(int32_t i=0;i<defaultGenFileRetryCount;i++) {
IndexInput* genInput = NULL;
if ( ! directory->openInput(IndexFileNames::SEGMENTS_GEN, genInput, e) ){
if (e.number() == CL_ERR_IO ) {
if ( infoStream ){
(*infoStream) << "[SIS]: segments.gen open: IOException " << e.what() << "\n";
}
break;
} else {
genInput->close();
_CLLDELETE(genInput);
throw e;
}
}
if (genInput != NULL) {
try {
int32_t version = genInput->readInt();
if (version == FORMAT_LOCKLESS) {
int64_t gen0 = genInput->readLong();
int64_t gen1 = genInput->readLong();
//CL_TRACE("fallback check: %d; %d", gen0, gen1);
if (gen0 == gen1) {
// The file is consistent.
genB = gen0;
genInput->close();
_CLDELETE(genInput);
break;
}
}
} catch (CLuceneError &err2) {
if (err2.number() != CL_ERR_IO) {
genInput->close();
_CLLDELETE(genInput);
throw err2; // retry only for IOException
}
} _CLFINALLY({
genInput->close();
_CLDELETE(genInput);
});
}
_LUCENE_SLEEP(defaultGenFileRetryPauseMsec);
/*
//todo: Wrap the LUCENE_SLEEP call above with the following try/catch block if
// InterruptedException is implemented
try {
} catch (CLuceneError &e) {
//if (err2.number != CL_ERR_Interrupted) // retry only for InterruptedException
// todo: see if CL_ERR_Interrupted needs to be added...
throw e;
}*/
}
}
//CL_TRACE("%s check: genB=%d", IndexFileNames::SEGMENTS_GEN, genB);
// Pick the larger of the two gen's:
if (genA > genB)
gen = genA;
else
gen = genB;
if (gen == -1) {
// Neither approach found a generation
_CLTHROWA(CL_ERR_IO, (string("No segments* file found in ") + directory->toString()).c_str());
}
}
// Third method (fallback if first & second methods
// are not reliable): since both directory cache and
// file contents cache seem to be stale, just
// advance the generation.
if ( 1 == method || ( 0 == method && lastGen == gen && retry )) {
method = 1;
if (genLookaheadCount < defaultGenLookaheadCount) {
gen++;
genLookaheadCount++;
//CL_TRACE("look ahead increment gen to %d", gen);
}
}
if (lastGen == gen) {
// This means we're about to try the same
// segments_N last tried. This is allowed,
// exactly once, because writer could have been in
// the process of writing segments_N last time.
if (retry) {
// OK, we've tried the same segments_N file
// twice in a row, so this must be a real
// error. We throw the original exception we
// got.
throw exc;
} else {
retry = true;
}
} else {
// Segment file has advanced since our last loop, so
// reset retry:
retry = false;
}
lastGen = gen;
segmentFileName = IndexFileNames::fileNameFromGeneration(IndexFileNames::SEGMENTS, "", gen);
CLuceneError saved_error;
if ( tryDoBody(segmentFileName.c_str(), saved_error) ){
return;
}
// Save the original root cause:
if (exc.number() == 0) {
CND_CONDITION( saved_error.number() > 0, "Unsupported error code");
exc.set(saved_error.number(),saved_error.what());
}
//CL_TRACE("primary Exception on '" + segmentFileName + "': " + err + "'; will retry: retry=" + retry + "; gen = " + gen);
if (!retry && gen > 1) {
// This is our first time trying this segments
// file (because retry is false), and, there is
// possibly a segments_(N-1) (because gen > 1).
// So, check if the segments_(N-1) exists and
// try it if so:
string prevSegmentFileName = IndexFileNames::fileNameFromGeneration( IndexFileNames::SEGMENTS, "", gen-1 );
bool prevExists=false;
if (directory != NULL)
prevExists = directory->fileExists(prevSegmentFileName.c_str());
else
prevExists = Misc::dir_Exists( (string(fileDirectory) + prevSegmentFileName).c_str() );
if (prevExists) {
//CL_TRACE("fallback to prior segment file '%s'", prevSegmentFileName);
CLuceneError saved_error;
if ( tryDoBody(prevSegmentFileName.c_str(), saved_error) ){
return;
}
//CL_TRACE("secondary Exception on '" + prevSegmentFileName + "': " + err2 + "'; will retry");
}
}
}
}
SegmentInfos::FindSegmentsRead::FindSegmentsRead( CL_NS(store)::Directory* dir, SegmentInfos* _this ) :
SegmentInfos::FindSegmentsFile<bool>(dir) {
this->_this = _this;
}
bool SegmentInfos::FindSegmentsRead::doBody( const char* segmentFileName ) {
//Have SegmentInfos read the segments file in directory
_this->read(directory, segmentFileName);
return true;
}
SegmentInfos::FindSegmentsVersion::FindSegmentsVersion( CL_NS(store)::Directory* dir ) :
SegmentInfos::FindSegmentsFile<int64_t>(dir) {
}
int64_t SegmentInfos::FindSegmentsVersion::doBody( const char* segmentFileName ) {
IndexInput* input = directory->openInput( segmentFileName );
int32_t format = 0;
int64_t version=0;
try {
format = input->readInt();
if(format < 0){
if(format < CURRENT_FORMAT){
char err[30];
cl_sprintf(err,30,"Unknown format version: %d",format);
_CLTHROWA(CL_ERR_CorruptIndex,err);
}
version = input->readLong(); // read version
}
}
_CLFINALLY( input->close(); _CLDELETE(input); );
if(format < 0)
return version;
// We cannot be sure about the format of the file.
// Therefore we have to read the whole file and cannot simply seek to the version entry.
SegmentInfos* sis = _CLNEW SegmentInfos();
sis->read(directory, segmentFileName);
version = sis->getVersion();
_CLDELETE(sis);
return version;
}
CL_NS_END
| 32.606383 | 145 | 0.615334 | asheeshv |
6647e8e1a937c948e484c3ace1332e62285bd87c | 6,862 | cpp | C++ | Implementation/Core/amc_statejournalstream.cpp | GibbekAdsk/AutodeskMachineControlFramework | 48c220c1acfbc2c4c33f636354e9372100f7c896 | [
"BSD-3-Clause"
] | null | null | null | Implementation/Core/amc_statejournalstream.cpp | GibbekAdsk/AutodeskMachineControlFramework | 48c220c1acfbc2c4c33f636354e9372100f7c896 | [
"BSD-3-Clause"
] | null | null | null | Implementation/Core/amc_statejournalstream.cpp | GibbekAdsk/AutodeskMachineControlFramework | 48c220c1acfbc2c4c33f636354e9372100f7c896 | [
"BSD-3-Clause"
] | null | null | null | /*++
Copyright (C) 2020 Autodesk Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Autodesk Inc. 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 AUTODESK INC. 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 "amc_statejournalstream.hpp"
#include "common_utils.hpp"
#include "common_chrono.hpp"
#include "libmc_interfaceexception.hpp"
#include <iostream>
namespace AMC {
class CStateJournalStreamChunk
{
private:
std::vector<uint64_t> m_TimeStamps;
std::vector<uint8_t> m_Data;
std::map<uint32_t, std::string> m_NameDefinitions;
void writeData(const uint8_t* pData, uint32_t nLength)
{
if (pData == nullptr)
throw ELibMCInterfaceException(LIBMC_ERROR_INVALIDPARAM);
const uint8_t* pSrc = pData;
for (uint32_t nIndex = 0; nIndex < nLength; nIndex++) {
m_Data.push_back(*pSrc);
pSrc++;
}
}
public:
CStateJournalStreamChunk(uint64_t nStartTimeStamp)
{
m_TimeStamps.push_back(nStartTimeStamp);
}
void writeCommand(const uint32_t nCommand)
{
writeData((const uint8_t*)&nCommand, 4);
}
void writeUint64(const uint64_t nValue)
{
writeData((const uint8_t*)&nValue, 8);
}
void writeString(const std::string& sValue)
{
uint32_t nLength = (uint32_t)sValue.length();
writeData((const uint8_t*)&nLength, 4);
writeData((const uint8_t*) sValue.c_str (), nLength);
}
void writeDouble(const double dValue)
{
writeData((const uint8_t*)&dValue, 8);
}
void storeTimeStamp (const uint64_t nTimeStamp)
{
auto iLast = m_TimeStamps.rbegin();
if (iLast == m_TimeStamps.rend())
throw ELibMCInterfaceException(LIBMC_ERROR_INTERNALERROR);
auto nLastTimeStamp = *iLast;
if (nTimeStamp < nLastTimeStamp)
throw ELibMCInterfaceException(LIBMC_ERROR_INVALIDTIMESTAMP);
if (nTimeStamp > nLastTimeStamp) {
m_TimeStamps.push_back(nTimeStamp);
}
}
void writeNameDefinition (const uint32_t nID, const std::string& sName)
{
auto iIter = m_NameDefinitions.find(nID);
if (iIter != m_NameDefinitions.end())
throw ELibMCInterfaceException(LIBMC_ERROR_DUPLICATEJOURNALID);
m_NameDefinitions.insert(std::make_pair (nID, sName));
writeCommand(nID | STATEJOURNAL_COMMANDFLAG_DEFINITION);
writeString(sName);
}
};
CStateJournalStream::CStateJournalStream()
: m_nCurrentTimeStamp (0)
{
}
CStateJournalStream::~CStateJournalStream()
{
}
void CStateJournalStream::writeString(const uint32_t nID, const std::string& sValue)
{
if (m_pCurrentChunk == nullptr)
throw ELibMCInterfaceException(LIBMC_ERROR_NOCURRENTJOURNALCHUNK);
m_pCurrentChunk->writeCommand(nID | STATEJOURNAL_COMMANDFLAG_STRING);
m_pCurrentChunk->writeString(sValue);
}
void CStateJournalStream::startNewChunk()
{
m_pCurrentChunk = std::make_shared <CStateJournalStreamChunk>(m_nCurrentTimeStamp);
m_Chunks.push_back(m_pCurrentChunk);
}
void CStateJournalStream::writeTimeStamp(const uint64_t nAbsoluteTimeStamp)
{
if (nAbsoluteTimeStamp < m_nCurrentTimeStamp)
throw ELibMCInterfaceException(LIBMC_ERROR_INVALIDTIMESTAMP);
uint64_t nDeltaTime = nAbsoluteTimeStamp - m_nCurrentTimeStamp;
if (nDeltaTime >= STATEJOURNAL_MAXTIMESTAMPDELTA)
throw ELibMCInterfaceException(LIBMC_ERROR_INVALIDTIMESTAMP);
m_pCurrentChunk->writeCommand(((uint32_t) nDeltaTime) | STATEJOURNAL_COMMANDFLAG_TIMESTAMP);
m_pCurrentChunk->storeTimeStamp(nAbsoluteTimeStamp);
m_nCurrentTimeStamp = nAbsoluteTimeStamp;
}
void CStateJournalStream::writeBool(const uint32_t nID, bool bValue)
{
if (m_pCurrentChunk == nullptr)
throw ELibMCInterfaceException(LIBMC_ERROR_NOCURRENTJOURNALCHUNK);
if (bValue) {
m_pCurrentChunk->writeCommand(nID | STATEJOURNAL_COMMANDFLAG_BOOL | STATEJOURNAL_COMMANDFLAG_BOOL_TRUE);
}
else {
m_pCurrentChunk->writeCommand(nID | STATEJOURNAL_COMMANDFLAG_BOOL | STATEJOURNAL_COMMANDFLAG_BOOL_FALSE);
}
}
void CStateJournalStream::writeInt64Delta(const uint32_t nID, int64_t nDelta)
{
if (m_pCurrentChunk == nullptr)
throw ELibMCInterfaceException(LIBMC_ERROR_NOCURRENTJOURNALCHUNK);
if (nDelta > 0) {
m_pCurrentChunk->writeCommand(nID | STATEJOURNAL_COMMANDFLAG_INTEGER | STATEJOURNAL_COMMANDFLAG_INTEGER_POSITIVE);
m_pCurrentChunk->writeUint64((uint64_t) nDelta);
}
else {
m_pCurrentChunk->writeCommand(nID | STATEJOURNAL_COMMANDFLAG_INTEGER | STATEJOURNAL_COMMANDFLAG_INTEGER_NEGATIVE);
m_pCurrentChunk->writeUint64((uint64_t)(- nDelta));
}
}
void CStateJournalStream::writeDoubleDelta(const uint32_t nID, int64_t nDelta)
{
if (m_pCurrentChunk == nullptr)
throw ELibMCInterfaceException(LIBMC_ERROR_NOCURRENTJOURNALCHUNK);
if (nDelta > 0) {
m_pCurrentChunk->writeCommand(nID | STATEJOURNAL_COMMANDFLAG_DOUBLE | STATEJOURNAL_COMMANDFLAG_DOUBLE_POSITIVE);
m_pCurrentChunk->writeUint64((uint64_t)nDelta);
}
else {
m_pCurrentChunk->writeCommand(nID | STATEJOURNAL_COMMANDFLAG_DOUBLE | STATEJOURNAL_COMMANDFLAG_DOUBLE_NEGATIVE);
m_pCurrentChunk->writeUint64((uint64_t)(-nDelta));
}
}
void CStateJournalStream::writeNameDefinition(const uint32_t nID, const std::string& sName)
{
if (m_pCurrentChunk == nullptr)
throw ELibMCInterfaceException(LIBMC_ERROR_NOCURRENTJOURNALCHUNK);
m_pCurrentChunk->writeNameDefinition(nID, sName);
}
void CStateJournalStream::writeUnits(const uint32_t nID, double dUnits)
{
if (m_pCurrentChunk == nullptr)
throw ELibMCInterfaceException(LIBMC_ERROR_NOCURRENTJOURNALCHUNK);
m_pCurrentChunk->writeCommand(nID | STATEJOURNAL_COMMANDFLAG_UNITS);
m_pCurrentChunk->writeDouble(dUnits);
}
}
| 28.473029 | 117 | 0.773244 | GibbekAdsk |
66486ff130fd25c45a38a5513c1e7578f742e6cb | 39,531 | hpp | C++ | external/libc++/unordered_set.hpp | greck2908/LudOS | db38455eb33dfc0dfc6d4be102e6bd54d852eee8 | [
"MIT"
] | 44 | 2018-01-28T20:07:48.000Z | 2022-02-11T22:58:49.000Z | external/libc++/unordered_set.hpp | greck2908/LudOS | db38455eb33dfc0dfc6d4be102e6bd54d852eee8 | [
"MIT"
] | 2 | 2017-09-12T15:38:16.000Z | 2017-11-05T12:19:01.000Z | external/libc++/unordered_set.hpp | greck2908/LudOS | db38455eb33dfc0dfc6d4be102e6bd54d852eee8 | [
"MIT"
] | 8 | 2018-08-17T13:30:57.000Z | 2021-06-25T16:56:12.000Z | // -*- C++ -*-
//===-------------------------- unordered_set -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_UNORDERED_SET
#define _LIBCPP_UNORDERED_SET
#include <__config.hpp>
#include <__hash_table.hpp>
#include <functional.hpp>
#include <__debug.hpp>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
template <class _Value, class _Hash = hash<_Value>, class _Pred = equal_to<_Value>,
class _Alloc = allocator<_Value> >
class _LIBCPP_TEMPLATE_VIS unordered_set
{
public:
// types
typedef _Value key_type;
typedef key_type value_type;
typedef _Hash hasher;
typedef _Pred key_equal;
typedef _Alloc allocator_type;
typedef value_type& reference;
typedef const value_type& const_reference;
static_assert((is_same<value_type, typename allocator_type::value_type>::value),
"Invalid allocator::value_type");
private:
typedef __hash_table<value_type, hasher, key_equal, allocator_type> __table;
__table __table_;
public:
typedef typename __table::pointer pointer;
typedef typename __table::const_pointer const_pointer;
typedef typename __table::size_type size_type;
typedef typename __table::difference_type difference_type;
typedef typename __table::const_iterator iterator;
typedef typename __table::const_iterator const_iterator;
typedef typename __table::const_local_iterator local_iterator;
typedef typename __table::const_local_iterator const_local_iterator;
_LIBCPP_INLINE_VISIBILITY
unordered_set()
_NOEXCEPT_(is_nothrow_default_constructible<__table>::value)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
explicit unordered_set(size_type __n, const hasher& __hf = hasher(),
const key_equal& __eql = key_equal());
#if _LIBCPP_STD_VER > 11
inline _LIBCPP_INLINE_VISIBILITY
unordered_set(size_type __n, const allocator_type& __a)
: unordered_set(__n, hasher(), key_equal(), __a) {}
inline _LIBCPP_INLINE_VISIBILITY
unordered_set(size_type __n, const hasher& __hf, const allocator_type& __a)
: unordered_set(__n, __hf, key_equal(), __a) {}
#endif
unordered_set(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a);
template <class _InputIterator>
unordered_set(_InputIterator __first, _InputIterator __last);
template <class _InputIterator>
unordered_set(_InputIterator __first, _InputIterator __last,
size_type __n, const hasher& __hf = hasher(),
const key_equal& __eql = key_equal());
template <class _InputIterator>
unordered_set(_InputIterator __first, _InputIterator __last,
size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a);
#if _LIBCPP_STD_VER > 11
template <class _InputIterator>
inline _LIBCPP_INLINE_VISIBILITY
unordered_set(_InputIterator __first, _InputIterator __last,
size_type __n, const allocator_type& __a)
: unordered_set(__first, __last, __n, hasher(), key_equal(), __a) {}
template <class _InputIterator>
unordered_set(_InputIterator __first, _InputIterator __last,
size_type __n, const hasher& __hf, const allocator_type& __a)
: unordered_set(__first, __last, __n, __hf, key_equal(), __a) {}
#endif
_LIBCPP_INLINE_VISIBILITY
explicit unordered_set(const allocator_type& __a);
unordered_set(const unordered_set& __u);
unordered_set(const unordered_set& __u, const allocator_type& __a);
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
unordered_set(unordered_set&& __u)
_NOEXCEPT_(is_nothrow_move_constructible<__table>::value);
unordered_set(unordered_set&& __u, const allocator_type& __a);
unordered_set(initializer_list<value_type> __il);
unordered_set(initializer_list<value_type> __il, size_type __n,
const hasher& __hf = hasher(),
const key_equal& __eql = key_equal());
unordered_set(initializer_list<value_type> __il, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a);
#if _LIBCPP_STD_VER > 11
inline _LIBCPP_INLINE_VISIBILITY
unordered_set(initializer_list<value_type> __il, size_type __n,
const allocator_type& __a)
: unordered_set(__il, __n, hasher(), key_equal(), __a) {}
inline _LIBCPP_INLINE_VISIBILITY
unordered_set(initializer_list<value_type> __il, size_type __n,
const hasher& __hf, const allocator_type& __a)
: unordered_set(__il, __n, __hf, key_equal(), __a) {}
#endif
#endif // _LIBCPP_CXX03_LANG
// ~unordered_set() = default;
_LIBCPP_INLINE_VISIBILITY
unordered_set& operator=(const unordered_set& __u)
{
__table_ = __u.__table_;
return *this;
}
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
unordered_set& operator=(unordered_set&& __u)
_NOEXCEPT_(is_nothrow_move_assignable<__table>::value);
_LIBCPP_INLINE_VISIBILITY
unordered_set& operator=(initializer_list<value_type> __il);
#endif // _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
allocator_type get_allocator() const _NOEXCEPT
{return allocator_type(__table_.__node_alloc());}
_LIBCPP_INLINE_VISIBILITY
bool empty() const _NOEXCEPT {return __table_.size() == 0;}
_LIBCPP_INLINE_VISIBILITY
size_type size() const _NOEXCEPT {return __table_.size();}
_LIBCPP_INLINE_VISIBILITY
size_type max_size() const _NOEXCEPT {return __table_.max_size();}
_LIBCPP_INLINE_VISIBILITY
iterator begin() _NOEXCEPT {return __table_.begin();}
_LIBCPP_INLINE_VISIBILITY
iterator end() _NOEXCEPT {return __table_.end();}
_LIBCPP_INLINE_VISIBILITY
const_iterator begin() const _NOEXCEPT {return __table_.begin();}
_LIBCPP_INLINE_VISIBILITY
const_iterator end() const _NOEXCEPT {return __table_.end();}
_LIBCPP_INLINE_VISIBILITY
const_iterator cbegin() const _NOEXCEPT {return __table_.begin();}
_LIBCPP_INLINE_VISIBILITY
const_iterator cend() const _NOEXCEPT {return __table_.end();}
#ifndef _LIBCPP_CXX03_LANG
template <class... _Args>
_LIBCPP_INLINE_VISIBILITY
pair<iterator, bool> emplace(_Args&&... __args)
{return __table_.__emplace_unique(_VSTD::forward<_Args>(__args)...);}
template <class... _Args>
_LIBCPP_INLINE_VISIBILITY
#if _LIBCPP_DEBUG_LEVEL >= 2
iterator emplace_hint(const_iterator __p, _Args&&... __args)
{
_LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__p) == this,
"unordered_set::emplace_hint(const_iterator, args...) called with an iterator not"
" referring to this unordered_set");
return __table_.__emplace_unique(_VSTD::forward<_Args>(__args)...).first;
}
#else
iterator emplace_hint(const_iterator, _Args&&... __args)
{return __table_.__emplace_unique(_VSTD::forward<_Args>(__args)...).first;}
#endif
_LIBCPP_INLINE_VISIBILITY
pair<iterator, bool> insert(value_type&& __x)
{return __table_.__insert_unique(_VSTD::move(__x));}
_LIBCPP_INLINE_VISIBILITY
#if _LIBCPP_DEBUG_LEVEL >= 2
iterator insert(const_iterator __p, value_type&& __x)
{
_LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__p) == this,
"unordered_set::insert(const_iterator, value_type&&) called with an iterator not"
" referring to this unordered_set");
return insert(_VSTD::move(__x)).first;
}
#else
iterator insert(const_iterator, value_type&& __x)
{return insert(_VSTD::move(__x)).first;}
#endif
_LIBCPP_INLINE_VISIBILITY
void insert(initializer_list<value_type> __il)
{insert(__il.begin(), __il.end());}
#endif // _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
pair<iterator, bool> insert(const value_type& __x)
{return __table_.__insert_unique(__x);}
_LIBCPP_INLINE_VISIBILITY
#if _LIBCPP_DEBUG_LEVEL >= 2
iterator insert(const_iterator __p, const value_type& __x)
{
_LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__p) == this,
"unordered_set::insert(const_iterator, const value_type&) called with an iterator not"
" referring to this unordered_set");
return insert(__x).first;
}
#else
iterator insert(const_iterator, const value_type& __x)
{return insert(__x).first;}
#endif
template <class _InputIterator>
_LIBCPP_INLINE_VISIBILITY
void insert(_InputIterator __first, _InputIterator __last);
_LIBCPP_INLINE_VISIBILITY
iterator erase(const_iterator __p) {return __table_.erase(__p);}
_LIBCPP_INLINE_VISIBILITY
size_type erase(const key_type& __k) {return __table_.__erase_unique(__k);}
_LIBCPP_INLINE_VISIBILITY
iterator erase(const_iterator __first, const_iterator __last)
{return __table_.erase(__first, __last);}
_LIBCPP_INLINE_VISIBILITY
void clear() _NOEXCEPT {__table_.clear();}
_LIBCPP_INLINE_VISIBILITY
void swap(unordered_set& __u)
_NOEXCEPT_(__is_nothrow_swappable<__table>::value)
{__table_.swap(__u.__table_);}
_LIBCPP_INLINE_VISIBILITY
hasher hash_function() const {return __table_.hash_function();}
_LIBCPP_INLINE_VISIBILITY
key_equal key_eq() const {return __table_.key_eq();}
_LIBCPP_INLINE_VISIBILITY
iterator find(const key_type& __k) {return __table_.find(__k);}
_LIBCPP_INLINE_VISIBILITY
const_iterator find(const key_type& __k) const {return __table_.find(__k);}
_LIBCPP_INLINE_VISIBILITY
size_type count(const key_type& __k) const {return __table_.__count_unique(__k);}
_LIBCPP_INLINE_VISIBILITY
pair<iterator, iterator> equal_range(const key_type& __k)
{return __table_.__equal_range_unique(__k);}
_LIBCPP_INLINE_VISIBILITY
pair<const_iterator, const_iterator> equal_range(const key_type& __k) const
{return __table_.__equal_range_unique(__k);}
_LIBCPP_INLINE_VISIBILITY
size_type bucket_count() const _NOEXCEPT {return __table_.bucket_count();}
_LIBCPP_INLINE_VISIBILITY
size_type max_bucket_count() const _NOEXCEPT {return __table_.max_bucket_count();}
_LIBCPP_INLINE_VISIBILITY
size_type bucket_size(size_type __n) const {return __table_.bucket_size(__n);}
_LIBCPP_INLINE_VISIBILITY
size_type bucket(const key_type& __k) const {return __table_.bucket(__k);}
_LIBCPP_INLINE_VISIBILITY
local_iterator begin(size_type __n) {return __table_.begin(__n);}
_LIBCPP_INLINE_VISIBILITY
local_iterator end(size_type __n) {return __table_.end(__n);}
_LIBCPP_INLINE_VISIBILITY
const_local_iterator begin(size_type __n) const {return __table_.cbegin(__n);}
_LIBCPP_INLINE_VISIBILITY
const_local_iterator end(size_type __n) const {return __table_.cend(__n);}
_LIBCPP_INLINE_VISIBILITY
const_local_iterator cbegin(size_type __n) const {return __table_.cbegin(__n);}
_LIBCPP_INLINE_VISIBILITY
const_local_iterator cend(size_type __n) const {return __table_.cend(__n);}
_LIBCPP_INLINE_VISIBILITY
float load_factor() const _NOEXCEPT {return __table_.load_factor();}
_LIBCPP_INLINE_VISIBILITY
float max_load_factor() const _NOEXCEPT {return __table_.max_load_factor();}
_LIBCPP_INLINE_VISIBILITY
void max_load_factor(float __mlf) {__table_.max_load_factor(__mlf);}
_LIBCPP_INLINE_VISIBILITY
void rehash(size_type __n) {__table_.rehash(__n);}
_LIBCPP_INLINE_VISIBILITY
void reserve(size_type __n) {__table_.reserve(__n);}
#if _LIBCPP_DEBUG_LEVEL >= 2
bool __dereferenceable(const const_iterator* __i) const
{return __table_.__dereferenceable(__i);}
bool __decrementable(const const_iterator* __i) const
{return __table_.__decrementable(__i);}
bool __addable(const const_iterator* __i, ptrdiff_t __n) const
{return __table_.__addable(__i, __n);}
bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const
{return __table_.__addable(__i, __n);}
#endif // _LIBCPP_DEBUG_LEVEL >= 2
};
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(size_type __n,
const hasher& __hf, const key_equal& __eql)
: __table_(__hf, __eql)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(size_type __n,
const hasher& __hf, const key_equal& __eql, const allocator_type& __a)
: __table_(__hf, __eql, __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
template <class _InputIterator>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
_InputIterator __first, _InputIterator __last)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
insert(__first, __last);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
template <class _InputIterator>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
_InputIterator __first, _InputIterator __last, size_type __n,
const hasher& __hf, const key_equal& __eql)
: __table_(__hf, __eql)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
insert(__first, __last);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
template <class _InputIterator>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
_InputIterator __first, _InputIterator __last, size_type __n,
const hasher& __hf, const key_equal& __eql, const allocator_type& __a)
: __table_(__hf, __eql, __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
insert(__first, __last);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
const allocator_type& __a)
: __table_(__a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
const unordered_set& __u)
: __table_(__u.__table_)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__u.bucket_count());
insert(__u.begin(), __u.end());
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
const unordered_set& __u, const allocator_type& __a)
: __table_(__u.__table_, __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__u.bucket_count());
insert(__u.begin(), __u.end());
}
#ifndef _LIBCPP_CXX03_LANG
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
unordered_set&& __u)
_NOEXCEPT_(is_nothrow_move_constructible<__table>::value)
: __table_(_VSTD::move(__u.__table_))
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
__get_db()->swap(this, &__u);
#endif
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
unordered_set&& __u, const allocator_type& __a)
: __table_(_VSTD::move(__u.__table_), __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
if (__a != __u.get_allocator())
{
iterator __i = __u.begin();
while (__u.size() != 0)
__table_.__insert_unique(_VSTD::move(__u.__table_.remove(__i++)->__value_));
}
#if _LIBCPP_DEBUG_LEVEL >= 2
else
__get_db()->swap(this, &__u);
#endif
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
initializer_list<value_type> __il)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
insert(__il.begin(), __il.end());
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
initializer_list<value_type> __il, size_type __n, const hasher& __hf,
const key_equal& __eql)
: __table_(__hf, __eql)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
insert(__il.begin(), __il.end());
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set(
initializer_list<value_type> __il, size_type __n, const hasher& __hf,
const key_equal& __eql, const allocator_type& __a)
: __table_(__hf, __eql, __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
insert(__il.begin(), __il.end());
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline
unordered_set<_Value, _Hash, _Pred, _Alloc>&
unordered_set<_Value, _Hash, _Pred, _Alloc>::operator=(unordered_set&& __u)
_NOEXCEPT_(is_nothrow_move_assignable<__table>::value)
{
__table_ = _VSTD::move(__u.__table_);
return *this;
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline
unordered_set<_Value, _Hash, _Pred, _Alloc>&
unordered_set<_Value, _Hash, _Pred, _Alloc>::operator=(
initializer_list<value_type> __il)
{
__table_.__assign_unique(__il.begin(), __il.end());
return *this;
}
#endif // _LIBCPP_CXX03_LANG
template <class _Value, class _Hash, class _Pred, class _Alloc>
template <class _InputIterator>
inline
void
unordered_set<_Value, _Hash, _Pred, _Alloc>::insert(_InputIterator __first,
_InputIterator __last)
{
for (; __first != __last; ++__first)
__table_.__insert_unique(*__first);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline _LIBCPP_INLINE_VISIBILITY
void
swap(unordered_set<_Value, _Hash, _Pred, _Alloc>& __x,
unordered_set<_Value, _Hash, _Pred, _Alloc>& __y)
_NOEXCEPT_(_NOEXCEPT_(__x.swap(__y)))
{
__x.swap(__y);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
bool
operator==(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x,
const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y)
{
if (__x.size() != __y.size())
return false;
typedef typename unordered_set<_Value, _Hash, _Pred, _Alloc>::const_iterator
const_iterator;
for (const_iterator __i = __x.begin(), __ex = __x.end(), __ey = __y.end();
__i != __ex; ++__i)
{
const_iterator __j = __y.find(*__i);
if (__j == __ey || !(*__i == *__j))
return false;
}
return true;
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator!=(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x,
const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y)
{
return !(__x == __y);
}
template <class _Value, class _Hash = hash<_Value>, class _Pred = equal_to<_Value>,
class _Alloc = allocator<_Value> >
class _LIBCPP_TEMPLATE_VIS unordered_multiset
{
public:
// types
typedef _Value key_type;
typedef key_type value_type;
typedef _Hash hasher;
typedef _Pred key_equal;
typedef _Alloc allocator_type;
typedef value_type& reference;
typedef const value_type& const_reference;
static_assert((is_same<value_type, typename allocator_type::value_type>::value),
"Invalid allocator::value_type");
private:
typedef __hash_table<value_type, hasher, key_equal, allocator_type> __table;
__table __table_;
public:
typedef typename __table::pointer pointer;
typedef typename __table::const_pointer const_pointer;
typedef typename __table::size_type size_type;
typedef typename __table::difference_type difference_type;
typedef typename __table::const_iterator iterator;
typedef typename __table::const_iterator const_iterator;
typedef typename __table::const_local_iterator local_iterator;
typedef typename __table::const_local_iterator const_local_iterator;
_LIBCPP_INLINE_VISIBILITY
unordered_multiset()
_NOEXCEPT_(is_nothrow_default_constructible<__table>::value)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
explicit unordered_multiset(size_type __n, const hasher& __hf = hasher(),
const key_equal& __eql = key_equal());
unordered_multiset(size_type __n, const hasher& __hf,
const key_equal& __eql, const allocator_type& __a);
#if _LIBCPP_STD_VER > 11
inline _LIBCPP_INLINE_VISIBILITY
unordered_multiset(size_type __n, const allocator_type& __a)
: unordered_multiset(__n, hasher(), key_equal(), __a) {}
inline _LIBCPP_INLINE_VISIBILITY
unordered_multiset(size_type __n, const hasher& __hf, const allocator_type& __a)
: unordered_multiset(__n, __hf, key_equal(), __a) {}
#endif
template <class _InputIterator>
unordered_multiset(_InputIterator __first, _InputIterator __last);
template <class _InputIterator>
unordered_multiset(_InputIterator __first, _InputIterator __last,
size_type __n, const hasher& __hf = hasher(),
const key_equal& __eql = key_equal());
template <class _InputIterator>
unordered_multiset(_InputIterator __first, _InputIterator __last,
size_type __n , const hasher& __hf,
const key_equal& __eql, const allocator_type& __a);
#if _LIBCPP_STD_VER > 11
template <class _InputIterator>
inline _LIBCPP_INLINE_VISIBILITY
unordered_multiset(_InputIterator __first, _InputIterator __last,
size_type __n, const allocator_type& __a)
: unordered_multiset(__first, __last, __n, hasher(), key_equal(), __a) {}
template <class _InputIterator>
inline _LIBCPP_INLINE_VISIBILITY
unordered_multiset(_InputIterator __first, _InputIterator __last,
size_type __n, const hasher& __hf, const allocator_type& __a)
: unordered_multiset(__first, __last, __n, __hf, key_equal(), __a) {}
#endif
_LIBCPP_INLINE_VISIBILITY
explicit unordered_multiset(const allocator_type& __a);
unordered_multiset(const unordered_multiset& __u);
unordered_multiset(const unordered_multiset& __u, const allocator_type& __a);
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
unordered_multiset(unordered_multiset&& __u)
_NOEXCEPT_(is_nothrow_move_constructible<__table>::value);
unordered_multiset(unordered_multiset&& __u, const allocator_type& __a);
unordered_multiset(initializer_list<value_type> __il);
unordered_multiset(initializer_list<value_type> __il, size_type __n,
const hasher& __hf = hasher(),
const key_equal& __eql = key_equal());
unordered_multiset(initializer_list<value_type> __il, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a);
#if _LIBCPP_STD_VER > 11
inline _LIBCPP_INLINE_VISIBILITY
unordered_multiset(initializer_list<value_type> __il, size_type __n, const allocator_type& __a)
: unordered_multiset(__il, __n, hasher(), key_equal(), __a) {}
inline _LIBCPP_INLINE_VISIBILITY
unordered_multiset(initializer_list<value_type> __il, size_type __n, const hasher& __hf, const allocator_type& __a)
: unordered_multiset(__il, __n, __hf, key_equal(), __a) {}
#endif
#endif // _LIBCPP_CXX03_LANG
// ~unordered_multiset() = default;
_LIBCPP_INLINE_VISIBILITY
unordered_multiset& operator=(const unordered_multiset& __u)
{
__table_ = __u.__table_;
return *this;
}
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
unordered_multiset& operator=(unordered_multiset&& __u)
_NOEXCEPT_(is_nothrow_move_assignable<__table>::value);
unordered_multiset& operator=(initializer_list<value_type> __il);
#endif // _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
allocator_type get_allocator() const _NOEXCEPT
{return allocator_type(__table_.__node_alloc());}
_LIBCPP_INLINE_VISIBILITY
bool empty() const _NOEXCEPT {return __table_.size() == 0;}
_LIBCPP_INLINE_VISIBILITY
size_type size() const _NOEXCEPT {return __table_.size();}
_LIBCPP_INLINE_VISIBILITY
size_type max_size() const _NOEXCEPT {return __table_.max_size();}
_LIBCPP_INLINE_VISIBILITY
iterator begin() _NOEXCEPT {return __table_.begin();}
_LIBCPP_INLINE_VISIBILITY
iterator end() _NOEXCEPT {return __table_.end();}
_LIBCPP_INLINE_VISIBILITY
const_iterator begin() const _NOEXCEPT {return __table_.begin();}
_LIBCPP_INLINE_VISIBILITY
const_iterator end() const _NOEXCEPT {return __table_.end();}
_LIBCPP_INLINE_VISIBILITY
const_iterator cbegin() const _NOEXCEPT {return __table_.begin();}
_LIBCPP_INLINE_VISIBILITY
const_iterator cend() const _NOEXCEPT {return __table_.end();}
#ifndef _LIBCPP_CXX03_LANG
template <class... _Args>
_LIBCPP_INLINE_VISIBILITY
iterator emplace(_Args&&... __args)
{return __table_.__emplace_multi(_VSTD::forward<_Args>(__args)...);}
template <class... _Args>
_LIBCPP_INLINE_VISIBILITY
iterator emplace_hint(const_iterator __p, _Args&&... __args)
{return __table_.__emplace_hint_multi(__p, _VSTD::forward<_Args>(__args)...);}
_LIBCPP_INLINE_VISIBILITY
iterator insert(value_type&& __x) {return __table_.__insert_multi(_VSTD::move(__x));}
_LIBCPP_INLINE_VISIBILITY
iterator insert(const_iterator __p, value_type&& __x)
{return __table_.__insert_multi(__p, _VSTD::move(__x));}
_LIBCPP_INLINE_VISIBILITY
void insert(initializer_list<value_type> __il)
{insert(__il.begin(), __il.end());}
#endif // _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
iterator insert(const value_type& __x) {return __table_.__insert_multi(__x);}
_LIBCPP_INLINE_VISIBILITY
iterator insert(const_iterator __p, const value_type& __x)
{return __table_.__insert_multi(__p, __x);}
template <class _InputIterator>
_LIBCPP_INLINE_VISIBILITY
void insert(_InputIterator __first, _InputIterator __last);
_LIBCPP_INLINE_VISIBILITY
iterator erase(const_iterator __p) {return __table_.erase(__p);}
_LIBCPP_INLINE_VISIBILITY
size_type erase(const key_type& __k) {return __table_.__erase_multi(__k);}
_LIBCPP_INLINE_VISIBILITY
iterator erase(const_iterator __first, const_iterator __last)
{return __table_.erase(__first, __last);}
_LIBCPP_INLINE_VISIBILITY
void clear() _NOEXCEPT {__table_.clear();}
_LIBCPP_INLINE_VISIBILITY
void swap(unordered_multiset& __u)
_NOEXCEPT_(__is_nothrow_swappable<__table>::value)
{__table_.swap(__u.__table_);}
_LIBCPP_INLINE_VISIBILITY
hasher hash_function() const {return __table_.hash_function();}
_LIBCPP_INLINE_VISIBILITY
key_equal key_eq() const {return __table_.key_eq();}
_LIBCPP_INLINE_VISIBILITY
iterator find(const key_type& __k) {return __table_.find(__k);}
_LIBCPP_INLINE_VISIBILITY
const_iterator find(const key_type& __k) const {return __table_.find(__k);}
_LIBCPP_INLINE_VISIBILITY
size_type count(const key_type& __k) const {return __table_.__count_multi(__k);}
_LIBCPP_INLINE_VISIBILITY
pair<iterator, iterator> equal_range(const key_type& __k)
{return __table_.__equal_range_multi(__k);}
_LIBCPP_INLINE_VISIBILITY
pair<const_iterator, const_iterator> equal_range(const key_type& __k) const
{return __table_.__equal_range_multi(__k);}
_LIBCPP_INLINE_VISIBILITY
size_type bucket_count() const _NOEXCEPT {return __table_.bucket_count();}
_LIBCPP_INLINE_VISIBILITY
size_type max_bucket_count() const _NOEXCEPT {return __table_.max_bucket_count();}
_LIBCPP_INLINE_VISIBILITY
size_type bucket_size(size_type __n) const {return __table_.bucket_size(__n);}
_LIBCPP_INLINE_VISIBILITY
size_type bucket(const key_type& __k) const {return __table_.bucket(__k);}
_LIBCPP_INLINE_VISIBILITY
local_iterator begin(size_type __n) {return __table_.begin(__n);}
_LIBCPP_INLINE_VISIBILITY
local_iterator end(size_type __n) {return __table_.end(__n);}
_LIBCPP_INLINE_VISIBILITY
const_local_iterator begin(size_type __n) const {return __table_.cbegin(__n);}
_LIBCPP_INLINE_VISIBILITY
const_local_iterator end(size_type __n) const {return __table_.cend(__n);}
_LIBCPP_INLINE_VISIBILITY
const_local_iterator cbegin(size_type __n) const {return __table_.cbegin(__n);}
_LIBCPP_INLINE_VISIBILITY
const_local_iterator cend(size_type __n) const {return __table_.cend(__n);}
_LIBCPP_INLINE_VISIBILITY
float load_factor() const _NOEXCEPT {return __table_.load_factor();}
_LIBCPP_INLINE_VISIBILITY
float max_load_factor() const _NOEXCEPT {return __table_.max_load_factor();}
_LIBCPP_INLINE_VISIBILITY
void max_load_factor(float __mlf) {__table_.max_load_factor(__mlf);}
_LIBCPP_INLINE_VISIBILITY
void rehash(size_type __n) {__table_.rehash(__n);}
_LIBCPP_INLINE_VISIBILITY
void reserve(size_type __n) {__table_.reserve(__n);}
#if _LIBCPP_DEBUG_LEVEL >= 2
bool __dereferenceable(const const_iterator* __i) const
{return __table_.__dereferenceable(__i);}
bool __decrementable(const const_iterator* __i) const
{return __table_.__decrementable(__i);}
bool __addable(const const_iterator* __i, ptrdiff_t __n) const
{return __table_.__addable(__i, __n);}
bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const
{return __table_.__addable(__i, __n);}
#endif // _LIBCPP_DEBUG_LEVEL >= 2
};
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
size_type __n, const hasher& __hf, const key_equal& __eql)
: __table_(__hf, __eql)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a)
: __table_(__hf, __eql, __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
template <class _InputIterator>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
_InputIterator __first, _InputIterator __last)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
insert(__first, __last);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
template <class _InputIterator>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
_InputIterator __first, _InputIterator __last, size_type __n,
const hasher& __hf, const key_equal& __eql)
: __table_(__hf, __eql)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
insert(__first, __last);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
template <class _InputIterator>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
_InputIterator __first, _InputIterator __last, size_type __n,
const hasher& __hf, const key_equal& __eql, const allocator_type& __a)
: __table_(__hf, __eql, __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
insert(__first, __last);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
const allocator_type& __a)
: __table_(__a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
const unordered_multiset& __u)
: __table_(__u.__table_)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__u.bucket_count());
insert(__u.begin(), __u.end());
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
const unordered_multiset& __u, const allocator_type& __a)
: __table_(__u.__table_, __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__u.bucket_count());
insert(__u.begin(), __u.end());
}
#ifndef _LIBCPP_CXX03_LANG
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
unordered_multiset&& __u)
_NOEXCEPT_(is_nothrow_move_constructible<__table>::value)
: __table_(_VSTD::move(__u.__table_))
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
__get_db()->swap(this, &__u);
#endif
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
unordered_multiset&& __u, const allocator_type& __a)
: __table_(_VSTD::move(__u.__table_), __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
if (__a != __u.get_allocator())
{
iterator __i = __u.begin();
while (__u.size() != 0)
__table_.__insert_multi(_VSTD::move(__u.__table_.remove(__i++)->__value_));
}
#if _LIBCPP_DEBUG_LEVEL >= 2
else
__get_db()->swap(this, &__u);
#endif
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
initializer_list<value_type> __il)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
insert(__il.begin(), __il.end());
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
initializer_list<value_type> __il, size_type __n, const hasher& __hf,
const key_equal& __eql)
: __table_(__hf, __eql)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
insert(__il.begin(), __il.end());
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::unordered_multiset(
initializer_list<value_type> __il, size_type __n, const hasher& __hf,
const key_equal& __eql, const allocator_type& __a)
: __table_(__hf, __eql, __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__table_.rehash(__n);
insert(__il.begin(), __il.end());
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline
unordered_multiset<_Value, _Hash, _Pred, _Alloc>&
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::operator=(
unordered_multiset&& __u)
_NOEXCEPT_(is_nothrow_move_assignable<__table>::value)
{
__table_ = _VSTD::move(__u.__table_);
return *this;
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline
unordered_multiset<_Value, _Hash, _Pred, _Alloc>&
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::operator=(
initializer_list<value_type> __il)
{
__table_.__assign_multi(__il.begin(), __il.end());
return *this;
}
#endif // _LIBCPP_CXX03_LANG
template <class _Value, class _Hash, class _Pred, class _Alloc>
template <class _InputIterator>
inline
void
unordered_multiset<_Value, _Hash, _Pred, _Alloc>::insert(_InputIterator __first,
_InputIterator __last)
{
for (; __first != __last; ++__first)
__table_.__insert_multi(*__first);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline _LIBCPP_INLINE_VISIBILITY
void
swap(unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x,
unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y)
_NOEXCEPT_(_NOEXCEPT_(__x.swap(__y)))
{
__x.swap(__y);
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
bool
operator==(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x,
const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y)
{
if (__x.size() != __y.size())
return false;
typedef typename unordered_multiset<_Value, _Hash, _Pred, _Alloc>::const_iterator
const_iterator;
typedef pair<const_iterator, const_iterator> _EqRng;
for (const_iterator __i = __x.begin(), __ex = __x.end(); __i != __ex;)
{
_EqRng __xeq = __x.equal_range(*__i);
_EqRng __yeq = __y.equal_range(*__i);
if (_VSTD::distance(__xeq.first, __xeq.second) !=
_VSTD::distance(__yeq.first, __yeq.second) ||
!_VSTD::is_permutation(__xeq.first, __xeq.second, __yeq.first))
return false;
__i = __xeq.second;
}
return true;
}
template <class _Value, class _Hash, class _Pred, class _Alloc>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator!=(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x,
const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y)
{
return !(__x == __y);
}
_LIBCPP_END_NAMESPACE_STD
#endif // _LIBCPP_UNORDERED_SET
| 37.901246 | 119 | 0.693709 | greck2908 |
664b6287154d6c4e004e6a20788376ba4ee6b901 | 751 | cpp | C++ | Solution/045.Jump Game II/solution1-16ms.cpp | zhufei2805801318/352_Leetcode | fc9bfdd7eb462684b1345c953de843d6cfffabd0 | [
"MIT"
] | 6 | 2018-11-08T06:16:19.000Z | 2019-09-07T13:39:00.000Z | Solution/045.Jump Game II/solution1-16ms.cpp | zhufei2805801318/352_Leetcode | fc9bfdd7eb462684b1345c953de843d6cfffabd0 | [
"MIT"
] | 10 | 2018-11-09T12:17:55.000Z | 2018-12-03T18:11:49.000Z | Solution/045.Jump Game II/solution1-16ms.cpp | zhufei2805801318/352_Leetcode | fc9bfdd7eb462684b1345c953de843d6cfffabd0 | [
"MIT"
] | 7 | 2018-11-08T14:31:49.000Z | 2018-11-23T14:55:45.000Z | class Solution {
public:
int jump(vector<int>& nums) {
int i,j,cnt,ref_i,ref;
int n=nums.size();
if(n==0)
return 0;
if(n==1)
return 0;
cnt=0;
i=0;
while(i<n-1&&nums[i]){
ref_i=i;
ref=-1;
for(j=1;j<=nums[i];j++){
if(j+i>=n-1){
ref_i=i+j;
break;
}
if(j+nums[i+j]>ref){
ref=j+nums[i+j];
ref_i=i+j;
}
}
i=ref_i;
cnt++;
}
if(i<n-1){
return n-1;
}
else{
return cnt;
}
}
}; | 20.861111 | 36 | 0.28229 | zhufei2805801318 |
664e91a54ed5a7e75791bc2bcf9c2f7343ce8317 | 1,999 | cpp | C++ | docker/d-streamon-master/d-streamon/streamon/tests/libfc/test/TestReader.cpp | ferrarimarco/open-scissor | d54718a1969701798f3e2d57f3db68d829da1cc0 | [
"Apache-2.0"
] | 2 | 2017-12-02T10:38:05.000Z | 2018-04-22T17:15:01.000Z | docker/d-streamon-master/d-streamon/streamon/tests/libfc/test/TestReader.cpp | scissor-project/open-scissor | d54718a1969701798f3e2d57f3db68d829da1cc0 | [
"Apache-2.0"
] | 67 | 2017-11-11T15:22:34.000Z | 2018-04-24T06:44:59.000Z | docker/d-streamon-master/d-streamon/streamon/tests/libfc/test/TestReader.cpp | ferrarimarco/open-scissor | d54718a1969701798f3e2d57f3db68d829da1cc0 | [
"Apache-2.0"
] | 1 | 2017-12-07T08:18:49.000Z | 2017-12-07T08:18:49.000Z | #include "TestCommon.h"
#include <cstdio>
using namespace IPFIX;
class SimpleFlowReceiver : public SetReceiver {
private:
SimpleFlow vsf_;
StructTemplate vst_;
public:
SimpleFlowReceiver() {
initSimpleFlow(vsf_);
makeSimpleFlowTemplate(vst_);
}
const IETemplate *structTemplate() {
return &vst_;
}
void registerWithCollector(Collector& c) {
c.registerReceiver(&vst_, this);
}
virtual void receive(const Collector* collector,
Transcoder& setxc,
const WireTemplate* settmpl) {
SimpleFlow sf;
while (settmpl->decode(setxc, vst_, reinterpret_cast<uint8_t*>(&sf))) {
incrSimpleFlow(vsf_);
matchSimpleFlow(vsf_, sf);
// fprintf(stdout, "[X %5u] %016llx - %016llx %08x:%04x -> %08x:%04x (%08x)\n",
// packet_count,
// vsf_.flowStartMilliseconds, vsf_.flowEndMilliseconds,
// vsf_.sourceIPv4Address, vsf_.sourceTransportPort,
// vsf_.destinationIPv4Address, vsf_.destinationTransportPort,
// vsf_.packetDeltaCount);
// fprintf(stdout, "[A %5u] %016llx - %016llx %08x:%04x -> %08x:%04x (%08x)\n",
// packet_count++,
// sf.flowStartMilliseconds, sf.flowEndMilliseconds,
// sf.sourceIPv4Address, sf.sourceTransportPort,
// sf.destinationIPv4Address, sf.destinationTransportPort,
// sf.packetDeltaCount);
}
}
};
int main (int argc, char *argv[]) {
// set up signal handlers
install_quit_handler();
// initialize an information model for IPFIX, no biflows
InfoModel::instance().defaultIPFIX();
// create a file exporter for stdout
FileReader fr("test.ipfix");
// register them as minimal templates
SimpleFlowReceiver sfsrecv;
sfsrecv.registerWithCollector(fr);
while (!didQuit()) {
MBuf mbuf;
if (!fr.receiveMessage(mbuf)) { doQuit(0); }
}
} | 28.557143 | 87 | 0.613807 | ferrarimarco |
593f227284280d7f48dcdc48795a96427bafca17 | 3,012 | cpp | C++ | src/Renderer/EskyDisplay.cpp | danielofdaniels/ProjectEskyLLAPI | 9278ea025f1a392adf563364ff7ee87b8223b262 | [
"BSD-3-Clause"
] | 5 | 2020-12-29T03:37:17.000Z | 2022-02-20T10:58:25.000Z | src/Renderer/EskyDisplay.cpp | danielofdaniels/ProjectEskyLLAPI | 9278ea025f1a392adf563364ff7ee87b8223b262 | [
"BSD-3-Clause"
] | 1 | 2021-01-14T04:30:31.000Z | 2021-01-14T04:30:31.000Z | src/Renderer/EskyDisplay.cpp | danielofdaniels/ProjectEskyLLAPI | 9278ea025f1a392adf563364ff7ee87b8223b262 | [
"BSD-3-Clause"
] | 3 | 2020-12-13T03:52:52.000Z | 2021-10-30T04:00:36.000Z | #include "EskyDisplay.h"
#include <iostream>
#include <sstream>
#include "EskyRenderer.h"
EskyDisplay::EskyDisplay() {
_debugCallback("Creating EskyDisplay");
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::ostringstream error_message;
error_message << "Failed to initialize SDL: ";
error_message << SDL_GetError();
_debugCallback(error_message.str().c_str());
return;
}
_renderer = EskyRenderer::Create(kUnityGfxRendererVulkan, _debugCallback);
}
EskyDisplay::~EskyDisplay() {
_debugCallback("Destroying EskyDisplay");
for (int i = 0; i < _windows.size(); i++) {
stopWindowById(i);
}
if (_renderer) {
delete _renderer;
}
SDL_Quit();
}
void EskyDisplay::run() {
bool quit = false;
while (!quit) {
SDL_Event e;
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_QUIT: {
quit = true;
break;
}
case SDL_WINDOWEVENT: {
SDL_Window* event_window = SDL_GetWindowFromID(e.window.windowID);
for (auto& window : _windows) {
if (window && event_window == window->getHandle()) {
window->onEvent(&e.window);
break;
}
}
break;
}
default:
break;
}
}
_renderer->renderFrame();
}
}
EskyRenderer* EskyDisplay::getRenderer() { return _renderer; }
void EskyDisplay::startWindowById(int id, const wchar_t*, int, int, bool) {
// Check that there isn't already a window here
EskyWindow* old_window = _assertWindow(id);
if (old_window) {
std::ostringstream error_message;
error_message << "Window #" << id << " is already started";
_debugCallback(error_message.str().c_str());
return;
}
SDL_Window* new_window = SDL_CreateWindow(
"Esky Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600,
SDL_WINDOW_SHOWN | SDL_WINDOW_VULKAN);
if (!new_window) {
std::ostringstream error_message;
error_message << "Failed to create SDL window: ";
error_message << SDL_GetError();
_debugCallback(error_message.str().c_str());
return;
}
// Ensure that the window vector has enough room
if (id >= _windows.size()) {
// Pad new elements with nullptr
_windows.resize(id + 1, nullptr);
}
_windows[id] = _renderer->createWindow(new_window);
}
EskyWindow* EskyDisplay::getWindowById(int id) { return _assertWindow(id); }
void EskyDisplay::stopWindowById(int id) {
EskyWindow* window = _assertWindow(id);
if (window) {
_windows[id] = nullptr;
delete window;
}
}
void EskyDisplay::setColorFormat(int colorFormat) {
// TODO(marceline-cramer) Set color format
}
EskyWindow* EskyDisplay::_assertWindow(int id) {
// TODO(marceline-cramer) DebugMessage here
if (id < 0 || id >= _windows.size()) {
return nullptr;
}
EskyWindow* window = _windows[id];
return window;
}
void EskyDisplay::_debugCallback(const char* message) {
std::cerr << "Debug: " << message << std::endl;
}
| 23.348837 | 80 | 0.642098 | danielofdaniels |
5942524eb41163d677b22ea26f59b95749d8c17b | 1,166 | cpp | C++ | src/catch2/internal/catch_debug_console.cpp | nicramage/Catch2 | 6f21a3609cea360846a0ca93be55877cca14c86d | [
"BSL-1.0"
] | 9,861 | 2017-11-03T13:11:42.000Z | 2022-03-31T23:50:03.000Z | src/catch2/internal/catch_debug_console.cpp | nicramage/Catch2 | 6f21a3609cea360846a0ca93be55877cca14c86d | [
"BSL-1.0"
] | 1,409 | 2017-11-03T13:42:48.000Z | 2022-03-31T14:46:42.000Z | src/catch2/internal/catch_debug_console.cpp | nicramage/Catch2 | 6f21a3609cea360846a0ca93be55877cca14c86d | [
"BSL-1.0"
] | 2,442 | 2017-11-03T14:48:53.000Z | 2022-03-31T23:07:09.000Z |
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
#include <catch2/internal/catch_debug_console.hpp>
#include <catch2/internal/catch_config_android_logwrite.hpp>
#include <catch2/internal/catch_stream.hpp>
#include <catch2/internal/catch_platform.hpp>
#include <catch2/internal/catch_windows_h_proxy.hpp>
#if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
#include <android/log.h>
namespace Catch {
void writeToDebugConsole( std::string const& text ) {
__android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
}
}
#elif defined(CATCH_PLATFORM_WINDOWS)
namespace Catch {
void writeToDebugConsole( std::string const& text ) {
::OutputDebugStringA( text.c_str() );
}
}
#else
namespace Catch {
void writeToDebugConsole( std::string const& text ) {
// !TBD: Need a version for Mac/ XCode and other IDEs
Catch::cout() << text;
}
}
#endif // Platform
| 28.439024 | 76 | 0.669811 | nicramage |
5949938cb7a1970c1b826cb1b1d281a8e31e4944 | 6,366 | cpp | C++ | computeProjectionsAutocorrelation.cpp | cpuimage/Deblurring | 8083d4f4a0413bc3e43f1657400c314c51dce860 | [
"MIT"
] | 50 | 2018-11-20T07:50:40.000Z | 2022-03-23T08:18:50.000Z | computeProjectionsAutocorrelation.cpp | chuckwoody/Deblurring | 8083d4f4a0413bc3e43f1657400c314c51dce860 | [
"MIT"
] | 1 | 2019-12-05T05:59:31.000Z | 2019-12-05T05:59:31.000Z | computeProjectionsAutocorrelation.cpp | chuckwoody/Deblurring | 8083d4f4a0413bc3e43f1657400c314c51dce860 | [
"MIT"
] | 15 | 2019-03-27T08:18:28.000Z | 2021-11-05T00:58:37.000Z | #include <cmath>
#include <cassert>
#include <cstring>
#include <algorithm>
#include "image.hpp"
#include "angleSet.hpp"
#include "projectImage.hpp"
#include "conjugate_gradient.hpp"
/// computed the autocorrelation of a signal up to a given window size
/// values at a radius windowRadius of the border of data are not used
template <typename T>
void computeAutocorrelation(std::vector<T>& out, const std::vector<T>& data,
int windowRadius)
{
out.resize(windowRadius*2+1);
std::fill(out.begin(), out.end(), 0.);
int len = data.size();
for (int i = 0; i <= windowRadius; i++) {
T suma = 0.;
T sumb = 0.;
for (int j = 0; j < len - (windowRadius*2 + 1); j++) {
suma += data[windowRadius + j] * data[windowRadius - i + j];
sumb += data[windowRadius + j] * data[windowRadius + i + j];
}
T res = (suma + sumb) / 2.;
out[windowRadius-i] = res;
out[windowRadius+i] = res;
}
for (int i = 0; i < windowRadius*2+1; i++) {
out[i] /= len - (windowRadius*2+1);
}
}
/// whiten an image by convolving it with a 9 points 1D differentiation filter
/// the filter is applied to rows and columns (returns two images)
template <typename T>
static void whitenImage(img_t<T>& imgBlurX, img_t<T>& imgBlurY,
const img_t<T>& imgBlur)
{
const T filter[] = { 3/840., -32/840., 168/840., -672/840.,
0, 672/840., -168/840., 32/840., -3/840. };
int filterSize = sizeof(filter) / sizeof(*filter);
int w = imgBlur.w;
int h = imgBlur.h;
imgBlurX.ensure_size(w, h);
imgBlurX.set_value(0);
imgBlurY.ensure_size(w, h);
imgBlurY.set_value(0);
// apply the filter vertically and horizontally
for (int y = filterSize/2; y < h - filterSize/2; y++) {
for (int x = filterSize/2; x < w - filterSize/2; x++) {
for (int i = 0; i < filterSize; i++) {
imgBlurX(x, y) += filter[filterSize-1 - i] * imgBlur(x + i - filterSize/2, y);
imgBlurY(x, y) += filter[filterSize-1 - i] * imgBlur(x, y + i - filterSize/2);
}
}
}
}
template <typename T>
void conv(T *y, T *x, int n, void *e)
{
std::vector<T>& filter = *(std::vector<T>*)e;
assert((int)filter.size() == n);
for (int i = 0; i < n; i++) {
y[i] = 0;
for (int j = -n/2; j < n/2; j++) {
int jj = j + n/2;
// repeating boundaries
int idx = std::max(0, std::min(n-1, i - j));
y[i] += filter[jj] * x[idx];
}
}
}
template <typename T>
static void deconvolveAutocorrelation(std::vector<T>& acCompensatedRow,
const std::vector<T>& acRow,
const std::vector<T>& compensationFilter)
{
auto deconvRow = acRow;
// solve `acRow = convolve(compensationFilter, deconvRow)` to find deconvRow
conjugate_gradient<T>(&deconvRow[0], conv, &acRow[0], acRow.size(), (void*)&compensationFilter);
// detect negatives values in the center of the row
bool hasNegatives = false;
for (unsigned x = deconvRow.size() / 2 - 2; x <= deconvRow.size() / 2 + 2; x++)
hasNegatives |= deconvRow[x] < 0.;
// if there are some negative values, revert the changes
if (hasNegatives) {
acCompensatedRow = acRow;
} else {
acCompensatedRow = deconvRow;
}
}
/// computes the autocorrelation of the projections of the whitened image
template <typename T>
void computeProjectionsAutocorrelation(img_t<T>& acProjections, const img_t<T>& imgBlur,
const std::vector<angle_t>& angleSet,
int psSize, T compensationFactor)
{
img_t<T> projections;
// whiten the image (horizontal and vertical filtering with the filter 'd')
img_t<T> imgBlurX;
img_t<T> imgBlurY;
whitenImage(imgBlurX, imgBlurY, imgBlur);
// compute the projections of the derivative
projectImage(projections, imgBlurX, imgBlurY, angleSet);
acProjections.ensure_size(psSize*2 + 1, projections.h);
// build the compensation filter
// k(x) = 1 / x^compensationFactor
std::vector<T> compensationFilter(acProjections.w);
if (compensationFactor > 0.) {
int center = compensationFilter.size() / 2;
T sum = 0.;
for (int i = 0; i < (int) compensationFilter.size(); i++) {
compensationFilter[i] = 1. / std::pow(std::abs(i - center) + 1, compensationFactor);
sum += compensationFilter[i];
}
for (unsigned int i = 0; i < compensationFilter.size(); i++) {
compensationFilter[i] /= sum;
}
}
#pragma omp parallel
{
std::vector<T> proj1d(projections.h);
#pragma omp for
for (int j = 0; j < projections.h; j++) {
// extract meaningful values of the projections
proj1d.resize(0);
for (int i = 0; i < projections.w; i++) {
if (!std::isnan(projections(i, j))) {
proj1d.push_back(projections(i, j));
}
}
// compute the mean
T mean = 0.;
for (T v : proj1d)
mean += v;
mean /= proj1d.size();
// center
for (T& v : proj1d)
v -= mean;
// compute the norm
T norm = 0.;
for (T v : proj1d)
norm += v * v;
norm = std::sqrt(norm);
// normalize
for (T& v : proj1d)
v /= norm;
// compute autocorrelation of the projection
std::vector<T> autocorrelation;
computeAutocorrelation(autocorrelation, proj1d, psSize);
// apply the compensation filter
if (compensationFactor > 0.) {
// deconvolve the autocorrelation with the compensation filter
deconvolveAutocorrelation(autocorrelation, autocorrelation, compensationFilter);
}
// extract the central part of the autocorrelation
auto start = &autocorrelation[0] + autocorrelation.size() / 2 - acProjections.w / 2;
std::copy(start, start + acProjections.w, &acProjections(0, j));
}
}
}
| 33.861702 | 100 | 0.552152 | cpuimage |
594b95d9e760360d5730d6b5af539b4652b058a9 | 12,235 | cpp | C++ | jaus_ros_bridge/src/fake_thruster.cpp | ChrisScianna/ROS-Underwater-RnD | f928bcc6b19a830b98e2cc2aedd65ff35b887901 | [
"BSD-3-Clause"
] | null | null | null | jaus_ros_bridge/src/fake_thruster.cpp | ChrisScianna/ROS-Underwater-RnD | f928bcc6b19a830b98e2cc2aedd65ff35b887901 | [
"BSD-3-Clause"
] | 85 | 2020-10-05T11:44:46.000Z | 2021-09-08T14:31:07.000Z | jaus_ros_bridge/src/fake_thruster.cpp | ChrisScianna/ROS-Underwater-RnD | f928bcc6b19a830b98e2cc2aedd65ff35b887901 | [
"BSD-3-Clause"
] | 1 | 2021-11-04T13:18:17.000Z | 2021-11-04T13:18:17.000Z | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2020, QinetiQ, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of QinetiQ nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
// Original version: Jie Sun <Jie.Sun@us.QinetiQ.com>
#include <thruster_control/ReportRPM.h>
#include <thruster_control/SetRPM.h>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <thruster_control/ReportMotorTemperature.h>
//#include <keller_4lc_pressure/Pressure.h>
//#include <keller_9lx_pressure/Pressure.h>
//#include <ixblue_c3_ins/C3Ins.h>
#include <health_monitor/ReportLeakDetected.h>
//#include <sea_scan_echo_sensor/ReportAltimeterRange.h>
#include <health_monitor/ReportBatteryInfo.h>
#include <pose_estimator/CorrectedData.h>
//#include <mission_control/ReportLoadMissionState.h>
//#include <mission_control/ReportExecuteMissionState.h>
class MessageHandler {
ros::NodeHandle* nodeHandle;
ros::Timer report_timer;
ros::Timer reportINS_timer;
ros::Publisher publisher_reportRPM;
ros::Publisher publisher_reportTemp;
ros::Publisher publisher_reportINS;
ros::Publisher publisher_reportPressureSensor;
ros::Publisher publisher_reportBatteryLeak;
ros::Publisher publisher_reportAltimeter;
ros::Publisher publisher_reportPoseData;
ros::Publisher publisher_reportBatteryInfo;
// ros::Publisher publisher_reportMissionState;
// ros::Publisher publisher_reportLoadState;
// ros::Publisher chatter_pub;
int _newRPM;
bool _changed = false;
int _engineTemp = -100;
int _batteryPosition = 0;
int _batteryStatus = 1; // Moving
float insData = -200.123456789;
bool leaked = false;
// called every 3 second
void reportINSSendTimeout(const ros::TimerEvent& timer) {
if (insData >= 200)
insData = -200.123456789;
else
insData = insData + 5;
// ixblue_c3_ins::C3Ins message;
// message.heading = insData/200;
// message.roll = insData/200;
// message.pitch = insData/200;
// message.north_speed = insData;
// message.east_speed = insData;
// message.vertical_speed = insData;
// message.latitude = insData;
// message.longitude = insData;
// message.altitude = insData;
// message.timestamp = (unsigned int) insData;//ros::Time::now();
// publisher_reportINS.publish(message);
// //ROS_INFO("Reported INS data from reportINSSendTimeout(). Data is %f", insData);
// keller_9lx_pressure::Pressure message1;
// message1.pressure = insData/200;
// message1.temperature = insData+2;
// publisher_reportPressureSensor.publish(message1);
// ROS_INFO("Reported Pressure data from reportINSSendTimeout(). Pressure is %d", insData);
// health_monitor::ReportLeakDetected message3;
// leaked = !leaked;
// //ROS_ERROR("leaked = %d", leaked);
// message3.leakDetected = (int8_t)leaked;
// publisher_reportBatteryLeak.publish(message3);
// sea_scan_echo_sensor/ReportAltimeterRange
// sea_scan_echo_sensor::ReportAltimeterRange message4;
// message4.UnfilteredRange = insData;
// publisher_reportAltimeter.publish(message4);
pose_estimator::CorrectedData message5;
// ROS_ERROR("pose_estimator::CorrectedData is published!!!");
message5.latitude = insData; // 123.456;
message5.longitude = -insData; //-123.456;
message5.depth = insData;
// message5.altitude = insData;
message5.speed = insData;
message5.rpy_ang[pose_estimator::CorrectedData::ROLL] = insData;
message5.rpy_ang[pose_estimator::CorrectedData::PITCH] = insData;
message5.rpy_ang[pose_estimator::CorrectedData::YAW] = insData;
publisher_reportPoseData.publish(message5);
// health_monitor::ReportBatteryInfo message6;
// message6.batteryPackAConnected = true;
// message6.batteryPacksTotalCurrent = 5.01;
// message6.batteryPackACell1 = 1.02;
// message6.batteryPackACell2 = 2.02;
// message6.batteryPackACell3 = 3.02;
// message6.batteryPackACell4 = 4.02;
// message6.batteryPackACell5 = 5.02;
// message6.batteryPackACell6 = 6.02;
// message6.batteryPackACell7 = 7.02;
// message6.batteryPackACell8 = 8.02;
// message6.batteryPackACell9 = 9.02;
// message6.batteryPackACell10 = 10.02;
// message6.batteryCell1Thermocouple = 11;
// message6.batteryCell2Thermocouple = 22;
// message6.batteryCell3Thermocouple = 33;
// message6.batteryCell4Thermocouple = 44;
// message6.batteryCell5Thermocouple = 55;
// message6.batteryCell6Thermocouple = 66;
// message6.batteryCell7Thermocouple = 77;
// message6.batteryCell8Thermocouple = 88;
// message6.systemThermocouple1 = 99;
// publisher_reportBatteryInfo.publish(message6);
// mission_control::ReportLoadMissionState message7;
// message7.stamp = ros::Time::now();
// message7.mission_id = 202;
// message7.load_state = 0; //successful
// publisher_reportLoadState.publish(message7);
// mission_control::ReportExecuteMissionState message8;
// message8.stamp = ros::Time::now();
// ROS_WARN("message8.stamp in second is: %f", message8.stamp.toSec());
// ROS_WARN("message8.stamp in mili second is: %f", message8.stamp.toSec()*1000);
// message8.mission_id = 101;
// message8.execute_mission_state = 4; //running
// publisher_reportMissionState.publish(message8);
// ROS_INFO("Report battery info message is published");
}
// called every 1 second
void reportRPMSendTimeout(const ros::TimerEvent& timer) {
thruster_control::ReportRPM message;
message.stamp = ros::Time::now();
_newRPM = _newRPM + 2;
message.rpms = _newRPM;
publisher_reportRPM.publish(message);
// ROS_INFO("Report RPM message: rpm [%f] is published back.", message.rpms);
thruster_control::ReportMotorTemperature message1;
message1.motor_temp = (int)_engineTemp;
if (_engineTemp >= 300)
_engineTemp = -100;
else
_engineTemp += 20;
publisher_reportTemp.publish(message1);
// ROS_INFO("Report motor temperature message: motor_temp [%f] is published back.",
// message1.motor_temp);
_changed = false;
}
public:
void SetNodeHangdle(ros::NodeHandle* n) {
nodeHandle = n;
// chatter_pub = nodeHandle->advertise<std_msgs::String>("fake_thruster_topic", 1000);
// repeat duration is set to 1 seconds
report_timer =
nodeHandle->createTimer(ros::Duration(2), &MessageHandler::reportRPMSendTimeout, this);
reportINS_timer =
nodeHandle->createTimer(ros::Duration(1), &MessageHandler::reportINSSendTimeout, this);
publisher_reportRPM =
nodeHandle->advertise<thruster_control::ReportRPM>("/thruster_control/report_rpm", 1);
publisher_reportTemp = nodeHandle->advertise<thruster_control::ReportMotorTemperature>(
"/thruster_control/report_motor_temp", 1);
// publisher_reportINS = nodeHandle->advertise<ixblue_c3_ins::C3Ins>("/ixblue_c3_ins/C3Ins", 1);
// publisher_reportPressureSensor =
// nodeHandle->advertise<keller_9lx_pressure::Pressure>("/pressure/data", 1);
// publisher_reportBatteryPosition =
// nodeHandle->advertise<health_monitor::ReportBatteryPosition>("/battery_position_control/report_battery_position",
// 1);
publisher_reportBatteryLeak = nodeHandle->advertise<health_monitor::ReportLeakDetected>(
"/health_monitor/report_leak_detected", 1);
// publisher_reportAltimeter =
// nodeHandle->advertise<sea_scan_echo_sensor::ReportAltimeterRange>("/sea_scan_echo_sensor/report_altimeter_range",
// 1);
publisher_reportPoseData =
nodeHandle->advertise<pose_estimator::CorrectedData>("/pose/corrected_data", 1);
publisher_reportBatteryInfo = nodeHandle->advertise<health_monitor::ReportBatteryInfo>(
"/health_monitor/report_battery_info", 1);
// publisher_reportLoadState =
// nodeHandle->advertise<mission_control::ReportLoadMissionState>("/mngr/report_mission_load_state",
// 1); publisher_reportMissionState =
// nodeHandle->advertise<mission_control::ReportExecuteMissionState>("/mngr/report_mission_execute_state",
// 1);
};
void chatterCallback(const std_msgs::String::ConstPtr& msg){
// ROS_INFO("I heard from bridge node: [%s]", msg->data.c_str());
// ros::Publisher chatter_pub = nodeHandle->advertise<std_msgs::String>("fake_thruster_topic",
// 1000); chatter_pub.publish(msg);
};
void handleSetRPM(const thruster_control::SetRPM::ConstPtr& msg) {
// ROS_ERROR("inside fake_thruster handleSetRPM(): rpm is [%f]", msg->commanded_rpms);
if ((int)msg->commanded_rpms != 0) {
// ROS_ERROR("newRPM is set to: [%d]", (int)msg->commanded_rpms);
_newRPM = (int)msg->commanded_rpms;
_changed = true;
}
// if(0){
// if(_changed == true && setRpmFinished == true)
// {
// ROS_INFO("reportRPMSendTimeout is called.");
// thruster_control::ReportRPM message;
// message.stamp = ros::Time::now();
// message.rpms = _newRPM;
// publisher_reportRPM.publish(message);
// ROS_INFO("Report RPM message: rpm [%f] is published back.", message.rpms);
// thruster_control::ReportMotorTemperature message1;
// message1.motor_temp = (int)_engineTemp;
// _engineTemp+= 20;
// if(_engineTemp >= 300)
// _engineTemp = 100;
// publisher_reportTemp.publish(message1);
// ROS_INFO("Report motor temperature message: motor_temp [%f] is published
// back.", message1.motor_temp); _changed = false;
// }
// }
};
};
int main(int argc, char** argv) {
MessageHandler msgHandler;
ros::init(argc, argv, "listener1");
ros::NodeHandle n;
msgHandler.SetNodeHangdle(&n);
ros::Subscriber sub =
n.subscribe("bridge_topic", 1, &MessageHandler::chatterCallback, &msgHandler);
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("fake_thruster_topic", 1);
ros::Subscriber thruster_set_rmp =
n.subscribe("/thruster_control/set_rpm", 1, &MessageHandler::handleSetRPM, &msgHandler);
ros::spin();
return 0;
}
| 41.757679 | 120 | 0.671189 | ChrisScianna |
594fec8ff494e02d6d6300f24c87593dff854d4d | 1,885 | cpp | C++ | 3-1.cpp | wuyudi/-Computer-Graphics | 228ef5e5db24c2af78ea8b5f68def47675895fd3 | [
"MIT"
] | null | null | null | 3-1.cpp | wuyudi/-Computer-Graphics | 228ef5e5db24c2af78ea8b5f68def47675895fd3 | [
"MIT"
] | null | null | null | 3-1.cpp | wuyudi/-Computer-Graphics | 228ef5e5db24c2af78ea8b5f68def47675895fd3 | [
"MIT"
] | null | null | null | //g++ -o 3-1 -Wall 3-1.cpp -mwindows glut32.lib -lopengl32 -lglu32
#include <windows.h>
#include <gl/glut.h>
//y1 在 GCC 里是内置函数,改名为 y3
int iPointNum = 0;
int x1 = 0, x2 = 0, y3 = 0, y2 = 0;
int winWidth = 400, winHeight = 300;
void Inital()
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
}
void ChangeSize(int w, int h)
{
winWidth = w;
winHeight = h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, winWidth, 0.0, winHeight);
}
void Display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 0.0f, 0.0f);
if (iPointNum >= 1)
{
glBegin(GL_LINES);
glVertex2i(x1, y3);
glVertex2i(x2, y2);
glEnd();
}
glutSwapBuffers();
}
void MousePlot(GLint button, GLint action, GLint xMouse, GLint yMouse)
{
if (button == GLUT_LEFT_BUTTON && action == GLUT_DOWN)
{
if (iPointNum == 0 || iPointNum == 2)
{
iPointNum = 1;
x1 = xMouse;
y3 = winHeight - yMouse;
}
else
{
iPointNum = 2;
x2 = xMouse;
y2 = winHeight - yMouse;
glutPostRedisplay();
}
}
if (button == GLUT_RIGHT_BUTTON && action == GLUT_DOWN)
{
iPointNum = 0;
glutPostRedisplay();
}
}
void PassiveMouseMove(GLint xMouse, GLint yMouse)
{
if (iPointNum == 1)
{
x2 = xMouse;
y2 = winHeight - yMouse;
glutPostRedisplay();
}
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(400, 300);
glutInitWindowPosition(100, 100);
glutCreateWindow("xpj");
glutDisplayFunc(Display);
glutReshapeFunc(ChangeSize);
glutMouseFunc(MousePlot);
glutPassiveMotionFunc(PassiveMouseMove);
Inital();
glutMainLoop();
return 0;
} | 22.987805 | 70 | 0.575066 | wuyudi |
59508a1ecb70d9ae1f395bafc9412e474711623a | 1,681 | cc | C++ | code30/cpp/20190821/v4/SocketIO.cc | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | 2 | 2020-12-09T09:55:51.000Z | 2021-01-08T11:38:22.000Z | mycode/cpp/0820/networklib/v4/SocketIO.cc | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | null | null | null | mycode/cpp/0820/networklib/v4/SocketIO.cc | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | null | null | null | ///
/// @file SocketIO.cc
/// @author lemon(haohb13@gmail.com)
/// @date 2019-05-07 16:01:31
///
#include "SocketIO.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
namespace wd
{
SocketIO::SocketIO(int fd)
: _fd(fd)
{}
int SocketIO::readn(char * buff, int len)
{
int left = len;
char * p = buff;
while(left > 0) {
int ret = ::read(_fd, p, left);
if(ret == -1 && errno == EINTR)
continue;
else if(ret == -1) {
perror("read");
return len - left;
}
else if(ret == 0) {
return len - left;
} else {
left -= ret;
p += ret;
}
}
return len - left;
}
//每一次读取一行数据
int SocketIO::readline(char * buff, int maxlen)
{
int left = maxlen - 1;
char * p = buff;
int ret;
int total = 0;
while(left > 0) {
ret = recvPeek(p, left);
//查找 '\n'
for(int idx = 0; idx != ret; ++idx) {
if(p[idx] == '\n') {
int sz = idx + 1;
readn(p, sz);
total += sz;
p += sz;
*p = '\0';
return total;
}
}
//如果没有发现 '\n'
readn(p, ret);
left -= ret;
p += ret;
total += ret;
}
*p = '\0';// 最终没有发现'\n'
return total;
}
int SocketIO::recvPeek(char * buff, int len)
{
int ret;
do {
ret = ::recv(_fd, buff, len, MSG_PEEK);
} while(ret == -1 && errno == EINTR);
return ret;
}
int SocketIO::writen(const char * buff, int len)
{
int left = len;
const char * p = buff;
while(left > 0) {
int ret = ::write(_fd, p, left);
if(ret == -1 && errno == EINTR)
continue;
else if(ret == -1) {
perror("write");
return len - left;
} else {
left -= ret;
p += ret;
}
}
return len - left;
}
}//end of namespace wd
| 15.858491 | 48 | 0.53599 | stdbilly |
596117c2455217dba06746689ab54862929054d2 | 3,665 | hxx | C++ | opencascade/IntPolyh_StartPoint.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | opencascade/IntPolyh_StartPoint.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 66 | 2019-12-20T16:07:36.000Z | 2022-03-15T21:56:10.000Z | opencascade/IntPolyh_StartPoint.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | // Created on: 1999-04-06
// Created by: Fabrice SERVANT
// Copyright (c) 1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IntPolyh_StartPoint_HeaderFile
#define _IntPolyh_StartPoint_HeaderFile
#include <Standard.hxx>
class IntPolyh_Triangle;
class IntPolyh_StartPoint
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT IntPolyh_StartPoint();
Standard_EXPORT IntPolyh_StartPoint(const Standard_Real xx, const Standard_Real yy, const Standard_Real zz, const Standard_Real uu1, const Standard_Real vv1, const Standard_Real uu2, const Standard_Real vv2, const Standard_Integer T1, const Standard_Integer E1, const Standard_Real LAM1, const Standard_Integer T2, const Standard_Integer E2, const Standard_Real LAM2, const Standard_Integer List);
Standard_EXPORT Standard_Real X() const;
Standard_EXPORT Standard_Real Y() const;
Standard_EXPORT Standard_Real Z() const;
Standard_EXPORT Standard_Real U1() const;
Standard_EXPORT Standard_Real V1() const;
Standard_EXPORT Standard_Real U2() const;
Standard_EXPORT Standard_Real V2() const;
Standard_EXPORT Standard_Integer T1() const;
Standard_EXPORT Standard_Integer E1() const;
Standard_EXPORT Standard_Real Lambda1() const;
Standard_EXPORT Standard_Integer T2() const;
Standard_EXPORT Standard_Integer E2() const;
Standard_EXPORT Standard_Real Lambda2() const;
Standard_EXPORT Standard_Real GetAngle() const;
Standard_EXPORT Standard_Integer ChainList() const;
Standard_EXPORT Standard_Integer GetEdgePoints (const IntPolyh_Triangle& Triangle, Standard_Integer& FirstEdgePoint, Standard_Integer& SecondEdgePoint, Standard_Integer& LastPoint) const;
Standard_EXPORT void SetXYZ (const Standard_Real XX, const Standard_Real YY, const Standard_Real ZZ);
Standard_EXPORT void SetUV1 (const Standard_Real UU1, const Standard_Real VV1);
Standard_EXPORT void SetUV2 (const Standard_Real UU2, const Standard_Real VV2);
Standard_EXPORT void SetEdge1 (const Standard_Integer IE1);
Standard_EXPORT void SetLambda1 (const Standard_Real LAM1);
Standard_EXPORT void SetEdge2 (const Standard_Integer IE2);
Standard_EXPORT void SetLambda2 (const Standard_Real LAM2);
Standard_EXPORT void SetCoupleValue (const Standard_Integer IT1, const Standard_Integer IT2);
Standard_EXPORT void SetAngle (const Standard_Real ang);
Standard_EXPORT void SetChainList (const Standard_Integer ChList);
Standard_EXPORT Standard_Integer CheckSameSP (const IntPolyh_StartPoint& SP) const;
Standard_EXPORT void Dump() const;
Standard_EXPORT void Dump (const Standard_Integer i) const;
private:
Standard_Real x;
Standard_Real y;
Standard_Real z;
Standard_Real u1;
Standard_Real v1;
Standard_Real u2;
Standard_Real v2;
Standard_Real lambda1;
Standard_Real lambda2;
Standard_Real angle;
Standard_Integer t1;
Standard_Integer e1;
Standard_Integer t2;
Standard_Integer e2;
Standard_Integer chainlist;
};
#endif // _IntPolyh_StartPoint_HeaderFile
| 32.723214 | 399 | 0.789359 | valgur |
596181d08ef5a2ebddb46833dd05ef4b0ae3a3b2 | 2,757 | cpp | C++ | questions/threads-18369174/main.cpp | SammyEnigma/stackoverflown | 0f70f2534918b2e65cec1046699573091d9a40b5 | [
"Unlicense"
] | 54 | 2015-09-13T07:29:52.000Z | 2022-03-16T07:43:50.000Z | questions/threads-18369174/main.cpp | SammyEnigma/stackoverflown | 0f70f2534918b2e65cec1046699573091d9a40b5 | [
"Unlicense"
] | null | null | null | questions/threads-18369174/main.cpp | SammyEnigma/stackoverflown | 0f70f2534918b2e65cec1046699573091d9a40b5 | [
"Unlicense"
] | 31 | 2016-08-26T13:35:01.000Z | 2022-03-13T16:43:12.000Z | // main.cpp
#include <QCoreApplication>
#include <QObjectList>
#include <QList>
#include <QThread>
#include <iostream>
const int cycleCount = 500; //!< number of cycles to run at, set to 0 to run forever
const int threadCount = 5; //!< number of threads to create
class Object : public QObject
{
Q_OBJECT
int m_threadNumber;
int m_delayUs;
volatile bool m_active;
public:
explicit Object(int delayUs, int no) : m_threadNumber(no), m_delayUs(delayUs) {}
Q_SIGNAL void indexReady(int);
Q_SLOT void stop() { m_active = false; }
Q_SLOT void start()
{
m_active = true;
while (m_active) {
usleep(m_delayUs);
emit indexReady(m_threadNumber);
}
}
};
class Consumer : public QObject
{
Q_OBJECT
QList<Object*> m_objects;
QList<QThread*> m_threads;
int m_threadCount; //!< number of active threads in m_threads
int m_count;
public:
Consumer() : m_count(0) {}
void addObject(Object * o) { m_objects << o; }
void addThread(QThread * t) {
m_threads << t;
m_threadCount ++;
connect(t, SIGNAL(finished()), SLOT(done()));
connect(t, SIGNAL(terminated()), SLOT(done()));
}
Q_SLOT void ready(int n) {
std::cout << "<" << m_count++ << ":" << n << ">" << std::endl;
if (m_count == cycleCount) {
foreach (Object * o, m_objects) o->stop();
foreach (QThread * t, m_threads) t->wait();
}
}
Q_SLOT void done() {
QThread * t = qobject_cast<QThread*>(sender());
int i = m_threads.indexOf(t);
if (t) t->deleteLater();
if (i>=0) {
std::cout << "Thread " << i << " is done." << std::endl;
m_threadCount --;
}
if (! m_threadCount) qApp->quit();
}
};
int main(int argc, char *argv[])
{
Consumer c;
QObjectList l;
QCoreApplication a(argc, argv);
std::cout << "Running under Qt version " << qVersion() << std::endl;
for (int i = 0; i < threadCount; ++i) {
Object * o = new Object(10000 + 5000*i, i+1);
QThread * t = new QThread;
c.addObject(o);
c.addThread(t);
o->moveToThread(t);
o->connect(t, SIGNAL(started()), SLOT(start()));
c.connect(o, SIGNAL(indexReady(int)), SLOT(ready(int)));
t->start();
t->exit();
l << o;
}
return a.exec();
}
#include "main.moc"
| 31.329545 | 88 | 0.491839 | SammyEnigma |
59628f001d2d6570df31489ca32702486fd303b5 | 3,813 | cpp | C++ | src/plugProjectOgawaU/ogCallBackScreen.cpp | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 33 | 2021-12-08T11:10:59.000Z | 2022-03-26T19:59:37.000Z | src/plugProjectOgawaU/ogCallBackScreen.cpp | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 6 | 2021-12-22T17:54:31.000Z | 2022-01-07T21:43:18.000Z | src/plugProjectOgawaU/ogCallBackScreen.cpp | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 2 | 2022-01-04T06:00:49.000Z | 2022-01-26T07:27:28.000Z | #include "types.h"
#include "og/Screen/callbackNodes.h"
/*
Generated from dpostproc
.section .data, "wa" # 0x8049E220 - 0x804EFC20
.global __vt__Q32og6Screen15CallBack_Screen
__vt__Q32og6Screen15CallBack_Screen:
.4byte 0
.4byte 0
.4byte __dt__Q32og6Screen15CallBack_ScreenFv
.4byte getChildCount__5CNodeFv
.4byte update__Q32og6Screen15CallBack_ScreenFv
.4byte draw__Q32og6Screen15CallBack_ScreenFR8GraphicsR14J2DGrafContext
.4byte doInit__Q29P2DScreen4NodeFv
.4byte 0
.section .sdata2, "a" # 0x80516360 - 0x80520E40
.global lbl_8051D698
lbl_8051D698:
.float 1.0
.global lbl_8051D69C
lbl_8051D69C:
.4byte 0x00000000
*/
namespace og {
namespace Screen {
/*
* --INFO--
* Address: 8030B370
* Size: 0000A4
*/
CallBack_Screen::CallBack_Screen(P2DScreen::Mgr*, unsigned long long)
{
/*
stwu r1, -0x20(r1)
mflr r0
stw r0, 0x24(r1)
stmw r27, 0xc(r1)
mr r27, r3
mr r0, r27
mr r29, r4
mr r31, r5
mr r30, r6
mr r28, r0
bl __ct__5CNodeFv
lis r3, __vt__Q29P2DScreen4Node@ha
lis r4, __vt__Q29P2DScreen12CallBackNode@ha
addi r0, r3, __vt__Q29P2DScreen4Node@l
lis r3, __vt__Q32og6Screen15CallBack_Screen@ha
stw r0, 0(r28)
li r5, 0
addi r4, r4, __vt__Q29P2DScreen12CallBackNode@l
addi r0, r3, __vt__Q32og6Screen15CallBack_Screen@l
stw r5, 0x18(r28)
mr r6, r30
mr r5, r31
stw r4, 0(r28)
stw r0, 0(r27)
stw r29, 0x1c(r27)
lwz r3, 0x1c(r27)
bl TagSearch__Q22og6ScreenFP9J2DScreenUx
stw r3, 0x20(r27)
li r0, 0
lfs f1, lbl_8051D698@sda21(r2)
mr r3, r27
stw r0, 0x24(r27)
lfs f0, lbl_8051D69C@sda21(r2)
stfs f1, 0x28(r27)
stfs f0, 0x2c(r27)
stfs f0, 0x30(r27)
lmw r27, 0xc(r1)
lwz r0, 0x24(r1)
mtlr r0
addi r1, r1, 0x20
blr
*/
}
/*
* --INFO--
* Address: 8030B414
* Size: 000008
*/
J2DScreen* CallBack_Screen::getPartsScreen(void) { return m_partsScreen; }
/*
* --INFO--
* Address: ........
* Size: 000044
*/
void CallBack_Screen::changeScreen(P2DScreen::Mgr*, unsigned long long)
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: 8030B41C
* Size: 000038
*/
void CallBack_Screen::update(void)
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
lwz r3, 0x1c(r3)
cmplwi r3, 0
beq lbl_8030B444
lwz r12, 0(r3)
lwz r12, 0x30(r12)
mtctr r12
bctrl
lbl_8030B444:
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8030B454
* Size: 0000D0
*/
void CallBack_Screen::draw(Graphics&, J2DGrafContext&)
{
/*
stwu r1, -0x80(r1)
mflr r0
stw r0, 0x84(r1)
stw r31, 0x7c(r1)
stw r30, 0x78(r1)
mr r30, r5
stw r29, 0x74(r1)
mr r29, r4
stw r28, 0x70(r1)
mr r28, r3
lwz r0, 0x1c(r3)
cmplwi r0, 0
beq lbl_8030B504
lfs f1, 0x28(r28)
addi r3, r1, 0x38
lwz r4, 0x24(r28)
fmr f2, f1
lfs f3, lbl_8051D69C@sda21(r2)
addi r31, r4, 0x80
bl PSMTXScale
addi r4, r1, 0x38
mr r3, r31
mr r5, r4
bl PSMTXConcat
lfs f1, 0x2c(r28)
addi r3, r1, 8
lfs f2, 0x30(r28)
lfs f3, lbl_8051D69C@sda21(r2)
bl PSMTXTrans
mr r5, r31
addi r3, r1, 0x38
addi r4, r1, 8
bl PSMTXConcat
lwz r4, 0x20(r28)
mr r3, r31
addi r4, r4, 0x50
bl PSMTXCopy
lwz r3, 0x1c(r28)
mr r4, r29
mr r5, r30
lwz r12, 0(r3)
lwz r12, 0x9c(r12)
mtctr r12
bctrl
lbl_8030B504:
lwz r0, 0x84(r1)
lwz r31, 0x7c(r1)
lwz r30, 0x78(r1)
lwz r29, 0x74(r1)
lwz r28, 0x70(r1)
mtlr r0
addi r1, r1, 0x80
blr
*/
}
} // namespace Screen
} // namespace og
| 19.654639 | 78 | 0.603724 | projectPiki |
5963f24acd88fe3ba388ed949339e130ebe68fb1 | 535 | cpp | C++ | Week-4/Day-24-bagOfTokensScore.cpp | utkarshavardhana/october-leetcoding-challenge | f2303421ee02539141a1bb78840e03a669ee6e2b | [
"MIT"
] | null | null | null | Week-4/Day-24-bagOfTokensScore.cpp | utkarshavardhana/october-leetcoding-challenge | f2303421ee02539141a1bb78840e03a669ee6e2b | [
"MIT"
] | null | null | null | Week-4/Day-24-bagOfTokensScore.cpp | utkarshavardhana/october-leetcoding-challenge | f2303421ee02539141a1bb78840e03a669ee6e2b | [
"MIT"
] | null | null | null | class Solution {
public:
int bagOfTokensScore(vector<int>& tokens, int P) {
sort(tokens.begin(), tokens.end());
int res = 0, points = 0, i = 0, j = tokens.size() - 1;
while (i <= j) {
if (P >= tokens[i]) {
P -= tokens[i++];
res = max(res, ++points);
} else if (points > 0) {
points--;
P += tokens[j--];
} else {
break;
}
}
return res;
}
};
| 26.75 | 63 | 0.362617 | utkarshavardhana |
5966da95d284eb4206a6b9e4d320bc2a1735c3f5 | 6,818 | cpp | C++ | bullet-2.81-rev2613/src/BulletFluids/Hf/btFluidHfBuoyantConvexShape.cpp | rtrius/Bullet-FLUIDS | b58dbc5108512e5a4bb0a532284a98128fd8f8ce | [
"Zlib"
] | 19 | 2015-01-18T09:34:48.000Z | 2021-07-22T08:00:17.000Z | bullet-2.81-rev2613/src/BulletFluids/Hf/btFluidHfBuoyantConvexShape.cpp | rtrius/Bullet-FLUIDS | b58dbc5108512e5a4bb0a532284a98128fd8f8ce | [
"Zlib"
] | null | null | null | bullet-2.81-rev2613/src/BulletFluids/Hf/btFluidHfBuoyantConvexShape.cpp | rtrius/Bullet-FLUIDS | b58dbc5108512e5a4bb0a532284a98128fd8f8ce | [
"Zlib"
] | 8 | 2015-02-09T08:03:04.000Z | 2021-07-22T08:01:54.000Z | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Experimental Buoyancy fluid demo written by John McCutchan
*/
//This is an altered source version based on the HeightFieldFluidDemo included with Bullet Physics 2.80(bullet-2.80-rev2531).
#include "btFluidHfBuoyantConvexShape.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
btFluidHfBuoyantConvexShape::btFluidHfBuoyantConvexShape (btConvexShape* convexShape)
{
m_convexShape = convexShape;
m_shapeType = HFFLUID_BUOYANT_CONVEX_SHAPE_PROXYTYPE;
m_collisionRadius = btScalar(0.0);
m_totalVolume = btScalar(0.0);
m_useFluidDensity = false;
m_buoyancyScale = btScalar(1.0);
}
//must be above the machine epsilon
#define REL_ERROR2 btScalar(1.0e-6)
static bool intersect(btVoronoiSimplexSolver* simplexSolver,
const btTransform& transformA,
const btTransform& transformB,
btConvexShape* a,
btConvexShape* b)
{
btScalar squaredDistance = SIMD_INFINITY;
btTransform localTransA = transformA;
btTransform localTransB = transformB;
btVector3 positionOffset = (localTransA.getOrigin() + localTransB.getOrigin()) * btScalar(0.5);
localTransA.getOrigin() -= positionOffset;
localTransB.getOrigin() -= positionOffset;
btScalar delta = btScalar(0.);
btVector3 v = btVector3(1.0f, 0.0f, 0.0f);
simplexSolver->reset ();
do
{
btVector3 seperatingAxisInA = (-v)* transformA.getBasis();
btVector3 seperatingAxisInB = v* transformB.getBasis();
btVector3 pInA = a->localGetSupportVertexNonVirtual(seperatingAxisInA);
btVector3 qInB = b->localGetSupportVertexNonVirtual(seperatingAxisInB);
btVector3 pWorld = localTransA(pInA);
btVector3 qWorld = localTransB(qInB);
btVector3 w = pWorld - qWorld;
delta = v.dot(w);
// potential exit, they don't overlap
if ((delta > btScalar(0.0)))
{
return false;
}
if (simplexSolver->inSimplex (w))
{
return false;
}
simplexSolver->addVertex (w, pWorld, qWorld);
if (!simplexSolver->closest(v))
{
return false;
}
btScalar previousSquaredDistance = squaredDistance;
squaredDistance = v.length2();
if (previousSquaredDistance - squaredDistance <= SIMD_EPSILON * previousSquaredDistance)
{
return false;
}
}
while (!simplexSolver->fullSimplex() && squaredDistance > REL_ERROR2 * simplexSolver->maxVertex());
return true;
}
void btFluidHfBuoyantConvexShape::generateShape(btScalar collisionRadius, btScalar volumeEstimationRadius)
{
m_voxelPositions.resize(0);
btVoronoiSimplexSolver simplexSolver;
btTransform voxelTransform = btTransform::getIdentity();
btVector3 aabbMin, aabbMax;
getAabb( btTransform::getIdentity(), aabbMin, aabbMax ); //AABB of the convex shape
//Generate voxels for collision
{
btSphereShape collisionShape(collisionRadius);
const btScalar collisionDiameter = btScalar(2.0) * collisionRadius;
btVector3 numVoxels = (aabbMax - aabbMin) / collisionDiameter;
for(int i = 0; i < ceil( numVoxels.x() ); i++)
{
for(int j = 0; j < ceil( numVoxels.y() ); j++)
{
for(int k = 0; k < ceil( numVoxels.z() ); k++)
{
btVector3 voxelPosition = aabbMin + btVector3(i * collisionDiameter, j * collisionDiameter, k * collisionDiameter);
voxelTransform.setOrigin(voxelPosition);
if( intersect(&simplexSolver, btTransform::getIdentity(), voxelTransform, m_convexShape, &collisionShape) )
m_voxelPositions.push_back(voxelPosition);
}
}
}
const bool CENTER_VOXELS_AABB_ON_ORIGIN = true;
if(CENTER_VOXELS_AABB_ON_ORIGIN)
{
btVector3 diameter(collisionDiameter, collisionDiameter, collisionDiameter);
btVector3 voxelAabbMin(BT_LARGE_FLOAT, BT_LARGE_FLOAT, BT_LARGE_FLOAT);
btVector3 voxelAabbMax(-BT_LARGE_FLOAT, -BT_LARGE_FLOAT, -BT_LARGE_FLOAT);
for(int i = 0; i < m_voxelPositions.size(); ++i)
{
voxelAabbMin.setMin(m_voxelPositions[i] - diameter);
voxelAabbMax.setMax(m_voxelPositions[i] + diameter);
}
btVector3 offset = (voxelAabbMax - voxelAabbMin)*btScalar(0.5) - voxelAabbMax;
for(int i = 0; i < m_voxelPositions.size(); ++i) m_voxelPositions[i] += offset;
}
}
//Estimate volume with smaller spheres
btScalar estimatedVolume;
{
btSphereShape volumeEstimationShape(volumeEstimationRadius);
int numCollidingVoxels = 0;
const btScalar estimationDiameter = btScalar(2.0) * volumeEstimationRadius;
btVector3 numEstimationVoxels = (aabbMax - aabbMin) / estimationDiameter;
for(int i = 0; i < ceil( numEstimationVoxels.x() ); i++)
{
for(int j = 0; j < ceil( numEstimationVoxels.y() ); j++)
{
for(int k = 0; k < ceil( numEstimationVoxels.z() ); k++)
{
btVector3 voxelPosition = aabbMin + btVector3(i * estimationDiameter, j * estimationDiameter, k * estimationDiameter);
voxelTransform.setOrigin(voxelPosition);
if( intersect(&simplexSolver, btTransform::getIdentity(), voxelTransform, m_convexShape, &volumeEstimationShape) )
++numCollidingVoxels;
}
}
}
//Although the voxels are spherical, it is better to use the volume of a cube
//for volume estimation. Since convex shapes are completely solid and the voxels
//are generated by moving along a cubic lattice, using the volume of a sphere
//would result in gaps. Comparing the volume of a cube with edge length 2(8 m^3)
//and the volume of a sphere with diameter 2(~4 m^3), the estimated volume would
//be off by about 1/2.
btScalar volumePerEstimationVoxel = btPow( estimationDiameter, btScalar(3.0) );
//btScalar volumePerEstimationVoxel = btScalar(4.0/3.0) * SIMD_PI * btPow( volumeEstimationRadius, btScalar(3.0) );
estimatedVolume = static_cast<btScalar>(numCollidingVoxels) * volumePerEstimationVoxel;
}
m_volumePerVoxel = estimatedVolume / static_cast<btScalar>( getNumVoxels() );
m_totalVolume = estimatedVolume;
m_collisionRadius = collisionRadius;
}
| 35.326425 | 243 | 0.74318 | rtrius |
5967d5ed66f583f9d40666f5e47c58d595999e24 | 2,264 | hpp | C++ | include/poike/core/CommandBuffers.hpp | florianvazelle/poike | 2ff7313c994b888dd83e22a0a9703c08b4a3a361 | [
"MIT"
] | null | null | null | include/poike/core/CommandBuffers.hpp | florianvazelle/poike | 2ff7313c994b888dd83e22a0a9703c08b4a3a361 | [
"MIT"
] | null | null | null | include/poike/core/CommandBuffers.hpp | florianvazelle/poike | 2ff7313c994b888dd83e22a0a9703c08b4a3a361 | [
"MIT"
] | null | null | null | /**
* @file CommandBuffers.hpp
* @brief Define CommandBuffers base class
*/
#ifndef COMMANDBUFFERS_HPP
#define COMMANDBUFFERS_HPP
#include <poike/core/CommandPool.hpp>
#include <poike/core/DescriptorSets.hpp>
#include <poike/core/Device.hpp>
#include <poike/core/GraphicsPipeline.hpp>
#include <poike/meta/NoCopy.hpp>
#include <poike/core/RenderPass.hpp>
#include <poike/core/SwapChain.hpp>
#include <poike/core/VulkanHeader.hpp>
#include <functional>
#include <vector>
namespace poike {
class CommandBuffersBase : public NoCopy {
public:
CommandBuffersBase(const Device& device,
const RenderPass& renderpass,
const SwapChain& swapChain,
const GraphicsPipeline& graphicsPipeline,
const CommandPool& commandPool);
~CommandBuffersBase();
inline VkCommandBuffer& command(uint32_t index) { return m_commandBuffers[index]; }
inline const VkCommandBuffer& command(uint32_t index) const { return m_commandBuffers[index]; }
protected:
std::vector<VkCommandBuffer> m_commandBuffers;
const Device& m_device;
const RenderPass& m_renderPass;
const SwapChain& m_swapChain;
const GraphicsPipeline& m_graphicsPipeline;
const CommandPool& m_commandPool;
void destroyCommandBuffers();
};
class CommandBuffers : public CommandBuffersBase {
public:
CommandBuffers(const Device& device,
const RenderPass& renderpass,
const SwapChain& swapChain,
const GraphicsPipeline& graphicsPipeline,
const CommandPool& commandPool,
const DescriptorSets& descriptorSets,
const std::vector<const IBuffer*>& buffers);
void recreate();
static void SingleTimeCommands(const Device& device,
const CommandPool& cmdPool,
const VkQueue& queue,
const std::function<void(const VkCommandBuffer&)>& func);
protected:
const DescriptorSets& m_descriptorSets;
const std::vector<const IBuffer*>& m_buffers;
virtual void createCommandBuffers() = 0;
};
} // namespace poike
#endif // COMMANDBUFFERS_HPP
| 31.887324 | 99 | 0.660336 | florianvazelle |
5969418dbac4ccf9e9ecabcd8be076aaf0932974 | 3,380 | hpp | C++ | src/Engine/Drawables/Light/QuadLight.hpp | DaftMat/Daft-Engine | e3d918b4b876d17abd889b9b6b13bd858a079538 | [
"MIT"
] | 1 | 2020-10-26T02:36:58.000Z | 2020-10-26T02:36:58.000Z | src/Engine/Drawables/Light/QuadLight.hpp | DaftMat/Daft-Engine | e3d918b4b876d17abd889b9b6b13bd858a079538 | [
"MIT"
] | 6 | 2020-02-14T21:45:52.000Z | 2020-09-23T17:58:58.000Z | src/Engine/Drawables/Light/QuadLight.hpp | DaftMat/Daft-Engine | e3d918b4b876d17abd889b9b6b13bd858a079538 | [
"MIT"
] | null | null | null | //
// Created by mathis on 28/11/2020.
//
#pragma once
#include <API.hpp>
#include "Light.hpp"
namespace daft::engine {
class ENGINE_API QuadLight : public Light {
public:
/**
* Default/standard constructor.
* @param mesh - line mesh that represents the light.
* @param color - color emitted by the light.
*/
explicit QuadLight(glm::vec3 position = glm::vec3{0.f}, glm::vec3 xdir = {1.f, 0.f, 0.f},
glm::vec3 ydir = {0.f, 1.f, 0.f}, glm::vec2 size = {1.f, 1.f}, glm::vec3 color = glm::vec3{1.f},
float intensity = 1.f, Composite *parent = nullptr,
std::string name = "QuadLight" + std::to_string(m_nrQuadLight++))
: Light{color, parent, std::move(name)},
m_posBase{position},
m_xDir{xdir},
m_yDir{ydir},
m_xDirBase{xdir},
m_yDirBase{ydir},
m_width{size.x},
m_height{size.y},
m_intensity{intensity} {
this->position() = position;
m_isAreaLight = true;
createQuadLight();
}
/**
* Destructor.
*/
~QuadLight() override = default;
/**
* Default move constructor.
*/
QuadLight(QuadLight &&) noexcept = default;
/**
* Default move assignment operator.
* @return ref to this.
*/
QuadLight &operator=(QuadLight &&) noexcept = default;
void render(const core::ShaderProgram &shader) override;
/**
* Gets the quad light's specific settings as a SettingManager .
* @return settings.
*/
[[nodiscard]] core::SettingManager getSettings() const override;
/**
* Settings setter using a SettingManager .
* @param s - settings.
*/
void setSettings(const core::SettingManager &s) override;
/**
* Transformations setter using a SettingManager .
* @param t - transformations.
*/
void setTransformations(const core::SettingManager &t) override;
float width() const { return m_width; }
void setWidth(float w);
float height() const { return m_height; }
void setHeight(float h);
/**
* Intensity getter.
* @return intensity.
*/
[[nodiscard]] float intensity() const { return m_intensity; }
/**
* Intensity ref getter.
* @return ref to intensity.
*/
float &intensity() { return m_intensity; }
/**
* Loads this light to a target shader as a uniform struct.
* @param shader - shader to load the light to.
* @param index - index of the light in its list.
*/
void loadToShader(const core::ShaderProgram &shader, int index) const override;
/**
* Accepts a DrawableVisitor.
* @param visitor - visitor.
*/
void accept(DrawableVisitor *visitor) override;
/**
* Gets the type of drawable.
* @return Type::PointLight .
*/
Type getType() const override { return Type::QuadLight; }
void update() override { createQuadLight(); }
private:
std::vector<glm::vec3> points() const;
std::vector<glm::vec3> transformedPoints() const;
void createQuadLight();
glm::vec3 m_posBase;
glm::vec3 m_xDir;
glm::vec3 m_yDir;
glm::vec3 m_xDirBase;
glm::vec3 m_yDirBase;
float m_width;
float m_height;
float m_intensity;
static int m_nrQuadLight;
};
} // namespace daft::engine | 26.20155 | 119 | 0.596154 | DaftMat |
5969c9ba2cccb63ef5754687545e6ff6acd0c737 | 106,008 | cpp | C++ | coreLibrary_300/source/meshUtil/dgMeshEffect1.cpp | wivlaro/newton-dynamics | 2bafd29aea919f237e56784510db1cb8011d0f40 | [
"Zlib"
] | null | null | null | coreLibrary_300/source/meshUtil/dgMeshEffect1.cpp | wivlaro/newton-dynamics | 2bafd29aea919f237e56784510db1cb8011d0f40 | [
"Zlib"
] | null | null | null | coreLibrary_300/source/meshUtil/dgMeshEffect1.cpp | wivlaro/newton-dynamics | 2bafd29aea919f237e56784510db1cb8011d0f40 | [
"Zlib"
] | null | null | null | /* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "dgPhysicsStdafx.h"
#include "dgBody.h"
#include "dgWorld.h"
#include "dgMeshEffect.h"
#include "dgCollisionBVH.h"
#include "dgCollisionCompound.h"
#include "dgCollisionConvexHull.h"
dgMeshEffect::dgMeshBVH::dgFitnessList::dgFitnessList (dgMemoryAllocator* const allocator)
:dgTree <dgMeshBVHNode*, dgMeshBVHNode*>(allocator)
{
}
dgFloat64 dgMeshEffect::dgMeshBVH::dgFitnessList::TotalCost () const
{
dgFloat64 cost = dgFloat32 (0.0f);
Iterator iter (*this);
for (iter.Begin(); iter; iter ++) {
dgTreeNode* const node = iter.GetNode();
dgMeshBVHNode* const box = node->GetInfo();
cost += box->m_area;
}
return cost;
}
dgMeshEffect::dgMeshBVH::dgMeshBVHNode::dgMeshBVHNode (const dgMeshEffect* const mesh, dgEdge* const face, void* const userData)
:m_area(dgFloat32 (0.0f))
,m_face (face)
,m_userData(userData)
,m_left (NULL)
,m_right(NULL)
,m_parent(NULL)
{
dgBigVector p0(1.0e30, 1.0e30, 1.0e30, 0.0);
dgBigVector p1(-1.0e30, -1.0e30, -1.0e30, 0.0);
const dgBigVector* const points = (dgBigVector*) mesh->GetVertexPool();
dgEdge* ptr = m_face;
do {
dgInt32 i = ptr->m_incidentVertex;
const dgBigVector& p = points[i];
p0.m_x = dgMin(p.m_x, p0.m_x);
p0.m_y = dgMin(p.m_y, p0.m_y);
p0.m_z = dgMin(p.m_z, p0.m_z);
p1.m_x = dgMax(p.m_x, p1.m_x);
p1.m_y = dgMax(p.m_y, p1.m_y);
p1.m_z = dgMax(p.m_z, p1.m_z);
ptr = ptr->m_next;
} while (ptr != face);
SetBox (dgVector (dgFloat32 (p0.m_x) - dgFloat32 (0.1f), dgFloat32 (p0.m_y) - dgFloat32 (0.1f), dgFloat32 (p0.m_z) - dgFloat32 (0.1f), 0.0f),
dgVector (dgFloat32 (p1.m_x) + dgFloat32 (0.1f), dgFloat32 (p1.m_y) + dgFloat32 (0.1f), dgFloat32 (p1.m_z) + dgFloat32 (0.1f), 0.0f));
}
dgMeshEffect::dgMeshBVH::dgMeshBVHNode::dgMeshBVHNode (dgMeshBVHNode* const left, dgMeshBVHNode* const right)
:m_area(dgFloat32 (0.0f))
,m_face (NULL)
,m_userData(NULL)
,m_left (left)
,m_right(right)
,m_parent(NULL)
{
m_left->m_parent = this;
m_right->m_parent = this;
dgVector p0 (dgMin (left->m_p0.m_x, right->m_p0.m_x), dgMin (left->m_p0.m_y, right->m_p0.m_y), dgMin (left->m_p0.m_z, right->m_p0.m_z), dgFloat32 (0.0f));
dgVector p1 (dgMax (left->m_p1.m_x, right->m_p1.m_x), dgMax (left->m_p1.m_y, right->m_p1.m_y), dgMax (left->m_p1.m_z, right->m_p1.m_z), dgFloat32 (0.0f));
SetBox(p0, p1);
}
dgMeshEffect::dgMeshBVH::dgMeshBVHNode::~dgMeshBVHNode ()
{
if (m_left) {
delete m_left;
}
if (m_right) {
delete m_right;
}
}
void dgMeshEffect::dgMeshBVH::dgMeshBVHNode::SetBox (const dgVector& p0, const dgVector& p1)
{
m_p0 = p0;
m_p1 = p1;
m_p0.m_w = 0.0f;
m_p1.m_w = 0.0f;
dgVector size ((m_p1 - m_p0).Scale3 (dgFloat32 (0.5f)));
dgVector size1(size.m_y, size.m_z, size.m_x, dgFloat32 (0.0f));
m_area = size % size1;
}
dgMeshEffect::dgMeshBVH::dgMeshBVH (dgMeshEffect* const mesh)
:m_mesh(mesh)
,m_rootNode(NULL)
,m_fitness(m_mesh->GetAllocator())
{
}
dgMeshEffect::dgMeshBVH::~dgMeshBVH()
{
Cleanup ();
}
dgMeshEffect* dgMeshEffect::CreateFromSerialization (dgMemoryAllocator* const allocator, dgDeserialize deserialization, void* const userData)
{
return new (allocator) dgMeshEffect(allocator, deserialization, userData);
}
void dgMeshEffect::Serialize (dgSerialize callback, void* const userData) const
{
dgInt32 faceCount = 0;
dgTree<dgEdge*, dgEdge*>filter(GetAllocator());
Iterator iter (*this);
for (iter.Begin(); iter; iter ++) {
dgEdge* const face = &iter.GetNode()->GetInfo();
if (!filter.Find(face) && (face->m_incidentFace > 0)) {
faceCount ++;
dgEdge* edge = face;
do {
filter.Insert(edge, edge);
edge = edge->m_next;
} while (edge != face);
}
}
callback (userData, &faceCount, sizeof (dgInt32));
callback (userData, &m_pointCount, sizeof (dgInt32));
callback (userData, &m_atribCount, sizeof (dgInt32));
callback (userData, &m_atribCount, sizeof (dgInt32));
callback (userData, m_points, m_pointCount * sizeof (dgBigVector));
callback (userData, m_attrib, m_atribCount * sizeof (dgVertexAtribute));
filter.RemoveAll();
for (iter.Begin(); iter; iter ++) {
dgEdge* const face = &iter.GetNode()->GetInfo();
if (!filter.Find(face) && (face->m_incidentFace > 0)) {
dgInt32 indices[1024];
dgInt64 attibuteIndex[1024];
dgInt32 vertexCount = 0;
dgEdge* edge = face;
do {
indices[vertexCount] = edge->m_incidentVertex;
attibuteIndex[vertexCount] = edge->m_userData;
vertexCount ++;
filter.Insert(edge, edge);
edge = edge->m_next;
} while (edge != face);
callback (userData, &vertexCount, sizeof (dgInt32));
callback (userData, indices, vertexCount * sizeof (dgInt32));
callback (userData, attibuteIndex, vertexCount * sizeof (dgInt64));
}
}
}
void dgMeshEffect::dgMeshBVH::Build ()
{
for (void* faceNode = m_mesh->GetFirstFace (); faceNode; faceNode = m_mesh->GetNextFace(faceNode)) {
if (!m_mesh->IsFaceOpen(faceNode)) {
dgEdge* const face = &((dgTreeNode*)faceNode)->GetInfo();
AddFaceNode(face, NULL);
}
}
ImproveNodeFitness ();
}
void dgMeshEffect::dgMeshBVH::Cleanup ()
{
if (m_rootNode) {
delete m_rootNode;
}
}
dgFloat32 dgMeshEffect::dgMeshBVH::CalculateSurfaceArea (dgMeshBVHNode* const node0, dgMeshBVHNode* const node1, dgVector& minBox, dgVector& maxBox) const
{
minBox = dgVector (dgMin (node0->m_p0.m_x, node1->m_p0.m_x), dgMin (node0->m_p0.m_y, node1->m_p0.m_y), dgMin (node0->m_p0.m_z, node1->m_p0.m_z), dgFloat32 (0.0f));
maxBox = dgVector (dgMax (node0->m_p1.m_x, node1->m_p1.m_x), dgMax (node0->m_p1.m_y, node1->m_p1.m_y), dgMax (node0->m_p1.m_z, node1->m_p1.m_z), dgFloat32 (0.0f));
dgVector side0 ((maxBox - minBox).Scale3 (dgFloat32 (0.5f)));
dgVector side1 (side0.m_y, side0.m_z, side0.m_x, dgFloat32 (0.0f));
return side0 % side1;
}
void dgMeshEffect::dgMeshBVH::ImproveNodeFitness (dgMeshBVHNode* const node)
{
dgAssert (node->m_left);
dgAssert (node->m_right);
if (node->m_parent) {
if (node->m_parent->m_left == node) {
dgFloat32 cost0 = node->m_area;
dgVector cost1P0;
dgVector cost1P1;
dgFloat32 cost1 = CalculateSurfaceArea (node->m_right, node->m_parent->m_right, cost1P0, cost1P1);
dgVector cost2P0;
dgVector cost2P1;
dgFloat32 cost2 = CalculateSurfaceArea (node->m_left, node->m_parent->m_right, cost2P0, cost2P1);
if ((cost1 <= cost0) && (cost1 <= cost2)) {
dgMeshBVHNode* const parent = node->m_parent;
node->m_p0 = parent->m_p0;
node->m_p1 = parent->m_p1;
node->m_area = parent->m_area;
if (parent->m_parent) {
if (parent->m_parent->m_left == parent) {
parent->m_parent->m_left = node;
} else {
dgAssert (parent->m_parent->m_right == parent);
parent->m_parent->m_right = node;
}
} else {
m_rootNode = node;
}
node->m_parent = parent->m_parent;
parent->m_parent = node;
node->m_right->m_parent = parent;
parent->m_left = node->m_right;
node->m_right = parent;
parent->m_p0 = cost1P0;
parent->m_p1 = cost1P1;
parent->m_area = cost1;
} else if ((cost2 <= cost0) && (cost2 <= cost1)) {
dgMeshBVHNode* const parent = node->m_parent;
node->m_p0 = parent->m_p0;
node->m_p1 = parent->m_p1;
node->m_area = parent->m_area;
if (parent->m_parent) {
if (parent->m_parent->m_left == parent) {
parent->m_parent->m_left = node;
} else {
dgAssert (parent->m_parent->m_right == parent);
parent->m_parent->m_right = node;
}
} else {
m_rootNode = node;
}
node->m_parent = parent->m_parent;
parent->m_parent = node;
node->m_left->m_parent = parent;
parent->m_left = node->m_left;
node->m_left = parent;
parent->m_p0 = cost2P0;
parent->m_p1 = cost2P1;
parent->m_area = cost2;
}
} else {
dgFloat32 cost0 = node->m_area;
dgVector cost1P0;
dgVector cost1P1;
dgFloat32 cost1 = CalculateSurfaceArea (node->m_left, node->m_parent->m_left, cost1P0, cost1P1);
dgVector cost2P0;
dgVector cost2P1;
dgFloat32 cost2 = CalculateSurfaceArea (node->m_right, node->m_parent->m_left, cost2P0, cost2P1);
if ((cost1 <= cost0) && (cost1 <= cost2)) {
dgMeshBVHNode* const parent = node->m_parent;
node->m_p0 = parent->m_p0;
node->m_p1 = parent->m_p1;
node->m_area = parent->m_area;
if (parent->m_parent) {
if (parent->m_parent->m_left == parent) {
parent->m_parent->m_left = node;
} else {
dgAssert (parent->m_parent->m_right == parent);
parent->m_parent->m_right = node;
}
} else {
m_rootNode = node;
}
node->m_parent = parent->m_parent;
parent->m_parent = node;
node->m_left->m_parent = parent;
parent->m_right = node->m_left;
node->m_left = parent;
parent->m_p0 = cost1P0;
parent->m_p1 = cost1P1;
parent->m_area = cost1;
} else if ((cost2 <= cost0) && (cost2 <= cost1)) {
dgMeshBVHNode* const parent = node->m_parent;
node->m_p0 = parent->m_p0;
node->m_p1 = parent->m_p1;
node->m_area = parent->m_area;
if (parent->m_parent) {
if (parent->m_parent->m_left == parent) {
parent->m_parent->m_left = node;
} else {
dgAssert (parent->m_parent->m_right == parent);
parent->m_parent->m_right = node;
}
} else {
m_rootNode = node;
}
node->m_parent = parent->m_parent;
parent->m_parent = node;
node->m_right->m_parent = parent;
parent->m_right = node->m_right;
node->m_right = parent;
parent->m_p0 = cost2P0;
parent->m_p1 = cost2P1;
parent->m_area = cost2;
}
}
}
// dgAssert (SanityCheck());
}
void dgMeshEffect::dgMeshBVH::ImproveNodeFitness ()
{
dgFloat64 cost0 = m_fitness.TotalCost ();
dgFloat64 cost1 = cost0;
do {
cost0 = cost1;
dgFitnessList::Iterator iter (m_fitness);
for (iter.Begin(); iter; iter ++) {
dgFitnessList::dgTreeNode* const node = iter.GetNode();
ImproveNodeFitness (node->GetInfo());
}
cost1 = m_fitness.TotalCost ();
} while (cost1 < (dgFloat32 (0.95f)) * cost0);
}
dgMeshEffect::dgMeshBVH::dgMeshBVHNode* dgMeshEffect::dgMeshBVH::AddFaceNode (dgEdge* const face, void* const userData)
{
dgMemoryAllocator* const allocator = m_mesh->GetAllocator();
dgMeshBVHNode* const newNode = new (allocator) dgMeshBVHNode (m_mesh, face, userData);
if (!m_rootNode) {
m_rootNode = newNode;
} else {
dgVector p0;
dgVector p1;
dgMeshBVHNode* sibling = m_rootNode;
dgFloat32 surfaceArea = dgMeshBVH::CalculateSurfaceArea (newNode, sibling, p0, p1);
while(sibling->m_left && sibling->m_right) {
if (surfaceArea > sibling->m_area) {
break;
}
sibling->SetBox (p0, p1);
dgVector leftP0;
dgVector leftP1;
dgFloat32 leftSurfaceArea = CalculateSurfaceArea (newNode, sibling->m_left, leftP0, leftP1);
dgVector rightP0;
dgVector rightP1;
dgFloat32 rightSurfaceArea = CalculateSurfaceArea (newNode, sibling->m_right, rightP0, rightP1);
if (leftSurfaceArea < rightSurfaceArea) {
sibling = sibling->m_left;
p0 = leftP0;
p1 = leftP1;
surfaceArea = leftSurfaceArea;
} else {
sibling = sibling->m_right;
p0 = rightP0;
p1 = rightP1;
surfaceArea = rightSurfaceArea;
}
}
if (!sibling->m_parent) {
m_rootNode = new (allocator) dgMeshBVHNode (sibling, newNode);
m_fitness.Insert(m_rootNode, m_rootNode);
} else {
dgMeshBVHNode* const parent = sibling->m_parent;
if (parent->m_left == sibling) {
dgMeshBVHNode* const node = new (allocator) dgMeshBVHNode (sibling, newNode);
m_fitness.Insert(node, node);
parent->m_left = node;
node->m_parent = parent;
} else {
dgAssert (parent->m_right == sibling);
dgMeshBVHNode* const node = new (allocator) dgMeshBVHNode (sibling, newNode);
m_fitness.Insert(node, node);
parent->m_right = node;
node->m_parent = parent;
}
}
}
return newNode;
}
void dgMeshEffect::dgMeshBVH::RemoveNode (dgMeshBVHNode* const treeNode)
{
if (!treeNode->m_parent) {
delete (m_rootNode);
m_rootNode = NULL;
} else if (!treeNode->m_parent->m_parent) {
dgMeshBVHNode* const root = m_rootNode;
if (treeNode->m_parent->m_left == treeNode) {
m_rootNode = treeNode->m_parent->m_right;
treeNode->m_parent->m_right = NULL;
} else {
dgAssert (treeNode->m_parent->m_right == treeNode);
m_rootNode = treeNode->m_parent->m_left;
treeNode->m_parent->m_left= NULL;
}
m_rootNode->m_parent = NULL;
dgAssert (m_fitness.Find(root));
m_fitness.Remove(root);
delete (root);
} else {
dgMeshBVHNode* const root = treeNode->m_parent->m_parent;
if (treeNode->m_parent == root->m_left) {
if (treeNode->m_parent->m_right == treeNode) {
root->m_left = treeNode->m_parent->m_left;
treeNode->m_parent->m_left = NULL;
} else {
dgAssert (treeNode->m_parent->m_left == treeNode);
root->m_left = treeNode->m_parent->m_right;
treeNode->m_parent->m_right = NULL;
}
root->m_left->m_parent = root;
} else {
if (treeNode->m_parent->m_right == treeNode) {
root->m_right = treeNode->m_parent->m_left;
treeNode->m_parent->m_left = NULL;
} else {
dgAssert (treeNode->m_parent->m_left == treeNode);
root->m_right = treeNode->m_parent->m_right;
treeNode->m_parent->m_right = NULL;
}
root->m_right->m_parent = root;
}
dgAssert (m_fitness.Find(treeNode->m_parent));
m_fitness.Remove(treeNode->m_parent);
delete (treeNode->m_parent);
}
//dgAssert (SanityCheck());
}
bool dgMeshEffect::dgMeshBVH::SanityCheck() const
{
#ifdef _DEBUG
dgAssert (m_mesh->Sanity ());
if (!m_rootNode) {
return false;
}
if ((!m_rootNode->m_left && m_rootNode->m_right) || (m_rootNode->m_left && !m_rootNode->m_right)) {
return false;
}
if (m_rootNode->m_left && m_rootNode->m_right) {
if (m_rootNode->m_left->m_parent != m_rootNode) {
return false;
}
if (m_rootNode->m_right->m_parent != m_rootNode) {
return false;
}
dgMeshBVHNode* stackPool[DG_MESH_EFFECT_BVH_STACK_DEPTH];
dgInt32 stack = 2;
stackPool[0] = m_rootNode->m_left;
stackPool[1] = m_rootNode->m_right;
while (stack) {
stack --;
dgMeshBVHNode* const node = stackPool[stack];
if ((node->m_parent->m_left != node) && (node->m_parent->m_right != node)){
return false;
}
if (node->m_left) {
dgAssert (node->m_right);
stackPool[stack] = node->m_left;
stack++;
dgAssert (stack < dgInt32 (sizeof (stackPool) / sizeof (dgMeshBVHNode*)));
stackPool[stack] = node->m_right;
stack++;
dgAssert (stack < dgInt32 (sizeof (stackPool) / sizeof (dgMeshBVHNode*)));
}
}
}
#endif
return true;
}
void dgMeshEffect::dgMeshBVH::GetOverlapNodes (dgList<dgMeshBVHNode*>& overlapNodes, const dgBigVector& p0, const dgBigVector& p1) const
{
dgMeshBVHNode* stackPool[DG_MESH_EFFECT_BVH_STACK_DEPTH];
dgInt32 stack = 1;
stackPool[0] = m_rootNode;
dgVector l0(p0);
dgVector l1(p1);
while (stack) {
stack --;
dgMeshBVHNode* const me = stackPool[stack];
if (me && dgOverlapTest (me->m_p0, me->m_p1, l0, l1)) {
if (!me->m_left) {
dgAssert (!me->m_right);
overlapNodes.Append(me);
} else {
dgAssert (me->m_left);
dgAssert (me->m_right);
stackPool[stack] = me->m_left;
stack++;
dgAssert (stack < dgInt32 (sizeof (stackPool) / sizeof (dgMeshBVHNode*)));
stackPool[stack] = me->m_right;
stack++;
dgAssert (stack < dgInt32 (sizeof (stackPool) / sizeof (dgMeshBVHNode*)));
}
}
}
}
dgFloat64 dgMeshEffect::dgMeshBVH::VertexRayCast (const dgBigVector& p0, const dgBigVector& p1) const
{
dgAssert (0);
/*
dgMeshBVHNode* stackPool[DG_MESH_EFFECT_BVH_STACK_DEPTH];
dgInt32 stack = 1;
stackPool[0] = m_rootNode;
dgVector l0(p0);
dgVector l1(p1);
dgBigVector p1p0 (p1 - p0);
dgFloat64 den = p1p0 % p1p0;
const dgBigVector* const points = (dgBigVector*) m_mesh->GetVertexPool();
while (stack) {
stack --;
dgMeshBVHNode* const me = stackPool[stack];
if (me && dgOverlapTest (me->m_p0, me->m_p1, l0, l1)) {
if (!me->m_left) {
dgAssert (!me->m_right);
dgEdge* ptr = me->m_face;
do {
dgInt32 index = ptr->m_incidentVertex;
const dgBigVector& q0 = points[index];
dgBigVector q0p0 (q0 - p0);
dgFloat64 alpha = q0p0 % p1p0;
if ((alpha > (DG_BOOLEAN_ZERO_TOLERANCE * den)) && (alpha < (den - DG_BOOLEAN_ZERO_TOLERANCE))) {
dgBigVector dist (p0 + p1p0.Scale3 (alpha / den) - q0);
dgFloat64 dist2 = dist % dist;
if (dist2 < (DG_BOOLEAN_ZERO_TOLERANCE * DG_BOOLEAN_ZERO_TOLERANCE)) {
return alpha / den;
}
}
ptr = ptr->m_next;
} while (ptr != me->m_face);
} else {
dgAssert (me->m_left);
dgAssert (me->m_right);
stackPool[stack] = me->m_left;
stack++;
dgAssert (stack < dgInt32 (sizeof (stackPool) / sizeof (dgMeshBVHNode*)));
stackPool[stack] = me->m_right;
stack++;
dgAssert (stack < dgInt32 (sizeof (stackPool) / sizeof (dgMeshBVHNode*)));
}
}
}
*/
return 1.2f;
}
bool dgMeshEffect::dgMeshBVH::RayRayIntersect (dgEdge* const edge, const dgMeshEffect* const otherMesh, dgEdge* const otherEdge, dgFloat64& param, dgFloat64& otherParam) const
{
dgAssert (0);
/*
dgBigVector ray_p0 (m_mesh->m_points[edge->m_incidentVertex]);
dgBigVector ray_p1 (m_mesh->m_points[edge->m_twin->m_incidentVertex]);
dgBigVector ray_q0 (otherMesh->m_points[otherEdge->m_incidentVertex]);
dgBigVector ray_q1 (otherMesh->m_points[otherEdge->m_twin->m_incidentVertex]);
dgBigVector p1p0 (ray_p1 - ray_p0);
dgBigVector q1q0 (ray_q1 - ray_q0);
dgBigVector p0q0 (ray_p0 - ray_q0);
dgFloat64 a = p1p0 % p1p0; // always >= 0
dgFloat64 c = q1q0 % q1q0; // always >= 0
dgFloat64 b = p1p0 % q1q0;
dgFloat64 d = (p1p0 % p0q0);
dgFloat64 e = (q1q0 % p0q0);
dgFloat64 den = a * c - b * b; // always >= 0
// compute the line parameters of the two closest points
if (den < DG_BOOLEAN_ZERO_TOLERANCE) {
// the lines are almost parallel
return false;
} else {
// get the closest points on the infinite lines
dgFloat64 t = b * e - c * d;
dgFloat64 s = a * e - b * d;
if (t < (DG_BOOLEAN_ZERO_TOLERANCE * den) || (s < (DG_BOOLEAN_ZERO_TOLERANCE * den)) || (t > (den - DG_BOOLEAN_ZERO_TOLERANCE)) || (s > (den - DG_BOOLEAN_ZERO_TOLERANCE))) {
return false;
}
//dgBigVector normal (p1p0 * q1q0);
//dgFloat64 dist0 = normal % (p1p0.Scale3 (t / den) - ray_p0);
//dgFloat64 dist1 = normal % (q1q0.Scale3 (s / den) - ray_q0);
dgBigVector r0 = ray_p0 + p1p0.Scale3 (t / den);
dgBigVector r1 = ray_q0 + q1q0.Scale3 (s / den);
dgBigVector r1r0 (r1 - r0);
dgFloat64 dist2 = r1r0 % r1r0;
if (dist2 > (DG_BOOLEAN_ZERO_TOLERANCE * DG_BOOLEAN_ZERO_TOLERANCE)) {
return false;
}
param = t / den;
otherParam = s / den;
}
*/
return true;
}
dgFloat64 dgMeshEffect::dgMeshBVH::RayFaceIntersect (const dgMeshBVHNode* const faceNode, const dgBigVector& p0, const dgBigVector& p1, bool doubleSidedFaces) const
{
dgBigVector normal (m_mesh->FaceNormal(faceNode->m_face, m_mesh->GetVertexPool(), sizeof(dgBigVector)));
dgBigVector diff (p1 - p0);
dgFloat64 tOut = 2.0f;
const dgBigVector* const points = (dgBigVector*) m_mesh->GetVertexPool();
dgFloat64 dir = normal % diff;
if (dir < 0.0f) {
dgEdge* ptr = faceNode->m_face;
do {
dgInt32 index0 = ptr->m_incidentVertex;
dgInt32 index1 = ptr->m_next->m_incidentVertex;
dgBigVector p0v0 (points[index0] - p0);
dgBigVector p0v1 (points[index1] - p0);
dgFloat64 alpha = (diff * p0v1) % p0v0;
if (alpha <= 0.0f) {
return 1.2f;
}
ptr = ptr->m_next;
} while (ptr != faceNode->m_face);
dgInt32 index0 = ptr->m_incidentVertex;
dgBigVector p0v0 (points[index0] - p0);
tOut = normal % p0v0;
dgFloat64 dist = normal % diff;
tOut = tOut / dist;
} else if (doubleSidedFaces && (dir > 0.0f)) {
dgEdge* ptr = faceNode->m_face;
do {
dgInt32 index0 = ptr->m_incidentVertex;
dgInt32 index1 = ptr->m_prev->m_incidentVertex;
dgBigVector p0v0 (points[index0] - p0);
dgBigVector p0v1 (points[index1] - p0);
dgFloat64 alpha = (diff * p0v1) % p0v0;
if (alpha <= 0.0f) {
return 1.2f;
}
ptr = ptr->m_prev;
} while (ptr != faceNode->m_face);
dgInt32 index0 = ptr->m_incidentVertex;
dgBigVector p0v0 (points[index0] - p0);
tOut = normal % p0v0;
dgFloat64 dist = normal % diff;
tOut = tOut / dist;
}
if (tOut < 1.e-12f) {
tOut = 2.0f;
} else if (tOut > (1.0 - 1.e-12f)) {
tOut = 2.0f;
}
return tOut;
}
dgMeshEffect::dgMeshBVH::dgMeshBVHNode* dgMeshEffect::dgMeshBVH::FaceRayCast (const dgBigVector& p0, const dgBigVector& p1, dgFloat64& paramOut, bool doubleSidedFaces) const
{
dgMeshBVHNode* stackPool[DG_MESH_EFFECT_BVH_STACK_DEPTH];
dgInt32 stack = 1;
dgMeshBVHNode* node = NULL;
stackPool[0] = m_rootNode;
dgFloat64 maxParam = dgFloat32 (1.2f);
dgVector l0(p0);
dgVector l1(p1);
l0 = l0 & dgVector::m_triplexMask;
l1 = l1 & dgVector::m_triplexMask;
dgFastRayTest ray (l0, l1);
while (stack) {
stack --;
dgMeshBVHNode* const me = stackPool[stack];
if (me && ray.BoxTest (me->m_p0, me->m_p1)) {
if (!me->m_left) {
dgAssert (!me->m_right);
dgFloat64 param = RayFaceIntersect (me, p0, p1, doubleSidedFaces);
if (param < maxParam) {
node = me;
maxParam = param;
}
} else {
dgAssert (me->m_left);
dgAssert (me->m_right);
stackPool[stack] = me->m_left;
stack++;
dgAssert (stack < dgInt32 (sizeof (stackPool) / sizeof (dgMeshBVHNode*)));
stackPool[stack] = me->m_right;
stack++;
dgAssert (stack < dgInt32 (sizeof (stackPool) / sizeof (dgMeshBVHNode*)));
}
}
}
paramOut = maxParam;
return node;
}
dgMeshEffect::dgMeshEffect ()
:dgPolyhedra(NULL)
{
dgAssert (0);
}
dgMeshEffect::dgMeshEffect(dgMemoryAllocator* const allocator)
:dgPolyhedra(allocator)
{
Init();
}
dgMeshEffect::dgMeshEffect (dgMemoryAllocator* const allocator, const dgMatrix& planeMatrix, dgFloat32 witdth, dgFloat32 breadth, dgInt32 material, const dgMatrix& textureMatrix0, const dgMatrix& textureMatrix1)
:dgPolyhedra(allocator)
{
dgInt32 index[4];
dgInt64 attrIndex[4];
dgBigVector face[4];
Init();
face[0] = dgBigVector (dgFloat32 (0.0f), -witdth, -breadth, dgFloat32 (0.0f));
face[1] = dgBigVector (dgFloat32 (0.0f), witdth, -breadth, dgFloat32 (0.0f));
face[2] = dgBigVector (dgFloat32 (0.0f), witdth, breadth, dgFloat32 (0.0f));
face[3] = dgBigVector (dgFloat32 (0.0f), -witdth, breadth, dgFloat32 (0.0f));
for (dgInt32 i = 0; i < 4; i ++) {
dgBigVector uv0 (textureMatrix0.TransformVector(face[i]));
dgBigVector uv1 (textureMatrix1.TransformVector(face[i]));
m_points[i] = planeMatrix.TransformVector(face[i]);
m_attrib[i].m_vertex.m_x = m_points[i].m_x;
m_attrib[i].m_vertex.m_y = m_points[i].m_y;
m_attrib[i].m_vertex.m_z = m_points[i].m_z;
m_attrib[i].m_vertex.m_w = dgFloat64 (0.0f);
m_attrib[i].m_normal_x = planeMatrix.m_front.m_x;
m_attrib[i].m_normal_y = planeMatrix.m_front.m_y;
m_attrib[i].m_normal_z = planeMatrix.m_front.m_z;
m_attrib[i].m_u0 = uv0.m_y;
m_attrib[i].m_v0 = uv0.m_z;
m_attrib[i].m_u1 = uv1.m_y;
m_attrib[i].m_v1 = uv1.m_z;
m_attrib[i].m_material = material;
index[i] = i;
attrIndex[i] = i;
}
m_pointCount = 4;
m_atribCount = 4;
BeginFace();
AddFace (4, index, attrIndex);
EndFace();
}
dgMeshEffect::dgMeshEffect(dgPolyhedra& mesh, const dgMeshEffect& source)
:dgPolyhedra (mesh)
{
m_pointCount = source.m_pointCount;
m_maxPointCount = source.m_maxPointCount;
m_points = (dgBigVector*) GetAllocator()->MallocLow(dgInt32 (m_maxPointCount * sizeof(dgBigVector)));
memcpy (m_points, source.m_points, m_pointCount * sizeof(dgBigVector));
m_atribCount = source.m_atribCount;
m_maxAtribCount = source.m_maxAtribCount;
m_attrib = (dgVertexAtribute*) GetAllocator()->MallocLow(dgInt32 (m_maxAtribCount * sizeof(dgVertexAtribute)));
memcpy (m_attrib, source.m_attrib, m_atribCount * sizeof(dgVertexAtribute));
}
dgMeshEffect::dgMeshEffect(const dgMeshEffect& source)
:dgPolyhedra (source)
{
m_pointCount = source.m_pointCount;
m_maxPointCount = source.m_maxPointCount;
m_points = (dgBigVector*) GetAllocator()->MallocLow(dgInt32 (m_maxPointCount * sizeof(dgBigVector)));
memcpy (m_points, source.m_points, m_pointCount * sizeof(dgBigVector));
m_atribCount = source.m_atribCount;
m_maxAtribCount = source.m_maxAtribCount;
m_attrib = (dgVertexAtribute*) GetAllocator()->MallocLow(dgInt32 (m_maxAtribCount * sizeof(dgVertexAtribute)));
memcpy (m_attrib, source.m_attrib, m_atribCount * sizeof(dgVertexAtribute));
}
dgMeshEffect::dgMeshEffect(dgCollisionInstance* const collision)
:dgPolyhedra (collision->GetAllocator())
{
class dgMeshEffectBuilder
{
public:
dgMeshEffectBuilder ()
{
m_brush = 0;
m_faceCount = 0;
m_vertexCount = 0;
m_maxFaceCount = 32;
m_maxVertexCount = 32;
m_vertex = (dgVector*) dgMallocStack(m_maxVertexCount * sizeof(dgVector));
m_faceIndexCount = (dgInt32*) dgMallocStack(m_maxFaceCount * sizeof(dgInt32));
}
~dgMeshEffectBuilder ()
{
dgFreeStack (m_faceIndexCount);
dgFreeStack (m_vertex);
}
static void GetShapeFromCollision (void* userData, dgInt32 vertexCount, const dgFloat32* faceVertex, dgInt32 id)
{
dgInt32 vertexIndex;
dgMeshEffectBuilder& builder = *((dgMeshEffectBuilder*)userData);
if (builder.m_faceCount >= builder.m_maxFaceCount) {
dgInt32* index;
builder.m_maxFaceCount *= 2;
index = (dgInt32*) dgMallocStack(builder.m_maxFaceCount * sizeof(dgInt32));
memcpy (index, builder.m_faceIndexCount, builder.m_faceCount * sizeof(dgInt32));
dgFreeStack(builder.m_faceIndexCount);
builder.m_faceIndexCount = index;
}
builder.m_faceIndexCount[builder.m_faceCount] = vertexCount;
builder.m_faceCount = builder.m_faceCount + 1;
vertexIndex = builder.m_vertexCount;
dgFloat32 brush = dgFloat32 (builder.m_brush);
for (dgInt32 i = 0; i < vertexCount; i ++) {
if (vertexIndex >= builder.m_maxVertexCount) {
builder.m_maxVertexCount *= 2;
dgVector* const points = (dgVector*) dgMallocStack(builder.m_maxVertexCount * sizeof(dgVector));
memcpy (points, builder.m_vertex, vertexIndex * sizeof(dgVector));
dgFreeStack(builder.m_vertex);
builder.m_vertex = points;
}
builder.m_vertex[vertexIndex].m_x = faceVertex[i * 3 + 0];
builder.m_vertex[vertexIndex].m_y = faceVertex[i * 3 + 1];
builder.m_vertex[vertexIndex].m_z = faceVertex[i * 3 + 2];
builder.m_vertex[vertexIndex].m_w = brush;
vertexIndex ++;
}
builder.m_vertexCount = vertexIndex;
}
dgInt32 m_brush;
dgInt32 m_vertexCount;
dgInt32 m_maxVertexCount;
dgInt32 m_faceCount;
dgInt32 m_maxFaceCount;
dgVector* m_vertex;
dgInt32* m_faceIndexCount;
};
dgMeshEffectBuilder builder;
if (collision->IsType (dgCollision::dgCollisionCompound_RTTI)) {
dgCollisionInfo collisionInfo;
collision->GetCollisionInfo (&collisionInfo);
dgInt32 brush = 0;
dgMatrix matrix (collisionInfo.m_offsetMatrix);
dgCollisionCompound* const compoundCollision = (dgCollisionCompound*) collision->GetChildShape();
for (dgTree<dgCollisionCompound::dgNodeBase*, dgInt32>::dgTreeNode* node = compoundCollision->GetFirstNode(); node; node = compoundCollision->GetNextNode(node)) {
builder.m_brush = brush;
brush ++;
dgCollisionInstance* const childShape = compoundCollision->GetCollisionFromNode(node);
childShape->DebugCollision (matrix, (dgCollision::OnDebugCollisionMeshCallback) dgMeshEffectBuilder::GetShapeFromCollision, &builder);
}
} else {
dgMatrix matrix (dgGetIdentityMatrix());
collision->DebugCollision (matrix, (dgCollision::OnDebugCollisionMeshCallback) dgMeshEffectBuilder::GetShapeFromCollision, &builder);
}
dgStack<dgInt32>indexList (builder.m_vertexCount);
dgVertexListToIndexList (&builder.m_vertex[0].m_x, sizeof (dgVector), sizeof (dgVector), 0, builder.m_vertexCount, &indexList[0], DG_VERTEXLIST_INDEXLIST_TOL);
dgStack<dgInt32> materialIndex(builder.m_faceCount);
dgStack<dgInt32> m_normalUVIndex(builder.m_vertexCount);
dgVector normalUV(dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));
memset (&materialIndex[0], 0, size_t (materialIndex.GetSizeInBytes()));
memset (&m_normalUVIndex[0], 0, size_t (m_normalUVIndex.GetSizeInBytes()));
Init();
BuildFromVertexListIndexList(builder.m_faceCount, builder.m_faceIndexCount, &materialIndex[0],
&builder.m_vertex[0].m_x, sizeof (dgVector), &indexList[0],
&normalUV.m_x, sizeof (dgVector), &m_normalUVIndex[0],
&normalUV.m_x, sizeof (dgVector), &m_normalUVIndex[0],
&normalUV.m_x, sizeof (dgVector), &m_normalUVIndex[0]);
RepairTJoints();
CalculateNormals(dgFloat32 (45.0f * 3.141592f/180.0f));
}
dgMeshEffect::dgMeshEffect(dgMemoryAllocator* const allocator, const char* const fileName)
:dgPolyhedra (allocator)
{
class ParceOFF
{
public:
enum Token
{
m_off,
m_value,
m_end,
};
ParceOFF (FILE* const file)
:m_file (file)
{
}
Token GetToken(char* const buffer) const
{
while (!feof (m_file) && fscanf (m_file, "%s", buffer)) {
if (buffer[0] == '#') {
SkipLine();
} else {
if (!_stricmp (buffer, "OFF")) {
return m_off;
}
return m_value;
}
}
return m_end;
}
char* SkipLine() const
{
char tmp[1024];
return fgets (tmp, sizeof (tmp), m_file);
}
dgInt32 GetInteger() const
{
char buffer[1024];
GetToken(buffer);
return atoi (buffer);
}
dgFloat64 GetFloat() const
{
char buffer[1024];
GetToken(buffer);
return atof (buffer);
}
FILE* m_file;
};
Init();
FILE* const file = fopen (fileName, "rb");
if (file) {
ParceOFF parcel (file);
dgInt32 vertexCount = 0;
dgInt32 faceCount = 0;
// dgInt32 edgeCount = 0;
char buffer[1024];
bool stillData = true;
while (stillData) {
ParceOFF::Token token = parcel.GetToken(buffer);
switch (token)
{
case ParceOFF::m_off:
{
vertexCount = parcel.GetInteger();
faceCount = parcel.GetInteger();
// edgeCount = parcel.GetInteger();
parcel.SkipLine();
dgVertexAtribute attribute;
memset (&attribute, 0, sizeof (dgVertexAtribute));
attribute.m_normal_y = 1.0f;
//AddAtribute(attribute);
for (dgInt32 i = 0; i < vertexCount; i ++) {
//dgBigVector point;
attribute.m_vertex.m_x = parcel.GetFloat();
attribute.m_vertex.m_y = parcel.GetFloat();
attribute.m_vertex.m_z = parcel.GetFloat();
attribute.m_vertex.m_w = 0.0;
parcel.SkipLine();
//AddVertex(point);
AddPoint(&attribute.m_vertex.m_x, 0);
}
BeginFace();
for (dgInt32 i = 0; i < faceCount; i ++) {
dgInt32 face[256];
dgInt64 attrib[256];
dgInt32 faceVertexCount = parcel.GetInteger();
for (dgInt32 j = 0; j < faceVertexCount; j ++) {
face[j] = parcel.GetInteger();
attrib[j] = face[j];
}
parcel.SkipLine();
AddFace(faceVertexCount, face, attrib);
}
EndFace();
CalculateNormals (3.1416f * 30.0f / 180.0f);
stillData = false;
break;
}
default:;
}
}
fclose (file);
}
}
dgMeshEffect::dgMeshEffect (dgMemoryAllocator* const allocator, dgDeserialize deserialization, void* const userData)
:dgPolyhedra (allocator)
{
dgInt32 faceCount;
deserialization (userData, &faceCount, sizeof (dgInt32));
deserialization (userData, &m_pointCount, sizeof (dgInt32));
deserialization (userData, &m_atribCount, sizeof (dgInt32));
deserialization (userData, &m_atribCount, sizeof (dgInt32));
m_maxPointCount = m_pointCount;
m_maxAtribCount = m_atribCount;
m_points = (dgBigVector*) GetAllocator()->MallocLow(dgInt32 (m_pointCount * sizeof(dgBigVector)));
m_attrib = (dgVertexAtribute*) GetAllocator()->MallocLow(dgInt32 (m_atribCount * sizeof(dgVertexAtribute)));
deserialization (userData, m_points, m_pointCount * sizeof (dgBigVector));
deserialization (userData, m_attrib, m_atribCount * sizeof (dgVertexAtribute));
BeginFace();
for (dgInt32 i = 0; i < faceCount; i ++) {
dgInt32 vertexCount;
dgInt32 face[1024];
dgInt64 attrib[1024];
deserialization (userData, &vertexCount, sizeof (dgInt32));
deserialization (userData, face, vertexCount * sizeof (dgInt32));
deserialization (userData, attrib, vertexCount * sizeof (dgInt64));
AddFace (vertexCount, face, attrib);
}
EndFace();
}
dgMeshEffect::~dgMeshEffect(void)
{
GetAllocator()->FreeLow (m_points);
GetAllocator()->FreeLow (m_attrib);
}
void dgMeshEffect::BeginFace()
{
dgPolyhedra::BeginFace();
}
void dgMeshEffect::EndFace ()
{
dgPolyhedra::EndFace();
for (bool hasVertexCollision = true; hasVertexCollision;) {
hasVertexCollision = false;
const dgInt32 currentCount = m_pointCount;
dgStack<dgInt8> verterCollision (currentCount);
memset (&verterCollision[0], 0, verterCollision.GetSizeInBytes());
Iterator iter (*this);
dgInt32 mark = IncLRU();
dgList<dgTreeNode*> collisionFound(GetAllocator());
for (iter.Begin(); iter; iter ++) {
dgEdge* const edge = &iter.GetNode()->GetInfo();
if (edge->m_mark != mark) {
if ((edge->m_incidentVertex < currentCount) && (verterCollision[edge->m_incidentVertex] == 0)) {
verterCollision[edge->m_incidentVertex] = 1;
} else {
hasVertexCollision = true;
collisionFound.Append(iter.GetNode());
}
dgEdge* ptr = edge;
do {
ptr->m_mark = mark;
ptr = ptr->m_twin->m_next;
} while (ptr != edge);
}
}
if (hasVertexCollision) {
dgAssert (Sanity());
for (dgList<dgTreeNode*>::dgListNode* node = collisionFound.GetFirst(); node; node = node->GetNext()) {
dgEdge* const edge = &node->GetInfo()->GetInfo();
// this is a vertex collision
dgBigVector point (m_points[edge->m_incidentVertex]);
point.m_w += dgFloat64 (1.0f);
AddVertex (point);
dgEdge* ptr = edge;
do {
ptr->m_incidentVertex = m_pointCount - 1;
dgTreeNode* const edgeNode = GetNodeFromInfo (*ptr);
dgPairKey edgeKey (ptr->m_incidentVertex, ptr->m_twin->m_incidentVertex);
ReplaceKey (edgeNode, edgeKey.GetVal());
dgTreeNode* const twinNode = GetNodeFromInfo (*(ptr->m_twin));
dgPairKey twinKey (ptr->m_twin->m_incidentVertex, ptr->m_incidentVertex);
ReplaceKey (twinNode, twinKey.GetVal());
ptr = ptr->m_twin->m_next;
} while (ptr != edge);
}
dgAssert (Sanity());
}
}
}
void dgMeshEffect::Init()
{
m_pointCount = 0;
m_atribCount = 0;
m_maxPointCount = DG_MESH_EFFECT_INITIAL_VERTEX_SIZE;
m_maxAtribCount = DG_MESH_EFFECT_INITIAL_VERTEX_SIZE;
m_points = (dgBigVector*) GetAllocator()->MallocLow(dgInt32 (m_maxPointCount * sizeof(dgBigVector)));
m_attrib = (dgVertexAtribute*) GetAllocator()->MallocLow(dgInt32 (m_maxAtribCount * sizeof(dgVertexAtribute)));
}
void dgMeshEffect::Trace () const
{
for (dgInt32 i = 0; i < m_pointCount; i ++ ) {
dgTrace (("%d-> %f %f %f\n", i, m_points[i].m_x, m_points[i].m_y, m_points[i].m_z));
}
dgTree<dgEdge*, dgEdge*>filter(GetAllocator());
Iterator iter (*this);
for (iter.Begin(); iter; iter ++) {
dgEdge* const edge = &iter.GetNode()->GetInfo();
if (!filter.Find(edge)) {
dgEdge* ptr = edge;
do {
filter.Insert(edge, ptr);
dgTrace (("%d ", ptr->m_incidentVertex));
ptr = ptr->m_next;
} while (ptr != edge);
if (edge->m_incidentFace <= 0) {
dgTrace (("open"));
}
dgTrace (("\n"));
}
}
dgTrace (("\n"));
};
void dgMeshEffect::SaveOFF (const char* const fileName) const
{
FILE* const file = fopen (fileName, "wb");
fprintf (file, "OFF\n");
dgInt32 faceCount = 0;
dgTree<dgEdge*, dgEdge*>filter(GetAllocator());
Iterator iter (*this);
for (iter.Begin(); iter; iter ++) {
dgEdge* const face = &iter.GetNode()->GetInfo();
if (!filter.Find(face) && (face->m_incidentFace > 0)) {
faceCount ++;
dgEdge* edge = face;
do {
filter.Insert(edge, edge);
edge = edge->m_next;
} while (edge != face);
}
}
fprintf (file, "%d %d 0\n", m_pointCount, faceCount);
for (dgInt32 i = 0; i < m_pointCount; i ++) {
fprintf (file, "%f %f %f\n", m_points[i].m_x, m_points[i].m_y, m_points[i].m_z);
}
filter.RemoveAll();
for (iter.Begin(); iter; iter ++) {
dgEdge* const face = &iter.GetNode()->GetInfo();
if (!filter.Find(face) && (face->m_incidentFace > 0)) {
dgInt32 indices[1024];
dgInt32 vertexCount = 0;
dgEdge* edge = face;
do {
indices[vertexCount] = edge->m_incidentVertex;
vertexCount ++;
filter.Insert(edge, edge);
edge = edge->m_next;
} while (edge != face);
fprintf (file, "%d", vertexCount);
for (dgInt32 j = 0; j < vertexCount; j ++) {
fprintf (file, " %d", indices[j]);
}
fprintf (file, "\n");
}
}
fclose (file);
}
void dgMeshEffect::Triangulate ()
{
dgPolyhedra polygon(GetAllocator());
dgInt32 mark = IncLRU();
polygon.BeginFace();
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; iter ++){
dgEdge* const face = &(*iter);
if ((face->m_mark != mark) && (face->m_incidentFace > 0)) {
dgInt32 index[DG_MESH_EFFECT_POINT_SPLITED];
dgEdge* ptr = face;
dgInt32 indexCount = 0;
do {
dgInt32 attribIndex = dgInt32 (ptr->m_userData);
m_attrib[attribIndex].m_vertex.m_w = dgFloat64 (ptr->m_incidentVertex);
ptr->m_mark = mark;
index[indexCount] = attribIndex;
indexCount ++;
ptr = ptr->m_next;
} while (ptr != face);
polygon.AddFace(indexCount, index);
}
}
polygon.EndFace();
dgPolyhedra leftOversOut(GetAllocator());
polygon.Triangulate(&m_attrib[0].m_vertex.m_x, sizeof (dgVertexAtribute), &leftOversOut);
dgAssert (leftOversOut.GetCount() == 0);
RemoveAll();
SetLRU (0);
mark = polygon.IncLRU();
BeginFace();
dgPolyhedra::Iterator iter1 (polygon);
for (iter1.Begin(); iter1; iter1 ++){
dgEdge* const face = &(*iter1);
if ((face->m_mark != mark) && (face->m_incidentFace > 0)) {
dgInt32 index[DG_MESH_EFFECT_POINT_SPLITED];
dgInt64 userData[DG_MESH_EFFECT_POINT_SPLITED];
dgEdge* ptr = face;
dgInt32 indexCount = 0;
do {
ptr->m_mark = mark;
index[indexCount] = dgInt32 (m_attrib[ptr->m_incidentVertex].m_vertex.m_w);
userData[indexCount] = ptr->m_incidentVertex;
indexCount ++;
ptr = ptr->m_next;
} while (ptr != face);
AddFace(indexCount, index, userData);
}
}
EndFace();
for (iter.Begin(); iter; iter ++){
dgEdge* const face = &(*iter);
if (face->m_incidentFace > 0) {
dgInt32 attribIndex = dgInt32 (face->m_userData);
m_attrib[attribIndex].m_vertex.m_w = m_points[face->m_incidentVertex].m_w;
}
}
RepairTJoints ();
dgAssert (Sanity ());
}
void dgMeshEffect::ConvertToPolygons ()
{
dgPolyhedra polygon(GetAllocator());
dgInt32 mark = IncLRU();
polygon.BeginFace();
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; iter ++){
dgEdge* const face = &(*iter);
if ((face->m_mark != mark) && (face->m_incidentFace > 0)) {
dgInt32 index[DG_MESH_EFFECT_POINT_SPLITED];
dgEdge* ptr = face;
dgInt32 indexCount = 0;
do {
dgInt32 attribIndex = dgInt32 (ptr->m_userData);
m_attrib[attribIndex].m_vertex.m_w = dgFloat32 (ptr->m_incidentVertex);
ptr->m_mark = mark;
index[indexCount] = attribIndex;
indexCount ++;
ptr = ptr->m_next;
} while (ptr != face);
polygon.AddFace(indexCount, index);
}
}
polygon.EndFace();
dgPolyhedra leftOversOut(GetAllocator());
polygon.ConvexPartition (&m_attrib[0].m_vertex.m_x, sizeof (dgVertexAtribute), &leftOversOut);
dgAssert (leftOversOut.GetCount() == 0);
RemoveAll();
SetLRU (0);
mark = polygon.IncLRU();
BeginFace();
dgPolyhedra::Iterator iter1 (polygon);
for (iter1.Begin(); iter1; iter1 ++){
dgEdge* const face = &(*iter1);
if ((face->m_mark != mark) && (face->m_incidentFace > 0)) {
dgInt32 index[DG_MESH_EFFECT_POINT_SPLITED];
dgInt64 userData[DG_MESH_EFFECT_POINT_SPLITED];
dgEdge* ptr = face;
dgInt32 indexCount = 0;
do {
ptr->m_mark = mark;
index[indexCount] = dgInt32 (m_attrib[ptr->m_incidentVertex].m_vertex.m_w);
userData[indexCount] = ptr->m_incidentVertex;
indexCount ++;
ptr = ptr->m_next;
} while (ptr != face);
AddFace(indexCount, index, userData);
}
}
EndFace();
for (iter.Begin(); iter; iter ++){
dgEdge* const face = &(*iter);
if (face->m_incidentFace > 0) {
dgInt32 attribIndex = dgInt32 (face->m_userData);
m_attrib[attribIndex].m_vertex.m_w = m_points[face->m_incidentVertex].m_w;
}
}
RepairTJoints ();
dgAssert (Sanity ());
}
void dgMeshEffect::RemoveUnusedVertices(dgInt32* const vertexMapResult)
{
dgPolyhedra polygon(GetAllocator());
dgStack<dgInt32>attrbMap(m_atribCount);
dgStack<dgInt32>vertexMap(m_pointCount);
dgInt32 savedPointCount = m_pointCount;
memset(&vertexMap[0], -1, m_pointCount * sizeof (int));
memset(&attrbMap[0], -1, m_atribCount * sizeof (int));
int attribCount = 0;
int vertexCount = 0;
dgStack<dgBigVector>points (m_pointCount);
dgStack<dgVertexAtribute>atributes (m_atribCount);
dgInt32 mark = IncLRU();
polygon.BeginFace();
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; iter ++){
dgEdge* const face = &(*iter);
if ((face->m_mark != mark) && (face->m_incidentFace > 0)) {
dgInt32 vertex[DG_MESH_EFFECT_POINT_SPLITED];
dgInt64 userData[DG_MESH_EFFECT_POINT_SPLITED];
int indexCount = 0;
dgEdge* ptr = face;
do {
ptr->m_mark = mark;
int index = ptr->m_incidentVertex;
if (vertexMap[index] == -1) {
vertexMap[index] = vertexCount;
points[vertexCount] = m_points[index];
vertexCount ++;
}
vertex[indexCount] = vertexMap[index];
index = int (ptr->m_userData);
if (attrbMap[index] == -1) {
attrbMap[index] = attribCount;
atributes[attribCount] = m_attrib[index];
attribCount ++;
}
userData[indexCount] = attrbMap[index];
indexCount ++;
ptr = ptr->m_next;
} while (ptr != face);
polygon.AddFace(indexCount, vertex, userData);
}
}
polygon.EndFace();
m_pointCount = vertexCount;
memcpy (&m_points[0].m_x, &points[0].m_x, m_pointCount * sizeof (dgBigVector));
m_atribCount = attribCount;
memcpy (&m_attrib[0].m_vertex.m_x, &atributes[0].m_vertex.m_x, m_atribCount * sizeof (dgVertexAtribute));
RemoveAll();
SetLRU (0);
BeginFace();
dgPolyhedra::Iterator iter1 (polygon);
for (iter1.Begin(); iter1; iter1 ++){
dgEdge* const face = &(*iter1);
if ((face->m_mark != mark) && (face->m_incidentFace > 0)) {
dgInt32 index[DG_MESH_EFFECT_POINT_SPLITED];
dgInt64 userData[DG_MESH_EFFECT_POINT_SPLITED];
void AddPolygon (dgInt32 count, const dgFloat32* const vertexList, dgInt32 stride, dgInt32 material);
dgEdge* ptr = face;
dgInt32 indexCount = 0;
do {
ptr->m_mark = mark;
index[indexCount] = ptr->m_incidentVertex;
userData[indexCount] = dgInt64 (ptr->m_userData);
indexCount ++;
ptr = ptr->m_next;
} while (ptr != face);
AddFace(indexCount, index, userData);
}
}
EndFace();
PackVertexArrays ();
if (vertexMapResult) {
memcpy (vertexMapResult, &vertexMap[0], savedPointCount * sizeof (dgInt32));
}
}
void dgMeshEffect::ApplyTransform (const dgMatrix& matrix)
{
matrix.TransformTriplex(&m_points[0].m_x, sizeof (dgBigVector), &m_points[0].m_x, sizeof (dgBigVector), m_pointCount);
matrix.TransformTriplex(&m_attrib[0].m_vertex.m_x, sizeof (dgVertexAtribute), &m_attrib[0].m_vertex.m_x, sizeof (dgVertexAtribute), m_atribCount);
dgMatrix rotation ((matrix.Inverse4x4()).Transpose4X4());
for (dgInt32 i = 0; i < m_atribCount; i ++) {
dgVector n (dgFloat32 (m_attrib[i].m_normal_x), dgFloat32 (m_attrib[i].m_normal_y), dgFloat32 (m_attrib[i].m_normal_z), dgFloat32 (0.0f));
n = rotation.RotateVector(n);
dgAssert ((n % n) > dgFloat32 (0.0f));
n = n.Scale3 (dgRsqrt (n % n));
m_attrib[i].m_normal_x = n.m_x;
m_attrib[i].m_normal_y = n.m_y;
m_attrib[i].m_normal_z = n.m_z;
}
}
dgMatrix dgMeshEffect::CalculateOOBB (dgBigVector& size) const
{
dgObb sphere (CalculateSphere (&m_points[0].m_x, sizeof (dgBigVector), NULL));
size = sphere.m_size;
size.m_w = 0.0f;
// dgMatrix permuation (dgGetIdentityMatrix());
// permuation[0][0] = dgFloat32 (0.0f);
// permuation[0][1] = dgFloat32 (1.0f);
// permuation[1][1] = dgFloat32 (0.0f);
// permuation[1][2] = dgFloat32 (1.0f);
// permuation[2][2] = dgFloat32 (0.0f);
// permuation[2][0] = dgFloat32 (1.0f);
// while ((size.m_x < size.m_y) || (size.m_x < size.m_z)) {
// sphere = permuation * sphere;
// size = permuation.UnrotateVector(size);
// }
return sphere;
}
void dgMeshEffect::CalculateAABB (dgBigVector& minBox, dgBigVector& maxBox) const
{
dgBigVector minP ( dgFloat64 (1.0e15f), dgFloat64 (1.0e15f), dgFloat64 (1.0e15f), dgFloat64 (0.0f));
dgBigVector maxP (-dgFloat64 (1.0e15f), -dgFloat64 (1.0e15f), -dgFloat64 (1.0e15f), dgFloat64 (0.0f));
dgPolyhedra::Iterator iter (*this);
const dgBigVector* const points = &m_points[0];
for (iter.Begin(); iter; iter ++){
dgEdge* const edge = &(*iter);
const dgBigVector& p (points[edge->m_incidentVertex]);
minP.m_x = dgMin (p.m_x, minP.m_x);
minP.m_y = dgMin (p.m_y, minP.m_y);
minP.m_z = dgMin (p.m_z, minP.m_z);
maxP.m_x = dgMax (p.m_x, maxP.m_x);
maxP.m_y = dgMax (p.m_y, maxP.m_y);
maxP.m_z = dgMax (p.m_z, maxP.m_z);
}
minBox = minP;
maxBox = maxP;
}
void dgMeshEffect::BeginPolygon ()
{
m_pointCount = 0;
m_atribCount = 0;
RemoveAll();
BeginFace();
}
void dgMeshEffect::AddAtribute (const dgVertexAtribute& attib)
{
if (m_atribCount >= m_maxAtribCount) {
m_maxAtribCount *= 2;
dgVertexAtribute* const attibArray = (dgVertexAtribute*) GetAllocator()->MallocLow(dgInt32 (m_maxAtribCount * sizeof(dgVertexAtribute)));
memcpy (attibArray, m_attrib, m_atribCount * sizeof(dgVertexAtribute));
GetAllocator()->FreeLow(m_attrib);
m_attrib = attibArray;
}
m_attrib[m_atribCount] = attib;
dgBigVector n (attib.m_normal_x, attib.m_normal_y, attib.m_normal_z, dgFloat64 (0.0f));
dgFloat64 mag2 = n % n ;
if (mag2 < dgFloat64 (1.0e-16f)) {
n.m_x = dgFloat64 (0.0f);
n.m_y = dgFloat64 (1.0f);
n.m_z = dgFloat64 (0.0f);
}
m_attrib[m_atribCount].m_normal_x = n.m_x;
m_attrib[m_atribCount].m_normal_y = n.m_y;
m_attrib[m_atribCount].m_normal_z = n.m_z;
m_attrib[m_atribCount].m_vertex.m_x = QuantizeCordinade(m_attrib[m_atribCount].m_vertex.m_x);
m_attrib[m_atribCount].m_vertex.m_y = QuantizeCordinade(m_attrib[m_atribCount].m_vertex.m_y);
m_attrib[m_atribCount].m_vertex.m_z = QuantizeCordinade(m_attrib[m_atribCount].m_vertex.m_z);
m_atribCount ++;
}
void dgMeshEffect::AddVertex(const dgBigVector& vertex)
{
if (m_pointCount >= m_maxPointCount) {
m_maxPointCount *= 2;
dgBigVector* const points = (dgBigVector*) GetAllocator()->MallocLow(dgInt32 (m_maxPointCount * sizeof(dgBigVector)));
memcpy (points, m_points, m_pointCount * sizeof(dgBigVector));
GetAllocator()->FreeLow(m_points);
m_points = points;
}
m_points[m_pointCount].m_x = QuantizeCordinade(vertex[0]);
m_points[m_pointCount].m_y = QuantizeCordinade(vertex[1]);
m_points[m_pointCount].m_z = QuantizeCordinade(vertex[2]);
m_points[m_pointCount].m_w = vertex.m_w;
m_pointCount ++;
}
void dgMeshEffect::AddPoint(const dgFloat64* vertex, dgInt32 material)
{
dgVertexAtribute attib;
AddVertex(dgBigVector (vertex[0], vertex[1], vertex[2], vertex[3]));
attib.m_vertex.m_x = m_points[m_pointCount - 1].m_x;
attib.m_vertex.m_y = m_points[m_pointCount - 1].m_y;
attib.m_vertex.m_z = m_points[m_pointCount - 1].m_z;
attib.m_vertex.m_w = m_points[m_pointCount - 1].m_w;
attib.m_normal_x = vertex[4];
attib.m_normal_y = vertex[5];
attib.m_normal_z = vertex[6];
attib.m_u0 = vertex[7];
attib.m_v0 = vertex[8];
attib.m_u1 = vertex[9];
attib.m_v1 = vertex[10];
attib.m_material = material;
AddAtribute (attib);
}
void dgMeshEffect::PackVertexArrays ()
{
if (m_maxPointCount > m_pointCount) {
dgBigVector* const points = (dgBigVector*) GetAllocator()->MallocLow(dgInt32 (m_pointCount * sizeof(dgBigVector)));
memcpy (points, m_points, m_pointCount * sizeof(dgBigVector));
GetAllocator()->FreeLow(m_points);
m_points = points;
m_maxPointCount = m_pointCount;
}
if (m_maxAtribCount > m_atribCount) {
dgVertexAtribute* const attibArray = (dgVertexAtribute*) GetAllocator()->MallocLow(dgInt32 (m_atribCount * sizeof(dgVertexAtribute)));
memcpy (attibArray, m_attrib, m_atribCount * sizeof(dgVertexAtribute));
GetAllocator()->FreeLow(m_attrib);
m_attrib = attibArray;
m_maxAtribCount = m_atribCount;
}
};
void dgMeshEffect::AddPolygon (dgInt32 count, const dgFloat64* const vertexList, dgInt32 strideIndBytes, dgInt32 material)
{
dgAssert (strideIndBytes >= sizeof (dgBigVector));
dgInt32 stride = dgInt32 (strideIndBytes / sizeof (dgFloat64));
if (count > 3) {
dgPolyhedra polygon (GetAllocator());
dgInt32 indexList[256];
dgAssert (count < dgInt32 (sizeof (indexList)/sizeof(indexList[0])));
for (dgInt32 i = 0; i < count; i ++) {
indexList[i] = i;
}
polygon.BeginFace();
polygon.AddFace(count, indexList, NULL);
polygon.EndFace();
polygon.Triangulate(vertexList, strideIndBytes, NULL);
dgInt32 mark = polygon.IncLRU();
dgPolyhedra::Iterator iter (polygon);
for (iter.Begin(); iter; iter ++) {
dgEdge* const edge = &iter.GetNode()->GetInfo();
if ((edge->m_incidentFace > 0) && (edge->m_mark < mark)) {
dgInt32 i0 = edge->m_incidentVertex;
dgInt32 i1 = edge->m_next->m_incidentVertex;
dgInt32 i2 = edge->m_next->m_next->m_incidentVertex;
edge->m_mark = mark;
edge->m_next->m_mark = mark;
edge->m_next->m_next->m_mark = mark;
// #ifdef _DEBUG
// dgBigVector p0_ (&vertexList[i0 * stride]);
// dgBigVector p1_ (&vertexList[i1 * stride]);
// dgBigVector p2_ (&vertexList[i2 * stride]);
// dgBigVector e1_ (p1_ - p0_);
// dgBigVector e2_ (p2_ - p0_);
// dgBigVector n_ (e1_ * e2_);
// dgFloat64 mag2_ = n_ % n_;
// dgAssert (mag2_ > dgFloat32 (DG_MESH_EFFECT_PRECISION_SCALE_INV * DG_MESH_EFFECT_PRECISION_SCALE_INV));
// #endif
AddPoint(vertexList + i0 * stride, material);
AddPoint(vertexList + i1 * stride, material);
AddPoint(vertexList + i2 * stride, material);
#ifdef _DEBUG
const dgBigVector& p0 = m_points[m_pointCount - 3];
const dgBigVector& p1 = m_points[m_pointCount - 2];
const dgBigVector& p2 = m_points[m_pointCount - 1];
dgBigVector e1 (p1 - p0);
dgBigVector e2 (p2 - p0);
dgBigVector n (e1 * e2);
dgFloat64 mag3 = n % n;
dgAssert (mag3 > dgFloat64 (DG_MESH_EFFECT_PRECISION_SCALE_INV * DG_MESH_EFFECT_PRECISION_SCALE_INV));
#endif
}
}
} else {
AddPoint(vertexList, material);
AddPoint(vertexList + stride, material);
AddPoint(vertexList + stride + stride, material);
const dgBigVector& p0 = m_points[m_pointCount - 3];
const dgBigVector& p1 = m_points[m_pointCount - 2];
const dgBigVector& p2 = m_points[m_pointCount - 1];
dgBigVector e1 (p1 - p0);
dgBigVector e2 (p2 - p0);
dgBigVector n (e1 * e2);
dgFloat64 mag3 = n % n;
if (mag3 < dgFloat64 (DG_MESH_EFFECT_PRECISION_SCALE_INV * DG_MESH_EFFECT_PRECISION_SCALE_INV)) {
m_pointCount -= 3;
m_atribCount -= 3;
}
}
}
#ifndef _NEWTON_USE_DOUBLE
void dgMeshEffect::AddPolygon (dgInt32 count, const dgFloat32* const vertexList, dgInt32 strideIndBytes, dgInt32 material)
{
dgVertexAtribute points[256];
dgAssert (count < dgInt32 (sizeof (points)/sizeof (points[0])));
dgInt32 stride = strideIndBytes / sizeof (dgFloat32);
if (stride < 4) {
for (dgInt32 i = 0; i < count; i ++) {
points[i].m_vertex.m_x = vertexList[i * stride + 0];
points[i].m_vertex.m_y = vertexList[i * stride + 1];
points[i].m_vertex.m_z = vertexList[i * stride + 2];
points[i].m_vertex.m_w = dgFloat64(0.0f);
points[i].m_normal_x = dgFloat64(0.0f);
points[i].m_normal_y = dgFloat64(1.0f);
points[i].m_normal_z = dgFloat64(0.0f);
points[i].m_u0 = dgFloat64(0.0f);
points[i].m_v0 = dgFloat64(0.0f);
points[i].m_u1 = dgFloat64(0.0f);
points[i].m_v1 = dgFloat64(0.0f);
points[i].m_material = dgFloat64(material);
}
} else {
for (dgInt32 i = 0; i < count; i ++) {
points[i].m_vertex.m_x = vertexList[i * stride + 0];
points[i].m_vertex.m_y = vertexList[i * stride + 1];
points[i].m_vertex.m_z = vertexList[i * stride + 2];
points[i].m_vertex.m_w = vertexList[i * stride + 3];
points[i].m_normal_x = vertexList[i * stride + 4];
points[i].m_normal_y = vertexList[i * stride + 5];
points[i].m_normal_z = vertexList[i * stride + 6];
points[i].m_u0 = vertexList[i * stride + 7];
points[i].m_v0 = vertexList[i * stride + 8];
points[i].m_u1 = vertexList[i * stride + 9];
points[i].m_v1 = vertexList[i * stride + 10];
points[i].m_material = dgFloat64(material);
}
}
AddPolygon (count, &points[0].m_vertex.m_x, sizeof (dgVertexAtribute), material);
}
#endif
void dgMeshEffect::EndPolygon (dgFloat64 tol, bool fixTjoint)
{
dgStack<dgInt32>indexMap(m_pointCount);
dgStack<dgInt32>attrIndexMap(m_atribCount);
#ifdef _DEBUG
for (dgInt32 i = 0; i < m_pointCount; i += 3) {
dgBigVector p0 (m_points[i + 0]);
dgBigVector p1 (m_points[i + 1]);
dgBigVector p2 (m_points[i + 2]);
dgBigVector e1 (p1 - p0);
dgBigVector e2 (p2 - p0);
dgBigVector n (e1 * e2);
dgFloat64 mag2 = n % n;
dgAssert (mag2 > dgFloat32 (0.0f));
}
#endif
dgInt32 triangCount = m_pointCount / 3;
m_pointCount = dgVertexListToIndexList (&m_points[0].m_x, sizeof (dgBigVector), sizeof (dgBigVector)/sizeof (dgFloat64), m_pointCount, &indexMap[0], tol);
m_atribCount = dgVertexListToIndexList (&m_attrib[0].m_vertex.m_x, sizeof (dgVertexAtribute), sizeof (dgVertexAtribute)/sizeof (dgFloat64), m_atribCount, &attrIndexMap[0], tol);
for (dgInt32 i = 0; i < triangCount; i ++) {
dgInt32 index[3];
dgInt64 userdata[3];
index[0] = indexMap[i * 3 + 0];
index[1] = indexMap[i * 3 + 1];
index[2] = indexMap[i * 3 + 2];
dgBigVector e1 (m_points[index[1]] - m_points[index[0]]);
dgBigVector e2 (m_points[index[2]] - m_points[index[0]]);
dgBigVector n (e1 * e2);
dgFloat64 mag2 = n % n;
if (mag2 > dgFloat64 (1.0e-12f)) {
userdata[0] = attrIndexMap[i * 3 + 0];
userdata[1] = attrIndexMap[i * 3 + 1];
userdata[2] = attrIndexMap[i * 3 + 2];
dgEdge* const edge = AddFace (3, index, userdata);
if (!edge) {
dgAssert ((m_pointCount + 3) <= m_maxPointCount);
m_points[m_pointCount + 0] = m_points[index[0]];
m_points[m_pointCount + 1] = m_points[index[1]];
m_points[m_pointCount + 2] = m_points[index[2]];
index[0] = m_pointCount + 0;
index[1] = m_pointCount + 1;
index[2] = m_pointCount + 2;
m_pointCount += 3;
#ifdef _DEBUG
dgEdge* test = AddFace (3, index, userdata);
dgAssert (test);
#else
AddFace (3, index, userdata);
#endif
}
}
}
EndFace();
if (fixTjoint) {
RepairTJoints ();
}
#ifdef _DEBUG
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; iter ++){
dgEdge* const face = &(*iter);
if (face->m_incidentFace > 0) {
dgBigVector p0 (m_points[face->m_incidentVertex]);
dgBigVector p1 (m_points[face->m_next->m_incidentVertex]);
dgBigVector p2 (m_points[face->m_next->m_next->m_incidentVertex]);
dgBigVector e1 (p1 - p0);
dgBigVector e2 (p2 - p0);
dgBigVector n (e1 * e2);
dgFloat64 mag2 = n % n;
dgAssert (mag2 >= dgFloat32 (0.0f));
}
}
#endif
}
void dgMeshEffect::BuildFromVertexListIndexList(
dgInt32 faceCount, const dgInt32* const faceIndexCount, const dgInt32* const faceMaterialIndex,
const dgFloat32* const vertex, dgInt32 vertexStrideInBytes, const dgInt32* const vertexIndex,
const dgFloat32* const normal, dgInt32 normalStrideInBytes, const dgInt32* const normalIndex,
const dgFloat32* const uv0, dgInt32 uv0StrideInBytes, const dgInt32* const uv0Index,
const dgFloat32* const uv1, dgInt32 uv1StrideInBytes, const dgInt32* const uv1Index)
{
BeginPolygon ();
// calculate vertex Count
dgInt32 acc = 0;
dgInt32 vertexCount = 0;
for (dgInt32 j = 0; j < faceCount; j ++) {
dgInt32 count = faceIndexCount[j];
for (dgInt32 i = 0; i < count; i ++) {
vertexCount = dgMax(vertexCount, vertexIndex[acc + i] + 1);
}
acc += count;
}
dgInt32 layerCountBase = 0;
dgInt32 vertexStride = dgInt32 (vertexStrideInBytes / sizeof (dgFloat32));
for (dgInt32 i = 0; i < vertexCount; i ++) {
dgInt32 index = i * vertexStride;
dgBigVector v (vertex[index + 0], vertex[index + 1], vertex[index + 2], vertex[index + 3]);
AddVertex (v);
layerCountBase += (vertex[index + 3]) > dgFloat32(layerCountBase);
}
dgInt32 maxAttribCount = 0;
for (dgInt32 j = 0; j < faceCount; j ++) {
maxAttribCount += faceIndexCount[j];
}
dgStack<dgInt32>attrIndexMap(maxAttribCount);
acc = 0;
dgInt32 currentCount = 0;
dgInt32 attributeCount = 0;
dgInt32 attributeCountMarker = 0;
dgInt32 normalStride = dgInt32 (normalStrideInBytes / sizeof (dgFloat32));
dgInt32 uv0Stride = dgInt32 (uv0StrideInBytes / sizeof (dgFloat32));
dgInt32 uv1Stride = dgInt32 (uv1StrideInBytes / sizeof (dgFloat32));
for (dgInt32 j = 0; j < faceCount; j ++) {
dgInt32 indexCount = faceIndexCount[j];
dgInt32 materialIndex = faceMaterialIndex[j];
for (dgInt32 i = 0; i < indexCount; i ++) {
dgVertexAtribute point;
dgInt32 index = vertexIndex[acc + i];
point.m_vertex = m_points[index];
index = normalIndex[(acc + i)] * normalStride;
point.m_normal_x = normal[index + 0];
point.m_normal_y = normal[index + 1];
point.m_normal_z = normal[index + 2];
index = uv0Index[(acc + i)] * uv0Stride;
point.m_u0 = uv0[index + 0];
point.m_v0 = uv0[index + 1];
index = uv1Index[(acc + i)] * uv1Stride;
point.m_u1 = uv1[index + 0];
point.m_v1 = uv1[index + 1];
point.m_material = materialIndex;
AddAtribute(point);
attrIndexMap[attributeCount] = attributeCount;
attributeCount ++;
}
acc += indexCount;
if (attributeCount >= (attributeCountMarker + 1024 * 256)) {
dgInt32 count = attributeCount - attributeCountMarker;
dgInt32 newCount = dgVertexListToIndexList (&m_attrib[currentCount].m_vertex.m_x, sizeof (dgVertexAtribute), sizeof (dgVertexAtribute) / sizeof (dgFloat64), count, &attrIndexMap[attributeCountMarker], DG_VERTEXLIST_INDEXLIST_TOL);
for (dgInt32 i = 0; i < count; i ++) {
attrIndexMap[attributeCountMarker + i] += currentCount;
}
currentCount += newCount;
m_atribCount = currentCount;
attributeCountMarker = attributeCount;
}
}
if (attributeCountMarker) {
dgInt32 count = attributeCount - attributeCountMarker;
dgInt32 newCount = dgVertexListToIndexList (&m_attrib[currentCount].m_vertex.m_x, sizeof (dgVertexAtribute), sizeof (dgVertexAtribute) / sizeof (dgFloat64), count, &attrIndexMap[attributeCountMarker], DG_VERTEXLIST_INDEXLIST_TOL);
for (dgInt32 i = 0; i < count; i ++) {
attrIndexMap[attributeCountMarker + i] += currentCount;
}
currentCount += newCount;
m_atribCount = currentCount;
attributeCountMarker = attributeCount;
dgStack<dgInt32>indirectAttrIndexMap(m_atribCount);
m_atribCount = dgVertexListToIndexList (&m_attrib[0].m_vertex.m_x, sizeof (dgVertexAtribute), sizeof (dgVertexAtribute) / sizeof (dgFloat64), m_atribCount, &indirectAttrIndexMap[0], DG_VERTEXLIST_INDEXLIST_TOL);
for (dgInt32 i = 0; i < maxAttribCount; i ++) {
dgInt32 j = attrIndexMap[i];
attrIndexMap[i] = indirectAttrIndexMap[j];
}
} else {
m_atribCount = dgVertexListToIndexList (&m_attrib[0].m_vertex.m_x, sizeof (dgVertexAtribute), sizeof (dgVertexAtribute) / sizeof (dgFloat64), m_atribCount, &attrIndexMap[0], DG_VERTEXLIST_INDEXLIST_TOL);
}
bool hasFaces = true;
dgStack<dgInt8> faceMark (faceCount);
memset (&faceMark[0], 1, size_t (faceMark.GetSizeInBytes()));
dgInt32 layerCount = 0;
while (hasFaces) {
acc = 0;
hasFaces = false;
dgInt32 vertexBank = layerCount * vertexCount;
for (dgInt32 j = 0; j < faceCount; j ++) {
int indexCount = faceIndexCount[j];
if (indexCount > 0) {
dgInt32 index[256];
dgInt64 userdata[256];
dgAssert (indexCount >= 3);
dgAssert (indexCount < dgInt32 (sizeof (index) / sizeof (index[0])));
if (faceMark[j]) {
for (int i = 0; i < indexCount; i ++) {
index[i] = vertexIndex[acc + i] + vertexBank;
userdata[i] = attrIndexMap[acc + i];
}
dgEdge* const edge = AddFace (indexCount, index, userdata);
if (edge) {
faceMark[j] = 0;
} else {
// check if the face is not degenerated
bool degeneratedFace = false;
for (int i = 0; i < indexCount - 1; i ++) {
for (int k = i + 1; k < indexCount; k ++) {
if (index[i] == index[k]) {
degeneratedFace = true;
}
}
}
if (degeneratedFace) {
faceMark[j] = 0;
} else {
hasFaces = true;
}
}
}
acc += indexCount;
}
}
if (hasFaces) {
layerCount ++;
for (int i = 0; i < vertexCount; i ++) {
int index = i * vertexStride;
AddVertex (dgBigVector (vertex[index + 0], vertex[index + 1], vertex[index + 2], dgFloat64 (layerCount + layerCountBase)));
}
}
}
EndFace();
PackVertexArrays ();
}
dgInt32 dgMeshEffect::GetTotalFaceCount() const
{
return GetFaceCount();
}
dgInt32 dgMeshEffect::GetTotalIndexCount() const
{
Iterator iter (*this);
dgInt32 count = 0;
dgInt32 mark = IncLRU();
for (iter.Begin(); iter; iter ++) {
dgEdge* const edge = &(*iter);
if (edge->m_mark == mark) {
continue;
}
if (edge->m_incidentFace < 0) {
continue;
}
dgEdge* ptr = edge;
do {
count ++;
ptr->m_mark = mark;
ptr = ptr->m_next;
} while (ptr != edge);
}
return count;
}
void dgMeshEffect::GetFaces (dgInt32* const facesIndex, dgInt32* const materials, void** const faceNodeList) const
{
Iterator iter (*this);
dgInt32 faces = 0;
dgInt32 indexCount = 0;
dgInt32 mark = IncLRU();
for (iter.Begin(); iter; iter ++) {
dgEdge* const edge = &(*iter);
if (edge->m_mark == mark) {
continue;
}
if (edge->m_incidentFace < 0) {
continue;
}
dgInt32 faceCount = 0;
dgEdge* ptr = edge;
do {
// indexList[indexCount] = dgInt32 (ptr->m_userData);
faceNodeList[indexCount] = GetNodeFromInfo (*ptr);
indexCount ++;
faceCount ++;
ptr->m_mark = mark;
ptr = ptr->m_next;
} while (ptr != edge);
facesIndex[faces] = faceCount;
materials[faces] = dgFastInt(m_attrib[dgInt32 (edge->m_userData)].m_material);
faces ++;
}
}
void* dgMeshEffect::GetFirstVertex () const
{
Iterator iter (*this);
iter.Begin();
dgTreeNode* node = NULL;
if (iter) {
dgInt32 mark = IncLRU();
node = iter.GetNode();
dgEdge* const edge = &node->GetInfo();
dgEdge* ptr = edge;
do {
ptr->m_mark = mark;
ptr = ptr->m_twin->m_next;
} while (ptr != edge);
}
return node;
}
void* dgMeshEffect::GetNextVertex (const void* const vertex) const
{
dgTreeNode* node = (dgTreeNode*) vertex;
dgInt32 mark = node->GetInfo().m_mark;
Iterator iter (*this);
iter.Set (node);
for (iter ++; iter; iter ++) {
dgTreeNode* node = iter.GetNode();
if (node->GetInfo().m_mark != mark) {
dgEdge* const edge = &node->GetInfo();
dgEdge* ptr = edge;
do {
ptr->m_mark = mark;
ptr = ptr->m_twin->m_next;
} while (ptr != edge);
return node;
}
}
return NULL;
}
dgInt32 dgMeshEffect::GetVertexIndex (const void* const vertex) const
{
dgTreeNode* const node = (dgTreeNode*) vertex;
dgEdge* const edge = &node->GetInfo();
return edge->m_incidentVertex;
}
void* dgMeshEffect::GetFirstPoint () const
{
Iterator iter (*this);
for (iter.Begin(); iter; iter ++) {
dgTreeNode* const node = iter.GetNode();
dgEdge* const edge = &node->GetInfo();
if (edge->m_incidentFace > 0) {
return node;
}
}
return NULL;
}
void* dgMeshEffect::GetNextPoint (const void* const point) const
{
Iterator iter (*this);
iter.Set ((dgTreeNode*) point);
for (iter ++; iter; iter ++) {
dgTreeNode* const node = iter.GetNode();
dgEdge* const edge = &node->GetInfo();
if (edge->m_incidentFace > 0) {
return node;
}
}
return NULL;
}
dgInt32 dgMeshEffect::GetPointIndex (const void* const point) const
{
dgTreeNode* const node = (dgTreeNode*) point;
dgEdge* const edge = &node->GetInfo();
return int (edge->m_userData);
}
dgInt32 dgMeshEffect::GetVertexIndexFromPoint (const void* const point) const
{
return GetVertexIndex (point);
}
dgEdge* dgMeshEffect::SpliteFace (dgInt32 v0, dgInt32 v1)
{
if (!FindEdge(v0, v1)) {
dgPolyhedra::dgPairKey key (v0, 0);
dgTreeNode* const node = FindGreaterEqual(key.GetVal());
if (node) {
dgEdge* const edge = &node->GetInfo();
dgEdge* edge0 = edge;
do {
if (edge0->m_incidentFace > 0) {
for (dgEdge* edge1 = edge0->m_next->m_next; edge1 != edge0->m_prev; edge1 = edge1->m_next) {
if (edge1->m_incidentVertex == v1) {
return ConnectVertex (edge0, edge1);
}
};
}
edge0 = edge0->m_twin->m_next;
} while (edge0 != edge);
}
}
return NULL;
}
void* dgMeshEffect::GetFirstEdge () const
{
Iterator iter (*this);
iter.Begin();
dgTreeNode* node = NULL;
if (iter) {
dgInt32 mark = IncLRU();
node = iter.GetNode();
dgEdge* const edge = &node->GetInfo();
edge->m_mark = mark;
edge->m_twin->m_mark = mark;
}
return node;
}
void* dgMeshEffect::GetNextEdge (const void* const edge) const
{
dgTreeNode* node = (dgTreeNode*) edge;
dgInt32 mark = node->GetInfo().m_mark;
Iterator iter (*this);
iter.Set (node);
for (iter ++; iter; iter ++) {
dgTreeNode* node = iter.GetNode();
if (node->GetInfo().m_mark != mark) {
node->GetInfo().m_mark = mark;
node->GetInfo().m_twin->m_mark = mark;
return node;
}
}
return NULL;
}
void dgMeshEffect::GetEdgeIndex (const void* const edge, dgInt32& v0, dgInt32& v1) const
{
dgTreeNode* node = (dgTreeNode*) edge;
v0 = node->GetInfo().m_incidentVertex;
v1 = node->GetInfo().m_twin->m_incidentVertex;
}
//void* dgMeshEffect::FindEdge (dgInt32 v0, dgInt32 v1) const
//{
// return FindEdgeNode(v0, v1);
//}
//void dgMeshEffect::GetEdgeAttributeIndex (const void* edge, dgInt32& v0, dgInt32& v1) const
//{
// dgTreeNode* node = (dgTreeNode*) edge;
// v0 = int (node->GetInfo().m_userData);
// v1 = int (node->GetInfo().m_twin->m_userData);
//}
void* dgMeshEffect::GetFirstFace () const
{
Iterator iter (*this);
iter.Begin();
dgTreeNode* node = NULL;
if (iter) {
dgInt32 mark = IncLRU();
node = iter.GetNode();
dgEdge* const edge = &node->GetInfo();
dgEdge* ptr = edge;
do {
ptr->m_mark = mark;
ptr = ptr->m_next;
} while (ptr != edge);
}
return node;
}
void* dgMeshEffect::GetNextFace (const void* const face) const
{
dgTreeNode* node = (dgTreeNode*) face;
dgInt32 mark = node->GetInfo().m_mark;
Iterator iter (*this);
iter.Set (node);
for (iter ++; iter; iter ++) {
dgTreeNode* node = iter.GetNode();
if (node->GetInfo().m_mark != mark) {
dgEdge* const edge = &node->GetInfo();
dgEdge* ptr = edge;
do {
ptr->m_mark = mark;
ptr = ptr->m_next;
} while (ptr != edge);
return node;
}
}
return NULL;
}
dgInt32 dgMeshEffect::IsFaceOpen (const void* const face) const
{
dgTreeNode* const node = (dgTreeNode*) face;
dgEdge* const edge = &node->GetInfo();
return (edge->m_incidentFace > 0) ? 0 : 1;
}
dgInt32 dgMeshEffect::GetFaceMaterial (const void* const face) const
{
dgTreeNode* const node = (dgTreeNode*) face;
dgEdge* const edge = &node->GetInfo();
return dgInt32 (m_attrib[edge->m_userData].m_material);
}
void dgMeshEffect::SetFaceMaterial (const void* const face, int mateialID) const
{
dgTreeNode* const node = (dgTreeNode*) face;
dgEdge* const edge = &node->GetInfo();
if (edge->m_incidentFace > 0) {
dgEdge* ptr = edge;
do {
dgVertexAtribute* const attrib = &m_attrib[ptr->m_userData];
attrib->m_material = dgFloat64 (mateialID);
ptr = ptr->m_next;
} while (ptr != edge) ;
}
}
dgInt32 dgMeshEffect::GetFaceIndexCount (const void* const face) const
{
int count = 0;
dgTreeNode* node = (dgTreeNode*) face;
dgEdge* const edge = &node->GetInfo();
dgEdge* ptr = edge;
do {
count ++;
ptr = ptr->m_next;
} while (ptr != edge);
return count;
}
void dgMeshEffect::GetFaceIndex (const void* const face, dgInt32* const indices) const
{
int count = 0;
dgTreeNode* node = (dgTreeNode*) face;
dgEdge* const edge = &node->GetInfo();
dgEdge* ptr = edge;
do {
indices[count] = ptr->m_incidentVertex;
count ++;
ptr = ptr->m_next;
} while (ptr != edge);
}
void dgMeshEffect::GetFaceAttributeIndex (const void* const face, dgInt32* const indices) const
{
int count = 0;
dgTreeNode* node = (dgTreeNode*) face;
dgEdge* const edge = &node->GetInfo();
dgEdge* ptr = edge;
do {
indices[count] = int (ptr->m_userData);
count ++;
ptr = ptr->m_next;
} while (ptr != edge);
}
dgBigVector dgMeshEffect::CalculateFaceNormal (const void* const face) const
{
dgTreeNode* const node = (dgTreeNode*) face;
dgEdge* const faceEdge = &node->GetInfo();
dgBigVector normal (FaceNormal (faceEdge, &m_points[0].m_x, sizeof (m_points[0])));
normal = normal.Scale3 (1.0f / sqrt (normal % normal));
return normal;
}
/*
dgInt32 GetTotalFaceCount() const;
{
dgInt32 mark;
dgInt32 count;
dgInt32 materialCount;
dgInt32 materials[256];
dgInt32 streamIndexMap[256];
dgIndexArray* array;
count = 0;
materialCount = 0;
array = (dgIndexArray*) GetAllocator()->MallocLow (4 * sizeof (dgInt32) * GetCount() + sizeof (dgIndexArray) + 2048);
array->m_indexList = (dgInt32*)&array[1];
mark = IncLRU();
dgPolyhedra::Iterator iter (*this);
memset(streamIndexMap, 0, sizeof (streamIndexMap));
for(iter.Begin(); iter; iter ++){
dgEdge* const edge;
edge = &(*iter);
if ((edge->m_incidentFace >= 0) && (edge->m_mark != mark)) {
dgEdge* ptr;
dgInt32 hashValue;
dgInt32 index0;
dgInt32 index1;
ptr = edge;
ptr->m_mark = mark;
index0 = dgInt32 (ptr->m_userData);
ptr = ptr->m_next;
ptr->m_mark = mark;
index1 = dgInt32 (ptr->m_userData);
ptr = ptr->m_next;
do {
ptr->m_mark = mark;
array->m_indexList[count * 4 + 0] = index0;
array->m_indexList[count * 4 + 1] = index1;
array->m_indexList[count * 4 + 2] = dgInt32 (ptr->m_userData);
array->m_indexList[count * 4 + 3] = m_attrib[dgInt32 (edge->m_userData)].m_material;
index1 = dgInt32 (ptr->m_userData);
hashValue = array->m_indexList[count * 4 + 3] & 0xff;
streamIndexMap[hashValue] ++;
materials[hashValue] = array->m_indexList[count * 4 + 3];
count ++;
ptr = ptr->m_next;
} while (ptr != edge);
}
}
*/
void dgMeshEffect::GetVertexStreams (dgInt32 vetexStrideInByte, dgFloat32* const vertex,
dgInt32 normalStrideInByte, dgFloat32* const normal,
dgInt32 uvStrideInByte0, dgFloat32* const uv0,
dgInt32 uvStrideInByte1, dgFloat32* const uv1)
{
uvStrideInByte0 /= sizeof (dgFloat32);
uvStrideInByte1 /= sizeof (dgFloat32);
vetexStrideInByte /= sizeof (dgFloat32);
normalStrideInByte /= sizeof (dgFloat32);
for (dgInt32 i = 0; i < m_atribCount; i ++) {
dgInt32 j = i * vetexStrideInByte;
vertex[j + 0] = dgFloat32 (m_attrib[i].m_vertex.m_x);
vertex[j + 1] = dgFloat32 (m_attrib[i].m_vertex.m_y);
vertex[j + 2] = dgFloat32 (m_attrib[i].m_vertex.m_z);
j = i * normalStrideInByte;
normal[j + 0] = dgFloat32 (m_attrib[i].m_normal_x);
normal[j + 1] = dgFloat32 (m_attrib[i].m_normal_y);
normal[j + 2] = dgFloat32 (m_attrib[i].m_normal_z);
j = i * uvStrideInByte1;
uv1[j + 0] = dgFloat32 (m_attrib[i].m_u1);
uv1[j + 1] = dgFloat32 (m_attrib[i].m_v1);
j = i * uvStrideInByte0;
uv0[j + 0] = dgFloat32 (m_attrib[i].m_u0);
uv0[j + 1] = dgFloat32 (m_attrib[i].m_v0);
}
}
void dgMeshEffect::GetIndirectVertexStreams(
dgInt32 vetexStrideInByte, dgFloat64* const vertex, dgInt32* const vertexIndices, dgInt32* const vertexCount,
dgInt32 normalStrideInByte, dgFloat64* const normal, dgInt32* const normalIndices, dgInt32* const normalCount,
dgInt32 uvStrideInByte0, dgFloat64* const uv0, dgInt32* const uvIndices0, dgInt32* const uvCount0,
dgInt32 uvStrideInByte1, dgFloat64* const uv1, dgInt32* const uvIndices1, dgInt32* const uvCount1)
{
/*
GetVertexStreams (vetexStrideInByte, vertex, normalStrideInByte, normal, uvStrideInByte0, uv0, uvStrideInByte1, uv1);
*vertexCount = dgVertexListToIndexList(vertex, vetexStrideInByte, vetexStrideInByte, 0, m_atribCount, vertexIndices, dgFloat32 (0.0f));
*normalCount = dgVertexListToIndexList(normal, normalStrideInByte, normalStrideInByte, 0, m_atribCount, normalIndices, dgFloat32 (0.0f));
dgTriplex* const tmpUV = (dgTriplex*) GetAllocator()->MallocLow (dgInt32 (sizeof (dgTriplex) * m_atribCount));
dgInt32 stride = dgInt32 (uvStrideInByte1 /sizeof (dgFloat32));
for (dgInt32 i = 0; i < m_atribCount; i ++){
tmpUV[i].m_x = uv1[i * stride + 0];
tmpUV[i].m_y = uv1[i * stride + 1];
tmpUV[i].m_z = dgFloat32 (0.0f);
}
dgInt32 count = dgVertexListToIndexList(&tmpUV[0].m_x, sizeof (dgTriplex), sizeof (dgTriplex), 0, m_atribCount, uvIndices1, dgFloat32 (0.0f));
for (dgInt32 i = 0; i < count; i ++){
uv1[i * stride + 0] = tmpUV[i].m_x;
uv1[i * stride + 1] = tmpUV[i].m_y;
}
*uvCount1 = count;
stride = dgInt32 (uvStrideInByte0 /sizeof (dgFloat32));
for (dgInt32 i = 0; i < m_atribCount; i ++){
tmpUV[i].m_x = uv0[i * stride + 0];
tmpUV[i].m_y = uv0[i * stride + 1];
tmpUV[i].m_z = dgFloat32 (0.0f);
}
count = dgVertexListToIndexList(&tmpUV[0].m_x, sizeof (dgTriplex), sizeof (dgTriplex), 0, m_atribCount, uvIndices0, dgFloat32 (0.0f));
for (dgInt32 i = 0; i < count; i ++){
uv0[i * stride + 0] = tmpUV[i].m_x;
uv0[i * stride + 1] = tmpUV[i].m_y;
}
*uvCount0 = count;
GetAllocator()->FreeLow (tmpUV);
*/
}
dgMeshEffect::dgIndexArray* dgMeshEffect::MaterialGeometryBegin()
{
dgInt32 materials[256];
dgInt32 streamIndexMap[256];
dgInt32 count = 0;
dgInt32 materialCount = 0;
dgIndexArray* const array = (dgIndexArray*) GetAllocator()->MallocLow (dgInt32 (4 * sizeof (dgInt32) * GetCount() + sizeof (dgIndexArray) + 2048));
array->m_indexList = (dgInt32*)&array[1];
dgInt32 mark = IncLRU();
dgPolyhedra::Iterator iter (*this);
memset(streamIndexMap, 0, sizeof (streamIndexMap));
for(iter.Begin(); iter; iter ++){
dgEdge* const edge = &(*iter);
if ((edge->m_incidentFace >= 0) && (edge->m_mark != mark)) {
dgEdge* ptr = edge;
ptr->m_mark = mark;
dgInt32 index0 = dgInt32 (ptr->m_userData);
ptr = ptr->m_next;
ptr->m_mark = mark;
dgInt32 index1 = dgInt32 (ptr->m_userData);
ptr = ptr->m_next;
do {
ptr->m_mark = mark;
array->m_indexList[count * 4 + 0] = index0;
array->m_indexList[count * 4 + 1] = index1;
array->m_indexList[count * 4 + 2] = dgInt32 (ptr->m_userData);
array->m_indexList[count * 4 + 3] = dgInt32 (m_attrib[dgInt32 (edge->m_userData)].m_material);
index1 = dgInt32 (ptr->m_userData);
dgInt32 hashValue = array->m_indexList[count * 4 + 3] & 0xff;
streamIndexMap[hashValue] ++;
materials[hashValue] = array->m_indexList[count * 4 + 3];
count ++;
ptr = ptr->m_next;
} while (ptr != edge);
}
}
array->m_indexCount = count;
array->m_materialCount = materialCount;
count = 0;
for (dgInt32 i = 0; i < 256;i ++) {
if (streamIndexMap[i]) {
array->m_materials[count] = materials[i];
array->m_materialsIndexCount[count] = streamIndexMap[i] * 3;
count ++;
}
}
array->m_materialCount = count;
return array;
}
void dgMeshEffect::MaterialGeomteryEnd(dgIndexArray* const handle)
{
GetAllocator()->FreeLow (handle);
}
dgInt32 dgMeshEffect::GetFirstMaterial (dgIndexArray* const handle) const
{
return GetNextMaterial (handle, -1);
}
dgInt32 dgMeshEffect::GetNextMaterial (dgIndexArray* const handle, dgInt32 materialId) const
{
materialId ++;
if(materialId >= handle->m_materialCount) {
materialId = -1;
}
return materialId;
}
void dgMeshEffect::GetMaterialGetIndexStream (dgIndexArray* const handle, dgInt32 materialHandle, dgInt32* const indexArray) const
{
dgInt32 index = 0;
dgInt32 textureID = handle->m_materials[materialHandle];
for (dgInt32 j = 0; j < handle->m_indexCount; j ++) {
if (handle->m_indexList[j * 4 + 3] == textureID) {
indexArray[index + 0] = handle->m_indexList[j * 4 + 0];
indexArray[index + 1] = handle->m_indexList[j * 4 + 1];
indexArray[index + 2] = handle->m_indexList[j * 4 + 2];
index += 3;
}
}
}
void dgMeshEffect::GetMaterialGetIndexStreamShort (dgIndexArray* const handle, dgInt32 materialHandle, dgInt16* const indexArray) const
{
dgInt32 index = 0;
dgInt32 textureID = handle->m_materials[materialHandle];
for (dgInt32 j = 0; j < handle->m_indexCount; j ++) {
if (handle->m_indexList[j * 4 + 3] == textureID) {
indexArray[index + 0] = (dgInt16)handle->m_indexList[j * 4 + 0];
indexArray[index + 1] = (dgInt16)handle->m_indexList[j * 4 + 1];
indexArray[index + 2] = (dgInt16)handle->m_indexList[j * 4 + 2];
index += 3;
}
}
}
dgCollisionInstance* dgMeshEffect::CreateCollisionTree(dgWorld* const world, dgInt32 shapeID) const
{
dgCollisionBVH* const collision = new (GetAllocator()) dgCollisionBVH (world);
collision->BeginBuild();
dgInt32 mark = IncLRU();
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; iter ++){
dgEdge* const face = &(*iter);
if ((face->m_mark != mark) && (face->m_incidentFace > 0)) {
dgInt32 count = 0;
dgVector polygon[256];
dgEdge* ptr = face;
do {
polygon[count] = dgVector (m_points[ptr->m_incidentVertex]);
polygon[count].m_w = dgFloat32 (0.0f);
count ++;
ptr->m_mark = mark;
ptr = ptr->m_next;
} while (ptr != face);
collision->AddFace(count, &polygon[0].m_x, sizeof (dgVector), dgInt32 (m_attrib[face->m_userData].m_material));
}
}
collision->EndBuild(0);
dgCollisionInstance* const instance = world->CreateInstance(collision, shapeID, dgGetIdentityMatrix());
collision->Release();
return instance;
}
dgCollisionInstance* dgMeshEffect::CreateConvexCollision(dgWorld* const world, dgFloat64 tolerance, dgInt32 shapeID, const dgMatrix& srcMatrix) const
{
dgStack<dgVector> poolPtr (m_pointCount * 2);
dgVector* const pool = &poolPtr[0];
dgBigVector minBox;
dgBigVector maxBox;
CalculateAABB (minBox, maxBox);
dgVector com ((minBox + maxBox).Scale3 (dgFloat32 (0.5f)));
dgInt32 count = 0;
dgInt32 mark = IncLRU();
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; iter ++){
dgEdge* const vertex = &(*iter);
if (vertex->m_mark != mark) {
dgEdge* ptr = vertex;
do {
ptr->m_mark = mark;
ptr = ptr->m_twin->m_next;
} while (ptr != vertex);
if (count < dgInt32 (poolPtr.GetElementsCount())) {
const dgBigVector p = m_points[vertex->m_incidentVertex];
pool[count] = dgVector (p) - com;
count ++;
}
}
}
dgMatrix matrix (srcMatrix);
matrix.m_posit += matrix.RotateVector(com);
matrix.m_posit.m_w = dgFloat32 (1.0f);
dgUnsigned32 crc = dgCollisionConvexHull::CalculateSignature (count, &pool[0].m_x, sizeof (dgVector));
dgCollisionConvexHull* const collision = new (GetAllocator()) dgCollisionConvexHull (GetAllocator(), crc, count, sizeof (dgVector), dgFloat32 (tolerance), &pool[0].m_x);
if (!collision->GetConvexVertexCount()) {
collision->Release();
return NULL;
}
dgCollisionInstance* const instance = world->CreateInstance(collision, shapeID, matrix);
collision->Release();
return instance;
}
void dgMeshEffect::TransformMesh (const dgMatrix& matrix)
{
dgMatrix normalMatrix (matrix);
normalMatrix.m_posit = dgVector (dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (1.0f));
matrix.TransformTriplex (&m_points->m_x, sizeof (dgBigVector), &m_points->m_x, sizeof (dgBigVector), m_pointCount);
matrix.TransformTriplex (&m_attrib[0].m_vertex.m_x, sizeof (dgVertexAtribute), &m_attrib[0].m_vertex.m_x, sizeof (dgVertexAtribute), m_atribCount);
normalMatrix.TransformTriplex (&m_attrib[0].m_normal_x, sizeof (dgVertexAtribute), &m_attrib[0].m_normal_x, sizeof (dgVertexAtribute), m_atribCount);
}
dgMeshEffect::dgVertexAtribute dgMeshEffect::InterpolateEdge (dgEdge* const edge, dgFloat64 param) const
{
dgVertexAtribute attrEdge;
dgFloat64 t1 = param;
dgFloat64 t0 = dgFloat64 (1.0f) - t1;
dgAssert (t1 >= dgFloat64(0.0f));
dgAssert (t1 <= dgFloat64(1.0f));
const dgVertexAtribute& attrEdge0 = m_attrib[edge->m_userData];
const dgVertexAtribute& attrEdge1 = m_attrib[edge->m_next->m_userData];
attrEdge.m_vertex.m_x = attrEdge0.m_vertex.m_x * t0 + attrEdge1.m_vertex.m_x * t1;
attrEdge.m_vertex.m_y = attrEdge0.m_vertex.m_y * t0 + attrEdge1.m_vertex.m_y * t1;
attrEdge.m_vertex.m_z = attrEdge0.m_vertex.m_z * t0 + attrEdge1.m_vertex.m_z * t1;
attrEdge.m_vertex.m_w = dgFloat32(0.0f);
attrEdge.m_normal_x = attrEdge0.m_normal_x * t0 + attrEdge1.m_normal_x * t1;
attrEdge.m_normal_y = attrEdge0.m_normal_y * t0 + attrEdge1.m_normal_y * t1;
attrEdge.m_normal_z = attrEdge0.m_normal_z * t0 + attrEdge1.m_normal_z * t1;
attrEdge.m_u0 = attrEdge0.m_u0 * t0 + attrEdge1.m_u0 * t1;
attrEdge.m_v0 = attrEdge0.m_v0 * t0 + attrEdge1.m_v0 * t1;
attrEdge.m_u1 = attrEdge0.m_u1 * t0 + attrEdge1.m_u1 * t1;
attrEdge.m_v1 = attrEdge0.m_v1 * t0 + attrEdge1.m_v1 * t1;
attrEdge.m_material = attrEdge0.m_material;
return attrEdge;
}
bool dgMeshEffect::Sanity () const
{
#ifdef _DEBUG
dgMeshEffect::Iterator iter (*this);
for (iter.Begin(); iter; iter ++) {
dgEdge* const edge = &iter.GetNode()->GetInfo();
dgAssert (edge->m_twin->m_twin == edge);
dgAssert (edge->m_next->m_incidentVertex == edge->m_twin->m_incidentVertex);
dgAssert (edge->m_incidentVertex == edge->m_twin->m_next->m_incidentVertex);
if (edge->m_incidentFace > 0) {
dgBigVector p0 (m_points[edge->m_incidentVertex]);
dgBigVector p1 (m_attrib[edge->m_userData].m_vertex);
dgBigVector p1p0 (p1 - p0);
dgFloat64 mag2 (p1p0 % p1p0);
dgAssert (mag2 < 1.0e-16f);
}
}
#endif
return true;
}
dgEdge* dgMeshEffect::InsertEdgeVertex (dgEdge* const edge, dgFloat64 param)
{
dgEdge* const twin = edge->m_twin;
dgVertexAtribute attrEdge (InterpolateEdge (edge, param));
dgVertexAtribute attrTwin (InterpolateEdge (twin, dgFloat32 (1.0f) - param));
attrTwin.m_vertex = attrEdge.m_vertex;
AddPoint(&attrEdge.m_vertex.m_x, dgFastInt (attrEdge.m_material));
AddAtribute (attrTwin);
dgInt32 edgeAttrV0 = dgInt32 (edge->m_userData);
dgInt32 twinAttrV0 = dgInt32 (twin->m_userData);
dgEdge* const faceA0 = edge->m_next;
dgEdge* const faceA1 = edge->m_prev;
dgEdge* const faceB0 = twin->m_next;
dgEdge* const faceB1 = twin->m_prev;
// SpliteEdgeAndTriangulate (m_pointCount - 1, edge);
SpliteEdge (m_pointCount - 1, edge);
faceA0->m_prev->m_userData = dgUnsigned64 (m_atribCount - 2);
faceA1->m_next->m_userData = dgUnsigned64 (edgeAttrV0);
faceB0->m_prev->m_userData = dgUnsigned64 (m_atribCount - 1);
faceB1->m_next->m_userData = dgUnsigned64 (twinAttrV0);
return faceA1->m_next;
}
dgMeshEffect::dgVertexAtribute dgMeshEffect::InterpolateVertex (const dgBigVector& srcPoint, const dgEdge* const face) const
{
const dgBigVector point (srcPoint);
dgVertexAtribute attribute;
memset (&attribute, 0, sizeof (attribute));
// dgBigVector normal (FaceNormal(face, &m_points[0].m_x, sizeof(dgBigVector)));
// normal = normal.Scale3 (dgFloat64 (1.0f) / sqrt (normal % normal));
// attribute.m_vertex = srcPoint;
// attribute.m_normal_x = normal.m_x;
// attribute.m_normal_y = normal.m_y;
// attribute.m_normal_z = normal.m_z;
dgFloat64 tol = dgFloat32 (1.0e-4f);
for (dgInt32 i = 0; i < 4; i ++) {
const dgEdge* ptr = face;
const dgEdge* const edge0 = ptr;
dgBigVector q0 (m_points[ptr->m_incidentVertex]);
ptr = ptr->m_next;
const dgEdge* edge1 = ptr;
dgBigVector q1 (m_points[ptr->m_incidentVertex]);
ptr = ptr->m_next;
const dgEdge* edge2 = ptr;
do {
const dgBigVector q2 (m_points[ptr->m_incidentVertex]);
dgBigVector p10 (q1 - q0);
dgBigVector p20 (q2 - q0);
dgFloat64 dot = p20 % p10;
dgFloat64 mag1 = p10 % p10;
dgFloat64 mag2 = p20 % p20;
dgFloat64 collinear = dot * dot - mag2 * mag1;
if (fabs (collinear) > dgFloat64 (1.0e-8f)) {
dgBigVector p_p0 (point - q0);
dgBigVector p_p1 (point - q1);
dgBigVector p_p2 (point - q2);
dgFloat64 alpha1 = p10 % p_p0;
dgFloat64 alpha2 = p20 % p_p0;
dgFloat64 alpha3 = p10 % p_p1;
dgFloat64 alpha4 = p20 % p_p1;
dgFloat64 alpha5 = p10 % p_p2;
dgFloat64 alpha6 = p20 % p_p2;
dgFloat64 vc = alpha1 * alpha4 - alpha3 * alpha2;
dgFloat64 vb = alpha5 * alpha2 - alpha1 * alpha6;
dgFloat64 va = alpha3 * alpha6 - alpha5 * alpha4;
dgFloat64 den = va + vb + vc;
dgFloat64 minError = den * (-tol);
dgFloat64 maxError = den * (dgFloat32 (1.0f) + tol);
if ((va > minError) && (vb > minError) && (vc > minError) && (va < maxError) && (vb < maxError) && (vc < maxError)) {
edge2 = ptr;
den = dgFloat64 (1.0f) / (va + vb + vc);
dgFloat64 alpha0 = dgFloat32 (va * den);
dgFloat64 alpha1 = dgFloat32 (vb * den);
dgFloat64 alpha2 = dgFloat32 (vc * den);
const dgVertexAtribute& attr0 = m_attrib[edge0->m_userData];
const dgVertexAtribute& attr1 = m_attrib[edge1->m_userData];
const dgVertexAtribute& attr2 = m_attrib[edge2->m_userData];
dgBigVector normal (attr0.m_normal_x * alpha0 + attr1.m_normal_x * alpha1 + attr2.m_normal_x * alpha2,
attr0.m_normal_y * alpha0 + attr1.m_normal_y * alpha1 + attr2.m_normal_y * alpha2,
attr0.m_normal_z * alpha0 + attr1.m_normal_z * alpha1 + attr2.m_normal_z * alpha2, dgFloat32 (0.0f));
normal = normal.Scale3 (dgFloat64 (1.0f) / sqrt (normal % normal));
#ifdef _DEBUG
dgBigVector testPoint (attr0.m_vertex.m_x * alpha0 + attr1.m_vertex.m_x * alpha1 + attr2.m_vertex.m_x * alpha2,
attr0.m_vertex.m_y * alpha0 + attr1.m_vertex.m_y * alpha1 + attr2.m_vertex.m_y * alpha2,
attr0.m_vertex.m_z * alpha0 + attr1.m_vertex.m_z * alpha1 + attr2.m_vertex.m_z * alpha2, dgFloat32 (0.0f));
dgAssert (fabs (testPoint.m_x - point.m_x) < dgFloat32 (1.0e-2f));
dgAssert (fabs (testPoint.m_y - point.m_y) < dgFloat32 (1.0e-2f));
dgAssert (fabs (testPoint.m_z - point.m_z) < dgFloat32 (1.0e-2f));
#endif
attribute.m_vertex.m_x = point.m_x;
attribute.m_vertex.m_y = point.m_y;
attribute.m_vertex.m_z = point.m_z;
attribute.m_vertex.m_w = point.m_w;
attribute.m_normal_x = normal.m_x;
attribute.m_normal_y = normal.m_y;
attribute.m_normal_z = normal.m_z;
attribute.m_u0 = attr0.m_u0 * alpha0 + attr1.m_u0 * alpha1 + attr2.m_u0 * alpha2;
attribute.m_v0 = attr0.m_v0 * alpha0 + attr1.m_v0 * alpha1 + attr2.m_v0 * alpha2;
attribute.m_u1 = attr0.m_u1 * alpha0 + attr1.m_u1 * alpha1 + attr2.m_u1 * alpha2;
attribute.m_v1 = attr0.m_v1 * alpha0 + attr1.m_v1 * alpha1 + attr2.m_v1 * alpha2;
attribute.m_material = attr0.m_material;
dgAssert (attr0.m_material == attr1.m_material);
dgAssert (attr0.m_material == attr2.m_material);
return attribute;
}
}
q1 = q2;
edge1 = ptr;
ptr = ptr->m_next;
} while (ptr != face);
tol *= dgFloat64 (2.0f);
}
// this should never happens
dgAssert (0);
return attribute;
}
bool dgMeshEffect::HasOpenEdges () const
{
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; iter ++){
dgEdge* const face = &(*iter);
if (face->m_incidentFace < 0){
return true;
}
}
return false;
}
dgFloat64 dgMeshEffect::CalculateVolume () const
{
dgAssert (0);
return 0;
/*
dgPolyhedraMassProperties localData;
dgInt32 mark = IncLRU();
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; iter ++){
dgInt32 count;
dgEdge* ptr;
dgEdge* face;
dgVector points[256];
face = &(*iter);
if ((face->m_incidentFace > 0) && (face->m_mark != mark)) {
count = 0;
ptr = face;
do {
points[count] = m_points[ptr->m_incidentVertex];
count ++;
ptr->m_mark = mark;
ptr = ptr->m_next;
} while (ptr != face);
localData.AddCGFace (count, points);
}
}
dgFloat32 volume;
dgVector p0;
dgVector p1;
dgVector com;
dgVector inertia;
dgVector crossInertia;
volume = localData.MassProperties (com, inertia, crossInertia);
return volume;
*/
}
dgMeshEffect* dgMeshEffect::GetNextLayer (dgInt32 mark)
{
Iterator iter(*this);
dgEdge* edge = NULL;
for (iter.Begin (); iter; iter ++) {
edge = &(*iter);
if ((edge->m_mark < mark) && (edge->m_incidentFace > 0)) {
break;
}
}
if (!edge) {
return NULL;
}
dgInt32 layer = dgInt32 (m_points[edge->m_incidentVertex].m_w);
dgPolyhedra polyhedra(GetAllocator());
polyhedra.BeginFace ();
for (iter.Begin (); iter; iter ++) {
dgEdge* const edge = &(*iter);
if ((edge->m_mark < mark) && (edge->m_incidentFace > 0)) {
dgInt32 thislayer = dgInt32 (m_points[edge->m_incidentVertex].m_w);
if (thislayer == layer) {
dgEdge* ptr = edge;
dgInt32 count = 0;
dgInt32 faceIndex[256];
dgInt64 faceDataIndex[256];
do {
ptr->m_mark = mark;
faceIndex[count] = ptr->m_incidentVertex;
faceDataIndex[count] = ptr->m_userData;
count ++;
dgAssert (count < dgInt32 (sizeof (faceIndex)/ sizeof(faceIndex[0])));
ptr = ptr->m_next;
} while (ptr != edge);
polyhedra.AddFace (count, &faceIndex[0], &faceDataIndex[0]);
}
}
}
polyhedra.EndFace ();
dgMeshEffect* solid = NULL;
if (polyhedra.GetCount()) {
solid = new (GetAllocator()) dgMeshEffect(polyhedra, *this);
solid->SetLRU(mark);
}
return solid;
}
void dgMeshEffect::MergeFaces (const dgMeshEffect* const source)
{
dgInt32 mark = source->IncLRU();
dgPolyhedra::Iterator iter (*source);
for(iter.Begin(); iter; iter ++){
dgEdge* const edge = &(*iter);
if ((edge->m_incidentFace > 0) && (edge->m_mark < mark)) {
dgVertexAtribute face[DG_MESH_EFFECT_POINT_SPLITED];
dgInt32 count = 0;
dgEdge* ptr = edge;
do {
ptr->m_mark = mark;
face[count] = source->m_attrib[ptr->m_userData];
count ++;
dgAssert (count < dgInt32 (sizeof (face) / sizeof (face[0])));
ptr = ptr->m_next;
} while (ptr != edge);
AddPolygon(count, &face[0].m_vertex.m_x, sizeof (dgVertexAtribute), dgFastInt (face[0].m_material));
}
}
}
bool dgMeshEffect::SeparateDuplicateLoops (dgEdge* const face)
{
for (dgEdge* ptr0 = face; ptr0 != face->m_prev; ptr0 = ptr0->m_next) {
dgInt32 index = ptr0->m_incidentVertex;
dgEdge* ptr1 = ptr0->m_next;
do {
if (ptr1->m_incidentVertex == index) {
dgEdge* const ptr00 = ptr0->m_prev;
dgEdge* const ptr11 = ptr1->m_prev;
ptr00->m_next = ptr1;
ptr1->m_prev = ptr00;
ptr11->m_next = ptr0;
ptr0->m_prev = ptr11;
return true;
}
ptr1 = ptr1->m_next;
} while (ptr1 != face);
}
return false;
}
void dgMeshEffect::RepairTJoints ()
{
dgAssert (Sanity ());
// delete edge of zero length
bool dirty = true;
while (dirty) {
dgFloat64 tol = 1.0e-5;
dgFloat64 tol2 = tol * tol;
dirty = false;
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; ) {
dgEdge* const edge = &(*iter);
iter ++;
const dgBigVector& p0 = m_points[edge->m_incidentVertex];
const dgBigVector& p1 = m_points[edge->m_twin->m_incidentVertex];
dgBigVector dist (p1 - p0);
dgFloat64 mag2 = dist % dist;
if (mag2 < tol2) {
bool move = true;
while (move) {
move = false;
dgEdge* ptr = edge->m_twin;
do {
if ((&(*iter) == ptr) || (&(*iter) == ptr->m_twin)) {
move = true;
iter ++;
}
ptr = ptr->m_twin->m_next;
} while (ptr != edge->m_twin);
ptr = edge;
do {
if ((&(*iter) == ptr) || (&(*iter) == ptr->m_twin)) {
move = true;
iter ++;
}
ptr = ptr->m_twin->m_next;
} while (ptr != edge);
}
dgEdge* const collapsedEdge = CollapseEdge(edge);
if (collapsedEdge) {
dirty = true;
dgBigVector q (m_points[collapsedEdge->m_incidentVertex]);
dgEdge* ptr = collapsedEdge;
do {
if (ptr->m_incidentFace > 0) {
m_attrib[ptr->m_userData].m_vertex = q;
}
ptr = ptr->m_twin->m_next;
} while (ptr != collapsedEdge);
}
}
}
}
dgAssert (Sanity ());
// repair straight open edges
dgInt32 mark = IncLRU();
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; iter ++) {
dgEdge* const edge = &(*iter);
if ((edge->m_mark) != mark && (edge->m_incidentFace < 0)) {
while (SeparateDuplicateLoops (edge));
dgEdge* ptr = edge;
do {
ptr->m_mark = mark;
ptr = ptr->m_next;
} while (ptr != edge);
}
}
dgAssert (Sanity ());
DeleteDegenerateFaces(&m_points[0].m_x, sizeof (m_points[0]), dgFloat64 (1.0e-7f));
dgAssert (Sanity ());
// delete straight line edges
dirty = true;
while (dirty) {
dgFloat64 tol = 1.0 - 1.0e-8;
dgFloat64 tol2 = tol * tol;
dirty = false;
dgAssert (Sanity ());
dgPolyhedra::Iterator iter (*this);
for (iter.Begin(); iter; ) {
dgEdge* const edge = &(*iter);
iter ++;
const dgBigVector& p0 = m_points[edge->m_incidentVertex];
const dgBigVector& p1 = m_points[edge->m_next->m_incidentVertex];
const dgBigVector& p2 = m_points[edge->m_next->m_next->m_incidentVertex];
dgBigVector A (p1 - p0);
dgBigVector B (p2 - p1);
dgFloat64 ab = A % B;
if (ab >= 0.0f) {
dgFloat64 aa = A % A;
dgFloat64 bb = B % B;
dgFloat64 magab2 = ab * ab;
dgFloat64 magaabb = aa * bb * tol2;
if (magab2 >= magaabb) {
if ((edge->m_incidentFace > 0) && (edge->m_twin->m_incidentFace > 0)) {
if (edge->m_twin->m_prev == edge->m_next->m_twin) {
dgEdge* const newEdge = AddHalfEdge(edge->m_incidentVertex, edge->m_next->m_next->m_incidentVertex);
if (newEdge) {
dirty = true;
dgEdge* const newTwin = AddHalfEdge(edge->m_next->m_next->m_incidentVertex, edge->m_incidentVertex);
dgAssert (newEdge);
dgAssert (newTwin);
newEdge->m_twin = newTwin;
newTwin->m_twin = newEdge;
newEdge->m_userData = edge->m_userData;
newTwin->m_userData = edge->m_twin->m_prev->m_userData;
newEdge->m_incidentFace = edge->m_incidentFace;
newTwin->m_incidentFace = edge->m_twin->m_incidentFace;
dgEdge* const nextEdge = edge->m_next;
nextEdge->m_twin->m_prev->m_next = newTwin;
newTwin->m_prev = nextEdge->m_twin->m_prev;
edge->m_twin->m_next->m_prev = newTwin;
newTwin->m_next = edge->m_twin->m_next;
nextEdge->m_next->m_prev = newEdge;
newEdge->m_next = nextEdge->m_next;
edge->m_prev->m_next = newEdge;
newEdge->m_prev = edge->m_prev;
while ((&(*iter) == edge->m_twin) || (&(*iter) == nextEdge) || (&(*iter) == nextEdge->m_twin)) {
iter ++;
}
nextEdge->m_twin->m_prev = nextEdge;
nextEdge->m_twin->m_next = nextEdge;
nextEdge->m_prev = nextEdge->m_twin;
nextEdge->m_next = nextEdge->m_twin;
edge->m_twin->m_prev = edge;
edge->m_twin->m_next = edge;
edge->m_prev = edge->m_twin;
edge->m_next = edge->m_twin;
DeleteEdge(edge);
DeleteEdge(nextEdge);
//dgAssert (Sanity ());
} else if (edge->m_next->m_next->m_next == edge) {
dirty = true;
dgEdge* const openEdge = edge;
dgEdge* const nextEdge = openEdge->m_next;
dgEdge* const deletedEdge = openEdge->m_prev;
while ((&(*iter) == deletedEdge) || (&(*iter) == deletedEdge->m_twin)) {
iter ++;
}
openEdge->m_userData = deletedEdge->m_twin->m_userData;
dgBigVector p2p0 (p2 - p0);
dgFloat64 den = p2p0 % p2p0;
dgFloat64 param1 = ((p1 - p0) % p2p0) / den;
dgVertexAtribute attib1 = InterpolateEdge (deletedEdge->m_twin, param1);
AddAtribute(attib1);
openEdge->m_next->m_userData = m_atribCount - 1;
openEdge->m_incidentFace = deletedEdge->m_twin->m_incidentFace;
openEdge->m_next->m_incidentFace = deletedEdge->m_twin->m_incidentFace;
deletedEdge->m_twin->m_prev->m_next = openEdge;
openEdge->m_prev = deletedEdge->m_twin->m_prev;
deletedEdge->m_twin->m_next->m_prev = nextEdge;
nextEdge->m_next = deletedEdge->m_twin->m_next;
deletedEdge->m_twin->m_next = deletedEdge;
deletedEdge->m_twin->m_prev = deletedEdge;
deletedEdge->m_next = deletedEdge->m_twin;
deletedEdge->m_prev = deletedEdge->m_twin;
DeleteEdge(deletedEdge);
//dgAssert (Sanity ());
}
}
} else if (FindEdge(edge->m_incidentVertex, edge->m_next->m_next->m_incidentVertex)) {
dgEdge* const openEdge = edge;
dgAssert (openEdge->m_incidentFace <= 0);
dgEdge* const nextEdge = openEdge->m_next;
dgEdge* const deletedEdge = openEdge->m_prev;
if (deletedEdge == openEdge->m_next->m_next) {
dirty = true;
while ((&(*iter) == deletedEdge) || (&(*iter) == deletedEdge->m_twin)) {
iter ++;
}
dgAssert (deletedEdge->m_twin->m_incidentFace > 0);
openEdge->m_incidentFace = deletedEdge->m_twin->m_incidentFace;
openEdge->m_next->m_incidentFace = deletedEdge->m_twin->m_incidentFace;
openEdge->m_userData = deletedEdge->m_twin->m_userData;
dgBigVector p2p0 (p2 - p0);
dgFloat64 den = p2p0 % p2p0;
dgFloat64 param1 = ((p1 - p0) % p2p0) / den;
dgVertexAtribute attib1 = InterpolateEdge (deletedEdge->m_twin, param1);
attib1.m_vertex = m_points[openEdge->m_next->m_incidentVertex];
AddAtribute(attib1);
openEdge->m_next->m_userData = m_atribCount - 1;
deletedEdge->m_twin->m_prev->m_next = openEdge;
openEdge->m_prev = deletedEdge->m_twin->m_prev;
deletedEdge->m_twin->m_next->m_prev = nextEdge;
nextEdge->m_next = deletedEdge->m_twin->m_next;
deletedEdge->m_twin->m_next = deletedEdge;
deletedEdge->m_twin->m_prev = deletedEdge;
deletedEdge->m_next = deletedEdge->m_twin;
deletedEdge->m_prev = deletedEdge->m_twin;
DeleteEdge(deletedEdge);
//dgAssert (Sanity ());
}
} else {
dgEdge* const openEdge = (edge->m_incidentFace <= 0) ? edge : edge->m_twin;
dgAssert (openEdge->m_incidentFace <= 0);
const dgBigVector& p3 = m_points[openEdge->m_next->m_next->m_next->m_incidentVertex];
dgBigVector A (p3 - p2);
dgBigVector B (p2 - p1);
dgFloat64 ab (A % B);
if (ab >= 0.0) {
dgFloat64 aa (A % A);
dgFloat64 bb (B % B);
dgFloat64 magab2 = ab * ab;
dgFloat64 magaabb = aa * bb * tol2;
if (magab2 >= magaabb) {
if (openEdge->m_next->m_next->m_next->m_next != openEdge) {
const dgBigVector& p4 = m_points[openEdge->m_prev->m_incidentVertex];
dgBigVector A (p1 - p0);
dgBigVector B (p1 - p4);
dgFloat64 ab (A % B);
if (ab < 0.0f) {
dgFloat64 magab2 = ab * ab;
dgFloat64 magaabb = aa * bb * tol2;
if (magab2 >= magaabb) {
dgEdge* const newFace = ConnectVertex (openEdge->m_prev, openEdge->m_next);
dirty |= newFace ? true : false;
}
}
//dgAssert (Sanity ());
} else if (openEdge->m_prev->m_twin->m_incidentFace > 0) {
dirty = true;
dgEdge* const nextEdge = openEdge->m_next->m_next;
dgEdge* const deletedEdge = openEdge->m_prev;
while ((&(*iter) == deletedEdge) || (&(*iter) == deletedEdge->m_twin)) {
iter ++;
}
openEdge->m_incidentFace = deletedEdge->m_twin->m_incidentFace;
openEdge->m_next->m_incidentFace = deletedEdge->m_twin->m_incidentFace;
openEdge->m_next->m_next->m_incidentFace = deletedEdge->m_twin->m_incidentFace;
openEdge->m_userData = deletedEdge->m_twin->m_userData;
dgBigVector p3p0 (p3 - p0);
dgFloat64 den = p3p0 % p3p0;
dgFloat64 param1 = ((p1 - p0) % p3p0) / den;
dgVertexAtribute attib1 = InterpolateEdge (deletedEdge->m_twin, param1);
attib1.m_vertex = m_points[openEdge->m_next->m_incidentVertex];
AddAtribute(attib1);
openEdge->m_next->m_userData = m_atribCount - 1;
dgFloat64 param2 = ((p2 - p0) % p3p0) / den;
dgVertexAtribute attib2 = InterpolateEdge (deletedEdge->m_twin, param2);
attib2.m_vertex = m_points[openEdge->m_next->m_next->m_incidentVertex];
AddAtribute(attib2);
openEdge->m_next->m_next->m_userData = m_atribCount - 1;
deletedEdge->m_twin->m_prev->m_next = openEdge;
openEdge->m_prev = deletedEdge->m_twin->m_prev;
deletedEdge->m_twin->m_next->m_prev = nextEdge;
nextEdge->m_next = deletedEdge->m_twin->m_next;
deletedEdge->m_twin->m_next = deletedEdge;
deletedEdge->m_twin->m_prev = deletedEdge;
deletedEdge->m_next = deletedEdge->m_twin;
deletedEdge->m_prev = deletedEdge->m_twin;
DeleteEdge(deletedEdge);
//dgAssert (Sanity ());
}
}
}
}
}
}
}
}
dgAssert (Sanity ());
DeleteDegenerateFaces(&m_points[0].m_x, sizeof (m_points[0]), dgFloat64 (1.0e-7f));
for (iter.Begin(); iter; iter ++) {
dgEdge* const edge = &iter.GetNode()->GetInfo();
if (edge->m_incidentFace > 0) {
dgBigVector p0 (m_points[edge->m_incidentVertex]);
m_attrib[edge->m_userData].m_vertex.m_x = p0.m_x;
m_attrib[edge->m_userData].m_vertex.m_y = p0.m_y;
m_attrib[edge->m_userData].m_vertex.m_z = p0.m_z;
}
}
dgAssert (Sanity ());
}
| 30.479586 | 234 | 0.644234 | wivlaro |
596c733ed7598fbf307a9324884bdb5b95bf66e1 | 538 | cpp | C++ | test/test_symbol_load.cpp | lingjf/h2un | 7735c2f07f58ea8b92a9e9608c9b45c98c94c670 | [
"Apache-2.0"
] | 5 | 2015-03-02T22:29:00.000Z | 2020-06-28T08:52:00.000Z | test/test_symbol_load.cpp | lingjf/h2un | 7735c2f07f58ea8b92a9e9608c9b45c98c94c670 | [
"Apache-2.0"
] | 5 | 2019-05-10T02:28:00.000Z | 2021-07-17T00:53:18.000Z | test/test_symbol_load.cpp | lingjf/h2un | 7735c2f07f58ea8b92a9e9608c9b45c98c94c670 | [
"Apache-2.0"
] | 5 | 2016-05-25T07:31:16.000Z | 2021-08-29T04:25:18.000Z | #include "../source/h2_unit.cpp"
void say_something1()
{
::printf("hello world\n");
}
#if 0
SUITE(load)
{
Case(addr_to_ptr)
{
h2::h2_symbol* res[16];
int n = h2::h2_nm::get_by_name("say_something1", res, 16);
OK(1, n);
OK(Nq((unsigned long long)say_something1), (unsigned long long)res[0]->offset);
OK((unsigned long long)say_something1, (unsigned long long)res[0]->offset);
OK((unsigned long long)say_something1, (unsigned long long)h2::h2_load::addr_to_ptr(res[0]->offset));
}
}
#endif
| 24.454545 | 107 | 0.644981 | lingjf |
596e09a66b9785a7691b25d87ea261663311be75 | 571 | hpp | C++ | LeetCode/386_LexicographicalNumbers.hpp | defUserName-404/Online-Judge | 197ac5bf3e2149474b191eeff106b12cd723ec8c | [
"MIT"
] | null | null | null | LeetCode/386_LexicographicalNumbers.hpp | defUserName-404/Online-Judge | 197ac5bf3e2149474b191eeff106b12cd723ec8c | [
"MIT"
] | null | null | null | LeetCode/386_LexicographicalNumbers.hpp | defUserName-404/Online-Judge | 197ac5bf3e2149474b191eeff106b12cd723ec8c | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <vector>
// 100ms run time(faster than 16%)
// need to optimize the solution
class Solution
{
public:
std::vector<int> lexicalOrder(int n)
{
std::vector<std::string> lexicalString;
for (int i = 1; i <= n; i++)
lexicalString.push_back(std::to_string(i));
std::sort(lexicalString.begin(), lexicalString.end());
std::vector<int> lexicalInt;
for (auto it : lexicalString)
lexicalInt.push_back(std::stoi(it));
return lexicalInt;
}
}; | 21.148148 | 62 | 0.605954 | defUserName-404 |
5973549ffceae0114a97ad921660145eeac4b2d1 | 2,828 | cc | C++ | Testcase4-Application-breakdown/online-compiling/test_vectors/mosh/src/terminal/terminaluserinput.cc | hunhoffe/ServerlessBench | 529eb835638cad0edb5be3343166c7ade375ece2 | [
"MulanPSL-1.0"
] | 129 | 2020-08-09T12:02:30.000Z | 2022-03-31T15:26:03.000Z | Testcase4-Application-breakdown/online-compiling/test_vectors/mosh/src/terminal/terminaluserinput.cc | hunhoffe/ServerlessBench | 529eb835638cad0edb5be3343166c7ade375ece2 | [
"MulanPSL-1.0"
] | 11 | 2020-09-17T09:42:07.000Z | 2022-03-30T19:05:38.000Z | Testcase4-Application-breakdown/online-compiling/test_vectors/mosh/src/terminal/terminaluserinput.cc | hunhoffe/ServerlessBench | 529eb835638cad0edb5be3343166c7ade375ece2 | [
"MulanPSL-1.0"
] | 22 | 2020-08-20T06:59:24.000Z | 2022-03-18T21:00:05.000Z | /*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
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/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <assert.h>
#include "terminaluserinput.h"
using namespace Terminal;
using namespace std;
string UserInput::input( const Parser::UserByte *act,
bool application_mode_cursor_keys )
{
/* The user will always be in application mode. If stm is not in
application mode, convert user's cursor control function to an
ANSI cursor control sequence */
/* We need to look ahead one byte in the SS3 state to see if
the next byte will be A, B, C, or D (cursor control keys). */
switch ( state ) {
case Ground:
if ( act->c == 0x1b ) { /* ESC */
state = ESC;
}
return string( &act->c, 1 );
break;
case ESC:
if ( act->c == 'O' ) { /* ESC O = 7-bit SS3 */
state = SS3;
return string();
} else {
state = Ground;
return string( &act->c, 1 );
}
break;
case SS3:
state = Ground;
if ( (!application_mode_cursor_keys)
&& (act->c >= 'A')
&& (act->c <= 'D') ) {
char translated_cursor[ 2 ] = { '[', act->c };
return string( translated_cursor, 2 );
} else {
char original_cursor[ 2 ] = { 'O', act->c };
return string( original_cursor, 2 );
}
break;
}
/* This doesn't handle the 8-bit SS3 C1 control, which would be
two octets in UTF-8. Fortunately nobody seems to send this. */
assert( false );
return string();
}
| 32.505747 | 73 | 0.669378 | hunhoffe |
5977311284a3882abd70bfc7d7b3d3e305b3a80d | 5,169 | cc | C++ | depends/dbcommon/src/dbcommon/nodes/select-list.cc | YangHao666666/hawq | 10cff8350f1ba806c6fec64eb67e0e6f6f24786c | [
"Artistic-1.0-Perl",
"ISC",
"bzip2-1.0.5",
"TCL",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"PostgreSQL",
"BSD-3-Clause"
] | 1 | 2020-05-11T01:39:13.000Z | 2020-05-11T01:39:13.000Z | depends/dbcommon/src/dbcommon/nodes/select-list.cc | YangHao666666/hawq | 10cff8350f1ba806c6fec64eb67e0e6f6f24786c | [
"Artistic-1.0-Perl",
"ISC",
"bzip2-1.0.5",
"TCL",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"PostgreSQL",
"BSD-3-Clause"
] | 1 | 2021-03-01T02:57:26.000Z | 2021-03-01T02:57:26.000Z | depends/dbcommon/src/dbcommon/nodes/select-list.cc | YangHao666666/hawq | 10cff8350f1ba806c6fec64eb67e0e6f6f24786c | [
"Artistic-1.0-Perl",
"ISC",
"bzip2-1.0.5",
"TCL",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"PostgreSQL",
"BSD-3-Clause"
] | 1 | 2020-05-03T07:29:21.000Z | 2020-05-03T07:29:21.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "dbcommon/nodes/select-list.h"
#include "dbcommon/common/vector-transformer.h"
#include "dbcommon/common/vector.h"
#include "dbcommon/utils/bool-buffer.h"
namespace dbcommon {
SelectList::SelectList(size_t plainSize) : plainSize_(plainSize) {
indexs_.reset(new value_type[DEFAULT_NUMBER_TUPLES_PER_BATCH + 2]);
}
SelectList::SelectList(const SelectList& x)
: size_(x.size_), plainSize_(x.plainSize_) {
indexs_.reset(new value_type[DEFAULT_NUMBER_TUPLES_PER_BATCH + 2]);
for (auto i = 0; i < size_; i++) indexs_[i] = x.indexs_[i];
if (x.nulls_) {
nulls_.reset(new BoolBuffer(true));
nulls_->reset(x.plainSize_, nullptr, x.nulls_->getBools());
} else {
nulls_ = nullptr;
}
}
SelectList::SelectList(SelectList&& x)
: size_(x.size_), plainSize_(x.plainSize_) {
indexs_.swap(x.indexs_);
nulls_.swap(x.nulls_);
}
SelectList::SelectList(std::initializer_list<value_type> il)
: size_(il.size()) {
indexs_.reset(new value_type[size_]);
for (auto i = 0; i < size_; i++) indexs_[i] = *(il.begin() + i);
}
SelectList::~SelectList() {}
SelectList& SelectList::operator=(std::initializer_list<value_type> il) {
size_ = il.size();
assert(DEFAULT_NUMBER_TUPLES_PER_BATCH + 2 > size_);
for (auto i = 0; i < size_; i++) indexs_[i] = *(il.begin() + i);
if (nulls_) nulls_->resize(0);
return *this;
}
SelectList& SelectList::operator=(SelectList x) {
swap(x);
return *this;
}
void SelectList::reserve(size_type n) {
size_ = 0;
indexs_.reset(new value_type[n]);
}
void SelectList::clear() {
size_ = 0;
if (nulls_) nulls_->resize(0);
}
SelectList SelectList::getComplement(size_t size) {
SelectList retval;
auto ret = retval.begin();
auto nulls = getNulls();
uint64_t ret_size = 0;
uint64_t idx = 0;
if (nulls) {
for (auto i = 0; i < size_; i++) {
auto b = indexs_[i];
while (idx < b) {
if (!nulls[idx]) ret[ret_size++] = idx;
idx++;
}
idx = b + 1;
}
while (idx < size) {
if (!nulls[idx]) ret[ret_size++] = idx;
idx++;
}
} else {
for (auto i = 0; i < size_; i++) {
auto b = indexs_[i];
while (idx < b) {
ret[ret_size++] = (idx++);
}
idx = b + 1;
}
while (idx < size) {
ret[ret_size++] = (idx++);
}
}
retval.size_ = ret_size;
retval.plainSize_ = plainSize();
return retval;
}
const bool* SelectList::getNulls() const {
return reinterpret_cast<const bool*>(
nulls_ ? (nulls_->size() != 0 ? nulls_->data() : nullptr) : nullptr);
}
void SelectList::setNulls(size_t plainSize, const SelectList* sel,
const bool* __restrict__ nulls1,
const bool* __restrict__ nulls2,
const bool* __restrict__ nulls3) {
plainSize_ = plainSize;
if (nulls1 || nulls2) {
if (nulls_ == nullptr) nulls_.reset(new BoolBuffer(true));
this->nulls_->reset(plainSize, sel, nulls1, nulls2, nulls3);
} else {
if (nulls_) nulls_->resize(0);
}
}
void SelectList::setNulls(size_t plainSize, const SelectList* sel, bool null) {
plainSize_ = plainSize;
if (nulls_) {
nulls_->reset(plainSize, sel, null);
}
}
void SelectList::toVector(Vector* outVector) {
assert(outVector->getTypeKind() == TypeKind::BOOLEANID);
assert(size_ <= plainSize_);
outVector->resize(plainSize_, nullptr, this->getNulls());
FixedSizeTypeVectorRawData<bool> out(outVector);
memset(out.values, 0, plainSize_);
auto setBoolean = [&](uint64_t plainIdx) { out.values[plainIdx] = true; };
transformVector(out.plainSize, this, out.nulls, setBoolean);
}
void SelectList::fromVector(const Vector* inVector) {
assert(inVector->getTypeKind() == TypeKind::BOOLEANID);
FixedSizeTypeVectorRawData<bool> in(const_cast<Vector*>(inVector));
SelectList::size_type counter = 0;
SelectList::value_type* __restrict__ ret = this->begin();
auto updateSel = [&](uint64_t plainIdx) {
if (in.values[plainIdx]) ret[counter++] = plainIdx;
};
transformVector(in.plainSize, in.sel, in.nulls, updateSel);
size_ = counter;
plainSize_ = in.plainSize;
setNulls(plainSize_, nullptr, inVector->getNulls());
}
std::string SelectList::toString() {
auto vec = Vector::BuildVector(TypeKind::BOOLEANID, true);
this->toVector(vec.get());
return vec->toString();
}
} // namespace dbcommon
| 29.369318 | 79 | 0.662024 | YangHao666666 |
597b50f3192465ff37e17f6f8a5bcebbbdbee784 | 1,419 | cpp | C++ | LeetCode/C++/34. Find First and Last Position of Element in Sorted Array.cpp | shreejitverma/GeeksforGeeks | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-18T05:14:28.000Z | 2022-03-08T07:00:08.000Z | LeetCode/C++/34. Find First and Last Position of Element in Sorted Array.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 6 | 2022-01-13T04:31:04.000Z | 2022-03-12T01:06:16.000Z | LeetCode/C++/34. Find First and Last Position of Element in Sorted Array.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-14T19:53:53.000Z | 2022-02-18T05:14:30.000Z | //binary search
//Runtime: 16 ms, faster than 90.01% of C++ online submissions for Find First and Last Position of Element in Sorted Array.
//Memory Usage: 14.1 MB, less than 10.23% of C++ online submissions for Find First and Last Position of Element in Sorted Array.
//time: O(logN), space: O(1)
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n = nums.size();
if(n == 0) return {-1, -1};
int left = 0, right = n-1;
//find left boundary
while(left <= right){
int mid = (left+right) >> 1;
// cout << left << ", " << mid << ", " << right << endl;
if(nums[mid] < target){
left = mid+1;
}else{
right = mid-1;
}
}
if(left >= n || nums[left] != target){
return {-1, -1};
}
vector<int> ans = {left};
//find right boundary
left = 0;
right = n-1;
while(left <= right){
int mid = (left+right) >> 1;
// cout << left << ", " << mid << ", " << right << endl;
if(nums[mid] > target){
right = mid-1;
}else{
left = mid+1;
}
}
ans.push_back(right);
return ans;
}
};
| 27.823529 | 128 | 0.427766 | shreejitverma |
597fefef7cb4bddfa4c1c0b181b1ce8f5d300357 | 495 | hpp | C++ | Plus7/Modules/Gfx/Include/RasterizerProperties.hpp | txfx/plus7 | 44df3622ea8abe296d921759144e5f0d630b2945 | [
"MIT"
] | null | null | null | Plus7/Modules/Gfx/Include/RasterizerProperties.hpp | txfx/plus7 | 44df3622ea8abe296d921759144e5f0d630b2945 | [
"MIT"
] | null | null | null | Plus7/Modules/Gfx/Include/RasterizerProperties.hpp | txfx/plus7 | 44df3622ea8abe296d921759144e5f0d630b2945 | [
"MIT"
] | null | null | null | #pragma once
namespace p7 {
namespace gfx {
enum class PolygonMode
{
Fill,
Line,
Point
};
enum class CullMode
{
None,
Front,
Back,
Front_And_Back
};
enum class FrontFace
{
ClockWise,
CounterClockWise
};
struct RasterizerProperties
{
PolygonMode fillmode = PolygonMode::Fill;
CullMode cullmode = CullMode::Back;
FrontFace frontface = FrontFace::CounterClockWise;
bool scissor = false;
};
} // namespace gfx
} // namespace p7 | 14.558824 | 56 | 0.652525 | txfx |
59859b7e9dc0f0d7b9878eece674c7bd4da591f4 | 405 | hpp | C++ | include/hecl/Blender/Token.hpp | linkmauve/hecl | 57bfd8cb3fefb3e57caddef46b636d762ec642a1 | [
"MIT"
] | 267 | 2016-03-10T21:59:16.000Z | 2021-03-28T18:21:03.000Z | hecl/include/hecl/Blender/Token.hpp | cobalt2727/metaforce | 3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a | [
"MIT"
] | 129 | 2016-03-12T10:17:32.000Z | 2021-04-05T20:45:19.000Z | include/hecl/Blender/Token.hpp | RetroView/hecl | 2d1328c04bdbe9928ae89ec5b51bedb51a0133f1 | [
"MIT"
] | 31 | 2016-03-20T00:20:11.000Z | 2021-03-10T21:14:11.000Z | #pragma once
#include <memory>
namespace hecl::blender {
class Connection;
class Token {
std::unique_ptr<Connection> m_conn;
public:
Connection& getBlenderConnection();
void shutdown();
Token() = default;
~Token();
Token(const Token&) = delete;
Token& operator=(const Token&) = delete;
Token(Token&&) = default;
Token& operator=(Token&&) = default;
};
} // namespace hecl::blender
| 16.875 | 42 | 0.676543 | linkmauve |
598751fdcd0b3a69a6186b3973daca3e8c1fc575 | 3,374 | cpp | C++ | implementation/src/address.cpp | GT-TDAlab/ElGA | cebf356f8c052abfe8fd5fdc43a9396e0daf3ff8 | [
"BSD-3-Clause"
] | 7 | 2021-11-19T09:15:01.000Z | 2022-03-06T01:41:15.000Z | implementation/src/address.cpp | GT-TDAlab/ElGA | cebf356f8c052abfe8fd5fdc43a9396e0daf3ff8 | [
"BSD-3-Clause"
] | null | null | null | implementation/src/address.cpp | GT-TDAlab/ElGA | cebf356f8c052abfe8fd5fdc43a9396e0daf3ff8 | [
"BSD-3-Clause"
] | 3 | 2022-03-06T01:41:23.000Z | 2022-03-18T10:06:33.000Z | /**
* ElGA chatterbox addresses
*
* Author: Kasimir Gabert
*
* Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
* (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
* Government retains certain rights in this software.
*
* Please see the LICENSE.md file for license information.
*/
#include "address.hpp"
#include <sstream>
#include <arpa/inet.h>
using namespace elga;
ZMQAddress::ZMQAddress(std::string addr, localnum_t localnum) {
struct in_addr in_addr;
// Extract the IP from the given string
// We want to make sure we're using a 32 bit address representation
static_assert(sizeof(addr_) == sizeof(struct in_addr));
if (inet_aton(addr.c_str(), &in_addr) == 0)
throw std::runtime_error("Unable to parse IP address");
addr_ = in_addr.s_addr;
localnum_ = localnum;
// Now, pre-compute the strings
precompute_strings_();
}
uint64_t ZMQAddress::serialize() const {
// Pack the localnum and addr as localnum||addr
return (((uint64_t)localnum_)<<32) | (uint64_t)addr_;
}
ZMQAddress::ZMQAddress(uint64_t ser_addr) {
// Unpack the localnum and addr
addr_ = (uint32_t)ser_addr;
localnum_ = (localnum_t)(ser_addr >> 32);
// Now, pre-compute the strings
precompute_strings_();
}
const char * ZMQAddress::get_conn_str(const ZMQAddress &myself, addr_type_t at) const {
// Return either local or remote, depending on whether the addresses
// are the same
if (addr_ == myself.get_addr() &&
(localnum_ >= local_base &&
localnum_ < local_max)) {
if (at == PUBLISH)
return get_local_pub_str();
else if (at == REQUEST)
return get_local_str();
else if (at == PULL)
return get_local_pull_str();
} else {
if (at == PUBLISH)
return get_remote_pub_str();
else if (at == REQUEST)
return get_remote_str();
else if (at == PULL)
return get_remote_pull_str();
}
throw std::runtime_error("Unknown address type");
}
void ZMQAddress::precompute_strings_() {
struct in_addr in_addr;
in_addr.s_addr = addr_;
// Now, re-convert to a string, and use that to build the remote
// string for consistency
std::string ip(inet_ntoa(in_addr));
uint16_t port = localnum_ + START_PORT;
std::ostringstream remote_addr_os;
remote_addr_os << "tcp://" << ip << ":" << port;
remote_addr_ = remote_addr_os.str();
std::ostringstream local_addr_os;
local_addr_os << "inproc://" << localnum_;
local_addr_ = local_addr_os.str();
std::ostringstream remote_pub_addr_os;
remote_pub_addr_os << "tcp://" << ip << ":" << (port+PUB_OFFSET);
remote_pub_addr_ = remote_pub_addr_os.str();
std::ostringstream local_pub_addr_os;
local_pub_addr_os << "inproc://" << (localnum_+PUB_OFFSET);
local_pub_addr_ = local_pub_addr_os.str();
std::ostringstream remote_pull_addr_os;
remote_pull_addr_os << "tcp://" << ip << ":" << (port+PULL_OFFSET);
remote_pull_addr_ = remote_pull_addr_os.str();
std::ostringstream local_pull_addr_os;
local_pull_addr_os << "inproc://" << (localnum_+PULL_OFFSET);
local_pull_addr_ = local_pull_addr_os.str();
}
bool ZMQAddress::is_zero() const {
if (addr_ == 0) return true;
return false;
}
| 29.596491 | 87 | 0.659158 | GT-TDAlab |
5990e3aa9c87c5ceb5a0409a42bbb5d236a4a8ac | 8,315 | cpp | C++ | emulator/src/mame/drivers/babbage.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/mame/drivers/babbage.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/mame/drivers/babbage.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Robbbert
/***************************************************************************
Babbage-2nd skeleton driver (19/OCT/2011)
http://takeda-toshiya.my.coocan.jp/babbage/index.html
Pasting:
0-F : as is
INC : ^
AD : -
DA : =
GO : X
Here is a test program to turn on the LEDs.
Copy the text and Paste into the emulator.
=3E^=0F^=D3^=13^=3E^=07^=D3^=13^=3E^=00^=D3^=12^=76^-1000X
ToDo:
- Blank the display if digits aren't being refreshed
***************************************************************************/
#include "emu.h"
#include "cpu/z80/z80.h"
#include "machine/timer.h"
#include "machine/z80ctc.h"
#include "machine/z80pio.h"
#include "cpu/z80/z80daisy.h"
#include "babbage.lh"
#define MAIN_CLOCK 25e5
class babbage_state : public driver_device
{
public:
babbage_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_maincpu(*this, "maincpu")
, m_pio_1(*this, "z80pio_1")
, m_pio_2(*this, "z80pio_2")
, m_ctc(*this, "z80ctc")
, m_keyboard(*this, "X%u", 0)
, m_digits(*this, "digit%u", 0U)
{ }
void babbage(machine_config &config);
protected:
DECLARE_READ8_MEMBER(pio2_a_r);
DECLARE_WRITE8_MEMBER(pio1_b_w);
DECLARE_WRITE8_MEMBER(pio2_b_w);
DECLARE_WRITE_LINE_MEMBER(ctc_z0_w);
DECLARE_WRITE_LINE_MEMBER(ctc_z1_w);
DECLARE_WRITE_LINE_MEMBER(ctc_z2_w);
TIMER_DEVICE_CALLBACK_MEMBER(keyboard_callback);
void babbage_io(address_map &map);
void babbage_map(address_map &map);
private:
uint8_t m_segment;
uint8_t m_key;
uint8_t m_prev_key;
bool m_step;
virtual void machine_start() override { m_digits.resolve(); }
required_device<cpu_device> m_maincpu;
required_device<z80pio_device> m_pio_1;
required_device<z80pio_device> m_pio_2;
required_device<z80ctc_device> m_ctc;
required_ioport_array<4> m_keyboard;
output_finder<33> m_digits;
};
/***************************************************************************
Address Map
***************************************************************************/
void babbage_state::babbage_map(address_map &map)
{
map.global_mask(0x3fff);
map(0x0000, 0x07ff).rom();
map(0x1000, 0x17ff).ram();
}
void babbage_state::babbage_io(address_map &map)
{
map.global_mask(0xff);
map(0x00, 0x03).rw(m_ctc, FUNC(z80ctc_device::read), FUNC(z80ctc_device::write));
map(0x10, 0x13).rw(m_pio_1, FUNC(z80pio_device::read_alt), FUNC(z80pio_device::write_alt));
map(0x20, 0x23).rw(m_pio_2, FUNC(z80pio_device::read_alt), FUNC(z80pio_device::write_alt));
}
/**************************************************************************
Keyboard Layout
***************************************************************************/
// no idea of the actual key matrix
static INPUT_PORTS_START( babbage )
PORT_START("X0")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("0") PORT_CODE(KEYCODE_0) PORT_CHAR('0')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("4") PORT_CODE(KEYCODE_4) PORT_CHAR('4')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("8") PORT_CODE(KEYCODE_8) PORT_CHAR('8')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("C") PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("GO") PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_START("X1")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("1") PORT_CODE(KEYCODE_1) PORT_CHAR('1')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("5") PORT_CODE(KEYCODE_5) PORT_CHAR('5')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("9") PORT_CODE(KEYCODE_9) PORT_CHAR('9')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("D") PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("AD") PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-')
PORT_START("X2")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("2") PORT_CODE(KEYCODE_2) PORT_CHAR('2')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("6") PORT_CODE(KEYCODE_6) PORT_CHAR('6')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("A") PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("E") PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("DA") PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('=')
PORT_START("X3")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("3") PORT_CODE(KEYCODE_3) PORT_CHAR('3')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("7") PORT_CODE(KEYCODE_7) PORT_CHAR('7')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("B") PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("F") PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("INC") PORT_CODE(KEYCODE_UP) PORT_CHAR('^')
INPUT_PORTS_END
/* Z80-CTC Interface */
WRITE_LINE_MEMBER( babbage_state::ctc_z0_w )
{
}
WRITE_LINE_MEMBER( babbage_state::ctc_z1_w )
{
}
WRITE_LINE_MEMBER( babbage_state::ctc_z2_w )
{
}
/* Z80-PIO Interface */
// The 8 LEDs
// bios never writes here - you need to set PIO for output yourself - see test program above
WRITE8_MEMBER( babbage_state::pio1_b_w )
{
char ledname[8];
for (int i = 0; i < 8; i++)
{
sprintf(ledname,"led%d",i);
output().set_value(ledname, BIT(data, i));
}
}
READ8_MEMBER( babbage_state::pio2_a_r )
{
m_maincpu->set_input_line(0, CLEAR_LINE); // release interrupt
return m_key;
}
WRITE8_MEMBER( babbage_state::pio2_b_w )
{
if (BIT(data, 7))
{
m_step = false;
}
else if (!m_step)
{
m_segment = data;
m_step = true;
}
else
{
m_digits[data] = m_segment;
}
}
static const z80_daisy_config babbage_daisy_chain[] =
{// need to check the order
{ "z80pio_1" },
{ "z80pio_2" },
{ "z80ctc" },
{ nullptr }
};
TIMER_DEVICE_CALLBACK_MEMBER(babbage_state::keyboard_callback)
{
u8 inp, data = 0xff;
for (u8 i = 0; i < 4; i++)
{
inp = m_keyboard[i]->read();
for (u8 j = 0; j < 5; j++)
if (BIT(inp, j))
data = (j << 2) | i;
}
/* make sure only one keystroke */
if (data != m_prev_key)
m_prev_key = data;
else
data = 0xff;
/* while key is down, activate strobe. When key released, deactivate strobe which causes an interrupt */
if (data < 0xff)
{
m_key = data;
m_pio_2->strobe(0, 0);
}
else
m_pio_2->strobe(0, 1);
}
/***************************************************************************
Machine driver
***************************************************************************/
MACHINE_CONFIG_START(babbage_state::babbage)
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", Z80, MAIN_CLOCK) //2.5MHz
MCFG_CPU_PROGRAM_MAP(babbage_map)
MCFG_CPU_IO_MAP(babbage_io)
MCFG_Z80_DAISY_CHAIN(babbage_daisy_chain)
/* video hardware */
MCFG_DEFAULT_LAYOUT(layout_babbage)
/* Devices */
MCFG_DEVICE_ADD("z80ctc", Z80CTC, MAIN_CLOCK)
MCFG_Z80CTC_INTR_CB(INPUTLINE("maincpu", INPUT_LINE_IRQ0))
MCFG_Z80CTC_ZC0_CB(WRITELINE(babbage_state, ctc_z0_w))
MCFG_Z80CTC_ZC1_CB(WRITELINE(babbage_state, ctc_z1_w))
MCFG_Z80CTC_ZC2_CB(WRITELINE(babbage_state, ctc_z2_w))
MCFG_DEVICE_ADD("z80pio_1", Z80PIO, MAIN_CLOCK)
MCFG_Z80PIO_OUT_INT_CB(INPUTLINE("maincpu", INPUT_LINE_IRQ0))
MCFG_Z80PIO_OUT_PB_CB(WRITE8(babbage_state, pio1_b_w))
MCFG_DEVICE_ADD("z80pio_2", Z80PIO, MAIN_CLOCK)
MCFG_Z80PIO_OUT_INT_CB(INPUTLINE("maincpu", INPUT_LINE_IRQ0))
MCFG_Z80PIO_IN_PA_CB(READ8(babbage_state, pio2_a_r))
MCFG_Z80PIO_OUT_PB_CB(WRITE8(babbage_state, pio2_b_w))
MCFG_TIMER_DRIVER_ADD_PERIODIC("keyboard_timer", babbage_state, keyboard_callback, attotime::from_hz(30))
MACHINE_CONFIG_END
/***************************************************************************
Game driver
***************************************************************************/
ROM_START(babbage)
ROM_REGION(0x10000, "maincpu", ROMREGION_ERASEFF)
ROM_LOAD("mon.rom", 0x0000, 0x0200, CRC(469bd607) SHA1(8f3489a0f96de6a03b05c1ee01b89d9848f4b152) )
ROM_END
// YEAR NAME PARENT COMPAT MACHINE INPUT STATE INIT COMPANY FULLNAME FLAGS
COMP( 1986, babbage, 0, 0, babbage, babbage, babbage_state, 0, "Mr Takafumi Aihara", "Babbage-2nd" , MACHINE_NO_SOUND_HW )
| 30.018051 | 139 | 0.664702 | rjw57 |
59950b49010124aa885e437363e451e6bb05f30e | 5,431 | cpp | C++ | src/final_chain/replay_protection_service.cpp | agrebin/taraxa-node | a594b01f52e727c8fc5dc87c9c325510c2a6f1cb | [
"MIT"
] | null | null | null | src/final_chain/replay_protection_service.cpp | agrebin/taraxa-node | a594b01f52e727c8fc5dc87c9c325510c2a6f1cb | [
"MIT"
] | 7 | 2021-06-08T12:40:38.000Z | 2021-06-16T12:11:15.000Z | src/final_chain/replay_protection_service.cpp | agrebin/taraxa-node | a594b01f52e727c8fc5dc87c9c325510c2a6f1cb | [
"MIT"
] | null | null | null | #include "replay_protection_service.hpp"
#include <libdevcore/CommonJS.h>
#include <libdevcore/RLP.h>
#include <optional>
#include <shared_mutex>
#include <sstream>
#include <string>
#include <unordered_map>
#include "util/util.hpp"
namespace taraxa::final_chain {
using namespace dev;
using namespace util;
using namespace std;
string senderStateKey(string const& sender_addr_hex) { return "sender_" + sender_addr_hex; }
string periodDataKeysKey(uint64_t period) { return "data_keys_at_" + to_string(period); }
string maxNonceAtRoundKey(uint64_t period, string const& sender_addr_hex) {
return "max_nonce_at_" + to_string(period) + "_" + sender_addr_hex;
}
struct SenderState {
uint64_t nonce_max = 0;
optional<uint64_t> nonce_watermark;
explicit SenderState(uint64_t nonce_max) : nonce_max(nonce_max) {}
explicit SenderState(RLP const& rlp)
: nonce_max(rlp[0].toInt<trx_nonce_t>()),
nonce_watermark(rlp[1].toInt<bool>() ? optional(rlp[2].toInt<uint64_t>()) : std::nullopt) {}
bytes rlp() {
RLPStream rlp(3);
rlp << nonce_max;
rlp << nonce_watermark.has_value();
rlp << (nonce_watermark ? *nonce_watermark : 0);
return rlp.out();
}
};
DB::Slice db_slice(dev::bytes const& b) { return {(char*)b.data(), b.size()}; }
class ReplayProtectionServiceImpl : public virtual ReplayProtectionService {
Config config_;
shared_ptr<DB> db_;
shared_mutex mutable mu_;
public:
ReplayProtectionServiceImpl(Config const& config, shared_ptr<DB> db) : config_(config), db_(move(db)) {}
bool is_nonce_stale(addr_t const& addr, uint64_t nonce) const override {
shared_lock l(mu_);
auto sender_state = loadSenderState(senderStateKey(addr.hex()));
if (!sender_state) {
return false;
}
return sender_state->nonce_watermark && nonce <= *sender_state->nonce_watermark;
}
// TODO use binary types instead of hex strings
void update(DB::Batch& batch, uint64_t period, RangeView<TransactionInfo> const& trxs) override {
unique_lock l(mu_);
unordered_map<string, shared_ptr<SenderState>> sender_states;
sender_states.reserve(trxs.size);
unordered_map<string, shared_ptr<SenderState>> sender_states_dirty;
sender_states_dirty.reserve(trxs.size);
trxs.for_each([&, this](auto const& trx) {
auto sender_addr = trx.sender.hex();
shared_ptr<SenderState> sender_state;
if (auto e = sender_states.find(sender_addr); e != sender_states.end()) {
sender_state = e->second;
} else {
sender_state = loadSenderState(senderStateKey(sender_addr));
if (!sender_state) {
sender_states[sender_addr] = sender_states_dirty[sender_addr] = s_ptr(new SenderState(trx.nonce));
return;
}
sender_states[sender_addr] = sender_state;
}
if (sender_state->nonce_max < trx.nonce) {
sender_state->nonce_max = trx.nonce;
sender_states_dirty[sender_addr] = sender_state;
}
});
stringstream period_data_keys;
for (auto const& [sender, state] : sender_states_dirty) {
db_->insert(batch, DB::Columns::final_chain_replay_protection, maxNonceAtRoundKey(period, sender),
to_string(state->nonce_max));
db_->insert(batch, DB::Columns::final_chain_replay_protection, senderStateKey(sender), db_slice(state->rlp()));
period_data_keys << sender << "\n";
}
if (auto v = period_data_keys.str(); !v.empty()) {
db_->insert(batch, DB::Columns::final_chain_replay_protection, periodDataKeysKey(period), v);
}
if (period < config_.range) {
return;
}
auto bottom_period = period - config_.range;
auto bottom_period_data_keys_key = periodDataKeysKey(bottom_period);
auto keys = db_->lookup(bottom_period_data_keys_key, DB::Columns::final_chain_replay_protection);
if (keys.empty()) {
return;
}
istringstream is(keys);
for (string line; getline(is, line);) {
auto nonce_max_key = maxNonceAtRoundKey(bottom_period, line);
if (auto v = db_->lookup(nonce_max_key, DB::Columns::final_chain_replay_protection); !v.empty()) {
auto sender_state_key = senderStateKey(line);
auto state = loadSenderState(sender_state_key);
state->nonce_watermark = stoull(v);
db_->insert(batch, DB::Columns::final_chain_replay_protection, sender_state_key, db_slice(state->rlp()));
db_->remove(batch, DB::Columns::final_chain_replay_protection, nonce_max_key);
}
}
db_->remove(batch, DB::Columns::final_chain_replay_protection, bottom_period_data_keys_key);
}
shared_ptr<SenderState> loadSenderState(string const& key) const {
if (auto v = db_->lookup(key, DB::Columns::final_chain_replay_protection); !v.empty()) {
return s_ptr(new SenderState(RLP(v)));
}
return nullptr;
}
};
std::unique_ptr<ReplayProtectionService> NewReplayProtectionService(ReplayProtectionService::Config config,
std::shared_ptr<DB> db) {
return make_unique<ReplayProtectionServiceImpl>(config, move(db));
}
Json::Value enc_json(ReplayProtectionService::Config const& obj) {
Json::Value json(Json::objectValue);
json["range"] = dev::toJS(obj.range);
return json;
}
void dec_json(Json::Value const& json, ReplayProtectionService::Config& obj) {
obj.range = dev::jsToInt(json["range"].asString());
}
} // namespace taraxa::final_chain | 37.455172 | 117 | 0.69582 | agrebin |
5997027482046486252fb9d2db0fbb2c7227c018 | 14,441 | cpp | C++ | drlvm/vm/vmcore/src/init/vm_properties.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 5 | 2017-03-08T20:32:39.000Z | 2021-07-10T10:12:38.000Z | drlvm/vm/vmcore/src/init/vm_properties.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | null | null | null | drlvm/vm/vmcore/src/init/vm_properties.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 4 | 2015-07-07T07:06:59.000Z | 2018-06-19T22:38:04.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <apr_file_io.h>
#include <apr_file_info.h>
#include <apr_strings.h>
#include "port_dso.h"
#include "port_filepath.h"
#include "port_sysinfo.h"
#define LOG_DOMAIN "init.properties"
#include "cxxlog.h"
#include "properties.h"
#include "vm_properties.h"
#include "init.h"
#include "port_modules.h"
#include "version.h"
#if defined(FREEBSD)
#include <dlfcn.h>
#endif
inline char* unquote(char *str)
{
const char *tokens = " \t\n\r\'\"";
size_t i = strspn(str, tokens);
str += i;
char *p = str + strlen(str) - 1;
while(strchr(tokens, *p) && p >= str)
*(p--) = '\0';
return str;
}
// local memory pool for temporary allocation
static apr_pool_t *prop_pool;
static const char *api_dll_files[] =
{
"harmonyvm", NULL,
"hythr", NULL,
"hyprt", NULL,
#if defined(HY_LOCAL_ZLIB)
"z", "1",
#else
"hyzlib", NULL,
#endif
"hynio", NULL,
"vmi", NULL,
"hyluni", NULL,
"hyarchive", NULL
};
/**
* Compose a string of file names each of them beginning with path,
* names separated by PORT_PATH_SEPARATOR. If patch is NULL, no path
* or separator will be prefixed
*/
static const char *compose_full_files_path_names_list(const char *path,
const char **dll_names,
const int names_number,
bool is_dll)
{
const char* full_name = "";
for (int iii = 0; iii < names_number; )
{
const char *tmp = dll_names[iii++];
const char *ver = dll_names[iii++];
if (is_dll) {
tmp = port_dso_name_decorate(tmp, ver, prop_pool);
}
/*
* if the path is non-null, prefix, otherwise do nothing
* to avoid the problem of "/libfoo.so" when we don't want
* a path attached
*/
if (path != NULL) {
tmp = port_filepath_merge(path, tmp, prop_pool);
}
full_name = apr_pstrcat(prop_pool, full_name, tmp,
(iii < names_number) ? PORT_PATH_SEPARATOR_STR : "", NULL);
}
return full_name;
}
static char* get_module_filename(void* code_ptr)
{
native_module_t* modules;
int modules_count;
#ifdef _IPF_
// On IPF function pointer is not a pointer to a function, it is a pointer
// to a table with first element of it the address of the funtion
void **ptr = (void**)code_ptr;
code_ptr = ptr[0];
#endif
#if defined(FREEBSD)
Dl_info info;
if (dladdr( (const void*)code_ptr, &info) == 0) {
return NULL;
}
return apr_pstrdup(prop_pool, info.dli_fname);
#else
if (! port_get_all_modules(&modules, &modules_count))
return NULL;
native_module_t* module = port_find_module(modules, code_ptr);
char* filename = NULL;
if (NULL != module) {
filename = apr_pstrdup(prop_pool, module->filename);
}
port_clear_modules(&modules);
return filename;
#endif
}
static void init_java_properties(Properties & properties)
{
//java part
//!!! java.compiler property must be defined by EM
char *os_name, *os_version, *path;
const char *tmp;
char *path_buf = NULL;
port_OS_name_version(&os_name, &os_version, prop_pool);
apr_filepath_get(&path, APR_FILEPATH_NATIVE, prop_pool);
if (APR_SUCCESS != apr_temp_dir_get(&tmp, prop_pool)) {
tmp = ".";
}
properties.set_new("java.version", JAVA_RUNTIME_VERSION);
properties.set_new("java.vendor", "Apache Software Foundation");
properties.set_new("java.vendor.url", "http://harmony.apache.org");
properties.set_new("java.fullversion", VERSION);
// java.home initialization, try to find absolute location of the executable and set
// java.home to the parent directory.
char *launcher_dir;
if (port_executable_name(&launcher_dir) != APR_SUCCESS) {
LDIE(13, "Failed to find executable location");
}
STD_FREE(launcher_dir);
properties.set_new("java.vm.specification.version", "1.0");
properties.set_new("java.vm.specification.vendor", "Sun Microsystems Inc.");
properties.set_new("java.vm.specification.name", "Java Virtual Machine Specification");
properties.set_new("java.vm.version",
JAVA_RUNTIME_VERSION "-r" VERSION_SVN_TAG);
properties.set_new("java.vm.vendor", "Apache Software Foundation");
properties.set_new("java.vm.name", "DRLVM");
properties.set_new("java.runtime.name", "Apache Harmony");
properties.set_new("java.runtime.version", JAVA_RUNTIME_VERSION);
properties.set_new("java.specification.version",
JAVA_SPECIFICATION_VERSION);
properties.set_new("java.specification.vendor", "Sun Microsystems Inc.");
properties.set_new("java.specification.name", "Java Platform API Specification");
properties.set_new("java.class.version", EXPAND(CLASSFILE_MAJOR_MAX) "."
EXPAND(CLASSFILE_MINOR_MAX));
properties.set_new("java.class.path", ".");
/*
* it's possible someone forgot to set this property - set to default of location of vm module
*/
if (! properties.is_set(O_A_H_VM_VMDIR)) {
char* vm_dir = get_module_filename((void*) &init_java_properties);
if (NULL == vm_dir)
LDIE(43, "ERROR: Can't determine vm module location. Please specify {0} property." << O_A_H_VM_VMDIR);
char *p = strrchr(vm_dir, PORT_FILE_SEPARATOR);
if (NULL == p)
LDIE(43, "ERROR: Can't determine vm module location. Please specify {0} property." << O_A_H_VM_VMDIR);
*p = '\0';
properties.set(O_A_H_VM_VMDIR, vm_dir);
}
char* vm_dir = properties.get(O_A_H_VM_VMDIR);
// home directory
char* home_path = apr_pstrdup(prop_pool, vm_dir);
char* p = strrchr(home_path, PORT_FILE_SEPARATOR);
if (NULL == p)
LDIE(15, "Failed to determine java home directory");
*p = '\0';
char* lib_path = apr_pstrcat(prop_pool, vm_dir,
PORT_PATH_SEPARATOR_STR, home_path, NULL);
p = strrchr(home_path, PORT_FILE_SEPARATOR);
if (NULL == p)
LDIE(15, "Failed to determine java home directory");
*p = '\0';
properties.set_new("java.home", home_path);
properties.destroy(vm_dir);
vm_dir = NULL;
/*
* This property is used by java/lang/Runtime#loadLibrary0 as path to
* system native libraries.
* The value is the location of launcher executable and vm binary directory
*/
properties.set_new("vm.boot.library.path", lib_path);
// Added for compatibility with the external java JDWP agent
properties.set_new("sun.boot.library.path", lib_path);
// java.library.path initialization, the value is the same as for
// vm.boot.library.path appended with OS library search path
char *env;
if (APR_SUCCESS == port_dso_search_path(&env, prop_pool))
{
lib_path = apr_pstrcat(prop_pool, lib_path, PORT_PATH_SEPARATOR_STR,
env, NULL);
}
properties.set_new("java.library.path", lib_path);
//java.ext.dirs initialization.
char *ext_path = port_filepath_merge(home_path, "lib" PORT_FILE_SEPARATOR_STR "ext", prop_pool);
properties.set_new("java.ext.dirs", ext_path);
properties.set_new("os.name", os_name);
properties.set_new("os.arch", port_CPU_architecture());
properties.set_new("os.version", os_version);
properties.set_new("file.separator", PORT_FILE_SEPARATOR_STR);
properties.set_new("path.separator", PORT_PATH_SEPARATOR_STR);
properties.set_new("line.separator", APR_EOL_STR);
// user.name initialization, try to get the name from the system
char *user_buf;
apr_status_t status = port_user_name(&user_buf, prop_pool);
if (APR_SUCCESS != status) {
LDIE(16, "Failed to get user name from the system. Error code {0}" << status);
}
properties.set_new("user.name", user_buf);
// user.home initialization, try to get home from the system.
char *user_home;
status = port_user_home(&user_home, prop_pool);
if (APR_SUCCESS != status) {
LDIE(17, "Failed to get user home from the system. Error code {0}" << status);
}
properties.set_new("user.home", user_home);
// java.io.tmpdir initialization.
const char *tmpdir;
status = apr_temp_dir_get(&tmpdir, prop_pool);
if (APR_SUCCESS != status) {
tmpdir = user_home;
}
properties.set_new("java.io.tmpdir", tmpdir);
properties.set_new("user.dir", path);
// FIXME??? other (not required by api specification) properties
properties.set_new("java.vm.info", "no info");
properties.set_new("java.tmpdir", tmp);
// FIXME user.timezone initialization, required by java.util.TimeZone implementation
char *user_tz;
status = port_user_timezone(&user_tz, prop_pool);
if (APR_SUCCESS != status) {
INFO("Failed to get user timezone from the system. Error code " << status);
user_tz = NULL;
}
properties.set_new("user.timezone", user_tz ? user_tz : "GMT");
/*
* it's possible someone forgot to set this property - set to default of .
*/
properties.set_new("java.class.path", ".");
}
//vm part
static void init_vm_properties(Properties & properties)
{
#ifdef _DEBUG
properties.set_new("vm.assert_dialog", "true");
#else
properties.set_new("vm.assert_dialog", "false");
#endif
properties.set_new("vm.crash_handler", "false");
properties.set_new("vm.finalize", "true");
properties.set_new("vm.jit_may_inline_sync", "true");
properties.set_new("vm.use_verifier", "true");
properties.set_new("vm.jvmti.enabled", "false");
properties.set_new("vm.jvmti.compiled_method_load.inlined", "false");
properties.set_new("vm.bootclasspath.appendclasspath", "false");
properties.set_new("thread.soft_unreservation", "false");
#ifdef REFS_USE_RUNTIME_SWITCH
properties.set_new("vm.compress_references", "true");
#endif
int n_api_dll_files = sizeof(api_dll_files) / sizeof(char *);
/*
* pass NULL for the pathname as we don't want
* any path pre-pended
*/
const char* path_buf = compose_full_files_path_names_list(NULL, api_dll_files, n_api_dll_files, true);
properties.set_new("vm.other_natives_dlls", path_buf);
}
jint initialize_properties(Global_Env * p_env)
{
jint status = JNI_OK;
if (!prop_pool) {
apr_pool_create(&prop_pool, 0);
}
/*
* 1. Process command line options.
* Java properties are set as -Dkey[=value];
* VM properties are set with the following syntax ("fully compatible" with RI):
* - options are set with -XX:<option>=<string>
* - Boolean options may be turned on with -XX:+<option> and turned off with -XX:-<option>
* - Numeric options are set with -XX:<option>=<number>.
* Numbers can include 'm' or 'M' for megabytes, 'k' or 'K' for kilobytes, and 'g' or
* 'G' for gigabytes (for example, 32k is the same as 32768).
*/
char *src, *tok;
for (int arg_num = 0; arg_num < p_env->vm_arguments.nOptions; arg_num++)
{
char *option = p_env->vm_arguments.options[arg_num].optionString;
if (strncmp(option, "-D", 2) == 0)
{
TRACE("setting property " << option + 2);
src = strdup(option + 2);
tok = strchr(src, '=');
if(tok)
{
*tok = '\0';
p_env->JavaProperties()->set(unquote(src), unquote(tok + 1));
}
else
{
p_env->JavaProperties()->set(unquote(src), "");
}
STD_FREE(src);
}
else if (strncmp(option, "-XD", 3) == 0)
{
WARN(("Deprecated syntax to set internal property, use -XX:key=value instead: %s", option));
TRACE("setting internal property " << option + 3);
src = strdup(option + 3);
tok = strchr(src, '=');
if(tok)
{
*tok = '\0';
p_env->VmProperties()->set(unquote(src), unquote(tok + 1));
}
else
{
p_env->VmProperties()->set(unquote(src), "");
}
STD_FREE(src);
}
else if (strncmp(option, "-XX:", 4) == 0)
{
TRACE("setting internal property " << option + 4);
src = strdup(option + 4);
char* name = unquote(src);
char* valptr = strchr(src, '=');
const char* value;
if(valptr)
{
*valptr = '\0';
value = valptr + 1;
}
else
{
if (name[0] == '-' ) {
value = "off";
++name;
} else if (src[0] == '+') {
value = "on";
++name;
} else {
value = "";
LECHO(28, "Wrong option format {0}" << option);
status = JNI_ERR;
}
}
TRACE("parsed internal property " << name << " = " << value << ";");
p_env->VmProperties()->set(name, value);
STD_FREE(src);
if (status != JNI_OK) break;
}
}
/*
* 2. Set predefined values to properties not defined via vm options.
*/
if (status == JNI_OK)
{
init_java_properties(*p_env->JavaProperties());
init_vm_properties(*p_env->VmProperties());
}
apr_pool_clear(prop_pool);
return status;
}
| 34.220379 | 114 | 0.614016 | sirinath |
59976f90689a1ebd7daa77a7d18111f1108d5707 | 3,586 | inl | C++ | Base/PLCore/include/PLCore/Application/ApplicationContext.inl | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Base/PLCore/include/PLCore/Application/ApplicationContext.inl | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 27 | 2019-06-18T06:46:07.000Z | 2020-02-02T11:11:28.000Z | Base/PLCore/include/PLCore/Application/ApplicationContext.inl | naetherm/PixelLight | d7666f5b49020334cbb5debbee11030f34cced56 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: ApplicationContext.inl *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace PLCore {
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
//[-------------------------------------------------------]
//[ Options and data ]
//[-------------------------------------------------------]
/**
* @brief
* Get absolute path of application executable
*/
inline String ApplicationContext::GetExecutableFilename() const
{
// Return absolute executable filename
return m_sExecutableFilename;
}
/**
* @brief
* Get command line arguments
*/
inline const Array<String> &ApplicationContext::GetArguments() const
{
// Return argument list
return m_lstArguments;
}
/**
* @brief
* Set command line arguments
*/
inline void ApplicationContext::SetArguments(const Array<String> &lstArguments)
{
// Set argument list
m_lstArguments = lstArguments;
}
/**
* @brief
* Get directory of application executable
*/
inline String ApplicationContext::GetExecutableDirectory() const
{
// Return application executable directory
return m_sExecutableDirectory;
}
/**
* @brief
* Get directory of application
*/
inline String ApplicationContext::GetAppDirectory() const
{
// Return application directory
return m_sAppDirectory;
}
/**
* @brief
* Get current directory when the application constructor was called
*/
inline String ApplicationContext::GetStartupDirectory() const
{
// Return startup directory
return m_sStartupDirectory;
}
/**
* @brief
* Get log filename
*/
inline String ApplicationContext::GetLogFilename() const
{
// Return log filename
return m_sLog;
}
/**
* @brief
* Get config filename
*/
inline String ApplicationContext::GetConfigFilename() const
{
// Return config filename
return m_sConfig;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLCore
| 29.393443 | 97 | 0.578639 | ktotheoz |
599a66bc13ffa4630c6484be6cdf9ffce4394696 | 7,939 | cpp | C++ | Frame/Server/ProxyServer/ProxyNetClientPlugin/AFCProxyServerToGameModule.cpp | yebing115/ARK | f1c61b222dacc83e95ffb623b4ce99cbb8e386d5 | [
"Apache-2.0"
] | 1 | 2021-07-09T04:50:39.000Z | 2021-07-09T04:50:39.000Z | Frame/Server/ProxyServer/ProxyNetClientPlugin/AFCProxyServerToGameModule.cpp | yigao/ARK | f1c61b222dacc83e95ffb623b4ce99cbb8e386d5 | [
"Apache-2.0"
] | 1 | 2018-12-19T08:58:25.000Z | 2018-12-19T08:59:07.000Z | Frame/Server/ProxyServer/ProxyNetClientPlugin/AFCProxyServerToGameModule.cpp | yigao/ARK | f1c61b222dacc83e95ffb623b4ce99cbb8e386d5 | [
"Apache-2.0"
] | null | null | null | /*
* This source file is part of ArkGameFrame
* For the latest info, see https://github.com/ArkGame
*
* Copyright (c) 2013-2018 ArkGame authors.
*
* 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 "AFCProxyServerToGameModule.h"
#include "AFProxyNetClientPlugin.h"
#include "SDK/Core/AFIHeartBeatManager.h"
#include "SDK/Core/AFCHeartBeatManager.h"
#include "SDK/Interface/AFIClassModule.h"
bool AFCProxyServerToGameModule::Init()
{
m_pNetClientModule = ARK_NEW AFINetClientModule(pPluginManager);
m_pNetClientModule->Init();
return true;
}
bool AFCProxyServerToGameModule::Shut()
{
//Final();
//Clear();
return true;
}
void AFCProxyServerToGameModule::Update()
{
m_pNetClientModule->Update();
}
bool AFCProxyServerToGameModule::PostInit()
{
m_pProxyLogicModule = pPluginManager->FindModule<AFIProxyLogicModule>();
m_pKernelModule = pPluginManager->FindModule<AFIKernelModule>();
m_pProxyServerNet_ServerModule = pPluginManager->FindModule<AFIProxyNetServerModule>();
m_pElementModule = pPluginManager->FindModule<AFIElementModule>();
m_pLogModule = pPluginManager->FindModule<AFILogModule>();
m_pClassModule = pPluginManager->FindModule<AFIClassModule>();
m_pNetClientModule->AddReceiveCallBack(AFMsg::EGMI_ACK_ENTER_GAME, this, &AFCProxyServerToGameModule::OnAckEnterGame);
m_pNetClientModule->AddReceiveCallBack(AFMsg::EGMI_GTG_BROCASTMSG, this, &AFCProxyServerToGameModule::OnBrocastmsg);
m_pNetClientModule->AddReceiveCallBack(this, &AFCProxyServerToGameModule::Transpond);
m_pNetClientModule->AddEventCallBack(this, &AFCProxyServerToGameModule::OnSocketGSEvent);
ARK_SHARE_PTR<AFIClass> xLogicClass = m_pClassModule->GetElement("Server");
if(nullptr != xLogicClass)
{
AFList<std::string>& xNameList = xLogicClass->GetConfigNameList();
std::string strConfigName;
for(bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName))
{
const int nServerType = m_pElementModule->GetNodeInt(strConfigName, "Type");
const int nServerID = m_pElementModule->GetNodeInt(strConfigName, "ServerID");
if(nServerType == ARK_SERVER_TYPE::ARK_ST_GAME)
{
const int nPort = m_pElementModule->GetNodeInt(strConfigName, "Port");
const int nMaxConnect = m_pElementModule->GetNodeInt(strConfigName, "MaxOnline");
const int nCpus = m_pElementModule->GetNodeInt(strConfigName, "CpuCount");
const std::string strName(m_pElementModule->GetNodeString(strConfigName, "Name"));
const std::string strIP(m_pElementModule->GetNodeString(strConfigName, "IP"));
ConnectData xServerData;
xServerData.nGameID = nServerID;
xServerData.eServerType = (ARK_SERVER_TYPE)nServerType;
xServerData.strIP = strIP;
xServerData.nPort = nPort;
xServerData.strName = strName;
m_pNetClientModule->AddServer(xServerData);
}
}
}
return true;
}
AFINetClientModule* AFCProxyServerToGameModule::GetClusterModule()
{
return m_pNetClientModule;
}
void AFCProxyServerToGameModule::OnSocketGSEvent(const NetEventType eEvent, const AFGUID& xClientID, const int nServerID)
{
if(eEvent == DISCONNECTED)
{
ARK_LOG_INFO("Connection closed, id = %s", xClientID.ToString().c_str());
}
else if(eEvent == CONNECTED)
{
ARK_LOG_INFO("Connected success, id = %s", xClientID.ToString().c_str());
Register(nServerID);
}
}
void AFCProxyServerToGameModule::Register(const int nServerID)
{
ARK_SHARE_PTR<AFIClass> xLogicClass = m_pClassModule->GetElement("Server");
if(nullptr == xLogicClass)
{
ARK_ASSERT_NO_EFFECT(0);
}
AFList<std::string>& xNameList = xLogicClass->GetConfigNameList();
std::string strConfigName;
for(bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName))
{
const int nServerType = m_pElementModule->GetNodeInt(strConfigName, "Type");
const int nSelfServerID = m_pElementModule->GetNodeInt(strConfigName, "ServerID");
if(nServerType == ARK_SERVER_TYPE::ARK_ST_PROXY && pPluginManager->AppID() == nSelfServerID)
{
const int nPort = m_pElementModule->GetNodeInt(strConfigName, "Port");
const int nMaxConnect = m_pElementModule->GetNodeInt(strConfigName, "MaxOnline");
const int nCpus = m_pElementModule->GetNodeInt(strConfigName, "CpuCount");
const std::string strName(m_pElementModule->GetNodeString(strConfigName, "Name"));
const std::string strIP(m_pElementModule->GetNodeString(strConfigName, "IP"));
AFMsg::ServerInfoReportList xMsg;
AFMsg::ServerInfoReport* pData = xMsg.add_server_list();
pData->set_server_id(nSelfServerID);
pData->set_server_name(strName);
pData->set_server_cur_count(0);
pData->set_server_ip(strIP);
pData->set_server_port(nPort);
pData->set_server_max_online(nMaxConnect);
pData->set_server_state(AFMsg::EST_NARMAL);
pData->set_server_type(nServerType);
ARK_SHARE_PTR<ConnectData> pServerData = m_pNetClientModule->GetServerNetInfo(nServerID);
if(pServerData)
{
int nTargetID = pServerData->nGameID;
m_pNetClientModule->SendToServerByPB(nTargetID, AFMsg::EGameMsgID::EGMI_PTWG_PROXY_REGISTERED, xMsg, 0);
ARK_LOG_INFO("Register, server_id = %d server_name = %s", pData->server_id(), pData->server_name().c_str());
}
}
}
}
void AFCProxyServerToGameModule::OnAckEnterGame(const AFIMsgHead& xHead, const int nMsgID, const char* msg, const uint32_t nLen, const AFGUID& xClientID)
{
AFGUID nPlayerID;
AFMsg::AckEventResult xData;
if(!AFINetServerModule::ReceivePB(xHead, nMsgID, msg, nLen, xData, nPlayerID))
{
return;
}
if(xData.event_code() == AFMsg::EGEC_ENTER_GAME_SUCCESS)
{
const AFGUID& xClient = AFINetServerModule::PBToGUID(xData.event_client());
const AFGUID& xPlayer = AFINetServerModule::PBToGUID(xData.event_object());
m_pProxyServerNet_ServerModule->EnterGameSuccessEvent(xClient, xPlayer);
}
}
void AFCProxyServerToGameModule::OnBrocastmsg(const AFIMsgHead& xHead, const int nMsgID, const char* msg, const uint32_t nLen, const AFGUID& xClientID)
{
//保持记录,直到下线,或者1分钟不上线即可删除
AFGUID nPlayerID;
AFMsg::BrocastMsg xMsg;
if(!AFINetServerModule::ReceivePB(xHead, nMsgID, msg, nLen, xMsg, nPlayerID))
{
return;
}
for(int i = 0; i < xMsg.player_client_list_size(); i++)
{
const AFMsg::Ident& tmpID = xMsg.player_client_list(i);
m_pProxyServerNet_ServerModule->SendToPlayerClient(xMsg.nmsgid(), xMsg.msg_data().c_str(), xMsg.msg_data().size(), AFINetServerModule::PBToGUID(tmpID), nPlayerID);
}
}
void AFCProxyServerToGameModule::LogServerInfo(const std::string& strServerInfo)
{
ARK_LOG_INFO("%s", strServerInfo.c_str());
}
void AFCProxyServerToGameModule::Transpond(const AFIMsgHead& xHead, const int nMsgID, const char * msg, const uint32_t nLen, const AFGUID& xClientID)
{
m_pProxyServerNet_ServerModule->Transpond(xHead, nMsgID, msg, nLen);
} | 39.108374 | 171 | 0.70034 | yebing115 |
599c11f5305faeb0f97c4072f6b1c2288de4d551 | 8,865 | cpp | C++ | Plugins/PLParticleGroups/src/PGFume.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Plugins/PLParticleGroups/src/PGFume.cpp | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 19 | 2018-08-24T08:10:13.000Z | 2018-11-29T06:39:08.000Z | Plugins/PLParticleGroups/src/PGFume.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: PGFume.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <PLCore/Tools/Timing.h>
#include <PLScene/Scene/SceneContext.h>
#include "PLParticleGroups/PGFume.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
using namespace PLCore;
using namespace PLMath;
using namespace PLScene;
namespace PLParticleGroups {
//[-------------------------------------------------------]
//[ RTTI interface ]
//[-------------------------------------------------------]
pl_implement_class(PGFume)
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
/**
* @brief
* Default constructor
*/
PGFume::PGFume() :
Size(this),
SizeTimeScale(this),
Energie(this),
Color(this),
PositionScale(this),
Material(this),
Particles(this),
TextureAnimationColumns(this),
TextureAnimationRows(this),
EventHandlerUpdate(&PGFume::OnUpdate, this),
m_bUpdate(false),
m_fParticleTime(0.0f),
m_bCreateNewParticles(true)
{
// Overwritten SNParticleGroup variables
m_sMaterial = "Data/Effects/PGFume.plfx";
m_nParticles = 20;
m_nTextureAnimationColumns = 4;
m_nTextureAnimationRows = 4;
// Init data
m_SData.fSize = 0.0f;
m_SData.fEnergy = 0.0f;
m_SData.fParticleTime = 0.0f;
}
/**
* @brief
* Destructor
*/
PGFume::~PGFume()
{
}
/**
* @brief
* Returns the default settings of the particle group
*/
void PGFume::GetDefaultSettings(PGFume::InitData &cData) const
{
// Set default settings
cData.fSize = Size;
cData.fEnergy = Energie;
cData.fParticleTime = 0.01f;
}
/**
* @brief
* Returns whether new particles should be created or not
*/
bool PGFume::GetCreateNewParticles() const
{
return m_bCreateNewParticles;
}
/**
* @brief
* Sets whether new particles should be created or not
*/
void PGFume::CreateNewParticles(bool bCreate)
{
m_bCreateNewParticles = bCreate;
}
//[-------------------------------------------------------]
//[ Private virtual PLScene::SceneNode functions ]
//[-------------------------------------------------------]
void PGFume::OnActivate(bool bActivate)
{
// Call the base implementation
SNParticleGroup::OnActivate(bActivate);
// Connect/disconnect event handler
SceneContext *pSceneContext = GetSceneContext();
if (pSceneContext) {
if (bActivate)
pSceneContext->EventUpdate.Connect(EventHandlerUpdate);
else
pSceneContext->EventUpdate.Disconnect(EventHandlerUpdate);
}
}
void PGFume::OnAddedToVisibilityTree(VisNode &cVisNode)
{
m_bUpdate = true;
}
//[-------------------------------------------------------]
//[ Private functions ]
//[-------------------------------------------------------]
/**
* @brief
* Initializes a particle
*/
void PGFume::InitParticle(Particle &cParticle) const
{
float vColor = static_cast<float>(200 + Math::GetRand()%56)/255;
cParticle.vColor[0] = vColor*Color.Get().r;
cParticle.vColor[1] = vColor*Color.Get().g;
cParticle.vColor[2] = vColor*Color.Get().b;
cParticle.vColor[3] = 1.0f;
cParticle.vPos.x = GetTransform().GetPosition().x + Math::GetRandNegFloat()*PositionScale;
cParticle.vPos.y = GetTransform().GetPosition().y + Math::GetRandNegFloat()*PositionScale;
cParticle.vPos.z = GetTransform().GetPosition().z + Math::GetRandNegFloat()*PositionScale;
cParticle.fSize = m_SData.fSize*2;
cParticle.fRot = Math::GetRandNegFloat()*180;
cParticle.fEnergy = 255*m_SData.fEnergy;
cParticle.vVelocity.x = 5.0f + 6.0f * Math::GetRandFloat(); // Lifetime
cParticle.vVelocity.y = 1.0f + 4.0f * Math::GetRandFloat(); // Frequency
cParticle.vVelocity.z = 20.0f + 30.0f * Math::GetRandFloat(); // Intensity
cParticle.vDistortion.x = 0.0f;
cParticle.vDistortion.y = 0.0f;
cParticle.vDistortion.z = 0.0f;
cParticle.fCustom1 = Math::GetRandNegFloat()*0.5f;
}
/**
* @brief
* Called when the scene node needs to be updated
*/
void PGFume::OnUpdate()
{
// If this scene node wasn't drawn at the last frame, we can skip some update stuff
if ((GetFlags() & ForceUpdate) || m_bUpdate) {
m_bUpdate = false;
// Check new particle generation
float fTimeDiff = Timing::GetInstance()->GetTimeDifference();
if (!GetRemoveAutomatically() && m_bCreateNewParticles) {
m_fParticleTime -= fTimeDiff;
if (m_fParticleTime < 0.0f) {
// Create a new particle
m_fParticleTime = m_SData.fParticleTime;
Particle *pParticle = AddParticle();
if (pParticle)
InitParticle(*pParticle);
}
}
uint32 nActive = 0;
{ // Update particles
float fFriction = static_cast<float>(Math::Pow(0.3f, fTimeDiff));
Iterator<Particle> cIterator = GetParticleIterator();
while (cIterator.HasNext()) {
Particle &cParticle = cIterator.Next();
nActive++;
cParticle.fSize += 0.8f*fTimeDiff*SizeTimeScale;
cParticle.vVelocity.x -= fTimeDiff; // Lifetime
cParticle.vVelocity.z -= fTimeDiff*20.0f*Math::GetRandFloat(); // Intensity
cParticle.vPos.x += cParticle.vDistortion.x*fTimeDiff; // Velocity
cParticle.vPos.y += cParticle.vDistortion.y*fTimeDiff;
cParticle.vPos.z += cParticle.vDistortion.z*fTimeDiff;
cParticle.vDistortion.x *= fFriction;
cParticle.vDistortion.y *= fFriction;
cParticle.vDistortion.z *= fFriction;
cParticle.fRot += fTimeDiff*cParticle.fCustom1;
float vColor = (cParticle.vVelocity.z + 30.0f*Math::Sin(cParticle.vVelocity.x*cParticle.vVelocity.y))/255;
if (vColor < 0.0f) {
vColor = 0.0f;
if (cParticle.vVelocity.x <= 0.0f) {
RemoveParticle(cParticle);
continue;
}
}
cParticle.vColor[3] = vColor*Color.Get().a;
// Texture animation
cParticle.fAnimationTimer += fTimeDiff;
if (cParticle.fAnimationTimer > 0.08f) {
cParticle.fAnimationTimer = 0.0f;
cParticle.nAnimationStep++;
if (cParticle.nAnimationStep >= GetTextureAnimationSteps())
cParticle.nAnimationStep = 0;
}
}
}
// Remove particle group?
if (GetRemoveAutomatically() && !nActive)
Delete();
else {
// We have to recalculate the current axis align bounding box in 'scene node space'
DirtyAABoundingBox();
}
}
}
//[-------------------------------------------------------]
//[ Public virtual SNParticleGroup functions ]
//[-------------------------------------------------------]
bool PGFume::InitParticleGroup(uint32 nMaxNumOfParticles, const String &sMaterial, const void *pData)
{
if (pData) {
const InitData &cData = *static_cast<const InitData*>(pData);
m_SData.fSize = cData.fSize;
m_SData.fEnergy = cData.fEnergy;
m_SData.fParticleTime = cData.fParticleTime;
} else {
GetDefaultSettings(m_SData);
}
// Initialize the particles
if (!InitParticles(nMaxNumOfParticles, sMaterial))
return false; // Error!
// Init data
m_fParticleTime = m_SData.fParticleTime;
// Done
return true;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLParticleGroups
| 31.774194 | 110 | 0.593909 | ktotheoz |
599cd6b6b20598bed33179bbb630bc5128ddc745 | 2,382 | cpp | C++ | src/main/tool/ar/override.cpp | kkysen/DifferentiableFuzzer | 22088a3871e4104c4afc463c05ce58f0221dbc43 | [
"MIT"
] | 1 | 2019-06-19T06:03:03.000Z | 2019-06-19T06:03:03.000Z | src/main/tool/ar/override.cpp | kkysen/SmartNeuralFuzzer | 22088a3871e4104c4afc463c05ce58f0221dbc43 | [
"MIT"
] | null | null | null | src/main/tool/ar/override.cpp | kkysen/SmartNeuralFuzzer | 22088a3871e4104c4afc463c05ce58f0221dbc43 | [
"MIT"
] | null | null | null | //
// Created by Khyber on 6/12/2019.
//
#include "src/share/io/Popen.h"
#include "src/share/stde/getline.h"
#include "src/share/stde/addStrings.h"
#include <vector>
#include <fcntl.h>
#include <unistd.h>
std::string escape(std::string_view unescaped) {
std::string escaped;
escaped.reserve(unescaped.size() + unescaped.size() / 2);
for (const auto c : unescaped) {
if (c == '/') {
escaped += '\\';
}
escaped += c;
}
return escaped;
}
void run(bool reset) {
using namespace std::literals;
using stde::string::operator+;
using io::Popen;
// don't need to run repeatedly, just once every time cmake is re-run
// cmake deletes this file to let us know we should run this again
const int fd = ::open(BIN_PATH_AR_LOCK, O_RDWR | (reset ? 0 : O_CREAT | O_EXCL), 0600);
if (fd == -1) {
if (reset) {
::unlink(BIN_PATH_AR_LOCK);
}
::close(fd);
printf("already %soverrode\n", reset ? "un-" : "");
return;
}
FILE& file = *fdopen(fd, "w+");
auto ar = Popen("which llvm-ar").read();
if (ar.back() == '\n') {
ar.pop_back(); // remove trailing '\n'
}
const auto[find, replace] = !reset
? std::pair(std::move(ar), BIN_PATH_AR ""s)
: std::pair(BIN_PATH_AR ""s, std::move(ar));
const auto replaceCommand = "sed -i -e 's/"s + escape(find) + "/"sv + escape(replace) + "/g' "sv;
std::vector<Popen> replacers; // delay closing so they can run in parallel
if (!reset) {
Popen("grep -irl \""s + find + "\" " BIN_PATH""sv)
.forEachLine([&](const std::string_view line) {
if (line.find("CMake") != std::string_view::npos) {
return;
}
const auto path = line;
fwrite(path.data(), 1, path.size(), &file);
replacers.emplace_back(replaceCommand + path);
});
} else {
stde::forEachLine([&](const std::string_view path) {
replacers.emplace_back(replaceCommand + path);
}, file);
::unlink(BIN_PATH_AR_LOCK);
}
fclose(&file);
printf("%soverriding llvm-ar\n", reset ? "un-" : "");
}
int main(int argc, char**) {
run(argc > 1);
}
| 30.538462 | 101 | 0.52225 | kkysen |