hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aa9ccf96cd9a53939bba1cd4e5e5c7e3d4490733 | 2,977 | hpp | C++ | libs/core/render/include/bksge/core/render/inl/texture_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/render/include/bksge/core/render/inl/texture_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/render/include/bksge/core/render/inl/texture_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file texture_inl.hpp
*
* @brief Texture の実装
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_RENDER_INL_TEXTURE_INL_HPP
#define BKSGE_CORE_RENDER_INL_TEXTURE_INL_HPP
#include <bksge/core/render/texture.hpp>
#include <bksge/fnd/memory/make_shared.hpp>
#include <bksge/fnd/assert.hpp>
#include <bksge/fnd/config.hpp>
#include <cstddef>
#include <cstdint>
namespace bksge
{
namespace render
{
BKSGE_INLINE
Texture::Texture(void)
: m_format(TextureFormat::kUndefined)
, m_extent(0, 0)
, m_mipmap_count(0)
, m_pixels(bksge::make_shared<Pixels>())
{}
BKSGE_INLINE
Texture::Texture(
TextureFormat format,
ExtentType const& extent,
std::size_t mipmap_count,
std::uint8_t const* src)
: m_format(format)
, m_extent(extent)
, m_mipmap_count(mipmap_count)
, m_pixels(bksge::make_shared<Pixels>())
{
BKSGE_ASSERT(format != TextureFormat::kUndefined);
BKSGE_ASSERT(extent.width() >= 1u);
BKSGE_ASSERT(extent.height() >= 1u);
BKSGE_ASSERT(mipmap_count >= 1u);
auto const bytes = GetMipmappedSizeInBytes(format, extent.width(), extent.height(), mipmap_count);
BKSGE_ASSERT(bytes >= 1u);
m_pixels->resize(bytes);
if (src)
{
m_pixels->copy(src, bytes);
}
}
BKSGE_INLINE
Texture::Texture(TextureFormat format, ExtentType const& extent, std::size_t mipmap_count)
: Texture(format, extent, mipmap_count, nullptr)
{}
BKSGE_INLINE
Texture::Texture(TextureFormat format, ExtentType const& extent, std::uint8_t const* src)
: Texture(format, extent, 1, src)
{}
BKSGE_INLINE
Texture::Texture(TextureFormat format, ExtentType const& extent)
: Texture(format, extent, 1, nullptr)
{}
BKSGE_INLINE
TextureFormat Texture::format(void) const
{
return m_format;
}
BKSGE_INLINE
auto Texture::extent(void) const
-> ExtentType const&
{
return m_extent;
}
BKSGE_INLINE
std::uint32_t Texture::width(void) const
{
return extent().width();
}
BKSGE_INLINE
std::uint32_t Texture::height(void) const
{
return extent().height();
}
BKSGE_INLINE
std::size_t Texture::mipmap_count(void) const
{
return m_mipmap_count;
}
BKSGE_INLINE
std::size_t Texture::stride(void) const
{
return GetStrideInBytes(format(), width());
}
BKSGE_INLINE
std::uint8_t const* Texture::data(void) const
{
BKSGE_ASSERT(m_pixels != nullptr);
return m_pixels->data();
}
BKSGE_INLINE
auto Texture::pixels(void) const
-> Pixels const&
{
BKSGE_ASSERT(m_pixels != nullptr);
return *m_pixels;
}
BKSGE_INLINE
bool operator==(Texture const& lhs, Texture const& rhs)
{
return
lhs.format() == rhs.format() &&
lhs.extent() == rhs.extent() &&
lhs.mipmap_count() == rhs.mipmap_count() &&
lhs.pixels() == rhs.pixels();
}
BKSGE_INLINE
bool operator!=(Texture const& lhs, Texture const& rhs)
{
return !(lhs == rhs);
}
} // namespace render
} // namespace bksge
#endif // BKSGE_CORE_RENDER_INL_TEXTURE_INL_HPP
| 20.114865 | 100 | 0.689956 | myoukaku |
aaa0dbc846b98e467f10b4031a968212b5c1ab91 | 1,054 | cpp | C++ | src/JImage.cpp | jildertviet/ofxJVisuals | 878c5b0e7a7dda49ddb71b3f5d19c13987706a73 | [
"MIT"
] | null | null | null | src/JImage.cpp | jildertviet/ofxJVisuals | 878c5b0e7a7dda49ddb71b3f5d19c13987706a73 | [
"MIT"
] | 6 | 2021-10-16T07:10:04.000Z | 2021-12-26T13:23:54.000Z | src/JImage.cpp | jildertviet/ofxJVisuals | 878c5b0e7a7dda49ddb71b3f5d19c13987706a73 | [
"MIT"
] | null | null | null | //
// Image.cpp
// Bas
//
// Created by Jildert Viet on 18-03-16.
//
//
#include "JImage.hpp"
JImage::JImage(string filename, ofVec2f loc){
this->loc = loc;
setType("JImage");
bLoadSucces = loadImage(filename);
colors[0] = ofColor(255,255);
}
void JImage::display(){
if(!bLoadSucces)
return;
ofSetColor(colors[0]);
ofPushMatrix();
ofTranslate(loc);
if(zoom != 1.0){
ofTranslate(size.x * 0.5, size.y * 0.5);
ofScale(zoom);
ofTranslate(size.x * -0.5, size.y * -0.5);
}
switch(drawMode){
case DEFAULT:
image.draw(0, 0, size.x, size.y);
break;
}
ofPopMatrix();
}
void JImage::specificFunction(){
}
bool JImage::loadImage(string path){
image.clear();
if(image.load(path)){
cout << "Image " << path << " loaded" << endl;
size = glm::vec2(image.getWidth(), image.getHeight());
return true;
} else{
return false;
}
}
| 19.518519 | 63 | 0.510436 | jildertviet |
aaa4e343a803b91d7be91c16c80b30a6aac9a633 | 2,742 | cpp | C++ | Arcane/src/Arcane/Platform/OpenGL/Framebuffer/GBuffer.cpp | flygod1159/Arcane-Engine | bfb95cc6734a25e5737d4195c2b9e92e03117707 | [
"MIT"
] | 387 | 2016-10-04T03:30:38.000Z | 2022-03-31T15:42:29.000Z | Arcane/src/Arcane/Platform/OpenGL/Framebuffer/GBuffer.cpp | flygod1159/Arcane-Engine | bfb95cc6734a25e5737d4195c2b9e92e03117707 | [
"MIT"
] | 9 | 2017-04-04T04:23:47.000Z | 2020-07-11T05:05:54.000Z | Arcane/src/Arcane/Platform/OpenGL/Framebuffer/GBuffer.cpp | flygod1159/Arcane-Engine | bfb95cc6734a25e5737d4195c2b9e92e03117707 | [
"MIT"
] | 36 | 2017-07-02T07:11:40.000Z | 2022-03-08T01:49:24.000Z | #include "arcpch.h"
#include "GBuffer.h"
namespace Arcane
{
GBuffer::GBuffer(unsigned int width, unsigned int height) : Framebuffer(width, height, false) {
Init();
}
GBuffer::~GBuffer() {}
void GBuffer::Init() {
AddDepthStencilTexture(NormalizedDepthStencil);
Bind();
// Render Target 1
{
TextureSettings renderTarget1;
renderTarget1.TextureFormat = GL_RGBA8;
renderTarget1.TextureWrapSMode = GL_CLAMP_TO_EDGE;
renderTarget1.TextureWrapTMode = GL_CLAMP_TO_EDGE;
renderTarget1.TextureMinificationFilterMode = GL_NEAREST;
renderTarget1.TextureMagnificationFilterMode = GL_NEAREST;
renderTarget1.TextureAnisotropyLevel = 1.0f;
renderTarget1.HasMips = false;
m_GBufferRenderTargets[0].SetTextureSettings(renderTarget1);
m_GBufferRenderTargets[0].Generate2DTexture(m_Width, m_Height, GL_RGB);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_GBufferRenderTargets[0].GetTextureId(), 0);
}
// Render Target 2
{
TextureSettings renderTarget2;
renderTarget2.TextureFormat = GL_RGB32F;
renderTarget2.TextureWrapSMode = GL_CLAMP_TO_EDGE;
renderTarget2.TextureWrapTMode = GL_CLAMP_TO_EDGE;
renderTarget2.TextureMinificationFilterMode = GL_NEAREST;
renderTarget2.TextureMagnificationFilterMode = GL_NEAREST;
renderTarget2.TextureAnisotropyLevel = 1.0f;
renderTarget2.HasMips = false;
m_GBufferRenderTargets[1].SetTextureSettings(renderTarget2);
m_GBufferRenderTargets[1].Generate2DTexture(m_Width, m_Height, GL_RGB);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_GBufferRenderTargets[1].GetTextureId(), 0);
}
// Render Target 3
{
TextureSettings renderTarget3;
renderTarget3.TextureFormat = GL_RGBA8;
renderTarget3.TextureWrapSMode = GL_CLAMP_TO_EDGE;
renderTarget3.TextureWrapTMode = GL_CLAMP_TO_EDGE;
renderTarget3.TextureMinificationFilterMode = GL_NEAREST;
renderTarget3.TextureMagnificationFilterMode = GL_NEAREST;
renderTarget3.TextureAnisotropyLevel = 1.0f;
renderTarget3.HasMips = false;
m_GBufferRenderTargets[2].SetTextureSettings(renderTarget3);
m_GBufferRenderTargets[2].Generate2DTexture(m_Width, m_Height, GL_RGB);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_GBufferRenderTargets[2].GetTextureId(), 0);
}
// Finally tell OpenGL that we will be rendering to all of the attachments
unsigned int attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, attachments);
// Check if the creation failed
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
ARC_LOG_FATAL("Could not initialize GBuffer");
return;
}
Unbind();
}
}
| 37.054054 | 124 | 0.78884 | flygod1159 |
aaa6da5ef96b6b36ca4a940e12ee7346d14b08ef | 1,783 | cpp | C++ | main.cpp | ikbo0217/glazkov_lab3_sem2 | eceb826eaa9aeeb5df148682a1398a2bed34bfe7 | [
"MIT"
] | null | null | null | main.cpp | ikbo0217/glazkov_lab3_sem2 | eceb826eaa9aeeb5df148682a1398a2bed34bfe7 | [
"MIT"
] | null | null | null | main.cpp | ikbo0217/glazkov_lab3_sem2 | eceb826eaa9aeeb5df148682a1398a2bed34bfe7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <math.h>
using namespace std;
int pointState(int cx, int cy, int cr, int x, int y) {
int result = 0;
if(pow(x - cx, 2) + pow(y - cy, 2) == pow(cr, 2)) result = 2;
if(pow(x - cx, 2) + pow(y - cy, 2) < pow(cr, 2)) result = 1;
return result;
}
int quadrilateralState(int cx, int cy, int cr, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
int result = 0;
int p1 = pointState(cx, cy, cr, x1, y1);
int p2 = pointState(cx, cy, cr, x2, y2);
int p3 = pointState(cx, cy, cr, x3, y3);
int p4 = pointState(cx, cy, cr, x4, y4);
if(p1 == 2 && p2 == 2 && p3 == 2 && p4 == 2) return result = 2;
if(p1 && p2 && p3 && p4) return result = 1;
return result;
}
int main() {
int cx = 0;
int cy = 0;
int cr = 0;
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
int x3 = 0;
int y3 = 0;
int x4 = 0;
int y4 = 0;
cout << "Enter circle center coordinates: " << endl;
cout << "Enter x: ";
cin >> cx;
cout << "Enter y: ";
cin >> cy;
cout << "Enter radius: ";
cin >> cr;
cout << endl;
cout << "Enter quadrilateral vertex coordinates: " << endl;
cout << "Enter x1: ";
cin >> x1;
cout << "Enter y1: ";
cin >> y1;
cout << "Enter x2: ";
cin >> x2;
cout << "Enter y2: ";
cin >> y2;
cout << "Enter x3: ";
cin >> x3;
cout << "Enter y3: ";
cin >> y3;
cout << "Enter x4: ";
cin >> x4;
cout << "Enter y4: ";
cin >> y4;
cout << endl;
int result = quadrilateralState(cx, cy, cr, x1, y1, x2, y2, x3, y3, x4, y4);
switch (result) {
case 0:
cout << "Result: OUTSIDE" << endl;
case 1:
cout << "Result: INSIDE" << endl;
case 2:
cout << "Result: TOUCH" << endl;
}
return 0;
}
| 18.572917 | 112 | 0.503085 | ikbo0217 |
aaad34f2d74344a8c641f2b74145ceca9b30b093 | 938 | cpp | C++ | catchMain.cpp | skrtks/ft_containers_tests | a5044a4b559bbbd1292c6f5996dff4ed8b9b599f | [
"BSD-2-Clause"
] | null | null | null | catchMain.cpp | skrtks/ft_containers_tests | a5044a4b559bbbd1292c6f5996dff4ed8b9b599f | [
"BSD-2-Clause"
] | null | null | null | catchMain.cpp | skrtks/ft_containers_tests | a5044a4b559bbbd1292c6f5996dff4ed8b9b599f | [
"BSD-2-Clause"
] | 2 | 2021-02-25T14:25:21.000Z | 2021-11-24T11:32:23.000Z | /* ************************************************************************** */
/* */
/* :::::::: */
/* catchMain.cpp :+: :+: */
/* +:+ */
/* By: skorteka <[email protected]> +#+ */
/* +#+ */
/* Created: 2020/10/23 14:12:47 by skorteka #+# #+# */
/* Updated: 2020/10/23 14:12:47 by skorteka ######## odam.nl */
/* */
/* ************************************************************************** */
#define CATCH_CONFIG_MAIN
#include "Catch2.h"
| 62.533333 | 80 | 0.158849 | skrtks |
aaada067b38f9be1a996c674c8ff8359931d902c | 8,322 | cpp | C++ | unit_tests/maths/matrix_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 28 | 2021-11-23T11:52:55.000Z | 2022-03-04T01:48:52.000Z | unit_tests/maths/matrix_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | null | null | null | unit_tests/maths/matrix_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 3 | 2022-01-02T12:23:04.000Z | 2022-01-07T04:21:26.000Z | //
// matrix_tests.cpp
// unit_tests
//
// Created by 杨丰 on 2021/11/25.
//
#include "maths/matrix.h"
#include "gtest.h"
#include "gtest_helper.h"
#include "gtest_math_helper.h"
using vox::math::Float3;
using vox::math::Matrix;
using vox::math::Quaternion;
TEST(Matrix, multiply) {
const auto a = Matrix(1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
const auto b = Matrix(16, 15, 14, 13, 12, 11, 10, 9, 8.88, 7, 6, 5, 4, 3, 2, 1);
const Matrix out = a * b;
EXPECT_MATRIX_EQ(out,
386,
456.59997558,
506.8,
560,
274,
325,
361.6,
400,
162.88,
195.16000000000003,
219.304,
243.52,
50,
61.8,
71.2,
80);
}
TEST(Matrix, lerp) {
const auto a = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
const auto b = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
const auto c = Lerp(a, b, 0.7);
EXPECT_MATRIX_EQ(c, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
}
TEST(Matrix, rotationQuaternion) {
const auto q = Quaternion(1, 2, 3, 4);
const auto out = Matrix::rotationQuaternion(q);
EXPECT_MATRIX_EQ(out, -25, 28, -10, 0, -20, -19, 20, 0, 22, 4, -9, 0, 0, 0, 0, 1);
}
TEST(Matrix, rotationAxisAngle) {
const auto out = Matrix::rotationAxisAngle(Float3(0, 1, 0), M_PI / 3);
EXPECT_MATRIX_EQ(out,
0.5000000000000001,
0,
-0.8660254037844386,
0,
0,
1,
0,
0,
0.8660254037844386,
0,
0.5000000000000001,
0,
0,
0,
0,
1);
}
TEST(Matrix, rotationTranslation) {
const auto q = Quaternion(1, 0.5, 2, 1);
const auto v = Float3(1, 1, 1);
const auto out = Matrix::rotationTranslation(q, v);
EXPECT_MATRIX_EQ(out, -7.5, 5, 3, 0, -3, -9, 4, 0, 5, 0, -1.5, 0, 1, 1, 1, 1);
}
TEST(Matrix, affineTransformation) {
const auto q = Quaternion(1, 0.5, 2, 1);
const auto v = Float3(1, 1, 1);
const auto s = Float3(1, 0.5, 2);
const auto out = Matrix::affineTransformation(s, q, v);
EXPECT_MATRIX_EQ(out, -7.5, 5, 3, 0, -1.5, -4.5, 2, 0, 10, 0, -3, 0, 1, 1, 1, 1);
}
TEST(Matrix, scaling) {
const auto a = Matrix();
const auto out = scale(a, Float3(1, 2, 0.5));
EXPECT_MATRIX_EQ(out, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1);
}
TEST(Matrix, translation) {
const auto v = Float3(1, 2, 0.5);
const auto out = Matrix::translation(v);
EXPECT_MATRIX_EQ(out, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 0.5, 1);
}
TEST(Matrix, invert) {
const auto a = Matrix(1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
const auto out = invert(a);
EXPECT_MATRIX_EQ(out,
-1.1111111111111172,
1.3703594207763672,
-0.7407407407407528,
0.1481481481481532,
0,
-0.5555555555555607,
1.1110992431640625,
-0.5555555555555607,
3.3333001136779785,
-4.9999480247497559,
0,
1.6666476726531982,
-2.222196102142334,
4.0601420402526855,
-0.3703703703703687,
-1.1342480182647705
);
}
TEST(Matrix, lookAt) {
auto eye = Float3(0, 0, -8);
auto target = Float3(0, 0, 0);
auto up = Float3(0, 1, 0);
auto out = Matrix::lookAt(eye, target, up);
EXPECT_MATRIX_EQ(out, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, -8, 1);
eye = Float3(0, 0, 0);
target = Float3(0, 1, -1);
up = Float3(0, 1, 0);
out = Matrix::lookAt(eye, target, up);
EXPECT_MATRIX_EQ(out,
1,
0,
0,
0,
0,
0.7071067690849304,
-0.7071067690849304,
0,
0,
0.7071067690849304,
0.7071067690849304,
0,
0,
0,
0,
1
);
}
TEST(Matrix, ortho) {
const auto out = Matrix::ortho(0, 2, -1, 1, 0.1, 100);
EXPECT_MATRIX_EQ(out, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.02002002002002002, 0, -1, 0, -1.002002002002002, 1);
}
TEST(Matrix, perspective) {
const auto out = Matrix::perspective(1, 1.5, 0.1, 100);
EXPECT_MATRIX_EQ(out,
1.2203251478083013,
0,
0,
0,
0,
1.830487721712452,
0,
0,
0,
0,
-1.002002002002002,
-1,
0,
0,
-0.20020020020020018,
0
);
}
TEST(Matrix, rotateAxisAngle) {
const auto a = Matrix(1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
const auto out = rotateAxisAngle(a, Float3(0, 1, 0), M_PI / 3);
EXPECT_MATRIX_EQ(out,
-7.294228634059947,
-8.439676901250381,
-7.876279441628824,
-8.392304845413264,
5,
6,
7,
8,
5.366025403784439,
7.182050807568878,
8.357883832488648,
9.464101615137757,
13,
14,
15,
16
);
}
TEST(Matrix, scale) {
const auto a = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
const auto out = scale(a, Float3(1, 2, 0.5));
EXPECT_MATRIX_EQ(out, 1, 2, 3, 4, 10, 12, 14, 16, 4.5, 5, 5.5, 6, 13, 14, 15, 16);
}
TEST(Matrix, translate) {
const auto a = Matrix(1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
const auto out = translate(a, Float3(1, 2, 0.5));
EXPECT_MATRIX_EQ(out, 1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 28.5, 33.45, 37.8, 42);
}
TEST(Matrix, transpose) {
const auto a = Matrix(1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
const auto out = transpose(a);
EXPECT_MATRIX_EQ(out, 1, 5, 9, 13, 2, 6, 10.9, 14, 3.3, 7, 11, 15, 4, 8, 12, 16);
}
TEST(Matrix, determinant) {
const auto a = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
EXPECT_FLOAT_EQ(a.determinant(), -6.1035156e-05);
}
TEST(Matrix, decompose) {
const auto a = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
// const a = new Matrix(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
auto pos = Float3();
auto quat = Quaternion();
auto scale = Float3();
a.decompose(pos, quat, scale);
EXPECT_FLOAT3_EQ(pos, 13, 14, 15);
EXPECT_QUATERNION_EQ(quat, 0.01879039477474769, -0.09554131404261303, 0.01844761344901482, 0.783179537258594);
EXPECT_FLOAT3_EQ(scale, 3.7416573867739413, 10.488088481701515, 17.91116946723357);
}
TEST(Matrix, getXXX) {
const auto a = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10.9, 11, 12, 13, 14, 15, 16);
// getRotation
auto quat = a.getRotation();
EXPECT_QUATERNION_EQ(quat, -0.44736068104759547, 0.6882472016116852, -0.3441236008058426, 2.179449471770337);
// getScaling
auto scale = a.getScaling();
EXPECT_FLOAT3_EQ(scale, 3.7416573867739413, 10.488088481701515, 17.911169699380327);
// getTranslation
auto translation = a.getTranslation();
EXPECT_FLOAT3_EQ(translation, 13, 14, 15);
}
| 32.255814 | 114 | 0.451214 | yangfengzzz |
aaae4cc2e61c02950c900c410a97b6c2ad46049c | 2,259 | cpp | C++ | src/Array.cpp | chnlkw/xuanwu | f796e9a851d8fad289ac5a625679e7db6c090a04 | [
"MIT"
] | 1 | 2018-04-09T01:45:17.000Z | 2018-04-09T01:45:17.000Z | src/Array.cpp | chnlkw/xuanwu | f796e9a851d8fad289ac5a625679e7db6c090a04 | [
"MIT"
] | null | null | null | src/Array.cpp | chnlkw/xuanwu | f796e9a851d8fad289ac5a625679e7db6c090a04 | [
"MIT"
] | 1 | 2020-04-14T03:39:20.000Z | 2020-04-14T03:39:20.000Z | //
// Created by chnlkw on 1/16/18.
//
#include "Array.h"
#include "DataCopy.h"
#include "Device.h"
#include "Allocator.h"
#include "Xuanwu.h"
#include "Ptr.h"
namespace Xuanwu {
ArrayBase::ArrayBase(size_t bytes, AllocatorPtr allocator)
: allocator_(allocator), bytes_(bytes), ptr_(allocator->Alloc(bytes)) {
}
// ArrayBase::ArrayBase(const ArrayBase &that) :
// allocator_(Xuanwu::GetDefaultDevice()->GetDefaultAllocator()) {
// Allocate(that.bytes_);
// ArrayCopy(allocator_->GetDevice(), ptr_, that.allocator_->GetDevice(), that.ptr_, that.bytes_);
// }
// ArrayBase::ArrayBase(void *ptr, size_t bytes) : //alias from cpu array
// allocator_(nullptr),
// ptr_(ptr),
// bytes_(bytes) {
// }
ArrayBase::ArrayBase(ArrayBase &&that) :
allocator_(that.allocator_),
bytes_(that.bytes_),
ptr_(that.ptr_) {
that.ptr_ = nullptr;
}
ArrayBase::ArrayBase(const ArrayBase &that, size_t off, size_t bytes)
: allocator_(nullptr),
bytes_(bytes),
ptr_((char *) that.ptr_ + off) {
}
ArrayBase::~ArrayBase() {
Free();
}
void ArrayBase::Free() {
if (allocator_ && ptr_)
allocator_->Free(ptr_);
ptr_ = nullptr;
bytes_ = 0;
}
void ArrayBase::Allocate(size_t bytes) {
bytes_ = bytes;
if (bytes > 0 && allocator_) {
ptr_ = allocator_->Alloc(bytes);
} else {
ptr_ = nullptr;
}
// printf("reallocate ptr %p bytes = %lu\n", ptr_, bytes);
}
// void ArrayBase::CopyFrom(const ArrayBase &that) {
// CopyFromAsync(that, GetDefaultWorker());
// }
//
// void ArrayBase::CopyFromAsync(const ArrayBase &that, WorkerPtr worker) {
// size_t bytes = std::min(this->bytes_, that.bytes_);
// assert(this->bytes_ == that.bytes_);
// worker->Copy(GetPtr(), that.GetPtr(), bytes);
// }
// DevicePtr ArrayBase::GetDevice() const { return allocator_->GetDevice(); }
// AllocatorPtr ArrayBase::GetAllocator() const { return allocator_; }
Ptr ArrayBase::GetPtr() const {
return allocator_->MakePtr(ptr_);
}
}
| 27.54878 | 105 | 0.578132 | chnlkw |
aab0500972a427259f69e429bb8ca96d7c2635e3 | 1,764 | hpp | C++ | drape/vulkan/vulkan_param_descriptor.hpp | sthirvela/organicmaps | 14885ba070ac9d1b7241ebb89eeefa46c9fdc1e4 | [
"Apache-2.0"
] | 3,062 | 2021-04-09T16:51:55.000Z | 2022-03-31T21:02:51.000Z | drape/vulkan/vulkan_param_descriptor.hpp | MAPSWorks/organicmaps | b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f | [
"Apache-2.0"
] | 1,396 | 2021-04-08T07:26:49.000Z | 2022-03-31T20:27:46.000Z | drape/vulkan/vulkan_param_descriptor.hpp | MAPSWorks/organicmaps | b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f | [
"Apache-2.0"
] | 242 | 2021-04-10T17:10:46.000Z | 2022-03-31T13:41:07.000Z | #pragma once
#include "drape/graphics_context.hpp"
#include "drape/vulkan/vulkan_gpu_program.hpp"
#include "drape/vulkan/vulkan_utils.hpp"
#include <array>
#include <cstdint>
#include <string>
#include <vector>
namespace dp
{
namespace vulkan
{
struct ParamDescriptor
{
enum class Type : uint8_t
{
DynamicUniformBuffer = 0,
Texture
};
Type m_type = Type::DynamicUniformBuffer;
VkDescriptorBufferInfo m_bufferDescriptor = {};
uint32_t m_bufferDynamicOffset = 0;
VkDescriptorImageInfo m_imageDescriptor = {};
int8_t m_textureSlot = 0;
uint32_t m_id = 0;
};
size_t constexpr kMaxDescriptorSets = 8;
struct DescriptorSetGroup
{
VkDescriptorSet m_descriptorSet = {};
VkDescriptorPool m_descriptorPool = {};
std::array<uint32_t, kMaxDescriptorSets> m_ids = {};
bool m_updated = false;
explicit operator bool()
{
return m_descriptorSet != VK_NULL_HANDLE &&
m_descriptorPool != VK_NULL_HANDLE;
}
void Update(VkDevice device, std::vector<ParamDescriptor> const & descriptors);
};
class VulkanObjectManager;
class ParamDescriptorUpdater
{
public:
explicit ParamDescriptorUpdater(ref_ptr<VulkanObjectManager> objectManager);
void Update(ref_ptr<dp::GraphicsContext> context);
void Destroy();
VkDescriptorSet GetDescriptorSet() const;
private:
void Reset(uint32_t inflightFrameIndex);
ref_ptr<VulkanObjectManager> m_objectManager;
struct UpdateData
{
std::vector<DescriptorSetGroup> m_descriptorSetGroups;
ref_ptr<VulkanGpuProgram> m_program;
uint32_t m_updateDescriptorFrame = 0;
uint32_t m_descriptorSetIndex = 0;
};
std::array<UpdateData, kMaxInflightFrames> m_updateData;
uint32_t m_currentInflightFrameIndex = 0;
};
} // namespace vulkan
} // namespace dp
| 21.512195 | 81 | 0.751134 | sthirvela |
82b5f763483e02639ac4259a4c32820b43a85c6c | 1,012 | cpp | C++ | Solutions/Search for a Range/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | 1 | 2015-04-13T10:58:30.000Z | 2015-04-13T10:58:30.000Z | Solutions/Search for a Range/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | null | null | null | Solutions/Search for a Range/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> res(2,-1);
int left = 0;
int right = n-1;
while(left <= right) {
int mid = (left + right) / 2;
if (A[mid] == target) {
int i,j;
i = j = mid;
for(; i >= left && A[i] == target; i--);
for(; j <= right && A[j] == target; j++);
res[0] = i+1;
res[1] = j-1;
return res;
}
if (target > A[mid]) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return res;
}
};
int main()
{
int A[] = {};
Solution s;
vector<int> res = s.searchRange(A,sizeof(A)/sizeof(A[0]), 5);
for(auto iter = res.begin(); iter != res.end(); iter++) {
cout<<*iter<<" ";
}
return 0;
}
| 23 | 65 | 0.387352 | Crayzero |
82bc46df9fd678d43a3c01cfed5eb170d9c6da2c | 272 | cpp | C++ | src/gui/columnize/ColumnDefinitionFactory.cpp | tomvodi/QTail | 2e7acf31664969e6890edede6b60e02b20f33eb2 | [
"MIT"
] | 1 | 2017-04-29T12:17:59.000Z | 2017-04-29T12:17:59.000Z | src/gui/columnize/ColumnDefinitionFactory.cpp | tomvodi/QTail | 2e7acf31664969e6890edede6b60e02b20f33eb2 | [
"MIT"
] | 25 | 2016-06-11T17:35:42.000Z | 2017-07-19T04:19:08.000Z | src/gui/columnize/ColumnDefinitionFactory.cpp | tomvodi/QTail | 2e7acf31664969e6890edede6b60e02b20f33eb2 | [
"MIT"
] | null | null | null | /**
* @author Thomas Baumann <[email protected]>
*
* @section LICENSE
* See LICENSE for more informations.
*
*/
#include "ColumnDefinitionFactory.h"
ColumnDefinitionFactory::ColumnDefinitionFactory()
{
}
ColumnDefinitionFactory::~ColumnDefinitionFactory()
{
}
| 13.6 | 51 | 0.735294 | tomvodi |
82c0470a2dbc15b744b23b933a494c7ace723a50 | 4,964 | hpp | C++ | diffsim_torch3d/arcsim/src/util.hpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | diffsim_torch3d/arcsim/src/util.hpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | diffsim_torch3d/arcsim/src/util.hpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
Copyright ©2013 The Regents of the University of California
(Regents). All Rights Reserved. Permission to use, copy, modify, and
distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a
signed licensing agreement, is hereby granted, provided that the
above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and
distributions. Contact The Office of Technology Licensing, UC
Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620,
(510) 643-7201, for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#ifndef UTIL_HPP
#define UTIL_HPP
#include <string> // aa: win
#include "mesh.hpp"
#include "spline.hpp"
#include <iostream>
#include <string>
#include <vector>
using torch::Tensor;
#define EPSILON 1e-7f
// i+1 and i-1 modulo 3
// This way of computing it tends to be faster than using %
#define NEXT(i) ((i)<2 ? (i)+1 : (i)-2)
#define PREV(i) ((i)>0 ? (i)-1 : (i)+2)
typedef unsigned int uint;
struct Transformation;
// Quick-and easy statistics
// sprintf for std::strings
std::string stringf (const std::string &format, ...);
// Easy reporting of vertices and faces
std::ostream &operator<< (std::ostream &out, const Vert *vert);
std::ostream &operator<< (std::ostream &out, const Node *node);
std::ostream &operator<< (std::ostream &out, const Edge *edge);
std::ostream &operator<< (std::ostream &out, const Face *face);
// Math utilities
int solve_quadratic (Tensor a, Tensor b, Tensor c, Tensor x[2]);
Tensor solve_cubic(Tensor a, Tensor b, Tensor c, Tensor d);
// Find, replace, and all that jazz
template <typename T> inline int find (const T *x, T* const *xs, int n=3) {
for (int i = 0; i < n; i++) if (xs[i] == x) return i; return -1;}
template <typename T> inline int find (const T &x, const T *xs, int n=3) {
for (int i = 0; i < n; i++) if (xs[i] == x) return i; return -1;}
template <typename T> inline int find (const T &x, const std::vector<T> &xs) {
for (int i = 0; i < xs.size(); i++) if (xs[i] == x) return i; return -1;}
template <typename T> inline bool is_in (const T *x, T* const *xs, int n=3) {
return find(x, xs, n) != -1;}
template <typename T> inline bool is_in (const T &x, const T *xs, int n=3) {
return find(x, xs, n) != -1;}
template <typename T> inline bool is_in (const T &x, const std::vector<T> &xs) {
return find(x, xs) != -1;}
template <typename T> inline void include (const T &x, std::vector<T> &xs) {
if (!is_in(x, xs)) xs.push_back(x);}
template <typename T> inline void remove (int i, std::vector<T> &xs) {
xs[i] = xs.back(); xs.pop_back();}
template <typename T> inline void exclude (const T &x, std::vector<T> &xs) {
int i = find(x, xs); if (i != -1) remove(i, xs);}
template <typename T> inline void replace (const T &v0, const T &v1, T vs[3]) {
int i = find(v0, vs); if (i != -1) vs[i] = v1;}
template <typename T>
inline void replace (const T &x0, const T &x1, std::vector<T> &xs) {
int i = find(x0, xs); if (i != -1) xs[i] = x1;}
template <typename T>
inline bool subset (const std::vector<T> &xs, const std::vector<T> &ys) {
for (int i = 0; i < xs.size(); i++) if (!is_in(xs[i], ys)) return false;
return true;
}
template <typename T>
inline void append (std::vector<T> &xs, const std::vector<T> &ys) {
xs.insert(xs.end(), ys.begin(), ys.end());}
// Comparisons on vectors
// Mesh utilities
bool is_seam_or_boundary (const Vert *v);
bool is_seam_or_boundary (const Node *n);
bool is_seam_or_boundary (const Edge *e);
bool is_seam_or_boundary (const Face *f);
// Debugging
void debug_save_mesh (const Mesh &mesh, const std::string &name, int n=-1);
void debug_save_meshes (const std::vector<Mesh*> &meshes,
const std::string &name, int n=-1);
template <typename T>
std::ostream &operator<< (std::ostream &out, const std::vector<T> &v) {
out << "[";
for (int i = 0; i < v.size(); i++)
out << (i==0 ? "" : ", ") << v[i];
out << "]";
return out;
}
#define ECHO(x) std::cout << #x << std::endl
#define REPORT(x) std::cout << #x << " = " << (x) << std::endl
#define REPORT_ARRAY(x,n) std::cout << #x << "[" << #n << "] = " << vector<double>(&(x)[0], &(x)[n]) << std::endl
#endif
| 33.315436 | 113 | 0.657736 | priyasundaresan |
82c0f7cd93a78771fc18805fd2e8c07344645e07 | 2,886 | cc | C++ | project2/solution/solution2.cc | EverNebula/CompilerProject-2020Spring | 513173a74f0062e09adbfba0fdef2a5816ef75b5 | [
"MIT"
] | null | null | null | project2/solution/solution2.cc | EverNebula/CompilerProject-2020Spring | 513173a74f0062e09adbfba0fdef2a5816ef75b5 | [
"MIT"
] | null | null | null | project2/solution/solution2.cc | EverNebula/CompilerProject-2020Spring | 513173a74f0062e09adbfba0fdef2a5816ef75b5 | [
"MIT"
] | null | null | null | // this is a silly solution
// just to show you how different
// components of this framework work
// please bring your wise to write
// a 'real' solution :)
#include <iostream>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
#include <dirent.h>
#include <json/json.h>
#include "parser.h"
#include "IRVisitor.h"
#include "printer.h"
using std::string;
// debug output
#define VERBOSE
#ifdef VERBOSE
#define dprintf(format, ...) printf(format, ##__VA_ARGS__)
#else
#define dprintf(format, ...)
#endif
void real();
void readjson(std::ifstream &ifile);
int main() {
Printer Mypt;
std::cout << "call real()" << std::endl;
real();
return 0;
}
void real(){
//std::cout << "Try to open directory PROJ_ROOT_DIR/project1/cases" << std::endl;
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("../project2/cases/")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
char jsonfilename[256] = "../project2/cases/";
if(strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name,"..") == 0)
continue;
strcat(jsonfilename, ent->d_name);
printf ("%s\n", jsonfilename);
std::ifstream ifile(jsonfilename, std::ios::in);
readjson(ifile);
// break;
}
closedir (dir);
} else {
/* could not open directory */
std::cout << "Could not open directory \"cases\"" << std::endl;
return ;
}
}
void readjson(std::ifstream &ifile){
Json::CharReaderBuilder rbuilder;
rbuilder["collectComments"] = false;
Json::Value root_group;
Json::String errs;
bool parse_ok = Json::parseFromStream(rbuilder, ifile, &root_group, &errs);
if(!parse_ok){
std::cout << "Json::parseFromStream failed!" << std::endl;
return;
}
std::string name = root_group["name"].asString();
std::string data_type = root_group["data_type"].asString();
std::string kernel = root_group["kernel"].asString();
std::vector<string> insvec;
std::vector<string> outvec;
std::vector<string> gradto;
for(auto &insval : root_group["ins"])
insvec.push_back(insval.asString());
for(auto &outval : root_group["outs"])
outvec.push_back(outval.asString());
for(auto &gradval : root_group["grad_to"])
gradto.push_back(gradval.asString());
Parser psr(name, insvec, outvec, gradto,data_type, kernel);
psr.build_Kernel();
// Expr tref = psr.parse_RHS("A<4>[k]+B<7,8>[j+1,j+2]");
// parse_P(string("A<16, 32>[i, j] = A<16, 32>[i, j] + alpha<1> * (B<16, 32>[i, k] * C<32, 32>[k, j]); A<16, 32>[i, j] = A<16, 32>[i, j] + beta<1> * D<16, 32>[i, j];"));
}
| 30.0625 | 174 | 0.577963 | EverNebula |
82c2efabff35347dc9d65dbdcc676b2784997b8a | 554 | cpp | C++ | cppcheck/data/c_files/387.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | 2 | 2022-03-23T12:16:20.000Z | 2022-03-31T06:19:40.000Z | cppcheck/data/c_files/387.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | null | null | null | cppcheck/data/c_files/387.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | null | null | null | static int parse_token(char **name, char **value, char **cp)
{
char *end;
if (!name || !value || !cp)
return -BLKID_ERR_PARAM;
if (!(*value = strchr(*cp, '=')))
return 0;
**value = '\0';
*name = strip_line(*cp);
*value = skip_over_blank(*value + 1);
if (**value == '"') {
end = strchr(*value + 1, '"');
if (!end) {
DBG(READ, ul_debug("unbalanced quotes at: %s", *value));
*cp = *value;
return -BLKID_ERR_CACHE;
}
(*value)++;
*end = '\0';
end++;
} else {
end = skip_over_word(*value);
if (*end) {
*end = '\0';
end++;
}
}
*cp = end;
return 1;
}
| 15.388889 | 60 | 0.559567 | awsm-research |
82c6c8b697af5086554092edf799f341264df045 | 2,064 | cpp | C++ | src/_leetcode/leet_1104.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | src/_leetcode/leet_1104.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | src/_leetcode/leet_1104.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | /*
* ====================== leet_1104.cpp ==========================
* -- tpr --
* CREATE -- 2020.06.02
* MODIFY --
* ----------------------------------------------------------
* 1104. 二叉树寻路
*/
#include "innLeet.h"
#include "TreeNode1.h"
#include "ListNode.h"
namespace leet_1104 {//~
// 45% 100%
// 先生产 正常完全二叉树的 数组
// 然后把其中,反转的 层,修改下
class S{
std::vector<int> lvlLstIdxs {};//每层尾元素序号(基于1)
void init_lvlLstIdxs( int N ){
lvlLstIdxs.push_back(0);//[0]空置
int v = 1;
for( int i=1; i<=N; i++ ){
v *= 2;
lvlLstIdxs.push_back( v-1 );
}
}
// deep based on 1
int calc_mirror( int v, int deep ){
int l = lvlLstIdxs.at(deep-1)+1;
int r = lvlLstIdxs.at(deep);
return r-(v-l);
}
public:
std::vector<int> pathInZigZagTree( int label ){
//== 如果路径长度为 偶数,说明 最后一位所在的 行,也应该是反的
// 那就应该,先找到 label 对应的行内镜像值,在用这个镜像值,求出表。
int roadN = 0;
for( int i=label; i!=0; i>>=1 ){ roadN++; }
//== 准备好 lvlLstIdxs
init_lvlLstIdxs( roadN );
int target = (roadN&1)==0 ? calc_mirror(label,roadN) : label;
std::deque<int> que {};
for( int i=target; i!=0; i>>=1 ){
que.push_front(i);
}
std::vector<int> road (que.begin(), que.end());
// 将所有 偶数行 都取镜像值
for( int i=1; i<roadN-1; i++ ){// 尾部元素就算是偶数行 也先不管
if( (i&1)==1 ){// 只处理偶数
road.at(i) = calc_mirror( road.at(i), i+1 );
}
}
if( (roadN&1)==0 ){
road.back() = label;
}
return road;
}
};
// 方法2:
// 只计算 label 的镜像点
// 然后同时 生成两个点的 路径数组
// 最后将偶数位 交换一下
// 理论上这个方法会更快...
//=========================================================//
void main_(){
auto ret = S{}.pathInZigZagTree( 26 );
for( int i : ret ){
cout<<i<<", ";
}cout<<endl;
debug::log( "\n~~~~ leet: 1104 :end ~~~~\n" );
}
}//~
| 21.957447 | 69 | 0.419574 | turesnake |
82cac00fbe9e4525df27de88947d694f46f7391f | 3,062 | hpp | C++ | include/argumentative/argument/Argument.hpp | ViralTaco/Argumentative | 9dba6cb5de53df75616ec823d8dc211f0ec78296 | [
"MIT"
] | 1 | 2020-10-03T05:09:49.000Z | 2020-10-03T05:09:49.000Z | include/argumentative/argument/Argument.hpp | ViralTaco/Argumentative | 9dba6cb5de53df75616ec823d8dc211f0ec78296 | [
"MIT"
] | null | null | null | include/argumentative/argument/Argument.hpp | ViralTaco/Argumentative | 9dba6cb5de53df75616ec823d8dc211f0ec78296 | [
"MIT"
] | null | null | null | #ifndef VT_ARGUMENT_HPP
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ Argument.hpp: ┃
// ┃ Copyright (c) 2020 viraltaco_ ([email protected]) ┃
// ┃ https://github.com/ViralTaco ┃
// ┃ SPDX-License-Identifier: MIT ┃
// ┃ <http://www.opensource.org/licenses/MIT> ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
#define VT_ARGUMENT_HPP "2.2.1"
#include "../utils/typealias.hpp"
#include "../utils/swap_sign.hpp"
#include "errors/InvalidOption.hpp"
#include <string_view>
#include <string>
#include <iostream>
#include <iomanip>
#include <utility>
#include <algorithm>
namespace argumentative {
enum class ArgKind {
version,
option,
flag,
help
};
struct Argument {
public: // MARK: aliases
using Self = Argument;
public: // MARK: members
static constexpr auto kTag = "--";
ArgKind kind;
String name;
StringView help;
String description;
String value;
bool seen = false;
public: // MARK: init
Argument(ArgKind kind, StringView name, StringView help) noexcept
: kind{ kind }
, name{ String(kTag).append(name) }
, help{ help }
, description{ this->to_string() }
, value{ }
, seen{ kind == ArgKind::help or kind == ArgKind::version }
{}
Argument(StringView name, StringView help) noexcept
: Argument{ ArgKind::flag, name, help }
{}
Argument() noexcept = delete;
Argument(Self const&) noexcept = default;
Argument(Self&&) = default;
Argument& operator =(Self const&) noexcept = default;
virtual ~Argument() = default;
public: // MARK: instance methods
[[nodiscard]] String to_string() const {
auto str = StringStream();
str << '[' << name;
switch (kind) {
case ArgKind::option:
str << " <" << name.substr(2) << ">]";
break;
default:
str << ']';
break;
}
return str.str();
}
bool in(Vector<StringView> const& argv) {
const auto end = std::end(argv);
auto arg = std::find(std::begin(argv), end, this->name);
if (not (this->seen = arg != end)) {
return false;
} else if (kind == ArgKind::option) {
if ((++arg) != end) {
this->value = *arg;
} else {
throw InvalidOption(name);
}
}
return this->seen;
}
public: // MARK: operator overloads
explicit operator bool() const noexcept {
return seen;
}
Argument& operator =(String const& arg) {
value = arg;
return *this;
}
bool operator ==(StringView rhs) const noexcept {
return name == rhs;
}
bool operator ==(Argument const& rhs) const noexcept {
return name == rhs.name;
}
public: // MARK: friend operator overloads
friend std::ostream&
operator <<(std::ostream& out, Self const& self) noexcept {
const auto padding = 20 - self.name.length();
return out << self.name << std::setw((padding > 0) ? padding : 1)
<< std::right << '\t' << self.help;
}
};
} namespace ive = argumentative;
#endif
| 23.921875 | 70 | 0.567929 | ViralTaco |
82cd932e95e55306d18326596ec619fd1d01e2ca | 5,424 | cpp | C++ | extra/facs/cytolib/src/CytoFrameView.cpp | scignscape/PGVM | e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0 | [
"BSL-1.0"
] | null | null | null | extra/facs/cytolib/src/CytoFrameView.cpp | scignscape/PGVM | e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0 | [
"BSL-1.0"
] | null | null | null | extra/facs/cytolib/src/CytoFrameView.cpp | scignscape/PGVM | e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0 | [
"BSL-1.0"
] | null | null | null | // Copyright 2019 Fred Hutchinson Cancer Research Center
// See the included LICENSE file for details on the licence that is granted to the user of this software.
#include <cytolib/CytoFrameView.hpp>
#include <cytolib/global.hpp>
namespace cytolib
{
CytoFramePtr CytoFrameView::get_cytoframe_ptr() const{
if(ptr_)
return ptr_;
else
throw(domain_error("Empty CytoFrameView!"));
}
vector<string> CytoFrameView::get_channels() const{
vector<string> orig = get_cytoframe_ptr()->get_channels();
unsigned n = col_idx_.size();
if(!is_col_indexed_)
return orig;
else if(n == 0)
return vector<string>();
else
{
vector<string> res(n);
for(unsigned i = 0; i < n; i++)
res[i] = orig[col_idx_[i]];
return res;
}
}
vector<string> CytoFrameView::get_markers() const{
vector<string> orig = get_cytoframe_ptr()->get_markers();
unsigned n = col_idx_.size();
if(!is_col_indexed_)
return orig;
else if(n == 0)
return vector<string>();
else
{
vector<string> res(n);
for(unsigned i = 0; i < n; i++)
res[i] = orig[col_idx_[i]];
return res;
}
}
/*subsetting*/
void CytoFrameView::cols_(vector<string> colnames, ColType col_type)
{
uvec col_idx = get_cytoframe_ptr()->get_col_idx(colnames, col_type);//idx from original frame
if(is_col_indexed())//convert abs idex to relative indx
{
for(unsigned i = 0; i < col_idx.size(); i++)
{
auto it = std::find(col_idx_.begin(), col_idx_.end(), col_idx[i]);
if(it == col_idx_.end())
throw(domain_error(colnames[i] + " not present in the current cytoframeView!"));
col_idx[i] = it - col_idx_.begin();
}
}
//update params
CytoFrameView::cols_(col_idx);
}
/**
*
* @param col_idx column index relative to view
*/
void CytoFrameView::cols_(uvec col_idx)
{
if(col_idx.is_empty()){
col_idx_.reset();
}else{
unsigned max_idx = col_idx.max();
unsigned min_idx = col_idx.min();
if(max_idx >= n_cols() || min_idx < 0)
throw(domain_error("The size of the new col index is not within the original mat size!"));
if(is_col_indexed())//covert relative idx to abs idx
{
// cout << "indexing " << endl;
for(auto & i : col_idx)
{
// cout << "relative idx: " << i << " abs: " << col_idx_[i] << endl;
i = col_idx_[i];
}
}
col_idx_ = col_idx;
}
is_col_indexed_ = true;
}
void CytoFrameView::cols_(vector<unsigned> col_idx)
{
cols_(arma::conv_to<uvec>::from(col_idx));
}
void CytoFrameView::rows_(vector<unsigned> row_idx)
{
rows_(arma::conv_to<uvec>::from(row_idx));
}
void CytoFrameView::rows_(uvec row_idx)
{
if(row_idx.is_empty()){
row_idx_.reset();
}else{
unsigned max_idx = row_idx.max();
unsigned min_idx = row_idx.min();
if(max_idx >= n_rows() || min_idx < 0)
throw(domain_error("The size of the new row index ("
+ to_string(min_idx) + "," + to_string(min_idx)
+ ") is not within the original mat size (0, " + to_string(n_rows()) + ")"
)
);
if(is_row_indexed())
{
for(auto & i : row_idx)
i = row_idx_[i];
}
row_idx_ = row_idx;
}
is_row_indexed_ = true;
}
/**
* Corresponding to the original $Pn FCS TEXT
* @return
*/
vector<unsigned> CytoFrameView::get_original_col_ids() const
{
unsigned n = n_cols();
vector<unsigned> res(n);
for(unsigned i = 0; i < n; i++)
if(is_col_indexed())
res[i] = col_idx_[i];
else
res[i] = i;
return res;
}
unsigned CytoFrameView::n_cols() const
{
if(is_col_indexed_)
return col_idx_.size();
else
return get_cytoframe_ptr()->n_cols();
}
/**
* get the number of rows(or events)
* @return
*/
unsigned CytoFrameView::n_rows() const
{
//read nEvents
if(is_row_indexed_)
return row_idx_.size();
else
return get_cytoframe_ptr()->n_rows();
}
void CytoFrameView::set_data(const EVENT_DATA_VEC & data_in){
if(is_empty()){
// Setting empty to empty is an allowed no-op, but not setting empty to non-empty
if(!data_in.is_empty()){
throw(domain_error("Cannot assign non-empty input data to empty CytoFrameView!"));
}
}else{
//fetch the original view of data
EVENT_DATA_VEC data_orig = get_cytoframe_ptr()->get_data();
//update it
if(is_col_indexed_&&is_row_indexed_)
data_orig.submat(row_idx_, col_idx_) = data_in;
else if(is_row_indexed_)
data_orig.rows(row_idx_) = data_in;
else if(is_col_indexed_)
data_orig.cols(col_idx_) = data_in;
else
if(data_orig.n_cols!=data_in.n_cols||data_orig.n_rows!=data_in.n_rows)
throw(domain_error("The size of the input data is different from the cytoframeview!"));
else
data_orig = data_in;
//write back to ptr_
get_cytoframe_ptr()->set_data(data_orig);
}
}
EVENT_DATA_VEC CytoFrameView::get_data() const
{
EVENT_DATA_VEC data;
if(is_empty()){
data = EVENT_DATA_VEC(n_rows(), n_cols());
}else{
auto ptr = get_cytoframe_ptr();
if(is_col_indexed()&&is_row_indexed())
data = ptr->get_data(row_idx_, col_idx_);
else if(is_col_indexed())
{
data = ptr->get_data(col_idx_, true);
}else if(is_row_indexed())
data = ptr->get_data(row_idx_, false);
else
data = ptr->get_data();
}
return data;
}
CytoFrameView CytoFrameView::copy(const string & h5_filename) const
{
CytoFrameView cv(*this);
cv.ptr_ = get_cytoframe_ptr()->copy(h5_filename);
return cv;
}
};
| 24.542986 | 105 | 0.652102 | scignscape |
82d214d29af3a1269b0a24ccce5077b0da44502c | 7,135 | cpp | C++ | 3DRadSpace/3DRadSpaceDll/Model3D.cpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | 9 | 2017-01-10T11:47:06.000Z | 2021-11-27T14:32:55.000Z | 3DRadSpace/3DRadSpaceDll/Model3D.cpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | null | null | null | 3DRadSpace/3DRadSpaceDll/Model3D.cpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | 6 | 2017-07-08T23:03:43.000Z | 2022-03-08T07:47:13.000Z | #include "Model3D.hpp"
inline Engine3DRadSpace::VertexDeclDeterminantFlag Engine3DRadSpace::operator|(VertexDeclDeterminantFlag a, VertexDeclDeterminantFlag b)
{
return static_cast<VertexDeclDeterminantFlag>(static_cast<int>(a) | static_cast<int>(b));
}
inline Engine3DRadSpace::VertexDeclDeterminantFlag Engine3DRadSpace::operator|=(VertexDeclDeterminantFlag a, VertexDeclDeterminantFlag b)
{
return static_cast<VertexDeclDeterminantFlag>(static_cast<int>(a) | static_cast<int>(b));
}
inline Engine3DRadSpace::VertexDeclDeterminantFlag Engine3DRadSpace::operator&(VertexDeclDeterminantFlag a, VertexDeclDeterminantFlag b)
{
return static_cast<VertexDeclDeterminantFlag>(static_cast<int>(a) & static_cast<int>(b));
}
Engine3DRadSpace::Model3D::Model3D(Game* game, const char* file)
{
this->device = game->GetDevice();
this->context = game->GetDeviceContext();
this->_loaded = false;
Assimp::Importer importer;
aiScene* scene = (aiScene*)importer.ReadFile(file, aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_CalcTangentSpace | aiProcess_ImproveCacheLocality | aiProcess_RemoveRedundantMaterials | aiProcess_OptimizeMeshes | aiProcess_MakeLeftHanded | aiProcess_OptimizeGraph);
if (scene == nullptr)
throw ResourceCreationException("Failed to load the file!", typeid(Model3D));
NumMeshes = scene->mNumMeshes;
if (NumMeshes == 0 || !scene->HasMeshes())
throw ResourceCreationException("Attempted to load a model without any meshes!", typeid(Model3D));
Meshes = new MeshPart<void>*[NumMeshes];
MeshFlags = new VertexDeclDeterminantFlag[NumMeshes];
//NumTextures = scene->mNumTextures;
NumTextures = 0;
size_t i;
for (i = 0; i < scene->mNumMaterials; i++)
{
aiString loadpath;
aiReturn r = scene->mMaterials[i]->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &loadpath);
if (r != aiReturn::aiReturn_SUCCESS)
throw ResourceCreationException("Failed to load a model texture!", typeid(Texture2D));
else
NumTextures += 1;
}
Textures = new Texture2D * [NumTextures];
for (i = 0; i < scene->mNumMaterials; i++)
{
aiString loadpath;
aiReturn r = scene->mMaterials[i]->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &loadpath);
if (r == aiReturn::aiReturn_SUCCESS)
{
Textures[i] = new Texture2D(game, loadpath.C_Str());
}
else
throw ResourceCreationException("How did we get here?????", typeid(Texture2D));
}
/*
for (i = 0; i < NumTextures; i++)
{
if (scene->mTextures[i]->mHeight != 0)
{
this->Textures[i] = new Texture2D(game, scene->mTextures[i]->pcData, scene->mTextures[i]->mWidth * scene->mTextures[i]->mHeight);
}
}*/
for (i = 0; i < NumMeshes; i++)
{
//We won't allow creating lines, dots and empty meshes
if (!scene->mMeshes[i]->HasFaces() || scene->mMeshes[i]->mNumVertices < 2)
{
Meshes[i] = nullptr;
continue;
}
//determine the vertex buffer layout
MeshFlags[i] = VertexDeclDeterminantFlag::Position;
if (scene->mMeshes[i]->HasNormals()) MeshFlags[i] |= VertexDeclDeterminantFlag::Normal;
if (scene->mMeshes[i]->HasTangentsAndBitangents()) MeshFlags[i] |= VertexDeclDeterminantFlag::TangentBitangent;
unsigned NumVColors = scene->mMeshes[i]->GetNumUVChannels();
if (NumVColors == 1) MeshFlags[i] |= VertexDeclDeterminantFlag::SingleVertexColor;
else if (NumVColors > 1) throw ResourceCreationException("Multiple color channels not supported", typeid(Model3D));//MeshFlags[i] |= VertexDeclDeterminantFlag::MultipleVertexColors;
unsigned NumUV = scene->mMeshes[i]->GetNumUVChannels();
if (NumUV == 1) MeshFlags[i] |= VertexDeclDeterminantFlag::SingleUV;
else if (NumUV > 1) throw ResourceCreationException("Multiple UV channels not supported", typeid(Model3D));//MeshFlags[i] |= VertexDeclDeterminantFlag::MultipleUVs;
bool hasNormals = CheckVertexDeclDeterminant(MeshFlags[i], VertexDeclDeterminantFlag::Normal);
bool hasVertexColor = CheckVertexDeclDeterminant(MeshFlags[i], VertexDeclDeterminantFlag::SingleVertexColor);
bool hasTangentBitangent = CheckVertexDeclDeterminant(MeshFlags[i], VertexDeclDeterminantFlag::TangentBitangent);
bool hasUV = CheckVertexDeclDeterminant(MeshFlags[i], VertexDeclDeterminantFlag::SingleUV);
//determine vertex buffer size
size_t vertexbuffersize = scene->mMeshes[i]->mNumVertices;
size_t vertexdeclsize = sizeof(Vector4);
if (hasNormals)
vertexdeclsize += sizeof(Vector4);
if (hasVertexColor)
vertexdeclsize += sizeof(ColorShader);
if (hasTangentBitangent)
vertexdeclsize += 2 * sizeof(Vector4);
if (hasUV)
vertexdeclsize += sizeof(Vector4);
//create vertex buffer in memory
size_t finalvertexbuffersize = (vertexdeclsize * vertexbuffersize) / 4;
float* vertexbuffer = new float[finalvertexbuffersize];
//memset(vertexbuffer, 0, sizeof(float) * finalvertexbuffersize);
for (unsigned pos = 0, j = 0; pos < finalvertexbuffersize; j++)
{
memcpy_s(vertexbuffer + pos, sizeof(Vector3), &(scene->mMeshes[i]->mVertices[j]), sizeof(Vector3));
pos += 4;
if (hasNormals)
{
memcpy_s(vertexbuffer + pos, sizeof(Vector3), &(scene->mMeshes[i]->mNormals[j]), sizeof(Vector3));
pos += 4;
}
if (hasVertexColor)
{
memcpy_s(vertexbuffer + pos, sizeof(ColorShader), &(scene->mMeshes[i]->mColors[0][j]), sizeof(ColorShader));
pos += 4;
}
if (hasTangentBitangent)
{
memcpy_s(vertexbuffer + pos, sizeof(Vector3), &(scene->mMeshes[i]->mTangents[j]), sizeof(Vector3));
pos += 4;
memcpy_s(vertexbuffer + pos, sizeof(Vector3), &(scene->mMeshes[i]->mBitangents[j]), sizeof(Vector3));
pos += 4;
}
if (hasUV)
{
memcpy_s(vertexbuffer + pos, sizeof(Vector3), &(scene->mMeshes[i]->mTextureCoords[0][j]), sizeof(Vector3));
pos += 4;
}
}
//create index buffer
size_t indexbuffersize = scene->mMeshes[i]->mNumFaces * 3; //faces are triangulated, so multiply with 3
unsigned* indexbuffer = new unsigned[indexbuffersize];
for (unsigned j = 0; j < indexbuffersize; j += 3)
{
memcpy_s(indexbuffer + j, sizeof(unsigned) * 3, scene->mMeshes[i]->mFaces[j].mIndices, sizeof(unsigned) * 3);
}
VertexBuffer<void>* vertexbuffer_f = new VertexBuffer<void>(vertexbuffer, vertexbuffersize, vertexdeclsize);
IndexBuffer* indexbuffer_f = new IndexBuffer(indexbuffer, indexbuffersize);
this->Meshes[i] = new MeshPart<void>(vertexbuffer_f, indexbuffer_f, Textures[scene->mMeshes[i]->mMaterialIndex]);
this->_loaded = true;
}
}
bool Engine3DRadSpace::Model3D::CheckVertexDeclDeterminant(VertexDeclDeterminantFlag flag, VertexDeclDeterminantFlag comp)
{
return (comp == (flag & comp));
}
void Engine3DRadSpace::Model3D::Draw()
{
for (size_t i = 0; i < NumMeshes; i++)
{
this->Meshes[i]->Draw(context);
}
}
Engine3DRadSpace::Model3D::~Model3D()
{
size_t i;
for (i = 0; i < NumMeshes; i++)
{
if (this->Meshes[i] != nullptr) delete this->Meshes[i];
}
delete[] this->Meshes;
delete[] this->MeshFlags;
for (i = 0; i < NumTextures; i++)
{
if (this->Textures[i] != nullptr) delete this->Textures[i];
}
delete[] this->Textures;
this->Meshes = nullptr;
this->MeshFlags = nullptr;
this->Textures = nullptr;
}
| 34.97549 | 288 | 0.723616 | NicusorN5 |
82d5a6fa8fd7b4dec64b4eec6bc738bd3942a30c | 495 | cpp | C++ | app_v01/src/app/main.cpp | azaremde/cpp-opengl-gamedev | f4d02e955b401fc78321a23f91809662fefcda92 | [
"Apache-2.0"
] | null | null | null | app_v01/src/app/main.cpp | azaremde/cpp-opengl-gamedev | f4d02e955b401fc78321a23f91809662fefcda92 | [
"Apache-2.0"
] | null | null | null | app_v01/src/app/main.cpp | azaremde/cpp-opengl-gamedev | f4d02e955b401fc78321a23f91809662fefcda92 | [
"Apache-2.0"
] | null | null | null | #define ENGINE_DEBUG_MODE
#include "environment/window.h"
#include "layers/layer_manager.h"
#include "gui_layer.h"
#include "graphics_layer.h"
int main()
{
window_init();
layers::layer_manager.add_layer(new GUILayer());
layers::layer_manager.add_layer(new GraphicsLayer());
layers::layer_manager.init();
while (!window_should_close())
{
window_poll_events();
layers::layer_manager.update();
window_swap_buffers();
window_clear_state();
}
window_shutdown();
return 0;
} | 15.967742 | 54 | 0.735354 | azaremde |
82d6d7e6ab1bd78c0f800a5ab4cbfd7488b671f2 | 2,237 | cpp | C++ | folly/synchronization/test/BatonBenchmark.cpp | Aoikiseki/folly | df3633c731d08bab0173039a050a30853fb47212 | [
"Apache-2.0"
] | 19,046 | 2015-01-01T17:01:10.000Z | 2022-03-31T23:01:43.000Z | folly/synchronization/test/BatonBenchmark.cpp | Aoikiseki/folly | df3633c731d08bab0173039a050a30853fb47212 | [
"Apache-2.0"
] | 1,493 | 2015-01-11T15:47:13.000Z | 2022-03-28T18:13:58.000Z | folly/synchronization/test/BatonBenchmark.cpp | Aoikiseki/folly | df3633c731d08bab0173039a050a30853fb47212 | [
"Apache-2.0"
] | 4,818 | 2015-01-01T12:28:16.000Z | 2022-03-31T16:22:10.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/synchronization/Baton.h>
#include <thread>
#include <folly/Benchmark.h>
#include <folly/synchronization/NativeSemaphore.h>
#include <folly/synchronization/test/BatonTestHelpers.h>
#include <folly/test/DeterministicSchedule.h>
using namespace folly::test;
using folly::detail::EmulatedFutexAtomic;
BENCHMARK(baton_pingpong_blocking, iters) {
run_pingpong_test<true, std::atomic>(iters);
}
BENCHMARK(baton_pingpong_nonblocking, iters) {
run_pingpong_test<false, std::atomic>(iters);
}
BENCHMARK_DRAW_LINE();
BENCHMARK(baton_pingpong_emulated_futex_blocking, iters) {
run_pingpong_test<true, EmulatedFutexAtomic>(iters);
}
BENCHMARK(baton_pingpong_emulated_futex_nonblocking, iters) {
run_pingpong_test<false, EmulatedFutexAtomic>(iters);
}
BENCHMARK_DRAW_LINE();
BENCHMARK(native_sem_pingpong, iters) {
alignas(folly::hardware_destructive_interference_size)
folly::NativeSemaphore a;
alignas(folly::hardware_destructive_interference_size)
folly::NativeSemaphore b;
auto thr = std::thread([&] {
for (size_t i = 0; i < iters; ++i) {
a.wait();
b.post();
}
});
for (size_t i = 0; i < iters; ++i) {
a.post();
b.wait();
}
thr.join();
}
// I am omitting a benchmark result snapshot because these microbenchmarks
// mainly illustrate that PreBlockAttempts is very effective for rapid
// handoffs. The performance of Baton and sem_t is essentially identical
// to the required futex calls for the blocking case
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
folly::runBenchmarks();
return 0;
}
| 28.679487 | 75 | 0.738936 | Aoikiseki |
82d92d0839449f2e8ddbc75dbf81995fd62d2e80 | 4,706 | cpp | C++ | sensors/SensorBase.cpp | Huawei-mt6737/device | baec9804cf904c17d2abd45a1ecddde384ec22b7 | [
"FTL"
] | 2 | 2018-12-24T09:37:43.000Z | 2019-09-22T13:55:54.000Z | sensors/SensorBase.cpp | Huawei-mt6737/device | baec9804cf904c17d2abd45a1ecddde384ec22b7 | [
"FTL"
] | null | null | null | sensors/SensorBase.cpp | Huawei-mt6737/device | baec9804cf904c17d2abd45a1ecddde384ec22b7 | [
"FTL"
] | 8 | 2017-07-05T17:09:28.000Z | 2019-03-04T09:37:45.000Z | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2012. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/select.h>
#include <cutils/log.h>
#include <linux/input.h>
#include "SensorBase.h"
#include <utils/SystemClock.h>
#include <string.h>
#ifdef LOG_TAG
#undef LOG_TAG
#define LOG_TAG "SensorBase"
#endif
/*****************************************************************************/
SensorBase::SensorBase(
const char* dev_name,
const char* data_name)
: dev_name(dev_name), data_name(data_name),
dev_fd(-1), data_fd(-1)
{
//data_fd = openInput(data_name);
}
SensorBase::~SensorBase() {
if (data_fd >= 0) {
close(data_fd);
}
if (dev_fd >= 0) {
close(dev_fd);
}
}
int SensorBase::open_device() {
if (dev_fd<0 && dev_name) {
dev_fd = open(dev_name, O_RDONLY);
ALOGE_IF(dev_fd<0, "Couldn't open %s (%s)", dev_name, strerror(errno));
}
return 0;
}
int SensorBase::close_device() {
if (dev_fd >= 0) {
close(dev_fd);
dev_fd = -1;
}
return 0;
}
int SensorBase::getFd() const {
return data_fd;
}
int SensorBase::setDelay(int32_t handle, int64_t ns) {
ALOGD("handle=%d,ns=%lld\n",handle,ns);
return 0;
}
bool SensorBase::hasPendingEvents() const {
return false;
}
int64_t SensorBase::getTimestamp() {
return android::elapsedRealtimeNano();
}
/*
int SensorBase::openInput(const char* inputName) {
int fd = -1;
const char *dirname = "/dev/input";
char devname[PATH_MAX];
char *filename;
DIR *dir;
struct dirent *de;
dir = opendir(dirname);
if(dir == NULL)
return -1;
strcpy(devname, dirname);
filename = devname + strlen(devname);
*filename++ = '/';
while((de = readdir(dir))) {
if(de->d_name[0] == '.' &&
(de->d_name[1] == '\0' ||
(de->d_name[1] == '.' && de->d_name[2] == '\0')))
continue;
strcpy(filename, de->d_name);
fd = open(devname, O_RDONLY);
if (fd>=0) {
char name[80];
if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) < 1) {
name[0] = '\0';
}
if (!strcmp(name, inputName)) {
break;
} else {
close(fd);
fd = -1;
}
}
}
closedir(dir);
ALOGE_IF(fd<0, "couldn't find '%s' input device", inputName);
return fd;
}
*/
| 32.232877 | 95 | 0.649809 | Huawei-mt6737 |
82dc868342959ab731cfcb77da1bec85da90bd70 | 2,054 | cpp | C++ | HazelGameEngine/src/Platform/OpenGL/OpenGLVertexArray.cpp | duo131/Hazel_practice | 04eeec2550b9536e7b8a565d67630c1d2a669991 | [
"Apache-2.0"
] | null | null | null | HazelGameEngine/src/Platform/OpenGL/OpenGLVertexArray.cpp | duo131/Hazel_practice | 04eeec2550b9536e7b8a565d67630c1d2a669991 | [
"Apache-2.0"
] | null | null | null | HazelGameEngine/src/Platform/OpenGL/OpenGLVertexArray.cpp | duo131/Hazel_practice | 04eeec2550b9536e7b8a565d67630c1d2a669991 | [
"Apache-2.0"
] | null | null | null | #include "hzpch.h"
#include "OpenGLVertexArray.h"
#include <glad/glad.h>
namespace Hazel {
//temp function
static GLenum ShaderDataTypeToOpenGLBaseType(ShaderDataType type)
{
switch (type)
{
case ShaderDataType::NONE: break;
case ShaderDataType::FLOAT: return GL_FLOAT;
case ShaderDataType::FLOAT2: return GL_FLOAT;
case ShaderDataType::FLOAT3: return GL_FLOAT;
case ShaderDataType::FLOAT4: return GL_FLOAT;
case ShaderDataType::MAT3: return GL_FLOAT;
case ShaderDataType::MAT4: return GL_FLOAT;
case ShaderDataType::INT: return GL_INT;
case ShaderDataType::INT2: return GL_INT;
case ShaderDataType::INT3: return GL_INT;
case ShaderDataType::INT4: return GL_INT;
case ShaderDataType::BOOL: return GL_BOOL;
default: break;
}
HZ_CORE_ASSERT(false, "Unknow ShaderDataType!");
return 0;
}
OpenGLVertexArray::OpenGLVertexArray()
{
glCreateVertexArrays(1, &m_RendererID);
}
OpenGLVertexArray::~OpenGLVertexArray()
{
glDeleteVertexArrays(1, &m_RendererID);
}
void OpenGLVertexArray::Bind() const
{
glBindVertexArray(m_RendererID);
}
void OpenGLVertexArray::UnBind() const
{
glBindVertexArray(0);
}
void OpenGLVertexArray::AddVertexBuffer(const Ref<VertexBuffer>& vertexBuffer)
{
HZ_CORE_ASSERT(vertexBuffer->GetLaypout().GetElements().size(), "VertexBuffer has no layout");
glBindVertexArray(m_RendererID);
vertexBuffer->Bind();
uint32_t index = 0;
for (const auto& element : vertexBuffer->GetLaypout())
{
glEnableVertexAttribArray(index);
// no normalize
glVertexAttribPointer(index,
element.GetElementCount(),
ShaderDataTypeToOpenGLBaseType(element.Type),
element.Normalized ? GL_TRUE : GL_FALSE,
vertexBuffer->GetLaypout().GetStride(),
(const void*)element.Offset);
index++;
}
m_VertexBuffers.push_back(vertexBuffer);
}
void OpenGLVertexArray::SetIndexBuffer(const Ref<IndexBuffer>& indexBuffer)
{
glBindVertexArray(m_RendererID);
indexBuffer->Bind();
m_IndexBuffer = indexBuffer;
}
} | 24.164706 | 96 | 0.731256 | duo131 |
82dd0a742a3e6f7fd1298001e6f365b5ea428afc | 80,114 | cc | C++ | EnergyPlus/HighTempRadiantSystem.cc | yurigabrich/EnergyPlusShadow | 396ca83aa82b842e6b177ba35c91b3f481dfbbf9 | [
"BSD-3-Clause"
] | null | null | null | EnergyPlus/HighTempRadiantSystem.cc | yurigabrich/EnergyPlusShadow | 396ca83aa82b842e6b177ba35c91b3f481dfbbf9 | [
"BSD-3-Clause"
] | 1 | 2020-07-08T13:32:09.000Z | 2020-07-08T13:32:09.000Z | EnergyPlus/HighTempRadiantSystem.cc | yurigabrich/EnergyPlusShadow | 396ca83aa82b842e6b177ba35c91b3f481dfbbf9 | [
"BSD-3-Clause"
] | null | null | null | // EnergyPlus, Copyright (c) 1996-2018, The Board of Trustees of the University of Illinois,
// The Regents of the University of California, through Lawrence Berkeley National Laboratory
// (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge
// National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other
// contributors. All rights reserved.
//
// NOTICE: This Software was developed under funding from the U.S. Department of Energy and the
// U.S. Government consequently retains certain rights. As such, the U.S. Government has been
// granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable,
// worldwide license in the Software to reproduce, distribute copies to the public, prepare
// derivative works, and perform publicly and display publicly, and to permit others to do so.
//
// 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 University of California, Lawrence Berkeley National Laboratory,
// the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form
// without changes from the version obtained under this License, or (ii) Licensee makes a
// reference solely to the software portion of its product, Licensee must refer to the
// software as "EnergyPlus version X" software, where "X" is the version number Licensee
// obtained under this License and may not use a different name for the software. Except as
// specifically required in this Section (4), Licensee shall not use in a company name, a
// product name, in advertising, publicity, or other promotional activities any name, trade
// name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly
// similar designation, without the U.S. Department of Energy's prior written consent.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// C++ Headers
#include <cassert>
#include <cmath>
// ObjexxFCL Headers
#include <ObjexxFCL/Array.functions.hh>
// EnergyPlus Headers
#include <DataHVACGlobals.hh>
#include <DataHeatBalFanSys.hh>
#include <DataHeatBalSurface.hh>
#include <DataHeatBalance.hh>
#include <DataIPShortCuts.hh>
#include <DataLoopNode.hh>
#include <DataPrecisionGlobals.hh>
#include <DataSizing.hh>
#include <DataSurfaces.hh>
#include <DataZoneEnergyDemands.hh>
#include <DataZoneEquipment.hh>
#include <General.hh>
#include <GeneralRoutines.hh>
#include <HeatBalanceSurfaceManager.hh>
#include <HighTempRadiantSystem.hh>
#include <InputProcessing/InputProcessor.hh>
#include <OutputProcessor.hh>
#include <ReportSizingManager.hh>
#include <ScheduleManager.hh>
#include <UtilityRoutines.hh>
namespace EnergyPlus {
namespace HighTempRadiantSystem {
// Module containing the routines dealing with the high temperature radiant systems
// MODULE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS MODULE:
// The purpose of this module is to simulate high temperature radiant systems.
// It is the intention of this module to cover all types of high temperature
// radiant systems (gas and electric)
// METHODOLOGY EMPLOYED:
// Based on work done in BLAST, the EnergyPlus low temperature radiant system
// model, this model has similar inherent challenges that are similar to the
// low temperature radiant system. Because it is a system that directly
// effects the surface heat balances, it must be a part of both the heat
// balance routines and linked in with the HVAC system.
// REFERENCES:
// Building Systems Laboratory, BLAST User's Guide/Reference.
// Maloney, Dan. 1987. "Development of a radiant heater model and the
// incorporation of thermal comfort considerations into the BLAST
// energy analysis program", M.S. thesis, University of Illinois at
// Urbana-Champaign (Dept. of Mechanical and Industrial Engineering).
// OTHER NOTES: none
// USE STATEMENTS:
// Use statements for data only modules
// Using/Aliasing
using namespace DataPrecisionGlobals;
using DataGlobals::BeginTimeStepFlag;
using DataGlobals::DisplayExtraWarnings;
using DataGlobals::ScheduleAlwaysOn;
using DataGlobals::SysSizingCalc;
using DataHVACGlobals::SmallLoad;
// Data
// MODULE PARAMETER DEFINITIONS:
std::string const cGas("Gas");
std::string const cNaturalGas("NaturalGas");
std::string const cElectric("Electric");
std::string const cElectricity("Electricity");
int const Gas(1);
int const Electric(2);
std::string const cMATControl("MeanAirTemperature"); // Control for using mean air temperature
std::string const cMRTControl("MeanRadiantTemperature"); // Control for using mean radiant temperature
std::string const cOperativeControl("OperativeTemperature"); // Control for using operative temperature
std::string const cMATSPControl("MeanAirTemperatureSetpoint"); // Control for to MAT setpoint
std::string const cMRTSPControl("MeanRadiantTemperatureSetpoint"); // Control for to MRT setpoint
std::string const cOperativeSPControl("OperativeTemperatureSetpoint"); // Control for operative temperature setpoint
int const MATControl(1001);
int const MRTControl(1002);
int const OperativeControl(1003);
int const MATSPControl(1004);
int const MRTSPControl(1005);
int const OperativeSPControl(1006);
static std::string const BlankString;
// DERIVED TYPE DEFINITIONS:
// MODULE VARIABLE DECLARATIONS:
// Standard, run-of-the-mill variables...
int NumOfHighTempRadSys(0); // Number of hydronic low tempererature radiant systems
Array1D<Real64> QHTRadSource; // Need to keep the last value in case we are still iterating
Array1D<Real64> QHTRadSrcAvg; // Need to keep the last value in case we are still iterating
Array1D<Real64> ZeroSourceSumHATsurf; // Equal to the SumHATsurf for all the walls in a zone with no source
// Record keeping variables used to calculate QHTRadSrcAvg locally
Array1D<Real64> LastQHTRadSrc; // Need to keep the last value in case we are still iterating
Array1D<Real64> LastSysTimeElapsed; // Need to keep the last value in case we are still iterating
Array1D<Real64> LastTimeStepSys; // Need to keep the last value in case we are still iterating
Array1D_bool MySizeFlag;
Array1D_bool CheckEquipName;
// SUBROUTINE SPECIFICATIONS FOR MODULE HighTempRadiantSystem
// Object Data
Array1D<HighTempRadiantSystemData> HighTempRadSys;
Array1D<HighTempRadSysNumericFieldData> HighTempRadSysNumericFields;
// Functions
void clear_state()
{
NumOfHighTempRadSys = 0;
QHTRadSource.deallocate();
QHTRadSrcAvg.deallocate();
ZeroSourceSumHATsurf.deallocate();
LastQHTRadSrc.deallocate();
LastSysTimeElapsed.deallocate();
LastTimeStepSys.deallocate();
MySizeFlag.deallocate();
CheckEquipName.deallocate();
HighTempRadSys.deallocate();
HighTempRadSysNumericFields.deallocate();
}
void SimHighTempRadiantSystem(std::string const &CompName, // name of the low temperature radiant system
bool const FirstHVACIteration, // TRUE if 1st HVAC simulation of system timestep
Real64 &LoadMet, // load met by the radiant system, in Watts
int &CompIndex)
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine is the "manager" for the high temperature radiant
// system model. It is called from the outside and controls the
// actions and subroutine calls to lower levels as appropriate.
// METHODOLOGY EMPLOYED:
// Standard EnergyPlus manager subroutine layout
// Using/Aliasing
using General::TrimSigDigits;
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
static bool GetInputFlag(true); // First time, input is "gotten"
bool ErrorsFoundInGet; // Set to true when there are severe errors during the Get routine
int RadSysNum; // Radiant system number/index in local derived types
// FLOW:
if (GetInputFlag) {
ErrorsFoundInGet = false;
GetHighTempRadiantSystem(ErrorsFoundInGet);
if (ErrorsFoundInGet) ShowFatalError("GetHighTempRadiantSystem: Errors found in input. Preceding condition(s) cause termination.");
GetInputFlag = false;
}
// Find the correct ZoneHVAC:HighTemperatureRadiant
if (CompIndex == 0) {
RadSysNum = UtilityRoutines::FindItemInList(CompName, HighTempRadSys);
if (RadSysNum == 0) {
ShowFatalError("SimHighTempRadiantSystem: Unit not found=" + CompName);
}
CompIndex = RadSysNum;
} else {
RadSysNum = CompIndex;
if (RadSysNum > NumOfHighTempRadSys || RadSysNum < 1) {
ShowFatalError("SimHighTempRadiantSystem: Invalid CompIndex passed=" + TrimSigDigits(RadSysNum) +
", Number of Units=" + TrimSigDigits(NumOfHighTempRadSys) + ", Entered Unit name=" + CompName);
}
if (CheckEquipName(RadSysNum)) {
if (CompName != HighTempRadSys(RadSysNum).Name) {
ShowFatalError("SimHighTempRadiantSystem: Invalid CompIndex passed=" + TrimSigDigits(RadSysNum) + ", Unit name=" + CompName +
", stored Unit Name for that index=" + HighTempRadSys(RadSysNum).Name);
}
CheckEquipName(RadSysNum) = false;
}
}
InitHighTempRadiantSystem(FirstHVACIteration, RadSysNum);
{
auto const SELECT_CASE_var(HighTempRadSys(RadSysNum).ControlType);
if ((SELECT_CASE_var == MATControl) || (SELECT_CASE_var == MRTControl) || (SELECT_CASE_var == OperativeControl)) {
CalcHighTempRadiantSystem(RadSysNum);
} else if ((SELECT_CASE_var == MATSPControl) || (SELECT_CASE_var == MRTSPControl) || (SELECT_CASE_var == OperativeSPControl)) {
CalcHighTempRadiantSystemSP(FirstHVACIteration, RadSysNum);
}
}
UpdateHighTempRadiantSystem(RadSysNum, LoadMet);
ReportHighTempRadiantSystem(RadSysNum);
}
void GetHighTempRadiantSystem(bool &ErrorsFound // TRUE if errors are found on processing the input
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine reads the input for high temperature radiant systems
// from the user input file. This will contain all of the information
// needed to simulate a high temperature radiant system.
// METHODOLOGY EMPLOYED:
// Standard EnergyPlus methodology.
// Using/Aliasing
using DataHeatBalance::Zone;
using DataSizing::AutoSize;
using DataSizing::CapacityPerFloorArea;
using DataSizing::FractionOfAutosizedHeatingCapacity;
using DataSizing::HeatingDesignCapacity;
using DataSurfaces::Surface;
using General::TrimSigDigits;
using ScheduleManager::GetScheduleIndex;
using namespace DataIPShortCuts;
// SUBROUTINE PARAMETER DEFINITIONS:
Real64 const MaxCombustionEffic(1.00); // Limit the combustion efficiency to perfection
Real64 const MaxFraction(1.0); // Limit the highest allowed fraction for heat transfer parts
Real64 const MinCombustionEffic(0.01); // Limit the minimum combustion efficiency
Real64 const MinFraction(0.0); // Limit the lowest allowed fraction for heat transfer parts
Real64 const MinThrottlingRange(0.5); // Smallest throttling range allowed in degrees Celsius
// INTEGER, PARAMETER :: MaxDistribSurfaces = 20 ! Maximum number of surfaces that a radiant heater can radiate to
static std::string const RoutineName("GetHighTempRadiantSystem: "); // include trailing blank space
int const iHeatCAPMAlphaNum(4); // get input index to High Temperature Radiant system heating capacity sizing method
int const iHeatDesignCapacityNumericNum(1); // get input index to High Temperature Radiant system heating capacity
int const iHeatCapacityPerFloorAreaNumericNum(2); // get input index to High Temperature Radiant system heating capacity per floor area sizing
int const iHeatFracOfAutosizedCapacityNumericNum(
3); // get input index to High Temperature Radiant system heating capacity sizing as fraction of autozized heating capacity
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
Real64 AllFracsSummed; // Sum of the fractions radiant, latent, and lost (must be <= 1)
Real64 FracOfRadPotentiallyLost; // Difference between unity and AllFracsSummed for error reporting
int IOStatus; // Used in GetObjectItem
int Item; // Item to be "gotten"
int NumAlphas; // Number of Alphas for each GetObjectItem call
int NumNumbers; // Number of Numbers for each GetObjectItem call
int SurfNum; // Surface number DO loop counter
Real64 TotalFracToSurfs; // Sum of fractions of radiation to surfaces
// FLOW:
// Initializations and allocations
NumOfHighTempRadSys = inputProcessor->getNumObjectsFound("ZoneHVAC:HighTemperatureRadiant");
HighTempRadSys.allocate(NumOfHighTempRadSys);
CheckEquipName.allocate(NumOfHighTempRadSys);
HighTempRadSysNumericFields.allocate(NumOfHighTempRadSys);
CheckEquipName = true;
// extensible object, do not need max args because using IPShortCuts
cCurrentModuleObject = "ZoneHVAC:HighTemperatureRadiant";
// Obtain all of the user data related to high temperature radiant systems...
for (Item = 1; Item <= NumOfHighTempRadSys; ++Item) {
inputProcessor->getObjectItem(cCurrentModuleObject,
Item,
cAlphaArgs,
NumAlphas,
rNumericArgs,
NumNumbers,
IOStatus,
lNumericFieldBlanks,
lAlphaFieldBlanks,
cAlphaFieldNames,
cNumericFieldNames);
HighTempRadSysNumericFields(Item).FieldNames.allocate(NumNumbers);
HighTempRadSysNumericFields(Item).FieldNames = "";
HighTempRadSysNumericFields(Item).FieldNames = cNumericFieldNames;
UtilityRoutines::IsNameEmpty(cAlphaArgs(1), cCurrentModuleObject, ErrorsFound);
// General user input data
HighTempRadSys(Item).Name = cAlphaArgs(1);
HighTempRadSys(Item).SchedName = cAlphaArgs(2);
if (lAlphaFieldBlanks(2)) {
HighTempRadSys(Item).SchedPtr = ScheduleAlwaysOn;
} else {
HighTempRadSys(Item).SchedPtr = GetScheduleIndex(cAlphaArgs(2));
if (HighTempRadSys(Item).SchedPtr == 0) {
ShowSevereError(cCurrentModuleObject + ": invalid " + cAlphaFieldNames(2) + " entered =" + cAlphaArgs(2) + " for " +
cAlphaFieldNames(1) + " = " + cAlphaArgs(1));
ErrorsFound = true;
}
}
HighTempRadSys(Item).ZoneName = cAlphaArgs(3);
HighTempRadSys(Item).ZonePtr = UtilityRoutines::FindItemInList(cAlphaArgs(3), Zone);
if (HighTempRadSys(Item).ZonePtr == 0) {
ShowSevereError("Invalid " + cAlphaFieldNames(3) + " = " + cAlphaArgs(3));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
}
// HighTempRadSys( Item ).MaxPowerCapac = rNumericArgs( 1 );
// Determine High Temp Radiant heating design capacity sizing method
if (UtilityRoutines::SameString(cAlphaArgs(iHeatCAPMAlphaNum), "HeatingDesignCapacity")) {
HighTempRadSys(Item).HeatingCapMethod = HeatingDesignCapacity;
if (!lNumericFieldBlanks(iHeatDesignCapacityNumericNum)) {
HighTempRadSys(Item).ScaledHeatingCapacity = rNumericArgs(iHeatDesignCapacityNumericNum);
if (HighTempRadSys(Item).ScaledHeatingCapacity < 0.0 && HighTempRadSys(Item).ScaledHeatingCapacity != AutoSize) {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Illegal " + cNumericFieldNames(iHeatDesignCapacityNumericNum) + " = " +
TrimSigDigits(rNumericArgs(iHeatDesignCapacityNumericNum), 7));
ErrorsFound = true;
}
} else {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Input for " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ShowContinueError("Blank field not allowed for " + cNumericFieldNames(iHeatDesignCapacityNumericNum));
ErrorsFound = true;
}
} else if (UtilityRoutines::SameString(cAlphaArgs(iHeatCAPMAlphaNum), "CapacityPerFloorArea")) {
HighTempRadSys(Item).HeatingCapMethod = CapacityPerFloorArea;
if (!lNumericFieldBlanks(iHeatCapacityPerFloorAreaNumericNum)) {
HighTempRadSys(Item).ScaledHeatingCapacity = rNumericArgs(iHeatCapacityPerFloorAreaNumericNum);
if (HighTempRadSys(Item).ScaledHeatingCapacity <= 0.0) {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Input for " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ShowContinueError("Illegal " + cNumericFieldNames(iHeatCapacityPerFloorAreaNumericNum) + " = " +
TrimSigDigits(rNumericArgs(iHeatCapacityPerFloorAreaNumericNum), 7));
ErrorsFound = true;
} else if (HighTempRadSys(Item).ScaledHeatingCapacity == AutoSize) {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Input for " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ShowContinueError("Illegal " + cNumericFieldNames(iHeatCapacityPerFloorAreaNumericNum) + " = Autosize");
ErrorsFound = true;
}
} else {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Input for " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ShowContinueError("Blank field not allowed for " + cNumericFieldNames(iHeatCapacityPerFloorAreaNumericNum));
ErrorsFound = true;
}
} else if (UtilityRoutines::SameString(cAlphaArgs(iHeatCAPMAlphaNum), "FractionOfAutosizedHeatingCapacity")) {
HighTempRadSys(Item).HeatingCapMethod = FractionOfAutosizedHeatingCapacity;
if (!lNumericFieldBlanks(iHeatFracOfAutosizedCapacityNumericNum)) {
HighTempRadSys(Item).ScaledHeatingCapacity = rNumericArgs(iHeatFracOfAutosizedCapacityNumericNum);
if (HighTempRadSys(Item).ScaledHeatingCapacity < 0.0) {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Illegal " + cNumericFieldNames(iHeatFracOfAutosizedCapacityNumericNum) + " = " +
TrimSigDigits(rNumericArgs(iHeatFracOfAutosizedCapacityNumericNum), 7));
ErrorsFound = true;
}
} else {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Input for " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ShowContinueError("Blank field not allowed for " + cNumericFieldNames(iHeatFracOfAutosizedCapacityNumericNum));
ErrorsFound = true;
}
} else {
ShowSevereError(cCurrentModuleObject + " = " + HighTempRadSys(Item).Name);
ShowContinueError("Illegal " + cAlphaFieldNames(iHeatCAPMAlphaNum) + " = " + cAlphaArgs(iHeatCAPMAlphaNum));
ErrorsFound = true;
}
if (UtilityRoutines::SameString(cAlphaArgs(5), cNaturalGas)) {
HighTempRadSys(Item).HeaterType = Gas;
} else if (UtilityRoutines::SameString(cAlphaArgs(5), cElectricity)) {
HighTempRadSys(Item).HeaterType = Electric;
} else if (UtilityRoutines::SameString(cAlphaArgs(5), cGas)) {
HighTempRadSys(Item).HeaterType = Gas;
} else if (UtilityRoutines::SameString(cAlphaArgs(5), cElectric)) {
HighTempRadSys(Item).HeaterType = Electric;
} else {
ShowSevereError("Invalid " + cAlphaFieldNames(5) + " = " + cAlphaArgs(5));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
}
if (HighTempRadSys(Item).HeaterType == Gas) {
HighTempRadSys(Item).CombustionEffic = rNumericArgs(4);
// Limit the combustion efficiency to between zero and one...
if (HighTempRadSys(Item).CombustionEffic < MinCombustionEffic) {
HighTempRadSys(Item).CombustionEffic = MinCombustionEffic;
ShowWarningError(cNumericFieldNames(4) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).CombustionEffic > MaxCombustionEffic) {
HighTempRadSys(Item).CombustionEffic = MaxCombustionEffic;
ShowWarningError(cNumericFieldNames(4) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
} else {
HighTempRadSys(Item).CombustionEffic = MaxCombustionEffic; // No inefficiency in the heater
}
HighTempRadSys(Item).FracRadiant = rNumericArgs(5);
if (HighTempRadSys(Item).FracRadiant < MinFraction) {
HighTempRadSys(Item).FracRadiant = MinFraction;
ShowWarningError(cNumericFieldNames(5) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).FracRadiant > MaxFraction) {
HighTempRadSys(Item).FracRadiant = MaxFraction;
ShowWarningError(cNumericFieldNames(5) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
HighTempRadSys(Item).FracLatent = rNumericArgs(6);
if (HighTempRadSys(Item).FracLatent < MinFraction) {
HighTempRadSys(Item).FracLatent = MinFraction;
ShowWarningError(cNumericFieldNames(6) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).FracLatent > MaxFraction) {
HighTempRadSys(Item).FracLatent = MaxFraction;
ShowWarningError(cNumericFieldNames(6) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
HighTempRadSys(Item).FracLost = rNumericArgs(7);
if (HighTempRadSys(Item).FracLost < MinFraction) {
HighTempRadSys(Item).FracLost = MinFraction;
ShowWarningError(cNumericFieldNames(7) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).FracLost > MaxFraction) {
HighTempRadSys(Item).FracLost = MaxFraction;
ShowWarningError(cNumericFieldNames(7) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
// Based on the input for fractions radiant, latent, and lost, determine the fraction convective (remaining fraction)
AllFracsSummed = HighTempRadSys(Item).FracRadiant + HighTempRadSys(Item).FracLatent + HighTempRadSys(Item).FracLost;
if (AllFracsSummed > MaxFraction) {
ShowSevereError("Fractions radiant, latent, and lost sum up to greater than 1 for" + cAlphaArgs(1));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
HighTempRadSys(Item).FracConvect = 0.0;
} else {
HighTempRadSys(Item).FracConvect = 1.0 - AllFracsSummed;
}
// Process the temperature control type
if (UtilityRoutines::SameString(cAlphaArgs(6), cMATControl)) {
HighTempRadSys(Item).ControlType = MATControl;
} else if (UtilityRoutines::SameString(cAlphaArgs(6), cMRTControl)) {
HighTempRadSys(Item).ControlType = MRTControl;
} else if (UtilityRoutines::SameString(cAlphaArgs(6), cOperativeControl)) {
HighTempRadSys(Item).ControlType = OperativeControl;
} else if (UtilityRoutines::SameString(cAlphaArgs(6), cMATSPControl)) {
HighTempRadSys(Item).ControlType = MATSPControl;
} else if (UtilityRoutines::SameString(cAlphaArgs(6), cMRTSPControl)) {
HighTempRadSys(Item).ControlType = MRTSPControl;
} else if (UtilityRoutines::SameString(cAlphaArgs(6), cOperativeSPControl)) {
HighTempRadSys(Item).ControlType = OperativeSPControl;
} else {
ShowWarningError("Invalid " + cAlphaFieldNames(6) + " = " + cAlphaArgs(6));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ShowContinueError("Control reset to OPERATIVE control for this " + cCurrentModuleObject);
HighTempRadSys(Item).ControlType = OperativeControl;
}
HighTempRadSys(Item).ThrottlRange = rNumericArgs(8);
if (HighTempRadSys(Item).ThrottlRange < MinThrottlingRange) {
HighTempRadSys(Item).ThrottlRange = 1.0;
ShowWarningError(cNumericFieldNames(8) + " is below the minimum allowed.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ShowContinueError("Thus, the throttling range value has been reset to 1.0");
}
HighTempRadSys(Item).SetptSched = cAlphaArgs(7);
HighTempRadSys(Item).SetptSchedPtr = GetScheduleIndex(cAlphaArgs(7));
if ((HighTempRadSys(Item).SetptSchedPtr == 0) && (!lAlphaFieldBlanks(7))) {
ShowSevereError(cAlphaFieldNames(7) + " not found: " + cAlphaArgs(7));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
}
HighTempRadSys(Item).FracDistribPerson = rNumericArgs(9);
if (HighTempRadSys(Item).FracDistribPerson < MinFraction) {
HighTempRadSys(Item).FracDistribPerson = MinFraction;
ShowWarningError(cNumericFieldNames(9) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).FracDistribPerson > MaxFraction) {
HighTempRadSys(Item).FracDistribPerson = MaxFraction;
ShowWarningError(cNumericFieldNames(9) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
HighTempRadSys(Item).TotSurfToDistrib = NumNumbers - 9;
// IF (HighTempRadSys(Item)%TotSurfToDistrib > MaxDistribSurfaces) THEN
// CALL ShowSevereError('Trying to distribute radiant energy to too many surfaces for heater '//TRIM(cAlphaArgs(1)))
// CALL ShowContinueError('Occurs for '//TRIM(cCurrentModuleObject)//' = '//TRIM(cAlphaArgs(1)))
// ErrorsFound=.TRUE.
// END IF
HighTempRadSys(Item).SurfaceName.allocate(HighTempRadSys(Item).TotSurfToDistrib);
HighTempRadSys(Item).SurfacePtr.allocate(HighTempRadSys(Item).TotSurfToDistrib);
HighTempRadSys(Item).FracDistribToSurf.allocate(HighTempRadSys(Item).TotSurfToDistrib);
AllFracsSummed = HighTempRadSys(Item).FracDistribPerson;
for (SurfNum = 1; SurfNum <= HighTempRadSys(Item).TotSurfToDistrib; ++SurfNum) {
HighTempRadSys(Item).SurfaceName(SurfNum) = cAlphaArgs(SurfNum + 7);
HighTempRadSys(Item).SurfacePtr(SurfNum) = UtilityRoutines::FindItemInList(cAlphaArgs(SurfNum + 7), Surface);
HighTempRadSys(Item).FracDistribToSurf(SurfNum) = rNumericArgs(SurfNum + 9);
// Error trap for surfaces that do not exist or surfaces not in the zone the radiant heater is in
if (HighTempRadSys(Item).SurfacePtr(SurfNum) == 0) {
ShowSevereError(RoutineName + "Invalid Surface name = " + HighTempRadSys(Item).SurfaceName(SurfNum));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
} else if (Surface(HighTempRadSys(Item).SurfacePtr(SurfNum)).Zone != HighTempRadSys(Item).ZonePtr) {
ShowWarningError("Surface referenced in ZoneHVAC:HighTemperatureRadiant not in same zone as Radiant System, surface=" +
HighTempRadSys(Item).SurfaceName(SurfNum));
ShowContinueError("Surface is in Zone=" + Zone(Surface(HighTempRadSys(Item).SurfacePtr(SurfNum)).Zone).Name +
" ZoneHVAC:HighTemperatureRadiant in Zone=" + cAlphaArgs(3));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
// Error trap for fractions that are out of range
if (HighTempRadSys(Item).FracDistribToSurf(SurfNum) < MinFraction) {
HighTempRadSys(Item).FracDistribToSurf(SurfNum) = MinFraction;
ShowWarningError(cNumericFieldNames(SurfNum + 9) + " was less than the allowable minimum, reset to minimum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).FracDistribToSurf(SurfNum) > MaxFraction) {
HighTempRadSys(Item).FracDistribToSurf(SurfNum) = MaxFraction;
ShowWarningError(cNumericFieldNames(SurfNum + 9) + " was greater than the allowable maximum, reset to maximum value.");
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
}
if (HighTempRadSys(Item).SurfacePtr(SurfNum) != 0) {
Surface(HighTempRadSys(Item).SurfacePtr(SurfNum)).IntConvSurfGetsRadiantHeat = true;
}
AllFracsSummed += HighTempRadSys(Item).FracDistribToSurf(SurfNum);
} // ...end of DO loop through surfaces that the heater radiates to.
// Error trap if the fractions add up to greater than 1.0
if (AllFracsSummed > (MaxFraction + 0.01)) {
ShowSevereError("Fraction of radiation distributed to surfaces sums up to greater than 1 for " + cAlphaArgs(1));
ShowContinueError("Occurs for " + cCurrentModuleObject + " = " + cAlphaArgs(1));
ErrorsFound = true;
}
if (AllFracsSummed < (MaxFraction - 0.01)) { // User didn't distribute all of the radiation warn that some will be lost
TotalFracToSurfs = AllFracsSummed - HighTempRadSys(Item).FracDistribPerson;
FracOfRadPotentiallyLost = 1.0 - AllFracsSummed;
ShowSevereError("Fraction of radiation distributed to surfaces and people sums up to less than 1 for " + cAlphaArgs(1));
ShowContinueError("This would result in some of the radiant energy delivered by the high temp radiant heater being lost.");
ShowContinueError("The sum of all radiation fractions to surfaces = " + TrimSigDigits(TotalFracToSurfs, 5));
ShowContinueError("The radiant fraction to people = " + TrimSigDigits(HighTempRadSys(Item).FracDistribPerson, 5));
ShowContinueError("So, all radiant fractions including surfaces and people = " + TrimSigDigits(AllFracsSummed, 5));
ShowContinueError(
"This means that the fraction of radiant energy that would be lost from the high temperature radiant heater would be = " +
TrimSigDigits(FracOfRadPotentiallyLost, 5));
ShowContinueError("Please check and correct this so that all radiant energy is accounted for in " + cCurrentModuleObject + " = " +
cAlphaArgs(1));
ErrorsFound = true;
}
} // ...end of DO loop through all of the high temperature radiant heaters
// Set up the output variables for high temperature radiant heaters
// cCurrentModuleObject = "ZoneHVAC:HighTemperatureRadiant"
for (Item = 1; Item <= NumOfHighTempRadSys; ++Item) {
SetupOutputVariable("Zone Radiant HVAC Heating Rate",
OutputProcessor::Unit::W,
HighTempRadSys(Item).HeatPower,
"System",
"Average",
HighTempRadSys(Item).Name);
SetupOutputVariable("Zone Radiant HVAC Heating Energy",
OutputProcessor::Unit::J,
HighTempRadSys(Item).HeatEnergy,
"System",
"Sum",
HighTempRadSys(Item).Name,
_,
"ENERGYTRANSFER",
"HEATINGCOILS",
_,
"System");
if (HighTempRadSys(Item).HeaterType == Gas) {
SetupOutputVariable("Zone Radiant HVAC Gas Rate",
OutputProcessor::Unit::W,
HighTempRadSys(Item).GasPower,
"System",
"Average",
HighTempRadSys(Item).Name);
SetupOutputVariable("Zone Radiant HVAC Gas Energy",
OutputProcessor::Unit::J,
HighTempRadSys(Item).GasEnergy,
"System",
"Sum",
HighTempRadSys(Item).Name,
_,
"Gas",
"Heating",
_,
"System");
} else if (HighTempRadSys(Item).HeaterType == Electric) {
SetupOutputVariable("Zone Radiant HVAC Electric Power",
OutputProcessor::Unit::W,
HighTempRadSys(Item).ElecPower,
"System",
"Average",
HighTempRadSys(Item).Name);
SetupOutputVariable("Zone Radiant HVAC Electric Energy",
OutputProcessor::Unit::J,
HighTempRadSys(Item).ElecEnergy,
"System",
"Sum",
HighTempRadSys(Item).Name,
_,
"ELECTRICITY",
"Heating",
_,
"System");
}
}
}
void InitHighTempRadiantSystem(bool const FirstHVACIteration, // TRUE if 1st HVAC simulation of system timestep
int const RadSysNum // Index for the low temperature radiant system under consideration within the derived types
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine initializes variables relating to high temperature
// radiant heating systems.
// METHODOLOGY EMPLOYED:
// Simply initializes whatever needs initializing.
// REFERENCES:
// na
// Using/Aliasing
using DataGlobals::BeginEnvrnFlag;
using DataGlobals::NumOfZones;
using DataZoneEquipment::CheckZoneEquipmentList;
using DataZoneEquipment::ZoneEquipInputsFilled;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
// na
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
static bool firstTime(true); // For one-time initializations
int ZoneNum; // Intermediate variable for keeping track of the zone number
static bool MyEnvrnFlag(true);
static bool ZoneEquipmentListChecked(false); // True after the Zone Equipment List has been checked for items
int Loop;
// FLOW:
if (firstTime) {
ZeroSourceSumHATsurf.dimension(NumOfZones, 0.0);
QHTRadSource.dimension(NumOfHighTempRadSys, 0.0);
QHTRadSrcAvg.dimension(NumOfHighTempRadSys, 0.0);
LastQHTRadSrc.dimension(NumOfHighTempRadSys, 0.0);
LastSysTimeElapsed.dimension(NumOfHighTempRadSys, 0.0);
LastTimeStepSys.dimension(NumOfHighTempRadSys, 0.0);
MySizeFlag.dimension(NumOfHighTempRadSys, true);
firstTime = false;
}
// need to check all units to see if they are on Zone Equipment List or issue warning
if (!ZoneEquipmentListChecked && ZoneEquipInputsFilled) {
ZoneEquipmentListChecked = true;
for (Loop = 1; Loop <= NumOfHighTempRadSys; ++Loop) {
if (CheckZoneEquipmentList("ZoneHVAC:HighTemperatureRadiant", HighTempRadSys(Loop).Name)) continue;
ShowSevereError("InitHighTempRadiantSystem: Unit=[ZoneHVAC:HighTemperatureRadiant," + HighTempRadSys(Loop).Name +
"] is not on any ZoneHVAC:EquipmentList. It will not be simulated.");
}
}
if (!SysSizingCalc && MySizeFlag(RadSysNum)) {
// for each radiant systen do the sizing once.
SizeHighTempRadiantSystem(RadSysNum);
MySizeFlag(RadSysNum) = false;
}
if (BeginEnvrnFlag && MyEnvrnFlag) {
ZeroSourceSumHATsurf = 0.0;
QHTRadSource = 0.0;
QHTRadSrcAvg = 0.0;
LastQHTRadSrc = 0.0;
LastSysTimeElapsed = 0.0;
LastTimeStepSys = 0.0;
MyEnvrnFlag = false;
}
if (!BeginEnvrnFlag) {
MyEnvrnFlag = true;
}
if (BeginTimeStepFlag && FirstHVACIteration) { // This is the first pass through in a particular time step
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
ZeroSourceSumHATsurf(ZoneNum) = SumHATsurf(ZoneNum); // Set this to figure out what part of the load the radiant system meets
QHTRadSrcAvg(RadSysNum) = 0.0; // Initialize this variable to zero (radiant system defaults to off)
LastQHTRadSrc(RadSysNum) = 0.0; // At the beginning of a time step, reset to zero so average calculation can start again
LastSysTimeElapsed(RadSysNum) = 0.0; // At the beginning of a time step, reset to zero so average calculation can start again
LastTimeStepSys(RadSysNum) = 0.0; // At the beginning of a time step, reset to zero so average calculation can start again
}
}
void SizeHighTempRadiantSystem(int const RadSysNum)
{
// SUBROUTINE INFORMATION:
// AUTHOR Fred Buhl
// DATE WRITTEN February 2002
// MODIFIED August 2013 Daeho Kang, add component sizing table entries
// July 2014, B. Nigusse, added scalable sizing
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine is for sizing high temperature radiant components for which max power input has not been
// specified in the input.
// METHODOLOGY EMPLOYED:
// Obtains design heating load from the zone sizing arrays
// REFERENCES:
// na
// Using/Aliasing
using namespace DataSizing;
using DataHeatBalance::Zone;
using DataHVACGlobals::HeatingCapacitySizing;
using General::RoundSigDigits;
using ReportSizingManager::ReportSizingOutput;
using ReportSizingManager::RequestSizing;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
static std::string const RoutineName("SizeHighTempRadiantSystem");
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS
Real64 MaxPowerCapacDes; // Design maximum capacity for reproting
Real64 MaxPowerCapacUser; // User hard-sized maximum capacity for reproting
bool IsAutoSize; // Indicator to autosizing nominal capacity
std::string CompName; // component name
std::string CompType; // component type
std::string SizingString; // input field sizing description (e.g., Nominal Capacity)
Real64 TempSize; // autosized value of coil input field
int FieldNum = 1; // IDD numeric field number where input field description is found
int SizingMethod; // Integer representation of sizing method name (e.g., CoolingAirflowSizing, HeatingAirflowSizing, CoolingCapacitySizing,
// HeatingCapacitySizing, etc.)
bool PrintFlag; // TRUE when sizing information is reported in the eio file
int CapSizingMethod(0); // capacity sizing methods (HeatingDesignCapacity, CapacityPerFloorArea, FractionOfAutosizedCoolingCapacity, and
// FractionOfAutosizedHeatingCapacity )
IsAutoSize = false;
MaxPowerCapacDes = 0.0;
MaxPowerCapacUser = 0.0;
DataScalableCapSizingON = false;
if (CurZoneEqNum > 0) {
CompType = "ZoneHVAC:HighTemperatureRadiant";
CompName = HighTempRadSys(RadSysNum).Name;
DataFracOfAutosizedHeatingCapacity = 1.0;
DataZoneNumber = HighTempRadSys(RadSysNum).ZonePtr;
SizingMethod = HeatingCapacitySizing;
FieldNum = 1;
PrintFlag = true;
SizingString = HighTempRadSysNumericFields(RadSysNum).FieldNames(FieldNum) + " [W]";
CapSizingMethod = HighTempRadSys(RadSysNum).HeatingCapMethod;
ZoneEqSizing(CurZoneEqNum).SizingMethod(SizingMethod) = CapSizingMethod;
if (CapSizingMethod == HeatingDesignCapacity || CapSizingMethod == CapacityPerFloorArea ||
CapSizingMethod == FractionOfAutosizedHeatingCapacity) {
if (CapSizingMethod == HeatingDesignCapacity) {
if (HighTempRadSys(RadSysNum).ScaledHeatingCapacity == AutoSize) {
CheckZoneSizing(CompType, CompName);
ZoneEqSizing(CurZoneEqNum).DesHeatingLoad = FinalZoneSizing(CurZoneEqNum).NonAirSysDesHeatLoad /
(HighTempRadSys(RadSysNum).FracRadiant + HighTempRadSys(RadSysNum).FracConvect);
} else {
ZoneEqSizing(CurZoneEqNum).DesHeatingLoad = HighTempRadSys(RadSysNum).ScaledHeatingCapacity;
}
ZoneEqSizing(CurZoneEqNum).HeatingCapacity = true;
TempSize = ZoneEqSizing(CurZoneEqNum).DesHeatingLoad;
} else if (CapSizingMethod == CapacityPerFloorArea) {
ZoneEqSizing(CurZoneEqNum).HeatingCapacity = true;
ZoneEqSizing(CurZoneEqNum).DesHeatingLoad = HighTempRadSys(RadSysNum).ScaledHeatingCapacity * Zone(DataZoneNumber).FloorArea;
TempSize = ZoneEqSizing(CurZoneEqNum).DesHeatingLoad;
DataScalableCapSizingON = true;
} else if (CapSizingMethod == FractionOfAutosizedHeatingCapacity) {
CheckZoneSizing(CompType, CompName);
ZoneEqSizing(CurZoneEqNum).HeatingCapacity = true;
DataFracOfAutosizedHeatingCapacity = HighTempRadSys(RadSysNum).ScaledHeatingCapacity;
ZoneEqSizing(CurZoneEqNum).DesHeatingLoad = FinalZoneSizing(CurZoneEqNum).NonAirSysDesHeatLoad /
(HighTempRadSys(RadSysNum).FracRadiant + HighTempRadSys(RadSysNum).FracConvect);
TempSize = AutoSize;
DataScalableCapSizingON = true;
} else {
TempSize = HighTempRadSys(RadSysNum).ScaledHeatingCapacity;
}
RequestSizing(CompType, CompName, SizingMethod, SizingString, TempSize, PrintFlag, RoutineName);
HighTempRadSys(RadSysNum).MaxPowerCapac = TempSize;
DataScalableCapSizingON = false;
}
}
}
void CalcHighTempRadiantSystem(int const RadSysNum) // name of the low temperature radiant system
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine does all of the stuff that is necessary to simulate
// a high temperature radiant heating system.
// METHODOLOGY EMPLOYED:
// Follows the methods used by many other pieces of zone equipment except
// that we are controlling the input to the heater element. Note that
// cooling is not allowed for such a system. Controls are very basic at
// this point using just a linear interpolation between being off at
// one end of the throttling range, fully on at the other end, and varying
// linearly in between.
// REFERENCES:
// Other EnergyPlus modules
// Building Systems Laboratory, BLAST User's Guide/Reference.
// Fanger, P.O. "Analysis and Applications in Environmental Engineering",
// Danish Technical Press, 1970.
// Maloney, Dan. 1987. "Development of a radiant heater model and the
// incorporation of thermal comfort considerations into the BLAST
// energy analysis program", M.S. thesis, University of Illinois at
// Urbana-Champaign (Dept. of Mechanical and Industrial Engineering).
// Using/Aliasing
using DataHeatBalance::MRT;
using DataHeatBalFanSys::MAT;
using namespace DataZoneEnergyDemands;
using ScheduleManager::GetCurrentScheduleValue;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
// na
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
Real64 HeatFrac; // fraction of maximum energy input to radiant system [dimensionless]
Real64 OffTemp; // Temperature above which the radiant system should be completely off [C]
Real64 OpTemp; // Operative temperature [C]
// REAL(r64) :: QZnReq ! heating or cooling needed by zone [Watts]
Real64 SetPtTemp; // Setpoint temperature [C]
int ZoneNum; // number of zone being served
// FLOW:
// initialize local variables
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
HeatFrac = 0.0;
if (GetCurrentScheduleValue(HighTempRadSys(RadSysNum).SchedPtr) <= 0) {
// Unit is off or has no load upon it; set the flow rates to zero and then
// simulate the components with the no flow conditions
QHTRadSource(RadSysNum) = 0.0;
} else { // Unit might be on-->this section is intended to control the output of the
// high temperature radiant heater (temperature controlled)
// Determine the current setpoint temperature and the temperature at which the unit should be completely off
SetPtTemp = GetCurrentScheduleValue(HighTempRadSys(RadSysNum).SetptSchedPtr);
OffTemp = SetPtTemp + 0.5 * HighTempRadSys(RadSysNum).ThrottlRange;
OpTemp = (MAT(ZoneNum) + MRT(ZoneNum)) / 2.0; // Approximate the "operative" temperature
// Determine the fraction of maximum power to the unit (limiting the fraction range from zero to unity)
{
auto const SELECT_CASE_var(HighTempRadSys(RadSysNum).ControlType);
if (SELECT_CASE_var == MATControl) {
HeatFrac = (OffTemp - MAT(ZoneNum)) / HighTempRadSys(RadSysNum).ThrottlRange;
} else if (SELECT_CASE_var == MRTControl) {
HeatFrac = (OffTemp - MRT(ZoneNum)) / HighTempRadSys(RadSysNum).ThrottlRange;
} else if (SELECT_CASE_var == OperativeControl) {
OpTemp = 0.5 * (MAT(ZoneNum) + MRT(ZoneNum));
HeatFrac = (OffTemp - OpTemp) / HighTempRadSys(RadSysNum).ThrottlRange;
}
}
if (HeatFrac < 0.0) HeatFrac = 0.0;
if (HeatFrac > 1.0) HeatFrac = 1.0;
// Set the heat source for the high temperature electric radiant system
QHTRadSource(RadSysNum) = HeatFrac * HighTempRadSys(RadSysNum).MaxPowerCapac;
}
}
void CalcHighTempRadiantSystemSP(
bool const EP_UNUSED(FirstHVACIteration), // true if this is the first HVAC iteration at this system time step !unused1208
int const RadSysNum // name of the low temperature radiant system
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2008
// MODIFIED Sep 2011 LKL/BG - resimulate only zones needing it for Radiant systems
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine does all of the stuff that is necessary to simulate
// a high temperature radiant heating system using setpoint temperature control.
// METHODOLOGY EMPLOYED:
// Follows the methods used by many other pieces of zone equipment except
// that we are controlling the input to the heater element. Note that
// cooling is not allowed for such a system. Controls are very basic and
// use an iterative approach to get close to what we need.
// REFERENCES:
// Other EnergyPlus modules
// Building Systems Laboratory, BLAST User's Guide/Reference.
// Fanger, P.O. "Analysis and Applications in Environmental Engineering",
// Danish Technical Press, 1970.
// Maloney, Dan. 1987. "Development of a radiant heater model and the
// incorporation of thermal comfort considerations into the BLAST
// energy analysis program", M.S. thesis, University of Illinois at
// Urbana-Champaign (Dept. of Mechanical and Industrial Engineering).
// Using/Aliasing
using DataHeatBalance::MRT;
using DataHeatBalFanSys::MAT;
using ScheduleManager::GetCurrentScheduleValue;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
float const TempConvToler(0.1); // Temperature controller tries to converge to within 0.1C
int const MaxIterations(10); // Maximum number of iterations to achieve temperature control
// (10 interval halvings achieves control to 0.1% of capacity)
// These two parameters are intended to achieve reasonable control
// without excessive run times.
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
bool ConvergFlag; // convergence flag for temperature control
// unused INTEGER, SAVE :: ErrIterCount=0 ! number of time max iterations has been exceeded
float HeatFrac; // fraction of maximum energy input to radiant system [dimensionless]
float HeatFracMax; // maximum range of heat fraction
float HeatFracMin; // minimum range of heat fraction
int IterNum; // iteration number
Real64 SetPtTemp; // Setpoint temperature [C]
int ZoneNum; // number of zone being served
Real64 ZoneTemp(0.0); // zone temperature (MAT, MRT, or Operative Temperature, depending on control type) [C]
// FLOW:
// initialize local variables
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
QHTRadSource(RadSysNum) = 0.0;
if (GetCurrentScheduleValue(HighTempRadSys(RadSysNum).SchedPtr) > 0) {
// Unit is scheduled on-->this section is intended to control the output of the
// high temperature radiant heater (temperature controlled)
// Determine the current setpoint temperature and the temperature at which the unit should be completely off
SetPtTemp = GetCurrentScheduleValue(HighTempRadSys(RadSysNum).SetptSchedPtr);
// Now, distribute the radiant energy of all systems to the appropriate
// surfaces, to people, and the air; determine the latent portion
DistributeHTRadGains();
// Now "simulate" the system by recalculating the heat balances
HeatBalanceSurfaceManager::CalcHeatBalanceOutsideSurf(ZoneNum);
HeatBalanceSurfaceManager::CalcHeatBalanceInsideSurf(ZoneNum);
// First determine whether or not the unit should be on
// Determine the proper temperature on which to control
{
auto const SELECT_CASE_var(HighTempRadSys(RadSysNum).ControlType);
if (SELECT_CASE_var == MATSPControl) {
ZoneTemp = MAT(ZoneNum);
} else if (SELECT_CASE_var == MRTSPControl) {
ZoneTemp = MRT(ZoneNum);
} else if (SELECT_CASE_var == OperativeSPControl) {
ZoneTemp = 0.5 * (MAT(ZoneNum) + MRT(ZoneNum));
} else {
assert(false);
}
}
if (ZoneTemp < (SetPtTemp - TempConvToler)) {
// Use simple interval halving to find the best operating fraction to achieve proper temperature control
IterNum = 0;
ConvergFlag = false;
HeatFracMax = 1.0;
HeatFracMin = 0.0;
while ((IterNum <= MaxIterations) && (!ConvergFlag)) {
// In the first iteration (IterNum=0), try full capacity and see if that is the best solution
if (IterNum == 0) {
HeatFrac = 1.0;
} else {
HeatFrac = (HeatFracMin + HeatFracMax) / 2.0;
}
// Set the heat source for the high temperature radiant system
QHTRadSource(RadSysNum) = HeatFrac * HighTempRadSys(RadSysNum).MaxPowerCapac;
// Now, distribute the radiant energy of all systems to the appropriate
// surfaces, to people, and the air; determine the latent portion
DistributeHTRadGains();
// Now "simulate" the system by recalculating the heat balances
HeatBalanceSurfaceManager::CalcHeatBalanceOutsideSurf(ZoneNum);
HeatBalanceSurfaceManager::CalcHeatBalanceInsideSurf(ZoneNum);
// Redetermine the current value of the controlling temperature
{
auto const SELECT_CASE_var(HighTempRadSys(RadSysNum).ControlType);
if (SELECT_CASE_var == MATControl) {
ZoneTemp = MAT(ZoneNum);
} else if (SELECT_CASE_var == MRTControl) {
ZoneTemp = MRT(ZoneNum);
} else if (SELECT_CASE_var == OperativeControl) {
ZoneTemp = 0.5 * (MAT(ZoneNum) + MRT(ZoneNum));
}
}
if ((std::abs(ZoneTemp - SetPtTemp)) <= TempConvToler) {
// The radiant heater has controlled the zone temperature to the appropriate level--stop iterating
ConvergFlag = true;
} else if (ZoneTemp < SetPtTemp) {
// The zone temperature is too low--try increasing the radiant heater output
if (IterNum == 0) {
// Heater already at capacity--this is the best that we can do
ConvergFlag = true;
} else {
HeatFracMin = HeatFrac;
}
} else { // (ZoneTemp > SetPtTemp)
// The zone temperature is too high--try decreasing the radiant heater output
if (IterNum > 0) HeatFracMax = HeatFrac;
}
++IterNum;
}
}
}
}
void UpdateHighTempRadiantSystem(int const RadSysNum, // Index for the low temperature radiant system under consideration within the derived types
Real64 &LoadMet // load met by the radiant system, in Watts
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine does any updating that needs to be done for high
// temperature radiant heating systems. This routine has two functions.
// First, it needs to keep track of the average high temperature
// radiant source. The method for doing this is similar to low
// temperature systems except that heat input is kept locally on
// a system basis rather than a surface basis. This is because a high
// temperature system affects many surfaces while a low temperature
// system directly affects only one surface. This leads to the second
// function of this subroutine which is to account for the affect of
// all high temperature radiant systems on each surface. This
// distribution must be "redone" every time to be sure that we have
// properly accounted for all of the systems.
// METHODOLOGY EMPLOYED:
// For the source average update, if the system time step elapsed is
// still what it used to be, then either we are still iterating or we
// had to go back and shorten the time step. As a result, we have to
// subtract out the previous value that we added. If the system time
// step elapsed is different, then we just need to add the new values
// to the running average.
// REFERENCES:
// na
// Using/Aliasing
using DataGlobals::BeginEnvrnFlag;
using DataGlobals::TimeStepZone;
using DataHeatBalFanSys::SumConvHTRadSys;
using DataHVACGlobals::SysTimeElapsed;
using DataHVACGlobals::TimeStepSys;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
// na
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
int ZoneNum; // Zone index number for the current radiant system
static bool MyEnvrnFlag(true);
// FLOW:
if (BeginEnvrnFlag && MyEnvrnFlag) {
MyEnvrnFlag = false;
}
if (!BeginEnvrnFlag) {
MyEnvrnFlag = true;
}
// First, update the running average if necessary...
if (LastSysTimeElapsed(RadSysNum) == SysTimeElapsed) {
// Still iterating or reducing system time step, so subtract old values which were
// not valid
QHTRadSrcAvg(RadSysNum) -= LastQHTRadSrc(RadSysNum) * LastTimeStepSys(RadSysNum) / TimeStepZone;
}
// Update the running average and the "last" values with the current values of the appropriate variables
QHTRadSrcAvg(RadSysNum) += QHTRadSource(RadSysNum) * TimeStepSys / TimeStepZone;
LastQHTRadSrc(RadSysNum) = QHTRadSource(RadSysNum);
LastSysTimeElapsed(RadSysNum) = SysTimeElapsed;
LastTimeStepSys(RadSysNum) = TimeStepSys;
{
auto const SELECT_CASE_var(HighTempRadSys(RadSysNum).ControlType);
if ((SELECT_CASE_var == MATControl) || (SELECT_CASE_var == MRTControl) || (SELECT_CASE_var == OperativeControl)) {
// Only need to do this for the non-SP controls (SP has already done this enough)
// Now, distribute the radiant energy of all systems to the appropriate
// surfaces, to people, and the air; determine the latent portion
DistributeHTRadGains();
// Now "simulate" the system by recalculating the heat balances
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
HeatBalanceSurfaceManager::CalcHeatBalanceOutsideSurf(ZoneNum);
HeatBalanceSurfaceManager::CalcHeatBalanceInsideSurf(ZoneNum);
}
}
if (QHTRadSource(RadSysNum) <= 0.0) {
LoadMet = 0.0; // System wasn't running so it can't meet a load
} else {
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
LoadMet = (SumHATsurf(ZoneNum) - ZeroSourceSumHATsurf(ZoneNum)) + SumConvHTRadSys(ZoneNum);
}
}
void UpdateHTRadSourceValAvg(bool &HighTempRadSysOn) // .TRUE. if the radiant system has run this zone time step
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// To transfer the average value of the heat source over the entire
// zone time step back to the heat balance routines so that the heat
// balance algorithms can simulate one last time with the average source
// to maintain some reasonable amount of continuity and energy balance
// in the temperature and flux histories.
// METHODOLOGY EMPLOYED:
// All of the record keeping for the average term is done in the Update
// routine so the only other thing that this subroutine does is check to
// see if the system was even on. If any average term is non-zero, then
// one or more of the radiant systems was running.
// REFERENCES:
// na
// USE STATEMENTS:
// na
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
// na
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
int RadSysNum; // DO loop counter for surface index
// FLOW:
HighTempRadSysOn = false;
// If this was never allocated, then there are no radiant systems in this input file (just RETURN)
if (!allocated(QHTRadSrcAvg)) return;
// If it was allocated, then we have to check to see if this was running at all...
for (RadSysNum = 1; RadSysNum <= NumOfHighTempRadSys; ++RadSysNum) {
if (QHTRadSrcAvg(RadSysNum) != 0.0) {
HighTempRadSysOn = true;
break; // DO loop
}
}
QHTRadSource = QHTRadSrcAvg;
DistributeHTRadGains(); // QHTRadSource has been modified so we need to redistribute gains
}
void DistributeHTRadGains()
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED April 2010 Brent Griffith, max limit to protect surface temperature calcs
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// To distribute the gains from the high temperature radiant heater
// as specified in the user input file. This includes distribution
// of long wavelength radiant gains to surfaces and "people" as well
// as latent, lost, and convective portions of the total gain.
// METHODOLOGY EMPLOYED:
// We must cycle through all of the radiant systems because each
// surface could feel the effect of more than one radiant system.
// Note that the energy radiated to people is assumed to affect them
// but them it is assumed to be convected to the air. This is why
// the convective portion shown below has two parts to it.
// REFERENCES:
// na
// Using/Aliasing
using DataGlobals::NumOfZones;
using DataHeatBalance::Zone;
using DataHeatBalFanSys::MaxRadHeatFlux;
using DataHeatBalFanSys::QHTRadSysSurf;
using DataHeatBalFanSys::QHTRadSysToPerson;
using DataHeatBalFanSys::SumConvHTRadSys;
using DataHeatBalFanSys::SumLatentHTRadSys;
using DataSurfaces::Surface;
using General::RoundSigDigits;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// na
// SUBROUTINE PARAMETER DEFINITIONS:
Real64 const SmallestArea(0.001); // Smallest area in meters squared (to avoid a divide by zero)
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
int RadSurfNum; // Counter for surfaces receiving radiation from radiant heater
int RadSysNum; // Counter for the radiant systems
int SurfNum; // Pointer to the Surface derived type
int ZoneNum; // Pointer to the Zone derived type
Real64 ThisSurfIntensity; // temporary for W/m2 term for rad on a surface
// FLOW:
// Initialize arrays
SumConvHTRadSys = 0.0;
SumLatentHTRadSys = 0.0;
QHTRadSysSurf = 0.0;
QHTRadSysToPerson = 0.0;
for (RadSysNum = 1; RadSysNum <= NumOfHighTempRadSys; ++RadSysNum) {
ZoneNum = HighTempRadSys(RadSysNum).ZonePtr;
QHTRadSysToPerson(ZoneNum) =
QHTRadSource(RadSysNum) * HighTempRadSys(RadSysNum).FracRadiant * HighTempRadSys(RadSysNum).FracDistribPerson;
SumConvHTRadSys(ZoneNum) += QHTRadSource(RadSysNum) * HighTempRadSys(RadSysNum).FracConvect;
SumLatentHTRadSys(ZoneNum) += QHTRadSource(RadSysNum) * HighTempRadSys(RadSysNum).FracLatent;
for (RadSurfNum = 1; RadSurfNum <= HighTempRadSys(RadSysNum).TotSurfToDistrib; ++RadSurfNum) {
SurfNum = HighTempRadSys(RadSysNum).SurfacePtr(RadSurfNum);
if (Surface(SurfNum).Area > SmallestArea) {
ThisSurfIntensity = (QHTRadSource(RadSysNum) * HighTempRadSys(RadSysNum).FracRadiant *
HighTempRadSys(RadSysNum).FracDistribToSurf(RadSurfNum) / Surface(SurfNum).Area);
QHTRadSysSurf(SurfNum) += ThisSurfIntensity;
if (ThisSurfIntensity > MaxRadHeatFlux) { // CR 8074, trap for excessive intensity (throws off surface balance )
ShowSevereError("DistributeHTRadGains: excessive thermal radiation heat flux intensity detected");
ShowContinueError("Surface = " + Surface(SurfNum).Name);
ShowContinueError("Surface area = " + RoundSigDigits(Surface(SurfNum).Area, 3) + " [m2]");
ShowContinueError("Occurs in ZoneHVAC:HighTemperatureRadiant = " + HighTempRadSys(RadSysNum).Name);
ShowContinueError("Radiation intensity = " + RoundSigDigits(ThisSurfIntensity, 2) + " [W/m2]");
ShowContinueError("Assign a larger surface area or more surfaces in ZoneHVAC:HighTemperatureRadiant");
ShowFatalError("DistributeHTRadGains: excessive thermal radiation heat flux intensity detected");
}
} else { // small surface
ShowSevereError("DistributeHTRadGains: surface not large enough to receive thermal radiation heat flux");
ShowContinueError("Surface = " + Surface(SurfNum).Name);
ShowContinueError("Surface area = " + RoundSigDigits(Surface(SurfNum).Area, 3) + " [m2]");
ShowContinueError("Occurs in ZoneHVAC:HighTemperatureRadiant = " + HighTempRadSys(RadSysNum).Name);
ShowContinueError("Assign a larger surface area or more surfaces in ZoneHVAC:HighTemperatureRadiant");
ShowFatalError("DistributeHTRadGains: surface not large enough to receive thermal radiation heat flux");
}
}
}
// Here an assumption is made regarding radiant heat transfer to people.
// While the QHTRadSysToPerson array will be used by the thermal comfort
// routines, the energy transfer to people would get lost from the perspective
// of the heat balance. So, to avoid this net loss of energy which clearly
// gets added to the zones, we must account for it somehow. This assumption
// that all energy radiated to people is converted to convective energy is
// not very precise, but at least it conserves energy.
for (ZoneNum = 1; ZoneNum <= NumOfZones; ++ZoneNum) {
SumConvHTRadSys(ZoneNum) += QHTRadSysToPerson(ZoneNum);
}
}
void ReportHighTempRadiantSystem(int const RadSysNum) // Index for the low temperature radiant system under consideration within the derived types
{
// SUBROUTINE INFORMATION:
// AUTHOR Rick Strand
// DATE WRITTEN February 2001
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// This subroutine simply produces output for the high temperature radiant system.
// METHODOLOGY EMPLOYED:
// Standard EnergyPlus methodology.
// REFERENCES:
// na
// Using/Aliasing
using DataGlobals::SecInHour;
using DataHVACGlobals::TimeStepSys;
using DataSurfaces::Surface;
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
// INTERFACE BLOCK SPECIFICATIONS
// na
// DERIVED TYPE DEFINITIONS
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
// na
// FLOW:
if (HighTempRadSys(RadSysNum).HeaterType == Gas) {
HighTempRadSys(RadSysNum).GasPower = QHTRadSource(RadSysNum) / HighTempRadSys(RadSysNum).CombustionEffic;
HighTempRadSys(RadSysNum).GasEnergy = HighTempRadSys(RadSysNum).GasPower * TimeStepSys * SecInHour;
HighTempRadSys(RadSysNum).ElecPower = 0.0;
HighTempRadSys(RadSysNum).ElecEnergy = 0.0;
} else if (HighTempRadSys(RadSysNum).HeaterType == Electric) {
HighTempRadSys(RadSysNum).GasPower = 0.0;
HighTempRadSys(RadSysNum).GasEnergy = 0.0;
HighTempRadSys(RadSysNum).ElecPower = QHTRadSource(RadSysNum);
HighTempRadSys(RadSysNum).ElecEnergy = HighTempRadSys(RadSysNum).ElecPower * TimeStepSys * SecInHour;
} else {
ShowWarningError("Someone forgot to add a high temperature radiant heater type to the reporting subroutine");
}
HighTempRadSys(RadSysNum).HeatPower = QHTRadSource(RadSysNum);
HighTempRadSys(RadSysNum).HeatEnergy = HighTempRadSys(RadSysNum).HeatPower * TimeStepSys * SecInHour;
}
Real64 SumHATsurf(int const ZoneNum) // Zone number
{
// FUNCTION INFORMATION:
// AUTHOR Peter Graham Ellis
// DATE WRITTEN July 2003
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS FUNCTION:
// This function calculates the zone sum of Hc*Area*Tsurf. It replaces the old SUMHAT.
// The SumHATsurf code below is also in the CalcZoneSums subroutine in ZoneTempPredictorCorrector
// and should be updated accordingly.
// METHODOLOGY EMPLOYED:
// na
// REFERENCES:
// na
// Using/Aliasing
using namespace DataSurfaces;
using namespace DataHeatBalance;
using namespace DataHeatBalSurface;
// Return value
Real64 SumHATsurf;
// Locals
// FUNCTION ARGUMENT DEFINITIONS:
// FUNCTION LOCAL VARIABLE DECLARATIONS:
int SurfNum; // Surface number
Real64 Area; // Effective surface area
// FLOW:
SumHATsurf = 0.0;
for (SurfNum = Zone(ZoneNum).SurfaceFirst; SurfNum <= Zone(ZoneNum).SurfaceLast; ++SurfNum) {
if (!Surface(SurfNum).HeatTransSurf) continue; // Skip non-heat transfer surfaces
Area = Surface(SurfNum).Area;
if (Surface(SurfNum).Class == SurfaceClass_Window) {
if (SurfaceWindow(SurfNum).ShadingFlag == IntShadeOn || SurfaceWindow(SurfNum).ShadingFlag == IntBlindOn) {
// The area is the shade or blind area = the sum of the glazing area and the divider area (which is zero if no divider)
Area += SurfaceWindow(SurfNum).DividerArea;
}
if (SurfaceWindow(SurfNum).FrameArea > 0.0) {
// Window frame contribution
SumHATsurf += HConvIn(SurfNum) * SurfaceWindow(SurfNum).FrameArea * (1.0 + SurfaceWindow(SurfNum).ProjCorrFrIn) *
SurfaceWindow(SurfNum).FrameTempSurfIn;
}
if (SurfaceWindow(SurfNum).DividerArea > 0.0 && SurfaceWindow(SurfNum).ShadingFlag != IntShadeOn &&
SurfaceWindow(SurfNum).ShadingFlag != IntBlindOn) {
// Window divider contribution (only from shade or blind for window with divider and interior shade or blind)
SumHATsurf += HConvIn(SurfNum) * SurfaceWindow(SurfNum).DividerArea * (1.0 + 2.0 * SurfaceWindow(SurfNum).ProjCorrDivIn) *
SurfaceWindow(SurfNum).DividerTempSurfIn;
}
}
SumHATsurf += HConvIn(SurfNum) * Area * TempSurfInTmp(SurfNum);
}
return SumHATsurf;
}
} // namespace HighTempRadiantSystem
} // namespace EnergyPlus
| 51.686452 | 150 | 0.613601 | yurigabrich |
82e1cf46c547ee7bd50b783a31f234185a1116b3 | 3,092 | cpp | C++ | tests/cthread/test_bhv_fifo.cpp | hachetman/systemc-compiler | 0cc81ace03336d752c0146340ff5763a20e3cefd | [
"Apache-2.0"
] | 86 | 2020-10-23T15:59:47.000Z | 2022-03-28T18:51:19.000Z | tests/cthread/test_bhv_fifo.cpp | hachetman/systemc-compiler | 0cc81ace03336d752c0146340ff5763a20e3cefd | [
"Apache-2.0"
] | 18 | 2020-12-14T13:11:26.000Z | 2022-03-14T05:34:20.000Z | tests/cthread/test_bhv_fifo.cpp | hachetman/systemc-compiler | 0cc81ace03336d752c0146340ff5763a20e3cefd | [
"Apache-2.0"
] | 17 | 2020-10-29T16:19:43.000Z | 2022-03-11T09:51:05.000Z | /******************************************************************************
* Copyright (c) 2020, Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception.
*
*****************************************************************************/
#include "systemc.h"
using namespace sc_core;
#define BUFSIZE 4
#define LOGBUFSIZE 2
#define LOGBUFSIZEPLUSONE 3
// Behavioral FIFO example
class Circ_buf : public sc_module
{
public:
sc_in<bool> clk;
sc_in<bool> read_fifo;
sc_in<bool> write_fifo;
sc_in<sc_uint<32>> data_in;
sc_in<bool> reset;
sc_out<sc_uint<32>> data_out;
sc_out<bool> full;
sc_out<bool> empty;
// Internal signals
sc_signal<sc_uint<32>> buffer[BUFSIZE];
sc_uint<LOGBUFSIZE> headp; // FIFO head ptr
sc_uint<LOGBUFSIZE> tailp; // FIFO tail ptr
// Counter for fifo depth
sc_uint<LOGBUFSIZEPLUSONE> num_in_buf;
SC_CTOR(Circ_buf) {
SC_HAS_PROCESS(Circ_buf);
SC_CTHREAD(fifo_rw, clk.pos());
async_reset_signal_is(reset, true);
}
void fifo_rw() {
// Reset operations
headp = 0;
tailp = 0;
num_in_buf = 0;
full = false;
empty = true;
data_out = 0;
for (int i = 0; i < BUFSIZE; i++) {
buffer[i] = 0;
}
wait();
// Main loop
while (true) {
if (read_fifo.read()) {
// Check if FIFO is not empty
if (num_in_buf != 0) {
num_in_buf--;
data_out = buffer[headp++];
full = false;
if (num_in_buf == 0)
empty = true;
}
// Ignore read request otherwise
} else if (write_fifo.read()) {
// Check if FIFO is not full
if (num_in_buf != BUFSIZE) {
buffer[tailp++] = data_in;
num_in_buf++;
empty = false;
if (num_in_buf == BUFSIZE)
full = true;
}
// Ignore write request otherwise
} else {
}
wait();
}
}
};
class B_top: public sc_module
{
public:
sc_in<bool> clk{"clk"};
sc_signal<bool> read_fifo{"read_fifo"};
sc_signal<bool> write_fifo{"write_fifo"};
sc_signal<sc_uint<32>> data_in{"data_in"};
sc_signal<bool> reset{"reset"};
sc_signal<sc_uint<32>> data_out{"data_out"};
sc_signal<bool> full{"full"};
sc_signal<bool> empty{"empty"};
Circ_buf a_mod{"a_mod"};
SC_CTOR(B_top) {
a_mod.clk(clk);
a_mod.read_fifo(read_fifo);
a_mod.write_fifo(write_fifo);
a_mod.data_in(data_in);
a_mod.reset(reset);
a_mod.data_out(data_out);
a_mod.full(full);
a_mod.empty(empty);
}
};
int sc_main(int argc, char* argv[])
{
sc_clock clk { "clk", sc_time(1, SC_NS) };
B_top b_mod{"b_mod"};
b_mod.clk(clk);
sc_start();
return 0;
}
| 24.736 | 79 | 0.502587 | hachetman |
82e236a9dc748b89398c20334b2359958d95cfb8 | 233 | hpp | C++ | source-sdk/classes/net_channel.hpp | BuddDwyer-0x00/csgo-cheat-base | 3103f0e1ba811270f7f862cdfd105f712a6eb700 | [
"MIT"
] | 10 | 2020-06-23T00:44:29.000Z | 2021-11-16T01:52:16.000Z | source-sdk/classes/net_channel.hpp | BuddDwyer-0x00/csgo-cheat-base | 3103f0e1ba811270f7f862cdfd105f712a6eb700 | [
"MIT"
] | 1 | 2020-06-08T17:58:31.000Z | 2021-05-09T17:26:48.000Z | source-sdk/classes/net_channel.hpp | BuddDwyer-0x00/csgo-cheat-base | 3103f0e1ba811270f7f862cdfd105f712a6eb700 | [
"MIT"
] | 3 | 2020-06-08T00:31:44.000Z | 2021-05-27T23:16:13.000Z | #pragma once
class i_net_channel {
public:
uint8_t pad_0x0000[0x17];
bool should_delete;
int out_sequence_nr;
int in_sequence_nr;
int out_sequence_nr_ack;
int out_reliable_state;
int in_reliable_state;
int choked_packets;
}; | 17.923077 | 26 | 0.802575 | BuddDwyer-0x00 |
82e729cadf94428b8eab67a209530dddd04bdd21 | 11,342 | cpp | C++ | ClassicStartSrc/ClassicIE/ClassicIEDLL/DrawCaption.cpp | Duzzy-ExoDuus/Classic-Start | 8b70f64b5bceeadfa4e5599b299a856c1e452e80 | [
"MIT"
] | 1 | 2018-07-19T20:59:32.000Z | 2018-07-19T20:59:32.000Z | ClassicStartSrc/ClassicIE/ClassicIEDLL/DrawCaption.cpp | Duzzy-ExoDuus/Classic-Start | 8b70f64b5bceeadfa4e5599b299a856c1e452e80 | [
"MIT"
] | null | null | null | ClassicStartSrc/ClassicIE/ClassicIEDLL/DrawCaption.cpp | Duzzy-ExoDuus/Classic-Start | 8b70f64b5bceeadfa4e5599b299a856c1e452e80 | [
"MIT"
] | null | null | null | // Classic Shell (c) 2009-2017, Ivo Beltchev
// Classic Start (c) 2017-2018, The Passionate-Coder Team
// Confidential information of Ivo Beltchev. Not for disclosure or distribution without prior written consent from the author
#include "stdafx.h"
#include "ClassicIEDLL.h"
#include "Settings.h"
#include "ResourceHelper.h"
#include "SettingsUIHelper.h"
#include <vssym32.h>
#include <dwmapi.h>
static _declspec(thread) SIZE g_SysButtonSize; // the size of the system buttons (close, minimize) for this thread's window
static WNDPROC g_OldClassCaptionProc;
static HBITMAP g_GlowBmp;
static HBITMAP g_GlowBmpMax;
static LONG g_bInjected; // the process is injected
static int g_DPI;
static UINT g_Message; // private message to detect if the caption is subclassed
static ATOM g_SubclassAtom;
struct CustomCaption
{
int leftPadding;
int topPadding;
int iconPadding;
};
static CustomCaption g_CustomCaption[3]={
{2,3,10}, // Aero
{4,2,10}, // Aero maximized
{4,2,10}, // Basic
};
void GetSysButtonSize( HWND hWnd )
{
TITLEBARINFOEX titleInfo={sizeof(titleInfo)};
SendMessage(hWnd,WM_GETTITLEBARINFOEX,0,(LPARAM)&titleInfo);
int buttonLeft=titleInfo.rgrect[2].left;
if (buttonLeft>titleInfo.rgrect[5].left) buttonLeft=titleInfo.rgrect[5].left;
int buttonRight=titleInfo.rgrect[2].right;
if (buttonRight<titleInfo.rgrect[5].right) buttonRight=titleInfo.rgrect[5].right;
int w=buttonRight-buttonLeft;
int h=titleInfo.rgrect[5].bottom-titleInfo.rgrect[5].top;
g_SysButtonSize.cx=w;
g_SysButtonSize.cy=h;
}
// Subclasses the main IE frame to redraw the caption when the text changes
static LRESULT CALLBACK SubclassFrameProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
if (uMsg==g_Message)
{
GetSysButtonSize(hWnd);
HWND caption=FindWindowEx(hWnd,NULL,L"Client Caption",NULL);
if (caption)
InvalidateRect(caption,NULL,FALSE);
return 0;
}
if (uMsg==WM_SETTEXT || uMsg==WM_ACTIVATE)
{
HWND caption=FindWindowEx(hWnd,NULL,L"Client Caption",NULL);
if (caption)
InvalidateRect(caption,NULL,FALSE);
}
if (uMsg==WM_SIZE || uMsg==WM_SETTINGCHANGE)
{
GetSysButtonSize(hWnd);
if (uMsg==WM_SETTINGCHANGE)
{
CSettingsLockWrite lock;
UpdateSettings();
}
}
while (1)
{
WNDPROC proc=(WNDPROC)GetProp(hWnd,MAKEINTATOM(g_SubclassAtom));
if (proc)
return CallWindowProc(proc,hWnd,uMsg,wParam,lParam);
}
}
static LRESULT DefCaptionProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
while (1)
{
WNDPROC proc=(WNDPROC)GetProp(hWnd,MAKEINTATOM(g_SubclassAtom));
if (proc)
return CallWindowProc(proc,hWnd,uMsg,wParam,lParam);
}
}
// Subclasses the caption window to draw the icon and the text
static LRESULT CALLBACK SubclassCaptionProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
if (uMsg==g_Message)
return 1;
if (uMsg==WM_ERASEBKGND)
return 0;
if (uMsg==WM_PAINT)
{
HTHEME theme=OpenThemeData(hWnd,L"Window");
if (!theme) return DefCaptionProc(hWnd,uMsg,wParam,lParam);
// get the icon and the text from the parent
HWND parent=GetParent(hWnd);
wchar_t caption[256];
GetWindowText(parent,caption,_countof(caption));
HICON hIcon=(HICON)SendMessage(parent,WM_GETICON,ICON_SMALL,0);
int iconSize=GetSystemMetrics(SM_CXSMICON);
bool bMaximized=IsZoomed(parent)!=0;
bool bActive=(parent==GetActiveWindow());
RECT rc;
GetClientRect(hWnd,&rc);
if (!g_DPI)
{
HDC hdc=GetDC(NULL);
g_DPI=GetDeviceCaps(hdc,LOGPIXELSY);
ReleaseDC(NULL,hdc);
}
// create a font from the user settings
HFONT font=CreateFontSetting(GetSettingString(L"CaptionFont"),g_DPI);
if (!font)
{
LOGFONT lFont;
GetThemeSysFont(theme,TMT_CAPTIONFONT,&lFont);
font=CreateFontIndirect(&lFont);
}
bool bIcon=GetSettingBool(L"ShowIcon");
bool bCenter=GetSettingBool(L"CenterCaption");
bool bGlow=GetSettingBool(bMaximized?L"MaxGlow":L"Glow");
DTTOPTS opts={sizeof(opts),DTT_COMPOSITED|DTT_TEXTCOLOR};
opts.crText=GetSettingInt(bMaximized?(bActive?L"MaxColor":L"InactiveMaxColor"):(bActive?L"TextColor":L"InactiveColor"))&0xFFFFFF;
BOOL bComposition;
if (SUCCEEDED(DwmIsCompositionEnabled(&bComposition)) && bComposition)
{
// Aero Theme
PAINTSTRUCT ps;
HDC hdc=BeginPaint(hWnd,&ps);
BP_PAINTPARAMS paintParams={sizeof(paintParams),BPPF_ERASE};
HDC hdcPaint=NULL;
HPAINTBUFFER hBufferedPaint=BeginBufferedPaint(hdc,&ps.rcPaint,BPBF_TOPDOWNDIB,&paintParams,&hdcPaint);
if (hdcPaint)
{
// exclude the caption buttons
rc.right-=g_SysButtonSize.cx+5;
if (GetWinVersion()==WIN_VER_VISTA) rc.bottom++;
if (!bMaximized)
{
rc.left+=g_CustomCaption[0].leftPadding;
int y=g_CustomCaption[0].topPadding;
if (y>rc.bottom-iconSize) y=rc.bottom-iconSize;
if (bIcon)
{
DrawIconEx(hdcPaint,rc.left,y,hIcon,iconSize,iconSize,0,NULL,DI_NORMAL|DI_NOMIRROR);
rc.left+=iconSize;
}
rc.left+=g_CustomCaption[0].iconPadding;
rc.bottom++;
}
else
{
// when the window is maximized, the caption bar is partially off-screen, so align the icon to the bottom
rc.left+=g_CustomCaption[1].leftPadding;
if (bIcon)
{
DrawIconEx(hdcPaint,rc.left,rc.bottom-iconSize-g_CustomCaption[1].topPadding,hIcon,iconSize,iconSize,0,NULL,DI_NORMAL|DI_NOMIRROR);
rc.left+=iconSize;
}
rc.left+=g_CustomCaption[1].iconPadding;
if (GetWinVersion()>=WIN_VER_WIN10)
rc.bottom++;
}
if (GetWinVersion()<WIN_VER_WIN10)
rc.top=rc.bottom-g_SysButtonSize.cy;
HFONT font0=(HFONT)SelectObject(hdcPaint,font);
RECT rcText={0,0,0,0};
opts.dwFlags|=DTT_CALCRECT;
DrawThemeTextEx(theme,hdcPaint,0,0,caption,-1,DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE|DT_CALCRECT,&rcText,&opts);
int textWidth=rcText.right-rcText.left;
if (bCenter && textWidth<rc.right-rc.left)
{
rc.left+=(rc.right-rc.left-textWidth)/2;
}
if (textWidth>rc.right-rc.left)
textWidth=rc.right-rc.left;
opts.dwFlags&=~DTT_CALCRECT;
if (bGlow)
{
HDC hSrc=CreateCompatibleDC(hdcPaint);
HGDIOBJ bmp0=SelectObject(hSrc,bMaximized?g_GlowBmpMax:g_GlowBmp);
BLENDFUNCTION func={AC_SRC_OVER,0,255,AC_SRC_ALPHA};
AlphaBlend(hdcPaint,rc.left-11,rc.top,11,rc.bottom-rc.top,hSrc,0,0,11,24,func);
AlphaBlend(hdcPaint,rc.left,rc.top,textWidth,rc.bottom-rc.top,hSrc,11,0,2,24,func);
AlphaBlend(hdcPaint,rc.left+textWidth,rc.top,11,rc.bottom-rc.top,hSrc,13,0,11,24,func);
SelectObject(hSrc,bmp0);
DeleteDC(hSrc);
}
DrawThemeTextEx(theme,hdcPaint,0,0,caption,-1,DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE|DT_END_ELLIPSIS,&rc,&opts);
SelectObject(hdcPaint,font0);
EndBufferedPaint(hBufferedPaint,TRUE);
}
EndPaint(hWnd,&ps);
}
else
{
// Basic Theme
// first draw the caption bar
DefCaptionProc(hWnd,uMsg,wParam,lParam);
// then draw the caption directly in the window DC
HDC hdc=GetWindowDC(hWnd);
// exclude the caption buttons
rc.right-=g_SysButtonSize.cx+5;
rc.top=rc.bottom-g_SysButtonSize.cy;
rc.left+=g_CustomCaption[2].leftPadding;
if (bIcon)
{
DrawIconEx(hdc,rc.left,rc.bottom-iconSize-g_CustomCaption[2].topPadding,hIcon,iconSize,iconSize,0,NULL,DI_NORMAL|DI_NOMIRROR);
rc.left+=iconSize;
}
rc.left+=g_CustomCaption[2].iconPadding;
HFONT font0=(HFONT)SelectObject(hdc,font);
RECT rcText={0,0,0,0};
opts.dwFlags|=DTT_CALCRECT;
DrawThemeTextEx(theme,hdc,0,0,caption,-1,DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE|DT_CALCRECT,&rcText,&opts);
int textWidth=rcText.right-rcText.left;
if (bCenter && textWidth<rc.right-rc.left)
{
rc.left+=(rc.right-rc.left-textWidth)/2;
}
if (textWidth>rc.right-rc.left)
textWidth=rc.right-rc.left;
opts.dwFlags&=~DTT_CALCRECT;
if (bGlow)
{
HDC hSrc=CreateCompatibleDC(hdc);
HGDIOBJ bmp0=SelectObject(hSrc,bMaximized?g_GlowBmpMax:g_GlowBmp);
BLENDFUNCTION func={AC_SRC_OVER,0,255,AC_SRC_ALPHA};
AlphaBlend(hdc,rc.left-11,rc.top,11,rc.bottom-rc.top,hSrc,0,0,11,24,func);
AlphaBlend(hdc,rc.left,rc.top,textWidth,rc.bottom-rc.top,hSrc,11,0,2,24,func);
AlphaBlend(hdc,rc.left+textWidth,rc.top,11,rc.bottom-rc.top,hSrc,13,0,11,24,func);
SelectObject(hSrc,bmp0);
DeleteDC(hSrc);
}
DrawThemeTextEx(theme,hdc,0,0,caption,-1,DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE|DT_END_ELLIPSIS,&rc,&opts);
SelectObject(hdc,font0);
ReleaseDC(hWnd,hdc);
}
DeleteObject(font);
CloseThemeData(theme);
return 0;
}
return DefCaptionProc(hWnd,uMsg,wParam,lParam);
}
// Replacement proc for the "Client Caption" class that hooks the main frame and the caption windows
static LRESULT CALLBACK ClassCaptionProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
if (uMsg==WM_CREATE)
{
WNDPROC proc=(WNDPROC)SetWindowLongPtr(hWnd,GWLP_WNDPROC,(LONG_PTR)SubclassCaptionProc);
SetProp(hWnd,MAKEINTATOM(g_SubclassAtom),(HANDLE)proc);
HWND frame=GetParent(hWnd);
proc=(WNDPROC)SetWindowLongPtr(frame,GWLP_WNDPROC,(LONG_PTR)SubclassFrameProc);
SetProp(frame,MAKEINTATOM(g_SubclassAtom),(HANDLE)proc);
PostMessage(frame,g_Message,0,0);
}
return CallWindowProc(g_OldClassCaptionProc,hWnd,uMsg,wParam,lParam);
}
static BOOL CALLBACK EnumTopWindows( HWND hwnd, LPARAM lParam )
{
DWORD processId;
DWORD threadId=GetWindowThreadProcessId(hwnd,&processId);
if (processId==GetCurrentProcessId())
{
HWND caption=FindWindowEx(hwnd,NULL,L"Client Caption",NULL);
if (caption)
{
LogToFile(CIE_LOG,L"InitClassicIE: caption=%p",caption);
if (!g_OldClassCaptionProc)
g_OldClassCaptionProc=(WNDPROC)SetClassLongPtr(caption,GCLP_WNDPROC,(LONG_PTR)ClassCaptionProc);
WNDPROC proc=(WNDPROC)SetWindowLongPtr(caption,GWLP_WNDPROC,(LONG_PTR)SubclassCaptionProc);
SetProp(caption,MAKEINTATOM(g_SubclassAtom),(HANDLE)proc);
proc=(WNDPROC)SetWindowLongPtr(hwnd,GWLP_WNDPROC,(LONG_PTR)SubclassFrameProc);
SetProp(hwnd,MAKEINTATOM(g_SubclassAtom),(HANDLE)proc);
PostMessage(hwnd,g_Message,0,0);
}
}
return TRUE;
}
void InitClassicIE( HMODULE hModule )
{
CRegKey regKey;
if (regKey.Open(HKEY_CURRENT_USER,GetSettingsRegPath())==ERROR_SUCCESS)
{
DWORD val;
if (regKey.QueryDWORDValue(L"CustomAero",val)==ERROR_SUCCESS)
{
g_CustomCaption[0].leftPadding=(val&255);
g_CustomCaption[0].topPadding=((val>>8)&255);
g_CustomCaption[0].iconPadding=((val>>16)&255);
}
if (regKey.QueryDWORDValue(L"CustomAeroMax",val)==ERROR_SUCCESS)
{
g_CustomCaption[1].leftPadding=(val&255);
g_CustomCaption[1].topPadding=((val>>8)&255);
g_CustomCaption[1].iconPadding=((val>>16)&255);
}
if (regKey.QueryDWORDValue(L"CustomBasic",val)==ERROR_SUCCESS)
{
g_CustomCaption[2].leftPadding=(val&255);
g_CustomCaption[2].topPadding=((val>>8)&255);
g_CustomCaption[2].iconPadding=((val>>16)&255);
}
}
g_Message=RegisterWindowMessage(L"ClassicIE.Injected");
g_SubclassAtom=GlobalAddAtom(L"ClassicIE.Subclass");
ChangeWindowMessageFilter(g_Message,MSGFLT_ADD);
g_GlowBmp=(HBITMAP)LoadImage(g_Instance,MAKEINTRESOURCE(IDB_GLOW),IMAGE_BITMAP,0,0,LR_CREATEDIBSECTION);
PremultiplyBitmap(g_GlowBmp,GetSettingInt(L"GlowColor"));
g_GlowBmpMax=(HBITMAP)LoadImage(g_Instance,MAKEINTRESOURCE(IDB_GLOW),IMAGE_BITMAP,0,0,LR_CREATEDIBSECTION);
PremultiplyBitmap(g_GlowBmpMax,GetSettingInt(L"MaxGlowColor"));
EnumWindows(EnumTopWindows,0);
}
| 32.685879 | 137 | 0.73629 | Duzzy-ExoDuus |
82ebc3afc48794c55ae6c033eb8b3d02d5e9b2e1 | 1,524 | cpp | C++ | code/920.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 23 | 2020-03-30T05:44:56.000Z | 2021-09-04T16:00:57.000Z | code/920.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 1 | 2020-05-10T15:04:05.000Z | 2020-06-14T01:21:44.000Z | code/920.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 6 | 2020-03-30T05:45:04.000Z | 2020-08-13T10:01:39.000Z | #include <bits/stdc++.h>
#define INF 2000000000
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isLeaf(TreeNode* root) {
return root->left == NULL && root->right == NULL;
}
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ostream& operator << (ostream& os, const vector<int>& vec){
for (int x: vec)
os << x << " ";
os << endl;
return os;
}
ostream& operator << (ostream& os, const vector<vector<int>>& vec){
for (auto& v: vec){
for (int x: v)
os << x << " ";
os << endl;
}
return os;
}
class Solution {
int f[105][105];
public:
int numMusicPlaylists(int N, int L, int K) {
if (L < N) return 0;
const int M = 1000000007;
f[0][0] = 1;
for (int i = 1; i <= L; ++i)
for (int j = 1; j <= N; ++j)
f[i][j] = 1ll * f[i - 1][j - 1] * (N - j + 1) % M +
1ll * f[i - 1][j] * max(j - K, 0) % M,
f[i][j] %= M;
return f[L][N];
}
};
Solution sol;
void init(){
}
void solve(){
// sol.convert();
}
int main(){
init();
solve();
return 0;
}
| 20.876712 | 68 | 0.463255 | Nightwish-cn |
82ebed1201a7f4989f1d879d85456272000dd064 | 1,541 | cpp | C++ | KnightmareRemake/GameMain.cpp | pdpdds/knightmare | 25323acb23a0af326cebb6f342e30ccbfe0c2f0d | [
"BSD-2-Clause"
] | null | null | null | KnightmareRemake/GameMain.cpp | pdpdds/knightmare | 25323acb23a0af326cebb6f342e30ccbfe0c2f0d | [
"BSD-2-Clause"
] | null | null | null | KnightmareRemake/GameMain.cpp | pdpdds/knightmare | 25323acb23a0af326cebb6f342e30ccbfe0c2f0d | [
"BSD-2-Clause"
] | null | null | null | #include "GameMain.h"
#include "CGameCore.h"
HINSTANCE g_hInst;
HWND g_hWnd;
#define SPRITE_DIAMETER 30
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
g_hInst = hInstance;
static char Name[] = "Knightmare";
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = CGameCore::WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = (HINSTANCE)GetWindowLong(NULL, GWL_HINSTANCE);
wndclass.hIcon = LoadIcon(NULL, "YUKINO");
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = Name;
RegisterClass(&wndclass);
g_hWnd = CreateWindow(Name,
"Knightmare", WS_POPUP | WS_VISIBLE,
200,
60, SCREEN_WIDTH,
SCREEN_HEIGHT,
NULL,
NULL,
(HINSTANCE)GetWindowLong(NULL, GWL_HINSTANCE),
NULL);
ShowWindow(g_hWnd, SW_SHOW);
UpdateWindow(g_hWnd);
CGameCore::GetInstance()->Initialize(hInstance, g_hWnd, SCREEN_WIDTH, SCREEN_HEIGHT);
SetTimer(g_hWnd, 1, 980, NULL);
while (TRUE)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (!GetMessage(&msg, NULL, 0, 0))
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else if (CGameCore::GetInstance()->GetPause())
{
WaitMessage();
}
else
{
CGameCore::GetInstance()->ProcessGame();
}
}
return 0;
}
| 18.129412 | 86 | 0.710578 | pdpdds |
82ede2568f481afb8ea5d7a75b26cea6097b188a | 841 | cpp | C++ | Leetcode/869_reorderedPowerOf2.cpp | ZZh2333/ubuntuProjectFiles | ded3d74e040bf6683b3b67a6956eb6fbe5805155 | [
"MIT"
] | null | null | null | Leetcode/869_reorderedPowerOf2.cpp | ZZh2333/ubuntuProjectFiles | ded3d74e040bf6683b3b67a6956eb6fbe5805155 | [
"MIT"
] | null | null | null | Leetcode/869_reorderedPowerOf2.cpp | ZZh2333/ubuntuProjectFiles | ded3d74e040bf6683b3b67a6956eb6fbe5805155 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool reorderedPowerOf2(int n)
{
vector<int> search = contDigital(n);
vector<vector<int>> allPossible;
for (int i = 0; i < 30; i++)
{
allPossible.push_back(contDigital(pow(2, i)));
}
for (int i = 0; i < allPossible.size(); i++)
{
if (search == allPossible[i])
{
return true;
}
}
return false;
}
vector<int> contDigital(int n)
{
vector<int> count = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
while (n != 0)
{
count[n % 10]++;
n = n / 10;
}
return count;
}
};
int main()
{
Solution solve;
int n = 46;
cout << solve.reorderedPowerOf2(n) << endl;
} | 20.512195 | 59 | 0.450654 | ZZh2333 |
82ededae93c7b0a0e9de59b4981a360c47a25df0 | 242 | hh | C++ | hackt_docker/hackt/src/lexer/input_manager.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/lexer/input_manager.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/lexer/input_manager.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | // aliased to different file name so "parser/lexyacc-prefix.awk"
// won't rename it.
#include "lexer/yyin_manager.hh"
namespace HAC {
namespace lexer {
typedef yyin_manager input_manager;
} // end namespace lexer
} // end namespace HAC
| 22 | 65 | 0.735537 | broken-wheel |
82f2fde8ae28b38d4bf29c8934c452428be9d414 | 3,470 | cpp | C++ | DSP/extensions/TrajectoryLib/sources/Bspline2D.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | null | null | null | DSP/extensions/TrajectoryLib/sources/Bspline2D.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | null | null | null | DSP/extensions/TrajectoryLib/sources/Bspline2D.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | null | null | null | /*
* Bspline Function Unit for TTBlue
* based on the bspline code by Jasch: http://www.jasch.ch/
* ported by Nils Peters
*
*/
#include "Bspline2D.h"
#define thisTTClass Bspline2D
#define thisTTClassName "bspline.2D"
#define thisTTClassTags "audio, trajectory, 2D, spline"
TT_AUDIO_CONSTRUCTOR
{ //addAttribute(A, kTypeFloat64);
addAttribute(Degree, kTypeUInt8);
addAttribute(Steps, kTypeUInt16);
addAttribute(Dimen, kTypeUInt8);
addAttribute(Resolution, kTypeUInt16);//was size
setProcessMethod(processAudio);
// setCalculateMethod(calculateValue);
}
Bspline2D::~Bspline2D()
{
;
}
//TTErr Bspline2D::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
//{
// y = x;
// return kTTErrNone;
//}
void Bspline2D::calculatePoint()
{
TTUInt16 i;
TTFloat64 temp;
point3D[0] = 0;//x
point3D[1] = 0;//y
point3D[2] = 0;//z
for ( i = 0; i <= mResolution; i++) {
temp = calculateBlend(i, mDegree); // same blend is used for each dimension coordinate
b_op[0] += b_control[i*3] * temp;
b_op[1] += b_control[i*3+1] * temp;
b_op[2] += b_control[i*3+2] * temp;
}
}
float Bspline2D::calculateBlend(TTUInt16 k, TTUInt16 t)
{
TTFloat64 value;
TTFloat64 v = interval;
if (t == 1) { // base case for the recursion
if ((b_knots[k] <= v) && (v < b_knots[k+1])) {
value=1;
} else {
value=0;
}
} else {
if ((b_knots[k + t - 1] == b_knots[k]) && (b_knots[k + t] == b_knots[k + 1])) { // check for divide by zero
value = 0;
} else if (b_knots[k + t - 1] == b_knots[k]) { // if a term's denominator is zero, use just the other
value = (b_knots[k + t] - v) / (b_knots[k + t] - b_knots[k + 1]) * calculateBlend(k + 1, t - 1);
} else if (b_knots[k + t] == b_knots[k + 1]) {
value = (v - b_knots[k]) / (b_knots[k + t - 1] - b_knots[k]) * calculateBlend(k, t - 1);
} else {
value = (v - b_knots[k]) / (b_knots[k + t - 1] - b_knots[k]) * calculateBlend(k, t - 1) +
(b_knots[k + t] - v) / (b_knots[k + t] - b_knots[k + 1]) * calculateBlend(k + 1, t - 1);
}
}
return value;
}
void Bspline2D::calculateKnots() // generate knot-vector
{
TTUInt8 i, t, n;
n = mResolution;
t = mDegree;
for (i = 0; i <= (n + t); i++){
if (i < t) {
b_knots[i] = 0;
} else if ((t <= i) && (i <= n)) {
b_knots[i] = i - t + 1;
} else if (i > n) {
b_knots[i] = n - t + 2; // if n - t = -2 then we're screwed, everything goes to 0
}
}
}
TTErr Bspline2D::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 numOutputChannels = out.getNumChannelsAsInt();
if (numOutputChannels != 2) {
TTValue v = 2;
out.setMaxNumChannels(v);
out.setNumChannels(v);
}
TTAudioSignal& in0 = inputs->getSignal(0);
TTUInt16 vs = in0.getVectorSizeAsInt();
TTSampleValuePtr inSampleX = in0.mSampleVectors[0];
TTSampleValuePtr outSampleX = out.mSampleVectors[0];
TTSampleValuePtr outSampleY = out.mSampleVectors[1];
TTFloat64 f;
for (int i=0; i<vs; i++) {
f = inSampleX[i] * 0.5; //0... 1.
if ((f > 0) && (f < 1)){
interval = f * (TTFloat64)((mResolution - mDegree) + 2);
calculatePoint(); // output intermediate point
outSampleX[i] = b_op[0];
outSampleY[i] = b_op[1];
//outSampleZ[i] = b_op[2];
} else if (f <= 0.0){
// output the first point
} else if (f >= 1.0){
// output the last point
}
}
return kTTErrNone;
}
| 25.514706 | 109 | 0.606916 | avilleret |
82f3159b433cb8391baa047bfd5822b211498d07 | 231 | cpp | C++ | tests/codegen/unroll.cpp | casparant/bpftrace | a6823165a521e894b3fb028733131878cf70d3a7 | [
"Apache-2.0"
] | 5,119 | 2018-10-08T15:19:24.000Z | 2022-03-31T15:03:48.000Z | tests/codegen/unroll.cpp | casparant/bpftrace | a6823165a521e894b3fb028733131878cf70d3a7 | [
"Apache-2.0"
] | 1,568 | 2018-10-08T19:14:25.000Z | 2022-03-31T01:44:41.000Z | tests/codegen/unroll.cpp | casparant/bpftrace | a6823165a521e894b3fb028733131878cf70d3a7 | [
"Apache-2.0"
] | 838 | 2018-10-08T20:16:47.000Z | 2022-03-31T06:15:58.000Z | #include "common.h"
namespace bpftrace {
namespace test {
namespace codegen {
TEST(codegen, unroll)
{
test("BEGIN { @i = 0; unroll(5) { @i += 1 } }", NAME);
}
} // namespace codegen
} // namespace test
} // namespace bpftrace
| 15.4 | 56 | 0.636364 | casparant |
d201aacc0ade4e8863df807d734fc8b348108d97 | 18,814 | cpp | C++ | src/main.cpp | stephan2nd/cpp-accelerator-settings-evolution | 653990ed991a75db6055790aafb8b628c685763a | [
"MIT"
] | null | null | null | src/main.cpp | stephan2nd/cpp-accelerator-settings-evolution | 653990ed991a75db6055790aafb8b628c685763a | [
"MIT"
] | null | null | null | src/main.cpp | stephan2nd/cpp-accelerator-settings-evolution | 653990ed991a75db6055790aafb8b628c685763a | [
"MIT"
] | null | null | null | #include <iostream>
#include <random>
#include <fstream>
#include <vector>
#include "Genome.hpp"
#include "Population.hpp"
#include "Accelerator.hpp"
#include "DriftTube.hpp"
#include "HKick.hpp"
#include "VKick.hpp"
#include "QuadrupoleMagnet.hpp"
#include "Slit.hpp"
#include "Screen.hpp"
#include "Trafo.hpp"
#include "DipoleMagnet.hpp"
#include "RectangularDipoleMagnet.hpp"
#include "ProfileGrid.hpp"
using namespace std;
Accelerator acc;
Trafo* t0;
Trafo* t1;
Trafo* t2;
Trafo* t3;
Trafo* t4;
Trafo* t5;
Trafo* t6;
Trafo* t7;
Trafo* final_trafo;
vector<Trafo*> trafos;
double fitness_simple_acc(const vector<double>& genes)
{
double sum_off_diff = 0;
acc.setNormValues(genes);
acc.startSimulation(20000);
sum_off_diff += t1->getCounts() + 10*t2->getCounts() + 100*t3->getCounts() + 1000*t4->getCounts() + 100000*final_trafo->getCounts();
return sum_off_diff;
}
void experiment_simple_acc()
{
double width = 0.1;
double height = 0.1;
t1 = new Trafo("T1");
t2 = new Trafo("T2");
t3 = new Trafo("T3");
t4 = new Trafo("T4");
int dpm = 1000;
acc.appendDevice(new DriftTube("Drift1", width, height, 0.25));
acc.appendDevice(t1);
acc.appendDevice(new Screen("Screen1", width, height, dpm));
acc.appendDevice(new HKick("HKick1", -0.1, 0.1));
acc.appendDevice(new DriftTube("Drift2", width, height, 0.25));
acc.appendDevice(t2);
acc.appendDevice(new Screen("Screen2", width, height, dpm));
acc.appendDevice(new QuadrupoleMagnet("QD1", width, height, 0.5, 0.0, 10));
acc.appendDevice(new QuadrupoleMagnet("QD2", width, height, 0.5, -10, 0.0));
acc.appendDevice(new Screen("Screen3", width, height, dpm));
acc.appendDevice(new DriftTube("Drift3", width, height, 4.0));
acc.appendDevice(t3);
acc.appendDevice(new Screen("Screen4", width, height, dpm));
acc.appendDevice(new DipoleMagnet("BEND1", width, height, 2.0, 0.5));
acc.appendDevice(new DriftTube("Drift4", width, height, 2.0));
acc.appendDevice(t4);
acc.appendDevice(new Screen("Screen5", width, height, dpm));
acc.appendDevice(new QuadrupoleMagnet("QD3", width, height, 0.5, 0.0, 10));
acc.appendDevice(new QuadrupoleMagnet("QD4", width, height, 0.5, -10, 0.0));
acc.appendDevice(new DriftTube("Drift5", width, height, 4.0));
acc.appendDevice(new Screen("Screen6", width, height, dpm));
acc.appendDevice(new HKick("HKick2", -0.1, 0.1));
acc.appendDevice(new DriftTube("Drift6", width, height, 2.0));
acc.appendDevice(new HKick("HKick3", -0.1, 0.1));
acc.appendDevice(new DriftTube("Drift7", width, height, 2.0));
acc.appendDevice(new Slit("Slit", -0.05, -0.04, -0.01, 0.01));
acc.appendDevice(new Screen("Screen7", width, height, dpm));
final_trafo = new Trafo("FinalTrafo");
acc.appendDevice(final_trafo);
acc.setScreenIgnore(true);
default_random_engine rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
int number_of_genes = acc.settingSize();
int number_of_genomes = 10;
int number_of_generations = 2000;
EvolutionParameters ep;
ep.n_keep = 2;
ep.sigma_survive = 0.3; // 0.3 scheint ein guter Wert zu sein // 0.1 wirft 60% weg, 0.2 wirft 40% weg
ep.p_mutate_disturbe = 0.7;
ep.p_mutate_replace = 0.05;
ep.p_non_homologous_crossover = 0.10;
ep.b_crossing_over = true;
ep.b_mutate_mutation_rate = true;
ep.n_min_genes_till_cross = 1;
ep.n_max_genes_till_cross = number_of_genes/2;
Population p(number_of_genomes, number_of_genes, rnd);
p.evaluate(fitness_simple_acc);
for( int i=0; i<number_of_generations; i++ ) {
p = p.createOffspring(ep, rnd);
p.evaluate(fitness_simple_acc);
cout << "Generation " << i << ":\t" << p.toString() << endl;
}
cout << p.getBestGenome() << endl;
acc.setScreenIgnore(false);
acc.setNormValues(p.getBestGenome().getGenes());
acc.startSimulation(1000000);
cout << acc.toString() << endl;
((Screen*) acc.getDeviceByName("Screen1"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen2"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen3"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen4"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen5"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen6"))->exportHistogram();
((Screen*) acc.getDeviceByName("Screen7"))->exportHistogram();
}
double fitness_m3_beamline(const vector<double>& genes)
{
double f=0;
acc.setNormValues(genes);
acc.startSimulation(80000);
f = t0->getCounts();
f = f * (1 + t1->getCounts() - t1->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("UMADG1g"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("UMADG1g"))->centerY())));
f = f * (1 + t2->getCounts() - t2->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("UMADG2g"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("UMADG2g"))->centerY())));
f = f * (1 + t3->getCounts() - t3->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("UMADG3g"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("UMADG3g"))->centerY())));
f = f * (1 + t4->getCounts() - t4->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("UMADG4g"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("UMADG4g"))->centerY())));
f = f * (1 + t5->getCounts());
f = f * (1 + t6->getCounts() - t6->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("UM3DG6g"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("UM3DG6g"))->centerY())));
f = f * (1 + t7->getCounts() - t7->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENag"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENag"))->centerY())));
f = f * (1 + t7->getCounts() - t7->getCounts()*(abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENbg"))->centerX()) + abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENbg"))->centerY())));
/* f += t0->getCounts() * (1 + t1->getCounts()) * (1 + t2->getCounts()) * (1 + t3->getCounts()) * (1 + t4->getCounts()) * (1 + t5->getCounts()) * (1 + t6->getCounts()) * (1 + t7->getCounts());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG1g"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG1g"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG2g"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG2g"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG3g"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG3g"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG4g"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UMADG4g"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UM3DG6g"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("UM3DG6g"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENag"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENag"))->centerY());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENbg"))->centerX());
f -= 1E6 * abs(((ProfileGrid*) acc.getDeviceByName("TARGET_SCREENbg"))->centerY());*/
return f;
}
double fitness_mix_beamline(const vector<double>& genes)
{
double f=1;
double fmax = 1;
acc.setNormValues(genes);
acc.startSimulation(50000);
for( auto it=trafos.begin(); it<trafos.end(); it++ ){
//f = f * ( 1 + (*it)->getCounts() );
f = f + (*it)->getCounts();
//fmax = fmax * (1 + 10000);
fmax = fmax + 50000;
}
return (f/fmax) - 0.01 * acc.excitation();
}
void experiment_m3_beamline()
{
t0 = new Trafo("T0");
t1 = new Trafo("T1");
t2 = new Trafo("T2");
t3 = new Trafo("T3");
t4 = new Trafo("T4");
t5 = new Trafo("T5");
t6 = new Trafo("T6");
t7 = new Trafo("T7");
IonSource ion_source(12, 6, 2, 1000, 0., 0.00012, 0., 0.00245, 0., 0.00063, 0., 0.00316, 0., 0., 0., 0.);
//IonSource ion_source(12, 6, 2, 1000, 0., 0.00006, 0., 0.00150, 0., 0.00030, 0., 0.00212, 0., 0., 0., 0.);
//IonSource ion_source(12, 6, 2, 1000, 0., 0.00003, 0., 0.00050, 0., 0.00015, 0., 0.00050, 0., 0., 0., 0.);
acc.setIonSource(ion_source);
double max_quad_strength = 7;
double drift_width = 0.040;
double grid_width = 0.040;
double dpm = 5000;
acc.appendDevice(new DriftTube("", drift_width, drift_width, 1.1 + 0.1));
acc.appendDevice(t0);
acc.appendDevice(new RectangularDipoleMagnet("UT1MK0", 0.080, 0.040, -10.*M_PI*-4.894/180., -10.*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.1 + 2.3385 + 0.124));
// acc.appendDevice(new Screen("PROBE", grid_width, grid_width, dpm));
acc.appendDevice(new HKick("UMAMS1H", -0.1, 0.1));
acc.appendDevice(new VKick("UMAMS1V", -0.1, 0.1));
// acc.appendDevice(new Screen("PROBE2", grid_width, grid_width, dpm));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.124 + 0.0935 + 0.0335));
// acc.appendDevice(new Screen("PROBE3", grid_width, grid_width, dpm));
acc.appendDevice(new QuadrupoleMagnet("UMAQD11", 0.040, 0.040, 0.318, 0.0, max_quad_strength));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0335 + 0.0335));
acc.appendDevice(new QuadrupoleMagnet("UMAQD12", 0.040, 0.040, 0.318, -max_quad_strength, 0.0));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0335 + 0.100));
// acc.appendDevice(new DriftTube("DUMMY", drift_width, drift_width, 4));
acc.appendDevice(new Screen("UMADG1", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("UMADG1g", grid_width, grid_width, 100));
acc.appendDevice(t1);
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.460));
acc.appendDevice(new RectangularDipoleMagnet("UMAMU1", 0.080, 0.040, -12.5*M_PI*-7.699/180., -12.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.465));
acc.appendDevice(new Screen("UMADG2", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("UMADG2g", grid_width, grid_width, 100));
acc.appendDevice(t2);
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.465));
acc.appendDevice(new RectangularDipoleMagnet("UMAMU2a", 0.080, 0.040, -22.5*M_PI*-2.739/180., -22.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.3335));
acc.appendDevice(new QuadrupoleMagnet("UMAQD21", 0.040, 0.040, 0.318, 0.0, max_quad_strength));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0335 + 0.0335));
acc.appendDevice(new QuadrupoleMagnet("UMAQD22", 0.040, 0.040, 0.318, -max_quad_strength, 0.0));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.3335));
acc.appendDevice(new RectangularDipoleMagnet("UMAMU2b", 0.080, 0.040, -22.5*M_PI*-2.739/180., -22.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.300));
acc.appendDevice(new Screen("UMADG3", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("UMADG3g", grid_width, grid_width, 100));
acc.appendDevice(t3);
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.300));
acc.appendDevice(new RectangularDipoleMagnet("UMAMU2c", 0.080, 0.040, -22.5*M_PI*-2.739/180., -22.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.3335));
acc.appendDevice(new QuadrupoleMagnet("UMAQD31", 0.040, 0.040, 0.318, 0.0, max_quad_strength));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0335 + 0.0335));
acc.appendDevice(new QuadrupoleMagnet("UMAQD32", 0.040, 0.040, 0.318, -max_quad_strength, 0.0));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.491));
acc.appendDevice(new Screen("UMADG4", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("UMADG4g", grid_width, grid_width, 100));
acc.appendDevice(t4);
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.275));
acc.appendDevice(new HKick("UMAMS2H", -0.1, 0.1));
acc.appendDevice(new VKick("UMAMS2V", -0.1, 0.1));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.124 + 0.3435 + 0.100));
acc.appendDevice(new RectangularDipoleMagnet("UM2MU5", 0.080, 0.040, -22.5*M_PI*-2.739/180., -22.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.700));
acc.appendDevice(new RectangularDipoleMagnet("UM3MU6", 0.080, 0.040, -22.5*M_PI*-2.739/180., -22.5*M_PI/180.));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0195 + 0.124));
acc.appendDevice(t5);
acc.appendDevice(new HKick("UM1MS3H", -0.1, 0.1));
acc.appendDevice(new VKick("UM1MS3V", -0.1, 0.1));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.124 + 0.3325 + 0.0335));
acc.appendDevice(new QuadrupoleMagnet("UM3QD41", 0.040, 0.040, 0.318, 0.0, max_quad_strength));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.0335 + 0.0335));
acc.appendDevice(new QuadrupoleMagnet("UM3QD42", 0.040, 0.040, 0.318, -max_quad_strength, 0.0));
acc.appendDevice(new DriftTube("", drift_width, drift_width, 0.249));
acc.appendDevice(new Screen("UM3DG6", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("UM3DG6g", grid_width, grid_width, 100));
acc.appendDevice(t6);
acc.appendDevice(new DriftTube("", drift_width, drift_width, 2.5845 + 2.400));
acc.appendDevice(new Screen("TARGET_SCREENa", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("TARGET_SCREENag", grid_width, grid_width, 100));
acc.appendDevice(new Slit("TARGET_SIZE", -0.002, 0.002, -0.002, 0.002));
acc.appendDevice(new Screen("TARGET_SCREENb", grid_width, grid_width, dpm));
acc.appendDevice(new ProfileGrid("TARGET_SCREENbg", grid_width, grid_width, 100));
acc.appendDevice(t7);
acc.setScreenIgnore(true);
// cout << acc.toString() << endl;
default_random_engine rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
int number_of_genes = acc.settingSize();
int number_of_genomes = 30;
int number_of_generations = 300;
EvolutionParameters ep;
ep.n_keep = 2;
ep.sigma_survive = 0.3; // 0.3 scheint ein guter Wert zu sein // 0.1 wirft 60% weg, 0.2 wirft 40% weg
ep.p_mutate_disturbe = 0.80; // 0.60
ep.p_mutate_replace = 0.05; // 0.05
ep.p_non_homologous_crossover = 0.025; // 0.05
ep.b_crossing_over = true;
ep.b_mutate_mutation_rate = true;
ep.n_min_genes_till_cross = 2;
ep.n_max_genes_till_cross = number_of_genes/2;
Population p(number_of_genomes, number_of_genes, rnd);
p.evaluate(fitness_m3_beamline);
ofstream outfile;
outfile.open("fitness.dat", ios::out | ios::trunc );
outfile << "func\n";
for( int i=0; i<number_of_generations; i++ ) {
p = p.createOffspring(ep, rnd);
p.evaluate(fitness_m3_beamline);
outfile << i << "," << p.getBestGenome().fitness() << "\n";
cout << "Generation " << i << ":\t" << p.toString() << endl;
//cout << "Generation " << i << ":\t" << p.toLine() << endl;
}
outfile.close();
cout << p.getBestGenome() << endl;
acc.setScreenIgnore(false);
acc.setNormValues(p.getBestGenome().getGenes());
acc.startSimulation(10000000);
cout << acc.toString() << endl;
acc.writeMirkoMakro("mirko.mak");
((Screen*) acc.getDeviceByName("UMADG1"))->exportHistogram();
((Screen*) acc.getDeviceByName("UMADG2"))->exportHistogram();
((Screen*) acc.getDeviceByName("UMADG3"))->exportHistogram();
((Screen*) acc.getDeviceByName("UMADG4"))->exportHistogram();
((Screen*) acc.getDeviceByName("UM3DG6"))->exportHistogram();
((Screen*) acc.getDeviceByName("TARGET_SCREENa"))->exportHistogram();
((Screen*) acc.getDeviceByName("TARGET_SCREENb"))->exportHistogram();
// ((Screen*) acc.getDeviceByName("PROBE"))->exportHistogram();
// ((Screen*) acc.getDeviceByName("PROBE2"))->exportHistogram();
// ((Screen*) acc.getDeviceByName("PROBE3"))->exportHistogram();
}
void experiment_mix_beamline()
{
IonSource ion_source(12, 6, 2, 1000, 0., 0.0000, 0., 0.0002, 0., 0.0000, 0., 0.0002, 0., 0., 0., 0.);
//IonSource ion_source(12, 6, 2, 1000, 0., 0.00012, 0., 0.00245, 0., 0.00063, 0., 0.00316, 0., 0., 0., 0.);
//IonSource ion_source(12, 6, 2, 1000, 0., 0.00006, 0., 0.00150, 0., 0.00030, 0., 0.00212, 0., 0., 0., 0.);
//IonSource ion_source(12, 6, 2, 1000, 0., 0.00003, 0., 0.00050, 0., 0.00015, 0., 0.00050, 0., 0., 0., 0.);
acc.setIonSource(ion_source);
bool add_trafo_to_each_screen = true;
acc.appendDevicesFromMirkoFile("apertures01.mix", add_trafo_to_each_screen);
acc.appendDevice(new Slit("TARGET_SIZE", -0.002, 0.002, -0.002, 0.002));
acc.appendDevice(new Screen("TARGET", 0.1, 0.1, 1000));
acc.appendDevice(new Trafo("TARGET"));
acc.getTrafos(trafos);
acc.setScreenIgnore(true);
default_random_engine rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
int number_of_genes = acc.settingSize()*2;
int number_of_genomes = 100;
int number_of_generations = 100;
EvolutionParameters ep;
ep.n_keep = 2;
ep.sigma_survive = 0.3; // 0.3 scheint ein guter Wert zu sein // 0.1 wirft 60% weg, 0.2 wirft 40% weg
ep.p_mutate_disturbe = 0.80; // 0.60
ep.p_mutate_replace = 0.05; // 0.05
ep.p_non_homologous_crossover = 0.08; // 0.05
ep.b_crossing_over = true;
ep.b_mutate_mutation_rate = true;
ep.n_min_genes_till_cross = 1; // 2
ep.n_max_genes_till_cross = number_of_genes/2;
Population p(number_of_genomes, number_of_genes, rnd);
p.evaluate(fitness_mix_beamline);
ofstream outfile;
outfile.open("fitness.dat", ios::out | ios::trunc );
outfile << "func\n";
for( int i=0; i<number_of_generations and p.getBestGenome().fitness()<0.99; i++ ) {
p = p.createOffspring(ep, rnd);
p.evaluate(fitness_mix_beamline);
outfile << i << "," << p.getBestGenome().fitness() << "\n";
//cout << "Generation " << i << ":\t" << p.toString() << endl;
cout << "Generation " << i << ":\t" << p.toLine() << endl;
}
outfile.close();
cout << p.getBestGenome() << endl;
acc.setScreenIgnore(false);
acc.setNormValues(p.getBestGenome().getGenes());
acc.startSimulation(10000000);
cout << acc.toString() << endl;
acc.writeMirkoMakro("mirko.mak");
acc.exportHistograms();
}
int main(int argc , char *argv[])
{
cout << "start" << endl;
clock_t begin = clock();
time_t start, finish;
time(&start);
//experiment_simple_acc();
//experiment_m3_beamline();
experiment_mix_beamline();
time(&finish);
float diff = (((float)clock()-(float)begin)/CLOCKS_PER_SEC);
cout << "CPU-time: " << diff << " s" << endl;
cout << "runtime: " << difftime(finish,start) << " s" << endl;
return 0;
}
| 44.372642 | 197 | 0.66695 | stephan2nd |
d201e0518fbb66f8cbf1ac94aea76743d477339c | 4,943 | cpp | C++ | ufora/FORA/Judgment/RandomJOVGenerator.py.cpp | ufora/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 571 | 2015-11-05T20:07:07.000Z | 2022-01-24T22:31:09.000Z | ufora/FORA/Judgment/RandomJOVGenerator.py.cpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 218 | 2015-11-05T20:37:55.000Z | 2021-05-30T03:53:50.000Z | ufora/FORA/Judgment/RandomJOVGenerator.py.cpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 40 | 2015-11-07T21:42:19.000Z | 2021-05-23T03:48:19.000Z | /***************************************************************************
Copyright 2015 Ufora 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 "RandomJOVGenerator.hppml"
#include <stdint.h>
#include <boost/python.hpp>
#include "../../native/Registrar.hpp"
#include "../../core/python/CPPMLWrapper.hpp"
#include "../../core/python/ScopedPyThreads.hpp"
#include "../../core/python/ValueLikeCPPMLWrapper.hppml"
#include "../Core/ExecutionContext.hppml"
class RandomJOVGeneratorWrapper :
public native::module::Exporter<RandomJOVGeneratorWrapper> {
public:
std::string getModuleName(void)
{
return "FORA";
}
static PolymorphicSharedPtr<RandomJOVGenerator>*
makeClassBySeed(
int seed,
PolymorphicSharedPtr<Fora::Interpreter::ExecutionContext>& context
)
{
return new PolymorphicSharedPtr<RandomJOVGenerator>(
new RandomJOVGenerator(seed, context)
);
}
static PolymorphicSharedPtr<RandomJOVGenerator>*
makeClassByGenerator(
boost::mt19937& generator,
PolymorphicSharedPtr<Fora::Interpreter::ExecutionContext>& context
)
{
return new PolymorphicSharedPtr<RandomJOVGenerator>(
new RandomJOVGenerator(generator, context)
);
}
static boost::python::object RJOVGRandomValue(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
const JOV& jov
)
{
Nullable<ImplValContainer> r = rjovg->RandomValue(jov);
if (!r) return boost::python::object();
return boost::python::object(*r);
}
static boost::python::object RJOVTGRandomValue(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
const JOVT& jovt
)
{
return RJOVGRandomValue(rjovg, JOV::Tuple(jovt));
}
static PolymorphicSharedPtr<RandomJOVGenerator>
RJOVGSymbolStrings(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
boost::python::list symbolStringsList
)
{
std::vector<std::string> symbol_strings;
int length = boost::python::len(symbolStringsList);
for (long k = 0; k < length; k++)
{
if (boost::python::extract<std::string>(symbolStringsList[k]).check())
symbol_strings.push_back(boost::python::extract<std::string>(symbolStringsList[k])());
else
lassert(false);
}
rjovg->setSymbolStrings(symbol_strings);
return rjovg;
}
static PolymorphicSharedPtr<RandomJOVGenerator> RJOVGsetMaxUnsignedInt(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
unsigned int i
)
{
rjovg->setLikelyMaxUnsignedInt(i);
return rjovg;
}
static PolymorphicSharedPtr<RandomJOVGenerator> RJOVGsetMaxReal(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
double d
)
{
rjovg->setMaxReal(d);
return rjovg;
}
static PolymorphicSharedPtr<RandomJOVGenerator> setMaxStringLength(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
int i
)
{
rjovg->setMaxStringLength(i);
return rjovg;
}
static PolymorphicSharedPtr<RandomJOVGenerator> RJOVGsetMinReal(
PolymorphicSharedPtr<RandomJOVGenerator>& rjovg,
double d
)
{
rjovg->setMinReal(d);
return rjovg;
}
void exportPythonWrapper()
{
using namespace boost::python;
class_<PolymorphicSharedPtr<RandomJOVGenerator> >("RandomJOVGenerator", no_init)
.def("__init__", make_constructor(makeClassBySeed))
.def("__init__", make_constructor(makeClassByGenerator))
.def("symbolStrings", &RJOVGSymbolStrings)
.def("randomValue", &RJOVGRandomValue)
.def("randomValue", &RJOVTGRandomValue)
.def("setMaxUnsignedInt", &RJOVGsetMaxUnsignedInt)
.def("setMaxReal", &RJOVGsetMaxReal)
.def("setMinReal", &RJOVGsetMinReal)
.def("setMaxStringLength", &setMaxStringLength)
;
}
};
//explicitly instantiating the registration element causes the linker to need
//this file
template<>
char native::module::Exporter<RandomJOVGeneratorWrapper>::mEnforceRegistration =
native::module::ExportRegistrar<
RandomJOVGeneratorWrapper>::registerWrapper();
| 31.484076 | 91 | 0.644346 | ufora |
d20272ed7b7e9d0d54b18926db4a1c5080b20d29 | 4,938 | cpp | C++ | ivld/src/v20210903/model/AudioInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | ivld/src/v20210903/model/AudioInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | ivld/src/v20210903/model/AudioInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/ivld/v20210903/model/AudioInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ivld::V20210903::Model;
using namespace std;
AudioInfo::AudioInfo() :
m_contentHasBeenSet(false),
m_startTimeStampHasBeenSet(false),
m_endTimeStampHasBeenSet(false),
m_tagHasBeenSet(false)
{
}
CoreInternalOutcome AudioInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Content") && !value["Content"].IsNull())
{
if (!value["Content"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AudioInfo.Content` IsString=false incorrectly").SetRequestId(requestId));
}
m_content = string(value["Content"].GetString());
m_contentHasBeenSet = true;
}
if (value.HasMember("StartTimeStamp") && !value["StartTimeStamp"].IsNull())
{
if (!value["StartTimeStamp"].IsLosslessDouble())
{
return CoreInternalOutcome(Core::Error("response `AudioInfo.StartTimeStamp` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_startTimeStamp = value["StartTimeStamp"].GetDouble();
m_startTimeStampHasBeenSet = true;
}
if (value.HasMember("EndTimeStamp") && !value["EndTimeStamp"].IsNull())
{
if (!value["EndTimeStamp"].IsLosslessDouble())
{
return CoreInternalOutcome(Core::Error("response `AudioInfo.EndTimeStamp` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_endTimeStamp = value["EndTimeStamp"].GetDouble();
m_endTimeStampHasBeenSet = true;
}
if (value.HasMember("Tag") && !value["Tag"].IsNull())
{
if (!value["Tag"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AudioInfo.Tag` IsString=false incorrectly").SetRequestId(requestId));
}
m_tag = string(value["Tag"].GetString());
m_tagHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void AudioInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_contentHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Content";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_content.c_str(), allocator).Move(), allocator);
}
if (m_startTimeStampHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "StartTimeStamp";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_startTimeStamp, allocator);
}
if (m_endTimeStampHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EndTimeStamp";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_endTimeStamp, allocator);
}
if (m_tagHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Tag";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_tag.c_str(), allocator).Move(), allocator);
}
}
string AudioInfo::GetContent() const
{
return m_content;
}
void AudioInfo::SetContent(const string& _content)
{
m_content = _content;
m_contentHasBeenSet = true;
}
bool AudioInfo::ContentHasBeenSet() const
{
return m_contentHasBeenSet;
}
double AudioInfo::GetStartTimeStamp() const
{
return m_startTimeStamp;
}
void AudioInfo::SetStartTimeStamp(const double& _startTimeStamp)
{
m_startTimeStamp = _startTimeStamp;
m_startTimeStampHasBeenSet = true;
}
bool AudioInfo::StartTimeStampHasBeenSet() const
{
return m_startTimeStampHasBeenSet;
}
double AudioInfo::GetEndTimeStamp() const
{
return m_endTimeStamp;
}
void AudioInfo::SetEndTimeStamp(const double& _endTimeStamp)
{
m_endTimeStamp = _endTimeStamp;
m_endTimeStampHasBeenSet = true;
}
bool AudioInfo::EndTimeStampHasBeenSet() const
{
return m_endTimeStampHasBeenSet;
}
string AudioInfo::GetTag() const
{
return m_tag;
}
void AudioInfo::SetTag(const string& _tag)
{
m_tag = _tag;
m_tagHasBeenSet = true;
}
bool AudioInfo::TagHasBeenSet() const
{
return m_tagHasBeenSet;
}
| 27.131868 | 150 | 0.686108 | suluner |
d2066ec92a515ab33a89cc38bd0cf834677e90e6 | 172 | cpp | C++ | src/np/subset_sum.cpp | zpooky/sputil | 3eddf94655fe4ec5bc2a3b5e487a86d772b038ae | [
"Apache-2.0"
] | null | null | null | src/np/subset_sum.cpp | zpooky/sputil | 3eddf94655fe4ec5bc2a3b5e487a86d772b038ae | [
"Apache-2.0"
] | null | null | null | src/np/subset_sum.cpp | zpooky/sputil | 3eddf94655fe4ec5bc2a3b5e487a86d772b038ae | [
"Apache-2.0"
] | null | null | null | #include "subset_sum.h"
namespace np {
namespace complete {
bool
subset_sum(const sp::Array<int> &) noexcept {
return true;
}
} // namespace complete
} // namespace np
| 14.333333 | 45 | 0.703488 | zpooky |
d2071e73011c882d7d7260a12311e751a08f036e | 859 | cpp | C++ | Source/ThirdPersonShooter/Private/Core/AI/BTService_SetMovementState.cpp | DanialKama/ThirdPersonShooter | 689873bcfcce7ef170df7fc7385d507e71a87a38 | [
"MIT"
] | 7 | 2021-12-03T17:31:34.000Z | 2022-03-16T09:24:46.000Z | Source/ThirdPersonShooter/Private/Core/AI/BTService_SetMovementState.cpp | DanialKama/ThirdPersonShooter | 689873bcfcce7ef170df7fc7385d507e71a87a38 | [
"MIT"
] | 45 | 2021-09-26T12:12:44.000Z | 2022-01-31T07:19:50.000Z | Source/ThirdPersonShooter/Private/Core/AI/BTService_SetMovementState.cpp | DanialKama/ThirdPersonShooter | 689873bcfcce7ef170df7fc7385d507e71a87a38 | [
"MIT"
] | null | null | null | // Copyright 2022 Danial Kamali. All Rights Reserved.
#include "Core/AI/BTService_SetMovementState.h"
#include "Characters/AICharacter.h"
#include "Core/AI/ShooterAIController.h"
UBTService_SetMovementState::UBTService_SetMovementState(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
NodeName = "Set Movement State";
bNotifyTick = false;
bTickIntervals = false;
bNotifyBecomeRelevant = true;
// Initialize variables
MovementState = EMovementState::Walk;
bRelatedToCrouch = false;
bRelatedToProne = false;
}
void UBTService_SetMovementState::OnBecomeRelevant(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
if (const AShooterAIController* Owner = Cast<AShooterAIController>(OwnerComp.GetOwner()))
{
Owner->ControlledPawn->SetMovementState_Implementation(MovementState, bRelatedToCrouch, bRelatedToProne);
}
} | 31.814815 | 107 | 0.80908 | DanialKama |
d20bdee934b63c6dc8b753cff9796ee3a427aa92 | 603 | hpp | C++ | src/RenderSystem.DXGI/DXGIFormatHelper.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | src/RenderSystem.DXGI/DXGIFormatHelper.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | src/RenderSystem.DXGI/DXGIFormatHelper.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | // Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.
#pragma once
#include "Pomdog/Graphics/detail/ForwardDeclarations.hpp"
#include <dxgi.h>
namespace Pomdog {
namespace Detail {
namespace DXGI {
struct DXGIFormatHelper final {
static DXGI_FORMAT ToDXGIFormat(DepthFormat format) noexcept;
static DXGI_FORMAT ToDXGIFormat(SurfaceFormat format) noexcept;
static DXGI_FORMAT ToDXGIFormat(IndexElementSize elementSize) noexcept;
static DXGI_FORMAT ToDXGIFormat(InputElementFormat format) noexcept;
};
} // namespace DXGI
} // namespace Detail
} // namespace Pomdog
| 27.409091 | 75 | 0.78607 | ValtoForks |
d20e1e07ea65e639ef0667b87826a916a61fcefe | 2,280 | cpp | C++ | src/1.4/dom/domGles_texcombiner_commandAlpha_type.cpp | maemo5/android-source-browsing.platform--external--collada | 538700ec332c8306a1283f8dfdb016e493905e6f | [
"MIT"
] | null | null | null | src/1.4/dom/domGles_texcombiner_commandAlpha_type.cpp | maemo5/android-source-browsing.platform--external--collada | 538700ec332c8306a1283f8dfdb016e493905e6f | [
"MIT"
] | null | null | null | src/1.4/dom/domGles_texcombiner_commandAlpha_type.cpp | maemo5/android-source-browsing.platform--external--collada | 538700ec332c8306a1283f8dfdb016e493905e6f | [
"MIT"
] | null | null | null | /*
* Copyright 2006 Sony Computer Entertainment Inc.
*
* Licensed under the MIT Open Source License, for details please see license.txt or the website
* http://www.opensource.org/licenses/mit-license.php
*
*/
#include <dae.h>
#include <dae/daeDom.h>
#include <dom/domGles_texcombiner_commandAlpha_type.h>
#include <dae/daeMetaCMPolicy.h>
#include <dae/daeMetaSequence.h>
#include <dae/daeMetaChoice.h>
#include <dae/daeMetaGroup.h>
#include <dae/daeMetaAny.h>
#include <dae/daeMetaElementAttribute.h>
daeElementRef
domGles_texcombiner_commandAlpha_type::create(DAE& dae)
{
domGles_texcombiner_commandAlpha_typeRef ref = new domGles_texcombiner_commandAlpha_type(dae);
return ref;
}
daeMetaElement *
domGles_texcombiner_commandAlpha_type::registerElement(DAE& dae)
{
daeMetaElement* meta = dae.getMeta(ID());
if ( meta != NULL ) return meta;
meta = new daeMetaElement(dae);
dae.setMeta(ID(), *meta);
meta->setName( "gles_texcombiner_commandAlpha_type" );
meta->registerClass(domGles_texcombiner_commandAlpha_type::create);
daeMetaCMPolicy *cm = NULL;
daeMetaElementAttribute *mea = NULL;
cm = new daeMetaSequence( meta, cm, 0, 1, 1 );
mea = new daeMetaElementArrayAttribute( meta, cm, 0, 1, 3 );
mea->setName( "argument" );
mea->setOffset( daeOffsetOf(domGles_texcombiner_commandAlpha_type,elemArgument_array) );
mea->setElementType( domGles_texcombiner_argumentAlpha_type::registerElement(dae) );
cm->appendChild( mea );
cm->setMaxOrdinal( 0 );
meta->setCMRoot( cm );
// Add attribute: operator
{
daeMetaAttribute *ma = new daeMetaAttribute;
ma->setName( "operator" );
ma->setType( dae.getAtomicTypes().get("Gles_texcombiner_operatorAlpha_enums"));
ma->setOffset( daeOffsetOf( domGles_texcombiner_commandAlpha_type , attrOperator ));
ma->setContainer( meta );
meta->appendAttribute(ma);
}
// Add attribute: scale
{
daeMetaAttribute *ma = new daeMetaAttribute;
ma->setName( "scale" );
ma->setType( dae.getAtomicTypes().get("xsFloat"));
ma->setOffset( daeOffsetOf( domGles_texcombiner_commandAlpha_type , attrScale ));
ma->setContainer( meta );
ma->setIsRequired( false );
meta->appendAttribute(ma);
}
meta->setElementSize(sizeof(domGles_texcombiner_commandAlpha_type));
meta->validate();
return meta;
}
| 28.5 | 96 | 0.752193 | maemo5 |
d2162c55d252d362c48415b6baa06fe572903c9d | 2,754 | cc | C++ | main.cc | sebgiles/pycolmap | 9590ab7b4dbd16348ada8ed63a7e32d30460669f | [
"BSD-3-Clause"
] | null | null | null | main.cc | sebgiles/pycolmap | 9590ab7b4dbd16348ada8ed63a7e32d30460669f | [
"BSD-3-Clause"
] | null | null | null | main.cc | sebgiles/pycolmap | 9590ab7b4dbd16348ada8ed63a7e32d30460669f | [
"BSD-3-Clause"
] | null | null | null | #include <pybind11/pybind11.h>
namespace py = pybind11;
#include "absolute_pose.cc"
#include "sequence_absolute_pose.cc"
#include "generalized_absolute_pose.cc"
#include "essential_matrix.cc"
#include "fundamental_matrix.cc"
#include "transformations.cc"
#include "sift.cc"
PYBIND11_MODULE(pycolmap, m) {
m.doc() = "COLMAP plugin built on " __TIMESTAMP__;
// Absolute pose.
m.def("absolute_pose_estimation", &absolute_pose_estimation,
py::arg("points2D"), py::arg("points3D"),
py::arg("camera_dict"),
py::arg("max_error_px") = 12.0,
"Absolute pose estimation with non-linear refinement.");
// Absolute pose from Sequence.
m.def("sequence_pose_estimation", &sequence_pose_estimation,
py::arg("points3D_0"),
py::arg("points3D_1"),
py::arg("map_points2D_0"),
py::arg("map_points2D_1"),
py::arg("rel1_points2D_0"),
py::arg("rel0_points2D_1"),
py::arg("camera_dict"),
py::arg("max_error_px") = 12.0,
py::arg("rel_max_error_px") = 12.0,
py::arg("rel_weight") = 1000.0,
"Absolute pose estimation with non-linear refinement.");
// Absolute pose from multiple images.
m.def("generalized_absolute_pose_estimation", &generalized_absolute_pose_estimation,
py::arg("points2D"), py::arg("points3D"),
py::arg("cam_idxs"),
py::arg("rel_camera_poses"),
py::arg("camera_dicts"),
py::arg("refinement_parameters"),
py::arg("max_error_px") = 12.0,
"Multi image absolute pose estimation.");
// Essential matrix.
m.def("essential_matrix_estimation", &essential_matrix_estimation,
py::arg("points2D1"), py::arg("points2D2"),
py::arg("camera_dict1"), py::arg("camera_dict2"),
py::arg("max_error_px") = 4.0,
py::arg("do_refinement") = false,
"LORANSAC + 5-point algorithm.");
// Fundamental matrix.
m.def("fundamental_matrix_estimation", &fundamental_matrix_estimation,
py::arg("points2D1"), py::arg("points2D2"),
py::arg("max_error_px") = 4.0,
"LORANSAC + 7-point algorithm.");
// Image-to-world and world-to-image.
m.def("image_to_world", &image_to_world, "Image to world transformation.");
m.def("world_to_image", &world_to_image, "World to image transformation.");
// SIFT.
m.def("extract_sift", &extract_sift,
py::arg("image"),
py::arg("num_octaves") = 4, py::arg("octave_resolution") = 3, py::arg("first_octave") = 0,
py::arg("edge_thresh") = 10.0, py::arg("peak_thresh") = 0.01, py::arg("upright") = false,
"Extract SIFT features.");
}
| 38.25 | 100 | 0.6122 | sebgiles |
d216c874fd8a85cbd55ac716fbc459fdaf3833cd | 978 | cpp | C++ | PAC-MAN_Allegro/imagem.cpp | JP-Clemente/Programming_Projects | 68ff8dccbf6bf70461cc4865840f6a187dadcb5e | [
"MIT"
] | 1 | 2020-11-29T08:06:21.000Z | 2020-11-29T08:06:21.000Z | PAC-MAN_Allegro/imagem.cpp | JP-Clemente/College_Projects | 94478657182e3dbf6ffd0fa425159d857f59a684 | [
"MIT"
] | null | null | null | PAC-MAN_Allegro/imagem.cpp | JP-Clemente/College_Projects | 94478657182e3dbf6ffd0fa425159d857f59a684 | [
"MIT"
] | null | null | null | #include <iostream>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
using namespace std;
int main(int argc, char **argv){
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_BITMAP *image = NULL;
if(!al_init()) {
cout <<"Failed to initialize allegro!" << endl;
return 0;
}
if(!al_init_image_addon()) {
cout <<"Failed to initialize al_init_image_addon!" << endl;
return 0;
}
display = al_create_display(500,550);
if(!display) {
cout <<"Failed to initialize display!" << endl;
return 0;
}
image = al_load_bitmap("map.bmp"); //Carrega imagem do arquivo map.bmp
if(!image) {
cout << "Failed to load image!" << endl;
al_destroy_display(display);
return 0;
}
al_draw_bitmap(image,0,0,0); //Desenha a imagem na posicao (0,0) - canto superior esquerdo
al_flip_display();
al_rest(10);
al_destroy_display(display);
al_destroy_bitmap(image);
return 0;
}
| 20.808511 | 96 | 0.632924 | JP-Clemente |
d217b52f2d76ab6ecb1d3195bb3d6643e39cb260 | 3,160 | hpp | C++ | include/util/geometric.hpp | Adanos020/ErupTrace | 2d359c4d53e758299e8b2d476d945fe2dd2f1c2d | [
"MIT"
] | null | null | null | include/util/geometric.hpp | Adanos020/ErupTrace | 2d359c4d53e758299e8b2d476d945fe2dd2f1c2d | [
"MIT"
] | null | null | null | include/util/geometric.hpp | Adanos020/ErupTrace | 2d359c4d53e758299e8b2d476d945fe2dd2f1c2d | [
"MIT"
] | null | null | null | #pragma once
#include <util/barycentric.hpp>
#include <util/colors.hpp>
#include <util/pairs.hpp>
#include <util/sizes.hpp>
#include <util/vector.hpp>
#include <glm/gtc/constants.hpp>
#include <glm/gtx/quaternion.hpp>
#include <algorithm>
#include <utility>
struct line
{
position_3D origin;
direction_3D direction;
position_3D point_at_distance(const float t) const
{
return origin + t * direction;
}
};
struct sphere
{
position_3D origin;
float radius;
};
inline static barycentric_2D mapping_on_sphere(const position_3D& in_normalized_p, const direction_3D& in_axial_tilt)
{
const direction_3D tilted = glm::clamp(in_normalized_p * glm::rotation(y_axis, in_axial_tilt),
direction_3D{ -1.f }, direction_3D{ 1.f });
return barycentric_2D{
1.f - ((glm::atan(tilted.z, tilted.x) + glm::pi<float>()) * glm::one_over_two_pi<float>()),
1.f - ((glm::asin(tilted.y) + glm::half_pi<float>()) * glm::one_over_pi<float>()),
};
}
struct plane
{
position_3D origin;
displacement_3D right;
displacement_3D up;
plane inverse() const
{
return plane{ this->origin, -this->right, -this->up };
}
};
struct triangle
{
position_3D a, b, c;
float area() const
{
const float ab = glm::distance(this->a, this->b);
const float ac = glm::distance(this->a, this->c);
const float theta = glm::acos(glm::dot(this->b - this->a, this->c - this->a) / (ab * ac));
return 0.5f * ab * ac * glm::sin(theta);
}
};
struct axis_aligned_box
{
position_3D min, max;
float width() const
{
return max.x - min.x;
}
float height() const
{
return max.y - min.y;
}
float depth() const
{
return max.z - min.z;
}
extent_3D<float> size() const
{
return { this->width(), this->height(), this->depth() };
}
position_3D origin() const
{
return this->min + displacement_3D{ this->width() * 0.5f, this->height() * 0.5f, this->depth() * 0.5f };
}
static axis_aligned_box zero()
{
return axis_aligned_box{ position_3D{ 0.f }, position_3D{ 0.f } };
}
static axis_aligned_box cuboid(const position_3D& in_origin, const extent_3D<float> in_half_size)
{
return axis_aligned_box{
in_origin - displacement_3D{ in_half_size.width, in_half_size.height, in_half_size.depth },
in_origin + displacement_3D{ in_half_size.width, in_half_size.height, in_half_size.depth }, };
}
static axis_aligned_box cuboid(const line& in_diagonal, const float in_length)
{
const position_3D a = in_diagonal.origin;
const position_3D b = in_diagonal.point_at_distance(in_length);
return axis_aligned_box{
position_3D{ std::min(a.x, b.x), std::min(a.y, b.y), std::min(a.z, b.z) },
position_3D{ std::max(a.x, b.x), std::max(a.y, b.y), std::max(a.z, b.z) }, };
}
static axis_aligned_box cube(const position_3D& in_origin, const float in_half_size)
{
return cuboid(in_origin, { in_half_size, in_half_size, in_half_size });
}
}; | 26.115702 | 117 | 0.625316 | Adanos020 |
d218f32735cbb059fd098fa344cae9d16cd6ddff | 2,311 | cpp | C++ | src/parser/parser.cpp | fezcode/boxer | 89139da2a93ae55d54bdf57a582d5eb7b1e157b0 | [
"Unlicense"
] | 1 | 2022-02-07T08:58:29.000Z | 2022-02-07T08:58:29.000Z | src/parser/parser.cpp | fezcode/boxer | 89139da2a93ae55d54bdf57a582d5eb7b1e157b0 | [
"Unlicense"
] | null | null | null | src/parser/parser.cpp | fezcode/boxer | 89139da2a93ae55d54bdf57a582d5eb7b1e157b0 | [
"Unlicense"
] | null | null | null | //============================
// Parser.cpp
//============================
//
#include "parser.h"
namespace boxer::parser {
/**
* Ctor
* Preconditions:
* - File exists.
*/
Parser::Parser(string_t path) : filename(path){
working_dir = boxer::string::getParentPath(path);
log_dbg("File:" + filename);
log_dbg("Working Directory:" + working_dir);
commandFactory = std::make_shared<boxer::commands::CommandFactory>();
}
// Start point of processing file.
bool_t Parser::processFile() {
if(!readFile()) {
log_war("Can NOT process file");
exit(1);
}
std::for_each(contentsOfFile.begin(), contentsOfFile.end(),
[&](const string_t& fileline) {
getCommandFromLine(fileline);
});
// start making sense of each line
return true;
}
// private functions
// -----------------
/**
* Reads file line by line and puts them into contentsOfFile string vector
*/
bool_t Parser::readFile() {
// Open the File
ifstream_t in{filename.c_str()};
// Check if object is valid
if(!in) {
log_err("Cannot open the File : " + filename);
return false;
}
string_t str;
// Read the next line from File until it reaches the end.
while (std::getline(in, str)) {
// Line contains string of length > 0 then save it in vector
if(str.size() > 0)
contentsOfFile.push_back(str);
}
//Close The File
in.close();
return true;
}
auto Parser::printContents() -> void {
for (auto const& c : contentsOfFile)
log_dbg(c);
}
auto Parser::getCommandFromLine(string_t line) -> void {
// Ignore line if it is a comment.
if (boxer::string::beginsWith(line, "#")) {
log_dbg("Ignore comment");
return;
}
stringvec_t words = boxer::string::split(line, " ");
if (words.size() <= 0) {
return;
}
log_dbg("Line: " + line);
// log_dbg("Words:");
// std::for_each(words.begin(),words.end(), [](const string_t &s){
// log_dbg(s);
// });
log_dbg("");
if (words.size() < 1) {
return;
}
auto command = commandFactory->createCommand(words, working_dir);
commands_list.push_back(command);
}
auto Parser::retrieveCommands() -> command_list_t {
return commands_list;
}
auto Parser::getWorkingDir() -> string_t {
return working_dir;
}
} // namespace boxer::parser
| 20.633929 | 75 | 0.607529 | fezcode |
d219264448484d31285b858d37eb887a667efaad | 5,731 | hpp | C++ | FDPS-5.0g/src/vector2.hpp | subarutaro/GPLUM | 89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f | [
"MIT"
] | null | null | null | FDPS-5.0g/src/vector2.hpp | subarutaro/GPLUM | 89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f | [
"MIT"
] | null | null | null | FDPS-5.0g/src/vector2.hpp | subarutaro/GPLUM | 89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f | [
"MIT"
] | null | null | null | #pragma once
#include<iostream>
#include<iomanip>
namespace ParticleSimulator{
template <typename T>
class Vector2{
public:
T x, y;
Vector2() : x(T(0)), y(T(0)) {}
Vector2(const T _x, const T _y) : x(_x), y(_y) {}
Vector2(const T s) : x(s), y(s) {}
Vector2(const Vector2 & src) : x(src.x), y(src.y) {}
static const int DIM = 2;
const Vector2 & operator = (const Vector2 & rhs){
x = rhs.x;
y = rhs.y;
return (*this);
}
const Vector2 & operator = (const T s){
x = y = s;
return (*this);
}
Vector2 operator + (const Vector2 & rhs) const{
return Vector2(x + rhs.x, y + rhs.y);
}
const Vector2 & operator += (const Vector2 & rhs){
(*this) = (*this) + rhs;
return (*this);
}
Vector2 operator - (const Vector2 & rhs) const{
return Vector2(x - rhs.x, y - rhs.y);
}
const Vector2 & operator -= (const Vector2 & rhs){
(*this) = (*this) - rhs;
return (*this);
}
// vector scholar products
Vector2 operator * (const T s) const{
return Vector2(x * s, y * s);
}
const Vector2 & operator *= (const T s){
(*this) = (*this) * s;
return (*this);
}
friend Vector2 operator * (const T s, const Vector2 & v){
return (v * s);
}
Vector2 operator / (const T s) const{
return Vector2(x / s, y / s);
}
const Vector2 & operator /= (const T s){
(*this) = (*this) / s;
return (*this);
}
const Vector2 & operator + () const {
return (* this);
}
const Vector2 operator - () const {
return Vector2(-x, -y);
}
// inner product
T operator * (const Vector2 & rhs) const{
return (x * rhs.x) + (y * rhs.y);
}
// outer product (retruned value is scholar)
T operator ^ (const Vector2 & rhs) const{
const T z = (x * rhs.y) - (y * rhs.x);
return z;
}
//cast to Vector2<U>
template <typename U>
operator Vector2<U> () const {
return Vector2<U> (static_cast<U>(x),
static_cast<U>(y));
}
T getMax() const {
return x > y ? x : y;
}
T getMin() const {
return x < y ? x : y;
}
template <class F>
Vector2 applyEach(F f) const {
return Vector2(f(x), f(y));
}
template <class F>
friend Vector2 ApplyEach(F f, const Vector2 & arg1, const Vector2 & arg2){
return Vector2( f(arg1.x, arg2.x), f(arg1.y, arg2.y) );
}
friend std::ostream & operator <<(std::ostream & c, const Vector2 & u){
c<<u.x<<" "<<u.y;
return c;
}
friend std::istream & operator >>(std::istream & c, Vector2 & u){
c>>u.x; c>>u.y;
return c;
}
#if 0
const T & operator[](const int i) const {
#ifdef PARTICLE_SIMULATOR_VECTOR_RANGE_CHECK
if(i >= DIM || i < 0){
std::cout<<"PS_ERROR: Vector invalid access. \n"<<"function: "<<__FUNCTION__<<", line: "<<__LINE__<<", file: "<<__FILE__<<std::endl;
std::cerr<<"Vector element="<<i<<" is not valid."<<std::endl;
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Abort(MPI_COMM_WORLD,-1);
#else
exit(-1);
#endif
}
#endif
return (&x)[i];
}
T & operator[](const int i){
#ifdef PARTICLE_SIMULATOR_VECTOR_RANGE_CHECK
if(i >= DIM || i < 0){
std::cout<<"PS_ERROR: Vector invalid access. \n"<<"function: "<<__FUNCTION__<<", line: "<<__LINE__<<", file: "<<__FILE__<<std::endl;
std::cerr<<"Vector element="<<i<<" is not valid."<<std::endl;
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Abort(MPI_COMM_WORLD,-1);
#else
exit(-1);
#endif
}
#endif
return (&x)[i];
}
#else
const T & operator[](const int i) const {
if(0==i) return x;
if(1==i) return y;
std::cout<<"PS_ERROR: Vector invalid access. \n"<<"function: "<<__FUNCTION__<<", line: "<<__LINE__<<", file: "<<__FILE__<<std::endl;
std::cerr<<"Vector element="<<i<<" is not valid."<<std::endl;
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Abort(MPI_COMM_WORLD,-1);
#endif
exit(-1);
return x; //dummy for avoid warning
}
T & operator[](const int i){
if(0==i) return x;
if(1==i) return y;
std::cout<<"PS_ERROR: Vector invalid access. \n"<<"function: "<<__FUNCTION__<<", line: "<<__LINE__<<", file: "<<__FILE__<<std::endl;
std::cerr<<"Vector element="<<i<<" is not valid."<<std::endl;
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Abort(MPI_COMM_WORLD,-1);
#endif
exit(-1);
return x; //dummy for avoid warning
}
#endif
T getDistanceSQ(const Vector2 & u) const {
T dx = x - u.x;
T dy = y - u.y;
return dx*dx + dy*dy;
}
bool operator == (const Vector2 & u) const {
return ( (x==u.x) && (y==u.y) );
}
bool operator != (const Vector2 & u) const {
return ( (x!=u.x) || (y!=u.y) );
}
};
template <>
inline Vector2<float> Vector2<float>::operator / (const float s) const {
const float inv_s = 1.0f/s;
return Vector2(x * inv_s, y * inv_s);
}
template <>
inline Vector2<double> Vector2<double>::operator / (const double s) const {
const double inv_s = 1.0/s;
return Vector2(x * inv_s, y * inv_s);
}
}
| 29.091371 | 137 | 0.503403 | subarutaro |
d21b4f55d714064edb9c4a1e2569597585a83ca2 | 4,552 | cpp | C++ | table/byte_addressable_RA_iterator.cpp | ruihong123/dLSM | 9158b25349389e0d46a0695ee05534409489412b | [
"BSD-3-Clause"
] | 2 | 2022-03-02T02:44:51.000Z | 2022-03-21T17:29:28.000Z | table/byte_addressable_RA_iterator.cpp | ruihong123/dLSM | 9158b25349389e0d46a0695ee05534409489412b | [
"BSD-3-Clause"
] | null | null | null | table/byte_addressable_RA_iterator.cpp | ruihong123/dLSM | 9158b25349389e0d46a0695ee05534409489412b | [
"BSD-3-Clause"
] | null | null | null | //
// Created by ruihong on 1/20/22.
//
#include "byte_addressable_RA_iterator.h"
#include "dLSM/env.h"
#include "table_memoryside.h"
namespace dLSM {
ByteAddressableRAIterator::ByteAddressableRAIterator(Iterator* index_iter,
KVFunction block_function,
void* arg,
const ReadOptions& options,
bool compute_side)
: compute_side_(compute_side),
mr_addr(nullptr),
kv_function_(block_function),
arg_(arg),
options_(options),
status_(Status::OK()),
index_iter_(index_iter),
valid_(false) {
#ifndef NDEBUG
if (compute_side){
assert(block_function == &Table::KVReader);
} else{
assert(block_function == &Table_Memory_Side::KVReader);
}
#endif
}
ByteAddressableRAIterator::~ByteAddressableRAIterator() {
if (mr_addr != nullptr){
auto rdma_mg = Env::Default()->rdma_mg;
rdma_mg->Deallocate_Local_RDMA_Slot(mr_addr, DataChunk);
}
// DEBUG_arg("TWOLevelIterator destructing, this pointer is %p\n", this);
};
//Note: if the iterator can not seek the same target, it will stop at the key right before or
// right after the data, we need to make it right before
void ByteAddressableRAIterator::Seek(const Slice& target) {
index_iter_.Seek(target);
GetKV();
assert(valid_);
// if ()
// //Todo: delete the things below.
// for (int i = 0; i < target.size(); ++i) {
// assert(key_.GetKey().data()[i] == target.data()[i]);
// }
}
void ByteAddressableRAIterator::SeekToFirst() {
index_iter_.SeekToFirst();
GetKV();
// if (data_iter_.iter() != nullptr) {
// data_iter_.SeekToFirst();
// valid_ = true;
// } else{
// assert(false);
// }
// SkipEmptyDataBlocksForward();
// assert(key().size() >0);
}
void ByteAddressableRAIterator::SeekToLast() {
index_iter_.SeekToLast();
GetKV();
// if (data_iter_.iter() != nullptr){
// data_iter_.SeekToLast();
// valid_ = true;
// }
// SkipEmptyDataBlocksBackward();
}
void ByteAddressableRAIterator::Next() {
index_iter_.Next();
GetKV();
}
void ByteAddressableRAIterator::Prev() {
assert(Valid());
index_iter_.Prev();
GetKV();
}
void ByteAddressableRAIterator::GetKV() {
if (!index_iter_.Valid()) {
// SetDataIterator(nullptr);
valid_ = false;
DEBUG_arg("TwoLevelIterator Index block invalid, error: %s\n", status().ToString().c_str());
} else {
valid_ = true;
// DEBUG("Index block valid\n");
Slice handle = index_iter_.value();
#ifndef NDEBUG
Slice test_handle = handle;
index_handle.DecodeFrom(&test_handle);
// printf("Iterator pointer is %p, Offset is %lu, this data block size is %lu\n", this, bhandle.offset(), bhandle.size());
#endif
if (handle.compare(data_block_handle_) == 0) {
// data_iter_ is already constructed with this iterator, so
// no need to change anything
} else {
if (compute_side_){
//TODO: just reuse the RDMA registered buffer every time, no need to
// allocate and deallocate again. we abandon the function pointer design,
// directly call the static function instead.
if (mr_addr != nullptr){
auto rdma_mg = Env::Default()->rdma_mg;
rdma_mg->Deallocate_Local_RDMA_Slot(mr_addr, DataChunk);
}
Slice KV = (*kv_function_)(arg_, options_, handle);
mr_addr = const_cast<char*>(KV.data());
uint32_t key_size, value_size;
GetFixed32(&KV, &key_size);
GetFixed32(&KV, &value_size);
assert(key_size + value_size == KV.size());
key_.SetKey(Slice(KV.data(), key_size), false /* copy */);
KV.remove_prefix(key_size);
assert(KV.size() == value_size);
value_ = KV;
data_block_handle_.assign(handle.data(), handle.size());
}else{
Slice KV = (*kv_function_)(arg_, options_, handle);
uint32_t key_size, value_size;
GetFixed32(&KV, &key_size);
GetFixed32(&KV, &value_size);
assert(key_size + value_size == KV.size());
// printf("!key is %p, KV.data is %p, the 7 bit is %s \n",
// key_.GetKey().data(), KV.data(), KV.data()+7);
key_.SetKey(Slice(KV.data(), key_size), false /* copy */);
KV.remove_prefix(key_size);
assert(KV.size() == value_size);
value_ = KV;
data_block_handle_.assign(handle.data(), handle.size());
}
}
}
}
} | 30.346667 | 125 | 0.609622 | ruihong123 |
d21ca9721fc9885affa723609c674c99af0be541 | 9,155 | cpp | C++ | src/spells/moppcode.cpp | eckserah/nifskope | 3a85ac55e65cc60abc3434cc4aaca2a5cc712eef | [
"RSA-MD"
] | 434 | 2015-02-06T05:08:20.000Z | 2022-03-28T16:32:15.000Z | src/spells/moppcode.cpp | SpectralPlatypus/nifskope | 7af7af39bfb0b29953024655235fde9fbc97071c | [
"RSA-MD"
] | 155 | 2015-01-10T15:28:01.000Z | 2022-03-05T03:28:09.000Z | src/spells/moppcode.cpp | SpectralPlatypus/nifskope | 7af7af39bfb0b29953024655235fde9fbc97071c | [
"RSA-MD"
] | 205 | 2015-02-07T15:10:16.000Z | 2022-03-12T16:59:05.000Z | #include "spellbook.h"
// Brief description is deliberately not autolinked to class Spell
/*! \file moppcode.cpp
* \brief Havok MOPP spells
*
* Note that this code only works on the Windows platform due an external
* dependency on the Havok SDK, with which NifMopp.dll is compiled.
*
* Most classes here inherit from the Spell class.
*/
// Need to include headers before testing this
#ifdef Q_OS_WIN32
// This code is only intended to be run with Win32 platform.
extern "C" void * __stdcall SetDllDirectoryA( const char * lpPathName );
extern "C" void * __stdcall LoadLibraryA( const char * lpModuleName );
extern "C" void * __stdcall GetProcAddress ( void * hModule, const char * lpProcName );
extern "C" void __stdcall FreeLibrary( void * lpModule );
//! Interface to the external MOPP library
class HavokMoppCode
{
private:
typedef int (__stdcall * fnGenerateMoppCode)( int nVerts, Vector3 const * verts, int nTris, Triangle const * tris );
typedef int (__stdcall * fnGenerateMoppCodeWithSubshapes)( int nShapes, int const * shapes, int nVerts, Vector3 const * verts, int nTris, Triangle const * tris );
typedef int (__stdcall * fnRetrieveMoppCode)( int nBuffer, char * buffer );
typedef int (__stdcall * fnRetrieveMoppScale)( float * value );
typedef int (__stdcall * fnRetrieveMoppOrigin)( Vector3 * value );
void * hMoppLib;
fnGenerateMoppCode GenerateMoppCode;
fnRetrieveMoppCode RetrieveMoppCode;
fnRetrieveMoppScale RetrieveMoppScale;
fnRetrieveMoppOrigin RetrieveMoppOrigin;
fnGenerateMoppCodeWithSubshapes GenerateMoppCodeWithSubshapes;
public:
HavokMoppCode() : hMoppLib( 0 ), GenerateMoppCode( 0 ), RetrieveMoppCode( 0 ), RetrieveMoppScale( 0 ),
RetrieveMoppOrigin( 0 ), GenerateMoppCodeWithSubshapes( 0 )
{
}
~HavokMoppCode()
{
if ( hMoppLib )
FreeLibrary( hMoppLib );
}
bool Initialize()
{
if ( !hMoppLib ) {
SetDllDirectoryA( QCoreApplication::applicationDirPath().toLocal8Bit().constData() );
hMoppLib = LoadLibraryA( "NifMopp.dll" );
GenerateMoppCode = (fnGenerateMoppCode)GetProcAddress( hMoppLib, "GenerateMoppCode" );
RetrieveMoppCode = (fnRetrieveMoppCode)GetProcAddress( hMoppLib, "RetrieveMoppCode" );
RetrieveMoppScale = (fnRetrieveMoppScale)GetProcAddress( hMoppLib, "RetrieveMoppScale" );
RetrieveMoppOrigin = (fnRetrieveMoppOrigin)GetProcAddress( hMoppLib, "RetrieveMoppOrigin" );
GenerateMoppCodeWithSubshapes = (fnGenerateMoppCodeWithSubshapes)GetProcAddress( hMoppLib, "GenerateMoppCodeWithSubshapes" );
}
return (GenerateMoppCode && RetrieveMoppCode && RetrieveMoppScale && RetrieveMoppOrigin);
}
QByteArray CalculateMoppCode( QVector<Vector3> const & verts, QVector<Triangle> const & tris, Vector3 * origin, float * scale )
{
QByteArray code;
if ( Initialize() ) {
int len = GenerateMoppCode( verts.size(), &verts[0], tris.size(), &tris[0] );
if ( len > 0 ) {
code.resize( len );
if ( 0 != RetrieveMoppCode( len, code.data() ) ) {
if ( scale )
RetrieveMoppScale( scale );
if ( origin )
RetrieveMoppOrigin( origin );
} else {
code.clear();
}
}
}
return code;
}
QByteArray CalculateMoppCode( QVector<int> const & subShapesVerts,
QVector<Vector3> const & verts,
QVector<Triangle> const & tris,
Vector3 * origin, float * scale )
{
QByteArray code;
if ( Initialize() ) {
int len;
if ( GenerateMoppCodeWithSubshapes )
len = GenerateMoppCodeWithSubshapes( subShapesVerts.size(), &subShapesVerts[0], verts.size(), &verts[0], tris.size(), &tris[0] );
else
len = GenerateMoppCode( verts.size(), &verts[0], tris.size(), &tris[0] );
if ( len > 0 ) {
code.resize( len );
if ( 0 != RetrieveMoppCode( len, code.data() ) ) {
if ( scale )
RetrieveMoppScale( scale );
if ( origin )
RetrieveMoppOrigin( origin );
} else {
code.clear();
}
}
}
return code;
}
}
TheHavokCode;
//! Update Havok MOPP for a given shape
class spMoppCode final : public Spell
{
public:
QString name() const override final { return Spell::tr( "Update MOPP Code" ); }
QString page() const override final { return Spell::tr( "Havok" ); }
bool isApplicable( const NifModel * nif, const QModelIndex & index ) override final
{
if ( nif->getUserVersion() != 10 && nif->getUserVersion() != 11 )
return false;
if ( TheHavokCode.Initialize() ) {
//QModelIndex iData = nif->getBlock( nif->getLink( index, "Data" ) );
if ( nif->isNiBlock( index, "bhkMoppBvTreeShape" ) ) {
return ( nif->checkVersion( 0x14000004, 0x14000005 )
|| nif->checkVersion( 0x14020007, 0x14020007 ) );
}
}
return false;
}
QModelIndex cast( NifModel * nif, const QModelIndex & iBlock ) override final
{
if ( !TheHavokCode.Initialize() ) {
Message::critical( nullptr, Spell::tr( "Unable to locate NifMopp.dll" ) );
return iBlock;
}
QPersistentModelIndex ibhkMoppBvTreeShape = iBlock;
QModelIndex ibhkPackedNiTriStripsShape = nif->getBlock( nif->getLink( ibhkMoppBvTreeShape, "Shape" ) );
if ( !nif->isNiBlock( ibhkPackedNiTriStripsShape, "bhkPackedNiTriStripsShape" ) ) {
Message::warning( nullptr, Spell::tr( "Only bhkPackedNiTriStripsShape is supported at this time." ) );
return iBlock;
}
QModelIndex ihkPackedNiTriStripsData = nif->getBlock( nif->getLink( ibhkPackedNiTriStripsShape, "Data" ) );
if ( !nif->isNiBlock( ihkPackedNiTriStripsData, "hkPackedNiTriStripsData" ) )
return iBlock;
QVector<int> subshapeVerts;
if ( nif->checkVersion( 0x14000004, 0x14000005 ) ) {
int nSubShapes = nif->get<int>( ibhkPackedNiTriStripsShape, "Num Sub Shapes" );
QModelIndex ihkSubShapes = nif->getIndex( ibhkPackedNiTriStripsShape, "Sub Shapes" );
subshapeVerts.resize( nSubShapes );
for ( int t = 0; t < nSubShapes; t++ ) {
subshapeVerts[t] = nif->get<int>( ihkSubShapes.child( t, 0 ), "Num Vertices" );
}
} else if ( nif->checkVersion( 0x14020007, 0x14020007 ) ) {
int nSubShapes = nif->get<int>( ihkPackedNiTriStripsData, "Num Sub Shapes" );
QModelIndex ihkSubShapes = nif->getIndex( ihkPackedNiTriStripsData, "Sub Shapes" );
subshapeVerts.resize( nSubShapes );
for ( int t = 0; t < nSubShapes; t++ ) {
subshapeVerts[t] = nif->get<int>( ihkSubShapes.child( t, 0 ), "Num Vertices" );
}
}
QVector<Vector3> verts = nif->getArray<Vector3>( ihkPackedNiTriStripsData, "Vertices" );
QVector<Triangle> triangles;
int nTriangles = nif->get<int>( ihkPackedNiTriStripsData, "Num Triangles" );
QModelIndex iTriangles = nif->getIndex( ihkPackedNiTriStripsData, "Triangles" );
triangles.resize( nTriangles );
for ( int t = 0; t < nTriangles; t++ ) {
triangles[t] = nif->get<Triangle>( iTriangles.child( t, 0 ), "Triangle" );
}
if ( verts.isEmpty() || triangles.isEmpty() ) {
Message::critical( nullptr, Spell::tr( "Insufficient data to calculate MOPP code" ),
Spell::tr("Vertices: %1, Triangles: %2").arg( !verts.isEmpty() ).arg( !triangles.isEmpty() )
);
return iBlock;
}
Vector3 origin;
float scale;
QByteArray moppcode = TheHavokCode.CalculateMoppCode( subshapeVerts, verts, triangles, &origin, &scale );
if ( moppcode.size() == 0 ) {
Message::critical( nullptr, Spell::tr( "Failed to generate MOPP code" ) );
} else {
QModelIndex iCodeOrigin = nif->getIndex( ibhkMoppBvTreeShape, "Origin" );
nif->set<Vector3>( iCodeOrigin, origin );
QModelIndex iCodeScale = nif->getIndex( ibhkMoppBvTreeShape, "Scale" );
nif->set<float>( iCodeScale, scale );
QModelIndex iCodeSize = nif->getIndex( ibhkMoppBvTreeShape, "MOPP Data Size" );
QModelIndex iCode = nif->getIndex( ibhkMoppBvTreeShape, "MOPP Data" ).child( 0, 0 );
if ( iCodeSize.isValid() && iCode.isValid() ) {
nif->set<int>( iCodeSize, moppcode.size() );
nif->updateArray( iCode );
nif->set<QByteArray>( iCode, moppcode );
}
}
return iBlock;
}
};
REGISTER_SPELL( spMoppCode )
//! Update MOPP code on all shapes in this model
class spAllMoppCodes final : public Spell
{
public:
QString name() const override final { return Spell::tr( "Update All MOPP Code" ); }
QString page() const override final { return Spell::tr( "Batch" ); }
bool isApplicable( const NifModel * nif, const QModelIndex & idx ) override final
{
if ( nif && nif->getUserVersion() != 10 && nif->getUserVersion() != 11 )
return false;
if ( TheHavokCode.Initialize() ) {
if ( nif && !idx.isValid() ) {
return ( nif->checkVersion( 0x14000004, 0x14000005 )
|| nif->checkVersion( 0x14020007, 0x14020007 ) );
}
}
return false;
}
QModelIndex cast( NifModel * nif, const QModelIndex & ) override final
{
QList<QPersistentModelIndex> indices;
spMoppCode TSpacer;
for ( int n = 0; n < nif->getBlockCount(); n++ ) {
QModelIndex idx = nif->getBlock( n );
if ( TSpacer.isApplicable( nif, idx ) )
indices << idx;
}
for ( const QModelIndex& idx : indices ) {
TSpacer.castIfApplicable( nif, idx );
}
return QModelIndex();
}
};
REGISTER_SPELL( spAllMoppCodes )
#endif // Q_OS_WIN32
| 31.898955 | 163 | 0.681049 | eckserah |
d21e101eeed85d188956e68a8fdf716c924f7cff | 8,259 | cc | C++ | src/game/LoadSaveTacticalStatusType.cc | flex-lab/ja2-stracciatella | 61f8f0445112c5d5ec80d7b3502ac24505f3d20c | [
"BSD-Source-Code"
] | null | null | null | src/game/LoadSaveTacticalStatusType.cc | flex-lab/ja2-stracciatella | 61f8f0445112c5d5ec80d7b3502ac24505f3d20c | [
"BSD-Source-Code"
] | null | null | null | src/game/LoadSaveTacticalStatusType.cc | flex-lab/ja2-stracciatella | 61f8f0445112c5d5ec80d7b3502ac24505f3d20c | [
"BSD-Source-Code"
] | null | null | null | #include <vector>
#include "Debug.h"
#include "FileMan.h"
#include "GameState.h"
#include "LoadSaveData.h"
#include "LoadSaveTacticalStatusType.h"
#include "Overhead.h"
void ExtractTacticalStatusTypeFromFile(HWFILE const f, bool stracLinuxFormat)
{
UINT32 dataSize = stracLinuxFormat ? TACTICAL_STATUS_TYPE_SIZE_STRAC_LINUX : TACTICAL_STATUS_TYPE_SIZE;
std::vector<BYTE> data(dataSize);
FileRead(f, data.data(), dataSize);
TacticalStatusType* const s = &gTacticalStatus;
DataReader d{data.data()};
EXTR_U32(d, s->uiFlags)
FOR_EACH(TacticalTeamType, t, s->Team)
{
EXTR_U8(d, t->bFirstID)
EXTR_U8(d, t->bLastID)
EXTR_SKIP(d, 2)
EXTR_U32(d, t->RadarColor)
EXTR_I8(d, t->bSide)
EXTR_I8(d, t->bMenInSector)
EXTR_SOLDIER(d, t->last_merc_to_radio)
EXTR_SKIP(d, 1)
EXTR_I8(d, t->bAwareOfOpposition)
EXTR_I8(d, t->bHuman)
EXTR_SKIP(d, 2)
}
EXTR_U8(d, s->ubCurrentTeam)
EXTR_SKIP(d, 1)
EXTR_I16(d, s->sSlideTarget)
EXTR_SKIP(d, 4)
EXTR_U32(d, s->uiTimeSinceMercAIStart)
EXTR_I8(d, s->fPanicFlags)
EXTR_SKIP(d, 5)
EXTR_U8(d, s->ubSpottersCalledForBy)
EXTR_SOLDIER(d, s->the_chosen_one)
EXTR_U32(d, s->uiTimeOfLastInput)
EXTR_U32(d, s->uiTimeSinceDemoOn)
EXTR_SKIP(d, 7)
EXTR_BOOLA(d, s->fCivGroupHostile, lengthof(s->fCivGroupHostile))
EXTR_U8(d, s->ubLastBattleSectorX)
EXTR_U8(d, s->ubLastBattleSectorY)
EXTR_BOOL(d, s->fLastBattleWon)
EXTR_SKIP(d, 2)
EXTR_BOOL(d, s->fVirginSector)
EXTR_BOOL(d, s->fEnemyInSector)
EXTR_BOOL(d, s->fInterruptOccurred)
EXTR_I8(d, s->bRealtimeSpeed)
EXTR_SKIP(d, 2)
EXTR_SOLDIER(d, s->enemy_sighting_on_their_turn_enemy)
EXTR_SKIP(d, 1)
EXTR_BOOL(d, s->fEnemySightingOnTheirTurn)
EXTR_BOOL(d, s->fAutoBandageMode)
EXTR_U8(d, s->ubAttackBusyCount)
EXTR_SKIP(d, 1)
EXTR_U8(d, s->ubEngagedInConvFromActionMercID)
EXTR_SKIP(d, 1)
EXTR_U16(d, s->usTactialTurnLimitCounter)
EXTR_BOOL(d, s->fInTopMessage)
EXTR_U8(d, s->ubTopMessageType)
if(stracLinuxFormat)
{
EXTR_SKIP(d, 82);
}
else
{
EXTR_SKIP(d, 40);
}
EXTR_U16(d, s->usTactialTurnLimitMax)
if(stracLinuxFormat)
{
EXTR_SKIP(d, 2);
}
EXTR_U32(d, s->uiTactialTurnLimitClock)
EXTR_BOOL(d, s->fTactialTurnLimitStartedBeep)
EXTR_I8(d, s->bBoxingState)
EXTR_I8(d, s->bConsNumTurnsNotSeen)
EXTR_U8(d, s->ubArmyGuysKilled)
EXTR_I16A(d, s->sPanicTriggerGridNo, lengthof(s->sPanicTriggerGridNo))
EXTR_I8A(d, s->bPanicTriggerIsAlarm, lengthof(s->bPanicTriggerIsAlarm))
EXTR_U8A(d, s->ubPanicTolerance, lengthof(s->ubPanicTolerance))
EXTR_BOOL(d, s->fAtLeastOneGuyOnMultiSelect)
EXTR_SKIP(d, 2)
EXTR_BOOL(d, s->fKilledEnemyOnAttack)
EXTR_SOLDIER(d, s->enemy_killed_on_attack)
EXTR_I8(d, s->bEnemyKilledOnAttackLevel)
EXTR_U16(d, s->ubEnemyKilledOnAttackLocation)
EXTR_BOOL(d, s->fItemsSeenOnAttack)
EXTR_SOLDIER(d, s->items_seen_on_attack_soldier)
EXTR_SKIP(d, 2)
EXTR_U16(d, s->usItemsSeenOnAttackGridNo)
EXTR_BOOL(d, s->fLockItemLocators)
EXTR_U8(d, s->ubLastQuoteSaid)
EXTR_U8(d, s->ubLastQuoteProfileNUm)
EXTR_BOOL(d, s->fCantGetThrough)
EXTR_I16(d, s->sCantGetThroughGridNo)
EXTR_I16(d, s->sCantGetThroughSoldierGridNo)
EXTR_SOLDIER(d, s->cant_get_through)
EXTR_BOOL(d, s->fDidGameJustStart)
EXTR_SKIP(d, 1)
EXTR_U8(d, s->ubLastRequesterTargetID)
EXTR_SKIP(d, 1)
EXTR_U8(d, s->ubNumCrowsPossible)
EXTR_SKIP(d, 4)
EXTR_BOOL(d, s->fUnLockUIAfterHiddenInterrupt)
EXTR_I8A(d, s->bNumFoughtInBattle, lengthof(s->bNumFoughtInBattle))
EXTR_SKIP(d, 1)
EXTR_U32(d, s->uiDecayBloodLastUpdate)
EXTR_U32(d, s->uiTimeSinceLastInTactical)
EXTR_BOOL(d, s->fHasAGameBeenStarted)
EXTR_I8(d, s->bConsNumTurnsWeHaventSeenButEnemyDoes)
EXTR_BOOL(d, s->fSomeoneHit)
EXTR_SKIP(d, 1)
EXTR_U32(d, s->uiTimeSinceLastOpplistDecay)
EXTR_I8(d, s->bMercArrivingQuoteBeingUsed)
EXTR_SOLDIER(d, s->enemy_killed_on_attack_killer)
EXTR_BOOL(d, s->fCountingDownForGuideDescription)
EXTR_I8(d, s->bGuideDescriptionCountDown)
EXTR_U8(d, s->ubGuideDescriptionToUse)
EXTR_I8(d, s->bGuideDescriptionSectorX)
EXTR_I8(d, s->bGuideDescriptionSectorY)
EXTR_I8(d, s->fEnemyFlags)
EXTR_BOOL(d, s->fAutoBandagePending)
EXTR_BOOL(d, s->fHasEnteredCombatModeSinceEntering)
EXTR_BOOL(d, s->fDontAddNewCrows)
EXTR_SKIP(d, 1)
EXTR_U16(d, s->sCreatureTenseQuoteDelay)
EXTR_SKIP(d, 2)
EXTR_U32(d, s->uiCreatureTenseQuoteLastUpdate)
Assert(d.getConsumed() == dataSize);
if (!GameState::getInstance()->debugging())
{
// Prevent restoring of debug UI modes
s->uiFlags &= ~(DEBUGCLIFFS | SHOW_Z_BUFFER);
}
}
void InjectTacticalStatusTypeIntoFile(HWFILE const f)
{
BYTE data[316];
DataWriter d{data};
TacticalStatusType* const s = &gTacticalStatus;
INJ_U32(d, s->uiFlags)
FOR_EACH(TacticalTeamType const, t, s->Team)
{
INJ_U8(d, t->bFirstID)
INJ_U8(d, t->bLastID)
INJ_SKIP(d, 2)
INJ_U32(d, t->RadarColor)
INJ_I8(d, t->bSide)
INJ_I8(d, t->bMenInSector)
INJ_SOLDIER(d, t->last_merc_to_radio)
INJ_SKIP(d, 1)
INJ_I8(d, t->bAwareOfOpposition)
INJ_I8(d, t->bHuman)
INJ_SKIP(d, 2)
}
INJ_U8(d, s->ubCurrentTeam)
INJ_SKIP(d, 1)
INJ_I16(d, s->sSlideTarget)
INJ_SKIP(d, 4)
INJ_U32(d, s->uiTimeSinceMercAIStart)
INJ_I8(d, s->fPanicFlags)
INJ_SKIP(d, 5)
INJ_U8(d, s->ubSpottersCalledForBy)
INJ_SOLDIER(d, s->the_chosen_one)
INJ_U32(d, s->uiTimeOfLastInput)
INJ_U32(d, s->uiTimeSinceDemoOn)
INJ_SKIP(d, 7)
INJ_BOOLA(d, s->fCivGroupHostile, lengthof(s->fCivGroupHostile))
INJ_U8(d, s->ubLastBattleSectorX)
INJ_U8(d, s->ubLastBattleSectorY)
INJ_BOOL(d, s->fLastBattleWon)
INJ_SKIP(d, 2)
INJ_BOOL(d, s->fVirginSector)
INJ_BOOL(d, s->fEnemyInSector)
INJ_BOOL(d, s->fInterruptOccurred)
INJ_I8(d, s->bRealtimeSpeed)
INJ_SKIP(d, 2)
INJ_SOLDIER(d, s->enemy_sighting_on_their_turn_enemy)
INJ_SKIP(d, 1)
INJ_BOOL(d, s->fEnemySightingOnTheirTurn)
INJ_BOOL(d, s->fAutoBandageMode)
INJ_U8(d, s->ubAttackBusyCount)
INJ_SKIP(d, 1)
INJ_U8(d, s->ubEngagedInConvFromActionMercID)
INJ_SKIP(d, 1)
INJ_U16(d, s->usTactialTurnLimitCounter)
INJ_BOOL(d, s->fInTopMessage)
INJ_U8(d, s->ubTopMessageType)
INJ_SKIP(d, 40)
INJ_U16(d, s->usTactialTurnLimitMax)
INJ_U32(d, s->uiTactialTurnLimitClock)
INJ_BOOL(d, s->fTactialTurnLimitStartedBeep)
INJ_I8(d, s->bBoxingState)
INJ_I8(d, s->bConsNumTurnsNotSeen)
INJ_U8(d, s->ubArmyGuysKilled)
INJ_I16A(d, s->sPanicTriggerGridNo, lengthof(s->sPanicTriggerGridNo))
INJ_I8A(d, s->bPanicTriggerIsAlarm, lengthof(s->bPanicTriggerIsAlarm))
INJ_U8A(d, s->ubPanicTolerance, lengthof(s->ubPanicTolerance))
INJ_BOOL(d, s->fAtLeastOneGuyOnMultiSelect)
INJ_SKIP(d, 2)
INJ_BOOL(d, s->fKilledEnemyOnAttack)
INJ_SOLDIER(d, s->enemy_killed_on_attack)
INJ_I8(d, s->bEnemyKilledOnAttackLevel)
INJ_U16(d, s->ubEnemyKilledOnAttackLocation)
INJ_BOOL(d, s->fItemsSeenOnAttack)
INJ_SOLDIER(d, s->items_seen_on_attack_soldier)
INJ_SKIP(d, 2)
INJ_U16(d, s->usItemsSeenOnAttackGridNo)
INJ_BOOL(d, s->fLockItemLocators)
INJ_U8(d, s->ubLastQuoteSaid)
INJ_U8(d, s->ubLastQuoteProfileNUm)
INJ_BOOL(d, s->fCantGetThrough)
INJ_I16(d, s->sCantGetThroughGridNo)
INJ_I16(d, s->sCantGetThroughSoldierGridNo)
INJ_SOLDIER(d, s->cant_get_through)
INJ_BOOL(d, s->fDidGameJustStart)
INJ_SKIP(d, 1)
INJ_U8(d, s->ubLastRequesterTargetID)
INJ_SKIP(d, 1)
INJ_U8(d, s->ubNumCrowsPossible)
INJ_SKIP(d, 4)
INJ_BOOL(d, s->fUnLockUIAfterHiddenInterrupt)
INJ_I8A(d, s->bNumFoughtInBattle, lengthof(s->bNumFoughtInBattle))
INJ_SKIP(d, 1)
INJ_U32(d, s->uiDecayBloodLastUpdate)
INJ_U32(d, s->uiTimeSinceLastInTactical)
INJ_BOOL(d, s->fHasAGameBeenStarted)
INJ_I8(d, s->bConsNumTurnsWeHaventSeenButEnemyDoes)
INJ_BOOL(d, s->fSomeoneHit)
INJ_SKIP(d, 1)
INJ_U32(d, s->uiTimeSinceLastOpplistDecay)
INJ_I8(d, s->bMercArrivingQuoteBeingUsed)
INJ_SOLDIER(d, s->enemy_killed_on_attack_killer)
INJ_BOOL(d, s->fCountingDownForGuideDescription)
INJ_I8(d, s->bGuideDescriptionCountDown)
INJ_U8(d, s->ubGuideDescriptionToUse)
INJ_I8(d, s->bGuideDescriptionSectorX)
INJ_I8(d, s->bGuideDescriptionSectorY)
INJ_I8(d, s->fEnemyFlags)
INJ_BOOL(d, s->fAutoBandagePending)
INJ_BOOL(d, s->fHasEnteredCombatModeSinceEntering)
INJ_BOOL(d, s->fDontAddNewCrows)
INJ_SKIP(d, 1)
INJ_U16(d, s->sCreatureTenseQuoteDelay)
INJ_SKIP(d, 2)
INJ_U32(d, s->uiCreatureTenseQuoteLastUpdate)
Assert(d.getConsumed() == lengthof(data));
FileWrite(f, data, sizeof(data));
}
| 31.643678 | 104 | 0.763531 | flex-lab |
d21e989a93c7bbe63be3d91a88abb98530110963 | 17,295 | cpp | C++ | src/vd_mesh.cpp | 22427/Vertex_Data | 8df9da253dadf21d1c89917f44103e6ed3ab52fa | [
"Unlicense"
] | null | null | null | src/vd_mesh.cpp | 22427/Vertex_Data | 8df9da253dadf21d1c89917f44103e6ed3ab52fa | [
"Unlicense"
] | null | null | null | src/vd_mesh.cpp | 22427/Vertex_Data | 8df9da253dadf21d1c89917f44103e6ed3ab52fa | [
"Unlicense"
] | null | null | null | #include "../include/vd_mesh.h"
#include <glm/geometric.hpp>
#include <string>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <algorithm>
using namespace glm;
///*****************************************************************************
///* UTILITIES *
///*****************************************************************************
namespace std
{
template<>
struct less<vec4>
{
inline bool eq(const float& a,const float& b) const
{
return std::nextafter(a, std::numeric_limits<float>::lowest()) <= b
&& std::nextafter(a, std::numeric_limits<float>::max()) >= b;
}
size_t operator()(const vec4 &a,const vec4 &b) const
{
for(int i = 0 ; i < 4; i++)
{
if(eq(a[i],b[i])) continue;
return a[i]<b[i];
}
return false;
}
};
}
namespace vd {
static inline void ltrim(std::string &s)
{
s.erase(s.begin(),std::find_if(s.begin(), s.end(),
std::not1(
std::ptr_fun<int,int>(std::isspace))));
}
static inline void rtrim(std::string &s)
{
s.erase(std::find_if(s.rbegin(), s.rend(),
std::not1(std::ptr_fun<int,int>(std::isspace))).base(),
s.end());
}
static inline void trim(std::string &s){ltrim(s);rtrim(s);}
std::string read_word(std::stringstream& ss)
{
std::string itm;
do
{
std::getline(ss,itm,' ');
trim(itm);
}while(itm.empty() && ss);
return itm;
}
///*****************************************************************************
///* INPUT *
///*****************************************************************************
bool MeshOPS::read(Mesh& m, const std::string& path)
{
std::string ext = path.substr(path.find_last_of('.')+1);
for(char &c : ext) c= toupper(c);
std::ifstream f(path);
if(!f.is_open())
{
m_errcde = CANNOT_OPEN_FILE;
m_errmsg = "Cannot open file '"+path+"'";
return false;
}
else if(ext == "OFF")
return MeshOPS::read_OFF(m,f);
else if(ext == "PLY")
return MeshOPS::read_PLY(m,f);
else if(ext=="OBJ" || ext == "OBJP" || ext == "OBJ+")
return MeshOPS::read_OBJP(m,f);
return false;
}
// OFF-Loader
//------------------------------------------------------------------------------
bool MeshOPS::read_OFF(Mesh &m, std::ifstream &f)
{
std::string line;
vec4 v(0,0,0,1);
Triangle t;
m.active_mask = AM_POSITION;
std::getline(f,line);
trim(line);
if(line != "OFF")
{
m_errcde = PARSING_FILE;
m_errmsg = "OFF files should start with 'OFF'";
return false;
}
std::getline(f,line);
int n_vert = 0;
int n_face = 0;
int n_edge = 0;
std::stringstream ls(line);
ls>>n_vert>>n_face>>n_edge;
m.get_pos_data().reserve(n_vert);
m.triangles.reserve(n_face);
for(int i = 0 ; i< n_vert;i++)
{
if(!std::getline(f,line))
{
m.get_pos_data().clear();
m_errcde = PARSING_FILE;
m_errmsg = "Not enough vertices to read.";
return false;
}
std::stringstream ls(line);
ls>>v.x>>v.y>>v.z;
m.get_pos_data().push_back(v);
}
for( int i = 0 ; i< n_face;i++)
{
if(!std::getline(f,line))
{
m.get_pos_data().clear();
m.triangles.clear();
m_errcde = PARSING_FILE;
m_errmsg = "Not enough faces to read.";
return false;
}
std::stringstream ls(line);
int q=0;
ls>>q;
if(q!=3)
{
m_errcde = NOT_SUPPORTED;
m_errmsg = "Only triangle meshes are supported for now!";
return false;
}
for(int j = 0; j<3;j++)
ls>>t[j].pos_id;
m.triangles.push_back(t);
}
return true;
}
// PLY-Loader
//------------------------------------------------------------------------------
struct ply_prop
{
int elements;
AttributeID id;
std::string type;
};
bool MeshOPS::read_PLY(Mesh &m, std::ifstream &f)
{
std::string line;
m.active_mask = 0;
for(int a = 0 ; a< AID_COUNT;a++)m.attribute_data[a].clear();
m.triangles.clear();
std::getline(f,line);
trim(line);
if(line != "ply")
{
m_errcde = PARSING_FILE;
m_errmsg = "PLY files should start with 'ply'";
return false;
}
int num_verts;
int num_faces;
std::vector<ply_prop> props;
int reading = 0; // 1 is verts 2 is faces
// read header
while (std::getline(f,line))
{
std::stringstream ls(line);
auto first_word = read_word(ls);
if(first_word == "comment")
continue;
if(first_word == "format")
{
if(read_word(ls) != "ascii")
{
m_errcde = PARSING_FILE;
m_errmsg = "Only PLY ASCII is supported!";
return false;
}
continue;
}
if(first_word == "element")
{
const auto ename = read_word(ls);
if(ename == "vertex")
{
ls>>num_verts;
reading = 1;
}
else if(ename == "face")
{
ls>>num_faces;
reading = 2;
}
else
{
m_errcde = PARSING_FILE;
m_errmsg = "element should be vertex or face not '"+ename+"'";
return false;
}
continue;
}
if(first_word == "property" && reading == 1)
{
auto type = read_word(ls);
auto name = read_word(ls);
AttributeID attrib;
switch (name[0])
{
case 'x':case'y':case'z':attrib = AID_POSITION; break;
case 'n':attrib = AID_NORMAL;break;
case 's':case 't': attrib = AID_TEXCOORD;break;
case 'r':case 'g':case 'b': attrib = AID_COLOR;break;
}
if(props.empty() || props.back().id != attrib)
{
ply_prop p;
p.elements = 1;
p.id = attrib;
p.type = type;
props.push_back(p);
m.active_mask |= (1<<attrib);
m.attribute_data[attrib].reserve(num_verts);
}
else
{
props.back().elements++;
props.back().type = type;
}
}
if(first_word == "end_header")
break;
}
// read vertex data
for(int i =0 ; i<num_verts;i++)
{
if(!std::getline(f,line))
{
m_errcde = PARSING_FILE;
m_errmsg = "Not enough vertices to read.";
return false;
}
std::stringstream ls(line);
for(auto& p : props)
{
vec4 v(0,0,0,0);
for(int j = 0 ; j <p.elements;j++)
ls >>v[j];
float scale = 1.0f;
if(p.type == "float")
{}
else if(p.type == "uchar")
{
scale/=static_cast<float>(std::numeric_limits<uint8_t>::max());
}
else if(p.type == "char")
{
scale/=static_cast<float>(std::numeric_limits<int8_t>::max());
}
else if(p.type == "short")
{
scale/=static_cast<float>(std::numeric_limits<int16_t>::max());
}
else if(p.type == "ushort")
{
scale/=static_cast<float>(std::numeric_limits<uint16_t>::max());
}
else if(p.type == "int")
{
scale/=static_cast<float>(std::numeric_limits<int32_t>::max());
}
else if(p.type == "uint")
{
scale/=static_cast<float>(std::numeric_limits<uint32_t>::max());
}
v*=scale;
if(p.id == AID_COLOR || p.id==AID_POSITION)
v.w = 1.0f;
m.attribute_data[p.id].push_back(v);
}
}
// read face data
m.triangles.reserve(num_faces);
for(int i =0 ; i<num_faces;i++)
{
if(!std::getline(f,line))
{
m_errcde = PARSING_FILE;
m_errmsg = "Not enough faces to read.";
return false;
}
std::stringstream ls(line);
int nv;
ls >> nv;
if(nv != 3)
{
m_errcde = NOT_SUPPORTED;
m_errmsg = "Only triangle meshes are supported!";
return false;
}
int q[3];
ls>>q[0]>>q[1]>>q[2];
Triangle t;
for(int v =0 ; v<3;v++)
{
for(int a = 0; a<AID_COUNT;a++)
{
if(m.active_mask & (1<<a))
{
t[v].att_id[a] = q[v];
t[v].active_mask=m.active_mask;
}
}
}
m.triangles.push_back(t);
}
m = MeshOPS::remove_double_attributes(m);
return true;
}
// OBJP-Loader
//------------------------------------------------------------------------------
bool MeshOPS::read_OBJP(Mesh &m, std::ifstream &f)
{
std::string line;
vec4 v;
m.active_mask = AM_POSITION;
int max_attr = 0;
while (std::getline(f,line))
{
auto first_hash = line.find_first_of('#');
if(line[first_hash+1]=='~')
line[first_hash]='~';
line = line.substr(0,line.find_first_of('#')-1);
trim(line);
if(line.empty()) continue;
std::stringstream line_str(line);
v = vec4(0,0,0,0);
std::string lt = read_word(line_str);
int attr_id = -1;
if(lt == "v") attr_id = 0;
else if(lt == "vt") attr_id = 1;
else if(lt == "vn") attr_id = 2;
else if(lt == "~~vc")attr_id = 3;
else if(lt == "~~vtn")attr_id = 4;
else if(lt == "~~vbtn")attr_id = 5;
if(attr_id >=0)
{
if(attr_id != AID_POSITION || AID_COLOR)
v.w =1.0;
m.active_mask |= (1<<attr_id);
line_str>>v.x>>v.y;
if(attr_id != AID_TEXCOORD)
line_str>>v.z;
if(attr_id == AID_COLOR)
line_str>>v.w;
m.attribute_data[attr_id].push_back(v);
max_attr = std::max(max_attr,attr_id);
}
else if(lt == "f")
{
Triangle t;
for( uint32_t v = 0; v < 3; v++)
{
for(int a =0 ; a<std::min(max_attr+1,3);a++)
{
if(m.active_mask & (1<<a))
{
line_str>>t[v].att_id[a];
t[v].att_id[a]-=1;
}
char c = '@';
if(a!= max_attr && a!= 2)
while(c != '/') line_str>>c;
}
t[v].active_mask = m.active_mask ;
}
m.triangles.push_back(t);
}
else if(lt == "~~f")
{
Triangle& t = m.triangles.back();
for( uint32_t v = 0; v < 3; v++)
{
for(int a =3 ; a<=max_attr;a++)
{
if(m.active_mask & (1<<a))
{
line_str>>t[v].att_id[a];
t[v].att_id[a]-=1;
}
char c = '@';
if(a!= max_attr)
while(c != '/') line_str>>c;
}
t[v].active_mask = m.active_mask ;
}
}
}
return true;
}
///*****************************************************************************
/// OUTPUT *
///*****************************************************************************
bool MeshOPS::write(const Mesh&m, const std::string& path)
{
std::string ext = path.substr(path.find_last_of('.')+1);
for(char &c : ext) c= toupper(c);
std::ofstream f(path);
if(!f.is_open())
{
m_errcde = CANNOT_OPEN_FILE;
m_errmsg = "Cannot open file to write '"+path+"'";
return false;
}
if(ext == "OFF")
{
return MeshOPS::write_OFF(m,f);
}
if(ext == "OBJ+" || ext == "OBJP" || ext=="OBJ")
{
return MeshOPS::write_OBJP(m,f);
}
return false;
}
// OFF-Writer
//------------------------------------------------------------------------------
bool MeshOPS::write_OFF(const Mesh &m, std::ofstream &f)
{
f<<"OFF\n"<<m.get_pos_data().size()<<" "<<m.triangles.size()<<" 0\n";
for( const auto& v : m.get_pos_data())
{
f<<v.x<<" "<<v.y<<" "<<v.z<<"\n";
}
for( const auto& t : m.triangles)
{
f<<"3";
for(int i = 0 ; i< 3;i++)
f<<" "<<t[i].pos_id;
f<<"\n";
}
return true;
}
// OBJ+-Writer
//------------------------------------------------------------------------------
void write_OBJp(const Mesh&m, uint32_t active_mask, std::ofstream& f);
bool MeshOPS::write_OBJP(const Mesh &m, std::ofstream &f)
{
f<<"# OBJ+ extends OBJ, there are now six attributes\n";
f<<"# in order make it OBJ compatible '#~' does not indicate a comment "
"anymore\n";
f<<"# v - vertex position\n";
f<<"# vn - vertex normal\n";
f<<"# vt - vertex textrue coord\n";
f<<"# #~vc - vertex color\n";
f<<"# #~vtn - vertex tangent\n";
f<<"# #~vbtn - vertex bitangent\n";
f<<"# a face consists of up to 6 indices, the usual 3 obj indices,\n";
f<<"# followed by the new obj+ indices, introduced by #~ \n";
f<<"# Example:\n";
f<<"# \tf 1/2/3 2/3/3 3/4/3 #~ 1 2 3 # with normals,texcoords & colors\n";
f<<"# \tf 1 2 3 #~f 3 7 2 # with colors\n";
f<<"# \tf 1 2 3 #~f 3/2 7/4 2/12 # with colors & tangents\n\n";
f<<"# Note any .obj is an .obj+, and the other way arround if\n";
f<<"# and _ONLY_ if there are no commends '#~ ...' in the .obj-file\n";
f<<"# But why in the name of everything holy would your write ~ in an obj?"
"\n\n";
write_OBJp(m,m.active_mask,f);
return true;
}
void write_OBJp(const Mesh&m, uint32_t active_mask, std::ofstream& f)
{
std::string a_names[AID_COUNT] = {
std::string("v"),
std::string("vt"),
std::string("vn"),
std::string("#~vc"),
std::string("#~vtn"),
std::string("#~vbtn")};
int max_active =0 ;
for(int a =0 ; a< AID_COUNT;a++)
if(active_mask & (1<<a))
{
for( const auto& v : m.attribute_data[a])
{
f<<a_names[a]<<" "<<v.x<<" "<<v.y;
if(a != AID_TEXCOORD)
f<<" "<<v.z;
if(a == AID_COLOR)
f<<" "<<v.w;
f<<"\n";
}
max_active = a;
}
for(const auto& t : m.triangles)
{
f<<"f";
for(int v = 0 ; v< 3; v++)
{
f<<" ";
for(int a =0 ; a<= max_active && a < 3;a++)
{
if(active_mask & (1<<a))
{
f<<t[v].att_id[a]+1;
}
if(a<max_active && a != 2)
f<<"/";
}
}
if(max_active > 2)
f<<"\n#~f ";
for(int v = 0 ; v< 3; v++)
{
f<<" ";
for(int a =3 ; a<= max_active;a++)
{
if(active_mask & (1<<a))
{
f<<t[v].att_id[a]+1;
}
if(a<max_active )
f<<"/";
}
}
f<<"\n";
}
}
///*****************************************************************************
///* PROCESSING *
///*****************************************************************************
// Normal calculation
//------------------------------------------------------------------------------
vec4 get_weighted_normal(const Mesh&m, const uint32_t t_id)
{
const auto t = m.triangles[t_id];
const auto& pd = m.get_pos_data();
const vec4 A = (pd[t[1].pos_id])-pd[t[0].pos_id];
const vec4 B = (pd[t[2].pos_id])-pd[t[0].pos_id];
const vec3 a(A);
const vec3 b(B);
const vec3 cr = cross(a,b);
float area = 0.5f* length(cr);
auto n = normalize(cr);
const float w = area/((dot(a,a)*dot(b,b)));
return vec4(n*w,0.0f);
}
void MeshOPS::recalculate_normals(Mesh &m)
{
auto& norms = m.get_nrm_data();
norms.clear();
norms.resize(m.get_pos_data().size(), vec4(0.0f));
for(uint i = 0 ; i < m.triangles.size();i++)
{
auto& t = m.triangles[i];
auto n = get_weighted_normal(m,i);
for(uint j = 0 ;j < 3;j++)
{
t[j].nrm_id = t[j].pos_id;
norms[t[j].pos_id] += n;
}
}
for(auto& a : norms)
{
a = normalize(a);
}
m.active_mask |= AM_NORMAL;
}
// Tangent and Bitangent calculation
//------------------------------------------------------------------------------
bool MeshOPS::recalculate_tan_btn(Mesh &m)
{
uint32_t req = AM_TEXCOORD|AM_NORMAL|AM_POSITION;
if((m.active_mask&req) != req)
{
m_errcde = NEED_MORE_DATA;
m_errmsg = "Calculating tangents and bitangents needs texcoords,"
"normals and positions.";
return false;
}
m.get_tan_data().clear();
m.get_btn_data().clear();
std::map<MeshVertex,uint32_t,
vertex_masked_comperator<AM_POSITION|AM_NORMAL|AM_TEXCOORD>> ids;
auto& tans = m.get_tan_data();
auto& btns = m.get_btn_data();
for (auto& t : m.triangles)
{
auto& vtx = t[0];
const vec4& v0 = m.get_pos_data()[vtx.pos_id];
const vec4& uv0 = m.get_tex_data()[vtx.pos_id];
vtx = t[1];
const vec4& v1 = m.get_pos_data()[vtx.pos_id];
const vec4& uv1 = m.get_tex_data()[vtx.pos_id];
vtx = t[2];
const vec4& v2 = m.get_pos_data()[vtx.pos_id];
const vec4& uv2 = m.get_tex_data()[vtx.pos_id];
vec4 dPos1 = v1 - v0;
vec4 dPos2 = v2 - v0;
vec4 dUV1 =uv1 -uv0;
vec4 dUV2 =uv2 -uv0;
float r = 1.0f / (dUV1.x * dUV2.y - dUV1.y * dUV2.x);
vec4 tan = (dPos1 * dUV2.y - dPos2 * dUV1.y)*r;
vec4 btn = (dPos2 * dUV1.x - dPos1 * dUV2.x)*r;
tan.w = btn.w = 0.0f;
for(uint j = 0 ;j < 3;j++)
{
auto it = ids.find(t[j]);
if(it == ids.end())
{
const uint32_t new_id = static_cast<uint32_t>(tans.size());
ids[t[j]] = new_id;
t[j].tan_id = t[j].btn_id = new_id;
tans.push_back(tan);
btns.push_back(btn);
}
else
{
tans[(*it).second] += tan;
btns[(*it).second] += btn;
}
}
}
m.active_mask |= AM_TANGENT | AM_BITANGENT;
return true;
}
uint32_t insert_attrib_value(const vec4& val,
std::map<vec4,uint32_t,std::less<vec4>>& ad,
std::vector<vec4> &attribute_data)
{
auto it = ad.find(val);
if(it != ad.end())
return (*it).second;
const uint32_t id = static_cast<uint32_t>(attribute_data.size());
ad[val] = id;
attribute_data.push_back(val);
return id;
}
Mesh MeshOPS::remove_double_attributes(const Mesh &m)
{
Mesh r;
std::map<vec4,uint32_t,std::less<vec4> > attribute_id[AID_COUNT];
Triangle proto_tri;
for(auto&v:proto_tri)
v.active_mask = m.active_mask;
r.active_mask = m.active_mask;
r.triangles.resize(m.triangles.size(),proto_tri);
for(uint32_t a = 0 ; a < AID_COUNT; a++)
{
if(!(m.active_mask & (1<<a)))
continue;
const auto& ia_array = m.attribute_data[a];
auto& oa_array = r.attribute_data[a];
auto& attrib_map = attribute_id[a];
for(uint t = 0 ; t<m.triangles.size();t++)
{
for(int v = 0 ; v<3;v++)
{
int aeid= m.triangles[t][v].att_id[a];
r.triangles[t][v].att_id[a] = insert_attrib_value(
ia_array[aeid],
attrib_map,
oa_array);
}
}
}
return r;
}
MeshVertex::MeshVertex()
{
for(uint32_t i = 0 ; i < AID_COUNT;i++)
att_id[i] = UINT32_MAX;
active_mask = (1<<AID_COUNT)-1;
}
bool MeshVertex::operator<(const MeshVertex &o) const
{
for(uint32_t i = 0 ; i< AID_COUNT;i++)
{
if(att_id[i] == o.att_id[i])
continue;
else
return att_id[i] < o.att_id[i];
}
return false;
}
std::string MeshOPS::m_errmsg = "";
ErrorCode MeshOPS::m_errcde=NO_ERROR;
}
| 21.837121 | 80 | 0.535184 | 22427 |
d220acfae0348a757cc2c112bd12f5141ed80802 | 1,358 | cc | C++ | pagespeed/system/redis_cache_cluster_setup_main.cc | dimitrilongo/mod_pagespeed | d0d3bc51aa4feddf010b7085872c64cc46b5aae0 | [
"Apache-2.0"
] | 2 | 2019-11-02T07:54:17.000Z | 2020-04-16T09:26:51.000Z | pagespeed/system/redis_cache_cluster_setup_main.cc | dimitrilongo/mod_pagespeed | d0d3bc51aa4feddf010b7085872c64cc46b5aae0 | [
"Apache-2.0"
] | 12 | 2017-03-14T18:26:11.000Z | 2021-10-01T15:33:50.000Z | pagespeed/system/redis_cache_cluster_setup_main.cc | dimitrilongo/mod_pagespeed | d0d3bc51aa4feddf010b7085872c64cc46b5aae0 | [
"Apache-2.0"
] | 1 | 2020-04-16T09:28:30.000Z | 2020-04-16T09:28:30.000Z | /*
* Copyright 2016 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.
*
* Author: [email protected] (Steve Hill)
*/
#include <vector>
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/system/redis_cache_cluster_setup.h"
// Lint complains if I put 'using namespace net_instaweb' even in main(), so
// adding this instead.
namespace net_instaweb {
namespace {
int SetupRedisCluster() {
StringVector node_ids;
std::vector<int> ports;
ConnectionList connections;
// LOGs errors on failure.
if (RedisCluster::LoadConfiguration(&node_ids, &ports, &connections)) {
RedisCluster::ResetConfiguration(&node_ids, &ports, &connections);
} else {
return 1;
}
return 0;
}
} // namespace
} // namespace net_instaweb
int main(int argc, char** argv) {
return net_instaweb::SetupRedisCluster();
}
| 26.627451 | 76 | 0.726068 | dimitrilongo |
d2236f382ef4a8f1d494d1cede58881c17fb936d | 1,010 | hh | C++ | src/Nuxed/Kernel/Extension/SessionExtension.hh | tomoki1337/framework | ff06d260c5bf2a78a99b8d17b041de756550f95a | [
"MIT"
] | null | null | null | src/Nuxed/Kernel/Extension/SessionExtension.hh | tomoki1337/framework | ff06d260c5bf2a78a99b8d17b041de756550f95a | [
"MIT"
] | null | null | null | src/Nuxed/Kernel/Extension/SessionExtension.hh | tomoki1337/framework | ff06d260c5bf2a78a99b8d17b041de756550f95a | [
"MIT"
] | null | null | null | <?hh // strict
namespace Nuxed\Kernel\Extension;
use namespace Nuxed\Http\Session;
use namespace Nuxed\Kernel\ServiceProvider;
use type Nuxed\Container\ServiceProvider\ServiceProviderInterface;
use type Nuxed\Contract\Http\Server\MiddlewarePipeInterface;
use type Nuxed\Http\Server\MiddlewareFactory;
use type Nuxed\Kernel\Configuration;
class SessionExtension extends AbstractExtension {
<<__Override>>
public function services(
Configuration $_configuration,
): Container<ServiceProviderInterface> {
return vec[
new ServiceProvider\SessionServiceProvider(),
];
}
<<__Override>>
public function pipe(
MiddlewarePipeInterface $pipe,
MiddlewareFactory $middlewares,
): void {
/*
* Register the session middleware in the middleware pipeline.
* This middleware register the 'session' attribute containing the
* session implementation.
*/
$pipe->pipe(
$middlewares->prepare(Session\SessionMiddleware::class),
0x9100,
);
}
}
| 26.578947 | 70 | 0.738614 | tomoki1337 |
d227ed7477080fdc07ca1f44790ce2e1267cc918 | 607 | cpp | C++ | src/layer_renderer.cpp | GhostInABottle/octopus_engine | 50429e889493527bdc0e78b307937002e0f2c510 | [
"BSD-2-Clause"
] | 3 | 2017-10-02T03:18:59.000Z | 2020-11-01T09:21:28.000Z | src/layer_renderer.cpp | GhostInABottle/octopus_engine | 50429e889493527bdc0e78b307937002e0f2c510 | [
"BSD-2-Clause"
] | 2 | 2019-04-06T21:48:08.000Z | 2020-05-22T23:38:54.000Z | src/layer_renderer.cpp | GhostInABottle/octopus_engine | 50429e889493527bdc0e78b307937002e0f2c510 | [
"BSD-2-Clause"
] | 1 | 2017-07-17T20:58:26.000Z | 2017-07-17T20:58:26.000Z | #include "../include/layer_renderer.hpp"
#include "../include/layer.hpp"
#include "../include/custom_shaders.hpp"
#include "../include/utility/file.hpp"
#include "../include/log.hpp"
#include <utility>
Layer_Renderer::Layer_Renderer(const Layer& layer, const Camera& camera) :
layer(layer), camera(camera), needs_redraw(false) {
if (!layer.vertex_shader.empty()) {
auto vshader = file_utilities::read_file(layer.vertex_shader);
auto fshader = file_utilities::read_file(layer.fragment_shader);
batch.set_shader(std::make_unique<Custom_Shader>(vshader, fshader));
}
}
| 37.9375 | 76 | 0.711697 | GhostInABottle |
d22aac8fb80d854c44ab859af04e81414a0eddfc | 2,924 | hpp | C++ | include/GaussianProcessSupport.hpp | snowpac/snowpac | ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305 | [
"BSD-2-Clause"
] | 3 | 2019-08-04T20:18:00.000Z | 2021-06-22T23:50:27.000Z | include/GaussianProcessSupport.hpp | snowpac/snowpac | ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305 | [
"BSD-2-Clause"
] | null | null | null | include/GaussianProcessSupport.hpp | snowpac/snowpac | ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305 | [
"BSD-2-Clause"
] | null | null | null | #ifndef HGaussianProcessSupport
#define HGaussianProcessSupport
#include "GaussianProcess.hpp"
#include "BlackBoxData.hpp"
#include "VectorOperations.hpp"
#include <vector>
#include <float.h>
#include <cmath>
#include <iomanip>
#include <assert.h>
class GaussianProcessSupport : protected VectorOperations {
private:
double *delta;
bool do_parameter_estimation = false;
int number_processes;
int nb_values = 0;
std::vector<int> update_at_evaluations;
int update_interval_length;
int next_update = 0;
int last_included = 0;
int best_index;
double delta_tmp;
double variance, mean;
double weight;
std::vector<double> gaussian_process_values;
std::vector<double> gaussian_process_noise;
std::vector< std::vector<double> > gaussian_process_nodes;
std::vector<int> gaussian_process_active_index;
std::vector<std::shared_ptr<GaussianProcess>> gaussian_processes;
std::vector<double> rescaled_node;
std::vector<std::vector<double>> best_index_analytic_information;
bool use_approx_gaussian_process = false;
bool approx_gaussian_process_active = false;
bool use_analytic_smoothing = false;
const double u_ratio = 0.15;
const int min_nb_u = 2;
int cur_nb_u_points = 0;
double gaussian_process_delta_factor = 3.;
std::vector<double> bootstrap_estimate;
int smoothing_ctr;
private:
int NOEXIT;
void update_gaussian_processes_for_agp( BlackBoxData&);
static double fill_width_objective(std::vector<double> const &x,
std::vector<double> &grad,
void *data);
static void ball_constraint(unsigned int m, double* c, unsigned n, const double *x, double *grad, void *data);
//void do_resample_u(); //TODO check if able to remove this one
protected:
virtual double compute_fill_width(BlackBoxData& evaluations);
void update_gaussian_processes ( BlackBoxData& );
void update_gaussian_processes_for_gp (BlackBoxData&);
public:
void initialize ( const int, const int, double&, BlackBoxBaseClass *blackbox,
std::vector<int> const&, int , const std::string, const int exitconst, const bool use_analytic_smoothing);
int smooth_data ( BlackBoxData& );
double evaluate_objective ( BlackBoxData const& );
void evaluate_gaussian_process_at(const int&, std::vector<double> const&, double&, double&);
const std::vector<std::vector<double>> &get_nodes_at(const int&) const;
void get_induced_nodes_at(const int idx, std::vector<std::vector<double>> &induced_nodes);
void set_constraint_ball_center(const std::vector<double>& center);
void set_constraint_ball_radius(const double& radius);
const std::vector<std::vector<double>> &getBest_index_analytic_information() const;
void set_gaussian_process_delta(double gaussian_process_delta);
};
#endif
| 33.227273 | 128 | 0.718878 | snowpac |
d22f225f252e9421c36e5091464181bd2aadf2ef | 20 | cpp | C++ | src/cpps_module.cpp | TansuoTro/CPPS | cca35d8dc2128aba7fa4a40cb6d83487e265cf3f | [
"MIT"
] | null | null | null | src/cpps_module.cpp | TansuoTro/CPPS | cca35d8dc2128aba7fa4a40cb6d83487e265cf3f | [
"MIT"
] | null | null | null | src/cpps_module.cpp | TansuoTro/CPPS | cca35d8dc2128aba7fa4a40cb6d83487e265cf3f | [
"MIT"
] | null | null | null | #include "cpps.h"
| 5 | 17 | 0.6 | TansuoTro |
d230fcc4f1e016884d0b9ab207c200a21082df75 | 949 | cpp | C++ | cpp/p74.cpp | voltrevo/project-euler | 0db5451f72b1353b295e56f928c968801e054444 | [
"MIT"
] | null | null | null | cpp/p74.cpp | voltrevo/project-euler | 0db5451f72b1353b295e56f928c968801e054444 | [
"MIT"
] | null | null | null | cpp/p74.cpp | voltrevo/project-euler | 0db5451f72b1353b295e56f928c968801e054444 | [
"MIT"
] | null | null | null | #include <cassert>
#include <iostream>
int factorials[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
int NonRepeatLength(int n)
{
int count = 0;
while (count != 61)
{
++count;
int nCopy = n;
n = 0;
while (nCopy > 0)
{
n += factorials[nCopy % 10];
nCopy /= 10;
}
if (n == 0 || n == 1 || n == 2 || n == 145)
return count + 1;
else if (n == 169 || n == 1454 || n == 363601)
return count + 3;
else if (n == 871 || n == 872 || n == 45361 || n == 45362)
return count + 2;
}
return -1;
}
int main()
{
int count = 0;
assert(NonRepeatLength(69) == 5);
assert(NonRepeatLength(78) == 4);
for (int i = 3; i != 1000000; ++i)
{
if (NonRepeatLength(i) == 60)
++count;
}
std::cout << count << std::endl;
return 0;
}
| 19.770833 | 69 | 0.42255 | voltrevo |
d23165a566a38bd2b648ef2b69ff4cab9d235301 | 7,215 | cpp | C++ | Source/Renderer.cpp | cstechfoodie/COMP371-Computer-Graphic-Scence-of-End-of-the-World | 91e47546d663e079b756fd90dab14c8954903a5a | [
"MIT"
] | 2 | 2019-08-09T00:54:29.000Z | 2020-11-16T22:49:27.000Z | Source/Renderer.cpp | cstechfoodie/COMP371-Computer-Graphic-Scence-of-End-of-the-World | 91e47546d663e079b756fd90dab14c8954903a5a | [
"MIT"
] | null | null | null | Source/Renderer.cpp | cstechfoodie/COMP371-Computer-Graphic-Scence-of-End-of-the-World | 91e47546d663e079b756fd90dab14c8954903a5a | [
"MIT"
] | 2 | 2019-08-08T13:42:35.000Z | 2019-08-09T22:20:41.000Z | //
// COMP 371 Assignment Framework
//
// Created by Nicolas Bergeron on 8/7/14.
// Updated by Gary Chang on 14/1/15
//
// Copyright (c) 2014-2019 Concordia University. All rights reserved.
//
#include "Renderer.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
#include <stdlib.h>
#include <string.h>
#include "Renderer.h"
#include "EventManager.h"
#include <GLFW/glfw3.h>
#if defined(PLATFORM_OSX)
#define fscanf_s fscanf
#endif
std::vector<unsigned int> Renderer::sShaderProgramID;
unsigned int Renderer::sCurrentShader;
GLFWwindow* Renderer::spWindow = nullptr;
void Renderer::Initialize()
{
spWindow = EventManager::GetWindow();
glfwMakeContextCurrent(spWindow);
// Initialize GLEW
glewExperimental = true; // Needed for core profile
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
getchar();
exit(-1);
}
// Somehow, glewInit triggers a glInvalidEnum... Let's ignore it
glGetError();
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
// Enable depth test
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
CheckForErrors();
// Loading Shaders
#if defined(PLATFORM_OSX)
std::string shaderPathPrefix = "Shaders/";
#else
std::string shaderPathPrefix = "../Assets/Shaders/";
#endif
sShaderProgramID.push_back(
LoadShaders(shaderPathPrefix + "SolidColor.vertexshader",
shaderPathPrefix + "SolidColor.fragmentshader")
);
sShaderProgramID.push_back(
LoadShaders(shaderPathPrefix + "PathLines.vertexshader",
shaderPathPrefix + "PathLines.fragmentshader")
);
sShaderProgramID.push_back(
LoadShaders(shaderPathPrefix + "SolidColor.vertexshader",
shaderPathPrefix + "BlueColor.fragmentshader")
);
sShaderProgramID.push_back(
LoadShaders(shaderPathPrefix + "Texture.vertexshader",
shaderPathPrefix + "Texture.fragmentshader")
);
sCurrentShader = 0;
}
void Renderer::Shutdown()
{
// Shaders
for (vector<unsigned int>::iterator it = sShaderProgramID.begin(); it < sShaderProgramID.end(); ++it)
{
glDeleteProgram(*it);
}
sShaderProgramID.clear();
// Managed by EventManager
spWindow = nullptr;
}
void Renderer::BeginFrame()
{
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Renderer::EndFrame()
{
// Swap buffers
glfwSwapBuffers(spWindow);
CheckForErrors();
}
void Renderer::SetShader(ShaderType type)
{
if (type < (int) sShaderProgramID.size())
{
sCurrentShader = type;
}
}
//
// The following code is taken from
// www.opengl-tutorial.org
//
GLuint Renderer::LoadShaders(std::string vertex_shader_path,std::string fragment_shader_path)
{
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
// Read the Vertex Shader code from the file
std::string VertexShaderCode;
std::ifstream VertexShaderStream(vertex_shader_path, std::ios::in);
if(VertexShaderStream.is_open()){
std::string Line = "";
while(getline(VertexShaderStream, Line))
VertexShaderCode += "\n" + Line;
VertexShaderStream.close();
}else{
printf("Impossible to open %s. Are you in the right directory ? Don't forget to read the FAQ !\n", vertex_shader_path.c_str());
getchar();
exit(-1);
}
// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragment_shader_path, std::ios::in);
if(FragmentShaderStream.is_open()){
std::string Line = "";
while(getline(FragmentShaderStream, Line))
FragmentShaderCode += "\n" + Line;
FragmentShaderStream.close();
}
GLint Result = GL_FALSE;
int InfoLogLength;
// Compile Vertex Shader
printf("Compiling shader : %s\n", vertex_shader_path.c_str());
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer, nullptr);
glCompileShader(VertexShaderID);
// Check Vertex Shader
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> VertexShaderErrorMessage(InfoLogLength+1);
glGetShaderInfoLog(VertexShaderID, InfoLogLength, nullptr, &VertexShaderErrorMessage[0]);
printf("%s\n", &VertexShaderErrorMessage[0]);
}
// Compile Fragment Shader
printf("Compiling shader : %s\n", fragment_shader_path.c_str());
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, nullptr);
glCompileShader(FragmentShaderID);
// Check Fragment Shader
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> FragmentShaderErrorMessage(InfoLogLength+1);
glGetShaderInfoLog(FragmentShaderID, InfoLogLength, nullptr, &FragmentShaderErrorMessage[0]);
printf("%s\n", &FragmentShaderErrorMessage[0]);
}
// Link the program
printf("Linking program\n");
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
// Check the program
glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> ProgramErrorMessage(InfoLogLength+1);
glGetProgramInfoLog(ProgramID, InfoLogLength, nullptr, &ProgramErrorMessage[0]);
printf("%s\n", &ProgramErrorMessage[0]);
}
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
bool Renderer::PrintError()
{
static bool checkForErrors = true;
//
if( !checkForErrors )
{
return false;
}
//
const char * errorString = NULL;
bool retVal = false;
switch( glGetError() )
{
case GL_NO_ERROR:
retVal = true;
break;
case GL_INVALID_ENUM:
errorString = "GL_INVALID_ENUM";
break;
case GL_INVALID_VALUE:
errorString = "GL_INVALID_VALUE";
break;
case GL_INVALID_OPERATION:
errorString = "GL_INVALID_OPERATION";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
errorString = "GL_INVALID_FRAMEBUFFER_OPERATION";
break;
case GL_OUT_OF_MEMORY:
errorString = "GL_OUT_OF_MEMORY";
break;
default:
errorString = "UNKNOWN";
break;
}
//
if( !retVal )
{
printf( "%s\n", errorString );
}
//
return retVal;
}
void Renderer::CheckForErrors()
{
while(PrintError() == false)
{
}
}
| 25.052083 | 129 | 0.666112 | cstechfoodie |
d233ce3c377159f4e760f9ceaf0322d6617761c1 | 947 | cpp | C++ | Codeforces/1283C.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | Codeforces/1283C.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | Codeforces/1283C.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int arr[200000];
bool received[200000];
bool notYet[200000];
set<int> ungifted;
set<int> undecided;
int main(){
int n, i;
cin >> n;
for(i=0; i<n; i++){
cin >> arr[i];
if(arr[i]>0){
received[arr[i]-1]=true;
}
}
for(i=0; i<n; i++){
if(!received[i]){
ungifted.insert(i);
}
if(arr[i]==0){
undecided.insert(i);
}
}
auto ungiftedIt = ungifted.begin();
auto undecidedIt = undecided.rbegin();
while(ungiftedIt != ungifted.end()){
int ungifted = *ungiftedIt;
int undecided = *undecidedIt;
//cout << undecided << " to " << ungifted+1 << endl;
arr[undecided]=ungifted+1;
ungiftedIt++;
undecidedIt++;
}
for(i=0; i<n; i++){
if(arr[i]-1==i){
undecidedIt = undecided.rbegin();
if(*undecidedIt == i){
undecidedIt++;
}
arr[i]=arr[*undecidedIt];
arr[*undecidedIt]=i+1;
}
}
for(i=0; i<n; i++){
printf("%d ", arr[i]);
}
printf("\n");
return 0;
} | 18.568627 | 54 | 0.581837 | DT3264 |
d23639af87c1f15f9c808a8fdbe311cfc4f5bd68 | 369 | cpp | C++ | Split the Str Ing.cpp | Rogg-et/codechef-challenges | 7704901eaa3928730124dd43b57f213a82d19392 | [
"MIT"
] | 2 | 2020-10-30T16:22:31.000Z | 2021-10-06T14:30:07.000Z | Split the Str Ing.cpp | Rogg-et/codechef-challenges | 7704901eaa3928730124dd43b57f213a82d19392 | [
"MIT"
] | 2 | 2021-10-08T19:49:53.000Z | 2021-10-08T19:53:56.000Z | Split the Str Ing.cpp | Rogg-et/codechef-challenges | 7704901eaa3928730124dd43b57f213a82d19392 | [
"MIT"
] | 9 | 2020-10-17T19:11:38.000Z | 2021-10-19T01:55:18.000Z | #include<iostream>
using namespace std;
int main()
{ int t;
cin>>t;
for(int i=1;i<=t;i++)
{
int n;
cin>>n;
string s;
cin>>s;
int temp=0;
for(int j=0;j<n-1;j++)
{
if(s[j]==s[n-1]) {cout<<"YES"<<endl; temp++; break;}
}
if(temp==0) cout<<"NO"<<endl;
}
return 0;
}
| 17.571429 | 62 | 0.401084 | Rogg-et |
d238b410650a672e3f03549f0f15011e8fcbdb69 | 39,395 | hpp | C++ | tests/functional/coherence/net/messaging/NamedCacheTest.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | tests/functional/coherence/net/messaging/NamedCacheTest.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | tests/functional/coherence/net/messaging/NamedCacheTest.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "cxxtest/TestSuite.h"
#include "coherence/lang.ns"
#include "coherence/net/DefaultOperationalContext.hpp"
#include "coherence/net/OperationalContext.hpp"
#include "coherence/run/xml/XmlElement.hpp"
#include "coherence/util/ArrayList.hpp"
#include "private/coherence/component/net/extend/RemoteNamedCache.hpp"
#include "private/coherence/component/net/extend/protocol/cache/ClearRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/ContainsAllRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/ContainsKeyRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/ContainsValueRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/GetRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/GetAllRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/NamedCacheResponse.hpp"
#include "private/coherence/component/net/extend/protocol/cache/PutRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/PutAllRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/RemoveRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/RemoveAllRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/SizeRequest.hpp"
#include "private/coherence/component/net/extend/protocol/cache/service/DestroyCacheRequest.hpp"
#include "private/coherence/component/util/Peer.hpp"
#include "private/coherence/component/util/TcpInitiator.hpp"
#include "private/coherence/net/messaging/Connection.hpp"
#include "private/coherence/net/messaging/ConnectionInitiator.hpp"
#include "private/coherence/net/messaging/Message.hpp"
#include "private/coherence/util/logging/Logger.hpp"
using namespace coherence::lang;
using namespace std;
using coherence::net::DefaultOperationalContext;
using coherence::net::OperationalContext;
using coherence::util::ArrayList;
using coherence::component::net::extend::RemoteNamedCache;
using coherence::component::net::extend::protocol::cache::ClearRequest;
using coherence::component::net::extend::protocol::cache::ContainsAllRequest;
using coherence::component::net::extend::protocol::cache::ContainsKeyRequest;
using coherence::component::net::extend::protocol::cache::ContainsValueRequest;
using coherence::component::net::extend::protocol::cache::GetRequest;
using coherence::component::net::extend::protocol::cache::GetAllRequest;
using coherence::component::net::extend::protocol::cache::NamedCacheResponse;
using coherence::component::net::extend::protocol::cache::PutRequest;
using coherence::component::net::extend::protocol::cache::PutAllRequest;
using coherence::component::net::extend::protocol::cache::RemoveRequest;
using coherence::component::net::extend::protocol::cache::RemoveAllRequest;
using coherence::component::net::extend::protocol::cache::SizeRequest;
using coherence::component::net::extend::protocol::cache::service::DestroyCacheRequest;
using coherence::component::util::Peer;
using coherence::component::util::TcpInitiator;
using coherence::net::messaging::Connection;
using coherence::net::messaging::ConnectionInitiator;
using coherence::net::messaging::Message;
using coherence::run::xml::XmlElement;
using coherence::util::logging::Logger;
/**
* NamedCache Test Suite.
*/
class NamedCacheTest : public CxxTest::TestSuite
{
MemberHandle<Connection> m_hConnection;
MemberHandle<ConnectionInitiator> m_hInitiator;
MemberHandle<Channel> hNamedCacheChannel;
MemberView<Protocol::MessageFactory> vNamedCacheFactory;
MemberHandle<RemoteNamedCache::ConverterFromBinary> convFromBinary;
MemberHandle<RemoteNamedCache::ConverterValueToBinary> convToBinary;
MemberHandle<Channel> hCacheServiceChannel;
public:
NamedCacheTest()
: m_hConnection(System::common()),
m_hInitiator(System::common()),
hNamedCacheChannel(System::common()),
vNamedCacheFactory(System::common()),
convFromBinary(System::common()),
convToBinary(System::common()),
hCacheServiceChannel(System::common())
{
}
// ----- test fixtures --------------------------------------------------
public:
/**
* Runs before each test
*/
void setUp()
{
OperationalContext::View vContext = DefaultOperationalContext::create();
// Need to manage logger manually as we are not using CacheFactory
Logger::getLogger()->shutdown();
Logger::Handle hLogger = Logger::getLogger();
hLogger->configure(vContext);
hLogger->start();
stringstream ss;
ss << " <initiator-config>"
<< " <tcp-initiator>"
<< " <remote-addresses>"
<< " <socket-address>"
<< " <address system-property=\"tangosol.coherence.proxy.address\">127.0.0.1</address>"
<< " <port system-property=\"tangosol.coherence.proxy.port\">32000</port>"
<< " </socket-address>"
<< " </remote-addresses>"
<< " </tcp-initiator>"
<< " </initiator-config>";
m_hInitiator = TcpInitiator::create();
m_hInitiator->setOperationalContext(vContext);
XmlElement::Handle hXml = SimpleParser::create()->parseXml(ss);
XmlHelper::replaceSystemProperties(hXml, "system-property");
m_hInitiator->configure(hXml);
m_hInitiator->registerProtocol(CacheServiceProtocol::getInstance());
m_hInitiator->registerProtocol(NamedCacheProtocol::getInstance());
m_hInitiator->start();
m_hConnection = m_hInitiator->ensureConnection();
convFromBinary = RemoteNamedCache::ConverterFromBinary::create();
convToBinary = RemoteNamedCache::ConverterValueToBinary::create();
hCacheServiceChannel = m_hConnection->openChannel(CacheServiceProtocol::getInstance(), "CacheServiceProxy", NULL, NULL);
vNamedCacheFactory = hCacheServiceChannel->getMessageFactory();
EnsureCacheRequest::Handle hEnsureRequest = cast<EnsureCacheRequest::Handle>(vNamedCacheFactory->createMessage(EnsureCacheRequest::type_id));
hEnsureRequest->setCacheName("dist-extend-direct");
URI::View vUri = URI::create(cast<String::View>(hCacheServiceChannel->request(cast<Request::Handle>(hEnsureRequest))));
hNamedCacheChannel = m_hConnection->acceptChannel(vUri, NULL, NULL);
vNamedCacheFactory = hNamedCacheChannel->getMessageFactory();
convToBinary->setSerializer(hNamedCacheChannel->getSerializer());
convFromBinary->setSerializer(hNamedCacheChannel->getSerializer());
}
/**
* Runs after each test
*/
void tearDown()
{
ConnectionInitiator::Handle hInitiator = m_hInitiator;
if (hInitiator != NULL)
{
hInitiator->stop();
m_hInitiator = NULL;
}
Logger::getLogger()->shutdown();
}
public:
/**
* Test MessageFactory.
*/
void testMessageFactory()
{
Message::Handle hGetRequest = vNamedCacheFactory->createMessage(GetRequest::type_id);
TS_ASSERT(instanceof<GetRequest::View>(hGetRequest));
TS_ASSERT(GetRequest::type_id == hGetRequest->getTypeId());
Message::Handle hPutRequest = vNamedCacheFactory->createMessage(PutRequest::type_id);
TS_ASSERT(instanceof<PutRequest::View>(hPutRequest));
TS_ASSERT(PutRequest::type_id == hPutRequest->getTypeId());
Message::Handle hSizeRequest = vNamedCacheFactory->createMessage(SizeRequest::type_id);
TS_ASSERT(instanceof<SizeRequest::View>(hSizeRequest));
TS_ASSERT(SizeRequest::type_id == hSizeRequest->getTypeId());
Message::Handle hGetAllRequest = vNamedCacheFactory->createMessage(GetAllRequest::type_id);
TS_ASSERT(instanceof<GetAllRequest::View>(hGetAllRequest));
TS_ASSERT(GetAllRequest::type_id == hGetAllRequest->getTypeId());
Message::Handle hPutAllRequest = vNamedCacheFactory->createMessage(PutAllRequest::type_id);
TS_ASSERT(instanceof<PutAllRequest::View>(hPutAllRequest));
TS_ASSERT(PutAllRequest::type_id == hPutAllRequest->getTypeId());
Message::Handle hClearRequest = vNamedCacheFactory->createMessage(ClearRequest::type_id);
TS_ASSERT(instanceof<ClearRequest::View>(hClearRequest));
TS_ASSERT(ClearRequest::type_id == hClearRequest->getTypeId());
Message::Handle hContainsKeyRequest = vNamedCacheFactory->createMessage(ContainsKeyRequest::type_id);
TS_ASSERT(instanceof<ContainsKeyRequest::View>(hContainsKeyRequest));
TS_ASSERT(ContainsKeyRequest::type_id == hContainsKeyRequest->getTypeId());
Message::Handle hContainsValueRequest = vNamedCacheFactory->createMessage(ContainsValueRequest::type_id);
TS_ASSERT(instanceof<ContainsValueRequest::View>(hContainsValueRequest));
TS_ASSERT(ContainsValueRequest::type_id == hContainsValueRequest->getTypeId());
Message::Handle hContainsAllRequest = vNamedCacheFactory->createMessage(ContainsAllRequest::type_id);
TS_ASSERT(instanceof<ContainsAllRequest::View>(hContainsAllRequest));
TS_ASSERT(ContainsAllRequest::type_id == hContainsAllRequest->getTypeId());
Message::Handle hRemoveRequest = vNamedCacheFactory->createMessage(RemoveRequest::type_id);
TS_ASSERT(instanceof<RemoveRequest::View>(hRemoveRequest));
TS_ASSERT(RemoveRequest::type_id == hRemoveRequest->getTypeId());
Message::Handle hRemoveAllRequest = vNamedCacheFactory->createMessage(RemoveAllRequest::type_id);
TS_ASSERT(instanceof<RemoveAllRequest::View>(hRemoveAllRequest));
TS_ASSERT(RemoveAllRequest::type_id == hRemoveAllRequest->getTypeId());
}
/**
* Test PutRequest.
*/
void testPutRequest()
{
String::Handle key = "testPutKey";
String::Handle value1 = "testPutValue1";
String::Handle value2 = "testPutValue2";
Object::Holder previousValue;
GetRequest::Handle hGetRequest = cast<GetRequest::Handle>(vNamedCacheFactory->createMessage(GetRequest::type_id));
hGetRequest->setKey(convToBinary->convert(key));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hGetRequest))->waitForResponse(-1);
if (hResponse->isFailure() == false)
{
previousValue = convFromBinary->convert(hResponse->getResult());
}
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value1));
hPutRequest->setReturnRequired(true);
OctetArrayWriteBuffer::Handle hBuf = OctetArrayWriteBuffer::create(1024);
WriteBuffer::BufferOutput::Handle hbout = hBuf->getBufferOutput();
Codec::Handle hCodec = PofCodec::create();
hCodec->encode(hNamedCacheChannel, hPutRequest, hbout);
ReadBuffer::BufferInput::Handle hbin = hBuf->getReadBuffer()->getBufferInput();
PutRequest::Handle hPutRequestResult = cast<PutRequest::Handle>(hCodec->decode(hNamedCacheChannel, hbin));
TS_ASSERT(hPutRequestResult->getExpiryDelay() == hPutRequest->getExpiryDelay());
TS_ASSERT(hPutRequestResult->isReturnRequired() == hPutRequest->isReturnRequired());
TS_ASSERT(hPutRequestResult->getValue()->equals(convToBinary->convert(value1)));
hPutRequest = hPutRequestResult;
Response::Handle hPutResponse = hNamedCacheChannel->send(cast<Request::Handle>(hPutRequest))->waitForResponse(-1);
TS_ASSERT(hPutRequest->getTypeId() == PutRequest::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hPutResponse));
TS_ASSERT_EQUALS(7, hPutRequest->getImplVersion());
TS_ASSERT(hPutResponse->isFailure() == false);
TS_ASSERT(hPutRequest->getId() == hPutResponse->getRequestId());
TS_ASSERT(hPutResponse->getTypeId() == 0);
if (hPutRequest->isReturnRequired() == true)
{
if (previousValue == NULL)
{
TS_ASSERT(hPutResponse->getResult() == NULL);
}
else
{
TS_ASSERT(hPutResponse->getResult()->equals(convToBinary->convert(previousValue)));
}
}
hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value2));
hPutRequest->setReturnRequired(true);
hPutResponse = hNamedCacheChannel->send(cast<Request::Handle>(hPutRequest))->waitForResponse(-1);
TS_ASSERT(hPutResponse->isFailure() == false);
TS_ASSERT(hPutRequest->getId() == hPutResponse->getRequestId());
TS_ASSERT(hPutResponse->getTypeId() == 0);
if (hPutRequest->isReturnRequired() == true)
{
TS_ASSERT(value1->equals(convFromBinary->convert(hPutResponse->getResult())));
}
}
/**
* Test GetRequest.
*/
void testGetRequest()
{
String::Handle key = "testGetKey";
String::Handle value = "testGetValue";
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value));
hNamedCacheChannel->request(cast<Request::Handle>(hPutRequest));
GetRequest::Handle hGetRequest = cast<GetRequest::Handle>(vNamedCacheFactory->createMessage(GetRequest::type_id));
hGetRequest->setKey(convToBinary->convert(key));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hGetRequest))->waitForResponse(-1);
TS_ASSERT(hPutRequest->getTypeId() == PutRequest::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hResponse));
TS_ASSERT_EQUALS(7, hGetRequest->getImplVersion());
TS_ASSERT(hResponse->isFailure() == false);
TS_ASSERT(hGetRequest->getId() == hResponse->getRequestId());
TS_ASSERT(hResponse->getTypeId() == 0);
TS_ASSERT(value->equals(convFromBinary->convert(hResponse->getResult())));
}
/**
* Test GetRequest and PutAllRequest.
*/
void testGetAndPutAllRequest()
{
ObjectArray::Handle keys = ObjectArray::create(3);
keys[0] = String::create("Goran Milosavljevic");
keys[1] = String::create("Ana Cikic");
keys[2] = String::create("Ivan Cikic");
ObjectArray::Handle values = ObjectArray::create(3);
values[0] = String::create("10.0.0.180");
values[1] = String::create("10.0.0.181");
values[2] = String::create("10.0.0.182");
HashMap::Handle addresses = HashMap::create();
addresses->put(convToBinary->convert(keys[0]), convToBinary->convert(values[0]));
addresses->put(convToBinary->convert(keys[1]), convToBinary->convert(values[1]));
addresses->put(convToBinary->convert(keys[2]), convToBinary->convert(values[2]));
PutAllRequest::Handle hPutAllRequest = cast<PutAllRequest::Handle>(vNamedCacheFactory->createMessage(PutAllRequest::type_id));
hPutAllRequest->setMap(addresses);
OctetArrayWriteBuffer::Handle hBuf = OctetArrayWriteBuffer::create(1024);
WriteBuffer::BufferOutput::Handle hbout = hBuf->getBufferOutput();
Codec::Handle hCodec = PofCodec::create();
hCodec->encode(hNamedCacheChannel, hPutAllRequest, hbout);
ReadBuffer::BufferInput::Handle hbin = hBuf->getReadBuffer()->getBufferInput();
PutAllRequest::Handle hResult = cast<PutAllRequest::Handle>(hCodec->decode(hNamedCacheChannel, hbin));
TS_ASSERT(hResult->getMap()->size() == 3);
TS_ASSERT(addresses->get(convToBinary->convert(keys[0]))->equals(hResult->getMap()->get(convToBinary->convert(keys[0]))));
TS_ASSERT(addresses->get(convToBinary->convert(keys[1]))->equals(hResult->getMap()->get(convToBinary->convert(keys[1]))));
TS_ASSERT(addresses->get(convToBinary->convert(keys[2]))->equals(hResult->getMap()->get(convToBinary->convert(keys[2]))));
hPutAllRequest = cast<PutAllRequest::Handle>(vNamedCacheFactory->createMessage(PutAllRequest::type_id));
hPutAllRequest->setMap(addresses);
Response::Handle hPutAllResponse = hNamedCacheChannel->send(cast<Request::Handle>(hPutAllRequest))->waitForResponse(-1);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hPutAllResponse));
TS_ASSERT(hPutAllResponse->isFailure() == false);
TS_ASSERT(hPutAllRequest->getId() == hPutAllResponse->getRequestId());
TS_ASSERT(hPutAllResponse->getResult() == NULL);
GetAllRequest::Handle hGetAllRequest = cast<GetAllRequest::Handle>(vNamedCacheFactory->createMessage(GetAllRequest::type_id));
ArrayList::Handle hNames = ArrayList::create();
hNames->add(convToBinary->convert(keys[1]));
hNames->add(convToBinary->convert(keys[2]));
hGetAllRequest->setKeySet(hNames);
Response::Handle hGetAllResponse = hNamedCacheChannel->send(cast<Request::Handle>(hGetAllRequest))->waitForResponse(-1);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hGetAllResponse));
TS_ASSERT(hGetAllResponse->isFailure() == false);
TS_ASSERT(hGetAllRequest->getId() == hGetAllResponse->getRequestId());
TS_ASSERT(hGetAllResponse->getTypeId() == 0);
TS_ASSERT(instanceof<Map::View>(hGetAllResponse->getResult()));
Map::View vResult = cast<Map::View>(hGetAllResponse->getResult());
TS_ASSERT(addresses->get(convToBinary->convert(keys[1]))->equals(vResult->get(convToBinary->convert(keys[1]))));
TS_ASSERT(addresses->get(convToBinary->convert(keys[2]))->equals(vResult->get(convToBinary->convert(keys[2]))));
}
/**
* Test SizeRequest.
*/
void testSizeRequest()
{
ClearRequest::Handle hClearRequest = cast<ClearRequest::Handle>(vNamedCacheFactory->createMessage(ClearRequest::type_id));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hClearRequest))->waitForResponse(-1);
TS_ASSERT(hClearRequest->getTypeId() == ClearRequest::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hResponse));
TS_ASSERT(hClearRequest->getId() == hResponse->getRequestId());
TS_ASSERT(hResponse->isFailure() == false);
SizeRequest::Handle hSizeRequest = cast<SizeRequest::Handle>(vNamedCacheFactory->createMessage(SizeRequest::type_id));
Response::Handle hSizeResponseBefore = hNamedCacheChannel->send(cast<Request::Handle>(hSizeRequest))->waitForResponse(-1);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hSizeResponseBefore));
TS_ASSERT(hSizeResponseBefore->isFailure() == false);
TS_ASSERT(hSizeRequest->getId() == hSizeResponseBefore->getRequestId());
TS_ASSERT(hSizeResponseBefore->getTypeId() == 0);
TS_ASSERT(instanceof<Integer32::View>(hSizeResponseBefore->getResult()));
Integer32::View sizeBefore = cast<Integer32::View>(hSizeResponseBefore->getResult());
TS_ASSERT(sizeBefore->getInt32Value() == 0);
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(String::create("newKey")));
hPutRequest->setValue(convToBinary->convert(String::create("newValue")));
hNamedCacheChannel->request(cast<Request::Handle>(hPutRequest));
hSizeRequest = cast<SizeRequest::Handle>(vNamedCacheFactory->createMessage(SizeRequest::type_id));
Response::Handle hSizeResponseAfter = hNamedCacheChannel->send(cast<Request::Handle>(hSizeRequest))->waitForResponse(-1);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hSizeResponseAfter));
TS_ASSERT(hSizeResponseAfter->isFailure() == false);
TS_ASSERT(hSizeRequest->getId() == hSizeResponseAfter->getRequestId());
TS_ASSERT(hSizeResponseAfter->getTypeId() == 0);
TS_ASSERT(instanceof<Integer32::View>(hSizeResponseAfter->getResult()));
Integer32::View sizeAfter = cast<Integer32::View>(hSizeResponseAfter->getResult());
TS_ASSERT(sizeAfter->getInt32Value() == 1);
}
/**
* Test NamedCache Exception.
*/
void testNamedCacheException()
{
ObjectArray::Handle keys = ObjectArray::create(3);
keys[0] = String::create("Goran Milosavljevic");
keys[1] = String::create("Ana Cikic");
keys[2] = String::create("Ivan Cikic");
ObjectArray::Handle values = ObjectArray::create(3);
values[0] = String::create("10.0.0.180");
values[1] = String::create("10.0.0.181");
values[2] = String::create("10.0.0.182");
HashMap::Handle addresses = HashMap::create();
addresses->put(convToBinary->convert(keys[0]), convToBinary->convert(values[0]));
addresses->put(convToBinary->convert(keys[1]), convToBinary->convert(values[1]));
addresses->put(convToBinary->convert(keys[2]), convToBinary->convert(values[2]));
PutAllRequest::Handle hPutAllRequest = cast<PutAllRequest::Handle>(vNamedCacheFactory->createMessage(PutAllRequest::type_id));
hPutAllRequest->setMap(addresses);
hNamedCacheChannel->request(cast<Request::Handle>(hPutAllRequest));
DestroyCacheRequest::Handle hDestroyRequest = cast<DestroyCacheRequest::Handle>(hCacheServiceChannel->getMessageFactory()->createMessage(DestroyCacheRequest::type_id));
hDestroyRequest->setCacheName("dist-extend-direct");
Response::Handle hResponse = hCacheServiceChannel->send(cast<Request::Handle>(hDestroyRequest))->waitForResponse(-1);
// the sleep was added to work around COH-4544
Thread::sleep(5000);
GetAllRequest::Handle hGetAllRequest = cast<GetAllRequest::Handle>(vNamedCacheFactory->createMessage(GetAllRequest::type_id));
ArrayList::Handle hNames = ArrayList::create();
hNames->add(convToBinary->convert(keys[1]));
hNames->add(convToBinary->convert(keys[2]));
hGetAllRequest->setKeySet(hNames);
try
{
hNamedCacheChannel->send(cast<Request::Handle>(hGetAllRequest))->waitForResponse(-1);
// should never reach here - no longer true, due to COH-8696
//TS_ASSERT(1 == 0);
}
catch(Exception::View ve)
{
TS_ASSERT(ve != NULL);
TS_ASSERT(instanceof<PortableException::View>(ve));
}
}
/**
* Test ContainsKeyRequest.
*/
void testContainsKeyRequest()
{
String::Handle key = "testContainsKeyKey";
String::Handle value = "testContainsKeyValue";
ClearRequest::Handle hClearRequest = cast<ClearRequest::Handle>(vNamedCacheFactory->createMessage(ClearRequest::type_id));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hClearRequest))->waitForResponse(-1);
TS_ASSERT(hResponse->isFailure() == false);
ContainsKeyRequest::Handle hContainsKeyRequest = cast<ContainsKeyRequest::Handle>(vNamedCacheFactory->createMessage(ContainsKeyRequest::type_id));
hContainsKeyRequest->setKey(convToBinary->convert(key));
Response::Handle hContainsKeyResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsKeyRequest))->waitForResponse(-1);
TS_ASSERT(hContainsKeyRequest->getTypeId() == ContainsKeyRequest::type_id);
TS_ASSERT(hContainsKeyResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hContainsKeyResponse));
TS_ASSERT(hContainsKeyResponse->isFailure() == false);
TS_ASSERT(hContainsKeyRequest->getId() == hContainsKeyResponse->getRequestId());
TS_ASSERT(instanceof<Boolean::View>(hContainsKeyResponse->getResult()));
Boolean::View vBoolResult = cast<Boolean::View>(hContainsKeyResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(false)));
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value));
hNamedCacheChannel->request(cast<Request::Handle>(hPutRequest));
hContainsKeyRequest = cast<ContainsKeyRequest::Handle>(vNamedCacheFactory->createMessage(ContainsKeyRequest::type_id));
hContainsKeyRequest->setKey(convToBinary->convert(key));
hContainsKeyResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsKeyRequest))->waitForResponse(-1);
TS_ASSERT(hContainsKeyRequest->getTypeId() == ContainsKeyRequest::type_id);
TS_ASSERT(hContainsKeyResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hContainsKeyResponse));
TS_ASSERT(hContainsKeyResponse->isFailure() == false);
TS_ASSERT(hContainsKeyRequest->getId() == hContainsKeyResponse->getRequestId());
TS_ASSERT(instanceof<Boolean::View>(hContainsKeyResponse->getResult()));
vBoolResult = cast<Boolean::View>(hContainsKeyResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(true)));
}
/**
* Test ContainsValueRequest.
*/
void testContainsValueRequest()
{
String::Handle key = "testContainsValueKey";
String::Handle value = "testContainsValueValue";
ClearRequest::Handle hClearRequest = cast<ClearRequest::Handle>(vNamedCacheFactory->createMessage(ClearRequest::type_id));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hClearRequest))->waitForResponse(-1);
TS_ASSERT(hResponse->isFailure() == false);
ContainsValueRequest::Handle hContainsValueRequest = cast<ContainsValueRequest::Handle>(vNamedCacheFactory->createMessage(ContainsValueRequest::type_id));
hContainsValueRequest->setValue(convToBinary->convert(value));
Response::Handle hContainsValueResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsValueRequest))->waitForResponse(-1);
TS_ASSERT(hContainsValueRequest->getTypeId() == ContainsValueRequest::type_id);
TS_ASSERT(hContainsValueResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hContainsValueResponse));
TS_ASSERT(hContainsValueResponse->isFailure() == false);
TS_ASSERT(hContainsValueRequest->getId() == hContainsValueResponse->getRequestId());
TS_ASSERT(instanceof<Boolean::View>(hContainsValueResponse->getResult()));
Boolean::View vBoolResult = cast<Boolean::View>(hContainsValueResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(false)));
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value));
hNamedCacheChannel->request(cast<Request::Handle>(hPutRequest));
hContainsValueRequest = cast<ContainsValueRequest::Handle>(vNamedCacheFactory->createMessage(ContainsValueRequest::type_id));
hContainsValueRequest->setValue(convToBinary->convert(value));
hContainsValueResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsValueRequest))->waitForResponse(-1);
TS_ASSERT(hContainsValueRequest->getTypeId() == ContainsValueRequest::type_id);
TS_ASSERT(hContainsValueResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hContainsValueResponse));
TS_ASSERT(hContainsValueResponse->isFailure() == false);
TS_ASSERT(hContainsValueRequest->getId() == hContainsValueResponse->getRequestId());
TS_ASSERT(instanceof<Boolean::View>(hContainsValueResponse->getResult()));
vBoolResult = cast<Boolean::View>(hContainsValueResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(true)));
}
/**
* Test RemoveRequest.
*/
void testRemoveRequest()
{
String::Handle key = "testRemoveKey";
String::Handle value = "testRemoveValue";
ClearRequest::Handle hClearRequest = cast<ClearRequest::Handle>(vNamedCacheFactory->createMessage(ClearRequest::type_id));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hClearRequest))->waitForResponse(-1);
TS_ASSERT(hResponse->isFailure() == false);
PutRequest::Handle hPutRequest = cast<PutRequest::Handle>(vNamedCacheFactory->createMessage(PutRequest::type_id));
hPutRequest->setKey(convToBinary->convert(key));
hPutRequest->setValue(convToBinary->convert(value));
hPutRequest->setReturnRequired(true);
Response::Handle hPutResponse = hNamedCacheChannel->send(cast<Request::Handle>(hPutRequest))->waitForResponse(-1);
TS_ASSERT(hPutResponse->isFailure() == false);
TS_ASSERT(convFromBinary->convert(hPutResponse->getResult()) == NULL);
ContainsKeyRequest::Handle hContainsKeyRequest = cast<ContainsKeyRequest::Handle>(vNamedCacheFactory->createMessage(ContainsKeyRequest::type_id));
hContainsKeyRequest->setKey(convToBinary->convert(key));
Response::Handle hContainsKeyResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsKeyRequest))->waitForResponse(-1);
TS_ASSERT(hContainsKeyResponse->isFailure() == false);
Boolean::View vBoolResult = cast<Boolean::View>(hContainsKeyResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(true)));
RemoveRequest::Handle hRemoveRequest = cast<RemoveRequest::Handle>(vNamedCacheFactory->createMessage(RemoveRequest::type_id));
hRemoveRequest->setKey(convToBinary->convert(key));
hRemoveRequest->setReturnRequired(true);
Response::Handle hRemoveResponse = hNamedCacheChannel->send(cast<Request::Handle>(hRemoveRequest))->waitForResponse(-1);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hRemoveResponse));
TS_ASSERT(hRemoveResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(hRemoveRequest->getId() == hRemoveResponse->getRequestId());
TS_ASSERT(hRemoveResponse->isFailure() == false);
if (hRemoveRequest->isReturnRequired() == true)
{
TS_ASSERT(hRemoveResponse->getResult()->equals(convToBinary->convert(value)));
}
hRemoveRequest = cast<RemoveRequest::Handle>(vNamedCacheFactory->createMessage(RemoveRequest::type_id));
OctetArrayWriteBuffer::Handle hBuf = OctetArrayWriteBuffer::create(1024);
WriteBuffer::BufferOutput::Handle hbout = hBuf->getBufferOutput();
Codec::Handle hCodec = PofCodec::create();
hRemoveRequest->setKey(convToBinary->convert(key));
hRemoveRequest->setReturnRequired(true);
hCodec->encode(hNamedCacheChannel, hRemoveRequest, hbout);
ReadBuffer::BufferInput::Handle hbin = hBuf->getReadBuffer()->getBufferInput();
RemoveRequest::Handle hRemoveResult = cast<RemoveRequest::Handle>(hCodec->decode(hNamedCacheChannel, hbin));
hRemoveRequest = cast<RemoveRequest::Handle>(vNamedCacheFactory->createMessage(RemoveRequest::type_id));
hRemoveRequest->setKey(convToBinary->convert(key));
hRemoveRequest->setReturnRequired(true);
TS_ASSERT(hRemoveRequest->isReturnRequired() == hRemoveResult->isReturnRequired());
TS_ASSERT(hRemoveRequest->getKey()->equals(hRemoveResult->getKey()));
TS_ASSERT(hRemoveRequest->getTypeId() == RemoveRequest::type_id);
hContainsKeyRequest = cast<ContainsKeyRequest::Handle>(vNamedCacheFactory->createMessage(ContainsKeyRequest::type_id));
hContainsKeyRequest->setKey(convToBinary->convert(key));
hContainsKeyResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsKeyRequest))->waitForResponse(-1);
TS_ASSERT(hContainsKeyResponse->isFailure() == false);
TS_ASSERT(instanceof<Boolean::View>(hContainsKeyResponse->getResult()));
vBoolResult = cast<Boolean::View>(hContainsKeyResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(false)));
}
/**
* Test ContainsAllRequest and RemoveAllRequest.
*/
void testContainsAllAndRemoveAllRequest()
{
ObjectArray::Handle keys = ObjectArray::create(3);
keys[0] = String::create("Goran Milosavljevic");
keys[1] = String::create("Ana Cikic");
keys[2] = String::create("Ivan Cikic");
ObjectArray::Handle values = ObjectArray::create(3);
values[0] = String::create("10.0.0.180");
values[1] = String::create("10.0.0.181");
values[2] = String::create("10.0.0.182");
HashMap::Handle addresses = HashMap::create();
addresses->put(convToBinary->convert(keys[0]), convToBinary->convert(values[0]));
addresses->put(convToBinary->convert(keys[1]), convToBinary->convert(values[1]));
addresses->put(convToBinary->convert(keys[2]), convToBinary->convert(values[2]));
ClearRequest::Handle hClearRequest = cast<ClearRequest::Handle>(vNamedCacheFactory->createMessage(ClearRequest::type_id));
Response::Handle hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hClearRequest))->waitForResponse(-1);
TS_ASSERT(hResponse->isFailure() == false);
PutAllRequest::Handle hPutAllRequest = cast<PutAllRequest::Handle>(vNamedCacheFactory->createMessage(PutAllRequest::type_id));
hPutAllRequest->setMap(addresses);
hResponse = hNamedCacheChannel->send(cast<Request::Handle>(hPutAllRequest))->waitForResponse(-1);
TS_ASSERT(hResponse->isFailure() == false);
ContainsAllRequest::Handle hContainsAllRequest = cast<ContainsAllRequest::Handle>(vNamedCacheFactory->createMessage(ContainsAllRequest::type_id));
ArrayList::Handle hList = ArrayList::create();
hList->add(convToBinary->convert(keys[0]));
hList->add(convToBinary->convert(keys[2]));
hList->add(convToBinary->convert(String::create("dummy")));
hContainsAllRequest->setKeySet(hList);
Response::Handle hContainsAllResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsAllRequest))->waitForResponse(-1);
TS_ASSERT(hContainsAllRequest->getTypeId() == ContainsAllRequest::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hContainsAllResponse));
TS_ASSERT(hContainsAllResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(hContainsAllRequest->getId() == hContainsAllResponse->getRequestId());
TS_ASSERT(hContainsAllResponse->isFailure() == false);
TS_ASSERT(instanceof<Boolean::View>(hContainsAllResponse->getResult()));
Boolean::View vBoolResult = cast<Boolean::View>(hContainsAllResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(false)));
hContainsAllRequest = cast<ContainsAllRequest::Handle>(vNamedCacheFactory->createMessage(ContainsAllRequest::type_id));
hList->remove(convToBinary->convert(String::create("dummy")));
hContainsAllRequest->setKeySet(hList);
hContainsAllResponse = hNamedCacheChannel->send(cast<Request::Handle>(hContainsAllRequest))->waitForResponse(-1);
TS_ASSERT(hContainsAllResponse->isFailure() == false);
TS_ASSERT(instanceof<Boolean::View>(hContainsAllResponse->getResult()));
vBoolResult = cast<Boolean::View>(hContainsAllResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(true)));
RemoveAllRequest::Handle hRemoveAllRequest = cast<RemoveAllRequest::Handle>(vNamedCacheFactory->createMessage(RemoveAllRequest::type_id));
hRemoveAllRequest->setKeySet(hList);
Response::Handle hRemoveAllResponse = hNamedCacheChannel->send(cast<Request::Handle>(hRemoveAllRequest))->waitForResponse(-1);
TS_ASSERT(hRemoveAllRequest->getTypeId() == RemoveAllRequest::type_id);
TS_ASSERT(instanceof<NamedCacheResponse::View>(hRemoveAllResponse));
TS_ASSERT(hRemoveAllResponse->getTypeId() == NamedCacheResponse::type_id);
TS_ASSERT(hRemoveAllRequest->getId() == hRemoveAllResponse->getRequestId());
TS_ASSERT(hRemoveAllResponse->isFailure() == false);
TS_ASSERT(instanceof<Boolean::View>(hRemoveAllResponse->getResult()));
vBoolResult = cast<Boolean::View>(hRemoveAllResponse->getResult());
TS_ASSERT(vBoolResult->equals(Boolean::create(true)));
}
};
| 58.019146 | 180 | 0.666201 | chpatel3 |
d238e6d49bc7b71f72fb3d7b87c9c04e438e9638 | 1,081 | cpp | C++ | graphs/bellman-ford.cpp | KaisatoK/icpc-notebook | a9afbb35e143376947a06bc21339b5eb6b664c99 | [
"MIT"
] | 46 | 2018-01-23T01:43:23.000Z | 2020-10-03T15:16:25.000Z | graphs/bellman-ford.cpp | KaisatoK/icpc-notebook | a9afbb35e143376947a06bc21339b5eb6b664c99 | [
"MIT"
] | 1 | 2019-08-02T16:29:03.000Z | 2020-03-16T22:36:11.000Z | graphs/bellman-ford.cpp | KaisatoK/icpc-notebook | a9afbb35e143376947a06bc21339b5eb6b664c99 | [
"MIT"
] | 16 | 2018-07-12T05:30:49.000Z | 2021-02-19T01:40:49.000Z | /**********************************************************************************
* BELLMAN-FORD ALGORITHM (SHORTEST PATH TO A VERTEX - WITH NEGATIVE COST) *
* Time complexity: O(VE) *
* Usage: dist[node] *
* Notation: m: number of edges *
* n: number of vertices *
* (a, b, w): edge between a and b with weight w *
* s: starting node *
**********************************************************************************/
const int N = 1e4+10; // Maximum number of nodes
vector<int> adj[N], adjw[N];
int dist[N], v, w;
memset(dist, 63, sizeof(dist));
dist[0] = 0;
for (int i = 0; i < n-1; ++i)
for (int u = 0; u < n; ++u)
for (int j = 0; j < adj[u].size(); ++j)
v = adj[u][j], w = adjw[u][j],
dist[v] = min(dist[v], dist[u]+w);
| 51.47619 | 83 | 0.307123 | KaisatoK |
d2396b70e556838a690e2550db916c0dbdfc0a04 | 235 | cxx | C++ | Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CTestTest/SmallAndFast/intentional_compile_warning.cxx | duonglvtnaist/Multi-ROMix-Scrypt-Accelerator | 9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8 | [
"MIT"
] | 107 | 2021-08-28T20:08:42.000Z | 2022-03-22T08:02:16.000Z | Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CTestTest/SmallAndFast/intentional_compile_warning.cxx | duonglvtnaist/Multi-ROMix-Scrypt-Accelerator | 9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8 | [
"MIT"
] | 3 | 2021-09-08T02:18:00.000Z | 2022-03-12T00:39:44.000Z | Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CTestTest/SmallAndFast/intentional_compile_warning.cxx | duonglvtnaist/Multi-ROMix-Scrypt-Accelerator | 9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8 | [
"MIT"
] | 16 | 2021-08-30T06:57:36.000Z | 2022-03-22T08:05:52.000Z | #include <stdio.h>
int main(int argc, const char* argv[])
{
unsigned int i =
0; // "i<argc" should produce a "signed/unsigned comparison" warning
for (; i < argc; ++i) {
fprintf(stdout, "%s\n", argv[i]);
}
return 0;
}
| 19.583333 | 72 | 0.591489 | duonglvtnaist |
d23b45102eb6c362ae2fd611a14c81f7945db8c8 | 2,798 | cc | C++ | squim/image/codecs/webp_decoder_test.cc | baranov1ch/squim | 5bde052735e0dac7c87e8f7939d0168e6ee05857 | [
"Apache-2.0"
] | 2 | 2016-05-06T01:15:49.000Z | 2016-05-06T01:29:00.000Z | squim/image/codecs/webp_decoder_test.cc | baranov1ch/squim | 5bde052735e0dac7c87e8f7939d0168e6ee05857 | [
"Apache-2.0"
] | null | null | null | squim/image/codecs/webp_decoder_test.cc | baranov1ch/squim | 5bde052735e0dac7c87e8f7939d0168e6ee05857 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 Alexey Baranov <[email protected]>. 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 "squim/image/codecs/webp_decoder.h"
#include <memory>
#include <vector>
#include "squim/base/logging.h"
#include "squim/base/memory/make_unique.h"
#include "squim/image/test/image_test_util.h"
#include "gtest/gtest.h"
namespace image {
namespace {
const char kWebPTestDir[] = "webp";
std::unique_ptr<ImageDecoder> CreateDecoder(
std::unique_ptr<io::BufReader> source) {
auto decoder = base::make_unique<WebPDecoder>(WebPDecoder::Params::Default(),
std::move(source));
return std::move(decoder);
}
} // namespace
class WebPDecoderTest : public testing::Test {
protected:
void ValidateWebPRandomReads(const std::string& filename,
size_t max_chunk_size,
ReadType read_type) {
std::vector<uint8_t> webp_data;
std::vector<uint8_t> png_data;
ASSERT_TRUE(ReadTestFile(kWebPTestDir, filename, "webp", &webp_data));
ASSERT_TRUE(ReadTestFile(kWebPTestDir, filename, "png", &png_data));
auto read_spec = GenerateFuzzyReads(webp_data.size(), max_chunk_size);
auto ref_reader = [&png_data, filename](ImageInfo* info,
ImageFrame* frame) -> bool {
return LoadReferencePng(filename, png_data, info, frame);
};
ValidateDecodeWithReadSpec(filename, webp_data, CreateDecoder, ref_reader,
read_spec, read_type);
}
void CheckInvalidRead(const std::string& filename) {
std::vector<uint8_t> data;
ASSERT_TRUE(ReadTestFileWithExt(kWebPTestDir, filename, &data));
auto source = base::make_unique<io::BufReader>(
base::make_unique<io::BufferedSource>());
source->source()->AddChunk(
base::make_unique<io::Chunk>(&data[0], data.size()));
source->source()->SendEof();
auto testee = base::make_unique<WebPDecoder>(WebPDecoder::Params::Default(),
std::move(source));
auto result = testee->Decode();
EXPECT_EQ(Result::Code::kDecodeError, result.code()) << filename;
}
};
TEST_F(WebPDecoderTest, ReadSuccessAll) {}
} // namespace image
| 35.417722 | 80 | 0.662974 | baranov1ch |
d23c7bd55965412a621c017d96b564190fa63b5e | 2,281 | cc | C++ | src/Board/Position.cc | rodrigowerberich/simple-terminal-chess | 73c62251c4d130a896270c1e27b297da3ab0933f | [
"MIT"
] | null | null | null | src/Board/Position.cc | rodrigowerberich/simple-terminal-chess | 73c62251c4d130a896270c1e27b297da3ab0933f | [
"MIT"
] | null | null | null | src/Board/Position.cc | rodrigowerberich/simple-terminal-chess | 73c62251c4d130a896270c1e27b297da3ab0933f | [
"MIT"
] | null | null | null | #include "Board/Position.hh"
#include <sstream>
std::ostream& operator<<(std::ostream& os, const Chess::Board::Position& position){
os << position.toString();
return os;
}
namespace Chess{
namespace Board{
std::string column_to_string(Column column){
switch (column){
case Chess::Board::Column::A :
return "A";
case Chess::Board::Column::B :
return "B";
case Chess::Board::Column::C :
return "C";
case Chess::Board::Column::D :
return "D";
case Chess::Board::Column::E :
return "E";
case Chess::Board::Column::F :
return "F";
case Chess::Board::Column::G :
return "G";
case Chess::Board::Column::H :
return "H";
default:
return "Invalid";
}
}
std::vector<Column> column_as_vector(){
return {Column::A, Column::B, Column::C, Column::D, Column::E, Column::F, Column::G, Column::H};
}
int column_to_int(Column column){
switch (column){
case Chess::Board::Column::A :
return 1;
case Chess::Board::Column::B :
return 2;
case Chess::Board::Column::C :
return 3;
case Chess::Board::Column::D :
return 4;
case Chess::Board::Column::E :
return 5;
case Chess::Board::Column::F :
return 6;
case Chess::Board::Column::G :
return 7;
case Chess::Board::Column::H :
return 8;
default:
return 0;
}
}
Chess::Board::Row Chess::Board::Position::row() const{
return m_row;
}
Chess::Board::Column Chess::Board::Position::column() const{
return m_column;
}
bool Chess::Board::Position::isValid() const{
return (m_row != Chess::Board::Position::INVALID_ROW_VALUE) && (m_column != Chess::Board::Column::Invalid);
}
std::string Chess::Board::Position::toString() const{
std::stringstream out;
if(!Chess::Board::Position::isValid()){
out << "Invalid";
}else{
out << column_to_string(m_column);
out << m_row;
}
return out.str();
}
bool Chess::Board::Position::operator==(const Chess::Board::Position& lhs) const{
return (m_row == lhs.m_row) && (m_column == lhs.m_column);
}
}
} // namespace Chess
| 24.265957 | 112 | 0.567295 | rodrigowerberich |
d23ed2fdcfeafde9b72b24cd691149e3469a48b4 | 3,294 | cpp | C++ | Core/Util.cpp | TomasSirgedas/HadwigerNelsonTiling | 2862ef41a2de229eccd9854f283e5424e188f47d | [
"Unlicense"
] | null | null | null | Core/Util.cpp | TomasSirgedas/HadwigerNelsonTiling | 2862ef41a2de229eccd9854f283e5424e188f47d | [
"Unlicense"
] | null | null | null | Core/Util.cpp | TomasSirgedas/HadwigerNelsonTiling | 2862ef41a2de229eccd9854f283e5424e188f47d | [
"Unlicense"
] | null | null | null | #include "Util.h"
#include <string>
int mod( int x, int m ) { return x >= 0 ? x % m : (x+1) % m + m-1; }
Matrix4x4 toMatrix( const XYZ& a, const XYZ& b, const XYZ& c )
{
return Matrix4x4( a.x, b.x, c.x, 0,
a.y, b.y, c.y, 0,
a.z, b.z, c.z, 0,
0, 0, 0 , 1 );
}
Matrix4x4 map( const std::vector<XYZ>& a, const std::vector<XYZ>& b )
{
if ( a.size() == 3 && b.size() == 3 )
return toMatrix( b[0], b[1], b[2] ) * toMatrix( a[0], a[1], a[2] ).inverted();
if ( a.size() == 4 && b.size() == 4 )
{
Matrix4x4 m = ::map( { a[1]-a[0], a[2]-a[0], a[3]-a[0] }, { b[1]-b[0], b[2]-b[0], b[3]-b[0] } );
return Matrix4x4::translation( b[0] ) * m * Matrix4x4::translation( -a[0] );
}
throw 777;
}
Icosahedron::Icosahedron()
{
const double PHI = .5 + sqrt(1.25);
v = { XYZ( -1, 0, -PHI )
, XYZ( 1, 0, -PHI )
, XYZ( 0, PHI, -1 )
, XYZ( -PHI, 1, 0 )
, XYZ( -PHI, -1, 0 )
, XYZ( 0, -PHI, -1 )
, XYZ( 1, 0, PHI )
, XYZ( -1, 0, PHI )
, XYZ( 0, -PHI, 1 )
, XYZ( PHI, -1, 0 )
, XYZ( PHI, 1, 0 )
, XYZ( 0, PHI, 1 ) };
for ( XYZ& p : v )
p = p.normalized();
}
Matrix4x4 Icosahedron::map( const std::vector<int>& a, const std::vector<int>& b ) const
{
return ::map( std::vector<XYZ> { v[a[0]], v[a[1]], v[a[2]] }, std::vector<XYZ> { v[b[0]], v[b[1]], v[b[2]] } );
}
uint64_t matrixHash( const Matrix4x4& m )
{
std::wstring str;
std::vector<double> v = { m[0].x, m[0].y, m[0].z, m[0].w
, m[1].x, m[1].y, m[1].z, m[1].w
, m[2].x, m[2].y, m[2].z, m[2].w
, m[3].x, m[3].y, m[3].z, m[3].w };
static_assert( sizeof(wchar_t) >= 2 );
for ( double x : v )
str += wchar_t( lround( x * 1000 ) );
uint64_t h = std::hash<std::wstring>{}( str );
return h;
}
// rotation matrix that rotates p to the Z-axis
Matrix4x4 matrixRotateToZAxis( XYZ& p )
{
XYZ newZ = p.normalized();
XYZ q = abs(newZ.z) < abs(newZ.y) ? XYZ(0,0,1) : XYZ(0,1,0);
XYZ newX = (newZ ^ q).normalized();
XYZ newY = (newZ ^ newX).normalized();
return Matrix4x4( toMatrix( newX, newY, newZ ) ).inverted();
}
XYZ operator*( const Matrix4x4& m, const XYZ& p )
{
return (m * XYZW( p )).toXYZ();
}
double signedArea( const std::vector<XYZ>& v )
{
if ( v.empty() )
return 0;
double area2 = v.back().x * v[0].y - v[0].x * v.back().y;
for ( int i = 0; i+1 < (int)v.size(); i++ )
area2 += v[i].x * v[i+1].y - v[i+1].x * v[i].y;
return area2 / 2;
}
XYZ centroid( const std::vector<XYZ>& v )
{
if ( v.empty() )
return XYZ();
double A = signedArea( v );
double sumX = (v.back().x + v[0].x) * (v.back().x * v[0].y - v[0].x * v.back().y);
double sumY = (v.back().y + v[0].y) * (v.back().x * v[0].y - v[0].x * v.back().y);
for ( int i = 0; i+1 < (int)v.size(); i++ )
{
sumX += (v[i].x + v[i+1].x) * (v[i].x * v[i+1].y - v[i+1].x * v[i].y);
sumY += (v[i].y + v[i+1].y) * (v[i].x * v[i+1].y - v[i+1].x * v[i].y);
}
return XYZ( sumX / (6*A), sumY / (6*A), 0 );
} | 28.643478 | 114 | 0.440194 | TomasSirgedas |
d24296884e72420dcd0a9c5a2b95e4b4b785e462 | 3,841 | cpp | C++ | lumino/LuminoEngine/src/UI/Controls/UIListBoxItem.cpp | LuminoEngine/Lumino | 370db149da12abbe1c01a3a42b6caf07ca4000fe | [
"MIT"
] | 113 | 2020-03-05T01:27:59.000Z | 2022-03-28T13:20:51.000Z | lumino/LuminoEngine/src/UI/Controls/UIListBoxItem.cpp | LuminoEngine/Lumino | 370db149da12abbe1c01a3a42b6caf07ca4000fe | [
"MIT"
] | 13 | 2020-03-23T20:36:44.000Z | 2022-02-28T11:07:32.000Z | lumino/LuminoEngine/src/UI/Controls/UIListBoxItem.cpp | LuminoEngine/Lumino | 370db149da12abbe1c01a3a42b6caf07ca4000fe | [
"MIT"
] | 12 | 2020-12-21T12:03:59.000Z | 2021-12-15T02:07:49.000Z |
#include "Internal.hpp"
#include <LuminoEngine/Reflection/VMProperty.hpp>
//#include <LuminoEngine/UI/UICommand.hpp>
#include <LuminoEngine/UI/UIStyle.hpp>
//#include <LuminoEngine/UI/Layout/UILayoutPanel.hpp>
#include <LuminoEngine/UI/UIText.hpp>
#include <LuminoEngine/UI/Controls/UIListBox.hpp>
#include <LuminoEngine/UI/Controls/UIListBoxItem.hpp>
namespace ln {
//==============================================================================
// UIListItem
LN_OBJECT_IMPLEMENT(UIListItem, UIControl) {}
UIListItem::UIListItem()
: m_ownerListControl(nullptr)
, m_onSubmit()
, m_isSelected(false)
{
m_objectManagementFlags.unset(detail::ObjectManagementFlags::AutoAddToPrimaryElement);
m_specialElementFlags.set(detail::UISpecialElementFlags::ListItem);
}
bool UIListItem::init()
{
if (!UIControl::init()) return false;
auto vsm = getVisualStateManager();
vsm->registerState(UIVisualStates::SelectionStates, UIVisualStates::Unselected);
vsm->registerState(UIVisualStates::SelectionStates, UIVisualStates::Selected);
vsm->gotoState(UIVisualStates::Unselected);
return true;
}
Ref<EventConnection> UIListItem::connectOnSubmit(Ref<UIGeneralEventHandler> handler)
{
return m_onSubmit.connect(handler);
}
void UIListItem::onSubmit()
{
m_onSubmit.raise(UIEventArgs::create(this, UIEvents::Submitted));
}
void UIListItem::onSelected(UIEventArgs* e)
{
}
void UIListItem::onUnselected(UIEventArgs* e)
{
}
void UIListItem::onRoutedEvent(UIEventArgs* e)
{
if (e->type() == UIEvents::MouseDownEvent) {
const auto* me = static_cast<const UIMouseEventArgs*>(e);
m_ownerListControl->notifyItemClicked(this, me->getClickCount());
e->handled = true;
return;
}
else if (e->type() == UIEvents::MouseMoveEvent) {
if (m_ownerListControl->submitMode() == UIListSubmitMode::Single) {
m_ownerListControl->selectItemExclusive(this);
e->handled = true;
return;
}
}
//if (e->type() == UIEvents::MouseEnterEvent) {
// if (m_ownerListControl->submitMode() == UIListSubmitMode::Single) {
// return;
// }
//}
//else if (e->type() == UIEvents::MouseLeaveEvent) {
// if (m_ownerListControl->submitMode() == UIListSubmitMode::Single) {
// return;
// }
//}
UIControl::onRoutedEvent(e);
}
void UIListItem::setSelectedInternal(bool selected)
{
if (m_isSelected != selected) {
m_isSelected = selected;
if (m_isSelected) {
onSelected(UIEventArgs::create(this, UIEvents::Selected));
getVisualStateManager()->gotoState(UIVisualStates::Selected);
}
else {
onUnselected(UIEventArgs::create(this, UIEvents::Selected));
getVisualStateManager()->gotoState(UIVisualStates::Unselected);
}
}
}
//==============================================================================
// UIListBoxItem
LN_OBJECT_IMPLEMENT(UIListBoxItem, UIListItem) {}
Ref<UIListBoxItem> UIListBoxItem::create(StringRef text)
{
return makeObject<UIListBoxItem>(text);
}
UIListBoxItem::UIListBoxItem()
{
}
bool UIListBoxItem::init()
{
if (!UIListItem::init()) return false;
return true;
}
bool UIListBoxItem::init(StringRef text)
{
if (!init()) return false;
addChild(makeObject<UIText>(text));
return true;
}
bool UIListBoxItem::init(UIElement* content)
{
if (!init()) return false;
addChild(content);
return true;
}
void UIListBoxItem::bind(ObservablePropertyBase* prop)
{
auto textblock = makeObject<UIText>();
auto viewProp = textblock->getViewProperty(_TT("text"));
viewProp->bind(prop);
addChild(textblock);
}
//==============================================================================
// UIListBox::BuilderDetails
void UIListBoxItem::BuilderDetails::apply(UIListBoxItem* p) const
{
UIListItem::BuilderDetails::apply(p);
if (!text.isEmpty()) {
auto textblock = makeObject<UIText>(text);
p->addChild(textblock);
}
if (onSubmit) p->connectOnSubmit(onSubmit);
}
} // namespace ln
| 23.857143 | 87 | 0.690706 | LuminoEngine |
d2447998d8c4adfaf82075610bd9930c7d8bc32e | 3,537 | cc | C++ | omaha/statsreport/persistent_iterator-win32_unittest.cc | r3yn0ld4/omaha | 05eeb606c433b7d0622dc95a10afd0c8d7af11b6 | [
"Apache-2.0"
] | 1,975 | 2015-07-03T07:00:50.000Z | 2022-03-31T20:04:04.000Z | omaha/statsreport/persistent_iterator-win32_unittest.cc | rodriguez74745/omaha | a244aea380b48fc488a0555c3fa51a2e03677557 | [
"Apache-2.0"
] | 277 | 2015-07-18T00:13:30.000Z | 2022-03-31T22:18:39.000Z | omaha/statsreport/persistent_iterator-win32_unittest.cc | rodriguez74745/omaha | a244aea380b48fc488a0555c3fa51a2e03677557 | [
"Apache-2.0"
] | 685 | 2015-07-18T11:24:49.000Z | 2022-03-30T20:50:12.000Z | // Copyright 2006-2009 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 <atlbase.h>
#include <atlcom.h>
#include <iterator>
#include <map>
#include "gtest/gtest.h"
#include "omaha/statsreport/aggregator-win32_unittest.h"
#include "omaha/statsreport/const-win32.h"
#include "omaha/statsreport/persistent_iterator-win32.h"
using namespace stats_report;
namespace {
class PersistentMetricsIteratorWin32Test: public MetricsAggregatorWin32Test {
public:
bool WriteStats() {
// put some persistent metrics into the registry
MetricsAggregatorWin32 agg(coll_, kAppName);
AddStats();
bool ret = agg.AggregateMetrics();
// Reset the stats, we should now have the same stats
// in our collection as in registry.
AddStats();
return ret;
}
typedef std::map<std::string, MetricBase*> MetricsMap;
void IndexMetrics(MetricsMap *metrics) {
// build a map over the metrics in our collection
MetricIterator it(coll_), end;
for (; it != end; ++it) {
metrics->insert(std::make_pair(std::string(it->name()), *it));
}
}
};
// compare two metrics instances for equality
bool equals(MetricBase *a, MetricBase *b) {
if (!a || !b)
return false;
if (a->type() != b->type() || 0 != strcmp(a->name(), b->name()))
return false;
switch (a->type()) {
case kCountType:
return a->AsCount().value() == b->AsCount().value();
break;
case kTimingType: {
TimingMetric &at = a->AsTiming();
TimingMetric &bt = b->AsTiming();
return at.count() == bt.count() &&
at.sum() == bt.sum() &&
at.minimum() == bt.minimum() &&
at.maximum() == bt.maximum();
}
break;
case kIntegerType:
return a->AsInteger().value() == b->AsInteger().value();
break;
case kBoolType:
return a->AsBool().value() == b->AsBool().value();
break;
case kInvalidType:
default:
LOG(FATAL) << "Impossible metric type";
}
return false;
}
} // namespace
TEST_F(PersistentMetricsIteratorWin32Test, Basic) {
EXPECT_TRUE(WriteStats());
PersistentMetricsIteratorWin32 a, b, c(kAppName);
EXPECT_TRUE(a == b);
EXPECT_TRUE(b == a);
EXPECT_FALSE(a == c);
EXPECT_FALSE(b == c);
EXPECT_FALSE(c == a);
EXPECT_FALSE(c == b);
++a;
EXPECT_TRUE(a == b);
EXPECT_TRUE(b == a);
}
// Test to see whether we can reliably roundtrip metrics through
// the registry without corruption.
TEST_F(PersistentMetricsIteratorWin32Test, WriteStats) {
EXPECT_TRUE(WriteStats());
MetricsMap metrics;
IndexMetrics(&metrics);
PersistentMetricsIteratorWin32 it(kAppName), end;
int count = 0;
for (; it != end; ++it) {
MetricsMap::iterator found = metrics.find(it->name());
// Make sure we found it, and that it's the correct value.
EXPECT_TRUE(found != metrics.end() && equals(found->second, *it));
count++;
}
// Did we visit all metrics?
EXPECT_EQ(count, metrics.size());
}
| 26.593985 | 77 | 0.647441 | r3yn0ld4 |
d24e223eaf1e320a86b4a4f1cdebc94b2e323aab | 5,338 | hpp | C++ | bryllite-core/bcp_server.hpp | bryllite/bcp-concept-prototype | 3ded79a85ee4c876fbbd0c1ee51680346874494e | [
"MIT"
] | null | null | null | bryllite-core/bcp_server.hpp | bryllite/bcp-concept-prototype | 3ded79a85ee4c876fbbd0c1ee51680346874494e | [
"MIT"
] | null | null | null | bryllite-core/bcp_server.hpp | bryllite/bcp-concept-prototype | 3ded79a85ee4c876fbbd0c1ee51680346874494e | [
"MIT"
] | null | null | null | #pragma once
// bcp callback interface
class IBcpServerCallback
{
public:
virtual size_t qualify_votes_count( void ) = 0;
virtual int onBcpNewRoundReady( size_t prevRoundIdx ) = 0;
virtual int onBcpNewRoundStart( size_t roundIdx ) = 0;
virtual int onBcpProposeStart( size_t roundIdx ) = 0;
virtual int onBcpVoteStart( size_t roundIdx ) = 0;
virtual int onBcpCommitStart( size_t roundIdx, CBlockHeader vote_header ) = 0;
virtual bool onBcpVerifyBlock( size_t roundIdx, CBlock verify_block ) = 0;
virtual int onBcpNewBlock( size_t roundIdx, CBlock newBlock ) = 0;
virtual int onBcpTimeout( size_t roundIdx ) = 0;
};
class CBcpServer;
// round storage
class CBcpData
{
friend class CBcpServer;
protected:
// lock objects of CBcpServer
bryllite::lockable& _lock;
// current block idx
size_t _round_idx;
// node candidate block
CBlock _candidate_block;
// user signed headers
std::map< std::string, CBlockHeader > _user_signed_headers;
CBlockHeader _lowest_user_signed_header;
// node proposed headers
std::map< int, CBlockHeader > _proposed_headers;
CBlockHeader _lowest_proposed_header;
// node voted headers
std::map< int, CBlockHeader > _votes_box;
std::map< uint256, CBlockHeader > _votes_headers;
std::map< uint256, size_t > _votes;
CBlockHeader _votes_qualified_header;
bool _votes_completed;
// verify block
CBlock _verify_block;
bool _verify_completed;
// node committed block
CBlock _commit_block;
std::map< int, CBlock > _committed_blocks;
std::map< int, CSecret > _committed_secrets;
bool _commit_completed;
public:
CBcpData( size_t roundIdx, bryllite::lockable& lock );
size_t round_idx( void );
// candidate block
void candidate_block( CBlock block );
CBlock& candidate_block( void );
// user signed header
bool append_user_signed_header( std::string user_address, CBlockHeader signed_header );
bool find_lowest_user_signed_header( CBlockHeader& lowest_header );
bool get_lowest_user_signed_header( CBlockHeader& lowest_header );
size_t get_participated_users( std::vector< std::string >& users );
// proposed header
bool append_proposed_header( int peer_id, CBlockHeader proposed_header );
bool find_lowest_proposed_header( CBlockHeader& lowest_header );
bool get_lowest_proposed_header( CBlockHeader& lowest_header );
// votes headers
bool append_votes_header( int peer_id, CBlockHeader votes_header );
bool find_qualified_votes_header( CBlockHeader& qualified_header, size_t qualify_count );
bool get_qualified_votes_header( CBlockHeader& qualified_header );
// commit block
bool append_commit_block( int peer_id, CBlock commit_block, CSecret commit_secret );
bool find_qualified_commit_block( CBlock& qualified_block, size_t qualify_count );
bool get_qualified_commit_block( CBlock& qualified_block );
// verify block
void verify_block( CBlock block );
CBlock& verify_block( void );
};
#if defined(_DEBUG) && 0
#define _USE_SHORT_BLOCK_TIME_
#endif
// BCP class
class CBcpServer : public ICallbackTimer
{
using callback_timer = bryllite::callback_timer;
// bcp timeout in ms
enum bcp_timeout
{
#ifdef _USE_SHORT_BLOCK_TIME_
bcp_timeout_proof_of_participation = 4000,
bcp_timeout_propose = 6000,
bcp_timeout_vote = 8000,
bcp_timeout_commit = 10000,
#else // _USE_SHORT_BLOCK_TIME_
bcp_timeout_proof_of_participation = 5000,
bcp_timeout_propose = 10000,
bcp_timeout_vote = 20000,
bcp_timeout_commit = 30000,
#endif
bcp_block_time = bcp_timeout_commit
};
protected:
// lock object of CNodeServer
bryllite::lockable& _lock;
// CBcpTimer ref
CBcpTimer& _bcp_timer;
// callback timer
callback_timer _callback_timer;
// BCP callback interface
IBcpServerCallback& _bcp_callback;
// time context
time_t _time_context;
// round idx
size_t _round_idx;
// new round messages
std::map< int, size_t > _new_round_messages;
std::map< size_t, size_t > _new_round_votes;
// < round, CBcpData >
std::map< size_t, std::unique_ptr< CBcpData > > _bcp_data;
public:
CBcpServer( IBcpServerCallback& bcp_callback, bryllite::lockable& lock, CBcpTimer& bcpTimer );
// start/stop bcp
bool start( void );
bool stop( void );
// update bcp
int update( void );
CBcpData* get_bcp_data( size_t round_idx );
CBcpData* get_bcp_data( void );
bool ready( void );
public:
time_t getTime( void );
// timeline in (ms)
time_t timeline( time_t& timeContext );
time_t timeline( void );
protected:
enum
{
timeout_proof_of_participation = 0,
timeout_propose,
timeout_vote,
timeout_commit
};
int onTimeOut(timer_id id, void* pContext) override;
void onTimeOutProofOfParticipation( void );
void onTimeOutPropose( void );
void onTimeOutVote( void );
void onTimeOutCommit( void );
void setTimeOutProofOfParticipation( void );
void setTimeOutPropose( void );
void setTimeOutVote( void );
void killTimeOutVote( void );
void setTimeOutCommit( void );
void killTimeOutCommit( void );
public:
// add new round message
bool new_round_vote( int peer_id, size_t round_idx );
// is new round vote qualified?
bool new_round_vote_qualified( size_t& round_idx );
bool onVote( int peer_id, size_t round_idx, CBlockHeader vote_header );
bool onVerify( int peer_id, size_t round_idx, CBlock verify_block );
bool onCommit( int peer_id, size_t round_idx, CBlock commit_block, CSecret secret );
};
| 25.54067 | 95 | 0.765268 | bryllite |
d251dbf8042beea6c819de0dc0bf008be59cd1fe | 502 | cpp | C++ | Source Code/Dynamics/Entities/Units/Vehicle.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | 9 | 2018-05-02T19:53:41.000Z | 2021-10-18T18:30:47.000Z | Source Code/Dynamics/Entities/Units/Vehicle.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | 7 | 2018-02-01T12:16:43.000Z | 2019-10-21T14:03:43.000Z | Source Code/Dynamics/Entities/Units/Vehicle.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | 1 | 2020-09-08T03:28:22.000Z | 2020-09-08T03:28:22.000Z | #include "stdafx.h"
#include "Headers/Vehicle.h"
namespace Divide {
Vehicle::Vehicle()
: Unit(UnitType::UNIT_TYPE_VEHICLE),
_vehicleTypeMask(0)
{
_playerControlled = false;
}
void Vehicle::setVehicleTypeMask(const U32 mask) {
assert((mask &
~(to_base(VehicleType::COUNT) - 1)) == 0);
_vehicleTypeMask = mask;
}
bool Vehicle::checkVehicleMask(const VehicleType type) const {
return (_vehicleTypeMask & to_U32(type)) != to_U32(type);
}
} | 20.916667 | 63 | 0.643426 | IonutCava |
d2524a730ed575f4317f425ea7d902dada5e6103 | 4,739 | cpp | C++ | src/framework/fastapi/BaseHttpRequestParams.cpp | AronProgram/pccl | d9f1c5ee3ed81d3195fab0765bb58cce1c97a91a | [
"MIT"
] | 3 | 2020-11-02T01:12:36.000Z | 2021-03-12T08:44:57.000Z | src/framework/fastapi/BaseHttpRequestParams.cpp | AronProgram/pccl | d9f1c5ee3ed81d3195fab0765bb58cce1c97a91a | [
"MIT"
] | null | null | null | src/framework/fastapi/BaseHttpRequestParams.cpp | AronProgram/pccl | d9f1c5ee3ed81d3195fab0765bb58cce1c97a91a | [
"MIT"
] | 1 | 2021-03-12T08:44:30.000Z | 2021-03-12T08:44:30.000Z | /**
* pccl is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 "BaseHttpRequestParams.h"
#include "util/tc_epoll_server.h"
#include "util/tc_common.h"
#include "util/tc_cgi.h"
#include "json.h"
#include "BaseHttpPlus.h"
#include "BaseRandom.h"
#include <algorithm>
namespace pccl
{
BaseHttpRequestParams::BaseHttpRequestParams(void) :
_bodyType(HTTP_BODY_NOTHING)
{
}
BaseHttpRequestParams::~BaseHttpRequestParams(void)
{
}
void BaseHttpRequestParams::setBuffer(std::vector<char>* inBuffer, std::vector<char>* outBuffer)
{
_inBuffer = inBuffer;
_outBuffer = outBuffer;
}
std::vector<char>& BaseHttpRequestParams::getOutBuffer(void)
{
return *_outBuffer;
}
void BaseHttpRequestParams::reset()
{
_bodyType = HTTP_BODY_NOTHING;
_sequence.clear();
_route.clear();
_params.clear();
_doc.clear();
tars::TC_HttpRequest::reset();
}
int BaseHttpRequestParams::parse(void)
{
int result = parseHttpPacket();
if ( pccl::STATE_SUCCESS != result )
{
return pccl::STATE_ERROR;
}
result = parseHttpBody();
// 构建染色ID,用于日志的数据链条的追踪
_sequence = BaseRandom::alpha(12);
// 获取HTTP路由
_route = this->getRequestUrl();
dump();
return result;
}
std::string& BaseHttpRequestParams::getSequence(void)
{
return _sequence;
}
int BaseHttpRequestParams::parseHttpPacket(void)
{
std::vector<char>& inBuffer = *_inBuffer;
TLOGDEBUG("parse http packet:" << std::string( (const char*) &inBuffer[0], inBuffer.size() ) << "\n" );
bool status = this->decode( (const char*) &inBuffer[0] , inBuffer.size() );
if ( !status )
{
TLOGERROR( "parse http packet error" << std::endl );
return pccl::STATE_ERROR;
}
//解析http query stirng 的参数
parseQueryHeader();
return pccl::STATE_SUCCESS;
}
int BaseHttpRequestParams::parseHttpBody(void)
{
_doc.clear();
std::string header = this->getHeader("Content-Type");
if ( header.find("application/json") )
{
parseJsonBody();
return pccl::STATE_SUCCESS;
}
parseQueryBody();
return pccl::STATE_SUCCESS;
}
int BaseHttpRequestParams::parseJsonBody(void)
{
// 解析body: json
std::string content = this->getContent();
Json::CharReaderBuilder builder;
const std::unique_ptr<Json::CharReader> reader( builder.newCharReader() );
JSONCPP_STRING err;
bool status = reader->parse(content.c_str(), content.c_str() + content.length() , &_doc, &err);
if ( status )
{
_bodyType = HTTP_BODY_JSON;
}
return pccl::STATE_SUCCESS;
}
void BaseHttpRequestParams::parseQueryHeader(void)
{
std::string request = getRequest();
split(request);
_bodyType = HTTP_BODY_QUERY;
}
void BaseHttpRequestParams::parseQueryBody(void)
{
std::string content = this->getContent();
split(content);
}
void BaseHttpRequestParams::split(const std::string& sQuery)
{
std::vector<std::string> query = tars::TC_Common::sepstr<std::string>(sQuery,"&");
for( std::size_t i = 0; i < query.size(); i++ )
{
{
std::vector<std::string> params;
params.clear();
params = tars::TC_Common::sepstr<std::string>(query[i],"=",true);
if ( 2 == params.size() )
{
_params[ params[0] ] = tars::TC_Cgi::decodeURL(params[1]);
}
}
}
}
const std::string& BaseHttpRequestParams::getRoute()
{
return _route;
}
void BaseHttpRequestParams::putParams(const std::string& sKey, const std::string& sValue )
{
_params[ sKey ] = sValue ;
}
std::string BaseHttpRequestParams::getRemoteIp(void)
{
//const http_header_type& header = getHeaders();
if ( !this->getHeader("X-real-ip").empty() )
{
return this->getHeader("X-real-ip");
}
else if ( !this->getHeader("X-Forwarded-For").empty() )
{
return this->getHeader("X-Forwarded-For");
}
else
{
return "127.0.0.1";
}
}
void BaseHttpRequestParams::dump(void)
{
dumpParams();
}
void BaseHttpRequestParams::dumpParams(void)
{
TLOGDEBUG( "dumpParams, " << _sequence << std::endl );
for( auto it = _params.begin(); it != _params.end(); it++ )
{
TLOGDEBUG( "dumpParams, " << _sequence << ", key:" <<it->first << ",value:" << it->second << std::endl);
}
}
}
| 18.226923 | 106 | 0.683689 | AronProgram |
d257626bef78f94d4cd9fbcdbdf1ed92003ef3b1 | 587 | cpp | C++ | CSES-Problemset/sorting and searching/ferris_wheel.cpp | rranjan14/cp-solutions | 9614508efbed1e4ee8b970b5eed535d782a5783f | [
"MIT"
] | null | null | null | CSES-Problemset/sorting and searching/ferris_wheel.cpp | rranjan14/cp-solutions | 9614508efbed1e4ee8b970b5eed535d782a5783f | [
"MIT"
] | null | null | null | CSES-Problemset/sorting and searching/ferris_wheel.cpp | rranjan14/cp-solutions | 9614508efbed1e4ee8b970b5eed535d782a5783f | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
#define vlli vector<long long int>
typedef long long int lli;
using namespace std;
int main()
{
lli n, x, count = 0;
cin >> n >> x;
vlli p(n, 0);
for (int i = 0; i < n; i++)
{
cin >> p[i];
}
sort(p.begin(), p.end());
lli i = 0, j = n - 1;
while (i <= j)
{
if (p[i] + p[j] <= x)
{
count++;
i++;
j--;
}
else
{
j--;
count++;
}
}
cout << count << "\n";
return 0;
} | 17.264706 | 34 | 0.383305 | rranjan14 |
d2576a85dc4d3b7319eb53f12d375a804d4fd722 | 539 | cpp | C++ | Grade_10/Second_Semester/max_sum_from_pairs.cpp | MagicWinnie/SESC_IT | 934ac49a177bfa5d02fc3234d31c929aad3c60c2 | [
"MIT"
] | 2 | 2020-10-10T10:21:49.000Z | 2021-05-28T18:10:42.000Z | Grade_10/Second_Semester/max_sum_from_pairs.cpp | MagicWinnie/SESC_IT | 934ac49a177bfa5d02fc3234d31c929aad3c60c2 | [
"MIT"
] | null | null | null | Grade_10/Second_Semester/max_sum_from_pairs.cpp | MagicWinnie/SESC_IT | 934ac49a177bfa5d02fc3234d31c929aad3c60c2 | [
"MIT"
] | null | null | null | // You get N pairs, from which you have to choose one number so the sum is max and does not divide by 3.
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int n;
int s = 0, mr = 1000000;
cin >> n;
for (int i = 0; i < n; i++)
{
int a, b;
cin >> a >> b;
s += (a > b) ? a : b;
if (abs(a - b) % 3 != 0 && abs(a - b) < mr)
mr = abs(a - b);
}
if (s % 3 != 0)
cout << s << endl;
else
cout << s - mr << endl;
}
| 20.730769 | 104 | 0.45269 | MagicWinnie |
d259aa34186e6601ee8e659cfc1d36c1f77b120b | 1,466 | cpp | C++ | Striver SDE Sheet/Day - 4 (Hashing)/2 Sum.cpp | HariAcidReign/Striver-SDE-Solutions | 80757b212abe479f3975b890398a8d877ebfd41e | [
"MIT"
] | 25 | 2021-08-17T04:04:41.000Z | 2022-03-16T07:43:30.000Z | Striver SDE Sheet/Day - 4 (Hashing)/2 Sum.cpp | hashwanthalla/Striver-Sheets-Resources | 80757b212abe479f3975b890398a8d877ebfd41e | [
"MIT"
] | null | null | null | Striver SDE Sheet/Day - 4 (Hashing)/2 Sum.cpp | hashwanthalla/Striver-Sheets-Resources | 80757b212abe479f3975b890398a8d877ebfd41e | [
"MIT"
] | 8 | 2021-08-18T02:02:23.000Z | 2022-02-11T06:05:07.000Z | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<pair<int, int>> x;
int n = nums.size();
for(int i = 0; i < n; i++)
{
x.push_back(make_pair(nums[i], i));
}
sort(x.begin(), x.end());
int l = 0;
int r = n-1;
vector<int> res;
while(l < r)
{
if(x[l].first + x[r].first == target)
{
res.push_back(x[l].second);
res.push_back(x[r].second);
break;
}
else if(x[l].first + x[r].first > target)
r--;
else
l++;
}
sort(res.begin(), res.end());
return res;
}
};
// Hari's
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<pair<int, int>> vec;
vector<int> res;
for(int i = 0; i<nums.size(); i++){
vec.push_back(make_pair(nums[i], i));
}
sort(vec.begin(), vec.end());
int p1 = 0, p2 = vec.size()-1;
while(p1 < p2){
if(vec[p1].first + vec[p2].first == target){
res.push_back(vec[p1].second);
res.push_back(vec[p2].second);
return res;
}
else if(vec[p1].first + vec[p2].first < target){
p1++;
}
else p2--;
}
return res;
}
};
| 25.719298 | 60 | 0.411323 | HariAcidReign |
d2603441ad6264eca71e2a001fd2adbb7d2acd0e | 2,077 | hpp | C++ | include/orwell/game/Robot.hpp | orwell-int/server-game | d3c410ff734a6f32de0303b25d816ae392df8a18 | [
"BSD-3-Clause"
] | null | null | null | include/orwell/game/Robot.hpp | orwell-int/server-game | d3c410ff734a6f32de0303b25d816ae392df8a18 | [
"BSD-3-Clause"
] | 39 | 2015-02-01T15:24:59.000Z | 2020-11-16T13:58:11.000Z | include/orwell/game/Robot.hpp | orwell-int/server-game | d3c410ff734a6f32de0303b25d816ae392df8a18 | [
"BSD-3-Clause"
] | 2 | 2015-03-14T13:05:25.000Z | 2015-07-05T07:11:23.000Z | /// This class stores the information about a robot that is connected to the server
#pragma once
#include <string>
#include <memory>
#include <zmq.hpp>
#include "orwell/com/Socket.hpp"
namespace orwell
{
namespace support
{
class ISystemProxy;
} // namespace support
namespace game
{
class Player;
class Item;
class Team;
class Robot
{
public:
static std::shared_ptr< Robot> MakeRobot(
support::ISystemProxy const & iSystemProxy,
std::string const & iName,
std::string const & iRobotId,
Team & ioTeam,
uint16_t const & iVideoRetransmissionPort,
uint16_t const & iServerCommandPort);
Robot(
support::ISystemProxy const & iSystemProxy,
std::string const & iName,
std::string const & iRobotId,
Team & ioTeam,
uint16_t const & iVideoRetransmissionPort,
uint16_t const & iServerCommandPort);
~Robot();
Team & getTeam();
Team const & getTeam() const;
void setHasRealRobot(bool const iHasRealRobot);
bool getHasRealRobot() const;
void setPlayer(std::shared_ptr< Player > const iPlayer);
std::shared_ptr< Player > getPlayer() const;
bool getHasPlayer() const;
void setVideoUrl(std::string const & iVideoUrl);
std::string const & getVideoUrl() const;
uint16_t getVideoRetransmissionPort() const;
uint16_t getServerCommandPort() const;
std::string const & getName() const;
std::string const & getRobotId() const;
bool getIsAvailable() const;
void fire();
void stop();
void readImage();
void startVideo();
// void fillRobotStateMessage( messages::RobotState & oMessage );
std::string getAsString() const;
private:
support::ISystemProxy const & m_systemProxy;
std::string m_name;
std::string m_robotId;
Team & m_team;
std::string m_videoUrl; //the origin URL of the videofeed
uint16_t m_videoRetransmissionPort; // the port on which the python server retransmits the video feed
uint16_t m_serverCommandPort; // the port used to give instructions to the retransmitter.
bool m_hasRealRobot;
std::weak_ptr< Player > m_player;
zmq::context_t m_zmqContext;
};
} // namespace game
} // namespace orwell
| 22.095745 | 102 | 0.738084 | orwell-int |
d2624a5b4bf7c04fe2e2e07abffde2795eaea4de | 12,518 | cpp | C++ | src/graph_page_file_io.cpp | mattvchandler/graph3 | f045b24a2657f4ad5628c8376cb7a54f1f1daf8e | [
"MIT"
] | null | null | null | src/graph_page_file_io.cpp | mattvchandler/graph3 | f045b24a2657f4ad5628c8376cb7a54f1f1daf8e | [
"MIT"
] | 1 | 2015-07-07T22:30:20.000Z | 2015-07-09T17:27:14.000Z | src/graph_page_file_io.cpp | mattvchandler/graph3 | f045b24a2657f4ad5628c8376cb7a54f1f1daf8e | [
"MIT"
] | null | null | null | // graph_page_file_io.cpp
// read and write graphs to disk
// Copyright 2018 Matthew Chandler
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <sstream>
#include <gtkmm/messagedialog.h>
#include <libconfig.h++>
#include "graph.hpp"
#include "graph_page.hpp"
// save graph to file
void Graph_page::save_graph(const std::string & filename)
{
// build the config file from widget properties
libconfig::Config cfg;
libconfig::Setting & cfg_root = cfg.getRoot().add("graph", libconfig::Setting::TypeGroup);
cfg_root.add("r_car", libconfig::Setting::TypeBoolean) = _r_car.get_active();
cfg_root.add("r_cyl", libconfig::Setting::TypeBoolean) = _r_cyl.get_active();
cfg_root.add("r_sph", libconfig::Setting::TypeBoolean) = _r_sph.get_active();
cfg_root.add("r_par", libconfig::Setting::TypeBoolean) = _r_par.get_active();
cfg_root.add("eqn", libconfig::Setting::TypeString) = _eqn.get_text();
cfg_root.add("eqn_par_y", libconfig::Setting::TypeString) = _eqn_par_y.get_text();
cfg_root.add("eqn_par_z", libconfig::Setting::TypeString) = _eqn_par_z.get_text();
cfg_root.add("row_min", libconfig::Setting::TypeString) = _row_min.get_text();
cfg_root.add("row_max", libconfig::Setting::TypeString) = _row_max.get_text();
cfg_root.add("col_min", libconfig::Setting::TypeString) = _col_min.get_text();
cfg_root.add("col_max", libconfig::Setting::TypeString) = _col_max.get_text();
cfg_root.add("row_res", libconfig::Setting::TypeInt) = _row_res.get_value_as_int();
cfg_root.add("col_res", libconfig::Setting::TypeInt) = _col_res.get_value_as_int();
cfg_root.add("draw", libconfig::Setting::TypeBoolean) = _draw.get_active();
cfg_root.add("transparent", libconfig::Setting::TypeBoolean) = _transparent.get_active();
cfg_root.add("draw_normals", libconfig::Setting::TypeBoolean) = _draw_normals.get_active();
cfg_root.add("draw_grid", libconfig::Setting::TypeBoolean) = _draw_grid.get_active();
cfg_root.add("use_color", libconfig::Setting::TypeBoolean) = _use_color.get_active();
cfg_root.add("use_tex", libconfig::Setting::TypeBoolean) = _use_tex.get_active();
libconfig::Setting & color = cfg_root.add("color", libconfig::Setting::TypeList);
color.add(libconfig::Setting::TypeFloat) = _color.r;
color.add(libconfig::Setting::TypeFloat) = _color.g;
color.add(libconfig::Setting::TypeFloat) = _color.b;
cfg_root.add("transparency", libconfig::Setting::TypeFloat) = _transparency.get_value();
cfg_root.add("tex_filename", libconfig::Setting::TypeString) = _tex_filename;
try
{
// write file
cfg.writeFile(filename.c_str());
}
catch(const libconfig::FileIOException & e)
{
// create an error message box
Gtk::MessageDialog error_dialog("Error writing to " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel()));
error_dialog.set_secondary_text(e.what());
error_dialog.set_title("Error");
error_dialog.run();
}
}
// read from a file
bool Graph_page::load_graph(const std::string & filename)
{
bool complete = true;
libconfig::Config cfg;
try
{
// open and parse file
cfg.readFile(filename.c_str());
libconfig::Setting & cfg_root = cfg.getRoot()["graph"];
// set properties - reqired settings
bool r_car = cfg_root["r_car"];
bool r_cyl = cfg_root["r_cyl"];
bool r_sph = cfg_root["r_sph"];
bool r_par = cfg_root["r_par"];
// one and only one should be set
if((int)r_car + (int)r_cyl + (int)r_sph + (int)r_par != 1)
{
// show error message box
Gtk::MessageDialog error_dialog("Error parsing " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel()));
error_dialog.set_secondary_text("Invalid combination of r_car, r_cyl, r_sph, r_par");
error_dialog.set_title("Error");
error_dialog.run();
return false;
}
_r_car.set_active(r_car);
_r_cyl.set_active(r_cyl);
_r_sph.set_active(r_sph);
_r_par.set_active(r_par);
bool use_color = cfg_root["use_color"];
bool use_tex = cfg_root["use_tex"];
// check for mutual exclusion
if((int)use_color + (int)use_tex != 1)
{
// show error message box
Gtk::MessageDialog error_dialog("Error parsing " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel()));
error_dialog.set_secondary_text("Invalid combination of use_color, use_tex");
error_dialog.set_title("Error");
error_dialog.run();
return false;
}
_use_color.set_active(use_color);
_use_tex.set_active(use_tex);
// non-required settings, but needed to draw graph
try { _eqn.set_text(static_cast<const char *>(cfg_root["eqn"])); }
catch(const libconfig::SettingNotFoundException) { complete = false; }
try { _eqn_par_y.set_text(static_cast<const char *>(cfg_root["eqn_par_y"])); }
catch(const libconfig::SettingNotFoundException)
{
if(r_par)
complete = false;
}
try { _eqn_par_z.set_text(static_cast<const char *>(cfg_root["eqn_par_z"])); }
catch(const libconfig::SettingNotFoundException)
{
if(r_par)
complete = false;
}
try { _row_min.set_text(static_cast<const char *>(cfg_root["row_min"])); }
catch(const libconfig::SettingNotFoundException) { complete = false; }
try { _row_max.set_text(static_cast<const char *>(cfg_root["row_max"])); }
catch(const libconfig::SettingNotFoundException) { complete = false; }
try { _col_min.set_text(static_cast<const char *>(cfg_root["col_min"])); }
catch(const libconfig::SettingNotFoundException) { complete = false; }
try { _col_max.set_text(static_cast<const char *>(cfg_root["col_max"])); }
catch(const libconfig::SettingNotFoundException) { complete = false; }
// non-required settings
try { _row_res.get_adjustment()->set_value(static_cast<int>(cfg_root["row_res"])); }
catch(const libconfig::SettingNotFoundException) {}
try { _col_res.get_adjustment()->set_value(static_cast<int>(cfg_root["col_res"])); }
catch(const libconfig::SettingNotFoundException) {}
try { _draw.set_active(static_cast<bool>(cfg_root["draw"])); }
catch(const libconfig::SettingNotFoundException) {}
try { _transparent.set_active(static_cast<bool>(cfg_root["transparent"])); }
catch(const libconfig::SettingNotFoundException) {}
try { _draw_normals.set_active(static_cast<bool>(cfg_root["draw_normals"])); }
catch(const libconfig::SettingNotFoundException) {}
try { _draw_grid.set_active(static_cast<bool>(cfg_root["draw_grid"])); }
catch(const libconfig::SettingNotFoundException) {}
try { _tex_filename = static_cast<const char *>(cfg_root["tex_filename"]); }
catch(const libconfig::SettingNotFoundException) {}
try
{
libconfig::Setting & color_l = cfg_root["color"];
// check for valid color (list of 3)
if(!color_l.isList() || color_l.getLength() != 3)
{
// show error message box
Gtk::MessageDialog error_dialog("Error parsing " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel()));
std::ostringstream msg;
msg<<"Invalid number of color elements (expected 3, got "<<color_l.getLength()<<")";
error_dialog.set_secondary_text(msg.str());
error_dialog.set_title("Error");
error_dialog.run();
return false;
}
_color.r = color_l[0];
_color.g = color_l[1];
_color.b = color_l[2];
}
catch(const libconfig::SettingNotFoundException) {}
try { _transparency.set_value(static_cast<float>(cfg_root["transparency"])); }
catch(const libconfig::SettingNotFoundException) {}
}
catch(const libconfig::FileIOException & e)
{
// show error message box
Gtk::MessageDialog error_dialog("Error reading from " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel()));
error_dialog.set_secondary_text(e.what());
error_dialog.set_title("Error");
error_dialog.run();
return false;
}
catch(const libconfig::ParseException & e)
{
// show error message box
Gtk::MessageDialog error_dialog("Error parsing " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel()));
std::ostringstream msg;
msg<<e.getError()<<" on line: "<<e.getLine();
error_dialog.set_secondary_text(msg.str());
error_dialog.set_title("Error");
error_dialog.run();
return false;
}
catch(const libconfig::SettingTypeException & e)
{
// show error message box
Gtk::MessageDialog error_dialog("Invalid setting type in" + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel()));
error_dialog.set_secondary_text(e.getPath());
error_dialog.set_title("Error");
error_dialog.run();
return false;
}
catch(const libconfig::SettingNotFoundException & e)
{
// show error message box
Gtk::MessageDialog error_dialog("Could not find setting in" + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel()));
error_dialog.set_secondary_text(e.getPath());
error_dialog.set_title("Error");
error_dialog.run();
return false;
}
// try to open the texture file
if(!_tex_filename.empty())
{
try
{
_tex_ico = Gdk::Pixbuf::create_from_file(_tex_filename)->scale_simple(32, 32, Gdk::InterpType::INTERP_BILINEAR);
}
catch(Glib::Exception &e)
{
_tex_ico.reset();
// show error message box
Gtk::MessageDialog error_dialog(e.what(), false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel()));
error_dialog.set_title("Error");
error_dialog.set_secondary_text("");
error_dialog.run();
}
}
// set color thumbnail
guint8 r = (guint8)(_color.r * 256.0f);
guint8 g = (guint8)(_color.g * 256.0f);
guint8 b = (guint8)(_color.b * 256.0f);
guint32 hex_color = r << 24 | g << 16 | b << 8;
_color_ico->fill(hex_color);
// set properties from widget values
change_type();
change_coloring();
if(complete)
apply();
return true;
}
| 41.866221 | 130 | 0.653219 | mattvchandler |
d920fbc87885ef55ac10520762b3c6e8c90f6d5f | 677 | cpp | C++ | tests/StdStats_test.cpp | syntaxonly/algs4-cpp | 3ca6336b77e72e0186dfa6ce23585f3bb34fc213 | [
"BSL-1.0"
] | null | null | null | tests/StdStats_test.cpp | syntaxonly/algs4-cpp | 3ca6336b77e72e0186dfa6ce23585f3bb34fc213 | [
"BSL-1.0"
] | null | null | null | tests/StdStats_test.cpp | syntaxonly/algs4-cpp | 3ca6336b77e72e0186dfa6ce23585f3bb34fc213 | [
"BSL-1.0"
] | null | null | null | #include "algs4/StdStats.h"
#include "algs4/StdArrayIO.h"
#include "algs4/StdOut.h"
// run by: StdStats_test < algs4-data/tinyDouble1D.txt
int main() {
using namespace algs4;
auto a = StdArrayIO::readDouble1D();
StdOut::printf(" min %10.3f\n", StdStats::min(a));
StdOut::printf(" mean %10.3f\n", StdStats::mean(a));
StdOut::printf(" max %10.3f\n", StdStats::max(a));
StdOut::printf(" stddev %10.3f\n", StdStats::stddev(a));
StdOut::printf(" var %10.3f\n", StdStats::var(a));
StdOut::printf(" stddevp %10.3f\n", StdStats::stddevp(a));
StdOut::printf(" varp %10.3f\n", StdStats::varp(a));
return 0;
}
| 30.772727 | 64 | 0.601182 | syntaxonly |
d933db0d014d82faf2211754bc4538aa50e6b432 | 7,231 | cpp | C++ | BreaksPPU/PPUSim/regs.cpp | ogamespec/breaknes | b053afb6924ca661f71a129766e8945f64f6ec7b | [
"CC0-1.0"
] | null | null | null | BreaksPPU/PPUSim/regs.cpp | ogamespec/breaknes | b053afb6924ca661f71a129766e8945f64f6ec7b | [
"CC0-1.0"
] | null | null | null | BreaksPPU/PPUSim/regs.cpp | ogamespec/breaknes | b053afb6924ca661f71a129766e8945f64f6ec7b | [
"CC0-1.0"
] | null | null | null | // Control Registers
#include "pch.h"
using namespace BaseLogic;
namespace PPUSim
{
ControlRegs::ControlRegs(PPU* parent)
{
ppu = parent;
}
ControlRegs::~ControlRegs()
{
}
void ControlRegs::sim()
{
sim_RegularRegOps();
sim_W56RegOps();
sim_FirstSecond_SCCX_Write();
sim_RegFFs();
if (ppu->rev == Revision::RP2C07_0)
{
sim_PalBLACK();
}
}
void ControlRegs::sim_RWDecoder()
{
TriState RnW = ppu->wire.RnW;
TriState n_DBE = ppu->wire.n_DBE;
ppu->wire.n_RD = NOT(NOR(NOT(RnW), n_DBE));
ppu->wire.n_WR = NOT(NOR(RnW, n_DBE));
}
void ControlRegs::sim_RegularRegOps()
{
TriState RS0 = ppu->wire.RS[0];
TriState RS1 = ppu->wire.RS[1];
TriState RS2 = ppu->wire.RS[2];
TriState RnW = ppu->wire.RnW;
TriState in2[4]{};
// Others
in2[0] = NOT(RS0);
in2[1] = NOT(RS1);
in2[2] = NOT(RS2);
in2[3] = NOT(RnW);
ppu->wire.n_R7 = NOT(NOR4(in2));
in2[0] = NOT(RS0);
in2[1] = NOT(RS1);
in2[2] = NOT(RS2);
in2[3] = RnW;
ppu->wire.n_W7 = NOT(NOR4(in2));
in2[0] = RS0;
in2[1] = RS1;
in2[2] = NOT(RS2);
in2[3] = RnW;
ppu->wire.n_W4 = NOT(NOR4(in2));
in2[0] = NOT(RS0);
in2[1] = NOT(RS1);
in2[2] = RS2;
in2[3] = RnW;
ppu->wire.n_W3 = NOT(NOR4(in2));
in2[0] = RS0;
in2[1] = NOT(RS1);
in2[2] = RS2;
in2[3] = NOT(RnW);
ppu->wire.n_R2 = NOT(NOR4(in2));
in2[0] = NOT(RS0);
in2[1] = RS1;
in2[2] = RS2;
in2[3] = RnW;
ppu->wire.n_W1 = NOT(NOR4(in2));
in2[0] = RS0;
in2[1] = RS1;
in2[2] = RS2;
in2[3] = RnW;
ppu->wire.n_W0 = NOT(NOR4(in2));
in2[0] = RS0;
in2[1] = RS1;
in2[2] = NOT(RS2);
in2[3] = NOT(RnW);
ppu->wire.n_R4 = NOT(NOR4(in2));
}
void ControlRegs::sim_W56RegOps()
{
TriState RS0 = ppu->wire.RS[0];
TriState RS1 = ppu->wire.RS[1];
TriState RS2 = ppu->wire.RS[2];
TriState RnW = ppu->wire.RnW;
TriState in[5]{};
TriState in2[4]{};
// SCCX
in[0] = RS0;
in[1] = NOT(RS1);
in[2] = NOT(RS2);
in[3] = get_Scnd();
in[4] = RnW;
ppu->wire.n_W6_1 = NOT(NOR5(in));
in[0] = RS0;
in[1] = NOT(RS1);
in[2] = NOT(RS2);
in[3] = get_Frst();
in[4] = RnW;
ppu->wire.n_W6_2 = NOT(NOR5(in));
in[0] = NOT(RS0);
in[1] = RS1;
in[2] = NOT(RS2);
in[3] = get_Scnd();
in[4] = RnW;
ppu->wire.n_W5_1 = NOT(NOR5(in));
in[0] = NOT(RS0);
in[1] = RS1;
in[2] = NOT(RS2);
in[3] = get_Frst();
in[4] = RnW;
ppu->wire.n_W5_2 = NOT(NOR5(in));
in2[0] = NOT(ppu->wire.n_W5_1);
in2[1] = NOT(ppu->wire.n_W5_2);
in2[2] = NOT(ppu->wire.n_W6_1);
in2[3] = NOT(ppu->wire.n_W6_2);
n_W56 = NOR4(in2);
}
void ControlRegs::sim_FirstSecond_SCCX_Write()
{
TriState RC = ppu->wire.RC;
TriState n_DBE = ppu->wire.n_DBE;
TriState n_R2 = ppu->wire.n_R2;
TriState R2_Enable = NOR(n_R2, n_DBE);
TriState W56_Enable = NOR(n_W56, n_DBE);
SCCX_FF1.set(NOR3(RC, R2_Enable, MUX(W56_Enable, NOT(SCCX_FF2.get()), NOT(SCCX_FF1.get()))));
SCCX_FF2.set(NOR3(RC, R2_Enable, MUX(W56_Enable, NOT(SCCX_FF2.get()), SCCX_FF1.get())));
}
void ControlRegs::sim_RegFFs()
{
TriState RC = ppu->wire.RC;
TriState n_W0 = ppu->wire.n_W0;
TriState n_W1 = ppu->wire.n_W1;
TriState n_DBE = ppu->wire.n_DBE;
TriState W0_Enable = NOR(n_W0, n_DBE);
TriState W1_Enable = NOR(n_W1, n_DBE);
for (size_t n = 0; n < 8; n++)
{
if (n >= 2)
{
// Bits 0 and 1 in the PAR Gen.
PPU_CTRL0[n].set(NOR(RC, NOT(MUX(W0_Enable, PPU_CTRL0[n].get(), ppu->GetDBBit(n)))));
}
PPU_CTRL1[n].set(NOR(RC, NOT(MUX(W1_Enable, PPU_CTRL1[n].get(), ppu->GetDBBit(n)))));
}
// CTRL0
i132_latch.set(PPU_CTRL0[2].get(), NOT(W0_Enable));
ppu->wire.I1_32 = NOT(i132_latch.nget());
obsel_latch.set(PPU_CTRL0[3].get(), NOT(W0_Enable));
ppu->wire.OBSEL = obsel_latch.nget();
bgsel_latch.set(PPU_CTRL0[4].get(), NOT(W0_Enable));
ppu->wire.BGSEL = bgsel_latch.nget();
o816_latch.set(PPU_CTRL0[5].get(), NOT(W0_Enable));
ppu->wire.O8_16 = NOT(o816_latch.nget());
ppu->wire.n_SLAVE = PPU_CTRL0[6].get();
ppu->wire.VBL = PPU_CTRL0[7].get();
// CTRL1
ppu->wire.BnW = PPU_CTRL1[0].get();
bgclip_latch.set(PPU_CTRL1[1].get(), NOT(W1_Enable));
ppu->wire.n_BGCLIP = ClippingAlwaysDisabled ? TriState::One : NOT(bgclip_latch.nget());
obclip_latch.set(PPU_CTRL1[2].get(), NOT(W1_Enable));
ppu->wire.n_OBCLIP = ClippingAlwaysDisabled ? TriState::One : NOT(obclip_latch.nget());
bge_latch.set(PPU_CTRL1[3].get(), NOT(W1_Enable));
obe_latch.set(PPU_CTRL1[4].get(), NOT(W1_Enable));
ppu->wire.BGE = RenderAlwaysEnabled ? TriState::One : bge_latch.get();
ppu->wire.OBE = RenderAlwaysEnabled ? TriState::One : obe_latch.get();
ppu->wire.BLACK = NOR(ppu->wire.BGE, ppu->wire.OBE);
tr_latch.set(PPU_CTRL1[5].get(), NOT(W1_Enable));
ppu->wire.n_TR = tr_latch.nget();
tg_latch.set(PPU_CTRL1[6].get(), NOT(W1_Enable));
ppu->wire.n_TG = tg_latch.nget();
ppu->wire.n_TB = NOT(PPU_CTRL1[7].get());
}
TriState ControlRegs::get_Frst()
{
return SCCX_FF1.nget();
}
TriState ControlRegs::get_Scnd()
{
return SCCX_FF1.get();
}
/// <summary>
/// The CLPB/CLPO signal acquisition simulation should be done after the FSM.
/// </summary>
void ControlRegs::sim_CLP()
{
TriState n_PCLK = ppu->wire.n_PCLK;
TriState n_VIS = ppu->fsm.nVIS;
TriState CLIP_B = ppu->fsm.CLIP_B;
TriState CLIP_O = ppu->fsm.CLIP_O;
TriState BGE = ppu->wire.BGE;
TriState OBE = ppu->wire.OBE;
nvis_latch.set(n_VIS, n_PCLK);
clipb_latch.set(CLIP_B, n_PCLK);
clipo_latch.set(NOR3(nvis_latch.get(), CLIP_O, NOT(OBE)), n_PCLK);
ppu->wire.n_CLPB = NOR3(nvis_latch.get(), clipb_latch.get(), NOT(BGE));
ppu->wire.CLPO = clipo_latch.nget();
}
void ControlRegs::Debug_RenderAlwaysEnabled(bool enable)
{
RenderAlwaysEnabled = enable;
}
void ControlRegs::Debug_ClippingAlwaysDisabled(bool enable)
{
ClippingAlwaysDisabled = enable;
}
uint8_t ControlRegs::Debug_GetCTRL0()
{
uint8_t val = 0;
for (size_t n = 0; n < 8; n++)
{
val |= (PPU_CTRL0[n].get() == TriState::One ? 1ULL : 0) << n;
}
return val;
}
uint8_t ControlRegs::Debug_GetCTRL1()
{
uint8_t val = 0;
for (size_t n = 0; n < 8; n++)
{
val |= (PPU_CTRL1[n].get() == TriState::One ? 1ULL : 0) << n;
}
return val;
}
void ControlRegs::Debug_SetCTRL0(uint8_t val)
{
for (size_t n = 0; n < 8; n++)
{
TriState bit_val = FromByte((val >> n) & 1);
PPU_CTRL0[n].set(bit_val);
}
}
void ControlRegs::Debug_SetCTRL1(uint8_t val)
{
for (size_t n = 0; n < 8; n++)
{
TriState bit_val = FromByte((val >> n) & 1);
PPU_CTRL1[n].set(bit_val);
}
}
/// <summary>
/// The `/SLAVE` signal is used for EXT input terminals.
/// </summary>
/// <returns></returns>
TriState ControlRegs::get_nSLAVE()
{
return PPU_CTRL0[6].get();
}
/// <summary>
/// Special BLACK signal processing for PAL PPU.
/// </summary>
void ControlRegs::sim_PalBLACK()
{
TriState PCLK = ppu->wire.PCLK;
TriState n_PCLK = ppu->wire.n_PCLK;
BLACK_FF1.set(MUX(PCLK, NOT(NOT(BLACK_FF1.get())), ppu->wire.BLACK));
BLACK_FF2.set(MUX(n_PCLK, NOT(NOT(BLACK_FF2.get())), NOT(NOT(BLACK_FF1.get()))));
black_latch1.set(NOT(NOT(BLACK_FF2.get())), PCLK);
black_latch2.set(black_latch1.nget(), n_PCLK);
ppu->wire.BLACK = black_latch2.nget();
}
}
| 22.045732 | 95 | 0.620661 | ogamespec |
d9351319abdb18af2bc0c496f50fbcf9278e44bf | 1,250 | cpp | C++ | 7FA4/1.5/Q1.5.5.3.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | 7FA4/1.5/Q1.5.5.3.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | 7FA4/1.5/Q1.5.5.3.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | // Q1.5.5.3. 多项式加减乘
// WzhDnwzWzh
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int f1[1001], f2[1001], ans[1000001], n1, n2, n_ans;
memset(f1, 0, sizeof(f1));
memset(f2, 0, sizeof(f2));
memset(ans, 0, sizeof(ans));
cin >> n1 >> n2;
for (int i = 0; i <= n1; i++)
cin >> f1[i];
for (int i = 0; i <= n2; i++)
cin >> f2[i];
n_ans = n1 < n2 ? n2 : n1;
for (int i = 0; i <= n_ans; i++)
ans[i] = f1[i] + f2[i];
while (ans[n_ans] == 0 && n_ans >= 1)
n_ans--;
for (int i = 0; i <= n_ans; i++)
cout << ans[i] << " ";
cout << endl;
memset(ans, 0, sizeof(ans));
n_ans = n1 < n2 ? n2 : n1;
for (int i = 0; i <= n_ans; i++)
ans[i] = f1[i] - f2[i];
while (ans[n_ans] == 0 && n_ans >= 1)
n_ans--;
for (int i = 0; i <= n_ans; i++)
cout << ans[i] << " ";
cout << endl;
memset(ans, 0, sizeof(ans));
n_ans = n1 * n2;
for (int i = 0; i <= n1; i++)
for (int j = 0; j <= n2; j++)
ans[i + j] += f1[i] * f2[j];
while (ans[n_ans] == 0 && n_ans >= 1)
n_ans--;
for (int i = 0; i <= n_ans; i++)
cout << ans[i] << " ";
cout << endl;
return 0;
} | 23.584906 | 56 | 0.4296 | XenonWZH |
d938202b9dd190c708538419786d7e89c49df397 | 408 | hpp | C++ | libs/core/math/include/bksge/core/math/fwd/transform3_fwd.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/math/include/bksge/core/math/fwd/transform3_fwd.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/math/include/bksge/core/math/fwd/transform3_fwd.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file transform3_fwd.hpp
*
* @brief Transform3 の前方宣言
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_MATH_FWD_TRANSFORM3_FWD_HPP
#define BKSGE_CORE_MATH_FWD_TRANSFORM3_FWD_HPP
namespace bksge
{
namespace math
{
template <typename T>
class Transform3;
} // namespace math
using math::Transform3;
} // namespace bksge
#endif // BKSGE_CORE_MATH_FWD_TRANSFORM3_FWD_HPP
| 14.571429 | 49 | 0.713235 | myoukaku |
d938e853764c02451212522187e630c3f405de86 | 5,042 | hpp | C++ | ql/termstructures/yield/compositezeroyieldstructure.hpp | zhengyuzhang1/QuantLib | 65867ab7c44419b69e40e553b41230744b83cff9 | [
"BSD-3-Clause"
] | 2 | 2021-12-12T01:27:45.000Z | 2022-01-25T17:44:12.000Z | ql/termstructures/yield/compositezeroyieldstructure.hpp | zhengyuzhang1/QuantLib | 65867ab7c44419b69e40e553b41230744b83cff9 | [
"BSD-3-Clause"
] | 17 | 2020-11-23T06:35:50.000Z | 2022-03-28T19:00:09.000Z | ql/termstructures/yield/compositezeroyieldstructure.hpp | zhengyuzhang1/QuantLib | 65867ab7c44419b69e40e553b41230744b83cff9 | [
"BSD-3-Clause"
] | 5 | 2020-06-04T15:19:22.000Z | 2020-06-18T08:24:37.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
Copyright (C) 2007, 2008 StatPro Italia srl
Copyright (C) 2017 Francois Botha
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<[email protected]>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file compositezeroyieldstructure.hpp
\brief Composite zero term structure
*/
#ifndef quantlib_composite_zero_yield_structure
#define quantlib_composite_zero_yield_structure
#include <ql/termstructures/yield/zeroyieldstructure.hpp>
namespace QuantLib {
template <class BinaryFunction>
class CompositeZeroYieldStructure : public ZeroYieldStructure {
public:
CompositeZeroYieldStructure(const Handle<YieldTermStructure>& h1,
const Handle<YieldTermStructure>& h2,
const BinaryFunction& f,
Compounding comp = Continuous,
Frequency freq = NoFrequency);
//! \name YieldTermStructure interface
//@{
DayCounter dayCounter() const;
Calendar calendar() const;
Natural settlementDays() const;
const Date& referenceDate() const;
Date maxDate() const;
Time maxTime() const;
//@}
//! \name Observer interface
//@{
void update();
//@}
protected:
//! returns the composite zero yield rate
Rate zeroYieldImpl(Time) const;
private:
Handle<YieldTermStructure> curve1_;
Handle<YieldTermStructure> curve2_;
BinaryFunction f_;
Compounding comp_;
Frequency freq_;
};
// inline definitions
template <class BinaryFunction>
inline CompositeZeroYieldStructure<BinaryFunction>::CompositeZeroYieldStructure(
const Handle<YieldTermStructure>& h1,
const Handle<YieldTermStructure>& h2,
const BinaryFunction& f,
Compounding comp,
Frequency freq)
: curve1_(h1), curve2_(h2), f_(f), comp_(comp), freq_(freq) {
if (!curve1_.empty() && !curve2_.empty())
enableExtrapolation(curve1_->allowsExtrapolation() && curve2_->allowsExtrapolation());
registerWith(curve1_);
registerWith(curve2_);
}
template <class BinaryFunction>
inline DayCounter CompositeZeroYieldStructure<BinaryFunction>::dayCounter() const {
return curve1_->dayCounter();
}
template <class BinaryFunction>
inline Calendar CompositeZeroYieldStructure<BinaryFunction>::calendar() const {
return curve1_->calendar();
}
template <class BinaryFunction>
inline Natural CompositeZeroYieldStructure<BinaryFunction>::settlementDays() const {
return curve1_->settlementDays();
}
template <class BinaryFunction>
inline const Date& CompositeZeroYieldStructure<BinaryFunction>::referenceDate() const {
return curve1_->referenceDate();
}
template <class BinaryFunction>
inline Date CompositeZeroYieldStructure<BinaryFunction>::maxDate() const {
return curve1_->maxDate();
}
template <class BinaryFunction>
inline Time CompositeZeroYieldStructure<BinaryFunction>::maxTime() const {
return curve1_->maxTime();
}
template <class BinaryFunction>
inline void CompositeZeroYieldStructure<BinaryFunction>::update() {
if (!curve1_.empty() && !curve2_.empty()) {
YieldTermStructure::update();
enableExtrapolation(curve1_->allowsExtrapolation() && curve2_->allowsExtrapolation());
}
else {
/* The implementation inherited from YieldTermStructure
asks for our reference date, which we don't have since
the original curve is still not set. Therefore, we skip
over that and just call the base-class behavior. */
TermStructure::update();
}
}
template <class BinaryFunction>
inline Rate CompositeZeroYieldStructure<BinaryFunction>::zeroYieldImpl(Time t) const {
Rate zeroRate1 =
curve1_->zeroRate(t, comp_, freq_, true);
InterestRate zeroRate2 =
curve2_->zeroRate(t, comp_, freq_, true);
InterestRate compositeRate(f_(zeroRate1, zeroRate2), dayCounter(), comp_, freq_);
return compositeRate.equivalentRate(Continuous, NoFrequency, t);
}
}
#endif
| 35.758865 | 98 | 0.664816 | zhengyuzhang1 |
d93d8e9c9fc4d497c5458a69578e22148aadd130 | 31 | hpp | C++ | src/boost_vmd_array.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_vmd_array.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_vmd_array.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/vmd/array.hpp>
| 15.5 | 30 | 0.741935 | miathedev |
d93da3ce769ea2a0b6bdebad8430307a6c9669c2 | 3,071 | cpp | C++ | opticalFlowApp1/src/ofApp.cpp | aa-debdeb/openFrameworks | c535eaa4a386879ef5db551357b29135b60520a0 | [
"MIT"
] | 1 | 2020-05-26T09:23:30.000Z | 2020-05-26T09:23:30.000Z | opticalFlowApp1/src/ofApp.cpp | aadebdeb/openFrameworks | c535eaa4a386879ef5db551357b29135b60520a0 | [
"MIT"
] | null | null | null | opticalFlowApp1/src/ofApp.cpp | aadebdeb/openFrameworks | c535eaa4a386879ef5db551357b29135b60520a0 | [
"MIT"
] | 2 | 2018-12-18T09:12:55.000Z | 2021-05-26T04:27:37.000Z | #include "ofApp.h"
using namespace ofxCv;
using namespace cv;
//--------------------------------------------------------------
void ofApp::setup(){
ofSetFrameRate(60);
camera.setup(320, 240);
gui.setup();
gui.add(fbPyrScale.set("fbPyrScale", .5, 0, .99));
gui.add(fbLevels.set("fbLevels", 4, 1, 8));
gui.add(fbIterations.set("fbIterations", 2, 1, 8));
gui.add(fbPolyN.set("fbPolyN", 7, 5, 10));
gui.add(fbPolySigma.set("fbPolySigma", 1.5, 1.1, 2));
gui.add(fbUseGaussian.set("fbUseGaussian", false));
gui.add(fbWinSize.set("winSize", 32, 4, 64));
particles = vector<Particle>();
for(int i = 0; i < 1000; i++){
particles.push_back(Particle());
}
}
//--------------------------------------------------------------
void ofApp::update(){
camera.update();
fbFlow.setPyramidScale(fbPyrScale);
fbFlow.setNumLevels(fbLevels);
fbFlow.setWindowSize(fbWinSize);
fbFlow.setNumIterations(fbIterations);
fbFlow.setPolyN(fbPolyN);
fbFlow.setPolySigma(fbPolySigma);
fbFlow.setUseGaussian(fbUseGaussian);
fbFlow.calcOpticalFlow(camera);
for(int i = 0; i < particles.size(); i++){
float adjustedX = particles[i].position.x * float(camera.getWidth()) / ofGetWidth();
float adjustedY = particles[i].position.y * float(camera.getHeight()) / ofGetHeight();
ofVec2f force = fbFlow.getFlowOffset(adjustedX, adjustedY) * 3;
particles[i].serForce(force);
particles[i].update();
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofSetColor(255);
camera.draw(0, 0, ofGetWidth(), ofGetHeight());
fbFlow.draw(0, 0, ofGetWidth(), ofGetHeight());
for(int i = 0; i < particles.size(); i++){
particles[i].draw();
}
gui.draw();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 26.474138 | 94 | 0.447086 | aa-debdeb |
d93f12f5799f74fddc5cea504535c8da95092caf | 712 | cpp | C++ | TimeTableGenerator/src/Colors.cpp | Electrux/CCPP-Code | 3c5e5b866cf050c11bced9651b112eb31dd2465d | [
"BSD-3-Clause"
] | 6 | 2019-08-29T23:31:17.000Z | 2021-11-14T20:35:47.000Z | TimeTableGenerator/src/Colors.cpp | Electrux/CCPP-Code | 3c5e5b866cf050c11bced9651b112eb31dd2465d | [
"BSD-3-Clause"
] | null | null | null | TimeTableGenerator/src/Colors.cpp | Electrux/CCPP-Code | 3c5e5b866cf050c11bced9651b112eb31dd2465d | [
"BSD-3-Clause"
] | 1 | 2019-09-01T12:22:58.000Z | 2019-09-01T12:22:58.000Z | #include <string>
#include <map>
#include "../include/Colors.hpp"
int SubstituteColors( std::string & str )
{
int len = 0;
std::string var;
for( std::string::iterator it = str.begin(); it != str.end(); ) {
if( * it == '{' && it + 1 != str.end() ) {
it = str.erase( it );
if( * it == '{' ) {
len++;
++it;
continue;
}
var = "";
while( it != str.end() && * it != '}' ) {
var += * it;
it = str.erase( it );
}
it = str.erase( it );
if( COLORS.find( var ) != COLORS.end() ) {
it = str.insert( it, COLORS[ var ].begin(), COLORS[ var ].end() );
it += COLORS[ var ].size();
}
continue;
}
len = * it == '\n' ? 0 : len + 1;
++it;
}
return len;
} | 18.25641 | 70 | 0.464888 | Electrux |
d949945e1d6bfbef9602f86e463bd04c8c5c2734 | 1,416 | cpp | C++ | tdutils/td/utils/port/detail/ThreadIdGuard.cpp | takpare/-T | 6c706f45e7a73c936b9f2f267785092c8a73348f | [
"BSL-1.0"
] | 1 | 2022-02-04T01:49:51.000Z | 2022-02-04T01:49:51.000Z | tdutils/td/utils/port/detail/ThreadIdGuard.cpp | shafiahmed/td | 19ef0361f9e4bf7e45e117f2fd12307629298d5e | [
"BSL-1.0"
] | null | null | null | tdutils/td/utils/port/detail/ThreadIdGuard.cpp | shafiahmed/td | 19ef0361f9e4bf7e45e117f2fd12307629298d5e | [
"BSL-1.0"
] | null | null | null | //
// Copyright Aliaksei Levin ([email protected]), Arseny Smirnov ([email protected]) 2014-2018
//
// 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)
//
#include "td/utils/port/detail/ThreadIdGuard.h"
#include "td/utils/logging.h"
#include "td/utils/port/thread_local.h"
#include <array>
#include <mutex>
namespace td {
namespace detail {
class ThreadIdManager {
public:
int32 register_thread() {
std::lock_guard<std::mutex> guard(mutex_);
for (size_t i = 0; i < is_id_used_.size(); i++) {
if (!is_id_used_[i]) {
is_id_used_[i] = true;
return static_cast<int32>(i + 1);
}
}
LOG(FATAL) << "Cannot create more than " << max_thread_count() << " threads";
return 0;
}
void unregister_thread(int32 thread_id) {
thread_id--;
std::lock_guard<std::mutex> guard(mutex_);
CHECK(is_id_used_.at(thread_id));
is_id_used_[thread_id] = false;
}
private:
std::mutex mutex_;
std::array<bool, max_thread_count()> is_id_used_{{false}};
};
static ThreadIdManager thread_id_manager;
ThreadIdGuard::ThreadIdGuard() {
thread_id_ = thread_id_manager.register_thread();
set_thread_id(thread_id_);
}
ThreadIdGuard::~ThreadIdGuard() {
thread_id_manager.unregister_thread(thread_id_);
set_thread_id(0);
}
} // namespace detail
} // namespace td
| 26.716981 | 96 | 0.695621 | takpare |
d951492eb5b7308620f090ddc66b4b3d40280e35 | 293 | hpp | C++ | WinSensor/Source/HRESULT_Support.hpp | SekiShuhei/ARWorkspace | 917089e29f5ea41336ffea4cd6f545bffb1f1c16 | [
"Apache-2.0"
] | null | null | null | WinSensor/Source/HRESULT_Support.hpp | SekiShuhei/ARWorkspace | 917089e29f5ea41336ffea4cd6f545bffb1f1c16 | [
"Apache-2.0"
] | 5 | 2020-04-17T10:08:29.000Z | 2020-04-26T07:17:18.000Z | WinSensor/Source/HRESULT_Support.hpp | SekiShuhei/ARWorkspace | 917089e29f5ea41336ffea4cd6f545bffb1f1c16 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "SensorManagerDefine.hpp"
namespace WinSensor {
class HRESULT_Support
{
public:
inline bool IsError() const
{
return FAILED(this->result);
}
inline HRESULT GetResult() const
{
return this->result;
}
protected:
HRESULT result = S_OK;
};
} | 13.952381 | 35 | 0.668942 | SekiShuhei |
d9534321c02648b59665b03a32e04b2229ab4343 | 2,955 | hpp | C++ | bbdata/prbs.hpp | kb3gtn/kb3gtn_sdr | 384c2ea7c778cd0ddbf355a705a19cbf08725d4e | [
"MIT"
] | null | null | null | bbdata/prbs.hpp | kb3gtn/kb3gtn_sdr | 384c2ea7c778cd0ddbf355a705a19cbf08725d4e | [
"MIT"
] | null | null | null | bbdata/prbs.hpp | kb3gtn/kb3gtn_sdr | 384c2ea7c778cd0ddbf355a705a19cbf08725d4e | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <vector>
#include <cstdint>
#include <cmath>
// PRBS patterns
enum prbs_pattern_t {
USER = 0,
ALL_ZEROS = 1,
ALL_ONES = 2,
ALT_ONE_ZERO = 3,
ITU_PN9 = 4,
ITU_PN11 = 5,
ITU_PN15 = 6,
ITU_PN23 = 7
};
// utility methods
int popcount64(uint64_t x);
uint8_t flipbitorder(uint8_t b);
uint64_t TAP(int bit_idx);
void PrintDataBuffer( std::vector<uint8_t> buffer );
void PrintDataBuffer( uint8_t *mem, int len );
// pattern table entry
struct pattern_table_entry_t {
int pattern_idx; // Index in table
uint64_t reg; // regsiter initial value
uint64_t reg_mask; // register active bit mask
uint64_t fb_mask; // register feedback bit mask
uint64_t reg_len_bits; // number of bits in active mask
char name[32]; // name of this pattern
};
// pre-defined patterns for this generator.
// user defined patters will require manual update to pattern_info_t data member
// in the Handle top setup register taps and length values..
const struct pattern_table_entry_t pattern_lookup_table[] = {
{USER, 0, 0, 0, 0, "user pattern"},
{ALL_ZEROS, 0, 0, 0, 1, "all zeros"},
{ALL_ONES, 1, 1, 1, 1, "all ones"},
{ALT_ONE_ZERO, 0x2, 0x3, 0x2, 2, "alt one zero" },
{ITU_PN9, 0x1FF, 0x1FF, TAP(9) | TAP(5), 9, "ITU PN9"},
{ITU_PN11, 0x7FF, 0x7FF, TAP(11) | TAP(9), 11, "ITU PN11"},
{ITU_PN15, 0x7FFF, 0x7FFF, TAP(15) | TAP(14), 15, "ITU PN15"},
{ITU_PN23, 0x7FFFFF, 0x7FFFFF, TAP(23) | TAP(18), 23, "ITU PN23"}
};
// data/state and function for PRBS pattern generation.
struct PRBSGEN {
// generate PRBS pattern to fill the buffer.
void generate( std::vector<uint8_t> *buffer );
void generate( uint8_t *buffer, int len );
// number of bits sent.
uint64_t bits_tx;
// register
uint64_t reg;
uint64_t reg_mask;
uint64_t fb_mask;
uint64_t reg_len_bits;
// constructors
// initialize from known pattern
PRBSGEN( prbs_pattern_t pat );
// initialize from specified parameters
PRBSGEN( uint64_t _reg, uint64_t _reg_mask, uint64_t _fb_mask, uint64_t _reg_len_bits );
};
// data/state and functions for PRBS pattern checking.
struct PRBSCHK {
// generate PRBS pattern to fill the buffer.
void check( std::vector<uint8_t> *buffer );
void check( uint8_t *buffer, int len );
// number of bits received.
// number of bits received.
uint64_t bits_rx;
uint64_t bits_rx_locked;
uint64_t bit_errors_detected;
uint64_t isLocked;
uint64_t sync_slips;
double getBER();
void reset_stats();
double __bit_match;
// register
uint64_t reg;
uint64_t reg_mask;
uint64_t fb_mask;
uint64_t reg_len_bits;
// constructors
// initialize from known pattern
PRBSCHK( prbs_pattern_t pat );
// initialize from specified parameters
PRBSCHK( uint64_t _reg, uint64_t _reg_mask, uint64_t _fb_mask, uint64_t _reg_len_bits );
};
| 29.257426 | 92 | 0.679188 | kb3gtn |
d9537b7a24ec7b4dbd1d631dd0d30ca6a7139118 | 1,163 | hpp | C++ | ares/sfc/coprocessor/competition/competition.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | ares/sfc/coprocessor/competition/competition.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | ares/sfc/coprocessor/competition/competition.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | //HLE of the NEC uPD78P214GC processor found on SNES-EVENT PCBs, used by:
//* Campus Challenge '92
//* PowerFest '94
//The NEC uPD78214 family are 8-bit microprocessors containing:
//* UART/CSI serial interface
//* ALU (MUL, DIV, BCD)
//* interrupts (12 internal; 7 external; 2 priority levels)
//* 16384 x 8-bit ROM
//* 512 x 8-bit RAM
//* 4 x timer/counters
//None of the SNES-EVENT games have had their uPD78214 firmware dumped.
//As such, our only option is very basic high-level emulation, provided here.
struct Competition : Thread {
//competition.cpp
auto main() -> void;
auto unload() -> void;
auto power() -> void;
auto mcuRead(n24 address, n8) -> n8;
auto mcuWrite(n24 address, n8) -> void;
auto read(n24 address, n8 data) -> n8;
auto write(n24 address, n8 data) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
public:
ReadableMemory rom[4];
enum class Board : u32 { Unknown, CampusChallenge92, PowerFest94 } board;
u32 timer;
private:
n8 status;
n8 select;
n1 timerActive;
n1 scoreActive;
u32 timerSecondsRemaining;
u32 scoreSecondsRemaining;
};
extern Competition competition;
| 23.734694 | 77 | 0.698194 | CasualPokePlayer |
d953a2cc6db36ee829db0d1e0b7f9d9fd9adaaa3 | 307 | hpp | C++ | libs/libwarhammerengine/model.hpp | julienlopez/QWarhammerSimulator | bd6f5b657dab36da0abdf14747434a1c9e9eaf20 | [
"MIT"
] | null | null | null | libs/libwarhammerengine/model.hpp | julienlopez/QWarhammerSimulator | bd6f5b657dab36da0abdf14747434a1c9e9eaf20 | [
"MIT"
] | 6 | 2021-01-07T07:38:46.000Z | 2021-07-13T16:43:35.000Z | libs/libwarhammerengine/model.hpp | julienlopez/QWarhammerSimulator | bd6f5b657dab36da0abdf14747434a1c9e9eaf20 | [
"MIT"
] | null | null | null | #pragma once
#include "characteristics.hpp"
#include "point.hpp"
#include <string>
namespace QWarhammerSimulator::LibWarhammerEngine
{
struct Model
{
std::string name;
LibGeometry::Point base_size;
Characteristics characteristics;
};
} // namespace QWarhammerSimulator::LibWarhammerEngine
| 15.35 | 54 | 0.762215 | julienlopez |
d9564bc29a2194995a78829e4d6319abb350a4c7 | 133 | cpp | C++ | contest/AtCoder/abc002/C.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | contest/AtCoder/abc002/C.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | contest/AtCoder/abc002/C.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "geometry/segment.hpp"
int main() {
Point a(in), b(in), c(in);
cout << (Segment(b - a, c - a)).area().abs() << endl;
}
| 19 | 55 | 0.541353 | not522 |
d957ce783bc07533b3b1a826a0fdd55463ac8b8a | 2,678 | hpp | C++ | gazebo_ros2_control_bolt/include/gazebo_ros2_control_bolt/gazebo_bolt_ros2_control_plugin.hpp | stack-of-tasks/ros2_control_bolt | 0be202ffffc7b22118db38d77a8d52e572dc4d13 | [
"Apache-2.0"
] | 5 | 2022-01-10T14:26:12.000Z | 2022-02-01T12:36:55.000Z | gazebo_ros2_control_bolt/include/gazebo_ros2_control_bolt/gazebo_bolt_ros2_control_plugin.hpp | stack-of-tasks/ros2_control_bolt | 0be202ffffc7b22118db38d77a8d52e572dc4d13 | [
"Apache-2.0"
] | 3 | 2022-01-15T14:44:45.000Z | 2022-02-01T05:54:13.000Z | gazebo_ros2_control_bolt/include/gazebo_ros2_control_bolt/gazebo_bolt_ros2_control_plugin.hpp | stack-of-tasks/ros2_control_bolt | 0be202ffffc7b22118db38d77a8d52e572dc4d13 | [
"Apache-2.0"
] | 3 | 2022-01-10T13:05:20.000Z | 2022-01-14T17:51:05.000Z | // Copyright (c) 2013, Open Source Robotics Foundation. All rights reserved.
// Copyright (c) 2013, The Johns Hopkins University. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the Open Source Robotics Foundation 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.
/* Author: Dave Coleman, Jonathan Bohren
Desc: Gazebo plugin for ros_control that allows 'hardware_interfaces' to be plugged in
using pluginlib
*/
#ifndef GAZEBO_ROS2_CONTROL__GAZEBO_ROS2_CONTROL_PLUGIN_HPP_
#define GAZEBO_ROS2_CONTROL__GAZEBO_ROS2_CONTROL_PLUGIN_HPP_
#include <memory>
#include <string>
#include <vector>
#include "controller_manager/controller_manager.hpp"
#include "gazebo/common/common.hh"
#include "gazebo/physics/Model.hh"
namespace gazebo_ros2_control_bolt
{
class GazeboRosControlPrivate;
class GazeboBoltRosControlPlugin : public gazebo::ModelPlugin
{
public:
GazeboBoltRosControlPlugin();
~GazeboBoltRosControlPlugin();
// Overloaded Gazebo entry point
void Load(gazebo::physics::ModelPtr parent, sdf::ElementPtr sdf) override;
private:
/// Private data pointer
std::unique_ptr<GazeboRosControlPrivate> impl_;
};
} // namespace gazebo_ros2_control
#endif // GAZEBO_ROS2_CONTROL__GAZEBO_ROS2_CONTROL_PLUGIN_HPP_
| 39.382353 | 91 | 0.775205 | stack-of-tasks |
d95c47b8c9dd490dbb4a6ad37778a670d2cbf32c | 2,658 | hxx | C++ | include/prevc/pipeline/AST/new.hxx | arazeiros/prevc | 378f045f57b2e1c9460ac1699951291ac055c078 | [
"MIT"
] | 3 | 2018-10-30T20:33:45.000Z | 2019-03-06T11:46:31.000Z | include/prevc/pipeline/AST/new.hxx | arazeiros/prevc | 378f045f57b2e1c9460ac1699951291ac055c078 | [
"MIT"
] | null | null | null | include/prevc/pipeline/AST/new.hxx | arazeiros/prevc | 378f045f57b2e1c9460ac1699951291ac055c078 | [
"MIT"
] | null | null | null |
#ifndef PREVC_PIPELINE_AST_NEW_HXX
#define PREVC_PIPELINE_AST_NEW_HXX
#include <prevc/pipeline/AST/expression.hxx>
#include <prevc/pipeline/AST/type.hxx>
namespace prevc
{
namespace pipeline
{
namespace AST
{
/**
* \brief Represent an new-expression in the AST.
* */
class New: public Expression
{
public:
/**
* \brief Create an AST new-expression at the specified location.
* \param pipeline The pipeline that owns this AST node.
* \param location The location of the expression in the source code.
* \param type The type of the new-allocation.
* */
New(Pipeline* pipeline, util::Location&& location, Type* type);
/**
* \brief Release the used resources.
* */
virtual ~New();
/**
* \brief Checks the semantics of the node.
* \param pipeline The pipeline of the node.
* */
virtual void check_semantics() override;
/**
* \brief Generate the IR code for this expression.
* \param builder The builder of the IR block containing this expression.
* \return The IR value representing this expression.
* */
virtual llvm::Value* generate_IR(llvm::IRBuilder<>* builder) override;
/**
* \brief Evaluate the expression as an integer (if possible).
* \return Returns the evaluated integer.
* */
virtual std::optional<std::int64_t> evaluate_as_integer() const noexcept override;
/**
* \brief Returns the semantic type of this expression.
* \return The semantic type of this expression.
*
* Before this method can be called, the call to `check_semantics()` have to be done.
* */
virtual const semantic_analysis::Type* get_semantic_type() override;
/**
* \brief Returns a string representation of this primitive type.
* \return The representation in JSON format.
* */
virtual util::String to_string() const noexcept override;
private:
/**
* \brief The type of the new-allocation.
* */
Type* type;
};
}
}
}
#endif
| 34.519481 | 101 | 0.501129 | arazeiros |
d95f42fba2d8cfeff48263ce830de7bf6ac7aa37 | 1,950 | cpp | C++ | LuoguCodes/P1589.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | LuoguCodes/P1589.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | LuoguCodes/P1589.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | // luogu-judger-enable-o2
#include <cmath>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <numeric>
#include <iomanip>
#include <iostream>
#include <algorithm>
#define fn "cover"
#define ll long long
#define int long long
#define pc(x) putchar(x)
#define fileIn freopen("testdata.in", "r", stdin)
#define fileOut freopen("testdata.out", "w", stdout)
#define rep(i, a, b) for (int i = (a); i <= (b); ++i)
#define per(i, a, b) for (int i = (a); i >= (b); --i)
#ifdef yyfLocal
#define dbg(x) std::clog << #x" = " << (x) << std::endl
#define logs(x) std::clog << (x) << std::endl
#else
#define dbg(x) 42
#define logs(x) 42
#endif
int read() {
int res = 0, flag = 1; char ch = getchar();
while (!isdigit(ch)) { if (ch == ';-';) flag = -1; ch = getchar(); }
while (isdigit(ch)) res = res * 10 + ch - 48, ch = getchar();
return res * flag;
}
void print(int x) {
if (x < 0) putchar(';-';), x = -x;
if (x > 9) print(x / 10);
putchar(x % 10 + 48);
}
struct Segment {
int l, r;
Segment() = default;
Segment(int l, int r) : l(l), r(r) {}
};
const int N = 100000 + 5;
Segment seg[N];
void solution() {
int n = read(), len = read();
rep(i, 1, n) seg[i].l = read(), seg[i].r = read();
std::sort(seg + 1, seg + n + 1, [](const Segment &s1, const Segment &s2) {
return s1.l < s2.l;
});
int tot = 0, cur = 0;
rep(i, 1, n) {
cur = std::max(cur, seg[i].l);
if (cur < seg[i].r) {
int a = seg[i].r - cur;
int b = a / len + static_cast<bool>(a % len);
cur += b * len;
tot += b;
}
}
print(tot), puts("");
}
signed main() {
#ifdef yyfLocal
fileIn;
//fileOut;
#else
#ifndef ONLINE_JUDGE
freopen(fn".in", "r", stdin);
freopen(fn".out", "w", stdout);
#endif
#endif
solution();
} | 23.214286 | 78 | 0.53641 | Anguei |
d9661b5f5ede8062fd17df72765419140b3ebbc0 | 2,202 | cpp | C++ | src/cpp/game_logic/player.cpp | Tomius/pyromaze | 7100f0ef6972b62829b2ad2dd7e7e88af697a5c2 | [
"MIT"
] | null | null | null | src/cpp/game_logic/player.cpp | Tomius/pyromaze | 7100f0ef6972b62829b2ad2dd7e7e88af697a5c2 | [
"MIT"
] | null | null | null | src/cpp/game_logic/player.cpp | Tomius/pyromaze | 7100f0ef6972b62829b2ad2dd7e7e88af697a5c2 | [
"MIT"
] | null | null | null | // Copyright (c) Tamas Csala
#include <lodepng.h>
#include <Silice3D/core/scene.hpp>
#include <Silice3D/core/game_engine.hpp>
#include <Silice3D/debug/debug_texture.hpp>
#include "game_logic/player.hpp"
#include "game_logic/dynamite.hpp"
#include "./main_scene.hpp"
void ShowYouDiedScreen(Silice3D::ShaderManager* shader_manager) {
unsigned width, height;
std::vector<unsigned char> data;
unsigned error = lodepng::decode(data, width, height, "src/resource/died.png", LCT_RGBA, 8);
if (error) {
std::cerr << "Image decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
throw std::runtime_error("Image decoder error");
}
gl::Texture2D texture;
gl::Bind(texture);
texture.upload(gl::kSrgb8Alpha8, width, height,
gl::kRgba, gl::kUnsignedByte, data.data());
texture.minFilter(gl::kLinear);
texture.magFilter(gl::kLinear);
gl::Unbind(texture);
Silice3D::DebugTexture{shader_manager}.Render(texture);
}
Player::Player(Silice3D::GameObject* parent)
: Silice3D::GameObject(parent)
{ }
void Player::KeyAction(int key, int scancode, int action, int mods) {
if (action == GLFW_PRESS) {
Silice3D::Transform dynamite_trafo;
if (key == GLFW_KEY_SPACE) {
glm::dvec3 pos = GetTransform().GetPos();
pos += 3.0 * GetTransform().GetForward();
dynamite_trafo.SetPos({pos.x, 0, pos.z});
GetScene()->AddComponent<Dynamite>(dynamite_trafo, 2.5 + 1.0*Silice3D::Math::Rand01());
} else if (key == GLFW_KEY_F1) {
for (int i = 0; i < 4; ++i) {
dynamite_trafo.SetPos({Silice3D::Math::Rand01()*256-128, 0, Silice3D::Math::Rand01()*256-128});
GetScene()->AddComponent<Dynamite>(dynamite_trafo, 2.5 + 1.0*Silice3D::Math::Rand01());
}
}
}
}
void Player::ReactToExplosion(const glm::dvec3& exp_position, double exp_radius) {
glm::dvec3 pos = GetTransform().GetPos();
pos.y = 0;
if (length(pos - exp_position) < 1.2*exp_radius) {
ShowYouDiedScreen(GetScene()->GetShaderManager());
glfwSwapBuffers(GetScene()->GetWindow());
Silice3D::GameEngine* engine = GetScene()->GetEngine();
engine->LoadScene(std::unique_ptr<Silice3D::Scene>{new MainScene{engine}});
}
}
| 34.40625 | 103 | 0.676658 | Tomius |
d96db87e22f59ed963625bee6b3581e9e22025a1 | 4,098 | cpp | C++ | src/mc.cpp | byrnedj/lsm-sim | ec45d2eb784357ee4c917cb3d4e3a10430886dae | [
"ISC"
] | 13 | 2017-02-05T09:41:57.000Z | 2022-02-13T14:38:28.000Z | src/mc.cpp | byrnedj/lsm-sim | ec45d2eb784357ee4c917cb3d4e3a10430886dae | [
"ISC"
] | 13 | 2016-03-17T17:43:58.000Z | 2017-01-11T09:21:45.000Z | src/mc.cpp | utah-scs/lsm-sim | 730e339cb4d5a719407643c8bb45a6c3dde1bfb8 | [
"0BSD"
] | 7 | 2017-01-03T18:11:08.000Z | 2021-03-09T12:30:12.000Z | #include <iostream>
#include <cinttypes>
#include <cstring>
#include <utility>
#include <stdio.h>
#include "mc.h"
static const int MAX_NUMBER_OF_SLAB_CLASSES = 64;
static const size_t POWER_SMALLEST = 1;
static const size_t POWER_LARGEST = 256;
static const size_t CHUNK_ALIGN_BYTES = 8;
static const size_t chunk_size = 48;
static const size_t item_size_max = 1024 * 1024;
typedef uint32_t rel_time_t;
typedef struct _stritem {
/* Protected by LRU locks */
struct _stritem *next;
struct _stritem *prev;
/* Rest are protected by an item lock */
struct _stritem *h_next; /* hash chain next */
rel_time_t time; /* least recent access */
rel_time_t exptime; /* expire time */
int nbytes; /* size of data */
unsigned short refcount;
uint8_t nsuffix; /* length of flags-and-length string */
uint8_t it_flags; /* ITEM_* above */
uint8_t slabs_clsid;/* which slab class we're in */
uint8_t nkey; /* key length, w/terminating null and padding */
/* this odd type prevents type-punning issues when we do
* the little shuffle to save space when not using CAS. */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
union {
uint64_t cas;
char end;
} data[];
#pragma GCC diagnostic pop
/* if it_flags & ITEM_CAS we have 8 bytes CAS */
/* then null-terminated key */
/* then " flags length\r\n" (no terminating null) */
/* then data with terminating \r\n (no terminating null; it's binary!) */
} item;
typedef struct {
unsigned int size; /* sizes of items */
unsigned int perslab; /* how many items per slab */
void *slots; /* list of item ptrs */
unsigned int sl_curr; /* total free items in list */
unsigned int slabs; /* how many slabs were allocated for this class */
void **slab_list; /* array of slab pointers */
unsigned int list_size; /* size of prev array */
size_t requested; /* The number of requested bytes */
} slabclass_t;
static slabclass_t slabclass[MAX_NUMBER_OF_SLAB_CLASSES];
static int power_largest;
/**
* Determines the chunk sizes and initializes the slab class descriptors
* accordingly.
*
*
* NOTE: Modified to return the max number of slabs
* (for sizing arrays elsewhere).
*/
uint16_t slabs_init(const double factor) {
int i = POWER_SMALLEST - 1;
// stutsman: original memcached code boost class size by
// at least sizeof(item) but since our simulator doesn't
// account for metadata this probably doesn't make sense?
unsigned int size = sizeof(item) + chunk_size;
//unsigned int size = chunk_size;
memset(slabclass, 0, sizeof(slabclass));
while (++i < MAX_NUMBER_OF_SLAB_CLASSES-1 &&
size <= item_size_max / factor) {
/* Make sure items are always n-byte aligned */
if (size % CHUNK_ALIGN_BYTES)
size += CHUNK_ALIGN_BYTES - (size % CHUNK_ALIGN_BYTES);
std::cout << "slab class " << i << " size " << size << std::endl;
slabclass[i].size = size;
slabclass[i].perslab = item_size_max / slabclass[i].size;
size *= factor;
}
power_largest = i;
slabclass[power_largest].size = item_size_max;
slabclass[power_largest].perslab = 1;
std::cout << "slab class " << i << " size " << item_size_max << std::endl;
return power_largest;
}
/*
* Figures out which slab class (chunk size) is required to store an item of
* a given size.
*
* Given object size, return id to use when allocating/freeing memory for object
* 0 means error: can't store such a large object
*
* NOTE: modified to return class id and class_size.
*/
std::pair<uint32_t, uint32_t> slabs_clsid(const size_t size) {
int res = POWER_SMALLEST;
if (size == 0)
return {0,0};
while (size > slabclass[res].size) {
++res;
if (res == power_largest) /* won't fit in the biggest slab */
return {0,0};
}
return {slabclass[res].size, res};
}
| 32.267717 | 80 | 0.641532 | byrnedj |
d9703f9c892af53cc55607571e8afe489bccd9a1 | 5,780 | cpp | C++ | src/TCPConnectionServer.cpp | sempr-tk/sempr-gui | ba96dca6945122a157f61fec9e41f4aa6060e3b2 | [
"BSD-3-Clause"
] | null | null | null | src/TCPConnectionServer.cpp | sempr-tk/sempr-gui | ba96dca6945122a157f61fec9e41f4aa6060e3b2 | [
"BSD-3-Clause"
] | null | null | null | src/TCPConnectionServer.cpp | sempr-tk/sempr-gui | ba96dca6945122a157f61fec9e41f4aa6060e3b2 | [
"BSD-3-Clause"
] | null | null | null | #include "TCPConnectionServer.hpp"
#include "ECDataZMQ.hpp"
#include "LogDataZMQ.hpp"
#include "TCPConnectionRequest.hpp"
#include <cereal/archives/json.hpp>
#include <iostream>
namespace sempr { namespace gui {
TCPConnectionServer::TCPConnectionServer(
DirectConnection::Ptr con,
const std::string& publishEndpoint,
const std::string& requestEndpoint)
:
updatePublisher_(context_, zmqpp::socket_type::publish),
replySocket_(context_, zmqpp::socket_type::reply),
semprConnection_(con),
handlingRequests_(false)
{
updatePublisher_.bind(publishEndpoint);
replySocket_.bind(requestEndpoint);
}
void TCPConnectionServer::updateCallback(
AbstractInterface::callback_t::first_argument_type data,
AbstractInterface::callback_t::second_argument_type action)
{
// construct the message -- just all the data entries in the ECData struct,
// plus the action.
zmqpp::message msg, topic;
msg << UpdateType::EntityComponent << data << action;
topic << "data";
// and send it to all subscribers
updatePublisher_.send("data", zmqpp::socket_t::send_more);
updatePublisher_.send(msg);
}
void TCPConnectionServer::tripleUpdateCallback(
AbstractInterface::triple_callback_t::first_argument_type value,
AbstractInterface::triple_callback_t::second_argument_type action)
{
std::cout << "TCPConnectionServer::tripleUpdateCallback" << std::endl;
zmqpp::message msg;
std::stringstream ss;
{
cereal::JSONOutputArchive ar(ss);
ar(value);
}
msg << UpdateType::Triple << ss.str() << action;
updatePublisher_.send("data", zmqpp::socket_t::send_more);
updatePublisher_.send(msg);
}
void TCPConnectionServer::loggingCallback(
AbstractInterface::logging_callback_t::argument_type log)
{
zmqpp::message msg;
msg << log;
updatePublisher_.send("logging", zmqpp::socket_t::send_more);
updatePublisher_.send(msg);
}
void TCPConnectionServer::start()
{
// connect the update callback
semprConnection_->setUpdateCallback(
std::bind(
&TCPConnectionServer::updateCallback,
this,
std::placeholders::_1,
std::placeholders::_2
)
);
semprConnection_->setTripleUpdateCallback(
std::bind(
&TCPConnectionServer::tripleUpdateCallback,
this,
std::placeholders::_1,
std::placeholders::_2
)
);
semprConnection_->setLoggingCallback(
std::bind(
&TCPConnectionServer::loggingCallback,
this,
std::placeholders::_1
)
);
// start a thread that handles requests
handlingRequests_ = true;
requestHandler_ = std::thread(
[this]()
{
while (handlingRequests_)
{
zmqpp::message msg;
bool requestAvailable = replySocket_.receive(msg, true);
if (requestAvailable)
{
TCPConnectionRequest request;
msg >> request;
TCPConnectionResponse response = handleRequest(request);
zmqpp::message responseMsg;
responseMsg << response;
replySocket_.send(responseMsg);
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
}
);
}
std::string TCPConnectionServer::getReteNetwork()
{
auto graph = semprConnection_->getReteNetworkRepresentation();
std::stringstream ss;
{
cereal::JSONOutputArchive ar(ss);
ar(graph);
}
return ss.str();
}
TCPConnectionResponse TCPConnectionServer::handleRequest(const TCPConnectionRequest& request)
{
TCPConnectionResponse response;
try {
// just map directly to the DirectConnection we use here.
switch(request.action) {
case TCPConnectionRequest::LIST_ALL_EC_PAIRS:
response.data = semprConnection_->listEntityComponentPairs();
break;
case TCPConnectionRequest::ADD_EC_PAIR:
semprConnection_->addEntityComponentPair(request.data);
break;
case TCPConnectionRequest::MODIFY_EC_PAIR:
semprConnection_->modifyEntityComponentPair(request.data);
break;
case TCPConnectionRequest::REMOVE_EC_PAIR:
semprConnection_->removeEntityComponentPair(request.data);
break;
case TCPConnectionRequest::GET_RETE_NETWORK:
response.reteNetwork = getReteNetwork();
break;
case TCPConnectionRequest::GET_RULES:
response.rules = semprConnection_->getRulesRepresentation();
break;
case TCPConnectionRequest::LIST_ALL_TRIPLES:
response.triples = semprConnection_->listTriples();
break;
case TCPConnectionRequest::GET_EXPLANATION_TRIPLE:
{
auto triple = std::make_shared<sempr::Triple>(request.toExplain);
response.explanationGraph = semprConnection_->getExplanation(triple);
break;
}
case TCPConnectionRequest::GET_EXPLANATION_ECWME:
response.explanationGraph = semprConnection_->getExplanation(request.data);
break;
}
response.success = true;
} catch (std::exception& e) {
// and in case of exceptions just notify the client
response.success = false;
response.msg = e.what();
}
return response;
}
}}
| 30.421053 | 93 | 0.614706 | sempr-tk |
d974bda0d23cdc3228d59dfe7ec6a65218961464 | 897 | cpp | C++ | source/PyMaterialX/PyMaterialXGenOsl/PyOslShaderGenerator.cpp | willmuto-lucasfilm/MaterialX | 589dbcb5ef292b5e5b64f30aa3fea442a8498ef6 | [
"BSD-3-Clause"
] | 973 | 2017-07-06T02:29:09.000Z | 2022-02-28T18:49:10.000Z | source/PyMaterialX/PyMaterialXGenOsl/PyOslShaderGenerator.cpp | willmuto-lucasfilm/MaterialX | 589dbcb5ef292b5e5b64f30aa3fea442a8498ef6 | [
"BSD-3-Clause"
] | 1,002 | 2018-01-09T10:33:07.000Z | 2022-03-31T18:35:04.000Z | source/PyMaterialX/PyMaterialXGenOsl/PyOslShaderGenerator.cpp | willmuto-lucasfilm/MaterialX | 589dbcb5ef292b5e5b64f30aa3fea442a8498ef6 | [
"BSD-3-Clause"
] | 305 | 2017-07-11T19:05:41.000Z | 2022-02-14T12:25:43.000Z | //
// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include <PyMaterialX/PyMaterialX.h>
#include <MaterialXGenOsl/OslShaderGenerator.h>
#include <MaterialXGenShader/GenContext.h>
#include <MaterialXGenShader/Shader.h>
#include <string>
namespace py = pybind11;
namespace mx = MaterialX;
void bindPyOslShaderGenerator(py::module& mod)
{
mod.attr("OSL_UNIFORMS") = mx::OSL::UNIFORMS;
mod.attr("OSL_INPUTS") = mx::OSL::INPUTS;
mod.attr("OSL_OUTPUTS") = mx::OSL::OUTPUTS;
py::class_<mx::OslShaderGenerator, mx::ShaderGenerator, mx::OslShaderGeneratorPtr>(mod, "OslShaderGenerator")
.def_static("create", &mx::OslShaderGenerator::create)
.def(py::init<>())
.def("getTarget", &mx::OslShaderGenerator::getTarget)
.def("generate", &mx::OslShaderGenerator::generate);
}
| 30.931034 | 113 | 0.7068 | willmuto-lucasfilm |
d97716c7906995a33c5fcfb3954329533f61c951 | 9,609 | cpp | C++ | lume/src/lume/grob.cpp | sreiter/lume | a321cbc35376684b711a8c54cd88eea7ce786d05 | [
"BSD-2-Clause"
] | 6 | 2018-09-11T12:05:55.000Z | 2021-11-27T11:56:33.000Z | lume/src/lume/grob.cpp | sreiter/lume | a321cbc35376684b711a8c54cd88eea7ce786d05 | [
"BSD-2-Clause"
] | 2 | 2019-10-06T21:05:15.000Z | 2019-10-08T09:09:30.000Z | lume/src/lume/grob.cpp | sreiter/lume | a321cbc35376684b711a8c54cd88eea7ce786d05 | [
"BSD-2-Clause"
] | 2 | 2018-12-25T00:57:17.000Z | 2019-10-06T21:05:39.000Z | // This file is part of lume, a C++ library for lightweight unstructured meshes
//
// Copyright (C) 2018, 2019 Sebastian Reiter
// Copyright (C) 2018 G-CSC, Goethe University Frankfurt
// Author: Sebastian Reiter <[email protected]>
// 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.
//
// 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 HOLDERS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <lume/grob.h>
namespace lume
{
ConstGrob::ConstGrob (GrobType grobType, index_t const* corners) :
m_globCornerInds (corners),
m_cornerOffsets (impl::Array_16_4::ascending_order ()),
m_desc (grobType)
{}
ConstGrob::ConstGrob (ConstGrob const& other)
: m_globCornerInds {other.m_globCornerInds}
, m_cornerOffsets {other.m_cornerOffsets}
, m_desc {other.m_desc}
{}
ConstGrob::ConstGrob (Grob const& other)
: m_globCornerInds {other.global_corner_array ()}
, m_cornerOffsets {other.corner_offsets ()}
, m_desc {other.desc ()}
{}
ConstGrob::ConstGrob (GrobType grobType, index_t const* globCornerInds, const impl::Array_16_4& cornerOffsets) :
m_globCornerInds (globCornerInds),
m_cornerOffsets (cornerOffsets),
m_desc (grobType)
{}
void ConstGrob::reset (Grob const& other)
{
reset (ConstGrob (other));
}
void ConstGrob::reset (ConstGrob const& other)
{
m_globCornerInds = other.m_globCornerInds;
m_cornerOffsets = other.m_cornerOffsets;
m_desc = other.m_desc;
}
void ConstGrob::set_global_corner_array (index_t const* cornerArray)
{
m_globCornerInds = cornerArray;
}
/// only compares corners, ignores order and orientation.
bool ConstGrob::operator == (const ConstGrob& g) const
{
if (m_desc.grob_type() != g.m_desc.grob_type())
return false;
CornerIndexContainer gCorners;
g.collect_corners (gCorners);
const index_t numCorners = num_corners ();
for(index_t i = 0; i < numCorners; ++i) {
bool gotOne = false;
const index_t c = corner(i);
for(index_t j = 0; j < numCorners; ++j) {
if(c == gCorners [j]){
gotOne = true;
break;
}
}
if (!gotOne)
return false;
}
return true;
}
bool ConstGrob::operator != (const ConstGrob& g) const
{
return !((*this) == g);
}
index_t ConstGrob::operator [] (const index_t i) const
{
return corner (i);
}
index_t ConstGrob::dim () const {return m_desc.dim ();}
GrobType ConstGrob::grob_type () const {return m_desc.grob_type ();}
GrobDesc ConstGrob::desc () const {return m_desc;}
index_t const* ConstGrob::global_corner_array () const
{
return m_globCornerInds;
}
index_t ConstGrob::num_corners () const {return m_desc.num_corners();}
/// returns the global index of the i-th corner
index_t ConstGrob::corner (const index_t i) const
{
assert (m_globCornerInds != nullptr);
return m_globCornerInds [m_cornerOffsets.get(i)];
}
/// collects the global indices of corners
/** \param cornersOut Array of size `Grob::max_num_corners(). Only the first
* `Grob::num_corners()` entries are filled
*
* \returns The number of corners of the specified side
*/
index_t ConstGrob::collect_corners (CornerIndexContainer& cornersOut) const
{
assert (m_globCornerInds != nullptr);
const index_t numCorners = num_corners();
for(index_t i = 0; i < numCorners; ++i)
cornersOut[i] = static_cast<index_t> (m_globCornerInds [m_cornerOffsets.get(i)]);
return numCorners;
}
index_t ConstGrob::num_sides (const index_t sideDim) const
{
return m_desc.num_sides(sideDim);
}
GrobDesc ConstGrob::side_desc (const index_t sideDim, const index_t sideIndex) const
{
return m_desc.side_desc (sideDim, sideIndex);
}
ConstGrob ConstGrob::side (const index_t sideDim, const index_t sideIndex) const
{
assert (m_globCornerInds != nullptr);
impl::Array_16_4 cornerOffsets;
const index_t numCorners = m_desc.side_desc(sideDim, sideIndex).num_corners();
const index_t* locCorners = m_desc.local_side_corners (sideDim, sideIndex);
// LOGT(side, "side " << sideIndex << "(dim: " << sideDim << ", num corners: " << numCorners << "): ");
for(index_t i = 0; i < numCorners; ++i){
// LOG(locCorners[i] << " ");
cornerOffsets.set (i, m_cornerOffsets.get(locCorners[i]));
}
// LOG("\n");
return ConstGrob (m_desc.side_type (sideDim, sideIndex), m_globCornerInds, cornerOffsets);
}
/// returns the index of the side which corresponds to the given grob
/** if no such side was found, 'lume::NO_INDEX' is returned.*/
index_t ConstGrob::find_side (const ConstGrob& sideGrob) const
{
const index_t sideDim = sideGrob.dim();
const index_t numSides = num_sides (sideDim);
for(index_t iside = 0; iside < numSides; ++iside) {
if (sideGrob == side (sideDim, iside))
return iside;
}
return NO_INDEX;
}
const impl::Array_16_4& ConstGrob::corner_offsets () const
{
return m_cornerOffsets;
}
Grob::Grob (GrobType grobType, index_t* corners)
: m_constGrob (grobType, corners)
{}
Grob::Grob (Grob const& other)
: m_constGrob (other)
{}
Grob::Grob (GrobType grobType, index_t* globCornerInds, const impl::Array_16_4& cornerOffsets)
: m_constGrob (grobType, globCornerInds, cornerOffsets)
{}
void Grob::reset (Grob const& other)
{
m_constGrob.reset (other);
}
void Grob::set_global_corner_array (index_t* cornerArray)
{
m_constGrob.set_global_corner_array (cornerArray);
}
Grob& Grob::operator = (Grob const& other)
{
return operator = (ConstGrob (other));
}
Grob& Grob::operator = (ConstGrob const& other)
{
assert (global_corner_array () != nullptr);
assert (other.global_corner_array () != nullptr);
assert (other.grob_type () == grob_type ());
assert (other.num_corners () == num_corners ());
index_t const numCorners = num_corners ();
for (index_t i = 0; i < numCorners; ++i)
{
set_corner (i, other [i]);
}
return *this;
}
/// only compares corners, ignores order and orientation.
bool Grob::operator == (const Grob& other) const
{
return m_constGrob == other;
}
bool Grob::operator == (const ConstGrob& other) const
{
return m_constGrob == other;
}
bool Grob::operator != (const Grob& other) const
{
return m_constGrob != other;
}
bool Grob::operator != (const ConstGrob& other) const
{
return m_constGrob != other;
}
index_t Grob::operator [] (const index_t i) const
{
return corner (i);
}
index_t Grob::dim () const
{
return m_constGrob.dim ();
}
GrobType Grob::grob_type () const
{
return m_constGrob.grob_type ();
}
GrobDesc Grob::desc () const
{
return m_constGrob.desc ();
}
index_t const* Grob::global_corner_array () const
{
return m_constGrob.global_corner_array ();
}
index_t* Grob::global_corner_array ()
{
return const_cast <index_t*> (m_constGrob.global_corner_array ());
}
index_t Grob::num_corners () const
{
return m_constGrob.num_corners ();
}
/// returns the global index of the i-th corner
index_t Grob::corner (const index_t i) const
{
return m_constGrob.corner (i);
}
/// sets the point index of the i-th corner
void Grob::set_corner (const index_t cornerIndex, const index_t pointIndex)
{
assert (global_corner_array () != nullptr);
assert (cornerIndex < num_corners ());
global_corner_array () [m_constGrob.corner_offsets ().get(cornerIndex)] = pointIndex;
}
/// collects the global indices of corners
/** \param cornersOut Array of size `Grob::max_num_corners(). Only the first
* `Grob::num_corners()` entries are filled
*
* \returns The number of corners of the specified side
*/
index_t Grob::collect_corners (CornerIndexContainer& cornersOut) const
{
return m_constGrob.collect_corners (cornersOut);
}
index_t Grob::num_sides (const index_t sideDim) const
{
return m_constGrob.num_sides(sideDim);
}
GrobDesc Grob::side_desc (const index_t sideDim, const index_t sideIndex) const
{
return m_constGrob.side_desc (sideDim, sideIndex);
}
Grob Grob::side (const index_t sideDim, const index_t sideIndex) const
{
auto const cgrob = m_constGrob.side (sideDim, sideIndex);
return Grob (cgrob.grob_type (),
const_cast <index_t*> (cgrob.global_corner_array ()),
cgrob.corner_offsets ());
}
/// returns the index of the side which corresponds to the given grob
/** if no such side was found, 'lume::NO_INDEX' is returned.*/
index_t Grob::find_side (const Grob& sideGrob) const
{
return m_constGrob.find_side (sideGrob);
}
const impl::Array_16_4& Grob::corner_offsets () const
{
return m_constGrob.corner_offsets ();
}
}// end of namespace
| 28.014577 | 112 | 0.714018 | sreiter |
d97808de077bc4a6e83f133391500728b8e77233 | 20,741 | cpp | C++ | binding/WebAssembly/applications/wFormats/wFormats.cpp | Fabrice-Praxinos/ULIS | 232ad5c0804da1202d8231fda67ff4aea70f57ef | [
"RSA-MD"
] | 30 | 2020-09-16T17:39:36.000Z | 2022-02-17T08:32:53.000Z | binding/WebAssembly/applications/wFormats/wFormats.cpp | Fabrice-Praxinos/ULIS | 232ad5c0804da1202d8231fda67ff4aea70f57ef | [
"RSA-MD"
] | 7 | 2020-11-23T14:37:15.000Z | 2022-01-17T11:35:32.000Z | binding/WebAssembly/applications/wFormats/wFormats.cpp | Fabrice-Praxinos/ULIS | 232ad5c0804da1202d8231fda67ff4aea70f57ef | [
"RSA-MD"
] | 5 | 2020-09-17T00:39:14.000Z | 2021-08-30T16:14:07.000Z | // IDDN FR.001.250001.004.S.X.2019.000.00000
/**
*
* ULIS
*__________________
*
* @file wFormats.cpp
* @author Clement Berthaud
* @brief Formats application for wasm ULIS.
* @copyright Copyright 2018-2021 Praxinos, Inc. All Rights Reserved.
* @license Please refer to LICENSE.md
*/
#include <ULIS>
using namespace ::ULIS;
int main() {
std::cout << "Format_G8 : " << Format_G8 << std::endl;
std::cout << "Format_GA8 : " << Format_GA8 << std::endl;
std::cout << "Format_AG8 : " << Format_AG8 << std::endl;
std::cout << "Format_G16 : " << Format_G16 << std::endl;
std::cout << "Format_GA16 : " << Format_GA16 << std::endl;
std::cout << "Format_AG16 : " << Format_AG16 << std::endl;
std::cout << "Format_GF : " << Format_GF << std::endl;
std::cout << "Format_GAF : " << Format_GAF << std::endl;
std::cout << "Format_AGF : " << Format_AGF << std::endl;
std::cout << "Format_RGB8 : " << Format_RGB8 << std::endl;
std::cout << "Format_BGR8 : " << Format_BGR8 << std::endl;
std::cout << "Format_RGBA8 : " << Format_RGBA8 << std::endl;
std::cout << "Format_ABGR8 : " << Format_ABGR8 << std::endl;
std::cout << "Format_ARGB8 : " << Format_ARGB8 << std::endl;
std::cout << "Format_BGRA8 : " << Format_BGRA8 << std::endl;
std::cout << "Format_RGB16 : " << Format_RGB16 << std::endl;
std::cout << "Format_BGR16 : " << Format_BGR16 << std::endl;
std::cout << "Format_RGBA16 : " << Format_RGBA16 << std::endl;
std::cout << "Format_ABGR16 : " << Format_ABGR16 << std::endl;
std::cout << "Format_ARGB16 : " << Format_ARGB16 << std::endl;
std::cout << "Format_BGRA16 : " << Format_BGRA16 << std::endl;
std::cout << "Format_RGBF : " << Format_RGBF << std::endl;
std::cout << "Format_BGRF : " << Format_BGRF << std::endl;
std::cout << "Format_RGBAF : " << Format_RGBAF << std::endl;
std::cout << "Format_ABGRF : " << Format_ABGRF << std::endl;
std::cout << "Format_ARGBF : " << Format_ARGBF << std::endl;
std::cout << "Format_BGRAF : " << Format_BGRAF << std::endl;
std::cout << "Format_HSV8 : " << Format_HSV8 << std::endl;
std::cout << "Format_VSH8 : " << Format_VSH8 << std::endl;
std::cout << "Format_HSVA8 : " << Format_HSVA8 << std::endl;
std::cout << "Format_AVSH8 : " << Format_AVSH8 << std::endl;
std::cout << "Format_AHSV8 : " << Format_AHSV8 << std::endl;
std::cout << "Format_VSHA8 : " << Format_VSHA8 << std::endl;
std::cout << "Format_HSV16 : " << Format_HSV16 << std::endl;
std::cout << "Format_VSH16 : " << Format_VSH16 << std::endl;
std::cout << "Format_HSVA16 : " << Format_HSVA16 << std::endl;
std::cout << "Format_AVSH16 : " << Format_AVSH16 << std::endl;
std::cout << "Format_AHSV16 : " << Format_AHSV16 << std::endl;
std::cout << "Format_VSHA16 : " << Format_VSHA16 << std::endl;
std::cout << "Format_HSVF : " << Format_HSVF << std::endl;
std::cout << "Format_VSHF : " << Format_VSHF << std::endl;
std::cout << "Format_HSVAF : " << Format_HSVAF << std::endl;
std::cout << "Format_AVSHF : " << Format_AVSHF << std::endl;
std::cout << "Format_AHSVF : " << Format_AHSVF << std::endl;
std::cout << "Format_VSHAF : " << Format_VSHAF << std::endl;
std::cout << "Format_HSL8 : " << Format_HSL8 << std::endl;
std::cout << "Format_LSH8 : " << Format_LSH8 << std::endl;
std::cout << "Format_HSLA8 : " << Format_HSLA8 << std::endl;
std::cout << "Format_ALSH8 : " << Format_ALSH8 << std::endl;
std::cout << "Format_AHSL8 : " << Format_AHSL8 << std::endl;
std::cout << "Format_LSHA8 : " << Format_LSHA8 << std::endl;
std::cout << "Format_HSL16 : " << Format_HSL16 << std::endl;
std::cout << "Format_LSH16 : " << Format_LSH16 << std::endl;
std::cout << "Format_HSLA16 : " << Format_HSLA16 << std::endl;
std::cout << "Format_ALSH16 : " << Format_ALSH16 << std::endl;
std::cout << "Format_AHSL16 : " << Format_AHSL16 << std::endl;
std::cout << "Format_LSHA16 : " << Format_LSHA16 << std::endl;
std::cout << "Format_HSLF : " << Format_HSLF << std::endl;
std::cout << "Format_LSHF : " << Format_LSHF << std::endl;
std::cout << "Format_HSLAF : " << Format_HSLAF << std::endl;
std::cout << "Format_ALSHF : " << Format_ALSHF << std::endl;
std::cout << "Format_AHSLF : " << Format_AHSLF << std::endl;
std::cout << "Format_LSHAF : " << Format_LSHAF << std::endl;
std::cout << "Format_CMY8 : " << Format_CMY8 << std::endl;
std::cout << "Format_YMC8 : " << Format_YMC8 << std::endl;
std::cout << "Format_CMYA8 : " << Format_CMYA8 << std::endl;
std::cout << "Format_AYMC8 : " << Format_AYMC8 << std::endl;
std::cout << "Format_ACMY8 : " << Format_ACMY8 << std::endl;
std::cout << "Format_YMCA8 : " << Format_YMCA8 << std::endl;
std::cout << "Format_CMY16 : " << Format_CMY16 << std::endl;
std::cout << "Format_YMC16 : " << Format_YMC16 << std::endl;
std::cout << "Format_CMYA16 : " << Format_CMYA16 << std::endl;
std::cout << "Format_AYMC16 : " << Format_AYMC16 << std::endl;
std::cout << "Format_ACMY16 : " << Format_ACMY16 << std::endl;
std::cout << "Format_YMCA16 : " << Format_YMCA16 << std::endl;
std::cout << "Format_CMYF : " << Format_CMYF << std::endl;
std::cout << "Format_YMCF : " << Format_YMCF << std::endl;
std::cout << "Format_CMYAF : " << Format_CMYAF << std::endl;
std::cout << "Format_AYMCF : " << Format_AYMCF << std::endl;
std::cout << "Format_ACMYF : " << Format_ACMYF << std::endl;
std::cout << "Format_YMCAF : " << Format_YMCAF << std::endl;
std::cout << "Format_CMYK8 : " << Format_CMYK8 << std::endl;
std::cout << "Format_KCMY8 : " << Format_KCMY8 << std::endl;
std::cout << "Format_KYMC8 : " << Format_KYMC8 << std::endl;
std::cout << "Format_YMCK8 : " << Format_YMCK8 << std::endl;
std::cout << "Format_CMYKA8 : " << Format_CMYKA8 << std::endl;
std::cout << "Format_ACMYK8 : " << Format_ACMYK8 << std::endl;
std::cout << "Format_AKYMC8 : " << Format_AKYMC8 << std::endl;
std::cout << "Format_KYMCA8 : " << Format_KYMCA8 << std::endl;
std::cout << "Format_CMYK16 : " << Format_CMYK16 << std::endl;
std::cout << "Format_KCMY16 : " << Format_KCMY16 << std::endl;
std::cout << "Format_KYMC16 : " << Format_KYMC16 << std::endl;
std::cout << "Format_YMCK16 : " << Format_YMCK16 << std::endl;
std::cout << "Format_CMYKA16 : " << Format_CMYKA16 << std::endl;
std::cout << "Format_ACMYK16 : " << Format_ACMYK16 << std::endl;
std::cout << "Format_AKYMC16 : " << Format_AKYMC16 << std::endl;
std::cout << "Format_KYMCA16 : " << Format_KYMCA16 << std::endl;
std::cout << "Format_CMYKF : " << Format_CMYKF << std::endl;
std::cout << "Format_KCMYF : " << Format_KCMYF << std::endl;
std::cout << "Format_KYMCF : " << Format_KYMCF << std::endl;
std::cout << "Format_YMCKF : " << Format_YMCKF << std::endl;
std::cout << "Format_CMYKAF : " << Format_CMYKAF << std::endl;
std::cout << "Format_ACMYKF : " << Format_ACMYKF << std::endl;
std::cout << "Format_AKYMCF : " << Format_AKYMCF << std::endl;
std::cout << "Format_KYMCAF : " << Format_KYMCAF << std::endl;
std::cout << "Format_YUV8 : " << Format_YUV8 << std::endl;
std::cout << "Format_VUY8 : " << Format_VUY8 << std::endl;
std::cout << "Format_YUVA8 : " << Format_YUVA8 << std::endl;
std::cout << "Format_AVUY8 : " << Format_AVUY8 << std::endl;
std::cout << "Format_AYUV8 : " << Format_AYUV8 << std::endl;
std::cout << "Format_VUYA8 : " << Format_VUYA8 << std::endl;
std::cout << "Format_YUV16 : " << Format_YUV16 << std::endl;
std::cout << "Format_VUY16 : " << Format_VUY16 << std::endl;
std::cout << "Format_YUVA16 : " << Format_YUVA16 << std::endl;
std::cout << "Format_AVUY16 : " << Format_AVUY16 << std::endl;
std::cout << "Format_AYUV16 : " << Format_AYUV16 << std::endl;
std::cout << "Format_VUYA16 : " << Format_VUYA16 << std::endl;
std::cout << "Format_YUVF : " << Format_YUVF << std::endl;
std::cout << "Format_VUYF : " << Format_VUYF << std::endl;
std::cout << "Format_YUVAF : " << Format_YUVAF << std::endl;
std::cout << "Format_AVUYF : " << Format_AVUYF << std::endl;
std::cout << "Format_AYUVF : " << Format_AYUVF << std::endl;
std::cout << "Format_VUYAF : " << Format_VUYAF << std::endl;
std::cout << "Format_Lab8 : " << Format_Lab8 << std::endl;
std::cout << "Format_baL8 : " << Format_baL8 << std::endl;
std::cout << "Format_LabA8 : " << Format_LabA8 << std::endl;
std::cout << "Format_AbaL8 : " << Format_AbaL8 << std::endl;
std::cout << "Format_ALab8 : " << Format_ALab8 << std::endl;
std::cout << "Format_baLA8 : " << Format_baLA8 << std::endl;
std::cout << "Format_Lab16 : " << Format_Lab16 << std::endl;
std::cout << "Format_baL16 : " << Format_baL16 << std::endl;
std::cout << "Format_LabA16 : " << Format_LabA16 << std::endl;
std::cout << "Format_AbaL16 : " << Format_AbaL16 << std::endl;
std::cout << "Format_ALab16 : " << Format_ALab16 << std::endl;
std::cout << "Format_baLA16 : " << Format_baLA16 << std::endl;
std::cout << "Format_LabF : " << Format_LabF << std::endl;
std::cout << "Format_baLF : " << Format_baLF << std::endl;
std::cout << "Format_LabAF : " << Format_LabAF << std::endl;
std::cout << "Format_AbaLF : " << Format_AbaLF << std::endl;
std::cout << "Format_ALabF : " << Format_ALabF << std::endl;
std::cout << "Format_baLAF : " << Format_baLAF << std::endl;
std::cout << "Format_XYZ8 : " << Format_XYZ8 << std::endl;
std::cout << "Format_ZYX8 : " << Format_ZYX8 << std::endl;
std::cout << "Format_XYZA8 : " << Format_XYZA8 << std::endl;
std::cout << "Format_AZYX8 : " << Format_AZYX8 << std::endl;
std::cout << "Format_AXYZ8 : " << Format_AXYZ8 << std::endl;
std::cout << "Format_ZYXA8 : " << Format_ZYXA8 << std::endl;
std::cout << "Format_XYZ16 : " << Format_XYZ16 << std::endl;
std::cout << "Format_ZYX16 : " << Format_ZYX16 << std::endl;
std::cout << "Format_XYZA16 : " << Format_XYZA16 << std::endl;
std::cout << "Format_AZYX16 : " << Format_AZYX16 << std::endl;
std::cout << "Format_AXYZ16 : " << Format_AXYZ16 << std::endl;
std::cout << "Format_ZYXA16 : " << Format_ZYXA16 << std::endl;
std::cout << "Format_XYZF : " << Format_XYZF << std::endl;
std::cout << "Format_ZYXF : " << Format_ZYXF << std::endl;
std::cout << "Format_XYZAF : " << Format_XYZAF << std::endl;
std::cout << "Format_AZYXF : " << Format_AZYXF << std::endl;
std::cout << "Format_AXYZF : " << Format_AXYZF << std::endl;
std::cout << "Format_ZYXAF : " << Format_ZYXAF << std::endl;
std::cout << "Format_Yxy8 : " << Format_Yxy8 << std::endl;
std::cout << "Format_yxY8 : " << Format_yxY8 << std::endl;
std::cout << "Format_YxyA8 : " << Format_YxyA8 << std::endl;
std::cout << "Format_AyxY8 : " << Format_AyxY8 << std::endl;
std::cout << "Format_AYxy8 : " << Format_AYxy8 << std::endl;
std::cout << "Format_yxYA8 : " << Format_yxYA8 << std::endl;
std::cout << "Format_Yxy16 : " << Format_Yxy16 << std::endl;
std::cout << "Format_yxY16 : " << Format_yxY16 << std::endl;
std::cout << "Format_YxyA16 : " << Format_YxyA16 << std::endl;
std::cout << "Format_AyxY16 : " << Format_AyxY16 << std::endl;
std::cout << "Format_AYxy16 : " << Format_AYxy16 << std::endl;
std::cout << "Format_yxYA16 : " << Format_yxYA16 << std::endl;
std::cout << "Format_YxyF : " << Format_YxyF << std::endl;
std::cout << "Format_yxYF : " << Format_yxYF << std::endl;
std::cout << "Format_YxyAF : " << Format_YxyAF << std::endl;
std::cout << "Format_AyxYF : " << Format_AyxYF << std::endl;
std::cout << "Format_AYxyF : " << Format_AYxyF << std::endl;
std::cout << "Format_yxYAF : " << Format_yxYAF << std::endl;
return 0;
}
| 104.752525 | 114 | 0.336532 | Fabrice-Praxinos |
d978ce34b2efaee9bf4b740929bdddf506aa29b3 | 7,366 | inl | C++ | volume/Unified2/src/Task/ElasticVolumeMesh/Distributed/DistributedElasticVolumeMeshCommon.inl | llmontoryxd/mipt_diploma | 7d7d65cd619fe983736773f95ebb50b470adbed2 | [
"MIT"
] | null | null | null | volume/Unified2/src/Task/ElasticVolumeMesh/Distributed/DistributedElasticVolumeMeshCommon.inl | llmontoryxd/mipt_diploma | 7d7d65cd619fe983736773f95ebb50b470adbed2 | [
"MIT"
] | null | null | null | volume/Unified2/src/Task/ElasticVolumeMesh/Distributed/DistributedElasticVolumeMeshCommon.inl | llmontoryxd/mipt_diploma | 7d7d65cd619fe983736773f95ebb50b470adbed2 | [
"MIT"
] | null | null | null | template<typename Space, typename FunctionSpace>
typename Space::IndexType
DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::GetSyncDataSize(IndexType dstDomainIndex) const
{
return syncDataSizes[dstDomainIndex];
}
template<typename Space, typename FunctionSpace>
void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::
RebuildTimeHierarchyLevels(IndexType globalStepIndex, bool allowCollisions)
{
volumeMesh.timeHierarchyLevelsManager.Initialize(
volumeMesh.cells.size(),
volumeMesh.GetHierarchyLevelsCount(),
volumeMesh.GetSolverPhasesCount(), false);
for (IndexType dstDomainIndex = 0; dstDomainIndex < domainsCount; ++dstDomainIndex)
{
for (IndexType cellNumber = 0; cellNumber < transitionInfos[dstDomainIndex].cells.size(); ++cellNumber)
{
IndexType cellIndex = volumeMesh.GetCellIndex(transitionInfos[dstDomainIndex].cells[cellNumber].incidentNodes);
volumeMesh.timeHierarchyLevelsManager.SetLevel(cellIndex, 0);
}
}
volumeMesh.RebuildTimeHierarchyLevels(globalStepIndex, allowCollisions, true);
}
template<typename Space, typename FunctionSpace>
bool DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::
IsSyncDataEmpty(IndexType dstDomainIndex) const
{
return transitionInfos[dstDomainIndex].nodesIndices.empty() ||
transitionInfos[dstDomainIndex].cells.empty() ||
transitionInfos[dstDomainIndex].transitionNodes.empty();
}
template<typename Space, typename FunctionSpace>
void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::SetTransitionInfo(
const std::vector< TransitionInfo<Space> >& transitionInfos)
{
this->transitionInfos = transitionInfos;
ComputeSyncDataSizes();
nodesDictionaries.resize(domainsCount);
for (IndexType dstDomainIndex = 0; dstDomainIndex < domainsCount; ++dstDomainIndex)
{
for (IndexType transitionNodeIndex = 0; transitionNodeIndex < transitionInfos[dstDomainIndex].transitionNodes.size(); ++transitionNodeIndex)
{
const typename TransitionInfo<Space>::TransitionNode& transitionNode = transitionInfos[dstDomainIndex].transitionNodes[transitionNodeIndex];
nodesDictionaries[dstDomainIndex][transitionNode.nativeIndex] = transitionNode.targetIndex;
}
}
}
template<typename Space, typename FunctionSpace>
typename DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::BytesHandled
DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::UpdateDomainData(const char* const data)
{
IndexType offset = 0;
// cells
IndexType cellsCount = *((IndexType*)data);
offset += sizeof(IndexType);
UpdateCellsData(cellsCount, (CellSyncData*)(data + offset));
offset += sizeof(CellSyncData) * cellsCount;
// nodes
IndexType nodesCount = *((IndexType*)(data + offset));
offset += sizeof(IndexType);
UpdateNodesData(nodesCount, (NodeSyncData*)(data + offset));
offset += sizeof(NodeSyncData) * nodesCount;
return offset;
}
template<typename Space, typename FunctionSpace>
typename DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::BytesHandled
DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::BuildSyncData(IndexType dstDomainIndex, char* const data)
{
*((IndexType*)data) = dstDomainIndex;
IndexType offset = sizeof(IndexType);
BuildCellsSyncData(dstDomainIndex, data + offset);
offset += sizeof(CellSyncData) * transitionInfos[dstDomainIndex].cells.size() + sizeof(IndexType);
if (sendNodesInfo)
{
BuildNodesSyncData(dstDomainIndex, data + offset);
offset += sizeof(NodeSyncData) * transitionInfos[dstDomainIndex].nodesIndices.size();
} else
{
*((IndexType*)(data + offset)) = 0;
}
offset += sizeof(IndexType);
return offset;
}
template<typename Space, typename FunctionSpace>
void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::UpdateCellsData(IndexType cellsCount, CellSyncData* const cellsData)
{
#pragma omp parallel for
for (int cellNumber = 0; cellNumber < (int)cellsCount; ++cellNumber)
{
CellSolution& cellSolution = cellsData[cellNumber].cellSolution;
IndexType cellIndex = volumeMesh.GetCellIndex(cellsData[cellNumber].cell.incidentNodes);
assert(cellIndex != IndexType(-1));
IndexType associatedPermutation[Space::NodesPerCell];
volumeMesh.GetCellsPairOrientation(cellsData[cellNumber].cell.incidentNodes,
volumeMesh.cells[cellIndex].incidentNodes, associatedPermutation);
// ? TODO
volumeMesh.TransformCellSolution(cellIndex, associatedPermutation, &cellSolution);
volumeMesh.cellSolutions[cellIndex] = cellSolution;
}
}
template<typename Space, typename FunctionSpace>
void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::UpdateNodesData(IndexType nodesCount, const NodeSyncData* const nodesData)
{
#pragma omp parallel for
for (int nodeNumber = 0; nodeNumber < (int)nodesCount; ++nodeNumber)
{
const Vector& pos = nodesData[nodeNumber].pos;
IndexType nodeIndex = nodesData[nodeNumber].nodeIndex;
volumeMesh.nodes[nodeIndex] = Node(pos);
}
}
template<typename Space, typename FunctionSpace>
void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::BuildCellsSyncData(IndexType dstDomainIndex, char* const data)
{
*((IndexType*)data) = (IndexType)transitionInfos[dstDomainIndex].cells.size();
CellSyncData* cellsData = (CellSyncData*)(data + sizeof(IndexType));
#pragma omp parallel for
for (int cellNumber = 0; cellNumber < (int)transitionInfos[dstDomainIndex].cells.size(); ++cellNumber)
{
IndexType cellIndex = volumeMesh.GetCellIndex(
transitionInfos[dstDomainIndex].cells[cellNumber].incidentNodes);
assert(cellIndex != IndexType(-1));
CellSyncData& cellSyncData = cellsData[cellNumber];
cellSyncData.cellSolution = volumeMesh.cellSolutions[cellIndex];
for (IndexType nodeNumber = 0; nodeNumber < Space::NodesPerCell; ++nodeNumber)
{
cellSyncData.cell.incidentNodes[nodeNumber] = nodesDictionaries[dstDomainIndex][volumeMesh.cells[cellIndex].incidentNodes[nodeNumber]];
}
// TODO
// cellSyncData.destroy =
}
}
template<typename Space, typename FunctionSpace>
void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::BuildNodesSyncData(IndexType dstDomainIndex, char* const data)
{
*((IndexType*)data) = transitionInfos[dstDomainIndex].nodesIndices.size();
NodeSyncData* nodesData = (NodeSyncData*)(data + sizeof(IndexType));
#pragma omp parallel for
for (int nodeNumber = 0; nodeNumber < (int)transitionInfos[dstDomainIndex].nodesIndices.size(); ++nodeNumber)
{
IndexType nodeIndex = transitionInfos[dstDomainIndex].nodesIndices[nodeNumber];
NodeSyncData& nodeSyncData = nodesData[nodeNumber];
nodeSyncData.pos = volumeMesh.nodes[nodeIndex].pos;
nodeSyncData.nodeIndex = nodesDictionaries[dstDomainIndex][nodeIndex];
}
}
template<typename Space, typename FunctionSpace>
void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::ComputeSyncDataSizes()
{
for (IndexType dstDomainIndex = 0; dstDomainIndex < domainsCount; ++dstDomainIndex)
{
syncDataSizes[dstDomainIndex] += sizeof(IndexType) + // dstDomainIndes
sizeof(IndexType) + // cells count
transitionInfos[dstDomainIndex].cells.size() * sizeof(CellSyncData) +
sizeof(IndexType) + // nodes count
(sendNodesInfo ? transitionInfos[dstDomainIndex].nodesIndices.size() * sizeof(NodeSyncData) : 0);
}
}
| 39.816216 | 146 | 0.771518 | llmontoryxd |
d97aa82743ee3cd0b534a9895eb818613dd5fa36 | 6,003 | cpp | C++ | src/Core/Canvas.cpp | dgi09/2DGameEngine | 18eff334f2ebf469d780688b2bfee6af760a699d | [
"BSD-2-Clause"
] | 1 | 2017-03-13T22:07:35.000Z | 2017-03-13T22:07:35.000Z | src/Core/Canvas.cpp | dgi09/2DGameEngine | 18eff334f2ebf469d780688b2bfee6af760a699d | [
"BSD-2-Clause"
] | null | null | null | src/Core/Canvas.cpp | dgi09/2DGameEngine | 18eff334f2ebf469d780688b2bfee6af760a699d | [
"BSD-2-Clause"
] | null | null | null | #include "Canvas.h"
using namespace DirectX;
Canvas::Canvas(HWND handle, UINT width, UINT height)
{
this->width = width;
this->height = height;
DXGI_SWAP_CHAIN_DESC desc;
ZeroMemory(&desc,sizeof(DXGI_SWAP_CHAIN_DESC));
desc.BufferCount = 2;
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.BufferDesc.Width = width;
desc.BufferDesc.Height = height;
desc.OutputWindow = handle;
desc.SampleDesc.Count = 1;
desc.Windowed = TRUE;
D3D_FEATURE_LEVEL ftr;
ftr = D3D_FEATURE_LEVEL_11_0;
D3D11CreateDeviceAndSwapChain(NULL,D3D_DRIVER_TYPE_HARDWARE,
nullptr,0,&ftr,1,
D3D11_SDK_VERSION,
&desc,
&swapChain,
&device,
nullptr,
&context);
ID3D11Texture2D * backBuffer = nullptr;
swapChain->GetBuffer(0,__uuidof(ID3D11Texture2D),(LPVOID*)&backBuffer);
device->CreateRenderTargetView(backBuffer,nullptr,&backBufferView);
context->OMSetRenderTargets(1,&backBufferView,nullptr);
D3D11_DEPTH_STENCIL_DESC depthDesc;
ZeroMemory(&depthDesc,sizeof(D3D11_DEPTH_STENCIL_DESC));
depthDesc.DepthEnable = false;
D3D11_RASTERIZER_DESC rasterDesc;
ZeroMemory(&rasterDesc,sizeof(D3D11_RASTERIZER_DESC));
rasterDesc.CullMode = D3D11_CULL_NONE;
rasterDesc.FillMode = D3D11_FILL_SOLID;
device->CreateRasterizerState(&rasterDesc,&rasterState);
context->RSSetState(rasterState);
device->CreateDepthStencilState(&depthDesc,&depthState);
context->OMSetDepthStencilState(depthState,0);
D3D11_BLEND_DESC blendStateDescription;
ZeroMemory(&blendStateDescription,sizeof(D3D11_BLEND_DESC));
blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;
device->CreateBlendState(&blendStateDescription,&blend);
float factor[] = {0.0f,0.0f,0.0f,0.0f};
context->OMSetBlendState(blend,factor,0xffffffff);
D3D11_VIEWPORT view;
ZeroMemory(&view,sizeof(D3D11_VIEWPORT));
view.TopLeftX = 0.0f;
view.TopLeftY = 0.0f;
view.Width = (UINT)width;
view.Height = (UINT)height;
view.MinDepth = 0.0f;
view.MaxDepth = 1.0f;
context->RSSetViewports(1,&view);
tQuad.Init(device);
cQuad.Init(device);
cLine.Init(device);
lastRotationAngle = 0;
XMMATRIX viewMat = XMMatrixLookAtLH(XMVectorSet(0.0f,0.0f,0.0f,1.0f),XMVectorSet(0.0f,0.0f,1.0f,1.0f),XMVectorSet(0.0f,1.0f,0.0f,1.0f));
XMMATRIX proj = XMMatrixOrthographicLH((float)width,(float)height,0.1f,1.0f);
XMStoreFloat4x4(&mat.viewMatrix,XMMatrixTranspose(viewMat));
XMStoreFloat4x4(&mat.projmatrix,XMMatrixTranspose(proj));
XMStoreFloat4x4(&mat.worldMatrix,XMMatrixTranspose(XMMatrixIdentity()));
D3D11_BUFFER_DESC cDesc;
cDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cDesc.ByteWidth = sizeof(Matrixes);
cDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cDesc.MiscFlags = 0;
cDesc.StructureByteStride = 0;
cDesc.Usage = D3D11_USAGE_DYNAMIC;
D3D11_SUBRESOURCE_DATA data;
data.pSysMem = &mat;
device->CreateBuffer(&cDesc,&data,&matrixBuffer);
context->VSSetConstantBuffers(0,1,&matrixBuffer);
}
Canvas::~Canvas()
{
rasterState->Release();
depthState->Release();
matrixBuffer->Release();
backBufferView->Release();
context->Release();
device->Release();
swapChain->Release();
}
void Canvas::SetClearColor(Color color)
{
clearColor = color;
}
Color Canvas::GetClearColor()
{
return clearColor;
}
void Canvas::Clear()
{
context->ClearRenderTargetView(backBufferView,(float*)&clearColor);
}
void Canvas::Present()
{
swapChain->Present(0,0);
}
void Canvas::DrawRectSolid(Rect & rect,Color color,int rotationAngle)
{
BindWorldMatrix(rect,rotationAngle);
cQuad.Draw(color);
}
void Canvas::DrawTexture(Texture * texture,Rect & destRect, Rect * srcRect, int rotationAngle)
{
BindWorldMatrix(destRect,rotationAngle);
tQuad.Draw(texture,srcRect);
}
void Canvas::DrawLine(int x1,int y1,int x2,int y2,Color color)
{
BindWorldMatrix();
cLine.Draw(x1,y1,x2,y2,color);
}
void Canvas::DrawRect(Rect rect,Color color)
{
BindWorldMatrix();
cLine.Draw(rect.left,rect.top,rect.right,rect.top,color);
cLine.Draw(rect.right,rect.top,rect.right,rect.bottom,color);
cLine.Draw(rect.left,rect.top,rect.left,rect.bottom,color);
cLine.Draw(rect.left,rect.bottom,rect.right,rect.bottom,color);
}
ID3D11Device * Canvas::GetDevice()
{
return device;
}
void Canvas::BindWorldMatrix(Rect & destRect,int rotationAngle)
{
XMMATRIX scale = XMMatrixScaling((float)(destRect.right - destRect.left),(float)(destRect.bottom - destRect.top),1.0f);
XMMATRIX rotation = XMMatrixRotationZ(XMConvertToRadians((float)rotationAngle));
XMMATRIX translation = XMMatrixTranslation((float)destRect.left - (float)(width/2),(float)(height/2) - (float)destRect.top,0.0f);
XMStoreFloat4x4(&mat.worldMatrix,XMMatrixTranspose(scale * rotation * translation));
D3D11_MAPPED_SUBRESOURCE map;
context->Map(matrixBuffer,0,D3D11_MAP_WRITE_DISCARD,0,&map);
memcpy(map.pData,&mat,sizeof(mat));
context->Unmap(matrixBuffer,0);
}
void Canvas::BindWorldMatrix()
{
XMMATRIX translation = XMMatrixTranslation(-(float)(width/2),(float)(height/2),0.0f);
XMStoreFloat4x4(&mat.worldMatrix,XMMatrixTranspose(translation));
D3D11_MAPPED_SUBRESOURCE map;
context->Map(matrixBuffer,0,D3D11_MAP_WRITE_DISCARD,0,&map);
memcpy(map.pData,&mat,sizeof(mat));
context->Unmap(matrixBuffer,0);
}
void Canvas::BindWorlMatrix_Identity()
{
XMStoreFloat4x4(&mat.worldMatrix,XMMatrixIdentity());
D3D11_MAPPED_SUBRESOURCE map;
context->Map(matrixBuffer,0,D3D11_MAP_WRITE_DISCARD,0,&map);
memcpy(map.pData,&mat,sizeof(mat));
context->Unmap(matrixBuffer,0);
}
| 26.213974 | 137 | 0.775112 | dgi09 |
d97ba6d598c6bf6fb2e084606a3c1214fe97f695 | 2,838 | hpp | C++ | flightgoggles_ros_bridge/src/CameraModel/FisheyeModel.hpp | aau-cns/flightgoggles | 7e194480b3852bd4ac34467222ffbbbaf9355b77 | [
"BSD-2-Clause"
] | null | null | null | flightgoggles_ros_bridge/src/CameraModel/FisheyeModel.hpp | aau-cns/flightgoggles | 7e194480b3852bd4ac34467222ffbbbaf9355b77 | [
"BSD-2-Clause"
] | null | null | null | flightgoggles_ros_bridge/src/CameraModel/FisheyeModel.hpp | aau-cns/flightgoggles | 7e194480b3852bd4ac34467222ffbbbaf9355b77 | [
"BSD-2-Clause"
] | null | null | null | /// Copyright (C) 2020 Martin Scheiber, Control of Networked Systems,
/// University of Klagenfurt, Austria.
///
/// All rights reserved.
///
/// This software is licensed under the terms of the BSD-2-Clause-License with
/// no commercial use allowed, the full terms of which are made available in the
/// LICENSE file. No license in patents is granted.
///
/// You can contact the author at [email protected]
#ifndef FISHEYEMODEL_H
#define FISHEYEMODEL_H
#include "CameraModel.hpp"
class FisheyeCamera : public CameraModel
{
public:
/// @name Parameter Struct
/**
* @brief The FisheyeParameters struct describes the parameters used in the fisheye model.
*/
struct FisheyeParameters
{
/// @name Parameters
uint img_width; //!< resolution width
uint img_height; //!< resolution height
float fx; //!< focal length in x
float fy; //!< focal length in y
float cx; //!< center point in x
float cy; //!< center point in y
float s; //!< fisheye distortion parameter
/// @name Precalculated Parameters
float s_inv; //!< inverse fisheye distortion parameter
float s_2tan; //!< two times tan of s \f$ 2 * \tan(\frac{s}{2}) \f$
float s_2tan_inv; //!< inverse of two times the tan of s
/**
* @brief setAdditional sets additional calculated parameters
*/
void setAdditional() {
if (! s == 0)
{
s_inv = 1/s;
s_2tan = 2.0 * std::tan(s / 2.0);
s_2tan_inv = 1.0 / (s_2tan);
} // if
} // setAdditional()
}; // struct FisheyeParameters
/// @name Con-/Destructors
FisheyeCamera();
~FisheyeCamera();
/// @name Initial Calls
virtual void setCameraParameters(const FisheyeParameters _parameters);
virtual void setCameraParameters(const uint _img_width, const uint _img_height, const float _fx, const float _fy,
const float _cx, const float _cy, const float _s);
/// @name Image Modification
virtual void applyDistortion(cv::Mat &_image_in, cv::Mat &_image_out, bool _force_dim=false);
virtual void removeDistortion(cv::Mat &_image_in, cv::Mat &_image_out, bool _force_dim=false);
virtual void applyDistortion(cv::Mat &_image);
virtual void removeDistortion(cv::Mat &_image);
/// @name Pixel Modification
virtual cv::Point2f distortPixel(const cv::Point2f _P) const;
virtual cv::Point2f undistortPixel(const cv::Point2f _pix) const;
protected:
private:
/// @name Model Parameters
// Static variables
FisheyeParameters cam_parameters_;
// Methods
void updateLookups();
}; // class FisheyeCamera
#endif
| 34.192771 | 118 | 0.621917 | aau-cns |
d99218e47bd6535383e54e5ac49519f1fd2626ae | 1,350 | hpp | C++ | deployment/configenv/xml_jlibpt/ConfigEnvFactory.hpp | davidarcher/HPCC-Platform | fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3 | [
"Apache-2.0"
] | 286 | 2015-01-03T12:45:17.000Z | 2022-03-25T18:12:57.000Z | deployment/configenv/xml_jlibpt/ConfigEnvFactory.hpp | davidarcher/HPCC-Platform | fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3 | [
"Apache-2.0"
] | 9,034 | 2015-01-02T08:49:19.000Z | 2022-03-31T20:34:44.000Z | deployment/configenv/xml_jlibpt/ConfigEnvFactory.hpp | cloLN/HPCC-Platform | 42ffb763a1cdcf611d3900831973d0a68e722bbe | [
"Apache-2.0"
] | 208 | 2015-01-02T03:27:28.000Z | 2022-02-11T05:54:52.000Z | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2018 HPCC Systems®.
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 _CONFIGENVFACTORY_HPP_
#define _CONFIGENVFACTORY_HPP_
#include <cstddef>
#include "jiface.hpp"
#include "jliball.hpp"
#include "IConfigEnv.hpp"
#include "ConfigEnv.hpp"
interface IPropertyTree;
//interface IConfigEnv<IPropertyTree, StringBuffer>;
//interface IConfigComp;
namespace ech
{
//template<class PTTYPE, class SB>
class configenv_decl ConfigEnvFactory
{
public:
static IConfigEnv<IPropertyTree, StringBuffer> * getIConfigEnv(IPropertyTree *config);
static void destroy(IConfigEnv<IPropertyTree, StringBuffer> * iCfgEnv);
};
}
#endif
| 29.347826 | 90 | 0.66963 | davidarcher |
d99220c4343da522edb4e2580575a7cc271d3adc | 2,400 | cpp | C++ | game/source/src/Projectile_creator.cpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | 5 | 2019-02-12T07:23:55.000Z | 2020-06-22T15:03:36.000Z | game/source/src/Projectile_creator.cpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | null | null | null | game/source/src/Projectile_creator.cpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | 2 | 2019-06-17T05:04:21.000Z | 2020-04-22T09:05:57.000Z | #include "Projectile_creator.hpp"
#include "Creator.hpp"
#include "Game_object.hpp"
#include "Projectile.hpp"
#include "vec2.hpp"
#include "vec3.hpp"
#include "AABB_2d.hpp"
#include "Animator_controller.hpp"
#include "Animator_state.hpp"
#include "Sprite_atlas.hpp"
#include "Sprite_atlas_manager.hpp"
#include "string_id.hpp"
#include "Collider_2d_def.hpp"
#include "Body_2d_def.hpp"
#include "runtime_memory_allocator.hpp"
#include "Object.hpp"
#include <utility>
Projectile_creator::Projectile_creator(const string_id atlas_id,
const physics_2d::Body_2d_def & body_def,
const gfx::Animator_controller *panim_controller) :
gom::Creator(), m_atlas_res_id(atlas_id)
{
//create body_2d_def
void *pmem = mem::allocate(sizeof(physics_2d::Body_2d_def));
if (pmem != nullptr) {
m_pbody_def = static_cast<physics_2d::Body_2d_def*>( new (pmem) physics_2d::Body_2d_def(body_def));
}
//makea copy of this anim controller
pmem = mem::allocate(sizeof(gfx::Animator_controller));
m_pcontroller = static_cast<gfx::Animator_controller*>(new (pmem) gfx::Animator_controller(*panim_controller));
}
gom::Game_object *Projectile_creator::create(const Object & obj_description)
{
//get the data to create sprite component
gfx::Sprite_atlas *patlas = static_cast<gfx::Sprite_atlas*>(gfx::g_sprite_atlas_mgr.get_by_id(m_atlas_res_id));
gom::Projectile::atlas_n_layer data(patlas, 1);
math::vec3 wld_pos(obj_description.get_x(), obj_description.get_y());
math::vec2 translation = math::vec2(wld_pos.x, wld_pos.y) - m_pbody_def->m_position;
m_pbody_def->m_position += translation;
m_pbody_def->m_aabb.p_max += translation;
m_pbody_def->m_aabb.p_min += translation;
physics_2d::Collider_2d_def coll_def;
coll_def.m_aabb = m_pbody_def->m_aabb;
std::size_t object_sz = sizeof(gom::Projectile);
void *pmem = mem::allocate(object_sz);
gom::Game_object *pgame_object = static_cast<gom::Game_object*>(
new (pmem) gom::Projectile(object_sz, wld_pos, data, m_pbody_def, m_pcontroller));
pgame_object->get_body_2d_component()->create_collider_2d(coll_def);
pgame_object->set_type(m_obj_type);
pgame_object->set_tag(m_obj_tag);
return pgame_object;
}
Projectile_creator::~Projectile_creator()
{
mem::free(static_cast<void*>(m_pcontroller), sizeof(gfx::Animator_controller));
} | 33.333333 | 112 | 0.7375 | mateusgondim |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.