hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ec227843bff823854bb7d77c491ca51fad330f4a | 14,023 | hpp | C++ | inc/tlib/String.hpp | tvarney/tlib | 990b65df258dd470839b3209fd80b98426867896 | [
"MIT"
] | null | null | null | inc/tlib/String.hpp | tvarney/tlib | 990b65df258dd470839b3209fd80b98426867896 | [
"MIT"
] | null | null | null | inc/tlib/String.hpp | tvarney/tlib | 990b65df258dd470839b3209fd80b98426867896 | [
"MIT"
] | null | null | null |
#ifndef TLIB_STRING_HPP
#define TLIB_STRING_HPP
#include <stdint.h>
#include <stddef.h>
#include <boost/locale.hpp>
#include <locale>
#include <string>
#include <utility>
namespace tlib {
template <typename Allocator>
class Utf8String {
public:
/**
* \brief Create an empty Utf8String
*/
Utf8String() :
mData()
{ }
/**
* \brief Move a Utf8String
*
* In order to move the string, the allocators have to be of the same
* type. Further, the allocator must be copied - if you want allocators
* with shared state they should delegate the actual operations to
* something accessed through a shared pointer.
*
* \param source The source Utf8String to move
*/
Utf8String(Utf8String<Allocator> &&source) :
mData(std::forward<std::basic_string<char>>(source.mData))
{ }
Utf8String(const std::basic_string<char> &str) :
mData(str)
{ }
Utf8String(std::basic_string<char> &&str) :
mData(std::forward<std::basic_string<char>>(str))
{ }
/**
* \brief Create a Utf8String copy of the given c-string data.
*/
Utf8String(const char *cstr) :
Utf8String(cstr, std::locale())
{ }
Utf8String(const char *cstr, std::locale loc) :
mData(boost::locale::normalize(cstr,
boost::locale::norm_default,
loc))
{ }
/**
* \brief Copy the given Utf8String
*
* This constructor may take Utf8Strings with possibly different
* allocators.
*
* \param source The source Utf8String to copy
*/
template <typename Alloc>
Utf8String(const Utf8String<Alloc> &source) :
mData(source.mData.data())
{ }
/**
* \brief Destroy the Utf8String
*/
~Utf8String() { }
template <typename Alloc>
Utf8String<Allocator> & operator=(const Utf8String<Alloc> &rhs) {
mData = rhs.mData.data();
return *this;
}
Utf8String<Allocator> & operator=(const char *cstr) {
mData = cstr;
return *this;
}
/**
* \brief Get the size of the string
*
* The value returned by this function is the number of bytes stored
* in this buffer.
*
* To get the number of code points in the string, use the length()
* method.
*
* To get the number of characters in the string, use the characters()
* method instead.
*
* \returns The number of code points in the string.
*/
size_t size() const {
return mData.size();
}
/**
* \brief Get the length of the string
*
* To get the size of the buffer use the size() method instead.
*
* To get the number of characters in the string, use the characters()
* method instead.
*
* \returns The number of code points in the string.
*/
size_t length() const {
size_t bsize = mData.size();
size_t count = 0;
for(size_t i = 0; i < bsize; ) {
auto ch = mData.at(i);
if((ch & 0x80) == 0) {
i += 1;
}else if((ch & 0xE0) == 0xC0) {
i += 2;
}else if((ch & 0xF0) == 0xE0) {
i += 3;
}else if((ch & 0xF8) == 0xF0) { //< TODO: Test this
i += 4;
}else if((ch & 0xFC) == 0xF8) { //< TODO: Test this
i += 5;
}else if((ch & 0xFE) == 0xFC) { //< TODO: Test this
i += 6;
}else {
//TODO: Error, this is not a valid utf-8 encoded string
return 0;
}
count += 1;
}
return count;
}
/**
* \brief Get the capacity of the string
*
* The value returned by this is the number of bytes the string buffer
* can hold.
*
* \returns The capacity of the string in bytes
*/
size_t capacity() const {
return mData.capacity();
}
/**
* \brief Get the number of characters in the string
*
* The value returned by this is the number of characters in the
* string. This value is modified by combining characters in such a
* way that
*
* characters() <= length() <= size()
*
* characters() = length() - (# of combining marks/letter pairs)
*
* That is, for each regular character preceeded by a combining
* character, the value of characters() is one less than that of
* length().
*
* \return The number of characters in the string
*/
size_t characters(std::locale const & loc = std::locale()) const {
// I generally don't like doing this, but not doing so causes the
// map type to take a line, and the arguments to take 2
namespace ba = boost::locale::boundary;
typedef ba::segment_index<std::string::const_iterator> MapType;
// This /should/ give us an object we can iterate over to
// examine the characters in the string.
MapType map(ba::character, mData.begin(), mData.end(), loc);
size_t count = 0;
for(auto i = map.begin(); i != map.end(); ++i) {
count += 1;
}
return count;
}
/**
* \brief Test if this string is empty
*
* Functionally equivalent to
*
* size() == 0
* length() == 0
* characters() == 0
*
* \return True if the string is empty.
*/
bool empty() const {
return mData.empty();
}
/**
* \brief Change the size of this string to the new size
*
* The characters inserted into the string are null characters '\0'.
*
* \param size The new size of the string
*/
void resize(size_t size) {
mData.resize(size, '\0');
}
/**
* \brief Change the size of this string to the new size and initialize
*
* The characters inserted into the string are the UTF-8 character
* given
*/
void resize(size_t newsize, char c) {
mData.resize(newsize, c);
}
/**
* \brief Change the size of this string to the new size and initialize
*/
template <typename Alloc>
void resize(size_t newsize, const Utf8String<Alloc> &c) {
//TODO: Write Me!
}
size_t reserve(size_t size) {
mData.reserve(size);
}
/**
* \brief
*/
void clear() {
mData.clear();
}
/**
* \brief Reduces the capacity to fit the length of the string.
*
* Reduces the capacity of the string to be equal to the length of the
* string. Unlike the standard library, the capacity of the string
* after this operation is guaranteed to be equal to the length of the
* string.
*/
void shrink() {
mData.shrink_to_fit();
}
/**
* \brief Return a copy of this string
* \returns A copy of this string
*/
Utf8String copy() const {
return Utf8String(*this);
}
/**
* \brief Convert this string into a unicode normalized form
*
* Perform a conversion of the string which normalizes the contents
* of the string in a unicode defined way.
*
* Any string which is read from the user should have this called on it
* to prevent any problems when comparing strings.
*
* \param loc The locale in which to perform this conversion
* \returns The normalized version of this string
*/
Utf8String normalize(std::locale loc = std::locale()) const {
boost::locale::norm_type n = boost::locale::norm_default;
return Utf8String(boost::locale::normalize(mData, n, loc));
}
/**
* \brief Convert this string to lower case
*
* Perform a full string lower case conversion. Every character in this
* string is converted to its lower case equivalent if one exists.
*
* Note that this is not sufficient for a semantic comparison of the
* contents of the text.
*
* If no locale is given to this function, the global locale is used.
*
* \param loc The locale in which to perform this conversion
* \returns The lower case version of this string
*/
Utf8String lower(std::locale const & loc = std::locale()) const {
return Utf8String(boost::locale::to_lower(mData, loc));
}
/**
* \breif Convert this string to upper case
*
* Perform a full string upper case conversion. Every character in this
* string is converted to its upper case equivalent if one exists.
*
* Note that this is not sufficent for a semantic comparison of the
* contents of the text.
*
* If no locale is given to this function, the global locale is used.
*
* \param loc The locale in which to perform this conversion
* \return A string in which all characters are upper-case
*/
Utf8String upper(std::locale const & loc = std::locale()) const {
return Utf8String(boost::locale::to_upper(mData, loc));
}
/**
* \brief Convert this string to title case
*
* Perform a title-case conversion of the string, which makes the first
* character after each word break upper case and the rest lower case.
*
* If no locale is given to this string, the global locale is used.
*
* \param loc The locale in which to perform this conversion
* \returns A string which has been converted to title-case
*/
Utf8String title(std::locale const & loc = std::locale()) const {
return Utf8String(boost::locale::to_title(mData, loc));
}
/**
* \brief Convert this string into a representation for comparison.
*
* Perform a text fold operation, which converts the underlying unicode
* text into a form which is intended for comparisons.
*
* See http://www.w3.org/International/wiki/Case_folding for more
* information on the subject.
*
* If no locale is given to this function, the global locale is used.
*
* \param loc The locale in which to perform this conversion
* \returns A string intended for semantic comparison
*/
Utf8String fold(std::locale const & loc = std::locale()) const {
return Utf8String(boost::locale::fold_case(mData, loc));
}
/**
* \brief Return a const reference to the underlying std::string
*
* \returns A const reference to the underlying std::string
*/
const std::basic_string<char> & stdstring() const {
return mData;
}
//Utf8String asUtf8() const;
//Utf16String asUtf16() const;
//Utf32String asUtf32() const;
private:
std::basic_string<char> mData;
};
/**
* \brief Check equality of the two Utf8Strings
* \param lhs The Utf8String on the left of the operator==
* \param rhs The Utf8String on the right of the operator==
* \return True if the two Utf8String instances collate to the same thing
*/
template <typename AllocA, typename AllocB>
bool operator==(const Utf8String<AllocA> &lhs,
const Utf8String<AllocB> &rhs)
{
//return (0 == use_facet<collator<char> >(loc).compare(collator_base::secondary,lhs,rhs));
return lhs.stdstring() == rhs.stdstring();
}
/**
* \brief Compare a cstring and a Utf8String for equality
*/
template <typename Alloc>
bool operator==(const char *cstr, const Utf8String<Alloc> &rhs) {
return std::string(cstr) == rhs.stdstring();
}
/**
* \brief Compare a Utf8String and a cstring for equality
*/
template <typename Alloc>
bool operator==(const Utf8String<Alloc> &lhs, const char *rhs) {
return lhs.stdstring() == std::string(rhs);
}
template <typename AllocA, typename AllocB>
bool operator==(const std::basic_string<char, AllocA> &lhs,
const Utf8String<AllocB> &rhs)
{
return lhs == rhs.stdstring();
}
template <typename AllocA, typename AllocB>
bool operator==(const Utf8String<AllocA> &lhs,
const std::basic_string<char, AllocB> &rhs)
{
return lhs.stdstring() == rhs;
}
//template <typename ostream, typename alloc>
//ostream & operator<<(ostream &out, const Utf8String<alloc> &str) {
// return out << str.stdstring();
//}
typedef Utf8String<std::allocator<char>> U8String;
}
#endif
| 34.036408 | 98 | 0.525636 | [
"object"
] |
ec2397b70a7cecf99022df8fd439d9a12465ef1c | 5,631 | cc | C++ | src/main/audio.cc | hisahi/hiemalia | bb5370d6ef0b2480b3b8f563d292ddfab7c0f6e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/main/audio.cc | hisahi/hiemalia | bb5370d6ef0b2480b3b8f563d292ddfab7c0f6e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/main/audio.cc | hisahi/hiemalia | bb5370d6ef0b2480b3b8f563d292ddfab7c0f6e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /****************************************************************************/
/* */
/* HIEMALIA SOURCE CODE (C) 2021 SAMPO HIPPELAINEN (HISAHI). */
/* SEE THE LICENSE FILE IN THE SOURCE ROOT DIRECTORY FOR LICENSE INFO. */
/* */
/****************************************************************************/
// audio.cc: implementation of AudioEngine
#include "audio.hh"
#include "abase.hh"
#include "assetmod.hh"
#include "assets.hh"
#include "file.hh"
namespace hiemalia {
static auto soundEffectNames = hiemalia::makeArray<NamePair<SoundEffect>>(
{{"mselect.wav", SoundEffect::MenuSelect},
{"mmove.wav", SoundEffect::MenuChange},
{"pause.wav", SoundEffect::Pause},
{"explode.wav", SoundEffect::PlayerExplode},
{"hit.wav", SoundEffect::PlayerHit},
{"fire.wav", SoundEffect::PlayerFire},
{"hiscore.wav", SoundEffect::HighScoreEntered},
{"expsmall.wav", SoundEffect::ExplodeSmall},
{"expmed.wav", SoundEffect::ExplodeMedium},
{"explarge.wav", SoundEffect::ExplodeLarge},
{"fizz.wav", SoundEffect::BulletFizz},
{"bhit.wav", SoundEffect::BulletDamage},
{"bnohit.wav", SoundEffect::BulletNoDamage},
{"fire1.wav", SoundEffect::EnemyFire1},
{"fire2.wav", SoundEffect::EnemyFire2},
{"fire3.wav", SoundEffect::EnemyFire3},
{"fire4.wav", SoundEffect::EnemyFire4},
{"fire5.wav", SoundEffect::EnemyFire5},
{"fire6.wav", SoundEffect::EnemyFire6},
{"fire7.wav", SoundEffect::EnemyFire7},
{"place.wav", SoundEffect::BlockerPlace},
{"flip.wav", SoundEffect::DirFlip},
{"awaywego.wav", SoundEffect::Liftoff},
{"1up.wav", SoundEffect::ExtraLife},
{"credit.wav", SoundEffect::Credit}});
void AudioConfig::load(ConfigSectionStore store) {
music = store.get<bool>("Music", music);
sound = store.get<bool>("Sound", sound);
}
void AudioConfig::save(ConfigSectionStore store) const {
store.set<bool>("Music", music);
store.set<bool>("Sound", sound);
}
AudioEngine::AudioEngine(const std::shared_ptr<HostModule>& host,
GameState& state)
: audio_(getAudioModule(host)),
config_(state.config.section<AudioConfig>()) {}
void AudioEngine::load() {
std::vector<sound_t> sounds(
static_cast<std::size_t>(SoundEffect::EndOfSounds), -1);
std::vector<std::string> tracks;
for (const auto& pair : soundEffectNames) {
sounds[static_cast<size_t>(pair.value)] =
audio_->loadSound(buildAssetFilePath("sounds", pair.name));
}
auto file = openAssetFileRead("music", "hiemalia.sng", false);
for (std::string line; std::getline(file, line);) {
tracks.push_back(buildAssetFilePath("music", line));
}
setAssetLoadedSounds(std::move(sounds));
setAssetLoadedMusicTracks(std::move(tracks));
}
static int getLoopCount(MusicTrack track) {
switch (track) {
case MusicTrack::StageStart:
case MusicTrack::GameOver:
return 1;
default:
return 0;
}
}
static int getSoundChannel(SoundEffect sfx) {
switch (sfx) {
case SoundEffect::BulletFizz:
return 0;
case SoundEffect::PlayerFire:
return 1;
case SoundEffect::BulletDamage:
return 2;
case SoundEffect::BulletNoDamage:
return 3;
case SoundEffect::ExplodeSmall:
case SoundEffect::ExplodeMedium:
case SoundEffect::ExplodeLarge:
return 4;
case SoundEffect::Credit:
return 5;
default:
return channelAny;
}
}
void AudioEngine::tick() {}
void AudioEngine::gotMessage(const AudioMessage& msg) {
switch (msg.type) {
case AudioMessageType::PlaySound: {
if (!config_->sound || muted_) return;
const AudioMessageSoundEffect& e = msg.getSound();
sound_t s = getAssets().sounds.at(static_cast<size_t>(e.sound));
if (s != -1)
audio_->playSound(s, e.volume, e.pan, e.pitch, 1,
getSoundChannel(e.sound));
break;
}
case AudioMessageType::StopSounds:
audio_->stopSounds();
break;
case AudioMessageType::PlayMusic: {
if (!config_->music || muted_) return;
MusicTrack m = msg.getMusic();
size_t i = static_cast<size_t>(m);
const auto& tracks = getAssets().musicTracks;
if (i < tracks.size())
audio_->playMusic(tracks[i], getLoopCount(m));
break;
}
case AudioMessageType::FadeOutMusic:
audio_->fadeOutMusic();
break;
case AudioMessageType::StopMusic:
audio_->stopMusic();
break;
case AudioMessageType::Pause:
audio_->pause();
break;
case AudioMessageType::Resume:
audio_->resume();
break;
case AudioMessageType::Mute:
mute();
break;
case AudioMessageType::Unmute:
unmute();
break;
}
}
bool AudioEngine::canPlayMusic() { return audio_->canPlayMusic(); }
bool AudioEngine::canPlaySound() { return audio_->canPlaySound(); }
void AudioEngine::mute() {
muted_ = true;
audio_->stopSounds();
audio_->stopMusic();
}
void AudioEngine::unmute() { muted_ = false; }
bool AudioEngine::isMuted() const { return muted_; }
} // namespace hiemalia
| 33.718563 | 78 | 0.572367 | [
"vector"
] |
ec2427ca95acf6e0627a95681e3f3a2f0e87316c | 2,606 | cc | C++ | larq_compute_engine/mlir/python/graphdef_tfl_flatbuffer.cc | godhj93/compute-engine | 1f812a6722e2ee6a510c883826fd5925f9c34b18 | [
"Apache-2.0"
] | null | null | null | larq_compute_engine/mlir/python/graphdef_tfl_flatbuffer.cc | godhj93/compute-engine | 1f812a6722e2ee6a510c883826fd5925f9c34b18 | [
"Apache-2.0"
] | null | null | null | larq_compute_engine/mlir/python/graphdef_tfl_flatbuffer.cc | godhj93/compute-engine | 1f812a6722e2ee6a510c883826fd5925f9c34b18 | [
"Apache-2.0"
] | null | null | null | #include <exception>
#include "larq_compute_engine/mlir/python/common.h"
#include "larq_compute_engine/mlir/tf_tfl_passes.h"
#include "larq_compute_engine/mlir/tf_to_tfl_flatbuffer.h"
#include "mlir/IR/MLIRContext.h"
#include "pybind11/pybind11.h"
#include "tensorflow/compiler/mlir/lite/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/import_utils.h"
namespace tensorflow {
pybind11::bytes ConvertGraphDefToTFLiteFlatBuffer(
const pybind11::bytes& graphdef_bytes,
const std::vector<string>& input_arrays,
const std::vector<string>& input_dtypes,
const std::vector<std::vector<int>>& input_shapes,
const std::vector<string>& output_arrays, const bool should_quantize,
const std::string& target_str, const pybind11::object& default_ranges) {
GraphDef graphdef;
if (!tensorflow::LoadProtoFromBuffer(std::string(graphdef_bytes), &graphdef)
.ok()) {
throw std::runtime_error("Could not load GraphDef.");
}
auto target = GetLCETarget(target_str);
// `ParseInputArrayInfo` requires a type that isn't pybind compatible, so
// translate here.
std::vector<llvm::Optional<std::vector<int>>> translated_input_shapes;
for (auto x : input_shapes) {
if (x.size() > 0) {
translated_input_shapes.push_back(x);
} else {
translated_input_shapes.push_back(llvm::None);
}
}
GraphImportConfig specs;
specs.prune_unused_nodes = true;
specs.convert_legacy_fed_inputs = true;
specs.graph_as_function = false;
specs.upgrade_legacy = true;
if (!ParseInputArrayInfo(input_arrays, input_dtypes, translated_input_shapes,
&specs.inputs)
.ok()) {
throw std::runtime_error("Could not parse input arrays.");
}
if (!ParseOutputArrayInfo(output_arrays, &specs.outputs).ok()) {
throw std::runtime_error("Could not parse output arrays.");
}
mlir::MLIRContext context;
GraphDebugInfo debug_info;
mlir::StatusScopedDiagnosticHandler statusHandler(&context,
/*propagate=*/true);
auto module = ConvertGraphdefToMlir(graphdef, debug_info, specs, &context);
if (!module.ok()) {
throw std::runtime_error("Could not convert GraphDef.");
}
return ConvertMLIRModuleToTFLiteFlatBuffer(
&module.ValueOrDie(), context, target, default_ranges,
input_arrays.size(), should_quantize,
/*mark_as_post_training_quant=*/false);
}
} // namespace tensorflow
| 36.194444 | 79 | 0.717959 | [
"object",
"vector"
] |
ec26a44a39e1cc936e2e2586908702bd4e82a110 | 11,595 | cpp | C++ | FlexEngine/src/Graphics/Vulkan/VulkanRenderPass.cpp | ajweeks/Rendering-Engine | fe0f2cdb44a067fec875110572b3b91f5f4c659c | [
"MIT"
] | 762 | 2017-11-07T23:40:58.000Z | 2022-03-31T16:03:22.000Z | FlexEngine/src/Graphics/Vulkan/VulkanRenderPass.cpp | ajweeks/Rendering-Engine | fe0f2cdb44a067fec875110572b3b91f5f4c659c | [
"MIT"
] | 5 | 2018-03-13T14:41:06.000Z | 2020-11-01T12:02:29.000Z | FlexEngine/src/Graphics/Vulkan/VulkanRenderPass.cpp | ajweeks/Rendering-Engine | fe0f2cdb44a067fec875110572b3b91f5f4c659c | [
"MIT"
] | 43 | 2017-11-17T11:22:37.000Z | 2022-03-14T01:51:19.000Z | #include "stdafx.hpp"
#if COMPILE_VULKAN
#include "Graphics/Vulkan/VulkanRenderPass.hpp"
#include "Graphics/Vulkan/VulkanDevice.hpp"
#include "Graphics/Vulkan/VulkanHelpers.hpp"
#include "Graphics/Vulkan/VulkanInitializers.hpp"
#include "Graphics/Vulkan/VulkanRenderer.hpp"
namespace flex
{
namespace vk
{
VulkanRenderPass::VulkanRenderPass(VulkanDevice* device) :
m_VulkanDevice(device),
m_RenderPass{ device->m_LogicalDevice, vkDestroyRenderPass }
{
m_FrameBuffer = new FrameBuffer(device);
}
VulkanRenderPass::~VulkanRenderPass()
{
if (!bCreateFrameBuffer)
{
// Prevent cleanup on framebuffers which we don't own
m_FrameBuffer->frameBuffer = VK_NULL_HANDLE;
}
delete m_FrameBuffer;
}
void VulkanRenderPass::Create()
{
assert(m_bRegistered); // This function can only be called on render passes whose Register[...] function has been called
const bool bDepthAttachmentPresent = m_TargetDepthAttachmentID != InvalidFrameBufferAttachmentID;
const u32 colourAttachmentCount = (u32)m_TargetColourAttachmentIDs.size();
const u32 attachmentCount = colourAttachmentCount + (bDepthAttachmentPresent ? 1 : 0);
i32 frameBufferWidth = -1;
i32 frameBufferHeight = -1;
std::vector<VkAttachmentDescription> colourAttachments(colourAttachmentCount);
std::vector<VkAttachmentReference> colourAttachmentReferences(colourAttachmentCount);
std::vector<VkImageView> attachmentImageViews(attachmentCount);
for (u32 i = 0; i < colourAttachmentCount; ++i)
{
FrameBufferAttachment* attachment = bCreateFrameBuffer ? ((VulkanRenderer*)g_Renderer)->GetFrameBufferAttachment(m_TargetColourAttachmentIDs[i]) : nullptr;
colourAttachments[i] = vks::attachmentDescription(attachment ? attachment->format : m_ColourAttachmentFormat, m_TargetColourAttachmentFinalLayouts[i]);
colourAttachmentReferences[i] = VkAttachmentReference{ i, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
if (attachment != nullptr)
{
attachmentImageViews[i] = attachment->view;
if (frameBufferWidth == -1)
{
frameBufferWidth = attachment->width;
frameBufferHeight = attachment->height;
}
}
}
for (u32 i = 0; i < m_TargetColourAttachmentInitialLayouts.size(); ++i)
{
if (m_TargetColourAttachmentInitialLayouts[i] != VK_IMAGE_LAYOUT_UNDEFINED)
{
colourAttachments[i].initialLayout = m_TargetColourAttachmentInitialLayouts[i];
colourAttachments[i].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
}
}
FrameBufferAttachment* depthAttachment = nullptr;
if (bDepthAttachmentPresent && bCreateFrameBuffer)
{
depthAttachment = ((VulkanRenderer*)g_Renderer)->GetFrameBufferAttachment(m_TargetDepthAttachmentID);
attachmentImageViews[attachmentImageViews.size() - 1] = depthAttachment->view;
if (frameBufferWidth == -1)
{
frameBufferWidth = depthAttachment->width;
frameBufferHeight = depthAttachment->height;
}
}
VkAttachmentDescription depthAttachmentDesc = vks::attachmentDescription((bDepthAttachmentPresent && bCreateFrameBuffer) ? depthAttachment->format : m_DepthAttachmentFormat, m_TargetDepthAttachmentFinalLayout);
VkAttachmentReference depthAttachmentRef = { colourAttachmentCount, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
if (m_TargetDepthAttachmentInitialLayout != VK_IMAGE_LAYOUT_UNDEFINED)
{
depthAttachmentDesc.initialLayout = m_TargetDepthAttachmentInitialLayout;
depthAttachmentDesc.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
}
std::vector<VkAttachmentDescription> attachmentDescriptions(attachmentCount);
for (u32 i = 0; i < colourAttachmentCount; ++i)
{
attachmentDescriptions[i] = colourAttachments[i];
}
if (bDepthAttachmentPresent)
{
attachmentDescriptions[attachmentDescriptions.size() - 1] = depthAttachmentDesc;
}
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = (u32)colourAttachmentReferences.size();
subpass.pColorAttachments = colourAttachmentReferences.data();
subpass.pDepthStencilAttachment = bDepthAttachmentPresent ? &depthAttachmentRef : nullptr;
std::array<VkSubpassDependency, 2> dependencies;
dependencies[0] = {};
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
dependencies[1] = {};
dependencies[1].srcSubpass = 0;
dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
VkRenderPassCreateInfo renderPassCreateInfo = vks::renderPassCreateInfo();
renderPassCreateInfo.attachmentCount = (u32)attachmentDescriptions.size();
renderPassCreateInfo.pAttachments = attachmentDescriptions.data();
renderPassCreateInfo.subpassCount = 1;
renderPassCreateInfo.pSubpasses = &subpass;
renderPassCreateInfo.dependencyCount = (u32)dependencies.size();
renderPassCreateInfo.pDependencies = dependencies.data();
if (bCreateFrameBuffer)
{
assert(frameBufferWidth != -1 && frameBufferHeight != -1);
}
Create(m_Name, &renderPassCreateInfo, attachmentImageViews, frameBufferWidth, frameBufferHeight);
}
void VulkanRenderPass::Register(
const char* passName,
const std::vector<FrameBufferAttachmentID>& targtColourAttachmentIDs,
FrameBufferAttachmentID targtDepthAttachmentID,
const std::vector<FrameBufferAttachmentID>& sampledAttachmentIDs)
{
m_TargetColourAttachmentIDs = targtColourAttachmentIDs;
m_TargetDepthAttachmentID = targtDepthAttachmentID;
m_SampledAttachmentIDs = sampledAttachmentIDs;
m_Name = passName;
m_TargetColourAttachmentFinalLayouts.resize(targtColourAttachmentIDs.size(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
m_TargetColourAttachmentInitialLayouts.resize(targtColourAttachmentIDs.size(), VK_IMAGE_LAYOUT_UNDEFINED);
m_bRegistered = true;
}
void VulkanRenderPass::RegisterForColourAndDepth(
const char* passName,
FrameBufferAttachmentID targetColourAttachmentID,
FrameBufferAttachmentID targetDepthAttachmentID,
const std::vector<FrameBufferAttachmentID>& sampledAttachmentIDs)
{
Register(passName, { targetColourAttachmentID }, targetDepthAttachmentID, sampledAttachmentIDs);
}
void VulkanRenderPass::RegisterForMultiColourAndDepth(
const char* passName,
const std::vector<FrameBufferAttachmentID>& targetColourAttachmentIDs,
FrameBufferAttachmentID targetDepthAttachmentID,
const std::vector<FrameBufferAttachmentID>& sampledAttachmentIDs)
{
Register(passName, targetColourAttachmentIDs, targetDepthAttachmentID, sampledAttachmentIDs);
}
void VulkanRenderPass::RegisterForDepthOnly(
const char* passName,
FrameBufferAttachmentID targetDepthAttachmentID,
const std::vector<FrameBufferAttachmentID>& sampledAttachmentIDs)
{
Register(passName, {}, targetDepthAttachmentID, sampledAttachmentIDs);
}
void VulkanRenderPass::RegisterForColourOnly(
const char* passName,
FrameBufferAttachmentID targetColourAttachmentID,
const std::vector<FrameBufferAttachmentID>& sampledAttachmentIDs)
{
Register(passName, { targetColourAttachmentID }, InvalidFrameBufferAttachmentID, sampledAttachmentIDs);
}
void VulkanRenderPass::ManuallySpecifyLayouts(
const std::vector<VkImageLayout>& finalLayouts, // VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
const std::vector<VkImageLayout>& initialLayouts, // VK_IMAGE_LAYOUT_UNDEFINED
VkImageLayout finalDepthLayout /* = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL */,
VkImageLayout initialDepthLayout /* = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL */)
{
m_TargetColourAttachmentFinalLayouts = finalLayouts;
m_TargetColourAttachmentInitialLayouts = initialLayouts;
m_TargetDepthAttachmentFinalLayout = finalDepthLayout;
m_TargetDepthAttachmentInitialLayout = initialDepthLayout;
}
VkRenderPass* VulkanRenderPass::Replace()
{
return m_RenderPass.replace();
}
VulkanRenderPass::operator VkRenderPass()
{
return m_RenderPass;
}
void VulkanRenderPass::Begin(VkCommandBuffer cmdBuf, VkClearValue* clearValues, u32 clearValueCount)
{
Begin(cmdBuf, clearValues, clearValueCount, m_FrameBuffer);
}
void VulkanRenderPass::Begin_WithFrameBuffer(VkCommandBuffer cmdBuf, VkClearValue* clearValues, u32 clearValueCount, FrameBuffer* targetFrameBuffer)
{
Begin(cmdBuf, clearValues, clearValueCount, targetFrameBuffer);
}
void VulkanRenderPass::End()
{
if (m_ActiveCommandBuffer == VK_NULL_HANDLE)
{
PrintError("Attempted to end render pass which has invalid m_ActiveCommandBuffer (%s)", m_Name);
return;
}
vkCmdEndRenderPass(m_ActiveCommandBuffer);
m_ActiveCommandBuffer = VK_NULL_HANDLE;
}
void VulkanRenderPass::Create(
const char* passName,
VkRenderPassCreateInfo* inCreateInfo,
const std::vector<VkImageView>& attachmentImageViews,
u32 frameBufferWidth,
u32 frameBufferHeight)
{
m_Name = passName;
VK_CHECK_RESULT(vkCreateRenderPass(m_VulkanDevice->m_LogicalDevice, inCreateInfo, nullptr, m_RenderPass.replace()));
VulkanRenderer::SetRenderPassName(m_VulkanDevice, m_RenderPass, m_Name);
if (bCreateFrameBuffer)
{
VkFramebufferCreateInfo framebufferInfo = vks::framebufferCreateInfo(m_RenderPass);
framebufferInfo.attachmentCount = (u32)attachmentImageViews.size();
framebufferInfo.pAttachments = attachmentImageViews.data();
framebufferInfo.width = frameBufferWidth;
framebufferInfo.height = frameBufferHeight;
VK_CHECK_RESULT(vkCreateFramebuffer(m_VulkanDevice->m_LogicalDevice, &framebufferInfo, nullptr, m_FrameBuffer->Replace()));
m_FrameBuffer->width = frameBufferWidth;
m_FrameBuffer->height = frameBufferHeight;
char name[256];
sprintf(name, "%s frame buffer", passName);
VulkanRenderer::SetFramebufferName(m_VulkanDevice, m_FrameBuffer->frameBuffer, name);
}
}
void VulkanRenderPass::Begin(VkCommandBuffer cmdBuf, VkClearValue* clearValues, u32 clearValueCount, FrameBuffer* targetFrameBuffer)
{
if (m_ActiveCommandBuffer != VK_NULL_HANDLE)
{
PrintError("Attempted to begin render pass (%s) multiple times! Did you forget to call End?\n", m_Name);
return;
}
m_ActiveCommandBuffer = cmdBuf;
VkRenderPassBeginInfo renderPassBeginInfo = vks::renderPassBeginInfo(m_RenderPass);
renderPassBeginInfo.renderPass = m_RenderPass;
renderPassBeginInfo.framebuffer = targetFrameBuffer->frameBuffer;
renderPassBeginInfo.renderArea.offset = { 0, 0 };
renderPassBeginInfo.renderArea.extent = { targetFrameBuffer->width, targetFrameBuffer->height };
renderPassBeginInfo.clearValueCount = clearValueCount;
renderPassBeginInfo.pClearValues = clearValues;
vkCmdBeginRenderPass(cmdBuf, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
}
} // namespace vk
} // namespace flex
#endif // COMPILE_VULKAN | 39.305085 | 213 | 0.784649 | [
"render",
"vector"
] |
ec2f25316431ea7aee9035835288a276ad5d8634 | 14,344 | cpp | C++ | RobWork/src/rwlibs/opengl/RWGLFrameBuffer.cpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | 1 | 2021-12-29T14:16:27.000Z | 2021-12-29T14:16:27.000Z | RobWork/src/rwlibs/opengl/RWGLFrameBuffer.cpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | RobWork/src/rwlibs/opengl/RWGLFrameBuffer.cpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | /********************************************************************************
* Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,
* Faculty of Engineering, University of Southern Denmark
*
* 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 "RWGLFrameBuffer.hpp"
#include <rw/core/Log.hpp>
#include <rw/core/LogWriter.hpp>
using namespace rw::core;
using namespace rwlibs::opengl;
bool RWGLFrameBuffer::_hasFrameBuffers = false;
bool RWGLFrameBuffer::_frameBuffersInitialized = false;
// Framebuffer object
PFNGLGENFRAMEBUFFERSEXTPROC RWGLFrameBuffer::glGenFramebuffersEXT =
0; // FBO name generation procedure
PFNGLDELETEFRAMEBUFFERSEXTPROC RWGLFrameBuffer::glDeleteFramebuffersEXT =
0; // FBO deletion procedure
PFNGLBINDFRAMEBUFFEREXTPROC RWGLFrameBuffer::glBindFramebufferEXT = 0; // FBO bind procedure
PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC RWGLFrameBuffer::glCheckFramebufferStatusEXT =
0; // FBO completeness test procedure
PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC
RWGLFrameBuffer::glGetFramebufferAttachmentParameterivEXT = 0; // return various FBO parameters
PFNGLGENERATEMIPMAPEXTPROC RWGLFrameBuffer::glGenerateMipmapEXT =
0; // FBO automatic mipmap generation procedure
PFNGLFRAMEBUFFERTEXTURE2DEXTPROC RWGLFrameBuffer::glFramebufferTexture2DEXT =
0; // FBO texdture attachement procedure
PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC RWGLFrameBuffer::glFramebufferRenderbufferEXT =
0; // FBO renderbuffer attachement procedure
// Renderbuffer object
PFNGLGENRENDERBUFFERSEXTPROC RWGLFrameBuffer::glGenRenderbuffersEXT =
0; // renderbuffer generation procedure
PFNGLDELETERENDERBUFFERSEXTPROC RWGLFrameBuffer::glDeleteRenderbuffersEXT =
0; // renderbuffer deletion procedure
PFNGLBINDRENDERBUFFEREXTPROC RWGLFrameBuffer::glBindRenderbufferEXT =
0; // renderbuffer bind procedure
PFNGLRENDERBUFFERSTORAGEEXTPROC RWGLFrameBuffer::glRenderbufferStorageEXT =
0; // renderbuffer memory allocation procedure
PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC RWGLFrameBuffer::glGetRenderbufferParameterivEXT =
0; // return various renderbuffer parameters
PFNGLISRENDERBUFFEREXTPROC RWGLFrameBuffer::glIsRenderbufferEXT =
0; // determine renderbuffer object type
PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC RWGLFrameBuffer::glRenderbufferStorageMultisampleEXT = 0;
PFNGLTEXIMAGE2DMULTISAMPLEPROC RWGLFrameBuffer::glTexImage2DMultisample = 0;
PFNGLBLITFRAMEBUFFEREXTPROC RWGLFrameBuffer::glBlitFrameBufferEXT = 0;
bool RWGLFrameBuffer::initialize ()
{
if (_frameBuffersInitialized)
return _hasFrameBuffers;
// check if FBO is supported by your video card
// if(glInfo.isExtensionSupported("GL_EXT_framebuffer_object"))
#if defined(RW_WIN32)
// get pointers to GL functions
glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) wglGetProcAddress ("glGenFramebuffersEXT");
glDeleteFramebuffersEXT =
(PFNGLDELETEFRAMEBUFFERSEXTPROC) wglGetProcAddress ("glDeleteFramebuffersEXT");
glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) wglGetProcAddress ("glBindFramebufferEXT");
glCheckFramebufferStatusEXT =
(PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) wglGetProcAddress ("glCheckFramebufferStatusEXT");
glGetFramebufferAttachmentParameterivEXT =
(PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) wglGetProcAddress (
"glGetFramebufferAttachmentParameterivEXT");
glGenerateMipmapEXT = (PFNGLGENERATEMIPMAPEXTPROC) wglGetProcAddress ("glGenerateMipmapEXT");
glFramebufferTexture2DEXT =
(PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) wglGetProcAddress ("glFramebufferTexture2DEXT");
glFramebufferRenderbufferEXT =
(PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) wglGetProcAddress ("glFramebufferRenderbufferEXT");
glGenRenderbuffersEXT =
(PFNGLGENRENDERBUFFERSEXTPROC) wglGetProcAddress ("glGenRenderbuffersEXT");
glDeleteRenderbuffersEXT =
(PFNGLDELETERENDERBUFFERSEXTPROC) wglGetProcAddress ("glDeleteRenderbuffersEXT");
glBindRenderbufferEXT =
(PFNGLBINDRENDERBUFFEREXTPROC) wglGetProcAddress ("glBindRenderbufferEXT");
glRenderbufferStorageEXT =
(PFNGLRENDERBUFFERSTORAGEEXTPROC) wglGetProcAddress ("glRenderbufferStorageEXT");
glGetRenderbufferParameterivEXT = (PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) wglGetProcAddress (
"glGetRenderbufferParameterivEXT");
glIsRenderbufferEXT = (PFNGLISRENDERBUFFEREXTPROC) wglGetProcAddress ("glIsRenderbufferEXT");
glRenderbufferStorageMultisampleEXT =
(PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) wglGetProcAddress (
"glRenderbufferStorageMultisampleEXT");
glTexImage2DMultisample =
(PFNGLTEXIMAGE2DMULTISAMPLEPROC) wglGetProcAddress ("glTexImage2DMultisample");
glBlitFrameBufferEXT = (PFNGLBLITFRAMEBUFFEREXTPROC) wglGetProcAddress ("glBlitFramebufferEXT");
#elif defined(RW_MACOS)
glGenFramebuffersEXT = &glGenFramebuffers;
glDeleteFramebuffersEXT = &glDeleteFramebuffers;
glBindFramebufferEXT = &glBindFramebuffer;
glCheckFramebufferStatusEXT = &glCheckFramebufferStatus;
glGetFramebufferAttachmentParameterivEXT = &glGetFramebufferAttachmentParameteriv;
glGenerateMipmapEXT = &glGenerateMipmap;
glFramebufferTexture2DEXT = &glFramebufferTexture2D;
glFramebufferRenderbufferEXT = &glFramebufferRenderbuffer;
glGenRenderbuffersEXT = &glGenRenderbuffers;
glDeleteRenderbuffersEXT = &glDeleteRenderbuffers;
glBindRenderbufferEXT = &glBindRenderbuffer;
glRenderbufferStorageEXT = &glRenderbufferStorage;
glGetRenderbufferParameterivEXT = &glGetRenderbufferParameteriv;
glIsRenderbufferEXT = &glIsRenderbuffer;
glRenderbufferStorageMultisampleEXT = glRenderbufferStorageMultisampleEXT;
glTexImage2DMultisample = glTexImage2DMultisample;
glBlitFrameBufferEXT = glBlitFrameBufferEXT;
#else
// get pointers to GL functions
glGenFramebuffersEXT =
(PFNGLGENFRAMEBUFFERSEXTPROC) glXGetProcAddress ((GLubyte*) "glGenFramebuffersEXT");
glDeleteFramebuffersEXT =
(PFNGLDELETEFRAMEBUFFERSEXTPROC) glXGetProcAddress ((GLubyte*) "glDeleteFramebuffersEXT");
glBindFramebufferEXT =
(PFNGLBINDFRAMEBUFFEREXTPROC) glXGetProcAddress ((GLubyte*) "glBindFramebufferEXT");
glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) glXGetProcAddress (
(GLubyte*) "glCheckFramebufferStatusEXT");
glGetFramebufferAttachmentParameterivEXT =
(PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) glXGetProcAddress (
(GLubyte*) "glGetFramebufferAttachmentParameterivEXT");
glGenerateMipmapEXT =
(PFNGLGENERATEMIPMAPEXTPROC) glXGetProcAddress ((GLubyte*) "glGenerateMipmapEXT");
glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) glXGetProcAddress (
(GLubyte*) "glFramebufferTexture2DEXT");
glFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) glXGetProcAddress (
(GLubyte*) "glFramebufferRenderbufferEXT");
glGenRenderbuffersEXT =
(PFNGLGENRENDERBUFFERSEXTPROC) glXGetProcAddress ((GLubyte*) "glGenRenderbuffersEXT");
glDeleteRenderbuffersEXT =
(PFNGLDELETERENDERBUFFERSEXTPROC) glXGetProcAddress ((GLubyte*) "glDeleteRenderbuffersEXT");
glBindRenderbufferEXT =
(PFNGLBINDRENDERBUFFEREXTPROC) glXGetProcAddress ((GLubyte*) "glBindRenderbufferEXT");
glRenderbufferStorageEXT =
(PFNGLRENDERBUFFERSTORAGEEXTPROC) glXGetProcAddress ((GLubyte*) "glRenderbufferStorageEXT");
glGetRenderbufferParameterivEXT = (PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) glXGetProcAddress (
(GLubyte*) "glGetRenderbufferParameterivEXT");
glIsRenderbufferEXT =
(PFNGLISRENDERBUFFEREXTPROC) glXGetProcAddress ((GLubyte*) "glIsRenderbufferEXT");
glRenderbufferStorageMultisampleEXT =
(PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) glXGetProcAddress (
(GLubyte*) "glRenderbufferStorageMultisampleEXT");
glTexImage2DMultisample =
(PFNGLTEXIMAGE2DMULTISAMPLEPROC) glXGetProcAddress ((GLubyte*) "glTexImage2DMultisample");
glBlitFrameBufferEXT =
(PFNGLBLITFRAMEBUFFEREXTPROC) glXGetProcAddress ((GLubyte*) "glBlitFramebufferEXT");
#endif
// check once again FBO extension
if (glGenFramebuffersEXT && glDeleteFramebuffersEXT && glBindFramebufferEXT &&
glCheckFramebufferStatusEXT && glGetFramebufferAttachmentParameterivEXT &&
glGenerateMipmapEXT && glFramebufferTexture2DEXT && glFramebufferRenderbufferEXT &&
glGenRenderbuffersEXT && glDeleteRenderbuffersEXT && glBindRenderbufferEXT &&
glRenderbufferStorageEXT && glGetRenderbufferParameterivEXT && glIsRenderbufferEXT
#if !defined(RW_MACOS)
&& glTexImage2DMultisample && glRenderbufferStorageMultisampleEXT && glBlitFrameBufferEXT
#endif
) {
_hasFrameBuffers = true;
std::cout << "Video card supports GL_EXT_framebuffer_object." << std::endl;
}
else {
_hasFrameBuffers = false;
std::cout << "Video card does NOT support GL_EXT_framebuffer_object." << std::endl;
}
_frameBuffersInitialized = true;
return _hasFrameBuffers;
}
void RWGLFrameBuffer::test (LogWriter& log)
{
GLint var;
glGetIntegerv (GL_MAX_RENDERBUFFER_SIZE_EXT, &var);
(log) << "GL_MAX_RENDERBUFFER_SIZE_EXT: " << var << std::endl;
glGetRenderbufferParameterivEXT (GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_WIDTH_EXT, &var);
(log) << "GL_RENDERBUFFER_WIDTH_EXT: " << var << std::endl;
glGetRenderbufferParameterivEXT (GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_HEIGHT_EXT, &var);
(log) << "GL_RENDERBUFFER_HEIGHT_EXT: " << var << std::endl;
glGetRenderbufferParameterivEXT (
GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_INTERNAL_FORMAT_EXT, &var);
(log) << "GL_RENDERBUFFER_INTERNAL_FORMAT_EXT: " << var << std::endl;
glGetRenderbufferParameterivEXT (GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_RED_SIZE_EXT, &var);
(log) << "GL_RENDERBUFFER_RED_SIZE_EXT: " << var << std::endl;
glGetRenderbufferParameterivEXT (GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_GREEN_SIZE_EXT, &var);
(log) << "GL_RENDERBUFFER_GREEN_SIZE_EXT: " << var << std::endl;
glGetRenderbufferParameterivEXT (GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_BLUE_SIZE_EXT, &var);
(log) << "GL_RENDERBUFFER_BLUE_SIZE_EXT: " << var << std::endl;
glGetRenderbufferParameterivEXT (GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_ALPHA_SIZE_EXT, &var);
(log) << "GL_RENDERBUFFER_ALPHA_SIZE_EXT: " << var << std::endl;
glGetRenderbufferParameterivEXT (GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_DEPTH_SIZE_EXT, &var);
(log) << "GL_RENDERBUFFER_DEPTH_SIZE_EXT: " << var << std::endl;
glGetRenderbufferParameterivEXT (GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_STENCIL_SIZE_EXT, &var);
(log) << "GL_RENDERBUFFER_STENCIL_SIZE_EXT: " << var << std::endl;
}
bool RWGLFrameBuffer::testFrameBufferCompleteness ()
{
GLenum status;
status = RWGLFrameBuffer::glCheckFramebufferStatusEXT (GL_FRAMEBUFFER_EXT);
switch (status) {
case GL_FRAMEBUFFER_COMPLETE_EXT: return true; break;
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
// Choose different formats
Log::errorLog () << "Framebuffer object format is unsupported by the video hardware. "
"(GL_FRAMEBUFFER_UNSUPPORTED_EXT)(FBO - 820)";
break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
Log::errorLog ()
<< "Incomplete attachment. (GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT)(FBO - 820)";
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
Log::errorLog () << "Incomplete missing attachment. "
"(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT)(FBO - 820)";
break;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
Log::errorLog ()
<< "Incomplete dimensions. (GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT)(FBO - 820)";
break;
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
Log::errorLog ()
<< "Incomplete formats. (GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT)(FBO - 820)";
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
Log::errorLog ()
<< "Incomplete draw buffer. (GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT)(FBO - 820)";
break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
Log::errorLog ()
<< "Incomplete read buffer. (GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT)(FBO - 820)";
break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT:
Log::errorLog () << "Incomplete multisample buffer. "
"(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT)(FBO - 820)";
break;
default:
// Programming error; will fail on all hardware
Log::errorLog () << "Some video driver error or programming error occured. Framebuffer "
"object status is invalid. (FBO - 823)";
}
return false;
}
bool RWGLFrameBuffer::hasFrameBuffers ()
{
return _hasFrameBuffers;
}
bool RWGLFrameBuffer::isFrameBuffersInitialized ()
{
return _frameBuffersInitialized;
}
RWGLFrameBuffer::RWGLFrameBuffer ()
{}
| 53.125926 | 100 | 0.725669 | [
"object"
] |
ec39dece7e174bce1f8d070800313209bac31f36 | 713 | cpp | C++ | CodeForces/Complete/100-199/159C-StringManipulation.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/100-199/159C-StringManipulation.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/100-199/159C-StringManipulation.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <iostream>
#include <vector>
#include <set>
int main(){
const int N = 26;
std::ios_base::sync_with_stdio(false);
long k; std::cin >> k;
std::string s; std::cin >> s;
std::string t("");
for(long p = 0; p < k; p++){t += s;}
std::vector<std::vector<long> > m(N);
std::vector<bool> f(t.size(), 1);
for(long p = 0; p < t.size(); p++){m[t[p] - 'a'].push_back(p);}
long n; std::cin >> n;
while(n--){
long r; char c; std::cin >> r >> c;
int cc = c - 'a';
f[m[cc][r - 1]] = 0;
m[cc].erase(m[cc].begin() + r - 1);
}
for(long p = 0; p < t.size(); p++){if(f[p]){std::cout << t[p];}}
std::cout << std::endl;
return 0;
}
| 23.766667 | 68 | 0.465638 | [
"vector"
] |
ec39e70f029eb63e379218d18d0b49c9349d7846 | 1,511 | hh | C++ | gazebo/gui/model/ModelEditorPalette_TEST.hh | shyamalschandra/gazebo-official | 0b2d72d8ad7ef17c0b3e5aea627c3ec1753310c5 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2015-04-06T16:17:36.000Z | 2015-04-06T16:17:36.000Z | gazebo/gui/model/ModelEditorPalette_TEST.hh | shyamalschandra/gazebo-official | 0b2d72d8ad7ef17c0b3e5aea627c3ec1753310c5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | gazebo/gui/model/ModelEditorPalette_TEST.hh | shyamalschandra/gazebo-official | 0b2d72d8ad7ef17c0b3e5aea627c3ec1753310c5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2015 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _GAZEBO_MODEL_EDITOR_PALETTE_TEST_HH_
#define _GAZEBO_MODEL_EDITOR_PALETTE_TEST_HH_
#include "gazebo/gui/QTestFixture.hh"
/// \brief A test class for the ModelEditorPalette class.
class ModelEditorPalette_TEST : public QTestFixture
{
Q_OBJECT
/// \brief Tests loading nested models.
/// FIXME: This test only passes if ran before the others, otherwise it
/// crashes on QCoreApplication::processEvents
private slots: void LoadNestedModel();
/// \brief Tests adding an item to the palette.
private slots: void AddItem();
/// \brief Tests the nested model list.
private slots: void AddRemoveNestedModels();
/// \brief Tests the link list.
private slots: void AddRemoveLinks();
/// \brief Tests the joint list.
private slots: void AddRemoveJoints();
/// \brief Tests the model plugin list.
private slots: void AddRemoveModelPlugins();
};
#endif
| 30.22 | 75 | 0.741231 | [
"model"
] |
ec4290c9c9d77d5a14c0ad56081daec79634ccaa | 1,454 | cc | C++ | codeforces/593/A.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | codeforces/593/A.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | codeforces/593/A.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
using vi = vector<int>; using vvi = vector<vi>;
using ii = pair<int,int>; using vii = vector<ii>;
using l = long long; using vl = vector<l>; using vvl = vector<vl>;
using lu = unsigned long long;
using vb = vector<bool>; using vvb = vector<vb>;
using vd = vector<double>; using vvd = vector<vd>;
const int INF = numeric_limits<int>::max();
const double EPS = 1e-10;
const l e5 = 100000, e6 = 1000000, e7 = 10000000, e9 = 1000000000;
const l MAX = 26;
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
l n;
while (cin >> n) {
l count[MAX][MAX] = {0};
for (l i = 0; i < n; i++) {
string s;
cin >> s;
char a = ' ';
char b = ' ';
for (auto c : s) {
if (a == ' ' || a == c) {
a = c;
continue;
}
if (b == ' ' || b == c) {
b = c;
continue;
}
a = ' ';
break;
}
if (a == ' ') continue;
l k = s.size();
if (b == ' ') {
for (l j = 0; j < MAX; j++) {
if (j == (a - 'a')) continue;
count[a - 'a'][j] += k;
count[j][a - 'a'] += k;
}
} else {
count[a - 'a'][b - 'a'] += k;
count[b - 'a'][a - 'a'] += k;
}
}
l best = 0;
for (l i = 0; i < MAX; i++) {
for (l j = 0; j < MAX; j++) {
best = max(best, count[i][j]);
}
}
cout << best << endl;
}
}
| 24.233333 | 66 | 0.429161 | [
"vector"
] |
ec4c1e28caf95bc9a84504f2d1e633540f802f76 | 861 | cc | C++ | leetcode/66-plus-one.cc | Stone-Zeng/toys | ca040cb1b1546cdb422940f3785c6b1a5624bc89 | [
"MIT"
] | 6 | 2019-03-11T10:38:02.000Z | 2022-01-07T08:55:58.000Z | leetcode/66-plus-one.cc | Stone-Zeng/toys | ca040cb1b1546cdb422940f3785c6b1a5624bc89 | [
"MIT"
] | null | null | null | leetcode/66-plus-one.cc | Stone-Zeng/toys | ca040cb1b1546cdb422940f3785c6b1a5624bc89 | [
"MIT"
] | 1 | 2021-03-05T02:03:11.000Z | 2021-03-05T02:03:11.000Z | // 66. Plus One
// https://leetcode.com/problems/plus-one/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for (auto iter = digits.rbegin(); iter != digits.rend(); ++iter) {
if (*iter != 9) {
(*iter)++;
return digits;
}
*iter = 0;
if (iter + 1 == digits.rend()) {
digits.insert(digits.begin(), 1);
return digits;
}
}
return digits;
}
};
int main() {
vector<vector<int>> data = {
{1,2,3},
{1,2,3,4},
{1,2,3,9},
{9},
{9,9,9,9},
{0},
};
for (auto v: data) {
Solution sol;
for (auto i: sol.plusOne(v)) cout << i << ", ";
cout << endl;
}
}
| 21 | 74 | 0.426249 | [
"vector"
] |
ec4d4c0514d97c7a1ef6e613f1975cbd77ade366 | 4,782 | hpp | C++ | core/algorithms/partitioning/seed_partitioner.hpp | wickedb/LSOracle | ec2df3a3c9c1cc3b1c2dd7ca4dc7a52285781110 | [
"MIT"
] | 37 | 2018-08-12T11:25:57.000Z | 2020-11-30T16:09:41.000Z | core/algorithms/partitioning/seed_partitioner.hpp | wickedb/LSOracle | ec2df3a3c9c1cc3b1c2dd7ca4dc7a52285781110 | [
"MIT"
] | 28 | 2021-02-18T22:09:38.000Z | 2022-03-09T08:08:14.000Z | core/algorithms/partitioning/seed_partitioner.hpp | wickedb/LSOracle | ec2df3a3c9c1cc3b1c2dd7ca4dc7a52285781110 | [
"MIT"
] | 15 | 2021-02-26T17:10:24.000Z | 2022-03-26T12:41:45.000Z | /* LSOracle: A learning based Oracle for Logic Synthesis
* MIT License
* Copyright 2019 Laboratory for Nano Integrated Systems (LNIS)
*
* 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 <algorithm>
#include <cstdint>
#include <unordered_map>
#include <vector>
#include <set>
#include <cassert>
#include <mockturtle/mockturtle.hpp>
#include <libkahypar.h>
namespace oracle
{
/*! \brief Partitions circuit using multi-level hypergraph partitioner
*
*/
template<typename Ntk>
class seed_partitioner : public Ntk
{
public:
using storage = typename Ntk::storage;
using node = typename Ntk::node;
using signal = typename Ntk::signal;
public:
seed_partitioner() {}
seed_partitioner(Ntk const &ntk, int pi_const, int node_count_const) : Ntk(ntk)
{
static_assert(mockturtle::is_network_type_v<Ntk>, "Ntk is not a network type");
static_assert(mockturtle::has_set_visited_v<Ntk>,
"Ntk does not implement the set_visited method");
static_assert(mockturtle::has_visited_v<Ntk>,
"Ntk does not implement the visited method");
static_assert(mockturtle::has_get_node_v<Ntk>,
"Ntk does not implement the get_node method");
static_assert(mockturtle::has_get_constant_v<Ntk>,
"Ntk does not implement the get_constant method");
static_assert(mockturtle::has_is_constant_v<Ntk>,
"Ntk does not implement the is_constant method");
static_assert(mockturtle::has_make_signal_v<Ntk>,
"Ntk does not implement the make_signal method");
mockturtle::topo_view top_view{ntk};
std::vector<node> nodes2part = top_view.get_node_vec();
// std::reverse(nodes2part.begin(), nodes2part.end());
std::map<node, bool> visited;
for (int i = 0; i < nodes2part.size(); i++) {
visited[nodes2part.at(i)] = false;
}
int num_pi = 0;
int num_int = 0;
int part_idx = 0;
for (int i = 0; i < nodes2part.size(); i++) {
auto curr_node = nodes2part.at(i);
std::cout << "Current node = " << curr_node << "\n";
if (visited[curr_node] == true) {
continue;
}
int new_pi = 0;
ntk.foreach_fanin(curr_node, [&](auto conn, auto i) {
std::cout << "fanin = " << conn.index << "\n";
if (visited[ntk.get_node(conn)] == false) {
new_pi = 1;
}
});
if (new_pi == 1 || ntk.is_pi(curr_node)) {
std::cout << "increase pi count\n";
num_pi++;
} else {
std::cout << "increase internal node count\n";
num_int++;
}
visited[curr_node] = true;
mapped_part[curr_node] = part_idx;
std::cout << "num pi = " << num_pi << "\n";
std::cout << "num internal nodes = " << num_int << "\n";
if (num_pi >= pi_const && num_int >= node_count_const) {
std::cout << "Create partition\n";
part_idx++;
num_partitions++;
num_pi = 0;
num_int = 0;
for (int j = 0; j < nodes2part.size(); j++) {
visited[nodes2part.at(j)] = false;
}
}
}
}
partition_manager<Ntk> create_part_man(Ntk const &ntk)
{
partition_manager<Ntk> part_man(ntk, mapped_part, num_partitions);
return part_man;
}
private:
int num_partitions = 1;
std::map<node, int> mapped_part;
};
} /* namespace oracle */
| 33.440559 | 87 | 0.599749 | [
"vector"
] |
ec559ef457f39be718358e5e117e645a0228695a | 4,636 | cpp | C++ | SMOL/Misc/StringUtils.cpp | all500234765/SMOL | d6f1e9401105cd1bf2209f30311dc90bcc78e43b | [
"MIT"
] | null | null | null | SMOL/Misc/StringUtils.cpp | all500234765/SMOL | d6f1e9401105cd1bf2209f30311dc90bcc78e43b | [
"MIT"
] | null | null | null | SMOL/Misc/StringUtils.cpp | all500234765/SMOL | d6f1e9401105cd1bf2209f30311dc90bcc78e43b | [
"MIT"
] | null | null | null | #include "pc.h"
#include "StringUtils.h"
#include "Misc/Log.h"
#include <sstream>
#include <cstring>
#include <cstdarg>
#include <string>
template <typename T>
std::string ToString(T val)
{
std::stringstream stream;
stream << val;
return stream.str();
}
String Bytes2String(size_t bytes) {
const StringView str[] = { " byte" , " bytes" , " KByte", " KBytes",
" MByte", " MBytes", " GByte", " GBytes" };
u32 index = 0;
u64 res = bytes;
for( u32 i = 1, j = 0; bytes > i && j < 4; j++, i *= 1024 ) {
if( bytes == i ) {
index = j * 2;
break;
} else if( bytes < 1024 * i ) {
index = j * 2 + 1;
break;
}
res /= 1024;
}
return ToString(res) + str[index].data();
}
String StringReplace(String &str, StringView substr, StringView replace_with) {
u64 pos = str.find(substr.data());
while( pos != String::npos ) {
str.replace(pos, substr.size(), replace_with.data());
pos = str.find(substr.data(), pos + replace_with.size());
}
return str;
}
StringW StringReplace(StringW &str, StringWView substr, StringWView replace_with) {
u64 pos = str.find(substr.data());
while( pos != StringW::npos ) {
str.replace(pos, substr.size(), replace_with.data());
pos = str.find(substr.data(), pos + replace_with.size());
}
return str;
}
bool StringIsWhitespace(char ch) {
return (ch == ' ') || (ch == '\t') || StringIsNewline(ch);
}
bool StringIsNewline(char ch) {
return (ch == '\n') || (ch == '\r');
}
StringW StringWiden(StringView str) {
using namespace std;
wostringstream wstm;
const ctype<wchar_t>& ctfacet = use_facet< ctype<wchar_t> >(wstm.getloc());
for( u64 i = 0; i < str.size(); i++ )
wstm << static_cast<wchar_t>(ctfacet.widen(str[i]));
return wstm.str();
}
String StringNarrow(StringWView str) {
using namespace std;
ostringstream stm;
const ctype<char>& ctfacet = use_facet< ctype<char> >(stm.getloc());
for( u64 i = 0; i < str.size(); i++ )
stm << static_cast<char>(ctfacet.narrow(str[i], '\0'));
return stm.str();
}
f32 IEEEFloat(u32 f) {
static_assert(sizeof(f32) == sizeof(f), "`f32` has a weird size.");
f32 ret;
memcpy(&ret, &f, sizeof(f32));
return ret;
}
u32 IEEEUInt32(f32 f) {
static_assert(sizeof(u32) == sizeof(f), "`u32` has a weird size.");
u32 ret;
memcpy(&ret, &f, sizeof(u32));
return ret;
}
bool StringMask(cstr mask, cstr string) {
for( ; *mask != '\0'; ++mask ) {
switch( *mask ) {
case '?':
if( *string == '\0' )
return false;
string++;
break;
case '*':
{
if( mask[1] == '\0' )
return true;
for( u64 i = 0, len = strlen(string); i < len; i++ ) {
if( StringMask(mask + 1, string + i) )
return true;
}
return false;
}
default:
if( *string != *mask )
return false;
string++;
break;
}
}
return *string == '\0';
}
String StringFormat(cstr format, ...) {
char buff[4096];
va_list _ArgList;
#if SMOL_OS == SMOL_OS_WIN
__crt_va_start(_ArgList, format);
vsprintf_s(buff, format, _ArgList);
__crt_va_end(_ArgList);
#endif
#if SMOL_OS == SMOL_OS_SWITCH
__builtin_va_start(_ArgList, format);
vsprintf(buff, format, _ArgList);
__builtin_va_end(_ArgList);
#endif
return buff;
}
Vector<StringW> StringSplit(StringWView string, wchar_t delim) {
Vector<StringW> arr{ };
StringW str = string.data();
for( u32 i = 0; i < string.length(); i++ ) {
if( str[i] == delim ) {
arr.push_back(str.substr(0, i));
str = str.substr(i + 1);
}
}
// No delimeters were met
if( arr.size() == 0 )
arr.push_back(str);
return arr;
}
Vector<String> StringSplit(StringView string, char delim) {
Vector<String> arr{ };
String str = string.data();
for( u32 i = 0; i < string.length(); i++ ) {
if( str[i] == delim ) {
arr.push_back(str.substr(0, i));
str = str.substr(i + 1);
}
}
// No delimeters were met
if( arr.size() == 0 )
arr.push_back(str);
return arr;
}
| 23.532995 | 83 | 0.512295 | [
"vector"
] |
ec58b68bd5b23fecf8015006bdf21f07d40b3f76 | 3,266 | cpp | C++ | android-31/java/util/concurrent/CopyOnWriteArraySet.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/util/concurrent/CopyOnWriteArraySet.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/util/concurrent/CopyOnWriteArraySet.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JObjectArray.hpp"
#include "../../../JObject.hpp"
#include "./CopyOnWriteArrayList.hpp"
#include "./CopyOnWriteArraySet.hpp"
namespace java::util::concurrent
{
// Fields
// QJniObject forward
CopyOnWriteArraySet::CopyOnWriteArraySet(QJniObject obj) : java::util::AbstractSet(obj) {}
// Constructors
CopyOnWriteArraySet::CopyOnWriteArraySet()
: java::util::AbstractSet(
"java.util.concurrent.CopyOnWriteArraySet",
"()V"
) {}
CopyOnWriteArraySet::CopyOnWriteArraySet(JObject arg0)
: java::util::AbstractSet(
"java.util.concurrent.CopyOnWriteArraySet",
"(Ljava/util/Collection;)V",
arg0.object()
) {}
// Methods
jboolean CopyOnWriteArraySet::add(JObject arg0) const
{
return callMethod<jboolean>(
"add",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jboolean CopyOnWriteArraySet::addAll(JObject arg0) const
{
return callMethod<jboolean>(
"addAll",
"(Ljava/util/Collection;)Z",
arg0.object()
);
}
void CopyOnWriteArraySet::clear() const
{
callMethod<void>(
"clear",
"()V"
);
}
jboolean CopyOnWriteArraySet::contains(JObject arg0) const
{
return callMethod<jboolean>(
"contains",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jboolean CopyOnWriteArraySet::containsAll(JObject arg0) const
{
return callMethod<jboolean>(
"containsAll",
"(Ljava/util/Collection;)Z",
arg0.object()
);
}
jboolean CopyOnWriteArraySet::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
void CopyOnWriteArraySet::forEach(JObject arg0) const
{
callMethod<void>(
"forEach",
"(Ljava/util/function/Consumer;)V",
arg0.object()
);
}
jboolean CopyOnWriteArraySet::isEmpty() const
{
return callMethod<jboolean>(
"isEmpty",
"()Z"
);
}
JObject CopyOnWriteArraySet::iterator() const
{
return callObjectMethod(
"iterator",
"()Ljava/util/Iterator;"
);
}
jboolean CopyOnWriteArraySet::remove(JObject arg0) const
{
return callMethod<jboolean>(
"remove",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jboolean CopyOnWriteArraySet::removeAll(JObject arg0) const
{
return callMethod<jboolean>(
"removeAll",
"(Ljava/util/Collection;)Z",
arg0.object()
);
}
jboolean CopyOnWriteArraySet::removeIf(JObject arg0) const
{
return callMethod<jboolean>(
"removeIf",
"(Ljava/util/function/Predicate;)Z",
arg0.object()
);
}
jboolean CopyOnWriteArraySet::retainAll(JObject arg0) const
{
return callMethod<jboolean>(
"retainAll",
"(Ljava/util/Collection;)Z",
arg0.object()
);
}
jint CopyOnWriteArraySet::size() const
{
return callMethod<jint>(
"size",
"()I"
);
}
JObject CopyOnWriteArraySet::spliterator() const
{
return callObjectMethod(
"spliterator",
"()Ljava/util/Spliterator;"
);
}
JObjectArray CopyOnWriteArraySet::toArray() const
{
return callObjectMethod(
"toArray",
"()[Ljava/lang/Object;"
);
}
JObjectArray CopyOnWriteArraySet::toArray(JObjectArray arg0) const
{
return callObjectMethod(
"toArray",
"([Ljava/lang/Object;)[Ljava/lang/Object;",
arg0.object<jobjectArray>()
);
}
} // namespace java::util::concurrent
| 20.540881 | 91 | 0.677587 | [
"object"
] |
ec5a2a0a8489809c80e9221d725575c994db23a2 | 14,882 | cpp | C++ | tests/day05_tests.cpp | beached/aoc_2017 | 553d42e50b81384ad93aae6e0aec624ca7c8bf58 | [
"MIT"
] | 1 | 2017-12-11T16:17:18.000Z | 2017-12-11T16:17:18.000Z | tests/day05_tests.cpp | beached/aoc_2017 | 553d42e50b81384ad93aae6e0aec624ca7c8bf58 | [
"MIT"
] | null | null | null | tests/day05_tests.cpp | beached/aoc_2017 | 553d42e50b81384ad93aae6e0aec624ca7c8bf58 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2017 Darrell Wright
//
// 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.
#define BOOST_TEST_MODULE aoc_2017_day05
#include <daw/boost_test.h>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include "day05.h"
namespace daw {
namespace aoc_2017 {
namespace day05 {
BOOST_AUTO_TEST_CASE( test_001 ) {
std::vector<intmax_t> tst = {0, 3, 0, 1, -3};
BOOST_REQUIRE_EQUAL( count_steps( daw::make_span( tst ) ), 5 );
}
BOOST_AUTO_TEST_CASE( test_002 ) {
std::vector<intmax_t> tst = {
1, 1, 1, 1, 0, 0, 0, -4, -1, 0, -3, -4, 0, -9, -3, 2, -14, 0,
-17, -12, -15, -7, 0, -7, -12, -3, -17, -11, -24, -10, -16, -15, -28, -13, -28, -15,
-28, -29, -20, 0, -10, -30, -13, -24, -34, -42, -25, -36, -38, -35, -23, -11, -4, -16,
-15, -10, -31, 0, -16, -21, -50, -26, -31, -36, -53, -54, -12, -28, 1, -16, -65, -69,
-4, -47, 1, -42, -33, -55, -72, -29, -2, -62, -40, -28, 0, -42, -78, 2, -23, -86,
-75, -17, -15, -9, 0, -24, -36, -91, -64, -65, -98, -30, -21, -80, 0, -88, -105, -103,
-32, -54, -62, -105, -68, -101, -73, -26, -112, -96, -66, -115, -53, -69, -99, -84, -46, -105,
-16, -18, -104, -19, -16, -9, -45, -40, -40, -11, -105, -105, -72, -89, -3, -119, -74, -124,
-111, -128, -79, -145, -138, -147, -92, -44, -115, -51, -139, -15, -72, -116, -149, -38, -55, -63,
-62, -3, -48, -115, -33, -56, -51, -28, -8, -15, -162, -7, -24, -72, -104, -7, -23, -16,
-25, -169, -157, -53, -123, -183, -127, -98, -133, -180, -96, -56, -57, -123, -123, 0, -35, -174,
-91, -167, -121, -67, -47, -201, 0, -111, -158, -36, -62, -111, -114, -183, -139, -108, -74, -154,
-12, -18, -182, -217, -199, -68, -212, -183, -126, -56, -112, -211, -203, -223, -40, 0, -225, -101,
-24, -91, -94, -80, -190, -6, -234, -2, -222, -208, -46, -163, -136, -45, -17, -141, -18, -67,
-224, -39, -135, -91, -91, -146, -158, -70, -33, -232, -54, -45, -80, -124, -221, -130, -236, -112,
-238, -11, -34, -110, -198, -15, -252, -230, -118, -230, -193, -119, -162, -214, -206, -158, -199, -141,
-167, -9, -140, -185, -126, -106, -293, -142, -290, -78, -137, -274, -186, -88, -167, -287, -218, -300,
-5, -81, -108, -287, -276, -235, -189, -116, -16, -232, -32, -189, -78, -8, -72, -219, -12, -63,
-7, -114, -170, -125, -162, -19, -140, -152, -3, -127, -314, -158, -301, -153, -62, -7, -94, -182,
-61, -6, -285, -260, -123, -298, -131, -66, -155, -347, -181, -71, -143, -232, -146, -100, 0, -101,
-315, -53, -348, -209, -320, -212, -358, -108, -101, -188, -218, -309, -290, -245, -253, -111, -188, -104,
-296, -14, -306, -335, -87, -284, -14, -117, -143, -386, -367, -292, -251, -289, -340, -41, -85, -52,
-236, -265, -265, -341, -395, -110, -311, -391, -79, -262, -214, -395, -205, -50, -318, -198, -199, -44,
-153, -403, -261, -290, -55, -321, -407, -17, -30, -342, -321, -37, -197, -5, -305, -394, -373, -297,
-40, -114, -240, -218, -164, -334, -337, -38, -124, -362, -209, -79, -208, -277, -341, -345, -112, -137,
-306, -90, -10, -50, -447, -445, -50, -327, -374, -441, -197, -231, -31, -361, -444, -109, -294, -452,
-327, -411, -137, -326, -201, -217, -277, -245, -263, -111, -286, -265, -298, -107, -204, -395, -299, -175,
-158, -94, -34, 2, -55, -113, -278, -74, -380, -167, -429, -261, -57, -95, -215, -392, -121, -460,
-250, -393, -41, -183, -123, -367, -387, -66, -431, -399, -295, -449, -10, -461, -392, -277, -302, -460,
-197, -307, -229, -296, -415, -313, -334, -172, -303, -439, -479, -364, -156, -287, -315, -265, -153, -134,
-238, -88, 1, -306, -399, -197, -363, -156, -370, -313, -365, -510, -91, -464, -177, -550, -95, -49,
-108, -24, -289, -229, -547, 0, -538, -164, -202, -190, -92, -302, -416, -42, -148, -192, -246, -118,
-144, -264, -497, -276, -350, -318, -219, -301, -398, -12, -292, -395, -565, -102, -118, -424, -3, -473,
-94, -413, -145, -38, -97, -485, -363, -309, -250, -506, -345, -346, -447, -319, -330, -198, -255, -353,
-260, -370, -22, -91, -345, -333, -315, -593, -450, -37, -380, -543, -5, -556, -164, -135, -513, -56,
-166, -474, -14, -84, -561, -596, -454, -429, -457, -69, -59, -597, -598, -391, -260, -596, -384, -267,
-34, -158, -531, -243, -495, -165, -190, -466, -574, -344, -365, -277, -329, -64, -616, -123, -551, -537,
-412, -333, -589, -212, -376, -290, -366, -363, -477, -39, -37, -495, -317, -554, -675, -442, -427, -407,
-515, -169, -113, -395, -561, -358, -214, -20, -424, -74, -311, -110, -353, -112, -217, -181, -496, -336,
-311, -585, -407, -383, -663, -266, -591, -235, -266, -406, -347, -268, -281, -449, -569, -8, -178, -62,
-139, -89, -72, -487, -352, -164, -244, -640, -139, -639, -330, -348, -390, -260, -632, -171, -343, -700,
-21, -653, -250, -20, -587, -357, -151, -536, -287, -614, -582, -564, -136, -613, -130, -717, -54, -35,
-205, -49, -711, -538, -342, -222, -579, -300, -641, -240, -198, -76, -550, -73, -528, -465, -485, -327,
-433, -325, -441, -575, -661, -126, -588, -315, -651, -692, -189, -656, -533, -627, -459, -244, -737, -422,
-647, -324, -759, -592, -305, -281, -360, -79, -271, -52, -129, -416, -39, -497, -147, -755, -398, -382,
-217, -301, -581, -345, -310, -68, -90, -128, -303, -416, -348, -745, -204, -795, -482, -537, -315, -662,
-432, -464, -239, -19, -216, -230, -240, -612, -129, -655, -197, -369, -89, -573, -180, -229, -264, -268,
-401, -820, -412, -99, -666, -360, -814, -348, -755, -772, -296, -851, -818, -394, -161, -77, -109, -362,
-273, -688, -574, -50, -137, -550, -380, -462, -851, -611, -237, -853, -11, -383, -767, -349, -170, -389,
-747, -247, -462, -839, -87, -852, -672, -796, -839, -788, -78, -151, -507, -414, -363, -750, -521, -468,
-418, -251, -803, -802, -269, -766, -520, -301, -156, -488, -130, -100, -191, -45, -352, -774, -506, -306,
-517, -220, -62, -523, -111, -157, -516, -541, -888, -514, -223, -902, -159, -255, -699, -901, -893, -273,
-602, -850, -382, -207, -528, -566, -834, -695, -25, -166, -650, -569, -667, -771, -809, -922, -858, -53,
-703, -552, -584, -190, -193, -146, -218, -503, -252, -432, -93, -180, -277, -250, -610, -194, -415, -67,
-793, -413, -930, -785, -890, -417, -501, -109, -839, -916, -860, -467, -741, -645, -795, -769, -665, -974,
-318, -334, -963, -674, -432, -402, -702, -724, -524, -753, -146, -719, -953};
auto const ans1 = count_steps( daw::make_span( tst ) );
std::cout << "Answer #1: " << ans1 << '\n';
BOOST_REQUIRE_EQUAL( ans1, 315613 );
}
BOOST_AUTO_TEST_CASE( test_p2_001 ) {
std::vector<intmax_t> tst = {0, 3, 0, 1, -3};
BOOST_REQUIRE_EQUAL( count_steps2( daw::make_span( tst ) ), 10 );
}
BOOST_AUTO_TEST_CASE( test_p2_002 ) {
std::vector<intmax_t> tst = {
1, 1, 1, 1, 0, 0, 0, -4, -1, 0, -3, -4, 0, -9, -3, 2, -14, 0,
-17, -12, -15, -7, 0, -7, -12, -3, -17, -11, -24, -10, -16, -15, -28, -13, -28, -15,
-28, -29, -20, 0, -10, -30, -13, -24, -34, -42, -25, -36, -38, -35, -23, -11, -4, -16,
-15, -10, -31, 0, -16, -21, -50, -26, -31, -36, -53, -54, -12, -28, 1, -16, -65, -69,
-4, -47, 1, -42, -33, -55, -72, -29, -2, -62, -40, -28, 0, -42, -78, 2, -23, -86,
-75, -17, -15, -9, 0, -24, -36, -91, -64, -65, -98, -30, -21, -80, 0, -88, -105, -103,
-32, -54, -62, -105, -68, -101, -73, -26, -112, -96, -66, -115, -53, -69, -99, -84, -46, -105,
-16, -18, -104, -19, -16, -9, -45, -40, -40, -11, -105, -105, -72, -89, -3, -119, -74, -124,
-111, -128, -79, -145, -138, -147, -92, -44, -115, -51, -139, -15, -72, -116, -149, -38, -55, -63,
-62, -3, -48, -115, -33, -56, -51, -28, -8, -15, -162, -7, -24, -72, -104, -7, -23, -16,
-25, -169, -157, -53, -123, -183, -127, -98, -133, -180, -96, -56, -57, -123, -123, 0, -35, -174,
-91, -167, -121, -67, -47, -201, 0, -111, -158, -36, -62, -111, -114, -183, -139, -108, -74, -154,
-12, -18, -182, -217, -199, -68, -212, -183, -126, -56, -112, -211, -203, -223, -40, 0, -225, -101,
-24, -91, -94, -80, -190, -6, -234, -2, -222, -208, -46, -163, -136, -45, -17, -141, -18, -67,
-224, -39, -135, -91, -91, -146, -158, -70, -33, -232, -54, -45, -80, -124, -221, -130, -236, -112,
-238, -11, -34, -110, -198, -15, -252, -230, -118, -230, -193, -119, -162, -214, -206, -158, -199, -141,
-167, -9, -140, -185, -126, -106, -293, -142, -290, -78, -137, -274, -186, -88, -167, -287, -218, -300,
-5, -81, -108, -287, -276, -235, -189, -116, -16, -232, -32, -189, -78, -8, -72, -219, -12, -63,
-7, -114, -170, -125, -162, -19, -140, -152, -3, -127, -314, -158, -301, -153, -62, -7, -94, -182,
-61, -6, -285, -260, -123, -298, -131, -66, -155, -347, -181, -71, -143, -232, -146, -100, 0, -101,
-315, -53, -348, -209, -320, -212, -358, -108, -101, -188, -218, -309, -290, -245, -253, -111, -188, -104,
-296, -14, -306, -335, -87, -284, -14, -117, -143, -386, -367, -292, -251, -289, -340, -41, -85, -52,
-236, -265, -265, -341, -395, -110, -311, -391, -79, -262, -214, -395, -205, -50, -318, -198, -199, -44,
-153, -403, -261, -290, -55, -321, -407, -17, -30, -342, -321, -37, -197, -5, -305, -394, -373, -297,
-40, -114, -240, -218, -164, -334, -337, -38, -124, -362, -209, -79, -208, -277, -341, -345, -112, -137,
-306, -90, -10, -50, -447, -445, -50, -327, -374, -441, -197, -231, -31, -361, -444, -109, -294, -452,
-327, -411, -137, -326, -201, -217, -277, -245, -263, -111, -286, -265, -298, -107, -204, -395, -299, -175,
-158, -94, -34, 2, -55, -113, -278, -74, -380, -167, -429, -261, -57, -95, -215, -392, -121, -460,
-250, -393, -41, -183, -123, -367, -387, -66, -431, -399, -295, -449, -10, -461, -392, -277, -302, -460,
-197, -307, -229, -296, -415, -313, -334, -172, -303, -439, -479, -364, -156, -287, -315, -265, -153, -134,
-238, -88, 1, -306, -399, -197, -363, -156, -370, -313, -365, -510, -91, -464, -177, -550, -95, -49,
-108, -24, -289, -229, -547, 0, -538, -164, -202, -190, -92, -302, -416, -42, -148, -192, -246, -118,
-144, -264, -497, -276, -350, -318, -219, -301, -398, -12, -292, -395, -565, -102, -118, -424, -3, -473,
-94, -413, -145, -38, -97, -485, -363, -309, -250, -506, -345, -346, -447, -319, -330, -198, -255, -353,
-260, -370, -22, -91, -345, -333, -315, -593, -450, -37, -380, -543, -5, -556, -164, -135, -513, -56,
-166, -474, -14, -84, -561, -596, -454, -429, -457, -69, -59, -597, -598, -391, -260, -596, -384, -267,
-34, -158, -531, -243, -495, -165, -190, -466, -574, -344, -365, -277, -329, -64, -616, -123, -551, -537,
-412, -333, -589, -212, -376, -290, -366, -363, -477, -39, -37, -495, -317, -554, -675, -442, -427, -407,
-515, -169, -113, -395, -561, -358, -214, -20, -424, -74, -311, -110, -353, -112, -217, -181, -496, -336,
-311, -585, -407, -383, -663, -266, -591, -235, -266, -406, -347, -268, -281, -449, -569, -8, -178, -62,
-139, -89, -72, -487, -352, -164, -244, -640, -139, -639, -330, -348, -390, -260, -632, -171, -343, -700,
-21, -653, -250, -20, -587, -357, -151, -536, -287, -614, -582, -564, -136, -613, -130, -717, -54, -35,
-205, -49, -711, -538, -342, -222, -579, -300, -641, -240, -198, -76, -550, -73, -528, -465, -485, -327,
-433, -325, -441, -575, -661, -126, -588, -315, -651, -692, -189, -656, -533, -627, -459, -244, -737, -422,
-647, -324, -759, -592, -305, -281, -360, -79, -271, -52, -129, -416, -39, -497, -147, -755, -398, -382,
-217, -301, -581, -345, -310, -68, -90, -128, -303, -416, -348, -745, -204, -795, -482, -537, -315, -662,
-432, -464, -239, -19, -216, -230, -240, -612, -129, -655, -197, -369, -89, -573, -180, -229, -264, -268,
-401, -820, -412, -99, -666, -360, -814, -348, -755, -772, -296, -851, -818, -394, -161, -77, -109, -362,
-273, -688, -574, -50, -137, -550, -380, -462, -851, -611, -237, -853, -11, -383, -767, -349, -170, -389,
-747, -247, -462, -839, -87, -852, -672, -796, -839, -788, -78, -151, -507, -414, -363, -750, -521, -468,
-418, -251, -803, -802, -269, -766, -520, -301, -156, -488, -130, -100, -191, -45, -352, -774, -506, -306,
-517, -220, -62, -523, -111, -157, -516, -541, -888, -514, -223, -902, -159, -255, -699, -901, -893, -273,
-602, -850, -382, -207, -528, -566, -834, -695, -25, -166, -650, -569, -667, -771, -809, -922, -858, -53,
-703, -552, -584, -190, -193, -146, -218, -503, -252, -432, -93, -180, -277, -250, -610, -194, -415, -67,
-793, -413, -930, -785, -890, -417, -501, -109, -839, -916, -860, -467, -741, -645, -795, -769, -665, -974,
-318, -334, -963, -674, -432, -402, -702, -724, -524, -753, -146, -719, -953};
auto const ans1 = count_steps2( daw::make_span( tst ) );
BOOST_REQUIRE_EQUAL( ans1, 22570529 );
std::cout << "Answer #2: " << ans1 << '\n';
}
} // namespace day05
} // namespace aoc_2017
} // namespace daw
| 84.556818 | 113 | 0.458272 | [
"vector"
] |
ec61afd9e1f670e534e8e6d7f64dbca3ce351997 | 3,770 | cpp | C++ | test_conformance/spirv_new/test_op_branch.cpp | jainvikas8/OpenCL-CTS | b7e7a3eb65d80d6847bd522f66f876fd5f6fe938 | [
"Apache-2.0"
] | 130 | 2017-05-16T14:15:25.000Z | 2022-03-26T22:31:05.000Z | test_conformance/spirv_new/test_op_branch.cpp | jainvikas8/OpenCL-CTS | b7e7a3eb65d80d6847bd522f66f876fd5f6fe938 | [
"Apache-2.0"
] | 919 | 2017-05-19T08:01:20.000Z | 2022-03-29T23:08:35.000Z | test_conformance/spirv_new/test_op_branch.cpp | jainvikas8/OpenCL-CTS | b7e7a3eb65d80d6847bd522f66f876fd5f6fe938 | [
"Apache-2.0"
] | 125 | 2017-05-17T01:14:15.000Z | 2022-03-25T22:34:42.000Z | /******************************************************************
Copyright (c) 2016 The Khronos Group Inc. All Rights Reserved.
This code is protected by copyright laws and contains material proprietary to the Khronos Group, Inc.
This is UNPUBLISHED PROPRIETARY SOURCE CODE that may not be disclosed in whole or in part to
third parties, and may not be reproduced, republished, distributed, transmitted, displayed,
broadcast or otherwise exploited in any manner without the express prior written permission
of Khronos Group. The receipt or possession of this code does not convey any rights to reproduce,
disclose, or distribute its contents, or to manufacture, use, or sell anything that it may describe,
in whole or in part other than under the terms of the Khronos Adopters Agreement
or Khronos Conformance Test Source License Agreement as executed between Khronos and the recipient.
******************************************************************/
#include "testBase.h"
#include "types.hpp"
template<typename T>
int test_branch_simple(cl_device_id deviceID, cl_context context,
cl_command_queue queue, const char *name,
std::vector<T> &results,
bool (*notEqual)(const T&, const T&) = isNotEqual<T>)
{
clProgramWrapper prog;
cl_int err = get_program_with_il(prog, deviceID, context, name);
SPIRV_CHECK_ERROR(err, "Failed to build program");
clKernelWrapper kernel = clCreateKernel(prog, name, &err);
SPIRV_CHECK_ERROR(err, "Failed to create kernel");
int num = (int)results.size();
size_t bytes = num * sizeof(T);
clMemWrapper in_mem = clCreateBuffer(context, CL_MEM_READ_WRITE, bytes, NULL, &err);
SPIRV_CHECK_ERROR(err, "Failed to create buffer");
err = clEnqueueWriteBuffer(queue, in_mem, CL_TRUE, 0, bytes, &results[0], 0, NULL, NULL);
SPIRV_CHECK_ERROR(err, "Failed to copy to lhs buffer");
clMemWrapper out_mem = clCreateBuffer(context, CL_MEM_READ_WRITE, bytes, NULL, &err);
SPIRV_CHECK_ERROR(err, "Failed to create buffer");
err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &in_mem);
SPIRV_CHECK_ERROR(err, "Failed to set kernel argument");
err = clSetKernelArg(kernel, 1, sizeof(cl_mem), &out_mem);
SPIRV_CHECK_ERROR(err, "Failed to set kernel argument");
size_t global = num;
err = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, NULL, 0, NULL, NULL);
SPIRV_CHECK_ERROR(err, "Failed to enqueue kernel");
std::vector<T> host(num);
err = clEnqueueReadBuffer(queue, out_mem, CL_TRUE, 0, bytes, &host[0], 0, NULL, NULL);
SPIRV_CHECK_ERROR(err, "Failed to copy from cl_buffer");
for (int i = 0; i < num; i++) {
if (notEqual(host[i], results[i])) {
log_error("Values do not match at location %d\n", i);
return -1;
}
}
return 0;
}
#define TEST_BRANCH_SIMPLE(NAME) \
TEST_SPIRV_FUNC(op_##NAME##_simple) \
{ \
RandomSeed seed(gRandomSeed); \
int num = 1 << 10; \
std::vector<cl_int> results(num); \
for (int i = 0; i < num; i++) { \
results[i] = genrand<cl_int>(seed); \
} \
return test_branch_simple(deviceID, context, queue, \
#NAME "_simple", \
results); \
} \
TEST_BRANCH_SIMPLE(label)
TEST_BRANCH_SIMPLE(branch)
TEST_BRANCH_SIMPLE(unreachable)
| 45.421687 | 101 | 0.589125 | [
"vector"
] |
ec644eb0e54bf3216b4a7d84ab1cd5a689e25464 | 48,148 | cpp | C++ | sdl1/wolf4sdl/wl_draw.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/wolf4sdl/wl_draw.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/wolf4sdl/wl_draw.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | // WL_DRAW.C
#include "wl_def.h"
#pragma hdrstop
#include "wl_cloudsky.h"
#include "wl_atmos.h"
#include "wl_shade.h"
/*
=============================================================================
LOCAL CONSTANTS
=============================================================================
*/
// the door is the last picture before the sprites
#define DOORWALL (PMSpriteStart-8)
#define ACTORSIZE 0x4000
/*
=============================================================================
GLOBAL VARIABLES
=============================================================================
*/
static byte *vbuf = NULL;
unsigned vbufPitch = 0;
int32_t lasttimecount;
int32_t frameon;
boolean fpscounter;
int fps_frames=0, fps_time=0, fps=0;
int *wallheight;
int min_wallheight;
//
// math tables
//
short *pixelangle;
int32_t finetangent[FINEANGLES/4];
fixed sintable[ANGLES+ANGLES/4];
fixed *costable = sintable+(ANGLES/4);
//
// refresh variables
//
fixed viewx,viewy; // the focal point
short viewangle;
fixed viewsin,viewcos;
void TransformActor (objtype *ob);
void BuildTables (void);
void ClearScreen (void);
int CalcRotate (objtype *ob);
void DrawScaleds (void);
void CalcTics (void);
void ThreeDRefresh (void);
//
// wall optimization variables
//
int lastside; // true for vertical
int32_t lastintercept;
int lasttilehit;
int lasttexture;
//
// ray tracing variables
//
short focaltx,focalty,viewtx,viewty;
longword xpartialup,xpartialdown,ypartialup,ypartialdown;
short midangle,angle;
word tilehit;
int pixx;
short xtile,ytile;
short xtilestep,ytilestep;
int32_t xintercept,yintercept;
word xstep,ystep;
word xspot,yspot;
int texdelta;
word horizwall[MAXWALLTILES],vertwall[MAXWALLTILES];
/*
============================================================================
3 - D DEFINITIONS
============================================================================
*/
/*
========================
=
= TransformActor
=
= Takes paramaters:
= gx,gy : globalx/globaly of point
=
= globals:
= viewx,viewy : point of view
= viewcos,viewsin : sin/cos of viewangle
= scale : conversion from global value to screen value
=
= sets:
= screenx,transx,transy,screenheight: projected edge location and size
=
========================
*/
//
// transform actor
//
void TransformActor (objtype *ob)
{
fixed gx,gy,gxt,gyt,nx,ny;
//
// translate point to view centered coordinates
//
gx = ob->x-viewx;
gy = ob->y-viewy;
//
// calculate newx
//
gxt = FixedMul(gx,viewcos);
gyt = FixedMul(gy,viewsin);
nx = gxt-gyt-ACTORSIZE; // fudge the shape forward a bit, because
// the midpoint could put parts of the shape
// into an adjacent wall
//
// calculate newy
//
gxt = FixedMul(gx,viewsin);
gyt = FixedMul(gy,viewcos);
ny = gyt+gxt;
//
// calculate perspective ratio
//
ob->transx = nx;
ob->transy = ny;
if (nx<MINDIST) // too close, don't overflow the divide
{
ob->viewheight = 0;
return;
}
ob->viewx = (word)(centerx + ny*scale/nx);
//
// calculate height (heightnumerator/(nx>>8))
//
ob->viewheight = (word)(heightnumerator/(nx>>8));
}
//==========================================================================
/*
========================
=
= TransformTile
=
= Takes paramaters:
= tx,ty : tile the object is centered in
=
= globals:
= viewx,viewy : point of view
= viewcos,viewsin : sin/cos of viewangle
= scale : conversion from global value to screen value
=
= sets:
= screenx,transx,transy,screenheight: projected edge location and size
=
= Returns true if the tile is withing getting distance
=
========================
*/
boolean TransformTile (int tx, int ty, short *dispx, short *dispheight)
{
fixed gx,gy,gxt,gyt,nx,ny;
//
// translate point to view centered coordinates
//
gx = ((int32_t)tx<<TILESHIFT)+0x8000-viewx;
gy = ((int32_t)ty<<TILESHIFT)+0x8000-viewy;
//
// calculate newx
//
gxt = FixedMul(gx,viewcos);
gyt = FixedMul(gy,viewsin);
nx = gxt-gyt-0x2000; // 0x2000 is size of object
//
// calculate newy
//
gxt = FixedMul(gx,viewsin);
gyt = FixedMul(gy,viewcos);
ny = gyt+gxt;
//
// calculate height / perspective ratio
//
if (nx<MINDIST) // too close, don't overflow the divide
*dispheight = 0;
else
{
*dispx = (short)(centerx + ny*scale/nx);
*dispheight = (short)(heightnumerator/(nx>>8));
}
//
// see if it should be grabbed
//
if (nx<TILEGLOBAL && ny>-TILEGLOBAL/2 && ny<TILEGLOBAL/2)
return true;
else
return false;
}
//==========================================================================
/*
====================
=
= CalcHeight
=
= Calculates the height of xintercept,yintercept from viewx,viewy
=
====================
*/
int CalcHeight()
{
fixed z = FixedMul(xintercept - viewx, viewcos)
- FixedMul(yintercept - viewy, viewsin);
if(z < MINDIST) z = MINDIST;
int height = heightnumerator / (z >> 8);
if(height < min_wallheight) min_wallheight = height;
return height;
}
//==========================================================================
/*
===================
=
= ScalePost
=
===================
*/
byte *postsource;
int postx;
int postwidth;
void ScalePost()
{
int ywcount, yoffs, yw, yd, yendoffs;
byte col;
#ifdef USE_SHADING
byte *curshades = shadetable[GetShade(wallheight[postx])];
#endif
ywcount = yd = wallheight[postx] >> 3;
if(yd <= 0) yd = 100;
yoffs = (viewheight / 2 - ywcount) * vbufPitch;
if(yoffs < 0) yoffs = 0;
yoffs += postx;
yendoffs = viewheight / 2 + ywcount - 1;
yw=TEXTURESIZE-1;
while(yendoffs >= viewheight)
{
ywcount -= TEXTURESIZE/2;
while(ywcount <= 0)
{
ywcount += yd;
yw--;
}
yendoffs--;
}
if(yw < 0) return;
#ifdef USE_SHADING
col = curshades[postsource[yw]];
#else
col = postsource[yw];
#endif
yendoffs = yendoffs * vbufPitch + postx;
while(yoffs <= yendoffs)
{
vbuf[yendoffs] = col;
ywcount -= TEXTURESIZE/2;
if(ywcount <= 0)
{
do
{
ywcount += yd;
yw--;
}
while(ywcount <= 0);
if(yw < 0) break;
#ifdef USE_SHADING
col = curshades[postsource[yw]];
#else
col = postsource[yw];
#endif
}
yendoffs -= vbufPitch;
}
}
void GlobalScalePost(byte *vidbuf, unsigned pitch)
{
vbuf = vidbuf;
vbufPitch = pitch;
ScalePost();
}
/*
====================
=
= HitVertWall
=
= tilehit bit 7 is 0, because it's not a door tile
= if bit 6 is 1 and the adjacent tile is a door tile, use door side pic
=
====================
*/
void HitVertWall (void)
{
int wallpic;
int texture;
texture = ((yintercept+texdelta)>>TEXTUREFROMFIXEDSHIFT)&TEXTUREMASK;
if (xtilestep == -1)
{
texture = TEXTUREMASK-texture;
xintercept += TILEGLOBAL;
}
if(lastside==1 && lastintercept==xtile && lasttilehit==tilehit && !(lasttilehit & 0x40))
{
if((pixx&3) && texture == lasttexture)
{
ScalePost();
postx = pixx;
wallheight[pixx] = wallheight[pixx-1];
return;
}
ScalePost();
wallheight[pixx] = CalcHeight();
postsource+=texture-lasttexture;
postwidth=1;
postx=pixx;
lasttexture=texture;
return;
}
if(lastside!=-1) ScalePost();
lastside=1;
lastintercept=xtile;
lasttilehit=tilehit;
lasttexture=texture;
wallheight[pixx] = CalcHeight();
postx = pixx;
postwidth = 1;
if (tilehit & 0x40)
{ // check for adjacent doors
ytile = (short)(yintercept>>TILESHIFT);
if ( tilemap[xtile-xtilestep][ytile]&0x80 )
wallpic = DOORWALL+3;
else
wallpic = vertwall[tilehit & ~0x40];
}
else
wallpic = vertwall[tilehit];
postsource = PM_GetTexture(wallpic) + texture;
}
/*
====================
=
= HitHorizWall
=
= tilehit bit 7 is 0, because it's not a door tile
= if bit 6 is 1 and the adjacent tile is a door tile, use door side pic
=
====================
*/
void HitHorizWall (void)
{
int wallpic;
int texture;
texture = ((xintercept+texdelta)>>TEXTUREFROMFIXEDSHIFT)&TEXTUREMASK;
if (ytilestep == -1)
yintercept += TILEGLOBAL;
else
texture = TEXTUREMASK-texture;
if(lastside==0 && lastintercept==ytile && lasttilehit==tilehit && !(lasttilehit & 0x40))
{
if((pixx&3) && texture == lasttexture)
{
ScalePost();
postx=pixx;
wallheight[pixx] = wallheight[pixx-1];
return;
}
ScalePost();
wallheight[pixx] = CalcHeight();
postsource+=texture-lasttexture;
postwidth=1;
postx=pixx;
lasttexture=texture;
return;
}
if(lastside!=-1) ScalePost();
lastside=0;
lastintercept=ytile;
lasttilehit=tilehit;
lasttexture=texture;
wallheight[pixx] = CalcHeight();
postx = pixx;
postwidth = 1;
if (tilehit & 0x40)
{ // check for adjacent doors
xtile = (short)(xintercept>>TILESHIFT);
if ( tilemap[xtile][ytile-ytilestep]&0x80)
wallpic = DOORWALL+2;
else
wallpic = horizwall[tilehit & ~0x40];
}
else
wallpic = horizwall[tilehit];
postsource = PM_GetTexture(wallpic) + texture;
}
//==========================================================================
/*
====================
=
= HitHorizDoor
=
====================
*/
void HitHorizDoor (void)
{
int doorpage;
int doornum;
int texture;
doornum = tilehit&0x7f;
texture = ((xintercept-doorposition[doornum])>>TEXTUREFROMFIXEDSHIFT)&TEXTUREMASK;
if(lasttilehit==tilehit)
{
if((pixx&3) && texture == lasttexture)
{
ScalePost();
postx=pixx;
wallheight[pixx] = wallheight[pixx-1];
return;
}
ScalePost();
wallheight[pixx] = CalcHeight();
postsource+=texture-lasttexture;
postwidth=1;
postx=pixx;
lasttexture=texture;
return;
}
if(lastside!=-1) ScalePost();
lastside=2;
lasttilehit=tilehit;
lasttexture=texture;
wallheight[pixx] = CalcHeight();
postx = pixx;
postwidth = 1;
switch(doorobjlist[doornum].lock)
{
case dr_normal:
doorpage = DOORWALL;
break;
case dr_lock1:
case dr_lock2:
case dr_lock3:
case dr_lock4:
doorpage = DOORWALL+6;
break;
case dr_elevator:
doorpage = DOORWALL+4;
break;
}
postsource = PM_GetTexture(doorpage) + texture;
}
//==========================================================================
/*
====================
=
= HitVertDoor
=
====================
*/
void HitVertDoor (void)
{
int doorpage;
int doornum;
int texture;
doornum = tilehit&0x7f;
texture = ((yintercept-doorposition[doornum])>>TEXTUREFROMFIXEDSHIFT)&TEXTUREMASK;
if(lasttilehit==tilehit)
{
if((pixx&3) && texture == lasttexture)
{
ScalePost();
postx=pixx;
wallheight[pixx] = wallheight[pixx-1];
return;
}
ScalePost();
wallheight[pixx] = CalcHeight();
postsource+=texture-lasttexture;
postwidth=1;
postx=pixx;
lasttexture=texture;
return;
}
if(lastside!=-1) ScalePost();
lastside=2;
lasttilehit=tilehit;
lasttexture=texture;
wallheight[pixx] = CalcHeight();
postx = pixx;
postwidth = 1;
switch(doorobjlist[doornum].lock)
{
case dr_normal:
doorpage = DOORWALL+1;
break;
case dr_lock1:
case dr_lock2:
case dr_lock3:
case dr_lock4:
doorpage = DOORWALL+7;
break;
case dr_elevator:
doorpage = DOORWALL+5;
break;
}
postsource = PM_GetTexture(doorpage) + texture;
}
//==========================================================================
#define HitHorizBorder HitHorizWall
#define HitVertBorder HitVertWall
//==========================================================================
byte vgaCeiling[]=
{
#ifndef SPEAR
0x1d,0x1d,0x1d,0x1d,0x1d,0x1d,0x1d,0x1d,0x1d,0xbf,
0x4e,0x4e,0x4e,0x1d,0x8d,0x4e,0x1d,0x2d,0x1d,0x8d,
0x1d,0x1d,0x1d,0x1d,0x1d,0x2d,0xdd,0x1d,0x1d,0x98,
0x1d,0x9d,0x2d,0xdd,0xdd,0x9d,0x2d,0x4d,0x1d,0xdd,
0x7d,0x1d,0x2d,0x2d,0xdd,0xd7,0x1d,0x1d,0x1d,0x2d,
0x1d,0x1d,0x1d,0x1d,0xdd,0xdd,0x7d,0xdd,0xdd,0xdd
#else
0x6f,0x4f,0x1d,0xde,0xdf,0x2e,0x7f,0x9e,0xae,0x7f,
0x1d,0xde,0xdf,0xde,0xdf,0xde,0xe1,0xdc,0x2e,0x1d,0xdc
#endif
};
/*
=====================
=
= VGAClearScreen
=
=====================
*/
void VGAClearScreen (void)
{
byte ceiling=vgaCeiling[gamestate.episode*10+mapon];
int y;
byte *ptr = vbuf;
#ifdef USE_SHADING
for(y = 0; y < viewheight / 2; y++, ptr += vbufPitch)
memset(ptr, shadetable[GetShade((viewheight / 2 - y) << 3)][ceiling], viewwidth);
for(; y < viewheight; y++, ptr += vbufPitch)
memset(ptr, shadetable[GetShade((y - viewheight / 2) << 3)][0x19], viewwidth);
#else
for(y = 0; y < viewheight / 2; y++, ptr += vbufPitch)
memset(ptr, ceiling, viewwidth);
for(; y < viewheight; y++, ptr += vbufPitch)
memset(ptr, 0x19, viewwidth);
#endif
}
//==========================================================================
/*
=====================
=
= CalcRotate
=
=====================
*/
int CalcRotate (objtype *ob)
{
int angle, viewangle;
// this isn't exactly correct, as it should vary by a trig value,
// but it is close enough with only eight rotations
viewangle = player->angle + (centerx - ob->viewx)/8;
if (ob->obclass == rocketobj || ob->obclass == hrocketobj)
angle = (viewangle-180) - ob->angle;
else
angle = (viewangle-180) - dirangle[ob->dir];
angle+=ANGLES/16;
while (angle>=ANGLES)
angle-=ANGLES;
while (angle<0)
angle+=ANGLES;
if (ob->state->rotate == 2) // 2 rotation pain frame
return 0; // pain with shooting frame bugfix
return angle/(ANGLES/8);
}
void ScaleShape (int xcenter, int shapenum, unsigned height, uint32_t flags)
{
t_compshape *shape;
unsigned scale,pixheight;
unsigned starty,endy;
word *cmdptr;
byte *cline;
byte *line;
byte *vmem;
int actx,i,upperedge;
short newstart;
int scrstarty,screndy,lpix,rpix,pixcnt,ycnt;
unsigned j;
byte col;
#ifdef USE_SHADING
byte *curshades;
if(flags & FL_FULLBRIGHT)
curshades = shadetable[0];
else
curshades = shadetable[GetShade(height)];
#endif
shape = (t_compshape *) PM_GetSprite(shapenum);
scale=height>>3; // low three bits are fractional
if(!scale) return; // too close or far away
pixheight=scale*SPRITESCALEFACTOR;
actx=xcenter-scale;
upperedge=viewheight/2-scale;
cmdptr=(word *) shape->dataofs;
for(i=shape->leftpix,pixcnt=i*pixheight,rpix=(pixcnt>>6)+actx;i<=shape->rightpix;i++,cmdptr++)
{
lpix=rpix;
if(lpix>=viewwidth) break;
pixcnt+=pixheight;
rpix=(pixcnt>>6)+actx;
if(lpix!=rpix && rpix>0)
{
if(lpix<0) lpix=0;
if(rpix>viewwidth) rpix=viewwidth,i=shape->rightpix+1;
cline=(byte *)shape + *cmdptr;
while(lpix<rpix)
{
if(wallheight[lpix]<=(int)height)
{
line=cline;
while((endy = READWORD(line)) != 0)
{
endy >>= 1;
newstart = READWORD(line);
starty = READWORD(line) >> 1;
j=starty;
ycnt=j*pixheight;
screndy=(ycnt>>6)+upperedge;
if(screndy<0) vmem=vbuf+lpix;
else vmem=vbuf+screndy*vbufPitch+lpix;
for(;j<endy;j++)
{
scrstarty=screndy;
ycnt+=pixheight;
screndy=(ycnt>>6)+upperedge;
if(scrstarty!=screndy && screndy>0)
{
#ifdef USE_SHADING
col=curshades[((byte *)shape)[newstart+j]];
#else
col=((byte *)shape)[newstart+j];
#endif
if(scrstarty<0) scrstarty=0;
if(screndy>viewheight) screndy=viewheight,j=endy;
while(scrstarty<screndy)
{
*vmem=col;
vmem+=vbufPitch;
scrstarty++;
}
}
}
}
}
lpix++;
}
}
}
}
void SimpleScaleShape (int xcenter, int shapenum, unsigned height)
{
t_compshape *shape;
unsigned scale,pixheight;
unsigned starty,endy;
word *cmdptr;
byte *cline;
byte *line;
int actx,i,upperedge;
short newstart;
int scrstarty,screndy,lpix,rpix,pixcnt,ycnt;
unsigned j;
byte col;
byte *vmem;
shape = (t_compshape *) PM_GetSprite(shapenum);
scale=height>>1;
pixheight=scale*SPRITESCALEFACTOR;
actx=xcenter-scale;
upperedge=viewheight/2-scale;
cmdptr=shape->dataofs;
for(i=shape->leftpix,pixcnt=i*pixheight,rpix=(pixcnt>>6)+actx;i<=shape->rightpix;i++,cmdptr++)
{
lpix=rpix;
if(lpix>=viewwidth) break;
pixcnt+=pixheight;
rpix=(pixcnt>>6)+actx;
if(lpix!=rpix && rpix>0)
{
if(lpix<0) lpix=0;
if(rpix>viewwidth) rpix=viewwidth,i=shape->rightpix+1;
cline = (byte *)shape + *cmdptr;
while(lpix<rpix)
{
line=cline;
while((endy = READWORD(line)) != 0)
{
endy >>= 1;
newstart = READWORD(line);
starty = READWORD(line) >> 1;
j=starty;
ycnt=j*pixheight;
screndy=(ycnt>>6)+upperedge;
if(screndy<0) vmem=vbuf+lpix;
else vmem=vbuf+screndy*vbufPitch+lpix;
for(;j<endy;j++)
{
scrstarty=screndy;
ycnt+=pixheight;
screndy=(ycnt>>6)+upperedge;
if(scrstarty!=screndy && screndy>0)
{
col=((byte *)shape)[newstart+j];
if(scrstarty<0) scrstarty=0;
if(screndy>viewheight) screndy=viewheight,j=endy;
while(scrstarty<screndy)
{
*vmem=col;
vmem+=vbufPitch;
scrstarty++;
}
}
}
}
lpix++;
}
}
}
}
/*
=====================
=
= DrawScaleds
=
= Draws all objects that are visable
=
=====================
*/
#define MAXVISABLE 250
typedef struct
{
short viewx,
viewheight,
shapenum;
short flags; // this must be changed to uint32_t, when you
// you need more than 16-flags for drawing
#ifdef USE_DIR3DSPR
statobj_t *transsprite;
#endif
} visobj_t;
visobj_t vislist[MAXVISABLE];
visobj_t *visptr,*visstep,*farthest;
void DrawScaleds (void)
{
int i,least,numvisable,height;
byte *tilespot,*visspot;
unsigned spotloc;
statobj_t *statptr;
objtype *obj;
visptr = &vislist[0];
//
// place static objects
//
for (statptr = &statobjlist[0] ; statptr !=laststatobj ; statptr++)
{
if ((visptr->shapenum = statptr->shapenum) == -1)
continue; // object has been deleted
if (!*statptr->visspot)
continue; // not visable
if (TransformTile (statptr->tilex,statptr->tiley,
&visptr->viewx,&visptr->viewheight) && statptr->flags & FL_BONUS)
{
GetBonus (statptr);
if(statptr->shapenum == -1)
continue; // object has been taken
}
if (!visptr->viewheight)
continue; // to close to the object
#ifdef USE_DIR3DSPR
if(statptr->flags & FL_DIR_MASK)
visptr->transsprite=statptr;
else
visptr->transsprite=NULL;
#endif
if (visptr < &vislist[MAXVISABLE-1]) // don't let it overflow
{
visptr->flags = (short) statptr->flags;
visptr++;
}
}
//
// place active objects
//
for (obj = player->next;obj;obj=obj->next)
{
if ((visptr->shapenum = obj->state->shapenum)==0)
continue; // no shape
spotloc = (obj->tilex<<mapshift)+obj->tiley; // optimize: keep in struct?
visspot = &spotvis[0][0]+spotloc;
tilespot = &tilemap[0][0]+spotloc;
//
// could be in any of the nine surrounding tiles
//
if (*visspot
|| ( *(visspot-1) && !*(tilespot-1) )
|| ( *(visspot+1) && !*(tilespot+1) )
|| ( *(visspot-65) && !*(tilespot-65) )
|| ( *(visspot-64) && !*(tilespot-64) )
|| ( *(visspot-63) && !*(tilespot-63) )
|| ( *(visspot+65) && !*(tilespot+65) )
|| ( *(visspot+64) && !*(tilespot+64) )
|| ( *(visspot+63) && !*(tilespot+63) ) )
{
obj->active = ac_yes;
TransformActor (obj);
if (!obj->viewheight)
continue; // too close or far away
visptr->viewx = obj->viewx;
visptr->viewheight = obj->viewheight;
if (visptr->shapenum == -1)
visptr->shapenum = obj->temp1; // special shape
if (obj->state->rotate)
visptr->shapenum += CalcRotate (obj);
if (visptr < &vislist[MAXVISABLE-1]) // don't let it overflow
{
visptr->flags = (short) obj->flags;
#ifdef USE_DIR3DSPR
visptr->transsprite = NULL;
#endif
visptr++;
}
obj->flags |= FL_VISABLE;
}
else
obj->flags &= ~FL_VISABLE;
}
//
// draw from back to front
//
numvisable = (int) (visptr-&vislist[0]);
if (!numvisable)
return; // no visable objects
for (i = 0; i<numvisable; i++)
{
least = 32000;
for (visstep=&vislist[0] ; visstep<visptr ; visstep++)
{
height = visstep->viewheight;
if (height < least)
{
least = height;
farthest = visstep;
}
}
//
// draw farthest
//
#ifdef USE_DIR3DSPR
if(farthest->transsprite)
Scale3DShape(vbuf, vbufPitch, farthest->transsprite);
else
#endif
ScaleShape(farthest->viewx, farthest->shapenum, farthest->viewheight, farthest->flags);
farthest->viewheight = 32000;
}
}
//==========================================================================
/*
==============
=
= DrawPlayerWeapon
=
= Draw the player's hands
=
==============
*/
int weaponscale[NUMWEAPONS] = {SPR_KNIFEREADY, SPR_PISTOLREADY,
SPR_MACHINEGUNREADY, SPR_CHAINREADY};
void DrawPlayerWeapon (void)
{
int shapenum;
#ifndef SPEAR
if (gamestate.victoryflag)
{
#ifndef APOGEE_1_0
if (player->state == &s_deathcam && (GetTimeCount()&32) )
SimpleScaleShape(viewwidth/2,SPR_DEATHCAM,viewheight+1);
#endif
return;
}
#endif
if (gamestate.weapon != -1)
{
shapenum = weaponscale[gamestate.weapon]+gamestate.weaponframe;
SimpleScaleShape(viewwidth/2,shapenum,viewheight+1);
}
if (demorecord || demoplayback)
SimpleScaleShape(viewwidth/2,SPR_DEMO,viewheight+1);
}
//==========================================================================
/*
=====================
=
= CalcTics
=
=====================
*/
void CalcTics (void)
{
//
// calculate tics since last refresh for adaptive timing
//
if (lasttimecount > (int32_t) GetTimeCount())
lasttimecount = GetTimeCount(); // if the game was paused a LONG time
uint32_t curtime = SDL_GetTicks();
tics = (curtime * 7) / 100 - lasttimecount;
if(!tics)
{
// wait until end of current tic
SDL_Delay(((lasttimecount + 1) * 100) / 7 - curtime);
tics = 1;
}
lasttimecount += tics;
if (tics>MAXTICS)
tics = MAXTICS;
}
//==========================================================================
void AsmRefresh()
{
int32_t xstep,ystep;
longword xpartial,ypartial;
boolean playerInPushwallBackTile = tilemap[focaltx][focalty] == 64;
for(pixx=0;pixx<viewwidth;pixx++)
{
short angl=midangle+pixelangle[pixx];
if(angl<0) angl+=FINEANGLES;
if(angl>=3600) angl-=FINEANGLES;
if(angl<900)
{
xtilestep=1;
ytilestep=-1;
xstep=finetangent[900-1-angl];
ystep=-finetangent[angl];
xpartial=xpartialup;
ypartial=ypartialdown;
}
else if(angl<1800)
{
xtilestep=-1;
ytilestep=-1;
xstep=-finetangent[angl-900];
ystep=-finetangent[1800-1-angl];
xpartial=xpartialdown;
ypartial=ypartialdown;
}
else if(angl<2700)
{
xtilestep=-1;
ytilestep=1;
xstep=-finetangent[2700-1-angl];
ystep=finetangent[angl-1800];
xpartial=xpartialdown;
ypartial=ypartialup;
}
else if(angl<3600)
{
xtilestep=1;
ytilestep=1;
xstep=finetangent[angl-2700];
ystep=finetangent[3600-1-angl];
xpartial=xpartialup;
ypartial=ypartialup;
}
yintercept=FixedMul(ystep,xpartial)+viewy;
xtile=focaltx+xtilestep;
xspot=(word)((xtile<<mapshift)+((uint32_t)yintercept>>16));
xintercept=FixedMul(xstep,ypartial)+viewx;
ytile=focalty+ytilestep;
yspot=(word)((((uint32_t)xintercept>>16)<<mapshift)+ytile);
texdelta=0;
// Special treatment when player is in back tile of pushwall
if(playerInPushwallBackTile)
{
if( pwalldir == di_east && xtilestep == 1
|| pwalldir == di_west && xtilestep == -1)
{
int32_t yintbuf = yintercept - ((ystep * (64 - pwallpos)) >> 6);
if((yintbuf >> 16) == focalty) // ray hits pushwall back?
{
if(pwalldir == di_east)
xintercept = (focaltx << TILESHIFT) + (pwallpos << 10);
else
xintercept = (focaltx << TILESHIFT) - TILEGLOBAL + ((64 - pwallpos) << 10);
yintercept = yintbuf;
ytile = (short) (yintercept >> TILESHIFT);
tilehit = pwalltile;
HitVertWall();
continue;
}
}
else if(pwalldir == di_south && ytilestep == 1
|| pwalldir == di_north && ytilestep == -1)
{
int32_t xintbuf = xintercept - ((xstep * (64 - pwallpos)) >> 6);
if((xintbuf >> 16) == focaltx) // ray hits pushwall back?
{
xintercept = xintbuf;
if(pwalldir == di_south)
yintercept = (focalty << TILESHIFT) + (pwallpos << 10);
else
yintercept = (focalty << TILESHIFT) - TILEGLOBAL + ((64 - pwallpos) << 10);
xtile = (short) (xintercept >> TILESHIFT);
tilehit = pwalltile;
HitHorizWall();
continue;
}
}
}
do
{
if(ytilestep==-1 && (yintercept>>16)<=ytile) goto horizentry;
if(ytilestep==1 && (yintercept>>16)>=ytile) goto horizentry;
vertentry:
if((uint32_t)yintercept>mapheight*65536-1 || (word)xtile>=mapwidth)
{
if(xtile<0) xintercept=0, xtile=0;
else if(xtile>=mapwidth) xintercept=mapwidth<<TILESHIFT, xtile=mapwidth-1;
else xtile=(short) (xintercept >> TILESHIFT);
if(yintercept<0) yintercept=0, ytile=0;
else if(yintercept>=(mapheight<<TILESHIFT)) yintercept=mapheight<<TILESHIFT, ytile=mapheight-1;
yspot=0xffff;
tilehit=0;
HitHorizBorder();
break;
}
if(xspot>=maparea) break;
tilehit=((byte *)tilemap)[xspot];
if(tilehit)
{
if(tilehit&0x80)
{
int32_t yintbuf=yintercept+(ystep>>1);
if((yintbuf>>16)!=(yintercept>>16))
goto passvert;
if((word)yintbuf<doorposition[tilehit&0x7f])
goto passvert;
yintercept=yintbuf;
xintercept=(xtile<<TILESHIFT)|0x8000;
ytile = (short) (yintercept >> TILESHIFT);
HitVertDoor();
}
else
{
if(tilehit==64)
{
if(pwalldir==di_west || pwalldir==di_east)
{
int32_t yintbuf;
int pwallposnorm;
int pwallposinv;
if(pwalldir==di_west)
{
pwallposnorm = 64-pwallpos;
pwallposinv = pwallpos;
}
else
{
pwallposnorm = pwallpos;
pwallposinv = 64-pwallpos;
}
if(pwalldir == di_east && xtile==pwallx && ((uint32_t)yintercept>>16)==pwally
|| pwalldir == di_west && !(xtile==pwallx && ((uint32_t)yintercept>>16)==pwally))
{
yintbuf=yintercept+((ystep*pwallposnorm)>>6);
if((yintbuf>>16)!=(yintercept>>16))
goto passvert;
xintercept=(xtile<<TILESHIFT)+TILEGLOBAL-(pwallposinv<<10);
yintercept=yintbuf;
ytile = (short) (yintercept >> TILESHIFT);
tilehit=pwalltile;
HitVertWall();
}
else
{
yintbuf=yintercept+((ystep*pwallposinv)>>6);
if((yintbuf>>16)!=(yintercept>>16))
goto passvert;
xintercept=(xtile<<TILESHIFT)-(pwallposinv<<10);
yintercept=yintbuf;
ytile = (short) (yintercept >> TILESHIFT);
tilehit=pwalltile;
HitVertWall();
}
}
else
{
int pwallposi = pwallpos;
if(pwalldir==di_north) pwallposi = 64-pwallpos;
if(pwalldir==di_south && (word)yintercept<(pwallposi<<10)
|| pwalldir==di_north && (word)yintercept>(pwallposi<<10))
{
if(((uint32_t)yintercept>>16)==pwally && xtile==pwallx)
{
if(pwalldir==di_south && (int32_t)((word)yintercept)+ystep<(pwallposi<<10)
|| pwalldir==di_north && (int32_t)((word)yintercept)+ystep>(pwallposi<<10))
goto passvert;
if(pwalldir==di_south)
yintercept=(yintercept&0xffff0000)+(pwallposi<<10);
else
yintercept=(yintercept&0xffff0000)-TILEGLOBAL+(pwallposi<<10);
xintercept=xintercept-((xstep*(64-pwallpos))>>6);
xtile = (short) (xintercept >> TILESHIFT);
tilehit=pwalltile;
HitHorizWall();
}
else
{
texdelta = -(pwallposi<<10);
xintercept=xtile<<TILESHIFT;
ytile = (short) (yintercept >> TILESHIFT);
tilehit=pwalltile;
HitVertWall();
}
}
else
{
if(((uint32_t)yintercept>>16)==pwally && xtile==pwallx)
{
texdelta = -(pwallposi<<10);
xintercept=xtile<<TILESHIFT;
ytile = (short) (yintercept >> TILESHIFT);
tilehit=pwalltile;
HitVertWall();
}
else
{
if(pwalldir==di_south && (int32_t)((word)yintercept)+ystep>(pwallposi<<10)
|| pwalldir==di_north && (int32_t)((word)yintercept)+ystep<(pwallposi<<10))
goto passvert;
if(pwalldir==di_south)
yintercept=(yintercept&0xffff0000)-((64-pwallpos)<<10);
else
yintercept=(yintercept&0xffff0000)+((64-pwallpos)<<10);
xintercept=xintercept-((xstep*pwallpos)>>6);
xtile = (short) (xintercept >> TILESHIFT);
tilehit=pwalltile;
HitHorizWall();
}
}
}
}
else
{
xintercept=xtile<<TILESHIFT;
ytile = (short) (yintercept >> TILESHIFT);
HitVertWall();
}
}
break;
}
passvert:
*((byte *)spotvis+xspot)=1;
xtile+=xtilestep;
yintercept+=ystep;
xspot=(word)((xtile<<mapshift)+((uint32_t)yintercept>>16));
}
while(1);
continue;
do
{
if(xtilestep==-1 && (xintercept>>16)<=xtile) goto vertentry;
if(xtilestep==1 && (xintercept>>16)>=xtile) goto vertentry;
horizentry:
if((uint32_t)xintercept>mapwidth*65536-1 || (word)ytile>=mapheight)
{
if(ytile<0) yintercept=0, ytile=0;
else if(ytile>=mapheight) yintercept=mapheight<<TILESHIFT, ytile=mapheight-1;
else ytile=(short) (yintercept >> TILESHIFT);
if(xintercept<0) xintercept=0, xtile=0;
else if(xintercept>=(mapwidth<<TILESHIFT)) xintercept=mapwidth<<TILESHIFT, xtile=mapwidth-1;
xspot=0xffff;
tilehit=0;
HitVertBorder();
break;
}
if(yspot>=maparea) break;
tilehit=((byte *)tilemap)[yspot];
if(tilehit)
{
if(tilehit&0x80)
{
int32_t xintbuf=xintercept+(xstep>>1);
if((xintbuf>>16)!=(xintercept>>16))
goto passhoriz;
if((word)xintbuf<doorposition[tilehit&0x7f])
goto passhoriz;
xintercept=xintbuf;
yintercept=(ytile<<TILESHIFT)+0x8000;
xtile = (short) (xintercept >> TILESHIFT);
HitHorizDoor();
}
else
{
if(tilehit==64)
{
if(pwalldir==di_north || pwalldir==di_south)
{
int32_t xintbuf;
int pwallposnorm;
int pwallposinv;
if(pwalldir==di_north)
{
pwallposnorm = 64-pwallpos;
pwallposinv = pwallpos;
}
else
{
pwallposnorm = pwallpos;
pwallposinv = 64-pwallpos;
}
if(pwalldir == di_south && ytile==pwally && ((uint32_t)xintercept>>16)==pwallx
|| pwalldir == di_north && !(ytile==pwally && ((uint32_t)xintercept>>16)==pwallx))
{
xintbuf=xintercept+((xstep*pwallposnorm)>>6);
if((xintbuf>>16)!=(xintercept>>16))
goto passhoriz;
yintercept=(ytile<<TILESHIFT)+TILEGLOBAL-(pwallposinv<<10);
xintercept=xintbuf;
xtile = (short) (xintercept >> TILESHIFT);
tilehit=pwalltile;
HitHorizWall();
}
else
{
xintbuf=xintercept+((xstep*pwallposinv)>>6);
if((xintbuf>>16)!=(xintercept>>16))
goto passhoriz;
yintercept=(ytile<<TILESHIFT)-(pwallposinv<<10);
xintercept=xintbuf;
xtile = (short) (xintercept >> TILESHIFT);
tilehit=pwalltile;
HitHorizWall();
}
}
else
{
int pwallposi = pwallpos;
if(pwalldir==di_west) pwallposi = 64-pwallpos;
if(pwalldir==di_east && (word)xintercept<(pwallposi<<10)
|| pwalldir==di_west && (word)xintercept>(pwallposi<<10))
{
if(((uint32_t)xintercept>>16)==pwallx && ytile==pwally)
{
if(pwalldir==di_east && (int32_t)((word)xintercept)+xstep<(pwallposi<<10)
|| pwalldir==di_west && (int32_t)((word)xintercept)+xstep>(pwallposi<<10))
goto passhoriz;
if(pwalldir==di_east)
xintercept=(xintercept&0xffff0000)+(pwallposi<<10);
else
xintercept=(xintercept&0xffff0000)-TILEGLOBAL+(pwallposi<<10);
yintercept=yintercept-((ystep*(64-pwallpos))>>6);
ytile = (short) (yintercept >> TILESHIFT);
tilehit=pwalltile;
HitVertWall();
}
else
{
texdelta = -(pwallposi<<10);
yintercept=ytile<<TILESHIFT;
xtile = (short) (xintercept >> TILESHIFT);
tilehit=pwalltile;
HitHorizWall();
}
}
else
{
if(((uint32_t)xintercept>>16)==pwallx && ytile==pwally)
{
texdelta = -(pwallposi<<10);
yintercept=ytile<<TILESHIFT;
xtile = (short) (xintercept >> TILESHIFT);
tilehit=pwalltile;
HitHorizWall();
}
else
{
if(pwalldir==di_east && (int32_t)((word)xintercept)+xstep>(pwallposi<<10)
|| pwalldir==di_west && (int32_t)((word)xintercept)+xstep<(pwallposi<<10))
goto passhoriz;
if(pwalldir==di_east)
xintercept=(xintercept&0xffff0000)-((64-pwallpos)<<10);
else
xintercept=(xintercept&0xffff0000)+((64-pwallpos)<<10);
yintercept=yintercept-((ystep*pwallpos)>>6);
ytile = (short) (yintercept >> TILESHIFT);
tilehit=pwalltile;
HitVertWall();
}
}
}
}
else
{
yintercept=ytile<<TILESHIFT;
xtile = (short) (xintercept >> TILESHIFT);
HitHorizWall();
}
}
break;
}
passhoriz:
*((byte *)spotvis+yspot)=1;
ytile+=ytilestep;
xintercept+=xstep;
yspot=(word)((((uint32_t)xintercept>>16)<<mapshift)+ytile);
}
while(1);
}
}
/*
====================
=
= WallRefresh
=
====================
*/
void WallRefresh (void)
{
xpartialdown = viewx&(TILEGLOBAL-1);
xpartialup = TILEGLOBAL-xpartialdown;
ypartialdown = viewy&(TILEGLOBAL-1);
ypartialup = TILEGLOBAL-ypartialdown;
min_wallheight = viewheight;
lastside = -1; // the first pixel is on a new wall
AsmRefresh ();
ScalePost (); // no more optimization on last post
}
void CalcViewVariables()
{
viewangle = player->angle;
midangle = viewangle*(FINEANGLES/ANGLES);
viewsin = sintable[viewangle];
viewcos = costable[viewangle];
viewx = player->x - FixedMul(focallength,viewcos);
viewy = player->y + FixedMul(focallength,viewsin);
focaltx = (short)(viewx>>TILESHIFT);
focalty = (short)(viewy>>TILESHIFT);
viewtx = (short)(player->x >> TILESHIFT);
viewty = (short)(player->y >> TILESHIFT);
}
//==========================================================================
/*
========================
=
= ThreeDRefresh
=
========================
*/
void ThreeDRefresh (void)
{
//
// clear out the traced array
//
memset(spotvis,0,maparea);
spotvis[player->tilex][player->tiley] = 1; // Detect all sprites over player fix
vbuf = VL_LockSurface(screenBuffer);
vbuf+=screenofs;
vbufPitch = bufferPitch;
CalcViewVariables();
//
// follow the walls from there to the right, drawing as we go
//
VGAClearScreen ();
#if defined(USE_FEATUREFLAGS) && defined(USE_STARSKY)
if(GetFeatureFlags() & FF_STARSKY)
DrawStarSky(vbuf, vbufPitch);
#endif
WallRefresh ();
#if defined(USE_FEATUREFLAGS) && defined(USE_PARALLAX)
if(GetFeatureFlags() & FF_PARALLAXSKY)
DrawParallax(vbuf, vbufPitch);
#endif
#if defined(USE_FEATUREFLAGS) && defined(USE_CLOUDSKY)
if(GetFeatureFlags() & FF_CLOUDSKY)
DrawClouds(vbuf, vbufPitch, min_wallheight);
#endif
#ifdef USE_FLOORCEILINGTEX
DrawFloorAndCeiling(vbuf, vbufPitch, min_wallheight);
#endif
//
// draw all the scaled images
//
DrawScaleds(); // draw scaled stuff
#if defined(USE_FEATUREFLAGS) && defined(USE_RAIN)
if(GetFeatureFlags() & FF_RAIN)
DrawRain(vbuf, vbufPitch);
#endif
#if defined(USE_FEATUREFLAGS) && defined(USE_SNOW)
if(GetFeatureFlags() & FF_SNOW)
DrawSnow(vbuf, vbufPitch);
#endif
DrawPlayerWeapon (); // draw player's hands
if(Keyboard[sc_Tab] && viewsize == 21 && gamestate.weapon != -1)
ShowActStatus();
VL_UnlockSurface(screenBuffer);
vbuf = NULL;
//
// show screen and time last cycle
//
if (fizzlein)
{
FizzleFade(screenBuffer, 0, 0, screenWidth, screenHeight, 20, false);
fizzlein = false;
lasttimecount = GetTimeCount(); // don't make a big tic count
}
else
{
#ifndef REMDEBUG
if (fpscounter)
{
fontnumber = 0;
SETFONTCOLOR(7,127);
PrintX=4; PrintY=1;
VWB_Bar(0,0,50,10,bordercol);
US_PrintSigned(fps);
US_Print(" fps");
}
#endif
SDL_BlitSurface(screenBuffer, NULL, screen, NULL);
SDL_Flip(screen);
}
#ifndef REMDEBUG
if (fpscounter)
{
fps_frames++;
fps_time+=tics;
if(fps_time>35)
{
fps_time-=35;
fps=fps_frames<<1;
fps_frames=0;
}
}
#endif
}
| 29.216019 | 119 | 0.452584 | [
"object",
"shape",
"transform"
] |
ec6577a1ebb99eb85469a56a29f561ae4f7ec6da | 4,597 | cpp | C++ | net/http/HttpServer.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 27 | 2019-04-27T00:51:22.000Z | 2022-03-30T04:05:44.000Z | net/http/HttpServer.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 9 | 2020-05-03T12:17:50.000Z | 2021-10-15T02:18:47.000Z | net/http/HttpServer.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 1 | 2019-04-16T01:45:36.000Z | 2019-04-16T01:45:36.000Z | #include "Object.hpp"
#include "StrongPointer.hpp"
#include "ArrayList.hpp"
#include "AutoLock.hpp"
#include "Error.hpp"
#include "HttpHeader.hpp"
#include "HttpInternalException.hpp"
#include "HttpLinker.hpp"
#include "HttpLinkerManager.hpp"
#include "HttpPacket.hpp"
#include "HttpServer.hpp"
#include "InetAddress.hpp"
#include "InterruptedException.hpp"
#include "Log.hpp"
#include "SSLManager.hpp"
#include "SocketBuilder.hpp"
#include "SocketOption.hpp"
#include "String.hpp"
#include "HttpPacketWriter.hpp"
namespace obotcha {
void _HttpServer::onSocketMessage(int event, Socket r, ByteArray pack) {
switch (event) {
case SocketEvent::Message: {
HttpLinker info = mLinkerManager->getLinker(r);
if (info == nullptr) {
LOG(ERROR) << "http linker already removed";
return;
}
if (info->pushHttpData(pack) == -1) {
// some thing may be wrong(overflow)
LOG(ERROR) << "push http data error";
mHttpListener->onHttpMessage(SocketEvent::InternalError, info,
nullptr, nullptr);
mLinkerManager->removeLinker(r);
r->close();
return;
}
ArrayList<HttpPacket> packets = info->pollHttpPacket();
if (packets != nullptr && packets->size() != 0) {
HttpPacketWriter writer =
createHttpPacketWriter(info->getSocket()->getOutputStream());
ListIterator<HttpPacket> iterator = packets->getIterator();
while (iterator->hasValue()) {
mHttpListener->onHttpMessage(event, info, writer,
iterator->getValue());
iterator->next();
}
}
} break;
case SocketEvent::Connect: {
HttpLinker info = createHttpLinker(r);
if (isSSl) {
SSLInfo ssl = st(SSLManager)::getInstance()->get(
r->getFileDescriptor()->getFd());
if (info != nullptr) {
info->setSSLInfo(ssl);
}
}
mLinkerManager->addLinker(info);
mHttpListener->onHttpMessage(event, info, nullptr, nullptr);
} break;
case SocketEvent::Disconnect: {
HttpLinker info = mLinkerManager->getLinker(r);
mHttpListener->onHttpMessage(event, info, nullptr, nullptr);
mLinkerManager->removeLinker(r);
} break;
}
}
_HttpServer::_HttpServer(InetAddress addr, HttpListener l, HttpOption option) {
mHttpListener = l;
mServerSock = nullptr;
mSockMonitor = nullptr;
mSSLServer = nullptr;
mAddress = addr;
mOption = option;
mLinkerManager = createHttpLinkerManager();
}
void _HttpServer::start() {
String certificate = nullptr;
String key = nullptr;
if (mOption != nullptr) {
certificate = mOption->getCertificate();
key = mOption->getKey();
}
if (certificate != nullptr && key != nullptr) {
// https server
isSSl = true;
mSSLServer =
createSSLServer(mAddress->getAddress(), mAddress->getPort(),
AutoClone(this), certificate, key);
} else {
isSSl = false;
mServerSock = createSocketBuilder()
->setOption(mOption)
->setAddress(mAddress)
->newServerSocket();
if (mServerSock->bind() < 0) {
LOG(ERROR) << "bind socket failed,reason " << strerror(errno);
this->close();
return;
}
int threadsNum = st(Enviroment)::getInstance()->getInt(
st(Enviroment)::gHttpServerThreadsNum, 4);
mSockMonitor = createSocketMonitor(threadsNum);
mSockMonitor->bind(mServerSock, AutoClone(this));
}
}
// interface for websocket
void _HttpServer::deMonitor(Socket s) { mSockMonitor->remove(s); }
void _HttpServer::close() {
if (mSockMonitor != nullptr) {
mSockMonitor->close();
mSockMonitor = nullptr;
}
if (mServerSock != nullptr) {
mServerSock->close();
mServerSock = nullptr;
}
if (mSSLServer != nullptr) {
mSSLServer->close();
mSSLServer = nullptr;
}
if(mLinkerManager != nullptr) {
mLinkerManager->clear();
mLinkerManager = nullptr;
}
}
_HttpServer::~_HttpServer() { close(); }
} // namespace obotcha
| 30.646667 | 81 | 0.561018 | [
"object"
] |
ec65bf12e23650c3b8b6c1dcc4c31320efc3cc56 | 14,474 | cc | C++ | cpp/src/arrow/dataset/file_base.cc | karldw/arrow | 0d995486e6eb4c94a64f03578731aad05c151596 | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 1 | 2020-09-30T02:48:39.000Z | 2020-09-30T02:48:39.000Z | cpp/src/arrow/dataset/file_base.cc | karldw/arrow | 0d995486e6eb4c94a64f03578731aad05c151596 | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 20 | 2021-05-09T06:53:01.000Z | 2022-03-27T22:21:50.000Z | cpp/src/arrow/dataset/file_base.cc | karldw/arrow | 0d995486e6eb4c94a64f03578731aad05c151596 | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "arrow/dataset/file_base.h"
#include <algorithm>
#include <unordered_map>
#include <vector>
#include "arrow/compute/exec/forest_internal.h"
#include "arrow/compute/exec/subtree_internal.h"
#include "arrow/dataset/dataset_internal.h"
#include "arrow/dataset/dataset_writer.h"
#include "arrow/dataset/scanner.h"
#include "arrow/dataset/scanner_internal.h"
#include "arrow/filesystem/filesystem.h"
#include "arrow/filesystem/path_util.h"
#include "arrow/io/compressed.h"
#include "arrow/io/interfaces.h"
#include "arrow/io/memory.h"
#include "arrow/util/compression.h"
#include "arrow/util/iterator.h"
#include "arrow/util/macros.h"
#include "arrow/util/make_unique.h"
#include "arrow/util/map.h"
#include "arrow/util/string.h"
#include "arrow/util/task_group.h"
#include "arrow/util/variant.h"
namespace arrow {
using internal::checked_pointer_cast;
namespace dataset {
Result<std::shared_ptr<io::RandomAccessFile>> FileSource::Open() const {
if (filesystem_) {
return filesystem_->OpenInputFile(file_info_);
}
if (buffer_) {
return std::make_shared<io::BufferReader>(buffer_);
}
return custom_open_();
}
Result<std::shared_ptr<io::InputStream>> FileSource::OpenCompressed(
util::optional<Compression::type> compression) const {
ARROW_ASSIGN_OR_RAISE(auto file, Open());
auto actual_compression = Compression::type::UNCOMPRESSED;
if (!compression.has_value()) {
// Guess compression from file extension
auto extension = fs::internal::GetAbstractPathExtension(path());
if (extension == "gz") {
actual_compression = Compression::type::GZIP;
} else {
auto maybe_compression = util::Codec::GetCompressionType(extension);
if (maybe_compression.ok()) {
ARROW_ASSIGN_OR_RAISE(actual_compression, maybe_compression);
}
}
} else {
actual_compression = compression.value();
}
if (actual_compression == Compression::type::UNCOMPRESSED) {
return file;
}
ARROW_ASSIGN_OR_RAISE(auto codec, util::Codec::Create(actual_compression));
return io::CompressedInputStream::Make(codec.get(), std::move(file));
}
Future<util::optional<int64_t>> FileFormat::CountRows(
const std::shared_ptr<FileFragment>&, compute::Expression,
const std::shared_ptr<ScanOptions>&) {
return Future<util::optional<int64_t>>::MakeFinished(util::nullopt);
}
Result<std::shared_ptr<FileFragment>> FileFormat::MakeFragment(
FileSource source, std::shared_ptr<Schema> physical_schema) {
return MakeFragment(std::move(source), compute::literal(true),
std::move(physical_schema));
}
Result<std::shared_ptr<FileFragment>> FileFormat::MakeFragment(
FileSource source, compute::Expression partition_expression) {
return MakeFragment(std::move(source), std::move(partition_expression), nullptr);
}
Result<std::shared_ptr<FileFragment>> FileFormat::MakeFragment(
FileSource source, compute::Expression partition_expression,
std::shared_ptr<Schema> physical_schema) {
return std::shared_ptr<FileFragment>(
new FileFragment(std::move(source), shared_from_this(),
std::move(partition_expression), std::move(physical_schema)));
}
// The following implementation of ScanBatchesAsync is both ugly and terribly inefficient.
// Each of the formats should provide their own efficient implementation. However, this
// is a reasonable starting point or implementation for a dummy/mock format.
Result<RecordBatchGenerator> FileFormat::ScanBatchesAsync(
const std::shared_ptr<ScanOptions>& scan_options,
const std::shared_ptr<FileFragment>& file) const {
ARROW_ASSIGN_OR_RAISE(auto scan_task_it, ScanFile(scan_options, file));
struct State {
State(std::shared_ptr<ScanOptions> scan_options, ScanTaskIterator scan_task_it)
: scan_options(std::move(scan_options)),
scan_task_it(std::move(scan_task_it)),
current_rb_it(),
finished(false) {}
std::shared_ptr<ScanOptions> scan_options;
ScanTaskIterator scan_task_it;
RecordBatchIterator current_rb_it;
bool finished;
};
struct Generator {
Future<std::shared_ptr<RecordBatch>> operator()() {
while (!state->finished) {
if (!state->current_rb_it) {
RETURN_NOT_OK(PumpScanTask());
if (state->finished) {
return AsyncGeneratorEnd<std::shared_ptr<RecordBatch>>();
}
}
ARROW_ASSIGN_OR_RAISE(auto next_batch, state->current_rb_it.Next());
if (IsIterationEnd(next_batch)) {
state->current_rb_it = RecordBatchIterator();
} else {
return Future<std::shared_ptr<RecordBatch>>::MakeFinished(next_batch);
}
}
return AsyncGeneratorEnd<std::shared_ptr<RecordBatch>>();
}
Status PumpScanTask() {
ARROW_ASSIGN_OR_RAISE(auto next_task, state->scan_task_it.Next());
if (IsIterationEnd(next_task)) {
state->finished = true;
} else {
ARROW_ASSIGN_OR_RAISE(state->current_rb_it, next_task->Execute());
}
return Status::OK();
}
std::shared_ptr<State> state;
};
return Generator{std::make_shared<State>(scan_options, std::move(scan_task_it))};
}
Result<std::shared_ptr<Schema>> FileFragment::ReadPhysicalSchemaImpl() {
return format_->Inspect(source_);
}
Result<ScanTaskIterator> FileFragment::Scan(std::shared_ptr<ScanOptions> options) {
auto self = std::dynamic_pointer_cast<FileFragment>(shared_from_this());
return format_->ScanFile(options, self);
}
Result<RecordBatchGenerator> FileFragment::ScanBatchesAsync(
const std::shared_ptr<ScanOptions>& options) {
auto self = std::dynamic_pointer_cast<FileFragment>(shared_from_this());
return format_->ScanBatchesAsync(options, self);
}
Future<util::optional<int64_t>> FileFragment::CountRows(
compute::Expression predicate, const std::shared_ptr<ScanOptions>& options) {
ARROW_ASSIGN_OR_RAISE(predicate, compute::SimplifyWithGuarantee(std::move(predicate),
partition_expression_));
if (!predicate.IsSatisfiable()) {
return Future<util::optional<int64_t>>::MakeFinished(0);
}
auto self = checked_pointer_cast<FileFragment>(shared_from_this());
return format()->CountRows(self, std::move(predicate), options);
}
struct FileSystemDataset::FragmentSubtrees {
// Forest for skipping fragments based on extracted subtree expressions
compute::Forest forest;
// fragment indices and subtree expressions in forest order
std::vector<util::Variant<int, compute::Expression>> fragments_and_subtrees;
};
Result<std::shared_ptr<FileSystemDataset>> FileSystemDataset::Make(
std::shared_ptr<Schema> schema, compute::Expression root_partition,
std::shared_ptr<FileFormat> format, std::shared_ptr<fs::FileSystem> filesystem,
std::vector<std::shared_ptr<FileFragment>> fragments,
std::shared_ptr<Partitioning> partitioning) {
std::shared_ptr<FileSystemDataset> out(
new FileSystemDataset(std::move(schema), std::move(root_partition)));
out->format_ = std::move(format);
out->filesystem_ = std::move(filesystem);
out->fragments_ = std::move(fragments);
out->partitioning_ = std::move(partitioning);
out->SetupSubtreePruning();
return out;
}
Result<std::shared_ptr<Dataset>> FileSystemDataset::ReplaceSchema(
std::shared_ptr<Schema> schema) const {
RETURN_NOT_OK(CheckProjectable(*schema_, *schema));
return Make(std::move(schema), partition_expression_, format_, filesystem_, fragments_);
}
std::vector<std::string> FileSystemDataset::files() const {
std::vector<std::string> files;
for (const auto& fragment : fragments_) {
files.push_back(fragment->source().path());
}
return files;
}
std::string FileSystemDataset::ToString() const {
std::string repr = "FileSystemDataset:";
if (fragments_.empty()) {
return repr + " []";
}
for (const auto& fragment : fragments_) {
repr += "\n" + fragment->source().path();
const auto& partition = fragment->partition_expression();
if (partition != compute::literal(true)) {
repr += ": " + partition.ToString();
}
}
return repr;
}
void FileSystemDataset::SetupSubtreePruning() {
subtrees_ = std::make_shared<FragmentSubtrees>();
compute::SubtreeImpl impl;
auto encoded = impl.EncodeGuarantees(
[&](int index) { return fragments_[index]->partition_expression(); },
static_cast<int>(fragments_.size()));
std::sort(encoded.begin(), encoded.end(), compute::SubtreeImpl::ByGuarantee());
for (const auto& e : encoded) {
if (e.index) {
subtrees_->fragments_and_subtrees.emplace_back(*e.index);
} else {
subtrees_->fragments_and_subtrees.emplace_back(impl.GetSubtreeExpression(e));
}
}
subtrees_->forest = compute::Forest(static_cast<int>(encoded.size()),
compute::SubtreeImpl::IsAncestor{encoded});
}
Result<FragmentIterator> FileSystemDataset::GetFragmentsImpl(
compute::Expression predicate) {
if (predicate == compute::literal(true)) {
// trivial predicate; skip subtree pruning
return MakeVectorIterator(FragmentVector(fragments_.begin(), fragments_.end()));
}
std::vector<int> fragment_indices;
std::vector<compute::Expression> predicates{predicate};
RETURN_NOT_OK(subtrees_->forest.Visit(
[&](compute::Forest::Ref ref) -> Result<bool> {
if (auto fragment_index =
util::get_if<int>(&subtrees_->fragments_and_subtrees[ref.i])) {
fragment_indices.push_back(*fragment_index);
return false;
}
const auto& subtree_expr =
util::get<compute::Expression>(subtrees_->fragments_and_subtrees[ref.i]);
ARROW_ASSIGN_OR_RAISE(auto simplified,
SimplifyWithGuarantee(predicates.back(), subtree_expr));
if (!simplified.IsSatisfiable()) {
return false;
}
predicates.push_back(std::move(simplified));
return true;
},
[&](compute::Forest::Ref ref) { predicates.pop_back(); }));
std::sort(fragment_indices.begin(), fragment_indices.end());
FragmentVector fragments(fragment_indices.size());
std::transform(fragment_indices.begin(), fragment_indices.end(), fragments.begin(),
[this](int i) { return fragments_[i]; });
return MakeVectorIterator(std::move(fragments));
}
Status FileWriter::Write(RecordBatchReader* batches) {
while (true) {
ARROW_ASSIGN_OR_RAISE(auto batch, batches->Next());
if (batch == nullptr) break;
RETURN_NOT_OK(Write(batch));
}
return Status::OK();
}
Status FileWriter::Finish() {
RETURN_NOT_OK(FinishInternal());
return destination_->Close();
}
namespace {
Future<> WriteNextBatch(internal::DatasetWriter* dataset_writer, TaggedRecordBatch batch,
const FileSystemDatasetWriteOptions& write_options) {
ARROW_ASSIGN_OR_RAISE(auto groups,
write_options.partitioning->Partition(batch.record_batch));
batch.record_batch.reset(); // drop to hopefully conserve memory
if (groups.batches.size() > static_cast<size_t>(write_options.max_partitions)) {
return Status::Invalid("Fragment would be written into ", groups.batches.size(),
" partitions. This exceeds the maximum of ",
write_options.max_partitions);
}
std::shared_ptr<size_t> counter = std::make_shared<size_t>(0);
std::shared_ptr<Fragment> fragment = std::move(batch.fragment);
AsyncGenerator<std::shared_ptr<RecordBatch>> partitioned_batch_gen =
[groups, counter, fragment, &write_options,
dataset_writer]() -> Future<std::shared_ptr<RecordBatch>> {
auto index = *counter;
if (index >= groups.batches.size()) {
return AsyncGeneratorEnd<std::shared_ptr<RecordBatch>>();
}
auto partition_expression =
and_(groups.expressions[index], fragment->partition_expression());
auto next_batch = groups.batches[index];
ARROW_ASSIGN_OR_RAISE(std::string destination,
write_options.partitioning->Format(partition_expression));
(*counter)++;
return dataset_writer->WriteRecordBatch(next_batch, destination).Then([next_batch] {
return next_batch;
});
};
return VisitAsyncGenerator(
std::move(partitioned_batch_gen),
[](const std::shared_ptr<RecordBatch>&) -> Status { return Status::OK(); });
}
} // namespace
Status FileSystemDataset::Write(const FileSystemDatasetWriteOptions& write_options,
std::shared_ptr<Scanner> scanner) {
ARROW_ASSIGN_OR_RAISE(auto batch_gen, scanner->ScanBatchesAsync());
ARROW_ASSIGN_OR_RAISE(auto dataset_writer,
internal::DatasetWriter::Make(write_options));
AsyncGenerator<std::shared_ptr<int>> queued_batch_gen =
[batch_gen, &dataset_writer, &write_options]() -> Future<std::shared_ptr<int>> {
Future<TaggedRecordBatch> next_batch_fut = batch_gen();
return next_batch_fut.Then(
[&dataset_writer, &write_options](const TaggedRecordBatch& batch) {
if (IsIterationEnd(batch)) {
return AsyncGeneratorEnd<std::shared_ptr<int>>();
}
return WriteNextBatch(dataset_writer.get(), batch, write_options).Then([] {
return std::make_shared<int>(0);
});
});
};
Future<> queue_fut =
VisitAsyncGenerator(std::move(queued_batch_gen),
[&](const std::shared_ptr<int>&) { return Status::OK(); });
ARROW_RETURN_NOT_OK(queue_fut.status());
return dataset_writer->Finish().status();
}
} // namespace dataset
} // namespace arrow
| 36.736041 | 90 | 0.69725 | [
"vector",
"transform"
] |
ec6a30f1438cbb90955da12b3e2a899cc7021b51 | 5,455 | cc | C++ | ash/wm/desks/persistent_desks_bar_view.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | ash/wm/desks/persistent_desks_bar_view.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | ash/wm/desks/persistent_desks_bar_view.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/wm/desks/persistent_desks_bar_view.h"
#include "ash/shell.h"
#include "ash/style/ash_color_provider.h"
#include "ash/system/unified/collapse_button.h"
#include "ash/wm/desks/desk.h"
#include "ash/wm/desks/desks_controller.h"
#include "ash/wm/desks/desks_histogram_enums.h"
#include "ash/wm/desks/zero_state_button.h"
#include "ash/wm/overview/overview_controller.h"
#include "base/containers/flat_set.h"
#include "base/stl_util.h"
#include "ui/views/background.h"
namespace ash {
namespace {
constexpr int kDeskButtonWidth = 60;
constexpr int kDeskButtonHeight = 28;
constexpr int kDeskButtonSpacing = 8;
constexpr int kDeskButtonsY = 6;
const int kToggleButtonRightPadding = 6;
} // namespace
// -----------------------------------------------------------------------------
// PersistentDesksBarDeskButton:
// The button with the desk's name inside the PersistentDesksBarView.
class PersistentDesksBarDeskButton : public DeskButtonBase {
public:
explicit PersistentDesksBarDeskButton(const Desk* desk)
: DeskButtonBase(desk->name()), desk_(desk) {
// Only paint the background of the active desk's button.
SetShouldPaintBackground(desk_ == DesksController::Get()->active_desk());
}
PersistentDesksBarDeskButton(const PersistentDesksBarDeskButton&) = delete;
PersistentDesksBarDeskButton& operator=(const PersistentDesksBarDeskButton) =
delete;
~PersistentDesksBarDeskButton() override = default;
const Desk* desk() const { return desk_; }
private:
// DeskButtonBase:
void OnButtonPressed() override {
DesksController::Get()->ActivateDesk(
desk_, DesksSwitchSource::kPersistentDesksBar);
}
void OnThemeChanged() override {
DeskButtonBase::OnThemeChanged();
SetEnabledTextColors(AshColorProvider::Get()->GetContentLayerColor(
AshColorProvider::ContentLayerType::kTextColorPrimary));
}
void OnMouseEntered(const ui::MouseEvent& event) override {
SetShouldPaintBackground(true);
}
void OnMouseExited(const ui::MouseEvent& event) override {
SetShouldPaintBackground(desk_ == DesksController::Get()->active_desk());
}
const Desk* desk_;
};
// -----------------------------------------------------------------------------
// PersistentDesksBarView:
PersistentDesksBarView::PersistentDesksBarView() {
toggle_button_ = AddChildView(std::make_unique<CollapseButton>(
base::BindRepeating(&PersistentDesksBarView::OnToggleButtonPressed,
base::Unretained(this))));
}
PersistentDesksBarView::~PersistentDesksBarView() = default;
void PersistentDesksBarView::RefreshDeskButtons() {
base::flat_set<PersistentDesksBarDeskButton*> to_be_removed(
desk_buttons_.begin(), desk_buttons_.end());
auto* desk_controller = DesksController::Get();
const auto& desks = desk_controller->desks();
const size_t previous_desk_buttons_size = desk_buttons_.size();
for (const auto& desk : desks) {
const Desk* desk_ptr = desk.get();
auto iter =
std::find_if(to_be_removed.begin(), to_be_removed.end(),
[desk_ptr](PersistentDesksBarDeskButton* desk_button) {
return desk_ptr == desk_button->desk();
});
if (iter != to_be_removed.end()) {
(*iter)->SetShouldPaintBackground(desk->is_active());
to_be_removed.erase(iter);
continue;
}
desk_buttons_.push_back(
AddChildView(std::make_unique<PersistentDesksBarDeskButton>(desk_ptr)));
}
if (!to_be_removed.empty()) {
DCHECK_EQ(1u, to_be_removed.size());
auto* to_be_removed_desk_button = *(to_be_removed.begin());
base::Erase(desk_buttons_, to_be_removed_desk_button);
RemoveChildViewT(to_be_removed_desk_button);
}
if (desks.size() != previous_desk_buttons_size)
Layout();
}
const std::vector<std::u16string>
PersistentDesksBarView::GetDeskButtonsTextForTesting() const {
std::vector<std::u16string> desk_buttons_text;
for (auto* desk_button : desk_buttons_)
desk_buttons_text.push_back(desk_button->desk()->name());
return desk_buttons_text;
}
void PersistentDesksBarView::Layout() {
const int width = bounds().width();
const int content_width =
(desk_buttons_.size() + 1) * (kDeskButtonWidth + kDeskButtonSpacing) -
kDeskButtonSpacing;
int x = (width - content_width) / 2;
for (auto* desk_button : desk_buttons_) {
desk_button->SetBoundsRect(
gfx::Rect(gfx::Point(x, kDeskButtonsY),
gfx::Size(kDeskButtonWidth, kDeskButtonHeight)));
x += (kDeskButtonWidth + kDeskButtonSpacing);
}
const gfx::Size toggle_button_size = toggle_button_->GetPreferredSize();
toggle_button_->SetBoundsRect(gfx::Rect(
gfx::Point(bounds().right() - toggle_button_size.width() -
kToggleButtonRightPadding,
(bounds().height() - toggle_button_size.height()) / 2),
toggle_button_size));
}
void PersistentDesksBarView::OnThemeChanged() {
views::View::OnThemeChanged();
SetBackground(
views::CreateSolidBackground(AshColorProvider::Get()->GetBaseLayerColor(
AshColorProvider::BaseLayerType::kOpaque)));
}
void PersistentDesksBarView::OnToggleButtonPressed() {
Shell::Get()->overview_controller()->StartOverview();
}
} // namespace ash
| 34.308176 | 80 | 0.699542 | [
"vector"
] |
ec6f059d9e0fe5ed51f3c0122c9f14f96363b15b | 3,630 | cpp | C++ | JPR/src/jpr_interface.cpp | huangqx/MultiScanRegistration | fb56eb4f51f322423add2e33ef25890e5df8908d | [
"MIT"
] | 93 | 2020-08-14T09:40:07.000Z | 2022-01-05T17:07:05.000Z | JPR/src/jpr_interface.cpp | huangqx/MultiScanRegistration | fb56eb4f51f322423add2e33ef25890e5df8908d | [
"MIT"
] | null | null | null | JPR/src/jpr_interface.cpp | huangqx/MultiScanRegistration | fb56eb4f51f322423add2e33ef25890e5df8908d | [
"MIT"
] | 12 | 2020-08-24T02:04:30.000Z | 2022-01-04T14:14:28.000Z | /*---
function [scanposes, corres] = jpr_interface(datapoints, scan_offsets, paras)
Input:
Output
--*/
#include "mex.h"
#include "point_cloud.h"
#include "linear_algebra.h"
#include "affine_transformation.h"
#include "joint_pairwise_registration.h"
#include <vector>
#include <algorithm>
using namespace std;
// The three input matrices are
// 1) The mesh vertices
// 2) The mesh faces
// 3) The camera parameters
// The output parameters
// 1) The intersecting pixels
void mexFunction(
int nargout,
mxArray *output[],
int nargin,
const mxArray *input[]) {
/* check argument */
if (nargin != 3) {
mexErrMsgTxt("Three input arguments required.");
}
if (nargout != 2) {
mexErrMsgTxt("Incorrect number of output arguments.");
}
double *pointData = (double*)mxGetData(input[0]);
unsigned numPoints = static_cast<unsigned> (mxGetN(input[0]));
double *offsetData = (double*)mxGetData(input[1]);
unsigned numScans = static_cast<unsigned> (mxGetN(input[1]))-1;
vector<PointCloud> scans;
scans.resize(numScans);
for (unsigned id = 0; id < numScans; ++id) {
vector<Surfel3D> *surfels = scans[id].GetPointArray();
int left = static_cast<int> (offsetData[id]);
int right = static_cast<int> (offsetData[id+1]);
surfels->resize(right-left);
for (int i = left; i < right; ++i) {
Surfel3D *sur = &(*surfels)[i-left];
int off = 9*i;
for (int k = 0; k < 3; ++k) {
sur->position[k] = static_cast<float> (pointData[off+k]);
sur->normal[k] = static_cast<float> (pointData[off+3+k]);
sur->color[k] = 0.f;
}
}
}
// Setup the parameters
double *data = (double*)mxGetData(input[2]);
float max_distance = static_cast<float> (data[0]);
float overlap_ratio = static_cast<float> (data[1]);
float weight_normal = static_cast<float> (data[2]);
float weight_color = static_cast<float> (data[3]);
unsigned down_sampling_rate = static_cast<unsigned> (data[4]);
unsigned num_reweighting_iters = static_cast<unsigned> (data[5]);
unsigned num_gauss_newton_iters = static_cast<unsigned> (data[6]);
float weight_point2planeDis = static_cast<float> (data[7]);
//
vector<Affine3d> opt_poses;
opt_poses.resize(numScans);
vector<PointCorres2> pointcorres;
// Perform multi-scan registration
JointPairwiseRegistration jpr;
bool flag = jpr.Compute(scans,
max_distance, overlap_ratio,
weight_normal, weight_color,
down_sampling_rate, num_reweighting_iters, num_gauss_newton_iters,
weight_point2planeDis,
&opt_poses,
&pointcorres);
// Output optimized scan poses
output[0] = mxCreateDoubleMatrix(12, numScans, mxREAL);
data = mxGetPr(output[0]);
if (flag) {
for (unsigned scanid = 0; scanid < numScans; ++scanid) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 3; ++j) {
data[12*scanid+i*3+j] = opt_poses[scanid][i][j];
}
}
}
}
// Output optimized correspondences
unsigned numcorres = pointcorres.size();
output[1] = mxCreateDoubleMatrix(5, numcorres, mxREAL);
data = mxGetPr(output[1]);
for (unsigned corid = 0; corid < numcorres; ++corid) {
const PointCorres2 &pc = pointcorres[corid];
data[5*corid] = pc.sourceSurfId + 1;
data[5*corid+1] = pc.targetSurfId + 1;
data[5*corid+2] = pc.sourcePointId + 1;
data[5*corid+3] = pc.targetPointId + 1;
data[5*corid+4] = pc.weight;
}
} | 33.302752 | 78 | 0.622865 | [
"mesh",
"vector"
] |
ec72d889c73f966a224feae9184c3c6f21ce1e2a | 856 | cpp | C++ | Understand Pointers/SmartPointers.cpp | soumilk/Inheritance- | 8aa19aef0f4d739db71124af1616ec8f6ddd8375 | [
"BSL-1.0"
] | 12 | 2019-07-04T19:35:36.000Z | 2021-11-28T15:10:19.000Z | Understand Pointers/SmartPointers.cpp | soumilk/Inheritance- | 8aa19aef0f4d739db71124af1616ec8f6ddd8375 | [
"BSL-1.0"
] | 13 | 2019-07-16T17:15:27.000Z | 2019-10-25T09:07:12.000Z | Understand Pointers/SmartPointers.cpp | soumilk/Inheritance- | 8aa19aef0f4d739db71124af1616ec8f6ddd8375 | [
"BSL-1.0"
] | 16 | 2019-08-16T00:52:50.000Z | 2021-09-29T15:03:32.000Z | #include<iostream>
/*
*
* @author Avinash Mager
* Smart pointer are a kind of pointers whose destruction happens impliceitely.
* Usually these are the wrappers over the pointer variable/object.
* This program demonstrates the use of smart pointers by aking an example of calculation of factorial.
*/
using namespace std;
class Factorial
{
unsigned long *ptr;
public:
Factorial()
{
}
explicit Factorial(long num)
{
ptr = new unsigned long(num);
}
~Factorial()
{
delete ptr;
}
unsigned long CalculateFactorial()
{
if ( *ptr == 0 )
return 1;
long tmp = *ptr;
while(--tmp)
{
*ptr = *ptr * tmp;
}
return *ptr;
}
};
int main()
{
long num;
cout << "Enter Number: ";
cin >> num;
Factorial fact(num);
cout << "Factorial of given number : " << fact.CalculateFactorial() << endl;
return 0;
}
| 15.563636 | 103 | 0.641355 | [
"object"
] |
ec766eb51d3cd4237cc693f38d96bb0abbd4d94e | 3,551 | cpp | C++ | src/conv.cpp | songqun/speedup-aarch64-cpu | a78dea87e25e71e68ab1985e91d5d99b1aa6fb1a | [
"MIT"
] | 13 | 2019-07-14T12:45:44.000Z | 2022-02-08T06:10:14.000Z | src/conv.cpp | songqun/speedup-aarch64-cpu | a78dea87e25e71e68ab1985e91d5d99b1aa6fb1a | [
"MIT"
] | null | null | null | src/conv.cpp | songqun/speedup-aarch64-cpu | a78dea87e25e71e68ab1985e91d5d99b1aa6fb1a | [
"MIT"
] | null | null | null | #include "conv.hpp"
// More description see header for detail.
void get_output_hw(int ih, int iw, int fh, int fw, int s, int p, int *oh, int *ow)
{
// ignore remainder if it appears divided by s, like what Caffe does.
*oh = (ih + 2*p - fh) / s + 1;
*ow = (iw + 2*p - fw) / s + 1;
}
void infer_conv_alg(int nb, int ic, int ih, int iw, int oc, int oh, int ow, int fh, int fw, int s, int p, ConvAlg *alg)
{
// TODO make implementations more general when there are remainders.
if (ic%4 != 0 || oc%8 != 0) {
*alg = CONV_NOT_MATCH;
return;
}
#if defined(_USE_NEON_A55) || defined(_USE_NEON_A76)
if (fh==3 && fw==3 && s==1 && p==1) {
*alg = CONV_WINO_ONE_STEP;
} else if (ih < 24 && iw < 24) {
#else
if (ih < 24 && iw < 24) { // just guess threshold (between 14 and 28)
#endif
*alg = CONV_IM2COL_TOTAL_PACK;
} else {
*alg = CONV_IM2COL_TILE_PACK;
}
}
void conv_buffer_size(int nb, int ic, int ih, int iw, int oc, int oh, int ow, int fh, int fw, int s, int p, ConvAlg alg, int *bytes)
{
switch(alg) {
case CONV_WINO_ONE_STEP: {
int tile_h = (oh + 3) / 4;
int tile_w = (ow + 3) / 4;
int p_left = p;
int p_w_mod_4 = tile_w*4 - ow;
int p_right = p + p_w_mod_4;
int p_top = p;
int p_h_mod_4 = tile_h*4 - oh;
int p_bottom = p + p_h_mod_4;
int ih_pad = ih + p_top + p_bottom; // pad to 4|ih_pad(iw_pad) for 4x4 block input transform to 6x6 block
int iw_pad = iw + p_left + p_right;
*bytes = ic*ih_pad*iw_pad + 6*6*ic*8 + oc*6*6*8;
break;
}
case CONV_IM2COL_TOTAL_PACK: {
// padding + in_pack
int ih_pad = ih + 2*p;
int iw_pad = iw + 2*p;
*bytes = ic*ih_pad*iw_pad + fh*fw*ic*oh*ow;
break;
}
case CONV_IM2COL_TILE_PACK: {
// padding + in_pack
int ih_pad = ih + 2*p;
int iw_pad = iw + 2*p;
*bytes = ic*ih_pad*iw_pad + fh*fw*ic*8;
break;
}
default: {
break;
}
}
*bytes *= sizeof(float);
}
void weight_trans_size(int nb, int ic, int ih, int iw, int oc, int oh, int ow, int fh, int fw, int s, int p, ConvAlg alg, int *bytes)
{
switch(alg) {
case CONV_WINO_ONE_STEP: {
*bytes = ic*oc*6*6;
break;
}
default: {
*bytes = ic*oc*fh*fw;
break;
}
}
*bytes *= sizeof(float);
}
void weight_trans(float *weight, float *weight_tm, int ic, int oc, int fh, int fw, ConvAlg alg)
{
switch(alg) {
case CONV_IM2COL_TOTAL_PACK: {
weight_trans_im2col(weight, weight_tm, ic, oc, fh, fw);
break;
}
case CONV_IM2COL_TILE_PACK: {
weight_trans_im2col(weight, weight_tm, ic, oc, fh, fw);
break;
}
case CONV_WINO_ONE_STEP: {
weight_trans_wino(weight, weight_tm, ic, oc, fh, fw);
break;
}
default: {
break;
}
}
}
void conv(float *input, float *weight, float *output, float *bias,
int nb, int ic, int ih, int iw, int oc, int oh, int ow, int fh, int fw, int s, int p, float *buf, ConvAlg alg)
{
switch(alg) {
case CONV_WINO_ONE_STEP: {
conv3x3s1p1_wino_one_step(input, weight, output, bias, nb, ic, ih, iw, oc, oh, ow, fh, fw, s, p, buf);
break;
}
case CONV_IM2COL_TOTAL_PACK: {
conv_im2col_total_pack(input, weight, output, bias, nb, ic, ih, iw, oc, oh, ow, fh, fw, s, p, buf);
break;
}
case CONV_IM2COL_TILE_PACK: {
conv_im2col_tile_pack(input, weight, output, bias, nb, ic, ih, iw, oc, oh, ow, fh, fw, s, p, buf);
break;
}
default: {
break;
}
}
} | 26.5 | 133 | 0.580118 | [
"transform"
] |
3f3f229de193cd1b1e446211226d6eb61dc10178 | 9,202 | cpp | C++ | ping360_sonar/src/ping360_node.cpp | AlexisFetet/ping360_sonar | 9060485a4800bd010c4c1135a8bba1936408a150 | [
"MIT"
] | 4 | 2019-12-13T20:52:54.000Z | 2019-12-20T12:33:03.000Z | ping360_sonar/src/ping360_node.cpp | AlexisFetet/ping360_sonar | 9060485a4800bd010c4c1135a8bba1936408a150 | [
"MIT"
] | 9 | 2019-12-13T20:35:41.000Z | 2020-01-09T19:27:56.000Z | ping360_sonar/src/ping360_node.cpp | Robotics-CentraleNantes/ping360_sonar | 0e74e7bfb91beee494822cb311e1b378102bce96 | [
"MIT"
] | 1 | 2020-01-06T08:34:46.000Z | 2020-01-06T08:34:46.000Z |
#include <ping360_sonar/ping360_node.h>
#include <ping360_sonar/sector.h>
#include <ping-message-common.h>
#include <ping-message-ping360.h>
using namespace std::chrono_literals;
using namespace ping360_sonar;
using std::string;
using std::vector;
Ping360Sonar::Ping360Sonar(rclcpp::NodeOptions options)
: Node("ping360", options)
{
// bounded parameters that are parsed later
declareParamDescription("gain", 0, "Sonar gain (0 = low, 1 = normal, 2 = high)", 0, 2);
declareParamDescription("frequency", 740, "Sonar operating frequency [kHz]", 650, 850);
declareParamDescription("range_max", 2, "Sonar max range [m]", 1, 50);
declareParamDescription("angle_sector", 360, "Scanned angular sector around sonar heading [degrees]. Will oscillate if not 360", 60, 360);
declareParamDescription("angle_step", 1, "Sonar angular resolution [degrees]", 1, 20);
declareParamDescription("image_size", 300, "Output image size [pixels]", 100, 1000, 2);
declareParamDescription("scan_threshold", 200, "Intensity threshold for LaserScan message", 1, 255);
declareParamDescription("speed_of_sound", 1500, "Speed of sound [m/s]", 1450, 1550);
declareParamDescription("image_rate", 100, "Image publishing rate [ms]", 50, 2000);
declareParamDescription("sonar_timeout", 8000, "Sonar timeout [ms]", 0, 20000);
// other, unbounded params
publish_image = declareParamDescription("publish_image", true, "Publish images on 'scan_image'");
publish_scan = declareParamDescription("publish_scan", false, "Publish laserscans on 'scan'");
publish_echo = declareParamDescription("publish_echo", false, "Publish raw echo on 'scan_echo'");
// constant initialization
const auto frame{declareParamDescription<string>("frame", "sonar", "Frame ID of the message headers")};
image.header.set__frame_id(frame);
image.set__encoding("mono8");
image.set__is_bigendian(0);
scan.header.set__frame_id(frame);
scan.set__range_min(0.75);
echo.header.set__frame_id(frame);
// ROS interface
configureFromParams();
const auto image_rate_ms{get_parameter("image_rate").as_int()};
image_timer = this->create_wall_timer(std::chrono::milliseconds(image_rate_ms),
[this](){publishImage();});
param_change = add_on_set_parameters_callback(
std::bind(&Ping360Sonar::parametersCallback, this, std::placeholders::_1));
}
Ping360Sonar::IntParams Ping360Sonar::updatedParams(const std::vector<rclcpp::Parameter> &new_params) const
{
// "only" parameters to be monitored for change
using ParamType = rclcpp::ParameterType;
const std::map<ParamType,vector<string>> mutable_params{
{ParamType::PARAMETER_INTEGER,{"gain","frequency","range_max",
"angle_sector","angle_step",
"speed_of_sound","image_size", "scan_threshold", "sonar_timeout"}},
{ParamType::PARAMETER_BOOL, {"publish_image","publish_scan","publish_echo"}}};
IntParams mapping;
for(const auto &[type,names]: mutable_params)
{
const auto params{get_parameters(names)};
if(type == ParamType::PARAMETER_INTEGER)
{
for(auto ¶m: params)
mapping[param.get_name()] = param.as_int();
}
else
{
for(auto ¶m: params)
mapping[param.get_name()] = param.as_bool();
}
}
// override with new ones
for(auto ¶m: new_params)
{
if(param.get_type() == ParamType::PARAMETER_BOOL)
mapping[param.get_name()] = param.as_bool();
else if(param.get_type() == ParamType::PARAMETER_INTEGER)
mapping[param.get_name()] = param.as_int();
}
return mapping;
}
SetParametersResult Ping360Sonar::parametersCallback(const vector<rclcpp::Parameter> ¶meters)
{
configureFromParams(parameters);
return SetParametersResult().set__successful(true);
}
void Ping360Sonar::initPublishers(bool image, bool scan, bool echo)
{
#ifdef PING360_PUBLISH_RELIABLE
const auto qos{rclcpp::QoS(5)};
#else
const auto qos{rclcpp::SensorDataQoS()};
#endif
publish_echo = echo;
publish_image = image;
publish_scan = scan;
if(publish_image && image_pub.getTopic().empty())
image_pub = image_transport::create_publisher(this, "scan_image");
if(publish_echo && echo_pub == nullptr)
echo_pub = create_publisher<ping360_sonar_msgs::msg::SonarEcho>("scan_echo", qos);
if(publish_scan && scan_pub == nullptr)
scan_pub = create_publisher<sensor_msgs::msg::LaserScan>("scan", qos);
}
void Ping360Sonar::configureFromParams(const vector<rclcpp::Parameter> &new_params)
{
// get current params updated with new ones, if any
const auto params{updatedParams(new_params)};
// forward to configuration
const auto [angle_sector, step] = sonar.configureAngles(params.at("angle_sector"),
params.at("angle_step"),
params.at("publish_scan")); {}
// inform if requested angle config cannot be met because of gradians
if(angle_sector != params.at("angle_sector") || step != params.at("angle_step"))
{
RCLCPP_INFO(get_logger(),
"Due to sonar using gradians, sector is %i (requested %i) and step is %i (requested %i)",
angle_sector, params.at("angle_sector"), step, params.at("angle_step"));
}
initPublishers(params.at("publish_image"),
params.at("publish_scan"),
params.at("publish_echo"));
sonar.configureTransducer(params.at("gain"),
params.at("frequency"),
params.at("speed_of_sound"),
params.at("range_max"));
sonar.setTimeout(params.at("sonar_timeout"));
// forward to message meta-data
echo.set__gain(params.at("gain"));
echo.set__range(params.at("range_max"));
echo.set__speed_of_sound(params.at("speed_of_sound"));
echo.set__number_of_samples(sonar.samples());
echo.set__transmit_frequency(params.at("frequency"));
scan.set__range_max(params.at("range_max"));
scan.set__time_increment(sonar.transmitDuration());
scan.set__angle_max(sonar.angleMax());
scan.set__angle_min(sonar.angleMin());
scan.set__angle_increment(sonar.angleStep());
const int size{params.at("image_size")};
if(size != static_cast<int>(image.step) ||
std::any_of(new_params.begin(), new_params.end(),
[](const auto ¶m){return param.get_name() == "angle_sector";}))
{
image.data.resize(size*size);
std::fill(image.data.begin(), image.data.end(), 0);
image.height = image.width = image.step = size;
}
sector.configure(sonar.samples(), size/2);
scan_threshold = params.at("scan_threshold");
}
void Ping360Sonar::publishEcho(const rclcpp::Time &now)
{
const auto [data, length] = sonar.intensities(); {}
echo.angle = sonar.currentAngle();
echo.intensities.resize(length);
std::copy(data, data+length, echo.intensities.begin());
echo.header.set__stamp(now);
echo_pub->publish(echo);
}
void Ping360Sonar::publishScan(const rclcpp::Time &now, bool end_turn)
{
// write latest reading
scan.ranges.resize(sonar.angleCount());
scan.intensities.resize(sonar.angleCount());
const auto angle{sonar.angleIndex()};
auto &this_range = scan.ranges[angle] = 0;
auto &this_intensity = scan.intensities[angle] = 0;
// find first (nearest) valid point in this direction
const auto [data, length] = sonar.intensities(); {}
for(int index=0; index<length; index++)
{
if(data[index] >= scan_threshold)
{
if(const auto range{sonar.rangeFrom(index)};
range >= scan.range_min && range < scan.range_max)
{
this_range = range;
this_intensity = data[index]/255.f;
break;
}
}
}
if(end_turn)
{
if(!sonar.fullScan())
{
if(sonar.angleStep() < 0)
{
// now going negative: scan was positive
scan.set__angle_max(sonar.angleMax());
scan.set__angle_min(sonar.angleMin());
}
else
{
// now going positive: scan was negative
scan.set__angle_max(sonar.angleMin());
scan.set__angle_min(sonar.angleMax());
}
scan.set__angle_increment(-sonar.angleStep());
scan.angle_max -= scan.angle_increment;
}
scan.header.set__stamp(now);
scan_pub->publish(scan);
}
}
void Ping360Sonar::refreshImage()
{
const auto [data, length] = sonar.intensities(); {}
if(length == 0) return;
const auto half_size{image.step/2};
sector.init(sonar.currentAngle(), fabs(sonar.angleStep()));
int x{}, y{}, index{};
while(sector.nextPoint(x, y, index))
{
if(index < length)
image.data[half_size-y + image.step*(half_size-x)] = data[index];
}
}
void Ping360Sonar::refresh()
{
const auto &[valid, end_turn] = sonar.read(); {}
if(!valid)
{
RCLCPP_WARN(get_logger(), "Cannot communicate with sonar");
return;
}
const auto now{this->now()};
if(publish_echo && echo_pub->get_subscription_count())
publishEcho(now);
if(publish_image)
refreshImage();
if(publish_scan && scan_pub->get_subscription_count())
publishScan(now, end_turn);
}
void Ping360Sonar::publishImage()
{
if(publish_image)
{
image.header.set__stamp(now());
image_pub.publish(image);
}
}
| 33.220217 | 140 | 0.679418 | [
"vector"
] |
3f3f621a179f781442dc47a90a5670aebcd83913 | 2,107 | cpp | C++ | CPP/ListNode/23/MergeKSortedLists3.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | CPP/ListNode/23/MergeKSortedLists3.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | CPP/ListNode/23/MergeKSortedLists3.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | //
// Created by Insomnia on 2018/6/23.
//
#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {};
};
ListNode *mergeTwoLists(ListNode *listOne, ListNode *listTwo) {
//考察21题目知识点
ListNode tempList(0);
ListNode *ptr = &tempList;
while (listOne && listTwo) {
if (listOne->val < listTwo->val) {
ptr->next = listOne;
listOne = listOne->next;
} else {
ptr->next = listTwo;
listTwo = listTwo->next;
}
ptr = ptr->next;
}
if (listOne) {
ptr->next = listOne;
}
if (listTwo) {
ptr->next = listTwo;
}
return tempList.next;
}
class Solution {
public:
ListNode *mergeKLists(std::vector<ListNode *> lists) {
if (lists.size() == 0) {
return NULL;
}
if (lists.size() == 1) {
return lists[0];
}
if (lists.size() == 2) {
return mergeTwoLists(lists[0], lists[1]);
}
int mid = lists.size() / 2;
std::vector<ListNode *> sub1List;
std::vector<ListNode *> sub2List;
for (int i = 0; i < mid; ++i) {
sub1List.push_back(lists[i]);
}
for (int j = mid; j < lists.size(); ++j) {
sub2List.push_back(lists[j]);
}
ListNode *l1 = mergeKLists(sub1List);
ListNode *l2 = mergeKLists(sub2List);
return mergeTwoLists(l1, l2);
};
};
int main() {
ListNode a(1);
ListNode b(4);
ListNode c(6);
ListNode d(0);
ListNode e(5);
ListNode f(7);
ListNode g(2);
ListNode h(3);
a.next = &b;
b.next = &c;
d.next = &e;
e.next = &f;
g.next = &h;
vector<ListNode *> lists;
lists.push_back(&a);
lists.push_back(&d);
lists.push_back(&g);
Solution sol;
ListNode *head = sol.mergeKLists(lists);
while (head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
return 0;
} | 18.646018 | 63 | 0.506882 | [
"vector"
] |
3f3f7cb7ff47e08421ec6221088286354ee8d00e | 15,185 | cc | C++ | plugins/experimental/lua/hook.cc | syucream/trafficserver | 144b2ef0a80c154ae132c9e73e94a5b4596c2b81 | [
"Apache-2.0"
] | 1 | 2016-04-29T08:11:46.000Z | 2016-04-29T08:11:46.000Z | plugins/experimental/lua/hook.cc | syucream/trafficserver | 144b2ef0a80c154ae132c9e73e94a5b4596c2b81 | [
"Apache-2.0"
] | null | null | null | plugins/experimental/lua/hook.cc | syucream/trafficserver | 144b2ef0a80c154ae132c9e73e94a5b4596c2b81 | [
"Apache-2.0"
] | null | null | null | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <ts/ts.h>
#include <ts/remap.h>
#include <string.h>
#include "lapi.h"
#include "lutil.h"
#include "hook.h"
#include "state.h"
#include <memory> // placement new
#include "ink_config.h"
#include "ink_defs.h"
const char *
HttpHookName(TSHttpHookID hookid)
{
static const char * names[TS_HTTP_LAST_HOOK] = {
"HTTP_READ_REQUEST_HDR_HOOK",
"HTTP_OS_DNS_HOOK",
"HTTP_SEND_REQUEST_HDR_HOOK",
"HTTP_READ_CACHE_HDR_HOOK",
"HTTP_READ_RESPONSE_HDR_HOOK",
"HTTP_SEND_RESPONSE_HDR_HOOK",
NULL, // XXX TS_HTTP_REQUEST_TRANSFORM_HOOK
NULL, // XXX TS_HTTP_RESPONSE_TRANSFORM_HOOK
NULL, // XXX HTTP_SELECT_ALT_HOOK
"HTTP_TXN_START_HOOK",
"HTTP_TXN_CLOSE_HOOK",
"HTTP_SSN_START_HOOK",
"HTTP_SSN_CLOSE_HOOK",
"HTTP_CACHE_LOOKUP_COMPLETE_HOOK",
"HTTP_PRE_REMAP_HOOK",
"HTTP_POST_REMAP_HOOK",
};
if (hookid >= 0 && hookid < static_cast<TSHttpHookID>(countof(names))) {
return names[hookid];
}
return NULL;
}
static bool
HookIsValid(int hookid)
{
if (hookid == TS_HTTP_REQUEST_TRANSFORM_HOOK || hookid == TS_HTTP_RESPONSE_TRANSFORM_HOOK) {
return false;
}
return hookid >= 0 && hookid < TS_HTTP_LAST_HOOK;
}
static void
LuaPushEventData(lua_State * lua, TSEvent event, void * edata)
{
switch (event) {
case TS_EVENT_HTTP_READ_REQUEST_HDR:
case TS_EVENT_HTTP_OS_DNS:
case TS_EVENT_HTTP_SEND_REQUEST_HDR:
case TS_EVENT_HTTP_READ_CACHE_HDR:
case TS_EVENT_HTTP_READ_RESPONSE_HDR:
case TS_EVENT_HTTP_SEND_RESPONSE_HDR:
case TS_EVENT_HTTP_SELECT_ALT:
case TS_EVENT_HTTP_TXN_START:
case TS_EVENT_HTTP_TXN_CLOSE:
case TS_EVENT_CACHE_LOOKUP_COMPLETE:
case TS_EVENT_HTTP_CACHE_LOOKUP_COMPLETE:
case TS_EVENT_HTTP_PRE_REMAP:
case TS_EVENT_HTTP_POST_REMAP:
LuaPushHttpTransaction(lua, (TSHttpTxn)edata);
break;
case TS_EVENT_HTTP_SSN_START:
case TS_EVENT_HTTP_SSN_CLOSE:
LuaPushHttpSession(lua, (TSHttpSsn)edata);
break;
default:
lua_pushnil(lua);
}
}
#if defined(INLINE_LUA_HOOK_REFERENCE)
typedef char __size_check[sizeof(this_type) == sizeof(void *) ? 0 : -1];
#endif
// For 64-bit pointers, we can inline the LuaHookReference, otherwise we need an extra malloc.
//
#if SIZEOF_VOID_POINTER >= 8
#define INLINE_LUA_HOOK_REFERENCE 1
#else
#undef INLINE_LUA_HOOK_REFERENCE
#endif
template <typename t1, typename t2>
struct inline_tuple
{
typedef t1 first_type;
typedef t2 second_type;
typedef inline_tuple<first_type, second_type> this_type;
union {
struct {
first_type first;
second_type second;
} s;
void * ptr;
} storage;
first_type& first() { return storage.s.first; }
second_type& second() { return storage.s.second; }
static void * allocate(const first_type first, const second_type second) {
#if defined(INLINE_LUA_HOOK_REFERENCE)
this_type obj;
obj.first() = first;
obj.second() = second;
return obj.storage.ptr;
#else
this_type * ptr = (this_type *)TSmalloc(sizeof(this_type));
ptr->first() = first;
ptr->second() = second;
return ptr;
#endif
}
static void free(void *ptr ATS_UNUSED) {
#if defined(INLINE_LUA_HOOK_REFERENCE)
// Nothing to do, because we never allocated.
#else
TSfree(ptr);
#endif
}
static this_type get(void * ptr) {
#if defined(INLINE_LUA_HOOK_REFERENCE)
this_type obj;
obj.storage.ptr = ptr;
return obj;
#else
return ptr ? *(this_type *)ptr : this_type();
#endif
}
};
// The per-ssn and per-txn argument mechanism stores a pointer, so it's NULL when not set. Unfortunately, 0 is a
// legitimate Lua reference value (all values except LUA_NOREF are legitimate), so we can't distinguish NULL from a 0
// reference. In 64-bit mode we have some extra bits and we can maintain the state, but in 32-bit mode, we need to
// allocate the LuaHookReference to have enough space to store the state.
typedef inline_tuple<int, bool> LuaHookReference;
static void *
LuaHttpObjectArgGet(TSHttpSsn ssn)
{
return TSHttpSsnArgGet(ssn, LuaHttpArgIndex);
}
static void *
LuaHttpObjectArgGet(TSHttpTxn txn)
{
return TSHttpTxnArgGet(txn, LuaHttpArgIndex);
}
static void
LuaHttpObjectArgSet(TSHttpSsn ssn, void * ptr)
{
return TSHttpSsnArgSet(ssn, LuaHttpArgIndex, ptr);
}
static void
LuaHttpObjectArgSet(TSHttpTxn txn, void * ptr)
{
return TSHttpTxnArgSet(txn, LuaHttpArgIndex, ptr);
}
template<typename T> static int
LuaGetArgReference(T ptr)
{
LuaHookReference href(LuaHookReference::get(LuaHttpObjectArgGet(ptr)));
// Only return the Lua ref if it was previously set.
return href.second() ? href.first() : LUA_NOREF;
}
template <typename T> void
LuaSetArgReference(T ptr, int ref)
{
LuaHookReference::free(LuaHttpObjectArgGet(ptr));
LuaHttpObjectArgSet(ptr, LuaHookReference::allocate(ref, true));
}
template <typename T> static void
LuaClearArgReference(T ptr)
{
LuaHookReference::free(LuaHttpObjectArgGet(ptr));
LuaHttpObjectArgSet(ptr, NULL);
}
// Force template instantiation of LuaSetArgReference().
template void LuaSetArgReference<TSHttpSsn>(TSHttpSsn ssn, int ref);
template void LuaSetArgReference<TSHttpTxn>(TSHttpTxn txn, int ref);
static void
LuaDemuxInvokeCallback(lua_State * lua, TSHttpHookID hookid, TSEvent event, void * edata, int ref)
{
int nitems = lua_gettop(lua);
// Push the callback table onto the top of the stack.
lua_rawgeti(lua, LUA_REGISTRYINDEX, ref);
// XXX If this is a global hook, we have a function reference. If it's a ssn or txn hook then we
// have a callback table reference. We need to make these the same, but not rught now ...
switch (lua_type(lua, -1)) {
case LUA_TFUNCTION:
// Nothing to do, the function we want to invoke is already on top of the stack.
break;
case LUA_TTABLE:
// Push the hookid onto the stack so we can use it to index the table (that is now at -2).
lua_pushinteger(lua, hookid);
TSAssert(lua_isnumber(lua, -1));
TSAssert(lua_istable(lua, -2));
// Index the callback table with the hookid to get the callback function for this hook.
lua_gettable(lua, -2);
break;
default:
LuaLogError("invalid callback reference type %s", ltypeof(lua, -1));
TSReleaseAssert(0);
}
// The item on the top of the stack *ought* to be the callback function. However when we register a
// cleanup function to release the callback reference (because the ssn or txn closes), then we won't
// have a function because there's nothing to do here.
if (!lua_isnil(lua, -1)) {
TSAssert(lua_isfunction(lua, -1));
lua_pushinteger(lua, event);
LuaPushEventData(lua, event, edata);
if (lua_pcall(lua, 2 /* nargs */, 0, 0) != 0) {
LuaLogDebug("hook callback failed: %s", lua_tostring(lua, -1));
lua_pop(lua, 1); // pop the error message
}
}
// If we left anything on the stack, pop it.
lua_pop(lua, lua_gettop(lua) - nitems);
}
int
LuaDemuxGlobalHook(TSHttpHookID hookid, TSCont cont, TSEvent event, void * edata)
{
instanceid_t instanceid = (uintptr_t)TSContDataGet(cont);
ScopedLuaState lstate(instanceid);
int ref = lstate->hookrefs[hookid];
LuaLogDebug("%u/%p %s event=%d edata=%p, ref=%d",
instanceid, lstate->lua,
HttpHookName(hookid), event, edata, ref);
if (ref == LUA_NOREF) {
LuaLogError("no Lua callback for hook %s", HttpHookName(hookid));
return TS_EVENT_ERROR;
}
LuaDemuxInvokeCallback(lstate->lua, hookid, event, edata, ref);
return TS_EVENT_NONE;
}
int
LuaDemuxTxnHook(TSHttpHookID hookid, TSCont cont, TSEvent event, void * edata)
{
int ref = LuaGetArgReference((TSHttpTxn)edata);
instanceid_t instanceid = (uintptr_t)TSContDataGet(cont);
ScopedLuaState lstate(instanceid);
LuaLogDebug("%s(%s) instanceid=%u event=%d edata=%p",
__func__, HttpHookName(hookid), instanceid, event, edata);
if (ref == LUA_NOREF) {
LuaLogError("no Lua callback for hook %s", HttpHookName(hookid));
return TS_EVENT_ERROR;
}
LuaDemuxInvokeCallback(lstate->lua, hookid, event, edata, ref);
if (event == TS_EVENT_HTTP_TXN_CLOSE) {
LuaLogDebug("unref event handler %d", ref);
luaL_unref(lstate->lua, LUA_REGISTRYINDEX, ref);
LuaClearArgReference((TSHttpTxn)edata);
}
return TS_EVENT_NONE;
}
int
LuaDemuxSsnHook(TSHttpHookID hookid, TSCont cont, TSEvent event, void * edata)
{
instanceid_t instanceid = (uintptr_t)TSContDataGet(cont);
ScopedLuaState lstate(instanceid);
TSHttpSsn ssn;
int ref;
// The edata might be a Txn or a Ssn, depending on the event type. If we get here, it's because we
// registered a callback on the Ssn, so we need to get back to the Ssn object in order to the the
// callback table reference ...
switch (event) {
case TS_EVENT_HTTP_SSN_START:
case TS_EVENT_HTTP_SSN_CLOSE:
ssn = (TSHttpSsn)edata;
break;
default:
ssn = TSHttpTxnSsnGet((TSHttpTxn)edata);
}
LuaLogDebug("%s(%s) instanceid=%u event=%d edata=%p",
__func__, HttpHookName(hookid), instanceid, event, edata);
ref = LuaGetArgReference(ssn);
if (ref == LUA_NOREF) {
LuaLogError("no Lua callback for hook %s", HttpHookName(hookid));
return TS_EVENT_ERROR;
}
LuaDemuxInvokeCallback(lstate->lua, hookid, event, edata, ref);
if (event == TS_EVENT_HTTP_SSN_CLOSE) {
LuaLogDebug("unref event handler %d", ref);
luaL_unref(lstate->lua, LUA_REGISTRYINDEX, ref);
LuaClearArgReference((TSHttpSsn)edata);
}
return TS_EVENT_NONE;
}
bool
LuaRegisterHttpHooks(lua_State * lua, void * obj, LuaHookAddFunction add, int hooks)
{
bool hooked_close = false;
const TSHttpHookID closehook = (add == LuaHttpSsnHookAdd ? TS_HTTP_SSN_CLOSE_HOOK : TS_HTTP_TXN_CLOSE_HOOK);
TSAssert(add == LuaHttpSsnHookAdd || add == LuaHttpTxnHookAdd);
// Push the hooks reference back onto the stack.
lua_rawgeti(lua, LUA_REGISTRYINDEX, hooks);
// The value on the top of the stack (index -1) MUST be the callback table.
TSAssert(lua_istable(lua, lua_gettop(lua)));
// Now we need our LuaThreadState to access the hook tables.
ScopedLuaState lstate(lua);
// Walk the table and register the hook for each entry.
lua_pushnil(lua); // Push the first key, makes the callback table index -2.
while (lua_next(lua, -2) != 0) {
TSHttpHookID hookid;
// uses 'key' (at index -2) and 'value' (at index -1).
// LuaLogDebug("key=%s value=%s\n", ltypeof(lua, -2), ltypeof(lua, -1));
// Now the key (index -2) and value (index -1) got pushed onto the stack. The key must be a hook ID and
// the value must be a callback function.
luaL_checktype(lua, -1, LUA_TFUNCTION);
hookid = (TSHttpHookID)luaL_checkint(lua, -2);
if (!HookIsValid(hookid)) {
LuaLogError("invalid Hook ID %d", hookid);
goto next;
}
if (hookid == closehook) {
hooked_close = true;
}
// At demux time, we need the hook ID and the table (or function) ref.
add(obj, lstate.instance(), hookid);
LuaLogDebug("registered callback table %d for event %s on object %p",
hooks, HttpHookName(hookid), obj);
next:
// Pop the value (index -1), leaving key as the new top (index -1).
lua_pop(lua, 1);
}
// we always need to hook the close because we keep a reference to the callback table and we need to
// release that reference when the object's lifetime ends.
if (!hooked_close) {
add(obj, lstate.instance(), closehook);
}
return true;
}
void
LuaHttpSsnHookAdd(void * ssn, const LuaPluginInstance * instance, TSHttpHookID hookid)
{
TSHttpSsnHookAdd((TSHttpSsn)ssn, hookid, instance->demux.ssn[hookid]);
}
void
LuaHttpTxnHookAdd(void * txn, const LuaPluginInstance * instance, TSHttpHookID hookid)
{
TSHttpTxnHookAdd((TSHttpTxn)txn, hookid, instance->demux.txn[hookid]);
}
static int
TSLuaHttpHookRegister(lua_State * lua)
{
TSHttpHookID hookid;
hookid = (TSHttpHookID)luaL_checkint(lua, 1);
luaL_checktype(lua, 2, LUA_TFUNCTION);
LuaLogDebug("registering hook %s (%d)", HttpHookName(hookid), (int)hookid);
if (hookid < 0 || hookid >= TS_HTTP_LAST_HOOK) {
LuaLogDebug("hook ID %d out of range", hookid);
return -1;
}
ScopedLuaState lstate(lua);
TSReleaseAssert(lstate);
// The lstate must match the current Lua state or something is seriously wrong.
TSReleaseAssert(lstate->lua == lua);
// Global hooks can only be registered once, but we load the Lua scripts in every thread. Check whether
// the hook has already been registered and ignore any double-registrations.
if (lstate->hookrefs[hookid] != LUA_NOREF) {
LuaLogDebug("ignoring double registration for %s hook", HttpHookName(hookid));
return 0;
}
// The callback function for the hook should be on the top of the stack now. Keep a reference
// to the callback function in the registry so we can pop it out later.
TSAssert(lua_type(lua, lua_gettop(lua)) == LUA_TFUNCTION);
lstate->hookrefs[hookid] = luaL_ref(lua, LUA_REGISTRYINDEX);
LuaLogDebug("%u/%p added hook ref %d for %s",
lstate->instance->instanceid, lua, lstate->hookrefs[hookid], HttpHookName(hookid));
// We need to atomically install this global hook. We snaffle the high bit to mark whether or
// not it has been installed.
if (((uintptr_t)lstate->instance->demux.global[hookid] & 0x01u) == 0) {
TSCont cont = (TSCont)((uintptr_t)lstate->instance->demux.global[hookid] | 0x01u);
if (__sync_bool_compare_and_swap(&lstate->instance->demux.global[hookid],
lstate->instance->demux.global[hookid], cont)) {
LuaLogDebug("installed continuation for %s", HttpHookName(hookid));
TSHttpHookAdd(hookid, (TSCont)((uintptr_t)cont & ~0x01u));
} else {
LuaLogDebug("lost hook creation race for %s", HttpHookName(hookid));
}
}
return 0;
}
static const luaL_Reg LUAEXPORTS[] =
{
{ "register", TSLuaHttpHookRegister },
{ NULL, NULL}
};
int
LuaHookApiInit(lua_State * lua)
{
LuaLogDebug("initializing TS Hook API");
lua_newtable(lua);
// Register functions in the "ts.hook" module.
luaL_register(lua, NULL, LUAEXPORTS);
for (unsigned i = 0; i < TS_HTTP_LAST_HOOK; ++i) {
if (HttpHookName((TSHttpHookID)i) != NULL) {
// Register named constants for each hook ID.
LuaSetConstantField(lua, HttpHookName((TSHttpHookID)i), i);
}
}
return 1;
}
| 30.128968 | 117 | 0.708001 | [
"object"
] |
3f46024e215d8df5acb84517539ed1f14740af06 | 13,694 | cpp | C++ | src/librrl/test/audio_signal_flow_checking.cpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | 17 | 2019-03-12T14:52:22.000Z | 2021-11-09T01:16:23.000Z | src/librrl/test/audio_signal_flow_checking.cpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | null | null | null | src/librrl/test/audio_signal_flow_checking.cpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | 2 | 2019-08-11T12:53:07.000Z | 2021-06-22T10:08:08.000Z | /* Copyright Institue of Sound and Vibration Research - All rights reserved. */
#include <librrl/audio_signal_flow.hpp>
#include <librrl/integrity_checking.hpp>
#include <libvisr/audio_input.hpp>
#include <libvisr/audio_output.hpp>
#include <libvisr/atomic_component.hpp>
#include <libvisr/composite_component.hpp>
#include <libvisr/signal_flow_context.hpp>
#include <boost/test/unit_test.hpp>
#include <ciso646>
#include <cstddef>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
namespace visr
{
namespace rrl
{
namespace test
{
namespace // unnamed
{
static std::size_t const audioWidth = 4;
/**
* Object to hold a name constructed of a string and a number
*/
struct numberedItem
{
public:
explicit numberedItem( std::string const & base, std::size_t index)
{
std::stringstream res;
res << base << "_" << index;
mVal = res.str();
}
/**
* Implicit conversion to char const *
*/
operator char const*() const
{
return mVal.c_str();
}
private:
std::string mVal;
};
class MyAtom: public AtomicComponent
{
public:
MyAtom( SignalFlowContext & context, char const * componentName, CompositeComponent * parent,
std::size_t numInputs, std::size_t numOutputs)
: AtomicComponent( context, componentName, parent )
{
for( std::size_t portIdx( 0 ); portIdx < numInputs; ++portIdx )
{
mInputs.push_back( std::unique_ptr<AudioInput>( new AudioInput( numberedItem( "in", portIdx ), *this, audioWidth ) ) );
}
for( std::size_t portIdx( 0 ); portIdx < numOutputs; ++portIdx )
{
mOutputs.push_back( std::unique_ptr<AudioOutput>( new AudioOutput( numberedItem( "out", portIdx ), *this, audioWidth ) ) );
}
}
void process() override {}
private:
std::vector< std::unique_ptr<AudioInput> > mInputs;
std::vector<std::unique_ptr<AudioOutput> > mOutputs;
};
class MyComposite: public CompositeComponent
{
public:
MyComposite( SignalFlowContext & context, char const * componentName, CompositeComponent * parent,
std::size_t numInputs, std::size_t numOutputs )
: CompositeComponent( context, componentName, parent )
, mAtom( context, "SecondLevelAtom", this, numInputs, numOutputs )
{
ChannelRange const indices( 0, audioWidth );
for( std::size_t portIdx( 0 ); portIdx < numInputs; ++portIdx )
{
mExtInputs.push_back( std::unique_ptr<AudioInput>( new AudioInput( numberedItem( "placeholder_in", portIdx ), *this ) ) );
mExtInputs[portIdx]->setWidth( audioWidth );
audioConnection( "this", numberedItem( "placeholder_in", portIdx ), indices,
"SecondLevelAtom", numberedItem( "in", portIdx ), indices );
}
for( std::size_t portIdx( 0 ); portIdx < numOutputs; ++portIdx )
{
mExtOutputs.push_back( std::unique_ptr<AudioOutput>( new AudioOutput( numberedItem( "placeholder_out", portIdx ), *this ) ) );
mExtOutputs[portIdx]->setWidth( audioWidth );
audioConnection( "SecondLevelAtom", numberedItem( "out", portIdx ), indices,
"this", numberedItem( "placeholder_out", portIdx ), indices );
}
}
private:
MyAtom mAtom;
std::vector< std::unique_ptr<AudioInput> > mExtInputs;
std::vector<std::unique_ptr<AudioOutput> > mExtOutputs;
};
class MyRecursiveComposite: public CompositeComponent
{
public:
MyRecursiveComposite( SignalFlowContext & context, char const * componentName, CompositeComponent * parent,
std::size_t numInputs, std::size_t numOutputs, std::size_t recursionCount, bool insertAtom )
: CompositeComponent( context, componentName, parent )
{
if( (not insertAtom) and( numInputs != numOutputs ) )
{
throw std::invalid_argument( "If \"insertAtom\" is false, then the number of inputs must match the number of outputs." );
}
ChannelRange const indices( 0, audioWidth, 1 );
std::stringstream childNameStr;
if( (recursionCount > 0) or insertAtom )
{
if( recursionCount > 0 )
{
childNameStr << "level" << recursionCount-1 << "composite";
mChild.reset( new MyRecursiveComposite( context, childNameStr.str().c_str(), this, numInputs, numOutputs, recursionCount - 1, insertAtom ) );
for( std::size_t portIdx( 0 ); portIdx < numInputs; ++portIdx )
{
mExtInputs.push_back( std::unique_ptr<AudioInput>( new AudioInput( numberedItem( "placeholder_in", portIdx ), *this ) ) );
mExtInputs[portIdx]->setWidth( audioWidth );
audioConnection( "this", numberedItem( "placeholder_in", portIdx ), indices,
childNameStr.str( ).c_str( ), numberedItem( "placeholder_in", portIdx ), indices );
}
for( std::size_t portIdx( 0 ); portIdx < numOutputs; ++portIdx )
{
mExtOutputs.push_back( std::unique_ptr<AudioOutput>( new AudioOutput( numberedItem( "placeholder_out", portIdx ), *this ) ) );
mExtOutputs[portIdx]->setWidth( audioWidth );
audioConnection( childNameStr.str( ).c_str( ), numberedItem( "placeholder_out", portIdx ), indices,
"this", numberedItem( "placeholder_out", portIdx ), indices );
}
}
else
{
childNameStr << "level" << recursionCount << "atom";
mChild.reset( new MyAtom( context, childNameStr.str( ).c_str( ), this, numInputs, numOutputs ) );
for( std::size_t portIdx( 0 ); portIdx < numInputs; ++portIdx )
{
mExtInputs.push_back( std::unique_ptr<AudioInput>( new AudioInput( numberedItem( "placeholder_in", portIdx ), *this ) ) );
mExtInputs[portIdx]->setWidth( audioWidth );
audioConnection( "this", numberedItem( "placeholder_in", portIdx ), indices,
childNameStr.str( ).c_str( ), numberedItem( "in", portIdx ), indices );
}
for( std::size_t portIdx( 0 ); portIdx < numOutputs; ++portIdx )
{
mExtOutputs.push_back( std::unique_ptr<AudioOutput>( new AudioOutput( numberedItem( "placeholder_out", portIdx ), *this ) ) );
mExtOutputs[portIdx]->setWidth( audioWidth );
audioConnection( childNameStr.str( ).c_str(), numberedItem( "out", portIdx ), indices,
"this", numberedItem( "placeholder_out", portIdx ), indices );
}
}
}
else // no atom at the lowest level, just connect the composite input to the output
{
for( std::size_t portIdx( 0 ); portIdx < numInputs; ++portIdx )
{
mExtInputs.push_back( std::unique_ptr<AudioInput>( new AudioInput( numberedItem( "placeholder_in", portIdx ), *this ) ) );
mExtOutputs.push_back( std::unique_ptr<AudioOutput>( new AudioOutput( numberedItem( "placeholder_out", portIdx ), *this ) ) );
mExtInputs[portIdx]->setWidth( audioWidth );
mExtOutputs[portIdx]->setWidth( audioWidth );
audioConnection( "this", numberedItem( "placeholder_in", portIdx ), indices,
"this", numberedItem( "placeholder_out", portIdx ), indices );
}
}
}
private:
std::unique_ptr<Component> mChild;
std::vector< std::unique_ptr<AudioInput> > mExtInputs;
std::vector<std::unique_ptr<AudioOutput> > mExtOutputs;
};
class MyTopLevel: public CompositeComponent
{
public:
MyTopLevel( SignalFlowContext & context, char const * componentName, CompositeComponent * parent,
std::size_t numInputs, std::size_t numOutputs )
: CompositeComponent( context, componentName, parent )
, mComposite1( context, "FirstLevelComposite", this, numInputs, numOutputs )
, mAtomTopLevel( context, "FirstLevelAtom", this, numOutputs, numOutputs )
{
ChannelRange const indices( 0, audioWidth, 1 );
for( std::size_t portIdx( 0 ); portIdx < numInputs; ++portIdx )
{
mExtInputs.push_back( std::unique_ptr<AudioInput>( new AudioInput( numberedItem( "ext_in", portIdx ), *this ) ) );
mExtInputs[portIdx]->setWidth( audioWidth );
audioConnection( "this", numberedItem( "ext_in", portIdx ), indices,
"FirstLevelComposite", numberedItem( "placeholder_in", portIdx ), indices );
}
for( std::size_t portIdx( 0 ); portIdx < numOutputs; ++portIdx )
{
mExtOutputs.push_back( std::unique_ptr<AudioOutput>( new AudioOutput( numberedItem( "ext_out", portIdx ), *this ) ) );
mExtOutputs[portIdx]->setWidth( audioWidth );
audioConnection( "FirstLevelComposite", numberedItem( "placeholder_out", portIdx ), indices,
"FirstLevelAtom", numberedItem( "in", portIdx ), indices );
audioConnection( "FirstLevelAtom", numberedItem( "out", portIdx ), indices,
"this", numberedItem( "ext_out", portIdx ), indices );
}
}
private:
MyComposite mComposite1;
MyAtom mAtomTopLevel;
std::vector< std::unique_ptr<AudioInput> > mExtInputs;
std::vector<std::unique_ptr<AudioOutput> > mExtOutputs;
};
class MyTopLevelRecursive: public CompositeComponent
{
public:
MyTopLevelRecursive( SignalFlowContext & context, char const * componentName, CompositeComponent * parent,
std::size_t numInputs, std::size_t numOutputs, std::size_t recursionLevels, bool insertAtom )
: CompositeComponent( context, componentName, parent )
, mComposite( context, "FirstLevelComposite", this, numInputs, numOutputs, recursionLevels, insertAtom )
{
ChannelRange const indices( 0, audioWidth );
for( std::size_t portIdx( 0 ); portIdx < numInputs; ++portIdx )
{
mExtInputs.push_back( std::unique_ptr<AudioInput>( new AudioInput( numberedItem( "ext_in", portIdx ), *this ) ) );
mExtInputs[portIdx]->setWidth( audioWidth );
audioConnection( "this", numberedItem( "ext_in", portIdx ), indices,
"FirstLevelComposite", numberedItem( "placeholder_in", portIdx ), indices );
}
for( std::size_t portIdx( 0 ); portIdx < numOutputs; ++portIdx )
{
mExtOutputs.push_back( std::unique_ptr<AudioOutput>( new AudioOutput( numberedItem( "ext_out", portIdx ), *this ) ) );
mExtOutputs[portIdx]->setWidth( audioWidth );
audioConnection( "FirstLevelComposite", numberedItem( "placeholder_out", portIdx ), indices,
"this", numberedItem( "ext_out", portIdx ), indices );
}
}
private:
MyRecursiveComposite mComposite;
std::vector< std::unique_ptr<AudioInput> > mExtInputs;
std::vector<std::unique_ptr<AudioOutput> > mExtOutputs;
};
} // namespace unnamed
BOOST_AUTO_TEST_CASE( CheckAtomicComponent )
{
SignalFlowContext context( 128, 48000 );
std::size_t numInputs = 2;
std::size_t numOutputs = 4;
MyAtom atomicComp( context, "", nullptr, numInputs, numOutputs );
std::stringstream msg;
bool const res = checkConnectionIntegrity( atomicComp, true, msg );
BOOST_CHECK( res and msg.str().empty() );
rrl::AudioSignalFlow flow( atomicComp );
// Perform basic tests of the external I/O interface
BOOST_CHECK( flow.numberOfAudioCapturePorts() == numInputs );
BOOST_CHECK( flow.numberOfAudioPlaybackPorts() == numOutputs );
BOOST_CHECK( flow.numberOfCaptureChannels() == audioWidth * numInputs );
BOOST_CHECK( flow.numberOfPlaybackChannels() == audioWidth * numOutputs );
}
BOOST_AUTO_TEST_CASE( CheckCompositeComponent )
{
SignalFlowContext context( 128, 48000 );
MyComposite composite( context, "top", nullptr, 2, 3 );
std::stringstream msg;
bool const res = checkConnectionIntegrity( composite, true, msg );
BOOST_CHECK( res and msg.str().empty() );
if( not res )
{
std::cout << "Error messages:\n" << msg.str() << std::endl;
}
rrl::AudioSignalFlow flow( composite );
// Perform basic tests of the external I/O interface
}
BOOST_AUTO_TEST_CASE( CheckTwoLevelCompositeComponent )
{
SignalFlowContext context( 1024, 48000 );
MyTopLevel composite( context, "", nullptr, 1, 1 );
std::stringstream msg;
bool const res = checkConnectionIntegrity( composite, true, msg );
if( not res )
{
std::cout << "Connection check failed, message: " << msg.str() << std::endl;
}
BOOST_CHECK( res and msg.str().empty() );
BOOST_CHECK_NO_THROW( rrl::AudioSignalFlow flow( composite ) );
// Perform basic tests of the external I/O interface
}
/**
* Check the instantiation of a recursive hierachical signal flow that hast a composite component at the lowest level which
* interconnect the input to the output. The flattening algorithms results in a direct interconnection of the top-level capture
* to the top-level playback port.
*/
BOOST_AUTO_TEST_CASE( CheckRecursiveCompositeComponentNoAtom )
{
SignalFlowContext context( 1024, 48000 );
std::size_t const recursionLimit = 1;
bool const insertAtom = false;
MyTopLevelRecursive composite( context, "", nullptr, 1, 1, recursionLimit, insertAtom );
std::stringstream msg;
bool const res = checkConnectionIntegrity( composite, true, msg );
BOOST_CHECK( res and msg.str().empty() );
rrl::AudioSignalFlow flow( composite );
// Perform basic tests of the external I/O interface
BOOST_CHECK( flow.numberOfAudioCapturePorts() == 1 );
}
/**
* Check the instantiation of a recursive hierachical signal flow that instantiates a single component
* at the lowest level and interconnects the inputs and outputs through all composite levels.
*/
BOOST_AUTO_TEST_CASE( CheckRecursiveCompositeComponent )
{
SignalFlowContext context( 1024, 48000 );
std::size_t const recursionLimit = 3;
bool const insertAtom = true;
MyTopLevelRecursive composite( context, "", nullptr, 3, 4, recursionLimit, insertAtom );
rrl::AudioSignalFlow flow( composite );
// Perform basic tests of the external I/O interface
}
} // namespace test
} // namespace rrl
} // namespace visr
| 36.811828 | 149 | 0.682708 | [
"object",
"vector"
] |
3f55de7d62c91f69be146dc98590daa97ed2c6d7 | 1,992 | cc | C++ | CPP/muduo/testsuite/datetime/benchmark.cc | ctimbai/coding-demo | 96e2bdc1716a088070d9994c86b36c8dfe80a684 | [
"Apache-2.0"
] | null | null | null | CPP/muduo/testsuite/datetime/benchmark.cc | ctimbai/coding-demo | 96e2bdc1716a088070d9994c86b36c8dfe80a684 | [
"Apache-2.0"
] | null | null | null | CPP/muduo/testsuite/datetime/benchmark.cc | ctimbai/coding-demo | 96e2bdc1716a088070d9994c86b36c8dfe80a684 | [
"Apache-2.0"
] | null | null | null | #include "datetime/TimerQueue.h"
#include "datetime/TimerWheel.h"
#include "reactor/EventLoop.h"
#include "logging/Logging.h"
#include <chrono>
#include <random>
#include <iostream>
using namespace libcpp;
const int k = 1000 * 1000;
const double unit = 0.01;
const double base = 3600;
std::vector<int> distribution;
std::unique_ptr<TimerQueue> tq;
std::unique_ptr<TimerWheel> tw;
std::vector<TimerId> timers(k, TimerId());
void func() {}
void benchTimerQueue()
{
TimeStamp current(TimeStamp::now());
auto begin = std::chrono::high_resolution_clock::now();
for (int i = 0; i < k; ++i) {
timers[i] = tq->addTimer(func,
addTime(current, base + distribution[i] * unit), 0);
}
for (int i = 0; i < k; ++i) {
tq->cancel(timers[i]);
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "TimerQueue insert/delete " << k << " times: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>
(end - begin).count() << "ns" << std::endl;
}
void benchTimerWheel()
{
TimeStamp current(TimeStamp::now());
auto begin = std::chrono::high_resolution_clock::now();
for (int i = 0; i < k; ++i) {
timers[i] = tw->addTimer(func,
addTime(current, base + distribution[i] * unit), 0);
}
for (int i = 0; i < k; ++i) {
tw->cancel(timers[i]);
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "TimerWheel insert/delete " << k << " times: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>
(end - begin).count() << "ns" << std::endl;
}
int main()
{
EventLoop loop(0);
/* generate timer task distribution */
std::default_random_engine generator;
std::uniform_int_distribution<int> dist(0, k);
for (int i = 0; i < k; ++i) {
distribution.push_back(dist(generator));
}
/* generate TimerQueue and TimerWheel */
tq.reset(new TimerQueue(&loop));
tw.reset(new TimerWheel(&loop, unit, 100));
benchTimerQueue();
benchTimerWheel();
} | 25.87013 | 64 | 0.627008 | [
"vector"
] |
3f5d785f461e0a4557f4db3a781910b90f184799 | 18,634 | hpp | C++ | cpp/oneapi/dal/algo/decision_forest/test/fixture.hpp | dmitrii-kriukov/oneDAL | e962159893ffabdcc601f999f998ce2373c3ce71 | [
"Apache-2.0"
] | 169 | 2020-03-30T09:13:05.000Z | 2022-03-15T11:12:36.000Z | cpp/oneapi/dal/algo/decision_forest/test/fixture.hpp | dmitrii-kriukov/oneDAL | e962159893ffabdcc601f999f998ce2373c3ce71 | [
"Apache-2.0"
] | 1,198 | 2020-03-24T17:26:18.000Z | 2022-03-31T08:06:15.000Z | cpp/oneapi/dal/algo/decision_forest/test/fixture.hpp | dmitrii-kriukov/oneDAL | e962159893ffabdcc601f999f998ce2373c3ce71 | [
"Apache-2.0"
] | 75 | 2020-03-30T11:39:58.000Z | 2022-03-26T05:16:20.000Z | /*******************************************************************************
* Copyright 2020-2021 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "oneapi/dal/algo/decision_forest/train.hpp"
#include "oneapi/dal/algo/decision_forest/infer.hpp"
#include "oneapi/dal/test/engine/fixtures.hpp"
#include "oneapi/dal/test/engine/math.hpp"
#include <list>
#define sizeofa(p) sizeof(p) / sizeof(*p)
namespace oneapi::dal::decision_forest::test {
namespace df = dal::decision_forest;
namespace te = dal::test::engine;
template <typename T>
struct checker_info {
typedef T (*checker_func)(const dal::v1::table& infer_responses,
const dal::v1::table& ground_truth);
std::string name;
checker_func check;
double required_accuracy;
};
template <typename TestType, typename Derived>
class df_test : public te::crtp_algo_fixture<TestType, Derived> {
public:
using base_t = te::crtp_algo_fixture<TestType, Derived>;
using float_t = std::tuple_element_t<0, TestType>;
using method_t = std::tuple_element_t<1, TestType>;
using task_t = std::tuple_element_t<2, TestType>;
using descriptor_t = df::descriptor<float_t, method_t, task_t>;
using train_input_t = df::train_input<task_t>;
using train_result_t = df::train_result<task_t>;
using infer_input_t = df::infer_input<task_t>;
using infer_result_t = df::infer_result<task_t>;
using model_t = df::model<task_t>;
using Float = std::tuple_element_t<0, TestType>;
using Method = std::tuple_element_t<1, TestType>;
using Task = std::tuple_element_t<2, TestType>;
bool is_gpu() {
return this->get_policy().is_gpu();
}
bool not_available_on_device() {
constexpr bool is_dense = std::is_same_v<Method, decision_forest::method::dense>;
return this->get_policy().is_gpu() && is_dense;
}
auto get_default_descriptor() {
return df::descriptor<Float, Method, Task>{};
}
auto get_cls_dataframe_base() {
constexpr double required_accuracy = 0.95;
constexpr std::int64_t row_count_train = 6;
constexpr std::int64_t row_count_test = 3;
constexpr std::int64_t column_count = 3;
constexpr std::int64_t class_count = 2;
static const float train_arr[] = { -2.f, -1.f, 0.f, -1.f, -1.f, 0.f, -1.f, -2.f, 0.f,
+1.f, +1.f, 1.f, +1.f, +2.f, 1.f, +2.f, +1.f, 1.f };
static const float test_arr[] = { -1.f, -1.f, 0.f, +2.f, +2.f, 1.f, +3.f, +2.f, 1.f };
te::dataframe data{ array<float>::wrap(train_arr, row_count_train * column_count),
row_count_train,
column_count };
te::dataframe data_test{ array<float>::wrap(test_arr, row_count_test * column_count),
row_count_test,
column_count };
const std::list<checker_info<double>> checker_list = { this->get_cls_checker(
1 - required_accuracy) };
return std::make_tuple(data, data_test, class_count, checker_list);
}
auto get_cls_dataframe(std::string ds_name, double required_accuracy) {
const te::dataframe data =
GENERATE_DATAFRAME(te::dataframe_builder{ ds_name + ".train.csv" });
const te::dataframe data_test =
GENERATE_DATAFRAME(te::dataframe_builder{ ds_name + ".test.csv" });
const std::list<checker_info<double>> checker_list = { this->get_cls_checker(
1 - required_accuracy) };
return std::make_tuple(data, data_test, checker_list);
}
auto get_reg_dataframe_base() {
const double required_mse = 0.05;
constexpr std::int64_t row_count_train = 10;
constexpr std::int64_t row_count_test = 5;
constexpr std::int64_t column_count = 3;
static const float train_arr[] = {
0.1f, 0.25f, 0.0079f, 0.15f, 0.35f, 0.0160f, 0.25f, 0.55f,
0.0407f, 0.3f, 0.65f, 0.0573f, 0.4f, 0.85f, 0.0989f, 0.45f,
0.95f, 0.1240f, 0.55f, 1.15f, 0.1827f, 0.6f, 1.25f, 0.2163f,
0.7f, 1.45f, 0.2919f, 0.8f, 1.65f, 0.3789f,
};
static const float test_arr[] = {
0.2f, 0.45f, 0.0269f, 0.35f, 0.75f, 0.0767f, 0.5f, 1.05f,
0.1519f, 0.65f, 1.35f, 0.2527f, 0.75f, 1.55f, 0.3340f,
};
te::dataframe data{ array<float>::wrap(train_arr, row_count_train * column_count),
row_count_train,
column_count };
te::dataframe data_test{ array<float>::wrap(test_arr, row_count_test * column_count),
row_count_test,
column_count };
const std::list<checker_info<double>> checker_list = { this->get_mse_checker(
required_mse) };
return std::make_tuple(data, data_test, checker_list);
}
auto get_reg_dataframe(std::string ds_name, double required_mse, double required_mae) {
const te::dataframe data =
GENERATE_DATAFRAME(te::dataframe_builder{ ds_name + ".train.csv" });
const te::dataframe data_test =
GENERATE_DATAFRAME(te::dataframe_builder{ ds_name + ".test.csv" });
const std::list<checker_info<double>> checker_list = { this->get_mse_checker(required_mse),
this->get_mae_checker(
required_mae) };
return std::make_tuple(data, data_test, checker_list);
}
auto train_base_checks(const df::descriptor<Float, Method, Task>& desc,
const te::dataframe& data,
const te::table_id& data_table_id) {
const auto x = data.get_table(data_table_id, range(0, -1));
const auto y = data.get_table(data_table_id,
range(data.get_column_count() - 1, data.get_column_count()));
INFO("run training");
const auto train_result = this->train(desc, x, y);
check_train_shapes(desc, data, train_result);
return train_result;
}
auto infer_base_checks(const df::descriptor<Float, Method, Task>& desc,
const te::dataframe& data,
const te::table_id& data_table_id,
const df::model<Task>& model,
const std::list<checker_info<double>>& checker_list) {
const auto x_test = data.get_table(data_table_id, range(0, -1));
const auto y_test =
data.get_table(data_table_id,
range(data.get_column_count() - 1, data.get_column_count()));
INFO("run inference");
const auto infer_result = this->infer(desc, model, x_test);
check_infer_shapes(desc, data, infer_result);
INFO("check if infer accuracy is expected")
for (auto ch : checker_list) {
CAPTURE(desc.get_features_per_node());
CAPTURE(desc.get_max_tree_depth());
CAPTURE(ch.name);
REQUIRE(ch.check(infer_result.get_responses(), y_test) < ch.required_accuracy + eps);
}
return infer_result;
}
template <typename Checker>
void model_traverse_check(const df::model<Task>& model, Checker&& check) {
INFO("run model check");
for (std::int64_t tree_idx = 0; tree_idx < model.get_tree_count(); ++tree_idx) {
CAPTURE(tree_idx);
model.traverse_depth_first(tree_idx, std::forward<Checker>(check));
}
}
void check_trees_node_min_sample_count(const df::model<Task>& model,
std::int64_t min_observations_in_leaf_node) {
INFO("run check trees' node min sample count");
model_traverse_check(model, [&](const node_info<Task>& node) {
CAPTURE(node.get_level());
REQUIRE(node.get_sample_count() >= min_observations_in_leaf_node);
return true;
});
}
void check_train_shapes(const df::descriptor<Float, Method, Task>& desc,
const te::dataframe& data,
const df::train_result<Task>& result) {
constexpr bool is_cls = std::is_same_v<Task, decision_forest::task::classification>;
INFO("check if model shape is expected")
REQUIRE(result.get_model().get_tree_count() == desc.get_tree_count());
if constexpr (is_cls) {
REQUIRE(result.get_model().get_class_count() == desc.get_class_count());
}
if (check_mask_flag(desc.get_error_metric_mode(), error_metric_mode::out_of_bag_error)) {
INFO("check if oob error shape is expected")
REQUIRE(result.get_oob_err().has_data());
REQUIRE(result.get_oob_err().get_row_count() == 1);
REQUIRE(result.get_oob_err().get_column_count() == 1);
}
if (check_mask_flag(desc.get_error_metric_mode(),
error_metric_mode::out_of_bag_error_per_observation)) {
INFO("check if oob error per observation shape is expected")
REQUIRE(result.get_oob_err_per_observation().has_data());
REQUIRE(result.get_oob_err_per_observation().get_row_count() == data.get_row_count());
REQUIRE(result.get_oob_err_per_observation().get_column_count() == 1);
}
if (variable_importance_mode::none != desc.get_variable_importance_mode()) {
INFO("check if variable improtance shape is expected")
REQUIRE(result.get_var_importance().has_data());
REQUIRE(result.get_var_importance().get_row_count() == 1);
REQUIRE(result.get_var_importance().get_column_count() == data.get_column_count() - 1);
}
}
void check_infer_shapes(const df::descriptor<Float, Method, Task>& desc,
const te::dataframe& data,
const df::infer_result<Task>& result) {
constexpr bool is_cls = std::is_same_v<Task, decision_forest::task::classification>;
if constexpr (is_cls) {
if (check_mask_flag(desc.get_infer_mode(), infer_mode::class_responses)) {
INFO("check if infer responses shape is expected")
REQUIRE(result.get_responses().has_data());
REQUIRE(result.get_responses().get_row_count() == data.get_row_count());
REQUIRE(result.get_responses().get_column_count() == 1);
}
if (check_mask_flag(desc.get_infer_mode(), infer_mode::class_probabilities)) {
INFO("check if infer probabilities shape is expected")
REQUIRE(result.get_probabilities().has_data());
REQUIRE(result.get_probabilities().get_row_count() == data.get_row_count());
REQUIRE(result.get_probabilities().get_column_count() == desc.get_class_count());
}
}
else {
INFO("check if infer responses shape is expected")
REQUIRE(result.get_responses().has_data());
REQUIRE(result.get_responses().get_row_count() == data.get_row_count());
REQUIRE(result.get_responses().get_column_count() == 1);
}
}
void check_var_importance_matches_required(const df::descriptor<Float, Method, Task>& desc,
const df::train_result<Task>& train_result,
const te::dataframe& var_imp_data,
const te::table_id& data_table_id,
double accuracy_threshold) {
if (variable_importance_mode::none != desc.get_variable_importance_mode()) {
INFO("check if match of variable importance vs required one is expected")
const auto required_var_imp = var_imp_data.get_table(data_table_id);
std::int64_t row_ind = 0;
switch (desc.get_variable_importance_mode()) {
case variable_importance_mode::mda_raw: row_ind = 1; break;
case variable_importance_mode::mda_scaled: row_ind = 2; break;
default: row_ind = 0; break;
};
const auto var_imp_val =
dal::row_accessor<const Float>(train_result.get_var_importance()).pull();
const auto required_var_imp_val =
dal::row_accessor<const float>(required_var_imp).pull({ row_ind, row_ind + 1 });
for (std::int32_t i = 0; i < var_imp_val.get_count(); i++) {
if (required_var_imp_val[i] > 0.0) {
REQUIRE(((required_var_imp_val[i] - var_imp_val[i]) / required_var_imp_val[i]) <
accuracy_threshold + eps);
}
}
}
}
void check_oob_err_matches_required(const df::descriptor<Float, Method, Task>& desc,
const df::train_result<Task>& train_result,
double required_oob_error,
double accuracy_threshold) {
if (check_mask_flag(desc.get_error_metric_mode(), error_metric_mode::out_of_bag_error)) {
INFO("check if match of oob error vs required one is expected")
const auto oob_err_val =
dal::row_accessor<const double>(train_result.get_oob_err()).pull();
if (required_oob_error > 0.0) {
REQUIRE(std::abs((required_oob_error - oob_err_val[0]) / required_oob_error) <
accuracy_threshold + eps);
}
}
}
void check_oob_err_matches_oob_err_per_observation(
const df::descriptor<Float, Method, Task>& desc,
const df::train_result<Task>& train_result,
double accuracy_threshold) {
if (check_mask_flag(desc.get_error_metric_mode(),
error_metric_mode::out_of_bag_error_per_observation)) {
INFO("check if match of oob error vs cumulative oob error per observation is expected")
const auto oob_err_val =
dal::row_accessor<const double>(train_result.get_oob_err()).pull();
const auto oob_err_per_obs_arr =
dal::row_accessor<const double>(train_result.get_oob_err_per_observation()).pull();
std::int64_t oob_err_obs_count = 0;
double ref_oob_err = 0.0;
for (std::int64_t i = 0; i < oob_err_per_obs_arr.get_count(); i++) {
if (oob_err_per_obs_arr[i] >= 0.0) {
oob_err_obs_count++;
ref_oob_err += oob_err_per_obs_arr[i];
}
else {
REQUIRE(oob_err_per_obs_arr[i] >= -1.0);
}
}
if (oob_err_val[0] > 0.0) {
REQUIRE(((oob_err_val[0] - ref_oob_err) / oob_err_val[0]) <
accuracy_threshold + eps);
}
}
}
checker_info<double> get_cls_checker(double required_accuracy) {
return checker_info<double>{ "cls_checker",
&calculate_classification_error,
required_accuracy };
}
checker_info<double> get_mse_checker(double required_accuracy) {
return checker_info<double>{ "mse_checker", &calculate_mse, required_accuracy };
}
checker_info<double> get_mae_checker(double required_accuracy) {
return checker_info<double>{ "mae_checker", &calculate_mae, required_accuracy };
}
static double calculate_classification_error(const dal::table& infer_responses,
const dal::table& ground_truth) {
const auto responses = dal::row_accessor<const Float>(infer_responses).pull();
const auto truth_responses = dal::row_accessor<const Float>(ground_truth).pull();
std::int64_t incorrect_response_count = 0;
for (std::int64_t i = 0; i < responses.get_count(); i++) {
incorrect_response_count +=
(static_cast<int>(responses[i]) != static_cast<int>(truth_responses[i]));
}
return static_cast<double>(incorrect_response_count) / responses.get_count();
}
static double calculate_mse(const dal::v1::table& infer_responses,
const dal::v1::table& ground_truth) {
double mean = 0.0;
const auto responses = dal::row_accessor<const Float>(infer_responses).pull();
const auto truth_responses = dal::row_accessor<const Float>(ground_truth).pull();
for (std::int64_t i = 0; i < responses.get_count(); i++) {
mean += (responses[i] - truth_responses[i]) * (responses[i] - truth_responses[i]);
}
return mean / responses.get_count();
}
static double calculate_mae(const dal::v1::table& infer_responses,
const dal::v1::table& ground_truth) {
double mae = 0.0;
const auto responses = dal::row_accessor<const Float>(infer_responses).pull();
const auto truth_responses = dal::row_accessor<const Float>(ground_truth).pull();
for (std::int64_t i = 0; i < responses.get_count(); i++) {
mae += std::abs(responses[i] - truth_responses[i]);
}
return mae / responses.get_count();
}
private:
double eps = 1e-10;
};
struct dataset_info {
std::string name;
std::int64_t class_count = 0;
std::int64_t categ_feature_count = 0;
const std::int64_t* categ_feature_list = nullptr;
};
struct workload_cls {
dataset_info ds_info;
double required_accuracy = 0.0;
};
struct workload_reg {
dataset_info ds_info;
double required_mse = 0.0;
double required_mae = 0.0;
};
} // namespace oneapi::dal::decision_forest::test
| 44.578947 | 100 | 0.592251 | [
"shape",
"model"
] |
3f6434db5ac6fc116fada80768b8e1b66edb518b | 11,638 | hh | C++ | includes/rend3d.hh | hisahi/hiemalia | bb5370d6ef0b2480b3b8f563d292ddfab7c0f6e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | includes/rend3d.hh | hisahi/hiemalia | bb5370d6ef0b2480b3b8f563d292ddfab7c0f6e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | includes/rend3d.hh | hisahi/hiemalia | bb5370d6ef0b2480b3b8f563d292ddfab7c0f6e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /****************************************************************************/
/* */
/* HIEMALIA SOURCE CODE (C) 2021 SAMPO HIPPELAINEN (HISAHI). */
/* SEE THE LICENSE FILE IN THE SOURCE ROOT DIRECTORY FOR LICENSE INFO. */
/* */
/****************************************************************************/
// rend3d.hh: header file for rend3d.cc
#ifndef M_REND3D_HH
#define M_REND3D_HH
#include <string>
#include <vector>
#include "defs.hh"
#include "model.hh"
#include "sbuf.hh"
namespace hiemalia {
static const coord_t viewDistance = 2;
struct Vector3D {
coord_t x;
coord_t y;
coord_t z;
coord_t w;
Vector3D(const Point3D& p) : x(p.x), y(p.y), z(p.z), w(1) {}
Vector3D(coord_t x, coord_t y, coord_t z) : x(x), y(y), z(z), w(1) {}
Vector3D(coord_t x, coord_t y, coord_t z, coord_t w)
: x(x), y(y), z(z), w(w) {}
inline Vector3D& operator+=(const Vector3D& r) {
x += r.x;
y += r.y;
z += r.z;
w += r.w;
return *this;
}
inline Vector3D& operator-=(const Vector3D& r) {
x -= r.x;
y -= r.y;
z -= r.z;
w -= r.w;
return *this;
}
friend inline Vector3D operator+(Vector3D a, const Vector3D& b) {
return a += b;
}
friend inline Vector3D operator-(Vector3D a, const Vector3D& b) {
return a -= b;
}
inline coord_t getX() { return x / w; }
inline coord_t getY() { return y / w; }
inline coord_t getDepth() { return z / w; }
Point3D toCartesian() const;
inline static coord_t dot(const Vector3D& a, const Vector3D& b) {
coord_t wf = 1.0 / (a.w * b.w);
return wf * a.x * b.x + wf * a.y * b.y + wf * a.z * b.z;
}
inline static Vector3D cross(const Vector3D& a, const Vector3D& b) {
coord_t wf = 1.0 / (a.w * b.w);
return Vector3D(wf * a.y * b.z - wf * a.z * b.y,
wf * a.x * b.z - wf * a.z * b.x,
wf * a.x * b.y - wf * a.y * b.x, 1);
}
};
struct Matrix3D3 {
coord_t m[9];
Matrix3D3() : m{0} {}
Matrix3D3(coord_t a00, coord_t a01, coord_t a02, coord_t a10, coord_t a11,
coord_t a12, coord_t a20, coord_t a21, coord_t a22)
: m{a00, a01, a02, a10, a11, a12, a20, a21, a22} {}
inline coord_t& operator[](size_t i) { return m[i]; }
inline const coord_t& operator[](size_t i) const { return m[i]; }
inline static Matrix3D3 identity() {
return Matrix3D3({1, 0, 0, 0, 1, 0, 0, 0, 1});
}
static Matrix3D3 rotate(const Orient3D& r);
static Matrix3D3 scale(const Point3D& s);
static Matrix3D3 scale(coord_t s);
static Matrix3D3 yaw(coord_t theta);
static Matrix3D3 pitch(coord_t theta);
static Matrix3D3 roll(coord_t theta);
Point3D project(const Point3D& p) const;
Vector3D project(const Vector3D& v) const;
inline bool operator==(const Matrix3D3& r) const {
for (size_t i = 0; i < 9; ++i)
if (m[i] != r.m[i]) return false;
return true;
}
inline bool operator!=(const Matrix3D3& r) const { return !(*this == r); }
inline Matrix3D3& operator+=(const Matrix3D3& r) {
m[0] += r[0];
m[1] += r[1];
m[2] += r[2];
m[3] += r[3];
m[4] += r[4];
m[5] += r[5];
m[6] += r[6];
m[7] += r[7];
m[8] += r[8];
return *this;
}
inline Matrix3D3& operator-=(const Matrix3D3& r) {
m[0] -= r[0];
m[1] -= r[1];
m[2] -= r[2];
m[3] -= r[3];
m[4] -= r[4];
m[5] -= r[5];
m[6] -= r[6];
m[7] -= r[7];
m[8] -= r[8];
return *this;
}
inline Matrix3D3& operator*=(const Matrix3D3& r) {
*this = *this * r;
return *this;
}
inline Matrix3D3 operator-() const {
return Matrix3D3(-m[0], -m[1], -m[2], -m[3], -m[4], -m[5], -m[6], -m[7],
-m[8]);
}
friend inline Matrix3D3 operator+(Matrix3D3 a, const Matrix3D3& b) {
return a += b;
}
friend inline Matrix3D3 operator-(Matrix3D3 a, const Matrix3D3& b) {
return a -= b;
}
friend inline Matrix3D3 operator*(const Matrix3D3& a, const Matrix3D3& b) {
return Matrix3D3(a.m[0] * b.m[0] + a.m[1] * b.m[3] + a.m[2] * b.m[6],
a.m[0] * b.m[1] + a.m[1] * b.m[4] + a.m[2] * b.m[7],
a.m[0] * b.m[2] + a.m[1] * b.m[5] + a.m[2] * b.m[8],
a.m[3] * b.m[0] + a.m[4] * b.m[3] + a.m[5] * b.m[6],
a.m[3] * b.m[1] + a.m[4] * b.m[4] + a.m[5] * b.m[7],
a.m[3] * b.m[2] + a.m[4] * b.m[5] + a.m[5] * b.m[8],
a.m[6] * b.m[0] + a.m[7] * b.m[3] + a.m[8] * b.m[6],
a.m[6] * b.m[1] + a.m[7] * b.m[4] + a.m[8] * b.m[7],
a.m[6] * b.m[2] + a.m[7] * b.m[5] + a.m[8] * b.m[8]);
}
};
struct Matrix3D {
coord_t m[16];
Matrix3D() : m{0} {}
Matrix3D(coord_t a00, coord_t a01, coord_t a02, coord_t a03, coord_t a10,
coord_t a11, coord_t a12, coord_t a13, coord_t a20, coord_t a21,
coord_t a22, coord_t a23, coord_t a30, coord_t a31, coord_t a32,
coord_t a33)
: m{a00, a01, a02, a03, a10, a11, a12, a13,
a20, a21, a22, a23, a30, a31, a32, a33} {}
inline coord_t& operator[](size_t i) { return m[i]; }
inline const coord_t& operator[](size_t i) const { return m[i]; }
inline static Matrix3D identity() {
return Matrix3D({1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1});
}
static Matrix3D translate(const Point3D& p);
Point3D project(const Point3D& p) const;
Vector3D project(const Vector3D& v) const;
inline bool operator==(const Matrix3D& r) const {
for (size_t i = 0; i < 16; ++i)
if (m[i] != r.m[i]) return false;
return true;
}
inline bool operator!=(const Matrix3D& r) const { return !(*this == r); }
inline Matrix3D& operator+=(const Matrix3D& r) {
m[0] += r[0];
m[1] += r[1];
m[2] += r[2];
m[3] += r[3];
m[4] += r[4];
m[5] += r[5];
m[6] += r[6];
m[7] += r[7];
m[8] += r[8];
m[9] += r[9];
m[10] += r[10];
m[11] += r[11];
m[12] += r[12];
m[13] += r[13];
m[14] += r[14];
m[15] += r[15];
return *this;
}
inline Matrix3D& operator-=(const Matrix3D& r) {
m[0] -= r[0];
m[1] -= r[1];
m[2] -= r[2];
m[3] -= r[3];
m[4] -= r[4];
m[5] -= r[5];
m[6] -= r[6];
m[7] -= r[7];
m[8] -= r[8];
m[9] -= r[9];
m[10] -= r[10];
m[11] -= r[11];
m[12] -= r[12];
m[13] -= r[13];
m[14] -= r[14];
m[15] -= r[15];
return *this;
}
inline Matrix3D& operator*=(const Matrix3D& r) {
*this = *this * r;
return *this;
}
inline Matrix3D& operator*=(const Matrix3D3& r) {
*this = *this * r;
return *this;
}
inline Matrix3D operator-() const {
return Matrix3D(-m[0], -m[1], -m[2], -m[3], -m[4], -m[5], -m[6], -m[7],
-m[8], -m[9], -m[10], -m[11], -m[12], -m[13], -m[14],
-m[15]);
}
friend inline Matrix3D operator+(Matrix3D a, const Matrix3D& b) {
return a += b;
}
friend inline Matrix3D operator-(Matrix3D a, const Matrix3D& b) {
return a -= b;
}
friend inline Matrix3D operator*(const Matrix3D& a, const Matrix3D& b) {
return Matrix3D(a.m[0] * b.m[0] + a.m[1] * b.m[4] + a.m[2] * b.m[8] +
a.m[3] * b.m[12],
a.m[0] * b.m[1] + a.m[1] * b.m[5] + a.m[2] * b.m[9] +
a.m[3] * b.m[13],
a.m[0] * b.m[2] + a.m[1] * b.m[6] + a.m[2] * b.m[10] +
a.m[3] * b.m[14],
a.m[0] * b.m[3] + a.m[1] * b.m[7] + a.m[2] * b.m[11] +
a.m[3] * b.m[15],
a.m[4] * b.m[0] + a.m[5] * b.m[4] + a.m[6] * b.m[8] +
a.m[7] * b.m[12],
a.m[4] * b.m[1] + a.m[5] * b.m[5] + a.m[6] * b.m[9] +
a.m[7] * b.m[13],
a.m[4] * b.m[2] + a.m[5] * b.m[6] + a.m[6] * b.m[10] +
a.m[7] * b.m[14],
a.m[4] * b.m[3] + a.m[5] * b.m[7] + a.m[6] * b.m[11] +
a.m[7] * b.m[15],
a.m[8] * b.m[0] + a.m[9] * b.m[4] + a.m[10] * b.m[8] +
a.m[11] * b.m[12],
a.m[8] * b.m[1] + a.m[9] * b.m[5] + a.m[10] * b.m[9] +
a.m[11] * b.m[13],
a.m[8] * b.m[2] + a.m[9] * b.m[6] + a.m[10] * b.m[10] +
a.m[11] * b.m[14],
a.m[8] * b.m[3] + a.m[9] * b.m[7] + a.m[10] * b.m[11] +
a.m[11] * b.m[15],
a.m[12] * b.m[0] + a.m[13] * b.m[4] + a.m[14] * b.m[8] +
a.m[15] * b.m[12],
a.m[12] * b.m[1] + a.m[13] * b.m[5] + a.m[14] * b.m[9] +
a.m[15] * b.m[13],
a.m[12] * b.m[2] + a.m[13] * b.m[6] +
a.m[14] * b.m[10] + a.m[15] * b.m[14],
a.m[12] * b.m[3] + a.m[13] * b.m[7] +
a.m[14] * b.m[11] + a.m[15] * b.m[15]);
}
friend inline Matrix3D operator*(const Matrix3D& a, const Matrix3D3& b) {
return Matrix3D(
a.m[0] * b.m[0] + a.m[1] * b.m[3] + a.m[2] * b.m[6],
a.m[0] * b.m[1] + a.m[1] * b.m[4] + a.m[2] * b.m[7],
a.m[0] * b.m[2] + a.m[1] * b.m[5] + a.m[2] * b.m[8], a.m[3],
a.m[4] * b.m[0] + a.m[5] * b.m[3] + a.m[6] * b.m[6],
a.m[4] * b.m[1] + a.m[5] * b.m[4] + a.m[6] * b.m[7],
a.m[4] * b.m[2] + a.m[5] * b.m[5] + a.m[6] * b.m[8], a.m[7],
a.m[8] * b.m[0] + a.m[9] * b.m[3] + a.m[10] * b.m[6],
a.m[8] * b.m[1] + a.m[9] * b.m[4] + a.m[10] * b.m[7],
a.m[8] * b.m[2] + a.m[9] * b.m[5] + a.m[10] * b.m[8], a.m[11],
a.m[12] * b.m[0] + a.m[13] * b.m[3] + a.m[14] * b.m[6],
a.m[12] * b.m[1] + a.m[13] * b.m[4] + a.m[14] * b.m[7],
a.m[12] * b.m[2] + a.m[13] * b.m[5] + a.m[14] * b.m[8], a.m[15]);
}
};
#if !NDEBUG
std::string printMatrix(const Matrix3D& m); // test.cc
#endif
class Renderer3D {
public:
static Matrix3D getModelMatrix(Point3D p, Orient3D r, Point3D s);
void renderModel(SplinterBuffer& buf, Point3D p, Orient3D r, Point3D s,
const Model& m);
void setCamera(Point3D pos, Orient3D rot, Point3D scale);
Renderer3D();
private:
void renderModelFragment(SplinterBuffer& buf, const ModelFragment& f) const;
void projectVertices(const std::vector<Point3D>& v, const Matrix3D& m);
static Point3D clipPoint(const Vector3D& onScreen,
const Vector3D& offScreen);
bool clipLine(const Vector3D& v0, const Vector3D& v1, Point3D& p0,
Point3D& p1) const;
Matrix3D view;
std::vector<Vector3D> points_;
};
}; // namespace hiemalia
#endif // M_REND3D_HH
| 35.809231 | 80 | 0.419144 | [
"vector",
"model"
] |
3f6bc09f157462f49cca5c04fad85af172515472 | 3,715 | cpp | C++ | src/modules/gdgem/tests/HitGenerator.cpp | geishm-ansto/event-formation-unit | bab9f211913ee9e633eae627ec2c2ed96ae380b4 | [
"BSD-2-Clause"
] | 8 | 2017-12-02T09:20:26.000Z | 2022-03-28T08:17:40.000Z | src/modules/gdgem/tests/HitGenerator.cpp | geishm-ansto/event-formation-unit | bab9f211913ee9e633eae627ec2c2ed96ae380b4 | [
"BSD-2-Clause"
] | 296 | 2017-10-24T09:06:10.000Z | 2022-03-31T07:31:06.000Z | src/modules/gdgem/tests/HitGenerator.cpp | geishm-ansto/event-formation-unit | bab9f211913ee9e633eae627ec2c2ed96ae380b4 | [
"BSD-2-Clause"
] | 8 | 2018-04-08T15:35:50.000Z | 2021-04-12T05:06:15.000Z | // Copyright (C) 2019 European Spallation Source ERIC
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <fmt/format.h>
#include <gdgem/tests/HitGenerator.h>
#include <vector>
#include <cassert>
/// \todo Should not belong to gdgem but to common, reduction?
namespace Gem {
//
void HitGenerator::printHits() {
for (auto & Hit : Hits) {
fmt::print("t {}, p {}, c {}, w {}\n", uint64_t(Hit.time), int(Hit.plane), int(Hit.coordinate), int(Hit.weight));
}
}
//
void HitGenerator::printEvents() {
fmt::print("t (x, y)\n");
for (auto & Event : Events) {
fmt::print("{} ({}, {})\n", Event.TimeNs, Event.XPos, Event.YPos);
}
}
//
std::vector<NeutronEvent> & HitGenerator::randomEvents(int NumEvents, int MinCoord, int MaxCoord) {
auto TimeNs = T0;
std::uniform_int_distribution<int> coords(MinCoord, MaxCoord);
for (int i = 0; i < NumEvents; i++) {
auto XPos = coords(RandGen);
auto YPos = coords(RandGen);
//fmt::print("Event: ({}, {}), t={}\n", XPos, YPos, Time);
Events.push_back({XPos, YPos, TimeNs});
TimeNs += TGap;
}
return Events;
}
//
std::vector<Hit> & HitGenerator::randomHits(int MaxHits, int Gaps, int DeadTimeNs, bool Shuffle) {
std::uniform_int_distribution<int> angle(0, 360);
for (auto & Event : Events) {
auto Degrees = angle(RandGen);
//fmt::print("({},{}) @ {}\n", Event.XPos, Event.YPos, Degrees);
makeHitsForSinglePlane(0, MaxHits, Event.XPos, Event.YPos, Degrees, Gaps, DeadTimeNs, Shuffle);
makeHitsForSinglePlane(1, MaxHits, Event.XPos, Event.YPos, Degrees, Gaps, DeadTimeNs, Shuffle);
advanceTime(TGap);
}
return Hits;
}
//
std::vector<Hit> & HitGenerator::makeHitsForSinglePlane(int Plane, int MaxHits,
float X0, float Y0, float Angle, int Gaps, int DeadTimeNs, bool Shuffle) {
int64_t TimeNs = T0;
int32_t OldTime = TimeNs;
float TmpCoord{0};
int Coord{32767}, OldCoord{32767};
uint16_t ADC{2345};
std::vector<Hit> TmpHits;
if ((Plane != PlaneX) and (Plane != PlaneY)) {
return Hits;
}
for (int hit = 0; hit < MaxHits; hit++) {
if (Plane == PlaneX) {
TmpCoord = X0 + hit * 1.0 * cos(D2R(Angle));
//fmt::print("X0 {}, RO {}, Angle {}, cos(angle) {}, TmpCoord {}\n", X0, hit, Angle, cosa, TmpCoord);
} else {
TmpCoord = Y0 + hit * 1.0 * sin(D2R(Angle));
}
Coord = (int)TmpCoord;
if ((Coord > CoordMax) or (Coord < CoordMin)) {
continue;
}
// Same coordinate - time gap is critical
if (Coord == OldCoord) {
//fmt::print("Same coordinate, OldTime {}, Time {}\n", OldTime, Time);
if ((OldTime != TimeNs) and (TimeNs - OldTime < DeadTimeNs) ) {
// Not the first Hit but within deadtime
//fmt::print(" dT {} shorter than deadtime - skipping\n", Time - OldTime);
TimeNs += DeltaT;
continue;
}
}
Hit CurrHit{(uint64_t)TimeNs, (uint16_t)Coord, ADC, (uint8_t)Plane};
TmpHits.push_back(CurrHit);
OldTime = TimeNs;
TimeNs += DeltaT;
OldCoord = Coord;
}
// Handle gaps
TmpHits = makeGaps(TmpHits, Gaps);
if (Shuffle) {
std::shuffle(TmpHits.begin(), TmpHits.end(), RandGen);
}
for (auto &Hit : TmpHits) {
Hits.push_back(Hit);
}
return Hits;
}
//
std::vector<Hit> & HitGenerator::makeGaps(std::vector<Hit> & Hits, uint8_t Gaps) {
if (Gaps == 0) {
return Hits;
}
std::vector<Hit> GapHits;
if (Gaps > Hits.size() - 2) {
//fmt::print("Gaps requestes {}, available {}\n", Gaps, TmpHits.size() - 2);
Hits.clear();
}
for (unsigned int i = 0; i < Hits.size(); i ++) {
if ((i == 0) or (i > Gaps)) {
GapHits.push_back(Hits[i]);
}
}
Hits = GapHits;
return Hits;
}
} // namespace
| 27.932331 | 117 | 0.607537 | [
"vector"
] |
3f702eebf9239074ff68df4b2de3574a3efb0cfb | 1,595 | cpp | C++ | _KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/renderer_framework/std_ui_framework/std_ui_framework.cpp | Karamays/karamay_engine | 858054ea5155d0b690b7cf17d0e6a6266e0b0b9c | [
"MIT"
] | null | null | null | _KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/renderer_framework/std_ui_framework/std_ui_framework.cpp | Karamays/karamay_engine | 858054ea5155d0b690b7cf17d0e6a6266e0b0b9c | [
"MIT"
] | null | null | null | _KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/renderer_framework/std_ui_framework/std_ui_framework.cpp | Karamays/karamay_engine | 858054ea5155d0b690b7cf17d0e6a6266e0b0b9c | [
"MIT"
] | 1 | 2022-01-29T08:24:14.000Z | 2022-01-29T08:24:14.000Z | #include "std_ui_framework.h"
#include "graphics/opengl/dispatcher/gl_renderer_dispatcher.h"
#include "renderers/templates/gl_shader_toy_renderer.h"
namespace std_ui_framework
{
gl_renderer_template<gl_shader_toy_renderer> _shader_toy_renderer_template;
}
bool std_ui_framework::framework::initialize() noexcept
{
std::vector<gl_shader_toy_renderer*> _invoked_st_renderers;
_shader_toy_renderer_template.load_all(_invoked_st_renderers);
for (auto _invoked_st_renderer : _invoked_st_renderers)
{
if (_invoked_st_renderer && _invoked_st_renderer->attach())
_renderers.push_back(_invoked_st_renderer);
}
auto _st_renderer = gl_shader_toy_renderer::invoke();
if(_st_renderer && _st_renderer->attach())
_renderers.push_back(_st_renderer);
return true;
}
void std_ui_framework::framework::tick(float delta_time) noexcept
{
for (auto _renderer : _renderers)
{
if (_renderer)
{
_renderer->render(delta_time);
}
}
}
bool std_ui_framework::framework::set_state(bool active) noexcept
{
return false;
}
bool std_ui_framework::framework::is_active() const noexcept
{
return true;
}
struct std_ui_framework_helper
{
static std_ui_framework_helper helper;
std_ui_framework_helper()
{
auto _std_ui_fw = new std_ui_framework::framework();
gl_renderer_dispatcher::register_framework("std_ui_framework", _std_ui_fw);
std::cout << "std_ui_framework has been registered." << std::endl;
}
};
std_ui_framework_helper std_ui_framework_helper::helper;
| 27.033898 | 83 | 0.734169 | [
"render",
"vector"
] |
3f73a82bb5fc873d7db2eb23a0701eca0bb85789 | 5,918 | cpp | C++ | mapleall/maple_driver/src/compiler.cpp | lvyitian/mapleall | 1112501c1bcbff5d9388bf46f195d56560c5863a | [
"MulanPSL-1.0"
] | null | null | null | mapleall/maple_driver/src/compiler.cpp | lvyitian/mapleall | 1112501c1bcbff5d9388bf46f195d56560c5863a | [
"MulanPSL-1.0"
] | null | null | null | mapleall/maple_driver/src/compiler.cpp | lvyitian/mapleall | 1112501c1bcbff5d9388bf46f195d56560c5863a | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) [2019-2020] Huawei Technologies Co., Ltd. All rights reserved.
*
* OpenArkCompiler is licensed under the Mulan Permissive Software License v2.
* You can use this software according to the terms and conditions of the MulanPSL - 2.0.
* You may obtain a copy of MulanPSL - 2.0 at:
*
* https://opensource.org/licenses/MulanPSL-2.0
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the MulanPSL - 2.0 for more details.
*/
#include "compiler.h"
#include <cstdlib>
#include "file_utils.h"
#include "safe_exe.h"
#include "mpl_timer.h"
namespace maple {
using namespace mapleOption;
int Compiler::Exe(const MplOptions &mplOptions, const std::string &options) const {
std::ostringstream ostrStream;
ostrStream << GetBinPath(mplOptions) << GetBinName();
std::string binPath = ostrStream.str();
return SafeExe::Exe(binPath, options);
}
std::string Compiler::GetBinPath(const MplOptions &mplOptions) const {
#ifdef MAPLE_PRODUCT_EXECUTABLE // build flag -DMAPLE_PRODUCT_EXECUTABLE
std::string binPath = std::string(MAPLE_PRODUCT_EXECUTABLE);
if (binPath.empty()) {
binPath = mplOptions.GetExeFolder();
} else {
binPath = binPath + kFileSeperatorChar;
}
#else
std::string binPath = mplOptions.GetExeFolder();
#endif
return binPath;
}
ErrorCode Compiler::Compile(MplOptions &options, MIRModulePtr &theModule) {
MPLTimer timer = MPLTimer();
LogInfo::MapleLogger() << "Starting " << GetName() << '\n';
timer.Start();
std::string strOption = MakeOption(options);
if (strOption.empty()) {
return kErrorInvalidParameter;
}
if (Exe(options, strOption) != 0) {
return kErrorCompileFail;
}
timer.Stop();
LogInfo::MapleLogger() << (GetName() + " consumed ") << timer.Elapsed() << "s\n";
return kErrorNoError;
}
std::string Compiler::MakeOption(const MplOptions &options) const {
std::map<std::string, MplOption> finalOptions;
std::map<std::string, MplOption> defaultOptions = MakeDefaultOptions(options);
AppendDefaultOptions(finalOptions, defaultOptions);
auto userOption = options.GetOptions().find(GetBinName());
if (userOption != options.GetOptions().end()) {
AppendUserOptions(finalOptions, userOption->second);
}
AppendExtraOptions(finalOptions, options.GetExtras());
std::ostringstream strOption;
for (const auto &finalOption : finalOptions) {
strOption << " " << finalOption.first << finalOption.second.GetconnectSymbol() << finalOption.second.GetValue();
if (options.HasSetDebugFlag()) {
LogInfo::MapleLogger() << Compiler::GetName() << " options: " << finalOption.first << " "
<< finalOption.second.GetValue() << '\n';
}
}
strOption << " " << this->GetInputFileName(options);
if (options.HasSetDebugFlag()) {
LogInfo::MapleLogger() << Compiler::GetName() << " input files: " << GetInputFileName(options) << '\n';
}
return strOption.str();
}
void Compiler::AppendDefaultOptions(std::map<std::string, MplOption> &finalOptions,
const std::map<std::string, MplOption> &defaultOptions) const {
for (const auto &defaultIt : defaultOptions) {
finalOptions.insert(make_pair(defaultIt.first, defaultIt.second));
}
}
void Compiler::AppendUserOptions(std::map<std::string, MplOption> &finalOptions,
const std::vector<Option> &userOptions) const {
#ifdef OPTION_PARSER_EXTRAOPT
const std::string &binName = GetBinName();
for (const auto &userOption : userOptions) {
auto extra = userOption.FindExtra(binName);
if (extra != nullptr) {
AppendOptions(finalOptions, extra->optionKey, userOption.Args(), userOption.ConnectSymbol(binName));
}
}
#endif
}
void Compiler::AppendExtraOptions(std::map<std::string, MplOption> &finalOptions,
const std::map<std::string, std::vector<MplOption>> &extraOptions) const {
const std::string &binName = GetBinName();
auto extras = extraOptions.find(binName);
if (extras == extraOptions.end()) {
return;
}
for (const auto &secondExtras : extras->second) {
AppendOptions(finalOptions, secondExtras.GetKey(), secondExtras.GetValue(), secondExtras.GetconnectSymbol());
}
}
std::map<std::string, MplOption> Compiler::MakeDefaultOptions(const MplOptions &options) const {
DefaultOption rawDefaultOptions = GetDefaultOptions(options);
std::map<std::string, MplOption> defaultOptions;
if (rawDefaultOptions.mplOptions != nullptr) {
for (uint32_t i = 0; i < rawDefaultOptions.length; ++i) {
defaultOptions.insert(std::make_pair(rawDefaultOptions.mplOptions[i].GetKey(),
rawDefaultOptions.mplOptions[i]));
}
}
return defaultOptions;
}
void Compiler::AppendOptions(std::map<std::string, MplOption> &finalOptions, const std::string &key,
const std::string &value, const std::string &connectSymbol) const {
auto finalOpt = finalOptions.find(key);
if (finalOpt != finalOptions.end()) {
if (finalOpt->second.GetIsAppend()) {
std::string temp = finalOpt->second.GetValue() + finalOpt->second.GetAppendSplit() + value;
finalOpt->second.SetValue(temp);
} else {
finalOpt->second.SetValue(value);
}
} else {
MplOption option(key, value, connectSymbol, false, "");
finalOptions.insert(make_pair(key, option));
}
}
bool Compiler::CanAppendOptimization() const {
// there're some issues for passing -Ox to each component, let users determine self.
return false;
}
std::string Compiler::AppendOptimization(const MplOptions &options, const std::string &optionStr) const {
if (!CanAppendOptimization()) {
return optionStr;
}
return optionStr + " " + options.OptimizationLevelStr();
}
} // namespace maple
| 37.694268 | 116 | 0.692971 | [
"vector"
] |
3f827d715aaa3f379560552006f053ce15da478b | 1,444 | cpp | C++ | SDLTuts/Main.cpp | Amaranthos/SDLPlayground | 693a0430c2d814089408bd6c55d5174c1469ea73 | [
"MIT"
] | null | null | null | SDLTuts/Main.cpp | Amaranthos/SDLPlayground | 693a0430c2d814089408bd6c55d5174c1469ea73 | [
"MIT"
] | null | null | null | SDLTuts/Main.cpp | Amaranthos/SDLPlayground | 693a0430c2d814089408bd6c55d5174c1469ea73 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string>
#include <cmath>
#include <sstream>
#include <iostream>
#include <fstream>
#include <SDL.h>
#include <SDL_image.h>
//#include <SDL_ttf.h>
#include "Globals.h"
#include "Texture.h"
#include "Window.h"
#include "Dot.h"
bool Init();
bool LoadMedia(Game::Tile* tiles[]);
void Close(Game::Tile* tiles[]);
bool CheckCollision(SDL_Rect a, SDL_Rect b);
bool TouchesWall(SDL_Rect box, Game::Tile* tiles[]);
bool SetTiles(Game::Tile* tiles[]);
int main(int argc, char* args[]) {
//Init
if (!Init()) {
printf("Failed to Init!\n");
}
else {
Game::Tile* tileSet[TOTAL_TILES];
//Load
if (!LoadMedia(tileSet)) {
printf("Failed to load media!\n");
}
else {
//Main loop flag
bool quit = false;
//Event handler
SDL_Event event;
Dot dot;
SDL_Rect camera = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
//Main loop
while (!quit) {
//Poll for events/input
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT) quit = true;
else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) quit = true;
window.HandleEvent(event);
dot.HandleEvent(event);
}
dot.Move(tileSet);
dot.SetCamera(camera);
window.Clear();
for (int i = 0; i < TOTAL_TILES; ++i)
tileSet[i]->Render(camera);
dot.Render(camera, window.GetRenderer());
window.Render();
}
}
}
//Clean up
Close();
return 0;
} | 18.278481 | 92 | 0.623269 | [
"render"
] |
3f8472b3683b54d092a4354c460ec13f7696fffe | 9,708 | cpp | C++ | src/vidhrdw/xevious.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 33 | 2015-08-10T11:13:47.000Z | 2021-08-30T10:00:46.000Z | src/vidhrdw/xevious.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 13 | 2015-08-25T03:53:08.000Z | 2022-03-30T18:02:35.000Z | src/vidhrdw/xevious.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 40 | 2015-08-25T05:09:21.000Z | 2022-02-08T05:02:30.000Z | /***************************************************************************
vidhrdw.c
Functions to emulate the video hardware of the machine.
***************************************************************************/
#include "driver.h"
unsigned char *xevious_fg_videoram,*xevious_fg_colorram;
unsigned char *xevious_bg_videoram,*xevious_bg_colorram;
extern unsigned char *spriteram,*spriteram_2,*spriteram_3;
extern size_t spriteram_size;
static struct tilemap *fg_tilemap,*bg_tilemap;
/***************************************************************************
Convert the color PROMs into a more useable format.
Xevious has three 256x4 palette PROMs (one per gun) and four 512x4 lookup
table PROMs (two for sprites, two for background tiles; foreground
characters map directly to a palette color without using a PROM).
The palette PROMs are connected to the RGB output this way:
bit 3 -- 220 ohm resistor -- RED/GREEN/BLUE
-- 470 ohm resistor -- RED/GREEN/BLUE
-- 1 kohm resistor -- RED/GREEN/BLUE
bit 0 -- 2.2kohm resistor -- RED/GREEN/BLUE
***************************************************************************/
void xevious_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom)
{
int i;
#define TOTAL_COLORS(gfxn) (Machine->gfx[gfxn]->total_colors * Machine->gfx[gfxn]->color_granularity)
#define COLOR(gfxn,offs) (colortable[Machine->drv->gfxdecodeinfo[gfxn].color_codes_start + offs])
for (i = 0;i < 128;i++)
{
int bit0,bit1,bit2,bit3;
/* red component */
bit0 = (color_prom[0] >> 0) & 0x01;
bit1 = (color_prom[0] >> 1) & 0x01;
bit2 = (color_prom[0] >> 2) & 0x01;
bit3 = (color_prom[0] >> 3) & 0x01;
*(palette++) = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3;
/* green component */
bit0 = (color_prom[256] >> 0) & 0x01;
bit1 = (color_prom[256] >> 1) & 0x01;
bit2 = (color_prom[256] >> 2) & 0x01;
bit3 = (color_prom[256] >> 3) & 0x01;
*(palette++) = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3;
/* blue component */
bit0 = (color_prom[2*256] >> 0) & 0x01;
bit1 = (color_prom[2*256] >> 1) & 0x01;
bit2 = (color_prom[2*256] >> 2) & 0x01;
bit3 = (color_prom[2*256] >> 3) & 0x01;
*(palette++) = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3;
color_prom++;
}
/* color 0x80 is used by sprites to mark transparency */
*(palette++) = 0;
*(palette++) = 0;
*(palette++) = 0;
color_prom += 128; /* the bottom part of the PROM is unused */
color_prom += 2*256;
/* color_prom now points to the beginning of the lookup table */
/* background tiles */
for (i = 0;i < TOTAL_COLORS(1);i++)
{
COLOR(1,i) = (color_prom[0] & 0x0f) | ((color_prom[TOTAL_COLORS(1)] & 0x0f) << 4);
color_prom++;
}
color_prom += TOTAL_COLORS(1);
/* sprites */
for (i = 0;i < TOTAL_COLORS(2);i++)
{
int c = (color_prom[0] & 0x0f) | ((color_prom[TOTAL_COLORS(2)] & 0x0f) << 4);
if (c & 0x80) COLOR(2,i) = c & 0x7f;
else COLOR(2,i) = 0x80; /* transparent */
color_prom++;
}
color_prom += TOTAL_COLORS(2);
/* foreground characters */
for (i = 0;i < TOTAL_COLORS(0);i++)
{
if (i % 2 == 0) COLOR(0,i) = 0x80; /* transparent */
else COLOR(0,i) = i / 2;
}
}
/***************************************************************************
Callbacks for the TileMap code
***************************************************************************/
static void get_fg_tile_info(int tile_index)
{
unsigned char attr = xevious_fg_colorram[tile_index];
SET_TILE_INFO(0,xevious_fg_videoram[tile_index],
((attr & 0x03) << 4) | ((attr & 0x3c) >> 2))
tile_info.flags = TILE_FLIPYX((attr & 0xc0) >> 6);
}
static void get_bg_tile_info(int tile_index)
{
unsigned char code = xevious_bg_videoram[tile_index];
unsigned char attr = xevious_bg_colorram[tile_index];
SET_TILE_INFO(1,code + ((attr & 0x01) << 8),
((attr & 0x3c) >> 2) | ((code & 0x80) >> 3) | ((attr & 0x03) << 5))
tile_info.flags = TILE_FLIPYX((attr & 0xc0) >> 6);
}
/***************************************************************************
Start the video hardware emulation.
***************************************************************************/
int xevious_vh_start(void)
{
bg_tilemap = tilemap_create(get_bg_tile_info,tilemap_scan_rows,TILEMAP_OPAQUE, 8,8,64,32);
fg_tilemap = tilemap_create(get_fg_tile_info,tilemap_scan_rows,TILEMAP_TRANSPARENT,8,8,64,32);
if (!bg_tilemap || !fg_tilemap)
return 1;
fg_tilemap->transparent_pen = 0;
return 0;
}
/***************************************************************************
Memory handlers
***************************************************************************/
WRITE_HANDLER( xevious_fg_videoram_w )
{
if (xevious_fg_videoram[offset] != data)
{
xevious_fg_videoram[offset] = data;
tilemap_mark_tile_dirty(fg_tilemap,offset);
}
}
WRITE_HANDLER( xevious_fg_colorram_w )
{
if (xevious_fg_colorram[offset] != data)
{
xevious_fg_colorram[offset] = data;
tilemap_mark_tile_dirty(fg_tilemap,offset);
}
}
WRITE_HANDLER( xevious_bg_videoram_w )
{
if (xevious_bg_videoram[offset] != data)
{
xevious_bg_videoram[offset] = data;
tilemap_mark_tile_dirty(bg_tilemap,offset);
}
}
WRITE_HANDLER( xevious_bg_colorram_w )
{
if (xevious_bg_colorram[offset] != data)
{
xevious_bg_colorram[offset] = data;
tilemap_mark_tile_dirty(bg_tilemap,offset);
}
}
WRITE_HANDLER( xevious_vh_latch_w )
{
int reg;
data = data + ((offset&0x01)<<8); /* A0 -> D8 */
reg = (offset&0xf0)>>4;
switch (reg)
{
case 0:
if (flip_screen)
tilemap_set_scrollx(bg_tilemap,0,data-312);
else
tilemap_set_scrollx(bg_tilemap,0,data+20);
break;
case 1:
tilemap_set_scrollx(fg_tilemap,0,data+32);
break;
case 2:
tilemap_set_scrolly(bg_tilemap,0,data+16);
break;
case 3:
tilemap_set_scrolly(fg_tilemap,0,data+18);
break;
case 7:
flip_screen_w(0,data & 1);
break;
default:
//logerror("CRTC WRITE REG: %x Data: %03x\n",reg, data);
break;
}
}
/*
background pattern data
colorram mapping
b000-bfff background attribute
bit 0-1 COL:palette set select
bit 2-5 AN :color select
bit 6 AFF:Y flip
bit 7 PFF:X flip
c000-cfff background pattern name
bit 0-7 PP0-7
seet 8A
2 +-------+
COL0,1 --------------------------------------->|backg. |
1 |color |
PP7------------------------------------------->|replace|
4 | ROM | 6
AN0-3 ---------------------------------------->| 4H |-----> color code 6 bit
1 +-----------+ +--------+ | 4F |
COL0 ---->|B8 ROM 3C| 16 |custom | 2 | |
8 | |----->|shifter |------>| |
PP0-7 ---->|B0-7 ROM 3D| |16->2*8 | | |
+-----------+ +--------+ +-------+
font rom controller
1 +--------+ +--------+
ANF --->| ROM | 8 |shift | 1
8 | 3B |---->|reg |-----> font data
PP0-7 --->| | |8->1*8 |
+--------+ +--------+
font color ( not use color map )
2 |
COL0-1 --->| color code 6 bit
4 |
AN0-3 --->|
sprite
ROM 3M,3L color reprace table for sprite
*/
/***************************************************************************
Display refresh
***************************************************************************/
static void draw_sprites(struct osd_bitmap *bitmap)
{
int offs,sx,sy;
for (offs = 0;offs < spriteram_size;offs += 2)
{
if ((spriteram[offs + 1] & 0x40) == 0) /* I'm not sure about this one */
{
int bank,code,color,flipx,flipy;
if (spriteram_3[offs] & 0x80)
{
bank = 4;
code = spriteram[offs] & 0x3f;
}
else
{
bank = 2 + ((spriteram[offs] & 0x80) >> 7);
code = spriteram[offs] & 0x7f;
}
color = spriteram[offs + 1] & 0x7f;
flipx = spriteram_3[offs] & 4;
flipy = spriteram_3[offs] & 8;
if (flip_screen)
{
flipx = !flipx;
flipy = !flipy;
}
sx = spriteram_2[offs + 1] - 40 + 0x100*(spriteram_3[offs + 1] & 1);
sy = 28*8-spriteram_2[offs]-1;
if (spriteram_3[offs] & 2) /* double height (?) */
{
if (spriteram_3[offs] & 1) /* double width, double height */
{
code &= 0x7c;
drawgfx(bitmap,Machine->gfx[bank],
code+3,color,flipx,flipy,
flipx ? sx : sx+16,flipy ? sy-16 : sy,
&Machine->visible_area,TRANSPARENCY_COLOR,0x80);
drawgfx(bitmap,Machine->gfx[bank],
code+1,color,flipx,flipy,
flipx ? sx : sx+16,flipy ? sy : sy-16,
&Machine->visible_area,TRANSPARENCY_COLOR,0x80);
}
code &= 0x7d;
drawgfx(bitmap,Machine->gfx[bank],
code+2,color,flipx,flipy,
flipx ? sx+16 : sx,flipy ? sy-16 : sy,
&Machine->visible_area,TRANSPARENCY_COLOR,0x80);
drawgfx(bitmap,Machine->gfx[bank],
code,color,flipx,flipy,
flipx ? sx+16 : sx,flipy ? sy : sy-16,
&Machine->visible_area,TRANSPARENCY_COLOR,0x80);
}
else if (spriteram_3[offs] & 1) /* double width */
{
code &= 0x7e;
drawgfx(bitmap,Machine->gfx[bank],
code,color,flipx,flipy,
flipx ? sx+16 : sx,flipy ? sy-16 : sy,
&Machine->visible_area,TRANSPARENCY_COLOR,0x80);
drawgfx(bitmap,Machine->gfx[bank],
code+1,color,flipx,flipy,
flipx ? sx : sx+16,flipy ? sy-16 : sy,
&Machine->visible_area,TRANSPARENCY_COLOR,0x80);
}
else /* normal */
{
drawgfx(bitmap,Machine->gfx[bank],
code,color,flipx,flipy,sx,sy,
&Machine->visible_area,TRANSPARENCY_COLOR,0x80);
}
}
}
}
void xevious_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh)
{
tilemap_update(ALL_TILEMAPS);
tilemap_render(ALL_TILEMAPS);
tilemap_draw(bitmap,bg_tilemap,0);
draw_sprites(bitmap);
tilemap_draw(bitmap,fg_tilemap,0);
}
| 25.547368 | 118 | 0.560466 | [
"3d"
] |
3f8c18bdbfe01ad7eb3ce7b421dad6f9dd622089 | 2,764 | cpp | C++ | inex/render/base/sources/command_processor.cpp | PhysShell/inexplicable_engine | a91d2f30fc4c64abd5a78fd71f21b13052c86c9d | [
"WTFPL"
] | null | null | null | inex/render/base/sources/command_processor.cpp | PhysShell/inexplicable_engine | a91d2f30fc4c64abd5a78fd71f21b13052c86c9d | [
"WTFPL"
] | null | null | null | inex/render/base/sources/command_processor.cpp | PhysShell/inexplicable_engine | a91d2f30fc4c64abd5a78fd71f21b13052c86c9d | [
"WTFPL"
] | null | null | null | #include "pch.h"
#include "command_processor.h"
#include <inex/render/base/world.h>
using inex::render::command_processor;
using inex::render::engine::command;
using inex::render::engine::wrapper;
//using inex::render::delete_on_tick_callback_type;
command_processor::command_processor ( /*delete_on_tick_callback_type*/ pvoid engine ) :
//delete_on_tick ( engine ),
m_next_frame_orders_first ( 0 ),
m_next_frame_orders_last ( 0 ),
m_command_frame_id ( 0 ),
m_process_next_frame_orders ( false )
{
//m_orders.set_pop_thread_id ( );
}
void command_processor::initialize_queue( command* command )
{
//m_orders.push_null_node ( command );
}
void command_processor::push_command ( command* const command )
{
//bool const empty = m_orders.empty();
//m_orders.push_back ( command );
//if ( empty )
// m_wait_form_command_event.set ( true );
}
bool command_processor::run ( bool wait_for_command )
{
return 1;
if ( m_process_next_frame_orders ) {
m_process_next_frame_orders = false;
command* new_buffer_first = 0;
command* new_buffer_last = 0;
for ( command* i = m_next_frame_orders_first; i; )
{
i->execute ( );
command* order = i;
i = i->next;
if ( order->remove_frame_id <= m_command_frame_id )
{
//delete_on_tick ( order );
}
else
{
order->next = 0;
if ( !new_buffer_first )
new_buffer_first = order;
else
new_buffer_last->next = order;
new_buffer_last = order;
}
}
m_next_frame_orders_first = new_buffer_first;
m_next_frame_orders_last = new_buffer_last;
}
//for (u32 i=0; wait_for_command && m_orders.empty() && i<64; ++i )
// threading::yield ( 0 );
//if ( wait_for_command && m_orders.empty() )
//m_wait_form_command_event.wait ( 16 );
/*while ( !m_orders.empty( ) ) {
command* to_delete;
command* const order = m_orders.pop_front( to_delete );
u32 const frame_id = m_command_frame_id;
order->execute ( );
if ( order->remove_frame_id <= frame_id )
delete_on_tick ( to_delete );
else {
order->next = 0;
if ( !m_next_frame_orders_first )
m_next_frame_orders_first = order;
else
m_next_frame_orders_last->next = order;
m_next_frame_orders_last = order;
}
ASSERT ( frame_id <= m_command_frame_id );
if ( frame_id < m_command_frame_id ) {
m_process_next_frame_orders = true;
return ( false );
}
}*/
return ( true );
}
void command_processor::purge_orders ( )
{
command* order;
//while ( m_orders.pop_front( order ) )
// delete_on_tick ( order );
//order = m_orders.pop_null_node();
//delete_on_tick ( order );
}
void command_processor::set_push_thread_id ( )
{
//m_orders.set_push_thread_id ( );
} | 23.423729 | 88 | 0.666787 | [
"render"
] |
3f92993a7ba425ab73accb8360a89e2ae89478f8 | 3,792 | cc | C++ | src/model/standard_model_node.cc | karaoulanis/nemesis-code | 1ed488b389a552802ea910c9d8045f4cb0e57200 | [
"BSL-1.0"
] | 2 | 2019-07-02T11:59:42.000Z | 2020-08-17T11:51:55.000Z | src/model/standard_model_node.cc | karaoulanis/nemesis-code | 1ed488b389a552802ea910c9d8045f4cb0e57200 | [
"BSL-1.0"
] | null | null | null | src/model/standard_model_node.cc | karaoulanis/nemesis-code | 1ed488b389a552802ea910c9d8045f4cb0e57200 | [
"BSL-1.0"
] | null | null | null | /*******************************************************************************
* nemesis. an experimental finite element code. *
* Copyright (C) 2004-2011 F.E.Karaoulanis [http://www.nemesis-project.org] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 3, as *
* published by the Free Software Foundation. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see < http://www.gnu.org/licenses/>. *
*******************************************************************************/
// *****************************************************************************
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
// $HeadURL$
// Author(s): F.E. Karaoulanis (fkar@nemesis-project.org)
// *****************************************************************************
#include "model/standard_model_node.h"
#include "node/node.h"
/**
* Default constructor.
*/
StandardModelNode::StandardModelNode() {
}
/**
* Constructor.
* Initializes the ModelObject, which in turn initializes the FEObject, passes
* the FTable to the ModelObject and copies the address of it's node.
*/
StandardModelNode::StandardModelNode(const IDContainer& FTable, Node* pNode)
:ModelNode(FTable, pNode) {
}
StandardModelNode::~StandardModelNode() {
}
void StandardModelNode::incTrialDisp(const Vector& du) {
for (unsigned i = 0; i < theFTable.size(); i++)
(*myVector)[i]=du[theFTable[i]];
myNode->incTrialDisp(*myVector);
}
void StandardModelNode::incTrialVecs(const Vector& du, const Vector& dv,
const Vector& da) {
for (unsigned i = 0; i < theFTable.size(); i++)
(*myVector)[i]=du[theFTable[i]];
myNode->incTrialDisp(*myVector);
for (unsigned i = 0; i < theFTable.size(); i++)
(*myVector)[i]=dv[theFTable[i]];
myNode->addTrialVelc(*myVector);
for (unsigned i = 0; i < theFTable.size(); i++)
(*myVector)[i]=da[theFTable[i]];
myNode->addTrialAccl(*myVector);
}
void StandardModelNode::set_trial_disp(const Vector& u) {
for (unsigned i = 0; i < theFTable.size(); i++)
(*myVector)[i]=u[theFTable[i]];
myNode->set_trial_disp(*myVector);
}
void StandardModelNode::set_trial_vecs(const Vector& u, const Vector& v,
const Vector& a) {
for (unsigned i = 0; i < theFTable.size(); i++)
(*myVector)[i]=u[theFTable[i]];
myNode->set_trial_disp(*myVector);
for (unsigned i = 0; i < theFTable.size(); i++)
(*myVector)[i]=v[theFTable[i]];
myNode->set_trial_velc(*myVector);
for (unsigned i = 0; i < theFTable.size(); i++)
(*myVector)[i]=a[theFTable[i]];
myNode->set_trial_accl(*myVector);
}
void StandardModelNode::Commit() {
myNode->Commit();
}
void StandardModelNode::commitSens(const Vector& X, int param) {
for (unsigned i = 0; i < theFTable.size(); i++)
(*myVector)[i]=X[theFTable[i]];
myNode->commitSens(*myVector, param);
}
void StandardModelNode::add_R(double factor) {
if (myNode->existsLoad()) myVector->Add_cV(factor, myNode->get_R());
}
| 42.606742 | 80 | 0.545359 | [
"vector",
"model"
] |
3f9cb9ca81fa4f7b473364319b3ec8c1f4a5552e | 16,365 | cpp | C++ | Modules/Core/src/DataManagement/mitkPropertyRelationRuleBase.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 1 | 2021-11-20T08:19:27.000Z | 2021-11-20T08:19:27.000Z | Modules/Core/src/DataManagement/mitkPropertyRelationRuleBase.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | Modules/Core/src/DataManagement/mitkPropertyRelationRuleBase.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkPropertyRelationRuleBase.h"
#include <mitkDataNode.h>
#include <mitkExceptionMacro.h>
#include <mitkNodePredicateBase.h>
#include <mitkStringProperty.h>
#include <mitkUIDGenerator.h>
#include <mutex>
#include <regex>
bool mitk::PropertyRelationRuleBase::IsSourceCandidate(const IPropertyProvider *owner) const
{
return owner != nullptr;
};
bool mitk::PropertyRelationRuleBase::IsDestinationCandidate(const IPropertyProvider *owner) const
{
return owner != nullptr;
};
mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRootKeyPath()
{
return PropertyKeyPath().AddElement("MITK").AddElement("Relations");
};
mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRuleRootKeyPath() const
{
return GetRootKeyPath().AddElement(this->GetRuleID());
};
bool mitk::PropertyRelationRuleBase::IsSource(const IPropertyProvider *owner) const
{
if (!owner)
{
mitkThrow() << "Error. Passed owner pointer is NULL";
}
auto keys = owner->GetPropertyKeys();
auto rootkey = PropertyKeyPathToPropertyName(this->GetRuleRootKeyPath());
for (const auto &key : keys)
{
if (key.find(rootkey) == 0)
{
return true;
}
}
return false;
};
mitk::PropertyRelationRuleBase::RelationType mitk::PropertyRelationRuleBase::HasRelation(
const IPropertyProvider *source, const IPropertyProvider *destination) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
if (!destination)
{
mitkThrow() << "Error. Passed owner pointer is NULL";
}
RelationType result = RelationType::None;
if (this->GetInstanceID_IDLayer(source, destination) != NULL_INSTANCE_ID())
{ // has relations of type Connected_ID;
result = RelationType::Connected_ID;
}
if (result == RelationType::None)
{
auto instanceIDs_data = this->GetInstanceID_datalayer(source, destination);
if (instanceIDs_data.size() > 1)
{
MITK_WARN << "Property relation on data level is ambiguous. First relation is used. Instance ID: "
<< instanceIDs_data.front();
}
if (!instanceIDs_data.empty() && instanceIDs_data.front() != NULL_INSTANCE_ID())
{ // has relations of type Connected_Data;
result = RelationType::Connected_Data;
}
}
if (result == RelationType::None)
{
if (this->HasImplicitDataRelation(source, destination))
{ // has relations of type Connected_Data;
result = RelationType::Implicit_Data;
}
}
return result;
};
mitk::PropertyRelationRuleBase::RelationUIDVectorType mitk::PropertyRelationRuleBase::GetExistingRelations(
const IPropertyProvider *source) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
auto relIDRegExStr =
PropertyKeyPathToPropertyRegEx(this->GetRuleRootKeyPath().AddAnyElement().AddElement("relationUID"));
auto regEx = std::regex(relIDRegExStr);
const auto keys = source->GetPropertyKeys();
RelationUIDVectorType relationUIDs;
for (const auto &key : keys)
{
if (std::regex_match(key, regEx))
{
auto idProp = source->GetConstProperty(key);
relationUIDs.push_back(idProp->GetValueAsString());
}
}
return relationUIDs;
};
mitk::PropertyRelationRuleBase::RelationUIDType mitk::PropertyRelationRuleBase::GetRelationUID(
const IPropertyProvider *source, const IPropertyProvider *destination) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
if (!destination)
{
mitkThrow() << "Error. Passed destination pointer is NULL";
}
RelationUIDType result;
auto instanceID = this->GetInstanceID_IDLayer(source, destination);
if (instanceID == NULL_INSTANCE_ID())
{
auto instanceID_data = this->GetInstanceID_datalayer(source, destination);
if (!instanceID_data.empty())
{
instanceID = instanceID_data.front();
}
if (instanceID_data.size() > 1)
{
MITK_WARN << "Property relation on data level is ambigious. First relation is used. Instance ID: " << instanceID;
}
}
return this->GetRelationUIDByInstanceID(source, instanceID);
};
mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::NULL_INSTANCE_ID()
{
return std::string();
};
mitk::PropertyRelationRuleBase::RelationUIDType mitk::PropertyRelationRuleBase::GetRelationUIDByInstanceID(
const IPropertyProvider *source, const InstanceIDType &instanceID) const
{
RelationUIDType result;
if (instanceID != NULL_INSTANCE_ID())
{
auto idProp = source->GetConstProperty(
PropertyKeyPathToPropertyName(this->GetRuleRootKeyPath().AddElement(instanceID).AddElement("relationUID")));
if (idProp.IsNotNull())
{
result = idProp->GetValueAsString();
}
}
if (result.empty())
{
mitkThrowException(NoPropertyRelationException);
}
return result;
};
mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::GetInstanceIDByRelationUID(
const IPropertyProvider *source, const RelationUIDType &relationUID) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
InstanceIDType result;
auto destRegExStr =
PropertyKeyPathToPropertyRegEx(this->GetRuleRootKeyPath().AddAnyElement().AddElement("relationUID"));
auto regEx = std::regex(destRegExStr);
std::smatch instance_matches;
auto keys = source->GetPropertyKeys();
for (const auto &key : keys)
{
if (std::regex_search(key, instance_matches, regEx))
{
auto idProp = source->GetConstProperty(key);
if (idProp->GetValueAsString() == relationUID)
{
if (instance_matches.size()>1)
{
result = instance_matches[1];
break;
}
}
}
}
return result;
};
mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::GetInstanceID_IDLayer(
const IPropertyProvider *source, const IPropertyProvider *destination) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
if (!destination)
{
mitkThrow() << "Error. Passed destination pointer is NULL";
}
auto identifiable = dynamic_cast<const Identifiable *>(destination);
std::string result;
if (identifiable)
{ // check for relations of type Connected_ID;
auto destRegExStr =
PropertyKeyPathToPropertyRegEx(this->GetRuleRootKeyPath().AddAnyElement().AddElement("destinationUID"));
auto regEx = std::regex(destRegExStr);
std::smatch instance_matches;
auto destUID = identifiable->GetUID();
auto keys = source->GetPropertyKeys();
for (const auto &key : keys)
{
if (std::regex_search(key, instance_matches, regEx))
{
auto idProp = source->GetConstProperty(key);
if (idProp->GetValueAsString() == destUID)
{
if (instance_matches.size()>1)
{
result = instance_matches[1];
break;
}
}
}
}
}
return result;
};
void mitk::PropertyRelationRuleBase::Connect(IPropertyOwner *source, const IPropertyProvider *destination) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
if (!destination)
{
mitkThrow() << "Error. Passed destination pointer is NULL";
}
InstanceIDType instanceID = this->GetInstanceID_IDLayer(source, destination);
bool hasIDlayer = instanceID != NULL_INSTANCE_ID();
auto instanceIDs_data = this->GetInstanceID_datalayer(source, destination);
if (instanceIDs_data.size() > 1)
{
MITK_WARN << "Property relation on data level is ambiguous. First relation is used. Instance ID: "
<< instanceIDs_data.front();
}
bool hasDatalayer = !instanceIDs_data.empty();
if (hasIDlayer && hasDatalayer && instanceID != instanceIDs_data.front())
{
mitkThrow() << "Property relation information is in an invalid state. ID and data layer point to different "
"relation instances. Rule: "
<< this->GetRuleID() << "; ID based instance: " << instanceID
<< "; Data base instance: " << instanceIDs_data.front();
}
RelationUIDType relationUID = this->CreateRelationUID();
if (!hasIDlayer)
{
if (hasDatalayer)
{
instanceID = instanceIDs_data.front();
}
else
{
instanceID = this->CreateNewRelationInstance(source, relationUID);
}
}
auto relUIDKey =
PropertyKeyPathToPropertyName(this->GetRuleRootKeyPath().AddElement(instanceID).AddElement("relationUID"));
source->SetProperty(relUIDKey, mitk::StringProperty::New(relationUID));
if (!hasIDlayer)
{
auto identifiable = dynamic_cast<const Identifiable *>(destination);
if (identifiable)
{
auto destUIDKey =
PropertyKeyPathToPropertyName(this->GetRuleRootKeyPath().AddElement(instanceID).AddElement("destinationUID"));
source->SetProperty(destUIDKey, mitk::StringProperty::New(identifiable->GetUID()));
}
}
if (!hasDatalayer)
{
this->Connect_datalayer(source, destination, instanceID);
}
};
void mitk::PropertyRelationRuleBase::Disconnect(IPropertyOwner *source, const IPropertyProvider *destination) const
{
try
{
this->Disconnect(source, this->GetRelationUID(source, destination));
}
catch (const NoPropertyRelationException &)
{
// nothing to do and no real error in context of disconnect.
}
};
void mitk::PropertyRelationRuleBase::Disconnect(IPropertyOwner *source, RelationUIDType relationUID) const
{
auto instanceID = this->GetInstanceIDByRelationUID(source, relationUID);
if (instanceID != NULL_INSTANCE_ID())
{
this->Disconnect_datalayer(source, instanceID);
auto instancePrefix = PropertyKeyPathToPropertyName(this->GetRuleRootKeyPath().AddElement(instanceID));
auto keys = source->GetPropertyKeys();
for (const auto &key : keys)
{
if (key.find(instancePrefix) == 0)
{
source->RemoveProperty(key);
}
}
}
};
mitk::PropertyRelationRuleBase::RelationUIDType mitk::PropertyRelationRuleBase::CreateRelationUID()
{
UIDGenerator generator;
return generator.GetUID();
};
/**This mutex is used to guard mitk::PropertyRelationRuleBase::CreateNewRelationInstance by a class wide mutex to avoid
racing conditions in a scenario where rules are used concurrently. It is not in the class interface itself, because it
is an implementation detail.
*/
std::mutex relationCreationLock;
mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::CreateNewRelationInstance(
IPropertyOwner *source, const RelationUIDType &relationUID) const
{
std::lock_guard<std::mutex> guard(relationCreationLock);
//////////////////////////////////////
// Get all existing instanc IDs
std::vector<int> instanceIDs;
InstanceIDType newID = "1";
auto destRegExStr =
PropertyKeyPathToPropertyRegEx(this->GetRuleRootKeyPath().AddAnyElement().AddElement("destinationUID"));
auto regEx = std::regex(destRegExStr);
std::smatch instance_matches;
auto keys = source->GetPropertyKeys();
for (const auto &key : keys)
{
if (std::regex_search(key, instance_matches, regEx))
{
if (instance_matches.size()>1)
{
instanceIDs.push_back(std::stoi(instance_matches[1]));
}
}
}
//////////////////////////////////////
// Get new ID
std::sort(instanceIDs.begin(), instanceIDs.end());
if (!instanceIDs.empty())
{
newID = std::to_string(instanceIDs.back() + 1);
}
//////////////////////////////////////
// reserve new ID
auto relUIDKey =
PropertyKeyPathToPropertyName(this->GetRuleRootKeyPath().AddElement(newID).AddElement("relationUID"));
source->SetProperty(relUIDKey, mitk::StringProperty::New(relationUID));
return newID;
};
itk::LightObject::Pointer mitk::PropertyRelationRuleBase::InternalClone() const
{
return Superclass::InternalClone();
};
namespace mitk
{
/**
* \brief Predicate used to wrap rule checks.
*
* \ingroup DataStorage
*/
class NodePredicateRuleFunction : public NodePredicateBase
{
public:
using FunctionType = std::function<bool(const mitk::IPropertyProvider *, const mitk::PropertyRelationRuleBase *)>;
mitkClassMacro(NodePredicateRuleFunction, NodePredicateBase)
mitkNewMacro2Param(NodePredicateRuleFunction, const FunctionType &, PropertyRelationRuleBase::ConstPointer)
~NodePredicateRuleFunction() override = default;
bool CheckNode(const mitk::DataNode *node) const override
{
if (!node)
{
return false;
}
return m_Function(node, m_Rule);
};
protected:
explicit NodePredicateRuleFunction(const FunctionType &function, PropertyRelationRuleBase::ConstPointer rule) : m_Function(function), m_Rule(rule)
{
};
FunctionType m_Function;
PropertyRelationRuleBase::ConstPointer m_Rule;
};
} // namespace mitk
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetSourceCandidateIndicator() const
{
auto check = [](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) {
return rule->IsSourceCandidate(node);
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
};
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetDestinationCandidateIndicator() const
{
auto check = [](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) {
return rule->IsDestinationCandidate(node);
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
};
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetConnectedSourcesDetector() const
{
auto check = [](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule)
{
return rule->IsSource(node);
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
};
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetSourcesDetector(
const IPropertyProvider *destination, RelationType minimalRelation) const
{
if (!destination)
{
mitkThrow() << "Error. Passed destination pointer is NULL";
}
auto check = [destination, minimalRelation](const mitk::IPropertyProvider *node,
const mitk::PropertyRelationRuleBase *rule) {
return rule->HasRelation(node, destination) >= minimalRelation;
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
};
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetDestinationsDetector(
const IPropertyProvider *source, RelationType minimalRelation) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
auto check = [source, minimalRelation](const mitk::IPropertyProvider *node,
const mitk::PropertyRelationRuleBase *rule) {
return rule->HasRelation(source, node) >= minimalRelation;
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
};
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetDestinationDetector(
const IPropertyProvider *source, RelationUIDType relationUID) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
auto relUIDs = this->GetExistingRelations(source);
if (std::find(relUIDs.begin(), relUIDs.end(), relationUID) == relUIDs.end())
{
mitkThrow()
<< "Error. Passed relationUID does not identify a relation instance of the passed source for this rule instance.";
};
auto check = [source, relationUID](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) {
try
{
return rule->GetRelationUID(source, node) == relationUID;
}
catch(const NoPropertyRelationException &)
{
return false;
}
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
};
| 28.166954 | 150 | 0.697097 | [
"vector"
] |
3fa2cfc6336e4415177def06cd771941eec199c3 | 3,461 | hpp | C++ | libraries/chain/include/muse/chain/history_object.hpp | top1st/SounDAC-Source | 5e4a898a17cfda2fcb9da23572e97246174654f1 | [
"BSD-2-Clause"
] | 2 | 2018-10-07T11:46:51.000Z | 2019-05-07T09:51:44.000Z | libraries/chain/include/muse/chain/history_object.hpp | top1st/SounDAC-Source | 5e4a898a17cfda2fcb9da23572e97246174654f1 | [
"BSD-2-Clause"
] | 26 | 2018-08-20T13:03:25.000Z | 2019-10-02T19:42:00.000Z | libraries/chain/include/muse/chain/history_object.hpp | top1st/SounDAC-Source | 5e4a898a17cfda2fcb9da23572e97246174654f1 | [
"BSD-2-Clause"
] | 7 | 2018-08-23T13:53:11.000Z | 2020-10-16T06:48:41.000Z | #pragma once
#include <muse/chain/protocol/authority.hpp>
#include <muse/chain/protocol/types.hpp>
#include <muse/chain/protocol/operations.hpp>
#include <muse/chain/protocol/base_operations.hpp>
#include <muse/chain/witness_objects.hpp>
#include <muse/chain/streaming_platform_objects.hpp>
#include <graphene/db/generic_index.hpp>
#include <boost/multi_index/composite_key.hpp>
namespace muse { namespace chain {
using namespace graphene::db;
class operation_object : public abstract_object<operation_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_operation_object_type;
transaction_id_type trx_id;
uint32_t block = 0;
uint32_t trx_in_block = 0;
uint16_t op_in_trx = 0;
uint64_t virtual_op = 0;
time_point_sec timestamp;
operation op;
};
struct by_location;
struct by_transaction_id;
typedef multi_index_container<
operation_object,
indexed_by<
ordered_unique< tag< by_id >, member< object, object_id_type, &object::id > >,
ordered_unique< tag< by_location >,
composite_key< operation_object,
member< operation_object, uint32_t, &operation_object::block>,
member< operation_object, uint32_t, &operation_object::trx_in_block>,
member< operation_object, uint16_t, &operation_object::op_in_trx>,
member< operation_object, uint64_t, &operation_object::virtual_op>,
member< object, object_id_type, &operation_object::id>
>
>,
ordered_unique< tag< by_transaction_id >,
composite_key< operation_object,
member< operation_object, transaction_id_type, &operation_object::trx_id>,
member< object, object_id_type, &operation_object::id>
>
>
>
> operation_multi_index_type;
class account_history_object : public abstract_object<account_history_object> {
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_account_history_object_type;
string account;
uint32_t sequence = 0;
operation_id_type op;
};
struct by_account;
typedef multi_index_container<
account_history_object,
indexed_by<
ordered_unique< tag< by_id >, member< object, object_id_type, &object::id > >,
ordered_unique< tag< by_account >,
composite_key< account_history_object,
member< account_history_object, string, &account_history_object::account>,
member< account_history_object, uint32_t, &account_history_object::sequence>
>,
composite_key_compare< std::less<string>, std::greater<uint32_t> >
>
>
> account_history_multi_index_type;
typedef generic_index< operation_object, operation_multi_index_type > operation_index;
typedef generic_index< account_history_object, account_history_multi_index_type > account_history_index;
} }
FC_REFLECT_DERIVED( muse::chain::operation_object, (graphene::db::object), (trx_id)(block)(trx_in_block)(op_in_trx)(virtual_op)(timestamp)(op) )
FC_REFLECT_DERIVED( muse::chain::account_history_object, (graphene::db::object), (account)(sequence)(op) )
| 38.88764 | 144 | 0.668882 | [
"object"
] |
3fb579001e436aec8db3dce1550efb1b7311631e | 6,213 | hpp | C++ | logos/bootstrap/pull.hpp | LogosNetwork/logos-core | 6b155539a734efefb8f649a761d044b5f267a51a | [
"BSD-2-Clause"
] | 3 | 2020-01-17T18:05:19.000Z | 2021-12-29T04:21:59.000Z | logos/bootstrap/pull.hpp | LogosNetwork/logos-core | 6b155539a734efefb8f649a761d044b5f267a51a | [
"BSD-2-Clause"
] | null | null | null | logos/bootstrap/pull.hpp | LogosNetwork/logos-core | 6b155539a734efefb8f649a761d044b5f267a51a | [
"BSD-2-Clause"
] | 2 | 2020-12-22T05:51:53.000Z | 2021-06-08T00:27:46.000Z | #pragma once
#include <deque>
#include <unordered_map>
#include <memory>
#include <logos/consensus/persistence/block_cache.hpp>
#include <logos/bootstrap/bootstrap_messages.hpp>
#include <logos/node/node.hpp>
namespace Bootstrap
{
using PullPtr = std::shared_ptr<PullRequest>;
using BSBPtr = std::shared_ptr<ApprovedRB>;
using MBPtr = std::shared_ptr<ApprovedMB>;
using EBPtr = std::shared_ptr<ApprovedEB>;
class BootstrapAttempt;
using AttemptPtr = std::shared_ptr<BootstrapAttempt>;
constexpr uint16_t BLOCK_CACHE_TIMEOUT_MS = 10000; // 10 seconds
enum class PullStatus : uint8_t
{
Continue,
Done,
DisconnectSender,
BlackListSender,
Unknown = 0xff
};
class Puller : public std::enable_shared_from_this<Puller>
{
public:
/**
* constructor
* @param block_cache the block cache
*/
Puller(logos::IBlockCache & block_cache, logos::alarm & alarm);
/**
* initialize the puller
* @param my_tips my tips
* @param others_tips peer's tips
*/
bool Init(AttemptPtr a, const TipSet &my_tipset, const TipSet &others_tipset);
/**
* get a pull request
* @return shared_ptr of a pull request
*/
PullPtr GetPull();
/**
* if the bootstrap is completed
* @return true if the bootstrap is completed
*/
bool AllDone();
/**
* get the number of waiting pull requests
* @return the number of waiting pull requests
*/
size_t GetNumWaitingPulls();
/**
* an epoch block is received
* @param pull the pull request that the block belongs to
* @param block the block
* @return status of the pull
*/
PullStatus EBReceived(PullPtr pull, EBPtr block);
/**
* a micro block is received
* @param pull the pull request that the block belongs to
* @param block the block
* @return status of the pull
*/
PullStatus MBReceived(PullPtr pull, MBPtr block);
/**
* a request block is received
* @param pull the pull request that the block belongs to
* @param block the block
* @param last_block if the block is the last block that we can get
* @return status of the pull
*/
PullStatus BSBReceived(PullPtr pull, BSBPtr block, bool last_block);
/**
* the peer failed to provide more blocks
* @param pull the pull request
*/
void PullFailed(PullPtr pull);
bool GetTipsets(TipSet &my, TipSet &others, uint8_t &mb_Qed, uint8_t &eb_Qed);
private:
void CreateMorePulls();
void CheckMicroProgressAndCreateMorePulls(bool wakeup = false);
bool ReduceNumBlockToDownload();
void UpdateMyBSBTip(BSBPtr block);
void UpdateMyMBTip(MBPtr block);
void UpdateMyEBTip(EBPtr block);
logos::IBlockCache & block_cache;
logos::alarm & alarm;
AttemptPtr attempt;
TipSet my_tips;
TipSet others_tips;
uint64_t num_blocks_to_download;
bool inited;
std::mutex mtx;//for waiting_pulls and ongoing_pulls
std::deque<PullPtr> waiting_pulls;
std::unordered_set<PullPtr> ongoing_pulls;
enum class PullerState : uint8_t
{
Epoch,
Micro,
Batch,
Batch_No_MB,
Batch_No_MB_Next_Epoch,
Done
};
PullerState state = PullerState::Done;
struct MicroPeriod
{
MBPtr mb;
std::unordered_set<BlockHash> bsb_targets;
void Clean()
{
mb = nullptr;
assert(bsb_targets.empty());
}
};
struct EpochPeriod
{
EpochPeriod(uint32_t epoch_num = 0)
: epoch_num(epoch_num)
, two_mbps(false)
{}
uint32_t epoch_num;
EBPtr eb;
MicroPeriod cur_mbp;
/*
* for corner case: bsb of cur_mbp depends on bsb in next_mbp.
* in more detail, because of time drift allowed in the system,
* there is a chance that an earlier request block A proposed by
* delegate X has a later timestamp comparing to another block B
* proposed by Y. If that happens, then there is a small chance that
* B is included in a micro block and A is not (due to the later
* timestamp). There is also a small chance that two requests of the
* same account r1 and r2 end up in block A and block B respectively.
* If all above happens, the earlier micro block will have a
* dependency on a request block that is not included in this micro
* block.
* Note that the last micro block of an epoch uses epoch_number field
* in the block to cut off. So this cornor case will not happen
* cross the epoch boundary.
*/
bool two_mbps;
MicroPeriod next_mbp;
};
EpochPeriod working_epoch;
uint32_t final_ep_number = 0;
Log log;
};
class PullRequestHandler
{
public:
/**
* constructor
* @param request the pull request
* @param store the database
*/
PullRequestHandler(PullRequest request, Store & store);
//return: if true call again for more blocks
/**
* Get the next serialized pull response
* @param buf the data buffer that will be filled with a pull response
* @return true if the caller should call again for more blocks
*/
bool GetNextSerializedResponse(std::vector<uint8_t> & buf);
private:
uint32_t GetBlock(BlockHash & hash, std::vector<uint8_t> & buf);
void TraceToEpochBegin();
PullRequest request;
Store & store;
BlockHash next;
Log log;
};
} //namespace
| 29.727273 | 86 | 0.579752 | [
"vector"
] |
3fb672144e712f9afe9566f6ccc3b4ae5f54b45f | 2,026 | cpp | C++ | src/glfwOnWindows/besaier.cpp | 99611400/computerGraphics | 37255b51e82ccd3a02ad0d5a33b686bbe7cb4ede | [
"Apache-2.0"
] | 1 | 2021-06-29T10:22:35.000Z | 2021-06-29T10:22:35.000Z | src/glfwOnWindows/besaier.cpp | 99611400/computerGraphics | 37255b51e82ccd3a02ad0d5a33b686bbe7cb4ede | [
"Apache-2.0"
] | null | null | null | src/glfwOnWindows/besaier.cpp | 99611400/computerGraphics | 37255b51e82ccd3a02ad0d5a33b686bbe7cb4ede | [
"Apache-2.0"
] | null | null | null | #include <chrono>
#include <iostream>
#include <opencv2/opencv.hpp>
std::vector<cv::Point2f> control_points;
cv::Point2f lerp_v2f(const cv::Point2f& a, const cv::Point2f& b, float t)
{
return a + (b - a) * t;
}
cv::Point2f recursive_bezier(const std::vector<cv::Point2f> &control_points, float t)
{
if (control_points.size() == 1)
{
return control_points[0];
}
std::vector<cv::Point2f> lerp_points;
for (size_t i = 1;i<control_points.size();i++)
{
lerp_points.push_back(lerp_v2f(control_points[i - 1], control_points[i], t));
}
return recursive_bezier(lerp_points,t);
}
void bezier(const std::vector<cv::Point2f> &control_points, cv::Mat &window)
{
// TODO: Iterate through all t = 0 to t = 1 with small steps, and call de Casteljau's
// recursive Bezier algorithm.
for (double t = 0.0;t<=1.0;t+=0.001)
{
auto point = recursive_bezier(control_points, t);
window.at<cv::Vec3b>(point.y, point.x)[1] = 255;
}
}
cv::Mat window;
void mouse_handler(int event, int x, int y, int flags, void *userdata)
{
if (event == cv::EVENT_LBUTTONDOWN )
{
std::cout << "Left button of the mouse is clicked - position (" << x << ", "
<< y << ")" << '\n';
control_points.emplace_back(x, y);
for (auto &point : control_points)
{
cv::circle(window, point, 1, {255, 255, 255}, 3);
}
cv::imshow("Bezier Curve", window);
}
if (event == cv::EVENT_RBUTTONDOWN )
{
std::cout << "asdfasfd"<<std::endl;
bezier(control_points, window);
cv::imshow("Bezier Curve", window);
}
}
int main()
{
window = cv::Mat(700, 700, CV_8UC3, cv::Scalar(0));
cv::cvtColor(window, window, cv::COLOR_BGR2RGB);
cv::namedWindow("Bezier Curve", cv::WINDOW_AUTOSIZE);
cv::setMouseCallback("Bezier Curve", mouse_handler, nullptr);
int key = -1;
while (key != 27)
{
key = cv::waitKey(0);
}
return 0;
}
| 22.263736 | 89 | 0.588351 | [
"vector"
] |
3fb9f1af04720e8ad9d2331b1f7ec22d0278ed8a | 17,739 | cpp | C++ | frameworks/compile/slang/slang_rs_backend.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2022-01-07T01:53:19.000Z | 2022-01-07T01:53:19.000Z | frameworks/compile/slang/slang_rs_backend.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | null | null | null | frameworks/compile/slang/slang_rs_backend.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2020-02-28T02:48:42.000Z | 2020-02-28T02:48:42.000Z | /*
* Copyright 2010-2012, 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.
*/
#include "slang_rs_backend.h"
#include <string>
#include <vector>
#include "clang/AST/ASTContext.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/DebugLoc.h"
#include "slang_assert.h"
#include "slang_rs.h"
#include "slang_rs_context.h"
#include "slang_rs_export_foreach.h"
#include "slang_rs_export_func.h"
#include "slang_rs_export_type.h"
#include "slang_rs_export_var.h"
#include "slang_rs_metadata.h"
namespace slang {
RSBackend::RSBackend(RSContext *Context,
clang::DiagnosticsEngine *DiagEngine,
const clang::CodeGenOptions &CodeGenOpts,
const clang::TargetOptions &TargetOpts,
PragmaList *Pragmas,
llvm::raw_ostream *OS,
Slang::OutputType OT,
clang::SourceManager &SourceMgr,
bool AllowRSPrefix,
bool IsFilterscript)
: Backend(DiagEngine, CodeGenOpts, TargetOpts, Pragmas, OS, OT),
mContext(Context),
mSourceMgr(SourceMgr),
mAllowRSPrefix(AllowRSPrefix),
mIsFilterscript(IsFilterscript),
mExportVarMetadata(NULL),
mExportFuncMetadata(NULL),
mExportForEachNameMetadata(NULL),
mExportForEachSignatureMetadata(NULL),
mExportTypeMetadata(NULL),
mRSObjectSlotsMetadata(NULL),
mRefCount(mContext->getASTContext()),
mASTChecker(mContext->getASTContext(), mContext->getTargetAPI(),
IsFilterscript) {
}
// 1) Add zero initialization of local RS object types
void RSBackend::AnnotateFunction(clang::FunctionDecl *FD) {
if (FD &&
FD->hasBody() &&
!SlangRS::IsLocInRSHeaderFile(FD->getLocation(), mSourceMgr)) {
mRefCount.Init();
mRefCount.Visit(FD->getBody());
}
return;
}
bool RSBackend::HandleTopLevelDecl(clang::DeclGroupRef D) {
// Disallow user-defined functions with prefix "rs"
if (!mAllowRSPrefix) {
// Iterate all function declarations in the program.
for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end();
I != E; I++) {
clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I);
if (FD == NULL)
continue;
if (!FD->getName().startswith("rs")) // Check prefix
continue;
if (!SlangRS::IsLocInRSHeaderFile(FD->getLocation(), mSourceMgr))
mDiagEngine.Report(
clang::FullSourceLoc(FD->getLocation(), mSourceMgr),
mDiagEngine.getCustomDiagID(clang::DiagnosticsEngine::Error,
"invalid function name prefix, "
"\"rs\" is reserved: '%0'"))
<< FD->getName();
}
}
// Process any non-static function declarations
for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; I++) {
clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I);
if (FD && FD->isGlobal()) {
// Check that we don't have any array parameters being misintrepeted as
// kernel pointers due to the C type system's array to pointer decay.
size_t numParams = FD->getNumParams();
for (size_t i = 0; i < numParams; i++) {
const clang::ParmVarDecl *PVD = FD->getParamDecl(i);
clang::QualType QT = PVD->getOriginalType();
if (QT->isArrayType()) {
mDiagEngine.Report(
clang::FullSourceLoc(PVD->getTypeSpecStartLoc(), mSourceMgr),
mDiagEngine.getCustomDiagID(clang::DiagnosticsEngine::Error,
"exported function parameters may "
"not have array type: %0")) << QT;
}
}
AnnotateFunction(FD);
}
}
return Backend::HandleTopLevelDecl(D);
}
void RSBackend::HandleTranslationUnitPre(clang::ASTContext &C) {
clang::TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
// If we have an invalid RS/FS AST, don't check further.
if (!mASTChecker.Validate()) {
return;
}
if (mIsFilterscript) {
mContext->addPragma("rs_fp_relaxed", "");
}
int version = mContext->getVersion();
if (version == 0) {
// Not setting a version is an error
mDiagEngine.Report(
mSourceMgr.getLocForEndOfFile(mSourceMgr.getMainFileID()),
mDiagEngine.getCustomDiagID(
clang::DiagnosticsEngine::Error,
"missing pragma for version in source file"));
} else {
slangAssert(version == 1);
}
if (mContext->getReflectJavaPackageName().empty()) {
mDiagEngine.Report(
mSourceMgr.getLocForEndOfFile(mSourceMgr.getMainFileID()),
mDiagEngine.getCustomDiagID(clang::DiagnosticsEngine::Error,
"missing \"#pragma rs "
"java_package_name(com.foo.bar)\" "
"in source file"));
return;
}
// Create a static global destructor if necessary (to handle RS object
// runtime cleanup).
clang::FunctionDecl *FD = mRefCount.CreateStaticGlobalDtor();
if (FD) {
HandleTopLevelDecl(clang::DeclGroupRef(FD));
}
// Process any static function declarations
for (clang::DeclContext::decl_iterator I = TUDecl->decls_begin(),
E = TUDecl->decls_end(); I != E; I++) {
if ((I->getKind() >= clang::Decl::firstFunction) &&
(I->getKind() <= clang::Decl::lastFunction)) {
clang::FunctionDecl *FD = llvm::dyn_cast<clang::FunctionDecl>(*I);
if (FD && !FD->isGlobal()) {
AnnotateFunction(FD);
}
}
}
return;
}
///////////////////////////////////////////////////////////////////////////////
void RSBackend::HandleTranslationUnitPost(llvm::Module *M) {
if (!mContext->processExport()) {
return;
}
// Write optimization level
llvm::SmallVector<llvm::Value*, 1> OptimizationOption;
OptimizationOption.push_back(llvm::ConstantInt::get(
mLLVMContext, llvm::APInt(32, mCodeGenOpts.OptimizationLevel)));
// Dump export variable info
if (mContext->hasExportVar()) {
int slotCount = 0;
if (mExportVarMetadata == NULL)
mExportVarMetadata = M->getOrInsertNamedMetadata(RS_EXPORT_VAR_MN);
llvm::SmallVector<llvm::Value*, 2> ExportVarInfo;
// We emit slot information (#rs_object_slots) for any reference counted
// RS type or pointer (which can also be bound).
for (RSContext::const_export_var_iterator I = mContext->export_vars_begin(),
E = mContext->export_vars_end();
I != E;
I++) {
const RSExportVar *EV = *I;
const RSExportType *ET = EV->getType();
bool countsAsRSObject = false;
// Variable name
ExportVarInfo.push_back(
llvm::MDString::get(mLLVMContext, EV->getName().c_str()));
// Type name
switch (ET->getClass()) {
case RSExportType::ExportClassPrimitive: {
const RSExportPrimitiveType *PT =
static_cast<const RSExportPrimitiveType*>(ET);
ExportVarInfo.push_back(
llvm::MDString::get(
mLLVMContext, llvm::utostr_32(PT->getType())));
if (PT->isRSObjectType()) {
countsAsRSObject = true;
}
break;
}
case RSExportType::ExportClassPointer: {
ExportVarInfo.push_back(
llvm::MDString::get(
mLLVMContext, ("*" + static_cast<const RSExportPointerType*>(ET)
->getPointeeType()->getName()).c_str()));
break;
}
case RSExportType::ExportClassMatrix: {
ExportVarInfo.push_back(
llvm::MDString::get(
mLLVMContext, llvm::utostr_32(
RSExportPrimitiveType::DataTypeRSMatrix2x2 +
static_cast<const RSExportMatrixType*>(ET)->getDim() - 2)));
break;
}
case RSExportType::ExportClassVector:
case RSExportType::ExportClassConstantArray:
case RSExportType::ExportClassRecord: {
ExportVarInfo.push_back(
llvm::MDString::get(mLLVMContext,
EV->getType()->getName().c_str()));
break;
}
}
mExportVarMetadata->addOperand(
llvm::MDNode::get(mLLVMContext, ExportVarInfo));
ExportVarInfo.clear();
if (mRSObjectSlotsMetadata == NULL) {
mRSObjectSlotsMetadata =
M->getOrInsertNamedMetadata(RS_OBJECT_SLOTS_MN);
}
if (countsAsRSObject) {
mRSObjectSlotsMetadata->addOperand(llvm::MDNode::get(mLLVMContext,
llvm::MDString::get(mLLVMContext, llvm::utostr_32(slotCount))));
}
slotCount++;
}
}
// Dump export function info
if (mContext->hasExportFunc()) {
if (mExportFuncMetadata == NULL)
mExportFuncMetadata =
M->getOrInsertNamedMetadata(RS_EXPORT_FUNC_MN);
llvm::SmallVector<llvm::Value*, 1> ExportFuncInfo;
for (RSContext::const_export_func_iterator
I = mContext->export_funcs_begin(),
E = mContext->export_funcs_end();
I != E;
I++) {
const RSExportFunc *EF = *I;
// Function name
if (!EF->hasParam()) {
ExportFuncInfo.push_back(llvm::MDString::get(mLLVMContext,
EF->getName().c_str()));
} else {
llvm::Function *F = M->getFunction(EF->getName());
llvm::Function *HelperFunction;
const std::string HelperFunctionName(".helper_" + EF->getName());
slangAssert(F && "Function marked as exported disappeared in Bitcode");
// Create helper function
{
llvm::StructType *HelperFunctionParameterTy = NULL;
if (!F->getArgumentList().empty()) {
std::vector<llvm::Type*> HelperFunctionParameterTys;
for (llvm::Function::arg_iterator AI = F->arg_begin(),
AE = F->arg_end(); AI != AE; AI++)
HelperFunctionParameterTys.push_back(AI->getType());
HelperFunctionParameterTy =
llvm::StructType::get(mLLVMContext, HelperFunctionParameterTys);
}
if (!EF->checkParameterPacketType(HelperFunctionParameterTy)) {
fprintf(stderr, "Failed to export function %s: parameter type "
"mismatch during creation of helper function.\n",
EF->getName().c_str());
const RSExportRecordType *Expected = EF->getParamPacketType();
if (Expected) {
fprintf(stderr, "Expected:\n");
Expected->getLLVMType()->dump();
}
if (HelperFunctionParameterTy) {
fprintf(stderr, "Got:\n");
HelperFunctionParameterTy->dump();
}
}
std::vector<llvm::Type*> Params;
if (HelperFunctionParameterTy) {
llvm::PointerType *HelperFunctionParameterTyP =
llvm::PointerType::getUnqual(HelperFunctionParameterTy);
Params.push_back(HelperFunctionParameterTyP);
}
llvm::FunctionType * HelperFunctionType =
llvm::FunctionType::get(F->getReturnType(),
Params,
/* IsVarArgs = */false);
HelperFunction =
llvm::Function::Create(HelperFunctionType,
llvm::GlobalValue::ExternalLinkage,
HelperFunctionName,
M);
HelperFunction->addFnAttr(llvm::Attribute::NoInline);
HelperFunction->setCallingConv(F->getCallingConv());
// Create helper function body
{
llvm::Argument *HelperFunctionParameter =
&(*HelperFunction->arg_begin());
llvm::BasicBlock *BB =
llvm::BasicBlock::Create(mLLVMContext, "entry", HelperFunction);
llvm::IRBuilder<> *IB = new llvm::IRBuilder<>(BB);
llvm::SmallVector<llvm::Value*, 6> Params;
llvm::Value *Idx[2];
Idx[0] =
llvm::ConstantInt::get(llvm::Type::getInt32Ty(mLLVMContext), 0);
// getelementptr and load instruction for all elements in
// parameter .p
for (size_t i = 0; i < EF->getNumParameters(); i++) {
// getelementptr
Idx[1] = llvm::ConstantInt::get(
llvm::Type::getInt32Ty(mLLVMContext), i);
llvm::Value *Ptr =
IB->CreateInBoundsGEP(HelperFunctionParameter, Idx);
// load
llvm::Value *V = IB->CreateLoad(Ptr);
Params.push_back(V);
}
// Call and pass the all elements as parameter to F
llvm::CallInst *CI = IB->CreateCall(F, Params);
CI->setCallingConv(F->getCallingConv());
if (F->getReturnType() == llvm::Type::getVoidTy(mLLVMContext))
IB->CreateRetVoid();
else
IB->CreateRet(CI);
delete IB;
}
}
ExportFuncInfo.push_back(
llvm::MDString::get(mLLVMContext, HelperFunctionName.c_str()));
}
mExportFuncMetadata->addOperand(
llvm::MDNode::get(mLLVMContext, ExportFuncInfo));
ExportFuncInfo.clear();
}
}
// Dump export function info
if (mContext->hasExportForEach()) {
if (mExportForEachNameMetadata == NULL) {
mExportForEachNameMetadata =
M->getOrInsertNamedMetadata(RS_EXPORT_FOREACH_NAME_MN);
}
if (mExportForEachSignatureMetadata == NULL) {
mExportForEachSignatureMetadata =
M->getOrInsertNamedMetadata(RS_EXPORT_FOREACH_MN);
}
llvm::SmallVector<llvm::Value*, 1> ExportForEachName;
llvm::SmallVector<llvm::Value*, 1> ExportForEachInfo;
for (RSContext::const_export_foreach_iterator
I = mContext->export_foreach_begin(),
E = mContext->export_foreach_end();
I != E;
I++) {
const RSExportForEach *EFE = *I;
ExportForEachName.push_back(
llvm::MDString::get(mLLVMContext, EFE->getName().c_str()));
mExportForEachNameMetadata->addOperand(
llvm::MDNode::get(mLLVMContext, ExportForEachName));
ExportForEachName.clear();
ExportForEachInfo.push_back(
llvm::MDString::get(mLLVMContext,
llvm::utostr_32(EFE->getSignatureMetadata())));
mExportForEachSignatureMetadata->addOperand(
llvm::MDNode::get(mLLVMContext, ExportForEachInfo));
ExportForEachInfo.clear();
}
}
// Dump export type info
if (mContext->hasExportType()) {
llvm::SmallVector<llvm::Value*, 1> ExportTypeInfo;
for (RSContext::const_export_type_iterator
I = mContext->export_types_begin(),
E = mContext->export_types_end();
I != E;
I++) {
// First, dump type name list to export
const RSExportType *ET = I->getValue();
ExportTypeInfo.clear();
// Type name
ExportTypeInfo.push_back(
llvm::MDString::get(mLLVMContext, ET->getName().c_str()));
if (ET->getClass() == RSExportType::ExportClassRecord) {
const RSExportRecordType *ERT =
static_cast<const RSExportRecordType*>(ET);
if (mExportTypeMetadata == NULL)
mExportTypeMetadata =
M->getOrInsertNamedMetadata(RS_EXPORT_TYPE_MN);
mExportTypeMetadata->addOperand(
llvm::MDNode::get(mLLVMContext, ExportTypeInfo));
// Now, export struct field information to %[struct name]
std::string StructInfoMetadataName("%");
StructInfoMetadataName.append(ET->getName());
llvm::NamedMDNode *StructInfoMetadata =
M->getOrInsertNamedMetadata(StructInfoMetadataName);
llvm::SmallVector<llvm::Value*, 3> FieldInfo;
slangAssert(StructInfoMetadata->getNumOperands() == 0 &&
"Metadata with same name was created before");
for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
FE = ERT->fields_end();
FI != FE;
FI++) {
const RSExportRecordType::Field *F = *FI;
// 1. field name
FieldInfo.push_back(llvm::MDString::get(mLLVMContext,
F->getName().c_str()));
// 2. field type name
FieldInfo.push_back(
llvm::MDString::get(mLLVMContext,
F->getType()->getName().c_str()));
StructInfoMetadata->addOperand(
llvm::MDNode::get(mLLVMContext, FieldInfo));
FieldInfo.clear();
}
} // ET->getClass() == RSExportType::ExportClassRecord
}
}
return;
}
RSBackend::~RSBackend() {
return;
}
} // namespace slang
| 34.511673 | 80 | 0.593889 | [
"object",
"vector"
] |
3fbfddd64bf7aff386229102601197c1ffde1aaa | 2,253 | cxx | C++ | 1.5 Secretary Swap/main.cxx | SemenMartynov/openedu-itmo-algorithms | 93697a1ac4de2300a9140d8752de7851743c0426 | [
"MIT"
] | null | null | null | 1.5 Secretary Swap/main.cxx | SemenMartynov/openedu-itmo-algorithms | 93697a1ac4de2300a9140d8752de7851743c0426 | [
"MIT"
] | null | null | null | 1.5 Secretary Swap/main.cxx | SemenMartynov/openedu-itmo-algorithms | 93697a1ac4de2300a9140d8752de7851743c0426 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
int main(int argc, char **argv)
{
std::vector<int> nums;
size_t nums_c = 0;
int item = 0;
bool item_in_proccess = false;
bool item_is_negative = false;
std::ifstream fin("input.txt");
char buf[4096];
do
{
fin.read(buf, sizeof(buf));
int k = fin.gcount();
for (int i = 0; i != k + 1; ++i)
{
switch (buf[i])
{
case '\n':
case ' ':
case '\0':
if (item_in_proccess)
{
if (nums_c)
{
if (item_is_negative)
item *= -1;
nums.push_back(item);
}
else
{
nums_c = item;
nums.reserve(nums_c);
}
}
item = 0;
item_in_proccess = false;
item_is_negative = false;
break;
case '-':
item_is_negative = true;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
item_in_proccess = true;
item = 10 * item + buf[i] - '0';
break;
default:
std::cerr << "NaN" << std::endl;
}
}
} while (fin);
const char out_file_name[] = "output.txt";
FILE *pFile = fopen(out_file_name, "w");
// sort
for (size_t i = 0; i != nums_c - 1; ++i)
{
size_t min = i;
for (size_t j = i + 1; j != nums_c; ++j)
{
if (nums[j] < nums[min])
{
min = j;
}
}
if (min != i)
{
std::swap(nums[i], nums[min]);
fprintf(pFile, "Swap elements at indices %d and %d.\n", i + 1, min + 1);
}
}
fprintf(pFile, "No more swaps needed.\n");
fclose(pFile);
return 0;
} | 24.225806 | 84 | 0.363515 | [
"vector"
] |
3fc542139bb58f64379d7a7a4962d01cb1e088f4 | 760 | hpp | C++ | PO_class/assignment_2/cplex/include/Data.hpp | ItamarRocha/Operations-Research | 55c4d54959555c3b9d54641e76eb6cfb2c011a2c | [
"MIT"
] | 7 | 2020-07-04T01:50:12.000Z | 2021-06-03T21:54:52.000Z | PO_class/assignment_2/cplex/include/Data.hpp | ItamarRocha/Operations-Research | 55c4d54959555c3b9d54641e76eb6cfb2c011a2c | [
"MIT"
] | null | null | null | PO_class/assignment_2/cplex/include/Data.hpp | ItamarRocha/Operations-Research | 55c4d54959555c3b9d54641e76eb6cfb2c011a2c | [
"MIT"
] | null | null | null | #ifndef _DATA_H_
#define _DATA_H_
#include <vector>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <chrono>
#define N_MODES 3
using namespace std::chrono;
class Data
{
private:
int N_tasks;
int N_days;
int penalty;
int max_duration;
std::vector<std::vector<int>> costs_matrix;
std::vector<std::vector<int>> days_taken_matrix;
std::vector<std::pair<int, int>> precedences;
public:
Data(char* filePath);
int getNTasks();
int getNDays();
int getPenalty();
std::vector<std::pair<int, int>> getPrecedences();
int getCost(int i, int k);
int getDaysTaken(int i, int k);
int getMaxDuration();
};
#endif
| 16.170213 | 58 | 0.597368 | [
"vector"
] |
3fd209e524ba93b4edfe51c06d55a03f918712d2 | 3,477 | hh | C++ | Shared/BrainCloudEvent.hh | pascalf1309/braincloud-objc | d3519eb26d753515a0d57d2ce07fe26399c14fac | [
"Apache-2.0"
] | null | null | null | Shared/BrainCloudEvent.hh | pascalf1309/braincloud-objc | d3519eb26d753515a0d57d2ce07fe26399c14fac | [
"Apache-2.0"
] | 1 | 2019-11-30T17:08:15.000Z | 2019-11-30T17:08:15.000Z | Shared/BrainCloudEvent.hh | pascalf1309/braincloud-objc | d3519eb26d753515a0d57d2ce07fe26399c14fac | [
"Apache-2.0"
] | null | null | null | //
// BrainCloudEvent.h
// brainCloudClientObjc
//
// Created by Hill, Bradley on 2015-08-12.
// Copyright (c) 2016 bitHeads. All rights reserved.
//
#pragma once
#import <Foundation/Foundation.h>
#import "BrainCloudCompletionBlocks.hh"
@class BrainCloudClient;
@interface BrainCloudEvent : NSObject
/**
* Initializes the brainCloudService
*/
- (instancetype) init: (BrainCloudClient*) client;
/**
* Sends an event to the designated player id with the attached json data.
* Any events that have been sent to a player will show up in their
* incoming event mailbox. If the recordLocally flag is set to true,
* a copy of this event (with the exact same event id) will be stored
* in the sending player's "sent" event mailbox.
*
* Note that the list of sent and incoming events for a player is returned
* in the "ReadPlayerState" call (in the BrainCloudPlayer module).
*
* Service Name - event
* Service Operation - SEND
*
* @param toProfileId The id of the player who is being sent the event
* @param eventType The user-defined type of the event.
* @param jsonEventData The user-defined data for this event encoded in JSON.
* @param completionBlock Block to call on return of successful server response
* @param errorCompletionBlock Block to call on return of unsuccessful server response
* @param cbObject User object sent to the completion blocks
*/
- (void)sendEvent:(NSString *)toProfileId
eventType:(NSString *)eventType
jsonEventData:(NSString *)eventData
completionBlock:(BCCompletionBlock)cb
errorCompletionBlock:(BCErrorCompletionBlock)ecb
cbObject:(BCCallbackObject)cbObject;
/**
* Updates an event in the player's incoming event mailbox.
*
* Service Name - event
* Service Operation - UPDATE_EVENT_DATA
*
* @param eventId The event id
* @param jsonEventData The user-defined data for this event encoded in JSON.
* @param completionBlock Block to call on return of successful server response
* @param errorCompletionBlock Block to call on return of unsuccessful server response
* @param cbObject User object sent to the completion blocks
*/
- (void)updateIncomingEventData:(NSString *)evId
jsonEventData:(NSString *)eventData
completionBlock:(BCCompletionBlock)cb
errorCompletionBlock:(BCErrorCompletionBlock)ecb
cbObject:(BCCallbackObject)cbObject;
/**
* Delete an event out of the player's incoming mailbox.
*
* Service Name - event
* Service Operation - DELETE_INCOMING
*
* @param evId The event id
* @param completionBlock Block to call on return of successful server response
* @param errorCompletionBlock Block to call on return of unsuccessful server response
* @param cbObject User object sent to the completion blocks
*/
- (void)deleteIncomingEvent:(NSString *)evId
completionBlock:(BCCompletionBlock)cb
errorCompletionBlock:(BCErrorCompletionBlock)ecb
cbObject:(BCCallbackObject)cbObject;
/**
* Get the events currently queued for the player.
*
* Service Name - event
* Service Operation - GET_EVENTS
*
* @param completionBlock Block to call on return of successful server response
* @param errorCompletionBlock Block to call on return of unsuccessful server response
* @param cbObject User object sent to the completion blocks
*/
- (void)getEvents:(BCCompletionBlock)cb
errorCompletionBlock:(BCErrorCompletionBlock)ecb
cbObject:(BCCallbackObject)cbObject;
@end
| 35.121212 | 85 | 0.745758 | [
"object"
] |
3fd9466d35ab3a00ffb8215502943450ef90bf7e | 3,030 | hpp | C++ | src/agl/engine/object.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/engine/object.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/engine/object.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | #pragma once
#include "geometry.hpp"
#include "material.hpp"
#include "uniform.hpp"
#include <agl/opengl/all.hpp>
#include <iostream>
#include <memory>
struct Object {
std::shared_ptr<Geometry> geometry = {};
std::shared_ptr<Material> material = {};
std::map<std::string, agl::Texture> textures = {};
std::map<std::string, std::unique_ptr<AnyUniform>> uniforms = {};
agl::VertexArray vertex_array = agl::vertex_array();
};
inline
void configure(Object& o) {
auto geometry = *o.geometry;
auto program = o.material->program;
auto& va = o.vertex_array;
if(geometry.indexes) {
element_buffer(va, *geometry.indexes);
}
for(int i = 0; i < agl::active_attributes(program); ++i) {
auto ai = agl::AttributeIndex(i);
auto aa = agl::active_attrib(program, ai);
auto attribute = geometry.attributes.at(aa.name);
auto bi = agl::BindingIndex<GLuint>(i);
attribute_binding(va, ai, bi);
attribute_format(va, ai,
attribute.size, attribute.type);
vertex_buffer(va, bi,
attribute.buffer, attribute.offset, attribute.stride);
enable(va, ai);
}
{ // Texture to uniform.
auto i = 0;
for(auto [name, t] : o.textures) {
o.uniforms[name] = std::make_unique<Uniform<GLuint>>(i);
}
}
}
inline
void render(const Object& object) {
auto& geometry = *object.geometry;
auto& material = *object.material;
for(auto& p : material.parameters) {
p();
}
for(auto c : material.capabilities) {
agl::enable(c);
}
auto program = material.program;
agl::use(program);
{ // Binding texture units.
auto i = 0;
for(auto [name, t] : object.textures) {
agl::bind(agl::TextureUnit(i++), t);
}
}
{ // Uniforms.
for(int idx = 0; idx < agl::active_uniforms(program); ++idx) {
auto ui = agl::UniformIndex(idx);
auto info = agl::active_uniform(
program, agl::UniformIndex<GLuint>(ui));
auto it = object.uniforms.find(info.name);
if(it != end(object.uniforms)) {
it->second->set(program, ui);
} else {
std::cout << "Missing " << info.name << " uniform." << std::endl;
}
}
}
{ // Draw.
agl::bind(object.vertex_array);
if(geometry.indexes) {
agl::draw_elements(
geometry.draw_mode,
geometry.primitive_count,
agl::DrawType::unsigned_int);
} else {
agl::draw_arrays(
geometry.draw_mode,
agl::Offset<GLint>(0),
geometry.primitive_count);
}
}
for(auto c : material.capabilities) {
agl::disable(c);
}
{ // Unbinding texture units.
auto i = 0;
for(auto [name, t] : object.textures) {
agl::unbind(agl::TextureUnit(i++));
}
}
}
| 27.545455 | 81 | 0.543234 | [
"geometry",
"render",
"object"
] |
3fe471731709d9d15b26e52ba199734e7901f523 | 4,940 | cpp | C++ | Code/Gfx/Source/D3D12/ShaderInputLayout.cpp | Mu-L/Luna-Engine-0.6 | 05ae1037f0d173589a535eb6ec2964f20d80e5c1 | [
"MIT"
] | 167 | 2020-06-17T06:09:41.000Z | 2022-03-13T20:31:26.000Z | Code/Gfx/Source/D3D12/ShaderInputLayout.cpp | Mu-L/Luna-Engine-0.6 | 05ae1037f0d173589a535eb6ec2964f20d80e5c1 | [
"MIT"
] | 2 | 2020-07-11T15:12:50.000Z | 2021-06-01T01:45:49.000Z | Code/Gfx/Source/D3D12/ShaderInputLayout.cpp | Mu-L/Luna-Engine-0.6 | 05ae1037f0d173589a535eb6ec2964f20d80e5c1 | [
"MIT"
] | 22 | 2020-06-12T02:26:10.000Z | 2022-01-02T14:04:32.000Z | // Copyright 2018-2020 JXMaster. All rights reserved.
/*
* @file ShaderInputLayout.cpp
* @author JXMaster
* @date 2020/3/14
*/
#include "ShaderInputLayout.hpp"
#ifdef LUNA_GFX_D3D12
namespace Luna
{
namespace Gfx
{
namespace D3D12
{
RV ShaderInputLayout::init(const ShaderInputLayoutDesc& desc)
{
m_groups.resize(desc.num_groups);
for (u32 i = 0; i < desc.num_groups; ++i)
{
m_groups[i] = desc.groups[i];
}
D3D12_ROOT_SIGNATURE_DESC d;
d.NumStaticSamplers = 0;
d.pStaticSamplers = nullptr;
d.NumParameters = desc.num_groups;
D3D12_ROOT_PARAMETER* params = (D3D12_ROOT_PARAMETER*)alloca(sizeof(D3D12_ROOT_PARAMETER) * desc.num_groups);
d.pParameters = params;
u32 ranges_count = desc.num_groups;
D3D12_DESCRIPTOR_RANGE* ranges = (D3D12_DESCRIPTOR_RANGE*)alloca(sizeof(D3D12_DESCRIPTOR_RANGE) * ranges_count);
// for every group (view table).
for (u32 i = 0; i < desc.num_groups; ++i)
{
// One range per group.
const ShaderInputGroupDesc& group = desc.groups[i];
D3D12_ROOT_PARAMETER& param = params[i];
param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
param.DescriptorTable.NumDescriptorRanges = 1;
param.DescriptorTable.pDescriptorRanges = &(ranges[i]);
// for every range.
D3D12_DESCRIPTOR_RANGE& dest_range = ranges[i];
dest_range.BaseShaderRegister = group.base_shader_register;
dest_range.NumDescriptors = group.num_views;
dest_range.OffsetInDescriptorsFromTableStart = 0;
switch (group.type)
{
case EShaderInputGroupType::cbv:
dest_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
break;
case EShaderInputGroupType::sampler:
dest_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
break;
case EShaderInputGroupType::srv:
dest_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
break;
case EShaderInputGroupType::uav:
dest_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
break;
default:
lupanic();
break;
}
dest_range.RegisterSpace = 0;
switch (group.shader_visibility)
{
case EShaderVisibility::all:
param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
break;
case EShaderVisibility::pixel:
param.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
break;
case EShaderVisibility::vertex:
param.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
break;
case EShaderVisibility::domain:
param.ShaderVisibility = D3D12_SHADER_VISIBILITY_DOMAIN;
break;
case EShaderVisibility::geometry:
param.ShaderVisibility = D3D12_SHADER_VISIBILITY_GEOMETRY;
break;
case EShaderVisibility::hull:
param.ShaderVisibility = D3D12_SHADER_VISIBILITY_HULL;
break;
default:
lupanic();
break;
}
}
d.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE;
if ((desc.flags & EShaderInputLayoutFlag::allow_input_assembler_input_layout) != EShaderInputLayoutFlag::none)
{
d.Flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
}
if ((desc.flags & EShaderInputLayoutFlag::allow_stream_output) != EShaderInputLayoutFlag::none)
{
d.Flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT;
}
if ((desc.flags & EShaderInputLayoutFlag::deny_domain_shader_access) != EShaderInputLayoutFlag::none)
{
d.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS;
}
if ((desc.flags & EShaderInputLayoutFlag::deny_geometry_shader_access) != EShaderInputLayoutFlag::none)
{
d.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
}
if ((desc.flags & EShaderInputLayoutFlag::deny_hull_shader_access) != EShaderInputLayoutFlag::none)
{
d.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS;
}
if ((desc.flags & EShaderInputLayoutFlag::deny_pixel_shader_access) != EShaderInputLayoutFlag::none)
{
d.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;
}
if ((desc.flags & EShaderInputLayoutFlag::deny_vertex_shader_access) != EShaderInputLayoutFlag::none)
{
d.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS;
}
ComPtr<ID3DBlob> b;
ComPtr<ID3DBlob> err;
if (FAILED(D3D12SerializeRootSignature(&d, D3D_ROOT_SIGNATURE_VERSION_1_0, b.GetAddressOf(), err.GetAddressOf())))
{
get_error_object() = Error(BasicError::bad_system_call(), "Failed to create D3D12 root signature: %s", err->GetBufferPointer());
return BasicError::error_object();
}
if (FAILED(m_device->m_device->CreateRootSignature(0, b->GetBufferPointer(), b->GetBufferSize(), IID_PPV_ARGS(&m_rs))))
{
get_error_object() = Error(BasicError::bad_system_call(), "Failed to create D3D12 root signature.");
return BasicError::error_object();
}
return RV();
}
}
}
}
#endif | 35.285714 | 133 | 0.718016 | [
"geometry"
] |
3fe552badfa99f17ed325af63897519ea1516326 | 3,461 | cpp | C++ | run_cb.cpp | ricardaxel/bayesmix | c9fb79c2f6fb05783adf31dd31030440413ae9cb | [
"BSD-3-Clause"
] | null | null | null | run_cb.cpp | ricardaxel/bayesmix | c9fb79c2f6fb05783adf31dd31030440413ae9cb | [
"BSD-3-Clause"
] | null | null | null | run_cb.cpp | ricardaxel/bayesmix | c9fb79c2f6fb05783adf31dd31030440413ae9cb | [
"BSD-3-Clause"
] | 1 | 2020-12-21T21:24:49.000Z | 2020-12-21T21:24:49.000Z | #include <Eigen/Dense>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "src/includes.hpp"
using namespace std;
using namespace Eigen;
template <typename M>
M load_csv1(const std::string &path) {
// Use this if csv is separated with ","
std::ifstream indata;
indata.open(path);
std::string line;
std::vector<int> values;
uint rows = 0;
while (std::getline(indata, line)) {
std::stringstream lineStream(line);
std::string cell;
while (std::getline(lineStream, cell, ',')) {
values.push_back(std::stod(cell));
}
++rows;
}
return Map<const Matrix<typename M::Scalar, M::RowsAtCompileTime,
M::ColsAtCompileTime, RowMajor>>(
values.data(), rows, values.size() / rows);
}
template <typename M>
M load_csv2(const std::string &path) {
// use this if csv is searated with spaces " "
std::ifstream indata;
indata.open(path);
std::string line;
std::vector<int> values;
uint rows = 0;
while (std::getline(indata, line)) {
std::stringstream lineStream(line);
std::string cell;
while (std::getline(lineStream, cell, ' ')) {
values.push_back(std::stod(cell));
}
++rows;
}
return Map<const Matrix<typename M::Scalar, M::RowsAtCompileTime,
M::ColsAtCompileTime, RowMajor>>(
values.data(), rows, values.size() / rows);
}
int main(int argc, char const *argv[]) {
cout << "Credible-balls test" << endl;
if (argc != 6) {
throw domain_error(
"Syntax : ./run_cb filename_mcmc filename_pe filename_out loss rate");
}
string filename_mcmc =
argv[1]; // name of the file containing the mcmc samples
string filename_pe = argv[2]; // name of the file with the point estimate
string filename_out = argv[3]; // name of the file to save the output
int loss_type =
std::stoi(argv[4]); // 0: BinderLoss, 1: VI, 2: Normalized VI
double learning_rate =
stoi(argv[5]); // a good choice for "learning_rate" is 1 to 5
cout << "Learning rate: " << learning_rate << endl;
Eigen::MatrixXi mcmc, pe_tmp;
Eigen::VectorXi pe;
mcmc = load_csv2<MatrixXi>(filename_mcmc);
pe_tmp = load_csv1<MatrixXi>(filename_pe);
pe = pe_tmp.row(0);
cout << "Dimension of the point estimate: " << pe_tmp.cols() << endl;
cout << "Matrix with dimensions : " << mcmc.rows() << "*" << mcmc.cols()
<< " found." << endl;
CredibleBall CB =
CredibleBall(static_cast<LOSS_FUNCTION>(loss_type), mcmc, 0.05, pe);
CB.calculateRegion(learning_rate);
double r = CB.getRadius();
cout << "radius: " << r << "\n";
cout << "Vertical Upper Bound\n";
Eigen::VectorXi VUB = CB.VerticalUpperBound();
cout << "VUB cardinality: " << VUB.size() << " \n";
for (int i = 0; i < VUB.size(); i++) {
cout << "Index of the VUB element:" << VUB(i) << " ";
}
cout << "\n";
cout << "Vertical Lower Bound\n";
Eigen::VectorXi VLB = CB.VerticalLowerBound();
cout << "VLB cardinality: " << VLB.size() << " \n";
for (int i = 0; i < VLB.size(); i++) {
cout << "Index of the VLB element:" << VLB(i) << " ";
}
cout << "\n";
cout << "Horizontal Bound\n";
Eigen::VectorXi HB = CB.HorizontalBound();
cout << "HB cardinality: " << HB.size() << " \n";
for (int i = 0; i < HB.size(); i++) {
cout << "Index of the HB element:" << HB(i) << " ";
}
cout << "\n";
CB.sumary(HB, VUB, VLB, filename_out);
return 0;
}
| 29.581197 | 78 | 0.610228 | [
"vector"
] |
6847ddcac86821cf331b8eed51d4575186a1afcc | 1,500 | cpp | C++ | Volume_10/Number_2/Baerentzen2005/Appsrc/PointImpostors/PointRecord.cpp | kyeonghopark/jgt-code | 08bbcc298e12582e32cb56a52e70344c57689d73 | [
"MIT"
] | 415 | 2015-10-24T17:37:12.000Z | 2022-02-18T04:09:07.000Z | Volume_10/Number_2/Baerentzen2005/Appsrc/PointImpostors/PointRecord.cpp | kyeonghopark/jgt-code | 08bbcc298e12582e32cb56a52e70344c57689d73 | [
"MIT"
] | 8 | 2016-01-15T13:23:16.000Z | 2021-05-27T01:49:50.000Z | Volume_10/Number_2/Baerentzen2005/Appsrc/PointImpostors/PointRecord.cpp | kyeonghopark/jgt-code | 08bbcc298e12582e32cb56a52e70344c57689d73 | [
"MIT"
] | 77 | 2015-10-24T22:36:29.000Z | 2022-03-24T01:03:54.000Z | #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#include "PointRecord.h"
using namespace std;
bool save_points(const std::string& fname,
const std::vector<PointRecord>& points,
float unit_scale)
{
int f = creat(fname.data(), 0644);
if(f != -1)
{
char magic[] = "POINTS";
if(write(f,magic,7) == -1)
return false;
int N = points.size();
if(write(f, reinterpret_cast<char*>(&N), sizeof(int)) == -1)
return false;
if(write(f, reinterpret_cast<char*>(&unit_scale), sizeof(float)) == -1)
return false;
int sz = sizeof(PointRecord)* N;
if(write(f, reinterpret_cast<const char*>(&points[0]), sz) == -1)
return false;
close(f);
return true;
}
return false;
}
bool load_points(const std::string& fname,
std::vector<PointRecord>& points,
float& unit_scale)
{
int f = open(fname.data(), O_RDONLY);
if(f != -1)
{
char magic[7];
if(read(f,magic,7) == -1)
return false;
if(string(magic) != string("POINTS"))
return false;
int N;
if(read(f, reinterpret_cast<char*>(&N), sizeof(int)) == -1)
return false;
points.resize(N);
if(read(f, reinterpret_cast<char*>(&unit_scale), sizeof(float)) == -1)
return false;
int sz = sizeof(PointRecord)* N;
if(read(f, reinterpret_cast<char*>(&points[0]), sz) == -1)
return false;
close(f);
return true;
}
return false;
}
| 19.480519 | 75 | 0.598667 | [
"vector"
] |
6849d361e69c89ed27fd47aecb6c541644cae4b9 | 2,900 | cpp | C++ | src/main.cpp | victor-smirnov/dumbo-seastar | 4a9d57c927f64826b5bf138763569825f5ab0cb9 | [
"Apache-2.0"
] | 2 | 2017-12-15T07:14:53.000Z | 2019-09-07T12:49:01.000Z | src/main.cpp | victor-smirnov/dumbo-seastar | 4a9d57c927f64826b5bf138763569825f5ab0cb9 | [
"Apache-2.0"
] | null | null | null | src/main.cpp | victor-smirnov/dumbo-seastar | 4a9d57c927f64826b5bf138763569825f5ab0cb9 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 Victor Smirnov
//
// 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 <dumbo/v1/allocators/inmem/factory.hpp>
#include <dumbo/v1/tools/dumbo_iostreams.hpp>
#include <dumbo/v1/tools/aio_uuid.hpp>
#include <dumbo/v1/tools/aio_string.hpp>
#include <memoria/v1/memoria.hpp>
#include <memoria/v1/containers/set/set_factory.hpp>
#include <memoria/v1/core/tools/iobuffer/io_buffer.hpp>
#include <memoria/v1/core/tools/strings/string_codec.hpp>
#include <memoria/v1/core/tools/time.hpp>
#include <memoria/v1/core/tools/fixed_array.hpp>
#include <memoria/v1/core/tools/random.hpp>
#include <memoria/v1/core/tools/ticker.hpp>
#include "core/app-template.hh"
#include "core/sleep.hh"
#include "core/fstream.hh"
#include "core/shared_ptr.hh"
#include "core/thread.hh"
#include <algorithm>
#include <vector>
#include <type_traits>
#include <iostream>
#include <thread>
using namespace memoria::v1;
using namespace dumbo::v1;
namespace ss = seastar;
int main(int argc, char** argv)
{
MEMORIA_INIT(DumboProfile<>);
using Key = BigInt;
DumboInit<Set<Key>>();
try {
app_template app;
app.run(argc, argv, [&] {
return ss::async([&] {
auto alloc = SeastarInMemAllocator<>::create();
auto snp = alloc->master()->branch();
snp->parent();
snp->has_parent();
snp->describe();
snp->metadata();
alloc->describe_master();
auto map = create<Set<Key>>(snp, UUID::parse("b1197537-12eb-4dc7-811b-ee0491720fbc"));
for (int c = 0; c < 10000; c++)
{
map->insert_key(c);
}
snp->commit();
snp->set_as_master();
alloc->store("dumbo-data.dump");
std::cout << "Store created\n";
auto alloc1 = SeastarInMemAllocator<>::load("dumbo-data.dump");
alloc1->dump("dumbo-dump");
auto snp1 = alloc1->master();
auto map1 = snp1->find<Set<Key>>(UUID::parse("b1197537-12eb-4dc7-811b-ee0491720fbc"));
auto i1 = map1->begin();
while (!i1->isEnd())
{
std::cout << i1->key() << "\n";
i1->next();
}
snp1->dump("snp1.dump");
}).handle_exception([](auto eptr){
try {
std::rethrow_exception(eptr);
}
catch(Exception &e) {
std::cerr << "HANDLED: " << e.source() << ": " << e.message() << "\n";
}
return ::now();
});
});
}
catch(std::runtime_error &e) {
std::cerr << "Couldn't start application: " << e.what() << "\n";
return 1;
}
}
| 23.966942 | 90 | 0.657586 | [
"vector"
] |
68582866c6e23776a0359e8dd7913812c880a63f | 11,171 | cc | C++ | cc_code/src/hmm/hmm/peptide-hmm.test.cc | erisyon/whatprot | 176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c | [
"MIT"
] | null | null | null | cc_code/src/hmm/hmm/peptide-hmm.test.cc | erisyon/whatprot | 176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c | [
"MIT"
] | 1 | 2021-06-12T00:50:08.000Z | 2021-06-15T17:59:12.000Z | cc_code/src/hmm/hmm/peptide-hmm.test.cc | erisyon/whatprot | 176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c | [
"MIT"
] | 1 | 2021-06-11T19:34:43.000Z | 2021-06-11T19:34:43.000Z | /******************************************************************************\
* Author: Matthew Beauregard Smith *
* Affiliation: The University of Texas at Austin *
* Department: Oden Institute and Institute for Cellular and Molecular Biology *
* PI: Edward Marcotte *
* Project: Protein Fluorosequencing *
\******************************************************************************/
// Boost unit test framework (recommended to be the first include):
#include <boost/test/unit_test.hpp>
// File under test:
#include "peptide-hmm.h"
// Standard C++ library headers:
#include <cmath>
#include <functional>
#include <vector>
// Local project headers:
#include "common/dye-seq.h"
#include "common/error-model.h"
#include "common/radiometry.h"
#include "hmm/fit/error-model-fitter.h"
#include "hmm/precomputations/dye-seq-precomputations.h"
#include "hmm/precomputations/radiometry-precomputations.h"
#include "hmm/precomputations/universal-precomputations.h"
#include "hmm/state-vector/peptide-state-vector.h"
#include "hmm/step/binomial-transition.h"
#include "hmm/step/detach-transition.h"
#include "hmm/step/edman-transition.h"
#include "hmm/step/peptide-emission.h"
#include "hmm/step/step.h"
#include "tensor/tensor.h"
namespace whatprot {
namespace {
using boost::unit_test::tolerance;
using std::exp;
using std::function;
using std::log;
using std::sqrt;
using std::vector;
const double PI = 3.141592653589793238;
const double TOL = 0.000000001;
} // namespace
BOOST_AUTO_TEST_SUITE(hmm_suite)
BOOST_AUTO_TEST_SUITE(hmm_suite)
BOOST_AUTO_TEST_SUITE(peptide_hmm_suite)
BOOST_AUTO_TEST_CASE(constructor_test, *tolerance(TOL)) {
double p_edman_failure = 0.01;
double p_detach = 0.02;
double p_bleach = 0.03;
double p_dud = 0.04;
DistributionType dist_type = DistributionType::LOGNORMAL;
double mu = 1.0;
double sigma = 0.05;
double stuck_dye_ratio = 0.5;
double p_stuck_dye_loss = 0.08;
ErrorModel em(p_edman_failure,
p_detach,
p_bleach,
p_dud,
dist_type,
mu,
sigma,
stuck_dye_ratio,
p_stuck_dye_loss);
int num_channels = 2;
int max_num_dyes = 3;
UniversalPrecomputations universal_precomputations(em, num_channels);
universal_precomputations.set_max_num_dyes(max_num_dyes);
int num_timesteps = 4;
DyeSeq ds(num_channels, ".1.0.1.0.1"); // two in ch 0, three in ch 1.
DyeSeqPrecomputations dye_seq_precomputations(
ds, em, num_timesteps, num_channels);
Radiometry r(num_timesteps, num_channels);
r(0, 0) = 1.0;
r(0, 1) = 1.0;
r(1, 0) = 1.0;
r(1, 1) = 1.0;
r(2, 0) = 1.0;
r(2, 1) = 1.0;
r(3, 0) = 1.0;
r(3, 1) = 1.0;
RadiometryPrecomputations radiometry_precomputations(r, em, max_num_dyes);
PeptideHMM hmm(num_timesteps,
num_channels,
dye_seq_precomputations,
radiometry_precomputations,
universal_precomputations);
BOOST_ASSERT(hmm.tensor_shape.size() == 1 + num_channels);
BOOST_TEST(hmm.tensor_shape[0] == num_timesteps);
BOOST_TEST(hmm.tensor_shape[1] == 2 + 1); // extra is to have 0 & num dyes.
BOOST_TEST(hmm.tensor_shape[2] == 3 + 1); // extra is to have 0 & num dyes.
BOOST_ASSERT(hmm.steps.size()
== (3 + num_channels) * (num_timesteps - 1) + 1
+ num_channels);
vector<const Step<PeptideStateVector>*>::iterator step = hmm.steps.begin();
BOOST_TEST(*step == &universal_precomputations.dud_transitions[0]);
step++;
BOOST_TEST(*step == &universal_precomputations.dud_transitions[1]);
step++;
BOOST_TEST(*step == &radiometry_precomputations.peptide_emission);
step++;
BOOST_TEST(*step == &universal_precomputations.detach_transition);
step++;
BOOST_TEST(*step == &universal_precomputations.bleach_transitions[0]);
step++;
BOOST_TEST(*step == &universal_precomputations.bleach_transitions[1]);
step++;
BOOST_TEST(*step == &dye_seq_precomputations.edman_transition);
step++;
BOOST_TEST(*step == &radiometry_precomputations.peptide_emission);
step++;
BOOST_TEST(*step == &universal_precomputations.detach_transition);
step++;
BOOST_TEST(*step == &universal_precomputations.bleach_transitions[0]);
step++;
BOOST_TEST(*step == &universal_precomputations.bleach_transitions[1]);
step++;
BOOST_TEST(*step == &dye_seq_precomputations.edman_transition);
step++;
BOOST_TEST(*step == &radiometry_precomputations.peptide_emission);
step++;
BOOST_TEST(*step == &universal_precomputations.detach_transition);
step++;
BOOST_TEST(*step == &universal_precomputations.bleach_transitions[0]);
step++;
BOOST_TEST(*step == &universal_precomputations.bleach_transitions[1]);
step++;
BOOST_TEST(*step == &dye_seq_precomputations.edman_transition);
step++;
BOOST_TEST(*step == &radiometry_precomputations.peptide_emission);
}
BOOST_AUTO_TEST_CASE(probability_trivial_test, *tolerance(TOL)) {
double p_edman_failure = 0.0;
double p_detach = 0.0;
double p_bleach = 0.0;
double p_dud = 0.0;
DistributionType dist_type = DistributionType::OVERRIDE;
double mu = 1.0;
double sigma = 0.05;
double stuck_dye_ratio = 0.5;
double p_stuck_dye_loss = 0.08;
ErrorModel em(p_edman_failure,
p_detach,
p_bleach,
p_dud,
dist_type,
mu,
sigma,
stuck_dye_ratio,
p_stuck_dye_loss);
int num_channels = 0;
int max_num_dyes = 0;
UniversalPrecomputations up(em, num_channels);
up.set_max_num_dyes(max_num_dyes);
int num_timesteps = 1;
DyeSeq ds(num_channels, ""); // 0 in all channels.
DyeSeqPrecomputations dsp(ds, em, num_timesteps, num_channels);
Radiometry r(num_timesteps, num_channels);
RadiometryPrecomputations rp(r, em, max_num_dyes);
PeptideHMM hmm(num_timesteps, num_channels, dsp, rp, up);
BOOST_TEST(hmm.probability() == 1.0);
}
BOOST_AUTO_TEST_CASE(probability_sum_to_one_test, *tolerance(TOL)) {
// The idea here is that if the emission just causes a multiplication by one
// no matter what, then the transitions shouldn't matter; they should just
// be reallocating a probability of one between different states.
double p_edman_failure = 0.45;
double p_detach = 0.15;
double p_bleach = 0.35;
double p_dud = 0.25;
DistributionType dist_type = DistributionType::OVERRIDE;
double mu = 1.0;
double sigma = 0.05;
double stuck_dye_ratio = 0.5;
double p_stuck_dye_loss = 0.08;
ErrorModel em(p_edman_failure,
p_detach,
p_bleach,
p_dud,
dist_type,
mu,
sigma,
stuck_dye_ratio,
p_stuck_dye_loss);
int num_channels = 2;
int max_num_dyes = 5;
UniversalPrecomputations up(em, num_channels);
up.set_max_num_dyes(max_num_dyes);
int num_timesteps = 3;
DyeSeq ds(num_channels, "10.01111"); // two in ch 0, five in ch 1.
DyeSeqPrecomputations dsp(ds, em, num_timesteps, num_channels);
Radiometry r(num_timesteps, num_channels);
r(0, 0) = 0.0;
r(0, 1) = 0.1;
r(1, 0) = 1.0;
r(1, 1) = 1.1;
r(2, 0) = 2.0;
r(2, 1) = 2.1;
RadiometryPrecomputations rp(r, em, max_num_dyes);
PeptideHMM hmm(num_timesteps, num_channels, dsp, rp, up);
BOOST_TEST(hmm.probability() == 1.0);
}
BOOST_AUTO_TEST_CASE(probability_more_involved_test, *tolerance(TOL)) {
// This is essentially a "no change" test. It assumes that the function was
// giving the correct result on November 10, 2020.
double p_edman_failure = 0.06;
double p_detach = 0.05;
double p_bleach = 0.05;
double p_dud = 0.07;
DistributionType dist_type = DistributionType::LOGNORMAL;
double mu = log(1.0);
double sigma = 0.16;
double stuck_dye_ratio = 0.5;
double p_stuck_dye_loss = 0.08;
ErrorModel em(p_edman_failure,
p_detach,
p_bleach,
p_dud,
dist_type,
mu,
sigma,
stuck_dye_ratio,
p_stuck_dye_loss);
int num_channels = 2;
int max_num_dyes = 5;
UniversalPrecomputations up(em, num_channels);
up.set_max_num_dyes(max_num_dyes);
int num_timesteps = 3;
DyeSeq ds(num_channels, "10.01111"); // two in ch 0, five in ch 1.
DyeSeqPrecomputations dsp(ds, em, num_timesteps, num_channels);
Radiometry r(num_timesteps, num_channels);
r(0, 0) = 5.0;
r(0, 1) = 2.0;
r(1, 0) = 5.0;
r(1, 1) = 1.0;
r(2, 0) = 4.0;
r(2, 1) = 1.0;
RadiometryPrecomputations rp(r, em, max_num_dyes);
PeptideHMM hmm(num_timesteps, num_channels, dsp, rp, up);
BOOST_TEST(hmm.probability() == 3.2324422559808915e-23);
}
BOOST_AUTO_TEST_CASE(improve_fit_test, *tolerance(TOL)) {
double p_edman_failure = 0.01;
double p_detach = 0.02;
double p_bleach = 0.03;
double p_dud = 0.04;
DistributionType dist_type = DistributionType::LOGNORMAL;
double mu = 1.0;
double sigma = 0.05;
double stuck_dye_ratio = 0.5;
double p_stuck_dye_loss = 0.08;
ErrorModel em(p_edman_failure,
p_detach,
p_bleach,
p_dud,
dist_type,
mu,
sigma,
stuck_dye_ratio,
p_stuck_dye_loss);
int num_channels = 2;
int max_num_dyes = 3;
UniversalPrecomputations universal_precomputations(em, num_channels);
universal_precomputations.set_max_num_dyes(max_num_dyes);
int num_timesteps = 4;
DyeSeq ds(num_channels, ".1.0.1.0.1"); // two in ch 0, three in ch 1.
DyeSeqPrecomputations dye_seq_precomputations(
ds, em, num_timesteps, num_channels);
Radiometry r(num_timesteps, num_channels);
r(0, 0) = 1.0;
r(0, 1) = 1.0;
r(1, 0) = 1.0;
r(1, 1) = 1.0;
r(2, 0) = 1.0;
r(2, 1) = 1.0;
r(3, 0) = 1.0;
r(3, 1) = 1.0;
RadiometryPrecomputations radiometry_precomputations(r, em, max_num_dyes);
PeptideHMM hmm(num_timesteps,
num_channels,
dye_seq_precomputations,
radiometry_precomputations,
universal_precomputations);
ErrorModelFitter emf;
hmm.improve_fit(&emf);
// There are no BOOST_TEST statements because setting up a proper test for
// this function is very difficult. We still have the test though as a no
// crash test.
}
BOOST_AUTO_TEST_SUITE_END() // peptide_hmm_suite
BOOST_AUTO_TEST_SUITE_END() // hmm_suite
BOOST_AUTO_TEST_SUITE_END() // hmm_suite
} // namespace whatprot
| 36.387622 | 80 | 0.62528 | [
"vector",
"model"
] |
6859875627d32ead1e8f69727fc7e2981abee694 | 16,422 | cpp | C++ | sizeTest.cpp | dib-lab/2020-paper-mqf-benchmarks | 29245836d142b4912c120f3e3899042e972e959c | [
"BSD-3-Clause"
] | 1 | 2020-07-15T20:27:53.000Z | 2020-07-15T20:27:53.000Z | sizeTest.cpp | dib-lab/2020-paper-mqf-benchmarks | 29245836d142b4912c120f3e3899042e972e959c | [
"BSD-3-Clause"
] | null | null | null | sizeTest.cpp | dib-lab/2020-paper-mqf-benchmarks | 29245836d142b4912c120f3e3899042e972e959c | [
"BSD-3-Clause"
] | 1 | 2021-03-22T01:09:08.000Z | 2021-03-22T01:09:08.000Z | #include "gqf.h"
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h>
#include<iostream>
#include <fstream>
#include "hashutil.h"
#include "kmer.h"
#include <vector>
#include <chrono>
#include<cmath>
#include <random>
#include <algorithm>
#include "Benchmark_Utils_Script/generators.hpp"
#include "Benchmark_Utils_Script/countingStructure.hpp"
#include "CLI11.hpp"
#include "countmin-khmer/storage.hh"
using namespace std;
#include <iostream>
inline uint64_t estimateMemory(uint64_t nslots, uint64_t slotSize, uint64_t fcounter, uint64_t tagSize) {
uint64_t SLOTS_PER_BLOCK_t = 64;
uint64_t xnslots = nslots + 10 * sqrt((double) nslots);
uint64_t nblocks = (xnslots + SLOTS_PER_BLOCK_t - 1) / SLOTS_PER_BLOCK_t;
uint64_t blocksize = 17;
return ((nblocks) * (blocksize + 8 * (slotSize + fcounter + tagSize))) / 1024;
}
bool isEnough(vector<uint64_t>& histogram, uint64_t noSlots, uint64_t fixedSizeCounter, uint64_t slotSize) {
// cout<<"noSlots= "<<noSlots<<endl
// <<"fcounter= "<<fixedSizeCounter<<endl
// <<"slot size= "<<numHashBits<<endl;
noSlots = (uint64_t) ((double) noSlots * 0.95);
for (uint64_t i = 1; i < 1000; i++) {
uint64_t usedSlots = 1;
if (i > ((1ULL) << fixedSizeCounter) - 1) {
uint64_t nSlots2 = 0;
__uint128_t capacity;
do {
nSlots2++;
capacity = ((__uint128_t) (1ULL) << (nSlots2 * slotSize + fixedSizeCounter)) - 1;
// cout<<"slots num "<<nSlots2<<" "<<capacity<<endl;
} while ((__uint128_t) i > capacity);
usedSlots += nSlots2;
}
//cout<<"i= "<<i<<"->"<<usedSlots<<" * "<<histogram[i]<<endl;
if (noSlots >= (usedSlots * histogram[i])) {
noSlots -= (usedSlots * histogram[i]);
} else {
// cout<<"failed"<<endl<<endl;
return false;
}
}
//cout<<"success"<<endl<<endl;
return true;
}
void estimateMemRequirement(vector<uint64_t>& histogram,
uint64_t numHashBits, uint64_t tagSize,
uint64_t *res_noSlots, uint64_t *res_fixedSizeCounter, uint64_t *res_memory) {
uint64_t noDistinctKmers = 0, totalNumKmers=0;
*res_memory = numeric_limits<uint64_t>::max();
for (int i = 8; i < 64; i++) {
uint64_t noSlots = (1ULL) << i;
if (noSlots < noDistinctKmers)
continue;
bool moreWork = false;
uint64_t slotSize = numHashBits - log2((double) noSlots);
for (uint64_t fixedSizeCounter = 1; fixedSizeCounter < slotSize; fixedSizeCounter++) {
if (isEnough(histogram, noSlots, fixedSizeCounter, slotSize)) {
uint64_t tmpMem = estimateMemory(noSlots, slotSize, fixedSizeCounter, tagSize);
if (*res_memory > tmpMem) {
*res_memory = tmpMem;
*res_fixedSizeCounter = fixedSizeCounter;
*res_noSlots = i;
moreWork = true;
} else {
break;
}
}
}
if (!moreWork && *res_memory != numeric_limits<uint64_t>::max())
break;
}
if (*res_memory == numeric_limits<uint64_t>::max()) {
throw std::overflow_error(
"Data limits exceeds MQF capabilities(> uint64). Check if ntcard file is corrupted");
}
}
int main(int argc, char const *argv[]) {
cout<<"Command = ";
for(int i=0;i<argc;i++)
{
cout<<argv[i]<<" ";
}
cout<<endl;
CLI::App app;
string distribution="zipfian";
double zipifian_coefficient=3.0;
double uniform_coefficient=5;
string dataStrucureInput="mqf";
double fpr=0.01;
uint64_t countErrorMargin=5;
uint64_t kSize=25;
string fqPath="";
uint64_t qbits=25;
uint64_t num_elements=10000000;
app.add_option("-d,--distribution",distribution,
"Distributions which items will be drew from. options are zipfian,kmers. Default is zipfian");
app.add_option("-z",zipifian_coefficient,"Zipifian Coeffiecient. Default =3")->group("Zipfian Distribution Options");
app.add_option("-u",uniform_coefficient,
"Frequency of items in the uinform distribution. Default =5")
->group("Uniform Distribution Options");
app.add_option("-k",fqPath,"Fastq file to draw the kmers");
// app.add_option("-s,--datastructure",dataStrucureInput,
// "Datastructure to be benchmarked. Options are mqf, lmqf, cqf, and countmin. Default is mqf");
// app.add_option("-s,--size",qbits
// ,"No slots equals to 2^(s). default is 25")
// ->group("Counting Strucutre Options");
app.add_option("-f,--fpr",fpr
,"False positive rate. default is 0.01")
->group("Counting Strucutre Options");
app.add_option("-n,--num_elements",num_elements,
"Number of elements to generate. Default is 10M");
app.add_option("-c,--countsError",countErrorMargin
,"Counts error margin. default is 5")
->group("Countmin options");
CLI11_PARSE(app, argc, (char**)argv);
uint64_t p=(uint64_t)log2((double)num_elements/fpr);
cout<<"Num Hashbits= "<<p<<endl;
uint64_t estimatedQ=log2((double)num_elements*1.1)+1;// worst case zipifian distribution
cout<<"Estimated Q= "<<estimatedQ<<endl;
vector<countingStructure*> dataStructures;
dataStructures.push_back(new MQF(estimatedQ+1,p-estimatedQ-1,1));
dataStructures.push_back(new MQF(estimatedQ,p-estimatedQ,5));
dataStructures.push_back(new MQF(estimatedQ,p-estimatedQ,4));
dataStructures.push_back(new MQF(estimatedQ,p-estimatedQ,3));
dataStructures.push_back(new MQF(estimatedQ,p-estimatedQ,2));
dataStructures.push_back(new MQF(estimatedQ,p-estimatedQ,1));
dataStructures.push_back(new MQF(estimatedQ-1,p-estimatedQ+1,5));
dataStructures.push_back(new MQF(estimatedQ-1,p-estimatedQ+1,4));
dataStructures.push_back(new MQF(estimatedQ-1,p-estimatedQ+1,3));
dataStructures.push_back(new MQF(estimatedQ-1,p-estimatedQ+1,2));
dataStructures.push_back(new MQF(estimatedQ-1,p-estimatedQ+1,1));
dataStructures.push_back(new MQF(estimatedQ-2,p-estimatedQ+2,5));
dataStructures.push_back(new MQF(estimatedQ-2,p-estimatedQ+2,4));
dataStructures.push_back(new MQF(estimatedQ-2,p-estimatedQ+2,3));
dataStructures.push_back(new MQF(estimatedQ-2,p-estimatedQ+2,2));
dataStructures.push_back(new MQF(estimatedQ-2,p-estimatedQ+2,1));
dataStructures.push_back(new CQF(estimatedQ+1,p-estimatedQ-1));
dataStructures.push_back(new CQF(estimatedQ,p-estimatedQ));
dataStructures.push_back(new CQF(estimatedQ-1,p-estimatedQ+1));
dataStructures.push_back(new CQF(estimatedQ-2,p-estimatedQ+2));
//dataStructures.push_back(new LMQF(estimatedQ-1,estimatedQ-2,p-estimatedQ+1,2));
//dataStructures.push_back(new LMQF(estimatedQ-1,estimatedQ-3,p-estimatedQ+1,2));
uint64_t BufferSize=num_elements/25;
uint64_t num_queries=100;
int countMinDepth=log(1.0/(fpr))+1;
double e=2.71828;
// uint64_t countMinWidth =e*(double)num_elements/(double) (countErrorMargin+1) ;
uint64_t countMinWidth=dataStructures[0]->size/countMinDepth;
//cout<<"Count Min Sketch Width= "<<countMinWidth<<endl;
//cout<<"Count Min Sketch Depth= "<<countMinDepth<<endl;
//dataStructures.push_back(new countminKhmer((uint64_t)((double)countMinWidth*1.2),countMinDepth));
// dataStructures.push_back(new countminKhmer((uint64_t)((double)countMinWidth*1),countMinDepth));
// dataStructures.push_back(new countminKhmer((uint64_t)((double)countMinWidth*0.8),countMinDepth));
//dataStructures.push_back(new countmin(countMinWidth,countMinDepth));
uint64_t range=(1ULL<<(int)p);
srand (1);
map<uint64_t,uint64_t> gold;
generator *g;
if(distribution=="uniform")
{
g=new uniformGenerator(num_elements,range,uniform_coefficient);
}
else if(distribution=="kmers")
{
g= new kmersGenerator(num_elements,fqPath,kSize);
}
else if(distribution=="zipfian"){
g= new zipfGenerator(num_elements,range,zipifian_coefficient);
}
else{
cout<<"Unknown Distribution"<<endl;
return -1;
}
//
//
uint64_t countedKmers=0;
vector<uint64_t> insertions(BufferSize);
//set<uint64_t> succesfullQueries(num_queries);
uint64_t queryTop=0;
// auto now = std::chrono::high_resolution_clock::now();
// auto prev=now;
// now = std::chrono::high_resolution_clock::now();
//
//
//
// vector<pair<int,int> > lmqfSpace;
// vector<pair<double,double> > result;
// vector<pair<double,double> > results_slotsUsed;
// cout<<"Capacity\t1M insertions per second"<<endl;
// double capacity=dataStructure->space();
//
//
// uint64_t old_capacity=capacity;
// uint64_t insertiontime=0;
// uint64_t querytime=0;
// uint64_t curr_item;
auto now=std::chrono::high_resolution_clock::now();
auto prev=std::chrono::high_resolution_clock::now();
auto microseconds = (chrono::duration_cast<chrono::microseconds>(now-prev)).count();
uint64_t curr_item;
// check the size of cqf
while(g->hasMore())
{
// cerr<<"Number of unique items generated so far ="<<g->nunique_items<<endl;
uint64_t tmp_inserted=0;
for(int j=0;j<BufferSize;j++){
if(!g->getElement(curr_item))
break;
tmp_inserted++;
// cout<<"sss"<<curr_item<<"\n";
insertions[j]=curr_item;
// gold[curr_item]++;
// if(queryTop<num_queries)
// succesfullQueries[queryTop++]=curr_item;
}
// cerr<<"Finished generation"<<endl;
countedKmers+=BufferSize;
for(auto structure: dataStructures){
if(structure->space()>=95)
{
structure->failed=true;
continue;
}
// cerr<<"Inserting "<<BufferSize<<" to "<<structure->name<<"("<<structure->space()<<")"<<endl;
prev=std::chrono::high_resolution_clock::now();
for(int j=0;j<tmp_inserted;j++){
structure->insert(insertions[j],1);
if(structure->space()>=95)
{
structure->failed=true;
break;
}
}
now=std::chrono::high_resolution_clock::now();
microseconds = (chrono::duration_cast<chrono::microseconds>(now-prev)).count();
microseconds/=1000;
structure->insertionTime+=microseconds;
}
}
cout<<"Final Number of unique items generated="<<g->nunique_items<<endl;
// for(auto structure: dataStructures){
// if(structure->failed)
// {
// structure->fpr=1;
// structure->fpr5=1;
// structure->fpr10=1;
// structure->fpr20=1;
// structure->fpr30=1;
// continue;
//
// }
// cerr<<"Querying from "<<structure->name<<endl;
// prev=std::chrono::high_resolution_clock::now();
//
// for(auto a :g->newItems)
// {
// uint64_t tmpCount=structure->query(a);
//
// if(tmpCount>0)
// structure->fpr++;
// if(tmpCount>5)
// structure->fpr5++;
// if(tmpCount>10)
// structure->fpr10++;
// if(tmpCount>20)
// structure->fpr20++;
// if(tmpCount>30)
// structure->fpr30++;
// }
// uint64_t numQueries5=0,
// numQueries10=0,
// numQueries20=0,
// numQueries30=0;
//
// // for(auto it=gold.begin();it!=gold.end();it++)
// // {
// // uint64_t tmpCount=structure->query(it->first);
// // if(it->second<5){
// // numQueries5++;
// // if(tmpCount>5)
// // structure->fpr5++;
// // }
// // if(it->second<10){
// // numQueries10++;
// // if(tmpCount>10)
// // structure->fpr10++;
// // }
// // if(it->second<20){
// // numQueries20++;
// // if(tmpCount>20)
// // structure->fpr20++;
// // }
// // if(it->second<30){
// // numQueries30++;
// // if(tmpCount>30)
// // structure->fpr30++;
// // }
// //
// // }
// // now=std::chrono::high_resolution_clock::now();
// // structure->fpr/=double(g->newItems.size());
// // structure->fpr5/=double(g->newItems.size()+numQueries5);
// // structure->fpr10/=double(g->newItems.size()+numQueries10);
// // structure->fpr20/=double(g->newItems.size()+numQueries20);
// // structure->fpr30/=double(g->newItems.size()+numQueries30);
//
// microseconds = (chrono::duration_cast<chrono::microseconds>(now-prev)).count();
// microseconds/=1000;
// structure->queryTime+=microseconds;
//
//
// }
cout<<"Number of insertions = "<<countedKmers<<endl;
// cout<<"Number of succesfull lookups = "<<num_queries<<endl;
// cout<<"Number of non succesfull lookups = "<<num_queries<<endl;
cout<<"Name"<<"\t"
<<"Parametes"<<"\t"
<<"Size"<<"\t"
<<"Space"<<"\t"
<<"Succeded"<<"\t"
<<"fpr"<<"\t"
<<"fpr5"<<"\t"
<<"fpr10"<<"\t"
<<"fpr20"<<"\t"
<<"fpr30"<<endl;
for(auto structure: dataStructures){
cout<<structure->name<<"\t"
<<structure->parameters<<"\t"
<<structure->size/(1024*1024)<<"MB\t"
<<structure->space()<<"\t"
<<!structure->failed<<"\t"
<<structure->fpr<<"\t"
<<structure->fpr5<<"\t"
<<structure->fpr10<<"\t"
<<structure->fpr20<<"\t"
<<structure->fpr30<<endl;
}
vector<uint64_t> histogram(10000);
for(auto structure: dataStructures)
{
if(structure->name=="MQF" && !structure->failed)
{
QF* mqf=((MQF*)structure)->get_MQF();
QFi iterator;
qf_iterator(mqf,&iterator,0);
while(!qfi_end(&iterator))
{
uint64_t key,count,tag;
qfi_get(&iterator,&key,&tag,&count);
histogram[count]++;
qfi_next(&iterator);
}
uint64_t res_noSlots,res_fixedSizeCounter, res_memory;
estimateMemRequirement(histogram,p,0,&res_noSlots, &res_fixedSizeCounter,&res_memory);
cout<<"Estimated Q = "<<res_noSlots<<endl;
cout<<"Estimated Fixed Size counter = "<<res_fixedSizeCounter<<endl;
cout<<"Estimated memory = "<<res_memory<<endl;
break;
}
}
//
// now = std::chrono::high_resolution_clock::now();
// if(dataStrucureInput=="bmqf")
// {
//
// }
// else{
// for(int j=0;j<BufferSize;j++)
// {
// dataStructure->query(input[j]);
// }
// }
//
// prev=now;
// now = std::chrono::high_resolution_clock::now();
//
// microseconds = (chrono::duration_cast<chrono::microseconds>(now-prev)).count();
// querytime=microseconds;
// {
// double millionInsertionSecond=(double)countedKmers/(double)insertiontime;
// cout<<capacity<<"\t"<<g->get_generated_elements()<<"\t"<<millionInsertionSecond;
// if (dataStrucureInput=="lmqf"){
// pair<int, int> tmp;
// layeredMQF* lmqf=((LMQF*)dataStructure)->get_MQF();
// tmp.first=qf_space(lmqf->firstLayer_singletons);
// tmp.second=qf_space(lmqf->secondLayer);
// int64_t tmp2=(int64_t)slotsUsedInCounting(lmqf->firstLayer_singletons);
// tmp2-=(int64_t)lmqf->firstLayer_singletons->metadata->noccupied_slots;
// cout<<"\t"<<tmp.first<<"\t"<<tmp.second<<"\t"<<tmp2;
// }
// cout<<endl;
// old_capacity=capacity;
//
// capacity=dataStructure->space();
//
// double millionQuerysSecond=(double)countedKmers/(double)querytime;
// result.push_back(make_pair(capacity,(double)millionQuerysSecond));
// }
//
// capacity=dataStructure->space();
// if(dataStrucureInput=="mqf")
// {
// double slots_used=((MQF*)dataStructure)->calculate_slotsUsedInCounting();
// slots_used-=((MQF*)dataStructure)->get_MQF()->metadata->noccupied_slots;
// results_slotsUsed.push_back(make_pair(capacity,slots_used));
// }
//
//
// }
// cout<<"Capacity\t1M Query per second"<<endl;
// for(int i=0;i<result.size();i++)
// {
// cout<<result[i].first<<"\t"<<result[i].second<<endl;
// }
// if(dataStrucureInput=="mqf"){
// cout<<"Capacity\t%slots used in counting"<<endl;
// for(int i=0;i<results_slotsUsed.size();i++)
// {
// cout<<results_slotsUsed[i].first<<"\t"<<results_slotsUsed[i].second<<endl;
// }
// }
// cerr<<"#generated elements= "<<g->get_generated_elements()<<endl;
return 0;
}
| 32.844 | 119 | 0.611497 | [
"vector"
] |
685a1ba865e1401bac3f819de78a9132522b8e2d | 1,998 | cpp | C++ | example/heartbeat_example.cpp | alipay/sofa-bolt-cpp | 6f422c0a8767ff8292db2b7c0557f9990219eb6b | [
"Apache-2.0"
] | 13 | 2018-09-05T07:10:11.000Z | 2019-04-30T01:31:32.000Z | example/heartbeat_example.cpp | sofastack/sofa-bolt-cpp | 6f422c0a8767ff8292db2b7c0557f9990219eb6b | [
"Apache-2.0"
] | 1 | 2018-11-03T03:54:40.000Z | 2018-11-05T11:37:33.000Z | example/heartbeat_example.cpp | sofastack/sofa-bolt-cpp | 6f422c0a8767ff8292db2b7c0557f9990219eb6b | [
"Apache-2.0"
] | 2 | 2019-09-08T13:52:09.000Z | 2021-04-21T08:42:08.000Z | #include <iostream>
#include <stdio.h>
#include <thread>
#include <random>
#include <thread>
#include "rpc.h"
#include "../src/common/log.h"
int main() {
if (!antflash::globalInit()) {
LOG_INFO("global init fail.");
return -1;
}
antflash::ChannelOptions options;
options.connection_type =
antflash::EConnectionType::CONNECTION_TYPE_POOLED;
options.max_retry = 1;
antflash::Channel channel;
if (!channel.init("127.0.0.1:12200", &options)) {
LOG_INFO("channel init fail.");
return -1;
}
antflash::BoltRequest request;
std::vector<std::unique_ptr<std::thread>> threads;
std::vector<bool> exits;
//size_t total_size = std::thread::hardware_concurrency();
size_t total_size = 3;
for (size_t i = 0; i < total_size; ++i) {
exits.push_back(false);
threads.emplace_back(
new std::thread([&channel, &request, &exits, i]() {
std::default_random_engine e;
std::uniform_int_distribution<> u(1, 20);
while (!exits[i]) {
antflash::BoltResponse response;
antflash::Session session;
LOG_INFO("thread[{}] begin heartbeat.", i);
session.send(request).to(channel).receiveTo(response).sync();
if (session.failed()) {
LOG_INFO("thread[{}] session fail: {}", i, session.getErrText());
} else if (response.isHeartbeat()) {
LOG_INFO("thread[{}] session success, status[{}]", i, response.status());
}
std::this_thread::sleep_for(
std::chrono::seconds(u(e)));
}
}));
}
std::this_thread::sleep_for(std::chrono::seconds(86400));
for (size_t i = 0; i < total_size; ++i) {
exits[i] = true;
}
for (size_t i = 0; i < total_size; ++i) {
threads[i]->join();
}
antflash::globalDestroy();
return 0;
}
| 29.382353 | 93 | 0.547548 | [
"vector"
] |
686ce43ab63f7ddf6b8ba43a26197047967afd30 | 3,797 | cpp | C++ | benchmark/arrays_and_strings.cpp | lkeegan/CTCI | 1f15dabaf85aaa6d2f8bd21b5451d55173cf8ad4 | [
"MIT"
] | 1 | 2018-10-09T03:52:16.000Z | 2018-10-09T03:52:16.000Z | benchmark/arrays_and_strings.cpp | lkeegan/CTCI | 1f15dabaf85aaa6d2f8bd21b5451d55173cf8ad4 | [
"MIT"
] | null | null | null | benchmark/arrays_and_strings.cpp | lkeegan/CTCI | 1f15dabaf85aaa6d2f8bd21b5451d55173cf8ad4 | [
"MIT"
] | null | null | null | #include <benchmark/benchmark.h>
#include <arrays_and_strings.hpp>
#include <random>
using namespace ctci::arrays_and_strings;
void BM_is_unique_a(benchmark::State& state) {
std::string unique_string;
for (int ci = 0; ci < 128; ++ci) {
unique_string.push_back(static_cast<char>(ci));
}
int n = state.range(0);
std::string s = unique_string.substr(0, n);
for (auto _ : state) {
is_unique_a(s);
}
state.SetComplexityN(n);
}
void BM_is_unique_b(benchmark::State& state) {
std::string unique_string;
for (int ci = 0; ci < 128; ++ci) {
unique_string.push_back(static_cast<char>(ci));
}
int n = state.range(0);
std::string s = unique_string.substr(0, n);
for (auto _ : state) {
is_unique_b(s);
}
state.SetComplexityN(n);
}
void BM_check_permutation(benchmark::State& state) {
int n = state.range(0);
std::string s1;
for (int ci = 0; ci < n; ++ci) {
s1.push_back(static_cast<char>(ci % 128));
}
std::string s2(s1);
for (auto _ : state) {
check_permutation(s1, s2);
}
state.SetComplexityN(n);
}
void BM_URLify(benchmark::State& state) {
int n = state.range(0);
std::string s16("asd dg ww! 1s f.");
std::string s{};
for (int i = 0; i < n; ++i) {
s += s16;
}
s += std::string(15 * n, ' ');
for (auto _ : state) {
URLify(s, n * s16.size());
}
state.SetComplexityN(n);
}
void BM_is_permutation_of_palindrome(benchmark::State& state) {
int n = state.range(0);
std::string s16("asd dg ww! 1s f.");
std::string s{};
for (int i = 0; i < n; ++i) {
s += s16;
}
for (auto _ : state) {
is_permutation_of_palindrome(s);
}
state.SetComplexityN(n);
}
void BM_one_away(benchmark::State& state) {
int n = state.range(0);
std::string s16("asd dg ww! 1s f.");
std::string s1{};
for (int i = 0; i < n; ++i) {
s1 += s16;
}
s16 = s1;
s16[16 * n / 2] = 'X';
for (auto _ : state) {
one_away(s1, s16);
}
state.SetComplexityN(n);
}
void BM_string_compression(benchmark::State& state) {
int n = state.range(0);
std::string s16("qqqqccc sppppooo");
std::string s1{};
for (int i = 0; i < n; ++i) {
s1 += s16;
}
for (auto _ : state) {
std::string s2 = string_compression(s1);
}
state.SetComplexityN(n);
}
void BM_rotate_matrix(benchmark::State& state) {
int n = state.range(0);
std::vector<int> vec;
vec.reserve(n);
for (int i = 0; i < n; ++i) {
vec.push_back(i);
}
matrix mat(n);
for (auto& v : mat) {
v = vec;
}
for (auto _ : state) {
rotate_matrix(mat);
}
state.SetComplexityN(n);
}
void BM_zero_matrix(benchmark::State& state) {
int n = state.range(0);
std::vector<int> vec;
vec.reserve(n);
matrix mat(n);
int j = 0;
for (auto& v : mat) {
for (int i = 0; i < n; ++i) {
vec.push_back(i - j);
}
v = vec;
++j;
}
for (auto _ : state) {
zero_matrix(mat);
}
state.SetComplexityN(n);
}
void BM_is_rotation(benchmark::State& state) {
int n = state.range(0);
std::string s16("qqqqccc sppppooo");
std::string s1{};
for (int i = 0; i < n; ++i) {
s1 += s16;
}
for (auto _ : state) {
is_rotation(s1, s1);
}
state.SetComplexityN(n);
}
BENCHMARK(BM_is_unique_a)->Range(2, 1 << 7)->Complexity();
BENCHMARK(BM_is_unique_b)->Range(2, 1 << 7)->Complexity();
BENCHMARK(BM_check_permutation)->Range(2, 1 << 14)->Complexity();
BENCHMARK(BM_URLify)->Range(1, 1 << 14)->Complexity();
BENCHMARK(BM_is_permutation_of_palindrome)->Range(1, 1 << 14)->Complexity();
BENCHMARK(BM_one_away)->Range(1, 1 << 14)->Complexity();
BENCHMARK(BM_string_compression)->Range(1, 1 << 14)->Complexity();
BENCHMARK(BM_rotate_matrix)->Range(1, 1 << 8)->Complexity();
BENCHMARK(BM_zero_matrix)->Range(1, 1 << 8)->Complexity();
BENCHMARK(BM_is_rotation)->Range(1, 1 << 14)->Complexity();
| 23.73125 | 76 | 0.609428 | [
"vector"
] |
686d6e6468fabf1967f1b2fc0c7383e158ff9ca2 | 1,243 | cpp | C++ | Codeforces 963B.cpp | Jvillegasd/Codeforces | ffdd2d5db1dabc7ff76f8f92270c79233a77b933 | [
"MIT"
] | null | null | null | Codeforces 963B.cpp | Jvillegasd/Codeforces | ffdd2d5db1dabc7ff76f8f92270c79233a77b933 | [
"MIT"
] | null | null | null | Codeforces 963B.cpp | Jvillegasd/Codeforces | ffdd2d5db1dabc7ff76f8f92270c79233a77b933 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define pb push_back
#define pob pop_back
#define fp first
#define sp second
#define mp make_pair
#define ins insert
#define uEdge(u, v) g[u].pb(v), g[v].pb(u)
#define uwEdge(u, v, w) g[u].pb({v, w}), g[v].pb({u, w})
#define dEdge(u, v) g[u].pb(v)
#define dwEdge(u, v, w) g[u].pb({v, w})
#define BOOST ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define minHeap int, vector<int>, greater<int>
using namespace std;
typedef long long int lli;
typedef pair<int, int> pii;
vector<int> g[200100];
int sz[200100], root;
bool vist[200100];
void delSubtree(int u){
vist[u] = true;
printf("%d\n", u);
for(auto v : g[u]) if(!vist[v]) delSubtree(v);
}
void DFS(int u){
int degree = 0;
for(auto v : g[u]){
DFS(v);
if(!vist[v]) degree++;
}
if(u != root) degree++;
if(!(degree & 1)) delSubtree(u);
}
int main(){
int n, u;
scanf("%d", &n);
for(int v = 1; v <= n; v++){
scanf("%d", &u);
if(u) dEdge(u, v);
else root = v;
}
if(n & 1) printf("YES\n"), DFS(root);
else printf("NO");
return 0;
}
/*
Se trata el Arbol como direccionado porque solo se tiene que eliminar el subarbol cuya raiz v
tenga degree(v) par.
*/ | 23.45283 | 97 | 0.578439 | [
"vector"
] |
686fa801a18f8dfb5347bf89b538e752d5421581 | 926 | cpp | C++ | world/religion/source/unit_tests/Deity_test.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | world/religion/source/unit_tests/Deity_test.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | world/religion/source/unit_tests/Deity_test.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #include "gtest/gtest.h"
TEST(SW_World_Religion_Deity, serialization_id)
{
Deity d;
EXPECT_EQ(ClassIdentifier::CLASS_ID_DEITY, d.get_class_identifier());
}
TEST(SW_World_Religion_Deity, saveload)
{
Deity d, d2;
d.set_id("foo");
d.set_name_sid("test");
d.set_description_sid("asdf");
d.set_short_description_sid("short_sid");
d.set_anger_message_sid("anger_sid");
d.set_death_message_sid("death_msg");
d.set_alignment_range(AlignmentRange::ALIGNMENT_RANGE_GOOD);
vector<string> crowning_gifts;
crowning_gifts.push_back("big_club");
d.set_crowning_gifts(crowning_gifts);
d.set_pct_chance_class_crowning(53);
d.set_dislike("cats", true);
Modifier initial(1,2,3,4,5,6,7);
d.set_initial_modifier(initial);
d.set_user_playable(true);
EXPECT_FALSE(d == d2);
ostringstream ss;
d.serialize(ss);
istringstream iss(ss.str());
d2.deserialize(iss);
EXPECT_TRUE(d == d2);
}
| 20.130435 | 71 | 0.732181 | [
"vector"
] |
687b2f0779fa65973a316928feee9886e1a5592d | 2,358 | cc | C++ | headless/lib/browser/headless_browser_impl_aura.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | headless/lib/browser/headless_browser_impl_aura.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | headless/lib/browser/headless_browser_impl_aura.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "headless/lib/browser/headless_browser_impl.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "headless/lib/browser/headless_clipboard.h"
#include "headless/lib/browser/headless_screen.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/display/screen.h"
#include "ui/events/devices/device_data_manager.h"
#include "ui/gfx/geometry/rect.h"
namespace headless {
void HeadlessBrowserImpl::PlatformInitialize() {
HeadlessScreen* screen = HeadlessScreen::Create(options()->window_size);
display::Screen::SetScreenInstance(screen);
// TODO(eseckler): We shouldn't share clipboard contents across WebContents
// (or at least BrowserContexts).
ui::Clipboard::SetClipboardForCurrentThread(
base::MakeUnique<HeadlessClipboard>());
}
void HeadlessBrowserImpl::PlatformStart() {
DCHECK(aura::Env::GetInstance());
ui::DeviceDataManager::CreateInstance();
}
void HeadlessBrowserImpl::PlatformInitializeWebContents(
HeadlessWebContentsImpl* web_contents) {
auto window_tree_host = base::MakeUnique<HeadlessWindowTreeHost>(gfx::Rect());
window_tree_host->InitHost();
gfx::NativeWindow parent_window = window_tree_host->window();
parent_window->Show();
window_tree_host->SetParentWindow(parent_window);
web_contents->set_window_tree_host(std::move(window_tree_host));
gfx::NativeView native_view = web_contents->web_contents()->GetNativeView();
DCHECK(!parent_window->Contains(native_view));
parent_window->AddChild(native_view);
native_view->Show();
}
void HeadlessBrowserImpl::PlatformSetWebContentsBounds(
HeadlessWebContentsImpl* web_contents,
const gfx::Rect& bounds) {
web_contents->window_tree_host()->SetBoundsInPixels(bounds);
web_contents->window_tree_host()->window()->SetBounds(bounds);
gfx::NativeView native_view = web_contents->web_contents()->GetNativeView();
native_view->SetBounds(bounds);
content::RenderWidgetHostView* host_view =
web_contents->web_contents()->GetRenderWidgetHostView();
if (host_view)
host_view->SetSize(bounds.size());
}
} // namespace headless
| 35.727273 | 80 | 0.772265 | [
"geometry"
] |
687c6a90f712f562714dd25a1ca73603206e078e | 2,596 | cpp | C++ | dataset/test/modification/1466_all/28/transformation_1.cpp | Karina5005/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | 3 | 2022-02-15T00:29:39.000Z | 2022-03-15T08:36:44.000Z | dataset/test/modification/1466_all/28/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | dataset/test/modification/1466_all/28/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | #include <iomanip>
#include <iostream>
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
#define pb push_back
#define fo(i,n) for(int i=0;i<n;i++)
#define foo(i,n) for(int i=1;i<=n;i++)
#define int long long int
#define mod 1000000007
#define all(v) (v).begin(),(v).end()
#define pb push_back
#define ff first
#define ss second
const int rts = 998244353;
#define fast std::ios::sync_with_stdio(false);cin.tie(NULL);
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x);
#endif
void xk(long long v_ri) ;
void e_xgd(std::string otf) ;
void kno_xf(char h) ;
void trk(double jox) ;
template <class T, class V> void _print(pair<T, V> hu_d);
template <class T> void _print(vector<T> io_i);
template <class T> void _print(set<T> k_s);
template <class T, class V> void _print(map<T, V> pvq_dlp);
template <class T> void _print(multiset<T> i_r);
long long av(long long cxp_e, long long eq_d) {
return (cxp_e / __gcd(cxp_e, eq_d)) * eq_d;
}
int32_t main() ;
int32_t main() {
cin.tie(__null);
;
freopen("error.txt", "w", stderr);
long long yb;
cin >> yb;
if (5 > 3) cout << "new code";for ( ; yb--; )
/* 'for' inside */
{
std::string qf_ux;
cin >> qf_ux;
long long yjm = 0;
{
long long fve = 1;
if (5 > 3) cout << "new code";for ( ; fve < qf_ux.length(); )
/* 'for' inside */
{
/* 'if' begin */
if (qf_ux[fve] == qf_ux[fve - 1] || qf_ux[fve] == qf_ux[fve - 2]) /* 'if' inside */
{
yjm++;
qf_ux[fve] = 0;
}
fve++;
}}
cout << yjm << endl;
}
}
void _print(int v) {
cerr << "[ ";
cerr << "]";
}
void _print(int v) {
cerr << "[ ";
cerr << "]";
}
void cd_v(int v) {
cerr << "[ ";
cerr << "]";
}
void exe_mj(int v) {
cerr << "[ ";
cerr << "]";
}
void cp(int p) {
cerr << "{";
cerr << ",";
cerr << "}";
}
void _print(double z_yg) {
cerr << z_yg;
}
void _print(char h) {
cerr << h;
}
void _print(std::string stg) {
cerr << stg;
}
void rb(long long fdg) {
cerr << fdg;
}
| 10.771784 | 99 | 0.468028 | [
"vector"
] |
687d9d72117b836f3ea8a50b8396f01b14749380 | 10,495 | cpp | C++ | detection/mainwindow.cpp | WenzheDai/Auto_sort | 20c73fb189cf00f302861b4269bee7a2bf8af8eb | [
"MIT"
] | 1 | 2022-02-05T20:59:48.000Z | 2022-02-05T20:59:48.000Z | detection/mainwindow.cpp | WenzheDai/Pipeline-Real-time-Detection-and-Sorting-System | 20c73fb189cf00f302861b4269bee7a2bf8af8eb | [
"MIT"
] | null | null | null | detection/mainwindow.cpp | WenzheDai/Pipeline-Real-time-Detection-and-Sorting-System | 20c73fb189cf00f302861b4269bee7a2bf8af8eb | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
mThread_motor = new thread_motor();
mUtils = new ImageUtils();
mUtils->setLED(ui->label_led_red, 0, 16);
mUtils->setLED(ui->label_led_yellow, 0, 16);
mUtils->setLED(ui->label_led_green, 0, 16);
mUtils->setLED(ui->label_led_square, 0, 16);
mUtils->setLED(ui->label_led_circle, 0, 16);
mUtils->setLED(ui->label_led_Triangle, 0, 16);
ui->label_team->setText("Team number: 12");
ui->groupBox->setStyleSheet("background-color: rgba(200,200,200,1)");
time = new QTime();
time->setHMS(0, 0, 0);
time_num = 0;
mDetecting = new Detecting();
// select button
connect(ui->checkBox_R, SIGNAL(stateChanged(int)), this, SLOT(On_Changed_R()));
connect(ui->checkBox_Y, SIGNAL(stateChanged(int)), this, SLOT(On_Changed_Y()));
connect(ui->checkBox_G, SIGNAL(stateChanged(int)), this, SLOT(On_Changed_G()));
connect(ui->checkBox_T, SIGNAL(stateChanged(int)), this, SLOT(On_Changed_T()));
connect(ui->checkBox_S, SIGNAL(stateChanged(int)), this, SLOT(On_Changed_S()));
connect(ui->checkBox_C, SIGNAL(stateChanged(int)), this, SLOT(On_Changed_C()));
m_color = -1;
}
MainWindow::~MainWindow() {
delete ui;
}
// Open camera
void MainWindow::on_Bt_start_clicked() {
Time_camera = new QTimer(this);
connect(Time_camera, SIGNAL(timeout()), this, SLOT(open_camera_time_click()));
Time_camera->start(30);// refresh camera every 30ms
frame = cap.open(0);
// cap.set(cv::CAP_PROP_AUTO_EXPOSURE, 1);
// cap.set(cv::CAP_PROP_EXPOSURE, 600);
if (!cap.isOpened()) {
printf("open camera failed !");
}
timer_run = new QTimer(this);
connect(timer_run, SIGNAL(timeout()), this, SLOT(updateTime()));
timer_run->start(1000);
mThread_motor->start();
}
void MainWindow::open_camera_time_click() {
QString countShow;
//weightshow.sprintf("%d (g)", ui->horizontalSlider->value());
//ui->label_set_weight_show->setText(weightshow);
//get image
cap.read(frame);
if (frame.empty()) {
qDebug("frame.empty()");
return;
}
cv::resize(frame, frame, Size(frame.cols / 4, frame.rows / 4));
mDetecting->setCameraImage(frame);
mObject = mDetecting->detectColor();
if (mObject.getColor() == "red") {
mUtils->setLED(ui->label_led_red, 1, 16);
mUtils->setLED(ui->label_led_yellow, 0, 16);
mUtils->setLED(ui->label_led_green, 0, 16);
} else if (mObject.getColor() == "yellow") {
mUtils->setLED(ui->label_led_red, 0, 16);
mUtils->setLED(ui->label_led_yellow, 3, 16);
mUtils->setLED(ui->label_led_green, 0, 16);
} else if (mObject.getColor() == "green") {
mUtils->setLED(ui->label_led_red, 0, 16);
mUtils->setLED(ui->label_led_yellow, 0, 16);
mUtils->setLED(ui->label_led_green, 2, 16);
} else {
mUtils->setLED(ui->label_led_red, 0, 16);
mUtils->setLED(ui->label_led_yellow, 0, 16);
mUtils->setLED(ui->label_led_green, 0, 16);
}
//qDebug("state,R = %d", ui->checkBox_R->isChecked());
//qDebug("state,Y = %d", ui->checkBox_Y->isChecked());
//qDebug("state,G = %d", ui->checkBox_G->isChecked());
//qDebug("m_color = %d", m_color);
int mshape = mObject.getShape();
//QString t_1 = QString::number(m_color);
//QString t_1 = QString::number(mshape);
//ui->textBrowser_count->setText(t_1);
//red, yellow, green, square, circle, triangle
if (mshape == 3) {
mUtils->setLED(ui->label_led_Triangle, 1, 16);
mUtils->setLED(ui->label_led_square, 0, 16);
mUtils->setLED(ui->label_led_circle, 0, 16);
} else if (mshape == 4) {
mUtils->setLED(ui->label_led_Triangle, 0, 16);
mUtils->setLED(ui->label_led_square, 1, 16);
mUtils->setLED(ui->label_led_circle, 0, 16);
} else if (mshape >= 5) {
mUtils->setLED(ui->label_led_Triangle, 0, 16);
mUtils->setLED(ui->label_led_square, 0, 16);
mUtils->setLED(ui->label_led_circle, 1, 16);
} else {
mUtils->setLED(ui->label_led_Triangle, 0, 16);
mUtils->setLED(ui->label_led_square, 0, 16);
mUtils->setLED(ui->label_led_circle, 0, 16);
}
// logic for object color and shape solection
// if object needed, open a thread for motor operation
// if object detected is not needed, reset the motor status
switch (m_color) {
case red:
if (m_shape == 0) {
if (mObject.getColor() == "red" && mObject.getShape() == 3) {
qDebug("yes,R triangle!");
mThread_motor->set_run_motor(true);
} else {
mThread_motor->set_run_motor(false);
qDebug("other ....");
}
} else if (m_shape == 1) {
if (mObject.getColor() == "red" && mObject.getShape() == 4) {
qDebug("yes,R square!");
mThread_motor->set_run_motor(true);
} else {
mThread_motor->set_run_motor(false);
qDebug("other ....");
}
} else if (m_shape == 2) {
if (mObject.getColor() == "red" && mObject.getShape() >= 5) {
qDebug("yes,R circle!");
mThread_motor->set_run_motor(true);
} else {
mThread_motor->set_run_motor(false);
qDebug("other ....");
}
}
break;
case yellow:
if (m_shape == 0) {
if (mObject.getColor() == "yellow" && mObject.getShape() == 3) {
qDebug("yes,Y triangle!");
mThread_motor->set_run_motor(true);
} else {
mThread_motor->set_run_motor(false);
qDebug("other ....");
}
} else if (m_shape == 1) {
if (mObject.getColor() == "yellow" && mObject.getShape() == 4) {
qDebug("yes,Y square!");
mThread_motor->set_run_motor(true);
} else {
mThread_motor->set_run_motor(false);
qDebug("other ....");
}
} else if (m_shape == 2) {
if (mObject.getColor() == "yellow" && mObject.getShape() >= 5) {
qDebug("yes,Y circle!");
mThread_motor->set_run_motor(true);
} else {
mThread_motor->set_run_motor(false);
qDebug("other ....");
}
}
break;
case green:
if (m_shape == 0) {
if (mObject.getColor() == "green" && mObject.getShape() == 3) {
qDebug("yes,G triangle!");
mThread_motor->set_run_motor(true);
} else {
mThread_motor->set_run_motor(false);
qDebug("other ....");
}
} else if (m_shape == 1) {
if (mObject.getColor() == "green" && mObject.getShape() == 4) {
qDebug("yes,G square!");
mThread_motor->set_run_motor(true);
} else {
mThread_motor->set_run_motor(false);
qDebug("other ....");
}
} else if (m_shape == 2) {
if (mObject.getColor() == "green" && mObject.getShape() >= 5) {
qDebug("yes,G circle!");
mThread_motor->set_run_motor(true);
} else {
mThread_motor->set_run_motor(false);
qDebug("other ....");
}
}
break;
default:
mThread_motor->set_run_motor(false);
break;
}
int shape_num = mObject.getCount();
if (shape_num >= 0) {
ui->textBrowser_count->setText(QString::number(shape_num));
}
// Create a display container
cvtColor(frame, frame, COLOR_BGR2RGB);
cv::resize(frame, frame, Size(380, 280));
QImage showImage = QImage(frame.data, frame.cols, frame.rows, QImage::Format_RGB888);
// Add a file with a file path of fileName (QString type) to the container
scene->clear();
scene->addPixmap(QPixmap::fromImage(showImage));
// Show container with graphicsView(QGraphicsView class)
ui->graphicsView_Camera->setScene(scene);
// Start showing
ui->graphicsView_Camera->show();
}
void MainWindow::On_Changed_R() {
if (ui->checkBox_R->isChecked()) {
ui->checkBox_Y->setChecked(false);
ui->checkBox_G->setChecked(false);
m_color = 0;
} else {
m_color = -1;
}
}
void MainWindow::On_Changed_Y() {
if (ui->checkBox_Y->isChecked()) {
ui->checkBox_R->setChecked(false);
ui->checkBox_G->setChecked(false);
m_color = 1;
} else {
m_color = -1;
}
}
void MainWindow::On_Changed_G() {
if (ui->checkBox_G->isChecked()) {
ui->checkBox_R->setChecked(false);
ui->checkBox_Y->setChecked(false);
m_color = 2;
} else {
m_color = -1;
}
}
void MainWindow::On_Changed_T() {
if (ui->checkBox_T->isChecked()) {
ui->checkBox_S->setChecked(false);
ui->checkBox_C->setChecked(false);
m_shape = 0;
} else {
m_shape = -1;
}
}
void MainWindow::On_Changed_S() {
if (ui->checkBox_S->isChecked()) {
ui->checkBox_T->setChecked(false);
ui->checkBox_C->setChecked(false);
m_shape = 1;
} else {
m_shape = -1;
}
}
void MainWindow::On_Changed_C() {
if (ui->checkBox_C->isChecked()) {
ui->checkBox_T->setChecked(false);
ui->checkBox_S->setChecked(false);
m_shape = 2;
} else {
m_shape = -1;
}
}
void MainWindow::updateTime() {
//qDebug("update");
time_num++;
QString strTime;
strTime = time->addSecs(time_num).toString("hh:mm:ss");
//strTime = time->currentTime().toString("hh:mm:ss");
qDebug("update = %s", qPrintable(strTime));
ui->textBrowser_timeShow->setText(strTime);
}
// exit
void MainWindow::on_Bt_stop_clicked() {
printf("exit....");
this->close();
}
| 31.422156 | 89 | 0.543592 | [
"object",
"shape"
] |
687dbb3400846c83fa5b40609ffe232daf67a6ac | 4,724 | cpp | C++ | modules/hash_calculator/src/Utils.cpp | nicledomaS/HashCalculator | 4708824e2ddde1fc7c330711ae7939c57556cb7d | [
"Apache-2.0"
] | null | null | null | modules/hash_calculator/src/Utils.cpp | nicledomaS/HashCalculator | 4708824e2ddde1fc7c330711ae7939c57556cb7d | [
"Apache-2.0"
] | null | null | null | modules/hash_calculator/src/Utils.cpp | nicledomaS/HashCalculator | 4708824e2ddde1fc7c330711ae7939c57556cb7d | [
"Apache-2.0"
] | null | null | null | #include "Utils.h"
#include "SegmentImpl.h"
#include "SegmentGroup.h"
#include "FileMapper.h"
#include <iostream>
#include <fcntl.h>
#include <sched.h>
namespace hash_calculator
{
namespace
{
constexpr auto MaxSingleBufSize = 200; // MB
constexpr auto MaxPartBufSize = 50; // MB
constexpr auto MaxBigSegmentCount = 4;
constexpr auto MaxCpuCount = 4;
static cpu_set_t mask;
void assignCores(int cpuCount)
{
CPU_ZERO(&mask);
int currentCpuId = 0;
while(currentCpuId < cpuCount)
{
CPU_SET(currentCpuId++, &mask);
}
if(sched_setaffinity(0, sizeof(mask), &mask) == 0)
{
std::cout << "Assigned " << cpuCount << " first CPUs" << std::endl;
}
else
{
std::cerr << "CPUs did not assigned" << std::endl;
}
}
std::vector<std::shared_ptr<Segment>> segmentsWithMinBlock(
const FileDesc& desc, long blockSize, long size, int cpuCount, size_t segmentCount)
{
std::vector<std::shared_ptr<Segment>> groups;
std::vector<std::shared_ptr<Segment>> segments;
std::vector<std::shared_ptr<FileMapper>> mappers;
auto pos = 0;
while(pos < desc.sb.st_size)
{
auto diff = desc.sb.st_size - pos;
auto fileMapOffset = diff < size ? diff : size;
auto fileMapper = std::make_shared<FileMapper>(desc.fd, pos, fileMapOffset);
auto startPos = pos;
for(size_t i = 0; i < segmentCount && startPos < desc.sb.st_size; ++i)
{
auto diff = desc.sb.st_size - startPos;
auto offset = diff < blockSize ? diff : blockSize;
auto segment = std::make_shared<SegmentImpl>(fileMapper, startPos, startPos + offset, offset);
segments.push_back(std::move(segment));
startPos += offset;
}
mappers.push_back(std::move(fileMapper));
auto groupSegment = std::make_shared<SegmentGroup>(cpuCount, std::move(segments), std::move(mappers));
groups.push_back(std::move(groupSegment));
pos += fileMapOffset;
}
return groups;
}
std::vector<std::shared_ptr<Segment>> segmentsWithMaxBlock(
const FileDesc& desc, long blockSize, long size, int cpuCount, size_t segmentCount = MaxBigSegmentCount)
{
std::vector<std::shared_ptr<Segment>> groups;
std::vector<std::shared_ptr<Segment>> segments;
std::vector<std::shared_ptr<FileMapper>> mappers;
auto pos = 0;
while(pos < desc.sb.st_size)
{
auto diff = desc.sb.st_size - pos;
auto fileMapOffset = diff < size ? diff : size;
auto fileMapper = std::make_shared<FileMapper>(desc.fd, pos, fileMapOffset);
auto segmentOffset = diff < blockSize ? diff : blockSize;
auto segment = std::make_shared<SegmentImpl>(fileMapper, pos, pos + segmentOffset, fileMapOffset);
segments.push_back(std::move(segment));
mappers.push_back(std::move(fileMapper));
pos += segmentOffset;
if(segments.size() == segmentCount || pos == desc.sb.st_size)
{
auto segment = std::make_shared<SegmentGroup>(cpuCount, std::move(segments), std::move(mappers));
groups.push_back(std::move(segment));
}
}
return groups;
}
} // anonymous
FileDesc fileOpen(const std::string& inFilePath)
{
int fd = open(inFilePath.c_str(), O_RDONLY);
if (fd == -1)
{
throw std::runtime_error("File did not open");
}
struct stat sb;
if (fstat(fd, &sb) == -1)
{
throw std::runtime_error("File information did not get");
}
return {fd, sb};
}
std::vector<std::shared_ptr<Segment>> prepareSegments(const FileDesc& desc, size_t blockSize)
{
auto allCpuCount = std::thread::hardware_concurrency();
auto cpuCount = allCpuCount > MaxCpuCount ? MaxCpuCount : allCpuCount;
assignCores(cpuCount);
if(desc.sb.st_size == 0)
{
std::vector<std::shared_ptr<FileMapper>> mappers;
std::vector<std::shared_ptr<Segment>> segments;
auto fileMapper = std::make_shared<FileMapper>(desc.fd, 0, 0);
segments.push_back(std::make_shared<SegmentImpl>(fileMapper, 0, 0, 0));
mappers.push_back(std::move(fileMapper));
auto segmentGroup = std::make_shared<SegmentGroup>(cpuCount, std::move(segments), std::move(mappers));
return { segmentGroup };
}
auto blockSizeInBytes = toBytes(blockSize);
auto segmentCount = (MaxSingleBufSize / blockSize);
auto size = segmentCount > 0 ? segmentCount * blockSizeInBytes : toBytes(MaxPartBufSize);
return segmentCount > 1 ?
segmentsWithMinBlock(desc, blockSizeInBytes, size, cpuCount, segmentCount) :
segmentsWithMaxBlock(desc, blockSizeInBytes, size, cpuCount);
}
} // hash_calculator | 30.282051 | 110 | 0.646274 | [
"vector"
] |
6897943ec1fe6c0d9a0bed15ab8b7ab6ca7accc6 | 4,730 | cpp | C++ | gtsam/slam/tests/testBetweenFactor.cpp | h-rover/gtsam | a0206e210d8f47b6ee295a1fbf95af84d98c5cf0 | [
"BSD-3-Clause"
] | 1,402 | 2017-03-28T00:18:11.000Z | 2022-03-30T10:28:32.000Z | gtsam/slam/tests/testBetweenFactor.cpp | h-rover/gtsam | a0206e210d8f47b6ee295a1fbf95af84d98c5cf0 | [
"BSD-3-Clause"
] | 851 | 2017-11-27T15:09:56.000Z | 2022-03-31T22:26:38.000Z | gtsam/slam/tests/testBetweenFactor.cpp | h-rover/gtsam | a0206e210d8f47b6ee295a1fbf95af84d98c5cf0 | [
"BSD-3-Clause"
] | 565 | 2017-11-30T16:15:59.000Z | 2022-03-31T02:53:04.000Z | /**
* @file testBetweenFactor.cpp
* @brief
* @author Duy-Nguyen Ta, Varun Agrawal
* @date Aug 2, 2013
*/
#include <CppUnitLite/TestHarness.h>
#include <gtsam/base/TestableAssertions.h>
#include <gtsam/base/numericalDerivative.h>
#include <gtsam/geometry/Pose3.h>
#include <gtsam/geometry/Rot3.h>
#include <gtsam/inference/Symbol.h>
#include <gtsam/nonlinear/factorTesting.h>
#include <gtsam/slam/BetweenFactor.h>
using namespace std::placeholders;
using namespace gtsam;
using namespace gtsam::symbol_shorthand;
using namespace gtsam::noiseModel;
/**
* This TEST should fail. If you want it to pass, change noise to 0.
*/
TEST(BetweenFactor, Rot3) {
Rot3 R1 = Rot3::Rodrigues(0.1, 0.2, 0.3);
Rot3 R2 = Rot3::Rodrigues(0.4, 0.5, 0.6);
Rot3 noise = Rot3(); // Rot3::Rodrigues(0.01, 0.01, 0.01); // Uncomment to make unit test fail
Rot3 measured = R1.between(R2)*noise ;
BetweenFactor<Rot3> factor(R(1), R(2), measured, Isotropic::Sigma(3, 0.05));
Matrix actualH1, actualH2;
Vector actual = factor.evaluateError(R1, R2, actualH1, actualH2);
Vector expected = Rot3::Logmap(measured.inverse() * R1.between(R2));
EXPECT(assert_equal(expected,actual/*, 1e-100*/)); // Uncomment to make unit test fail
Matrix numericalH1 = numericalDerivative21<Vector3, Rot3, Rot3>(
std::function<Vector(const Rot3&, const Rot3&)>(std::bind(
&BetweenFactor<Rot3>::evaluateError, factor, std::placeholders::_1,
std::placeholders::_2, boost::none, boost::none)),
R1, R2, 1e-5);
EXPECT(assert_equal(numericalH1,actualH1, 1E-5));
Matrix numericalH2 = numericalDerivative22<Vector3,Rot3,Rot3>(
std::function<Vector(const Rot3&, const Rot3&)>(std::bind(
&BetweenFactor<Rot3>::evaluateError, factor, std::placeholders::_1, std::placeholders::_2, boost::none,
boost::none)), R1, R2, 1e-5);
EXPECT(assert_equal(numericalH2,actualH2, 1E-5));
}
/* ************************************************************************* */
// Constructor scalar
TEST(BetweenFactor, ConstructorScalar) {
SharedNoiseModel model;
double measured = 0.0;
BetweenFactor<double> factor(1, 2, measured, model);
}
/* ************************************************************************* */
// Constructor vector3
TEST(BetweenFactor, ConstructorVector3) {
SharedNoiseModel model = noiseModel::Isotropic::Sigma(3, 1.0);
Vector3 measured(1, 2, 3);
BetweenFactor<Vector3> factor(1, 2, measured, model);
}
/* ************************************************************************* */
// Constructor dynamic sized vector
TEST(BetweenFactor, ConstructorDynamicSizeVector) {
SharedNoiseModel model = noiseModel::Isotropic::Sigma(5, 1.0);
Vector measured(5); measured << 1, 2, 3, 4, 5;
BetweenFactor<Vector> factor(1, 2, measured, model);
}
/* ************************************************************************* */
TEST(BetweenFactor, Point3Jacobians) {
SharedNoiseModel model = noiseModel::Isotropic::Sigma(3, 1.0);
Point3 measured(1, 2, 3);
BetweenFactor<Point3> factor(1, 2, measured, model);
Values values;
values.insert(1, Point3(0, 0, 0));
values.insert(2, Point3(1, 2, 3));
Vector3 error = factor.evaluateError(Point3(0, 0, 0), Point3(1, 2, 3));
EXPECT(assert_equal<Vector3>(Vector3::Zero(), error, 1e-9));
EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-7, 1e-5);
}
/* ************************************************************************* */
TEST(BetweenFactor, Rot3Jacobians) {
SharedNoiseModel model = noiseModel::Isotropic::Sigma(3, 1.0);
Rot3 measured = Rot3::Ry(M_PI_2);
BetweenFactor<Rot3> factor(1, 2, measured, model);
Values values;
values.insert(1, Rot3());
values.insert(2, Rot3::Ry(M_PI_2));
Vector3 error = factor.evaluateError(Rot3(), Rot3::Ry(M_PI_2));
EXPECT(assert_equal<Vector3>(Vector3::Zero(), error, 1e-9));
EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-7, 1e-5);
}
/* ************************************************************************* */
TEST(BetweenFactor, Pose3Jacobians) {
SharedNoiseModel model = noiseModel::Isotropic::Sigma(6, 1.0);
Pose3 measured(Rot3(), Point3(1, 2, 3));
BetweenFactor<Pose3> factor(1, 2, measured, model);
Pose3 pose1, pose2(Rot3(), Point3(1, 2, 3));
Values values;
values.insert(1, pose1);
values.insert(2, pose2);
Vector6 error = factor.evaluateError(pose1, pose2);
EXPECT(assert_equal<Vector6>(Vector6::Zero(), error, 1e-9));
EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-7, 1e-5);
}
/* ************************************************************************* */
int main() {
TestResult tr;
return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */
| 37.84 | 113 | 0.610571 | [
"geometry",
"vector",
"model"
] |
68995082ac2f402b434ada5494ab841e1760fada | 49,482 | cpp | C++ | src/generator/x86_64/generator.cpp | ERAP-SBT/ERAP-SBT | 67cf885634ed9205650ee2353849d623d318e2d6 | [
"MIT"
] | 2 | 2022-03-28T07:43:02.000Z | 2022-03-30T11:53:25.000Z | src/generator/x86_64/generator.cpp | ERAP-SBT/ERAP-SBT | 67cf885634ed9205650ee2353849d623d318e2d6 | [
"MIT"
] | null | null | null | src/generator/x86_64/generator.cpp | ERAP-SBT/ERAP-SBT | 67cf885634ed9205650ee2353849d623d318e2d6 | [
"MIT"
] | 2 | 2022-03-30T10:39:04.000Z | 2022-03-30T11:53:28.000Z | #include "generator/x86_64/generator.h"
#include <iostream>
using namespace generator::x86_64;
// TODO: imm handling is questionable at best here
namespace {
std::array<const char *, 4> op_reg_mapping_64 = {"rax", "rbx", "rcx", "rdx"};
std::array<const char *, 4> op_reg_mapping_32 = {"eax", "ebx", "ecx", "edx"};
std::array<const char *, 4> op_reg_mapping_16 = {"ax", "bx", "cx", "dx"};
std::array<const char *, 4> op_reg_mapping_8 = {"al", "bl", "cl", "dl"};
std::array<const char *, 4> op_reg_mapping_fp = {"xmm0", "xmm1", "xmm2", "xmm3"};
std::array<const char *, 4> &op_reg_map_for_type(const Type type) {
switch (type) {
case Type::imm:
case Type::i64:
return op_reg_mapping_64;
case Type::i32:
return op_reg_mapping_32;
case Type::i16:
return op_reg_mapping_16;
case Type::i8:
return op_reg_mapping_8;
case Type::f32:
case Type::f64:
return op_reg_mapping_fp;
case Type::mt:
assert(0);
exit(1);
}
assert(0);
exit(1);
}
std::array<const char *, 6> call_reg = {"rdi", "rsi", "rdx", "rcx", "r8", "r9"};
const char *rax_from_type(const Type type) {
switch (type) {
case Type::imm:
case Type::i64:
return "rax";
case Type::i32:
return "eax";
case Type::i16:
return "ax";
case Type::i8:
return "al";
case Type::f32:
return "eax";
case Type::f64:
return "rax";
case Type::mt:
assert(0);
exit(1);
}
assert(0);
exit(1);
}
const char *ptr_from_type(const Type type) {
switch (type) {
case Type::imm:
case Type::i64:
return "QWORD PTR";
case Type::i32:
return "DWORD PTR";
case Type::i16:
return "WORD PTR";
case Type::i8:
return "BYTE PTR";
case Type::f32:
case Type::f64:
case Type::mt:
assert(0);
exit(1);
}
assert(0);
exit(1);
}
size_t index_for_var(const BasicBlock *block, const SSAVar *var) {
for (size_t idx = 0; idx < block->variables.size(); ++idx) {
if (block->variables[idx].get() == var)
return idx;
}
assert(0);
exit(1);
}
} // namespace
const char *Generator::fp_op_size_from_type(const Type type) {
assert(is_float(type));
return type == Type::f32 ? "s" : "d";
}
const char *Generator::convert_name_from_type(const Type type) {
switch (type) {
case Type::i32:
case Type::i64:
return "si";
case Type::f32:
return "ss";
case Type::f64:
return "sd";
default:
assert(0);
exit(0);
break;
}
}
constexpr bool compatible_types(const Type t1, const Type t2) { return (t1 == t2) || ((t1 == Type::imm || t2 == Type::imm) && (is_integer(t1) || is_integer(t2))); }
void Generator::compile() {
assert(err_msgs.empty());
fprintf(out_fd, ".intel_syntax noprefix\n\n");
if (!binary_filepath.empty()) {
/* TODO: extract read-write-execute information from source ELF program headers */
/* Put the original image into a seperate section so we can set the start address */
fprintf(out_fd, ".section .orig_binary, \"aw\"\n");
fprintf(out_fd, ".incbin \"%s\"\n", binary_filepath.c_str());
}
/* we expect the linker to link the original binary image (if any) at
* exactly this address
*/
fprintf(out_fd, ".global orig_binary_vaddr\n");
fprintf(out_fd, "orig_binary_vaddr = %#lx\n", ir->base_addr);
fprintf(out_fd, ".global orig_binary_size\n");
fprintf(out_fd, "orig_binary_size = %#lx\n", ir->load_size);
fprintf(out_fd, "binary = orig_binary_vaddr\n");
compile_statics();
compile_phdr_info();
compile_section(Section::BSS);
fprintf(out_fd, "param_passing:\n");
fprintf(out_fd, ".space 128\n");
fprintf(out_fd, ".type param_passing,STT_OBJECT\n");
fprintf(out_fd, ".size param_passing,$-param_passing\n");
fprintf(out_fd, ".align 16\n");
fprintf(out_fd, "stack_space:\n");
fprintf(out_fd, ".space 1048576\n"); /* 1MiB */
fprintf(out_fd, "stack_space_end:\n");
fprintf(out_fd, ".type stack_space,STT_OBJECT\n");
fprintf(out_fd, ".size stack_space,$-stack_space\n");
fprintf(out_fd, "init_stack_ptr: .quad 0\n");
fprintf(out_fd, "init_ret_stack_ptr: .quad 0\n");
if (interpreter_only) {
compile_interpreter_only_entry();
} else {
compile_blocks();
compile_entry();
compile_err_msgs();
}
compile_ijump_lookup();
}
void Generator::compile_ijump_lookup() {
fprintf(out_fd, ".global ijump_use_hash_table\n");
fprintf(out_fd, ".global ijump_lookup_table_base\n");
fprintf(out_fd, ".global ijump_lookup_table\n");
fprintf(out_fd, ".global ijump_lookup_table_end\n");
if (!(optimizations & OPT_NO_HASH_LOOKUP)) {
using namespace hashing;
while (!ijump_hasher.build()) {
ijump_hasher.load_factor -= 0.1;
ijump_hasher.bucket_size -= 1;
if (ijump_hasher.load_factor <= 0.05) {
std::cerr << "Unable to calculate valid hash function!" << std::endl;
assert(0);
exit(1);
}
ijump_hasher.fill(ijump_hasher.keys);
}
compile_section(Section::TEXT);
ijump_hasher.print_ijump_lookup(out_fd);
compile_section(Section::RODATA);
ijump_hasher.print_hash_func_ids(out_fd);
ijump_hasher.print_hash_table(out_fd, ir);
ijump_hasher.print_hash_constants(out_fd);
fprintf(out_fd, "ijump_use_hash_table:\n.byte 1\n");
// Lookup table stubs
fprintf(out_fd, "ijump_lookup_table:\n");
fprintf(out_fd, "ijump_lookup_table_end:\n");
fprintf(out_fd, "ijump_lookup_table_base:\n.8byte 0\n");
} else {
compile_section(Section::TEXT);
fprintf(out_fd, "ijump_lookup:");
fprintf(out_fd, "sub rbx, %zu\n", ir->virt_bb_start_addr);
size_t size = ir->virt_bb_end_addr - ir->virt_bb_start_addr;
if (size < 0x8000'0000) {
fprintf(out_fd, "cmp rbx, %zu\n", size);
} else {
fprintf(out_fd, "mov rdi, %zu\n", size);
fprintf(out_fd, "cmp rbx, rdi\n");
}
fprintf(out_fd, "ja 0f\n");
fprintf(out_fd, "lea rdi, [rip + ijump_lookup_table]\n");
fprintf(out_fd, "mov rdi, [rdi + 4 * rbx]\n");
fprintf(out_fd, "test rdi, rdi\n");
fprintf(out_fd, "je 0f\n");
fprintf(out_fd, "jmp rdi\n");
fprintf(out_fd, "0:\n");
/* Slow-path: unresolved IJump, call interpreter */
fprintf(out_fd, "lea rdi, [rbx + %zu]\n", ir->virt_bb_start_addr);
fprintf(out_fd, "jmp unresolved_ijump\n");
compile_section(Section::RODATA);
fprintf(out_fd, "ijump_lookup_table_base:\n");
fprintf(out_fd, ".8byte %zu\n", ir->virt_bb_start_addr);
fprintf(out_fd, "ijump_lookup_table:\n");
assert(ir->virt_bb_start_addr <= ir->virt_bb_end_addr);
/* Incredibly space inefficient but also O(1) fast */
for (uint64_t i = ir->virt_bb_start_addr; i < ir->virt_bb_end_addr; i += 2) {
const auto bb = ir->bb_at_addr(i);
fprintf(out_fd, "/* 0x%#.8lx: */", i);
if (bb != nullptr && bb->virt_start_addr == i && (!(optimizations & OPT_MBRA) || !(optimizations & OPT_NO_TRANS_BBS) || RegAlloc::is_block_jumpable(bb))) {
fprintf(out_fd, ".8byte b%zu\n", bb->id);
} else {
fprintf(out_fd, ".8byte 0x0\n");
}
}
fprintf(out_fd, "ijump_lookup_table_end:\n");
fprintf(out_fd, ".type ijump_lookup_table,STT_OBJECT\n");
fprintf(out_fd, ".size ijump_lookup_table,ijump_lookup_table_end-ijump_lookup_table\n");
fprintf(out_fd, "ijump_use_hash_table:\n.byte 0\n");
// Hash stubs
fprintf(out_fd, ".global ijump_hash_function_idxs\nijump_hash_function_idxs:\n");
fprintf(out_fd, ".global ijump_hash_table\nijump_hash_table:\n");
fprintf(out_fd, ".global ijump_hash_bucket_number\nijump_hash_bucket_number:\n.quad 0\n");
fprintf(out_fd, ".global ijump_hash_table_size\nijump_hash_table_size:\n.quad 0\n");
}
}
void Generator::compile_statics() {
compile_section(Section::DATA);
fprintf(out_fd, ".global register_file\n");
fprintf(out_fd, "register_file:\n");
for (const auto &var : ir->statics) {
fprintf(out_fd, "s%zu: .quad 0\n", var.id); // for now have all of the statics be 64bit
}
}
void Generator::compile_phdr_info() {
std::fprintf(out_fd, "phdr_off: .quad %lu\n", ir->phdr_off);
std::fprintf(out_fd, "phdr_num: .quad %lu\n", ir->phdr_num);
std::fprintf(out_fd, "phdr_size: .quad %lu\n", ir->phdr_size);
std::fprintf(out_fd, ".global phdr_off\n.global phdr_num\n.global phdr_size\n");
}
void Generator::compile_interpreter_only_entry() {
compile_section(Section::TEXT);
fprintf(out_fd, ".global _start\n");
fprintf(out_fd, "_start:\n");
// setup the RISC-V stack
fprintf(out_fd, "mov rbx, offset param_passing\n");
fprintf(out_fd, "mov rdi, rsp\n");
fprintf(out_fd, "mov rsi, offset stack_space_end\n");
fprintf(out_fd, "call copy_stack\n");
// mov the stack pointer to the register which holds the stack pointer (refering to the calling convention)
fprintf(out_fd, "mov [rip + register_file + 16], rax\n");
// load the entry address of the binary and call the interpreter
fprintf(out_fd, "mov rdi, %ld\n", ir->p_entry_addr);
fprintf(out_fd, "call unresolved_ijump_handler\n");
fprintf(out_fd, ".type _start,STT_FUNC\n");
fprintf(out_fd, ".size _start,$-_start\n");
}
void Generator::compile_blocks() {
compile_section(Section::TEXT);
if (optimizations & OPT_MBRA) {
reg_alloc = std::make_unique<RegAlloc>(this);
reg_alloc->compile_blocks();
return;
}
for (const auto &block : ir->basic_blocks) {
compile_block(block.get());
}
}
void Generator::compile_block(const BasicBlock *block) {
for (const auto *input : block->inputs) {
// don't try to compile blocks that cannot be independent for now
if (!std::holds_alternative<size_t>(input->info))
return;
}
// align to size to 16 bytes
const size_t stack_size = (((block->variables.size() * 8) + 15) & 0xFFFFFFFF'FFFFFFF0);
fprintf(out_fd, "b%zu:\nsub rsp, %zu\n", block->id, stack_size);
fprintf(out_fd, "# block->virt_start_addr: %#lx\n", block->virt_start_addr);
compile_vars(block);
for (size_t i = 0; i < block->control_flow_ops.size(); ++i) {
const auto &cf_op = block->control_flow_ops[i];
assert(cf_op.source == block);
fprintf(out_fd, "b%zu_cf%zu:\n", block->id, i);
switch (cf_op.type) {
case CFCInstruction::jump:
compile_cf_args(block, cf_op, stack_size);
fprintf(out_fd, "# control flow\n");
fprintf(out_fd, "jmp b%zu\n", std::get<CfOp::JumpInfo>(cf_op.info).target->id);
break;
case CFCInstruction::_return:
compile_ret(block, cf_op, stack_size);
break;
case CFCInstruction::cjump:
compile_cjump(block, cf_op, i, stack_size);
break;
case CFCInstruction::call:
compile_call(block, cf_op, stack_size);
break;
case CFCInstruction::syscall:
compile_syscall(block, cf_op, stack_size);
break;
case CFCInstruction::ijump:
compile_ijump(block, cf_op, stack_size);
break;
case CFCInstruction::unreachable:
err_msgs.emplace_back(ErrType::unreachable, block);
fprintf(out_fd, "lea rdi, [rip + err_unreachable_b%zu]\n", block->id);
fprintf(out_fd, "jmp panic\n");
break;
case CFCInstruction::icall:
compile_icall(block, cf_op, stack_size);
break;
}
}
fprintf(out_fd, ".type b%zu,STT_FUNC\n", block->id);
fprintf(out_fd, ".size b%zu,$-b%zu\n", block->id, block->id);
fprintf(out_fd, "\n");
}
void Generator::compile_call(const BasicBlock *block, const CfOp &op, const size_t stack_size) {
fprintf(out_fd, "# Call Mapping\n");
// Store statics for call
compile_cf_args(block, op, stack_size);
// prevent overflow
fprintf(out_fd, "cmp rsp, stack_space + 524288\n"); // max depth ~65k
fprintf(out_fd, "cmovb rsp, [init_ret_stack_ptr]\n");
// return address
const auto &info = std::get<CfOp::CallInfo>(op.info);
if (info.continuation_block->virt_start_addr <= 0x7FFFFFFF) {
fprintf(out_fd, "push %lu\n", info.continuation_block->virt_start_addr);
} else {
fprintf(out_fd, "mov rax, %lu\n", info.continuation_block->virt_start_addr);
fprintf(out_fd, "push rax\n");
}
fprintf(out_fd, "# control flow\n");
fprintf(out_fd, "call b%zu\nadd rsp, 8\n", std::get<CfOp::CallInfo>(op.info).target->id);
assert(std::get<CfOp::CallInfo>(op.info).continuation_block != nullptr);
fprintf(out_fd, "jmp b%zu\n", std::get<CfOp::CallInfo>(op.info).continuation_block->id);
}
void Generator::compile_icall(const BasicBlock *block, const CfOp &op, const size_t stack_size) {
fprintf(out_fd, "# ICall Mapping\n");
const auto &icall_info = std::get<CfOp::ICallInfo>(op.info);
for (const auto &[var, s_idx] : icall_info.mapping) {
if (var->type == Type::mt) {
continue;
}
fprintf(out_fd, "# s%zu from var v%zu\n", s_idx, var->id);
if (optimizations & OPT_UNUSED_STATIC && std::holds_alternative<size_t>(var->info)) {
const auto orig_static_idx = std::get<size_t>(var->info);
if (orig_static_idx == s_idx) {
fprintf(out_fd, "# Skipped\n");
continue;
}
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [s%zu]\n", rax_from_type(var->type), orig_static_idx);
} else {
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", rax_from_type(var->type), index_for_var(block, var));
}
fprintf(out_fd, "mov [s%zu], rax\n", s_idx);
}
assert(op.in_vars[0] != nullptr);
fprintf(out_fd, "# Get IJump Destination\n");
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", rax_from_type(op.in_vars[0]->type), index_for_var(block, op.in_vars[0]));
fprintf(out_fd, "# destroy stack space\n");
fprintf(out_fd, "add rsp, %zu\n", stack_size + 8);
fprintf(out_fd, "mov rbx, rax\n");
if (icall_info.continuation_block->virt_start_addr <= 0x7FFFFFFF) {
fprintf(out_fd, "push %lu\n", icall_info.continuation_block->virt_start_addr);
} else {
fprintf(out_fd, "mov rax, %lu\n", icall_info.continuation_block->virt_start_addr);
fprintf(out_fd, "push rax\n");
}
fprintf(out_fd, "call ijump_lookup\nadd rsp, 8\n");
assert(std::get<CfOp::ICallInfo>(op.info).continuation_block != nullptr);
fprintf(out_fd, "jmp b%zu\n", std::get<CfOp::ICallInfo>(op.info).continuation_block->id);
}
void Generator::compile_ijump(const BasicBlock *block, const CfOp &op, const size_t stack_size) {
assert(op.type == CFCInstruction::ijump);
fprintf(out_fd, "# IJump Mapping\n");
const auto &ijump_info = std::get<CfOp::IJumpInfo>(op.info);
for (const auto &[var, s_idx] : ijump_info.mapping) {
if (var->type == Type::mt) {
continue;
}
fprintf(out_fd, "# s%zu from var v%zu\n", s_idx, var->id);
if (optimizations & OPT_UNUSED_STATIC && std::holds_alternative<size_t>(var->info)) {
const auto orig_static_idx = std::get<size_t>(var->info);
if (orig_static_idx == s_idx) {
fprintf(out_fd, "# Skipped\n");
continue;
}
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [s%zu]\n", rax_from_type(var->type), orig_static_idx);
} else {
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", rax_from_type(var->type), index_for_var(block, var));
}
fprintf(out_fd, "mov [s%zu], rax\n", s_idx);
}
assert(op.in_vars[0] != nullptr);
assert(ijump_info.targets.empty());
assert((op.in_vars[0]->type == Type::i64) || (op.in_vars[0]->type == Type::imm)); // TODO: only one should be used
fprintf(out_fd, "# Get IJump Destination\n");
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", rax_from_type(op.in_vars[0]->type), index_for_var(block, op.in_vars[0]));
fprintf(out_fd, "# destroy stack space\n");
fprintf(out_fd, "add rsp, %zu\n", stack_size);
fprintf(out_fd, "mov rbx, rax\n");
fprintf(out_fd, "jmp ijump_lookup\n");
}
void Generator::compile_entry() {
compile_section(Section::TEXT);
fprintf(out_fd, ".global _start\n");
fprintf(out_fd, "_start:\n");
// create zero
fprintf(out_fd, "xor rbp, rbp\n");
fprintf(out_fd, "mov rbx, offset param_passing\n");
fprintf(out_fd, "mov rdi, rsp\n");
fprintf(out_fd, "mov rsi, offset stack_space_end\n");
fprintf(out_fd, "call copy_stack\n");
fprintf(out_fd, "mov [init_stack_ptr], rax\n");
fprintf(out_fd, "push 0\npush 0\n");
fprintf(out_fd, "mov [init_ret_stack_ptr], rsp\n");
fprintf(out_fd, "jmp b%zu\n", ir->entry_block);
fprintf(out_fd, ".type _start,STT_FUNC\n");
fprintf(out_fd, ".size _start,$-_start\n");
}
void Generator::compile_err_msgs() {
compile_section(Section::RODATA);
for (const auto &[type, block] : err_msgs) {
switch (type) {
case ErrType::unreachable:
fprintf(out_fd, "err_unreachable_b%zu: .ascii \"Reached unreachable code in block %zu\\n\\0\"\n", block->id, block->id);
break;
}
}
err_msgs.clear();
}
void Generator::compile_vars(const BasicBlock *block) {
for (size_t idx = 0; idx < block->variables.size(); ++idx) {
const auto *var = block->variables[idx].get();
fprintf(out_fd, "# Handling v%zu (v%zu)\n", idx, var->id);
if (var->info.index() == 0) {
continue;
}
if (std::holds_alternative<size_t>(var->info)) {
if (var->type == Type::mt) {
continue;
}
if (optimizations & OPT_UNUSED_STATIC) {
auto has_var_ref = false;
for (size_t j = idx + 1; j < block->variables.size(); ++j) {
const auto *var2 = block->variables[j].get();
if (!std::holds_alternative<std::unique_ptr<Operation>>(var2->info)) {
continue;
}
const auto *op = std::get<std::unique_ptr<Operation>>(var2->info).get();
for (const auto &in_var : op->in_vars) {
if (in_var && in_var == var) {
has_var_ref = true;
break;
}
}
if (has_var_ref) {
break;
}
}
if (!has_var_ref) {
fprintf(out_fd, "# Skipped\n");
continue;
}
}
const auto *reg_str = rax_from_type(var->type);
fprintf(out_fd, "mov rax, [s%zu]\n", std::get<size_t>(var->info));
fprintf(out_fd, "mov [rsp + 8 * %zu], %s\n", idx, reg_str);
continue;
}
assert(var->info.index() != 2);
if (var->info.index() == 1) {
const auto &info = std::get<SSAVar::ImmInfo>(var->info);
if (info.binary_relative) {
fprintf(out_fd, "lea rax, [binary + %ld]\n", info.val);
fprintf(out_fd, "mov [rsp + 8 * %zu], rax\n", idx);
} else {
// use other loading if the immediate is to big
if (info.val > INT32_MAX || info.val < INT32_MIN) {
fprintf(out_fd, "mov rax, %ld\n", info.val);
fprintf(out_fd, "mov QWORD PTR [rsp + 8 * %zu], rax\n", idx);
} else {
fprintf(out_fd, "mov %s [rsp + 8 * %zu], %ld\n", ptr_from_type(var->type), idx, info.val);
}
}
continue;
}
assert(var->info.index() == 3);
const auto *op = std::get<3>(var->info).get();
assert(op != nullptr);
std::array<const char *, 4> in_regs{};
size_t arg_count = 0;
for (size_t in_idx = 0; in_idx < op->in_vars.size(); ++in_idx) {
const auto &in_var = op->in_vars[in_idx];
if (!in_var)
break;
arg_count++;
if (in_var->type == Type::mt)
continue;
const auto *reg_str = op_reg_map_for_type(in_var->type)[in_idx];
// zero the full register so stuff doesn't go broke e.g. in zero-extend, cast
if (is_float(in_var->type)) {
fprintf(out_fd, "pxor %s, %s\n", reg_str, reg_str);
fprintf(out_fd, "mov%s %s, [rsp + 8 * %zu]\n", (in_var->type == Type::f32 ? "d" : "q"), reg_str, index_for_var(block, in_var));
} else {
const auto *full_reg_str = op_reg_map_for_type(Type::i64)[in_idx];
fprintf(out_fd, "xor %s, %s\n", full_reg_str, full_reg_str);
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", reg_str, index_for_var(block, in_var));
}
in_regs[in_idx] = reg_str;
}
auto set_if_op = [this, var, op, in_regs, arg_count](const char *cc_i_1, const char *cc_i_2, const char *cc_fp_1, const char *cc_fp_2, bool allow_fp = true) {
assert(arg_count == 4);
SSAVar *const in1 = op->in_vars[0];
SSAVar *const in2 = op->in_vars[1];
SSAVar *const in3 = op->in_vars[2];
SSAVar *const in4 = op->in_vars[3];
const char *cc_1, *cc_2;
if (is_float(in1->type) || is_float(in2->type)) {
assert(allow_fp);
assert(in1->type == in2->type);
assert(!is_float(var->type));
assert(compatible_types(var->type, in3->type) && compatible_types(var->type, in4->type));
fprintf(out_fd, "comis%s %s, %s\n", fp_op_size_from_type(in1->type), in_regs[0], in_regs[1]);
cc_1 = cc_fp_1;
cc_2 = cc_fp_2;
} else {
const Type cmp_type = (in1->type == Type::imm ? (in2->type == Type::imm ? Type::i64 : in2->type) : in1->type);
assert(compatible_types(var->type, in3->type) && compatible_types(var->type, in4->type));
fprintf(out_fd, "cmp %s, %s\n", op_reg_map_for_type(cmp_type)[0], op_reg_map_for_type(cmp_type)[1]);
cc_1 = cc_i_1;
cc_2 = cc_i_2;
}
fprintf(out_fd, "cmov%s %s, %s\n", cc_1, rax_from_type(var->type), op_reg_map_for_type(var->type)[2]);
fprintf(out_fd, "cmov%s %s, %s\n", cc_2, rax_from_type(var->type), op_reg_map_for_type(var->type)[3]);
};
switch (op->type) {
case Instruction::store:
assert(op->in_vars[0]->type == Type::i64 || op->in_vars[0]->type == Type::imm);
assert(arg_count == 3);
if (is_float(op->in_vars[1]->type)) {
fprintf(out_fd, "mov%s [%s], %s\n", (op->in_vars[1]->type == Type::f32 ? "d" : "q"), in_regs[0], in_regs[1]);
} else {
fprintf(out_fd, "mov %s [%s], %s\n", ptr_from_type(op->in_vars[1]->type), in_regs[0], in_regs[1]);
}
break;
case Instruction::load:
assert(op->in_vars[0]->type == Type::i64 || op->in_vars[0]->type == Type::imm);
assert(op->out_vars[0] == var);
assert(arg_count == 2);
if (is_float(var->type)) {
fprintf(out_fd, "mov%s xmm0, [%s]\n", (op->in_vars[1]->type == Type::f32 ? "d" : "q"), in_regs[0]);
} else {
fprintf(out_fd, "mov %s, %s [%s]\n", op_reg_map_for_type(var->type)[0], ptr_from_type(var->type), in_regs[0]);
}
break;
case Instruction::add:
assert(arg_count == 2);
if (is_float(var->type)) {
assert(var->type == op->in_vars[0]->type && op->in_vars[0]->type == op->in_vars[1]->type);
fprintf(out_fd, "adds%s xmm0, xmm1\n", fp_op_size_from_type(op->in_vars[0]->type));
} else {
fprintf(out_fd, "add rax, rbx\n");
}
break;
case Instruction::sub:
assert(arg_count == 2);
if (is_float(var->type)) {
assert(var->type == op->in_vars[0]->type && op->in_vars[0]->type == op->in_vars[1]->type);
fprintf(out_fd, "subs%s xmm0, xmm1\n", fp_op_size_from_type(op->in_vars[0]->type));
} else {
fprintf(out_fd, "sub rax, rbx\n");
}
break;
case Instruction::mul_l:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "imul rax, rbx\n");
break;
case Instruction::ssmul_h:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "imul rbx\nmov rax, rdx\n");
break;
case Instruction::uumul_h:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "mul rbx\nmov rax, rdx\n");
break;
case Instruction::div:
assert(arg_count == 2 || arg_count == 3);
assert(!is_float(var->type));
if (var->type == Type::i32) {
fprintf(out_fd, "cdq\nidiv ebx\n");
} else {
fprintf(out_fd, "cqo\nidiv rbx\n");
}
fprintf(out_fd, "mov rbx, rdx\n"); // second output is remainder and needs to be in rbx atm
break;
case Instruction::udiv:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "xor rdx, rdx\ndiv rbx\n");
fprintf(out_fd, "mov rbx, rdx\n"); // second output is remainder and needs to be in rbx atm
break;
case Instruction::shl:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "mov cl, bl\nshl %s, cl\n", rax_from_type(op->in_vars[0]->type));
break;
case Instruction::shr:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "mov cl, bl\nshr %s, cl\n", rax_from_type(op->in_vars[0]->type));
break;
case Instruction::sar:
assert(arg_count == 2);
assert(!is_float(var->type));
// make sure that it uses the bit-width of the input operand for shifting
// so that the sign-bit is properly recognized
// TODO: find out if that is a problem elsewhere
fprintf(out_fd, "mov cl, bl\nsar %s, cl\n", rax_from_type(op->in_vars[0]->type));
break;
case Instruction::_or:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "or rax, rbx\n");
break;
case Instruction::_and:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "and rax, rbx\n");
break;
case Instruction::_not:
assert(arg_count == 1);
assert(!is_float(var->type));
fprintf(out_fd, "not rax\n");
break;
case Instruction::_xor:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "xor rax, rbx\n");
break;
case Instruction::cast:
assert(arg_count == 1);
if (is_float(var->type)) {
if (op->in_vars[0]->type == Type::f64 && var->type == Type::f32) {
// nothing to be done
} else if (is_integer(op->in_vars[0]->type)) {
fprintf(out_fd, "mov%s xmm0, %s\n", (var->type == Type::f32 ? "d" : "q"), in_regs[0]);
} else {
assert(0);
}
} else if (is_integer(var->type) && is_float(op->in_vars[0]->type)) {
fprintf(out_fd, "mov%s %s, xmm0\n", (var->type == Type::i32 ? "d" : "q"), rax_from_type(var->type));
}
break;
case Instruction::setup_stack:
assert(arg_count == 0);
fprintf(out_fd, "mov rax, [init_stack_ptr]\n");
break;
case Instruction::zero_extend:
assert(arg_count == 1);
// nothing to be done
break;
case Instruction::sign_extend:
assert(arg_count == 1);
assert(!is_float(var->type));
if (op->in_vars[0]->type != Type::i64) {
fprintf(out_fd, "movsx rax, %s\n", in_regs[0]);
}
break;
case Instruction::slt:
set_if_op("l", "ge", "b", "ae");
break;
case Instruction::sltu:
set_if_op("b", "ae", "", "", false);
break;
case Instruction::sumul_h: /* TODO: implement */
assert(0);
break;
case Instruction::umax:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "cmp %s, %s\n", in_regs[0], in_regs[1]);
fprintf(out_fd, "cmova %s, %s\n", in_regs[0], in_regs[1]);
fprintf(out_fd, "mov %s, %s\n", rax_from_type(op->in_vars[0]->type), in_regs[0]);
break;
case Instruction::umin:
assert(arg_count == 2);
assert(!is_float(var->type));
fprintf(out_fd, "cmp %s, %s\n", in_regs[0], in_regs[1]);
fprintf(out_fd, "cmovb %s, %s\n", in_regs[0], in_regs[1]);
fprintf(out_fd, "mov %s, %s\n", rax_from_type(op->in_vars[0]->type), in_regs[0]);
break;
case Instruction::max:
assert(arg_count == 2);
if (is_float(var->type)) {
fprintf(out_fd, "maxs%s xmm0, xmm1\n", fp_op_size_from_type(var->type));
} else {
fprintf(out_fd, "cmp %s, %s\n", in_regs[0], in_regs[1]);
fprintf(out_fd, "cmovg %s, %s\n", in_regs[0], in_regs[1]);
fprintf(out_fd, "mov %s, %s\n", rax_from_type(op->in_vars[0]->type), in_regs[0]);
}
break;
case Instruction::min:
assert(arg_count == 2);
if (is_float(var->type)) {
fprintf(out_fd, "mins%s xmm0, xmm1\n", fp_op_size_from_type(var->type));
} else {
fprintf(out_fd, "cmp %s, %s\n", in_regs[0], in_regs[1]);
fprintf(out_fd, "cmovl %s, %s\n", in_regs[0], in_regs[1]);
fprintf(out_fd, "mov %s, %s\n", rax_from_type(op->in_vars[0]->type), in_regs[0]);
}
break;
case Instruction::sle:
set_if_op("le", "g", "be", "a");
break;
case Instruction::seq:
set_if_op("e", "ne", "e", "ne");
break;
case Instruction::fmul:
assert(arg_count == 2);
assert(is_float(var->type));
assert(var->type == op->in_vars[0]->type && var->type == op->in_vars[1]->type);
fprintf(out_fd, "muls%s xmm0, xmm1\n", fp_op_size_from_type(var->type));
break;
case Instruction::fdiv:
assert(arg_count == 2);
assert(is_float(var->type));
assert(var->type == op->in_vars[0]->type && var->type == op->in_vars[1]->type);
fprintf(out_fd, "divs%s xmm0, xmm1\n", fp_op_size_from_type(var->type));
break;
case Instruction::fsqrt:
assert(arg_count == 1);
assert(is_float(var->type));
assert(var->type == op->in_vars[0]->type);
fprintf(out_fd, "sqrts%s xmm0, xmm0\n", fp_op_size_from_type(var->type));
break;
case Instruction::fmadd:
assert(arg_count == 3);
assert(is_float(var->type));
assert(var->type == op->in_vars[0]->type && var->type == op->in_vars[1]->type && var->type == op->in_vars[2]->type);
fprintf(out_fd, "muls%s xmm0, xmm1\n", fp_op_size_from_type(var->type));
fprintf(out_fd, "adds%s xmm0, xmm2\n", fp_op_size_from_type(var->type));
break;
case Instruction::fmsub:
assert(arg_count == 3);
assert(is_float(var->type));
assert(var->type == op->in_vars[0]->type && var->type == op->in_vars[1]->type && var->type == op->in_vars[2]->type);
fprintf(out_fd, "muls%s xmm0, xmm1\n", fp_op_size_from_type(var->type));
fprintf(out_fd, "subs%s xmm0, xmm2\n", fp_op_size_from_type(var->type));
break;
case Instruction::fnmadd: {
assert(arg_count == 3);
assert(is_float(var->type));
assert(var->type == op->in_vars[0]->type && var->type == op->in_vars[1]->type && var->type == op->in_vars[2]->type);
const bool is_single_precision = var->type == Type::f32;
fprintf(out_fd, "muls%s xmm0, xmm1\n", fp_op_size_from_type(var->type));
// toggle the sign of the result (negate) of the product by using a mask and xor
fprintf(out_fd, "mov rax, %s\n", is_single_precision ? "0x80000000" : "0x8000000000000000");
fprintf(out_fd, "mov%s xmm3, rax\n", is_single_precision ? "d" : "q");
fprintf(out_fd, "pxor xmm0, xmm3\n");
fprintf(out_fd, "adds%s xmm0, xmm2\n", fp_op_size_from_type(var->type));
break;
}
case Instruction::fnmsub: {
assert(arg_count == 3);
assert(is_float(var->type));
assert(var->type == op->in_vars[0]->type && var->type == op->in_vars[1]->type && var->type == op->in_vars[2]->type);
const bool is_single_precision = var->type == Type::f32;
fprintf(out_fd, "muls%s xmm0, xmm1\n", fp_op_size_from_type(var->type));
// toggle the sign of the result (negate) of the product by using a mask and xor
fprintf(out_fd, "mov rax, %s\n", is_single_precision ? "0x80000000" : "0x8000000000000000");
fprintf(out_fd, "mov%s xmm3, rax\n", is_single_precision ? "d" : "q");
fprintf(out_fd, "pxor xmm0, xmm3\n");
fprintf(out_fd, "subs%s xmm0, xmm2\n", fp_op_size_from_type(var->type));
break;
}
case Instruction::convert:
assert(arg_count == 1);
assert(is_float(var->type) || is_float(op->in_vars[0]->type));
if (is_integer(var->type)) {
compile_rounding_mode(var);
}
fprintf(out_fd, "cvt%s2%s %s, %s\n", convert_name_from_type(op->in_vars[0]->type), convert_name_from_type(var->type), (is_float(var->type) ? "xmm0" : rax_from_type(var->type)),
(is_float(op->in_vars[0]->type) ? "xmm0" : rax_from_type(op->in_vars[0]->type)));
break;
case Instruction::uconvert: {
assert(arg_count == 1);
const Type in_var_type = op->in_vars[0]->type;
assert(is_float(var->type) ^ is_float(in_var_type));
if (is_float(in_var_type)) {
compile_rounding_mode(var);
const bool is_single_precision = in_var_type == Type::f32;
// spread the sign bit of the floating point number to the length of the (result) integer.
// Negate this value and with an "and" operation set so the result to zero if the floating point value is negative
const char *help_reg_name = (is_single_precision ? "ebx" : "rbx");
fprintf(out_fd, "mov%s %s, xmm0\n", (is_single_precision ? "d" : "q"), help_reg_name);
fprintf(out_fd, "sar %s, %u\n", help_reg_name, (is_single_precision ? 31 : 63));
fprintf(out_fd, "not %s\n", help_reg_name);
if (is_single_precision && var->type == Type::i64) {
fprintf(out_fd, "movsxd rbx, ebx\n");
}
fprintf(out_fd, "cvt%s2%s %s, xmm0\n", convert_name_from_type(in_var_type), convert_name_from_type(var->type), rax_from_type(var->type));
fprintf(out_fd, "and rax, rbx\n");
} else {
if (in_var_type == Type::i32) {
// "zero extend" and then convert: use 64bit register
fprintf(out_fd, "mov eax, eax\n");
fprintf(out_fd, "cvt%s2%s xmm0, rax\n", convert_name_from_type(Type::i32), convert_name_from_type(var->type));
} else if (in_var_type == Type::i64) {
// method taken from gcc compiler
fprintf(out_fd, "mov rbx, rax\n");
fprintf(out_fd, "shr rax\n");
fprintf(out_fd, "and rbx, 1\n");
fprintf(out_fd, "or rax, rbx\n");
fprintf(out_fd, "cvt%s2%s xmm0, rax\n", convert_name_from_type(Type::i64), convert_name_from_type(var->type));
fprintf(out_fd, "adds%s xmm0, xmm0\n", fp_op_size_from_type(var->type));
} else {
assert(0);
}
}
break;
}
}
if (var->type != Type::mt) {
if (is_float(var->type)) {
fprintf(out_fd, "mov%s [rsp + 8 * %zu], xmm0\n", (var->type == Type::f32 ? "d" : "q"), index_for_var(block, var));
} else {
for (size_t out_idx = 0; out_idx < op->out_vars.size(); ++out_idx) {
const auto &out_var = op->out_vars[out_idx];
if (!out_var)
continue;
const auto *reg_str = op_reg_map_for_type(out_var->type)[out_idx];
fprintf(out_fd, "mov [rsp + 8 * %zu], %s\n", index_for_var(block, out_var), reg_str);
}
}
}
}
}
void Generator::compile_rounding_mode(const SSAVar *var) {
assert(std::holds_alternative<std::unique_ptr<Operation>>(var->info));
auto &rounding_mode_variant = std::get<std::unique_ptr<Operation>>(var->info).get()->rounding_info;
if (std::holds_alternative<RefPtr<SSAVar>>(rounding_mode_variant)) {
// TODO: Handle dynamic rounding
assert(0);
} else if (std::holds_alternative<RoundingMode>(rounding_mode_variant)) {
uint32_t x86_64_rounding_mode;
switch (std::get<RoundingMode>(rounding_mode_variant)) {
case RoundingMode::NEAREST:
x86_64_rounding_mode = 0x0000;
break;
case RoundingMode::DOWN:
x86_64_rounding_mode = 0x2000;
break;
case RoundingMode::UP:
x86_64_rounding_mode = 0x4000;
break;
case RoundingMode::ZERO:
x86_64_rounding_mode = 0x6000;
break;
default:
assert(0);
break;
}
// clear rounding mode and set correctly
fprintf(out_fd, "sub rsp, 4\n");
fprintf(out_fd, "stmxcsr [rsp]\n");
fprintf(out_fd, "mov edi, [rsp]\n");
fprintf(out_fd, "and edi, 0xFFFF1FFF\n");
if (x86_64_rounding_mode != 0) {
fprintf(out_fd, "or edi, %u\n", x86_64_rounding_mode);
}
fprintf(out_fd, "mov [rsp], edi\n");
fprintf(out_fd, "ldmxcsr [rsp]\n");
fprintf(out_fd, "add rsp, 4\n");
} else {
assert(0);
}
}
void Generator::compile_cf_args(const BasicBlock *block, const CfOp &cf_op, const size_t stack_size) {
const auto *target = cf_op.target();
const auto &target_inputs = cf_op.target_inputs();
if (target->inputs.size() != target_inputs.size()) {
std::cout << "target->inputs.size() = " << target->inputs.size() << "\n";
std::cout << "cf_op.target_inputs().size() = " << target_inputs.size() << "\n";
}
assert(target->inputs.size() == target_inputs.size());
for (size_t i = 0; i < target_inputs.size(); ++i) {
const auto *target_var = target->inputs[i];
const auto *source_var = target_inputs[i];
assert(target_var->type != Type::imm && target_var->info.index() > 1);
if (target_var->type == Type::mt || source_var->type == Type::mt) {
assert(target_var->type == source_var->type);
continue;
}
fprintf(out_fd, "# Setting input %zu\n", i);
const auto target_is_static = std::holds_alternative<size_t>(target_var->info);
if (std::holds_alternative<size_t>(source_var->info)) {
if (optimizations & OPT_UNUSED_STATIC) {
if (target_is_static && std::get<size_t>(source_var->info) == std::get<size_t>(target_var->info)) {
// TODO: see this as a different optimization?
fprintf(out_fd, "# Skipped\n");
continue;
} else {
// when using the unused static optimization, the static load might have been optimized out
// so we need to get the static directly
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [s%zu]\n", rax_from_type(source_var->type), std::get<size_t>(source_var->info));
}
} else {
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", rax_from_type(source_var->type), index_for_var(block, source_var));
}
} else {
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", rax_from_type(source_var->type), index_for_var(block, source_var));
}
if (target_is_static) {
fprintf(out_fd, "mov [s%zu], rax\n", std::get<size_t>(target_var->info));
} else {
fprintf(out_fd, "mov qword ptr [rbx], rax\nadd rbx, 8\n");
}
}
// destroy stack space
fprintf(out_fd, "# destroy stack space\n");
fprintf(out_fd, "add rsp, %zu\n", stack_size);
}
void Generator::compile_ret(const BasicBlock *block, const CfOp &op, const size_t stack_size) {
fprintf(out_fd, "# Ret Mapping\n");
assert(op.info.index() == 2);
const auto &ret_info = std::get<CfOp::RetInfo>(op.info);
for (const auto &[var, s_idx] : ret_info.mapping) {
if (var->type == Type::mt) {
continue;
}
if (optimizations & OPT_UNUSED_STATIC && std::holds_alternative<size_t>(var->info)) {
if (std::get<size_t>(var->info) == s_idx) {
fprintf(out_fd, "# Skipped\n");
continue;
}
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [s%zu]\n", rax_from_type(var->type), std::get<size_t>(var->info));
} else {
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", rax_from_type(var->type), index_for_var(block, var));
}
fprintf(out_fd, "mov [s%zu], rax\n", s_idx);
}
const auto ret_idx = index_for_var(block, op.in_vars[0]);
fprintf(out_fd, "mov rax, [rsp + 8 * %zu]\n", ret_idx);
// destroy stack space
fprintf(out_fd, "# destroy stack space\n");
fprintf(out_fd, "add rsp, %zu\n", stack_size);
fprintf(out_fd, "cmp [rsp + 8], rax\n");
fprintf(out_fd, "jnz 0f\n");
fprintf(out_fd, "ret\n");
fprintf(out_fd, "0:\n");
// reset ret stack
fprintf(out_fd, "mov rsp, [init_ret_stack_ptr]\n");
// do ijump
fprintf(out_fd, "mov rbx, rax\n");
fprintf(out_fd, "jmp ijump_lookup\n");
}
void Generator::compile_cjump(const BasicBlock *block, const CfOp &cf_op, const size_t cond_idx, const size_t stack_size) {
assert(cf_op.in_vars[0] != nullptr && cf_op.in_vars[1] != nullptr);
assert(cf_op.info.index() == 1);
// this breaks when the arg mapping is changed
fprintf(out_fd, "# Get CJump Args\nxor rax, rax\nxor rbx, rbx\n");
if (optimizations & OPT_UNUSED_STATIC && std::holds_alternative<size_t>(cf_op.in_vars[0]->info)) {
// load might be optimized out so get the value directly
fprintf(out_fd, "mov %s, [s%zu]\n", rax_from_type(cf_op.in_vars[0]->type), std::get<size_t>(cf_op.in_vars[0]->info));
} else {
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", rax_from_type(cf_op.in_vars[0]->type), index_for_var(block, cf_op.in_vars[0]));
}
if (optimizations & OPT_UNUSED_STATIC && std::holds_alternative<size_t>(cf_op.in_vars[1]->info)) {
// load might be optimized out so get the value directly
fprintf(out_fd, "mov %s, [s%zu]\n", op_reg_map_for_type(cf_op.in_vars[1]->type)[1], std::get<size_t>(cf_op.in_vars[1]->info));
} else {
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", op_reg_map_for_type(cf_op.in_vars[1]->type)[1], index_for_var(block, cf_op.in_vars[1]));
}
fprintf(out_fd, "cmp rax, rbx\n");
fprintf(out_fd, "# Check CJump cond\n");
const auto &info = std::get<CfOp::CJumpInfo>(cf_op.info);
switch (info.type) {
case CfOp::CJumpInfo::CJumpType::eq:
fprintf(out_fd, "jne b%zu_cf%zu\n", block->id, cond_idx + 1);
break;
case CfOp::CJumpInfo::CJumpType::neq:
fprintf(out_fd, "je b%zu_cf%zu\n", block->id, cond_idx + 1);
break;
case CfOp::CJumpInfo::CJumpType::lt:
fprintf(out_fd, "jae b%zu_cf%zu\n", block->id, cond_idx + 1);
break;
case CfOp::CJumpInfo::CJumpType::gt:
fprintf(out_fd, "jbe b%zu_cf%zu\n", block->id, cond_idx + 1);
break;
case CfOp::CJumpInfo::CJumpType::slt:
fprintf(out_fd, "jge b%zu_cf%zu\n", block->id, cond_idx + 1);
break;
case CfOp::CJumpInfo::CJumpType::sgt:
fprintf(out_fd, "jle b%zu_cf%zu\n", block->id, cond_idx + 1);
break;
}
compile_cf_args(block, cf_op, stack_size);
fprintf(out_fd, "# control flow\n");
fprintf(out_fd, "jmp b%zu\n", info.target->id);
}
void Generator::compile_syscall(const BasicBlock *block, const CfOp &cf_op, const size_t stack_size) {
const auto &info = std::get<CfOp::SyscallInfo>(cf_op.info);
compile_continuation_args(block, info.continuation_mapping);
for (size_t i = 0; i < call_reg.size(); ++i) {
const auto &var = cf_op.in_vars[i];
if (!var)
break;
if (var->type == Type::mt)
continue;
fprintf(out_fd, "# syscall argument %lu\n", i);
if (optimizations & OPT_UNUSED_STATIC && std::holds_alternative<size_t>(var->info)) {
fprintf(out_fd, "mov %s, [s%zu]\n", call_reg[i], std::get<size_t>(var->info));
} else {
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", call_reg[i], index_for_var(block, var));
}
}
if (cf_op.in_vars[6] == nullptr) {
// since the function can theoretically change the value on the stack we do want to add some space here
fprintf(out_fd, "sub rsp, 16\n");
} else {
fprintf(out_fd, "mov rax, [rsp + 8 * %zu]\n", index_for_var(block, cf_op.in_vars[6]));
fprintf(out_fd, "sub rsp, 8\n");
fprintf(out_fd, "push rax\n");
}
fprintf(out_fd, "call syscall_impl\nadd rsp, 16\n");
if (info.static_mapping.size() > 0) {
fprintf(out_fd, "mov [s%zu], rax\n", info.static_mapping.at(0));
}
fprintf(out_fd, "# destroy stack space\n");
fprintf(out_fd, "add rsp, %zu\n", stack_size);
fprintf(out_fd, "jmp b%zu\n", info.continuation_block->id);
}
void Generator::compile_continuation_args(const BasicBlock *block, const std::vector<std::pair<RefPtr<SSAVar>, size_t>> &mapping) {
for (const auto &[var, s_idx] : mapping) {
if (var->type == Type::mt) {
continue;
}
if (optimizations & OPT_UNUSED_STATIC && std::holds_alternative<size_t>(var->info)) {
const auto orig_static_idx = std::get<size_t>(var->info);
if (orig_static_idx == s_idx) {
fprintf(out_fd, "# Skipped\n");
continue;
}
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [s%zu]\n", rax_from_type(var->type), orig_static_idx);
} else {
fprintf(out_fd, "xor rax, rax\n");
fprintf(out_fd, "mov %s, [rsp + 8 * %zu]\n", rax_from_type(var->type), index_for_var(block, var));
}
fprintf(out_fd, "mov [s%zu], rax\n", s_idx);
}
}
void Generator::compile_section(Section section) {
switch (section) {
case Section::DATA:
fprintf(out_fd, ".data\n");
break;
case Section::BSS:
fprintf(out_fd, ".bss\n");
break;
case Section::TEXT:
fprintf(out_fd, ".text\n");
break;
case Section::RODATA:
fprintf(out_fd, ".section .rodata\n");
break;
}
}
| 40.492635 | 188 | 0.558425 | [
"vector"
] |
68a230bd9fbbf77a86d0890aeebb481211aa8a9e | 19,021 | cpp | C++ | ext/include/osgEarthDrivers/wms/ReaderWriterWMS.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 6 | 2015-09-26T15:33:41.000Z | 2021-06-13T13:21:50.000Z | ext/include/osgEarthDrivers/wms/ReaderWriterWMS.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | null | null | null | ext/include/osgEarthDrivers/wms/ReaderWriterWMS.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 5 | 2015-05-04T09:02:23.000Z | 2019-06-17T11:34:12.000Z | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2013 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarth/TileSource>
#include <osgEarth/ImageToHeightFieldConverter>
#include <osgEarth/Registry>
#include <osgEarth/TimeControl>
#include <osgEarth/XmlUtils>
#include <osgEarthUtil/WMS>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osg/ImageSequence>
#include <sstream>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <iomanip>
#include "TileService"
#include "WMSOptions"
#define LC "[WMS] "
using namespace osgEarth;
using namespace osgEarth::Util;
using namespace osgEarth::Drivers;
//----------------------------------------------------------------------------
namespace
{
// All looping ImageSequences deriving from this class will be in sync due to
// a shared reference time.
struct SyncImageSequence : public osg::ImageSequence
{
SyncImageSequence() : osg::ImageSequence() { }
virtual void update(osg::NodeVisitor* nv)
{
setReferenceTime( 0.0 );
osg::ImageSequence::update( nv );
}
};
}
//----------------------------------------------------------------------------
class WMSSource : public TileSource, public SequenceControl
{
public:
WMSSource( const TileSourceOptions& options ) : TileSource( options ), _options(options)
{
_isPlaying = false;
if ( _options.times().isSet() )
{
StringTokenizer( *_options.times(), _timesVec, ",", "", false, true );
OE_INFO << LC << "WMS-T: found " << _timesVec.size() << " times." << std::endl;
for( unsigned i=0; i<_timesVec.size(); ++i )
{
_seqFrameInfoVec.push_back(SequenceFrameInfo());
_seqFrameInfoVec.back().timeIdentifier = _timesVec[i];
}
}
// localize it since we might override them:
_formatToUse = _options.format().value();
_srsToUse = _options.wmsVersion().value() == "1.3.0" ? _options.crs().value() : _options.srs().value();
if (_srsToUse.empty())
{
//If they didn't specify a CRS, see if they specified an SRS and try to use that
_srsToUse = _options.srs().value();
}
}
/** override */
Status initialize( const osgDB::Options* dbOptions )
{
osg::ref_ptr<const Profile> result;
char sep = _options.url()->full().find_first_of('?') == std::string::npos? '?' : '&';
URI capUrl = _options.capabilitiesUrl().value();
if ( capUrl.empty() )
{
capUrl = URI(
_options.url()->full() +
sep +
std::string("SERVICE=WMS") +
std::string("&VERSION=") + _options.wmsVersion().value() +
std::string("&REQUEST=GetCapabilities") );
}
//Try to read the WMS capabilities
osg::ref_ptr<WMSCapabilities> capabilities = WMSCapabilitiesReader::read( capUrl.full(), dbOptions );
if ( !capabilities.valid() )
{
return Status::Error( "Unable to read WMS GetCapabilities." );
}
else
{
OE_INFO << "[osgEarth::WMS] Got capabilities from " << capUrl.full() << std::endl;
}
if ( _formatToUse.empty() && capabilities.valid() )
{
_formatToUse = capabilities->suggestExtension();
OE_INFO << "[osgEarth::WMS] No format specified, capabilities suggested extension " << _formatToUse << std::endl;
}
if ( _formatToUse.empty() )
_formatToUse = "png";
if ( _srsToUse.empty() )
_srsToUse = "EPSG:4326";
std::string wmsFormatToUse = _options.wmsFormat().value();
//Initialize the WMS request prototype
std::stringstream buf;
// first the mandatory keys:
buf
<< std::fixed << _options.url()->full() << sep
<< "SERVICE=WMS"
<< "&VERSION=" << _options.wmsVersion().value()
<< "&REQUEST=GetMap"
<< "&LAYERS=" << _options.layers().value()
<< "&FORMAT=" << ( wmsFormatToUse.empty() ? std::string("image/") + _formatToUse : wmsFormatToUse )
<< "&STYLES=" << _options.style().value()
<< (_options.wmsVersion().value() == "1.3.0" ? "&CRS=" : "&SRS=") << _srsToUse
<< "&WIDTH="<< _options.tileSize().value()
<< "&HEIGHT="<< _options.tileSize().value()
<< "&BBOX=%lf,%lf,%lf,%lf";
// then the optional keys:
if ( _options.transparent().isSet() )
buf << "&TRANSPARENT=" << (_options.transparent() == true ? "TRUE" : "FALSE");
_prototype = "";
_prototype = buf.str();
//OE_NOTICE << "Prototype " << _prototype << std::endl;
osg::ref_ptr<SpatialReference> wms_srs = SpatialReference::create( _srsToUse );
// check for spherical mercator:
if ( wms_srs.valid() && wms_srs->isEquivalentTo( osgEarth::Registry::instance()->getGlobalMercatorProfile()->getSRS() ) )
{
result = osgEarth::Registry::instance()->getGlobalMercatorProfile();
}
else if (wms_srs.valid() && wms_srs->isEquivalentTo( osgEarth::Registry::instance()->getGlobalGeodeticProfile()->getSRS()))
{
result = osgEarth::Registry::instance()->getGlobalGeodeticProfile();
}
// Next, try to glean the extents from the layer list
if ( capabilities.valid() )
{
//TODO: "layers" mights be a comma-separated list. need to loop through and
//combine the extents?? yes
WMSLayer* layer = capabilities->getLayerByName( _options.layers().value() );
if ( layer )
{
double minx, miny, maxx, maxy;
minx = miny = maxx = maxy = 0;
//Check to see if the profile is equivalent to global-geodetic
if (wms_srs->isGeographic())
{
//Try to get the lat lon extents if they are provided
layer->getLatLonExtents(minx, miny, maxx, maxy);
//If we still don't have any extents, just default to global geodetic.
if (!result.valid() && minx == 0 && miny == 0 && maxx == 0 && maxy == 0)
{
result = osgEarth::Registry::instance()->getGlobalGeodeticProfile();
}
}
if (minx == 0 && miny == 0 && maxx == 0 && maxy == 0)
{
layer->getExtents(minx, miny, maxx, maxy);
}
if (!result.valid())
{
result = Profile::create( _srsToUse, minx, miny, maxx, maxy );
}
//Add the layer extents to the list of valid areas
if (minx != 0 || maxx != 0 || miny != 0 || maxy != 0)
{
GeoExtent extent( result->getSRS(), minx, miny, maxx, maxy);
getDataExtents().push_back( DataExtent(extent, 0) );
}
}
}
// Last resort: create a global extent profile (only valid for global maps)
if ( !result.valid() && wms_srs->isGeographic())
{
result = osgEarth::Registry::instance()->getGlobalGeodeticProfile();
}
// JPL uses an experimental interface called TileService -- ping to see if that's what
// we are trying to read:
URI tsUrl = _options.tileServiceUrl().value();
if ( tsUrl.empty() )
{
tsUrl = URI(_options.url()->full() + sep + std::string("request=GetTileService") );
}
OE_INFO << "[osgEarth::WMS] Testing for JPL/TileService at " << tsUrl.full() << std::endl;
_tileService = TileServiceReader::read(tsUrl.full(), dbOptions);
if (_tileService.valid())
{
OE_INFO << "[osgEarth::WMS] Found JPL/TileService spec" << std::endl;
TileService::TilePatternList patterns;
_tileService->getMatchingPatterns(
_options.layers().value(),
_formatToUse,
_options.style().value(),
_srsToUse,
_options.tileSize().value(),
_options.tileSize().value(),
patterns );
if (patterns.size() > 0)
{
result = _tileService->createProfile( patterns );
_prototype = _options.url()->full() + sep + patterns[0].getPrototype();
}
}
else
{
OE_INFO << "[osgEarth::WMS] No JPL/TileService spec found; assuming standard WMS" << std::endl;
}
// Use the override profile if one is passed in.
if ( getProfile() == 0L )
{
setProfile( result.get() );
}
if ( getProfile() )
{
OE_NOTICE << "[osgEarth::WMS] Profile=" << getProfile()->toString() << std::endl;
// set up the cache options properly for a TileSource.
_dbOptions = Registry::instance()->cloneOrCreateOptions( dbOptions );
CachePolicy::NO_CACHE.apply( _dbOptions.get() );
return STATUS_OK;
}
else
{
return Status::Error( "Unable to establish profile" );
}
}
/* override */
bool isDynamic() const
{
// return TRUE if we are reading WMS-T.
return _timesVec.size() > 1;
}
public:
// fetch a tile image from the WMS service and report any exceptions.
osg::Image* fetchTileImage(
const TileKey& key,
const std::string& extraAttrs,
ProgressCallback* progress,
ReadResult& out_response )
{
osg::ref_ptr<osg::Image> image;
std::string uri = createURI(key);
if ( !extraAttrs.empty() )
{
std::string delim = uri.find("?") == std::string::npos ? "?" : "&";
uri = uri + delim + extraAttrs;
}
// Try to get the image first
out_response = URI( uri ).readImage( _dbOptions.get(), progress);
if ( !out_response.succeeded() )
{
// If it failed, try to read it again as a string to get the exception.
out_response = URI( uri ).readString( _dbOptions.get(), progress );
// get the mime type:
std::string mt = out_response.metadata().value( IOMetadata::CONTENT_TYPE );
if ( mt == "application/vnd.ogc.se_xml" || mt == "text/xml" )
{
std::istringstream content( out_response.getString() );
// an XML result means there was a WMS service exception:
Config se;
if ( se.fromXML(content) )
{
Config ex = se.child("serviceexceptionreport").child("serviceexception");
if ( !ex.empty() )
{
OE_NOTICE << "WMS Service Exception: " << ex.toJSON(true) << std::endl;
}
else
{
OE_NOTICE << "WMS Response: " << se.toJSON(true) << std::endl;
}
}
else
{
OE_NOTICE << "WMS: unknown error." << std::endl;
}
}
}
else
{
image = out_response.getImage();
}
return image.release();
}
/** override */
osg::Image* createImage( const TileKey& key, ProgressCallback* progress )
{
osg::ref_ptr<osg::Image> image;
if ( _timesVec.size() > 1 )
{
image = createImageSequence( key, progress );
}
else
{
std::string extras;
if ( _timesVec.size() == 1 )
extras = std::string("TIME=") + _timesVec[0];
ReadResult response;
image = fetchTileImage( key, extras, progress, response );
}
return image.release();
}
/** creates a 3D image from timestamped data. */
osg::Image* createImage3D( const TileKey& key, ProgressCallback* progress )
{
osg::ref_ptr<osg::Image> image;
for( unsigned int r=0; r<_timesVec.size(); ++r )
{
std::string extraAttrs = std::string("TIME=") + _timesVec[r];
ReadResult response;
osg::ref_ptr<osg::Image> timeImage = fetchTileImage( key, extraAttrs, progress, response );
if ( !image.valid() )
{
image = new osg::Image();
image->allocateImage(
timeImage->s(), timeImage->t(), _timesVec.size(),
timeImage->getPixelFormat(),
timeImage->getDataType(),
timeImage->getPacking() );
image->setInternalTextureFormat( timeImage->getInternalTextureFormat() );
}
memcpy( image->data(0,0,r),
timeImage->data(),
osg::minimum(image->getImageSizeInBytes(), timeImage->getImageSizeInBytes()) );
}
return image.release();
}
/** creates a 3D image from timestamped data. */
osg::Image* createImageSequence( const TileKey& key, ProgressCallback* progress )
{
osg::ImageSequence* seq = new SyncImageSequence();
seq->setLoopingMode( osg::ImageStream::LOOPING );
seq->setLength( _options.secondsPerFrame().value() * (double)_timesVec.size() );
if ( this->isSequencePlaying() )
seq->play();
for( unsigned int r=0; r<_timesVec.size(); ++r )
{
std::string extraAttrs = std::string("TIME=") + _timesVec[r];
ReadResult response;
osg::ref_ptr<osg::Image> image = fetchTileImage( key, extraAttrs, progress, response );
if ( image.get() )
{
seq->addImage( image );
}
}
_sequenceCache.insert( seq );
return seq;
}
/** override */
osg::HeightField* createHeightField( const TileKey& key, ProgressCallback* progress)
{
osg::Image* image = createImage(key, progress);
if (!image)
{
OE_INFO << "[osgEarth::WMS] Failed to read heightfield from " << createURI(key) << std::endl;
}
float scaleFactor = 1;
//Scale the heightfield to meters
if ( _options.elevationUnit() == "ft")
{
scaleFactor = 0.3048;
}
ImageToHeightFieldConverter conv;
return conv.convert( image, scaleFactor );
}
std::string createURI( const TileKey& key ) const
{
double minx, miny, maxx, maxy;
key.getExtent().getBounds( minx, miny, maxx, maxy);
char buf[2048];
sprintf(buf, _prototype.c_str(), minx, miny, maxx, maxy);
std::string uri(buf);
// url-ize the uri before returning it
if ( osgDB::containsServerAddress( uri ) )
uri = replaceIn(uri, " ", "%20");
return uri;
}
virtual int getPixelsPerTile() const
{
return _options.tileSize().value();
}
virtual std::string getExtension() const
{
return _formatToUse;
}
public: // SequenceControl
/** Whether the implementation supports these methods */
bool supportsSequenceControl() const
{
return _timesVec.size() > 1;
}
/** Starts playback */
void playSequence()
{
//todo
_isPlaying = true;
}
/** Stops playback */
void pauseSequence()
{
//todo
_isPlaying = false;
}
/** Seek to a specific frame */
void seekToSequenceFrame(unsigned frame)
{
//todo
}
/** Whether the object is in playback mode */
bool isSequencePlaying() const
{
return _isPlaying;
}
/** Gets data about the current frame in the sequence */
const std::vector<SequenceFrameInfo>& getSequenceFrameInfo() const
{
return _seqFrameInfoVec;
}
/** Index of current frame */
int getCurrentSequenceFrameIndex( const osg::FrameStamp* fs ) const
{
if ( _seqFrameInfoVec.size() == 0 )
return 0;
double len = _options.secondsPerFrame().value() * (double)_timesVec.size();
double t = fmod( fs->getSimulationTime(), len ) / len;
return osg::clampBetween(
(int)(t * (double)_seqFrameInfoVec.size()),
(int)0,
(int)_seqFrameInfoVec.size()-1);
}
private:
const WMSOptions _options;
std::string _formatToUse;
std::string _srsToUse;
osg::ref_ptr<TileService> _tileService;
osg::ref_ptr<const Profile> _profile;
std::string _prototype;
std::vector<std::string> _timesVec;
osg::ref_ptr<osgDB::Options> _dbOptions;
bool _isPlaying;
std::vector<SequenceFrameInfo> _seqFrameInfoVec;
mutable Threading::ThreadSafeObserverSet<osg::ImageSequence> _sequenceCache;
};
class WMSSourceFactory : public TileSourceDriver
{
public:
WMSSourceFactory() {}
virtual const char* className()
{
return "WMS Reader";
}
virtual bool acceptsExtension(const std::string& extension) const
{
return osgDB::equalCaseInsensitive( extension, "osgearth_wms" );
}
virtual ReadResult readObject(const std::string& file_name, const Options* opt) const
{
std::string ext = osgDB::getFileExtension( file_name );
if ( !acceptsExtension( ext ) )
{
return ReadResult::FILE_NOT_HANDLED;
}
return new WMSSource( getTileSourceOptions(opt) );
}
};
REGISTER_OSGPLUGIN(osgearth_wms, WMSSourceFactory)
| 32.626072 | 131 | 0.536144 | [
"object",
"vector",
"3d"
] |
68a40ee08c3e8a3446a0a22000860b3e8e89de16 | 12,151 | cpp | C++ | SurgSim/Physics/Fem1DElementBeam.cpp | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 24 | 2015-01-19T16:18:59.000Z | 2022-03-13T03:29:11.000Z | SurgSim/Physics/Fem1DElementBeam.cpp | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 3 | 2018-12-21T14:54:08.000Z | 2022-03-14T12:38:07.000Z | SurgSim/Physics/Fem1DElementBeam.cpp | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 8 | 2015-04-10T19:45:36.000Z | 2022-02-02T17:00:59.000Z | // This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Math/Geometry.h"
#include "SurgSim/Math/OdeEquation.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Physics/Fem1DElementBeam.h"
using SurgSim::Math::getSubMatrix;
using SurgSim::Math::getSubVector;
using SurgSim::Math::setSubMatrix;
using SurgSim::Math::Vector;
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace Physics
{
SURGSIM_REGISTER(SurgSim::Physics::FemElement, SurgSim::Physics::Fem1DElementBeam, Fem1DElementBeam)
Fem1DElementBeam::Fem1DElementBeam()
{
initializeMembers();
}
Fem1DElementBeam::Fem1DElementBeam(std::array<size_t, 2> nodeIds)
{
initializeMembers();
m_nodeIds.assign(nodeIds.cbegin(), nodeIds.cend());
}
Fem1DElementBeam::Fem1DElementBeam(std::shared_ptr<FemElementStructs::FemElementParameter> elementData)
{
initializeMembers();
auto element1DData = std::dynamic_pointer_cast<FemElementStructs::FemElement1DParameter>(elementData);
SURGSIM_ASSERT(element1DData != nullptr) << "Incorrect struct type passed";
SURGSIM_ASSERT(element1DData->nodeIds.size() == 2) << "Incorrect number of nodes for a Fem1D Beam";
m_nodeIds.assign(element1DData->nodeIds.begin(), element1DData->nodeIds.end());
setShearingEnabled(element1DData->enableShear);
setRadius(element1DData->radius);
setMassDensity(element1DData->massDensity);
setPoissonRatio(element1DData->poissonRatio);
setYoungModulus(element1DData->youngModulus);
}
void Fem1DElementBeam::setRadius(double radius)
{
SURGSIM_ASSERT(radius != 0.0) << "The beam radius cannot be set to 0";
SURGSIM_ASSERT(radius > 0.0) << "The beam radius cannot be negative (trying to set it to " << radius << ")";
m_radius = radius;
}
double Fem1DElementBeam::getRadius() const
{
return m_radius;
}
bool Fem1DElementBeam::getShearingEnabled() const
{
return m_haveShear;
}
void Fem1DElementBeam::setShearingEnabled(bool enabled)
{
m_haveShear = enabled;
}
double Fem1DElementBeam::getVolume(const SurgSim::Math::OdeState& state) const
{
const Vector3d A = state.getPosition(m_nodeIds[0]);
const Vector3d B = state.getPosition(m_nodeIds[1]);
return m_A * (B - A).norm();
}
void Fem1DElementBeam::initializeMembers()
{
m_restLength = 0.0;
m_radius = 0.0;
m_A = 0.0;
m_haveShear = true;
m_shearFactor = (5.0 / 8.0);
m_J = 0.0;
// 6 dof per node (x, y, z, thetaX, thetaY, thetaZ)
setNumDofPerNode(6);
}
void Fem1DElementBeam::initialize(const SurgSim::Math::OdeState& state)
{
// Test the validity of the physical parameters
FemElement::initialize(state);
SURGSIM_ASSERT(m_radius > 0) << "Fem1DElementBeam radius should be positive and non-zero. Did you call "
"setCrossSectionCircular(radius) ?";
m_A = M_PI * (m_radius * m_radius);
const double iz = M_PI * (m_radius * m_radius * m_radius * m_radius) / 4.0;
m_J = iz + iz;
// Store the rest state for this beam in m_x0
getSubVector(state.getPositions(), m_nodeIds, 6, &m_x0);
m_restLength = (m_x0.segment<3>(6) - m_x0.segment<3>(0)).norm();
SURGSIM_ASSERT(m_restLength > 0) << "Fem1DElementBeam rest length is zero (degenerate beam)";
computeInitialRotation(state);
// Pre-compute the mass and stiffness matrix
computeMass(state);
computeStiffness(state);
}
const SurgSim::Math::Matrix33d& Fem1DElementBeam::getInitialRotation() const
{
return m_R0;
}
void Fem1DElementBeam::computeMass(const SurgSim::Math::OdeState& state)
{
double& L = m_restLength;
double L2 = L * L;
double AL = m_A * L;
double AL2 = AL * L;
double m = AL * m_rho;
const double Iz = M_PI * (m_radius * m_radius * m_radius * m_radius) / 4.0;
const double Iy = Iz;
m_MLocal.setZero();
// From pg 294 of "Theory of Matrix Structural Analysis" from J.S. Przemieniecki:
// Mass matrix for node0 / node0
m_MLocal(0, 0) = 1.0 / 3.0;
m_MLocal(1, 1) = 13.0 / 35.0 + 6.0 * Iz / (5.0 * AL2);
m_MLocal(1, 5) = 11.0 * L / 210.0 + Iz / (10.0 * AL);
m_MLocal(2, 2) = 13.0 / 35.0 + 6.0 * Iy / (5.0 * AL2);
m_MLocal(2, 4) = -11.0 * L / 210.0 - Iy / (10.0 * AL);
m_MLocal(3, 3) = m_J / (3.0 * m_A);
m_MLocal(4, 2) = m_MLocal(2, 4); // symmetric
m_MLocal(4, 4) = L2 / 105.0 + 2.0 * Iy / (15.0 * m_A);
m_MLocal(5, 1) = m_MLocal(1, 5); // symmetric
m_MLocal(5, 5) = L2 / 105.0 + 2.0 * Iz / (15.0 * m_A);
// Mass matrix for node1 / node1
m_MLocal(6, 6) = 1.0 / 3.0;
m_MLocal(7, 7) = 13.0 / 35.0 + 6.0 * Iz / (5.0 * AL2);
m_MLocal(7, 11) = -11.0 * L / 210.0 - Iz / (10.0 * AL);
m_MLocal(8, 8) = 13.0 / 35.0 + 6.0 * Iy / (5.0 * AL2);
m_MLocal(8, 10) = 11.0 * L / 210.0 + Iy / (10.0 * AL);
m_MLocal(9, 9) = m_J / (3.0 * m_A);
m_MLocal(10, 8) = m_MLocal(8, 10); // symmetric
m_MLocal(10, 10) = L2 / 105.0 + 2.0 * Iy / (15.0 * m_A);
m_MLocal(11, 7) = m_MLocal(7, 11); // symmetric
m_MLocal(11, 11) = L2 / 105.0 + 2.0 * Iz / (15.0 * m_A);
// Mass matrix for node1 / node0
m_MLocal(6, 0) = 1.0 / 6.0;
m_MLocal(7, 1) = 9.0 / 70.0 - 6.0 * Iz / (5.0 * AL2);
m_MLocal(7, 5) = 13.0 * L / 420.0 - Iz / (10.0 * AL);
m_MLocal(8, 2) = 9.0 / 70.0 - 6.0 * Iy / (5.0 * AL2);
m_MLocal(8, 4) = -13.0 * L / 420.0 + Iy / (10.0 * AL);
m_MLocal(9, 3) = m_J / (6.0 * m_A);
m_MLocal(10, 2) = 13.0 * L / 420.0 - Iy / (10.0 * AL);
m_MLocal(10, 4) = -L2 / 140.0 - Iy / (30.0 * m_A);
m_MLocal(11, 1) = -13.0 * L / 420.0 + Iz / (10.0 * AL);
m_MLocal(11, 5) = -L2 / 140.0 - Iz / (30.0 * m_A);
// Mass matrix for node0 / node1
m_MLocal(0, 6) = m_MLocal(6, 0); // symmetric
m_MLocal(1, 7) = m_MLocal(7, 1); // symmetric
m_MLocal(1, 11) = m_MLocal(11, 1); // symmetric
m_MLocal(2, 8) = m_MLocal(8, 2); // symmetric
m_MLocal(2, 10) = m_MLocal(10, 2); // symmetric
m_MLocal(3, 9) = m_MLocal(9, 3); // symmetric
m_MLocal(4, 8) = m_MLocal(8, 4); // symmetric
m_MLocal(4, 10) = m_MLocal(10, 4); // symmetric
m_MLocal(5, 7) = m_MLocal(7, 5); // symmetric
m_MLocal(5, 11) = m_MLocal(11, 5); // symmetric
m_MLocal *= m;
// Transformation Local -> Global
Eigen::Matrix<double, 12, 12> r0;
r0.setZero();
setSubMatrix(m_R0, 0, 0, 3, 3, &r0);
setSubMatrix(m_R0, 1, 1, 3, 3, &r0);
setSubMatrix(m_R0, 2, 2, 3, 3, &r0);
setSubMatrix(m_R0, 3, 3, 3, 3, &r0);
m_M = r0 * m_MLocal.selfadjointView<Eigen::Upper>() * r0.transpose();
}
void Fem1DElementBeam::computeStiffness(const SurgSim::Math::OdeState& state)
{
double& L = m_restLength;
double L2 = L * L;
double L3 = L2 * L;
/// Cross sectional moment of inertia
const double Iz = M_PI * (m_radius * m_radius * m_radius * m_radius) / 4.0;
const double Iy = Iz;
// General expression for shear modulus in terms of Young's modulus and Poisson's ratio
const double g = m_E / (2.0 * (1.0 + m_nu));
/// The shear area in the y and z directions (=0 => no shear) http://en.wikipedia.org/wiki/Timoshenko_beam_theory
double asy = 0.0;
double asz = 0.0;
/// Shear deformation parameters
double phi_y = 0.0;
double phi_z = 0.0;
if (m_haveShear)
{
// Special values for solid cross sections.
asy = m_A * 5.0 / 6.0;
asz = m_A * 5.0 / 6.0;
// From pg 80 of "Theory of Matrix Structural Analysis" from J.S. Przemieniecki:
phi_y = 12.0 * m_E * Iz / (g * asy * L2);
phi_z = 12.0 * m_E * Iy / (g * asz * L2);
}
m_KLocal.setZero();
// From pg 79 of "Theory of Matrix Structural Analysis" from J.S. Przemieniecki:
// Stiffness matrix node 1 / node 1
m_KLocal(0, 0) = m_E * m_A / L;
m_KLocal(1, 1) = 12 * m_E * Iz / (L3 * (1 + phi_y));
m_KLocal(2, 2) = 12 * m_E * Iy / (L3 * (1 + phi_z));
m_KLocal(3, 3) = g * m_J / L;
m_KLocal(4, 4) = (4 + phi_z) * m_E * Iy / (L * (1 + phi_z));
m_KLocal(4, 2) = -6 * m_E * Iy / (L2 * (1 + phi_z)); // Symmetric
m_KLocal(2, 4) = m_KLocal(4, 2); // Symmetric
m_KLocal(5, 5) = (4 + phi_y) * m_E * Iz / (L * (1 + phi_y));
m_KLocal(5, 1) = 6 * m_E * Iz / (L2 * (1 + phi_y)); // Symmetric
m_KLocal(1, 5) = m_KLocal(5, 1); // Symmetric
// Stiffness matrix node 2 / node 2
m_KLocal(6, 6) = m_E * m_A / L;
m_KLocal(7, 7) = 12 * m_E * Iz / (L3 * (1 + phi_y));
m_KLocal(8, 8) = 12 * m_E * Iy / (L3 * (1 + phi_z));
m_KLocal(9, 9) = g * m_J / L;
m_KLocal(10, 10) = (4 + phi_z) * m_E * Iy / (L * (1 + phi_z));
m_KLocal(10, 8) = 6 * m_E * Iy / (L2 * (1 + phi_z)); // Symmetric
m_KLocal(8, 10) = m_KLocal(10, 8); // Symmetric
m_KLocal(11, 11) = (4 + phi_y) * m_E * Iz / (L * (1 + phi_y));
m_KLocal(11, 7) = -6 * m_E * Iz / (L2 * (1 + phi_y)); // Symmetric
m_KLocal(7, 11) = m_KLocal(11, 7); // Symmetric
// Stiffness matrix node 2 / node 1
m_KLocal(6, 0) = -m_E * m_A / L;
m_KLocal(7, 1) = -12 * m_E * Iz / (L3 * (1 + phi_y));
m_KLocal(8, 2) = -12 * m_E * Iy / (L3 * (1 + phi_z));
m_KLocal(9, 3) = -g * m_J / L;
m_KLocal(10, 4) = (2 - phi_z) * m_E * Iy / (L * (1 + phi_z));
m_KLocal(10, 2) = -6 * m_E * Iy / (L2 * (1 + phi_z)); // Anti-symmetric
m_KLocal(8, 4) = -m_KLocal(10, 2); // Anti-symmetric
m_KLocal(11, 5) = (2 - phi_y) * m_E * Iz / (L * (1 + phi_y));
m_KLocal(11, 1) = 6 * m_E * Iz / (L2 * (1 + phi_y)); // Anti-symmetric
m_KLocal(7, 5) = -m_KLocal(11, 1); // Anti-symmetric
// Stiffness matrix node 1 / node 2 (symmetric of node 2 / node 1)
m_KLocal(0, 6) = m_KLocal(6, 0);
m_KLocal(1, 7) = m_KLocal(7, 1);
m_KLocal(2, 8) = m_KLocal(8, 2);
m_KLocal(3, 9) = m_KLocal(9, 3);
m_KLocal(4, 10) = m_KLocal(10, 4);
m_KLocal(2, 10) = m_KLocal(10, 2);
m_KLocal(4, 8) = m_KLocal(8, 4);
m_KLocal(5, 11) = m_KLocal(11, 5);
m_KLocal(1, 11) = m_KLocal(11, 1);
m_KLocal(5, 7) = m_KLocal(7, 5);
// Transformation Local -> Global
Eigen::Matrix<double, 12, 12> r0;
r0.setZero();
setSubMatrix(m_R0, 0, 0, 3, 3, &r0);
setSubMatrix(m_R0, 1, 1, 3, 3, &r0);
setSubMatrix(m_R0, 2, 2, 3, 3, &r0);
setSubMatrix(m_R0, 3, 3, 3, 3, &r0);
m_K = r0 * m_KLocal * r0.transpose();
}
void Fem1DElementBeam::computeInitialRotation(const SurgSim::Math::OdeState& state)
{
// Build (i, j, k) an orthonormal frame
const Vector3d A = state.getPosition(m_nodeIds[0]);
const Vector3d B = state.getPosition(m_nodeIds[1]);
Vector3d i = B - A;
Vector3d j, k;
SURGSIM_ASSERT(SurgSim::Math::buildOrthonormalBasis(&i, &j, &k))
<< "Invalid beam formed by extremities A=(" << A.transpose() << ") B=(" << B.transpose() << ")";
m_R0.col(0) = i;
m_R0.col(1) = j;
m_R0.col(2) = k;
}
SurgSim::Math::Vector Fem1DElementBeam::computeCartesianCoordinate(
const SurgSim::Math::OdeState& state,
const SurgSim::Math::Vector& naturalCoordinate) const
{
SURGSIM_ASSERT(isValidCoordinate(naturalCoordinate)) << "naturalCoordinate must be normalized and length 2.";
const Vector& positions = state.getPositions();
return naturalCoordinate(0) * getSubVector(positions, m_nodeIds[0], getNumDofPerNode()).segment<3>(0) +
naturalCoordinate(1) * getSubVector(positions, m_nodeIds[1], getNumDofPerNode()).segment<3>(0);
}
void Fem1DElementBeam::doUpdateFMDK(const Math::OdeState& state, int options)
{
if (options & SurgSim::Math::OdeEquationUpdate::ODEEQUATIONUPDATE_F)
{
Eigen::Matrix<double, 12, 1> x;
// K.U = F_ext
// K.(x - x0) = F_ext
// 0 = F_ext + F_int, with F_int = -K.(x - x0)
getSubVector(state.getPositions(), m_nodeIds, 6, &x);
m_f.noalias() = -m_K * (x - m_x0);
}
}
SurgSim::Math::Vector Fem1DElementBeam::computeNaturalCoordinate(
const SurgSim::Math::OdeState& state,
const SurgSim::Math::Vector& cartesianCoordinate) const
{
SURGSIM_FAILURE() << "Function " << __FUNCTION__ << " not yet implemented.";
return SurgSim::Math::Vector3d::Zero();
}
} // namespace Physics
} // namespace SurgSim
| 34.519886 | 114 | 0.641099 | [
"geometry",
"vector",
"solid"
] |
68a82d5127175bcc989a0cfb01b483b0b050bba4 | 6,735 | hpp | C++ | Testing/test_string.hpp | Joseph-Heetel/StringCppTemplateLib_Dev | dd9a9a3e4b23f4af21c7dda1e5423c66362885bc | [
"MIT"
] | null | null | null | Testing/test_string.hpp | Joseph-Heetel/StringCppTemplateLib_Dev | dd9a9a3e4b23f4af21c7dda1e5423c66362885bc | [
"MIT"
] | null | null | null | Testing/test_string.hpp | Joseph-Heetel/StringCppTemplateLib_Dev | dd9a9a3e4b23f4af21c7dda1e5423c66362885bc | [
"MIT"
] | null | null | null | #pragma once
#include "jhtstring.hpp"
#include <cassert>
#include <iostream>
namespace jht
{
inline void RunTests_String()
{
std::cout << "RunTests_String\n";
{ // Constructors
String str0;
assert(!str0.IsManaged());
assert(str0.Length() == 0);
assert(strcmp(str0.ConstData(), "") == 0);
String str1 = "a const char* cstr";
assert(!str1.IsManaged());
assert(str1.Length() == strlen("a const char* cstr"));
assert(strcmp(str1.ConstData(), "a const char* cstr") == 0);
String str2("a const char* cstr", 10);
assert(!str2.IsManaged());
assert(str2.Length() == 10);
assert(str2 == String("a const ch"));
}
{ // Static constructors
std::string_view strview("a const char* cstr");
String str0 = String::MakeView(strview);
assert(!str0.IsManaged());
assert(str0.Length() == strview.length());
assert(strcmp(str0.ConstData(), "a const char* cstr") == 0);
String str1 = String::MakeView("a const char* cstr");
assert(!str1.IsManaged());
assert(str1.Length() == strlen("a const char* cstr"));
assert(strcmp(str1.ConstData(), "a const char* cstr") == 0);
String str2 = String::MakeView("a const char* cstr", 10);
assert(!str2.IsManaged());
assert(str2.Length() == 10);
assert(str2 == String("a const ch"));
String str3 = String::MakeManaged('a', 14);
assert(str3.IsManaged());
assert(str3.Length() == 14);
for (int i = 0; i < 14; i++)
{
assert(str3[i] == 'a');
}
String str4 = String::MakeManaged("a const char* cstr");
assert(str4.IsManaged());
assert(str4.Length() == strlen("a const char* cstr"));
assert(strcmp(str4.ConstData(), "a const char* cstr") == 0);
String str5 = String::MakeManaged("a const char* cstr", 10);
assert(str5.IsManaged());
assert(str5.Length() == 10);
assert(str5 == String("a const ch"));
String str6 = String::MakeManaged(64);
assert(str6.IsManaged());
assert(str6.Length() == 64);
String str7 = String::MakeManaged(strview);
assert(str7.IsManaged());
assert(str7.Length() == strview.length());
assert(strcmp(str7.ConstData(), strview.data()) == 0);
}
{ // Copying
String str0;
{
String str1 = String::MakeView("a const char* cstr");
str0 = str1.MakeCopy();
}
assert(str0.IsManaged());
}
{ // Comparison
String str0 = "a";
String str1 = "b";
String str2 = "c";
String str3 = "ab";
String str4 = "bc";
String str5 = "cd";
assert(str0 == str0);
assert(str1 == str1);
assert(str2 == str2);
assert(str3 == str3);
assert(str4 == str4);
assert(str5 == str5);
assert(str0 != str1);
assert(String::Compare(str0, str1) == clamp(strcmp(str0.ConstData(), str1.ConstData()), -1, 1));
assert(String::Compare(str1, str2) == clamp(strcmp(str1.ConstData(), str2.ConstData()), -1, 1));
assert(String::Compare(str2, str3) == clamp(strcmp(str2.ConstData(), str3.ConstData()), -1, 1));
assert(String::Compare(str3, str4) == clamp(strcmp(str3.ConstData(), str4.ConstData()), -1, 1));
assert(String::Compare(str4, str5) == clamp(strcmp(str4.ConstData(), str5.ConstData()), -1, 1));
assert(String::Compare(str5, str0) == clamp(strcmp(str5.ConstData(), str0.ConstData()), -1, 1));
assert(String::Compare(str0, str3) == clamp(strcmp(str0.ConstData(), str3.ConstData()), -1, 1));
assert(String::Compare(str1, str4) == clamp(strcmp(str1.ConstData(), str4.ConstData()), -1, 1));
assert(String::Compare(str2, str5) == clamp(strcmp(str2.ConstData(), str5.ConstData()), -1, 1));
assert(String::Compare(str3, str0) == clamp(strcmp(str3.ConstData(), str0.ConstData()), -1, 1));
assert(String::Compare(str4, str1) == clamp(strcmp(str4.ConstData(), str1.ConstData()), -1, 1));
assert(String::Compare(str5, str2) == clamp(strcmp(str5.ConstData(), str2.ConstData()), -1, 1));
//assert(String::Compare(str0, str1) == strcmp(str0.ConstData(), str1.ConstData()));
//assert(String::Compare(str1, str2) == strcmp(str1.ConstData(), str2.ConstData()));
//assert(String::Compare(str2, str3) == strcmp(str2.ConstData(), str3.ConstData()));
//assert(String::Compare(str3, str4) == strcmp(str3.ConstData(), str4.ConstData()));
//assert(String::Compare(str4, str5) == strcmp(str4.ConstData(), str5.ConstData()));
//assert(String::Compare(str5, str0) == strcmp(str5.ConstData(), str0.ConstData()));
//assert(String::Compare(str0, str3) == strcmp(str0.ConstData(), str3.ConstData()));
//assert(String::Compare(str1, str4) == strcmp(str1.ConstData(), str4.ConstData()));
//assert(String::Compare(str2, str5) == strcmp(str2.ConstData(), str5.ConstData()));
//assert(String::Compare(str3, str0) == strcmp(str3.ConstData(), str0.ConstData()));
//assert(String::Compare(str4, str1) == strcmp(str4.ConstData(), str1.ConstData()));
//assert(String::Compare(str5, str2) == strcmp(str5.ConstData(), str2.ConstData()));
}
{ // Fill operation
String templ = "__________";
String entry = "01234";
String str0 = templ.MakeCopy();
str0.Fill('+');
JHT_ITERATE(jht::String, str0, iter)
{
assert(*iter == '+');
}
String str1 = templ.MakeCopy();
str1.Fill(entry);
assert(str1 == "01234_____");
String str2 = templ.MakeCopy();
str2.Fill(entry, 3);
assert(str2 == "___01234__");
}
{ // Split
String templ0 = "I \nlike\n Ns \t\n Ps";
String templ1 = "\n\n";
String templ2 = "\n .\n\n";
std::vector<String> testvector;
templ0.Split('\n', testvector);
assert(testvector.size() == 4);
assert(testvector[0] == "I ");
assert(testvector[1] == "like");
assert(testvector[2] == " Ns \t");
assert(testvector[3] == " Ps");
testvector.clear();
templ1.Split('\n', testvector);
assert(testvector.size() == 0);
testvector.clear();
templ2.Split('\n', testvector);
assert(testvector.size() == 1);
assert(testvector[0] == " .");
}
{ // SubString
String templ = "0123456789";
String str0 = templ.SubString(0);
assert(str0 == templ);
String str1 = templ.SubString(1, 3);
assert(str1 == "123");
String str2 = templ.SubString(0, 9);
assert(str2 == "012345678" && str2 != templ);
String str3 = templ.SubString(9);
assert(str3 == "9");
String str4 = templ.SubString(95);
assert(str4.IsEmpty());
String str5 = templ.SubString(0, 0);
assert(str5.IsEmpty());
}
{ // Trimming
String templ0 = "\u0009\u000A\u000B\u000C\u000D\u0020.\u0009\u000A\u000B\u000C\u000D\u0020";
String templ1 = "\u0009\u000A\u000B\u000C\u000D\u0020";
String templ2;
String str0 = templ0.Trimmed();
assert(str0 == ".");
String str1 = templ1.Trimmed();
assert(str1.IsEmpty());
String str2 = templ2.Trimmed();
assert(str2.IsEmpty());
}
}
} | 32.853659 | 99 | 0.62346 | [
"vector"
] |
68af204852d5a4d3e11a5d1238208099e29209d8 | 3,770 | cpp | C++ | inference-engine/src/vpu/graph_transformer/src/stages/static_shape_nms.cpp | cwzrad/openvino | ae4bd370eac7c695bd797a31e62317d328dbe742 | [
"Apache-2.0"
] | 1 | 2020-08-25T06:01:49.000Z | 2020-08-25T06:01:49.000Z | inference-engine/src/vpu/graph_transformer/src/stages/static_shape_nms.cpp | cwzrad/openvino | ae4bd370eac7c695bd797a31e62317d328dbe742 | [
"Apache-2.0"
] | 1 | 2021-07-24T15:22:27.000Z | 2021-07-24T15:22:27.000Z | inference-engine/src/vpu/graph_transformer/src/stages/static_shape_nms.cpp | cwzrad/openvino | ae4bd370eac7c695bd797a31e62317d328dbe742 | [
"Apache-2.0"
] | 1 | 2020-08-13T08:33:55.000Z | 2020-08-13T08:33:55.000Z | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vpu/frontend/frontend.hpp>
#include <ngraph/op/non_max_suppression.hpp>
#include <memory>
#include <set>
namespace vpu {
namespace {
class StaticShapeNMS final : public StageNode {
private:
StagePtr cloneImpl() const override {
return std::make_shared<StaticShapeNMS>(*this);
}
void propagateDataOrderImpl(StageDataInfo<DimsOrder>& orderInfo) override {
}
void getDataStridesRequirementsImpl(StageDataInfo<StridesRequirement>& stridesInfo) override {
}
void finalizeDataLayoutImpl() override {
}
void getBatchSupportInfoImpl(StageDataInfo<BatchSupport>& batchInfo) override {
}
StageSHAVEsRequirements getSHAVEsRequirementsImpl() const override {
return StageSHAVEsRequirements::OnlyOne;
}
void initialCheckImpl() const override {
assertInputsOutputsTypes(this,
{{DataType::FP16},
{DataType::FP16},
{DataType::S32},
{DataType::FP16},
{DataType::FP16}},
{{DataType::S32},
{DataType::S32}});
}
void finalCheckImpl() const override {
initialCheckImpl();
}
void serializeParamsImpl(BlobSerializer& serializer) const override {
bool center_point_box = attrs().get<bool>("center_point_box");
serializer.append(static_cast<int32_t>(center_point_box));
}
void serializeDataImpl(BlobSerializer& serializer) const override {
auto input1 = inputEdges()[0]->input();
auto input2 = inputEdges()[1]->input();
auto input3 = inputEdges()[2]->input();
auto input4 = inputEdges()[3]->input();
auto input5 = inputEdges()[4]->input();
auto outputData = outputEdges()[0]->output();
auto outputDims = outputEdges()[1]->output();
input1->serializeBuffer(serializer);
input2->serializeBuffer(serializer);
input3->serializeBuffer(serializer);
input4->serializeBuffer(serializer);
input5->serializeBuffer(serializer);
outputData->serializeBuffer(serializer);
outputDims->serializeBuffer(serializer);
}
};
} // namespace
void FrontEnd::parseStaticShapeNMS(const Model& model, const ie::CNNLayerPtr& layer, const DataVector& inputs, const DataVector& outputs) const {
VPU_THROW_UNLESS(inputs.size() >= 2 && inputs.size() <= 5,
"StaticShapeNMS parsing failed, expected number of input is in range [2, 5], but {} provided",
inputs.size());
VPU_THROW_UNLESS(outputs.size() == 2,
"StaticShapeNMS parsing failed, expected number of outputs: 2, but {} provided",
outputs.size());
const auto sortResultDescending = layer->GetParamAsBool("sort_result_descending");
const auto boxEncoding = layer->GetParamAsString("box_encoding");
VPU_THROW_UNLESS(sortResultDescending == false,
"StaticShapeNMS: parameter sortResultDescending=true is not supported on VPU");
VPU_THROW_UNLESS(boxEncoding == "corner" || boxEncoding == "center",
"StaticShapeNMS: boxEncoding currently supports only two values: \"corner\" and \"center\" "
"while {} was provided", boxEncoding);
DataVector tempInputs = inputs;
for (auto fake = inputs.size(); fake < 5; fake++) {
tempInputs.push_back(model->addFakeData());
}
auto stage = model->addNewStage<StaticShapeNMS>(layer->name, StageType::StaticShapeNMS, layer, tempInputs, outputs);
stage->attrs().set<bool>("center_point_box", boxEncoding == "center");
}
} // namespace vpu
| 35.233645 | 145 | 0.644032 | [
"model"
] |
68b21aa1f10e5dad08b31bb476749b5b1915f1a0 | 8,576 | cpp | C++ | Engine/ChunkMesh.cpp | tairoman/CraftClone | b50e40f5fb4a10febe8a17a37a439aa238d8deb3 | [
"MIT"
] | 5 | 2018-11-17T18:15:44.000Z | 2020-04-26T11:27:16.000Z | Engine/ChunkMesh.cpp | tairoman/CraftClone | b50e40f5fb4a10febe8a17a37a439aa238d8deb3 | [
"MIT"
] | 1 | 2020-04-22T13:03:52.000Z | 2020-04-23T12:57:40.000Z | Engine/ChunkMesh.cpp | tairoman/CraftClone | b50e40f5fb4a10febe8a17a37a439aa238d8deb3 | [
"MIT"
] | null | null | null | #include "ChunkMesh.h"
#include "Chunk.h"
using namespace Engine;
namespace
{
// How many block types there are
constexpr auto numTypes = 4;
// How many vertices per block side
constexpr auto numVertices = 6;
constexpr auto texArraySize = numTypes * numVertices;
constexpr std::array<glm::vec2, texArraySize> texLookup {
/* 0. GRASS SIDE */
glm::vec2{ 0.635f, 0.9375f },
glm::vec2{ 0.759f, 0.9375f },
glm::vec2{ 0.635f, 1.0f },
glm::vec2{ 0.635f, 1.0f },
glm::vec2{ 0.759f, 0.9375f },
glm::vec2{ 0.759f, 1.0f },
/* 1. GRASS TOP */
glm::vec2{ 0.507f, 0.557f },
glm::vec2{ 0.633f, 0.557f },
glm::vec2{ 0.507f, 0.619f },
glm::vec2{ 0.507f, 0.619f },
glm::vec2{ 0.633f, 0.557f },
glm::vec2{ 0.633f, 0.619f },
/* 2. DIRT */
glm::vec2{ 0.634f, 0.875f },
glm::vec2{ 0.759f, 0.875f },
glm::vec2{ 0.634f, 0.936f },
glm::vec2{ 0.634f, 0.936f },
glm::vec2{ 0.759f, 0.875f },
glm::vec2{ 0.759f, 0.936f },
/* 3. STONE */
glm::vec2{ 0.254f, 0.62f },
glm::vec2{ 0.379f, 0.62f },
glm::vec2{ 0.254f, 0.683f },
glm::vec2{ 0.254f, 0.683f },
glm::vec2{ 0.379f, 0.62f },
glm::vec2{ 0.379f, 0.683f },
};
std::size_t atlasLookup(BlockType type, BlockSide side)
{
switch (type) {
case BlockType::GRASS:
switch(side) {
case BlockSide::SIDE: return 0 * 6;
case BlockSide::TOP: return 1 * 6;
case BlockSide::BOTTOM: return 2 * 6;
}
case BlockType::DIRT: return 2*6;
case BlockType::STONE: return 3*6;
}
return 0;
}
}
ChunkMesh::ChunkMesh(Chunk* chunk)
: m_chunk(chunk)
{
m_vertices.reserve(ChunkData::BLOCKS * 6 * 6);
}
const std::vector<Vertex>& ChunkMesh::vertices() const
{
return m_vertices;
}
void ChunkMesh::regenerate()
{
m_vertices.clear();
for(auto x = 0; x < ChunkData::BLOCKS_X; x++) {
for (auto y = 0; y < ChunkData::BLOCKS_Y; y++) {
for (auto z = 0; z < ChunkData::BLOCKS_Z; z++) {
const BlockType typ = m_chunk->get(x,y,z);
if (typ == BlockType::AIR){
continue;
}
const auto offset_side = atlasLookup(typ, BlockSide::SIDE);
const auto offset_top = atlasLookup(typ, BlockSide::TOP);
const auto offset_bottom = atlasLookup(typ, BlockSide::BOTTOM);
// - X
auto negXNeighbor = m_chunk->neighbor(Direction::NegX);
bool negXCond = x != 0 ? m_chunk->get(x-1,y,z) == BlockType::AIR : (negXNeighbor ? negXNeighbor->get(ChunkData::BLOCKS_X - 1, y, z) == BlockType::AIR : true);
if (negXCond) {
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 0), glm::vec3(x, y, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 1), glm::vec3(x, y, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 2), glm::vec3(x, y + 1, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 3), glm::vec3(x, y + 1, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 4), glm::vec3(x, y, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 5), glm::vec3(x, y + 1, z + 1) });
}
// + X
auto posXNeighbor = m_chunk->neighbor(Direction::PlusX);
bool posXCond = x != ChunkData::BLOCKS_X - 1 ? m_chunk->get(x+1,y,z) == BlockType::AIR : (posXNeighbor ? posXNeighbor->get(0, y, z) == BlockType::AIR : true);
if (posXCond) {
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 0), glm::vec3(x + 1, y, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 1), glm::vec3(x + 1, y, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 2), glm::vec3(x + 1, y + 1, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 3), glm::vec3(x + 1, y + 1, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 4), glm::vec3(x + 1, y, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 5), glm::vec3(x + 1, y + 1, z) });
}
// - Y
auto negYNeighbor = m_chunk->neighbor(Direction::NegY);
bool negYCond = y != 0 ? m_chunk->get(x,y-1,z) == BlockType::AIR : (negYNeighbor ? negYNeighbor->get(x, ChunkData::BLOCKS_Y - 1, z) == BlockType::AIR : true);
if (negYCond) {
m_vertices.emplace_back(Vertex { texLookup.at(offset_bottom + 0), glm::vec3(x, y, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_bottom + 1), glm::vec3(x, y, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_bottom + 2), glm::vec3(x + 1, y, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_bottom + 3), glm::vec3(x + 1, y, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_bottom + 4), glm::vec3(x, y, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_bottom + 5), glm::vec3(x + 1, y, z) });
}
// + Y
auto posYNeighbor = m_chunk->neighbor(Direction::PlusY);
bool posYCond = y != ChunkData::BLOCKS_Y - 1 ? m_chunk->get(x,y+1,z) == BlockType::AIR : (posYNeighbor ? posYNeighbor->get(x, 0, z) == BlockType::AIR : true);
if (posYCond) {
m_vertices.emplace_back(Vertex { texLookup.at(offset_top + 0), glm::vec3(x, y + 1, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_top + 1), glm::vec3(x, y + 1, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_top + 2), glm::vec3(x + 1, y + 1, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_top + 3), glm::vec3(x + 1, y + 1, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_top + 4), glm::vec3(x, y + 1, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_top + 5), glm::vec3(x + 1, y + 1, z + 1) });
}
// - Z
auto negZNeighbor = m_chunk->neighbor(Direction::NegZ);
bool negZCond = z != 0 ? m_chunk->get(x,y,z-1) == BlockType::AIR : (negZNeighbor ? negZNeighbor->get(x, y, ChunkData::BLOCKS_Z - 1) == BlockType::AIR : true);
if (negZCond) {
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 0), glm::vec3(x + 1, y, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 1), glm::vec3(x, y, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 2), glm::vec3(x + 1, y + 1, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 3), glm::vec3(x + 1, y + 1, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 4), glm::vec3(x, y, z) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 5), glm::vec3(x, y + 1, z) });
}
// + Z
auto posZNeighbor = m_chunk->neighbor(Direction::PlusZ);
bool posZCond = z != ChunkData::BLOCKS_Z - 1 ? m_chunk->get(x,y,z+1) == BlockType::AIR : (posZNeighbor ? posZNeighbor->get(x, y, 0) == BlockType::AIR : true);
if (posZCond) {
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 0), glm::vec3(x, y, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 1), glm::vec3(x + 1, y, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 2), glm::vec3(x, y + 1, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 3), glm::vec3(x, y + 1, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 4), glm::vec3(x + 1, y, z + 1) });
m_vertices.emplace_back(Vertex { texLookup.at(offset_side + 5), glm::vec3(x + 1, y + 1, z + 1) });
}
}
}
}
}
| 49.287356 | 174 | 0.53125 | [
"vector"
] |
68b249ba2d25bd4f9a51537be4d1a1cbaeea961b | 29,987 | cpp | C++ | Stars45/Weapon.cpp | RogerioY/starshatter-open | 3a507e08b1d4e5970b27401a7e6517570d529400 | [
"BSD-3-Clause"
] | null | null | null | Stars45/Weapon.cpp | RogerioY/starshatter-open | 3a507e08b1d4e5970b27401a7e6517570d529400 | [
"BSD-3-Clause"
] | 4 | 2019-09-05T22:22:57.000Z | 2021-03-28T02:09:24.000Z | Stars45/Weapon.cpp | RogerioY/starshatter-open | 3a507e08b1d4e5970b27401a7e6517570d529400 | [
"BSD-3-Clause"
] | null | null | null | /* Starshatter OpenSource Distribution
Copyright (c) 1997-2004, Destroyer Studios LLC.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name "Destroyer Studios" nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
SUBSYSTEM: Stars.exe
FILE: Weapon.cpp
AUTHOR: John DiCamillo
OVERVIEW
========
Weapon class
*/
#include "MemDebug.h"
#include "Weapon.h"
#include "Shot.h"
#include "Drone.h"
#include "Contact.h"
#include "Ship.h"
#include "Sim.h"
#include "SimEvent.h"
#include "Random.h"
#include "NetGame.h"
#include "NetUtil.h"
#include "Game.h"
#include "Solid.h"
// +----------------------------------------------------------------------+
Weapon::Weapon(WeaponDesign* d, int nmuz, Vec3* muzzles, double az, double el)
: System(WEAPON, d->type, d->name, d->value, d->capacity, d->capacity,
d->recharge_rate),
design(d), group(d->group), ammo(-1), ripple_count(0),
aim_azimuth((float) az), aim_elevation((float) el),
old_azimuth(0.0f), old_elevation(0.0f), aim_time(0),
enabled(true), refire(0.0f),
mass(d->carry_mass), resist(d->carry_resist),
guided(d->guided), shot_speed(d->speed),
active_barrel(0), locked(false), centered(false), firing(false), blocked(false),
index(0), target(0), subtarget(0), beams(0), orders(MANUAL),
control(SINGLE_FIRE), sweep(SWEEP_TIGHT), turret(0), turret_base(0)
{
ZeroMemory(visible_stores, sizeof(visible_stores));
if (design->primary)
abrv = Game::GetText("sys.weapon.primary.abrv");
else
abrv = Game::GetText("sys.weapon.secondary.abrv");
nbarrels = nmuz;
if (nbarrels > MAX_BARRELS)
nbarrels = MAX_BARRELS;
if (nbarrels == 0 && design->nbarrels > 0) {
nbarrels = design->nbarrels;
for (int i = 0; i < nbarrels; i++)
muzzle_pts[i] = rel_pts[i] = design->muzzle_pts[i] * design->scale;
ammo = design->ammo * nbarrels;
}
else if (nbarrels == 1 && design->nstores > 0) {
nbarrels = design->nstores;
for (int i = 0; i < nbarrels; i++)
muzzle_pts[i] = rel_pts[i] = (muzzles[0] + design->attachments[i]);
ammo = nbarrels;
}
else {
for (int i = 0; i < nbarrels; i++)
muzzle_pts[i] = rel_pts[i] = muzzles[i];
ammo = design->ammo * nbarrels;
}
if (design->syncro)
active_barrel = -1;
emcon_power[0] = 0;
emcon_power[1] = 0;
emcon_power[2] = 100;
aim_az_max = design->aim_az_max;
aim_az_min = design->aim_az_min;
aim_az_rest = design->aim_az_rest;
aim_el_max = design->aim_el_max;
aim_el_min = design->aim_el_min;
aim_el_rest = design->aim_el_rest;
}
// +----------------------------------------------------------------------+
Weapon::Weapon(const Weapon& w)
: System(w), design(w.design), ammo(-1), ripple_count(0),
enabled(true), refire(0.0f),
mass(w.mass), resist(w.resist),
aim_azimuth(w.aim_azimuth), aim_elevation(w.aim_elevation),
old_azimuth(0.0f), old_elevation(0.0f), aim_time(0),
guided(w.guided), shot_speed(w.shot_speed),
active_barrel(0), locked(false), centered(false), firing(false), blocked(false),
target(0), subtarget(0), beams(0), orders(MANUAL),
control(SINGLE_FIRE), sweep(SWEEP_TIGHT), group(w.group),
aim_az_max(w.aim_az_max), aim_az_min(w.aim_az_min), aim_az_rest(w.aim_az_rest),
aim_el_max(w.aim_el_max), aim_el_min(w.aim_el_min), aim_el_rest(w.aim_el_rest),
turret(0), turret_base(0)
{
Mount(w);
ZeroMemory(visible_stores, sizeof(visible_stores));
nbarrels = w.nbarrels;
for (int i = 0; i < nbarrels; i++) {
muzzle_pts[i] = rel_pts[i] = w.muzzle_pts[i];
}
ammo = design->ammo * nbarrels;
if (design->syncro)
active_barrel = -1;
if (design->beam) {
beams = new(__FILE__,__LINE__) Shot* [nbarrels];
ZeroMemory(beams, sizeof(Shot*) * nbarrels);
}
if (aim_az_rest >= 2*PI)
aim_az_rest = design->aim_az_rest;
if (aim_el_rest >= 2*PI)
aim_el_rest = design->aim_el_rest;
}
// +--------------------------------------------------------------------+
Weapon::~Weapon()
{
if (beams) {
for (int i = 0; i < nbarrels; i++) {
if (beams[i]) {
Ignore(beams[i]);
delete beams[i];
beams[i] = 0;
}
}
delete [] beams;
}
GRAPHIC_DESTROY(turret);
GRAPHIC_DESTROY(turret_base);
for (int i = 0; i < MAX_BARRELS; i++)
GRAPHIC_DESTROY(visible_stores[i]);
}
// +--------------------------------------------------------------------+
bool
Weapon::IsPrimary() const
{
return design->primary;
}
bool
Weapon::IsDrone() const
{
return design->drone;
}
bool
Weapon::IsDecoy() const
{
return design->decoy_type != 0;
}
bool
Weapon::IsProbe() const
{
return design->probe != 0;
}
bool
Weapon::IsMissile() const
{
return !design->primary;
}
bool
Weapon::IsBeam() const
{
return design->beam;
}
// +--------------------------------------------------------------------+
Shot*
Weapon::GetBeam(int i)
{
if (beams && i >= 0 && i < nbarrels)
return beams[i];
return 0;
}
// +--------------------------------------------------------------------+
void
Weapon::SetOwner(Ship* s)
{
ship = s;
if (design->turret_model) {
Solid* t = new(__FILE__,__LINE__) Solid;
t->UseModel(design->turret_model);
turret = t;
}
if (design->turret_base_model) {
Solid* t = new(__FILE__,__LINE__) Solid;
t->UseModel(design->turret_base_model);
turret_base = t;
}
if (!design->primary &&
design->visible_stores &&
ammo == nbarrels &&
design->shot_model != 0)
{
for (int i = 0; i < nbarrels; i++) {
Solid* s = new(__FILE__,__LINE__) Solid;
s->UseModel(design->shot_model);
visible_stores[i] = s;
}
}
}
Solid*
Weapon::GetTurret()
{
return turret;
}
Solid*
Weapon::GetTurretBase()
{
return turret_base;
}
Solid*
Weapon::GetVisibleStore(int i)
{
if (i >= 0 && i < MAX_BARRELS)
return visible_stores[i];
return 0;
}
void
Weapon::SetAmmo(int a)
{
if (a >= 0) {
if (active_barrel >= 0 && design->visible_stores) {
while (a < ammo) {
if (active_barrel >= nbarrels)
active_barrel = 0;
if (visible_stores[active_barrel]) {
GRAPHIC_DESTROY(visible_stores[active_barrel]);
active_barrel++;
ammo--;
}
}
}
ammo = a;
}
}
// +--------------------------------------------------------------------+
void
Weapon::ExecFrame(double seconds)
{
System::ExecFrame(seconds);
if (refire > 0)
refire -= (float) seconds;
locked = false;
centered = false;
if (!ship)
return;
if (orders == POINT_DEFENSE && enabled)
SelectTarget();
if (beams && !target) {
for (int i = 0; i < nbarrels; i++) {
if (beams[i]) {
// aim beam straight:
Aim();
SetBeamPoints(false);
return;
}
}
}
if (design->self_aiming) {
Track(target, subtarget);
}
else if (turret) {
ZeroAim();
}
if (ship->CheckFire())
return;
// aim beam at target:
bool aim_beams = false;
if (beams) {
for (int i = 0; i < nbarrels; i++) {
if (beams[i]) {
aim_beams = true;
SetBeamPoints(true);
break;
}
}
}
if (!aim_beams) {
if (ripple_count > 0) {
if (Fire())
ripple_count--;
}
else if (locked && !blocked) {
if (!ship->IsHostileTo(target))
return;
if (orders == AUTO && centered) {
if (energy >= design->charge &&
(ammo < 0 || target && target->Integrity() >= 1) &&
objective.length() < design->max_range)
Fire();
}
else if (orders == POINT_DEFENSE) {
if (energy >= design->min_charge &&
(ammo < 0 || target && target->Integrity() >= 1) &&
objective.length() < design->max_range)
Fire();
}
}
}
}
// +----------------------------------------------------------------------+
void
Weapon::Distribute(double delivered_energy, double seconds)
{
if (UsesWatts()) {
if (seconds < 0.01)
seconds = 0.01;
// convert Joules to Watts:
energy = (float) (delivered_energy/seconds);
}
else if (!Game::Paused()) {
energy += (float) (delivered_energy * 1.25);
if (energy > capacity)
energy = capacity;
else if (energy < 0)
energy = 0.0f;
}
}
// +--------------------------------------------------------------------+
bool
Weapon::Update(SimObject* obj)
{
if (obj == target) {
target = 0;
}
else if (beams) {
for (int i = 0; i < nbarrels; i++)
if (obj == beams[i])
beams[i] = 0;
}
return SimObserver::Update(obj);
}
const char*
Weapon::GetObserverName() const
{
static char name[256];
sprintf_s(name, "Weapon %s", design->name.data());
return name;
}
// +--------------------------------------------------------------------+
void
Weapon::SetFiringOrders(int o)
{
if (o >= MANUAL && o <= POINT_DEFENSE)
orders = o;
}
void
Weapon::SetControlMode(int m)
{
if (m >= SINGLE_FIRE && m <= SALVO_FIRE)
control = m;
}
void
Weapon::SetSweep(int s)
{
if (s >= SWEEP_NONE && s <= SWEEP_WIDE)
sweep = s;
}
// +--------------------------------------------------------------------+
bool
Weapon::CanTarget(DWORD classification) const
{
return (design->target_type & classification) ? true : false;
}
// +--------------------------------------------------------------------+
void
Weapon::SetTarget(SimObject* targ, System* sub)
{
// check self targeting:
if (targ == (SimObject*) ship)
return;
// check target class filter:
if (targ) {
switch (targ->Type()) {
case SimObject::SIM_SHIP: {
Ship* tgt_ship = (Ship*) targ;
if ((tgt_ship->Class() & design->target_type) == 0)
return;
}
break;
case SimObject::SIM_SHOT:
return;
case SimObject::SIM_DRONE: {
if ((design->target_type & Ship::DRONE) == 0)
return;
}
break;
default:
return;
}
}
// if ok, target this object:
if (target != targ) {
target = targ;
if (target)
Observe(target);
}
subtarget = sub;
}
// +--------------------------------------------------------------------+
void
Weapon::SelectTarget()
{
bool select_locked = false;
SimObject* targ = 0;
double dist = 1e9;
double az = 0;
double el = 0;
if (ammo && enabled && (availability > crit_level)) {
ZeroAim();
ListIter<Contact> contact = ship->ContactList();
// lock onto any threatening shots first (if we can):
if (design->target_type & Ship::DRONE) {
while (++contact) {
Shot* c_shot = contact->GetShot();
if (c_shot && contact->Threat(ship)) {
// distance from self to target:
double distance = Point(c_shot->Location() - muzzle_pts[0]).length();
if (distance > design->min_range &&
distance < design->max_range &&
distance < dist) {
// check aim basket:
select_locked = CanLockPoint(c_shot->Location(), az, el);
if (select_locked) {
targ = c_shot;
dist = distance;
}
}
}
}
}
// lock onto a threatening ship only if it is (much) closer:
dist *= 0.2;
contact.reset();
while (++contact) {
Ship* c_ship = contact->GetShip();
if (!c_ship) continue;
// can we lock onto this target?
if ((c_ship->IsRogue() || c_ship->GetIFF() > 0 && c_ship->GetIFF() != ship->GetIFF()) &&
(c_ship->Class() & design->target_type) &&
c_ship->Weapons().size() > 0) {
// distance from self to target:
double distance = Point(c_ship->Location() - muzzle_pts[0]).length();
if (distance < design->max_range && distance < dist) {
// check aim basket:
select_locked = CanLockPoint(c_ship->Location(), az, el);
if (select_locked) {
targ = c_ship;
dist = distance;
}
}
}
}
}
if (!ammo || !enabled) {
SetTarget(0,0);
locked = false;
}
else {
SetTarget(targ, 0);
}
}
// +--------------------------------------------------------------------+
int
Weapon::Track(SimObject* targ, System* sub)
{
if (ammo && enabled && (availability > crit_level)) {
firing = 0;
Aim();
}
else if (turret) {
ZeroAim();
}
return locked;
}
// +--------------------------------------------------------------------+
Shot*
Weapon::Fire()
{
if (Game::Paused())
return 0;
if (ship && ship->CheckFire())
return 0;
if (ship->IsStarship() && target && !centered)
return 0;
if (beams && active_barrel >= 0 && active_barrel < nbarrels && beams[active_barrel])
return 0;
Shot* shot = 0;
if (ammo && enabled &&
(refire <= 0) && (energy > design->min_charge) &&
(availability > crit_level)) {
refire = design->refire_delay;
NetGame* net_game = NetGame::GetInstance();
bool net_client = net_game ? net_game->IsClient() : false;
// all barrels
if (active_barrel < 0) {
if (net_client || IsPrimary())
NetUtil::SendWepTrigger(this, nbarrels);
if (!net_game || IsPrimary()) {
for (int i = 0; i < nbarrels; i++)
shot = FireBarrel(i);
}
else if (net_game && net_game->IsServer() && IsMissile()) {
for (int i = 0; i < nbarrels; i++) {
shot = FireBarrel(i);
NetUtil::SendWepRelease(this, shot);
}
}
}
// single barrel
else {
if (net_client || IsPrimary())
NetUtil::SendWepTrigger(this, nbarrels);
if (!net_game || IsPrimary()) {
shot = FireBarrel(active_barrel++);
}
else if (net_game && net_game->IsServer() && IsMissile()) {
shot = FireBarrel(active_barrel++);
NetUtil::SendWepRelease(this, shot);
}
if (active_barrel >= nbarrels) {
active_barrel = 0;
refire += design->salvo_delay;
}
}
if (design->ripple_count > 0 && ripple_count <= 0)
ripple_count = design->ripple_count-1;
if (status != NOMINAL)
refire *= 2;
}
return shot;
}
// +--------------------------------------------------------------------+
Shot*
Weapon::NetFirePrimary(SimObject* tgt, System* sub, int count)
{
Shot* shot = 0;
if (!IsPrimary() || Game::Paused())
return shot;
if (active_barrel < 0 || active_barrel >= nbarrels)
active_barrel = 0;
target = tgt;
subtarget = sub;
aim_time = 0;
for (int i = 0; i < count; i++) {
shot = FireBarrel(active_barrel++);
if (active_barrel >= nbarrels) {
active_barrel = 0;
refire += design->salvo_delay;
}
}
if (target)
Observe(target);
return shot;
}
Shot*
Weapon::NetFireSecondary(SimObject* tgt, System* sub, DWORD objid)
{
Shot* shot = 0;
if (IsPrimary() || Game::Paused())
return shot;
if (active_barrel < 0 || active_barrel >= nbarrels)
active_barrel = 0;
target = tgt;
subtarget = sub;
aim_time = 0;
shot = FireBarrel(active_barrel++);
if (active_barrel >= nbarrels) {
active_barrel = 0;
refire += design->salvo_delay;
}
if (shot)
shot->SetObjID(objid);
if (target)
Observe(target);
return shot;
}
// +--------------------------------------------------------------------+
Shot*
Weapon::FireBarrel(int n)
{
const Point& base_vel = ship->Velocity();
Shot* shot = 0;
SimRegion* region = ship->GetRegion();
if (!region || n < 0 || n >= nbarrels || Game::Paused())
return 0;
firing = 1;
Aim();
Camera rail_cam;
rail_cam.Clone(aim_cam);
Point shotpos = muzzle_pts[n];
if (design->length > 0)
shotpos = shotpos + aim_cam.vpn() * design->length;
// guns may be slewed towards target:
if (design->primary) {
shot = CreateShot(shotpos, aim_cam, design, ship);
if (shot) {
shot->SetVelocity(shot->Velocity() + base_vel);
}
}
// missiles always launch in rail direction:
else {
// unless they are on a mobile launcher
if (turret && design->self_aiming) {
shot = CreateShot(shotpos, aim_cam, design, ship);
shot->SetVelocity(base_vel);
}
else {
shot = CreateShot(shotpos, rail_cam, design, ship);
if (shot /* && !turret */) {
Matrix orient = ship->Cam().Orientation();
if (aim_azimuth != 0) orient.Yaw(aim_azimuth);
if (aim_elevation != 0) orient.Pitch(aim_elevation);
Point eject = design->eject * orient;
shot->SetVelocity(base_vel + eject);
}
}
if (shot && visible_stores[n]) {
GRAPHIC_DESTROY(visible_stores[n]);
}
}
if (shot) {
if (ammo > 0)
ammo--;
if (guided && target)
shot->SeekTarget(target, subtarget);
float shot_load;
if (energy > design->charge)
shot_load = design->charge;
else
shot_load = energy;
energy -= shot_load;
shot->SetCharge(shot_load * availability);
if (target && design->flak && !design->guided) {
double speed = shot->Velocity().length();
double range = (target->Location() - shot->Location()).length();
if (range > design->min_range && range < design->max_range) {
shot->SetFuse(range / speed);
}
}
region->InsertObject(shot);
if (beams) {
beams[n] = shot;
Observe(beams[n]);
// aim beam at target:
SetBeamPoints(true);
}
if (ship) {
ShipStats* stats = ShipStats::Find(ship->Name());
if (design->primary)
stats->AddGunShot();
else if (design->decoy_type == 0 && design->damage > 0)
stats->AddMissileShot();
}
}
return shot;
}
Shot*
Weapon::CreateShot(const Point& loc, const Camera& cam, WeaponDesign* dsn, const Ship* own)
{
if (dsn->drone)
return new(__FILE__,__LINE__) Drone(loc, cam, dsn, own);
else
return new(__FILE__,__LINE__) Shot(loc, cam, dsn, own);
}
// +--------------------------------------------------------------------+
void
Weapon::Orient(const Physical* rep)
{
System::Orient(rep);
const Matrix& orientation = rep->Cam().Orientation();
Point loc = rep->Location();
// align graphics with camera:
if (turret) {
if (!design->self_aiming)
ZeroAim();
const Matrix& aim = aim_cam.Orientation();
turret->MoveTo(mount_loc);
turret->SetOrientation(aim);
if (turret_base) {
Matrix base = orientation;
if (design->turret_axis == 1) {
base.Pitch(aim_elevation);
base.Pitch(old_elevation);
}
else {
base.Yaw(aim_azimuth);
base.Yaw(old_azimuth);
}
turret_base->MoveTo(mount_loc);
turret_base->SetOrientation(base);
}
for (int i = 0; i < nbarrels; i++) {
muzzle_pts[i] = (rel_pts[i] * aim) + mount_loc;
if (visible_stores[i]) {
visible_stores[i]->SetOrientation(aim);
visible_stores[i]->MoveTo(muzzle_pts[i]);
}
}
}
else {
for (int i = 0; i < nbarrels; i++) {
muzzle_pts[i] = (rel_pts[i] * orientation) + loc;
if (visible_stores[i]) {
visible_stores[i]->SetOrientation(orientation);
visible_stores[i]->MoveTo(muzzle_pts[i]);
}
}
}
}
// +--------------------------------------------------------------------+
void
Weapon::SetBeamPoints(bool aim)
{
for (int i = 0; i < nbarrels; i++) {
if (beams && beams[i]) {
Point from = muzzle_pts[i];
Point to;
double len = design->length;
if (len < 1 || len > 1e7)
len = design->max_range;
if (len < 1)
len = 3e5;
else if (len > 1e7)
len = 1e7;
// always use the aim cam, to enforce slew_rate
to = from + aim_cam.vpn() * len;
beams[i]->SetBeamPoints(from, to);
}
}
}
// +--------------------------------------------------------------------+
void
Weapon::Aim()
{
locked = false;
centered = false;
FindObjective();
if (target) {
double az = 0;
double el = 0;
locked = CanLockPoint(obj_w, az, el, &objective);
double spread_az = design->spread_az;
double spread_el = design->spread_el;
// beam sweep target:
if (design->beam) {
double factor = 0;
double az_phase = 0;
double el_phase = 0;
if (target->Type() == SimObject::SIM_SHIP) {
Ship* s = (Ship*) target;
if (s->IsStarship()) {
switch (sweep) {
default:
case SWEEP_NONE: factor = 0; break;
case SWEEP_TIGHT: factor = 1; break;
case SWEEP_WIDE: factor = 2; break;
}
}
}
if (factor > 0) {
factor *= atan2(target->Radius(), (double) objective.z);
for (int i = 0; i < nbarrels; i++) {
if (beams && beams[i]) {
az_phase = sin(beams[i]->Life() * 0.4 * PI);
el_phase = sin(beams[i]->Life() * 1.0 * PI);
break;
}
}
az += factor * spread_az * az_phase;
el += factor * spread_el * el_phase * 0.25;
}
}
else if (!design->beam) {
if (spread_az > 0)
az += Random(-spread_az, spread_az);
if (spread_el > 0)
el += Random(-spread_el, spread_el);
}
AimTurret(az, -el);
// check range for guided weapons:
if (locked && guided) {
double range = objective.length();
if (range > design->max_track)
locked = false;
else if (range > design->max_range) {
if (firing) {
if (RandomChance(1,4)) // 1 in 4 chance of locking anyway
locked = false;
}
else {
locked = false;
}
}
}
if (locked) {
Point tloc = target->Location();
tloc = Transform(tloc);
if (tloc.z > 1) {
az = atan2(fabs(tloc.x), tloc.z);
el = atan2(fabs(tloc.y), tloc.z);
double firing_cone = 10*DEGREES;
if (orders == MANUAL)
firing_cone = 30*DEGREES;
if (az < firing_cone && el < firing_cone)
centered = true;
}
}
}
else {
AimTurret(aim_az_rest, -aim_el_rest);
}
}
void
Weapon::FindObjective()
{
ZeroAim();
if (!target || !design->self_aiming) {
objective = Point();
return;
}
obj_w = target->Location();
if (subtarget) {
obj_w = subtarget->MountLocation();
}
else if (target->Type() == SimObject::SIM_SHIP) {
Ship* tgt_ship = (Ship*) target;
if (tgt_ship->IsGroundUnit())
obj_w += Point(0,150,0);
}
if (!design->beam && shot_speed > 0) {
// distance from self to target:
double distance = Point(obj_w - muzzle_pts[0]).length();
// TRUE shot speed is relative to ship speed:
Point eff_shot_vel = ship->Velocity() + aim_cam.vpn() * shot_speed - target->Velocity();
double eff_shot_speed = eff_shot_vel.length();
// time to reach target:
double time = distance / eff_shot_speed;
// where the target will be when the shot reaches it:
obj_w += (target->Velocity() - ship->Velocity()) * time +
target->Acceleration() * 0.25 * time * time;
}
// transform into camera coords:
objective = Transform(obj_w);
}
Point
Weapon::Transform(const Point& pt)
{
Point result;
Point obj_t = pt - aim_cam.Pos();
result.x = obj_t * aim_cam.vrt();
result.y = obj_t * aim_cam.vup();
result.z = obj_t * aim_cam.vpn();
return result;
}
bool
Weapon::CanLockPoint(const Point& test, double& az, double& el, Point* obj)
{
Point pt = Transform(test);
bool locked = true;
// first compute az:
if (fabs(pt.z) < 0.1) pt.z = 0.1;
az = atan(pt.x / pt.z);
if (pt.z < 0) az -= PI;
if (az < -PI) az += 2*PI;
// then, rotate target into az-coords to compute el:
Camera tmp;
tmp.Clone(aim_cam);
aim_cam.Yaw(az);
pt = Transform(test);
aim_cam.Clone(tmp);
if (fabs(pt.z) < 0.1) pt.z = 0.1;
el = atan(pt.y / pt.z);
if (obj) *obj = pt;
// is the target in the basket?
// clamp if necessary:
if (az > aim_az_max) {
az = aim_az_max;
locked = false;
}
else if (az < aim_az_min) {
az = aim_az_min;
locked = false;
}
if (el > aim_el_max) {
el = aim_el_max;
locked = false;
}
else if (el < aim_el_min) {
el = aim_el_min;
locked = false;
}
if (IsDrone() && guided) {
double firing_cone = 10*DEGREES;
if (orders == MANUAL)
firing_cone = 20*DEGREES;
if (az < firing_cone && el < firing_cone)
locked = true;
}
return locked;
}
// +--------------------------------------------------------------------+
void
Weapon::AimTurret(double az, double el)
{
double seconds = (Game::GameTime() - aim_time) / 1000.0;
// don't let the weapon turn faster than turret slew rate:
double max_turn = design->slew_rate * seconds;
if (fabs(az-old_azimuth) > max_turn) {
if (az > old_azimuth)
az = old_azimuth + max_turn;
else
az = old_azimuth - max_turn;
}
if (fabs(el-old_elevation) > PI/2 * seconds) {
if (el > old_elevation)
el = old_elevation + max_turn;
else
el = old_elevation - max_turn;
}
aim_cam.Yaw(az);
aim_cam.Pitch(el);
old_azimuth = (float) az;
old_elevation = (float) el;
aim_time = Game::GameTime();
}
void
Weapon::ZeroAim()
{
aim_cam.Clone(ship->Cam());
if (aim_azimuth != 0) aim_cam.Yaw(aim_azimuth);
if (aim_elevation != 0) aim_cam.Pitch(aim_elevation);
aim_cam.MoveTo(muzzle_pts[0]);
}
| 24.803143 | 100 | 0.495281 | [
"object",
"transform",
"solid"
] |
68b4058b9b8fad42cb68c5942dc0bfd5f1b18fdf | 4,223 | cpp | C++ | src/math/Vector.test.cpp | j0ntan/RayTracerChallenge | 91e201b2d7f90032580101a1ccf18eb2d6e5b522 | [
"Unlicense"
] | null | null | null | src/math/Vector.test.cpp | j0ntan/RayTracerChallenge | 91e201b2d7f90032580101a1ccf18eb2d6e5b522 | [
"Unlicense"
] | null | null | null | src/math/Vector.test.cpp | j0ntan/RayTracerChallenge | 91e201b2d7f90032580101a1ccf18eb2d6e5b522 | [
"Unlicense"
] | null | null | null | #include <cmath>
#include <gtest/gtest.h>
#include <math/Vector.hpp>
TEST(Vector, defaultConstruct) { Vector v; }
TEST(Vector, componentsDefaultedToZero) {
Vector v;
ASSERT_FLOAT_EQ(v.x(), 0.0);
ASSERT_FLOAT_EQ(v.y(), 0.0);
ASSERT_FLOAT_EQ(v.z(), 0.0);
}
TEST(Vector, initialValueConstructed) {
Vector v(1.0, 2.0, 3.0);
ASSERT_FLOAT_EQ(v.x(), 1.0);
ASSERT_FLOAT_EQ(v.y(), 2.0);
ASSERT_FLOAT_EQ(v.z(), 3.0);
}
TEST(Vector, copyConstruct) {
Vector v1(1.0, 2.0, 3.0);
Vector v2(v1);
ASSERT_FLOAT_EQ(v1.x(), v2.x());
ASSERT_FLOAT_EQ(v1.y(), v2.y());
ASSERT_FLOAT_EQ(v1.z(), v2.z());
}
TEST(Vector, equalToSelf) {
Vector v;
ASSERT_TRUE(v == v);
}
TEST(Vector, equalToCopy) {
Vector v1, v2(v1);
ASSERT_TRUE(v1 == v2);
}
TEST(Vector, notEqualToDifferentVector) {
Vector v1, v2(1.0, 2.0, 3.0);
ASSERT_FALSE(v1 == v2);
}
TEST(Vector, equalToVeryNearVector) {
Vector v1, v2(0.0, 0.0, 0.000001);
ASSERT_TRUE(v1 == v2);
}
TEST(Vector, changeCoordinates) {
Vector v;
v.x() = 1.0;
v.y() = 2.0;
v.z() = 3.0;
}
TEST(Vector, assignFromVector) {
Vector v1, v2(1.0, 2.0, 3.0);
v1 = v2;
ASSERT_EQ(v1, v2);
}
TEST(Vector, addPointToVector) {
Point p = Vector(1.0, 2.0, 3.0) + Point(4.0, 5.0, 6.0);
ASSERT_EQ(p, Point(5.0, 7.0, 9.0));
}
TEST(Vector, addVectorToPoint) {
Point p = Point(4.0, 5.0, 6.0) + Vector(1.0, 2.0, 3.0);
ASSERT_EQ(p, Point(5.0, 7.0, 9.0));
}
TEST(Vector, addTwoVectors) {
Vector v = Vector(1.0, 2.0, 3.0) + Vector(4.0, 5.0, 6.0);
ASSERT_EQ(v, Vector(5.0, 7.0, 9.0));
}
TEST(Vector, subtractTwoPoints) {
Point p1(4.0, 5.0, 6.0), p2(1.0, 2.0, 3.0);
Vector v1 = p1 - p2;
Vector v2 = p2 - p1;
ASSERT_EQ(v1, Vector(3.0, 3.0, 3.0));
ASSERT_EQ(v2, Vector(-3.0, -3.0, -3.0));
}
TEST(Vector, subtractVectorFromPoint) {
Point p = Point(4.0, 5.0, 6.0) - Vector(1.0, 2.0, 3.0);
ASSERT_EQ(p, Point(3.0, 3.0, 3.0));
}
TEST(Vector, subtractTwoVectors) {
Vector v1(4.0, 5.0, 6.0), v2(1.0, 2.0, 3.0);
Vector v3 = v1 - v2;
Vector v4 = v2 - v1;
ASSERT_EQ(v3, Vector(3.0, 3.0, 3.0));
ASSERT_EQ(v4, Vector(-3.0, -3.0, -3.0));
}
TEST(Vector, negateVector) {
Vector v(0.0, 1.0, 2.0);
Vector negative_v = -v;
ASSERT_EQ(negative_v, Vector(0.0, -1.0, -2.0));
}
TEST(Vector, multiplyByScalar) {
Vector v1 = Vector(1.0, 2.0, 3.0) * 0.5;
Vector v2 = Vector(1.0, 2.0, 3.0) * -2.0;
ASSERT_EQ(v1, Vector(0.5, 1.0, 1.5));
ASSERT_EQ(v2, Vector(-2.0, -4.0, -6.0));
}
TEST(Vector, multiplyScalarByVector) {
Vector v1 = 0.5 * Vector(1.0, 2.0, 3.0);
Vector v2 = -2.0 * Vector(1.0, 2.0, 3.0);
ASSERT_EQ(v1, Vector(0.5, 1.0, 1.5));
ASSERT_EQ(v2, Vector(-2.0, -4.0, -6.0));
}
TEST(Vector, divideByScalar) {
Vector v = Vector(2.0, 4.0, 6.0) / 2.0;
ASSERT_EQ(v, Vector(1.0, 2.0, 3.0));
}
TEST(Vector, getMagnitude) {
ASSERT_FLOAT_EQ(Vector(1, 0, 0).magnitude(), 1.0);
ASSERT_FLOAT_EQ(Vector(0, 1, 0).magnitude(), 1.0);
ASSERT_FLOAT_EQ(Vector(0, 0, 1).magnitude(), 1.0);
ASSERT_FLOAT_EQ(Vector(1, 2, 3).magnitude(), std::sqrt(14));
ASSERT_FLOAT_EQ(Vector(-1, -2, -3).magnitude(), std::sqrt(14));
}
TEST(Vector, normalize) {
ASSERT_EQ(Vector(4, 0, 0).normalize(), Vector(1, 0, 0));
ASSERT_EQ(Vector(1, 2, 3).normalize(),
Vector(1 / std::sqrt(14), 2 / std::sqrt(14), 3 / std::sqrt(14)));
ASSERT_FLOAT_EQ(Vector(1, 2, 3).normalize().magnitude(), 1.0);
}
TEST(Vector, takeDotProduct) {
double result = dot(Vector(1, 2, 3), Vector(2, 3, 4));
ASSERT_FLOAT_EQ(result, 20.);
}
TEST(Vector, takeCrossProduct) {
Vector v1 = cross(Vector(1, 2, 3), Vector(2, 3, 4));
Vector v2 = cross(Vector(2, 3, 4), Vector(1, 2, 3));
ASSERT_EQ(v1, Vector(-1, 2, -1));
ASSERT_EQ(v2, Vector(1, -2, 1));
}
TEST(Reflection, reflectTwoVectors) {
reflect(Vector(1, 0, 0), Vector(0, 1, 0));
}
TEST(Reflection, produceVector) {
Vector reflected = reflect(Vector(1, 0, 0), Vector(0, 1, 0));
}
TEST(Reflection, vectorAt45Degrees) {
Vector v(1, -1, 0), n(0, 1, 0);
auto reflection = reflect(v, n);
ASSERT_EQ(reflection, Vector(1, 1, 0));
}
TEST(Reflection, slantedSurface) {
Vector v(0, -1, 0), n(sqrt(2) / 2, sqrt(2) / 2, 0);
auto reflection = reflect(v, n);
ASSERT_EQ(reflection, Vector(1, 0, 0));
}
| 24.988166 | 77 | 0.606915 | [
"vector"
] |
68bbcf5b3a20f66f9318cc80e094e81798cb07cc | 4,772 | hpp | C++ | deps/glider/ui/ListBox.hpp | Xecutor/zorroeditor | 69627f9a555ee739ea4fce0c9eb9f589b1e7f5f9 | [
"MIT"
] | null | null | null | deps/glider/ui/ListBox.hpp | Xecutor/zorroeditor | 69627f9a555ee739ea4fce0c9eb9f589b1e7f5f9 | [
"MIT"
] | null | null | null | deps/glider/ui/ListBox.hpp | Xecutor/zorroeditor | 69627f9a555ee739ea4fce0c9eb9f589b1e7f5f9 | [
"MIT"
] | null | null | null | #ifndef __GLIDER_UI_LISTBOX_HPP__
#define __GLIDER_UI_LISTBOX_HPP__
#include "UIContainer.hpp"
#include "ScrollBar.hpp"
#include <set>
namespace glider{
namespace ui{
enum ListBoxEventType{
lbetSelectionChanged,
lbetCount
};
class ListBox:public UIContainer{
public:
ListBox();
void draw();
UIObject* getSelection()
{
if(selItem!=objLst.end())
{
return selItem->get();
}else
{
return 0;
}
}
using UIObject::setEventHandler;
void setEventHandler(ListBoxEventType et,UICallBack cb)
{
eventHandlers[et]=cb;
}
UIObjectsList getMultiSelection()
{
UIObjectsList rv;
for(SelSet::iterator it=selSet.begin(),end=selSet.end();it!=end;++it)
{
rv.push_back(**it);
}
return rv;
}
void setSelection(int idx)
{
for(UIObjectsList::iterator it=objLst.begin(),end=objLst.end();it!=end;++it)
{
if(idx--==0)
{
setSelItem(it);
break;
}
}
}
void setBgColor(Color clr)
{
bgRect.setColor(clr);
}
void setSelColor(Color clr)
{
selRect.setColor(clr);
}
void setScrollPos(int idx);
void scrollToEnd();
protected:
UIObjectsList::iterator topItem;
UIObjectsList::iterator selItem;
struct IteratorComparator{
bool operator()(const UIObjectsList::iterator& a,const UIObjectsList::iterator& b)const
{
return a->get()<b->get();
}
};
typedef std::set<UIObjectsList::iterator,IteratorComparator> SelSet;
SelSet selSet;
ScrollBarRef sb;
Rectangle bgRect,selRect;
float totalHeight;
bool multiSel;
UICallBack eventHandlers[lbetCount];
void onAddObject();
void onRemoveObject(UIObjectsList::iterator it);
void onClear();
void onObjectResizeEnd();
void onKeyDown(const KeyboardEvent& key);
void onMouseButtonDown(const MouseEvent& me);
void setSelItem(UIObjectsList::iterator newSelItem)
{
if(newSelItem!=selItem)
{
selItem=newSelItem;
if(selItem!=objLst.end())
{
int h=(int)(calcHeight(objLst.begin(),selItem)-calcHeight(objLst.begin(),topItem));
if(h<0)
{
topItem=selItem;
}else
{
while(h>=size.y)
{
h-=(int)(*topItem)->getSize().y;
++topItem;
}
}
}
updateScroll();
if(eventHandlers[lbetSelectionChanged])
{
eventHandlers[lbetSelectionChanged](UIEvent(this,lbetSelectionChanged));
}
}
}
void onScroll(const UIEvent& evt);
float calcHeight(UIObjectsList::iterator from,UIObjectsList::iterator to);
void updateScroll();
};
typedef ReferenceTmpl<ListBox> ListBoxRef;
class MultiColumnListItem:public UIContainer{
public:
MultiColumnListItem(int argSpacing=4):spacing(argSpacing)
{
}
void setSpacing(int argSpacing)
{
spacing=argSpacing;
}
protected:
int spacing;
void onAssignParent()
{
updateSizes();
}
void onAddObject()
{
size.x+=objLst.back()->getSize().x;
if(objLst.back()->getSize().y>size.y)
{
size.y=objLst.back()->getSize().y;
}
}
void updateSizes()
{
std::vector<int> sizes;
ListBox* lb=dynamic_cast<ListBox*>(parent);
if(!lb)return;
ListEnumerator le(sizes);
lb->enumerate(&le);
int x=0;
for(size_t i=0;i<sizes.size();++i)
{
int w=sizes[i];
sizes[i]=x;
x+=w+spacing;
}
PosUpdater pu(sizes);
lb->enumerate(&pu);
}
struct ListEnumerator:UIContainerEnumerator{
std::vector<int>& sizes;
ListEnumerator(std::vector<int>& argSizes):sizes(argSizes)
{
}
bool nextItem(UIObject* obj)
{
MultiColumnListItem* mci=dynamic_cast<MultiColumnListItem*>(obj);
if(!mci)return true;
int idx=0;
for(UIObjectsList::iterator it=mci->objLst.begin(),end=mci->objLst.end();it!=end;++it,++idx)
{
if((int)sizes.size()<idx+1)
{
sizes.resize(idx+1);
}
if(sizes[idx]<(*it)->getSize().x)
{
sizes[idx]=(int)(*it)->getSize().x;
}
}
return true;
}
};
struct PosUpdater:UIContainerEnumerator{
std::vector<int>& positions;
PosUpdater(std::vector<int>& argPositions):positions(argPositions)
{
}
bool nextItem(UIObject* obj)
{
MultiColumnListItem* mci=dynamic_cast<MultiColumnListItem*>(obj);
if(!mci)return true;
if(mci->objLst.empty())return true;
int idx=0;
for(UIObjectsList::iterator it=mci->objLst.begin(),end=mci->objLst.end();it!=end;++it,++idx)
{
(*it)->setPos(Pos((float)positions[idx],(*it)->getPos().y));
}
mci->setSize(Pos(mci->objLst.back()->getPos().x+mci->objLst.back()->getSize().x,mci->getSize().y));
return true;
}
};
};
}
}
#endif
| 21.690909 | 105 | 0.61798 | [
"vector"
] |
68bd1409612e2d3d13e31a714fb914c5b0630213 | 18,234 | cpp | C++ | src/eepp/physics/cspace.cpp | dogtwelve/eepp | dd672ff0e108ae1e08449ca918dc144018fb4ba4 | [
"MIT"
] | null | null | null | src/eepp/physics/cspace.cpp | dogtwelve/eepp | dd672ff0e108ae1e08449ca918dc144018fb4ba4 | [
"MIT"
] | null | null | null | src/eepp/physics/cspace.cpp | dogtwelve/eepp | dd672ff0e108ae1e08449ca918dc144018fb4ba4 | [
"MIT"
] | null | null | null | #include <eepp/physics/cspace.hpp>
#include <eepp/physics/cphysicsmanager.hpp>
#ifdef PHYSICS_RENDERER_ENABLED
#include <eepp/window/cengine.hpp>
#include <eepp/graphics/cglobalbatchrenderer.hpp>
using namespace EE::Graphics;
#endif
CP_NAMESPACE_BEGIN
cSpace * cSpace::New() {
return cpNew( cSpace, () );
}
void cSpace::Free( cSpace * space ) {
cpSAFE_DELETE( space );
}
cSpace::cSpace() :
mData( NULL )
{
mSpace = cpSpaceNew();
mSpace->data = (void*)this;
mStaticBody = cpNew( cBody, ( mSpace->staticBody ) );
cPhysicsManager::instance()->RemoveBodyFree( mStaticBody );
cPhysicsManager::instance()->AddSpace( this );
}
cSpace::~cSpace() {
cpSpaceFree( mSpace );
std::list<cConstraint*>::iterator itc = mConstraints.begin();
for ( ; itc != mConstraints.end(); itc++ )
cpSAFE_DELETE( *itc );
std::list<cShape*>::iterator its = mShapes.begin();
for ( ; its != mShapes.end(); its++ )
cpSAFE_DELETE( *its );
std::list<cBody*>::iterator itb = mBodys.begin();
for ( ; itb != mBodys.end(); itb++ )
cpSAFE_DELETE( *itb );
mStaticBody->mBody = NULL; // The body has been released by cpSpaceFree( mSpace )
cpSAFE_DELETE( mStaticBody );
cPhysicsManager::instance()->RemoveSpace( this );
}
void cSpace::Data( void * data ) {
mData = data;
}
void * cSpace::Data() const {
return mData;
}
void cSpace::Step( const cpFloat& dt ) {
cpSpaceStep( mSpace, dt );
}
void cSpace::Update() {
#ifdef PHYSICS_RENDERER_ENABLED
Step( Window::cEngine::instance()->Elapsed().AsSeconds() );
#else
Step( 1 / 60 );
#endif
}
const int& cSpace::Iterations() const {
return mSpace->iterations;
}
void cSpace::Iterations( const int& iterations ) {
mSpace->iterations = iterations;
}
cVect cSpace::Gravity() const {
return tovect( mSpace->gravity );
}
void cSpace::Gravity( const cVect& gravity ) {
mSpace->gravity = tocpv( gravity );
}
const cpFloat& cSpace::Damping() const {
return mSpace->damping;
}
void cSpace::Damping( const cpFloat& damping ) {
mSpace->damping = damping;
}
const cpFloat& cSpace::IdleSpeedThreshold() const {
return mSpace->idleSpeedThreshold;
}
void cSpace::IdleSpeedThreshold( const cpFloat& idleSpeedThreshold ) {
mSpace->idleSpeedThreshold = idleSpeedThreshold;
}
const cpFloat& cSpace::SleepTimeThreshold() const {
return mSpace->sleepTimeThreshold;
}
void cSpace::SleepTimeThreshold( const cpFloat& sleepTimeThreshold ) {
mSpace->sleepTimeThreshold = sleepTimeThreshold;
}
void cSpace::CollisionSlop( cpFloat slop ) {
mSpace->collisionSlop = slop;
}
cpFloat cSpace::CollisionSlop() const {
return mSpace->collisionSlop;
}
void cSpace::CollisionBias( cpFloat bias ) {
mSpace->collisionBias = bias;
}
cpFloat cSpace::CollisionBias() const {
return mSpace->collisionBias;
}
cpTimestamp cSpace::CollisionPersistence() {
return cpSpaceGetCollisionPersistence( mSpace );
}
void cSpace::CollisionPersistence( cpTimestamp value ) {
cpSpaceSetCollisionPersistence( mSpace, value );
}
bool cSpace::EnableContactGraph() {
return cpTrue == cpSpaceGetEnableContactGraph( mSpace );
}
void cSpace::EnableContactGraph( bool value ) {
cpSpaceSetEnableContactGraph( mSpace, value );
}
cBody * cSpace::StaticBody() const {
return mStaticBody;
}
bool cSpace::Contains( cShape * shape ) {
return cpTrue == cpSpaceContainsShape( mSpace, shape->Shape() );
}
bool cSpace::Contains( cBody * body ) {
return cpTrue == cpSpaceContainsBody( mSpace, body->Body() );
}
bool cSpace::Contains( cConstraint * constraint ) {
return cpTrue == cpSpaceContainsConstraint( mSpace, constraint->Constraint() );
}
cShape * cSpace::AddShape( cShape * shape ) {
cpSpaceAddShape( mSpace, shape->Shape() );
mShapes.push_back( shape );
cPhysicsManager::instance()->RemoveShapeFree( shape );
return shape;
}
cShape * cSpace::AddStaticShape( cShape * shape ) {
cpSpaceAddStaticShape( mSpace, shape->Shape() );
mShapes.push_back( shape );
cPhysicsManager::instance()->RemoveShapeFree( shape );
return shape;
}
cBody * cSpace::AddBody( cBody * body ) {
cpSpaceAddBody( mSpace, body->Body() );
mBodys.push_back( body );
cPhysicsManager::instance()->RemoveBodyFree( body );
return body;
}
cConstraint * cSpace::AddConstraint( cConstraint * constraint ) {
cpSpaceAddConstraint( mSpace, constraint->Constraint() );
mConstraints.push_back( constraint );
cPhysicsManager::instance()->RemoveConstraintFree( constraint );
return constraint;
}
void cSpace::RemoveShape( cShape * shape ) {
if ( NULL != shape ) {
cpSpaceRemoveShape( mSpace, shape->Shape() );
mShapes.remove( shape );
cPhysicsManager::instance()->AddShapeFree( shape );
}
}
void cSpace::RemoveStaticShape( cShape * shape ) {
if ( NULL != shape ) {
cpSpaceRemoveStaticShape( mSpace, shape->Shape() );
mShapes.remove( shape );
cPhysicsManager::instance()->AddShapeFree( shape );
}
}
void cSpace::RemoveBody( cBody * body ) {
if ( NULL != body ) {
cpSpaceRemoveBody( mSpace, body->Body() );
mBodys.remove( body );
cPhysicsManager::instance()->RemoveBodyFree( body );
}
}
void cSpace::RemoveConstraint( cConstraint * constraint ) {
if ( NULL != constraint ) {
cpSpaceRemoveConstraint( mSpace, constraint->Constraint() );
mConstraints.remove( constraint );
cPhysicsManager::instance()->AddConstraintFree( constraint );
}
}
cShape * cSpace::PointQueryFirst( cVect point, cpLayers layers, cpGroup group ) {
cpShape * shape = cpSpacePointQueryFirst( mSpace, tocpv( point ), layers, group );
if ( NULL != shape ) {
return reinterpret_cast<cShape*> ( shape->data );
}
return NULL;
}
cShape * cSpace::SegmentQueryFirst( cVect start, cVect end, cpLayers layers, cpGroup group, cpSegmentQueryInfo * out ) {
cpShape * shape = cpSpaceSegmentQueryFirst( mSpace, tocpv( start ), tocpv( end ), layers, group, out );
if ( NULL != shape ) {
return reinterpret_cast<cShape*> ( shape->data );
}
return NULL;
}
cpSpace * cSpace::Space() const {
return mSpace;
}
void cSpace::ActivateShapesTouchingShape( cShape * shape ) {
cpSpaceActivateShapesTouchingShape( mSpace, shape->Shape() );
}
#ifdef PHYSICS_RENDERER_ENABLED
static void drawObject( cpShape * shape, cpSpace * space ) {
reinterpret_cast<cShape*> ( shape->data )->Draw( reinterpret_cast<cSpace*>( space->data ) );
}
static void drawObjectBorder( cpShape * shape, cpSpace * space ) {
reinterpret_cast<cShape*> ( shape->data )->DrawBorder( reinterpret_cast<cSpace*>( space->data ) );
}
static void drawBB( cpShape *shape, void * unused ) {
reinterpret_cast<cShape*> ( shape->data )->DrawBB();
}
static void drawConstraint( cpConstraint *constraint ) {
reinterpret_cast<cConstraint*> ( constraint->data )->Draw();
}
#endif
void cSpace::Draw() {
#ifdef PHYSICS_RENDERER_ENABLED
cBatchRenderer * BR = cGlobalBatchRenderer::instance();
BR->SetBlendMode( ALPHA_NORMAL );
cPhysicsManager::cDrawSpaceOptions * options = cPhysicsManager::instance()->GetDrawOptions();
cpFloat lw = BR->GetLineWidth();
cpFloat ps = BR->GetPointSize();
BR->SetLineWidth( options->LineThickness );
if ( options->DrawShapes ) {
cpSpatialIndexEach( mSpace->CP_PRIVATE(activeShapes), (cpSpatialIndexIteratorFunc)drawObject, mSpace );
cpSpatialIndexEach( mSpace->CP_PRIVATE(staticShapes), (cpSpatialIndexIteratorFunc)drawObject, mSpace );
}
if ( options->DrawShapesBorders ) {
cpSpatialIndexEach( mSpace->CP_PRIVATE(activeShapes), (cpSpatialIndexIteratorFunc)drawObjectBorder, mSpace );
cpSpatialIndexEach( mSpace->CP_PRIVATE(staticShapes), (cpSpatialIndexIteratorFunc)drawObjectBorder, mSpace );
}
BR->SetLineWidth( lw );
if ( options->DrawBBs ){
cpSpatialIndexEach( mSpace->CP_PRIVATE(activeShapes), (cpSpatialIndexIteratorFunc)drawBB, NULL );
cpSpatialIndexEach( mSpace->CP_PRIVATE(staticShapes), (cpSpatialIndexIteratorFunc)drawBB, NULL );
BR->Draw();
}
cpArray * constraints = mSpace->CP_PRIVATE(constraints);
for ( int i = 0, count = constraints->num; i < count; i++ ) {
drawConstraint( (cpConstraint *)constraints->arr[i] );
}
if ( options->BodyPointSize ) {
BR->SetPointSize( options->BodyPointSize );
BR->PointsBegin();
BR->PointSetColor( eeColorA( 255, 255, 255, 255 ) );
cpArray * bodies = mSpace->CP_PRIVATE(bodies);
for( int i=0, count = bodies->num; i<count; i++ ) {
cpBody * body = (cpBody *)bodies->arr[i];
BR->BatchPoint( body->p.x, body->p.y );
}
BR->Draw();
}
if ( options->CollisionPointSize ) {
BR->SetPointSize( options->CollisionPointSize );
BR->PointsBegin();
BR->PointSetColor( eeColorA( 255, 0, 0, 255 ) );
cpArray * arbiters = mSpace->CP_PRIVATE(arbiters);
for( int i = 0; i < arbiters->num; i++ ){
cpArbiter *arb = (cpArbiter*)arbiters->arr[i];
for( int i=0; i< arb->CP_PRIVATE(numContacts); i++ ){
cVect v = tovect( arb->CP_PRIVATE(contacts)[i].CP_PRIVATE(p) );
BR->BatchPoint( v.x, v.y );
}
}
BR->Draw();
}
BR->SetLineWidth( lw );
BR->SetPointSize( ps );
#endif
}
/** Collision Handling */
static cpBool RecieverCollisionBeginFunc( cpArbiter * arb, cpSpace * space, void * data ) {
cSpace * tspace = reinterpret_cast<cSpace*>( space->data );
cArbiter tarb( arb );
return tspace->OnCollisionBegin( &tarb, data );
}
static cpBool RecieverCollisionPreSolveFunc( cpArbiter * arb, cpSpace * space, void * data ) {
cSpace * tspace = reinterpret_cast<cSpace*>( space->data );
cArbiter tarb( arb );
return tspace->OnCollisionPreSolve( &tarb, data );
}
static void RecieverCollisionPostSolve( cpArbiter * arb, cpSpace * space, void * data ) {
cSpace * tspace = reinterpret_cast<cSpace*>( space->data );
cArbiter tarb( arb );
tspace->OnCollisionPostSolve( &tarb, data );
}
static void RecieverCollisionSeparateFunc( cpArbiter * arb, cpSpace * space, void * data ) {
cSpace * tspace = reinterpret_cast<cSpace*>( space->data );
cArbiter tarb( arb );
tspace->OnCollisionSeparate( &tarb, data );
}
static void RecieverPostStepCallback( cpSpace * space, void * obj, void * data ) {
cSpace * tspace = reinterpret_cast<cSpace*>( space->data );
tspace->OnPostStepCallback( obj, data );
}
static void RecieverBBQueryFunc( cpShape * shape, void * data ) {
cSpace::cBBQuery * query = reinterpret_cast<cSpace::cBBQuery*>( data );
query->Space->OnBBQuery( reinterpret_cast<cShape*>( shape->data ), query );
}
static void RecieverSegmentQueryFunc( cpShape *shape, cpFloat t, cpVect n, void * data ) {
cSpace::cSegmentQuery * query = reinterpret_cast<cSpace::cSegmentQuery*>( data );
query->Space->OnSegmentQuery( reinterpret_cast<cShape*>( shape->data ), t, tovect( n ), query );
}
static void RecieverPointQueryFunc( cpShape * shape, void * data ) {
cSpace::cPointQuery * query = reinterpret_cast<cSpace::cPointQuery*>( data );
query->Space->OnPointQuery( reinterpret_cast<cShape*>( shape->data ), query );
}
cpBool cSpace::OnCollisionBegin( cArbiter * arb, void * data ) {
cpHashValue hash = (cpHashValue)data;
//if ( NULL != data ) {
std::map< cpHashValue, cCollisionHandler >::iterator it = mCollisions.find( hash );
cCollisionHandler handler = static_cast<cCollisionHandler>( it->second );
if ( it != mCollisions.end() && handler.begin.IsSet() ) {
return handler.begin( arb, this, handler.data );
}
//}
if ( mCollisionsDefault.begin.IsSet() ) {
return mCollisionsDefault.begin( arb, this, mCollisionsDefault.data );
}
return 1;
}
cpBool cSpace::OnCollisionPreSolve( cArbiter * arb, void * data ) {
cpHashValue hash = (cpHashValue)data;
//if ( NULL != data ) {
std::map< cpHashValue, cCollisionHandler >::iterator it = mCollisions.find( hash );
cCollisionHandler handler = static_cast<cCollisionHandler>( it->second );
if ( it != mCollisions.end() && handler.preSolve.IsSet() ) {
return handler.preSolve( arb, this, handler.data );
}
//}
if ( mCollisionsDefault.preSolve.IsSet() ) {
return mCollisionsDefault.preSolve( arb, this, mCollisionsDefault.data );
}
return 1;
}
void cSpace::OnCollisionPostSolve( cArbiter * arb, void * data ) {
cpHashValue hash = (cpHashValue)data;
//if ( NULL != data ) {
std::map< cpHashValue, cCollisionHandler >::iterator it = mCollisions.find( hash );
cCollisionHandler handler = static_cast<cCollisionHandler>( it->second );
if ( it != mCollisions.end() && handler.postSolve.IsSet() ) {
handler.postSolve( arb, this, handler.data );
return;
}
//}
if ( mCollisionsDefault.begin.IsSet() ) {
mCollisionsDefault.postSolve( arb, this, mCollisionsDefault.data );
}
}
void cSpace::OnCollisionSeparate( cArbiter * arb, void * data ) {
cpHashValue hash = (cpHashValue)data;
//if ( NULL != data ) {
std::map< cpHashValue, cCollisionHandler >::iterator it = mCollisions.find( hash );
cCollisionHandler handler = static_cast<cCollisionHandler>( it->second );
if ( it != mCollisions.end() && handler.separate.IsSet() ) {
handler.separate( arb, this, handler.data );
return;
}
//}
if ( mCollisionsDefault.begin.IsSet() ) {
mCollisionsDefault.separate( arb, this, mCollisionsDefault.data );
}
}
void cSpace::OnPostStepCallback( void * obj, void * data ) {
cPostStepCallback * Cb = reinterpret_cast<cPostStepCallback *> ( data );
if ( Cb->Callback.IsSet() ) {
Cb->Callback( this, obj, Cb->Data );
}
mPostStepCallbacks.remove( Cb );
cpSAFE_DELETE( Cb );
}
void cSpace::OnBBQuery( cShape * shape, cBBQuery * query ) {
if ( query->Func.IsSet() ) {
query->Func( shape, query->Data );
}
}
void cSpace::OnSegmentQuery( cShape * shape, cpFloat t, cVect n , cSegmentQuery * query ) {
if ( query->Func.IsSet() ) {
query->Func( shape, t, n, query->Data );
}
}
void cSpace::OnPointQuery( cShape * shape, cPointQuery * query ) {
if ( query->Func.IsSet() ) {
query->Func( shape, query->Data );
}
}
void cSpace::AddCollisionHandler( const cCollisionHandler& handler ) {
cpHashValue hash = CP_HASH_PAIR( handler.a, handler.b );
cpCollisionBeginFunc f1 = ( handler.begin.IsSet() ) ? &RecieverCollisionBeginFunc : NULL;
cpCollisionPreSolveFunc f2 = ( handler.preSolve.IsSet() ) ? &RecieverCollisionPreSolveFunc : NULL;
cpCollisionPostSolveFunc f3 = ( handler.postSolve.IsSet() ) ? &RecieverCollisionPostSolve : NULL;
cpCollisionSeparateFunc f4 = ( handler.separate.IsSet() ) ? &RecieverCollisionSeparateFunc : NULL;
cpSpaceAddCollisionHandler( mSpace, handler.a, handler.b, f1, f2, f3, f4, (void*)hash );
mCollisions.erase( hash );
mCollisions[ hash ] = handler;
}
void cSpace::RemoveCollisionHandler( cpCollisionType a, cpCollisionType b ) {
cpSpaceRemoveCollisionHandler( mSpace, a, b );
mCollisions.erase( CP_HASH_PAIR( a, b ) );
}
void cSpace::SetDefaultCollisionHandler( const cCollisionHandler& handler ) {
cpCollisionBeginFunc f1 = ( handler.begin.IsSet() ) ? &RecieverCollisionBeginFunc : NULL;
cpCollisionPreSolveFunc f2 = ( handler.preSolve.IsSet() ) ? &RecieverCollisionPreSolveFunc : NULL;
cpCollisionPostSolveFunc f3 = ( handler.postSolve.IsSet() ) ? &RecieverCollisionPostSolve : NULL;
cpCollisionSeparateFunc f4 = ( handler.separate.IsSet() ) ? &RecieverCollisionSeparateFunc : NULL;
cpSpaceSetDefaultCollisionHandler( mSpace, f1, f2, f3, f4, NULL );
mCollisionsDefault = handler;
}
void cSpace::AddPostStepCallback( PostStepCallback postStep, void * obj, void * data ) {
cPostStepCallback * PostStepCb = cpNew( cPostStepCallback, () );
PostStepCb->Callback = postStep,
PostStepCb->Data = data;
cpSpaceAddPostStepCallback( mSpace, &RecieverPostStepCallback, obj, PostStepCb );
mPostStepCallbacks.push_back( PostStepCb );
}
void cSpace::BBQuery( cBB bb, cpLayers layers, cpGroup group, BBQueryFunc func, void * data ) {
cBBQuery tBBQuery;
tBBQuery.Space = this;
tBBQuery.Data = data;
tBBQuery.Func = func;
cpSpaceBBQuery( mSpace, tocpbb( bb ), layers, group, &RecieverBBQueryFunc, reinterpret_cast<void*>( &tBBQuery ) );
}
void cSpace::SegmentQuery( cVect start, cVect end, cpLayers layers, cpGroup group, SegmentQueryFunc func, void * data ) {
cSegmentQuery tSegmentQuery;
tSegmentQuery.Space = this;
tSegmentQuery.Data = data;
tSegmentQuery.Func = func;
cpSpaceSegmentQuery( mSpace, tocpv( start ), tocpv( end ), layers, group, &RecieverSegmentQueryFunc, reinterpret_cast<void*>( &tSegmentQuery ) );
}
void cSpace::PointQuery( cVect point, cpLayers layers, cpGroup group, PointQueryFunc func, void * data ) {
cPointQuery tPointQuery;
tPointQuery.Space = this;
tPointQuery.Data = data;
tPointQuery.Func = func;
cpSpacePointQuery( mSpace, tocpv( point ), layers, group, &RecieverPointQueryFunc, reinterpret_cast<void*>( &tPointQuery ) );
}
void cSpace::ReindexShape( cShape * shape ) {
cpSpaceReindexShape( mSpace, shape->Shape() );
}
void cSpace::ReindexShapesForBody( cBody *body ) {
cpSpaceReindexShapesForBody( mSpace, body->Body() );
}
void cSpace::ReindexStatic() {
cpSpaceReindexStatic( mSpace );
}
void cSpace::UseSpatialHash( cpFloat dim, int count ) {
cpSpaceUseSpatialHash( mSpace, dim, count );
}
static void SpaceBodyIteratorFunc( cpBody * body, void *data ) {
cSpace::cBodyIterator * it = reinterpret_cast<cSpace::cBodyIterator *> ( data );
it->Space->OnEachBody( reinterpret_cast<cBody*>( body->data ), it );
}
void cSpace::EachBody( BodyIteratorFunc Func, void * data ) {
cBodyIterator it( this, data, Func );
cpSpaceEachBody( mSpace, &SpaceBodyIteratorFunc, (void*)&it );
}
void cSpace::OnEachBody( cBody * Body, cBodyIterator * it ) {
if ( it->Func.IsSet() ) {
it->Func( it->Space, Body, it->Data );
}
}
static void SpaceShapeIteratorFunc ( cpShape * shape, void * data ) {
cSpace::cShapeIterator * it = reinterpret_cast<cSpace::cShapeIterator *> ( data );
it->Space->OnEachShape( reinterpret_cast<cShape*>( shape->data ), it );
}
void cSpace::EachShape( ShapeIteratorFunc Func, void * data ) {
cShapeIterator it( this, data, Func );
cpSpaceEachShape( mSpace, &SpaceShapeIteratorFunc, (void*)&it );
}
void cSpace::OnEachShape( cShape * Shape, cShapeIterator * it ) {
if ( it->Func.IsSet() ) {
it->Func( it->Space, Shape, it->Data );
}
}
void cSpace::ConvertBodyToDynamic( cBody * body, cpFloat mass, cpFloat moment ) {
cpSpaceConvertBodyToDynamic( mSpace, body->Body(), mass, moment );
}
void cSpace::ConvertBodyToStatic(cBody * body ) {
cpSpaceConvertBodyToStatic( mSpace, body->Body() );
}
CP_NAMESPACE_END
| 28.18238 | 146 | 0.709992 | [
"shape"
] |
68bd6c71f18c594fba89124991e7e34316fbe7a7 | 4,597 | cpp | C++ | UFORun/Classes/OpponentUpdate.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 58 | 2015-01-05T04:40:48.000Z | 2021-12-17T06:01:28.000Z | UFORun/Classes/OpponentUpdate.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | null | null | null | UFORun/Classes/OpponentUpdate.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 46 | 2015-01-03T06:20:54.000Z | 2020-04-18T13:32:52.000Z | //
// Nextpeer Sample for Cocos2d-X
// http://www.nextpeer.com
//
// Created by Nextpeer development team.
// Copyright (c) 2014 Innobell, Ltd. All rights reserved.
//
#include "OpponentUpdate.h"
#include "ViewPort.h"
#include "Box2D.h"
OpponentUpdate::OpponentUpdate()
{
}
MultiplayerMessageType OpponentUpdate::getMessageType() {
return MULTIPLAYER_MESSAGE_TYPE_OPPONENT_UPDATE;
}
OpponentUpdate* OpponentUpdate::createWithP2PData(const TournamentP2PData& tournamentP2PData)
{
OpponentUpdate* message = new OpponentUpdate();
if (message->extractDataFromByteVector(tournamentP2PData.message)) {
message->extractHeaderFromData(tournamentP2PData);
message->autorelease();
return message;
}
return NULL;
}
OpponentUpdate* OpponentUpdate::createWithHero(const Hero* hero)
{
OpponentUpdate* message = new OpponentUpdate();
// For some reason Cocos2D doesn't define getPosition() as const, so we'll const_cast here
CCPoint screenPosition = const_cast<Hero*>(hero)->getPosition();
b2Vec2 worldPos = ViewPort::getInstance()->screenToWorldCoordinate(screenPosition);
message->_worldPositionX = worldPos.x;
message->_worldPositionY = worldPos.y;
message->_isHurt = hero->isHurt();
message->_isStuck = hero->isStuck();
b2Body *heroBody = hero->getB2Body();
b2Vec2 currentLinearVel = heroBody->GetLinearVelocity();
message->_linearVelocityX = currentLinearVel.x;
message->_linearVelocityY = currentLinearVel.y;
OpponentState opponentState = kOpponentUnknown;
// Convert the Hero state to opponent state
switch (hero->getHeroState()) {
case kHeroReady:
opponentState = kOpponentReady;
break;
case kHeroStopped:
opponentState = kOpponentStopped;
break;
case kHeroPassedFinishLine:
opponentState = kOpponentRunning;
break;
case kHeroRunning:
// The hero can jump while runnning. For the hero that's actually the same state, while for the opponent it has seperate state
if (hero->getIsJumping()) {
opponentState = kOpponentJumping;
}
else {
opponentState = kOpponentRunning;
}
break;
default:
break;
}
message->_state = opponentState;
OpponentPowerUpState opponentPowerUpState = kOpponentPowerUpStateNone;
// Convert the Hero power up state to opponent power up state
switch (hero->getHeroPowerUpState()) {
case kHeroPowerUpStateShield:
opponentPowerUpState = kOpponentPowerUpStateShield;
break;
case kHeroPowerUpStateSpeedBoost:
opponentPowerUpState = kOpponentPowerUpStateSpeedBoost;
break;
default:
break;
}
message->mPowerUpState = opponentPowerUpState;
message->autorelease();
return message;
}
bool OpponentUpdate::extractDataFromByteVector(const vector<unsigned char>& byteVector)
{
if (byteVector.size() < sizeof(OpponentUpdateMessageStruct)) {
// This can't be a valid message
return false;
}
OpponentUpdateMessageStruct* structPtr = (OpponentUpdateMessageStruct*)&byteVector[0];
this->_worldPositionX = structPtr->worldPositionX;
this->_worldPositionY = structPtr->worldPositionY;
this->_linearVelocityX = structPtr->linearVelocityX;
this->_linearVelocityY = structPtr->linearVelocityY;
this->_state = (OpponentState)structPtr->state;
this->mPowerUpState = (OpponentPowerUpState)structPtr->powerUpState;
this->_isHurt = structPtr->isHurt;
this->_isStuck = structPtr->isStuck;
return true;
}
vector<unsigned char>& OpponentUpdate::toByteVector()
{
OpponentUpdateMessageStruct messageStruct;
messageStruct.header = this->getHeaderForDispatch();
messageStruct.worldPositionX = this->_worldPositionX;
messageStruct.worldPositionY = this->_worldPositionY;
messageStruct.linearVelocityX = this->_linearVelocityX;
messageStruct.linearVelocityY = this->_linearVelocityY;
messageStruct.state = this->_state;
messageStruct.isHurt = this->_isHurt;
messageStruct.isStuck = this->_isStuck;
messageStruct.powerUpState = this->mPowerUpState;
static vector<unsigned char> byteVector = vector<unsigned char>(sizeof(messageStruct));
memcpy(&byteVector[0], &messageStruct, sizeof(messageStruct));
return byteVector;
} | 32.373239 | 138 | 0.682184 | [
"vector"
] |
68cea9c296fa9fc98798e3c120cfa5875adf1a98 | 382 | cpp | C++ | src/question461.cpp | lxb1226/leetcode_cpp | 554280de6be2a77e2fe41a5e77cdd0f884ac2e20 | [
"MIT"
] | null | null | null | src/question461.cpp | lxb1226/leetcode_cpp | 554280de6be2a77e2fe41a5e77cdd0f884ac2e20 | [
"MIT"
] | null | null | null | src/question461.cpp | lxb1226/leetcode_cpp | 554280de6be2a77e2fe41a5e77cdd0f884ac2e20 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int hammingDistance(int x, int y) {
int s = x ^ y, ret = 0;
while(s){
ret += s & 1;
s >>= 1;
}
return ret;
}
};
int main(){
int x = 1, y = 4;
Solution su;
auto ans = su.hammingDistance(x, y);
cout << ans << endl;
} | 15.916667 | 40 | 0.479058 | [
"vector"
] |
68d1140fd5d2b6ed4b04ef85b41dafdf79b8acaa | 8,862 | cpp | C++ | middleware/http/source/outbound/handle.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | null | null | null | middleware/http/source/outbound/handle.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | null | null | null | middleware/http/source/outbound/handle.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | 1 | 2022-02-21T18:30:25.000Z | 2022-02-21T18:30:25.000Z | //!
//! Copyright (c) 2021, The casual project
//!
//! This software is licensed under the MIT license, https://opensource.org/licenses/MIT
//!
#include "http/outbound/handle.h"
#include "http/outbound/request.h"
#include "http/common.h"
#include "domain/message/discovery.h"
#include "common/communication/instance.h"
#include "common/message/handle.h"
namespace casual
{
using namespace common;
namespace http::outbound::handle
{
namespace internal
{
namespace local
{
namespace
{
namespace service::call
{
auto request( State& state)
{
return [&state]( message::service::call::callee::Request& message)
{
Trace trace{ "http::outbound::handle::local::service::call::request"};
log::line( verbose::log, "message: ", message);
auto send_error_reply = []( auto& message, auto code)
{
Trace trace{ "http::request::local::handle::service::call::Request::send_error_reply"};
log::line( log::category::verbose::error, code, " - message: ", message);
auto reply = message::reverse::type( message);
reply.code.result = code;
if( message.trid)
{
reply.transaction.trid = message.trid;
reply.transaction.state = decltype( reply.transaction.state)::rollback;
}
if( ! message.flags.exist( message::service::call::request::Flag::no_reply))
communication::device::blocking::optional::send( message.process.ipc, std::move( reply));
};
auto found = algorithm::find( state.lookup, message.service.name);
if( ! found)
{
log::line( log::category::error, code::xatmi::no_entry, " - http-outbound service not configured: ", message.service.name);
send_error_reply( message, code::xatmi::no_entry);
return;
}
const auto& node = found->second;
if( message.trid)
{
if( ! node.discard_transaction)
{
// we can't allow this forward to be in a transaction
log::line( log::category::error, code::xatmi::protocol, " - http-outbound can't be used in transaction for service: ", message.service.name);
log::line( log::category::verbose::error, code::xatmi::protocol, " - node: ", node);
send_error_reply( message, common::code::xatmi::protocol);
return;
}
else
log::line( log, "transaction discarded for '", message.service.name, "'");
}
// prepare and add the curl call
state.pending.requests.add( request::prepare( node, std::move( message)));
};
}
} // service::call
namespace discovery
{
//! reply with the intersection of requested and what we got...
auto request( const State& state)
{
return [&state]( casual::domain::message::discovery::Request& message)
{
Trace trace{ "http::outbound::handle::local::discovery::request"};
log::line( verbose::log, "message: ", message);
auto reply = common::message::reverse::type( message, process::handle());
reply.domain = state.identity;
reply.content.services = algorithm::accumulate( message.content.services, decltype( reply.content.services){}, [&state]( auto result, auto& name)
{
if( algorithm::find( state.lookup, name))
{
auto& service = result.emplace_back( name, "http", common::service::transaction::Type::none);
service.property.hops = 1;
service.property.type = decltype( service.property.type)::configured;
}
return result;
});
communication::device::blocking::optional::send( message.process.ipc, reply);
};
}
namespace advertised
{
//! reply with what we got...
auto request( const State& state)
{
return [&state]( const casual::domain::message::discovery::external::advertised::Request& message)
{
Trace trace{ "http::outbound::handle::local::discovery::advertised::request"};
log::line( verbose::log, "message: ", message);
auto reply = common::message::reverse::type( message, process::handle());
reply.content.services = algorithm::transform( state.lookup, predicate::adapter::first());
communication::device::blocking::optional::send( message.process.ipc, reply);
};
}
} // advertised
} // discovery
} // <unnamed>
} // local
handler_type create( State& state)
{
Trace trace{ "http::outbound::handle::handle"};
auto& device = communication::ipc::inbound::device();
return message::dispatch::handler( device,
message::handle::defaults( device),
local::service::call::request( state),
local::discovery::request( state),
local::discovery::advertised::request( state));
}
} // internal
namespace external
{
common::function< void( state::pending::Request&&, curl::type::code::easy)> reply( State& state)
{
return [&state]( state::pending::Request&& request, curl::type::code::easy curl_code)
{
Trace trace{ "http::outbound::manager::local::handle::Reply"};
log::line( verbose::log, "request: ", request);
log::line( verbose::log, "curl_code: ", curl_code);
message::service::call::Reply message;
message.correlation = request.state().correlation;
message.execution = request.state().execution;
message.code = request::transform::code( request, curl_code);
message.transaction = request::transform::transaction( request, message.code);
// take care of metrics
state.metric.add( request, message.code);
auto destination = request.state().destination;
// we're done with the request.
// there is only a payload if the call was 'successful'...
if( algorithm::compare::any( message.code.result, code::xatmi::ok, code::xatmi::service_fail))
{
try
{
message.buffer = request::receive::transcode::payload( std::move( request));
}
catch( ...)
{
auto error = exception::capture();
log::line( log::category::verbose::error, common::code::xatmi::protocol, " failed to transcode payload - reason: ", error);
message.code.result = common::code::xatmi::protocol;
}
}
log::line( verbose::log, "message: ", message);
communication::device::blocking::optional::send( destination.ipc, message);
// do we send metrics to service-manager?
if( state.pending.requests.empty() || state.metric)
{
communication::device::blocking::send( communication::instance::outbound::service::manager::device(), state.metric.message());
state.metric.clear();
}
};
}
} // external
} // http::outbound::handle
} // casual | 43.229268 | 172 | 0.474385 | [
"transform"
] |
68e9a482c24fabec4caff6f853fd53fcbac56edd | 1,061 | cpp | C++ | Codeforces/Contest 1629/C.cpp | Sansiff/Coding-Practice | b76f5a403c478abedc7bf22acb314b6cebb538ea | [
"MIT"
] | 1 | 2021-09-14T11:25:21.000Z | 2021-09-14T11:25:21.000Z | Codeforces/Contest 1629/C.cpp | Sansiff/Coding-Practice | b76f5a403c478abedc7bf22acb314b6cebb538ea | [
"MIT"
] | null | null | null | Codeforces/Contest 1629/C.cpp | Sansiff/Coding-Practice | b76f5a403c478abedc7bf22acb314b6cebb538ea | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define int long long
#define lowbit(x) (x&-x)
#define rep(i, l, r) for(int i = l; i < r; i ++)
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef vector<int> VI;
typedef vector<vector<int>> VII;
typedef vector<PII> VPII;
constexpr int N = 1e6 + 10;
int sum[N], f[N], res[N];
void solve() {
int n; cin >> n;
vector<int> a(n);
rep(i, 0, n + 1) sum[i] = f[i] = 0;
for(int &x: a) cin >> x, sum[x] ++;
int idx = 0;
int px = 0, prer = 0;
for(int i = 1; i <= n; i ++ ) {
f[a[i - 1]] ++;
while(f[px]) ++ px;
if(!sum[px]) {
res[++ idx] = px;
for(int j = prer + 1; j <= i; j ++ )
f[a[j - 1]] = 0, sum[a[j - 1]] --;
prer = i, px = 0;
}
}
cout << idx << endl;
rep(i, 1, idx + 1) cout << res[i] << ' ';
}
signed main() {
int _; cin >> _;
while(_ -- ) {
solve();
cout << '\n';
}
return 0;
}
| 23.577778 | 50 | 0.457116 | [
"vector"
] |
68f41a866de91e5361e78ab5346720fa46bdf765 | 1,216 | cpp | C++ | src/Stages/ProjectileMaker.cpp | lucashflores/jogo-tecprog | 21b114f21b933247a321e17905338a4f51620d2a | [
"MIT"
] | null | null | null | src/Stages/ProjectileMaker.cpp | lucashflores/jogo-tecprog | 21b114f21b933247a321e17905338a4f51620d2a | [
"MIT"
] | null | null | null | src/Stages/ProjectileMaker.cpp | lucashflores/jogo-tecprog | 21b114f21b933247a321e17905338a4f51620d2a | [
"MIT"
] | null | null | null | #include "Stages/ProjectileMaker.h"
using namespace Stages;
ProjectileMaker::ProjectileMaker() {
}
ProjectileMaker::ProjectileMaker(EntityList* pEL) {
if (pEL)
entityList = pEL;
}
ProjectileMaker::~ProjectileMaker() {
if (entityList)
entityList = NULL;
}
void ProjectileMaker::makeProjectile(Coordinates::Vector<float> pos, bool isFacingLeft) {
Entities::Projectile* projectile = NULL;
projectile = new Entities::Projectile(pos, isFacingLeft);
entityList->addEntity(static_cast<Entities::Entity*>(projectile));
projectile = NULL;
}
void ProjectileMaker::makeSmoke(Coordinates::Vector<float> pos) {
Entities::Smoke* smoke = NULL;
smoke = new Entities::Smoke(pos);
entityList->addEntity(static_cast<Entities::Entity*>(smoke));
smoke = NULL;
}
Entities::Projectile* ProjectileMaker::loadProjectile(Coordinates::Vector<float> pos, bool isFacingLeft) {
Entities::Projectile* projectile = NULL;
projectile = new Entities::Projectile(pos, isFacingLeft);
return projectile;
}
Entities::Smoke *ProjectileMaker::loadSmoke(Coordinates::Vector<float> pos) {
Entities::Smoke* smoke = NULL;
smoke = new Entities::Smoke(pos);
return smoke;
}
| 27.636364 | 106 | 0.71875 | [
"vector"
] |
190495b7aabf468a3a410bb7016f1ceec1f1d2b8 | 5,724 | cc | C++ | omaha/goopdate/app_command_model.cc | r3yn0ld4/omaha | 05eeb606c433b7d0622dc95a10afd0c8d7af11b6 | [
"Apache-2.0"
] | 1,975 | 2015-07-03T07:00:50.000Z | 2022-03-31T20:04:04.000Z | omaha/goopdate/app_command_model.cc | rodriguez74745/omaha | a244aea380b48fc488a0555c3fa51a2e03677557 | [
"Apache-2.0"
] | 277 | 2015-07-18T00:13:30.000Z | 2022-03-31T22:18:39.000Z | omaha/goopdate/app_command_model.cc | rodriguez74745/omaha | a244aea380b48fc488a0555c3fa51a2e03677557 | [
"Apache-2.0"
] | 685 | 2015-07-18T11:24:49.000Z | 2022-03-30T20:50:12.000Z | // Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
#include "omaha/goopdate/app_command_model.h"
#include <OleAuto.h>
#include "base/file.h"
#include "base/utils.h"
#include "omaha/base/constants.h"
#include "omaha/base/debug.h"
#include "omaha/base/error.h"
#include "omaha/base/system.h"
#include "omaha/base/utils.h"
#include "omaha/common/config_manager.h"
#include "omaha/common/const_cmd_line.h"
#include "omaha/common/const_goopdate.h"
#include "omaha/goopdate/app.h"
#include "omaha/goopdate/app_bundle.h"
#include "omaha/goopdate/app_command.h"
#include "omaha/goopdate/app_command_configuration.h"
#include "omaha/goopdate/google_app_command_verifier.h"
#include "omaha/goopdate/model.h"
#include "omaha/third_party/smartany/scoped_any.h"
namespace omaha {
AppCommandModel::AppCommandModel(App* app, AppCommand* app_command)
: ModelObject(app->model()),
app_command_(app_command) {
}
AppCommandModel::~AppCommandModel() {
ASSERT1(model()->IsLockedByCaller());
}
HRESULT AppCommandModel::Load(App* app,
const CString& cmd_id,
AppCommandModel** app_command_model) {
ASSERT1(app);
ASSERT1(app_command_model);
std::unique_ptr<AppCommandConfiguration> configuration;
HRESULT hr = AppCommandConfiguration::Load(GuidToString(app->app_guid()),
app->app_bundle()->is_machine(),
cmd_id,
&configuration);
if (FAILED(hr)) {
return hr;
}
*app_command_model = new AppCommandModel(
app, configuration->Instantiate(app->app_bundle()->session_id()));
return S_OK;
}
HRESULT AppCommandModel::Execute(AppCommandVerifier* verifier,
const std::vector<CString>& parameters,
HANDLE* process) {
__mutexScope(model()->lock());
return app_command_->Execute(verifier, parameters, process);
}
AppCommandStatus AppCommandModel::GetStatus() {
__mutexScope(model()->lock());
return app_command_->GetStatus();
}
DWORD AppCommandModel::GetExitCode() {
__mutexScope(model()->lock());
return app_command_->GetExitCode();
}
CString AppCommandModel::GetOutput() {
__mutexScope(model()->lock());
return app_command_->GetOutput();
}
bool AppCommandModel::is_web_accessible() const {
__mutexScope(model()->lock());
return app_command_->is_web_accessible();
}
STDMETHODIMP AppCommandWrapper::get_isWebAccessible(
VARIANT_BOOL* is_web_accessible) {
__mutexScope(model()->lock());
*is_web_accessible = wrapped_obj()->is_web_accessible();
return S_OK;
}
STDMETHODIMP AppCommandWrapper::get_status(UINT* status) {
__mutexScope(model()->lock());
*status = wrapped_obj()->GetStatus();
return S_OK;
}
STDMETHODIMP AppCommandWrapper::get_exitCode(DWORD* exit_code) {
__mutexScope(model()->lock());
*exit_code = wrapped_obj()->GetExitCode();
return S_OK;
}
STDMETHODIMP AppCommandWrapper::get_output(BSTR* output) {
__mutexScope(model()->lock());
*output = wrapped_obj()->GetOutput().AllocSysString();
return S_OK;
}
namespace {
// Extracts a BSTR from a VARIANT. Returns the inner BSTR if the VARIANT is
// VT_BSTR or VT_BSTR | VT_BYREF; returns NULL if the VARIANT does not contain
// a string.
BSTR BStrFromVariant(const VARIANT& source) {
if (V_VT(&source) == VT_BSTR) {
return V_BSTR(&source);
}
if (V_VT(&source) == (VT_BSTR | VT_BYREF)) {
return *(V_BSTRREF(&source));
}
return NULL;
}
} // namespace
STDMETHODIMP AppCommandWrapper::execute(VARIANT arg1,
VARIANT arg2,
VARIANT arg3,
VARIANT arg4,
VARIANT arg5,
VARIANT arg6,
VARIANT arg7,
VARIANT arg8,
VARIANT arg9) {
__mutexScope(model()->lock());
// Filled-in parameters should contain BSTR or BSTR-by-reference; unused
// parameters should be VT_ERROR with scode DISP_E_PARAMNOTFOUND, which will
// be converted to NULL. (In theory, a COM object could pass us anything in
// the Variants, but string types will be the only ones we will pass to the
// formatter.)
std::vector<CString> parameters_vector;
parameters_vector.push_back(BStrFromVariant(arg1));
parameters_vector.push_back(BStrFromVariant(arg2));
parameters_vector.push_back(BStrFromVariant(arg3));
parameters_vector.push_back(BStrFromVariant(arg4));
parameters_vector.push_back(BStrFromVariant(arg5));
parameters_vector.push_back(BStrFromVariant(arg6));
parameters_vector.push_back(BStrFromVariant(arg7));
parameters_vector.push_back(BStrFromVariant(arg8));
parameters_vector.push_back(BStrFromVariant(arg9));
GoogleAppCommandVerifier verifier;
scoped_process process;
return wrapped_obj()->Execute(
&verifier, parameters_vector, address(process));
}
} // namespace omaha
| 32.896552 | 78 | 0.662474 | [
"object",
"vector",
"model"
] |
1906f1d4b1b20cb2bbcb4d823dc5e5a453850f5d | 1,416 | cpp | C++ | src/Base/Dialog.cpp | roto5296/choreonoid | ffe12df8db71e32aea18833afb80dffc42c373d0 | [
"MIT"
] | 66 | 2020-03-11T14:06:01.000Z | 2022-03-23T23:18:27.000Z | src/Base/Dialog.cpp | roto5296/choreonoid | ffe12df8db71e32aea18833afb80dffc42c373d0 | [
"MIT"
] | 12 | 2020-07-23T06:13:11.000Z | 2022-01-13T14:25:01.000Z | src/Base/Dialog.cpp | roto5296/choreonoid | ffe12df8db71e32aea18833afb80dffc42c373d0 | [
"MIT"
] | 18 | 2020-07-17T15:57:54.000Z | 2022-03-29T13:18:59.000Z | /**
@author Shin'ichiro Nakaoka
*/
#include "Dialog.h"
#include "MainWindow.h"
using namespace cnoid;
/**
This constructor sets MainWindwo::instance() to the parent widget of this dialog
*/
Dialog::Dialog()
: QDialog(MainWindow::instance())
{
#if defined(__APPLE__) && defined(__MACH__)
// This is needed to show the dialog over the main window on OS X.
setWindowFlags(windowFlags() | Qt::Tool);
#endif
initialize();
}
Dialog::Dialog(QWidget* parent, Qt::WindowFlags f)
: QDialog(parent, f)
{
initialize();
}
void Dialog::initialize()
{
connect(this, (void(QDialog::*)()) &QDialog::accepted,
[this](){ onAccepted(); sigAccepted_(); });
connect(this, (void(QDialog::*)(int)) &QDialog::finished,
[this](int result){ sigFinished_(result); });
connect(this, (void(QDialog::*)()) &QDialog::rejected,
[this](){ onRejected(); sigRejected_(); });
isWindowPositionKeepingMode_ = false;
}
void Dialog::onAccepted()
{
}
void Dialog::onRejected()
{
}
void Dialog::setWindowPositionKeepingMode(bool on)
{
isWindowPositionKeepingMode_ = on;
}
void Dialog::show()
{
QDialog::show();
if(isWindowPositionKeepingMode_ && !lastWindowPosition_.isNull()){
setGeometry(lastWindowPosition_);
}
}
void Dialog::hideEvent(QHideEvent* event)
{
lastWindowPosition_ = geometry();
QDialog::hideEvent(event);
}
| 18.153846 | 83 | 0.652542 | [
"geometry"
] |
1912544dfdf25cdfceef423dae5c5a7bec84cd47 | 8,756 | cpp | C++ | BUS_QEV_Act.cpp | liudong206/qt_can_test | d0f50c300d689137da155d9aec059ea201dc3218 | [
"Apache-2.0"
] | null | null | null | BUS_QEV_Act.cpp | liudong206/qt_can_test | d0f50c300d689137da155d9aec059ea201dc3218 | [
"Apache-2.0"
] | null | null | null | BUS_QEV_Act.cpp | liudong206/qt_can_test | d0f50c300d689137da155d9aec059ea201dc3218 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include "BUS_QEV_Act.h"
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>
namespace vehicle
{
namespace qev
{
void vehicle_acticvity::VehicleParsingFunc(uint64_t InstanceId)
{
struct timeval ctime;
CAN_Data_Assignment(ECUTempDate);
#if 1
thread t(key_control_fun_,&ECUTempDate);
t.detach();
#endif
while(true)
{
int i = 0;
usleep(20000);
//usleep(200);
gettimeofday(&ctime, NULL);
vector<CanBusDataParam> VehSample;
VehSample.push_back(canDataParm);
if(0 == VehSample.size())
{
// VehicleProxy->CanDataRxEvent.Cleanup();
//continue;
}
for(auto Sample : VehSample)
{
VehicleData.seq = Sample.seq;
VehicleData.timeStamp.second = ctime.tv_sec;
VehicleData.timeStamp.nsecond = ctime.tv_usec;
for(auto Elem : Sample.elementList)
{
printf("Elem.canId %X\n",Elem.canId);
if(Veh_UP_MESSAGE_TAB.find(Elem.canId) == Veh_UP_MESSAGE_TAB.end())
{
continue;
}
printf("Elem.data %d %d %d %d %d %d %d %d\n",Elem.data[0],Elem.data[1],Elem.data[2],Elem.data[3],Elem.data[4],Elem.data[5],Elem.data[6],Elem.data[7]);
CAN_Data_Abstract_Func(Elem.data,&(VehicleData.VehInfo),Veh_UP_MESSAGE_TAB,INTELMODE,Elem.canId);
}
}
#if 1
CAN_Data_Package_Func(&ECUTempDate,canDataParm, vehicle::qev::Veh_DOWN_MESSAGE_TAB, INTELMODE, 1);
#endif
printf("!!!!!!!!!!!!!!!!!!VehicleData.VehInfo.DrivingModeFeedBack: %f\n",VehicleData.VehInfo.DrivingModeFeedBack);
printf("!!!!!!!!!!!!!!!!!!VehicleData.VehInfo.TargetAccelerated: %f\n",VehicleData.VehInfo.TargetAccelerated);
printf("!!!!!!!!!!!!!!!!!!VehicleData.VehInfo.TargetSteerAngle: %f\n",VehicleData.VehInfo.TargetSteerAngle);
}
}
void vehicle_acticvity::CAN_Data_Assignment(Veh_Sub_Info &ECUTempDate)
{
#if 1
int drivingstatus = 1;
/*临时关闭*/
if(1 == drivingstatus)
{
ECUTempDate.AutomaticDriveControlStatus = 0;
ECUTempDate.DrivingModeReg = 0x0;
ECUTempDate.DrivingModeFeedBack = 0x2;
ECUTempDate.TargetAccelerated = 0x0;
ECUTempDate.TargetSteerAngle = 0x0;
count ++;
if(count > 15) count = 0;
ECUTempDate.RollingCount_32E = count; //OX32E
std::cout << "################################ drivingstatus = 111111111111111########################################" << std::endl;
}
#endif
}
void vehicle_acticvity::CAN_Data_Package_Func(void* srcdata,CanBusDataParam &canDataParm, std::map<uint32_t,vector<table_info_t>> table, uint8_t mode, uint8_t seq)
{
uint8_t i,j = 0;
i = 0;
struct timeval ctime;
vector<uint8_t> Tempdata;
uint64_t tempdata = 0;
uint64_t tempdata_test = 0;
uint64_t Sum = 0;
uint64_t checksum = 0;
gettimeofday(&ctime, NULL);
canDataParm.seq = seq;
canDataParm.elementList.resize(table.size());
Tempdata.resize(8);
for(auto tab : table)
{
Sum = 0;
tempdata = 0;
//checksum = 0;//liudong
canDataParm.elementList[i].canId = tab.first;
canDataParm.elementList[i].validLen = 8;
canDataParm.elementList[i].timeStamp.second = ctime.tv_sec;
canDataParm.elementList[i].timeStamp.nsecond = ctime.tv_usec;
vector<table_info_t> stab;
stab = tab.second ;
if(stab.size() > 0)
{
for(int j = 0; j < stab.size(); j++)
{
::table_info_t t;
t.Bit_end.insloc = stab[j].Bit_end.insloc;
t.Bit_end.outloc = stab[j].Bit_end.outloc;
t.Bit_start.insloc = stab[j].Bit_start.insloc;
t.Bit_start.outloc = stab[j].Bit_start.outloc;
t.Length = stab[j].Length;
t.alpa = stab[j].alpa;
t.beta = stab[j].beta;
t.vloc = stab[j].vloc;
tempdata = static_cast<uint64_t>((*(UNIF_VAR_T *)(((uint64_t)(srcdata)) + t.vloc) - t.beta)/t.alpa);
//AutoDrivingMsg3CheckSum(tab.first,tempdata,t.Bit_start.insloc,checksum,j,stab);/*liudong*/
tempdata = DPACK(tempdata,t.Bit_start.outloc,t.Bit_start.insloc);
uint8_t tranf = LSHIFTBIT(t.Bit_start.outloc,t.Bit_start.insloc);
Sum += tempdata;
}
if(!mode)
{
INTELPACK(Tempdata,Sum);
}
if(mode)
{
MOTORPACK(Tempdata,Sum);
}
AutoDrivingMsg3CheckSum(Tempdata);
canDataParm.elementList[i].data = Tempdata;
printf("i: %d ,canDataParm->elementList[i].canId: %X \n", i, canDataParm.elementList[i].canId);
printf("i: %d ,canDataParm->elementList[i].data: %X %X %X %X %X %X %X %X\n", i, canDataParm.elementList[i].data[0], canDataParm.elementList[i].data[1], canDataParm.elementList[i].data[2],
canDataParm.elementList[i].data[3], canDataParm.elementList[i].data[4], canDataParm.elementList[i].data[5], canDataParm.elementList[i].data[6], canDataParm.elementList[i].data[7]);
}
i++;
}
}
void vehicle_acticvity::AutoDrivingMsg3CheckSum(vector<uint8_t> &data)/*liudong*/
{
uint32_t checksum = 0;
for (int i = 0; i < 7; i++){
checksum += data[i];
}
checksum = checksum ^ 0xff;
data[7] = checksum;
}
void vehicle_acticvity::CAN_Data_Abstract_Func(vector<uint8_t>& srcdata, void* dstdata, std::map<uint32_t,vector<table_info_t>> table, uint8_t mode, uint32_t CANId)
{
uint64_t CanVar = 0xFFFFFFFFFFFFFFFF;
uint64_t IntVar = 0xFFFFFFFFFFFFFFFF;
if((nullptr == dstdata)||(0 == srcdata.size())||(table.find(CANId) == table.end()))
{
return;
}
CanVar = (!mode) ? (INTELCAST(srcdata)) : (MOTORCAST(srcdata));
// printf("CanVar %lld\n",CanVar);
auto tab = table.find(CANId)->second;
for (auto t : tab)
{
IntVar = (CanVar & ((uint64_t)(DPICK(t.Bit_start.outloc, t.Bit_start.insloc, t.Bit_end.outloc, t.Bit_end.insloc)))) >> LSHIFTBIT(t.Bit_start.outloc, t.Bit_start.insloc);
*(UNIF_VAR_T *)(((uint64_t)(dstdata)) + t.vloc) = (t.alpa * ((UNIF_VAR_T)(IntVar))) + t.beta;
}
}
}
} // namespace vehicle
extern void *key_control_fun(void* args)
{
vehicle::qev::Veh_Sub_Info ecu_tempDate;
char c = '0';
std::cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<,,please enter key:"<<std::endl;
while (true) {
c = getchar();
if(c == 'w'){
ecu_tempDate.TargetAccelerated = ecu_tempDate.TargetAccelerated + 0.1;
}
else if(c == 's'){
ecu_tempDate.TargetAccelerated = ecu_tempDate.TargetAccelerated + 0.1;
}
else if(c == 'a') {
ecu_tempDate.TargetSteerAngle = ecu_tempDate.TargetSteerAngle + 10;
}
else if(c == 'd'){
ecu_tempDate.TargetSteerAngle = ecu_tempDate.TargetSteerAngle - 10;
}
else {
printf("key error");
}
usleep(20000);
}
}
extern int key_control_fun_(vehicle::qev::Veh_Sub_Info *ECUTempDate)
{
//byd::vehicle::qev::Veh_Sub_Info ecu_tempDate;
int c = 0;
std::cout<<"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<please enter key:"<<std::endl;
std::cout<<"ecu_tempDate.TargetAccelerated"<<ECUTempDate->TargetAccelerated<<std::endl;
std::cout<<"ecu_tempDate.TargetSteerAngle"<<ECUTempDate->TargetSteerAngle<<std::endl;
while(1)
{
std::cout<<"Before enter key"<<std::endl;
c = getch();
std::cout<<"After enter key"<<std::endl;
if(c == 119){
ECUTempDate->TargetAccelerated = ECUTempDate->TargetAccelerated + 0.1;//w
}
else if(c == 115){
ECUTempDate->TargetAccelerated = ECUTempDate->TargetAccelerated + 0.1;//s
}
else if(c == 97) {
ECUTempDate->TargetSteerAngle = ECUTempDate->TargetSteerAngle + 10;//a
std::cout<<"ecu_tempDate.TargetSteerAngle"<<ECUTempDate->TargetSteerAngle<<std::endl;
}
else if(c == 100){
ECUTempDate->TargetSteerAngle = ECUTempDate->TargetSteerAngle - 10;//d
}
else if(c == 13){
printf("key enter");
}
else {
printf("key error");
}
usleep(20000);
//break;
}
return 0;
}
extern int getch()
{
int c=0;
struct termios org_opts, new_opts;
int res=0;
//保留终端原来设置
res=tcgetattr(STDIN_FILENO, &org_opts);
assert(res==0);
//从新设置终端参数
memcpy(&new_opts, &org_opts, sizeof(new_opts));
new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
c=getchar();
//恢复中断设置
res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);assert(res==0);
return c;
}
| 34.203125 | 196 | 0.600274 | [
"vector"
] |
191bcab62be362c03658b9f31d724241aa9c6c7b | 1,781 | cxx | C++ | StRoot/StSpinPool/StTriggerFilterMaker/StTriggerFilterMaker.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StSpinPool/StTriggerFilterMaker/StTriggerFilterMaker.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StSpinPool/StTriggerFilterMaker/StTriggerFilterMaker.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | // $Id: StTriggerFilterMaker.cxx,v 1.2 2015/09/09 20:29:39 akio Exp $
#include "StTriggerFilterMaker.h"
#include "StMuDSTMaker/COMMON/StMuDst.h"
#include "StMuDSTMaker/COMMON/StMuEvent.h"
ClassImp(StTriggerFilterMaker)
StTriggerFilterMaker::StTriggerFilterMaker(const char *name) : StMaker(name), mPrint(0) { }
StTriggerFilterMaker::~StTriggerFilterMaker() {
mGoodTriggers.clear();
mVetoTriggers.clear();
}
Int_t StTriggerFilterMaker::Init() {
// this allows us to skip an event for other Makers
SetAttr(".Privilege",1);
return kStOk;
}
Int_t StTriggerFilterMaker::Make() {
if(mPrint){
vector<unsigned int> ids = StMuDst::event()->triggerIdCollection().nominal().triggerIds();
LOG_INFO << "Offline Trigger Id = ";
for(unsigned i=0; i<ids.size(); ++i) LOG_INFO << ids[i] << " ";
}
for(unsigned i=0; i<mVetoTriggers.size(); ++i) {
if(StMuDst::event()->triggerIdCollection().nominal().isTrigger(mVetoTriggers[i])) {
if(mPrint) LOG_INFO << " Veto" << endm;
return kStSkip;
}
}
for(unsigned i=0; i<mGoodTriggers.size(); ++i) {
if(StMuDst::event()->triggerIdCollection().nominal().isTrigger(mGoodTriggers[i])) {
if(mPrint) LOG_INFO << " Accept" << endm;
return kStOk;
}
}
if(mPrint) LOG_INFO << " Skip" << endm;
return kStSkip;
}
/*****************************************************************************
* $Log: StTriggerFilterMaker.cxx,v $
* Revision 1.2 2015/09/09 20:29:39 akio
* Adding Vetoing TriggerId
* Also adding printing if option is set
*
* Revision 1.1 2008/01/23 04:45:07 kocolosk
* Privileged Maker which skips events unless they fired any one of a set of supplied trigIDs
*
*****************************************************************************/
| 32.981481 | 94 | 0.614823 | [
"vector"
] |
192496a3bc61b443bf2786a4065d06ade2831e54 | 846 | cc | C++ | day05/main.cc | thorstel/Advent-of-Code-2020 | 8b183d904f94b0cdc93524ae8e7cf3dcf72da0f1 | [
"MIT"
] | 6 | 2020-12-03T14:56:06.000Z | 2021-11-28T11:48:44.000Z | day05/main.cc | thorstel/Advent-of-Code-2020 | 8b183d904f94b0cdc93524ae8e7cf3dcf72da0f1 | [
"MIT"
] | null | null | null | day05/main.cc | thorstel/Advent-of-Code-2020 | 8b183d904f94b0cdc93524ae8e7cf3dcf72da0f1 | [
"MIT"
] | 1 | 2020-12-05T21:27:56.000Z | 2020-12-05T21:27:56.000Z | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main()
{
string pass;
vector<ll> ids;
while (cin >> pass) {
ll r1 = 0, r2 = 127;
for (auto i = 0; i < 7; ++i) {
if (pass[i] == 'F') {
r2 -= ((r2 - r1 + 1) / 2);
} else {
assert(pass[i] == 'B');
r1 += ((r2 - r1 + 1) / 2);
}
}
assert(r1 == r2);
ll c1 = 0, c2 = 7;
for (auto i = 7; i < 10; ++i) {
if (pass[i] == 'L') {
c2 -= ((c2 - c1 + 1) / 2);
} else {
assert(pass[i] == 'R');
c1 += ((c2 - c1 + 1) / 2);
}
}
assert(c1 == c2);
ids.push_back((r1 * 8) + c1);
}
sort(ids.begin(), ids.end());
// Part 1
cout << *max_element(ids.begin(), ids.end()) << endl;
// Part 2
for (auto i = 0u; i < ids.size() - 1; ++i) {
if (ids[i] + 1 != ids[i+1]) {
cout << (ids[i] + 1) << endl;
break;
}
}
return 0;
}
| 18 | 54 | 0.432624 | [
"vector"
] |
1929bcf4862aa6cac2b48d68c5e1218cab84cecd | 32,667 | cpp | C++ | src/animation/animation_system.cpp | OndraVoves/LumixEngine | b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f | [
"MIT"
] | null | null | null | src/animation/animation_system.cpp | OndraVoves/LumixEngine | b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f | [
"MIT"
] | null | null | null | src/animation/animation_system.cpp | OndraVoves/LumixEngine | b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f | [
"MIT"
] | null | null | null | #include "animation_system.h"
#include "animation/animation.h"
#include "animation/controller.h"
#include "animation/events.h"
#include "engine/base_proxy_allocator.h"
#include "engine/blob.h"
#include "engine/crc32.h"
#include "engine/engine.h"
#include "engine/json_serializer.h"
#include "engine/lua_wrapper.h"
#include "engine/profiler.h"
#include "engine/property_descriptor.h"
#include "engine/property_register.h"
#include "engine/resource_manager.h"
#include "engine/serializer.h"
#include "engine/universe/universe.h"
#include "renderer/model.h"
#include "renderer/pose.h"
#include "renderer/render_scene.h"
#include <cfloat>
#include <cmath>
namespace Lumix
{
enum class AnimationSceneVersion
{
SHARED_CONTROLLER,
LATEST
};
static const ComponentType ANIMABLE_TYPE = PropertyRegister::getComponentType("animable");
static const ComponentType CONTROLLER_TYPE = PropertyRegister::getComponentType("anim_controller");
static const ComponentType SHARED_CONTROLLER_TYPE = PropertyRegister::getComponentType("shared_anim_controller");
static const ResourceType ANIMATION_TYPE("animation");
static const ResourceType CONTROLLER_RESOURCE_TYPE("anim_controller");
struct AnimSetPropertyDescriptor : public IEnumPropertyDescriptor
{
AnimSetPropertyDescriptor(const char* name)
{
setName(name);
m_type = ENUM;
}
void set(ComponentUID cmp, int index, InputBlob& stream) const override
{
int value;
stream.read(&value, sizeof(value));
(static_cast<AnimationScene*>(cmp.scene)->setControllerDefaultSet)(cmp.handle, value);
};
void get(ComponentUID cmp, int index, OutputBlob& stream) const override
{
int value;
ASSERT(index == -1);
value = (static_cast<AnimationScene*>(cmp.scene)->getControllerDefaultSet)(cmp.handle);
stream.write(&value, sizeof(value));
}
int getEnumCount(IScene* scene, ComponentHandle cmp) override
{
Anim::ControllerResource* res = static_cast<AnimationScene*>(scene)->getControllerResource(cmp);
return res->m_sets_names.size();
}
const char* getEnumItemName(IScene* scene, ComponentHandle cmp, int index) override
{
Anim::ControllerResource* res = static_cast<AnimationScene*>(scene)->getControllerResource(cmp);
return res->m_sets_names[index];
}
void getEnumItemName(IScene* scene, ComponentHandle cmp, int index, char* buf, int max_size) override
{
Anim::ControllerResource* res = static_cast<AnimationScene*>(scene)->getControllerResource(cmp);
copyString(buf, max_size, res->m_sets_names[index]);
}
};
namespace FS
{
class FileSystem;
};
class Animation;
class Engine;
class JsonSerializer;
class Universe;
struct AnimationSystemImpl LUMIX_FINAL : public IPlugin
{
explicit AnimationSystemImpl(Engine& engine);
~AnimationSystemImpl();
void registerLuaAPI();
void createScenes(Universe& ctx) override;
void destroyScene(IScene* scene) override;
const char* getName() const override { return "animation"; }
IAllocator& m_allocator;
Engine& m_engine;
AnimationManager m_animation_manager;
Anim::ControllerManager m_controller_manager;
private:
void operator=(const AnimationSystemImpl&);
AnimationSystemImpl(const AnimationSystemImpl&);
};
struct AnimationSceneImpl LUMIX_FINAL : public AnimationScene
{
friend struct AnimationSystemImpl;
struct SharedController
{
Entity entity;
Entity parent;
};
struct Controller
{
Controller(IAllocator& allocator) : input(allocator), animations(allocator) {}
Entity entity;
Anim::ControllerResource* resource = nullptr;
Anim::ComponentInstance* root = nullptr;
u32 default_set = 0;
Array<u8> input;
HashMap<u32, Animation*> animations;
struct IK
{
enum { MAX_BONES_COUNT = 8 };
float weight = 0;
i16 max_iterations = 5;
i16 bones_count = 4;
u32 bones[MAX_BONES_COUNT];
Vec3 target;
} inverse_kinematics[4];
};
struct Animable
{
float time;
float time_scale;
float start_time;
Animation* animation;
Entity entity;
};
AnimationSceneImpl(AnimationSystemImpl& anim_system, Engine& engine, Universe& universe, IAllocator& allocator)
: m_universe(universe)
, m_engine(engine)
, m_anim_system(anim_system)
, m_animables(allocator)
, m_controllers(allocator)
, m_shared_controllers(allocator)
, m_event_stream(allocator)
{
m_is_game_running = false;
m_render_scene = static_cast<RenderScene*>(universe.getScene(crc32("renderer")));
universe.registerComponentType(ANIMABLE_TYPE, this, &AnimationSceneImpl::serializeAnimable, &AnimationSceneImpl::deserializeAnimable);
universe.registerComponentType(CONTROLLER_TYPE, this, &AnimationSceneImpl::serializeController, &AnimationSceneImpl::deserializeController);
universe.registerComponentType(SHARED_CONTROLLER_TYPE, this, &AnimationSceneImpl::serializeSharedController, &AnimationSceneImpl::deserializeSharedController);
ASSERT(m_render_scene);
}
void serializeSharedController(ISerializer& serializer, ComponentHandle cmp)
{
SharedController& ctrl = m_shared_controllers[{cmp.index}];
serializer.write("parent", ctrl.parent);
}
void deserializeSharedController(IDeserializer& serializer, Entity entity, int /*scene_version*/)
{
Entity parent;
serializer.read(&parent);
m_shared_controllers.insert(entity, {entity, parent});
m_universe.addComponent(entity, SHARED_CONTROLLER_TYPE, this, {entity.index});
}
void serializeAnimable(ISerializer& serializer, ComponentHandle cmp)
{
Animable& animable = m_animables[{cmp.index}];
serializer.write("time_scale", animable.time_scale);
serializer.write("start_time", animable.start_time);
serializer.write("animation", animable.animation ? animable.animation->getPath().c_str() : "");
}
void deserializeAnimable(IDeserializer& serializer, Entity entity, int /*scene_version*/)
{
Animable& animable = m_animables.insert(entity);
animable.entity = entity;
serializer.read(&animable.time_scale);
serializer.read(&animable.start_time);
char tmp[MAX_PATH_LENGTH];
serializer.read(tmp, lengthOf(tmp));
auto* res = tmp[0] ? m_engine.getResourceManager().get(ANIMATION_TYPE)->load(Path(tmp)) : nullptr;
animable.animation = (Animation*)res;
m_universe.addComponent(entity, ANIMABLE_TYPE, this, {entity.index});
}
void serializeController(ISerializer& serializer, ComponentHandle cmp)
{
Controller& controller = m_controllers.get({cmp.index});
serializer.write("source", controller.resource ? controller.resource->getPath().c_str() : "");
serializer.write("default_set", controller.default_set);
}
int getVersion() const override { return (int)AnimationSceneVersion::LATEST; }
void deserializeController(IDeserializer& serializer, Entity entity, int scene_version)
{
Controller& controller = m_controllers.emplace(entity, m_anim_system.m_allocator);
controller.entity = entity;
char tmp[MAX_PATH_LENGTH];
serializer.read(tmp, lengthOf(tmp));
if (scene_version > (int)AnimationSceneVersion::SHARED_CONTROLLER)
{
serializer.read(&controller.default_set);
}
auto* res = tmp[0] ? m_engine.getResourceManager().get(CONTROLLER_RESOURCE_TYPE)->load(Path(tmp)) : nullptr;
controller.resource = (Anim::ControllerResource*)res;
m_universe.addComponent(entity, CONTROLLER_TYPE, this, {entity.index});
}
const OutputBlob& getEventStream() const override
{
return m_event_stream;
}
void clear() override
{
for (Animable& animable : m_animables)
{
unloadAnimation(animable.animation);
}
m_animables.clear();
for (Controller& controller : m_controllers)
{
unloadController(controller.resource);
LUMIX_DELETE(m_anim_system.m_allocator, controller.root);
}
m_controllers.clear();
}
static int setIK(lua_State* L)
{
AnimationSceneImpl* scene = LuaWrapper::checkArg<AnimationSceneImpl*>(L, 1);
ComponentHandle cmp = LuaWrapper::checkArg<ComponentHandle>(L, 2);
Controller& controller = scene->m_controllers.get({ cmp.index });
int index = LuaWrapper::checkArg<int>(L, 3);
Controller::IK& ik = controller.inverse_kinematics[index];
ik.weight = LuaWrapper::checkArg<float>(L, 4);
ik.target = LuaWrapper::checkArg<Vec3>(L, 5);
Transform tr = scene->m_universe.getTransform(controller.entity);
ik.target = tr.inverted().transform(ik.target);
ik.bones_count = lua_gettop(L) - 5;
if (ik.bones_count > lengthOf(ik.bones))
{
luaL_argerror(L, ik.bones_count, "Too many arguments");
}
for (int i = 0; i < ik.bones_count; ++i)
{
const char* bone = LuaWrapper::checkArg<const char*>(L, i + 6);
ik.bones[i] = crc32(bone);
}
return 0;
}
int getControllerInputIndex(ComponentHandle cmp, const char* name) const
{
const Controller& controller = m_controllers[{cmp.index}];
Anim::InputDecl& decl = controller.resource->m_input_decl;
for (int i = 0; i < lengthOf(decl.inputs); ++i)
{
if (decl.inputs[i].type != Anim::InputDecl::EMPTY && equalStrings(decl.inputs[i].name, name)) return i;
}
return -1;
}
void setControllerFloatInput(ComponentHandle cmp, int input_idx, float value)
{
Controller& controller = m_controllers.get({ cmp.index });
if (!controller.root)
{
g_log_warning.log("Animation") << "Trying to set input " << input_idx << " before the controller is ready";
return;
}
Anim::InputDecl& decl = controller.resource->m_input_decl;
if (input_idx < 0 || input_idx >= lengthOf(decl.inputs)) return;
if (decl.inputs[input_idx].type == Anim::InputDecl::FLOAT)
{
*(float*)&controller.input[decl.inputs[input_idx].offset] = value;
}
else
{
g_log_warning.log("Animation") << "Trying to set float to " << decl.inputs[input_idx].name;
}
}
void setControllerIntInput(ComponentHandle cmp, int input_idx, int value)
{
Controller& controller = m_controllers.get({ cmp.index });
if (!controller.root)
{
g_log_warning.log("Animation") << "Trying to set input " << input_idx << " before the controller is ready";
return;
}
Anim::InputDecl& decl = controller.resource->m_input_decl;
if (decl.inputs[input_idx].type == Anim::InputDecl::INT)
{
*(int*)&controller.input[decl.inputs[input_idx].offset] = value;
}
else
{
g_log_warning.log("Animation") << "Trying to set int to " << decl.inputs[input_idx].name;
}
}
void setControllerBoolInput(ComponentHandle cmp, int input_idx, bool value)
{
Controller& controller = m_controllers.get({ cmp.index });
if (!controller.root)
{
g_log_warning.log("Animation") << "Trying to set input " << input_idx << " before the controller is ready";
return;
}
Anim::InputDecl& decl = controller.resource->m_input_decl;
if (decl.inputs[input_idx].type == Anim::InputDecl::BOOL)
{
*(bool*)&controller.input[decl.inputs[input_idx].offset] = value;
}
else
{
g_log_warning.log("Animation") << "Trying to set bool to " << decl.inputs[input_idx].name;
}
}
float getAnimationLength(int animation_idx)
{
auto* animation = static_cast<Animation*>(animation_idx > 0 ? m_engine.getLuaResource(animation_idx) : nullptr);
if (animation) return animation->getLength();
return 0;
}
float getAnimableTime(ComponentHandle cmp) override
{
return m_animables[{cmp.index}].time;
}
void setAnimableTime(ComponentHandle cmp, float time) override
{
m_animables[{cmp.index}].time = time;
}
Animation* getAnimableAnimation(ComponentHandle cmp) override
{
return m_animables[{cmp.index}].animation;
}
void startGame() override
{
for (auto& controller : m_controllers)
{
initControllerRuntime(controller);
}
m_is_game_running = true;
}
void stopGame() override
{
for (auto& controller : m_controllers)
{
LUMIX_DELETE(m_anim_system.m_allocator, controller.root);
controller.root = nullptr;
}
m_is_game_running = false;
}
Universe& getUniverse() override { return m_universe; }
ComponentHandle getComponent(Entity entity, ComponentType type) override
{
if (type == ANIMABLE_TYPE)
{
if (m_animables.find(entity) < 0) return INVALID_COMPONENT;
return {entity.index};
}
else if (type == CONTROLLER_TYPE)
{
if (m_controllers.find(entity) < 0) return INVALID_COMPONENT;
return {entity.index};
}
else if (type == SHARED_CONTROLLER_TYPE)
{
if (m_shared_controllers.find(entity) < 0) return INVALID_COMPONENT;
return {entity.index};
}
return INVALID_COMPONENT;
}
ComponentHandle createComponent(ComponentType type, Entity entity) override
{
if (type == ANIMABLE_TYPE) return createAnimable(entity);
if (type == CONTROLLER_TYPE) return createController(entity);
if (type == SHARED_CONTROLLER_TYPE) return createSharedController(entity);
return INVALID_COMPONENT;
}
void unloadAnimation(Animation* animation)
{
if (!animation) return;
animation->getResourceManager().unload(*animation);
}
void unloadController(Anim::ControllerResource* res)
{
if (!res) return;
res->getResourceManager().unload(*res);
}
void destroyComponent(ComponentHandle component, ComponentType type) override
{
if (type == ANIMABLE_TYPE)
{
Entity entity = {component.index};
auto& animable = m_animables[entity];
unloadAnimation(animable.animation);
m_animables.erase(entity);
m_universe.destroyComponent(entity, type, this, component);
}
else if (type == CONTROLLER_TYPE)
{
Entity entity = {component.index};
auto& controller = m_controllers.get(entity);
unloadController(controller.resource);
LUMIX_DELETE(m_anim_system.m_allocator, controller.root);
m_controllers.erase(entity);
m_universe.destroyComponent(entity, type, this, component);
}
else if (type == SHARED_CONTROLLER_TYPE)
{
Entity entity = {component.index};
m_shared_controllers.erase(entity);
m_universe.destroyComponent(entity, type, this, component);
}
}
void serialize(OutputBlob& serializer) override
{
serializer.write((i32)m_animables.size());
for (const Animable& animable : m_animables)
{
serializer.write(animable.entity);
serializer.write(animable.time_scale);
serializer.write(animable.start_time);
serializer.writeString(animable.animation ? animable.animation->getPath().c_str() : "");
}
serializer.write(m_controllers.size());
for (const Controller& controller : m_controllers)
{
serializer.write(controller.default_set);
serializer.write(controller.entity);
serializer.writeString(controller.resource ? controller.resource->getPath().c_str() : "");
}
serializer.write(m_shared_controllers.size());
for (const SharedController& controller : m_shared_controllers)
{
serializer.write(controller.entity);
serializer.write(controller.parent);
}
}
void deserialize(InputBlob& serializer) override
{
i32 count;
serializer.read(count);
m_animables.reserve(count);
for (int i = 0; i < count; ++i)
{
Animable animable;
serializer.read(animable.entity);
serializer.read(animable.time_scale);
serializer.read(animable.start_time);
animable.time = animable.start_time;
char path[MAX_PATH_LENGTH];
serializer.readString(path, sizeof(path));
animable.animation = path[0] == '\0' ? nullptr : loadAnimation(Path(path));
m_animables.insert(animable.entity, animable);
ComponentHandle cmp = {animable.entity.index};
m_universe.addComponent(animable.entity, ANIMABLE_TYPE, this, cmp);
}
serializer.read(count);
m_controllers.reserve(count);
for (int i = 0; i < count; ++i)
{
Controller controller(m_anim_system.m_allocator);
serializer.read(controller.default_set);
serializer.read(controller.entity);
char tmp[MAX_PATH_LENGTH];
serializer.readString(tmp, lengthOf(tmp));
controller.resource = tmp[0] ? loadController(Path(tmp)) : nullptr;
m_controllers.insert(controller.entity, controller);
ComponentHandle cmp = { controller.entity.index };
m_universe.addComponent(controller.entity, CONTROLLER_TYPE, this, cmp);
}
serializer.read(count);
m_shared_controllers.reserve(count);
for (int i = 0; i < count; ++i)
{
SharedController controller;
serializer.read(controller.entity);
serializer.read(controller.parent);
m_shared_controllers.insert(controller.entity, controller);
ComponentHandle cmp = {controller.entity.index};
m_universe.addComponent(controller.entity, SHARED_CONTROLLER_TYPE, this, cmp);
}
}
void setSharedControllerParent(ComponentHandle cmp, Entity parent) override
{
m_shared_controllers[{cmp.index}].parent = parent;
}
Entity getSharedControllerParent(ComponentHandle cmp) override { return m_shared_controllers[{cmp.index}].parent; }
float getTimeScale(ComponentHandle cmp) { return m_animables[{cmp.index}].time_scale; }
void setTimeScale(ComponentHandle cmp, float time_scale) { m_animables[{cmp.index}].time_scale = time_scale; }
float getStartTime(ComponentHandle cmp) { return m_animables[{cmp.index}].start_time; }
void setStartTime(ComponentHandle cmp, float time) { m_animables[{cmp.index}].start_time = time; }
void setControllerSource(ComponentHandle cmp, const Path& path)
{
auto& controller = m_controllers.get({cmp.index});
unloadController(controller.resource);
controller.resource = loadController(path);
if (controller.resource->isReady() && m_is_game_running)
{
initControllerRuntime(controller);
}
}
Path getControllerSource(ComponentHandle cmp) override
{
const auto& controller = m_controllers.get({cmp.index});
return controller.resource ? controller.resource->getPath() : Path("");
}
Path getAnimation(ComponentHandle cmp)
{
const auto& animable = m_animables[{cmp.index}];
return animable.animation ? animable.animation->getPath() : Path("");
}
void setAnimation(ComponentHandle cmp, const Path& path)
{
auto& animable = m_animables[{cmp.index}];
unloadAnimation(animable.animation);
animable.animation = loadAnimation(path);
animable.time = 0;
}
void updateAnimable(Animable& animable, float time_delta)
{
if (!animable.animation || !animable.animation->isReady()) return;
ComponentHandle model_instance = m_render_scene->getModelInstanceComponent(animable.entity);
if (model_instance == INVALID_COMPONENT) return;
auto* pose = m_render_scene->getPose(model_instance);
auto* model = m_render_scene->getModelInstanceModel(model_instance);
if (!pose) return;
if (!model->isReady()) return;
model->getPose(*pose);
pose->computeRelative(*model);
animable.animation->getRelativePose(animable.time, *pose, *model);
pose->computeAbsolute(*model);
float t = animable.time + time_delta * animable.time_scale;
float l = animable.animation->getLength();
while (t > l)
{
t -= l;
}
animable.time = t;
}
void updateAnimable(ComponentHandle cmp, float time_delta) override
{
Animable& animable = m_animables[{cmp.index}];
updateAnimable(animable, time_delta);
}
void updateController(ComponentHandle cmp, float time_delta) override
{
Controller& controller = m_controllers.get({cmp.index});
updateController(controller, time_delta);
processEventStream();
m_event_stream.clear();
}
void setControllerInput(ComponentHandle cmp, int input_idx, float value) override
{
Controller& ctrl = m_controllers.get({ cmp.index });
Anim::InputDecl& decl = ctrl.resource->m_input_decl;
if (!ctrl.root) return;
if (input_idx >= lengthOf(decl.inputs)) return;
if (decl.inputs[input_idx].type != Anim::InputDecl::FLOAT) return;
*(float*)&ctrl.input[decl.inputs[input_idx].offset] = value;
}
void setControllerInput(ComponentHandle cmp, int input_idx, bool value) override
{
Controller& ctrl = m_controllers.get({ cmp.index });
Anim::InputDecl& decl = ctrl.resource->m_input_decl;
if (!ctrl.root) return;
if (input_idx >= lengthOf(decl.inputs)) return;
if (decl.inputs[input_idx].type != Anim::InputDecl::BOOL) return;
*(bool*)&ctrl.input[decl.inputs[input_idx].offset] = value;
}
Anim::ComponentInstance* getControllerRoot(ComponentHandle cmp) override
{
return m_controllers.get({cmp.index}).root;
}
Transform getControllerRootMotion(ComponentHandle cmp) override
{
Controller& ctrl = m_controllers.get({cmp.index});
return ctrl.root ? ctrl.root->getRootMotion() : Transform({0, 0, 0}, {0, 0, 0, 1});
}
Entity getControllerEntity(ComponentHandle cmp) override { return {cmp.index}; }
u8* getControllerInput(ComponentHandle cmp)
{
auto& input = m_controllers.get({cmp.index}).input;
return input.empty() ? nullptr : &input[0];
}
void applyControllerSet(ComponentHandle cmp, const char* set_name) override
{
Controller& ctrl = m_controllers.get({cmp.index});
u32 set_name_hash = crc32(set_name);
int set_idx = ctrl.resource->m_sets_names.find([set_name_hash](const StaticString<32>& val) {
return crc32(val) == set_name_hash;
});
if (set_idx < 0) return;
for (auto& entry : ctrl.resource->m_animation_set)
{
if (entry.set != set_idx) continue;
ctrl.animations[entry.hash] = entry.animation;
}
if (ctrl.root) ctrl.root->onAnimationSetUpdated(ctrl.animations);
}
void setControllerDefaultSet(ComponentHandle cmp, int set) override
{
Controller& ctrl = m_controllers.get({cmp.index});
ctrl.default_set = ctrl.resource ? crc32(ctrl.resource->m_sets_names[set]) : 0;
}
int getControllerDefaultSet(ComponentHandle cmp) override
{
Controller& ctrl = m_controllers.get({ cmp.index });
auto is_default_set = [&ctrl](const StaticString<32>& val) {
return crc32(val) == ctrl.default_set;
};
int idx = 0;
if(ctrl.resource) idx = ctrl.resource->m_sets_names.find(is_default_set);
return idx < 0 ? 0 : idx;
}
Anim::ControllerResource* getControllerResource(ComponentHandle cmp) override
{
return m_controllers.get({cmp.index}).resource;
}
bool initControllerRuntime(Controller& controller)
{
if (!controller.resource->isReady()) return false;
if (controller.resource->m_input_decl.getSize() == 0) return false;
controller.root = controller.resource->createInstance(m_anim_system.m_allocator);
controller.input.resize(controller.resource->m_input_decl.getSize());
int set_idx = 0;
for (int i = 0; i < controller.resource->m_sets_names.size(); ++i)
{
if (controller.default_set == crc32(controller.resource->m_sets_names[i]))
{
set_idx = i;
break;
}
}
for (auto& entry : controller.resource->m_animation_set)
{
if (entry.set != set_idx) continue;
controller.animations.insert(entry.hash, entry.animation);
}
setMemory(&controller.input[0], 0, controller.input.size());
Anim::RunningContext rc;
rc.time_delta = 0;
rc.allocator = &m_anim_system.m_allocator;
rc.input = &controller.input[0];
rc.current = nullptr;
rc.anim_set = &controller.animations;
rc.event_stream = &m_event_stream;
rc.controller = {controller.entity.index};
controller.root->enter(rc, nullptr);
return true;
}
void updateSharedController(SharedController& controller, float time_delta)
{
if (!controller.parent.isValid()) return;
int parent_controller_idx = m_controllers.find(controller.parent);
if (parent_controller_idx < 0) return;
Controller& parent_controller = m_controllers.at(parent_controller_idx);
if (!parent_controller.root) return;
ComponentHandle model_instance = m_render_scene->getModelInstanceComponent(controller.entity);
if (model_instance == INVALID_COMPONENT) return;
Pose* pose = m_render_scene->getPose(model_instance);
if (!pose) return;
Model* model = m_render_scene->getModelInstanceModel(model_instance);
model->getPose(*pose);
pose->computeRelative(*model);
parent_controller.root->fillPose(m_anim_system.m_engine, *pose, *model, 1);
pose->computeAbsolute(*model);
}
void updateController(Controller& controller, float time_delta)
{
if (!controller.resource->isReady())
{
LUMIX_DELETE(m_anim_system.m_allocator, controller.root);
controller.root = nullptr;
return;
}
if (!controller.root && !initControllerRuntime(controller)) return;
Anim::RunningContext rc;
rc.time_delta = time_delta;
rc.current = controller.root;
rc.allocator = &m_anim_system.m_allocator;
rc.input = &controller.input[0];
rc.anim_set = &controller.animations;
rc.event_stream = &m_event_stream;
rc.controller = {controller.entity.index};
controller.root = controller.root->update(rc, true);
ComponentHandle model_instance = m_render_scene->getModelInstanceComponent(controller.entity);
if (model_instance == INVALID_COMPONENT) return;
Pose* pose = m_render_scene->getPose(model_instance);
if (!pose) return;
Model* model = m_render_scene->getModelInstanceModel(model_instance);
model->getPose(*pose);
pose->computeRelative(*model);
controller.root->fillPose(m_anim_system.m_engine, *pose, *model, 1);
pose->computeAbsolute(*model);
for (Controller::IK& ik : controller.inverse_kinematics)
{
if (ik.weight == 0) break;
updateIK(ik, *pose, *model, controller.entity);
}
}
void updateIK(Controller::IK& ik, Pose& pose, Model& model, Entity& entity)
{
decltype(model.getBoneIndex(0)) bones_iters[Controller::IK::MAX_BONES_COUNT];
for (int i = 0; i < ik.bones_count; ++i)
{
bones_iters[i] = model.getBoneIndex(ik.bones[i]);
if (!bones_iters[i].isValid()) return;
}
int indices[Controller::IK::MAX_BONES_COUNT];
Vec3 pos[Controller::IK::MAX_BONES_COUNT];
float len[Controller::IK::MAX_BONES_COUNT - 1];
float len_sum = 0;
for (int i = 0; i < ik.bones_count; ++i)
{
indices[i] = bones_iters[i].value();
pos[i] = pose.positions[indices[i]];
if (i > 0)
{
len[i - 1] = (pos[i] - pos[i - 1]).length();
len_sum += len[i - 1];
}
}
Vec3 target = ik.target;
Vec3 to_target = target - pos[0];
if (len_sum * len_sum < to_target.squaredLength()) {
to_target.normalize();
target = pos[0] + to_target * len_sum;
}
for (int iteration = 0; iteration < ik.max_iterations; ++iteration)
{
pos[ik.bones_count - 1] = target;
// backward
for (int i = ik.bones_count - 1; i > 0; --i)
{
Vec3 dir = (pos[i - 1] - pos[i]).normalized();
pos[i - 1] = pos[i] + dir * len[i - 1];
}
// backward
for (int i = 1; i < ik.bones_count; ++i)
{
Vec3 dir = (pos[i] - pos[i - 1]).normalized();
pos[i] = pos[i - 1] + dir * len[i - 1];
}
}
for (int i = 0; i < ik.bones_count; ++i)
{
if (i < ik.bones_count - 1)
{
Vec3 old_d = pose.positions[indices[i + 1]] - pose.positions[indices[i]];
Vec3 new_d = pos[i + 1] - pos[i];
old_d.normalize();
new_d.normalize();
Quat rel_rot = Quat::vec3ToVec3(old_d, new_d);
pose.rotations[indices[i]] = rel_rot * pose.rotations[indices[i]];
}
pose.positions[indices[i]] = pos[i];
}
}
void update(float time_delta, bool paused) override
{
PROFILE_FUNCTION();
if (!m_is_game_running) return;
if (paused) return;
m_event_stream.clear();
for (Animable& animable : m_animables)
{
AnimationSceneImpl::updateAnimable(animable, time_delta);
}
for (Controller& controller : m_controllers)
{
AnimationSceneImpl::updateController(controller, time_delta);
}
for (SharedController& controller : m_shared_controllers)
{
AnimationSceneImpl::updateSharedController(controller, time_delta);
}
processEventStream();
}
void processEventStream()
{
InputBlob blob(m_event_stream);
u32 set_input_type = crc32("set_input");
while (blob.getPosition() < blob.getSize())
{
u32 type;
u8 size;
ComponentHandle cmp;
blob.read(type);
blob.read(cmp);
blob.read(size);
if (type == set_input_type)
{
Anim::SetInputEvent event;
blob.read(event);
Controller& ctrl = m_controllers.get({cmp.index});
if (ctrl.resource->isReady())
{
Anim::InputDecl& decl = ctrl.resource->m_input_decl;
Anim::InputDecl::Input& input = decl.inputs[event.input_idx];
switch (input.type)
{
case Anim::InputDecl::BOOL: *(bool*)&ctrl.input[input.offset] = event.b_value; break;
case Anim::InputDecl::INT: *(int*)&ctrl.input[input.offset] = event.i_value; break;
case Anim::InputDecl::FLOAT: *(float*)&ctrl.input[input.offset] = event.f_value; break;
default: ASSERT(false); break;
}
}
}
else
{
blob.skip(size);
}
}
}
Animation* loadAnimation(const Path& path)
{
ResourceManager& rm = m_engine.getResourceManager();
return static_cast<Animation*>(rm.get(ANIMATION_TYPE)->load(path));
}
Anim::ControllerResource* loadController(const Path& path)
{
ResourceManager& rm = m_engine.getResourceManager();
return static_cast<Anim::ControllerResource*>(rm.get(CONTROLLER_RESOURCE_TYPE)->load(path));
}
ComponentHandle createAnimable(Entity entity)
{
Animable& animable = m_animables.insert(entity);
animable.time = 0;
animable.animation = nullptr;
animable.entity = entity;
animable.time_scale = 1;
animable.start_time = 0;
ComponentHandle cmp = {entity.index};
m_universe.addComponent(entity, ANIMABLE_TYPE, this, cmp);
return cmp;
}
ComponentHandle createController(Entity entity)
{
Controller& controller = m_controllers.emplace(entity, m_anim_system.m_allocator);
controller.entity = entity;
ComponentHandle cmp = {entity.index};
m_universe.addComponent(entity, CONTROLLER_TYPE, this, cmp);
return cmp;
}
ComponentHandle createSharedController(Entity entity)
{
m_shared_controllers.insert(entity, {entity, INVALID_ENTITY});
ComponentHandle cmp = {entity.index};
m_universe.addComponent(entity, SHARED_CONTROLLER_TYPE, this, cmp);
return cmp;
}
IPlugin& getPlugin() const override { return m_anim_system; }
Universe& m_universe;
AnimationSystemImpl& m_anim_system;
Engine& m_engine;
AssociativeArray<Entity, Animable> m_animables;
AssociativeArray<Entity, Controller> m_controllers;
AssociativeArray<Entity, SharedController> m_shared_controllers;
RenderScene* m_render_scene;
bool m_is_game_running;
OutputBlob m_event_stream;
};
AnimationSystemImpl::AnimationSystemImpl(Engine& engine)
: m_allocator(engine.getAllocator())
, m_engine(engine)
, m_animation_manager(m_allocator)
, m_controller_manager(m_allocator)
{
m_animation_manager.create(ANIMATION_TYPE, m_engine.getResourceManager());
m_controller_manager.create(CONTROLLER_RESOURCE_TYPE, m_engine.getResourceManager());
PropertyRegister::add("anim_controller",
LUMIX_NEW(m_allocator, ResourcePropertyDescriptor<AnimationSceneImpl>)("Source",
&AnimationSceneImpl::getControllerSource,
&AnimationSceneImpl::setControllerSource,
"Animation controller (*.act)",
CONTROLLER_RESOURCE_TYPE));
PropertyRegister::add("anim_controller", LUMIX_NEW(m_allocator, AnimSetPropertyDescriptor)("Default set"));
PropertyRegister::add("animable",
LUMIX_NEW(m_allocator, ResourcePropertyDescriptor<AnimationSceneImpl>)("Animation",
&AnimationSceneImpl::getAnimation,
&AnimationSceneImpl::setAnimation,
"Animation (*.ani)",
ANIMATION_TYPE));
PropertyRegister::add("animable",
LUMIX_NEW(m_allocator, DecimalPropertyDescriptor<AnimationSceneImpl>)(
"Start time", &AnimationSceneImpl::getStartTime, &AnimationSceneImpl::setStartTime, 0, FLT_MAX, 0.1f));
PropertyRegister::add("animable",
LUMIX_NEW(m_allocator, DecimalPropertyDescriptor<AnimationSceneImpl>)(
"Time scale", &AnimationSceneImpl::getTimeScale, &AnimationSceneImpl::setTimeScale, 0, FLT_MAX, 0.1f));
PropertyRegister::add("shared_anim_controller",
LUMIX_NEW(m_allocator, EntityPropertyDescriptor<AnimationSceneImpl>)(
"Parent", &AnimationSceneImpl::getSharedControllerParent, &AnimationSceneImpl::setSharedControllerParent));
registerLuaAPI();
}
AnimationSystemImpl::~AnimationSystemImpl()
{
m_animation_manager.destroy();
m_controller_manager.destroy();
}
void AnimationSystemImpl::registerLuaAPI()
{
lua_State* L = m_engine.getState();
#define REGISTER_FUNCTION(name) \
do {\
auto f = &LuaWrapper::wrapMethod<AnimationSceneImpl, decltype(&AnimationSceneImpl::name), &AnimationSceneImpl::name>; \
LuaWrapper::createSystemFunction(L, "Animation", #name, f); \
} while(false) \
REGISTER_FUNCTION(getAnimationLength);
REGISTER_FUNCTION(setControllerIntInput);
REGISTER_FUNCTION(setControllerBoolInput);
REGISTER_FUNCTION(setControllerFloatInput);
REGISTER_FUNCTION(getControllerInputIndex);
#undef REGISTER_FUNCTION
LuaWrapper::createSystemFunction(L, "Animation", "setIK", &AnimationSceneImpl::setIK); \
}
void AnimationSystemImpl::createScenes(Universe& ctx)
{
auto* scene = LUMIX_NEW(m_allocator, AnimationSceneImpl)(*this, m_engine, ctx, m_allocator);
ctx.addScene(scene);
}
void AnimationSystemImpl::destroyScene(IScene* scene) { LUMIX_DELETE(m_allocator, scene); }
LUMIX_PLUGIN_ENTRY(animation)
{
return LUMIX_NEW(engine.getAllocator(), AnimationSystemImpl)(engine);
}
}
| 28.580052 | 161 | 0.731105 | [
"model",
"transform"
] |
1931cccc2257fcc9489c3394be698f1abaae4de1 | 3,560 | cpp | C++ | answers/98/ans.cpp | yumaokao/leetcpp | 440296f8639673bb5b8f33ee8764f25bb7fc75db | [
"MIT"
] | null | null | null | answers/98/ans.cpp | yumaokao/leetcpp | 440296f8639673bb5b8f33ee8764f25bb7fc75db | [
"MIT"
] | null | null | null | answers/98/ans.cpp | yumaokao/leetcpp | 440296f8639673bb5b8f33ee8764f25bb7fc75db | [
"MIT"
] | null | null | null | #include <string>
#include <climits>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isValid(TreeNode* root, bool bmax, int vmax, bool bmin, int vmin) {
bool r = true;
if (root->left != NULL) {
if (root->left->val >= root->val || root->left->val < vmin)
return false;
if (bmin && root->left->val <= vmin)
return false;
if (isValid(root->left, true, root->val, bmin, vmin) == false)
return false;
}
if (root->right != NULL) {
if (root->right->val <= root->val || root->right->val > vmax)
return false;
if (bmax &&root->right->val >= vmax)
return false;
if (isValid(root->right, bmax, vmax, true, root->val) == false)
return false;
}
return true;
}
bool isValidBST(TreeNode* root) {
if (root == NULL)
return true;
return isValid(root, false, INT_MAX, false, INT_MIN);
}
};
void showTree(TreeNode* root) {
if (root == NULL)
return;
queue<TreeNode*> q;
queue<TreeNode*> nq;
q.push(root);
if (root->left)
nq.push(root->left);
if (root->right)
nq.push(root->right);
cout << "[" << root->val << "]" << endl;
while(nq.size() > 0) {
q = nq;
nq = {};
while(!q.empty()) {
TreeNode* n = q.front();
cout << " [" << n->val << "]";
if (n->left)
nq.push(n->left);
if (n->right)
nq.push(n->right);
q.pop();
}
cout << endl;
}
}
void showAns(TreeNode* root, bool ans) {
showTree(root);
cout << "isBST -> " << ((ans) ? "Yes" : "No") << endl;
}
int main() {
Solution s;
bool ans;
TreeNode* head = new TreeNode(2);
head->left = new TreeNode(1);
head->right = new TreeNode(3);
ans = s.isValidBST(head);
showAns(head, ans);
head = new TreeNode(1);
head->left = new TreeNode(2);
head->right = new TreeNode(3);
ans = s.isValidBST(head);
showAns(head, ans);
head = new TreeNode(6);
head->left = new TreeNode(2);
head->left->left = new TreeNode(1);
head->left->right = new TreeNode(7);
head->right = new TreeNode(8);
ans = s.isValidBST(head);
showAns(head, ans);
head = new TreeNode(6);
head->left = new TreeNode(2);
head->left->left = new TreeNode(1);
head->left->right = new TreeNode(5);
head->right = new TreeNode(8);
ans = s.isValidBST(head);
showAns(head, ans);
head = new TreeNode(6);
head->left = new TreeNode(2);
head->left->left = new TreeNode(1);
head->left->right = new TreeNode(5);
head->right = new TreeNode(10);
head->right->left = new TreeNode(5);
ans = s.isValidBST(head);
showAns(head, ans);
head = new TreeNode(6);
head->left = new TreeNode(2);
head->left->left = new TreeNode(1);
head->left->right = new TreeNode(5);
head->right = new TreeNode(10);
head->right->left = new TreeNode(7);
ans = s.isValidBST(head);
showAns(head, ans);
head = new TreeNode(6);
ans = s.isValidBST(head);
showAns(head, ans);
head = new TreeNode(1);
head->left = new TreeNode(1);
ans = s.isValidBST(head);
showAns(head, ans);
head = new TreeNode(INT_MIN);
head->right = new TreeNode(INT_MAX);
ans = s.isValidBST(head);
showAns(head, ans);
return 0;
}
| 23.267974 | 76 | 0.579494 | [
"vector"
] |
1932d038cd9415e14b0cb713fe5feb188882c9f9 | 11,643 | cpp | C++ | video/opengl/libretro_test_gl_compute_shaders/gl/mesh.cpp | jimbo00000/libretro-samples | 7418a585efd24c6506ca5f09f90c36268f0074ed | [
"MIT"
] | 58 | 2016-09-12T06:14:09.000Z | 2022-03-27T06:16:56.000Z | video/opengl/libretro_test_gl_compute_shaders/gl/mesh.cpp | jimbo00000/libretro-samples | 7418a585efd24c6506ca5f09f90c36268f0074ed | [
"MIT"
] | 9 | 2016-09-12T05:00:23.000Z | 2021-05-14T18:38:51.000Z | video/opengl/libretro_test_gl_compute_shaders/gl/mesh.cpp | jimbo00000/libretro-samples | 7418a585efd24c6506ca5f09f90c36268f0074ed | [
"MIT"
] | 39 | 2016-09-04T17:43:59.000Z | 2021-07-07T05:35:19.000Z | #include "mesh.hpp"
#include "shader.hpp"
#include <set>
using namespace std;
using namespace glm;
namespace GL
{
template<typename T>
inline T parse_line(const string& data);
template<>
inline vec2 parse_line(const string& data)
{
float x = 0, y = 0;
vector<string> split = String::split(data, " ");
if (split.size() >= 2)
{
x = stof(split[0]);
y = stof(split[1]);
}
return vec2(x, y);
}
template<>
inline vec3 parse_line(const string& data)
{
float x = 0, y = 0, z = 0;
vector<string> split = String::split(data, " ");
if (split.size() >= 3)
{
x = stof(split[0]);
y = stof(split[1]);
z = stof(split[2]);
}
return vec3(x, y, z);
}
inline size_t translate_index(int index, size_t size)
{
return index < 0 ? size + index + 1 : index;
}
static map<string, Material> parse_mtllib(const string& path)
{
map<string, Material> materials;
ifstream file(asset_path(path).c_str(), ios::in);
if (!file.is_open())
throw runtime_error(String::cat("Failed to open mtllib: ", path));
Material current;
string current_mtl;
for (string line; getline(file, line); )
{
line = String::strip(line);
size_t split_point = line.find_first_of(' ');
string type = line.substr(0, split_point);
string data = split_point != string::npos ? line.substr(split_point + 1) : string();
if (type == "newmtl")
{
if (!current_mtl.empty())
materials[current_mtl] = current;
current = Material();
current_mtl = data;
}
else if (type == "Ka")
current.ambient = parse_line<vec3>(data);
else if (type == "Kd")
current.diffuse = parse_line<vec3>(data);
else if (type == "Ks")
current.specular = parse_line<vec3>(data);
else if (type == "Ns")
current.specular_power = stof(data);
else if (type == "map_Kd")
current.diffuse_map = Path::join(Path::basedir(path), data);
}
materials[current_mtl] = current;
return materials;
}
void Mesh::finalize()
{
arrays.clear();
GLsizei offset = 0;
if (has_vertex)
{
arrays.push_back({ Shader::VertexLocation, 3, GL_FLOAT, GL_FALSE, 0, 0, 0, offset});
offset += 3 * sizeof(float);
}
if (has_normal)
{
arrays.push_back({ Shader::NormalLocation, 3, GL_FLOAT, GL_FALSE, 0, 0, 0, offset});
offset += 3 * sizeof(float);
}
if (has_texcoord)
{
arrays.push_back({ Shader::TexCoordLocation, 2, GL_FLOAT, GL_FALSE, 0, 0, 0, offset});
offset += 2 * sizeof(float);
}
for (auto& array : arrays)
array.stride = offset;
}
struct Face
{
int vertex = -1;
int normal = -1;
int texcoord = -1;
unsigned buffer_index = 0;
bool operator<(const Face& other) const
{
if (vertex - other.vertex)
return vertex < other.vertex;
if (normal - other.normal)
return normal < other.normal;
if (texcoord - other.texcoord)
return texcoord < other.texcoord;
return false;
}
};
static void parse_vertex(const string& vert,
set<Face>& faces,
Mesh& mesh,
const vector<vec3>& vertex,
const vector<vec3>& normal,
const vector<vec2>& tex)
{
Face face;
auto coords = String::split(vert, "/", true);
if (coords.size() == 1) // Vertex only
{
size_t coord = translate_index(stoi(coords[0]), vertex.size());
if (coord && vertex.size() >= coord)
face.vertex = coord - 1;
mesh.has_vertex = true;
}
else if (coords.size() == 2) // Vertex/Texcoord
{
size_t coord_vert = translate_index(stoi(coords[0]), vertex.size());
size_t coord_tex = translate_index(stoi(coords[1]), tex.size());
if (coord_vert && vertex.size() >= coord_vert)
face.vertex = coord_vert - 1;
if (coord_tex && tex.size() >= coord_tex)
face.texcoord = coord_tex - 1;
mesh.has_vertex = true;
mesh.has_texcoord = true;
}
else if (coords.size() == 3 && coords[1].size()) // Vertex/Texcoord/Normal
{
size_t coord_vert = translate_index(stoi(coords[0]), vertex.size());
size_t coord_tex = translate_index(stoi(coords[1]), tex.size());
size_t coord_normal = translate_index(stoi(coords[2]), normal.size());
if (coord_vert && vertex.size() >= coord_vert)
face.vertex = coord_vert - 1;
if (coord_tex && tex.size() >= coord_tex)
face.texcoord = coord_tex - 1;
if (coord_normal && normal.size() >= coord_normal)
face.normal = coord_normal - 1;
mesh.has_vertex = true;
mesh.has_texcoord = true;
mesh.has_normal = true;
}
else if (coords.size() == 3 && !coords[1].size()) // Vertex//Normal
{
size_t coord_vert = translate_index(stoi(coords[0]), vertex.size());
size_t coord_normal = translate_index(stoi(coords[2]), normal.size());
if (coord_vert && vertex.size() >= coord_vert)
face.vertex = coord_vert - 1;
if (coord_normal && normal.size() >= coord_normal)
face.normal = coord_normal - 1;
mesh.has_vertex = true;
mesh.has_normal = true;
}
auto itr = faces.find(face);
if (itr == end(faces))
{
face.buffer_index = faces.size();
faces.insert(face);
if (face.vertex >= 0)
mesh.vbo.insert(end(mesh.vbo),
value_ptr(vertex[face.vertex]),
value_ptr(vertex[face.vertex]) + 3);
if (face.normal >= 0)
mesh.vbo.insert(end(mesh.vbo),
value_ptr(normal[face.normal]),
value_ptr(normal[face.normal]) + 3);
if (face.texcoord >= 0)
mesh.vbo.insert(end(mesh.vbo),
value_ptr(tex[face.texcoord]),
value_ptr(tex[face.texcoord]) + 2);
mesh.ibo.push_back(face.buffer_index);
}
else
mesh.ibo.push_back(itr->buffer_index);
}
static void parse_face(const string& data,
set<Face>& faces,
Mesh& mesh,
const vector<vec3>& vertex,
const vector<vec3>& normal,
const vector<vec2>& tex)
{
vector<string> vertices = String::split(data, " ");
if (vertices.size() > 3)
vertices.resize(3);
for (auto& vert : vertices)
parse_vertex(vert, faces, mesh, vertex, normal, tex);
}
static AABB compute_aabb(const vector<float>& vec, unsigned stride)
{
if (vec.empty())
return {};
auto minimum = make_vec3(vec.data());
vec3 maximum = minimum;
for (unsigned i = stride; i < vec.size(); i += stride)
{
auto v = make_vec3(vec.data() + i);
minimum = min(minimum, v);
maximum = max(maximum, v);
}
AABB aabb;
aabb.base = minimum;
aabb.offset = maximum - minimum;
return aabb;
}
vector<Mesh> load_meshes_obj(const string& path)
{
vector<Mesh> meshes;
vector<vec3> vertex;
vector<vec3> normal;
vector<vec2> tex;
Material current_material;
map<string, Material> materials;
Mesh current;
set<Face> faces;
ifstream file(asset_path(path).c_str(), ios::in);
if (!file.is_open())
throw runtime_error(String::cat("Failed to open OBJ: ", path));
for (string line; getline(file, line); )
{
line = String::strip(line);
size_t split_point = line.find_first_of(' ');
string type = line.substr(0, split_point);
string data = split_point != string::npos ? line.substr(split_point + 1) : string();
if (type == "v")
vertex.push_back(parse_line<vec3>(data));
else if (type == "vn")
normal.push_back(parse_line<vec3>(data));
else if (type == "vt")
tex.push_back(parse_line<vec2>(data));
else if (type == "f")
parse_face(data, faces, current, vertex, normal, tex);
else if (type == "usemtl")
{
if (!current.ibo.empty()) // Different texture, new mesh.
{
current.finalize();
meshes.push_back(move(current));
current = Mesh();
}
faces.clear();
current.material = materials[data];
}
else if (type == "mtllib")
materials = parse_mtllib(Path::join(Path::basedir(path), data));
}
if (!current.ibo.empty())
{
current.finalize();
meshes.push_back(move(current));
}
for (auto& mesh : meshes)
{
unsigned stride = 0;
if (mesh.has_vertex)
stride += 3;
if (mesh.has_normal)
stride += 3;
if (mesh.has_texcoord)
stride += 2;
mesh.aabb = compute_aabb(mesh.vbo, stride);
}
return meshes;
}
Mesh create_mesh_box()
{
Mesh mesh{};
mesh.has_vertex = true;
mesh.has_normal = true;
mesh.has_texcoord = true;
struct Vertex
{
float vert[3];
float normal[3];
float tex[2];
};
static const Vertex vertex_data[] = {
{ { -1, -1, 1 }, { 0, 0, 1 }, { 0, 1 } }, // Front
{ { 1, -1, 1 }, { 0, 0, 1 }, { 1, 1 } },
{ { -1, 1, 1 }, { 0, 0, 1 }, { 0, 0 } },
{ { 1, 1, 1 }, { 0, 0, 1 }, { 1, 0 } },
{ { 1, -1, -1 }, { 0, 0, -1 }, { 0, 1 } }, // Back
{ { -1, -1, -1 }, { 0, 0, -1 }, { 1, 1 } },
{ { 1, 1, -1 }, { 0, 0, -1 }, { 0, 0 } },
{ { -1, 1, -1 }, { 0, 0, -1 }, { 1, 0 } },
{ { -1, -1, -1 }, { -1, 0, 0 }, { 0, 1 } }, // Left
{ { -1, -1, 1 }, { -1, 0, 0 }, { 1, 1 } },
{ { -1, 1, -1 }, { -1, 0, 0 }, { 0, 0 } },
{ { -1, 1, 1 }, { -1, 0, 0 }, { 1, 0 } },
{ { 1, -1, 1 }, { 1, 0, 0 }, { 0, 1 } }, // Right
{ { 1, -1, -1 }, { 1, 0, 0 }, { 1, 1 } },
{ { 1, 1, 1 }, { 1, 0, 0 }, { 0, 0 } },
{ { 1, 1, -1 }, { 1, 0, 0 }, { 1, 0 } },
{ { -1, 1, 1 }, { 0, 1, 0 }, { 0, 1 } }, // Top
{ { 1, 1, 1 }, { 0, 1, 0 }, { 1, 1 } },
{ { -1, 1, -1 }, { 0, 1, 0 }, { 0, 0 } },
{ { 1, 1, -1 }, { 0, 1, 0 }, { 1, 0 } },
{ { -1, -1, -1 }, { 0, -1, 0 }, { 0, 1 } }, // Bottom
{ { 1, -1, -1 }, { 0, -1, 0 }, { 1, 1 } },
{ { -1, -1, 1 }, { 0, -1, 0 }, { 0, 0 } },
{ { 1, -1, 1 }, { 0, -1, 0 }, { 1, 0 } },
};
static const GLuint indices[] = {
0, 1, 2, // Front
3, 2, 1,
4, 5, 6, // Back
7, 6, 5,
8, 9, 10, // Left
11, 10, 9,
12, 13, 14, // Right
15, 14, 13,
16, 17, 18, // Top
19, 18, 17,
20, 21, 22, // Bottom
23, 22, 21,
};
mesh.vbo.resize(sizeof(vertex_data) / sizeof(float));
memcpy(mesh.vbo.data(), vertex_data, sizeof(vertex_data));
mesh.ibo.insert(end(mesh.ibo), indices, indices + 36);
mesh.aabb.base = vec3(-1);
mesh.aabb.offset = vec3(2);
mesh.finalize();
return mesh;
}
}
| 28.60688 | 95 | 0.488019 | [
"mesh",
"vector"
] |
1936230135540216cf3efdd70e1289daee38f592 | 26,496 | hpp | C++ | include/eagine/msgbus/posix_mqueue.hpp | matus-chochlik/eagine-msgbus | 1672be9db227e918b17792e01d8a45ac58954181 | [
"BSL-1.0"
] | 1 | 2021-07-18T10:17:10.000Z | 2021-07-18T10:17:10.000Z | include/eagine/msgbus/posix_mqueue.hpp | matus-chochlik/eagine-msgbus | 1672be9db227e918b17792e01d8a45ac58954181 | [
"BSL-1.0"
] | null | null | null | include/eagine/msgbus/posix_mqueue.hpp | matus-chochlik/eagine-msgbus | 1672be9db227e918b17792e01d8a45ac58954181 | [
"BSL-1.0"
] | 1 | 2021-06-25T07:15:10.000Z | 2021-06-25T07:15:10.000Z | /// @file
///
/// Copyright Matus Chochlik.
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE_1_0.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
///
#ifndef EAGINE_MSGBUS_POSIX_MQUEUE_HPP
#define EAGINE_MSGBUS_POSIX_MQUEUE_HPP
#include "conn_factory.hpp"
#include "serialize.hpp"
#include <eagine/bool_aggregate.hpp>
#include <eagine/branch_predict.hpp>
#include <eagine/main_ctx_object.hpp>
#include <eagine/random_identifier.hpp>
#include <eagine/serialize/block_sink.hpp>
#include <eagine/serialize/block_source.hpp>
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <mqueue.h>
#include <mutex>
#include <random>
#include <sys/resource.h>
#include <sys/stat.h>
namespace eagine::msgbus {
//------------------------------------------------------------------------------
/// @brief Class wrapping a POSIX message queue
/// @ingroup msgbus
class posix_mqueue : public main_ctx_object {
public:
posix_mqueue(main_ctx_parent parent) noexcept
: main_ctx_object{EAGINE_ID(PosixMQue), parent} {}
/// @brief Move constructible.
posix_mqueue(posix_mqueue&& temp) noexcept
: main_ctx_object{static_cast<main_ctx_object&&>(temp)} {
using std::swap;
swap(_s2cname, temp._s2cname);
swap(_c2sname, temp._c2sname);
swap(_ihandle, temp._ihandle);
swap(_ohandle, temp._ohandle);
}
/// @brief Not copy constructible.
posix_mqueue(const posix_mqueue&) = delete;
/// @brief Not move assignable.
auto operator=(posix_mqueue&& temp) = delete;
/// @brief Not copy assignable.
auto operator=(const posix_mqueue&) = delete;
~posix_mqueue() noexcept {
try {
this->close();
} catch(...) {
}
}
/// @brief Returns the unique name of this queue.
/// @see set_name
auto get_name() const noexcept -> string_view {
return _s2cname.empty()
? string_view{}
: string_view{
_s2cname.data(), span_size(_s2cname.size() - 1U)};
}
/// @brief Sets the unique name of the queue.
/// @see get_name
auto set_name(std::string name) noexcept -> auto& {
_s2cname = std::move(name);
if(_s2cname.empty()) {
_s2cname = "/eagine-msgbus";
} else {
if(_s2cname.front() != '/') {
_s2cname.insert(_s2cname.begin(), '/');
}
}
log_info("assigned message queue name ${name}")
.arg(EAGINE_ID(name), _s2cname);
_c2sname = _s2cname;
_s2cname.push_back('s');
_c2sname.push_back('c');
return *this;
}
static auto name_from(const identifier id) noexcept -> std::string {
std::string result;
result.reserve(std_size(identifier::max_size() + 1));
id.name().str(result);
return result;
}
/// @brief Sets the unique name of the queue.
/// @see get_name
auto set_name(const identifier id) noexcept -> auto& {
return set_name(name_from(id));
}
/// @brief Constructs the queue and sets the specified name.
/// @see set_name
posix_mqueue(main_ctx_parent parent, std::string name) noexcept
: main_ctx_object{EAGINE_ID(PosixMQue), parent} {
set_name(std::move(name));
}
auto error_message(const int error_number) const noexcept -> std::string {
if(error_number) {
char buf[128] = {};
const auto unused =
::strerror_r(error_number, static_cast<char*>(buf), sizeof(buf));
EAGINE_MAYBE_UNUSED(unused);
return {static_cast<const char*>(buf)};
}
return {};
}
/// @brief Returns the error message of the last failed operation.
/// @see had_error
auto error_message() const noexcept -> std::string {
return error_message(_last_errno);
}
/// @brief Indicates if there a previous operation finished with an error.
/// @see error_message
/// @see needs_retry
auto had_error() const noexcept -> bool {
return _last_errno != 0;
}
/// @brief Indicates if a previous operation on the queue needs to be retried.
/// @see had_error
auto needs_retry() const noexcept -> bool {
return (_last_errno == EAGAIN) || (_last_errno == ETIMEDOUT);
}
/// @brief Indicates if this message queue is open.
/// @see is_usable
constexpr auto is_open() const noexcept -> bool {
return (_ihandle >= 0) && (_ohandle >= 0);
}
/// @brief Indicates if this message queue can be used.
/// @see is_open
/// @see had_error
constexpr auto is_usable() const noexcept -> bool {
return is_open() && !(had_error() && !needs_retry());
}
/// @brief Unlinks the OS queue objects.
/// @see create
/// @see open
/// @see close
auto unlink() noexcept -> auto& {
if(get_name()) {
log_debug("unlinking message queue ${name}")
.arg(EAGINE_ID(name), get_name());
errno = 0;
::mq_unlink(_s2cname.c_str());
::mq_unlink(_c2sname.c_str());
_last_errno = errno;
}
return *this;
}
/// @brief Creates new OS queue objects.
/// @see unlink
/// @see open
/// @see close
auto create() noexcept -> auto& {
log_debug("creating new message queue ${name}")
.arg(EAGINE_ID(name), get_name());
struct ::mq_attr attr {};
zero(as_bytes(cover_one(attr)));
attr.mq_maxmsg = limit_cast<long>(8);
attr.mq_msgsize = limit_cast<long>(default_data_size());
errno = 0;
// NOLINTNEXTLINE(hicpp-vararg)
_ihandle = ::mq_open(
_c2sname.c_str(),
// NOLINTNEXTLINE(hicpp-signed-bitwise)
O_RDONLY | O_CREAT | O_EXCL | O_NONBLOCK,
// NOLINTNEXTLINE(hicpp-signed-bitwise)
S_IRUSR | S_IWUSR,
&attr);
_last_errno = errno;
if(_last_errno == 0) {
// NOLINTNEXTLINE(hicpp-vararg)
_ohandle = ::mq_open(
_s2cname.c_str(),
// NOLINTNEXTLINE(hicpp-signed-bitwise)
O_WRONLY | O_CREAT | O_EXCL | O_NONBLOCK,
// NOLINTNEXTLINE(hicpp-signed-bitwise)
S_IRUSR | S_IWUSR,
&attr);
_last_errno = errno;
}
if(_last_errno) {
log_error("failed to create message queue ${name}")
.arg(EAGINE_ID(name), get_name())
.arg(EAGINE_ID(errno), _last_errno)
.arg(EAGINE_ID(message), error_message(_last_errno));
}
return *this;
}
/// @brief Opens existing OS queue objects.
/// @see create
/// @see unlink
/// @see close
auto open() noexcept -> auto& {
log_debug("opening existing message queue ${name}")
.arg(EAGINE_ID(name), get_name());
errno = 0;
// NOLINTNEXTLINE(hicpp-vararg)
_ihandle = ::mq_open(
_s2cname.c_str(),
// NOLINTNEXTLINE(hicpp-signed-bitwise)
O_RDONLY | O_NONBLOCK,
// NOLINTNEXTLINE(hicpp-signed-bitwise)
S_IRUSR | S_IWUSR,
nullptr);
_last_errno = errno;
if(_last_errno == 0) {
// NOLINTNEXTLINE(hicpp-vararg)
_ohandle = ::mq_open(
_c2sname.c_str(),
// NOLINTNEXTLINE(hicpp-signed-bitwise)
O_WRONLY | O_NONBLOCK,
// NOLINTNEXTLINE(hicpp-signed-bitwise)
S_IRUSR | S_IWUSR,
nullptr);
_last_errno = errno;
}
if(_last_errno) {
log_error("failed to open message queue ${name}")
.arg(EAGINE_ID(name), get_name())
.arg(EAGINE_ID(errno), _last_errno)
.arg(EAGINE_ID(message), error_message(_last_errno));
}
return *this;
}
/// @brief Closes the OS queue objects.
/// @see create
/// @see open
/// @see unlink
auto close() noexcept -> posix_mqueue& {
if(is_open()) {
log_debug("closing message queue ${name}")
.arg(EAGINE_ID(name), get_name());
::mq_close(_ihandle);
::mq_close(_ohandle);
_ihandle = _invalid_handle();
_ohandle = _invalid_handle();
_last_errno = errno;
}
return *this;
}
constexpr static auto default_data_size() noexcept -> span_size_t {
return 2 * 1024;
}
/// @brief Returns the absolute maximum block size that can be sent in a message.
/// @see data_size
auto max_data_size() noexcept -> valid_if_positive<span_size_t> {
if(is_open()) {
struct ::mq_attr attr {};
errno = 0;
::mq_getattr(_ohandle, &attr);
_last_errno = errno;
return {span_size(attr.mq_msgsize)};
}
return {0};
}
/// @brief Returns the maximum block size that can be sent in a message.
auto data_size() noexcept -> span_size_t {
return extract_or(max_data_size(), default_data_size());
}
/// @brief Sends a block of data with the specified priority.
auto send(const unsigned priority, const span<const char> blk) noexcept
-> auto& {
if(is_open()) {
errno = 0;
::mq_send(_ohandle, blk.data(), std_size(blk.size()), priority);
_last_errno = errno;
if(EAGINE_UNLIKELY((_last_errno != 0) && (_last_errno != EAGAIN))) {
log_error("failed to send message")
.arg(EAGINE_ID(name), get_name())
.arg(EAGINE_ID(errno), _last_errno)
.arg(EAGINE_ID(data), as_bytes(blk));
}
}
return *this;
}
/// @brief Alias for received message handler.
/// @see receive
using receive_handler =
callable_ref<void(unsigned, span<const char>) noexcept>;
/// @brief Receives messages and calls the specified handler on them.
auto receive(memory::span<char> blk, const receive_handler handler) noexcept
-> bool {
if(is_open()) {
unsigned priority{0U};
errno = 0;
const auto received =
::mq_receive(_ihandle, blk.data(), blk.size(), &priority);
_last_errno = errno;
if(received > 0) {
handler(priority, head(blk, received));
return true;
} else if(EAGINE_UNLIKELY(
(_last_errno != 0) && (_last_errno != EAGAIN) &&
(_last_errno != ETIMEDOUT))) {
log_error("failed to receive message")
.arg(EAGINE_ID(name), get_name())
.arg(EAGINE_ID(errno), _last_errno);
}
}
return false;
}
private:
std::string _s2cname{};
std::string _c2sname{};
static constexpr auto _invalid_handle() noexcept -> ::mqd_t {
return ::mqd_t(-1);
}
::mqd_t _ihandle{_invalid_handle()};
::mqd_t _ohandle{_invalid_handle()};
int _last_errno{0};
};
//------------------------------------------------------------------------------
struct posix_mqueue_shared_state {
auto make_id() const noexcept {
return random_identifier();
}
};
//------------------------------------------------------------------------------
/// @brief Implementation of the connection_info interface for POSIX queue connection.
/// @ingroup msgbus
/// @see connection_info
template <typename Base>
class posix_mqueue_connection_info : public Base {
public:
using Base::Base;
auto kind() noexcept -> connection_kind final {
return connection_kind::local_interprocess;
}
auto addr_kind() noexcept -> connection_addr_kind final {
return connection_addr_kind::filepath;
}
auto type_id() noexcept -> identifier final {
return EAGINE_ID(PosixMQue);
}
};
//------------------------------------------------------------------------------
/// @brief Implementation of connection on top of POSIX message queues.
/// @ingroup msgbus
/// @see posix_mqueue
/// @see posix_mqueue_connector
/// @see posix_mqueue_acceptor
class posix_mqueue_connection
: public posix_mqueue_connection_info<connection>
, public main_ctx_object {
public:
/// @brief Alias for received message fetch handler callable.
using fetch_handler = connection::fetch_handler;
/// @brief Construction from parent main context object.
posix_mqueue_connection(
main_ctx_parent parent,
std::shared_ptr<posix_mqueue_shared_state> shared_state) noexcept
: main_ctx_object{EAGINE_ID(MQueConn), parent}
, _shared_state{std::move(shared_state)} {
_buffer.resize(_data_queue.data_size());
}
/// @brief Opens the connection.
auto open(std::string name) noexcept -> bool {
return !_data_queue.set_name(std::move(name)).open().had_error();
}
auto is_usable() noexcept -> bool final {
return _data_queue.is_usable();
}
auto max_data_size() noexcept -> valid_if_positive<span_size_t> final {
return {_buffer.size()};
}
auto update() noexcept -> work_done override {
std::unique_lock lock{_mutex};
some_true something_done{};
something_done(_receive());
something_done(_send());
return something_done;
}
auto send(const message_id msg_id, const message_view& message) noexcept
-> bool final {
if(EAGINE_LIKELY(is_usable())) {
block_data_sink sink(cover(_buffer));
default_serializer_backend backend(sink);
auto errors = serialize_message(msg_id, message, backend);
if(!errors) {
std::unique_lock lock{_mutex};
_outgoing.push(sink.done());
return true;
} else {
log_error("failed to serialize message");
}
}
return false;
}
auto fetch_messages(const fetch_handler handler) noexcept
-> work_done final {
std::unique_lock lock{_mutex};
return _incoming.fetch_all(handler);
}
auto query_statistics(connection_statistics&) noexcept -> bool final {
return false;
}
protected:
auto _checkup(posix_mqueue& connect_queue) noexcept -> work_done {
some_true something_done{};
if(connect_queue.is_usable()) {
if(!_data_queue.is_usable()) {
if(_reconnect_timeout) {
_data_queue.close();
_data_queue.unlink();
EAGINE_ASSERT(_shared_state);
log_debug("connecting to ${name}")
.arg(EAGINE_ID(name), connect_queue.get_name());
if(!_data_queue.set_name(_shared_state->make_id())
.create()
.had_error()) {
_buffer.resize(connect_queue.data_size());
block_data_sink sink(cover(_buffer));
default_serializer_backend backend(sink);
const auto errors = serialize_message(
EAGINE_MSGBUS_ID(pmqConnect),
message_view(_data_queue.get_name()),
backend);
if(EAGINE_LIKELY(!errors)) {
connect_queue.send(1, as_chars(sink.done()));
_buffer.resize(_data_queue.data_size());
something_done();
} else {
log_error("failed to serialize connection name")
.arg(EAGINE_ID(client), _data_queue.get_name())
.arg(EAGINE_ID(server), connect_queue.get_name());
}
} else {
log_warning("failed to connect to ${server}")
.arg(EAGINE_ID(server), connect_queue.get_name());
}
_reconnect_timeout.reset();
}
}
}
return something_done;
}
auto _receive() noexcept -> work_done {
some_true something_done{};
if(_data_queue.is_usable()) {
while(_data_queue.receive(
as_chars(cover(_buffer)),
posix_mqueue::receive_handler(
EAGINE_THIS_MEM_FUNC_REF(_handle_receive)))) {
something_done();
}
}
return something_done;
}
auto _send() noexcept -> bool {
if(_data_queue.is_usable()) {
return _outgoing.fetch_all(EAGINE_THIS_MEM_FUNC_REF(_handle_send));
}
return false;
}
protected:
auto _handle_send(
const message_timestamp,
const memory::const_block data) noexcept -> bool {
return !_data_queue.send(1, as_chars(data)).had_error();
}
void _handle_receive(
const unsigned,
const memory::span<const char> data) noexcept {
_incoming.push_if(
[data](
message_id& msg_id, message_timestamp&, stored_message& message) {
block_data_source source(as_bytes(data));
default_deserializer_backend backend(source);
const auto errors = deserialize_message(msg_id, message, backend);
return !errors;
});
}
std::mutex _mutex;
memory::buffer _buffer;
message_storage _incoming;
serialized_message_storage _outgoing;
posix_mqueue _data_queue{*this};
timeout _reconnect_timeout{std::chrono::seconds{2}, nothing};
std::shared_ptr<posix_mqueue_shared_state> _shared_state;
};
//------------------------------------------------------------------------------
/// @brief Implementation of connection on top of POSIX message queues.
/// @ingroup msgbus
/// @see posix_mqueue
/// @see posix_mqueue_acceptor
class posix_mqueue_connector final : public posix_mqueue_connection {
using base = posix_mqueue_connection;
public:
/// @brief Alias for received message fetch handler callable.
using fetch_handler = connection::fetch_handler;
/// @brief Construction from parent main context object and queue name.
posix_mqueue_connector(
main_ctx_parent parent,
std::string name,
std::shared_ptr<posix_mqueue_shared_state> shared_state) noexcept
: base{parent, std::move(shared_state)}
, _connect_queue{*this, std::move(name)} {}
/// @brief Construction from parent main context object and queue identifier.
posix_mqueue_connector(
main_ctx_parent parent,
const identifier id,
std::shared_ptr<posix_mqueue_shared_state> shared_state) noexcept
: base{parent, std::move(shared_state)}
, _connect_queue{*this, posix_mqueue::name_from(id)} {}
posix_mqueue_connector(posix_mqueue_connector&&) = delete;
posix_mqueue_connector(const posix_mqueue_connector&) = delete;
auto operator=(posix_mqueue_connector&&) = delete;
auto operator=(const posix_mqueue_connector&) = delete;
~posix_mqueue_connector() noexcept final {
_data_queue.unlink();
}
auto update() noexcept -> work_done final {
std::unique_lock lock{_mutex};
some_true something_done{};
something_done(_checkup());
something_done(_receive());
something_done(_send());
return something_done;
}
private:
auto _checkup() noexcept -> work_done {
some_true something_done{};
if(!_connect_queue.is_usable()) {
if(_reconnect_timeout) {
_connect_queue.close();
if(!_connect_queue.open().had_error()) {
something_done();
}
_reconnect_timeout.reset();
}
}
something_done(posix_mqueue_connection::_checkup(_connect_queue));
return something_done;
}
posix_mqueue _connect_queue{*this};
};
//------------------------------------------------------------------------------
/// @brief Implementation of acceptor on top of POSIX message queues.
/// @ingroup msgbus
/// @see posix_mqueue
/// @see posix_mqueue_connector
class posix_mqueue_acceptor final
: public posix_mqueue_connection_info<acceptor>
, public main_ctx_object {
public:
/// @brief Alias for accepted connection handler callable.
using accept_handler = acceptor::accept_handler;
/// @brief Construction from parent main context object and queue name.
posix_mqueue_acceptor(
main_ctx_parent parent,
std::string name,
std::shared_ptr<posix_mqueue_shared_state> shared_state) noexcept
: main_ctx_object{EAGINE_ID(MQueConnAc), parent}
, _accept_queue{*this, std::move(name)}
, _shared_state{std::move(shared_state)} {
_buffer.resize(_accept_queue.data_size());
}
/// @brief Construction from parent main context object and queue identifier.
posix_mqueue_acceptor(
main_ctx_parent parent,
const identifier id,
std::shared_ptr<posix_mqueue_shared_state> shared_state) noexcept
: posix_mqueue_acceptor{
parent,
posix_mqueue::name_from(id),
std::move(shared_state)} {}
posix_mqueue_acceptor(posix_mqueue_acceptor&&) noexcept = default;
posix_mqueue_acceptor(const posix_mqueue_acceptor&) = delete;
auto operator=(posix_mqueue_acceptor&&) = delete;
auto operator=(const posix_mqueue_acceptor&) = delete;
~posix_mqueue_acceptor() noexcept final {
_accept_queue.unlink();
}
auto update() noexcept -> work_done final {
some_true something_done{};
something_done(_checkup());
something_done(_receive());
return something_done;
}
auto process_accepted(const accept_handler handler) noexcept
-> work_done final {
auto fetch_handler = [this, &handler](
const message_id msg_id,
const message_age,
const message_view& message) -> bool {
EAGINE_ASSERT((msg_id == EAGINE_MSGBUS_ID(pmqConnect)));
EAGINE_MAYBE_UNUSED(msg_id);
log_debug("accepting connection from ${name}")
.arg(EAGINE_ID(name), message.text_content());
if(auto conn{std::make_unique<posix_mqueue_connection>(
*this, _shared_state)}) {
if(conn->open(to_string(message.text_content()))) {
handler(std::move(conn));
}
}
return true;
};
return _requests.fetch_all({construct_from, fetch_handler});
}
private:
auto _checkup() noexcept -> work_done {
some_true something_done{};
if(!_accept_queue.is_usable()) {
if(_reconnect_timeout) {
_accept_queue.close();
_accept_queue.unlink();
if(!_accept_queue.create().had_error()) {
_buffer.resize(_accept_queue.data_size());
something_done();
}
_reconnect_timeout.reset();
}
}
return something_done;
}
auto _receive() noexcept -> work_done {
some_true something_done{};
if(_accept_queue.is_usable()) {
while(_accept_queue.receive(
as_chars(cover(_buffer)),
EAGINE_THIS_MEM_FUNC_REF(_handle_receive))) {
something_done();
}
}
return something_done;
}
void _handle_receive(
const unsigned,
const memory::span<const char> data) noexcept {
_requests.push_if(
[data](
message_id& msg_id, message_timestamp&, stored_message& message) {
block_data_source source(as_bytes(data));
default_deserializer_backend backend(source);
const auto errors = deserialize_message(msg_id, message, backend);
if(EAGINE_LIKELY(is_special_message(msg_id))) {
if(EAGINE_LIKELY(msg_id.has_method(EAGINE_ID(pmqConnect)))) {
return !errors;
}
}
return false;
});
}
memory::buffer _buffer;
message_storage _requests;
posix_mqueue _accept_queue;
timeout _reconnect_timeout{std::chrono::seconds{2}, nothing};
std::shared_ptr<posix_mqueue_shared_state> _shared_state;
};
//------------------------------------------------------------------------------
/// @brief Implementation of connection_factory for POSIX message queue connections.
/// @ingroup msgbus
/// @see posix_mqueue_connector
/// @see posix_mqueue_acceptor
class posix_mqueue_connection_factory
: public posix_mqueue_connection_info<connection_factory>
, public main_ctx_object {
public:
/// @brief Construction from parent main context object.
posix_mqueue_connection_factory(main_ctx_parent parent) noexcept
: main_ctx_object{EAGINE_ID(MQueConnFc), parent} {
_increase_res_limit();
}
using connection_factory::make_acceptor;
using connection_factory::make_connector;
/// @brief Makes an connection acceptor listening at queue with the specified name.
auto make_acceptor(const string_view address) noexcept
-> std::unique_ptr<acceptor> final {
return std::make_unique<posix_mqueue_acceptor>(
*this, to_string(address), _shared_state);
}
/// @brief Makes a connector connecting to queue with the specified name.
auto make_connector(const string_view address) noexcept
-> std::unique_ptr<connection> final {
return std::make_unique<posix_mqueue_connector>(
*this, to_string(address), _shared_state);
}
private:
std::shared_ptr<posix_mqueue_shared_state> _shared_state{
std::make_shared<posix_mqueue_shared_state>()};
void _increase_res_limit() noexcept {
struct rlimit rlim {};
zero(as_bytes(cover_one(rlim)));
rlim.rlim_cur = RLIM_INFINITY;
rlim.rlim_max = RLIM_INFINITY;
errno = 0;
::setrlimit(RLIMIT_MSGQUEUE, &rlim);
}
};
//------------------------------------------------------------------------------
} // namespace eagine::msgbus
#endif // EAGINE_MSGBUS_POSIX_MQUEUE_HPP
| 34.012837 | 87 | 0.585145 | [
"object"
] |
193cd06ed37b7f12d8e7baf2d873390f7982236a | 2,641 | cpp | C++ | SFML_RPG/src/Game.cpp | realjf/SFML_RPG | 51fe895d3e3c75f26fe45c7b3ba145fd3112b212 | [
"Apache-2.0"
] | null | null | null | SFML_RPG/src/Game.cpp | realjf/SFML_RPG | 51fe895d3e3c75f26fe45c7b3ba145fd3112b212 | [
"Apache-2.0"
] | null | null | null | SFML_RPG/src/Game.cpp | realjf/SFML_RPG | 51fe895d3e3c75f26fe45c7b3ba145fd3112b212 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "Game.h"
// static functions
// init functions
// constructor/destructor
Game::Game()
{
initVariables();
initGraphicsSettings();
initWindow();
initKeys();
initStateData();
initStates();
}
Game::~Game()
{
delete m_Window;
while (!m_States.empty())
{
delete m_States.top();
m_States.pop();
}
}
void Game::updateDt()
{
m_Dt = m_DtClock.restart().asSeconds();
//system("cls");
//std::cout << m_Dt << std::endl;
}
void Game::updateSFMLEvents()
{
while (m_Window->pollEvent(m_SfEvent))
{
if (m_SfEvent.type == sf::Event::Closed)
m_Window->close();
}
}
void Game::update()
{
updateSFMLEvents();
if (!m_States.empty())
{
if (m_Window->hasFocus())
{
m_States.top()->update(m_Dt);
if (m_States.top()->getQuit())
{
m_States.top()->endState();
delete m_States.top();
m_States.pop();
}
}
}
// APP END
else
{
endApplication();
m_Window->close();
}
}
void Game::render()
{
m_Window->clear();
// render
if (!m_States.empty())
m_States.top()->render();
m_Window->display();
}
void Game::run()
{
while (m_Window->isOpen())
{
updateDt();
update();
render();
}
}
void Game::endApplication()
{
std::cout << "ending application" << std::endl;
}
void Game::initVariables()
{
m_Window = NULL;
m_Dt = 0.f;
m_GridSize = 64.f;
}
void Game::initGraphicsSettings()
{
m_GfxSettings.loadFromFile("config/graphics.ini");
}
void Game::initWindow()
{
if (m_GfxSettings.m_Fullscreen)
m_Window = new sf::RenderWindow(m_GfxSettings.m_Resolution, m_GfxSettings.m_Title, sf::Style::Fullscreen, m_GfxSettings.m_ContextSettings);
else
m_Window = new sf::RenderWindow(m_GfxSettings.m_Resolution, m_GfxSettings.m_Title, sf::Style::Titlebar | sf::Style::Close, m_GfxSettings.m_ContextSettings);
m_Window->setFramerateLimit(m_GfxSettings.m_FrameRateLimit);
m_Window->setVerticalSyncEnabled(m_GfxSettings.m_VerticalSync);
}
void Game::initStates()
{
m_States.push(new MainMenuState(&m_StateData));
//m_States.push(new GameState(m_Window, &m_SupportedKeys));
}
void Game::initKeys()
{
std::ifstream ifs("config/supported_keys.ini");
if (ifs.is_open())
{
std::string key = "";
int key_value = 0;
while (ifs >> key >> key_value)
{
m_SupportedKeys[key] = key_value;
}
}
ifs.close();
for (auto i : m_SupportedKeys)
{
std::cout << i.first << " " << i.second << std::endl;
}
}
void Game::initStateData()
{
m_StateData.m_Window = m_Window;
m_StateData.m_GfxSettings = &m_GfxSettings;
m_StateData.m_SupportedKeys = &m_SupportedKeys;
m_StateData.m_States = &m_States;
m_StateData.m_GridSize = m_GridSize;
}
| 16.302469 | 158 | 0.671337 | [
"render"
] |
1943704ac0e6c245f005c04d47b5f29fdc6fb5e9 | 1,733 | cpp | C++ | PolyRender/Auto.cpp | pauldoo/scratch | 1c8703d8b8e5cc5a026bfd5f0b036b9632faf161 | [
"0BSD"
] | null | null | null | PolyRender/Auto.cpp | pauldoo/scratch | 1c8703d8b8e5cc5a026bfd5f0b036b9632faf161 | [
"0BSD"
] | 4 | 2021-08-31T22:03:39.000Z | 2022-02-19T07:12:05.000Z | PolyRender/Auto.cpp | pauldoo/scratch | 1c8703d8b8e5cc5a026bfd5f0b036b9632faf161 | [
"0BSD"
] | 1 | 2022-02-23T13:46:49.000Z | 2022-02-23T13:46:49.000Z | #include "stdafx.h"
#include "AutoDeclarations.h"
#include "Auto.h"
#include "Utilities.h"
#include "DestructionAsserter.h"
#include "LinkCount.h"
#include "ColorSolid.h"
#include "TextureMap.h"
#include "Intersect.h"
#include "BumpMap.h"
#include "World.h"
#include "RenderInfo.h"
#include "RenderMask.h"
#include "Light.h"
template <typename Type>
Auto<Type>::Auto() : m_item(NULL)
{
};
template <typename Type>
Auto<Type>::Auto(Type* item) : m_item(item)
{
m_item->IncrementCount();
};
template <typename Type>
Auto<Type>::Auto(const Auto& otherAuto)
: m_item(otherAuto.m_item)
{
m_item->IncrementCount();
};
template <typename Type>
Auto<Type>::~Auto() {
m_item->DecrementCount();
}
template <typename Type>
Type* Auto<Type>::operator->() {
return m_item;
}
template <typename Type>
const Type* Auto<Type>::operator->() const {
return m_item;
}
template <typename Type>
Type* Auto<Type>::Pointer() {
return m_item;
}
template <typename Type>
const Type* Auto<Type>::Pointer() const {
return m_item;
}
template <typename Type>
void Auto<Type>::operator=(Type* item) {
item->IncrementCount();
m_item->DecrementCount();
m_item = item;
}
template class Auto<DestructionAsserter>;
template class Auto<DestructionAsserter const>;
template class Auto<LinkCount>;
template class Auto<LinkCount const>;
template class Auto<Solid const>;
template class Auto<TextureMap const>;
template class Auto<ColorSolid const>;
template class Auto<Intersect const>;
template class Auto<BumpMap const>;
template class Auto<World const>;
template class Auto<RenderInfo const>;
template class Auto<RenderMask const>;
template class Auto<Light const>;
| 21.395062 | 48 | 0.704559 | [
"solid"
] |
194527e9b9d492f3b7699a0e10e4c671a8942e00 | 3,138 | cc | C++ | components/service/ucloud/live/src/model/DescribeMixStreamListRequest.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | components/service/ucloud/live/src/model/DescribeMixStreamListRequest.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | components/service/ucloud/live/src/model/DescribeMixStreamListRequest.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/live/model/DescribeMixStreamListRequest.h>
using AlibabaCloud::Live::Model::DescribeMixStreamListRequest;
DescribeMixStreamListRequest::DescribeMixStreamListRequest() :
RpcServiceRequest("live", "2016-11-01", "DescribeMixStreamList")
{
setMethod(HttpRequest::Method::Post);
}
DescribeMixStreamListRequest::~DescribeMixStreamListRequest()
{}
std::string DescribeMixStreamListRequest::getStartTime()const
{
return startTime_;
}
void DescribeMixStreamListRequest::setStartTime(const std::string& startTime)
{
startTime_ = startTime;
setParameter("StartTime", startTime);
}
std::string DescribeMixStreamListRequest::getAppName()const
{
return appName_;
}
void DescribeMixStreamListRequest::setAppName(const std::string& appName)
{
appName_ = appName;
setParameter("AppName", appName);
}
int DescribeMixStreamListRequest::getPageSize()const
{
return pageSize_;
}
void DescribeMixStreamListRequest::setPageSize(int pageSize)
{
pageSize_ = pageSize;
setParameter("PageSize", std::to_string(pageSize));
}
std::string DescribeMixStreamListRequest::getStreamName()const
{
return streamName_;
}
void DescribeMixStreamListRequest::setStreamName(const std::string& streamName)
{
streamName_ = streamName;
setParameter("StreamName", streamName);
}
std::string DescribeMixStreamListRequest::getMixStreamId()const
{
return mixStreamId_;
}
void DescribeMixStreamListRequest::setMixStreamId(const std::string& mixStreamId)
{
mixStreamId_ = mixStreamId;
setParameter("MixStreamId", mixStreamId);
}
std::string DescribeMixStreamListRequest::getDomainName()const
{
return domainName_;
}
void DescribeMixStreamListRequest::setDomainName(const std::string& domainName)
{
domainName_ = domainName;
setParameter("DomainName", domainName);
}
std::string DescribeMixStreamListRequest::getEndTime()const
{
return endTime_;
}
void DescribeMixStreamListRequest::setEndTime(const std::string& endTime)
{
endTime_ = endTime;
setParameter("EndTime", endTime);
}
long DescribeMixStreamListRequest::getOwnerId()const
{
return ownerId_;
}
void DescribeMixStreamListRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
int DescribeMixStreamListRequest::getPageNo()const
{
return pageNo_;
}
void DescribeMixStreamListRequest::setPageNo(int pageNo)
{
pageNo_ = pageNo;
setParameter("PageNo", std::to_string(pageNo));
}
| 24.325581 | 82 | 0.757808 | [
"model"
] |
194548acf18b4a32cc47f41b0101a6156aa30c39 | 7,287 | cc | C++ | src/animation/offline/collada/collada.cc | nstokes2/ozz-animation | 0b9a1c90398dbc8dc11394fbc93720159db19cc9 | [
"Zlib"
] | null | null | null | src/animation/offline/collada/collada.cc | nstokes2/ozz-animation | 0b9a1c90398dbc8dc11394fbc93720159db19cc9 | [
"Zlib"
] | null | null | null | src/animation/offline/collada/collada.cc | nstokes2/ozz-animation | 0b9a1c90398dbc8dc11394fbc93720159db19cc9 | [
"Zlib"
] | null | null | null | //============================================================================//
// //
// ozz-animation, 3d skeletal animation libraries and tools. //
// https://code.google.com/p/ozz-animation/ //
// //
//----------------------------------------------------------------------------//
// //
// Copyright (c) 2012-2015 Guillaume Blanc //
// //
// This software is provided 'as-is', without any express or implied //
// warranty. In no event will the authors be held liable for any damages //
// arising from the use of this software. //
// //
// Permission is granted to anyone to use this software for any purpose, //
// including commercial applications, and to alter it and redistribute it //
// freely, subject to the following restrictions: //
// //
// 1. The origin of this software must not be misrepresented; you must not //
// claim that you wrote the original software. If you use this software //
// in a product, an acknowledgment in the product documentation would be //
// appreciated but is not required. //
// //
// 2. Altered source versions must be plainly marked as such, and must not be //
// misrepresented as being the original software. //
// //
// 3. This notice may not be removed or altered from any source //
// distribution. //
// //
//============================================================================//
#define OZZ_INCLUDE_PRIVATE_HEADER // Allows to include private headers.
#include "ozz/animation/offline/collada/collada.h"
#include <cassert>
#include "tinyxml.h"
#include "ozz/base/log.h"
#include "ozz/base/memory/allocator.h"
#include "ozz/base/io/stream.h"
#include "ozz/animation/runtime/skeleton.h"
#include "ozz/animation/offline/raw_animation.h"
#include "ozz/animation/offline/raw_skeleton.h"
#include "animation/offline/collada/collada_skeleton.h"
#include "animation/offline/collada/collada_animation.h"
namespace ozz {
namespace animation {
namespace offline {
namespace collada {
namespace {
// Load _filename to memory as a string. Return a valid pointer if read was
// successful, or NULL otherwise. The caller is responsible for deleting the
// return string using default_allocator().Deallocate() function.
char* LoadFileToString(const char* _filename) {
if (!_filename) {
return NULL;
}
log::Log() << "Reads Collada document " << _filename << "." << std::endl;
// Loads file to memory.
char* content = NULL;
io::File file(_filename, "rb");
if (file.opened()) {
// Gets file size.
file.Seek(0, io::Stream::kEnd);
size_t file_length = file.Tell();
file.Seek(0, io::Stream::kSet);
// Allocates and read file.
content = memory::default_allocator()->Allocate<char>(file_length + 1);
content[file_length] = '\0';
if (file.Read(content, file_length) != file_length) {
log::Err() << "Failed to read file " << _filename << "." << std::endl;
memory::default_allocator()->Deallocate(content);
content = NULL;
}
} else {
log::Err() << "Failed to open file " << _filename << "." << std::endl;
}
return content;
}
} // namespace
bool ImportFromFile(const char* _filename, RawSkeleton* _skeleton) {
char* xml = LoadFileToString(_filename);
// Import xml from memory even if load from file has failed. ImportFromMemory
// supports NULL argument and will fill output.
bool success = ImportFromMemory(xml, _skeleton);
memory::default_allocator()->Deallocate(xml);
return success;
}
bool ParseDocument(TiXmlDocument* _doc, const char* _xml) {
if (!_doc || !_xml) {
return false;
}
_doc->Parse(_xml);
if (_doc->Error()) {
log::Err() << "Failed to parse xml document";
if (_doc->ErrorRow()) {
log::Err() << " (line " << _doc->ErrorRow();
}
if (_doc->ErrorCol()) {
log::Err() << " column " << _doc->ErrorCol() << ")";
}
log::Err() << ":" << _doc->ErrorDesc() << std::endl;
return false;
}
log::Log() << "Successfully parsed xml document." << std::endl;
return true;
}
bool ImportFromMemory(const char* _xml, RawSkeleton* _skeleton) {
if (!_skeleton) {
return false;
}
// Reset skeleton.
*_skeleton = RawSkeleton();
// Opens the document.
TiXmlDocument doc;
if (!ParseDocument(&doc, _xml)) {
return false;
}
SkeletonVisitor skeleton_visitor;
if (!doc.Accept(&skeleton_visitor)) {
log::Err() << "Collada skeleton parsing failed." << std::endl;
return false;
}
if (!ExtractSkeleton(skeleton_visitor, _skeleton)) {
log::Err() << "Collada skeleton extraction failed." << std::endl;
return false;
}
return true;
}
bool ImportFromFile(const char* _filename,
const Skeleton& _skeleton,
float _sampling_rate,
RawAnimation* _animation) {
char* xml = LoadFileToString(_filename);
// Import xml from memory even if load from file has failed. ImportFromMemory
// supports NULL argument and will fill output.
bool success = ImportFromMemory(xml, _skeleton, _sampling_rate, _animation);
memory::default_allocator()->Deallocate(xml);
return success;
}
bool ImportFromMemory(const char* _xml,
const Skeleton& _skeleton,
float _sampling_rate,
RawAnimation* _animation) {
(void)_sampling_rate;
if (!_animation) {
return false;
}
// Reset animation.
*_animation = RawAnimation();
// Opens the document.
TiXmlDocument doc;
if (!ParseDocument(&doc, _xml)) {
return false;
}
// Extracts skeletons from the Collada document.
SkeletonVisitor skeleton_visitor;
if (!doc.Accept(&skeleton_visitor)) {
log::Err() << "Collada skeleton parsing failed." << std::endl;
return false;
}
// Extracts animations from the Collada document.
AnimationVisitor animation_visitor;
if (!doc.Accept(&animation_visitor)) {
log::Err() << "Collada animation import failed." << std::endl;
return false;
}
// Allocates RawAnimation.
if (!ExtractAnimation(animation_visitor,
skeleton_visitor,
_skeleton,
_animation)) {
log::Err() << "Collada animation extraction failed." << std::endl;
return false;
}
return true;
}
} // collada
} // offline
} // animation
} // ozz
| 35.033654 | 80 | 0.543571 | [
"3d"
] |
194a1c093c5512830519d290e2553702349fa132 | 2,600 | cc | C++ | code/render/visibility/visibilitysortjob.cc | Nechrito/nebula | 6c7ef27ab1374d3f751d866500729524f72a0c87 | [
"BSD-2-Clause"
] | null | null | null | code/render/visibility/visibilitysortjob.cc | Nechrito/nebula | 6c7ef27ab1374d3f751d866500729524f72a0c87 | [
"BSD-2-Clause"
] | null | null | null | code/render/visibility/visibilitysortjob.cc | Nechrito/nebula | 6c7ef27ab1374d3f751d866500729524f72a0c87 | [
"BSD-2-Clause"
] | null | null | null | //------------------------------------------------------------------------------
// visibilitysortjob.cc
// (C) 2018-2020 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "render/stdneb.h"
#include "jobs/jobs.h"
#include "visibilitycontext.h"
#include "models/modelcontext.h"
#include "models/nodes/shaderstatenode.h"
namespace Visibility
{
//------------------------------------------------------------------------------
/**
*/
void
VisibilitySortJob(const Jobs::JobFuncContext& ctx)
{
ObserverContext::VisibilityDrawList* buckets = (ObserverContext::VisibilityDrawList*)ctx.outputs[0];
Memory::ArenaAllocator<1024>* packetAllocator = (Memory::ArenaAllocator<1024>*)ctx.uniforms[0];
bool* results = (bool*)ctx.inputs[0];
Graphics::ContextEntityId* entities = (Graphics::ContextEntityId*)ctx.inputs[1];
// begin adding buckets
buckets->BeginBulkAdd();
// calculate amount of models
uint32 numModels = ctx.inputSizes[0] / sizeof(bool);
uint32 i;
for (i = 0; i < numModels; i++)
{
// get model instance
const Models::ModelId model = Models::ModelContext::GetModel(entities[i]);
const Util::Array<Models::ModelNode::Instance*>& nodes = Models::ModelContext::GetModelNodeInstances(entities[i]);
const Util::Array<Models::NodeType>& types = Models::ModelContext::GetModelNodeTypes(entities[i]);
bool result = results[i];
IndexT j;
if (result) for (j = 0; j < nodes.Size(); j++)
{
Models::ModelNode::Instance* const inst = nodes[j];
// only treat renderable nodes
if (types[j] >= Models::NodeHasShaderState)
{
Models::ShaderStateNode::Instance* const shdNodeInst = reinterpret_cast<Models::ShaderStateNode::Instance*>(inst);
Models::ShaderStateNode* const shdNode = reinterpret_cast<Models::ShaderStateNode*>(inst->node);
auto& bucket = buckets->AddUnique(shdNode->materialType);
if (!bucket.IsBulkAdd())
bucket.BeginBulkAdd();
// add an array if non existant, or return reference to one if it exists
auto& draw = bucket.AddUnique(inst->node);
// allocate memory for draw packet
void* mem = packetAllocator->Alloc(shdNodeInst->GetDrawPacketSize());
// update packet and add to list
Models::ModelNode::DrawPacket* packet = shdNodeInst->UpdateDrawPacket(mem);
draw.Append(packet);
}
}
}
// end adding inner buckets
auto it = buckets->Begin();
while (it != buckets->End())
{
if (it.val->IsBulkAdd())
it.val->EndBulkAdd();
it++;
}
// end adding buckets
buckets->EndBulkAdd();
}
} // namespace Visibility
| 32.5 | 118 | 0.641154 | [
"render",
"model"
] |
194d3002b879312f2270841b0bb9ac8722341679 | 3,396 | cxx | C++ | smtk/bridge/cgm/ImportSolid.cxx | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | null | null | null | smtk/bridge/cgm/ImportSolid.cxx | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | 4 | 2016-11-10T15:49:51.000Z | 2017-02-06T23:24:16.000Z | smtk/bridge/cgm/ImportSolid.cxx | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | null | null | null | //=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#include "smtk/bridge/cgm/ImportSolid.h"
#include "smtk/bridge/cgm/Session.h"
#include "smtk/bridge/cgm/CAUUID.h"
#include "smtk/bridge/cgm/Engines.h"
#include "smtk/bridge/cgm/TDUUID.h"
#include "smtk/model/CellEntity.h"
#include "smtk/model/Group.h"
#include "smtk/model/Model.h"
#include "smtk/model/Manager.h"
#include "smtk/common/UUID.h"
#include "CGMApp.hpp"
#include "DagType.hpp"
#include "CubitAttribManager.hpp"
#include "CubitCompat.hpp"
#include "CubitDefines.h"
#include "DLIList.hpp"
#include "InitCGMA.hpp"
#include "GeometryModifyTool.hpp"
#include "GeometryQueryEngine.hpp"
#include "GeometryQueryTool.hpp"
#include "RefEntity.hpp"
#include "RefEntityFactory.hpp"
#include "RefGroup.hpp"
#include <map>
using namespace smtk::model;
namespace smtk {
namespace bridge {
namespace cgm {
smtk::common::UUIDArray ImportSolid::fromFilenameIntoManager(
const std::string& filename,
const std::string& filetype,
smtk::model::ManagerPtr manager)
{
smtk::common::UUIDArray result;
smtk::bridge::cgm::CAUUID::registerWithAttributeManager();
std::string engine = "OCC";
if (filetype == "FACET_TYPE") engine = "FACET";
else if (filetype == "ACIS_SAT") engine = "ACIS";
if (!Engines::setDefault(engine))
{
std::cerr << "Could not set default engine to \"" << engine << "\"\n";
return result;
}
std::cout << "Default modeler now \"" << GeometryQueryTool::instance()->get_gqe()->modeler_type() << "\"\n";
CubitStatus s;
DLIList<RefEntity*> imported;
int prevAutoFlag = CGMApp::instance()->attrib_manager()->auto_flag();
CGMApp::instance()->attrib_manager()->auto_flag(CUBIT_TRUE);
s = CubitCompat_import_solid_model(
filename.c_str(),
filetype.c_str(),
/*logfile_name*/ NULL,
/*heal_step*/ CUBIT_TRUE,
/*import_bodies*/ CUBIT_TRUE,
/*import_surfaces*/ CUBIT_TRUE,
/*import_curves*/ CUBIT_TRUE,
/*import_vertices*/ CUBIT_TRUE,
/*free_surfaces*/ CUBIT_TRUE,
&imported
);
CGMApp::instance()->attrib_manager()->auto_flag(prevAutoFlag);
if (s != CUBIT_SUCCESS)
{
std::cerr << "Failed to import CGM model, status " << s << "\n";
return result;
}
Session::Ptr session = Session::create();
std::string modelName = filename.substr(0, filename.find_last_of("."));
int ne = static_cast<int>(imported.size());
result.reserve(ne);
for (int i = 0; i < ne; ++i)
{
RefEntity* entry = imported.get_and_step();
smtk::bridge::cgm::TDUUID* refId = smtk::bridge::cgm::TDUUID::ofEntity(entry, true);
smtk::common::UUID entId = refId->entityId();
EntityRef smtkEntry(manager, entId);
if (session->transcribe(smtkEntry, SESSION_EVERYTHING, false))
result.push_back(smtkEntry.entity());
}
// FIXME: Until this is implemented, Session will be deleted upon exit:
//manager->addSession(session);
imported.reset();
return result;
}
} // namespace cgm
} //namespace bridge
} // namespace smtk
| 31.444444 | 110 | 0.662839 | [
"model"
] |
1958e4557f9dcc9ecb9eae395b7b51e1afb964ea | 3,192 | hpp | C++ | yprocessing.hpp | frenchraccoon/whyparser | 5e8211a2d2e81b79041ff7784fac1b851a5dd533 | [
"BSD-2-Clause"
] | null | null | null | yprocessing.hpp | frenchraccoon/whyparser | 5e8211a2d2e81b79041ff7784fac1b851a5dd533 | [
"BSD-2-Clause"
] | null | null | null | yprocessing.hpp | frenchraccoon/whyparser | 5e8211a2d2e81b79041ff7784fac1b851a5dd533 | [
"BSD-2-Clause"
] | null | null | null | /**
* YCombinator Main Parser Logic.
* Specialization of mapped records parser to extract hacker news logs stats
* Copyright (C) 2018 Xavier Roche (http://www.httrack.com/)
* All rights reserved.
* License: http://opensource.org/licenses/BSD-2-Clause
**/
#ifndef RX_YPROCESSING_HPP
#define RX_YPROCESSING_HPP
#include <string.h>
#include <strings.h>
#include <getopt.h>
#include <assert.h>
#include <limits>
#include <iostream>
#include "yrequest.hpp"
#include "refstringmap.hpp"
/**
* Specialization of mapped records parser to extract hacker news logs stats
**/
class YParser: protected MappedRecords<WhyRequest> {
public:
/**
* Constructor.
*
* @param filename The path of the record fiel to open.
**/
YParser(const char* filename):
MappedRecords<WhyRequest>(filename),
wordMap(),
from(0),
to(std::numeric_limits<time_t>::max()),
fast_seek(true),
jitter(900)
{
}
/**
* Was the file correctly opened ?
*
* @return @c true If the file was opened successfully
**/
bool is_valid() const {
return MappedRecords<WhyRequest>::is_valid();
}
/**
* Get the last error number encountered if the file could not be opened.
**/
int get_error() const {
return MappedRecords<WhyRequest>::get_error();
}
/**
* Enable or disable fast file seek (using binary search)
*
* @param enabled If @c true, enable fast seek
* @param jitter_s The jitter time, in seconds, to locate the start point
* @comment This function can only be called before @c parse_records
**/
void set_fast_seek(bool enabled, time_t jitter_s = 900) {
fast_seek = enabled;
jitter = jitter_s;
}
/**
* Set the range start
*
* @param timestamp The start range (seconds since Epoch)
* @comment This function can only be called before @c parse_records
**/
void set_start(time_t timestamp) {
from = timestamp;
}
/**
* Set the range end
*
* @param timestamp The ending range (seconds since Epoch)
* @comment This function can only be called before @c parse_records
**/
void set_end(time_t timestamp) {
to = timestamp;
}
/**
* Parse all requested records. The @c set_start, @c set_end, and
* @c set_fast_seek function must not be called afterwards.
**/
void parse_records();
/**
* Get the number of distinct queries.
*
* @comment This function can only be called after @c parse_records
**/
size_t get_distinct_queries() const;
/**
* Get the top queries.
*
* @param top_queries The maximum number of top queries to retreive
* @return The list of top queries, sorted in descending order
* @comment This function can only be called after @c parse_records
**/
std::vector<std::pair<RefString, unsigned>> get_top_queries(size_t top_queries = 10) const;
protected:
// hashmap (unordered map) of RefString (ie. small string objects
// referencing mapped memory bytes) to count unique queries
RefStringUnorderedHashMap<unsigned> wordMap;
// Start timestamp
time_t from;
// End timestamp
time_t to;
// Enable fast-seek
bool fast_seek;
// Jitter for loosely ordered file
time_t jitter;
};
#endif
| 24.181818 | 93 | 0.681078 | [
"vector"
] |
1968992a1b47b9e685b7b137848df8fb5b717f9b | 3,138 | cpp | C++ | src/sensor_factory.cpp | trazfr/alarm | ea511eb0f16945de2005d828f452c76fce9d77e7 | [
"MIT"
] | null | null | null | src/sensor_factory.cpp | trazfr/alarm | ea511eb0f16945de2005d828f452c76fce9d77e7 | [
"MIT"
] | null | null | null | src/sensor_factory.cpp | trazfr/alarm | ea511eb0f16945de2005d828f452c76fce9d77e7 | [
"MIT"
] | null | null | null | #include "sensor_factory.hpp"
#include "sensor.hpp"
#include "sensor_iio.hpp"
#include "sensor_thermal.hpp"
#include <algorithm>
#include <cstring>
#include <numeric>
#include <ostream>
#include <vector>
namespace
{
constexpr size_t sumSize()
{
return 0;
}
template <typename... Params>
size_t sumSize(const std::vector<std::unique_ptr<Sensor>> &sensors, const Params &... others)
{
return sensors.size() + sumSize(others...);
}
void pushBack(std::vector<std::unique_ptr<Sensor>> &)
{
}
template <typename... Params>
void pushBack(std::vector<std::unique_ptr<Sensor>> &result, std::vector<std::unique_ptr<Sensor>> &&sensors, Params &&... others)
{
for (auto &sensor : sensors)
{
result.push_back(std::move(sensor));
}
pushBack(result, std::forward<Params>(others)...);
}
/**
* Concatenate all the next std::vector<> into the 1st one
*/
template <typename... Params>
std::vector<std::unique_ptr<Sensor>> concat(std::vector<std::unique_ptr<Sensor>> result, Params &&... params)
{
result.reserve(result.size() + sumSize(params...));
pushBack(result, std::forward<Params>(params)...);
std::sort(result.begin(), result.end(),
[](const auto &first, const auto &second) { return std::strcmp(first->getName(), second->getName()) < 0; });
return result;
}
void print(std::ostream &str, const std::vector<std::unique_ptr<Sensor>> &sensors, const char *name)
{
str << " - " << name << " sensors (" << sensors.size() << "):\n";
for (const auto &sensor : sensors)
{
str << " - " << sensor->getName() << '\n';
}
}
} // namespace
struct SensorFactory::Impl
{
std::vector<std::unique_ptr<Sensor>> temperature;
std::vector<std::unique_ptr<Sensor>> humidity;
std::vector<std::unique_ptr<Sensor>> *get(SensorFactory::Type type)
{
switch (type)
{
case SensorFactory::Type::Temperature:
return &temperature;
case SensorFactory::Type::Humidity:
return &humidity;
default:
break;
}
return nullptr;
}
};
SensorFactory::SensorFactory()
: pimpl{std::make_unique<Impl>()}
{
pimpl->temperature = concat(SensorThermal::create(), SensorIio::create("temp"));
pimpl->humidity = concat(SensorIio::create("humidityrelative"));
}
SensorFactory::~SensorFactory() = default;
size_t SensorFactory::getSize(Type type) const
{
if (const auto sensors = pimpl->get(type))
{
return sensors->size();
}
return 0;
}
Sensor *SensorFactory::get(Type type, size_t sensorNumber)
{
if (const auto sensors = pimpl->get(type))
{
if (sensorNumber < sensors->size())
{
return (*sensors)[sensorNumber].get();
}
}
return nullptr;
}
const Sensor *SensorFactory::get(Type type, size_t sensorNumber) const
{
return const_cast<SensorFactory *>(this)->get(type, sensorNumber);
}
std::ostream &SensorFactory::toStream(std::ostream &str) const
{
str << "Sensors found:\n";
print(str, pimpl->temperature, "temperature");
print(str, pimpl->humidity, "humidity");
return str;
}
| 24.904762 | 128 | 0.632887 | [
"vector"
] |
196934035c0a285c4173203be609e7b225d1dd11 | 3,869 | cpp | C++ | test/src/tracking/multi_tracker_test.cpp | PPokorski/laser_object_tracker | bc967459218b417c7e0e97603464e77f110e25ef | [
"BSD-3-Clause"
] | 14 | 2019-08-05T04:00:58.000Z | 2022-03-24T02:15:23.000Z | test/src/tracking/multi_tracker_test.cpp | PPokorski/laser_object_tracker | bc967459218b417c7e0e97603464e77f110e25ef | [
"BSD-3-Clause"
] | null | null | null | test/src/tracking/multi_tracker_test.cpp | PPokorski/laser_object_tracker | bc967459218b417c7e0e97603464e77f110e25ef | [
"BSD-3-Clause"
] | 5 | 2020-03-11T12:09:45.000Z | 2021-11-09T12:33:32.000Z | /*********************************************************************
*
* BSD 3-Clause License
*
* Copyright (c) 2019, Piotr Pokorski
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include "laser_object_tracker/tracking/multi_tracker.hpp"
#include "test/utils.hpp"
#include "test/data_association/mocks.hpp"
#include "test/tracking/mocks.hpp"
TEST(MultiTrackerTest, UpdateAndInitializeTracksTest) {
auto data_association = std::make_unique<test::MockDataAssociation>();
auto tracking = std::make_unique<test::MockTracking>();
auto tracker_rejection = std::make_unique<test::MockTrackerRejection>();
laser_object_tracker::tracking::MultiTracker multi_tracker(
[](const auto& lhs, const auto& rhs) {return 0.0;},
std::move(data_association),
std::move(tracking),
std::move(tracker_rejection));
static constexpr int NO_ASSIGNMENT = laser_object_tracker::data_association::BaseDataAssociation::NO_ASSIGNMENT;
std::vector<Eigen::VectorXd> measurements;
Eigen::VectorXi assignment_vector;
measurements.resize(5);
assignment_vector.setConstant(5, NO_ASSIGNMENT);
multi_tracker.updateAndInitializeTracks(measurements, assignment_vector);
ASSERT_EQ(5, multi_tracker.size());
// All objects should be unique (with respect to pointer)
for (auto it_1 = multi_tracker.begin(); it_1 != multi_tracker.end(); ++it_1) {
for (auto it_2 = std::next(it_1); it_2 != multi_tracker.end(); ++it_2) {
EXPECT_NE(*it_1, *it_2);
}
}
measurements.resize(3);
assignment_vector.setConstant(3, NO_ASSIGNMENT);
multi_tracker.updateAndInitializeTracks(measurements, assignment_vector);
ASSERT_EQ(8, multi_tracker.size());
// All objects should be unique (with respect to pointer)
for (auto it_1 = multi_tracker.begin(); it_1 != multi_tracker.end(); ++it_1) {
for (auto it_2 = std::next(it_1); it_2 != multi_tracker.end(); ++it_2) {
EXPECT_NE(*it_1, *it_2);
}
}
measurements.resize(8);
assignment_vector.resize(8);
assignment_vector << 0, 1, 2, 3, 4, 5, 6, 7;
for (const auto& tracker : multi_tracker) {
auto& cast_tracker = dynamic_cast<test::MockTracking&>(*tracker);
EXPECT_CALL(cast_tracker, update(testing::_));
}
multi_tracker.updateAndInitializeTracks(measurements, assignment_vector);
}
| 43.47191 | 114 | 0.719307 | [
"vector"
] |
19732c52b4579e68c2a56c59e020c9fb7906fabc | 4,062 | cpp | C++ | tests/io_test.cpp | gnieradk/oneSolver | cd04c51ac3e63e7e091acb496c2f568410a0af56 | [
"MIT"
] | 1 | 2021-09-30T13:27:38.000Z | 2021-09-30T13:27:38.000Z | tests/io_test.cpp | gnieradk/oneSolver | cd04c51ac3e63e7e091acb496c2f568410a0af56 | [
"MIT"
] | null | null | null | tests/io_test.cpp | gnieradk/oneSolver | cd04c51ac3e63e7e091acb496c2f568410a0af56 | [
"MIT"
] | 5 | 2020-12-23T12:36:41.000Z | 2022-02-21T08:35:16.000Z | /*! file io_test.cpp
*
* @copyright Licensed under MIT license by hyperQ – Ewa Hendzel
*
*/
#include "model/qubo.hpp"
#include "model/solution.hpp"
#include <boost/test/data/test_case.hpp>
#include <boost/test/unit_test.hpp>
#include <sstream>
const std::string
qubo_file_contents("c qubo Target MaxNodes NumNodes NumLinks\n"
"p qubo 0 100 2 2\n"
"c comment\n"
"0 0 -0.5\n"
"0 1 2.0\n"
"1 2 4\n"
"2 2 -0.7\n");
const std::string grammatically_incorrect_file_contents[]{
std::string("p qubo 0 1 100 3 492\n"
"0 0 -0.5\n"
"0 1 2.0\n"),
std::string("p qubo 0 100 3 492\n"
"0 0 1 -0.5\n"
"0 1 2.0\n"),
std::string("p qubo 0 100 3 492\n"
"0 0 -0.5\n"
"0 2.0\n"),
std::string("p qubo 0 100 492\n"
"0 0 -0.5\n"
"0 1 2.0\n"),
std::string("p qubo 0 100 3 492\n"
"0 0 -0.5\n"
"unexpected string\n"
"0 1 2.0\n")};
BOOST_AUTO_TEST_SUITE(io_test)
BOOST_AUTO_TEST_CASE(number_of_variable_agrees_with_given_in_input_stream) {
std::stringstream stream(qubo_file_contents);
stream.unsetf(std::ios::skipws);
qubo::QUBOModel<int, double> problem =
qubo::QUBOModel<int, double>::load(stream);
BOOST_TEST_REQUIRE(problem.get_nodes() == 3);
}
BOOST_AUTO_TEST_CASE(all_linear_coefficients_are_present_in_the_model) {
std::stringstream stream(qubo_file_contents);
stream.unsetf(std::ios::skipws);
qubo::QUBOModel<int, double> problem =
qubo::QUBOModel<int, double>::load(stream);
BOOST_TEST_REQUIRE(problem.get_variable(0) == -0.5);
BOOST_TEST_REQUIRE(problem.get_variable(2) == -0.7);
}
BOOST_AUTO_TEST_CASE(all_quadratic_coefficients_are_present_in_the_model) {
std::stringstream stream(qubo_file_contents);
stream.unsetf(std::ios::skipws);
qubo::QUBOModel<int, double> problem =
qubo::QUBOModel<int, double>::load(stream);
BOOST_TEST_REQUIRE(problem.get_connection(std::pair(0, 1)) == 2.0);
BOOST_TEST_REQUIRE(problem.get_connection(std::pair(1, 2)) == 4.0);
}
BOOST_AUTO_TEST_CASE(
read_qubo_throws_if_interaction_is_placed_in_reversed_order) {
std::string invalid_qubo_file_contents("p qubo 0 100 2 2\n"
"0 0 -0.5\n"
"1 0 2.0\n"
"1 2 4\n"
"2 2 -0.7\n");
std::stringstream stream(invalid_qubo_file_contents);
stream.unsetf(std::ios::skipws);
BOOST_CHECK_THROW((qubo::QUBOModel<int, double>::load(stream)),
std::invalid_argument);
}
BOOST_DATA_TEST_CASE(read_qubo_throws_if_stream_contents_dont_adhere_to_grammar,
grammatically_incorrect_file_contents) {
std::stringstream stream(sample);
stream.unsetf(std::ios::skipws);
BOOST_CHECK_THROW((qubo::QUBOModel<int, double>::load(stream)),
std::invalid_argument);
}
BOOST_AUTO_TEST_CASE(number_of_quadratic_terms_is_equal_to_the_declared_one) {
std::string invalid_qubo_file_contents("p qubo 0 100 3 3\n"
"0 0 -0.5\n"
"0 1 2.0\n"
"1 2 4\n"
"2 2 -0.7\n");
std::stringstream stream(invalid_qubo_file_contents);
stream.unsetf(std::ios::skipws);
BOOST_CHECK_THROW((qubo::QUBOModel<int, double>::load(stream)),
std::invalid_argument);
}
BOOST_AUTO_TEST_CASE(saved_solution_has_correct_structure) {
char state[] = {0, 1, 1, 0, 1};
qubo::Solution solution(state, state + 5, -12.5);
std::string expected_output = "0,1,2,3,4,energy\n0,1,1,0,1,-12.5\n";
std::stringstream stream("");
solution.save(stream);
BOOST_TEST_REQUIRE(stream.str() == expected_output);
}
BOOST_AUTO_TEST_SUITE_END()
| 33.570248 | 80 | 0.590596 | [
"model"
] |
197f2ec0a22d0f5e51b6ef23061b6e67b3d7fd2f | 831 | cpp | C++ | solutions/604.design-compressed-string-iterator.326214775.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/604.design-compressed-string-iterator.326214775.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/604.design-compressed-string-iterator.326214775.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | class StringIterator {
string s;
int i;
char c = ' ';
int count = 0;
public:
StringIterator(string compressedString) : s(compressedString), i(0) {
_set();
}
void _set() {
if (count > 0)
return;
if (i >= s.size()) {
c = ' ';
return;
}
while (count == 0 && i < s.size()) {
c = s[i++];
count = 0;
while (i < s.size() && isdigit(s[i]))
count = count * 10 + s[i++] - '0';
}
if (count == 0) {
c = ' ';
}
}
char next() {
char r = c;
count--;
_set();
return r;
}
bool hasNext() { return count > 0; }
};
/**
* Your StringIterator object will be instantiated and called as such:
* StringIterator* obj = new StringIterator(compressedString);
* char param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
| 16.62 | 71 | 0.499398 | [
"object"
] |
198038b3e332094f60bd6deae39334be08c696fa | 990 | hh | C++ | geometry/spatial/interpolator.hh | jpanikulam/experiments | be36319a89f8baee54d7fa7618b885edb7025478 | [
"MIT"
] | 1 | 2019-04-14T11:40:28.000Z | 2019-04-14T11:40:28.000Z | geometry/spatial/interpolator.hh | jpanikulam/experiments | be36319a89f8baee54d7fa7618b885edb7025478 | [
"MIT"
] | 5 | 2018-04-18T13:54:29.000Z | 2019-08-22T20:04:17.000Z | geometry/spatial/interpolator.hh | jpanikulam/experiments | be36319a89f8baee54d7fa7618b885edb7025478 | [
"MIT"
] | 1 | 2018-12-24T03:45:47.000Z | 2018-12-24T03:45:47.000Z | #pragma once
#include "eigen.hh"
#include "util/optional.hh"
namespace geometry {
namespace spatial {
struct ControlPoint {
double parameter;
jcc::Vec3 value;
};
// Return a sorted vector of control points
std::vector<ControlPoint> sort_control_points(const std::vector<ControlPoint>& points);
class Interpolator {
public:
jcc::Optional<jcc::Vec3> interpolate(const double t) const {
return (*this)(t);
}
virtual jcc::Optional<jcc::Vec3> operator()(const double t) const = 0;
virtual std::size_t count_between(const double start, const double end) const = 0;
};
class LinearInterpolator final : public Interpolator {
public:
LinearInterpolator(const std::vector<ControlPoint>& control_points);
jcc::Optional<jcc::Vec3> operator()(const double t) const override;
std::size_t count_between(const double start, const double end) const override;
private:
const std::vector<ControlPoint> control_points_;
};
} // namespace spatial
} // namespace geometry
| 24.146341 | 87 | 0.739394 | [
"geometry",
"vector"
] |
19810fb90f35011ebfa83c8d1030009eac8b3ef0 | 1,750 | cpp | C++ | src/editor/AssetListRequest.cpp | CronosTs/phobos3d | c0336456d946f3a9e62fb9b7815831ad32820da5 | [
"Zlib"
] | 2 | 2015-01-14T20:20:51.000Z | 2015-09-08T15:49:18.000Z | src/editor/AssetListRequest.cpp | CronosTs/phobos3d | c0336456d946f3a9e62fb9b7815831ad32820da5 | [
"Zlib"
] | null | null | null | src/editor/AssetListRequest.cpp | CronosTs/phobos3d | c0336456d946f3a9e62fb9b7815831ad32820da5 | [
"Zlib"
] | 1 | 2015-11-03T13:58:58.000Z | 2015-11-03T13:58:58.000Z | #include "Phobos/Editor/AssetListRequest.h"
#include "Phobos/Editor/RequestFactory.h"
#include <Phobos/Register/Hive.h>
#include <Phobos/Register/Manager.h>
#include <Phobos/Register/Table.h>
#include <Phobos/Game/Things/Keys.h>
#include <OgreResourceGroupManager.h>
#include <JsonCreator/Object.h>
#include <JsonCreator/StringWriter.h>
namespace Phobos
{
namespace Editor
{
PH_FULL_REQUEST_CREATOR("AssetList", AssetListRequest);
}
}
Phobos::Editor::AssetListRequest::AssetListRequest(const rapidjson::Value &value):
Request(value)
{
//empty
}
void Phobos::Editor::AssetListRequest::OnExecute(JsonCreator::StringWriter &response)
{
{
auto obj = JsonCreator::MakeObject(response);
obj.AddStringValue("command", "AssetListResponse");
{
auto assetArray = obj.AddArray("assets");
Ogre::StringVectorPtr pList = Ogre::ResourceGroupManager::getSingleton().findResourceNames("PH_GameData","*.mesh",false);
for(Ogre::StringVector::iterator it = pList->begin(), end = pList->end(); it != end;++it)
{
auto assetObj = assetArray.AddObject();
assetObj.AddStringValue("name", it->c_str());
assetObj.AddStringValue("category", "static");
assetObj.AddStringValue("type", "static");
}
const auto &hive = Register::GetHive(PH_ENTITY_DEF_HIVE);
for(auto it : hive)
{
auto table = static_cast<Register::Table *>(it.second);
auto assetObj = assetArray.AddObject();
auto strCategory = table->TryGetString("category");
auto category = strCategory ? strCategory->c_str() : "entity";
assetObj.AddStringValue("name", table->GetName().c_str());
assetObj.AddStringValue("category", category);
assetObj.AddStringValue("type", "entity");
}
}
}
}
| 25 | 127 | 0.700571 | [
"mesh",
"object"
] |
1981bc852cea40614fa23740dcf4f5abbcd42d31 | 4,826 | cpp | C++ | src/gamebase/src/impl/tools/ObjectsSelector.cpp | TheMrButcher/opengl_lessons | 76ac96c45773a54a85d49c6994770b0c3496303f | [
"MIT"
] | 1 | 2016-10-25T21:15:16.000Z | 2016-10-25T21:15:16.000Z | src/gamebase/src/impl/tools/ObjectsSelector.cpp | TheMrButcher/gamebase | 76ac96c45773a54a85d49c6994770b0c3496303f | [
"MIT"
] | 375 | 2016-06-04T11:27:40.000Z | 2019-04-14T17:11:09.000Z | src/gamebase/src/impl/tools/ObjectsSelector.cpp | TheMrButcher/gamebase | 76ac96c45773a54a85d49c6994770b0c3496303f | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2018 Slavnejshev Filipp
* This file is licensed under the terms of the MIT license.
*/
#include <stdafx.h>
#include <gamebase/impl/tools/ObjectsSelector.h>
#include <gamebase/impl/serial/ISerializer.h>
#include <gamebase/impl/serial/IDeserializer.h>
namespace gamebase { namespace impl {
ObjectsSelector::ObjectsSelector(const IPositionable* position)
: Drawable(position)
, m_position(position)
, m_currentObjectID(-1)
{}
void ObjectsSelector::insertObject(int id, const std::shared_ptr<IObject>& object)
{
{
auto& value = m_objects[id];
if (value && m_registerBuilder)
m_register.remove(value.get());
value = object;
}
auto& objDesc = m_objDescs[id];
if (auto positionable = dynamic_cast<IPositionable*>(object.get()))
objDesc.positionable = positionable;
if (auto drawable = dynamic_cast<IDrawable*>(object.get()))
objDesc.drawable = drawable;
if (auto findable = dynamic_cast<IFindable*>(object.get()))
objDesc.findable = findable;
if (m_registerBuilder)
m_registerBuilder->registerObject(object.get());
}
void ObjectsSelector::removeObject(int id)
{
if (m_currentObjectID == id)
m_currentObjectID = -1;
auto it = m_objects.find(id);
if (it == m_objects.end())
return;
m_register.remove(it->second.get());
m_objects.erase(it);
m_objDescs.erase(id);
}
void ObjectsSelector::clear()
{
m_objects.clear();
m_objDescs.clear();
m_register.clear();
m_currentObjectID = -1;
}
void ObjectsSelector::select(int id)
{
m_currentObjectID = id;
}
std::shared_ptr<IObject> ObjectsSelector::findChildByPoint(const Vec2& point) const
{
if (!isVisible())
return nullptr;
Vec2 transformedPoint = m_position ? m_position->position().inversed() * point : point;
auto it = m_objDescs.find(m_currentObjectID);
if (it != m_objDescs.end()) {
auto* findable = it->second.findable;
if (!findable)
return nullptr;
if (auto obj = findable->findChildByPoint(transformedPoint))
return obj;
if (findable->isSelectableByPoint(transformedPoint))
return m_objects.at(it->first);
}
return nullptr;
}
IScrollable* ObjectsSelector::findScrollableByPoint(const Vec2& point)
{
if (!isVisible())
return nullptr;
Vec2 transformedPoint = m_position ? m_position->position().inversed() * point : point;
auto it = m_objDescs.find(m_currentObjectID);
if (it != m_objDescs.end()) {
auto* findable = it->second.findable;
if (!findable)
return nullptr;
if (auto obj = findable->findScrollableByPoint(transformedPoint))
return obj;
}
return nullptr;
}
void ObjectsSelector::loadResources()
{
for (auto it = m_objDescs.begin(); it != m_objDescs.end(); ++it)
it->second.drawable->loadResources();
}
void ObjectsSelector::drawAt(const Transform2& position) const
{
auto it = m_objDescs.find(m_currentObjectID);
if (it != m_objDescs.end())
it->second.drawable->draw(position);
}
void ObjectsSelector::setBox(const BoundingBox& allowedBox)
{
for (auto it = m_objDescs.begin(); it != m_objDescs.end(); ++it)
it->second.drawable->setBox(allowedBox);
}
BoundingBox ObjectsSelector::box() const
{
BoundingBox result;
for (auto it = m_objDescs.begin(); it != m_objDescs.end(); ++it) {
if (it->second.drawable) {
auto box = it->second.drawable->box();
if (it->second.positionable)
box.transform(it->second.positionable->position());
result.add(box);
}
}
return result;
}
void ObjectsSelector::registerObject(PropertiesRegisterBuilder* builder)
{
m_registerBuilder.reset(new PropertiesRegisterBuilder(*builder));
for (auto it = m_objects.begin(); it != m_objects.end(); ++it)
builder->registerObject(it->second.get());
builder->registerPropertyWithSetter("cur", &m_currentObjectID,
[this](int id) { select(id); });
}
void ObjectsSelector::serialize(Serializer& s) const
{
s << "objects" << m_objects << "currentID" << m_currentObjectID;
}
std::unique_ptr<IObject> deserializeObjectsSelector(Deserializer& deserializer)
{
std::unique_ptr<ObjectsSelector> result(new ObjectsSelector());
deserializeObjectsSelectorElements(deserializer, result.get());
return std::move(result);
}
REGISTER_CLASS(ObjectsSelector);
void deserializeObjectsSelectorElements(
Deserializer& deserializer, ObjectsSelector* obj)
{
typedef std::map<int, std::shared_ptr<IObject>> IdToObj;
DESERIALIZE(IdToObj, objects);
DESERIALIZE(int, currentID);
for (auto it = objects.begin(); it != objects.end(); ++it)
obj->insertObject(it->first, it->second);
obj->select(currentID);
}
} }
| 28.72619 | 91 | 0.67385 | [
"object",
"transform"
] |
19880551637b7754310f96a02ed815573cd10949 | 3,958 | cc | C++ | feature-lines.cc | GaryRay/mallie | 8588a98efff2d9c143cc361dedb1303e4452453c | [
"Zlib"
] | null | null | null | feature-lines.cc | GaryRay/mallie | 8588a98efff2d9c143cc361dedb1303e4452453c | [
"Zlib"
] | null | null | null | feature-lines.cc | GaryRay/mallie | 8588a98efff2d9c143cc361dedb1303e4452453c | [
"Zlib"
] | null | null | null | #include "feature-lines.h"
#ifdef _MSC_VER
#define _USE_MATH_DEFINES
#endif
#include <cmath>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
#include "common.h"
using namespace mallie;
typedef struct {
float x;
float y;
} Point;
static inline int clamp(float x, int w) {
int i = (int)x;
if (i < 0)
i = 0.;
if (i > (w - 1))
i = w - 1;
return i;
}
FeatureLineImageSpace::FeatureLineImageSpace() {}
FeatureLineImageSpace::~FeatureLineImageSpace() {}
void FeatureLineImageSpace::Filter(float *outputs, // output image.
int *geomIDs, // int
float *normals, // [xyz] x float
float *depths, // float
int width, // image width,
int height, // image height,
int N, float h) {
memset(outputs, 0, sizeof(float) * width * height);
// Stencil point to compute gradient
float stencilDir[4][2];
stencilDir[0][0] = h;
stencilDir[0][1] = 0.0f;
stencilDir[1][0] = 0.0f;
stencilDir[1][1] = h;
stencilDir[2][0] = -h;
stencilDir[2][1] = 0.0f;
stencilDir[3][0] = 0.0f;
stencilDir[3][1] = -h;
// Precompute sampling point.
std::vector<Point> samplePoints;
for (int i = 1; i <= N; i++) {
// Concentric circles.
float radius = (i / (float)N);
for (int k = 0; k < 8; k++) {
float theta = 2.0 * M_PI * (k / 8.0);
Point p;
p.x = radius * cos(theta);
p.y = radius * sin(theta);
samplePoints.push_back(p);
}
}
float mHalf = samplePoints.size() * 0.5f;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// s = center of sampling point.
Point s;
s.x = x + 0.5f;
s.y = y + 0.5f;
// 1) compute m.
// m is the number of samples(rays) r in filter region for which g_r !=
// g_s
// (i.e., the number of samples hitting different geom ID)
int m = 0;
int g_s = geomIDs[y * width + x];
float normalDiffMax = 1.0f;
float distDiffMax = 0.0f;
float distDiffThres = 1.5f; // @fixme. scene scale dependent
float t_s = depths[y * width + x];
real3 normal;
normal[0] = normals[3 * (y * width + x) + 0];
normal[1] = normals[3 * (y * width + x) + 1];
normal[2] = normals[3 * (y * width + x) + 2];
for (int k = 0; k < samplePoints.size(); k++) {
int px = clamp(s.x + samplePoints[k].x, width);
int py = clamp(s.y + samplePoints[k].y, height);
int g_r = geomIDs[py * width + px];
float t_r = depths[py * width + px];
if (g_s != g_r) {
m++;
}
real3 n;
n[0] = normals[3 * (py * width + px) + 0];
n[1] = normals[3 * (py * width + px) + 1];
n[2] = normals[3 * (py * width + px) + 2];
// same dir = near to 1.0, diff dir = near to 0.0, so we take min() to
// compute diffMax.
float normalDiff = fabs(vdot(n, normal));
normalDiffMax = std::min<float>(normalDiff, normalDiffMax);
if (fabsf(t_s - t_r) > 0.1f && (t_s > 0.1f) && (t_r > 0.1f)) {
distDiffMax = std::max<float>(distDiffMax, fabsf(t_s - t_r));
}
}
outputs[y * width + x] = 0.0f;
if (m == 0) {
// Geom ID are all same.
// 2.2) Check crease-edge.
// If any normal is significantly different, it is crease-edge.
// if (normalDiffMax < 0.25) {
// outputs[y*width+x] = 4.0f * (0.25 - normalDiffMax);
//}
// 2.2) Check self-occlusion.
// Disabled for now because visual quality is not good.
// if (distDiffMax > distDiffThres) {
// outputs[y*width+x] = 1.0f;
//}
} else {
float e = 1.0 - fabs(m - mHalf) / mHalf;
outputs[y * width + x] = e;
}
}
}
}
| 28.47482 | 80 | 0.505306 | [
"vector"
] |
198c5379ce4cf13c75e50fdeea99c2e5172034ff | 642 | cpp | C++ | contest/yukicoder/168.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | contest/yukicoder/168.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | contest/yukicoder/168.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "container/union_find.hpp"
#include "math.hpp"
int main() {
int n(in);
Vector<Tuple<int64_t, int64_t>> p(n, in);
Vector<Tuple<int64_t, int, int>> dis;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
auto nrm =
norm(p[i].get<0>(), p[i].get<1>(), p[j].get<0>(), p[j].get<1>());
auto d = sqrt_int(nrm) + (isSquare(nrm) ? 0 : 1);
dis.emplace_back(d, i, j);
}
}
dis.sort();
UnionFind uf(n);
for (const auto &d : dis) {
uf.unite(d.get<1>(), d.get<2>());
if (uf.equal(0, n - 1)) {
cout << ceil<int64_t>(d.get<0>(), 10) * 10 << endl;
return 0;
}
}
}
| 24.692308 | 75 | 0.490654 | [
"vector"
] |
198cb56a3280649267b6c6f85882177c809db857 | 4,126 | cpp | C++ | Sources/Internal/Base/FixedSizePoolAllocator.cpp | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Sources/Internal/Base/FixedSizePoolAllocator.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Sources/Internal/Base/FixedSizePoolAllocator.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z | #include "Base/FixedSizePoolAllocator.h"
#include "Base/TemplateHelpers.h"
#if defined(__DAVAENGINE_MACOS__) || defined(__DAVAENGINE_IPHONE__)
#include <stdlib.h>
#endif
#include <cstdlib>
namespace DAVA
{
FixedSizePoolAllocator::FixedSizePoolAllocator(uint32 _blockSize, uint32 _blockArraySize)
{
DVASSERT(_blockSize >= sizeof(uint8*));
blockSize = _blockSize;
blockArraySize = _blockArraySize;
allocatedBlockArrays = nullptr;
nextFreeBlock = nullptr;
#ifdef __DAVAENGINE_DEBUG__
totalBlockCount = 0;
freeItemCount = 0;
maxItemCount = 0;
#endif
CreateNewDataBlock();
}
void FixedSizePoolAllocator::CreateNewDataBlock()
{
DVASSERT(blockSize >= sizeof(uint8*));
void** block = static_cast<void**>(::malloc(blockArraySize * blockSize + sizeof(uint8*)));
//Logger::FrameworkDebug("Allocated new data block: %p pointer size: %d", block, sizeof(uint8*));
// insert to list
*block = allocatedBlockArrays;
allocatedBlockArrays = block;
#ifdef __DAVAENGINE_DEBUG__
totalBlockCount++;
freeItemCount += blockArraySize;
#endif
InsertBlockToFreeNodes(block);
}
void FixedSizePoolAllocator::InsertBlockToFreeNodes(void* block)
{
uint8* blockItem = OffsetPointer<uint8>(block, sizeof(uint8*) + blockSize * (blockArraySize - 1));
for (uint32 k = 0; k < blockArraySize; ++k)
{
//Logger::FrameworkDebug("Free block added: %p", blockItem);
*reinterpret_cast<uint8**>(blockItem) = static_cast<uint8*>(nextFreeBlock);
nextFreeBlock = blockItem;
blockItem -= blockSize;
}
}
void FixedSizePoolAllocator::Reset()
{
nextFreeBlock = 0;
void* currentBlock = allocatedBlockArrays;
while (currentBlock)
{
void* next = *static_cast<void**>(currentBlock);
InsertBlockToFreeNodes(currentBlock);
currentBlock = next;
}
}
void FixedSizePoolAllocator::DeallocateMemory()
{
#ifdef __DAVAENGINE_DEBUG__
// DVASSERT(freeItemCount == (totalBlockCount*blockArraySize));
#endif
while (allocatedBlockArrays)
{
uint8* next = *static_cast<uint8**>(allocatedBlockArrays);
::free(allocatedBlockArrays);
#ifdef __DAVAENGINE_DEBUG__
totalBlockCount--;
#endif
//Logger::FrameworkDebug("Deallocated data block: %p pointer size: %d", allocatedBlockArrays, sizeof(uint8*));
allocatedBlockArrays = next;
}
#ifdef __DAVAENGINE_DEBUG__
DVASSERT(0 == totalBlockCount);
freeItemCount = 0;
#endif
}
FixedSizePoolAllocator::~FixedSizePoolAllocator()
{
DeallocateMemory();
}
void* FixedSizePoolAllocator::New()
{
void* object = 0;
if (nextFreeBlock == nullptr)
{
CreateNewDataBlock();
}
#ifdef __DAVAENGINE_DEBUG__
freeItemCount--;
maxItemCount = Max(maxItemCount, (blockArraySize * blockSize) - freeItemCount);
#endif
object = nextFreeBlock;
nextFreeBlock = *static_cast<void**>(nextFreeBlock);
return object;
}
void FixedSizePoolAllocator::Delete(void* block)
{
*static_cast<void**>(block) = nextFreeBlock;
nextFreeBlock = block;
#ifdef __DAVAENGINE_DEBUG__
freeItemCount++;
#endif
}
bool FixedSizePoolAllocator::CheckIsPointerValid(void* blockvoid)
{
uint8* block = static_cast<uint8*>(blockvoid);
uint8* currentAllocatedBlockArray = static_cast<uint8*>(allocatedBlockArrays);
while (currentAllocatedBlockArray)
{
//uint8* next = *(uint8**)currentAllocatedBlockArray;
uint8* next = *reinterpret_cast<uint8**>(currentAllocatedBlockArray);
if ((block >= currentAllocatedBlockArray + sizeof(uint8*)) && (block < currentAllocatedBlockArray + sizeof(uint8*) + blockSize * blockArraySize))
{
// we are inside check is block correct.
uint32 shift = static_cast<uint32>(block - (currentAllocatedBlockArray + sizeof(uint8*)));
uint32 mod = shift % blockSize;
if (mod == 0)
{
return true;
}
else
{
return false;
}
}
currentAllocatedBlockArray = next;
}
return false;
}
}
| 27.324503 | 153 | 0.6762 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.