hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
โ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
โ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
โ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
โ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
โ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
โ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
โ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
โ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
โ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3f1d9331002cd16fcd383c568dfaca2752d3cebe
| 938
|
cc
|
C++
|
tools/re2c/src/ir/skeleton/maxlen.cc
|
351ELEC/lzdoom
|
2ee3ea91bc9c052b3143f44c96d85df22851426f
|
[
"RSA-MD"
] | 5
|
2021-07-31T03:34:09.000Z
|
2021-08-31T21:43:50.000Z
|
tools/re2c/src/ir/skeleton/maxlen.cc
|
Quake-Backup/Raze
|
16c81f0b1f409436ebf576d2c23f2459a29b34b4
|
[
"RSA-MD"
] | 4
|
2021-09-02T00:05:17.000Z
|
2021-09-07T14:56:12.000Z
|
tools/re2c/src/ir/skeleton/maxlen.cc
|
Quake-Backup/Raze
|
16c81f0b1f409436ebf576d2c23f2459a29b34b4
|
[
"RSA-MD"
] | 1
|
2021-09-28T19:03:39.000Z
|
2021-09-28T19:03:39.000Z
|
#include "src/util/c99_stdint.h"
#include <algorithm>
#include <limits>
#include <map>
#include <utility>
#include "src/ir/skeleton/skeleton.h"
namespace re2c
{
// 0 < DIST_MAX < DIST_ERROR <= std::numeric_limits<uint32_t>::max()
const uint32_t Node::DIST_ERROR = std::numeric_limits<uint32_t>::max();
const uint32_t Node::DIST_MAX = DIST_ERROR - 1;
// different from YYMAXFILL calculation
// in the way it handles loops and empty regexp
void Node::calc_dist ()
{
if (dist != DIST_ERROR)
{
return;
}
else if (end ())
{
dist = 0;
}
else if (loop < 2)
{
local_inc _ (loop);
for (arcs_t::iterator i = arcs.begin (); i != arcs.end (); ++i)
{
i->first->calc_dist ();
if (i->first->dist != DIST_ERROR)
{
if (dist == DIST_ERROR)
{
dist = i->first->dist;
}
else
{
dist = std::max (dist, i->first->dist);
}
}
}
dist = std::min (dist + 1, DIST_MAX);
}
}
} // namespace re2c
| 18.392157
| 71
| 0.609808
|
351ELEC
|
3f2034a3e8cad123ecf68947bd18fadf5d9db21e
| 498
|
cpp
|
C++
|
Niking2D/src/Niking2D/Renderer/VertexArray.cpp
|
SaNeOr/BabaIsYou_Niking2D
|
0fcf92c3b55f7c77950bf87f721b1b0010cf11a7
|
[
"Apache-2.0"
] | 1
|
2020-02-06T18:32:02.000Z
|
2020-02-06T18:32:02.000Z
|
Niking2D/src/Niking2D/Renderer/VertexArray.cpp
|
SaNeOr/BabaIsYou_Niking2D
|
0fcf92c3b55f7c77950bf87f721b1b0010cf11a7
|
[
"Apache-2.0"
] | null | null | null |
Niking2D/src/Niking2D/Renderer/VertexArray.cpp
|
SaNeOr/BabaIsYou_Niking2D
|
0fcf92c3b55f7c77950bf87f721b1b0010cf11a7
|
[
"Apache-2.0"
] | null | null | null |
#include "n2pch.h"
#include "VertexArray.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLVertexArray.h"
namespace Niking2D {
Ref<VertexArray> Niking2D::VertexArray::Create()
{
switch (Renderer::GetAPI()) {
case RendererAPI::API::None: {N2_CORE_ASSERT(false, "RendererAPI::None is currently is not supported!"); return nullptr; }
case RendererAPI::API::OpenGL: return CreateRef<OpenGLVertexArray>();
}
N2_CORE_ASSERT(false, "Unkonw RendererAPI!");
return nullptr;
}
}
| 24.9
| 125
| 0.726908
|
SaNeOr
|
3f20aa8608020d42becbfba298df30270c39a652
| 1,170
|
cc
|
C++
|
python/dune/xt/la/traits.cc
|
dune-community/dune-xt
|
da921524c6fff8d60c715cb4849a0bdd5f020d2b
|
[
"BSD-2-Clause"
] | 2
|
2020-02-08T04:08:52.000Z
|
2020-08-01T18:54:14.000Z
|
python/dune/xt/la/traits.cc
|
dune-community/dune-xt
|
da921524c6fff8d60c715cb4849a0bdd5f020d2b
|
[
"BSD-2-Clause"
] | 35
|
2019-08-19T12:06:35.000Z
|
2020-03-27T08:20:39.000Z
|
python/dune/xt/la/traits.cc
|
dune-community/dune-xt
|
da921524c6fff8d60c715cb4849a0bdd5f020d2b
|
[
"BSD-2-Clause"
] | 1
|
2020-02-08T04:09:34.000Z
|
2020-02-08T04:09:34.000Z
|
// This file is part of the dune-xt project:
// https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt
// Copyright 2009-2021 dune-xt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2020)
#include "config.h"
#include "traits.hh"
PYBIND11_MODULE(_la_traits, m)
{
namespace py = pybind11;
using namespace Dune::XT::LA::bindings;
#define BIND_(NAME) \
pybind11::class_<NAME>(m, #NAME, (std::string("tag: ") + #NAME).c_str()) \
.def(py::init()) \
.def("__repr__", [](const NAME&) { return std::string(#NAME) + "()"; })
BIND_(Common);
BIND_(Eigen);
BIND_(Istl);
BIND_(Dense);
BIND_(Sparse);
#undef BIND_
}
| 35.454545
| 120
| 0.528205
|
dune-community
|
3f23f5ac26ac75fbb2037260daf6c7e5533ba4ea
| 2,450
|
cc
|
C++
|
src/fileio.cc
|
izzyaxel/libcommons
|
3dbdf65fa8af05d3b7beb260bd8211ee4f24cfb0
|
[
"BSD-3-Clause"
] | null | null | null |
src/fileio.cc
|
izzyaxel/libcommons
|
3dbdf65fa8af05d3b7beb260bd8211ee4f24cfb0
|
[
"BSD-3-Clause"
] | null | null | null |
src/fileio.cc
|
izzyaxel/libcommons
|
3dbdf65fa8af05d3b7beb260bd8211ee4f24cfb0
|
[
"BSD-3-Clause"
] | null | null | null |
#include "commons/fileio.hh"
#include <stdexcept>
#include <fstream>
#if defined(WINDOWS)
#include <windows.h>
#include <libloaderapi.h>
#elif defined(LINUX) || defined(OSX)
#include <sys/stat.h>
#include <unistd.h>
#endif
std::string readTextFile(std::string const &filePath)
{
std::ifstream fileIn;
fileIn.open(filePath);
if(!fileIn) printf("Error opening file %s\n", filePath.data());
return {std::istreambuf_iterator<char>(fileIn), std::istreambuf_iterator<char>()};
}
std::vector<uint8_t> readFile(std::string const &filePath)
{
FILE *in = fopen(filePath.data(), "rb");
if(!in)
{
printf("File reader: failed to read input file: %s\n", filePath.data());
return {};
}
fseek(in, SEEK_END, SEEK_SET);
size_t len = (size_t)ftell(in);
rewind(in);
std::vector<uint8_t> data;
data.resize(len);
fread(data.data(), 1, len, in);
fclose(in);
return data;
}
void createDirectory(std::string const &folderPath)
{
#if defined(WINDOWS)
CreateDirectory(folderPath.data(), nullptr);
#elif defined(LINUX) || defined(OSX)
mkdir(folderPath.data(), 0755);
#endif
}
void closeFile(FILE *&file)
{
int result = fclose(file);
if(result != 0) throw std::runtime_error("Failed to close file");
file = nullptr;
}
FILE* openFile(std::string const &name, std::string const &mode)
{
FILE *out = fopen(name.data(), mode.data());
if(!out) throw std::runtime_error("Failed to open " + name + " with mode " + mode);
return out;
}
size_t readFile(FILE *file, void *destBuffer, size_t amount, size_t acceptableTimeouts)
{
size_t amtRead = 0, timeoutCounter = 0;
do
{
if(timeoutCounter >= acceptableTimeouts) throw std::runtime_error("Unable to read from file, timed out after " + std::to_string(acceptableTimeouts) + " 0-length reads");
size_t read = fread(reinterpret_cast<uint8_t *>(destBuffer) + amtRead, 1, amount - amtRead, file);
amtRead += read;
if(read == 0) timeoutCounter++;
} while(amtRead < amount);
return amtRead;
}
size_t writeFile(FILE *file, void const *inputBuffer, size_t amount, size_t acceptableTimeouts)
{
size_t amtWritten = 0, timeoutCounter = 0;
do
{
if(timeoutCounter >= acceptableTimeouts) throw std::runtime_error("Unable to write to file, timed out after " + std::to_string(acceptableTimeouts) + " 0-length writes");
size_t wrote = fwrite(inputBuffer, 1, amount - amtWritten, file);
amtWritten += wrote;
if(wrote == 0) timeoutCounter++;
} while(amtWritten < amount);
return amtWritten;
}
| 27.840909
| 171
| 0.704082
|
izzyaxel
|
3f25b5d2c504fed41cbe13ff407906b44d3140a7
| 2,003
|
cpp
|
C++
|
CraftEngine/ajek-framework/src/x-png-decode.cpp
|
guibec/rpgcraft
|
a4fd84effaf334b1ed637d32b8853b0e6beadf1e
|
[
"MIT"
] | 9
|
2017-04-05T01:42:36.000Z
|
2021-11-14T20:37:58.000Z
|
CraftEngine/ajek-framework/src/x-png-decode.cpp
|
guibec/rpgcraft
|
a4fd84effaf334b1ed637d32b8853b0e6beadf1e
|
[
"MIT"
] | 82
|
2017-04-05T00:26:54.000Z
|
2019-09-21T22:43:09.000Z
|
CraftEngine/ajek-framework/src/x-png-decode.cpp
|
guibec/rpgcraft
|
a4fd84effaf334b1ed637d32b8853b0e6beadf1e
|
[
"MIT"
] | 3
|
2019-01-08T17:11:17.000Z
|
2021-08-11T23:59:23.000Z
|
#include "PCH-framework.h"
#include "x-png-decode.h"
#include "x-stdfile.h"
#include "png.h"
void png_LoadFromFile(xBitmapData& dest, const xString& filename)
{
bug_on (filename.IsEmpty());
bug_on (!xPathIsUniversal(filename)); // paths should be converted at
auto* fp = xFopen(filename, "rb");
x_abort_on (!fp, "png_LoadFromFile('%s') error: %s", filename.c_str(), strerror(errno));
png_LoadFromFile(dest, fp, filename);
fclose(fp);
}
static xString png_errmsg_helper(const xString& filename, const FILE* fp)
{
if (filename.IsEmpty()) {
return xFmtStr("fp=%s", cPtrStr(fp));
}
else {
return xFmtStr("'%s'", filename.c_str());
}
}
// filename_for_error_msg_only - optional filename parameter for use in error messages only.
void png_LoadFromFile(xBitmapData& dest, FILE* fp, const xString& filename_for_error_msg_only)
{
bug_on (!fp);
const xString& filename = filename_for_error_msg_only;
png_image image;
png_color background = {0, 0xff, 0}; /* fully saturated green */
image.version = PNG_IMAGE_VERSION;
image.opaque = NULL;
int beginResult = png_image_begin_read_from_stdio(&image, fp);
x_abort_on(!beginResult, "png_LoadFromFile(%s) read error: %s", png_errmsg_helper(filename, fp), image.message);
// assume any negative size indicates some invalid object state.
dest.size = uint2 { image.width, image.height };
x_abort_on(dest.size.cmp_any() < 0, "png_LoadFromFile(%s) error: invalid object state dest.size={ %s }", png_errmsg_helper(filename, fp), cHexStr(dest.size));
image.format = PNG_FORMAT_RGBA;
dest.buffer.Resize(PNG_IMAGE_SIZE(image));
int finishResult = png_image_finish_read(&image, &background, dest.buffer.GetPtr(),
0, /*row_stride*/
NULL /*colormap for PNG_FORMAT_FLAG_COLORMAP */
);
x_abort_on(!finishResult, "png_LoadFromFile(%s) decode error: %s", png_errmsg_helper(filename, fp), image.message);
}
| 33.949153
| 162
| 0.685971
|
guibec
|
3f2aa04d2767660035d782890d5e9ae883d5557b
| 3,458
|
cpp
|
C++
|
JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/Core/Common/Timer/GameTimer.cpp
|
Jaraffe-github/Old_Engines
|
0586d383af99cfcf076b18dace49e779a55b88e8
|
[
"BSD-3-Clause"
] | null | null | null |
JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/Core/Common/Timer/GameTimer.cpp
|
Jaraffe-github/Old_Engines
|
0586d383af99cfcf076b18dace49e779a55b88e8
|
[
"BSD-3-Clause"
] | null | null | null |
JaraffeEngine_ComponentSystem/Jaraffe/Engine/Source/Core/Common/Timer/GameTimer.cpp
|
Jaraffe-github/Old_Engines
|
0586d383af99cfcf076b18dace49e779a55b88e8
|
[
"BSD-3-Clause"
] | null | null | null |
//***************************************************************************************
// GameTimer.cpp by Frank Luna (C) 2011 All Rights Reserved.
//***************************************************************************************
#include "stdafx.h"
#include "GameTimer.h"
JF::JFCGameTimer::JFCGameTimer()
: m_SecondsPerCount(0.0), m_DeltaTime(-1.0), m_nBaseTime(0),
m_nPausedTime(0), m_nPrevTime(0), m_nCurrTime(0), m_bStopped(false)
{
__int64 countsPerSec;
QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec);
m_SecondsPerCount = 1.0 / (double)countsPerSec;
}
JF::JFCGameTimer::~JFCGameTimer()
{
}
// Returns the total time elapsed since Reset() was called, NOT counting any
// time when the clock is stopped.
float JF::JFCGameTimer::TotalTime() const
{
// If we are stopped, do not count the time that has passed since we stopped.
// Moreover, if we previously already had a pause, the distance
// m_nStopTime - m_nBaseTime includes paused time, which we do not want to count.
// To correct this, we can subtract the paused time from m_nStopTime:
//
// |<--paused time-->|
// ----*---------------*-----------------*------------*------------*------> time
// m_nBaseTime m_nStopTime startTime m_nStopTime m_nCurrTime
if (m_bStopped)
{
return (float)(((m_nStopTime - m_nPausedTime) - m_nBaseTime)*m_SecondsPerCount);
}
// The distance m_nCurrTime - m_nBaseTime includes paused time,
// which we do not want to count. To correct this, we can subtract
// the paused time from m_nCurrTime:
//
// (m_nCurrTime - m_nPausedTime) - m_nBaseTime
//
// |<--paused time-->|
// ----*---------------*-----------------*------------*------> time
// m_nBaseTime m_nStopTime startTime m_nCurrTime
else
{
return (float)(((m_nCurrTime - m_nPausedTime) - m_nBaseTime)*m_SecondsPerCount);
}
}
float JF::JFCGameTimer::DeltaTime() const
{
return (float)m_DeltaTime;
}
void JF::JFCGameTimer::Reset()
{
__int64 currTime;
QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
m_nBaseTime = currTime;
m_nPrevTime = currTime;
m_nStopTime = 0;
m_bStopped = false;
}
void JF::JFCGameTimer::Start()
{
__int64 startTime;
QueryPerformanceCounter((LARGE_INTEGER*)&startTime);
// Accumulate the time elapsed between stop and start pairs.
//
// |<-------d------->|
// ----*---------------*-----------------*------------> time
// m_nBaseTime m_nStopTime startTime
if( m_bStopped )
{
m_nPausedTime += (startTime - m_nStopTime);
m_nPrevTime = startTime;
m_nStopTime = 0;
m_bStopped = false;
}
}
void JF::JFCGameTimer::Stop()
{
if( !m_bStopped )
{
__int64 currTime;
QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
m_nStopTime = currTime;
m_bStopped = true;
}
}
void JF::JFCGameTimer::Tick()
{
if( m_bStopped )
{
m_DeltaTime = 0.0;
return;
}
__int64 currTime;
QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
m_nCurrTime = currTime;
// Time difference between this frame and the previous.
m_DeltaTime = (m_nCurrTime - m_nPrevTime)*m_SecondsPerCount;
// Prepare for next frame.
m_nPrevTime = m_nCurrTime;
// Force nonnegative. The DXSDK's CDXUTTimer mentions that if the
// processor goes into a power save mode or we get shuffled to another
// processor, then m_DeltaTime can be negative.
if(m_DeltaTime < 0.0)
{
m_DeltaTime = 0.0;
}
}
| 26.396947
| 89
| 0.614806
|
Jaraffe-github
|
3f2e6b46b26fa9f78f9e4bd5de37a97c81977448
| 3,993
|
hpp
|
C++
|
src/Rendering/Base/include/HG/Rendering/Base/MaterialCollection.hpp
|
Megaxela/HGEngineReloaded
|
62d319308c2d8a62f6854721c31afc4981aa13df
|
[
"MIT"
] | 2
|
2021-02-26T05:25:48.000Z
|
2021-09-16T22:30:41.000Z
|
src/Rendering/Base/include/HG/Rendering/Base/MaterialCollection.hpp
|
Megaxela/HGEngineReloaded
|
62d319308c2d8a62f6854721c31afc4981aa13df
|
[
"MIT"
] | 1
|
2019-10-19T10:36:43.000Z
|
2019-10-19T10:36:43.000Z
|
src/Rendering/Base/include/HG/Rendering/Base/MaterialCollection.hpp
|
Megaxela/HGEngineReloaded
|
62d319308c2d8a62f6854721c31afc4981aa13df
|
[
"MIT"
] | 2
|
2019-10-22T18:56:59.000Z
|
2020-03-12T04:38:31.000Z
|
#pragma once
// C++ STL
#include <utility>
// HG::Core
#include <HG/Core/ResourceManager.hpp>
// HG::Rendering::Base
#include <HG/Rendering/Base/Material.hpp>
#include <HG/Rendering/Base/Shader.hpp>
// HG::Utils
#include <HG/Utils/Loaders/StringLoader.hpp>
namespace HG::Rendering::Base
{
class Renderer;
/**
* @brief Class, that describes
* material management system. It caches
* shader information and generates materials
* with cached shaders.
*/
class MaterialCollection
{
public:
/**
* @brief Constructor.
* @param Root application.
*/
explicit MaterialCollection(HG::Core::ResourceManager* resourceManager, HG::Rendering::Base::Renderer* pipeline);
/**
* @brief Destructor.
*/
~MaterialCollection();
/**
* @brief Method for getting material
* (and loading shader if required)
* @tparam MaterialType Type of material.
* @return Material.
*/
template <typename MaterialType>
typename std::enable_if<std::is_base_of<HG::Rendering::Base::Material, MaterialType>::value, MaterialType*>::type
getMaterial()
{
auto typeHash = typeid(MaterialType).hash_code();
auto shader = m_shaders.find(typeHash);
if (shader == m_shaders.end())
{
prepareMaterial<MaterialType>();
}
shader = m_shaders.find(typeHash);
auto newMaterial = new MaterialType;
newMaterial->setShader(shader->second);
return newMaterial;
}
/**
* @brief Method for preparing material's shader.
* @tparam MaterialType Type of material.
* @return Material.
*/
template <typename MaterialType>
typename std::enable_if<std::is_base_of<HG::Rendering::Base::Material, MaterialType>::value>::type prepareMaterial()
{
static_assert(has_raw_text<MaterialType>::value != sizeof(typename has_raw_text<MaterialType>::hasNothing),
"Material does not contains `rawShader` or `shaderPath`, or it cannot be accessed.");
auto typeHash = typeid(MaterialType).hash_code();
if (m_shaders.find(typeHash) != m_shaders.end())
{
return;
}
// Creating shader
auto newShader = new (m_resourceManager->application()->resourceCache()) HG::Rendering::Base::Shader();
if constexpr (has_raw_text<MaterialType>::value == sizeof(typename has_raw_text<MaterialType>::hasRawData))
{
newShader->setShaderText(MaterialType::rawShader);
m_shaders[typeHash] = newShader;
}
else if constexpr (has_raw_text<MaterialType>::value == sizeof(typename has_raw_text<MaterialType>::hasPaths))
{
auto shaderData = m_resourceManager->load<HG::Utils::StringLoader>(MaterialType::shaderPath);
newShader->setShaderText(shaderData);
}
setup(newShader);
}
/**
* @brief Method for clearing shader cache.
*/
void clearCache();
private:
// RAW shader text test
template <typename T>
class has_raw_text
{
public:
typedef uint8_t hasRawData;
typedef uint16_t hasPaths;
typedef uint32_t hasNothing;
private:
template <typename C>
static hasRawData test(decltype(C::rawShader));
template <typename C>
static hasPaths test(decltype(C::shaderPath));
template <typename C>
static hasNothing test(...);
public:
enum
{
value = sizeof(test<T>(0))
};
};
/**
* @brief Method for setting up shader. (Method
* implemented to decouple Renderer.hpp and MaterialCollection.hpp.
* @param shader Pointer to shader.
*/
void setup(HG::Rendering::Base::Shader* shader);
HG::Core::ResourceManager* m_resourceManager;
std::unordered_map<std::size_t, HG::Rendering::Base::Shader*> m_shaders;
HG::Rendering::Base::Renderer* m_renderer;
};
} // namespace HG::Rendering::Base
| 26.62
| 120
| 0.636614
|
Megaxela
|
3f35e9b62cfa00b9d2b43c3677d86f2efbe3e345
| 16,494
|
cpp
|
C++
|
src/gbutton.cpp
|
klei1984/max
|
dc0f9108bbcfd4cb73ea101883d551c612097469
|
[
"MIT"
] | 19
|
2020-02-06T17:41:39.000Z
|
2022-03-31T07:38:15.000Z
|
src/gbutton.cpp
|
klei1984/max
|
dc0f9108bbcfd4cb73ea101883d551c612097469
|
[
"MIT"
] | 9
|
2020-02-14T15:46:46.000Z
|
2021-12-22T16:35:53.000Z
|
src/gbutton.cpp
|
klei1984/max
|
dc0f9108bbcfd4cb73ea101883d551c612097469
|
[
"MIT"
] | null | null | null |
/* Copyright (c) 2021 M.A.X. Port Team
*
* 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 "gbutton.h"
#include <new>
#include "SDL_assert.h"
#define RESRCMGR_H
#include "gwindow.h"
#include "soundmgr.hpp"
static_assert(sizeof(GButton) == 56, "The structure needs to be packed.");
static void gbutton_get_button_rect(GButton *b, Rect *r);
static unsigned char *gbutton_get_up_image(GButton *b);
static unsigned char *gbutton_get_down_image(GButton *b);
static unsigned char *gbutton_get_up_disabled_image(GButton *b);
static unsigned char *gbutton_get_down_disabled_image(GButton *b);
static void gbutton_p_func(ButtonID bid, GButton *b);
static void gbutton_r_func(ButtonID bid, GButton *b);
void gbutton_init(GButton *b) {
b->bid = 0;
b->up = NULL;
b->down = NULL;
b->up_disabled = NULL;
b->down_disabled = NULL;
b->p_value = -1;
b->r_value = -1;
b->flags = 0;
b->p_func = NULL;
b->r_func = NULL;
b->wid = 0;
b->sfx = -1;
b->rest_state = 0;
}
GButton *gbutton_init_rect(GButton *b, int ulx, int uly, int lrx, int lry) {
gbutton_init(b);
b->ulx = ulx;
b->uly = uly;
b->lrx = lrx;
b->lry = lry;
b->enable = 1;
b->sfx = -1;
return b;
}
GButton *gbutton_init_texture(GButton *b, GAME_RESOURCE up, GAME_RESOURCE down, int ulx, int uly) {
gbutton_init(b);
GImage *image_up = new (std::nothrow) GImage();
if (image_up) {
image_up = gimage_init(image_up, up, ulx, uly);
} else {
image_up = NULL;
}
b->up = image_up;
b->ulx = gimage_get_ulx(b->up);
b->uly = gimage_get_uly(b->up);
b->lrx = gimage_get_width(b->up);
b->lry = gimage_get_height(b->up);
GImage *image_down = new (std::nothrow) GImage();
if (image_down) {
image_down = gimage_init(image_down, down, b->ulx, b->uly);
} else {
image_down = NULL;
}
b->down = image_down;
b->enable = 1;
return b;
}
GButton *gbutton_delete(GButton *b) {
if (b->bid) {
if (b->wid) {
GImage *image = new (std::nothrow) GImage();
SDL_assert(image);
gimage_alloc_ex(image, b->ulx, b->uly, b->lrx, b->lry);
WindowInfo window;
window.id = b->wid;
window.buffer = win_get_buf(b->wid);
window.width = win_width(b->wid);
gimage_copy_from_window(image, &window);
win_delete_button(b->bid);
gimage_copy_to_window(image, &window);
delete gimage_delete(image);
} else {
win_delete_button(b->bid);
}
}
if (b->up) {
delete gimage_delete(b->up);
b->up = NULL;
}
if (b->down) {
delete gimage_delete(b->down);
b->down = NULL;
}
if (b->up_disabled) {
delete gimage_delete(b->up_disabled);
b->up_disabled = NULL;
}
if (b->down_disabled) {
delete gimage_delete(b->down_disabled);
b->down_disabled = NULL;
}
return b;
}
void gbutton_alloc(GButton *b) {
if (b->up) {
gimage_alloc(b->up);
}
if (b->down) {
gimage_alloc(b->down);
}
if (b->up_disabled) {
gimage_alloc(b->up_disabled);
}
if (b->down_disabled) {
gimage_alloc(b->down_disabled);
}
}
void gbutton_get_button_rect(GButton *b, Rect *r) {
r->ulx = b->ulx;
r->uly = b->uly;
r->lrx = b->lrx + b->ulx;
r->lry = b->lry + b->uly;
}
unsigned char *gbutton_get_up_image(GButton *b) {
unsigned char *buffer;
if (b->up) {
buffer = gimage_get_buffer(b->up);
} else {
buffer = NULL;
}
return buffer;
}
unsigned char *gbutton_get_down_image(GButton *b) {
unsigned char *buffer;
if (b->down) {
buffer = gimage_get_buffer(b->down);
} else {
buffer = NULL;
}
return buffer;
}
unsigned char *gbutton_get_up_disabled_image(GButton *b) {
unsigned char *buffer;
if (b->up_disabled) {
buffer = gimage_get_buffer(b->up_disabled);
} else {
buffer = gbutton_get_up_image(b);
}
return buffer;
}
unsigned char *gbutton_get_down_disabled_image(GButton *b) {
unsigned char *buffer;
if (b->down_disabled) {
buffer = gimage_get_buffer(b->down_disabled);
} else {
buffer = gbutton_get_down_image(b);
}
return buffer;
}
void gbutton_copy_from_window(GButton *b, WinID wid) {
WindowInfo window;
GImage *source_image;
window.id = wid;
window.buffer = win_get_buf(wid);
window.width = win_width(wid);
source_image = new (std::nothrow) GImage();
SDL_assert(source_image);
gimage_alloc_ex(source_image, b->ulx, b->uly, b->lrx, b->lry);
gimage_copy_from_window(source_image, &window);
if (b->up) {
GImage *up_image;
up_image = new (std::nothrow) GImage();
SDL_assert(up_image);
gimage_alloc_ex(up_image, b->ulx, b->uly, b->lrx, b->lry);
gimage_copy_from_image(up_image, source_image);
gimage_copy_content(up_image, b->up);
if (b->up) {
delete gimage_delete(b->up);
}
b->up = up_image;
}
if (b->down) {
GImage *down_image;
down_image = new (std::nothrow) GImage();
SDL_assert(down_image);
gimage_alloc_ex(down_image, b->ulx, b->uly, b->lrx, b->lry);
gimage_copy_from_image(down_image, source_image);
gimage_copy_content(down_image, b->down);
if (b->down) {
delete gimage_delete(b->down);
}
b->down = down_image;
}
if (b->up_disabled) {
GImage *up_disabled_image;
up_disabled_image = new (std::nothrow) GImage();
SDL_assert(up_disabled_image);
gimage_alloc_ex(up_disabled_image, b->ulx, b->uly, b->lrx, b->lry);
gimage_copy_from_image(up_disabled_image, source_image);
gimage_copy_content(up_disabled_image, b->up_disabled);
if (b->up_disabled) {
delete gimage_delete(b->up_disabled);
}
b->up_disabled = up_disabled_image;
}
if (b->down_disabled) {
GImage *down_disabled_image;
down_disabled_image = new (std::nothrow) GImage();
SDL_assert(down_disabled_image);
gimage_alloc_ex(down_disabled_image, b->ulx, b->uly, b->lrx, b->lry);
gimage_copy_from_image(down_disabled_image, source_image);
gimage_copy_content(down_disabled_image, b->down_disabled);
if (b->down_disabled) {
delete gimage_delete(b->down_disabled);
}
b->down_disabled = down_disabled_image;
}
delete gimage_delete(source_image);
}
void gbutton_copy_from_resource(GButton *b, GAME_RESOURCE id, int ulx, int uly) {
WindowInfo window;
gbutton_alloc(b);
window.width = b->lrx;
window.window.ulx = 0;
window.window.uly = 0;
window.window.lrx = b->lrx;
window.window.lry = b->lry;
window.buffer = gimage_get_buffer(b->up);
gwin_load_image2(id, ulx, uly, 1, &window);
window.buffer = gimage_get_buffer(b->down);
gwin_load_image2(id, ulx, uly + 1, 1, &window);
}
void gbutton_copy_disabled_from_window(GButton *b, WindowInfo *w) {
GImage *up_disabled_image;
GImage *down_disabled_image;
if (b->up_disabled) {
delete gimage_delete(b->up_disabled);
}
if (b->down_disabled) {
delete gimage_delete(b->down_disabled);
}
up_disabled_image = new (std::nothrow) GImage();
if (up_disabled_image) {
gimage_alloc_ex(up_disabled_image, b->ulx, b->uly, b->lrx, b->lry);
}
b->up_disabled = up_disabled_image;
down_disabled_image = new (std::nothrow) GImage();
if (down_disabled_image) {
down_disabled_image = gimage_alloc_ex(down_disabled_image, b->ulx, b->uly, b->lrx, b->lry);
}
b->down_disabled = down_disabled_image;
gimage_copy_from_window(b->up_disabled, w);
gimage_copy_from_image(b->down_disabled, b->up_disabled);
}
void gbutton_copy_up_from_resource(GButton *b, GAME_RESOURCE id) {
GImage *image;
if (b->up) {
delete gimage_delete(b->up);
}
image = new (std::nothrow) GImage();
if (image) {
gimage_init(image, id, b->ulx, b->uly);
}
b->up = image;
}
void gbutton_copy_down_from_resource(GButton *b, GAME_RESOURCE id) {
GImage *image;
if (b->down) {
delete gimage_delete(b->down);
}
image = new (std::nothrow) GImage();
if (image) {
gimage_init(image, id, b->ulx, b->uly);
}
b->down = image;
}
void gbutton_copy_up_disabled_from_resource(GButton *b, GAME_RESOURCE id) {
GImage *image;
if (b->up_disabled) {
delete gimage_delete(b->up_disabled);
}
image = new (std::nothrow) GImage();
if (image) {
gimage_init(image, id, b->ulx, b->uly);
}
b->up_disabled = image;
}
void gbutton_copy_down_disabled_from_resource(GButton *b, GAME_RESOURCE id) {
GImage *image;
if (b->down_disabled) {
delete gimage_delete(b->down_disabled);
}
image = new (std::nothrow) GImage();
if (image) {
gimage_init(image, id, b->ulx, b->uly);
}
b->down_disabled = image;
}
void gbutton_copy_up_from_buffer(GButton *b, unsigned char *buffer) {
GImage *image;
if (b->up) {
delete gimage_delete(b->up);
}
image = new (std::nothrow) GImage();
if (image) {
gimage_alloc_ex(image, b->ulx, b->uly, b->lrx, b->lry);
}
b->up = image;
buf_to_buf(buffer, b->lrx, b->lry, b->lrx, gimage_get_buffer(b->up), b->lrx);
}
void gbutton_copy_down_from_buffer(GButton *b, unsigned char *buffer) {
GImage *image;
if (b->down) {
delete gimage_delete(b->down);
}
image = new (std::nothrow) GImage();
if (image) {
gimage_alloc_ex(image, b->ulx, b->uly, b->lrx, b->lry);
}
b->down = image;
buf_to_buf(buffer, b->lrx, b->lry, b->lrx, gimage_get_buffer(b->down), b->lrx);
}
void gbutton_copy_up_disabled_from_buffer(GButton *b, unsigned char *buffer) {
GImage *image;
if (b->up_disabled) {
delete gimage_delete(b->up_disabled);
}
image = new (std::nothrow) GImage();
if (image) {
gimage_alloc_ex(image, b->ulx, b->uly, b->lrx, b->lry);
}
b->up_disabled = image;
buf_to_buf(buffer, b->lrx, b->lry, b->lrx, gimage_get_buffer(b->up_disabled), b->lrx);
}
void gbutton_copy_down_disabled_from_buffer(GButton *b, unsigned char *buffer) {
GImage *image;
if (b->down_disabled) {
delete gimage_delete(b->down_disabled);
}
image = new (std::nothrow) GImage();
if (image) {
gimage_alloc_ex(image, b->ulx, b->uly, b->lrx, b->lry);
}
b->down_disabled = image;
buf_to_buf(buffer, b->lrx, b->lry, b->lrx, gimage_get_buffer(b->down_disabled), b->lrx);
}
void gbutton_set_p_func(GButton *b, ButtonFunc p_func, int p_value) {
b->p_func = p_func;
b->p_value = p_value;
}
void gbutton_set_r_func(GButton *b, ButtonFunc r_func, int r_value) {
b->r_func = r_func;
b->r_value = r_value;
}
void gbutton_register_button(GButton *b, WinID wid) {
WindowInfo w;
GImage *image;
unsigned char *up;
unsigned char *down;
int flags;
int r_value;
int p_value;
if (b->down && ((gimage_get_width(b->down) != b->lrx) || (gimage_get_height(b->down) != b->lry))) {
w.id = wid;
w.buffer = win_get_buf(wid);
w.width = win_width(wid);
image = new (std::nothrow) GImage();
if (image) {
gimage_alloc_ex(image, b->ulx, b->uly, b->lrx, b->lry);
}
gimage_copy_from_window(image, &w);
gimage_copy_from_image(image, b->down);
if (b->down) {
delete gimage_delete(b->down);
}
b->down = image;
}
flags = b->flags;
if (b->enable) {
up = gbutton_get_up_image(b);
down = gbutton_get_down_image(b);
} else {
up = gbutton_get_up_disabled_image(b);
down = gbutton_get_down_disabled_image(b);
b->flags |= 8u;
}
p_value = b->p_value;
r_value = b->r_value;
if (b->p_func || b->r_func) {
p_value = (int)b;
r_value = (int)b;
}
b->bid = win_register_button(wid, b->ulx, b->uly, b->lrx, b->lry, -1, -1, p_value, r_value, (char *)up,
(char *)down, NULL, flags);
if (b->p_func || b->r_func) {
win_register_button_func(b->bid, NULL, NULL, (ButtonFunc)gbutton_p_func, (ButtonFunc)gbutton_r_func);
}
b->wid = wid;
}
void gbutton_enable(GButton *b, char enable, char redraw) {
if (enable) {
if (!b->enable) {
if (b->bid) {
win_enable_button(b->bid);
win_register_button_image(b->bid, (char *)gbutton_get_up_image(b), (char *)gbutton_get_down_image(b),
NULL, redraw);
}
b->enable = 1;
}
} else {
gbutton_disable(b, 1);
}
}
void gbutton_disable(GButton *b, char redraw) {
if (b->enable) {
if (b->bid) {
win_register_button_image(b->bid, (char *)gbutton_get_up_disabled_image(b),
(char *)gbutton_get_down_disabled_image(b), NULL, redraw);
win_disable_button(b->bid);
}
b->enable = 0;
}
}
void gbutton_set_rest_state(GButton *b, char rest_state) {
if (b->bid) {
win_set_button_rest_state(b->bid, rest_state, 0);
b->rest_state = rest_state;
}
}
void gbutton_play_sound(GButton *b) { soundmgr.PlaySfx((ResourceID)b->sfx); }
static inline void gbutton_watcall(ButtonFunc func, ButtonID id, int value) {
__asm__ __volatile__(" call *%2\n"
: /* out */
: /* in */ "a"(id), "d"(value), "b"(func)
: /* clob */);
}
void gbutton_p_func(ButtonID bid, GButton *b) {
if (!b->rest_state) {
b->rest_state = 1;
if (b->sfx != -1) {
gbutton_play_sound(b);
}
}
if (b->p_func) {
gbutton_watcall(b->p_func, bid, b->p_value);
/// \todo b->p_func(bid, b->p_value);
}
}
void gbutton_r_func(ButtonID bid, GButton *b) {
b->rest_state = 0;
if (b->r_func) {
gbutton_watcall(b->r_func, bid, b->r_value);
/// \todo b->r_func(bid, b->r_value);
}
}
void gbutton_set_sfx(GButton *b, GAME_RESOURCE id) { b->sfx = id; }
ButtonID gbutton_get_button_id(GButton *b) { return b->bid; }
void gbutton_set_r_value(GButton *b, int r_value) { b->r_value = r_value; }
void gbutton_set_p_value(GButton *b, int p_value) { b->p_value = p_value; }
void gbutton_set_flags(GButton *b, int flags) { b->flags = flags; }
| 26.056872
| 118
| 0.579908
|
klei1984
|
3f3792ed733c7cf77c30db5f92a9166fd2b5f49e
| 2,140
|
cpp
|
C++
|
C++/014. Longest Common Prefix.cpp
|
WangYang-wy/LeetCode
|
c92fcb83f86c277de6785d5a950f16bc007ccd31
|
[
"MIT"
] | 3
|
2018-07-28T15:36:18.000Z
|
2020-03-17T01:26:22.000Z
|
C++/014. Longest Common Prefix.cpp
|
WangYang-wy/LeetCode
|
c92fcb83f86c277de6785d5a950f16bc007ccd31
|
[
"MIT"
] | null | null | null |
C++/014. Longest Common Prefix.cpp
|
WangYang-wy/LeetCode
|
c92fcb83f86c277de6785d5a950f16bc007ccd31
|
[
"MIT"
] | null | null | null |
//
// Created by ็้ณ on 2018/3/28.
//
/*
* Write a function to find the longest common prefix string amongst an array of strings.
*/
#include "header.h"
class Solution {
public:
string longestCommonPrefix(vector <string> &strs) {
if (strs.size() == 0) {
return ""; // ๅฆๆๆฒกๆๅญ็ฌฆไธฒใ
}
char *str = (char *) malloc(sizeof(char) * (strs[0].size() + 1));
for (int i = 0; i < strs[0].size(); i++) {
str[i] = strs[0][i];
}
str[strs[0].size()] = 0; // ่ฎพ็ฝฎ็ป็ป็ฌฆใ
for (int i = 1; i < strs.size(); i++) {
int j = 0;
while (str[j] && strs[i][j] && str[j] == strs[i][j]) {
j++; // ๅพช็ฏๆฏไธชๅญ็ฌฆไธฒใ
}
str[j] = 0; // ไปๅทฆๅฐๅณๅผๅงๅคๆญๆฏๅฆ็ธ็ญใ
}
return string(str);
}
/**
* ๆฌๅฐๆ ้๏ผๆไบคLeetCodeๆ้ใ
* @param strs ๅญ็ฌฆไธฒๆฐ็ปใ
* @return ๆ้ฟๅ
ฌๅ
ฑๅญๅบๅใ
*/
string longestCommonPrefix_ERROR(vector <string> &strs) {
printf("length = %d\n", strs.size());
if (0 == strs.size()) {
return "";
} else if (1 == strs.size()) { // ๅฆๆๅชๆไธไธชๅญ็ฌฆไธฒ๏ผ้ฃไน็ดๆฅ่ฟๅใ
return strs[0];
} else { // ๅญ็ฌฆไธฒๆฐ็ป๏ผๅคงไบ็ญไบ2ไธชใ
int index = 0;
for (int i = 0; i < strs[0].length(); i++) {
int flag = 0;
for (int j = 1; j < strs.size(); j++) {
if (strs[0][i] != strs[j][i]) {
flag = 1; // ่กจ็คบไธๅน้
ไบใ
break;
}
}
if (0 == flag) {
index++;
}
}
printf("index = %d\n", index);
string res = "";
for (int i = 0; i < index; i++) {
res = res + strs[0][i];
}
return res;
}
}
};
int main() {
Solution *solution = new Solution();
vector <string> *a = new vector<string>();
string s1 = "abab";
string s2 = "aba";
string s3 = "";
a->push_back(s1);
a->push_back(s2);
a->push_back(s3);
printf("%s\n", solution->longestCommonPrefix(*a).c_str());
return 0;
}
| 25.47619
| 89
| 0.413084
|
WangYang-wy
|
3f383172919759efce2a2e4f55029a8ac10a0743
| 4,346
|
cpp
|
C++
|
ProjectEuler+/euler-0178.cpp
|
sarvekash/HackerRank_Solutions
|
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
|
[
"Apache-2.0"
] | null | null | null |
ProjectEuler+/euler-0178.cpp
|
sarvekash/HackerRank_Solutions
|
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
|
[
"Apache-2.0"
] | null | null | null |
ProjectEuler+/euler-0178.cpp
|
sarvekash/HackerRank_Solutions
|
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
|
[
"Apache-2.0"
] | 1
|
2021-05-28T11:14:34.000Z
|
2021-05-28T11:14:34.000Z
|
// ////////////////////////////////////////////////////////
// # Title
// Step Numbers
//
// # URL
// https://projecteuler.net/problem=178
// http://euler.stephan-brumme.com/178/
//
// # Problem
// Consider the number 45656.
// It can be seen that each pair of consecutive digits of 45656 has a difference of one.
// A number for which every pair of consecutive digits has a difference of one is called a step number.
// A pandigital number contains every decimal digit from 0 to 9 at least once.
// How many pandigital step numbers less than `10^40` are there?
//
// # Solved by
// Stephan Brumme
// June 2017
//
// # Algorithm
// And again: it's time for Dynamic Programming ...
// My ''search'' function has three parameters:
// 1. a mask where bit x is set if any of the digits in front of the current digit was x.
// 2. the current digit
// 3. how many digits still have to be processed
//
// A number is pandigital if the all bits 0..9 are set (''AllDigits = (1 << 10) - 1'' which is 1023).
// If the current digit is bigger than 0, then the next can be "a step down".
// If the current digit is smaller than 9, then the next can be "a step up".
//
// Of course, this algorithm would be far too slow, but the algorithm can heavily memoize results.
// The function's parameters are merged into a single unique ID and stored in a ''cache'' (with 1024*40*10 = 409600 entries, which requires about 3 MByte RAM).
//
// # Note
// If the first digit is between 1 and 4 (inclusive), then for every solution there is a "mirrored" version, where each digit `b_i = 9 - a_i`.
// For example, 10123456789 is a solution and therefore 89876543210 is a solution, too.
// How does it help ? Well, you can compute all solutions starting with 1..4, multiply that number by 2 and add all solutions starting with 9.
//
// # Hackerrank
// They want you to compute the result for `n < 10^{10^4}`. I can't figure out whether their input is always a power-of-ten or not.
// The result will easily be too large for C++'s 64 bit integers anyway.
#include <iostream>
#include <vector>
// initial state: no digits used, all bits are zero
const unsigned int NoDigits = 0;
// all ten digits used => all ten bits set
const unsigned int AllDigits = (1 << 10) - 1; // = 1023
// analyze all numbers with up to 10^40
const unsigned int MaxDigits = 40;
// count pandigital step number where bits in "mask" are set according to the first digits
// and the current digit is "currentDigit" with "numDigitsLeft" digits to go
unsigned long long search(unsigned int mask, unsigned int currentDigit, unsigned int numDigitsLeft)
{
// update mask, "use digit"
mask |= 1 << currentDigit;
// arrived at last digit ?
if (numDigitsLeft == 1)
{
// all ten bits set ? => pandigital
if (mask == AllDigits)
return 1; // yes, a solution
// not pandigital, no valid solution
return 0;
}
// memoize
unsigned int hash = mask * MaxDigits * 10 + (numDigitsLeft - 1) * 10 + currentDigit;
static std::vector<unsigned long long> cache(1024 * 10 * MaxDigits, 0);
// result already known ?
if (cache[hash] != 0)
return cache[hash];
unsigned long long result = 0;
// next digit is smaller
if (currentDigit > 0)
result += search(mask, currentDigit - 1, numDigitsLeft - 1);
// next digit is bigger
if (currentDigit < 9)
result += search(mask, currentDigit + 1, numDigitsLeft - 1);
cache[hash] = result;
return result;
}
int main()
{
// maxDigits is the actual number of digits
// MaxDigits is the highest allowed value for maxDigits
// I know, it's confusing ...
unsigned int maxDigits = 40;
std::cin >> maxDigits;
// note: input syntax differs from Hackerrank !
unsigned long long result = 0;
// for each number of digits ...
for (unsigned int numDigits = 1; numDigits <= maxDigits; numDigits++)
{
// ... the first one must be 1..9 (and never zero !)
for (unsigned int digit = 1; digit <= 9; digit++)
result += search(NoDigits, digit, numDigits);
// a little bit faster:
//result += 2 * search(NoDigits, 1, numDigits);
//result += 2 * search(NoDigits, 2, numDigits);
//result += 2 * search(NoDigits, 3, numDigits);
//result += 2 * search(NoDigits, 4, numDigits);
//result += search(NoDigits, 9, numDigits);
}
std::cout << result << std::endl;
return 0;
}
| 36.830508
| 159
| 0.668661
|
sarvekash
|
2786811c2154e399199df90e6c754613fd524dc0
| 2,476
|
cpp
|
C++
|
src/pix/box.cpp
|
Sonotsugipaa/pixnn
|
ad0499522c65d118d5f4beffa556f0b3a809a949
|
[
"MIT"
] | 1
|
2019-09-28T20:50:50.000Z
|
2019-09-28T20:50:50.000Z
|
src/pix/box.cpp
|
Sonotsugipaa/pixnn
|
ad0499522c65d118d5f4beffa556f0b3a809a949
|
[
"MIT"
] | null | null | null |
src/pix/box.cpp
|
Sonotsugipaa/pixnn
|
ad0499522c65d118d5f4beffa556f0b3a809a949
|
[
"MIT"
] | null | null | null |
#include "pix/box_async.hpp"
#include <mutex>
namespace pix {
Box::Box(
gla::ShaderProgram& sp,
unsigned int w,
unsigned int h,
glm::vec4 color,
glm::vec2 top_left,
glm::vec2 bottom_right,
GLfloat depth
):
Canvas::Canvas(w, h),
shader (sp),
vb (GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW),
z (depth),
vertices {
{ top_left[1], bottom_right[0], 0.0f, 0.0f },
{ top_left[1], top_left[0], 0.0f, 1.0f },
{ bottom_right[1], top_left[0], 1.0f, 1.0f },
{ bottom_right[1], bottom_right[0], 1.0f, 0.0f }
},
color (color)
{
vb.bufferData(vertices, 4 * 4 * sizeof(GLfloat));
va.assignVertexBuffer(
vb, sp.getAttrib("in_position"),
2, GL_FLOAT, GL_FALSE,
4 * sizeof(GLfloat), (GLfloat*) (0 * sizeof(GLfloat)) );
va.assignVertexBuffer(
vb, sp.getAttrib("in_tex"),
2, GL_FLOAT, GL_FALSE,
4 * sizeof(GLfloat), (GLfloat*) (2 * sizeof(GLfloat)) );
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
}
void Box::updateTexture() {
if(! cached) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA,
Canvas::width, Canvas::height, 0,
GL_RGBA, GL_FLOAT, Canvas::data
);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
cached = true;
}
}
void Box::draw() {
va.bind();
updateTexture();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_id);
glUniform1i(shader.getUniform("box_texture"), 0);
glUniform1f(shader.getUniform("z"), 0.0f);
glUniform4fv(shader.getUniform("color"), 1, &(color[0]));
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
namespace pix {
AsyncBox::AsyncBox(
gla::ShaderProgram& sp,
unsigned int w,
unsigned int h,
glm::vec4 c,
glm::vec2 tl,
glm::vec2 br,
GLfloat d
):
Box::Box (sp, w, h, c, tl, br, d),
mutex ()
{ }
void AsyncBox::draw() {
auto lock = std::unique_lock<std::mutex>();
Box::draw();
}
void AsyncBox::updateTexture() {
auto lock = std::unique_lock<std::mutex>();
Box::updateTexture();
}
}
| 23.140187
| 72
| 0.662359
|
Sonotsugipaa
|
2788547f3838e911af852d5eb4c84b0db18f6905
| 424
|
cpp
|
C++
|
src/Edge.cpp
|
the13fools/fieldgen
|
6b1757e1a75cd65b73526aa9c200303fbee4d669
|
[
"Unlicense",
"MIT"
] | 93
|
2019-06-04T06:56:49.000Z
|
2022-03-30T08:44:58.000Z
|
src/Edge.cpp
|
the13fools/fieldgen
|
6b1757e1a75cd65b73526aa9c200303fbee4d669
|
[
"Unlicense",
"MIT"
] | 1
|
2020-02-06T14:56:41.000Z
|
2020-07-15T17:31:29.000Z
|
src/Edge.cpp
|
the13fools/fieldgen
|
6b1757e1a75cd65b73526aa9c200303fbee4d669
|
[
"Unlicense",
"MIT"
] | 11
|
2019-06-06T21:11:29.000Z
|
2021-08-14T05:06:16.000Z
|
#include "Edge.h"
#include "Mesh.h"
#include "HalfEdge.h"
namespace DDG
{
// only needed for old code
const Vector Edge::Xvector( void ) const {
return X()->next->vertex->position - X()->vertex->position;
}
// standard cotan Laplace coeff for this edge
const double Edge::cot( void ) const {
return .5 * ( ( he->onBoundary ? 0 : he->cot() ) +
( he->flip->onBoundary ? 0 : he->flip->cot() ) );
}
}
| 22.315789
| 63
| 0.606132
|
the13fools
|
278c9df25f31c7311880ac73a578f64bc25e0250
| 1,176
|
cc
|
C++
|
hackerrank/algorithms/search/sherlock-array.cc
|
fdavidcl/problems
|
a917a0e61fd80be38610e607eb86e6685323baa3
|
[
"MIT"
] | null | null | null |
hackerrank/algorithms/search/sherlock-array.cc
|
fdavidcl/problems
|
a917a0e61fd80be38610e607eb86e6685323baa3
|
[
"MIT"
] | null | null | null |
hackerrank/algorithms/search/sherlock-array.cc
|
fdavidcl/problems
|
a917a0e61fd80be38610e607eb86e6685323baa3
|
[
"MIT"
] | null | null | null |
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int test_cases;
cin >> test_cases;
for (int t = 0; t < test_cases; ++t) {
int size;
cin >> size;
vector<unsigned> ar(size);
for (auto& e : ar) {
cin >> e;
}
// Naive approach
/*
bool found = false;
for (int i = 1; i < ar.size() && !found; ++i) {
int left_sum, right_sum;
left_sum = accumulate(ar.begin(), ar.begin() + i - 1, 0, plus<int>());
right_sum = accumulate(ar.begin() + i, ar.end(), 0, plus<int>());
found = left_sum == right_sum;
}
*/
long long int sum = accumulate(ar.begin(), ar.end(), 0, plus<int>());
long long int partial_sum = 0;
bool found = false;
for (unsigned i = 0; i < ar.size(); ++i) {
if ((sum - ar[i]) % 2 == 0 && (sum - ar[i])/2 == partial_sum)
found = true;
partial_sum += ar[i];
}
if (found) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}
| 21
| 76
| 0.528912
|
fdavidcl
|
278da29f7eb135a9d53f57a6151f4c0100f5547e
| 17,119
|
cpp
|
C++
|
platform/RemotingNG/RemoteGen/src/GenUtility.cpp
|
gboyraz/macchina.io
|
3e26fea95e87512459693831242b297f0780cc21
|
[
"Apache-2.0"
] | 2
|
2020-11-23T23:37:00.000Z
|
2020-12-22T04:02:41.000Z
|
platform/RemotingNG/RemoteGen/src/GenUtility.cpp
|
gboyraz/macchina.io
|
3e26fea95e87512459693831242b297f0780cc21
|
[
"Apache-2.0"
] | null | null | null |
platform/RemotingNG/RemoteGen/src/GenUtility.cpp
|
gboyraz/macchina.io
|
3e26fea95e87512459693831242b297f0780cc21
|
[
"Apache-2.0"
] | 1
|
2020-11-23T23:37:09.000Z
|
2020-11-23T23:37:09.000Z
|
//
// GenUtility.cpp
//
// Copyright (c) 2006-2014, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "GenUtility.h"
#include "Poco/CodeGeneration/Utility.h"
#include "Poco/CodeGeneration/GeneratorEngine.h"
#include "Poco/CppParser/Utility.h"
#include "Poco/CppParser/Symbol.h"
#include "Poco/CppParser/TypeDef.h"
#include "Poco/Exception.h"
#include "Poco/String.h"
#include "Poco/NumberParser.h"
#include "Poco/Ascii.h"
#include <typeinfo>
#include <cctype>
POCO_IMPLEMENT_EXCEPTION(CodeGenerationException, Poco::ApplicationException, "Code generation error")
const std::string GenUtility::ATTR_INLINE("inline");
const std::string GenUtility::ATTR_NAME("name");
const std::string GenUtility::ATTR_REPLYNAME("replyName");
const std::string GenUtility::VAL_REQUEST("Request");
const std::string GenUtility::VAL_REPLY("Reply");
const std::string GenUtility::ATTR_RETURN("return");
const std::string GenUtility::ATTR_HEADER("header");
const std::string GenUtility::KEYS_VECTOR[KEYS_SIZE] = {"std::vector", "std::set", "std::multiset", "std::list", "std::array", "Poco::Array"};
std::string GenUtility::getMethodName(const Poco::CppParser::Function* pFunc)
{
Poco::CodeGeneration::CodeGenerator::Properties funcProps;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pFunc, funcProps);
std::string aName(pFunc->name());
Poco::CodeGeneration::GeneratorEngine::getStringProperty(funcProps, GenUtility::ATTR_NAME, aName);
return aName;
}
std::string GenUtility::getRequestMethodName(const Poco::CppParser::Function* pFunc)
{
Poco::CodeGeneration::CodeGenerator::Properties funcProps;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pFunc, funcProps);
std::string aName(pFunc->name());
std::string replyName(aName+GenUtility::VAL_REQUEST);
Poco::CodeGeneration::GeneratorEngine::getStringProperty(funcProps, GenUtility::ATTR_REPLYNAME, replyName);
return replyName;
}
std::string GenUtility::getReplyMethodName(const Poco::CppParser::Function* pFunc)
{
Poco::CodeGeneration::CodeGenerator::Properties funcProps;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pFunc, funcProps);
std::string aName(pFunc->name());
Poco::CodeGeneration::GeneratorEngine::getStringProperty(funcProps, GenUtility::ATTR_NAME, aName);
std::string replyName(aName+GenUtility::VAL_REPLY);
Poco::CodeGeneration::GeneratorEngine::getStringProperty(funcProps, GenUtility::ATTR_REPLYNAME, replyName);
return replyName;
}
std::string GenUtility::getParameterName(const Poco::CppParser::Function* pFunc, const Poco::CppParser::Parameter* pParam)
{
Poco::CodeGeneration::CodeGenerator::Properties funcProps;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pFunc, funcProps);
std::string name(pParam->name());
std::string elemStr;
bool found = Poco::CodeGeneration::GeneratorEngine::getStringProperty(funcProps, "$" + pParam->name(), elemStr);
if (found && !elemStr.empty())
{
Poco::CodeGeneration::CodeGenerator::Properties elemProps;
Poco::CodeGeneration::GeneratorEngine::parseElementProperties(elemStr, elemProps);
Poco::CodeGeneration::GeneratorEngine::getStringProperty(elemProps, GenUtility::ATTR_NAME, name);
}
return name;
}
std::string GenUtility::getVariableName(const Poco::CppParser::Variable* pVar)
{
Poco::CodeGeneration::CodeGenerator::Properties props;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pVar, props);
Poco::CodeGeneration::CodeGenerator::Properties::const_iterator itName = props.find(GenUtility::ATTR_NAME);
std::string result;
if (itName != props.end())
{
result = itName->second;
}
else
{
result = cleanVariableName(pVar->name());
}
return result;
}
Poco::UInt32 GenUtility::getVariableOrder(const Poco::CppParser::Variable* pVar, Poco::UInt32 defValue)
{
Poco::CodeGeneration::CodeGenerator::Properties props;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pVar, props);
Poco::CodeGeneration::GeneratorEngine::getUInt32Property(props, Poco::CodeGeneration::Utility::ORDER, defValue);
return defValue;
}
Poco::UInt32 GenUtility::getParameterOrder(const Poco::CppParser::Function* pFunc, const Poco::CppParser::Parameter* pParam, Poco::UInt32 defValue)
{
Poco::CodeGeneration::CodeGenerator::Properties funcProps;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pFunc, funcProps);
std::string elemStr;
bool found = Poco::CodeGeneration::GeneratorEngine::getStringProperty(funcProps, "$" + pParam->name(), elemStr);
if (found && !elemStr.empty())
{
Poco::CodeGeneration::CodeGenerator::Properties elemProps;
Poco::CodeGeneration::GeneratorEngine::parseElementProperties(elemStr, elemProps);
Poco::CodeGeneration::GeneratorEngine::getUInt32Property(elemProps, Poco::CodeGeneration::Utility::ORDER, defValue);
}
return defValue;
}
bool GenUtility::getIsMandatory(const Poco::CppParser::Function* pFunc, const Poco::CppParser::Parameter* pParam)
{
bool isMandatory = true;
Poco::CodeGeneration::CodeGenerator::Properties funcProps;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pFunc, funcProps);
std::string elemStr;
bool found = Poco::CodeGeneration::GeneratorEngine::getStringProperty(funcProps, "$" + pParam->name(), elemStr);
if (found && !elemStr.empty())
{
Poco::CodeGeneration::CodeGenerator::Properties elemProps;
Poco::CodeGeneration::GeneratorEngine::parseElementProperties(elemStr, elemProps);
isMandatory = getIsMandatory(elemProps);
}
return isMandatory;
}
bool GenUtility::getIsMandatory(const Poco::CppParser::Variable* pVar)
{
Poco::CodeGeneration::CodeGenerator::Properties props;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pVar, props);
return getIsMandatory(props);
}
bool GenUtility::getIsMandatory(const Poco::CodeGeneration::CodeGenerator::Properties& props)
{
bool isMandatory = true;
if (!Poco::CodeGeneration::GeneratorEngine::getBoolProperty(props, Poco::CodeGeneration::Utility::MANDATORY, isMandatory))
{
bool isOptional = !isMandatory;
if (Poco::CodeGeneration::GeneratorEngine::getBoolProperty(props, Poco::CodeGeneration::Utility::OPTIONAL, isOptional))
{
isMandatory = !isOptional;
}
}
return isMandatory;
}
bool GenUtility::getIsInHeader(const Poco::CppParser::Function* pFunc, const Poco::CppParser::Parameter* pParam)
{
bool soapHeader = false;
Poco::CodeGeneration::CodeGenerator::Properties funcProps;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pFunc, funcProps);
std::string elemStr;
bool found = Poco::CodeGeneration::GeneratorEngine::getStringProperty(funcProps, "$" + pParam->name(), elemStr);
if (found && !elemStr.empty())
{
Poco::CodeGeneration::CodeGenerator::Properties elemProps;
Poco::CodeGeneration::GeneratorEngine::parseElementProperties(elemStr, elemProps);
Poco::CodeGeneration::GeneratorEngine::getBoolProperty(elemProps, ATTR_HEADER, soapHeader);
}
return soapHeader;
}
std::string GenUtility::cleanVariableName(const std::string& origName)
{
std::string result;
std::size_t pos = origName.find("_");
if (pos != std::string::npos)
{
// is it at end or at the beginning?
if (pos == (origName.size()-1))
{
result = origName.substr(0, pos);
}
else if (pos == 0 || (pos == 1 && origName[0] == 'm'))
{
// at beginning
result = origName.substr(pos+1);
}
else
result = origName;
}
else
result = origName;
return result;
}
std::string GenUtility::getReturnParameterName(const Poco::CppParser::Function* pFunc)
{
Poco::CodeGeneration::CodeGenerator::Properties funcProps;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pFunc, funcProps);
std::string name(GenUtility::ATTR_RETURN);
std::string elemStr;
bool found = Poco::CodeGeneration::GeneratorEngine::getStringProperty(funcProps, GenUtility::ATTR_RETURN, elemStr);
if (found && !elemStr.empty())
{
Poco::CodeGeneration::CodeGenerator::Properties elemProps;
Poco::CodeGeneration::GeneratorEngine::parseElementProperties(elemStr, elemProps);
Poco::CodeGeneration::GeneratorEngine::getStringProperty(elemProps, GenUtility::ATTR_NAME, name);
}
return name;
}
bool GenUtility::getInlineReturnParam(const Poco::CppParser::Function* pFunc)
{
Poco::CodeGeneration::CodeGenerator::Properties funcProps;
Poco::CodeGeneration::GeneratorEngine::parseProperties(pFunc, funcProps);
bool doInline = false;
std::string elemStr;
bool found = Poco::CodeGeneration::GeneratorEngine::getStringProperty(funcProps, GenUtility::ATTR_RETURN, elemStr);
if (found && !elemStr.empty())
{
Poco::CodeGeneration::CodeGenerator::Properties elemProps;
Poco::CodeGeneration::GeneratorEngine::parseElementProperties(elemStr, elemProps);
Poco::CodeGeneration::GeneratorEngine::getBoolProperty(elemProps, GenUtility::ATTR_INLINE, doInline);
}
return doInline;
}
std::string GenUtility::getReturnParameterType(const Poco::CppParser::Function* pFunc)
{
if (pFunc->getReturnParameter().empty() || pFunc->getReturnParameter() == Poco::CodeGeneration::Utility::TYPE_VOID)
return Poco::CodeGeneration::Utility::TYPE_VOID;
return pFunc->getReturnParameter();
}
std::string GenUtility::getResolvedReturnParameterType(const Poco::CppParser::NameSpace* pNS, const Poco::CppParser::Function* pFunc)
{
std::string retParam(getReturnParameterType(pFunc));
return Poco::CodeGeneration::Utility::resolveType(pNS, retParam);
}
bool GenUtility::isVectorType(const Poco::CppParser::NameSpace* pNS, const Poco::CppParser::Parameter* pParam)
{
std::string paramType = Poco::CodeGeneration::Utility::resolveType(pNS, pParam->declType());
return isVectorType(paramType);
}
bool GenUtility::isVectorType(const std::string& resolvedType)
{
if (resolvedType == "std::vector < char >") return false;
bool found = false;
for (int i = 0; i < KEYS_SIZE && !found; ++i)
{
found = (resolvedType.find(KEYS_VECTOR[i]) == 0);
}
return found;
}
bool GenUtility::isArrayType(const Poco::CppParser::NameSpace* pNS, const Poco::CppParser::Parameter* pParam)
{
std::string paramType = Poco::CodeGeneration::Utility::resolveType(pNS, pParam->declType());
return isArrayType(paramType);
}
bool GenUtility::isArrayType(const std::string& resolvedType)
{
return resolvedType.compare(0, 11, "Poco::Array") == 0 || resolvedType.compare(0, 10, "std::array") == 0;
}
bool GenUtility::isNullableType(const Poco::CppParser::NameSpace* pNS, const Poco::CppParser::Parameter* pParam)
{
std::string resolvedType = Poco::CodeGeneration::Utility::resolveType(pNS, pParam->declType());
return isNullableType(resolvedType);
}
bool GenUtility::isOptionalType(const Poco::CppParser::NameSpace* pNS, const Poco::CppParser::Parameter* pParam)
{
std::string resolvedType = Poco::CodeGeneration::Utility::resolveType(pNS, pParam->declType());
return isOptionalType(resolvedType);
}
bool GenUtility::isTemplateType(const std::string& resolvedType)
{
std::size_t posStart = resolvedType.find('<');
std::size_t posEnd = resolvedType.find('>');
return (posStart != std::string::npos && posEnd != std::string::npos && posStart < posEnd);
}
bool GenUtility::isPtrType(const std::string& type)
{
return type.compare(0, 7, "AutoPtr") == 0
|| type.compare(0, 13, "Poco::AutoPtr") == 0
|| type.compare(0, 9, "SharedPtr") == 0
|| type.compare(0, 15, "Poco::SharedPtr") == 0;
}
bool GenUtility::isNullableType(const std::string& type)
{
return type.compare(0, 8, "Nullable") == 0
|| type.compare(0, 14, "Poco::Nullable") == 0;
}
bool GenUtility::isOptionalType(const std::string& type)
{
return type.compare(0, 8, "Optional") == 0
|| type.compare(0, 14, "Poco::Optional") == 0;
}
std::vector<std::string> GenUtility::getResolvedInnerTemplateTypes(const Poco::CppParser::NameSpace* pNS, const std::string& typeDecl)
{
std::string resolved(Poco::CodeGeneration::Utility::resolveType(pNS, typeDecl));
return getInnerTemplateTypes(resolved);
}
std::vector<std::string> GenUtility::getInnerTemplateTypes(const std::string& typeDecl)
{
std::vector<std::string> templTypes;
//a typical template def std::map<int, std::pair<int,int> >
int lvl = 0;
std::string temp;
for (int i = 0; i < typeDecl.size(); ++i)
{
char c = typeDecl[i];
if (c == '<')
{
++lvl;
if (lvl > 1)
temp.append(&c, 1);
}
else if (c == '>')
{
--lvl;
if (lvl == 0)
{
Poco::trimInPlace(temp);
if (!temp.empty() && (Poco::Ascii::isAlpha(temp[0]) || temp[0] == '_')) // Poco::Array<int, 8> -> 8 is not a type
templTypes.push_back(temp);
temp.clear();
}
else
temp.append(&c, 1);
}
else if (c == ',')
{
if (lvl > 0)
{
Poco::trimInPlace(temp);
if (!temp.empty() && (Poco::Ascii::isAlpha(temp[0]) || temp[0] == '_')) // Poco::Array<int, 8> -> 8 is not a type
templTypes.push_back(temp);
temp.clear();
}
else
temp.append(&c, 1);
}
else
{
if (lvl > 0)
{
temp.append(&c, 1);
}
}
}
return templTypes;
}
bool GenUtility::mustBeSerializable(const std::string& name)
{
return (name != "Thread" && name != "Runnable" && name != "RefCountedObject" && name != "Service");
}
bool GenUtility::isAService(const Poco::CppParser::Struct* pStruct)
{
if (!pStruct)
return false;
if (pStruct->fullName() == "Poco::OSP::Service")
return true;
Poco::CppParser::Struct::BaseIterator itB = pStruct->baseBegin();
Poco::CppParser::Struct::BaseIterator itBEnd = pStruct->baseEnd();
for (; itB != itBEnd; ++itB)
{
if (itB->pClass)
{
if (isAService(itB->pClass))
return true;
}
if (itB->name == "Service")
return true;
}
return false;
}
bool GenUtility::hasEvents(const Poco::CppParser::Struct* pStruct)
{
if (!pStruct)
return false;
Poco::CppParser::NameSpace::SymbolTable tbl;
pStruct->variables(tbl);
Poco::CppParser::NameSpace::SymbolTable::const_iterator it = tbl.begin();
Poco::CppParser::NameSpace::SymbolTable::const_iterator itEnd = tbl.end();
for (; it != itEnd; ++it)
{
Poco::CppParser::Variable* pVar = static_cast<Poco::CppParser::Variable*>(it->second);
const std::string& varType = pVar->declType();
if (pVar->getAccess() == Poco::CppParser::Variable::ACC_PUBLIC)
{
if (varType.find("Poco::BasicEvent") == 0 || varType.find("Poco::FIFOEvent") == 0)
{
return true;
}
}
}
return parentsHaveEvents(pStruct);
}
bool GenUtility::parentsHaveEvents(const Poco::CppParser::Struct* pStruct)
{
if (!pStruct)
return false;
// check parents
Poco::CppParser::Struct::BaseIterator itB = pStruct->baseBegin();
Poco::CppParser::Struct::BaseIterator itBEnd = pStruct->baseEnd();
for (; itB != itBEnd; ++itB)
{
if (itB->pClass)
{
if (GenUtility::hasEvents(itB->pClass))
return true;
}
}
return false;
}
bool GenUtility::hasAnyRemoteParent(const Poco::CppParser::Struct* pStruct)
{
bool hasAnyRemote = false;
Poco::CppParser::Struct::BaseIterator itB = pStruct->baseBegin();
Poco::CppParser::Struct::BaseIterator itBEnd = pStruct->baseEnd();
for (; itB != itBEnd; ++itB)
{
if (itB->pClass)
hasAnyRemote |= Poco::CodeGeneration::Utility::hasAnyRemoteProperty(itB->pClass);
}
return hasAnyRemote;
}
Poco::UInt64 GenUtility::parseExpireTime(const std::string& expireTimeStr)
{
std::size_t pos = 0;
while (std::isdigit(expireTimeStr[pos]) && pos < expireTimeStr.size())
pos++;
Poco::UInt64 expireTime = Poco::NumberParser::parseUnsigned(expireTimeStr.substr(0, pos));
// now search for either ms, s(ec), m(in), h(our),
// the default is ms
std::string tmp(expireTimeStr.substr(pos));
Poco::toLowerInPlace(tmp);
Poco::trimInPlace(tmp);
// convert to microsec
if (tmp == "ms" || (tmp.find("milli") == 0))
expireTime *= 1000;
else if (tmp == "s" || (tmp.find("sec") == 0))
expireTime *= (1000*1000);
else if (tmp == "m" || (tmp.find("min") == 0))
expireTime *= (1000*1000*60);
else if (tmp == "h" || (tmp.find("hour") == 0))
{
expireTime *= (1000*1000*60);
expireTime *= 60;
}
else
expireTime *= 1000;
return expireTime;
}
void GenUtility::checkFunctionParams(const Poco::CppParser::Function* pFunc)
{
Poco::CppParser::Function::Iterator it = pFunc->begin();
Poco::CppParser::Function::Iterator itEnd = pFunc->end();
for (; it != itEnd; ++it)
{
if ((*it)->name() == (*it)->declType())
throw CodeGenerationException("Unnamed function parameters are not allowed", pFunc->fullName() + "()");
}
}
bool GenUtility::isOverride(const std::string& funcName, const Poco::CppParser::Struct* pStruct)
{
poco_check_ptr (pStruct);
Poco::CppParser::Struct::Functions methods;
pStruct->methods(Poco::CppParser::Symbol::ACC_PUBLIC, methods);
bool isDefinedHere = false;
for (Poco::CppParser::Struct::Functions::const_iterator it = methods.begin(); !isDefinedHere && it != methods.end(); ++it)
{
if ((*it)->name() == funcName)
{
isDefinedHere = true;
}
}
if (!isDefinedHere) return false;
Poco::CppParser::Struct::FunctionSet inherited;
pStruct->inheritedMethods(inherited);
for (Poco::CppParser::Struct::FunctionSet::const_iterator it = inherited.begin(); it != inherited.end(); ++it)
{
if ((*it)->name() == funcName)
return true;
}
return false;
}
| 30.40675
| 147
| 0.721304
|
gboyraz
|
27946a8ac1b3b63e1b742b69ccf0d14f9cd460f3
| 2,525
|
cpp
|
C++
|
ChemistryLib/PhreeqcIOData/CreateAqueousSolution.cpp
|
MManicaM/ogs
|
6d5ee002f7ac1d046b34655851b98907d5b8cc4f
|
[
"BSD-4-Clause"
] | null | null | null |
ChemistryLib/PhreeqcIOData/CreateAqueousSolution.cpp
|
MManicaM/ogs
|
6d5ee002f7ac1d046b34655851b98907d5b8cc4f
|
[
"BSD-4-Clause"
] | 2
|
2019-06-05T12:06:11.000Z
|
2019-06-06T08:45:30.000Z
|
ChemistryLib/PhreeqcIOData/CreateAqueousSolution.cpp
|
MManicaM/ogs
|
6d5ee002f7ac1d046b34655851b98907d5b8cc4f
|
[
"BSD-4-Clause"
] | null | null | null |
/**
* \copyright
* Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#include "AqueousSolution.h"
#include "BaseLib/ConfigTree.h"
#include "BaseLib/Error.h"
namespace ChemistryLib
{
AqueousSolution createAqueousSolution(BaseLib::ConfigTree const& config)
{
//! \ogs_file_param{prj__chemical_system__solution__temperature}
auto const temperature = config.getConfigParameter<double>("temperature");
//! \ogs_file_param{prj__chemical_system__solution__pressure}
auto const pressure = config.getConfigParameter<double>("pressure");
//! \ogs_file_param{prj__chemical_system__solution__pe}
auto const pe = config.getConfigParameter<double>("pe");
//! \ogs_file_param{prj__chemical_system__solution__components}
auto comp_config = config.getConfigSubtree("components");
std::vector<Component> components;
for (
auto const& component_name :
//! \ogs_file_param{prj__chemical_system__solution__components__component}
comp_config.getConfigParameterList<std::string>("component"))
{
components.emplace_back(component_name);
}
// conversion the variable 'means_of_adjusting_charge' from std::string to
// enumerate class.
auto const means_of_adjusting_charge_in_str =
//! \ogs_file_param{prj__chemical_system__solution__means_of_adjusting_charge}
config.getConfigParameterOptional<std::string>(
"means_of_adjusting_charge");
MeansOfAdjustingCharge means_of_adjusting_charge;
if (means_of_adjusting_charge_in_str)
{
if (*means_of_adjusting_charge_in_str == "pH")
{
means_of_adjusting_charge = MeansOfAdjustingCharge::pH;
}
else if (*means_of_adjusting_charge_in_str == "pe")
{
means_of_adjusting_charge = MeansOfAdjustingCharge::pe;
}
else
{
OGS_FATAL(
"Error in specifying means of adjusting charge. Achieving "
"charge balance is currently supported with the way of "
"adjusting pH value or pe value.");
}
}
else
{
means_of_adjusting_charge = MeansOfAdjustingCharge::Unspecified;
}
return {temperature, pressure, pe, std::move(components),
means_of_adjusting_charge};
}
} // namespace ChemistryLib
| 34.121622
| 86
| 0.688713
|
MManicaM
|
27a373c9b0c89c4f06c7a1079a11ceece1e69b4e
| 3,961
|
cpp
|
C++
|
amd_tressfx/src/Util.cpp
|
vlj/TressFX
|
83678bf6a946ecbdd9643965e79ed20b35039f77
|
[
"MIT"
] | 1
|
2018-08-06T22:31:28.000Z
|
2018-08-06T22:31:28.000Z
|
amd_tressfx/src/Util.cpp
|
0x6E745C/TressFX
|
83678bf6a946ecbdd9643965e79ed20b35039f77
|
[
"MIT"
] | null | null | null |
amd_tressfx/src/Util.cpp
|
0x6E745C/TressFX
|
83678bf6a946ecbdd9643965e79ed20b35039f77
|
[
"MIT"
] | 1
|
2019-03-16T11:40:23.000Z
|
2019-03-16T11:40:23.000Z
|
//--------------------------------------------------------------------------------------
// File: Util.cpp
//
//
// Copyright (c) 2016 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.
//
//--------------------------------------------------------------------------------------
#pragma once
#include "AMD_Types.h"
#include "Util.h"
#include <iostream>
#include <fstream>
using namespace std;
using namespace DirectX;
typedef double StatsCounterType;
#define RAY_EPSILON 1e-3f
#if defined(WIN32)
#define memalign(a, b) _aligned_malloc(b, a)
#elif defined(__APPLE__)
#define memalign(a, b) valloc(b)
#elif defined(__OpenBSD__)
#define memalign(a, b) malloc(b)
#endif
void *AllocAligned(size_t size)
{
#ifndef L1_CACHE_LINE_SIZE
#define L1_CACHE_LINE_SIZE 64
#endif
return memalign(L1_CACHE_LINE_SIZE, size);
}
void FreeAligned(void *ptr)
{
#ifdef WIN32 // NOBOOK
_aligned_free(ptr);
#else // NOBOOK
free(ptr);
#endif // NOBOOK
}
float Log2(float x)
{
static float invLog2 = 1.f / logf(2.f);
return logf(x) * invLog2;
}
BBox Union(const BBox &b, const Float3 &p)
{
BBox ret = b;
ret.pMin.x = min(b.pMin.x, p.x);
ret.pMin.y = min(b.pMin.y, p.y);
ret.pMin.z = min(b.pMin.z, p.z);
ret.pMax.x = max(b.pMax.x, p.x);
ret.pMax.y = max(b.pMax.y, p.y);
ret.pMax.z = max(b.pMax.z, p.z);
return ret;
}
BBox Union(const BBox &b, const BBox &b2)
{
BBox ret;
ret.pMin.x = min(b.pMin.x, b2.pMin.x);
ret.pMin.y = min(b.pMin.y, b2.pMin.y);
ret.pMin.z = min(b.pMin.z, b2.pMin.z);
ret.pMax.x = max(b.pMax.x, b2.pMax.x);
ret.pMax.y = max(b.pMax.y, b2.pMax.y);
ret.pMax.z = max(b.pMax.z, b2.pMax.z);
return ret;
}
inline Float3 Normalize(const Float3 &v)
{
return v / v.Length();
}
inline float Distance(const Float3 &p1, const Float3 &p2)
{
return (p1-p2).Length();
}
inline Float3 Cross(const Float3 &v1, const Float3 &v2)
{
return Float3((v1.y * v2.z) - (v1.z * v2.y),
(v1.z * v2.x) - (v1.x * v2.z),
(v1.x * v2.y) - (v1.y * v2.x));
}
inline float Dot(const Float3 &v1, const Float3 &v2)
{
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
Float3 TransformPoint(const Matrix4x4 &m, const Float3 &pt)
{
float x = pt.x, y = pt.y, z = pt.z;
float xp = m.m[0][0]*x + m.m[0][1]*y + m.m[0][2]*z + m.m[0][3];
float yp = m.m[1][0]*x + m.m[1][1]*y + m.m[1][2]*z + m.m[1][3];
float zp = m.m[2][0]*x + m.m[2][1]*y + m.m[2][2]*z + m.m[2][3];
float wp = m.m[3][0]*x + m.m[3][1]*y + m.m[3][2]*z + m.m[3][3];
assert(wp != 0);
return Float3(xp, yp, zp)/wp;
}
void BBox::BoundingSphere(Float3 *c, float *rad) const
{
*c = pMin * .5f + pMax * .5f;
*rad = Inside(*c) ? Distance(*c, pMax) : 0.f;
}
| 28.702899
| 89
| 0.590255
|
vlj
|
27a70088cc10f8a2feb0f31d7334f88e66b3839a
| 240
|
cpp
|
C++
|
Codeforces/contests/round-483/a.cpp
|
Anzoteh96/Cpp-algorithms
|
7519c65dcfa2018d81280fe947bef749970bb8bc
|
[
"MIT"
] | 1
|
2017-06-24T11:17:37.000Z
|
2017-06-24T11:17:37.000Z
|
Codeforces/contests/round-483/a.cpp
|
Anzoteh96/Cpp-algorithms
|
7519c65dcfa2018d81280fe947bef749970bb8bc
|
[
"MIT"
] | null | null | null |
Codeforces/contests/round-483/a.cpp
|
Anzoteh96/Cpp-algorithms
|
7519c65dcfa2018d81280fe947bef749970bb8bc
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> vec(n);
for (int i = 0; i < n; ++i) {
cin >> vec[i];
}
sort(vec.begin(), vec.end());
cout << vec[(n-1)/2];
}
| 15
| 33
| 0.445833
|
Anzoteh96
|
27a8763ee97c5599f5f9ff165d177de69d9138f2
| 1,810
|
cpp
|
C++
|
mlog/throw.cpp
|
Lowdham/mlog
|
034134ec2048fb78084f4772275b5f67efeec433
|
[
"MIT"
] | 2
|
2021-06-19T04:14:14.000Z
|
2021-08-30T15:39:49.000Z
|
mlog/throw.cpp
|
Lowdham/mlog
|
034134ec2048fb78084f4772275b5f67efeec433
|
[
"MIT"
] | 1
|
2021-06-21T15:58:19.000Z
|
2021-06-22T02:04:39.000Z
|
mlog/throw.cpp
|
Lowdham/mlog
|
034134ec2048fb78084f4772275b5f67efeec433
|
[
"MIT"
] | null | null | null |
// This file is part of mlog.
/*
BSD 3-Clause License
Copyright (c) 2018 - 2021, LH_Mouse
All rights reserved.
*/
#include <cstdarg> // ::va_list
#include <cstdio> // ::vasprintf()
#include <cstdlib> // ::free()
#include "throw.hpp"
namespace mlog {
// Define the main template.
template <typename exceptT>
void SprintfAndThrow(const char* fmt, ...) {
#if defined(MLOG_WIN)
::va_list ap;
char* str = static_cast<char*>(malloc(sizeof(char) * 256));
int ret;
// Compose the error message in allocated storage.
va_start(ap, fmt);
ret = ::vsprintf(str, fmt, ap); // suspicious bug?
va_end(ap);
if (ret < 0) throw ::std::bad_alloc();
unique_ptr<char, void (&)(void*)> uptr(str, ::free);
// Construct the exception object and throw it.
throw exceptT(uptr.get());
#elif defined(MLOG_LINUX)
::va_list ap;
char* str;
int ret;
// Compose the error message in allocated storage.
va_start(ap, fmt);
ret = ::vasprintf(&str, fmt, ap);
va_end(ap);
if (ret < 0) throw ::std::bad_alloc();
unique_ptr<char, void (&)(void*)> uptr(str, ::free);
// Construct the exception object and throw it.
throw exceptT(uptr.get());
#endif
}
// Define specializations.
template void SprintfAndThrow<logic_error>(const char*, ...);
template void SprintfAndThrow<domain_error>(const char*, ...);
template void SprintfAndThrow<invalid_argument>(const char*, ...);
template void SprintfAndThrow<length_error>(const char*, ...);
template void SprintfAndThrow<out_of_range>(const char*, ...);
template void SprintfAndThrow<runtime_error>(const char*, ...);
template void SprintfAndThrow<range_error>(const char*, ...);
template void SprintfAndThrow<overflow_error>(const char*, ...);
template void SprintfAndThrow<underflow_error>(const char*, ...);
} // namespace mlog
| 26.231884
| 66
| 0.683425
|
Lowdham
|
27abb997becf1e4f59e93ce7a9678edbcf0ca07d
| 393
|
cpp
|
C++
|
hdu_oj/1000.cpp
|
zyzisyz/OJ
|
55221a55515231182b6bd133edbdb55501a565fc
|
[
"Apache-2.0"
] | null | null | null |
hdu_oj/1000.cpp
|
zyzisyz/OJ
|
55221a55515231182b6bd133edbdb55501a565fc
|
[
"Apache-2.0"
] | null | null | null |
hdu_oj/1000.cpp
|
zyzisyz/OJ
|
55221a55515231182b6bd133edbdb55501a565fc
|
[
"Apache-2.0"
] | 2
|
2020-01-01T13:49:08.000Z
|
2021-03-06T06:54:26.000Z
|
/*************************************************************************
> File Name: 1000.cpp
> Author: Yang Zhang
> Mail: zyziszy@foxmail.com
> Created Time: Tue 31 Dec 2019 12:04:02 PM CST
************************************************************************/
#include<iostream>
using namespace std;
int main(void){
int a,b;
while(cin>>a>>b)
cout<<a+b<<endl;
return 0;
}
| 23.117647
| 74
| 0.407125
|
zyzisyz
|
27abdc36df37acd4730d5e592a8d110c3cfeb134
| 3,513
|
cpp
|
C++
|
sources/source.cpp
|
hucker99/lab10_
|
18a59004a006f30b2c78265698ce892b66504acd
|
[
"MIT"
] | null | null | null |
sources/source.cpp
|
hucker99/lab10_
|
18a59004a006f30b2c78265698ce892b66504acd
|
[
"MIT"
] | null | null | null |
sources/source.cpp
|
hucker99/lab10_
|
18a59004a006f30b2c78265698ce892b66504acd
|
[
"MIT"
] | null | null | null |
// Copyright 2018 Your Name <your_email>
#include <header.hpp>
#include <constants.h>
int main(int argc, char **argv) {
std::string loglevel, pathin, pathout;
try {
boost::program_options::options_description desc("Allowed options");
desc.add_options()
("log-level", boost::program_options::value<std::string>(),
"logirovanye")
("thread-count", boost::program_options::value<int>(),
"potoki")
("output", boost::program_options::value<std::string>(),
"path out")
("input", boost::program_options::value<std::string>(),
"path in");
boost::program_options::variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
if (vm.count("log-level")) {
loglevel = vm["log-level"].as<std::string>();
std::cout << "log-level:" << loglevel << std::endl;
} else {
loglevel = "Severity";
std::cout << "log-level:" << loglevel << std::endl;
}
if (vm.count("thread-count")) {
threadcount = vm["thread-count"].as<int>();
std::cout << "threads:" << threadcount << std::endl;
} else {
threadcount = std::thread::hardware_concurrency();
std::cout << "threads:" << threadcount << std::endl;
}
if (vm.count("output")) {
pathout = vm["output"].as<std::string>();
std::cout << "output:" << pathout << std::endl;
} else {
pathout = Path2;
std::cout << "output:" << pathout << std::endl;
}
if (vm.count("input")) {
pathin = vm["input"].as<std::string>();
std::cout << "input:" << pathin << std::endl;
} else {
pathin = Path1;
std::cout << "input:" << pathin << std::endl;
}
}
catch (...) {
std::cout << "lazha" << "\n";
}
boost::log::register_simple_formatter_factory<boost::log
::trivial::severity_level, char>(loglevel);
boost::log::add_file_log(
boost::log::keywords::file_name = "log.log",
boost::log::keywords::rotation_size = 256 * 1024 * 1024,
boost::log::keywords::time_based_rotation =
boost::log::sinks::file
::rotation_at_time_point(0, 0, 0),
boost::log::keywords::filter = boost::log::trivial::severity
>= boost::log::trivial::error,
boost::log::keywords::format =
(
boost::log::expressions::stream
<< boost::posix_time
::second_clock::local_time()
<< " : <" << boost::log::
trivial::severity
<< "> " << boost::log::expressions::smessage));
boost::log::add_console_log(
std::cout,
boost::log::keywords::format =
"[%ThreadID%][%TimeStamp%][%Severity%]: %Message%");
boost::log::add_common_attributes();
db bd1;
bd1.parse(pathin);
bd1.open_db();
bd1.read_all();
db bd2;
bd2.create_db(pathout, bd1._column_families_names);
bd2.parse(pathout);
bd2.open_db();
bd2.my();
bd1.print();
bd1.close_db();
std::cout << "bd2:" << std::endl;
bd2.print();
bd2.close_db();
BOOST_LOG_TRIVIAL(info) << "done";
return 0;
}
| 37.774194
| 76
| 0.496442
|
hucker99
|
27aef53c2fd91ac85a8838960fc7649933f7a890
| 3,989
|
cpp
|
C++
|
Engine/source/gui/utility/guiInputCtrl.cpp
|
fr1tz/alux3d
|
249a3b51751ce3184d52879b481f83eabe89e7e3
|
[
"MIT"
] | 46
|
2015-01-05T17:34:43.000Z
|
2022-01-04T04:03:09.000Z
|
Engine/source/gui/utility/guiInputCtrl.cpp
|
fr1tz/alux3d
|
249a3b51751ce3184d52879b481f83eabe89e7e3
|
[
"MIT"
] | 10
|
2015-01-20T23:14:46.000Z
|
2019-04-05T22:04:15.000Z
|
Engine/source/gui/utility/guiInputCtrl.cpp
|
fr1tz/terminal-overload
|
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
|
[
"CC-BY-4.0"
] | 9
|
2015-08-08T18:46:06.000Z
|
2021-02-01T13:53:20.000Z
|
// Copyright information can be found in the file named COPYING
// located in the root directory of this distribution.
#include "gui/utility/guiInputCtrl.h"
#include "sim/actionMap.h"
#include "console/engineAPI.h"
IMPLEMENT_CONOBJECT(GuiInputCtrl);
ConsoleDocClass( GuiInputCtrl,
"@brief A control that locks the mouse and reports all keyboard input events to script.\n\n"
"This is useful for implementing custom keyboard handling code, and most commonly "
"used in Torque for a menu that allows a user to remap their in-game controls\n\n "
"@tsexample\n"
"new GuiInputCtrl(OptRemapInputCtrl)\n"
"{\n"
" lockMouse = \"0\";\n"
" position = \"0 0\";\n"
" extent = \"64 64\";\n"
" minExtent = \"8 8\";\n"
" horizSizing = \"center\";\n"
" vertSizing = \"bottom\";\n"
" profile = \"GuiInputCtrlProfile\";\n"
" visible = \"1\";\n"
" active = \"1\";\n"
" tooltipProfile = \"GuiToolTipProfile\";\n"
" hovertime = \"1000\";\n"
" isContainer = \"0\";\n"
" canSave = \"1\";\n"
" canSaveDynamicFields = \"0\";\n"
"};\n"
"@endtsexample\n\n"
"@see GuiMouseEventCtrl\n"
"@ingroup GuiUtil\n");
//------------------------------------------------------------------------------
void GuiInputCtrl::initPersistFields()
{
Parent::initPersistFields();
}
//------------------------------------------------------------------------------
bool GuiInputCtrl::onWake()
{
// Set the default profile on start-up:
if( !mProfile )
{
GuiControlProfile* profile;
Sim::findObject( "GuiInputCtrlProfile", profile);
if( profile )
setControlProfile( profile );
}
if ( !Parent::onWake() )
return( false );
if( !smDesignTime )
mouseLock();
setFirstResponder();
return( true );
}
//------------------------------------------------------------------------------
void GuiInputCtrl::onSleep()
{
Parent::onSleep();
mouseUnlock();
clearFirstResponder();
}
//------------------------------------------------------------------------------
static bool isModifierKey( U16 keyCode )
{
switch ( keyCode )
{
case KEY_LCONTROL:
case KEY_RCONTROL:
case KEY_LALT:
case KEY_RALT:
case KEY_LSHIFT:
case KEY_RSHIFT:
return( true );
}
return( false );
}
IMPLEMENT_CALLBACK( GuiInputCtrl, onInputEvent, void, (const char* device, const char* action, bool state ),
( device, action, state),
"@brief Callback that occurs when an input is triggered on this control\n\n"
"@param device The device type triggering the input, such as keyboard, mouse, etc\n"
"@param action The actual event occuring, such as a key or button\n"
"@param state True if the action is being pressed, false if it is being release\n\n"
);
//------------------------------------------------------------------------------
bool GuiInputCtrl::onInputEvent( const InputEventInfo &event )
{
// TODO - add POV support...
if ( event.action == SI_MAKE )
{
if ( event.objType == SI_BUTTON
|| event.objType == SI_POV
|| ( ( event.objType == SI_KEY ) && !isModifierKey( event.objInst ) ) )
{
char deviceString[32];
if ( !ActionMap::getDeviceName( event.deviceType, event.deviceInst, deviceString ) )
return( false );
const char* actionString = ActionMap::buildActionString( &event );
//Con::executef( this, "onInputEvent", deviceString, actionString, "1" );
onInputEvent_callback(deviceString, actionString, 1);
return( true );
}
}
else if ( event.action == SI_BREAK )
{
if ( ( event.objType == SI_KEY ) && isModifierKey( event.objInst ) )
{
char keyString[32];
if ( !ActionMap::getKeyString( event.objInst, keyString ) )
return( false );
//Con::executef( this, "onInputEvent", "keyboard", keyString, "0" );
onInputEvent_callback("keyboard", keyString, 0);
return( true );
}
}
return( false );
}
| 27.136054
| 108
| 0.566307
|
fr1tz
|
27b4e85bc39f655ef1f97aaf11e95f772d355697
| 7,650
|
hpp
|
C++
|
alpaka/include/alpaka/mem/buf/sycl/Copy.hpp
|
ComputationalRadiationPhysics/mallocMC
|
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
|
[
"MIT"
] | 25
|
2015-01-30T12:19:48.000Z
|
2020-10-30T07:52:45.000Z
|
alpaka/include/alpaka/mem/buf/sycl/Copy.hpp
|
ComputationalRadiationPhysics/mallocMC
|
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
|
[
"MIT"
] | 101
|
2015-01-06T11:31:26.000Z
|
2020-11-09T13:51:19.000Z
|
alpaka/include/alpaka/mem/buf/sycl/Copy.hpp
|
ComputationalRadiationPhysics/mallocMC
|
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
|
[
"MIT"
] | 10
|
2015-06-10T07:54:30.000Z
|
2020-05-06T10:07:39.000Z
|
/* Copyright 2022 Jan Stephan
*
* This file is part of Alpaka.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#ifdef ALPAKA_ACC_SYCL_ENABLED
# include <alpaka/core/Debug.hpp>
# include <alpaka/core/Sycl.hpp>
# include <alpaka/dev/DevCpu.hpp>
# include <alpaka/dev/DevGenericSycl.hpp>
# include <alpaka/dim/DimIntegralConst.hpp>
# include <alpaka/elem/Traits.hpp>
# include <alpaka/extent/Traits.hpp>
# include <alpaka/mem/buf/sycl/Common.hpp>
# include <alpaka/mem/view/Traits.hpp>
# include <CL/sycl.hpp>
# include <memory>
# include <type_traits>
namespace alpaka::experimental::detail
{
template<typename TElem, std::size_t TDim>
using SrcAccessor = sycl::
accessor<TElem, TDim, sycl::access_mode::read, sycl::target::global_buffer, sycl::access::placeholder::true_t>;
template<typename TElem, std::size_t TDim>
using DstAccessor = sycl::accessor<
TElem,
TDim,
sycl::access_mode::write,
sycl::target::global_buffer,
sycl::access::placeholder::true_t>;
enum class Direction
{
h2d,
d2h,
d2d
};
template<typename TSrc, typename TDst, Direction TDirection>
struct TaskCopySycl
{
auto operator()(sycl::handler& cgh) const -> void
{
if constexpr(TDirection == Direction::d2h || TDirection == Direction::d2d)
cgh.require(m_src);
if constexpr(TDirection == Direction::h2d || TDirection == Direction::d2d)
cgh.require(m_dst);
cgh.copy(m_src, m_dst);
}
TSrc m_src;
TDst m_dst;
static constexpr auto is_sycl_task = true;
};
} // namespace alpaka::experimental::detail
// Trait specializations for CreateTaskMemcpy.
namespace alpaka::trait
{
//! The SYCL host-to-device memory copy trait specialization.
template<typename TDim, typename TPltf>
struct CreateTaskMemcpy<TDim, experimental::DevGenericSycl<TPltf>, DevCpu>
{
template<typename TExtent, typename TViewSrc, typename TViewDst>
static auto createTaskMemcpy(TViewDst& viewDst, TViewSrc const& viewSrc, TExtent const& ext)
{
ALPAKA_DEBUG_FULL_LOG_SCOPE;
constexpr auto copy_dim = static_cast<int>(Dim<TExtent>::value);
using ElemType = Elem<std::remove_const_t<TViewSrc>>;
using SrcType = ElemType const*;
using DstType = alpaka::experimental::detail::DstAccessor<ElemType, copy_dim>;
static_assert(!std::is_const_v<TViewDst>, "The destination view cannot be const!");
static_assert(
Dim<TViewDst>::value == Dim<std::remove_const_t<TViewSrc>>::value,
"The source and the destination view are required to have the same dimensionality!");
static_assert(
Dim<TViewDst>::value == Dim<TExtent>::value,
"The views and the extent are required to have the same dimensionality!");
static_assert(
std::is_same_v<Elem<TViewDst>, ElemType>,
"The source and the destination view are required to have the same element type!");
auto const range = experimental::detail::make_sycl_range(ext);
auto const offset = experimental::detail::make_sycl_offset(viewDst);
return experimental::detail::TaskCopySycl<SrcType, DstType, experimental::detail::Direction::h2d>{
getPtrNative(viewSrc),
DstType{viewDst.m_buffer, range, offset}};
}
};
//! The SYCL device-to-host memory copy trait specialization.
template<typename TDim, typename TPltf>
struct CreateTaskMemcpy<TDim, DevCpu, experimental::DevGenericSycl<TPltf>>
{
template<typename TExtent, typename TViewSrc, typename TViewDst>
static auto createTaskMemcpy(TViewDst& viewDst, TViewSrc const& viewSrc, TExtent const& ext)
{
ALPAKA_DEBUG_FULL_LOG_SCOPE;
constexpr auto copy_dim = static_cast<int>(Dim<TExtent>::value);
using ElemType = Elem<std::remove_const_t<TViewSrc>>;
using SrcType = alpaka::experimental::detail::SrcAccessor<ElemType, copy_dim>;
using DstType = ElemType*;
static_assert(!std::is_const_v<TViewDst>, "The destination view cannot be const!");
static_assert(
Dim<TViewDst>::value == Dim<std::remove_const_t<TViewSrc>>::value,
"The source and the destination view are required to have the same dimensionality!");
static_assert(
Dim<TViewDst>::value == Dim<TExtent>::value,
"The views and the extent are required to have the same dimensionality!");
static_assert(
std::is_same_v<Elem<TViewDst>, ElemType>,
"The source and the destination view are required to have the same element type!");
auto const range = experimental::detail::make_sycl_range(ext);
auto const offset = experimental::detail::make_sycl_offset(viewSrc);
auto view_src = const_cast<TViewSrc&>(viewSrc);
return experimental::detail::TaskCopySycl<SrcType, DstType, experimental::detail::Direction::d2h>{
SrcType{view_src.m_buffer, range, offset},
getPtrNative(viewDst)};
}
};
//! The SYCL device-to-device memory copy trait specialization.
template<typename TDim, typename TPltfDst, typename TPltfSrc>
struct CreateTaskMemcpy<TDim, experimental::DevGenericSycl<TPltfDst>, experimental::DevGenericSycl<TPltfSrc>>
{
template<typename TExtent, typename TViewSrc, typename TViewDst>
static auto createTaskMemcpy(TViewDst& viewDst, TViewSrc const& viewSrc, TExtent const& ext)
{
ALPAKA_DEBUG_FULL_LOG_SCOPE;
constexpr auto copy_dim = static_cast<int>(Dim<TExtent>::value);
using ElemType = Elem<std::remove_const_t<TViewSrc>>;
using SrcType = alpaka::experimental::detail::SrcAccessor<ElemType, copy_dim>;
using DstType = alpaka::experimental::detail::DstAccessor<ElemType, copy_dim>;
static_assert(!std::is_const_v<TViewDst>, "The destination view cannot be const!");
static_assert(
Dim<TViewDst>::value == Dim<std::remove_const_t<TViewSrc>>::value,
"The source and the destination view are required to have the same dimensionality!");
static_assert(
Dim<TViewDst>::value == Dim<TExtent>::value,
"The views and the extent are required to have the same dimensionality!");
static_assert(
std::is_same_v<Elem<TViewDst>, ElemType>,
"The source and the destination view are required to have the same element type!");
auto const range = experimental::detail::make_sycl_range(ext);
auto const offset_src = experimental::detail::make_sycl_offset(viewSrc);
auto const offset_dst = experimental::detail::make_sycl_offset(viewDst);
auto view_src = const_cast<TViewSrc&>(viewSrc);
return experimental::detail::TaskCopySycl<SrcType, DstType, experimental::detail::Direction::d2d>{
SrcType{view_src.m_buffer, range, offset_src},
DstType{viewDst.m_buffer, range, offset_dst}};
}
};
} // namespace alpaka::trait
#endif
| 39.84375
| 119
| 0.644706
|
ComputationalRadiationPhysics
|
27b96295585dfc14f12291ada50c4d215e7242b7
| 1,571
|
cpp
|
C++
|
src/mergesort.cpp
|
xiangp126/sort_algorithm_gallery
|
803f5e725b78572249fa545545193fcdee506c21
|
[
"MIT"
] | null | null | null |
src/mergesort.cpp
|
xiangp126/sort_algorithm_gallery
|
803f5e725b78572249fa545545193fcdee506c21
|
[
"MIT"
] | null | null | null |
src/mergesort.cpp
|
xiangp126/sort_algorithm_gallery
|
803f5e725b78572249fa545545193fcdee506c21
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
void showArray(vector<int> &, int);
void mergeSort(vector<int> &, int);
void mSort(int *, vector<int> &, int, int);
void merge(int *, vector<int> &, int, int);
int main() {
vector<int> nums {13, 2, 7, 12, 8, -4, 9, 12, 6, 3};
const int N = nums.size();
cout << "Original Array: " << endl;
showArray(nums, N);
mergeSort(nums, N);
cout << "Merge Sorted: " << endl;
showArray(nums, N);
return 0;
}
void mergeSort(vector<int> &nums, int N) {
int *pArray = new int[N];
mSort(pArray, nums, 0, N - 1);
delete pArray;
return;
}
void mSort(int *mArray, vector<int> &nums, int left, int right) {
if (left >= right) return;
//int mid = left >> 1 + right >> 1;
int mid = (left & right) + ((left ^ right) >> 1);
mSort(mArray, nums, left, mid);
mSort(mArray, nums, mid + 1, right);
return merge(mArray, nums, left, right);
}
void merge(int *mArray, vector<int> &nums, int left, int right) {
int mid = (left & right) + ((left ^ right) >> 1);
int i = left, j = mid + 1, k = left;
while (i <= mid && j <= right) {
mArray[k++] = nums[i] <= nums[j] ? nums[i++] : nums[j++];
}
while (i <= mid) {
mArray[k++] = nums[i++];
}
while (j <= right) {
mArray[k++] = nums[j++];
}
for (int cnt = left; cnt < k; ++cnt) {
nums[cnt] = mArray[cnt];
}
return;
}
void showArray(vector<int> &nums, int N) {
for (auto val : nums) {
cout << val << " ";
}
cout << endl;
}
| 24.936508
| 65
| 0.526416
|
xiangp126
|
27ba6f83974749db260a5c6a80572c15ff23cf28
| 1,301
|
hpp
|
C++
|
src/cardres.hpp
|
katsuster/sample_arib_descramble
|
7a6e9218cf82addcee69e063477172fa4fa6a6aa
|
[
"Apache-2.0"
] | null | null | null |
src/cardres.hpp
|
katsuster/sample_arib_descramble
|
7a6e9218cf82addcee69e063477172fa4fa6a6aa
|
[
"Apache-2.0"
] | null | null | null |
src/cardres.hpp
|
katsuster/sample_arib_descramble
|
7a6e9218cf82addcee69e063477172fa4fa6a6aa
|
[
"Apache-2.0"
] | 1
|
2021-03-17T04:49:53.000Z
|
2021-03-17T04:49:53.000Z
|
#ifndef CARDRES_HPP__
#define CARDRES_HPP__
#include <cerrno>
#include <cstdint>
#include <cinttypes>
#include "packet.hpp"
class cardres_base : public packet {
public:
cardres_base() :
protocol_unit_number(0),
unit_length(0),
ic_card_instruction(0),
return_code(0)
{
}
virtual const packet::stub_base__read& get_read_stub() const
{
static const packet::stub_derived__read<cardres_base> s;
return s;
}
template <class T>
void read_stub(bitstream<T>& bs)
{
protocol_unit_number = bs.get_bits(8);
unit_length = bs.get_bits(8);
ic_card_instruction = bs.get_bits(16);
return_code = bs.get_bits(16);
}
virtual const packet::stub_base__write& get_write_stub() const
{
static const packet::stub_derived__write<cardres_base> s;
return s;
}
template <class T>
void write_stub(bitstream<T>& bs)
{
}
virtual void dump()
{
printf(FORMAT_STRING
FORMAT_STRING
FORMAT_STRING
FORMAT_STRING,
"protocol_unit_number", protocol_unit_number,
"unit_length" , unit_length ,
"ic_card_instruction" , ic_card_instruction ,
"return_code" , return_code );
}
public:
uint32_t protocol_unit_number;
uint32_t unit_length;
uint32_t ic_card_instruction;
uint32_t return_code;
};
#endif //CARDRES_HPP__
| 19.712121
| 63
| 0.708686
|
katsuster
|
27bc4c63aa336b0bf5c8514c6c53803e6c1c1046
| 11,866
|
cpp
|
C++
|
src/frameworks/av/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp
|
dAck2cC2/m3e
|
475b89b59d5022a94e00b636438b25e27e4eaab2
|
[
"Apache-2.0"
] | null | null | null |
src/frameworks/av/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp
|
dAck2cC2/m3e
|
475b89b59d5022a94e00b636438b25e27e4eaab2
|
[
"Apache-2.0"
] | null | null | null |
src/frameworks/av/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp
|
dAck2cC2/m3e
|
475b89b59d5022a94e00b636438b25e27e4eaab2
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "APM::AudioInputDescriptor"
//#define LOG_NDEBUG 0
#include <AudioPolicyInterface.h>
#include "AudioInputDescriptor.h"
#include "IOProfile.h"
#include "AudioGain.h"
#include "AudioPolicyMix.h"
#include "HwModule.h"
#include <media/AudioPolicy.h>
#include <policy.h>
namespace android {
AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile,
AudioPolicyClientInterface *clientInterface)
: mIoHandle(0),
mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
mProfile(profile), mPatchHandle(AUDIO_PATCH_HANDLE_NONE), mId(0),
mClientInterface(clientInterface)
{
if (profile != NULL) {
profile->pickAudioProfile(mSamplingRate, mChannelMask, mFormat);
if (profile->mGains.size() > 0) {
profile->mGains[0]->getDefaultConfig(&mGain);
}
}
}
audio_module_handle_t AudioInputDescriptor::getModuleHandle() const
{
if (mProfile == 0) {
return AUDIO_MODULE_HANDLE_NONE;
}
return mProfile->getModuleHandle();
}
uint32_t AudioInputDescriptor::getOpenRefCount() const
{
return mSessions.getOpenCount();
}
audio_port_handle_t AudioInputDescriptor::getId() const
{
return mId;
}
audio_source_t AudioInputDescriptor::inputSource(bool activeOnly) const
{
return getHighestPrioritySource(activeOnly);
}
void AudioInputDescriptor::toAudioPortConfig(struct audio_port_config *dstConfig,
const struct audio_port_config *srcConfig) const
{
ALOG_ASSERT(mProfile != 0,
"toAudioPortConfig() called on input with null profile %d", mIoHandle);
dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
if (srcConfig != NULL) {
dstConfig->config_mask |= srcConfig->config_mask;
}
AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
dstConfig->id = mId;
dstConfig->role = AUDIO_PORT_ROLE_SINK;
dstConfig->type = AUDIO_PORT_TYPE_MIX;
dstConfig->ext.mix.hw_module = getModuleHandle();
dstConfig->ext.mix.handle = mIoHandle;
dstConfig->ext.mix.usecase.source = inputSource();
}
void AudioInputDescriptor::toAudioPort(struct audio_port *port) const
{
ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
mProfile->toAudioPort(port);
port->id = mId;
toAudioPortConfig(&port->active_config);
port->ext.mix.hw_module = getModuleHandle();
port->ext.mix.handle = mIoHandle;
port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
}
void AudioInputDescriptor::setPreemptedSessions(const SortedVector<audio_session_t>& sessions)
{
mPreemptedSessions = sessions;
}
SortedVector<audio_session_t> AudioInputDescriptor::getPreemptedSessions() const
{
return mPreemptedSessions;
}
bool AudioInputDescriptor::hasPreemptedSession(audio_session_t session) const
{
return (mPreemptedSessions.indexOf(session) >= 0);
}
void AudioInputDescriptor::clearPreemptedSessions()
{
mPreemptedSessions.clear();
}
bool AudioInputDescriptor::isActive() const {
return mSessions.hasActiveSession();
}
bool AudioInputDescriptor::isSourceActive(audio_source_t source) const
{
return mSessions.isSourceActive(source);
}
audio_source_t AudioInputDescriptor::getHighestPrioritySource(bool activeOnly) const
{
return mSessions.getHighestPrioritySource(activeOnly);
}
bool AudioInputDescriptor::isSoundTrigger() const {
// sound trigger and non sound trigger sessions are not mixed
// on a given input
return mSessions.valueAt(0)->isSoundTrigger();
}
sp<AudioSession> AudioInputDescriptor::getAudioSession(
audio_session_t session) const {
return mSessions.valueFor(session);
}
AudioSessionCollection AudioInputDescriptor::getAudioSessions(bool activeOnly) const
{
if (activeOnly) {
return mSessions.getActiveSessions();
} else {
return mSessions;
}
}
size_t AudioInputDescriptor::getAudioSessionCount(bool activeOnly) const
{
if (activeOnly) {
return mSessions.getActiveSessionCount();
} else {
return mSessions.size();
}
}
status_t AudioInputDescriptor::addAudioSession(audio_session_t session,
const sp<AudioSession>& audioSession) {
return mSessions.addSession(session, audioSession, /*AudioSessionInfoProvider*/this);
}
status_t AudioInputDescriptor::removeAudioSession(audio_session_t session) {
return mSessions.removeSession(session);
}
audio_patch_handle_t AudioInputDescriptor::getPatchHandle() const
{
return mPatchHandle;
}
void AudioInputDescriptor::setPatchHandle(audio_patch_handle_t handle)
{
mPatchHandle = handle;
mSessions.onSessionInfoUpdate();
}
audio_config_base_t AudioInputDescriptor::getConfig() const
{
const audio_config_base_t config = { .sample_rate = mSamplingRate, .channel_mask = mChannelMask,
.format = mFormat };
return config;
}
status_t AudioInputDescriptor::open(const audio_config_t *config,
audio_devices_t device,
const String8& address,
audio_source_t source,
audio_input_flags_t flags,
audio_io_handle_t *input)
{
audio_config_t lConfig;
if (config == nullptr) {
lConfig = AUDIO_CONFIG_INITIALIZER;
lConfig.sample_rate = mSamplingRate;
lConfig.channel_mask = mChannelMask;
lConfig.format = mFormat;
} else {
lConfig = *config;
}
mDevice = device;
ALOGV("opening input for device %08x address %s profile %p name %s",
mDevice, address.string(), mProfile.get(), mProfile->getName().string());
status_t status = mClientInterface->openInput(mProfile->getModuleHandle(),
input,
&lConfig,
&mDevice,
address,
source,
flags);
LOG_ALWAYS_FATAL_IF(mDevice != device,
"%s openInput returned device %08x when given device %08x",
__FUNCTION__, mDevice, device);
if (status == NO_ERROR) {
LOG_ALWAYS_FATAL_IF(*input == AUDIO_IO_HANDLE_NONE,
"%s openInput returned input handle %d for device %08x",
__FUNCTION__, *input, device);
mSamplingRate = lConfig.sample_rate;
mChannelMask = lConfig.channel_mask;
mFormat = lConfig.format;
mId = AudioPort::getNextUniqueId();
mIoHandle = *input;
mProfile->curOpenCount++;
}
return status;
}
status_t AudioInputDescriptor::start()
{
if (getAudioSessionCount(true/*activeOnly*/) == 1) {
if (!mProfile->canStartNewIo()) {
ALOGI("%s mProfile->curActiveCount %d", __func__, mProfile->curActiveCount);
return INVALID_OPERATION;
}
mProfile->curActiveCount++;
}
return NO_ERROR;
}
void AudioInputDescriptor::stop()
{
if (!isActive()) {
LOG_ALWAYS_FATAL_IF(mProfile->curActiveCount < 1,
"%s invalid profile active count %u",
__func__, mProfile->curActiveCount);
mProfile->curActiveCount--;
}
}
void AudioInputDescriptor::close()
{
if (mIoHandle != AUDIO_IO_HANDLE_NONE) {
mClientInterface->closeInput(mIoHandle);
LOG_ALWAYS_FATAL_IF(mProfile->curOpenCount < 1, "%s profile open count %u",
__FUNCTION__, mProfile->curOpenCount);
// do not call stop() here as stop() is supposed to be called after
// AudioSession::changeActiveCount(-1) and we don't know how many sessions
// are still active at this time
if (isActive()) {
mProfile->curActiveCount--;
}
mProfile->curOpenCount--;
mIoHandle = AUDIO_IO_HANDLE_NONE;
}
}
status_t AudioInputDescriptor::dump(int fd)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, " ID: %d\n", getId());
result.append(buffer);
snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
result.append(buffer);
snprintf(buffer, SIZE, " Format: %d\n", mFormat);
result.append(buffer);
snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
result.append(buffer);
snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
result.append(buffer);
write(fd, result.string(), result.size());
mSessions.dump(fd, 1);
return NO_ERROR;
}
bool AudioInputCollection::isSourceActive(audio_source_t source) const
{
for (size_t i = 0; i < size(); i++) {
const sp<AudioInputDescriptor> inputDescriptor = valueAt(i);
if (inputDescriptor->isSourceActive(source)) {
return true;
}
}
return false;
}
sp<AudioInputDescriptor> AudioInputCollection::getInputFromId(audio_port_handle_t id) const
{
sp<AudioInputDescriptor> inputDesc = NULL;
for (size_t i = 0; i < size(); i++) {
inputDesc = valueAt(i);
if (inputDesc->getId() == id) {
break;
}
}
return inputDesc;
}
uint32_t AudioInputCollection::activeInputsCountOnDevices(audio_devices_t devices) const
{
uint32_t count = 0;
for (size_t i = 0; i < size(); i++) {
const sp<AudioInputDescriptor> inputDescriptor = valueAt(i);
if (inputDescriptor->isActive() &&
((devices == AUDIO_DEVICE_IN_DEFAULT) ||
((inputDescriptor->mDevice & devices & ~AUDIO_DEVICE_BIT_IN) != 0))) {
count++;
}
}
return count;
}
Vector<sp <AudioInputDescriptor> > AudioInputCollection::getActiveInputs(bool ignoreVirtualInputs)
{
Vector<sp <AudioInputDescriptor> > activeInputs;
for (size_t i = 0; i < size(); i++) {
const sp<AudioInputDescriptor> inputDescriptor = valueAt(i);
if ((inputDescriptor->isActive())
&& (!ignoreVirtualInputs ||
!is_virtual_input_device(inputDescriptor->mDevice))) {
activeInputs.add(inputDescriptor);
}
}
return activeInputs;
}
audio_devices_t AudioInputCollection::getSupportedDevices(audio_io_handle_t handle) const
{
sp<AudioInputDescriptor> inputDesc = valueFor(handle);
audio_devices_t devices = inputDesc->mProfile->getSupportedDevicesType();
return devices;
}
status_t AudioInputCollection::dump(int fd) const
{
const size_t SIZE = 256;
char buffer[SIZE];
snprintf(buffer, SIZE, "\nInputs dump:\n");
write(fd, buffer, strlen(buffer));
for (size_t i = 0; i < size(); i++) {
snprintf(buffer, SIZE, "- Input %d dump:\n", keyAt(i));
write(fd, buffer, strlen(buffer));
valueAt(i)->dump(fd);
}
return NO_ERROR;
}
}; //namespace android
| 31.226316
| 100
| 0.647564
|
dAck2cC2
|
27bd33b6112e210c9a26b3f39b3818fa4cdedd93
| 4,085
|
cpp
|
C++
|
mp/src/game/server/hl2rp/hl2rp_gamerules.cpp
|
HL2RP/HL2RP
|
7f8570785a106e66036d014bcb4e6bd669421b97
|
[
"Unlicense"
] | 2
|
2018-07-15T21:40:41.000Z
|
2022-01-29T15:18:29.000Z
|
mp/src/game/server/hl2rp/hl2rp_gamerules.cpp
|
HL2RP/HL2RP
|
7f8570785a106e66036d014bcb4e6bd669421b97
|
[
"Unlicense"
] | null | null | null |
mp/src/game/server/hl2rp/hl2rp_gamerules.cpp
|
HL2RP/HL2RP
|
7f8570785a106e66036d014bcb4e6bd669421b97
|
[
"Unlicense"
] | null | null | null |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
#include <cbase.h>
#include "hl2rp_gamerules.h"
#include "hl2_roleplayer.h"
#include <fmtstr.h>
#include <networkstringtable_gamedll.h>
#include <tier2/fileutils.h>
#define DOWNLOADABLE_FILE_TABLENAME "downloadables"
#define HL2RP_RULES_UPLOAD_PATH_ID "upload"
#define HL2RP_RULES_UPLOAD_LIST_FILE "cfg/upload.txt"
#ifdef HL2RP_FULL
void InstallGameRules()
{
CreateGameRulesObject("CHL2RPRules");
}
#else
static void CreateHL2RPRules()
{
new CHL2RPRules;
}
static CGameRulesRegister sHL2RPRulesRegister("CHL2MPRules", CreateHL2RPRules);
#endif // HL2RP_FULL
CHL2RPRules::CHL2RPRules() : mExcludedUploadExts(CaselessStringLessThan)
{
mExcludedUploadExts.Insert("bz2");
mExcludedUploadExts.Insert("cache");
mExcludedUploadExts.Insert("ztmp");
if (!engine->IsDedicatedServer())
{
// Enable this to overcome ClientDisconnected() not being called for listenserver's host
ListenForGameEvent("player_disconnect");
}
}
void CHL2RPRules::LevelInitPostEntity()
{
// Register custom user assets for download
uint startTime = Plat_MSTime();
INetworkStringTable* pDownloadables = networkstringtable->FindTable(DOWNLOADABLE_FILE_TABLENAME);
int oldDownloadablesCount = pDownloadables->GetNumStrings();
CFmtStrN<MAX_PATH> path;
RegisterDownloadableFiles(path, FILESYSTEM_INVALID_FIND_HANDLE, pDownloadables);
#ifdef HL2RP_LEGACY
// Register default HL2RP assets for download (only needed in HL2DM)
CInputTextFile uploadsList(HL2RP_RULES_UPLOAD_LIST_FILE);
for (char entry[MAX_PATH]; uploadsList.ReadLine(entry, sizeof(entry)) != NULL;)
{
Q_StripPrecedingAndTrailingWhitespace(entry);
Q_FixSlashes(entry);
if (pDownloadables->AddString(true, entry) == INVALID_STRING_INDEX)
{
break;
}
}
#endif // HL2RP_LEGACY
DevMsg("HL2RPRules: Took %s ms to register %s downloadable files\n", Q_pretifynum(Plat_MSTime() - startTime),
Q_pretifynum(pDownloadables->GetNumStrings() - oldDownloadablesCount));
}
void CHL2RPRules::RegisterDownloadableFiles(CFmtStrN<MAX_PATH>& path, FileFindHandle_t findHandle,
INetworkStringTable* pDownloadables)
{
int dirLen = path.Length();
const char* pNextFileName = filesystem->FindFirstEx(path += "*", HL2RP_RULES_UPLOAD_PATH_ID, &findHandle);
if (findHandle != FILESYSTEM_INVALID_FIND_HANDLE)
{
for (; pNextFileName != NULL; pNextFileName = filesystem->FindNext(findHandle))
{
path.SetLength(dirLen);
if (filesystem->FindIsDirectory(findHandle))
{
if (pNextFileName[0] != '.')
{
path.AppendFormat("%s%c", pNextFileName, CORRECT_PATH_SEPARATOR);
RegisterDownloadableFiles(path, findHandle, pDownloadables);
}
}
else if (!mExcludedUploadExts.HasElement(Q_GetFileExtension(pNextFileName))
&& pDownloadables->AddString(true, path += pNextFileName) == INVALID_STRING_INDEX)
{
break; // Can't register more files
}
}
filesystem->FindClose(findHandle);
}
}
void CHL2RPRules::FireGameEvent(IGameEvent* pEvent)
{
if (Q_strcmp(pEvent->GetName(), "player_disconnect") == 0)
{
CBasePlayer* pPlayer = UTIL_PlayerByUserId(pEvent->GetInt("userid"));
if (pPlayer != NULL && pPlayer->entindex() < 2)
{
ToHL2Roleplayer(pPlayer)->OnDisconnect();
}
}
}
void CHL2RPRules::ClientDisconnected(edict_t* pClient)
{
CHL2Roleplayer* pPlayer = static_cast<CHL2Roleplayer*>(CBaseEntity::Instance(pClient));
if (pPlayer != NULL)
{
pPlayer->OnDisconnect();
}
BaseClass::ClientDisconnected(pClient);
}
void CHL2RPRules::ClientCommandKeyValues(edict_t* pClient, KeyValues* pKeyValues)
{
#ifdef HL2RP_FULL
if (Q_strcmp(pKeyValues->GetName(), HL2RP_LEARNED_HUD_HINTS_UPDATE_EVENT_NAME) == 0)
{
CHL2Roleplayer* pPlayer = ToHL2Roleplayer(CBaseEntity::Instance(pClient));
if (pPlayer != NULL)
{
pPlayer->mLearnedHUDHints = pKeyValues->GetInt(HL2RP_LEARNED_HUD_HINTS_FIELD_NAME);
}
}
#endif // HL2RP_FULL
}
CHL2RPRules* HL2RPRules()
{
return static_cast<CHL2RPRules*>(GameRules());
}
| 27.979452
| 110
| 0.756916
|
HL2RP
|
27be73a3ee2382f3191d1244862fd414104b5620
| 21,916
|
cpp
|
C++
|
LLY/LLY/render/Device.cpp
|
ooeyusea/GameEngine
|
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
|
[
"MIT"
] | 3
|
2015-07-04T03:35:51.000Z
|
2017-09-10T08:23:25.000Z
|
LLY/LLY/render/Device.cpp
|
ooeyusea/GameEngine
|
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
|
[
"MIT"
] | null | null | null |
LLY/LLY/render/Device.cpp
|
ooeyusea/GameEngine
|
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
|
[
"MIT"
] | null | null | null |
#include "Device.h"
#include "../System.h"
#include "../input/Input.h"
#include <iostream>
#include "../util/FuncUnitl.h"
#include "../resource/Program.h"
#include "RenderTarget.h"
#include "../resource/Texture2D.h"
#include "../resource/Texture3D.h"
#include "../resource/TextureCube.h"
#include "../util/Macros.h"
namespace lly {
bool glew_dynamic_binding()
{
const char *gl_extensions = (const char*)glGetString(GL_EXTENSIONS);
// If the current opengl driver doesn't have framebuffers methods, check if an extension exists
if (glGenFramebuffers == nullptr)
{
if (strstr(gl_extensions, "ARB_framebuffer_object"))
{
glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)wglGetProcAddress("glIsRenderbuffer");
glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)wglGetProcAddress("glBindRenderbuffer");
glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)wglGetProcAddress("glDeleteRenderbuffers");
glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)wglGetProcAddress("glGenRenderbuffers");
glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)wglGetProcAddress("glRenderbufferStorage");
glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)wglGetProcAddress("glGetRenderbufferParameteriv");
glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)wglGetProcAddress("glIsFramebuffer");
glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wglGetProcAddress("glBindFramebuffer");
glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)wglGetProcAddress("glDeleteFramebuffers");
glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wglGetProcAddress("glGenFramebuffers");
glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)wglGetProcAddress("glCheckFramebufferStatus");
glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)wglGetProcAddress("glFramebufferTexture1D");
glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wglGetProcAddress("glFramebufferTexture2D");
glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)wglGetProcAddress("glFramebufferTexture3D");
glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)wglGetProcAddress("glFramebufferRenderbuffer");
glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)wglGetProcAddress("glGetFramebufferAttachmentParameteriv");
glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)wglGetProcAddress("glGenerateMipmap");
}
else
if (strstr(gl_extensions, "EXT_framebuffer_object"))
{
glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)wglGetProcAddress("glIsRenderbufferEXT");
glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)wglGetProcAddress("glBindRenderbufferEXT");
glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)wglGetProcAddress("glDeleteRenderbuffersEXT");
glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)wglGetProcAddress("glGenRenderbuffersEXT");
glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)wglGetProcAddress("glRenderbufferStorageEXT");
glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)wglGetProcAddress("glGetRenderbufferParameterivEXT");
glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)wglGetProcAddress("glIsFramebufferEXT");
glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wglGetProcAddress("glBindFramebufferEXT");
glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)wglGetProcAddress("glDeleteFramebuffersEXT");
glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wglGetProcAddress("glGenFramebuffersEXT");
glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)wglGetProcAddress("glCheckFramebufferStatusEXT");
glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)wglGetProcAddress("glFramebufferTexture1DEXT");
glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wglGetProcAddress("glFramebufferTexture2DEXT");
glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)wglGetProcAddress("glFramebufferTexture3DEXT");
glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)wglGetProcAddress("glFramebufferRenderbufferEXT");
glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)wglGetProcAddress("glGetFramebufferAttachmentParameterivEXT");
glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)wglGetProcAddress("glGenerateMipmapEXT");
}
else
{
return false;
}
}
return true;
}
bool Device::UniformCache::update(void * p, int s)
{
if (ptr == nullptr)
{
ptr = malloc(s);
size = s;
memcpy(ptr, p, s);
}
else if (size != s)
{
ptr = realloc(ptr, s);
size = s;
memcpy(ptr, p, s);
}
else if (memcmp(ptr, p, s) != 0)
{
memcpy(ptr, p, s);
}
else
return false;
return true;
}
void Device::UniformCache::clear()
{
LLY_SAFE_DELETE(ptr);
}
Input * g_input = nullptr;
Device::Device()
: _window(nullptr)
, _current_program(nullptr)
, _enable_blend(false)
, _blend_func({ BlendFactor::ONE, BlendFactor::ZERO })
, _enable_alpha_test(false)
, _alpha_test_func(AlphaTestFunc::ALWAYS)
, _alpha_test_factor(0.0f)
, _enable_depth_test(true)
, _enable_depth_write(true)
, _depth_func(DepthFunc::LEQUAL)
, _enable_cull_face(false)
, _cull_face_side(CullFaceSide::BACK)
, _front_face(FrontFace::CCW)
, _enable_stencil_test(false)
, _stencil_write_mask(0xff)
, _stencil_func({ StencilFuncType::ALWAYS, 0, 0xff })
, _stencil_op({ StencilOpType::KEEP, StencilOpType::KEEP, StencilOpType::KEEP })
{
glfwSetErrorCallback([](int error, const char* description){
std::cerr << description << std::endl;
});
glfwInit();
}
Device::~Device()
{
clear_cache();
glfwTerminate();
}
bool Device::init()
{
return true;
}
void Device::release()
{
}
bool Device::createWindow(const std::string& name, int width, int height)
{
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
glfwWindowHint(GLFW_RED_BITS, 8);
glfwWindowHint(GLFW_GREEN_BITS, 8);
glfwWindowHint(GLFW_BLUE_BITS, 8);
glfwWindowHint(GLFW_ALPHA_BITS, 8);
glfwWindowHint(GLFW_DEPTH_BITS, 24);
glfwWindowHint(GLFW_STENCIL_BITS, 8);
_window = glfwCreateWindow(width, height, name.c_str(), NULL, NULL);
if (!_window)
return false;
glfwMakeContextCurrent(_window);
GLenum GlewInitResult = glewInit();
if (GLEW_OK != GlewInitResult)
return false;
if (!GLEW_ARB_vertex_shader || !GLEW_ARB_fragment_shader)
{
return false;
}
if (!glewIsSupported("GL_VERSION_4_0"))
{
return false;
}
if (!glew_dynamic_binding())
{
return false;
}
glClearDepth(1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
return true;
}
void Device::reg(Input& input)
{
g_input = &input;
glfwSetMouseButtonCallback(_window, [](GLFWwindow* window, int button, int action, int modify){
if (action == GLFW_PRESS)
g_input->on_key_press(lly::to_key_from_glfw(button));
else if (action == GLFW_RELEASE)
g_input->on_key_release(lly::to_key_from_glfw(button));
});
glfwSetCursorPosCallback(_window, [](GLFWwindow* window, double x, double y){
g_input->on_mouse_move((float)x, (float)y);
});
glfwSetScrollCallback(_window, [](GLFWwindow* window, double x, double y){
g_input->on_mouse_scroll(x, y);
});
glfwSetCharCallback(_window, [](GLFWwindow* window, unsigned int character){
});
glfwSetKeyCallback(_window, [](GLFWwindow* window, int key, int scancode, int action, int mods){
if (action == GLFW_PRESS)
g_input->on_key_press(lly::to_key_from_glfw(key));
else if (action == GLFW_RELEASE)
g_input->on_key_release(lly::to_key_from_glfw(key));
});
glfwSetWindowPosCallback(_window, [](GLFWwindow* windows, int x, int y){
});
glfwSetFramebufferSizeCallback(_window, [](GLFWwindow* window, int w, int h){
});
glfwSetWindowSizeCallback(_window, [](GLFWwindow *window, int width, int height){
});
glfwSetWindowIconifyCallback(_window, [](GLFWwindow* window, int iconified){
});
}
bool Device::shouldClose()
{
return (glfwWindowShouldClose(_window) != 0);
}
void Device::run()
{
glfwSwapBuffers(_window);
glfwPollEvents();
}
void Device::exit()
{
glfwSetWindowShouldClose(_window, GL_TRUE);
}
void Device::begin(RenderTarget * target, int clear)
{
if (target)
{
target->load();
}
GLbitfield flag = 0;
if ((clear | ClearTarget::COLOR) > 0)
flag |= GL_COLOR_BUFFER_BIT;
if ((clear | ClearTarget::DEPTH) > 0)
flag |= GL_DEPTH_BUFFER_BIT;
if ((clear | ClearTarget::ACCUM) > 0)
flag |= GL_ACCUM_BUFFER_BIT;
if ((clear | ClearTarget::STENCIL) > 0)
flag |= GL_STENCIL_BUFFER_BIT;
if (flag > 0)
glClear(flag);
}
void Device::flush()
{
glFlush();
}
void Device::end(RenderTarget * target)
{
if (target)
{
target->unload();
}
else
glFinish();
}
void Device::use_program(Program * program)
{
if (_current_program != program)
{
_current_program = program;
clear_cache();
_current_program->use();
}
}
void Device::set_blend(bool enable, BlendFunc func)
{
if (_enable_blend != enable)
{
_enable_blend = enable;
if (_enable_blend)
{
glEnable(GL_BLEND);
_blend_func = func;
glBlendFunc(lly_util::to_blend_factor(func.src), lly_util::to_blend_factor(func.dst));
}
else
{
glDisable(GL_BLEND);
}
}
else if (_enable_blend)
{
if (_blend_func != func)
{
_blend_func = func;
glBlendFunc(lly_util::to_blend_factor(func.src), lly_util::to_blend_factor(func.dst));
}
}
}
void Device::set_alpha_test(bool enable, AlphaTestFunc func, float factor)
{
if (_enable_alpha_test != enable)
{
_enable_alpha_test = enable;
if (_enable_alpha_test)
{
glEnable(GL_ALPHA_TEST);
_alpha_test_func = func;
_alpha_test_factor = factor;
glAlphaFunc(lly_util::to_alpha_test_func(func), factor);
}
else
glDisable(GL_ALPHA_TEST);
}
else if (_enable_alpha_test)
{
if (_alpha_test_func != func || lly_util::eq(_alpha_test_factor, factor))
{
_alpha_test_func = func;
_alpha_test_factor = factor;
glAlphaFunc(lly_util::to_alpha_test_func(func), factor);
}
}
}
void Device::set_depth_test(bool enable, bool write, DepthFunc func)
{
if (_enable_depth_test != enable)
{
_enable_depth_test = enable;
if (_enable_depth_test)
{
glEnable(GL_DEPTH_TEST);
_enable_depth_write = write;
if (_enable_depth_write)
glDepthMask(GL_TRUE);
else
glDepthMask(GL_FALSE);
_depth_func = func;
glDepthFunc(lly_util::to_depth_func(func));
}
else
glDisable(GL_DEPTH_TEST);
}
else if (_enable_depth_test)
{
if (_enable_depth_write != write)
{
_enable_depth_write = write;
if (_enable_depth_write)
glDepthMask(GL_TRUE);
else
glDepthMask(GL_FALSE);
}
if (_depth_func != func)
{
_depth_func = func;
glDepthFunc(lly_util::to_depth_func(func));
}
}
}
void Device::set_cull_face(bool enable, CullFaceSide side, FrontFace front)
{
if (_enable_cull_face != enable)
{
_enable_cull_face = enable;
if (_enable_cull_face)
{
glEnable(GL_CULL_FACE);
_cull_face_side = side;
glCullFace(lly_util::to_cull_fase_side(side));
_front_face = front;
glFrontFace(lly_util::to_front_face(front));
}
else
glDisable(GL_CULL_FACE);
}
else if (_enable_cull_face)
{
if (_cull_face_side != side)
{
_cull_face_side = side;
glCullFace(lly_util::to_cull_fase_side(side));
}
if (_front_face != front)
{
_front_face = front;
glFrontFace(lly_util::to_front_face(front));
}
}
}
void Device::set_stencil_test(bool enable, unsigned int write_mask, StencilFunc func, StencilOp op)
{
if (_enable_stencil_test != enable)
{
_enable_stencil_test = enable;
if (_enable_stencil_test)
{
glEnable(GL_STENCIL_TEST);
}
else
glDisable(GL_STENCIL_TEST);
}
else if (_enable_stencil_test)
{
if (_stencil_write_mask != write_mask)
{
_stencil_write_mask = write_mask;
glStencilMask((GLuint)write_mask);
}
if (_stencil_func != func)
{
_stencil_func = func;
glStencilFunc(lly_util::to_stencil_func(func.func), (GLint)func.ref, (GLuint)func.mask);
}
if (_stencil_op != op)
{
_stencil_op = op;
glStencilOp(lly_util::to_stencil_op(op.s_fail), lly_util::to_stencil_op(op.d_fail), lly_util::to_stencil_op(op.d_pass));
}
}
}
void Device::clear_cache()
{
for (auto& itr : _caches)
{
itr.second.clear();
}
_caches.clear();
}
void Device::setUniformWith1i(const std::string& name, GLint i1)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::I1);
if (location == -1)
return;
if (_caches[name].update(&i1, sizeof(GLint)))
{
glUniform1i(location, i1);
}
}
void Device::setUniformWith2i(const std::string& name, GLint i1, GLint i2)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::I2);
if (location == -1)
return;
int tmp[] = { i1, i2 };
if (_caches[name].update(&tmp, sizeof(tmp)))
{
glUniform2i(location, i1, i2);
}
}
void Device::setUniformWith3i(const std::string& name, GLint i1, GLint i2, GLint i3)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::I3);
if (location == -1)
return;
int tmp[] = { i1, i2, i3 };
if (_caches[name].update(&tmp, sizeof(tmp)))
{
glUniform3i(location, i1, i2, i3);
}
}
void Device::setUniformWith4i(const std::string& name, GLint i1, GLint i2, GLint i3, GLint i4)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::I4);
if (location == -1)
return;
int tmp[] = { i1, i2, i3, i4 };
if (_caches[name].update(&tmp, sizeof(tmp)))
{
glUniform4i(location, i1, i2, i3, i4);
}
}
void Device::setUniformWith1iv(const std::string& name, GLint* ints, unsigned int numberOfArrays)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::IV1);
if (location == -1)
return;
if (_caches[name].update(ints, sizeof(int)* numberOfArrays))
{
glUniform1iv(location, (GLsizei)numberOfArrays, ints);
}
}
void Device::setUniformWith2iv(const std::string& name, GLint* ints, unsigned int numberOfArrays)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::IV2);
if (location == -1)
return;
if (_caches[name].update(ints, sizeof(int)* 2 * numberOfArrays))
{
glUniform2iv(location, (GLsizei)numberOfArrays, ints);
}
}
void Device::setUniformWith3iv(const std::string& name, GLint* ints, unsigned int numberOfArrays)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::IV3);
if (location == -1)
return;
if (_caches[name].update(ints, sizeof(int)* 3 * numberOfArrays))
{
glUniform3iv(location, (GLsizei)numberOfArrays, ints);
}
}
void Device::setUniformWith4iv(const std::string& name, GLint* ints, unsigned int numberOfArrays)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::IV4);
if (location == -1)
return;
if (_caches[name].update(ints, sizeof(int)* 4 * numberOfArrays))
{
glUniform4iv(location, (GLsizei)numberOfArrays, ints);
}
}
void Device::setUniformWith1f(const std::string& name, GLfloat f1)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::F1);
if (location == -1)
return;
if (_caches[name].update(&f1, sizeof(f1)))
{
glUniform1f(location, f1);
}
}
void Device::setUniformWith2f(const std::string& name, GLfloat f1, GLfloat f2)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::F2);
if (location == -1)
return;
float tmp[] = { f1, f2 };
if (_caches[name].update(&tmp, sizeof(tmp)))
{
glUniform2f(location, f1, f2);
}
}
void Device::setUniformWith3f(const std::string& name, GLfloat f1, GLfloat f2, GLfloat f3)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::F3);
if (location == -1)
return;
float tmp[] = { f1, f2, f3 };
if (_caches[name].update(&tmp, sizeof(tmp)))
{
glUniform3f(location, f1, f2, f3);
}
}
void Device::setUniformWith4f(const std::string& name, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::F4);
if (location == -1)
return;
float tmp[] = { f1, f2, f3, f4 };
if (_caches[name].update(&tmp, sizeof(tmp)))
{
glUniform4f(location, f1, f2, f3, f4);
}
}
void Device::setUniformWith1fv(const std::string& name, GLfloat* floats, unsigned int numberOfArrays)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::FV1);
if (location == -1)
return;
if (_caches[name].update(floats, sizeof(float)* numberOfArrays))
{
glUniform1fv(location, (GLsizei)numberOfArrays, floats);
}
}
void Device::setUniformWith2fv(const std::string& name, GLfloat* floats, unsigned int numberOfArrays)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::FV2);
if (location == -1)
return;
if (_caches[name].update(floats, sizeof(float)* 2 * numberOfArrays))
{
glUniform2fv(location, (GLsizei)numberOfArrays, floats);
}
}
void Device::setUniformWith3fv(const std::string& name, GLfloat* floats, unsigned int numberOfArrays)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::FV3);
if (location == -1)
return;
if (_caches[name].update(floats, sizeof(float)* 3 * numberOfArrays))
{
glUniform3fv(location, (GLsizei)numberOfArrays, floats);
}
}
void Device::setUniformWith4fv(const std::string& name, GLfloat* floats, unsigned int numberOfArrays)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::FV4);
if (location == -1)
return;
if (_caches[name].update(floats, sizeof(float)* 4 * numberOfArrays))
{
glUniform4fv(location, (GLsizei)numberOfArrays, floats);
}
}
void Device::setUniformWithMatrix2fv(const std::string& name, GLfloat* matrixArray, unsigned int numberOfMatrices)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::MATRIX2);
if (location == -1)
return;
if (_caches[name].update(matrixArray, sizeof(float)* 4 * numberOfMatrices))
{
glUniformMatrix2fv(location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
}
}
void Device::setUniformWithMatrix3fv(const std::string& name, GLfloat* matrixArray, unsigned int numberOfMatrices)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::MATRIX3);
if (location == -1)
return;
if (_caches[name].update(matrixArray, sizeof(float)* 9 * numberOfMatrices))
{
glUniformMatrix3fv(location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
}
}
void Device::setUniformWithMatrix4fv(const std::string& name, GLfloat* matrixArray, unsigned int numberOfMatrices)
{
if (_current_program == nullptr)
return;
GLint location = _current_program->get_location(name, Program::UniformType::MATRIX4);
if (location == -1)
return;
if (_caches[name].update(matrixArray, sizeof(float)* 16 * numberOfMatrices))
{
glUniformMatrix4fv(location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
}
}
void Device::setUniformWithTex(const std::string& name, Texture2D* texture, bool mipmap, TextureWrap s, TextureWrap t, TextureMinFilter min, TextureMagFilter mag)
{
if (_current_program == nullptr)
return;
auto tup = _current_program->get_texture_loaction(name, Program::UniformType::TEXTURE2D);
GLint location = std::get<0>(tup);
if (location == -1)
return;
GLint bind = std::get<1>(tup);
Texture2DCache tmp = { bind, texture->get_tex(), mipmap, s, t, min, mag };
if (_caches[name].update(&tmp, sizeof(tmp)))
{
glUniform1i(location, bind);
glActiveTexture(GL_TEXTURE0 + bind);
glBindTexture(GL_TEXTURE_2D, texture->get_tex());
texture->set_warp(s, t);
texture->set_filter(min, mag);
}
}
void Device::setUniformWithTex(const std::string& name, Texture3D* texture, bool mipmap, TextureWrap s, TextureWrap t, TextureWrap r, TextureMinFilter min, TextureMagFilter mag)
{
if (_current_program == nullptr)
return;
auto tup = _current_program->get_texture_loaction(name, Program::UniformType::TEXTURE3D);
GLint location = std::get<0>(tup);
if (location == -1)
return;
GLint bind = std::get<1>(tup);
Texture3DCache tmp = { bind, texture->get_tex(), mipmap, s, t, r, min, mag };
if (_caches[name].update(&tmp, sizeof(tmp)))
{
glUniform1i(location, bind);
glActiveTexture(GL_TEXTURE0 + bind);
glBindTexture(GL_TEXTURE_3D, texture->get_tex());
//texture->set_warp(s, t, r);
//texture->set_filter(min, mag);
}
}
void Device::setUniformWithTex(const std::string& name, TextureCube* texture)
{
if (_current_program == nullptr)
return;
auto tup = _current_program->get_texture_loaction(name, Program::UniformType::TEXTURECUBE);
GLint location = std::get<0>(tup);
if (location == -1)
return;
GLint bind = std::get<1>(tup);
}
}
| 26.923833
| 178
| 0.710851
|
ooeyusea
|
27c3778486886920d466b80c020171717eb58399
| 398
|
hpp
|
C++
|
inc/GraphicsLib/ImGui/imgui_impl_graphicslib.hpp
|
Sushiwave/graphics-lib
|
c303e9fb9f11276230a09b45581cdbefa8d2a356
|
[
"MIT"
] | 1
|
2020-07-13T18:10:33.000Z
|
2020-07-13T18:10:33.000Z
|
inc/GraphicsLib/ImGui/imgui_impl_graphicslib.hpp
|
Sushiwave/graphics-lib
|
c303e9fb9f11276230a09b45581cdbefa8d2a356
|
[
"MIT"
] | null | null | null |
inc/GraphicsLib/ImGui/imgui_impl_graphicslib.hpp
|
Sushiwave/graphics-lib
|
c303e9fb9f11276230a09b45581cdbefa8d2a356
|
[
"MIT"
] | null | null | null |
#pragma once
#include <Windows.h>
#include <ThirdParty/ExtendedImGui/ImGui/imgui.h>
IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
IMGUI_IMPL_API bool ImGui_ImplGraphicsLib_Init();
IMGUI_IMPL_API void ImGui_ImplGraphicsLib_Shutdown();
IMGUI_IMPL_API void ImGui_ImplGraphicsLib_NewFrame();
IMGUI_IMPL_API void ImGui_ImplGraphicsLib_Render();
| 33.166667
| 100
| 0.846734
|
Sushiwave
|
27c414c437288c03d54c807d65c211a77ae1b419
| 10,156
|
cpp
|
C++
|
source/Core/Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelSecondaryBounce.cpp
|
DragonJoker/Castor3D
|
ee0b02eeda70cd235a224be306539850e32195f6
|
[
"MIT"
] | 245
|
2015-10-29T14:31:45.000Z
|
2022-03-31T13:04:45.000Z
|
source/Core/Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelSecondaryBounce.cpp
|
DragonJoker/Castor3D
|
ee0b02eeda70cd235a224be306539850e32195f6
|
[
"MIT"
] | 64
|
2016-03-11T19:45:05.000Z
|
2022-03-31T23:58:33.000Z
|
source/Core/Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelSecondaryBounce.cpp
|
DragonJoker/Castor3D
|
ee0b02eeda70cd235a224be306539850e32195f6
|
[
"MIT"
] | 11
|
2018-05-24T09:07:43.000Z
|
2022-03-21T21:05:20.000Z
|
#include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelSecondaryBounce.hpp"
#include "Castor3D/Engine.hpp"
#include "Castor3D/Material/Texture/Sampler.hpp"
#include "Castor3D/Material/Texture/TextureLayout.hpp"
#include "Castor3D/Material/Texture/TextureUnit.hpp"
#include "Castor3D/Render/RenderDevice.hpp"
#include "Castor3D/Render/RenderSystem.hpp"
#include "Castor3D/Render/Technique/RenderTechniqueVisitor.hpp"
#include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelSceneData.hpp"
#include "Castor3D/Shader/Program.hpp"
#include "Castor3D/Shader/Shaders/GlslGlobalIllumination.hpp"
#include "Castor3D/Shader/Shaders/GlslSurface.hpp"
#include "Castor3D/Shader/Shaders/GlslUtils.hpp"
#include "Castor3D/Shader/Shaders/GlslVoxel.hpp"
#include "Castor3D/Shader/Ubos/VoxelizerUbo.hpp"
#include <CastorUtils/Miscellaneous/BitSize.hpp>
#include <ShaderWriter/Source.hpp>
#include <ashespp/Descriptor/DescriptorSet.hpp>
#include <ashespp/Descriptor/DescriptorSetLayout.hpp>
#include <ashespp/Image/Image.hpp>
#include <ashespp/Image/ImageView.hpp>
#include <RenderGraph/GraphContext.hpp>
#include <RenderGraph/RunnableGraph.hpp>
CU_ImplementCUSmartPtr( castor3d, VoxelSecondaryBounce )
namespace castor3d
{
//*********************************************************************************************
namespace
{
enum IDs : uint32_t
{
eVoxelBuffer,
eVoxelConfig,
eFirstBounce,
eResult,
};
ashes::DescriptorSetLayoutPtr createDescriptorLayout( RenderDevice const & device
, uint32_t voxelGridSize )
{
ashes::VkDescriptorSetLayoutBindingArray bindings{ makeDescriptorSetLayoutBinding( eVoxelBuffer
, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER
, VK_SHADER_STAGE_COMPUTE_BIT )
, makeDescriptorSetLayoutBinding( eVoxelConfig
, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER
, VK_SHADER_STAGE_COMPUTE_BIT )
, makeDescriptorSetLayoutBinding( eFirstBounce
, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER
, VK_SHADER_STAGE_COMPUTE_BIT )
, makeDescriptorSetLayoutBinding( eResult
, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE
, VK_SHADER_STAGE_COMPUTE_BIT ) };
return device->createDescriptorSetLayout( "VoxelSecondaryBounce"
, std::move( bindings ) );
}
ashes::DescriptorSetPtr createDescriptorSet( crg::RunnableGraph & graph
, ashes::DescriptorSetPool const & pool
, crg::FramePass const & pass
, uint32_t voxelGridSize )
{
auto voxelsBuffer = pass.buffers.front();
auto voxelsUbo = pass.buffers.back();
auto firstBounce = pass.images.front();
auto secondBounce = pass.images.back();
ashes::WriteDescriptorSetArray writes;
auto write = voxelsBuffer.getBufferWrite();
writes.push_back( ashes::WriteDescriptorSet{ write->dstBinding
, write->dstArrayElement
, write->descriptorCount
, write->descriptorType } );
writes.back().bufferInfo = write.bufferInfo;
write = voxelsUbo.getBufferWrite();
writes.push_back( ashes::WriteDescriptorSet{ write->dstBinding
, write->dstArrayElement
, write->descriptorCount
, write->descriptorType } );
writes.back().bufferInfo = write.bufferInfo;
writes.push_back( ashes::WriteDescriptorSet{ firstBounce.binding
, 0u
, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER
, { VkDescriptorImageInfo{ graph.createSampler( firstBounce.image.samplerDesc )
, graph.createImageView( firstBounce.view() )
, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL } } } );
writes.push_back( ashes::WriteDescriptorSet{ secondBounce.binding
, 0u
, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE
, { VkDescriptorImageInfo{ VK_NULL_HANDLE
, graph.createImageView( secondBounce.view() )
, VK_IMAGE_LAYOUT_GENERAL } } } );
auto descriptorSet = pool.createDescriptorSet( "VoxelSecondaryBounce" );
descriptorSet->setBindings( writes );
descriptorSet->update();
return descriptorSet;
}
ashes::PipelineLayoutPtr createPipelineLayout( RenderDevice const & device
, ashes::DescriptorSetLayout const & dslayout )
{
return device->createPipelineLayout( "VoxelSecondaryBounce"
, ashes::DescriptorSetLayoutCRefArray{ std::ref( dslayout ) } );
}
ashes::ComputePipelinePtr createPipeline( RenderDevice const & device
, ashes::PipelineLayout const & layout
, ShaderModule const & computeShader )
{
// Initialise the pipeline.
return device->createPipeline( "VoxelSecondaryBounce"
, ashes::ComputePipelineCreateInfo( 0u
, makeShaderState( device, computeShader )
, layout ) );
}
ShaderPtr createShader( uint32_t voxelGridSize
, RenderSystem const & renderSystem )
{
using namespace sdw;
ComputeWriter writer;
writer.inputLayout( 64u, 1u, 1u );
// Inputs
auto voxels( writer.declArrayShaderStorageBuffer< shader::Voxel >( "voxels"
, eVoxelBuffer
, 0u ) );
UBO_VOXELIZER( writer, eVoxelConfig, 0u, true );
auto firstBounce( writer.declSampledImage< FImg3DRgba32 >( "firstBounce"
, eFirstBounce
, 0u ) );
auto in = writer.getIn();
// Outputs
auto output( writer.declImage< RWFImg3DRgba32 >( "output"
, eResult
, 0u ) );
shader::Utils utils{ writer, *renderSystem.getEngine() };
utils.declareDecodeNormal();
utils.declareUnflatten();
shader::GlobalIllumination indirect{ writer, utils };
indirect.declareTraceConeRadiance();
writer.implementMain( [&]()
{
auto coord = writer.declLocale( "coord"
, ivec3( utils.unflatten( in.globalInvocationID.x()
, uvec3( UInt{ voxelGridSize } ) ) ) );
auto color = writer.declLocale( "color"
, firstBounce.lod( vec3( c3d_voxelData.gridToClip ) * vec3( coord ), 0.0_f ) );
IF( writer, color.a() > 0.0_f )
{
auto normal = writer.declLocale( "normal"
, utils.decodeNormal( voxels[in.globalInvocationID.x()].normalMask ) );
// [0.5,gridSize.5] => [0,1]
// center of voxel, to apply normal on it.
auto position = writer.declLocale( "position"
, ( vec3( coord ) + vec3( 0.5_f ) ) * c3d_voxelData.gridToClip );
// [0,1] => [-1,1]
position = position * 2 - 1;
position.y() *= -1;
// [-1,1] => [-gridSize/2,gridSize/2]
position *= c3d_voxelData.clipToGrid / 2.0f;
// to world
position *= c3d_voxelData.gridToWorld;
auto surface = writer.declLocale< shader::Surface >( "surface" );
surface.create( position, normal );
auto radiance = writer.declLocale( "radiance"
, indirect.traceConeRadiance( firstBounce
, surface
, c3d_voxelData ) );
output.store( coord, vec4( color.rgb() + radiance.rgb(), color.a() ) );
}
ELSE
{
output.store( coord, vec4( 0.0_f ) );
}
FI;
voxels[in.globalInvocationID.x()].normalMask = 0_u;
} );
return std::make_unique< ast::Shader >( std::move( writer.getShader() ) );
}
}
//*********************************************************************************************
VoxelSecondaryBounce::VoxelSecondaryBounce( crg::FramePass const & pass
, crg::GraphContext & context
, crg::RunnableGraph & graph
, RenderDevice const & device
, VoxelSceneData const & vctConfig )
: crg::RunnablePass{ pass
, context
, graph
, { [this](){ doInitialise(); }
, GetSemaphoreWaitFlagsCallback( [this](){ return doGetSemaphoreWaitFlags(); } )
, [this]( VkCommandBuffer cb, uint32_t i ){ doRecordInto( cb, i ); }
, crg::defaultV< crg::RunnablePass::RecordCallback >
, crg::defaultV< crg::RunnablePass::GetPassIndexCallback >
, crg::defaultV< crg::RunnablePass::IsEnabledCallback >
, IsComputePassCallback( [this](){ return doIsComputePass(); } ) }
, 2u }
, m_vctConfig{ vctConfig }
, m_shader{ VK_SHADER_STAGE_COMPUTE_BIT, "VoxelSecondaryBounce", createShader( m_vctConfig.gridSize.value(), device.renderSystem ) }
, m_descriptorSetLayout{ createDescriptorLayout( device, m_vctConfig.gridSize.value() ) }
, m_pipelineLayout{ createPipelineLayout( device, *m_descriptorSetLayout ) }
, m_pipeline{ createPipeline( device, *m_pipelineLayout, m_shader ) }
, m_descriptorSetPool{ m_descriptorSetLayout->createPool( 1u ) }
, m_descriptorSet{ createDescriptorSet( m_graph, *m_descriptorSetPool, m_pass, m_vctConfig.gridSize.value() ) }
{
}
void VoxelSecondaryBounce::accept( RenderTechniqueVisitor & visitor )
{
visitor.visit( m_shader );
}
void VoxelSecondaryBounce::doInitialise()
{
}
void VoxelSecondaryBounce::doRecordInto( VkCommandBuffer commandBuffer
, uint32_t index )
{
auto voxelGridSize = m_vctConfig.gridSize.value();
VkDescriptorSet descriptorSet = *m_descriptorSet;
auto view = m_pass.images.back().view();
auto transition = getTransition( index, view );
auto image = m_graph.createImage( view.data->image );
// Clear result
m_graph.memoryBarrier( commandBuffer
, view
, transition.needed
, { VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
, crg::getAccessMask( VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL )
, crg::getStageMask( VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) } );
m_context.vkCmdClearColorImage( commandBuffer
, image
, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
, &transparentBlackClearColor.color
, 1
, &view.data->info.subresourceRange );
m_graph.memoryBarrier( commandBuffer
, view
, { VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
, crg::getAccessMask( VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL )
, crg::getStageMask( VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) }
, transition.needed );
m_context.vkCmdBindPipeline( commandBuffer
, VK_PIPELINE_BIND_POINT_COMPUTE
, *m_pipeline );
m_context.vkCmdBindDescriptorSets( commandBuffer
, VK_PIPELINE_BIND_POINT_COMPUTE
, *m_pipelineLayout
, 0u
, 1u
, &descriptorSet
, 0u
, nullptr );
m_context.vkCmdDispatch( commandBuffer, voxelGridSize * voxelGridSize * voxelGridSize / 64u, 1u, 1u );
}
VkPipelineStageFlags VoxelSecondaryBounce::doGetSemaphoreWaitFlags()const
{
return VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
}
bool VoxelSecondaryBounce::doIsComputePass()const
{
return true;
}
//*********************************************************************************************
}
| 34.900344
| 134
| 0.700571
|
DragonJoker
|
27c80af676a0666290d391cdcf6467724af589d9
| 1,777
|
hpp
|
C++
|
utils/elements.in.hpp
|
c-vigo/mudirac
|
86c71f6ec25c8328ac7c32abde21c240f41f73e2
|
[
"MIT"
] | 3
|
2021-03-04T09:17:20.000Z
|
2022-03-03T04:13:16.000Z
|
utils/elements.in.hpp
|
c-vigo/mudirac
|
86c71f6ec25c8328ac7c32abde21c240f41f73e2
|
[
"MIT"
] | null | null | null |
utils/elements.in.hpp
|
c-vigo/mudirac
|
86c71f6ec25c8328ac7c32abde21c240f41f73e2
|
[
"MIT"
] | 2
|
2022-03-11T10:29:16.000Z
|
2022-03-25T16:05:47.000Z
|
/**
* MuDirac - A muonic atom Dirac equation solver
* by Simone Sturniolo (2019-2020)
*
* elements.hpp
*
* Atomic mass and spin data extracted by AME2016 and NUBASE databases.
* References:
*
* AME2016 (masses):
* "The Ame2016 atomic mass evaluation (I)" by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu
* Chinese Physics C41 030002, March 2017.
* "The Ame2016 atomic mass evaluation (II)" by M.Wang, G.Audi, F.G.Kondev, W.J.Huang, S.Naimi and X.Xu
* Chinese Physics C41 030003, March 2017.
*
* NUBASE (spins):
* "The NUBASE2016 evaluation of nuclear properties" by G.Audi, F.G.Kondev, M.Wang, W.J.Huang and S.Naimi
* Chinese Physics C41 030001, March 2017.
*
* @author Simone Sturniolo
* @version 1.0 20/03/2020
*/
#include <map>
#include <cmath>
#include <vector>
#include <limits>
#include <stdexcept>
#include <algorithm>
using namespace std;
#ifndef MUDIRAC_ELEMENTS
#define MUDIRAC_ELEMENTS
struct isotope
{
const double mass;
const double spin;
const double radius;
};
struct element
{
const int Z;
const int maxA;
const map<int, isotope> isotopes;
};
double getIsotopeMass(string symbol, int isotope=-1);
double getIsotopeMass(int Z, int isotope=-1);
double getIsotopeSpin(string symbol, int isotope=-1);
double getIsotopeSpin(int Z, int isotope=-1);
double getIsotopeRadius(string symbol, int isotope=-1);
double getIsotopeRadius(int Z, int isotope=-1);
vector<int> getAllIsotopes(string symbol);
vector<int> getAllIsotopes(int Z);
int getElementZ(string symbol);
string getElementSymbol(int Z);
int getElementMainIsotope(string symbol);
int getElementMainIsotope(int Z);
#endif
#ifndef ATOMIC_DATA
#define ATOMIC_DATA
//{HERE GOES THE ACTUAL DATA}//
#endif
| 26.522388
| 112
| 0.708497
|
c-vigo
|
27c829b4f304414c9ed69eea63903898ba018a97
| 2,873
|
hpp
|
C++
|
breath/meta/constant.hpp
|
erez-o/breath
|
adf197b4e959beffce11e090c5e806d2ff4df38a
|
[
"BSD-3-Clause"
] | null | null | null |
breath/meta/constant.hpp
|
erez-o/breath
|
adf197b4e959beffce11e090c5e806d2ff4df38a
|
[
"BSD-3-Clause"
] | null | null | null |
breath/meta/constant.hpp
|
erez-o/breath
|
adf197b4e959beffce11e090c5e806d2ff4df38a
|
[
"BSD-3-Clause"
] | null | null | null |
// ===========================================================================
// Copyright 2006-2007 Gennaro Prota
//
// Licensed under the 3-Clause BSD License.
// (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or
// <https://opensource.org/licenses/BSD-3-Clause>.)
// ___________________________________________________________________________
//
//! \file
//! \brief Wrapper for (integral) constant expressions.
// ---------------------------------------------------------------------------
#ifndef BREATH_GUARD_agSZ9lxbOGpOtPA3Qy3JqLm28BJW8oRr
#define BREATH_GUARD_agSZ9lxbOGpOtPA3Qy3JqLm28BJW8oRr
#include "breath/top_level_namespace.hpp"
namespace breath_ns {
namespace meta {
// constant:
// =========
//
//! \copybrief constant.hpp
//!
//! This template is a fundamental building block for our
//! meta-programming facilities, which date from when C++ didn't
//! have \c constexpr. So, it wraps a constant into a type.
//!
//! \par Type requirements
//! \a T must be a type suitable for declaring an integral
//! constant expression or a const-qualified version of such a
//! type (e.g. <code>int const</code>).
//!
//! \par Naming rationale
//! Though at the time of writing (September 2006) only
//! constants of integral and enumeration type are allowed in
//! C++, we chose a name which doesn't mention either families
//! of types, in order to eventually accommodate, for instance,
//! floating point types as well, if ever allowed by the
//! standard.
// ---------------------------------------------------------------------------
template< typename T, T v >
class constant
{
public:
//! A typedef for the type \c T.
// -----------------------------------------------------------------------
typedef T value_type ;
//! The same as \c constant< T, v >.
// -----------------------------------------------------------------------
typedef constant type ;
//! The result of the metafunction.
// -----------------------------------------------------------------------
static value_type const
value = v ;
} ;
//! This automatically generates a definition for the constant (see
//! core issue 454).
//!
//! \par Credit
//! I got the idea of automating the definition from Paul
//! Mensonides and his \c map_integral (again, see core issue
//! 454).
// ---------------------------------------------------------------------------
template< typename T, T v >
typename constant< T, v >::value_type const
constant< T, v >::value ;
}
}
#endif
// Local Variables:
// mode: c++
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim: set ft=cpp et sts=4 sw=4:
| 34.202381
| 78
| 0.507135
|
erez-o
|
27cff50ff0edcad99e6760d50d5ccf16a5bf3863
| 4,399
|
cpp
|
C++
|
src/core/log.cpp
|
celeron55/buildat
|
6e8202c6d5632485c7209623a7eab834daff49ca
|
[
"Apache-2.0"
] | 7
|
2015-04-15T14:27:52.000Z
|
2019-08-02T05:30:22.000Z
|
src/core/log.cpp
|
celeron55/buildat
|
6e8202c6d5632485c7209623a7eab834daff49ca
|
[
"Apache-2.0"
] | null | null | null |
src/core/log.cpp
|
celeron55/buildat
|
6e8202c6d5632485c7209623a7eab834daff49ca
|
[
"Apache-2.0"
] | 4
|
2017-06-14T23:20:54.000Z
|
2019-04-26T11:43:33.000Z
|
// http://www.apache.org/licenses/LICENSE-2.0
// Copyright 2014 Perttu Ahola <celeron55@gmail.com>
#include "log.h"
#include "interface/mutex.h"
//#include "interface/thread.h"
#include "c55/os.h"
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <ctime>
#include <cstring>
#include <cstdarg>
#ifdef _WIN32
#include "ports/windows_compat.h"
#else
#include <pthread.h>
#endif
const int CORE_FATAL = 0;
const int CORE_ERROR = 1;
const int CORE_WARNING = 2;
const int CORE_INFO = 3;
const int CORE_VERBOSE = 4;
const int CORE_DEBUG = 5;
const int CORE_TRACE = 6;
#ifdef _WIN32
static const bool use_colors = false;
#else
static const bool use_colors = true;
#endif
static interface::Mutex log_mutex;
//static interface::Thread *log_active_thread = nullptr;
static std::atomic_bool disable_bloat(false);
static std::atomic_bool line_begin(true);
static std::atomic_int current_level(0);
static std::atomic_int max_level(CORE_INFO);
static FILE *file = NULL;
void log_init()
{
}
void log_set_max_level(int level)
{
max_level = level;
}
int log_get_max_level()
{
return max_level;
}
void log_set_file(const char *path)
{
log_mutex.lock();
file = fopen(path, "a");
if(file)
fprintf(stderr, "Opened log file \"%s\"\n", path);
else
log_w("__log", "Failed to open log file \"%s\"", path);
log_mutex.unlock();
}
void log_close()
{
log_mutex.lock();
if(file){
fclose(file);
file = NULL;
}
log_mutex.unlock();
}
void log_disable_bloat()
{
disable_bloat = true;
}
void log_nl_nolock()
{
if(current_level <= max_level){
if(file){
fprintf(file, "\n");
fflush(file);
} else {
fprintf(stderr, "\n");
if(use_colors)
fprintf(stderr, "\033[0m");
}
}
line_begin = true;
}
void log_nl()
{
if(current_level > max_level){ // Fast path
line_begin = true;
return;
}
interface::MutexScope ms(log_mutex);
log_nl_nolock();
}
static void print(int level, const char *sys, const char *fmt, va_list va_args)
{
if(use_colors && !file &&
(level != current_level || line_begin) && level <= max_level){
if(level == CORE_FATAL)
fprintf(stderr, "\033[0m\033[0;1;41m"); // reset, bright red bg
else if(level == CORE_ERROR)
fprintf(stderr, "\033[0m\033[1;31m"); // bright red fg, black bg
else if(level == CORE_WARNING)
fprintf(stderr, "\033[0m\033[1;33m"); // bright yellow fg, black bg
else if(level == CORE_INFO)
fprintf(stderr, "\033[0m"); // reset
else if(level == CORE_VERBOSE)
fprintf(stderr, "\033[0m\033[0;36m"); // cyan fg, black bg
else if(level == CORE_DEBUG)
fprintf(stderr, "\033[0m\033[1;30m"); // bright black fg, black bg
else if(level == CORE_TRACE)
fprintf(stderr, "\033[0m\033[0;35m"); //
else
fprintf(stderr, "\033[0m"); // reset
}
current_level = level;
if(level > max_level)
return;
if(line_begin){
time_t now = time(NULL);
char timestr[30];
if(disable_bloat){
timestr[0] = 0;
} else {
size_t timestr_len = strftime(timestr, sizeof(timestr),
"%b %d %H:%M:%S", localtime(&now));
if(timestr_len == 0)
timestr[0] = '\0';
int ms = (get_timeofday_us() % 1000000) / 1000;
timestr_len += snprintf(timestr + timestr_len,
sizeof(timestr) - timestr_len, ".%03i", ms);
}
char sysstr[9];
snprintf(sysstr, 9, "%s ", sys);
const char *levelcs = "FEWIVDT";
if(file)
fprintf(file, "%s %c %s: ", timestr, levelcs[level], sysstr);
else
fprintf(stderr, "%s %c %s: ", timestr, levelcs[level], sysstr);
line_begin = false;
}
if(file)
vfprintf(file, fmt, va_args);
else
vfprintf(stderr, fmt, va_args);
}
// Does not require any locking
/*static void fallback_print(int level, const char *sys, const char *fmt,
va_list va_args)
{
FILE *f = file;
if(f == NULL)
f = stderr;
if(use_colors && !file)
fprintf(f, "\033[0m"); // reset
vfprintf(f, fmt, va_args);
fprintf(f, "\n");
}*/
void log_(int level, const char *sys, const char *fmt, ...)
{
if(level > max_level){ // Fast path
return;
}
interface::MutexScope ms(log_mutex);
va_list va_args;
va_start(va_args, fmt);
print(level, sys, fmt, va_args);
log_nl_nolock();
va_end(va_args);
}
void log_no_nl(int level, const char *sys, const char *fmt, ...)
{
if(level > max_level){ // Fast path
return;
}
interface::MutexScope ms(log_mutex);
va_list va_args;
va_start(va_args, fmt);
print(level, sys, fmt, va_args);
va_end(va_args);
}
// vim: set noet ts=4 sw=4:
| 22.105528
| 79
| 0.663787
|
celeron55
|
27d04cbbd3d105cdf0127cd89531cddd81310fc8
| 243
|
cpp
|
C++
|
libraries/VAL/src/FastEnvironment.cpp
|
teyssieuman/VAL
|
15320d3988bb6ed633babe6c7bd663a97c23a393
|
[
"BSD-3-Clause"
] | 65
|
2015-01-08T09:58:01.000Z
|
2021-11-16T11:08:31.000Z
|
libraries/VAL/src/FastEnvironment.cpp
|
teyssieuman/VAL
|
15320d3988bb6ed633babe6c7bd663a97c23a393
|
[
"BSD-3-Clause"
] | 48
|
2015-01-19T01:07:16.000Z
|
2021-07-29T18:26:54.000Z
|
libraries/VAL/src/FastEnvironment.cpp
|
teyssieuman/VAL
|
15320d3988bb6ed633babe6c7bd663a97c23a393
|
[
"BSD-3-Clause"
] | 45
|
2016-01-08T01:57:01.000Z
|
2022-03-07T04:00:36.000Z
|
// Copyright 2019 - University of Strathclyde, King's College London and Schlumberger Ltd
// This source code is licensed under the BSD license found in the LICENSE file in the root directory of this source tree.
#include "FastEnvironment.h"
| 48.6
| 122
| 0.790123
|
teyssieuman
|
27d4176d2d18efc511f4d249f3067e47d6bae1bb
| 628
|
cpp
|
C++
|
CodechefCodes/CANDY123.cpp
|
debashish05/competitive_programming
|
e2c0a7a741ac988e4393eda3b5006d6b8c88a5a9
|
[
"MIT"
] | null | null | null |
CodechefCodes/CANDY123.cpp
|
debashish05/competitive_programming
|
e2c0a7a741ac988e4393eda3b5006d6b8c88a5a9
|
[
"MIT"
] | null | null | null |
CodechefCodes/CANDY123.cpp
|
debashish05/competitive_programming
|
e2c0a7a741ac988e4393eda3b5006d6b8c88a5a9
|
[
"MIT"
] | null | null | null |
//Debashish Roy
#include<bits/stdc++.h>
#define ll long long int
#define loop(k) for(i=0;i<k;++i)
#define loop2(k) for(j=1;j<k;++j)
#define mod 1000000007
using namespace std;
int main()
{
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t=1,i=0,j=0;
cin>>t;
while(t--){
int a,b;
cin>>a>>b;
int c=1,d=2;
if(d>b){cout<<"Limak\n";continue;}
int k=1;i=3;
while(c<=a && d<=b){
if(k==1){c+=i;k=0;}
else{d+=i;k=1;}
++i;
}
//cout<<c<<" "<<d;
if(c>a)cout<<"Bob";
else cout<<"Limak";
cout<<"\n";
}
return 0;
}
| 19.625
| 42
| 0.482484
|
debashish05
|
27d4947c64a27699281af712681862c4c61a1730
| 6,358
|
cpp
|
C++
|
src/laserscan_to_ros_pointcloud.cpp
|
thanhphong98/laserscan_to_pointcloud
|
685ee50ebda342676ea03f6948fe19d56e4f22c0
|
[
"BSD-3-Clause"
] | 13
|
2015-04-28T11:28:20.000Z
|
2022-03-18T05:34:49.000Z
|
src/laserscan_to_ros_pointcloud.cpp
|
thanhphong98/laserscan_to_pointcloud
|
685ee50ebda342676ea03f6948fe19d56e4f22c0
|
[
"BSD-3-Clause"
] | null | null | null |
src/laserscan_to_ros_pointcloud.cpp
|
thanhphong98/laserscan_to_pointcloud
|
685ee50ebda342676ea03f6948fe19d56e4f22c0
|
[
"BSD-3-Clause"
] | 17
|
2015-01-06T15:20:12.000Z
|
2022-03-11T07:05:57.000Z
|
/**\file laserscan_to_ros_pointcloud.cpp
* \brief Description...
*
* @version 1.0
* @author Carlos Miguel Correia da Costa
*/
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
#include <laserscan_to_pointcloud/laserscan_to_ros_pointcloud.h>
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <imports> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </imports> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
namespace laserscan_to_pointcloud {
// ============================================================================= <public-section> ============================================================================
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <constructors-destructor> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
LaserScanToROSPointcloud::LaserScanToROSPointcloud(std::string target_frame, bool include_laser_intensity, double min_range_cutoff_percentage, double max_range_cutoff_percentage) :
LaserScanToPointcloud(target_frame, min_range_cutoff_percentage, max_range_cutoff_percentage),
include_laser_intensity_(include_laser_intensity),
pointcloud_data_position_(NULL) {
}
LaserScanToROSPointcloud::~LaserScanToROSPointcloud() { }
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </constructors-destructor> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <LaserScanToROSPointcloud-functions> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
void LaserScanToROSPointcloud::initNewPointCloud(size_t number_of_reserved_points) {
pointcloud_ = sensor_msgs::PointCloud2Ptr(new sensor_msgs::PointCloud2());
resetNumberOfPointsInCloud();
resetNumberOfScansAsembledInCurrentCloud();
pointcloud_->header.seq = getNumberOfPointcloudsCreated();
pointcloud_->header.stamp = ros::Time::now();
pointcloud_->header.frame_id = getTargetFrame();
pointcloud_->height = 1;
pointcloud_->width = 0;
pointcloud_->fields.clear();
pointcloud_->fields.resize(include_laser_intensity_ ? 4 : 3);
pointcloud_->fields[0].name = "x";
pointcloud_->fields[0].offset = 0;
pointcloud_->fields[0].datatype = sensor_msgs::PointField::FLOAT32;
pointcloud_->fields[0].count = 1;
pointcloud_->fields[1].name = "y";
pointcloud_->fields[1].offset = 4;
pointcloud_->fields[1].datatype = sensor_msgs::PointField::FLOAT32;
pointcloud_->fields[1].count = 1;
pointcloud_->fields[2].name = "z";
pointcloud_->fields[2].offset = 8;
pointcloud_->fields[2].datatype = sensor_msgs::PointField::FLOAT32;
pointcloud_->fields[2].count = 1;
pointcloud_->point_step = 12;
if (include_laser_intensity_) {
pointcloud_->fields[3].name = "intensity";
pointcloud_->fields[3].offset = 12;
pointcloud_->fields[3].datatype = sensor_msgs::PointField::FLOAT32;
pointcloud_->fields[3].count = 1;
pointcloud_->point_step += 4;
}
pointcloud_->row_step = 0;
pointcloud_->data.reserve(number_of_reserved_points * pointcloud_->point_step);
pointcloud_->is_dense = true;
incrementNumberOfPointCloudsCreated();
}
void LaserScanToROSPointcloud::addMeasureToPointCloud(const tf2::Vector3& point, float intensity) {
*pointcloud_data_position_++ = (float)point.getX();
*pointcloud_data_position_++ = (float)point.getY();
*pointcloud_data_position_++ = (float)point.getZ();
if (include_laser_intensity_) {
*pointcloud_data_position_++ = intensity;
}
}
void LaserScanToROSPointcloud::setupPointCloudForNewLaserScan(size_t number_laser_scan_points) {
pointcloud_->data.resize((getNumberOfPointsInCloud() + number_laser_scan_points) * pointcloud_->point_step); // resize to fit all points in the LaserScan
pointcloud_data_position_ = (float*)(&pointcloud_->data[getNumberOfPointsInCloud() * pointcloud_->point_step]);
}
void LaserScanToROSPointcloud::finishLaserScanIntegration() {
pointcloud_->width = getNumberOfPointsInCloud();
pointcloud_->row_step = pointcloud_->width * pointcloud_->point_step;
pointcloud_->data.resize(pointcloud_->height * pointcloud_->row_step); // resize to shrink the vector size to the real number of points inserted
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </LaserScanToROSPointcloud-functions> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <sets> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
void LaserScanToROSPointcloud::setIncludeLaserIntensity(bool include_laser_intensity) {
if (include_laser_intensity != include_laser_intensity_) {
include_laser_intensity_ = include_laser_intensity;
initNewPointCloud();
}
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </sets> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// ============================================================================= </public-section> ===========================================================================
// ============================================================================= <protected-section> =======================================================================
// ============================================================================= </protected-section> =======================================================================
// ============================================================================= <private-section> =========================================================================
// ============================================================================= </private-section> =========================================================================
} /* namespace laserscan_to_pointcloud */
| 57.279279
| 180
| 0.471689
|
thanhphong98
|
27d5b6ddbdbd4d6116a29db5c65992610bad76f4
| 732
|
cpp
|
C++
|
Easy/isomorphic_strings.cpp
|
Nikhil0487/Swift-Leetcode-June-2020
|
3583280ce03004569e17d059ea6a3325162426f0
|
[
"MIT"
] | null | null | null |
Easy/isomorphic_strings.cpp
|
Nikhil0487/Swift-Leetcode-June-2020
|
3583280ce03004569e17d059ea6a3325162426f0
|
[
"MIT"
] | null | null | null |
Easy/isomorphic_strings.cpp
|
Nikhil0487/Swift-Leetcode-June-2020
|
3583280ce03004569e17d059ea6a3325162426f0
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<string>
#include<map>
using namespace std;
bool isIsomorphic(string s, string t) {
map<char,char> hash;
map<char,bool> taken;
for(int i=0;i<s.length();i++) {
map<char,char>:: iterator it = hash.find(s[i]);
if(it == hash.end()) {
if(taken.find(t[i]) != taken.end()) {
return false;
}
hash.insert(make_pair(s[i],t[i]));
taken.insert(make_pair(t[i],true));
} else {
if(it->second != t[i]) {
return false;
}
}
}
return true;
}
int main() {
string s1 = string("ab");
string s2 = string("aa");
cout<<isIsomorphic(s1,s2)<<endl;
return 0;
}
| 25.241379
| 55
| 0.495902
|
Nikhil0487
|
27d807299a9d0cbe1df990f2137fb6c02c3574bb
| 3,222
|
cpp
|
C++
|
src/c++/methods/MeInstanceMethods.cpp
|
nlspartanNL/SDK
|
291f1e5869210baedbb5447f8f7388f50ec93950
|
[
"MIT"
] | null | null | null |
src/c++/methods/MeInstanceMethods.cpp
|
nlspartanNL/SDK
|
291f1e5869210baedbb5447f8f7388f50ec93950
|
[
"MIT"
] | null | null | null |
src/c++/methods/MeInstanceMethods.cpp
|
nlspartanNL/SDK
|
291f1e5869210baedbb5447f8f7388f50ec93950
|
[
"MIT"
] | 1
|
2020-11-06T01:42:10.000Z
|
2020-11-06T01:42:10.000Z
|
#include "c++/ModIOInstance.h"
namespace modio
{
void Instance::getAuthenticatedUser(const std::function<void(const modio::Response &response, const modio::User &user)> &callback)
{
struct GetAuthenticatedUserCall *get_authenticated_user_call = new GetAuthenticatedUserCall{callback};
get_authenticated_user_calls[current_call_id] = get_authenticated_user_call;
modioGetAuthenticatedUser((void*)((uintptr_t)current_call_id), &onGetAuthenticatedUser);
current_call_id++;
}
void Instance::getUserSubscriptions(modio::FilterCreator &filter, const std::function<void(const modio::Response &response, const std::vector<modio::Mod> &mods)> &callback)
{
struct GetUserSubscriptionsCall *get_user_subscriptions_call = new GetUserSubscriptionsCall{callback};
get_user_subscriptions_calls[current_call_id] = get_user_subscriptions_call;
modioGetUserSubscriptions((void*)((uintptr_t)current_call_id), *filter.getFilter(), &onGetUserSubscriptions);
current_call_id++;
}
void Instance::getUserEvents(modio::FilterCreator &filter, const std::function<void(const modio::Response &, const std::vector<modio::UserEvent> &events)> &callback)
{
struct GetUserEventsCall *get_user_events_call = new GetUserEventsCall{callback};
get_user_events_calls[current_call_id] = get_user_events_call;
modioGetUserEvents((void*)((uintptr_t)current_call_id), *filter.getFilter(), &onGetUserEvents);
current_call_id++;
}
void Instance::getUserGames(modio::FilterCreator &filter, const std::function<void(const modio::Response &response, const std::vector<modio::Game> &games)> &callback)
{
struct GetUserGamesCall *get_user_games_call = new GetUserGamesCall{callback};
get_user_games_calls[current_call_id] = get_user_games_call;
modioGetUserGames((void*)((uintptr_t)current_call_id), *filter.getFilter(), &onGetUserGames);
current_call_id++;
}
void Instance::getUserMods(modio::FilterCreator &filter, const std::function<void(const modio::Response &response, const std::vector<modio::Mod> &mods)> &callback)
{
struct GetUserModsCall *get_user_mods_call = new GetUserModsCall{callback};
get_user_mods_calls[current_call_id] = get_user_mods_call;
modioGetUserMods((void*)((uintptr_t)current_call_id), *filter.getFilter(), &onGetUserMods);
current_call_id++;
}
void Instance::getUserModfiles(modio::FilterCreator &filter, const std::function<void(const modio::Response &response, const std::vector<modio::Modfile> &modfiles)> &callback)
{
struct GetUserModfilesCall *get_user_modfiles_call = new GetUserModfilesCall{callback};
get_user_modfiles_calls[current_call_id] = get_user_modfiles_call;
modioGetUserModfiles((void*)((uintptr_t)current_call_id), *filter.getFilter(), &onGetUserModfiles);
current_call_id++;
}
void Instance::getUserRatings(modio::FilterCreator &filter, const std::function<void(const modio::Response &response, const std::vector<modio::Rating> &ratings)> &callback)
{
struct GetUserRatingsCall *get_user_ratings_call = new GetUserRatingsCall{callback};
get_user_ratings_calls[current_call_id] = get_user_ratings_call;
modioGetUserRatings((void*)((uintptr_t)current_call_id), *filter.getFilter(), &onGetUserRatings);
current_call_id++;
}
} // namespace modio
| 42.96
| 175
| 0.794538
|
nlspartanNL
|
27e80b2cb3a6701a6b1f364a359f9efda6426cd3
| 1,330
|
cpp
|
C++
|
smolengine.graphics/src/Primitives/Texture.cpp
|
Floritte/Game-Engine-Samples
|
2b5dfc9a998963614e6d25fbbeaa05dbe1d214f9
|
[
"Apache-2.0"
] | 3
|
2021-05-18T00:01:06.000Z
|
2021-07-09T15:39:23.000Z
|
smolengine.graphics/src/Primitives/Texture.cpp
|
Floritte/Game-Engine-Samples
|
2b5dfc9a998963614e6d25fbbeaa05dbe1d214f9
|
[
"Apache-2.0"
] | null | null | null |
smolengine.graphics/src/Primitives/Texture.cpp
|
Floritte/Game-Engine-Samples
|
2b5dfc9a998963614e6d25fbbeaa05dbe1d214f9
|
[
"Apache-2.0"
] | null | null | null |
#include "stdafx.h"
#include "Primitives/Texture.h"
#include "Primitives/Shader.h"
#include "Tools/Utils.h"
#include <memory>
#include <cereal/cereal.hpp>
#include <cereal/archives/json.hpp>
#include <stb_image/stb_image.h>
#ifdef OPENGL_IMPL
#include "Backends/OpenGL/OpenglTexture.h"
#else
#include "Backends/Vulkan/VulkanTexture.h"
#endif
namespace SmolEngine
{
Ref<Texture> Texture::Create()
{
Ref<Texture> texture = nullptr;
#ifdef OPENGL_IMPL
#else
texture = std::make_shared<VulkanTexture>();
#endif
return texture;
}
bool TextureCreateInfo::Save(const std::string& filePath)
{
std::stringstream storage;
{
cereal::JSONOutputArchive output{ storage };
serialize(output);
}
std::ofstream myfile(filePath);
if (myfile.is_open())
{
myfile << storage.str();
myfile.close();
return true;
}
return false;
}
bool TextureCreateInfo::Load(const std::string& filePath)
{
std::stringstream storage;
std::ifstream file(filePath);
if (!file)
{
DebugLog::LogError("Could not open the file: {}", filePath);
return false;
}
storage << file.rdbuf();
{
cereal::JSONInputArchive input{ storage };
input(bVerticalFlip, bAnisotropyEnable, bImGUIHandle, eFormat, eAddressMode, eFilter, eBorderColor, Width, Height, Mips, Depth, FilePath);
}
return true;
}
}
| 19.558824
| 141
| 0.703759
|
Floritte
|
27eef371a2771e38e57de26376937ba63c7a76b2
| 1,494
|
cpp
|
C++
|
src/entity-system/model/base/guid/GUIDBase_tests.cpp
|
inexorgame/entity-system
|
230a6f116fb02caeace79bc9b32f17fe08687c36
|
[
"MIT"
] | 19
|
2018-10-11T09:19:48.000Z
|
2020-04-19T16:36:58.000Z
|
src/entity-system/model/base/guid/GUIDBase_tests.cpp
|
inexorgame-obsolete/entity-system-inactive
|
230a6f116fb02caeace79bc9b32f17fe08687c36
|
[
"MIT"
] | 132
|
2018-07-28T12:30:54.000Z
|
2020-04-25T23:05:33.000Z
|
src/entity-system/model/base/guid/GUIDBase_tests.cpp
|
inexorgame-obsolete/entity-system-inactive
|
230a6f116fb02caeace79bc9b32f17fe08687c36
|
[
"MIT"
] | 3
|
2019-03-02T16:19:23.000Z
|
2020-02-18T05:15:29.000Z
|
#include "GUIDBase.hpp"
#include <gtest/gtest.h>
#include <memory>
using namespace inexor::entity_system;
// @class Test class for GUIDBase.
class ThingThatNeedsGuid : public GUIDBase
{
public:
ThingThatNeedsGuid() : GUIDBase()
{
}
ThingThatNeedsGuid(const xg::Guid ¶m_GUID) : GUIDBase(param_GUID)
{
}
};
TEST(GUIDBase, guid_generation)
{
std::shared_ptr<ThingThatNeedsGuid> test_thing = std::make_shared<ThingThatNeedsGuid>();
// Create an empty GUID.
xg::Guid empty_guid = xg::Guid(std::string(""));
// Make sure the GUID is not empty.
EXPECT_NE(empty_guid, test_thing->get_GUID());
}
TEST(GUIDBase, guid_regeneration)
{
std::shared_ptr<ThingThatNeedsGuid> test_thing = std::make_shared<ThingThatNeedsGuid>();
xg::Guid start_guid = test_thing->get_GUID();
// Generate a new GUID.
test_thing->generate_new_GUID();
xg::Guid end_guid = test_thing->get_GUID();
// The GUID should have changed now.
EXPECT_NE(start_guid, end_guid);
}
TEST(GUIDBase, guid_copy_constructor_test)
{
xg::Guid random_guid = xg::newGuid();
std::shared_ptr<ThingThatNeedsGuid> test_thing = std::make_shared<ThingThatNeedsGuid>(random_guid);
// Check if the GUID has been passed to the copy constructor.
EXPECT_EQ(random_guid, test_thing->get_GUID());
random_guid = xg::newGuid();
// Now that we generated a new guid they should no longer be equal.
EXPECT_NE(random_guid, test_thing->get_GUID());
}
| 25.322034
| 103
| 0.702811
|
inexorgame
|
27f7fb9a58267232e725e61d6db240c9275e0f3d
| 569
|
cpp
|
C++
|
CTaskRunner.cpp
|
KAdamek/task_runner
|
02e204bdf0b409080c8ea1e900dd5afff626699a
|
[
"MIT"
] | null | null | null |
CTaskRunner.cpp
|
KAdamek/task_runner
|
02e204bdf0b409080c8ea1e900dd5afff626699a
|
[
"MIT"
] | null | null | null |
CTaskRunner.cpp
|
KAdamek/task_runner
|
02e204bdf0b409080c8ea1e900dd5afff626699a
|
[
"MIT"
] | null | null | null |
#include "CTaskRunner.h"
CTaskRunner::CTaskRunner(ITask *task, CTaskMetadata *metadata) {
this->task = task;
// metadata could be cloned or stored as a pointer
this->metadata = *metadata;
}
void CTaskRunner::run(CHardwareConfiguration *hardwareConfiguration, CTaskData *data) {
task->setup(hardwareConfiguration, &metadata);
task->preProcessing();
task->start(data);
task->postProcessing();
task->teardown();
}
IExecutionEnvelope* CTaskRunner::executionEnvelope() {
if(envelope == nullptr) envelope = task->executionEnvelope(&metadata);
return envelope;
}
| 27.095238
| 87
| 0.752197
|
KAdamek
|
27ffadf2d315c812975ece7c4a3a2880ba417958
| 7,638
|
cpp
|
C++
|
ai/src/ai/ai_estimates_field.cpp
|
The-city-not-present/noughtsandcrosses-cpp
|
f0e34b02898f25cc1df1cf0c96733f98c7ccca8e
|
[
"MIT"
] | null | null | null |
ai/src/ai/ai_estimates_field.cpp
|
The-city-not-present/noughtsandcrosses-cpp
|
f0e34b02898f25cc1df1cf0c96733f98c7ccca8e
|
[
"MIT"
] | null | null | null |
ai/src/ai/ai_estimates_field.cpp
|
The-city-not-present/noughtsandcrosses-cpp
|
f0e34b02898f25cc1df1cf0c96733f98c7ccca8e
|
[
"MIT"
] | null | null | null |
#include "ai_estimates_field.h"
long double AI_estimates_field::calc_est_data[14] = { 1.0, 1.0, 1.0, 0.995, 0.88, 0.75, 0.19, 0.13, 0.09, 0.08, 0.0006, 0.0005, 0.0, 0.0 };
// ัะฐะฑะปะธัะฝัะต ะทะฝะฐัะตะฝะธั
long double AI_estimates_field::calc_est( char n, bool player_is_me ) {
switch(n) {
case 5:
return ( player_is_me ? calc_est_data[0] : calc_est_data[1] );
case 4:
return ( player_is_me ? calc_est_data[2] : calc_est_data[3] );
case 3:
return ( player_is_me ? calc_est_data[4] : calc_est_data[5] );
case 2:
return ( player_is_me ? calc_est_data[6] : calc_est_data[7] );
case 1:
return ( player_is_me ? calc_est_data[8] : calc_est_data[9] );
case 0:
return ( player_is_me ? calc_est_data[10] : calc_est_data[11] );
default:
return ( player_is_me ? calc_est_data[12] : calc_est_data[13] );
};
};
AI_estimates_field::AI_estimates_field( Field<Field_cell_type>* p ) {
moves_count = p->moves_count;
// now we find the really used area, adjust constraints to it and expand them by 4 squares
// this calculations help us keep field area wider then real field size, and avoid expansion of space
find_min_bounds( p->ctx, p );
expand_bounds();
Create(); // "init" function (mem allocation), substitution of a constructor call
XY point;
for( point.y = p->ctx.y_min; point.y<p->ctx.y_max+1; ++point.y )
for( point.x = p->ctx.x_min; point.x<p->ctx.x_max+1; ++point.x )
if( (bool)(*p)[point] )
(*this)[point].player = (*p)[point];
};
AI_estimates_field::AI_estimates_field( Field<Field_cell_type>* p, XY add ) {
moves_count = p->moves_count+1;
find_min_bounds( p->ctx, p );
if( add.x<ctx.x_min ) ctx.x_min = add.x;
if( add.x>ctx.x_max ) ctx.x_max = add.x;
if( add.y<ctx.y_min ) ctx.y_min = add.y;
if( add.y>ctx.y_max ) ctx.y_max = add.y;
expand_bounds();
Create();
XY point;
for( point.y = p->ctx.y_min; point.y<p->ctx.y_max+1; ++point.y )
for( point.x = p->ctx.x_min; point.x<p->ctx.x_max+1; ++point.x )
if( (bool)(*p)[point] )
(*this)[point].player = (*p)[point];
(*this)[add].player = ( (p->moves_count&1)==0 ? cross : nought );
};
AI_estimates_field::AI_estimates_field( Field<Estimate_field_cell_type>* p ) {
moves_count = p->moves_count;
// now we find the really used area, adjust constraints to it and expand them by 4 squares
// this calculations help us keep field area wider then real field size, and avoid expansion of space
find_min_bounds( p->ctx, p );
expand_bounds();
Create(); // "init" function (mem allocation), substitution of a constructor call
XY point;
for( point.y = p->ctx.y_min; point.y<p->ctx.y_max+1; ++point.y )
for( point.x = p->ctx.x_min; point.x<p->ctx.x_max+1; ++point.x )
if( (bool)(*p)[point] )
(*this)[point].player = (*p)[point].player;
};
AI_estimates_field::AI_estimates_field( Field<Estimate_field_cell_type>* p, XY add ) {
moves_count = p->moves_count+1;
find_min_bounds( p->ctx, p );
if( add.x<ctx.x_min ) ctx.x_min = add.x;
if( add.x>ctx.x_max ) ctx.x_max = add.x;
if( add.y<ctx.y_min ) ctx.y_min = add.y;
if( add.y>ctx.y_max ) ctx.y_max = add.y;
expand_bounds();
Create();
XY point;
for( point.y = p->ctx.y_min; point.y<p->ctx.y_max+1; ++point.y )
for( point.x = p->ctx.x_min; point.x<p->ctx.x_max+1; ++point.x )
if( (bool)(*p)[point] )
(*this)[point].player = (*p)[point].player;
(*this)[add].player = ( (p->moves_count&1)==0 ? cross : nought );
};
// ะฒะฐะถะฝะตะนัะฐั ััะฝะบัะธั
// ะทะฐะฟะพะปะฝัะตั ะฟะพะปะต ะพัะตะฝะบะฐะผะธ ะบะปะตัะพะบ
void AI_estimates_field::calculate() {
lines_direction dirs[4] { dir_rows, dir_columns, dir_diagonal_main, dir_diagonal_minor };
for( auto i_dir : dirs )
for( auto ii = line_iterator_begin_by_dir(i_dir); ii->is_not_equal(*line_iterator_end_by_dir(i_dir)); ii->next() ) {
auto j = ii->begin();
auto to = ii->end();
for( int i=0; i<4; ++i ) {
if( to==j ) break;
--to;
};
for( ; j!=to; ++j ) {
int t_0 = 0;
int t_1 = 0;
int i; auto jj = j;
for( i=0; i<5; ++jj,++i ) {
if( (Val)(*jj).player == cross )
t_0++;
if( (Val)(*jj).player == nought )
t_1++;
};
long double e_0 = calc_est( ( t_1>0 ? -1 : t_0 ), (moves_count&1)==0 );
long double e_1 = calc_est( ( t_0>0 ? -1 : t_1 ), (moves_count&1)==1 );
for( jj=j,i=0; i<5; ++jj,++i ) {
if( (bool)(*jj) )
continue; // ะฝะต ะฑัะดะตะผ ััะฐะฒะธัั ะพัะตะฝะบั ะฒ ัั ะบะปะตัะบั, ะณะดะต ัะถะต ะตััั ั
ะพะด
(*jj).s0 = 1 - (1-(*jj).s0)*(1-e_0);
(*jj).s1 = 1 - (1-(*jj).s1)*(1-e_1);
};
};
};
};
void AI_estimates_field::expand_bounds() {
ctx.x_min -= 4;
ctx.x_max += 4;
ctx.y_min -= 4;
ctx.y_max += 4;
};
void AI_estimates_field::find_min_bounds( Field_constraints& ctx_ref, Field<Field_cell_type>* p ) {
XY t;
for( t.x = ctx_ref.x_min; t.x<0; t.x++ ) {
bool found = false;
for( t.y = ctx_ref.y_min; t.y<=ctx_ref.y_max; ++t.y )
found = found || (bool)(*p)[t];
if( found ) {
ctx.x_min = t.x;
break;
};
};
for( t.x = ctx_ref.x_max; t.x>=0; t.x-- ) {
bool found = false;
for( t.y = ctx_ref.y_min; t.y<=ctx_ref.y_max; ++t.y )
found = found || (bool)(*p)[t];
if( found ) {
ctx.x_max = t.x;
break;
};
};
for( t.y = ctx_ref.y_min; t.y<0; t.y++ ) {
bool found = false;
for( t.x = ctx_ref.x_min; t.x<=ctx_ref.x_max; ++t.x )
found = found || (bool)(*p)[t];
if( found ) {
ctx.y_min = t.y;
break;
};
};
for( t.y = ctx_ref.y_max; t.y>=0; t.y-- ) {
bool found = false;
for( t.x = ctx_ref.x_min; t.x<=ctx_ref.x_max; ++t.x )
found = found || (bool)(*p)[t];
if( found ) {
ctx.y_max = t.y;
break;
};
};
};
void AI_estimates_field::find_min_bounds( Field_constraints& ctx_ref, Field<Estimate_field_cell_type>* p ) {
XY t;
for( t.x = ctx_ref.x_min; t.x<0; t.x++ ) {
bool found = false;
for( t.y = ctx_ref.y_min; t.y<=ctx_ref.y_max; ++t.y )
found = found || (bool)(*p)[t];
if( found ) {
ctx.x_min = t.x;
break;
};
};
for( t.x = ctx_ref.x_max; t.x>=0; t.x-- ) {
bool found = false;
for( t.y = ctx_ref.y_min; t.y<=ctx_ref.y_max; ++t.y )
found = found || (bool)(*p)[t];
if( found ) {
ctx.x_max = t.x;
break;
};
};
for( t.y = ctx_ref.y_min; t.y<0; t.y++ ) {
bool found = false;
for( t.x = ctx_ref.x_min; t.x<=ctx_ref.x_max; ++t.x )
found = found || (bool)(*p)[t];
if( found ) {
ctx.y_min = t.y;
break;
};
};
for( t.y = ctx_ref.y_max; t.y>=0; t.y-- ) {
bool found = false;
for( t.x = ctx_ref.x_min; t.x<=ctx_ref.x_max; ++t.x )
found = found || (bool)(*p)[t];
if( found ) {
ctx.y_max = t.y;
break;
};
};
};
| 33.946667
| 139
| 0.513485
|
The-city-not-present
|
7e0369b65f5f813e2e114f46f61fd92bd0e77f4b
| 1,021
|
hpp
|
C++
|
src/But/Pattern/detail/DispatcherMockImpl.hpp
|
el-bart/but
|
eee2e7e34dde415f4c87461f75c2bab38fc56407
|
[
"BSD-3-Clause"
] | 27
|
2016-01-12T19:30:57.000Z
|
2022-01-27T15:52:39.000Z
|
src/But/Pattern/detail/DispatcherMockImpl.hpp
|
el-bart/but
|
eee2e7e34dde415f4c87461f75c2bab38fc56407
|
[
"BSD-3-Clause"
] | 4
|
2017-04-10T16:30:22.000Z
|
2019-04-24T21:02:55.000Z
|
src/But/Pattern/detail/DispatcherMockImpl.hpp
|
el-bart/but
|
eee2e7e34dde415f4c87461f75c2bab38fc56407
|
[
"BSD-3-Clause"
] | 2
|
2016-12-09T17:09:59.000Z
|
2019-07-16T00:19:31.000Z
|
#pragma once
#include <gmock/gmock.h>
#include <But/Pattern/Dispatcher.hpp>
#include <But/Mpl/NamedVariadicTemplate.hpp>
namespace But
{
namespace Pattern
{
namespace detail
{
template<typename M>
struct MockMethod
{
MOCK_METHOD1_T(handle, void(M const&));
protected:
~MockMethod() = default;
};
template<typename ...Msgs>
struct MockAll
{ };
template<typename Head, typename ...Tail>
struct MockAll<Head, Tail...>: public MockMethod<Head>,
public MockAll<Tail...>
{ };
template<typename Disp, typename ...Msgs>
struct DispatcherMockImpl;
template<typename Disp, typename ...Msgs>
struct DispatcherMockImpl<Disp, Mpl::NamedVariadicTemplate<Msgs...>> final:
public AutoDispatcher< DispatcherMockImpl<Disp, Mpl::NamedVariadicTemplate<Msgs...> >,
typename Disp::PolicyType,
Msgs... >,
public MockAll<Msgs...>
{
template<typename M>
void handle(M const& m)
{
static_cast<MockMethod<M>&>(*this).handle(m);
}
};
}
}
}
| 20.019608
| 88
| 0.665034
|
el-bart
|
7e06cfa7e765c4fcc9c794d4bb83b601d73c8295
| 803
|
cpp
|
C++
|
C++/Binary Tree Inorder Traversal/main.cpp
|
Leobuaa/LeetCode
|
dc2f0fc2d0ddd38e94e71b7a3ffdb75306178a04
|
[
"MIT"
] | 2
|
2016-04-27T11:55:44.000Z
|
2017-02-06T04:15:46.000Z
|
C++/Binary Tree Inorder Traversal/main.cpp
|
Leobuaa/LeetCode
|
dc2f0fc2d0ddd38e94e71b7a3ffdb75306178a04
|
[
"MIT"
] | null | null | null |
C++/Binary Tree Inorder Traversal/main.cpp
|
Leobuaa/LeetCode
|
dc2f0fc2d0ddd38e94e71b7a3ffdb75306178a04
|
[
"MIT"
] | null | null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res = {};
if (!root)
return res;
vector<TreeNode*> sta;
TreeNode* p = root;
while (!sta.empty() || p)
{
while (p)
{
sta.push_back(p);
p = p->left;
}
if (!sta.empty())
{
p = sta.back();
sta.pop_back();
res.push_back(p->val);
p = p->right;
}
}
return res;
}
};
| 22.305556
| 59
| 0.39726
|
Leobuaa
|
7e0c87a29d8473201fc3837c04ab51eb0567388b
| 6,200
|
cpp
|
C++
|
source/ConvexHull.cpp
|
mackron/GTGameEngine
|
380d1e01774fe6bc2940979e4e5983deef0bf082
|
[
"BSD-3-Clause"
] | 31
|
2015-03-19T08:44:48.000Z
|
2021-12-15T20:52:31.000Z
|
source/ConvexHull.cpp
|
mackron/GTGameEngine
|
380d1e01774fe6bc2940979e4e5983deef0bf082
|
[
"BSD-3-Clause"
] | 19
|
2015-07-09T09:02:44.000Z
|
2016-06-09T03:51:03.000Z
|
source/ConvexHull.cpp
|
mackron/GTGameEngine
|
380d1e01774fe6bc2940979e4e5983deef0bf082
|
[
"BSD-3-Clause"
] | 3
|
2017-10-04T23:38:18.000Z
|
2022-03-07T08:27:13.000Z
|
// Copyright (C) 2011 - 2014 David Reid. See included LICENCE.
// HACD headers need to be first.
#include <GTGE/HACD/hacdCircularList.h>
#include <GTGE/HACD/hacdVector.h>
#include <GTGE/HACD/hacdICHull.h>
#include <GTGE/HACD/hacdGraph.h>
#include <GTGE/HACD/hacdHACD.h>
#include <GTGE/ConvexHull.hpp>
namespace GT
{
ConvexHull::ConvexHull()
: vertices(), indices()
{
}
ConvexHull::ConvexHull(const ConvexHull &other)
: vertices(other.vertices), indices(other.indices)
{
}
ConvexHull::ConvexHull(const float* verticesIn, unsigned int vertexCount, const unsigned int* indicesIn, unsigned int indexCount)
: vertices(), indices()
{
this->Build(verticesIn, vertexCount, indicesIn, indexCount);
}
ConvexHull::~ConvexHull()
{
}
void ConvexHull::Build(const float* verticesIn, unsigned int vertexCount, const unsigned int* indicesIn, unsigned int indexCount)
{
this->vertices.Clear();
this->indices.Clear();
for (unsigned int i = 0; i < vertexCount; ++i)
{
this->vertices.PushBack(glm::vec3(verticesIn[i * 3 + 0], verticesIn[i * 3 + 1], verticesIn[i * 3 + 2]));
}
for (unsigned int i = 0; i < indexCount; ++i)
{
this->indices.PushBack(indicesIn[i]);
}
}
//////////////////////////////////////////////////////////
// Static Functions
void ConvexHull::BuildConvexHulls(const VertexArray &va, ConvexHull* &outputArray, unsigned int &outputCount, ConvexHullBuildSettings &settings)
{
outputArray = nullptr;
outputCount = 0;
auto vertexData = va.GetVertexDataPtr();
auto indexData = va.GetIndexDataPtr();
auto vertexCount = va.GetVertexCount();
auto indexCount = va.GetIndexCount();
if (vertexData != nullptr && indexData != nullptr)
{
auto vertexSize = va.GetFormat().GetSize();
auto positionOffset = va.GetFormat().GetAttributeOffset(VertexAttribs::Position);
HACD::HACD* hacd = HACD::CreateHACD(nullptr); // heh.
if (hacd != nullptr)
{
Vector<HACD::Vec3<HACD::Real>> pointsHACD(vertexCount);
Vector<HACD::Vec3<long>> triangles(indexCount / 3);
for (size_t i = 0; i < vertexCount; ++i)
{
auto position = vertexData + (i * vertexSize) + positionOffset;
pointsHACD.PushBack(HACD::Vec3<HACD::Real>(position[0], position[1], position[2]));
}
for (size_t i = 0; i < indexCount; i += 3)
{
triangles.PushBack(HACD::Vec3<long>(indexData[i + 0], indexData[i + 1], indexData[i + 2]));
}
hacd->SetPoints(&pointsHACD[0]);
hacd->SetNPoints(pointsHACD.count);
hacd->SetTriangles(&triangles[0]);
hacd->SetNTriangles(triangles.count);
hacd->SetCompacityWeight( settings.compacityWeight);
hacd->SetVolumeWeight( settings.volumeWeight);
hacd->SetNClusters( settings.minClusters); // Minimum number of clusters to generate.
hacd->SetNVerticesPerCH( settings.verticesPerCH); // CH = Convex-Hull.
hacd->SetConcavity( settings.concavity);
hacd->SetSmallClusterThreshold( settings.smallClusterThreshold);
hacd->SetConnectDist( settings.connectedComponentsDist);
hacd->SetNTargetTrianglesDecimatedMesh(settings.simplifiedTriangleCountTarget);
hacd->SetAddExtraDistPoints( settings.addExtraDistPoints);
hacd->SetAddFacesPoints( settings.addFacesPoints);
if (hacd->Compute())
{
auto clusterCount = hacd->GetNClusters();
outputArray = new ConvexHull[clusterCount];
outputCount = clusterCount;
for (size_t iCluster = 0U; iCluster < clusterCount; ++iCluster)
{
size_t pointCount = hacd->GetNPointsCH(iCluster);
size_t triangleCount = hacd->GetNTrianglesCH(iCluster);
auto pointsCH = new HACD::Vec3<HACD::Real>[pointCount];
auto trianglesCH = new HACD::Vec3<long>[triangleCount];
hacd->GetCH(iCluster, pointsCH, trianglesCH);
auto points = new float[pointCount * 3];
for (size_t iPoint = 0; iPoint < pointCount; ++iPoint)
{
points[iPoint * 3 + 0] = static_cast<float>(pointsCH[iPoint].X());
points[iPoint * 3 + 1] = static_cast<float>(pointsCH[iPoint].Y());
points[iPoint * 3 + 2] = static_cast<float>(pointsCH[iPoint].Z());
}
auto indices = new unsigned int[triangleCount * 3];
for (size_t iTriangle = 0; iTriangle < triangleCount; ++iTriangle)
{
indices[iTriangle * 3 + 0] = static_cast<unsigned int>(trianglesCH[iTriangle].X());
indices[iTriangle * 3 + 1] = static_cast<unsigned int>(trianglesCH[iTriangle].Y());
indices[iTriangle * 3 + 2] = static_cast<unsigned int>(trianglesCH[iTriangle].Z());
}
outputArray[iCluster].Build(points, pointCount, indices, triangleCount * 3);
delete [] pointsCH;
delete [] trianglesCH;
delete [] points;
delete [] indices;
}
}
HACD::DestroyHACD(hacd);
}
}
}
void ConvexHull::DeleteConvexHulls(ConvexHull* convexHulls)
{
delete [] convexHulls;
}
}
| 39.240506
| 148
| 0.526774
|
mackron
|
7e1cc40c65643e2a5d93ade4964e0614b8a9a879
| 358
|
cpp
|
C++
|
src/engine/ChessEngineFactory.cpp
|
patryk-kacperski/chess-engine
|
d636bf3cab9f5d8b72523ce8f2be493b6666c660
|
[
"MIT"
] | null | null | null |
src/engine/ChessEngineFactory.cpp
|
patryk-kacperski/chess-engine
|
d636bf3cab9f5d8b72523ce8f2be493b6666c660
|
[
"MIT"
] | null | null | null |
src/engine/ChessEngineFactory.cpp
|
patryk-kacperski/chess-engine
|
d636bf3cab9f5d8b72523ce8f2be493b6666c660
|
[
"MIT"
] | 1
|
2019-04-05T20:26:27.000Z
|
2019-04-05T20:26:27.000Z
|
//
// Created by Patryk Kacperski on 09/07/2018.
//
#include "ChessEngineFactory.h"
namespace pkchessengine {
std::unique_ptr<ChessEngine> ChessEngineFactory::create() {
return nullptr;
}
std::unique_ptr<ChessEngine> ChessEngineFactory::create(const std::vector<std::vector<PieceInfo>>& initialState) {
return nullptr;
}
}
| 22.375
| 118
| 0.692737
|
patryk-kacperski
|
7e21cbcda03a1ec0e77025ea2dd8395ec6eeb100
| 2,516
|
cpp
|
C++
|
src/simpcl/src/filters/model_projection.cpp
|
senceryazici/point-cloud-filters
|
d5e4e599b493cc2af1517000c012d7936d46cf0f
|
[
"MIT"
] | 17
|
2020-01-08T14:35:05.000Z
|
2021-12-09T12:30:07.000Z
|
src/simpcl/src/filters/model_projection.cpp
|
senceryazici/point-cloud-filters
|
d5e4e599b493cc2af1517000c012d7936d46cf0f
|
[
"MIT"
] | 2
|
2020-01-31T16:31:48.000Z
|
2022-03-09T12:49:53.000Z
|
src/simpcl/src/filters/model_projection.cpp
|
senceryazici/point-cloud-filters
|
d5e4e599b493cc2af1517000c012d7936d46cf0f
|
[
"MIT"
] | 7
|
2020-01-08T21:28:58.000Z
|
2021-12-03T06:00:05.000Z
|
// Projecting points using a parametric model
// Plane Model used.
// http://www.pointclouds.org/documentation/tutorials/project_inliers.php
// Import dependencies
#include <string>
#include <ros/ros.h>
#include <iostream>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl_conversions/pcl_conversions.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/filters/project_inliers.h>
// Definitions
ros::Publisher pub;
std::string subscribed_topic;
std::string published_topic;
// callback
void cloud_cb(const sensor_msgs::PointCloud2ConstPtr& cloud_msg)
{
//Create point cloud objects for cleaned_cloud and projected_cloud
pcl::PCLPointCloud2* cleaned_cloud = new pcl::PCLPointCloud2;
pcl::PCLPointCloud2ConstPtr cloudPtr(cleaned_cloud);
pcl::PCLPointCloud2 projected_cloud;
// Convert to PCL data type
pcl_conversions::toPCL(*cloud_msg, *cleaned_cloud);
// Fill the ModelCoefficients values
pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients());
coefficients->values.resize(4);
coefficients->values[0] = 0;
coefficients->values[1] = 0;
coefficients->values[2] = 1.0;
coefficients->values[3] = 0;
// Perform Projection on a plane model
pcl::ProjectInliers<pcl::PCLPointCloud2> proj;
proj.setModelType (pcl::SACMODEL_PLANE); // Set model to plane
proj.setInputCloud(cloudPtr); // cleaned_cloud to the filter
proj.setModelCoefficients(coefficients);
proj.filter(projected_cloud); // Store output data in projected_cloud
// Convert to ROS data type
sensor_msgs::PointCloud2 output_cloud;
pcl_conversions::moveFromPCL(projected_cloud, output_cloud);
pub.publish(output_cloud); // Publish projected_cloud to the /cloud_projected topic
}
int main(int argc, char **argv)
{
// Initialize ROS
ros::init(argc, argv, "model_projection");
ros::NodeHandle n;
// Load parameters from launch file
ros::NodeHandle nh_private("~");
nh_private.param<std::string>("subscribed_topic", subscribed_topic, "/point_cloud");
nh_private.param<std::string>("published_topic", published_topic, "cloud_projected");
// Create Subscriber and listen /cloud_cleaned topic
ros::Subscriber sub = n.subscribe<sensor_msgs::PointCloud2>(subscribed_topic, 1, cloud_cb);
// Create Publisher
pub = n.advertise<sensor_msgs::PointCloud2>(published_topic, 1);
// Spin
ros::spin();
return 0;
}
| 33.105263
| 95
| 0.736089
|
senceryazici
|
7e29a52aa00653cbadc64bed34e358dffe9a20b5
| 1,669
|
hh
|
C++
|
EvtGen1_06_00/EvtGenModels/EvtbsToLLLLAmp.hh
|
klendathu2k/StarGenerator
|
7dd407c41d4eea059ca96ded80d30bda0bc014a4
|
[
"MIT"
] | 2
|
2018-12-24T19:37:00.000Z
|
2022-02-28T06:57:20.000Z
|
EvtGen1_06_00/EvtGenModels/EvtbsToLLLLAmp.hh
|
klendathu2k/StarGenerator
|
7dd407c41d4eea059ca96ded80d30bda0bc014a4
|
[
"MIT"
] | null | null | null |
EvtGen1_06_00/EvtGenModels/EvtbsToLLLLAmp.hh
|
klendathu2k/StarGenerator
|
7dd407c41d4eea059ca96ded80d30bda0bc014a4
|
[
"MIT"
] | null | null | null |
//--------------------------------------------------------------------------
//
// Environment:
// This software is part of the EvtGen package developed jointly
// for the BaBar and CLEO collaborations. If you use all or part
// of it, please give an appropriate acknowledgement.
//
// Copyright Information: See EvtGen/COPYRIGHT
// Copyright (C) 1998 Caltech, UCSB
//
// Module: EvtGen/EvtbsToLLLLAmp.hh
//
// Description:
//
// Modification history:
//
// N.Nikitin Jult 24, 2011 Module created
//
//------------------------------------------------------------------------
#ifndef EVTBSTOLLLL_AMP_HH
#define EVTBSTOLLLL_AMP_HH
class EvtId;
class EvtAmp;
class EvtParticle;
class Evtbs2llGammaFF;
class EvtbTosllWilsCoeffNLO;
class EvtbsToLLLLAmp{
public:
void CalcAmp( EvtParticle *parent, EvtAmp& amp,
Evtbs2llGammaFF *formFactors,
EvtbTosllWilsCoeffNLO *WilsCoeff,
double mu, int Nf,
int res_swch, int ias,
double CKM_A, double CKM_lambda,
double CKM_barrho, double CKM_bareta);
double CalcMaxProb(
// EvtId parnum,
// EvtId l1num, EvtId l2num,
// EvtId l3num, EvtId l4num,
// Evtbs2llGammaFF *formFactors,
// EvtbTosllWilsCoeffNLO *WilsCoeff,
// double mu, int Nf, int res_swch, int ias,
// double CKM_A, double CKM_lambda,
// double CKM_barrho, double CKM_bareta
);
double lambda(double a, double b, double c);
};
#endif
| 27.816667
| 76
| 0.536249
|
klendathu2k
|
7e2ae383187c5c86098f92ac86f5d12281172e0c
| 3,189
|
hpp
|
C++
|
include/CQLDriver/Common/ColumnTypes/MapBase.hpp
|
cpv-project/cpv-cql-driver
|
66eebfd4e9ec75dc49cd4a7073a51a830236807a
|
[
"MIT"
] | 41
|
2018-01-23T09:27:32.000Z
|
2021-02-15T15:49:07.000Z
|
include/CQLDriver/Common/ColumnTypes/MapBase.hpp
|
cpv-project/cpv-cql-driver
|
66eebfd4e9ec75dc49cd4a7073a51a830236807a
|
[
"MIT"
] | 20
|
2018-01-25T04:25:48.000Z
|
2019-03-09T02:49:41.000Z
|
include/CQLDriver/Common/ColumnTypes/MapBase.hpp
|
cpv-project/cpv-cql-driver
|
66eebfd4e9ec75dc49cd4a7073a51a830236807a
|
[
"MIT"
] | 5
|
2018-04-10T12:19:13.000Z
|
2020-02-17T03:30:50.000Z
|
#pragma once
#include <cstdint>
#include <initializer_list>
#include "../Exceptions/DecodeException.hpp"
#include "../ColumnTrait.hpp"
#include "./Int.hpp"
namespace cql {
/**
* A [int] n indicating the number of key/value pairs in the map, followed by n entries.
* Each entry is composed of two [bytes] representing the key and value.
*/
template <class MapType>
class MapBase {
public:
using UnderlyingType = MapType;
using KeyType = typename MapType::key_type;
using MappedType = typename MapType::mapped_type;
using ValueType = typename MapType::value_type;
/** Get the map value */
const UnderlyingType& get() const& { return value_; }
/** Get the mutable map value */
UnderlyingType& get() & { return value_; }
/** Set the map value */
void set(const UnderlyingType& value) { value_ = value_; }
/** Set the map value */
void set(UnderlyingType&& value) { value_ = std::move(value); }
/** Set the map value by initializer list */
template <class UKey, class UValue>
void set(std::initializer_list<std::pair<UKey, UValue>>&& items) {
value_.clear();
for (auto&& item : items) {
value_.emplace(
KeyType(std::move(item.first)),
MappedType(std::move(item.second)));
}
}
/** Reset to initial state */
void reset() { value_.clear(); }
/** Encode to binary data */
void encodeBody(std::string& data) const {
Int mapSize(value_.size());
mapSize.encodeBody(data);
for (const auto& item : value_) {
ColumnTrait<KeyType>::encode(item.first, data);
ColumnTrait<MappedType>::encode(item.second, data);
}
}
/** Decode from binary data */
void decodeBody(const char* ptr, const ColumnEncodeDecodeSizeType& size) {
if (CQL_UNLIKELY(size < static_cast<ColumnEncodeDecodeSizeType>(Int::EncodeSize))) {
throw DecodeException(CQL_CODEINFO,
"length of map size not enough, element type is:",
typeid(ValueType).name());
}
Int mapSize;
mapSize.decodeBody(ptr, Int::EncodeSize);
if (CQL_UNLIKELY(mapSize < 0)) {
throw DecodeException(CQL_CODEINFO,
"map size can't be negative:", mapSize);
}
const char* ptrStart = ptr + Int::EncodeSize;
const char* end = ptr + size;
value_.clear();
for (Int::UnderlyingType index = 0; index < mapSize; ++index) {
KeyType key;
MappedType value;
ColumnTrait<KeyType>::decode(key, ptrStart, end);
ColumnTrait<MappedType>::decode(value, ptrStart, end);
value_.emplace(std::move(key), std::move(value));
}
}
/** Constructors */
MapBase() : value_() { }
explicit MapBase(const UnderlyingType& value) : value_(value) { }
explicit MapBase(UnderlyingType&& value) : value_(std::move(value)) { }
template <class UKey, class UValue>
explicit MapBase(std::initializer_list<std::pair<UKey, UValue>>&& items) : value_() {
set(std::move(items));
}
/** Dereference operation */
const UnderlyingType& operator*() const& { return value_; }
UnderlyingType& operator*() & { return value_; }
/** Get pointer operation */
const UnderlyingType* operator->() const& { return &value_; }
UnderlyingType* operator->() & { return &value_; }
private:
UnderlyingType value_;
};
}
| 30.663462
| 89
| 0.669489
|
cpv-project
|
7e2b1474dff3c8a0ef00d63b4fb62b0e86b44c35
| 10,154
|
cpp
|
C++
|
digitanks/src/digitanks/ui/ui.cpp
|
BSVino/Digitanks
|
1bd1ed115493bce22001ae6684b70b8fcf135db0
|
[
"BSD-4-Clause"
] | 5
|
2015-07-03T18:42:32.000Z
|
2017-08-25T10:28:12.000Z
|
digitanks/src/digitanks/ui/ui.cpp
|
BSVino/Digitanks
|
1bd1ed115493bce22001ae6684b70b8fcf135db0
|
[
"BSD-4-Clause"
] | null | null | null |
digitanks/src/digitanks/ui/ui.cpp
|
BSVino/Digitanks
|
1bd1ed115493bce22001ae6684b70b8fcf135db0
|
[
"BSD-4-Clause"
] | null | null | null |
#include "digitankswindow.h"
#include <glgui/rootpanel.h>
#include <tinker_platform.h>
#include <strutils.h>
#include <sockets/sockets.h>
#include <glgui/filedialog.h>
#include <ui/instructor.h>
#include <tengine/lobby/lobby_client.h>
#include <tengine/lobby/lobby_server.h>
#include <renderer/renderer.h>
#include "hud.h"
#include "menu.h"
#include "ui.h"
#include "lobbyui.h"
#define _T(x) x
using namespace glgui;
void CDigitanksWindow::InitUI()
{
m_pMainMenu = CRootPanel::Get()->AddControl(new CMainMenu());
m_pMenu = CRootPanel::Get()->AddControl(new CDigitanksMenu());
m_pVictory = CRootPanel::Get()->AddControl(new CVictoryPanel());
m_pStory = CRootPanel::Get()->AddControl(new CStoryPanel());
m_pLobby = CRootPanel::Get()->AddControl(new CLobbyPanel());
CRootPanel::Get()->Layout();
}
void CDigitanksWindow::Layout()
{
CRootPanel::Get()->Layout();
}
CDigitanksMenu::CDigitanksMenu()
: CPanel(0, 0, 200, 300)
{
m_pOptionsPanel = NULL;
m_pDigitanks = AddControl(new CLabel(0, 0, 100, 100, _T("DIGITANKS")));
m_pDigitanks->SetFont(_T("header"));
m_pDifficulty = AddControl(new CScrollSelector<int>(_T("text")));
m_pDifficulty->AddSelection(CScrollSelection<int>(0, _T("Easy")));
m_pDifficulty->AddSelection(CScrollSelection<int>(1, _T("Normal")));
m_pDifficulty->SetSelection(1);
m_pDifficultyLabel = AddControl(new CLabel(0, 0, 32, 32, _T("Difficulty")));
m_pDifficultyLabel->SetWrap(false);
m_pDifficultyLabel->SetFont(_T("text"));
m_pReturnToMenu = AddControl(new CButton(0, 0, 100, 100, _T("EXIT TO MENU")));
m_pReturnToMenu->SetClickedListener(this, Exit);
m_pReturnToMenu->SetFont(_T("header"));
m_pReturnToGame = AddControl(new CButton(0, 0, 100, 100, _T("X")));
m_pReturnToGame->SetClickedListener(this, Close);
m_pSaveGame = AddControl(new CButton(0, 0, 100, 100, _T("SAVE GAME")));
m_pSaveGame->SetClickedListener(this, Save);
m_pSaveGame->SetFont(_T("header"));
m_pLoadGame = AddControl(new CButton(0, 0, 100, 100, _T("LOAD GAME")));
m_pLoadGame->SetClickedListener(this, Load);
m_pLoadGame->SetFont(_T("header"));
m_pOptions = AddControl(new CButton(0, 0, 100, 100, _T("OPTIONS")));
m_pOptions->SetClickedListener(this, Options);
m_pOptions->SetFont(_T("header"));
m_pExit = AddControl(new CButton(0, 0, 100, 100, _T("QUIT TO DESKTOP")));
m_pExit->SetClickedListener(this, Quit);
m_pExit->SetFont(_T("header"));
Layout();
SetVisible(false);
}
void CDigitanksMenu::Layout()
{
size_t iWidth = RootPanel()->GetWidth();
size_t iHeight = RootPanel()->GetHeight();
SetPos(iWidth/2-GetWidth()/2, iHeight/2-GetHeight()/2);
m_pDigitanks->SetPos(0, 20);
m_pDigitanks->SetSize(GetWidth(), GetHeight());
m_pDigitanks->SetAlign(CLabel::TA_TOPCENTER);
int iSelectorSize = m_pDifficultyLabel->GetHeight() - 4;
m_pDifficultyLabel->EnsureTextFits();
m_pDifficultyLabel->SetPos(25, 60);
m_pDifficultyLabel->SetVisible(!GameNetwork()->IsConnected());
m_pDifficulty->SetSize(GetWidth() - m_pDifficultyLabel->GetLeft()*2 - m_pDifficultyLabel->GetWidth(), iSelectorSize);
m_pDifficulty->SetPos(m_pDifficultyLabel->GetRight(), 60);
m_pDifficulty->SetVisible(!GameNetwork()->IsConnected());
m_pSaveGame->SetPos(25, 130);
m_pSaveGame->SetSize(150, 20);
m_pLoadGame->SetPos(25, 160);
m_pLoadGame->SetSize(150, 20);
m_pOptions->SetPos(25, 190);
m_pOptions->SetSize(150, 20);
m_pReturnToMenu->SetPos(25, 220);
m_pReturnToMenu->SetSize(150, 20);
m_pReturnToGame->SetPos(GetWidth()-20, 10);
m_pReturnToGame->SetSize(10, 10);
m_pReturnToGame->SetButtonColor(Color(255, 0, 0));
m_pExit->SetPos(25, 250);
m_pExit->SetSize(150, 20);
BaseClass::Layout();
}
void CDigitanksMenu::Paint(float x, float y, float w, float h)
{
if (GameServer())
CRootPanel::PaintRect(x, y, w, h, Color(12, 13, 12, 235));
BaseClass::Paint(x, y, w, h);
}
void CDigitanksMenu::SetVisible(bool bVisible)
{
m_pReturnToGame->SetVisible(!!GameServer());
if (m_pOptionsPanel)
{
RemoveControl(m_pOptionsPanel);
m_pOptionsPanel = NULL;
}
BaseClass::SetVisible(bVisible);
}
void CDigitanksMenu::CloseCallback(const tstring& sArgs)
{
SetVisible(false);
if (m_pOptionsPanel)
{
RemoveControl(m_pOptionsPanel);
m_pOptionsPanel = NULL;
}
}
void CDigitanksMenu::SaveCallback(const tstring& sArgs)
{
glgui::CFileDialog::ShowSaveDialog(DigitanksWindow()->GetAppDataDirectory(), ".sav", this, SaveFile);
}
void CDigitanksMenu::SaveFileCallback(const tstring& sArgs)
{
tstring sFilename = glgui::CFileDialog::GetFile();
if (!sFilename.length())
return;
CGameServer::SaveToFile(sFilename.c_str());
}
void CDigitanksMenu::LoadCallback(const tstring& sArgs)
{
if (!GameServer())
GameWindow()->Restart("empty");
glgui::CFileDialog::ShowOpenDialog(DigitanksWindow()->GetAppDataDirectory(), ".sav", this, Open);
}
void CDigitanksMenu::OpenCallback(const tstring& sArgs)
{
tstring sFilename = glgui::CFileDialog::GetFile();
if (!sFilename.length())
return;
DigitanksWindow()->RenderLoading();
if (CGameServer::LoadFromFile(sFilename.c_str()))
SetVisible(false);
else
{
DigitanksWindow()->DestroyGame();
GameWindow()->Restart("menu");
}
}
void CDigitanksMenu::OptionsCallback(const tstring& sArgs)
{
if (m_pOptionsPanel)
RemoveControl(m_pOptionsPanel);
m_pOptionsPanel = CRootPanel::Get()->AddControl(new COptionsPanel(), true);
m_pOptionsPanel->SetStandalone(true);
m_pOptionsPanel->Layout();
}
void CDigitanksMenu::ExitCallback(const tstring& sArgs)
{
CGameLobbyClient::S_LeaveLobby();
CGameLobbyServer::DestroyLobby(0);
GameNetwork()->Disconnect();
LobbyNetwork()->Disconnect();
GameServer()->SetLoading(true);
DigitanksWindow()->DestroyGame();
GameWindow()->Restart("menu");
SetVisible(false);
DigitanksWindow()->GetMainMenu()->SetVisible(true);
GameServer()->SetLoading(false);
}
void CDigitanksMenu::QuitCallback(const tstring& sArgs)
{
DigitanksWindow()->CloseApplication();
}
CVictoryPanel::CVictoryPanel()
: CPanel(0, 0, 400, 300)
{
m_pVictory = AddControl(new CLabel(0, 0, 100, 100, _T("")));
m_pVictory->SetFont(_T("text"));
m_pRestart = AddControl(new CButton(0, 0, 100, 100, _T("Restart")));
m_pRestart->SetFont(_T("header"));
SetVisible(false);
Layout();
}
void CVictoryPanel::Layout()
{
SetSize(550, 200);
SetPos(CRootPanel::Get()->GetWidth()/2-GetWidth()/2, CRootPanel::Get()->GetHeight()/2-GetHeight()/2);
m_pVictory->SetPos(10, 20);
m_pVictory->SetSize(GetWidth()-20, GetHeight());
m_pVictory->SetAlign(CLabel::TA_TOPCENTER);
m_pRestart->SetSize(80, 35);
m_pRestart->SetPos(GetWidth()/2-m_pRestart->GetWidth()/2, GetHeight() - m_pRestart->GetHeight() - 20);
m_pRestart->SetClickedListener(this, Restart);
}
void CVictoryPanel::Paint(float x, float y, float w, float h)
{
CRootPanel::PaintRect(x, y, w, h, Color(12, 13, 12, 235));
BaseClass::Paint(x, y, w, h);
}
void CVictoryPanel::GameOver(bool bPlayerWon)
{
if (bPlayerWon)
m_pVictory->SetText(_T("VICTORY!\n \nYou have crushed the weak and foolish under your merciless, unwavering treads. Your enemies bow before you as you stand - ruler of the Digiverse!\n \n"));
else
m_pVictory->SetText(_T("DEFEAT!\n \nYour ravenous enemies have destroyed your feeble tank armies. Database memories will recall the day when your once-glorious digital empire crumbled!\n \n"));
if (DigitanksGame()->GetGameType() == GAMETYPE_CAMPAIGN && bPlayerWon)
m_pRestart->SetVisible(false);
else
m_pRestart->SetVisible(true);
if (!GameNetwork()->IsHost())
m_pRestart->SetVisible(false);
SetVisible(true);
}
void CVictoryPanel::RestartCallback(const tstring& sArgs)
{
DigitanksWindow()->RestartLevel();
SetVisible(false);
}
CStoryPanel::CStoryPanel()
: CPanel(0, 0, 400, 300)
{
m_pStory = AddControl(new CLabel(0, 0, 100, 100,
_T("THE STORY OF DIGIVILLE\n \n")
_T("The Digizens of Digiville were happy and content.\n")
_T("They ate in tiny bits and bytes and always paid their rent.\n")
_T("They shared every Electronode and Data Wells were free,\n")
_T("But that's not very interesting, as you're about to see.\n \n ")
_T("One day the shortest Digizen in all the Digiverse\n")
_T("He cried, \"U nubs OLOL i h4x j0ur m3g4hu|2tz!\"\n")
_T("The Digizens of Digiville just laughed and said, \"That's great!\"\n")
_T("\"You're way too short and you're just trying to overcompensate!\"\n \n")
_T("Our little man was not so pleased, retreating to his lair\n")
_T("He powered up his Trolling Rage Machine with utmost flair.\n")
_T("It sputtered up to life with a cacophony of clanks\n")
_T("And shortly then thereafter it began to spit out tanks.\n \n")
_T("The Digizens were sleeping when there came a sudden chill\n")
_T("And when they woke there was no longer any Digiville.\n")
_T("It's up to you now! You must act before it gets much worse,\n")
_T("And while you're there, why not conquer the whole damn Digiverse?\n \n")
_T("Click here to begin.")
));
m_pStory->SetFont(_T("text"));
SetVisible(false);
Layout();
}
void CStoryPanel::Layout()
{
SetSize(500, 400);
SetPos(CRootPanel::Get()->GetWidth()/2-GetWidth()/2, CRootPanel::Get()->GetHeight()/2-GetHeight()/2);
m_pStory->SetPos(10, 20);
m_pStory->SetSize(GetWidth()-20, GetHeight());
m_pStory->SetAlign(CLabel::TA_TOPCENTER);
}
void CStoryPanel::Paint(float x, float y, float w, float h)
{
CRootPanel::PaintRect(x, y, w, h, Color(12, 13, 12, 235));
BaseClass::Paint(x, y, w, h);
}
bool CStoryPanel::MousePressed(int code, int mx, int my)
{
if (BaseClass::MousePressed(code, mx, my))
return true;
SetVisible(false);
// Now that it's closed, run the tutorial!
CInstructor* pInstructor = DigitanksWindow()->GetInstructor();
pInstructor->SetActive(true);
pInstructor->Initialize();
pInstructor->DisplayFirstLesson("strategy-select");
return true;
}
bool CStoryPanel::KeyPressed(int iKey, bool bCtrlDown)
{
SetVisible(false);
// Now that it's closed, run the tutorial!
CInstructor* pInstructor = DigitanksWindow()->GetInstructor();
pInstructor->SetActive(true);
pInstructor->Initialize();
pInstructor->DisplayFirstLesson("strategy-select");
// Pass the keypress through so that the menu opens.
return false;
}
| 27.295699
| 195
| 0.719815
|
BSVino
|
7e2fe5855d09cb05c741ae37737cefed9d0575bc
| 2,615
|
hpp
|
C++
|
include/Nazara/Graphics/DepthPipelinePass.hpp
|
jayrulez/NazaraEngine
|
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
|
[
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 11
|
2019-11-27T00:40:43.000Z
|
2020-01-29T14:31:52.000Z
|
include/Nazara/Graphics/DepthPipelinePass.hpp
|
jayrulez/NazaraEngine
|
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
|
[
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7
|
2019-11-27T00:29:08.000Z
|
2020-01-08T18:53:39.000Z
|
include/Nazara/Graphics/DepthPipelinePass.hpp
|
jayrulez/NazaraEngine
|
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
|
[
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7
|
2019-11-27T10:27:40.000Z
|
2020-01-15T17:43:33.000Z
|
// Copyright (C) 2022 Jรฉrรดme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_GRAPHICS_DEPTHPIPELINEPASS_HPP
#define NAZARA_GRAPHICS_DEPTHPIPELINEPASS_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Graphics/Config.hpp>
#include <Nazara/Graphics/ElementRenderer.hpp>
#include <Nazara/Graphics/FramePipelinePass.hpp>
#include <Nazara/Graphics/MaterialPass.hpp>
#include <Nazara/Graphics/RenderElement.hpp>
#include <Nazara/Graphics/RenderQueue.hpp>
#include <Nazara/Graphics/RenderQueueRegistry.hpp>
#include <Nazara/Math/Frustum.hpp>
namespace Nz
{
class AbstractViewer;
class FrameGraph;
class FramePipeline;
class Material;
class NAZARA_GRAPHICS_API DepthPipelinePass : public FramePipelinePass
{
public:
DepthPipelinePass(FramePipeline& owner, AbstractViewer* viewer);
DepthPipelinePass(const DepthPipelinePass&) = delete;
DepthPipelinePass(DepthPipelinePass&&) = delete;
~DepthPipelinePass();
inline void InvalidateCommandBuffers();
inline void InvalidateElements();
void Prepare(RenderFrame& renderFrame, const Frustumf& frustum, const std::vector<FramePipelinePass::VisibleRenderable>& visibleRenderables, std::size_t visibilityHash);
void RegisterMaterial(const Material& material);
void RegisterToFrameGraph(FrameGraph& frameGraph, std::size_t depthBufferIndex);
void UnregisterMaterial(const Material& material);
DepthPipelinePass& operator=(const DepthPipelinePass&) = delete;
DepthPipelinePass& operator=(DepthPipelinePass&&) = delete;
private:
struct MaterialPassEntry
{
std::size_t usedCount = 1;
NazaraSlot(MaterialPass, OnMaterialPassPipelineInvalidated, onMaterialPipelineInvalidated);
NazaraSlot(MaterialPass, OnMaterialPassShaderBindingInvalidated, onMaterialShaderBindingInvalidated);
};
std::size_t m_depthPassIndex;
std::size_t m_lastVisibilityHash;
std::vector<std::unique_ptr<ElementRendererData>> m_elementRendererData;
std::vector<std::unique_ptr<RenderElement>> m_renderElements;
std::vector<ElementRenderer::RenderStates> m_renderStates;
std::unordered_map<MaterialPass*, MaterialPassEntry> m_materialPasses;
RenderQueue<RenderElement*> m_renderQueue;
RenderQueueRegistry m_renderQueueRegistry;
AbstractViewer* m_viewer;
FramePipeline& m_pipeline;
bool m_rebuildCommandBuffer;
bool m_rebuildElements;
};
}
#include <Nazara/Graphics/DepthPipelinePass.inl>
#endif // NAZARA_GRAPHICS_DEPTHPIPELINEPASS_HPP
| 34.866667
| 172
| 0.798088
|
jayrulez
|
7e31387852b04a4c94e654536d035d4682fbca73
| 8,721
|
cpp
|
C++
|
Modular/library/source/TTSender.cpp
|
jamoma/JamomaCore
|
7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43
|
[
"BSD-3-Clause"
] | 31
|
2015-02-28T23:51:10.000Z
|
2021-12-25T04:16:01.000Z
|
Modular/library/source/TTSender.cpp
|
jamoma/JamomaCore
|
7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43
|
[
"BSD-3-Clause"
] | 126
|
2015-01-01T13:42:05.000Z
|
2021-07-13T14:11:42.000Z
|
Modular/library/source/TTSender.cpp
|
jamoma/JamomaCore
|
7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43
|
[
"BSD-3-Clause"
] | 14
|
2015-02-10T15:08:32.000Z
|
2019-09-17T01:21:25.000Z
|
/** @file
*
* @ingroup modularLibrary
*
* @brief A Sender Object
*
* @details
*
* @authors Thรฉo de la Hogue
*
* @copyright ยฉ 2010, Thรฉo de la Hogue @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTSender.h"
#define thisTTClass TTSender
#define thisTTClassName "Sender"
#define thisTTClassTags "node, sender"
TT_MODULAR_CONSTRUCTOR,
mAddress(kTTAdrsEmpty),
mObjectCache(NULL)
{
// a Sender can handle a signal
if (arguments.size() == 1)
mSignal = arguments[0];
addAttributeWithSetter(Address, kTypeSymbol);
addAttribute(ObjectCache, kTypePointer);
addAttributeProperty(ObjectCache, hidden, YES);
addAttributeProperty(ObjectCache, readOnly, YES);
addMessageWithArguments(Send);
addMessageProperty(Send, hidden, YES);
mIsSending = false;
mObjectCache = new TTList();
mObjectCache->setThreadProtection(true);
}
TTSender::~TTSender()
{
unbindAddress(accessApplicationDirectoryFrom(mAddress));
unbindApplication();
delete mObjectCache;
}
TTErr TTSender::setAddress(const TTValue& newValue)
{
unbindAddress(accessApplicationDirectoryFrom(mAddress));
unbindApplication();
mAddress = newValue[0];
if (mAddress != kTTAdrsEmpty) {
// default attribute to bind is value
if (mAddress.getAttribute() == NO_ATTRIBUTE)
mAddress = mAddress.appendAttribute(kTTSym_value);
return bindAddress(accessApplicationDirectoryFrom(mAddress));
}
return kTTErrGeneric;
}
#if 0
#pragma mark -
#pragma mark Some Methods
#endif
TTErr TTSender::Send(TTValue& valueToSend, TTValue& outputValue)
{
TTObject anObject;
TTValue aCacheElement, v, c, none;
TTAttributePtr anAttribute;
TTSymbol ttAttributeName;
TTMessagePtr aMessage;
TTAddress relativeAddress;
TTErr err = kTTErrNone;
if (!accessApplicationDirectoryFrom(mAddress) || mAddress == kTTAdrsEmpty)
return kTTErrGeneric;
if (!mIsSending) {
// lock
mIsSending = true;
if (!mObjectCache->isEmpty()) {
ttAttributeName = ToTTName(mAddress.getAttribute());
// send data to each node of the selection
for (mObjectCache->begin(); mObjectCache->end(); mObjectCache->next()) {
aCacheElement = mObjectCache->current();
// then his object
anObject = aCacheElement[0];
if (anObject.valid()) {
// DATA CASE for value attribute
if (anObject.name() == kTTSym_Data && ttAttributeName == kTTSym_value) {
// set the value attribute using a command
anObject.send(kTTSym_Command, valueToSend);
}
// CONTAINER CASE for value attribute
else if (anObject.name() == kTTSym_Container && ttAttributeName == kTTSym_value) {
if (valueToSend.size() >= 1 ) {
if (valueToSend[0].type() == kTypeSymbol) {
relativeAddress = valueToSend[0];
c.copyFrom(valueToSend, 1);
v = TTValue(relativeAddress);
v.append((TTPtr*)&c);
// send the value
anObject.send(kTTSym_Send, v);
}
else
err = kTTErrGeneric;
}
else
err = kTTErrGeneric;
}
else if ((anObject.name() == kTTSym_Input || anObject.name() == kTTSym_InputAudio) && ttAttributeName == kTTSym_signal) {
// send the value
anObject.send(kTTSym_Send, valueToSend);
}
// DEFAULT CASE
// Look for attribute and set it
else if (!anObject.instance()->findAttribute(ttAttributeName, &anAttribute))
anObject.set(ttAttributeName, valueToSend);
// Or look for message and send it
else if (!anObject.instance()->findMessage(ttAttributeName, &aMessage))
anObject.send(ttAttributeName, valueToSend);
}
}
}
// unlock
mIsSending = false;
}
return err;
}
TTErr TTSender::bindAddress(TTNodeDirectoryPtr aDirectory)
{
TTNodePtr aNode;
TTObject anObject;
TTValue aCacheElement;
TTList aNodeList;
TTValue v, baton;
if (!aDirectory)
return bindApplication();
// 1. Look for the node(s) into the directory
aDirectory->Lookup(mAddress, aNodeList, &aNode);
// 2. make a cache containing each object
for (aNodeList.begin(); aNodeList.end(); aNodeList.next()) {
aNode = TTNodePtr((TTPtr)aNodeList.current()[0]);
anObject = aNode->getObject();
mObjectCache->append(anObject);
}
// 3. Observe any creation or destruction below the address
mAddressObserver = TTObject("callback");
mAddressObserver.set(kTTSym_baton, TTPtr(this)); // thรฉo -- we have to register our self as a #TTPtr to not reference this instance otherwhise the destructor will never be called
mAddressObserver.set(kTTSym_function, TTPtr(&TTSenderDirectoryCallback));
aDirectory->addObserverForNotifications(mAddress, mAddressObserver, 0); // ask for notification only for equal addresses
return kTTErrNone;
}
TTErr TTSender::unbindAddress(TTNodeDirectoryPtr aDirectory)
{
TTErr err = kTTErrNone;
if (mAddress != kTTAdrsEmpty) {
mObjectCache->clear();
// stop life cycle observation
if(mAddressObserver.valid() && aDirectory) {
err = aDirectory->removeObserverForNotifications(mAddress, mAddressObserver);
mAddressObserver = TTObject();
}
}
return kTTErrNone;
}
TTErr TTSender::bindApplication()
{
if (!mApplicationObserver.valid()) {
mApplicationObserver = TTObject("callback");
mApplicationObserver.set(kTTSym_baton, TTPtr(this)); // thรฉo -- we have to register our self as a #TTPtr to not reference this instance otherwhise the destructor will never be called
mApplicationObserver.set(kTTSym_function, TTPtr(&TTSenderApplicationManagerCallback));
return TTApplicationManagerAddApplicationObserver(mAddress.getDirectory(), mApplicationObserver);
}
return kTTErrGeneric;
}
TTErr TTSender::unbindApplication()
{
if (mApplicationObserver.valid()) {
TTApplicationManagerRemoveApplicationObserver(mAddress.getDirectory(), mApplicationObserver);
mApplicationObserver = TTObject();
}
return kTTErrNone;
}
TTErr TTSenderDirectoryCallback(const TTValue& baton, const TTValue& data)
{
TTValue aCacheElement;
TTSenderPtr aSender;
TTNodePtr aNode;
TTObject anObject, aCacheObject;
TTAddress anAddress;
TTValue v;
TTUInt8 flag;
// unpack baton (a #TTSenderPtr)
aSender = TTSenderPtr((TTPtr)baton[0]); // thรฉo -- we have to register our self as a #TTPtr to not reference this instance otherwhise the destructor will never be called
// Unpack data (address, aNode, flag, anObserver)
anAddress = data[0];
aNode = TTNodePtr((TTPtr)data[1]);
flag = data[2];
switch (flag) {
case kAddressCreated :
{
anObject = aNode->getObject();
if (anObject.valid())
aSender->mObjectCache->appendUnique(anObject);
break;
}
case kAddressDestroyed :
{
anObject = aNode->getObject();
// find the object in the cache and remove it
for (aSender->mObjectCache->begin(); aSender->mObjectCache->end(); aSender->mObjectCache->next()) {
// get a node
aCacheObject = aSender->mObjectCache->current()[0];
if (aCacheObject == anObject) {
aSender->mObjectCache->remove(aSender->mObjectCache->current());
break;
}
}
break;
}
default:
break;
}
return kTTErrNone;
}
TTErr TTSenderApplicationManagerCallback(const TTValue& baton, const TTValue& data)
{
TTSenderPtr aSender;
TTSymbol anApplicationName;
TTObject anApplication;
TTValue v;
TTUInt8 flag;
// unpack baton (a #TTSenderPtr)
aSender = TTSenderPtr((TTPtr)baton[0]); // thรฉo -- we have to register our self as a #TTPtr to not reference this instance otherwhise the destructor will never be called
// Unpack data (applicationName, application, flag, observer)
anApplicationName = data[0];
anApplication = data[1];
flag = data[2];
switch (flag) {
case kApplicationInstantiated :
{
aSender->bindAddress(accessApplicationDirectoryFrom(aSender->mAddress));
break;
}
case kApplicationProtocolStarted :
{
break;
}
case kApplicationProtocolStopped :
{
break;
}
case kApplicationReleased :
{
aSender->unbindAddress(accessApplicationDirectoryFrom(aSender->mAddress));
break;
}
default:
break;
}
return kTTErrNone;
}
| 25.65
| 184
| 0.660819
|
jamoma
|
7e33517c5581bc6b16746c399585ef984c5053f2
| 222
|
hpp
|
C++
|
AppGodRays/src/SunComponent.hpp
|
jaafersheriff/Neo-Engine
|
526e83829761322ccf09e661efa825b028426fa5
|
[
"MIT"
] | 6
|
2017-10-17T17:54:42.000Z
|
2022-02-13T09:43:02.000Z
|
AppGodRays/src/SunComponent.hpp
|
jaafersheriff/Neo-Engine
|
526e83829761322ccf09e661efa825b028426fa5
|
[
"MIT"
] | 1
|
2020-04-11T10:37:41.000Z
|
2021-11-15T21:03:32.000Z
|
AppGodRays/src/SunComponent.hpp
|
jaafersheriff/Neo-Engine
|
526e83829761322ccf09e661efa825b028426fa5
|
[
"MIT"
] | 4
|
2017-09-08T05:56:51.000Z
|
2021-02-03T15:16:41.000Z
|
#pragma once
#include "ECS/Component/Component.hpp"
#include "ECS/GameObject.hpp"
using namespace neo;
class SunComponent : public Component {
public:
SunComponent(GameObject *go) :
Component(go)
{}
};
| 14.8
| 39
| 0.693694
|
jaafersheriff
|
ccdefca83f34579e9b5d91a7cccb4c7273914886
| 2,404
|
cpp
|
C++
|
src/main.cpp
|
darkhunterbg/hypershot
|
87e063261ba95b0dfa5c9321691497bdc9e82f87
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
darkhunterbg/hypershot
|
87e063261ba95b0dfa5c9321691497bdc9e82f87
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
darkhunterbg/hypershot
|
87e063261ba95b0dfa5c9321691497bdc9e82f87
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include <string>
#include "win32.h"
#include "MemoryService.h"
#include "GameLoop.h"
#include "HiResTimer.h"
LRESULT CALLBACK WinProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void OnAssertFailed(const std::string& msg);
void ShowGameWindow(const wchar_t* msg, HINSTANCE hInstance, int nCmdShow);
int CALLBACK WinMain(IN HINSTANCE hInstance, IN HINSTANCE hPrevInstance, IN LPSTR lcCmdLine, IN int nCmdShow)
{
debug::__onAssertFailed = OnAssertFailed;
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
MemoryService service(sysInfo.dwPageSize);
ShowGameWindow(L"HyperShot", hInstance, nCmdShow);
MSG msg = { 0 };
GameLoop gameLoop;
HiResTimer timer;
while (true)
{
//Message pump - process windows messages before letting game run it's own logic
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (msg.message == WM_QUIT)
break;
double seconds = timer.Update().ToSeconds();
timer.Reset();
}
return msg.wParam;
}
LRESULT CALLBACK WinProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
} break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
void ShowGameWindow(const wchar_t* msg, HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WinProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = L"WindowClass1";
RegisterClassEx(&wc);
hWnd = CreateWindowEx(0,
L"WindowClass1", // name of the window class
msg, // title of the window
WS_OVERLAPPEDWINDOW, // window style
CW_USEDEFAULT, // x-position of the window
CW_USEDEFAULT, // y-position of the window
1024, // width of the window
768, // height of the window
nullptr, // we have no parent window, NULL
nullptr, // we aren't using menus, NULL
hInstance, // application handle
nullptr); // used with multiple windows, NULL
if (!hWnd)
{
ASSERT(false, "Failed to create window! '%s'.", GetLastErrorString());
}
ShowWindow(hWnd, nCmdShow);
}
void OnAssertFailed(const std::string& msg)
{
OutputDebugStringA(msg.c_str());
}
| 21.274336
| 109
| 0.708819
|
darkhunterbg
|
cce3801d7f9a5ae5fc83a1a80b0f6a78a2c7a54d
| 13,277
|
cpp
|
C++
|
CHAPTER14/sources.cpp
|
lrpinnto/stroustrup-exercises
|
a471a0d7b49b51b7c26e005ff9e66f3f6db199dd
|
[
"MIT"
] | null | null | null |
CHAPTER14/sources.cpp
|
lrpinnto/stroustrup-exercises
|
a471a0d7b49b51b7c26e005ff9e66f3f6db199dd
|
[
"MIT"
] | null | null | null |
CHAPTER14/sources.cpp
|
lrpinnto/stroustrup-exercises
|
a471a0d7b49b51b7c26e005ff9e66f3f6db199dd
|
[
"MIT"
] | null | null | null |
//g++ -w -Wall -std=c++11 ../sourcesgui/Graph.cpp ../sourcesgui/Window.cpp ../sourcesgui/GUI.cpp '../sourcesgui/Simple_window.cpp' ../CHAPTER13/sources.cpp sources.cpp C14E01.cpp `fltk-config --ldflags --use-images` -o C14E01
#include "./sources.h"
//EX 05
void Striped_rectangle::draw_lines() const
{
if (fill_color().visibility()) { // fill
fl_color(fill_color().as_int());
fl_line_style(0,0); //Line_style affects this type of fill. Override it. these are default line values. Which we want for filling
for (int i = 2; i < Rectangle::height(); i+=2)
{
fl_line(Rectangle::point(0).x, Rectangle::point(0).y + i, Rectangle::point(0).x + Rectangle::width() -1, Rectangle::point(0).y + i);
}
fl_color(color().as_int()); // reset color
fl_line_style(Rectangle::style().style(),Rectangle::style().width()); //reset linestyle
}
if (color().visibility()) { // edge on top of fill
fl_color(color().as_int());
fl_rect(point(0).x,point(0).y,Rectangle::width(),Rectangle::height());
}
}
//EX 05----
//EX 06
int mod(int x)
{
if (x<0) return -1*x;
else return x;
}
void Striped_circle::draw_lines() const
{
if (fill_color().visibility()) { // fill
fl_color(fill_color().as_int());
fl_line_style(0,0); //Line_style affects this type of fill. Override it. these are default line values. Which we want for filling
double angle;
int horizontal_length;
int opposite_leg;
for (int i = Circle::center().y-Circle::radius(); i < Circle::center().y+Circle::radius(); i+=2)
{
//arc sin (Opposite leg / Hipotenuse) = angle (we know the opposite leg because we increment y from top to bottom)
//Hipotenuse * cos (angle) = Horizontal length or adjacent leg
opposite_leg = mod(Circle::center().y-i);
angle = asin(opposite_leg/(Circle::radius()*1.0));
horizontal_length = round(Circle::radius() * cos(angle));
fl_line(Circle::center().x-horizontal_length,i,Circle::center().x+horizontal_length-1,i);
}
fl_color(color().as_int()); // reset color
fl_line_style(Circle::style().style(),Circle::style().width()); //reset linestyle
}
if (color().visibility()) {
fl_color(color().as_int());
fl_arc(point(0).x,point(0).y,Circle::radius()+Circle::radius(),Circle::radius()+Circle::radius(),0,360);
}
}
//EX 06----
//EX 07
// does two lines (p1,p2) and (p3,p4) intersect?
// if se return the distance of the intersect point as distances from p1
inline pair<double,double> line_intersect(Point p1, Point p2, Point p3, Point p4, bool& parallel)
{
double x1 = p1.x;
double x2 = p2.x;
double x3 = p3.x;
double x4 = p4.x;
double y1 = p1.y;
double y2 = p2.y;
double y3 = p3.y;
double y4 = p4.y;
double denom = ((y4 - y3)*(x2-x1) - (x4-x3)*(y2-y1));
if (denom == 0){
parallel= true;
return pair<double,double>(0,0);
}
parallel = false;
return pair<double,double>( ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3))/denom,
((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3))/denom);
}
//intersection between two line segments
//Returns true if the two segments intersect,
//in which case intersection is set to the point of intersection
inline bool line_segment_intersect(Point p1, Point p2, Point p3, Point p4, Point& intersection){
bool parallel;
pair<double,double> u = line_intersect(p1,p2,p3,p4,parallel);
if (parallel || u.first < 0 || u.first > 1 || u.second < 0 || u.second > 1) return false;
intersection.x = p1.x + u.first*(p2.x - p1.x);
intersection.y = p1.y + u.first*(p2.y - p1.y);
return true;
}
void Striped_closed_polyline::draw_lines() const
{
//Create limiting square/rectangle
int x_min {point(0).x};
int x_max {0};
int y_min {point(0).y};
int y_max {0};
for (int i = 0; i < number_of_points(); i++)
{
if(point(i).x<x_min) x_min=point(i).x;
if(point(i).y<y_min) y_min=point(i).y;
if(point(i).x>x_max) x_max=point(i).x;
if(point(i).y>y_max) y_max=point(i).y;
}
if (fill_color().visibility()) { // fill
fl_color(fill_color().as_int());
fl_line_style(0,0); //Line_style affects this type of fill. Override it. these are default line values. Which we want for filling
//check for intersects, one line at the time. get the list of intersection points and draw lines accordingly
//do this every 2 vertical lines
Point intersection;
vector<Point>intersections;
for (int i = y_min + 2; i < y_max; i+=2)
{
//check which pairs of points intersect then y axis on the given i (doing this out of efficency, maybe it's not the best way?)
vector<pair<Point,Point>> pairs_of_points; //A vector of pairs of points. In this context, that intersect the given i or y axis
if (point(number_of_points()-1).y < i && i <= point(0).y || point(0).y < i && i <= point(number_of_points()-1).y ) //do last pair, first
{
pairs_of_points.push_back({point(number_of_points()-1),point(0)});
}
for (int index = 0; index < number_of_points()-1; index++)
{
if( point(index).y < i && i <= point(index +1 ).y || point(index+1).y < i && i <= point(index ).y )
{
pairs_of_points.push_back({point(index),point(index+1)});
}
}
if(pairs_of_points.size()==1) pairs_of_points.clear();
for(pair<Point,Point> point_pair : pairs_of_points)
{
if(line_segment_intersect(Point(point_pair.first.x,i),Point(point_pair.second.x,i),point_pair.first,point_pair.second,intersection))
intersections.push_back(intersection);
}
pairs_of_points.clear();
for (int index = 0; index < intersections.size(); index+=2)
{
fl_line(intersections[index].x,intersections[index].y,intersections[index+1].x,intersections[index+1].y);
}
intersections.clear();
}
fl_color(color().as_int()); // reset color
fl_line_style(Closed_polyline::style().style(),Closed_polyline::style().width()); //reset linestyle
}
if (color().visibility())
Shape::draw_lines(); //need to use Shape's draw in order to avoid the Closed_polyline filling the shape
fl_line(point(number_of_points()-1).x,point(number_of_points()-1).y,point(0).x,point(0).y);// draw closing line:
}
//EX 07----
//EX 08
Octagon::Octagon(Point p, int rr, int anglee) //anglee in degrees
: r{rr}, ref_angle{anglee*PI/180.0}, center_point(p)
{
if(r<2) error("small radius on Octagon()"); //find minimum radius that forms a Octagon
const int N {8};
double smallest_rad_division = 2*PI/N; //dividing full circle into N amount of points
for (int i = 0; i < N; i++) //go through all rad angles of the full circle
{
double radangle = smallest_rad_division * i + ref_angle;
Polygon::add(Point{sin(radangle)*r+p.x,cos(radangle)*r+p.y});
}
}
void Octagon::draw_lines() const
{
Polygon::draw_lines();
}
//EX 08----
//EX 09
Group::Group(Vector_ref<Shape>&sp)
{
for (int i = 0; i < sp.size(); i++)
{
add(sp[i]);
}
}
void Group::draw_lines() const
{
for (int i = 0; i < vr.size(); i++)
{
vr[i].draw();
}
}
void Group::set_color(Color col)
{
for (int i = 0; i < vr.size(); i++)
{
vr[i].set_color(col);
}
}
void Group::set_fill_color(Color col)
{
for (int i = 0; i < vr.size(); i++)
{
vr[i].set_fill_color(col);
}
}
void Group::set_style(Line_style sty)
{
for (int i = 0; i < vr.size() ; i++)
{
vr[i].set_style(sty);
}
}
void Group::move(int dx, int dy)
{
for (int i = 0; i < vr.size(); i++)
{
vr[i].move(dx,dy);
}
}
void Group::move(int dx, int dy, int index) {vr[index].move(dx,dy);}
//EX 09----
//EX 10
void Resizeable_rectangle::draw_lines() const
{
if (fill_color().visibility()) { // fill
fl_color(fill_color().as_int());
fl_rectf(point(0).x,point(0).y,w,h);
fl_color(color().as_int()); // reset color
}
if (color().visibility()) { // edge on top of fill
fl_color(color().as_int());
fl_rect(point(0).x,point(0).y,w,h);
}
}
Pseudo_window::Pseudo_window(Point p, int widthh, int heigthh, string labell)
: Box(p,heigthh,widthh,10), label_text{labell}, top_bar{p,30,widthh,10}, top_bar2{{p.x,p.y+15},widthh,20},
exit_sym{{p.x+widthh-18,p.y+23},"X"}, text_top{{p.x+widthh/2,p.y+19},label_text}, square_sym{{p.x+widthh-32,p.y+23},"#"},
minimize_sym{{p.x+widthh-47,p.y+23},"-"}
{
top_bar.set_fill_color(Color::blue);
top_bar2.set_fill_color(Color::blue);
top_bar2.set_color(Color::invisible);
exit_sym.set_font(Graph_lib::Font::courier_bold);
exit_sym.set_font_size(20);
square_sym.set_font(Graph_lib::Font::courier_bold);
square_sym.set_font_size(20);
minimize_sym.set_font(Graph_lib::Font::courier_bold);
minimize_sym.set_font_size(20);
}
void Pseudo_window::set_width(int w)
{
exit_sym.move(-Box::get_width()+w,0);
square_sym.move(-Box::get_width()+w,0);
minimize_sym.move(-Box::get_width()+w,0);
text_top.move(-Box::get_width()+w,0); //Bug causes move() to create a negative position. Couldn't afford to spend more time on it
Box::set_width(w);
top_bar.set_width(w);
top_bar2.set_width(w);
}
void Pseudo_window::draw_lines() const
{
for (int i = 0; i < vr.size(); i++) //draws attachments to pseudo_window
{
vr[i].draw();
}
Box::draw_lines();
top_bar.draw_lines();
top_bar2.draw_lines();
exit_sym.draw_lines();
square_sym.draw_lines();
minimize_sym.draw_lines();
text_top.draw_lines();
}
//EX 10---
//EX 11
Binary_tree::Binary_tree(int levelss) //levels==0 means no nodes, levels==1 means one node, levels==2 means one top node with two sub-nodes, level==3 follows same logic
: levels{levelss}
{
int r {50};
int x_size {(16/19.2)*x_max()}; //assuming 16:9 display. scalling down a notch. weird division represents screen ratio
int y_size {(9/10.8)*y_max()};
//add() add center point to shape?
if (levels==0);
else
{
int number_of_nodes {1};
vector<int>nodes_per_index(1);
nodes_per_index.push_back(1);
for (int i = 2; i <= levels; i++)
{
number_of_nodes*=2;
nodes_per_index.push_back(number_of_nodes);
}
int y_division {y_size/levels};
int x_division ;
while(2*r*nodes_per_index[nodes_per_index.size()-1]>x_size) r/=2; //half node size if horizontal screen fill overflows
for (int i = 1; i <= levels; i++)
{
for(int j = 1 ; j<=nodes_per_index[i]; j++)
{
x_division = x_size/(nodes_per_index[i]+1);
Point center_node
{
x_division*j,
y_division*(i-1)+r
};
nodes.push_back(new Circle{center_node,r});
nodes[nodes.size()-1].set_fill_color(Color::green);
}
}
for (int i = 1; i < nodes.size(); i++)
{
connectors.push_back(new Arrow{
s(nodes[(i-1)/2]),
n(nodes[i])
});
}
}
}
void Binary_tree::move(int dx, int dy)
{
for (int i = 0; i < nodes.size(); i++)
{
nodes[i].move(dx,dy);
}
for (int i = 0; i < connectors.size(); i++)
{
connectors[i].move(dx,dy);
}
}
void Binary_tree::set_fill_color(Color col)
{
fillcolor = col;
for (int i = 0; i < nodes.size(); i++)
{
nodes[i].set_fill_color(fillcolor);
}
}
void Binary_tree::set_color(Color col)
{
llcolor = col;
for (int i = 0; i < connectors.size(); i++)
{
connectors[i].set_color(llcolor);
}
}
void Binary_tree::set_style(Line_style sty)
{
lls = sty;
for (int i = 0; i < connectors.size(); i++)
{
connectors[i].set_style(lls);
}
}
void Binary_tree::draw_lines() const
{
for(int i = 0 ; i < nodes.size() ; i++)
nodes[i].draw_lines();
for(int i = 0 ; i < connectors.size() ; i++)
connectors[i].draw_lines();
}
//EX 11---
//EX 16
void Control_shape::on() {status=true; shape1.set_color(level);}
void Control_shape::off() {status=false; shape1.set_color(Color::invisible);}
void Control_shape::set_level_style(int l)
{
level_style=l;
if(level_style<0 || level_style>4) error("set_level_style() need to be between 0 and 4");
shape1.set_style(level_style);
}
void Control_shape::set_level(int l)
{
level=l;
if(level<0 || level>255) error("set_level() need to be between 0 and 255");
shape1.set_color(level);
}
void Control_shape::set_level(Color c)
{
level=c.as_int();
shape1.set_color(c);
}
Control_shape::Control_shape(Shape& shapee)
: shape1{shapee}
{
if(shape1.color().visibility() == 0) //check if invisible
{
status=false;
}
else status=true;
level=shape1.color().as_int();
level_style=shape1.style().style();
}
//EX 16--
| 31.462085
| 226
| 0.599307
|
lrpinnto
|
cce99baf58d084edeece5f26bb23fa662b22a12c
| 10,239
|
cpp
|
C++
|
CGEditor/src/EditorLayer.cpp
|
chen1180/CG-SandBox
|
59473fe44fb515f4e79479070c924de7e0e2c760
|
[
"MIT"
] | null | null | null |
CGEditor/src/EditorLayer.cpp
|
chen1180/CG-SandBox
|
59473fe44fb515f4e79479070c924de7e0e2c760
|
[
"MIT"
] | null | null | null |
CGEditor/src/EditorLayer.cpp
|
chen1180/CG-SandBox
|
59473fe44fb515f4e79479070c924de7e0e2c760
|
[
"MIT"
] | null | null | null |
#include "EditorLayer.h"
#include"glad/glad.h"
#include"glm/glm.hpp"
#include"glm/gtc/matrix_transform.hpp"
#include"platform/opengl/OpenGLFrameBuffer.h"
namespace CGCore {
void EditorLayer::OnAttach()
{
CG_CLIENT_INFO("App layer attached");
m_Shader = Shader::Create(std::string("../assets/shader/Debug_cube.vert.glsl"), std::string("../assets/shader/Debug_cube.frag.glsl"));
m_DepthShader= Shader::Create(std::string("../assets/shader/Debug_depth.vert.glsl"), std::string("../assets/shader/Debug_depth.frag.glsl"));
auto width=(float)Application::Get().GetWindow().GetWidth();
auto height= (float)Application::Get().GetWindow().GetHeight();
m_Camera = CreateRef<Camera> ( 60.0f, 0.1f, 100.0f, width / height);
m_Camera->SetCameraControllerType(ControllerType::MayaCamera);
m_PhongRenderer = PhongRenderer();
m_PhongRenderer.Init();
m_Scene = CreateRef<Scene>();
auto cameraEntity=m_Scene->CreateEntity("Camera");
cameraEntity.AddComponent<CameraComponent>(m_Camera,true);
auto cube = ModelLoader::LoadModel("../assets/mesh/cube.obj", m_Scene.get());
auto& transform1 = cube.GetComponent<TransformComponent>();
transform1.SetWorldMatrix(glm::translate(glm::mat4(1.0f), glm::vec3(0.0,1.0, 2.0)));
auto meshEntity = m_Scene->CreateEntity();
auto transform = TransformComponent();
transform.SetWorldMatrix(glm::translate(glm::mat4(1.0f), glm::vec3(0.0, -5.0,0.0))*glm::scale(glm::mat4(1.0f),glm::vec3(5.0f,5.0f,5.0f)));
meshEntity.AddComponent<TransformComponent>(transform);
meshEntity.AddComponent<MeshComponent>(cube.GetComponent<MeshComponent>());
/*for (int i = 0;i < 10;i++) {
for (int j = 0;j < 10;j++) {
auto meshEntity = m_Scene->CreateEntity();
auto transform = TransformComponent();
transform.SetWorldMatrix(glm::translate(glm::mat4(1.0f), glm::vec3( i*2.5, 0.0, j * 3.5f)));
meshEntity.AddComponent<TransformComponent>(transform);
meshEntity.AddComponent<MeshComponent>(cube.GetComponent<MeshComponent>());
}
}*/
auto sphere= ModelLoader::LoadModel("../assets/mesh/sphere.obj", m_Scene.get());
auto& transform2 = sphere.GetComponent<TransformComponent>();
transform2.SetWorldMatrix(glm::translate(glm::mat4(1.0f), glm::vec3(-2.0, 1.0, -1.0)));
auto planeEntt = m_Scene->CreateEntity();
Ref<Mesh> plane = MeshFactory::CreateQuad(-0.5,1.5,5.0,5.0);
planeEntt.AddComponent<MeshComponent>(plane);
planeEntt.AddComponent<TransformComponent>();
auto& transform3 = planeEntt.GetComponent<TransformComponent>();
//transform3.SetLocalScale(glm::vec3(10.0, 10.0, 1.0));
transform3.SetWorldMatrix(glm::translate(glm::mat4(1.0f), glm::vec3(0.0, 0.5, 0.0)) * glm::rotate(glm::mat4(1.0),glm::radians(90.0f),glm::vec3(1.0,0.0,0.0)));
//TODO: Add texture component
m_TextureCheckerBoard = Texture2D::Create("../assets/texture/Checkerboard.png");
m_TexturePig= Texture2D::Create("../assets/texture/Texture.jpg");
m_Light=m_Scene->CreateEntity("Light1");
m_Light.AddComponent<Light>(glm::vec4(-2.0f, 7.0f, -1.0f,0.0f), glm::vec4(0.0, 0.0, 0.0,0.0), glm::vec4(0.0, 1.0, 0.0, 1.0));
auto light2 = m_Scene->CreateEntity("Light2");
light2.AddComponent<Light>(glm::vec4(3.0f, 5.0f, 1.0f, 0.0f), glm::vec4(0.0, 0.0, 0.0, 0.0), glm::vec4(0.0, 0.0, 1.0, 1.0));
auto light3 = m_Scene->CreateEntity("Light3");
light3.AddComponent<Light>(glm::vec4(0.0f, 5.0f, 3.0f, 0.0f), glm::vec4(0.0, 0.0, 0.0, 0.0), glm::vec4(1.0, 0.0, 0.0, 1.0));
m_ScenePanel = CreateScope<SceneHierarchyPanel>(m_Scene);
}
void EditorLayer::OnDettach()
{
}
void EditorLayer::OnUpdate(float deltaTime)
{
framerate = deltaTime;
RenderCommand::Clear();
RenderCommand::ClearColor();
{
m_PhongRenderer.BeginScene(m_Scene.get());
m_PhongRenderer.EndScene();
}
m_PhongRenderer.GetFrameBuffer()->Unbind();
}
void EditorLayer::OnImGuiRender()
{
static bool showWindow = true;
static bool opt_fullscreen_persistant = true;
bool opt_fullscreen = opt_fullscreen_persistant;
static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
// We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into,
// because it would be confusing to have two docking targets within each others.
ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
if (opt_fullscreen)
{
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->GetWorkPos());
ImGui::SetNextWindowSize(viewport->GetWorkSize());
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
}
// When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background
// and handle the pass-thru hole, so we ask Begin() to not render a background.
if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
window_flags |= ImGuiWindowFlags_NoBackground;
// Important: note that we proceed even if Begin() returns false (aka window is collapsed).
// This is because we want to keep our DockSpace() active. If a DockSpace() is inactive,
// all active windows docked into it will lose their parent and become undocked.
// We cannot preserve the docking relationship between an active window and an inactive docking, otherwise
// any change of dockspace/settings would lead to windows being stuck in limbo and never being visible.
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace Demo", &showWindow, window_flags);
ImGui::PopStyleVar();
if (opt_fullscreen)
ImGui::PopStyleVar(2);
// DockSpace
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)
{
ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
}
else
{
ImGuiIO& io = ImGui::GetIO();
ImGui::Text("ERROR: Docking is not enabled! See Demo > Configuration.");
ImGui::Text("Set io.ConfigFlags |= ImGuiConfigFlags_DockingEnable in your code, or ");
ImGui::SameLine(0.0f, 0.0f);
if (ImGui::SmallButton("click here"))
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
}
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("Docking"))
{
// Disabling fullscreen would allow the window to be moved to the front of other windows,
// which we can't undo at the moment without finer window depth/z control.
//ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant);
if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoSplit;
if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoResize;
if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode;
if (ImGui::MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode;
if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar;
ImGui::Separator();
if (ImGui::MenuItem("Close DockSpace", NULL, false, &showWindow != NULL))
showWindow = false;
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::End();
m_ScenePanel->OnImGuiRender();
ImGui::Begin("New session");
ImGui::Separator();
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Separator();
ImGui::Checkbox("Imgui Demo", &m_ShowImguiDemo);
ImVec2 viewportSize = ImGui::GetContentRegionAvail();
for (int i = 0;i < ShadowRenderer::GetShadowMap().size();i++) {
ImGui::Separator();
auto texture = ShadowRenderer::GetShadowMap()[i]->GetDepthAttachment();
ImGui::Image((void*)texture->GetID(), ImVec2(400,300), ImVec2(0, 1), ImVec2(1, 0));
}
if (m_ShowImguiDemo)
ImGui::ShowDemoWindow(&m_ShowImguiDemo);
ImGui::End();
Renderer2D::OnImguiRender();
m_PhongRenderer.OnImguiRender();
ImGui::Begin("GameWindow");
{
// Using a Child allow to fill all the space of the window.
// It also alows customization
ImGui::BeginChild("GameRender");
//Camera
if (ImGui::IsWindowHovered()) {
//TODO: move the following functions into event.
m_Camera->GetController()->HandleKeyboard(m_Camera.get(), framerate);
m_Camera->GetController()->HandleMouse(m_Camera.get(), framerate, Input::GetMousePosition().first, Input::GetMousePosition().second);
}
// Get the size of the child (i.e. the whole draw size of the windows).
ImVec2 wsize = ImGui::GetWindowSize();
// Because I use the texture from OpenGL, I need to invert the V from the UV.
glm::vec2 m_FrameBufferSize = { m_PhongRenderer.GetFrameBuffer()->GetSpecification().Width, m_PhongRenderer.GetFrameBuffer()->GetSpecification().Height };
if (m_FrameBufferSize != *(glm::vec2*) & wsize) {
CG_CLIENT_INFO("Viewport size: {0} ,{1}", wsize.x, wsize.y);
m_PhongRenderer.GetFrameBuffer()->Resize(wsize.x, wsize.y);
ShadowRenderer::Resize(wsize.x, wsize.y);
m_Camera->SetAspectRatio(wsize.x / wsize.y);
}
auto texture = static_cast<OpenGLFrameBuffer*>(m_PhongRenderer.GetFrameBuffer().get());
ImGui::Image((void*)texture->GetColor(), wsize, ImVec2(0, 1), ImVec2(1, 0));
ImGui::EndChild();
}
ImGui::End();
}
void EditorLayer::OnEvent(Event& e) {
//TODO: move this snippet of code to Camera controller class
//update camera resize
if (e.GetEventType() == CGCore::EventType::WindowResize) {
CGCore::WindowResizeEvent& event = (CGCore::WindowResizeEvent&) e;
}
}
}
| 44.907895
| 191
| 0.714425
|
chen1180
|
cced4c7f6d05a204b4460f834dd64ddcbc97b158
| 14,445
|
cpp
|
C++
|
MultiComposite/VRClient-Stub/VirtualInput.cpp
|
DrPotatoNet/MultiComposite
|
d71e065661a55b22bfcec8b162859e4fbec18782
|
[
"MIT"
] | 2
|
2020-09-06T08:14:15.000Z
|
2020-09-06T19:03:12.000Z
|
MultiComposite/VRClient-Stub/VirtualInput.cpp
|
Bluscream/MultiComposite
|
eac46d3fc7167629181b0652087cb6c2ab12747a
|
[
"MIT"
] | 4
|
2020-09-07T09:50:31.000Z
|
2020-09-30T05:16:31.000Z
|
MultiComposite/VRClient-Stub/VirtualInput.cpp
|
Bluscream/MultiComposite
|
eac46d3fc7167629181b0652087cb6c2ab12747a
|
[
"MIT"
] | 1
|
2020-09-29T20:57:15.000Z
|
2020-09-29T20:57:15.000Z
|
#include "VirtualInput.h"
#include "VRClient.h"
#include "Logger.h"
vr::EVRInputError VirtualInput::SetActionManifestPath(const char* pchActionManifestPath)
{
dlog::Println("[VirtualInput::SetActionManifestPath] Called.");
return static_cast<IVRInput_010*>(steamInput)->SetActionManifestPath(pchActionManifestPath);
}
vr::EVRInputError VirtualInput::GetActionSetHandle(const char* pchActionSetName, vr::VRActionSetHandle_t* pHandle)
{
return static_cast<IVRInput_010*>(steamInput)->GetActionSetHandle(pchActionSetName, pHandle);
}
vr::EVRInputError VirtualInput::GetActionHandle(const char* pchActionName, vr::VRActionHandle_t* pHandle)
{
return static_cast<IVRInput_010*>(steamInput)->GetActionHandle(pchActionName, pHandle);
}
vr::EVRInputError VirtualInput::GetInputSourceHandle(const char* pchInputSourcePath, vr::VRInputValueHandle_t* pHandle)
{
return static_cast<IVRInput_010*>(steamInput)->GetInputSourceHandle(pchInputSourcePath, pHandle);
}
vr::EVRInputError VirtualInput::UpdateActionState(VR_ARRAY_COUNT(unSetCount)vr::VRActiveActionSet_t* pSets, uint32_t unSizeOfVRSelectedActionSet_t, uint32_t unSetCount)
{
// Check Perms
if ((VRClient::cInstance->pRuntime->permissions & ApplicationPermissions_ReceivesInputs) != ApplicationPermissions_ReceivesInputs)
return VRInputError_None;
return static_cast<IVRInput_010*>(steamInput)->UpdateActionState(pSets, unSizeOfVRSelectedActionSet_t, unSetCount);
}
vr::EVRInputError VirtualInput::GetDigitalActionData(vr::VRActionHandle_t action, vr::InputDigitalActionData_t* pActionData, uint32_t unActionDataSize, vr::VRInputValueHandle_t ulRestrictToDevice)
{
// Check Perms
if ((VRClient::cInstance->pRuntime->permissions & ApplicationPermissions_ReceivesInputs) != ApplicationPermissions_ReceivesInputs)
return VRInputError_None;
return static_cast<IVRInput_010*>(steamInput)->GetDigitalActionData(action, pActionData, unActionDataSize, ulRestrictToDevice);
}
vr::EVRInputError VirtualInput::GetAnalogActionData(vr::VRActionHandle_t action, vr::InputAnalogActionData_t* pActionData, uint32_t unActionDataSize, vr::VRInputValueHandle_t ulRestrictToDevice)
{
// Check Perms
if ((VRClient::cInstance->pRuntime->permissions & ApplicationPermissions_ReceivesInputs) != ApplicationPermissions_ReceivesInputs)
return VRInputError_None;
return static_cast<IVRInput_010*>(steamInput)->GetAnalogActionData(action, pActionData, unActionDataSize, ulRestrictToDevice);
}
vr::EVRInputError VirtualInput::GetPoseActionData(vr::VRActionHandle_t action, vr::ETrackingUniverseOrigin eOrigin, float fPredictedSecondsFromNow, vr::InputPoseActionData_t* pActionData, uint32_t unActionDataSize, vr::VRInputValueHandle_t ulRestrictToDevice)
{
// Check Perms
if ((VRClient::cInstance->pRuntime->permissions & ApplicationPermissions_ReceivesPoses) != ApplicationPermissions_ReceivesPoses)
return VRInputError_None;
return static_cast<IVRInput_005*>(steamInput)->GetPoseActionData(action, eOrigin, fPredictedSecondsFromNow, pActionData, unActionDataSize, ulRestrictToDevice);
}
vr::EVRInputError VirtualInput::GetPoseActionDataRelativeToNow(vr::VRActionHandle_t action, vr::ETrackingUniverseOrigin eOrigin, float fPredictedSecondsFromNow, vr::InputPoseActionData_t* pActionData, uint32_t unActionDataSize, vr::VRInputValueHandle_t ulRestrictToDevice)
{
// Check Perms
if ((VRClient::cInstance->pRuntime->permissions & ApplicationPermissions_ReceivesPoses) != ApplicationPermissions_ReceivesPoses)
return VRInputError_None;
return static_cast<IVRInput_010*>(steamInput)->GetPoseActionDataRelativeToNow(action, eOrigin, fPredictedSecondsFromNow, pActionData, unActionDataSize, ulRestrictToDevice);
}
vr::EVRInputError VirtualInput::GetPoseActionDataForNextFrame(vr::VRActionHandle_t action, vr::ETrackingUniverseOrigin eOrigin, vr::InputPoseActionData_t* pActionData, uint32_t unActionDataSize, vr::VRInputValueHandle_t ulRestrictToDevice)
{
// Check Perms
if ((VRClient::cInstance->pRuntime->permissions & ApplicationPermissions_ReceivesPoses) != ApplicationPermissions_ReceivesPoses)
return VRInputError_None;
return static_cast<IVRInput_010*>(steamInput)->GetPoseActionDataForNextFrame(action, eOrigin, pActionData, unActionDataSize, ulRestrictToDevice);
}
vr::EVRInputError VirtualInput::GetSkeletalActionData(vr::VRActionHandle_t action, vr::InputSkeletalActionData_t* pActionData, uint32_t unActionDataSize, vr::VRInputValueHandle_t ulRestrictToDevice)
{
// Check Perms
if ((VRClient::cInstance->pRuntime->permissions & ApplicationPermissions_ReceivesPoses) != ApplicationPermissions_ReceivesPoses)
return VRInputError_None;
return static_cast<IVRInput_004*>(steamInput)->GetSkeletalActionData(action, pActionData, unActionDataSize, ulRestrictToDevice);
}
vr::EVRInputError VirtualInput::GetSkeletalActionData(vr::VRActionHandle_t action, vr::InputSkeletalActionData_t* pActionData, uint32_t unActionDataSize)
{
// Check Perms
if ((VRClient::cInstance->pRuntime->permissions & ApplicationPermissions_ReceivesPoses) != ApplicationPermissions_ReceivesPoses)
return VRInputError_None;
return static_cast<IVRInput_010*>(steamInput)->GetSkeletalActionData(action, pActionData, unActionDataSize);
}
vr::EVRInputError VirtualInput::GetDominantHand(vr::ETrackedControllerRole* peDominantHand)
{
return static_cast<IVRInput_010*>(steamInput)->GetDominantHand(peDominantHand);
}
vr::EVRInputError VirtualInput::SetDominantHand(vr::ETrackedControllerRole eDominantHand)
{
return static_cast<IVRInput_010*>(steamInput)->SetDominantHand(eDominantHand);
}
vr::EVRInputError VirtualInput::GetBoneCount(vr::VRActionHandle_t action, uint32_t* pBoneCount)
{
return static_cast<IVRInput_010*>(steamInput)->GetBoneCount(action, pBoneCount);
}
vr::EVRInputError VirtualInput::GetBoneHierarchy(vr::VRActionHandle_t action, VR_ARRAY_COUNT(unIndexArayCount)vr::BoneIndex_t* pParentIndices, uint32_t unIndexArayCount)
{
return static_cast<IVRInput_010*>(steamInput)->GetBoneHierarchy(action, pParentIndices, unIndexArayCount);
}
vr::EVRInputError VirtualInput::GetBoneName(vr::VRActionHandle_t action, vr::BoneIndex_t nBoneIndex, VR_OUT_STRING() char* pchBoneName, uint32_t unNameBufferSize)
{
return static_cast<IVRInput_010*>(steamInput)->GetBoneName(action, nBoneIndex, pchBoneName, unNameBufferSize);
}
vr::EVRInputError VirtualInput::GetSkeletalReferenceTransforms(vr::VRActionHandle_t action, vr::EVRSkeletalTransformSpace eTransformSpace, vr::EVRSkeletalReferencePose eReferencePose, VR_ARRAY_COUNT(unTransformArrayCount)vr::VRBoneTransform_t* pTransformArray, uint32_t unTransformArrayCount)
{
return static_cast<IVRInput_010*>(steamInput)->GetSkeletalReferenceTransforms(action, eTransformSpace, eReferencePose, pTransformArray, unTransformArrayCount);
}
vr::EVRInputError VirtualInput::GetSkeletalTrackingLevel(vr::VRActionHandle_t action, vr::EVRSkeletalTrackingLevel* pSkeletalTrackingLevel)
{
return static_cast<IVRInput_010*>(steamInput)->GetSkeletalTrackingLevel(action, pSkeletalTrackingLevel);
}
vr::EVRInputError VirtualInput::GetSkeletalBoneData(vr::VRActionHandle_t action, vr::EVRSkeletalTransformSpace eTransformSpace, vr::EVRSkeletalMotionRange eMotionRange, VR_ARRAY_COUNT(unTransformArrayCount)vr::VRBoneTransform_t* pTransformArray, uint32_t unTransformArrayCount, vr::VRInputValueHandle_t ulRestrictToDevice)
{
// Check Perms
if ((VRClient::cInstance->pRuntime->permissions & ApplicationPermissions_ReceivesPoses) != ApplicationPermissions_ReceivesPoses)
return VRInputError_None;
return static_cast<IVRInput_010*>(steamInput)->GetSkeletalBoneData(action, eTransformSpace, eMotionRange, pTransformArray, unTransformArrayCount);
}
vr::EVRInputError VirtualInput::GetSkeletalBoneData(vr::VRActionHandle_t action, vr::EVRSkeletalTransformSpace eTransformSpace, vr::EVRSkeletalMotionRange eMotionRange, VR_ARRAY_COUNT(unTransformArrayCount)vr::VRBoneTransform_t* pTransformArray, uint32_t unTransformArrayCount)
{
// Check Perms
if ((VRClient::cInstance->pRuntime->permissions & ApplicationPermissions_ReceivesPoses) != ApplicationPermissions_ReceivesPoses)
return VRInputError_None;
return static_cast<IVRInput_010*>(steamInput)->GetSkeletalBoneData(action, eTransformSpace, eMotionRange, pTransformArray, unTransformArrayCount);
}
vr::EVRInputError VirtualInput::GetSkeletalSummaryData(vr::VRActionHandle_t action, vr::EVRSummaryType eSummaryType, vr::VRSkeletalSummaryData_t* pSkeletalSummaryData)
{
return static_cast<IVRInput_010*>(steamInput)->GetSkeletalSummaryData(action, eSummaryType, pSkeletalSummaryData);
}
vr::EVRInputError VirtualInput::GetSkeletalSummaryData(vr::VRActionHandle_t action, vr::VRSkeletalSummaryData_t* pSkeletalSummaryData)
{
return static_cast<IVRInput_005*>(steamInput)->GetSkeletalSummaryData(action, pSkeletalSummaryData);
}
vr::EVRInputError VirtualInput::GetSkeletalBoneDataCompressed(vr::VRActionHandle_t action, vr::EVRSkeletalTransformSpace eTransformSpace, vr::EVRSkeletalMotionRange eMotionRange, VR_OUT_BUFFER_COUNT(unCompressedSize) void* pvCompressedData, uint32_t unCompressedSize, uint32_t* punRequiredCompressedSize, vr::VRInputValueHandle_t ulRestrictToDevice)
{
return static_cast<IVRInput_004*>(steamInput)->GetSkeletalBoneDataCompressed(action, eTransformSpace, eMotionRange, pvCompressedData, unCompressedSize, punRequiredCompressedSize, ulRestrictToDevice);
}
vr::EVRInputError VirtualInput::GetSkeletalBoneDataCompressed(vr::VRActionHandle_t action, vr::EVRSkeletalMotionRange eMotionRange, VR_OUT_BUFFER_COUNT(unCompressedSize) void* pvCompressedData, uint32_t unCompressedSize, uint32_t* punRequiredCompressedSize)
{
return static_cast<IVRInput_010*>(steamInput)->GetSkeletalBoneDataCompressed(action, eMotionRange, pvCompressedData, unCompressedSize, punRequiredCompressedSize);
}
vr::EVRInputError VirtualInput::DecompressSkeletalBoneData(void* pvCompressedBuffer, uint32_t unCompressedBufferSize, vr::EVRSkeletalTransformSpace* peTransformSpace, VR_ARRAY_COUNT(unTransformArrayCount)vr::VRBoneTransform_t* pTransformArray, uint32_t unTransformArrayCount)
{
return static_cast<IVRInput_004*>(steamInput)->DecompressSkeletalBoneData(pvCompressedBuffer, unCompressedBufferSize, peTransformSpace, pTransformArray, unTransformArrayCount);
}
vr::EVRInputError VirtualInput::DecompressSkeletalBoneData(const void* pvCompressedBuffer, uint32_t unCompressedBufferSize, vr::EVRSkeletalTransformSpace eTransformSpace, VR_ARRAY_COUNT(unTransformArrayCount)vr::VRBoneTransform_t* pTransformArray, uint32_t unTransformArrayCount)
{
return static_cast<IVRInput_010*>(steamInput)->DecompressSkeletalBoneData(pvCompressedBuffer, unCompressedBufferSize, eTransformSpace, pTransformArray, unTransformArrayCount);
}
vr::EVRInputError VirtualInput::TriggerHapticVibrationAction(vr::VRActionHandle_t action, float fStartSecondsFromNow, float fDurationSeconds, float fFrequency, float fAmplitude, vr::VRInputValueHandle_t ulRestrictToDevice)
{
return static_cast<IVRInput_010*>(steamInput)->TriggerHapticVibrationAction(action, fStartSecondsFromNow, fDurationSeconds, fFrequency, fAmplitude, ulRestrictToDevice);
}
vr::EVRInputError VirtualInput::GetActionOrigins(vr::VRActionSetHandle_t actionSetHandle, vr::VRActionHandle_t digitalActionHandle, VR_ARRAY_COUNT(originOutCount)vr::VRInputValueHandle_t* originsOut, uint32_t originOutCount)
{
return static_cast<IVRInput_010*>(steamInput)->GetActionOrigins(actionSetHandle, digitalActionHandle, originsOut, originOutCount);
}
vr::EVRInputError VirtualInput::GetOriginLocalizedName(vr::VRInputValueHandle_t origin, VR_OUT_STRING() char* pchNameArray, uint32_t unNameArraySize)
{
return static_cast<IVRInput_004*>(steamInput)->GetOriginLocalizedName(origin, pchNameArray, unNameArraySize);
}
vr::EVRInputError VirtualInput::GetOriginLocalizedName(vr::VRInputValueHandle_t origin, VR_OUT_STRING() char* pchNameArray, uint32_t unNameArraySize, int32_t unStringSectionsToInclude)
{
return static_cast<IVRInput_010*>(steamInput)->GetOriginLocalizedName(origin, pchNameArray, unNameArraySize, unStringSectionsToInclude);
}
vr::EVRInputError VirtualInput::GetOriginTrackedDeviceInfo(vr::VRInputValueHandle_t origin, vr::InputOriginInfo_t* pOriginInfo, uint32_t unOriginInfoSize)
{
return static_cast<IVRInput_010*>(steamInput)->GetOriginTrackedDeviceInfo(origin, pOriginInfo, unOriginInfoSize);
}
vr::EVRInputError VirtualInput::GetActionBindingInfo(vr::VRActionHandle_t action, vr::InputBindingInfo_t* pOriginInfo, uint32_t unBindingInfoSize, uint32_t unBindingInfoCount, uint32_t* punReturnedBindingInfoCount)
{
return static_cast<IVRInput_010*>(steamInput)->GetActionBindingInfo(action, pOriginInfo, unBindingInfoSize, unBindingInfoCount, punReturnedBindingInfoCount);
}
vr::EVRInputError VirtualInput::ShowActionOrigins(vr::VRActionSetHandle_t actionSetHandle, vr::VRActionHandle_t ulActionHandle)
{
return static_cast<IVRInput_010*>(steamInput)->ShowActionOrigins(actionSetHandle, ulActionHandle);
}
vr::EVRInputError VirtualInput::ShowBindingsForActionSet(VR_ARRAY_COUNT(unSetCount)vr::VRActiveActionSet_t* pSets, uint32_t unSizeOfVRSelectedActionSet_t, uint32_t unSetCount, vr::VRInputValueHandle_t originToHighlight)
{
return static_cast<IVRInput_010*>(steamInput)->ShowBindingsForActionSet(pSets, unSizeOfVRSelectedActionSet_t, unSetCount, originToHighlight);
}
vr::EVRInputError VirtualInput::GetComponentStateForBinding(const char* pchRenderModelName, const char* pchComponentName, const vr::InputBindingInfo_t* pOriginInfo, uint32_t unBindingInfoSize, uint32_t unBindingInfoCount, vr::RenderModel_ComponentState_t* pComponentState)
{
return static_cast<IVRInput_010*>(steamInput)->GetComponentStateForBinding(pchRenderModelName, pchComponentName, pOriginInfo, unBindingInfoSize, unBindingInfoCount, pComponentState);
}
bool VirtualInput::IsUsingLegacyInput()
{
return static_cast<IVRInput_010*>(steamInput)->IsUsingLegacyInput();
}
vr::EVRInputError VirtualInput::OpenBindingUI(const char* pchAppKey, vr::VRActionSetHandle_t ulActionSetHandle, vr::VRInputValueHandle_t ulDeviceHandle, bool bShowOnDesktop)
{
return static_cast<IVRInput_010*>(steamInput)->OpenBindingUI(pchAppKey, ulActionSetHandle, ulDeviceHandle, bShowOnDesktop);
}
vr::EVRInputError VirtualInput::GetBindingVariant(vr::VRInputValueHandle_t ulDevicePath, char* pchVariantArray, uint32_t unVariantArraySize)
{
return static_cast<IVRInput_010*>(steamInput)->GetBindingVariant(ulDevicePath, pchVariantArray, unVariantArraySize);
}
| 59.937759
| 349
| 0.849152
|
DrPotatoNet
|
ccef87ea731620cf17b57865b213d1d8b0d1db92
| 4,431
|
cpp
|
C++
|
GControl/GControl/GControlDlg.cpp
|
GongZhihui/GControl
|
ed2076e3dd025760e5c34f1d4e0f1151451420c9
|
[
"Apache-2.0"
] | 4
|
2020-02-24T02:36:48.000Z
|
2020-12-27T12:49:35.000Z
|
GControl/GControl/GControlDlg.cpp
|
GongZhihui/GControl
|
ed2076e3dd025760e5c34f1d4e0f1151451420c9
|
[
"Apache-2.0"
] | null | null | null |
GControl/GControl/GControlDlg.cpp
|
GongZhihui/GControl
|
ed2076e3dd025760e5c34f1d4e0f1151451420c9
|
[
"Apache-2.0"
] | 1
|
2021-03-21T06:04:03.000Z
|
2021-03-21T06:04:03.000Z
|
๏ปฟ
// GControlDlg.cpp: ๅฎ็ฐๆไปถ
//
#include "stdafx.h"
#include "GControl.h"
#include "GControlDlg.h"
#include "afxdialogex.h"
#include "resource.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CGControlDlg ๅฏน่ฏๆก
CGControlDlg::CGControlDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_GCONTROL_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CGControlDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_COMBO_A, aCobo_);
DDX_Control(pDX, IDC_EDIT_A, aEdit_);
DDX_Control(pDX, IDC_LISTBOX_A, aListbox_);
DDX_Control(pDX, IDC_STATIC_DXAN, dcanStc);
DDX_Control(pDX, IDC_RADIO_A, dxanAStc_);
DDX_Control(pDX, IDC_RADIO_B, dxanBStc_);
}
BEGIN_MESSAGE_MAP(CGControlDlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
END_MESSAGE_MAP()
// CGControlDlg ๆถๆฏๅค็็จๅบ
BOOL CGControlDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
SetIcon(m_hIcon, TRUE); // ่ฎพ็ฝฎๅคงๅพๆ
SetIcon(m_hIcon, FALSE); // ่ฎพ็ฝฎๅฐๅพๆ
initBK();
initComboBox();
initEdit();
initListBox();
initMessage();
initDXAN();
return TRUE;
}
void CGControlDlg::initBK()
{
bk_.LoadBitmapA(IDB_BITMAP_BK);
}
void CGControlDlg::initComboBox()
{
auto n = RGB(255,255,255);
//aCobo_.loadDownPic(IDB_BITMAP1);
aCobo_.InsertString(0, "ๆกๅญ");
aCobo_.InsertString(1, "่นๆ");
aCobo_.InsertString(2, "ๆขจ");
aCobo_.InsertString(3, "ๆขจ");
aCobo_.InsertString(4, "ๆขจ");
aCobo_.InsertString(5, "ๆขจ");
aCobo_.InsertString(6, "ๆขจ");
aCobo_.InsertString(7, "ๆขจ");
aCobo_.InsertString(8, "ๆขจ");
aCobo_.setItemSelectedColor(RGB(255,0,0));
CFont f;
LOGFONT lf = { 0 };
lf.lfHeight = 24;
strcpy_s(lf.lfFaceName, "ๅพฎ่ฝฏ้
้ป");
f.CreateFontIndirectA(&lf);
aCobo_.setFont(f);
aCobo_.setItemHeight(20);
aCobo_.setHeight(25);
aCobo_.SetCurSel(0);
aCobo_.setTextColor(RGB(255, 0, 0));
//aCobo_.setItemColor(RGB(255,0,0));
textcob_.createDropList(20, {400, 200, 400, 30});
textcob_.InsertString(0, "ๆกๅญ");
textcob_.InsertString(1, "่นๆ");
textcob_.InsertString(2, "ๆขจ");
textcob_.InsertString(3, "ๆขจ");
textcob_.InsertString(4, "ๆขจ");
textcob_.InsertString(5, "ๆขจ");
textcob_.InsertString(6, "ๆขจ");
textcob_.InsertString(7, "ๆขจ");
textcob_.InsertString(8, "ๆขจ");
textcob_.setItemSelectedColor(RGB(255, 0, 0));
textcob_.setFont(f);
textcob_.setItemHeight(20);
textcob_.setHeight(25);
textcob_.SetCurSel(0);
textcob_.setTextColor(RGB(255, 0, 0));
}
void CGControlDlg::initEdit()
{
aEdit_.SetWindowText("123456789");
aEdit_.setBorderColor(RGB(255,0,0));
aEdit_.setRoundPoint({ 10,10 });
LOGFONT lf = { 0 };
lf.lfHeight = 25;
strcpy_s(lf.lfFaceName, "ๅพฎ่ฝฏ้
้ป");
f.CreateFontIndirectA(&lf);
aEdit_.SetFont(&f);
//aEdit_.SetReadOnly();
}
void CGControlDlg::initListBox()
{
auto n = RGB(255, 255, 255);
//aCobo_.loadDownPic(IDB_BITMAP1);
aListbox_.InsertString(0, "ๆกๅญ");
aListbox_.InsertString(1, "่นๆ");
aListbox_.InsertString(2, "ๆขจ");
aListbox_.InsertString(3, "ๆขจ");
aListbox_.InsertString(4, "ๆขจ");
aListbox_.InsertString(5, "ๆขจ");
aListbox_.InsertString(6, "ๆขจ");
aListbox_.InsertString(7, "ๆขจ");
aListbox_.InsertString(8, "ๆขจ");
aListbox_.setItemSelectedColor(RGB(255, 0, 0));
CFont f;
LOGFONT lf = { 0 };
lf.lfHeight = 24;
strcpy_s(lf.lfFaceName, "ๅพฎ่ฝฏ้
้ป");
f.CreateFontIndirectA(&lf);
aListbox_.setFont(f);
aListbox_.SetCurSel(0);
}
void CGControlDlg::initMessage()
{
}
void CGControlDlg::initDXAN()
{
/*dxanAStc_.SetParent(&dcanStc);
dxanBStc_.SetParent(&dcanStc);
nvStc_.SetParent(&xbStc_);
nanStc_.SetParent(&xbStc_);*/
}
void CGControlDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // ็จไบ็ปๅถ็่ฎพๅคไธไธๆ
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// ไฝฟๅพๆ ๅจๅทฅไฝๅบ็ฉๅฝขไธญๅฑ
ไธญ
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// ็ปๅถๅพๆ
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//ๅฝ็จๆทๆๅจๆๅฐๅ็ชๅฃๆถ็ณป็ป่ฐ็จๆญคๅฝๆฐๅๅพๅ
ๆ
//ๆพ็คบใ
HCURSOR CGControlDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CGControlDlg::OnBnClickedRadioNan()
{
// TODO: ๅจๆญคๆทปๅ ๆงไปถ้็ฅๅค็็จๅบไปฃ็
}
| 21.509709
| 79
| 0.662604
|
GongZhihui
|
ccfd666127dec64f2c71cb225434a550569d218d
| 2,085
|
cpp
|
C++
|
Striver Sheet/Day-15/Roman to Integer.cpp
|
Akshad7829/DataStructures-Algorithms
|
439822c6a374672d1734e2389d3fce581a35007d
|
[
"MIT"
] | 5
|
2021-08-10T18:47:49.000Z
|
2021-08-21T15:42:58.000Z
|
Striver Sheet/Day-15/Roman to Integer.cpp
|
Akshad7829/DataStructures-Algorithms
|
439822c6a374672d1734e2389d3fce581a35007d
|
[
"MIT"
] | 2
|
2022-02-25T13:36:46.000Z
|
2022-02-25T14:06:44.000Z
|
Striver Sheet/Day-15/Roman to Integer.cpp
|
Akshad7829/DataStructures-Algorithms
|
439822c6a374672d1734e2389d3fce581a35007d
|
[
"MIT"
] | 1
|
2021-08-11T06:36:42.000Z
|
2021-08-11T06:36:42.000Z
|
/*
Roman to Integer
================
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III"
Output: 3
Example 2:
Input: s = "IV"
Output: 4
Example 3:
Input: s = "IX"
Output: 9
Example 4:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
*/
class Solution
{
public:
int romanToInt(string s)
{
unordered_map<char, pair<int, int>> m;
m['I'] = {1, 1};
m['V'] = {5, 2};
m['X'] = {10, 3};
m['L'] = {50, 4};
m['C'] = {100, 5};
m['D'] = {500, 6};
m['M'] = {1000, 7};
if (s.size() == 0)
return 0;
int ans = m[s[0]].first;
for (int i = 1; i < s.size(); ++i)
{
if (m[s[i - 1]].second < m[s[i]].second)
{
ans = ans - 2 * (m[s[i - 1]].first) + m[s[i]].first;
}
else
{
ans = ans + m[s[i]].first;
}
}
return ans;
}
};
| 24.529412
| 345
| 0.568345
|
Akshad7829
|
6901fef899b4f3ebe16f6cecf70147d09a0e11c7
| 872
|
cpp
|
C++
|
src/main.cpp
|
pamelus/air-conditioning-sensor
|
8d575d9cbf9a993d26437bd71addd114b07a689c
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
pamelus/air-conditioning-sensor
|
8d575d9cbf9a993d26437bd71addd114b07a689c
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
pamelus/air-conditioning-sensor
|
8d575d9cbf9a993d26437bd71addd114b07a689c
|
[
"MIT"
] | null | null | null |
#include <Arduino.h>
#include "Controller/RemoteCommandExecutor.h"
#include "Controller/SensorController.h"
#define INDOOR 1
#define OUTDOOR 2
#define VARIANT OUTDOOR
ACC::Controller::RemoteCommand::Radio radio(Serial, 2);
ACC::Controller::RemoteCommand::Executor executor(radio);
#if VARIANT == OUTDOOR
#include "Sensors/MCP9808.h"
ACC::Sensors::MCP9808 mcp9808(0x18);
ACC::Controller::SensorController controller(executor, mcp9808, nullptr, 0xA1, 0x41);
#elif VARIANT == INDOOR
#include "Sensors/SHT35.h"
ACC::Sensors::SHT35 sht35(0x45);
ACC::Controller::SensorController controller(executor, sht35, &sht35, 0xA1U, 0x21U);
#endif
void setup() {
Serial.begin(9600);
radio.initialize();
#if VARIANT == OUTDOOR
mcp9808.initialize();
#elif VARIANT == INDOOR
sht35.initialize();
#endif
}
void loop() {
controller.process();
}
| 24.914286
| 89
| 0.719037
|
pamelus
|
69051f1bc346206245819cbde0299aa3875036de
| 657
|
cpp
|
C++
|
modules/algorithm/test/test_pca.cpp
|
ljm941004/HYPERCV_PUBLIC
|
aef4f392ed0136284409c3e2d750a7812e4a5e35
|
[
"BSD-3-Clause"
] | 8
|
2019-08-16T00:38:02.000Z
|
2021-12-05T10:24:44.000Z
|
modules/algorithm/test/test_pca.cpp
|
mafu0927/HYPERCV_PUBLIC
|
aef4f392ed0136284409c3e2d750a7812e4a5e35
|
[
"BSD-3-Clause"
] | null | null | null |
modules/algorithm/test/test_pca.cpp
|
mafu0927/HYPERCV_PUBLIC
|
aef4f392ed0136284409c3e2d750a7812e4a5e35
|
[
"BSD-3-Clause"
] | 5
|
2019-07-23T07:28:29.000Z
|
2021-01-14T01:27:48.000Z
|
/*************************************************************************
> File Name: test_pca.cpp
> Author: ljm
> Mail: jimin@iscas.ac.cn
************************************************************************/
#include "precomp.h"
using namespace std;
void test_pca()
{
hyper_mat t = hmread_with_hdr("/home/ljm/data/dataz/bd0z","/home/ljm/data/dataz/bd0z.hdr");
hyper_mat float_mat =hyper_mat_ushort2float(t);
delete_hyper_mat(t);
hyper_mat dst_mat = hyper_mat_copy(float_mat);
hyper_mat_pca(float_mat,dst_mat,1);
hmsave("pca",dst_mat);
delete_hyper_mat(float_mat);
delete_hyper_mat(dst_mat);
}
TEST(ALGORITHM,PCA)
{
test_pca();
}
| 23.464286
| 95
| 0.567732
|
ljm941004
|
69060246c3450242cb7b3fe7d659180d0b31f87f
| 4,947
|
hpp
|
C++
|
glfw3_app/basic/buff.hpp
|
hirakuni45/glfw3_app
|
d9ceeef6d398229fda4849afe27f8b48d1597fcf
|
[
"BSD-3-Clause"
] | 9
|
2015-09-22T21:36:57.000Z
|
2021-04-01T09:16:53.000Z
|
glfw3_app/basic/buff.hpp
|
hirakuni45/glfw3_app
|
d9ceeef6d398229fda4849afe27f8b48d1597fcf
|
[
"BSD-3-Clause"
] | null | null | null |
glfw3_app/basic/buff.hpp
|
hirakuni45/glfw3_app
|
d9ceeef6d398229fda4849afe27f8b48d1597fcf
|
[
"BSD-3-Clause"
] | 2
|
2019-02-21T04:22:13.000Z
|
2021-03-02T17:24:32.000Z
|
#pragma once
//=====================================================================//
/*! @file
@brief ใใใใกใปใฏใฉใน
@author ๅนณๆพ้ฆไป (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ๆจๆบ็ใใใใกๆไฝ
@param[in] SIZE ใใใใกใปใตใคใบ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint16_t SIZE>
class buff {
public:
typedef uint16_t index_type;
private:
uint8_t buff_[SIZE];
uint16_t front_;
uint16_t back_;
public:
//-----------------------------------------------------------------//
/*!
@brief ใณใณในใใฉใฏใฟใผ
*/
//-----------------------------------------------------------------//
buff() : front_(0), back_(SIZE) { }
//-----------------------------------------------------------------//
/*!
@brief ใฏใชใขใปใใญใณใ
*/
//-----------------------------------------------------------------//
void clear_front() { front_ = 0; }
//-----------------------------------------------------------------//
/*!
@brief ใฏใชใขใปใใใฏ
*/
//-----------------------------------------------------------------//
void clear_back() { back_ = SIZE; }
//-----------------------------------------------------------------//
/*!
@brief ๅ
จใฏใชใข
*/
//-----------------------------------------------------------------//
void clear() {
clear_front();
clear_back();
}
//-----------------------------------------------------------------//
/*!
@brief ใใชใผใปใตใคใบใ่ฟใ
@return ใใชใผใปใตใคใบ
*/
//-----------------------------------------------------------------//
uint16_t get_free() const { return back_ - front_; }
//-----------------------------------------------------------------//
/*!
@brief ใใญใณใใปใตใคใบใ่ฟใ
@return ใใญใณใใปใตใคใบ
*/
//-----------------------------------------------------------------//
uint16_t get_front_size() const { return front_; }
//-----------------------------------------------------------------//
/*!
@brief ใใใฏใปใตใคใบใ่ฟใ
@return ใใใฏใปใตใคใบ
*/
//-----------------------------------------------------------------//
uint16_t get_back_size() const { return SIZE - back_; }
//-----------------------------------------------------------------//
/*!
@brief ่จญๅฎ
@param[in] src ใใญใใฏใฎๅ
้ ญ
@param[in] len ้ทใ
@param[in] dst ใณใใผๅ
*/
//-----------------------------------------------------------------//
void set(const void* src, uint16_t len, uint16_t dst) {
std::memcpy(&buff_[dst], src, len);
}
//-----------------------------------------------------------------//
/*!
@brief ่จญๅฎ๏ผ๏ผใใคใ๏ผ
@param[in] val ๅค
@param[in] dst ใณใใผๅ
*/
//-----------------------------------------------------------------//
void set1(uint8_t val, uint16_t dst) {
buff_[dst] = val;
}
//-----------------------------------------------------------------//
/*!
@brief ่จญๅฎ๏ผ๏ผใใคใ๏ผ
@param[in] val ๅค
@param[in] dst ใณใใผๅ
*/
//-----------------------------------------------------------------//
void set2(uint16_t val, uint16_t dst) {
buff_[dst] = val & 0xff;
buff_[dst + 1] = val >> 8;
}
//-----------------------------------------------------------------//
/*!
@brief ใใญใณใใใชใตใคใบ
@param[in] len ้ทใ
*/
//-----------------------------------------------------------------//
void resize_front(uint16_t len) {
front_ = len;
}
//-----------------------------------------------------------------//
/*!
@brief ใใผใฟใฎ็งปๅ
@param[in] src ใใผใฟใฎ็งปๅๅ
@param[in] dst ใใผใฟใฎ็งปๅๅ
@param[in] len ้ทใ
*/
//-----------------------------------------------------------------//
void move(uint16_t src, uint16_t dst, uint16_t len) {
std::memmove(&buff_[dst], &buff_[src], len);
}
//-----------------------------------------------------------------//
/*!
@brief ใใคใณใฟใผใๅๅพ
@param[in] pos ใใใใกใฎไฝ็ฝฎ
@return ใใคใณใฟใผใๅๅพ
*/
//-----------------------------------------------------------------//
const void* get(uint16_t pos) const {
return &buff_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief ๅคใๅๅพ๏ผ๏ผใใคใ๏ผ
@param[in] pos ใใใใกใฎไฝ็ฝฎ
@return ๅค
*/
//-----------------------------------------------------------------//
uint8_t get1(uint16_t pos) const {
return buff_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief ๅคใๅๅพ๏ผ๏ผใใคใ๏ผ
@param[in] pos ใใใใกใฎไฝ็ฝฎ
@return ๅค
*/
//-----------------------------------------------------------------//
uint16_t get2(uint16_t pos) const {
uint16_t v = buff_[pos];
v |= static_cast<uint16_t>(buff_[pos + 1]) << 8;
return v;
}
};
}
| 25.632124
| 74
| 0.269658
|
hirakuni45
|
6917b99944ad02adb3239541ef5b7322727884ad
| 1,405
|
cpp
|
C++
|
Algorithms/Sliding_Window/fixed_size/sub_arr_avg.cpp
|
abhishekjha786/ds_algo
|
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
|
[
"MIT"
] | 11
|
2020-03-20T17:24:28.000Z
|
2022-01-08T02:43:24.000Z
|
Algorithms/Sliding_Window/fixed_size/sub_arr_avg.cpp
|
abhishekjha786/ds_algo
|
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
|
[
"MIT"
] | 1
|
2021-07-25T11:24:46.000Z
|
2021-07-25T12:09:25.000Z
|
Algorithms/Sliding_Window/fixed_size/sub_arr_avg.cpp
|
abhishekjha786/ds_algo
|
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
|
[
"MIT"
] | 4
|
2020-03-20T17:24:36.000Z
|
2021-12-07T19:22:59.000Z
|
#include<bits/stdc++.h>
using namespace std;
// Find the subarray with least average
// Input: arr[] = {3, 7, 90, 20, 10, 50, 40}, k = 3
// Output: Subarray between indexes 3 and 5
// The subarray {20, 10, 50} has the least average
// among all subarrays of size 3.
// Input: arr[] = {3, 7, 5, 20, -10, 0, 12}, k = 2
// Output: Subarray between [4, 5] has minimum average
void print_v(vector <int> v)
{
for(auto x : v)
{
cout<<x<<" ";
}
}
int find_sub_arr_avg(vector <int> v, int k)
{
int n = v.size();
// Do calculation for first sub array of size k.
int wind_avg = -1;
int wind_sum = 0;
for(int j=0; j<k; j++)
{
wind_sum += v[j];
}
wind_avg = wind_sum / k;
// Now add next element and remove calculations of previous.
// i is pointer to start of window, j is to end of window.
int i = 0;
int min_avg = wind_avg;
for(int j=k; j<n; j++)
{
wind_sum = wind_sum + v[j] - v[i];
wind_avg = wind_sum / k;
min_avg = min(min_avg, wind_avg);
// Move ith pointer.
i += 1;
}
return min_avg;
// To search for minimum avg. Use the computed minimum average and find it
}
int main()
{
vector <int> v {3, 7, 90, 20, 10, 50, 40};
int k = 3; // Sub array size
auto min_avg = find_sub_arr_avg(v, k);
cout<<min_avg<<endl;
return(0);
}
| 23.032787
| 78
| 0.556584
|
abhishekjha786
|
691a3829cd80d1e079ee6b8be5851a29924b51d1
| 457
|
cpp
|
C++
|
LibsExternes/Includes/lzma465/CPP/7zip/Archive/Split/SplitRegister.cpp
|
benkaraban/anima-games-engine
|
8aa7a5368933f1b82c90f24814f1447119346c3b
|
[
"BSD-3-Clause"
] | 2
|
2015-04-16T01:05:53.000Z
|
2019-08-26T07:38:43.000Z
|
LibsExternes/Includes/lzma465/CPP/7zip/Archive/Split/SplitRegister.cpp
|
benkaraban/anima-games-engine
|
8aa7a5368933f1b82c90f24814f1447119346c3b
|
[
"BSD-3-Clause"
] | null | null | null |
LibsExternes/Includes/lzma465/CPP/7zip/Archive/Split/SplitRegister.cpp
|
benkaraban/anima-games-engine
|
8aa7a5368933f1b82c90f24814f1447119346c3b
|
[
"BSD-3-Clause"
] | null | null | null |
// SplitRegister.cpp
#include "StdAfx.h"
#include "../../Common/RegisterArc.h"
#include "SplitHandler.h"
static IInArchive *CreateArc() { return new NArchive::NSplit::CHandler; }
/*
#ifndef EXTRACT_ONLY
static IOutArchive *CreateArcOut() { return new NArchive::NSplit::CHandler; }
#else
#define CreateArcOut 0
#endif
*/
static CArcInfo g_ArcInfo =
{ L"Split", L"001", 0, 0xEA, { 0 }, 0, false, CreateArc, 0 };
REGISTER_ARC(Split)
| 21.761905
| 79
| 0.676149
|
benkaraban
|
691b25f641e13bd9afe819903b250410c4050e09
| 770
|
hpp
|
C++
|
libs/fnd/algorithm/include/bksge/fnd/algorithm/detail/binary_search.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 4
|
2018-06-10T13:35:32.000Z
|
2021-06-03T14:27:41.000Z
|
libs/fnd/algorithm/include/bksge/fnd/algorithm/detail/binary_search.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 566
|
2017-01-31T05:36:09.000Z
|
2022-02-09T05:04:37.000Z
|
libs/fnd/algorithm/include/bksge/fnd/algorithm/detail/binary_search.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 1
|
2018-07-05T04:40:53.000Z
|
2018-07-05T04:40:53.000Z
|
๏ปฟ/**
* @file binary_search.hpp
*
* @brief binary_search ใฎๅฎ่ฃ
*
* @author myoukaku
*/
#ifndef BKSGE_FND_ALGORITHM_DETAIL_BINARY_SEARCH_HPP
#define BKSGE_FND_ALGORITHM_DETAIL_BINARY_SEARCH_HPP
#include <bksge/fnd/algorithm/detail/lower_bound.hpp>
#include <bksge/fnd/config.hpp>
namespace bksge
{
namespace detail
{
template <typename Compare, typename ForwardIterator, typename T>
inline BKSGE_CXX14_CONSTEXPR bool
binary_search(
ForwardIterator first,
ForwardIterator last,
T const& value,
Compare comp)
{
first = bksge::detail::lower_bound(first, last, value, comp);
return first != last && !comp(value, *first);
}
} // namespace detail
} // namespace bksge
#endif // BKSGE_FND_ALGORITHM_DETAIL_BINARY_SEARCH_HPP
| 20.263158
| 66
| 0.732468
|
myoukaku
|
691e54f2c51985ef24079e3c9ba77cc7c08a2236
| 6,712
|
cpp
|
C++
|
lib/src/HOMappedGeometry/MultiBlockLevelGeom.cpp
|
rmrsk/Chombo-3.3
|
f2119e396460c1bb19638effd55eb71c2b35119e
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
lib/src/HOMappedGeometry/MultiBlockLevelGeom.cpp
|
rmrsk/Chombo-3.3
|
f2119e396460c1bb19638effd55eb71c2b35119e
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
lib/src/HOMappedGeometry/MultiBlockLevelGeom.cpp
|
rmrsk/Chombo-3.3
|
f2119e396460c1bb19638effd55eb71c2b35119e
|
[
"BSD-3-Clause-LBNL"
] | 1
|
2021-04-13T19:06:43.000Z
|
2021-04-13T19:06:43.000Z
|
#ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include "MultiBlockLevelGeom.H"
#include "BoxFixedOff.H"
#include "NamespaceHeader.H"
/// constructor
MultiBlockLevelGeom::MultiBlockLevelGeom(const MultiBlockCoordSys* a_coordSysPtr,
const DisjointBoxLayout& a_grids,
int a_ghosts,
Interval a_fixedDims,
Vector<int> a_fixedPt)
{
m_isDefined = false;
define(a_coordSysPtr, a_grids, a_ghosts,
a_fixedDims, a_fixedPt);
}
/// destructor
MultiBlockLevelGeom::~MultiBlockLevelGeom()
{
undefine();
}
void MultiBlockLevelGeom::undefine()
{
if (m_isDefined)
{
delete m_mbUtil;
m_interpDimsVect.clear();
m_fixedDimsVect.clear();
DataIterator dit = m_grids.dataIterator();
for (dit.begin(); dit.ok(); ++dit)
{
delete m_validIndices[dit];
delete m_validBlock[dit];
delete m_validMappedCenter[dit];
}
}
m_isDefined = false;
}
// Define knowing only ghosts required for the solution update procedure. DEPRECATED.
/** \param[in] a_ghosts
* The number of ghosts that are required in the solution
* update procedure can be interpolated.
* \param[in] a_spaceOrder
* Spatial order of the scheme
*/
void
MultiBlockLevelGeom::define(const MultiBlockCoordSys* a_coordSysPtr,
const DisjointBoxLayout& a_grids,
const int a_solUpdateGhosts,
const int a_spaceOrder,
Interval a_fixedDims,
Vector<int> a_fixedPt)
{
CH_assert(a_spaceOrder >= 2);
// petermc, 20 Nov 2012: earlier had a_solUpdateGhosts + a_spaceOrder/2
// instead of a_solUpdateGhosts, but that was with a previous version
// of MultiBlockLevelExchange.
define(a_coordSysPtr, a_grids, a_solUpdateGhosts,
a_fixedDims, a_fixedPt);
}
// Define with explicit specification of number of multiblock ghosts
/** This function should be avoided in user code unless you want to explicitly
* maintain the required number of ghosts.
* \param[in] a_ghosts
* The number of ghosts that must exchanged across block
* boundaries so that the number of ghosts required
* in the solution advance procedure can be interpolated.
*/
void
MultiBlockLevelGeom::define(const MultiBlockCoordSys* a_coordSysPtr,
const DisjointBoxLayout& a_grids,
int a_ghosts,
Interval a_fixedDims,
Vector<int> a_fixedPt)
{
undefine();
CH_TIME("MultiBlockLevelGeom::define");
CH_assert(a_coordSysPtr->isDefined());
m_coordSysPtr = (MultiBlockCoordSys*) a_coordSysPtr;
m_ghosts = a_ghosts;
// MultiBlockUtil has a new in it.
m_mbUtil = new MultiBlockUtil(m_coordSysPtr, a_fixedDims, a_fixedPt);
m_fixedDims = a_fixedDims;
m_interpDimsVect.clear();
m_fixedDimsVect.clear();
for (int idir = 0; idir < SpaceDim; idir++)
{
if ( a_fixedDims.contains(idir) )
{
m_fixedDimsVect.push_back(idir);
}
else
{
m_interpDimsVect.push_back(idir);
}
}
m_fixedPt = Vector<int>(a_fixedPt);
m_gridsFull = a_grids;
// Set BoxLayout m_gridsFixedOff to DisjointBoxLayout m_gridsFull
// modified so that every Box
// has range 0 in m_interpDimsVect, and
// shifted down by m_gridsFull.smallEnd(m_fixedDimsVect) in m_fixedDimsVect.
// Purpose: all cells in m_ghostCells[dit] + m_gridsFixedOff[dit]
// will have the same interpolation stencil.
m_allGridsHaveFixedPt = m_mbUtil->allGridsHaveFixedPt(m_gridsFull);
m_mbUtil->getCollapsedLayout(m_grids, m_gridsFull);
m_mbUtil->getFixedOffLayout(m_gridsFixedOff, m_gridsFull);
CH_assert(m_coordSysPtr->gotBoundaries());
#if 0
m_boundaries = m_coordSysPtr->boundaries();
#else
// workaround until we figure out why the above breaks COGENT
const Vector < Tuple< BlockBoundary, 2*SpaceDim > >& src_boundaries = m_coordSysPtr->boundaries();
int n = src_boundaries.size();
m_boundaries.resize(n);
for (int i=0; i<n; ++i)
{
m_boundaries[i] = src_boundaries[i];
}
#endif
DataIterator dit = m_grids.dataIterator();
// Get m_block.
m_block.define(m_grids);
for (dit.begin(); dit.ok(); ++dit)
{
const Box& baseBox = m_grids[dit];
// LayoutData<int> m_block;
int thisBlock = m_coordSysPtr->whichBlock(baseBox);
m_block[dit] = thisBlock;
}
// Get m_ghostCells.
extraBlockGhosts(m_ghostCells, m_ghosts);
{ CH_TIME("MultiBlockLevelGeom::define m_valid... arrays");
m_validIndices.define(m_grids);
m_validBlock.define(m_grids);
m_validMappedCenter.define(m_grids);
}
for (dit.begin(); dit.ok(); ++dit)
{ CH_TIME("MultiBlockLevelGeom::define validIndices, validBlock, validMappedCenter");
const IntVectSet& ghostCellsIVS = m_ghostCells[dit];
m_validIndices[dit] = new IVSFAB<IntVect>(ghostCellsIVS, 1);
m_validBlock[dit] = new IVSFAB<int>(ghostCellsIVS, 1);
m_validMappedCenter[dit] = new IVSFAB<RealVect>(ghostCellsIVS, 1);
m_mbUtil->getValid(*m_validIndices[dit],
*m_validBlock[dit],
*m_validMappedCenter[dit],
ghostCellsIVS,
m_block[dit]);
}
m_isDefined = true;
}
void
MultiBlockLevelGeom::extraBlockGhosts(LayoutData< IntVectSet >& a_ghostCells,
int a_ghostLayer) const
{
CH_TIME("MultiBlockLevelGeom::extraBlockGhosts");
a_ghostCells.define(m_grids);
DataIterator dit = m_grids.dataIterator();
if (a_ghostLayer == 0)
{ // empty
for (dit.begin(); dit.ok(); ++dit)
{
a_ghostCells[dit] = IntVectSet();
}
}
else
{
for (dit.begin(); dit.ok(); ++dit)
{
const Box& baseBox = m_grids[dit];
int baseBlockNum = m_block[dit];
a_ghostCells[dit] =
m_mbUtil->extraBlockGhosts(baseBox, a_ghostLayer, baseBlockNum);
}
}
}
#include "NamespaceFooter.H"
| 32.901961
| 100
| 0.604589
|
rmrsk
|
69223569b49d94c6fa91b28ce4a1ac86aea0d3bc
| 193
|
cpp
|
C++
|
src/passman/fs/is_empty.cpp
|
tabz1234/passman
|
adab0c58982619a7640716e7304d1a58d6257793
|
[
"Unlicense"
] | null | null | null |
src/passman/fs/is_empty.cpp
|
tabz1234/passman
|
adab0c58982619a7640716e7304d1a58d6257793
|
[
"Unlicense"
] | null | null | null |
src/passman/fs/is_empty.cpp
|
tabz1234/passman
|
adab0c58982619a7640716e7304d1a58d6257793
|
[
"Unlicense"
] | null | null | null |
#include "is_empty.hpp"
#include <filesystem>
bool Passman::FS::is_empty(const std::string_view path) noexcept
{
std::error_code errc;
return std::filesystem::is_empty(path, errc);
}
| 19.3
| 64
| 0.720207
|
tabz1234
|
6929c8e2ff33abbf48b8f3a8d2b958d9146ee49e
| 870
|
cpp
|
C++
|
Leetcode/Practice/Find Common Characters.cpp
|
coderanant/Competitive-Programming
|
45076af7894251080ac616c9581fbf2dc49604af
|
[
"MIT"
] | 4
|
2019-06-04T11:03:38.000Z
|
2020-06-19T23:37:32.000Z
|
Leetcode/Practice/Find Common Characters.cpp
|
coderanant/Competitive-Programming
|
45076af7894251080ac616c9581fbf2dc49604af
|
[
"MIT"
] | null | null | null |
Leetcode/Practice/Find Common Characters.cpp
|
coderanant/Competitive-Programming
|
45076af7894251080ac616c9581fbf2dc49604af
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<string> commonChars(vector<string>& A) {
int base[26];
memset(base, 0, sizeof base);
for(int i = 0; i < A[0].size(); i++)
base[A[0][i] - 'a']++;
for(int i = 1; i < A.size(); i++)
{
int temp[26];
memset(temp, 0, sizeof temp);
for(int j = 0; j < A[i].size(); j++)
{
temp[A[i][j] - 'a']++;
}
for(int j = 0; j < 26; j++)
{
base[j] = min(base[j], temp[j]);
}
}
vector<string> ans;
for(int i = 0; i < 26; i++)
{
for(int j = 0; j < base[i]; j++)
{
string temp;
temp += char(i + 'a');
ans.push_back(temp);
}
}
return ans;
}
};
| 26.363636
| 51
| 0.33908
|
coderanant
|
692d2ec687dac5872f4640258dbd0aeae26f1895
| 4,815
|
cpp
|
C++
|
grading_tool/settings_window.cpp
|
almikh/automatic-knee-oa-grading-tools
|
f59c2ba627ed3f52d0acdb01535c3224c64210de
|
[
"MIT"
] | null | null | null |
grading_tool/settings_window.cpp
|
almikh/automatic-knee-oa-grading-tools
|
f59c2ba627ed3f52d0acdb01535c3224c64210de
|
[
"MIT"
] | null | null | null |
grading_tool/settings_window.cpp
|
almikh/automatic-knee-oa-grading-tools
|
f59c2ba627ed3f52d0acdb01535c3224c64210de
|
[
"MIT"
] | null | null | null |
#include "settings_window.h"
#include "settings_window.h"
#include <QApplication>
#include <QJsonDocument>
#include <QGridLayout>
#include <QScrollArea>
#include <QScrollBar>
#include <QPushButton>
#include <QFileDialog>
#include <QComboBox>
#include <QGroupBox>
#include <QLineEdit>
#include <QCheckBox>
#include <QListWidget>
#include <QLabel>
#include <QDebug>
#include "app_preferences.h"
bool SettingsWindow::opened = false;
SettingsWindow::SettingsWindow(QWidget* parent) :
QMainWindow(parent, Qt::Dialog)
{
SettingsWindow::opened = true;
setWindowTitle("Settings");
setWindowIcon(QIcon(":/ic_settings"));
setAttribute(Qt::WA_DeleteOnClose);
auto w = new QWidget();
auto vl = new QVBoxLayout(w);
vl->setAlignment(Qt::AlignTop);
auto create_selector = [this](QGridLayout* l, QString title, QString name, QString filter, int row) {
auto caption = new QLabel(title);
caption->setFixedWidth(115);
l->addWidget(caption, row, 0, Qt::AlignVCenter);
auto line_edit = new QLineEdit("");
line_edit->setObjectName(name);
l->addWidget(line_edit, row, 1);
auto button = new QPushButton("...");
button->setFixedWidth(64);
l->addWidget(button, row, 2);
connect(button, &QPushButton::clicked, [this, line_edit, filter, title]() {
auto default_dir = AppPrefs::read("last_selector_path", line_edit->text()).toString();
auto filename = QFileDialog::getOpenFileName(this, title, default_dir, filter, nullptr, QFileDialog::DontConfirmOverwrite);
if (!filename.isEmpty()) {
AppPrefs::write("last_selector_path", QFileInfo(filename).dir().path());
line_edit->setText(filename);
}
});
return std::make_tuple(line_edit, button);
};
auto create_combo_box = [this](QGridLayout* l, QString title, QString name, int row, QStringList vals) {
auto caption = new QLabel(title);
caption->setFixedWidth(150);
l->addWidget(caption, row, 0);
auto cb = new QComboBox();
cb->setObjectName(name);
cb->addItems(vals);
l->addWidget(cb, row, 1);
return cb;
};
auto create_check_box = [this](QGridLayout* l, QString title, QString name, int row, int cols = 1, bool fixed_width = false) {
auto ch = new QCheckBox(title);
ch->setObjectName(name);
if (fixed_width) {
ch->setFixedWidth(250);
}
ch->setFocusPolicy(Qt::FocusPolicy::NoFocus);
l->addWidget(ch, row, 0, 1, cols, Qt::AlignTop | Qt::AlignLeft);
return ch;
};
auto create_item = [this](QGridLayout* l, QString title, QString name, int row) {
auto caption = new QLabel(title);
caption->setFixedWidth(250);
l->addWidget(caption, row, 0);
auto line_edit = new QLineEdit("");
line_edit->setObjectName(name);
l->addWidget(line_edit, row, 1);
return line_edit;
};
//
auto gb = new QGroupBox("Common settings");
gb->setStyleSheet("QGroupBox { font-weight: bold; } ");
gb->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
vl->addWidget(gb);
int r = 0;
auto l = new QGridLayout(gb);
l->setContentsMargins(8, 8, 8, 8);
l->setAlignment(Qt::AlignTop);
l->setSpacing(8);
// UI
auto enable_classifier = new QCheckBox("Enable automitic osteoarthritis classification");
enable_classifier->setObjectName("enable_classifier");
l->addWidget(enable_classifier, r, 0, 1, 2);
r += 1;
create_selector(l, "Classifier file path", "classifier_params_path", "", r);
r += 1;
//
auto scroll_area = new QScrollArea(this);
scroll_area->horizontalScrollBar()->hide();
scroll_area->setBackgroundRole(QPalette::Window);
scroll_area->setFrameShadow(QFrame::Plain);
scroll_area->setFrameShape(QFrame::NoFrame);
scroll_area->setWidgetResizable(true);
scroll_area->setWidget(w);
setCentralWidget(scroll_area);
setFixedSize(480, 320);
// ะทะฐะฟะธัั ะธะทะผะตะฝะตะฝะธะน
QObject::connect(this, &SettingsWindow::closed, [=](bool) {
const auto enable_classifier = findChild<QCheckBox*>("enable_classifier");
const auto classifier_params_path = findChild<QLineEdit*>("classifier_params_path");
AppPrefs::write("enable_classifier", enable_classifier->isChecked());
AppPrefs::write("classifier_params_path", classifier_params_path->text());
});
init();
}
SettingsWindow::~SettingsWindow() {
SettingsWindow::opened = false;
}
void SettingsWindow::hideEvent(QHideEvent* e) {
emit visibilityChanged(false);
emit closed(true);
QMainWindow::hideEvent(e);
}
void SettingsWindow::init() {
const auto classifier_params_path = findChild<QLineEdit*>("classifier_params_path");
const auto enable_classifier = findChild<QCheckBox*>("enable_classifier");
enable_classifier->setChecked(AppPrefs::read("enable_classifier").toBool());
classifier_params_path->setText(AppPrefs::read("classifier_params_path").toString());
}
| 30.865385
| 129
| 0.701558
|
almikh
|
693392e4bb211afb02711eb3e25c4dfe6f4f5e53
| 448
|
cpp
|
C++
|
programs_AtoZ/Conversion Decimal to Octal/Decimal_to_Octal.cpp
|
EarthMan123/unitech_cpp_with_oops-course
|
941fec057bdcb8a5289994780ae553e6d4fddbbe
|
[
"Unlicense"
] | 2
|
2021-06-12T02:55:28.000Z
|
2021-07-04T22:25:38.000Z
|
programs_AtoZ/Conversion Decimal to Octal/Decimal_to_Octal.cpp
|
EarthMan123/unitech_cpp_with_oops-course
|
941fec057bdcb8a5289994780ae553e6d4fddbbe
|
[
"Unlicense"
] | null | null | null |
programs_AtoZ/Conversion Decimal to Octal/Decimal_to_Octal.cpp
|
EarthMan123/unitech_cpp_with_oops-course
|
941fec057bdcb8a5289994780ae553e6d4fddbbe
|
[
"Unlicense"
] | 1
|
2021-07-04T22:28:38.000Z
|
2021-07-04T22:28:38.000Z
|
// C++ Program to Convert Decimal to Octal
#include<iostream>
using namespace std;
int main()
{
int decimalNum, octalNum[50], i=0;
cout<<"Enter any Decimal number: ";
cin>>decimalNum;
while(decimalNum != 0)
{
octalNum[i] = decimalNum%8;
i++;
decimalNum = decimalNum/8;
}
cout<<"\nEquivalent Octal Value = ";
for(i=(i-1); i>=0; i--)
cout<<octalNum[i];
cout<<endl;
return 0;
}
| 20.363636
| 42
| 0.564732
|
EarthMan123
|
69339dffd05441ed22395d48782ffe7ac3f6c8ff
| 2,902
|
cpp
|
C++
|
engine/scene_impl/scene_pause.cpp
|
rimuz/unfair-game
|
5479d64b2f22d109b77cc024ab61d67be98b64d5
|
[
"Apache-2.0"
] | 4
|
2019-01-22T21:06:39.000Z
|
2022-02-27T22:00:38.000Z
|
engine/scene_impl/scene_pause.cpp
|
rimuz/unfair
|
5479d64b2f22d109b77cc024ab61d67be98b64d5
|
[
"Apache-2.0"
] | null | null | null |
engine/scene_impl/scene_pause.cpp
|
rimuz/unfair
|
5479d64b2f22d109b77cc024ab61d67be98b64d5
|
[
"Apache-2.0"
] | null | null | null |
#include "engine/scene.hpp"
#include "io/save.hpp"
namespace ue{
void Scene::togglePauseGame(){
if(Game::curr_game){
GAME.paused = !GAME.paused;
if(GAME.paused){
if(GAME.showingLevel){
removeLevelScreen();
} else {
removeHUD();
}
pauseButtons->selected = 0;
addSubject(blackScreen);
addSubject(pauseText);
addSubject(pauseButtons);
} else {
if(GAME.showingLevel){
showLevelScreen(GAME.currLevel.n, GAME.currLevel.boss->name);
} else {
showHUD();
}
pauseButtons->selected = 0;
removeSubject(blackScreen);
removeSubject(pauseText);
removeSubject(pauseButtons);
}
}
}
void Scene::leaveGame(){
GAME.showingLevel = false;
if(GAME.paused){
togglePauseGame();
}
removeHUD();
clearTimeJobs();
clearMemory();
}
void Scene::pause(){
if(Game::curr_game && in_game && !GAME.paused){
togglePauseGame();
}
}
void Scene::updateDifficulties(){
bool enabledNoob = false;
bool enabledHard = false;
bool enabledPro = false;
bool enabledHell = false;
for(save::Score& sc : save::score){
switch(sc.mode){
case 4:
case 3:{
enabledHell = true;
break;
}
case 2:{
enabledPro = true;
break;
}
case 1:{
enabledHard = true;
break;
}
case 0:{
enabledNoob = true;
break;
}
}
}
if(enabledNoob){
chooseDifficultyButtons->buttons[1]->enable("NOOB");
} else {
chooseDifficultyButtons->buttons[1]->disable("NOOB (LOCKED)");
}
if(enabledHard){
chooseDifficultyButtons->buttons[2]->enable("HARD");
} else {
chooseDifficultyButtons->buttons[2]->disable("HARD (LOCKED)");
}
if(enabledPro){
chooseDifficultyButtons->buttons[3]->enable("PRO");
} else{
chooseDifficultyButtons->buttons[3]->disable("PRO (LOCKED)");
}
if(enabledHell){
chooseDifficultyButtons->buttons[4]->enable("HELL");
} else {
chooseDifficultyButtons->buttons[4]->disable("HELL (LOCKED)");
}
}
}
| 26.87037
| 82
| 0.431082
|
rimuz
|
69355da0cec1c8ade38a25fddf638183285fcd2c
| 595
|
cpp
|
C++
|
qt3dwidget.cpp
|
MedMoute/EF-Solver
|
aa79a0b21b08016f66277ec2cba686776b83f0e3
|
[
"MIT"
] | null | null | null |
qt3dwidget.cpp
|
MedMoute/EF-Solver
|
aa79a0b21b08016f66277ec2cba686776b83f0e3
|
[
"MIT"
] | null | null | null |
qt3dwidget.cpp
|
MedMoute/EF-Solver
|
aa79a0b21b08016f66277ec2cba686776b83f0e3
|
[
"MIT"
] | 1
|
2021-08-12T14:10:34.000Z
|
2021-08-12T14:10:34.000Z
|
#include <Qt3DCore/QEntity>
#include <Qt3DRender/QCamera>
#include <Qt3DRender/QCameraLens>
#include <Qt3DCore/QTransform>
#include <Qt3DCore/QAspectEngine>
#include <Qt3DInput/QInputAspect>
#include <Qt3DRender/QRenderAspect>
#include <Qt3DExtras/QForwardRenderer>
#include "qt3dwindow.h"
#include "qt3dwidget.h"
#include "viewer3d.h"
Qt3DWidget::Qt3DWidget(QWidget *parent,vector<Triangle>* meshVector)
: QWidget(parent)
{
Viewer3D* m_viewer3D = new Viewer3D(this);
m_viewer3D->sceneModifier()->addTriangleMeshCustomMaterial(QString(), meshVector);
m_viewer3D->show();
}
| 23.8
| 86
| 0.766387
|
MedMoute
|
693c019d724684da451f0a226087c501abbe6931
| 8,309
|
cpp
|
C++
|
DT3Core/Scripting/ScriptingSoundHighPassFilter3db.cpp
|
9heart/DT3
|
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
|
[
"MIT"
] | 3
|
2016-01-27T13:17:18.000Z
|
2019-03-19T09:18:25.000Z
|
DT3Core/Scripting/ScriptingSoundHighPassFilter3db.cpp
|
pakoito/DT3
|
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
|
[
"MIT"
] | 1
|
2016-01-28T14:39:49.000Z
|
2016-01-28T22:12:07.000Z
|
DT3Core/Scripting/ScriptingSoundHighPassFilter3db.cpp
|
adderly/DT3
|
e2605be091ec903d3582e182313837cbaf790857
|
[
"MIT"
] | 3
|
2016-01-25T16:44:51.000Z
|
2021-01-29T19:59:45.000Z
|
//==============================================================================
///
/// File: ScriptingSoundHighPassFilter3db.cpp
///
/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DT3Core/Scripting/ScriptingSoundHighPassFilter3db.hpp"
#include "DT3Core/System/Factory.hpp"
#include "DT3Core/System/Profiler.hpp"
#include "DT3Core/Types/FileBuffer/ArchiveData.hpp"
#include "DT3Core/Types/FileBuffer/Archive.hpp"
#include "DT3Core/Types/Math/MoreMath.hpp"
//==============================================================================
//==============================================================================
namespace DT3 {
//==============================================================================
/// Register with object factory
//==============================================================================
IMPLEMENT_FACTORY_CREATION_SCRIPT(ScriptingSoundHighPassFilter3db,"Sound",NULL)
IMPLEMENT_PLUG_NODE(ScriptingSoundHighPassFilter3db)
IMPLEMENT_PLUG_INFO_INDEX(_sound_packet_in)
IMPLEMENT_PLUG_INFO_INDEX(_sound_packet_out)
IMPLEMENT_PLUG_INFO_INDEX(_cutoff_frequency)
//==============================================================================
//==============================================================================
BEGIN_IMPLEMENT_PLUGS(ScriptingSoundHighPassFilter3db)
PLUG_INIT(_sound_packet_in,"Sound_Packet_In")
.affects(PLUG_INFO_INDEX(_sound_packet_out))
.set_input(true)
.set_always_dirty(true);
PLUG_INIT(_sound_packet_out,"Sound_Packet_Out")
.set_single_output(true)
.set_output(true)
.set_always_dirty(true);
PLUG_INIT(_cutoff_frequency,"Cutoff_Frequency")
.set_input(true);
END_IMPLEMENT_PLUGS
//==============================================================================
/// Standard class constructors/destructors
//==============================================================================
ScriptingSoundHighPassFilter3db::ScriptingSoundHighPassFilter3db (void)
: _sound_packet_in (PLUG_INFO_INDEX(_sound_packet_in)),
_sound_packet_out (PLUG_INFO_INDEX(_sound_packet_out)),
_cutoff_frequency (PLUG_INFO_INDEX(_cutoff_frequency), 8000.0F),
_last_in_sample_left (0),
_last_out_sample_left (0),
_last_in_sample_right (0),
_last_out_sample_right (0)
{
}
ScriptingSoundHighPassFilter3db::ScriptingSoundHighPassFilter3db (const ScriptingSoundHighPassFilter3db &rhs)
: ScriptingSoundBase (rhs),
_sound_packet_in (rhs._sound_packet_in),
_sound_packet_out (rhs._sound_packet_out),
_cutoff_frequency (rhs._cutoff_frequency),
_last_in_sample_left (rhs._last_in_sample_left),
_last_out_sample_left (rhs._last_out_sample_left),
_last_in_sample_right (rhs._last_in_sample_right),
_last_out_sample_right (rhs._last_out_sample_right)
{
}
ScriptingSoundHighPassFilter3db & ScriptingSoundHighPassFilter3db::operator = (const ScriptingSoundHighPassFilter3db &rhs)
{
// Make sure we are not assigning the class to itself
if (&rhs != this) {
ScriptingSoundBase::operator = (rhs);
_sound_packet_in = rhs._sound_packet_in;
_sound_packet_out = rhs._sound_packet_out;
_cutoff_frequency = rhs._cutoff_frequency;
_last_in_sample_left = rhs._last_in_sample_left;
_last_out_sample_left = rhs._last_out_sample_left;
_last_in_sample_right = rhs._last_in_sample_right;
_last_out_sample_right = rhs._last_out_sample_right;
}
return (*this);
}
ScriptingSoundHighPassFilter3db::~ScriptingSoundHighPassFilter3db (void)
{
}
//==============================================================================
//==============================================================================
void ScriptingSoundHighPassFilter3db::initialize (void)
{
ScriptingSoundBase::initialize();
}
//==============================================================================
//==============================================================================
void ScriptingSoundHighPassFilter3db::archive (const std::shared_ptr<Archive> &archive)
{
ScriptingSoundBase::archive(archive);
archive->push_domain (class_id ());
*archive << ARCHIVE_PLUG(_cutoff_frequency, DATA_PERSISTENT | DATA_SETTABLE);
archive->pop_domain ();
}
//==============================================================================
//==============================================================================
DTboolean ScriptingSoundHighPassFilter3db::compute (const PlugBase *plug)
{
PROFILER(SOUND);
if (super_type::compute(plug)) return true;
if (plug == &_sound_packet_out) {
SoundPacket &sound_packet_in = _sound_packet_in.as_ref_no_compute();
SoundPacket &sound_packet_out = _sound_packet_out.as_ref_no_compute();
if (!_sound_packet_in.has_incoming_connection()) {
sound_packet_out.set_format(SoundResource::FORMAT_STEREO16);
sound_packet_out.set_num_bytes(0);
sound_packet_out.set_frequency(44100);
return true;
}
// This copies the buffer so no extra memory is needed
sound_packet_out = sound_packet_in;
DTfloat period = 1.0F / sound_packet_in.frequency();
DTfloat RC = 1.0F / (TWO_PI * _cutoff_frequency);
DTfloat alpha = RC / ( RC + period );
DTshort *data_in = (DTshort *) sound_packet_in.buffer();
DTshort *data_out = (DTshort *) sound_packet_out.buffer();
DTint alpha_int = UNIT_TO_10BIT_INT(alpha);
if (sound_packet_in.format() == SoundResource::FORMAT_MONO16) {
DTsize num_samples = sound_packet_in.num_samples();
DTshort *sample_in = &data_in[0];
DTshort *sample_out = &data_out[0];
for (DTuint s = 0; s < num_samples; ++s) {
DTshort last_in_sample = (*sample_in);
(*sample_out) = static_cast<DTshort>(REM_10BIT(CLAMP_PAD_10BIT(alpha_int * (_last_out_sample_left + last_in_sample - _last_in_sample_left))));
_last_in_sample_left = last_in_sample;
_last_out_sample_left = (*sample_out);
++sample_in;
++sample_out;
}
} else if (sound_packet_in.format() == SoundResource::FORMAT_STEREO16) {
DTsize num_samples = sound_packet_in.num_samples();
DTshort *sample_in = &data_in[0];
DTshort *sample_out = &data_out[0];
for (DTuint s = 0; s < num_samples; ++s) {
DTshort last_in_sample = (*sample_in);
(*sample_out) = static_cast<DTshort>(REM_10BIT(CLAMP_PAD_10BIT(alpha_int * (_last_out_sample_left + last_in_sample - _last_in_sample_left))));
_last_in_sample_left = last_in_sample;
_last_out_sample_left = (*sample_out);
++sample_in;
++sample_out;
last_in_sample = (*sample_in);
(*sample_out) = static_cast<DTshort>(REM_10BIT(CLAMP_PAD_10BIT(alpha_int * (_last_out_sample_right + last_in_sample - _last_in_sample_right))));
_last_in_sample_right = last_in_sample;
_last_out_sample_right = (*sample_out);
++sample_in;
++sample_out;
}
}
_sound_packet_out.set_clean();
return true;
}
return false;
}
//==============================================================================
//==============================================================================
} // DT3
| 37.427928
| 161
| 0.533999
|
9heart
|
693d7e33c67decac79b6d3863a5d076d1f256682
| 2,849
|
cpp
|
C++
|
alicia_modder/source/main/buffer/buffer.cpp
|
rgnter/alicia_modwork
|
88713a943a7dccf0f0ec9f4322f5cb41b1200db4
|
[
"MIT"
] | 3
|
2021-03-29T15:37:38.000Z
|
2021-09-18T18:53:02.000Z
|
alicia_modder/source/main/buffer/buffer.cpp
|
rgnter/alicia_modwork
|
88713a943a7dccf0f0ec9f4322f5cb41b1200db4
|
[
"MIT"
] | null | null | null |
alicia_modder/source/main/buffer/buffer.cpp
|
rgnter/alicia_modwork
|
88713a943a7dccf0f0ec9f4322f5cb41b1200db4
|
[
"MIT"
] | null | null | null |
//
// Created by maros on 31/05/2021.
//
#include "buffer.hpp"
#include "cstdio"
#include "string.h"
buffer::stack_buffer::stack_buffer(const void *dataPtr, size_t dataLen) :
m_buffer((uint8_t *) dataPtr), m_bufferLength(dataLen), m_bufferCursor(0) {
}
void buffer::stack_buffer::setCursor(size_t pos) {
this->m_bufferCursor = pos;
}
void buffer::stack_buffer::resetCursor() {
this->m_bufferCursor = 0;
}
size_t buffer::stack_buffer::getCursor() const {
return this->m_bufferCursor;
}
uint8_t *buffer::stack_buffer::dataPtr() const {
return this->m_buffer;
}
size_t buffer::stack_buffer::getLength() const {
return this->m_bufferLength;
}
size_t buffer::stack_buffer::getSize() const {
return this->m_bufferLength;
}
uint8_t buffer::stack_buffer::readUnsignedByte() {
if (m_bufferCursor > m_bufferLength)
return 0;
const auto result = m_buffer[m_bufferCursor++];
return result;
}
void buffer::stack_buffer::writeUnsignedByte(uint8_t byte) {
m_buffer[m_bufferCursor++] = byte;
}
uint8_t buffer::stack_buffer::peekUnsignedByte() const {
return m_buffer[m_bufferCursor];
}
int8_t buffer::stack_buffer::readByte() {
return (int8_t) readUnsignedByte();
}
void buffer::stack_buffer::writeByte(int8_t byte) {
writeUnsignedByte((uint8_t) byte);
}
int8_t buffer::stack_buffer::peekByte() const {
return (int8_t) peekUnsignedByte();
}
uint16_t buffer::stack_buffer::readUnsignedShort() {
return (uint16_t) (readUnsignedByte() + (readUnsignedByte() << 8));
}
void buffer::stack_buffer::writeUnsignedShort(uint16_t val) {
writeUnsignedByte(val & 0xFF);
writeUnsignedByte(val >> 8);
}
uint16_t buffer::stack_buffer::peekUnsignedShort() const {
return (uint16_t) (peekUnsignedByte() + (peekUnsignedByte() << 8));
}
int16_t buffer::stack_buffer::readShort() {
return (int16_t) readUnsignedShort();
}
void buffer::stack_buffer::writeShort(int16_t val) {
writeUnsignedShort((uint16_t) val);
}
int16_t buffer::stack_buffer::peekShort() const {
return (int16_t) peekUnsignedShort();
}
uint32_t buffer::stack_buffer::readUnsignedInteger() {
uint16_t least = readUnsignedShort();
uint32_t most = readUnsignedShort() << 16;
return (uint32_t) (least+most);
}
void buffer::stack_buffer::writeUnsignedInteger(uint32_t val) {
writeUnsignedShort(val & 0xFFFF);
writeUnsignedShort(val << 16);
}
uint32_t buffer::stack_buffer::peekUnsignedInteger() const {
return (uint32_t) (peekUnsignedShort() + (peekUnsignedShort() << 16));
}
int32_t buffer::stack_buffer::readInteger() {
return (int32_t) readUnsignedInteger();
}
void buffer::stack_buffer::writeInteger(int32_t val) {
writeUnsignedInteger((uint16_t) val);
}
int32_t buffer::stack_buffer::peekInteger() const {
return (int32_t) peekUnsignedInteger();
}
| 23.352459
| 83
| 0.716041
|
rgnter
|
693f21cd4794e8c3892720088e28e867736b3d8b
| 1,174
|
cpp
|
C++
|
src/DesktopCore/Utils/Patterns/PublisherSubscriber/Broker.cpp
|
lurume84/blink-desktop
|
d6d01f8dc461edd22192a521fbd49669bfa8f684
|
[
"MIT"
] | 75
|
2019-03-08T14:15:49.000Z
|
2022-01-05T17:30:43.000Z
|
src/DesktopCore/Utils/Patterns/PublisherSubscriber/Broker.cpp
|
lurume84/blink-desktop
|
d6d01f8dc461edd22192a521fbd49669bfa8f684
|
[
"MIT"
] | 55
|
2019-02-17T01:34:12.000Z
|
2022-02-26T21:07:33.000Z
|
src/DesktopCore/Utils/Patterns/PublisherSubscriber/Broker.cpp
|
lurume84/blink-desktop
|
d6d01f8dc461edd22192a521fbd49669bfa8f684
|
[
"MIT"
] | 20
|
2019-05-21T19:02:31.000Z
|
2022-03-28T07:29:28.000Z
|
#include "Broker.h"
#include "Event.h"
namespace desktop { namespace core { namespace utils { namespace patterns {
Broker& Broker::get()
{
static Broker S;
return S;
}
Broker::Broker() = default;
Broker::~Broker()
{
std::unique_lock<std::mutex> lock(m_mutexSubscriptions);
TStrSubscriberMap::iterator it = m_subscriptions.begin();
while(it != m_subscriptions.end())
{
it->second.reset();
++it;
}
m_subscriptions.clear();
}
Broker::SignalType& Broker::getSignal(const EventType& evtName)
{
std::unique_lock<std::mutex> lock(m_mutexSubscriptions);
TStrSubscriberMap::iterator it = m_subscriptions.find(evtName);
if(it == m_subscriptions.end())
{
m_subscriptions[evtName] = std::make_unique<SignalType>();
return *m_subscriptions[evtName];
}
else
{
return *it->second;
}
}
std::unique_ptr<Broker::ConnectionType> Broker::subscribe(CallbackType cb, const EventType& evtName)
{
SignalType& signal = getSignal(evtName);
return std::make_unique<ConnectionType>(signal.connect(cb));
}
void Broker::publish(const Event& evt)
{
getSignal(evt.m_name)(evt);
}
}}}}
| 20.964286
| 101
| 0.669506
|
lurume84
|
6942dd0d32d26e8a4dcc9e070425e468c34063b8
| 348
|
cpp
|
C++
|
Camp_1-2562/07 Pointer-Structure/Untitled2.cpp
|
MasterIceZ/POSN_BUU
|
56e176fb843d7ddcee0cf4acf2bb141576c260cf
|
[
"MIT"
] | null | null | null |
Camp_1-2562/07 Pointer-Structure/Untitled2.cpp
|
MasterIceZ/POSN_BUU
|
56e176fb843d7ddcee0cf4acf2bb141576c260cf
|
[
"MIT"
] | null | null | null |
Camp_1-2562/07 Pointer-Structure/Untitled2.cpp
|
MasterIceZ/POSN_BUU
|
56e176fb843d7ddcee0cf4acf2bb141576c260cf
|
[
"MIT"
] | null | null | null |
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main (){
struct profile{
char name[20];
int age;
}s[10];
for(int i=0;i<10;i++){
printf("Student[%d]\n",i);
printf("\t %s",s[i].name);
printf("\t age");
scanf("%d",&s[i].age);
}
for(int j=0;j<10;j++)
if(s[j].age>20)
printf("\n%s,%d",s[j].name,s[j].age);
return 0;
}
| 16.571429
| 40
| 0.545977
|
MasterIceZ
|
6942fbf506141863c5861da224e93bddbf51b79e
| 579
|
hpp
|
C++
|
src/Tools/Constellation/PAM/Constellation_PAM.hpp
|
WilliamMajor/aff3ct
|
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
|
[
"MIT"
] | 1
|
2022-02-17T08:47:47.000Z
|
2022-02-17T08:47:47.000Z
|
src/Tools/Constellation/PAM/Constellation_PAM.hpp
|
WilliamMajor/aff3ct
|
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
|
[
"MIT"
] | null | null | null |
src/Tools/Constellation/PAM/Constellation_PAM.hpp
|
WilliamMajor/aff3ct
|
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
|
[
"MIT"
] | 1
|
2022-02-15T23:32:39.000Z
|
2022-02-15T23:32:39.000Z
|
#ifndef CONSTELLATION_PAM_HPP__
#define CONSTELLATION_PAM_HPP__
#include <cstdint>
#include "Tools/Constellation/Constellation.hpp"
namespace aff3ct
{
namespace tools
{
template <typename R>
class Constellation_PAM : public Constellation<R>
{
public:
using typename Constellation<R>::S;
/*
* \param n_bps is the number of bits per symbol
*/
explicit Constellation_PAM(const unsigned n_bps);
protected:
S bits_to_symbol(const uint8_t bits[]) const;
const R sqrt_es;
};
}
}
#include "Tools/Constellation/PAM/Constellation_PAM.hxx"
#endif // CONSTELLATION_PAM_HPP__
| 17.545455
| 56
| 0.773748
|
WilliamMajor
|
69437699b710ac295ab84838f08e2a71666fbe3e
| 30,405
|
cpp
|
C++
|
unittests/snapshot_tests.cpp
|
forfreeday/eos
|
11d35f0f934402321853119d36caeb7022813743
|
[
"Apache-2.0",
"MIT"
] | 13,162
|
2017-05-29T22:08:27.000Z
|
2022-03-29T19:25:05.000Z
|
unittests/snapshot_tests.cpp
|
forfreeday/eos
|
11d35f0f934402321853119d36caeb7022813743
|
[
"Apache-2.0",
"MIT"
] | 6,450
|
2017-05-30T14:41:50.000Z
|
2022-03-30T11:30:04.000Z
|
unittests/snapshot_tests.cpp
|
forfreeday/eos
|
11d35f0f934402321853119d36caeb7022813743
|
[
"Apache-2.0",
"MIT"
] | 4,491
|
2017-05-29T22:08:32.000Z
|
2022-03-29T07:09:52.000Z
|
#include <sstream>
#include <eosio/chain/block_log.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <eosio/chain/kv_chainbase_objects.hpp>
#include <eosio/chain/snapshot.hpp>
#include <eosio/testing/tester.hpp>
#include <eosio/testing/snapshot_suites.hpp>
#include <boost/mpl/list.hpp>
#include <boost/test/unit_test.hpp>
#include <contracts.hpp>
#include <snapshots.hpp>
using namespace eosio::testing;
using namespace eosio::chain;
chainbase::bfs::path get_parent_path(chainbase::bfs::path blocks_dir, int ordinal) {
chainbase::bfs::path leaf_dir = blocks_dir.filename();
if (leaf_dir.generic_string() == std::string("blocks")) {
blocks_dir = blocks_dir.parent_path();
leaf_dir = blocks_dir.filename();
try {
auto ordinal_for_config = boost::lexical_cast<int>(leaf_dir.generic_string());
blocks_dir = blocks_dir.parent_path();
}
catch(const boost::bad_lexical_cast& ) {
// no extra ordinal directory added to path
}
}
return blocks_dir / std::to_string(ordinal);
}
controller::config copy_config(const controller::config& config, int ordinal) {
controller::config copied_config = config;
auto parent_path = get_parent_path(config.blog.log_dir, ordinal);
copied_config.blog.log_dir = parent_path / config.blog.log_dir.filename().generic_string();
copied_config.state_dir = parent_path / config.state_dir.filename().generic_string();
return copied_config;
}
controller::config copy_config_and_files(const controller::config& config, int ordinal) {
controller::config copied_config = copy_config(config, ordinal);
fc::create_directories(copied_config.blog.log_dir);
fc::copy(config.blog.log_dir / "blocks.log", copied_config.blog.log_dir / "blocks.log");
fc::copy(config.blog.log_dir / config::reversible_blocks_dir_name, copied_config.blog.log_dir / config::reversible_blocks_dir_name );
return copied_config;
}
class snapshotted_tester : public base_tester {
public:
enum config_file_handling { dont_copy_config_files, copy_config_files };
snapshotted_tester(controller::config config, const snapshot_reader_ptr& snapshot, int ordinal,
config_file_handling copy_files_from_config = config_file_handling::dont_copy_config_files) {
FC_ASSERT(config.blog.log_dir.filename().generic_string() != "."
&& config.state_dir.filename().generic_string() != ".", "invalid path names in controller::config");
controller::config copied_config = (copy_files_from_config == copy_config_files)
? copy_config_and_files(config, ordinal) : copy_config(config, ordinal);
init(copied_config, snapshot);
}
signed_block_ptr produce_block( fc::microseconds skip_time = fc::milliseconds(config::block_interval_ms) )override {
return _produce_block(skip_time, false);
}
signed_block_ptr produce_empty_block( fc::microseconds skip_time = fc::milliseconds(config::block_interval_ms) )override {
control->abort_block();
return _produce_block(skip_time, true);
}
signed_block_ptr finish_block()override {
return _finish_block();
}
bool validate() { return true; }
};
BOOST_AUTO_TEST_SUITE(snapshot_tests)
namespace {
void variant_diff_helper(const fc::variant& lhs, const fc::variant& rhs, std::function<void(const std::string&, const fc::variant&, const fc::variant&)>&& out){
if (lhs.get_type() != rhs.get_type()) {
out("", lhs, rhs);
} else if (lhs.is_object() ) {
const auto& l_obj = lhs.get_object();
const auto& r_obj = rhs.get_object();
static const std::string sep = ".";
// test keys from LHS
std::set<std::string_view> keys;
for (const auto& entry: l_obj) {
const auto& l_val = entry.value();
const auto& r_iter = r_obj.find(entry.key());
if (r_iter == r_obj.end()) {
out(sep + entry.key(), l_val, fc::variant());
} else {
const auto& r_val = r_iter->value();
variant_diff_helper(l_val, r_val, [&out, &entry](const std::string& path, const fc::variant& lhs, const fc::variant& rhs){
out(sep + entry.key() + path, lhs, rhs);
});
}
keys.insert(entry.key());
}
// print keys in RHS that were not tested
for (const auto& entry: r_obj) {
if (keys.find(entry.key()) != keys.end()) {
continue;
}
const auto& r_val = entry.value();
out(sep + entry.key(), fc::variant(), r_val);
}
} else if (lhs.is_array()) {
const auto& l_arr = lhs.get_array();
const auto& r_arr = rhs.get_array();
// diff common
auto common_count = std::min(l_arr.size(), r_arr.size());
for (size_t idx = 0; idx < common_count; idx++) {
const auto& l_val = l_arr.at(idx);
const auto& r_val = r_arr.at(idx);
variant_diff_helper(l_val, r_val, [&](const std::string& path, const fc::variant& lhs, const fc::variant& rhs){
out( std::string("[") + std::to_string(idx) + std::string("]") + path, lhs, rhs);
});
}
// print lhs additions
for (size_t idx = common_count; idx < lhs.size(); idx++) {
const auto& l_val = l_arr.at(idx);
out( std::string("[") + std::to_string(idx) + std::string("]"), l_val, fc::variant());
}
// print rhs additions
for (size_t idx = common_count; idx < rhs.size(); idx++) {
const auto& r_val = r_arr.at(idx);
out( std::string("[") + std::to_string(idx) + std::string("]"), fc::variant(), r_val);
}
} else if (!(lhs == rhs)) {
out("", lhs, rhs);
}
}
void print_variant_diff(const fc::variant& lhs, const fc::variant& rhs) {
variant_diff_helper(lhs, rhs, [](const std::string& path, const fc::variant& lhs, const fc::variant& rhs){
std::cout << path << std::endl;
if (!lhs.is_null()) {
std::cout << " < " << fc::json::to_pretty_string(lhs) << std::endl;
}
if (!rhs.is_null()) {
std::cout << " > " << fc::json::to_pretty_string(rhs) << std::endl;
}
});
}
template <typename SNAPSHOT_SUITE>
void verify_integrity_hash(const controller& lhs, const controller& rhs) {
const auto lhs_integrity_hash = lhs.calculate_integrity_hash();
const auto rhs_integrity_hash = rhs.calculate_integrity_hash();
if (std::is_same_v<SNAPSHOT_SUITE, variant_snapshot_suite> && lhs_integrity_hash.str() != rhs_integrity_hash.str()) {
auto lhs_latest_writer = SNAPSHOT_SUITE::get_writer();
lhs.write_snapshot(lhs_latest_writer);
auto lhs_latest = SNAPSHOT_SUITE::finalize(lhs_latest_writer);
auto rhs_latest_writer = SNAPSHOT_SUITE::get_writer();
rhs.write_snapshot(rhs_latest_writer);
auto rhs_latest = SNAPSHOT_SUITE::finalize(rhs_latest_writer);
print_variant_diff(lhs_latest, rhs_latest);
}
BOOST_REQUIRE_EQUAL(lhs_integrity_hash.str(), rhs_integrity_hash.str());
}
}
template<typename SnapshotSuite>
void exhaustive_snapshot(const eosio::chain::backing_store_type main_store,
const eosio::chain::backing_store_type sub_store) {
fc::temp_directory temp_dir;
tester chain(temp_dir, [main_store] (auto& config) { config.backing_store = main_store; }, true);
// Create 2 accounts
chain.create_accounts({"snapshot"_n, "snapshot1"_n});
// Set code and increment the first account
chain.produce_blocks(1);
chain.set_code("snapshot"_n, contracts::snapshot_test_wasm());
chain.set_abi("snapshot"_n, contracts::snapshot_test_abi().data());
chain.produce_blocks(1);
chain.push_action("snapshot"_n, "increment"_n, "snapshot"_n, mutable_variant_object()
( "value", 1 )
);
// Set code and increment the second account
chain.produce_blocks(1);
chain.set_code("snapshot1"_n, contracts::snapshot_test_wasm());
chain.set_abi("snapshot1"_n, contracts::snapshot_test_abi().data());
chain.produce_blocks(1);
// increment the test contract
chain.push_action("snapshot1"_n, "increment"_n, "snapshot1"_n, mutable_variant_object()
( "value", 1 )
);
chain.produce_blocks(1);
chain.control->abort_block();
static const int generation_count = 8;
std::list<snapshotted_tester> sub_testers;
for (int generation = 0; generation < generation_count; generation++) {
// create a new snapshot child
auto writer = SnapshotSuite::get_writer();
chain.control->write_snapshot(writer);
auto snapshot = SnapshotSuite::finalize(writer);
// create a new child at this snapshot
auto new_config = chain.get_config();
new_config.backing_store = sub_store;
sub_testers.emplace_back(new_config, SnapshotSuite::get_reader(snapshot), generation);
// increment the test contract
chain.push_action("snapshot"_n, "increment"_n, "snapshot"_n, mutable_variant_object()
( "value", 1 )
);
chain.push_action("snapshot1"_n, "increment"_n, "snapshot1"_n, mutable_variant_object()
( "value", 1 )
);
// produce block
auto new_block = chain.produce_block();
// undo the auto-pending from tester
chain.control->abort_block();
auto integrity_value = chain.control->calculate_integrity_hash();
// push that block to all sub testers and validate the integrity of the database after it.
for (auto& other: sub_testers) {
other.push_block(new_block);
verify_integrity_hash<SnapshotSuite>(*chain.control, *other.control);
BOOST_REQUIRE_EQUAL(integrity_value.str(), other.control->calculate_integrity_hash().str());
}
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_exhaustive_snapshot_cb_to_cb, SNAPSHOT_SUITE, snapshot_suites)
{
exhaustive_snapshot<SNAPSHOT_SUITE>(eosio::chain::backing_store_type::CHAINBASE,
eosio::chain::backing_store_type::CHAINBASE);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_exhaustive_snapshot_cb_to_rdb, SNAPSHOT_SUITE, snapshot_suites)
{
exhaustive_snapshot<SNAPSHOT_SUITE>(eosio::chain::backing_store_type::CHAINBASE,
eosio::chain::backing_store_type::ROCKSDB);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_exhaustive_snapshot_rdb_to_cb, SNAPSHOT_SUITE, snapshot_suites)
{
exhaustive_snapshot<SNAPSHOT_SUITE>(eosio::chain::backing_store_type::ROCKSDB,
eosio::chain::backing_store_type::CHAINBASE);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_exhaustive_snapshot_rdb_to_rdb, SNAPSHOT_SUITE, snapshot_suites)
{
exhaustive_snapshot<SNAPSHOT_SUITE>(eosio::chain::backing_store_type::ROCKSDB,
eosio::chain::backing_store_type::ROCKSDB);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_replay_over_snapshot, SNAPSHOT_SUITE, snapshot_suites)
{
tester chain;
const chainbase::bfs::path parent_path = chain.get_config().blog.log_dir.parent_path();
chain.create_account("snapshot"_n);
chain.produce_blocks(1);
chain.set_code("snapshot"_n, contracts::snapshot_test_wasm());
chain.set_abi("snapshot"_n, contracts::snapshot_test_abi().data());
chain.produce_blocks(1);
chain.control->abort_block();
static const int pre_snapshot_block_count = 12;
static const int post_snapshot_block_count = 12;
for (int itr = 0; itr < pre_snapshot_block_count; itr++) {
// increment the contract
chain.push_action("snapshot"_n, "increment"_n, "snapshot"_n, mutable_variant_object()
( "value", 1 )
);
// produce block
chain.produce_block();
}
chain.control->abort_block();
// create a new snapshot child
auto writer = SNAPSHOT_SUITE::get_writer();
chain.control->write_snapshot(writer);
auto snapshot = SNAPSHOT_SUITE::finalize(writer);
// create a new child at this snapshot
int ordinal = 1;
snapshotted_tester snap_chain(chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), ordinal++);
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *snap_chain.control);
// push more blocks to build up a block log
for (int itr = 0; itr < post_snapshot_block_count; itr++) {
// increment the contract
chain.push_action("snapshot"_n, "increment"_n, "snapshot"_n, mutable_variant_object()
( "value", 1 )
);
// produce & push block
snap_chain.push_block(chain.produce_block());
}
// verify the hash at the end
chain.control->abort_block();
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *snap_chain.control);
// replay the block log from the snapshot child, from the snapshot
using config_file_handling = snapshotted_tester::config_file_handling;
snapshotted_tester replay_chain(snap_chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), ordinal++, config_file_handling::copy_config_files);
const auto replay_head = replay_chain.control->head_block_num();
auto snap_head = snap_chain.control->head_block_num();
BOOST_REQUIRE_EQUAL(replay_head, snap_chain.control->last_irreversible_block_num());
for (auto block_num = replay_head + 1; block_num <= snap_head; ++block_num) {
auto block = snap_chain.control->fetch_block_by_number(block_num);
replay_chain.push_block(block);
}
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *replay_chain.control);
auto block = chain.produce_block();
chain.control->abort_block();
snap_chain.push_block(block);
replay_chain.push_block(block);
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *snap_chain.control);
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *replay_chain.control);
snapshotted_tester replay2_chain(snap_chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), ordinal++, config_file_handling::copy_config_files);
const auto replay2_head = replay2_chain.control->head_block_num();
snap_head = snap_chain.control->head_block_num();
BOOST_REQUIRE_EQUAL(replay2_head, snap_chain.control->last_irreversible_block_num());
for (auto block_num = replay2_head + 1; block_num <= snap_head; ++block_num) {
auto block = snap_chain.control->fetch_block_by_number(block_num);
replay2_chain.push_block(block);
}
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *replay2_chain.control);
// verifies that chain's block_log has a genesis_state (and blocks starting at 1)
controller::config copied_config = copy_config_and_files(chain.get_config(), ordinal++);
auto genesis = eosio::chain::block_log::extract_genesis_state(chain.get_config().blog.log_dir);
BOOST_REQUIRE(genesis);
tester from_block_log_chain(copied_config, *genesis);
const auto from_block_log_head = from_block_log_chain.control->head_block_num();
BOOST_REQUIRE_EQUAL(from_block_log_head, snap_chain.control->last_irreversible_block_num());
for (auto block_num = from_block_log_head + 1; block_num <= snap_head; ++block_num) {
auto block = snap_chain.control->fetch_block_by_number(block_num);
from_block_log_chain.push_block(block);
}
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *from_block_log_chain.control);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_chain_id_in_snapshot, SNAPSHOT_SUITE, snapshot_suites)
{
tester chain;
const chainbase::bfs::path parent_path = chain.get_config().blog.log_dir.parent_path();
chain.create_account("snapshot"_n);
chain.produce_blocks(1);
chain.set_code("snapshot"_n, contracts::snapshot_test_wasm());
chain.set_abi("snapshot"_n, contracts::snapshot_test_abi().data());
chain.produce_blocks(1);
chain.control->abort_block();
// create a new snapshot child
auto writer = SNAPSHOT_SUITE::get_writer();
chain.control->write_snapshot(writer);
auto snapshot = SNAPSHOT_SUITE::finalize(writer);
snapshotted_tester snap_chain(chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), 0);
BOOST_REQUIRE_EQUAL(chain.control->get_chain_id(), snap_chain.control->get_chain_id());
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *snap_chain.control);
}
static auto get_extra_args() {
bool save_snapshot = false;
bool generate_log = false;
auto argc = boost::unit_test::framework::master_test_suite().argc;
auto argv = boost::unit_test::framework::master_test_suite().argv;
std::for_each(argv, argv + argc, [&](const std::string &a){
if (a == "--save-snapshot") {
save_snapshot = true;
} else if (a == "--generate-snapshot-log") {
generate_log = true;
}
});
return std::make_tuple(save_snapshot, generate_log);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_compatible_versions, SNAPSHOT_SUITE, snapshot_suites)
{
const uint32_t legacy_default_max_inline_action_size = 4 * 1024;
bool save_snapshot = false;
bool generate_log = false;
std::tie(save_snapshot, generate_log) = get_extra_args();
const auto source_log_dir = bfs::path(snapshot_file<snapshot::binary>::base_path);
if (generate_log) {
///< Begin deterministic code to generate blockchain for comparison
tester chain(setup_policy::none, db_read_mode::SPECULATIVE, {legacy_default_max_inline_action_size});
chain.create_account("snapshot"_n);
chain.produce_blocks(1);
chain.set_code("snapshot"_n, contracts::snapshot_test_wasm());
chain.set_abi("snapshot"_n, contracts::snapshot_test_abi().data());
chain.produce_blocks(1);
chain.control->abort_block();
// continue until all the above blocks are in the blocks.log
auto head_block_num = chain.control->head_block_num();
while (chain.control->last_irreversible_block_num() < head_block_num) {
chain.produce_blocks(1);
}
auto source = chain.get_config().blog.log_dir / "blocks.log";
auto dest = bfs::path(snapshot_file<snapshot::binary>::base_path) / "blocks.log";
bfs::copy_file(source, source_log_dir / "blocks.log", bfs::copy_option::overwrite_if_exists);
chain.close();
}
auto config = tester::default_config(fc::temp_directory(), legacy_default_max_inline_action_size).first;
auto genesis = eosio::chain::block_log::extract_genesis_state(source_log_dir);
bfs::create_directories(config.blog.log_dir);
bfs::copy(source_log_dir / "blocks.log", config.blog.log_dir / "blocks.log");
tester base_chain(config, *genesis);
std::string current_version = "v5";
int ordinal = 0;
for(std::string version : {"v2", "v3", "v4", "v5"})
{
if(save_snapshot && version == current_version) continue;
static_assert(chain_snapshot_header::minimum_compatible_version <= 2, "version 2 unit test is no longer needed. Please clean up data files");
auto old_snapshot = SNAPSHOT_SUITE::load_from_file("snap_" + version);
BOOST_TEST_CHECKPOINT("loading snapshot: " << version);
snapshotted_tester old_snapshot_tester(base_chain.get_config(), SNAPSHOT_SUITE::get_reader(old_snapshot), ordinal++);
verify_integrity_hash<SNAPSHOT_SUITE>(*base_chain.control, *old_snapshot_tester.control);
// create a latest snapshot
auto latest_writer = SNAPSHOT_SUITE::get_writer();
old_snapshot_tester.control->write_snapshot(latest_writer);
auto latest = SNAPSHOT_SUITE::finalize(latest_writer);
// load the latest snapshot
snapshotted_tester latest_tester(base_chain.get_config(), SNAPSHOT_SUITE::get_reader(latest), ordinal++);
verify_integrity_hash<SNAPSHOT_SUITE>(*base_chain.control, *latest_tester.control);
}
// This isn't quite fully automated. The snapshots still need to be gzipped and moved to
// the correct place in the source tree.
if (save_snapshot)
{
// create a latest snapshot
auto latest_writer = SNAPSHOT_SUITE::get_writer();
base_chain.control->write_snapshot(latest_writer);
auto latest = SNAPSHOT_SUITE::finalize(latest_writer);
SNAPSHOT_SUITE::write_to_file("snap_" + current_version, latest);
}
}
/*
When WTMSIG changes were introduced in 1.8.x, the snapshot had to be able
to store more than a single producer key.
This test intends to make sure that a snapshot from before that change could
be correctly loaded into a new version to facilitate upgrading from 1.8.x
to v2.0.x without a replay.
The original test simulated a snapshot from 1.8.x with an inflight schedule change, loaded it on the newer version and reconstructed the chain via
push_transaction. This is too fragile.
The fix is to save block.log and its corresponding snapshot with infight
schedule changes, load the snapshot and replay the block.log on the new
version, and verify their integrity.
*/
BOOST_AUTO_TEST_CASE_TEMPLATE(test_pending_schedule_snapshot, SNAPSHOT_SUITE, snapshot_suites)
{
static_assert(chain_snapshot_header::minimum_compatible_version <= 2, "version 2 unit test is no longer needed. Please clean up data files");
// consruct a chain by replaying the saved blocks.log
std::string source_log_dir_str = snapshot_file<snapshot::binary>::base_path;
source_log_dir_str += "prod_sched";
const auto source_log_dir = bfs::path(source_log_dir_str.c_str());
const uint32_t legacy_default_max_inline_action_size = 4 * 1024;
auto config = tester::default_config(fc::temp_directory(), legacy_default_max_inline_action_size).first;
auto genesis = eosio::chain::block_log::extract_genesis_state(source_log_dir);
bfs::create_directories(config.blog.log_dir);
bfs::copy(source_log_dir / "blocks.log", config.blog.log_dir / "blocks.log");
tester blockslog_chain(config, *genesis);
// consruct a chain by loading the saved snapshot
auto ordinal = 0;
auto old_snapshot = SNAPSHOT_SUITE::load_from_file("snap_v2_prod_sched");
snapshotted_tester snapshot_chain(blockslog_chain.get_config(), SNAPSHOT_SUITE::get_reader(old_snapshot), ordinal++);
// make sure blockslog_chain and snapshot_chain agree to each other
verify_integrity_hash<SNAPSHOT_SUITE>(*blockslog_chain.control, *snapshot_chain.control);
// extra round of testing
// create a latest snapshot
auto latest_writer = SNAPSHOT_SUITE::get_writer();
snapshot_chain.control->write_snapshot(latest_writer);
auto latest = SNAPSHOT_SUITE::finalize(latest_writer);
// construct a chain from the latest snapshot
snapshotted_tester latest_chain(blockslog_chain.get_config(), SNAPSHOT_SUITE::get_reader(latest), ordinal++);
// make sure both chains agree
verify_integrity_hash<SNAPSHOT_SUITE>(*blockslog_chain.control, *latest_chain.control);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_restart_with_existing_state_and_truncated_block_log, SNAPSHOT_SUITE, snapshot_suites)
{
tester chain;
const chainbase::bfs::path parent_path = chain.get_config().blog.log_dir.parent_path();
chain.create_account("snapshot"_n);
chain.produce_blocks(1);
chain.set_code("snapshot"_n, contracts::snapshot_test_wasm());
chain.set_abi("snapshot"_n, contracts::snapshot_test_abi().data());
chain.produce_blocks(1);
chain.control->abort_block();
static const int pre_snapshot_block_count = 12;
for (int itr = 0; itr < pre_snapshot_block_count; itr++) {
// increment the contract
chain.push_action("snapshot"_n, "increment"_n, "snapshot"_n, mutable_variant_object()
( "value", 1 )
);
// produce block
chain.produce_block();
}
chain.control->abort_block();
// create a new snapshot child
auto writer = SNAPSHOT_SUITE::get_writer();
chain.control->write_snapshot(writer);
auto snapshot = SNAPSHOT_SUITE::finalize(writer);
// create a new child at this snapshot
int ordinal = 1;
snapshotted_tester snap_chain(chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), ordinal++);
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *snap_chain.control);
auto block = chain.produce_block();
chain.control->abort_block();
snap_chain.push_block(block);
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *snap_chain.control);
snap_chain.close();
auto cfg = snap_chain.get_config();
// restart chain with truncated block log and existing state, but no genesis state (chain_id)
snap_chain.open();
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *snap_chain.control);
block = chain.produce_block();
chain.control->abort_block();
snap_chain.push_block(block);
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *snap_chain.control);
}
// Psudo code for the following WAST:
// kv_get(receiver, ...)
// uint64_t buff[1];
// kv_get_data(offset, buff, ...)
// buff[0] = buff[0]++;
// kv_set(receiver, key, key_size, buff, ...)
static const char kv_snapshot_wast[] = R"=====(
(module
(func $kv_get (import "env" "kv_get") (param i64 i32 i32 i32) (result i32))
(func $kv_get_data (import "env" "kv_get_data") (param i32 i32 i32) (result i32))
(func $kv_set (import "env" "kv_set") (param i64 i32 i32 i32 i32 i64) (result i64))
(memory 1)
(func (export "apply") (param i64 i64 i64)
(drop (call $kv_get (get_local 0) (i32.const 0) (i32.const 8) (i32.const 8)))
(drop (call $kv_get_data (i32.const 0) (i32.const 0) (i32.const 8)))
(i64.store (i32.const 0) (i64.add (i64.load (i32.const 0)) (i64.const 1)))
(drop (call $kv_set (get_local 0) (i32.const 16) (i32.const 8) (i32.const 0) (i32.const 8) (get_local 0)))
)
)
)=====";
static const char kv_snapshot_bios[] = R"=====(
(module
(func $set_resource_limit (import "env" "set_resource_limit") (param i64 i64 i64))
(func $kv_set_parameters_packed (import "env" "set_kv_parameters_packed") (param i32 i32))
(memory 1)
(func (export "apply") (param i64 i64 i64)
(call $kv_set_parameters_packed (i32.const 0) (i32.const 16))
(call $kv_set_parameters_packed (i32.const 0) (i32.const 16))
(call $set_resource_limit (get_local 0) (i64.const 13376816793197215744) (i64.const -1))
)
(data (i32.const 4) "\00\04\00\00")
(data (i32.const 8) "\00\00\10\00")
(data (i32.const 12) "\80\00\00\00")
)
)=====";
BOOST_AUTO_TEST_CASE_TEMPLATE(test_kv_snapshot, SNAPSHOT_SUITE, snapshot_suites) {
for (backing_store_type origin_backing_store : { backing_store_type::CHAINBASE, backing_store_type::ROCKSDB }) {
for (backing_store_type resulting_backing_store: { backing_store_type::CHAINBASE, backing_store_type::ROCKSDB }) {
tester chain {setup_policy::full, db_read_mode::SPECULATIVE, std::optional<uint32_t>{}, std::optional<uint32_t>{}, origin_backing_store};
chain.create_accounts({"manager"_n});
auto get_ext = [](unsigned i) {
std::string ext;
do {
unsigned rem = i % 5;
i /= 5;
ext += std::to_string(rem + 1);
} while(i > 0);
std::reverse(ext.begin(), ext.end());
return ext;
};
std::vector<name> contracts;
for (unsigned i = 0; i < 10; ++i) {
name contract { std::string("snapshot") + get_ext(i) };
contracts.push_back(contract);
}
chain.create_accounts(contracts);
chain.set_code("manager"_n, kv_snapshot_bios);
chain.push_action("eosio"_n, "setpriv"_n, "eosio"_n, mutable_variant_object()("account", "manager")("is_priv", 1));
chain.produce_blocks(1);
{
signed_transaction trx;
trx.actions.push_back({{{"manager"_n, "active"_n}}, "manager"_n, "snapshot"_n, {}});
chain.set_transaction_headers(trx);
trx.sign(chain.get_private_key("manager"_n, "active"), chain.control->get_chain_id());
chain.push_transaction(trx);
}
chain.produce_blocks(1);
for (auto contract : contracts) {
chain.set_code(contract, kv_snapshot_wast);
}
chain.produce_blocks(1);
chain.control->abort_block();
static const int generation_count = 8;
std::list<snapshotted_tester> sub_testers;
for (int generation = 0; generation < generation_count; generation++) {
// create a new snapshot child
auto writer = SNAPSHOT_SUITE::get_writer();
chain.control->write_snapshot(writer);
auto snapshot = SNAPSHOT_SUITE::finalize(writer);
auto cfg = chain.get_config();
// Set backing_store for loading snapshot in the child
cfg.backing_store = resulting_backing_store;
// create a new child at this snapshot
sub_testers.emplace_back(cfg, SNAPSHOT_SUITE::get_reader(snapshot), generation);
int contract_gen = 0;
for (auto contract : contracts) {
if (contract_gen++ > generation)
break; // ensure that every entry in the KV tables are not just exactly the same data
// Calling apply method which will increment the
// current value stored
signed_transaction trx;
trx.actions.push_back({{{contract, "active"_n}}, contract, "eosio.kvram"_n, {}});
chain.set_transaction_headers(trx);
trx.sign(chain.get_private_key(contract, "active"), chain.control->get_chain_id());
chain.push_transaction(trx);
}
// produce block
auto new_block = chain.produce_block();
#warning TODO: adding verification of the kv_object content and storing more than one key so that snapshot looping is tested
// undo the auto-pending from tester
chain.control->abort_block();
auto integrity_value = chain.control->calculate_integrity_hash();
// push that block to all sub testers and validate the integrity of the database after it.
for (auto& other: sub_testers) {
other.push_block(new_block);
verify_integrity_hash<SNAPSHOT_SUITE>(*chain.control, *other.control);
BOOST_REQUIRE_EQUAL(integrity_value.str(), other.control->calculate_integrity_hash().str());
}
}
}
}
}
BOOST_AUTO_TEST_SUITE_END()
| 42.643759
| 163
| 0.68617
|
forfreeday
|
694409f0b03164d37256e9935ce970573501d858
| 2,117
|
cpp
|
C++
|
tests/basic_query_match_test.cpp
|
HardwareIR/netlistDB
|
2c52a1c88b7be712d6cdc9146f1a9dbf26441198
|
[
"MIT"
] | 14
|
2019-03-27T00:53:06.000Z
|
2021-12-13T15:18:04.000Z
|
tests/basic_query_match_test.cpp
|
PDFxy/netlistDB
|
2c52a1c88b7be712d6cdc9146f1a9dbf26441198
|
[
"MIT"
] | 11
|
2019-02-25T18:43:48.000Z
|
2019-06-13T15:00:33.000Z
|
tests/basic_query_match_test.cpp
|
HardwareIR/hardwareIr
|
2c52a1c88b7be712d6cdc9146f1a9dbf26441198
|
[
"MIT"
] | 2
|
2020-03-12T06:01:13.000Z
|
2021-04-09T10:00:32.000Z
|
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE netlistDB_basic_query_test
#include <boost/test/unit_test.hpp>
#include <functional>
#include <iostream>
#include <fstream>
#include <stdint.h>
#include <netlistDB/netlist.h>
#include <netlistDB/statement_if.h>
#include <netlistDB/query/query_match.h>
#include <netlistDB/query/query_path.h>
#include <netlistDB/hw_type/common.h>
using namespace netlistDB;
using namespace netlistDB::query;
using namespace netlistDB::hw_type;
BOOST_AUTO_TEST_SUITE( netlistDB_testsuite )
BOOST_AUTO_TEST_CASE( query_result_of_add ) {
Netlist ctx("adder");
std::vector<std::tuple<Net *, Net *, Net *>> expected;
size_t n = 20;
for (size_t i = 0; i < n; i++) {
auto &a = ctx.sig_in("a", hw_int32);
auto &b = ctx.sig_in("b", hw_int32);
auto &res = a + b;
expected.push_back( { &a, &b, &res });
// add some garbage
auto & c = ctx.sig_in("c", hw_int32);
~a;
res & c;
auto path = QueryPath::find_path(a, res);
BOOST_CHECK_EQUAL(path.second, true);
BOOST_CHECK_EQUAL(path.first.size(), 3);
if (path.first.size() == 3) {
std::vector<iNode*> ref = { &a, res.drivers[0], &res };
size_t i = 0;
for (auto p : path.first) {
BOOST_CHECK_EQUAL(p, ref[i]);
i++;
}
}
}
QueryMatch query_add;
auto &r = query_add.sig_in("a", hw_int32) + query_add.sig_in("b", hw_int32);
r.direction = Direction::DIR_OUT;
auto qres = query_add.search(ctx);
BOOST_CHECK_EQUAL(qres.size(), n);
}
BOOST_AUTO_TEST_CASE( simple_mux ) {
Netlist ctx("mux");
size_t N = 1;
for (size_t i = 0; i < N; i++) {
auto &a = ctx.sig_in("a", hw_bit);
auto &b = ctx.sig_in("b", hw_bit);
auto &c = ctx.sig_in("c", hw_bit);
If(a)( { &a(b), }).Else( { &a(c), });
}
QueryMatch q_mux;
auto &qa = q_mux.sig_in("a", hw_bit);
auto &qb = q_mux.sig_in("b", hw_bit);
auto &qc = q_mux.sig_in("c", hw_bit);
If(qa)( { &qa(qb), }).Else( { &qa(qc), });
auto qres = q_mux.search(q_mux);
BOOST_CHECK_EQUAL(qres.size(), 1);
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_SUITE_END()
| 24.056818
| 80
| 0.667454
|
HardwareIR
|
69451b4c9948071c013fde7618500ca36e68298f
| 1,442
|
cpp
|
C++
|
lib/cpalgo/graph/tests/articulation_points_test.cpp
|
xirc/cp-algorithm
|
89c67cff2f00459c5bb020ab44bff5ae419a1728
|
[
"Apache-2.0"
] | 8
|
2020-12-23T07:54:53.000Z
|
2021-11-23T02:46:35.000Z
|
lib/cpalgo/graph/tests/articulation_points_test.cpp
|
xirc/cp-algorithm
|
89c67cff2f00459c5bb020ab44bff5ae419a1728
|
[
"Apache-2.0"
] | 1
|
2020-11-07T13:22:29.000Z
|
2020-12-20T12:54:00.000Z
|
lib/cpalgo/graph/tests/articulation_points_test.cpp
|
xirc/cp-algorithm
|
89c67cff2f00459c5bb020ab44bff5ae419a1728
|
[
"Apache-2.0"
] | 1
|
2021-01-16T03:40:10.000Z
|
2021-01-16T03:40:10.000Z
|
#include <bits/stdc++.h>
#include "gtest/gtest.h"
#include "cpalgo/graph/articulation_points.hpp"
using namespace std;
TEST(ArticulationPointsTest, IsEmptyInitially) {
ArticulationPoints solver;
EXPECT_EQ(0ULL, solver.size());
}
TEST(ArticulationPointsTest, ShouldComputeArticulationPointsInCase1) {
size_t const N = 4;
ArticulationPoints solver(N);
// articulation_points_testcase1
solver.add_edge(0, 1);
solver.add_edge(0, 2);
solver.add_edge(1, 2);
solver.add_edge(2, 3);
auto aps = solver.solve();
EXPECT_EQ(aps, vector<size_t>({ 2ULL }));
}
TEST(ArticulationPointsTest, ShouldComputeArticulationPointsInCase2) {
size_t const N = 5;
ArticulationPoints solver(N);
// articulation_points_testcase2
solver.add_edge(0, 1);
solver.add_edge(1, 2);
solver.add_edge(2, 3);
solver.add_edge(3, 4);
auto aps = solver.solve();
sort(aps.begin(), aps.end());
EXPECT_EQ(aps, vector<size_t>({ 1ULL, 2ULL, 3ULL }));
}
TEST(ArticulationPointsTest, ShouldComputeArticulationPointsInCase3) {
size_t const N = 5;
ArticulationPoints solver(N);
// articulation_points_testcase3
solver.add_edge(0, 1);
solver.add_edge(0, 2);
solver.add_edge(0, 2);
solver.add_edge(1, 2);
solver.add_edge(2, 3);
solver.add_edge(2, 3);
auto aps = solver.solve();
sort(aps.begin(), aps.end());
EXPECT_EQ(aps, vector<size_t>({ 2ULL }));
}
| 24.862069
| 70
| 0.678918
|
xirc
|
69455c396ce5f6d8aeae6d67c8b5f42b40ff9db4
| 4,394
|
hpp
|
C++
|
CKGfx/Context.hpp
|
samkusin/overview
|
affddf0b21f7e76ad9dae1425a4f5ac6a29a24c1
|
[
"MIT"
] | null | null | null |
CKGfx/Context.hpp
|
samkusin/overview
|
affddf0b21f7e76ad9dae1425a4f5ac6a29a24c1
|
[
"MIT"
] | null | null | null |
CKGfx/Context.hpp
|
samkusin/overview
|
affddf0b21f7e76ad9dae1425a4f5ac6a29a24c1
|
[
"MIT"
] | null | null | null |
//
// Context.hpp
// GfxPrototype
//
// Created by Samir Sinha on 9/26/15.
//
//
#ifndef CK_Graphics_Context_hpp
#define CK_Graphics_Context_hpp
#include "GfxTypes.hpp"
#include <cinek/managed_dictionary.hpp>
#include <functional>
namespace cinek {
namespace gfx {
class Context
{
public:
struct ResourceInitParams
{
uint32_t numMeshes;
uint32_t numMaterials;
uint32_t numTextures;
uint32_t numAnimations;
uint32_t numLights;
uint32_t numModelSets;
};
Context() = default;
explicit Context(const ResourceInitParams& params);
// Used for texture loading by an external system. The external system
// uses the supplied name to load a Texture, and then to use the context
// to register it.
using TextureLoadDelegate = std::function<Texture(Context&, const std::string&)>;
// Sets the Texture load delegate issued when a call to loadTexture is
// made.
void setTextureLoadDelegate(TextureLoadDelegate delegate);
TextureLoadDelegate textureLoadDelegate() const;
// Run periodically to update the context's state. State in this case
// includes file I/O, resource cleanup and other periodic functions
void update();
// Generates a MeshHandle for system-wide persistance
MeshHandle registerMesh(Mesh&& mesh);
// Generates a TextureHandle for system-wide persistance and maps it to
// a key name
TextureHandle registerTexture(Texture&& texture, const char* name="");
// Loads a Texture using the file system (see cinek::file for details on
// customizing the file interface.) The texture may not be loaded
// immediately - so the returned texture could be empty, but filled in
// at a later time (i.e. asynchronously, if the underlying system supports
// async file IO.)
TextureHandle loadTexture(const char* pathname);
// Unregisters the named Texture from the Context's dictionary
void unregisterTexture(const char* name);
// Finds a texture from the Context's dictionary
TextureHandle findTexture(const char* name) const;
// Generates a MaterialHandle for system-wide persistance and maps it to
// a key name
MaterialHandle registerMaterial(Material&& material, const char* name="");
// Unregisters the named Material
void unregisterMaterial(const char* name);
// Finds a named Material
MaterialHandle findMaterial(const char* name) const;
// Generates an AnimationSet handle for system-wide persistance and maps it
// optionally to a name
AnimationSetHandle registerAnimationSet(AnimationSet&& animation, const char* name="");
// Unregisters the named AnimationSet
void unregisterAnimationSet(const char* name);
// Finds an AnimationSet given its name
AnimationSetHandle findAnimationSet(const char* name) const;
// Registers a light handle
LightHandle registerLight(Light&& light);
// Registers a NodeGraph Model with an noptinoal name
ModelSetHandle registerModelSet(ModelSet&& modelSet, const char* name="");
// Unregisters a Model
void unregisterModelSet(const char *name);
// Finds a Model given its name
ModelSetHandle findModelSet(const char* name) const;
private:
// restrict Context access to pointer and reference -
// copying of contexts is prohibited and move operations limited to
// construction
//
// contexts can only be explicitly created and destroyed
Context(const Context&);
Context& operator=(const Context&);
Context& operator=(Context&&);
private:
MeshPool _meshes;
MaterialPool _materials;
TexturePool _textures;
AnimationSetPool _animationSets;
LightPool _lights;
ModelSetPool _modelSets;
using TextureDictionary = ManagedDictionary<TextureHandle>;
using MaterialDictionary = ManagedDictionary<MaterialHandle>;
using AnimationSetDictionary = ManagedDictionary<AnimationSetHandle>;
using ModelSetDictionary = ManagedDictionary<ModelSetHandle>;
TextureDictionary _textureDictionary;
MaterialDictionary _materialDictionary;
AnimationSetDictionary _animationSetDictionary;
ModelSetDictionary _modelSetDictionary;
TextureLoadDelegate _textureLoadDelegate;
};
} // namespace gfx
} // namespace cinek
#endif
| 35.152
| 91
| 0.715066
|
samkusin
|
694c8798ea55938161cafa427afe7b5af78ae55d
| 722
|
cc
|
C++
|
src/llvm-backend/deserialise_ir/deserialise_protobuf.cc
|
paulocoghi/bolt
|
a81627f95af6577cd465df09290a51c9d469c667
|
[
"MIT"
] | 305
|
2020-05-08T11:09:53.000Z
|
2022-03-19T18:43:58.000Z
|
src/llvm-backend/deserialise_ir/deserialise_protobuf.cc
|
paulocoghi/bolt
|
a81627f95af6577cd465df09290a51c9d469c667
|
[
"MIT"
] | 53
|
2019-11-10T13:46:46.000Z
|
2022-02-04T17:20:15.000Z
|
src/llvm-backend/deserialise_ir/deserialise_protobuf.cc
|
paulocoghi/bolt
|
a81627f95af6577cd465df09290a51c9d469c667
|
[
"MIT"
] | 33
|
2020-05-09T00:35:53.000Z
|
2022-03-14T21:10:25.000Z
|
#include "src/llvm-backend/deserialise_ir/deserialise_protobuf.h"
#include <stdlib.h>
#include <fstream>
#include <string>
#include "src/llvm-backend/deserialise_ir/program_ir.h"
Frontend_ir::program deserialiseProtobufFile(std::string &filePath) {
Frontend_ir::program program;
std::fstream fileIn(filePath, std::ios::in | std::ios::binary);
if (!fileIn) {
throw DeserialiseProtobufException("File not found.");
}
if (!program.ParseFromIstream(&fileIn)) {
throw DeserialiseProtobufException("Protobuf not deserialised from file.");
}
return program;
}
std::unique_ptr<ProgramIR> protobufToIR(const Frontend_ir::program &program) {
return std::unique_ptr<ProgramIR>(new ProgramIR(program));
}
| 28.88
| 79
| 0.750693
|
paulocoghi
|
695086470a997d5e73f6aedb43fa5aa013ba8cee
| 101
|
cpp
|
C++
|
Ping/graph.cpp
|
siddhantkhandelwal/Hello-world
|
fc08cc3aef52992cbec0d76dd4572d6cd69bbc93
|
[
"MIT"
] | null | null | null |
Ping/graph.cpp
|
siddhantkhandelwal/Hello-world
|
fc08cc3aef52992cbec0d76dd4572d6cd69bbc93
|
[
"MIT"
] | null | null | null |
Ping/graph.cpp
|
siddhantkhandelwal/Hello-world
|
fc08cc3aef52992cbec0d76dd4572d6cd69bbc93
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<graphics.h>
void main()
{
line (0,0,1280,800);
getch();
}
| 12.625
| 25
| 0.564356
|
siddhantkhandelwal
|
6950d8a7fd4013470461beebe950ad6ae8d08514
| 4,026
|
cpp
|
C++
|
gui/dialogs/HoughTransformDialog.cpp
|
frooms/stira
|
60b419f3e478397a8ab43ce9315a259567d94a26
|
[
"MIT"
] | 8
|
2016-03-23T08:12:33.000Z
|
2022-01-25T14:07:03.000Z
|
gui/dialogs/HoughTransformDialog.cpp
|
frooms/stira
|
60b419f3e478397a8ab43ce9315a259567d94a26
|
[
"MIT"
] | null | null | null |
gui/dialogs/HoughTransformDialog.cpp
|
frooms/stira
|
60b419f3e478397a8ab43ce9315a259567d94a26
|
[
"MIT"
] | 8
|
2015-06-29T12:00:06.000Z
|
2019-09-03T12:40:47.000Z
|
/***********************************************************************************
* Copyright (C) 2016 by Filip Rooms *
* *
* Terms and conditions for using this software in any form are provided in the *
* file COPYING, which can be found in the root directory of this project. *
* *
* Contact data: filip.rooms@gmail.com *
* http://www.filiprooms.be/ *
* *
***********************************************************************************/
#include "HoughTransformDialog.h"
#include "../src/MainWindow.h"
#include "../processes/HoughTransformProcess.h"
using namespace std;
using namespace stira::imagedata;
using namespace stira::imagetools;
HoughTransformDialog::HoughTransformDialog( Image* pImage ) : DialogMaster( pImage )
{
mpProcess = 0;
mpTitelLabel->setText( QString("<b>Hough Transform Parameters</b>") );
mpChooseHoughTransformTypeBox = new QGroupBox( tr( "&Choose Hough type" ) );
mpChooseCircleHoughTransformRadioButton = new QRadioButton( "Circles" );
mpChooseLineHoughTransformRadioButton = new QRadioButton( "Lines" );
mpChooseHoughTransformLayout = new QVBoxLayout;
mpChooseHoughTransformLayout->addWidget(mpChooseCircleHoughTransformRadioButton);
mpChooseHoughTransformLayout->addWidget(mpChooseLineHoughTransformRadioButton);
mpChooseHoughTransformTypeBox->setLayout(mpChooseHoughTransformLayout);
mpChooseCircleHoughTransformRadioButton->setChecked(true);
mpMaximalRadiusLabel = new QLabel("Max circle radius");
mpMaximalRadiusLayout = new QHBoxLayout;
mpMaximalRadiusLineEdit = new QLineEdit("100");
mpMaximalRadiusLayout->addWidget(mpMaximalRadiusLabel);
mpMaximalRadiusLayout->addWidget(mpMaximalRadiusLineEdit);
mpMinimalRadiusLabel = new QLabel("Min circle radius");
mpMinimalRadiusLayout = new QHBoxLayout;
mpMinimalRadiusLineEdit = new QLineEdit("80");
mpMinimalRadiusLayout->addWidget(mpMinimalRadiusLabel);
mpMinimalRadiusLayout->addWidget(mpMinimalRadiusLineEdit);
mpDialogLayout->addWidget( mpTitelLabel );
mpDialogLayout->addWidget( mpChooseHoughTransformTypeBox );
mpDialogLayout->addLayout( mpMaximalRadiusLayout );
mpDialogLayout->addLayout( mpMinimalRadiusLayout );
mpDialogLayout->addWidget( mpMessageLabel );
mpDialogLayout->addLayout( mpButtonLayout );
this->show();
}
//------------------------------------------------------------------
HoughTransformDialog::~HoughTransformDialog()
{
if (mpProcess != 0)
{
delete mpProcess;
}
}
//------------------------------------------------------------------
int HoughTransformDialog::GetMaximalRadius()
{
return mpMaximalRadiusLineEdit->text().toInt();
}
//------------------------------------------------------------------
int HoughTransformDialog::GetMinimalRadius()
{
return mpMinimalRadiusLineEdit->text().toInt();
}
bool HoughTransformDialog::DidChooseCircles()
{
return mpChooseCircleHoughTransformRadioButton->isChecked();
}
//------------------------------------------------------------------
void HoughTransformDialog::SlotRun()
{
mpProcess = new HoughTransformProcess( mpInputImage );
connect( mpProcess, SIGNAL( finished() ), this, SLOT( SlotProcessResult() ) );
mpProcess->SetMaximalRadius( this->GetMaximalRadius() );
mpProcess->SetMinimalRadius( this->GetMinimalRadius() );
mpProcess->SetChooseCircles( this->DidChooseCircles() );
mpProcess->start();
}
//--------------------------------------------------------
Process* HoughTransformDialog::GetProcess()
{
return mpProcess;
}
//------------------------------------------------------------------
| 38.342857
| 85
| 0.575261
|
frooms
|
6953a5d4532d05fe2bcc4a139c77b69f7dcf9693
| 1,970
|
cpp
|
C++
|
Data/Note.cpp
|
zmeyc/notetrainer
|
0c046d7db5402a84a1085a51bd4e9b9eac5d4adf
|
[
"MIT"
] | 3
|
2016-04-06T16:57:48.000Z
|
2019-01-01T08:51:07.000Z
|
Data/Note.cpp
|
zmeyc/notetrainer
|
0c046d7db5402a84a1085a51bd4e9b9eac5d4adf
|
[
"MIT"
] | 3
|
2016-03-14T19:43:25.000Z
|
2021-11-24T03:52:18.000Z
|
Data/Note.cpp
|
zmeyc/notetrainer
|
0c046d7db5402a84a1085a51bd4e9b9eac5d4adf
|
[
"MIT"
] | null | null | null |
// NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information.
#include <QHash>
#include "Note.h"
#include "Utils/Utils.h"
Note::Note(Note::Pitch pitch, int octave)
: pitch_(pitch)
, octave_(octave)
{
}
Note Note::noteFromKey(int key)
{
Note note;
note.setPitch((Note::Pitch)(key % 12));
note.setOctave(-1 + key / 12);
return note;
}
QString Note::pitchName(Note::Pitch pitch)
{
switch (pitch) {
case Pitch::C: return "do";
case Pitch::Cis: return "di";
case Pitch::D: return "re";
case Pitch::Ees: return "me";
case Pitch::E: return "mi";
case Pitch::F: return "fa";
case Pitch::Fis: return "fi";
case Pitch::G: return "so";
case Pitch::Aes: return "lu";
case Pitch::A: return "la";
case Pitch::Bes: return "se";
case Pitch::B: return "si";
default: break;
}
return "?";
}
QString Note::pitchName() const
{
return pitchName(pitch_);
}
bool Note::isFilled() const
{
switch (pitch_) {
case Pitch::C:
case Pitch::D:
case Pitch::E:
case Pitch::Fis:
case Pitch::Aes:
case Pitch::Bes:
return true;
default:
break;
}
return false;
}
Note::Pitch Note::pitch() const
{
return pitch_;
}
void Note::setPitch(const Pitch &pitch)
{
pitch_ = pitch;
}
int Note::octave() const
{
return octave_;
}
void Note::setOctave(int octave)
{
octave_ = octave;
}
bool Note::operator==(const Note &other) const
{
return pitch_ == other.pitch_ && octave_ == other.octave_;
}
bool Note::operator<(const Note &other) const
{
return octave_ < other.octave_ ||
(octave_ == other.octave_ && pitch_ < other.pitch_);
}
uint qHash(Note note)
{
return ::qHash((int)note.pitch()) ^ ::qHash(note.octave());
}
QTextStream &operator<<(QTextStream &s, const Note ¬e)
{
return s << "{ octave: " << (int)note.octave() << ", pitch: " << (int)note.pitch() << " }";
}
| 18.942308
| 95
| 0.598985
|
zmeyc
|
6955d1915628874359f1f8f2a24da84badaaab04
| 2,559
|
cpp
|
C++
|
March Challenge 2020 Division 2/Ada Bishop 2.cpp
|
geekcodershivam/CodeChef-Solution
|
7b92a18c3dfbb76c58f4e4b974a0b93b3a43e16d
|
[
"MIT"
] | 1
|
2020-03-12T14:30:37.000Z
|
2020-03-12T14:30:37.000Z
|
March Challenge 2020 Division 2/Ada Bishop 2.cpp
|
geekcodershivam/CodeChef-Solution
|
7b92a18c3dfbb76c58f4e4b974a0b93b3a43e16d
|
[
"MIT"
] | null | null | null |
March Challenge 2020 Division 2/Ada Bishop 2.cpp
|
geekcodershivam/CodeChef-Solution
|
7b92a18c3dfbb76c58f4e4b974a0b93b3a43e16d
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define endl "\n"
typedef long long int ll;
void printBoard(ll r, ll c){
ll row = 2, col = 2;
ll count = 0;
while(row != 2 || col != 8){
cout << row << " " << col << endl;
if(count % 2 == 0){
row = row - 1;
}
else{
row = row + 1;
}
col++;
count++;
}
cout << row << " " << col << endl;
cout << row + 1 << " " << col - 1 << endl; row++; col--;
cout << row + 1 << " " << col + 1 << endl; count = 0;
while(row != 3 || col != 1){
cout << row << " " << col << endl;
if(count % 2 == 0){
row = row + 1;
}
else{
row = row - 1;
}
col--;
count++;
}
cout << row << " " << col << endl;
cout << row + 1 << " " << col + 1 << endl; row++; col++;
cout << row + 1 << " " << col - 1 << endl; row = row + 2; count = 0;
while(row != 6 || col != 8){
cout << row << " " << col << endl;
if(count % 2 == 0){
row = row - 1;
}
else{
row = row + 1;
}
col++;
count++;
}
cout << row << " " << col << endl;
cout << row + 1 << " " << col - 1 << endl; row++; col--;
cout << row + 1 << " " << col + 1 << endl; count = 0;
while(row != 7 || col != 1){
cout << row << " " << col << endl;
if(count % 2 == 0){
row = row + 1;
}
else{
row = row - 1;
}
col--;
count++;
}
cout << row << " " << col << endl;
}
int main()
{
fast;
ll t;
cin >> t;
while(t--){
ll r, c;
cin >> r >> c;
ll ans = 34;
if(r != 1 || c != 1){
if(r != c){
cout << ans + 2 << endl;
cout << (r + c) / 2 << " " << (r + c) / 2 << endl;
cout << 1 << " " << 1 << endl;
printBoard(1, 1);
}
else{
cout << ans + 1 << endl;
cout << 1 << " " << 1 << endl;
printBoard(1, 1);
}
}
else{
cout << ans << endl;
printBoard(1, 1);
}
}
return 0;
}
| 26.65625
| 79
| 0.309887
|
geekcodershivam
|
695a1808469b0a3ec21c8b35c1a495357d2f34e8
| 5,319
|
cpp
|
C++
|
Engine/Src/SFEngineDLL/Java/JniConnection.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | 1
|
2020-06-20T07:35:25.000Z
|
2020-06-20T07:35:25.000Z
|
Engine/Src/SFEngineDLL/Java/JniConnection.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | null | null | null |
Engine/Src/SFEngineDLL/Java/JniConnection.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) 2016 StormForge
//
// Author : KyungKun Ko
//
// Description : Connection
//
//
////////////////////////////////////////////////////////////////////////////////
#include "SFEngineDLLPCH.h"
#if SF_PLATFORM == SF_PLATFORM_ANDROID
#include <jni.h>
#include <android/configuration.h>
#include <android/native_activity.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include "SFAssert.h"
#include "Util/SFUtility.h"
#include "Application/Android/AndroidApp.h"
#include "Application/Android/AndroidAppTasks.h"
#include "Util/SFLog.h"
#include "Object/SFObject.h"
#include "Service/SFEngineService.h"
#include "Net/SFConnectionMUDP.h"
#include "Net/SFMessage.h"
#include "Protocol/SFProtocol.h"
#include "JniUtil.h"
namespace SF
{
}
using namespace SF;
extern "C"
{
//////////////////////////////////////////////////////////////////////////////////////
//
// Connection interface
//
JNIEXPORT jlong JNICALL Java_com_SF_SFConnection_NativeCreateConnection(JNIEnv* env)
{
auto pConnection = new(Service::NetSystem->GetHeap()) Net::ConnectionMUDPClient(Service::NetSystem->GetHeap());
return (jlong)(Net::Connection*)pConnection;
}
//JNIEXPORT void JNICALL Java_com_SF_SFConnection_NativeDestroyConnection(JNIEnv* env, jobject thisConnection, jlong nativeHandle)
//{
// if (nativeHandle == 0)
// return;
// auto pConnection = (Net::Connection*)nativeHandle;
// pConnection->
//}
JNIEXPORT int JNICALL Java_com_SF_SFConnection_NativeConnect(JNIEnv* env, jobject thisConnection, jlong nativeHandle, long authTicket, jstring address, int port)
{
if (nativeHandle == 0)
return ResultCode::INVALID_ARG;
const char *nativeAddress = env->GetStringUTFChars(address, 0);
NetAddress remoteAddress(nativeAddress, port);
env->ReleaseStringUTFChars(address, nativeAddress);
auto pConnection = (Net::Connection*)nativeHandle;
return pConnection->Connect(Net::PeerInfo(NetClass::Client, authTicket), Net::PeerInfo(NetClass::Unknown, remoteAddress, 0));
}
JNIEXPORT void JNICALL Java_com_SF_SFConnection_NativeDisconnect(JNIEnv* env, jobject thisConnection, jlong nativeHandle)
{
if (nativeHandle == 0)
return;
auto pConnection = (Net::Connection*)nativeHandle;
pConnection->Disconnect("Requested from java");
}
JNIEXPORT int JNICALL Java_com_SF_SFConnection_NativeGetState(JNIEnv* env, jobject thisConnection, jlong nativeHandle)
{
if (nativeHandle == 0)
return 0;
auto pConnection = (Net::Connection*)nativeHandle;
return (int)pConnection->GetConnectionState();
}
jobject GetEnumFieldValue(JNIEnv* env, const char* enumTypePath, const char* enumValueName)
{
char enumTypeSig[1024];
StrUtil::Format(enumTypeSig, "L{0};", enumTypePath);
jclass jclsEventTypes = env->FindClass(enumTypePath);
jfieldID eventTypeFiledID = env->GetStaticFieldID(jclsEventTypes, enumValueName, enumTypeSig);
jobject enumValue = env->GetStaticObjectField(jclsEventTypes, eventTypeFiledID);
return enumValue;
}
JNIEXPORT jobject JNICALL Java_com_SF_SFConnection_NativeDequeueEvent(JNIEnv* env, jobject thisConnection, jlong nativeHandle)
{
if (nativeHandle == 0)
return 0;
auto pConnection = (Net::Connection*)nativeHandle;
// Create java event object
static jclass jcls = env->FindClass("java/com/sf/SFConnection$Event");
//jmethodID mID1 = env->GetMethodID(jcls, "<init>", "()V"); // default constructor
static jmethodID connectionStatusConstructorID = env->GetMethodID(jcls, "<init>", "(I;I;I)V"); // parameterzed
//jobject jobj = env->AllocObject(jcls);
Net::ConnectionEvent conEvent;
if (pConnection->DequeueConnectionEvent(conEvent))
{
jobject jobj = env->NewObject(jcls, connectionStatusConstructorID, (int)conEvent.Components.EventType, (int)conEvent.Components.State, (int)conEvent.Components.hr);
return jobj;
}
return nullptr;
}
JNIEXPORT jobject JNICALL Java_com_SF_SFConnection_NativeDequeueMessage(JNIEnv* env, jobject thisConnection, jlong nativeHandle)
{
if (nativeHandle == 0)
return 0;
auto pConnection = (Net::Connection*)nativeHandle;
// Create java message object
static jclass jcls = env->FindClass("java/com/sf/SFMessage");
static jmethodID constructorID = env->GetMethodID(jcls, "<init>", "(I)V");
static jmethodID setValueID = env->GetMethodID(jcls, "SetValue", "(Ljava/lang/String;Ljava/lang/Object)V");
static jmethodID setVariableSizeValueID = env->GetMethodID(jcls, "SetValue", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object)V");
//static jmethodID getValuesID = env->GetMethodID(jcls, "GetValues", "()Ljava/lang/Object");
//jobject jobj = env->AllocObject(jcls);
MessageDataPtr pIMsg;
if (!pConnection->GetRecvMessage(pIMsg))
return nullptr;
jobject jobj = env->NewObject(jcls, constructorID, pIMsg->GetMessageHeader()->msgID.ID);
// Fill parameters
VariableMapBuilderJObject builder(env, jobj, setValueID, setVariableSizeValueID);
if (!SF::Protocol::ParseMessage(pIMsg, builder))
return nullptr;
return jobj;
}
}
#endif
| 30.745665
| 168
| 0.690167
|
blue3k
|
695fd35921fd6c3f13fa42f39e9a96fe239e1214
| 979
|
hpp
|
C++
|
test/test_utils/read_orlib_sc.hpp
|
Kommeren/AA
|
e537b58d50e93d4a72709821b9ea413008970c6b
|
[
"BSL-1.0"
] | null | null | null |
test/test_utils/read_orlib_sc.hpp
|
Kommeren/AA
|
e537b58d50e93d4a72709821b9ea413008970c6b
|
[
"BSL-1.0"
] | null | null | null |
test/test_utils/read_orlib_sc.hpp
|
Kommeren/AA
|
e537b58d50e93d4a72709821b9ea413008970c6b
|
[
"BSL-1.0"
] | 1
|
2021-02-24T06:23:56.000Z
|
2021-02-24T06:23:56.000Z
|
/**
* @file read_orlib_sc.hpp
* @brief
* @author Piotr Smulewicz
* @version 1.0
* @date 2013-08-01
*/
#ifndef PAAL_READ_ORLIB_SC_HPP
#define PAAL_READ_ORLIB_SC_HPP
#include <boost/range/irange.hpp>
#include <cassert>
#include <vector>
#include <utility>
#include <istream>
namespace paal {
inline
std::pair<std::vector<int>, std::vector<std::vector<int>>>
read_ORLIB_SC(std::istream &ist) {
assert(ist.good());
int number_of_elements, number_of_set, cov, setI_id;
ist >> number_of_elements >> number_of_set;
std::vector<std::vector<int>> sets(number_of_set);
std::vector<int> costs(number_of_set);
for (auto &cost:costs) {
ist >> cost;
}
for (int i:boost::irange(0,number_of_elements)) {
ist >> cov;
for (int j = 0; j < cov; j++) {
ist >> setI_id;
sets[setI_id - 1].push_back(i);
}
}
return std::make_pair(costs, sets);
}
} //! paal
#endif /* PAAL_READ_ORLIB_SC_HPP */
| 21.282609
| 58
| 0.629213
|
Kommeren
|
69608d372051022abd4a6f04b4893c4da5b81328
| 2,346
|
cpp
|
C++
|
VisualStudio/LoaderXML/Source/LoaderXML.cpp
|
L0mion/Makes-a-Click
|
c7f53a53ea3a58da027ea5f00176352edb914718
|
[
"MIT"
] | 1
|
2016-04-28T06:24:15.000Z
|
2016-04-28T06:24:15.000Z
|
VisualStudio/LoaderXML/Source/LoaderXML.cpp
|
L0mion/Makes-a-Click
|
c7f53a53ea3a58da027ea5f00176352edb914718
|
[
"MIT"
] | null | null | null |
VisualStudio/LoaderXML/Source/LoaderXML.cpp
|
L0mion/Makes-a-Click
|
c7f53a53ea3a58da027ea5f00176352edb914718
|
[
"MIT"
] | null | null | null |
#include <rapidxml.hpp>
//Parser_XML
#include <ParserXML.h>
#include <DocXML.h>
//Util
#include <Util.h>
#include "WinDetective.h"
#include "InterpreterXML.h"
#include "LoaderXML.h"
namespace Loader_XML {
LoaderXML::LoaderXML(
std::wstring p_filePathToSearch,
std::wstring p_fileEnding,
bool p_recursiveSearch) {
m_filePathToSearch = p_filePathToSearch;
m_fileEnding = p_fileEnding;
m_recursiveSearch = p_recursiveSearch;
m_winDetective = nullptr;
}
LoaderXML::~LoaderXML() {
if( m_winDetective != nullptr ) {
delete m_winDetective;
}
}
bool LoaderXML::init( Util::MacDesc& inout_result ) {
m_winDetective = new WinDetective(
m_filePathToSearch,
m_fileEnding,
m_recursiveSearch);
bool sucessfulLoad = false;
sucessfulLoad = m_winDetective->init();
if(sucessfulLoad) {
parse( inout_result );
}
return sucessfulLoad;
}
bool LoaderXML::parse( Util::MacDesc& inout_result ) {
std::vector<WinDetective::Culprit> foundFiles;
foundFiles = m_winDetective->getLocatedCulprits();
bool sucessfulParse = true;
//This needs to be fixed somehow, append result to vector of MACs instead of a single inout-parameter?
for(unsigned int i = 0;
i<foundFiles.size() && sucessfulParse==true;
i++) {
WinDetective::Culprit c = foundFiles.at(i);
sucessfulParse = parseXML(
c.filePath,
c.fileName,
c.fileEnding,
inout_result );
}
return sucessfulParse;
}
bool LoaderXML::parseXML(
const std::wstring filePath,
const std::wstring fileName,
const std::wstring fileEnding,
Util::MacDesc& inout_result ) {
std::string filePathStd;
std::string fileNameStd;
filePathStd = Util::UtilString::W2Std(filePath, filePathStd);
fileNameStd = Util::UtilString::W2Std(fileName, fileNameStd);
//Parse xml.
bool sucessfulParse = false;
Parser_XML::ParserXML parserXML(filePathStd, fileNameStd);
sucessfulParse = parserXML.init();
if(sucessfulParse == true) {
Parser_XML::DocXML* docXML = nullptr;
parserXML.getDocXML(&docXML);
//Load data from parsed XML-document into resulting type
InterpreterXML interpreter( docXML->getXML() );
sucessfulParse = interpreter.init( inout_result );
//Clear some memory
if( docXML != nullptr ) {
delete docXML;
}
}
return sucessfulParse;
}
}
| 23.69697
| 104
| 0.702472
|
L0mion
|
69651d5deaa13d9e7c750a2286cdf94ef8c831fe
| 815
|
cpp
|
C++
|
Pointers/addressofArrayPointer.cpp
|
anjali9811/Programming-in-Cpp
|
02e80e045a7fb20f8970fcdae68c08bdf27f95b8
|
[
"Apache-2.0"
] | null | null | null |
Pointers/addressofArrayPointer.cpp
|
anjali9811/Programming-in-Cpp
|
02e80e045a7fb20f8970fcdae68c08bdf27f95b8
|
[
"Apache-2.0"
] | null | null | null |
Pointers/addressofArrayPointer.cpp
|
anjali9811/Programming-in-Cpp
|
02e80e045a7fb20f8970fcdae68c08bdf27f95b8
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
#include<math.h>
using namespace std;
int main() {
int arr[5],*ptr;
cout<<*&arr<<endl; //address of first element in array
cout<<&arr<<endl;//address of first element in array
cout<<arr<<endl;//address of first element in array
cout<<"&arr + 1 = "<<&arr+1<<endl; // address of complete array incremented by 5*4 bytes
cout<<"arr+1 = "<<arr+1<<endl;//address of 2 element of array - incrmented by 4 bytes as it is an integer array
cout<<&ptr<<endl;
cout<<&ptr+1<<endl;//prints address of pointer with increment of 4
cout<<&ptr+2<<endl;
cout<<&ptr+3<<endl;
//a pointer has size 8 bytes on a 64 bit machine, so &ptr+1 will print =hex addr of pointer + next 8 bytes
// int i=1;
// while(i)
// {
// i++;
// }
// i=i/2;
// int size = log(i);
// cout<<size;
// return 0;
}
| 23.285714
| 112
| 0.634356
|
anjali9811
|
696d9a2dd9f2039f5b480f24bc6645c4080c25a1
| 2,211
|
cxx
|
C++
|
src/medVtkInria/HWShading/vtkShaderBase.cxx
|
lcatanes/medInria-public
|
5d79ce0085c11f2fb9277a06c8cf56b4258a9d9f
|
[
"BSD-4-Clause"
] | 1
|
2020-11-16T13:55:45.000Z
|
2020-11-16T13:55:45.000Z
|
src/medVtkInria/HWShading/vtkShaderBase.cxx
|
lcatanes/medInria-public
|
5d79ce0085c11f2fb9277a06c8cf56b4258a9d9f
|
[
"BSD-4-Clause"
] | null | null | null |
src/medVtkInria/HWShading/vtkShaderBase.cxx
|
lcatanes/medInria-public
|
5d79ce0085c11f2fb9277a06c8cf56b4258a9d9f
|
[
"BSD-4-Clause"
] | null | null | null |
/*============================================================================
The Hardware Shading (HWShading) module is protected by the
following copyright:
Copyright (c) 2007 Biomedical Image Analysis (BMIA) - Department of
Biomedical Engineering - Eindhoven University of Technology.
All rights reserved. See Copyright.txt for details.
The HWShading implementation was originally written by Tim Peeters (BMIA - TUe)
and published at the "11th International Fall Workshop on Vision, Modeling,
and Visualization 2006" (VMV'06):
"Visualization of the Fibrous Structure of the Heart", by T. Peeters et al.
See http://timpeeters.com/research/vmv2006 for more information.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
============================================================================*/
/**
* vtkShaderBase.cxx
* by Tim Peeters
*
* 2005-05-03 Tim Peeters
* - First version
*
* 2005-05-17 Tim Peeters
* - Removed most implementations because they were moved to
* vktShaderBaseHandle subclass.
*
* 2005-07-14 Tim Peeters
* - Added SupportsOpenGLVersion() function.
*/
#include "vtkShaderBase.h"
#include <vtkObjectFactory.h>
vtkCxxRevisionMacro(vtkShaderBase, "$Revision: 1 $");
vtkStandardNewMacro(vtkShaderBase);
vtkShaderBase::vtkShaderBase()
{
// nothing
}
vtkShaderBase::~vtkShaderBase()
{
// nothing was created by this class, so don't destroy anything either.
// do that in the subclasses that were creating things.
}
// from http://developer.nvidia.com/object/nv_ogl2_support.html
bool vtkShaderBase::SupportsOpenGLVersion(int atLeastMajor, int atLeastMinor)
{
const char* version;
int major, minor;
//glewInit();
version = (const char *) glGetString(GL_VERSION);
cout<<"OpenGL version is "<<version<<endl;
//vtkDebugMacro(<<"OpenGL version is "<<version);
if (sscanf(version, "%d.%d", &major, &minor) == 2) {
if (major > atLeastMajor)
return true;
if (major == atLeastMajor && minor >= atLeastMinor)
return true;
} else {
/* OpenGL version string malformed! */
}
return false;
}
| 31.585714
| 79
| 0.688829
|
lcatanes
|
696ed7ad189132c831d377c6f430971f393f683c
| 2,853
|
hpp
|
C++
|
tests/test1/myWorld.hpp
|
EEnginE/engine
|
9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc
|
[
"Apache-2.0"
] | 28
|
2015-01-02T19:06:37.000Z
|
2018-11-23T11:34:17.000Z
|
tests/test1/myWorld.hpp
|
EEnginE/engine
|
9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc
|
[
"Apache-2.0"
] | null | null | null |
tests/test1/myWorld.hpp
|
EEnginE/engine
|
9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc
|
[
"Apache-2.0"
] | 6
|
2015-01-10T16:48:14.000Z
|
2019-10-08T13:43:44.000Z
|
/*!
* \file myWorld.hpp
* \brief Class myWorld
*/
/*
* Copyright (C) 2015 EEnginE project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cmdANDinit.hpp"
#include <engine.hpp>
#include "myScene.hpp"
#ifndef HANDLER_HPP
#define HANDLER_HPP
using e_engine::GlobConf;
using e_engine::iDisplayBasic;
using e_engine::rFrameCounter;
using e_engine::rRendererBase;
using e_engine::rRendererBasic;
using e_engine::rRendererDeferred;
using e_engine::rWorld;
class myWorld final : public rWorld, public rFrameCounter {
typedef uSlot<void, myWorld, e_engine::iEventInfo const &> _SLOT_;
private:
float vAlpha;
std::vector<std::shared_ptr<iDisplayBasic>> vDisp_RandR;
std::shared_ptr<rRendererBase> vRenderer;
myScene vScene;
e_engine::iInit *vInitPointer;
float vNearZ;
float vFarZ;
bool vKeepWaiting = true;
_SLOT_ slotWindowClose;
_SLOT_ slotResize;
_SLOT_ slotKey;
std::mutex vWaitMutex;
std::condition_variable vWaitCond;
void disconnectSlotsAndContinue();
public:
myWorld(cmdANDinit &_cmd, e_engine::iInit *_init)
: rWorld(_init),
rFrameCounter(this, true),
vRenderer(std::make_shared<rRendererBasic>(this, L"R1")),
vScene(this, _cmd),
vInitPointer(_init),
vNearZ(_cmd.getNearZ()),
vFarZ(_cmd.getFarZ()),
slotWindowClose(&myWorld::windowClose, this),
slotResize(&myWorld::resize, this),
slotKey(&myWorld::key, this) {
_init->addWindowCloseSlot(&slotWindowClose);
_init->addResizeSlot(&slotResize);
_init->addKeySlot(&slotKey);
vAlpha = 1;
}
~myWorld();
myWorld() = delete;
void windowClose(e_engine::iEventInfo const &) {
iLOG("User closed window");
disconnectSlotsAndContinue();
}
void key(e_engine::iEventInfo const &info);
void resize(e_engine::iEventInfo const &info) {
iLOG("Window resized: W = ", info.eResize.width, "; H = ", info.eResize.height);
updateViewPort(0, 0, static_cast<int>(GlobConf.win.width), static_cast<int>(GlobConf.win.height));
vScene.calculateProjectionPerspective(GlobConf.win.width, GlobConf.win.height, vNearZ, vFarZ, glm::radians(60.0f));
}
void waitForEnd();
int initGL();
};
#endif // HANDLER_HPP
// kate: indent-mode cstyle; indent-width 2; replace-tabs on; line-numbers on;
| 27.171429
| 119
| 0.702419
|
EEnginE
|
69714ea0ce2ea304626ebf9ec61861a22c1618a6
| 103
|
cpp
|
C++
|
Homework (20.05.21)/exercise3.cpp
|
Sadik326-ctrl/computer_programming
|
cbae264ffa04fc487008fa6a0a32e0a1a316e01e
|
[
"MIT"
] | null | null | null |
Homework (20.05.21)/exercise3.cpp
|
Sadik326-ctrl/computer_programming
|
cbae264ffa04fc487008fa6a0a32e0a1a316e01e
|
[
"MIT"
] | null | null | null |
Homework (20.05.21)/exercise3.cpp
|
Sadik326-ctrl/computer_programming
|
cbae264ffa04fc487008fa6a0a32e0a1a316e01e
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
string x("3");
cout<<x;
return 0;
}
| 10.3
| 20
| 0.572816
|
Sadik326-ctrl
|
69728056a9d58ee7466f5bc0abd2a3e677ba214a
| 10,399
|
cpp
|
C++
|
hardware_layer/hardware_arduino/firmware/arduino_node.cpp
|
kaushikiagarwal/Anahita
|
bb41052d895622a32a0f55cf3a750aec92669661
|
[
"BSD-3-Clause"
] | null | null | null |
hardware_layer/hardware_arduino/firmware/arduino_node.cpp
|
kaushikiagarwal/Anahita
|
bb41052d895622a32a0f55cf3a750aec92669661
|
[
"BSD-3-Clause"
] | null | null | null |
hardware_layer/hardware_arduino/firmware/arduino_node.cpp
|
kaushikiagarwal/Anahita
|
bb41052d895622a32a0f55cf3a750aec92669661
|
[
"BSD-3-Clause"
] | null | null | null |
#include <Arduino.h>
#include <Wire.h>
#include <Servo.h>
#include <ros.h>
#include <ros/time.h>
#include <std_msgs/Int32.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Bool.h>
// #include <anahita_msgs/Depth.h>
// #include <anahita_msgs/Pressure.h>
#include <anahita_msgs/Thrust.h>
#include <MS5837.h>
#define MDPin1 25
#define MDPin2 24
#define servoEastPin 40 // pin definitions for forward thrusters
#define servoWestPin 43
#define servoNorthSwayPin 31 // pin definitions for sideward thrusters
#define servoSouthSwayPin 32
//31 30 32 33
#define servoNorthWestUpPin 28// pin definitions for upward thrusters
#define servoSouthWestUpPin 33
#define servoNorthEastUpPin 27
#define servoSouthEastUpPin 30
#define permanentGround1 29
#define permanentGround2 26
#define permanentGround3 41
#define permanentGround4 42
#define TorpedoPin1 38
#define TorpedoPin2 39
#define MDServoPin 3 //pin definition for depth sensor
Servo servoEast;
Servo servoWest;
Servo servoNorthSway;
Servo servoSouthSway;
Servo servoNorthWestUp;
Servo servoNorthEastUp;
Servo servoSouthWestUp;
Servo servoSouthEastUp;
Servo servoMarkerDropper;
void PWMCb(const anahita_msgs::Thrust& msg_);
void TEast(const int data);
void TWest(const int data);
void TNorth(const int data);
void TSouth(const int data);
void TNEUp(const int data);
void TNWUp(const int data);
void TSEUp(const int data);
void TSWUp(const int data);
void MDCb(const int msg);
void SOVCb(const int msg);
int ESC_Zero = 1500;
int deadZone = 25;
int torpedo_count = 0;
ros::NodeHandle nh;
// define rate at which sensor data should be published (in Hz)
#define PRESSURE_PUBLISH_RATE 10
// pressure sensor
MS5837 pressure_sensor;
// declare subscribers
ros::Subscriber<anahita_msgs::Thrust> PWM_Sub("/pwm", &PWMCb);
// function declration to puboish pressure sensor data
void publish_pressure_data();
// declaration of callback functions for all thrusters
// declare publishers
// ros::Subscriber<std_msgs::Int32> Marker_Dropper_Sub("/marker_dropper", &MDCb);
// ros::Subscriber<std_msgs::Int32> SOV_Sub("/torpedo", &SOVCb);
std_msgs::Float32 depth_msg;
ros::Publisher ps_depth_pub("/pressure_sensor/depth", &depth_msg);
int forward_right = 0;
int forward_left = 0;
int sideward_front = 0;
int sideward_back = 0;
int upward_north_east = 0;
int upward_north_west = 0;
int upward_south_east = 0;
int upward_south_west = 0;
int marker_dropper = 0;
int torpedo = 0;
void setup()
{
Serial.begin(57600);
servoEast.attach(servoEastPin);
servoEast.writeMicroseconds(ESC_Zero);
servoNorthSway.attach(servoNorthSwayPin);
servoNorthSway.writeMicroseconds(ESC_Zero);
servoWest.attach(servoWestPin);
servoWest.writeMicroseconds(ESC_Zero);
servoSouthSway.attach(servoSouthSwayPin);
servoSouthSway.writeMicroseconds(ESC_Zero);
servoNorthWestUp.attach(servoNorthWestUpPin);
servoNorthWestUp.writeMicroseconds(ESC_Zero);
servoNorthEastUp.attach(servoNorthEastUpPin);
servoNorthEastUp.writeMicroseconds(ESC_Zero);
servoSouthWestUp.attach(servoSouthWestUpPin);
servoSouthWestUp.writeMicroseconds(ESC_Zero);
servoSouthEastUp.attach(servoSouthEastUpPin);
servoSouthEastUp.writeMicroseconds(ESC_Zero);
pinMode(permanentGround1, OUTPUT);
pinMode(permanentGround2, OUTPUT);
pinMode(permanentGround3, OUTPUT);
pinMode(permanentGround4, OUTPUT);
digitalWrite(permanentGround1, LOW);
digitalWrite(permanentGround2, LOW);
digitalWrite(permanentGround3, LOW);
digitalWrite(permanentGround4, LOW);
pinMode(TorpedoPin1, OUTPUT);
pinMode(TorpedoPin2 ,OUTPUT);
digitalWrite(TorpedoPin1,LOW);
digitalWrite(TorpedoPin2,LOW);
servoMarkerDropper.attach(MDServoPin);
delay(7000);
Serial.print("Successfully started servos");
// setting up pressure sensor
Wire.begin();
// We can't continue with the rest of the program unless we can initialize the sensor
pressure_sensor.init();
pressure_sensor.setFluidDensity(997); //kg/m^3 (freshwater, 1029 for seawater)*/
// initialize ROS node
nh.initNode();
nh.getHardware()->setBaud(57600);
// start ros_node
nh.subscribe(PWM_Sub);
// nh.subscribe(Marker_Dropper_Sub);
// nh.subscribe(SOV_Sub);
// publisher
nh.advertise(ps_depth_pub);
while (!nh.connected())
{
nh.spinOnce();
}
nh.loginfo("Anahita CONNECTED");
}
void loop()
{
static unsigned long prev_pressure_time = 0;
// this block publishes the pressure sensor data based on defined rate
if ((millis() - prev_pressure_time) >= (1000 / PRESSURE_PUBLISH_RATE))
{
// publish_pressure_data();
prev_pressure_time = millis();
}
//nh.loginfo("Data being recieved");
delay(10);
TEast(forward_right);
TWest(forward_left);
TNorth(sideward_front);
TSouth(sideward_back);
TNEUp(upward_north_east);
TNWUp(upward_north_west);
TSEUp(upward_south_east);
TSWUp(upward_south_west);
MDCb(marker_dropper);
SOVCb(torpedo);
if(torpedo_count == 0)
{
digitalWrite(TorpedoPin1 ,LOW);
digitalWrite(TorpedoPin2 ,LOW);
}
nh.spinOnce();
digitalWrite(TorpedoPin1, HIGH);
}
// function definition for publish_pressure_data
void publish_pressure_data()
{
pressure_sensor.read();
// pressure_msg.data = pressure_sensor.pressure();
/** Depth returned in meters (valid for operation in incompressible
* liquids only. Uses density that is set for fresh or seawater.
*/
depth_msg.data = -100*pressure_sensor.depth(); //convert to centimeters
ps_depth_pub.publish(&depth_msg);
}
void MDCb(const int msg)
{
nh.loginfo("Inside marker dropper callback");
int data = msg;
int pos = 0;
if(data == 1)
{
nh.loginfo("First ball being dropped");
for(pos = 0; pos < 170; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
servoMarkerDropper.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
if(data == 2)
{
nh.loginfo("Second ball being dropped");
for(pos = 170; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
servoMarkerDropper.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
if(data == -1)
{
nh.loginfo("Can now load the inner ball");
for(pos = 0; pos < 170; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
servoMarkerDropper.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
if(data == -2)
{
nh.loginfo("Can now load the outer ball");
for(pos = 0; pos < 170; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
servoMarkerDropper.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
}
void SOVCb(const int msg)
{
nh.loginfo("Inside SOV callback");
int data = msg;
int pos = 0;
if(data == 1)
{
torpedo_count = 1;
nh.loginfo("First Torpedo being shot");
digitalWrite(TorpedoPin1, HIGH);
delay(100);
digitalWrite(TorpedoPin1, LOW);
torpedo_count = 0;
}
else if(data == 2)
{
torpedo_count = 1;
digitalWrite(TorpedoPin2, HIGH);
delay(100);
digitalWrite(TorpedoPin2, LOW);
torpedo_count = 0;
}
}
void TEast(const int data)
{
if(data>0)
servoEast.writeMicroseconds(ESC_Zero + data + deadZone);
else if(data<0)
servoEast.writeMicroseconds(ESC_Zero + data - deadZone);
else
servoEast.writeMicroseconds(ESC_Zero);
}
void TWest(const int data)
{
if(data>0)
servoWest.writeMicroseconds(ESC_Zero + data + deadZone);
else if(data<0)
servoWest.writeMicroseconds(ESC_Zero + data - deadZone);
else
servoWest.writeMicroseconds(ESC_Zero);
}
void TNorth(const int data)
{
if(data>0)
servoNorthSway.writeMicroseconds(ESC_Zero + data + deadZone);
else if(data<0)
servoNorthSway.writeMicroseconds(ESC_Zero + data - deadZone);
else
servoNorthSway.writeMicroseconds(ESC_Zero);
}
void TSouth(const int data)
{
if(data>0)
servoSouthSway.writeMicroseconds(ESC_Zero + data + deadZone);
else if(data<0)
servoSouthSway.writeMicroseconds(ESC_Zero + data - deadZone);
else
servoSouthSway.writeMicroseconds(ESC_Zero);
}
void TNEUp(const int data)
{
if(data>0)
servoNorthEastUp.writeMicroseconds(ESC_Zero + data + deadZone);
else if(data<0)
servoNorthEastUp.writeMicroseconds(ESC_Zero + data - deadZone);
else
servoNorthEastUp.writeMicroseconds(ESC_Zero);
}
void TNWUp(const int data)
{
if(data>0)
servoNorthWestUp.writeMicroseconds(ESC_Zero + data + deadZone);
else if(data<0)
servoNorthWestUp.writeMicroseconds(ESC_Zero + data - deadZone);
else
servoNorthWestUp.writeMicroseconds(ESC_Zero);
}
void TSEUp(const int data)
{
if(data>0)
servoSouthEastUp.writeMicroseconds(ESC_Zero + data + deadZone);
else if(data<0)
servoSouthEastUp.writeMicroseconds(ESC_Zero + data - deadZone);
else
servoSouthEastUp.writeMicroseconds(ESC_Zero);
}
void TSWUp(const int data)
{
if(data>0)
servoSouthWestUp.writeMicroseconds(ESC_Zero + data + deadZone);
else if(data<0)
servoSouthWestUp.writeMicroseconds(ESC_Zero + data - deadZone);
else
servoSouthWestUp.writeMicroseconds(ESC_Zero);
}
void PWMCb(const anahita_msgs::Thrust& msg_)
{
// nh.loginfo("Inside PWM Callback");
forward_right = msg_.forward_right;
forward_left = msg_.forward_left;
sideward_front = msg_.sideward_front;
sideward_back = msg_.sideward_back;
upward_north_east = msg_.upward_north_east;
upward_north_west = msg_.upward_north_west;
upward_south_east = msg_.upward_south_east;
upward_south_west = msg_.upward_south_west;
marker_dropper = msg_.marker_dropper;
torpedo = msg_.torpedo;
}
| 28.105405
| 100
| 0.690836
|
kaushikiagarwal
|
697b1d75b0cf179ad511ae228aec8a17824011ad
| 1,592
|
cpp
|
C++
|
Code/Engine/Foundation/Threading/Implementation/ThreadSignal.cpp
|
Tekh-ops/ezEngine
|
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
|
[
"MIT"
] | 703
|
2015-03-07T15:30:40.000Z
|
2022-03-30T00:12:40.000Z
|
Code/Engine/Foundation/Threading/Implementation/ThreadSignal.cpp
|
Tekh-ops/ezEngine
|
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
|
[
"MIT"
] | 233
|
2015-01-11T16:54:32.000Z
|
2022-03-19T18:00:47.000Z
|
Code/Engine/Foundation/Threading/Implementation/ThreadSignal.cpp
|
Tekh-ops/ezEngine
|
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
|
[
"MIT"
] | 101
|
2016-10-28T14:05:10.000Z
|
2022-03-30T19:00:59.000Z
|
#include <Foundation/FoundationPCH.h>
#include <Foundation/Threading/Lock.h>
#include <Foundation/Threading/ThreadSignal.h>
ezThreadSignal::ezThreadSignal(Mode mode /*= Mode::AutoReset*/)
{
m_mode = mode;
}
ezThreadSignal::~ezThreadSignal() = default;
void ezThreadSignal::WaitForSignal() const
{
EZ_LOCK(m_ConditionVariable);
while (!m_bSignalState)
{
m_ConditionVariable.UnlockWaitForSignalAndLock();
}
if (m_mode == Mode::AutoReset)
{
m_bSignalState = false;
}
}
ezThreadSignal::WaitResult ezThreadSignal::WaitForSignal(ezTime timeout) const
{
EZ_LOCK(m_ConditionVariable);
const ezTime tStart = ezTime::Now();
ezTime tElapsed = ezTime::Zero();
while (!m_bSignalState)
{
if (m_ConditionVariable.UnlockWaitForSignalAndLock(timeout - tElapsed) == ezConditionVariable::WaitResult::Timeout)
{
return WaitResult::Timeout;
}
tElapsed = ezTime::Now() - tStart;
if (tElapsed >= timeout)
{
return WaitResult::Timeout;
}
}
if (m_mode == Mode::AutoReset)
{
m_bSignalState = false;
}
return WaitResult::Signaled;
}
void ezThreadSignal::RaiseSignal()
{
{
EZ_LOCK(m_ConditionVariable);
m_bSignalState = true;
}
if (m_mode == Mode::AutoReset)
{
// with auto-reset there is no need to wake up more than one
m_ConditionVariable.SignalOne();
}
else
{
m_ConditionVariable.SignalAll();
}
}
void ezThreadSignal::ClearSignal()
{
EZ_LOCK(m_ConditionVariable);
m_bSignalState = false;
}
EZ_STATICLINK_FILE(Foundation, Foundation_Threading_Implementation_ThreadSignal);
| 19.414634
| 119
| 0.704774
|
Tekh-ops
|
69811fb63779a92b39ae7082f005674b16735ec9
| 2,578
|
hh
|
C++
|
src/AMOS/Motif_AMOS.hh
|
sagrudd/amos
|
47643a1d238bff83421892cb74daaf6fff8d9548
|
[
"Artistic-1.0"
] | 10
|
2015-03-20T18:25:56.000Z
|
2020-06-02T22:00:08.000Z
|
src/AMOS/Motif_AMOS.hh
|
sagrudd/amos
|
47643a1d238bff83421892cb74daaf6fff8d9548
|
[
"Artistic-1.0"
] | 5
|
2015-05-14T17:51:20.000Z
|
2020-07-19T04:17:47.000Z
|
src/AMOS/Motif_AMOS.hh
|
sagrudd/amos
|
47643a1d238bff83421892cb74daaf6fff8d9548
|
[
"Artistic-1.0"
] | 10
|
2015-05-17T16:01:23.000Z
|
2020-05-20T08:13:43.000Z
|
////////////////////////////////////////////////////////////////////////////////
//! \file
//! \author Sergey Koren
//! \date 04/11/11
//!
//! \brief Header for Motif_t
//!
////////////////////////////////////////////////////////////////////////////////
#ifndef __Motif_AMOS_HH
#define __Motif_AMOS_HH 1
#include "Universal_AMOS.hh"
#include "Scaffold_AMOS.hh"
#include <vector>
namespace AMOS {
//================================================ Motif_t ==================
//! \brief A ordered, oriented and positioned list of contigs
//!
//! A list of contigs that are ordered, oriented and positioned in
//! relation to one another.
//!
//==============================================================================
class Motif_t : public Scaffold_t
{
private:
ID_t scf_m;
protected:
//--------------------------------------------------- readRecord -------------
virtual void readRecord (std::istream & fix, std::istream & var);
//--------------------------------------------------- readRecordFix ----------
virtual void readRecordFix (std::istream & fix);
//--------------------------------------------------- writeRecord ------------
virtual void writeRecord (std::ostream & fix, std::ostream & var) const;
public:
static const NCode_t NCODE;
//!< The NCode type identifier for this object
//--------------------------------------------------- Motif_t -------------
//! \brief Constructs an empty Motif_t object
//!
Motif_t ( )
{
scf_m = NULL_ID;
}
//--------------------------------------------------- Motif_t -------------
//! \brief Copy constructor
//!
Motif_t (const Motif_t & source)
{
*this = source;
}
//--------------------------------------------------- ~Motif_t ------------
//! \brief Destroys a Motif_t object
//!
~Motif_t ( )
{
}
void setScf(ID_t &id) {
scf_m = id;
}
ID_t getScf() {
return scf_m;
}
//--------------------------------------------------- clear ------------------
virtual void clear ( )
{
Scaffold_t::clear( );
scf_m = NULL_ID;
}
//--------------------------------------------------- getNCode ---------------
virtual NCode_t getNCode ( ) const
{
return Motif_t::NCODE;
}
//--------------------------------------------------- readMessage ------------
virtual void readMessage (const Message_t & msg);
//--------------------------------------------------- writeMessage -----------
virtual void writeMessage (Message_t & msg) const;
};
} // namespace AMOS
#endif // #ifndef __Motif_AMOS_HH
| 22.224138
| 80
| 0.399147
|
sagrudd
|
6984161aed53a2f77249f1924ea703aa73b98847
| 810
|
cpp
|
C++
|
Sandbox/src/Geometry/Geometry.cpp
|
noidawt/AulysEngine
|
6e4a6482961fc27e48342d4767f2d075869b1abf
|
[
"MIT"
] | 1
|
2020-09-28T10:04:02.000Z
|
2020-09-28T10:04:02.000Z
|
Sandbox/src/Geometry/Geometry.cpp
|
noidawt/AulysEngine
|
6e4a6482961fc27e48342d4767f2d075869b1abf
|
[
"MIT"
] | null | null | null |
Sandbox/src/Geometry/Geometry.cpp
|
noidawt/AulysEngine
|
6e4a6482961fc27e48342d4767f2d075869b1abf
|
[
"MIT"
] | null | null | null |
#include "Geometry.h"
namespace App
{
// IMPROVEMENT: Could be constexpr if we make our own sin and cos.
// Note: sadly cmath's sin and cos aren't constexpr because of some legacy things
// that the library does, for example setting errno.
Geometry::V getGeometry(int p, int q, int r) {
auto testOne = sin(piOver(p)) * sin(piOver(r));
auto testTwo = cos(piOver(q));
if ( p == 4 && q == 3 && r == 4 )
return Geometry::Euclidean;
if ( testOne > testTwo ) {
return Geometry::Spherical;
}
return Geometry::Hyperbolic;
}
Geometry::V getGeometry2D(uint32_t p, uint32_t q) {
auto test = 1.0f / p + 1.0f / q;
if ( test == 0.5f ) {
return Geometry::Euclidean;
}
else if ( test > 0.5f ) {
return Geometry::Spherical;
}
return Geometry::Hyperbolic;
}
}; // namespace App
| 26.129032
| 82
| 0.640741
|
noidawt
|
698416cc8d9502b69e7b414950c7292e151bf678
| 648
|
cpp
|
C++
|
nullObject/nullObject.cpp
|
rededx/designPatterns_modernCpp
|
51cfe79ceb05182f69b8a6186013134c2fd2013b
|
[
"MIT"
] | null | null | null |
nullObject/nullObject.cpp
|
rededx/designPatterns_modernCpp
|
51cfe79ceb05182f69b8a6186013134c2fd2013b
|
[
"MIT"
] | null | null | null |
nullObject/nullObject.cpp
|
rededx/designPatterns_modernCpp
|
51cfe79ceb05182f69b8a6186013134c2fd2013b
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <memory>
#include <string>
class AbstractObject {
public:
virtual std::string operation() const = 0;
};
class RealObject : public AbstractObject {
public:
std::string operation() const override {
return std::string("computed something");
}
};
class NullObject : public AbstractObject {
public:
std::string operation() const override { return std::string(""); }
};
void doSomething(const AbstractObject& obj) {
std::cout << obj.operation() << "\n";
}
int main() {
RealObject realObject;
doSomething(realObject);
NullObject nullObject;
doSomething(nullObject);
}
| 20.25
| 70
| 0.669753
|
rededx
|
69897e4557b6864ff5543fb0cb14f131c0026164
| 7,616
|
cpp
|
C++
|
src/apps/M1DemoMachine/libFLNL/server.cpp
|
shortmr/CANOpenRobotController
|
61602c2d19ff1e87408152ca61b4f37df1598bfa
|
[
"Apache-2.0"
] | null | null | null |
src/apps/M1DemoMachine/libFLNL/server.cpp
|
shortmr/CANOpenRobotController
|
61602c2d19ff1e87408152ca61b4f37df1598bfa
|
[
"Apache-2.0"
] | null | null | null |
src/apps/M1DemoMachine/libFLNL/server.cpp
|
shortmr/CANOpenRobotController
|
61602c2d19ff1e87408152ca61b4f37df1598bfa
|
[
"Apache-2.0"
] | 1
|
2021-05-04T17:19:45.000Z
|
2021-05-04T17:19:45.000Z
|
/**
* \file server.cpp
* \brief Network server class implementation
* \author Vincent Crocher
* \version 0.5
* \date March 2010
*
*
*/
#include "server.h"
/*-----------------------------------------------------------------------------------------------------------------*/
/*######################################### CONSTRUCTOR AND DESTRUCTOR ########################################*/
/*-----------------------------------------------------------------------------------------------------------------*/
//! Constructor initializing data and creating a socket
//! \param nb_values_to_send : Number of double values the server send to the client
//! \param nb_values_to_receive : Number of double values the server receive from the client
server::server(int nb_values_to_send, int nb_values_to_receive)
{
//Copy values
NbValuesToSend=nb_values_to_send;
NbValuesToReceive=nb_values_to_receive;
//Initialise sin
sin.sin_family = AF_INET;
sin.sin_port = htons(2048);
//Initialise and allocates privates
IsValues=false;
Connected=false;
ReceivedValues=new double[NbValuesToReceive];
#ifdef WINDOWS
WSADATA WSAData;
WSAStartup(MAKEWORD(2,0), &WSAData);
#endif
//Initialise socket
Socket = socket(AF_INET, SOCK_STREAM, 0);
}
//! Destructor releasing memory and closing the socket
server::~server()
{
Connected=false;
if(close(Socket)==0)
{
printf("server::Connection closed.\n");
#ifdef WINDOWS
WSACleanup();
#endif
}
else
{
printf("server::Error closing connection.\n");
}
delete[] ReceivedValues;
}
/*#################################################################################################################*/
/*-----------------------------------------------------------------------------------------------------------------*/
/*################################### CONNECTING AND DISCONNECTING METHODS ###################################*/
/*-----------------------------------------------------------------------------------------------------------------*/
//! Open a connection and wait for a client launching an Accepting thread
//! \param addr : The server ip address (local address)
//! \return 0 if OK
//! \return -1 if bind() error
//! \return -2 if error creating the accepting thread
int server::Connect(char * addr)
{
//Initialise server address
sin.sin_addr.s_addr = inet_addr(addr);
printf("server::connection\n");
//Initialise
if(bind(Socket, (struct sockaddr*)&sin, sizeof(sin))==-1)
{
#ifdef WINDOWS
printf("WSA Error code : %d\t", WSAGetLastError());
#endif
perror("server::bind() :");
close(Socket);
return -1;
}
else
{
//Ecoute d'une seulle connexion
listen(Socket, 1);
//Creation d'un thread d'attente de connexion du client
if(pthread_create(&AcceptingThread, NULL, Accepting, (void*)this)!=0)
{
printf("server::Connect() : Error creating accepting thread\n");
return -2;
}
//OK
return 0;
}
}
//! Thread function waiting for a client connection
//! \param c : A pointer on server object
//! \return NULL
void * Accepting(void * c)
{
server * local_server;
local_server=(server*)c;
#ifdef WINDOWS
int taille = sizeof(SOCKADDR_IN);
local_server->ClientSocket=-1;
SOCKADDR_IN csin;
while(local_server->ClientSocket==INVALID_SOCKET)
local_server->ClientSocket = accept(local_server->Socket, (struct sockaddr*)&csin, &taille);
#else
socklen_t taille = sizeof(local_server->ClientSocket);
local_server->ClientSocket = accept(local_server->Socket, (struct sockaddr*)&local_server->ClientSocket, &taille);
#endif
//Connection OK
printf("server::Connected.\n");
local_server->Connected=true;
//Create a receiving thread
if(pthread_create(&local_server->ReceivingThread, NULL, ServerReceiving, (void*)local_server)!=0)
{
printf("server::Connect() : Error creating receiving thread\n");
local_server->Connected=false;
}
pthread_exit(NULL);
return NULL;
}
//! Disconnect from the client and so close the socket
//! \return the close(Socket) return value
int server::Disconnect()
{
Connected=false;
return close(Socket);
}
//! Tell if a client is connected
//! \return TRUE if the server have a client connected to, FALSE otherwise
bool server::IsConnected()
{
return Connected;
}
/*#################################################################################################################*/
/*-----------------------------------------------------------------------------------------------------------------*/
/*############################################### SENDING METHODS #############################################*/
/*-----------------------------------------------------------------------------------------------------------------*/
//! Send double values to the client
//! \param values : A pointer on a tab of doubles of NbValuesToSend elements
//! \return the send() return value
int server::Send(double * values)
{
//Convert double values in char tab
unsigned char values_in_char[NbValuesToSend*sizeof(double)];
//ATTENTION, PEUT ETRE ENLEVER LE UNSIGNED POUR WINDOWS
memcpy(values_in_char, values, NbValuesToSend*sizeof(double));
//Send the char tab
return send(ClientSocket, values_in_char, NbValuesToSend*sizeof(double), 0);
}
/*#################################################################################################################*/
/*-----------------------------------------------------------------------------------------------------------------*/
/*############################################ RECIVING METHODS #################################################*/
/*-----------------------------------------------------------------------------------------------------------------*/
//! Tell if values have been received since last GetReceivedValues()
//! \return TRUE if values have been received from the client, FALSE otherwise
bool server::IsReceivedValues()
{
return IsValues;
}
//! Return the last received values from the client
//! \return A tab of doubles of NbValuesToReceive elements, received from the client
double * server::GetReceivedValues()
{
IsValues=false;
return ReceivedValues;
}
//! Thread function waiting for data from the client
//! \param c : A pointer on the server object
//! \return NULL
void * ServerReceiving(void * c)
{
server * local_server;
local_server=(server*)c;
unsigned char values_in_char[local_server->NbValuesToReceive*sizeof(double)];
while(local_server->Connected)
{
int ret=recv(local_server->ClientSocket, values_in_char, local_server->NbValuesToReceive*sizeof(double), 0);
if(ret>0)
{
//Recopie des valeurs recues s'il y en a
memcpy(local_server->ReceivedValues, values_in_char, local_server->NbValuesToReceive*sizeof(double));
local_server->IsValues=true;
}
else if(ret<0)
{
#ifdef WINDOWS
printf("WSA Error code : %d\t", WSAGetLastError());
#endif
perror("server::Error reciving\n");
}
}
printf("server::Disconnected.\n");
pthread_exit(NULL);
return NULL;
}
/*#################################################################################################################*/
| 32.547009
| 122
| 0.507484
|
shortmr
|
698cf0d98867eb65670eb77b6a50c468ddbb7f4e
| 4,033
|
cpp
|
C++
|
Backend/ROS/src/discovery/src/discovery.cpp
|
Tannz0rz/ASDR
|
8799fb5416db3c91551afa1b0cde3db9fc5c581c
|
[
"MIT"
] | null | null | null |
Backend/ROS/src/discovery/src/discovery.cpp
|
Tannz0rz/ASDR
|
8799fb5416db3c91551afa1b0cde3db9fc5c581c
|
[
"MIT"
] | null | null | null |
Backend/ROS/src/discovery/src/discovery.cpp
|
Tannz0rz/ASDR
|
8799fb5416db3c91551afa1b0cde3db9fc5c581c
|
[
"MIT"
] | null | null | null |
#include "discovery.hpp"
void Discovery::setOccupancyGrid(nav_msgs::OccupancyGrid const &occupancy_grid)
{
m_occupancy_grid = occupancy_grid;
}
void Discovery::setCell(std::tuple<uint32_t, uint32_t> const &cell)
{
m_cell = cell;
}
void Discovery::compute(std::optional<std::tuple<uint32_t, uint32_t>> &goal)
{
auto const &[cell_x, cell_y] = m_cell;
nav_msgs::OccupancyGrid visit_occupancy_grid;
visit_occupancy_grid.info = m_occupancy_grid.info;
visit_occupancy_grid.data.resize(visit_occupancy_grid.info.width * visit_occupancy_grid.info.height);
std::fill(std::begin(visit_occupancy_grid.data), std::end(visit_occupancy_grid.data), -1);
std::queue<std::tuple<uint32_t, uint32_t>> visit_queue;
visit_queue.emplace(cell_x, cell_y);
goal = std::nullopt;
while (!visit_queue.empty()) {
auto const &[x, y] = visit_queue.front();
visit_queue.pop();
{
uint32_t const current_x = x + 1;
uint32_t const current_y = y;
uint32_t const index = current_x + current_y * m_occupancy_grid.info.width;
if (index >= 0 && index < std::size(m_occupancy_grid.data)) {
if (m_occupancy_grid.data[index] == -1 && current_x != cell_x && current_y != cell_y) {
goal = { current_x, current_y };
break;
}
else if (m_occupancy_grid.data[index] == 0 && visit_occupancy_grid.data[index] == -1) {
visit_occupancy_grid.data[index] = 0;
visit_queue.emplace(current_x, current_y);
}
}
}
{
uint32_t const current_x = x;
uint32_t const current_y = y + 1;
uint32_t const index = current_x + current_y * m_occupancy_grid.info.width;
if (index >= 0 && index < std::size(m_occupancy_grid.data)) {
if (m_occupancy_grid.data[index] == -1 && current_x != cell_x && current_y != cell_y) {
goal = { current_x, current_y };
break;
}
else if (m_occupancy_grid.data[index] == 0 && visit_occupancy_grid.data[index] == -1) {
visit_occupancy_grid.data[index] = 0;
visit_queue.emplace(current_x, current_y);
}
}
}
{
uint32_t const current_x = x - 1;
uint32_t const current_y = y;
uint32_t const index = current_x + current_y * m_occupancy_grid.info.width;
if (index >= 0 && index < std::size(m_occupancy_grid.data)) {
if (m_occupancy_grid.data[index] == -1 && current_x != cell_x && current_y != cell_y) {
goal = { current_x, current_y };
break;
}
else if (m_occupancy_grid.data[index] == 0 && visit_occupancy_grid.data[index] == -1) {
visit_occupancy_grid.data[index] = 0;
visit_queue.emplace(current_x, current_y);
}
}
}
{
uint32_t const current_x = x;
uint32_t const current_y = y - 1;
uint32_t const index = current_x + current_y * m_occupancy_grid.info.width;
if (index >= 0 && index < std::size(m_occupancy_grid.data)) {
if (m_occupancy_grid.data[index] == -1 && current_x != cell_x && current_y != cell_y) {
goal = { current_x, current_y };
break;
}
else if (m_occupancy_grid.data[index] == 0 && visit_occupancy_grid.data[index] == -1) {
visit_occupancy_grid.data[index] = 0;
visit_queue.emplace(current_x, current_y);
}
}
}
}
}
| 34.470085
| 105
| 0.521696
|
Tannz0rz
|
698e9055d4217cdcb31bfa85a77a9ff1885a332a
| 11,637
|
cpp
|
C++
|
Crazy Arcade_GIT/gameTwo.cpp
|
shinysong/CAU_CrazyArcade
|
0e96b28221f5ef12ef8aea02a090c36ad54081d1
|
[
"Apache-2.0"
] | null | null | null |
Crazy Arcade_GIT/gameTwo.cpp
|
shinysong/CAU_CrazyArcade
|
0e96b28221f5ef12ef8aea02a090c36ad54081d1
|
[
"Apache-2.0"
] | null | null | null |
Crazy Arcade_GIT/gameTwo.cpp
|
shinysong/CAU_CrazyArcade
|
0e96b28221f5ef12ef8aea02a090c36ad54081d1
|
[
"Apache-2.0"
] | null | null | null |
๏ปฟ#include <iostream>
#include <bangtal>
#include <cstdio>
#include <time.h>
#include <Windows.h>
#include<cstdlib>
#include<ctime>
using namespace bangtal;
using namespace std;
extern void lobby_main();
extern int level;
ObjectPtr board[12][12]; // ๊ฒ์๋ณด๋
ScenePtr scene; // ๋ฐฐ๊ฒฝ
ObjectPtr monsters[7]; // ๋ชฌ์คํฐ 7๋ง๋ฆฌ
TimerPtr mob_timer[7]; // ๋ชฌ์คํฐ๋ง๋ค ์์ง์ด๋ ํ์ด๋จธ
ObjectPtr heart[2]; //ํํธ
SoundPtr h_minus;
const int board_x1 = 37; //์์ง์ผ์ ์๋ ๋ฒ์
const int board_x2 = 906;
const int board_y1 = 58;
const int board_y2 = 619;
int heart_num = 2; //0-2 ์ธ๊ฐ
class Player {
public:
int px;
int py;
Player(int x, int y) :px(x), py(y) {}
};
class Mons {
public:
int x;
int y;
int speed;
bool isshow;
bool islive;
Mons(int x, int y, int s, bool isshow) :x(x), y(y), speed(s), isshow(true), islive(true) {}
public:
Mons() { // ์ด๊ธฐํ
x = board_x1;
y = board_y1;
speed = 10;
isshow = true;
islive = true;
}
};
class bomb {
public:
int bx;
int by;
bool isbomb;//ํฐ์ก์๋๋ง ๋ชฌ์คํฐ ์ฃฝ๊ฒ
bomb(int x, int y, bool isbomb) :bx(x), by(y), isbomb(false) {}
};
bool heart_touch(int mx, int my, int bx, int by, int radius) { //๋ฒ์์์ ์๋์ง ์ฒดํฌ
return((mx <= bx + radius && mx >= bx - radius && my <= by + radius && my >= by - radius));
}
bool board_check(int x, int y) { //๊ฒ์๋ณด๋ ์์ ์๋ ์ง ์ฒดํฌ
return ((board_x1 <= x && x <= board_x2 && board_y1 <= y && y <= board_y2));
}
bool t_monster; // ๋ชฌ์คํฐ๋ ๋ฟ์๋์ง
int b_radius = 73;
bool touch(int mx, int my, int bx, int by, int radius) { //๋ฒ์์์ ์๋์ง ์ฒดํฌ
return((mx <= bx + b_radius + radius && mx >= bx + b_radius - radius && my <= by + b_radius + radius && my >= by + b_radius - radius));
} //์ด๋ฏธ์ง ์์น์ ์ค์ ์์น์์ ๊ฑฐ๋ฆฌ๊ฐ์ด ์์ด์, ์กฐ์ ํด์ค.
int m_die = 0; // ์ฃฝ์ ๋ชฌ์คํฐ ์ ->๋ฉ์ธํจ์์์ ์ฒดํฌํ๋ ํ์ด๋จธ ์์.
//move ์ ์๋ ์ผ ์ค๋ฅธ ๋ง๋ค๊ธฐ
Mons right_move(ScenePtr scene, ObjectPtr monster, ObjectPtr player, Mons m, Player p, bomb b, bool t_monster) {
t_monster = touch(m.x, m.y, b.bx, b.by, 100); // ๋ฌผํ์ ๊ณผ ๋ฟ์๋์ง ์ฒดํฌ
if (t_monster == true && b.isbomb == true) {
monster->hide();
m.islive = false;
m_die++;
t_monster = false;
}
if (board_check(m.x, m.y) == true && heart_touch(m.x, m.y, p.px, p.py, 35) == false) {
monster->locate(scene, m.x, m.y);
m.x = m.x + m.speed;
}
else if (heart_touch(m.x, m.y, p.px, p.py, 35)) { //์บ๋ฆญํฐ์ ๋ชฌ์คํฐ๊ฐ ๋ฟ์ผ๋ฉด ํํธ ์ค์ด๋ฌ.
h_minus->play();
heart[heart_num]->hide();
heart_num--;
m.x = m.x + 70;
monster->locate(scene, m.x, m.y);
cout << "heart-1" << endl;
}
if (board_check(m.x, m.y) == false) { //๋ฒฝ์ ๋ฟ์ผ๋ฉด ์๊ณ๋ฐฉํฅ์ผ๋ก ์์ง์.
monster->locate(scene, board_x2, m.y - m.speed);
m.x = board_x2;
m.y = m.y - m.speed;
if (m.y < board_y1) {
monster->locate(scene, m.x - m.speed, board_y1);
m.x = m.x - m.speed;
m.y = board_y1;
}
}
return m;
}
Mons left_move(ScenePtr scene, ObjectPtr monster, ObjectPtr player, Mons m, Player p, bomb b, bool t_monster) {
t_monster = touch(m.x, m.y, b.bx, b.by, 100); // ๋ฌผํ์ ๊ณผ ๋ฟ์๋์ง ์ฒดํฌ
if (t_monster == true && b.isbomb == true) {
monster->hide();
m.islive = false;
m_die++;
t_monster = false;
}
if (board_check(m.x, m.y) == true && heart_touch(m.x, m.y, p.px, p.py, 35) == false) {
monster->locate(scene, m.x, m.y);
m.x = m.x - m.speed;
}
else if (heart_touch(m.x, m.y, p.px, p.py, 35)) {
h_minus->play();
heart[heart_num]->hide();
heart_num--;
m.x = m.x - 70;
monster->locate(scene, m.x, m.y);
cout << "heart-1" << endl;
}
if (board_check(m.x, m.y) == false) {
monster->locate(scene, board_x1, m.y + m.speed);
m.x = board_x1;
m.y = m.y + m.speed;
if (m.y > board_y2) {
monster->locate(scene, m.x + m.speed, board_y2);
m.x = m.x + m.speed;
m.y = board_y2;
}
}
return m;
}
Mons up_move(ScenePtr scene, ObjectPtr monster, ObjectPtr player, Mons m, Player p, bomb b, bool t_monster) {
t_monster = touch(m.x, m.y, b.bx, b.by, 100); // ๋ฌผํ์ ๊ณผ ๋ฟ์๋์ง ์ฒดํฌ
if (t_monster == true && b.isbomb == true) {
monster->hide();
m.islive = false;
m_die++;
t_monster = false;
}
if (board_check(m.x, m.y) == true && heart_touch(m.x, m.y, p.px, p.py, 35) == false) {
monster->locate(scene, m.x, m.y);
m.y = m.y + m.speed;
}
else if (heart_touch(m.x, m.y, p.px, p.py, 35)) {
h_minus->play();
heart[heart_num]->hide();
heart_num--;
m.y = m.y + 80;
monster->locate(scene, m.x, m.y);
cout << "heart-1" << endl;
}
if (board_check(m.x, m.y) == false) {
monster->locate(scene, m.x + m.speed, board_y2);
m.x = m.x + m.speed;
m.y = board_y2;
if (m.x > board_x2) {
monster->locate(scene, board_x2, m.y - m.speed);
m.x = board_x2;
m.y = m.y - m.speed;
}
}
return m;
}
Mons down_move(ScenePtr scene, ObjectPtr monster, ObjectPtr player, Mons m, Player p, bomb b, bool t_monster) {
t_monster = touch(m.x, m.y, b.bx, b.by, 100); // ๋ฌผํ์ ๊ณผ ๋ฟ์๋์ง ์ฒดํฌ
if (t_monster == true && b.isbomb == true) {
monster->hide();
m.islive = false;
m_die++;
t_monster = false;
}
if (board_check(m.x, m.y) == true && heart_touch(m.x, m.y, p.px, p.py, 35) == false) {
monster->locate(scene, m.x, m.y);
m.y = m.y - m.speed;
}
else if (heart_touch(m.x, m.y, p.px, p.py, 35)) {
h_minus->play();
heart[heart_num]->hide();
heart_num--;
m.y = m.y - 80;
monster->locate(scene, m.x, m.y);
cout << "heart-1" << endl;
}
if (board_check(m.x, m.y) == false) {
monster->locate(scene, m.x - m.speed, board_y1);
m.x = m.x - m.speed;
m.y = board_y1;
if (m.x < board_x1) {
monster->locate(scene, board_x1, m.y + m.speed);
m.x = board_x1;
m.y = m.y + m.speed;
}
}
return m;
}
void two_main() {
heart_num = 2;
srand((unsigned int)time(NULL));
setGameOption(GameOption::GAME_OPTION_INVENTORY_BUTTON, false);
setGameOption(GameOption::GAME_OPTION_MESSAGE_BOX_BUTTON, false);
setGameOption(GameOption::GAME_OPTION_ROOM_TITLE, false);
SoundPtr bgm = Sound::create("Music/2.mp3");
SoundPtr bomb_set = Sound::create("Music/bomb_set.mp3");
SoundPtr bomb_pop = Sound::create("Music/bomb_pop.mp3");
h_minus = Sound::create("Music/player_die.mp3");
scene = Scene::create("์คํ
์ด์ง 2", "images/2ํ.png"); //๋ฐฐ๊ฒฝ
Player player_class(275, 265);
auto player = Object::create("images/down_01.png", scene, 275, 265);
auto water = Object::create("images/water.png", scene, player_class.px, player_class.py, false);
bomb waterbomb(player_class.px, player_class.py, false);
auto water_bomb = Object::create("images/bomb.png", scene, player_class.px, player_class.py, false);
auto watertimer1 = Timer::create(1); //๋ฌผํ์ ์ด ํฐ์ง๋ ์๊ฐ
auto watertimer2 = Timer::create(0.5f); //ํฐ์ง๋ ์๊ฐ
auto gameoverTimer = Timer::create(60); //ํฐ์ง๋ ์๊ฐ
//ํํธ ์์น
for (int h = 0; h <= heart_num; h++) {
heart[h] = Object::create("images/heart.png", scene, 25 + h * 47, 5, true); //ํํธ
heart[h]->setScale(0.04f);
}
//๋ชฌ์คํฐ ๋๋ค์ผ๋ก ์์ง์ด๊ฒ
int stage = 2;
Mons mobs[7];
int mob_int[7] = { 0, 45, 24, 70, 15, 62, 32 }; //๋๋ค ์์น
Mons m1(board_x1, 300, 10, true);
for (int i = 0; i < 7; i++) {
if (i < 3) {
mobs[i].x = board_x1 + (rand() % 100);
mobs[i].y = 100 + (rand() % 500);
mobs[i].speed = 10 + (rand() % 5);
monsters[i] = Object::create("images/๋ชฌ์คํฐ.png", scene, mobs[i].x, mobs[i].y);
mob_timer[i] = Timer::create(0.1f);
}
else {
mobs[i].x = board_x2 - (rand() % 100);
mobs[i].y = board_y2 - (rand() % 500);
mobs[i].speed = 10 + (rand() % 10);
monsters[i] = Object::create("images/๋ชฌ์คํฐ.png", scene, mobs[i].x, mobs[i].y);
mob_timer[i] = Timer::create(0.1f);
}
}
for (int i = 0; i < 7; i++) {
mob_timer[i]->setOnTimerCallback([&, i](TimerPtr t)->bool {
if (mob_int[i] <= 30) { // ์
mobs[i] = up_move(scene, monsters[i], player, mobs[i], player_class, waterbomb, t_monster);
}
else if (30 < mob_int[i] && mob_int[i] <= 40) { // ์๋
mobs[i] = down_move(scene, monsters[i], player, mobs[i], player_class, waterbomb, t_monster);
}
else if (40 < mob_int[i] && mob_int[i] <= 60) { // ์ค๋ฅธ
mobs[i] = right_move(scene, monsters[i], player, mobs[i], player_class, waterbomb, t_monster);
}
else if (60 < mob_int[i] && mob_int[i] <= 80) { //์ผ
mobs[i] = left_move(scene, monsters[i], player, mobs[i], player_class, waterbomb, t_monster);
}
if (mob_int[i] == 81) { // ๊ฐ ๋ชฌ์คํฐ๋ง๋ค ๋ค๋ฅธ ๋๋ค์ผ๋ก ์์ง์ด๋ ์ซ์ ๋ถ์ฌ
mob_int[0] = rand() % 80;
mob_int[1] = rand() % 80;
mob_int[2] = rand() % 80;
mob_int[3] = rand() % 80;
mob_int[4] = rand() % 80;
mob_int[5] = rand() % 80;
mob_int[6] = rand() % 80;
}
if (stage == 2 && mobs[i].islive == true) {
mob_timer[i]->set(0.1f);
mob_timer[i]->start();
mob_int[i]++;
}
if (m_die == 7) {
//๋ชฌ์คํฐ ์ฃฝ์๋์ง
auto winSound = Sound::create("music/Win.mp3");
showMessage("SUCCESS!\n3๋จ๊ณ๋ก ์ด๋ํ์ธ์.");
level = level == 2 ? 3 : level;
m_die = 0;
heart_num = 2;
winSound->play();
bgm->stop();
gameoverTimer->stop();
hideTimer();
Sleep(1000);
lobby_main();
}
if (heart_num == -1) { //์บ๋ฆญํฐ ํํธ ์ฒดํฌ
for (int i = 0; i < 7; i++) {
mob_timer[i]->stop();
}
auto LoseSound = Sound::create("music/Lose.mp3");
showMessage("FAIL!\n๋ค์ ๋์ ํ์ธ์.");
m_die = 0;
heart_num = 2;
LoseSound->play();
bgm->stop();
gameoverTimer->stop();
hideTimer();
Sleep(1000);
lobby_main();
}
return 0;
});
}
bool water_use = false;
scene->setOnKeyboardCallback([&](ScenePtr scene, int key, bool pressed)->bool {
if ((player_class.py < board_y2 - 10 && key == 84)) {
player_class.py = player_class.py + 10;
player->setImage("images/up_01.png");
player->locate(scene, player_class.px, player_class.py);
return 0;
}
else if (player_class.py > board_y1 + 10 && key == 85)
{
player_class.py = player_class.py - 10;
player->setImage("images/down_01.png");
player->locate(scene, player_class.px, player_class.py);
return 0;
}
else if (player_class.px > board_x1 + 10 && key == 82)
{
player_class.px = player_class.px - 10;
player->setImage("images/left_01.png");
player->locate(scene, player_class.px, player_class.py);
return 0;
}
else if (player_class.px < board_x2 - 10 && key == 83)
{
player_class.px = player_class.px + 10;
player->setImage("images/right_01.png");
player->locate(scene, player_class.px, player_class.py);
return 0;
}
else if (board_check(player_class.px, player_class.py) == true && key == 75 && water_use == false)
{
cout << "space" << endl;
water->locate(scene, player_class.px, player_class.py);
waterbomb.bx = player_class.px - 68; // ์ค์ ์์น์ ๋ณด์ด๋ ์์น๋ฅผ ๊ฐ๊ฒ ์กฐ์
waterbomb.by = player_class.py - 68;
water_bomb->locate(scene, waterbomb.bx, waterbomb.by);
water->show();
bomb_set->play();
watertimer1->setOnTimerCallback([&](TimerPtr t)->bool {
waterbomb.isbomb = true;//๋ฌผํ์ ์ด ํฐ์ ธ์์๋๋ง ๋ชฌ์คํฐ ์ฃฝ์.
cout << "water" << endl;
water->hide();
bomb_pop->play();
water_bomb->show();
watertimer2->start();
return 0;
});
watertimer2->setOnTimerCallback([&](TimerPtr t)->bool {
cout << "waterbomb" << endl;
waterbomb.isbomb = false;
water_bomb->hide();
water_use = false;
return 0;
});
watertimer1->start();
water_use = true;
watertimer1->set(1);
watertimer2->set(0.5f);
}
});
for (int i = 0; i < 7; i++) {
mob_timer[i]->start();
}
//์๊ฐ ์ด๊ณผ์ ์คํจ
gameoverTimer->setOnTimerCallback([&](TimerPtr)-> bool {
for (int i = 0; i < 7; i++) {
monsters[i]->hide();
mob_timer[i]->stop();
}
auto LoseSound = Sound::create("music/Lose.mp3");
showMessage("FAIL!\n๋ค์ ๋์ ํ์ธ์.");
m_die = 0;
heart_num = 2;
LoseSound->play();
bgm->stop();
gameoverTimer->stop();
hideTimer();
Sleep(1000);
lobby_main();
return true;
});
gameoverTimer->start();
showTimer(gameoverTimer);
bgm->play(true);
startGame(scene);
}
| 26.447727
| 136
| 0.602475
|
shinysong
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.