hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
92846baa5a0b3e529bdcbf01caf8c96f0eebc2f8 | 3,012 | cpp | C++ | android-ndk-r10b/tests/device/test-stlport/unit/config_test.cpp | perezite/Boost4Android | 9ed03a45815aead156c129da1927cc04b8caa6a3 | [
"BSL-1.0"
] | 4 | 2017-12-04T08:22:48.000Z | 2019-10-26T21:44:59.000Z | master/core/third/stlport/test/unit/config_test.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | null | null | null | master/core/third/stlport/test/unit/config_test.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:49.000Z | 2018-12-27T03:20:31.000Z | #include <new>
#include <vector>
#include "cppunit/cppunit_proxy.h"
#if defined (_STLP_USE_NAMESPACES)
using namespace std;
#endif
//
// TestCase class
//
class ConfigTest : public CPPUNIT_NS::TestCase
{
CPPUNIT_TEST_SUITE(ConfigTest);
#if !defined (STLPORT)
CPPUNIT_IGNORE;
#endif
CPPUNIT_TEST(placement_new_bug);
CPPUNIT_TEST(endianess);
CPPUNIT_TEST(template_function_partial_ordering);
#if !defined (_STLP_USE_EXCEPTIONS)
CPPUNIT_IGNORE;
#endif
CPPUNIT_TEST(new_throw_bad_alloc);
CPPUNIT_TEST_SUITE_END();
protected:
void placement_new_bug();
void endianess();
void template_function_partial_ordering();
void new_throw_bad_alloc();
};
CPPUNIT_TEST_SUITE_REGISTRATION(ConfigTest);
void ConfigTest::placement_new_bug()
{
#if defined (STLPORT)
int int_val = 1;
int *pint;
pint = new(&int_val) int();
CPPUNIT_ASSERT( pint == &int_val );
# if defined (_STLP_DEF_CONST_PLCT_NEW_BUG)
CPPUNIT_ASSERT( int_val != 0 );
# else
CPPUNIT_ASSERT( int_val == 0 );
# endif
#endif
}
void ConfigTest::endianess()
{
#if defined (STLPORT)
int val = 0x01020304;
char *ptr = (char*)(&val);
# if defined (_STLP_BIG_ENDIAN)
//This test only work if sizeof(int) == 4, this is a known limitation
//that will be handle the day we find a compiler for which it is false.
CPPUNIT_ASSERT( *ptr == 0x01 ||
sizeof(int) > 4 && *ptr == 0x00 );
# elif defined (_STLP_LITTLE_ENDIAN)
CPPUNIT_ASSERT( *ptr == 0x04 );
# endif
#endif
}
void ConfigTest::template_function_partial_ordering()
{
#if defined (STLPORT)
vector<int> vect1(10, 0);
int* pvect1Front = &vect1.front();
vector<int> vect2(10, 0);
int* pvect2Front = &vect2.front();
swap(vect1, vect2);
# if defined (_STLP_FUNCTION_TMPL_PARTIAL_ORDER) || defined (_STLP_USE_PARTIAL_SPEC_WORKAROUND)
CPPUNIT_ASSERT( pvect1Front == &vect2.front() );
CPPUNIT_ASSERT( pvect2Front == &vect1.front() );
# else
CPPUNIT_ASSERT( pvect1Front != &vect2.front() );
CPPUNIT_ASSERT( pvect2Front != &vect1.front() );
# endif
#endif
}
void ConfigTest::new_throw_bad_alloc()
{
#if defined (STLPORT) && defined (_STLP_USE_EXCEPTIONS)
try
{
/* We try to exhaust heap memory. However, we don't actually use the
largest possible size_t value bus slightly less in order to avoid
triggering any overflows due to the allocator adding some more for
its internal data structures. */
size_t const huge_amount = size_t(-1) - 1024;
void* pvoid = operator new (huge_amount);
#if !defined (_STLP_NEW_DONT_THROW_BAD_ALLOC)
// Allocation should have fail
CPPUNIT_ASSERT( pvoid != 0 );
#endif
// Just in case it succeeds:
operator delete(pvoid);
}
catch (const bad_alloc&)
{
#if defined (_STLP_NEW_DONT_THROW_BAD_ALLOC)
// Looks like your compiler new operator finally throw bad_alloc, you can fix
// configuration.
CPPUNIT_FAIL;
#endif
}
catch (...)
{
//We shouldn't be there:
//Not bad_alloc exception thrown.
CPPUNIT_FAIL;
}
#endif
}
| 24.688525 | 96 | 0.706175 | [
"vector"
] |
928db55740b47fa6e7ba070ef0e240087b6a1e3a | 2,818 | hpp | C++ | NumberTheory/CRC.hpp | reidrac/CLK | a38974ef2e706d87f8ce7320b91c76c13dcede09 | [
"MIT"
] | 1 | 2019-07-05T18:09:34.000Z | 2019-07-05T18:09:34.000Z | NumberTheory/CRC.hpp | reidrac/CLK | a38974ef2e706d87f8ce7320b91c76c13dcede09 | [
"MIT"
] | null | null | null | NumberTheory/CRC.hpp | reidrac/CLK | a38974ef2e706d87f8ce7320b91c76c13dcede09 | [
"MIT"
] | null | null | null | //
// CRC.hpp
// Clock Signal
//
// Created by Thomas Harte on 18/09/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
#ifndef CRC_hpp
#define CRC_hpp
#include <cstdint>
#include <vector>
namespace CRC {
/*! Provides a class capable of generating a CRC from source data. */
template <typename T, T reset_value, T xor_output, bool reflect_input, bool reflect_output> class Generator {
public:
/*!
Instantiates a CRC16 that will compute the CRC16 specified by the supplied
@c polynomial and @c reset_value.
*/
Generator(T polynomial): value_(reset_value) {
const T top_bit = T(~(T(~0) >> 1));
for(int c = 0; c < 256; c++) {
T shift_value = static_cast<T>(c << multibyte_shift);
for(int b = 0; b < 8; b++) {
T exclusive_or = (shift_value&top_bit) ? polynomial : 0;
shift_value = static_cast<T>(shift_value << 1) ^ exclusive_or;
}
xor_table[c] = shift_value;
}
}
/// Resets the CRC to the reset value.
void reset() { value_ = reset_value; }
/// Updates the CRC to include @c byte.
void add(uint8_t byte) {
if(reflect_input) byte = reverse_byte(byte);
value_ = static_cast<T>((value_ << 8) ^ xor_table[(value_ >> multibyte_shift) ^ byte]);
}
/// @returns The current value of the CRC.
inline T get_value() const {
T result = value_^xor_output;
if(reflect_output) {
T reflected_output = 0;
for(std::size_t c = 0; c < sizeof(T); ++c) {
reflected_output = T(reflected_output << 8) | T(reverse_byte(result & 0xff));
result >>= 8;
}
return reflected_output;
}
return result;
}
/// Sets the current value of the CRC.
inline void set_value(T value) { value_ = value; }
/*!
A compound for:
reset()
[add all data from @c data]
get_value()
*/
T compute_crc(const std::vector<uint8_t> &data) {
reset();
for(const auto &byte: data) add(byte);
return get_value();
}
private:
static constexpr int multibyte_shift = (sizeof(T) * 8) - 8;
T xor_table[256];
T value_;
constexpr uint8_t reverse_byte(uint8_t byte) const {
return
((byte & 0x80) ? 0x01 : 0x00) |
((byte & 0x40) ? 0x02 : 0x00) |
((byte & 0x20) ? 0x04 : 0x00) |
((byte & 0x10) ? 0x08 : 0x00) |
((byte & 0x08) ? 0x10 : 0x00) |
((byte & 0x04) ? 0x20 : 0x00) |
((byte & 0x02) ? 0x40 : 0x00) |
((byte & 0x01) ? 0x80 : 0x00);
}
};
/*!
Provides a generator of 16-bit CCITT CRCs, which amongst other uses are
those used by the FM and MFM disk encodings.
*/
struct CCITT: public Generator<uint16_t, 0xffff, 0x0000, false, false> {
CCITT(): Generator(0x1021) {}
};
/*!
Provides a generator of "standard 32-bit" CRCs.
*/
struct CRC32: public Generator<uint32_t, 0xffffffff, 0xffffffff, true, true> {
CRC32(): Generator(0x04c11db7) {}
};
}
#endif /* CRC_hpp */
| 25.387387 | 109 | 0.631654 | [
"vector"
] |
929123871ea29c526bc2620c2a9aa1a52716aa3c | 162,793 | cc | C++ | gpu/command_buffer/service/gles2_cmd_decoder_passthrough_handlers_autogen.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | gpu/command_buffer/service/gles2_cmd_decoder_passthrough_handlers_autogen.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | gpu/command_buffer/service/gles2_cmd_decoder_passthrough_handlers_autogen.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is auto-generated from
// gpu/command_buffer/build_gles2_cmd_buffer.py
// It's formatted by clang-format using chromium coding style:
// clang-format -i -style=chromium filename
// DO NOT EDIT!
#include "gpu/command_buffer/service/gles2_cmd_decoder_passthrough.h"
namespace gpu {
namespace gles2 {
error::Error GLES2DecoderPassthroughImpl::HandleActiveTexture(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::ActiveTexture& c =
*static_cast<const volatile gles2::cmds::ActiveTexture*>(cmd_data);
GLenum texture = static_cast<GLenum>(c.texture);
error::Error error = DoActiveTexture(texture);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleAttachShader(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::AttachShader& c =
*static_cast<const volatile gles2::cmds::AttachShader*>(cmd_data);
GLuint program = c.program;
GLuint shader = c.shader;
error::Error error = DoAttachShader(program, shader);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBindBuffer(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BindBuffer& c =
*static_cast<const volatile gles2::cmds::BindBuffer*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLuint buffer = c.buffer;
error::Error error = DoBindBuffer(target, buffer);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBindBufferBase(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::BindBufferBase& c =
*static_cast<const volatile gles2::cmds::BindBufferBase*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLuint index = static_cast<GLuint>(c.index);
GLuint buffer = c.buffer;
error::Error error = DoBindBufferBase(target, index, buffer);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBindBufferRange(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::BindBufferRange& c =
*static_cast<const volatile gles2::cmds::BindBufferRange*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLuint index = static_cast<GLuint>(c.index);
GLuint buffer = c.buffer;
GLintptr offset = static_cast<GLintptr>(c.offset);
GLsizeiptr size = static_cast<GLsizeiptr>(c.size);
error::Error error = DoBindBufferRange(target, index, buffer, offset, size);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBindFramebuffer(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BindFramebuffer& c =
*static_cast<const volatile gles2::cmds::BindFramebuffer*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLuint framebuffer = c.framebuffer;
error::Error error = DoBindFramebuffer(target, framebuffer);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBindRenderbuffer(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BindRenderbuffer& c =
*static_cast<const volatile gles2::cmds::BindRenderbuffer*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLuint renderbuffer = c.renderbuffer;
error::Error error = DoBindRenderbuffer(target, renderbuffer);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBindSampler(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::BindSampler& c =
*static_cast<const volatile gles2::cmds::BindSampler*>(cmd_data);
GLuint unit = static_cast<GLuint>(c.unit);
GLuint sampler = c.sampler;
error::Error error = DoBindSampler(unit, sampler);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBindTexture(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BindTexture& c =
*static_cast<const volatile gles2::cmds::BindTexture*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLuint texture = c.texture;
error::Error error = DoBindTexture(target, texture);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBindTransformFeedback(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::BindTransformFeedback& c =
*static_cast<const volatile gles2::cmds::BindTransformFeedback*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLuint transformfeedback = c.transformfeedback;
error::Error error = DoBindTransformFeedback(target, transformfeedback);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBlendColor(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BlendColor& c =
*static_cast<const volatile gles2::cmds::BlendColor*>(cmd_data);
GLclampf red = static_cast<GLclampf>(c.red);
GLclampf green = static_cast<GLclampf>(c.green);
GLclampf blue = static_cast<GLclampf>(c.blue);
GLclampf alpha = static_cast<GLclampf>(c.alpha);
error::Error error = DoBlendColor(red, green, blue, alpha);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBlendEquation(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BlendEquation& c =
*static_cast<const volatile gles2::cmds::BlendEquation*>(cmd_data);
GLenum mode = static_cast<GLenum>(c.mode);
error::Error error = DoBlendEquation(mode);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBlendEquationSeparate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BlendEquationSeparate& c =
*static_cast<const volatile gles2::cmds::BlendEquationSeparate*>(
cmd_data);
GLenum modeRGB = static_cast<GLenum>(c.modeRGB);
GLenum modeAlpha = static_cast<GLenum>(c.modeAlpha);
error::Error error = DoBlendEquationSeparate(modeRGB, modeAlpha);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBlendFunc(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BlendFunc& c =
*static_cast<const volatile gles2::cmds::BlendFunc*>(cmd_data);
GLenum sfactor = static_cast<GLenum>(c.sfactor);
GLenum dfactor = static_cast<GLenum>(c.dfactor);
error::Error error = DoBlendFunc(sfactor, dfactor);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBlendFuncSeparate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BlendFuncSeparate& c =
*static_cast<const volatile gles2::cmds::BlendFuncSeparate*>(cmd_data);
GLenum srcRGB = static_cast<GLenum>(c.srcRGB);
GLenum dstRGB = static_cast<GLenum>(c.dstRGB);
GLenum srcAlpha = static_cast<GLenum>(c.srcAlpha);
GLenum dstAlpha = static_cast<GLenum>(c.dstAlpha);
error::Error error = DoBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBufferSubData(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BufferSubData& c =
*static_cast<const volatile gles2::cmds::BufferSubData*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLintptr offset = static_cast<GLintptr>(c.offset);
GLsizeiptr size = static_cast<GLsizeiptr>(c.size);
uint32_t data_size = size;
const void* data = GetSharedMemoryAs<const void*>(
c.data_shm_id, c.data_shm_offset, data_size);
error::Error error = DoBufferSubData(target, offset, size, data);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCheckFramebufferStatus(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CheckFramebufferStatus& c =
*static_cast<const volatile gles2::cmds::CheckFramebufferStatus*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
typedef cmds::CheckFramebufferStatus::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoCheckFramebufferStatus(target, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleClear(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Clear& c =
*static_cast<const volatile gles2::cmds::Clear*>(cmd_data);
GLbitfield mask = static_cast<GLbitfield>(c.mask);
error::Error error = DoClear(mask);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleClearBufferfi(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::ClearBufferfi& c =
*static_cast<const volatile gles2::cmds::ClearBufferfi*>(cmd_data);
GLenum buffer = static_cast<GLenum>(c.buffer);
GLint drawbuffers = static_cast<GLint>(c.drawbuffers);
GLfloat depth = static_cast<GLfloat>(c.depth);
GLint stencil = static_cast<GLint>(c.stencil);
error::Error error = DoClearBufferfi(buffer, drawbuffers, depth, stencil);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleClearBufferfvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::ClearBufferfvImmediate& c =
*static_cast<const volatile gles2::cmds::ClearBufferfvImmediate*>(
cmd_data);
GLenum buffer = static_cast<GLenum>(c.buffer);
GLint drawbuffers = static_cast<GLint>(c.drawbuffers);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLfloat, 4>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* value = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoClearBufferfv(buffer, drawbuffers, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleClearBufferivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::ClearBufferivImmediate& c =
*static_cast<const volatile gles2::cmds::ClearBufferivImmediate*>(
cmd_data);
GLenum buffer = static_cast<GLenum>(c.buffer);
GLint drawbuffers = static_cast<GLint>(c.drawbuffers);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLint, 4>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLint* value = GetImmediateDataAs<volatile const GLint*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoClearBufferiv(buffer, drawbuffers, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleClearBufferuivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::ClearBufferuivImmediate& c =
*static_cast<const volatile gles2::cmds::ClearBufferuivImmediate*>(
cmd_data);
GLenum buffer = static_cast<GLenum>(c.buffer);
GLint drawbuffers = static_cast<GLint>(c.drawbuffers);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLuint, 4>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLuint* value = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoClearBufferuiv(buffer, drawbuffers, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleClearColor(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::ClearColor& c =
*static_cast<const volatile gles2::cmds::ClearColor*>(cmd_data);
GLclampf red = static_cast<GLclampf>(c.red);
GLclampf green = static_cast<GLclampf>(c.green);
GLclampf blue = static_cast<GLclampf>(c.blue);
GLclampf alpha = static_cast<GLclampf>(c.alpha);
error::Error error = DoClearColor(red, green, blue, alpha);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleClearDepthf(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::ClearDepthf& c =
*static_cast<const volatile gles2::cmds::ClearDepthf*>(cmd_data);
GLclampf depth = static_cast<GLclampf>(c.depth);
error::Error error = DoClearDepthf(depth);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleClearStencil(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::ClearStencil& c =
*static_cast<const volatile gles2::cmds::ClearStencil*>(cmd_data);
GLint s = static_cast<GLint>(c.s);
error::Error error = DoClearStencil(s);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleColorMask(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::ColorMask& c =
*static_cast<const volatile gles2::cmds::ColorMask*>(cmd_data);
GLboolean red = static_cast<GLboolean>(c.red);
GLboolean green = static_cast<GLboolean>(c.green);
GLboolean blue = static_cast<GLboolean>(c.blue);
GLboolean alpha = static_cast<GLboolean>(c.alpha);
error::Error error = DoColorMask(red, green, blue, alpha);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCompileShader(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CompileShader& c =
*static_cast<const volatile gles2::cmds::CompileShader*>(cmd_data);
GLuint shader = c.shader;
error::Error error = DoCompileShader(shader);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCopyBufferSubData(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::CopyBufferSubData& c =
*static_cast<const volatile gles2::cmds::CopyBufferSubData*>(cmd_data);
GLenum readtarget = static_cast<GLenum>(c.readtarget);
GLenum writetarget = static_cast<GLenum>(c.writetarget);
GLintptr readoffset = static_cast<GLintptr>(c.readoffset);
GLintptr writeoffset = static_cast<GLintptr>(c.writeoffset);
GLsizeiptr size = static_cast<GLsizeiptr>(c.size);
error::Error error = DoCopyBufferSubData(readtarget, writetarget, readoffset,
writeoffset, size);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCopyTexImage2D(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CopyTexImage2D& c =
*static_cast<const volatile gles2::cmds::CopyTexImage2D*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLint level = static_cast<GLint>(c.level);
GLenum internalformat = static_cast<GLenum>(c.internalformat);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
GLint border = static_cast<GLint>(c.border);
error::Error error = DoCopyTexImage2D(target, level, internalformat, x, y,
width, height, border);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCopyTexSubImage2D(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CopyTexSubImage2D& c =
*static_cast<const volatile gles2::cmds::CopyTexSubImage2D*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLint level = static_cast<GLint>(c.level);
GLint xoffset = static_cast<GLint>(c.xoffset);
GLint yoffset = static_cast<GLint>(c.yoffset);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
error::Error error =
DoCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCopyTexSubImage3D(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::CopyTexSubImage3D& c =
*static_cast<const volatile gles2::cmds::CopyTexSubImage3D*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLint level = static_cast<GLint>(c.level);
GLint xoffset = static_cast<GLint>(c.xoffset);
GLint yoffset = static_cast<GLint>(c.yoffset);
GLint zoffset = static_cast<GLint>(c.zoffset);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
error::Error error = DoCopyTexSubImage3D(target, level, xoffset, yoffset,
zoffset, x, y, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCullFace(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CullFace& c =
*static_cast<const volatile gles2::cmds::CullFace*>(cmd_data);
GLenum mode = static_cast<GLenum>(c.mode);
error::Error error = DoCullFace(mode);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDeleteBuffersImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DeleteBuffersImmediate& c =
*static_cast<const volatile gles2::cmds::DeleteBuffersImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile const GLuint* buffers = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (buffers == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoDeleteBuffers(n, buffers);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDeleteFramebuffersImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DeleteFramebuffersImmediate& c =
*static_cast<const volatile gles2::cmds::DeleteFramebuffersImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile const GLuint* framebuffers =
GetImmediateDataAs<volatile const GLuint*>(c, data_size,
immediate_data_size);
if (framebuffers == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoDeleteFramebuffers(n, framebuffers);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDeleteProgram(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DeleteProgram& c =
*static_cast<const volatile gles2::cmds::DeleteProgram*>(cmd_data);
GLuint program = c.program;
error::Error error = DoDeleteProgram(program);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDeleteRenderbuffersImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DeleteRenderbuffersImmediate& c =
*static_cast<const volatile gles2::cmds::DeleteRenderbuffersImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile const GLuint* renderbuffers =
GetImmediateDataAs<volatile const GLuint*>(c, data_size,
immediate_data_size);
if (renderbuffers == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoDeleteRenderbuffers(n, renderbuffers);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDeleteSamplersImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::DeleteSamplersImmediate& c =
*static_cast<const volatile gles2::cmds::DeleteSamplersImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile const GLuint* samplers = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (samplers == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoDeleteSamplers(n, samplers);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDeleteSync(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::DeleteSync& c =
*static_cast<const volatile gles2::cmds::DeleteSync*>(cmd_data);
GLuint sync = c.sync;
error::Error error = DoDeleteSync(sync);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDeleteShader(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DeleteShader& c =
*static_cast<const volatile gles2::cmds::DeleteShader*>(cmd_data);
GLuint shader = c.shader;
error::Error error = DoDeleteShader(shader);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDeleteTexturesImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DeleteTexturesImmediate& c =
*static_cast<const volatile gles2::cmds::DeleteTexturesImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile const GLuint* textures = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (textures == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoDeleteTextures(n, textures);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleDeleteTransformFeedbacksImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::DeleteTransformFeedbacksImmediate& c =
*static_cast<
const volatile gles2::cmds::DeleteTransformFeedbacksImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile const GLuint* ids = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (ids == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoDeleteTransformFeedbacks(n, ids);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDepthFunc(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DepthFunc& c =
*static_cast<const volatile gles2::cmds::DepthFunc*>(cmd_data);
GLenum func = static_cast<GLenum>(c.func);
error::Error error = DoDepthFunc(func);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDepthMask(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DepthMask& c =
*static_cast<const volatile gles2::cmds::DepthMask*>(cmd_data);
GLboolean flag = static_cast<GLboolean>(c.flag);
error::Error error = DoDepthMask(flag);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDepthRangef(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DepthRangef& c =
*static_cast<const volatile gles2::cmds::DepthRangef*>(cmd_data);
GLclampf zNear = static_cast<GLclampf>(c.zNear);
GLclampf zFar = static_cast<GLclampf>(c.zFar);
error::Error error = DoDepthRangef(zNear, zFar);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDetachShader(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DetachShader& c =
*static_cast<const volatile gles2::cmds::DetachShader*>(cmd_data);
GLuint program = c.program;
GLuint shader = c.shader;
error::Error error = DoDetachShader(program, shader);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDisable(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Disable& c =
*static_cast<const volatile gles2::cmds::Disable*>(cmd_data);
GLenum cap = static_cast<GLenum>(c.cap);
error::Error error = DoDisable(cap);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDisableVertexAttribArray(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DisableVertexAttribArray& c =
*static_cast<const volatile gles2::cmds::DisableVertexAttribArray*>(
cmd_data);
GLuint index = static_cast<GLuint>(c.index);
error::Error error = DoDisableVertexAttribArray(index);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleEnable(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Enable& c =
*static_cast<const volatile gles2::cmds::Enable*>(cmd_data);
GLenum cap = static_cast<GLenum>(c.cap);
error::Error error = DoEnable(cap);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleEnableVertexAttribArray(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::EnableVertexAttribArray& c =
*static_cast<const volatile gles2::cmds::EnableVertexAttribArray*>(
cmd_data);
GLuint index = static_cast<GLuint>(c.index);
error::Error error = DoEnableVertexAttribArray(index);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleFinish(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
error::Error error = DoFinish();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleFlush(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
error::Error error = DoFlush();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleFramebufferRenderbuffer(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::FramebufferRenderbuffer& c =
*static_cast<const volatile gles2::cmds::FramebufferRenderbuffer*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum attachment = static_cast<GLenum>(c.attachment);
GLenum renderbuffertarget = static_cast<GLenum>(c.renderbuffertarget);
GLuint renderbuffer = c.renderbuffer;
error::Error error = DoFramebufferRenderbuffer(
target, attachment, renderbuffertarget, renderbuffer);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleFramebufferTexture2D(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::FramebufferTexture2D& c =
*static_cast<const volatile gles2::cmds::FramebufferTexture2D*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum attachment = static_cast<GLenum>(c.attachment);
GLenum textarget = static_cast<GLenum>(c.textarget);
GLuint texture = c.texture;
GLint level = static_cast<GLint>(c.level);
error::Error error =
DoFramebufferTexture2D(target, attachment, textarget, texture, level);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleFramebufferTextureLayer(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::FramebufferTextureLayer& c =
*static_cast<const volatile gles2::cmds::FramebufferTextureLayer*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum attachment = static_cast<GLenum>(c.attachment);
GLuint texture = c.texture;
GLint level = static_cast<GLint>(c.level);
GLint layer = static_cast<GLint>(c.layer);
error::Error error =
DoFramebufferTextureLayer(target, attachment, texture, level, layer);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleFrontFace(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::FrontFace& c =
*static_cast<const volatile gles2::cmds::FrontFace*>(cmd_data);
GLenum mode = static_cast<GLenum>(c.mode);
error::Error error = DoFrontFace(mode);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGenBuffersImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GenBuffersImmediate& c =
*static_cast<const volatile gles2::cmds::GenBuffersImmediate*>(cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile GLuint* buffers =
GetImmediateDataAs<volatile GLuint*>(c, data_size, immediate_data_size);
if (buffers == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoGenBuffers(n, buffers);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGenerateMipmap(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GenerateMipmap& c =
*static_cast<const volatile gles2::cmds::GenerateMipmap*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
error::Error error = DoGenerateMipmap(target);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGenFramebuffersImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GenFramebuffersImmediate& c =
*static_cast<const volatile gles2::cmds::GenFramebuffersImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile GLuint* framebuffers =
GetImmediateDataAs<volatile GLuint*>(c, data_size, immediate_data_size);
if (framebuffers == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoGenFramebuffers(n, framebuffers);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGenRenderbuffersImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GenRenderbuffersImmediate& c =
*static_cast<const volatile gles2::cmds::GenRenderbuffersImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile GLuint* renderbuffers =
GetImmediateDataAs<volatile GLuint*>(c, data_size, immediate_data_size);
if (renderbuffers == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoGenRenderbuffers(n, renderbuffers);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGenSamplersImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GenSamplersImmediate& c =
*static_cast<const volatile gles2::cmds::GenSamplersImmediate*>(cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile GLuint* samplers =
GetImmediateDataAs<volatile GLuint*>(c, data_size, immediate_data_size);
if (samplers == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoGenSamplers(n, samplers);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGenTexturesImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GenTexturesImmediate& c =
*static_cast<const volatile gles2::cmds::GenTexturesImmediate*>(cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile GLuint* textures =
GetImmediateDataAs<volatile GLuint*>(c, data_size, immediate_data_size);
if (textures == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoGenTextures(n, textures);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGenTransformFeedbacksImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GenTransformFeedbacksImmediate& c =
*static_cast<const volatile gles2::cmds::GenTransformFeedbacksImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile GLuint* ids =
GetImmediateDataAs<volatile GLuint*>(c, data_size, immediate_data_size);
if (ids == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoGenTransformFeedbacks(n, ids);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetBooleanv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetBooleanv& c =
*static_cast<const volatile gles2::cmds::GetBooleanv*>(cmd_data);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetBooleanv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLboolean* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error = DoGetBooleanv(pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetBufferParameteri64v(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GetBufferParameteri64v& c =
*static_cast<const volatile gles2::cmds::GetBufferParameteri64v*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetBufferParameteri64v::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint64* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetBufferParameteri64v(target, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetBufferParameteriv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetBufferParameteriv& c =
*static_cast<const volatile gles2::cmds::GetBufferParameteriv*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetBufferParameteriv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetBufferParameteriv(target, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetError(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetError& c =
*static_cast<const volatile gles2::cmds::GetError*>(cmd_data);
typedef cmds::GetError::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoGetError(result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetFloatv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetFloatv& c =
*static_cast<const volatile gles2::cmds::GetFloatv*>(cmd_data);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetFloatv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLfloat* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error = DoGetFloatv(pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleGetFramebufferAttachmentParameteriv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetFramebufferAttachmentParameteriv& c =
*static_cast<
const volatile gles2::cmds::GetFramebufferAttachmentParameteriv*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum attachment = static_cast<GLenum>(c.attachment);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetFramebufferAttachmentParameteriv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error = DoGetFramebufferAttachmentParameteriv(
target, attachment, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetInteger64v(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GetInteger64v& c =
*static_cast<const volatile gles2::cmds::GetInteger64v*>(cmd_data);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetInteger64v::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint64* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error = DoGetInteger64v(pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetIntegeri_v(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GetIntegeri_v& c =
*static_cast<const volatile gles2::cmds::GetIntegeri_v*>(cmd_data);
GLenum pname = static_cast<GLenum>(c.pname);
GLuint index = static_cast<GLuint>(c.index);
unsigned int buffer_size = 0;
typedef cmds::GetIntegeri_v::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.data_shm_id, c.data_shm_offset, sizeof(Result), &buffer_size);
GLint* data = result ? result->GetData() : NULL;
if (data == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error = DoGetIntegeri_v(pname, index, bufsize, length, data);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetInteger64i_v(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GetInteger64i_v& c =
*static_cast<const volatile gles2::cmds::GetInteger64i_v*>(cmd_data);
GLenum pname = static_cast<GLenum>(c.pname);
GLuint index = static_cast<GLuint>(c.index);
unsigned int buffer_size = 0;
typedef cmds::GetInteger64i_v::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.data_shm_id, c.data_shm_offset, sizeof(Result), &buffer_size);
GLint64* data = result ? result->GetData() : NULL;
if (data == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error = DoGetInteger64i_v(pname, index, bufsize, length, data);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetIntegerv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetIntegerv& c =
*static_cast<const volatile gles2::cmds::GetIntegerv*>(cmd_data);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetIntegerv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error = DoGetIntegerv(pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetProgramiv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetProgramiv& c =
*static_cast<const volatile gles2::cmds::GetProgramiv*>(cmd_data);
GLuint program = c.program;
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetProgramiv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error = DoGetProgramiv(program, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetRenderbufferParameteriv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetRenderbufferParameteriv& c =
*static_cast<const volatile gles2::cmds::GetRenderbufferParameteriv*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetRenderbufferParameteriv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetRenderbufferParameteriv(target, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetSamplerParameterfv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GetSamplerParameterfv& c =
*static_cast<const volatile gles2::cmds::GetSamplerParameterfv*>(
cmd_data);
GLuint sampler = c.sampler;
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetSamplerParameterfv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLfloat* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetSamplerParameterfv(sampler, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetSamplerParameteriv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GetSamplerParameteriv& c =
*static_cast<const volatile gles2::cmds::GetSamplerParameteriv*>(
cmd_data);
GLuint sampler = c.sampler;
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetSamplerParameteriv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetSamplerParameteriv(sampler, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetShaderiv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetShaderiv& c =
*static_cast<const volatile gles2::cmds::GetShaderiv*>(cmd_data);
GLuint shader = c.shader;
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetShaderiv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error = DoGetShaderiv(shader, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetSynciv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GetSynciv& c =
*static_cast<const volatile gles2::cmds::GetSynciv*>(cmd_data);
GLuint sync = static_cast<GLuint>(c.sync);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetSynciv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.values_shm_id, c.values_shm_offset, sizeof(Result), &buffer_size);
GLint* values = result ? result->GetData() : NULL;
if (values == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error = DoGetSynciv(sync, pname, bufsize, length, values);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetTexParameterfv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetTexParameterfv& c =
*static_cast<const volatile gles2::cmds::GetTexParameterfv*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetTexParameterfv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLfloat* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetTexParameterfv(target, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetTexParameteriv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetTexParameteriv& c =
*static_cast<const volatile gles2::cmds::GetTexParameteriv*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetTexParameteriv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetTexParameteriv(target, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetVertexAttribfv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetVertexAttribfv& c =
*static_cast<const volatile gles2::cmds::GetVertexAttribfv*>(cmd_data);
GLuint index = static_cast<GLuint>(c.index);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetVertexAttribfv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLfloat* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetVertexAttribfv(index, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetVertexAttribiv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetVertexAttribiv& c =
*static_cast<const volatile gles2::cmds::GetVertexAttribiv*>(cmd_data);
GLuint index = static_cast<GLuint>(c.index);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetVertexAttribiv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetVertexAttribiv(index, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetVertexAttribIiv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GetVertexAttribIiv& c =
*static_cast<const volatile gles2::cmds::GetVertexAttribIiv*>(cmd_data);
GLuint index = static_cast<GLuint>(c.index);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetVertexAttribIiv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetVertexAttribIiv(index, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetVertexAttribIuiv(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GetVertexAttribIuiv& c =
*static_cast<const volatile gles2::cmds::GetVertexAttribIuiv*>(cmd_data);
GLuint index = static_cast<GLuint>(c.index);
GLenum pname = static_cast<GLenum>(c.pname);
unsigned int buffer_size = 0;
typedef cmds::GetVertexAttribIuiv::Result Result;
Result* result = GetSharedMemoryAndSizeAs<Result*>(
c.params_shm_id, c.params_shm_offset, sizeof(Result), &buffer_size);
GLuint* params = result ? result->GetData() : NULL;
if (params == NULL) {
return error::kOutOfBounds;
}
GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
GLsizei written_values = 0;
GLsizei* length = &written_values;
error::Error error =
DoGetVertexAttribIuiv(index, pname, bufsize, length, params);
if (error != error::kNoError) {
return error;
}
if (written_values > bufsize) {
return error::kOutOfBounds;
}
result->SetNumResults(written_values);
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleHint(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Hint& c =
*static_cast<const volatile gles2::cmds::Hint*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum mode = static_cast<GLenum>(c.mode);
error::Error error = DoHint(target, mode);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleInvalidateFramebufferImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::InvalidateFramebufferImmediate& c =
*static_cast<const volatile gles2::cmds::InvalidateFramebufferImmediate*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLenum, 1>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLenum* attachments =
GetImmediateDataAs<volatile const GLenum*>(c, data_size,
immediate_data_size);
if (attachments == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoInvalidateFramebuffer(target, count, attachments);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleInvalidateSubFramebufferImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::InvalidateSubFramebufferImmediate& c =
*static_cast<
const volatile gles2::cmds::InvalidateSubFramebufferImmediate*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLenum, 1>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLenum* attachments =
GetImmediateDataAs<volatile const GLenum*>(c, data_size,
immediate_data_size);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
if (attachments == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoInvalidateSubFramebuffer(target, count, attachments, x,
y, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsBuffer(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::IsBuffer& c =
*static_cast<const volatile gles2::cmds::IsBuffer*>(cmd_data);
GLuint buffer = c.buffer;
typedef cmds::IsBuffer::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsBuffer(buffer, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsEnabled(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::IsEnabled& c =
*static_cast<const volatile gles2::cmds::IsEnabled*>(cmd_data);
GLenum cap = static_cast<GLenum>(c.cap);
typedef cmds::IsEnabled::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsEnabled(cap, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsFramebuffer(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::IsFramebuffer& c =
*static_cast<const volatile gles2::cmds::IsFramebuffer*>(cmd_data);
GLuint framebuffer = c.framebuffer;
typedef cmds::IsFramebuffer::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsFramebuffer(framebuffer, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsProgram(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::IsProgram& c =
*static_cast<const volatile gles2::cmds::IsProgram*>(cmd_data);
GLuint program = c.program;
typedef cmds::IsProgram::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsProgram(program, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsRenderbuffer(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::IsRenderbuffer& c =
*static_cast<const volatile gles2::cmds::IsRenderbuffer*>(cmd_data);
GLuint renderbuffer = c.renderbuffer;
typedef cmds::IsRenderbuffer::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsRenderbuffer(renderbuffer, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsSampler(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::IsSampler& c =
*static_cast<const volatile gles2::cmds::IsSampler*>(cmd_data);
GLuint sampler = c.sampler;
typedef cmds::IsSampler::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsSampler(sampler, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsShader(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::IsShader& c =
*static_cast<const volatile gles2::cmds::IsShader*>(cmd_data);
GLuint shader = c.shader;
typedef cmds::IsShader::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsShader(shader, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsSync(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::IsSync& c =
*static_cast<const volatile gles2::cmds::IsSync*>(cmd_data);
GLuint sync = c.sync;
typedef cmds::IsSync::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsSync(sync, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsTexture(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::IsTexture& c =
*static_cast<const volatile gles2::cmds::IsTexture*>(cmd_data);
GLuint texture = c.texture;
typedef cmds::IsTexture::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsTexture(texture, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsTransformFeedback(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::IsTransformFeedback& c =
*static_cast<const volatile gles2::cmds::IsTransformFeedback*>(cmd_data);
GLuint transformfeedback = c.transformfeedback;
typedef cmds::IsTransformFeedback::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsTransformFeedback(transformfeedback, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleLineWidth(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::LineWidth& c =
*static_cast<const volatile gles2::cmds::LineWidth*>(cmd_data);
GLfloat width = static_cast<GLfloat>(c.width);
error::Error error = DoLineWidth(width);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleLinkProgram(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::LinkProgram& c =
*static_cast<const volatile gles2::cmds::LinkProgram*>(cmd_data);
GLuint program = c.program;
error::Error error = DoLinkProgram(program);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandlePauseTransformFeedback(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
error::Error error = DoPauseTransformFeedback();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandlePolygonOffset(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::PolygonOffset& c =
*static_cast<const volatile gles2::cmds::PolygonOffset*>(cmd_data);
GLfloat factor = static_cast<GLfloat>(c.factor);
GLfloat units = static_cast<GLfloat>(c.units);
error::Error error = DoPolygonOffset(factor, units);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleReadBuffer(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::ReadBuffer& c =
*static_cast<const volatile gles2::cmds::ReadBuffer*>(cmd_data);
GLenum src = static_cast<GLenum>(c.src);
error::Error error = DoReadBuffer(src);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleReleaseShaderCompiler(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
error::Error error = DoReleaseShaderCompiler();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleRenderbufferStorage(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::RenderbufferStorage& c =
*static_cast<const volatile gles2::cmds::RenderbufferStorage*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum internalformat = static_cast<GLenum>(c.internalformat);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
error::Error error =
DoRenderbufferStorage(target, internalformat, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleResumeTransformFeedback(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
error::Error error = DoResumeTransformFeedback();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleSampleCoverage(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::SampleCoverage& c =
*static_cast<const volatile gles2::cmds::SampleCoverage*>(cmd_data);
GLclampf value = static_cast<GLclampf>(c.value);
GLboolean invert = static_cast<GLboolean>(c.invert);
error::Error error = DoSampleCoverage(value, invert);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleSamplerParameterf(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::SamplerParameterf& c =
*static_cast<const volatile gles2::cmds::SamplerParameterf*>(cmd_data);
GLuint sampler = c.sampler;
GLenum pname = static_cast<GLenum>(c.pname);
GLfloat param = static_cast<GLfloat>(c.param);
error::Error error = DoSamplerParameterf(sampler, pname, param);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleSamplerParameterfvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::SamplerParameterfvImmediate& c =
*static_cast<const volatile gles2::cmds::SamplerParameterfvImmediate*>(
cmd_data);
GLuint sampler = c.sampler;
GLenum pname = static_cast<GLenum>(c.pname);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLfloat, 1>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* params = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (params == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoSamplerParameterfv(sampler, pname, params);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleSamplerParameteri(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::SamplerParameteri& c =
*static_cast<const volatile gles2::cmds::SamplerParameteri*>(cmd_data);
GLuint sampler = c.sampler;
GLenum pname = static_cast<GLenum>(c.pname);
GLint param = static_cast<GLint>(c.param);
error::Error error = DoSamplerParameteri(sampler, pname, param);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleSamplerParameterivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::SamplerParameterivImmediate& c =
*static_cast<const volatile gles2::cmds::SamplerParameterivImmediate*>(
cmd_data);
GLuint sampler = c.sampler;
GLenum pname = static_cast<GLenum>(c.pname);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLint, 1>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLint* params = GetImmediateDataAs<volatile const GLint*>(
c, data_size, immediate_data_size);
if (params == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoSamplerParameteriv(sampler, pname, params);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleScissor(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Scissor& c =
*static_cast<const volatile gles2::cmds::Scissor*>(cmd_data);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
error::Error error = DoScissor(x, y, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleShaderSourceBucket(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::ShaderSourceBucket& c =
*static_cast<const volatile gles2::cmds::ShaderSourceBucket*>(cmd_data);
GLuint shader = static_cast<GLuint>(c.shader);
Bucket* bucket = GetBucket(c.str_bucket_id);
if (!bucket) {
return error::kInvalidArguments;
}
GLsizei count = 0;
std::vector<char*> strs;
std::vector<GLint> len;
if (!bucket->GetAsStrings(&count, &strs, &len)) {
return error::kInvalidArguments;
}
const char** str =
strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
const GLint* length =
len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
(void)length;
error::Error error = DoShaderSource(shader, count, str, length);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleStencilFunc(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::StencilFunc& c =
*static_cast<const volatile gles2::cmds::StencilFunc*>(cmd_data);
GLenum func = static_cast<GLenum>(c.func);
GLint ref = static_cast<GLint>(c.ref);
GLuint mask = static_cast<GLuint>(c.mask);
error::Error error = DoStencilFunc(func, ref, mask);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleStencilFuncSeparate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::StencilFuncSeparate& c =
*static_cast<const volatile gles2::cmds::StencilFuncSeparate*>(cmd_data);
GLenum face = static_cast<GLenum>(c.face);
GLenum func = static_cast<GLenum>(c.func);
GLint ref = static_cast<GLint>(c.ref);
GLuint mask = static_cast<GLuint>(c.mask);
error::Error error = DoStencilFuncSeparate(face, func, ref, mask);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleStencilMask(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::StencilMask& c =
*static_cast<const volatile gles2::cmds::StencilMask*>(cmd_data);
GLuint mask = static_cast<GLuint>(c.mask);
error::Error error = DoStencilMask(mask);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleStencilMaskSeparate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::StencilMaskSeparate& c =
*static_cast<const volatile gles2::cmds::StencilMaskSeparate*>(cmd_data);
GLenum face = static_cast<GLenum>(c.face);
GLuint mask = static_cast<GLuint>(c.mask);
error::Error error = DoStencilMaskSeparate(face, mask);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleStencilOp(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::StencilOp& c =
*static_cast<const volatile gles2::cmds::StencilOp*>(cmd_data);
GLenum fail = static_cast<GLenum>(c.fail);
GLenum zfail = static_cast<GLenum>(c.zfail);
GLenum zpass = static_cast<GLenum>(c.zpass);
error::Error error = DoStencilOp(fail, zfail, zpass);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleStencilOpSeparate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::StencilOpSeparate& c =
*static_cast<const volatile gles2::cmds::StencilOpSeparate*>(cmd_data);
GLenum face = static_cast<GLenum>(c.face);
GLenum fail = static_cast<GLenum>(c.fail);
GLenum zfail = static_cast<GLenum>(c.zfail);
GLenum zpass = static_cast<GLenum>(c.zpass);
error::Error error = DoStencilOpSeparate(face, fail, zfail, zpass);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleTexParameterf(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::TexParameterf& c =
*static_cast<const volatile gles2::cmds::TexParameterf*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum pname = static_cast<GLenum>(c.pname);
GLfloat param = static_cast<GLfloat>(c.param);
error::Error error = DoTexParameterf(target, pname, param);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleTexParameterfvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::TexParameterfvImmediate& c =
*static_cast<const volatile gles2::cmds::TexParameterfvImmediate*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum pname = static_cast<GLenum>(c.pname);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLfloat, 1>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* params = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (params == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoTexParameterfv(target, pname, params);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleTexParameteri(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::TexParameteri& c =
*static_cast<const volatile gles2::cmds::TexParameteri*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum pname = static_cast<GLenum>(c.pname);
GLint param = static_cast<GLint>(c.param);
error::Error error = DoTexParameteri(target, pname, param);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleTexParameterivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::TexParameterivImmediate& c =
*static_cast<const volatile gles2::cmds::TexParameterivImmediate*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum pname = static_cast<GLenum>(c.pname);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLint, 1>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLint* params = GetImmediateDataAs<volatile const GLint*>(
c, data_size, immediate_data_size);
if (params == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoTexParameteriv(target, pname, params);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleTexStorage3D(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::TexStorage3D& c =
*static_cast<const volatile gles2::cmds::TexStorage3D*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLsizei levels = static_cast<GLsizei>(c.levels);
GLenum internalFormat = static_cast<GLenum>(c.internalFormat);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
GLsizei depth = static_cast<GLsizei>(c.depth);
error::Error error =
DoTexStorage3D(target, levels, internalFormat, width, height, depth);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleTransformFeedbackVaryingsBucket(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::TransformFeedbackVaryingsBucket& c = *static_cast<
const volatile gles2::cmds::TransformFeedbackVaryingsBucket*>(cmd_data);
GLuint program = static_cast<GLuint>(c.program);
Bucket* bucket = GetBucket(c.varyings_bucket_id);
if (!bucket) {
return error::kInvalidArguments;
}
GLsizei count = 0;
std::vector<char*> strs;
std::vector<GLint> len;
if (!bucket->GetAsStrings(&count, &strs, &len)) {
return error::kInvalidArguments;
}
const char** varyings =
strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
const GLint* length =
len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
(void)length;
GLenum buffermode = static_cast<GLenum>(c.buffermode);
error::Error error =
DoTransformFeedbackVaryings(program, count, varyings, buffermode);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform1f(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform1f& c =
*static_cast<const volatile gles2::cmds::Uniform1f*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLfloat x = static_cast<GLfloat>(c.x);
error::Error error = DoUniform1f(location, x);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform1fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform1fvImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform1fvImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 1>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* v = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform1fv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform1i(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform1i& c =
*static_cast<const volatile gles2::cmds::Uniform1i*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLint x = static_cast<GLint>(c.x);
error::Error error = DoUniform1i(location, x);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform1ivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform1ivImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform1ivImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLint, 1>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLint* v = GetImmediateDataAs<volatile const GLint*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform1iv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform1ui(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::Uniform1ui& c =
*static_cast<const volatile gles2::cmds::Uniform1ui*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLuint x = static_cast<GLuint>(c.x);
error::Error error = DoUniform1ui(location, x);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform1uivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::Uniform1uivImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform1uivImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLuint, 1>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLuint* v = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform1uiv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform2f(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform2f& c =
*static_cast<const volatile gles2::cmds::Uniform2f*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLfloat x = static_cast<GLfloat>(c.x);
GLfloat y = static_cast<GLfloat>(c.y);
error::Error error = DoUniform2f(location, x, y);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform2fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform2fvImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform2fvImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 2>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* v = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform2fv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform2i(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform2i& c =
*static_cast<const volatile gles2::cmds::Uniform2i*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
error::Error error = DoUniform2i(location, x, y);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform2ivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform2ivImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform2ivImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLint, 2>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLint* v = GetImmediateDataAs<volatile const GLint*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform2iv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform2ui(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::Uniform2ui& c =
*static_cast<const volatile gles2::cmds::Uniform2ui*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLuint x = static_cast<GLuint>(c.x);
GLuint y = static_cast<GLuint>(c.y);
error::Error error = DoUniform2ui(location, x, y);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform2uivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::Uniform2uivImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform2uivImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLuint, 2>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLuint* v = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform2uiv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform3f(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform3f& c =
*static_cast<const volatile gles2::cmds::Uniform3f*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLfloat x = static_cast<GLfloat>(c.x);
GLfloat y = static_cast<GLfloat>(c.y);
GLfloat z = static_cast<GLfloat>(c.z);
error::Error error = DoUniform3f(location, x, y, z);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform3fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform3fvImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform3fvImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 3>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* v = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform3fv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform3i(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform3i& c =
*static_cast<const volatile gles2::cmds::Uniform3i*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLint z = static_cast<GLint>(c.z);
error::Error error = DoUniform3i(location, x, y, z);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform3ivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform3ivImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform3ivImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLint, 3>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLint* v = GetImmediateDataAs<volatile const GLint*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform3iv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform3ui(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::Uniform3ui& c =
*static_cast<const volatile gles2::cmds::Uniform3ui*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLuint x = static_cast<GLuint>(c.x);
GLuint y = static_cast<GLuint>(c.y);
GLuint z = static_cast<GLuint>(c.z);
error::Error error = DoUniform3ui(location, x, y, z);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform3uivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::Uniform3uivImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform3uivImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLuint, 3>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLuint* v = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform3uiv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform4f(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform4f& c =
*static_cast<const volatile gles2::cmds::Uniform4f*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLfloat x = static_cast<GLfloat>(c.x);
GLfloat y = static_cast<GLfloat>(c.y);
GLfloat z = static_cast<GLfloat>(c.z);
GLfloat w = static_cast<GLfloat>(c.w);
error::Error error = DoUniform4f(location, x, y, z, w);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform4fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform4fvImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform4fvImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 4>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* v = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform4fv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform4i(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform4i& c =
*static_cast<const volatile gles2::cmds::Uniform4i*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLint z = static_cast<GLint>(c.z);
GLint w = static_cast<GLint>(c.w);
error::Error error = DoUniform4i(location, x, y, z, w);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform4ivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Uniform4ivImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform4ivImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLint, 4>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLint* v = GetImmediateDataAs<volatile const GLint*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform4iv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform4ui(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::Uniform4ui& c =
*static_cast<const volatile gles2::cmds::Uniform4ui*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLuint x = static_cast<GLuint>(c.x);
GLuint y = static_cast<GLuint>(c.y);
GLuint z = static_cast<GLuint>(c.z);
GLuint w = static_cast<GLuint>(c.w);
error::Error error = DoUniform4ui(location, x, y, z, w);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniform4uivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::Uniform4uivImmediate& c =
*static_cast<const volatile gles2::cmds::Uniform4uivImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLuint, 4>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLuint* v = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (v == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniform4uiv(location, count, v);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniformMatrix2fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::UniformMatrix2fvImmediate& c =
*static_cast<const volatile gles2::cmds::UniformMatrix2fvImmediate*>(
cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
GLboolean transpose = static_cast<GLboolean>(c.transpose);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 4>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* value = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniformMatrix2fv(location, count, transpose, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniformMatrix2x3fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::UniformMatrix2x3fvImmediate& c =
*static_cast<const volatile gles2::cmds::UniformMatrix2x3fvImmediate*>(
cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
GLboolean transpose = static_cast<GLboolean>(c.transpose);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 6>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* value = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniformMatrix2x3fv(location, count, transpose, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniformMatrix2x4fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::UniformMatrix2x4fvImmediate& c =
*static_cast<const volatile gles2::cmds::UniformMatrix2x4fvImmediate*>(
cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
GLboolean transpose = static_cast<GLboolean>(c.transpose);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 8>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* value = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniformMatrix2x4fv(location, count, transpose, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniformMatrix3fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::UniformMatrix3fvImmediate& c =
*static_cast<const volatile gles2::cmds::UniformMatrix3fvImmediate*>(
cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
GLboolean transpose = static_cast<GLboolean>(c.transpose);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 9>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* value = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniformMatrix3fv(location, count, transpose, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniformMatrix3x2fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::UniformMatrix3x2fvImmediate& c =
*static_cast<const volatile gles2::cmds::UniformMatrix3x2fvImmediate*>(
cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
GLboolean transpose = static_cast<GLboolean>(c.transpose);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 6>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* value = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniformMatrix3x2fv(location, count, transpose, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniformMatrix3x4fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::UniformMatrix3x4fvImmediate& c =
*static_cast<const volatile gles2::cmds::UniformMatrix3x4fvImmediate*>(
cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
GLboolean transpose = static_cast<GLboolean>(c.transpose);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 12>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* value = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniformMatrix3x4fv(location, count, transpose, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniformMatrix4fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::UniformMatrix4fvImmediate& c =
*static_cast<const volatile gles2::cmds::UniformMatrix4fvImmediate*>(
cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
GLboolean transpose = static_cast<GLboolean>(c.transpose);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 16>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* value = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniformMatrix4fv(location, count, transpose, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniformMatrix4x2fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::UniformMatrix4x2fvImmediate& c =
*static_cast<const volatile gles2::cmds::UniformMatrix4x2fvImmediate*>(
cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
GLboolean transpose = static_cast<GLboolean>(c.transpose);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 8>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* value = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniformMatrix4x2fv(location, count, transpose, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUniformMatrix4x3fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::UniformMatrix4x3fvImmediate& c =
*static_cast<const volatile gles2::cmds::UniformMatrix4x3fvImmediate*>(
cmd_data);
GLint location = static_cast<GLint>(c.location);
GLsizei count = static_cast<GLsizei>(c.count);
GLboolean transpose = static_cast<GLboolean>(c.transpose);
uint32_t data_size = 0;
if (count >= 0 &&
!GLES2Util::ComputeDataSize<GLfloat, 12>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* value = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (value == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniformMatrix4x3fv(location, count, transpose, value);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleUseProgram(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::UseProgram& c =
*static_cast<const volatile gles2::cmds::UseProgram*>(cmd_data);
GLuint program = c.program;
error::Error error = DoUseProgram(program);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleValidateProgram(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::ValidateProgram& c =
*static_cast<const volatile gles2::cmds::ValidateProgram*>(cmd_data);
GLuint program = c.program;
error::Error error = DoValidateProgram(program);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttrib1f(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::VertexAttrib1f& c =
*static_cast<const volatile gles2::cmds::VertexAttrib1f*>(cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
GLfloat x = static_cast<GLfloat>(c.x);
error::Error error = DoVertexAttrib1f(indx, x);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttrib1fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::VertexAttrib1fvImmediate& c =
*static_cast<const volatile gles2::cmds::VertexAttrib1fvImmediate*>(
cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLfloat, 1>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* values = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (values == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoVertexAttrib1fv(indx, values);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttrib2f(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::VertexAttrib2f& c =
*static_cast<const volatile gles2::cmds::VertexAttrib2f*>(cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
GLfloat x = static_cast<GLfloat>(c.x);
GLfloat y = static_cast<GLfloat>(c.y);
error::Error error = DoVertexAttrib2f(indx, x, y);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttrib2fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::VertexAttrib2fvImmediate& c =
*static_cast<const volatile gles2::cmds::VertexAttrib2fvImmediate*>(
cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLfloat, 2>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* values = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (values == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoVertexAttrib2fv(indx, values);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttrib3f(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::VertexAttrib3f& c =
*static_cast<const volatile gles2::cmds::VertexAttrib3f*>(cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
GLfloat x = static_cast<GLfloat>(c.x);
GLfloat y = static_cast<GLfloat>(c.y);
GLfloat z = static_cast<GLfloat>(c.z);
error::Error error = DoVertexAttrib3f(indx, x, y, z);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttrib3fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::VertexAttrib3fvImmediate& c =
*static_cast<const volatile gles2::cmds::VertexAttrib3fvImmediate*>(
cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLfloat, 3>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* values = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (values == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoVertexAttrib3fv(indx, values);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttrib4f(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::VertexAttrib4f& c =
*static_cast<const volatile gles2::cmds::VertexAttrib4f*>(cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
GLfloat x = static_cast<GLfloat>(c.x);
GLfloat y = static_cast<GLfloat>(c.y);
GLfloat z = static_cast<GLfloat>(c.z);
GLfloat w = static_cast<GLfloat>(c.w);
error::Error error = DoVertexAttrib4f(indx, x, y, z, w);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttrib4fvImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::VertexAttrib4fvImmediate& c =
*static_cast<const volatile gles2::cmds::VertexAttrib4fvImmediate*>(
cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLfloat, 4>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* values = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (values == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoVertexAttrib4fv(indx, values);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttribI4i(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::VertexAttribI4i& c =
*static_cast<const volatile gles2::cmds::VertexAttribI4i*>(cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLint z = static_cast<GLint>(c.z);
GLint w = static_cast<GLint>(c.w);
error::Error error = DoVertexAttribI4i(indx, x, y, z, w);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttribI4ivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::VertexAttribI4ivImmediate& c =
*static_cast<const volatile gles2::cmds::VertexAttribI4ivImmediate*>(
cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLint, 4>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLint* values = GetImmediateDataAs<volatile const GLint*>(
c, data_size, immediate_data_size);
if (values == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoVertexAttribI4iv(indx, values);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttribI4ui(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::VertexAttribI4ui& c =
*static_cast<const volatile gles2::cmds::VertexAttribI4ui*>(cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
GLuint x = static_cast<GLuint>(c.x);
GLuint y = static_cast<GLuint>(c.y);
GLuint z = static_cast<GLuint>(c.z);
GLuint w = static_cast<GLuint>(c.w);
error::Error error = DoVertexAttribI4ui(indx, x, y, z, w);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleVertexAttribI4uivImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::VertexAttribI4uivImmediate& c =
*static_cast<const volatile gles2::cmds::VertexAttribI4uivImmediate*>(
cmd_data);
GLuint indx = static_cast<GLuint>(c.indx);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLuint, 4>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLuint* values = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (values == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoVertexAttribI4uiv(indx, values);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleViewport(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::Viewport& c =
*static_cast<const volatile gles2::cmds::Viewport*>(cmd_data);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
error::Error error = DoViewport(x, y, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBlitFramebufferCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BlitFramebufferCHROMIUM& c =
*static_cast<const volatile gles2::cmds::BlitFramebufferCHROMIUM*>(
cmd_data);
if (!features().chromium_framebuffer_multisample) {
return error::kUnknownCommand;
}
GLint srcX0 = static_cast<GLint>(c.srcX0);
GLint srcY0 = static_cast<GLint>(c.srcY0);
GLint srcX1 = static_cast<GLint>(c.srcX1);
GLint srcY1 = static_cast<GLint>(c.srcY1);
GLint dstX0 = static_cast<GLint>(c.dstX0);
GLint dstY0 = static_cast<GLint>(c.dstY0);
GLint dstX1 = static_cast<GLint>(c.dstX1);
GLint dstY1 = static_cast<GLint>(c.dstY1);
GLbitfield mask = static_cast<GLbitfield>(c.mask);
GLenum filter = static_cast<GLenum>(c.filter);
error::Error error = DoBlitFramebufferCHROMIUM(
srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleRenderbufferStorageMultisampleCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::RenderbufferStorageMultisampleCHROMIUM& c =
*static_cast<
const volatile gles2::cmds::RenderbufferStorageMultisampleCHROMIUM*>(
cmd_data);
if (!features().chromium_framebuffer_multisample) {
return error::kUnknownCommand;
}
GLenum target = static_cast<GLenum>(c.target);
GLsizei samples = static_cast<GLsizei>(c.samples);
GLenum internalformat = static_cast<GLenum>(c.internalformat);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
error::Error error = DoRenderbufferStorageMultisampleCHROMIUM(
target, samples, internalformat, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleRenderbufferStorageMultisampleEXT(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::RenderbufferStorageMultisampleEXT& c =
*static_cast<
const volatile gles2::cmds::RenderbufferStorageMultisampleEXT*>(
cmd_data);
if (!features().multisampled_render_to_texture) {
return error::kUnknownCommand;
}
GLenum target = static_cast<GLenum>(c.target);
GLsizei samples = static_cast<GLsizei>(c.samples);
GLenum internalformat = static_cast<GLenum>(c.internalformat);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
error::Error error = DoRenderbufferStorageMultisampleEXT(
target, samples, internalformat, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleFramebufferTexture2DMultisampleEXT(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::FramebufferTexture2DMultisampleEXT& c =
*static_cast<
const volatile gles2::cmds::FramebufferTexture2DMultisampleEXT*>(
cmd_data);
if (!features().multisampled_render_to_texture) {
return error::kUnknownCommand;
}
GLenum target = static_cast<GLenum>(c.target);
GLenum attachment = static_cast<GLenum>(c.attachment);
GLenum textarget = static_cast<GLenum>(c.textarget);
GLuint texture = c.texture;
GLint level = static_cast<GLint>(c.level);
GLsizei samples = static_cast<GLsizei>(c.samples);
error::Error error = DoFramebufferTexture2DMultisampleEXT(
target, attachment, textarget, texture, level, samples);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleTexStorage2DEXT(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::TexStorage2DEXT& c =
*static_cast<const volatile gles2::cmds::TexStorage2DEXT*>(cmd_data);
if (!features().ext_texture_storage) {
return error::kUnknownCommand;
}
GLenum target = static_cast<GLenum>(c.target);
GLsizei levels = static_cast<GLsizei>(c.levels);
GLenum internalFormat = static_cast<GLenum>(c.internalFormat);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
error::Error error =
DoTexStorage2DEXT(target, levels, internalFormat, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGenQueriesEXTImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GenQueriesEXTImmediate& c =
*static_cast<const volatile gles2::cmds::GenQueriesEXTImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile GLuint* queries =
GetImmediateDataAs<volatile GLuint*>(c, data_size, immediate_data_size);
if (queries == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoGenQueriesEXT(n, queries);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDeleteQueriesEXTImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DeleteQueriesEXTImmediate& c =
*static_cast<const volatile gles2::cmds::DeleteQueriesEXTImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile const GLuint* queries = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (queries == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoDeleteQueriesEXT(n, queries);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBeginTransformFeedback(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::BeginTransformFeedback& c =
*static_cast<const volatile gles2::cmds::BeginTransformFeedback*>(
cmd_data);
GLenum primitivemode = static_cast<GLenum>(c.primitivemode);
error::Error error = DoBeginTransformFeedback(primitivemode);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleEndTransformFeedback(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
error::Error error = DoEndTransformFeedback();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandlePopGroupMarkerEXT(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
error::Error error = DoPopGroupMarkerEXT();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGenVertexArraysOESImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GenVertexArraysOESImmediate& c =
*static_cast<const volatile gles2::cmds::GenVertexArraysOESImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile GLuint* arrays =
GetImmediateDataAs<volatile GLuint*>(c, data_size, immediate_data_size);
if (arrays == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoGenVertexArraysOES(n, arrays);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDeleteVertexArraysOESImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DeleteVertexArraysOESImmediate& c =
*static_cast<const volatile gles2::cmds::DeleteVertexArraysOESImmediate*>(
cmd_data);
GLsizei n = static_cast<GLsizei>(c.n);
uint32_t data_size;
if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
return error::kOutOfBounds;
}
volatile const GLuint* arrays = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (arrays == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoDeleteVertexArraysOES(n, arrays);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsVertexArrayOES(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::IsVertexArrayOES& c =
*static_cast<const volatile gles2::cmds::IsVertexArrayOES*>(cmd_data);
GLuint array = c.array;
typedef cmds::IsVertexArrayOES::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsVertexArrayOES(array, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBindVertexArrayOES(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BindVertexArrayOES& c =
*static_cast<const volatile gles2::cmds::BindVertexArrayOES*>(cmd_data);
GLuint array = c.array;
error::Error error = DoBindVertexArrayOES(array);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleSwapBuffers(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::SwapBuffers& c =
*static_cast<const volatile gles2::cmds::SwapBuffers*>(cmd_data);
GLuint64 swap_id = c.swap_id();
GLbitfield flags = static_cast<GLbitfield>(c.flags);
error::Error error = DoSwapBuffers(swap_id, flags);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleGetMaxValueInBufferCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::GetMaxValueInBufferCHROMIUM& c =
*static_cast<const volatile gles2::cmds::GetMaxValueInBufferCHROMIUM*>(
cmd_data);
GLuint buffer_id = c.buffer_id;
GLsizei count = static_cast<GLsizei>(c.count);
GLenum type = static_cast<GLenum>(c.type);
GLuint offset = static_cast<GLuint>(c.offset);
typedef cmds::GetMaxValueInBufferCHROMIUM::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error =
DoGetMaxValueInBufferCHROMIUM(buffer_id, count, type, offset, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleFlushMappedBufferRange(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::FlushMappedBufferRange& c =
*static_cast<const volatile gles2::cmds::FlushMappedBufferRange*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLintptr offset = static_cast<GLintptr>(c.offset);
GLsizeiptr size = static_cast<GLsizeiptr>(c.size);
error::Error error = DoFlushMappedBufferRange(target, offset, size);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCopyTextureCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CopyTextureCHROMIUM& c =
*static_cast<const volatile gles2::cmds::CopyTextureCHROMIUM*>(cmd_data);
GLuint source_id = static_cast<GLuint>(c.source_id);
GLint source_level = static_cast<GLint>(c.source_level);
GLenum dest_target = static_cast<GLenum>(c.dest_target);
GLuint dest_id = static_cast<GLuint>(c.dest_id);
GLint dest_level = static_cast<GLint>(c.dest_level);
GLint internalformat = static_cast<GLint>(c.internalformat);
GLenum dest_type = static_cast<GLenum>(c.dest_type);
GLboolean unpack_flip_y = static_cast<GLboolean>(c.unpack_flip_y);
GLboolean unpack_premultiply_alpha =
static_cast<GLboolean>(c.unpack_premultiply_alpha);
GLboolean unpack_unmultiply_alpha =
static_cast<GLboolean>(c.unpack_unmultiply_alpha);
error::Error error = DoCopyTextureCHROMIUM(
source_id, source_level, dest_target, dest_id, dest_level, internalformat,
dest_type, unpack_flip_y, unpack_premultiply_alpha,
unpack_unmultiply_alpha);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCopySubTextureCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CopySubTextureCHROMIUM& c =
*static_cast<const volatile gles2::cmds::CopySubTextureCHROMIUM*>(
cmd_data);
GLuint source_id = static_cast<GLuint>(c.source_id);
GLint source_level = static_cast<GLint>(c.source_level);
GLenum dest_target = static_cast<GLenum>(c.dest_target);
GLuint dest_id = static_cast<GLuint>(c.dest_id);
GLint dest_level = static_cast<GLint>(c.dest_level);
GLint xoffset = static_cast<GLint>(c.xoffset);
GLint yoffset = static_cast<GLint>(c.yoffset);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
GLboolean unpack_flip_y = static_cast<GLboolean>(c.unpack_flip_y);
GLboolean unpack_premultiply_alpha =
static_cast<GLboolean>(c.unpack_premultiply_alpha);
GLboolean unpack_unmultiply_alpha =
static_cast<GLboolean>(c.unpack_unmultiply_alpha);
error::Error error = DoCopySubTextureCHROMIUM(
source_id, source_level, dest_target, dest_id, dest_level, xoffset,
yoffset, x, y, width, height, unpack_flip_y, unpack_premultiply_alpha,
unpack_unmultiply_alpha);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCompressedCopyTextureCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CompressedCopyTextureCHROMIUM& c =
*static_cast<const volatile gles2::cmds::CompressedCopyTextureCHROMIUM*>(
cmd_data);
GLuint source_id = static_cast<GLuint>(c.source_id);
GLuint dest_id = static_cast<GLuint>(c.dest_id);
error::Error error = DoCompressedCopyTextureCHROMIUM(source_id, dest_id);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleProduceTextureDirectCHROMIUMImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::ProduceTextureDirectCHROMIUMImmediate& c =
*static_cast<
const volatile gles2::cmds::ProduceTextureDirectCHROMIUMImmediate*>(
cmd_data);
GLuint texture = c.texture;
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLbyte, 16>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLbyte* mailbox = GetImmediateDataAs<volatile const GLbyte*>(
c, data_size, immediate_data_size);
if (mailbox == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoProduceTextureDirectCHROMIUM(texture, mailbox);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleCreateAndConsumeTextureINTERNALImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CreateAndConsumeTextureINTERNALImmediate& c =
*static_cast<const volatile gles2::cmds::
CreateAndConsumeTextureINTERNALImmediate*>(cmd_data);
GLuint texture = static_cast<GLuint>(c.texture);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLbyte, 16>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLbyte* mailbox = GetImmediateDataAs<volatile const GLbyte*>(
c, data_size, immediate_data_size);
if (mailbox == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoCreateAndConsumeTextureINTERNAL(texture, mailbox);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBindTexImage2DCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BindTexImage2DCHROMIUM& c =
*static_cast<const volatile gles2::cmds::BindTexImage2DCHROMIUM*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLint imageId = static_cast<GLint>(c.imageId);
error::Error error = DoBindTexImage2DCHROMIUM(target, imageId);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleBindTexImage2DWithInternalformatCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::BindTexImage2DWithInternalformatCHROMIUM& c =
*static_cast<const volatile gles2::cmds::
BindTexImage2DWithInternalformatCHROMIUM*>(cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLenum internalformat = static_cast<GLenum>(c.internalformat);
GLint imageId = static_cast<GLint>(c.imageId);
error::Error error = DoBindTexImage2DWithInternalformatCHROMIUM(
target, internalformat, imageId);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleReleaseTexImage2DCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::ReleaseTexImage2DCHROMIUM& c =
*static_cast<const volatile gles2::cmds::ReleaseTexImage2DCHROMIUM*>(
cmd_data);
GLenum target = static_cast<GLenum>(c.target);
GLint imageId = static_cast<GLint>(c.imageId);
error::Error error = DoReleaseTexImage2DCHROMIUM(target, imageId);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleTraceEndCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
error::Error error = DoTraceEndCHROMIUM();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDiscardFramebufferEXTImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DiscardFramebufferEXTImmediate& c =
*static_cast<const volatile gles2::cmds::DiscardFramebufferEXTImmediate*>(
cmd_data);
if (!features().ext_discard_framebuffer) {
return error::kUnknownCommand;
}
GLenum target = static_cast<GLenum>(c.target);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLenum, 1>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLenum* attachments =
GetImmediateDataAs<volatile const GLenum*>(c, data_size,
immediate_data_size);
if (attachments == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoDiscardFramebufferEXT(target, count, attachments);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleLoseContextCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::LoseContextCHROMIUM& c =
*static_cast<const volatile gles2::cmds::LoseContextCHROMIUM*>(cmd_data);
GLenum current = static_cast<GLenum>(c.current);
GLenum other = static_cast<GLenum>(c.other);
error::Error error = DoLoseContextCHROMIUM(current, other);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleUnpremultiplyAndDitherCopyCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::UnpremultiplyAndDitherCopyCHROMIUM& c =
*static_cast<
const volatile gles2::cmds::UnpremultiplyAndDitherCopyCHROMIUM*>(
cmd_data);
if (!features().unpremultiply_and_dither_copy) {
return error::kUnknownCommand;
}
GLuint source_id = static_cast<GLuint>(c.source_id);
GLuint dest_id = static_cast<GLuint>(c.dest_id);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
error::Error error = DoUnpremultiplyAndDitherCopyCHROMIUM(
source_id, dest_id, x, y, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleDrawBuffersEXTImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::DrawBuffersEXTImmediate& c =
*static_cast<const volatile gles2::cmds::DrawBuffersEXTImmediate*>(
cmd_data);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLenum, 1>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLenum* bufs = GetImmediateDataAs<volatile const GLenum*>(
c, data_size, immediate_data_size);
if (bufs == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoDrawBuffersEXT(count, bufs);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleScheduleCALayerInUseQueryCHROMIUMImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::ScheduleCALayerInUseQueryCHROMIUMImmediate& c =
*static_cast<const volatile gles2::cmds::
ScheduleCALayerInUseQueryCHROMIUMImmediate*>(cmd_data);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLuint, 1>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLuint* textures = GetImmediateDataAs<volatile const GLuint*>(
c, data_size, immediate_data_size);
if (textures == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoScheduleCALayerInUseQueryCHROMIUM(count, textures);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCommitOverlayPlanesCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CommitOverlayPlanesCHROMIUM& c =
*static_cast<const volatile gles2::cmds::CommitOverlayPlanesCHROMIUM*>(
cmd_data);
GLuint64 swap_id = c.swap_id();
GLbitfield flags = static_cast<GLbitfield>(c.flags);
error::Error error = DoCommitOverlayPlanesCHROMIUM(swap_id, flags);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleFlushDriverCachesCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
error::Error error = DoFlushDriverCachesCHROMIUM();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleMatrixLoadfCHROMIUMImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::MatrixLoadfCHROMIUMImmediate& c =
*static_cast<const volatile gles2::cmds::MatrixLoadfCHROMIUMImmediate*>(
cmd_data);
if (!features().chromium_path_rendering) {
return error::kUnknownCommand;
}
GLenum matrixMode = static_cast<GLenum>(c.matrixMode);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLfloat, 16>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* m = GetImmediateDataAs<volatile const GLfloat*>(
c, data_size, immediate_data_size);
if (m == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoMatrixLoadfCHROMIUM(matrixMode, m);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleMatrixLoadIdentityCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::MatrixLoadIdentityCHROMIUM& c =
*static_cast<const volatile gles2::cmds::MatrixLoadIdentityCHROMIUM*>(
cmd_data);
if (!features().chromium_path_rendering) {
return error::kUnknownCommand;
}
GLenum matrixMode = static_cast<GLenum>(c.matrixMode);
error::Error error = DoMatrixLoadIdentityCHROMIUM(matrixMode);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleIsPathCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::IsPathCHROMIUM& c =
*static_cast<const volatile gles2::cmds::IsPathCHROMIUM*>(cmd_data);
if (!features().chromium_path_rendering) {
return error::kUnknownCommand;
}
GLuint path = c.path;
typedef cmds::IsPathCHROMIUM::Result Result;
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!result) {
return error::kOutOfBounds;
}
error::Error error = DoIsPathCHROMIUM(path, result);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandlePathStencilFuncCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::PathStencilFuncCHROMIUM& c =
*static_cast<const volatile gles2::cmds::PathStencilFuncCHROMIUM*>(
cmd_data);
if (!features().chromium_path_rendering) {
return error::kUnknownCommand;
}
GLenum func = static_cast<GLenum>(c.func);
GLint ref = static_cast<GLint>(c.ref);
GLuint mask = static_cast<GLuint>(c.mask);
error::Error error = DoPathStencilFuncCHROMIUM(func, ref, mask);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleCoverageModulationCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::CoverageModulationCHROMIUM& c =
*static_cast<const volatile gles2::cmds::CoverageModulationCHROMIUM*>(
cmd_data);
if (!features().chromium_framebuffer_mixed_samples) {
return error::kUnknownCommand;
}
GLenum components = static_cast<GLenum>(c.components);
error::Error error = DoCoverageModulationCHROMIUM(components);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleBlendBarrierKHR(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!features().blend_equation_advanced) {
return error::kUnknownCommand;
}
error::Error error = DoBlendBarrierKHR();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleApplyScreenSpaceAntialiasingCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!features().chromium_screen_space_antialiasing) {
return error::kUnknownCommand;
}
error::Error error = DoApplyScreenSpaceAntialiasingCHROMIUM();
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::
HandleUniformMatrix4fvStreamTextureMatrixCHROMIUMImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::
UniformMatrix4fvStreamTextureMatrixCHROMIUMImmediate& c = *static_cast<
const volatile gles2::cmds::
UniformMatrix4fvStreamTextureMatrixCHROMIUMImmediate*>(cmd_data);
GLint location = static_cast<GLint>(c.location);
GLboolean transpose = static_cast<GLboolean>(c.transpose);
uint32_t data_size;
if (!GLES2Util::ComputeDataSize<GLfloat, 16>(1, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLfloat* transform =
GetImmediateDataAs<volatile const GLfloat*>(c, data_size,
immediate_data_size);
if (transform == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoUniformMatrix4fvStreamTextureMatrixCHROMIUM(
location, transpose, transform);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleOverlayPromotionHintCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::OverlayPromotionHintCHROMIUM& c =
*static_cast<const volatile gles2::cmds::OverlayPromotionHintCHROMIUM*>(
cmd_data);
GLuint texture = c.texture;
GLboolean promotion_hint = static_cast<GLboolean>(c.promotion_hint);
GLint display_x = static_cast<GLint>(c.display_x);
GLint display_y = static_cast<GLint>(c.display_y);
GLint display_width = static_cast<GLint>(c.display_width);
GLint display_height = static_cast<GLint>(c.display_height);
error::Error error =
DoOverlayPromotionHintCHROMIUM(texture, promotion_hint, display_x,
display_y, display_width, display_height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error
GLES2DecoderPassthroughImpl::HandleSwapBuffersWithBoundsCHROMIUMImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::SwapBuffersWithBoundsCHROMIUMImmediate& c =
*static_cast<
const volatile gles2::cmds::SwapBuffersWithBoundsCHROMIUMImmediate*>(
cmd_data);
GLuint64 swap_id = c.swap_id();
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLint, 4>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLint* rects = GetImmediateDataAs<volatile const GLint*>(
c, data_size, immediate_data_size);
GLbitfield flags = static_cast<GLbitfield>(c.flags);
if (rects == nullptr) {
return error::kOutOfBounds;
}
error::Error error =
DoSwapBuffersWithBoundsCHROMIUM(swap_id, count, rects, flags);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleSetDrawRectangleCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::SetDrawRectangleCHROMIUM& c =
*static_cast<const volatile gles2::cmds::SetDrawRectangleCHROMIUM*>(
cmd_data);
GLint x = static_cast<GLint>(c.x);
GLint y = static_cast<GLint>(c.y);
GLint width = static_cast<GLint>(c.width);
GLint height = static_cast<GLint>(c.height);
error::Error error = DoSetDrawRectangleCHROMIUM(x, y, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleSetEnableDCLayersCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::SetEnableDCLayersCHROMIUM& c =
*static_cast<const volatile gles2::cmds::SetEnableDCLayersCHROMIUM*>(
cmd_data);
GLboolean enabled = static_cast<GLboolean>(c.enabled);
error::Error error = DoSetEnableDCLayersCHROMIUM(enabled);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleTexStorage2DImageCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
const volatile gles2::cmds::TexStorage2DImageCHROMIUM& c =
*static_cast<const volatile gles2::cmds::TexStorage2DImageCHROMIUM*>(
cmd_data);
if (!features().chromium_texture_storage_image) {
return error::kUnknownCommand;
}
GLenum target = static_cast<GLenum>(c.target);
GLenum internalFormat = static_cast<GLenum>(c.internalFormat);
GLenum bufferUsage = static_cast<GLenum>(c.bufferUsage);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
error::Error error = DoTexStorage2DImageCHROMIUM(target, internalFormat,
bufferUsage, width, height);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
error::Error GLES2DecoderPassthroughImpl::HandleWindowRectanglesEXTImmediate(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::WindowRectanglesEXTImmediate& c =
*static_cast<const volatile gles2::cmds::WindowRectanglesEXTImmediate*>(
cmd_data);
if (!features().ext_window_rectangles) {
return error::kUnknownCommand;
}
GLenum mode = static_cast<GLenum>(c.mode);
GLsizei count = static_cast<GLsizei>(c.count);
uint32_t data_size = 0;
if (count >= 0 && !GLES2Util::ComputeDataSize<GLint, 4>(count, &data_size)) {
return error::kOutOfBounds;
}
if (data_size > immediate_data_size) {
return error::kOutOfBounds;
}
volatile const GLint* box = GetImmediateDataAs<volatile const GLint*>(
c, data_size, immediate_data_size);
if (box == nullptr) {
return error::kOutOfBounds;
}
error::Error error = DoWindowRectanglesEXT(mode, count, box);
if (error != error::kNoError) {
return error;
}
return error::kNoError;
}
} // namespace gles2
} // namespace gpu
| 35.305357 | 80 | 0.721026 | [
"vector",
"transform"
] |
92950e3ad8701f9eff54afe39db32dec9537b922 | 10,344 | cc | C++ | be/src/statestore/simple-scheduler.cc | wangxnhit/impala | d7a37f00a515d6942ca28bd8cd84380bc8c93c5a | [
"Apache-2.0"
] | 1 | 2016-06-08T06:22:28.000Z | 2016-06-08T06:22:28.000Z | be/src/statestore/simple-scheduler.cc | boorad/impala | 108c5d8d39c45d49edfca98cd2d858352cd44d51 | [
"Apache-2.0"
] | null | null | null | be/src/statestore/simple-scheduler.cc | boorad/impala | 108c5d8d39c45d49edfca98cd2d858352cd44d51 | [
"Apache-2.0"
] | null | null | null | // Copyright 2012 Cloudera 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 <vector>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
#include <boost/foreach.hpp>
#include "util/metrics.h"
#include "runtime/coordinator.h"
#include "runtime/exec-env.h"
#include "statestore/simple-scheduler.h"
#include "statestore/state-store-subscriber.h"
#include "gen-cpp/Types_types.h"
#include "util/network-util.h"
using namespace std;
using namespace boost;
namespace impala {
static const string LOCAL_ASSIGNMENTS_KEY("simple-scheduler.local-assignments.total");
static const string ASSIGNMENTS_KEY("simple-scheduler.assignments.total");
static const string SCHEDULER_INIT_KEY("simple-scheduler.initialized");
const string SimpleScheduler::IMPALA_MEMBERSHIP_TOPIC("impala-membership");
SimpleScheduler::SimpleScheduler(StateStoreSubscriber* subscriber,
const string& backend_id, const TNetworkAddress& backend_address,
Metrics* metrics)
: metrics_(metrics),
statestore_subscriber_(subscriber),
backend_id_(backend_id),
thrift_serializer_(false),
total_assignments_(NULL),
total_local_assignments_(NULL),
initialised_(NULL),
update_count_(0) {
backend_descriptor_.address = backend_address;
next_nonlocal_host_entry_ = host_map_.begin();
}
SimpleScheduler::SimpleScheduler(const vector<TNetworkAddress>& backends,
Metrics* metrics)
: metrics_(metrics),
statestore_subscriber_(NULL),
thrift_serializer_(false),
total_assignments_(NULL),
total_local_assignments_(NULL),
initialised_(NULL),
update_count_(0) {
DCHECK(backends.size() > 0);
for (int i = 0; i < backends.size(); ++i) {
vector<string> ipaddrs;
Status status = HostnameToIpAddrs(backends[i].hostname, &ipaddrs);
if (!status.ok()) {
VLOG(1) << "Failed to resolve " << backends[i].hostname << ": "
<< status.GetErrorMsg();
continue;
}
// Try to find a non-localhost address, otherwise just use the
// first IP address returned.
string ipaddr = ipaddrs[0];
if (!FindFirstNonLocalhost(ipaddrs, &ipaddr)) {
VLOG(1) << "Only localhost addresses found for " << backends[i].hostname;
}
HostMap::iterator it = host_map_.find(ipaddr);
if (it == host_map_.end()) {
it = host_map_.insert(
make_pair(ipaddr, list<TNetworkAddress>())).first;
host_ip_map_[backends[i].hostname] = ipaddr;
}
TNetworkAddress backend_address = MakeNetworkAddress(ipaddr, backends[i].port);
it->second.push_back(backend_address);
}
next_nonlocal_host_entry_ = host_map_.begin();
}
Status SimpleScheduler::Init() {
LOG(INFO) << "Starting simple scheduler";
if (statestore_subscriber_ != NULL) {
StateStoreSubscriber::UpdateCallback cb =
bind<void>(mem_fn(&SimpleScheduler::UpdateMembership), this, _1, _2);
RETURN_IF_ERROR(
statestore_subscriber_->AddTopic(IMPALA_MEMBERSHIP_TOPIC, true, cb));
}
if (metrics_ != NULL) {
total_assignments_ =
metrics_->CreateAndRegisterPrimitiveMetric(ASSIGNMENTS_KEY, 0L);
total_local_assignments_ =
metrics_->CreateAndRegisterPrimitiveMetric(LOCAL_ASSIGNMENTS_KEY, 0L);
initialised_ =
metrics_->CreateAndRegisterPrimitiveMetric(SCHEDULER_INIT_KEY, true);
}
if (statestore_subscriber_ != NULL) {
// Figure out what our IP address is, so that each subscriber
// doesn't have to resolve it on every heartbeat.
vector<string> ipaddrs;
const string& hostname = backend_descriptor_.address.hostname;
Status status = HostnameToIpAddrs(hostname, &ipaddrs);
if (!status.ok()) {
VLOG(1) << "Failed to resolve " << hostname << ": " << status.GetErrorMsg();
return status;
}
// Find a non-localhost address for this host; if one can't be
// found use the first address returned by HostnameToIpAddrs
string ipaddr = ipaddrs[0];
if (!FindFirstNonLocalhost(ipaddrs, &ipaddr)) {
VLOG(3) << "Only localhost addresses found for " << hostname;
}
backend_descriptor_.ip_address = ipaddr;
LOG(INFO) << "Simple-scheduler using " << ipaddr << " as IP address";
}
return Status::OK;
}
void SimpleScheduler::UpdateMembership(
const StateStoreSubscriber::TopicDeltaMap& service_state,
vector<TTopicUpdate>* topic_updates) {
++update_count_;
// TODO: Work on a copy if possible, or at least do resolution as a separate step
// First look to see if the topic(s) we're interested in have an update
StateStoreSubscriber::TopicDeltaMap::const_iterator topic =
service_state.find(IMPALA_MEMBERSHIP_TOPIC);
// Copy to work on without holding the map lock
HostMap host_map_copy;
HostIpAddressMap host_ip_map_copy;
bool found_self = false;
if (topic != service_state.end()) {
const TTopicDelta& delta = topic->second;
if (delta.is_delta) {
// TODO: Handle deltas when the state-store starts sending them
LOG(WARNING) << "Unexpected delta update from state-store, ignoring as scheduler"
" cannot handle deltas";
return;
}
BOOST_FOREACH(const TTopicItem& item, delta.topic_entries) {
TBackendDescriptor backend_descriptor;
// Benchmarks have suggested that this method can deserialize
// ~10m messages per second, so no immediate need to consider optimisation.
uint32_t len = item.value.size();
Status status = DeserializeThriftMsg(reinterpret_cast<const uint8_t*>(
item.value.data()), &len, false, &backend_descriptor);
if (!status.ok()) {
VLOG(2) << "Error deserializing topic item with key: " << item.key;
continue;
}
if (item.key == backend_id_) {
if (backend_descriptor.address == backend_descriptor_.address) {
found_self = true;
} else {
// Someone else has registered this subscriber ID with a
// different address. We will try to re-register
// (i.e. overwrite their subscription), but there is likely
// a configuration problem.
LOG_EVERY_N(WARNING, 30) << "Duplicate subscriber registration from address: "
<< backend_descriptor.address;
}
}
host_map_copy[backend_descriptor.ip_address].push_back(
backend_descriptor.address);
host_ip_map_copy[backend_descriptor.address.hostname] =
backend_descriptor.ip_address;
}
}
// If this impalad is not in our view of the membership list, we
// should add it and tell the state-store.
if (!found_self) {
VLOG(2) << "Registering local backend with state-store";
topic_updates->push_back(TTopicUpdate());
TTopicUpdate& update = topic_updates->back();
update.topic_name = IMPALA_MEMBERSHIP_TOPIC;
update.topic_updates.push_back(TTopicItem());
TTopicItem& item = update.topic_updates.back();
item.key = backend_id_;
Status status = thrift_serializer_.Serialize(&backend_descriptor_, &item.value);
if (!status.ok()) {
LOG(INFO) << "Failed to serialize Impala backend address for state-store topic: "
<< status.GetErrorMsg();
topic_updates->pop_back();
}
}
{
lock_guard<mutex> lock(host_map_lock_);
host_map_.swap(host_map_copy);
host_ip_map_.swap(host_ip_map_copy);
next_nonlocal_host_entry_ = host_map_.begin();
}
}
Status SimpleScheduler::GetHosts(
const vector<TNetworkAddress>& data_locations, HostList* hostports) {
hostports->clear();
for (int i = 0; i < data_locations.size(); ++i) {
TNetworkAddress backend;
GetHost(data_locations[i], &backend);
hostports->push_back(backend);
}
DCHECK_EQ(data_locations.size(), hostports->size());
return Status::OK;
}
Status SimpleScheduler::GetHost(const TNetworkAddress& data_location,
TNetworkAddress* hostport) {
lock_guard<mutex> lock(host_map_lock_);
if (host_map_.size() == 0) {
return Status("No backends configured");
}
bool local_assignment = false;
HostMap::iterator entry = host_map_.find(data_location.hostname);
if (entry == host_map_.end()) {
// host_map_ map ip address to backend but data_location.hostname might be a hostname.
// Find the ip address of the data_location from host_ip_map_.
HostIpAddressMap::const_iterator itr = host_ip_map_.find(data_location.hostname);
if (itr != host_ip_map_.end()) {
entry = host_map_.find(itr->second);
}
}
if (entry == host_map_.end()) {
// round robin the ipaddress
entry = next_nonlocal_host_entry_;
++next_nonlocal_host_entry_;
if (next_nonlocal_host_entry_ == host_map_.end()) {
next_nonlocal_host_entry_ = host_map_.begin();
}
} else {
local_assignment = true;
}
DCHECK(!entry->second.empty());
// Round-robin between impalads on the same ipaddress.
// Pick the first one, then move it to the back of the queue
*hostport = entry->second.front();
entry->second.pop_front();
entry->second.push_back(*hostport);
if (metrics_ != NULL) {
total_assignments_->Increment(1);
if (local_assignment) {
total_local_assignments_->Increment(1L);
}
}
if (VLOG_FILE_IS_ON) {
stringstream s;
s << "(" << data_location.hostname << ":" << data_location.port;
s << " -> " << (hostport->hostname) << ":" << (hostport->port) << ")";
VLOG_FILE << "SimpleScheduler assignment (data->backend): " << s.str();
}
return Status::OK;
}
void SimpleScheduler::GetAllKnownHosts(HostList* hostports) {
lock_guard<mutex> lock(host_map_lock_);
hostports->clear();
BOOST_FOREACH(const HostMap::value_type& hosts, host_map_) {
hostports->insert(hostports->end(), hosts.second.begin(), hosts.second.end());
}
}
}
| 35.424658 | 90 | 0.691705 | [
"vector"
] |
92a19b2e699a3531c5bec8bee7b1431fdecf23d7 | 12,909 | cpp | C++ | NextEngineEditor/src/assets/inspect.cpp | CompilerLuke/NextEngine | aa1a8e9d9370bce004dba00854701597cab74989 | [
"MIT"
] | 1 | 2021-09-10T18:19:16.000Z | 2021-09-10T18:19:16.000Z | NextEngineEditor/src/assets/inspect.cpp | CompilerLuke/NextEngine | aa1a8e9d9370bce004dba00854701597cab74989 | [
"MIT"
] | null | null | null | NextEngineEditor/src/assets/inspect.cpp | CompilerLuke/NextEngine | aa1a8e9d9370bce004dba00854701597cab74989 | [
"MIT"
] | 2 | 2020-04-02T06:46:56.000Z | 2021-06-17T16:47:57.000Z | #include "graphics/assets/assets.h"
#include "graphics/assets/shader.h"
#include "graphics/rhi/pipeline.h"
#include <imgui/imgui.h>
#include "assets/node.h"
#include "assets/explorer.h"
#include "assets/inspect.h"
#include "custom_inspect.h"
#include "diffUtil.h"
#include "shaderGraph.h"
#include "../src/generated.h"
#include "editor.h"
struct AssetTab;
struct Editor;
__declspec(dllimport) extern DefaultTextures default_textures;
bool edit_color(glm::vec4& color, string_view name, glm::vec2 size) {
ImVec4 col(color.x, color.y, color.z, color.w);
if (ImGui::ColorButton(name.c_str(), col, 0, ImVec2(size.x, size.y))) {
ImGui::OpenPopup(name.c_str());
}
color = glm::vec4(col.x, col.y, col.z, col.w);
bool active = false;
if (ImGui::BeginPopup(name.c_str())) {
ImGui::ColorPicker4(name.c_str(), &color.x);
active = ImGui::IsItemActive();
ImGui::EndPopup();
}
return active;
}
bool edit_color(glm::vec3& color, string_view name, glm::vec2 size) {
glm::vec4 color4 = glm::vec4(color, 1.0f);
bool active = edit_color(color4, name, size);
color = color4;
return active;
}
void channel_image(uint& image, string_view name, float scaling) {
ImVec2 size(scaling * 200, scaling * 200);
if (image == INVALID_HANDLE) { ImGui::Image(default_textures.white, size); }
else ImGui::Image({ image }, size);
if (ImGui::IsMouseDragging(ImGuiMouseButton_Left) && ImGui::IsItemHovered()) {
if (name == "normal") image = default_textures.normal.id;
else image = INVALID_HANDLE;
}
accept_drop("DRAG_AND_DROP_IMAGE", &image, sizeof(texture_handle));
ImGui::SameLine();
ImGui::Text("%s", name.c_str());
ImGui::SameLine(ImGui::GetWindowWidth() - 300 * scaling);
}
void texture_properties(TextureAsset* tex, Editor& editor) {
TextureDesc& texture = *texture_desc(tex->handle);
if (ImGui::CollapsingHeader("TextureInfo - Modified")) {
ImGui::Text("Width : %i", texture.width);
ImGui::Text("Height : %i", texture.height);
ImGui::Text("Num Channels : %i", texture.num_channels);
ImGui::Text("Mips : %i", texture.num_mips);
TextureFormat format = texture.format;
const char* format_str = "Unknown format";
switch (texture.format) {
case TextureFormat::U8: format_str = "U8"; break;
case TextureFormat::UNORM: format_str = "UNORM"; break;
case TextureFormat::SRGB: format_str = "SRGB"; break;
case TextureFormat::HDR: format_str = "HDR"; break;
}
ImGui::Text("Format : %s", format_str);
}
ImGui::NewLine();
ImGui::SetNextItemOpen(true);
if (ImGui::CollapsingHeader("Preview")) {
float size = 500 * editor.scaling;
ImGui::Image(tex->handle, ImVec2(size, size));
}
}
MaterialDesc base_shader_desc(shader_handle shader, bool tiling) {
MaterialDesc desc{ shader };
desc.draw_state = Cull_None;
mat_channel3(desc, "diffuse", glm::vec3(1.0f));
mat_channel1(desc, "metallic", 0.0f);
mat_channel1(desc, "roughness", 0.5f);
mat_channel1(desc, "normal", 1.0f, default_textures.normal);
if (tiling) mat_vec2(desc, "tiling", glm::vec2(5.0f));
return desc;
}
#include "generated.h"
void begin_asset_diff(DiffUtil& util, AssetInfo& info, uint handle, AssetNode::Type type, void* copy) {
refl::Type* types[AssetNode::Count] = {
get_TextureAsset_type(),
get_MaterialAsset_type(),
get_ShaderAsset_type(),
get_ModelAsset_type(),
get_AssetFolder_type(),
};
ElementPtr ptr[2] = {};
ptr[0].type = ElementPtr::AssetNode;
ptr[0].id = handle;
ptr[0].component_id = type;
ptr[0].refl_type = types[type];
ptr[1].type = ElementPtr::StaticPointer;
ptr[1].ptr = &info;
begin_diff(util, {ptr, 2}, copy);
}
void inspect_material_params(Editor& editor, material_handle handle, MaterialDesc* material) {
static DiffUtil diff_util;
static MaterialDesc copy;
static material_handle last_asset = { INVALID_HANDLE };
static bool slider_active;
ElementPtr ptr[3] = {};
ptr[0] = {ElementPtr::Offset, offsetof(MaterialAsset, desc), get_MaterialDesc_type()};
ptr[1] = {ElementPtr::AssetNode, handle.id, AssetNode::Material, get_AssetNode_type()};
ptr[2] = {ElementPtr::StaticPointer, &editor.asset_info};
if (handle.id != last_asset.id || !slider_active) {
begin_diff(diff_util, {ptr,3}, ©);
last_asset.id = handle.id;
}
slider_active = false;
float scaling = editor.scaling;
for (auto& param : material->params) {
const char* name = param.name.data;
if (param.type == Param_Vec2) {
ImGui::PushItemWidth(200.0f);
ImGui::InputFloat2(name, ¶m.vec2.x);
}
if (param.type == Param_Vec3) {
edit_color(param.vec3, name);
ImGui::SameLine();
ImGui::Text(name);
}
if (param.type == Param_Image) {
channel_image(param.image, param.name, scaling);
ImGui::SameLine();
ImGui::Text(name);
}
if (param.type == Param_Int) {
ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.3f);
ImGui::InputInt(name, ¶m.integer);
}
if (param.type == Param_Float) {
ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.3f);
ImGui::SliderFloat(name, ¶m.real, -1.0f, 1.0f);
slider_active |= ImGui::IsItemActive();
}
if (param.type == Param_Channel3) {
channel_image(param.image, name, scaling);
slider_active |= edit_color(param.vec3, name, glm::vec2(50, 50));
}
if (param.type == Param_Channel2) {
channel_image(param.image, name, scaling);
ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.3f);
ImGui::InputFloat2(tformat("##", name).c_str(), ¶m.vec2.x);
slider_active |= ImGui::IsItemActive();
}
if (param.type == Param_Channel1) {
channel_image(param.image, name, scaling);
ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.3f);
ImGui::SliderFloat(tformat("##", name).c_str(), ¶m.real, 0, 1.0f);
slider_active |= ImGui::IsItemActive();
}
}
if (slider_active) {
commit_diff(editor.actions, diff_util);
}
else {
end_diff(editor.actions, diff_util, "Material Property");
}
}
void material_properties(MaterialAsset* mat_asset, Editor& editor, AssetTab& asset_tab) {
AssetPreviewResources& previewer = asset_tab.preview_resources;
auto& name = mat_asset->name;
render_name(name, asset_tab.explorer.default_font);
ImGui::SetNextTreeNodeOpen(true);
ImGui::CollapsingHeader("Material");
MaterialDesc& desc = mat_asset->desc;
if (false) { //todo check if handle becomes invalid, then again this should never happen
ImGui::Text("Material Handle is INVALID");
}
ShaderInfo* info = shader_info(desc.shader);
if (info == NULL) {
ImGui::Text("Shader Handle is INVALID!");
}
if (ImGui::Button(info->ffilename.data)) {
ImGui::OpenPopup("StandardShaders");
}
if (accept_drop("DRAG_AND_DROP_SHADER", &desc.shader, sizeof(shader_handle))) {
set_params_for_shader_graph(asset_tab, desc.shader);
}
if (ImGui::BeginPopup("StandardShaders")) {
if (ImGui::Button("shaders/pbr.frag")) {
shader_handle new_shad = default_shaders.pbr;
if (new_shad.id != desc.shader.id) {
desc = base_shader_desc(new_shad);
//set_base_shader_params(assets, desc, new_shad);
//material->set_vec2(shader_manager, "transformUVs", glm::vec2(1, 1));
}
}
if (ImGui::Button("shaders/tree.frag")) {
shader_handle new_shad = default_shaders.grass;
if (new_shad.id != desc.shader.id) {
//todo enable undo/redo for switching shaders
desc = base_shader_desc(new_shad, false);
desc.draw_state = Cull_None;
mat_float(desc, "cutoff", 0.5f);
}
}
if (ImGui::Button("shaders/paralax_pbr.frag")) {
shader_handle new_shad = load_Shader("shaders/pbr.vert", "shaders/paralax_pbr.frag");
if (new_shad.id != desc.shader.id) {
desc = base_shader_desc(new_shad);
mat_channel1(desc, "height", 1.0);
mat_channel1(desc, "ao", 1.0);
mat_int(desc, "steps", 5);
mat_float(desc, "depth_scale", 1);
mat_vec2(desc, "transformUVs", glm::vec2(1));
}
}
ImGui::EndPopup();
}
inspect_material_params(editor, mat_asset->handle, &desc);
rot_preview(previewer, mat_asset->rot_preview);
render_preview_for(previewer, *mat_asset);
}
void model_properties(ModelAsset* mod_asset, Editor& editor, AssetTab& self) {
Model* model = get_Model(mod_asset->handle);
render_name(mod_asset->name, self.explorer.default_font);
DiffUtil diff_util;
ModelAsset copy;
begin_asset_diff(diff_util, editor.asset_info, mod_asset->handle.id, AssetNode::Model, ©);
ImGui::SetNextTreeNodeOpen(true);
ImGui::CollapsingHeader("Transform");
ImGui::InputFloat3("position", &mod_asset->trans.position.x);
get_on_inspect_gui("glm::quat")(&mod_asset->trans.rotation, "rotation", editor);
ImGui::InputFloat3("scale", &mod_asset->trans.scale.x);
end_diff(editor.actions, diff_util, "Properties Material");
if (ImGui::Button("Apply")) {
begin_gpu_upload();
load_Model(mod_asset->handle, mod_asset->path, compute_model_matrix(mod_asset->trans));
end_gpu_upload();
mod_asset->rot_preview.rot_deg = glm::vec2();
mod_asset->rot_preview.current = glm::vec2();
mod_asset->rot_preview.previous = glm::vec2();
mod_asset->rot_preview.rot = glm::quat();
}
if (ImGui::CollapsingHeader("LOD")) {
float height = 200.0f;
float padding = 10.0f;
float cull_distance = model->lod_distance.last();
float avail_width = ImGui::GetContentRegionAvail().x - padding * 4;
float last_dist = 0;
auto draw_list = ImGui::GetForegroundDrawList();
glm::vec2 cursor_pos = glm::vec2(ImGui::GetCursorScreenPos()) + glm::vec2(padding);
ImGui::SetCursorPos(glm::vec2(ImGui::GetCursorPos()) + glm::vec2(0, height + padding * 2));
ImU32 colors[MAX_MESH_LOD] = {
ImColor(245, 66, 66),
ImColor(245, 144, 66),
ImColor(245, 194, 66),
ImColor(170, 245, 66),
ImColor(66, 245, 111),
ImColor(66, 245, 212),
ImColor(66, 126, 245),
ImColor(66, 69, 245),
};
//todo logic could be simplified
static int dragging = -1;
static glm::vec2 last_drag_delta;
glm::vec2 drag_delta = glm::vec2(ImGui::GetMouseDragDelta()) - last_drag_delta;
uint lod_count = model->lod_distance.length;
if (!ImGui::IsMouseDragging(ImGuiMouseButton_Left)) {
dragging = -1;
last_drag_delta = glm::vec2();
drag_delta = glm::vec2();
}
for (uint i = 0; i < lod_count; i++) {
float dist = model->lod_distance[i];
float offset = last_dist / cull_distance * avail_width;
float width = avail_width * (dist - last_dist) / cull_distance;
draw_list->AddRectFilled(cursor_pos + glm::vec2(offset, 0), cursor_pos + glm::vec2(offset + width, height), colors[i]);
char buffer[100];
snprintf(buffer, 100, "LOD %i - %.1fm", i, dist);
draw_list->AddText(cursor_pos + glm::vec2(offset + padding, padding), ImColor(255, 255, 255), buffer);
last_dist = dist;
bool last = i + 1 == lod_count;
bool is_dragged = i == dragging;
if (!last && (is_dragged || ImGui::IsMouseHoveringRect(cursor_pos + glm::vec2(offset + width - padding, 0), cursor_pos + glm::vec2(offset + width + padding, height)))) {
draw_list->AddRectFilled(cursor_pos + glm::vec2(offset + width - padding, 0), cursor_pos + glm::vec2(offset + width + padding, height), ImColor(255, 255, 255));
model->lod_distance[i] += drag_delta.x * cull_distance / avail_width;
dragging = i;
}
}
float last_cull_distance = cull_distance;
ImGui::InputFloat("Culling distance", &cull_distance);
if (last_cull_distance != cull_distance) {
for (uint i = 0; i < lod_count - 1; i++) {
model->lod_distance[i] *= cull_distance / last_cull_distance;
}
model->lod_distance.last() = cull_distance;
}
last_drag_delta = ImGui::GetMouseDragDelta();
mod_asset->lod_distance = (slice<float>)model->lod_distance;
}
ImGui::SetNextTreeNodeOpen(true);
ImGui::CollapsingHeader("Materials");
if (model->materials.length != mod_asset->materials.length) {
mod_asset->materials.resize(model->materials.length);
}
for (int i = 0; i < mod_asset->materials.length; i++) {
string_buffer prefix = tformat(model->materials[i], " : ");
get_on_inspect_gui("Material")(&mod_asset->materials[i], prefix, editor);
}
end_diff(editor.actions, diff_util, "Asset Properties");
rot_preview(self.preview_resources, mod_asset->rot_preview);
render_preview_for(self.preview_resources, *mod_asset);
}
void asset_properties(AssetNode& node, Editor& editor, AssetTab& tab) {
if (node.type == AssetNode::Texture) texture_properties(&node.texture, editor);
if (node.type == AssetNode::Shader) shader_graph_properties(node, editor, tab); //todo fix these signatures
if (node.type == AssetNode::Model) model_properties(&node.model, editor, tab);
if (node.type == AssetNode::Material) material_properties(&node.material, editor, tab);
}
| 31.408759 | 172 | 0.679371 | [
"model",
"transform"
] |
92a5f638ba72068c05a1df816bec31822c08a141 | 1,025 | cpp | C++ | Osiris/SDK/Utils.cpp | GetRektLOL/OsirisAndExtra | 022e68a7d4fbc40f535ea165fa85232c31bc6a10 | [
"MIT"
] | 2 | 2021-12-25T16:53:12.000Z | 2022-03-05T17:15:54.000Z | Osiris/SDK/Utils.cpp | Metaphysical1/OsirisAndExtra | 007491a5515712f6f76745e4cf4a82cf60473fcb | [
"MIT"
] | null | null | null | Osiris/SDK/Utils.cpp | Metaphysical1/OsirisAndExtra | 007491a5515712f6f76745e4cf4a82cf60473fcb | [
"MIT"
] | 1 | 2021-12-27T09:40:11.000Z | 2021-12-27T09:40:11.000Z | #include <cmath>
#include "../Memory.h"
#include "GlobalVars.h"
#include "Entity.h"
#include "matrix3x4.h"
#include "ModelInfo.h"
#include "Utils.h"
#include "Vector.h"
std::tuple<float, float, float> rainbowColor(float speed) noexcept
{
constexpr float pi = std::numbers::pi_v<float>;
return std::make_tuple(std::sin(speed * memory->globalVars->realtime) * 0.5f + 0.5f,
std::sin(speed * memory->globalVars->realtime + 2 * pi / 3) * 0.5f + 0.5f,
std::sin(speed * memory->globalVars->realtime + 4 * pi / 3) * 0.5f + 0.5f);
}
void resetMatrix(Entity* entity, matrix3x4* boneCacheData, Vector origin, Vector absAngle, Vector mins, Vector maxs) noexcept
{
memcpy(entity->getBoneCache().memory, boneCacheData, std::clamp(entity->getBoneCache().size, 0, MAXSTUDIOBONES) * sizeof(matrix3x4));
memory->setAbsOrigin(entity, origin);
memory->setAbsAngle(entity, Vector{ 0.f, absAngle.y, 0.f });
entity->getCollideable()->setCollisionBounds(mins, maxs);
} | 41 | 137 | 0.66439 | [
"vector"
] |
92a775e090d2e87401947b9a456d4f5a9b87e94a | 7,139 | cc | C++ | dcmtk-master2/dcmsign/libsrc/sicertvf.cc | happymanx/Weather_FFI | a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f | [
"MIT"
] | null | null | null | dcmtk-master2/dcmsign/libsrc/sicertvf.cc | happymanx/Weather_FFI | a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f | [
"MIT"
] | null | null | null | dcmtk-master2/dcmsign/libsrc/sicertvf.cc | happymanx/Weather_FFI | a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f | [
"MIT"
] | null | null | null | /*
*
* Copyright (C) 1998-2020, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmsign
*
* Author: Marco Eichelberg
*
* Purpose:
* classes: SiCertificateVerifier
*
*/
#include "dcmtk/config/osconfig.h"
#ifdef WITH_OPENSSL
#include "dcmtk/dcmsign/sicert.h"
#include "dcmtk/dcmsign/sicertvf.h"
BEGIN_EXTERN_C
#include <openssl/pem.h>
#include <openssl/x509.h>
END_EXTERN_C
SiCertificateVerifier::SiCertificateVerifier()
: x509store(NULL)
, x509untrusted(NULL)
, enableCRLverification(OFFalse)
, errorCode(0)
{
x509store = X509_STORE_new();
x509untrusted = sk_X509_new_null();
}
SiCertificateVerifier::~SiCertificateVerifier()
{
X509_STORE_free(x509store);
sk_X509_pop_free(x509untrusted, X509_free);
}
X509_STORE *SiCertificateVerifier::getTrustedCertStore()
{
return x509store;
}
stack_st_X509 *SiCertificateVerifier::getUntrustedCerts()
{
return x509untrusted;
}
OFCondition SiCertificateVerifier::addTrustedCertificateFile(const char *fileName, int fileType)
{
/* fileType should be X509_FILETYPE_PEM or X509_FILETYPE_ASN1 */
X509_LOOKUP *x509_lookup = X509_STORE_add_lookup(x509store, X509_LOOKUP_file());
if (x509_lookup == NULL) return SI_EC_OpenSSLFailure;
if (! X509_LOOKUP_load_file(x509_lookup, fileName, fileType)) return SI_EC_CannotRead;
return EC_Normal;
}
OFCondition SiCertificateVerifier::addUntrustedCertificateFile(const char *fileName, int fileType)
{
OFCondition result = EC_Normal;
if (x509untrusted)
{
// PEM has different loading code because a PEM file can contain several certificates and CRLs
if (fileType == X509_FILETYPE_PEM)
{
BIO *bio = BIO_new_file(fileName, "r");
if (bio)
{
STACK_OF(X509_INFO) *x509infostack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
if (x509infostack)
{
for (int i = 0; i < sk_X509_INFO_num(x509infostack); i++)
{
X509_INFO *xi = sk_X509_INFO_value(x509infostack, i);
if (xi->x509)
{
// move certificate to our list of untrusted certificates
sk_X509_push(x509untrusted, xi->x509);
xi->x509 = NULL;
}
}
// delete the remaining x509infostack
sk_X509_INFO_pop_free(x509infostack, X509_INFO_free);
} else result = SI_EC_CannotRead;
BIO_free(bio);
} else result = SI_EC_CannotRead;
}
else if (fileType == X509_FILETYPE_ASN1)
{
// load a single certificate in ASN.1 DER format
BIO *bio = BIO_new_file(fileName, "rb");
if (bio)
{
X509 *xcert = d2i_X509_bio(bio, NULL);
if (xcert)
{
sk_X509_push(x509untrusted, xcert);
} else result = SI_EC_CannotRead;
BIO_free(bio);
} else result = SI_EC_CannotRead;
} else result = SI_EC_InvalidFiletype;
} else result = SI_EC_CannotRead;
return result;
}
OFCondition SiCertificateVerifier::addTrustedCertificateDir(const char *pathName, int fileType)
{
/* fileType should be X509_FILETYPE_PEM or X509_FILETYPE_ASN1 */
X509_LOOKUP *x509_lookup = X509_STORE_add_lookup(x509store, X509_LOOKUP_hash_dir());
if (x509_lookup == NULL) return SI_EC_OpenSSLFailure;
if (! X509_LOOKUP_add_dir(x509_lookup, pathName, fileType)) return SI_EC_CannotRead;
return EC_Normal;
}
OFCondition SiCertificateVerifier::addCertificateRevocationList(const char *fileName, int fileType)
{
OFCondition result = SI_EC_CannotRead;
X509_CRL *x509crl = NULL;
if (fileName)
{
BIO *in = BIO_new(BIO_s_file());
if (in)
{
if (BIO_read_filename(in, fileName) > 0)
{
if (fileType == X509_FILETYPE_ASN1)
{
x509crl = d2i_X509_CRL_bio(in, NULL);
} else {
x509crl = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
}
if (x509crl)
{
X509_STORE_add_crl(x509store, x509crl); // creates a copy of the CRL object
X509_CRL_free(x509crl);
enableCRLverification = OFTrue;
result = EC_Normal;
}
}
BIO_free(in);
}
}
return result;
}
void SiCertificateVerifier::setCRLverification(OFBool enabled)
{
enableCRLverification = enabled;
}
extern "C"
{
int sicertvf_verify_callback(int deflt, X509_STORE_CTX *ctx);
}
int sicertvf_verify_callback(int deflt, X509_STORE_CTX *ctx)
{
if (ctx)
{
void *p = X509_STORE_CTX_get_ex_data(ctx, 0);
if (p)
{
SiCertificateVerifier *pthis = OFreinterpret_cast(SiCertificateVerifier *, p);
return pthis->verifyCallback(deflt, ctx);
}
}
return deflt;
}
OFCondition SiCertificateVerifier::verifyCertificate(SiCertificate& certificate)
{
errorCode = 0;
X509 *rawcert = certificate.getRawCertificate();
if (rawcert == NULL) return SI_EC_VerificationFailed_NoCertificate;
X509_STORE_CTX *ctx = X509_STORE_CTX_new();
X509_STORE_CTX_init(ctx, x509store, rawcert, x509untrusted);
X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
if (param)
{
if (enableCRLverification)
{
// enable CRL checking for the signer certificate
X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
}
X509_VERIFY_PARAM_set_depth(param, 100); // that's the OpenSSL default
X509_STORE_CTX_set0_param(ctx, param);
}
X509_STORE_CTX_set_ex_data(ctx, 0, OFreinterpret_cast(void *, this));
X509_STORE_CTX_set_verify_cb(ctx, sicertvf_verify_callback);
// If a complete chain can be built and validated X509_verify_cert() returns 1,
// otherwise it returns zero, in exceptional circumstances it can also return a negative code.
int ok = X509_verify_cert(ctx);
errorCode = X509_STORE_CTX_get_error(ctx);
X509_STORE_CTX_cleanup(ctx);
X509_STORE_CTX_free(ctx);
if (ok == 1) return EC_Normal; else return SI_EC_VerificationFailed_NoTrust;
}
int SiCertificateVerifier::verifyCallback(int deflt, X509_STORE_CTX *ctx)
{
if (X509_STORE_CTX_get_error(ctx) == X509_V_ERR_CERT_REVOKED)
{
// The signer certificate is on the revocation list. By default, this means that
// the certificate verification will fail, independent from the timestamp of the signature
// and the timestamp of the revocation. At this point we could add additional code that
// compares the time of revocation with the DICOM signature datetime or (preferrably) a
// certified timestamp that might also be present. If the revocation occured after the time of
// signature, we could still accept the certificate and thus the signature.
// For now, we retain the OpenSSL default behaviour.
}
return deflt;
}
OFBool SiCertificateVerifier::lastErrorIsCertExpiry() const
{
return (errorCode == X509_V_ERR_CERT_HAS_EXPIRED);
}
const char *SiCertificateVerifier::lastError() const
{
return X509_verify_cert_error_string(errorCode);
}
#else /* WITH_OPENSSL */
int sicertvf_cc_dummy_to_keep_linker_from_moaning = 0;
#endif
| 27.563707 | 99 | 0.70402 | [
"object"
] |
92a8125769358694ebd3788025a7b8d45b2b394b | 3,564 | cc | C++ | chrome/browser/ui/toolbar/wrench_menu_model_unittest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 2 | 2017-09-02T19:08:28.000Z | 2021-11-15T15:15:14.000Z | chrome/browser/ui/toolbar/wrench_menu_model_unittest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/toolbar/wrench_menu_model_unittest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T05:45:10.000Z | 2020-04-13T05:45:10.000Z | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/toolbar/wrench_menu_model.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/test/browser_with_test_window_test.h"
#include "chrome/test/menu_model_test.h"
#include "chrome/test/testing_profile.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
class WrenchMenuModelTest : public BrowserWithTestWindowTest,
public menus::AcceleratorProvider {
public:
// Don't handle accelerators.
virtual bool GetAcceleratorForCommandId(
int command_id,
menus::Accelerator* accelerator) { return false; }
};
// Copies parts of MenuModelTest::Delegate and combines them with the
// WrenchMenuModel since WrenchMenuModel is now a SimpleMenuModel::Delegate and
// not derived from SimpleMenuModel.
class TestWrenchMenuModel : public WrenchMenuModel {
public:
TestWrenchMenuModel(menus::AcceleratorProvider* provider,
Browser* browser)
: WrenchMenuModel(provider, browser),
execute_count_(0),
checked_count_(0),
enable_count_(0) {
}
// Testing overrides to menus::SimpleMenuModel::Delegate:
virtual bool IsCommandIdChecked(int command_id) const {
bool val = WrenchMenuModel::IsCommandIdChecked(command_id);
if (val)
checked_count_++;
return val;
}
virtual bool IsCommandIdEnabled(int command_id) const {
++enable_count_;
return true;
}
virtual void ExecuteCommand(int command_id) { ++execute_count_; }
int execute_count_;
mutable int checked_count_;
mutable int enable_count_;
};
TEST_F(WrenchMenuModelTest, Basics) {
TestWrenchMenuModel model(this, browser());
int itemCount = model.GetItemCount();
// Verify it has items. The number varies by platform, so we don't check
// the exact number.
EXPECT_GT(itemCount, 10);
// Execute a couple of the items and make sure it gets back to our delegate.
// We can't use CountEnabledExecutable() here because the encoding menu's
// delegate is internal, it doesn't use the one we pass in.
model.ActivatedAt(0);
EXPECT_TRUE(model.IsEnabledAt(0));
// Make sure to use the index that is not separator in all configurations.
model.ActivatedAt(2);
EXPECT_TRUE(model.IsEnabledAt(2));
EXPECT_EQ(model.execute_count_, 2);
EXPECT_EQ(model.enable_count_, 2);
model.execute_count_ = 0;
model.enable_count_ = 0;
// Choose something from the tools submenu and make sure it makes it back to
// the delegate as well. Use the first submenu as the tools one.
int toolsModelIndex = -1;
for (int i = 0; i < itemCount; ++i) {
if (model.GetTypeAt(i) == menus::MenuModel::TYPE_SUBMENU) {
toolsModelIndex = i;
break;
}
}
EXPECT_GT(toolsModelIndex, -1);
menus::MenuModel* toolsModel = model.GetSubmenuModelAt(toolsModelIndex);
EXPECT_TRUE(toolsModel);
EXPECT_GT(toolsModel->GetItemCount(), 2);
toolsModel->ActivatedAt(2);
EXPECT_TRUE(toolsModel->IsEnabledAt(2));
EXPECT_EQ(model.execute_count_, 1);
EXPECT_EQ(model.enable_count_, 1);
}
class EncodingMenuModelTest : public BrowserWithTestWindowTest,
public MenuModelTest {
};
TEST_F(EncodingMenuModelTest, IsCommandIdCheckedWithNoTabs) {
EncodingMenuModel model(browser());
ASSERT_EQ(NULL, browser()->GetSelectedTabContents());
EXPECT_FALSE(model.IsCommandIdChecked(IDC_ENCODING_ISO88591));
}
| 33.622642 | 79 | 0.727834 | [
"model"
] |
92abf84437ade8dcf8d0de3e1a0bcae1a1cd84e3 | 2,237 | cpp | C++ | plugins/OSPRay_plugin/src/OSPRayQuadLight.cpp | bkmgit/megamol | 1b70b47fa35691625f1aab2e0fe03d000077811c | [
"BSD-3-Clause"
] | null | null | null | plugins/OSPRay_plugin/src/OSPRayQuadLight.cpp | bkmgit/megamol | 1b70b47fa35691625f1aab2e0fe03d000077811c | [
"BSD-3-Clause"
] | null | null | null | plugins/OSPRay_plugin/src/OSPRayQuadLight.cpp | bkmgit/megamol | 1b70b47fa35691625f1aab2e0fe03d000077811c | [
"BSD-3-Clause"
] | null | null | null | /*
* OSPRayQuadLight.cpp
* Copyright (C) 2009-2017 by MegaMol Team
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "OSPRayQuadLight.h"
#include "mmcore/param/FloatParam.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/Vector3fParam.h"
using namespace megamol::ospray;
OSPRayQuadLight::OSPRayQuadLight(void) :
AbstractOSPRayLight(),
// quad light parameters
ql_position("Position", ""),
ql_edgeOne("Edge1", ""),
ql_edgeTwo("Edge2", "") {
// quad light
this->ql_position << new core::param::Vector3fParam(vislib::math::Vector<float, 3>(1.0f, 0.0f, 0.0f));
this->ql_edgeOne << new core::param::Vector3fParam(vislib::math::Vector<float, 3>(0.0f, 1.0f, 0.0f));
this->ql_edgeTwo << new core::param::Vector3fParam(vislib::math::Vector<float, 3>(0.0f, 0.0f, 1.0f));
this->MakeSlotAvailable(&this->ql_position);
this->MakeSlotAvailable(&this->ql_edgeOne);
this->MakeSlotAvailable(&this->ql_edgeTwo);
}
OSPRayQuadLight::~OSPRayQuadLight(void) {
this->Release();
}
void OSPRayQuadLight::readParams() {
lightContainer.lightType = lightenum::QUADLIGHT;
auto lcolor = this->lightColor.Param<core::param::Vector3fParam>()->Value().PeekComponents();
lightContainer.lightColor.assign(lcolor, lcolor + 3);
lightContainer.lightIntensity = this->lightIntensity.Param<core::param::FloatParam>()->Value();
auto ql_pos = this->ql_position.Param<core::param::Vector3fParam>()->Value().PeekComponents();
lightContainer.ql_position.assign(ql_pos, ql_pos + 3);
auto ql_e1 = this->ql_edgeOne.Param<core::param::Vector3fParam>()->Value().PeekComponents();
lightContainer.ql_edgeOne.assign(ql_e1, ql_e1 + 3);
auto ql_e2 = this->ql_edgeTwo.Param<core::param::Vector3fParam>()->Value().PeekComponents();
lightContainer.ql_edgeTwo.assign(ql_e2, ql_e2 + 3);
}
bool OSPRayQuadLight::InterfaceIsDirty() {
if (this->AbstractIsDirty() ||
this->ql_position.IsDirty() ||
this->ql_edgeOne.IsDirty() ||
this->ql_edgeTwo.IsDirty()
) {
this->ql_position.ResetDirty();
this->ql_edgeOne.ResetDirty();
this->ql_edgeTwo.ResetDirty();
return true;
} else {
return false;
}
} | 34.415385 | 106 | 0.682164 | [
"vector"
] |
92acf525dfbf56eb221c965df7fa34ba20a90af8 | 3,597 | cc | C++ | src/mesh/mesh_moab/test/test_hex_3x3x3_4P.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | 1 | 2021-02-23T18:34:47.000Z | 2021-02-23T18:34:47.000Z | src/mesh/mesh_moab/test/test_hex_3x3x3_4P.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | src/mesh/mesh_moab/test/test_hex_3x3x3_4P.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | #include <iostream>
#include "Epetra_Map.h"
#include "mpi.h"
#include "UnitTest++.h"
#include "AmanziComm.hh"
#include "../Mesh_MOAB.hh"
TEST(MOAB_HEX_3x3x3_4P)
{
using namespace Amanzi;
int j, nc, nf, nv;
int NVowned[4] = {16,16,16,16};
int NFowned[4] = {16,26,26,40};
int NCowned[4] = {3,6,6,12};
int NVused[4] = {36,48,48,64};
int NFused[4] = {52,75,75,108};
int NCused[4] = {12,18,18,27};
int NVghost[4] = {20,32,32,48};
int NFghost[4] = {36,49,49,68};
int NCghost[4] = {9,12,12,15};
auto comm = Amanzi::getDefaultComm();
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
CHECK_EQUAL(4,size);
if (rank == 0) {
int DebugWait = 0;
while (DebugWait);
}
// Load a single hex from the hex1.exo file
AmanziMesh::Mesh_MOAB mesh("test/hex_3x3x3_ss_4P.h5m", comm);
nv = mesh.num_entities(AmanziMesh::NODE, AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(NVowned[rank], nv);
nf = mesh.num_entities(AmanziMesh::FACE, AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(NFowned[rank], nf);
nc = mesh.num_entities(AmanziMesh::CELL, AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(NCowned[rank], nc);
nv = mesh.num_entities(AmanziMesh::NODE, AmanziMesh::Parallel_type::ALL);
CHECK_EQUAL(NVused[rank], nv);
nf = mesh.num_entities(AmanziMesh::FACE, AmanziMesh::Parallel_type::ALL);
CHECK_EQUAL(NFused[rank], nf);
nc = mesh.num_entities(AmanziMesh::CELL, AmanziMesh::Parallel_type::ALL);
CHECK_EQUAL(NCused[rank], nc);
nv = mesh.num_entities(AmanziMesh::NODE, AmanziMesh::Parallel_type::GHOST);
CHECK_EQUAL(NVghost[rank], nv);
nf = mesh.num_entities(AmanziMesh::FACE, AmanziMesh::Parallel_type::GHOST);
CHECK_EQUAL(NFghost[rank], nf);
nc = mesh.num_entities(AmanziMesh::CELL, AmanziMesh::Parallel_type::GHOST);
CHECK_EQUAL(NCghost[rank], nc);
AmanziMesh::Entity_ID_List c2f;
std::vector<int> c2fdirs;
Epetra_Map cell_map(mesh.cell_map(false));
Epetra_Map face_map(mesh.face_map(true));
for (int c = cell_map.MinLID(); c <= cell_map.MaxLID(); c++) {
CHECK_EQUAL(cell_map.GID(c), mesh.GID(c, AmanziMesh::CELL));
mesh.cell_get_faces_and_dirs(c, &c2f, &c2fdirs, true);
for (j = 0; j < 6; j++) {
int f = face_map.LID(mesh.GID(c2f[j], AmanziMesh::FACE));
CHECK_EQUAL(f, c2f[j]);
CHECK_EQUAL(1, abs(c2fdirs[j]));
}
}
// verify boundary maps: owned
int gid, g;
{
Epetra_Map extface_map(mesh.exterior_face_map(false));
int nfaces(extface_map.MaxLID() + 1), nall;
comm->SumAll(&nfaces, &nall, 1);
CHECK_EQUAL(nall, 54);
for (int f = extface_map.MinLID(); f <= extface_map.MaxLID(); ++f) {
gid = extface_map.GID(f);
g = face_map.LID(gid);
const AmanziGeometry::Point& xf = mesh.face_centroid(g);
CHECK(std::fabs(xf[0]) < 1e-7 || std::fabs(1.0 - xf[0]) < 1e-7 ||
std::fabs(xf[1]) < 1e-7 || std::fabs(1.0 - xf[1]) < 1e-7 ||
std::fabs(xf[2]) < 1e-7 || std::fabs(1.0 - xf[2]) < 1e-7);
}
}
// verify boundary maps: owned + ghost
{
Epetra_Map extface_map(mesh.exterior_face_map(true));
for (int f = extface_map.MinLID(); f <= extface_map.MaxLID(); ++f) {
gid = extface_map.GID(f);
g = face_map.LID(gid);
const AmanziGeometry::Point& xf = mesh.face_centroid(g);
CHECK(std::fabs(xf[0]) < 1e-7 || std::fabs(1.0 - xf[0]) < 1e-7 ||
std::fabs(xf[1]) < 1e-7 || std::fabs(1.0 - xf[1]) < 1e-7 ||
std::fabs(xf[2]) < 1e-7 || std::fabs(1.0 - xf[2]) < 1e-7);
}
}
}
| 29.483607 | 79 | 0.627189 | [
"mesh",
"vector"
] |
92afff1ccbcccfb3679986acc692af70912325fe | 8,367 | cpp | C++ | symbolics/printer/ModelicaPrinter.cpp | brutzl/pymbs | fb7c91435f56b5c4d460f82f081d5d1960fea886 | [
"MIT"
] | null | null | null | symbolics/printer/ModelicaPrinter.cpp | brutzl/pymbs | fb7c91435f56b5c4d460f82f081d5d1960fea886 | [
"MIT"
] | null | null | null | symbolics/printer/ModelicaPrinter.cpp | brutzl/pymbs | fb7c91435f56b5c4d460f82f081d5d1960fea886 | [
"MIT"
] | null | null | null | /*
This file is part of PyMbs.
PyMbs is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
PyMbs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with PyMbs.
If not, see <http://www.gnu.org/licenses/>.
Copyright 2011, 2012 Carsten Knoll, Christian Schubert,
Jens Frenkel, Sebastian Voigt
*/
#include "ModelicaPrinter.h"
#include "str.h"
using namespace Symbolics;
/*****************************************************************************/
ModelicaPrinter::ModelicaPrinter()
/*****************************************************************************/
{
}
/*****************************************************************************/
/*****************************************************************************/
ModelicaPrinter::~ModelicaPrinter()
/*****************************************************************************/
{
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::comment( const std::string &c ) const
/*****************************************************************************/
{
if (c.empty())
return "";
return " \"" + c + "\"";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::dimension( const BasicPtr &b )
/*****************************************************************************/
{
if (b->is_Scalar())
return "";
return "[" + str(b->getShape().getDimension(1)) + "," + str(b->getShape().getDimension(2)) + "]";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Mul( const Mul *mul )
/*****************************************************************************/
{
if (mul == NULL) throw InternalError("ModelicaPrinter: Mul is NULL");
bool makeScalar = false;
if (mul->is_Scalar())
for (size_t i=0; i<mul->getArgsSize(); ++i )
if ( ! mul->getArg(i)->is_Scalar())
makeScalar = true;
if (makeScalar) // Wenn das Ergebnis der Multiplikation Skalar ist, in der Mul. jedoch Matritzen enthalten sind muss das Ergebnis skalarisiert werden
return "scalar(" + join(ConstBasicPtr(mul), " * ") + ")";
else
return "(" + join(ConstBasicPtr(mul), " * ") + ")";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Matrix( const Matrix *c )
/*****************************************************************************/
{
if (c==NULL) throw InternalError("ModelicaPrinter: Matrix is NULL");
return Printer::print_Matrix(c, ',', ',',
'{', '}',
'{', '}',
"\n " );
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Inverse( const Inverse *c )
/*****************************************************************************/
{
if (c == NULL) throw InternalError("ModelicaPrinter: Inverse is NULL");
return "Modelica.Math.Matrices.inv(" + print(c->getArg()) + ")";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Pow( const Pow *pow )
/*****************************************************************************/
{
if (pow == NULL) throw InternalError("ModelicaPrinter: Pow is NULL");
return "(" + print(pow->getBase()) + "^" + print(pow->getExponent()) + ")";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Der( const Der *d )
/*****************************************************************************/
{
if (d == NULL) throw InternalError("ModelicaPrinter: Der is NULL");
return "der(" + print(d->getArg()) + ")";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Element( const Element *e )
/*****************************************************************************/
{
if (e == NULL) throw InternalError("ModelicaPrinter: Element is NULL");
return print(e->getArg(0)) + "[" + str(e->getRow()+1) + "," + str(e->getCol()+1) + "]";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Skew( const Skew *s )
/*****************************************************************************/
{
if (s == NULL) throw InternalError("ModelicaPrinter: Skew is NULL");
return "skew(vector( " + print(s->getArg()) + "))";
//Alternativ ginge auch:
//std::string v = print(s->getArg());
//return "{{0,-" + v + "[3,1], " + v + "[2,1]}, {" + v + "[3,1], 0, -" + v + "[1,1]}, {-" + v + "[2,1], " + v + "[1,1], 0}}";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Solve( const Solve *s )
/*****************************************************************************/
{
if (s == NULL) throw InternalError("ModelicaPrinter: Solve is NULL");
return "Modelica.Math.Matrices.solve2(" + print(s->getArg1()) + ", " + print(s->getArg2()) + ")";
//solve2 erspart vector() und matrix() Umwandlungen, da Arg2 auch eine Matrix sein kann.
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Zero( const Zero *z )
/*****************************************************************************/
{
if (z == NULL) throw InternalError("ModelicaPrinter: Zero is NULL");
if (z->is_Scalar())
return "0";
return "zeros(" + str(z->getShape().getDimension(1)) + "," + str(z->getShape().getDimension(2)) + ")";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_If( const If *e )
/*****************************************************************************/
{
if (e==NULL) throw InternalError("ModelicaPrinter: If is NULL");
return "(if " + print(e->getArg(0)) + " then " + print(e->getArg(1)) + " else " + print(e->getArg(2)) + ")";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Scalar( const Scalar *s )
/*****************************************************************************/
{
if (s == NULL) throw InternalError("ModelicaPrinter: Scalar is NULL");
return "scalar(" + print(s->getArg()) + ")";
}
/*****************************************************************************/
/*****************************************************************************/
std::string ModelicaPrinter::print_Bool( const Bool *b )
/*****************************************************************************/
{
if (b == NULL) throw InternalError("ModelicaPrinter: Bool is NULL");
if (b->getValue())
return "true";
else
return "false";
}
/*****************************************************************************/ | 43.578125 | 150 | 0.347556 | [
"vector"
] |
92b9bc9760e6640db115d0a2b389037abcfdd690 | 4,285 | cc | C++ | ompi/contrib/vt/vt/tools/vtfilter/vt_filter_gen.cc | urids/XSCALAMPI | 38624f682211d55c047183637fed8dbcc09f6d74 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2019-02-25T19:56:36.000Z | 2019-02-25T19:56:36.000Z | ompi/contrib/vt/vt/tools/vtfilter/vt_filter_gen.cc | urids/XSCALAMPI | 38624f682211d55c047183637fed8dbcc09f6d74 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | ompi/contrib/vt/vt/tools/vtfilter/vt_filter_gen.cc | urids/XSCALAMPI | 38624f682211d55c047183637fed8dbcc09f6d74 | [
"BSD-3-Clause-Open-MPI"
] | 3 | 2015-11-29T06:00:56.000Z | 2021-03-29T07:03:29.000Z | /**
* VampirTrace
* http://www.tu-dresden.de/zih/vampirtrace
*
* Copyright (c) 2005-2013, ZIH, TU Dresden, Federal Republic of Germany
*
* Copyright (c) 1998-2005, Forschungszentrum Juelich, Juelich Supercomputing
* Centre, Federal Republic of Germany
*
* See the file COPYING in the package base directory for details
**/
#include "vt_filter.h"
#include "vt_filter_gen.h"
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern int vtfilter_main( int argc, char** argv );
//////////////////// class FilterGeneratorC ////////////////////
// public methods
//
FilterGeneratorC::FilterGeneratorC() : FilterCommonC()
{
// empty
}
FilterGeneratorC::~FilterGeneratorC()
{
// empty
}
bool
FilterGeneratorC::run()
{
bool error = false;
VPrint( 1, "Generating filter file\n" );
int argc;
char** argv = 0;
char** envp = 0;
do
{
envp = new char*[2];
envp[0] = envp[1] = 0;
// convert program parameters for the old vtfilter
//
if( ( error = !getOldParams( argc, argv, envp ) ) )
break;
// run old vtfilter in gen-mode
//
if( ( error = ( vtfilter_main( argc, argv ) != 0 ) ) )
break;
VPrint( 1, "Done\n" );
} while( false );
// free some memory
//
if( argv )
{
for( int i = 0; i < argc; i++ )
delete [] argv[i];
delete [] argv;
}
//if( envp )
{
if( envp[0] )
delete [] envp[0];
if( envp[1] )
delete [] envp[1];
delete [] envp;
}
return !error;
}
// private methods
//
bool
FilterGeneratorC::getOldParams( int& argc, char**& argv, char**& envp )
{
// at this point we should have an input trace file and an output filter file
//
vt_assert( !Params.input_trcfile.empty() );
vt_assert( !Params.g_output_filtfile.empty() );
// vector of converted command line options
std::vector<std::string> args;
std::ostringstream os;
// pathname of program's executable (argv[0])
args.push_back( "vtfilter" );
// -gen
args.push_back( "-gen" );
// -p
//
if( Params.show_progress )
args.push_back( "-p" );
// -fo
//
args.push_back( "-fo" );
args.push_back( Params.g_output_filtfile );
// -r
//
if( Params.g_reduce_ratio == 0 )
Params.g_reduce_ratio = 100;
args.push_back( "-r" );
os << Params.g_reduce_ratio;
args.push_back( os.str() );
os.str(""); os.clear();
// -l
//
args.push_back( "-l" );
os << Params.g_call_limit;
args.push_back( os.str() );
os.str(""); os.clear();
// -stats
//
if( Params.g_print_stats )
args.push_back( "-stats" );
// -in
//
if( Params.g_incl_funcs.size() > 0 )
{
args.push_back( "-in" );
std::string incl_list = "";
for( uint32_t i = 0; i < Params.g_incl_funcs.size(); i++ )
{
incl_list += Params.g_incl_funcs[i];
if( i < Params.g_incl_funcs.size() - 1 )
incl_list += ",";
}
args.push_back( incl_list );
}
// -ex
//
if( Params.g_excl_funcs.size() > 0 )
{
args.push_back( "-ex" );
std::string excl_list = "";
for( uint32_t i = 0; i < Params.g_excl_funcs.size(); i++ )
{
excl_list += Params.g_excl_funcs[i];
if( i < Params.g_excl_funcs.size() - 1 )
excl_list += ",";
}
args.push_back( excl_list );
}
// -inc
//
if( Params.g_incl_callees )
args.push_back( "-inc" );
// input trace file
args.push_back( Params.input_trcfile );
// env. TRACEFILTER_INCLUDEFILE
//
if( !Params.g_incl_file.empty() )
{
envp[0] = new char[24 + Params.g_incl_file.length() + 1];
vt_assert( envp[0] );
sprintf( envp[0], "TRACEFILTER_INCLUDEFILE=%s",
Params.g_incl_file.c_str() );
putenv( envp[0] );
}
// env. TRACEFILTER_EXCLUDEFILE
//
if( !Params.g_excl_file.empty() )
{
envp[1] = new char[24 + Params.g_excl_file.length() + 1];
vt_assert( envp[1] );
sprintf( envp[1], "TRACEFILTER_EXCLUDEFILE=%s",
Params.g_excl_file.c_str() );
putenv( envp[1] );
}
// convert C++ vector and strings to array of char*
//
argc = args.size();
argv = new char *[argc];
for( int i = 0; i < argc; i++ )
{
argv[i] = strdup( args[i].c_str() );
vt_assert( argv[i] );
}
return true;
}
| 19.477273 | 79 | 0.576663 | [
"vector"
] |
92bbb3b5acdaead73c1caa6d35274e0587f7037c | 968 | cpp | C++ | src/BabylonCpp/src/meshes/mesh_lod_level.cpp | samdauwe/BabylonCpp | eea9f761a49bb460ff1324c20e4674ef120e94f1 | [
"Apache-2.0"
] | 277 | 2017-05-18T08:27:10.000Z | 2022-03-26T01:31:37.000Z | src/BabylonCpp/src/meshes/mesh_lod_level.cpp | samdauwe/BabylonCpp | eea9f761a49bb460ff1324c20e4674ef120e94f1 | [
"Apache-2.0"
] | 77 | 2017-09-03T15:35:02.000Z | 2022-03-28T18:47:20.000Z | src/BabylonCpp/src/meshes/mesh_lod_level.cpp | samdauwe/BabylonCpp | eea9f761a49bb460ff1324c20e4674ef120e94f1 | [
"Apache-2.0"
] | 37 | 2017-03-30T03:36:24.000Z | 2022-01-28T08:28:36.000Z | #include <babylon/meshes/mesh_lod_level.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/meshes/mesh.h>
namespace BABYLON {
MeshLODLevel::MeshLODLevel(float iDistanceOrScreenCoverage, const MeshPtr& iMesh)
: distanceOrScreenCoverage{iDistanceOrScreenCoverage}, mesh{iMesh}
{
}
MeshLODLevel::MeshLODLevel(const MeshLODLevel& other) = default;
MeshLODLevel::MeshLODLevel(MeshLODLevel&& other) = default;
MeshLODLevel& MeshLODLevel::operator=(const MeshLODLevel& other) = default;
MeshLODLevel& MeshLODLevel::operator=(MeshLODLevel&& other) = default;
MeshLODLevel::~MeshLODLevel() = default;
bool MeshLODLevel::operator==(const MeshLODLevel& other) const
{
return stl_util::almost_equal(distanceOrScreenCoverage, other.distanceOrScreenCoverage)
&& (mesh == other.mesh);
}
bool MeshLODLevel::operator!=(const MeshLODLevel& other) const
{
return !(operator==(other));
}
} // end of namespace BABYLON
| 27.657143 | 90 | 0.742769 | [
"mesh"
] |
92c12bafdd9a35439e97a3a6c3e8c805820aac7a | 4,925 | cc | C++ | tests/cpp/texture_copy_test.cc | XiaoSong9905/tvm | 48940f697e15d5b50fa1f032003e6c700ae1e423 | [
"Apache-2.0"
] | 4,640 | 2017-08-17T19:22:15.000Z | 2019-11-04T15:29:46.000Z | tests/cpp/texture_copy_test.cc | XiaoSong9905/tvm | 48940f697e15d5b50fa1f032003e6c700ae1e423 | [
"Apache-2.0"
] | 3,022 | 2020-11-24T14:02:31.000Z | 2022-03-31T23:55:31.000Z | tests/cpp/texture_copy_test.cc | XiaoSong9905/tvm | 48940f697e15d5b50fa1f032003e6c700ae1e423 | [
"Apache-2.0"
] | 1,352 | 2017-08-17T19:30:38.000Z | 2019-11-04T16:09:29.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <dmlc/logging.h>
#include <gtest/gtest.h>
#include <tvm/runtime/registry.h>
#include <cmath>
#include <random>
TEST(TextureCopy, HostDeviceRT) {
using namespace tvm;
bool enabled = tvm::runtime::RuntimeEnabled("opencl");
if (!enabled) {
LOG(INFO) << "Skip texture copy test because opencl runtime is disabled.\n";
return;
}
std::vector<int64_t> shape{16, 16, 4};
auto cpu_arr0 = runtime::NDArray::Empty(shape, {kDLFloat, 32, 1}, {kDLCPU, 0});
auto cpu_arr1 = runtime::NDArray::Empty(shape, {kDLFloat, 32, 1}, {kDLCPU, 0});
String mem_scope = "global.texture";
auto opencl_txarr0 = runtime::NDArray::Empty(shape, {kDLFloat, 32, 1}, {kDLOpenCL, 0}, mem_scope);
size_t size = 1;
for (size_t i = 0; i < shape.size(); ++i) {
size *= static_cast<size_t>(shape[i]);
}
std::random_device dev;
std::mt19937 mt(dev());
std::uniform_real_distribution<> random(-10.0, 10.0);
// Random initialize host ndarray
for (size_t i = 0; i < size; i++) {
static_cast<float*>(cpu_arr0->data)[i] = random(mt);
}
// Do a roundtrip from host storage to opencl texture storage and back
cpu_arr0.CopyTo(opencl_txarr0);
opencl_txarr0.CopyTo(cpu_arr1);
for (size_t i = 0; i < size; ++i) {
ICHECK_LT(
std::fabs(static_cast<float*>(cpu_arr1->data)[i] - static_cast<float*>(cpu_arr0->data)[i]),
1e-5);
}
}
TEST(TextureCopy, OverwritePoolSubview) {
using namespace tvm;
bool enabled = tvm::runtime::RuntimeEnabled("opencl");
if (!enabled) {
LOG(INFO) << "Skip texture copy test because opencl runtime is disabled.\n";
return;
}
std::vector<int64_t> shape{16, 16, 4};
std::vector<int64_t> shape_pool{32, 32, 4};
auto cpu_arr0 = runtime::NDArray::Empty(shape, {kDLFloat, 32, 1}, {kDLCPU, 0});
auto cpu_arr1 = runtime::NDArray::Empty(shape, {kDLFloat, 32, 1}, {kDLCPU, 0});
auto cpu_pool0 = runtime::NDArray::Empty(shape_pool, {kDLFloat, 32, 1}, {kDLCPU, 0});
auto cpu_pool1 = runtime::NDArray::Empty(shape_pool, {kDLFloat, 32, 1}, {kDLCPU, 0});
String mem_scope = "global.texture";
auto opencl_txpool =
runtime::NDArray::Empty(shape_pool, {kDLFloat, 32, 1}, {kDLOpenCL, 0}, mem_scope);
auto opencl_txarr0 = opencl_txpool.CreateView(shape, {kDLFloat, 32, 1});
std::random_device dev;
std::mt19937 mt(dev());
std::uniform_real_distribution<> random(-10.0, 10.0);
size_t size = 1;
size_t size_pool = 1;
for (size_t i = 0; i < shape_pool.size(); ++i) {
size *= static_cast<size_t>(shape[i]);
size_pool *= static_cast<size_t>(shape_pool[i]);
}
// Random initialize host pool storage
for (size_t i = 0; i < size_pool; i++) {
static_cast<float*>(cpu_pool0->data)[i] = random(mt);
}
// Random initialize host array
for (int64_t h = 0; h < shape[0]; h++) {
for (int64_t w = 0; w < shape[1]; w++) {
for (int64_t rgba = 0; rgba < shape[2]; rgba++) {
static_cast<float*>(cpu_arr0->data)[shape[1] * shape[2] * h + shape[2] * w + rgba] = 1.1f;
}
}
}
// Copy to texture pool for initialization
cpu_pool0.CopyTo(opencl_txpool);
// Copy host data to subview into texture storage
cpu_arr0.CopyTo(opencl_txarr0);
// Copy modified pool back
opencl_txpool.CopyTo(cpu_pool1);
// Check that modifications to pool follow two dimensional
// strides according to the written texture shape.
for (int64_t h = 0; h < shape_pool[0]; h++) {
for (int64_t w = 0; w < shape_pool[1]; w++) {
for (int64_t rgba = 0; rgba < shape_pool[2]; rgba++) {
size_t i = shape_pool[1] * shape_pool[2] * h + shape_pool[2] * w + rgba;
if (h < shape[0] && w < shape[1] && rgba < shape[2]) {
size_t j = shape[1] * shape[2] * h + shape[2] * w + rgba;
ICHECK_LT(std::fabs(static_cast<float*>(cpu_pool1->data)[i] -
static_cast<float*>(cpu_arr0->data)[j]),
1e-5);
} else {
ICHECK_LT(std::fabs(static_cast<float*>(cpu_pool1->data)[i] -
static_cast<float*>(cpu_pool0->data)[i]),
1e-5);
}
}
}
}
}
| 35.948905 | 100 | 0.641218 | [
"shape",
"vector"
] |
92c6a0d98d5cb597ebb010bd5ee8c9689b2f0549 | 7,377 | cpp | C++ | torrentsqltablemodel.cpp | silverqx/qMedia | 33447c3dba32c430f4afac797ee6438b60809dda | [
"MIT"
] | null | null | null | torrentsqltablemodel.cpp | silverqx/qMedia | 33447c3dba32c430f4afac797ee6438b60809dda | [
"MIT"
] | null | null | null | torrentsqltablemodel.cpp | silverqx/qMedia | 33447c3dba32c430f4afac797ee6438b60809dda | [
"MIT"
] | null | null | null | #include "torrentsqltablemodel.h"
#include <QDateTime>
#include <QDebug>
#include <QHeaderView>
#include <QLocale>
#include <QSqlField>
#include <QSqlRecord>
#include <QTableView>
#include "common.h"
#include "torrentstatus.h"
#include "torrenttransfertableview.h"
#include "utils/misc.h"
TorrentSqlTableModel::TorrentSqlTableModel(
TorrentTransferTableView *const parent,
const QSqlDatabase db // NOLINT(performance-unnecessary-value-param)
)
: QSqlTableModel(parent, db)
, m_torrentTableView(parent)
, m_statusHash(StatusHash::instance())
{}
QVariant TorrentSqlTableModel::data(const QModelIndex &modelIndex, const int role) const
{
if (!modelIndex.isValid())
return {};
const auto column = modelIndex.column();
const auto row = modelIndex.row();
const auto getTooltipForNameColumn = [this, &modelIndex, &column, &row]()
{
// Relative cursor position from left side of TorrentTransferTableView
const auto postitionX =
(qobject_cast<QTableView *>(parent())->
horizontalHeader()->mapFromGlobal(QCursor::pos())).x();
// TODO get decorationSize from QStyledItemDelegate ( see NOTES.txt ) silverqx
// Cursor is over icon
static const auto iconWidth = 24;
if (postitionX <= iconWidth)
return (*m_statusHash)[record(row).value("status").toString()].title;
return displayValue(modelIndex, column);
};
const auto getPeersTooltip = [this, &row]()
{
// Compute peers count
const auto peers = record(row).value("leechers").toInt() +
record(row).value("seeds").toInt();
const auto peersTotal = record(row).value("total_leechers").toInt() +
record(row).value("total_seeds").toInt();
if (peers == 0 && peersTotal == 0)
return QString {};
return QStringLiteral("Peers: %1 (%2)").arg(peers).arg(peersTotal);
};
switch (role) {
// Set color
case Qt::ForegroundRole:
return (*m_statusHash)[record(row).value("status").toString()].color();
case Qt::DisplayRole:
return displayValue(modelIndex, column);
// Raw database value
case UnderlyingDataRole:
return record(row).value(column);
case Qt::TextAlignmentRole:
switch (column) {
case TR_ID:
case TR_PROGRESS:
return QVariant {Qt::AlignCenter};
case TR_ETA:
case TR_SIZE:
case TR_SEEDS:
case TR_LEECHERS:
case TR_AMOUNT_LEFT:
case TR_ADDED_ON:
case TR_HASH:
return QVariant {Qt::AlignRight | Qt::AlignVCenter};
}
break;
case Qt::FontRole:
switch (column) {
case TR_NAME:
// Increase font size for the name column
auto font = qobject_cast<QTableView *>(parent())->font();
font.setPointSize(12);
return font;
}
break;
// Set icon
case Qt::DecorationRole:
switch (column) {
case TR_NAME:
return (*m_statusHash)[record(row).value("status").toString()].icon();
}
break;
case Qt::ToolTipRole:
switch (column) {
case TR_NAME:
return getTooltipForNameColumn();
case TR_SEEDS:
case TR_LEECHERS:
return getPeersTooltip();
}
break;
}
return QSqlTableModel::data(modelIndex, role);
}
QVariant TorrentSqlTableModel::headerData(
const int section, const Qt::Orientation orientation, const int role) const
{
switch (role) {
// Initial sort order by section
case Qt::InitialSortOrderRole:
switch (section) {
case TR_NAME:
return Qt::AscendingOrder;
default:
return Qt::DescendingOrder;
}
break;
}
return QSqlTableModel::headerData(section, orientation, role);
}
int TorrentSqlTableModel::getTorrentRowByInfoHash(const QString &infoHash) const
{
if (m_torrentMap.contains(infoHash))
return m_torrentMap[infoHash];
qDebug().noquote() << "Torrent with this info hash doesn't exist :" << infoHash;
return -1;
}
quint64 TorrentSqlTableModel::getTorrentIdByInfoHash(const QString &infoHash) const
{
// TODO investigate return value 0 and alternatives like exception and similar, or nullable type, std::optional is right solution, leaving it for now, may be refactor later silverqx
if (m_torrentIdMap.contains(infoHash))
return m_torrentIdMap[infoHash];
qDebug().noquote() << "Torrent with this info hash doesn't exist :" << infoHash;
return 0;
}
const QHash<int, int> &TorrentSqlTableModel::mapPeersToTotal()
{
static const QHash<int, int> cached {
{TorrentSqlTableModel::TR_SEEDS, TorrentSqlTableModel::TR_TOTAL_SEEDS},
{TorrentSqlTableModel::TR_LEECHERS, TorrentSqlTableModel::TR_TOTAL_LEECHERS},
};
return cached;
}
bool TorrentSqlTableModel::select()
{
// Populate model
bool retVal = QSqlTableModel::select();
// Create hash maps from populated data
createInfoHashToRowTorrentMap();
return retVal;
}
QString TorrentSqlTableModel::displayValue(const QModelIndex &modelIndex,
const int column) const
{
const auto unitString = [](const auto value, const bool isSpeedUnit = false)
{
return value == 0 && ::HIDE_ZERO_VALUES
? QString {}
: Utils::Misc::friendlyUnit(value, isSpeedUnit);
};
const auto amountString = [](const auto value, const auto total)
{
return value == 0 && total == 0 && ::HIDE_ZERO_VALUES
? QString {}
: QStringLiteral("%1 (%2)").arg(value).arg(total);
};
// Get value from underlying model
const auto row = modelIndex.row();
const auto rawData = record(row).value(column);
if (!rawData.isValid() || rawData.isNull())
return {};
switch (column) {
case TR_ID:
case TR_NAME:
case TR_HASH:
return rawData.toString();
case TR_PROGRESS:
return QString::number(rawData.toReal() / 10) + QChar('%');
case TR_ETA: {
// If qBittorrent is not running, show ∞ for every torrent
if (!m_torrentTableView->isqBittorrentUp())
return ::C_INFINITY;
return Utils::Misc::userFriendlyDuration(rawData.toLongLong(), ::MAX_ETA);
}
case TR_ADDED_ON:
return QLocale::system().toString(rawData.toDateTime(), QLocale::ShortFormat);
case TR_SIZE:
case TR_AMOUNT_LEFT:
return unitString(rawData.toLongLong());
case TR_SEEDS:
case TR_LEECHERS:
return amountString(rawData.toInt(),
record(row).value(mapPeersToTotal().value(column)).toInt());
}
return {};
}
void TorrentSqlTableModel::createInfoHashToRowTorrentMap()
{
for (auto i = 0; i < rowCount() ; ++i) {
const auto torrentHash = data(index(i, TR_HASH), UnderlyingDataRole).toString();
// Map a torrent info hash to the table row
m_torrentMap[torrentHash] = i;
// Map a torrent info hash to the torrent id
m_torrentIdMap[torrentHash] = data(index(i, TR_ID), UnderlyingDataRole)
.toULongLong();
}
}
| 29.390438 | 185 | 0.620849 | [
"model"
] |
92c9aae9bbc8a7307528d49ce4e2116edb210365 | 8,249 | cpp | C++ | vod/src/v20180717/model/MediaTrackItem.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | vod/src/v20180717/model/MediaTrackItem.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | vod/src/v20180717/model/MediaTrackItem.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"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/vod/v20180717/model/MediaTrackItem.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Vod::V20180717::Model;
using namespace std;
MediaTrackItem::MediaTrackItem() :
m_typeHasBeenSet(false),
m_videoItemHasBeenSet(false),
m_audioItemHasBeenSet(false),
m_stickerItemHasBeenSet(false),
m_transitionItemHasBeenSet(false),
m_emptyItemHasBeenSet(false)
{
}
CoreInternalOutcome MediaTrackItem::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Type") && !value["Type"].IsNull())
{
if (!value["Type"].IsString())
{
return CoreInternalOutcome(Error("response `MediaTrackItem.Type` IsString=false incorrectly").SetRequestId(requestId));
}
m_type = string(value["Type"].GetString());
m_typeHasBeenSet = true;
}
if (value.HasMember("VideoItem") && !value["VideoItem"].IsNull())
{
if (!value["VideoItem"].IsObject())
{
return CoreInternalOutcome(Error("response `MediaTrackItem.VideoItem` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_videoItem.Deserialize(value["VideoItem"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_videoItemHasBeenSet = true;
}
if (value.HasMember("AudioItem") && !value["AudioItem"].IsNull())
{
if (!value["AudioItem"].IsObject())
{
return CoreInternalOutcome(Error("response `MediaTrackItem.AudioItem` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_audioItem.Deserialize(value["AudioItem"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_audioItemHasBeenSet = true;
}
if (value.HasMember("StickerItem") && !value["StickerItem"].IsNull())
{
if (!value["StickerItem"].IsObject())
{
return CoreInternalOutcome(Error("response `MediaTrackItem.StickerItem` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_stickerItem.Deserialize(value["StickerItem"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_stickerItemHasBeenSet = true;
}
if (value.HasMember("TransitionItem") && !value["TransitionItem"].IsNull())
{
if (!value["TransitionItem"].IsObject())
{
return CoreInternalOutcome(Error("response `MediaTrackItem.TransitionItem` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_transitionItem.Deserialize(value["TransitionItem"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_transitionItemHasBeenSet = true;
}
if (value.HasMember("EmptyItem") && !value["EmptyItem"].IsNull())
{
if (!value["EmptyItem"].IsObject())
{
return CoreInternalOutcome(Error("response `MediaTrackItem.EmptyItem` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_emptyItem.Deserialize(value["EmptyItem"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_emptyItemHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void MediaTrackItem::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_typeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Type";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_type.c_str(), allocator).Move(), allocator);
}
if (m_videoItemHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VideoItem";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_videoItem.ToJsonObject(value[key.c_str()], allocator);
}
if (m_audioItemHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AudioItem";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_audioItem.ToJsonObject(value[key.c_str()], allocator);
}
if (m_stickerItemHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "StickerItem";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_stickerItem.ToJsonObject(value[key.c_str()], allocator);
}
if (m_transitionItemHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TransitionItem";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_transitionItem.ToJsonObject(value[key.c_str()], allocator);
}
if (m_emptyItemHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EmptyItem";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_emptyItem.ToJsonObject(value[key.c_str()], allocator);
}
}
string MediaTrackItem::GetType() const
{
return m_type;
}
void MediaTrackItem::SetType(const string& _type)
{
m_type = _type;
m_typeHasBeenSet = true;
}
bool MediaTrackItem::TypeHasBeenSet() const
{
return m_typeHasBeenSet;
}
VideoTrackItem MediaTrackItem::GetVideoItem() const
{
return m_videoItem;
}
void MediaTrackItem::SetVideoItem(const VideoTrackItem& _videoItem)
{
m_videoItem = _videoItem;
m_videoItemHasBeenSet = true;
}
bool MediaTrackItem::VideoItemHasBeenSet() const
{
return m_videoItemHasBeenSet;
}
AudioTrackItem MediaTrackItem::GetAudioItem() const
{
return m_audioItem;
}
void MediaTrackItem::SetAudioItem(const AudioTrackItem& _audioItem)
{
m_audioItem = _audioItem;
m_audioItemHasBeenSet = true;
}
bool MediaTrackItem::AudioItemHasBeenSet() const
{
return m_audioItemHasBeenSet;
}
StickerTrackItem MediaTrackItem::GetStickerItem() const
{
return m_stickerItem;
}
void MediaTrackItem::SetStickerItem(const StickerTrackItem& _stickerItem)
{
m_stickerItem = _stickerItem;
m_stickerItemHasBeenSet = true;
}
bool MediaTrackItem::StickerItemHasBeenSet() const
{
return m_stickerItemHasBeenSet;
}
MediaTransitionItem MediaTrackItem::GetTransitionItem() const
{
return m_transitionItem;
}
void MediaTrackItem::SetTransitionItem(const MediaTransitionItem& _transitionItem)
{
m_transitionItem = _transitionItem;
m_transitionItemHasBeenSet = true;
}
bool MediaTrackItem::TransitionItemHasBeenSet() const
{
return m_transitionItemHasBeenSet;
}
EmptyTrackItem MediaTrackItem::GetEmptyItem() const
{
return m_emptyItem;
}
void MediaTrackItem::SetEmptyItem(const EmptyTrackItem& _emptyItem)
{
m_emptyItem = _emptyItem;
m_emptyItemHasBeenSet = true;
}
bool MediaTrackItem::EmptyItemHasBeenSet() const
{
return m_emptyItemHasBeenSet;
}
| 28.25 | 133 | 0.676809 | [
"object",
"model"
] |
92cdd58214caa068e7042ce9086ec118f42d943f | 5,553 | cxx | C++ | panda/src/particlesystem/discEmitter.cxx | kestred/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | panda/src/particlesystem/discEmitter.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | panda/src/particlesystem/discEmitter.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | // Filename: discEmitter.cxx
// Created by: charles (22Jun00)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "discEmitter.h"
////////////////////////////////////////////////////////////////////
// Function : DiscEmitter::DiscEmitter
// Access : Public
// Description : constructor
////////////////////////////////////////////////////////////////////
DiscEmitter::
DiscEmitter() {
_radius = 1.0f;
_inner_aoe = _outer_aoe = 0.0f;
_inner_magnitude = _outer_magnitude = 1.0f;
_cubic_lerping = false;
}
////////////////////////////////////////////////////////////////////
// Function : DiscEmitter::DiscEmitter
// Access : Public
// Description : copy constructor
////////////////////////////////////////////////////////////////////
DiscEmitter::
DiscEmitter(const DiscEmitter ©) :
BaseParticleEmitter(copy) {
_radius = copy._radius;
_inner_aoe = copy._inner_aoe;
_outer_aoe = copy._outer_aoe;
_inner_magnitude = copy._inner_magnitude;
_outer_magnitude = copy._outer_magnitude;
_cubic_lerping = copy._cubic_lerping;
_distance_from_center = copy._distance_from_center;
_sinf_theta = copy._sinf_theta;
_cosf_theta = copy._cosf_theta;
}
////////////////////////////////////////////////////////////////////
// Function : DiscEmitter::~DiscEmitter
// Access : Public
// Description : destructor
////////////////////////////////////////////////////////////////////
DiscEmitter::
~DiscEmitter() {
}
////////////////////////////////////////////////////////////////////
// Function : make_copy
// Access : Public
// Description : copier
////////////////////////////////////////////////////////////////////
BaseParticleEmitter *DiscEmitter::
make_copy() {
return new DiscEmitter(*this);
}
////////////////////////////////////////////////////////////////////
// Function : DiscEmitter::assign_initial_position
// Access : Public
// Description : Generates a location for a new particle
////////////////////////////////////////////////////////////////////
void DiscEmitter::
assign_initial_position(LPoint3& pos) {
// position
PN_stdfloat theta = NORMALIZED_RAND() * 2.0f * MathNumbers::pi_f;
_distance_from_center = NORMALIZED_RAND();
PN_stdfloat r_scalar = _distance_from_center * _radius;
_sinf_theta = sinf(theta);
_cosf_theta = cosf(theta);
PN_stdfloat new_x = _cosf_theta * r_scalar;
PN_stdfloat new_y = _sinf_theta * r_scalar;
pos.set(new_x, new_y, 0.0f);
}
////////////////////////////////////////////////////////////////////
// Function : DiscEmitter::assign_initial_velocity
// Access : Public
// Description : Generates a velocity for a new particle
////////////////////////////////////////////////////////////////////
void DiscEmitter::
assign_initial_velocity(LVector3& vel) {
PN_stdfloat aoe, mag;
// lerp type
if (_cubic_lerping == true) {
aoe = CLERP(_distance_from_center, _inner_aoe, _outer_aoe);
mag = CLERP(_distance_from_center, _inner_magnitude, _outer_magnitude);
}
else {
aoe = LERP(_distance_from_center, _inner_aoe, _outer_aoe);
mag = LERP(_distance_from_center, _inner_magnitude, _outer_magnitude);
}
// velocity
PN_stdfloat vel_z = mag * sinf(deg_2_rad(aoe));
PN_stdfloat abs_diff = fabs((mag * mag) - (vel_z * vel_z));
PN_stdfloat root_mag_minus_z_squared = sqrtf(abs_diff);
PN_stdfloat vel_x = _cosf_theta * root_mag_minus_z_squared;
PN_stdfloat vel_y = _sinf_theta * root_mag_minus_z_squared;
// quick and dirty
if((aoe > 90.0f) && (aoe < 270.0f))
{
vel_x = -vel_x;
vel_y = -vel_y;
}
vel.set(vel_x, vel_y, vel_z);
}
////////////////////////////////////////////////////////////////////
// Function : output
// Access : Public
// Description : Write a string representation of this instance to
// <out>.
////////////////////////////////////////////////////////////////////
void DiscEmitter::
output(ostream &out) const {
#ifndef NDEBUG //[
out<<"DiscEmitter";
#endif //] NDEBUG
}
////////////////////////////////////////////////////////////////////
// Function : write
// Access : Public
// Description : Write a string representation of this instance to
// <out>.
////////////////////////////////////////////////////////////////////
void DiscEmitter::
write(ostream &out, int indent) const {
#ifndef NDEBUG //[
out.width(indent); out<<""; out<<"DiscEmitter:\n";
out.width(indent+2); out<<""; out<<"_radius "<<_radius<<"\n";
out.width(indent+2); out<<""; out<<"_outer_aoe "<<_outer_aoe<<"\n";
out.width(indent+2); out<<""; out<<"_inner_aoe "<<_inner_aoe<<"\n";
out.width(indent+2); out<<""; out<<"_outer_magnitude "<<_outer_magnitude<<"\n";
out.width(indent+2); out<<""; out<<"_inner_magnitude "<<_inner_magnitude<<"\n";
out.width(indent+2); out<<""; out<<"_cubic_lerping "<<_cubic_lerping<<"\n";
out.width(indent+2); out<<""; out<<"_distance_from_center "<<_distance_from_center<<"\n";
out.width(indent+2); out<<""; out<<"_sinf_theta "<<_sinf_theta<<"\n";
out.width(indent+2); out<<""; out<<"_cosf_theta "<<_cosf_theta<<"\n";
BaseParticleEmitter::write(out, indent+2);
#endif //] NDEBUG
}
| 34.277778 | 91 | 0.535026 | [
"3d"
] |
92cee1bb397e9f1751f724deb8a89b09bcf34913 | 1,374 | cc | C++ | src/Eval/RuleProcessing.cc | mnowotnik/fovris | 82f692743fa6c96fef05041e686d716b03c22f07 | [
"BSD-3-Clause"
] | 4 | 2017-01-04T17:22:55.000Z | 2018-12-08T02:10:18.000Z | src/Eval/RuleProcessing.cc | Mike-Now/fovris | 82f692743fa6c96fef05041e686d716b03c22f07 | [
"BSD-3-Clause"
] | null | null | null | src/Eval/RuleProcessing.cc | Mike-Now/fovris | 82f692743fa6c96fef05041e686d716b03c22f07 | [
"BSD-3-Clause"
] | 1 | 2022-03-24T05:26:13.000Z | 2022-03-24T05:26:13.000Z | #include "Eval/RuleProcessing.h"
namespace fovris {
std::vector<KBRuleLiteral>
SortRuleLiterals(std::vector<KBRuleLiteral> evalOrder) {
auto it =
std::find_if(evalOrder.begin(), evalOrder.end(),
[](const KBRuleLiteral &rl) { return rl.isUnsafe(); });
// no unsafe return as is
if (it == evalOrder.end()) {
return evalOrder;
}
std::sort(evalOrder.begin(), evalOrder.end(),
[](const KBRuleLiteral &a, const KBRuleLiteral &b) {
if (a.isUnsafe() && b.isUnsafe()) {
return a.getVarSet().size() > b.getVarSet().size();
}
if (a.isUnsafe()) {
if (HaveCommonVariables(a, b)) {
return false;
} else {
return true;
}
}
if (b.isUnsafe()) {
if (HaveCommonVariables(a, b)) {
return true;
} else {
return false;
}
}
return a.getVarSet().size() > b.getVarSet().size();
});
return evalOrder;
}
std::vector<unsigned>
getRelIdsFromSafeLiterals(const std::vector<KBRuleLiteral> &ruleBody) {
std::vector<unsigned> relationIds;
for (auto &rl : ruleBody) {
if (!rl.isUnsafe()) {
relationIds.push_back(rl.getRelId());
}
}
return relationIds;
}
} // fovris
| 25.924528 | 76 | 0.521106 | [
"vector"
] |
92d2c83658c1809595ac3df202361e43678cc8a2 | 3,326 | cpp | C++ | LaserBombon/Menu.cpp | Calvin-Ruiz/LaserBombon | 404bea5b95393b3d011902a0d1458bd86efdc5a5 | [
"MIT"
] | null | null | null | LaserBombon/Menu.cpp | Calvin-Ruiz/LaserBombon | 404bea5b95393b3d011902a0d1458bd86efdc5a5 | [
"MIT"
] | null | null | null | LaserBombon/Menu.cpp | Calvin-Ruiz/LaserBombon | 404bea5b95393b3d011902a0d1458bd86efdc5a5 | [
"MIT"
] | null | null | null | #include "Menu.hpp"
#include "Game.hpp"
#include "EntityLib/Core/EntityLib.hpp"
#include "EntityLib/Core/MenuMgr.hpp"
#include "EntityLib/Core/MenuButton.hpp"
#include "EntityLib/Core/MenuImage.hpp"
#include "EntityLib/Core/MenuText.hpp"
Menu::Menu(Game *master, std::shared_ptr<EntityLib> &core, Player &player1, Player &player2, unsigned short &maxLevel, unsigned int &recursion, unsigned char nbPlayer) : master(master), core(core), player1(player1), player2(player2), maxLevel(maxLevel), recursion(recursion), nbPlayer(nbPlayer)
{
}
Menu::~Menu()
{
}
// Coloring : black = default | blue = maxed | green = gain | red = loss or can't affroad
bool Menu::mainloop(int type)
{
menu = std::make_unique<MenuMgr>(core, this, (type == RESEARCH) ? selectResearchPage : nullptr);
std::vector<MenuText *> texts;
std::vector<MenuImage *> images;
std::vector<MenuButton *> buttons;
images.push_back(new MenuImage(*menu));
images[0]->addDependency({nullptr, 0, 0, 0, Align::LEFT | Align::UP});
images[0]->addDependency({nullptr, 1, 1, 0, Align::RIGHT | Align::DOWN});
images[0]->load("menu.png");
// dual equipment submenu or single research menu : NAME IMAGE STATISTICS COST EQUIP/UPGRADE BACK -- all aligned to the name
switch (type) {
case GENERAL:
break;
case LOAD:
master->load(0); // load menu is the first mandatory menu
return true;
break;
case EQUIPMENT:
// dual from here
break;
case RESEARCH:
break;
case DISMANTLE:
texts.push_back(new MenuText(*menu));
texts.back()->setString(std::string("Are you sure to dismantle for research ?\nYour score, level and equipment will be resetted.\nResearch gain depend on your equipment and score.\nYou will get ") + EntityLib::toText(master->getRecursionGain()) + "/" + EntityLib::toText(master->getMaxedRecursionGain()) + "research points.\nAfter dismantle, your score will be of " + EntityLib::toText(master->getScoreAfterRecursion()) + ".");
texts.back()->addDependency({texts.back(), 0, 0.6, Align::UP, Align::DOWN});
texts.back()->addDependency({nullptr, 0.5, 0.4, 0, Align::CENTER});
buttons.push_back(new MenuButton(*menu, this, &backButton, "Cancel", "button.png", 0.01));
buttons.back()->setColor({240, 64, 64, 255});
buttons.back()->addDependency({buttons.back(), 0.3, 0.1, Align::UP | Align::LEFT, Align::DOWN | Align::RIGHT});
buttons.back()->addDependency({nullptr, 0.3, 0.85, 0, Align::CENTER});
buttons.push_back(new MenuButton(*menu, this, &dismantleButton, "Dismantle", "button.png", 0.01));
buttons.back()->setColor({64, 240, 64, 255});
buttons.back()->addDependency({buttons.back(), 0.3, 0.1, Align::UP | Align::LEFT, Align::DOWN | Align::RIGHT});
buttons.back()->addDependency({buttons[0], 0.7, 0, Align::UP | Align::DOWN, Align::CENTER});
break;
}
return menu->mainloop(type != LOAD);
}
void Menu::backButton(void *data, MenuButton *button)
{
reinterpret_cast<Menu *>(data)->menu->close();
}
void Menu::dismantleButton(void *data, MenuButton *button)
{
}
void Menu::selectResearchPage(void *data, int pageShift, int player)
{
}
| 46.194444 | 439 | 0.645219 | [
"vector"
] |
92d2fff0bfde7ec52b13d4c1db9740333c221f00 | 19,927 | cpp | C++ | samples/driver_easimer/hmd_lua.cpp | Easimer/openvr | 11d9d23f0237ce801ff30a911bdffea0713529b3 | [
"BSD-3-Clause"
] | null | null | null | samples/driver_easimer/hmd_lua.cpp | Easimer/openvr | 11d9d23f0237ce801ff30a911bdffea0713529b3 | [
"BSD-3-Clause"
] | null | null | null | samples/driver_easimer/hmd_lua.cpp | Easimer/openvr | 11d9d23f0237ce801ff30a911bdffea0713529b3 | [
"BSD-3-Clause"
] | null | null | null | // === Copyright (c) 2017-2020 easimer.net. All rights reserved. ===
#include "hmd_lua.h"
#include "driverlog.h"
extern "C" {
#include "lauxlib.h"
#include "lua.h"
#include "lualib.h"
}
#include "CSteamController.h"
using namespace vr;
#define TABLE_VRDISP "VRDisplayComponent"
#define TABLE_TRACKDEV "TrackedDeviceServerDriver"
#define TABLE_CONTROL "SteamController"
// Convert a HmdQuaternion_t into a Lua table
// If the operation is successful, the top of the stack contains
// the table and true is returned.
// On failure the stack remains balanced and false is returned.
// [-0, +1, e]
static bool ToLuaTable(lua_State* L, const vr::HmdQuaternion_t& ev) {
bool ret = false;
if (L) {
lua_newtable(L); // +1
lua_pushstring(L, "w"); lua_pushnumber(L, ev.w); lua_settable(L, -3);
lua_pushstring(L, "x"); lua_pushnumber(L, ev.x); lua_settable(L, -3);
lua_pushstring(L, "y"); lua_pushnumber(L, ev.y); lua_settable(L, -3);
lua_pushstring(L, "z"); lua_pushnumber(L, ev.z); lua_settable(L, -3);
ret = true;
}
return ret;
}
// Convert a SteamControllerUpdateEvent into a Lua table
// If the operation is successful, the top of the stack contains
// the table and true is returned.
// On failure the stack remains balanced and false is returned.
// [-0, +1, e]
static bool ToLuaTable(lua_State* L, const SteamControllerUpdateEvent& ev) {
bool ret = false;
if (L) {
lua_newtable(L); // +1
auto x = ev.orientation.x / 32767.0f;
auto y = ev.orientation.y / 32767.0f;
auto z = ev.orientation.z / 32767.0f;
auto w = 1.0f - sqrtf(x * x + y * y + z * z);
auto orientation = HmdQuaternion_t{ w, x, y, z };
lua_pushstring(L, "orientation"); // +1
if (ToLuaTable(L, orientation)) { // +1
lua_settable(L, -3); // -2
ret = true;
} else {
lua_pop(L, 2); // -2
}
}
return ret;
}
#define X2(x) #x
#define X(x) X2(x)
#define TABLE_GET_T(cont, key, field, conv, coercion) { \
lua_pushstring(L, X(key)); \
lua_gettable(L, -2); \
cont.field = coercion conv(L, -1); \
lua_pop(L, 1); \
}
#define TABLE_MAP_T(cont, key, conv, coercion) TABLE_GET_T(cont, key, key, conv, coercion)
#define TABLE_MAP_NUMBER(cont, key) TABLE_MAP_T(cont, key, lua_tonumber)
#define TABLE_MAP_BOOL(cont, key) TABLE_MAP_T(cont, key, lua_toboolean)
#define TABLE_MAP_INT(cont, key) TABLE_MAP_T(cont, key, lua_tointeger)
#define TABLE_MAP_ENUM(cont, key, type) TABLE_MAP_T(cont, key, lua_tointeger, (type))
#define TABLE_GET_TRIV(cont, key, field, type) { \
lua_pushstring(L, X(key)); \
lua_gettable(L, -2); \
FromLuaTable(L, cont.field); \
}
#define TABLE_MAP_TRIV(cont, key) TABLE_GET_TRIV(cont, key, key)
// Convert the Lua table at the top of the stack to a HMD quat
// Returns true on success and false on failure.
// Pops the table from the stack.
// [-1, +0, -]
static bool FromLuaTable(lua_State* L, vr::HmdQuaternion_t& q) {
bool ret = false;
if (L) {
TABLE_MAP_NUMBER(q, w);
TABLE_MAP_NUMBER(q, x);
TABLE_MAP_NUMBER(q, y);
TABLE_MAP_NUMBER(q, z);
}
lua_pop(L, 1);
return ret;
}
// Convert the Lua table at the top of the stack to driver pose
// Returns true on success and false on failure.
// Pops the table from the stack.
// [-1, +0, -]
static bool FromLuaTable(lua_State* L, DriverPose_t& pose) {
bool ret = false;
pose = { 0 };
if (L) {
TABLE_MAP_BOOL(pose, poseIsValid);
TABLE_MAP_BOOL(pose, deviceIsConnected);
TABLE_MAP_ENUM(pose, result, ETrackingResult);
TABLE_MAP_TRIV(pose, qWorldFromDriverRotation);
TABLE_MAP_TRIV(pose, qDriverFromHeadRotation);
TABLE_MAP_TRIV(pose, qRotation);
ret = true;
}
lua_pop(L, 1);
return ret;
}
class CLuaHMDDriver::BaseLuaInterface {
public:
BaseLuaInterface() : L(NULL), m_nRefMethodTable(LUA_NOREF), m_nRefInstance(LUA_NOREF) {}
BaseLuaInterface(const BaseLuaInterface&) = delete;
BaseLuaInterface(lua_State* L, int nRefMethodTable) : L(L), m_nRefMethodTable(nRefMethodTable) {
if (!CheckMethodTable()) {
DriverLog("Methods are missing!");
}
// Create a new instance by calling Interface:new()
PushMethodTable();
lua_getfield(L, -1, "Create");
PushMethodTable();
lua_call(L, 1, 1);
m_nRefInstance = luaL_ref(L, LUA_REGISTRYINDEX);
if (m_nRefInstance != LUA_NOREF && m_nRefInstance != LUA_REFNIL) {
OnInit();
} else {
DriverLog("new: instance reference is %d, a NOREF or REFNIL!", m_nRefInstance);
}
lua_pop(L, 1);
}
// Push the method table object onto the Lua stack
// [-0, +1, -]
inline void PushMethodTable() {
lua_rawgeti(L, LUA_REGISTRYINDEX, m_nRefMethodTable);
}
// Push the instance object onto the Lua stack
// [-0, +1, -]
inline void PushInstance() {
lua_rawgeti(L, LUA_REGISTRYINDEX, m_nRefInstance);
}
// Call OnInit on the handler instance
// [-0, +0, -]
void OnInit() {
PushMethod("OnInit");
PushInstance();
lua_call(L, 1, 0);
lua_pop(L, 1);
}
virtual ~BaseLuaInterface() {
if (L) {
if (m_nRefInstance != LUA_NOREF && m_nRefMethodTable != LUA_NOREF) {
PushMethod("OnShutdown");
PushInstance();
lua_call(L, 1, 0);
lua_pop(L, 1);
}
if (m_nRefInstance != LUA_NOREF) {
luaL_unref(L, LUA_REGISTRYINDEX, m_nRefInstance);
}
if (m_nRefMethodTable != LUA_NOREF) {
luaL_unref(L, LUA_REGISTRYINDEX, m_nRefMethodTable);
}
}
}
bool IsMethodPresent(char const* pszKey) {
bool ret = true;
PushMethod(pszKey);
if (lua_isnil(L, -1)) {
ret = false;
DriverLog("Interface method missing: %s", pszKey);
}
lua_pop(L, 1);
return ret;
}
virtual bool CheckMethodTable() {
return IsMethodPresent("Create") &&
IsMethodPresent("OnInit") &&
IsMethodPresent("OnShutdown");
}
protected:
// Add a method to the method table
// [-0, +0, -]
void AddMethod(char const* pszKey, lua_CFunction pFunc) {
PushMethodTable(); // +1
lua_pushstring(L, pszKey); // +1
lua_pushcfunction(L, pFunc); // +1
lua_settable(L, -3); // -2
lua_pop(L, 1); // -1
}
// Push a method onto the Lua stack
// Top of the stack will contain the method
// [-0, +2, -]
void PushMethod(char const* pszKey) {
PushMethodTable(); // +1
lua_pushstring(L, pszKey); // +1
lua_gettable(L, -2); // -1 +1
}
lua_State* L;
int m_nRefMethodTable;
int m_nRefInstance;
};
static int Lua_ISteamController_Rumble(lua_State* L) {
auto pSC = (CSteamController*)lua_touserdata(L, -1);
if (pSC) {
pSC->TriggerHaptic(0, 1000, 1000, 500);
pSC->TriggerHaptic(1, 1000, 1000, 500);
}
return 0;
}
class ISteamController : public CLuaHMDDriver::BaseLuaInterface, public CSteamController {
public:
ISteamController(lua_State* L, int nRefMethodTable, SteamControllerDeviceEnum* it) :
CLuaHMDDriver::BaseLuaInterface(L, nRefMethodTable),
CSteamController::CSteamController(it),
m_bReload(false) {
Configure(STEAMCONTROLLER_CONFIG_SEND_ORIENTATION);
DriverLog("Adding Rumble method");
AddMethod("Rumble", Lua_ISteamController_Rumble);
DriverLog("Calling OnConnect");
OnConnect();
}
virtual ~ISteamController() {
}
virtual void OnUpdate(const SteamControllerUpdateEvent& ev) override {
if (ev.buttons & STEAMCONTROLLER_BUTTON_HOME) {
// Reload script
m_bReload = true;
DriverLog("User requested script reload by pressing Home");
} else {
// Propagate event to Lua script
PushMethod("OnUpdate"); // +2
PushInstance(); // +1
if (ToLuaTable(L, ev)) { // +1
lua_call(L, 2, 0); // -3
lua_pop(L, 1); // -1
} else {
lua_pop(L, 3);
}
}
}
virtual bool CheckMethodTable() override {
return CLuaHMDDriver::BaseLuaInterface::CheckMethodTable() &&
IsMethodPresent("OnConnect") &&
IsMethodPresent("OnDisconnect") &&
IsMethodPresent("OnUpdate") &&
IsMethodPresent("GetControllerHandle");
}
bool UserRequestedReload() {
auto ret = m_bReload;
m_bReload = false;
return ret;
}
protected:
void OnConnect() {
PushMethod("OnConnect"); // +2
PushInstance(); // +1
lua_pushlightuserdata(L, this); // +1
lua_call(L, 2, 0); // -3
lua_pop(L, 1); // -1
}
bool m_bReload;
};
static int Lua_AtPanic(lua_State* L) {
const char* pszMsg = lua_tostring(L, -1);
DriverLog("script fatal error: %s", pszMsg);
return 0;
}
static int Lua_DriverLog(lua_State* L) {
const char* pszMsg = lua_tostring(L, -1);
DriverLog("script: %s", pszMsg);
return 0;
}
static int Lua_RegisterHandler(lua_State* L) {
auto driver = (CLuaHMDDriver*)lua_touserdata(L, -3);
if (driver == NULL) {
DriverLog("Lua_RegisterHandler failed because the driver pointer is NULL!");
return 0;
}
auto interfaceId = lua_tostring(L, -2);
// pop table off stack and pin it
auto table = luaL_ref(L, LUA_REGISTRYINDEX);
DriverLog("Registering handler for %s (driver=%p, table=%d)", interfaceId, driver, table);
HandlerType_t type = k_unHandlerType_Max;
CLuaHMDDriver::BaseLuaInterface* pIf = NULL;
if (strcmp(TABLE_CONTROL, interfaceId) == 0) {
type = k_unHandlerType_SteamController;
} else if (strcmp(TABLE_VRDISP, interfaceId) == 0) {
} else if (strcmp(TABLE_TRACKDEV, interfaceId) == 0) {
}
if (type != k_unHandlerType_Max) {
driver->SetHandler(type, table);
}
lua_pop(L, 2);
return 0;
}
static bool InitializeLuaState(lua_State* L, std::string const& sPath) {
int res;
luaL_openlibs(L);
// Set panic func
lua_atpanic(L, Lua_AtPanic);
// Define a DriverLog function for the script
lua_register(L, "DriverLog", Lua_DriverLog);
lua_register(L, "RegisterHandler", Lua_RegisterHandler);
// Load and exec script file
res = luaL_dofile(L, sPath.c_str());
if(res == LUA_OK) {
DriverLog("script loaded successfully!");
return true;
} else {
DriverLog("failed to load the script: %s", lua_tostring(L, -1));
return false;
}
}
CLuaHMDDriver::CLuaHMDDriver(const char* pszPath) :
m_unObjectId(k_unTrackedDeviceIndexInvalid),
m_ulPropertyContainer(k_ulInvalidPropertyContainer),
m_sSerialNumber("SN00000001"),
m_sModelNumber("v1.hmd.vr.easimer.net"),
m_sScriptPath(pszPath),
m_pLua(NULL),
m_pLuaSteamController(NULL) {
for (int i = 0; i < k_unHandlerType_Max; i++) {
m_arefHandlers[i] = LUA_NOREF;
}
Reload();
}
CLuaHMDDriver::~CLuaHMDDriver() {
Unload();
}
static void PushTableFunction(lua_State* L, const char* pchTable, const char* pchFunction) {
lua_getglobal(L, pchTable);
lua_getfield(L, -1, pchFunction);
}
#define DO_SIMPLE_CALLBACK(t, f) \
if (m_pLua != NULL) { \
PushTableFunction(m_pLua, t, f); \
lua_getglobal(m_pLua, t); \
lua_call(m_pLua, 1, 0); \
}
EVRInitError CLuaHMDDriver::Activate(uint32_t unObjectId) {
EVRInitError ret = VRInitError_Init_Internal;
m_unObjectId = unObjectId;
m_ulPropertyContainer = VRProperties()->TrackedDeviceToPropertyContainer(m_unObjectId);
VRProperties()->SetStringProperty(m_ulPropertyContainer, Prop_ModelNumber_String, m_sModelNumber.c_str());
VRProperties()->SetStringProperty(m_ulPropertyContainer, Prop_RenderModelName_String, m_sModelNumber.c_str());
VRProperties()->SetFloatProperty(m_ulPropertyContainer, Prop_UserIpdMeters_Float, 0.063f);
VRProperties()->SetFloatProperty(m_ulPropertyContainer, Prop_UserHeadToEyeDepthMeters_Float, 0.0f);
VRProperties()->SetFloatProperty(m_ulPropertyContainer, Prop_DisplayFrequency_Float, 60.0f);
VRProperties()->SetFloatProperty(m_ulPropertyContainer, Prop_SecondsFromVsyncToPhotons_Float, 0.1f);
VRProperties()->SetUint64Property(m_ulPropertyContainer, Prop_CurrentUniverseId_Uint64, 2);
VRProperties()->SetBoolProperty(m_ulPropertyContainer, Prop_IsOnDesktop_Bool, false);
if (m_pLua != NULL) {
PushTableFunction(m_pLua, TABLE_TRACKDEV, "Activate");
lua_getglobal(m_pLua, TABLE_TRACKDEV);
lua_pushinteger(m_pLua, unObjectId);
lua_call(m_pLua, 2, 1);
if (lua_toboolean(m_pLua, -1)) {
ret = vr::VRInitError_None;
}
lua_pop(m_pLua, 1);
}
return ret;
}
void CLuaHMDDriver::Deactivate() {
DO_SIMPLE_CALLBACK(TABLE_TRACKDEV, "Deactivate");
m_unObjectId = k_unTrackedDeviceIndexInvalid;
}
void CLuaHMDDriver::EnterStandby() {
DO_SIMPLE_CALLBACK(TABLE_TRACKDEV, "EnterStandby");
}
void* CLuaHMDDriver::GetComponent(const char* pchComponentNameAndVersion) {
if (!_stricmp(pchComponentNameAndVersion, vr::IVRDisplayComponent_Version)) {
return (vr::IVRDisplayComponent*)this;
}
return nullptr;
}
void CLuaHMDDriver::DebugRequest(const char* pchRequest, char* pchResponseBuffer, uint32_t unResponseBufferSize) {
if (unResponseBufferSize >= 1) {
pchResponseBuffer[0] = 0;
}
}
vr::DriverPose_t CLuaHMDDriver::GetPose() {
if (m_pLua != NULL) {
DriverPose_t pose = { 0 };
PushTableFunction(m_pLua, TABLE_TRACKDEV, "GetPose");
lua_getglobal(m_pLua, TABLE_TRACKDEV);
lua_call(m_pLua, 1, 1);
if (FromLuaTable(m_pLua, pose)) {
if (pose.result != TrackingResult_Running_OK) {
DriverLog("Tracking result is %d!", pose.result);
}
return pose;
} else {
return { 0 };
}
}
return { 0 };
}
void CLuaHMDDriver::GetWindowBounds(int32_t* pnX, int32_t* pnY, uint32_t* pnWidth, uint32_t* pnHeight) {
if (m_pLua != NULL) {
PushTableFunction(m_pLua, TABLE_VRDISP, "GetWindowBounds");
lua_getglobal(m_pLua, TABLE_VRDISP);
lua_call(m_pLua, 1, 4);
*pnX = lua_tonumber(m_pLua, -4);
*pnY = lua_tonumber(m_pLua, -3);
*pnWidth = lua_tonumber(m_pLua, -2);
*pnHeight = lua_tonumber(m_pLua, -1);
DriverLog("lua GetWindowBounds returned (%d, %d, %u, %u)", *pnX, *pnY, *pnWidth, *pnHeight);
lua_pop(m_pLua, 4);
}
}
bool CLuaHMDDriver::IsDisplayOnDesktop() {
return true;
}
bool CLuaHMDDriver::IsDisplayRealDisplay() {
return false;
}
void CLuaHMDDriver::GetRecommendedRenderTargetSize(uint32_t* pnWidth, uint32_t* pnHeight) {
if (m_pLua != NULL) {
PushTableFunction(m_pLua, TABLE_VRDISP, "GetRecommendedRenderTargetSize");
lua_getglobal(m_pLua, TABLE_VRDISP);
lua_call(m_pLua, 1, 2);
*pnWidth = lua_tonumber(m_pLua, -2);
*pnHeight = lua_tonumber(m_pLua, -1);
DriverLog("lua GetRecommendedRenderTargetSize returned (%u, %u)", *pnWidth, *pnHeight);
lua_pop(m_pLua, 4);
}
}
void CLuaHMDDriver::GetEyeOutputViewport(EVREye eEye, uint32_t* pnX, uint32_t* pnY, uint32_t* pnWidth, uint32_t* pnHeight) {
if (m_pLua != NULL) {
PushTableFunction(m_pLua, TABLE_VRDISP, "GetEyeOutputViewport");
lua_getglobal(m_pLua, TABLE_VRDISP);
lua_pushnumber(m_pLua, eEye);
lua_call(m_pLua, 2, 4);
*pnX = (int32_t)lua_tonumber(m_pLua, -4);
*pnY = (int32_t)lua_tonumber(m_pLua, -3);
*pnWidth = (uint32_t)lua_tonumber(m_pLua, -2);
*pnHeight = (uint32_t)lua_tonumber(m_pLua, -1);
DriverLog("lua GetEyeOutputViewport returned (%d, %d, %u, %u) for eye %d", *pnX, *pnY, *pnWidth, *pnHeight, eEye);
lua_pop(m_pLua, 4);
}
}
void CLuaHMDDriver::GetProjectionRaw(EVREye eEye, float* pfLeft, float* pfRight, float* pfTop, float* pfBottom) {
*pfLeft = -1.0;
*pfRight = 1.0;
*pfTop = -1.0;
*pfBottom = 1.0;
}
DistortionCoordinates_t CLuaHMDDriver::ComputeDistortion(EVREye eEye, float fU, float fV) {
DistortionCoordinates_t coordinates;
coordinates.rfBlue[0] = fU;
coordinates.rfBlue[1] = fV;
coordinates.rfGreen[0] = fU;
coordinates.rfGreen[1] = fV;
coordinates.rfRed[0] = fU;
coordinates.rfRed[1] = fV;
return coordinates;
}
void CLuaHMDDriver::RunFrame() {
vr::VREvent_t vrEvent;
if (m_pLuaSteamController != NULL) {
auto pSC = (ISteamController*)m_pLuaSteamController;
if (pSC) {
pSC->RunFrames();
if (pSC->UserRequestedReload()) {
DriverLog("User requested script reload through Steam Controller");
Reload();
}
} else {
DriverLog("ISteamController* conversion failed?");
}
}
while (vr::VRServerDriverHost()->PollNextEvent(&vrEvent, sizeof(vrEvent))) {
if (vrEvent.eventType == VREvent_SeatedZeroPoseReset) {
DriverLog("SeatedZeroPoseReset!");
DO_SIMPLE_CALLBACK(TABLE_TRACKDEV, "OnSeatedZeroPoseReset");
}
}
VRServerDriverHost()->TrackedDevicePoseUpdated(m_unObjectId, GetPose(), sizeof(DriverPose_t));
}
void CLuaHMDDriver::SetHandler(HandlerType_t type, int refHandler) {
m_arefHandlers[type] = refHandler;
DriverLog("Handler #%d set to %d", type, refHandler);
}
void CLuaHMDDriver::Unload() {
DriverLog("Unloading script...");
if (m_pLuaSteamController != NULL) {
delete m_pLuaSteamController;
m_pLuaSteamController = NULL;
}
if (m_pLua != NULL) {
DO_SIMPLE_CALLBACK(TABLE_VRDISP, "OnShutdown");
DO_SIMPLE_CALLBACK(TABLE_TRACKDEV, "OnShutdown");
lua_close(m_pLua);
m_pLua = NULL;
}
for (int i = 0; i < k_unHandlerType_Max; i++) {
m_arefHandlers[i] = LUA_NOREF;
}
}
void CLuaHMDDriver::Reload() {
Unload();
DriverLog("Creating Lua state");
m_pLua = luaL_newstate();
if (m_pLua) {
DriverLog("Loading script...");
if (InitializeLuaState(m_pLua, m_sScriptPath)) {
DriverLog("Script has been reloaded!");
// Asking script to register it's handlers
// We pass in the pointer to this instance and the function
// will pass it back to us by calling RegisterHandler
lua_getglobal(m_pLua, "API_RegisterHandlers");
lua_pushlightuserdata(m_pLua, this);
lua_call(m_pLua, 1, 0);
DO_SIMPLE_CALLBACK(TABLE_TRACKDEV, "OnInit");
DO_SIMPLE_CALLBACK(TABLE_VRDISP, "OnInit");
// Find first Steam Controller
DriverLog("Discovering Steam Controllers");
auto it = SteamController_EnumControllerDevices();
if (it != NULL) {
DriverLog("Found a Steam Controller");
this->m_pLuaSteamController = new ISteamController(m_pLua, m_arefHandlers[k_unHandlerType_SteamController], it);
do {
it = SteamController_NextControllerDevice(it);
} while (it != NULL);
}
} else {
lua_close(m_pLua);
m_pLua = NULL;
}
} else {
DriverLog("Failed to create Lua state!");
}
}
| 31.480253 | 128 | 0.621017 | [
"object"
] |
92de9a79155a65b75638daa6597ac268553616db | 4,269 | hpp | C++ | Source/cserialization/csystem/CPropertyBase.hpp | zao/CyberpunkSaveEditor | 5ba3f2301936c2e695cefdb9e778f14d29dc23fc | [
"MIT"
] | null | null | null | Source/cserialization/csystem/CPropertyBase.hpp | zao/CyberpunkSaveEditor | 5ba3f2301936c2e695cefdb9e778f14d29dc23fc | [
"MIT"
] | null | null | null | Source/cserialization/csystem/CPropertyBase.hpp | zao/CyberpunkSaveEditor | 5ba3f2301936c2e695cefdb9e778f14d29dc23fc | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <string>
#include <memory>
#include <list>
#include <vector>
#include <array>
#include <exception>
#include <utils.hpp>
#include <cpinternals/cpnames.hpp>
#include <cserialization/serializers.hpp>
#include <cserialization/csystem/CStringPool.hpp>
#ifndef DISABLE_CP_IMGUI_WIDGETS
#include <widgets/list_widget.hpp>
#include <imgui_extras/cpp_imgui.hpp>
#include <imgui_extras/imgui_stdlib.h>
#endif
enum class EPropertyKind
{
None,
Unknown,
Bool,
Integer,
Float,
Double,
Combo,
Array,
DynArray,
Handle,
Object,
TweakDBID,
CName,
NodeRef
};
static inline std::string_view
property_kind_to_display_name(EPropertyKind prop_kind)
{
switch (prop_kind)
{
case EPropertyKind::None: return "None";
case EPropertyKind::Unknown: return "Unknown";
case EPropertyKind::Bool: return "Bool";
case EPropertyKind::Integer: return "Integer";
case EPropertyKind::Float: return "Float";
case EPropertyKind::Double: return "Double";
case EPropertyKind::Combo: return "Combo";
case EPropertyKind::Array: return "Array";
case EPropertyKind::DynArray: return "DynArray";
case EPropertyKind::Handle: return "Handle";
case EPropertyKind::Object: return "Object";
}
return "Invalid";
}
class CProperty
{
EPropertyKind m_property_kind;
protected:
CProperty(EPropertyKind kind)
: m_property_kind(kind) {}
virtual ~CProperty() = default;
public:
EPropertyKind kind() const { return m_property_kind; }
public:
virtual std::string_view ctypename() const = 0;
// serialization
virtual bool serialize_in(std::istream& is, CStringPool& strpool) = 0;
virtual bool serialize_out(std::ostream& os, CStringPool& strpool) const = 0;
// gui (define DISABLE_CP_IMGUI_WIDGETS to disable implementations)
[[nodiscard]] virtual bool imgui_widget(const char* label, bool editable)
{
#ifndef DISABLE_CP_IMGUI_WIDGETS
ImGui::Text("widget not implemented");
return false;
#endif
}
void imgui_widget(const char* label) const
{
std::ignore = const_cast<CProperty*>(this)->imgui_widget(label, false);
}
};
using CPropertySPtr = std::shared_ptr<CProperty>;
//------------------------------------------------------------------------------
// DEFAULT
//------------------------------------------------------------------------------
class CUnknownProperty
: public CProperty
{
protected:
std::string m_ctypename;
std::vector<char> m_data;
std::string m_child_ctypename;
public:
CUnknownProperty(std::string_view ctypename)
: CProperty(EPropertyKind::Unknown), m_ctypename(ctypename)
{
}
~CUnknownProperty() override = default;
public:
const std::vector<char>& raw_data() const { return m_data; };
// overrides
std::string_view ctypename() const override { return m_ctypename; };
bool serialize_in(std::istream& is, CStringPool& strpool) override
{
std::streampos beg = is.tellg();
is.seekg(0, std::ios_base::end);
const size_t size = (size_t)(is.tellg() - beg);
is.seekg(beg);
m_data.resize(size);
is.read(m_data.data(), size);
//std::istream_iterator<char> it(is), end;
//m_data.assign(it, end);
return is.good();
}
virtual bool serialize_out(std::ostream& os, CStringPool& strpool) const
{
os.write(m_data.data(), m_data.size());
return true;
}
#ifndef DISABLE_CP_IMGUI_WIDGETS
[[nodiscard]] bool imgui_widget(const char* label, bool editable) override
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return false;
bool modified = false;
ImGui::BeginChild(label, ImVec2(0,0), true, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::Text("refactoring");
ImGui::Text("ctypename: %s", ctypename().data());
ImGui::Text("data size: %08X", m_data.size());
if (m_data.size() > 50)
ImGui::Text("data: %s...", bytes_to_hex(m_data.data(), 50).c_str());
else
ImGui::Text("data: %s", bytes_to_hex(m_data.data(), m_data.size()).c_str());
ImGui::EndChild();
return modified;
}
#endif
};
| 24.255682 | 84 | 0.642071 | [
"object",
"vector"
] |
92e01f1d1ea2fd55c38d718cf8ffc70ab75a9963 | 1,184 | cpp | C++ | src/routingAlgorithms/Routing_DELTA.cpp | vsskarthik/noxim-new | c5fcb547f172390cfa06988f66c3e89a2ba008af | [
"BSD-4-Clause-UC"
] | 127 | 2015-07-08T14:39:34.000Z | 2022-03-25T08:00:38.000Z | src/routingAlgorithms/Routing_DELTA.cpp | pakeunji/noxim | dbe0b8991b28a44df7c47d940bd59a11cfcc4dd2 | [
"BSD-4-Clause-UC"
] | 124 | 2015-08-03T11:32:05.000Z | 2022-03-24T16:03:02.000Z | src/routingAlgorithms/Routing_DELTA.cpp | pakeunji/noxim | dbe0b8991b28a44df7c47d940bd59a11cfcc4dd2 | [
"BSD-4-Clause-UC"
] | 100 | 2015-07-29T15:08:12.000Z | 2022-03-25T08:00:42.000Z | #include "Routing_DELTA.h"
RoutingAlgorithmsRegister Routing_DELTA::routingAlgorithmsRegister("DELTA", getInstance());
Routing_DELTA * Routing_DELTA::routing_DELTA = 0;
Routing_DELTA * Routing_DELTA::getInstance() {
if ( routing_DELTA == 0 )
routing_DELTA = new Routing_DELTA();
return routing_DELTA;
}
vector<int> Routing_DELTA::route(Router * router, const RouteData & routeData)
{
vector <int> directions;
// int switch_offset = GlobalParams::n_delta_tiles;
// first hop (core->1st stage)
if (routeData.current_id < GlobalParams::n_delta_tiles)
directions.push_back(0); // for inputs cores
else
{ // for switch bloc
int destination = routeData.dst_id;
// LOG << "I am switch: " <<routeData.current_id << " _Going to destination: " <<destination<<endl;
int currentStage = id2Coord(routeData.current_id).x;
int shift_amount= log2(GlobalParams::n_delta_tiles)-1-currentStage;
int direction = 1 & (destination >> shift_amount);
// LOG << "I am again switch: " <<routeData.current_id << " _Going to destination: " <<destination<< " _Via direction "<<direction <<endl;
directions.push_back(direction);
}
return directions;
}
| 31.157895 | 141 | 0.714527 | [
"vector"
] |
2bc1087c86156710526e4b485cefbf32862af46d | 11,016 | cpp | C++ | drlvm/vm/vmcore/src/jvmti/jvmti_pop_frame.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 8 | 2015-11-04T06:06:35.000Z | 2021-07-04T13:47:36.000Z | drlvm/vm/vmcore/src/jvmti/jvmti_pop_frame.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 1 | 2021-10-17T13:07:28.000Z | 2021-10-17T13:07:28.000Z | drlvm/vm/vmcore/src/jvmti/jvmti_pop_frame.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 13 | 2015-11-27T03:14:50.000Z | 2022-02-26T15:12:20.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* JVMTI JIT pop frame support functions.
*/
#define LOG_DOMAIN "jvmti.stack.popframe"
#include "clog.h"
#include "open/vm_method_access.h"
#include "jvmti_direct.h"
#include "jvmti_interface.h"
#include "exceptions.h"
#include "environment.h"
#include "jthread.h"
#include "vm_threads.h"
#include "jit_intf_cpp.h"
#include "m2n.h"
#include "mon_enter_exit.h"
#include "stack_iterator.h"
#include "jvmti_break_intf.h"
#include "cci.h"
static void jvmti_pop_frame_callback()
{
CTRACE(("JVMTI PopFrame callback is called"));
frame_type type =
m2n_get_frame_type((M2nFrame*)(p_TLS_vmthread->last_m2n_frame));
// frame wasn't requested to be popped
if (FRAME_POP_NOW != (FRAME_POP_NOW & type)) {
CTRACE(("PopFrame callback is not FRAME_POP_NOW"));
return;
}
// if we are in hythread_safe_point() frame is unwindable
if (FRAME_SAFE_POINT == (FRAME_SAFE_POINT & type)) {
CTRACE(("PopFrame callback is FRAME_SAFE_POINT"));
jvmti_jit_prepare_pop_frame();
} else if (is_unwindable()) {
// unwindable frame, wait for resume
CTRACE(("PopFrame callback is FRAME_SAFE_POINT"));
// switch execution to the previous frame
jvmti_jit_do_pop_frame();
assert(0 /* mustn't get here */);
} else {
// nonunwindable frame, raise special exception object
CTRACE(("PopFrame callback is raising exception"));
exn_raise_object(VM_Global_State::loader_env->popFrameException);
}
} //jvmti_pop_frame_callback
jvmtiError jvmti_jit_pop_frame(jthread java_thread)
{
assert(hythread_is_suspend_enabled());
CTRACE(("Called PopFrame for JIT"));
DebugUtilsTI *ti = VM_Global_State::loader_env->TI;
if (!ti->get_global_capability(DebugUtilsTI::TI_GC_ENABLE_POP_FRAME)) {
return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
}
hythread_t hy_thread = jthread_get_native_thread(java_thread);
vm_thread_t vm_thread = jthread_get_vm_thread(hy_thread);
M2nFrame* top_frame = m2n_get_last_frame(vm_thread);
frame_type type = m2n_get_frame_type(top_frame);
if (FRAME_POPABLE != (FRAME_POPABLE & type))
return JVMTI_ERROR_OPAQUE_FRAME;
StackIterator *si = si_create_from_native(vm_thread);
// check that topmost frame is M2n
assert(si_is_native(si));
// go to 2-d frame & check it's managed
si_goto_previous(si);
assert(! si_is_native(si));
Method* UNREF pop_method = si_get_code_chunk_info(si)->get_method();
CTRACE(("PopFrame is called for method %s.%s%s :%p",
pop_method->get_class()->get_name()->bytes,
pop_method->get_name()->bytes,
pop_method->get_descriptor()->bytes,
si_get_ip(si)));
// go to 3-d frame & check its type
si_goto_previous(si);
if (si_is_native(si)) {
si_free(si);
return JVMTI_ERROR_OPAQUE_FRAME;
}
si_free(si);
// change type from popable to pop_now, pop_done should'n be changed
if (FRAME_POPABLE == (type & FRAME_POP_MASK)) {
type = (frame_type)((type & ~FRAME_POP_MASK) | FRAME_POP_NOW);
}
m2n_set_frame_type(top_frame, type);
// Install safepoint callback that would perform popping job
hythread_set_safepoint_callback(hy_thread, &jvmti_pop_frame_callback);
return JVMTI_ERROR_NONE;
} //jvmti_jit_pop_frame
#ifdef _IPF_
void jvmti_jit_prepare_pop_frame(){
assert(0);
}
void jvmti_jit_complete_pop_frame(){
assert(0);
}
void jvmti_jit_do_pop_frame(){
assert(0);
}
#else // _IA32_ & _EM64T_
// requires stack iterator and buffer to save intermediate information
static void jvmti_jit_prepare_pop_frame(StackIterator* si, U_32* buf) {
CTRACE(("Prepare PopFrame for JIT"));
// pop native frame
assert(si_is_native(si));
si_goto_previous(si);
// save information about java frame
assert(!si_is_native(si));
CodeChunkInfo *cci = si_get_code_chunk_info(si);
JitFrameContext* jitContext = si_get_jit_context(si);
// save information about java method
assert(cci);
Method* method = cci->get_method();
Class* method_class = method->get_class();
bool is_method_static = method->is_static();
CTRACE(("PopFrame method %s.%s%s, stop IP: %p",
method->get_class()->get_name()->bytes,
method->get_name()->bytes,
method->get_descriptor()->bytes,
si_get_ip(si)));
// free lock of synchronized method
/*
Currently JIT does not unlock monitors of synchronized blocks relying
on compiler which generates pseudo finally statement to unlock them.
For correct implementation of PopFrame these monitors will have to be
unlocked by VM, so JIT has to store information about these monitors
somewhere.
*/
vm_monitor_exit_synchronized_method(si);
// pop java frame
si_goto_previous(si);
// find correct ip and restore required registers context
NativeCodePtr current_method_addr = NULL;
cci = si_get_code_chunk_info(si);
method = cci->get_method();
NativeCodePtr ip = si_get_ip(si);
JIT *jit = cci->get_jit();
CTRACE(("PopFrame method %s.%s%s, set IP begin: %p",
method->get_class()->get_name()->bytes,
method->get_name()->bytes,
method->get_descriptor()->bytes, ip));
uint16 bcOffset;
NativeCodePtr bcip;
jit->fix_handler_context(method, si_get_jit_context(si));
jit->get_bc_location_for_native(method, (NativeCodePtr)((POINTER_SIZE_INT)ip - 1), &bcOffset);
jit->get_native_location_for_bc(method, bcOffset, &bcip);
si_set_ip(si, bcip, false);
method = si_get_code_chunk_info(si)->get_method();
CTRACE(("PopFrame method %s.%s%s, set IP end: %p",
method->get_class()->get_name()->bytes,
method->get_name()->bytes,
method->get_descriptor()->bytes, ip ));
}
void jvmti_jit_prepare_pop_frame() {
// Find top m2n frame
M2nFrame* top_frame = m2n_get_last_frame();
frame_type type = m2n_get_frame_type(top_frame);
// Check that frame has correct type
assert((FRAME_POP_NOW == (FRAME_POP_MASK & type))
||(FRAME_POP_DONE == (FRAME_POP_MASK & type)));
// create stack iterator from native
StackIterator* si = si_create_from_native();
si_transfer_all_preserved_registers(si);
CTRACE(("PopFrame prepare for method IP: %p", si_get_ip(si) ));
// prepare pop frame - find regs values
U_32 buf = 0;
jvmti_jit_prepare_pop_frame(si, &buf);
// save regs value from jit context to m2n
Registers* regs = get_pop_frame_registers(top_frame);
si_copy_to_registers(si, regs);
si_free(si);
// set pop done frame state
m2n_set_frame_type(top_frame, frame_type(FRAME_POP_DONE | FRAME_MODIFIED_STACK));
return;
}
static void
jvmti_relocate_single_step_breakpoints( StackIterator *si)
{
// relocate single step
DebugUtilsTI *ti = VM_Global_State::loader_env->TI;
if (ti->isEnabled() && ti->is_single_step_enabled())
{
jvmti_thread_t jvmti_thread = jthread_self_jvmti();
LMAutoUnlock lock(ti->vm_brpt->get_lock());
if (NULL != jvmti_thread->ss_state) {
// remove old single step breakpoints
jvmti_remove_single_step_breakpoints(ti, jvmti_thread);
// set new single step breakpoints
CodeChunkInfo *cci = si_get_code_chunk_info(si);
Method *method = cci->get_method();
NativeCodePtr ip = si_get_ip(si);
uint16 bc;
JIT *jit = cci->get_jit();
OpenExeJpdaError UNREF result =
jit->get_bc_location_for_native(method, ip, &bc);
assert(EXE_ERROR_NONE == result);
jvmti_StepLocation locations = {method, ip, bc, false};
jvmti_set_single_step_breakpoints(ti, jvmti_thread, &locations, 1);
}
}
return;
} // jvmti_relocate_single_step_breakpoints
void jvmti_jit_complete_pop_frame() {
// Destructive Unwinding!!! NO CXX Logging put here.
CTRACE(("Complete PopFrame for JIT"));
// Find top m2n frame
M2nFrame* top_frame = m2n_get_last_frame();
frame_type type = m2n_get_frame_type(top_frame);
// Check that frame has correct type
assert(FRAME_POP_DONE == (FRAME_POP_MASK & type));
// create stack iterator from native
StackIterator* si = (StackIterator*) STD_ALLOCA(si_size());
si_fill_from_native(si);
si_transfer_all_preserved_registers(si);
// pop native frame
assert(si_is_native(si));
si_goto_previous(si);
// relocate single step breakpoints
jvmti_relocate_single_step_breakpoints(si);
// transfer control
CTRACE(("PopFrame transfer control to: %p", (void*)si_get_ip(si) ));
si_transfer_control(si);
}
void jvmti_jit_do_pop_frame() {
// Destructive Unwinding!!! NO CXX Logging put here.
CTRACE(("Do PopFrame for JIT"));
// Find top m2n frame
M2nFrame* top_frame = m2n_get_last_frame();
frame_type type = m2n_get_frame_type(top_frame);
// Check that frame has correct type
assert(FRAME_POP_NOW == (FRAME_POP_MASK & type));
// create stack iterator from native
StackIterator* si = (StackIterator*) STD_ALLOCA(si_size());
si_fill_from_native(si);
si_transfer_all_preserved_registers(si);
// prepare pop frame - find regs values
U_32 buf = 0;
jvmti_jit_prepare_pop_frame(si, &buf);
// relocate single step breakpoints
jvmti_relocate_single_step_breakpoints(si);
// transfer control
CTRACE(("PopFrame transfer control to: %p", (void*)si_get_ip(si) ));
si_transfer_control(si);
}
#endif // _IA32_
void jvmti_safe_point()
{
Registers regs;
M2nFrame* top_frame = m2n_get_last_frame();
set_pop_frame_registers(top_frame, ®s);
CTRACE(("entering exception_safe_point"));
hythread_exception_safe_point();
CTRACE(("left exception_safe_point"));
CTRACE(("entering safe_point"));
hythread_safe_point();
CTRACE(("left safe_point"));
// find frame type
frame_type type = m2n_get_frame_type(top_frame);
// complete pop frame if frame has correct type
if (FRAME_POP_DONE == (FRAME_POP_MASK & type)){
jvmti_jit_complete_pop_frame();
}
}
| 31.83815 | 98 | 0.689361 | [
"object"
] |
2bc5b9d3eaaf6be52ece05138fb007fddb7447a1 | 13,640 | cpp | C++ | src/rendering/renderers/TextSelectorRenderer.cpp | skylerpfli/libpag | 41adf2754a428569d3513a85908bcc6c1bf3d906 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | 1,546 | 2022-01-14T02:09:47.000Z | 2022-03-31T10:38:42.000Z | src/rendering/renderers/TextSelectorRenderer.cpp | skylerpfli/libpag | 41adf2754a428569d3513a85908bcc6c1bf3d906 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | 86 | 2022-01-14T04:50:28.000Z | 2022-03-31T01:54:31.000Z | src/rendering/renderers/TextSelectorRenderer.cpp | skylerpfli/libpag | 41adf2754a428569d3513a85908bcc6c1bf3d906 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | 207 | 2022-01-14T02:09:52.000Z | 2022-03-31T08:34:49.000Z | /////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tencent is pleased to support the open source community by making libpag available.
//
// Copyright (C) 2021 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 "TextSelectorRenderer.h"
#include "base/utils/BezierEasing.h"
namespace pag {
float TextSelectorRenderer::CalculateFactorFromSelectors(
const std::vector<TextSelectorRenderer*>& selectorRenderers, size_t index, bool* pBiasFlag) {
float totalFactor = 1.0f;
bool isFirstSelector = true;
for (auto selectorRenderer : selectorRenderers) {
bool biasFlag = false;
auto factor = selectorRenderer->calculateFactorByIndex(index, &biasFlag);
if (pBiasFlag != nullptr) {
*pBiasFlag |= biasFlag;
}
totalFactor = selectorRenderer->overlayFactor(totalFactor, factor, isFirstSelector);
isFirstSelector = false;
}
return totalFactor;
}
static float OverlayFactorByMode(float oldFactor, float factor, Enum mode) {
float newFactor;
switch (mode) {
case TextSelectorMode::Subtract:
if (factor >= 0.0f) {
newFactor = oldFactor * (1.0f - factor);
} else {
newFactor = oldFactor * (-1.0f - factor);
}
break;
case TextSelectorMode::Intersect:
newFactor = oldFactor * factor;
break;
case TextSelectorMode::Min:
newFactor = std::min(oldFactor, factor);
break;
case TextSelectorMode::Max:
newFactor = std::max(oldFactor, factor);
break;
case TextSelectorMode::Difference:
newFactor = fabs(oldFactor - factor);
break;
default: // TextSelectorMode::Add:
newFactor = oldFactor + factor;
break;
}
return newFactor;
}
// 叠加选择器
float TextSelectorRenderer::overlayFactor(float oldFactor, float factor, bool isFirstSelector) {
auto newFactor = 0.0f;
if (isFirstSelector && mode != TextSelectorMode::Subtract) {
// 首次且叠加模式不为Subtract时,直接取factor
// 首次且叠加模式为Subtract时,合并入OverlayFactorByMode计算。(首次时oldFactor外部默认为1.0f)
newFactor = factor;
} else {
newFactor = OverlayFactorByMode(oldFactor, factor, mode);
}
if (newFactor < -1.0f) {
newFactor = -1.0f;
} else if (newFactor > 1.0f) {
newFactor = 1.0f;
}
return newFactor;
}
//
// 因无法获取AE的随机策略,所以随机的具体值也和AE不一样,但因需要获取准确的FirtBaseline,
// 而Position动画会影响插件里FirtBaseline的获取,所以我们需要得到第一个字符的准确位置,
// 因此,我们需要得到文本动画里第一个字符的随机值。
// 下表即是指示第一个字符的随机值,表中具体取值经AE测试得出。
// 经测试,AE里的随机值仅跟字符数目相关,所以下表(和函数)是通过字符数目获取第一个字符的随机值。
// 具体含义:字符数textCount处于范围[start,end]时,第一字符的随机值为index。
// 其中,因start可以通过上一个end+1获取,所以表里忽略start,仅有end和index。
//
static const struct {
int end;
int index;
} randomRanges[] = {
{2, 0}, // [1,2] = 0
{4, 2}, // [3,4] = 2
{5, 4}, // [5,5] = 4
{20, 5}, // [6,20] = 5
{69, 20}, // [21,69] = 20
{127, 69}, // [70,127] = 69
{206, 127}, // [128,206] = 127
{10000, 205} // [207, ...] = 205 后面结束点未测试
};
static int GetRandomIndex(int textCount) {
for (size_t i = 0; i < sizeof(randomRanges) / sizeof(randomRanges[0]); i++) {
if (textCount <= randomRanges[i].end) {
return randomRanges[i].index;
}
}
return 0;
}
void TextSelectorRenderer::calculateRandomIndexs(uint16_t seed) {
srand(seed); // 重置随机种子
std::vector<std::pair<int, int>> randList;
for (size_t i = 0; i < textCount; i++) {
randList.push_back(std::make_pair(rand(), i)); // 生成随机数
}
// 排序
std::sort(std::begin(randList), std::end(randList),
[](const std::pair<int, int>& a, std::pair<int, int>& b) { return a.first < b.first; });
// 随机数排序后的序号作为真正的顺序
for (size_t i = 0; i < textCount; i++) {
randomIndexs.push_back(randList[i].second);
}
if (seed == 0 && textCount > 1) {
// 查表获取位置0的随机序号m
// 同时,为了避免序号冲突,需要再把0原本的序号赋值给原本取值为m的位置k
auto m = GetRandomIndex(static_cast<int>(textCount));
size_t k = 0;
do {
if (randomIndexs[k] == m) {
break;
}
} while (++k < textCount);
std::swap(randomIndexs[0], randomIndexs[k]);
}
}
// 读取摆动选择器
WigglySelectorRenderer::WigglySelectorRenderer(const TextWigglySelector* selector, size_t textCount,
Frame frame)
: TextSelectorRenderer(textCount, frame) {
// 获取属性:模式、最大量、最小量
mode = selector->mode->getValueAt(frame); // 模式
maxAmount = selector->maxAmount->getValueAt(frame); // 数量
minAmount = selector->minAmount->getValueAt(frame); // 数量
wigglesPerSecond = selector->wigglesPerSecond->getValueAt(frame); // 摇摆/秒
correlation = selector->correlation->getValueAt(frame); // 关联
temporalPhase = selector->temporalPhase->getValueAt(frame); // 时间相位
spatialPhase = selector->spatialPhase->getValueAt(frame); // 空间相位
randomSeed = selector->randomSeed->getValueAt(frame); // 随机植入
}
// 计算摆动选择器中某个字符的范围因子
float WigglySelectorRenderer::calculateFactorByIndex(size_t index, bool* pBiasFlag) {
if (textCount == 0) {
return 0.0f;
}
// 这里的公式离复原AE效果还有一定的距离。后续可优化。
// 经验值也需要优化.
auto temporalSeed = wigglesPerSecond / 2.0 * (frame + temporalPhase / 30.f) / 24.0f;
auto spatialSeed = (13.73f * (1.0f - correlation) * index + spatialPhase / 80.0f) / 21.13f;
auto seed = (spatialSeed + temporalSeed + randomSeed / 3.13f) * 2 * M_PI;
auto factor = cos(seed) * cos(seed / 7 + M_PI / 5);
if (factor < -1.0f) {
factor = -1.0f;
} else if (factor > 1.0f) {
factor = 1.0f;
}
// 考虑"最大量"/"最小量"的影响
factor = (factor + 1.0f) / 2 * (maxAmount - minAmount) + minAmount;
if (pBiasFlag != nullptr) {
*pBiasFlag = true; // 摆动选择器计算有误差
}
return factor;
}
// 读取范围选择器
RangeSelectorRenderer::RangeSelectorRenderer(const TextRangeSelector* selector, size_t textCount,
Frame frame)
: TextSelectorRenderer(textCount, frame) {
// 获取基础属性:开始、结束、偏移
rangeStart = selector->start->getValueAt(frame); // 开始
rangeEnd = selector->end->getValueAt(frame); // 结束
auto offset = selector->offset->getValueAt(frame); // 偏移
rangeStart += offset;
rangeEnd += offset;
if (rangeStart > rangeEnd) { // 如果开始比结束大,则调换,方便后续处理
std::swap(rangeStart, rangeEnd);
}
// 获取高级属性:模式、数量、形状、随机排序
mode = selector->mode->getValueAt(frame); // 模式
amount = selector->amount->getValueAt(frame); // 数量
shape = selector->shape; // 形状
randomizeOrder = selector->randomizeOrder; // 随机排序
randomSeed = selector->randomSeed->getValueAt(frame); // 随机植入
if (randomizeOrder) {
// 随机排序开启时,生成随机序号
calculateRandomIndexs(randomSeed);
}
}
static float CalculateFactorSquare(float textStart, float textEnd, float rangeStart,
float rangeEnd) {
//
// 正方形
// ___________
// | |
// | |
// | |
// __________| |__________
//
if (textStart >= rangeEnd || textEnd <= rangeStart) {
return 0.0f;
}
auto textRange = textEnd - textStart;
if (textStart < rangeStart) {
textStart = rangeStart;
}
if (textEnd > rangeEnd) {
textEnd = rangeEnd;
}
auto factor = (textEnd - textStart) / textRange;
return factor;
}
static float CalculateRangeFactorRampUp(float textStart, float textEnd, float rangeStart,
float rangeEnd) {
//
// 上斜坡
// __________
// /
// /
// /
// /
// /
// ___________/
//
auto textCenter = (textStart + textEnd) * 0.5f;
auto factor = (textCenter - rangeStart) / (rangeEnd - rangeStart);
return factor;
}
static float CalculateRangeFactorRampDown(float textStart, float textEnd, float rangeStart,
float rangeEnd) {
//
// 下斜坡
// ___________
// \
// \
// \
// \
// \
// \_________
//
auto textCenter = (textStart + textEnd) * 0.5f;
auto factor = (rangeEnd - textCenter) / (rangeEnd - rangeStart);
return factor;
}
static float CalculateRangeFactorTriangle(float textStart, float textEnd, float rangeStart,
float rangeEnd) {
//
// 三角形
// /\
// / \
// / \
// / \
// / \
// __________/ \__________
//
auto textCenter = (textStart + textEnd) * 0.5f;
auto rangeCenter = (rangeStart + rangeEnd) * 0.5f;
float factor;
if (textCenter < rangeCenter) {
factor = (textCenter - rangeStart) / (rangeCenter - rangeStart);
} else {
factor = (rangeEnd - textCenter) / (rangeEnd - rangeCenter);
}
return factor;
}
static float CalculateRangeFactorRound(float textStart, float textEnd, float rangeStart,
float rangeEnd) {
//
// 圆形:
// 利用勾股定理确定高度:B*B = C*C - A*A (其中 C 为圆的半径)
//
// ***
// * *
// * /| *
// * / | *
// * / | *
// * C / | B *
// * / | *
// * / | *
// *_______________________/______|_________________*
// A
//
auto textCenter = (textStart + textEnd) * 0.5f;
if (textCenter >= rangeEnd || textCenter <= rangeStart) {
return 0.0f;
}
auto rangeCenter = (rangeStart + rangeEnd) * 0.5f;
auto radius = (rangeEnd - rangeStart) * 0.5f; // C = radius
auto xWidth = rangeCenter - textCenter; // A = xWidth
auto yHeight = std::sqrt(radius * radius - xWidth * xWidth); // B = yHeight
auto factor = yHeight / radius;
return factor;
}
static float CalculateRangeFactorSmooth(float textStart, float textEnd, float rangeStart,
float rangeEnd) {
//
// 平滑
// 三次贝塞尔曲线
// _ - - - _
// - -
// - -
// - -
// _ _
// _ _ _ _ - - _ _ _ _
//
auto textCenter = (textStart + textEnd) * 0.5f;
if (textCenter >= rangeEnd || textCenter <= rangeStart) {
return 0.0f;
}
auto rangeCenter = (rangeStart + rangeEnd) * 0.5f;
float x = 0.0f;
if (textCenter < rangeCenter) {
x = (textCenter - rangeStart) / (rangeCenter - rangeStart);
} else {
x = (rangeEnd - textCenter) / (rangeEnd - rangeCenter);
}
// 根据AE实际数据, 拟合出贝塞尔曲线两个控制点
// P1、P2的取值分别为(0.5, 0.0)、(0.5, 1.0)
static BezierEasing bezier = BezierEasing(Point::Make(0.5, 0.0), Point::Make(0.5, 1.0));
auto factor = bezier.getInterpolation(x);
return factor;
}
void RangeSelectorRenderer::calculateBiasFlag(bool* pBiasFlag) {
if (pBiasFlag != nullptr) {
if (shape == TextRangeSelectorShape::Round || shape == TextRangeSelectorShape::Smooth) {
*pBiasFlag = true; // 圆形和平滑计算有误差
} else if (randomizeOrder && randomSeed != 0 && textCount > 1) {
*pBiasFlag = true; // 随机数不为0时有误差
} else {
*pBiasFlag = false;
}
}
}
// 计算某个字符的范围因子
float RangeSelectorRenderer::calculateFactorByIndex(size_t index, bool* pBiasFlag) {
if (textCount == 0) {
return 0.0f;
}
if (randomizeOrder) {
index = randomIndexs[index]; // 从随机过后的列表中获取新的序号。
}
auto textStart = static_cast<float>(index) / textCount;
auto textEnd = static_cast<float>(index + 1) / textCount;
auto factor = 0.0f;
switch (shape) {
case TextRangeSelectorShape::RampUp: // 上斜坡
factor = CalculateRangeFactorRampUp(textStart, textEnd, rangeStart, rangeEnd);
break;
case TextRangeSelectorShape::RampDown: // 下斜坡
factor = CalculateRangeFactorRampDown(textStart, textEnd, rangeStart, rangeEnd);
break;
case TextRangeSelectorShape::Triangle: // 三角形
factor = CalculateRangeFactorTriangle(textStart, textEnd, rangeStart, rangeEnd);
break;
case TextRangeSelectorShape::Round: // 圆形
factor = CalculateRangeFactorRound(textStart, textEnd, rangeStart, rangeEnd);
break;
case TextRangeSelectorShape::Smooth: // 平滑
factor = CalculateRangeFactorSmooth(textStart, textEnd, rangeStart, rangeEnd);
break;
default: // TextRangeSelectorShape::Square // 正方形
factor = CalculateFactorSquare(textStart, textEnd, rangeStart, rangeEnd);
break;
}
if (factor < 0.0f) {
factor = 0.0f;
} else if (factor > 1.0f) {
factor = 1.0f;
}
factor *= amount; // 乘以高级选项里的"数量"系数
calculateBiasFlag(pBiasFlag);
return factor;
}
} // namespace pag | 33.349633 | 100 | 0.576173 | [
"shape",
"vector"
] |
2bc704598b2abc96d40689eed813d9cd43f7d1eb | 2,668 | cc | C++ | talk/base/filelock.cc | chromium-googlesource-mirror/libjingle | 7246b07650052c150a237c99284fc689388f321c | [
"BSD-3-Clause"
] | 2 | 2017-09-05T03:49:39.000Z | 2017-09-09T03:53:10.000Z | talk/base/filelock.cc | chromium-googlesource-mirror/libjingle | 7246b07650052c150a237c99284fc689388f321c | [
"BSD-3-Clause"
] | null | null | null | talk/base/filelock.cc | chromium-googlesource-mirror/libjingle | 7246b07650052c150a237c99284fc689388f321c | [
"BSD-3-Clause"
] | 2 | 2016-08-17T07:21:08.000Z | 2020-03-04T06:21:25.000Z | /*
* libjingle
* Copyright 2009, Google Inc.
*
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/base/filelock.h"
#include "talk/base/fileutils.h"
#include "talk/base/logging.h"
#include "talk/base/pathutils.h"
#include "talk/base/stream.h"
namespace talk_base {
FileLock::FileLock(const std::string& path, FileStream* file)
: path_(path), file_(file) {
}
FileLock::~FileLock() {
MaybeUnlock();
}
void FileLock::Unlock() {
LOG_F(LS_INFO);
MaybeUnlock();
}
void FileLock::MaybeUnlock() {
if (file_.get() != NULL) {
LOG(LS_INFO) << "Unlocking:" << path_;
file_->Close();
Filesystem::DeleteFile(path_);
file_.reset();
}
}
FileLock* FileLock::TryLock(const std::string& path) {
FileStream* stream = new FileStream();
bool ok = false;
#ifdef WIN32
// Open and lock in a single operation.
ok = stream->OpenShare(path, "a", _SH_DENYRW, NULL);
#else // Linux and OSX
ok = stream->Open(path, "a", NULL) && stream->TryLock();
#endif
if (ok) {
return new FileLock(path, stream);
} else {
// Something failed, either we didn't succeed to open the
// file or we failed to lock it. Anyway remove the heap
// allocated object and then return NULL to indicate failure.
delete stream;
return NULL;
}
}
} // namespace talk_base
| 33.35 | 80 | 0.715142 | [
"object"
] |
2bc70b5c652f49eda0b14a053f95fd8e1cc5ed5a | 605 | hpp | C++ | twitterlib/include/twitterlib/objects/sizes.hpp | zina1995/Twitter-API-C-Library | 87b29c63b89be6feb05adbe05ebed0213aa67f9b | [
"MIT"
] | null | null | null | twitterlib/include/twitterlib/objects/sizes.hpp | zina1995/Twitter-API-C-Library | 87b29c63b89be6feb05adbe05ebed0213aa67f9b | [
"MIT"
] | null | null | null | twitterlib/include/twitterlib/objects/sizes.hpp | zina1995/Twitter-API-C-Library | 87b29c63b89be6feb05adbe05ebed0213aa67f9b | [
"MIT"
] | null | null | null | #ifndef TWITTERLIB_OBJECTS_SIZES_HPP
#define TWITTERLIB_OBJECTS_SIZES_HPP
#include <string>
#include <boost/property_tree/ptree_fwd.hpp>
#include <twitterlib/objects/size.hpp>
namespace twitter {
struct Sizes {
Size thumb;
Size large;
Size medium;
Size small;
};
/// Generates a string display of all data in \p sizes.
[[nodiscard]] auto to_string(Sizes const& sizes) -> std::string;
/// Create a Sizes object from a property tree.
[[nodiscard]] auto parse_sizes(boost::property_tree::ptree const& tree)
-> Sizes;
} // namespace twitter
#endif // TWITTERLIB_OBJECTS_SIZES_HPP
| 22.407407 | 71 | 0.733884 | [
"object"
] |
2bcfb842ca6948fc2a595e7fd32d1b873a9fc5ba | 13,348 | cpp | C++ | src/caffe/layers/dyn_conv_layer.cpp | Sandbox3aster/caffe-charles | eb372728992d53f29bc035ea93cb099715a92dda | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/dyn_conv_layer.cpp | Sandbox3aster/caffe-charles | eb372728992d53f29bc035ea93cb099715a92dda | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/dyn_conv_layer.cpp | Sandbox3aster/caffe-charles | eb372728992d53f29bc035ea93cb099715a92dda | [
"BSD-2-Clause"
] | null | null | null | #include <vector>
#include "caffe/layers/dyn_conv_layer.hpp"
namespace caffe {
template <typename Dtype>
void DynamicConvolutionLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
CHECK_GE(bottom.size(), 2) << "bottom[0] as input, bottom[1] as kernel banks, bottom[2] as bias if given";
// Configure the kernel size, padding, stride, and inputs.
ConvolutionParameter conv_param = this->layer_param_.convolution_param();
this->force_nd_im2col_ = conv_param.force_nd_im2col();
this->channel_axis_ = bottom[0]->CanonicalAxisIndex(conv_param.axis());
const int first_spatial_axis = this->channel_axis_ + 1;
const int num_axes = bottom[0]->num_axes();
this->num_spatial_axes_ = num_axes - first_spatial_axis;
CHECK_GE(this->num_spatial_axes_, 0);
vector<int> bottom_dim_blob_shape(1, this->num_spatial_axes_ + 1);
vector<int> spatial_dim_blob_shape(1, std::max(this->num_spatial_axes_, 1));
// Setup filter kernel dimensions (kernel_shape_).
this->kernel_shape_.Reshape(spatial_dim_blob_shape);
int* kernel_shape_data = this->kernel_shape_.mutable_cpu_data();
if (conv_param.has_kernel_h() || conv_param.has_kernel_w()) {
CHECK_EQ(this->num_spatial_axes_, 2)
<< "kernel_h & kernel_w can only be used for 2D convolution.";
CHECK_EQ(0, conv_param.kernel_size_size())
<< "Either kernel_size or kernel_h/w should be specified; not both.";
kernel_shape_data[0] = conv_param.kernel_h();
kernel_shape_data[1] = conv_param.kernel_w();
}
else {
const int num_kernel_dims = conv_param.kernel_size_size();
CHECK(num_kernel_dims == 1 || num_kernel_dims == this->num_spatial_axes_)
<< "kernel_size must be specified once, or once per spatial dimension "
<< "(kernel_size specified " << num_kernel_dims << " times; "
<< this->num_spatial_axes_ << " spatial dims).";
for (int i = 0; i < this->num_spatial_axes_; ++i) {
kernel_shape_data[i] =
conv_param.kernel_size((num_kernel_dims == 1) ? 0 : i);
}
}
for (int i = 0; i < this->num_spatial_axes_; ++i) {
CHECK_GT(kernel_shape_data[i], 0) << "Filter dimensions must be nonzero.";
}
// Setup stride dimensions (stride_).
this->stride_.Reshape(spatial_dim_blob_shape);
int* stride_data = this->stride_.mutable_cpu_data();
if (conv_param.has_stride_h() || conv_param.has_stride_w()) {
CHECK_EQ(this->num_spatial_axes_, 2)
<< "stride_h & stride_w can only be used for 2D convolution.";
CHECK_EQ(0, conv_param.stride_size())
<< "Either stride or stride_h/w should be specified; not both.";
stride_data[0] = conv_param.stride_h();
stride_data[1] = conv_param.stride_w();
}
else {
const int num_stride_dims = conv_param.stride_size();
CHECK(num_stride_dims == 0 || num_stride_dims == 1 ||
num_stride_dims == this->num_spatial_axes_)
<< "stride must be specified once, or once per spatial dimension "
<< "(stride specified " << num_stride_dims << " times; "
<< this->num_spatial_axes_ << " spatial dims).";
const int kDefaultStride = 1;
for (int i = 0; i < this->num_spatial_axes_; ++i) {
stride_data[i] = (num_stride_dims == 0) ? kDefaultStride :
conv_param.stride((num_stride_dims == 1) ? 0 : i);
CHECK_GT(stride_data[i], 0) << "Stride dimensions must be nonzero.";
}
}
// Setup pad dimensions (pad_).
this->pad_.Reshape(spatial_dim_blob_shape);
int* pad_data = this->pad_.mutable_cpu_data();
if (conv_param.has_pad_h() || conv_param.has_pad_w()) {
CHECK_EQ(this->num_spatial_axes_, 2)
<< "pad_h & pad_w can only be used for 2D convolution.";
CHECK_EQ(0, conv_param.pad_size())
<< "Either pad or pad_h/w should be specified; not both.";
pad_data[0] = conv_param.pad_h();
pad_data[1] = conv_param.pad_w();
}
else {
const int num_pad_dims = conv_param.pad_size();
CHECK(num_pad_dims == 0 || num_pad_dims == 1 ||
num_pad_dims == this->num_spatial_axes_)
<< "pad must be specified once, or once per spatial dimension "
<< "(pad specified " << num_pad_dims << " times; "
<< this->num_spatial_axes_ << " spatial dims).";
const int kDefaultPad = 0;
for (int i = 0; i < this->num_spatial_axes_; ++i) {
pad_data[i] = (num_pad_dims == 0) ? kDefaultPad :
conv_param.pad((num_pad_dims == 1) ? 0 : i);
}
}
// Setup dilation dimensions (dilation_).
this->dilation_.Reshape(spatial_dim_blob_shape);
int* dilation_data = this->dilation_.mutable_cpu_data();
const int num_dilation_dims = conv_param.dilation_size();
CHECK(num_dilation_dims == 0 || num_dilation_dims == 1 ||
num_dilation_dims == this->num_spatial_axes_)
<< "dilation must be specified once, or once per spatial dimension "
<< "(dilation specified " << num_dilation_dims << " times; "
<< this->num_spatial_axes_ << " spatial dims).";
const int kDefaultDilation = 1;
for (int i = 0; i < this->num_spatial_axes_; ++i) {
dilation_data[i] = (num_dilation_dims == 0) ? kDefaultDilation :
conv_param.dilation((num_dilation_dims == 1) ? 0 : i);
}
// Special case: im2col is the identity for 1x1 convolution with stride 1
// and no padding, so flag for skipping the buffer and transformation.
this->is_1x1_ = true;
for (int i = 0; i < this->num_spatial_axes_; ++i) {
this->is_1x1_ &=
kernel_shape_data[i] == 1 && stride_data[i] == 1 && pad_data[i] == 0;
if (!this->is_1x1_) { break; }
}
// Configure output channels and groups.
this->channels_ = bottom[0]->shape(this->channel_axis_);
this->num_output_ = this->layer_param_.convolution_param().num_output();
CHECK_GT(this->num_output_, 0);
this->group_ = this->layer_param_.convolution_param().group();
CHECK_EQ(this->channels_ % this->group_, 0);
CHECK_EQ(this->num_output_ % this->group_, 0)
<< "Number of output should be multiples of group.";
if (reverse_dimensions()) {
this->conv_out_channels_ = this->channels_;
this->conv_in_channels_ = this->num_output_;
}
else {
this->conv_out_channels_ = this->num_output_;
this->conv_in_channels_ = this->channels_;
}
// Handle the parameters: weights and biases.
// - bottom[1] holds the filter weights
// - bottom[2] holds the biases (optional)
this->kernel_dim_ = this->conv_in_channels_ / this->group_;
for (int i = 0; i < this->num_spatial_axes_; ++i) {
this->kernel_dim_ *= kernel_shape_data[i];
}
this->bias_term_ = bottom.size() == 3;
this->weight_offset_ = this->conv_out_channels_ * this->kernel_dim_ / this->group_;
// Propagate gradients to the parameters (as directed by backward pass).
this->param_propagate_down_.resize(bottom.size() - 1, true);
}
template <typename Dtype>
void DynamicConvolutionLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const int first_spatial_axis = this->channel_axis_ + 1;
CHECK_LE(bottom.size(), 3) << "bottom not larger than 3";
CHECK_EQ(bottom[0]->num_axes(), first_spatial_axis + this->num_spatial_axes_)
<< "bottom num_axes may not change.";
this->num_ = bottom[0]->count(0, this->channel_axis_);
CHECK_EQ(bottom[0]->shape(this->channel_axis_), this->channels_)
<< "Input size incompatible with convolution kernel.";
CHECK_GE(bottom.size(), 2) << "bottom[0] as input, bottom[1] as kernel banks, bottom[2] as bias if given.";
CHECK_EQ(bottom[0]->shape(0), bottom[1]->shape(0))
<< "Input number must be equal to kernel banks' number.";
CHECK_EQ(bottom[1]->count(1), this->conv_out_channels_ * this->kernel_dim_)
<< "Kernel bank's dimension not proper for convolution. bank shape: " << bottom[1]->shape_string();
if (this->bias_term_){
CHECK_EQ(bottom[0]->shape(0), bottom[2]->shape(0))
<< "Input number must be equal to bias's number.";
CHECK_EQ(bottom[2]->count(1), this->num_output_)
<< "Bias dimension must be equal to layer's output number.";
}
// Shape the tops.
this->bottom_shape_ = &bottom[0]->shape();
compute_output_shape();
vector<int> top_shape(bottom[0]->shape().begin(),
bottom[0]->shape().begin() + this->channel_axis_);
top_shape.push_back(this->num_output_);
for (int i = 0; i < this->num_spatial_axes_; ++i) {
top_shape.push_back(this->output_shape_[i]);
}
for (int top_id = 0; top_id < top.size(); ++top_id) {
top[top_id]->Reshape(top_shape);
}
if (reverse_dimensions()) {
this->conv_out_spatial_dim_ = bottom[0]->count(first_spatial_axis);
}
else {
this->conv_out_spatial_dim_ = top[0]->count(first_spatial_axis);
}
this->col_offset_ = this->kernel_dim_ * this->conv_out_spatial_dim_;
this->output_offset_ = this->conv_out_channels_ * this->conv_out_spatial_dim_ / this->group_;
// Setup input dimensions (conv_input_shape_).
vector<int> bottom_dim_blob_shape(1, this->num_spatial_axes_ + 1);
this->conv_input_shape_.Reshape(bottom_dim_blob_shape);
int* conv_input_shape_data = this->conv_input_shape_.mutable_cpu_data();
for (int i = 0; i < this->num_spatial_axes_ + 1; ++i) {
if (reverse_dimensions()) {
conv_input_shape_data[i] = top[0]->shape(this->channel_axis_ + i);
}
else {
conv_input_shape_data[i] = bottom[0]->shape(this->channel_axis_ + i);
}
}
// The im2col result buffer will only hold one image at a time to avoid
// overly large memory usage. In the special case of 1x1 convolution
// it goes lazily unused to save memory.
this->col_buffer_shape_.clear();
this->col_buffer_shape_.push_back(this->kernel_dim_ * this->group_);
for (int i = 0; i < this->num_spatial_axes_; ++i) {
if (reverse_dimensions()) {
this->col_buffer_shape_.push_back(this->input_shape(i + 1));
}
else {
this->col_buffer_shape_.push_back(this->output_shape_[i]);
}
}
this->col_buffer_.Reshape(this->col_buffer_shape_);
this->bottom_dim_ = bottom[0]->count(this->channel_axis_);
this->top_dim_ = top[0]->count(this->channel_axis_);
this->num_kernels_im2col_ = this->conv_in_channels_ * this->conv_out_spatial_dim_;
this->num_kernels_col2im_ = reverse_dimensions() ? this->top_dim_ : this->bottom_dim_;
// Set up the all ones "bias multiplier" for adding biases by BLAS
this->out_spatial_dim_ = top[0]->count(first_spatial_axis);
if (this->bias_term_) {
vector<int> bias_multiplier_shape(1, this->out_spatial_dim_);
this->bias_multiplier_.Reshape(bias_multiplier_shape);
caffe_set(this->bias_multiplier_.count(), Dtype(1),
this->bias_multiplier_.mutable_cpu_data());
}
}
template <typename Dtype>
void DynamicConvolutionLayer<Dtype>::compute_output_shape() {
const int* kernel_shape_data = this->kernel_shape_.cpu_data();
const int* stride_data = this->stride_.cpu_data();
const int* pad_data = this->pad_.cpu_data();
const int* dilation_data = this->dilation_.cpu_data();
this->output_shape_.clear();
for (int i = 0; i < this->num_spatial_axes_; ++i) {
// i + 1 to skip channel axis
const int input_dim = this->input_shape(i + 1);
const int kernel_extent = dilation_data[i] * (kernel_shape_data[i] - 1) + 1;
const int output_dim = (input_dim + 2 * pad_data[i] - kernel_extent)
/ stride_data[i] + 1;
this->output_shape_.push_back(output_dim);
}
}
template <typename Dtype>
void DynamicConvolutionLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* weight = bottom[1]->cpu_data();
int weight_size = bottom[1]->count(1);
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
for (int n = 0; n < this->num_; ++n) {
this->forward_cpu_gemm(bottom_data + n * this->bottom_dim_, weight + n * weight_size,
top_data + n * this->top_dim_);
if (this->bias_term_) {
const Dtype* bias = bottom[2]->cpu_data();
this->forward_cpu_bias(top_data + n * this->top_dim_, bias + n * this->num_output_);
}
}
}
template <typename Dtype>
void DynamicConvolutionLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
const Dtype* weight = bottom[1]->cpu_data();
Dtype* weight_diff = bottom[1]->mutable_cpu_diff();
int weight_size = bottom[1]->count(1);
const Dtype* top_diff = top[0]->cpu_diff();
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
if (this->param_propagate_down_[0]) {
caffe_set(bottom[1]->count(), Dtype(0), weight_diff);
}
if (this->bias_term_ && this->param_propagate_down_[1]) {
caffe_set(bottom[2]->count(), Dtype(0),
bottom[2]->mutable_cpu_diff());
}
// Bias gradient, if necessary.
if (this->bias_term_ && this->param_propagate_down_[1]) {
Dtype* bias_diff = bottom[2]->mutable_cpu_diff();
for (int n = 0; n < this->num_; ++n) {
this->backward_cpu_bias(bias_diff + n * this->num_output_, top_diff + n * this->top_dim_);
}
}
if (this->param_propagate_down_[0] || propagate_down[0]) {
for (int n = 0; n < this->num_; ++n) {
// gradient w.r.t. weight. Note that we will accumulate diffs.
if (this->param_propagate_down_[0]) {
this->weight_cpu_gemm(bottom_data + n * this->bottom_dim_,
top_diff + n * this->top_dim_, weight_diff + n * weight_size);
}
// gradient w.r.t. bottom data, if necessary.
if (propagate_down[0]) {
this->backward_cpu_gemm(top_diff + n * this->top_dim_, weight + n * weight_size,
bottom_diff + n * this->bottom_dim_);
}
}
}
}
#ifdef CPU_ONLY
STUB_GPU(DynamicConvolutionLayer);
#endif
INSTANTIATE_CLASS(DynamicConvolutionLayer);
REGISTER_LAYER_CLASS(DynamicConvolution);
} // namespace caffe
| 42.919614 | 108 | 0.7046 | [
"shape",
"vector"
] |
2bd0cd454f540fd3de0a478cfd441a745766742d | 34,150 | hpp | C++ | numerics/polynomial_body.hpp | net-lisias-ksp/Principia | 9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a | [
"MIT"
] | 565 | 2015-01-04T21:47:18.000Z | 2022-03-22T12:04:58.000Z | numerics/polynomial_body.hpp | net-lisias-ksp/Principia | 9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a | [
"MIT"
] | 1,019 | 2015-01-03T11:42:27.000Z | 2022-03-29T21:02:15.000Z | numerics/polynomial_body.hpp | pleroy/Principia | 64c4c6c124f4744381b6489e39e6b53e2a440ce9 | [
"MIT"
] | 92 | 2015-02-11T23:08:58.000Z | 2022-03-21T03:35:37.000Z | #pragma once
#include "numerics/polynomial.hpp"
#include <algorithm>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/strings/str_join.h"
#include "absl/strings/str_cat.h"
#include "base/macros.hpp"
#include "base/not_constructible.hpp"
#include "base/traits.hpp"
#include "geometry/cartesian_product.hpp"
#include "geometry/serialization.hpp"
#include "numerics/combinatorics.hpp"
#include "numerics/quadrature.hpp"
#include "quantities/named_quantities.hpp"
namespace principia {
namespace numerics {
namespace internal_polynomial {
using base::is_instance_of_v;
using base::make_not_null_unique;
using base::not_constructible;
using geometry::DoubleOrQuantityOrPointOrMultivectorSerializer;
using geometry::cartesian_product::operator+;
using geometry::cartesian_product::operator-;
using geometry::cartesian_product::operator*;
using geometry::cartesian_product::operator/;
using geometry::pointwise_inner_product::PointwiseInnerProduct;
using geometry::polynomial_ring::operator*;
using quantities::Apply;
using quantities::DebugString;
using quantities::Difference;
using quantities::Exponentiation;
using quantities::Pow;
using quantities::Time;
// A helper for changing the origin of a monomial (x - x₁)ⁿ. It computes the
// coefficients of the same monomial as a polynomial of (x - x₂), i.e.:
// cₙ(x - x₁)ⁿ = cₙ((x - x₂) + (x₁ - x₂))ⁿ =
// Σ cₙ(n k)(x - x₂)ᵏ(x₁ - x₂)ⁿ⁻ᵏ
// where (n k) is the binomial coefficient. The coefficients are for a
// polynomial of the given degree, with zeros for the unneeded high-degree
// terms.
template<typename Value, typename Argument, int degree, int n,
template<typename, typename, int> typename Evaluator,
typename = std::make_index_sequence<degree + 1>>
struct MonomialAtOrigin;
template<typename Value, typename Argument, int degree, int n,
template<typename, typename, int> typename Evaluator,
std::size_t... k>
struct MonomialAtOrigin<Value, Argument, degree, n,
Evaluator,
std::index_sequence<k...>> {
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree, Evaluator>::
Coefficients;
// The parameter coefficient is the coefficient of the monomial. The
// parameter shift is x₁ - x₂, computed only once by the caller.
static Coefficients MakeCoefficients(
std::tuple_element_t<n, Coefficients> const& coefficient,
Difference<Argument> const& shift);
};
template<typename Value, typename Argument, int degree, int n,
template<typename, typename, int> typename Evaluator,
std::size_t... k>
auto MonomialAtOrigin<Value, Argument, degree, n,
Evaluator,
std::index_sequence<k...>>::MakeCoefficients(
std::tuple_element_t<n, Coefficients> const& coefficient,
Difference<Argument> const& shift) -> Coefficients {
return {(k <= n ? coefficient * Binomial(n, k) *
Pow<static_cast<int>(n - k)>(shift)
: std::tuple_element_t<k, Coefficients>{})...};
}
// A helper for changing the origin of an entire polynomial, by repeatedly
// using MonomialAtOrigin. We need two helpers because changing the origin is
// a quadratic operation in terms of the degree.
template<typename Value, typename Argument, int degree_,
template<typename, typename, int> typename Evaluator,
typename = std::make_index_sequence<degree_ + 1>>
struct PolynomialAtOrigin;
template<typename Value, typename Argument, int degree,
template<typename, typename, int> typename Evaluator,
std::size_t... indices>
struct PolynomialAtOrigin<Value, Argument, degree, Evaluator,
std::index_sequence<indices...>> {
using Polynomial =
PolynomialInMonomialBasis<Value, Argument, degree, Evaluator>;
static Polynomial MakePolynomial(
typename Polynomial::Coefficients const& coefficients,
Argument const& from_origin,
Argument const& to_origin);
#if PRINCIPIA_COMPILER_MSVC_HAS_CXX20
using PolynomialAlias = Polynomial;
#endif
};
template<typename Value, typename Argument, int degree,
template<typename, typename, int> typename Evaluator,
std::size_t ...indices>
auto PolynomialAtOrigin<Value, Argument, degree,
Evaluator,
std::index_sequence<indices...>>::
#if PRINCIPIA_COMPILER_MSVC_HAS_CXX20
MakePolynomial(typename PolynomialAlias::Coefficients const& coefficients,
Argument const& from_origin,
Argument const& to_origin) -> PolynomialAlias {
#else
MakePolynomial(typename Polynomial::Coefficients const& coefficients,
Argument const& from_origin,
Argument const& to_origin) -> Polynomial {
#endif
Difference<Argument> const shift = to_origin - from_origin;
std::array<typename Polynomial::Coefficients, degree + 1> const
all_coefficients{
MonomialAtOrigin<Value, Argument, degree, indices, Evaluator>::
MakeCoefficients(std::get<indices>(coefficients), shift)...};
// It would be nicer to compute the sum using a fold expression, but Clang
// refuses to find the operator + in that context. Fold expressions, the
// final frontier...
typename Polynomial::Coefficients sum_coefficients;
for (auto const& coefficients : all_coefficients) {
sum_coefficients = sum_coefficients + coefficients;
}
return Polynomial(sum_coefficients, to_origin);
}
// Index-by-index assignment of RTuple to LTuple, which must have at least as
// many elements (and the types must match).
template<typename LTuple, typename RTuple,
typename = std::make_index_sequence<std::tuple_size_v<RTuple>>>
struct TupleAssigner;
template<typename LTuple, typename RTuple, std::size_t... indices>
struct TupleAssigner<LTuple, RTuple, std::index_sequence<indices...>> {
static void Assign(LTuple& left_tuple, RTuple const& right_tuple);
};
template<typename LTuple, typename RTuple, std::size_t... indices>
void TupleAssigner<LTuple, RTuple, std::index_sequence<indices...>>::Assign(
LTuple& left_tuple,
RTuple const& right_tuple) {
// This fold expression effectively implements repeated assignments.
((std::get<indices>(left_tuple) = std::get<indices>(right_tuple)), ...);
}
// - 1 in the second type is ultimately to avoid evaluating Pow<0> as generating
// a one is hard.
template<typename LTuple, typename RTuple,
typename = std::make_index_sequence<std::tuple_size_v<LTuple> - 1>>
struct TupleComposition;
template<typename LTuple, typename RTuple, std::size_t... left_indices>
struct TupleComposition<LTuple, RTuple, std::index_sequence<left_indices...>> {
static constexpr auto Compose(LTuple const& left_tuple,
RTuple const& right_tuple);
};
template<typename LTuple, typename RTuple, std::size_t... left_indices>
constexpr auto
TupleComposition<LTuple, RTuple, std::index_sequence<left_indices...>>::Compose(
LTuple const& left_tuple,
RTuple const& right_tuple) {
auto const degree_0 = std::tuple(std::get<0>(left_tuple));
if constexpr (sizeof...(left_indices) == 0) {
return degree_0;
} else {
// The + 1 in the expressions below match the - 1 in the primary declaration
// of TupleComposition.
return degree_0 +
((std::get<left_indices + 1>(left_tuple) *
geometry::polynomial_ring::Pow<left_indices + 1>(right_tuple)) +
...);
}
}
template<typename Tuple, int order,
typename = std::make_index_sequence<std::tuple_size_v<Tuple> - order>>
struct TupleDerivation;
template<typename Tuple, int order, std::size_t... indices>
struct TupleDerivation<Tuple, order, std::index_sequence<indices...>> {
static constexpr auto Derive(Tuple const& tuple);
};
template<typename Tuple, int order, std::size_t... indices>
constexpr auto
TupleDerivation<Tuple, order, std::index_sequence<indices...>>::Derive(
Tuple const& tuple) {
return std::make_tuple(FallingFactorial(order + indices, order) *
std::get<order + indices>(tuple)...);
}
template<typename Tuple, int count,
typename = std::make_index_sequence<std::tuple_size_v<Tuple> - count>>
struct TupleDropper;
template<typename Tuple, int count, std::size_t... indices>
struct TupleDropper<Tuple, count, std::index_sequence<indices...>> {
// Drops the first |count| elements of |tuple|.
static constexpr auto Drop(Tuple const& tuple);
};
template<typename Tuple, int count, std::size_t... indices>
constexpr auto
TupleDropper<Tuple, count, std::index_sequence<indices...>>::Drop(
Tuple const& tuple) {
return std::make_tuple(std::get<count + indices>(tuple)...);
}
template<typename Argument, typename Tuple,
typename = std::make_index_sequence<std::tuple_size_v<Tuple>>>
struct TupleIntegration;
template<typename Argument, typename Tuple, std::size_t... indices>
struct TupleIntegration<Argument, Tuple, std::index_sequence<indices...>> {
static constexpr auto Integrate(Tuple const& tuple);
};
template<typename Argument, typename Tuple, std::size_t... indices>
constexpr auto
TupleIntegration<Argument, Tuple, std::index_sequence<indices...>>::Integrate(
Tuple const& tuple) {
constexpr auto zero =
quantities::Primitive<std::tuple_element_t<0, Tuple>, Argument>{};
return std::make_tuple(
zero, std::get<indices>(tuple) / static_cast<double>(indices + 1)...);
}
template<typename Tuple, int k, int size = std::tuple_size_v<Tuple>>
struct TupleSerializer : not_constructible {
static void WriteToMessage(
Tuple const& tuple,
not_null<serialization::PolynomialInMonomialBasis*> message);
static void FillFromMessage(
serialization::PolynomialInMonomialBasis const& message,
Tuple& tuple);
// Cannot be called DebugString because of ADL in its body.
static std::vector<std::string> TupleDebugString(Tuple const& tuple,
std::string const& argument);
};
template<typename Tuple, int size>
struct TupleSerializer<Tuple, size, size> : not_constructible {
static void WriteToMessage(
Tuple const& tuple,
not_null<serialization::PolynomialInMonomialBasis*> message);
static void FillFromMessage(
serialization::PolynomialInMonomialBasis const& message,
Tuple& tuple);
// Cannot be called DebugString because of ADL in its body.
static std::vector<std::string> TupleDebugString(Tuple const& tuple,
std::string const& argument);
};
template<typename Tuple, int k, int size>
void TupleSerializer<Tuple, k, size>::WriteToMessage(
Tuple const& tuple,
not_null<serialization::PolynomialInMonomialBasis*> message) {
DoubleOrQuantityOrPointOrMultivectorSerializer<
std::tuple_element_t<k, Tuple>,
serialization::PolynomialInMonomialBasis::Coefficient>::
WriteToMessage(std::get<k>(tuple), message->add_coefficient());
TupleSerializer<Tuple, k + 1, size>::WriteToMessage(tuple, message);
}
template<typename Tuple, int k, int size>
void TupleSerializer<Tuple, k, size>::FillFromMessage(
serialization::PolynomialInMonomialBasis const& message,
Tuple& tuple) {
std::get<k>(tuple) =
DoubleOrQuantityOrPointOrMultivectorSerializer<
std::tuple_element_t<k, Tuple>,
serialization::PolynomialInMonomialBasis::Coefficient>::
ReadFromMessage(message.coefficient(k));
TupleSerializer<Tuple, k + 1, size>::FillFromMessage(message, tuple);
}
template<typename Tuple, int k, int size>
std::vector<std::string> TupleSerializer<Tuple, k, size>::TupleDebugString(
Tuple const& tuple,
std::string const& argument) {
auto tail =
TupleSerializer<Tuple, k + 1, size>::TupleDebugString(tuple, argument);
auto const coefficient = std::get<k>(tuple);
if (coefficient == std::tuple_element_t<k, Tuple>{}) {
return tail;
}
std::string head;
switch (k) {
case 0:
head = DebugString(coefficient);
break;
case 1:
head = absl::StrCat(DebugString(coefficient), " * ", argument);
break;
default:
head = absl::StrCat(DebugString(coefficient), " * ", argument, "^", k);
break;
}
tail.insert(tail.begin(), head);
return tail;
}
template<typename Tuple, int size>
void TupleSerializer<Tuple, size, size>::WriteToMessage(
Tuple const& tuple,
not_null<serialization::PolynomialInMonomialBasis*> message) {}
template<typename Tuple, int size>
void TupleSerializer<Tuple, size, size>::FillFromMessage(
serialization::PolynomialInMonomialBasis const& message,
Tuple& tuple) {}
template<typename Tuple, int size>
std::vector<std::string> TupleSerializer<Tuple, size, size>::TupleDebugString(
Tuple const& tuple,
std::string const& argument) {
return {};
}
#define PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(value) \
case value: \
return make_not_null_unique< \
PolynomialInMonomialBasis<Value, Argument, value, Evaluator>>( \
PolynomialInMonomialBasis<Value, Argument, value, Evaluator>:: \
ReadFromMessage(message))
template<typename Value_, typename Argument_>
template<template<typename, typename, int> typename Evaluator>
not_null<std::unique_ptr<Polynomial<Value_, Argument_>>>
Polynomial<Value_, Argument_>::ReadFromMessage(
serialization::Polynomial const& message) {
// 24 is the largest exponent that we can serialize for Quantity.
switch (message.degree()) {
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(1);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(2);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(3);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(4);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(5);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(6);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(7);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(8);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(9);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(10);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(11);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(12);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(13);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(14);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(15);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(16);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(17);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(18);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(19);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(20);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(21);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(22);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(23);
PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE(24);
default:
LOG(FATAL) << "Unexpected degree " << message.degree();
break;
}
}
#undef PRINCIPIA_POLYNOMIAL_DEGREE_VALUE_CASE
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
constexpr
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
PolynomialInMonomialBasis(Coefficients coefficients,
Argument const& origin)
: coefficients_(std::move(coefficients)),
origin_(origin) {}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
template<typename, typename>
constexpr PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
PolynomialInMonomialBasis(Coefficients coefficients)
: coefficients_(std::move(coefficients)),
origin_(Argument{}) {}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
template<int higher_degree_,
template<typename, typename, int> typename HigherEvaluator>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
operator PolynomialInMonomialBasis<Value_, Argument_, higher_degree_,
HigherEvaluator>() const {
static_assert(degree_ <= higher_degree_);
using Result = PolynomialInMonomialBasis<
Value, Argument, higher_degree_, HigherEvaluator>;
typename Result::Coefficients higher_coefficients;
TupleAssigner<typename Result::Coefficients, Coefficients>::Assign(
higher_coefficients, coefficients_);
return Result(higher_coefficients, origin_);
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
Value_ PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
operator()(Argument const& argument) const {
return Evaluator<Value, Difference<Argument>, degree_>::Evaluate(
coefficients_, argument - origin_);
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
Derivative<Value_, Argument_>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
EvaluateDerivative(Argument const& argument) const {
return Evaluator<Value, Difference<Argument>, degree_>::EvaluateDerivative(
coefficients_, argument - origin_);
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
constexpr int
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
degree() const {
return degree_;
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
bool PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
is_zero() const {
return coefficients_ == Coefficients{};
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
Argument_ const&
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
origin() const {
return origin_;
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
AtOrigin(Argument const& origin) const {
return PolynomialAtOrigin<Value, Argument, degree_, Evaluator>::
MakePolynomial(coefficients_,
/*from_origin=*/origin_,
/*to_origin=*/origin);
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
template<int order>
PolynomialInMonomialBasis<
Derivative<Value_, Argument_, order>, Argument_, degree_ - order, Evaluator>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
Derivative() const {
return PolynomialInMonomialBasis<
quantities::Derivative<Value, Argument, order>, Argument,
degree_ - order, Evaluator>(
TupleDerivation<Coefficients, order>::Derive(coefficients_),
origin_);
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
template<typename, typename>
PolynomialInMonomialBasis<Primitive<Value_, Argument_>, Argument_,
degree_ + 1, Evaluator>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
Primitive() const {
return PolynomialInMonomialBasis<
quantities::Primitive<Value, Argument>, Argument,
degree_ + 1, Evaluator>(
TupleIntegration<Argument, Coefficients>::Integrate(coefficients_),
origin_);
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
template<typename, typename>
quantities::Primitive<Value_, Argument_>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
Integrate(Argument const& argument1,
Argument const& argument2) const {
// + 2 is to take into account the truncation resulting from integer division.
return quadrature::GaussLegendre<(degree_ + 2) / 2>(*this,
argument1, argument2);
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>&
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
operator+=(PolynomialInMonomialBasis const& right) {
*this = *this + right;
return *this;
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>&
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
operator-=(PolynomialInMonomialBasis const& right) {
*this = *this - right;
return *this;
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
void PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
WriteToMessage(not_null<serialization::Polynomial*> message) const {
message->set_degree(degree_);
auto* const extension =
message->MutableExtension(
serialization::PolynomialInMonomialBasis::extension);
TupleSerializer<Coefficients, 0>::WriteToMessage(coefficients_, extension);
DoubleOrQuantityOrPointOrMultivectorSerializer<
Argument,
serialization::PolynomialInMonomialBasis>::WriteToMessage(origin_,
extension);
}
template<typename Value_, typename Argument_, int degree_,
template<typename, typename, int> typename Evaluator>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>
PolynomialInMonomialBasis<Value_, Argument_, degree_, Evaluator>::
ReadFromMessage(serialization::Polynomial const& message) {
CHECK_EQ(degree_, message.degree()) << message.DebugString();
CHECK(message.HasExtension(
serialization::PolynomialInMonomialBasis::extension))
<< message.DebugString();
auto const& extension =
message.GetExtension(
serialization::PolynomialInMonomialBasis::extension);
bool const is_pre_gröbner = extension.origin_case() ==
serialization::PolynomialInMonomialBasis::ORIGIN_NOT_SET;
LOG_IF(WARNING, is_pre_gröbner)
<< u8"Reading pre-Gröbner PolynomialInMonomialBasis";
Coefficients coefficients;
TupleSerializer<Coefficients, 0>::FillFromMessage(extension, coefficients);
auto const origin = is_pre_gröbner
? Argument{}
: DoubleOrQuantityOrPointOrMultivectorSerializer<
Argument,
serialization::PolynomialInMonomialBasis>::
ReadFromMessage(extension);
return PolynomialInMonomialBasis(coefficients, origin);
}
template<typename Value, typename Argument, int rdegree_,
template<typename, typename, int> typename Evaluator>
constexpr PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator>
operator+(PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator> const&
right) {
return right;
}
template<typename Value, typename Argument, int rdegree_,
template<typename, typename, int> typename Evaluator>
constexpr PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator>
operator-(PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator> const&
right) {
return PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator>(
-right.coefficients_,
right.origin_);
}
template<typename Value, typename Argument, int ldegree_, int rdegree_,
template<typename, typename, int> typename Evaluator>
FORCE_INLINE(constexpr)
PolynomialInMonomialBasis<Value, Argument,
PRINCIPIA_MAX(ldegree_, rdegree_), Evaluator>
operator+(
PolynomialInMonomialBasis<Value, Argument, ldegree_, Evaluator> const& left,
PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator> const&
right) {
CONSTEXPR_CHECK(left.origin_ == right.origin_);
return PolynomialInMonomialBasis<Value, Argument,
std::max(ldegree_, rdegree_), Evaluator>(
left.coefficients_ + right.coefficients_,
left.origin_);
}
template<typename Value, typename Argument, int ldegree_, int rdegree_,
template<typename, typename, int> typename Evaluator>
FORCE_INLINE(constexpr)
PolynomialInMonomialBasis<Value, Argument,
PRINCIPIA_MAX(ldegree_, rdegree_), Evaluator>
operator-(
PolynomialInMonomialBasis<Value, Argument, ldegree_, Evaluator> const& left,
PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator> const&
right) {
CONSTEXPR_CHECK(left.origin_ == right.origin_);
return PolynomialInMonomialBasis<Value, Argument,
std::max(ldegree_, rdegree_), Evaluator>(
left.coefficients_ - right.coefficients_,
left.origin_);
}
template<typename Scalar,
typename Value, typename Argument, int degree_,
template<typename, typename, int> typename Evaluator>
FORCE_INLINE(constexpr)
PolynomialInMonomialBasis<Product<Scalar, Value>, Argument,
degree_, Evaluator>
operator*(Scalar const& left,
PolynomialInMonomialBasis<Value, Argument, degree_, Evaluator> const&
right) {
return PolynomialInMonomialBasis<Product<Scalar, Value>, Argument, degree_,
Evaluator>(left * right.coefficients_,
right.origin_);
}
template<typename Scalar,
typename Value, typename Argument, int degree_,
template<typename, typename, int> typename Evaluator>
FORCE_INLINE(constexpr)
PolynomialInMonomialBasis<Product<Value, Scalar>, Argument,
degree_, Evaluator>
operator*(PolynomialInMonomialBasis<Value, Argument, degree_, Evaluator> const&
left,
Scalar const& right) {
return PolynomialInMonomialBasis<Product<Value, Scalar>, Argument, degree_,
Evaluator>(left.coefficients_ * right,
left.origin_);
}
template<typename Scalar,
typename Value, typename Argument, int degree_,
template<typename, typename, int> typename Evaluator>
FORCE_INLINE(constexpr)
PolynomialInMonomialBasis<Quotient<Value, Scalar>, Argument,
degree_, Evaluator>
operator/(PolynomialInMonomialBasis<Value, Argument, degree_, Evaluator> const&
left,
Scalar const& right) {
return PolynomialInMonomialBasis<Quotient<Value, Scalar>, Argument, degree_,
Evaluator>(left.coefficients_ / right,
left.origin_);
}
template<typename LValue, typename RValue,
typename Argument, int ldegree_, int rdegree_,
template<typename, typename, int> typename Evaluator>
FORCE_INLINE(constexpr)
PolynomialInMonomialBasis<Product<LValue, RValue>, Argument,
ldegree_ + rdegree_, Evaluator>
operator*(
PolynomialInMonomialBasis<LValue, Argument, ldegree_, Evaluator> const&
left,
PolynomialInMonomialBasis<RValue, Argument, rdegree_, Evaluator> const&
right) {
CONSTEXPR_CHECK(left.origin_ == right.origin_);
return PolynomialInMonomialBasis<Product<LValue, RValue>, Argument,
ldegree_ + rdegree_, Evaluator>(
left.coefficients_ * right.coefficients_,
left.origin_);
}
#if PRINCIPIA_COMPILER_MSVC_HANDLES_POLYNOMIAL_OPERATORS
template<typename Value, typename Argument, int ldegree_,
template<typename, typename, int> typename Evaluator>
constexpr PolynomialInMonomialBasis<Value, Argument, ldegree_, Evaluator>
operator+(PolynomialInMonomialBasis<Difference<Value>, Argument,
ldegree_, Evaluator> const& left,
Value const& right) {
auto const dropped_left_coefficients =
TupleDropper<typename PolynomialInMonomialBasis<
Difference<Value>, Argument, ldegree_, Evaluator>::
Coefficients,
/*count=*/1>::Drop(left.coefficients_);
return PolynomialInMonomialBasis<Value, Argument, ldegree_, Evaluator>(
std::tuple_cat(std::tuple(std::get<0>(left.coefficients_) + right),
dropped_left_coefficients),
left.origin_);
}
#endif
template<typename Value, typename Argument, int rdegree_,
template<typename, typename, int> typename Evaluator>
constexpr PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator>
operator+(Value const& left,
PolynomialInMonomialBasis<Difference<Value>, Argument,
rdegree_, Evaluator> const& right) {
auto const dropped_right_coefficients =
TupleDropper<typename PolynomialInMonomialBasis<
Difference<Value>, Argument, rdegree_, Evaluator>::
Coefficients,
/*count=*/1>::Drop(right.coefficients_);
return PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator>(
std::tuple_cat(std::tuple(left + std::get<0>(right.coefficients_)),
dropped_right_coefficients),
right.origin_);
}
template<typename Value, typename Argument, int ldegree_,
template<typename, typename, int> typename Evaluator>
constexpr PolynomialInMonomialBasis<Difference<Value>, Argument,
ldegree_, Evaluator>
operator-(PolynomialInMonomialBasis<Value, Argument,
ldegree_, Evaluator> const& left,
Value const& right) {
auto const dropped_left_coefficients =
TupleDropper<typename PolynomialInMonomialBasis<
Value, Argument, ldegree_, Evaluator>::Coefficients,
/*count=*/1>::Drop(left.coefficients_);
return PolynomialInMonomialBasis<Difference<Value>, Argument,
ldegree_, Evaluator>(
std::tuple_cat(std::tuple(std::get<0>(left.coefficients_) - right),
dropped_left_coefficients),
left.origin_);
}
template<typename Value, typename Argument, int rdegree_,
template<typename, typename, int> typename Evaluator>
constexpr PolynomialInMonomialBasis<Difference<Value>, Argument,
rdegree_, Evaluator>
operator-(Value const& left,
PolynomialInMonomialBasis<Value, Argument,
rdegree_, Evaluator> const& right) {
auto const dropped_right_coefficients =
TupleDropper<typename PolynomialInMonomialBasis<
Value, Argument, rdegree_, Evaluator>::Coefficients,
/*count=*/1>::Drop(right.coefficients_);
return PolynomialInMonomialBasis<Difference<Value>, Argument,
rdegree_, Evaluator>(
std::tuple_cat(std::tuple(left - std::get<0>(right.coefficients_)),
dropped_right_coefficients),
right.origin_);
}
template<typename LValue, typename RValue,
typename Argument, int ldegree_, int rdegree_,
template<typename, typename, int> typename Evaluator>
constexpr PolynomialInMonomialBasis<LValue, Argument,
ldegree_ * rdegree_, Evaluator>
Compose(
PolynomialInMonomialBasis<LValue, RValue, ldegree_, Evaluator> const&
left,
PolynomialInMonomialBasis<RValue, Argument, rdegree_, Evaluator> const&
right) {
using LCoefficients =
typename PolynomialInMonomialBasis<LValue, RValue, ldegree_,
Evaluator>::Coefficients;
using RCoefficients =
typename PolynomialInMonomialBasis<RValue, Argument, rdegree_,
Evaluator>::Coefficients;
return PolynomialInMonomialBasis<LValue, Argument,
ldegree_ * rdegree_,
Evaluator>(
TupleComposition<LCoefficients, RCoefficients>::Compose(
left.coefficients_, right.coefficients_),
right.origin_);
}
template<typename LValue, typename RValue,
typename Argument, int ldegree_, int rdegree_,
template<typename, typename, int> typename Evaluator>
FORCE_INLINE(constexpr)
PolynomialInMonomialBasis<
typename Hilbert<LValue, RValue>::InnerProductType, Argument,
ldegree_ + rdegree_, Evaluator>
PointwiseInnerProduct(
PolynomialInMonomialBasis<LValue, Argument, ldegree_, Evaluator> const&
left,
PolynomialInMonomialBasis<RValue, Argument, rdegree_, Evaluator> const&
right) {
CONSTEXPR_CHECK(left.origin_ == right.origin_);
return PolynomialInMonomialBasis<
typename Hilbert<LValue, RValue>::InnerProductType, Argument,
ldegree_ + rdegree_, Evaluator>(
PointwiseInnerProduct(left.coefficients_, right.coefficients_),
left.origin_);
}
template<typename Value, typename Argument, int degree_,
template<typename, typename, int> typename Evaluator>
std::ostream& operator<<(
std::ostream& out,
PolynomialInMonomialBasis<Value, Argument, degree_, Evaluator> const&
polynomial) {
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree_, Evaluator>::
Coefficients;
std::vector<std::string> debug_string;
debug_string = TupleSerializer<Coefficients, 0>::TupleDebugString(
polynomial.coefficients_,
absl::StrCat("(T - ", DebugString(polynomial.origin_), ")"));
if (debug_string.empty()) {
out << DebugString(Value{});
} else {
out << absl::StrJoin(debug_string, " + ");
}
return out;
}
} // namespace internal_polynomial
} // namespace numerics
} // namespace principia
| 41.393939 | 80 | 0.7 | [
"geometry",
"vector"
] |
2bd5439ad52bf13012db8db09e35393d5dda8acf | 15,200 | cpp | C++ | FEBioSource2.9/FECore/FEDomain2D.cpp | wzaylor/FEBio_MCLS | f1052733c31196544fb0921aa55ffa5167a25f98 | [
"Intel"
] | 1 | 2021-08-24T08:37:21.000Z | 2021-08-24T08:37:21.000Z | FEBioSource2.9/FECore/FEDomain2D.cpp | wzaylor/FEBio_MCLS | f1052733c31196544fb0921aa55ffa5167a25f98 | [
"Intel"
] | null | null | null | FEBioSource2.9/FECore/FEDomain2D.cpp | wzaylor/FEBio_MCLS | f1052733c31196544fb0921aa55ffa5167a25f98 | [
"Intel"
] | 1 | 2021-03-15T08:22:06.000Z | 2021-03-15T08:22:06.000Z | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2019 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "FEDomain2D.h"
#include "FEMesh.h"
#include "FEMaterial.h"
#include "log.h"
//-----------------------------------------------------------------------------
void FEDomain2D::Create(int nelems, int elemType)
{
m_Elem.resize(nelems);
for (int i = 0; i<nelems; ++i) m_Elem[i].SetDomain(this);
if (elemType != -1)
for (int i=0; i<nelems; ++i) m_Elem[i].SetType(elemType);
}
//-----------------------------------------------------------------------------
void FEDomain2D::PreSolveUpdate(const FETimeInfo& timeInfo)
{
for (size_t i=0; i<m_Elem.size(); ++i)
{
FEElement2D& el = m_Elem[i];
int n = el.GaussPoints();
for (int j=0; j<n; ++j) el.GetMaterialPoint(j)->Update(timeInfo);
}
}
//-----------------------------------------------------------------------------
//! Initialization
bool FEDomain2D::Init()
{
if (FEDomain::Init() == false) return false;
// check for initially inverted elements
int ninverted = 0;
for (int i = 0; i<Elements(); ++i)
{
FEElement2D& el = Element(i);
int nint = el.GaussPoints();
for (int n = 0; n<nint; ++n)
{
double J0 = detJ0(el, n);
if (J0 <= 0)
{
felog.printf("**************************** E R R O R ****************************\n");
felog.printf("Negative jacobian detected at integration point %d of element %d\n", n + 1, el.GetID());
felog.printf("Jacobian = %lg\n", J0);
felog.printf("Did you use the right node numbering?\n");
felog.printf("Nodes:");
for (int l = 0; l<el.Nodes(); ++l)
{
felog.printf("%d", el.m_node[l] + 1);
if (l + 1 != el.Nodes()) felog.printf(","); else felog.printf("\n");
}
felog.printf("*******************************************************************\n\n");
++ninverted;
}
}
}
return (ninverted == 0);
}
//-----------------------------------------------------------------------------
void FEDomain2D::Reset()
{
for (int i=0; i<(int) m_Elem.size(); ++i)
{
FEElement2D& el = m_Elem[i];
int n = el.GaussPoints();
for (int j=0; j<n; ++j) el.GetMaterialPoint(j)->Init();
}
}
//-----------------------------------------------------------------------------
//! Calculate the inverse jacobian with respect to the reference frame at
//! integration point n. The inverse jacobian is return in Ji. The return value
//! is the determinant of the jacobian (not the inverse!)
double FEDomain2D::invjac0(FEElement2D& el, double Ji[2][2], int n)
{
// initial nodal coordinates
int neln = el.Nodes();
double x[FEElement::MAX_NODES];
double y[FEElement::MAX_NODES];
for (int i=0; i<neln; ++i)
{
vec3d& ri = m_pMesh->Node(el.m_node[i]).m_r0;
x[i] = ri.x;
y[i] = ri.y;
}
// calculate Jacobian
double J[2][2] = {0};
for (int i=0; i<neln; ++i)
{
const double& Gri = el.Hr(n)[i];
const double& Gsi = el.Hs(n)[i];
J[0][0] += Gri*x[i]; J[0][1] += Gsi*x[i];
J[1][0] += Gri*y[i]; J[1][1] += Gsi*y[i];
}
// calculate the determinant
double det = J[0][0]*J[1][1] - J[0][1]*J[1][0];
// make sure the determinant is positive
if (det <= 0) throw NegativeJacobian(el.GetID(), n+1, det);
// calculate the inverse jacobian
double deti = 1.0 / det;
Ji[0][0] = deti*J[1][1];
Ji[1][0] = -deti*J[1][0];
Ji[0][1] = -deti*J[0][1];
Ji[1][1] = deti*J[0][0];
return det;
}
//-----------------------------------------------------------------------------
//! Calculate the inverse jacobian with respect to the reference frame at
//! integration point n. The inverse jacobian is return in Ji. The return value
//! is the determinant of the jacobian (not the inverse!)
double FEDomain2D::invjact(FEElement2D& el, double Ji[2][2], int n)
{
// number of nodes
int neln = el.Nodes();
// nodal coordinates
double x[FEElement::MAX_NODES];
double y[FEElement::MAX_NODES];
for (int i=0; i<neln; ++i)
{
vec3d& ri = m_pMesh->Node(el.m_node[i]).m_rt;
x[i] = ri.x;
y[i] = ri.y;
}
// calculate Jacobian
double J[2][2] = {0};
for (int i=0; i<neln; ++i)
{
const double& Gri = el.Hr(n)[i];
const double& Gsi = el.Hs(n)[i];
J[0][0] += Gri*x[i]; J[0][1] += Gsi*x[i];
J[1][0] += Gri*y[i]; J[1][1] += Gsi*y[i];
}
// calculate the determinant
double det = J[0][0]*J[1][1] - J[0][1]*J[1][0];
// make sure the determinant is positive
if (det <= 0) throw NegativeJacobian(el.GetID(), n+1, det);
// calculate the inverse jacobian
double deti = 1.0 / det;
Ji[0][0] = deti*J[1][1];
Ji[1][0] = -deti*J[1][0];
Ji[0][1] = -deti*J[0][1];
Ji[1][1] = deti*J[0][0];
return det;
}
//-----------------------------------------------------------------------------
//! calculate gradient of function at integration points
//! A 2D element is assumed to have no variation through the thickness.
vec2d FEDomain2D::gradient(FEElement2D& el, double* fn, int n)
{
double Ji[2][2];
invjact(el, Ji, n);
double* Grn = el.Hr(n);
double* Gsn = el.Hs(n);
double Gx, Gy;
vec2d gradf(0,0);
int N = el.Nodes();
for (int i=0; i<N; ++i)
{
// calculate global gradient of shape functions
// note that we need the transposed of Ji, not Ji itself !
Gx = Ji[0][0]*Grn[i]+Ji[1][0]*Gsn[i];
Gy = Ji[0][1]*Grn[i]+Ji[1][1]*Gsn[i];
// calculate gradient
gradf.x() += Gx*fn[i];
gradf.y() += Gy*fn[i];
}
return gradf;
}
//-----------------------------------------------------------------------------
//! calculate gradient of function at integration points
//! A 2D element is assumed to have no variation through the thickness.
vec2d FEDomain2D::gradient(FEElement2D& el, vector<double>& fn, int n)
{
double Ji[2][2];
invjact(el, Ji, n);
double* Grn = el.Hr(n);
double* Gsn = el.Hs(n);
vec2d gradf(0,0);
int N = el.Nodes();
for (int i=0; i<N; ++i)
{
// calculate global gradient of shape functions
// note that we need the transposed of Ji, not Ji itself !
double Gx = Ji[0][0]*Grn[i]+Ji[1][0]*Gsn[i];
double Gy = Ji[0][1]*Grn[i]+Ji[1][1]*Gsn[i];
// calculate pressure gradient
gradf.x() += Gx*fn[i];
gradf.y() += Gy*fn[i];
}
return gradf;
}
//-----------------------------------------------------------------------------
//! calculate spatial gradient of function at integration points
mat2d FEDomain2D::gradient(FEElement2D& el, vec2d* fn, int n)
{
double Ji[2][2];
invjact(el, Ji, n);
vec2d g1(Ji[0][0],Ji[0][1]);
vec2d g2(Ji[1][0],Ji[1][1]);
double* Gr = el.Hr(n);
double* Gs = el.Hs(n);
mat2d gradf;
gradf.zero();
int N = el.Nodes();
for (int i=0; i<N; ++i)
{
vec2d tmp = g1*Gr[i] + g2*Gs[i];
gradf += dyad(fn[i], tmp);
}
return gradf;
}
//-----------------------------------------------------------------------------
//! calculate spatial gradient of function at integration points
//! A 2D element is assumed to have no variation through the thickness.
mat3d FEDomain2D::gradient(FEElement2D& el, vec3d* fn, int n)
{
double Ji[2][2];
invjact(el, Ji, n);
vec3d g1(Ji[0][0],Ji[0][1],0.0);
vec3d g2(Ji[1][0],Ji[1][1],0.0);
double* Gr = el.Hr(n);
double* Gs = el.Hs(n);
mat3d gradf;
gradf.zero();
int N = el.Nodes();
for (int i=0; i<N; ++i)
gradf += fn[i] & (g1*Gr[i] + g2*Gs[i]);
return gradf;
}
//-----------------------------------------------------------------------------
//! Calculate jacobian with respect to reference frame
double FEDomain2D::detJ0(FEElement2D &el, int n)
{
// initial nodal coordinates
int neln = el.Nodes();
double x[FEElement::MAX_NODES];
double y[FEElement::MAX_NODES];
for (int i=0; i<neln; ++i)
{
vec3d& ri = m_pMesh->Node(el.m_node[i]).m_r0;
x[i] = ri.x;
y[i] = ri.y;
}
// calculate Jacobian
double J[2][2] = {0};
for (int i=0; i<neln; ++i)
{
const double& Gri = el.Hr(n)[i];
const double& Gsi = el.Hs(n)[i];
J[0][0] += Gri*x[i]; J[0][1] += Gsi*x[i];
J[1][0] += Gri*y[i]; J[1][1] += Gsi*y[i];
}
// calculate the determinant
double det = J[0][0]*J[1][1] - J[0][1]*J[1][0];
return det;
}
//-----------------------------------------------------------------------------
//! Calculate jacobian with respect to current frame
double FEDomain2D::detJt(FEElement2D &el, int n)
{
// initial nodal coordinates
int neln = el.Nodes();
double x[FEElement::MAX_NODES];
double y[FEElement::MAX_NODES];
for (int i=0; i<neln; ++i)
{
vec3d& ri = m_pMesh->Node(el.m_node[i]).m_rt;
x[i] = ri.x;
y[i] = ri.y;
}
// calculate Jacobian
double J[2][2] = {0};
for (int i=0; i<neln; ++i)
{
const double& Gri = el.Hr(n)[i];
const double& Gsi = el.Hs(n)[i];
J[0][0] += Gri*x[i]; J[0][1] += Gsi*x[i];
J[1][0] += Gri*y[i]; J[1][1] += Gsi*y[i];
}
// calculate the determinant
double det = J[0][0]*J[1][1] - J[0][1]*J[1][0];
return det;
}
//-----------------------------------------------------------------------------
//! This function calculates the covariant basis vectors of a 2D element
//! at an integration point
void FEDomain2D::CoBaseVectors(FEElement2D& el, int j, vec2d g[2])
{
FEMesh& m = *m_pMesh;
// get the nr of nodes
int n = el.Nodes();
// get the shape function derivatives
double* Hr = el.Hr(j);
double* Hs = el.Hs(j);
g[0] = g[1] = vec2d(0,0);
for (int i=0; i<n; ++i)
{
vec2d rt = vec2d(m.Node(el.m_node[i]).m_rt.x,m.Node(el.m_node[i]).m_rt.y);
g[0] += rt*Hr[i];
g[1] += rt*Hs[i];
}
}
//-----------------------------------------------------------------------------
//! This function calculates the contravariant basis vectors of a 2D element
//! at an integration point
void FEDomain2D::ContraBaseVectors(FEElement2D& el, int j, vec2d gcnt[2])
{
vec2d gcov[2];
CoBaseVectors(el, j, gcov);
mat2d J = mat2d(gcov[0].x(), gcov[1].x(),
gcov[0].y(), gcov[1].y());
mat3d Ji = J.inverse();
gcnt[0] = vec2d(Ji(0,0),Ji(0,1));
gcnt[1] = vec2d(Ji(1,0),Ji(1,1));
}
//-----------------------------------------------------------------------------
//! This function calculates the parametric derivatives of covariant basis
//! vectors of a 2D element at an integration point
void FEDomain2D::CoBaseVectorDerivatives(FEElement2D& el, int j, vec2d dg[2][2])
{
FEMesh& m = *m_pMesh;
// get the nr of nodes
int n = el.Nodes();
// get the shape function derivatives
double* Hrr = el.Hrr(j); double* Hrs = el.Hrs(j);
double* Hsr = el.Hsr(j); double* Hss = el.Hss(j);
dg[0][0] = dg[0][1] = vec2d(0,0); // derivatives of g[0]
dg[1][0] = dg[1][1] = vec2d(0,0); // derivatives of g[1]
for (int i=0; i<n; ++i)
{
vec2d rt = vec2d(m.Node(el.m_node[i]).m_rt.x,m.Node(el.m_node[i]).m_rt.y);
dg[0][0] += rt*Hrr[i]; dg[0][1] += rt*Hsr[i];
dg[1][0] += rt*Hrs[i]; dg[1][1] += rt*Hss[i];
}
}
//-----------------------------------------------------------------------------
//! This function calculates the parametric derivatives of contravariant basis
//! vectors of a solid element at an integration point
void FEDomain2D::ContraBaseVectorDerivatives(FEElement2D& el, int j, vec2d dgcnt[2][2])
{
vec2d gcnt[2];
vec2d dgcov[2][2];
ContraBaseVectors(el, j, gcnt);
CoBaseVectorDerivatives(el, j, dgcov);
// derivatives of gcnt[0]
dgcnt[0][0] = -gcnt[0]*(gcnt[0]*dgcov[0][0])-gcnt[1]*(gcnt[0]*dgcov[1][0]);
dgcnt[0][1] = -gcnt[0]*(gcnt[0]*dgcov[0][1])-gcnt[1]*(gcnt[0]*dgcov[1][1]);
// derivatives of gcnt[1]
dgcnt[1][0] = -gcnt[0]*(gcnt[1]*dgcov[0][0])-gcnt[1]*(gcnt[1]*dgcov[1][0]);
dgcnt[1][1] = -gcnt[0]*(gcnt[1]*dgcov[0][1])-gcnt[1]*(gcnt[1]*dgcov[1][1]);
}
//-----------------------------------------------------------------------------
//! calculate the laplacian of a vector function at an integration point
vec2d FEDomain2D::lapvec(FEElement2D& el, vec2d* fn, int n)
{
vec2d gcnt[2];
vec2d dgcnt[2][2];
ContraBaseVectors(el, n, gcnt);
ContraBaseVectorDerivatives(el, n, dgcnt);
double* Gr = el.Hr(n);
double* Gs = el.Hs(n);
// get the shape function derivatives
double* Hrr = el.Hrr(n); double* Hrs = el.Hrs(n);
double* Hsr = el.Hsr(n); double* Hss = el.Hss(n);
vec2d lapv(0,0);
int N = el.Nodes();
for (int i=0; i<N; ++i)
lapv += fn[i]*((gcnt[0]*Hrr[i]+dgcnt[0][0]*Gr[i])*gcnt[0]+
(gcnt[0]*Hrs[i]+dgcnt[0][1]*Gr[i])*gcnt[1]+
(gcnt[1]*Hsr[i]+dgcnt[1][0]*Gs[i])*gcnt[0]+
(gcnt[1]*Hss[i]+dgcnt[1][1]*Gs[i])*gcnt[1]);
return lapv;
}
//-----------------------------------------------------------------------------
//! calculate the gradient of the divergence of a vector function at an integration point
vec2d FEDomain2D::gradivec(FEElement2D& el, vec2d* fn, int n)
{
vec2d gcnt[2];
vec2d dgcnt[2][2];
ContraBaseVectors(el, n, gcnt);
ContraBaseVectorDerivatives(el, n, dgcnt);
double* Gr = el.Hr(n);
double* Gs = el.Hs(n);
// get the shape function derivatives
double* Hrr = el.Hrr(n); double* Hrs = el.Hrs(n);
double* Hsr = el.Hsr(n); double* Hss = el.Hss(n);
vec2d gdv(0,0);
int N = el.Nodes();
for (int i=0; i<N; ++i)
gdv +=
gcnt[0]*((gcnt[0]*Hrr[i]+dgcnt[0][0]*Gr[i])*fn[i])+
gcnt[1]*((gcnt[0]*Hrs[i]+dgcnt[0][1]*Gr[i])*fn[i])+
gcnt[0]*((gcnt[1]*Hsr[i]+dgcnt[1][0]*Gs[i])*fn[i])+
gcnt[1]*((gcnt[1]*Hss[i]+dgcnt[1][1]*Gs[i])*fn[i]);
return gdv;
}
| 30.339321 | 106 | 0.521776 | [
"shape",
"vector",
"solid"
] |
2bdddcac4fc4e4a5cae18d43deff53227d83b5a0 | 1,242 | hpp | C++ | dev/Basic/long/database/dao/HHCoordinatesDao.hpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 50 | 2018-12-21T08:21:38.000Z | 2022-01-24T09:47:59.000Z | dev/Basic/long/database/dao/HHCoordinatesDao.hpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 2 | 2018-12-19T13:42:47.000Z | 2019-05-13T04:11:45.000Z | dev/Basic/long/database/dao/HHCoordinatesDao.hpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 27 | 2018-11-28T07:30:34.000Z | 2022-02-05T02:22:26.000Z | /*
* HHCoordinatesDao.hpp
*
* Created on: 11 Mar 2016
* Author: gishara
*/
#pragma once
#include "database/dao/SqlAbstractDao.hpp"
#include "database/entity/HHCoordinates.hpp"
using namespace boost;
namespace sim_mob {
namespace long_term {
/**
* Data Access Object to household coordinates view on datasource.
*/
class HHCoordinatesDao : public db::SqlAbstractDao<HHCoordinates> {
public:
HHCoordinatesDao(db::DB_Connection& connection);
virtual ~HHCoordinatesDao();
private:
/**
* Fills the given outObj with all values contained on Row.
* @param result row with data to fill the out object.
* @param outObj to fill.
*/
void fromRow(db::Row& result, HHCoordinates& outObj);
/**
* Fills the outParam with all values to insert or update on datasource.
* @param data to get values.
* @param outParams to put the data parameters.
* @param update tells if operation is an Update or Insert.
*/
void toRow(HHCoordinates& data, db::Parameters& outParams, bool update);
};
}
}
| 28.883721 | 84 | 0.588567 | [
"object"
] |
2bde47001564322c806553345252625ddd494653 | 47,877 | cpp | C++ | Mojo.2.0/Mojo/Mojo.Native/TileManager.cpp | Rhoana/Mojo | b0d79bc4792b06fb508e30b23566ab3a3369879e | [
"MIT"
] | 4 | 2015-01-15T02:19:43.000Z | 2015-04-19T04:08:37.000Z | Mojo.2.0/Mojo/Mojo.Native/TileManager.cpp | Rhoana/Mojo | b0d79bc4792b06fb508e30b23566ab3a3369879e | [
"MIT"
] | null | null | null | Mojo.2.0/Mojo/Mojo.Native/TileManager.cpp | Rhoana/Mojo | b0d79bc4792b06fb508e30b23566ab3a3369879e | [
"MIT"
] | 7 | 2015-01-23T23:31:19.000Z | 2019-06-20T08:45:50.000Z | #include "TileManager.hpp"
#include "Mojo.Core/Stl.hpp"
//#include "Mojo.Core/OpenCV.hpp"
#include "Mojo.Core/ForEach.hpp"
#include "Mojo.Core/D3D11CudaTexture.hpp"
#include "Mojo.Core/Index.hpp"
#include "TileCacheEntry.hpp"
using namespace Mojo::Core;
namespace Mojo
{
namespace Native
{
TileManager::TileManager( ID3D11Device* d3d11Device, ID3D11DeviceContext* d3d11DeviceContext, ITileServer* tileServer, Core::PrimitiveMap constParameters ) :
mIdColorMapBuffer ( NULL ),
mIdColorMapShaderResourceView( NULL ),
mLabelIdMapBuffer ( NULL ),
mLabelIdMapShaderResourceView( NULL ),
mIdConfidenceMapBuffer ( NULL ),
mIdConfidenceMapShaderResourceView( NULL ),
mTileServer ( tileServer ),
mConstParameters ( constParameters ),
mIsTiledDatasetLoaded ( false ),
mIsSegmentationLoaded ( false )
{
mD3D11Device = d3d11Device;
mD3D11Device->AddRef();
mD3D11DeviceContext = d3d11DeviceContext;
mD3D11DeviceContext->AddRef();
}
TileManager::~TileManager()
{
mD3D11DeviceContext->Release();
mD3D11DeviceContext = NULL;
mD3D11Device->Release();
mD3D11Device = NULL;
}
void TileManager::LoadTiledDataset( TiledDatasetDescription& tiledDatasetDescription )
{
switch ( tiledDatasetDescription.tiledVolumeDescriptions.Get( "SourceMap" ).dxgiFormat )
{
case DXGI_FORMAT_R8_UNORM:
LoadTiledDatasetInternal< unsigned char >( tiledDatasetDescription );
break;
default:
RELEASE_ASSERT( 0 );
break;
}
}
void TileManager::UnloadTiledDataset()
{
UnloadTiledDatasetInternal();
}
bool TileManager::IsTiledDatasetLoaded()
{
return mIsTiledDatasetLoaded;
}
void TileManager::LoadSegmentation( TiledDatasetDescription& tiledDatasetDescription )
{
switch ( tiledDatasetDescription.tiledVolumeDescriptions.Get( "SourceMap" ).dxgiFormat )
{
case DXGI_FORMAT_R8_UNORM:
LoadSegmentationInternal< unsigned char >( tiledDatasetDescription );
break;
default:
RELEASE_ASSERT( 0 );
break;
}
}
void TileManager::UnloadSegmentation()
{
UnloadSegmentationInternal();
}
bool TileManager::IsSegmentationLoaded()
{
return mIsSegmentationLoaded;
}
void TileManager::SaveSegmentation()
{
mTileServer->SaveSegmentation();
}
void TileManager::SaveSegmentationAs( std::string savePath )
{
mTileServer->SaveSegmentationAs( savePath );
}
void TileManager::AutosaveSegmentation()
{
mTileServer->AutosaveSegmentation();
}
void TileManager::DeleteTempFiles()
{
mTileServer->DeleteTempFiles();
}
void TileManager::LoadOverTile( const TiledDatasetView& tiledDatasetView )
{
//
// Find a single tile that will completely cover the current view
//
MojoInt4 tileIndex = GetTileIndexCoveringView( tiledDatasetView );
int cacheIndex = mTileCachePageTable( tileIndex.w, tileIndex.z, tileIndex.y, tileIndex.x );
//
// all cache entries can be discarded unless they are in the current z window
//
for ( int cacheIndex = 0; cacheIndex < mDeviceTileCacheSize; cacheIndex++ )
{
if ( mTileCache[ cacheIndex ].indexTileSpace.z == tileIndex.z )
{
mTileCache[ cacheIndex ].keepState = TileCacheEntryKeepState_MustKeep;
mTileCache[ cacheIndex ].active = true;
}
else
{
mTileCache[ cacheIndex ].keepState = TileCacheEntryKeepState_CanDiscard;
mTileCache[ cacheIndex ].active = false;
}
}
//
// if the tile is not loaded...
//
if ( cacheIndex == TILE_CACHE_BAD_INDEX )
{
//Core::Printf( "Loading single tile at: w=", tileIndex.w, ", z=", tileIndex.z, ", y=", tileIndex.y, ", x=", tileIndex.x, "." );
//
// Overwrite the tile at mTileCacheSearchStart
//
int newCacheIndex = mTileCacheSearchStart;
mTileCacheSearchStart = ( newCacheIndex + 1 ) % mDeviceTileCacheSize;
//RELEASE_ASSERT( !mTileCache[ newCacheIndex ]->active );
//Core::Printf( "Replacing tile ", newCacheIndex, " in the device cache.");
//
// get the new cache entry's index in tile space
//
MojoInt4 indexTileSpace = mTileCache[ newCacheIndex ].indexTileSpace;
MojoInt4 tempTileIndex = MojoInt4( indexTileSpace.x, indexTileSpace.y, indexTileSpace.z, indexTileSpace.w );
//
// if the new cache entry refers to a tile that is already loaded...
//
if ( tempTileIndex.x != TILE_CACHE_PAGE_TABLE_BAD_INDEX ||
tempTileIndex.y != TILE_CACHE_PAGE_TABLE_BAD_INDEX ||
tempTileIndex.z != TILE_CACHE_PAGE_TABLE_BAD_INDEX ||
tempTileIndex.w != TILE_CACHE_PAGE_TABLE_BAD_INDEX )
{
//
// mark the tile as not being loaded any more
//
mTileCachePageTable( tempTileIndex.w, tempTileIndex.z, tempTileIndex.y, tempTileIndex.x ) = TILE_CACHE_BAD_INDEX;
}
//
// load image data into host memory
//
Core::HashMap< std::string, Core::VolumeDescription > volumeDescriptions = mTileServer->LoadTile( tileIndex );
//
// load the new data into into device memory for the new cache entry
//
mTileCache[ newCacheIndex ].d3d11CudaTextures.Get( "SourceMap" )->Update( volumeDescriptions.Get( "SourceMap" ) );
if ( IsSegmentationLoaded() )
{
if ( volumeDescriptions.GetHashMap().find( "IdMap" ) == volumeDescriptions.GetHashMap().end() )
{
Core::Printf( "Warning: Segmentation is loaded, but volume description is missing an IdMap." );
}
else
{
mTileCache[ newCacheIndex ].d3d11CudaTextures.Get( "IdMap" )->Update( volumeDescriptions.Get( "IdMap" ) );
//TiledVolumeDescription tiledVolumeDescription = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "IdMap" );
//int idNumVoxelsPerTile = tiledVolumeDescription.numVoxelsPerTileX * tiledVolumeDescription.numVoxelsPerTileY * tiledVolumeDescription.numVoxelsPerTileZ;
//Core::Thrust::MemcpyHostToDevice( mTileCache[ newCacheIndex ].deviceVectors.Get< int >( "IdMap" ), volumeDescriptions.Get( "IdMap" ).data, idNumVoxelsPerTile );
}
if ( volumeDescriptions.GetHashMap().find( "OverlayMap" ) != volumeDescriptions.GetHashMap().end() )
{
mTileCache[ newCacheIndex ].d3d11CudaTextures.Get( "OverlayMap" )->Update( volumeDescriptions.Get( "OverlayMap" ) );
//TiledVolumeDescription tiledVolumeDescription = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "OverlayMap" );
//int idNumVoxelsPerTile = tiledVolumeDescription.numVoxelsPerTileX * tiledVolumeDescription.numVoxelsPerTileY * tiledVolumeDescription.numVoxelsPerTileZ;
//Core::Thrust::MemcpyHostToDevice( mTileCache[ newCacheIndex ].deviceVectors.Get< int >( "OverlayMap" ), volumeDescriptions.Get( "OverlayMap" ).data, idNumVoxelsPerTile );
}
}
//
// unload image data from from host memory
//
mTileServer->UnloadTile( tileIndex );
//
// update tile cache state for the new cache entry
//
MojoFloat3 extentDataSpace =
MojoFloat3(
mConstParameters.Get< int >( "TILE_SIZE_X" ) * (float)pow( 2.0, tileIndex.w ),
mConstParameters.Get< int >( "TILE_SIZE_Y" ) * (float)pow( 2.0, tileIndex.w ),
mConstParameters.Get< int >( "TILE_SIZE_Z" ) * (float)pow( 2.0, tileIndex.w ) );
MojoFloat3 centerDataSpace =
MojoFloat3(
( tileIndex.x + 0.5f ) * extentDataSpace.x,
( tileIndex.y + 0.5f ) * extentDataSpace.y,
( tileIndex.z + 0.5f ) * extentDataSpace.z );
mTileCache[ newCacheIndex ].keepState = TileCacheEntryKeepState_MustKeep;
mTileCache[ newCacheIndex ].active = true;
mTileCache[ newCacheIndex ].indexTileSpace = tileIndex;
mTileCache[ newCacheIndex ].centerDataSpace = centerDataSpace;
mTileCache[ newCacheIndex ].extentDataSpace = extentDataSpace;
//
// mark the new location in tile space as being loaded into the cache
//
RELEASE_ASSERT( mTileCachePageTable( tileIndex.w, tileIndex.z, tileIndex.y, tileIndex.x ) == TILE_CACHE_BAD_INDEX );
mTileCachePageTable( tileIndex.w, tileIndex.z, tileIndex.y, tileIndex.x ) = newCacheIndex;
}
}
void TileManager::LoadTiles( const TiledDatasetView& tiledDatasetView )
{
//
// assume that all cache entries can be discarded unless explicitly marked otherwise
//
for ( int cacheIndex = 0; cacheIndex < mDeviceTileCacheSize; cacheIndex++ )
{
mTileCache[ cacheIndex ].keepState = TileCacheEntryKeepState_CanDiscard;
mTileCache[ cacheIndex ].active = false;
}
std::list< MojoInt4 > tileIndices = GetTileIndicesIntersectedByView( tiledDatasetView );
//
// explicitly mark all previously loaded cache entries that intersect the current view as cache entries to keep
//
MOJO_FOR_EACH( MojoInt4 tileIndex, tileIndices )
{
int cacheIndex = mTileCachePageTable( tileIndex.w, tileIndex.z, tileIndex.y, tileIndex.x );
if ( cacheIndex != TILE_CACHE_BAD_INDEX )
{
mTileCache[ cacheIndex ].keepState = TileCacheEntryKeepState_MustKeep;
mTileCache[ cacheIndex ].active = true;
}
}
//
// for each tile that intersects the current view but is not loaded, load it and overwrite a cache entry that can be discarded
//
MOJO_FOR_EACH( MojoInt4 tileIndex, tileIndices )
{
int cacheIndex = mTileCachePageTable( tileIndex.w, tileIndex.z, tileIndex.y, tileIndex.x );
//
// if the tile is not loaded...
//
if ( cacheIndex == TILE_CACHE_BAD_INDEX )
{
//
// find another cache entry to store the tile
//
int newCacheIndex = mTileCacheSearchStart;
int lastCacheIndex = ( mDeviceTileCacheSize + mTileCacheSearchStart - 1 ) % mDeviceTileCacheSize;
for (; mTileCache[ newCacheIndex ].keepState != TileCacheEntryKeepState_CanDiscard; newCacheIndex = ( newCacheIndex + 1 ) % mDeviceTileCacheSize )
{
//
// check if we have run out of tiles
//
//RELEASE_ASSERT ( newCacheIndex != lastCacheIndex );
}
mTileCacheSearchStart = ( newCacheIndex + 1 ) % mDeviceTileCacheSize;
//RELEASE_ASSERT( !mTileCache[ newCacheIndex ]->active );
//Core::Printf( "Replacing tile ", newCacheIndex, " in the device cache.");
//
// get the new cache entry's index in tile space
//
MojoInt4 indexTileSpace = mTileCache[ newCacheIndex ].indexTileSpace;
MojoInt4 tempTileIndex = MojoInt4( indexTileSpace.x, indexTileSpace.y, indexTileSpace.z, indexTileSpace.w );
//
// if the new cache entry refers to a tile that is already loaded...
//
if ( tempTileIndex.x != TILE_CACHE_PAGE_TABLE_BAD_INDEX ||
tempTileIndex.y != TILE_CACHE_PAGE_TABLE_BAD_INDEX ||
tempTileIndex.z != TILE_CACHE_PAGE_TABLE_BAD_INDEX ||
tempTileIndex.w != TILE_CACHE_PAGE_TABLE_BAD_INDEX )
{
//
// mark the tile as not being loaded any more
//
mTileCachePageTable( tempTileIndex.w, tempTileIndex.z, tempTileIndex.y, tempTileIndex.x ) = TILE_CACHE_BAD_INDEX;
}
//
// load image data into host memory
//
Core::HashMap< std::string, Core::VolumeDescription > volumeDescriptions = mTileServer->LoadTile( tileIndex );
//
// load the new data into into device memory for the new cache entry
//
mTileCache[ newCacheIndex ].d3d11CudaTextures.Get( "SourceMap" )->Update( volumeDescriptions.Get( "SourceMap" ) );
if ( IsSegmentationLoaded() )
{
if ( volumeDescriptions.GetHashMap().find( "IdMap" ) == volumeDescriptions.GetHashMap().end() )
{
Core::Printf( "Warning: Segmentation is loaded, but volume description is missing an IdMap." );
}
else
{
mTileCache[ newCacheIndex ].d3d11CudaTextures.Get( "IdMap" )->Update( volumeDescriptions.Get( "IdMap" ) );
//TiledVolumeDescription tiledVolumeDescription = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "IdMap" );
//int idNumVoxelsPerTile = tiledVolumeDescription.numVoxelsPerTileX * tiledVolumeDescription.numVoxelsPerTileY * tiledVolumeDescription.numVoxelsPerTileZ;
//Core::Thrust::MemcpyHostToDevice( mTileCache[ newCacheIndex ].deviceVectors.Get< int >( "IdMap" ), volumeDescriptions.Get( "IdMap" ).data, idNumVoxelsPerTile );
}
if ( volumeDescriptions.GetHashMap().find( "OverlayMap" ) != volumeDescriptions.GetHashMap().end() )
{
mTileCache[ newCacheIndex ].d3d11CudaTextures.Get( "OverlayMap" )->Update( volumeDescriptions.Get( "OverlayMap" ) );
//TiledVolumeDescription tiledVolumeDescription = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "OverlayMap" );
//int idNumVoxelsPerTile = tiledVolumeDescription.numVoxelsPerTileX * tiledVolumeDescription.numVoxelsPerTileY * tiledVolumeDescription.numVoxelsPerTileZ;
//Core::Thrust::MemcpyHostToDevice( mTileCache[ newCacheIndex ].deviceVectors.Get< int >( "OverlayMap" ), volumeDescriptions.Get( "OverlayMap" ).data, idNumVoxelsPerTile );
}
}
//
// unload image data from from host memory
//
mTileServer->UnloadTile( tileIndex );
//
// update tile cache state for the new cache entry
//
MojoFloat3 extentDataSpace =
MojoFloat3(
mConstParameters.Get< int >( "TILE_SIZE_X" ) * (float)pow( 2.0, tileIndex.w ),
mConstParameters.Get< int >( "TILE_SIZE_Y" ) * (float)pow( 2.0, tileIndex.w ),
mConstParameters.Get< int >( "TILE_SIZE_Z" ) * (float)pow( 2.0, tileIndex.w ) );
MojoFloat3 centerDataSpace =
MojoFloat3(
( tileIndex.x + 0.5f ) * extentDataSpace.x,
( tileIndex.y + 0.5f ) * extentDataSpace.y,
( tileIndex.z + 0.5f ) * extentDataSpace.z );
mTileCache[ newCacheIndex ].keepState = TileCacheEntryKeepState_MustKeep;
mTileCache[ newCacheIndex ].active = true;
mTileCache[ newCacheIndex ].indexTileSpace = tileIndex;
mTileCache[ newCacheIndex ].centerDataSpace = centerDataSpace;
mTileCache[ newCacheIndex ].extentDataSpace = extentDataSpace;
//
// mark the new location in tile space as being loaded into the cache
//
RELEASE_ASSERT( mTileCachePageTable( tileIndex.w, tileIndex.z, tileIndex.y, tileIndex.x ) == TILE_CACHE_BAD_INDEX );
mTileCachePageTable( tileIndex.w, tileIndex.z, tileIndex.y, tileIndex.x ) = newCacheIndex;
}
}
}
std::vector< TileCacheEntry >& TileManager::GetTileCache()
{
return mTileCache;
}
ID3D11ShaderResourceView* TileManager::GetIdColorMap()
{
return mIdColorMapShaderResourceView;
}
ID3D11ShaderResourceView* TileManager::GetLabelIdMap()
{
return mLabelIdMapShaderResourceView;
}
ID3D11ShaderResourceView* TileManager::GetIdConfidenceMap()
{
return mIdConfidenceMapShaderResourceView;
}
unsigned int TileManager::GetSegmentationLabelId( const TiledDatasetView& tiledDatasetView, MojoFloat3 pDataSpace )
{
MojoInt3 zoomLevel = GetZoomLevel( tiledDatasetView );
MojoFloat4 pointTileSpace;
MojoInt4 tileIndex;
unsigned int segmentId = 0;
if ( mIsSegmentationLoaded )
{
GetIndexTileSpace( zoomLevel, pDataSpace, pointTileSpace, tileIndex );
TiledVolumeDescription tiledVolumeDescription = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "IdMap" );
MojoInt3 numVoxels = MojoInt3( tiledVolumeDescription.numVoxelsX, tiledVolumeDescription.numVoxelsY, tiledVolumeDescription.numVoxelsZ );
MojoInt3 numVoxelsPerTile = tiledVolumeDescription.numVoxelsPerTile();
MojoInt3 pVoxelSpace = GetIndexVoxelSpace( pointTileSpace, numVoxelsPerTile );
//
// Check for overflow
//
if ( pVoxelSpace.x >= 0 && pVoxelSpace.x < numVoxels.x &&
pVoxelSpace.y >= 0 && pVoxelSpace.y < numVoxels.y &&
pVoxelSpace.z >= 0 && pVoxelSpace.z < numVoxels.z )
{
MojoInt3 offsetVoxelSpace = GetOffsetVoxelSpace( pointTileSpace, tileIndex, numVoxelsPerTile );
int offsetVoxelSpace1D = Core::Index3DToIndex1D( offsetVoxelSpace, numVoxelsPerTile );
Core::HashMap< std::string, Core::VolumeDescription > thisTile = mTileServer->LoadTile( tileIndex );
segmentId = mTileServer->GetSegmentInfoManager()->GetIdForLabel( ( (int*) thisTile.Get( "IdMap" ).data )[ offsetVoxelSpace1D ] );
mTileServer->UnloadTile( tileIndex );
}
}
return segmentId;
}
void TileManager::SortSegmentInfoById( bool reverse )
{
mTileServer->SortSegmentInfoById( reverse );
}
void TileManager::SortSegmentInfoByName( bool reverse )
{
mTileServer->SortSegmentInfoByName( reverse );
}
void TileManager::SortSegmentInfoBySize( bool reverse )
{
mTileServer->SortSegmentInfoBySize( reverse );
}
void TileManager::SortSegmentInfoByConfidence( bool reverse )
{
mTileServer->SortSegmentInfoByConfidence( reverse );
}
void TileManager::RemapSegmentLabel( unsigned int fromSegId, unsigned int toSegId )
{
Core::Printf( "From ", fromSegId, " before -> ", (*mLabelIdMap)( fromSegId ), "." );
Core::Printf( "To ", toSegId, " before -> ", (*mLabelIdMap)( toSegId ), "." );
std::set< unsigned int > fromSegIds;
fromSegIds.insert( fromSegId );
mTileServer->RemapSegmentLabels( fromSegIds, toSegId );
Core::Printf( "From ", fromSegId, " after -> ", (*mLabelIdMap)( fromSegId ), "." );
Core::Printf( "To ", toSegId, " after -> ", (*mLabelIdMap)( toSegId ), "." );
UpdateLabelIdMap( fromSegId );
}
void TileManager::UpdateLabelIdMap( unsigned int fromSegId )
{
//
// Update label id map shader buffer
//
unsigned int labelIdMapEntry = ( (*mLabelIdMap)( fromSegId ) );
D3D11_BOX updateBox;
ZeroMemory( &updateBox, sizeof( D3D11_BOX ) );
updateBox.left = fromSegId * sizeof( unsigned int );
updateBox.top = 0;
updateBox.front = 0;
updateBox.right = ( fromSegId + 1 ) * sizeof( unsigned int );
updateBox.bottom = 1;
updateBox.back = 1;
mD3D11DeviceContext->UpdateSubresource(
mLabelIdMapBuffer,
0,
&updateBox,
&labelIdMapEntry,
(UINT) mLabelIdMap->shape( 0 ) * sizeof( unsigned int ),
(UINT) mLabelIdMap->shape( 0 ) * sizeof( unsigned int ) );
}
void TileManager::LockSegmentLabel( unsigned int segId )
{
mTileServer->LockSegmentLabel( segId );
//
// Update confidence map shader buffer
//
unsigned char idConfidenceMapEntry = ( (*mIdConfidenceMap)( segId ) );
D3D11_BOX updateBox;
ZeroMemory( &updateBox, sizeof( D3D11_BOX ) );
updateBox.left = segId;
updateBox.top = 0;
updateBox.front = 0;
updateBox.right = segId + 1;
updateBox.bottom = 1;
updateBox.back = 1;
mD3D11DeviceContext->UpdateSubresource(
mIdConfidenceMapBuffer,
0,
&updateBox,
&idConfidenceMapEntry,
(UINT) mIdConfidenceMap->shape( 0 ) * sizeof( unsigned char ),
(UINT) mIdConfidenceMap->shape( 0 ) * sizeof( unsigned char ) );
}
void TileManager::UnlockSegmentLabel( unsigned int segId )
{
mTileServer->UnlockSegmentLabel( segId );
//
// Update confidence map shader buffer
//
unsigned char idConfidenceMapEntry = 0;
D3D11_BOX updateBox;
ZeroMemory( &updateBox, sizeof( D3D11_BOX ) );
updateBox.left = segId;
updateBox.top = 0;
updateBox.front = 0;
updateBox.right = segId + 1;
updateBox.bottom = 1;
updateBox.back = 1;
mD3D11DeviceContext->UpdateSubresource(
mIdConfidenceMapBuffer,
0,
&updateBox,
&idConfidenceMapEntry,
(UINT) mIdConfidenceMap->shape( 0 ) * sizeof( unsigned char ),
(UINT) mIdConfidenceMap->shape( 0 ) * sizeof( unsigned char ) );
}
unsigned int TileManager::GetSegmentInfoCount()
{
return mTileServer->GetSegmentInfoCount();
}
unsigned int TileManager::GetSegmentInfoCurrentListLocation( unsigned int segId )
{
return mTileServer->GetSegmentInfoCurrentListLocation( segId );
}
std::list< SegmentInfo > TileManager::GetSegmentInfoRange( int begin, int end )
{
return mTileServer->GetSegmentInfoRange( begin, end );
}
SegmentInfo TileManager::GetSegmentInfo( unsigned int segId )
{
return mTileServer->GetSegmentInfo( segId );
}
MojoInt3 TileManager::GetSegmentationLabelColor( unsigned int segId )
{
if ( mIdColorMap->size() > 0 )
{
int index = segId % mIdColorMap->shape( 0 );
return MojoInt3( (*mIdColorMap)( index, 0 ), (*mIdColorMap)( index, 1 ), (*mIdColorMap)( index, 2 ) );
}
return MojoInt3();
}
std::string TileManager::GetSegmentationLabelColorString( unsigned int segId )
{
if ( mIdColorMap->size() > 0 )
{
int index = segId % mIdColorMap->shape( 0 );
std::ostringstream colorConverter;
colorConverter << std::setfill( '0' ) << std::hex;
colorConverter << std::setw( 1 ) << "#";
colorConverter << std::setw( 2 ) << (int)(*mIdColorMap)( index, 0 );
colorConverter << std::setw( 2 ) << (int)(*mIdColorMap)( index, 1 );
colorConverter << std::setw( 2 ) << (int)(*mIdColorMap)( index, 2 );
return colorConverter.str();
}
return "#000000";
}
MojoInt3 TileManager::GetSegmentCentralTileLocation( unsigned int segId )
{
return mTileServer->GetSegmentCentralTileLocation( segId );
}
MojoInt4 TileManager::GetSegmentZTileBounds( unsigned int segId, int zIndex )
{
return mTileServer->GetSegmentZTileBounds( segId, zIndex );
}
void TileManager::ReplaceSegmentationLabel( unsigned int oldId, unsigned int newId )
{
mTileServer->ReplaceSegmentationLabel( oldId, newId );
ReloadTileCache();
}
void TileManager::ReplaceSegmentationLabelCurrentSlice( unsigned int oldId, unsigned int newId, MojoFloat3 pDataSpace )
{
mTileServer->ReplaceSegmentationLabelCurrentSlice( oldId, newId, pDataSpace );
ReloadTileCache();
}
void TileManager::DrawSplit( MojoFloat3 pointTileSpace, float radius )
{
mTileServer->DrawSplit( pointTileSpace, radius );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::DrawErase( MojoFloat3 pointTileSpace, float radius )
{
mTileServer->DrawErase( pointTileSpace, radius );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::DrawRegionA( MojoFloat3 pointTileSpace, float radius )
{
mTileServer->DrawRegionA( pointTileSpace, radius );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::DrawRegionB( MojoFloat3 pointTileSpace, float radius )
{
mTileServer->DrawRegionB( pointTileSpace, radius );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::AddSplitSource( MojoFloat3 pointTileSpace )
{
mTileServer->AddSplitSource( pointTileSpace );
}
void TileManager::RemoveSplitSource()
{
mTileServer->RemoveSplitSource();
}
void TileManager::ResetSplitState( MojoFloat3 pointTileSpace )
{
mTileServer->ResetSplitState();
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::PrepForSplit( unsigned int segId, MojoFloat3 pointTileSpace )
{
mTileServer->PrepForSplit( segId, pointTileSpace );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::FindBoundaryJoinPoints2D( unsigned int segId, MojoFloat3 pointTileSpace )
{
mTileServer->FindBoundaryJoinPoints2D( segId );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::FindBoundaryWithinRegion2D( unsigned int segId, MojoFloat3 pointTileSpace )
{
mTileServer->FindBoundaryWithinRegion2D( segId );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::FindBoundaryBetweenRegions2D( unsigned int segId, MojoFloat3 pointTileSpace )
{
mTileServer->FindBoundaryBetweenRegions2D( segId );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
int TileManager::CompletePointSplit( unsigned int segId, MojoFloat3 pointTileSpace )
{
int newId = mTileServer->CompletePointSplit( segId, pointTileSpace );
mTileServer->PrepForSplit( segId, pointTileSpace );
ReloadTileCache();
return newId;
}
int TileManager::CompleteDrawSplit( unsigned int segId, MojoFloat3 pointTileSpace, bool join3D, int splitStartZ )
{
int newId = mTileServer->CompleteDrawSplit( segId, pointTileSpace, join3D, splitStartZ );
mTileServer->PrepForSplit( segId, pointTileSpace );
ReloadTileCache();
return newId;
}
void TileManager::RecordSplitState( unsigned int segId, MojoFloat3 pointTileSpace )
{
mTileServer->RecordSplitState( segId, pointTileSpace );
}
void TileManager::PredictSplit( unsigned int segId, MojoFloat3 pointTileSpace, float radius )
{
mTileServer->PredictSplit( segId, pointTileSpace, radius );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::ResetAdjustState( MojoFloat3 pointTileSpace )
{
mTileServer->ResetAdjustState();
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::PrepForAdjust( unsigned int segId, MojoFloat3 pointTileSpace )
{
mTileServer->PrepForAdjust( segId, pointTileSpace );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::CommitAdjustChange( unsigned int segId, MojoFloat3 pointTileSpace )
{
mTileServer->CommitAdjustChange( segId, pointTileSpace );
mTileServer->PrepForAdjust( segId, pointTileSpace );
ReloadTileCache();
}
void TileManager::ResetDrawMergeState( MojoFloat3 pointTileSpace )
{
mTileServer->ResetDrawMergeState();
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
void TileManager::PrepForDrawMerge( MojoFloat3 pointTileSpace )
{
mTileServer->PrepForDrawMerge( pointTileSpace );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
}
unsigned int TileManager::CommitDrawMerge( MojoFloat3 pointTileSpace )
{
std::set< unsigned int > remapIds = mTileServer->GetDrawMergeIds( pointTileSpace );
unsigned int newId = 0;
if ( remapIds.size() == 1 )
{
newId = *remapIds.begin();
mTileServer->ResetDrawMergeState();
}
else if ( remapIds.size() > 1 )
{
newId = mTileServer->CommitDrawMerge( remapIds, pointTileSpace );
for ( std::set< unsigned int >::iterator updateIt = remapIds.begin(); updateIt != remapIds.end(); ++updateIt )
{
UpdateLabelIdMap( *updateIt );
}
}
mTileServer->PrepForDrawMerge( pointTileSpace );
ReloadTileCacheOverlayMapOnly( (int)pointTileSpace.z );
return newId;
}
unsigned int TileManager::CommitDrawMergeCurrentSlice( MojoFloat3 pointTileSpace )
{
unsigned int newId = mTileServer->CommitDrawMergeCurrentSlice( pointTileSpace );
mTileServer->PrepForDrawMerge( pointTileSpace );
ReloadTileCache();
return newId;
}
unsigned int TileManager::CommitDrawMergeCurrentConnectedComponent( MojoFloat3 pointTileSpace )
{
unsigned int newId = mTileServer->CommitDrawMergeCurrentConnectedComponent( pointTileSpace );
mTileServer->PrepForDrawMerge( pointTileSpace );
ReloadTileCache();
return newId;
}
void TileManager::ReplaceSegmentationLabelCurrentConnectedComponent( unsigned int oldId, unsigned int newId, MojoFloat3 pDataSpace )
{
mTileServer->ReplaceSegmentationLabelCurrentConnectedComponent( oldId, newId, pDataSpace );
ReloadTileCache();
}
unsigned int TileManager::GetNewId()
{
return mTileServer->GetNewId();
}
float TileManager::GetCurrentOperationProgress()
{
return mTileServer->GetCurrentOperationProgress();
}
void TileManager::UndoChange()
{
std::list< unsigned int > remappedIds = mTileServer->UndoChange();
for ( std::list< unsigned int >::iterator updateIt = remappedIds.begin(); updateIt != remappedIds.end(); ++updateIt )
{
UpdateLabelIdMap( *updateIt );
}
ReloadTileCache();
}
void TileManager::RedoChange()
{
std::list< unsigned int > remappedIds = mTileServer->RedoChange();
for ( std::list< unsigned int >::iterator updateIt = remappedIds.begin(); updateIt != remappedIds.end(); ++updateIt )
{
UpdateLabelIdMap( *updateIt );
}
ReloadTileCache();
}
void TileManager::TempSaveAndClearFileSystemTileCache()
{
mTileServer->TempSaveAndClearFileSystemTileCache();
}
void TileManager::ClearFileSystemTileCache()
{
mTileServer->ClearFileSystemTileCache();
}
void TileManager::UnloadTiledDatasetInternal()
{
if ( mIsSegmentationLoaded )
{
UnloadSegmentationInternal();
}
if ( mIsTiledDatasetLoaded )
{
//
// reset all state
//
mIsTiledDatasetLoaded = false;
mTiledDatasetDescription = TiledDatasetDescription();
//
// reset page table
//
mTileCachePageTable = marray::Marray< int >( 0 );
//
// output memory stats to the console
//
//size_t freeMemory, totalMemory;
//CUresult memInfoResult;
//memInfoResult = cuMemGetInfo( &freeMemory, &totalMemory );
//RELEASE_ASSERT( memInfoResult == CUDA_SUCCESS );
IDXGIDevice * pDXGIDevice;
mD3D11Device->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice);
IDXGIAdapter * pDXGIAdapter;
pDXGIDevice->GetAdapter(&pDXGIAdapter);
DXGI_ADAPTER_DESC adapterDesc;
pDXGIAdapter->GetDesc(&adapterDesc);
Core::Printf( "\nUnloading tiled dataset...\n" );
//Core::Printf( "\n Before freeing GPU memory:\n",
// " Total memory: ", (unsigned int) adapterDesc.DedicatedVideoMemory / ( 1024 * 1024 ), " MBytes.\n" );
//
// delete textures in the tile cache
//
for ( int i = 0; i < mDeviceTileCacheSize; i++ )
{
//mTileCache[ i ].deviceVectors.Clear();
delete mTileCache[ i ].d3d11CudaTextures.Get( "SourceMap" );
delete mTileCache[ i ].d3d11CudaTextures.Get( "IdMap" );
delete mTileCache[ i ].d3d11CudaTextures.Get( "OverlayMap" );
mTileCache[ i ].d3d11CudaTextures.GetHashMap().clear();
}
//
// output memory stats to the console
//
//memInfoResult = cuMemGetInfo( &freeMemory, &totalMemory );
//RELEASE_ASSERT( memInfoResult == CUDA_SUCCESS );
pDXGIAdapter->GetDesc(&adapterDesc);
//Core::Printf( " After freeing GPU memory:\n",
// " Total memory: ", (unsigned int) adapterDesc.DedicatedVideoMemory / ( 1024 * 1024 ), " MBytes.\n" );
}
}
void TileManager::UnloadSegmentationInternal()
{
if ( mIsSegmentationLoaded )
{
//
// reset segmentation state
//
mIsSegmentationLoaded = false;
//
// output memory stats to the console
//
//size_t freeMemory, totalMemory;
//CUresult memInfoResult;
//memInfoResult = cuMemGetInfo( &freeMemory, &totalMemory );
//RELEASE_ASSERT( memInfoResult == CUDA_SUCCESS );
IDXGIDevice * pDXGIDevice;
mD3D11Device->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice);
IDXGIAdapter * pDXGIAdapter;
pDXGIDevice->GetAdapter(&pDXGIAdapter);
DXGI_ADAPTER_DESC adapterDesc;
pDXGIAdapter->GetDesc(&adapterDesc);
Core::Printf( "\nUnloading segmentation...\n" );
//Core::Printf( "\n Before freeing GPU memory:\n",
// " Total memory: ", (unsigned int) adapterDesc.DedicatedVideoMemory / ( 1024 * 1024 ), " MBytes.\n" );
//
// release id color map
//
mIdColorMapShaderResourceView->Release();
mIdColorMapShaderResourceView = NULL;
mIdColorMapBuffer->Release();
mIdColorMapBuffer = NULL;
//
// release label id map
//
mLabelIdMapShaderResourceView->Release();
mLabelIdMapShaderResourceView = NULL;
mLabelIdMapBuffer->Release();
mLabelIdMapBuffer = NULL;
//
// release id lock map
//
mIdConfidenceMapShaderResourceView->Release();
mIdConfidenceMapShaderResourceView = NULL;
mIdConfidenceMapBuffer->Release();
mIdConfidenceMapBuffer = NULL;
//
// output memory stats to the console
//
//memInfoResult = cuMemGetInfo( &freeMemory, &totalMemory );
//RELEASE_ASSERT( memInfoResult == CUDA_SUCCESS );
pDXGIAdapter->GetDesc(&adapterDesc);
//Core::Printf( " After freeing GPU memory:\n",
// " Total memory: ", (unsigned int) adapterDesc.DedicatedVideoMemory / ( 1024 * 1024 ), " MBytes.\n" );
}
}
MojoInt3 TileManager::GetZoomLevel( const TiledDatasetView& tiledDatasetView )
{
//
// figure out what the current zoom level is
//
TiledVolumeDescription tiledvolumeDescription = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "SourceMap" );
double expZoomLevelXY = ( tiledDatasetView.extentDataSpace.x * tiledvolumeDescription.numVoxelsPerTileX ) / ( tiledDatasetView.widthNumPixels );
int zoomLevelXY = (int)floor( std::min( (double)( tiledvolumeDescription.numTilesW - 1 ), std::max( 0.0, ( log( expZoomLevelXY ) / log( 2.0 ) ) ) ) );
int zoomLevelZ = 0;
return MojoInt3( zoomLevelXY, zoomLevelXY, zoomLevelZ );
}
std::list< MojoInt4 > TileManager::GetTileIndicesIntersectedByView( const TiledDatasetView& tiledDatasetView )
{
std::list< MojoInt4 > tilesIntersectedByCamera;
//
// figure out what the current zoom level is
//
MojoInt3 zoomLevel = GetZoomLevel( tiledDatasetView );
int zoomLevelXY = std::min( zoomLevel.x, zoomLevel.y );
int zoomLevelZ = zoomLevel.z;
//
// figure out how many tiles there are at the current zoom level
//
MojoInt4 numTiles = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "SourceMap" ).numTiles();
int numTilesForZoomLevelX = (int)ceil( numTiles.x / pow( 2.0, zoomLevelXY ) );
int numTilesForZoomLevelY = (int)ceil( numTiles.y / pow( 2.0, zoomLevelXY ) );
int numTilesForZoomLevelZ = (int)ceil( numTiles.z / pow( 2.0, zoomLevelZ ) );
//
// figure out the tile size (in data space) at the current zoom level
//
int tileSizeDataSpaceX = (int)( mConstParameters.Get< int >( "TILE_SIZE_X" ) * pow( 2.0, zoomLevelXY ) );
int tileSizeDataSpaceY = (int)( mConstParameters.Get< int >( "TILE_SIZE_Y" ) * pow( 2.0, zoomLevelXY ) );
int tileSizeDataSpaceZ = (int)( mConstParameters.Get< int >( "TILE_SIZE_Z" ) * pow( 2.0, zoomLevelZ ) );
//
// compute the top-left-front and bottom-right-back points (in data space) that are currently in view
//
MojoFloat3 topLeftFrontDataSpace =
MojoFloat3(
tiledDatasetView.centerDataSpace.x - ( tiledDatasetView.extentDataSpace.x / 2 ),
tiledDatasetView.centerDataSpace.y - ( tiledDatasetView.extentDataSpace.y / 2 ),
tiledDatasetView.centerDataSpace.z - ( tiledDatasetView.extentDataSpace.z / 2 ) );
MojoFloat3 bottomRightBackDataSpace =
MojoFloat3(
tiledDatasetView.centerDataSpace.x + ( tiledDatasetView.extentDataSpace.x / 2 ),
tiledDatasetView.centerDataSpace.y + ( tiledDatasetView.extentDataSpace.y / 2 ),
tiledDatasetView.centerDataSpace.z + ( tiledDatasetView.extentDataSpace.z / 2 ) );
//
// compute the tile space indices for the top-left-front and bottom-right-back points
//
MojoInt3 topLeftFrontTileIndex =
MojoInt3(
(int)floor( topLeftFrontDataSpace.x / tileSizeDataSpaceX ),
(int)floor( topLeftFrontDataSpace.y / tileSizeDataSpaceY ),
(int)floor( topLeftFrontDataSpace.z / tileSizeDataSpaceZ ) );
MojoInt3 bottomRightBackTileIndex =
MojoInt3(
(int)floor( bottomRightBackDataSpace.x / tileSizeDataSpaceX ),
(int)floor( bottomRightBackDataSpace.y / tileSizeDataSpaceY ),
(int)floor( bottomRightBackDataSpace.z / tileSizeDataSpaceZ ) );
//
// clip the tiles to the appropriate tile space borders
//
int minX = std::max( 0, topLeftFrontTileIndex.x );
int maxX = std::min( numTilesForZoomLevelX - 1, bottomRightBackTileIndex.x );
int minY = std::max( 0, topLeftFrontTileIndex.y );
int maxY = std::min( numTilesForZoomLevelY - 1, bottomRightBackTileIndex.y );
int minZ = std::max( 0, topLeftFrontTileIndex.z );
int maxZ = std::min( numTilesForZoomLevelZ - 1, bottomRightBackTileIndex.z );
for ( int z = minZ; z <= maxZ; z++ )
for ( int y = minY; y <= maxY; y++ )
for ( int x = minX; x <= maxX; x++ )
tilesIntersectedByCamera.push_back( MojoInt4( x, y, z, zoomLevelXY ) );
return tilesIntersectedByCamera;
}
MojoInt4 TileManager::GetTileIndexCoveringView( const TiledDatasetView& tiledDatasetView )
{
MojoInt4 tileCoveringView;
//
// figure out what the current zoom level is
//
MojoInt3 zoomLevel = GetZoomLevel( tiledDatasetView );
int nextZoomLevelXY = std::min( zoomLevel.x, zoomLevel.y );
int zoomLevelZ = zoomLevel.z;
int minX = 0;
int maxX = 1;
int minY = 0;
int maxY = 1;
int minZ = 0;
int maxZ = 1;
int zoomLevelXY = 0;
MojoInt4 numTiles = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "SourceMap" ).numTiles();
//
// Zoom out until there is only one tile visible
//
while ( minX < maxX || minY < maxY || minZ < maxZ )
{
zoomLevelXY = nextZoomLevelXY;
if ( zoomLevelXY >= numTiles.w - 1 )
{
zoomLevelXY = numTiles.w - 1;
minX = 0;
minY = 0;
minZ = (int)tiledDatasetView.centerDataSpace.z;
break;
}
//
// figure out how many tiles there are at the current zoom level
//
int numTilesForZoomLevelX = (int)ceil( numTiles.x / pow( 2.0, zoomLevelXY ) );
int numTilesForZoomLevelY = (int)ceil( numTiles.y / pow( 2.0, zoomLevelXY ) );
int numTilesForZoomLevelZ = (int)ceil( numTiles.z / pow( 2.0, zoomLevelZ ) );
//
// figure out the tile size (in data space) at the current zoom level
//
int tileSizeDataSpaceX = (int)( mConstParameters.Get< int >( "TILE_SIZE_X" ) * pow( 2.0, zoomLevelXY ) );
int tileSizeDataSpaceY = (int)( mConstParameters.Get< int >( "TILE_SIZE_Y" ) * pow( 2.0, zoomLevelXY ) );
int tileSizeDataSpaceZ = (int)( mConstParameters.Get< int >( "TILE_SIZE_Z" ) * pow( 2.0, zoomLevelZ ) );
//
// compute the top-left-front and bottom-right-back points (in data space) that are currently in view
//
MojoFloat3 topLeftFrontDataSpace =
MojoFloat3(
tiledDatasetView.centerDataSpace.x - ( tiledDatasetView.extentDataSpace.x / 2 ),
tiledDatasetView.centerDataSpace.y - ( tiledDatasetView.extentDataSpace.y / 2 ),
tiledDatasetView.centerDataSpace.z - ( tiledDatasetView.extentDataSpace.z / 2 ) );
MojoFloat3 bottomRightBackDataSpace =
MojoFloat3(
tiledDatasetView.centerDataSpace.x + ( tiledDatasetView.extentDataSpace.x / 2 ),
tiledDatasetView.centerDataSpace.y + ( tiledDatasetView.extentDataSpace.y / 2 ),
tiledDatasetView.centerDataSpace.z + ( tiledDatasetView.extentDataSpace.z / 2 ) );
//
// compute the tile space indices for the top-left-front and bottom-right-back points
//
MojoInt3 topLeftFrontTileIndex =
MojoInt3(
(int)floor( topLeftFrontDataSpace.x / tileSizeDataSpaceX ),
(int)floor( topLeftFrontDataSpace.y / tileSizeDataSpaceY ),
(int)floor( topLeftFrontDataSpace.z / tileSizeDataSpaceZ ) );
MojoInt3 bottomRightBackTileIndex =
MojoInt3(
(int)floor( bottomRightBackDataSpace.x / tileSizeDataSpaceX ),
(int)floor( bottomRightBackDataSpace.y / tileSizeDataSpaceY ),
(int)floor( bottomRightBackDataSpace.z / tileSizeDataSpaceZ ) );
//
// clip the tiles to the appropriate tile space borders
//
minX = std::max( 0, topLeftFrontTileIndex.x );
maxX = std::min( numTilesForZoomLevelX - 1, bottomRightBackTileIndex.x );
minY = std::max( 0, topLeftFrontTileIndex.y );
maxY = std::min( numTilesForZoomLevelY - 1, bottomRightBackTileIndex.y );
minZ = std::max( 0, topLeftFrontTileIndex.z );
maxZ = std::min( numTilesForZoomLevelZ - 1, bottomRightBackTileIndex.z );
int maxTilesXY = std::max(maxX - minX + 1, maxY - minY + 1);
if ( maxTilesXY > 2 )
{
nextZoomLevelXY = zoomLevelXY + (int) ceil ( log( (double)maxTilesXY ) / log( 2.0 ) );
}
else
{
nextZoomLevelXY = zoomLevelXY + 1;
}
}
return MojoInt4(minX, minY, minZ, zoomLevelXY);
}
void TileManager::GetIndexTileSpace( MojoInt3 zoomLevel, MojoFloat3 pointDataSpace, MojoFloat4& pointTileSpace, MojoInt4& tileIndex )
{
int zoomLevelXY = std::min( zoomLevel.x, zoomLevel.y );
int zoomLevelZ = zoomLevel.z;
//
// figure out the tile size (in data space) at the current zoom level
//
int tileSizeDataSpaceX = (int)( mConstParameters.Get< int >( "TILE_SIZE_X" ) * pow( 2.0, zoomLevelXY ) );
int tileSizeDataSpaceY = (int)( mConstParameters.Get< int >( "TILE_SIZE_Y" ) * pow( 2.0, zoomLevelXY ) );
int tileSizeDataSpaceZ = (int)( mConstParameters.Get< int >( "TILE_SIZE_Z" ) * pow( 2.0, zoomLevelZ ) );
//
// compute the tile space indices for the requested point
//
pointTileSpace =
MojoFloat4(
(float)pointDataSpace.x / tileSizeDataSpaceX,
(float)pointDataSpace.y / tileSizeDataSpaceY,
(float)pointDataSpace.z / tileSizeDataSpaceZ,
(float)zoomLevelXY );
tileIndex =
MojoInt4(
(int)floor( pointTileSpace.x ),
(int)floor( pointTileSpace.y ),
(int)floor( pointTileSpace.z ),
(int)floor( pointTileSpace.w ) );
}
MojoInt3 TileManager::GetIndexVoxelSpace( MojoFloat4 pointTileSpace, MojoInt3 numVoxelsPerTile )
{
//
// compute the index in voxels within the full volume
//
MojoInt3 indexVoxelSpace =
MojoInt3(
(int)floor( pointTileSpace.x * numVoxelsPerTile.x * pow( 2.0, (int)pointTileSpace.w ) ),
(int)floor( pointTileSpace.y * numVoxelsPerTile.y * pow( 2.0, (int)pointTileSpace.w ) ),
(int)floor( pointTileSpace.z * numVoxelsPerTile.z ) );
return indexVoxelSpace;
}
MojoInt3 TileManager::GetOffsetVoxelSpace( MojoFloat4 pointTileSpace, MojoInt4 tileIndex, MojoInt3 numVoxelsPerTile )
{
//
// compute the offset (in data space) within the current tile
//
MojoFloat4 tileIndexMojoFloat4 =
MojoFloat4(
(float)tileIndex.x,
(float)tileIndex.y,
(float)tileIndex.z,
(float)tileIndex.w );
//
// compute the offset in voxels within the current tile
//
MojoInt3 offsetVoxelSpace =
MojoInt3(
(int)floor( ( pointTileSpace.x - tileIndexMojoFloat4.x ) * numVoxelsPerTile.x ),
(int)floor( ( pointTileSpace.y - tileIndexMojoFloat4.y ) * numVoxelsPerTile.y ),
(int)floor( ( pointTileSpace.z - tileIndexMojoFloat4.z ) * numVoxelsPerTile.z ) );
return offsetVoxelSpace;
}
void TileManager::ReloadTileCache()
{
for ( int cacheIndex = 0; cacheIndex < mDeviceTileCacheSize; cacheIndex++ )
{
if ( mTileCache[ cacheIndex ].indexTileSpace.x != TILE_CACHE_PAGE_TABLE_BAD_INDEX &&
mTileCache[ cacheIndex ].indexTileSpace.y != TILE_CACHE_PAGE_TABLE_BAD_INDEX &&
mTileCache[ cacheIndex ].indexTileSpace.z != TILE_CACHE_PAGE_TABLE_BAD_INDEX &&
mTileCache[ cacheIndex ].indexTileSpace.w != TILE_CACHE_PAGE_TABLE_BAD_INDEX )
{
//
// load image data into host memory
//
MojoInt4 tileIndex = MojoInt4 ( mTileCache[ cacheIndex ].indexTileSpace );
Core::HashMap< std::string, Core::VolumeDescription > volumeDescriptions = mTileServer->LoadTile( tileIndex );
//
// load the new data into into device memory for the new cache entry
//
mTileCache[ cacheIndex ].d3d11CudaTextures.Get( "SourceMap" )->Update( volumeDescriptions.Get( "SourceMap" ) );
if ( mIsSegmentationLoaded )
{
if ( volumeDescriptions.GetHashMap().find( "IdMap" ) != volumeDescriptions.GetHashMap().end() )
{
mTileCache[ cacheIndex ].d3d11CudaTextures.Get( "IdMap" )->Update( volumeDescriptions.Get( "IdMap" ) );
//MojoInt3 volShape = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "IdMap" ).numVoxelsPerTile();
//int idNumVoxelsPerTile = volShape.x * volShape.y * volShape.z;
//Core::Thrust::MemcpyHostToDevice( mTileCache[ cacheIndex ].deviceVectors.Get< int >( "IdMap" ), volumeDescriptions.Get( "IdMap" ).data, idNumVoxelsPerTile );
}
if ( volumeDescriptions.GetHashMap().find( "OverlayMap" ) != volumeDescriptions.GetHashMap().end() )
{
mTileCache[ cacheIndex ].d3d11CudaTextures.Get( "OverlayMap" )->Update( volumeDescriptions.Get( "OverlayMap" ) );
//MojoInt3 volShape = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "OverlayMap" ).numVoxelsPerTile();
//int idNumVoxelsPerTile = volShape.x * volShape.y * volShape.z;
//Core::Thrust::MemcpyHostToDevice( mTileCache[ cacheIndex ].deviceVectors.Get< int >( "OverlayMap" ), volumeDescriptions.Get( "OverlayMap" ).data, idNumVoxelsPerTile );
}
}
//
// unload image data from from host memory
//
mTileServer->UnloadTile( tileIndex );
}
}
}
void TileManager::ReloadTileCacheOverlayMapOnly( int currentZ )
{
for ( int cacheIndex = 0; cacheIndex < mDeviceTileCacheSize; cacheIndex++ )
{
if ( mTileCache[ cacheIndex ].indexTileSpace.x != TILE_CACHE_PAGE_TABLE_BAD_INDEX &&
mTileCache[ cacheIndex ].indexTileSpace.y != TILE_CACHE_PAGE_TABLE_BAD_INDEX &&
mTileCache[ cacheIndex ].indexTileSpace.z != TILE_CACHE_PAGE_TABLE_BAD_INDEX &&
mTileCache[ cacheIndex ].indexTileSpace.w != TILE_CACHE_PAGE_TABLE_BAD_INDEX &&
mTileCache[ cacheIndex ].indexTileSpace.z == currentZ )
{
//
// load image data into host memory
//
MojoInt4 tileIndex = MojoInt4 ( mTileCache[ cacheIndex ].indexTileSpace );
Core::HashMap< std::string, Core::VolumeDescription > volumeDescriptions = mTileServer->LoadTile( tileIndex );
//
// load the new data into into device memory for the new cache entry
//
if ( mIsSegmentationLoaded )
{
if ( volumeDescriptions.GetHashMap().find( "OverlayMap" ) != volumeDescriptions.GetHashMap().end() )
{
mTileCache[ cacheIndex ].d3d11CudaTextures.Get( "OverlayMap" )->Update( volumeDescriptions.Get( "OverlayMap" ) );
//MojoInt3 volShape = mTiledDatasetDescription.tiledVolumeDescriptions.Get( "OverlayMap" ).numVoxelsPerTile();
//int idNumVoxelsPerTile = volShape.x * volShape.y * volShape.z;
//Core::Thrust::MemcpyHostToDevice( mTileCache[ cacheIndex ].deviceVectors.Get< int >( "OverlayMap" ), volumeDescriptions.Get( "OverlayMap" ).data, idNumVoxelsPerTile );
}
}
//
// unload image data from from host memory
//
mTileServer->UnloadTile( tileIndex );
}
}
}
}
} | 34.076157 | 179 | 0.670635 | [
"shape",
"vector"
] |
2be00bb7eaaa932166f93edde751eb94a3db7d3a | 1,512 | hpp | C++ | Silent Killer/silentkiller.hpp | AlishaMomin/OOP-Project-Fall-2021 | 94d2d85de81fa40d8f8ea0ae126478ea146146cb | [
"MIT"
] | null | null | null | Silent Killer/silentkiller.hpp | AlishaMomin/OOP-Project-Fall-2021 | 94d2d85de81fa40d8f8ea0ae126478ea146146cb | [
"MIT"
] | null | null | null | Silent Killer/silentkiller.hpp | AlishaMomin/OOP-Project-Fall-2021 | 94d2d85de81fa40d8f8ea0ae126478ea146146cb | [
"MIT"
] | null | null | null | #include <SDL.h>
#include "Zombie.hpp"
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include "spider.hpp"
#include "Skull.hpp"
#include "fart.hpp"
#include "Bat.hpp"
#include "Wolf.hpp"
#include "Brain.hpp"
#include "SeveredHand.hpp"
#include "Axe.hpp"
#include "Heart.hpp"
#include "Blood.hpp"
#include "music.hpp"
#pragma once
using namespace std;
class Silentkiller
{
SDL_Renderer *gRenderer;
SDL_Texture *assets;
Zombie zombie;
public:
list<Spider *> Slist;
list<Skull *> skulllist;
list<Fart *> fartlist;
list<Bat *> batlist;
list<Wolf *> wolflist;
list<Brain *> brainlist;
list<Severed_hand *> Severedhandlist;
list<Axe *> axelist;
list<Heart *> heartlist;
list<Blood *> bloodlist;
Silentkiller(SDL_Renderer *, SDL_Texture *); //constructor
void drawObjects(); //will draw all the enemy and player objects on screen
void moveZombie(string direction); //movie zombie by calling zombie class and its function move
void createObject(); //will create an objects of enemy using vector list (just like hw3)
enum States //will help to detect the current states of game
{
RUNNING,
LOST,
WON
};
// this will increase or decrease the life of player and will effect the states of the game
int Lifeline = 20;
int Health = 0;
};
| 28.528302 | 117 | 0.615079 | [
"vector"
] |
2be1df52a9c0cfa6efe335ce2330c4bd1f445a9b | 7,695 | hpp | C++ | ThirdParty-mod/java2cpp/java/io/FileOutputStream.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/java/io/FileOutputStream.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/java/io/FileOutputStream.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: java.io.FileOutputStream
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_IO_FILEOUTPUTSTREAM_HPP_DECL
#define J2CPP_JAVA_IO_FILEOUTPUTSTREAM_HPP_DECL
namespace j2cpp { namespace java { namespace io { class Closeable; } } }
namespace j2cpp { namespace java { namespace io { class File; } } }
namespace j2cpp { namespace java { namespace io { class FileDescriptor; } } }
namespace j2cpp { namespace java { namespace io { class OutputStream; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace nio { namespace channels { class FileChannel; } } } }
#include <java/io/Closeable.hpp>
#include <java/io/File.hpp>
#include <java/io/FileDescriptor.hpp>
#include <java/io/OutputStream.hpp>
#include <java/lang/String.hpp>
#include <java/nio/channels/FileChannel.hpp>
namespace j2cpp {
namespace java { namespace io {
class FileOutputStream;
class FileOutputStream
: public object<FileOutputStream>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
J2CPP_DECLARE_METHOD(7)
J2CPP_DECLARE_METHOD(8)
J2CPP_DECLARE_METHOD(9)
J2CPP_DECLARE_METHOD(10)
J2CPP_DECLARE_METHOD(11)
explicit FileOutputStream(jobject jobj)
: object<FileOutputStream>(jobj)
{
}
operator local_ref<java::io::OutputStream>() const;
operator local_ref<java::io::Closeable>() const;
FileOutputStream(local_ref< java::io::File > const&);
FileOutputStream(local_ref< java::io::File > const&, jboolean);
FileOutputStream(local_ref< java::io::FileDescriptor > const&);
FileOutputStream(local_ref< java::lang::String > const&);
FileOutputStream(local_ref< java::lang::String > const&, jboolean);
void close();
local_ref< java::nio::channels::FileChannel > getChannel();
local_ref< java::io::FileDescriptor > getFD();
void write(local_ref< array<jbyte,1> > const&);
void write(local_ref< array<jbyte,1> > const&, jint, jint);
void write(jint);
}; //class FileOutputStream
} //namespace io
} //namespace java
} //namespace j2cpp
#endif //J2CPP_JAVA_IO_FILEOUTPUTSTREAM_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_IO_FILEOUTPUTSTREAM_HPP_IMPL
#define J2CPP_JAVA_IO_FILEOUTPUTSTREAM_HPP_IMPL
namespace j2cpp {
java::io::FileOutputStream::operator local_ref<java::io::OutputStream>() const
{
return local_ref<java::io::OutputStream>(get_jobject());
}
java::io::FileOutputStream::operator local_ref<java::io::Closeable>() const
{
return local_ref<java::io::Closeable>(get_jobject());
}
java::io::FileOutputStream::FileOutputStream(local_ref< java::io::File > const &a0)
: object<java::io::FileOutputStream>(
call_new_object<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(0),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(0)
>(a0)
)
{
}
java::io::FileOutputStream::FileOutputStream(local_ref< java::io::File > const &a0, jboolean a1)
: object<java::io::FileOutputStream>(
call_new_object<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(1),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(1)
>(a0, a1)
)
{
}
java::io::FileOutputStream::FileOutputStream(local_ref< java::io::FileDescriptor > const &a0)
: object<java::io::FileOutputStream>(
call_new_object<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(2),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(2)
>(a0)
)
{
}
java::io::FileOutputStream::FileOutputStream(local_ref< java::lang::String > const &a0)
: object<java::io::FileOutputStream>(
call_new_object<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(3),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(3)
>(a0)
)
{
}
java::io::FileOutputStream::FileOutputStream(local_ref< java::lang::String > const &a0, jboolean a1)
: object<java::io::FileOutputStream>(
call_new_object<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(4),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(4)
>(a0, a1)
)
{
}
void java::io::FileOutputStream::close()
{
return call_method<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(5),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(5),
void
>(get_jobject());
}
local_ref< java::nio::channels::FileChannel > java::io::FileOutputStream::getChannel()
{
return call_method<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(7),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(7),
local_ref< java::nio::channels::FileChannel >
>(get_jobject());
}
local_ref< java::io::FileDescriptor > java::io::FileOutputStream::getFD()
{
return call_method<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(8),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(8),
local_ref< java::io::FileDescriptor >
>(get_jobject());
}
void java::io::FileOutputStream::write(local_ref< array<jbyte,1> > const &a0)
{
return call_method<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(9),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(9),
void
>(get_jobject(), a0);
}
void java::io::FileOutputStream::write(local_ref< array<jbyte,1> > const &a0, jint a1, jint a2)
{
return call_method<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(10),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(10),
void
>(get_jobject(), a0, a1, a2);
}
void java::io::FileOutputStream::write(jint a0)
{
return call_method<
java::io::FileOutputStream::J2CPP_CLASS_NAME,
java::io::FileOutputStream::J2CPP_METHOD_NAME(11),
java::io::FileOutputStream::J2CPP_METHOD_SIGNATURE(11),
void
>(get_jobject(), a0);
}
J2CPP_DEFINE_CLASS(java::io::FileOutputStream,"java/io/FileOutputStream")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,0,"<init>","(Ljava/io/File;)V")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,1,"<init>","(Ljava/io/File;Z)V")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,2,"<init>","(Ljava/io/FileDescriptor;)V")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,3,"<init>","(Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,4,"<init>","(Ljava/lang/String;Z)V")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,5,"close","()V")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,6,"finalize","()V")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,7,"getChannel","()Ljava/nio/channels/FileChannel;")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,8,"getFD","()Ljava/io/FileDescriptor;")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,9,"write","([B)V")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,10,"write","([BII)V")
J2CPP_DEFINE_METHOD(java::io::FileOutputStream,11,"write","(I)V")
} //namespace j2cpp
#endif //J2CPP_JAVA_IO_FILEOUTPUTSTREAM_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 30.903614 | 101 | 0.711111 | [
"object"
] |
2be34d7efff88c873e2a9206805979dfe975e4c5 | 20,680 | cpp | C++ | xyz2mesh/xyz2mesh.cpp | tangrams/LIDar-tools | 23d1dfdeb543a730d370df6f02b44daa6c441a14 | [
"MIT"
] | 29 | 2015-01-28T01:29:07.000Z | 2022-02-20T13:22:36.000Z | xyz2mesh/xyz2mesh.cpp | tangrams/LIDar-tools | 23d1dfdeb543a730d370df6f02b44daa6c441a14 | [
"MIT"
] | null | null | null | xyz2mesh/xyz2mesh.cpp | tangrams/LIDar-tools | 23d1dfdeb543a730d370df6f02b44daa6c441a14 | [
"MIT"
] | 6 | 2017-05-24T08:04:38.000Z | 2022-01-10T02:34:53.000Z | // xyz2mesh.cpp
#define CGAL_EIGEN3_ENABLED
#include <CGAL/Timer.h>
#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>
#include <CGAL/trace.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/Surface_mesh_default_triangulation_3.h>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/make_surface_mesh.h>
#include <CGAL/Implicit_surface_3.h>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/IO/output_surface_facets_to_polyhedron.h>
#include <CGAL/IO/read_xyz_points.h>
#include <CGAL/Poisson_reconstruction_function.h>
#include <CGAL/Point_with_normal_3.h>
#include <CGAL/property_map.h>
#include <CGAL/compute_average_spacing.h>
#include <CGAL/jet_smooth_point_set.h>
#include <CGAL/grid_simplify_point_set.h>
#include <CGAL/mst_orient_normals.h>
#include <CGAL/pca_estimate_normals.h>
#include <CGAL/property_map.h>
#include <CGAL/remove_outliers.h>
#include <fstream>
#include <iostream>
#include <deque>
#include <cstdlib>
#include <math.h>
// ----------------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------------
// Kernel
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
// Simple geometric types
typedef Kernel::FT FT;
typedef Kernel::Point_3 Point;
typedef Kernel::Vector_3 Vector;
typedef CGAL::Point_with_normal_3<Kernel> Point_with_normal;
typedef Kernel::Sphere_3 Sphere;
typedef std::vector<Point> PointList;
typedef std::pair<Point, Vector> PointVectorPair;
typedef std::vector<PointVectorPair> PointVectorList;
typedef std::vector<Point_with_normal> PointWNList;
// polyhedron
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
// Poisson implicit function
typedef CGAL::Poisson_reconstruction_function<Kernel> Poisson_reconstruction_function;
// Surface mesher
typedef CGAL::Surface_mesh_default_triangulation_3 STr;
typedef CGAL::Surface_mesh_complex_2_in_triangulation_3<STr> C2t3;
typedef CGAL::Implicit_surface_3<Kernel, Poisson_reconstruction_function> Surface;
struct Counter {
int i, N;
Counter(int N): i(0), N(N){}
void operator()(){
i++;
if(i == N){
std::cerr << "Counter reached " << N << std::endl;
}
}
};
struct InsertVisitor {
Counter& c;
InsertVisitor(Counter& c):c(c){}
void before_insertion(){c();}
};
void simplifyCloud(PointList& points, float cell_size){
// simplification by clustering using erase-remove idiom
points.erase(CGAL::grid_simplify_point_set(points.begin(), points.end(), cell_size),
points.end());
// Optional: after erase(), use Scott Meyer's "swap trick" to trim excess capacity
std::vector<Point>(points).swap(points);
}
void removeOutliers(PointList& points, float removed_percentage, int nb_neighbors){
// Removes outliers using erase-remove idiom.
// The Identity_property_map property map can be omitted here as it is the default value.
// removed_percentage = 5.0; // percentage of points to remove
// nb_neighbors = 24; // considers 24 nearest neighbor points
points.erase(CGAL::remove_outliers(points.begin(), points.end(),
CGAL::Identity_property_map<Point>(),
nb_neighbors, removed_percentage),
points.end());
// Optional: after erase(), use Scott Meyer's "swap trick" to trim excess capacity
std::vector<Point>(points).swap(points);
}
void estimateNormals(const PointList& points, PointVectorList& point_vectors, int nb_neighbors){
point_vectors.resize(points.size());
for (int i=0; i<points.size(); i++) {
point_vectors[i].first = points[i];
}
// Estimates normals direction.
// Note: pca_estimate_normals() requires an iterator over points
// as well as property maps to access each point's position and normal.
// nb_neighbors = 18; // K-nearest neighbors = 3 rings
CGAL::pca_estimate_normals(point_vectors.begin(), point_vectors.end(),
CGAL::First_of_pair_property_map<PointVectorPair>(),
CGAL::Second_of_pair_property_map<PointVectorPair>(),
nb_neighbors);
}
void orientNormals(PointVectorList& points, int nb_neighbors, bool trim){
// Orients normals.
// Note: mst_orient_normals() requires an iterator over points
// as well as property maps to access each point's position and normal.
std::vector<PointVectorPair>::iterator unoriented_points_begin =
CGAL::mst_orient_normals(points.begin(), points.end(),
CGAL::First_of_pair_property_map<PointVectorPair>(),
CGAL::Second_of_pair_property_map<PointVectorPair>(),
nb_neighbors);
// Optional: delete points with an unoriented normal
// if you plan to call a reconstruction algorithm that expects oriented normals.
if (trim)
points.erase(unoriented_points_begin, points.end());
}
inline void convert(const PointVectorList& point_vectors, PointWNList& point_with_normals){
int n = point_vectors.size();
point_with_normals.resize(n);
for (int i=0; i<n; i++) {
point_with_normals[i].position() = point_vectors[i].first;
point_with_normals[i].normal() = point_vectors[i].second;
}
}
struct Vertex{
Vertex(long double _x, long double _y, long double _z):x(_x),y(_y),z(_z){};
long double x,y,z;
};
void savePly(const Polyhedron& _poly, std::string _path, bool _useBinary = false ) {
// COPY DATA (vertex + index)
//
std::vector<Vertex> vertices;
std::map<Point, uint16_t> vertices_indices;
std::vector<uint16_t> indices;
int count = 0;
for (auto it=_poly.vertices_begin(); it!=_poly.vertices_end(); ++it) {
auto& p = it->point();
vertices.push_back(Vertex(p.x(), p.y(), p.z()));
vertices_indices[p] = count++;
}
for (auto it=_poly.facets_begin(); it!=_poly.facets_end(); ++it) {
indices.push_back(vertices_indices[it->halfedge()->vertex()->point()]);
indices.push_back(vertices_indices[it->halfedge()->next()->vertex()->point()]);
indices.push_back(vertices_indices[it->halfedge()->prev()->vertex()->point()]);
}
// CREATE PLY
//
std::ios_base::openmode binary_mode = _useBinary ? std::ios::binary : (std::ios_base::openmode)0;
std::fstream os(_path.c_str(), std::ios::out | binary_mode);
// Header
os << "ply" << std::endl;
if(_useBinary) {
os << "format binary_little_endian 1.0" << std::endl;
} else {
os << "format ascii 1.0" << std::endl;
}
if(vertices.size()>0){
os << "element vertex " << vertices.size() << std::endl;
os << "property float x" << std::endl;
os << "property float y" << std::endl;
os << "property float z" << std::endl;
}
unsigned char faceSize = 3;
if(indices.size()>0){
os << "element face " << indices.size() / faceSize << std::endl;
os << "property list uchar int vertex_indices" << std::endl;
} else {
os << "element face " << vertices.size() / faceSize << std::endl;
os << "property list uchar int vertex_indices" << std::endl;
}
os << "end_header" << std::endl;
// Vertices
for(int i = 0; i < vertices.size(); i++){
if(_useBinary) {
os.write((char*) &vertices[i].x, sizeof(Vertex));
} else {
os << vertices[i].x << " " << vertices[i].y << " " << vertices[i].z;
}
if(!_useBinary) {
os << std::endl;
}
}
// Indices
if(indices.size()>0) {
for(int i = 0; i < indices.size(); i += faceSize) {
if(_useBinary) {
os.write((char*) &faceSize, sizeof(unsigned char));
for(int j = 0; j < faceSize; j++) {
int curIndex = indices[i + j];
os.write((char*) &curIndex, sizeof(uint16_t));
}
} else {
os << (int) faceSize << " " << indices[i] << " " << indices[i+1] << " " << indices[i+2] << std::endl;
}
}
} else {
for(int i = 0; i < vertices.size(); i += faceSize) {
int indices[] = {i, i + 1, i + 2};
if(_useBinary) {
os.write((char*) &faceSize, sizeof(unsigned char));
for(int j = 0; j < faceSize; j++) {
os.write((char*) &indices[j], sizeof(uint16_t));
}
} else {
os << (int) faceSize << " " << indices[0] << " " << indices[1] << " " << indices[2] << std::endl;
}
}
}
os.close();
}
int main(int argc, char * argv[]){
//***************************************
// decode parameters
//***************************************
// Simplification options
float cell_size = 0.5;
// Remove outliears
int rm_nb_neighbors = 24;
float rm_percentage = 0.0;
// Normal estimation options
int nb_neighbors = 100;
// Poisson options
FT sm_angle = 20.0; // Min triangle angle (degrees).
FT sm_radius = 100; // Max triangle size w.r.t. point set average spacing.
FT sm_distance = 0.25; // Approximation error w.r.t. point set average spacing.
std::string solver_name = "";//"eigen"; // Sparse linear solver name.
double approximation_ratio = 0.02;
double average_spacing_ratio = 5;
if (argc-1 < 2){
std::cerr << "Usage: " << argv[0] << " file_in.xyz file_out.off [options]\n";
std::cerr << "PointCloud simplification options:\n";
std::cerr << " -cell_size <float> Size of the cell for the simplification (default="<<cell_size<<")\n";
std::cerr << "\n";
std::cerr << "PointCloud outliers removal:\n";
std::cerr << " -rm_nb_neighbors <float> Nearby Neighbors for Outliers Removal (default="<<rm_nb_neighbors<<")\n";
std::cerr << " -rm_percentage <float> Porcentage of outliers to remove (default="<<rm_percentage<<")\n";
std::cerr << "\n";
std::cerr << "PointCloud normal estimation:\n";
std::cerr << " -nb_neighbors <float> Nearby Neighbors for Normal Estimation (default="<<nb_neighbors<<")\n";
std::cerr << "\n";
std::cerr << "Surface poisson reconstruction:\n";
std::cerr << " -solver <string> Linear solver name (default="<<solver_name<<")\n";
std::cerr << " -sm_angle <float> Min triangle angle (default="<< sm_angle <<" degrees)\n";
std::cerr << " -sm_radius <float> Max triangle size w.r.t. point set average spacing (default="<<sm_radius<<")\n";
std::cerr << " -sm_distance <float> Approximation error w.r.t. point set average spacing (default="<<sm_distance<<")\n";
std::cerr << " -approx <float> Aproximation ratio (default="<<approximation_ratio<<")\n";
std::cerr << " -ratio <float> Average spacing ratio (default="<<average_spacing_ratio<<")\n";
return EXIT_FAILURE;
}
// decode parameters
std::string input_filename = argv[1];
std::string output_filename = argv[2];
for (int i=3; i+1<argc ; ++i){
if (std::string(argv[i])=="-cell_size")
cell_size = atof(argv[++i]);
else if (std::string(argv[i])=="-rm_nb_neighbors")
rm_nb_neighbors = atof(argv[++i]);
else if (std::string(argv[i])=="-rm_nb_neighbors")
rm_percentage = atof(argv[++i]);
else if (std::string(argv[i])=="-nb_neighbors")
nb_neighbors = atof(argv[++i]);
else if (std::string(argv[i])=="-sm_radius")
sm_angle = atof(argv[++i]);
else if (std::string(argv[i])=="-sm_radius")
sm_radius = atof(argv[++i]);
else if (std::string(argv[i])=="-sm_distance")
sm_distance = atof(argv[++i]);
else if (std::string(argv[i])=="-solver")
solver_name = argv[++i];
else if (std::string(argv[i])=="-approx")
approximation_ratio = atof(argv[++i]);
else if (std::string(argv[i])=="-ratio")
average_spacing_ratio = atof(argv[++i]);
else {
std::cerr << "Error: invalid option " << argv[i] << "\n";
return EXIT_FAILURE;
}
}
CGAL::Timer task_timer;
task_timer.start();
//***************************************
// Loads mesh/point set
//***************************************
PointList points;
std::ifstream stream(input_filename, std::ifstream::in);
CGAL::read_xyz_points(stream, back_inserter(points));
// Prints status
int nb_points = points.size();
std::cerr << "Reads file " << input_filename << ": " << nb_points << " points, " << task_timer.time() << " seconds" << std::endl;
task_timer.reset();
//***************************************
// Simplify Point Cloud
//***************************************
//
if(cell_size!=0.0){
std::cout << "Simpliy...";
simplifyCloud(points, cell_size);
std::cout << points.size() << " points," << task_timer.time() << " seconds" << std::endl;
task_timer.reset();
}
//***************************************
// Remove outliers from Point Cloud
//***************************************
//
if(rm_percentage!=0.0 && rm_nb_neighbors != 0.0){
std::cout << "Removing outliers...";
removeOutliers(points, rm_percentage,rm_nb_neighbors);
std::cout << points.size() << " points," << task_timer.time() << " seconds" << std::endl;
task_timer.reset();
}
//***************************************
// Compute Normals normals on the Point Cloud
//***************************************
//
PointVectorList point_vectors;
std::cout << "Normal estimation...";
estimateNormals(points, point_vectors, nb_neighbors);
std::cout << task_timer.time() << " seconds" << std::endl;
task_timer.reset();
std::cout << "Normal orientation...";
orientNormals(point_vectors, nb_neighbors, true);
std::cout << task_timer.time() << " seconds" << std::endl;
task_timer.reset();
//***************************************
// Surface Reconstruction
//***************************************
//
PointWNList pointsWN;
convert(point_vectors, pointsWN);
// Reads the point set file in points[].
// Note: read_xyz_points_and_normals() requires an iterator over points
// + property maps to access each point's position and normal.
// The position property map can be omitted here as we use iterators over Point elements.
CGAL::Timer reconstruction_timer; reconstruction_timer.start();
Counter counter(std::distance(pointsWN.begin(), pointsWN.end()));
InsertVisitor visitor(counter) ;
// Creates implicit function from the read points using the default solver.
// Note: this method requires an iterator over points
// + property maps to access each point's position and normal.
// The position property map can be omitted here as we use iterators over Point_3 elements.
Poisson_reconstruction_function function(pointsWN.begin(), pointsWN.end(),
CGAL::make_identity_property_map(PointWNList::value_type()),
CGAL::make_normal_of_point_with_normal_pmap(PointWNList::value_type()),
visitor);
#ifdef CGAL_EIGEN3_ENABLED
// Computes the Poisson indicator function f()
// at each vertex of the triangulation.
if (solver_name == "eigen"){
std::cerr << "Use Eigen 3\n";
CGAL::Eigen_solver_traits<Eigen::ConjugateGradient<CGAL::Eigen_sparse_symmetric_matrix<double>::EigenType> > solver;
if ( !function.compute_implicit_function(solver, visitor,
approximation_ratio,
average_spacing_ratio) ){
std::cerr << "Error: cannot compute implicit function" << std::endl;
return EXIT_FAILURE;
}
} else {
if ( !function.compute_implicit_function() ){
std::cout << "Error: cannot compute implicit function" << std::endl;
return EXIT_FAILURE;
}
}
#else
if ( !function.compute_implicit_function() ){
std::cout << "Error: cannot compute implicit function" << std::endl;
return EXIT_FAILURE;
}
#endif
//***************************************
// Surface mesh generation
//***************************************
// Computes average spacing
FT average_spacing = CGAL::compute_average_spacing(pointsWN.begin(), pointsWN.end(), 6 /* knn = 1 ring */);
// Gets one point inside the implicit surface
Point inner_point = function.get_inner_point();
FT inner_point_value = function(inner_point);
if(inner_point_value >= 0.0){
std::cerr << "Error: unable to seed (" << inner_point_value << " at inner_point)" << std::endl;
return EXIT_FAILURE;
}
// Gets implicit function's radius
Sphere bsphere = function.bounding_sphere();
FT radius = std::sqrt(bsphere.squared_radius());
// Defines the implicit surface: requires defining a
// conservative bounding sphere centered at inner point.
FT sm_sphere_radius = 5.0 * radius;
FT sm_dichotomy_error = sm_distance*average_spacing/1000.0; // Dichotomy error must be << sm_distance
Surface surface(function,
Sphere(inner_point,sm_sphere_radius*sm_sphere_radius),
sm_dichotomy_error/sm_sphere_radius);
// Defines surface mesh generation criteria
CGAL::Surface_mesh_default_criteria_3<STr> criteria(sm_angle, // Min triangle angle (degrees)
sm_radius*average_spacing, // Max triangle size
sm_distance*average_spacing); // Approximation error
CGAL_TRACE_STREAM << " make_surface_mesh(sphere center=("<<inner_point << "),\n"
<< " sphere radius="<<sm_sphere_radius<<",\n"
<< " angle="<<sm_angle << " degrees,\n"
<< " triangle size="<<sm_radius<<" * average spacing="<<sm_radius*average_spacing<<",\n"
<< " distance="<<sm_distance<<" * average spacing="<<sm_distance*average_spacing<<",\n"
<< " dichotomy error=distance/"<<sm_distance*average_spacing/sm_dichotomy_error<<",\n"
<< " Manifold_with_boundary_tag)\n";
// Generates surface mesh with manifold option
STr tr; // 3D Delaunay triangulation for surface mesh generation
C2t3 c2t3(tr); // 2D complex in 3D Delaunay triangulation
CGAL::make_surface_mesh(c2t3, // reconstructed mesh
surface, // implicit surface
criteria, // meshing criteria
CGAL::Manifold_with_boundary_tag()); // require manifold mesh
// Prints status
std::cerr << "Surface meshing: " << task_timer.time() << " seconds, "
<< tr.number_of_vertices() << " output vertices"
<< std::endl;
task_timer.reset();
if(tr.number_of_vertices() == 0)
return EXIT_FAILURE;
// Converts to polyhedron
Polyhedron output_mesh;
CGAL::output_surface_facets_to_polyhedron(c2t3, output_mesh);
// Prints total reconstruction duration
std::cerr << "Total reconstruction (implicit function + meshing): " << reconstruction_timer.time() << " seconds\n";
std::cerr << "Write file " << output_filename << std::endl << std::endl;
std::string extension = output_filename.substr(output_filename.find_last_of('.'));
if(extension == ".off" || extension == ".OFF"){
std::ofstream out(output_filename);
out << output_mesh;
} else {
savePly(output_mesh, output_filename);
}
return EXIT_SUCCESS;
}
| 40.869565 | 136 | 0.575048 | [
"mesh",
"vector",
"3d"
] |
2be9ab0c5ef2818b50e6bd8e613a312b92a49b20 | 908 | cpp | C++ | inference-engine/tests_deprecated/functional/shared_tests/transformations/fq_as_output.cpp | shre2398/openvino | f84a6d97ace26b75ae9d852525a997cbaba32e6a | [
"Apache-2.0"
] | 2 | 2021-02-26T15:46:19.000Z | 2021-05-16T20:48:13.000Z | inference-engine/tests_deprecated/functional/shared_tests/transformations/fq_as_output.cpp | shre2398/openvino | f84a6d97ace26b75ae9d852525a997cbaba32e6a | [
"Apache-2.0"
] | 1 | 2020-12-22T05:01:12.000Z | 2020-12-23T09:49:43.000Z | inference-engine/tests_deprecated/functional/shared_tests/transformations/fq_as_output.cpp | shre2398/openvino | f84a6d97ace26b75ae9d852525a997cbaba32e6a | [
"Apache-2.0"
] | 1 | 2020-08-13T08:33:55.000Z | 2020-08-13T08:33:55.000Z | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "low_precision_transformer_single_layer_tests.hpp"
#include "common_test_utils/common_utils.hpp"
std::string FakeQuantizeAsOutputTest::getName() const {
return "FakeQuantizeAsOutputTest";
}
bool FakeQuantizeAsOutputTest::transform(CNNNetwork& network, LayerTransformation::Params& params) const {
network.addOutput("FakeQuantize12");
LowPrecisionTransformer transformer(LowPrecisionTransformer::getAllTransformations(params));
transformer.transform(network);
const auto fq = CommonTestUtils::getLayerByName(network, "FakeQuantize12");
if (fq == nullptr)
THROW_IE_EXCEPTION << "Layer 'FakeQuantize12' should not be transformed";
return true;
}
std::unordered_set<std::string> FakeQuantizeAsOutputTest::getNotTransformedLayers() const {
return { "Convolution14" };
}
| 32.428571 | 106 | 0.769824 | [
"transform"
] |
2bec608b2d239e3012f083f8e9b06aa7f2a44887 | 14,638 | cpp | C++ | mtTorrent/Core/Torrent.cpp | RazielXT/mtTorrent | 01faaea8e46886668d52e5c38ee3367ecb19f6ab | [
"MIT"
] | 11 | 2016-03-08T11:49:43.000Z | 2020-05-14T03:12:59.000Z | mtTorrent/Core/Torrent.cpp | RazielXT/mtTorrent | 01faaea8e46886668d52e5c38ee3367ecb19f6ab | [
"MIT"
] | 8 | 2020-05-13T13:16:17.000Z | 2021-01-02T19:59:03.000Z | mtTorrent/Core/Torrent.cpp | RazielXT/mtTorrent | 01faaea8e46886668d52e5c38ee3367ecb19f6ab | [
"MIT"
] | 5 | 2019-04-04T02:08:10.000Z | 2022-03-17T09:02:34.000Z | #include "Torrent.h"
#include "utils/TorrentFileParser.h"
#include "MetadataDownload.h"
#include "Peers.h"
#include "Configuration.h"
#include "FileTransfer.h"
#include "State.h"
#include "utils/HexEncoding.h"
#include "utils/Filesystem.h"
#include "AlertsManager.h"
#include <filesystem>
mtt::Torrent::Torrent() : service(0), files(infoFile.info)
{
}
mtt::Torrent::~Torrent()
{
}
mtt::TorrentPtr mtt::Torrent::fromFile(mtt::TorrentFileInfo fileInfo)
{
if (fileInfo.info.name.empty())
return nullptr;
mtt::TorrentPtr torrent = std::make_shared<Torrent>();
torrent->infoFile = std::move(fileInfo);
torrent->loadedState = LoadedState::Full;
torrent->initialize();
torrent->peers = std::make_shared<Peers>(torrent);
torrent->fileTransfer = std::make_shared<FileTransfer>(torrent);
torrent->addedTime = (int64_t)time(0);
return torrent;
}
mtt::TorrentPtr mtt::Torrent::fromMagnetLink(std::string link)
{
mtt::TorrentPtr torrent = std::make_shared<Torrent>();
if (torrent->infoFile.parseMagnetLink(link) != Status::Success)
return nullptr;
torrent->peers = std::make_shared<Peers>(torrent);
torrent->fileTransfer = std::make_shared<FileTransfer>(torrent);
torrent->addedTime = (int64_t)time(0);
return torrent;
}
mtt::TorrentPtr mtt::Torrent::fromSavedState(std::string name)
{
mtt::TorrentPtr torrent = std::make_shared<Torrent>();
TorrentState state(torrent->files.progress.pieces);
if (!state.load(name))
return nullptr;
torrent->infoFile.info.name = state.info.name;
torrent->infoFile.info.pieceSize = state.info.pieceSize;
decodeHexa(name, torrent->infoFile.info.hash);
if (state.info.name.empty())
{
if(!torrent->loadFileInfo())
return nullptr;
torrent->stateChanged = true;
}
torrent->files.initialize(state.selection, state.downloadPath);
torrent->lastStateTime = state.lastStateTime;
torrent->addedTime = state.addedTime;
if (torrent->addedTime == 0)
torrent->addedTime = (int64_t)time(0);
torrent->peers = std::make_shared<Peers>(torrent);
torrent->fileTransfer = std::make_shared<FileTransfer>(torrent);
torrent->fileTransfer->getUploadSum() = state.uploaded;
torrent->fileTransfer->addUnfinishedPieces(state.unfinishedPieces);
if (state.started)
torrent->start();
return torrent;
}
bool mtt::Torrent::loadFileInfo()
{
if (loadedState == LoadedState::Full)
return true;
if (utmDl)
return false;
loadedState = LoadedState::Full;
DataBuffer buffer;
if (!Torrent::loadSavedTorrentFile(hashString(), buffer))
{
lastError = Status::E_NoData;
return false;
}
infoFile = mtt::TorrentFileParser::parse(buffer.data(), buffer.size());
if (peers)
peers->reloadTorrentInfo();
return true;
}
void mtt::Torrent::save()
{
if (!stateChanged)
return;
TorrentState saveState(files.progress.pieces);
saveState.info.name = name();
saveState.info.pieceSize = infoFile.info.pieceSize;
saveState.downloadPath = files.storage.getPath();
saveState.lastStateTime = lastStateTime = files.storage.getLastModifiedTime();
saveState.addedTime = addedTime;
saveState.started = state == ActiveState::Started;
saveState.uploaded = fileTransfer->getUploadSum();
if (fileTransfer)
saveState.unfinishedPieces = std::move(fileTransfer->getUnfinishedPiecesState());
for (auto& f : files.selection)
saveState.selection.push_back({ f.selected, f.priority });
saveState.save(hashString());
stateChanged = saveState.started;
}
void mtt::Torrent::saveTorrentFile(const char* data, size_t size)
{
auto folderPath = mtt::config::getInternal().stateFolder + pathSeparator + hashString() + ".torrent";
std::ofstream file(folderPath, std::ios::binary);
if (!file)
return;
file.write(data, size);
}
void mtt::Torrent::removeMetaFiles()
{
auto path = mtt::config::getInternal().stateFolder + pathSeparator + hashString();
std::remove((path + ".torrent").data());
std::remove((path + ".state").data());
}
bool mtt::Torrent::importTrackers(const mtt::TorrentFileInfo& otherFileInfo)
{
std::vector<std::string> added;
for (auto& t : otherFileInfo.announceList)
{
if (std::find(infoFile.announceList.begin(), infoFile.announceList.end(), t) == infoFile.announceList.end())
{
added.push_back(t);
infoFile.announceList.push_back(t);
}
}
if (!added.empty())
{
if(infoFile.announce.empty())
infoFile.announce = infoFile.announceList.front();
DataBuffer buffer;
if (loadSavedTorrentFile(hashString(), buffer))
{
TorrentFileParser::ParsedInfo parseInfo;
auto loadedFile = mtt::TorrentFileParser::parse(buffer.data(), buffer.size(), &parseInfo);
if (!loadedFile.info.name.empty())
{
auto newFile = infoFile.createTorrentFileData((const uint8_t*)parseInfo.infoStart, parseInfo.infoSize);
saveTorrentFile(newFile.data(), newFile.size());
}
}
peers->trackers.addTrackers(added);
}
return !added.empty();
}
bool mtt::Torrent::loadSavedTorrentFile(const std::string& hash, DataBuffer& out)
{
auto filename = mtt::config::getInternal().stateFolder + pathSeparator + hash + ".torrent";
std::ifstream file(filename, std::ios_base::binary);
if (!file.good())
return false;
out = DataBuffer((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>()));
return !out.empty();
}
void mtt::Torrent::refreshLastState()
{
if (!checking)
{
bool needRecheck = false;
int64_t filesTime = 0;
const auto& tfiles = infoFile.info.files;
for (size_t i = 0; i < tfiles.size(); i++)
{
auto fileTime = files.storage.getLastModifiedTime(i);
if (filesTime < fileTime)
filesTime = fileTime;
bool checkFile = !lastStateTime;
if (!fileTime && files.progress.hasPiece(tfiles[i].startPieceIndex) && tfiles[i].size != 0)
needRecheck = true;
}
if (filesTime != lastStateTime || needRecheck)
{
fileTransfer->clearUnfinishedPieces();
if (filesTime == 0)
lastStateTime = 0;
checkFiles();
}
}
}
void mtt::Torrent::downloadMetadata()
{
service.start(4);
if(!utmDl)
utmDl = std::make_shared<MetadataDownload>(*peers, service);
utmDl->start([this](Status s, MetadataDownloadState& state)
{
if (s == Status::Success && state.finished && infoFile.info.files.empty())
{
infoFile.info = utmDl->metadata.getRecontructedInfo();
loadedState = LoadedState::Full;
auto fileData = infoFile.createTorrentFileData(utmDl->metadata.buffer.data(), utmDl->metadata.buffer.size());
saveTorrentFile(fileData.data(), fileData.size());
initialize();
peers->reloadTorrentInfo();
AlertsManager::Get().metadataAlert(AlertId::MetadataFinished, this);
if (this->state == ActiveState::Started)
service.io.post([this]() { start(); });
}
});
}
mttApi::Torrent::State mtt::Torrent::getState() const
{
if (checking)
return mttApi::Torrent::State::CheckingFiles;
else if (stopping)
return mttApi::Torrent::State::Stopping;
else if (utmDl && utmDl->state.active)
return mttApi::Torrent::State::DownloadingMetadata;
else if (state == mttApi::Torrent::ActiveState::Stopped)
return lastError == Status::Success ? mttApi::Torrent::State::Inactive : mttApi::Torrent::State::Interrupted;
else if (finished())
return mttApi::Torrent::State::Seeding;
else
return mttApi::Torrent::State::Downloading;
}
void mtt::Torrent::initialize()
{
stateChanged = true;
files.setDefaults(infoFile.info);
AlertsManager::Get().torrentAlert(AlertId::TorrentAdded, this);
}
mtt::Status mtt::Torrent::start()
{
std::unique_lock<std::mutex> guard(stateMutex);
#ifdef PEER_DIAGNOSTICS
std::filesystem::path logDir = std::filesystem::u8path(".\\logs\\" + name());
if (!std::filesystem::exists(logDir))
{
std::error_code ec;
std::filesystem::create_directory(logDir, ec);
}
#endif
if (getState() == mttApi::Torrent::State::DownloadingMetadata)
{
state = ActiveState::Started;
return Status::Success;
}
if (utmDl && !utmDl->state.finished)
{
downloadMetadata();
return Status::Success;
}
if (loadFileInfo())
{
refreshLastState();
if (!checking)
{
lastError = files.prepareSelection();
if (lastError == mtt::Status::Success)
lastStateTime = files.storage.getLastModifiedTime();
}
}
if (lastError != mtt::Status::Success)
{
guard.unlock();
stop(StopReason::Internal);
return lastError;
}
service.start(5);
state = ActiveState::Started;
stateChanged = true;
if (!checking)
fileTransfer->start();
return Status::Success;
}
void mtt::Torrent::stop(StopReason reason)
{
if (stopping)
return;
std::lock_guard<std::mutex> guard(stateMutex);
if (checking)
{
std::lock_guard<std::mutex> guard(checkStateMutex);
if (checkState)
checkState->rejected = true;
checking = false;
}
if (utmDl)
{
utmDl->stop();
}
if (state == mttApi::Torrent::ActiveState::Stopped)
{
save();
return;
}
stopping = true;
if (fileTransfer)
{
fileTransfer->stop();
}
if (reason != StopReason::Internal)
service.stop();
if(reason == StopReason::Manual)
state = ActiveState::Stopped;
save();
state = ActiveState::Stopped;
if(reason != StopReason::Internal)
lastError = Status::Success;
stateChanged = true;
stopping = false;
}
void mtt::Torrent::checkFiles(bool all)
{
if (checking)
return;
if (all)
{
lastStateTime = 0;
}
auto request = std::make_shared<mtt::PiecesCheck>(files.progress);
request->piecesCount = (uint32_t)files.progress.pieces.size();
std::vector<bool> wantedChecks(infoFile.info.pieces.size());
const auto& tfiles = infoFile.info.files;
for (size_t i = 0; i < tfiles.size(); i++)
{
bool checkFile = !lastStateTime;
if (!checkFile)
{
auto fileTime = files.storage.getLastModifiedTime(i);
if (lastStateTime < fileTime || (!fileTime && files.progress.selectedPiece(tfiles[i].startPieceIndex)))
checkFile = true;
}
if (checkFile)
{
for (uint32_t p = tfiles[i].startPieceIndex; p <= tfiles[i].endPieceIndex; p++)
wantedChecks[p] = true;
}
}
files.progress.removeReceived(wantedChecks);
auto localOnFinish = [this, request]()
{
checking = false;
{
std::lock_guard<std::mutex> guard(checkStateMutex);
checkState.reset();
}
if (!request->rejected)
{
files.progress.select(infoFile.info, files.selection);
lastStateTime = files.storage.getLastModifiedTime();
stateChanged = true;
if (state == ActiveState::Started)
start();
else
stop();
}
else
lastStateTime = 0;
};
checking = true;
lastError = Status::Success;
loadFileInfo();
const uint32_t WorkersCount = 4;
service.start(WorkersCount);
auto finished = std::make_shared<uint32_t>(0);
for (uint32_t i = 0; i < WorkersCount; i++)
service.io.post([WorkersCount, i, finished, localOnFinish, request, wantedChecks, this]()
{
files.storage.checkStoredPieces(*request.get(), infoFile.info.pieces, WorkersCount, i, wantedChecks);
if (++(*finished) == WorkersCount)
localOnFinish();
});
std::lock_guard<std::mutex> guard(checkStateMutex);
checkState = request;
}
float mtt::Torrent::checkingProgress() const
{
std::lock_guard<std::mutex> guard(checkStateMutex);
if (checkState)
return checkState->piecesChecked / (float)checkState->piecesCount;
else
return 1;
}
bool mtt::Torrent::selectFiles(const std::vector<bool>& s)
{
loadFileInfo();
if (!files.select(infoFile.info, s))
return false;
stateChanged = true;
if (state == ActiveState::Started)
{
lastError = files.prepareSelection();
if (fileTransfer)
fileTransfer->refreshSelection();
return lastError == Status::Success;
}
return true;
}
bool mtt::Torrent::selectFile(uint32_t index, bool selected)
{
loadFileInfo();
if (!files.select(infoFile.info, index, selected))
return false;
if (state == ActiveState::Started)
{
lastError = files.prepareSelection();
if (fileTransfer)
fileTransfer->refreshSelection();
return lastError == Status::Success;
}
return true;
}
void mtt::Torrent::setFilesPriority(const std::vector<mtt::Priority>& priority)
{
loadFileInfo();
if (files.selection.size() != priority.size())
return;
for (size_t i = 0; i < priority.size(); i++)
files.selection[i].priority = priority[i];
if (state == ActiveState::Started)
{
if (fileTransfer)
fileTransfer->refreshSelection();
}
stateChanged = true;
}
bool mtt::Torrent::finished() const
{
return files.progress.getPercentage() == 1;
}
bool mtt::Torrent::selectionFinished() const
{
return files.progress.getSelectedPercentage() == 1;
}
int64_t mtt::Torrent::getTimeAdded() const
{
return addedTime;
}
const uint8_t* mtt::Torrent::hash() const
{
return infoFile.info.hash;
}
std::string mtt::Torrent::hashString() const
{
return hexToString(infoFile.info.hash, 20);
}
const std::string& mtt::Torrent::name() const
{
return infoFile.info.name;
}
float mtt::Torrent::progress() const
{
float progress = files.progress.getPercentage();
if (fileTransfer && infoFile.info.pieceSize)
{
float unfinishedPieces = fileTransfer->getUnfinishedPiecesDownloadSize() / (float)infoFile.info.pieceSize;
progress += unfinishedPieces / files.progress.pieces.size();
}
if (progress > 1.0f)
progress = 1.0f;
return progress;
}
float mtt::Torrent::selectionProgress() const
{
if (files.progress.selectedPieces == files.progress.pieces.size())
return progress();
float progress = files.progress.getSelectedPercentage();
if (fileTransfer && infoFile.info.pieceSize)
{
auto unfinishedPieces = fileTransfer->getUnfinishedPiecesDownloadSizeMap();
uint32_t unfinishedSize = 0;
for (auto& p : unfinishedPieces)
{
if (files.progress.selectedPiece(p.first))
unfinishedSize += p.second;
}
if (files.progress.selectedPieces)
progress += unfinishedSize / (float)(infoFile.info.pieceSize * files.progress.selectedPieces);
}
if (progress > 1.0f)
progress = 1.0f;
return progress;
}
uint64_t mtt::Torrent::downloaded() const
{
return (uint64_t)(infoFile.info.fullSize * (double)files.progress.getPercentage()) + (fileTransfer ? fileTransfer->getUnfinishedPiecesDownloadSize() : 0);
}
size_t mtt::Torrent::downloadSpeed() const
{
return fileTransfer ? fileTransfer->getDownloadSpeed() : 0;
}
uint64_t mtt::Torrent::uploaded() const
{
return fileTransfer ? fileTransfer->getUploadSum() : 0;
}
size_t mtt::Torrent::uploadSpeed() const
{
return fileTransfer ? fileTransfer->getUploadSpeed() : 0;
}
uint64_t mtt::Torrent::dataLeft() const
{
return infoFile.info.fullSize - downloaded();
}
mtt::Status mtt::Torrent::setLocationPath(const std::string& path, bool moveFiles)
{
stateChanged = true;
auto status = files.storage.setPath(path, moveFiles);
if (!moveFiles)
checkFiles(true);
return status;
}
| 22.078431 | 155 | 0.705493 | [
"vector"
] |
2bf0fd382fc47ba2aeafc7bfc97794e914112194 | 200 | hpp | C++ | Demos/ODFAEG-CLIENT/pnj.hpp | Ornito/ODFAEG-1 | f563975ae4bdd2e178d1ed7267e1920425aa2c4d | [
"Zlib"
] | null | null | null | Demos/ODFAEG-CLIENT/pnj.hpp | Ornito/ODFAEG-1 | f563975ae4bdd2e178d1ed7267e1920425aa2c4d | [
"Zlib"
] | null | null | null | Demos/ODFAEG-CLIENT/pnj.hpp | Ornito/ODFAEG-1 | f563975ae4bdd2e178d1ed7267e1920425aa2c4d | [
"Zlib"
] | null | null | null | #ifndef SORROK_PNJ
#define SORROK_PNJ
namespace sorrok {
class Pnj : public Caracter {
public :
Pnj();
private :
std::vector<Quest> quests;
};
}
#endif
| 16.666667 | 38 | 0.55 | [
"vector"
] |
2bf294bcde850dec6022309cb2e98125dc365747 | 818 | cpp | C++ | Acwing/AC2.cpp | yanjinbin/Foxconn | d8340d228deb35bd8ec244f6156374da8a1f0aa0 | [
"CC0-1.0"
] | 8 | 2021-02-14T01:48:09.000Z | 2022-01-29T09:12:55.000Z | Acwing/AC2.cpp | yanjinbin/Foxconn | d8340d228deb35bd8ec244f6156374da8a1f0aa0 | [
"CC0-1.0"
] | null | null | null | Acwing/AC2.cpp | yanjinbin/Foxconn | d8340d228deb35bd8ec244f6156374da8a1f0aa0 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <iostream>
#include <map>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
const int INF = 0x3F3F3F3F;
#define debug puts("bling bling ⚡️⚡️");
#define FOR(i, a, b) for (int i = a; i < b; i++)
#define ll long long
#define pii pair<int, int>
int maxN = 1001;
int main() {
int N, V;
cin >> N >> V;
vector<int> c(N+1);
vector<int> w(N+1);
for (int i = 1; i <= N; i++) {
cin >> c[i] >> w[i];
}
vector <vector<int>> dp(N + 1, vector<int>(V + 1));
dp[0][0] = 0;
for (int i = 1; i <= N; i++) {
for (int j = 0; j <= V; j++) {
if (j >= c[i]) dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - c[i]] + w[i]);
else dp[i][j] = dp[i - 1][j];
}
}
cout << dp[N][V];
return dp[N][V];
}
| 22.108108 | 84 | 0.471883 | [
"vector"
] |
2bf3fbeead6237c43d0bd71d9ed494d23f890f35 | 7,057 | cc | C++ | third_party/txt/src/skia/paragraph_skia.cc | luoyibu/engine | e535969dbae360446faad3517e5f90ec9164d345 | [
"BSD-3-Clause"
] | 1 | 2022-03-14T18:29:14.000Z | 2022-03-14T18:29:14.000Z | third_party/txt/src/skia/paragraph_skia.cc | luoyibu/engine | e535969dbae360446faad3517e5f90ec9164d345 | [
"BSD-3-Clause"
] | 2 | 2019-05-09T12:15:03.000Z | 2020-03-09T09:24:39.000Z | third_party/txt/src/skia/paragraph_skia.cc | luoyibu/engine | e535969dbae360446faad3517e5f90ec9164d345 | [
"BSD-3-Clause"
] | 1 | 2022-02-08T00:14:53.000Z | 2022-02-08T00:14:53.000Z | /*
* Copyright 2019 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 "paragraph_skia.h"
#include <algorithm>
#include <numeric>
namespace txt {
namespace skt = skia::textlayout;
namespace {
// Convert SkFontStyle::Weight values (ranging from 100-900) to txt::FontWeight
// values (ranging from 0-8).
txt::FontWeight GetTxtFontWeight(int font_weight) {
int txt_weight = (font_weight - 100) / 100;
txt_weight = std::clamp(txt_weight, static_cast<int>(txt::FontWeight::w100),
static_cast<int>(txt::FontWeight::w900));
return static_cast<txt::FontWeight>(txt_weight);
}
txt::FontStyle GetTxtFontStyle(SkFontStyle::Slant font_slant) {
return font_slant == SkFontStyle::Slant::kUpright_Slant
? txt::FontStyle::normal
: txt::FontStyle::italic;
}
TextStyle SkiaToTxt(const skt::TextStyle& skia) {
TextStyle txt;
txt.color = skia.getColor();
txt.decoration = static_cast<TextDecoration>(skia.getDecorationType());
txt.decoration_color = skia.getDecorationColor();
txt.decoration_style =
static_cast<TextDecorationStyle>(skia.getDecorationStyle());
txt.decoration_thickness_multiplier =
SkScalarToDouble(skia.getDecorationThicknessMultiplier());
txt.font_weight = GetTxtFontWeight(skia.getFontStyle().weight());
txt.font_style = GetTxtFontStyle(skia.getFontStyle().slant());
txt.text_baseline = static_cast<TextBaseline>(skia.getTextBaseline());
for (const SkString& font_family : skia.getFontFamilies()) {
txt.font_families.emplace_back(font_family.c_str());
}
txt.font_size = SkScalarToDouble(skia.getFontSize());
txt.letter_spacing = SkScalarToDouble(skia.getLetterSpacing());
txt.word_spacing = SkScalarToDouble(skia.getWordSpacing());
txt.height = SkScalarToDouble(skia.getHeight());
txt.locale = skia.getLocale().c_str();
if (skia.hasBackground()) {
txt.background = skia.getBackground();
}
if (skia.hasForeground()) {
txt.foreground = skia.getForeground();
}
txt.text_shadows.clear();
for (const skt::TextShadow& skia_shadow : skia.getShadows()) {
txt::TextShadow shadow;
shadow.offset = skia_shadow.fOffset;
shadow.blur_sigma = skia_shadow.fBlurSigma;
shadow.color = skia_shadow.fColor;
txt.text_shadows.emplace_back(shadow);
}
return txt;
}
} // anonymous namespace
ParagraphSkia::ParagraphSkia(std::unique_ptr<skt::Paragraph> paragraph)
: paragraph_(std::move(paragraph)) {}
double ParagraphSkia::GetMaxWidth() {
return SkScalarToDouble(paragraph_->getMaxWidth());
}
double ParagraphSkia::GetHeight() {
return SkScalarToDouble(paragraph_->getHeight());
}
double ParagraphSkia::GetLongestLine() {
return SkScalarToDouble(paragraph_->getLongestLine());
}
std::vector<LineMetrics>& ParagraphSkia::GetLineMetrics() {
if (!line_metrics_) {
std::vector<skt::LineMetrics> metrics;
paragraph_->getLineMetrics(metrics);
line_metrics_.emplace();
line_metrics_styles_.reserve(
std::accumulate(metrics.begin(), metrics.end(), 0,
[](const int a, const skt::LineMetrics& b) {
return a + b.fLineMetrics.size();
}));
for (const skt::LineMetrics& skm : metrics) {
LineMetrics& txtm = line_metrics_->emplace_back(
skm.fStartIndex, skm.fEndIndex, skm.fEndExcludingWhitespaces,
skm.fEndIncludingNewline, skm.fHardBreak);
txtm.ascent = skm.fAscent;
txtm.descent = skm.fDescent;
txtm.unscaled_ascent = skm.fUnscaledAscent;
txtm.height = skm.fHeight;
txtm.width = skm.fWidth;
txtm.left = skm.fLeft;
txtm.baseline = skm.fBaseline;
txtm.line_number = skm.fLineNumber;
for (const auto& sk_iter : skm.fLineMetrics) {
const skt::StyleMetrics& sk_style_metrics = sk_iter.second;
line_metrics_styles_.push_back(SkiaToTxt(*sk_style_metrics.text_style));
txtm.run_metrics.emplace(
std::piecewise_construct, std::forward_as_tuple(sk_iter.first),
std::forward_as_tuple(&line_metrics_styles_.back(),
sk_style_metrics.font_metrics));
}
}
}
return line_metrics_.value();
}
double ParagraphSkia::GetMinIntrinsicWidth() {
return SkScalarToDouble(paragraph_->getMinIntrinsicWidth());
}
double ParagraphSkia::GetMaxIntrinsicWidth() {
return SkScalarToDouble(paragraph_->getMaxIntrinsicWidth());
}
double ParagraphSkia::GetAlphabeticBaseline() {
return SkScalarToDouble(paragraph_->getAlphabeticBaseline());
}
double ParagraphSkia::GetIdeographicBaseline() {
return SkScalarToDouble(paragraph_->getIdeographicBaseline());
}
bool ParagraphSkia::DidExceedMaxLines() {
return paragraph_->didExceedMaxLines();
}
void ParagraphSkia::Layout(double width) {
line_metrics_.reset();
line_metrics_styles_.clear();
paragraph_->layout(width);
}
void ParagraphSkia::Paint(SkCanvas* canvas, double x, double y) {
paragraph_->paint(canvas, x, y);
}
std::vector<Paragraph::TextBox> ParagraphSkia::GetRectsForRange(
size_t start,
size_t end,
RectHeightStyle rect_height_style,
RectWidthStyle rect_width_style) {
std::vector<skt::TextBox> skia_boxes = paragraph_->getRectsForRange(
start, end, static_cast<skt::RectHeightStyle>(rect_height_style),
static_cast<skt::RectWidthStyle>(rect_width_style));
std::vector<Paragraph::TextBox> boxes;
for (const skt::TextBox& skia_box : skia_boxes) {
boxes.emplace_back(skia_box.rect,
static_cast<TextDirection>(skia_box.direction));
}
return boxes;
}
std::vector<Paragraph::TextBox> ParagraphSkia::GetRectsForPlaceholders() {
std::vector<skt::TextBox> skia_boxes = paragraph_->getRectsForPlaceholders();
std::vector<Paragraph::TextBox> boxes;
for (const skt::TextBox& skia_box : skia_boxes) {
boxes.emplace_back(skia_box.rect,
static_cast<TextDirection>(skia_box.direction));
}
return boxes;
}
Paragraph::PositionWithAffinity ParagraphSkia::GetGlyphPositionAtCoordinate(
double dx,
double dy) {
skt::PositionWithAffinity skia_pos =
paragraph_->getGlyphPositionAtCoordinate(dx, dy);
return ParagraphSkia::PositionWithAffinity(
skia_pos.position, static_cast<Affinity>(skia_pos.affinity));
}
Paragraph::Range<size_t> ParagraphSkia::GetWordBoundary(size_t offset) {
skt::SkRange<size_t> range = paragraph_->getWordBoundary(offset);
return Paragraph::Range<size_t>(range.start, range.end);
}
} // namespace txt
| 32.223744 | 80 | 0.714468 | [
"vector"
] |
2bf43b471141af370b4b3410ed4a35b9d28d8727 | 11,981 | cpp | C++ | tests/api_tests/zendnn_conv_test.cpp | amd/ZenDNN | 2d8e025a05126b7c378d88a990a20e21a4182b20 | [
"Apache-2.0"
] | 28 | 2021-08-12T10:38:06.000Z | 2022-03-25T08:37:31.000Z | tests/api_tests/zendnn_conv_test.cpp | amd/ZenDNN | 2d8e025a05126b7c378d88a990a20e21a4182b20 | [
"Apache-2.0"
] | 2 | 2021-08-17T03:20:10.000Z | 2021-09-23T04:15:32.000Z | tests/api_tests/zendnn_conv_test.cpp | amd/ZenDNN | 2d8e025a05126b7c378d88a990a20e21a4182b20 | [
"Apache-2.0"
] | 5 | 2021-08-20T05:05:59.000Z | 2022-02-25T19:13:07.000Z | /*******************************************************************************
* Modifications Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
* Notified per clause 4(b) of the license.
*******************************************************************************/
/*******************************************************************************
* Copyright 2016-2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/* Steps:
*
* 1. create engin and stream
* 2. create user memory (source, weights, destination)
* 3. create memory descriptor
* 4. create convolution descriptor
* 5. create convolution primitive descriptor
* 6. create convolution primitive
* 7. execute the convlution
* 8. create ReLU desciptor
* 9. create ReLU primitive descriptor
* 10. create ReLU primitive
* 11. execute ReLU
*/
//IMP => export ZENDNN_VERBOSE=1
//ZENDNN_VERBOSE=1 bin/simple_conv_test cpu
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <chrono>
#include <iostream>
#include <vector>
#include <assert.h>
#include <cmath>
#include <fstream>
#include <numeric>
#include <string>
#include <math.h>
#include <cstdlib>
#include <unistd.h>
#include <string.h>
#include "test_utils.hpp"
#include "zendnn_logging.hpp"
#define ZENDNN_CMP_OUTPUT 1
using namespace std;
using namespace zendnn;
//set stride and padding
const memory::dims strides = {2, 2};
const memory::dims padding = {2, 2};
float *transpose(const float *matrix, int n, int m, float *transposed) {
int i = 0;
int j = 0;
float num;
//float *transposed=(float *)malloc(sizeof(float)*n*m);
if (transposed == NULL) {
zendnnError(ZENDNN_ALGOLOG, "transpose Memory Error");
}
while (i < n) {
j = 0;
while (j < m) {
num = *(matrix + i*m + j);
*(transposed + i+n*j) = num;
j++;
}
i++;
}
return transposed;
}
void nchw2nhwc(zendnn::memory &in,int N, int C, int H, int W, zendnn::memory &out) {
float *in_data= (float *)in.get_data_handle();
float *out_data= (float *)out.get_data_handle();
for (int n = 0; n < N; n++) {
int in_batch_offset = n * C * H * W;
int out_batch_offset = n * H * W * C;
for (int c = 0; c < C; ++c) {
int in_ch_offset = c * H * W + in_batch_offset;
int out_ch_offset = out_batch_offset + c;
for (int h = 0; h < H; ++h) {
int in_row_offset = h * W + in_ch_offset;
int out_row_offset = out_ch_offset + h * W * C;
for (int w = 0; w < W; ++w) {
int in_addr = w + in_row_offset;
int out_addr = out_row_offset + w * C;
out_data[out_addr] = in_data[in_addr];
}
}
}
}
}
//function to init data
void init_data(memory &m, float v) {
size_t size = m.get_desc().get_size() /sizeof(float);
//std::vector<float> data(size);
srand(1111);
float *data= (float *)m.get_data_handle();
for (size_t i = 0; i < size; ++i) {
data[i] = rand()%5;
}
}
//function to exeute non-fused relu
void create_and_execute_relu(memory &data, engine &eng, stream &s) {
//relu operates on whatever data format is given to it
//create a desciptor
auto relu_d = eltwise_forward::desc(prop_kind::forward_inference,
algorithm::eltwise_relu, data.get_desc(), 0.f, 0.f);
//create a relu primitive descriptor
auto relu_pd = eltwise_forward::primitive_desc(relu_d, eng);
//create a relu primitive
auto relu = eltwise_forward(relu_pd);
//execute in-place
relu.execute(s, {{ZENDNN_ARG_SRC, data}, {ZENDNN_ARG_DST, data}});
}
// Implementation for the naive convlolution on the nchw (data) and oihw (weights),
// followed by execution of non-fused relu
void conv_relu_naive(memory user_src, memory user_wei, memory user_dst, memory user_bias,
engine &eng, stream &s) {
//Create mem_desc
//copy the dimesnions and formats from user's memory
//First it sets the dimensions and format for the convolution memory descriptor (_md) to match user_ value
//for source, destonation and weight data.
//Then it uses those md to create the convolution descriptor conv_d which tells ZENDNN to use plain foramt
//(NCHW) for the convolution
auto conv_src_md = memory::desc(user_src.get_desc());
auto conv_wei_md = memory::desc(user_wei.get_desc());
auto conv_dst_md = memory::desc(user_dst.get_desc());
auto conv_bias_md = memory::desc(user_bias.get_desc());
//Next program creates a convolution descriptor, primitive descriptor conv_pd and convolution primitive conv
//These structs will inherit NCHW format from md by way of conv_d
//Finally it creates the convolution primitive conv and adds it to stream s, and then executes the
//create_and_execute_relu(user_dst) pfunction
//create a convolution descriptor
auto conv_d = convolution_forward::desc(prop_kind::forward_inference,
#if !ZENDNN_ENABLE
algorithm::convolution_direct,
#else
algorithm::convolution_gemm,
#endif
conv_src_md, conv_wei_md, conv_bias_md,
conv_dst_md, strides, padding, padding);
//create a convolution primitive descriptor
auto conv_pd = convolution_forward::primitive_desc(conv_d, eng);
//create convolution primitive
auto conv = convolution_forward(conv_pd);
//execute convolution by adding it to the stream s
conv.execute(s, {
{ZENDNN_ARG_SRC, user_src}, {ZENDNN_ARG_WEIGHTS, user_wei},{ZENDNN_ARG_BIAS, user_bias},
{ZENDNN_ARG_DST, user_dst}
});
//execute relu (on convolution's destination format, whatever it is )
//create_and_execute_relu(user_dst, eng, s);
}
int main(int argc, char **argv) {
zendnnInfo(ZENDNN_TESTLOG, "ZenDNN API test starts");
ofstream file;
//initialize the engine
if (argc <= 1) {
zendnnInfo(ZENDNN_TESTLOG, "The command to run this test");
zendnnInfo(ZENDNN_TESTLOG, "ZENDNN_VERBOSE=1 bin/simple_conv_test cpu");
return -1;
}
zendnn::engine::kind engine_kind = parse_engine_kind(argc, argv, 1);
//initialize engine
zendnn::engine eng(engine_kind, 0);
zendnnInfo(ZENDNN_TESTLOG, "engine created");
//initialize stream
stream s(eng);
zendnnInfo(ZENDNN_TESTLOG, "stream created");
//Set dimensions for synthetic data and weights
const memory::dim BATCH = 100;
const memory::dim IC = 3, OC = 64;
const memory::dim IH = 224, KH = 7, OH = 111;
const memory::dim IW = 224, KW = 7, OW = 111;
int batch = 100;
int input_h = 224;
int kernel_h = 7;
int output_h = 111;
int padding = 2;
int stride = 2;
int channel = 3;
int filters = 64;
//const memory::dim IH = 224, KH = 1, OH = 114;
//const memory::dim IW = 224, KW = 1, OW = 114;
//create ZENDNN memory objects in NCHW format. They are called user_ because they are meant to represent
//the user's source data entering ZENDNN with NCHW format
//create ZENDNN memory objct for user's tensors (in nchw and oihw format)
//here library allocate memory
auto user_src = memory({{BATCH, IC, IH, IW}, memory::data_type::f32,
memory::format_tag::nhwc
},
eng);
#if !ZENDNN_ENABLE
auto user_wei = memory({{OC, IC, KH, KW}, memory::data_type::f32,
memory::format_tag::oihw
},
eng);
#else
auto user_wei3 = memory({{OC, IC, KH, KW}, memory::data_type::f32,
memory::format_tag::oihw
},
eng);
auto user_wei2 = memory({{OC, IC, KH, KW}, memory::data_type::f32,
memory::format_tag::oihw
},
eng);
auto user_wei = memory({{OC, IC, KH, KW}, memory::data_type::f32,
memory::format_tag::oihw
},
eng);
#endif
auto user_dst = memory({{BATCH, OC, OH, OW}, memory::data_type::f32,
memory::format_tag::nhwc
},
eng);
auto user_bias = memory({{OC}, memory::data_type::f32,
memory::format_tag::x
}, eng);
zendnnInfo(ZENDNN_TESTLOG, "ZENDNN memory objects created");
//Fill source, destination and weights with synthetic data
init_data(user_src, 1);
init_data(user_dst, -1);
#if !ZENDNN_ENABLE
init_data(user_wei, .5);
#else
init_data(user_wei3, .5);
nchw2nhwc(user_wei3, OC, IC, KH, KW, user_wei2);
float *in_data= (float *)user_wei2.get_data_handle();
transpose(in_data, OC, IC*KH*KW, (float *)user_wei.get_data_handle());
#endif
init_data(user_bias, .5);
zendnnInfo(ZENDNN_TESTLOG, "implementation: naive");
//run conv + relu without fusing
conv_relu_naive(user_src, user_wei, user_dst, user_bias, eng, s);
zendnnInfo(ZENDNN_TESTLOG, "conv + relu w/ nchw completed");
//Dump the output buffer to a file
const char *zenDnnRootPath = getenv("ZENDNN_GIT_ROOT");
#if !ZENDNN_ENABLE
file.open(zenDnnRootPath + std::string("/_out/tests/ref_conv_output"));
#else
file.open(zenDnnRootPath + std::string("/_out/tests/zendnn_conv_output"));
#endif //ZENDNN_ENABLE
double sum = 0;
size_t size = user_dst.get_desc().get_size() /sizeof(float);
float *dataHandle= (float *)user_dst.get_data_handle();
for (size_t i = 0; i < size; ++i) {
sum += dataHandle[i];
}
//write the dataHandle to the file
file.write(reinterpret_cast<char const *>(dataHandle), user_dst.get_desc().get_size());
file.close();
#if !ZENDNN_ENABLE
zendnnInfo(ZENDNN_TESTLOG, "Ref API test: SUM: ", sum);
string str = std::string("sha1sum ") + zenDnnRootPath +
std::string("/_out/tests/ref_conv_output > ") + zenDnnRootPath +
std::string("/tests/api_tests/sha_out_NHWC/ref_conv_output.sha1");
#else
zendnnInfo(ZENDNN_TESTLOG, "ZENDNN API test: SUM: ", sum);
string str = std::string("sha1sum ") + zenDnnRootPath +
std::string("/_out/tests/zendnn_conv_output > ") + zenDnnRootPath +
std::string("/_out/tests/zendnn_conv_output.sha1");
#endif
//Convert string to const char * as system requires
//parameters of the type const char *
const char *command = str.c_str();
int status = system(command);
#if ZENDNN_CMP_OUTPUT //compare SHA1 value
ifstream zenDnnSha1(zenDnnRootPath + std::string("/_out/tests/zendnn_conv_output.sha1"));
string firstWordZen;
while (zenDnnSha1 >> firstWordZen) {
zendnnInfo(ZENDNN_TESTLOG, "ZenDNN output SHA1 value: ", firstWordZen);
zenDnnSha1.ignore(numeric_limits<streamsize>::max(), '\n');
}
ifstream refSha1(zenDnnRootPath +
std::string("/tests/api_tests/sha_out_NHWC/ref_conv_output.sha1"));
string firstWordRef;
while (refSha1 >> firstWordRef) {
zendnnInfo(ZENDNN_TESTLOG, "Ref output SHA1 value: ", firstWordRef);
refSha1.ignore(numeric_limits<streamsize>::max(), '\n');
}
ZENDNN_CHECK(firstWordZen == firstWordRef, ZENDNN_TESTLOG,
"sha1 /sha1sum value of ZenDNN output and Ref output do not matches");
#endif //ZENDNN_CMP_OUTPUT compare SHA1 value
zendnnInfo(ZENDNN_TESTLOG, "ZenDNN API test ends");
return 0;
}
| 34.036932 | 112 | 0.63175 | [
"vector"
] |
2bfc105f07ceeae138ec1c434a015982c65f551a | 12,780 | cpp | C++ | hamming_dec.cpp | eduardolucioac/cpphamming | d035593d804b13a014180eec5cc93e301e44d331 | [
"Apache-2.0"
] | 5 | 2016-11-04T20:01:09.000Z | 2021-12-21T23:42:01.000Z | hamming_dec.cpp | eduardolucioac/cpphamming | d035593d804b13a014180eec5cc93e301e44d331 | [
"Apache-2.0"
] | null | null | null | hamming_dec.cpp | eduardolucioac/cpphamming | d035593d804b13a014180eec5cc93e301e44d331 | [
"Apache-2.0"
] | null | null | null | /**
@file hamming_dec.cpp
@author Eduardo Lúcio Amorim Costa (Questor)
@date 11/02/2016
@version 1.0
@brief Applies the hamming method to modify and retrieve files.
@section DESCRIPTION
The Hamming code is a linear block code, was developed by Richard Hamming,
is used in signal processing and telecommunications. This application uses
this process over the bits of a file by taking them 4 out of 4.
@section LICENSE
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright 2016 Eduardo Lúcio Amorim Costa
*/
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
/**
@brief Converts a file into bytes vector.
@param char* fileName: Name of the file to be converted.
@return std::vector<unsigned char>: File in bytes array.
*/
std::vector<unsigned char> readFileBytes(const char* fileName){
// Open the file.
std::ifstream file(fileName, std::ios::binary);
// Stop eating new lines in binary mode.
file.unsetf(std::ios::skipws);
// Get its size.
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
// Reserve capacity.
std::vector<unsigned char> vec;
vec.reserve(fileSize);
// Read the data.
vec.insert(vec.begin(),
std::istream_iterator<unsigned char>(file),
std::istream_iterator<unsigned char>());
return vec;
}
/**
@brief Convert a vector of bytes to a file.
@param char* fileName: Name of the file to be written to the current
directory.
@param std::vector<unsigned char> fileBytes: File in bytes.
@return void.
*/
void writeFileBytes(const char* fileName, std::vector<unsigned char> fileBytes){
std::ofstream file(fileName, std::ios::out|std::ios::binary);
std::copy(fileBytes.cbegin(), fileBytes.cend(),
std::ostream_iterator<unsigned char>(file));
}
/**
@brief Convert bytes to bits.
@param std::vector<unsigned char> bytesArray: File Bytes.
@return std::vector<bool>: File in bits.
*/
std::vector<bool> bytesToBits(std::vector<unsigned char> bytesArray){
std::vector<bool> boolBitsArray;
std::vector<bool> oneByteBits;
int bytesArrayCount = bytesArray.size() - 1;
for( ; bytesArrayCount > -1; bytesArrayCount--){
for(int o=7; o >= 0; o--){
oneByteBits.push_back(((bytesArray[bytesArrayCount] >> o) & 1));
// [Ref.: http://www.cplusplus.com/reference/vector/vector/resize/]
// Reduces the size of the vector to free up memory.
bytesArray.resize(bytesArrayCount + 1);
// [Ref.: http://stackoverflow.com/questions/16173887/how-to-reduce-the-size-of-vector-when-removing-elements-from-it]
// [Ref.: http://stackoverflow.com/questions/1111078/reduce-the-capacity-of-an-stl-vector]
// Ensures that the allocated vector space will also be reduced.
std::vector<unsigned char>(bytesArray).swap(bytesArray);
}
// Invert then you can then put the boolBitsArray array in the correct order.
std::reverse(oneByteBits.begin(), oneByteBits.end());
boolBitsArray.insert(std::end(boolBitsArray), std::begin(oneByteBits), std::end(oneByteBits));
oneByteBits.clear();
}
// Put in the correct order.
std::reverse(boolBitsArray.begin(), boolBitsArray.end());
return boolBitsArray;
}
/**
@brief Convert bits into bytes.
@param std::vector<bool> bitsArray: File bits.
@param int byteAdjust=0 [Optional]: 1 - Complete with zeros the array of
bits to be a multiple of 8 (byte); 2 - Does not complete with zeros. Default 0.
@return std::vector<unsigned char>: File in bytes.
*/
std::vector<unsigned char> bitsToBytes(std::vector<bool> bitsArray, int byteAdjust=0){
if(byteAdjust == 1){
/**
The calculation below is to adjust the size of the array of bits
("bitsArray") to be equal to a multiple of 8 (size of the byte)
completing with zeros! The reason for this is because the smaller
possible data unit for c/c++ is 1 byte (8 bits).
*/
int boolBitsArraySize=bitsArray.size();
if((boolBitsArraySize%8) > 0){
int adjustFactor=((((int)boolBitsArraySize/8)+1)*8)-boolBitsArraySize;
for(int z=0; z < adjustFactor; z++){
bitsArray.push_back(0);
}
}
}
int bit8Count=0;
std::vector<bool> bit8Array;
unsigned char charByte;
std::vector<unsigned char> bytesArray;
// The array is read back-to-back to free up memory using the "resize"
// and "swap" operations.
int boolBitsArrayCount = bitsArray.size() - 1;
for( ; boolBitsArrayCount > -1; boolBitsArrayCount--){
if(bit8Count < 8){
bit8Array.push_back(bitsArray[boolBitsArrayCount]);
bit8Count++;
}
if(bit8Count == 8){
// [Ref.: http://www.cplusplus.com/reference/vector/vector/resize/]
// Reduces the size of the vector to free up memory.
bitsArray.resize(boolBitsArrayCount + 1);
// [Ref.: http://stackoverflow.com/questions/16173887/how-to-reduce-the-size-of-vector-when-removing-elements-from-it]
// [Ref.: http://stackoverflow.com/questions/1111078/reduce-the-capacity-of-an-stl-vector]
// Ensures that the allocated vector space will also be reduced.
std::vector<bool>(bitsArray).swap(bitsArray);
// It resets in the correct default order, because the treatment
// scheme below is already reversed.
charByte = (bit8Array[0] ) |
(bit8Array[1] << 1) |
(bit8Array[2] << 2) |
(bit8Array[3] << 3) |
(bit8Array[4] << 4) |
(bit8Array[5] << 5) |
(bit8Array[6] << 6) |
(bit8Array[7] << 7);
bytesArray.push_back(charByte);
bit8Array.clear();
bit8Count=0;
}
}
std::reverse(bytesArray.begin(), bytesArray.end());
return bytesArray;
}
/**
@brief Correct by applying the hamming method.
@param std::vector<bool> hamming7Bit: 7 bits in the hamming form
containing the 4 original bits.
@return std::vector<bool>: 4 original bits.
*/
std::vector<bool> hammingCorrection(std::vector<bool> hamming7Bit){
std::vector<bool> xorOddBitsPos;
std::vector<bool> original4Bit;
bool e;
int f;
for(int hamming7BitCount=0; hamming7BitCount < hamming7Bit.size(); hamming7BitCount++){
if(hamming7Bit[hamming7BitCount] == 1){
/**
Verifies what are the odd bits (1) and their positions
in the hamming logic (7~1) and stored in an array 3 to
3.
*/
/**
Adjusting the position of the calculation logic (hamming) to
the position in the array.
*/
f=7-hamming7BitCount;
for(int w = 2; w >= 0; w--){
e = ((f >> w) & 1);
xorOddBitsPos.push_back(e);
}
}
}
/**
They get the position of the bit to be inverted/corrected by taking
the array as groups of 3 and accessing the "indexes" 0, 1 and 2 of
each of these groups of three in that order and running an XOR between
them.
*/
bool corrPosBits[8]={0, 0, 0, 0, 0, 0, 0, 0};
if(xorOddBitsPos.size() > 0){
int octalBitPos;
int xorNumCount;
for(int octalBitGroupPos=0; octalBitGroupPos < 3; octalBitGroupPos++){
xorNumCount=0;
octalBitPos=octalBitGroupPos;
for(int xorBitsCount=0; xorBitsCount < (xorOddBitsPos.size()/3); xorBitsCount++){
if(xorOddBitsPos[octalBitPos] == 1){
xorNumCount++;
}
octalBitPos=octalBitPos+3;
}
if(xorNumCount%2 == 0){
corrPosBits[(octalBitGroupPos+5)]=0; // even
}else{
corrPosBits[(octalBitGroupPos+5)]=1; // odd
}
}
}
// Bit (position) to be corrected/inverted (converts the position value
// into bits for int).
int flipBit = (corrPosBits[7] ) |
(corrPosBits[6] << 1) |
(corrPosBits[5] << 2) |
(corrPosBits[4] << 3) |
(corrPosBits[3] << 4) |
(corrPosBits[2] << 5) |
(corrPosBits[1] << 6) |
(corrPosBits[0] << 7);
/**
If flipBit equals zero, then there are no fixes to be made.
*/
if(flipBit > 0){
// Transform the correction index into the vector index.
flipBit=7-flipBit;
// Scheme to invert one of the bits for the correction.
hamming7Bit[flipBit]=!hamming7Bit[flipBit];
}
// original4Bit contains the original 4 bits. As the source reading is
// done from forward to back we also invert here to adjust.
original4Bit.push_back(hamming7Bit[4]);
original4Bit.push_back(hamming7Bit[2]);
original4Bit.push_back(hamming7Bit[1]);
original4Bit.push_back(hamming7Bit[0]);
return original4Bit;
}
/**
@brief Correct by applying the hamming method.
@param std::vector<bool> boolBitsArray: Contains the bits of the file in
the hamming format. The bits will be taken 7-by-7.
@return std::vector<bool>: Original Bits.
*/
std::vector<bool> removeHammingParity(std::vector<bool> boolBitsArray){
int bit7Count=0;
std::vector<bool> bit7Array;
std::vector<bool> bit4Array;
std::vector<bool> originalBits;
/**
"boolBitsArray" will always have a size greater than or equal to the
largest multiple of 7 that "fits" inside it.
The array is read backwards to free up memory using the "resize" and
"swap" operations.
*/
int boolBitsArrayCount = ((((int)boolBitsArray.size()/7)*7) - 1);
for( ; boolBitsArrayCount > -1; boolBitsArrayCount--){
if(bit7Count < 7){
bit7Array.push_back(boolBitsArray[boolBitsArrayCount]);
bit7Count++;
}
if(bit7Count == 7){
// [Ref.: http://www.cplusplus.com/reference/vector/vector/resize/]
// Reduces the size of the vector to free up memory.
boolBitsArray.resize(boolBitsArrayCount + 1);
// [Ref.: http://stackoverflow.com/questions/16173887/how-to-reduce-the-size-of-vector-when-removing-elements-from-it]
// [Ref.: http://stackoverflow.com/questions/1111078/reduce-the-capacity-of-an-stl-vector]
// Ensures that the allocated vector space will also be reduced.
std::vector<bool>(boolBitsArray).swap(boolBitsArray);
// Replaces in the correct default order.
std::reverse(bit7Array.begin(), bit7Array.end());
bit4Array=hammingCorrection(bit7Array);
bit7Array.clear();
originalBits.insert(std::end(originalBits), std::begin(bit4Array), std::end(bit4Array));
bit4Array.clear();
bit7Count=0;
}
}
std::reverse(originalBits.begin(), originalBits.end());
return originalBits;
}
/**
@brief Control and retrieve using the hamming method.
@param char* flNameFrom: File to recover with hamming method.
@param char* flNameTo: Name of the file to be recovered with the hamming
method.
@return void.
*/
void recoverHamming(const char* flNameFrom, const char* flNameTo){
/**
The functions have been placed one inside the others so that the
memory is released immediately after the return of the operation.
Before we were duplicating the values (in memory) several times
because we were hosting them in variables unnecessarily!
*/
writeFileBytes(flNameTo,
bitsToBytes(
removeHammingParity(
bytesToBits(
readFileBytes(flNameFrom)
)
)
)
);
}
int main(int argc, char *argv[]){
const char* flNameFrom = argv[1];
const char* flNameTo = argv[2];
printf("%s", "> ---------------------------------------------\n");
printf("Correcting error!\n");
printf("%s", "\n< ---------------------------------------------\n");
recoverHamming(flNameFrom, flNameTo);
return 0;
}
| 34.447439 | 130 | 0.591393 | [
"vector",
"transform"
] |
2bfe885f18110ea1e45eb43e8d24c04a2977cc5a | 2,915 | cpp | C++ | 2020/day14/B.cpp | mpeyrotc/adventofcode | 7eed772462af5c960010eaf9f54b3b586e12581b | [
"MIT"
] | null | null | null | 2020/day14/B.cpp | mpeyrotc/adventofcode | 7eed772462af5c960010eaf9f54b3b586e12581b | [
"MIT"
] | null | null | null | 2020/day14/B.cpp | mpeyrotc/adventofcode | 7eed772462af5c960010eaf9f54b3b586e12581b | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <regex>
#include <map>
#include <numeric>
using namespace std;
typedef long long ll;
string parseMaskString(ll mask)
{
string result{ "000000000000000000000000000000000000" };
ll m{ 1 };
size_t shiftValue{ result.size() - 1 };
while (mask != 0)
{
if ((mask & m) != 0)
{
result.at(shiftValue) = '1';
}
mask = mask >> 1;
--shiftValue;
}
return result;
}
ll parseMask(string mask)
{
ll result{ 0 };
for (size_t shiftValue{ mask.size() - 1 }, index{ 0 }; const char c : mask)
{
char maskBit{ mask.at(index) };
if (maskBit == '1')
{
result |= (static_cast<ll>(1LL) << shiftValue);
}
--shiftValue;
++index;
}
return result;
}
int main()
{
regex maskRegex("mask = ([X10]{36})");
regex instructionRegex("mem\\[([0-9]+)\\] = ([0-9]+)");
map<string, ll> memory;
string line;
string maskString;
while (getline(cin, line))
{
if (smatch match; regex_search(line, match, maskRegex))
{
maskString = match[1];
}
else if (regex_search(line, match, instructionRegex))
{
ll memAddress{ stoll(match[1]) };
ll value{ stoll(match[2]) };
vector<string> candidateAddresses{ parseMaskString(memAddress) };
for (size_t i{ 0 }; i < maskString.size(); ++i)
{
if (maskString.at(i) == 'X')
{
for (size_t j{ 0 }; j < candidateAddresses.size(); ++j)
{
candidateAddresses.at(j).at(i) = '1';
}
size_t jSize{ candidateAddresses.size() };
for (size_t j{ 0 }; j < jSize; ++j)
{
string newAddress = candidateAddresses.at(j);
newAddress.at(i) = '0';
candidateAddresses.push_back(newAddress);
}
}
else if (maskString.at(i) == '1')
{
for (size_t j{ 0 }; j < candidateAddresses.size(); ++j)
{
candidateAddresses.at(j).at(i) = '1';
}
}
}
for (auto candidateAddress : candidateAddresses)
{
if (memory.contains(candidateAddress))
{
memory.at(candidateAddress) = value;
}
else
{
memory.emplace(candidateAddress, value);
}
}
}
}
ll total{ 0 };
for (const auto& p : memory)
{
total += p.second;
}
cout << total << endl;
return 0;
} | 23.893443 | 79 | 0.439108 | [
"vector"
] |
92052f52dafe6a3f9351505f406fd64c2b7fc13a | 703 | cpp | C++ | code/tsp.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 8 | 2020-02-21T22:21:01.000Z | 2022-02-16T05:30:54.000Z | code/tsp.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | null | null | null | code/tsp.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 3 | 2020-08-05T05:42:35.000Z | 2021-08-30T05:39:51.000Z | #define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_set>
#include <ctype.h>
#include <queue>
#include <map>
typedef long long ll;
using namespace std;
int main()
{
ll i, j, k;
ll cases;
double garb;
cin >> cases;
pair <double, int> temp;
vector<pair<double, int>> bodge;
for (i = 0; i < cases; i++)
{
cin >> garb;
temp.first = garb;
temp.second = i;
cin >> garb;
bodge.push_back(temp);
}
sort(bodge.begin(), bodge.end());
for (i = 0; i < cases; i++)
{
cout << bodge[i].second << "\n";
}
}
| 16.348837 | 40 | 0.55761 | [
"vector"
] |
92064fd0f12af0f0d5796912cc6283e4bffeafb1 | 3,524 | cpp | C++ | test/utils_utils/interleave.cpp | h6ah4i/cxxdasp | 44bf437ad688760265ea10d2dc7cb3c57e0e7008 | [
"Apache-2.0"
] | 35 | 2015-01-28T07:49:02.000Z | 2020-10-04T17:38:46.000Z | test/utils_utils/interleave.cpp | h6ah4i/cxxdasp | 44bf437ad688760265ea10d2dc7cb3c57e0e7008 | [
"Apache-2.0"
] | 1 | 2018-02-16T10:45:19.000Z | 2018-02-21T19:04:57.000Z | test/utils_utils/interleave.cpp | h6ah4i/cxxdasp | 44bf437ad688760265ea10d2dc7cb3c57e0e7008 | [
"Apache-2.0"
] | 10 | 2015-01-28T07:49:02.000Z | 2022-03-08T00:51:51.000Z | //
// Copyright (C) 2014 Haruki Hasegawa
//
// 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 "test_common.hpp"
#include <cxxporthelper/aligned_memory.hpp>
using namespace cxxdasp;
template <typename T>
class InterleaveTest : public ::testing::Test {
protected:
virtual void SetUp() { cxxdasp_init(); }
virtual void TearDown() {}
public:
typedef T value_type;
};
template <typename T>
class DeinterleaveTest : public ::testing::Test {
protected:
virtual void SetUp() { cxxdasp_init(); }
virtual void TearDown() {}
public:
typedef T value_type;
};
typedef InterleaveTest<float> InterleaveTest_Float;
typedef InterleaveTest<double> InterleaveTest_Double;
typedef DeinterleaveTest<float> DeinterleaveTest_Float;
typedef DeinterleaveTest<double> DeinterleaveTest_Double;
template <typename TInterleaveTest>
void do_interleave_test(TInterleaveTest *thiz, int n)
{
typedef typename TInterleaveTest::value_type value_type;
std::vector<value_type> in_data1;
std::vector<value_type> in_data2;
std::vector<value_type> expected;
std::vector<value_type> out_data;
for (int i = 0; i < n; ++i) {
in_data1.push_back(static_cast<float>(i));
in_data2.push_back(static_cast<float>(i * 2));
}
for (int i = 0; i < n; ++i) {
expected.push_back(in_data1[i]);
expected.push_back(in_data2[i]);
}
out_data.resize(2 * n);
utils::interleave(&out_data[0], &in_data1[0], &in_data2[0], n);
for (int i = 0; i < n; ++i) {
ASSERT_EQ(expected[2 * i + 0], out_data[2 * i + 0]);
ASSERT_EQ(expected[2 * i + 1], out_data[2 * i + 1]);
}
}
template <typename TInterleaveTest>
void do_deinterleave_test(TInterleaveTest *thiz, int n)
{
typedef typename TInterleaveTest::value_type value_type;
std::vector<value_type> in_data;
std::vector<value_type> expected1;
std::vector<value_type> expected2;
std::vector<value_type> out_data1;
std::vector<value_type> out_data2;
for (int i = 0; i < (2 * n); ++i) {
in_data.push_back(static_cast<float>(i));
}
for (int i = 0; i < n; ++i) {
expected1.push_back(in_data[2 * i + 0]);
expected2.push_back(in_data[2 * i + 1]);
}
out_data1.resize(n);
out_data2.resize(n);
utils::deinterleave(&out_data1[0], &out_data2[0], &in_data[0], n);
for (int i = 0; i < n; ++i) {
ASSERT_EQ(expected1[i], out_data1[i]);
ASSERT_EQ(expected2[i], out_data2[i]);
}
}
//
// utils::interleave(float *dest, const float *src1, const float *src2, int n)
//
TEST_F(InterleaveTest_Float, interleave) { do_interleave_test(this, 1000); }
TEST_F(InterleaveTest_Double, interleave) { do_interleave_test(this, 1000); }
//
// utils::deinterleave(float *dest1, float *dest2, const float *src, int n)
//
TEST_F(DeinterleaveTest_Float, deinterleave) { do_deinterleave_test(this, 1000); }
TEST_F(DeinterleaveTest_Double, deinterleave) { do_deinterleave_test(this, 1000); }
| 29.123967 | 83 | 0.679058 | [
"vector"
] |
920ae3f66461c20facab064cf75d10f2000fd811 | 2,145 | cpp | C++ | sis/src/v1/model/PhonemePronunciation.cpp | ChenwxJay/huaweicloud-sdk-cpp-v3 | f821ec6d269b50203e0c1638571ee1349c503c41 | [
"Apache-2.0"
] | 1 | 2021-11-30T09:31:16.000Z | 2021-11-30T09:31:16.000Z | sis/src/v1/model/PhonemePronunciation.cpp | ChenwxJay/huaweicloud-sdk-cpp-v3 | f821ec6d269b50203e0c1638571ee1349c503c41 | [
"Apache-2.0"
] | null | null | null | sis/src/v1/model/PhonemePronunciation.cpp | ChenwxJay/huaweicloud-sdk-cpp-v3 | f821ec6d269b50203e0c1638571ee1349c503c41 | [
"Apache-2.0"
] | null | null | null |
#include "huaweicloud/sis/v1/model/PhonemePronunciation.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Sis {
namespace V1 {
namespace Model {
PhonemePronunciation::PhonemePronunciation()
{
score_ = 0.0f;
scoreIsSet_ = false;
gop_ = 0.0f;
gopIsSet_ = false;
}
PhonemePronunciation::~PhonemePronunciation() = default;
void PhonemePronunciation::validate()
{
}
web::json::value PhonemePronunciation::toJson() const
{
web::json::value val = web::json::value::object();
if(scoreIsSet_) {
val[utility::conversions::to_string_t("score")] = ModelBase::toJson(score_);
}
if(gopIsSet_) {
val[utility::conversions::to_string_t("gop")] = ModelBase::toJson(gop_);
}
return val;
}
bool PhonemePronunciation::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("score"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("score"));
if(!fieldValue.is_null())
{
float refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setScore(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("gop"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("gop"));
if(!fieldValue.is_null())
{
float refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setGop(refVal);
}
}
return ok;
}
float PhonemePronunciation::getScore() const
{
return score_;
}
void PhonemePronunciation::setScore(float value)
{
score_ = value;
scoreIsSet_ = true;
}
bool PhonemePronunciation::scoreIsSet() const
{
return scoreIsSet_;
}
void PhonemePronunciation::unsetscore()
{
scoreIsSet_ = false;
}
float PhonemePronunciation::getGop() const
{
return gop_;
}
void PhonemePronunciation::setGop(float value)
{
gop_ = value;
gopIsSet_ = true;
}
bool PhonemePronunciation::gopIsSet() const
{
return gopIsSet_;
}
void PhonemePronunciation::unsetgop()
{
gopIsSet_ = false;
}
}
}
}
}
}
| 18.333333 | 96 | 0.645221 | [
"object",
"model"
] |
920e24cb7856933551868441dafbbbb4b8d6aa3d | 2,825 | cc | C++ | leetcode/leet-45.cc | yanrong/acm | a3bbc3b07eb3eeb2535f4a732228b7e27746bfb2 | [
"Apache-2.0"
] | 4 | 2020-03-20T10:39:08.000Z | 2020-12-04T00:36:54.000Z | leetcode/leet-45.cc | yanrong/acm | a3bbc3b07eb3eeb2535f4a732228b7e27746bfb2 | [
"Apache-2.0"
] | null | null | null | leetcode/leet-45.cc | yanrong/acm | a3bbc3b07eb3eeb2535f4a732228b7e27746bfb2 | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <iostream>
#include <algorithm>
using std::max;
using std::vector;
using std::cout;
using std::endl;
class Solution {
public:
//original soultion
int jump(vector<int>& nums) {
int len = nums.size(), jump ,counter = 0, temp = 0, step, i = 0;
if(nums.size() <= 1) return 0;
jump = nums[0];
// from 0 the len -1
while(i < len){
step = 0; temp = jump;
//search the whole string in [i + 1, jump]
for(int j = 1; j <= jump && (i + j < len); j++){
if(i + jump >= len -1){ //if the index add jump great string length, skip the whole string
break;
}
//else find the max one in the jump range
//i is current valid index, j + num[i+j] update j in range jump and add it's jump value
if((i + j + nums[i + j]) > temp) {
temp = i + j + nums[i + j];
step = j;
}
}
//this step update the index i, each time we assign a zero to var step,
//so if step is zero, that meas jump in i is grate most, update i with it' jump value
//otherwise , we get best one and remember the distance from i to it, so add it up
i += (step == 0) ? jump : step;
counter++;
if(i >= len - 1) break; //this is very import, must test it
jump = nums[i] ; // update the current jump value
}
return counter;
}
//from other solution in leetcode ikaruga
//greedy algorithms
int jump(vector<int> &nums)
{
int ans = 0;
int start = 0;
int end = 1;//至少每次可以跳到下一个数
while (end < nums.size())
{
int maxPos = 0;
for (int i = start; i < end; i++)
{
// 能跳到最远的距离
maxPos = max(maxPos, i + nums[i]);
}
start = end; // 下一次起跳点范围开始的格子
end = maxPos + 1; // 下一次起跳点范围结束的格子
ans++; // 跳跃次数
}
return ans;
}
int jump(vector<int>& nums)
{
int ans = 0;
int end = 0;
int maxPos = 0;
for (int i = 0; i < nums.size() - 1; i++)
{
//num[i] + i is reached max distance ,get the greatest one in this range
maxPos = max(nums[i] + i, maxPos);
if (i == end) //if reach the end
{
end = maxPos; // record the next end;
ans++; // finish a jump, add counter
}
}
return ans;
}
};
int main(int argc, const char** argv) {
int ret;
Solution s;
vector<int> nums{2,1};
ret = s.jump(nums);
cout <<"ret = " <<ret << endl;
return 0;
} | 31.388889 | 106 | 0.463009 | [
"vector"
] |
920fae739001247bee7fa8680d638256d11b599f | 7,967 | hpp | C++ | include/StringUtilities.hpp | Dinahmoe/dm-utils | 76115b485a4812df9aad44fac645fe4b40e7cc7b | [
"BSD-3-Clause"
] | null | null | null | include/StringUtilities.hpp | Dinahmoe/dm-utils | 76115b485a4812df9aad44fac645fe4b40e7cc7b | [
"BSD-3-Clause"
] | null | null | null | include/StringUtilities.hpp | Dinahmoe/dm-utils | 76115b485a4812df9aad44fac645fe4b40e7cc7b | [
"BSD-3-Clause"
] | 1 | 2015-10-06T07:21:32.000Z | 2015-10-06T07:21:32.000Z | /*
* Copyright (c) 2015, Dinahmoe. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON 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.
*
*/
// Created by Alessandro Saccoia on 7/18/12.
#ifndef dmaf_ios_StringUtilities_hpp
#define dmaf_ios_StringUtilities_hpp
#include <string>
#include <vector>
#include <sstream>
#include <ctime>
#include <stdio.h> /* defines FILENAME_MAX */
#include <iomanip>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include <cassert>
#include <fstream>
#include <algorithm>
#include <sys/stat.h>
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#ifdef DM_PLATFORM_OSX
#include <sys/types.h>
#include <pwd.h>
#include <uuid/uuid.h>
#endif
#endif
namespace dinahmoe {
namespace utils {
template <template<typename...> class ContainerT = std::vector>
inline ContainerT<std::string> tokenize(const std::string & str, const std::string & delim, bool toLower = false) {
ContainerT<std::string> tokens;
size_t p0 = 0, p1 = std::string::npos;
while(p0 != std::string::npos)
{
p1 = str.find_first_of(delim, p0);
if(p1 != p0)
{
std::string token = str.substr(p0, p1 - p0);
if (toLower) {
std::transform(token.begin(), token.end(), token.begin(), ::tolower);
}
tokens.push_back(token);
}
p0 = str.find_first_not_of(delim, p1);
}
return tokens;
}
inline std::string concat(const std::vector<std::string>& tokens_, const std::string & delim_, size_t sIndex_, size_t eIndex_) {
std::string reconstructedString("");
for (size_t i = sIndex_; i < eIndex_; ++i) {
reconstructedString += tokens_[i] + delim_;
}
reconstructedString += tokens_[eIndex_];
return reconstructedString;
}
template <typename OutputType>
OutputType stringConverter(std::string fieldValue_) {
std::stringstream m_idReader(fieldValue_);
OutputType toReturn;
m_idReader >> toReturn;
if (m_idReader.fail()) {
throw std::runtime_error("Parsing failed");
}
return toReturn;
}
template <typename InputType>
std::string toString(InputType input) {
std::stringstream out;
out << input;
return out.str();
}
std::string getFullPath(std::string file);
std::string pathToFile(std::string file);
std::string pathToFile(std::string file, std::string ext);
std::string getEnclosingDirectory(std::string file);
inline bool isAbsolute(std::string file) {
return file[0] == '/';
}
inline void ToUpper(const char* bufferIn, char* bufferOut, const int len) {
for(int i = 0; i < len; ++i) {
bufferOut[i] = toupper(bufferIn[i]);
}
}
inline bool IsNumber(const std::string& s) {
for (unsigned int i = 0; i < s.length(); i++) {
if (!std::isdigit(s[i])) {
return false;
}
}
return true;
}
#define xmlIntoPropertyWithDefault(name, actionName, property, type, default) \
propertyElement = actionNode->FirstChildElement(name); \
if (!propertyElement) { \
dmaf_log(Log::Warning, "The " name " element is missing for action " actionName); \
property = default; \
} else { \
retriever = propertyElement->GetText(); \
if (retriever == NULL) { \
dmaf_log(Log::Warning, "The " name " element is empty for action " actionName); \
property = default; \
} else { \
property = stringConverter<type>(retriever); \
} \
}
// returns the date in format MM/DD/YY hh::mm::ss
inline std::string getCurrentDateAndTime() {
std::ostringstream oss;
time_t t = time(NULL);
tm* timePtr = localtime(&t);
oss << timePtr->tm_mon + 1 << "/";
oss << timePtr->tm_mday << "/";
oss << ( 1900 + timePtr->tm_year) << " ";
oss << timePtr->tm_hour << ":";
oss << timePtr->tm_min << ":";
oss << timePtr->tm_sec;
return oss.str();
}
// returns the date in format MM/DD/YY hh::mm::ss
inline std::string getCurrentDateAndTime(std::string separator) {
std::ostringstream oss;
time_t t = time(NULL);
tm* timePtr = localtime(&t);
oss << std::setfill('0');
oss << std::setw(4) << (1900 + timePtr->tm_year) << separator;
oss << std::setw(2) << timePtr->tm_mon << separator;
oss << std::setw(2) << timePtr->tm_mday << separator;
oss << std::setw(2) << timePtr->tm_hour << separator;
oss << std::setw(2) << timePtr->tm_min << separator;
oss << std::setw(2) << timePtr->tm_sec;
return oss.str();
}
inline std::string GetWorkingDirectory() {
static char cCurrentPath[FILENAME_MAX];
if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) {
return std::string();
}
cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
return std::string(cCurrentPath);
}
inline std::string GetCurrentUser() {
#ifdef DM_PLATFORM_OSX
struct passwd *passwd;
passwd = getpwuid ( getuid());
return passwd->pw_name;
#else
return "Not implemented";
#endif
}
// changes the terminal settings, allowing one to get the key code
// of the button that was pressed without waiting for enter to be pressed
/*
USAGE:
for (;;) {
key = getch();
// terminate loop on ESC (0x1B) or Ctrl-D (0x04) on STDIN
if (key == 0x1B || key == 0x04) {
break;
}
else {
printf("%c\n", key));
}
}
*/
inline int getch(void) {
int c=0;
#ifndef DM_PLATFORM_CYGWIN
struct termios org_opts, new_opts;
int res=0;
//----- store old settings -----------
res=tcgetattr(STDIN_FILENO, &org_opts);
assert(res==0);
//---- set new terminal parms --------
memcpy(&new_opts, &org_opts, sizeof(new_opts));
new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
c=getchar();
//------ restore old settings ---------
res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
assert(res==0);
#endif
return(c);
}
// throws exception
inline std::string getFileContentAsString(std::string path_) {
std::ifstream ifs(path_.c_str());
return std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
}
inline bool fileExists (const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
inline std::string getFileExtension(const std::string filePath_) {
std::vector<std::string> tokens = tokenize(filePath_, ".");
return tokens[tokens.size() - 1];
}
inline void toLower(std::string& str_) {
std::transform(str_.begin(), str_.end(), str_.begin(), ::tolower);
}
}}
#endif
| 29.6171 | 128 | 0.671143 | [
"vector",
"transform"
] |
9218c07c2185def40c905fac1caeee038469962d | 3,716 | hpp | C++ | toolboxes/fft/gpu/cuFFTCachedPlan.hpp | roopchansinghv/gadgetron | fb6c56b643911152c27834a754a7b6ee2dd912da | [
"MIT"
] | 1 | 2022-02-22T21:06:36.000Z | 2022-02-22T21:06:36.000Z | toolboxes/fft/gpu/cuFFTCachedPlan.hpp | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | toolboxes/fft/gpu/cuFFTCachedPlan.hpp | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | #pragma once
#include "cuFFTCachedPlan.h"
#include "cuFFTPlan.h"
#include "cuNDArray_math.h"
namespace {
namespace cufft_detail{
auto compact_dims(int rank, const std::vector<size_t>& dimensions){
assert(rank <= dimensions.size());
auto dims = std::vector<size_t>(dimensions.begin(),dimensions.begin()+rank);
auto batches = std::reduce(dimensions.begin()+rank,dimensions.end(),1,std::multiplies());
dims.push_back(batches);
return dims;
}
auto fetch_plan = [](auto& cache, const auto& compacted_dims ) -> auto& {
return cache.try_emplace(compacted_dims,compacted_dims.size()-1,compacted_dims).first->second;
};
}
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::fft1(cuNDArray<ComplexType>& in_out, bool scale) {
this->fft(in_out, 1, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::fft2(cuNDArray<ComplexType>& in_out, bool scale) {
this->fft(in_out, 2, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::fft3(cuNDArray<ComplexType>& in_out, bool scale) {
this->fft(in_out, 3, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::ifft1(cuNDArray<ComplexType>& in_out, bool scale) {
this->ifft(in_out, 1, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::ifft2(cuNDArray<ComplexType>& in_out, bool scale) {
this->ifft(in_out, 2, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::ifft3(cuNDArray<ComplexType>& in_out, bool scale) {
this->ifft(in_out, 3, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::fft1c(cuNDArray<ComplexType>& in_out, bool scale) {
this->fftc(in_out, 1, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::fft2c(cuNDArray<ComplexType>& in_out, bool scale) {
this->fftc(in_out, 2, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::fft3c(cuNDArray<ComplexType>& in_out, bool scale) {
this->fftc(in_out, 3, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::ifft1c(cuNDArray<ComplexType>& in_out, bool scale) {
this->ifftc(in_out, 1, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::ifft2c(cuNDArray<ComplexType>& in_out, bool scale) {
this->ifftc(in_out, 2, scale);
}
template <class ComplexType> void Gadgetron::cuFFTCachedPlan<ComplexType>::ifft3c(cuNDArray<ComplexType>& in_out, bool scale) {
this->ifftc(in_out, 3, scale);
}
template <class ComplexType>
void Gadgetron::cuFFTCachedPlan<ComplexType>::fft(Gadgetron::cuNDArray<ComplexType>& in_out, unsigned int rank, bool scale) {
cufft_detail::fetch_plan(plans,cufft_detail::compact_dims(rank, in_out.dimensions())).fft(in_out, scale);
}
template <class ComplexType>
void Gadgetron::cuFFTCachedPlan<ComplexType>::ifft(Gadgetron::cuNDArray<ComplexType>& in_out, unsigned int rank, bool scale) {
cufft_detail::fetch_plan(plans,cufft_detail::compact_dims(rank, in_out.dimensions())).ifft(in_out, scale);
}
template <class ComplexType>
void Gadgetron::cuFFTCachedPlan<ComplexType>::fftc(Gadgetron::cuNDArray<ComplexType>& in_out, unsigned int rank, bool scale) {
cufft_detail::fetch_plan(plans,cufft_detail::compact_dims(rank, in_out.dimensions())).fftc(in_out, scale);
}
template <class ComplexType>
void Gadgetron::cuFFTCachedPlan<ComplexType>::ifftc(Gadgetron::cuNDArray<ComplexType>& in_out, unsigned int rank, bool scale) {
cufft_detail::fetch_plan(plans,cufft_detail::compact_dims(rank, in_out.dimensions())).ifftc(in_out, scale);
}
| 48.894737 | 127 | 0.749731 | [
"vector"
] |
9218eb55344b48a126d43720e4b502c603cc4c10 | 18,162 | cpp | C++ | IUI/Control/ControlCore/RichTextBox/RichEditSrc/propchg.cpp | jiaojian8063868/portsip-softphone-windows | df1b6391ff5d074cbc98cb559e52b181ef8e1b17 | [
"BSD-2-Clause"
] | null | null | null | IUI/Control/ControlCore/RichTextBox/RichEditSrc/propchg.cpp | jiaojian8063868/portsip-softphone-windows | df1b6391ff5d074cbc98cb559e52b181ef8e1b17 | [
"BSD-2-Clause"
] | null | null | null | IUI/Control/ControlCore/RichTextBox/RichEditSrc/propchg.cpp | jiaojian8063868/portsip-softphone-windows | df1b6391ff5d074cbc98cb559e52b181ef8e1b17 | [
"BSD-2-Clause"
] | 2 | 2021-12-31T03:42:48.000Z | 2022-02-20T08:37:41.000Z | /*
* @doc INTERNAL
*
* @module PROPCHG.CPP -- Property Change Notification Routines |
*
* Original Author: <nl>
* Rick Sailor
*
* History: <nl>
* 9/5/95 ricksa Created and documented
*
* Documentation is generated straight from the code. The following
* date/time stamp indicates the version of code from which the
* the documentation was generated.
*
*/
#include "stdafx.h"
#include "_common.h"
#include "_edit.h"
#include "_dispprt.h"
#include "_dispml.h"
#include "_dispsl.h"
#include "_select.h"
#include "_text.h"
#include "_runptr.h"
#include "_font.h"
#include "_measure.h"
#include "_render.h"
#include "_urlsup.h"
ASSERTDATA
CTxtEdit::FNPPROPCHG CTxtEdit::_fnpPropChg[MAX_PROPERTY_BITS] =
{
&CTxtEdit::OnRichEditChange, // TXTBIT_RICHTEXT
&CTxtEdit::OnTxMultiLineChange, // TXTBIT_MULTILINE
&CTxtEdit::OnTxReadOnlyChange, // TXTBIT_READONLY
&CTxtEdit::OnShowAccelerator, // TXTBIT_SHOWACCELERATOR
&CTxtEdit::OnUsePassword, // TXTBIT_USEPASSWORD
&CTxtEdit::OnTxHideSelectionChange, // TXTBIT_HIDESELECTION
&CTxtEdit::OnSaveSelection, // TXTBIT_SAVESELECTION
&CTxtEdit::OnAutoWordSel, // TXTBIT_AUTOWORDSEL
&CTxtEdit::OnTxVerticalChange, // TXTBIT_VERTICAL
&CTxtEdit::NeedViewUpdate, // TXTBIT_SELECTIONBAR
&CTxtEdit::OnWordWrapChange, // TXTBIT_WORDWRAP
&CTxtEdit::OnAllowBeep, // TXTBIT_ALLOWBEEP
&CTxtEdit::OnDisableDrag, // TXTBIT_DISABLEDRAG
&CTxtEdit::NeedViewUpdate, // TXTBIT_VIEWINSETCHANGE
&CTxtEdit::OnTxBackStyleChange, // TXTBIT_BACKSTYLECHANGE
&CTxtEdit::OnMaxLengthChange, // TXTBIT_MAXLENGTHCHANGE
&CTxtEdit::OnScrollChange, // TXTBIT_SCROLLBARCHANGE
&CTxtEdit::OnCharFormatChange, // TXTBIT_CHARFORMATCHANGE
&CTxtEdit::OnParaFormatChange, // TXTBIT_PARAFORMATCHANGE
&CTxtEdit::NeedViewUpdate, // TXTBIT_EXTENTCHANGE
&CTxtEdit::OnClientRectChange, // TXTBIT_CLIENTRECTCHANGE
};
/*
* CTxtEdit::UpdateAccelerator()
*
* @mfunc
* Get accelerator cp from host
*
* @rdesc
* HRESULT
*
* @devnote:
* The point of this is to leave the accelerator offset unchanged
* in the face of an error from the host.
*/
HRESULT CTxtEdit::UpdateAccelerator()
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::UpdateAccelerator");
LONG cpAccel;
HRESULT hr = _phost->TxGetAcceleratorPos(&cpAccel);
if (SUCCEEDED(hr))
{
// It worked so reset our value
AssertSz(cpAccel < 32768,
"CTxtEdit::UpdateAccelerator: cp too large");
_cpAccelerator = cpAccel;
}
return hr;
}
/*
* CTxtEdit::HandleRichToPlainConversion()
*
* @mfunc
* Convert a rich text object to a plain text object
*/
INLINE void CTxtEdit::HandleRichToPlainConversion()
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::HandleRichToPlainConversion");
CRchTxtPtr rtp(this, 0);
// Notify every interested party that they should dump their formatting
_nm.NotifyPreReplaceRange(NULL, CONVERT_TO_PLAIN, 0, 0, 0, 0);
// set _fRich to false so we can delete the final CRLF.
_fRich = 0;
if (_pdetecturl)
{
delete _pdetecturl;
_pdetecturl = NULL;
}
// Set the format runs to NULL since this really isn't a rich text object
// any more.
rtp._rpCF.SetToNull();
rtp._rpPF.SetToNull();
// Tell document to dump its format runs
_story.DeleteFormatRuns();
// clear out the ending CRLF
rtp.ReplaceRange(GetTextLength(), 0, NULL, NULL, -1);
}
/*
* CTxtEdit::HandleIMEToPlain()
*
* @mfunc
* After IME composition in a plain text environment, return the CF runs to normal.
*/
void CTxtEdit::HandleIMEToPlain()
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::HandleIMEToPlain");
CRchTxtPtr rtp(this, 0);
_pdp->WaitForRecalc(GetTextLength(), -1);
// Notify every interested party that they should dump their formatting
_nm.NotifyPreReplaceRange(NULL, CONVERT_TO_PLAIN, 0, 0, 0, 0);
// Set the format runs to NULL since this really isn't a rich text object
// any more.
rtp._rpCF.SetToNull();
// Tell document to dump its format runs
_story.DeleteFormatRuns();
}
/*
* CTxtEdit::OnRichEditChange (fPropertyFlag)
*
* @mfunc
* Notify text services that rich-text property changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnRichEditChange(
BOOL fPropertyFlag) //@parm New state of richedit flag
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnRichEditChange");
// Calculate length of empty document. Remember that multiline rich text
// controls always have and end of paragraph marker.
DWORD dwEmptyDocLen = cchCR;
if (!_fRich)
{
dwEmptyDocLen = 0;
}
else if (_f10Mode)
{
dwEmptyDocLen = cchCRLF;
}
// This can only be changed if there is no text and nothing to undo.
// It makes no sense to change when there is already text. This is
// particularly true of going from rich to plain. Further, what would
// you do with the undo state?
if ((GetTextLength() == dwEmptyDocLen)
&& (!_pundo || !_pundo->CanUndo()))
{
#ifdef DEBUG
// Make sure that document is in a sensible state.
if (_fRich)
{
CRchTxtPtr tp(this);
WCHAR szBuf[cchCRLF];
if (!_f10Mode)
{
// 2.0 Rich text document. Must have a single CR.
tp._rpTX.GetText(cchCR, &szBuf[0]);
AssertSz(szBuf[0] == szCRLF[0],
"CTxtEdit::OnRichEditChange 1.0 no CR terminator");
}
else
{
// 1.0 Rich text document. Must have a CRLF
tp._rpTX.GetText(cchCRLF, &szBuf[0]);
AssertSz((szBuf[0] == szCRLF[0]) && (szBuf[1] == szCRLF[1]),
"CTxtEdit::OnRichEditChange 1.0 no CRLF terminator");
}
}
#endif // DEBUG
if (_fRich && !fPropertyFlag)
{
// We are going from rich text to plain text. We need to
// dump all format runs.
HandleRichToPlainConversion();
}
else if (!_fRich && fPropertyFlag)
{
// Going to rich text from plain text ML. Need to add the
// appropriate EOP at the end of the document.
SetRichDocEndEOP(0);
}
_fRich = fPropertyFlag;
return S_OK;
}
return E_FAIL; // Flag was not updated
}
/*
* CTxtEdit::OnTxMultiLineChange (fMultiline)
*
* @mfunc
* Notify text services that the display changed.
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnTxMultiLineChange(
BOOL fMultiLine)
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnTxMultiLineChange");
BOOL fHadSelection = (_psel != NULL);
CDisplay *pSavedDisplay;
BOOL fOldShowSelection = FALSE;
// Remember the old value for show selection
if (fHadSelection)
{
fOldShowSelection = _psel->GetShowSelection();
}
// Save the current display away and null it out
pSavedDisplay = _pdp;
_pdp = NULL;
// Attempt to create the new display
if (fMultiLine)
{
_pdp = new CDisplayML(this);
}
else
{
_pdp = new CDisplaySL(this);
}
if (!_pdp)
{
_pdp = pSavedDisplay;
return E_OUTOFMEMORY;
}
// Attempt to init the new display
if (pSavedDisplay)
{
_pdp->InitFromDisplay(pSavedDisplay);
}
if (!_pdp->Init())
{
delete _pdp;
_pdp = pSavedDisplay;
return E_FAIL;
}
// Ok to now kill the old display
delete pSavedDisplay;
// Is there are selection?
if (_psel)
{
// Need to tell it there is a new display to talk to.
_psel->SetDisplay(_pdp);
}
// Is this a switch to Single Line? If this is we need to
// make sure we truncate the text to the first EOP. We wait
// till this point to do this check to make sure that everything
// is in sync before doing something which potentially affects
// the display and the selection.
if (!fMultiLine)
{
// Set up for finding an EOP
CTxtPtr tp(this, 0);
tp.FindEOP(tomForward);
// Is there any EOP and text beyond?
if (tp.GetCp() < GetAdjustedTextLength())
{
// FindEOP places the text after the EOP if there
// is one. Since we want to delete the EOP as well
// we need to back up to the EOP.
tp.BackupCpCRLF();
// Sync up the cp's of all the ranges before deleting
// the text.
CRchTxtPtr rtp(this, tp.GetCp());
// Truncate from the EOP to the end of the document
rtp.ReplaceRange(GetAdjustedTextLength() - tp.GetCp(), 0, NULL, NULL, -1);
}
}
_pdp->UpdateView();
if (fHadSelection)
{
if (_fFocus && fOldShowSelection)
{
_psel->ShowSelection(TRUE);
}
}
return S_OK;
}
/*
* CTxtEdit::OnTxReadOnlyChange (fReadOnly)
*
* @mfunc
* Notify text services that read-only property changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnTxReadOnlyChange(
BOOL fReadOnly) //@parm TRUE = read only, FALSE = not read only
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnTxReadOnlyChange");
if (fReadOnly)
{
_ldte.ReleaseDropTarget();
}
_fReadOnly = fReadOnly; // Cache bit
return S_OK;
}
/*
* CTxtEdit::OnShowAccelerator (fPropertyFlag)
*
* @mfunc
* Update accelerator based on change
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnShowAccelerator(
BOOL fPropertyFlag) //@parm TRUE = show accelerator
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnShowAccelerator");
// Get the new accelerator character
HRESULT hr = UpdateAccelerator();
// Update the view - we update even in the face of an error return.
// The point is that errors will be rare (non-existent?) and the update
// will work even in the face of the error so why bother conditionalizing
// the execution.
NeedViewUpdate(TRUE);
return hr;
}
/*
* CTxtEdit::OnUsePassword (fPropertyFlag)
*
* @mfunc
* Update use-password property
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnUsePassword(
BOOL fPropertyFlag) //@parm TRUE = use password character
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnUsePassword");
Assert((DWORD)fPropertyFlag <= 1); // Be sure it's C boolean
_fUsePassword = fPropertyFlag;
_pdp->UpdateView(); // State changed so update view
return S_OK;
}
/*
* CTxtEdit::OnTxHideSelectionChange (fHideSelection)
*
* @mfunc
* Notify text services that hide-selection property changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnTxHideSelectionChange(
BOOL fHideSelection) //@parm TRUE = hide selection
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnTxHideSelectionChange");
_fHideSelection = fHideSelection;
if (_fFocus) // If we have the focus, don't
{
return S_OK; // change the current selection
}
// display status
CTxtSelection *psel = GetSel();
if (psel)
{
psel->ShowSelection(!fHideSelection);
}
if (!_fInPlaceActive)
{
TxInvalidateRect(NULL, FALSE); // Since _fInPlaceActive = FALSE,
TxUpdateWindow(); // this only tells user.exe to
} // send a WM_PAINT message
return S_OK;
}
/*
* CTxtEdit::OnSaveSelection (fPropertyFlag)
*
* @mfunc
* Notify text services that save-selection property changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnSaveSelection(
BOOL fPropertyFlag) //@parm TRUE = save selection when inactive
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnSaveSelection");
return S_OK;
}
/*
* CTxtEdit::OnAutoWordSel (fPropertyFlag)
*
* @mfunc
* Notify text services that auto-word-selection property changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnAutoWordSel(
BOOL fPropertyFlag) //@parm TRUE = auto word selection on
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnAutoWordSel");
// We call back to the host when we need to know, so we don't bother doing
// anything in response to this notification.
return S_OK;
}
/*
* CTxtEdit::OnTxVerticalChange (fVertical)
*
* @mfunc
* Notify text services that vertical property changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnTxVerticalChange(
BOOL fVertical) //@parm TRUE - text vertically oriented.
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnTxVerticalChange");
// We pretend like something actually happened.
GetCallMgr()->SetChangeEvent(CN_GENERIC);
return S_OK;
}
/*
* CTxtEdit::OnClientRectChange (fPropertyFlag)
*
* @mfunc
* Notify text services that client rectangle changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnClientRectChange(
BOOL fPropertyFlag) //@parm Ignored for this property
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnClientRectChange");
// It is unclear whether we need to actually do anything for this
// notification. Logically, the change of this property is followed
// closely by some kind of operation which will cause the display
// cache to be updated anyway. The old code is left here as an
// example of what might be done if it turns out we need to do
// anything. For now, we will simply return S_OK to this notification.
#if 0
if (_fInPlaceActive)
{
RECT rc;
if (_phost->TxGetClientRect(&rc) == NOERROR)
{
_pdp->OnClientRectChange(rc);
}
return S_OK;
}
return NeedViewUpdate(fPropertyFlag);
#endif // 0
// With a client rect change we do need to update the caret when
// we get redrawn even if the basic information did not change.
_pdp->SetUpdateCaret();
return S_OK;
}
/*
* CTxtEdit::OnCharFormatChange (fPropertyFlag)
*
* @mfunc
* Update default CCharFormat
*
* @rdesc
* S_OK - update successfully processed.
*
*/
HRESULT CTxtEdit::OnCharFormatChange(
BOOL fPropertyFlag) //@parm Not used
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnCharFormatChange");
HRESULT hr;
CCharFormat CF;
hr = TxGetDefaultCharFormat(&CF);
if (hr == NOERROR)
{
// OnSetCharFormat handles updating the view.
hr = OnSetCharFormat(0, (LPARAM)&CF, NULL)
? NOERROR : E_FAIL;
}
return hr;
}
/*
* CTxtEdit::OnParaFormatChange (fPropertyFlag)
*
* @mfunc
* Update default CParaFormat
*
* @rdesc
* S_OK - update successfully processed
*
* @devnote
* Because Forms^3 doesn't set cbSize correctly, we limit this API
* to PARAFORMAT (until they fix it).
*/
HRESULT CTxtEdit::OnParaFormatChange(
BOOL fPropertyFlag) //@parm Not used
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnParaFormatChange");
HRESULT hr;
CParaFormat PF;
hr = TxGetDefaultParaFormat(&PF);
if (hr == NOERROR)
{
// OnSetParaFormat handles updating the view.
hr = OnSetParaFormat(SPF_SETDEFAULT, (LPARAM)&PF, NULL)
? NOERROR : E_FAIL;
}
return hr;
}
/*
* CTxtEdit::NeedViewUpdate (fPropertyFlag)
*
* @mfunc
* Notify text services that view of data changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::NeedViewUpdate(
BOOL fPropertyFlag)
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::NeedViewUpdate");
_pdp->UpdateView();
return S_OK;
}
/*
* CTxtEdit::OnTxBackStyleChange (fPropertyFlag)
*
* @mfunc
* Notify text services that background style changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnTxBackStyleChange(
BOOL fPropertyFlag) //@parm Ignored for this property
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnTxBackStyleChange");
_fTransparent = (TxGetBackStyle() == TXTBACK_TRANSPARENT);
TxInvalidateRect(NULL, FALSE);
return S_OK;
}
/*
* CTxtEdit::OnAllowBeep (fPropertyFlag)
*
* @mfunc
* Notify text services that beep property changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnAllowBeep(
BOOL fPropertyFlag) //@parm New state of property
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnAllowBeep");
_fAllowBeep = fPropertyFlag;
return S_OK;
}
/*
* CTxtEdit::OnMaxLengthChange (fPropertyFlag)
*
* @mfunc
* Notify text services that max-length property changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnMaxLengthChange(
BOOL fPropertyFlag) //@parm New state of property
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnMaxLengthChange");
// Query host for max text length
DWORD length = INFINITE;
_phost->TxGetMaxLength(&length);
_cchTextMost = length;
return S_OK;
}
/*
* CTxtEdit::OnWordWrapChange (fPropertyFlag)
*
* @mfunc
* Notify text services that word-wrap property changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnWordWrapChange(
BOOL fPropertyFlag) //@parm TRUE = do word wrap
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnWordWrapChange");
_pdp->SetWordWrap(fPropertyFlag);
// Update was successful so we need the screen updated at some point
_pdp->UpdateView();
return S_OK;
}
/*
* CTxtEdit::OnDisableDrag (fPropertyFlag)
*
* @mfunc
* Notify text services that disable drag property changed
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnDisableDrag(
BOOL fPropertyFlag) //@parm New state of property
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnDisableDrag");
_fDisableDrag = fPropertyFlag;
return S_OK;
}
/*
* CTxtEdit::OnScrollChange (fPropertyFlag)
*
* @mfunc
* Notify text services scroll property change
*
* @rdesc
* S_OK - Notification successfully processed.
*/
HRESULT CTxtEdit::OnScrollChange(
BOOL fPropertyFlag) //@parm New state of property
{
TRACEBEGIN(TRCSUBSYSTS, TRCSCOPEINTERN, "CTxtEdit::OnScrollChange");
// Tell the display that scroll bars for sure need to be updated
_pdp->SetViewChanged();
// Tell the display to update itself.
_pdp->UpdateView();
return S_OK;
}
| 24.02381 | 85 | 0.685332 | [
"object"
] |
921b0bbf7cd8e00e742e93be72fb688f2c506eb9 | 5,651 | cpp | C++ | src/Test_Replicate.cpp | pememoni/HElib | 96838a91b4d248573f9be7e3428d060bc4813da3 | [
"Apache-2.0"
] | 1 | 2019-11-04T04:55:29.000Z | 2019-11-04T04:55:29.000Z | src/Test_Replicate.cpp | PNIDEMOOO/HElib | 7427ed3709bb9872835324dd0007a97b3ca3baca | [
"Apache-2.0"
] | null | null | null | src/Test_Replicate.cpp | PNIDEMOOO/HElib | 7427ed3709bb9872835324dd0007a97b3ca3baca | [
"Apache-2.0"
] | null | null | null | /* Copyright (C) 2012-2017 IBM Corp.
* This program is 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. See accompanying LICENSE file.
*/
/* Test_Replicate.cpp - Testing the functionality of replicating one
* slot from a vector acress the whole vector (or replicating each slot
* to a full cipehrtext)
*/
#include <cassert>
#include <NTL/lzz_pXFactoring.h>
NTL_CLIENT
#include "FHE.h"
#include "replicate.h"
#include "timing.h"
#include "ArgMap.h"
static bool noPrint = false;
static bool check_replicate(const Ctxt& c1, const Ctxt& c0, long i,
const FHESecKey& sKey, const EncryptedArray& ea)
{
PlaintextArray pa0(ea), pa1(ea);
ea.decrypt(c0, sKey, pa0);
ea.decrypt(c1, sKey, pa1);
replicate(ea, pa0, i);
return equals(ea, pa1, pa0); // returns true if replication succeeded
}
class StopReplicate { };
// A class that handles the replicated ciphertexts one at a time
class ReplicateTester : public ReplicateHandler {
public:
const FHESecKey& sKey;
const EncryptedArray& ea;
const PlaintextArray& pa;
long B;
double t_last, t_total;
long pos;
bool error;
ReplicateTester(const FHESecKey& _sKey, const EncryptedArray& _ea,
const PlaintextArray& _pa, long _B)
: sKey(_sKey), ea(_ea), pa(_pa), B(_B)
{
t_last = GetTime();
t_total = 0.0;
pos = 0;
error = false;
}
// This method is called for every replicated ciphertext: in the i'th time
// that it is called, the cipehrtext will have in all the slots the content
// of the i'th input slot. In this test program we only decrypt and check
// the result, in a real program it will do something with the cipehrtext.
virtual void handle(const Ctxt& ctxt) {
double t_new = GetTime();
double t_elapsed = t_new - t_last;
t_total += t_elapsed;
// Decrypt and check
PlaintextArray pa1 = pa;
replicate(ea, pa1, pos);
PlaintextArray pa2(ea);
if (pos==0 && !noPrint) CheckCtxt(ctxt, "replicateAll");
ea.decrypt(ctxt, sKey, pa2);
if (!equals(ea, pa1, pa2)) error = true; // record the error, if any
t_last = GetTime();
pos++;
if (B > 0 && pos >= B) throw StopReplicate();
}
};
void TestIt(long m, long p, long r, long d, long L, long bnd, long B)
{
if (!noPrint)
std::cout << "*** TestIt" << (isDryRun()? "(dry run):" : ":")
<< " m=" << m
<< ", p=" << p
<< ", r=" << r
<< ", d=" << d
<< ", L=" << L
<< ", bnd=" << bnd
<< ", B=" << B
<< endl;
setTimersOn();
FHEcontext context(m, p, r);
buildModChain(context, L, /*c=*/2);
ZZX G;
if (d == 0)
G = context.alMod.getFactorsOverZZ()[0];
else
G = makeIrredPoly(p, d);
if (!noPrint) {
context.zMStar.printout();
cout << endl;
cout << "G = " << G << "\n";
}
FHESecKey secretKey(context);
const FHEPubKey& publicKey = secretKey;
secretKey.GenSecKey(); // A +-1/0 secret key
addSome1DMatrices(secretKey); // compute key-switching matrices that we need
EncryptedArray ea(context, G);
PlaintextArray xp0(ea), xp1(ea);
random(ea, xp0);
random(ea, xp1);
Ctxt xc0(publicKey);
ea.encrypt(xc0, publicKey, xp0);
ZZX poly_xp1;
ea.encode(poly_xp1, xp1);
if (!noPrint) cout << "** Testing replicate():\n";
bool error = false;
Ctxt xc1 = xc0;
if (!noPrint) CheckCtxt(xc1, "before replicate");
replicate(ea, xc1, ea.size()/2);
if (!check_replicate(xc1, xc0, ea.size()/2, secretKey, ea)) error = true;
if (!noPrint) CheckCtxt(xc1, "after replicate");
// Get some timing results
for (long i=0; i<20 && i<ea.size(); i++) {
xc1 = xc0;
FHE_NTIMER_START(replicate);
replicate(ea, xc1, i);
if (!check_replicate(xc1, xc0, i, secretKey, ea)) error = true;
FHE_NTIMER_STOP(replicate);
}
cout << (error? "BAD" : "GOOD") << endl;
if (!noPrint) {
printAllTimers();
cout << "\n** Testing replicateAll()... " << std::flush;
}
#ifdef DEBUG_PRINTOUT
replicateVerboseFlag = true;
#else
replicateVerboseFlag = false;
#endif
error = false;
ReplicateTester *handler = new ReplicateTester(secretKey, ea, xp0, B);
try {
FHE_NTIMER_START(replicateAll);
replicateAll(ea, xc0, handler, bnd);
}
catch (StopReplicate) {
}
std::cout << (handler->error? "BAD" : "GOOD") << endl;
if (!noPrint)
cout << " total time=" << handler->t_total << " ("
<< ((B>0)? B : ea.size()) << " vectors)\n";
delete handler;
}
int main(int argc, char *argv[])
{
ArgMap amap;
bool dry=false;
amap.arg("dry", dry, "dry=1 for a dry-run");
long m=2047;
amap.arg("m", m, "cyclotomic ring");
long p=2;
amap.arg("p", p, "plaintext base");
long r=1;
amap.arg("r", r, "lifting");
long d=1;
amap.arg("d", d, "degree of the field extension");
amap.note("d == 0 => factors[0] defines extension");
long L=250;
amap.arg("L", L, "# of bits in the modulus chain");
long bnd = 64;
amap.arg("bnd", bnd, "recursion bound for replication");
long B = 0;
amap.arg("B", B, "bound for # of replications", "all");
amap.arg("noPrint", noPrint, "suppress printouts");
amap.parse(argc, argv);
setDryRun(dry);
TestIt(m, p, r, d, L, bnd, B);
cout << endl;
}
| 25.922018 | 78 | 0.634401 | [
"vector"
] |
921be81a052abac32f573dbcfeea7e1250aaece5 | 3,346 | cpp | C++ | tests/cefclient/extension_test.cpp | svn2github/cef1 | 61d1537c697bec6265e02c9e9bb4c416b7b22db5 | [
"BSD-3-Clause"
] | 18 | 2015-07-11T03:16:54.000Z | 2019-01-19T12:10:38.000Z | tests/cefclient/extension_test.cpp | svn2github/cef | 61d1537c697bec6265e02c9e9bb4c416b7b22db5 | [
"BSD-3-Clause"
] | 2 | 2019-01-14T00:10:11.000Z | 2019-02-03T08:19:11.000Z | tests/cefclient/extension_test.cpp | svn2github/cef1 | 61d1537c697bec6265e02c9e9bb4c416b7b22db5 | [
"BSD-3-Clause"
] | 9 | 2015-01-08T01:07:25.000Z | 2018-03-05T03:52:04.000Z | // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "cefclient/extension_test.h"
#include <string>
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_stream.h"
#include "include/cef_v8.h"
namespace extension_test {
namespace {
// Implementation of the V8 handler class for the "cef.test" extension.
class ClientV8ExtensionHandler : public CefV8Handler {
public:
ClientV8ExtensionHandler() : test_param_("An initial string value.") {}
virtual ~ClientV8ExtensionHandler() {}
// Execute with the specified argument list and return value. Return true if
// the method was handled.
virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) {
if (name == "SetTestParam") {
// Handle the SetTestParam native function by saving the string argument
// into the local member.
if (arguments.size() != 1 || !arguments[0]->IsString())
return false;
test_param_ = arguments[0]->GetStringValue();
return true;
} else if (name == "GetTestParam") {
// Handle the GetTestParam native function by returning the local member
// value.
retval = CefV8Value::CreateString(test_param_);
return true;
} else if (name == "GetTestObject") {
// Handle the GetTestObject native function by creating and returning a
// new V8 object.
retval = CefV8Value::CreateObject(NULL);
// Add a string parameter to the new V8 object.
retval->SetValue("param", CefV8Value::CreateString(
"Retrieving a parameter on a native object succeeded."),
V8_PROPERTY_ATTRIBUTE_NONE);
// Add a function to the new V8 object.
retval->SetValue("GetMessage",
CefV8Value::CreateFunction("GetMessage", this),
V8_PROPERTY_ATTRIBUTE_NONE);
return true;
} else if (name == "GetMessage") {
// Handle the GetMessage object function by returning a string.
retval = CefV8Value::CreateString(
"Calling a function on a native object succeeded.");
return true;
}
return false;
}
private:
CefString test_param_;
IMPLEMENT_REFCOUNTING(ClientV8ExtensionHandler);
};
} // namespace
void InitTest() {
// Register a V8 extension with the below JavaScript code that calls native
// methods implemented in ClientV8ExtensionHandler.
std::string code = "var cef;"
"if (!cef)"
" cef = {};"
"if (!cef.test)"
" cef.test = {};"
"(function() {"
" cef.test.__defineGetter__('test_param', function() {"
" native function GetTestParam();"
" return GetTestParam();"
" });"
" cef.test.__defineSetter__('test_param', function(b) {"
" native function SetTestParam();"
" if (b) SetTestParam(b);"
" });"
" cef.test.test_object = function() {"
" native function GetTestObject();"
" return GetTestObject();"
" };"
"})();";
CefRegisterExtension("v8/test", code, new ClientV8ExtensionHandler());
}
} // namespace extension_test
| 34.142857 | 79 | 0.648536 | [
"object"
] |
921db9866373d23b413bf65802c888a94023886a | 13,217 | cpp | C++ | groups/csa/csaxform/csaxform_refactor_config.cpp | hyrosen/bde_verify | c2db13c9f1649806bfd9155e2bffcbbcf9d54918 | [
"Apache-2.0"
] | null | null | null | groups/csa/csaxform/csaxform_refactor_config.cpp | hyrosen/bde_verify | c2db13c9f1649806bfd9155e2bffcbbcf9d54918 | [
"Apache-2.0"
] | null | null | null | groups/csa/csaxform/csaxform_refactor_config.cpp | hyrosen/bde_verify | c2db13c9f1649806bfd9155e2bffcbbcf9d54918 | [
"Apache-2.0"
] | null | null | null | // csaxform_dump_defs.cpp -*-C++-*-
#include "csabase_analyser.h"
#include "csabase_debug.h"
#include "csabase_ppobserver.h"
#include "csabase_registercheck.h"
#include "csabase_report.h"
#include "csabase_util.h"
#include "csabase_visitor.h"
#include <llvm/ADT/StringExtras.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/Path.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/ASTMatchers/ASTMatchers.h>
#include <clang/Lex/Preprocessor.h>
#include <string>
#include <map>
#include <set>
using namespace clang;
using namespace clang::ast_matchers;
using namespace csabase;
// ----------------------------------------------------------------------------
static std::string const check_name("refactor-config");
// ----------------------------------------------------------------------------
namespace
{
typedef std::set<std::string> t_ss;
int s_index = 0;
std::map<std::string, t_ss> s_names[2];
std::string s_files[2];
std::string s_upper_prefix[2];
struct data
{
std::map<std::string, t_ss> d_ns; // reported names
};
// Callback object invoked upon completion.
struct report : Report<data>
{
INHERIT_REPORT_CTOR(report, Report, data);
void operator()();
// Callback for end of compilation unit.
llvm::StringRef clean_name(llvm::StringRef name, std::string& buf);
// Clean up the specified 'name' for use in refactor configuration
// using the specified 'buf' as a work area if needed, and return the
// cleaned string.
llvm::StringRef common_suffix(llvm::StringRef a, llvm::StringRef b);
// Return the longest common suffix of the specified 'a' and 'b'.
llvm::StringRef best_match(llvm::StringRef s, const t_ss& sequence);
// Return the first string in the specified 'sequence' that has the
// longest common suffix with the specified 's'. If the sequence
// contains an exact match for 's', that value is ignored.
llvm::StringRef prefer_e(llvm::StringRef s, const t_ss& sequence);
// Return the first string in the specified 'sequence' that has a
// preferred 'e_...' spelling variant of the specified 's' if such
// exists, and 's' otherwise.
};
llvm::StringRef report::clean_name(llvm::StringRef name, std::string& buf)
{
llvm::StringRef blp(a.config()->toplevel_namespace());
if (name.startswith(blp) && name.drop_front(blp.size()).startswith("::")) {
name = name.drop_front(blp.size() + 2);
}
if (name.endswith("::")) {
name = name.drop_back(2);
}
if (name.find("::::") != name.npos) {
SmallVector<llvm::StringRef, 5> ns;
name.split(ns, "::", -1, false);
buf = llvm::join(ns.begin(), ns.end(), "::");
name = buf;
}
return name;
}
llvm::StringRef report::common_suffix(llvm::StringRef a, llvm::StringRef b)
{
llvm::StringRef cs;
size_t na = a.size();
size_t nb = b.size();
bool saw_sep = false;
for (size_t i = 1; i <= na && i <= nb; ++i) {
if (!isalnum(a[na - i]) || !isalnum(b[nb - i])) {
saw_sep = true;
}
if (a[na - i] != b[nb - i]) {
break;
}
cs = a.drop_front(na - i);
}
return saw_sep ? cs : llvm::StringRef();
}
llvm::StringRef report::best_match(llvm::StringRef s, const t_ss& sequence)
{
llvm::StringRef lcs;
llvm::StringRef bm;
for (llvm::StringRef m : sequence) {
if (!s.equals(m)) {
llvm::StringRef cs = common_suffix(s, m);
if (cs.size() > lcs.size()) {
lcs = cs;
bm = m;
}
}
}
return bm;
}
llvm::StringRef report::prefer_e(llvm::StringRef s, const t_ss& sequence)
{
size_t last_colons = s.rfind("::");
if (last_colons != s.npos) {
llvm::StringRef lit = s.drop_front(last_colons + 2);
for (int i = 0; i <= 1; ++i) {
if (lit.startswith(s_upper_prefix[i])) {
lit = lit.drop_front(s_upper_prefix[i].size());
if (lit.startswith("_")) {
lit = lit.drop_front(1);
}
break;
}
}
std::string k = s.slice(0, last_colons + 2).str() + "k_" + lit.str();
std::string e = s.slice(0, last_colons + 2).str() + "e_" + lit.str();
auto ik = sequence.find(k);
auto ie = sequence.find(e);
if (ik != sequence.end()) {
s = *ik;
}
if (ie != sequence.end()) {
s = *ie;
}
}
return s;
}
void report::operator()()
{
auto tu = a.context()->getTranslationUnitDecl();
s_files[s_index] = llvm::sys::path::filename(
Location(m, m.getLocForStartOfFile(m.getMainFileID())).file()).str();
llvm::StringRef f(s_files[s_index]);
size_t under = f.find_first_of("_.");
if (under == f.npos) {
under = f.size();
}
s_upper_prefix[s_index] = f.slice(0, under).upper();
MatchFinder mf;
static const std::string Tags[] = {
"class", "enum", "literal", "template", "typedef", "macro"
};
enum { Class, Enum, Literal, Template, Typedef, Macro, NTags };
auto ¯os = d.d_ns[Tags[Macro]];
for (auto i = p.macro_begin(); i != p.macro_end(); ++i) {
IdentifierInfo *ii = const_cast<IdentifierInfo *>(i->first);
if (auto md = p.getMacroDefinition(ii).getLocalDirective()) {
if (m.isWrittenInMainFile(md->getLocation())) {
std::string s = ii->getName().str();
if (!llvm::StringRef(s).startswith("INCLUDE") &&
macros.emplace(s).second) {
a.report(md->getLocation(), check_name, "DD01",
"Found " + Tags[Macro] + " " + s);
}
}
}
}
OnMatch<> m1([&](const BoundNodes &nodes) {
if (!nodes.getNodeAs<NamespaceDecl>("n")->isAnonymousNamespace()) {
auto r = nodes.getNodeAs<CXXRecordDecl>(Tags[Class]);
if (m.isWrittenInMainFile(r->getLocation()) &&
!r->getTypedefNameForAnonDecl()) {
std::string s = r->getQualifiedNameAsString();
s = clean_name(s, s);
if (d.d_ns[Tags[Class]].emplace(s).second) {
a.report(r, check_name, "DD01",
"Found " + Tags[Class] + " " + s);
}
}
}
});
mf.addDynamicMatcher(
decl(forEachDescendant(
namespaceDecl(
forEach(recordDecl(isDefinition()
).bind(Tags[Class]))
).bind("n"))),
&m1);
OnMatch<> m2([&](const BoundNodes &nodes) {
if (!nodes.getNodeAs<NamespaceDecl>("n")->isAnonymousNamespace()) {
auto r = nodes.getNodeAs<CXXRecordDecl>(Tags[Class]);
auto e = nodes.getNodeAs<EnumDecl>(Tags[Enum]);
if (m.isWrittenInMainFile(e->getLocation()) &&
!r->getTypedefNameForAnonDecl() &&
e->hasNameForLinkage()) {
std::string s = e->getQualifiedNameAsString();
s = clean_name(s, s);
if (d.d_ns[Tags[Enum]].emplace(s).second) {
a.report(e, check_name, "DD01",
"Found " + Tags[Enum] + " " + s);
}
}
}
});
mf.addDynamicMatcher(
decl(forEachDescendant(
namespaceDecl(
forEach(recordDecl(isDefinition(),
forEach(enumDecl(
).bind(Tags[Enum]))
).bind(Tags[Class]))
).bind("n"))),
&m2);
OnMatch<> m3([&](const BoundNodes &nodes) {
if (!nodes.getNodeAs<NamespaceDecl>("n")->isAnonymousNamespace()) {
auto r = nodes.getNodeAs<CXXRecordDecl>(Tags[Class]);
auto l = nodes.getNodeAs<EnumConstantDecl>(Tags[Literal]);
if (m.isWrittenInMainFile(l->getLocation()) &&
!r->getTypedefNameForAnonDecl()) {
std::string s;
if (s_index == 0) {
// "From" side gets fully qualified name.
s = l->getQualifiedNameAsString();
}
else {
// "To" side gets "classname::literal".
s = r->getQualifiedNameAsString() + "::" +
l->getName().str();
}
s = clean_name(s, s);
if (d.d_ns[Tags[Literal]].emplace(s).second) {
a.report(l, check_name, "DD01",
"Found " + Tags[Literal] + " " + s);
}
}
}
});
mf.addDynamicMatcher(
decl(forEachDescendant(
namespaceDecl(
forEach(recordDecl(isDefinition(),
forEach(enumDecl(
forEach(enumConstantDecl(
).bind(Tags[Literal]))
).bind(Tags[Enum]))
).bind(Tags[Class]))
).bind("n"))),
&m3);
OnMatch<> m4([&](const BoundNodes &nodes) {
if (!nodes.getNodeAs<NamespaceDecl>("n")->isAnonymousNamespace()) {
auto t = nodes.getNodeAs<ClassTemplateDecl>(Tags[Template]);
if (m.isWrittenInMainFile(t->getLocation()) &&
t->isThisDeclarationADefinition()) {
std::string s = t->getQualifiedNameAsString();
s = clean_name(s, s);
if (d.d_ns[Tags[Template]].emplace(s).second) {
a.report(t, check_name, "DD01",
"Found " + Tags[Template] + " " + s);
}
}
}
});
mf.addDynamicMatcher(
decl(forEachDescendant(
namespaceDecl(
forEach(classTemplateDecl(
).bind(Tags[Template]))
).bind("n"))),
&m4);
OnMatch<> m5([&](const BoundNodes &nodes) {
if (!nodes.getNodeAs<NamespaceDecl>("n")->isAnonymousNamespace()) {
auto t = nodes.getNodeAs<TypedefNameDecl>(Tags[Typedef]);
if (m.isWrittenInMainFile(t->getLocation())) {
std::string s = t->getQualifiedNameAsString();
s = clean_name(s, s);
if (d.d_ns[Tags[Typedef]].emplace(s).second) {
a.report(t, check_name, "DD01",
"Found " + Tags[Typedef] + " " + s);
}
}
}
});
mf.addDynamicMatcher(
decl(forEachDescendant(
namespaceDecl(
forEach(typedefDecl(
).bind(Tags[Typedef]))
).bind("n"))),
&m5);
mf.match(*tu, *a.context());
s_names[s_index] = d.d_ns;
s_index = 1 - s_index;
if (s_index == 0) {
llvm::StringRef file = a.config()->value("refactorfile");
if (file == "" || file == "-") {
file = "refactor.cfg";
}
std::error_code ec;
llvm::raw_fd_ostream f(file, ec, llvm::sys::fs::F_Append);
if (ec) {
ERRS() << "File error " << file << " " << ec.message() << "\n";
return;
}
f << "append refactor file(" << s_files[0] << "," << s_files[1] << ")";
for (int t = 0; t < NTags; ++t) {
for (llvm::StringRef i : s_names[0][Tags[t]]) {
std::string bm = best_match(i, s_names[1][Tags[t]]);
if (bm.size() == 0) {
if (t == Typedef) {
// Likely an existing forward declaration.
continue;
}
bm = "@@@/* Need replacement for " + i.str() + " */";
}
else if (t == Literal) {
bm = prefer_e(bm, s_names[1][Tags[t]]);
}
f << " \\\n name(" << i << "," << bm << ")";
}
}
f << "\n";
}
}
void subscribe(Analyser& analyser, Visitor&, PPObserver& observer)
{
analyser.onTranslationUnitDone += report(analyser);
}
} // close anonymous namespace
// ----------------------------------------------------------------------------
static RegisterCheck c1(check_name, &subscribe);
// ----------------------------------------------------------------------------
// Copyright (C) 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 34.599476 | 79 | 0.500492 | [
"object"
] |
9221024306e70a0c73710495acd8aba03a86bd24 | 4,457 | cpp | C++ | automated-tests/src/dali-platform-abstraction/utc-image-loading-common.cpp | Coquinho/dali-adaptor | a8006aea66b316a5eb710e634db30f566acda144 | [
"Apache-2.0",
"BSD-3-Clause"
] | 6 | 2016-11-18T10:26:46.000Z | 2021-11-01T12:29:05.000Z | automated-tests/src/dali-platform-abstraction/utc-image-loading-common.cpp | Coquinho/dali-adaptor | a8006aea66b316a5eb710e634db30f566acda144 | [
"Apache-2.0",
"BSD-3-Clause"
] | 5 | 2020-07-15T11:30:49.000Z | 2020-12-11T19:13:46.000Z | automated-tests/src/dali-platform-abstraction/utc-image-loading-common.cpp | expertisesolutions/dali-adaptor | 810bf4dea833ea7dfbd2a0c82193bc0b3b155011 | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2019-05-17T07:14:40.000Z | 2021-05-24T07:25:26.000Z | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "utc-image-loading-common.h"
double GetTimeMilliseconds(Integration::PlatformAbstraction& abstraction)
{
timespec timeSpec;
clock_gettime(CLOCK_MONOTONIC, &timeSpec);
return (timeSpec.tv_sec * 1e3) + (timeSpec.tv_nsec / 1e6);
}
/** Live platform abstraction recreated for each test case. */
TizenPlatform::TizenPlatformAbstraction* gAbstraction = 0;
/** A variety of parameters to reach different code paths in image loading code. */
std::vector<ImageParameters> gCancelAttributes;
void utc_dali_loading_startup(void)
{
test_return_value = TET_UNDEF;
gAbstraction = TizenPlatform::CreatePlatformAbstraction();
// Setup some loading parameters to engage post-processing stages:
ImageParameters scaleToFillAttributes;
scaleToFillAttributes.second.first = FittingMode::SCALE_TO_FILL;
scaleToFillAttributes.first = ImageDimensions(160, 120);
gCancelAttributes.push_back(scaleToFillAttributes);
// Hit the derived dimensions code:
ImageParameters scaleToFillAttributesDeriveWidth = scaleToFillAttributes;
scaleToFillAttributesDeriveWidth.first = ImageDimensions(0, 120);
gCancelAttributes.push_back(scaleToFillAttributesDeriveWidth);
ImageParameters scaleToFillAttributesDeriveHeight = scaleToFillAttributes;
scaleToFillAttributesDeriveHeight.first = ImageDimensions(160, 0);
gCancelAttributes.push_back(scaleToFillAttributesDeriveHeight);
// Try to push a tall crop:
ImageParameters scaleToFillAttributesTall = scaleToFillAttributes;
scaleToFillAttributesTall.first = ImageDimensions(160, 480);
ImageParameters scaleToFillAttributesTall2 = scaleToFillAttributes;
scaleToFillAttributesTall2.first = ImageDimensions(160, 509);
ImageParameters scaleToFillAttributesTall3 = scaleToFillAttributes;
scaleToFillAttributesTall3.first = ImageDimensions(37, 251);
gCancelAttributes.push_back(scaleToFillAttributesTall);
gCancelAttributes.push_back(scaleToFillAttributesTall2);
gCancelAttributes.push_back(scaleToFillAttributesTall3);
// Try to push a wide crop:
ImageParameters scaleToFillAttributesWide = scaleToFillAttributes;
scaleToFillAttributesWide.first = ImageDimensions(320, 60);
ImageParameters scaleToFillAttributesWide2 = scaleToFillAttributes;
scaleToFillAttributesWide2.first = ImageDimensions(317, 60);
ImageParameters scaleToFillAttributesWide3 = scaleToFillAttributes;
scaleToFillAttributesWide3.first = ImageDimensions(317, 53);
gCancelAttributes.push_back(scaleToFillAttributesWide);
gCancelAttributes.push_back(scaleToFillAttributesWide2);
gCancelAttributes.push_back(scaleToFillAttributesWide3);
ImageParameters shrinkToFitAttributes = scaleToFillAttributes;
shrinkToFitAttributes.second.first = FittingMode::SHRINK_TO_FIT;
gCancelAttributes.push_back(shrinkToFitAttributes);
ImageParameters fitWidthAttributes = scaleToFillAttributes;
fitWidthAttributes.second.first = FittingMode::FIT_WIDTH;
gCancelAttributes.push_back(fitWidthAttributes);
ImageParameters fitHeightAttributes = scaleToFillAttributes;
fitHeightAttributes.second.first = FittingMode::FIT_HEIGHT;
gCancelAttributes.push_back(fitHeightAttributes);
///@ToDo: Add attribute variants for all scale modes.
///@ToDo: Add attribute variants for all filter modes.
// Pad the array to a prime number to mitigate any accidental periodic
// patterns in which image file has which attributes applied to its load:
srand48(104729);
const float lastUniques = gCancelAttributes.size() - 0.001f;
while(gCancelAttributes.size() < 61u)
{
gCancelAttributes.push_back(gCancelAttributes[unsigned(drand48() * lastUniques)]);
}
}
void utc_dali_loading_cleanup(void)
{
delete gAbstraction;
gAbstraction = 0;
test_return_value = TET_PASS;
}
| 41.268519 | 86 | 0.786403 | [
"vector"
] |
922db149ffc572b0ce42bbea64585c9606cb7dbd | 12,306 | cpp | C++ | src/IECore/ObjectInterpolator.cpp | goddardl/cortex | 323a160fd831569591cde1504f415a638f8b85bc | [
"BSD-3-Clause"
] | null | null | null | src/IECore/ObjectInterpolator.cpp | goddardl/cortex | 323a160fd831569591cde1504f415a638f8b85bc | [
"BSD-3-Clause"
] | null | null | null | src/IECore/ObjectInterpolator.cpp | goddardl/cortex | 323a160fd831569591cde1504f415a638f8b85bc | [
"BSD-3-Clause"
] | 1 | 2020-09-26T01:15:37.000Z | 2020-09-26T01:15:37.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2009, Image Engine Design Inc. All rights reserved.
// Copyright (c) 2012, John Haddon. 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 Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECore/Object.h"
#include "IECore/Interpolator.h"
#include "IECore/ObjectInterpolator.h"
#include "IECore/CompoundData.h"
#include "IECore/CompoundObject.h"
#include "IECore/Primitive.h"
#include "IECore/DespatchTypedData.h"
using namespace IECore;
namespace IECore
{
struct LinearInterpolator< Object >::Adaptor
{
typedef ObjectPtr ReturnType;
const Data *m_y0;
const Data *m_y1;
double m_x;
Adaptor( const Object *y0, const Object *y1, double x ) : m_x( x )
{
m_y0 = assertedStaticCast< const Data >( y0 );
m_y1 = assertedStaticCast< const Data >( y1 );
}
template<typename T>
ReturnType operator()( typename T::Ptr result )
{
const T *y0 = assertedStaticCast< const T>( m_y0 );
const T *y1 = assertedStaticCast< const T>( m_y1 );
LinearInterpolator<T>()( y0, y1, m_x, result );
return result;
};
};
void LinearInterpolator< Object >::operator()( const Object *y0, const Object *y1, double x, ObjectPtr &result ) const
{
if ( y0->typeId() != y1->typeId() || y0->typeId() != result->typeId() )
{
throw( Exception( "Interpolation objects type don't match!" ) );
}
if ( y0->isInstanceOf( CompoundDataTypeId ) )
{
const CompoundData *x0 = assertedStaticCast<const CompoundData>( y0 );
const CompoundData *x1 = assertedStaticCast<const CompoundData>( y1 );
CompoundDataPtr xRes = assertedStaticCast<CompoundData>( result );
for ( CompoundDataMap::const_iterator it0 = x0->readable().begin(); it0 != x0->readable().end(); it0++ )
{
CompoundDataMap::const_iterator it1 = x1->readable().find( it0->first );
if ( it1 != x1->readable().end() && it0->second->typeId() == it1->second->typeId() )
{
ObjectPtr resultObj = Object::create( it0->second->typeId() );
LinearInterpolator< Object >()( it0->second.get(), it1->second.get(), x, resultObj );
if ( resultObj )
{
xRes->writable()[ it0->first ] = assertedStaticCast<Data>( resultObj );
}
else
{
xRes->writable()[ it0->first ] = it0->second;
}
}
}
}
else if ( y0->isInstanceOf( CompoundObjectTypeId ) )
{
const CompoundObject *x0 = assertedStaticCast<const CompoundObject>( y0 );
const CompoundObject *x1 = assertedStaticCast<const CompoundObject>( y1 );
CompoundObjectPtr xRes = assertedStaticCast<CompoundObject>( result );
for ( CompoundObject::ObjectMap::const_iterator it0 = x0->members().begin(); it0 != x0->members().end(); it0++ )
{
CompoundObject::ObjectMap::const_iterator it1 = x1->members().find( it0->first );
if ( it1 != x1->members().end() && it0->second->typeId() == it1->second->typeId() )
{
ObjectPtr resultObj = Object::create( it0->second->typeId() );
LinearInterpolator< Object >()( it0->second.get(), it1->second.get(), x, resultObj );
if ( resultObj )
{
xRes->members()[ it0->first ] = resultObj;
}
else
{
xRes->members()[ it0->first ] = it0->second;
}
}
}
}
else if ( y0->isInstanceOf( PrimitiveTypeId ) )
{
const Primitive *x0 = assertedStaticCast<const Primitive>( y0 );
const Primitive *x1 = assertedStaticCast<const Primitive>( y1 );
if( x0->variableSize( PrimitiveVariable::Uniform ) == x1->variableSize( PrimitiveVariable::Uniform ) &&
x0->variableSize( PrimitiveVariable::Varying ) == x1->variableSize( PrimitiveVariable::Varying ) &&
x0->variableSize( PrimitiveVariable::Vertex ) == x1->variableSize( PrimitiveVariable::Vertex ) &&
x0->variableSize( PrimitiveVariable::FaceVarying ) == x1->variableSize( PrimitiveVariable::FaceVarying )
)
{
PrimitivePtr xRes = assertedStaticCast<Primitive>( result );
xRes->Object::copyFrom( (const Object *)x0 ); // to get topology and suchlike copied over
// interpolate blindData
const Object *bd0 = x0->blindData();
const Object *bd1 = x1->blindData();
ObjectPtr bdr = xRes->blindData();
LinearInterpolator<Object>()( bd0, bd1, x, bdr );
// interpolate primitive variables
for( PrimitiveVariableMap::const_iterator it0 = x0->variables.begin(); it0 != x0->variables.end(); it0++ )
{
PrimitiveVariableMap::const_iterator it1 = x1->variables.find( it0->first );
if( it1 != x1->variables.end() &&
it0->second.data->typeId() == it1->second.data->typeId() &&
it0->second.interpolation == it1->second.interpolation
)
{
PrimitiveVariableMap::iterator itRes = xRes->variables.find( it0->first );
ObjectPtr resultData = linearObjectInterpolation( it0->second.data.get(), it1->second.data.get(), x );
if( resultData )
{
itRes->second.data = boost::static_pointer_cast<Data>( resultData );
}
}
}
}
else
{
// primitive topologies don't match
result = 0;
}
}
else if ( result->isInstanceOf( DataTypeId ) )
{
DataPtr data = runTimeCast< Data >( result );
Adaptor adaptor( y0, y1, x );
result = despatchTypedData<
Adaptor,
TypeTraits::IsStrictlyInterpolable,
DespatchTypedDataIgnoreError
>( data.get(), adaptor );
}
else
{
result = 0;
}
}
struct CubicInterpolator< Object >::Adaptor
{
typedef ObjectPtr ReturnType;
const Data *m_y0;
const Data *m_y1;
const Data *m_y2;
const Data *m_y3;
double m_x;
Adaptor( const Object *y0, const Object *y1, const Object *y2, const Object *y3, double x ) : m_x( x )
{
m_y0 = assertedStaticCast< const Data >( y0 );
m_y1 = assertedStaticCast< const Data >( y1 );
m_y2 = assertedStaticCast< const Data >( y2 );
m_y3 = assertedStaticCast< const Data >( y3 );
}
template<typename T>
ReturnType operator()( typename T::Ptr result )
{
const T *y0 = assertedStaticCast< const T >( m_y0 );
const T *y1 = assertedStaticCast< const T >( m_y1 );
const T *y2 = assertedStaticCast< const T >( m_y2 );
const T *y3 = assertedStaticCast< const T >( m_y3 );
CubicInterpolator<T>()( y0, y1, y2, y3, m_x, result );
return result;
}
};
void CubicInterpolator<Object>::operator()( const Object *y0, const Object *y1, const Object *y2, const Object *y3, double x, ObjectPtr &result ) const
{
if ( y0->typeId() != y1->typeId() || y0->typeId() != y2->typeId() || y0->typeId() != y3->typeId() || y0->typeId() != result->typeId() )
{
throw( Exception( "Interpolation objects type don't match!" ) );
}
if ( y0->isInstanceOf( CompoundDataTypeId ) )
{
const CompoundData *x0 = assertedStaticCast<const CompoundData>( y0 );
const CompoundData *x1 = assertedStaticCast<const CompoundData>( y1 );
const CompoundData *x2 = assertedStaticCast<const CompoundData>( y2 );
const CompoundData *x3 = assertedStaticCast<const CompoundData>( y3 );
CompoundDataPtr xRes = assertedStaticCast<CompoundData>( result );
for ( CompoundDataMap::const_iterator it1 = x1->readable().begin(); it1 != x1->readable().end(); it1++ )
{
CompoundDataMap::const_iterator it0 = x0->readable().find( it1->first );
if ( it0 != x0->readable().end() && it0->second->typeId() == it1->second->typeId() )
{
CompoundDataMap::const_iterator it2 = x2->readable().find( it1->first );
if ( it2 != x2->readable().end() && it0->second->typeId() == it2->second->typeId() )
{
CompoundDataMap::const_iterator it3 = x3->readable().find( it1->first );
if ( it3 != x3->readable().end() && it0->second->typeId() == it3->second->typeId() )
{
ObjectPtr resultObj = Object::create( it1->second->typeId() );
CubicInterpolator< Object >()( it0->second.get(), it1->second.get(), it2->second.get(), it3->second.get(), x, resultObj );
if ( resultObj )
{
xRes->writable()[ it1->first ] = assertedStaticCast<Data>( resultObj );
}
else
{
xRes->writable()[ it1->first ] = it1->second;
}
}
else
{
xRes->writable()[ it1->first ] = it1->second;
}
}
else
{
xRes->writable()[ it1->first ] = it1->second;
}
}
else
{
xRes->writable()[ it1->first ] = it1->second;
}
}
}
else if ( y0->isInstanceOf( CompoundObjectTypeId ) )
{
const CompoundObject *x0 = assertedStaticCast<const CompoundObject>( y0 );
const CompoundObject *x1 = assertedStaticCast<const CompoundObject>( y1 );
const CompoundObject *x2 = assertedStaticCast<const CompoundObject>( y2 );
const CompoundObject *x3 = assertedStaticCast<const CompoundObject>( y3 );
CompoundObjectPtr xRes = assertedStaticCast<CompoundObject>( result );
for ( CompoundObject::ObjectMap::const_iterator it1 = x1->members().begin(); it1 != x1->members().end(); it1++ )
{
CompoundObject::ObjectMap::const_iterator it0 = x0->members().find( it1->first );
if ( it0 != x0->members().end() && it0->second->typeId() == it1->second->typeId() )
{
CompoundObject::ObjectMap::const_iterator it2 = x2->members().find( it1->first );
if ( it2 != x2->members().end() && it0->second->typeId() == it2->second->typeId() )
{
CompoundObject::ObjectMap::const_iterator it3 = x3->members().find( it1->first );
if ( it3 != x3->members().end() && it0->second->typeId() == it3->second->typeId() )
{
ObjectPtr resultObj = Object::create( it1->second->typeId() );
CubicInterpolator< Object >()( it0->second.get(), it1->second.get(), it2->second.get(), it3->second.get(), x, resultObj );
if ( resultObj )
{
xRes->members()[ it1->first ] = resultObj;
}
else
{
xRes->members()[ it1->first ] = it1->second;
}
}
else
{
xRes->members()[ it1->first ] = it1->second;
}
}
else
{
xRes->members()[ it1->first ] = it1->second;
}
}
else
{
xRes->members()[ it1->first ] = it1->second;
}
}
}
else if ( result->isInstanceOf( DataTypeId ) )
{
DataPtr data = runTimeCast< Data >( result );
Adaptor converter( y0, y1, y2, y3, x );
result = despatchTypedData<
Adaptor,
TypeTraits::IsStrictlyInterpolable,
DespatchTypedDataIgnoreError
>( data.get(), converter );
}
else
{
result = 0;
}
}
ObjectPtr linearObjectInterpolation( const Object *y0, const Object *y1, double x )
{
ObjectPtr result = Object::create( y0->typeId() );
LinearInterpolator<Object>()( y0, y1, x, result );
return result;
}
ObjectPtr cubicObjectInterpolation( const Object *y0, const Object *y1, const Object *y2, const Object *y3, double x )
{
ObjectPtr result = Object::create( y0->typeId() );
CubicInterpolator<Object>()( y0, y1, y2, y3, x, result );
return result;
}
}
| 34.86119 | 151 | 0.647327 | [
"object"
] |
9232dc651894b7241de0c7c7be8c6095553b7004 | 1,512 | hpp | C++ | test/bound/read/raw_json_reader_tests.hpp | ChadHartman/rapidjson-binder | 5da9484e9737d74fe9403df37a8df8872d472af6 | [
"BSD-3-Clause"
] | null | null | null | test/bound/read/raw_json_reader_tests.hpp | ChadHartman/rapidjson-binder | 5da9484e9737d74fe9403df37a8df8872d472af6 | [
"BSD-3-Clause"
] | null | null | null | test/bound/read/raw_json_reader_tests.hpp | ChadHartman/rapidjson-binder | 5da9484e9737d74fe9403df37a8df8872d472af6 | [
"BSD-3-Clause"
] | null | null | null | #ifndef BOUND_READ_RAW_JSON_READER_TESTS_HPP_
#define BOUND_READ_RAW_JSON_READER_TESTS_HPP_
#include "tests.h"
namespace bound_read_raw_json_reader_tests_hpp_
{
void TestReadRawJson(std::string &&json)
{
bound::JsonRaw raw_json;
bound::read::Parser<rapidjson::StringStream> parser{rapidjson::StringStream(json.c_str())};
bound::read::RawJsonReader<rapidjson::StringStream>(parser).Read(raw_json);
REQUIRE(json == raw_json.value);
}
TEST_CASE("Raw Json Reader Tests", "[raw_json_reader_tests]")
{
SECTION("Null")
{
TestReadRawJson("null");
}
SECTION("Bool")
{
TestReadRawJson("true");
}
SECTION("Int")
{
TestReadRawJson("-3200");
}
SECTION("Uint")
{
TestReadRawJson("3200");
}
SECTION("Double")
{
TestReadRawJson("44.44");
}
SECTION("String")
{
TestReadRawJson("\"Foo\"");
}
SECTION("Object")
{
TestReadRawJson("{\"Foo\":\"Bar\"}");
}
SECTION("Array")
{
TestReadRawJson("[\"Foo\",\"Bar\"]");
}
SECTION("Object Recurse")
{
TestReadRawJson("{\"Foo\":{\"Bar\":\"Baz\"}}");
}
SECTION("Array Recurse")
{
TestReadRawJson("[[\"Foo\"],[\"Bar\"]]");
}
SECTION("Object Mix")
{
TestReadRawJson("{\"Foo\":[\"Bar\",\"Baz\"]}");
}
SECTION("Array Mix")
{
TestReadRawJson("[{\"Foo\":\"Bar\"}]");
}
}
} // namespace bound_read_raw_json_reader_tests_hpp_
#endif | 19.139241 | 95 | 0.570106 | [
"object"
] |
9234ca148cf01f88147ad552d113afdc1b906a72 | 9,575 | cpp | C++ | lonestar/experimental/meshsingularities/DAGSolver3D/Node.cpp | rohankadekodi/compilers_project | 2f9455a5d0c516b9f1766afd1cdac1b86c930ec0 | [
"BSD-3-Clause"
] | null | null | null | lonestar/experimental/meshsingularities/DAGSolver3D/Node.cpp | rohankadekodi/compilers_project | 2f9455a5d0c516b9f1766afd1cdac1b86c930ec0 | [
"BSD-3-Clause"
] | 7 | 2020-02-27T19:24:51.000Z | 2020-04-10T21:04:28.000Z | lonestar/experimental/meshsingularities/DAGSolver3D/Node.cpp | rohankadekodi/compilers_project | 2f9455a5d0c516b9f1766afd1cdac1b86c930ec0 | [
"BSD-3-Clause"
] | 2 | 2020-02-17T22:00:40.000Z | 2020-03-24T10:18:02.000Z | /*
* This file belongs to the Galois project, a C++ library for exploiting parallelism.
* The code is being released under the terms of the 3-Clause BSD License (a
* copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
#include "Node.hpp"
#include <set>
#include <algorithm>
#include "Analysis.hpp"
void Node::setLeft(Node* left) { this->left = left; }
void Node::setRight(Node* right) { this->right = right; }
void Node::setParent(Node* parent) { this->parent = parent; }
void Node::addElement(Element* e) { this->mergedElements.push_back(e); }
void Node::clearElements() { this->mergedElements.clear(); }
void Node::setProduction(std::string& prodname) { this->production = prodname; }
std::string& Node::getProduction() { return this->production; }
Node* Node::getLeft() const { return this->left; }
Node* Node::getRight() const { return this->right; }
Node* Node::getParent() const { return this->parent; }
std::vector<Element*>& Node::getElements() { return this->mergedElements; }
int Node::getId() const { return this->node; }
void Node::addSupernode(uint64_t supernode) {
this->supernodes.push_back(supernode);
}
std::vector<uint64_t>& Node::getSupernodes() { return this->supernodes; }
void Node::clearSupernodes() { this->supernodes.clear(); }
void Node::setSupernodesToElim(uint64_t supernodes) {
this->supernodesToElim = supernodes;
}
uint64_t Node::getSupernodesToElim() const { return this->supernodesToElim; }
void Node::computeOffsets() {
uint64_t j;
uint64_t k;
j = 0;
k = 0;
offsets.resize(getSupernodes().size() + 1);
for (uint64_t i : getSupernodes()) {
offsets[k] = j;
j += (*meshSupernodes)[i];
++k;
}
offsets[k] = j;
}
void Node::allocateSystem(SolverMode mode) {
uint64_t dofs;
dofs = 0;
for (uint64_t supernode : getSupernodes()) {
dofs += (*meshSupernodes)[supernode];
}
this->system = new EquationSystem(dofs, mode);
}
void Node::deallocateSystem() {
if (this->system)
delete this->system;
this->system = NULL;
}
void Node::fillin() const {
int i, j;
double** matrix = this->system->matrix;
double* rhs = this->system->rhs;
int n = this->system->n;
for (j = 0; j < n; ++j) {
for (i = 0; i < n; ++i) {
matrix[j][i] = i == j ? 1.0 : 0.0;
}
rhs[j] = 1.0;
}
}
void Node::merge() const {
int i, j;
uint64_t k, l;
Node *left, *right;
double** matrix;
double** lmatrix;
double** rmatrix;
double* rhs;
double* rrhs;
double* lrhs;
left = this->left;
right = this->right;
matrix = system->matrix;
rhs = system->rhs;
lmatrix = left->system->matrix;
rmatrix = right->system->matrix;
rrhs = right->system->rhs;
lrhs = left->system->rhs;
if (system->mode != CHOLESKY) {
for (j = left->getSupernodesToElim(); j < left->getSupernodes().size();
++j) {
for (i = left->getSupernodesToElim(); i < left->getSupernodes().size();
++i) {
for (k = left->offsets[j]; k < left->offsets[j + 1]; ++k) {
uint64_t x;
x = offsets[leftPlaces[j - left->getSupernodesToElim()]] +
(k - left->offsets[j]);
for (l = left->offsets[i]; l < left->offsets[i + 1]; ++l) {
uint64_t y;
y = offsets[leftPlaces[i - left->getSupernodesToElim()]] +
(l - left->offsets[i]);
matrix[x][y] = lmatrix[k][l];
}
}
}
for (k = left->offsets[j]; k < left->offsets[j + 1]; ++k) {
rhs[offsets[leftPlaces[j - left->getSupernodesToElim()]] +
(k - left->offsets[j])] = lrhs[k];
}
}
for (j = right->getSupernodesToElim(); j < right->getSupernodes().size();
++j) {
for (i = right->getSupernodesToElim(); i < right->getSupernodes().size();
++i) {
for (k = right->offsets[j]; k < right->offsets[j + 1]; ++k) {
uint64_t x;
x = offsets[rightPlaces[j - right->getSupernodesToElim()]] +
(k - right->offsets[j]);
for (l = right->offsets[i]; l < right->offsets[i + 1]; ++l) {
uint64_t y;
y = offsets[rightPlaces[i - right->getSupernodesToElim()]] +
(l - right->offsets[i]);
matrix[x][y] += rmatrix[k][l];
}
}
}
for (k = right->offsets[j]; k < right->offsets[j + 1]; ++k) {
rhs[offsets[rightPlaces[j - right->getSupernodesToElim()]] +
(k - right->offsets[j])] += rrhs[k];
}
}
} else {
for (j = left->getSupernodesToElim(); j < left->getSupernodes().size();
++j) {
for (i = j; i < left->getSupernodes().size(); ++i) {
for (k = left->offsets[j]; k < left->offsets[j + 1]; ++k) {
uint64_t x;
x = offsets[leftPlaces[j - left->getSupernodesToElim()]] +
(k - left->offsets[j]);
for (l = i == j ? k : left->offsets[i]; l < left->offsets[i + 1];
++l) {
uint64_t y;
y = offsets[leftPlaces[i - left->getSupernodesToElim()]] +
(l - left->offsets[i]);
matrix[x][y] = lmatrix[k][l];
}
}
}
for (k = left->offsets[j]; k < left->offsets[j + 1]; ++k) {
rhs[offsets[leftPlaces[j - left->getSupernodesToElim()]] +
(k - left->offsets[j])] = lrhs[k];
}
}
for (j = right->getSupernodesToElim(); j < right->getSupernodes().size();
++j) {
for (i = j; i < right->getSupernodes().size(); ++i) {
for (k = right->offsets[j]; k < right->offsets[j + 1]; ++k) {
uint64_t x;
x = offsets[rightPlaces[j - right->getSupernodesToElim()]] +
(k - right->offsets[j]);
for (l = right->offsets[i]; l < right->offsets[i + 1]; ++l) {
uint64_t y;
y = offsets[rightPlaces[i - right->getSupernodesToElim()]] +
(l - right->offsets[i]);
matrix[x][y] += rmatrix[k][l];
}
}
}
for (k = right->offsets[j]; k < right->offsets[j + 1]; ++k) {
rhs[offsets[rightPlaces[j - right->getSupernodesToElim()]] +
(k - right->offsets[j])] += rrhs[k];
}
}
}
}
void Node::eliminate() const {
uint64_t dofs;
uint64_t i;
if ((left == NULL && right != NULL) || (left != NULL && right == NULL)) {
printf("Error at node: %d\n", node);
throw std::string("invalid tree!");
}
if (left != NULL && right != NULL) {
// this->mergeProduction(left->system->matrix, left->system->rhs,
// right->system->matrix, right->system->rhs,
// this->system->matrix, this->system->rhs);
this->merge();
} else {
// this->preprocessProduction();
this->fillin();
}
dofs = 0;
for (i = 0; i < getSupernodesToElim(); ++i) {
dofs += (*meshSupernodes)[supernodes[i]];
}
system->eliminate(dofs);
}
void Node::bs() const {
// system->backwardSubstitute(this->getSupernodesToElim());
/*for (int i=0; i<system->n; ++i) {
if (fabs(system->rhs[i]-1.0) > 1e-8) {
printf("WRONG SOLUTION - [%lu] %d: %lf\n", this->getId(), i,
system->rhs[i]);
}
}*/
}
/* DEBUG*/
int Node::treeSize() {
int ret = 1;
if (this->getLeft() != NULL) {
ret += this->getLeft()->treeSize();
}
if (this->getRight() != NULL) {
ret += this->getRight()->treeSize();
}
return ret;
}
unsigned long Node::getSizeInMemory(bool recursive) {
unsigned long total =
this->supernodes.size() * this->supernodes.size() * sizeof(double) +
this->supernodes.size() * sizeof(double*);
if (recursive && left != NULL && right != NULL) {
total += left->getSizeInMemory() + right->getSizeInMemory();
}
return total;
}
unsigned long Node::getFLOPs(bool recursive) {
auto flops = [](unsigned int a, unsigned int b) {
return a * (6 * b * b - 6 * a * b + 6 * b + 2 * a * a - 3 * a + 1) / 6;
};
unsigned long total =
flops(this->getSupernodesToElim(), this->getSupernodes().size());
if (recursive && left != NULL && right != NULL) {
total += left->getFLOPs() + right->getFLOPs();
}
return total;
}
unsigned long Node::getMemoryRearrangements() {
unsigned long total = 0;
if (left != NULL && right != NULL) {
unsigned long memLeft =
(left->getSupernodes().size() - left->getSupernodesToElim());
memLeft *= memLeft;
unsigned long memRight =
(right->getSupernodes().size() - right->getSupernodesToElim());
memRight *= memRight;
total = memLeft + memRight + left->getMemoryRearrangements() +
right->getMemoryRearrangements();
}
return total;
}
/*END OF DEBUG*/
| 30.787781 | 85 | 0.577023 | [
"vector"
] |
92350022986d731a1dca3b7d0ea9ed9ec69d72a8 | 3,301 | cc | C++ | hpyplm/dhpyplm_train.cc | redpony/cpyp | 7ecb1801af3636f9d5ae008799ae412d476153e2 | [
"Apache-2.0"
] | 29 | 2015-01-21T07:18:16.000Z | 2021-06-10T00:57:54.000Z | hpyplm/dhpyplm_train.cc | redpony/cpyp | 7ecb1801af3636f9d5ae008799ae412d476153e2 | [
"Apache-2.0"
] | null | null | null | hpyplm/dhpyplm_train.cc | redpony/cpyp | 7ecb1801af3636f9d5ae008799ae412d476153e2 | [
"Apache-2.0"
] | 8 | 2015-02-25T06:02:46.000Z | 2021-06-10T00:57:38.000Z | #include <iostream>
#include <unordered_map>
#include <cstdlib>
#include "corpus/corpus.h"
#include "cpyp/m.h"
#include "cpyp/random.h"
#include "cpyp/crp.h"
#include "cpyp/mf_crp.h"
#include "cpyp/tied_parameter_resampler.h"
#include "uvector.h"
#include "dhpyplm.h"
#include "cpyp/boost_serializers.h"
#include <boost/serialization/vector.hpp>
#include <boost/archive/binary_oarchive.hpp>
// A not very memory-efficient implementation of a domain adapting
// HPYP language model, as described by Wood & Teh (AISTATS, 2009)
//
// I use templates to handle the recursive formalation of the prior, so
// the order of the model has to be specified here, at compile time:
#define kORDER 3
using namespace std;
using namespace cpyp;
Dict dict;
int main(int argc, char** argv) {
if (argc < 4) {
cerr << argv[0] << " <training1.txt> <training2.txt> [...] <output.dlm> <nsamples>\n\nInfer a " << kORDER << "-gram HPYP LM and write the trained model\n100 is usually sufficient for <nsamples>\n";
return 1;
}
MT19937 eng;
vector<string> train_files;
for (int i = 1; i < argc - 2; ++i)
train_files.push_back(argv[i]);
string output_file = argv[argc - 2];
int samples = atoi(argv[argc - 1]);
assert(samples > 0);
{
ifstream test(output_file);
if (test.good()) {
cerr << "File " << output_file << " appears to exist: please remove\n";
return 1;
}
}
int d = 1;
for (auto& tf : train_files)
cerr << (d++==1 ? " [primary] " : "[secondary] ")
<< "training corpus "<< ": " << tf << endl;
set<unsigned> vocab;
const unsigned kSOS = dict.Convert("<s>");
const unsigned kEOS = dict.Convert("</s>");
vector<vector<vector<unsigned> > > corpora(train_files.size());
d = 0;
for (const auto& train_file : train_files)
ReadFromFile(train_file, &dict, &corpora[d++], &vocab);
PYPLM<kORDER> latent_lm(vocab.size(), 1, 1, 1, 1);
vector<DAPYPLM<kORDER>> dlm(corpora.size(), DAPYPLM<kORDER>(latent_lm)); // domain LMs
vector<unsigned> ctx(kORDER - 1, kSOS);
for (int sample=0; sample < samples; ++sample) {
int ci = 0;
for (const auto& corpus : corpora) {
DAPYPLM<kORDER>& lm = dlm[ci];
++ci;
for (const auto& s : corpus) {
ctx.resize(kORDER - 1);
for (unsigned i = 0; i <= s.size(); ++i) {
unsigned w = (i < s.size() ? s[i] : kEOS);
if (sample > 0) lm.decrement(w, ctx, eng);
lm.increment(w, ctx, eng);
ctx.push_back(w);
}
}
}
if (sample % 10 == 9) {
double llh = latent_lm.log_likelihood();
for (auto& lm : dlm) llh += lm.log_likelihood();
cerr << " [LLH=" << llh << "]\n";
if (sample % 30u == 29) {
for (auto& lm : dlm) lm.resample_hyperparameters(eng);
latent_lm.resample_hyperparameters(eng);
}
} else { cerr << '.' << flush; }
}
cerr << "Writing LM to " << output_file << " ...\n";
ofstream ofile(output_file.c_str(), ios::out | ios::binary);
if (!ofile.good()) {
cerr << "Failed to open " << output_file << " for writing\n";
return 1;
}
boost::archive::binary_oarchive oa(ofile);
oa & dict;
oa & latent_lm;
unsigned num_domains = dlm.size();
oa & num_domains;
for (unsigned i = 0; i < num_domains; ++i)
oa & dlm[i];
return 0;
}
| 31.141509 | 201 | 0.607392 | [
"vector",
"model"
] |
9235e7b2b7f212b2af57ada848c8215e42b35ae8 | 88,355 | cc | C++ | src/runtime/instr.cc | mizuki-nana/coreVM | 1ff863b890329265a86ff46b0fdf7bac8e362f0e | [
"MIT"
] | 2 | 2017-02-12T21:59:54.000Z | 2017-02-13T14:57:48.000Z | src/runtime/instr.cc | mizuki-nana/coreVM | 1ff863b890329265a86ff46b0fdf7bac8e362f0e | [
"MIT"
] | null | null | null | src/runtime/instr.cc | mizuki-nana/coreVM | 1ff863b890329265a86ff46b0fdf7bac8e362f0e | [
"MIT"
] | null | null | null | /*******************************************************************************
The MIT License (MIT)
Copyright (c) 2016 Yanzheng Li
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 "instr.h"
#include "catch_site.h"
#include "compartment.h"
#include "dbgmem_printer.h"
#include "dbgvar_printer.h"
#include "frame.h"
#include "frame_printer.h"
#include "invocation_ctx.h"
#include "process.h"
#include "utils.h"
#include "corevm/macros.h"
#include "dyobj/util.h"
#include "types/interfaces.h"
#include "types/native_type_value.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <ostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <boost/format.hpp>
namespace corevm {
namespace runtime {
// -----------------------------------------------------------------------------
#if defined(__clang__) and __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc99-extensions"
#endif
InstrHandler*
InstrHandlerMeta::instr_handlers[INSTR_CODE_MAX] {
/* -------------------------- Object instructions ------------------------- */
/* NEW */ instr_handler_new ,
/* LDOBJ */ instr_handler_ldobj ,
/* STOBJ */ instr_handler_stobj ,
/* STOBJN */ instr_handler_stobjn ,
/* GETATTR */ instr_handler_getattr ,
/* SETATTR */ instr_handler_setattr ,
/* DELATTR */ instr_handler_delattr ,
/* HASATTR2 */ instr_handler_hasattr2 ,
/* GETATTR2 */ instr_handler_getattr2 ,
/* SETATTR2 */ instr_handler_setattr2 ,
/* DELATTR2 */ instr_handler_delattr2 ,
/* POP */ instr_handler_pop ,
/* LDOBJ2 */ instr_handler_ldobj2 ,
/* STOBJ2 */ instr_handler_stobj2 ,
/* DELOBJ */ instr_handler_delobj ,
/* DELOBJ2 */ instr_handler_delobj2 ,
/* GETVAL */ instr_handler_getval ,
/* SETVAL */ instr_handler_setval ,
/* GETVAL2 */ instr_handler_getval2 ,
/* CLRVAL */ instr_handler_clrval ,
/* CPYVAL */ instr_handler_cpyval ,
/* CPYREPR */ instr_handler_cpyrepr ,
/* ISTRUTHY */ instr_handler_istruthy ,
/* OBJEQ */ instr_handler_objeq ,
/* OBJNEQ */ instr_handler_objneq ,
/* SETCTX */ instr_handler_setctx ,
/* CLDOBJ */ instr_handler_cldobj ,
/* RSETATTRS */ instr_handler_rsetattrs ,
/* SETATTRS */ instr_handler_setattrs ,
/* PUTOBJ */ instr_handler_putobj ,
/* GETOBJ */ instr_handler_getobj ,
/* SWAP */ instr_handler_swap ,
/* SETFLGC */ instr_handler_setflgc ,
/* SETFLDEL */ instr_handler_setfldel ,
/* SETFLCALL */ instr_handler_setflcall ,
/* SETFLMUTE */ instr_handler_setflmute ,
/* -------------------------- Control instructions ------------------------ */
/* PINVK */ instr_handler_pinvk ,
/* INVK */ instr_handler_invk ,
/* RTRN */ instr_handler_rtrn ,
/* JMP */ instr_handler_jmp ,
/* JMPIF */ instr_handler_jmpif ,
/* JMPR */ instr_handler_jmpr ,
/* EXC */ instr_handler_exc ,
/* EXCOBJ */ instr_handler_excobj ,
/* CLREXC */ instr_handler_clrexc ,
/* JMPEXC */ instr_handler_jmpexc ,
/* EXIT */ instr_handler_exit ,
/* ------------------------- Function instructions ------------------------ */
/* PUTARG */ instr_handler_putarg ,
/* PUTKWARG */ instr_handler_putkwarg ,
/* PUTARGS */ instr_handler_putargs ,
/* PUTKWARGS */ instr_handler_putkwargs ,
/* GETARG */ instr_handler_getarg ,
/* GETKWARG */ instr_handler_getkwarg ,
/* GETARGS */ instr_handler_getargs ,
/* GETKWARGS */ instr_handler_getkwargs ,
/* HASARGS */ instr_handler_hasargs ,
/* ------------------------- Runtime instructions ------------------------- */
/* GC */ instr_handler_gc ,
/* DEBUG */ instr_handler_debug ,
/* DBGFRM */ instr_handler_dbgfrm ,
/* DBGMEM */ instr_handler_dbgmem ,
/* DBGVAR */ instr_handler_dbgvar ,
/* PRINT */ instr_handler_print ,
/* SWAP2 */ instr_handler_swap2 ,
/* ---------------- Arithmetic and logic instructions --------------------- */
/* POS */ instr_handler_pos ,
/* NEG */ instr_handler_neg ,
/* INC */ instr_handler_inc ,
/* DEC */ instr_handler_dec ,
/* ABS */ instr_handler_abs ,
/* SQRT */ instr_handler_sqrt ,
/* ADD */ instr_handler_add ,
/* SUB */ instr_handler_sub ,
/* MUL */ instr_handler_mul ,
/* DIV */ instr_handler_div ,
/* MOD */ instr_handler_mod ,
/* POW */ instr_handler_pow ,
/* BNOT */ instr_handler_bnot ,
/* BAND */ instr_handler_band ,
/* BOR */ instr_handler_bor ,
/* BXOR */ instr_handler_bxor ,
/* BLS */ instr_handler_bls ,
/* BRS */ instr_handler_brs ,
/* EQ */ instr_handler_eq ,
/* NEQ */ instr_handler_neq ,
/* GT */ instr_handler_gt ,
/* LT */ instr_handler_lt ,
/* GTE */ instr_handler_gte ,
/* LTE */ instr_handler_lte ,
/* LNOT */ instr_handler_lnot ,
/* LAND */ instr_handler_land ,
/* LOR */ instr_handler_lor ,
/* CMP */ instr_handler_cmp ,
/* ----------------- Native type creation instructions -------------------- */
/* INT8 */ instr_handler_int8 ,
/* UINT8 */ instr_handler_uint8 ,
/* INT16 */ instr_handler_int16 ,
/* UINT16 */ instr_handler_uint16 ,
/* INT32 */ instr_handler_int32 ,
/* UINT32 */ instr_handler_uint32 ,
/* INT64 */ instr_handler_int64 ,
/* UINT64 */ instr_handler_uint64 ,
/* BOOL */ instr_handler_bool ,
/* DEC1 */ instr_handler_dec1 ,
/* DEC2 */ instr_handler_dec2 ,
/* STR */ instr_handler_str ,
/* ARY */ instr_handler_ary ,
/* MAP */ instr_handler_map ,
/* ----------------- Native type conversion instructions ------------------ */
/* TOINT8 */ instr_handler_2int8 ,
/* TOUINT8 */ instr_handler_2uint8 ,
/* TOINT16 */ instr_handler_2int16 ,
/* TOUINT16 */ instr_handler_2uint16 ,
/* TOINT32 */ instr_handler_2int32 ,
/* TOUINT32 */ instr_handler_2uint32 ,
/* TOINT64 */ instr_handler_2int64 ,
/* TOUINT64 */ instr_handler_2uint64 ,
/* TOBOOL */ instr_handler_2bool ,
/* TODEC1 */ instr_handler_2dec1 ,
/* TODEC2 */ instr_handler_2dec2 ,
/* TOSTR */ instr_handler_2str ,
/* TOARY */ instr_handler_2ary ,
/* TOMAP */ instr_handler_2map ,
/* ----------------- Native type manipulation instructions ---------------- */
/* TRUTHY */ instr_handler_truthy ,
/* REPR */ instr_handler_repr ,
/* HASH */ instr_handler_hash ,
/* SLICE */ instr_handler_slice ,
/* STRIDE */ instr_handler_stride ,
/* REVERSE */ instr_handler_reverse ,
/* ROUND */ instr_handler_round ,
/* --------------------- String type instructions ------------------------- */
/* STRLEN */ instr_handler_strlen ,
/* STRAT */ instr_handler_strat ,
/* STRCLR */ instr_handler_strclr ,
/* STRAPD */ instr_handler_strapd ,
/* STRPSH */ instr_handler_strpsh ,
/* STRIST */ instr_handler_strist ,
/* STRIST2 */ instr_handler_strist2 ,
/* STRERS */ instr_handler_strers ,
/* STRERS2 */ instr_handler_strers2 ,
/* STRRPLC */ instr_handler_strrplc ,
/* STRSWP */ instr_handler_strswp ,
/* STRSUB */ instr_handler_strsub ,
/* STRSUB2 */ instr_handler_strsub2 ,
/* STRFND */ instr_handler_strfnd ,
/* STRFND2 */ instr_handler_strfnd2 ,
/* STRRFND */ instr_handler_strrfnd ,
/* STRRFND2 */ instr_handler_strrfnd2 ,
/* --------------------- Array type instructions -------------------------- */
/* ARYLEN */ instr_handler_arylen ,
/* ARYEMP */ instr_handler_aryemp ,
/* ARYAT */ instr_handler_aryat ,
/* ARYFRT */ instr_handler_aryfrt ,
/* ARYBAK */ instr_handler_arybak ,
/* ARYPUT */ instr_handler_aryput ,
/* ARYAPND */ instr_handler_aryapnd ,
/* ARYERS */ instr_handler_aryers ,
/* ARYPOP */ instr_handler_arypop ,
/* ARYSWP */ instr_handler_aryswp ,
/* ARYCLR */ instr_handler_aryclr ,
/* ARYMRG */ instr_handler_arymrg ,
/* --------------------- Map type instructions ---------------------------- */
/* MAPLEN */ instr_handler_maplen ,
/* MAPEMP */ instr_handler_mapemp ,
/* MAPFIND */ instr_handler_mapfind ,
/* MAPAT */ instr_handler_mapat ,
/* MAPPUT */ instr_handler_mapput ,
/* MAPSET */ instr_handler_mapset ,
/* MAPERS */ instr_handler_mapers ,
/* MAPCLR */ instr_handler_mapclr ,
/* MAPSWP */ instr_handler_mapswp ,
/* MAPKEYS */ instr_handler_mapkeys ,
/* MAPVALS */ instr_handler_mapvals ,
/* MAPMRG */ instr_handler_mapmrg
};
#if defined(__clang__) and __clang__
#pragma clang diagnostic pop
#endif /* #if defined(__clang__) and __clang__ */
// -----------------------------------------------------------------------------
/* --------------------------- INSTRUCTION HANDLERS ------------------------- */
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_unary_operator_instr(Frame* frame, InterfaceFunc interface_func)
{
types::NativeTypeValue& oprd = frame->top_eval_stack();
interface_func(oprd);
}
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_binary_operator_instr(Frame* frame, InterfaceFunc interface_func)
{
size_t eval_stack_size = frame->eval_stack_size();
if (eval_stack_size < 2)
{
THROW(EvaluationStackEmptyError());
}
types::NativeTypeValue& lhs = frame->eval_stack_element(eval_stack_size - 1);
types::NativeTypeValue& rhs = frame->eval_stack_element(eval_stack_size - 2);
lhs = interface_func(lhs, rhs);
}
// -----------------------------------------------------------------------------
template<typename NativeType>
static
void
execute_native_integer_type_creation_instr(const Instr& instr, Frame* frame)
{
types::NativeTypeValue type_val(NativeType(instr.oprd1));
frame->push_eval_stack(std::move(type_val));
}
// -----------------------------------------------------------------------------
template<typename NativeType>
static
void
execute_native_floating_type_creation_instr(const Instr& instr, Frame* frame)
{
const Compartment* compartment = frame->compartment();
auto encoding_key = static_cast<encoding_key_t>(instr.oprd1);
auto fpt_literal = static_cast<NativeType>(compartment->get_fpt_literal(encoding_key));
types::NativeTypeValue type_val(fpt_literal);
frame->push_eval_stack(std::move(type_val));
}
// -----------------------------------------------------------------------------
template<typename NativeType>
static
void
execute_native_complex_type_creation_instr(
const Instr& /* instr */, Frame* frame)
{
NativeType value;
types::NativeTypeValue type_val(value);
frame->push_eval_stack(std::move(type_val));
}
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_native_type_conversion_instr(Frame* frame, InterfaceFunc interface_func)
{
types::NativeTypeValue& oprd = frame->top_eval_stack();
interface_func(oprd);
}
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_native_type_complex_instr_with_single_operand(
Frame* frame, InterfaceFunc interface_func)
{
types::NativeTypeValue& oprd = frame->top_eval_stack();
oprd = interface_func(oprd);
}
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_native_type_complex_instr_with_single_operand_in_place(
Frame* frame, InterfaceFunc interface_func)
{
types::NativeTypeValue& oprd = frame->top_eval_stack();
interface_func(oprd);
}
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_native_type_complex_instr_with_two_operands(
Frame* frame, InterfaceFunc interface_func)
{
size_t eval_stack_size = frame->eval_stack_size();
if (eval_stack_size < 2)
{
THROW(EvaluationStackEmptyError());
}
types::NativeTypeValue& oprd1 = frame->eval_stack_element(eval_stack_size - 1);
types::NativeTypeValue& oprd2 = frame->eval_stack_element(eval_stack_size - 2);
oprd1 = interface_func(oprd1, oprd2);
}
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_native_type_complex_instr_with_two_operands_in_place(Frame* frame,
InterfaceFunc interface_func)
{
size_t eval_stack_size = frame->eval_stack_size();
if (eval_stack_size < 2)
{
THROW(EvaluationStackEmptyError());
}
types::NativeTypeValue& oprd1 = frame->eval_stack_element(eval_stack_size - 1);
types::NativeTypeValue& oprd2 = frame->eval_stack_element(eval_stack_size - 2);
interface_func(oprd1, oprd2);
}
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_native_type_complex_instr_with_three_operands(Frame* frame,
InterfaceFunc interface_func)
{
size_t eval_stack_size = frame->eval_stack_size();
if (eval_stack_size < 3)
{
THROW(EvaluationStackEmptyError());
}
types::NativeTypeValue& oprd1 = frame->eval_stack_element(eval_stack_size - 1);
types::NativeTypeValue& oprd2 = frame->eval_stack_element(eval_stack_size - 2);
types::NativeTypeValue& oprd3 = frame->eval_stack_element(eval_stack_size - 3);
oprd1 = interface_func(oprd1, oprd2, oprd3);
}
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_native_type_complex_instr_with_three_operands_in_place(Frame* frame,
InterfaceFunc interface_func)
{
size_t eval_stack_size = frame->eval_stack_size();
if (eval_stack_size < 3)
{
THROW(EvaluationStackEmptyError());
}
types::NativeTypeValue& oprd1 = frame->eval_stack_element(eval_stack_size - 1);
types::NativeTypeValue& oprd2 = frame->eval_stack_element(eval_stack_size - 2);
types::NativeTypeValue& oprd3 = frame->eval_stack_element(eval_stack_size - 3);
interface_func(oprd1, oprd2, oprd3);
}
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_native_type_complex_instr_with_four_operands(Frame* frame,
InterfaceFunc interface_func)
{
size_t eval_stack_size = frame->eval_stack_size();
if (eval_stack_size < 4)
{
THROW(EvaluationStackEmptyError());
}
types::NativeTypeValue& oprd1 = frame->eval_stack_element(eval_stack_size - 1);
types::NativeTypeValue& oprd2 = frame->eval_stack_element(eval_stack_size - 2);
types::NativeTypeValue& oprd3 = frame->eval_stack_element(eval_stack_size - 3);
types::NativeTypeValue& oprd4 = frame->eval_stack_element(eval_stack_size - 4);
oprd1 = interface_func(oprd1, oprd2, oprd3, oprd4);
}
// -----------------------------------------------------------------------------
template<typename InterfaceFunc>
static
void
execute_native_type_complex_instr_with_four_operands_in_place(Frame* frame,
InterfaceFunc interface_func)
{
size_t eval_stack_size = frame->eval_stack_size();
if (eval_stack_size < 4)
{
THROW(EvaluationStackEmptyError());
}
types::NativeTypeValue& oprd1 = frame->eval_stack_element(eval_stack_size - 1);
types::NativeTypeValue& oprd2 = frame->eval_stack_element(eval_stack_size - 2);
types::NativeTypeValue& oprd3 = frame->eval_stack_element(eval_stack_size - 3);
types::NativeTypeValue& oprd4 = frame->eval_stack_element(eval_stack_size - 4);
interface_func(oprd1, oprd2, oprd3, oprd4);
}
// -----------------------------------------------------------------------------
void
instr_handler_new(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.create_dyobj();
process.push_stack(obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_ldobj(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
Process::dyobj_ptr obj = NULL;
if (frame->get_visible_var_through_ancestry(key, &obj))
{
#if __DEBUG__
ASSERT(obj);
#endif
process.push_stack(obj);
}
else
{
std::string name;
const auto encoding_key = static_cast<encoding_key_t>(key);
frame->compartment()->get_string_literal(encoding_key, &name);
THROW(NameNotFoundError(name.c_str()));
}
}
// -----------------------------------------------------------------------------
void
instr_handler_stobj(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
Frame* frame = *frame_ptr;
auto obj = process.pop_stack();
obj->manager().on_setattr();
frame->set_visible_var(key, obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_stobjn(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
size_t n = static_cast<size_t>(instr.oprd2);
Frame& frame = process.top_nth_frame(n);
auto obj = process.pop_stack();
obj->manager().on_setattr();
frame.set_visible_var(key, obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_getattr(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto str_key = static_cast<encoding_key_t>(instr.oprd1);
auto frame = *frame_ptr;
auto obj = process.pop_stack();
auto attr_obj = getattr(obj, frame->compartment(), str_key);
process.push_stack(attr_obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_setattr(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto str_key = static_cast<encoding_key_t>(instr.oprd1);
auto frame = *frame_ptr;
auto attr_key = get_attr_key(frame->compartment(), str_key);
auto attr_obj = process.pop_stack();
auto target_obj = process.top_stack();
if (target_obj->get_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_IMMUTABLE))
{
THROW(InvalidOperationError(
str(boost::format("cannot mutate immutable object 0x%08x") % target_obj->id()).c_str()));
}
const char* attr_name = NULL;
frame->compartment()->get_string_literal(str_key, &attr_name);
process.insert_attr_name(attr_key, attr_name);
target_obj->putattr(attr_key, attr_obj);
attr_obj->manager().on_setattr();
}
// -----------------------------------------------------------------------------
void
instr_handler_delattr(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
dyobj::attr_key_t attr_key = static_cast<dyobj::attr_key_t>(instr.oprd1);
auto obj = process.pop_stack();
if (obj->get_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_IMMUTABLE))
{
THROW(InvalidOperationError(
str(boost::format("cannot mutate immutable object 0x%08x") % obj->id()).c_str()));
}
auto attr_obj = obj->getattr(attr_key);
attr_obj->manager().on_delattr();
obj->delattr(attr_key);
process.push_stack(obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_hasattr2(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.top_stack();
const auto frame = *frame_ptr;
types::NativeTypeValue type_val = frame->top_eval_stack();
auto attr_str = types::get_intrinsic_value_from_type_value<types::native_string>(type_val);
std::string attr_str_value = static_cast<std::string>(attr_str);
dyobj::attr_key_t attr_key = dyobj::hash_attr_str(attr_str);
const bool res_value = obj->hasattr(attr_key);
types::NativeTypeValue res( (types::boolean(res_value)) );
frame->push_eval_stack(std::move(res));
}
// -----------------------------------------------------------------------------
void
instr_handler_getattr2(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.pop_stack();
const auto frame = *frame_ptr;
types::NativeTypeValue type_val = frame->top_eval_stack();
auto attr_str = types::get_intrinsic_value_from_type_value<types::native_string>(type_val);
std::string attr_str_value = static_cast<std::string>(attr_str);
auto attr_obj = getattr(obj, attr_str_value);
process.push_stack(attr_obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_setattr2(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto attr_obj = process.pop_stack();
auto target_obj = process.top_stack();
const auto frame = *frame_ptr;
types::NativeTypeValue type_val = frame->top_eval_stack();
auto attr_str = types::get_intrinsic_value_from_type_value<types::native_string>(type_val);
std::string attr_str_value = static_cast<std::string>(attr_str);
dyobj::attr_key_t attr_key = dyobj::hash_attr_str(attr_str);
target_obj->putattr(attr_key, attr_obj);
attr_obj->manager().on_setattr();
process.insert_attr_name(attr_key, attr_str_value.c_str());
}
// -----------------------------------------------------------------------------
void
instr_handler_delattr2(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.top_stack();
const auto frame = *frame_ptr;
types::NativeTypeValue type_val = frame->top_eval_stack();
auto attr_str = types::get_intrinsic_value_from_type_value<types::native_string>(type_val);
std::string attr_str_value = static_cast<std::string>(attr_str);
dyobj::attr_key_t attr_key = dyobj::hash_attr_str(attr_str);
obj->delattr(attr_key);
}
// -----------------------------------------------------------------------------
void
instr_handler_pop(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
process.pop_stack();
}
// -----------------------------------------------------------------------------
void
instr_handler_ldobj2(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
Process::dyobj_ptr obj = NULL;
if (frame->get_invisible_var_through_ancestry(key, &obj))
{
#if __DEBUG__
ASSERT(obj);
#endif
process.push_stack(obj);
}
else
{
const auto encoding_key = static_cast<encoding_key_t>(key);
const char* name = NULL;
frame->compartment()->get_string_literal(encoding_key, &name);
THROW(NameNotFoundError(name));
}
}
// -----------------------------------------------------------------------------
void
instr_handler_stobj2(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
Frame* frame = *frame_ptr;
auto obj = process.pop_stack();
frame->set_invisible_var(key, obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_delobj(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
Frame* frame = *frame_ptr;
auto obj = frame->pop_visible_var(key);
if (obj->get_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_INDELIBLE))
{
THROW(ObjectDeletionError(obj->id()));
}
obj->manager().on_delete();
}
// -----------------------------------------------------------------------------
void
instr_handler_delobj2(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
Frame* frame = *frame_ptr;
auto obj = frame->pop_invisible_var(key);
if (obj->get_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_INDELIBLE))
{
THROW(ObjectDeletionError(obj->id()));
}
obj->manager().on_delete();
}
// -----------------------------------------------------------------------------
void
instr_handler_getval(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
auto obj = process.top_stack();
if (!obj->has_type_value())
{
THROW(NativeTypeValueNotFoundError());
}
frame->push_eval_stack(obj->type_value());
}
// -----------------------------------------------------------------------------
void
instr_handler_setval(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
types::NativeTypeValue type_val(frame->pop_eval_stack());
auto obj = process.top_stack();
if (!obj->has_type_value())
{
auto new_type_val = process.insert_type_value(type_val);
obj->set_type_value(new_type_val);
}
else
{
process.get_type_value(&obj->type_value()) = std::move(type_val);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_getval2(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
auto obj = frame->get_visible_var(key);
if (!obj->has_type_value())
{
THROW(NativeTypeValueNotFoundError());
}
frame->push_eval_stack(obj->type_value());
}
// -----------------------------------------------------------------------------
void
instr_handler_clrval(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.top_stack();
if (!obj->has_type_value())
{
THROW(NativeTypeValueNotFoundError());
}
process.erase_type_value(&obj->type_value());
obj->clear_type_value();
}
// -----------------------------------------------------------------------------
void
instr_handler_cpyval(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
auto src_obj = process.pop_stack();
auto target_obj = process.pop_stack();
if (!src_obj->has_type_value())
{
THROW(NativeTypeValueNotFoundError());
}
types::NativeTypeValue res = src_obj->type_value();
uint32_t type = static_cast<uint32_t>(instr.oprd1);
switch (type)
{
case 1:
{
types::interface_to_int8(res);
break;
}
case 2:
{
types::interface_to_uint8(res);
break;
}
case 3:
{
types::interface_to_int16(res);
break;
}
case 4:
{
types::interface_to_uint16(res);
break;
}
case 5:
{
types::interface_to_int32(res);
break;
}
case 6:
{
types::interface_to_uint32(res);
break;
}
case 7:
{
types::interface_to_int64(res);
break;
}
case 8:
{
types::interface_to_uint64(res);
break;
}
case 9:
{
types::interface_to_bool(res);
break;
}
case 10:
{
types::interface_to_dec1(res);
break;
}
case 11:
{
types::interface_to_dec2(res);
break;
}
case 12:
{
types::interface_to_str(res);
break;
}
case 13:
{
types::interface_to_ary(res);
break;
}
case 14:
{
types::interface_to_map(res);
break;
}
default:
// Ignore invalid type.
break;
}
auto new_type_val = process.insert_type_value(res);
target_obj->set_type_value(new_type_val);
}
// -----------------------------------------------------------------------------
void
instr_handler_cpyrepr(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
Process::dyobj_ptr src_obj = process.pop_stack();
Process::dyobj_ptr target_obj = process.pop_stack();
if (!src_obj->has_type_value())
{
THROW(NativeTypeValueNotFoundError());
}
const types::NativeTypeValue& type_val = src_obj->type_value();
auto res = types::interface_compute_repr_value(type_val);
auto new_type_val = process.insert_type_value(res);
target_obj->set_type_value(new_type_val);
}
// -----------------------------------------------------------------------------
void
instr_handler_istruthy(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
auto obj = process.top_stack();
if (!obj->has_type_value())
{
THROW(NativeTypeValueNotFoundError());
}
const types::NativeTypeValue& type_val = obj->type_value();
auto res = types::interface_compute_truthy_value(type_val);
frame->push_eval_stack(std::move(res));
}
// -----------------------------------------------------------------------------
void
instr_handler_objeq(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj1 = process.pop_stack();
auto obj2 = process.pop_stack();
types::NativeTypeValue type_val(types::boolean(obj1 == obj2));
Frame* frame = *frame_ptr;
frame->push_eval_stack(std::move(type_val));
}
// -----------------------------------------------------------------------------
void
instr_handler_objneq(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj1 = process.pop_stack();
auto obj2 = process.pop_stack();
types::NativeTypeValue type_val(types::boolean(obj1 != obj2));
Frame* frame = *frame_ptr;
frame->push_eval_stack(std::move(type_val));
}
// -----------------------------------------------------------------------------
void
instr_handler_setctx(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.top_stack();
Frame* frame = *frame_ptr;
ClosureCtx frame_cls = frame->closure_ctx();
ClosureCtx ctx(frame_cls.compartment_id, static_cast<closure_id_t>(instr.oprd1));
obj->set_closure_ctx(ctx);
}
// -----------------------------------------------------------------------------
void
instr_handler_cldobj(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
types::NativeTypeValue type_val = frame->pop_eval_stack();
bool value = types::get_intrinsic_value_from_type_value<bool>(type_val);
variable_key_t key1 = static_cast<variable_key_t>(instr.oprd1);
variable_key_t key2 = static_cast<variable_key_t>(instr.oprd2);
variable_key_t key = value ? key1 : key2;
Process::dyobj_ptr obj = NULL;
while (!frame->get_visible_var_fast(key, &obj))
{
frame = frame->parent();
if (!frame)
{
const auto encoding_key = static_cast<encoding_key_t>(key);
const char* name = NULL;
(*frame_ptr)->compartment()->get_string_literal(encoding_key, &name);
THROW(NameNotFoundError(name));
}
}
#if __DEBUG__
ASSERT(obj);
#endif
process.push_stack(obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_rsetattrs(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto str_key = static_cast<encoding_key_t>(instr.oprd1);
Frame* frame = *frame_ptr;
auto attr_key = get_attr_key(frame->compartment(), str_key);
auto attr_obj = process.top_stack();
types::NativeTypeValue& type_val = frame->top_eval_stack();
types::native_map map = types::get_intrinsic_value_from_type_value<
types::native_map>(type_val);
for (auto itr = map.begin(); itr != map.end(); ++itr)
{
dyobj::dyobj_id_t id = static_cast<dyobj::dyobj_id_t>(itr->second);
auto &obj = process.get_dyobj(id);
attr_obj->manager().on_setattr();
obj.putattr(attr_key, attr_obj);
}
const char* attr_name = NULL;
frame->compartment()->get_string_literal(static_cast<encoding_key_t>(str_key),
&attr_name);
process.insert_attr_name(attr_key, attr_name);
}
// -----------------------------------------------------------------------------
void
instr_handler_setattrs(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto self_str_key = static_cast<encoding_key_t>(instr.oprd1);
auto frame = *frame_ptr;
auto self_attr_key = get_attr_key(frame->compartment(), self_str_key);
auto src_obj = process.pop_stack();
auto target_obj = process.top_stack();
auto * objects = process.create_dyobjs(src_obj->attr_count());
const char* attr_name = NULL;
frame->compartment()->get_string_literal(self_str_key, &attr_name);
size_t i = 0;
for (auto itr = src_obj->begin(); itr != src_obj->end(); ++itr, ++i)
{
dyobj::attr_key_t attr_key = static_cast<dyobj::attr_key_t>(itr->first);
auto attr_obj = itr->second;
auto& cloned_attr_obj = objects[i];
cloned_attr_obj.copy_from(*attr_obj);
cloned_attr_obj.manager().on_setattr();
cloned_attr_obj.putattr(self_attr_key, target_obj);
target_obj->putattr(attr_key, &cloned_attr_obj);
process.insert_attr_name(attr_key, attr_name);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_putobj(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto ptr = process.top_stack();
Frame* frame = *frame_ptr;
types::uint64 value(ptr->id());
types::NativeTypeValue type_val(value);
frame->push_eval_stack(std::move(type_val));
}
// -----------------------------------------------------------------------------
void
instr_handler_getobj(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
auto type_val = frame->pop_eval_stack();
dyobj::dyobj_id_t id = types::get_intrinsic_value_from_type_value<dyobj::dyobj_id_t>(type_val);
process.push_stack(&process.get_dyobj(id));
}
// -----------------------------------------------------------------------------
void
instr_handler_swap(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
process.swap_stack();
}
// -----------------------------------------------------------------------------
void
instr_handler_setflgc(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.top_stack();
bool on_off = static_cast<bool>(instr.oprd1);
if (on_off)
{
obj->set_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_NOT_GARBAGE_COLLECTIBLE);
}
else
{
obj->clear_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_NOT_GARBAGE_COLLECTIBLE);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_setfldel(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.top_stack();
bool on_off = static_cast<bool>(instr.oprd1);
if (on_off)
{
obj->set_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_INDELIBLE);
}
else
{
obj->clear_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_INDELIBLE);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_setflcall(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.top_stack();
bool on_off = static_cast<bool>(instr.oprd1);
if (on_off)
{
obj->set_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_NON_CALLABLE);
}
else
{
obj->clear_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_NON_CALLABLE);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_setflmute(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.top_stack();
bool on_off = static_cast<bool>(instr.oprd1);
if (on_off)
{
obj->set_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_IMMUTABLE);
}
else
{
obj->clear_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_IMMUTABLE);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_pinvk(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** invk_ctx_ptr)
{
auto obj = process.top_stack();
if (obj->get_flag(dyobj::DynamicObjectFlagBits::DYOBJ_IS_NON_CALLABLE))
{
THROW(InvocationError(obj->id()));
}
const ClosureCtx& ctx = obj->closure_ctx();
if (ctx.compartment_id == NONESET_COMPARTMENT_ID)
{
THROW(CompartmentNotFoundError(ctx.compartment_id));
}
if (ctx.closure_id == NONESET_CLOSURE_ID)
{
THROW(ClosureNotFoundError(ctx.closure_id));
}
Compartment* compartment = nullptr;
process.get_compartment(ctx.compartment_id, &compartment);
Closure *closure = nullptr;
compartment->get_closure_by_id(ctx.closure_id, &closure);
#if __DEBUG__
ASSERT(compartment);
ASSERT(closure);
#endif
process.emplace_invocation_ctx(ctx, compartment, closure);
process.top_invocation_ctx(invk_ctx_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_invk(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** invk_ctx_ptr)
{
InvocationCtx* invk_ctx = *invk_ctx_ptr;
const ClosureCtx& ctx = invk_ctx->closure_ctx();
Compartment* compartment = invk_ctx->compartment();
Closure* closure = invk_ctx->closure();
process.emplace_frame(ctx, compartment, closure, process.pc());
process.top_frame(frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_rtrn(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** invk_ctx_ptr)
{
Frame* frame = *frame_ptr;
instr_addr_t return_addr = frame->return_addr();
if (return_addr == NONESET_INSTR_ADDR)
{
THROW(InvalidInstrAddrError());
}
process.pop_frame();
if (process.has_frame())
{
process.top_frame(frame_ptr);
process.top_invocation_ctx(invk_ctx_ptr);
}
if (process.stack_size() > 0)
{
auto obj = process.top_stack();
obj->manager().on_setattr();
}
}
// -----------------------------------------------------------------------------
void
instr_handler_jmp(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
instr_addr_t starting_addr = process.pc();
instr_addr_t relative_addr = static_cast<instr_addr_t>(instr.oprd1);
instr_addr_t addr = starting_addr + relative_addr;
if (addr == NONESET_INSTR_ADDR)
{
THROW(InvalidInstrAddrError());
}
process.set_pc(addr);
}
// -----------------------------------------------------------------------------
void
instr_handler_jmpif(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
instr_addr_t starting_addr = process.pc();
instr_addr_t relative_addr = static_cast<instr_addr_t>(instr.oprd1);
instr_addr_t addr = starting_addr + relative_addr;
if (addr == NONESET_INSTR_ADDR)
{
THROW(InvalidInstrAddrError());
}
types::NativeTypeValue& type_val = frame->top_eval_stack();
bool value = types::get_intrinsic_value_from_type_value<bool>(type_val);
if (value)
{
process.set_pc(addr);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_jmpr(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
const instr_addr_t starting_addr = 0;
auto relative_addr = static_cast<instr_addr_t>(instr.oprd1);
const instr_addr_t addr = starting_addr + relative_addr;
if (addr == NONESET_INSTR_ADDR)
{
THROW(InvalidInstrAddrError());
}
process.set_pc(addr);
}
// -----------------------------------------------------------------------------
void
instr_handler_exc(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** invk_ctx_ptr)
{
bool search_catch_sites = static_cast<bool>(instr.oprd1);
while (process.has_frame())
{
Frame& frame = process.top_frame();
auto exc_obj = process.pop_stack();
instr_addr_t starting_addr = 0;
int64_t dst = 0;
if (search_catch_sites)
{
const Closure *closure = frame.closure();
#if __DEBUG__
ASSERT(closure);
#endif
uint32_t index = static_cast<uint32_t>(process.pc() - starting_addr);
if (search_catch_sites)
{
const auto& catch_sites = closure->catch_sites;
auto itr = std::find_if(
catch_sites.begin(),
catch_sites.end(),
[&index](const CatchSite& catch_site) -> bool {
return index >= catch_site.from && index <= catch_site.to;
}
);
if (itr != catch_sites.end())
{
const CatchSite& catch_site = *itr;
dst = catch_site.dst;
}
}
}
if (dst)
{
// A catch site found in the current frame. Jump to its destination.
frame.set_exc_obj(exc_obj);
instr_addr_t addr =
starting_addr + static_cast<instr_addr_t>(dst);
// Minus one so that it will be `addr` after this instruction finishes,
// since the pc gets incremented after every instruction.
process.set_pc(addr - 1);
return;
}
else
{
// No matching catch site found in the current frame.
// Pop the current frame, and set the exc object on the previous frame.
process.pop_frame();
if (process.has_frame())
{
runtime::Frame& previous_frame = process.top_frame();
*frame_ptr = &previous_frame;
*invk_ctx_ptr = &process.top_invocation_ctx();
previous_frame.set_exc_obj(exc_obj);
process.push_stack(exc_obj);
// Need to search catch sites in the other frames.
search_catch_sites = true;
}
}
}
}
// -----------------------------------------------------------------------------
void
instr_handler_excobj(const Instr& /* instr */, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
const Frame* frame = *frame_ptr;
auto exc_obj = frame->exc_obj();
if (!exc_obj)
{
THROW(InvalidOperationError("No exception raised"));
}
else
{
process.push_stack(exc_obj);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_clrexc(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
frame->clear_exc_obj();
}
// -----------------------------------------------------------------------------
void
instr_handler_jmpexc(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
const Frame* frame = *frame_ptr;
auto exc_obj = frame->exc_obj();
bool jump_on_exc = static_cast<bool>(instr.oprd2);
bool jump = jump_on_exc ? static_cast<bool>(exc_obj) : exc_obj == NULL;
if (jump)
{
instr_addr_t starting_addr = process.pc();
instr_addr_t relative_addr =
static_cast<instr_addr_t>(instr.oprd1);
instr_addr_t addr = starting_addr + relative_addr;
if (addr == NONESET_INSTR_ADDR)
{
THROW(InvalidInstrAddrError());
}
else if (addr < starting_addr)
{
THROW(InvalidInstrAddrError());
}
process.set_pc(addr);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_exit(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
process.terminate_exec();
}
// -----------------------------------------------------------------------------
void
instr_handler_putarg(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** invk_ctx_ptr)
{
auto obj = process.pop_stack();
obj->manager().on_setattr();
InvocationCtx* invk_ctx = *invk_ctx_ptr;
invk_ctx->put_param(obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_putkwarg(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** invk_ctx_ptr)
{
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
InvocationCtx* invk_ctx = *invk_ctx_ptr;
auto obj = process.pop_stack();
obj->manager().on_setattr();
invk_ctx->put_param_value_pair(key, obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_putargs(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** invk_ctx_ptr)
{
InvocationCtx* invk_ctx = *invk_ctx_ptr;
auto obj = process.pop_stack();
const types::NativeTypeValue& type_val = obj->type_value();
types::native_array array =
types::get_intrinsic_value_from_type_value<types::native_array>(type_val);
for (auto itr = array.begin(); itr != array.end(); ++itr)
{
dyobj::dyobj_id_t arg_id = static_cast<dyobj::dyobj_id_t>(*itr);
auto& arg_obj = process.get_dyobj(arg_id);
arg_obj.manager().on_setattr();
invk_ctx->put_param(&arg_obj);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_putkwargs(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** invk_ctx_ptr)
{
InvocationCtx* invk_ctx = *invk_ctx_ptr;
auto obj = process.pop_stack();
const types::NativeTypeValue& result = obj->type_value();
types::native_map map =
types::get_intrinsic_value_from_type_value<types::native_map>(result);
for (auto itr = map.begin(); itr != map.end(); ++itr)
{
variable_key_t arg_key = static_cast<variable_key_t>(itr->first);
dyobj::dyobj_id_t arg_id = static_cast<dyobj::dyobj_id_t>(itr->second);
auto& arg_obj = process.get_dyobj(arg_id);
arg_obj.manager().on_setattr();
invk_ctx->put_param_value_pair(arg_key, &arg_obj);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_getarg(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** invk_ctx_ptr)
{
InvocationCtx* invk_ctx = *invk_ctx_ptr;
auto obj = invk_ctx->pop_param();
obj->manager().on_setattr();
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
Frame* frame = *frame_ptr;
frame->set_visible_var(key, obj);
}
// -----------------------------------------------------------------------------
void
instr_handler_getkwarg(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** invk_ctx_ptr)
{
InvocationCtx* invk_ctx = *invk_ctx_ptr;
variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
if (invk_ctx->has_param_value_pair_with_key(key))
{
auto obj = invk_ctx->pop_param_value_pair(key);
Frame* frame = *frame_ptr;
frame->set_visible_var(key, obj);
auto relative_addr = static_cast<instr_addr_t>(instr.oprd2);
process.set_pc(process.pc() + relative_addr);
}
}
// -----------------------------------------------------------------------------
void
instr_handler_getargs(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** invk_ctx_ptr)
{
Frame* frame = *frame_ptr;
InvocationCtx* invk_ctx = *invk_ctx_ptr;
types::native_array array;
while (invk_ctx->has_params())
{
auto obj = invk_ctx->pop_param();
array.push_back(obj->id());
}
types::NativeTypeValue type_val(std::move(array));
frame->push_eval_stack(std::move(type_val));
}
// -----------------------------------------------------------------------------
void
instr_handler_getkwargs(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** invk_ctx_ptr)
{
Frame* frame = *frame_ptr;
InvocationCtx* invk_ctx = *invk_ctx_ptr;
types::native_map map;
std::vector<variable_key_t> params = invk_ctx->param_value_pair_keys();
for (auto itr = params.begin(); itr != params.end(); ++itr)
{
variable_key_t key = static_cast<variable_key_t>(*itr);
auto obj = invk_ctx->pop_param_value_pair(key);
auto key_val = static_cast<typename types::native_map::key_type>(key);
map[key_val] = obj->id();
}
types::NativeTypeValue type_val(std::move(map));
frame->push_eval_stack(std::move(type_val));
}
// -----------------------------------------------------------------------------
void
instr_handler_hasargs(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** invk_ctx_ptr)
{
Frame* frame = *frame_ptr;
InvocationCtx* invk_ctx = *invk_ctx_ptr;
const bool result = invk_ctx->has_params();
types::NativeTypeValue type_val( (types::boolean(result)) );
frame->push_eval_stack(std::move(type_val));
}
// -----------------------------------------------------------------------------
void
instr_handler_gc(const Instr& /* instr */, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
process.do_gc();
}
// -----------------------------------------------------------------------------
void
instr_handler_debug(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
const uint32_t opts = static_cast<uint32_t>(instr.oprd1);
Process::Printer printer(process, opts);
printer(std::cout) << std::endl;
}
// -----------------------------------------------------------------------------
void
instr_handler_dbgfrm(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
auto& frame = *frame_ptr;
const uint32_t opts = static_cast<uint32_t>(instr.oprd1);
FramePrinter printer(*frame, opts);
printer(std::cout) << std::endl;
}
// -----------------------------------------------------------------------------
void
instr_handler_dbgmem(const Instr& instr, Process& /* process */,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
const uint32_t opts = static_cast<uint32_t>(instr.oprd1);
DbgMemPrinter printer(opts);
printer(std::cout) << std::endl;
}
// -----------------------------------------------------------------------------
void
instr_handler_dbgvar(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
const encoding_key_t encoding_key = static_cast<encoding_key_t>(instr.oprd1);
Frame* frame = *frame_ptr;
std::string variable_name;
frame->compartment()->get_string_literal(encoding_key, &variable_name);
const variable_key_t key = static_cast<variable_key_t>(instr.oprd1);
Process::dyobj_ptr obj = NULL;
if (frame->get_visible_var_through_ancestry(key, &obj))
{
#if __DEBUG__
ASSERT(obj);
#endif
}
else
{
std::string name;
frame->compartment()->get_string_literal(encoding_key, &name);
THROW(NameNotFoundError(name.c_str()));
}
DbgvarPrinter printer(process, *frame, variable_name.c_str(), obj);
printer(std::cout);
}
// -----------------------------------------------------------------------------
void
instr_handler_print(const Instr& instr, Process& process,
Frame** /* frame_ptr */, InvocationCtx** /* invk_ctx_ptr */)
{
auto obj = process.top_stack();
if (!obj->has_type_value())
{
THROW(NativeTypeValueNotFoundError());
}
const types::NativeTypeValue& type_val = obj->type_value();
types::native_string native_str =
types::get_intrinsic_value_from_type_value<types::native_string>(type_val);
static const char* PRINT_FORMATS[2] = { "%s", "%s\n" };
const size_t index = static_cast<size_t>(instr.oprd1) % 2;
printf(PRINT_FORMATS[index], native_str.c_str());
}
// -----------------------------------------------------------------------------
void
instr_handler_swap2(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
frame->swap_eval_stack();
}
// -----------------------------------------------------------------------------
void
instr_handler_pos(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_unary_operator_instr(*frame_ptr, types::interface_apply_positive_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_neg(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_unary_operator_instr(*frame_ptr, types::interface_apply_negation_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_inc(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_unary_operator_instr(*frame_ptr, types::interface_apply_increment_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_dec(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_unary_operator_instr(*frame_ptr, types::interface_apply_decrement_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_abs(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_unary_operator_instr(*frame_ptr, types::interface_apply_abs_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_sqrt(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_unary_operator_instr(*frame_ptr, types::interface_apply_sqrt_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_add(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_addition_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_sub(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_subtraction_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_mul(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_multiplication_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_div(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_division_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_mod(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_modulus_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_pow(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_pow_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_bnot(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_unary_operator_instr(*frame_ptr, types::interface_apply_bitwise_not_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_band(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_bitwise_and_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_bor(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_bitwise_or_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_bxor(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_bitwise_xor_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_bls(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_bitwise_left_shift_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_brs(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_bitwise_right_shift_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_eq(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_eq_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_neq(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_neq_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_gt(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_gt_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_lt(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_lt_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_gte(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_gte_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_lte(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_lte_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_lnot(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_unary_operator_instr(*frame_ptr, types::interface_apply_logical_not_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_land(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_logical_and_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_lor(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_logical_or_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_cmp(
const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_binary_operator_instr(*frame_ptr, types::interface_apply_cmp_operator);
}
// -----------------------------------------------------------------------------
void
instr_handler_int8(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_integer_type_creation_instr<types::int8>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_uint8(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_integer_type_creation_instr<types::uint8>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_int16(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_integer_type_creation_instr<types::int16>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_uint16(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_integer_type_creation_instr<types::uint16>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_int32(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_integer_type_creation_instr<types::int32>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_uint32(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_integer_type_creation_instr<types::uint32>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_int64(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_integer_type_creation_instr<types::int64>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_uint64(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_integer_type_creation_instr<types::uint64>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_bool(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_integer_type_creation_instr<types::boolean>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_dec1(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_floating_type_creation_instr<types::decimal>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_dec2(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_floating_type_creation_instr<types::decimal2>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_str(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
// String type is different than other complex types.
Frame* frame = *frame_ptr;
std::string str;
if (instr.oprd1 > 0)
{
auto encoding_key = static_cast<runtime::encoding_key_t>(instr.oprd1);
const Compartment* compartment = frame->compartment();
str = compartment->get_string_literal(encoding_key);
}
types::NativeTypeValue type_val = types::string(str);
frame->push_eval_stack(std::move(type_val));
}
// -----------------------------------------------------------------------------
void
instr_handler_ary(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_complex_type_creation_instr<types::array>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_map(const Instr& instr, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_complex_type_creation_instr<types::map>(instr, *frame_ptr);
}
// -----------------------------------------------------------------------------
void
instr_handler_2int8(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_int8);
}
// -----------------------------------------------------------------------------
void
instr_handler_2uint8(
const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_uint8);
}
// -----------------------------------------------------------------------------
void
instr_handler_2int16(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_int16);
}
// -----------------------------------------------------------------------------
void
instr_handler_2uint16(
const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_uint16);
}
// -----------------------------------------------------------------------------
void
instr_handler_2int32(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_int32);
}
// -----------------------------------------------------------------------------
void
instr_handler_2uint32(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_uint32);
}
// -----------------------------------------------------------------------------
void
instr_handler_2int64(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_int64);
}
// -----------------------------------------------------------------------------
void
instr_handler_2uint64(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_uint64);
}
// -----------------------------------------------------------------------------
void
instr_handler_2bool(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_bool);
}
// -----------------------------------------------------------------------------
void
instr_handler_2dec1(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_dec1);
}
// -----------------------------------------------------------------------------
void
instr_handler_2dec2(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_dec2);
}
// -----------------------------------------------------------------------------
void
instr_handler_2str(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_str);
}
// -----------------------------------------------------------------------------
void
instr_handler_2ary(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_ary);
}
// -----------------------------------------------------------------------------
void
instr_handler_2map(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_conversion_instr(*frame_ptr, types::interface_to_map);
}
// -----------------------------------------------------------------------------
void
instr_handler_truthy(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
types::NativeTypeValue& oprd = frame->top_eval_stack();
types::NativeTypeValue result =
types::interface_compute_truthy_value(oprd);
frame->push_eval_stack(std::move(result));
}
// -----------------------------------------------------------------------------
void
instr_handler_repr(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
types::NativeTypeValue& oprd = frame->top_eval_stack();
types::NativeTypeValue result =
types::interface_compute_repr_value(oprd);
frame->push_eval_stack(std::move(result));
}
// -----------------------------------------------------------------------------
void
instr_handler_hash(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
Frame* frame = *frame_ptr;
types::NativeTypeValue& oprd = frame->top_eval_stack();
types::NativeTypeValue result =
types::interface_compute_hash_value(oprd);
frame->push_eval_stack(std::move(result));
}
// -----------------------------------------------------------------------------
void
instr_handler_slice(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_three_operands(*frame_ptr,
types::interface_compute_slice);
}
// -----------------------------------------------------------------------------
void
instr_handler_stride(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_compute_stride);
}
// -----------------------------------------------------------------------------
void
instr_handler_reverse(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_compute_reverse);
}
// -----------------------------------------------------------------------------
void
instr_handler_round(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_apply_rounding);
}
// -----------------------------------------------------------------------------
void
instr_handler_strlen(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_string_get_size);
}
// -----------------------------------------------------------------------------
void
instr_handler_strat(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_string_at_2);
}
// -----------------------------------------------------------------------------
void
instr_handler_strclr(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand_in_place(*frame_ptr,
types::interface_string_clear);
}
// -----------------------------------------------------------------------------
void
instr_handler_strapd(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands_in_place(*frame_ptr,
types::interface_string_append);
}
// -----------------------------------------------------------------------------
void
instr_handler_strpsh(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands_in_place(*frame_ptr,
types::interface_string_pushback);
}
// -----------------------------------------------------------------------------
void
instr_handler_strist(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_three_operands_in_place(*frame_ptr,
types::interface_string_insert_str);
}
// -----------------------------------------------------------------------------
void
instr_handler_strist2(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_three_operands_in_place(*frame_ptr,
types::interface_string_insert_char);
}
// -----------------------------------------------------------------------------
void
instr_handler_strers(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands_in_place(*frame_ptr,
types::interface_string_erase);
}
// -----------------------------------------------------------------------------
void
instr_handler_strers2(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_three_operands_in_place(*frame_ptr,
types::interface_string_erase2);
}
// -----------------------------------------------------------------------------
void
instr_handler_strrplc(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_four_operands_in_place(*frame_ptr,
types::interface_string_replace_str);
}
// -----------------------------------------------------------------------------
void
instr_handler_strswp(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands_in_place(*frame_ptr,
types::interface_string_swap);
}
// -----------------------------------------------------------------------------
void
instr_handler_strsub(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_string_substr);
}
// -----------------------------------------------------------------------------
void
instr_handler_strsub2(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_three_operands(*frame_ptr,
types::interface_string_substr2);
}
// -----------------------------------------------------------------------------
void
instr_handler_strfnd(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_string_find);
}
// -----------------------------------------------------------------------------
void
instr_handler_strfnd2(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_three_operands(*frame_ptr,
types::interface_string_find2);
}
// -----------------------------------------------------------------------------
void
instr_handler_strrfnd(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_string_rfind);
}
// -----------------------------------------------------------------------------
void
instr_handler_strrfnd2(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_three_operands(*frame_ptr,
types::interface_string_rfind2);
}
// -----------------------------------------------------------------------------
void
instr_handler_arylen(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_array_size);
}
// -----------------------------------------------------------------------------
void
instr_handler_aryemp(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_array_empty);
}
// -----------------------------------------------------------------------------
void
instr_handler_aryat(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_array_at);
}
// -----------------------------------------------------------------------------
void
instr_handler_aryfrt(
const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_array_front);
}
// -----------------------------------------------------------------------------
void
instr_handler_arybak(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_array_back);
}
// -----------------------------------------------------------------------------
void
instr_handler_aryput(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_three_operands_in_place(*frame_ptr,
types::interface_array_put);
}
// -----------------------------------------------------------------------------
void
instr_handler_aryapnd(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands_in_place(*frame_ptr,
types::interface_array_append);
}
// -----------------------------------------------------------------------------
void
instr_handler_aryers(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands_in_place(*frame_ptr,
types::interface_array_erase);
}
// -----------------------------------------------------------------------------
void
instr_handler_arypop(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_array_pop);
}
// -----------------------------------------------------------------------------
void
instr_handler_aryswp(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands_in_place(*frame_ptr,
types::interface_array_swap);
}
// -----------------------------------------------------------------------------
void
instr_handler_aryclr(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand_in_place(*frame_ptr,
types::interface_array_clear);
}
// -----------------------------------------------------------------------------
void
instr_handler_arymrg(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_array_merge);
}
// -----------------------------------------------------------------------------
void
instr_handler_maplen(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_map_size);
}
// -----------------------------------------------------------------------------
void
instr_handler_mapemp(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_map_empty);
}
// -----------------------------------------------------------------------------
void
instr_handler_mapat(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_map_at);
}
// -----------------------------------------------------------------------------
void
instr_handler_mapfind(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_map_find);
}
// -----------------------------------------------------------------------------
void
instr_handler_mapput(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_three_operands_in_place(*frame_ptr,
types::interface_map_put);
}
// -----------------------------------------------------------------------------
void
instr_handler_mapset(const Instr& instr, Process& process,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
types::native_map_key_type key = static_cast<
types::native_map_key_type>(instr.oprd1);
auto ptr = process.top_stack();
Frame* frame = *frame_ptr;
types::NativeTypeValue& res = frame->top_eval_stack();
types::native_map map = types::get_intrinsic_value_from_type_value<types::native_map>(res);
map[key] = ptr->id();
res = map;
}
// -----------------------------------------------------------------------------
void
instr_handler_mapers(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands_in_place(*frame_ptr,
types::interface_map_erase);
}
// -----------------------------------------------------------------------------
void
instr_handler_mapclr(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand_in_place(*frame_ptr,
types::interface_map_clear);
}
// -----------------------------------------------------------------------------
void
instr_handler_mapswp(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands_in_place(*frame_ptr,
types::interface_map_swap);
}
// -----------------------------------------------------------------------------
void
instr_handler_mapkeys(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_map_keys);
}
// -----------------------------------------------------------------------------
void
instr_handler_mapvals(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_single_operand(*frame_ptr,
types::interface_map_vals);
}
// -----------------------------------------------------------------------------
void
instr_handler_mapmrg(const Instr& /* instr */, Process& /* process */,
Frame** frame_ptr, InvocationCtx** /* invk_ctx_ptr */)
{
execute_native_type_complex_instr_with_two_operands(*frame_ptr,
types::interface_map_merge);
}
// -----------------------------------------------------------------------------
} /* end namespace runtime */
} /* end namespace corevm */
| 29.879946 | 97 | 0.576651 | [
"object",
"vector"
] |
9235f8de2dfd3fb25d897c0e964eb0cf20873a62 | 6,733 | hpp | C++ | include/raptor/search/run_program_multiple.hpp | KarolinaD/raptor | 2952646261ae82bdbe55d4e53373d5c3d96f1f8c | [
"BSD-3-Clause"
] | null | null | null | include/raptor/search/run_program_multiple.hpp | KarolinaD/raptor | 2952646261ae82bdbe55d4e53373d5c3d96f1f8c | [
"BSD-3-Clause"
] | null | null | null | include/raptor/search/run_program_multiple.hpp | KarolinaD/raptor | 2952646261ae82bdbe55d4e53373d5c3d96f1f8c | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <seqan3/search/dream_index/interleaved_bloom_filter.hpp>
#include <seqan3/search/views/minimiser_hash.hpp>
#include <raptor/search/compute_simple_model.hpp>
#include <raptor/search/do_parallel.hpp>
#include <raptor/search/load_ibf.hpp>
#include <raptor/search/sync_out.hpp>
namespace raptor
{
template <bool compressed>
void run_program_multiple(search_arguments const & arguments)
{
constexpr seqan3::data_layout ibf_data_layout = compressed ? seqan3::data_layout::compressed :
seqan3::data_layout::uncompressed;
auto ibf = seqan3::interleaved_bloom_filter<ibf_data_layout>{};
seqan3::sequence_file_input<dna4_traits, seqan3::fields<seqan3::field::id, seqan3::field::seq>> fin{arguments.query_file};
using record_type = typename decltype(fin)::record_type;
std::vector<record_type> records{};
double ibf_io_time{0.0};
double reads_io_time{0.0};
double compute_time{0.0};
size_t const kmers_per_window = arguments.window_size - arguments.kmer_size + 1;
size_t const kmers_per_pattern = arguments.pattern_size - arguments.kmer_size + 1;
size_t const min_number_of_minimisers = kmers_per_window == 1 ? kmers_per_pattern :
std::ceil(kmers_per_pattern / static_cast<double>(kmers_per_window));
size_t const kmer_lemma = arguments.pattern_size + 1u > (arguments.errors + 1u) * arguments.kmer_size ?
arguments.pattern_size + 1u - (arguments.errors + 1u) * arguments.kmer_size :
0;
size_t const max_number_of_minimisers = arguments.pattern_size - arguments.window_size + 1;
std::vector<size_t> const precomp_thresholds = compute_simple_model(arguments);
auto cereal_worker = [&] ()
{
load_ibf(ibf, arguments, 0, ibf_io_time);
};
for (auto && chunked_records : fin | seqan3::views::chunk((1ULL<<20)*10))
{
auto cereal_handle = std::async(std::launch::async, cereal_worker);
records.clear();
auto start = std::chrono::high_resolution_clock::now();
std::ranges::move(chunked_records, std::cpp20::back_inserter(records));
auto end = std::chrono::high_resolution_clock::now();
reads_io_time += std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();
std::vector<seqan3::counting_vector<uint16_t>> counts(records.size(),
seqan3::counting_vector<uint16_t>(ibf.bin_count(), 0));
auto count_task = [&](size_t const start, size_t const end)
{
auto counter = ibf.template counting_agent<uint16_t>();
size_t counter_id = start;
auto hash_view = seqan3::views::minimiser_hash(seqan3::ungapped{arguments.kmer_size},
seqan3::window_size{arguments.window_size},
seqan3::seed{adjust_seed(arguments.kmer_size)});
for (auto && [id, seq] : records | seqan3::views::slice(start, end))
{
(void) id;
auto & result = counter.bulk_count(seq | hash_view);
counts[counter_id++] += result;
}
};
cereal_handle.wait();
do_parallel(count_task, records.size(), arguments.threads, compute_time);
for (size_t const part : std::views::iota(1u, static_cast<unsigned int>(arguments.parts - 1)))
{
load_ibf(ibf, arguments, part, ibf_io_time);
do_parallel(count_task, records.size(), arguments.threads, compute_time);
}
load_ibf(ibf, arguments, arguments.parts - 1, ibf_io_time);
sync_out synced_out{arguments.out_file};
auto output_task = [&](size_t const start, size_t const end)
{
auto counter = ibf.template counting_agent<uint16_t>();
size_t counter_id = start;
std::string result_string{};
std::vector<uint64_t> minimiser;
auto hash_view = seqan3::views::minimiser_hash(seqan3::ungapped{arguments.kmer_size},
seqan3::window_size{arguments.window_size},
seqan3::seed{adjust_seed(arguments.kmer_size)});
for (auto && [id, seq] : records | seqan3::views::slice(start, end))
{
minimiser.clear();
result_string.clear();
result_string += id;
result_string += '\t';
minimiser = seq | hash_view | seqan3::views::to<std::vector<uint64_t>>;
counts[counter_id] += counter.bulk_count(minimiser);
size_t const minimiser_count{minimiser.size()};
size_t current_bin{0};
size_t const threshold = arguments.treshold_was_set ?
static_cast<size_t>(minimiser_count * arguments.threshold) :
kmers_per_window == 1 ? kmer_lemma :
precomp_thresholds[std::min(minimiser_count < min_number_of_minimisers ?
0 :
minimiser_count - min_number_of_minimisers,
max_number_of_minimisers -
min_number_of_minimisers)] + 2;
for (auto && count : counts[counter_id++])
{
if (count >= threshold)
{
result_string += std::to_string(current_bin);
result_string += ',';
}
++current_bin;
}
result_string += '\n';
synced_out.write(result_string);
}
};
do_parallel(output_task, records.size(), arguments.threads, compute_time);
}
if (arguments.write_time)
{
std::filesystem::path file_path{arguments.out_file};
file_path += ".time";
std::ofstream file_handle{file_path};
file_handle << "IBF I/O\tReads I/O\tCompute\n";
file_handle << std::fixed
<< std::setprecision(2)
<< ibf_io_time << '\t'
<< reads_io_time << '\t'
<< compute_time;
}
}
} // namespace raptor
| 44.589404 | 126 | 0.54775 | [
"vector"
] |
9239572d6c12e367f663e7687c8cafa436474c6d | 13,443 | cpp | C++ | Source/Motor2D/Application.cpp | BarcinoLechiguino/Project_F | 9e40c771f5ce6b821e3d380edd5d92fb129cdf53 | [
"MIT"
] | 1 | 2020-04-28T16:09:51.000Z | 2020-04-28T16:09:51.000Z | Source/Motor2D/Application.cpp | Aitorlb7/Project_F | 9e40c771f5ce6b821e3d380edd5d92fb129cdf53 | [
"MIT"
] | 3 | 2020-03-03T09:57:49.000Z | 2020-04-25T16:02:36.000Z | Source/Motor2D/Application.cpp | BarcinoLechiguino/Project-RTS | 9e40c771f5ce6b821e3d380edd5d92fb129cdf53 | [
"MIT"
] | 1 | 2020-11-06T22:31:26.000Z | 2020-11-06T22:31:26.000Z | #include <iostream>
#include <list>
#include <vector>
#include "Definitions.h"
#include "Log.h"
#include "Application.h"
#include "Window.h"
#include "Input.h"
#include "Render.h"
#include "Textures.h"
#include "Audio.h"
#include "Map.h"
#include "Fonts.h"
#include "EntityManager.h"
#include "Pathfinding.h"
#include "GuiManager.h"
#include "Player.h"
#include "Player.h"
#include "Minimap.h"
#include "TransitionManager.h"
#include "SceneManager.h"
#include "Movement.h"
#include "EnemyAIManager.h"
#include "FowManager.h"
#include "DialogManager.h"
#include "ParticleManager.h"
#include "QuestManager.h"
#include "ProjectileManager.h"
#include "AssetManager.h"
#include "Dependencies\Brofiler\Brofiler.h"
//#include "mmgr/mmgr.h"
// Constructor
Application::Application(int argc, char* args[]) : argc(argc), args(args)
{
PERF_START(perf_timer);
want_to_save = want_to_load = false;
frame_count = 0;
input = new Input();
win = new Window();
render = new Render();
tex = new Textures();
audio = new Audio();
map = new Map();
pathfinding = new PathFinding();
entity_manager = new EntityManager();
minimap = new Minimap();
font = new Fonts();
gui_manager = new GuiManager();
player = new Player();
transition_manager = new TransitionManager();
scene_manager = new SceneManager();
movement = new Movement();
enemy_AI_manager = new EnemyAIManager();
fow_manager = new FowManager();
dialog_manager = new DialogManager();
particle_manager = new ParticleManager();
quest_manager = new QuestManager();
projectile_manager = new ProjectileManager();
asset_manager = new AssetManager();
// Ordered for awake / Start / Update
// Reverse order of CleanUp
AddModule(input);
AddModule(win);
AddModule(tex);
AddModule(audio);
AddModule(map);
AddModule(pathfinding);
AddModule(font);
AddModule(movement);
AddModule(asset_manager);
// scene_manager last before render.
AddModule(particle_manager);
AddModule(minimap);
AddModule(gui_manager);
AddModule(scene_manager);
AddModule(transition_manager);
AddModule(entity_manager);
AddModule(projectile_manager);
AddModule(enemy_AI_manager);
AddModule(fow_manager);
AddModule(dialog_manager);
AddModule(player);
AddModule(quest_manager);
// render last to swap buffer
AddModule(render);
pause = false;
PERF_PEEK(perf_timer);
}
// Destructor
Application::~Application()
{
std::vector<Module*>::iterator item = modules.begin();
// release modules
for (; item != modules.end() ; ++item)
{
RELEASE((*item));
}
modules.clear();
}
void Application::AddModule(Module* module)
{
module->Init();
modules.push_back(module);
}
// Called before render is available
bool Application::Awake()
{
PERF_START(perf_timer);
pugi::xml_document config_file;
pugi::xml_node config;
pugi::xml_node app_config;
bool ret = false;
config = LoadConfig(config_file);
frame_cap = CAP_AT_60;
if(!config.empty())
{
// self-config
ret = true;
app_config = config.child("app");
title = (app_config.child("title").child_value()); //Calling constructor
organization = (app_config.child("organization").child_value());
frame_cap = config.child("app").attribute("framerate_cap").as_uint();
frames_are_capped = config.child("app").attribute("frame_cap_on").as_bool();
original_frame_cap = frame_cap;
}
int i = 0;
if(ret)
{
std::vector<Module*>::iterator item = modules.begin();
for (; item != modules.end() && ret; ++item)
{
i++;
ret = (*item)->Awake(config.child((*item)->name.c_str()));
if (!ret)
{
LOG("AWAKE RET IS FALSE %d", i);
}
}
}
LoadXMLFiles();
PERF_PEEK(perf_timer);
return ret;
}
// Called before the first frame
bool Application::Start()
{
PERF_START(perf_timer);
bool ret = true;
int i = 0;
std::vector<Module*>::iterator item = modules.begin();
for (; item != modules.end() && ret ; ++item)
{
if ((*item)->is_active)
{
i++;
ret = (*item)->Start();
if (!ret)
{
LOG("START RET IS FALSE %d", i);
}
}
}
startup_timer.Start();
PERF_PEEK(perf_timer);
return ret;
}
// Called each loop iteration
bool Application::Update()
{
BROFILER_CATEGORY("Update_App.cpp", Profiler::Color::Aqua)
bool ret = true;
PrepareUpdate();
if(input->GetWindowEvent(WE_QUIT))
ret = false;
if(ret == true)
ret = PreUpdate();
if(ret == true)
ret = DoUpdate();
if(ret == true)
ret = PostUpdate();
FinishUpdate();
return ret;
}
// ---------------------------------------------
pugi::xml_node Application::LoadConfig(pugi::xml_document& config_file) const
{
pugi::xml_node ret;
pugi::xml_parse_result result = config_file.load_file("config.xml");
if(result == NULL)
LOG("Could not load map xml file config.xml. pugi error: %s", result.description());
else
ret = config_file.child("config");
return ret;
}
pugi::xml_node Application::LoadParticleSystemConfig(pugi::xml_document& ps_file) const
{
pugi::xml_node ret;
pugi::xml_parse_result result = ps_file.load_file("ps_config");
if (result == NULL)
LOG("Could not load xml file ps_config.xml. pugi error: %s", result.description());
else
ret = ps_file.child("particlesystem");
return ret;
}
void Application::LoadXMLFiles()
{
pugi::xml_parse_result result;
// --- config.xml ---
result = config_file.load_file("config.xml");
if (result == NULL)
{
LOG("Could not load map xml file config.xml. pugi error: %s", result.description());
}
// --- animations.xml ---
result = animations_file.load_file("animations.xml");
if (result == NULL)
{
LOG("Could not load map xml file animations.xml. pugi error: %s", result.description());
}
// --- ps_config.xml ---
result = particle_system_file.load_file("ps_config");
if (result == NULL)
{
LOG("Could not load map xml file ps_config.xml. pugi error: %s", result.description());
}
// --- dialog.xml ---
result = dialog_system_file.load_file("dialog.xml");
if (result == NULL)
{
LOG("Could not load map xml file dialog.xml. pugi error: %s", result.description());
}
// --- quest_data.xml ---
result = quest_manager_file.load_file("quest_data.xml");
if (result == NULL)
{
LOG("Could not load map xml file quest_data.xml. pugi error: %s", result.description());
}
// --- entities.xml ---
result = entities_file.load_file("entities.xml");
if (result == NULL)
{
LOG("Could not load map xml file entities.xml. pugi error: %s", result.description());
}
}
// ---------------------------------------------
void Application::PrepareUpdate()
{
frame_count++;
frames_last_second++;
dt = frame_timer.ReadSec(); //Keeps track of the amount of time that has passed since last frame in seconds (processing time of a frame: Frame 1: 0.033secs, ...).
frame_timer.Start();
//LOG("The differential time since last frame: %f", dt);
}
// ---------------------------------------------
void Application::FinishUpdate()
{
if (want_to_save)
{
SavegameNow();
}
if (want_to_load)
{
LoadGameNow();
}
//------------ Framerate Calculations ------------
if (last_second_timer.ReadMs() > 1000)
{
last_second_timer.Start();
prev_sec_frames = frames_last_second;
frames_last_second = 0;
}
uint frame_cap_ms = 1000 / frame_cap;
uint current_frame_ms = frame_timer.Read();
if (frames_are_capped)
{
if (current_frame_ms < frame_cap_ms) //If the current frame processing time is lower than the specified frame_cap. Timer instead of PerfTimer was used because SDL_Delay is inaccurate.
{
true_delay_timer.Start();
SDL_Delay(frame_cap_ms - current_frame_ms); //SDL_Delay delays processing for a specified time. In this case, it delays for the difference in ms between the frame cap (30fps so 33,3ms per frame) and the current frame.
uint intended_delay = frame_cap_ms - current_frame_ms;
//LOG("We waited for %d milliseconds and got back in %f", intended_delay, true_delay_timer.ReadMs());
}
}
float avg_fps = frame_count / startup_timer.ReadSec();
seconds_since_startup = startup_timer.ReadSec();
uint32 last_frame_ms = frame_timer.Read();
uint32 frames_on_last_update = prev_sec_frames; //Keeps track of how many frames were processed the last second.
if (frames_are_capped)
{
frame_cap_on_off = "On";
}
else
{
frame_cap_on_off = "Off";
}
if (vsync_is_active)
{
vsync_on_off = "On";
}
else
{
vsync_on_off = "Off";
}
static char title[256];
sprintf_s(title, 256, "Av.FPS: %.2f / Last Frame Ms: %02u / Last sec frames: %i / Last dt: %.3f / Time since startup: %.3f / Frame Count: %llu / Vsync: %s / Frame cap: %s",
avg_fps, last_frame_ms, frames_on_last_update, dt, seconds_since_startup, frame_count, vsync_on_off, frame_cap_on_off);
App->win->SetTitle(title);
}
// Call modules before each loop iteration
bool Application::PreUpdate()
{
BROFILER_CATEGORY("PreUpdate_App.cpp", Profiler::Color::Aqua)
bool ret = true;
std::vector<Module*>::iterator item = modules.begin();
for (; item != modules.end() && ret ; ++item)
{
if(!(*item)->is_active)
{
continue;
}
ret = (*item)->PreUpdate();
}
return ret;
}
// Call modules on each loop iteration
bool Application::DoUpdate()
{
bool ret = true;
int i = 0;
std::vector<Module*>::iterator item = modules.begin();
for (; item != modules.end() && ret; ++item)
{
i++;
if(!(*item)->is_active)
{
continue;
}
if (!pause)
{
ret = (*item)->Update(dt); //Passes the calculated dt as an argument to all modules. This will make every update run in the same timestep.
}
else
{
ret = (*item)->Update(0.0f);
}
}
return ret;
}
// Call modules after each loop iteration
bool Application::PostUpdate()
{
BROFILER_CATEGORY("PostUpdate_App.cpp", Profiler::Color::Aqua)
bool ret = true;
std::vector<Module*>::iterator item = modules.begin();
for (; item != modules.end() && ret; ++item)
{
if(!(*item)->is_active)
{
continue;
}
ret = (*item)->PostUpdate();
}
return ret;
}
// Called before quitting
bool Application::CleanUp()
{
bool ret = true;
std::vector<Module*>::iterator item = modules.begin();
for (; item != modules.end() && ret; ++item)
{
if ((*item)->name.empty())
{
LOG("STARTING THE CLEANUP");
ret = (*item)->CleanUp();
LOG("FINISHING THE CLEANUP");
}
}
return ret;
}
// ---------------------------------------
int Application::GetArgc() const
{
return argc;
}
// ---------------------------------------
const char* Application::GetArgv(int index) const
{
if(index < argc)
return args[index];
else
return NULL;
}
// ---------------------------------------
const char* Application::GetTitle() const
{
return title.c_str();
}
// ---------------------------------------
const char* Application::GetOrganization() const
{
return organization.c_str();
}
float Application::GetDt() const
{
if (!pause)
{
return dt;
}
else
{
return 0.0f;
}
}
float Application::GetUnpausableDt() const
{
return dt;
}
// Load / Save
void Application::LoadGame(const char* file)
{
// we should be checking if that file actually exist
// from the "GetSaveGames" list
want_to_load = true;
}
// ---------------------------------------
void Application::SaveGame(const char* file) const
{
// we should be checking if that file actually exist
// from the "GetSaveGames" list ... should we overwrite ?
want_to_save = true;
save_game = (file);
}
// ---------------------------------------
void GetSaveGames(std::list<std::string>& list_to_fill)
{
// need to add functionality to file_system module for this to work
}
bool Application::LoadGameNow()
{
bool ret = false;
load_game = ("save_game.xml");
pugi::xml_document data;
pugi::xml_node root;
pugi::xml_parse_result result = data.load_file(load_game.c_str());
if (result != NULL)
{
LOG("Loading new Game State from %s...", load_game.c_str());
root = data.child("game_state");
ret = true;
std::vector<Module*>::iterator item = modules.begin();
for (; item != modules.end() && ret; ++item)
{
ret = (*item)->Load(root.child((*item)->name.c_str()));
}
data.reset();
if (ret == true)
{
LOG("...finished loading");
}
else
{
if ((*item) != nullptr)
{
LOG("...loading process interrupted with error on module %s", (*item)->name.c_str());
}
else
{
LOG("...loading process interrupted with error on module %s", "unknown");
}
}
}
else
{
LOG("Could not parse game state xml file %s. pugi error: %s", load_game.c_str(), result.description());
}
want_to_load = false;
return ret;
}
bool Application::SavegameNow() //Chenged to non const due to list unknown problem
{
bool ret = true;
save_game = ("save_game.xml");
LOG("Saving Game State to %s...", save_game.c_str());
// xml object were we will store all data
pugi::xml_document data;
pugi::xml_node root;
root = data.append_child("game_state");
std::vector<Module*>::iterator item = modules.begin();
for (; item != modules.end() && ret; ++item)
{
ret = (*item)->Save(root.append_child((*item)->name.c_str()));
}
if (ret == true)
{
data.save_file(save_game.c_str());
LOG("... finished saving", );
}
else
{
if ((*item) != nullptr)
{
LOG("Save process halted from an error in module %s", (*item)->name.c_str());
}
else
{
LOG("Save process halted from an error in module %s", "unknown");
}
}
data.reset();
want_to_save = false;
return ret;
} | 20.874224 | 223 | 0.648442 | [
"render",
"object",
"vector"
] |
9239b4b187e3f96601e6e56965726724052cec24 | 8,417 | cc | C++ | src/ivectorbin/ivector-extract-check-condition-final.cc | Shuang777/kaldi | 3df67141b55cfd5e2ba7305a72e795e7706d8d30 | [
"Apache-2.0"
] | 1 | 2019-02-06T09:31:59.000Z | 2019-02-06T09:31:59.000Z | src/ivectorbin/ivector-extract-check-condition-final.cc | Shuang777/kaldi | 3df67141b55cfd5e2ba7305a72e795e7706d8d30 | [
"Apache-2.0"
] | null | null | null | src/ivectorbin/ivector-extract-check-condition-final.cc | Shuang777/kaldi | 3df67141b55cfd5e2ba7305a72e795e7706d8d30 | [
"Apache-2.0"
] | null | null | null | // ivectorbin/ivector-extract.cc
// Copyright 2013 Daniel Povey
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "gmm/am-diag-gmm.h"
#include "ivector/ivector-extractor.h"
#include "thread/kaldi-task-sequence.h"
#include <utility>
#include <vector>
#include "gmm/model-common.h"
#include "matrix/matrix-lib.h"
#include "util/common-utils.h"
#include "gmm/full-gmm.h"
#include "gmm/am-diag-gmm.h"
namespace kaldi {
class TestClass:public IvectorExtractor {
public:
TestClass(string name) {
name_ = name;
}
Matrix<double> getMInfor() {
Matrix<double> T(NumGauss() * FeatDim(), IvectorDim());
int index = 0;
for(int i = 0; i < M_.size();i++)
{
//Matrix<double> mi = M_[i];
for(int j = 0; j < M_[i].NumRows(); j++)
{
T.Row(index).CopyFromVec(M_[i].Row(j));
index++;
}
}
cout << "Finish extracting T matrix " << endl;
return T;
}
private:
string name_;
};
Vector<double> getStats(const MatrixBase<kaldi::BaseFloat> &feats, const Posterior &post)
{
typedef std::vector<std::pair<int32, BaseFloat> > VecType;
int32 num_frames = feats.NumRows(),
num_gauss = 2048;
//feat_dim = feats.NumCols();
cout << "Num-of-frame = " << num_frames << endl;
Vector<double> gamma_(num_gauss);
//KALDI_ASSERT(X_.NumCols() == feat_dim);
KALDI_ASSERT(feats.NumRows() == static_cast<int32>(post.size()));
for (int32 t = 0; t < num_frames; t++) {
SubVector<BaseFloat> frame(feats, t);
const VecType &this_post(post[t]);
for (VecType::const_iterator iter = this_post.begin();
iter != this_post.end(); ++iter) {
int32 i = iter->first; // Gaussian index.
KALDI_ASSERT(i >= 0 && i < num_gauss &&
"Out-of-range Gaussian (mismatched posteriors?)");
double weight = iter->second;
gamma_(i) += weight;
}
}
return gamma_;
}
void getW(Matrix<double> &T, Vector<double> &zero_order, std::vector<SpMatrix<BaseFloat> > &inver_cova, kaldi::int32 numGauss, kaldi::int32 featSize)
{
KALDI_ASSERT(numGauss == static_cast<int32>(inver_cova.size()));
KALDI_ASSERT(numGauss == static_cast<int32>(zero_order.Dim()));
cout << "Pass condition here " << endl;
kaldi::int32 cf = featSize * numGauss;
T.Transpose();
kaldi::int32 r = T.NumRows();
cout << "Transpose T, number of rows = " << T.NumRows() << ", num of column = " << T.NumCols() << endl;
Matrix<double> TW(r, cf, kaldi::kSetZero);
cout << "Initialization finished. " << endl;
for(int i = 0; i < r; i++)
{
SubVector<double> rowI = T.Row(i);
for(int j = 0; j < cf ;j++)
{
int indexGauss = j/featSize;
int residual = j % featSize;
int startConsider = indexGauss * featSize;
int endConsider = startConsider + featSize - 1;
SpMatrix<BaseFloat> &inv_sigmaC = inver_cova[indexGauss];
double weightC = zero_order(indexGauss);
for(int k = startConsider ; k <= endConsider;k++)
{
TW(i,j) += rowI(k) * weightC * inv_sigmaC(k- startConsider, residual);
}
}
}
//cout << "Finish V^T * W" << endl;
T.Transpose();
Matrix<double> TWT(r, r, kaldi::kSetZero);
TWT.AddMatMat(1.0, TW, kaldi::kNoTrans, T, kaldi::kNoTrans, 1.0);
SpMatrix<double> temp(TWT.NumRows(), kaldi::kSetZero);
for(int i = 0; i < TWT.NumRows();i++)
for(int j = 0; j < TWT.NumRows();j++)
temp(i,j) = TWT(i,j);
//cout << "Finish V^T * W * V, now estimating condition number " << endl;
Vector<double> s(temp.NumRows());
Matrix<double> p(temp.NumRows(), temp.NumRows());
temp.Eig(&s, &p);
double min_abs = std::abs(s(0)), max_abs = std::abs(s(0)), min = s(0); // both absolute values...
for (MatrixIndexT i = 1;i < s.Dim();i++) {
min_abs = std::min((double)std::abs(s(i)), min_abs);
max_abs = std::max((double)std::abs(s(i)), max_abs);
min = std::min(s(i), min);
}
if (min_abs > 0)
cout << "Max_abs = " << max_abs << " Min_abs = " << min_abs << ", cond num = " << max_abs/min_abs << endl;
else
cout << "Max_abs = " << max_abs << " Min_abs = " << min_abs << ", bad condition number = 1.0e+100 " << endl;
}
}
int main(int argc, char *argv[]) {
using namespace kaldi;
typedef kaldi::int32 int32;
typedef kaldi::int64 int64;
try {
const char *usage =
"Extract iVectors for utterances, using a trained iVector extractor,\n"
"and features and Gaussian-level posteriors\n"
"Usage: ivector-extract [options] <model-in> <feature-rspecifier>"
"<posteriors-rspecifier> <ivector-wspecifier>\n"
"e.g.: \n"
" fgmm-global-gselect-to-post 1.fgmm '$feats' 'ark:gunzip -c gselect.1.gz|' ark:- | \\\n"
" ivector-extract final.ie '$feats' ark,s,cs:- ark,t:ivectors.1.ark\n";
ParseOptions po(usage);
IvectorExtractorStatsOptions stats_opts;
stats_opts.Register(&po);
po.Read(argc, argv);
if (po.NumArgs() != 4) {
po.PrintUsage();
exit(1);
}
std::string ivector_extractor_rxfilename = po.GetArg(1),
fgmm_rxfilename = po.GetArg(2),
feature_rspecifier = po.GetArg(3),
posteriors_rspecifier = po.GetArg(4);
IvectorExtractor extractor;
TestClass test(ivector_extractor_rxfilename);
//ReadKaldiObject(ivector_extractor_rxfilename, &extractor);
ReadKaldiObject(ivector_extractor_rxfilename, &test);
Matrix<double> T = test.getMInfor();
FullGmm fgmm;
ReadKaldiObject(fgmm_rxfilename, &fgmm);
// Initialize these Reader objects before reading the IvectorExtractor,
// because it uses up a lot of memory and any fork() after that will
// be in danger of causing an allocation failure.
SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier);
RandomAccessPosteriorReader posteriors_reader(posteriors_rspecifier);
std::vector<SpMatrix<BaseFloat> > inver_cova = fgmm.inv_covars();
//KALDI_LOG << "The SI model:"
// << "Number of Gaussian = " << fgmm.NumGauss() << endl;
//KALDI_LOG << "Size of the vector inver_covariance = " << inver_cova.size() << endl;
int dim_size = 0;
for(int i = 0; i < inver_cova.size();i++)
{
SpMatrix<BaseFloat> &aComponent = inver_cova[i];
dim_size = aComponent.NumRows();
}
//KALDI_LOG << "Feat size= " << dim_size << endl;
kaldi::int32 num_done = 0, num_err = 0;
{
for (; !feature_reader.Done(); feature_reader.Next()) {
std::string key = feature_reader.Key();
if (!posteriors_reader.HasKey(key)) {
KALDI_WARN << "No posteriors for utterance " << key;
num_err++;
continue;
}
const Matrix<BaseFloat> &mat = feature_reader.Value();
const Posterior &posterior = posteriors_reader.Value(key);
Vector<double> zero_order = getStats(mat, posterior) ;
//KALDI_LOG << "Size of zero-order = " << zero_order.Dim() << endl;
//for(int i = 0; i < 10;i++)
// cout << zero_order(i) << " ";
cout << endl;
getW(T, zero_order, inver_cova, fgmm.NumGauss(), dim_size);
if (static_cast<int32>(posterior.size()) != mat.NumRows()) {
KALDI_WARN << "Size mismatch between posterior " << (posterior.size())
<< " and features " << (mat.NumRows()) << " for utterance "
<< key;
num_err++;
continue;
}
num_done++;
}
// destructor of "sequencer" will wait for any remaining tasks that
// have not yet completed.
}
return 0;
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 34.495902 | 150 | 0.61554 | [
"vector",
"model"
] |
923db284b050b116906ab1df98089c704ba3b4bb | 2,978 | cpp | C++ | source/sw/src/interp.cpp | bisk89/Raze | 1a2663f7ac84d4e4f472e0796b937447ee6fab6b | [
"RSA-MD"
] | 2 | 2020-03-26T10:11:17.000Z | 2021-01-19T08:16:48.000Z | source/sw/src/interp.cpp | bisk89/Raze | 1a2663f7ac84d4e4f472e0796b937447ee6fab6b | [
"RSA-MD"
] | null | null | null | source/sw/src/interp.cpp | bisk89/Raze | 1a2663f7ac84d4e4f472e0796b937447ee6fab6b | [
"RSA-MD"
] | null | null | null | //-------------------------------------------------------------------------
/*
Copyright (C) 1997, 2005 - 3D Realms Entertainment
This file is part of Shadow Warrior version 1.2
Shadow Warrior is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Original Source: 1997 - Frank Maddin and Jim Norwood
Prepared for public release: 03/28/2005 - Charlie Wiederhold, 3D Realms
*/
//-------------------------------------------------------------------------
#include "ns.h"
#include "compat.h"
#include "pragmas.h"
#include "interp.h"
BEGIN_SW_NS
#define MAXINTERPOLATIONS 1024
int numinterpolations = 0, startofdynamicinterpolations = 0;
int oldipos[MAXINTERPOLATIONS];
int bakipos[MAXINTERPOLATIONS];
int *curipos[MAXINTERPOLATIONS];
void setinterpolation(int *posptr)
{
int i;
if (numinterpolations >= MAXINTERPOLATIONS)
return;
for (i = numinterpolations - 1; i >= 0; i--)
{
if (curipos[i] == posptr)
return;
}
curipos[numinterpolations] = posptr;
oldipos[numinterpolations] = *posptr;
numinterpolations++;
}
void stopinterpolation(int *posptr)
{
int i;
for (i = numinterpolations - 1; i >= startofdynamicinterpolations; i--)
{
if (curipos[i] == posptr)
{
numinterpolations--;
oldipos[i] = oldipos[numinterpolations];
bakipos[i] = bakipos[numinterpolations];
curipos[i] = curipos[numinterpolations];
}
}
}
void updateinterpolations(void) // Stick at beginning of domovethings
{
int i;
for (i = numinterpolations - 1; i >= 0; i--)
oldipos[i] = *curipos[i];
}
// must call restore for every do interpolations
// make sure you don't exit
void dointerpolations(int smoothratio) // Stick at beginning of drawscreen
{
int i, j, odelta, ndelta;
ndelta = 0;
j = 0;
for (i = numinterpolations - 1; i >= 0; i--)
{
bakipos[i] = *curipos[i];
odelta = ndelta;
ndelta = (*curipos[i]) - oldipos[i];
if (odelta != ndelta)
j = mulscale16(ndelta, smoothratio);
*curipos[i] = oldipos[i] + j;
}
}
void restoreinterpolations(void) // Stick at end of drawscreen
{
int i;
for (i = numinterpolations - 1; i >= 0; i--)
*curipos[i] = bakipos[i];
}
END_SW_NS
| 25.895652 | 95 | 0.619543 | [
"3d"
] |
923e63f85b42fda1dd5b0f45d679fe2c90e0625b | 6,482 | cpp | C++ | trace-generators/traces/implementation/ParallelismTraceAnalyzer.cpp | florianjacob/gpuocelot | fa63920ee7c5f9a86e264cd8acd4264657cbd190 | [
"BSD-3-Clause"
] | 221 | 2015-03-29T02:05:49.000Z | 2022-03-25T01:45:36.000Z | trace-generators/traces/implementation/ParallelismTraceAnalyzer.cpp | mprevot/gpuocelot | d9277ef05a110e941aef77031382d0260ff115ef | [
"BSD-3-Clause"
] | 106 | 2015-03-29T01:28:42.000Z | 2022-02-15T19:38:23.000Z | trace-generators/traces/implementation/ParallelismTraceAnalyzer.cpp | mprevot/gpuocelot | d9277ef05a110e941aef77031382d0260ff115ef | [
"BSD-3-Clause"
] | 83 | 2015-07-10T23:09:57.000Z | 2022-03-25T03:01:00.000Z | /*!
\file ParallelismTraceAnalyzer.cpp
\author Gregory Diamos
\date Monday April 13, 2009
\brief The source file for the ParallelismTraceAnalayzer class
*/
#ifndef PARALLELISM_TRACE_ANALYZER_CPP_INCLUDED
#define PARALLELISM_TRACE_ANALYZER_CPP_INCLUDED
#include <traces/interface/ParallelismTraceAnalyzer.h>
#include <hydrazine/interface/ArgumentParser.h>
#include <hydrazine/interface/Exception.h>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>
#include <fstream>
#include <cfloat>
#include <set>
#include <vector>
namespace trace
{
ParallelismTraceAnalyzer::ParallelismTraceAnalyzer(
const std::string& database )
{
std::ifstream stream(database.c_str());
if( !stream.is_open() )
{
throw hydrazine::Exception("Could not open database file "
+ database);
}
unsigned int count;
boost::archive::text_iarchive archive(stream);
archive >> count;
for( unsigned int i = 0; i < count; ++i )
{
KernelEntry entry;
archive >> entry;
if( entry.format == TraceGenerator::ParallelismTraceFormat )
{
KernelMap::iterator kernel = _kernels.find( entry.program );
if( kernel == _kernels.end() )
{
kernel = _kernels.insert( std::make_pair(
entry.program, KernelVector() ) ).first;
}
kernel->second.push_back( entry );
}
}
}
void ParallelismTraceAnalyzer::list() const
{
std::cout << "There are " << _kernels.size()
<< " programs referenced in the database\n";
for( KernelMap::const_iterator vector = _kernels.begin();
vector != _kernels.end(); ++vector )
{
std::cout << " Program \"" << vector->first << "\" contains "
<< vector->second.size() << " kernels.\n";
for( KernelVector::const_iterator kernel = vector->second.begin();
kernel != vector->second.end(); ++kernel )
{
std::cout << " " << kernel->path << "\n";
}
}
std::cout << "\n";
}
void ParallelismTraceAnalyzer::parallelism() const
{
typedef std::vector< ParallelismTraceGenerator::Event > EventVector;
typedef std::set< long long unsigned int > InstructionSet;
double averageSIMD = 0;
double averageMIMD = 0;
double averageCTAs = 0;
for( KernelMap::const_iterator vector = _kernels.begin();
vector != _kernels.end(); ++vector )
{
std::cout << " From program \"" << vector->first << "\".\n";
double localSIMD = 0;
double localMIMD = 0;
double localCTAs = 0;
for( KernelVector::const_iterator kernel = vector->second.begin();
kernel != vector->second.end(); ++kernel )
{
std::ifstream hstream( kernel->header.c_str() );
boost::archive::text_iarchive harchive( hstream );
ParallelismTraceGenerator::Header header;
harchive >> header;
assert( header.format
== TraceGenerator::ParallelismTraceFormat );
hstream.close();
std::ifstream stream( kernel->path.c_str() );
if( !stream.is_open() )
{
throw hydrazine::Exception(
"Failed to open ParallelismTrace kernel trace file "
+ kernel->path );
}
boost::archive::text_iarchive archive( stream );
EventVector events( header.dimensions );
for( EventVector::iterator event = events.begin();
event != events.end(); ++event )
{
archive >> *event;
}
std::cout << " From file " << kernel->path << "\n";
std::cout << " kernel: " << kernel->name << "\n";
std::cout << " module: " << kernel->module << "\n";
std::cout << " statistics:\n";
std::cout << " ctas: " << header.dimensions << "\n";
std::cout << " threads: " << header.threads << "\n";
InstructionSet instructions;
long long unsigned int totalInstructions = 0;
double activity = 0;
for( EventVector::iterator event = events.begin();
event != events.end(); ++event )
{
totalInstructions += event->instructions;
instructions.insert( event->instructions );
activity += event->activity * event->instructions;
}
activity /= totalInstructions + DBL_EPSILON;
unsigned int previous = 0;
unsigned int count = header.dimensions;
double mimd = 0;
for( InstructionSet::iterator
instruction = instructions.begin();
instruction != instructions.end(); ++instruction )
{
mimd += (*instruction - previous) * count;
previous = *instruction;
--count;
}
if( !instructions.empty() )
{
mimd /= *(--instructions.end()) + DBL_EPSILON;
}
std::cout << " SIMD parallelism: " << activity
<< "\n";
std::cout << " MIMD parallelism: " << mimd << "\n";
localSIMD += activity;
localMIMD += mimd;
localCTAs += header.dimensions;
}
localSIMD /= vector->second.size() + DBL_EPSILON;
localMIMD /= vector->second.size() + DBL_EPSILON;
localCTAs /= vector->second.size() + DBL_EPSILON;
std::cout << " Kernel " << vector->first << " statistics:\n";
std::cout << " average CTAs: " << localCTAs << "\n";
std::cout << " average SIMD parallelism: " << localSIMD << "\n";
std::cout << " average MIMD parallelism: " << localMIMD << "\n";
averageSIMD += localSIMD;
averageMIMD += localMIMD;
averageCTAs += localCTAs;
}
averageSIMD /= _kernels.size() + DBL_EPSILON;
averageMIMD /= _kernels.size() + DBL_EPSILON;
averageCTAs /= _kernels.size() + DBL_EPSILON;
std::cout << "Aggregate statistics:\n";
std::cout << " average CTAs: " << averageCTAs << "\n";
std::cout << " average SIMD parallelism: " << averageSIMD << "\n";
std::cout << " average MIMD parallelism: " << averageMIMD << "\n";
}
}
int main( int argc, char** argv )
{
hydrazine::ArgumentParser parser( argc, argv );
parser.description("Provides the ability to inspect a database created by"
+ std::string( "a BranchTraceGenerator" ) );
bool help;
bool list;
bool parallelism;
std::string database;
parser.parse( "-h", help, false, "Print this help message." );
parser.parse( "-l", list, false, "List all traces in the database." );
parser.parse( "-p", parallelism, false,
"Compute parallelism for each trace." );
parser.parse( "-i", database, "traces/database.trace",
"Path to database file." );
if( help )
{
std::cout << parser.help();
return 0;
}
trace::ParallelismTraceAnalyzer analyzer( database );
if( list )
{
analyzer.list();
}
if( parallelism )
{
analyzer.parallelism();
}
return 0;
}
#endif
| 25.519685 | 76 | 0.624807 | [
"vector"
] |
9242ba18b1048b900ff7397a1c0264b7b17f0336 | 3,929 | cc | C++ | src/core/execution_context/copy_execution_context.cc | willhemsley/biodynamo | c36830de621f8e105bf5eac913b96405b5c9d75c | [
"Apache-2.0"
] | null | null | null | src/core/execution_context/copy_execution_context.cc | willhemsley/biodynamo | c36830de621f8e105bf5eac913b96405b5c9d75c | [
"Apache-2.0"
] | null | null | null | src/core/execution_context/copy_execution_context.cc | willhemsley/biodynamo | c36830de621f8e105bf5eac913b96405b5c9d75c | [
"Apache-2.0"
] | null | null | null | // -----------------------------------------------------------------------------
//
// Copyright (C) 2021 CERN & Newcastle University for the benefit of the
// BioDynaMo collaboration. 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.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#include "core/execution_context/copy_execution_context.h"
#include "core/agent/agent.h"
#include "core/resource_manager.h"
#include "core/simulation.h"
namespace bdm {
namespace experimental {
// -----------------------------------------------------------------------------
void CopyExecutionContext::Use(Simulation* sim) {
auto size = sim->GetAllExecCtxts().size();
auto map = std::make_shared<
typename InPlaceExecutionContext::ThreadSafeAgentUidMap>();
std::vector<ExecutionContext*> exec_ctxts(size);
auto agents = std::make_shared<std::vector<std::vector<Agent*>>>();
#pragma omp parallel for schedule(static, 1)
for (uint64_t i = 0; i < size; i++) {
exec_ctxts[i] = new CopyExecutionContext(map, agents);
}
sim->SetAllExecCtxts(exec_ctxts);
}
// -----------------------------------------------------------------------------
CopyExecutionContext::CopyExecutionContext(
const std::shared_ptr<ThreadSafeAgentUidMap>& map,
std::shared_ptr<std::vector<std::vector<Agent*>>> agents)
: InPlaceExecutionContext(map), agents_(agents) {
auto* tinfo = ThreadInfo::GetInstance();
#pragma omp master
agents_->resize(tinfo->GetNumaNodes());
auto* param = Simulation::GetActive()->GetParam();
if (param->execution_order == Param::ExecutionOrder::kForEachOpForEachAgent) {
Log::Fatal("CopyExecutionContext",
"CopyExecutionContext does not support Param::execution_order = "
"Param::ExecutionOrder::kForEachOpForEachAgent");
}
}
// -----------------------------------------------------------------------------
CopyExecutionContext::~CopyExecutionContext() {}
// -----------------------------------------------------------------------------
void CopyExecutionContext::SetupIterationAll(
const std::vector<ExecutionContext*>& all_exec_ctxts) {
InPlaceExecutionContext::SetupIterationAll(all_exec_ctxts);
auto* rm = Simulation::GetActive()->GetResourceManager();
for (uint64_t n = 0; n < agents_->size(); ++n) {
agents_->at(n).reserve(rm->GetAgentVectorCapacity(n));
agents_->at(n).resize(rm->GetNumAgents(n));
}
auto* scheduler = Simulation::GetActive()->GetScheduler();
if (scheduler->GetAgentFilters().size() != 0) {
Log::Fatal("CopyExecutionContext",
"CopyExecutionContext does not support simulations with agent "
"filters yet (see Scheduler::SetAgentFilters)");
}
}
// -----------------------------------------------------------------------------
void CopyExecutionContext::TearDownAgentOpsAll(
const std::vector<ExecutionContext*>& all_exec_ctxts) {
auto* rm = Simulation::GetActive()->GetResourceManager();
auto del = L2F([](Agent* a) { delete a; });
rm->ForEachAgentParallel(del);
rm->SwapAgents(agents_.get());
}
// -----------------------------------------------------------------------------
void CopyExecutionContext::Execute(Agent* agent, AgentHandle ah,
const std::vector<Operation*>& operations) {
auto* copy = agent->NewCopy();
InPlaceExecutionContext::Execute(copy, ah, operations);
assert(ah.GetNumaNode() < agents_->size());
assert(ah.GetElementIdx() < agents_->at(ah.GetNumaNode()).size());
(*agents_.get())[ah.GetNumaNode()][ah.GetElementIdx()] = copy;
}
} // namespace experimental
} // namespace bdm
| 40.091837 | 80 | 0.591499 | [
"vector"
] |
9244065adfcd2160a1f7fca4ba3bb0ca8d69d7aa | 13,646 | cpp | C++ | source/Genesis/Bitmap/Compression/palettize.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | 3 | 2020-04-29T03:17:50.000Z | 2021-05-26T19:53:46.000Z | source/Genesis/Bitmap/Compression/palettize.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | 1 | 2020-04-29T03:12:47.000Z | 2020-04-29T03:12:47.000Z | source/Genesis/Bitmap/Compression/palettize.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | null | null | null | /****************************************************************************************/
/* Palettize */
/* */
/* Author: Charles Bloom */
/* Description: Palettize-ing code */
/* */
/* The contents of this file are subject to the Genesis3D Public License */
/* Version 1.01 (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.genesis3d.com */
/* */
/* Software distributed under the License is distributed on an "AS IS" */
/* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See */
/* the License for the specific language governing rights and limitations */
/* under the License. */
/* */
/* The Original Code is Genesis3D, released March 25, 1999. */
/*Genesis3D Version 1.1 released November 15, 1999 */
/* Copyright (C) 1999 WildTangent, Inc. All Rights Reserved */
/* */
/****************************************************************************************/
/*********
our colors are referred to as "RGB" triples, but are actually typically YUV
------
can palettize a 256x256 bitmap in less than 0.1 seconds
------
we palettize ("inverse colormap") using an octree lookup system
<> do we need to be able to palettize to RGBA ??
**********/
#include "palettize.h"
#include <stdlib.h>
#include <assert.h>
#include "ram.h"
#include "mempool.h"
#ifdef _TSC
#pragma message("palettize using TSC")
#include "tsc.h"
#endif
/*******/
#define new(type) geRam_AllocateClear(sizeof(type))
#define allocate(ptr) ptr = geRam_AllocateClear(sizeof(*ptr))
#define clear(ptr) memset(ptr,0,sizeof(*ptr))
#define destroy(ptr) if ( ptr ) { geRam_Free(ptr); (ptr) = nullptr; } else
/*******/
typedef struct palInfo palInfo;
int __inline closestPalInlineRGB(int R,int G,int B,palInfo *pi);
int closestPal(int R,int G,int B,palInfo *pi);
palInfo * closestPalInit(uint8 * palette);
void closestPalFree(palInfo *info);
/******/
geBoolean palettizePlane(const geBitmap_Info * SrcInfo,const void * SrcBits,
geBitmap_Info * DstInfo, void * DstBits,
int SizeX,int SizeY)
{
palInfo *palInfo;
int x,y,xtra,bpp;
gePixelFormat Format;
int R,G,B,A;
uint8 palette[768],*pSrc,*pDst;
assert( SrcInfo && SrcBits );
assert( DstInfo && DstBits );
assert( DstInfo->Format == GE_PIXELFORMAT_8BIT_PAL );
assert( gePixelFormat_IsRaw(SrcInfo->Format) );
if ( ! DstInfo->Palette )
return GE_FALSE;
if ( ! geBitmap_Palette_GetData(DstInfo->Palette,palette,GE_PIXELFORMAT_24BIT_RGB,256) )
return GE_FALSE;
#ifdef _TSC
pushTSC();
#endif
// rgbPlane is (planeLen*3) bytes
// palette is 768 bytes
palInfo = closestPalInit(palette);
if ( ! palInfo ) return GE_FALSE;
Format = SrcInfo->Format;
bpp = gePixelFormat_BytesPerPel(Format);
xtra = (SrcInfo->Stride - SizeX) * bpp;
pSrc = (uint8 *)SrcBits;
pDst = static_cast<uint8*>(DstBits);
if ( DstInfo->HasColorKey )
{
int DstCK;
const gePixelFormat_Operations * ops;
ops = gePixelFormat_GetOperations(Format);
assert(ops);
DstCK = DstInfo->ColorKey;
if ( gePixelFormat_HasAlpha(Format) )
{
gePixelFormat_ColorGetter GetColor;
GetColor = ops->GetColor;
for(y=SizeY;y--;)
{
for(x=SizeX;x--;)
{
GetColor(&pSrc,&R,&G,&B,&A);
if ( A < 128 )
{
*pDst++ = DstCK;
}
else
{
*pDst = closestPalInlineRGB(R,G,B,palInfo);
if ( *pDst == DstCK ) // {} this is really poor color-key avoidance!
*pDst ^= 1;
pDst++;
}
}
pSrc += xtra;
pDst += DstInfo->Stride - SizeX;
}
}
else if ( SrcInfo->HasColorKey )
{
uint32 SrcCK,Pixel;
gePixelFormat_PixelGetter GetPixel;
gePixelFormat_Decomposer DecomposePixel;
DecomposePixel = ops->DecomposePixel;
GetPixel = ops->GetPixel;
SrcCK = SrcInfo->ColorKey;
for(y=SizeY;y--;)
{
for(x=SizeX;x--;)
{
Pixel = GetPixel(&pSrc);
if ( Pixel == SrcCK )
{
*pDst++ = DstCK;
}
else
{
DecomposePixel(Pixel,&R,&G,&B,&A);
*pDst = closestPalInlineRGB(R,G,B,palInfo);
if ( *pDst == DstCK ) // {} this is really poor color-key avoidance!
*pDst ^= 1;
pDst++;
}
}
pSrc += xtra;
pDst += DstInfo->Stride - SizeX;
}
}
else
{
gePixelFormat_ColorGetter GetColor;
GetColor = ops->GetColor;
for(y=SizeY;y--;)
{
for(x=SizeX;x--;)
{
GetColor(&pSrc,&R,&G,&B,&A);
*pDst = closestPalInlineRGB(R,G,B,palInfo);
if ( *pDst == DstCK ) // {} this is really poor color-key avoidance!
*pDst ^= 1;
pDst++;
}
pSrc += xtra;
pDst += DstInfo->Stride - SizeX;
}
}
}
else
{
// dst does not have CK, and can't have alpha in this universe, so ignore src colorkey
#if 0 // these special cases just avoid a functional-call overhead
if ( Format == GE_PIXELFORMAT_24BIT_RGB )
{
for(y=SizeY;y--;)
{
for(x=SizeX;x--;)
{
R = *pSrc++; G = *pSrc++; B = *pSrc++;
*pDst++ = closestPalInlineRGB(R,G,B,palInfo);
}
pSrc += xtra;
pDst += DstInfo->Stride - SizeX;
}
}
else if ( Format == GE_PIXELFORMAT_24BIT_BGR )
{
for(y=SizeY;y--;)
{
for(x=SizeX;x--;)
{
B = *pSrc++; G = *pSrc++; R = *pSrc++;
*pDst++ = closestPalInlineRGB(R,G,B,palInfo);
}
pSrc += xtra;
pDst += DstInfo->Stride - SizeX;
}
}
else
#endif
{
const gePixelFormat_Operations * ops;
gePixelFormat_ColorGetter GetColor;
ops = gePixelFormat_GetOperations(Format);
assert(ops);
GetColor = ops->GetColor;
assert(GetColor);
for(y=SizeY;y--;)
{
for(x=SizeX;x--;)
{
GetColor(&pSrc,&R,&G,&B,&A);
*pDst++ = closestPalInlineRGB(R,G,B,palInfo);
}
pSrc += xtra;
pDst += DstInfo->Stride - SizeX;
}
}
}
#ifdef _TSC
showPopTSC("palettize");
#endif
closestPalFree(palInfo);
return GE_TRUE;
}
/***************
**
*
Build an OctTree containing all the palette entries; the RGB value
is the index into the tree, the value at the leaf is a palette index. All null children are then set
to point to their closest neighbor. It has a maximum depth of 8.
To find a palette entry, you take your RGB and just keep stepping in; in fact, it's quite trivial.
on an image of B bytes and a palette of P entries, this method is O(B+P)
Find the right neighbor for null children is a very difficult algorithm. I punt and
leave them null; when we find a null in descent, we do a hash-assisted search to find
the right pal entry, then add this color & pal entry to the octree for future use.
we store palette entries in the octree as (palVal+1) so that we can use 0 to mean "not assigned"
per-pixel time : 5e-7 (found in octree lookup)
per-color time : 7e-6 (not in octree time)
total_seconds = (5e-7)*(num_pels + palettize_size) +
(3e-8)*(num_actual_colors - palettize_size)*(palettize_size)
(coder=bitplane,transform=L97)
stop-rate 4 , PSNR on :
brute-force
pal1 ; 33.29
pal2 : 37.69
pal3 : 33.69
pal4 : 44.69
OctTree without "expandNulls" ("fast")
pal1 ; 25.73
pal2 : 32.50
pal3 : 27.84
pal4 : 28.07
OctTree with brute-force "expandNulls"
pal1 ; 32.53
pal2 : 37.09
pal3 : 33.27
pal4 : 33.50
OctTree with brute-force on null
pal1 ; 33.15
pal2 : 37.71
pal3 : 33.65
pal4 : 35.05
*
**
*****************/
#define QUANT_BITS (4)
#define QUANT_SHIFT (8-QUANT_BITS)
#define QUANT_ROUND (1<<(QUANT_SHIFT-1))
#define HASH_BITS (QUANT_BITS*3)
#define HASH_SIZE (1<<HASH_BITS)
#define HASH(R,G,B) ( (((R)>>QUANT_SHIFT)<<(QUANT_BITS+QUANT_BITS)) + (((G)>>QUANT_SHIFT)<<(QUANT_BITS)) + (((B)>>QUANT_SHIFT)))
#define HASHROUNDED(R,G,B) ( (((R+QUANT_ROUND)>>QUANT_SHIFT)<<(QUANT_BITS+QUANT_BITS)) + (((G+QUANT_ROUND)>>QUANT_SHIFT)<<(QUANT_BITS)) + (((B+QUANT_ROUND)>>QUANT_SHIFT)))
typedef struct octNode octNode;
struct octNode
{
octNode * kids[8];
octNode * parent;
};
typedef struct hashNode
{
struct hashNode *next;
int R,G,B,pal;
} hashNode;
struct palInfo
{
uint8 *palette;
octNode *root;
hashNode * hash[HASH_SIZE+1];
};
// internal protos:
int colorDistance(uint8 *ca,uint8 *cb);
int findClosestPalBrute(int R,int G,int B,palInfo *pi);
void addOctNode(octNode *root,int R,int G,int B,int palVal);
void addHash(palInfo *pi,int R,int G,int B,int palVal,int hash);
#define RGBbits(R,G,B,bits) (((((R)>>(bits))&1)<<2) + ((((G)>>(bits))&1)<<1) + (((B)>>((bits)))&1))
static MemPool * octNodePool = nullptr;
static MemPool * hashNodePool = nullptr;
static int PoolRefs = 0;
void Palettize_Start(void)
{
if ( PoolRefs == 0 )
{
// we init with 256 octnodes, then add one for each unique color
octNodePool = MemPool_Create(sizeof(octNode),1024,1024);
assert(octNodePool);
hashNodePool = MemPool_Create(sizeof(hashNode),1024,1024);
assert(hashNodePool);
}
PoolRefs ++;
}
void Palettize_Stop(void)
{
PoolRefs --;
if ( PoolRefs == 0 )
{
MemPool_Destroy(&octNodePool);
MemPool_Destroy(&hashNodePool);
}
}
/********************/
palInfo * closestPalInit(uint8 * palette)
{
palInfo *pi;
int i;
i = HASH_SIZE;
if ( (pi = static_cast<palInfo*>(new(palInfo))) == nullptr )
return nullptr;
pi->palette = palette;
pi->root = static_cast<octNode*>(MemPool_GetHunk(octNodePool));
assert(pi->root);
for(i=0;i<256;i++)
{
int R,G,B;
R = palette[3*i]; G = palette[3*i+1]; B = palette[3*i+2];
addOctNode(pi->root,R,G,B,i);
addHash(pi,R,G,B,i,HASH(R,G,B));
}
return pi;
}
int findClosestPal(int R,int G,int B,palInfo *pi)
{
hashNode *node;
int hash,d,bestD,bestP;
hash = HASHROUNDED(R,G,B);
if ( hash > HASH_SIZE ) hash = HASH_SIZE;
node = pi->hash[ hash ];
if ( ! node )
{
bestP = findClosestPalBrute(R,G,B,pi);
#if 1
// helps speed a little; depends on how common individual RGB values are
// (makes it so that if we see this exact RGB again we return bestP right away)
addOctNode(pi->root,R,G,B,bestP);
#endif
#if 0
//this could help speed, but actually makes this method approximate
node = MemPool_GetHunk(hashNodePool);
assert(node);
node->next = pi->hash[hash];
pi->hash[hash] = node;
node->R = R;
node->G = G;
node->B = B;
node->pal = bestP;
#endif
return bestP;
}
bestD = 99999999; bestP = node->pal;
while(node)
{
d = (R - node->R)*(R - node->R) + (G - node->G)*(G - node->G) + (B - node->B)*(B - node->B);
if ( d < bestD )
{
bestD = d;
bestP = node->pal;
}
node = node->next;
}
#if 1
// <> ?
// helps speed a little; depends on how common individual RGB values are
// (makes it so that if we see this exact RGB again we return bestP right away)
addOctNode(pi->root,R,G,B,bestP);
#endif
return bestP;
}
#define doStep(bits) do { kid = (node)->kids[ RGBbits(R,G,B,bits) ]; \
if ( kid ) node = kid; else return findClosestPal(R,G,B,pi); } while(0)
#define doSteps() do { node = pi->root; doStep(7); doStep(6); doStep(5); doStep(4); doStep(3); doStep(2); doStep(1); doStep(0); } while(0)
int __inline closestPalInlineRGB(int R,int G,int B,palInfo *pi)
{
octNode *node,*kid;
doSteps();
return ((int)node)-1;
}
int closestPal(int R,int G,int B,palInfo *pi)
{
octNode *node,*kid;
doSteps();
assert( ((int)node) <= 256 && ((int)node) > 0 );
return ((int)node)-1;
}
void closestPalFree(palInfo *pi)
{
assert(pi);
MemPool_Reset(octNodePool);
MemPool_Reset(hashNodePool);
destroy(pi);
}
int findClosestPalBrute(int R,int G,int B,palInfo *pi)
{
int d,p;
int bestD,bestP;
uint8 * pal;
uint8 color[3];
// now do a brute-force best-pal search to find the best pal entry
color[0] = R; color[1] = G; color[2] = B;
pal = pi->palette;
bestD = colorDistance(color,pal);
bestP = 0;
for(p=1;p<256;p++)
{
pal += 3;
d = colorDistance(color,pal);
if ( d < bestD )
{
bestD = d;
bestP = p;
}
}
return bestP;
}
int colorDistance(uint8 *ca,uint8 *cb)
{
int d,x;
d = 0;
x = ca[0] - cb[0];
d += x*x;
x = ca[1] - cb[1];
d += x*x;
x = ca[2] - cb[2];
d += x*x;
return d;
}
void addOctNode(octNode *root,int R,int G,int B,int palVal)
{
int idx;
int bits;
octNode *node = root;
for(bits=7;bits>0;bits--)
{
idx = RGBbits(R,G,B,bits);
if ( ! node->kids[idx] )
{
node->kids[idx] = static_cast<octNode*>(MemPool_GetHunk(octNodePool));
node->kids[idx]->parent = node;
}
node = node->kids[idx];
}
idx = RGBbits(R,G,B,0);
node->kids[idx] = (octNode *)(palVal+1);
}
void addHash(palInfo *pi,int R,int G,int B,int palVal,int hash)
{
hashNode *node;
int i,h;
for(i=0;i<8;i++)
{
h = hash + (i&1) + (((i>>1)&1)<<QUANT_BITS) + ((i>>2)<<(QUANT_BITS+QUANT_BITS));
if ( h <= HASH_SIZE )
{
node = static_cast<hashNode*>(MemPool_GetHunk(hashNodePool));
assert(node);
node->next = pi->hash[h];
pi->hash[h] = node;
node->R = R;
node->G = G;
node->B = B;
node->pal = palVal;
}
}
}
| 24.195035 | 171 | 0.5842 | [
"transform"
] |
92461e17304ac13a27d86c2fd73f61233d8267cf | 3,844 | h++ | C++ | include/rexio/keyboard.h++ | maciek-27/Rgp | d28b5522e640e4c7b951f6861d97cbe52b0a35c9 | [
"MIT"
] | null | null | null | include/rexio/keyboard.h++ | maciek-27/Rgp | d28b5522e640e4c7b951f6861d97cbe52b0a35c9 | [
"MIT"
] | null | null | null | include/rexio/keyboard.h++ | maciek-27/Rgp | d28b5522e640e4c7b951f6861d97cbe52b0a35c9 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008 Damian Kaczmarek, Maciej Kaminski
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////
#ifndef __KEYBOARD_H__
#define __KEYBOARD_H__
#include "commons.h++"
namespace Scr
{
/*!
\brief Class represents key (or key combination) pressed on client
terminal.
*/
class Key
{
private:
//Alt+letter or Esc,than letter
static const Uint altMask = 0x00400000;
//Control+letter
static const Uint controlMask = 0x00200000;
//!special key pressed
static const Uint specialMask = 0x56000000;
//basic key mask
static const Uint basicKeyMask= 0x0000007f;
Uint key;
public:
/*!
* Special ascii keys as teletype mnemonics. Please note, that this
* enum is temporary, and will be deprecated in 1.1
*
*/
enum ASCII
{
LF = 0xa,
CR = 0xd,
EoF = 0x4
};
/*!
* Special key names. May be used for comparizons against key object
* (please refer to handbook for use example)
*
*/
enum Special
{
Escape = 0x1b,
Tab = 0x561f0000, // on most systems: shift+tab
BackTab,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
//shifted
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
//??
F25,
F26,
F27,
F28,
F29,
F30,
F31,
F32,
F33,
F34,
F35,
F36,
Up,
Down,
Right,
Left,
CtrlUp,
CtrlDown,
CtrlRight,
CtrlLeft,
Enter,
Delete,
Backspace,
Insert,
Home,
PageUp,
PageDown,
End
};
__DE(NotABasicKey,Exception);
__DE(NotASpecialKey,Exception);
Key():key(0){;}
/*!
* \param key unsigned integer form
*
* This constructor allows implicit conversion between two forms of key
*/
Key(Uint key)throw()
{
this->key = key;
}
/*!
* implicit or
* static cast operator
*/
operator Uint()throw()
{
return key;
}
/*!
* If represents plain ascii character, function returns true.
* false is returned otherwise
*/
bool IsABasicKey()throw()
{
return
( key >= ' ' )
&& ( (key&0xff) <=127)
&& ((key & specialMask) != specialMask);
}
/*
* Function returns true if key is a special key (that means return,
* one of arrows, function key, delete etc.
*/
bool IsASpecialKey()throw()
{
return (key < ' ') or
((key & specialMask) == specialMask);
}
/*!
* as if it was a letter A-Z
*/
char GetBasicKey()throw(NotABasicKey);
//!
Special GetSpecialKey()throw(NotASpecialKey);
const char * GetKeyName()throw();
};
}
#endif
| 19.124378 | 73 | 0.604318 | [
"object"
] |
9247f52c22e70acef08a860c2268ab5d051fb35b | 3,887 | cpp | C++ | src/main/_2018/day17.cpp | Namdrib/adventofcode | c9479eb85326bcf9881396626523fb2a5524bf87 | [
"MIT"
] | null | null | null | src/main/_2018/day17.cpp | Namdrib/adventofcode | c9479eb85326bcf9881396626523fb2a5524bf87 | [
"MIT"
] | 6 | 2018-12-03T04:43:00.000Z | 2020-12-12T12:42:02.000Z | src/main/_2018/day17.cpp | Namdrib/adventofcode | c9479eb85326bcf9881396626523fb2a5524bf87 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include "../util/helpers.cpp"
using namespace std;
// http://adventofcode.com/2018/day/17
int spring_x = 500;
int spring_y = 0;
pii x_bounds = make_pair(500, 500);
pii y_bounds = make_pair(numeric_limits<int>::max(), numeric_limits<int>::min());
// setters and getters offsetting by min bounds
void set_grid(vs &grid, int x, int y, char c) {
grid.at(y - y_bounds.first)[x - x_bounds.first] = c;
}
char get_grid(vs &grid, int x, int y) {
return grid.at(y - y_bounds.first)[x - x_bounds.first];
}
// dir == 0 for left, == 1 for right
bool has_wall(vs &grid, int x, int y, bool dir) {
if (y >= y_bounds.second) {
return false;
}
while (true) {
if (x <= x_bounds.first) {
return false;
}
char thing = get_grid(grid, x, y);
if (thing == '.') {
return false;
}
if (thing == '#') {
return true;
}
x += (dir) ? -1 : 1;
}
}
// dir == 0 for left, == 1 for right
void fill_water(vs &grid, int x, int y, bool dir) {
if (y >= y_bounds.second) {
return;
}
while (true) {
if (x <= x_bounds.first) {
return;
}
if (get_grid(grid, x, y) == '#' || get_grid(grid, x, y) == '.') {
return;
}
set_grid(grid, x, y, '~');
x += (dir) ? -1 : 1;
}
}
// fill the grid with water starting from position x, y
void fill(vs &grid, int x, int y) {
// out of bounds
if (y >= y_bounds.second) {
return;
}
// move down
if (get_grid(grid, x, y + 1) == '.') {
set_grid(grid, x, y + 1, '|');
fill(grid, x, y + 1);
}
// can't go down any further
char below = get_grid(grid, x, y + 1);
if (below == '~' || below == '#') {
// expand left
if (get_grid(grid, x - 1, y) == '.') {
set_grid(grid, x - 1, y, '|');
fill(grid, x - 1, y);
}
// expand right
if (get_grid(grid, x + 1, y) == '.') {
set_grid(grid, x + 1, y, '|');
fill(grid, x + 1, y);
}
}
// turn '|' into '~' if the water is walled on both sides
if (has_wall(grid, x, y, 0) && has_wall(grid, x, y, 1)) {
fill_water(grid, x, y, 0);
fill_water(grid, x, y, 1);
}
}
int solve(vector<string> input, bool part_two) {
vector<vector<int>> nums;
vector<bool> x_first;
for (string s : input) {
nums.push_back(extract_nums_from(s));
x_first.push_back(s[0] == 'x');
}
// first pass to determine bounds
for (size_t i=0; i<nums.size(); i++) {
pii *fixed = &((x_first[i]) ? x_bounds : y_bounds);
pii *moving = &((x_first[i]) ? y_bounds : x_bounds);
fixed->first = min(fixed->first, nums[i][0]);
fixed->second = max(fixed->second, nums[i][0]);
moving->first = min(moving->first, nums[i][1]);
moving->second = max(moving->second, nums[i][2]);
}
x_bounds.first--;
x_bounds.second++;
// save min_y since output requires counting from the
// lowest y that appears in input values
// however the spring_y == 0
int min_y, max_y;
min_y = y_bounds.first;
max_y = y_bounds.second;
y_bounds.first = min(y_bounds.first, spring_y);
// second pass to build the grid
vector<string> grid(y_bounds.second - y_bounds.first + 1, string(x_bounds.second - x_bounds.first + 1, '.'));
for (size_t i = 0; i < nums.size(); i++) {
for (size_t j = nums[i][1]; j <= nums[i][2]; j++) {
int y = ((x_first[i]) ? j : nums[i][0]);
int x = ((x_first[i]) ? nums[i][0] : j);
set_grid(grid, x, y, '#');
}
}
set_grid(grid, spring_x, spring_y, '+');
// now actually do work
// simulate water dripping until overflow
fill(grid, spring_x, spring_y);
// calculate output values
int num_resting = 0, num_reach = 0;
for (size_t i = min_y; i <= max_y; i++) {
for (char c : grid[i]) {
if (c == '~') {
num_resting++;
}
else if (c == '|') {
num_reach++;
}
}
}
return num_resting + ((part_two) ? 0 : num_reach);
}
int main() {
vector<string> input = split_istream_per_line(cin);
cout << "Part 1: " << solve(input, false) << endl;
cout << "Part 2: " << solve(input, true) << endl;
}
| 21.594444 | 110 | 0.580911 | [
"vector"
] |
92584cc57e14aac9396814013c532cb80d8e320a | 154,836 | cpp | C++ | asteria/src/runtime/air_node.cpp | usama-makhzoum/asteria | ea4c893a038e0c5bef14d4d9f6723124a0cbb30f | [
"BSD-3-Clause"
] | null | null | null | asteria/src/runtime/air_node.cpp | usama-makhzoum/asteria | ea4c893a038e0c5bef14d4d9f6723124a0cbb30f | [
"BSD-3-Clause"
] | null | null | null | asteria/src/runtime/air_node.cpp | usama-makhzoum/asteria | ea4c893a038e0c5bef14d4d9f6723124a0cbb30f | [
"BSD-3-Clause"
] | null | null | null | // This file is part of Asteria.
// Copyleft 2018 - 2021, LH_Mouse. All wrongs reserved.
#include "../precompiled.hpp"
#include "air_node.hpp"
#include "enums.hpp"
#include "executive_context.hpp"
#include "global_context.hpp"
#include "abstract_hooks.hpp"
#include "analytic_context.hpp"
#include "genius_collector.hpp"
#include "runtime_error.hpp"
#include "variable_callback.hpp"
#include "variable.hpp"
#include "ptc_arguments.hpp"
#include "loader_lock.hpp"
#include "air_optimizer.hpp"
#include "../compiler/token_stream.hpp"
#include "../compiler/statement_sequence.hpp"
#include "../compiler/statement.hpp"
#include "../compiler/expression_unit.hpp"
#include "../llds/avmc_queue.hpp"
#include "../utils.hpp"
namespace asteria {
namespace {
bool&
do_rebind_nodes(bool& dirty, cow_vector<AIR_Node>& code,
Abstract_Context& ctx)
{
for(size_t i = 0; i < code.size(); ++i) {
auto qnode = code[i].rebind_opt(ctx);
dirty |= !!qnode;
if(qnode)
code.mut(i) = ::std::move(*qnode);
}
return dirty;
}
bool&
do_rebind_nodes(bool& dirty, cow_vector<cow_vector<AIR_Node>>& seqs,
Abstract_Context& ctx)
{
for(size_t k = 0; k < seqs.size(); ++k) {
for(size_t i = 0; i < seqs[k].size(); ++i) {
auto qnode = seqs[k][i].rebind_opt(ctx);
dirty |= !!qnode;
if(qnode)
seqs.mut(k).mut(i) = ::std::move(*qnode);
}
}
return dirty;
}
template<typename NodeT>
opt<AIR_Node>
do_rebind_return_opt(bool dirty, NodeT&& xnode)
{
if(!dirty)
return nullopt;
else
return ::std::forward<NodeT>(xnode);
}
bool
do_solidify_nodes(AVMC_Queue& queue, const cow_vector<AIR_Node>& code)
{
bool r = ::rocket::all_of(code, [&](const AIR_Node& node) { return node.solidify(queue); });
queue.shrink_to_fit();
return r;
}
void
do_simple_assign_value_common(Executive_Context& ctx)
{
auto value = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
ctx.stack().back().dereference_mutable() = ::std::move(value);
}
AIR_Status
do_evaluate_subexpression(Executive_Context& ctx, bool assign, const AVMC_Queue& queue)
{
if(queue.empty())
// Leave the condition on the top of the stack.
return air_status_next;
if(!assign) {
// Discard the top which will be overwritten anyway, then evaluate the
// subexpression. The status code must be forwarded as is, because PTCs may
// return `air_status_return_ref`.
ctx.stack().pop_back();
return queue.execute(ctx);
}
// Evaluate the subexpression.
auto status = queue.execute(ctx);
ROCKET_ASSERT(status == air_status_next);
do_simple_assign_value_common(ctx);
return air_status_next;
}
Value&
do_get_first_operand(Reference_Stack& stack, bool assign)
{
if(assign)
return stack.back().dereference_mutable();
else
return stack.mut_back().mutate_into_temporary();
}
Reference&
do_declare(Executive_Context& ctx, const phsh_string& name)
{
return ctx.open_named_reference(name).set_uninit();
}
AIR_Status
do_execute_block(const AVMC_Queue& queue, Executive_Context& ctx)
{
// Execute the body on a new context.
Executive_Context ctx_next(Executive_Context::M_plain(), ctx);
AIR_Status status;
ASTERIA_RUNTIME_TRY {
status = queue.execute(ctx_next);
}
ASTERIA_RUNTIME_CATCH(Runtime_Error& except) {
ctx_next.on_scope_exit(except);
throw;
}
ctx_next.on_scope_exit(status);
return status;
}
// These are user-defined parameter types for AVMC nodes.
// The `enumerate_variables()` callback is optional.
struct Sparam_sloc_text
{
Source_Location sloc;
cow_string text;
};
struct Sparam_sloc_name
{
Source_Location sloc;
phsh_string name;
};
struct Sparam_name
{
phsh_string name;
};
struct Sparam_import
{
Compiler_Options opts;
Source_Location sloc;
};
template<size_t sizeT>
struct Sparam_queues
{
array<AVMC_Queue, sizeT> queues;
Variable_Callback&
enumerate_variables(Variable_Callback& callback)
const
{
::rocket::for_each(this->queues, callback);
return callback;
}
};
using Sparam_queues_2 = Sparam_queues<2>;
using Sparam_queues_3 = Sparam_queues<3>;
using Sparam_queues_4 = Sparam_queues<4>;
struct Sparam_switch
{
cow_vector<AVMC_Queue> queues_labels;
cow_vector<AVMC_Queue> queues_bodies;
cow_vector<cow_vector<phsh_string>> names_added;
Variable_Callback&
enumerate_variables(Variable_Callback& callback)
const
{
::rocket::for_each(this->queues_labels, callback);
::rocket::for_each(this->queues_bodies, callback);
return callback;
}
};
struct Sparam_for_each
{
phsh_string name_key;
phsh_string name_mapped;
AVMC_Queue queue_init;
AVMC_Queue queue_body;
Variable_Callback&
enumerate_variables(Variable_Callback& callback)
const
{
this->queue_init.enumerate_variables(callback);
this->queue_body.enumerate_variables(callback);
return callback;
}
};
struct Sparam_try_catch
{
Source_Location sloc_try;
AVMC_Queue queue_try;
Source_Location sloc_catch;
phsh_string name_except;
AVMC_Queue queue_catch;
Variable_Callback&
enumerate_variables(Variable_Callback& callback)
const
{
this->queue_try.enumerate_variables(callback);
this->queue_catch.enumerate_variables(callback);
return callback;
}
};
struct Sparam_func
{
Compiler_Options opts;
Source_Location sloc;
cow_string func;
cow_vector<phsh_string> params;
cow_vector<AIR_Node> code_body;
Variable_Callback&
enumerate_variables(Variable_Callback& callback)
const
{
::rocket::for_each(this->code_body, callback);
return callback;
}
};
struct Sparam_defer
{
Source_Location sloc;
cow_vector<AIR_Node> code_body;
Variable_Callback&
enumerate_variables(Variable_Callback& callback)
const
{
::rocket::for_each(this->code_body, callback);
return callback;
}
};
// These are traits for individual AIR node types.
// Each traits struct must contain the `execute()` function, and optionally,
// these functions: `make_uparam()`, `make_sparam()`, `get_symbols()`.
struct AIR_Traits_clear_stack
{
// `up` is unused.
// `sp` is unused.
static
AIR_Status
execute(Executive_Context& ctx)
{
ctx.stack().clear();
return air_status_next;
}
};
struct AIR_Traits_execute_block
{
// `up` is unused.
// `sp` is the solidified body.
static
AVMC_Queue
make_sparam(bool& reachable, const AIR_Node::S_execute_block& altr)
{
AVMC_Queue queue;
reachable &= do_solidify_nodes(queue, altr.code_body);
return queue;
}
static
AIR_Status
execute(Executive_Context& ctx, const AVMC_Queue& queue)
{
return do_execute_block(queue, ctx);
}
};
struct AIR_Traits_declare_variable
{
// `up` is unused.
// `sp` is the source location and name;
static
const Source_Location&
get_symbols(const AIR_Node::S_declare_variable& altr)
{
return altr.sloc;
}
static
Sparam_sloc_name
make_sparam(bool& /*reachable*/, const AIR_Node::S_declare_variable& altr)
{
Sparam_sloc_name sp;
sp.sloc = altr.sloc;
sp.name = altr.name;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, const Sparam_sloc_name& sp)
{
const auto qhooks = ctx.global().get_hooks_opt();
const auto gcoll = ctx.global().genius_collector();
// Allocate an uninitialized variable.
// Inject the variable into the current context.
const auto var = gcoll->create_variable();
ctx.open_named_reference(sp.name).set_variable(var);
if(qhooks)
qhooks->on_variable_declare(sp.sloc, sp.name);
// Push a copy of the reference onto the stack.
ctx.stack().emplace_back_uninit().set_variable(var);
return air_status_next;
}
};
struct AIR_Traits_initialize_variable
{
// `up` is `immutable`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_initialize_variable& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_initialize_variable& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.immutable;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// Read the value of the initializer.
// Note that the initializer must not have been empty for this function.
auto val = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
// Get the variable back.
auto var = ctx.stack().back().get_variable_opt();
ROCKET_ASSERT(var && !var->is_initialized());
ctx.stack().pop_back();
// Initialize it.
var->initialize(::std::move(val), up.p8[0]);
return air_status_next;
}
};
struct AIR_Traits_if_statement
{
// `up` is `negative`.
// `sp` is the two branches.
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_if_statement& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.negative;
return up;
}
static
Sparam_queues_2
make_sparam(bool& reachable, const AIR_Node::S_if_statement& altr)
{
Sparam_queues_2 sp;
bool rtrue = do_solidify_nodes(sp.queues[0], altr.code_true);
bool rfalse = do_solidify_nodes(sp.queues[1], altr.code_false);
reachable &= rtrue | rfalse;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const Sparam_queues_2& sp)
{
// Check the value of the condition.
if(ctx.stack().back().dereference_readonly().test() != up.p8[0])
// Execute the true branch and forward the status verbatim.
return do_execute_block(sp.queues[0], ctx);
// Execute the false branch and forward the status verbatim.
return do_execute_block(sp.queues[1], ctx);
}
};
struct AIR_Traits_switch_statement
{
// `up` is unused.
// `sp` is ... everything.
static
Sparam_switch
make_sparam(bool& /*reachable*/, const AIR_Node::S_switch_statement& altr)
{
Sparam_switch sp;
sp.queues_labels.append(altr.code_labels.size());
for(size_t k = 0; k != altr.code_labels.size(); ++k)
do_solidify_nodes(sp.queues_labels.mut(k), altr.code_labels.at(k));
sp.queues_bodies.append(altr.code_bodies.size());
for(size_t k = 0; k != altr.code_bodies.size(); ++k)
do_solidify_nodes(sp.queues_bodies.mut(k), altr.code_bodies.at(k));
sp.names_added = altr.names_added;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, const Sparam_switch& sp)
{
// Get the number of clauses.
auto nclauses = sp.queues_labels.size();
ROCKET_ASSERT(nclauses == sp.queues_bodies.size());
ROCKET_ASSERT(nclauses == sp.names_added.size());
// Read the value of the condition and find the target clause for it.
auto cond = ctx.stack().back().dereference_readonly();
size_t bp = SIZE_MAX;
// This is different from the `switch` statement in C, where `case` labels must
// have constant operands.
for(size_t i = 0; i < nclauses; ++i) {
// This is a `default` clause if the condition is empty, and a `case` clause
// otherwise.
if(sp.queues_labels[i].empty()) {
if(bp == SIZE_MAX) {
bp = i;
continue;
}
ASTERIA_THROW("Multiple `default` clauses");
}
// Evaluate the operand and check whether it equals `cond`.
auto status = sp.queues_labels[i].execute(ctx);
ROCKET_ASSERT(status == air_status_next);
if(ctx.stack().back().dereference_readonly().compare(cond) == compare_equal) {
bp = i;
break;
}
}
// Skip this statement if no matching clause has been found.
if(bp != SIZE_MAX) {
Executive_Context ctx_body(Executive_Context::M_plain(), ctx);
AIR_Status status;
// Inject all bypassed variables into the scope.
for(const auto& name : sp.names_added[bp])
do_declare(ctx_body, name);
ASTERIA_RUNTIME_TRY {
do {
// Execute the body.
status = sp.queues_bodies[bp].execute(ctx_body);
if(::rocket::is_any_of(status, { air_status_break_unspec,
air_status_break_switch }))
break;
if(status != air_status_next)
return status;
}
while(++bp < nclauses);
}
ASTERIA_RUNTIME_CATCH(Runtime_Error& except) {
ctx_body.on_scope_exit(except);
throw;
}
ctx_body.on_scope_exit(status);
}
return air_status_next;
}
};
struct AIR_Traits_do_while_statement
{
// `up` is `negative`.
// `sp` is the loop body and condition.
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_do_while_statement& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.negative;
return up;
}
static
Sparam_queues_2
make_sparam(bool& reachable, const AIR_Node::S_do_while_statement& altr)
{
Sparam_queues_2 sp;
reachable &= do_solidify_nodes(sp.queues[0], altr.code_body);
do_solidify_nodes(sp.queues[1], altr.code_cond);
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const Sparam_queues_2& sp)
{
// This is the same as the `do...while` statement in C.
for(;;) {
// Execute the body.
auto status = do_execute_block(sp.queues[0], ctx);
if(::rocket::is_any_of(status, { air_status_break_unspec, air_status_break_while }))
break;
if(::rocket::is_none_of(status, { air_status_next, air_status_continue_unspec,
air_status_continue_while }))
return status;
// Check the condition.
status = sp.queues[1].execute(ctx);
ROCKET_ASSERT(status == air_status_next);
if(ctx.stack().back().dereference_readonly().test() == up.p8[0])
break;
}
return air_status_next;
}
};
struct AIR_Traits_while_statement
{
// `up` is `negative`.
// `sp` is the condition and loop body.
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_while_statement& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.negative;
return up;
}
static
Sparam_queues_2
make_sparam(bool& /*reachable*/, const AIR_Node::S_while_statement& altr)
{
Sparam_queues_2 sp;
do_solidify_nodes(sp.queues[0], altr.code_cond);
do_solidify_nodes(sp.queues[1], altr.code_body);
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const Sparam_queues_2& sp)
{
// This is the same as the `while` statement in C.
for(;;) {
// Check the condition.
auto status = sp.queues[0].execute(ctx);
ROCKET_ASSERT(status == air_status_next);
if(ctx.stack().back().dereference_readonly().test() == up.p8[0])
break;
// Execute the body.
status = do_execute_block(sp.queues[1], ctx);
if(::rocket::is_any_of(status, { air_status_break_unspec, air_status_break_while }))
break;
if(::rocket::is_none_of(status, { air_status_next, air_status_continue_unspec,
air_status_continue_while }))
return status;
}
return air_status_next;
}
};
struct AIR_Traits_for_each_statement
{
// `up` is unused.
// `sp` is ... everything.
static
Sparam_for_each
make_sparam(bool& /*reachable*/, const AIR_Node::S_for_each_statement& altr)
{
Sparam_for_each sp;
sp.name_key = altr.name_key;
sp.name_mapped = altr.name_mapped;
do_solidify_nodes(sp.queue_init, altr.code_init);
do_solidify_nodes(sp.queue_body, altr.code_body);
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, const Sparam_for_each& sp)
{
// Get global interfaces.
auto gcoll = ctx.global().genius_collector();
// We have to create an outer context due to the fact that the key and mapped
// references outlast every iteration.
Executive_Context ctx_for(Executive_Context::M_plain(), ctx);
// Allocate an uninitialized variable for the key.
const auto vkey = gcoll->create_variable();
ctx_for.open_named_reference(sp.name_key).set_variable(vkey);
// Create the mapped reference.
auto& mapped = do_declare(ctx_for, sp.name_mapped);
// Evaluate the range initializer and set the range up, which isn't going to
// change for all loops.
auto status = sp.queue_init.execute(ctx_for);
ROCKET_ASSERT(status == air_status_next);
mapped = ::std::move(ctx_for.stack().mut_back());
const auto range = mapped.dereference_readonly();
switch(weaken_enum(range.type())) {
case type_null:
// Do nothing.
return air_status_next;
case type_array: {
const auto& arr = range.as_array();
for(int64_t i = 0; i < arr.ssize(); ++i) {
// Set the key which is the subscript of the mapped element in the array.
vkey->initialize(i, true);
mapped.push_modifier_array_index(i);
// Execute the loop body.
status = do_execute_block(sp.queue_body, ctx_for);
if(::rocket::is_any_of(status, { air_status_break_unspec,
air_status_break_for }))
break;
if(::rocket::is_none_of(status, { air_status_next, air_status_continue_unspec,
air_status_continue_for }))
return status;
// Restore the mapped reference.
mapped.pop_modifier();
}
return air_status_next;
}
case type_object: {
const auto& obj = range.as_object();
for(auto it = obj.begin(); it != obj.end(); ++it) {
// Set the key which is the key of this element in the object.
vkey->initialize(it->first.rdstr(), true);
mapped.push_modifier_object_key(it->first);
// Execute the loop body.
status = do_execute_block(sp.queue_body, ctx_for);
if(::rocket::is_any_of(status, { air_status_break_unspec,
air_status_break_for }))
break;
if(::rocket::is_none_of(status, { air_status_next, air_status_continue_unspec,
air_status_continue_for }))
return status;
// Restore the mapped reference.
mapped.pop_modifier();
}
return air_status_next;
}
default:
ASTERIA_THROW("Range value not iterable (range `$1`)", range);
}
}
};
struct AIR_Traits_for_statement
{
// `up` is unused.
// `sp` is ... everything.
static
Sparam_queues_4
make_sparam(bool& /*reachable*/, const AIR_Node::S_for_statement& altr)
{
Sparam_queues_4 sp;
do_solidify_nodes(sp.queues[0], altr.code_init);
do_solidify_nodes(sp.queues[1], altr.code_cond);
do_solidify_nodes(sp.queues[2], altr.code_step);
do_solidify_nodes(sp.queues[3], altr.code_body);
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, const Sparam_queues_4& sp)
{
// This is the same as the `for` statement in C.
// We have to create an outer context due to the fact that names declared in the
// first segment outlast every iteration.
Executive_Context ctx_for(Executive_Context::M_plain(), ctx);
// Execute the loop initializer, which shall only be a definition or an expression
// statement.
auto status = sp.queues[0].execute(ctx_for);
ROCKET_ASSERT(status == air_status_next);
for(;;) {
// Check the condition.
status = sp.queues[1].execute(ctx_for);
ROCKET_ASSERT(status == air_status_next);
// This is a special case: If the condition is empty then the loop is infinite.
if(!ctx_for.stack().empty() &&
!ctx_for.stack().back().dereference_readonly().test())
break;
// Execute the body.
status = do_execute_block(sp.queues[3], ctx_for);
if(::rocket::is_any_of(status, { air_status_break_unspec, air_status_break_for }))
break;
if(::rocket::is_none_of(status, { air_status_next, air_status_continue_unspec,
air_status_continue_for }))
return status;
// Execute the increment.
status = sp.queues[2].execute(ctx_for);
ROCKET_ASSERT(status == air_status_next);
}
return air_status_next;
}
};
struct AIR_Traits_try_statement
{
// `up` is unused.
// `sp` is ... everything.
static
Sparam_try_catch
make_sparam(bool& reachable, const AIR_Node::S_try_statement& altr)
{
Sparam_try_catch sp;
sp.sloc_try = altr.sloc_try;
bool rtry = do_solidify_nodes(sp.queue_try, altr.code_try);
sp.sloc_catch = altr.sloc_catch;
sp.name_except = altr.name_except;
bool rcatch = do_solidify_nodes(sp.queue_catch, altr.code_catch);
reachable &= rtry | rcatch;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, const Sparam_try_catch& sp)
ASTERIA_RUNTIME_TRY {
// This is almost identical to JavaScript.
// Execute the `try` block. If no exception is thrown, this will have
// little overhead.
auto status = do_execute_block(sp.queue_try, ctx);
if(status != air_status_return_ref)
return status;
// This must not be PTC'd, otherwise exceptions thrown from tail calls
// won't be caught.
ctx.stack().mut_back().finish_call(ctx.global());
return status;
}
ASTERIA_RUNTIME_CATCH(Runtime_Error& except) {
// Append a frame due to exit of the `try` clause.
// Reuse the exception object. Don't bother allocating a new one.
except.push_frame_try(sp.sloc_try);
// This branch must be executed inside this `catch` block.
// User-provided bindings may obtain the current exception using
// `::std::current_exception`.
Executive_Context ctx_catch(Executive_Context::M_plain(), ctx);
AIR_Status status;
ASTERIA_RUNTIME_TRY {
// Set the exception reference.
ctx_catch.open_named_reference(sp.name_except)
.set_temporary(except.value());
// Set backtrace frames.
V_array backtrace;
for(size_t i = 0; i < except.count_frames(); ++i) {
const auto& f = except.frame(i);
// Translate each frame into a human-readable format.
V_object r;
r.try_emplace(sref("frame"), sref(f.what_type()));
r.try_emplace(sref("file"), f.file());
r.try_emplace(sref("line"), f.line());
r.try_emplace(sref("column"), f.column());
r.try_emplace(sref("value"), f.value());
// Append this frame.
backtrace.emplace_back(::std::move(r));
}
ctx_catch.open_named_reference(sref("__backtrace"))
.set_temporary(::std::move(backtrace));
// Execute the `catch` clause.
status = sp.queue_catch.execute(ctx_catch);
}
ASTERIA_RUNTIME_CATCH(Runtime_Error& nested) {
ctx_catch.on_scope_exit(nested);
nested.push_frame_catch(sp.sloc_catch, except.value());
throw;
}
ctx_catch.on_scope_exit(status);
return status;
}
};
struct AIR_Traits_throw_statement
{
// `up` is unused.
// `sp` is the source location.
static
Source_Location
make_sparam(bool& reachable, const AIR_Node::S_throw_statement& altr)
{
reachable = false;
return altr.sloc;
}
[[noreturn]] static
AIR_Status
execute(Executive_Context& ctx, const Source_Location& sloc)
{
// Read the value to throw.
// Note that the operand must not have been empty for this code.
throw Runtime_Error(Runtime_Error::M_throw(),
ctx.stack().back().dereference_readonly(), sloc);
}
};
struct AIR_Traits_assert_statement
{
// `up` is `negative`.
// `sp` is the source location.
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_assert_statement& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.negative;
return up;
}
static
Sparam_sloc_text
make_sparam(bool& /*reachable*/, const AIR_Node::S_assert_statement& altr)
{
Sparam_sloc_text sp;
sp.sloc = altr.sloc;
sp.text = altr.msg;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const Sparam_sloc_text& sp)
{
// Check the value of the condition.
// When the assertion succeeds, there is nothing to do.
if(ROCKET_EXPECT(ctx.stack().back().dereference_readonly().test() != up.p8[0]))
return air_status_next;
// Throw an exception if the assertion fails.
// This cannot be disabled.
throw Runtime_Error(Runtime_Error::M_assert(), sp.sloc, sp.text);
}
};
struct AIR_Traits_simple_status
{
// `up` is `status`.
// `sp` is unused.
static
AVMC_Queue::Uparam
make_uparam(bool& reachable, const AIR_Node::S_simple_status& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = weaken_enum(altr.status);
reachable = false;
return up;
}
static
AIR_Status
execute(Executive_Context& /*ctx*/, AVMC_Queue::Uparam up)
{
return static_cast<AIR_Status>(up.p8[0]);
}
};
struct AIR_Traits_convert_to_temporary
{
// `up` is unused.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_convert_to_temporary& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx)
{
ctx.stack().mut_back().mutate_into_temporary();
return air_status_next;
}
};
struct AIR_Traits_push_global_reference
{
// `up` is unused.
// `sp` is the source location and name;
static
const Source_Location&
get_symbols(const AIR_Node::S_push_global_reference& altr)
{
return altr.sloc;
}
static
phsh_string
make_sparam(bool& /*reachable*/, const AIR_Node::S_push_global_reference& altr)
{
return altr.name;
}
static
AIR_Status
execute(Executive_Context& ctx, const phsh_string& name)
{
// Look for the name in the global context.
auto qref = ctx.global().get_named_reference_opt(name);
if(!qref)
ASTERIA_THROW("Undeclared identifier `$1`", name);
// Push a copy of it.
ctx.stack().emplace_back_uninit() = *qref;
return air_status_next;
}
};
struct AIR_Traits_push_local_reference
{
// `up` is the depth.
// `sp` is the source location and name;
static
const Source_Location&
get_symbols(const AIR_Node::S_push_local_reference& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_push_local_reference& altr)
{
AVMC_Queue::Uparam up;
up.s32 = altr.depth;
return up;
}
static
phsh_string
make_sparam(bool& /*reachable*/, const AIR_Node::S_push_local_reference& altr)
{
return altr.name;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const phsh_string& name)
{
// Get the context.
Executive_Context* qctx = &ctx;
for(uint32_t k = 0; k != up.s32; ++k) {
qctx = qctx->get_parent_opt();
ROCKET_ASSERT(qctx);
}
// Look for the name in the context.
auto qref = qctx->get_named_reference_opt(name);
if(!qref)
ASTERIA_THROW("Undeclared identifier `$1`", name);
// Check if control flow has bypassed its initialization.
if(qref->is_uninit())
ASTERIA_THROW("Use of bypassed variable or reference `$1`", name);
// Push a copy of it.
ctx.stack().emplace_back_uninit() = *qref;
return air_status_next;
}
};
struct AIR_Traits_push_bound_reference
{
// `up` is unused.
// `sp` is the reference to push.
static
Reference
make_sparam(bool& /*reachable*/, const AIR_Node::S_push_bound_reference& altr)
{
return altr.ref;
}
static
AIR_Status
execute(Executive_Context& ctx, const Reference& ref)
{
ctx.stack().emplace_back_uninit() = ref;
return air_status_next;
}
};
struct AIR_Traits_define_function
{
// `up` is unused.
// `sp` is ... everything.
static
Sparam_func
make_sparam(bool& /*reachable*/, const AIR_Node::S_define_function& altr)
{
Sparam_func sp;
sp.opts = altr.opts;
sp.sloc = altr.sloc;
sp.func = altr.func;
sp.params = altr.params;
sp.code_body = altr.code_body;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, const Sparam_func& sp)
{
// Rewrite nodes in the body as necessary.
AIR_Optimizer optmz(sp.opts);
optmz.rebind(&ctx, sp.params, sp.code_body);
auto qtarget = optmz.create_function(sp.sloc, sp.func);
// Push the function as a temporary.
ctx.stack().emplace_back_uninit().set_temporary(::std::move(qtarget));
return air_status_next;
}
};
struct AIR_Traits_branch_expression
{
// `up` is `assign`.
// `sp` is the branches.
static
const Source_Location&
get_symbols(const AIR_Node::S_branch_expression& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_branch_expression& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
Sparam_queues_2
make_sparam(bool& reachable, const AIR_Node::S_branch_expression& altr)
{
Sparam_queues_2 sp;
bool rtrue = do_solidify_nodes(sp.queues[0], altr.code_true);
bool rfalse = do_solidify_nodes(sp.queues[1], altr.code_false);
reachable &= rtrue | rfalse;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const Sparam_queues_2& sp)
{
// Check the value of the condition.
if(ctx.stack().back().dereference_readonly().test())
return do_evaluate_subexpression(ctx, up.p8[0], sp.queues[0]);
else
return do_evaluate_subexpression(ctx, up.p8[0], sp.queues[1]);
}
};
struct AIR_Traits_coalescence
{
// `up` is `assign`.
// `sp` is the null branch.
static
const Source_Location&
get_symbols(const AIR_Node::S_coalescence& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_coalescence& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AVMC_Queue
make_sparam(bool& /*reachable*/, const AIR_Node::S_coalescence& altr)
{
AVMC_Queue queue;
do_solidify_nodes(queue, altr.code_null);
return queue;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const AVMC_Queue& queue)
{
// Check the value of the condition.
if(!ctx.stack().back().dereference_readonly().is_null())
return air_status_next;
else
return do_evaluate_subexpression(ctx, up.p8[0], queue);
}
};
ROCKET_NOINLINE
Reference&
do_invoke_nontail(Reference& self, const Source_Location& sloc, Executive_Context& ctx,
const cow_function& target, Reference_Stack&& stack)
{
// Perform plain calls if there is no hook.
const auto qhooks = ctx.global().get_hooks_opt();
if(ROCKET_EXPECT(!qhooks)) {
target.invoke(self, ctx.global(), ::std::move(stack));
return self;
}
// Note exceptions thrown here are not caught.
qhooks->on_function_call(sloc, target);
ASTERIA_RUNTIME_TRY {
target.invoke(self, ctx.global(), ::std::move(stack));
}
ASTERIA_RUNTIME_CATCH(Runtime_Error& except) {
qhooks->on_function_except(sloc, target, except);
throw;
}
qhooks->on_function_return(sloc, target, self);
return self;
}
AIR_Status
do_function_call_common(Reference& self, const Source_Location& sloc, Executive_Context& ctx,
const cow_function& target, PTC_Aware ptc, Reference_Stack&& stack)
{
// Perform plain calls in non-PTC contexts.
if(ROCKET_EXPECT(ptc == ptc_aware_none)) {
do_invoke_nontail(self, sloc, ctx, target, ::std::move(stack));
return air_status_next;
}
// Pack arguments for this proper tail call, which will be unpacked outside this scope.
stack.emplace_back_uninit() = ::std::move(self);
auto ptca = ::rocket::make_refcnt<PTC_Arguments>(sloc, ptc, target, ::std::move(stack));
self.set_ptc_args(::std::move(ptca));
// Force `air_status_return_ref` if control flow reaches the end of a function.
// Otherwise a null reference is returned instead of this PTC wrapper, which can then
// never be unpacked.
return air_status_return_ref;
}
Reference_Stack&
do_pop_positional_arguments_into_alt_stack(Executive_Context& ctx, size_t nargs)
{
auto& alt_stack = ctx.alt_stack();
alt_stack.clear();
for(size_t k = nargs - 1; k != SIZE_MAX; --k) {
// Get an argument. Ensure it is dereferenceable.
ROCKET_ASSERT(k < ctx.stack().size());
auto& arg = ctx.stack().mut_back(k);
arg.dereference_readonly();
alt_stack.emplace_back_uninit() = ::std::move(arg);
}
ctx.stack().pop_back(nargs);
return alt_stack;
}
struct AIR_Traits_function_call
{
// `up` is `nargs` and `ptc`.
// `sp` is the source location.
static
const Source_Location&
get_symbols(const AIR_Node::S_function_call& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& reachable, const AIR_Node::S_function_call& altr)
{
AVMC_Queue::Uparam up;
up.s32 = altr.nargs;
up.p8[0] = static_cast<uint8_t>(altr.ptc);
reachable &= (altr.ptc == ptc_aware_none);
return up;
}
static
Source_Location
make_sparam(bool& /*reachable*/, const AIR_Node::S_function_call& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const Source_Location& sloc)
{
const auto sentry = ctx.global().copy_recursion_sentry();
const auto qhooks = ctx.global().get_hooks_opt();
// Generate a single-step trap before unpacking arguments.
if(qhooks)
qhooks->on_single_step_trap(sloc);
// Pop arguments off the stack backwards.
auto& alt_stack = do_pop_positional_arguments_into_alt_stack(ctx, up.s32);
// Copy the target, which shall be of type `function`.
auto value = ctx.stack().back().dereference_readonly();
if(!value.is_function())
ASTERIA_THROW("Attempt to call a non-function (value `$1`)", value);
return do_function_call_common(ctx.stack().mut_back().pop_modifier(), sloc, ctx,
value.as_function(), static_cast<PTC_Aware>(up.p8[0]),
::std::move(alt_stack));
}
};
struct AIR_Traits_member_access
{
// `up` is unused.
// `sp` is the name.
static
const Source_Location&
get_symbols(const AIR_Node::S_member_access& altr)
{
return altr.sloc;
}
static
phsh_string
make_sparam(bool& /*reachable*/, const AIR_Node::S_member_access& altr)
{
return altr.name;
}
static
AIR_Status
execute(Executive_Context& ctx, const phsh_string& name)
{
ctx.stack().mut_back().push_modifier_object_key(name);
return air_status_next;
}
};
struct AIR_Traits_push_unnamed_array
{
// `up` is `nelems`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_push_unnamed_array& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_push_unnamed_array& altr)
{
AVMC_Queue::Uparam up;
up.s32 = altr.nelems;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// Pop elements from the stack and store them in an array backwards.
V_array array;
array.resize(up.s32);
for(auto it = array.mut_rbegin(); it != array.rend(); ++it) {
// Write elements backwards.
*it = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
}
// Push the array as a temporary.
ctx.stack().emplace_back_uninit().set_temporary(::std::move(array));
return air_status_next;
}
};
struct AIR_Traits_push_unnamed_object
{
// `up` is unused.
// `sp` is the list of keys.
static
const Source_Location&
get_symbols(const AIR_Node::S_push_unnamed_object& altr)
{
return altr.sloc;
}
static
cow_vector<phsh_string>
make_sparam(bool& /*reachable*/, const AIR_Node::S_push_unnamed_object& altr)
{
return altr.keys;
}
static
AIR_Status
execute(Executive_Context& ctx, const cow_vector<phsh_string>& keys)
{
// Pop elements from the stack and store them in an object backwards.
V_object object;
object.reserve(keys.size());
for(auto it = keys.rbegin(); it != keys.rend(); ++it) {
// Use `try_emplace()` instead of `insert_or_assign()`. In case of duplicate keys,
// the last value takes precedence.
object.try_emplace(*it, ctx.stack().back().dereference_readonly());
ctx.stack().pop_back();
}
// Push the object as a temporary.
ctx.stack().emplace_back_uninit().set_temporary(::std::move(object));
return air_status_next;
}
};
enum : uint32_t
{
tmask_null = UINT32_C(1) << type_null,
tmask_boolean = UINT32_C(1) << type_boolean,
tmask_integer = UINT32_C(1) << type_integer,
tmask_real = UINT32_C(1) << type_real,
tmask_string = UINT32_C(1) << type_string,
tmask_opaque = UINT32_C(1) << type_opaque,
tmask_function = UINT32_C(1) << type_function,
tmask_array = UINT32_C(1) << type_array,
tmask_object = UINT32_C(1) << type_object,
};
inline
uint32_t
do_tmask_of(const Value& val)
noexcept
{
return UINT32_C(1) << val.type();
}
int64_t
do_icast(double value)
{
if(!is_convertible_to_integer(value))
ASTERIA_THROW(
"Real value not representable as integer (value `$1`)",
value);
return static_cast<int64_t>(value);
}
struct AIR_Traits_apply_operator_inc_post
{
// `up` is unused.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx)
{
// This operator is unary. `assign` is ignored.
// First, get the old value.
auto& lhs = ctx.stack().back().dereference_mutable();
// Increment the value and replace the top with the old one.
switch(do_tmask_of(lhs)) {
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
auto& val = lhs.open_integer();
// Check for overflows.
if(val == INT64_MAX)
ASTERIA_THROW("Integer increment overflow");
ctx.stack().mut_back().set_temporary(val++);
return air_status_next;
}
case tmask_real: {
ROCKET_ASSERT(lhs.is_real());
auto& val = lhs.open_real();
ctx.stack().mut_back().set_temporary(val++);
return air_status_next;
}
default:
ASTERIA_THROW("Postfix increment not applicable (operand was `$1`)",
lhs);
}
}
};
struct AIR_Traits_apply_operator_dec_post
{
// `up` is unused.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx)
{
// This operator is unary. `assign` is ignored.
// First, get the old value.
auto& lhs = ctx.stack().back().dereference_mutable();
// Decrement the value and replace the top with the old one.
switch(do_tmask_of(lhs)) {
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
auto& val = lhs.open_integer();
// Check for overflows.
if(val == INT64_MIN)
ASTERIA_THROW("Integer decrement overflow");
ctx.stack().mut_back().set_temporary(val--);
return air_status_next;
}
case tmask_real: {
ROCKET_ASSERT(lhs.is_real());
auto& val = lhs.open_real();
ctx.stack().mut_back().set_temporary(val--);
return air_status_next;
}
default:
ASTERIA_THROW("Postfix decrement not applicable (operand was `$1`)",
lhs);
}
}
};
struct AIR_Traits_apply_operator_subscr
{
// `up` is unused.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
// Push a modifier depending the type of `rhs`.
switch(do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(rhs.is_integer());
ctx.stack().mut_back().push_modifier_array_index(rhs.as_integer());
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(rhs.is_string());
ctx.stack().mut_back().push_modifier_object_key(rhs.as_string());
return air_status_next;
}
default:
ASTERIA_THROW("Subscript not valid (value was `$1`)", rhs);
}
}
};
struct AIR_Traits_apply_operator_pos
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
// N.B. This is one of the few operators that work on all types.
do_get_first_operand(ctx.stack(), up.p8[0]); // assign
return air_status_next;
}
};
struct AIR_Traits_apply_operator_neg
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Get the opposite of the operand.
switch(do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(rhs.is_integer());
auto& val = rhs.open_integer();
// Check for overflows.
if(val == INT64_MIN)
ASTERIA_THROW("Integer negation overflow");
val = -val;
return air_status_next;
}
case tmask_real: {
ROCKET_ASSERT(rhs.is_real());
auto& val = rhs.open_real();
val = -val;
return air_status_next;
}
default:
ASTERIA_THROW("Prefix negation not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_notb
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Get the bitwise complement of the operand.
switch(do_tmask_of(rhs)) {
case tmask_boolean: {
ROCKET_ASSERT(rhs.is_boolean());
auto& val = rhs.open_boolean();
val = !val;
return air_status_next;
}
case tmask_integer: {
ROCKET_ASSERT(rhs.is_integer());
auto& val = rhs.open_integer();
val = ~val;
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(rhs.is_string());
auto& val = rhs.open_string();
for(auto it = val.mut_begin(); it != val.end(); ++it)
*it = static_cast<char>(~*it);
return air_status_next;
}
default:
ASTERIA_THROW("Prefix negation not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_notl
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Perform logical NOT operation on the operand.
// N.B. This is one of the few operators that work on all types.
rhs = !rhs.test();
return air_status_next;
}
};
struct AIR_Traits_apply_operator_inc_pre
{
// `up` is unused.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx)
{
// This operator is unary. `assign` is ignored.
auto& rhs = ctx.stack().back().dereference_mutable();
// Increment the value in place.
switch(do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(rhs.is_integer());
auto& val = rhs.open_integer();
// Check for overflows.
if(val == INT64_MAX)
ASTERIA_THROW("Integer increment overflow");
++val;
return air_status_next;
}
case tmask_real: {
ROCKET_ASSERT(rhs.is_real());
auto& val = rhs.open_real();
++val;
return air_status_next;
}
default:
ASTERIA_THROW("Prefix increment not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_dec_pre
{
// `up` is unused.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx)
{
// This operator is unary. `assign` is ignored.
auto& rhs = ctx.stack().back().dereference_mutable();
// Decrement the value in place.
switch(do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(rhs.is_integer());
auto& val = rhs.open_integer();
// Check for overflows.
if(val == INT64_MIN)
ASTERIA_THROW("Integer decrement overflow");
--val;
return air_status_next;
}
case tmask_real: {
ROCKET_ASSERT(rhs.is_real());
auto& val = rhs.open_real();
--val;
return air_status_next;
}
default:
ASTERIA_THROW("Prefix decrement not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_unset
{
// `up` is unused.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx)
{
// This operator is unary. `assign` is ignored.
// Unset the reference and store the result as a temporary.
auto val = ctx.stack().back().dereference_unset();
ctx.stack().mut_back().set_temporary(::std::move(val));
return air_status_next;
}
};
struct AIR_Traits_apply_operator_countof
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Get the number of bytes or elements in the operand.
switch(do_tmask_of(rhs)) {
case tmask_null: {
ROCKET_ASSERT(rhs.is_null());
rhs = 0;
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(rhs.is_string());
rhs = rhs.as_string().ssize();
return air_status_next;
}
case tmask_array: {
ROCKET_ASSERT(rhs.is_array());
rhs = rhs.as_array().ssize();
return air_status_next;
}
case tmask_object: {
ROCKET_ASSERT(rhs.is_object());
rhs = rhs.as_object().ssize();
return air_status_next;
}
default:
ASTERIA_THROW("Prefix `countof` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_typeof
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Get the type name of the operand, which is constant.
// N.B. This is one of the few operators that work on all types.
rhs = sref(rhs.what_type());
return air_status_next;
}
};
struct AIR_Traits_apply_operator_sqrt
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Get the square root of the operand as a real number.
switch(do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(rhs.is_integer());
rhs = ::std::sqrt(rhs.convert_to_real());
return air_status_next;
}
case tmask_real: {
ROCKET_ASSERT(rhs.is_real());
rhs = ::std::sqrt(rhs.as_real());
return air_status_next;
}
default:
ASTERIA_THROW("Prefix `__sqrt` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_isnan
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Check whether the operand is an arithmetic type and is a NaN.
// Note an integer is never a NaN.
switch(do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(rhs.is_integer());
rhs = false;
return air_status_next;
}
case tmask_real: {
ROCKET_ASSERT(rhs.is_real());
rhs = ::std::isnan(rhs.as_real());
return air_status_next;
}
default:
ASTERIA_THROW("Prefix `__isnan` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_isinf
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Check whether the operand is an arithmetic type and is an infinity.
// Note an integer is never an infinity.
switch(do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(rhs.is_integer());
rhs = false;
return air_status_next;
}
case tmask_real: {
ROCKET_ASSERT(rhs.is_real());
rhs = ::std::isinf(rhs.as_real());
return air_status_next;
}
default:
ASTERIA_THROW("Prefix `__isinf` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_abs
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Get the absolute value of the operand.
switch(do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(rhs.is_integer());
auto& val = rhs.open_integer();
// Check for overflows.
if(val == INT64_MIN)
ASTERIA_THROW("Integer absolute value overflow");
val = ::std::abs(val);
return air_status_next;
}
case tmask_real: {
ROCKET_ASSERT(rhs.is_real());
auto& val = rhs.open_real();
val = ::std::fabs(val);
return air_status_next;
}
default:
ASTERIA_THROW("Prefix `__abs` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_sign
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Get the sign bit of the operand and extend it to 64 bits.
switch(do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(rhs.is_integer());
rhs.open_integer() >>= 63;
return air_status_next;
}
case tmask_real: {
ROCKET_ASSERT(rhs.is_real());
rhs = ::std::signbit(rhs.as_real()) ? -1 : 0;
return air_status_next;
}
default:
ASTERIA_THROW("Prefix `__abs` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_round
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Round the operand to the nearest integer.
// This is a no-op for type `integer`.
switch(do_tmask_of(rhs)) {
case tmask_integer:
ROCKET_ASSERT(rhs.is_integer());
return air_status_next;
case tmask_real:
ROCKET_ASSERT(rhs.is_real());
rhs = ::std::round(rhs.as_real());
return air_status_next;
default:
ASTERIA_THROW("Prefix `__round` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_floor
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Round the operand to the nearest integer towards negative infinity.
// This is a no-op for type `integer`.
switch(do_tmask_of(rhs)) {
case tmask_integer:
ROCKET_ASSERT(rhs.is_integer());
return air_status_next;
case tmask_real:
ROCKET_ASSERT(rhs.is_real());
rhs = ::std::floor(rhs.as_real());
return air_status_next;
default:
ASTERIA_THROW("Prefix `__floor` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_ceil
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Round the operand to the nearest integer towards positive infinity.
// This is a no-op for type `integer`.
switch(do_tmask_of(rhs)) {
case tmask_integer:
ROCKET_ASSERT(rhs.is_integer());
return air_status_next;
case tmask_real:
ROCKET_ASSERT(rhs.is_real());
rhs = ::std::ceil(rhs.as_real());
return air_status_next;
default:
ASTERIA_THROW("Prefix `__ceil` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_trunc
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Round the operand to the nearest integer towards zero.
// This is a no-op for type `integer`.
switch(do_tmask_of(rhs)) {
case tmask_integer:
ROCKET_ASSERT(rhs.is_integer());
return air_status_next;
case tmask_real:
ROCKET_ASSERT(rhs.is_real());
rhs = ::std::trunc(rhs.as_real());
return air_status_next;
default:
ASTERIA_THROW("Prefix `__trunc` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_iround
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Round the operand to the nearest integer.
// This is a no-op for type `integer`.
switch(do_tmask_of(rhs)) {
case tmask_integer:
ROCKET_ASSERT(rhs.is_integer());
return air_status_next;
case tmask_real:
ROCKET_ASSERT(rhs.is_real());
rhs = do_icast(::std::round(rhs.as_real()));
return air_status_next;
default:
ASTERIA_THROW("Prefix `__iround` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_ifloor
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Round the operand to the nearest integer towards negative infinity.
// This is a no-op for type `integer`.
switch(do_tmask_of(rhs)) {
case tmask_integer:
ROCKET_ASSERT(rhs.is_integer());
return air_status_next;
case tmask_real:
ROCKET_ASSERT(rhs.is_real());
rhs = do_icast(::std::floor(rhs.as_real()));
return air_status_next;
default:
ASTERIA_THROW("Prefix `__ifloor` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_iceil
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Round the operand to the nearest integer towards positive infinity.
// This is a no-op for type `integer`.
switch(do_tmask_of(rhs)) {
case tmask_integer:
ROCKET_ASSERT(rhs.is_integer());
return air_status_next;
case tmask_real:
ROCKET_ASSERT(rhs.is_real());
rhs = do_icast(::std::ceil(rhs.as_real()));
return air_status_next;
default:
ASTERIA_THROW("Prefix `__iceil` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_itrunc
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is unary.
auto& rhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Round the operand to the nearest integer towards zero.
// This is a no-op for type `integer`.
switch(do_tmask_of(rhs)) {
case tmask_integer:
ROCKET_ASSERT(rhs.is_integer());
return air_status_next;
case tmask_real:
ROCKET_ASSERT(rhs.is_real());
rhs = do_icast(::std::trunc(rhs.as_real()));
return air_status_next;
default:
ASTERIA_THROW("Prefix `__itrunc` not applicable (operand was `$1`)",
rhs);
}
}
};
struct AIR_Traits_apply_operator_cmp_eq
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Check whether the two operands equal.
// Unordered operands are not equal.
// N.B. This is one of the few operators that work on all types.
lhs = lhs.compare(rhs) == compare_equal;
return air_status_next;
}
};
struct AIR_Traits_apply_operator_cmp_ne
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Check whether the two operands don't equal.
// Unordered operands are not equal.
// N.B. This is one of the few operators that work on all types.
lhs = lhs.compare(rhs) != compare_equal;
return air_status_next;
}
};
struct AIR_Traits_apply_operator_cmp_lt
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Check whether the LHS operand is less than the RHS operand.
// Throw an exception if they are unordered.
auto cmp = lhs.compare(rhs);
if(cmp == compare_unordered)
ASTERIA_THROW("Values not comparable (operands were `$1` and `$2`)",
lhs, rhs);
lhs = cmp == compare_less;
return air_status_next;
}
};
struct AIR_Traits_apply_operator_cmp_gt
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Check whether the LHS operand is greater than the RHS operand.
// Throw an exception if they are unordered.
auto cmp = lhs.compare(rhs);
if(cmp == compare_unordered)
ASTERIA_THROW("Values not comparable (operands were `$1` and `$2`)",
lhs, rhs);
lhs = cmp == compare_greater;
return air_status_next;
}
};
struct AIR_Traits_apply_operator_cmp_lte
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Check whether the LHS operand is less than or equal to the RHS operand.
// Throw an exception if they are unordered.
auto cmp = lhs.compare(rhs);
if(cmp == compare_unordered)
ASTERIA_THROW("Values not comparable (operands were `$1` and `$2`)",
lhs, rhs);
lhs = cmp != compare_greater;
return air_status_next;
}
};
struct AIR_Traits_apply_operator_cmp_gte
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Check whether the LHS operand is greater than or equal to the RHS operand.
// Throw an exception if they are unordered.
auto cmp = lhs.compare(rhs);
if(cmp == compare_unordered)
ASTERIA_THROW("Values not comparable (operands were `$1` and `$2`)",
lhs, rhs);
lhs = cmp != compare_less;
return air_status_next;
}
};
struct AIR_Traits_apply_operator_cmp_3way
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// Perform 3-way comparison on both operands.
// N.B. This is one of the few operators that work on all types.
auto cmp = lhs.compare(rhs);
switch(cmp) {
case compare_unordered:
lhs = sref("[unordered]");
return air_status_next;
case compare_less:
lhs = -1;
return air_status_next;
case compare_equal:
lhs = 0;
return air_status_next;
case compare_greater:
lhs = +1;
return air_status_next;
default:
ROCKET_ASSERT(false);
}
}
};
struct AIR_Traits_apply_operator_add
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// For the `boolean` type, perform logical OR of the operands.
// For the `integer` and `real` types, perform arithmetic addition.
// For the `string` type, concatenate them.
switch(do_tmask_of(lhs) | do_tmask_of(rhs)) {
case tmask_boolean: {
ROCKET_ASSERT(lhs.is_boolean());
ROCKET_ASSERT(rhs.is_boolean());
lhs.open_boolean() |= rhs.as_boolean();
return air_status_next;
}
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
ROCKET_ASSERT(rhs.is_integer());
auto& x = lhs.open_integer();
auto y = rhs.as_integer();
// Check for overflows.
if((y >= 0) ? (x > INT64_MAX - y) : (x < INT64_MIN - y))
ASTERIA_THROW("Integer addition overflow (operands were `$1` and `$2`)",
lhs, rhs);
x += y;
return air_status_next;
}
case tmask_real | tmask_integer:
case tmask_real: {
ROCKET_ASSERT(lhs.is_convertible_to_real());
ROCKET_ASSERT(rhs.is_convertible_to_real());
lhs.mutate_into_real() += rhs.convert_to_real();
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(lhs.is_string());
ROCKET_ASSERT(rhs.is_string());
lhs.open_string() += rhs.as_string();
return air_status_next;
}
default:
ASTERIA_THROW("Infix addition not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_sub
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// For the `boolean` type, perform logical XOR of the operands.
// For the `integer` and `real` types, perform arithmetic subtraction.
switch(do_tmask_of(lhs) | do_tmask_of(rhs)) {
case tmask_boolean: {
ROCKET_ASSERT(lhs.is_boolean());
ROCKET_ASSERT(rhs.is_boolean());
lhs.open_boolean() ^= rhs.as_boolean();
return air_status_next;
}
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
ROCKET_ASSERT(rhs.is_integer());
auto& x = lhs.open_integer();
auto y = rhs.as_integer();
// Check for overflows.
if((y >= 0) ? (x < INT64_MIN + y) : (x > INT64_MAX + y))
ASTERIA_THROW("Integer subtraction overflow (operands were `$1` and `$2`)",
lhs, rhs);
x -= y;
return air_status_next;
}
case tmask_real | tmask_integer:
case tmask_real: {
ROCKET_ASSERT(lhs.is_convertible_to_real());
ROCKET_ASSERT(rhs.is_convertible_to_real());
lhs.mutate_into_real() -= rhs.convert_to_real();
return air_status_next;
}
default:
ASTERIA_THROW("Infix subtraction not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_mul
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// For the `boolean` type, perform logical AND of the operands.
// For the `integer` and `real` types, perform arithmetic multiplication.
// If either operand is an `integer` and the other is a `string`, duplicate the string.
switch(do_tmask_of(lhs) | do_tmask_of(rhs)) {
case tmask_boolean: {
ROCKET_ASSERT(lhs.is_boolean());
ROCKET_ASSERT(rhs.is_boolean());
lhs.open_boolean() &= rhs.as_boolean();
return air_status_next;
}
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
ROCKET_ASSERT(rhs.is_integer());
auto& x = lhs.open_integer();
auto y = rhs.as_integer();
// Check for overflows.
if((x == 0) || (y == 0)) {
x = 0;
}
else if((x == INT64_MIN) || (y == INT64_MIN)) {
x = ((x ^ y) >> 63) ^ INT64_MAX;
}
else {
int64_t m = y >> 63;
int64_t s = (x ^ m) - m; // x
int64_t u = (y ^ m) - m; // abs(y)
if((s >= 0) ? (s > INT64_MAX / u) : (s < INT64_MIN / u))
ASTERIA_THROW("Integer multiplication overflow (operands were `$1` and `$2`)",
lhs, rhs);
x *= y;
}
return air_status_next;
}
case tmask_real | tmask_integer:
case tmask_real: {
ROCKET_ASSERT(lhs.is_convertible_to_real());
ROCKET_ASSERT(rhs.is_convertible_to_real());
lhs.mutate_into_real() *= rhs.convert_to_real();
return air_status_next;
}
case tmask_string | tmask_integer: {
cow_string str = ::std::move(lhs.is_string() ? lhs : rhs).as_string();
int64_t n = (lhs.is_integer() ? lhs : rhs).as_integer();
// Optimize for special cases.
if(n < 0) {
ASTERIA_THROW("Negative string duplicate count (value was `$2`)", n);
}
else if((n == 0) || str.empty()) {
str.clear();
}
else if(str.size() > str.max_size() / static_cast<uint64_t>(n)) {
ASTERIA_THROW("String length overflow (`$1` * `$2` > `$3`)",
str.size(), n, str.max_size());
}
else if(str.size() == 1) {
str.append(static_cast<size_t>(n - 1), str.front());
}
else {
size_t total = str.size();
str.append(total * static_cast<size_t>(n - 1), '*');
char* ptr = str.mut_data();
while(total <= str.size() / 2) {
::std::memcpy(ptr + total, ptr, total);
total *= 2;
}
if(total < str.size())
::std::memcpy(ptr + total, ptr, str.size() - total);
}
lhs = ::std::move(str);
return air_status_next;
}
default:
ASTERIA_THROW("Infix multiplication not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_div
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// For the `integer` and `real` types, perform arithmetic division.
switch(do_tmask_of(lhs) | do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
ROCKET_ASSERT(rhs.is_integer());
auto& x = lhs.open_integer();
auto y = rhs.as_integer();
// Check for overflows.
if(y == 0)
ASTERIA_THROW("Integer division by zero (operands were `$1` and `$2`)",
lhs, rhs);
if((x == INT64_MIN) && (y == -1))
ASTERIA_THROW("Integer division overflow (operands were `$1` and `$2`)",
lhs, rhs);
x /= y;
return air_status_next;
}
case tmask_real | tmask_integer:
case tmask_real: {
ROCKET_ASSERT(lhs.is_convertible_to_real());
ROCKET_ASSERT(rhs.is_convertible_to_real());
lhs.mutate_into_real() /= rhs.convert_to_real();
return air_status_next;
}
default:
ASTERIA_THROW("Infix division not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_mod
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// For the `integer` and `real` types, perform arithmetic modulo.
switch(do_tmask_of(lhs) | do_tmask_of(rhs)) {
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
ROCKET_ASSERT(rhs.is_integer());
auto& x = lhs.open_integer();
auto y = rhs.as_integer();
// Check for overflows.
if(y == 0)
ASTERIA_THROW("Integer division by zero (operands were `$1` and `$2`)",
lhs, rhs);
if((x == INT64_MIN) && (y == -1))
ASTERIA_THROW("Integer division overflow (operands were `$1` and `$2`)",
lhs, rhs);
x %= y;
return air_status_next;
}
case tmask_real | tmask_integer:
case tmask_real: {
ROCKET_ASSERT(lhs.is_convertible_to_real());
ROCKET_ASSERT(rhs.is_convertible_to_real());
lhs = ::std::fmod(lhs.convert_to_real(), rhs.convert_to_real());
return air_status_next;
}
default:
ASTERIA_THROW("Infix modulo not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_sll
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// The shift chount must be a non-negative integer.
if(!rhs.is_integer())
ASTERIA_THROW("Shift count not valid (operands were `$1` and `$2`)",
lhs, rhs);
int64_t n = rhs.as_integer();
if(n < 0)
ASTERIA_THROW("Negative shift count (operands were `$1` and `$2`)",
lhs, rhs);
// If the LHS operand is of type `integer`, shift the LHS operand to the left.
// Bits shifted out are discarded. Bits shifted in are filled with zeroes.
// If the LHS operand is of type `string`, fill space characters in the right
// and discard characters from the left. The number of bytes in the LHS operand
// will be preserved.
switch(do_tmask_of(lhs)) {
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
auto& val = lhs.open_integer();
if(n >= 64) {
val = 0;
}
else {
reinterpret_cast<uint64_t&>(val) <<= n;
}
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(lhs.is_string());
auto& val = lhs.open_string();
if(n >= val.ssize()) {
val.assign(val.size(), ' ');
}
else {
val.erase(0, static_cast<size_t>(n));
val.append(static_cast<size_t>(n), ' ');
}
return air_status_next;
}
default:
ASTERIA_THROW(
"Infix logical left shift not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_srl
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// The shift chount must be a non-negative integer.
if(!rhs.is_integer())
ASTERIA_THROW("Shift count not valid (operands were `$1` and `$2`)",
lhs, rhs);
int64_t n = rhs.as_integer();
if(n < 0)
ASTERIA_THROW("Negative shift count (operands were `$1` and `$2`)",
lhs, rhs);
// If the LHS operand is of type `integer`, shift the LHS operand to the right.
// Bits shifted out are discarded. Bits shifted in are filled with zeroes.
// If the LHS operand is of type `string`, fill space characters in the left
// and discard characters from the right. The number of bytes in the LHS operand
// will be preserved.
switch(do_tmask_of(lhs)) {
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
auto& val = lhs.open_integer();
if(n >= 64) {
val = 0;
}
else {
reinterpret_cast<uint64_t&>(val) >>= n;
}
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(lhs.is_string());
auto& val = lhs.open_string();
if(n >= val.ssize()) {
val.assign(val.size(), ' ');
}
else {
val.pop_back(static_cast<size_t>(n));
val.insert(0, static_cast<size_t>(n), ' ');
}
return air_status_next;
}
default:
ASTERIA_THROW(
"Infix logical right shift not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_sla
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// The shift chount must be a non-negative integer.
if(!rhs.is_integer())
ASTERIA_THROW("Shift count not valid (operands were `$1` and `$2`)",
lhs, rhs);
int64_t n = rhs.as_integer();
if(n < 0)
ASTERIA_THROW("Negative shift count (operands were `$1` and `$2`)",
lhs, rhs);
// If the LHS operand is of type `integer`, shift the LHS operand to the left.
// Bits shifted out that equal the sign bit are discarded. Bits shifted out
// that don't equal the sign bit cause an exception to be thrown. Bits shifted
// in are filled with zeroes.
// If the LHS operand is of type `string`, fill space characters in the right.
switch(do_tmask_of(lhs)) {
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
auto& val = lhs.open_integer();
if(n >= 64) {
ASTERIA_THROW("Integer left shift overflow (operands were `$1` and `$2`)",
lhs, rhs);
}
else {
int bc = static_cast<int>(63 - n);
uint64_t out = static_cast<uint64_t>(val) >> bc << bc;
uint64_t sgn = static_cast<uint64_t>(val >> 63) << bc;
if(out != sgn)
ASTERIA_THROW("Integer left shift overflow (operands were `$1` and `$2`)",
lhs, rhs);
reinterpret_cast<uint64_t&>(val) <<= n;
}
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(lhs.is_string());
auto& val = lhs.open_string();
if(n >= static_cast<int64_t>(val.max_size() - val.size())) {
ASTERIA_THROW("String length overflow (`$1` + `$2` > `$3`)",
val.size(), n, val.max_size());
}
else {
val.append(static_cast<size_t>(n), ' ');
}
return air_status_next;
}
default:
ASTERIA_THROW(
"Infix arithmetic left shift not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_sra
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// The shift chount must be a non-negative integer.
if(!rhs.is_integer())
ASTERIA_THROW("Shift count not valid (operands were `$1` and `$2`)",
lhs, rhs);
int64_t n = rhs.as_integer();
if(n < 0)
ASTERIA_THROW("Negative shift count (operands were `$1` and `$2`)",
lhs, rhs);
// If the LHS operand is of type `integer`, shift the LHS operand to the right.
// Bits shifted out are discarded. Bits shifted in are filled with the sign bit.
// If the LHS operand is of type `string`, discard characters from the right.
switch(do_tmask_of(lhs)) {
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
auto& val = lhs.open_integer();
if(n >= 64) {
val >>= 63;
}
else {
val >>= n;
}
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(lhs.is_string());
auto& val = lhs.open_string();
if(n >= val.ssize()) {
val.clear();
}
else {
val.pop_back(static_cast<size_t>(n));
}
return air_status_next;
}
default:
ASTERIA_THROW(
"Infix arithmetic right shift not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_andb
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// For the `boolean` type, perform logical AND of the operands.
// For the `integer` and `real` types, perform bitwise AND of the operands.
// For the `string` type, perform bytewise AND of the operands.
switch(do_tmask_of(lhs) | do_tmask_of(rhs)) {
case tmask_boolean: {
ROCKET_ASSERT(lhs.is_boolean());
ROCKET_ASSERT(rhs.is_boolean());
lhs.open_boolean() &= rhs.as_boolean();
return air_status_next;
}
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
ROCKET_ASSERT(rhs.is_integer());
lhs.open_integer() &= rhs.as_integer();
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(lhs.is_string());
ROCKET_ASSERT(rhs.is_string());
auto& val = lhs.open_string();
const auto& mask = rhs.as_string();
// The result is the bitwise AND of initial substrings of both operands.
size_t n = ::std::min(val.size(), mask.size());
if(n < val.size())
val.erase(n);
char* ptr = val.mut_data();
for(size_t k = 0; k != n; ++k)
ptr[k] = static_cast<char>(ptr[k] & mask[k]);
return air_status_next;
}
default:
ASTERIA_THROW("Infix bitwise AND not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_orb
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// For the `boolean` type, perform logical OR of the operands.
// For the `integer` and `real` types, perform bitwise OR of the operands.
// For the `string` type, perform bytewise OR of the operands.
switch(do_tmask_of(lhs) | do_tmask_of(rhs)) {
case tmask_boolean: {
ROCKET_ASSERT(lhs.is_boolean());
ROCKET_ASSERT(rhs.is_boolean());
lhs.open_boolean() |= rhs.as_boolean();
return air_status_next;
}
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
ROCKET_ASSERT(rhs.is_integer());
lhs.open_integer() |= rhs.as_integer();
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(lhs.is_string());
ROCKET_ASSERT(rhs.is_string());
auto& val = lhs.open_string();
const auto& mask = rhs.as_string();
// The result is the bitwise OR of both operands. Non-existent characters
// are treated as zeroes.
size_t n = ::std::min(val.size(), mask.size());
if(val.size() == n)
val.append(mask, n);
char* ptr = val.mut_data();
for(size_t k = 0; k != n; ++k)
ptr[k] = static_cast<char>(ptr[k] | mask[k]);
return air_status_next;
}
default:
ASTERIA_THROW("Infix bitwise OR not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_xorb
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is binary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// For the `boolean` type, perform logical XOR of the operands.
// For the `integer` and `real` types, perform bitwise XOR of the operands.
// For the `string` type, perform bytewise XOR of the operands.
switch(do_tmask_of(lhs) | do_tmask_of(rhs)) {
case tmask_boolean: {
ROCKET_ASSERT(lhs.is_boolean());
ROCKET_ASSERT(rhs.is_boolean());
lhs.open_boolean() ^= rhs.as_boolean();
return air_status_next;
}
case tmask_integer: {
ROCKET_ASSERT(lhs.is_integer());
ROCKET_ASSERT(rhs.is_integer());
lhs.open_integer() ^= rhs.as_integer();
return air_status_next;
}
case tmask_string: {
ROCKET_ASSERT(lhs.is_string());
ROCKET_ASSERT(rhs.is_string());
auto& val = lhs.open_string();
const auto& mask = rhs.as_string();
// The result is the bitwise XOR of both operands. Non-existent characters
// are treated as zeroes.
size_t n = ::std::min(val.size(), mask.size());
if(val.size() == n)
val.append(mask, n);
char* ptr = val.mut_data();
for(size_t k = 0; k != n; ++k)
ptr[k] = static_cast<char>(ptr[k] ^ mask[k]);
return air_status_next;
}
default:
ASTERIA_THROW("Infix bitwise XOR not applicable (operands were `$1` and `$2`)",
lhs, rhs);
}
}
};
struct AIR_Traits_apply_operator_assign
{
// `up` is unused.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx)
{
// This operator is binary. `assign` is ignored.
do_simple_assign_value_common(ctx);
return air_status_next;
}
};
struct AIR_Traits_apply_operator_fma
{
// `up` is `assign`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_apply_operator& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.assign;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// This operator is ternary.
const auto& rhs = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
const auto& mid = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
auto& lhs = do_get_first_operand(ctx.stack(), up.p8[0]); // assign
// For the `integer` and `real` types, perform fused multiply-add.
switch(do_tmask_of(lhs) | do_tmask_of(mid) | do_tmask_of(rhs)) {
case tmask_integer:
case tmask_real | tmask_integer:
case tmask_real: {
ROCKET_ASSERT(lhs.is_convertible_to_real());
ROCKET_ASSERT(mid.is_convertible_to_real());
ROCKET_ASSERT(rhs.is_convertible_to_real());
lhs = ::std::fma(lhs.convert_to_real(), mid.convert_to_real(),
rhs.convert_to_real());
return air_status_next;
}
default:
ASTERIA_THROW(
"Fused multiply-add not applicable (operands were `$1`, `$2` and `$3`)",
lhs, mid, rhs);
}
}
};
struct AIR_Traits_apply_operator_head
{
// `up` is unused.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx)
{
// This operator is binary. `assign` is ignored.
ctx.stack().mut_back().push_modifier_array_head();
return air_status_next;
}
};
struct AIR_Traits_apply_operator_tail
{
// `up` is unused.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_apply_operator& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx)
{
// This operator is binary. `assign` is ignored.
ctx.stack().mut_back().push_modifier_array_tail();
return air_status_next;
}
};
struct AIR_Traits_unpack_struct_array
{
// `up` is `immutable` and `nelems`.
// `sp` is unused.
static
const Source_Location&
get_symbols(const AIR_Node::S_unpack_struct_array& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_unpack_struct_array& altr)
{
AVMC_Queue::Uparam up;
up.s32 = altr.nelems;
up.p8[0] = altr.immutable;
return up;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up)
{
// Read the value of the initializer.
// Note that the initializer must not have been empty for this function.
auto val = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
// Make sure it is really an `array`.
V_array arr;
if(!val.is_null() && !val.is_array())
ASTERIA_THROW(
"Invalid argument for structured array binding (value was `$1`)",
val);
if(val.is_array())
arr = ::std::move(val.open_array());
for(uint32_t i = up.s32 - 1; i != UINT32_MAX; --i) {
// Get the variable back.
auto var = ctx.stack().back().get_variable_opt();
ctx.stack().pop_back();
// Initialize it.
ROCKET_ASSERT(var && !var->is_initialized());
auto qinit = arr.mut_ptr(i);
if(qinit)
var->initialize(::std::move(*qinit), up.p8[0]);
else
var->initialize(nullopt, up.p8[0]);
}
return air_status_next;
}
};
struct AIR_Traits_unpack_struct_object
{
// `up` is `immutable`.
// `sp` is the list of keys.
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_unpack_struct_object& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.immutable;
return up;
}
static
const Source_Location&
get_symbols(const AIR_Node::S_unpack_struct_object& altr)
{
return altr.sloc;
}
static
cow_vector<phsh_string>
make_sparam(bool& /*reachable*/, const AIR_Node::S_unpack_struct_object& altr)
{
return altr.keys;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const cow_vector<phsh_string>& keys)
{
// Read the value of the initializer.
// Note that the initializer must not have been empty for this function.
auto val = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
// Make sure it is really an `object`.
V_object obj;
if(!val.is_null() && !val.is_object())
ASTERIA_THROW(
"Invalid argument for structured object binding (value was `$1`)",
val);
if(val.is_object())
obj = ::std::move(val.open_object());
for(auto it = keys.rbegin(); it != keys.rend(); ++it) {
// Get the variable back.
auto var = ctx.stack().back().get_variable_opt();
ctx.stack().pop_back();
// Initialize it.
ROCKET_ASSERT(var && !var->is_initialized());
auto qinit = obj.mut_ptr(*it);
if(qinit)
var->initialize(::std::move(*qinit), up.p8[0]);
else
var->initialize(nullopt, up.p8[0]);
}
return air_status_next;
}
};
struct AIR_Traits_define_null_variable
{
// `up` is `immutable`.
// `sp` is the source location and name.
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_define_null_variable& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = altr.immutable;
return up;
}
static
const Source_Location&
get_symbols(const AIR_Node::S_define_null_variable& altr)
{
return altr.sloc;
}
static
Sparam_sloc_name
make_sparam(bool& /*reachable*/, const AIR_Node::S_define_null_variable& altr)
{
Sparam_sloc_name sp;
sp.sloc = altr.sloc;
sp.name = altr.name;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const Sparam_sloc_name& sp)
{
const auto qhooks = ctx.global().get_hooks_opt();
const auto gcoll = ctx.global().genius_collector();
// Allocate an uninitialized variable.
// Inject the variable into the current context.
const auto var = gcoll->create_variable();
ctx.open_named_reference(sp.name).set_variable(var);
if(qhooks)
qhooks->on_variable_declare(sp.sloc, sp.name);
// Initialize the variable to `null`.
var->initialize(nullopt, up.p8[0]);
return air_status_next;
}
};
struct AIR_Traits_single_step_trap
{
// `up` is unused.
// `sp` is the source location.
static
const Source_Location&
get_symbols(const AIR_Node::S_single_step_trap& altr)
{
return altr.sloc;
}
static
Source_Location
make_sparam(bool& /*reachable*/, const AIR_Node::S_single_step_trap& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx, const Source_Location& sloc)
{
const auto qhooks = ctx.global().get_hooks_opt();
if(qhooks)
qhooks->on_single_step_trap(sloc);
return air_status_next;
}
};
struct AIR_Traits_variadic_call
{
// `up` is `ptc`.
// `sp` is the source location.
static
const Source_Location&
get_symbols(const AIR_Node::S_variadic_call& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_variadic_call& altr)
{
AVMC_Queue::Uparam up;
up.p8[0] = static_cast<uint8_t>(altr.ptc);
return up;
}
static
Source_Location
make_sparam(bool& /*reachable*/, const AIR_Node::S_variadic_call& altr)
{
return altr.sloc;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const Source_Location& sloc)
{
const auto sentry = ctx.global().copy_recursion_sentry();
const auto qhooks = ctx.global().get_hooks_opt();
// Generate a single-step trap before the call.
if(qhooks)
qhooks->on_single_step_trap(sloc);
// Initialize arguments.
auto& alt_stack = ctx.alt_stack();
alt_stack.clear();
auto value = ctx.stack().back().dereference_readonly();
switch(weaken_enum(value.type())) {
case type_null:
// Leave `stack` empty.
break;
case type_array: {
auto& vals = value.open_array();
// Push all arguments backwards as temporaries.
for(auto it = vals.mut_rbegin(); it != vals.rend(); ++it) {
alt_stack.emplace_back_uninit().set_temporary(::std::move(*it));
}
break;
}
case type_function: {
const auto gfunc = ::std::move(value.open_function());
// Pass an empty argument stack to get the number of arguments to generate.
// This destroys the `self` reference so we have to copy it first.
ctx.stack().mut_back().pop_modifier();
auto self = ctx.stack().back();
ctx.stack().emplace_back_uninit() = self;
do_invoke_nontail(ctx.stack().mut_back(), sloc, ctx, gfunc, ::std::move(alt_stack));
value = ctx.stack().back().dereference_readonly();
ctx.stack().pop_back();
// Verify the argument count.
if(!value.is_integer())
ASTERIA_THROW("Invalid number of variadic arguments (value `$1`)", value);
int64_t nvargs = value.as_integer();
if((nvargs < 0) || (nvargs > INT32_MAX))
ASTERIA_THROW("Number of variadic arguments not acceptable (value `$1`)",
nvargs);
// Prepare `self` references for all upcoming calls.
for(int64_t k = 0; k < nvargs; ++k)
ctx.stack().emplace_back_uninit() = self;
// Generate arguments and push them onto `ctx.stack()`.
// The top is the first argument.
for(int64_t k = 0; k < nvargs; ++k) {
// Initialize arguments for the generator function.
alt_stack.clear();
alt_stack.emplace_back_uninit().set_temporary(k);
// Generate an argument. Ensure it is dereferenceable.
auto& arg = ctx.stack().mut_back(static_cast<size_t>(k));
do_invoke_nontail(arg, sloc, ctx, gfunc, ::std::move(alt_stack));
arg.dereference_readonly();
}
// Pop arguments and re-push them into the alternative stack.
// This reverses all arguments so the top will be the last argument.
alt_stack.clear();
for(int64_t k = 0; k < nvargs; ++k) {
alt_stack.emplace_back_uninit() = ::std::move(ctx.stack().mut_back());
ctx.stack().pop_back();
}
break;
}
default:
ASTERIA_THROW("Invalid variadic argument generator (value `$1`)", value);
}
ctx.stack().pop_back();
// Copy the target, which shall be of type `function`.
value = ctx.stack().back().dereference_readonly();
if(!value.is_function())
ASTERIA_THROW("Attempt to call a non-function (value `$1`)", value);
return do_function_call_common(ctx.stack().mut_back().pop_modifier(), sloc, ctx,
value.as_function(), static_cast<PTC_Aware>(up.p8[0]),
::std::move(alt_stack));
}
};
struct AIR_Traits_defer_expression
{
// `up` is unused.
// `sp` is the source location and body.
static
const Source_Location&
get_symbols(const AIR_Node::S_defer_expression& altr)
{
return altr.sloc;
}
static
Sparam_defer
make_sparam(bool& /*reachable*/, const AIR_Node::S_defer_expression& altr)
{
Sparam_defer sp;
sp.sloc = altr.sloc;
sp.code_body = altr.code_body;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, const Sparam_defer& sp)
{
// Rebind the body here.
bool dirty = false;
auto bound_body = sp.code_body;
do_rebind_nodes(dirty, bound_body, ctx);
// Solidify it.
AVMC_Queue queue;
do_solidify_nodes(queue, bound_body);
// Push this expression.
ctx.defer_expression(sp.sloc, ::std::move(queue));
return air_status_next;
}
};
struct AIR_Traits_import_call
{
// `up` is `nargs`.
// `sp` is the source location and compiler options.
static
const Source_Location&
get_symbols(const AIR_Node::S_import_call& altr)
{
return altr.sloc;
}
static
AVMC_Queue::Uparam
make_uparam(bool& /*reachable*/, const AIR_Node::S_import_call& altr)
{
AVMC_Queue::Uparam up;
up.s32 = altr.nargs;
return up;
}
static
Sparam_import
make_sparam(bool& /*reachable*/, const AIR_Node::S_import_call& altr)
{
Sparam_import sp;
sp.opts = altr.opts;
sp.sloc = altr.sloc;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, AVMC_Queue::Uparam up, const Sparam_import& sp)
{
const auto sentry = ctx.global().copy_recursion_sentry();
const auto qhooks = ctx.global().get_hooks_opt();
// Generate a single-step trap before the call.
if(qhooks)
qhooks->on_single_step_trap(sp.sloc);
// Pop arguments off the stack backwards.
ROCKET_ASSERT(up.s32 != 0);
auto& alt_stack = do_pop_positional_arguments_into_alt_stack(ctx, up.s32 - 1);
// Copy the filename, which shall be of type `string`.
auto value = ctx.stack().back().dereference_readonly();
if(!value.is_string())
ASTERIA_THROW("Invalid path specified for `import` (value `$1` not a string)",
value);
auto path = value.as_string();
if(path.empty())
ASTERIA_THROW("Empty path specified for `import`");
// Rewrite the path if it is not absolute.
if((path[0] != '/') && (sp.sloc.c_file()[0] == '/')) {
path.assign(sp.sloc.file());
path.erase(path.rfind('/') + 1);
path.append(value.as_string());
}
auto abspath = ::rocket::make_unique_handle(
::realpath(path.safe_c_str(), nullptr), ::free);
if(!abspath)
ASTERIA_THROW("Could not open script file '$2'\n"
"[`realpath()` failed: $1]",
format_errno(errno), path);
// Update the first argument to `import` if it was passed by reference.
path.assign(abspath);
auto& self = ctx.stack().mut_back();
if(self.is_variable())
self.dereference_mutable() = path;
// Compile the script file into a function object.
Loader_Lock::Unique_Stream strm;
strm.reset(ctx.global().loader_lock(), path.safe_c_str());
// Parse source code.
Token_Stream tstrm(sp.opts);
tstrm.reload(path, 1, strm);
Statement_Sequence stmtq(sp.opts);
stmtq.reload(tstrm);
// Instantiate the function.
const Source_Location sloc(path, 0, 0);
const cow_vector<phsh_string> params(1, sref("..."));
AIR_Optimizer optmz(sp.opts);
optmz.reload(nullptr, params, stmtq);
auto qtarget = optmz.create_function(sloc, sref("[file scope]"));
// Invoke the script.
// `this` is null for imported scripts.
self.set_temporary(nullopt);
do_invoke_nontail(self, sp.sloc, ctx, qtarget, ::std::move(alt_stack));
return air_status_next;
}
};
struct AIR_Traits_declare_reference
{
// `up` is unused.
// `sp` is the name;
static
Sparam_name
make_sparam(bool& /*reachable*/, const AIR_Node::S_declare_reference& altr)
{
Sparam_name sp;
sp.name = altr.name;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, const Sparam_name& sp)
{
ctx.open_named_reference(sp.name).set_uninit();
return air_status_next;
}
};
struct AIR_Traits_initialize_reference
{
// `up` is unused.
// `sp` is the name;
static
const Source_Location&
get_symbols(const AIR_Node::S_initialize_reference& altr)
{
return altr.sloc;
}
static
Sparam_name
make_sparam(bool& /*reachable*/, const AIR_Node::S_initialize_reference& altr)
{
Sparam_name sp;
sp.name = altr.name;
return sp;
}
static
AIR_Status
execute(Executive_Context& ctx, const Sparam_name& sp)
{
// Pop a reference from the stack. Ensure it is dereferenceable.
auto& top = ctx.stack().mut_back();
top.dereference_readonly();
// Move it into the context.
ctx.open_named_reference(sp.name) = ::std::move(top);
ctx.stack().pop_back();
return air_status_next;
}
};
// Finally...
template<typename TraitsT, typename NodeT, typename = void>
struct symbol_getter
{
static constexpr
const Source_Location*
opt(const NodeT&)
noexcept
{ return nullptr; }
};
template<typename TraitsT, typename NodeT>
struct symbol_getter<TraitsT, NodeT,
ROCKET_VOID_T(decltype(
TraitsT::get_symbols(
::std::declval<const NodeT&>())))>
{
static constexpr
const Source_Location*
opt(const NodeT& altr)
noexcept
{ return ::std::addressof(TraitsT::get_symbols(altr)); }
};
template<typename TraitsT, typename NodeT, typename = void>
struct has_uparam
: ::std::false_type
{ };
template<typename TraitsT, typename NodeT>
struct has_uparam<TraitsT, NodeT,
ROCKET_VOID_T(decltype(
TraitsT::make_uparam(::std::declval<bool&>(),
::std::declval<const NodeT&>())))>
: ::std::true_type
{ };
template<typename TraitsT, typename NodeT, typename = void>
struct has_sparam
: ::std::false_type
{ };
template<typename TraitsT, typename NodeT>
struct has_sparam<TraitsT, NodeT,
ROCKET_VOID_T(decltype(
TraitsT::make_sparam(::std::declval<bool&>(),
::std::declval<const NodeT&>())))>
: ::std::true_type
{ };
template<typename TraitsT, typename NodeT, bool, bool>
struct solidify_disp;
template<typename TraitsT, typename NodeT>
struct solidify_disp<TraitsT, NodeT, true, true> // uparam, sparam
{
ROCKET_FLATTEN_FUNCTION
static
AIR_Status
thunk(Executive_Context& ctx, const AVMC_Queue::Header* head)
{
return TraitsT::execute(ctx,
static_cast<typename ::std::decay<decltype(
TraitsT::make_uparam(::std::declval<bool&>(),
::std::declval<const NodeT&>()))>::type>(head->uparam),
reinterpret_cast<const typename ::std::decay<decltype(
TraitsT::make_sparam(::std::declval<bool&>(),
::std::declval<const NodeT&>()))>::type&>(head->sparam));
}
static
void
append(bool& reachable, AVMC_Queue& queue, const NodeT& altr)
{
queue.append(thunk, symbol_getter<TraitsT, NodeT>::opt(altr),
TraitsT::make_uparam(reachable, altr),
TraitsT::make_sparam(reachable, altr));
}
};
template<typename TraitsT, typename NodeT>
struct solidify_disp<TraitsT, NodeT, false, true> // uparam, sparam
{
ROCKET_FLATTEN_FUNCTION
static
AIR_Status
thunk(Executive_Context& ctx, const AVMC_Queue::Header* head)
{
return TraitsT::execute(ctx,
reinterpret_cast<const typename ::std::decay<decltype(
TraitsT::make_sparam(::std::declval<bool&>(),
::std::declval<const NodeT&>()))>::type&>(head->sparam));
}
static
void
append(bool& reachable, AVMC_Queue& queue, const NodeT& altr)
{
queue.append(thunk, symbol_getter<TraitsT, NodeT>::opt(altr),
TraitsT::make_sparam(reachable, altr));
}
};
template<typename TraitsT, typename NodeT>
struct solidify_disp<TraitsT, NodeT, true, false> // uparam, sparam
{
ROCKET_FLATTEN_FUNCTION
static
AIR_Status
thunk(Executive_Context& ctx, const AVMC_Queue::Header* head)
{
return TraitsT::execute(ctx,
static_cast<typename ::std::decay<decltype(
TraitsT::make_uparam(::std::declval<bool&>(),
::std::declval<const NodeT&>()))>::type>(head->uparam));
}
static
void
append(bool& reachable, AVMC_Queue& queue, const NodeT& altr)
{
queue.append(thunk, symbol_getter<TraitsT, NodeT>::opt(altr),
TraitsT::make_uparam(reachable, altr));
}
};
template<typename TraitsT, typename NodeT>
struct solidify_disp<TraitsT, NodeT, false, false> // uparam, sparam
{
ROCKET_FLATTEN_FUNCTION
static
AIR_Status
thunk(Executive_Context& ctx, const AVMC_Queue::Header* /*head*/)
{
return TraitsT::execute(ctx);
}
static
void
append(bool& /*reachable*/, AVMC_Queue& queue, const NodeT& altr)
{
queue.append(thunk, symbol_getter<TraitsT, NodeT>::opt(altr));
}
};
template<typename TraitsT, typename NodeT>
inline
bool
do_solidify(AVMC_Queue& queue, const NodeT& altr)
{
using disp = solidify_disp<TraitsT, NodeT,
has_uparam<TraitsT, NodeT>::value,
has_sparam<TraitsT, NodeT>::value>;
bool reachable = true;
disp::append(reachable, queue, altr);
return reachable;
}
} // namespace
opt<AIR_Node>
AIR_Node::
rebind_opt(Abstract_Context& ctx)
const
{
switch(this->index()) {
case index_clear_stack:
// There is nothing to rebind.
return nullopt;
case index_execute_block: {
const auto& altr = this->m_stor.as<index_execute_block>();
// Rebind the body.
Analytic_Context ctx_body(Analytic_Context::M_plain(), ctx);
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_body, ctx_body);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_declare_variable:
case index_initialize_variable:
// There is nothing to rebind.
return nullopt;
case index_if_statement: {
const auto& altr = this->m_stor.as<index_if_statement>();
// Rebind both branches.
Analytic_Context ctx_body(Analytic_Context::M_plain(), ctx);
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_true, ctx_body);
do_rebind_nodes(dirty, bound.code_false, ctx_body);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_switch_statement: {
const auto& altr = this->m_stor.as<index_switch_statement>();
// Rebind all clauses.
Analytic_Context ctx_body(Analytic_Context::M_plain(), ctx);
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_labels, ctx); // this is not part of the body!
do_rebind_nodes(dirty, bound.code_bodies, ctx_body);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_do_while_statement: {
const auto& altr = this->m_stor.as<index_do_while_statement>();
// Rebind the body and the condition.
Analytic_Context ctx_body(Analytic_Context::M_plain(), ctx);
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_body, ctx_body);
do_rebind_nodes(dirty, bound.code_cond, ctx); // this is not part of the body!
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_while_statement: {
const auto& altr = this->m_stor.as<index_while_statement>();
// Rebind the condition and the body.
Analytic_Context ctx_body(Analytic_Context::M_plain(), ctx);
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_cond, ctx); // this is not part of the body!
do_rebind_nodes(dirty, bound.code_body, ctx_body);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_for_each_statement: {
const auto& altr = this->m_stor.as<index_for_each_statement>();
// Rebind the range initializer and the body.
Analytic_Context ctx_for(Analytic_Context::M_plain(), ctx);
Analytic_Context ctx_body(Analytic_Context::M_plain(), ctx_for);
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_init, ctx_for);
do_rebind_nodes(dirty, bound.code_body, ctx_body);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_for_statement: {
const auto& altr = this->m_stor.as<index_for_statement>();
// Rebind the initializer, the condition, the loop increment and the body.
Analytic_Context ctx_for(Analytic_Context::M_plain(), ctx);
Analytic_Context ctx_body(Analytic_Context::M_plain(), ctx_for);
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_init, ctx_for);
do_rebind_nodes(dirty, bound.code_cond, ctx_for);
do_rebind_nodes(dirty, bound.code_step, ctx_for);
do_rebind_nodes(dirty, bound.code_body, ctx_body);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_try_statement: {
const auto& altr = this->m_stor.as<index_try_statement>();
// Rebind the `try` and `catch` clauses.
Analytic_Context ctx_body(Analytic_Context::M_plain(), ctx);
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_try, ctx_body);
do_rebind_nodes(dirty, bound.code_catch, ctx_body);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_throw_statement:
case index_assert_statement:
case index_simple_status:
case index_convert_to_temporary:
case index_push_global_reference:
// There is nothing to rebind.
return nullopt;
case index_push_local_reference: {
const auto& altr = this->m_stor.as<index_push_local_reference>();
// Get the context.
// Don't bind references in analytic contexts.
Abstract_Context* qctx = &ctx;
for(uint32_t k = 0; k != altr.depth; ++k) {
qctx = qctx->get_parent_opt();
ROCKET_ASSERT(qctx);
}
if(qctx->is_analytic())
return nullopt;
// Look for the name in the context.
auto qref = qctx->get_named_reference_opt(altr.name);
if(!qref)
return nullopt;
// Bind it now.
S_push_bound_reference xnode = { *qref };
return ::std::move(xnode);
}
case index_push_bound_reference:
// There is nothing to rebind.
return nullopt;
case index_define_function: {
const auto& altr = this->m_stor.as<index_define_function>();
// Rebind the function body.
Analytic_Context ctx_func(Analytic_Context::M_function(),
&ctx, altr.params);
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_body, ctx_func);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_branch_expression: {
const auto& altr = this->m_stor.as<index_branch_expression>();
// Rebind the expression.
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_true, ctx);
do_rebind_nodes(dirty, bound.code_false, ctx);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_coalescence: {
const auto& altr = this->m_stor.as<index_coalescence>();
// Rebind the expression.
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_null, ctx);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_function_call:
case index_member_access:
case index_push_unnamed_array:
case index_push_unnamed_object:
case index_apply_operator:
case index_unpack_struct_array:
case index_unpack_struct_object:
case index_define_null_variable:
case index_single_step_trap:
case index_variadic_call:
// There is nothing to rebind.
return nullopt;
case index_defer_expression: {
const auto& altr = this->m_stor.as<index_defer_expression>();
// Rebind the expression.
bool dirty = false;
auto bound = altr;
do_rebind_nodes(dirty, bound.code_body, ctx);
return do_rebind_return_opt(dirty, ::std::move(bound));
}
case index_import_call:
case index_declare_reference:
case index_initialize_reference:
// There is nothing to rebind.
return nullopt;
default:
ASTERIA_TERMINATE("invalid AIR node type (index `$1`)", this->index());
}
}
bool
AIR_Node::
solidify(AVMC_Queue& queue)
const
{
switch(this->index()) {
case index_clear_stack:
return do_solidify<AIR_Traits_clear_stack>(queue,
this->m_stor.as<index_clear_stack>());
case index_execute_block:
return do_solidify<AIR_Traits_execute_block>(queue,
this->m_stor.as<index_execute_block>());
case index_declare_variable:
return do_solidify<AIR_Traits_declare_variable>(queue,
this->m_stor.as<index_declare_variable>());
case index_initialize_variable:
return do_solidify<AIR_Traits_initialize_variable>(queue,
this->m_stor.as<index_initialize_variable>());
case index_if_statement:
return do_solidify<AIR_Traits_if_statement>(queue,
this->m_stor.as<index_if_statement>());
case index_switch_statement:
return do_solidify<AIR_Traits_switch_statement>(queue,
this->m_stor.as<index_switch_statement>());
case index_do_while_statement:
return do_solidify<AIR_Traits_do_while_statement>(queue,
this->m_stor.as<index_do_while_statement>());
case index_while_statement:
return do_solidify<AIR_Traits_while_statement>(queue,
this->m_stor.as<index_while_statement>());
case index_for_each_statement:
return do_solidify<AIR_Traits_for_each_statement>(queue,
this->m_stor.as<index_for_each_statement>());
case index_for_statement:
return do_solidify<AIR_Traits_for_statement>(queue,
this->m_stor.as<index_for_statement>());
case index_try_statement:
return do_solidify<AIR_Traits_try_statement>(queue,
this->m_stor.as<index_try_statement>());
case index_throw_statement:
return do_solidify<AIR_Traits_throw_statement>(queue,
this->m_stor.as<index_throw_statement>());
case index_assert_statement:
return do_solidify<AIR_Traits_assert_statement>(queue,
this->m_stor.as<index_assert_statement>());
case index_simple_status:
return do_solidify<AIR_Traits_simple_status>(queue,
this->m_stor.as<index_simple_status>());
case index_convert_to_temporary:
return do_solidify<AIR_Traits_convert_to_temporary>(queue,
this->m_stor.as<index_convert_to_temporary>());
case index_push_global_reference:
return do_solidify<AIR_Traits_push_global_reference>(queue,
this->m_stor.as<index_push_global_reference>());
case index_push_local_reference:
return do_solidify<AIR_Traits_push_local_reference>(queue,
this->m_stor.as<index_push_local_reference>());
case index_push_bound_reference:
return do_solidify<AIR_Traits_push_bound_reference>(queue,
this->m_stor.as<index_push_bound_reference>());
case index_define_function:
return do_solidify<AIR_Traits_define_function>(queue,
this->m_stor.as<index_define_function>());
case index_branch_expression:
return do_solidify<AIR_Traits_branch_expression>(queue,
this->m_stor.as<index_branch_expression>());
case index_coalescence:
return do_solidify<AIR_Traits_coalescence>(queue,
this->m_stor.as<index_coalescence>());
case index_function_call:
return do_solidify<AIR_Traits_function_call>(queue,
this->m_stor.as<index_function_call>());
case index_member_access:
return do_solidify<AIR_Traits_member_access>(queue,
this->m_stor.as<index_member_access>());
case index_push_unnamed_array:
return do_solidify<AIR_Traits_push_unnamed_array>(queue,
this->m_stor.as<index_push_unnamed_array>());
case index_push_unnamed_object:
return do_solidify<AIR_Traits_push_unnamed_object>(queue,
this->m_stor.as<index_push_unnamed_object>());
case index_apply_operator: {
const auto& altr = this->m_stor.as<index_apply_operator>();
switch(altr.xop) {
case xop_inc_post:
return do_solidify<AIR_Traits_apply_operator_inc_post>(queue, altr);
case xop_dec_post:
return do_solidify<AIR_Traits_apply_operator_dec_post>(queue, altr);
case xop_subscr:
return do_solidify<AIR_Traits_apply_operator_subscr>(queue, altr);
case xop_pos:
return do_solidify<AIR_Traits_apply_operator_pos>(queue, altr);
case xop_neg:
return do_solidify<AIR_Traits_apply_operator_neg>(queue, altr);
case xop_notb:
return do_solidify<AIR_Traits_apply_operator_notb>(queue, altr);
case xop_notl:
return do_solidify<AIR_Traits_apply_operator_notl>(queue, altr);
case xop_inc_pre:
return do_solidify<AIR_Traits_apply_operator_inc_pre>(queue, altr);
case xop_dec_pre:
return do_solidify<AIR_Traits_apply_operator_dec_pre>(queue, altr);
case xop_unset:
return do_solidify<AIR_Traits_apply_operator_unset>(queue, altr);
case xop_countof:
return do_solidify<AIR_Traits_apply_operator_countof>(queue, altr);
case xop_typeof:
return do_solidify<AIR_Traits_apply_operator_typeof>(queue, altr);
case xop_sqrt:
return do_solidify<AIR_Traits_apply_operator_sqrt>(queue, altr);
case xop_isnan:
return do_solidify<AIR_Traits_apply_operator_isnan>(queue, altr);
case xop_isinf:
return do_solidify<AIR_Traits_apply_operator_isinf>(queue, altr);
case xop_abs:
return do_solidify<AIR_Traits_apply_operator_abs>(queue, altr);
case xop_sign:
return do_solidify<AIR_Traits_apply_operator_sign>(queue, altr);
case xop_round:
return do_solidify<AIR_Traits_apply_operator_round>(queue, altr);
case xop_floor:
return do_solidify<AIR_Traits_apply_operator_floor>(queue, altr);
case xop_ceil:
return do_solidify<AIR_Traits_apply_operator_ceil>(queue, altr);
case xop_trunc:
return do_solidify<AIR_Traits_apply_operator_trunc>(queue, altr);
case xop_iround:
return do_solidify<AIR_Traits_apply_operator_iround>(queue, altr);
case xop_ifloor:
return do_solidify<AIR_Traits_apply_operator_ifloor>(queue, altr);
case xop_iceil:
return do_solidify<AIR_Traits_apply_operator_iceil>(queue, altr);
case xop_itrunc:
return do_solidify<AIR_Traits_apply_operator_itrunc>(queue, altr);
case xop_cmp_eq:
return do_solidify<AIR_Traits_apply_operator_cmp_eq>(queue, altr);
case xop_cmp_ne:
return do_solidify<AIR_Traits_apply_operator_cmp_ne>(queue, altr);
case xop_cmp_lt:
return do_solidify<AIR_Traits_apply_operator_cmp_lt>(queue, altr);
case xop_cmp_gt:
return do_solidify<AIR_Traits_apply_operator_cmp_gt>(queue, altr);
case xop_cmp_lte:
return do_solidify<AIR_Traits_apply_operator_cmp_lte>(queue, altr);
case xop_cmp_gte:
return do_solidify<AIR_Traits_apply_operator_cmp_gte>(queue, altr);
case xop_cmp_3way:
return do_solidify<AIR_Traits_apply_operator_cmp_3way>(queue, altr);
case xop_add:
return do_solidify<AIR_Traits_apply_operator_add>(queue, altr);
case xop_sub:
return do_solidify<AIR_Traits_apply_operator_sub>(queue, altr);
case xop_mul:
return do_solidify<AIR_Traits_apply_operator_mul>(queue, altr);
case xop_div:
return do_solidify<AIR_Traits_apply_operator_div>(queue, altr);
case xop_mod:
return do_solidify<AIR_Traits_apply_operator_mod>(queue, altr);
case xop_sll:
return do_solidify<AIR_Traits_apply_operator_sll>(queue, altr);
case xop_srl:
return do_solidify<AIR_Traits_apply_operator_srl>(queue, altr);
case xop_sla:
return do_solidify<AIR_Traits_apply_operator_sla>(queue, altr);
case xop_sra:
return do_solidify<AIR_Traits_apply_operator_sra>(queue, altr);
case xop_andb:
return do_solidify<AIR_Traits_apply_operator_andb>(queue, altr);
case xop_orb:
return do_solidify<AIR_Traits_apply_operator_orb>(queue, altr);
case xop_xorb:
return do_solidify<AIR_Traits_apply_operator_xorb>(queue, altr);
case xop_assign:
return do_solidify<AIR_Traits_apply_operator_assign>(queue, altr);
case xop_fma:
return do_solidify<AIR_Traits_apply_operator_fma>(queue, altr);
case xop_head:
return do_solidify<AIR_Traits_apply_operator_head>(queue, altr);
case xop_tail:
return do_solidify<AIR_Traits_apply_operator_tail>(queue, altr);
default:
ASTERIA_TERMINATE("invalid operator type (xop `$1`)", altr.xop);
}
}
case index_unpack_struct_array:
return do_solidify<AIR_Traits_unpack_struct_array>(queue,
this->m_stor.as<index_unpack_struct_array>());
case index_unpack_struct_object:
return do_solidify<AIR_Traits_unpack_struct_object>(queue,
this->m_stor.as<index_unpack_struct_object>());
case index_define_null_variable:
return do_solidify<AIR_Traits_define_null_variable>(queue,
this->m_stor.as<index_define_null_variable>());
case index_single_step_trap:
return do_solidify<AIR_Traits_single_step_trap>(queue,
this->m_stor.as<index_single_step_trap>());
case index_variadic_call:
return do_solidify<AIR_Traits_variadic_call>(queue,
this->m_stor.as<index_variadic_call>());
case index_defer_expression:
return do_solidify<AIR_Traits_defer_expression>(queue,
this->m_stor.as<index_defer_expression>());
case index_import_call:
return do_solidify<AIR_Traits_import_call>(queue,
this->m_stor.as<index_import_call>());
case index_declare_reference:
return do_solidify<AIR_Traits_declare_reference>(queue,
this->m_stor.as<index_declare_reference>());
case index_initialize_reference:
return do_solidify<AIR_Traits_initialize_reference>(queue,
this->m_stor.as<index_initialize_reference>());
default:
ASTERIA_TERMINATE("invalid AIR node type (index `$1`)", this->index());
}
}
Variable_Callback&
AIR_Node::
enumerate_variables(Variable_Callback& callback)
const
{
switch(this->index()) {
case index_clear_stack:
return callback;
case index_execute_block: {
const auto& altr = this->m_stor.as<index_execute_block>();
::rocket::for_each(altr.code_body, callback);
return callback;
}
case index_declare_variable:
case index_initialize_variable:
return callback;
case index_if_statement: {
const auto& altr = this->m_stor.as<index_if_statement>();
::rocket::for_each(altr.code_true, callback);
::rocket::for_each(altr.code_false, callback);
return callback;
}
case index_switch_statement: {
const auto& altr = this->m_stor.as<index_switch_statement>();
for(size_t i = 0; i < altr.code_labels.size(); ++i) {
::rocket::for_each(altr.code_labels.at(i), callback);
::rocket::for_each(altr.code_bodies.at(i), callback);
}
return callback;
}
case index_do_while_statement: {
const auto& altr = this->m_stor.as<index_do_while_statement>();
::rocket::for_each(altr.code_body, callback);
::rocket::for_each(altr.code_cond, callback);
return callback;
}
case index_while_statement: {
const auto& altr = this->m_stor.as<index_while_statement>();
::rocket::for_each(altr.code_cond, callback);
::rocket::for_each(altr.code_body, callback);
return callback;
}
case index_for_each_statement: {
const auto& altr = this->m_stor.as<index_for_each_statement>();
::rocket::for_each(altr.code_init, callback);
::rocket::for_each(altr.code_body, callback);
return callback;
}
case index_for_statement: {
const auto& altr = this->m_stor.as<index_for_statement>();
::rocket::for_each(altr.code_init, callback);
::rocket::for_each(altr.code_cond, callback);
::rocket::for_each(altr.code_step, callback);
::rocket::for_each(altr.code_body, callback);
return callback;
}
case index_try_statement: {
const auto& altr = this->m_stor.as<index_try_statement>();
::rocket::for_each(altr.code_try, callback);
::rocket::for_each(altr.code_catch, callback);
return callback;
}
case index_throw_statement:
case index_assert_statement:
case index_simple_status:
case index_convert_to_temporary:
case index_push_global_reference:
case index_push_local_reference:
return callback;
case index_push_bound_reference: {
const auto& altr = this->m_stor.as<index_push_bound_reference>();
altr.ref.enumerate_variables(callback);
return callback;
}
case index_define_function: {
const auto& altr = this->m_stor.as<index_define_function>();
::rocket::for_each(altr.code_body, callback);
return callback;
}
case index_branch_expression: {
const auto& altr = this->m_stor.as<index_branch_expression>();
::rocket::for_each(altr.code_true, callback);
::rocket::for_each(altr.code_false, callback);
return callback;
}
case index_coalescence: {
const auto& altr = this->m_stor.as<index_coalescence>();
::rocket::for_each(altr.code_null, callback);
return callback;
}
case index_function_call:
case index_member_access:
case index_push_unnamed_array:
case index_push_unnamed_object:
case index_apply_operator:
case index_unpack_struct_array:
case index_unpack_struct_object:
case index_define_null_variable:
case index_single_step_trap:
case index_variadic_call:
return callback;
case index_defer_expression: {
const auto& altr = this->m_stor.as<index_defer_expression>();
::rocket::for_each(altr.code_body, callback);
return callback;
}
case index_import_call:
case index_declare_reference:
case index_initialize_reference:
return callback;
default:
ASTERIA_TERMINATE("invalid AIR node type (index `$1`)", this->index());
}
}
} // namespace asteria
| 29.044457 | 97 | 0.583443 | [
"object"
] |
925bb7d2ae5c98e980eee3120021be3cc6cb5f4b | 2,874 | cpp | C++ | DeviceController/main.cpp | ktonchev/HOLOTWIN | 6918be4649c94ac720a771bc3fc8c9aafc0f471b | [
"Apache-2.0"
] | null | null | null | DeviceController/main.cpp | ktonchev/HOLOTWIN | 6918be4649c94ac720a771bc3fc8c9aafc0f471b | [
"Apache-2.0"
] | null | null | null | DeviceController/main.cpp | ktonchev/HOLOTWIN | 6918be4649c94ac720a771bc3fc8c9aafc0f471b | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <iostream>
#include <vector>
#include "MQTTAsync.h"
#include "msgReader.h"
#include "msgWriter.h"
#include "processRequest.h"
#include "databank.hpp"
#include "StreamClient.hpp"
#include "connection.hpp"
#include <thread>
#if !defined(_WIN32)
#include <unistd.h>
#else
#include <windows.h>
#endif
#if defined(_WRS_KERNEL)
#include <OsWrapper.h>
#endif
std::string &clientId = *get_clientIdPtr();
dataBank &db = *get_dbPtr();
StreamClient client;
unsigned int arr[4][4];
//Function that reads the client ID and topic from the input stream and saves them into the parameter variables
void inputParams() {
std::cout << "Please enter client ID\n";
std::cin >> clientId;
}
void serializeArray(char* buf, int& size, unsigned int *arr) {
unsigned int dims[2] = { 4,4 };
Encoder dataenc;
dataenc.Reset(buf);
}
void _stream() {
uint32_t val = 0;
int rc = db.getDataPairById(2, val);
while (1) {
rc = db.getDataPairById(2, val);
if (!rc && val > 500) {
client.SendData(const_cast<unsigned char*>((const unsigned char*)"data"), 3, true);
}
Sleep(5000);
}
}
void initArray() {
for(int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++) {
arr[i][j] = j;
}
}
}
int main(int argc, char* argv[]) {
initArray();
int rc = 0;
//Declaring 2 data pairs for testing
dataPair dp1(1, 101, GETTABLE);
dataPair dp2(2, 102, BOTH);
//Adding datapairs to dataBank
db.addDataPair(dp1);
db.addDataPair(dp2);
//Reading user input for client ID and topic
//inputParams();
clientId = "dc1";
InitMQTT_dc(ADDRESS);
//Wait while session is formed
while (!get_connected());
//Subscribe to own topic
std::cout << "Waiting for subscribtion\n";
subscribe_dc(clientId);
//Wait until the client is subscribed
while (!get_subscribed());
//Timestamp
const auto p1 = std::chrono::system_clock::now();
//Constructing a "New DC connected message"
msgstruct alert;
alert.msgType = 3;
alert.timestamp = std::chrono::duration_cast<std::chrono::seconds>(p1.time_since_epoch()).count();
alert.token = 1;
alert.newDeviceId = clientId;
//Publishing the message on the raise topic
sendMsg(alert,"raise");
//Init StreamClient
std::string message;
client.Init(const_cast<char*>("127.0.0.1"), const_cast<char*>("23"), const_cast<char*>("client"));
std::thread* _SendThread;
_SendThread = new std::thread(_stream);
//Wait for requests
std::cout << "Press 'q' to quit\n";
char c;
while (1) {
std::cin >> c;
if (c == 'q') {
break;
}
else {
}
}
if (get_connected()) {
disconnect();//Disconnect the client from the MQTT broker
}
DeinitMQTT();
client.~StreamClient();
return rc;
}
| 19.55102 | 113 | 0.630828 | [
"vector"
] |
925c45faef3856666bd595d5df002d7035844108 | 10,804 | cpp | C++ | src/tests/v8test.cpp | Barenboim/nativejson-benchmark | 5c13c515443ac885b1b315a452345bbd1937052e | [
"MIT"
] | 1,721 | 2015-03-25T02:21:25.000Z | 2022-03-30T18:01:01.000Z | src/tests/v8test.cpp | Barenboim/nativejson-benchmark | 5c13c515443ac885b1b315a452345bbd1937052e | [
"MIT"
] | 72 | 2015-04-16T03:35:22.000Z | 2021-11-27T19:25:52.000Z | src/tests/v8test.cpp | Barenboim/nativejson-benchmark | 5c13c515443ac885b1b315a452345bbd1937052e | [
"MIT"
] | 305 | 2015-01-30T16:16:54.000Z | 2022-02-21T10:54:22.000Z | #include "../test.h"
#if HAS_V8
#include "libplatform/libplatform.h"
#include "v8.h"
using namespace v8;
// Note: V8 does not support custom allocator for all allocation.
// Use Isolate::GetHeapStatistics() for memory statistics.
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
virtual void* Allocate(size_t length) {
void* data = AllocateUninitialized(length);
return data == NULL ? data : memset(data, 0, length);
}
virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
virtual void Free(void* data, size_t) { free(data); }
};
static void GenStat(Stat& stat, Local<Value> v) {
// Array must be appear earlier than Object, because array inherits from object in V8.
if (v->IsArray()) {
Local<Array> a = Local<Array>::Cast(v);
for (uint32_t i = 0; i < a->Length(); i++)
GenStat(stat, a->Get(i));
stat.arrayCount++;
stat.elementCount += a->Length();
}
else if (v->IsObject()) {
Local<Object> o = Local<Object>::Cast(v);
Local<Array> p = o->GetOwnPropertyNames();
for (uint32_t i = 0; i < p->Length(); i++) {
Local<Value> k = p->Get(i);
Local<String> key = Local<String>::Cast(k);
Local<Value> value = o->Get(key);
GenStat(stat, value);
// Keys in V8 can be non-string, so explicitly convert the key to string.
Local<String> keyString = key->ToString();
stat.stringLength += keyString->Length();
}
stat.objectCount++;
stat.memberCount += p->Length();
stat.stringCount += p->Length();
}
else if (v->IsString()) {
Local<String> s = Local<String>::Cast(v);
stat.stringCount++;
stat.stringLength += s->Length();
}
else if (v->IsNumber())
stat.numberCount++;
else if (v->IsTrue())
stat.trueCount++;
else if (v->IsFalse())
stat.falseCount++;
else if (v->IsNull())
stat.nullCount++;
}
class V8ParseResult : public ParseResultBase {
public:
V8ParseResult() : heapUsage() {}
~V8ParseResult() {
root.Reset();
#if USE_MEMORYSTAT
Memory::Instance().FreeStat(heapUsage);
#endif
}
Persistent<Value> root;
size_t heapUsage;
};
class V8StringResult : public StringResultBase {
public:
V8StringResult() : heapUsage() {}
~V8StringResult() {
#if USE_MEMORYSTAT
Memory::Instance().FreeStat(heapUsage);
#endif
}
virtual const char* c_str() const { return s.c_str(); }
std::string s;
size_t heapUsage;
};
class V8Test : public TestBase {
public:
V8Test() {
V8::InitializeICU();
V8::InitializeExternalStartupData("");
platform = platform::CreateDefaultPlatform();
V8::InitializePlatform(platform);
V8::Initialize();
}
~V8Test() {
V8::Dispose();
V8::ShutdownPlatform();
delete platform;
}
virtual void SetUp() const {
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = &allocator;
isolate = Isolate::New(create_params);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
context_.Reset(isolate, Context::New(isolate));
}
virtual void TearDown() const {
context_.Reset();
isolate->Dispose();
}
#if TEST_INFO
virtual const char* GetName() const { return "V8 (C++)"; }
virtual const char* GetFilename() const { return __FILE__; }
#endif
#if TEST_PARSE
virtual ParseResultBase* Parse(const char* json, size_t length) const {
HandleScope handle_scope(isolate);
Local<Context> context = Local<Context>::New(isolate, context_);
Context::Scope context_scope(context);
Isolate::Scope isolate_scope(isolate);
#if USE_MEMORYSTAT
HeapStatistics hs;
isolate->GetHeapStatistics(&hs);
#endif
Local<Object> global = context->Global();
Local<Object> JSON = Local<Object>::Cast(global->Get(context, String::NewFromUtf8(isolate, "JSON")).ToLocalChecked());
Local<Function> parse = Local<Function>::Cast(JSON->Get(context, String::NewFromUtf8(isolate, "parse")).ToLocalChecked());
Local<Value> argv[1] = { String::NewFromUtf8(isolate, json, NewStringType::kNormal, length).ToLocalChecked() };
MaybeLocal<Value> result = parse->Call(context, global, 1, argv);
if (!result.IsEmpty()) {
V8ParseResult* pr = new V8ParseResult;
pr->root.Reset(isolate, result.ToLocalChecked());
#if USE_MEMORYSTAT
HeapStatistics hs2;
isolate->GetHeapStatistics(&hs2);
pr->heapUsage = hs2.used_heap_size() - hs.used_heap_size();
Memory::Instance().MallocStat(pr->heapUsage);
#endif
return pr;
}
else
return 0;
}
#endif
#if TEST_STRINGIFY
virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const {
const V8ParseResult* pr = static_cast<const V8ParseResult*>(parseResult);
HandleScope handle_scope(isolate);
Local<Context> context = Local<Context>::New(isolate, context_);
Context::Scope context_scope(context);
Isolate::Scope isolate_scope(isolate);
#if USE_MEMORYSTAT
HeapStatistics hs;
isolate->GetHeapStatistics(&hs);
#endif
Local<Object> global = context->Global();
Local<Object> JSON = Local<Object>::Cast(global->Get(context, String::NewFromUtf8(isolate, "JSON")).ToLocalChecked());
Local<Function> parse = Local<Function>::Cast(JSON->Get(context, String::NewFromUtf8(isolate, "stringify")).ToLocalChecked());
Local<Value> argv[1] = { Local<Value>::New(isolate, pr->root) };
MaybeLocal<Value> result = parse->Call(context, global, 1, argv);
if (!result.IsEmpty()) {
V8StringResult* sr = new V8StringResult;
#if USE_MEMORYSTAT
HeapStatistics hs2;
isolate->GetHeapStatistics(&hs2);
sr->heapUsage = hs2.used_heap_size() - hs.used_heap_size();
Memory::Instance().MallocStat(sr->heapUsage);
#endif
String::Utf8Value u(result.ToLocalChecked());
sr->s = std::string(*u, u.length());
return sr;
}
else
return 0;
}
#endif
#if TEST_PRETTIFY
virtual StringResultBase* Prettify(const ParseResultBase* parseResult) const {
const V8ParseResult* pr = static_cast<const V8ParseResult*>(parseResult);
HandleScope handle_scope(isolate);
Local<Context> context = Local<Context>::New(isolate, context_);
Context::Scope context_scope(context);
Isolate::Scope isolate_scope(isolate);
#if USE_MEMORYSTAT
HeapStatistics hs;
isolate->GetHeapStatistics(&hs);
#endif
Local<Object> global = context->Global();
Local<Object> JSON = Local<Object>::Cast(global->Get(context, String::NewFromUtf8(isolate, "JSON")).ToLocalChecked());
Local<Function> parse = Local<Function>::Cast(JSON->Get(context, String::NewFromUtf8(isolate, "stringify")).ToLocalChecked());
Local<Value> argv[3] = { Local<Value>::New(isolate, pr->root), Null(isolate), Integer::New(isolate, 4) };
MaybeLocal<Value> result = parse->Call(context, global, 3, argv);
if (!result.IsEmpty()) {
V8StringResult* sr = new V8StringResult;
#if USE_MEMORYSTAT
HeapStatistics hs2;
isolate->GetHeapStatistics(&hs2);
sr->heapUsage = hs2.used_heap_size() - hs.used_heap_size();
Memory::Instance().MallocStat(sr->heapUsage);
#endif
String::Utf8Value u(result.ToLocalChecked());
sr->s = std::string(*u, u.length());
return sr;
}
else
return 0;
}
#endif
#if TEST_STATISTICS
virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const {
HandleScope handle_scope(isolate);
Local<Context> context = Local<Context>::New(isolate, context_);
Context::Scope context_scope(context);
Isolate::Scope isolate_scope(isolate);
const V8ParseResult* pr = static_cast<const V8ParseResult*>(parseResult);
memset(stat, 0, sizeof(Stat));
GenStat(*stat, Local<Value>::New(isolate, pr->root));
return true;
}
#endif
#if TEST_CONFORMANCE
virtual bool ParseDouble(const char* json, double* d) const {
HandleScope handle_scope(isolate);
Local<Context> context = Local<Context>::New(isolate, context_);
Context::Scope context_scope(context);
Isolate::Scope isolate_scope(isolate);
Local<Object> global = context->Global();
Local<Object> JSON = Local<Object>::Cast(global->Get(context, String::NewFromUtf8(isolate, "JSON")).ToLocalChecked());
Local<Function> parse = Local<Function>::Cast(JSON->Get(context, String::NewFromUtf8(isolate, "parse")).ToLocalChecked());
Local<Value> argv[1] = { String::NewFromUtf8(isolate, json, NewStringType::kNormal).ToLocalChecked() };
MaybeLocal<Value> result = parse->Call(context, global, 1, argv);
if (!result.IsEmpty()) {
Local<Array> a = Local<Array>::Cast(result.ToLocalChecked());
Local<Number> n = Local<Number>::Cast(a->Get(0));
*d = n->Value();
return true;
}
else
return false;
}
virtual bool ParseString(const char* json, std::string& s) const {
HandleScope handle_scope(isolate);
Local<Context> context = Local<Context>::New(isolate, context_);
Context::Scope context_scope(context);
Isolate::Scope isolate_scope(isolate);
Local<Object> global = context->Global();
Local<Object> JSON = Local<Object>::Cast(global->Get(context, String::NewFromUtf8(isolate, "JSON")).ToLocalChecked());
Local<Function> parse = Local<Function>::Cast(JSON->Get(context, String::NewFromUtf8(isolate, "parse")).ToLocalChecked());
Local<Value> argv[1] = { String::NewFromUtf8(isolate, json, NewStringType::kNormal).ToLocalChecked() };
MaybeLocal<Value> result = parse->Call(context, global, 1, argv);
if (!result.IsEmpty()) {
Local<Array> a = Local<Array>::Cast(result.ToLocalChecked());
String::Utf8Value u(Local<String>::Cast(a->Get(0)));
s = std::string(*u, u.length());
return true;
}
else
return false;
}
#endif
Platform* platform;
mutable ArrayBufferAllocator allocator;
mutable Isolate* isolate;
mutable Persistent<Context> context_;
};
REGISTER_TEST(V8Test);
#endif
| 35.893688 | 134 | 0.622177 | [
"object"
] |
177f5cbd3d67851366baf81ad993b03ab1179508 | 8,189 | cpp | C++ | src/main/renderer/Curve2D.cpp | SamuelGauthier/iphito | 83cbcc9037965f5722aa39e7a7c13f0677264ff3 | [
"Unlicense"
] | null | null | null | src/main/renderer/Curve2D.cpp | SamuelGauthier/iphito | 83cbcc9037965f5722aa39e7a7c13f0677264ff3 | [
"Unlicense"
] | null | null | null | src/main/renderer/Curve2D.cpp | SamuelGauthier/iphito | 83cbcc9037965f5722aa39e7a7c13f0677264ff3 | [
"Unlicense"
] | null | null | null | /**
* @file Curve2D.cpp
* @brief Implements a 2D parametric curve
* @author Samuel Gauthier
* @version 0.1.0
* @date 2018-12-10
*/
#include <iostream>
#include <sstream>
#include "Curve2D.h"
#include "utils/Logger.h"
#include "utils/Utils.h"
namespace iphito::renderer {
using namespace iphito::math;
using namespace iphito::utils;
inline std::atomic<unsigned long long> Curve2D::nextID = 0;
inline std::mt19937_64 Curve2D::engine = std::mt19937_64();
inline std::uniform_real_distribution<double> Curve2D::distribution(0.0, 1.0);
Curve2D::Curve2D(std::shared_ptr<Curve> curve, double curveWidth,
const Eigen::Vector3d& curveColor,
const Eigen::Matrix3d& transform) :
curve{curve}, curveWidth{curveWidth/2.0}, curveColor{curveColor},
isDirty{true}, viewMatrixUpdate{true}, projectionMatrixUpdate{true},
id{this->nextID.fetch_add(1)}, samplePoints{std::vector<Eigen::Vector2d>()},
model{Eigen::Matrix4d::Identity()}, view{Eigen::Matrix4d::Identity()},
projection{Eigen::Matrix4d::Identity()} {
if(!Utils::isGlfwInitialized())
throw std::runtime_error("Please initialize GLFW.");
if(!Utils::isGlewInitialized())
throw std::runtime_error("Please initialize Glew.");
this->shader.reset(new Shader("../src/shaders/basic.vert",
"../src/shaders/basic.frag"));
this->shader->useProgram();
int curveColorLocation = glGetUniformLocation(this->shader->getProgramID(),
"color");
glUniform3f(curveColorLocation, this->curveColor[0], this->curveColor[1],
this->curveColor[2]);
glGenVertexArrays(1, &this->vertexArrayObjectID);
glBindVertexArray(this->vertexArrayObjectID);
glGenBuffers(1, &this->vertexBufferID);
glGenBuffers(1, &this->indexBufferID);
}
void Curve2D::recomputeVerticesAndIndices() {
this->vertices = std::vector<GLfloat>();
this->indices = std::vector<GLuint>();
this->samplePoints = std::vector<Eigen::Vector2d>();
sampleCurve(0.0, 1.0);
verticesFromSamplePoints(this->samplePoints);
indicesFromVertices();
glBindVertexArray(this->vertexArrayObjectID);
glBindBuffer(GL_ARRAY_BUFFER, this->vertexBufferID);
glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(GLfloat),
&this->vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->indexBufferID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint),
&this->indices[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(0);
this->isDirty = false;
}
unsigned long long Curve2D::getID() {
return this->id;
}
void Curve2D::sampleCurve(double a, double b) {
double t = 0.45 + 0.1 * Curve2D::distribution(Curve2D::engine);
double m = a + t * (b - a);
Eigen::Vector4d pa3D;
Eigen::Vector4d pb3D;
Eigen::Vector4d pm3D;
pa3D << this->curve->evaluateAt(a), 1.0, 0.0;
pb3D << this->curve->evaluateAt(b), 1.0, 0.0;
pm3D << this->curve->evaluateAt(m), 1.0, 0.0;
Eigen::Vector2d pa;
Eigen::Vector2d pb;
Eigen::Vector2d pm;
pa << pa3D[0], pa3D[1];
pb << pb3D[0], pb3D[1];
pm << pm3D[0], pm3D[1];
pa3D = this->projection * this->view * this->model * pa3D;
pb3D = this->projection * this->view * this->model * pb3D;
pm3D = this->projection * this->view * this->model * pm3D;
Eigen::Vector2d paScreen;
Eigen::Vector2d pbScreen;
Eigen::Vector2d pmScreen;
paScreen << pa3D[0], pa3D[1];
pbScreen << pb3D[0], pb3D[1];
pmScreen << pm3D[0], pm3D[1];
if(isFlat(paScreen, pbScreen, pmScreen)) {
if(!samplePoints.empty()) {
Eigen::Vector2d back = this->samplePoints.back();
if(!(Utils::nearlyEqual(back[0], pa[0]) &&
Utils::nearlyEqual(back[1], pa[1]))) {
this->samplePoints.push_back(pa);
this->samplePoints.push_back(pb);
}
else {
this->samplePoints.push_back(pb);
}
}
else {
this->samplePoints.push_back(pa);
this->samplePoints.push_back(pb);
}
}
else{
sampleCurve(a, m);
sampleCurve(m, b);
}
}
bool Curve2D::isFlat(Eigen::Vector2d a, Eigen::Vector2d b, Eigen::Vector2d m) {
Eigen::Vector2d ma = a - m;
Eigen::Vector2d mb = b - m;
if (ma.isApprox(Eigen::Vector2d::Zero()) ||
mb.isApprox(Eigen::Vector2d::Zero())) {
return true;
}
return std::abs(ma.dot(mb) / (ma.norm() * mb.norm())) > 0.999;
}
void Curve2D::verticesFromSamplePoints(std::vector<Eigen::Vector2d>&
samplePoints) {
if(samplePoints.size() == 0 ) return;
Eigen::Vector2d a = samplePoints[0];
Eigen::Vector2d b = samplePoints[1];
Eigen::Vector2d d = b-a;
std::swap(d[0], d[1]);
d[0] *= -1;
d.normalize();
Eigen::Vector2d a1 = a + (this->curveWidth * d);
Eigen::Vector2d a2 = a - (this->curveWidth * d);
this->vertices.push_back(a1[0]);
this->vertices.push_back(a1[1]);
this->vertices.push_back(a2[0]);
this->vertices.push_back(a2[1]);
for (int i = 0; i < samplePoints.size() - 2; i++) {
Eigen::Vector2d a = samplePoints[i];
Eigen::Vector2d b = samplePoints[i+1];
Eigen::Vector2d c = samplePoints[i+2];
Eigen::Vector2d v1 = (b-a);
Eigen::Vector2d v2 = (c-b);
v1.normalize();
v2.normalize();
Eigen::Vector2d d1 = v1;
std::swap(d1[0], d1[1]);
d1[0] *= -1;
d1.normalize();
Eigen::Vector2d d2 = v2;
std::swap(d2[0], d2[1]);
d2[0] *= -1;
d2.normalize();
Eigen::Vector2d b1 = b + (this->curveWidth * d1);
Eigen::Vector2d b2 = b - (this->curveWidth * d1);
Eigen::Vector2d c1 = b + (this->curveWidth * d2);
Eigen::Vector2d c2 = b - (this->curveWidth * d2);
double det1 = v1[0]*v2[1] - v1[1]*v2[0];
double det2 = v1[0]*b1[1] - v1[1]*b1[0];
double det3 = c1[0]*v1[1] - c1[1]*v1[0];
Eigen::Vector2d i1;
if(det1 > 0.00001 || det1 < -0.00001)
i1 = c1 + (det2 + det3) / det1 * v1;
else i1 = b1;
det1 = v1[0]*v2[1] - v1[1]*v2[0];
det2 = v1[0]*b2[1] - v1[1]*b2[0];
det3 = c2[0]*v1[1] - c2[1]*v1[0];
Eigen::Vector2d i2;
if(det1 > 0.00001 || det1 < -0.00001)
i2 = c2 + (det2 + det3) / det1 * v1;
else i2 = b2;
this->vertices.push_back(i1[0]);
this->vertices.push_back(i1[1]);
this->vertices.push_back(i2[0]);
this->vertices.push_back(i2[1]);
}
a = samplePoints[samplePoints.size() - 2];
b = samplePoints[samplePoints.size() - 1];
d = b-a;
std::swap(d[0], d[1]);
d[0] *= -1;
d.normalize();
Eigen::Vector2d b1 = b + (this->curveWidth * d);
Eigen::Vector2d b2 = b - (this->curveWidth * d);
this->vertices.push_back(b1[0]);
this->vertices.push_back(b1[1]);
this->vertices.push_back(b2[0]);
this->vertices.push_back(b2[1]);
}
void Curve2D::indicesFromVertices() {
int size = this->vertices.size()/4;
for (int i = 0, j = 0; j < size - 1; i += 2, j++) {
this->indices.push_back(i);
this->indices.push_back(i+1);
this->indices.push_back(i+2);
this->indices.push_back(i+1);
this->indices.push_back(i+3);
this->indices.push_back(i+2);
}
}
void Curve2D::updateSamplePoints(Eigen::Matrix3d& transform) {
for (int i = 0; i < this->samplePoints.size(); i++) {
Eigen::Vector2d originalPoint = this->samplePoints[i];
}
}
void Curve2D::updateModelMatrix(const Eigen::Matrix4d& model) {
this->model = model;
}
void Curve2D::updateViewMatrix(const Eigen::Matrix4d& view) {
this->view = view;
this->viewMatrixUpdate = true;
}
void Curve2D::updateProjectionMatrix(const Eigen::Matrix4d& projection) {
this->projection = projection;
this->projectionMatrixUpdate = true;
this->isDirty = true;
}
} /* namespace iphito::renderer */
| 29.456835 | 80 | 0.594944 | [
"vector",
"model",
"transform"
] |
17806fcd8701885be199842d1dcc8e7725957e26 | 5,403 | cxx | C++ | dune/gdt/test/hyperbolic/eocexpectations-fv-burgers-1dyaspgrid.cxx | TiKeil/dune-gdt | 25c8b987cc07a4b8b966c1a07ea21b78dba7852f | [
"BSD-2-Clause"
] | null | null | null | dune/gdt/test/hyperbolic/eocexpectations-fv-burgers-1dyaspgrid.cxx | TiKeil/dune-gdt | 25c8b987cc07a4b8b966c1a07ea21b78dba7852f | [
"BSD-2-Clause"
] | null | null | null | dune/gdt/test/hyperbolic/eocexpectations-fv-burgers-1dyaspgrid.cxx | TiKeil/dune-gdt | 25c8b987cc07a4b8b966c1a07ea21b78dba7852f | [
"BSD-2-Clause"
] | null | null | null | // This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2016 - 2017)
// Rene Milk (2016 - 2018)
// Tobias Leibner (2016 - 2017)
#include "config.h"
#include "eocexpectations-fv-burgers-1dyaspgrid.hh"
namespace Dune {
namespace GDT {
namespace Test {
std::vector<double> HyperbolicEocExpectations<Hyperbolic::BurgersTestCase<Yasp1, double, 1>,
Hyperbolic::ChooseDiscretizer::fv,
1,
NumericalFluxes::godunov,
TimeStepperMethods::explicit_euler,
TimeStepperMethods::explicit_euler>::
results(const HyperbolicEocExpectations<Hyperbolic::BurgersTestCase<Yasp1, double, 1>,
Hyperbolic::ChooseDiscretizer::fv,
1,
NumericalFluxes::godunov,
TimeStepperMethods::explicit_euler,
TimeStepperMethods::explicit_euler>::TestCaseType& test_case,
const std::string type)
{
if (type == "L1") {
if (test_case.num_refinements() == 1) {
if (Dune::XT::Common::FloatCmp::eq(test_case.t_end(), 1.0))
return {8.96e-02, 3.87e-02};
else if (Dune::XT::Common::FloatCmp::eq(test_case.t_end(), 1.0 / 5.0))
return {1.35e-02, 6.37e-03};
else
EXPECT_TRUE(false) << "test results missing for t_end = " << Dune::XT::Common::to_string(test_case.t_end());
} else {
return {1.14e-01, 6.19e-02, 2.89e-02, 1.25e-02, 4.82e-03};
}
} else
EXPECT_TRUE(false) << "test results missing for type: " << type;
return {};
}
std::vector<double> HyperbolicEocExpectations<Hyperbolic::BurgersTestCase<Yasp1, double, 1>,
Hyperbolic::ChooseDiscretizer::fv,
1,
NumericalFluxes::godunov,
TimeStepperMethods::dormand_prince,
TimeStepperMethods::dormand_prince>::
results(const HyperbolicEocExpectations<Hyperbolic::BurgersTestCase<Yasp1, double, 1>,
Hyperbolic::ChooseDiscretizer::fv,
1,
NumericalFluxes::godunov,
TimeStepperMethods::dormand_prince,
TimeStepperMethods::dormand_prince>::TestCaseType& test_case,
const std::string type)
{
if (type == "L1") {
if (test_case.num_refinements() == 1) {
if (Dune::XT::Common::FloatCmp::eq(test_case.t_end(), 1.0))
return {8.64e-02, 3.72e-02};
else if (Dune::XT::Common::FloatCmp::eq(test_case.t_end(), 1.0 / 5.0))
return {1.35e-02, 6.36e-03};
else
EXPECT_TRUE(false) << "test results missing for t_end = " << Dune::XT::Common::to_string(test_case.t_end());
} else {
return {1.15e-01, 6.50e-02, 3.31e-02, 1.52e-02, 5.68e-03};
}
} else
EXPECT_TRUE(false) << "test results missing for type: " << type;
return {};
}
std::vector<double> HyperbolicEocExpectations<Hyperbolic::BurgersTestCase<Yasp1, double, 1>,
Hyperbolic::ChooseDiscretizer::fv,
1,
NumericalFluxes::laxfriedrichs,
TimeStepperMethods::explicit_euler,
TimeStepperMethods::explicit_euler>::
results(const HyperbolicEocExpectations<Hyperbolic::BurgersTestCase<Yasp1, double, 1>,
Hyperbolic::ChooseDiscretizer::fv,
1,
NumericalFluxes::laxfriedrichs,
TimeStepperMethods::explicit_euler,
TimeStepperMethods::explicit_euler>::TestCaseType& test_case,
const std::string type)
{
if (type == "L1") {
if (test_case.num_refinements() == 1)
if (Dune::XT::Common::FloatCmp::eq(test_case.t_end(), 1.0))
return {1.03e-01, 5.58e-02};
else if (Dune::XT::Common::FloatCmp::eq(test_case.t_end(), 1.0 / 5.0))
return {1.73e-02, 7.67e-03};
else
EXPECT_TRUE(false) << "test results missing for t_end = " << Dune::XT::Common::to_string(test_case.t_end());
else
return {1.77e-01, 1.30e-01, 7.80e-02, 3.85e-02, 1.41e-02};
} else
EXPECT_TRUE(false) << "test results missing for type: " << type;
return {};
}
} // namespace Test
} // namespace GDT
} // namespace Dune
| 48.241071 | 116 | 0.513789 | [
"vector"
] |
1785dd7752bac2ce52b21a3ea2b49d20628d5f3a | 8,204 | cxx | C++ | StRoot/StFmsHitMaker/StFmsHitMaker.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StFmsHitMaker/StFmsHitMaker.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StFmsHitMaker/StFmsHitMaker.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | // ROOT
#include "TFile.h"
#include "TH1.h"
#include "TH2.h"
#include "TTree.h"
#include "StMessMgr.h"
#include "StEventTypes.h"
#include "StMuDSTMaker/COMMON/StMuTypes.hh"
#include "StMuDSTMaker/COMMON/StMuFmsUtil.h"
#include "StFmsDbMaker/StFmsDbMaker.h"
#include "StFmsCollection.h"
#include "StFmsHit.h"
#include "StFmsHitMaker.h"
#include "StTriggerData2009.h"
// PSU-FMS package
//#include "StFmsPointMaker/StFmsClusterFitter.h"
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
ClassImp(StFmsHitMaker);
StFmsHitMaker::StFmsHitMaker(const char* name) : StMaker(name) {
mFmsDbMaker = NULL;
mFmsCollection = NULL;
mMuFmsColl = NULL;
LOG_DEBUG << "StFmsHitMaker::constructor." << endm;
}
StFmsHitMaker::~StFmsHitMaker(){
LOG_DEBUG << "StFmsHitMaker::destructor." << endm;
}
void StFmsHitMaker::Clear(Option_t* option){
LOG_DEBUG << "StFmsHitMaker::Clear()" << endm;
StMaker::Clear(option);
}
int StFmsHitMaker::Init() {
LOG_DEBUG<<"StFmsHitMaker::Init() "<<endm;
return StMaker::Init();
}
int StFmsHitMaker::InitRun(Int_t runNumber) {
LOG_INFO << "StFmsHitMaker::InitRun --run# changed to " << runNumber << endm;
mFmsDbMaker = static_cast<StFmsDbMaker*>(GetMaker("fmsDb"));
if(!mFmsDbMaker){
LOG_ERROR << "StFmsHitMaker::InitRun Failed to get StFmsDbMaker" << endm;
return kStFatal;
}
mCurrentRunNumber = runNumber; //called by maker's method :InitRun(run); when the run# changes
return kStOK;
}
//// This is StFmsHitMaker Make, it reads in data and make hit and fill StFmsCollection
int StFmsHitMaker::Make(){
LOG_DEBUG<<"StFmsHitMaker::Make start"<<endm;
int flag = 0;
StTriggerData* triggerData = 0;
Float_t mCurrentEventNumber=0;
if(mReadMuDst>0) return readMuDst();
//first try to get StTriggerData from StTriggerDataMaker (works for proudction) and create StFmsCollection
TObjectSet *os = (TObjectSet*)GetDataSet("StTriggerData");
if (os) {
triggerData = (StTriggerData*)os->GetObject();
if(triggerData){
flag=1;
mCurrentEventNumber=triggerData->eventNumber();
// mFmsCollection = new StFmsCollection();
LOG_DEBUG<<"StFmsHitMaker::Make Found StTriggerData from StTriggerDataMaker"<<endm;
}
}
//2nd try to get StTriggerData from StEvent
//but once FMS data is killed in StEvent, this will not work and all you see is empty data
StEvent* stEvent = (StEvent*) GetInputDS("StEvent");
if(flag==0){
if(stEvent){
mCurrentEventNumber=stEvent->id();
triggerData = stEvent->triggerData();
if(triggerData) {
flag=2;
LOG_DEBUG<<"StFmsHitMaker::Make Found StTriggerData from StEvent"<<endm;
}
else{
mFmsCollection = stEvent->fmsCollection();
if(mFmsCollection){
flag=3;
LOG_DEBUG<<"StFmsHitMaker::Make Found StFmsCollection from StEvent"<<endm;
}
}
} //found StEvent
}
//3rd try to get StTriggerData from StMuEvent, works for produced data (.MuDst.root) --Yuxi
StMuDst* muDst = (StMuDst*)GetInputDS("MuDst");
if(flag==0){
if(muDst && muDst->event()){
mCurrentRunNumber = muDst->event()->runNumber();
mCurrentEventNumber = muDst->event()->eventNumber();
triggerData = (StTriggerData*)StMuDst::event()->triggerData();
if(triggerData){
flag = 4; //Yuxi
LOG_DEBUG<<"StFmsHitMaker::Make Found StFmsTriggerData in MuDst"<<endm;
}
else LOG_ERROR << "Finally, no StFmsTriggerData in MuDst " <<endm;
}
}
LOG_DEBUG<<"Flag="<<flag<<" (0=Not found, 1=StTriggerDataMaker, 2=StEvent, 3=FmsCollection 4=Mudst)"<<endm;
//after this step triggerData is pointing to StTriggerData block of StEvent
if(flag>0){
mFmsCollection = new StFmsCollection();
//create StFmsHit and add it to StFmsCollection
for(unsigned short crt=1; crt<=4; crt++){
for(unsigned short slot=1; slot<=16; slot++){
for(unsigned short ch=0; ch<32; ch++){
unsigned short adc=0;
unsigned short tdc=0;
if(flag<=4 && triggerData){ //wont work when flag=3
adc=triggerData->fmsADC(crt,slot-1,ch);
tdc=triggerData->fmsTDC(crt,slot-1,ch);
}
if(adc>0 || tdc>0){
// LOG_INFO<<"adc of crt "<<crt<<", slot "<<slot<<", channel "<<ch<<" is: "<<adc<<endm;
// LOG_INFO<<"tdc=====================================================is: "<<tdc<<endm;
StFmsHit* hit = new StFmsHit();
if(!hit){
LOG_ERROR <<"Failed to create FMS hit, skip this hit."<<endm;
continue;
}
hit->setDetectorId(0);
hit->setChannel(0);
hit->setQtCrate(crt);
hit->setQtSlot(slot);
hit->setQtChannel(ch);
hit->setAdc(adc);
hit->setTdc(tdc);
hit->setEnergy(0.0);
mFmsCollection->addHit(hit);
if(GetDebug()>0) hit->print();
}
}
}
}
/// Read DB and put DetectorId, channeel and apply Calibration to get Energy
for(unsigned int i=0; i<mFmsCollection->numberOfHits(); i++){
int d,c;
StFmsHit* fmsHit = (mFmsCollection->hits())[i];
int crt =fmsHit->qtCrate();
int slot =fmsHit->qtSlot();
int ch =fmsHit->qtChannel();
unsigned short adc =fmsHit->adc();
mFmsDbMaker->getReverseMap(crt,slot,ch,&d,&c);
float e=0.0;
if(d>0 || c>0){
//unsigned short rawadc=adc;
short bitshift=0;
if(mCorrectAdcOffByOne){
bitshift = mFmsDbMaker->getBitShiftGain(d,c);
if(bitshift>0){
int check=adc % (1<<bitshift);
if(check!=0){
LOG_ERROR << Form("Bitshift in DB is not consistent with data! det=%2d ch=%3d adc=%4d bitshift=%2d adc%(1<<bitshift)=%d",
d,c,adc,bitshift,check) << endm;
}
}else if(bitshift<0){
int check=adc / (1<< (12+bitshift));
if(check!=0){
LOG_ERROR << Form("Bitshift in DB is not consistent with data! det=%2d ch=%3d adc=%4d bitshift=%2d adc/(1<<(12+bitshift))=%d",
d,c,adc,bitshift,check) << endm;
}
}
//Leaving ADC value in StFmsHit as it was recorded, so that when we read from MuDST, we don't double correct!!!!
// if(bitshift>=0) {
// adc += (0x1<<bitshift);
// fmsHit->setAdc(adc);
// }
//LOG_INFO << Form("RawADC=%4d NewADC=%4d Bitshift=%d",rawadc,adc,bitshift) << endm;
}
float g1=mFmsDbMaker->getGain(d,c);
float g2=mFmsDbMaker->getGainCorrection(d,c);
float gt=1.0;
if(mTimeDepCorr==1){ // time dep. Correction
gt = mFmsDbMaker->getTimeDepCorr(mCurrentEventNumber,d-8,c);
if(gt<0){
if(mTowerRej==1){
gt = 0; // making -ve(tower to be rej) to zero
}else{
gt = -gt; // making +ve : doing time dep corr. for all towers
}
}
// cout<<d<<" "<<ch<<" "<<gt<<endl;
}
if(mCorrectAdcOffByOne){
e=(adc+pow(2.0,bitshift))*g1*g2*gt;
}else{
e=adc*g1*g2*gt;
}
}
fmsHit->setDetectorId(d);
fmsHit->setChannel(c);
fmsHit->setEnergy(e);
if(GetDebug()>0) fmsHit->print();
}
LOG_INFO<<"StFmsHitMaker::Make(): flag = "<<flag<<", got "<<mFmsCollection->numberOfHits()<<" hits in StFmsCollection"<<endm;
}else{
LOG_INFO<<"StFmsHitMaker::Make(): flag = "<<flag<<", no StTrigger data found"<<endm;
}
if(stEvent) {
//Adding StFmsCollection to StEvent
LOG_DEBUG<<"StFmsHitMaker::Make Adding StFmsCollection to StEvent"<<endm;
stEvent->setFmsCollection(mFmsCollection);
}else{
LOG_INFO << "StEvent is empty" << endm;
}
return kStOk;
}
int StFmsHitMaker::Finish(){
LOG_DEBUG << "StFmsHitMaker::Finish() " << endm;
return kStOk;
}
Int_t StFmsHitMaker::readMuDst(){
StEvent* event = (StEvent*)GetInputDS("StEvent");
if(!event){LOG_ERROR<<"StFmsHitMaker::readMuDst found no StEvent"<<endm; return kStErr;}
StFmsCollection* fmsColl = event->fmsCollection();
if(!fmsColl){
fmsColl=new StFmsCollection;
event->setFmsCollection(fmsColl);
}
StMuDst* mudst = (StMuDst*)GetInputDS("MuDst");
if(!mudst){LOG_ERROR<<"StFmsHitMaker::readMuDst found no MuDst"<<endm; return kStErr;}
StMuFmsCollection* mufmsColl= mudst->muFmsCollection();
if(!mufmsColl){LOG_ERROR<<"StFmsHitMaker::readMuDst found no MuFmsCollection"<<endm; return kStErr;}
StMuFmsUtil util;
util.fillFms(fmsColl,mufmsColl);
return kStOk;
}
| 32.426877 | 130 | 0.646148 | [
"3d"
] |
178fa5aedb6a630b6fb97554fe4591635848d988 | 7,188 | hh | C++ | src/Zynga/Framework/Cache/V2/Driver/Memcache.hh | ifuyivara/zynga-hacklang-framework | f06b4b8e5929c0884c9b52b0c677a8935df68f9b | [
"MIT"
] | 19 | 2018-04-23T09:30:48.000Z | 2022-03-06T21:35:18.000Z | src/Zynga/Framework/Cache/V2/Driver/Memcache.hh | ifuyivara/zynga-hacklang-framework | f06b4b8e5929c0884c9b52b0c677a8935df68f9b | [
"MIT"
] | 22 | 2017-11-27T23:39:25.000Z | 2019-08-09T08:56:57.000Z | src/Zynga/Framework/Cache/V2/Driver/Memcache.hh | ifuyivara/zynga-hacklang-framework | f06b4b8e5929c0884c9b52b0c677a8935df68f9b | [
"MIT"
] | 28 | 2017-11-16T20:53:56.000Z | 2021-01-04T11:13:17.000Z | <?hh // strict
namespace Zynga\Framework\Cache\V2\Driver;
use Zynga\Framework\Cache\V2\Driver\Base as DriverBase;
use Zynga\Framework\Cache\V2\Exceptions\InvalidIncrementStepException;
use Zynga\Framework\Cache\V2\Exceptions\NoServerPairsProvidedException;
use Zynga\Framework\Cache\V2\Exceptions\NoConnectionException;
use Zynga\Framework\Cache\V2\Exceptions\StorableObjectRequiredException;
use Zynga\Framework\Cache\V2\Interfaces\DriverConfigInterface;
use Zynga\Framework\Cache\V2\Interfaces\MemcacheDriverInterface;
use Zynga\Framework\Cache\V2\Interfaces\DriverInterface;
use Zynga\Framework\Dynamic\V1\DynamicClassCreation;
use Zynga\Framework\Exception\V1\Exception;
use Zynga\Framework\StorableObject\V1\Interfaces\StorableObjectInterface;
use \Memcache as NativeMemcacheDriver;
class Memcache extends DriverBase implements MemcacheDriverInterface {
private NativeMemcacheDriver $_memcache;
private DriverConfigInterface $_config;
// Map used to keep track of hosts that have been registered to avoid duplicates
private Map<string, int> $_registeredHosts;
// Operations like set and delete will retry their operation
const int OPERATION_ATTEMPTS_MAX = 100; // 100 * 10000 = 1s max wait time.
const int OPERATION_TIMEOUT_AMOUNT_MICRO_SECONDS = 10000;
// Max lock timeout is 1 seconds
const int MAX_TIMEOUT_AMOUNT_SECONDS = 1;
public function __construct(DriverConfigInterface $config) {
$this->_config = $config;
$this->_memcache = new NativeMemcacheDriver();
$this->_registeredHosts = Map {};
}
public function getConfig(): DriverConfigInterface {
return $this->_config;
}
public function directIncrement(string $key, int $incrementValue = 1): int {
try {
$this->connect();
if ($incrementValue < 0 || $incrementValue == 0) {
throw new InvalidIncrementStepException(
'Increment value must be greater than 0',
);
}
$value = $this->_memcache->increment($key, $incrementValue);
if ($value === false) {
return 0;
}
return $value;
} catch (Exception $e) {
throw $e;
}
}
public function directAdd(
string $key,
mixed $value,
int $flags = 0,
int $ttl = 0,
): bool {
try {
$this->connect();
$value = $this->_memcache->add($key, $value, $flags, $ttl);
if ($value == true) {
return true;
}
return false;
} catch (Exception $e) {
throw $e;
}
}
public function directSet(
string $key,
mixed $value,
int $flags = 0,
int $ttl = 0,
): bool {
try {
$this->connect();
$startTime = microtime(true);
for ($retryCount = 0; $retryCount < self::OPERATION_ATTEMPTS_MAX; $retryCount++) {
$success = $this->_memcache->set($key, $value, $flags, $ttl);
if ($success == true) {
return true;
}
// We crossed max timeout, break early.
if( (microtime(true) - $startTime) > self::MAX_TIMEOUT_AMOUNT_SECONDS) {
return false;
}
usleep(self::OPERATION_TIMEOUT_AMOUNT_MICRO_SECONDS);
}
return false;
} catch (Exception $e) {
throw $e;
}
}
public function directGet(string $key): mixed {
try {
$this->connect();
$item = $this->_memcache->get($key);
return $item;
} catch (Exception $e) {
throw $e;
}
}
public function directDelete(string $key): bool {
try {
$this->connect();
$startTime = microtime(true);
for ($retryCount = 0; $retryCount < self::OPERATION_ATTEMPTS_MAX; $retryCount++) {
$success = $this->_memcache->delete($key);
if ($success == true) {
return true;
}
// We crossed max timeout, break early.
if( (microtime(true) - $startTime) > self::MAX_TIMEOUT_AMOUNT_SECONDS) {
return false;
}
usleep(self::OPERATION_TIMEOUT_AMOUNT_MICRO_SECONDS);
}
return false;
} catch (Exception $e) {
throw $e;
}
}
public function connect(): bool {
// --
// sadly they don't provide a way to see if the connection has been
// configured. So you jiggle getversion to see if there is anything
// configured. SAD PANDA!
// --
$versionInfo = $this->_memcache->getversion();
if ($this->_memcache->getversion() !== false) {
return true;
}
$memcache = $this->_memcache;
try {
$serverPairs = $this->getConfig()->getServerPairings();
if ($serverPairs->count() == 0) {
throw new NoServerPairsProvidedException(
'config='.get_class($this->getConfig()),
);
}
// add the host / port combinations to the memcache object, addserver
// always returns true as it lazy connects at use time.
foreach ($serverPairs as $host => $port) {
// addserver does not check for duplicates
if ($this->_registeredHosts->containsKey($host) === false) {
$memcache->addserver($host, $port);
$this->_registeredHosts[$host] = $port;
}
}
$this->_memcache = $memcache;
return true;
} catch (Exception $e) {
throw $e;
}
}
public function add(
StorableObjectInterface $obj,
string $keyOverride = '',
int $ttlOverride = -1,
): bool {
try {
$key = $this->getKeySupportingOverride($obj, $keyOverride);
$ttl = $this->getTTLSupportingOverride($ttlOverride);
$jsonValue = $obj->export()->asJSON();
$flags = 0;
$return = $this->directAdd($key, $jsonValue, $flags, $ttl);
if ($return == true) {
return true;
}
return false;
} catch (Exception $e) {
throw $e;
}
}
public function get(
StorableObjectInterface $obj,
string $keyOverride = '',
): ?StorableObjectInterface {
try {
$key = $this->getKeySupportingOverride($obj, $keyOverride);
$this->connect();
$data = $this->directGet($key);
// no data to work with.
if ($data === false) {
return null;
}
$obj->import()->fromJSON(strval($data));
return $obj;
} catch (Exception $e) {
throw $e;
}
}
public function set(
StorableObjectInterface $obj,
string $keyOverride = '',
int $ttlOverride = -1,
): bool {
try {
$key = $this->getKeySupportingOverride($obj, $keyOverride);
$ttl = $this->getTTLSupportingOverride($ttlOverride);
$this->connect();
$jsonValue = $obj->export()->asJSON();
$flags = 0;
$success = $this->directSet($key, $jsonValue, $flags, $ttl);
return $success;
} catch (Exception $e) {
throw $e;
}
}
public function delete(
StorableObjectInterface $obj,
string $keyOverride = '',
): bool {
try {
$key = $this->getKeySupportingOverride($obj, $keyOverride);
$this->connect();
$success = $this->_memcache->delete($key);
if ($success == 1) {
return true;
}
return false;
} catch (Exception $e) {
throw $e;
}
}
}
| 22.25387 | 88 | 0.601697 | [
"object"
] |
17979cc3771c3a27809af6aa86500db1b108753e | 19,543 | cpp | C++ | MeshmoonCommon/common/layers/MeshmoonLayerProcessor.cpp | Adminotech/meshmoon-plugins | 32043ef783bdf137860d7d01eb22de564628e572 | [
"Apache-2.0"
] | 4 | 2018-05-09T01:55:14.000Z | 2021-12-19T17:46:29.000Z | MeshmoonCommon/common/layers/MeshmoonLayerProcessor.cpp | Adminotech/meshmoon-plugins | 32043ef783bdf137860d7d01eb22de564628e572 | [
"Apache-2.0"
] | null | null | null | MeshmoonCommon/common/layers/MeshmoonLayerProcessor.cpp | Adminotech/meshmoon-plugins | 32043ef783bdf137860d7d01eb22de564628e572 | [
"Apache-2.0"
] | 2 | 2016-03-15T06:12:05.000Z | 2021-06-06T00:18:38.000Z | /**
@author Admino Technologies Ltd.
Copyright 2013 Admino Technologies Ltd.
All rights reserved.
@file
@brief */
#include "StableHeaders.h"
#include "MeshmoonLayerProcessor.h"
#include "common/json/MeshmoonJson.h"
#include "Framework.h"
#include "LoggingFunctions.h"
#include "IRenderer.h"
#include "CoreJsonUtils.h"
#include "UniqueIdGenerator.h"
#include "SceneAPI.h"
#include "Scene.h"
#include "SceneDesc.h"
#include "Entity.h"
#include "IComponent.h"
#include "AssetAPI.h"
#include "EC_Name.h"
#include "EC_DynamicComponent.h"
#include "EC_Placeable.h"
#include "EC_Mesh.h"
#include "EC_Sky.h"
#include "EC_Billboard.h"
#include "EC_ParticleSystem.h"
#include "EC_Material.h"
#include "EC_Script.h"
#include "EC_Sound.h"
#include "EC_HoveringText.h"
#include <QTextStream>
#include <QDomDocument>
#include <kNet/PolledTimer.h>
/// @cond PRIVATE
namespace
{
const u32 InvalidTypeId = 0xffffffff;
}
MeshmoonLayerProcessor::MeshmoonLayerProcessor(Framework *framework) :
framework_(framework),
LC("[MeshmoonLayers]: ")
{
interestingComponentTypeNames_ << EC_Mesh::TypeNameStatic()
<< EC_Material::TypeNameStatic()
<< EC_Sound::TypeNameStatic()
<< EC_Sky::TypeNameStatic()
<< EC_HoveringText::TypeNameStatic()
<< EC_Billboard::TypeNameStatic()
<< EC_ParticleSystem::TypeNameStatic()
<< EC_Script::TypeNameStatic()
// Manual names for components where we don't want direct linking.
<< "EC_RigidBody"
<< "EC_Terrain"
<< "EC_WaterPlane"
<< "EC_SlideShow"
<< "EC_WidgetBillboard"
<< "EC_Hydrax";
interestingComponentTypeIds_ << EC_Mesh::TypeIdStatic()
<< EC_Material::TypeIdStatic()
<< EC_Sound::TypeIdStatic()
<< EC_Sky::TypeIdStatic()
<< EC_HoveringText::TypeIdStatic()
<< EC_Billboard::TypeIdStatic()
<< EC_ParticleSystem::TypeIdStatic()
<< EC_Script::TypeIdStatic()
// Manual IDs for components where we don't want direct linking.
// @note Hazard is that these *might* change, but its very unlikely.
<< 23 // EC_RigidBody
<< 11 // EC_Terrain
<< 12 // EC_WaterPlane
<< 41 // EC_SlideShow
<< 42 // EC_WidgetBillboard
<< 39; // EC_Hydrax
interestingAttributeTypeIds_ << (u32)IAttribute::StringId
<< (u32)IAttribute::AssetReferenceId
<< (u32)IAttribute::AssetReferenceListId
<< (u32)IAttribute::VariantListId;
}
MeshmoonLayerProcessor::~MeshmoonLayerProcessor()
{
}
Meshmoon::SceneLayerList MeshmoonLayerProcessor::DeserializeFrom(const QByteArray &meshmoonLayersJsonData)
{
QTextStream layersStream(meshmoonLayersJsonData);
layersStream.setCodec("UTF-8");
layersStream.setAutoDetectUnicode(true);
QByteArray layersDataStr = layersStream.readAll().toUtf8();
Meshmoon::SceneLayerList out;
// Parse the application JSON.
bool ok = false;
QVariantList layerList = TundraJson::Parse(layersDataStr, &ok).toList();
if (ok)
{
UniqueIdGenerator idGenerator;
foreach(const QVariant &layerVariant, layerList)
{
QVariantMap layerData = layerVariant.toMap();
// Read layer data
Meshmoon::SceneLayer layer;
layer.id = idGenerator.AllocateReplicated(); /// @todo This can generate duplicate IDs if this function is called multiple times per run!
layer.name = layerData.contains("Name") ? QString(layerData.value("Name").toString().data()) : "";
layer.iconUrl = layerData.contains("IconUrl") ? QString(layerData.value("IconUrl").toString().data()) : "";
layer.defaultVisible = layerData.contains("DefaultVisible") ? layerData.value("DefaultVisible").toBool() : false;
layer.txmlUrl = QUrl::fromEncoded(QString(layerData.value("Url").toString().data()).toUtf8(), QUrl::StrictMode);
if (layer.txmlUrl.toString().isEmpty())
{
LogError(LC + "Found layer without txml URL, skipping layer: " + layer.toString());
continue;
}
// Support two different ways of parsing position! Old and new Kirnu implementation.
QVariant positionVariant = layerData.value("Position");
if (positionVariant.isValid())
{
if (!Meshmoon::JSON::DeserializeFloat3(positionVariant, layer.centerPosition))
LogError(LC + QString("Found layer unsupported QVariant type as 'Position': %1").arg(positionVariant.type()));
}
else
LogError(LC + "Found layer description without 'Position': " + layer.toString());
out << layer;
}
}
else
{
LogError(LC + "Failed to deserialize layers list from JSON data");
qDebug() << "RAW JSON DATA" << endl << layersDataStr;
}
return out;
}
bool MeshmoonLayerProcessor::LoadSceneLayer(Meshmoon::SceneLayer &layer) const
{
kNet::PolledTimer timer;
if (layer.sceneData.isEmpty())
{
LogWarning(LC + "-- Scene layer content is empty: " + layer.toString() + " txml = " + layer.txmlUrl.toString());
return false;
}
QString txmlUrlNoQuery = layer.txmlUrl.toString(QUrl::RemoveQuery|QUrl::StripTrailingSlash);
Scene *activeScene = framework_->Renderer()->MainCameraScene();
if (!activeScene)
{
LogError(LC + "Failed to get active scene to load scene layer: " + txmlUrlNoQuery);
return false;
}
// Load txml scene
QString txmlUrl = layer.txmlUrl.toString();
QString txmlUrlLower = txmlUrl.toLower();
QString layerBaseUrl = txmlUrlNoQuery.left(txmlUrlNoQuery.lastIndexOf("/") + 1);
QString layerFilename = txmlUrlNoQuery.mid(layerBaseUrl.length());
LogInfo(LC + QString("Loading %1 '%2'").arg(layer.id).arg(layer.name));
LogInfo(LC + QString(" - Base %1").arg(layerBaseUrl));
LogInfo(LC + QString(" - File %1").arg(layerFilename));
LogInfo(LC + QString(" - Default Visibility %1").arg(layer.defaultVisible));
LogInfo(LC + QString(" - Offset %1").arg(layer.centerPosition.toString()));
SceneDesc sceneDesc;
if (txmlUrlLower.contains(".txml"))
{
activeScene->CreateSceneDescFromXml(layer.sceneData, sceneDesc, false);
if (sceneDesc.entities.isEmpty())
{
LogInfo(LC + " * No Entities in scene data");
return false;
}
}
else
{
LogError(LC + "-- Format of layer load request asset is invalid, aborting: " + txmlUrl);
return false;
}
// Manipulate scene description from relative to full asset refs before loading entities to scene
/// @todo Profile; there's porbably room for optimization here.
const float timeBeforeAssetRefAdjustment = timer.MSecsElapsed();
int adjustedRefs = 0;
for (int iE=0; iE<sceneDesc.entities.size(); ++iE)
{
EntityDesc &ent = sceneDesc.entities[iE];
ent.temporary = true;
for (int iC=0; iC<ent.components.size(); ++iC)
{
ComponentDesc &comp = ent.components[iC];
bool compIsInteresting = false;
if (comp.typeId != InvalidTypeId)
compIsInteresting = interestingComponentTypeIds_.contains(comp.typeId);
else
compIsInteresting = interestingComponentTypeNames_.contains(IComponent::EnsureTypeNameWithPrefix(comp.typeName), Qt::CaseInsensitive);
if (!compIsInteresting)
continue;
//qDebug() << " " << comp.typeName;
for (int iA=0; iA<comp.attributes.size(); ++iA)
{
AttributeDesc &attr = comp.attributes[iA];
u32 attrTypeId = SceneAPI::GetAttributeTypeId(attr.typeName);
if (interestingAttributeTypeIds_.contains(attrTypeId))
{
// AssetReference, generic conversion
if (attrTypeId == cAttributeAssetReference)
{
QString ref = attr.value;
if (ref.trimmed().isEmpty())
continue;
if (AssetAPI::ParseAssetRef(ref) == AssetAPI::AssetRefRelativePath)
{
attr.value = framework_->Asset()->ResolveAssetRef(layerBaseUrl, ref);
//qDebug() << " " << attr.typeName.toStdString().c_str() << ":" << ref.toStdString().c_str() << "->" << attr.value.toStdString().c_str();
adjustedRefs++;
}
}
// AssetReferenceList, generic conversion
else if (attrTypeId == cAttributeAssetReferenceList)
{
QString ref = attr.value;
if (ref.trimmed().isEmpty())
continue;
QStringList inputRefs;
if (ref.contains(";"))
inputRefs = ref.split(";", QString::KeepEmptyParts);
else
inputRefs << ref;
QStringList outputRefs;
foreach(QString inputRef, inputRefs)
{
if (!inputRef.trimmed().isEmpty() && AssetAPI::ParseAssetRef(inputRef) == AssetAPI::AssetRefRelativePath)
{
outputRefs << framework_->Asset()->ResolveAssetRef(layerBaseUrl, inputRef);
//qDebug() << " " << attr.typeName.toStdString().c_str() << ":" << inputRef.toStdString().c_str() << "->" << framework_->Asset()->ResolveAssetRef(layerBaseUrl, inputRef).toStdString().c_str();
adjustedRefs++;
}
else
outputRefs << inputRef;
}
if (outputRefs.size() > 1)
attr.value = outputRefs.join(";");
else if (outputRefs.size() == 1)
attr.value = outputRefs.first();
}
// String
else if (attrTypeId == cAttributeString)
{
// Per component conversion
if (comp.typeName == EC_Material::TypeNameStatic())
{
/** @todo We could fix non "generated://" output refs right here,
but then we would have to go through all the meshes for usage.
Lets trust that the original layer txml is proper. */
if (attr.name == "Input Material")
{
QString ref = attr.value;
if (ref.trimmed().isEmpty())
continue;
if (AssetAPI::ParseAssetRef(ref) == AssetAPI::AssetRefRelativePath)
{
attr.value = framework_->Asset()->ResolveAssetRef(layerBaseUrl, ref);
//qDebug() << " " << attr.typeName.toStdString().c_str() << ":" << ref.toStdString().c_str() << "->" << attr.value.toStdString().c_str();
adjustedRefs++;
}
}
}
}
// QVariantList
else if (attrTypeId == cAttributeQVariantList)
{
// Per component conversion
if (comp.typeName == EC_Material::TypeNameStatic())
{
if (attr.name == "Parameters")
{
// We only want to check the "texture = <ref>" parameter
QString ref = attr.value;
if (ref.isEmpty() || ref.indexOf("texture", 0, Qt::CaseInsensitive) == -1)
continue;
QStringList inputRefs;
if (ref.contains(";"))
inputRefs = ref.split(";", QString::KeepEmptyParts);
else
inputRefs << ref;
QStringList outputRefs;
foreach(QString inputRef, inputRefs)
{
if (!inputRef.trimmed().isEmpty() && inputRef.trimmed().startsWith("texture =", Qt::CaseInsensitive))
{
// Split ref from: "texture = <ref>"
QString texAssetRef = inputRef.mid(inputRef.lastIndexOf("= ") + 2).trimmed();
if (AssetAPI::ParseAssetRef(texAssetRef) == AssetAPI::AssetRefRelativePath)
{
outputRefs << "texture = " + framework_->Asset()->ResolveAssetRef(layerBaseUrl, texAssetRef);
//qDebug() << " " << attr.typeName.toStdString().c_str() << ":" << inputRef.toStdString().c_str() << "->" << QString("texture = ") + framework_->Asset()->ResolveAssetRef(layerBaseUrl, texAssetRef).toStdString().c_str();
adjustedRefs++;
}
else
outputRefs << inputRef;
}
else
outputRefs << inputRef;
}
if (outputRefs.size() > 1)
attr.value = outputRefs.join(";");
else if (outputRefs.size() == 1)
attr.value = outputRefs.first();
}
}
else if (comp.typeName == "EC_SlideShow")
{
QString ref = attr.value;
if (ref.trimmed().isEmpty())
continue;
QStringList inputRefs;
if (ref.contains(";"))
inputRefs = ref.split(";", QString::KeepEmptyParts);
else
inputRefs << ref;
QStringList outputRefs;
foreach(QString inputRef, inputRefs)
{
if (!inputRef.trimmed().isEmpty() && AssetAPI::ParseAssetRef(inputRef) == AssetAPI::AssetRefRelativePath)
{
outputRefs << framework_->Asset()->ResolveAssetRef(layerBaseUrl, inputRef);
//qDebug() << " " << attr.typeName.toStdString().c_str() << ":" << inputRef.toStdString().c_str() << "->" << framework_->Asset()->ResolveAssetRef(layerBaseUrl, inputRef).toStdString().c_str();
adjustedRefs++;
}
else
outputRefs << inputRef;
}
if (outputRefs.size() > 1)
attr.value = outputRefs.join(";");
else if (outputRefs.size() == 1)
attr.value = outputRefs.first();
}
}
}
}
}
}
const float assetRefAdjustingTime = timer.MSecsElapsed() - timeBeforeAssetRefAdjustment;
QList<Entity*> createdEnts = activeScene->CreateContentFromSceneDesc(sceneDesc, false, AttributeChange::Replicate);
const QString layerIndentifier = "Meshmoon Layer: " + layer.name;
const bool adjustPlaceables = !layer.centerPosition.IsZero();
uint adjustedPositions = 0;
layer.entities.clear();
foreach(Entity *createdEntity, createdEnts)
{
layer.entities << createdEntity->shared_from_this();
// Set layer group and/or desc identifier (don't overwrite existing, app logic might depend on these)
if (createdEntity->Group().trimmed().isEmpty())
createdEntity->SetGroup(layerIndentifier);
if (createdEntity->Description().trimmed().isEmpty())
createdEntity->SetDescription(layerIndentifier);
// Layer offset. Do not apply on Entity level parented Entities.
if (adjustPlaceables && !createdEntity->Parent().get())
{
std::vector<shared_ptr<EC_Placeable> > placeables = createdEntity->ComponentsOfType<EC_Placeable>();
for(size_t i = 0; i < placeables.size(); ++i)
{
// Do not apply on Placeable level parented Entities.
if (placeables[i]->parentRef.Get().ref.trimmed().isEmpty())
{
Transform t = placeables[i]->transform.Get();
t.pos += layer.centerPosition;
placeables[i]->transform.Set(t, AttributeChange::Replicate);
adjustedPositions++;
}
}
}
}
if (adjustedRefs > 0)
{
LogInfo(LC + QString(" - Adjusted %1 relative layer refs with base url in %2 msecs.")
.arg(adjustedRefs).arg(assetRefAdjustingTime));
}
if (adjustPlaceables)
{
LogInfo(LC + QString(" - Adjusted layer with position offset %1 for %2 non-parented Placeables.")
.arg(layer.centerPosition.toString()).arg(adjustedPositions));
}
LogInfo(LC + QString(" - Scene layer loaded with %1 temporary entities in %2 msecs.")
.arg(createdEnts.size()).arg(timer.MSecsElapsed()));
return true;
}
/// @endcond
| 45.238426 | 264 | 0.485187 | [
"vector",
"transform"
] |
1799cae8d9eba86d0ef40aa888483a93b9d3f763 | 85,619 | cpp | C++ | dlls/sas.cpp | edgarbarney/halflife-planckepoch | 630e7066d8bf260783eaea7341f3c84fb87d69dd | [
"Unlicense"
] | 3 | 2021-08-08T14:22:11.000Z | 2022-02-02T03:08:17.000Z | dlls/sas.cpp | edgarbarney/halflife-planckepoch | 630e7066d8bf260783eaea7341f3c84fb87d69dd | [
"Unlicense"
] | 7 | 2021-02-27T01:55:27.000Z | 2021-09-06T17:32:43.000Z | dlls/sas.cpp | edgarbarney/halflife-planckepoch | 630e7066d8bf260783eaea7341f3c84fb87d69dd | [
"Unlicense"
] | 6 | 2021-03-14T15:35:17.000Z | 2022-01-10T22:53:15.000Z | // Thanks to Solokiller's OP4 for ally dudes
//
// Why didn't I do it myself?
// Lazyness.
//=========================================================
// Hit groups!
//=========================================================
/*
1 - Head
2 - Stomach
3 - Gun
*/
#include "extdll.h"
#include "plane.h"
#include "util.h"
#include "cbase.h"
#include "monsters.h"
#include "schedule.h"
#include "defaultai.h"
#include "animation.h"
#include "squadmonster.h"
#include "weapons.h"
#include "talkmonster.h"
#include "COFAllyMonster.h"
#include "COFSquadTalkMonster.h"
#include "soundent.h"
#include "effects.h"
#include "customentity.h"
int g_fGruntAllyQuestion; // true if an idle grunt asked a question. Cleared when someone answers.
extern DLL_GLOBAL int g_iSkillLevel;
//=========================================================
// monster-specific DEFINE's
//=========================================================
#define SAS_MP5_CLIP_SIZE 36 // how many bullets in a clip? - NOTE: 3 round burst sound, so keep as 3 * x!
#define SAS_SHOTGUN_CLIP_SIZE 8
#define SAS_AR16_CLIP_SIZE 40
#define SAS_VOL 0.35 // volume of grunt sounds
#define SAS_ATTN ATTN_NORM // attenutation of grunt sentences
#define HSAS_LIMP_HEALTH 20
#define HSAS_DMG_HEADSHOT ( DMG_BULLET | DMG_CLUB ) // damage types that can kill a grunt with a single headshot.
#define HSAS_NUM_HEADS 2 // how many grunt heads are there?
#define HSAS_MINIMUM_HEADSHOT_DAMAGE 15 // must do at least this much damage in one shot to head to score a headshot kill
#define HSAS_SENTENCE_VOLUME (float)0.35 // volume of grunt sentences
namespace SASWeaponFlag
{
enum SASWeaponFlag
{
MP5 = 1 << 0,
HandGrenade = 1 << 1,
GrenadeLauncher = 1 << 2,
Shotgun = 1 << 3,
AR16 = 1 << 4,
Flashbang = 1 << 5,
};
}
namespace SASBodygroup
{
enum SASBodygroup
{
Head = 1,
Torso = 2,
Weapons = 3
};
}
namespace SASHead
{
enum SASHead
{
Default = -1,
GasMask = 0,
Leader
};
}
namespace SASSkin
{
enum SASSkin
{
Default = -1,
WhiteBrown = 0,
WhiteBlu,
ScotBrown,
ScotBlu,
LeaderWhite,
LeaderScot,
SKINCOUNT_SOLDIERS = 3, // Total heads -1 (Leaders Excluded);
SKINCOUNT_LEADERS = 1, // Total heads -1 (Leaders Only);
};
}
namespace SASTorso
{
enum SASTorso
{
Normal = 0,
AR16,
Nothing,
Shotgun
};
}
namespace SASWeapon
{
enum SASWeapon
{
MP5 = 0,
Shotgun,
AR16,
None
};
}
//=========================================================
// Monster's Anim Events Go Here
//=========================================================
#define HSAS_AE_RELOAD ( 2 )
#define HSAS_AE_KICK ( 3 )
#define HSAS_AE_BURST1 ( 4 )
#define HSAS_AE_BURST2 ( 5 )
#define HSAS_AE_BURST3 ( 6 )
#define HSAS_AE_GREN_TOSS ( 7 )
#define HSAS_AE_GREN_LAUNCH ( 8 )
#define HSAS_AE_GREN_DROP ( 9 )
#define HSAS_AE_CAUGHT_ENEMY ( 10 ) // grunt established sight with an enemy (player only) that had previously eluded the squad.
#define HSAS_AE_DROP_GUN ( 11 ) // grunt (probably dead) is dropping his mp5.
#define HSAS_AE_RELOAD_SOUND ( 12 ) // play sound BEFORE reload is finished.
//=========================================================
// monster-specific schedule types
//=========================================================
enum
{
SCHED_SAS_SUPPRESS = LAST_TALKMONSTER_SCHEDULE + 1,
SCHED_SAS_ESTABLISH_LINE_OF_FIRE,// move to a location to set up an attack against the enemy. (usually when a friendly is in the way).
SCHED_SAS_COVER_AND_RELOAD,
SCHED_SAS_SWEEP,
SCHED_SAS_FOUND_ENEMY,
SCHED_SAS_REPEL,
SCHED_SAS_REPEL_ATTACK,
SCHED_SAS_REPEL_LAND,
SCHED_SAS_WAIT_FACE_ENEMY,
SCHED_SAS_TAKECOVER_FAILED,// special schedule type that forces analysis of conditions and picks the best possible schedule to recover from this type of failure.
SCHED_SAS_ELOF_FAIL,
};
//=========================================================
// monster-specific tasks
//=========================================================
enum
{
TASK_SAS_FACE_TOSS_DIR = LAST_TALKMONSTER_TASK + 1,
TASK_SAS_SPEAK_SENTENCE,
TASK_SAS_CHECK_FIRE,
};
//=========================================================
// monster-specific conditions
//=========================================================
#define bits_COND_SAS_NOFIRE ( bits_COND_SPECIAL1 )
class CSAS : public COFSquadTalkMonster
{
public:
void Spawn() override;
void Precache() override;
void SetYawSpeed() override;
int Classify() override;
int ISoundMask() override;
void HandleAnimEvent(MonsterEvent_t* pEvent) override;
void BeStunned(float stunTime) override;
BOOL FCanCheckAttacks() override;
BOOL CheckMeleeAttack1(float flDot, float flDist) override;
BOOL CheckRangeAttack1(float flDot, float flDist) override;
BOOL CheckRangeAttack2(float flDot, float flDist) override;
void CheckAmmo() override;
void SetActivity(Activity NewActivity) override;
void StartTask(Task_t* pTask) override;
void RunTask(Task_t* pTask) override;
void DeathSound() override;
void PainSound() override;
void IdleSound() override;
Vector GetGunPosition() override;
void Shoot();
void Shotgun();
void PrescheduleThink() override;
void GibMonster() override;
void SpeakSentence();
int Save(CSave& save) override;
int Restore(CRestore& restore) override;
CBaseEntity* Kick();
Schedule_t* GetSchedule() override;
Schedule_t* GetScheduleOfType(int Type) override;
void TraceAttack(entvars_t* pevAttacker, float flDamage, Vector vecDir, TraceResult* ptr, int bitsDamageType) override;
int TakeDamage(entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType) override;
BOOL FOkToSpeak();
void JustSpoke();
int GetCount();
int ObjectCaps() override;
void TalkInit();
void AlertSound() override;
void DeclineFollowing() override;
void ShootAR16();
void KeyValue(KeyValueData* pkvd) override;
void Killed(entvars_t* pevAttacker, int iGib) override;
MONSTERSTATE GetIdealState() override
{
return COFSquadTalkMonster::GetIdealState();
}
CUSTOM_SCHEDULES;
static TYPEDESCRIPTION m_SaveData[];
BOOL m_lastAttackCheck;
float m_flPlayerDamage;
// checking the feasibility of a grenade toss is kind of costly, so we do it every couple of seconds,
// not every server frame.
float m_flNextGrenadeCheck;
float m_flNextPainTime;
float m_flLastEnemySightTime;
Vector m_vecTossVelocity;
BOOL m_fThrowGrenade;
BOOL m_fStanding;
BOOL m_fFirstEncounter;// only put on the handsign show in the squad's first encounter.
int m_cClipSize;
int m_iBrassShell;
int m_iShotgunShell;
int m_iAR16Shell;
int m_iAR16Link;
int m_iSentence;
int m_iWeaponIdx;
int m_iGruntHead;
int m_iGruntTorso;
static const char* pGruntSentences[];
};
LINK_ENTITY_TO_CLASS(monster_sas, CSAS);
TYPEDESCRIPTION CSAS::m_SaveData[] =
{
DEFINE_FIELD(CSAS, m_flPlayerDamage, FIELD_FLOAT),
DEFINE_FIELD(CSAS, m_flNextGrenadeCheck, FIELD_TIME),
DEFINE_FIELD(CSAS, m_flNextPainTime, FIELD_TIME),
// DEFINE_FIELD( CSAS, m_flLastEnemySightTime, FIELD_TIME ), // don't save, go to zero
DEFINE_FIELD(CSAS, m_vecTossVelocity, FIELD_VECTOR),
DEFINE_FIELD(CSAS, m_fThrowGrenade, FIELD_BOOLEAN),
DEFINE_FIELD(CSAS, m_fStanding, FIELD_BOOLEAN),
DEFINE_FIELD(CSAS, m_fFirstEncounter, FIELD_BOOLEAN),
DEFINE_FIELD(CSAS, m_cClipSize, FIELD_INTEGER),
DEFINE_FIELD( CSAS, m_voicePitch, FIELD_INTEGER ),
// DEFINE_FIELD( CShotgun, m_iBrassShell, FIELD_INTEGER ),
// DEFINE_FIELD( CShotgun, m_iShotgunShell, FIELD_INTEGER ),
DEFINE_FIELD(CSAS, m_iSentence, FIELD_INTEGER),
DEFINE_FIELD(CSAS, m_iWeaponIdx, FIELD_INTEGER),
DEFINE_FIELD(CSAS, m_iGruntHead, FIELD_INTEGER),
DEFINE_FIELD(CSAS, m_iGruntTorso, FIELD_INTEGER),
DEFINE_FIELD(CSAS, m_deadMates, FIELD_INTEGER),
DEFINE_FIELD(CSAS, m_canSayUsLeft, FIELD_INTEGER),
DEFINE_FIELD(CSAS, m_canLoseSquad, FIELD_BOOLEAN),
};
IMPLEMENT_SAVERESTORE(CSAS, COFSquadTalkMonster);
const char* CSAS::pGruntSentences[] =
{
"SAS_GREN", // grenade scared grunt
"SAS_ALERT", // sees player
"SAS_MONSTER", // sees monster
"SAS_COVER", // running to cover
"SAS_THROW", // about to throw grenade
"SAS_CHARGE", // running out to get the enemy
"SAS_TAUNT", // say rude things
};
enum
{
HSAS_SENT_NONE = -1,
HSAS_SENT_GREN = 0,
HSAS_SENT_ALERT,
HSAS_SENT_MONSTER,
HSAS_SENT_COVER,
HSAS_SENT_THROW,
HSAS_SENT_CHARGE,
HSAS_SENT_TAUNT,
} HSAS_ALLY_SENTENCE_TYPES;
//=========================================================
// Speak Sentence - say your cued up sentence.
//
// Some grunt sentences (take cover and charge) rely on actually
// being able to execute the intended action. It's really lame
// when a grunt says 'COVER ME' and then doesn't move. The problem
// is that the sentences were played when the decision to TRY
// to move to cover was made. Now the sentence is played after
// we know for sure that there is a valid path. The schedule
// may still fail but in most cases, well after the grunt has
// started moving.
//=========================================================
void CSAS::SpeakSentence()
{
if (m_iSentence == HSAS_SENT_NONE)
{
// no sentence cued up.
return;
}
if (FOkToSpeak())
{
SENTENCEG_PlayRndSz(ENT(pev), pGruntSentences[m_iSentence], HSAS_SENTENCE_VOLUME, SAS_ATTN, 0, m_voicePitch);
JustSpoke();
}
}
//=========================================================
// GibMonster - make gun fly through the air.
//=========================================================
void CSAS::GibMonster()
{
if (m_hWaitMedic)
{
auto pMedic = m_hWaitMedic.Entity<COFSquadTalkMonster>();
if (pMedic->pev->deadflag != DEAD_NO)
m_hWaitMedic = nullptr;
else
pMedic->HealMe(nullptr);
}
Vector vecGunPos;
Vector vecGunAngles;
if (m_iWeaponIdx != SASWeapon::None)
{// throw a gun if the grunt has one
GetAttachment(0, vecGunPos, vecGunAngles);
CBaseEntity* pGun;
if (FBitSet(pev->weapons, SASWeaponFlag::Shotgun))
{
pGun = DropItem("weapon_shotgun", vecGunPos, vecGunAngles);
}
else if (FBitSet(pev->weapons, SASWeaponFlag::AR16))
{
pGun = DropItem("weapon_ar16", vecGunPos, vecGunAngles);
}
else
{
pGun = DropItem("weapon_9mmAR", vecGunPos, vecGunAngles);
}
if (pGun)
{
pGun->pev->velocity = Vector(RANDOM_FLOAT(-100, 100), RANDOM_FLOAT(-100, 100), RANDOM_FLOAT(200, 300));
pGun->pev->avelocity = Vector(0, RANDOM_FLOAT(200, 400), 0);
}
if (FBitSet(pev->weapons, SASWeaponFlag::GrenadeLauncher))
{
pGun = DropItem("ammo_ARgrenades", vecGunPos, vecGunAngles);
if (pGun)
{
pGun->pev->velocity = Vector(RANDOM_FLOAT(-100, 100), RANDOM_FLOAT(-100, 100), RANDOM_FLOAT(200, 300));
pGun->pev->avelocity = Vector(0, RANDOM_FLOAT(200, 400), 0);
}
}
m_iWeaponIdx = SASWeapon::None;
}
CBaseMonster::GibMonster();
}
//=========================================================
// ISoundMask - Overidden for human grunts because they
// hear the DANGER sound that is made by hand grenades and
// other dangerous items.
//=========================================================
int CSAS::ISoundMask()
{
return bits_SOUND_WORLD |
bits_SOUND_COMBAT |
bits_SOUND_PLAYER |
bits_SOUND_DANGER |
bits_SOUND_CARCASS |
bits_SOUND_MEAT |
bits_SOUND_GARBAGE;
}
//=========================================================
// someone else is talking - don't speak
//=========================================================
BOOL CSAS::FOkToSpeak()
{
// if someone else is talking, don't speak
if (gpGlobals->time <= COFSquadTalkMonster::g_talkWaitTime)
return FALSE;
if (pev->spawnflags & SF_MONSTER_GAG)
{
if (m_MonsterState != MONSTERSTATE_COMBAT)
{
// no talking outside of combat if gagged.
return FALSE;
}
}
// if player is not in pvs, don't speak
// if (FNullEnt(FIND_CLIENT_IN_PVS(edict())))
// return FALSE;
return TRUE;
}
//=========================================================
//=========================================================
void CSAS::JustSpoke()
{
COFSquadTalkMonster::g_talkWaitTime = gpGlobals->time + RANDOM_FLOAT(1.5, 2.0);
m_iSentence = HSAS_SENT_NONE;
}
//=========================================================
// PrescheduleThink - this function runs after conditions
// are collected and before scheduling code is run.
//=========================================================
void CSAS::PrescheduleThink()
{
if (InSquad() && m_hEnemy != nullptr)
{
if (HasConditions(bits_COND_SEE_ENEMY))
{
// update the squad's last enemy sighting time.
MySquadLeader()->m_flLastEnemySightTime = gpGlobals->time;
}
else
{
if (gpGlobals->time - MySquadLeader()->m_flLastEnemySightTime > 5)
{
// been a while since we've seen the enemy
MySquadLeader()->m_fEnemyEluded = TRUE;
}
}
}
}
//=========================================================
// FCanCheckAttacks - this is overridden for human grunts
// because they can throw/shoot grenades when they can't see their
// target and the base class doesn't check attacks if the monster
// cannot see its enemy.
//
// !!!BUGBUG - this gets called before a 3-round burst is fired
// which means that a friendly can still be hit with up to 2 rounds.
// ALSO, grenades will not be tossed if there is a friendly in front,
// this is a bad bug. Friendly machine gun fire avoidance
// will unecessarily prevent the throwing of a grenade as well.
//=========================================================
BOOL CSAS::FCanCheckAttacks()
{
if (!HasConditions(bits_COND_ENEMY_TOOFAR))
{
return TRUE;
}
else
{
return FALSE;
}
}
//=========================================================
// CheckMeleeAttack1
//=========================================================
BOOL CSAS::CheckMeleeAttack1(float flDot, float flDist)
{
CBaseMonster* pEnemy;
if (m_hEnemy != nullptr)
{
pEnemy = m_hEnemy->MyMonsterPointer();
if (!pEnemy)
{
return FALSE;
}
}
if (flDist <= 64 && flDot >= 0.7 &&
pEnemy->Classify() != CLASS_ALIEN_BIOWEAPON &&
pEnemy->Classify() != CLASS_PLAYER_BIOWEAPON)
{
return TRUE;
}
return FALSE;
}
//=========================================================
// CheckRangeAttack1 - overridden for HGrunt, cause
// FCanCheckAttacks() doesn't disqualify all attacks based
// on whether or not the enemy is occluded because unlike
// the base class, the HGrunt can attack when the enemy is
// occluded (throw grenade over wall, etc). We must
// disqualify the machine gun attack if the enemy is occluded.
//=========================================================
BOOL CSAS::CheckRangeAttack1(float flDot, float flDist)
{
//Only if we have a weapon
if (pev->weapons)
{
const auto maxDistance = pev->weapons & SASWeaponFlag::Shotgun ? 640 : 1024;
//Friendly fire is allowed
if (!HasConditions(bits_COND_ENEMY_OCCLUDED) && flDist <= maxDistance && flDot >= 0.5 /*&& NoFriendlyFire()*/)
{
TraceResult tr;
auto pEnemy = m_hEnemy.Entity<CBaseEntity>();
if (!pEnemy->IsPlayer() && flDist <= 64)
{
// kick nonclients, but don't shoot at them.
return FALSE;
}
//TODO: kinda odd that this doesn't use GetGunPosition like the original
Vector vecSrc = pev->origin + Vector(0, 0, 55);
//Fire at last known position, adjusting for target origin being offset from entity origin
const auto targetOrigin = pEnemy->BodyTarget(vecSrc);
const auto targetPosition = targetOrigin - pEnemy->pev->origin + m_vecEnemyLKP;
// verify that a bullet fired from the gun will hit the enemy before the world.
UTIL_TraceLine(vecSrc, targetPosition, dont_ignore_monsters, ENT(pev), &tr);
m_lastAttackCheck = tr.flFraction == 1.0 ? true : tr.pHit && GET_PRIVATE(tr.pHit) == pEnemy;
return m_lastAttackCheck;
}
}
return FALSE;
}
//=========================================================
// CheckRangeAttack2 - this checks the Grunt's grenade
// attack.
//=========================================================
BOOL CSAS::CheckRangeAttack2(float flDot, float flDist)
{
if (!FBitSet(pev->weapons, (SASWeaponFlag::Flashbang | SASWeaponFlag::HandGrenade | SASWeaponFlag::GrenadeLauncher)))
{
return FALSE;
}
// if the grunt isn't moving, it's ok to check.
if (m_flGroundSpeed != 0)
{
m_fThrowGrenade = FALSE;
return m_fThrowGrenade;
}
// assume things haven't changed too much since last time
if (gpGlobals->time < m_flNextGrenadeCheck)
{
return m_fThrowGrenade;
}
if (!FBitSet(m_hEnemy->pev->flags, FL_ONGROUND) && m_hEnemy->pev->waterlevel == 0 && m_vecEnemyLKP.z > pev->absmax.z)
{
//!!!BUGBUG - we should make this check movetype and make sure it isn't FLY? Players who jump a lot are unlikely to
// be grenaded.
// don't throw grenades at anything that isn't on the ground!
m_fThrowGrenade = FALSE;
return m_fThrowGrenade;
}
Vector vecTarget;
if (FBitSet(pev->weapons, SASWeaponFlag::HandGrenade | SASWeaponFlag::Flashbang))
{
// find feet
if (RANDOM_LONG(0, 1))
{
// magically know where they are
vecTarget = Vector(m_hEnemy->pev->origin.x, m_hEnemy->pev->origin.y, m_hEnemy->pev->absmin.z);
}
else
{
// toss it to where you last saw them
vecTarget = m_vecEnemyLKP;
}
// vecTarget = m_vecEnemyLKP + (m_hEnemy->BodyTarget( pev->origin ) - m_hEnemy->pev->origin);
// estimate position
// vecTarget = vecTarget + m_hEnemy->pev->velocity * 2;
}
else
{
// find target
// vecTarget = m_hEnemy->BodyTarget( pev->origin );
vecTarget = m_vecEnemyLKP + (m_hEnemy->BodyTarget(pev->origin) - m_hEnemy->pev->origin);
// estimate position
if (HasConditions(bits_COND_SEE_ENEMY))
vecTarget = vecTarget + ((vecTarget - pev->origin).Length() / gSkillData.SASGrenadeSpeed) * m_hEnemy->pev->velocity;
}
// are any of my squad members near the intended grenade impact area?
if (InSquad())
{
if (SquadMemberInRange(vecTarget, 256))
{
// crap, I might blow my own guy up. Don't throw a grenade and don't check again for a while.
m_flNextGrenadeCheck = gpGlobals->time + 1; // one full second.
m_fThrowGrenade = FALSE;
}
}
if ((vecTarget - pev->origin).Length2D() <= 256)
{
// crap, I don't want to blow myself up
m_flNextGrenadeCheck = gpGlobals->time + 1; // one full second.
m_fThrowGrenade = FALSE;
return m_fThrowGrenade;
}
if (FBitSet(pev->weapons, SASWeaponFlag::HandGrenade | SASWeaponFlag::Flashbang))
{
Vector vecToss = VecCheckToss(pev, GetGunPosition(), vecTarget, 0.5);
if (vecToss != g_vecZero)
{
m_vecTossVelocity = vecToss;
// throw a hand grenade
m_fThrowGrenade = TRUE;
// don't check again for a while.
m_flNextGrenadeCheck = gpGlobals->time; // 1/3 second.
}
else
{
// don't throw
m_fThrowGrenade = FALSE;
// don't check again for a while.
m_flNextGrenadeCheck = gpGlobals->time + 1; // one full second.
}
}
else
{
Vector vecToss = VecCheckThrow(pev, GetGunPosition(), vecTarget, gSkillData.SASGrenadeSpeed, 0.5);
if (vecToss != g_vecZero)
{
m_vecTossVelocity = vecToss;
// throw a hand grenade
m_fThrowGrenade = TRUE;
// don't check again for a while.
m_flNextGrenadeCheck = gpGlobals->time + 0.3; // 1/3 second.
}
else
{
// don't throw
m_fThrowGrenade = FALSE;
// don't check again for a while.
m_flNextGrenadeCheck = gpGlobals->time + 1; // one full second.
}
}
return m_fThrowGrenade;
}
//=========================================================
// TraceAttack - make sure we're not taking it in the helmet
//=========================================================
void CSAS::TraceAttack(entvars_t* pevAttacker, float flDamage, Vector vecDir, TraceResult* ptr, int bitsDamageType)
{
// check for helmet shot
if (ptr->iHitgroup == 11)
{
// make sure we're wearing one
//TODO: disabled for ally
if (/*GetBodygroup( SASBodygroup::Head ) == SASHead::GasMask &&*/ (bitsDamageType & (DMG_BULLET | DMG_SLASH | DMG_CLUB)))
{
// absorb damage
flDamage -= 20;
if (flDamage <= 0)
{
UTIL_Ricochet(ptr->vecEndPos, 1.0);
flDamage = 0.01;
}
}
// it's head shot anyways
ptr->iHitgroup = HITGROUP_HEAD;
}
//PCV absorbs some damage types
else if ((ptr->iHitgroup == HITGROUP_CHEST || ptr->iHitgroup == HITGROUP_STOMACH)
&& (bitsDamageType & (DMG_BLAST | DMG_BULLET | DMG_SLASH)))
{
flDamage *= 0.5;
}
COFSquadTalkMonster::TraceAttack(pevAttacker, flDamage, vecDir, ptr, bitsDamageType);
}
//=========================================================
// TakeDamage - overridden for the grunt because the grunt
// needs to forget that he is in cover if he's hurt. (Obviously
// not in a safe place anymore).
//=========================================================
int CSAS::TakeDamage(entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType)
{
// make sure friends talk about it if player hurts talkmonsters...
int ret = COFSquadTalkMonster::TakeDamage(pevInflictor, pevAttacker, flDamage, bitsDamageType);
if (pev->deadflag != DEAD_NO)
return ret;
Forget(bits_MEMORY_INCOVER);
if (m_MonsterState != MONSTERSTATE_PRONE && (pevAttacker->flags & FL_CLIENT))
{
m_flPlayerDamage += flDamage;
// This is a heurstic to determine if the player intended to harm me
// If I have an enemy, we can't establish intent (may just be crossfire)
if (m_hEnemy == nullptr)
{
// Hey, be careful with that
Remember(bits_MEMORY_SUSPICIOUS);
if (GetCount() < 2)
{
PlaySentence("SAS_FSHOT", 4, VOL_NORM, ATTN_NORM);
}
if (4.0 > gpGlobals->time - m_flLastHitByPlayer)
++m_iPlayerHits;
else
m_iPlayerHits = 0;
m_flLastHitByPlayer = gpGlobals->time;
ALERT(at_console, "HGrunt Ally is now SUSPICIOUS!\n");
}
else if (!m_hEnemy->IsPlayer())
{
PlaySentence("SAS_SHOT", 4, VOL_NORM, ATTN_NORM);
}
}
return ret;
}
//=========================================================
// SetYawSpeed - allows each sequence to have a different
// turn rate associated with it.
//=========================================================
void CSAS::SetYawSpeed()
{
int ys;
switch (m_Activity)
{
case ACT_IDLE:
ys = 150;
break;
case ACT_RUN:
ys = 150;
break;
case ACT_WALK:
ys = 180;
break;
case ACT_RANGE_ATTACK1:
ys = 120;
break;
case ACT_RANGE_ATTACK2:
ys = 120;
break;
case ACT_MELEE_ATTACK1:
ys = 120;
break;
case ACT_MELEE_ATTACK2:
ys = 120;
break;
case ACT_TURN_LEFT:
case ACT_TURN_RIGHT:
ys = 180;
break;
case ACT_GLIDE:
case ACT_FLY:
ys = 30;
break;
default:
ys = 90;
break;
}
pev->yaw_speed = ys;
}
int CSAS::GetCount()
{
CBaseEntity* pMate = nullptr;
int totCount = 0;
while ((pMate = UTIL_FindEntityByClassname(pMate, "monster_sas")) != nullptr)
{
ALERT(at_console, "Found one. Count is now %d\n", totCount);
totCount += pMate->IsAlive();
}
ALERT(at_console, "Finished. Returning %d", totCount);
return totCount;
}
void CSAS::IdleSound()
{
if (FOkToSpeak() && (g_fGruntAllyQuestion || RANDOM_LONG(0, 1)))
{
if (!g_fGruntAllyQuestion)
{
//ALERT(at_console, "\n - %s - %s - \n", m_canLoseSquad ? "true" : "false", m_canSayUsLeft ? "true" : "false");
if (m_canSayUsLeft > 1 && m_canLoseSquad && GetCount() == 2)
{
PlaySentence("SAS_GONBD", 4, VOL_NORM, ATTN_NORM);
m_canSayUsLeft--;
}
else if (m_canSayUsLeft > 0 && m_canLoseSquad && GetCount() < 2)
{
// Its just us left
SENTENCEG_PlayRndSz(ENT(pev), "SAS_JULSN", HSAS_SENTENCE_VOLUME, ATTN_NORM, 0, m_voicePitch);
m_canSayUsLeft--;
}
else if (m_canLoseSquad && GetCount() < 2 && RANDOM_LONG(0, 2) == 2)
{
// I wish my friends was here
SENTENCEG_PlayRndSz(ENT(pev), "SAS_MOURN", HSAS_SENTENCE_VOLUME, ATTN_NORM, 0, m_voicePitch);
}
else
{
// ask question or make statement
switch (RANDOM_LONG(0, 2))
{
case 0: // check in
SENTENCEG_PlayRndSz(ENT(pev), "SAS_CHECK", HSAS_SENTENCE_VOLUME, ATTN_NORM, 0, m_voicePitch);
g_fGruntAllyQuestion = 1;
break;
case 1: // question
SENTENCEG_PlayRndSz(ENT(pev), "SAS_QUEST", HSAS_SENTENCE_VOLUME, ATTN_NORM, 0, m_voicePitch);
g_fGruntAllyQuestion = 2;
break;
case 2: // statement
SENTENCEG_PlayRndSz(ENT(pev), "SAS_IDLE", HSAS_SENTENCE_VOLUME, ATTN_NORM, 0, m_voicePitch);
break;
}
}
}
else
{
switch (g_fGruntAllyQuestion)
{
case 1: // check in
SENTENCEG_PlayRndSz(ENT(pev), "SAS_CLEAR", HSAS_SENTENCE_VOLUME, ATTN_NORM, 0, m_voicePitch);
break;
case 2: // question
SENTENCEG_PlayRndSz(ENT(pev), "SAS_ANSWER", HSAS_SENTENCE_VOLUME, ATTN_NORM, 0, m_voicePitch);
break;
}
g_fGruntAllyQuestion = 0;
}
JustSpoke();
}
}
//=========================================================
// CheckAmmo - overridden for the grunt because he actually
// uses ammo! (base class doesn't)
//=========================================================
void CSAS::CheckAmmo()
{
if (m_cAmmoLoaded <= 0)
{
SetConditions(bits_COND_NO_AMMO_LOADED);
}
}
//=========================================================
// Classify - indicates this monster's place in the
// relationship table.
//=========================================================
int CSAS::Classify()
{
return m_iClass?m_iClass:CLASS_PLAYER_ALLY;
}
//=========================================================
//=========================================================
CBaseEntity* CSAS::Kick()
{
TraceResult tr;
UTIL_MakeVectors(pev->angles);
Vector vecStart = pev->origin;
vecStart.z += pev->size.z * 0.5;
Vector vecEnd = vecStart + (gpGlobals->v_forward * 70);
UTIL_TraceHull(vecStart, vecEnd, dont_ignore_monsters, head_hull, ENT(pev), &tr);
if (tr.pHit)
{
CBaseEntity* pEntity = CBaseEntity::Instance(tr.pHit);
return pEntity;
}
return nullptr;
}
//=========================================================
// GetGunPosition return the end of the barrel
//=========================================================
Vector CSAS::GetGunPosition()
{
if (m_fStanding)
{
return pev->origin + Vector(0, 0, 60);
}
else
{
return pev->origin + Vector(0, 0, 48);
}
}
//=========================================================
// Shoot
//=========================================================
void CSAS::Shoot()
{
if (m_hEnemy == nullptr)
{
return;
}
Vector vecShootOrigin = GetGunPosition();
Vector vecShootDir = ShootAtEnemy(vecShootOrigin);
UTIL_MakeVectors(pev->angles);
Vector vecShellVelocity = gpGlobals->v_right * RANDOM_FLOAT(40, 90) + gpGlobals->v_up * RANDOM_FLOAT(75, 200) + gpGlobals->v_forward * RANDOM_FLOAT(-40, 40);
EjectBrass(vecShootOrigin - vecShootDir * 24, vecShellVelocity, pev->angles.y, m_iBrassShell, TE_BOUNCE_SHELL);
FireBullets(1, vecShootOrigin, vecShootDir, VECTOR_CONE_10DEGREES, 2048, BULLET_MONSTER_MP5); // shoot +-5 degrees
pev->effects |= EF_MUZZLEFLASH;
m_cAmmoLoaded--;// take away a bullet!
Vector angDir = UTIL_VecToAngles(vecShootDir);
SetBlending(0, angDir.x);
}
//=========================================================
// Shoot
//=========================================================
void CSAS::Shotgun()
{
if (m_hEnemy == nullptr)
{
return;
}
Vector vecShootOrigin = GetGunPosition();
Vector vecShootDir = ShootAtEnemy(vecShootOrigin);
UTIL_MakeVectors(pev->angles);
Vector vecShellVelocity = gpGlobals->v_right * RANDOM_FLOAT(40, 90) + gpGlobals->v_up * RANDOM_FLOAT(75, 200) + gpGlobals->v_forward * RANDOM_FLOAT(-40, 40);
EjectBrass(vecShootOrigin - vecShootDir * 24, vecShellVelocity, pev->angles.y, m_iShotgunShell, TE_BOUNCE_SHOTSHELL);
FireBullets(gSkillData.SASShotgunPellets, vecShootOrigin, vecShootDir, VECTOR_CONE_15DEGREES, 2048, BULLET_PLAYER_BUCKSHOT, 0); // shoot +-7.5 degrees
pev->effects |= EF_MUZZLEFLASH;
m_cAmmoLoaded--;// take away a bullet!
Vector angDir = UTIL_VecToAngles(vecShootDir);
SetBlending(0, angDir.x);
}
void CSAS::ShootAR16()
{
if (m_hEnemy == nullptr)
{
return;
}
Vector vecShootOrigin = GetGunPosition();
Vector vecShootDir = ShootAtEnemy(vecShootOrigin);
UTIL_MakeVectors(pev->angles);
switch (RANDOM_LONG(0, 1))
{
case 0:
{
auto vecShellVelocity = gpGlobals->v_right * RANDOM_FLOAT(75, 200) + gpGlobals->v_up * RANDOM_FLOAT(150, 200) + gpGlobals->v_forward * 25.0;
EjectBrass(vecShootOrigin - vecShootDir * 6, vecShellVelocity, pev->angles.y, m_iAR16Link, TE_BOUNCE_SHELL);
break;
}
case 1:
{
auto vecShellVelocity = gpGlobals->v_right * RANDOM_FLOAT(100, 250) + gpGlobals->v_up * RANDOM_FLOAT(100, 150) + gpGlobals->v_forward * 25.0;
EjectBrass(vecShootOrigin - vecShootDir * 6, vecShellVelocity, pev->angles.y, m_iAR16Shell, TE_BOUNCE_SHELL);
break;
}
}
FireBullets(1, vecShootOrigin, vecShootDir, VECTOR_CONE_5DEGREES, 8192, BULLET_PLAYER_556, 2); // shoot +-5 degrees
switch (RANDOM_LONG(0, 2))
{
case 0: EMIT_SOUND_DYN(edict(), CHAN_WEAPON, "weapons/AR16_fire1.wav", VOL_NORM, ATTN_NORM, 0, RANDOM_LONG(0, 15) + 94); break;
case 1: EMIT_SOUND_DYN(edict(), CHAN_WEAPON, "weapons/AR16_fire2.wav", VOL_NORM, ATTN_NORM, 0, RANDOM_LONG(0, 15) + 94); break;
case 2: EMIT_SOUND_DYN(edict(), CHAN_WEAPON, "weapons/AR16_fire3.wav", VOL_NORM, ATTN_NORM, 0, RANDOM_LONG(0, 15) + 94); break;
}
pev->effects |= EF_MUZZLEFLASH;
m_cAmmoLoaded--;// take away a bullet!
Vector angDir = UTIL_VecToAngles(vecShootDir);
SetBlending(0, angDir.x);
}
//=========================================================
// HandleAnimEvent - catches the monster-specific messages
// that occur when tagged animation frames are played.
//=========================================================
void CSAS::HandleAnimEvent(MonsterEvent_t* pEvent)
{
Vector vecShootDir;
Vector vecShootOrigin;
switch (pEvent->event)
{
case HSAS_AE_DROP_GUN:
{
Vector vecGunPos;
Vector vecGunAngles;
GetAttachment(0, vecGunPos, vecGunAngles);
// switch to body group with no gun.
SetBodygroup(SASBodygroup::Weapons, SASWeapon::None);
// now spawn a gun.
if (FBitSet(pev->weapons, SASWeaponFlag::Shotgun))
{
DropItem("weapon_shotgun", vecGunPos, vecGunAngles);
}
else if (FBitSet(pev->weapons, SASWeaponFlag::AR16))
{
DropItem("weapon_ar16", vecGunPos, vecGunAngles);
}
else
{
DropItem("weapon_9mmAR", vecGunPos, vecGunAngles);
}
if (FBitSet(pev->weapons, SASWeaponFlag::GrenadeLauncher))
{
DropItem("ammo_ARgrenades", BodyTarget(pev->origin), vecGunAngles);
}
m_iWeaponIdx = SASWeapon::None;
}
break;
case HSAS_AE_RELOAD_SOUND:
if (FBitSet(pev->weapons, SASWeaponFlag::AR16))
EMIT_SOUND(ENT(pev), CHAN_WEAPON, "weapons/AR16_reload.wav", 1, ATTN_NORM);
else if (FBitSet(pev->weapons, SASWeaponFlag::Shotgun))
EMIT_SOUND(ENT(pev), CHAN_WEAPON, "hgrunt/gr_shotgunrlod.wav", 1, ATTN_NORM);
else
EMIT_SOUND(ENT(pev), CHAN_WEAPON, "hgrunt/gr_reload1.wav", 1, ATTN_NORM);
break;
case HSAS_AE_RELOAD:
m_cAmmoLoaded = m_cClipSize;
ClearConditions(bits_COND_NO_AMMO_LOADED);
break;
case HSAS_AE_GREN_TOSS:
{
UTIL_MakeVectors(pev->angles);
// CGrenade::ShootTimed( pev, pev->origin + gpGlobals->v_forward * 34 + Vector (0, 0, 32), m_vecTossVelocity, 3.5 );
if (FBitSet(pev->weapons, SASWeaponFlag::Flashbang) && FBitSet(pev->weapons, SASWeaponFlag::HandGrenade))
{
switch (RANDOM_LONG(0, 1))
{
case 0:
CGrenade::ShootStun(pev, GetGunPosition(), m_vecTossVelocity, 2.5);
ClearSchedule();
ChangeSchedule(GetScheduleOfType(SCHED_TAKE_COVER_FROM_ENEMY));
break;
case 1:
CGrenade::ShootTimed(pev, GetGunPosition(), m_vecTossVelocity, 3.5);
break;
}
}
else if (FBitSet(pev->weapons, SASWeaponFlag::Flashbang))
{
CGrenade::ShootStun(pev, GetGunPosition(), m_vecTossVelocity, 2.5);
ClearSchedule();
ChangeSchedule(GetScheduleOfType(SCHED_TAKE_COVER_FROM_ENEMY));
}
else
CGrenade::ShootTimed(pev, GetGunPosition(), m_vecTossVelocity, 3.5);
m_fThrowGrenade = FALSE;
m_flNextGrenadeCheck = gpGlobals->time + 6;// wait six seconds before even looking again to see if a grenade can be thrown.
// !!!LATER - when in a group, only try to throw grenade if ordered.
}
break;
case HSAS_AE_GREN_LAUNCH:
{
EMIT_SOUND(ENT(pev), CHAN_WEAPON, "weapons/glauncher.wav", 0.8, ATTN_NORM);
CGrenade::ShootContact(pev, GetGunPosition(), m_vecTossVelocity);
m_fThrowGrenade = FALSE;
if (g_iSkillLevel == SKILL_HARD)
m_flNextGrenadeCheck = gpGlobals->time + RANDOM_FLOAT(2, 5);// wait a random amount of time before shooting again
else
m_flNextGrenadeCheck = gpGlobals->time + 6;// wait six seconds before even looking again to see if a grenade can be thrown.
}
break;
case HSAS_AE_GREN_DROP:
{
UTIL_MakeVectors(pev->angles);
CGrenade::ShootTimed(pev, pev->origin + gpGlobals->v_forward * 17 - gpGlobals->v_right * 27 + gpGlobals->v_up * 6, g_vecZero, 3);
}
break;
case HSAS_AE_BURST1:
{
if (FBitSet(pev->weapons, SASWeaponFlag::MP5))
{
Shoot();
// the first round of the three round burst plays the sound and puts a sound in the world sound list.
if (RANDOM_LONG(0, 1))
{
EMIT_SOUND(ENT(pev), CHAN_WEAPON, "hgrunt/gr_mgun1.wav", 1, ATTN_NORM);
}
else
{
EMIT_SOUND(ENT(pev), CHAN_WEAPON, "hgrunt/gr_mgun2.wav", 1, ATTN_NORM);
}
}
else if (FBitSet(pev->weapons, SASWeaponFlag::AR16))
{
ShootAR16();
}
else
{
Shotgun();
EMIT_SOUND(ENT(pev), CHAN_WEAPON, "hgrunt/gr_shotgunfire.wav", 1, ATTN_NORM);
}
CSoundEnt::InsertSound(bits_SOUND_COMBAT, pev->origin, 384, 0.3);
}
break;
case HSAS_AE_BURST2:
case HSAS_AE_BURST3:
if (FBitSet(pev->weapons, SASWeaponFlag::MP5))
{
Shoot();
}
else if (FBitSet(pev->weapons, SASWeaponFlag::AR16))
{
ShootAR16();
}
break;
case HSAS_AE_KICK:
{
CBaseEntity* pHurt = Kick();
if (pHurt)
{
// SOUND HERE!
UTIL_MakeVectors(pev->angles);
pHurt->pev->punchangle.x = 15;
pHurt->pev->velocity = pHurt->pev->velocity + gpGlobals->v_forward * 100 + gpGlobals->v_up * 50;
pHurt->TakeDamage(pev, pev, gSkillData.SASDmgKick, DMG_CLUB);
}
}
break;
case HSAS_AE_CAUGHT_ENEMY:
{
if (FOkToSpeak())
{
SENTENCEG_PlayRndSz(ENT(pev), "SAS_ALERT", HSAS_SENTENCE_VOLUME, SAS_ATTN, 0, m_voicePitch);
JustSpoke();
}
}
default:
COFSquadTalkMonster::HandleAnimEvent(pEvent);
break;
}
}
void CSAS::BeStunned(float stunTime)
{
//SAS can't be stunned too long because of their helmets and masks
m_canCancelStun = true;
return CBaseMonster::BeStunned(stunTime / 6.0f);
}
//=========================================================
// Spawn
//=========================================================
void CSAS::Spawn()
{
Precache();
SET_MODEL(ENT(pev), "models/sas.mdl");
UTIL_SetSize(pev, VEC_HUMAN_HULL_MIN, VEC_HUMAN_HULL_MAX);
pev->solid = SOLID_SLIDEBOX;
pev->movetype = MOVETYPE_STEP;
m_bloodColor = BLOOD_COLOR_RED;
pev->effects = 0;
pev->health = gSkillData.SASHealth;
m_flFieldOfView = 0.2;// indicates the width of this monster's forward view cone ( as a dotproduct result )
m_MonsterState = MONSTERSTATE_NONE;
m_flNextGrenadeCheck = gpGlobals->time + 1;
m_flNextPainTime = gpGlobals->time;
m_iSentence = HSAS_SENT_NONE;
m_deadMates = 0;
m_afCapability = bits_CAP_SQUAD | bits_CAP_TURN_HEAD | bits_CAP_DOORS_GROUP | bits_CAP_HEAR;
m_fEnemyEluded = FALSE;
m_fFirstEncounter = TRUE;// this is true when the grunt spawns, because he hasn't encountered an enemy yet.
m_HackedGunPos = Vector(0, 0, 55);
m_canSayUsLeft = 2;
//Note: this code has been rewritten to use SetBodygroup since it relies on hardcoded offsets in the original
pev->body = 0;
m_iGruntTorso = SASTorso::Normal;
if (pev->weapons & SASWeaponFlag::MP5)
{
m_iWeaponIdx = SASWeapon::MP5;
m_cClipSize = SAS_MP5_CLIP_SIZE;
pev->controller[1] = 255;
}
else if (pev->weapons & SASWeaponFlag::Shotgun)
{
m_cClipSize = SAS_SHOTGUN_CLIP_SIZE;
m_iWeaponIdx = SASWeapon::Shotgun;
m_iGruntTorso = SASTorso::Shotgun;
pev->controller[1] = 0;
}
else if (pev->weapons & SASWeaponFlag::AR16)
{
// Randomize Weapons If AR
switch (RANDOM_LONG(1,6))
{
case 1:
pev->weapons = SASWeaponFlag::AR16 | SASWeaponFlag::HandGrenade;
break;
case 2:
pev->weapons = SASWeaponFlag::AR16 | SASWeaponFlag::Flashbang | SASWeaponFlag::GrenadeLauncher;
break;
case 3:
pev->weapons = SASWeaponFlag::AR16 | SASWeaponFlag::Flashbang;
break;
case 4:
pev->weapons = SASWeaponFlag::AR16 | SASWeaponFlag::HandGrenade;
break;
case 5:
pev->weapons = SASWeaponFlag::AR16 | SASWeaponFlag::HandGrenade | SASWeaponFlag::Flashbang;
break;
case 6:
pev->weapons = SASWeaponFlag::AR16; // Sad Boi
break;
}
m_iWeaponIdx = SASWeapon::AR16;
m_cClipSize = SAS_AR16_CLIP_SIZE;
m_iGruntTorso = SASTorso::AR16;
pev->controller[1] = 0;
}
else
{
m_iWeaponIdx = SASWeapon::None;
m_cClipSize = 0;
}
m_cAmmoLoaded = m_cClipSize;
/*
if (m_iGruntHead == SASHead::Default)
{
if (pev->spawnflags & SF_SQUADMONSTER_LEADER)
{
m_iGruntHead = SASHead::BeretWhite;
}
else if (m_iWeaponIdx == SASWeapon::Shotgun)
{
m_iGruntHead = SASHead::OpsMask;
}
else if (m_iWeaponIdx == SASWeapon::AR16)
{
m_iGruntHead = RANDOM_LONG(0, 1) + SASHead::BandanaWhite;
}
else if (m_iWeaponIdx == SASWeapon::MP5)
{
m_iGruntHead = SASHead::MilitaryPolice;
}
else
{
m_iGruntHead = SASHead::GasMask;
}
}
*/
//TODO: probably also needs this for head SASHead::BeretBlack
//if (m_iGruntHead == SASHead::OpsMask || m_iGruntHead == SASHead::BandanaBlack)
// m_voicePitch = 90;
//Random Skin
if (pev->skin == -1 && pev->spawnflags & SF_SQUADMONSTER_LEADER)
{
pev->skin = SASSkin::LeaderScot;
m_iGruntHead = SASHead::Leader;
}
else
{
pev->skin = RANDOM_LONG(1, SASSkin::SKINCOUNT_SOLDIERS);
m_iGruntHead = SASHead::GasMask;
}
// get voice pitch
if (RANDOM_LONG(0, 1) && !(pev->spawnflags & SF_SQUADMONSTER_LEADER))
{
m_voicePitch = 100 + RANDOM_LONG(0, 18);
}
else
{
m_voicePitch = 100;
}
SetBodygroup(SASBodygroup::Head, m_iGruntHead);
//SetBodygroup(SASBodygroup::Torso, m_iGruntTorso); // Theres just one torso
SetBodygroup(SASBodygroup::Weapons, m_iWeaponIdx);
m_iAR16Shell = PRECACHE_MODEL("models/556shell.mdl");
//m_iAR16Link = PRECACHE_MODEL("models/AR16_link.mdl");
COFAllyMonster::g_talkWaitTime = 0;
m_flMedicWaitTime = gpGlobals->time;
MonsterInit();
SetUse(&CSAS::FollowerUse);
}
//=========================================================
// Precache - precaches all resources this monster needs
//=========================================================
void CSAS::Precache()
{
PRECACHE_MODEL("models/sas.mdl");
TalkInit();
PRECACHE_SOUND("hgrunt/gr_mgun1.wav");
PRECACHE_SOUND("hgrunt/gr_mgun2.wav");
PRECACHE_SOUND("sas/ct_death01.wav");
PRECACHE_SOUND("sas/ct_death02.wav");
PRECACHE_SOUND("sas/ct_death03.wav");
PRECACHE_SOUND("sas/ct_death04.wav");
PRECACHE_SOUND("sas/ct_death05.wav");
PRECACHE_SOUND("sas/ct_death06.wav");
PRECACHE_SOUND("fgrunt/pain1.wav");
PRECACHE_SOUND("fgrunt/pain2.wav");
PRECACHE_SOUND("fgrunt/pain3.wav");
PRECACHE_SOUND("fgrunt/pain4.wav");
PRECACHE_SOUND("fgrunt/pain5.wav");
PRECACHE_SOUND("fgrunt/pain6.wav");
PRECACHE_SOUND("hgrunt/gr_reload1.wav");
PRECACHE_SOUND("weapons/AR16_fire1.wav");
PRECACHE_SOUND("weapons/AR16_fire2.wav");
PRECACHE_SOUND("weapons/AR16_fire3.wav");
PRECACHE_SOUND("weapons/AR16_reload.wav");
PRECACHE_SOUND("weapons/glauncher.wav");
PRECACHE_SOUND("hgrunt/gr_shotgunfire.wav");
PRECACHE_SOUND("hgrunt/gr_shotgunrlod.wav");
PRECACHE_SOUND("sas/help04.wav");
PRECACHE_SOUND("zombie/claw_miss2.wav");// because we use the basemonster SWIPE animation event
m_iBrassShell = PRECACHE_MODEL("models/shell.mdl");// brass shell
m_iShotgunShell = PRECACHE_MODEL("models/shotgunshell.mdl");
COFSquadTalkMonster::Precache();
}
//=========================================================
// start task
//=========================================================
void CSAS::StartTask(Task_t* pTask)
{
m_iTaskStatus = TASKSTATUS_RUNNING;
switch (pTask->iTask)
{
case TASK_SAS_CHECK_FIRE:
if (!NoFriendlyFire())
{
SetConditions(bits_COND_SAS_NOFIRE);
}
TaskComplete();
break;
case TASK_SAS_SPEAK_SENTENCE:
SpeakSentence();
TaskComplete();
break;
case TASK_WALK_PATH:
case TASK_RUN_PATH:
// grunt no longer assumes he is covered if he moves
Forget(bits_MEMORY_INCOVER);
COFSquadTalkMonster::StartTask(pTask);
break;
case TASK_RELOAD:
m_IdealActivity = ACT_RELOAD;
break;
case TASK_SAS_FACE_TOSS_DIR:
break;
case TASK_FACE_IDEAL:
case TASK_FACE_ENEMY:
COFSquadTalkMonster::StartTask(pTask);
if (pev->movetype == MOVETYPE_FLY)
{
m_IdealActivity = ACT_GLIDE;
}
break;
default:
COFSquadTalkMonster::StartTask(pTask);
break;
}
}
//=========================================================
// RunTask
//=========================================================
void CSAS::RunTask(Task_t* pTask)
{
switch (pTask->iTask)
{
case TASK_SAS_FACE_TOSS_DIR:
{
// project a point along the toss vector and turn to face that point.
MakeIdealYaw(pev->origin + m_vecTossVelocity * 64);
ChangeYaw(pev->yaw_speed);
if (FacingIdeal())
{
m_iTaskStatus = TASKSTATUS_COMPLETE;
}
break;
}
default:
{
COFSquadTalkMonster::RunTask(pTask);
break;
}
}
}
//=========================================================
// PainSound
//=========================================================
void CSAS::PainSound()
{
if (gpGlobals->time > m_flNextPainTime)
{
#if 0
if (RANDOM_LONG(0, 99) < 5)
{
// pain sentences are rare
if (FOkToSpeak())
{
//SENTENCEG_PlayRndSz(ENT(pev), "SAS_PAIN", HSAS_SENTENCE_VOLUME, ATTN_NORM, 0, PITCH_NORM);
JustSpoke();
return;
}
}
#endif
/*
switch (RANDOM_LONG(0, 7))
{
case 0:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "fgrunt/pain3.wav", 1, ATTN_NORM);
break;
case 1:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "fgrunt/pain4.wav", 1, ATTN_NORM);
break;
case 2:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "fgrunt/pain5.wav", 1, ATTN_NORM);
break;
case 3:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "fgrunt/pain1.wav", 1, ATTN_NORM);
break;
case 4:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "fgrunt/pain2.wav", 1, ATTN_NORM);
break;
case 5:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "fgrunt/pain6.wav", 1, ATTN_NORM);
break;
}
*/
m_flNextPainTime = gpGlobals->time + 1;
}
}
//=========================================================
// DeathSound
//=========================================================
void CSAS::DeathSound()
{
//TODO: these sounds don't exist, the gr_ prefix is wrong
switch (RANDOM_LONG(0, 5))
{
case 0:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "sas/ct_death01.wav", 1, ATTN_IDLE);
break;
case 1:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "sas/ct_death02.wav", 1, ATTN_IDLE);
break;
case 2:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "sas/ct_death03.wav", 1, ATTN_IDLE);
break;
case 3:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "sas/ct_death04.wav", 1, ATTN_IDLE);
break;
case 4:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "sas/ct_death05.wav", 1, ATTN_IDLE);
break;
case 5:
EMIT_SOUND(ENT(pev), CHAN_VOICE, "sas/ct_death06.wav", 1, ATTN_IDLE);
break;
}
}
//=========================================================
// AI Schedules Specific to this monster
//=========================================================
//=========================================================
// GruntFail
//=========================================================
Task_t tlGruntAllyFail[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_WAIT, (float)2 },
{ TASK_WAIT_PVS, (float)0 },
};
Schedule_t slGruntAllyFail[] =
{
{
tlGruntAllyFail,
ARRAYSIZE(tlGruntAllyFail),
bits_COND_CAN_RANGE_ATTACK1 |
bits_COND_CAN_RANGE_ATTACK2 |
bits_COND_CAN_MELEE_ATTACK1 |
bits_COND_CAN_MELEE_ATTACK2,
0,
"Grunt Fail"
},
};
//=========================================================
// Grunt Combat Fail
//=========================================================
Task_t tlGruntAllyCombatFail[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_WAIT_FACE_ENEMY, (float)2 },
{ TASK_WAIT_PVS, (float)0 },
};
Schedule_t slGruntAllyCombatFail[] =
{
{
tlGruntAllyCombatFail,
ARRAYSIZE(tlGruntAllyCombatFail),
bits_COND_CAN_RANGE_ATTACK1 |
bits_COND_CAN_RANGE_ATTACK2,
0,
"Grunt Combat Fail"
},
};
//=========================================================
// Victory dance!
//=========================================================
Task_t tlGruntAllyVictoryDance[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_WAIT, (float)1.5 },
{ TASK_GET_PATH_TO_ENEMY_CORPSE, (float)0 },
{ TASK_WALK_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_VICTORY_DANCE },
};
Schedule_t slGruntAllyVictoryDance[] =
{
{
tlGruntAllyVictoryDance,
ARRAYSIZE(tlGruntAllyVictoryDance),
bits_COND_NEW_ENEMY |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE,
0,
"GruntVictoryDance"
},
};
//=========================================================
// Establish line of fire - move to a position that allows
// the grunt to attack.
//=========================================================
Task_t tlGruntAllyEstablishLineOfFire[] =
{
{ TASK_SET_FAIL_SCHEDULE, (float)SCHED_SAS_ELOF_FAIL },
{ TASK_GET_PATH_TO_ENEMY, (float)0 },
{ TASK_SAS_SPEAK_SENTENCE,(float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
};
Schedule_t slGruntAllyEstablishLineOfFire[] =
{
{
tlGruntAllyEstablishLineOfFire,
ARRAYSIZE(tlGruntAllyEstablishLineOfFire),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_CAN_RANGE_ATTACK1 |
bits_COND_CAN_MELEE_ATTACK1 |
bits_COND_CAN_RANGE_ATTACK2 |
bits_COND_CAN_MELEE_ATTACK2 |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"GruntEstablishLineOfFire"
},
};
//=========================================================
// GruntFoundEnemy - grunt established sight with an enemy
// that was hiding from the squad.
//=========================================================
Task_t tlGruntAllyFoundEnemy[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_PLAY_SEQUENCE_FACE_ENEMY,(float)ACT_SIGNAL1 },
};
Schedule_t slGruntAllyFoundEnemy[] =
{
{
tlGruntAllyFoundEnemy,
ARRAYSIZE(tlGruntAllyFoundEnemy),
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"GruntFoundEnemy"
},
};
//=========================================================
// GruntCombatFace Schedule
//=========================================================
Task_t tlGruntAllyCombatFace1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_WAIT, (float)1.5 },
{ TASK_SET_SCHEDULE, (float)SCHED_SAS_SWEEP },
};
Schedule_t slGruntAllyCombatFace[] =
{
{
tlGruntAllyCombatFace1,
ARRAYSIZE(tlGruntAllyCombatFace1),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_CAN_RANGE_ATTACK1 |
bits_COND_CAN_RANGE_ATTACK2,
0,
"Combat Face"
},
};
//=========================================================
// Suppressing fire - don't stop shooting until the clip is
// empty or grunt gets hurt.
//=========================================================
Task_t tlGruntAllySignalSuppress[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_IDEAL, (float)0 },
{ TASK_PLAY_SEQUENCE_FACE_ENEMY, (float)ACT_SIGNAL2 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
};
Schedule_t slGruntAllySignalSuppress[] =
{
{
tlGruntAllySignalSuppress,
ARRAYSIZE(tlGruntAllySignalSuppress),
bits_COND_ENEMY_DEAD |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND |
bits_COND_SAS_NOFIRE |
bits_COND_NO_AMMO_LOADED,
bits_SOUND_DANGER,
"SignalSuppress"
},
};
Task_t tlGruntAllySuppress[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
};
Schedule_t slGruntAllySuppress[] =
{
{
tlGruntAllySuppress,
ARRAYSIZE(tlGruntAllySuppress),
bits_COND_ENEMY_DEAD |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND |
bits_COND_SAS_NOFIRE |
bits_COND_NO_AMMO_LOADED,
bits_SOUND_DANGER,
"Suppress"
},
};
//=========================================================
// grunt wait in cover - we don't allow danger or the ability
// to attack to break a grunt's run to cover schedule, but
// when a grunt is in cover, we do want them to attack if they can.
//=========================================================
Task_t tlGruntAllyWaitInCover[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_WAIT_FACE_ENEMY, (float)1 },
};
Schedule_t slGruntAllyWaitInCover[] =
{
{
tlGruntAllyWaitInCover,
ARRAYSIZE(tlGruntAllyWaitInCover),
bits_COND_NEW_ENEMY |
bits_COND_HEAR_SOUND |
bits_COND_CAN_RANGE_ATTACK1 |
bits_COND_CAN_RANGE_ATTACK2 |
bits_COND_CAN_MELEE_ATTACK1 |
bits_COND_CAN_MELEE_ATTACK2,
bits_SOUND_DANGER,
"GruntWaitInCover"
},
};
//=========================================================
// run to cover.
// !!!BUGBUG - set a decent fail schedule here.
//=========================================================
Task_t tlGruntAllyTakeCover1[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_SET_FAIL_SCHEDULE, (float)SCHED_SAS_TAKECOVER_FAILED },
{ TASK_WAIT, (float)0.2 },
{ TASK_FIND_COVER_FROM_ENEMY, (float)0 },
{ TASK_SAS_SPEAK_SENTENCE, (float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_REMEMBER, (float)bits_MEMORY_INCOVER },
{ TASK_SET_SCHEDULE, (float)SCHED_SAS_WAIT_FACE_ENEMY },
};
Schedule_t slGruntAllyTakeCover[] =
{
{
tlGruntAllyTakeCover1,
ARRAYSIZE(tlGruntAllyTakeCover1),
0,
0,
"TakeCover"
},
};
//=========================================================
// drop grenade then run to cover.
//=========================================================
Task_t tlGruntAllyGrenadeCover1[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_FIND_COVER_FROM_ENEMY, (float)99 },
{ TASK_FIND_FAR_NODE_COVER_FROM_ENEMY, (float)384 },
{ TASK_PLAY_SEQUENCE, (float)ACT_SPECIAL_ATTACK1 },
{ TASK_CLEAR_MOVE_WAIT, (float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_SET_SCHEDULE, (float)SCHED_SAS_WAIT_FACE_ENEMY },
};
Schedule_t slGruntAllyGrenadeCover[] =
{
{
tlGruntAllyGrenadeCover1,
ARRAYSIZE(tlGruntAllyGrenadeCover1),
0,
0,
"GrenadeCover"
},
};
//=========================================================
// drop grenade then run to cover.
//=========================================================
Task_t tlGruntAllyTossGrenadeCover1[] =
{
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_RANGE_ATTACK2, (float)0 },
{ TASK_SET_SCHEDULE, (float)SCHED_TAKE_COVER_FROM_ENEMY },
};
Schedule_t slGruntAllyTossGrenadeCover[] =
{
{
tlGruntAllyTossGrenadeCover1,
ARRAYSIZE(tlGruntAllyTossGrenadeCover1),
0,
0,
"TossGrenadeCover"
},
};
//=========================================================
// hide from the loudest sound source (to run from grenade)
//=========================================================
Task_t tlGruntAllyTakeCoverFromBestSound[] =
{
{ TASK_SET_FAIL_SCHEDULE, (float)SCHED_COWER },// duck and cover if cannot move from explosion
{ TASK_STOP_MOVING, (float)0 },
{ TASK_FIND_COVER_FROM_BEST_SOUND, (float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_REMEMBER, (float)bits_MEMORY_INCOVER },
{ TASK_TURN_LEFT, (float)179 },
};
Schedule_t slGruntAllyTakeCoverFromBestSound[] =
{
{
tlGruntAllyTakeCoverFromBestSound,
ARRAYSIZE(tlGruntAllyTakeCoverFromBestSound),
0,
0,
"GruntTakeCoverFromBestSound"
},
};
//=========================================================
// Grunt reload schedule
//=========================================================
Task_t tlGruntAllyHideReload[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_SET_FAIL_SCHEDULE, (float)SCHED_RELOAD },
{ TASK_FIND_COVER_FROM_ENEMY, (float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_REMEMBER, (float)bits_MEMORY_INCOVER },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_RELOAD },
};
Schedule_t slGruntAllyHideReload[] =
{
{
tlGruntAllyHideReload,
ARRAYSIZE(tlGruntAllyHideReload),
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"GruntHideReload"
}
};
//=========================================================
// Do a turning sweep of the area
//=========================================================
Task_t tlGruntAllySweep[] =
{
{ TASK_TURN_LEFT, (float)179 },
{ TASK_WAIT, (float)1 },
{ TASK_TURN_LEFT, (float)179 },
{ TASK_WAIT, (float)1 },
};
Schedule_t slGruntAllySweep[] =
{
{
tlGruntAllySweep,
ARRAYSIZE(tlGruntAllySweep),
bits_COND_NEW_ENEMY |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_CAN_RANGE_ATTACK1 |
bits_COND_CAN_RANGE_ATTACK2 |
bits_COND_HEAR_SOUND,
bits_SOUND_WORLD |// sound flags
bits_SOUND_DANGER |
bits_SOUND_PLAYER,
"Grunt Sweep"
},
};
//=========================================================
// primary range attack. Overriden because base class stops attacking when the enemy is occluded.
// grunt's grenade toss requires the enemy be occluded.
//=========================================================
Task_t tlGruntAllyRangeAttack1A[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_PLAY_SEQUENCE_FACE_ENEMY, (float)ACT_CROUCH },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
};
Schedule_t slGruntAllyRangeAttack1A[] =
{
{
tlGruntAllyRangeAttack1A,
ARRAYSIZE(tlGruntAllyRangeAttack1A),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_HEAVY_DAMAGE |
bits_COND_ENEMY_OCCLUDED |
bits_COND_HEAR_SOUND |
bits_COND_SAS_NOFIRE |
bits_COND_NO_AMMO_LOADED,
bits_SOUND_DANGER,
"Range Attack1A"
},
};
//=========================================================
// primary range attack. Overriden because base class stops attacking when the enemy is occluded.
// grunt's grenade toss requires the enemy be occluded.
//=========================================================
Task_t tlGruntAllyRangeAttack1B[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_PLAY_SEQUENCE_FACE_ENEMY,(float)ACT_IDLE_ANGRY },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SAS_CHECK_FIRE, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
};
Schedule_t slGruntAllyRangeAttack1B[] =
{
{
tlGruntAllyRangeAttack1B,
ARRAYSIZE(tlGruntAllyRangeAttack1B),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_HEAVY_DAMAGE |
bits_COND_ENEMY_OCCLUDED |
bits_COND_NO_AMMO_LOADED |
bits_COND_SAS_NOFIRE |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"Range Attack1B"
},
};
//=========================================================
// secondary range attack. Overriden because base class stops attacking when the enemy is occluded.
// grunt's grenade toss requires the enemy be occluded.
//=========================================================
Task_t tlGruntAllyRangeAttack2[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_SAS_FACE_TOSS_DIR, (float)0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_RANGE_ATTACK2 },
{ TASK_SET_SCHEDULE, (float)SCHED_SAS_WAIT_FACE_ENEMY },// don't run immediately after throwing grenade.
};
Schedule_t slGruntAllyRangeAttack2[] =
{
{
tlGruntAllyRangeAttack2,
ARRAYSIZE(tlGruntAllyRangeAttack2),
0,
0,
"RangeAttack2"
},
};
//=========================================================
// repel
//=========================================================
Task_t tlGruntAllyRepel[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_FACE_IDEAL, (float)0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_GLIDE },
};
Schedule_t slGruntAllyRepel[] =
{
{
tlGruntAllyRepel,
ARRAYSIZE(tlGruntAllyRepel),
bits_COND_SEE_ENEMY |
bits_COND_NEW_ENEMY |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER |
bits_SOUND_COMBAT |
bits_SOUND_PLAYER,
"Repel"
},
};
//=========================================================
// repel
//=========================================================
Task_t tlGruntAllyRepelAttack[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_FLY },
};
Schedule_t slGruntAllyRepelAttack[] =
{
{
tlGruntAllyRepelAttack,
ARRAYSIZE(tlGruntAllyRepelAttack),
bits_COND_ENEMY_OCCLUDED,
0,
"Repel Attack"
},
};
//=========================================================
// repel land
//=========================================================
Task_t tlGruntAllyRepelLand[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_LAND },
{ TASK_GET_PATH_TO_LASTPOSITION,(float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_CLEAR_LASTPOSITION, (float)0 },
};
Schedule_t slGruntAllyRepelLand[] =
{
{
tlGruntAllyRepelLand,
ARRAYSIZE(tlGruntAllyRepelLand),
bits_COND_SEE_ENEMY |
bits_COND_NEW_ENEMY |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER |
bits_SOUND_COMBAT |
bits_SOUND_PLAYER,
"Repel Land"
},
};
Task_t tlGruntAllyFollow[] =
{
{ TASK_MOVE_TO_TARGET_RANGE,(float)128 }, // Move within 128 of target ent (client)
{ TASK_SET_SCHEDULE, (float)SCHED_TARGET_FACE },
};
Schedule_t slGruntAllyFollow[] =
{
{
tlGruntAllyFollow,
ARRAYSIZE(tlGruntAllyFollow),
bits_COND_NEW_ENEMY |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND |
bits_COND_PROVOKED,
bits_SOUND_DANGER,
"Follow"
},
};
Task_t tlGruntAllyFaceTarget[] =
{
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_FACE_TARGET, (float)0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_SET_SCHEDULE, (float)SCHED_TARGET_CHASE },
};
Schedule_t slGruntAllyFaceTarget[] =
{
{
tlGruntAllyFaceTarget,
ARRAYSIZE(tlGruntAllyFaceTarget),
bits_COND_CLIENT_PUSH |
bits_COND_NEW_ENEMY |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND |
bits_COND_PROVOKED,
bits_SOUND_DANGER,
"FaceTarget"
},
};
Task_t tlGruntAllyIdleStand[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_WAIT, (float)2 }, // repick IDLESTAND every two seconds.
{ TASK_TLK_HEADRESET, (float)0 }, // reset head position
};
Schedule_t slGruntAllyIdleStand[] =
{
{
tlGruntAllyIdleStand,
ARRAYSIZE(tlGruntAllyIdleStand),
bits_COND_NEW_ENEMY |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND |
bits_COND_SMELL |
bits_COND_PROVOKED,
bits_SOUND_COMBAT |// sound flags - change these, and you'll break the talking code.
//bits_SOUND_PLAYER |
//bits_SOUND_WORLD |
bits_SOUND_DANGER |
bits_SOUND_MEAT |// scents
bits_SOUND_CARCASS |
bits_SOUND_GARBAGE,
"IdleStand"
},
};
DEFINE_CUSTOM_SCHEDULES(CSAS)
{
slGruntAllyFollow,
slGruntAllyFaceTarget,
slGruntAllyIdleStand,
slGruntAllyFail,
slGruntAllyCombatFail,
slGruntAllyVictoryDance,
slGruntAllyEstablishLineOfFire,
slGruntAllyFoundEnemy,
slGruntAllyCombatFace,
slGruntAllySignalSuppress,
slGruntAllySuppress,
slGruntAllyWaitInCover,
slGruntAllyTakeCover,
slGruntAllyGrenadeCover,
slGruntAllyTossGrenadeCover,
slGruntAllyTakeCoverFromBestSound,
slGruntAllyHideReload,
slGruntAllySweep,
slGruntAllyRangeAttack1A,
slGruntAllyRangeAttack1B,
slGruntAllyRangeAttack2,
slGruntAllyRepel,
slGruntAllyRepelAttack,
slGruntAllyRepelLand,
};
IMPLEMENT_CUSTOM_SCHEDULES(CSAS, COFSquadTalkMonster);
//=========================================================
// SetActivity
//=========================================================
void CSAS::SetActivity(Activity NewActivity)
{
int iSequence = ACTIVITY_NOT_AVAILABLE;
void* pmodel = GET_MODEL_PTR(ENT(pev));
switch (NewActivity)
{
case ACT_RANGE_ATTACK1:
// grunt is either shooting standing or shooting crouched
if (FBitSet(pev->weapons, SASWeaponFlag::MP5))
{
if (m_fStanding)
{
// get aimable sequence
iSequence = LookupSequence("standing_mp5");
}
else
{
// get crouching shoot
iSequence = LookupSequence("crouching_mp5");
}
}
else if (FBitSet(pev->weapons, SASWeaponFlag::AR16))
{
if (m_fStanding)
{
// get aimable sequence
//iSequence = LookupSequence("standing_AR16");
iSequence = LookupSequence("standing_mp5");
}
else
{
// get crouching shoot
//iSequence = LookupSequence("crouching_AR16");
iSequence = LookupSequence("crouching_mp5");
}
}
else
{
if (m_fStanding)
{
// get aimable sequence
iSequence = LookupSequence("standing_shotgun");
}
else
{
// get crouching shoot
iSequence = LookupSequence("crouching_shotgun");
}
}
break;
case ACT_RANGE_ATTACK2:
// grunt is going to a secondary long range attack. This may be a thrown
// grenade or fired grenade, we must determine which and pick proper sequence
if (pev->weapons & SASWeaponFlag::HandGrenade)
{
// get toss anim
iSequence = LookupSequence("throwgrenade");
}
else
{
// get launch anim
iSequence = LookupSequence("launchgrenade");
}
break;
case ACT_RUN:
if (pev->health <= HSAS_LIMP_HEALTH)
{
// limp!
iSequence = LookupActivity(ACT_RUN_HURT);
}
else
{
iSequence = LookupActivity(NewActivity);
}
break;
case ACT_WALK:
if (pev->health <= HSAS_LIMP_HEALTH)
{
// limp!
iSequence = LookupActivity(ACT_WALK_HURT);
}
else
{
iSequence = LookupActivity(NewActivity);
}
break;
case ACT_IDLE:
if (m_MonsterState == MONSTERSTATE_COMBAT)
{
NewActivity = ACT_IDLE_ANGRY;
}
iSequence = LookupActivity(NewActivity);
break;
default:
iSequence = LookupActivity(NewActivity);
break;
}
m_Activity = NewActivity; // Go ahead and set this so it doesn't keep trying when the anim is not present
// Set to the desired anim, or default anim if the desired is not present
if (iSequence > ACTIVITY_NOT_AVAILABLE)
{
if (pev->sequence != iSequence || !m_fSequenceLoops)
{
pev->frame = 0;
}
pev->sequence = iSequence; // Set to the reset anim (if it's there)
ResetSequenceInfo();
SetYawSpeed();
}
else
{
// Not available try to get default anim
ALERT(at_console, "%s has no sequence for act:%d\n", STRING(pev->classname), NewActivity);
pev->sequence = 0; // Set to the reset anim (if it's there)
}
}
//=========================================================
// Get Schedule!
//=========================================================
Schedule_t* CSAS::GetSchedule()
{
// clear old sentence
m_iSentence = HSAS_SENT_NONE;
// flying? If PRONE, barnacle has me. IF not, it's assumed I am rapelling.
if (pev->movetype == MOVETYPE_FLY && m_MonsterState != MONSTERSTATE_PRONE)
{
if (pev->flags & FL_ONGROUND)
{
// just landed
pev->movetype = MOVETYPE_STEP;
return GetScheduleOfType(SCHED_SAS_REPEL_LAND);
}
else
{
// repel down a rope,
if (m_MonsterState == MONSTERSTATE_COMBAT)
return GetScheduleOfType(SCHED_SAS_REPEL_ATTACK);
else
return GetScheduleOfType(SCHED_SAS_REPEL);
}
}
// grunts place HIGH priority on running away from danger sounds.
if (HasConditions(bits_COND_HEAR_SOUND))
{
CSound* pSound;
pSound = PBestSound();
ASSERT(pSound != nullptr);
if (pSound)
{
if (pSound->m_iType & bits_SOUND_DANGER)
{
// dangerous sound nearby!
//!!!KELLY - currently, this is the grunt's signal that a grenade has landed nearby,
// and the grunt should find cover from the blast
// good place for "SHIT!" or some other colorful verbal indicator of dismay.
// It's not safe to play a verbal order here "Scatter", etc cause
// this may only affect a single individual in a squad.
if (FOkToSpeak())
{
SENTENCEG_PlayRndSz(ENT(pev), "SAS_GREN", HSAS_SENTENCE_VOLUME, SAS_ATTN, 0, m_voicePitch);
JustSpoke();
}
return GetScheduleOfType(SCHED_TAKE_COVER_FROM_BEST_SOUND);
}
/*
if (!HasConditions( bits_COND_SEE_ENEMY ) && ( pSound->m_iType & (bits_SOUND_PLAYER | bits_SOUND_COMBAT) ))
{
MakeIdealYaw( pSound->m_vecOrigin );
}
*/
}
}
switch (m_MonsterState)
{
case MONSTERSTATE_COMBAT:
{
// dead enemy
if (HasConditions(bits_COND_ENEMY_DEAD))
{
if (FOkToSpeak())
{
PlaySentence("SAS_KILL", 4, VOL_NORM, ATTN_NORM);
}
// call base class, all code to handle dead enemies is centralized there.
return COFSquadTalkMonster::GetSchedule();
}
if (m_hWaitMedic)
{
auto pMedic = m_hWaitMedic.Entity<COFSquadTalkMonster>();
if (pMedic->pev->deadflag != DEAD_NO)
m_hWaitMedic = nullptr;
else
pMedic->HealMe(nullptr);
m_flMedicWaitTime = gpGlobals->time + 5.0;
}
// new enemy
//Do not fire until fired upon
if (HasAllConditions(bits_COND_NEW_ENEMY | bits_COND_LIGHT_DAMAGE))
{
if (InSquad())
{
MySquadLeader()->m_fEnemyEluded = FALSE;
if (!IsLeader())
{
return GetScheduleOfType(SCHED_TAKE_COVER_FROM_ENEMY);
}
else
{
//!!!KELLY - the leader of a squad of grunts has just seen the player or a
// monster and has made it the squad's enemy. You
// can check pev->flags for FL_CLIENT to determine whether this is the player
// or a monster. He's going to immediately start
// firing, though. If you'd like, we can make an alternate "first sight"
// schedule where the leader plays a handsign anim
// that gives us enough time to hear a short sentence or spoken command
// before he starts pluggin away.
if (FOkToSpeak())// && RANDOM_LONG(0,1))
{
if ((m_hEnemy != nullptr) && m_hEnemy->IsPlayer())
// player
SENTENCEG_PlayRndSz(ENT(pev), "SAS_ALERT", HSAS_SENTENCE_VOLUME, SAS_ATTN, 0, m_voicePitch);
else if ((m_hEnemy != nullptr) &&
(m_hEnemy->Classify() != CLASS_PLAYER_ALLY) &&
(m_hEnemy->Classify() != CLASS_HUMAN_PASSIVE) &&
(m_hEnemy->Classify() != CLASS_MACHINE))
// monster
SENTENCEG_PlayRndSz(ENT(pev), "SAS_MONST", HSAS_SENTENCE_VOLUME, SAS_ATTN, 0, m_voicePitch);
JustSpoke();
}
if (HasConditions(bits_COND_CAN_RANGE_ATTACK1))
{
return GetScheduleOfType(SCHED_SAS_SUPPRESS);
}
else
{
return GetScheduleOfType(SCHED_SAS_ESTABLISH_LINE_OF_FIRE);
}
}
}
return GetScheduleOfType(SCHED_SMALL_FLINCH);
}
else if (HasConditions(bits_COND_HEAVY_DAMAGE))
return GetScheduleOfType(SCHED_TAKE_COVER_FROM_ENEMY);
// no ammo
//Only if the grunt has a weapon
else if (pev->weapons && HasConditions(bits_COND_NO_AMMO_LOADED))
{
//!!!KELLY - this individual just realized he's out of bullet ammo.
// He's going to try to find cover to run to and reload, but rarely, if
// none is available, he'll drop and reload in the open here.
return GetScheduleOfType(SCHED_SAS_COVER_AND_RELOAD);
}
// damaged just a little
else if (HasConditions(bits_COND_LIGHT_DAMAGE))
{
// if hurt:
// 90% chance of taking cover
// 10% chance of flinch.
int iPercent = RANDOM_LONG(0, 99);
if (iPercent <= 90 && m_hEnemy != nullptr)
{
// only try to take cover if we actually have an enemy!
//!!!KELLY - this grunt was hit and is going to run to cover.
if (FOkToSpeak()) // && RANDOM_LONG(0,1))
{
//SENTENCEG_PlayRndSz( ENT(pev), "SAS_COVER", HSAS_SENTENCE_VOLUME, SAS_ATTN, 0, m_voicePitch);
m_iSentence = HSAS_SENT_COVER;
//JustSpoke();
}
return GetScheduleOfType(SCHED_TAKE_COVER_FROM_ENEMY);
}
else
{
return GetScheduleOfType(SCHED_SMALL_FLINCH);
}
}
// can kick
else if (HasConditions(bits_COND_CAN_MELEE_ATTACK1))
{
return GetScheduleOfType(SCHED_MELEE_ATTACK1);
}
// can grenade launch
else if (FBitSet(pev->weapons, SASWeaponFlag::GrenadeLauncher) && HasConditions(bits_COND_CAN_RANGE_ATTACK2) && OccupySlot(bits_SLOTS_HGRUNT_GRENADE))
{
// shoot a grenade if you can
return GetScheduleOfType(SCHED_RANGE_ATTACK2);
}
// can shoot
else if (HasConditions(bits_COND_CAN_RANGE_ATTACK1))
{
if (InSquad())
{
// if the enemy has eluded the squad and a squad member has just located the enemy
// and the enemy does not see the squad member, issue a call to the squad to waste a
// little time and give the player a chance to turn.
if (MySquadLeader()->m_fEnemyEluded && !HasConditions(bits_COND_ENEMY_FACING_ME))
{
MySquadLeader()->m_fEnemyEluded = FALSE;
return GetScheduleOfType(SCHED_SAS_FOUND_ENEMY);
}
}
if (OccupySlot(bits_SLOTS_HGRUNT_ENGAGE))
{
// try to take an available ENGAGE slot
return GetScheduleOfType(SCHED_RANGE_ATTACK1);
}
else if (HasConditions(bits_COND_CAN_RANGE_ATTACK2) && OccupySlot(bits_SLOTS_HGRUNT_GRENADE))
{
// throw a grenade if can and no engage slots are available
return GetScheduleOfType(SCHED_RANGE_ATTACK2);
}
else
{
// hide!
return GetScheduleOfType(SCHED_TAKE_COVER_FROM_ENEMY);
}
}
// can't see enemy
else if (HasConditions(bits_COND_ENEMY_OCCLUDED))
{
if (HasConditions(bits_COND_CAN_RANGE_ATTACK2) && OccupySlot(bits_SLOTS_HGRUNT_GRENADE))
{
//!!!KELLY - this grunt is about to throw or fire a grenade at the player. Great place for "fire in the hole" "frag out" etc
if (FOkToSpeak())
{
SENTENCEG_PlayRndSz(ENT(pev), "SAS_THROW", HSAS_SENTENCE_VOLUME, SAS_ATTN, 0, m_voicePitch);
JustSpoke();
}
return GetScheduleOfType(SCHED_RANGE_ATTACK2);
}
else if (OccupySlot(bits_SLOTS_HGRUNT_ENGAGE))
{
//!!!KELLY - grunt cannot see the enemy and has just decided to
// charge the enemy's position.
if (FOkToSpeak())// && RANDOM_LONG(0,1))
{
//SENTENCEG_PlayRndSz( ENT(pev), "SAS_CHARGE", HSAS_SENTENCE_VOLUME, SAS_ATTN, 0, m_voicePitch);
m_iSentence = HSAS_SENT_CHARGE;
//JustSpoke();
}
return GetScheduleOfType(SCHED_SAS_ESTABLISH_LINE_OF_FIRE);
}
else
{
//!!!KELLY - grunt is going to stay put for a couple seconds to see if
// the enemy wanders back out into the open, or approaches the
// grunt's covered position. Good place for a taunt, I guess?
if (FOkToSpeak() && RANDOM_LONG(0, 1))
{
SENTENCEG_PlayRndSz(ENT(pev), "SAS_TAUNT", HSAS_SENTENCE_VOLUME, SAS_ATTN, 0, m_voicePitch);
JustSpoke();
}
return GetScheduleOfType(SCHED_STANDOFF);
}
}
//Only if not following a player
if (!m_hTargetEnt || !m_hTargetEnt->IsPlayer())
{
if (HasConditions(bits_COND_SEE_ENEMY) && !HasConditions(bits_COND_CAN_RANGE_ATTACK1))
{
return GetScheduleOfType(SCHED_SAS_ESTABLISH_LINE_OF_FIRE);
}
}
//Don't fall through to idle schedules
break;
}
case MONSTERSTATE_ALERT:
case MONSTERSTATE_IDLE:
if (HasConditions(bits_COND_LIGHT_DAMAGE | bits_COND_HEAVY_DAMAGE))
{
// flinch if hurt
return GetScheduleOfType(SCHED_SMALL_FLINCH);
}
//if we're not waiting on a medic and we're hurt, call out for a medic
if (!m_hWaitMedic
&& gpGlobals->time > m_flMedicWaitTime
&& pev->health <= 20.0)
{
auto pMedic = MySquadMedic();
if (!pMedic)
{
pMedic = FindSquadMedic(1024);
}
if (pMedic)
{
if (pMedic->pev->deadflag == DEAD_NO)
{
ALERT(at_aiconsole, "Injured Grunt found Medic\n");
if (pMedic->HealMe(this))
{
ALERT(at_aiconsole, "Injured Grunt called for Medic\n");
EMIT_SOUND_DYN(edict(), CHAN_VOICE, "sas/help04.wav", VOL_NORM, ATTN_NORM, 0, PITCH_NORM);
JustSpoke();
m_flMedicWaitTime = gpGlobals->time + 5.0;
}
}
}
}
if (m_hEnemy == nullptr && IsFollowing())
{
if (!m_hTargetEnt->IsAlive())
{
// UNDONE: Comment about the recently dead player here?
StopFollowing(FALSE);
break;
}
else
{
if (HasConditions(bits_COND_CLIENT_PUSH))
{
return GetScheduleOfType(SCHED_MOVE_AWAY_FOLLOW);
}
return GetScheduleOfType(SCHED_TARGET_FACE);
}
}
if (HasConditions(bits_COND_CLIENT_PUSH))
{
return GetScheduleOfType(SCHED_MOVE_AWAY);
}
// try to say something about smells
TrySmellTalk();
break;
}
// no special cases here, call the base class
return COFSquadTalkMonster::GetSchedule();
}
//=========================================================
//=========================================================
Schedule_t* CSAS::GetScheduleOfType(int Type)
{
switch (Type)
{
case SCHED_TAKE_COVER_FROM_ENEMY:
{
if (InSquad())
{
if (g_iSkillLevel == SKILL_HARD && HasConditions(bits_COND_CAN_RANGE_ATTACK2) && OccupySlot(bits_SLOTS_HGRUNT_GRENADE))
{
if (FOkToSpeak())
{
SENTENCEG_PlayRndSz(ENT(pev), "SAS_THROW", HSAS_SENTENCE_VOLUME, SAS_ATTN, 0, m_voicePitch);
JustSpoke();
}
return slGruntAllyTossGrenadeCover;
}
else
{
return &slGruntAllyTakeCover[0];
}
}
else
{
//if ( RANDOM_LONG(0,1) )
//{
return &slGruntAllyTakeCover[0];
//}
//else
//{
// return &slGruntAllyGrenadeCover[ 0 ];
//}
}
}
case SCHED_TAKE_COVER_FROM_BEST_SOUND:
{
return &slGruntAllyTakeCoverFromBestSound[0];
}
case SCHED_SAS_TAKECOVER_FAILED:
{
if (HasConditions(bits_COND_CAN_RANGE_ATTACK1) && OccupySlot(bits_SLOTS_HGRUNT_ENGAGE))
{
return GetScheduleOfType(SCHED_RANGE_ATTACK1);
}
return GetScheduleOfType(SCHED_FAIL);
}
break;
case SCHED_SAS_ELOF_FAIL:
{
// human grunt is unable to move to a position that allows him to attack the enemy.
return GetScheduleOfType(SCHED_TAKE_COVER_FROM_ENEMY);
}
break;
case SCHED_SAS_ESTABLISH_LINE_OF_FIRE:
{
return &slGruntAllyEstablishLineOfFire[0];
}
break;
case SCHED_RANGE_ATTACK1:
{
//Always stand when using AR16
if (pev->weapons & SASWeaponFlag::AR16)
{
m_fStanding = true;
return &slGruntAllyRangeAttack1B[0];
}
// randomly stand or crouch
if (RANDOM_LONG(0, 9) == 0)
m_fStanding = RANDOM_LONG(0, 1);
if (m_fStanding)
return &slGruntAllyRangeAttack1B[0];
else
return &slGruntAllyRangeAttack1A[0];
}
case SCHED_RANGE_ATTACK2:
{
return &slGruntAllyRangeAttack2[0];
}
case SCHED_COMBAT_FACE:
{
return &slGruntAllyCombatFace[0];
}
case SCHED_SAS_WAIT_FACE_ENEMY:
{
return &slGruntAllyWaitInCover[0];
}
case SCHED_SAS_SWEEP:
{
return &slGruntAllySweep[0];
}
case SCHED_SAS_COVER_AND_RELOAD:
{
return &slGruntAllyHideReload[0];
}
case SCHED_SAS_FOUND_ENEMY:
{
return &slGruntAllyFoundEnemy[0];
}
case SCHED_VICTORY_DANCE:
{
if (InSquad())
{
if (!IsLeader())
{
if (MySquadLeader()->m_deadMates > 2)
{
//Sad Victory Dance Taunt
MySquadLeader()->PlaySentence("SAS_VDNSD", 4, VOL_NORM, ATTN_NORM);
}
else if (MySquadLeader()->m_deadMates == 2)
{
//"That Was Close" Victory Dance Taunt
MySquadLeader()->PlaySentence("SAS_VDNCL", 4, VOL_NORM, ATTN_NORM);
}
else
{
//Happy Victory Dance Taunt
MySquadLeader()->PlaySentence("SAS_VDNHP", 4, VOL_NORM, ATTN_NORM);
}
return &slGruntAllyFail[0];
}
}
return &slGruntAllyVictoryDance[0];
}
case SCHED_SAS_SUPPRESS:
{
if (m_hEnemy->IsPlayer() && m_fFirstEncounter)
{
m_fFirstEncounter = FALSE;// after first encounter, leader won't issue handsigns anymore when he has a new enemy
return &slGruntAllySignalSuppress[0];
}
else
{
return &slGruntAllySuppress[0];
}
}
case SCHED_FAIL:
{
if (m_hEnemy != nullptr)
{
// grunt has an enemy, so pick a different default fail schedule most likely to help recover.
return &slGruntAllyCombatFail[0];
}
return &slGruntAllyFail[0];
}
case SCHED_SAS_REPEL:
{
if (pev->velocity.z > -128)
pev->velocity.z -= 32;
return &slGruntAllyRepel[0];
}
case SCHED_SAS_REPEL_ATTACK:
{
if (pev->velocity.z > -128)
pev->velocity.z -= 32;
return &slGruntAllyRepelAttack[0];
}
case SCHED_SAS_REPEL_LAND:
{
return &slGruntAllyRepelLand[0];
}
case SCHED_TARGET_CHASE:
return slGruntAllyFollow;
case SCHED_TARGET_FACE:
{
auto pSchedule = COFSquadTalkMonster::GetScheduleOfType(SCHED_TARGET_FACE);
if (pSchedule == slIdleStand)
return slGruntAllyFaceTarget;
return pSchedule;
}
case SCHED_IDLE_STAND:
{
auto pSchedule = COFSquadTalkMonster::GetScheduleOfType(SCHED_IDLE_STAND);
if (pSchedule == slIdleStand)
return slGruntAllyIdleStand;
return pSchedule;
}
case SCHED_CANT_FOLLOW:
return &slGruntAllyFail[0];
default:
{
return COFSquadTalkMonster::GetScheduleOfType(Type);
}
}
}
int CSAS::ObjectCaps()
{
return FCAP_ACROSS_TRANSITION | FCAP_IMPULSE_USE;
}
void CSAS::TalkInit()
{
COFSquadTalkMonster::TalkInit();
m_szGrp[TLK_ANSWER] = "SAS_ANSWER";
m_szGrp[TLK_QUESTION] = "SAS_QUESTION";
m_szGrp[TLK_IDLE] = "SAS_IDLE";
m_szGrp[TLK_STARE] = "SAS_STARE";
m_szGrp[TLK_USE] = "SAS_OK";
m_szGrp[TLK_UNUSE] = "SAS_WAIT";
m_szGrp[TLK_STOP] = "SAS_STOP";
m_szGrp[TLK_NOSHOOT] = "SAS_FSHOT";
m_szGrp[TLK_FRKILL] = "SAS_FKIL";
m_szGrp[TLK_HELLO] = "SAS_ALERT";
m_szGrp[TLK_PLHURT1] = "!SAS_CUREA";
m_szGrp[TLK_PLHURT2] = "!SAS_CUREB";
m_szGrp[TLK_PLHURT3] = "!SAS_CUREC";
m_szGrp[TLK_PHELLO] = nullptr; //"BA_PHELLO"; // UNDONE
m_szGrp[TLK_PIDLE] = nullptr; //"BA_PIDLE"; // UNDONE
m_szGrp[TLK_PQUESTION] = "SAS_PQUEST"; // UNDONE
m_szGrp[TLK_SMELL] = "SAS_SMELL";
m_szGrp[TLK_WOUND] = "SAS_WOUND";
m_szGrp[TLK_MORTAL] = "SAS_MORTAL";
// get voice for head - just one voice for now
m_voicePitch = 100;
}
void CSAS::AlertSound()
{
if (m_hEnemy && FOkToSpeak())
{
PlaySentence("SAS_ATTACK", RANDOM_FLOAT(2.8, 3.2), VOL_NORM, ATTN_NORM);
}
}
void CSAS::DeclineFollowing()
{
PlaySentence("SAS_POK", 2, VOL_NORM, ATTN_NORM);
}
void CSAS::KeyValue(KeyValueData* pkvd)
{
if (FStrEq(pkvd->szKeyName, "head"))
{
m_iGruntHead = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else
COFSquadTalkMonster::KeyValue(pkvd);
}
void CSAS::Killed(entvars_t* pevAttacker, int iGib)
{
if (m_MonsterState != MONSTERSTATE_DEAD)
{
if (HasMemory(bits_MEMORY_SUSPICIOUS) || IsFacing(pevAttacker, pev->origin))
{
Remember(bits_MEMORY_PROVOKED);
StopFollowing(true);
}
}
if (m_hWaitMedic)
{
auto v4 = m_hWaitMedic.Entity<COFSquadTalkMonster>();
if (v4->pev->deadflag)
m_hWaitMedic = nullptr;
else
v4->HealMe(nullptr);
}
SetUse(nullptr);
COFSquadTalkMonster::Killed(pevAttacker, iGib);
}
//=========================================================
// CSASRepel - when triggered, spawns a monster_sas
// repelling down a line.
//=========================================================
class CSASRepel : public CBaseMonster
{
public:
void KeyValue(KeyValueData* pkvd) override;
void Spawn() override;
void Precache() override;
void EXPORT RepelUse(CBaseEntity* pActivator, CBaseEntity* pCaller, USE_TYPE useType, float value);
int m_iSpriteTexture; // Don't save, precache
//TODO: needs save/restore (not in op4)
int m_iGruntHead;
int m_iszUse;
int m_iszUnUse;
};
LINK_ENTITY_TO_CLASS(monster_sas_repel, CSASRepel);
void CSASRepel::KeyValue(KeyValueData* pkvd)
{
if (FStrEq(pkvd->szKeyName, "head"))
{
m_iGruntHead = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "UseSentence"))
{
m_iszUse = ALLOC_STRING(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "UnUseSentence"))
{
m_iszUnUse = ALLOC_STRING(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else
CBaseMonster::KeyValue(pkvd);
}
void CSASRepel::Spawn()
{
Precache();
pev->solid = SOLID_NOT;
SetUse(&CSASRepel::RepelUse);
}
void CSASRepel::Precache()
{
UTIL_PrecacheOther("monster_sas");
m_iSpriteTexture = PRECACHE_MODEL("sprites/rope.spr");
}
void CSASRepel::RepelUse(CBaseEntity* pActivator, CBaseEntity* pCaller, USE_TYPE useType, float value)
{
TraceResult tr;
UTIL_TraceLine(pev->origin, pev->origin + Vector(0, 0, -4096.0), dont_ignore_monsters, ENT(pev), &tr);
/*
if ( tr.pHit && Instance( tr.pHit )->pev->solid != SOLID_BSP)
return NULL;
*/
CBaseEntity* pEntity = Create("monster_sas", pev->origin, pev->angles);
auto pGrunt = static_cast<CSAS*>(pEntity->MySquadTalkMonsterPointer());
if (pGrunt)
{
pGrunt->pev->weapons = pev->weapons;
pGrunt->pev->netname = pev->netname;
//Carry over these spawn flags
pGrunt->pev->spawnflags |= pev->spawnflags
& (SF_MONSTER_WAIT_TILL_SEEN
| SF_MONSTER_GAG
| SF_MONSTER_HITMONSTERCLIP
| SF_MONSTER_PRISONER
| SF_SQUADMONSTER_LEADER
| SF_MONSTER_PREDISASTER);
pGrunt->m_iGruntHead = m_iGruntHead;
pGrunt->m_iszUse = m_iszUse;
pGrunt->m_iszUnUse = m_iszUnUse;
//Run logic to set up body groups (Spawn was already called once by Create above)
pGrunt->Spawn();
pGrunt->pev->movetype = MOVETYPE_FLY;
pGrunt->pev->velocity = Vector(0, 0, RANDOM_FLOAT(-196, -128));
pGrunt->SetActivity(ACT_GLIDE);
// UNDONE: position?
pGrunt->m_vecLastPosition = tr.vecEndPos;
CBeam* pBeam = CBeam::BeamCreate("sprites/rope.spr", 10);
pBeam->PointEntInit(pev->origin + Vector(0, 0, 112), pGrunt->entindex());
pBeam->SetFlags(BEAM_FSOLID);
pBeam->SetColor(255, 255, 255);
pBeam->SetThink(&CBeam::SUB_Remove);
pBeam->pev->nextthink = gpGlobals->time + -4096.0 * tr.flFraction / pGrunt->pev->velocity.z + 0.5;
UTIL_Remove(this);
}
}
//=========================================================
// DEAD HGRUNT PROP
//=========================================================
class CDeadSAS : public CBaseMonster
{
public:
void Spawn() override;
int Classify() override { return CLASS_PLAYER_ALLY; }
void KeyValue(KeyValueData* pkvd) override;
int m_iPose;// which sequence to display -- temporary, don't need to save
int m_iGruntHead;
static char* m_szPoses[7];
};
char* CDeadSAS::m_szPoses[] = { "deadstomach", "deadside", "deadsitting", "dead_on_back", "HSAS_dead_stomach", "dead_headcrabed", "dead_canyon" };
void CDeadSAS::KeyValue(KeyValueData* pkvd)
{
if (FStrEq(pkvd->szKeyName, "pose"))
{
m_iPose = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "head"))
{
m_iGruntHead = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else
CBaseMonster::KeyValue(pkvd);
}
LINK_ENTITY_TO_CLASS(monster_sas_dead, CDeadSAS);
//=========================================================
// ********** DeadSAS SPAWN **********
//=========================================================
void CDeadSAS::Spawn()
{
PRECACHE_MODEL("models/sas.mdl");
SET_MODEL(ENT(pev), "models/sas.mdl");
pev->effects = 0;
pev->yaw_speed = 8;
pev->sequence = 0;
m_bloodColor = BLOOD_COLOR_RED;
pev->sequence = LookupSequence(m_szPoses[m_iPose]);
if (pev->sequence == -1)
{
ALERT(at_console, "Dead hgrunt with bad pose\n");
}
// Corpses have less health
pev->health = 8;
if (pev->weapons & SASWeaponFlag::MP5)
{
//SetBodygroup(SASBodygroup::Torso, SASTorso::Normal);
SetBodygroup(SASBodygroup::Weapons, SASWeapon::MP5);
}
else if (pev->weapons & SASWeaponFlag::Shotgun)
{
//SetBodygroup(SASBodygroup::Torso, SASTorso::Shotgun);
SetBodygroup(SASBodygroup::Weapons, SASWeapon::Shotgun);
}
else if (pev->weapons & SASWeaponFlag::AR16)
{
//SetBodygroup(SASBodygroup::Torso, SASTorso::AR16);
SetBodygroup(SASBodygroup::Weapons, SASWeapon::AR16);
}
else
{
//SetBodygroup(SASBodygroup::Torso, SASTorso::Normal);
SetBodygroup(SASBodygroup::Weapons, SASWeapon::None);
}
//SetBodygroup(SASBodygroup::Head, m_iGruntHead);
pev->skin = 0;
MonsterInitDead();
}
| 26.031925 | 162 | 0.644857 | [
"vector",
"solid"
] |
179bd8b82a288687399c935dcc9e244adc2f2fb5 | 3,277 | cpp | C++ | Array/Subarray or Subsequence Related Problems/Min Len Unsorted Subarr, Sorting Which Makes The Complete Array Sorted.cpp | Edith-3000/Algorithmic-Implementations | 7ff8cd615fd453a346b4e851606d47c26f05a084 | [
"MIT"
] | 8 | 2021-02-13T17:07:27.000Z | 2021-08-20T08:20:40.000Z | Array/Subarray or Subsequence Related Problems/Min Len Unsorted Subarr, Sorting Which Makes The Complete Array Sorted.cpp | Edith-3000/Algorithmic-Implementations | 7ff8cd615fd453a346b4e851606d47c26f05a084 | [
"MIT"
] | null | null | null | Array/Subarray or Subsequence Related Problems/Min Len Unsorted Subarr, Sorting Which Makes The Complete Array Sorted.cpp | Edith-3000/Algorithmic-Implementations | 7ff8cd615fd453a346b4e851606d47c26f05a084 | [
"MIT"
] | 5 | 2021-02-17T18:12:20.000Z | 2021-10-10T17:49:34.000Z | // Problem: https://www.interviewbit.com/problems/maximum-unsorted-subarray/
// Ref: https://www.geeksforgeeks.org/minimum-length-unsorted-subarray-sorting-which-makes-the-complete-array-sorted/
// https://www.youtube.com/watch?v=Hg03KTli9co
/********************************************************************************************************************/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
vi find_ans(vi &v) {
int n = (int)v.size();
// base case
if(n <= 1) {
vi res = {-1};
return res;
}
// if array is already sorted
bool ok = 1;
for(int i = 1; i < n; i++) {
ok &= (v[i] >= v[i-1]);
}
if(ok) {
vi res = {-1};
return res;
}
// Main algorithm ===>
// 1. from the beginning of the array find the index upto which array is sorted
int start = -1, end = n;
for(int i = 0; i + 1 < n; i++) {
if(v[i] <= v[i+1]) start = i;
else break;
}
start += 1;
// 2. from the end of the array find the index upto which array is sorted
for(int i = (n - 1); i >= start + 1; i--) {
if(v[i] >= v[i-1]) end = i;
else break;
}
end -= 1;
// 3. find the minimum and maximum in the subarray from [start, end]
int mx = *max_element(v.begin() + start, v.begin() + end + 1);
int mn = *min_element(v.begin() + start, v.begin() + end + 1);
int mn_idx = -1, mx_idx = -1;
// 4. find the correct position of the minimum in the subarr [0, start]
for(int i = 0; i <= start; i++) {
if(v[i] > mn) { mn_idx = i; break; }
}
if(mn_idx == -1) mn_idx = start;
// 5. find the correct position of the maximum in the subarr [end, n-1]
for(int i = (n - 1); i >= end; i--) {
if(v[i] < mx) { mx_idx = i; break; }
}
if(mx_idx == -1) mx_idx = end;
// 6. required subarray is the subarray [mn_idx, mx_idx]
vi res(2);
res[0] = mn_idx, res[1] = mx_idx;
return res;
}
void solve()
{
int n; cin >> n;
vi v(n);
for(int i = 0; i < n; i++) cin >> v[i];
vi res = find_ans(v);
for(auto x: res) cout << x << " ";
cout << "\n";
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t = 1;
// int test = 1;
// cin >> t;
while(t--) {
// cout << "Case #" << test++ << ": ";
solve();
}
return 0;
}
// Time Complexity: O(n)
// Space Complexity: O(1) | 24.274074 | 118 | 0.566372 | [
"vector"
] |
17a018899ea692e36e142e3f196badc97dd1df7d | 5,230 | cpp | C++ | 11/day11-cpp/src/fuel.cpp | gagbo/advent-of-code_2018 | ca2bb5282468a5ddba40bafddd85878cea253499 | [
"MIT"
] | null | null | null | 11/day11-cpp/src/fuel.cpp | gagbo/advent-of-code_2018 | ca2bb5282468a5ddba40bafddd85878cea253499 | [
"MIT"
] | 1 | 2018-12-06T20:41:23.000Z | 2018-12-06T20:41:23.000Z | 11/day11-cpp/src/fuel.cpp | gagbo/advent-of-code_2018 | ca2bb5282468a5ddba40bafddd85878cea253499 | [
"MIT"
] | null | null | null | #include "fuel.hpp"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
const size_t FuelGrid::GRID_SIZE = 300;
FuelGrid::FuelGrid(int grid_serial) : serial(grid_serial) {
for (size_t x = 0; x < GRID_SIZE; ++x) {
std::vector<std::unique_ptr<FuelCell>> line_x;
for (size_t y = 0; y < GRID_SIZE; ++y) {
line_x.push_back(std::make_unique<FuelCell>(x + 1, y + 1));
}
_grid.push_back(std::move(line_x));
}
}
void FuelCell::compute_value(int serial) {
int rack_id = _x + 10;
int power_level = rack_id * _y;
power_level += serial;
power_level *= rack_id;
for (int i = 0; i < 2; i++) {
power_level -= power_level % 10;
power_level /= 10;
}
power_level = power_level % 10;
_value = power_level - 5;
}
void FuelGrid::convert_all_cells() {
for (auto& line : _grid) {
std::for_each(line.begin(), line.end(),
[&](auto& cell) { cell->compute_value(serial); });
}
}
void FuelGrid::best_square() {
convert_all_cells();
size_t x_max, y_max, sq_size_max;
int val_max = std::numeric_limits<int>::min();
for (size_t sq_size = 1; sq_size <= 300; ++sq_size) {
std::cout << "Testing " << sq_size << "x" << sq_size << " squares...\n";
for (size_t x = 1; x <= GRID_SIZE; ++x) {
for (size_t y = 1; y <= GRID_SIZE; ++y) {
int current_val = square_value(x, y, sq_size);
if (current_val > val_max) {
x_max = x;
y_max = y;
sq_size_max = sq_size;
val_max = current_val;
}
}
}
}
std::cout << "Best square is (" << x_max << ", " << y_max << ", "
<< sq_size_max << ") with a value of " << val_max << "\n";
}
void FuelGrid::best_square_one_size(size_t sq_size) {
convert_all_cells();
size_t x_max, y_max;
int val_max = std::numeric_limits<int>::min();
for (size_t x = 1; x <= GRID_SIZE; ++x) {
for (size_t y = 1; y <= GRID_SIZE; ++y) {
int current_val = square_value(x, y, sq_size);
if (current_val > val_max) {
x_max = x;
y_max = y;
val_max = current_val;
}
}
}
std::cout << "Best square is (" << x_max << ", " << y_max
<< ") with a value of " << val_max << "\n";
}
int FuelGrid::square_value(size_t x, size_t y, size_t sq_size) const {
if (x < 1 || y < 1 || x + sq_size - 1 > GRID_SIZE ||
y + sq_size - 1 > GRID_SIZE) {
return std::numeric_limits<int>::min();
}
auto find_in_cache = square_cache.find(std::make_tuple(x, y, sq_size));
if (find_in_cache != square_cache.end()) {
return find_in_cache->second;
}
if (sq_size == 1) {
int total_val = _grid[x-1][y-1]->value();
square_cache.insert(std::make_pair(std::make_tuple(x, y, sq_size), total_val));
return total_val;
}
int total_val = 0;
size_t left_size = static_cast<size_t>(std::floor(sq_size / 2));
// NW square : Always a square
total_val += square_value(x, y, left_size);
// SE square : Always a square
total_val +=
square_value(x + left_size, y + left_size, sq_size - left_size);
// SW square : this leaves the bottom row is sq_size is odd
total_val += square_value(x, y + left_size, left_size);
// NE square : this leaves the right col is sq_size is odd
total_val += square_value(x + left_size, y, left_size);
if (sq_size - left_size != left_size) {
size_t bottom_y = y + sq_size - 1;
for (size_t bottom_x = x; bottom_x < x + left_size; bottom_x++) {
// Which line is better ?
// I think that the _grid direct access line grants quicker access
// instruction-count wise. Also, calling it for every 1x1 requests
// means that _grid should stay in a close enough cache, and the
// contiguous guarantee of a std::vector<> helps a lot.
// But maybe actually having this line
// forces _grid to be called back in a closer cache, where my
// square_cache is pulled to test for find() and insert()
//
// The square_value() is a 'slower' operation instruction-count wise I
// think. But the mean time per instruction should be better since
// once the cache is loaded with the 1x1 values, _grid is never called
// anymore and everything should happen in sq_cache.
//
// Benchmark has spoken, memory locality of _grid wins, and HANDILY.
// See README.md for results
total_val += _grid[bottom_x - 1][bottom_y - 1]->value();
/* total_val += square_value(bottom_x, bottom_y, 1); */
}
size_t right_x = x + sq_size - 1;
for (size_t right_y = y; right_y < y + left_size; right_y++) {
total_val += _grid[right_x - 1][right_y - 1]->value();
/* total_val += square_value(right_x, right_y, 1); */
}
}
square_cache.insert(std::make_pair(std::make_tuple(x, y, sq_size), total_val));
return total_val;
}
| 36.068966 | 85 | 0.56501 | [
"vector"
] |
17a4e1758c383c22534fef7271af4125644b1043 | 22,153 | cpp | C++ | src/framework/shared/core/fxrequestbase.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 994 | 2015-03-18T21:37:07.000Z | 2019-04-26T04:04:14.000Z | src/framework/shared/core/fxrequestbase.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 13 | 2019-06-13T15:58:03.000Z | 2022-02-18T22:53:35.000Z | src/framework/shared/core/fxrequestbase.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 350 | 2015-03-19T04:29:46.000Z | 2019-05-05T23:26:50.000Z | /*++
Copyright (c) Microsoft Corporation
Module Name:
FxRequestBase.cpp
Abstract:
This module implements FxRequestBase object
Author:
Environment:
Both kernel and user mode
Revision History:
--*/
#include "coreprivshared.hpp"
// Tracing support
extern "C" {
#include "FxRequestBase.tmh"
}
FxRequestBase::FxRequestBase(
__in PFX_DRIVER_GLOBALS FxDriverGlobals,
__in USHORT ObjectSize,
__in_opt MdIrp Irp,
__in FxRequestIrpOwnership Ownership,
__in FxRequestConstructorCaller Caller,
__in FxObjectType ObjectType
) : FxNonPagedObject(FX_TYPE_REQUEST, ObjectSize, FxDriverGlobals, ObjectType),
m_Irp(Irp)
{
//
// By default requests cannot be completed except for request associated with
// IRP allocated from I/O (upper drivers).
//
m_CanComplete = FALSE;
//
// After is all said and done with assigning to m_IrpAllocation value, if
// m_Irp().GetIrp == NULL, then m_IrpAllocation can be overridden in
// ValidateTarget.
//
if (Caller == FxRequestConstructorCallerIsDriver) {
if (Ownership == FxRequestOwnsIrp) {
//
// Driver writer gave the irp to the framework but still owns it
// or there is no irp passed in when the FxRequest was created.
//
m_IrpAllocation = REQUEST_ALLOCATED_INTERNAL;
}
else {
//
// Driver writer gave the irp to the framework but still owns it
//
m_IrpAllocation = REQUEST_ALLOCATED_DRIVER;
}
//
// Cleanup request's context in Dispose. Please see Dispose below
// for specific scenario we are trying to fix. Enable Dispose only if
// driver is v1.11 or above b/c it may be possible that older driver
// may have used invalid/bad scenarios similar to this one:
// - create target object.
// - create one or more driver created requests parented to the target.
// - send one or more of these requests to the target (lower stack).
// - delete the target object while requests are pending.
// Deleting a target while it has a pending request is a valid
// operation, what is not valid is for these request to be also
// parented to the target at the same time.
// In this scenario if we turn on Dispose, the Dispose callback will
// be called before the request is completed.
// Note that if the driver had specified any Cleanup callbacks on
// these requests, these also are called before the requests are
// completed.
//
if (FxDriverGlobals->IsVersionGreaterThanOrEqualTo(1, 11)) {
MarkDisposeOverride();
}
}
else if (Ownership == FxRequestOwnsIrp) {
//
// The request will own the irp and free it when the request is freed
//
m_IrpAllocation = REQUEST_ALLOCATED_INTERNAL;
}
else {
//
// Request is owned by the io queue
//
m_IrpAllocation = REQUEST_ALLOCATED_FROM_IO;
m_CanComplete = TRUE;
}
m_Target = NULL;
m_TargetFlags = 0;
m_TargetCompletionContext = NULL;
m_Completed = m_Irp.GetIrp() ? FALSE : TRUE;
m_Canceled = FALSE;
m_PriorityBoost = 0;
m_RequestContext = NULL;
m_Timer = NULL;
InitializeListHead(&m_ListEntry);
m_DrainSingleEntry.Next = NULL;
m_IrpReferenceCount = 0;
m_IrpQueue = NULL;
m_SystemBufferOffset = 0;
m_OutputBufferOffset = 0;
m_IrpCompletionReferenceCount = 0;
m_AllocatedMdl = NULL;
m_VerifierFlags = 0;
m_RequestBaseFlags = 0;
m_RequestBaseStaticFlags = 0x0;
m_CompletionState = FxRequestCompletionStateNone;
}
FxRequestBase::~FxRequestBase(
VOID
)
{
MdIrp irp;
//
// Since m_ListEntry is a union with the CSQ context and the irp have just
// come off of a CSQ, we cannot be guaranteed that the m_ListEntry is
// initialized to point to itself.
//
// ASSERT(IsListEmpty(&m_ListEntry));
#if (FX_CORE_MODE == FX_CORE_KERNEL_MODE)
//
// If an MDL is associated with the request, free it
//
if (m_AllocatedMdl != NULL) {
FxMdlFree(GetDriverGlobals(), m_AllocatedMdl);
}
#endif
irp = m_Irp.GetIrp();
//
// If the request was created through WdfRequestCreate, formatted, and not
// reused, we can still have a request context.
//
if (m_RequestContext != NULL) {
if (irp != NULL) {
m_RequestContext->ReleaseAndRestore(this);
}
delete m_RequestContext;
}
if (irp != NULL && m_IrpAllocation == REQUEST_ALLOCATED_INTERNAL) {
m_Irp.FreeIrp();
}
if (m_Timer != NULL) {
delete m_Timer;
}
}
VOID
FX_VF_METHOD(FxRequestBase, VerifyDispose) (
_In_ PFX_DRIVER_GLOBALS FxDriverGlobals
)
{
SHORT flags;
KIRQL irql;
PAGED_CODE_LOCKED();
Lock(&irql);
flags = GetVerifierFlagsLocked();
if (flags & FXREQUEST_FLAG_SENT_TO_TARGET) {
DoTraceLevelMessage(
FxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGREQUEST,
"Driver is trying to delete WDFREQUEST 0x%p while it is still "
"active on WDFIOTARGET 0x%p. ",
GetTraceObjectHandle(), GetTarget()->GetHandle());
FxVerifierDbgBreakPoint(FxDriverGlobals);
}
Unlock(irql);
}
BOOLEAN
FxRequestBase::Dispose()
{
//
// Make sure request is not in use.
//
VerifyDispose(GetDriverGlobals());
//
// Now call Cleanup on any handle context's exposed
// to the device driver.
//
CallCleanup();
//
// Call the request's cleanup (~dtor or Dispose).
//
if (m_RequestContext != NULL) {
if (IsAllocatedFromIo() == FALSE && m_Irp.GetIrp() != NULL) {
//
// This code allows the following scenario to work correctly b/c
// the original request can be completed without worrying that the
// new request's context has references on the original request.
//
// * Driver receives an ioctl request.
// * Driver creates a new request.
// * Driver formats the new request with buffers from original ioctl.
// * Driver sends the new request synchronously.
// * Driver retrieves info/status from the new request.
// * Driver deletes the new request.
// * Driver completes the original request.
//
m_RequestContext->ReleaseAndRestore(this);
//
// ~dtor cleans up everything. No need to call its Dispose method.
//
delete m_RequestContext;
m_RequestContext = NULL;
}
else {
//
// Let request's context know that Dispose is in progress.
// RequestContext may receive the following two calls after Dispose:
// . ReleaseAndRestore if an IRP is still present.
// . Destructor
//
m_RequestContext->Dispose();
}
}
return FALSE;
}
VOID
FxRequestBase::ClearFieldsForReuse(
VOID
)
{
#if (FX_CORE_MODE == FX_CORE_KERNEL_MODE)
if (m_AllocatedMdl != NULL) {
FxMdlFree(GetDriverGlobals(), m_AllocatedMdl);
m_AllocatedMdl = NULL;
}
#endif
m_RequestBaseFlags = 0;
m_RequestBaseStaticFlags = 0x0;
m_VerifierFlags = 0;
m_Canceled = FALSE;
SetCompleted(FALSE);
SetPriorityBoost(0);
m_NextStackLocationFormatted = FALSE;
if (m_Timer != NULL) {
delete m_Timer;
m_Timer = NULL;
}
m_Target = NULL;
m_TargetFlags = 0;
m_TargetCompletionContext = NULL;
InitializeListHead(&m_ListEntry);
m_DrainSingleEntry.Next = NULL;
m_IrpCompletionReferenceCount = 0;
m_CompletionState = FxRequestCompletionStateNone;
}
_Must_inspect_result_
NTSTATUS
FxRequestBase::ValidateTarget(
__in FxIoTarget* Target
)
{
MdIrp pIrp, pOldIrp;
FxIrp fxIrp;
NTSTATUS status;
pOldIrp = NULL;
pIrp = GetSubmitIrp();
fxIrp.SetIrp(pIrp);
//
// Must restore to the previous irp in case we reallocate the irp
//
ContextReleaseAndRestore();
if (Target->HasValidStackSize() == FALSE) {
//
// Target is closed down
//
status = STATUS_INVALID_DEVICE_STATE;
DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGIOTARGET,
"WDFIOTARGET %p is closed, cannot validate, %!STATUS!",
Target->GetHandle(), status);
}
else if (pIrp != NULL && Target->HasEnoughStackLocations(&fxIrp)) {
status = STATUS_SUCCESS;
}
else if (pIrp == NULL || m_IrpAllocation == REQUEST_ALLOCATED_INTERNAL) {
//
// Try to allocate a new irp.
//
pIrp = FxIrp::AllocateIrp(Target->m_TargetStackSize, Target->GetDevice());
if (pIrp == NULL) {
status = STATUS_INSUFFICIENT_RESOURCES;
DoTraceLevelMessage(
GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGIOTARGET,
"Could not allocate irp for WDFREQUEST %p for WDFIOTARGET %p,"
" %!STATUS!", GetTraceObjectHandle(), Target->GetHandle(), status);
}
else {
pOldIrp = SetSubmitIrp(pIrp, FALSE);
m_IrpAllocation = REQUEST_ALLOCATED_INTERNAL;
status = STATUS_SUCCESS;
}
}
else {
//
// The internal IRP is not owned by this object, so we can't reallocate
// it.
//
status = STATUS_REQUEST_NOT_ACCEPTED;
DoTraceLevelMessage(
GetDriverGlobals(), TRACE_LEVEL_ERROR, TRACINGIOTARGET,
"Cannot reallocate PIRP for WDFREQUEST %p using WDFIOTARGET %p,"
" %!STATUS!", GetTraceObjectHandle(), Target->GetHandle(), status);
}
if (pOldIrp != NULL) {
DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGIO,
"Freeing irp %p from WDFREQUEST %p\n",
pOldIrp, GetTraceObjectHandle());
FxIrp oldIrp(pOldIrp);
oldIrp.FreeIrp();
}
return status;
}
MdIrp
FxRequestBase::SetSubmitIrp(
__in_opt MdIrp NewIrp,
__in BOOLEAN FreeIrp
)
{
MdIrp pOldIrp, pIrpToFree;
pIrpToFree = NULL;
pOldIrp = m_Irp.SetIrp(NewIrp);
if (NewIrp != NULL) {
m_Completed = FALSE;
}
//
// If there is a previous irp that is not the current value and we
// allocated it ourselves and the caller wants us to free it, do so.
//
if (pOldIrp != NULL &&
pOldIrp != NewIrp &&
m_IrpAllocation == REQUEST_ALLOCATED_INTERNAL) {
if (FreeIrp) {
FxIrp oldIrp(pOldIrp);
oldIrp.FreeIrp();
}
else {
pIrpToFree = pOldIrp;
}
}
return pIrpToFree;
}
VOID
FxRequestBase::CompleteSubmittedNoContext(
VOID
)
/*++
Routine Description:
Invokes the completion routine and uses a completion params that is on the
stack. This is in a separate function so that we only consume the stack
space if we need to.
Arguments:
None
Return Value:
None
--*/
{
WDF_REQUEST_COMPLETION_PARAMS params;
params.Type = WdfRequestTypeNoFormat;
GetSubmitFxIrp()->CopyStatus(¶ms.IoStatus);
RtlZeroMemory(¶ms.Parameters, sizeof(params.Parameters));
//
// Once we call the completion routine we can't touch any fields anymore
// since the request may be resent down the stack.
//
ClearCompletionRoutine()(GetHandle(),
m_Target->GetHandle(),
¶ms,
ClearCompletionContext());
}
VOID
FxRequestBase::CompleteSubmitted(
VOID
)
/*++
Routine Description:
Routine that handles the setting up of the request packet for being passed
back to the completion routine. This includes copying over parameters from
the PIRP and any dereferences necessary.
Arguments:
None.
Return Value:
None.
--*/
{
FxIoTarget* pTarget;
pTarget = m_Target;
FX_TRACK_DRIVER(GetDriverGlobals());
if (GetDriverGlobals()->FxVerifierOn) {
//
// Zero out any values previous driver may have set; when completing the irp
// through FxRequest::CompleteInternal, we check to see what the lastest
// package was (stored off in the DriverContext). Since the request was
// sent off to another devobj, don't assume any valid values in the
// DriverContext anymore.
//
ZeroOutDriverContext();
//
// ClearFormatted also checks for WdfVefiefierOn, but that's OK
//
VerifierClearFormatted();
}
if (m_RequestContext != NULL) {
//
// Always do the copy because the driver can retrieve the parameters
// later even if there is no completion routine set.
//
GetSubmitFxIrp()->CopyStatus(
&m_RequestContext->m_CompletionParams.IoStatus
);
m_RequestContext->CopyParameters(this);
//
// Call the completion routine if present. Once we call the completion
// routine we can't touch any fields anymore since the request may be resent
// down the stack.
//
if (m_CompletionRoutine.m_Completion != NULL) {
ClearCompletionRoutine()(GetHandle(),
pTarget->GetHandle(),
&m_RequestContext->m_CompletionParams,
ClearCompletionContext());
}
}
else if (m_CompletionRoutine.m_Completion != NULL) {
//
// Only put a completion parameters struct on the stack if we have to.
// By putting it into a separate function, we can control stack usage
// in this way.
//
CompleteSubmittedNoContext();
}
//
// Release the tag that was acquired when the request was submitted or
// pended.
//
RELEASE(pTarget);
}
BOOLEAN
FxRequestBase::Cancel(
VOID
)
/*++
Routine Description:
Attempts to cancel a previously submitted or pended request.
Arguments:
None
Return Value:
TRUE if the request was successfully cancelled, FALSE otherwise
--*/
{
BOOLEAN result;
DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGIO,
"Request %p", this);
//
// It is critical to set m_Canceled before we check the reference count.
// We could be racing with FxIoTarget::SubmitLocked and if this call executes
// before SubmitLocked, the completion reference count will still be zero.
// SubmitLocked will check m_Canceled after setting the reference count to
// one so that it decrement the count back.
//
m_Canceled = TRUE;
//
// If the ref count is zero, the irp has completed already. This means we
// cannot safely touch the underlying PIRP because we cannot guarantee it
// will not be completed from underneath us.
//
if (FxInterlockedIncrementGTZero(&m_IrpCompletionReferenceCount) != 0) {
//
// Successfully incremented the ref count. The PIRP will not be completed
// until the count goes to zero.
//
// Cancelling the irp handles all 2 states:
//
// 1) the request is pended in a target. the target will attempt to
// complete the request immediately in the cancellation routine, but
// will not be able to because of the added count to the ref count
// done above. The count will move back to zero below and
// CompletedCanceledRequest will complete the request
//
// 2) The irp is in flight to the target WDM device. In which case the
// target WDM device should complete the request immediatley. If
// it does not, it becomes the same as the case where the target WDM
// device has already pended it and placed a cancellation routine
// on the request and the request will (a)synchronously complete
//
result = m_Irp.Cancel();
DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGIO,
"Request %p, PIRP %p, cancel result %d",
this, m_Irp.GetIrp(), result);
//
// If the count goes to zero, the completion routine ran, but deferred
// completion ownership to this thread since we had the outstanding
// refeference.
//
if (InterlockedDecrement(&m_IrpCompletionReferenceCount) == 0) {
//
// Since completion ownership was claimed, m_Target will be valid
// until m_Target->CompleteRequest executes because the target will
// not delete while there is outstanding I/O.
//
ASSERT(m_Target != NULL);
DoTraceLevelMessage(
GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGIO,
"Request %p, PIRP %p, completed synchronously in cancel call, "
"completing request on target %p", this, m_Irp.GetIrp(), m_Target);
m_Target->CompleteCanceledRequest(this);
}
}
else {
DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGIO,
"Could not cancel request %p, already completed", this);
result = FALSE;
}
return result;
}
VOID
FxRequestBase::_TimerDPC(
__in PKDPC Dpc,
__in_opt PVOID Context,
__in_opt PVOID SystemArgument1,
__in_opt PVOID SystemArgument2
)
/*++
Routine Description:
DPC for the request timer. It lets the FxIoTarget associated with the
request handle the cancellation synchronization with the PIRP's
completion routine.
Arguments:
Dpc - The DPC itself (part of FxRequestExtension)
Context - FxRequest* that has timed out
SystemArgument1 - Ignored
SystemArgument2 - Ignored
Return Value:
None.
--*/
{
FxRequest* pRequest;
FxIoTarget* pTarget;
UNREFERENCED_PARAMETER(Dpc);
UNREFERENCED_PARAMETER(SystemArgument1);
UNREFERENCED_PARAMETER(SystemArgument2);
//
// No need to grab FxRequest::Lock b/c if there is a timer running, then the
// request is guaranteed to be associated with a target.
//
pRequest = (FxRequest*) Context;
pTarget = pRequest->m_Target;
ASSERT(pTarget != NULL);
pTarget->TimerCallback(pRequest);
}
_Must_inspect_result_
NTSTATUS
FxRequestBase::CreateTimer(
VOID
)
/*++
Routine Description:
Late time initialization of timer related structures, we only init
timer structures if we are going to use them.
Arguments:
None
Assumes:
m_Target->Lock() is being held by the caller
Return Value:
None
--*/
{
FxRequestTimer* pTimer;
PVOID pResult;
NTSTATUS status;
PFX_DRIVER_GLOBALS FxDriverGlobals = GetDriverGlobals();
if (m_Timer != NULL) {
return STATUS_SUCCESS;
}
pTimer = new (FxDriverGlobals) FxRequestTimer();
if(pTimer == NULL) {
return STATUS_INSUFFICIENT_RESOURCES;
}
status = pTimer->Timer.Initialize(this, _TimerDPC, 0);
if(!NT_SUCCESS(status)) {
DoTraceLevelMessage(FxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGIO,
"Failed to initialize timer for request %p", this);
delete pTimer;
return status;
}
pResult = InterlockedCompareExchangePointer((PVOID*)&m_Timer, pTimer, NULL);
if (pResult != NULL) {
//
// Another value was set before we could set it, free our timer now
//
delete pTimer;
}
return STATUS_SUCCESS;
}
VOID
FxRequestBase::StartTimer(
__in LONGLONG Timeout
)
/*++
Routine Description:
Starts a timer for the request
Arguments:
Timeout - How long the timeout should be
Assumes:
m_Target->Lock() is being held by the caller.
Return Value:
None
--*/
{
LARGE_INTEGER timeout;
timeout.QuadPart = Timeout;
m_TargetFlags |= FX_REQUEST_TIMER_SET;
m_Timer->Timer.Start(timeout);
}
_Must_inspect_result_
BOOLEAN
FxRequestBase::CancelTimer(
VOID
)
/*++
Routine Description:
Cancel a previously queued timer based on this request if one was set.
Arguments:
None
Assumes:
Caller is providing synchronization around the call of this function with
regard to m_TargetFlags.
Return Value:
TRUE if the timer was cancelled successfully or if there was no timer set,
otherwise FALSE if the timer was not cancelled and has fired.
--*/
{
if (m_TargetFlags & FX_REQUEST_TIMER_SET) {
//
// If we can successfully cancel the timer, release the reference
// taken in StartTimer and mark the timer as not queued.
//
if (m_Timer->Timer.Stop() == FALSE) {
DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGIO,
"Request %p, did not cancel timer", this);
//
// Leave FX_REQUEST_TIMER_SET set. The timer DPC will clear the it
//
return FALSE;
}
DoTraceLevelMessage(GetDriverGlobals(), TRACE_LEVEL_VERBOSE, TRACINGIO,
"Request %p, canceled timer successfully", this);
m_TargetFlags &= ~FX_REQUEST_TIMER_SET;
}
return TRUE;
}
__declspec(noreturn)
VOID
FxRequestBase::FatalError(
__in NTSTATUS Status
)
{
WDF_QUEUE_FATAL_ERROR_DATA data;
RtlZeroMemory(&data, sizeof(data));
data.Queue = NULL;
data.Request = (WDFREQUEST) GetTraceObjectHandle();
data.Status = Status;
FxVerifierBugCheck(GetDriverGlobals(),
WDF_QUEUE_FATAL_ERROR,
(ULONG_PTR) &data);
}
| 26.594238 | 84 | 0.619781 | [
"object"
] |
17acbdf11ed7794e236c26d2eec3c090d639b005 | 5,035 | cpp | C++ | src/mscapi/crypto_encrypt.cpp | PeculiarVentures/pvpkcs11 | 474cf3b2a958c83ccfebf3165e45e7f46d649c81 | [
"MIT"
] | 30 | 2017-05-25T08:54:25.000Z | 2021-12-21T13:42:35.000Z | src/mscapi/crypto_encrypt.cpp | PeculiarVentures/pvpkcs11 | 474cf3b2a958c83ccfebf3165e45e7f46d649c81 | [
"MIT"
] | 37 | 2017-05-24T21:47:36.000Z | 2021-06-02T09:23:54.000Z | src/mscapi/crypto_encrypt.cpp | PeculiarVentures/pvpkcs11 | 474cf3b2a958c83ccfebf3165e45e7f46d649c81 | [
"MIT"
] | 7 | 2017-07-22T09:50:13.000Z | 2019-08-18T23:42:52.000Z | #include "crypto.h"
#include "rsa.h"
using namespace mscapi;
typedef
_Check_return_
SECURITY_STATUS
WINAPI
ncryptFn(
_In_ NCRYPT_KEY_HANDLE hKey,
_In_reads_bytes_opt_(cbInput) PBYTE pbInput,
_In_ DWORD cbInput,
_In_opt_ VOID *pPaddingInfo,
_Out_writes_bytes_to_opt_(cbOutput, *pcbResult) PBYTE pbOutput,
_In_ DWORD cbOutput,
_Out_ DWORD * pcbResult,
_In_ DWORD dwFlags);
CryptoRsaOAEPEncrypt::CryptoRsaOAEPEncrypt(
CK_BBOOL type
) :
CryptoEncrypt(type)
{
}
CK_RV CryptoRsaOAEPEncrypt::Init
(
CK_MECHANISM_PTR pMechanism,
Scoped<core::Object> key
)
{
LOGGER_FUNCTION_BEGIN;
try {
if (pMechanism->mechanism != CKM_RSA_PKCS_OAEP) {
THROW_PKCS11_MECHANISM_INVALID();
}
// Check parameters
if (pMechanism->pParameter == NULL_PTR) {
THROW_PKCS11_EXCEPTION(CKR_ARGUMENTS_BAD, "pMechanism is NULL");
}
CK_RSA_PKCS_OAEP_PARAMS_PTR params = static_cast<CK_RSA_PKCS_OAEP_PARAMS_PTR>(pMechanism->pParameter);
if (params == NULL_PTR) {
THROW_PKCS11_EXCEPTION(CKR_MECHANISM_PARAM_INVALID, "pMechanism->pParameter is not CK_RSA_PKCS_OAEP_PARAMS");
}
switch (params->hashAlg) {
case CKM_SHA_1:
digestAlg = NCRYPT_SHA1_ALGORITHM;
break;
case CKM_SHA256:
digestAlg = NCRYPT_SHA256_ALGORITHM;
break;
case CKM_SHA384:
digestAlg = NCRYPT_SHA384_ALGORITHM;
break;
case CKM_SHA512:
digestAlg = NCRYPT_SHA512_ALGORITHM;
break;
default:
THROW_PKCS11_EXCEPTION(CKR_MECHANISM_PARAM_INVALID, "Wrong hashAlg");
}
if (params->pSourceData) {
label = std::string((PCHAR)params->pSourceData, params->ulSourceDataLen);
}
else {
label = std::string("");
}
ObjectKey* cryptoKey = NULL;
if (this->type == CRYPTO_ENCRYPT) {
cryptoKey = dynamic_cast<RsaPublicKey*>(key.get());
if (!cryptoKey) {
THROW_PKCS11_EXCEPTION(CKR_KEY_TYPE_INCONSISTENT, "Key is not RSA public key");
}
}
else {
cryptoKey = dynamic_cast<RsaPrivateKey*>(key.get());
if (!cryptoKey) {
THROW_PKCS11_EXCEPTION(CKR_KEY_TYPE_INCONSISTENT, "Key is not RSA private key");
}
}
this->key = cryptoKey->GetKey();
active = true;
return CKR_OK;
}
CATCH_EXCEPTION
}
CK_RV CryptoRsaOAEPEncrypt::Once(
CK_BYTE_PTR pData,
CK_ULONG ulDataLen,
CK_BYTE_PTR pEncryptedData,
CK_ULONG_PTR pulEncryptedDataLen
)
{
LOGGER_FUNCTION_BEGIN;
try {
if (!active) {
THROW_PKCS11_OPERATION_NOT_INITIALIZED();
}
BCRYPT_OAEP_PADDING_INFO paddingInfo = {
digestAlg, // pszAlgId
(PUCHAR)(label.length() ? label.c_str() : NULL), // pbLabel
(ULONG)label.length() // cbLabel
};
ncryptFn* fn;
if (type == CRYPTO_ENCRYPT) {
fn = &NCryptEncrypt;
}
else {
fn = &NCryptDecrypt;
}
NTSTATUS status;
if (pEncryptedData == NULL) {
status = fn(
key->GetNKey()->Get(),
pData, ulDataLen,
&paddingInfo,
NULL,
0,
pulEncryptedDataLen,
BCRYPT_PAD_OAEP
);
}
else {
status = fn(
key->GetNKey()->Get(),
pData, ulDataLen,
&paddingInfo,
pEncryptedData,
*pulEncryptedDataLen,
pulEncryptedDataLen,
BCRYPT_PAD_OAEP
);
}
if (status) {
if (status == NTE_BUFFER_TOO_SMALL) {
THROW_PKCS11_BUFFER_TOO_SMALL();
}
if (status == NTE_PERM) {
THROW_PKCS11_EXCEPTION(CKR_FUNCTION_FAILED, "The key identified by the hKey parameter cannot be used for decryption.");
}
active = false;
THROW_NT_EXCEPTION(status, "CryptoRsaOAEPEncrypt::Once");
}
active = false;
return CKR_OK;
}
CATCH_EXCEPTION
}
CK_RV CryptoRsaOAEPEncrypt::Update
(
CK_BYTE_PTR pPart,
CK_ULONG ulPartLen,
CK_BYTE_PTR pEncryptedPart,
CK_ULONG_PTR pulEncryptedPartLen
)
{
LOGGER_FUNCTION_BEGIN;
try {
THROW_PKCS11_MECHANISM_INVALID();
}
CATCH_EXCEPTION
}
CK_RV CryptoRsaOAEPEncrypt::Final
(
CK_BYTE_PTR pLastEncryptedPart,
CK_ULONG_PTR pulLastEncryptedPartLen
)
{
LOGGER_FUNCTION_BEGIN;
try {
active = false;
THROW_PKCS11_MECHANISM_INVALID();
}
CATCH_EXCEPTION
} | 25.953608 | 135 | 0.558888 | [
"object"
] |
17b975464ef9683c107485bd89b46e76e6400f62 | 8,054 | cpp | C++ | source/detail/posix/theme.cpp | StillGreen-san/nana | 87ffd31013f031ef2a36331a7f776b3a00cd54b8 | [
"BSL-1.0"
] | null | null | null | source/detail/posix/theme.cpp | StillGreen-san/nana | 87ffd31013f031ef2a36331a7f776b3a00cd54b8 | [
"BSL-1.0"
] | null | null | null | source/detail/posix/theme.cpp | StillGreen-san/nana | 87ffd31013f031ef2a36331a7f776b3a00cd54b8 | [
"BSL-1.0"
] | null | null | null | #include <nana/c++defines.hpp>
#if defined(NANA_POSIX) && defined(NANA_X11)
#include "theme.hpp"
#include <filesystem>
#include <algorithm>
#include <vector>
namespace nana
{
namespace detail
{
static int gschema_override_priority(const std::string& filename)
{
if(filename.size() < 3)
return -1;
auto str = filename.substr(0, 2);
if('0' <= str[0] && str[0] <= '9' && '0' <= str[1] && str[1] <= '9')
return std::stoi(str);
return 0;
}
//Removes the wrap of ' and " character.
std::string remove_decoration(const std::string& primitive_value)
{
auto pos = primitive_value.find_first_of("'\"");
if(pos == primitive_value.npos)
return primitive_value;
auto endpos = primitive_value.find(primitive_value[pos], pos + 1);
if(endpos == primitive_value.npos)
return primitive_value;
return primitive_value.substr(pos + 1, endpos - pos - 1);
}
std::string find_value(std::ifstream& ifs, const std::string& category, const std::string& key)
{
ifs.seekg(0, std::ios::beg);
std::string dec_categ = "[" + category + "]";
bool found_cat = false;
while(ifs.good())
{
std::string text;
std::getline(ifs, text);
if((text.size() > 2) && ('[' == text[0]))
{
if(found_cat)
break;
found_cat = (text == dec_categ);
}
else if(found_cat && (text.find(key + "=") == 0))
{
return remove_decoration(text.substr(key.size() + 1));
}
}
return {};
}
std::vector<std::string> split_value(const std::string& value_string)
{
std::vector<std::string> values;
std::size_t start_pos = 0;
while(start_pos != value_string.npos)
{
auto pos = value_string.find(',', start_pos);
if(value_string.npos == pos)
{
if(start_pos < value_string.size())
values.emplace_back(value_string.substr(start_pos));
break;
}
values.emplace_back(value_string.substr(start_pos, pos - start_pos));
start_pos = value_string.find_first_not_of(',', pos);
}
return values;
}
namespace fs = std::filesystem;
std::string find_gnome_theme_name()
{
try
{
//Searches all the gschema override files
std::vector<std::string> overrides;
for(fs::directory_iterator i{"/usr/share/glib-2.0/schemas"}, end; i != end; ++i)
{
auto filename = i->path().filename().string();
if(filename.size() > 17 && filename.substr(filename.size() - 17) == ".gschema.override")
{
auto priority = gschema_override_priority(filename);
if(priority < 0)
continue;
auto i = std::find_if(overrides.cbegin(), overrides.cend(), [priority](const std::string& ovrd){
return (priority > gschema_override_priority(ovrd));
});
overrides.emplace(i, std::move(filename));
//overrides.insert(i, filename);
}
}
//Searches the org.gnome.desktop.interface in override files.
for(auto & gschema_override : overrides)
{
std::ifstream ifs{"/usr/share/glib-2.0/schemas/" + gschema_override};
auto value = find_value(ifs, "org.gnome.desktop.interface", "icon-theme");
if(!value.empty())
return value;
}
//Return the value from org.gnome.desktop.interface.gschema.xml
fs::path xml = "/usr/share/glib-2.0/schemas/org.gnome.desktop.interface.gschema.xml";
auto bytes = fs::file_size(xml);
if(0 == bytes)
return {};
std::ifstream xml_ifs{"/usr/share/glib-2.0/schemas/org.gnome.desktop.interface.gschema.xml", std::ios::binary};
if(xml_ifs)
{
std::string data;
data.resize(bytes);
xml_ifs.read(&data.front(), bytes);
auto pos = data.find("\"icon-theme\"");
if(pos != data.npos)
{
pos = data.find("<default>", pos + 22);
if(pos != data.npos)
{
pos += 9;
auto endpos = data.find("</default>", pos);
if(endpos != data.npos)
{
return remove_decoration(data.substr(pos, endpos - pos));
}
}
}
}
}
catch(...){}
return {};
}
std::string find_kde_theme_name()
{
auto home = getenv("HOME");
if(home)
{
fs::path kdeglobals{home};
kdeglobals /= ".kde/share/config/kdeglobals";
std::error_code err;
if(fs::exists(kdeglobals, err))
{
std::ifstream ifs{kdeglobals};
return find_value(ifs, "Icons", "Theme");
}
}
return {};
}
std::string find_theme_name()
{
auto name = find_kde_theme_name();
if(name.empty())
return find_gnome_theme_name();
return name;
}
class icon_theme
{
public:
icon_theme(const std::string& name):
theme_name_(name),
ifs_("/usr/share/icons/" + name + "/index.theme")
{
//First of all, read the Inherits and Directories
inherits_ = split_value(find_value(ifs_, "Icon Theme", "Inherits"));
directories_ = split_value(find_value(ifs_, "Icon Theme", "Directories"));
}
std::string find(const std::string& name, std::size_t size_wanted) const
{
namespace fs = std::filesystem;
//candidates
std::vector<std::pair<std::string,int>> first, second, third;
fs::path theme_path = "/usr/share/icons/" + theme_name_;
std::string base_path = "/usr/share/icons/" + theme_name_ + "/";
std::string filename = "/" + name + ".png";
std::error_code err;
for(auto & dir : directories_)
{
if(!fs::exists(theme_path / dir / (name + ".png"), err))
continue;
auto size = find_value(ifs_, dir, "Size");
auto type = find_value(ifs_, dir, "Type");
auto scaled = find_value(ifs_, dir, "Scale");
if(size.empty() || ("Fixed" != type))
continue;
int int_size = std::stoi(size);
if(!scaled.empty())
int_size *= std::stoi(scaled);
auto distance = std::abs(static_cast<int>(size_wanted) - int_size);
if(0 == distance)
{
if(scaled.empty() || scaled == "1")
return base_path + dir + filename;
else
first.emplace_back(dir, 0);
}
else
{
if(scaled.empty() || scaled == "1")
second.emplace_back(dir, distance);
else
third.emplace_back(dir, distance);
}
}
using pair_type = std::pair<std::string,int>;
auto comp = [](const pair_type& a, const pair_type& b){
return a.second < b.second;
};
std::sort(first.begin(), first.end(), comp);
std::sort(second.begin(), second.end(), comp);
std::sort(third.begin(), third.end(), comp);
std::string closer_dir;
if(!first.empty())
closer_dir = first.front().first;
else if(!second.empty())
closer_dir = second.front().first;
else if(!third.empty())
closer_dir = third.front().first;
if(closer_dir.empty())
{
for(auto & inh : inherits_)
{
auto dir = icon_theme{inh}.find(name, size_wanted);
if(!dir.empty())
return dir;
}
//Avoid recursively traverse directory for hicolor if current theme name is hicolor
if("hicolor" == theme_name_)
return {};
return icon_theme{"hicolor"}.find(name, size_wanted);
}
return base_path + closer_dir + filename;
}
private:
const std::string theme_name_;
mutable std::ifstream ifs_;
std::vector<std::string> inherits_;
std::vector<std::string> directories_;
};
theme::theme():
path_("/usr/share/icons/"),
ifs_("/usr/share/icons/default/index.theme")
{
}
std::string theme::cursor(const std::string& name) const
{
auto theme = find_value(ifs_, "Icon Theme", "Inherits");
return path_ + theme + "/cursors/" + name;
}
std::string theme::icon(const std::string& name, std::size_t size_wanted) const
{
//Lookup in cache
auto i = iconcache_.find(name);
if(i != iconcache_.end())
{
for(auto & p : i->second)
{
if(p.first == size_wanted)
return p.second;
}
}
//Cache is missed.
auto file = icon_theme{find_theme_name()}.find(name, size_wanted);
if(!file.empty())
iconcache_[name].emplace_back(size_wanted, file);
return file;
}
}
}
#endif | 24.705521 | 115 | 0.603799 | [
"vector"
] |
17c30f6841d86a3d16831d938efa25862cd14adc | 3,449 | hpp | C++ | native/jni/init/init.hpp | Joyoe/Magisk-23001-jojo-t2 | 28f7bffe248c380c55335ad438f7d2a6392fd0be | [
"MIT"
] | 2 | 2022-01-16T00:59:54.000Z | 2022-02-09T12:00:48.000Z | native/jni/init/init.hpp | Joyoe/Magisk-23001-jojo-t2 | 28f7bffe248c380c55335ad438f7d2a6392fd0be | [
"MIT"
] | 1 | 2022-02-09T11:55:40.000Z | 2022-02-09T11:55:40.000Z | native/jni/init/init.hpp | Joyoe/Magisk-23001-jojo-t2 | 28f7bffe248c380c55335ad438f7d2a6392fd0be | [
"MIT"
] | 2 | 2022-02-09T12:00:39.000Z | 2022-02-21T18:34:46.000Z | #include <utils.hpp>
#include "raw_data.hpp"
struct cmdline {
bool skip_initramfs;
bool force_normal_boot;
bool rootwait;
char slot[3];
char dt_dir[64];
char fstab_suffix[32];
char hardware[32];
char hardware_plat[32];
};
struct fstab_entry {
std::string dev;
std::string mnt_point;
std::string type;
std::string mnt_flags;
std::string fsmgr_flags;
fstab_entry() = default;
fstab_entry(const fstab_entry &) = delete;
fstab_entry(fstab_entry &&) = default;
void to_file(FILE *fp);
};
#define INIT_SOCKET "MAGISKINIT"
#define DEFAULT_DT_DIR "/proc/device-tree/firmware/android"
extern std::vector<std::string> mount_list;
bool unxz(int fd, const uint8_t *buf, size_t size);
void load_kernel_info(cmdline *cmd);
bool check_two_stage();
void setup_klog();
/***************
* Base classes
***************/
class BaseInit {
protected:
cmdline *cmd;
char **argv;
[[noreturn]] void exec_init();
void read_dt_fstab(std::vector<fstab_entry> &fstab);
public:
BaseInit(char *argv[], cmdline *cmd) : cmd(cmd), argv(argv) {}
virtual ~BaseInit() = default;
virtual void start() = 0;
};
class MagiskInit : public BaseInit {
protected:
mmap_data self;
mmap_data config;
std::string custom_rules_dir;
void mount_with_dt();
bool patch_sepolicy(const char *file);
void setup_tmp(const char *path);
void mount_rules_dir(const char *dev_base, const char *mnt_base);
public:
MagiskInit(char *argv[], cmdline *cmd) : BaseInit(argv, cmd) {}
};
class SARBase : public MagiskInit {
protected:
std::vector<raw_file> overlays;
void backup_files();
void patch_rootdir();
void mount_system_root();
public:
SARBase(char *argv[], cmdline *cmd) : MagiskInit(argv, cmd) {}
};
/***************
* 2 Stage Init
***************/
class FirstStageInit : public BaseInit {
private:
void prepare();
public:
FirstStageInit(char *argv[], cmdline *cmd) : BaseInit(argv, cmd) {
LOGD("%s\n", __FUNCTION__);
};
void start() override {
prepare();
exec_init();
}
};
class SecondStageInit : public SARBase {
private:
void prepare();
public:
SecondStageInit(char *argv[]) : SARBase(argv, nullptr) {
LOGD("%s\n", __FUNCTION__);
};
void start() override {
prepare();
patch_rootdir();
exec_init();
}
};
/*************
* Legacy SAR
*************/
class SARInit : public SARBase {
private:
bool is_two_stage;
void early_mount();
void first_stage_prep();
public:
SARInit(char *argv[], cmdline *cmd) : SARBase(argv, cmd), is_two_stage(false) {
LOGD("%s\n", __FUNCTION__);
};
void start() override {
early_mount();
if (is_two_stage)
first_stage_prep();
else
patch_rootdir();
exec_init();
}
};
/************
* Initramfs
************/
class RootFSInit : public MagiskInit {
private:
void early_mount();
void patch_rootfs();
public:
RootFSInit(char *argv[], cmdline *cmd) : MagiskInit(argv, cmd) {
LOGD("%s\n", __FUNCTION__);
}
void start() override {
early_mount();
patch_rootfs();
exec_init();
}
};
class MagiskProxy : public MagiskInit {
public:
explicit MagiskProxy(char *argv[]) : MagiskInit(argv, nullptr) {
LOGD("%s\n", __FUNCTION__);
}
void start() override;
};
| 21.290123 | 83 | 0.610322 | [
"vector"
] |
17c63d2088f7d0d3a9d68f8a53983e2153cf7967 | 7,038 | cc | C++ | MagneticField/ParametrizedEngine/src/BFit.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | MagneticField/ParametrizedEngine/src/BFit.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | MagneticField/ParametrizedEngine/src/BFit.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "BFit.h"
#include <cstring>
using namespace std;
using namespace magfieldparam;
//_______________________________________________________________________________
#ifdef BFit_PW
const double BFit::Z_nom[4] = { -2.37615687260664e-2,
-1.86400109250045e-2,
-1.80502358070104e-2,
-1.60470955291956e-2 };
const double BFit::B_nom[4] = { 2.02156567013928, //Nominal foeld values
3.51622117206486,
3.81143026675623,
4.01242188708911 };
const double BFit::C_nom[4][16] = {{ 1.0, -3.61278802720839e-3,
6.36561393690475e-6, 8.32541914664693e-5,
-2.42108313492765e-6, -1.87295909297299e-5,
3.06832709074461e-7, 1.91827319271226e-6,
-2.15392717311725e-8, -1.25266203359502e-7,
3.87507522135914e-10, 4.85518568040635e-9,
4.42080729840719e-11, -8.83065447433858e-11,
-2.41380148377896e-12, 0.0 },
{ 1.0, -5.04020236643808e-3,
2.03224205921125e-6, 6.79444854179620e-5,
-1.98082200052911e-6, -1.93324798138490e-5,
3.15120940544812e-7, 1.82623212354924e-6,
-3.30483297560429e-8, -1.13251951654739e-7,
1.96974144659278e-9, 4.25153392971594e-9,
-6.12986034064675e-11, -7.59031334826116e-11,
6.40295019219590e-13, 0.0 },
{ 1.0, -5.23012318846739e-3,
8.80302231241395e-7, 6.51341641212249e-5,
-1.68564063895995e-6, -1.93693613146655e-5,
2.58178734098114e-7, 1.81311192824207e-6,
-2.79301520182866e-8, -1.11679980224632e-7,
1.72615649164433e-9, 4.17328869038146e-9,
-5.72514160410955e-11, -7.41998111228714e-11,
7.30938527053447e-13, 0.0 },
{ 1.0, -5.34172971309074e-3,
2.48943649506081e-7, 6.23054033447814e-5,
-1.60390978074464e-6, -1.92618217244767e-5,
2.42461261622770e-7, 1.78772142159379e-6,
-2.61432416866515e-8, -1.09159464672341e-7,
1.62705377496138e-9, 4.02967933726133e-9,
-5.48168162195020e-11, -7.00249566028285e-11,
8.22254619144001e-13, 0.0 }};
#else
const double BFit::dZ_0 = -2.62328760352034e-2;
const double BFit::dZ_2 = 5.94363870284212e-4;
const double BFit::C_0[16] = { 1.0, -2.52864632909442e-3,
8.76365790071351e-6, 9.19077286315044e-5,
-2.49284256023752e-6, -1.80143891826520e-5,
2.29295162454016e-7, 1.96139195659245e-6,
-3.47342625923464e-9, -1.32147627969588e-7,
-1.50735830442900e-9, 5.17724172101696e-9,
1.54539960459831e-10, -9.30914368388717e-11,
-5.20466591966397e-12, 0.0 };
const double BFit::C_2[16] = { 0.0, -2.96314154618866e-4,
-6.04246295125223e-7, -2.22393436573694e-6,
2.84133631738674e-9, -2.07090716476209e-7,
2.55850963123821e-8, -1.06689136150163e-8,
-5.48842256680751e-9, 1.78987539969165e-9,
5.57809366992069e-10, -8.25055601520632e-11,
-3.18509299957904e-11, 1.11714602344300e-12,
7.90102331886296e-13, 0.0 };
const double BFit::C_4[16] = { 0.0, 7.57194953855834e-6,
4.48169046115052e-9, 2.49606093449927e-8,
3.42264285146368e-9, 7.95338846845187e-9,
-1.57711106312732e-9, 1.02715424120585e-11,
2.57261485255293e-10, -2.41682937761163e-11,
-2.27894837943020e-11, 7.98570801347331e-13,
1.17889573705870e-12, 1.64571374852252e-14,
-2.60212133934707e-14, 0.0 };
#endif
//_______________________________________________________________________________
BFit::BFit()
{
dZ = 0.;
memset(C, 0, 16*sizeof(double));
rz_poly *P_base = new rz_poly(16); //Potential basis
Bz_base = new rz_poly(P_base->Diff(1)); //Bz basis
Bz_base->SetOFF(1); //Switch off linear term
Br_base = new rz_poly(P_base->Diff(0)); //Br basis is shifted, so
Br_base->SetOFF(0); //"0" term is ignored
delete P_base;
}
//_______________________________________________________________________________
void BFit::SetField(double B)
{
//Set nominal field [Tesla]
//
unsigned int jj;
#ifdef BFit_PW
unsigned int kk = 1;
double w_0, w_1;
if (B <= B_nom[0]) {
dZ = Z_nom[0];
for (jj = 0; jj < 16; ++jj) {
C[jj] = B*C_nom[0][jj];
}
} else if (B >= B_nom[3]) {
dZ = Z_nom[3];
for (jj = 0; jj < 16; ++jj) {
C[jj] = B*C_nom[3][jj];
}
} else {
while (B_nom[kk] < B) ++kk;
w_1 = (B - B_nom[kk-1])/(B_nom[kk] - B_nom[kk-1]);
w_0 = 1.0 - w_1;
dZ = Z_nom[kk-1]*w_0 + Z_nom[kk]*w_1;
for (jj = 0; jj < 16; ++jj) {
C[jj] = B*(C_nom[kk-1][jj]*w_0 + C_nom[kk][jj]*w_1);
}
}
#else
double B2 = B*B;
dZ = dZ_0 + dZ_2*B2;
for (jj = 0; jj < 16; ++jj) {
C[jj] = B*((C_4[jj]*B2 + C_2[jj])*B2 + C_0[jj]);
}
#endif
}
//_______________________________________________________________________________
void BFit::GetField(double r, double z, double phi,
double &Br, double &Bz, double &Bphi) const
{
//Get field components in the point (r,z,phi). Always return Bphi=0.
//Parameters phi and Bphi introduced in order to keep interface
//compatible with future trully 3D version
//
double zc = z + dZ;
Bz = Bz_base->GetSVal(r, zc, C);
Br = Br_base->GetSVal(r, zc, C+1);
Bphi = 0.;
}
| 46.302632 | 82 | 0.47272 | [
"3d"
] |
17cb5491497db7296c0b72a741de0978438b1d0e | 1,491 | cc | C++ | ghpi/webscripts/modules/shm_togglelamp.cc | Sc0rpe/GreenHousePi | a193cee9acbe61f5c682b3d48132b315a6a97af8 | [
"Unlicense"
] | null | null | null | ghpi/webscripts/modules/shm_togglelamp.cc | Sc0rpe/GreenHousePi | a193cee9acbe61f5c682b3d48132b315a6a97af8 | [
"Unlicense"
] | 3 | 2018-04-26T14:16:54.000Z | 2018-10-09T14:37:35.000Z | ghpi/webscripts/modules/shm_togglelamp.cc | Sc0rpe/GreenHousePi | a193cee9acbe61f5c682b3d48132b315a6a97af8 | [
"Unlicense"
] | null | null | null | //
// 2018 Rico Schulz
//
#pragma once
#include <vector>
#include <iostream>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include "operator.h"
#include "action.h"
using namespace boost::interprocess;
int main() {
boost::interprocess::shared_memory_object shm_messages_;
boost::interprocess::mapped_region region_;
shm_messages_ = shared_memory_object(open_only, ghpi::Operator::SHM_NAME, read_write);
shm_messages_.truncate(sizeof(ghpi::Operator::MSGQueue));
region_ = mapped_region(shm_messages_, read_write);
//Get the address of the mapped region
void * addr = region_.get_address();
//Construct the shared structure in memory
ghpi::Operator::MSGQueue * data = static_cast<ghpi::Operator::MSGQueue*>(addr);
ghpi::Action toggle_lamp("ToggleLamp", ghpi::ActionFn::AFN_TOGGLE, NULL, "Lamp", true);
ghpi::Action op_manu_lamp("OperateManually", ghpi::ActionFn::AFN_OP_MANU, NULL, "Lamp", true);
{ // Code block for scoped_lock. Mutex will automatically unlock after block.
// even if an exception occurs
scoped_lock<interprocess_mutex> lock(data->mutex);
// Put the action in the shared memory object
data->Put(toggle_lamp);
data->Put(op_manu_lamp);
}
std::cout << "Added Action " << toggle_lamp.get_name() << " to queue" << std::endl;
return 0;
} | 33.886364 | 95 | 0.731053 | [
"object",
"vector"
] |
17ccc7fa55bd6b4829009be4e0ad81f1b9a1cf73 | 3,489 | cpp | C++ | NetMePiet/src/main.cpp | Assertores/NetMePiet | b2054d9c41f214f6c4a285c4798fd281d5c2d12d | [
"MIT"
] | null | null | null | NetMePiet/src/main.cpp | Assertores/NetMePiet | b2054d9c41f214f6c4a285c4798fd281d5c2d12d | [
"MIT"
] | null | null | null | NetMePiet/src/main.cpp | Assertores/NetMePiet | b2054d9c41f214f6c4a285c4798fd281d5c2d12d | [
"MIT"
] | null | null | null | #include "network/netcode_api.hpp"
#include <chrono>
#include <ratio>
#include <SDL.h>
#include <glad/glad.h>
#include <imgui/imgui.h>
#include <imgui/examples/imgui_impl_opengl3.h>
#include <imgui/examples/imgui_impl_sdl.h>
#include <screens/screen.hpp>
#include <screens/startup_screen.hpp>
//#include <screens/imgui_demo_screen.hpp>
int main(int argc, char* argv[]) {
if (SDL_Init(SDL_INIT_EVERYTHING)) {
SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
return 1;
}
uint32_t window_flags = 0;
window_flags |= SDL_WINDOW_OPENGL;
window_flags |= SDL_WINDOW_SHOWN;
window_flags |= SDL_WINDOW_RESIZABLE;
//Use OpenGL 3.3 core
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_Window* window = SDL_CreateWindow("NetMePiet", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1280, 720, window_flags);
if (!window) {
SDL_Log("Unable to create window: %s", SDL_GetError());
return 1;
}
auto gl_context = SDL_GL_CreateContext(window);
if (!gl_context) {
SDL_Log("Unable to create opengl context: %s", SDL_GetError());
SDL_DestroyWindow(window);
return 1;
}
// glad
if (!gladLoadGLLoader((GLADloadproc) SDL_GL_GetProcAddress)) {
SDL_Log("Failed to initialize OpenGL context");
SDL_GL_DeleteContext(gl_context);
SDL_DestroyWindow(window);
return 1;
}
if (SDL_GL_MakeCurrent(window, gl_context)) {
SDL_Log("SDL_GL_MakeCurrent(): %s", SDL_GetError());
SDL_GL_DeleteContext(gl_context);
SDL_DestroyWindow(window);
return 1;
}
// imgui
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
(void)io;
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
//io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
ImGui_ImplSDL2_InitForOpenGL(window, gl_context);
ImGui_ImplOpenGL3_Init();
// style
{
ImGui::StyleColorsDark();
auto& style = ImGui::GetStyle();
style.WindowRounding = 2.f;
}
}
//NMP::Screens::ScreenI* curr_screen = new NMP::Screens::ImGuiDemoScreen(); // new
NMP::Screens::ScreenI* curr_screen = new NMP::Screens::StartupScreen(); // new
auto last_clock = std::chrono::high_resolution_clock::now();
while (curr_screen) {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(window);
ImGui::NewFrame();
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
delete curr_screen;
curr_screen = nullptr;
break;
}
ImGui_ImplSDL2_ProcessEvent(&event);
}
if (!curr_screen) {
break;
}
auto new_clock = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> delta = new_clock - last_clock;
last_clock = new_clock;
curr_screen->update(delta.count());
// render
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(window);
glClearColor(0.1f, 0.1f, 0.1f, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
if (curr_screen->finished()) {
auto* prev_screen = curr_screen;
curr_screen = curr_screen->getNextScreen();
delete prev_screen;
}
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
SDL_GL_DeleteContext(gl_context);
SDL_DestroyWindow(window);
// teardown global state and shutdown sdl_net
NMP::Network::ShutDown();
SDL_Quit();
return 0;
}
| 24.398601 | 127 | 0.729722 | [
"render"
] |
17ce04c5e4cdb00f1eca5d6bc95efe191874ce9a | 94,307 | cpp | C++ | VkLayer_profiler_layer/profiler_overlay/profiler_overlay.cpp | lstalmir/VulkanProfiler | da06f27d71bf753bdef575ba1ed35e0acb8e84e7 | [
"MIT"
] | 1 | 2021-03-11T12:10:20.000Z | 2021-03-11T12:10:20.000Z | VkLayer_profiler_layer/profiler_overlay/profiler_overlay.cpp | lstalmir/VulkanProfiler | da06f27d71bf753bdef575ba1ed35e0acb8e84e7 | [
"MIT"
] | 10 | 2020-12-09T15:14:11.000Z | 2021-01-23T18:52:26.000Z | VkLayer_profiler_layer/profiler_overlay/profiler_overlay.cpp | lstalmir/VulkanProfiler | da06f27d71bf753bdef575ba1ed35e0acb8e84e7 | [
"MIT"
] | null | null | null | // Copyright (c) 2019-2021 Lukasz Stalmirski
//
// 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 "profiler_overlay.h"
#include "profiler_trace/profiler_trace.h"
#include "profiler_helpers/profiler_data_helpers.h"
#include "imgui_impl_vulkan_layer.h"
#include <string>
#include <sstream>
#include <stack>
#include <fstream>
#include "utils/lockable_unordered_map.h"
#include "imgui_widgets/imgui_breakdown_ex.h"
#include "imgui_widgets/imgui_histogram_ex.h"
#include "imgui_widgets/imgui_table_ex.h"
#include "imgui_widgets/imgui_ex.h"
// Languages
#include "lang/en_us.h"
#include "lang/pl_pl.h"
#if 1
using Lang = Profiler::DeviceProfilerOverlayLanguage_Base;
#else
using Lang = Profiler::DeviceProfilerOverlayLanguage_PL;
#endif
#ifdef VK_USE_PLATFORM_WIN32_KHR
#include "imgui_impl_win32.h"
#endif
#ifdef WIN32
#include <ShlObj.h> // SHGetKnownFolderPath
#endif
#ifdef VK_USE_PLATFORM_WAYLAND_KHR
#include <wayland-client.h>
#endif
#ifdef VK_USE_PLATFORM_XCB_KHR
#include "imgui_impl_xcb.h"
#endif
#ifdef VK_USE_PLATFORM_XLIB_KHR
#include "imgui_impl_xlib.h"
#endif
#ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT
#include <X11/extensions/Xrandr.h>
#endif
namespace Profiler
{
// Define static members
std::mutex ProfilerOverlayOutput::s_ImGuiMutex;
struct ProfilerOverlayOutput::PerformanceGraphColumn : ImGuiX::HistogramColumnData
{
HistogramGroupMode groupMode;
FrameBrowserTreeNodeIndex nodeIndex;
};
/***********************************************************************************\
Function:
ProfilerOverlayOutput
Description:
Constructor.
\***********************************************************************************/
ProfilerOverlayOutput::ProfilerOverlayOutput()
: m_pDevice( nullptr )
, m_pGraphicsQueue( nullptr )
, m_pSwapchain( nullptr )
, m_Window()
, m_pImGuiContext( nullptr )
, m_pImGuiVulkanContext( nullptr )
, m_pImGuiWindowContext( nullptr )
, m_DescriptorPool( VK_NULL_HANDLE )
, m_RenderPass( VK_NULL_HANDLE )
, m_RenderArea( {} )
, m_ImageFormat( VK_FORMAT_UNDEFINED )
, m_Images()
, m_ImageViews()
, m_Framebuffers()
, m_CommandPool( VK_NULL_HANDLE )
, m_CommandBuffers()
, m_CommandFences()
, m_CommandSemaphores()
, m_VendorMetricProperties()
, m_TimestampPeriod( 0 )
, m_FrameBrowserSortMode( FrameBrowserSortMode::eSubmissionOrder )
, m_HistogramGroupMode( HistogramGroupMode::eRenderPass )
, m_Pause( false )
, m_ShowDebugLabels( true )
, m_SelectedFrameBrowserNodeIndex( { 0xFFFF } )
, m_ScrollToSelectedFrameBrowserNode( false )
, m_SelectionUpdateTimestamp( std::chrono::high_resolution_clock::duration::zero() )
, m_SerializationFinishTimestamp( std::chrono::high_resolution_clock::duration::zero() )
, m_SerializationSucceeded( false )
, m_SerializationMessage()
, m_SerializationOutputWindowSize( { 0, 0 } )
, m_SerializationOutputWindowDuration( std::chrono::seconds( 4 ) )
, m_SerializationOutputWindowFadeOutDuration( std::chrono::seconds( 1 ) )
, m_RenderPassColumnColor( 0 )
, m_GraphicsPipelineColumnColor( 0 )
, m_ComputePipelineColumnColor( 0 )
, m_InternalPipelineColumnColor( 0 )
, m_pStringSerializer( nullptr )
{
}
/***********************************************************************************\
Function:
Initialize
Description:
Initializes profiler overlay.
\***********************************************************************************/
VkResult ProfilerOverlayOutput::Initialize(
VkDevice_Object& device,
VkQueue_Object& graphicsQueue,
VkSwapchainKhr_Object& swapchain,
const VkSwapchainCreateInfoKHR* pCreateInfo )
{
VkResult result = VK_SUCCESS;
// Setup objects
m_pDevice = &device;
m_pGraphicsQueue = &graphicsQueue;
m_pSwapchain = &swapchain;
// Create descriptor pool
if( result == VK_SUCCESS )
{
VkDescriptorPoolCreateInfo descriptorPoolCreateInfo = {};
descriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
// TODO: Is this necessary?
const VkDescriptorPoolSize descriptorPoolSizes[] = {
{ VK_DESCRIPTOR_TYPE_SAMPLER, 1000 },
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 },
{ VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 },
{ VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 } };
descriptorPoolCreateInfo.maxSets = 1000;
descriptorPoolCreateInfo.poolSizeCount = std::extent_v<decltype(descriptorPoolSizes)>;
descriptorPoolCreateInfo.pPoolSizes = descriptorPoolSizes;
result = m_pDevice->Callbacks.CreateDescriptorPool(
m_pDevice->Handle,
&descriptorPoolCreateInfo,
nullptr,
&m_DescriptorPool );
}
// Create command pool
if( result == VK_SUCCESS )
{
VkCommandPoolCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
info.flags |= VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
info.queueFamilyIndex = m_pGraphicsQueue->Family;
result = m_pDevice->Callbacks.CreateCommandPool(
m_pDevice->Handle,
&info,
nullptr,
&m_CommandPool );
}
// Get timestamp query period
if( result == VK_SUCCESS )
{
m_TimestampPeriod = Nanoseconds( m_pDevice->pPhysicalDevice->Properties.limits.timestampPeriod );
}
// Create swapchain-dependent resources
if( result == VK_SUCCESS )
{
result = ResetSwapchain( swapchain, pCreateInfo );
}
// Init ImGui
if( result == VK_SUCCESS )
{
std::scoped_lock lk( s_ImGuiMutex );
IMGUI_CHECKVERSION();
m_pImGuiContext = ImGui::CreateContext();
ImGui::SetCurrentContext( m_pImGuiContext );
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = { (float)m_RenderArea.width, (float)m_RenderArea.height };
io.DeltaTime = 1.0f / 60.0f;
io.IniFilename = "VK_LAYER_profiler_imgui.ini";
io.ConfigFlags = ImGuiConfigFlags_None;
InitializeImGuiDefaultFont();
InitializeImGuiStyle();
}
// Init window
if( result == VK_SUCCESS )
{
result = InitializeImGuiWindowHooks( pCreateInfo );
}
// Init vulkan
if( result == VK_SUCCESS )
{
result = InitializeImGuiVulkanContext( pCreateInfo );
}
// Get vendor metric properties
if( result == VK_SUCCESS )
{
uint32_t vendorMetricCount = 0;
vkEnumerateProfilerPerformanceCounterPropertiesEXT( device.Handle, &vendorMetricCount, nullptr );
m_VendorMetricProperties.resize( vendorMetricCount );
vkEnumerateProfilerPerformanceCounterPropertiesEXT( device.Handle, &vendorMetricCount, m_VendorMetricProperties.data() );
}
// Initialize serializer
if( result == VK_SUCCESS )
{
result = (m_pStringSerializer = new (std::nothrow) DeviceProfilerStringSerializer( device ))
? VK_SUCCESS
: VK_ERROR_OUT_OF_HOST_MEMORY;
}
// Don't leave object in partly-initialized state if something went wrong
if( result != VK_SUCCESS )
{
Destroy();
}
return result;
}
/***********************************************************************************\
Function:
Destroy
Description:
Destructor.
\***********************************************************************************/
void ProfilerOverlayOutput::Destroy()
{
if( m_pDevice )
{
m_pDevice->Callbacks.DeviceWaitIdle( m_pDevice->Handle );
}
if( m_pStringSerializer )
{
delete m_pStringSerializer;
m_pStringSerializer = nullptr;
}
if( m_pImGuiVulkanContext )
{
delete m_pImGuiVulkanContext;
m_pImGuiVulkanContext = nullptr;
}
if( m_pImGuiWindowContext )
{
delete m_pImGuiWindowContext;
m_pImGuiWindowContext = nullptr;
}
if( m_pImGuiContext )
{
ImGui::DestroyContext( m_pImGuiContext );
m_pImGuiContext = nullptr;
}
if( m_DescriptorPool )
{
m_pDevice->Callbacks.DestroyDescriptorPool( m_pDevice->Handle, m_DescriptorPool, nullptr );
m_DescriptorPool = VK_NULL_HANDLE;
}
if( m_RenderPass )
{
m_pDevice->Callbacks.DestroyRenderPass( m_pDevice->Handle, m_RenderPass, nullptr );
m_RenderPass = VK_NULL_HANDLE;
}
if( m_CommandPool )
{
m_pDevice->Callbacks.DestroyCommandPool( m_pDevice->Handle, m_CommandPool, nullptr );
m_CommandPool = VK_NULL_HANDLE;
}
m_CommandBuffers.clear();
for( auto& framebuffer : m_Framebuffers )
{
m_pDevice->Callbacks.DestroyFramebuffer( m_pDevice->Handle, framebuffer, nullptr );
}
m_Framebuffers.clear();
for( auto& imageView : m_ImageViews )
{
m_pDevice->Callbacks.DestroyImageView( m_pDevice->Handle, imageView, nullptr );
}
m_ImageViews.clear();
for( auto& fence : m_CommandFences )
{
m_pDevice->Callbacks.DestroyFence( m_pDevice->Handle, fence, nullptr );
}
m_CommandFences.clear();
for( auto& semaphore : m_CommandSemaphores )
{
m_pDevice->Callbacks.DestroySemaphore( m_pDevice->Handle, semaphore, nullptr );
}
m_CommandSemaphores.clear();
m_Window = OSWindowHandle();
m_pDevice = nullptr;
}
/***********************************************************************************\
Function:
IsAvailable
Description:
Check if profiler overlay is ready for presenting.
\***********************************************************************************/
bool ProfilerOverlayOutput::IsAvailable() const
{
#ifndef _DEBUG
// There are many other objects that could be checked here, but we're keeping
// object quite consistent in case of any errors during initialization, so
// checking just one should be sufficient.
return (m_pSwapchain);
#else
// Check object state to confirm the note above
return (m_pSwapchain)
&& (m_pDevice)
&& (m_pGraphicsQueue)
&& (m_pImGuiContext)
&& (m_pImGuiVulkanContext)
&& (m_pImGuiWindowContext)
&& (m_RenderPass)
&& (!m_CommandBuffers.empty());
#endif
}
/***********************************************************************************\
Function:
GetSwapchain
Description:
Return swapchain the overlay is associated with.
\***********************************************************************************/
VkSwapchainKHR ProfilerOverlayOutput::GetSwapchain() const
{
return m_pSwapchain->Handle;
}
/***********************************************************************************\
Function:
ResetSwapchain
Description:
Move overlay to the new swapchain.
\***********************************************************************************/
VkResult ProfilerOverlayOutput::ResetSwapchain(
VkSwapchainKhr_Object& swapchain,
const VkSwapchainCreateInfoKHR* pCreateInfo )
{
assert( m_pSwapchain == nullptr ||
pCreateInfo->oldSwapchain == m_pSwapchain->Handle ||
pCreateInfo->oldSwapchain == VK_NULL_HANDLE );
VkResult result = VK_SUCCESS;
// Get swapchain images
uint32_t swapchainImageCount = 0;
m_pDevice->Callbacks.GetSwapchainImagesKHR(
m_pDevice->Handle,
swapchain.Handle,
&swapchainImageCount,
nullptr );
std::vector<VkImage> images( swapchainImageCount );
result = m_pDevice->Callbacks.GetSwapchainImagesKHR(
m_pDevice->Handle,
swapchain.Handle,
&swapchainImageCount,
images.data() );
assert( result == VK_SUCCESS );
// Recreate render pass if swapchain format has changed
if( (result == VK_SUCCESS) && (pCreateInfo->imageFormat != m_ImageFormat) )
{
if( m_RenderPass != VK_NULL_HANDLE )
{
// Destroy old render pass
m_pDevice->Callbacks.DestroyRenderPass( m_pDevice->Handle, m_RenderPass, nullptr );
}
VkAttachmentDescription attachment = {};
attachment.format = pCreateInfo->imageFormat;
attachment.samples = VK_SAMPLE_COUNT_1_BIT;
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment.initialLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference color_attachment = {};
color_attachment.attachment = 0;
color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color_attachment;
VkSubpassDependency dependency = {};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
VkRenderPassCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
info.attachmentCount = 1;
info.pAttachments = &attachment;
info.subpassCount = 1;
info.pSubpasses = &subpass;
info.dependencyCount = 1;
info.pDependencies = &dependency;
result = m_pDevice->Callbacks.CreateRenderPass(
m_pDevice->Handle,
&info,
nullptr,
&m_RenderPass );
m_ImageFormat = pCreateInfo->imageFormat;
}
// Recreate image views and framebuffers
// This is required because swapchain images have changed and current framebuffer is out of date
if( result == VK_SUCCESS )
{
if( !m_Images.empty() )
{
// Destroy previous framebuffers
for( int i = 0; i < m_Images.size(); ++i )
{
m_pDevice->Callbacks.DestroyFramebuffer( m_pDevice->Handle, m_Framebuffers[ i ], nullptr );
m_pDevice->Callbacks.DestroyImageView( m_pDevice->Handle, m_ImageViews[ i ], nullptr );
}
m_Framebuffers.clear();
m_ImageViews.clear();
}
for( uint32_t i = 0; i < swapchainImageCount; i++ )
{
VkImageView imageView = VK_NULL_HANDLE;
VkFramebuffer framebuffer = VK_NULL_HANDLE;
// Create swapchain image view
if( result == VK_SUCCESS )
{
VkImageViewCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
info.viewType = VK_IMAGE_VIEW_TYPE_2D;
info.format = pCreateInfo->imageFormat;
info.image = images[ i ];
info.components.r = VK_COMPONENT_SWIZZLE_R;
info.components.g = VK_COMPONENT_SWIZZLE_G;
info.components.b = VK_COMPONENT_SWIZZLE_B;
info.components.a = VK_COMPONENT_SWIZZLE_A;
VkImageSubresourceRange range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
info.subresourceRange = range;
result = m_pDevice->Callbacks.CreateImageView(
m_pDevice->Handle,
&info,
nullptr,
&imageView );
m_ImageViews.push_back( imageView );
}
// Create framebuffer
if( result == VK_SUCCESS )
{
VkFramebufferCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
info.renderPass = m_RenderPass;
info.attachmentCount = 1;
info.pAttachments = &imageView;
info.width = pCreateInfo->imageExtent.width;
info.height = pCreateInfo->imageExtent.height;
info.layers = 1;
result = m_pDevice->Callbacks.CreateFramebuffer(
m_pDevice->Handle,
&info,
nullptr,
&framebuffer );
m_Framebuffers.push_back( framebuffer );
}
}
m_RenderArea = pCreateInfo->imageExtent;
}
// Allocate additional command buffers, fences and semaphores
if( (result == VK_SUCCESS) && (swapchainImageCount > m_Images.size()) )
{
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = m_CommandPool;
allocInfo.commandBufferCount = swapchainImageCount - m_Images.size();
std::vector<VkCommandBuffer> commandBuffers( swapchainImageCount );
result = m_pDevice->Callbacks.AllocateCommandBuffers(
m_pDevice->Handle,
&allocInfo,
commandBuffers.data() );
if( result == VK_SUCCESS )
{
// Append created command buffers to end
// We need to do this right after allocation to avoid leaks if something fails later
m_CommandBuffers.insert( m_CommandBuffers.end(), commandBuffers.begin(), commandBuffers.end() );
}
for( auto cmdBuffer : commandBuffers )
{
if( result == VK_SUCCESS )
{
// Command buffers are dispatchable handles, update pointers to parent's dispatch table
result = m_pDevice->SetDeviceLoaderData( m_pDevice->Handle, cmdBuffer );
}
}
// Create additional per-command-buffer semaphores and fences
for( int i = m_Images.size(); i < swapchainImageCount; ++i )
{
VkFence fence;
VkSemaphore semaphore;
// Create command buffer fence
if( result == VK_SUCCESS )
{
VkFenceCreateInfo fenceInfo = {};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.flags |= VK_FENCE_CREATE_SIGNALED_BIT;
result = m_pDevice->Callbacks.CreateFence(
m_pDevice->Handle,
&fenceInfo,
nullptr,
&fence );
m_CommandFences.push_back( fence );
}
// Create present semaphore
if( result == VK_SUCCESS )
{
VkSemaphoreCreateInfo semaphoreInfo = {};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
result = m_pDevice->Callbacks.CreateSemaphore(
m_pDevice->Handle,
&semaphoreInfo,
nullptr,
&semaphore );
m_CommandSemaphores.push_back( semaphore );
}
}
}
// Update objects
if( result == VK_SUCCESS )
{
m_pSwapchain = &swapchain;
m_Images = images;
}
// Reinitialize ImGui
if( (m_pImGuiContext) )
{
if( result == VK_SUCCESS )
{
// Reinit window
result = InitializeImGuiWindowHooks( pCreateInfo );
}
if( result == VK_SUCCESS )
{
// Init vulkan
result = InitializeImGuiVulkanContext( pCreateInfo );
}
}
// Don't leave object in partly-initialized state
if( result != VK_SUCCESS )
{
Destroy();
}
return result;
}
/***********************************************************************************\
Function:
Present
Description:
Draw profiler overlay before presenting the image to screen.
\***********************************************************************************/
void ProfilerOverlayOutput::Present(
const DeviceProfilerFrameData& data,
const VkQueue_Object& queue,
VkPresentInfoKHR* pPresentInfo )
{
// Record interface draw commands
Update( data );
if( ImGui::GetDrawData() )
{
// Grab command buffer for overlay commands
const uint32_t imageIndex = pPresentInfo->pImageIndices[ 0 ];
// Per-
VkFence& fence = m_CommandFences[ imageIndex ];
VkSemaphore& semaphore = m_CommandSemaphores[ imageIndex ];
VkCommandBuffer& commandBuffer = m_CommandBuffers[ imageIndex ];
VkFramebuffer& framebuffer = m_Framebuffers[ imageIndex ];
m_pDevice->Callbacks.WaitForFences( m_pDevice->Handle, 1, &fence, VK_TRUE, UINT64_MAX );
m_pDevice->Callbacks.ResetFences( m_pDevice->Handle, 1, &fence );
{
VkCommandBufferBeginInfo info = {};
info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
m_pDevice->Callbacks.BeginCommandBuffer( commandBuffer, &info );
}
{
VkRenderPassBeginInfo info = {};
info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
info.renderPass = m_RenderPass;
info.framebuffer = framebuffer;
info.renderArea.extent.width = m_RenderArea.width;
info.renderArea.extent.height = m_RenderArea.height;
m_pDevice->Callbacks.CmdBeginRenderPass( commandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE );
}
// Record Imgui Draw Data and draw funcs into command buffer
m_pImGuiVulkanContext->RenderDrawData( ImGui::GetDrawData(), commandBuffer );
// Submit command buffer
m_pDevice->Callbacks.CmdEndRenderPass( commandBuffer );
{
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
VkSubmitInfo info = {};
info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
info.waitSemaphoreCount = pPresentInfo->waitSemaphoreCount;
info.pWaitSemaphores = pPresentInfo->pWaitSemaphores;
info.pWaitDstStageMask = &wait_stage;
info.commandBufferCount = 1;
info.pCommandBuffers = &commandBuffer;
info.signalSemaphoreCount = 1;
info.pSignalSemaphores = &semaphore;
m_pDevice->Callbacks.EndCommandBuffer( commandBuffer );
m_pDevice->Callbacks.QueueSubmit( m_pGraphicsQueue->Handle, 1, &info, fence );
}
// Override wait semaphore
pPresentInfo->waitSemaphoreCount = 1;
pPresentInfo->pWaitSemaphores = &semaphore;
}
}
/***********************************************************************************\
Function:
Update
Description:
Update overlay.
\***********************************************************************************/
void ProfilerOverlayOutput::Update( const DeviceProfilerFrameData& data )
{
std::scoped_lock lk( s_ImGuiMutex );
ImGui::SetCurrentContext( m_pImGuiContext );
m_pImGuiVulkanContext->NewFrame();
m_pImGuiWindowContext->NewFrame();
ImGui::NewFrame();
ImGui::Begin( Lang::WindowName );
// Update input clipping rect
m_pImGuiWindowContext->UpdateWindowRect();
// GPU properties
ImGui::Text( "%s: %s", Lang::Device, m_pDevice->pPhysicalDevice->Properties.deviceName );
ImGuiX::TextAlignRight( "Vulkan %u.%u",
VK_VERSION_MAJOR( m_pDevice->pInstance->ApplicationInfo.apiVersion ),
VK_VERSION_MINOR( m_pDevice->pInstance->ApplicationInfo.apiVersion ) );
// Save results to file
if( ImGui::Button( Lang::Save ) )
{
DeviceProfilerTraceSerializer serializer( m_pStringSerializer, m_TimestampPeriod );
DeviceProfilerTraceSerializationResult result = serializer.Serialize( data );
m_SerializationSucceeded = result.m_Succeeded;
m_SerializationMessage = result.m_Message;
// Display message box
m_SerializationFinishTimestamp = std::chrono::high_resolution_clock::now();
m_SerializationOutputWindowSize = { 0, 0 };
}
// Keep results
ImGui::SameLine();
ImGui::Checkbox( Lang::Pause, &m_Pause );
if( !m_Pause )
{
// Update data
m_Data = data;
}
ImGui::BeginTabBar( "" );
if( ImGui::BeginTabItem( Lang::Performance ) )
{
UpdatePerformanceTab();
ImGui::EndTabItem();
}
if( ImGui::BeginTabItem( Lang::Memory ) )
{
UpdateMemoryTab();
ImGui::EndTabItem();
}
if( ImGui::BeginTabItem( Lang::Statistics ) )
{
UpdateStatisticsTab();
ImGui::EndTabItem();
}
if( ImGui::BeginTabItem( Lang::Settings ) )
{
UpdateSettingsTab();
ImGui::EndTabItem();
}
ImGui::EndTabBar();
// Draw other windows
DrawTraceSerializationOutputWindow();
ImGui::End();
ImGui::Render();
}
/***********************************************************************************\
Function:
InitializeImGuiWindowHooks
Description:
\***********************************************************************************/
VkResult ProfilerOverlayOutput::InitializeImGuiWindowHooks( const VkSwapchainCreateInfoKHR* pCreateInfo )
{
VkResult result = VK_SUCCESS;
// Get window handle from the swapchain surface
OSWindowHandle window = m_pDevice->pInstance->Surfaces.at( pCreateInfo->surface ).Window;
if( m_Window == window )
{
// No need to update window hooks
return result;
}
// Free current window
delete m_pImGuiWindowContext;
try
{
#ifdef VK_USE_PLATFORM_WIN32_KHR
if( window.Type == OSWindowHandleType::eWin32 )
{
m_pImGuiWindowContext = new ImGui_ImplWin32_Context( window.Win32Handle );
}
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WAYLAND_KHR
if( window.Type == OSWindowHandleType::eWayland )
{
m_pImGuiWindowContext = new ImGui_ImplWayland_Context( window.WaylandHandle );
}
#endif // VK_USE_PLATFORM_WAYLAND_KHR
#ifdef VK_USE_PLATFORM_XCB_KHR
if( window.Type == OSWindowHandleType::eXcb )
{
m_pImGuiWindowContext = new ImGui_ImplXcb_Context( window.XcbHandle );
}
#endif // VK_USE_PLATFORM_XCB_KHR
#ifdef VK_USE_PLATFORM_XLIB_KHR
if( window.Type == OSWindowHandleType::eXlib )
{
m_pImGuiWindowContext = new ImGui_ImplXlib_Context( window.XlibHandle );
}
#endif // VK_USE_PLATFORM_XLIB_KHR
}
catch( ... )
{
// Catch exceptions thrown by OS-specific ImGui window constructors
result = VK_ERROR_INITIALIZATION_FAILED;
}
// Deinitialize context if something failed
if( result != VK_SUCCESS )
{
delete m_pImGuiWindowContext;
m_pImGuiWindowContext = nullptr;
}
// Update objects
m_Window = window;
return result;
}
/***********************************************************************************\
Function:
InitializeImGuiDefaultFont
Description:
\***********************************************************************************/
void ProfilerOverlayOutput::InitializeImGuiDefaultFont()
{
ImGuiIO& io = ImGui::GetIO();
// Absolute path to the selected font
std::filesystem::path fontPath;
#ifdef WIN32
{
// Locate system fonts directory
std::filesystem::path fontsPath;
PWSTR pFontsDirectoryPath = nullptr;
if( SUCCEEDED( SHGetKnownFolderPath( FOLDERID_Fonts, KF_FLAG_DEFAULT, nullptr, &pFontsDirectoryPath ) ) )
{
fontsPath = pFontsDirectoryPath;
CoTaskMemFree( pFontsDirectoryPath );
}
// List of fonts to use (in this order)
const char* fonts[] = {
"segoeui.ttf",
"tahoma.ttf" };
for( const char* font : fonts )
{
fontPath = fontsPath / font;
if( std::filesystem::exists( fontPath ) )
break;
else fontPath = "";
}
}
#endif
#ifdef __linux__
{
// Linux distros use multiple font directories (or X server, TODO)
std::vector<std::filesystem::path> fontDirectories = {
"/usr/share/fonts",
"/usr/local/share/fonts",
"~/.fonts" };
// Some systems may have these directories specified in conf file
// https://stackoverflow.com/questions/3954223/platform-independent-way-to-get-font-directory
const char* fontConfigurationFiles[] = {
"/etc/fonts/fonts.conf",
"/etc/fonts/local.conf" };
std::vector<std::filesystem::path> configurationDirectories = {};
for( const char* fontConfigurationFile : fontConfigurationFiles )
{
if( std::filesystem::exists( fontConfigurationFile ) )
{
// Try to open configuration file for reading
std::ifstream conf( fontConfigurationFile );
if( conf.is_open() )
{
std::string line;
// conf is XML file, read line by line and find <dir> tag
while( std::getline( conf, line ) )
{
const size_t dirTagOpen = line.find( "<dir>" );
const size_t dirTagClose = line.find( "</dir>" );
// TODO: tags can be in different lines
if( (dirTagOpen != std::string::npos) && (dirTagClose != std::string::npos) )
{
configurationDirectories.push_back( line.substr( dirTagOpen + 5, dirTagClose - dirTagOpen - 5 ) );
}
}
}
}
}
if( !configurationDirectories.empty() )
{
// Override predefined font directories
fontDirectories = configurationDirectories;
}
// List of fonts to use (in this order)
const char* fonts[] = {
"Ubuntu-R.ttf",
"LiberationSans-Regural.ttf",
"DejaVuSans.ttf" };
for( const char* font : fonts )
{
for( const std::filesystem::path& fontDirectory : fontDirectories )
{
fontPath = ProfilerPlatformFunctions::FindFile( fontDirectory, font );
if( !fontPath.empty() )
break;
}
if( !fontPath.empty() )
break;
}
}
#endif
if( !fontPath.empty() )
{
// Include all glyphs in the font to support non-latin letters
const ImWchar range[] = { 0x20, 0xFFFF, 0 };
io.Fonts->AddFontFromFileTTF( fontPath.string().c_str(), 16.f, nullptr, range );
}
// Build atlas
unsigned char* tex_pixels = NULL;
int tex_w, tex_h;
io.Fonts->GetTexDataAsRGBA32( &tex_pixels, &tex_w, &tex_h );
}
/***********************************************************************************\
Function:
InitializeImGuiColors
Description:
\***********************************************************************************/
void ProfilerOverlayOutput::InitializeImGuiStyle()
{
ImGui::StyleColorsDark();
ImGuiStyle& style = ImGui::GetStyle();
// Round window corners
style.WindowRounding = 7.f;
// Performance graph colors
m_RenderPassColumnColor = ImGui::GetColorU32( { 0.9f, 0.7f, 0.0f, 1.0f } ); // #e6b200
m_GraphicsPipelineColumnColor = ImGui::GetColorU32( { 0.9f, 0.7f, 0.0f, 1.0f } ); // #e6b200
m_ComputePipelineColumnColor = ImGui::GetColorU32( { 0.9f, 0.55f, 0.0f, 1.0f } ); // #ffba42
m_InternalPipelineColumnColor = ImGui::GetColorU32( { 0.5f, 0.22f, 0.9f, 1.0f } ); // #9e30ff
}
/***********************************************************************************\
Function:
InitializeImGuiVulkanContext
Description:
\***********************************************************************************/
VkResult ProfilerOverlayOutput::InitializeImGuiVulkanContext( const VkSwapchainCreateInfoKHR* pCreateInfo )
{
VkResult result = VK_SUCCESS;
// Free current context
delete m_pImGuiVulkanContext;
try
{
ImGui_ImplVulkan_InitInfo imGuiInitInfo;
std::memset( &imGuiInitInfo, 0, sizeof( imGuiInitInfo ) );
imGuiInitInfo.Queue = m_pGraphicsQueue->Handle;
imGuiInitInfo.QueueFamily = m_pGraphicsQueue->Family;
imGuiInitInfo.Instance = m_pDevice->pInstance->Handle;
imGuiInitInfo.PhysicalDevice = m_pDevice->pPhysicalDevice->Handle;
imGuiInitInfo.Device = m_pDevice->Handle;
imGuiInitInfo.pInstanceDispatchTable = &m_pDevice->pInstance->Callbacks;
imGuiInitInfo.pDispatchTable = &m_pDevice->Callbacks;
imGuiInitInfo.Allocator = nullptr;
imGuiInitInfo.PipelineCache = VK_NULL_HANDLE;
imGuiInitInfo.CheckVkResultFn = nullptr;
imGuiInitInfo.MinImageCount = pCreateInfo->minImageCount;
imGuiInitInfo.ImageCount = m_Images.size();
imGuiInitInfo.MSAASamples = VK_SAMPLE_COUNT_1_BIT;
imGuiInitInfo.DescriptorPool = m_DescriptorPool;
m_pImGuiVulkanContext = new ImGui_ImplVulkan_Context( &imGuiInitInfo, m_RenderPass );
}
catch( ... )
{
// Catch all exceptions thrown by the context constructor and return VkResult
result = VK_ERROR_INITIALIZATION_FAILED;
}
// Initialize fonts
if( result == VK_SUCCESS )
{
result = m_pDevice->Callbacks.ResetFences( m_pDevice->Handle, 1, &m_CommandFences[ 0 ] );
}
if( result == VK_SUCCESS )
{
VkCommandBufferBeginInfo info = {};
info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
result = m_pDevice->Callbacks.BeginCommandBuffer( m_CommandBuffers[ 0 ], &info );
}
if( result == VK_SUCCESS )
{
m_pImGuiVulkanContext->CreateFontsTexture( m_CommandBuffers[ 0 ] );
}
if( result == VK_SUCCESS )
{
result = m_pDevice->Callbacks.EndCommandBuffer( m_CommandBuffers[ 0 ] );
}
// Submit initialization work
if( result == VK_SUCCESS )
{
VkSubmitInfo info = {};
info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
info.commandBufferCount = 1;
info.pCommandBuffers = &m_CommandBuffers[ 0 ];
result = m_pDevice->Callbacks.QueueSubmit( m_pGraphicsQueue->Handle, 1, &info, m_CommandFences[ 0 ] );
}
// Deinitialize context if something failed
if( result != VK_SUCCESS )
{
delete m_pImGuiVulkanContext;
m_pImGuiVulkanContext = nullptr;
}
return result;
}
/***********************************************************************************\
Function:
UpdatePerformanceTab
Description:
Updates "Performance" tab.
\***********************************************************************************/
void ProfilerOverlayOutput::UpdatePerformanceTab()
{
// Header
{
const Milliseconds gpuTimeMs = m_Data.m_Ticks * m_TimestampPeriod;
const Milliseconds cpuTimeMs = m_Data.m_CPU.m_EndTimestamp - m_Data.m_CPU.m_BeginTimestamp;
ImGui::Text( "%s: %.2f ms", Lang::GPUTime, gpuTimeMs.count() );
ImGui::Text( "%s: %.2f ms", Lang::CPUTime, cpuTimeMs.count() );
ImGuiX::TextAlignRight( "%.1f %s", m_Data.m_CPU.m_FramesPerSec, Lang::FPS );
}
// Histogram
{
static const char* groupOptions[] = {
Lang::RenderPasses,
Lang::Pipelines,
Lang::Drawcalls };
const char* selectedOption = groupOptions[ (size_t)m_HistogramGroupMode ];
// Select group mode
{
if( ImGui::BeginCombo( Lang::HistogramGroups, selectedOption, ImGuiComboFlags_NoPreview ) )
{
for( size_t i = 0; i < std::extent_v<decltype(groupOptions)>; ++i )
{
bool isSelected = (selectedOption == groupOptions[ i ]);
if( ImGui::Selectable( groupOptions[ i ], isSelected ) )
{
// Selection changed
selectedOption = groupOptions[ i ];
isSelected = true;
m_HistogramGroupMode = HistogramGroupMode( i );
}
if( isSelected )
{
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
}
// Enumerate columns for selected group mode
std::vector<PerformanceGraphColumn> columns;
GetPerformanceGraphColumns( columns );
char pHistogramDescription[ 32 ];
snprintf( pHistogramDescription, sizeof( pHistogramDescription ),
"%s (%s)",
Lang::GPUCycles,
selectedOption );
ImGui::PushItemWidth( -1 );
ImGuiX::PlotHistogramEx(
"",
columns.data(),
columns.size(),
0,
sizeof( columns.front() ),
pHistogramDescription, 0, FLT_MAX, { 0, 100 },
std::bind( &ProfilerOverlayOutput::DrawPerformanceGraphLabel, this, std::placeholders::_1 ),
std::bind( &ProfilerOverlayOutput::SelectPerformanceGraphColumn, this, std::placeholders::_1 ) );
}
// Top pipelines
if( ImGui::CollapsingHeader( Lang::TopPipelines ) )
{
uint32_t i = 0;
for( const auto& pipeline : m_Data.m_TopPipelines )
{
if( pipeline.m_Handle != VK_NULL_HANDLE )
{
const uint64_t pipelineTicks = (pipeline.m_EndTimestamp - pipeline.m_BeginTimestamp);
ImGui::Text( "%2u. %s", i + 1, m_pStringSerializer->GetName( pipeline ).c_str() );
ImGuiX::TextAlignRight( "(%.1f %%) %.2f ms",
pipelineTicks * 100.f / m_Data.m_Ticks,
pipelineTicks * m_TimestampPeriod.count() );
// Print up to 10 top pipelines
if( (++i) == 10 ) break;
}
}
}
// Vendor-specific
if( !m_Data.m_VendorMetrics.empty() &&
ImGui::CollapsingHeader( Lang::PerformanceCounters ) )
{
assert( m_Data.m_VendorMetrics.size() == m_VendorMetricProperties.size() );
ImGui::BeginTable( "Performance counters table",
/* columns_count */ 3,
ImGuiTableFlags_Resizable |
ImGuiTableFlags_NoClip |
ImGuiTableFlags_Borders );
// Headers
ImGui::TableSetupColumn( Lang::Metric, ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize );
ImGui::TableSetupColumn( Lang::Frame, ImGuiTableColumnFlags_WidthStretch );
ImGui::TableSetupColumn( "", ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize );
ImGui::TableHeadersRow();
for( uint32_t i = 0; i < m_Data.m_VendorMetrics.size(); ++i )
{
const VkProfilerPerformanceCounterResultEXT& metric = m_Data.m_VendorMetrics[ i ];
const VkProfilerPerformanceCounterPropertiesEXT& metricProperties = m_VendorMetricProperties[ i ];
ImGui::TableNextColumn();
{
ImGui::Text( "%s", metricProperties.shortName );
if( ImGui::IsItemHovered() &&
metricProperties.description[ 0 ] )
{
ImGui::BeginTooltip();
ImGui::PushTextWrapPos( 350.f );
ImGui::TextUnformatted( metricProperties.description );
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
ImGui::TableNextColumn();
{
const float columnWidth = ImGuiX::TableGetColumnWidth();
switch( metricProperties.storage )
{
case VK_PERFORMANCE_COUNTER_STORAGE_FLOAT32_KHR:
ImGuiX::TextAlignRight( columnWidth, "%.2f", metric.float32 );
break;
case VK_PERFORMANCE_COUNTER_STORAGE_UINT32_KHR:
ImGuiX::TextAlignRight( columnWidth, "%u", metric.uint32 );
break;
case VK_PERFORMANCE_COUNTER_STORAGE_UINT64_KHR:
ImGuiX::TextAlignRight( columnWidth, "%llu", metric.uint64 );
break;
}
}
ImGui::TableNextColumn();
{
const char* pUnitString = "???";
assert( metricProperties.unit < 11 );
static const char* const ppUnitString[ 11 ] =
{
"" /* VK_PERFORMANCE_COUNTER_UNIT_GENERIC_KHR */,
"%" /* VK_PERFORMANCE_COUNTER_UNIT_PERCENTAGE_KHR */,
"ns" /* VK_PERFORMANCE_COUNTER_UNIT_NANOSECONDS_KHR */,
"B" /* VK_PERFORMANCE_COUNTER_UNIT_BYTES_KHR */,
"B/s" /* VK_PERFORMANCE_COUNTER_UNIT_BYTES_PER_SECOND_KHR */,
"K" /* VK_PERFORMANCE_COUNTER_UNIT_KELVIN_KHR */,
"W" /* VK_PERFORMANCE_COUNTER_UNIT_WATTS_KHR */,
"V" /* VK_PERFORMANCE_COUNTER_UNIT_VOLTS_KHR */,
"A" /* VK_PERFORMANCE_COUNTER_UNIT_AMPS_KHR */,
"Hz" /* VK_PERFORMANCE_COUNTER_UNIT_HERTZ_KHR */,
"clk" /* VK_PERFORMANCE_COUNTER_UNIT_CYCLES_KHR */
};
if( metricProperties.unit < 11 )
{
pUnitString = ppUnitString[ metricProperties.unit ];
}
ImGui::TextUnformatted( pUnitString );
}
}
ImGui::EndTable();
}
// Force frame browser open
if( m_ScrollToSelectedFrameBrowserNode )
{
ImGui::SetNextItemOpen( true );
}
// Frame browser
if( ImGui::CollapsingHeader( Lang::FrameBrowser ) )
{
// Select sort mode
{
static const char* sortOptions[] = {
Lang::SubmissionOrder,
Lang::DurationDescending,
Lang::DurationAscending };
const char* selectedOption = sortOptions[ (size_t)m_FrameBrowserSortMode ];
ImGui::Text( Lang::Sort );
ImGui::SameLine();
if( ImGui::BeginCombo( "FrameBrowserSortMode", selectedOption ) )
{
for( size_t i = 0; i < std::extent_v<decltype(sortOptions)>; ++i )
{
bool isSelected = (selectedOption == sortOptions[ i ]);
if( ImGui::Selectable( sortOptions[ i ], isSelected ) )
{
// Selection changed
selectedOption = sortOptions[ i ];
isSelected = true;
m_FrameBrowserSortMode = FrameBrowserSortMode( i );
}
if( isSelected )
{
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
}
FrameBrowserTreeNodeIndex index = {
0x0,
0xFFFF,
0xFFFF,
0xFFFF,
0xFFFF,
0xFFFF,
0xFFFF,
0xFFFF };
// Enumerate submits in frame
for( const auto& submitBatch : m_Data.m_Submits )
{
const std::string queueName = m_pStringSerializer->GetName( submitBatch.m_Handle );
index.SubmitIndex = 0;
index.PrimaryCommandBufferIndex = 0;
char indexStr[ 2 * sizeof( index ) + 1 ] = {};
structtohex( indexStr, index );
if( m_ScrollToSelectedFrameBrowserNode &&
(m_SelectedFrameBrowserNodeIndex.SubmitBatchIndex == index.SubmitBatchIndex) )
{
ImGui::SetNextItemOpen( true );
}
if( ImGui::TreeNode( indexStr, "vkQueueSubmit(%s, %u)",
queueName.c_str(),
static_cast<uint32_t>(submitBatch.m_Submits.size()) ) )
{
for( const auto& submit : submitBatch.m_Submits )
{
structtohex( indexStr, index );
if( m_ScrollToSelectedFrameBrowserNode &&
(m_SelectedFrameBrowserNodeIndex.SubmitBatchIndex == index.SubmitBatchIndex) &&
(m_SelectedFrameBrowserNodeIndex.SubmitIndex == index.SubmitIndex) )
{
ImGui::SetNextItemOpen( true );
}
const bool inSubmitSubtree =
(submitBatch.m_Submits.size() > 1) &&
(ImGui::TreeNode( indexStr, "VkSubmitInfo #%u", index.SubmitIndex ));
if( (inSubmitSubtree) || (submitBatch.m_Submits.size() == 1) )
{
index.PrimaryCommandBufferIndex = 0;
// Sort frame browser data
std::list<const DeviceProfilerCommandBufferData*> pCommandBuffers =
SortFrameBrowserData( submit.m_CommandBuffers );
// Enumerate command buffers in submit
for( const auto* pCommandBuffer : pCommandBuffers )
{
PrintCommandBuffer( *pCommandBuffer, index );
index.PrimaryCommandBufferIndex++;
}
// Invalidate command buffer index
index.PrimaryCommandBufferIndex = 0xFFFF;
}
if( inSubmitSubtree )
{
// Finish submit subtree
ImGui::TreePop();
}
index.SubmitIndex++;
}
// Finish submit batch subtree
ImGui::TreePop();
// Invalidate submit index
index.SubmitIndex = 0xFFFF;
}
index.SubmitBatchIndex++;
}
}
m_ScrollToSelectedFrameBrowserNode = false;
}
/***********************************************************************************\
Function:
UpdateMemoryTab
Description:
Updates "Memory" tab.
\***********************************************************************************/
void ProfilerOverlayOutput::UpdateMemoryTab()
{
const VkPhysicalDeviceMemoryProperties& memoryProperties =
m_pDevice->pPhysicalDevice->MemoryProperties;
if( ImGui::CollapsingHeader( Lang::MemoryHeapUsage ) )
{
for( uint32_t i = 0; i < memoryProperties.memoryHeapCount; ++i )
{
ImGui::Text( "%s %u", Lang::MemoryHeap, i );
ImGuiX::TextAlignRight( "%u %s", m_Data.m_Memory.m_Heaps[ i ].m_AllocationCount, Lang::Allocations );
float usage = 0.f;
char usageStr[ 64 ] = {};
if( memoryProperties.memoryHeaps[ i ].size != 0 )
{
usage = (float)m_Data.m_Memory.m_Heaps[ i ].m_AllocationSize / memoryProperties.memoryHeaps[ i ].size;
snprintf( usageStr, sizeof( usageStr ),
"%.2f/%.2f MB (%.1f%%)",
m_Data.m_Memory.m_Heaps[ i ].m_AllocationSize / 1048576.f,
memoryProperties.memoryHeaps[ i ].size / 1048576.f,
usage * 100.f );
}
ImGui::ProgressBar( usage, { -1, 0 }, usageStr );
if( ImGui::IsItemHovered() && (memoryProperties.memoryHeaps[ i ].flags != 0) )
{
ImGui::BeginTooltip();
if( memoryProperties.memoryHeaps[ i ].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT )
{
ImGui::TextUnformatted( "VK_MEMORY_HEAP_DEVICE_LOCAL_BIT" );
}
if( memoryProperties.memoryHeaps[ i ].flags & VK_MEMORY_HEAP_MULTI_INSTANCE_BIT )
{
ImGui::TextUnformatted( "VK_MEMORY_HEAP_MULTI_INSTANCE_BIT" );
}
ImGui::EndTooltip();
}
std::vector<float> memoryTypeUsages( memoryProperties.memoryTypeCount );
std::vector<std::string> memoryTypeDescriptors( memoryProperties.memoryTypeCount );
for( uint32_t typeIndex = 0; typeIndex < memoryProperties.memoryTypeCount; ++typeIndex )
{
if( memoryProperties.memoryTypes[ typeIndex ].heapIndex == i )
{
memoryTypeUsages[ typeIndex ] = m_Data.m_Memory.m_Types[ typeIndex ].m_AllocationSize;
// Prepare descriptor for memory type
std::stringstream sstr;
sstr << Lang::MemoryTypeIndex << " " << typeIndex << "\n"
<< m_Data.m_Memory.m_Types[ typeIndex ].m_AllocationCount << " " << Lang::Allocations << "\n";
if( memoryProperties.memoryTypes[ typeIndex ].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT )
{
sstr << "VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT\n";
}
if( memoryProperties.memoryTypes[ typeIndex ].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD )
{
sstr << "VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD\n";
}
if( memoryProperties.memoryTypes[ typeIndex ].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD )
{
sstr << "VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD\n";
}
if( memoryProperties.memoryTypes[ typeIndex ].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT )
{
sstr << "VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT\n";
}
if( memoryProperties.memoryTypes[ typeIndex ].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT )
{
sstr << "VK_MEMORY_PROPERTY_HOST_COHERENT_BIT\n";
}
if( memoryProperties.memoryTypes[ typeIndex ].propertyFlags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT )
{
sstr << "VK_MEMORY_PROPERTY_HOST_CACHED_BIT\n";
}
if( memoryProperties.memoryTypes[ typeIndex ].propertyFlags & VK_MEMORY_PROPERTY_PROTECTED_BIT )
{
sstr << "VK_MEMORY_PROPERTY_PROTECTED_BIT\n";
}
if( memoryProperties.memoryTypes[ typeIndex ].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT )
{
sstr << "VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT\n";
}
memoryTypeDescriptors[ typeIndex ] = sstr.str();
}
}
// Get descriptor pointers
std::vector<const char*> memoryTypeDescriptorPointers( memoryProperties.memoryTypeCount );
for( uint32_t typeIndex = 0; typeIndex < memoryProperties.memoryTypeCount; ++typeIndex )
{
memoryTypeDescriptorPointers[ typeIndex ] = memoryTypeDescriptors[ typeIndex ].c_str();
}
ImGuiX::PlotBreakdownEx(
"HEAP_BREAKDOWN",
memoryTypeUsages.data(),
memoryProperties.memoryTypeCount, 0,
memoryTypeDescriptorPointers.data() );
}
}
}
/***********************************************************************************\
Function:
UpdateStatisticsTab
Description:
Updates "Statistics" tab.
\***********************************************************************************/
void ProfilerOverlayOutput::UpdateStatisticsTab()
{
// Draw count statistics
{
ImGui::TextUnformatted( Lang::DrawCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_DrawCount );
ImGui::TextUnformatted( Lang::DrawCallsIndirect );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_DrawIndirectCount );
ImGui::TextUnformatted( Lang::DispatchCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_DispatchCount );
ImGui::TextUnformatted( Lang::DispatchCallsIndirect );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_DispatchIndirectCount );
ImGui::TextUnformatted( Lang::CopyBufferCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_CopyBufferCount );
ImGui::TextUnformatted( Lang::CopyBufferToImageCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_CopyBufferToImageCount );
ImGui::TextUnformatted( Lang::CopyImageCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_CopyImageCount );
ImGui::TextUnformatted( Lang::CopyImageToBufferCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_CopyImageToBufferCount );
ImGui::TextUnformatted( Lang::PipelineBarriers );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_PipelineBarrierCount );
ImGui::TextUnformatted( Lang::ColorClearCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_ClearColorCount );
ImGui::TextUnformatted( Lang::DepthStencilClearCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_ClearDepthStencilCount );
ImGui::TextUnformatted( Lang::ResolveCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_ResolveCount );
ImGui::TextUnformatted( Lang::BlitCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_BlitImageCount );
ImGui::TextUnformatted( Lang::FillBufferCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_FillBufferCount );
ImGui::TextUnformatted( Lang::UpdateBufferCalls );
ImGuiX::TextAlignRight( "%u", m_Data.m_Stats.m_UpdateBufferCount );
}
}
/***********************************************************************************\
Function:
UpdateSettingsTab
Description:
Updates "Settings" tab.
\***********************************************************************************/
void ProfilerOverlayOutput::UpdateSettingsTab()
{
// Select synchronization mode
{
static const char* groupOptions[] = {
Lang::Present,
Lang::Submit };
// TMP
static int selectedOption = 0;
int previousSelectedOption = selectedOption;
ImGui::Combo( Lang::SyncMode, &selectedOption, groupOptions, 2 );
if( selectedOption != previousSelectedOption )
{
vkSetProfilerSyncModeEXT( m_pDevice->Handle, (VkProfilerSyncModeEXT)selectedOption );
}
ImGui::Checkbox( Lang::ShowDebugLabels, &m_ShowDebugLabels );
}
}
/***********************************************************************************\
Function:
GetPerformanceGraphColumns
Description:
Enumerate performance graph columns.
\***********************************************************************************/
void ProfilerOverlayOutput::GetPerformanceGraphColumns( std::vector<PerformanceGraphColumn>& columns ) const
{
FrameBrowserTreeNodeIndex index = {
0x0,
0xFFFF,
0xFFFF,
0xFFFF,
0xFFFF,
0xFFFF,
0xFFFF,
0xFFFF };
// Enumerate submits batches in frame
for( const auto& submitBatch : m_Data.m_Submits )
{
index.SubmitIndex = 0;
// Enumerate submits in submit batch
for( const auto& submit : submitBatch.m_Submits )
{
index.PrimaryCommandBufferIndex = 0;
// Enumerate command buffers in submit
for( const auto& commandBuffer : submit.m_CommandBuffers )
{
GetPerformanceGraphColumns( commandBuffer, index, columns );
index.PrimaryCommandBufferIndex++;
}
index.PrimaryCommandBufferIndex = 0xFFFF;
index.SubmitIndex++;
}
index.SubmitIndex = 0xFFFF;
index.SubmitBatchIndex++;
}
}
/***********************************************************************************\
Function:
GetPerformanceGraphColumns
Description:
Enumerate performance graph columns.
\***********************************************************************************/
void ProfilerOverlayOutput::GetPerformanceGraphColumns(
const DeviceProfilerCommandBufferData& data,
FrameBrowserTreeNodeIndex index,
std::vector<PerformanceGraphColumn>& columns ) const
{
// RenderPassIndex may be already set if we're processing secondary command buffer with RENDER_PASS_CONTINUE_BIT set.
const bool renderPassContinue = (index.RenderPassIndex != 0xFFFF);
if( !renderPassContinue )
{
index.RenderPassIndex = 0;
}
// Enumerate render passes in command buffer
for( const auto& renderPass : data.m_RenderPasses )
{
GetPerformanceGraphColumns( renderPass, index, columns );
index.RenderPassIndex++;
}
}
/***********************************************************************************\
Function:
GetPerformanceGraphColumns
Description:
Enumerate performance graph columns.
\***********************************************************************************/
void ProfilerOverlayOutput::GetPerformanceGraphColumns(
const DeviceProfilerRenderPassData& data,
FrameBrowserTreeNodeIndex index,
std::vector<PerformanceGraphColumn>& columns ) const
{
// RenderPassIndex may be already set if we're processing secondary command buffer with RENDER_PASS_CONTINUE_BIT set.
const bool renderPassContinue = (index.SubpassIndex != 0xFFFF);
if( (m_HistogramGroupMode <= HistogramGroupMode::eRenderPass) &&
(data.m_Handle != VK_NULL_HANDLE) )
{
const float cycleCount = data.m_EndTimestamp - data.m_BeginTimestamp;
PerformanceGraphColumn column = {};
column.x = cycleCount;
column.y = cycleCount;
column.color = m_RenderPassColumnColor;
column.userData = &data;
column.groupMode = HistogramGroupMode::eRenderPass;
column.nodeIndex = index;
// Insert render pass cycle count to histogram
columns.push_back( column );
}
else
{
if( !renderPassContinue )
{
index.SubpassIndex = 0;
}
// Enumerate subpasses in render pass
for( const auto& subpass : data.m_Subpasses )
{
if( subpass.m_Contents == VK_SUBPASS_CONTENTS_INLINE )
{
index.PipelineIndex = 0;
// Enumerate pipelines in subpass
for( const auto& pipeline : subpass.m_Pipelines )
{
GetPerformanceGraphColumns( pipeline, index, columns );
index.PipelineIndex++;
}
index.PipelineIndex = 0xFFFF;
}
else if( subpass.m_Contents == VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS )
{
index.SecondaryCommandBufferIndex = 0;
// Enumerate secondary command buffers
for( const auto& commandBuffer : subpass.m_SecondaryCommandBuffers )
{
GetPerformanceGraphColumns( commandBuffer, index, columns );
index.SecondaryCommandBufferIndex++;
}
index.SecondaryCommandBufferIndex = 0xFFFF;
}
index.SubpassIndex++;
}
}
}
/***********************************************************************************\
Function:
GetPerformanceGraphColumns
Description:
Enumerate performance graph columns.
\***********************************************************************************/
void ProfilerOverlayOutput::GetPerformanceGraphColumns(
const DeviceProfilerPipelineData& data,
FrameBrowserTreeNodeIndex index,
std::vector<PerformanceGraphColumn>& columns ) const
{
if( (m_HistogramGroupMode <= HistogramGroupMode::ePipeline) &&
((data.m_ShaderTuple.m_Hash & 0xFFFF) != 0) &&
(data.m_Handle != VK_NULL_HANDLE) )
{
const float cycleCount = data.m_EndTimestamp - data.m_BeginTimestamp;
PerformanceGraphColumn column = {};
column.x = cycleCount;
column.y = cycleCount;
column.userData = &data;
column.groupMode = HistogramGroupMode::ePipeline;
column.nodeIndex = index;
switch( data.m_BindPoint )
{
case VK_PIPELINE_BIND_POINT_GRAPHICS:
column.color = m_GraphicsPipelineColumnColor;
break;
case VK_PIPELINE_BIND_POINT_COMPUTE:
column.color = m_ComputePipelineColumnColor;
break;
default:
assert( !"Unsupported pipeline type" );
break;
}
// Insert pipeline cycle count to histogram
columns.push_back( column );
}
else
{
index.DrawcallIndex = 0;
// Enumerate drawcalls in pipeline
for( const auto& drawcall : data.m_Drawcalls )
{
GetPerformanceGraphColumns( drawcall, index, columns );
index.DrawcallIndex++;
}
}
}
/***********************************************************************************\
Function:
GetPerformanceGraphColumns
Description:
Enumerate performance graph columns.
\***********************************************************************************/
void ProfilerOverlayOutput::GetPerformanceGraphColumns(
const DeviceProfilerDrawcall& data,
FrameBrowserTreeNodeIndex index,
std::vector<PerformanceGraphColumn>& columns ) const
{
const float cycleCount = data.m_EndTimestamp - data.m_BeginTimestamp;
PerformanceGraphColumn column = {};
column.x = cycleCount;
column.y = cycleCount;
column.userData = &data;
column.groupMode = HistogramGroupMode::eDrawcall;
column.nodeIndex = index;
switch( data.GetPipelineType() )
{
case DeviceProfilerPipelineType::eGraphics:
column.color = m_GraphicsPipelineColumnColor;
break;
case DeviceProfilerPipelineType::eCompute:
column.color = m_ComputePipelineColumnColor;
break;
default:
column.color = m_InternalPipelineColumnColor;
break;
}
// Insert drawcall cycle count to histogram
columns.push_back( column );
}
/***********************************************************************************\
Function:
DrawPerformanceGraphLabel
Description:
Draw label for hovered column.
\***********************************************************************************/
void ProfilerOverlayOutput::DrawPerformanceGraphLabel( const ImGuiX::HistogramColumnData& data_ )
{
const PerformanceGraphColumn& data = reinterpret_cast<const PerformanceGraphColumn&>(data_);
std::string regionName = "";
uint64_t regionCycleCount = 0;
switch( data.groupMode )
{
case HistogramGroupMode::eRenderPass:
{
const DeviceProfilerRenderPassData& renderPassData =
*reinterpret_cast<const DeviceProfilerRenderPassData*>(data.userData);
regionName = m_pStringSerializer->GetName( renderPassData );
regionCycleCount = renderPassData.m_EndTimestamp - renderPassData.m_BeginTimestamp;
break;
}
case HistogramGroupMode::ePipeline:
{
const DeviceProfilerPipelineData& pipelineData =
*reinterpret_cast<const DeviceProfilerPipelineData*>(data.userData);
regionName = m_pStringSerializer->GetName( pipelineData );
regionCycleCount = pipelineData.m_EndTimestamp - pipelineData.m_BeginTimestamp;
break;
}
case HistogramGroupMode::eDrawcall:
{
const DeviceProfilerDrawcall& pipelineData =
*reinterpret_cast<const DeviceProfilerDrawcall*>(data.userData);
regionName = m_pStringSerializer->GetName( pipelineData );
regionCycleCount = pipelineData.m_EndTimestamp - pipelineData.m_BeginTimestamp;
break;
}
}
ImGui::SetTooltip( "%s\n%.2f ms",
regionName.c_str(),
regionCycleCount * m_TimestampPeriod.count() );
}
/***********************************************************************************\
Function:
SelectPerformanceGraphColumn
Description:
Scroll frame browser to node selected in performance graph.
\***********************************************************************************/
void ProfilerOverlayOutput::SelectPerformanceGraphColumn( const ImGuiX::HistogramColumnData& data_ )
{
const PerformanceGraphColumn& data = reinterpret_cast<const PerformanceGraphColumn&>(data_);
m_SelectedFrameBrowserNodeIndex = data.nodeIndex;
m_ScrollToSelectedFrameBrowserNode = true;
m_SelectionUpdateTimestamp = std::chrono::high_resolution_clock::now();
}
/***********************************************************************************\
Function:
DrawTraceSerializationOutputWindow
Description:
Display window with serialization output.
\***********************************************************************************/
void ProfilerOverlayOutput::DrawTraceSerializationOutputWindow()
{
using namespace std::chrono;
using namespace std::chrono_literals;
const auto& now = std::chrono::high_resolution_clock::now();
if( (now - m_SerializationFinishTimestamp) < 4s )
{
const ImVec2 windowPos = {
static_cast<float>(m_RenderArea.width - m_SerializationOutputWindowSize.width),
static_cast<float>(m_RenderArea.height - m_SerializationOutputWindowSize.height) };
const float fadeOutStep =
1.f - std::max( 0.f, std::min( 1.f,
duration_cast<milliseconds>(now - (m_SerializationFinishTimestamp + 3s)).count() / 1000.f ) );
ImGui::PushStyleVar( ImGuiStyleVar_Alpha, fadeOutStep );
if( !m_SerializationSucceeded )
{
ImGui::PushStyleColor( ImGuiCol_WindowBg, { 1, 0, 0, 1 } );
}
ImGui::SetNextWindowPos( windowPos );
ImGui::Begin( "Trace Export", nullptr,
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_AlwaysAutoResize );
ImGui::Text( "%s", m_SerializationMessage.c_str() );
// Save final size of the window
if( m_SerializationOutputWindowSize.width == 0 )
{
const ImVec2 windowSize = ImGui::GetWindowSize();
m_SerializationOutputWindowSize.width = static_cast<uint32_t>(windowSize.x);
m_SerializationOutputWindowSize.height = static_cast<uint32_t>(windowSize.y);
}
ImGui::End();
ImGui::PopStyleVar();
if( !m_SerializationSucceeded )
{
ImGui::PopStyleColor();
}
}
}
/***********************************************************************************\
Function:
PrintCommandBuffer
Description:
Writes command buffer data to the overlay.
\***********************************************************************************/
void ProfilerOverlayOutput::PrintCommandBuffer( const DeviceProfilerCommandBufferData& cmdBuffer, FrameBrowserTreeNodeIndex index )
{
const uint64_t commandBufferTicks = (cmdBuffer.m_EndTimestamp - cmdBuffer.m_BeginTimestamp);
// Mark hotspots with color
DrawSignificanceRect( (float)commandBufferTicks / m_Data.m_Ticks, index );
char indexStr[ 2 * sizeof( index ) + 1 ] = {};
structtohex( indexStr, index );
if( (m_ScrollToSelectedFrameBrowserNode) &&
(m_SelectedFrameBrowserNodeIndex.SubmitBatchIndex == index.SubmitBatchIndex) &&
(m_SelectedFrameBrowserNodeIndex.SubmitIndex == index.SubmitIndex) &&
(((cmdBuffer.m_Level == VK_COMMAND_BUFFER_LEVEL_PRIMARY) &&
(m_SelectedFrameBrowserNodeIndex.PrimaryCommandBufferIndex == index.PrimaryCommandBufferIndex)) ||
((cmdBuffer.m_Level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) &&
(m_SelectedFrameBrowserNodeIndex.PrimaryCommandBufferIndex == index.PrimaryCommandBufferIndex) &&
(m_SelectedFrameBrowserNodeIndex.RenderPassIndex == index.RenderPassIndex) &&
(m_SelectedFrameBrowserNodeIndex.SubpassIndex == index.SubpassIndex) &&
(m_SelectedFrameBrowserNodeIndex.SecondaryCommandBufferIndex == index.SecondaryCommandBufferIndex))) )
{
// Tree contains selected node
ImGui::SetNextItemOpen( true );
ImGui::SetScrollHereY();
}
if( ImGui::TreeNode( indexStr, "%s", m_pStringSerializer->GetName( cmdBuffer.m_Handle ).c_str() ) )
{
// Command buffer opened
ImGuiX::TextAlignRight( "%.2f ms", commandBufferTicks * m_TimestampPeriod.count() );
// Sort frame browser data
std::list<const DeviceProfilerRenderPassData*> pRenderPasses =
SortFrameBrowserData( cmdBuffer.m_RenderPasses );
// RenderPassIndex may be already set if we're processing secondary command buffer with RENDER_PASS_CONTINUE_BIT set.
const bool renderPassContinue = (index.RenderPassIndex != 0xFFFF);
if( !renderPassContinue )
{
index.RenderPassIndex = 0;
}
// Enumerate render passes in command buffer
for( const DeviceProfilerRenderPassData* pRenderPass : pRenderPasses )
{
PrintRenderPass( *pRenderPass, index );
index.RenderPassIndex++;
}
ImGui::TreePop();
}
else
{
// Command buffer collapsed
ImGuiX::TextAlignRight( "%.2f ms", commandBufferTicks * m_TimestampPeriod.count() );
}
}
/***********************************************************************************\
Function:
PrintRenderPass
Description:
Writes render pass data to the overlay.
\***********************************************************************************/
void ProfilerOverlayOutput::PrintRenderPass( const DeviceProfilerRenderPassData& renderPass, FrameBrowserTreeNodeIndex index )
{
const uint64_t renderPassTicks = (renderPass.m_EndTimestamp - renderPass.m_BeginTimestamp);
// Mark hotspots with color
DrawSignificanceRect( (float)renderPassTicks / m_Data.m_Ticks, index );
char indexStr[ 2 * sizeof( index ) + 1 ] = {};
structtohex( indexStr, index );
// At least one subpass must be present
assert( !renderPass.m_Subpasses.empty() );
if( (m_ScrollToSelectedFrameBrowserNode) &&
(m_SelectedFrameBrowserNodeIndex.SubmitBatchIndex == index.SubmitBatchIndex) &&
(m_SelectedFrameBrowserNodeIndex.SubmitIndex == index.SubmitIndex) &&
(m_SelectedFrameBrowserNodeIndex.PrimaryCommandBufferIndex == index.PrimaryCommandBufferIndex) &&
(m_SelectedFrameBrowserNodeIndex.RenderPassIndex == index.RenderPassIndex) &&
((index.SecondaryCommandBufferIndex == 0xFFFF) ||
(m_SelectedFrameBrowserNodeIndex.SecondaryCommandBufferIndex == index.SecondaryCommandBufferIndex)) )
{
// Tree contains selected node
ImGui::SetNextItemOpen( true );
ImGui::SetScrollHereY();
}
const bool inRenderPassSubtree =
(renderPass.m_Handle != VK_NULL_HANDLE) &&
(ImGui::TreeNode( indexStr, "%s",
m_pStringSerializer->GetName( renderPass.m_Handle ).c_str() ));
if( inRenderPassSubtree )
{
const uint64_t renderPassBeginTicks = (renderPass.m_Begin.m_EndTimestamp - renderPass.m_Begin.m_BeginTimestamp);
// Render pass subtree opened
ImGuiX::TextAlignRight( "%.2f ms", renderPassTicks * m_TimestampPeriod.count() );
index.DrawcallIndex = 0;
if( (m_ScrollToSelectedFrameBrowserNode) &&
(m_SelectedFrameBrowserNodeIndex == index) )
{
ImGui::SetScrollHereY();
}
// Mark hotspots with color
DrawSignificanceRect( (float)renderPassBeginTicks / m_Data.m_Ticks, index );
index.DrawcallIndex = 0xFFFF;
// Print BeginRenderPass pipeline
ImGui::TextUnformatted( "vkCmdBeginRenderPass" );
ImGuiX::TextAlignRight( "%.2f ms", renderPassBeginTicks * m_TimestampPeriod.count() );
}
if( inRenderPassSubtree ||
(renderPass.m_Handle == VK_NULL_HANDLE) )
{
// Sort frame browser data
std::list<const DeviceProfilerSubpassData*> pSubpasses =
SortFrameBrowserData( renderPass.m_Subpasses );
// SubpassIndex may be already set if we're processing secondary command buffer with RENDER_PASS_CONTINUE_BIT set.
const bool renderPassContinue = (index.SubpassIndex != 0xFFFF);
if( !renderPassContinue )
{
index.SubpassIndex = 0;
}
// Enumerate subpasses
for( const DeviceProfilerSubpassData* pSubpass : pSubpasses )
{
PrintSubpass( *pSubpass, index, (pSubpasses.size() == 1) );
index.SubpassIndex++;
}
if( !renderPassContinue )
{
index.SubpassIndex = 0xFFFF;
}
}
if( inRenderPassSubtree )
{
const uint64_t renderPassEndTicks = (renderPass.m_End.m_EndTimestamp - renderPass.m_End.m_BeginTimestamp);
index.DrawcallIndex = 1;
if( (m_ScrollToSelectedFrameBrowserNode) &&
(m_SelectedFrameBrowserNodeIndex == index) )
{
ImGui::SetScrollHereY();
}
// Mark hotspots with color
DrawSignificanceRect( (float)renderPassEndTicks / m_Data.m_Ticks, index );
index.DrawcallIndex = 0xFFFF;
// Print EndRenderPass pipeline
ImGui::TextUnformatted( "vkCmdEndRenderPass" );
ImGuiX::TextAlignRight( "%.2f ms", renderPassEndTicks * m_TimestampPeriod.count() );
ImGui::TreePop();
}
if( !inRenderPassSubtree &&
(renderPass.m_Handle != VK_NULL_HANDLE) )
{
// Render pass collapsed
ImGuiX::TextAlignRight( "%.2f ms", renderPassTicks * m_TimestampPeriod.count() );
}
}
/***********************************************************************************\
Function:
PrintSubpass
Description:
Writes subpass data to the overlay.
\***********************************************************************************/
void ProfilerOverlayOutput::PrintSubpass( const DeviceProfilerSubpassData& subpass, FrameBrowserTreeNodeIndex index, bool isOnlySubpass )
{
const uint64_t subpassTicks = (subpass.m_EndTimestamp - subpass.m_BeginTimestamp);
bool inSubpassSubtree = false;
if( !isOnlySubpass )
{
// Mark hotspots with color
DrawSignificanceRect( (float)subpassTicks / m_Data.m_Ticks, index );
char indexStr[ 2 * sizeof( index ) + 1 ] = {};
structtohex( indexStr, index );
if( (m_ScrollToSelectedFrameBrowserNode) &&
(m_SelectedFrameBrowserNodeIndex.SubmitBatchIndex == index.SubmitBatchIndex) &&
(m_SelectedFrameBrowserNodeIndex.SubmitIndex == index.SubmitIndex) &&
(m_SelectedFrameBrowserNodeIndex.PrimaryCommandBufferIndex == index.PrimaryCommandBufferIndex) &&
(m_SelectedFrameBrowserNodeIndex.SecondaryCommandBufferIndex == index.SecondaryCommandBufferIndex) &&
(m_SelectedFrameBrowserNodeIndex.RenderPassIndex == index.RenderPassIndex) &&
(m_SelectedFrameBrowserNodeIndex.SubpassIndex == index.SubpassIndex) )
{
// Tree contains selected node
ImGui::SetNextItemOpen( true );
ImGui::SetScrollHereY();
}
inSubpassSubtree =
(subpass.m_Index != -1) &&
(ImGui::TreeNode( indexStr, "Subpass #%u", subpass.m_Index ));
}
if( inSubpassSubtree )
{
// Subpass subtree opened
ImGuiX::TextAlignRight( "%.2f ms", subpassTicks * m_TimestampPeriod.count() );
}
if( inSubpassSubtree ||
isOnlySubpass ||
(subpass.m_Index == -1) )
{
if( subpass.m_Contents == VK_SUBPASS_CONTENTS_INLINE )
{
// Sort frame browser data
std::list<const DeviceProfilerPipelineData*> pPipelines =
SortFrameBrowserData( subpass.m_Pipelines );
index.PipelineIndex = 0;
// Enumerate pipelines in subpass
for( const DeviceProfilerPipelineData* pPipeline : pPipelines )
{
PrintPipeline( *pPipeline, index );
index.PipelineIndex++;
}
}
else if( subpass.m_Contents == VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS )
{
// Sort command buffers
std::list<const DeviceProfilerCommandBufferData*> pCommandBuffers =
SortFrameBrowserData( subpass.m_SecondaryCommandBuffers );
index.SecondaryCommandBufferIndex = 0;
// Enumerate command buffers in subpass
for( const DeviceProfilerCommandBufferData* pCommandBuffer : pCommandBuffers )
{
PrintCommandBuffer( *pCommandBuffer, index );
index.SecondaryCommandBufferIndex++;
}
}
}
if( inSubpassSubtree )
{
// Finish subpass tree
ImGui::TreePop();
}
if( !inSubpassSubtree && !isOnlySubpass && (subpass.m_Index != -1) )
{
// Subpass collapsed
ImGuiX::TextAlignRight( "%.2f ms", subpassTicks * m_TimestampPeriod.count() );
}
}
/***********************************************************************************\
Function:
PrintPipeline
Description:
Writes pipeline data to the overlay.
\***********************************************************************************/
void ProfilerOverlayOutput::PrintPipeline( const DeviceProfilerPipelineData& pipeline, FrameBrowserTreeNodeIndex index )
{
const uint64_t pipelineTicks = (pipeline.m_EndTimestamp - pipeline.m_BeginTimestamp);
const bool printPipelineInline =
(pipeline.m_Handle == VK_NULL_HANDLE) ||
((pipeline.m_ShaderTuple.m_Hash & 0xFFFF) == 0);
bool inPipelineSubtree = false;
if( !printPipelineInline )
{
// Mark hotspots with color
DrawSignificanceRect( (float)pipelineTicks / m_Data.m_Ticks, index );
char indexStr[ 2 * sizeof( index ) + 1 ] = {};
structtohex( indexStr, index );
if( (m_ScrollToSelectedFrameBrowserNode) &&
(m_SelectedFrameBrowserNodeIndex.SubmitBatchIndex == index.SubmitBatchIndex) &&
(m_SelectedFrameBrowserNodeIndex.SubmitIndex == index.SubmitIndex) &&
(m_SelectedFrameBrowserNodeIndex.PrimaryCommandBufferIndex == index.PrimaryCommandBufferIndex) &&
(m_SelectedFrameBrowserNodeIndex.SecondaryCommandBufferIndex == index.SecondaryCommandBufferIndex) &&
(m_SelectedFrameBrowserNodeIndex.RenderPassIndex == index.RenderPassIndex) &&
(m_SelectedFrameBrowserNodeIndex.SubpassIndex == index.SubpassIndex) &&
(m_SelectedFrameBrowserNodeIndex.PipelineIndex == index.PipelineIndex) )
{
// Tree contains selected node
ImGui::SetNextItemOpen( true );
ImGui::SetScrollHereY();
}
inPipelineSubtree =
(ImGui::TreeNode( indexStr, "%s", m_pStringSerializer->GetName( pipeline ).c_str() ));
}
if( inPipelineSubtree )
{
// Pipeline subtree opened
ImGuiX::TextAlignRight( "%.2f ms", pipelineTicks * m_TimestampPeriod.count() );
}
if( inPipelineSubtree || printPipelineInline )
{
// Sort frame browser data
std::list<const DeviceProfilerDrawcall*> pDrawcalls =
SortFrameBrowserData( pipeline.m_Drawcalls );
index.DrawcallIndex = 0;
// Enumerate drawcalls in pipeline
for( const DeviceProfilerDrawcall* pDrawcall : pDrawcalls )
{
PrintDrawcall( *pDrawcall, index );
index.DrawcallIndex++;
}
}
if( inPipelineSubtree )
{
// Finish pipeline subtree
ImGui::TreePop();
}
if( !inPipelineSubtree && !printPipelineInline )
{
// Pipeline collapsed
ImGuiX::TextAlignRight( "%.2f ms", pipelineTicks * m_TimestampPeriod.count() );
}
}
/***********************************************************************************\
Function:
PrintDrawcall
Description:
Writes drawcall data to the overlay.
\***********************************************************************************/
void ProfilerOverlayOutput::PrintDrawcall( const DeviceProfilerDrawcall& drawcall, FrameBrowserTreeNodeIndex index )
{
if( drawcall.GetPipelineType() != DeviceProfilerPipelineType::eDebug )
{
const uint64_t drawcallTicks = (drawcall.m_EndTimestamp - drawcall.m_BeginTimestamp);
if( (m_ScrollToSelectedFrameBrowserNode) &&
(m_SelectedFrameBrowserNodeIndex == index) )
{
ImGui::SetScrollHereY();
}
// Mark hotspots with color
DrawSignificanceRect( (float)drawcallTicks / m_Data.m_Ticks, index );
const std::string drawcallString = m_pStringSerializer->GetName( drawcall );
ImGui::TextUnformatted( drawcallString.c_str() );
// Print drawcall duration
ImGuiX::TextAlignRight( "%.2f ms", drawcallTicks * m_TimestampPeriod.count() );
}
else
{
// Draw debug label
PrintDebugLabel( drawcall.m_Payload.m_DebugLabel.m_pName, drawcall.m_Payload.m_DebugLabel.m_Color );
}
}
/***********************************************************************************\
Function:
DrawSignificanceRect
Description:
\***********************************************************************************/
void ProfilerOverlayOutput::DrawSignificanceRect( float significance, const FrameBrowserTreeNodeIndex& index )
{
ImVec2 cursorPosition = ImGui::GetCursorScreenPos();
ImVec2 rectSize;
cursorPosition.x = ImGui::GetWindowPos().x;
rectSize.x = cursorPosition.x + ImGui::GetWindowSize().x;
rectSize.y = cursorPosition.y + ImGui::GetTextLineHeight();
ImU32 color = ImGui::GetColorU32( { 1, 0, 0, significance } );
if( index == m_SelectedFrameBrowserNodeIndex )
{
using namespace std::chrono;
using namespace std::chrono_literals;
// Node is selected
ImU32 selectionColor = ImGui::GetColorU32( ImGuiCol_TabHovered );
// Interpolate color
auto now = std::chrono::high_resolution_clock::now();
float step = std::max( 0.0f, std::min( 1.0f,
duration_cast<Milliseconds>((now - m_SelectionUpdateTimestamp) - 0.3s).count() / 1000.0f ) );
// Linear interpolation
color = ImGuiX::ColorLerp( selectionColor, color, step );
}
ImDrawList* pDrawList = ImGui::GetWindowDrawList();
pDrawList->AddRectFilled( cursorPosition, rectSize, color );
}
/***********************************************************************************\
Function:
DrawDebugLabel
Description:
\***********************************************************************************/
void ProfilerOverlayOutput::PrintDebugLabel( const char* pName, const float pColor[ 4 ] )
{
if( !(m_ShowDebugLabels) ||
(m_FrameBrowserSortMode != FrameBrowserSortMode::eSubmissionOrder) ||
!(pName) )
{
// Don't print debug labels if frame browser is sorted out of submission order
return;
}
ImVec2 cursorPosition = ImGui::GetCursorScreenPos();
ImVec2 rectSize;
rectSize.x = cursorPosition.x + 8;
rectSize.y = cursorPosition.y + ImGui::GetTextLineHeight();
// Resolve debug label color
ImU32 color = ImGui::GetColorU32( *reinterpret_cast<const ImVec4*>(pColor) );
ImDrawList* pDrawList = ImGui::GetWindowDrawList();
pDrawList->AddRectFilled( cursorPosition, rectSize, color );
pDrawList->AddRect( cursorPosition, rectSize, ImGui::GetColorU32( ImGuiCol_Border ) );
cursorPosition.x += 12;
ImGui::SetCursorScreenPos( cursorPosition );
ImGui::TextUnformatted( pName );
}
}
| 36.72391 | 141 | 0.535559 | [
"render",
"object",
"vector"
] |
17d6fd92333f500f878ff6d0d18c81bfe06fa7c6 | 5,880 | cpp | C++ | RaiderEngine/GameObject.cpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | 4 | 2019-07-20T08:41:04.000Z | 2022-03-04T01:53:38.000Z | RaiderEngine/GameObject.cpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | null | null | null | RaiderEngine/GameObject.cpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "GameObject.hpp"
#include "mesh.hpp"
#include "model.hpp"
#include "settings.hpp"
#include "physics.hpp"
#include "constants.hpp"
GameObject::GameObject(glm::vec3 position, glm::vec3 rotationEA, glm::vec3 scale, std::string modelName, int makeStatic, bool grabbable, bool usePhysics, bool castShadows, bool drawTwoSided) :
position(position), scaleVal(scale), grabbable(grabbable), modelName(modelName), usePhysics(usePhysics), castShadows(castShadows), drawTwoSided(drawTwoSided) {
setModel(modelName, makeStatic == 1);
isStatic = makeStatic > 0;
if (isStatic)
this->grabbable = false;
addPhysics(setRotation(rotationEA));
}
void GameObject::initStaticVertexBuffer() {
glGenBuffers(1, &instancedModelVBO);
}
std::string GameObject::getDisplayString() {
return "";
}
void GameObject::setModel(std::string modelName, bool makeStatic) {
// note: this function should only be called once at initialization, as the object's physics depend on its set model
if (!models.contains(modelName))
models.insert({ modelName, std::make_unique<Model>(modelDir + modelName + '/' + modelName + ".gltf", makeStatic) });
model = models[modelName].get();
}
void GameObject::addPhysics(glm::quat rot) {
if (!usePhysics) return;
// calculate mass and prepare physics data structures
float averageScale = (scaleVal.x + scaleVal.y + scaleVal.z) / 3;
mass = model->isStaticMesh ? 0.0f : model->volume * averageScale * 1000;
PxQuat physRot(rot.x, rot.y, rot.z, rot.w);
PxVec3 physPot(position.x, position.y, position.z);
PxMeshScale physScale(PxVec3(scaleVal.x, scaleVal.y, scaleVal.z), PxQuat(PxIdentity));
// our body type depends on our staticness, which may or may not match our model's staticness
if (isStatic)
body = gPhysics->createRigidStatic(PxTransform(physPot, physRot));
else {
body = gPhysics->createRigidDynamic(PxTransform(physPot, physRot));
// TODO: physx does not appear to handle objects with a small mass well; handle this properly rather than providing objects with a minimum of 10kg
static_cast<PxRigidDynamic*>(body)->setMass(10 + mass);
}
// TODO: should the shape live in the model class rather than the GameObject class?
// our shape, unlike our body type, depends on our model's staticness
if (model->colliderType == "triangleMesh")
PxRigidActorExt::createExclusiveShape(*body, PxTriangleMeshGeometry((PxTriangleMesh*)model->collisionMesh, physScale), *gMaterial);
else
PxRigidActorExt::createExclusiveShape(*body, PxConvexMeshGeometry((PxConvexMesh*)model->collisionMesh, physScale), *gMaterial);
// assign default raycast filter
PxShape* shape;
body->getShapes(&shape, 1);
if (model->surfType == "solid") {
shape->setQueryFilterData(defaultFilterData);
}
else {
shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false);
shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, true);
shape->setQueryFilterData(triggerFilterData);
}
// store a pointer to this GameObject in the body's data field, then finally add the body to the physics scene
body->userData = this;
gScene->addActor(*body);
}
void GameObject::recalculateModelTransform() {
modelTransform = glm::scale(glm::translate(glm::mat4(1.0f), position) * rotation, scaleVal);
isDirty = false;
}
void GameObject::rotate(const float& angle, glm::vec3 const& axes) {
rotation = glm::rotate(rotation, angle, axes);
isDirty = true;
}
glm::quat GameObject::setRotation(glm::vec3 const& rotationEA) {
glm::quat q = glm::quat(rotationEA);
rotation = glm::toMat4(q);
isDirty = true;
return q;
}
glm::quat GameObject::setRotation(glm::quat const& rot) {
rotation = glm::toMat4(rot);
isDirty = true;
return rot;
}
glm::vec4 GameObject::forwardVec() {
return glm::normalize(rotation * glm::vec4(Direction::forward, 0));
}
glm::vec4 GameObject::backVec() {
return glm::normalize(rotation * glm::vec4(Direction::back, 0));
}
//TODO: for correct movement, right and left directions must be reversed; this must be investigated. perhaps the problem lies with assimp axes?
glm::vec4 GameObject::rightVec() {
return glm::normalize(rotation * glm::vec4(Direction::right, 0));
}
glm::vec4 GameObject::leftVec() {
return glm::normalize(rotation * glm::vec4(Direction::left, 0));
}
glm::vec4 GameObject::upVec() {
return glm::normalize(rotation * glm::vec4(Direction::up, 0));
}
glm::vec4 GameObject::downVec() {
return glm::normalize(rotation * glm::vec4(Direction::down, 0));
}
glm::vec2 GameObject::pitchYawFromMat(glm::mat4 const& inMat) {
glm::mat4 invRot = glm::inverse(inMat);
const glm::vec3 direction = -glm::vec3(invRot[2]);
float yaw = glm::degrees(glm::atan(-direction.x, -direction.z));
float pitch = glm::degrees(glm::asin(-direction.y));
return glm::vec2(pitch, yaw);
}
glm::vec2 GameObject::pitchYawFromEA(glm::vec3 const& inEA) {
return pitchYawFromMat(glm::toMat4(glm::quat(inEA)));
}
void GameObject::translate(glm::vec3 const& amnt) {
position += amnt;
isDirty = true;
}
void GameObject::translate(glm::vec4 const& dir, float const& amnt) {
position = (glm::vec4(position, 0) + dir * amnt).xyz();
isDirty = true;
}
void GameObject::setPos(glm::vec3 const& newPos) {
position = newPos;
isDirty = true;
}
void GameObject::scale(glm::vec3 const& amnt) {
scaleVal += amnt;
isDirty = true;
}
void GameObject::setScale(glm::vec3 const& newScale) {
scaleVal = newScale;
isDirty = true;
}
void GameObject::update() {
// update position and rotation to match the physics body
if (usePhysics) {
PxTransform pose = body->getGlobalPose();
if (std::memcmp(&pose.p, &position, sizeof(glm::vec3)) != 0) {
std::memcpy(&position, &pose.p, sizeof(glm::vec3));
isDirty = true;
}
if (std::memcmp(&pose.q, &prevRot, sizeof(glm::vec4)) != 0) {
std::memcpy(&prevRot, &pose.q, sizeof(glm::vec4));
rotation = glm::toMat4(glm::quat(pose.q.w, pose.q.x, pose.q.y, pose.q.z));
isDirty = true;
}
}
} | 34.792899 | 192 | 0.721259 | [
"mesh",
"object",
"shape",
"model",
"solid"
] |
17d88174ec7cea188ab10c0cbd4abeadae8e067f | 12,604 | cpp | C++ | src/modules/block/task.cpp | ronanjs/openperf | 55b759e399254547f8a6590b2e19cb47232265b7 | [
"Apache-2.0"
] | null | null | null | src/modules/block/task.cpp | ronanjs/openperf | 55b759e399254547f8a6590b2e19cb47232265b7 | [
"Apache-2.0"
] | null | null | null | src/modules/block/task.cpp | ronanjs/openperf | 55b759e399254547f8a6590b2e19cb47232265b7 | [
"Apache-2.0"
] | null | null | null | #include <thread>
#include <limits>
#include "task.hpp"
#include "framework/core/op_log.h"
#include "framework/utils/random.hpp"
namespace openperf::block::worker {
using namespace std::chrono_literals;
constexpr duration TASK_SPIN_THRESHOLD = 100ms;
struct operation_config
{
int fd;
size_t f_size;
size_t block_size;
uint8_t* buffer;
off_t offset;
size_t header_size;
int (*queue_aio_op)(aiocb* aiocb);
};
task_stat_t& task_stat_t::operator+=(const task_stat_t& stat)
{
assert(operation == stat.operation);
updated = std::max(updated, stat.updated);
ops_target += stat.ops_target;
ops_actual += stat.ops_actual;
bytes_target += stat.bytes_target;
bytes_actual += stat.bytes_actual;
latency += stat.latency;
latency_min = [&]() -> optional_time_t {
if (latency_min.has_value() && stat.latency_min.has_value())
return std::min(latency_min.value(), stat.latency_min.value());
return latency_min.has_value() ? latency_min : stat.latency_min;
}();
latency_max = [&]() -> optional_time_t {
if (latency_max.has_value() && stat.latency_max.has_value())
return std::max(latency_max.value(), stat.latency_max.value());
return latency_max.has_value() ? latency_max : stat.latency_max;
}();
return *this;
}
static int submit_aio_op(const operation_config& op_config,
operation_state& op_state)
{
op_state.aiocb = aiocb{
.aio_fildes = op_config.fd,
.aio_offset = static_cast<off_t>(op_config.block_size * op_config.offset
+ op_config.header_size),
.aio_buf = op_config.buffer,
.aio_nbytes = op_config.block_size,
.aio_reqprio = 0,
.aio_sigevent.sigev_notify = SIGEV_NONE,
};
/* Reset stat related variables */
op_state.state = PENDING;
op_state.start = ref_clock::now();
op_state.stop = op_state.start;
op_state.io_bytes = 0;
/* Submit operation to the kernel */
if (op_config.queue_aio_op(&op_state.aiocb) == -1) {
if (errno == EAGAIN) {
OP_LOG(OP_LOG_WARNING, "AIO queue is full!\n");
op_state.state = IDLE;
} else {
OP_LOG(OP_LOG_ERROR,
"Could not queue AIO operation: %s\n",
strerror(errno));
}
return -errno;
}
return 0;
}
static int wait_for_aio_ops(std::vector<operation_state>& aio_ops,
size_t nb_ops)
{
const aiocb* aiocblist[nb_ops];
size_t nb_cbs = 0;
/*
* Loop through all of our aio cb's and build a list with all pending
* operations.
*/
for (size_t i = 0; i < nb_ops; ++i) {
if (aio_ops.at(i).state == PENDING) {
aiocblist[nb_cbs++] = &aio_ops.at(i).aiocb;
}
}
int error = 0;
if (nb_cbs) {
/*
* Wait for one of our outstanding requests to finish. The one
* second timeout is a failsafe to prevent hanging here indefinitely.
* It should (hopefully?) be high enough to prevent interrupting valid
* block requests...
*/
struct timespec timeout = {.tv_sec = 1, .tv_nsec = 0};
if (aio_suspend(aiocblist, nb_cbs, &timeout) == -1) {
error = -errno;
OP_LOG(OP_LOG_ERROR, "aio_suspend failed: %s\n", strerror(errno));
}
}
return error;
}
static int complete_aio_op(struct operation_state& aio_op)
{
int err = 0;
auto aiocb = &aio_op.aiocb;
if (aio_op.state != PENDING) return (-1);
switch (err = aio_error(aiocb)) {
case 0: {
/* AIO operation completed */
ssize_t nb_bytes = aio_return(aiocb);
aio_op.stop = ref_clock::now();
aio_op.io_bytes = nb_bytes;
aio_op.state = COMPLETE;
break;
}
case EINPROGRESS:
/* Still waiting */
break;
case ECANCELED:
default:
/* could be canceled or error; we don't make a distinction */
aio_return(aiocb); /* free resources */
aio_op.stop = ref_clock::now();
aio_op.io_bytes = 0;
aio_op.state = FAILED;
err = 0;
}
return err;
}
// Constructors & Destructor
block_task::block_task(const task_config_t& configuration)
{
config(configuration);
}
// Methods : public
void block_task::reset()
{
m_stat = {.operation = m_task_config.operation};
m_operation_timestamp = {};
if (m_task_config.synchronizer) {
switch (m_task_config.operation) {
case task_operation::READ:
m_task_config.synchronizer->reads_actual.store(
0, std::memory_order_relaxed);
break;
case task_operation::WRITE:
m_task_config.synchronizer->writes_actual.store(
0, std::memory_order_relaxed);
break;
}
}
}
task_stat_t block_task::spin()
{
if (!m_task_config.ops_per_sec || !m_task_config.block_size) {
throw std::runtime_error(
"Could not spin worker: no block operations were specified");
}
if (m_operation_timestamp.time_since_epoch() == 0ns) {
m_operation_timestamp = ref_clock::now();
}
// Reduce the effect of ZMQ operations on total Block I/O operations amount
auto sleep_time = m_operation_timestamp - ref_clock::now();
if (sleep_time > 0ns) std::this_thread::sleep_for(sleep_time);
// Prepare for ratio synchronization
auto ops_per_sec = calculate_rate();
// Worker loop
auto stat = task_stat_t{.operation = m_task_config.operation};
auto loop_start_ts = ref_clock::now();
auto cur_time = ref_clock::now();
do {
// +1 need here to start spin at beginning of each time frame
auto ops_req = (cur_time - m_operation_timestamp).count() * ops_per_sec
/ std::nano::den
+ 1;
assert(ops_req);
auto worker_spin_stat = worker_spin(ops_req, cur_time + 1s);
stat += worker_spin_stat;
cur_time = ref_clock::now();
m_operation_timestamp +=
std::chrono::nanoseconds(std::nano::den / ops_per_sec)
* worker_spin_stat.ops_actual;
} while ((m_operation_timestamp < cur_time)
&& (cur_time <= loop_start_ts + TASK_SPIN_THRESHOLD));
stat.updated = realtime::now();
m_stat += stat;
return stat;
}
// Methods : private
task_stat_t block_task::worker_spin(uint64_t nb_ops,
realtime::time_point deadline)
{
auto op_conf = operation_config{
.fd = m_task_config.fd,
.f_size = m_task_config.f_size,
.block_size = m_task_config.block_size,
.buffer = m_buf.data(),
.offset = 0,
.header_size =
((m_task_config.header_size - 1) / m_task_config.block_size + 1)
* m_task_config.block_size,
.queue_aio_op = (m_task_config.operation == task_operation::READ)
? aio_read
: aio_write,
};
auto stat = task_stat_t{.operation = m_task_config.operation};
size_t pending_ops = 0;
auto queue_depth =
std::min(m_task_config.queue_depth, static_cast<size_t>(nb_ops));
for (size_t i = 0; i < queue_depth; ++i) {
auto& aio_op = m_aio_ops[i];
op_conf.offset = m_pattern.generate();
if (submit_aio_op(op_conf, aio_op) == 0) {
pending_ops++;
} else if (aio_op.state == FAILED) {
stat.ops_actual++;
stat.errors++;
} else {
/* temporary queueing error */
break;
}
op_conf.buffer += m_task_config.block_size;
}
while (pending_ops) {
if (wait_for_aio_ops(m_aio_ops, queue_depth) != 0) {
/*
* Eek! Waiting failed, so cancel pending operations.
* The aio_cancel function only has two documented failure modes:
* 1) bad file descriptor
* 2) aio_cancel not supported
* We consider either of these conditions to be fatal.
*/
if (aio_cancel(m_task_config.fd, nullptr) == -1) {
OP_LOG(OP_LOG_ERROR,
"Could not cancel pending AIO operatons: %s\n",
strerror(errno));
}
}
/*
* Find the completed op and fire off another one to
* take it's place.
*/
for (size_t i = 0; i < queue_depth; ++i) {
auto& aio_op = m_aio_ops[i];
if (complete_aio_op(aio_op) == 0) {
/* found it; update stats */
switch (aio_op.state) {
case COMPLETE: {
stat.ops_actual++;
stat.bytes_actual += aio_op.io_bytes;
auto op_ns = aio_op.stop - aio_op.start;
stat.latency += op_ns;
stat.latency_min =
(stat.latency_min.has_value())
? std::min(stat.latency_min.value(), op_ns)
: op_ns;
stat.latency_max =
(stat.latency_max.has_value())
? std::max(stat.latency_max.value(), op_ns)
: op_ns;
break;
}
case FAILED:
stat.ops_actual++;
stat.errors++;
break;
default:
OP_LOG(OP_LOG_WARNING,
"Completed AIO operation in %d state?\n",
aio_op.state);
break;
}
/* if we haven't hit our total or deadline, then fire off
* another op */
// if ((total_ops + pending_ops) >= queue_depth
if ((stat.ops_actual + pending_ops) >= queue_depth
|| ref_clock::now() >= deadline
|| submit_aio_op(op_conf, aio_op) != 0) {
// if any condition is true, we have one less pending op
pending_ops--;
if (aio_op.state == FAILED) {
stat.ops_actual++;
stat.errors++;
}
}
}
}
}
return stat;
}
void block_task::config(const task_config_t& p_config)
{
m_task_config = p_config;
m_stat.operation = m_task_config.operation;
auto buf_len = m_task_config.queue_depth * m_task_config.block_size;
m_buf.resize(buf_len);
utils::op_prbs23_fill(m_buf.data(), m_buf.size());
m_aio_ops.resize(m_task_config.queue_depth);
m_pattern.reset(
0,
static_cast<off_t>((m_task_config.f_size - m_task_config.header_size)
/ m_task_config.block_size),
m_task_config.pattern);
}
int32_t block_task::calculate_rate()
{
if (!m_task_config.synchronizer) return m_task_config.ops_per_sec;
if (m_task_config.operation == task_operation::READ)
m_task_config.synchronizer->reads_actual.store(
m_stat.ops_actual, std::memory_order_relaxed);
else
m_task_config.synchronizer->writes_actual.store(
m_stat.ops_actual, std::memory_order_relaxed);
int64_t reads_actual = m_task_config.synchronizer->reads_actual.load(
std::memory_order_relaxed);
int64_t writes_actual = m_task_config.synchronizer->writes_actual.load(
std::memory_order_relaxed);
int32_t ratio_reads =
m_task_config.synchronizer->ratio_reads.load(std::memory_order_relaxed);
int32_t ratio_writes = m_task_config.synchronizer->ratio_writes.load(
std::memory_order_relaxed);
switch (m_task_config.operation) {
case task_operation::READ: {
auto reads_expected = writes_actual * ratio_reads / ratio_writes;
return std::min(
std::max(reads_expected + m_task_config.ops_per_sec - reads_actual,
1L),
static_cast<long>(m_task_config.ops_per_sec));
}
case task_operation::WRITE: {
auto writes_expected = reads_actual * ratio_writes / ratio_reads;
return std::min(std::max(writes_expected + m_task_config.ops_per_sec
- writes_actual,
1L),
static_cast<long>(m_task_config.ops_per_sec));
}
}
}
} // namespace openperf::block::worker | 32.153061 | 80 | 0.572041 | [
"vector"
] |
17dad732a255e14c750dc6ff11408d6238890f8a | 2,350 | cpp | C++ | android-31/android/telephony/TelephonyManager_CallComposerException.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/telephony/TelephonyManager_CallComposerException.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-31/android/telephony/TelephonyManager_CallComposerException.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../java/io/IOException.hpp"
#include "./TelephonyManager_CallComposerException.hpp"
namespace android::telephony
{
// Fields
jint TelephonyManager_CallComposerException::ERROR_AUTHENTICATION_FAILED()
{
return getStaticField<jint>(
"android.telephony.TelephonyManager$CallComposerException",
"ERROR_AUTHENTICATION_FAILED"
);
}
jint TelephonyManager_CallComposerException::ERROR_FILE_TOO_LARGE()
{
return getStaticField<jint>(
"android.telephony.TelephonyManager$CallComposerException",
"ERROR_FILE_TOO_LARGE"
);
}
jint TelephonyManager_CallComposerException::ERROR_INPUT_CLOSED()
{
return getStaticField<jint>(
"android.telephony.TelephonyManager$CallComposerException",
"ERROR_INPUT_CLOSED"
);
}
jint TelephonyManager_CallComposerException::ERROR_IO_EXCEPTION()
{
return getStaticField<jint>(
"android.telephony.TelephonyManager$CallComposerException",
"ERROR_IO_EXCEPTION"
);
}
jint TelephonyManager_CallComposerException::ERROR_NETWORK_UNAVAILABLE()
{
return getStaticField<jint>(
"android.telephony.TelephonyManager$CallComposerException",
"ERROR_NETWORK_UNAVAILABLE"
);
}
jint TelephonyManager_CallComposerException::ERROR_REMOTE_END_CLOSED()
{
return getStaticField<jint>(
"android.telephony.TelephonyManager$CallComposerException",
"ERROR_REMOTE_END_CLOSED"
);
}
jint TelephonyManager_CallComposerException::ERROR_UNKNOWN()
{
return getStaticField<jint>(
"android.telephony.TelephonyManager$CallComposerException",
"ERROR_UNKNOWN"
);
}
// QJniObject forward
TelephonyManager_CallComposerException::TelephonyManager_CallComposerException(QJniObject obj) : java::lang::Exception(obj) {}
// Constructors
TelephonyManager_CallComposerException::TelephonyManager_CallComposerException(jint arg0, java::io::IOException arg1)
: java::lang::Exception(
"android.telephony.TelephonyManager$CallComposerException",
"(ILjava/io/IOException;)V",
arg0,
arg1.object()
) {}
// Methods
jint TelephonyManager_CallComposerException::getErrorCode() const
{
return callMethod<jint>(
"getErrorCode",
"()I"
);
}
java::io::IOException TelephonyManager_CallComposerException::getIOException() const
{
return callObjectMethod(
"getIOException",
"()Ljava/io/IOException;"
);
}
} // namespace android::telephony
| 27.325581 | 127 | 0.777021 | [
"object"
] |
17e3242e2b33c6fe8a9e195f4c8a4d2c82192bc6 | 951 | cpp | C++ | STL/generate_n.cpp | Sinchiguano/Algorithmic-Toolbox | 7e9dda588a72356fc43fa276016fc3486be47556 | [
"BSD-2-Clause"
] | null | null | null | STL/generate_n.cpp | Sinchiguano/Algorithmic-Toolbox | 7e9dda588a72356fc43fa276016fc3486be47556 | [
"BSD-2-Clause"
] | null | null | null | STL/generate_n.cpp | Sinchiguano/Algorithmic-Toolbox | 7e9dda588a72356fc43fa276016fc3486be47556 | [
"BSD-2-Clause"
] | null | null | null | /*
* generate_n.cpp
* Copyright (C) 2018 CESAR SINCHIGUANO <cesarsinchiguano@hotmail.es>
*
* Distributed under terms of the BSD license.
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <time.h>
#include <cstdlib>
using namespace std;
//g++ -std=c++14 -o temp sort.cpp
int generate_random()
{
return rand()%50;
}
int main()
{
srand(time(NULL));
std::vector<int> v1 , v2;
v1.resize(10);
v2.resize(10);
/* this assign each element a random value generated
by the generate_random() */
generate(v1.begin(), v1.end(), generate_random) ;
for (size_t i = 0; i < v1.size(); i++)
{
std::cout << "-----> " <<v1[i]<< '\n';
}
std::cout << "/* message */" << '\n';
/* this assign first 5 elements a random value
and rest of the elements are unchanged */
generate_n(v2.begin(), 5, generate_random);
for (size_t i = 0; i < v2.size(); i++)
{
std::cout << "-----> " <<v2[i]<< '\n';
}
}
| 18.288462 | 69 | 0.598318 | [
"vector"
] |
17e770e9d5c16969bd1e7ee7383bc65014da40d9 | 2,381 | cpp | C++ | time_perf_tests/parallel_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 28 | 2021-11-23T11:52:55.000Z | 2022-03-04T01:48:52.000Z | time_perf_tests/parallel_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | null | null | null | time_perf_tests/parallel_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 3 | 2022-01-02T12:23:04.000Z | 2022-01-07T04:21:26.000Z | // Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include "../vox.geometry/parallel.h"
#include <benchmark/benchmark.h>
#include <random>
class Parallel : public ::benchmark::Fixture {
public:
std::vector<double> a, b, c;
size_t n = 0;
unsigned int numThreads = 1;
std::mt19937 rng{0};
std::uniform_real_distribution<> d{0.0, 1.0};
void SetUp(const ::benchmark::State &state) override {
n = static_cast<size_t>(state.range(0));
numThreads = static_cast<unsigned int>(state.range(1));
a.resize(n);
b.resize(n);
c.resize(n);
}
};
BENCHMARK_DEFINE_F(Parallel, ParallelFor)(benchmark::State &state) {
unsigned int oldNumThreads = vox::geometry::maxNumberOfThreads();
vox::geometry::setMaxNumberOfThreads(numThreads);
while (state.KeepRunning()) {
vox::geometry::parallelFor(vox::geometry::kZeroSize, n, [this](size_t i) { c[i] = 1.0 / std::sqrt(a[i] / b[i] + 1.0); });
}
vox::geometry::setMaxNumberOfThreads(oldNumThreads);
}
BENCHMARK_REGISTER_F(Parallel, ParallelFor)
->UseRealTime()
->Args({1 << 8, 1})
->Args({1 << 8, 2})
->Args({1 << 8, 4})
->Args({1 << 8, 8})
->Args({1 << 16, 1})
->Args({1 << 16, 2})
->Args({1 << 16, 4})
->Args({1 << 16, 8})
->Args({1 << 24, 1})
->Args({1 << 24, 2})
->Args({1 << 24, 4})
->Args({1 << 24, 8});
BENCHMARK_DEFINE_F(Parallel, ParallelRangeFor)(benchmark::State &state) {
unsigned int oldNumThreads = vox::geometry::maxNumberOfThreads();
vox::geometry::setMaxNumberOfThreads(numThreads);
while (state.KeepRunning()) {
vox::geometry::parallelRangeFor(vox::geometry::kZeroSize, n, [this](size_t iBegin, size_t iEnd) {
for (size_t i = iBegin; i < iEnd; ++i) {
c[i] = 1.0 / std::sqrt(a[i] / b[i] + 1.0);
}
});
}
vox::geometry::setMaxNumberOfThreads(oldNumThreads);
}
BENCHMARK_REGISTER_F(Parallel, ParallelRangeFor)
->UseRealTime()
->Args({1 << 8, 1})
->Args({1 << 8, 2})
->Args({1 << 8, 4})
->Args({1 << 8, 8})
->Args({1 << 16, 1})
->Args({1 << 16, 2})
->Args({1 << 16, 4})
->Args({1 << 16, 8})
->Args({1 << 24, 1})
->Args({1 << 24, 2})
->Args({1 << 24, 4})
->Args({1 << 24, 8});
| 27.367816 | 125 | 0.594288 | [
"geometry",
"vector"
] |
17ea5551b173b3f3ab8ed2bb539075ef47313812 | 19,467 | cxx | C++ | main/extensions/test/sax/testwriter.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/extensions/test/sax/testwriter.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/extensions/test/sax/testwriter.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
//#include <tools/presys.h>
#include <vector>
//#include <tools/postsys.h>
#include <smart/com/sun/star/test/XSimpleTest.hxx>
#include <smart/com/sun/star/lang/XMultiServiceFactory.hxx> // for the multiservice-factories
#include <stdio.h>
#include <smart/com/sun/star/io/XActiveDataSource.hxx>
#include <smart/com/sun/star/io/XOutputStream.hxx>
#include <smart/com/sun/star/xml/sax/SAXParseException.hxx>
#include <smart/com/sun/star/xml/sax/XParser.hxx>
#include <smart/com/sun/star/xml/sax/XExtendedDocumentHandler.hxx>
#include <rtl/wstring.hxx>
#include <osl/time.h>
#include <usr/weak.hxx>
#include <tools/string.hxx>
#include <usr/factoryhlp.hxx>
#include <usr/reflserv.hxx> // for EXTERN_SERVICE_CALLTYPE
using namespace std;
using namespace rtl;
using namespace vos;
using namespace usr;
#define BUILD_ERROR(expr, Message)\
{\
m_seqErrors.realloc( m_seqErrors.getLen() + 1 ); \
m_seqExceptions.realloc( m_seqExceptions.getLen() + 1 ); \
String str; \
str += __FILE__;\
str += " "; \
str += "(" ; \
str += __LINE__ ;\
str += ")\n";\
str += "[ " ; \
str += #expr; \
str += " ] : " ; \
str += Message; \
m_seqErrors.getArray()[ m_seqErrors.getLen()-1] = StringToUString( str , CHARSET_SYSTEM ); \
}\
((void)0)
#define WARNING_ASSERT(expr, Message) \
if( ! (expr) ) { \
m_seqWarnings.realloc( m_seqErrors.getLen() +1 ); \
String str;\
str += __FILE__;\
str += " "; \
str += "(" ; \
str += __LINE__ ;\
str += ")\n";\
str += "[ " ; \
str += #expr; \
str += " ] : " ; \
str += Message; \
m_seqWarnings.getArray()[ m_seqWarnings.getLen()-1] = StringToUString( str , CHARSET_SYSTEM ); \
return; \
}\
((void)0)
#define ERROR_ASSERT(expr, Message) \
if( ! (expr) ) { \
BUILD_ERROR(expr, Message );\
return; \
}\
((void)0)
#define ERROR_EXCEPTION_ASSERT(expr, Message, Exception) \
if( !(expr)) { \
BUILD_ERROR(expr,Message);\
m_seqExceptions.getArray()[ m_seqExceptions.getLen()-1] = UsrAny( Exception );\
return; \
} \
((void)0)
/****
* test szenarios :
*
*
*
****/
class OFileWriter :
public XOutputStream,
public OWeakObject
{
public:
OFileWriter( char *pcFile ) { strcpy( m_pcFile , pcFile ); m_f = 0; }
public: // refcounting
BOOL queryInterface( Uik aUik, XInterfaceRef & rOut )
{
if( XOutputStream::getSmartUik() == aUik ) {
rOut = (XOutputStream *) this;
}
else return OWeakObject::queryInterface( aUik , rOut );
return TRUE;
}
void acquire() { OWeakObject::acquire(); }
void release() { OWeakObject::release(); }
void* getImplementation(Reflection *p) { return OWeakObject::getImplementation(p); }
public:
virtual void writeBytes(const Sequence< BYTE >& aData)
THROWS( (NotConnectedException, BufferSizeExceededException, UsrSystemException) );
virtual void flush(void)
THROWS( (NotConnectedException, BufferSizeExceededException, UsrSystemException) );
virtual void closeOutput(void)
THROWS( (NotConnectedException, BufferSizeExceededException, UsrSystemException) );
private:
char m_pcFile[256];
FILE *m_f;
};
void OFileWriter::writeBytes(const Sequence< BYTE >& aData)
THROWS( (NotConnectedException, BufferSizeExceededException, UsrSystemException) )
{
if( ! m_f ) {
m_f = fopen( m_pcFile , "w" );
}
fwrite( aData.getConstArray() , 1 , aData.getLen() , m_f );
}
void OFileWriter::flush(void)
THROWS( (NotConnectedException, BufferSizeExceededException, UsrSystemException) )
{
fflush( m_f );
}
void OFileWriter::closeOutput(void)
THROWS( (NotConnectedException, BufferSizeExceededException, UsrSystemException) )
{
fclose( m_f );
m_f = 0;
}
class OSaxWriterTest :
public XSimpleTest,
public OWeakObject
{
public:
OSaxWriterTest( const XMultiServiceFactoryRef & rFactory ) : m_rFactory( rFactory )
{
}
~OSaxWriterTest() {}
public: // refcounting
BOOL queryInterface( Uik aUik, XInterfaceRef & rOut );
void acquire() { OWeakObject::acquire(); }
void release() { OWeakObject::release(); }
void* getImplementation(Reflection *p) { return OWeakObject::getImplementation(p); }
public:
virtual void testInvariant(const UString& TestName, const XInterfaceRef& TestObject)
THROWS( ( IllegalArgumentException,
UsrSystemException) );
virtual INT32 test( const UString& TestName,
const XInterfaceRef& TestObject,
INT32 hTestHandle) THROWS( ( IllegalArgumentException,
UsrSystemException) );
virtual BOOL testPassed(void) THROWS( ( UsrSystemException) );
virtual Sequence< UString > getErrors(void) THROWS( (UsrSystemException) );
virtual Sequence< UsrAny > getErrorExceptions(void) THROWS( (UsrSystemException) );
virtual Sequence< UString > getWarnings(void) THROWS( (UsrSystemException) );
private:
void testSimple( const XExtendedDocumentHandlerRef &r );
void testExceptions( const XExtendedDocumentHandlerRef &r );
void testDTD( const XExtendedDocumentHandlerRef &r );
void testPerformance( const XExtendedDocumentHandlerRef &r );
void writeParagraph( const XExtendedDocumentHandlerRef &r , const UString & s);
private:
Sequence<UsrAny> m_seqExceptions;
Sequence<UString> m_seqErrors;
Sequence<UString> m_seqWarnings;
XMultiServiceFactoryRef m_rFactory;
};
/*----------------------------------------
*
* Attributlist implementation
*
*----------------------------------------*/
struct AttributeListImpl_impl;
class AttributeListImpl :
public XAttributeList,
public OWeakObject
{
public:
AttributeListImpl();
AttributeListImpl( const AttributeListImpl & );
~AttributeListImpl();
public:
BOOL queryInterface( Uik aUik, XInterfaceRef & rOut );
void acquire() { OWeakObject::acquire(); }
void release() { OWeakObject::release(); }
void* getImplementation(Reflection *p) { return OWeakObject::getImplementation(p); }
public:
virtual INT16 getLength(void) THROWS( (UsrSystemException) );
virtual UString getNameByIndex(INT16 i) THROWS( (UsrSystemException) );
virtual UString getTypeByIndex(INT16 i) THROWS( (UsrSystemException) );
virtual UString getTypeByName(const UString& aName) THROWS( (UsrSystemException) );
virtual UString getValueByIndex(INT16 i) THROWS( (UsrSystemException) );
virtual UString getValueByName(const UString& aName) THROWS( (UsrSystemException) );
public:
void addAttribute( const UString &sName , const UString &sType , const UString &sValue );
void clear();
private:
struct AttributeListImpl_impl *m_pImpl;
};
struct TagAttribute
{
TagAttribute(){}
TagAttribute( const UString &sName, const UString &sType , const UString &sValue )
{
this->sName = sName;
this->sType = sType;
this->sValue = sValue;
}
UString sName;
UString sType;
UString sValue;
};
struct AttributeListImpl_impl
{
AttributeListImpl_impl()
{
// performance improvement during adding
vecAttribute.reserve(20);
}
vector<struct TagAttribute> vecAttribute;
};
INT16 AttributeListImpl::getLength(void) THROWS( (UsrSystemException) )
{
return m_pImpl->vecAttribute.size();
}
AttributeListImpl::AttributeListImpl( const AttributeListImpl &r )
{
m_pImpl = new AttributeListImpl_impl;
*m_pImpl = *(r.m_pImpl);
}
UString AttributeListImpl::getNameByIndex(INT16 i) THROWS( (UsrSystemException) )
{
if( i < m_pImpl->vecAttribute.size() ) {
return m_pImpl->vecAttribute[i].sName;
}
return UString();
}
UString AttributeListImpl::getTypeByIndex(INT16 i) THROWS( (UsrSystemException) )
{
if( i < m_pImpl->vecAttribute.size() ) {
return m_pImpl->vecAttribute[i].sType;
}
return UString();
}
UString AttributeListImpl::getValueByIndex(INT16 i) THROWS( (UsrSystemException) )
{
if( i < m_pImpl->vecAttribute.size() ) {
return m_pImpl->vecAttribute[i].sValue;
}
return UString();
}
UString AttributeListImpl::getTypeByName( const UString& sName ) THROWS( (UsrSystemException) )
{
vector<struct TagAttribute>::iterator ii = m_pImpl->vecAttribute.begin();
for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) {
if( (*ii).sName == sName ) {
return (*ii).sType;
}
}
return UString();
}
UString AttributeListImpl::getValueByName(const UString& sName) THROWS( (UsrSystemException) )
{
vector<struct TagAttribute>::iterator ii = m_pImpl->vecAttribute.begin();
for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) {
if( (*ii).sName == sName ) {
return (*ii).sValue;
}
}
return UString();
}
BOOL AttributeListImpl::queryInterface( Uik aUik, XInterfaceRef & rOut )
{
if( aUik == XAttributeList::getSmartUik() ) {
rOut = (XAttributeList * )this;
}
else {
return OWeakObject::queryInterface( aUik , rOut );
}
return TRUE;
}
AttributeListImpl::AttributeListImpl()
{
m_pImpl = new AttributeListImpl_impl;
}
AttributeListImpl::~AttributeListImpl()
{
delete m_pImpl;
}
void AttributeListImpl::addAttribute( const UString &sName ,
const UString &sType ,
const UString &sValue )
{
m_pImpl->vecAttribute.push_back( TagAttribute( sName , sType , sValue ) );
}
void AttributeListImpl::clear()
{
vector<struct TagAttribute> dummy;
m_pImpl->vecAttribute.swap( dummy );
OSL_ASSERT( ! getLength() );
}
/**
* for external binding
*
*
**/
XInterfaceRef OSaxWriterTest_CreateInstance( const XMultiServiceFactoryRef & rSMgr ) THROWS((Exception))
{
OSaxWriterTest *p = new OSaxWriterTest( rSMgr );
XInterfaceRef xService = *p;
return xService;
}
UString OSaxWriterTest_getServiceName( ) THROWS( () )
{
return L"test.com.sun.star.xml.sax.Writer";
}
UString OSaxWriterTest_getImplementationName( ) THROWS( () )
{
return L"test.extensions.xml.sax.Writer";
}
Sequence<UString> OSaxWriterTest_getSupportedServiceNames( ) THROWS( () )
{
Sequence<UString> aRet(1);
aRet.getArray()[0] = OSaxWriterTest_getImplementationName( );
return aRet;
}
BOOL OSaxWriterTest::queryInterface( Uik uik , XInterfaceRef &rOut )
{
if( XSimpleTest::getSmartUik() == uik ) {
rOut = (XSimpleTest *) this;
}
else {
return OWeakObject::queryInterface( uik , rOut );
}
return TRUE;
}
void OSaxWriterTest::testInvariant( const UString& TestName, const XInterfaceRef& TestObject )
THROWS( ( IllegalArgumentException,
UsrSystemException) )
{
if( L"com.sun.star.xml.sax.Writer" == TestName ) {
XDocumentHandlerRef doc( TestObject , USR_QUERY );
XExtendedDocumentHandlerRef ext( TestObject , USR_QUERY );
XActiveDataSourceRef source( TestObject , USR_QUERY );
ERROR_ASSERT( doc.is() , "XDocumentHandler cannot be queried" );
ERROR_ASSERT( ext.is() , "XExtendedDocumentHandler cannot be queried" );
ERROR_ASSERT( source.is() , "XActiveDataSource cannot be queried" );
}
else {
BUILD_ERROR( 0 , "wrong test" );
}
}
INT32 OSaxWriterTest::test( const UString& TestName,
const XInterfaceRef& TestObject,
INT32 hTestHandle) THROWS( ( IllegalArgumentException,
UsrSystemException) )
{
if( L"com.sun.star.xml.sax.Writer" == TestName ) {
try {
if( 0 == hTestHandle ) {
testInvariant( TestName , TestObject );
}
else {
XExtendedDocumentHandlerRef writer( TestObject , USR_QUERY );
if( 1 == hTestHandle ) {
testSimple( writer );
}
else if( 2 == hTestHandle ) {
testExceptions( writer );
}
else if( 3 == hTestHandle ) {
testDTD( writer );
}
else if( 4 == hTestHandle ) {
testPerformance( writer );
}
}
}
catch( Exception& e ) {
BUILD_ERROR( 0 , UStringToString( e.getName() , CHARSET_SYSTEM ).GetCharStr() );
}
catch(...) {
BUILD_ERROR( 0 , "unknown exception (Exception is not base class)" );
}
hTestHandle ++;
if( hTestHandle >= 5) {
// all tests finished.
hTestHandle = -1;
}
}
else {
BUILD_ERROR( 0 , "service not supported by test." );
}
return hTestHandle;
}
BOOL OSaxWriterTest::testPassed(void) THROWS( (UsrSystemException) )
{
return m_seqErrors.getLen() == 0;
}
Sequence< UString > OSaxWriterTest::getErrors(void) THROWS( (UsrSystemException) )
{
return m_seqErrors;
}
Sequence< UsrAny > OSaxWriterTest::getErrorExceptions(void) THROWS( (UsrSystemException) )
{
return m_seqExceptions;
}
Sequence< UString > OSaxWriterTest::getWarnings(void) THROWS( (UsrSystemException) )
{
return m_seqWarnings;
}
void OSaxWriterTest::writeParagraph( const XExtendedDocumentHandlerRef &r , const UString & s)
{
int nMax = s.len();
int nStart = 0;
Sequence<UINT16> seq( s.len() );
memcpy( seq.getArray() , s.getStr() , s.len() * sizeof( UINT16 ) );
for( int n = 1 ; n < nMax ; n++ ){
if( 32 == seq.getArray()[n] ) {
r->allowLineBreak();
r->characters( s.copy( nStart , n - nStart ) );
nStart = n;
}
}
r->allowLineBreak();
r->characters( s.copy( nStart , n - nStart ) );
}
void OSaxWriterTest::testSimple( const XExtendedDocumentHandlerRef &r )
{
UString testParagraph = L"Dies ist ein bloeder Test um zu uberpruefen, ob der SAXWriter "
L"wohl Zeilenumbrueche halbwegs richtig macht oder ob er die Zeile "
L"bis zum bitteren Ende schreibt.";
OFileWriter *pw = new OFileWriter("output.xml");
AttributeListImpl *pList = new AttributeListImpl;
XAttributeListRef rList( (XAttributeList *) pList , USR_QUERY );
XOutputStreamRef ref( ( XOutputStream * ) pw , USR_QUERY );
XActiveDataSourceRef source( r , USR_QUERY );
ERROR_ASSERT( ref.is() , "no output stream" );
ERROR_ASSERT( source.is() , "no active data source" );
source->setOutputStream( ref );
r->startDocument();
pList->addAttribute( L"Arg1" , L"CDATA" , L"bla\n u" );
pList->addAttribute( L"Arg2" , L"CDATA" , L"blub" );
r->startElement( L"tag1" , rList );
r->ignorableWhitespace( L"" );
r->characters( L"huhu" );
r->ignorableWhitespace( L"" );
r->startElement( L"hi" , rList );
r->ignorableWhitespace( L"" );
// the enpassant must be converted & -> &
r->characters( L"ü" );
// Test added for mib. Tests if errors during conversions occurs
r->ignorableWhitespace( UString() );
sal_Char array[256];
for( sal_Int32 n = 32 ; n < 254 ; n ++ ) {
array[n-32] = n;
}
array[254-32] = 0;
r->characters(
StringToUString( array , RTL_TEXTENCODING_SYMBOL )
);
r->ignorableWhitespace( UString() );
// '>' must not be converted
r->startCDATA();
r->characters( L">fsfsdf<" );
r->endCDATA();
r->ignorableWhitespace( UString() );
writeParagraph( r , testParagraph );
r->ignorableWhitespace( UString() );
r->comment( L"Dies ist ein Kommentar !" );
r->ignorableWhitespace( UString() );
r->startElement( L"emptytagtest" , rList );
r->endElement( L"emptytagtest" );
r->endElement( L"hi" );
r->ignorableWhitespace( L"" );
r->endElement( L"tag1" );
r->endDocument();
}
void OSaxWriterTest::testExceptions( const XExtendedDocumentHandlerRef & r )
{
OFileWriter *pw = new OFileWriter("output2.xml");
AttributeListImpl *pList = new AttributeListImpl;
XAttributeListRef rList( (XAttributeList *) pList , USR_QUERY );
XOutputStreamRef ref( ( XOutputStream * ) pw , USR_QUERY );
XActiveDataSourceRef source( r , USR_QUERY );
ERROR_ASSERT( ref.is() , "no output stream" );
ERROR_ASSERT( source.is() , "no active data source" );
source->setOutputStream( ref );
{ // startDocument must be called before start element
BOOL bException = TRUE;
try {
r->startElement( L"huhu" , rList );
bException = FALSE;
}
catch( SAXException& e ) {
}
ERROR_ASSERT( bException , "expected exception not thrown !" );
}
r->startDocument();
r->startElement( L"huhu" , rList );
r->startCDATA();
{
BOOL bException = TRUE;
try {
r->startElement( L"huhu" , rList );
bException = FALSE;
}
catch( SAXException& e ) {
}
ERROR_ASSERT( bException , "expected exception not thrown !" );
}
r->endCDATA();
r->endElement( L"hi" );
r->endDocument();
}
void OSaxWriterTest::testDTD(const XExtendedDocumentHandlerRef &r )
{
OFileWriter *pw = new OFileWriter("outputDTD.xml");
AttributeListImpl *pList = new AttributeListImpl;
XAttributeListRef rList( (XAttributeList *) pList , USR_QUERY );
XOutputStreamRef ref( ( XOutputStream * ) pw , USR_QUERY );
XActiveDataSourceRef source( r , USR_QUERY );
ERROR_ASSERT( ref.is() , "no output stream" );
ERROR_ASSERT( source.is() , "no active data source" );
source->setOutputStream( ref );
r->startDocument();
r->unknown( L"<!DOCTYPE iCalendar >\n" );
r->startElement( L"huhu" , rList );
r->endElement( L"huhu" );
r->endDocument();
}
void OSaxWriterTest::testPerformance(const XExtendedDocumentHandlerRef &r )
{
OFileWriter *pw = new OFileWriter("testPerformance.xml");
AttributeListImpl *pList = new AttributeListImpl;
UString testParagraph = L"Dies ist ein bloeder Test um zu uberpruefen, ob der SAXWriter "
L"wohl > Zeilenumbrueche halbwegs richtig macht oder ob er die Zeile "
L"bis zum bitteren Ende schreibt.";
XAttributeListRef rList( (XAttributeList *) pList , USR_QUERY );
XOutputStreamRef ref( ( XOutputStream * ) pw , USR_QUERY );
XActiveDataSourceRef source( r , USR_QUERY );
ERROR_ASSERT( ref.is() , "no output stream" );
ERROR_ASSERT( source.is() , "no active data source" );
source->setOutputStream( ref );
TimeValue aStartTime, aEndTime;
osl_getSystemTime( &aStartTime );
r->startDocument();
// just write a bunch of xml tags !
// for performance testing
sal_Int32 i2;
for( i2 = 0 ; i2 < 15 ; i2 ++ )
{
r->startElement( UString( L"tag" ) + UString::valueOf( i2 ), rList );
for( sal_Int32 i = 0 ; i < 450 ; i ++ )
{
r->ignorableWhitespace( L"");
r->startElement( L"huhu" , rList );
r->characters( testParagraph );
// writeParagraph( r , testParagraph );
r->ignorableWhitespace( L"");
r->endElement( L"huhu" );
}
}
for( i2 = 14 ; i2 >= 0 ; i2-- )
{
r->ignorableWhitespace( L"");
r->endElement( UString( L"tag" ) + UString::valueOf( i2 ) );
}
r->endDocument();
osl_getSystemTime( &aEndTime );
double fStart = (double)aStartTime.Seconds + ((double)aStartTime.Nanosec / 1000000000.0);
double fEnd = (double)aEndTime.Seconds + ((double)aEndTime.Nanosec / 1000000000.0);
printf( "Performance writing : %g s\n" , fEnd - fStart );
}
| 25.314694 | 104 | 0.671239 | [
"vector"
] |
17ec1b0b5248802d29dde5b4219145b866726e9b | 4,361 | cc | C++ | src/backjump-solver.cc | ThuriyaThwin/ACE-CSP-Solver | 528b4c494fe77495888bb3f9155ec7c3ce9b0fbe | [
"MIT"
] | 2 | 2015-01-10T12:25:14.000Z | 2016-01-01T13:37:50.000Z | src/backjump-solver.cc | ThuriyaThwin/ACE-CSP-Solver | 528b4c494fe77495888bb3f9155ec7c3ce9b0fbe | [
"MIT"
] | null | null | null | src/backjump-solver.cc | ThuriyaThwin/ACE-CSP-Solver | 528b4c494fe77495888bb3f9155ec7c3ce9b0fbe | [
"MIT"
] | 1 | 2021-06-24T12:34:31.000Z | 2021-06-24T12:34:31.000Z | // Copyright 2012 Eugen Sawin <esawin@me73.com>
#include "./backjump-solver.h"
#include <cassert>
#include <vector>
#include <set>
#include <limits>
#include <iostream>
#include "./clock.h"
#include "./network.h"
#include "./variable-ordering.h"
using std::vector;
using std::set;
using base::Clock;
using std::numeric_limits;
using std::min;
using std::max;
namespace ace {
BackjumpSolver::BackjumpSolver(Network* network)
: Solver(),
network_(*network),
preprocessor_(network),
time_limit_(Solver::kDefTimeLimit),
max_num_solutions_(Solver::kDefMaxNumSolutions) {
Reset();
// Set the lexicographical variable ordering.
const int num_vars = network_.num_variables();
var_ordering_.resize(num_vars, 0);
for (int i = 0; i < num_vars; ++i) {
var_ordering_[i] = i;
}
}
bool BackjumpSolver::Solve() {
static const int kInvalidId = -1;
Reset();
begin_clock_ = Clock();
Assignment assignment(network_);
const int num_variables = network_.num_variables();
domains_.resize(num_variables);
latest_.resize(num_variables + 1, kInvalidId);
int var_seq = 0;
{
int var_id = var_ordering_[var_seq];
assert(var_id >= 0 && var_id < num_variables);
const Variable& var = network_.variable(var_id);
domains_[var_id] = var.domain();
}
while (var_seq != kInvalidId && var_seq < num_variables) {
if (solutions_.size() >= max_num_solutions_ ||
Clock() - begin_clock_ > time_limit_) {
// Enough solutions found or time limit reached.
break;
}
if (SelectValue(var_seq, &assignment)) {
latest_[++var_seq] = kInvalidId;
if (var_seq == num_variables) {
// Solution found.
assert(assignment.Complete() && assignment.Consistent());
solutions_.push_back(assignment);
} else if (var_seq != kInvalidId) {
const int var_id = var_ordering_[var_seq];
assert(var_id >= 0 && var_id < num_variables);
const Variable& var = network_.variable(var_id);
domains_[var_id] = var.domain();
}
} else {
++num_backtracks_;
const int jump_height = var_seq - latest_[var_seq];
assert(jump_height > 0);
var_seq = latest_[var_seq];
if (var_seq != kInvalidId) {
// const int num_ass = assignment.num_assigned();
for (int i = 0; i < jump_height; ++i) {
assignment.Revert();
}
assert(assignment.num_assigned() == var_seq);
}
}
}
duration_ = Clock() - begin_clock_;
return solutions_.size();
}
bool BackjumpSolver::SelectValue(const int var_seq, Assignment* assignment) {
const int var_id = var_ordering_[var_seq];
vector<int>& domain = domains_[var_id];
while (domain.size()) {
const int value = domain.back();
Assignment test_assignment(network_);
test_assignment.Assign(var_id, value);
bool consistent = test_assignment.Consistent();
int k = 0;
while (k < var_seq && consistent) {
latest_[var_seq] = max(latest_[var_seq], k);
const int k_var_id = var_ordering_[k];
const int k_value = assignment->value(k_var_id);
test_assignment.Assign(k_var_id, k_value);
consistent = test_assignment.Consistent();
++k;
}
domain.pop_back();
if (consistent) {
assignment->Assign(var_id, value);
return true;
}
}
return false;
}
void BackjumpSolver::Reset() {
duration_ = 0;
num_backtracks_ = 0;
num_explored_states_ = 0.0;
latest_.clear();
domains_.clear();
}
void BackjumpSolver::variable_ordering(const VariableOrdering& var_ordering) {
var_ordering_ = var_ordering.CreateOrdering();
}
void BackjumpSolver::time_limit(const Clock::Diff& limit) {
time_limit_ = min(limit, Solver::kDefTimeLimit);
}
Clock::Diff BackjumpSolver::time_limit() const {
return time_limit_;
}
void BackjumpSolver::max_num_solutions(const int num) {
max_num_solutions_ = num > 0 ? num : Solver::kDefMaxNumSolutions;
}
int BackjumpSolver::max_num_solutions() const {
return max_num_solutions_;
}
const vector<Assignment>& BackjumpSolver::solutions() const {
return solutions_;
}
double BackjumpSolver::num_explored_states() const {
return num_explored_states_;
}
int BackjumpSolver::num_backtracks() const {
return num_backtracks_;
}
Clock::Diff BackjumpSolver::duration() const {
return duration_;
}
} // namespace ace
| 26.430303 | 78 | 0.672781 | [
"vector"
] |
17ef902fda2023427679c389c56842547dcf1c54 | 22,595 | cpp | C++ | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/writeengine/shared/we_dbrootextenttracker.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/writeengine/shared/we_dbrootextenttracker.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/writeengine/shared/we_dbrootextenttracker.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | 2 | 2022-02-27T14:00:01.000Z | 2022-03-31T06:24:22.000Z | /* Copyright (C) 2014 InfiniDB, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2 of
the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
/*
* $Id: we_dbrootextenttracker.cpp 4631 2013-05-02 15:21:09Z dcathey $
*/
#include "we_dbrootextenttracker.h"
#include <algorithm>
#include <sstream>
#include "we_brm.h"
#include "we_config.h"
#include "we_log.h"
namespace
{
const char* stateStrings[] = { "initState",
"PartialExtent",
"EmptyDbRoot",
"ExtentBoundary",
"OutOfService"
};
}
namespace WriteEngine
{
//------------------------------------------------------------------------------
// DBRootExtentInfo constructor
//------------------------------------------------------------------------------
DBRootExtentInfo::DBRootExtentInfo(
uint16_t dbRoot,
uint32_t partition,
uint16_t segment,
BRM::LBID_t startLbid,
HWM localHwm,
uint64_t dbrootTotalBlocks,
DBRootExtentInfoState state) :
fPartition(partition),
fDbRoot(dbRoot),
fSegment(segment),
fStartLbid(startLbid),
fLocalHwm(localHwm),
fDBRootTotalBlocks(dbrootTotalBlocks),
fState(state)
{
}
//------------------------------------------------------------------------------
// LessThan operator used to sort DBRootExtentInfo objects by DBRoot.
//------------------------------------------------------------------------------
bool DBRootExtentInfo::operator<(
const DBRootExtentInfo& entry) const
{
if (fDbRoot < entry.fDbRoot)
return true;
return false;
}
//------------------------------------------------------------------------------
// DBRootExtentTracker constructor
//
// Mutex lock not needed in this function as it is only called from main thread
// before processing threads are spawned.
//------------------------------------------------------------------------------
DBRootExtentTracker::DBRootExtentTracker ( OID oid,
const std::vector<int>& colWidths,
const std::vector<BRM::EmDbRootHWMInfo_v>& dbRootHWMInfoColVec,
unsigned int columnIdx,
Log* logger ) :
fOID(oid),
fLog(logger),
fCurrentDBRootIdx(-1),
fEmptyOrDisabledPM(false),
fEmptyPM(true),
fDisabledHWM(false)
{
const BRM::EmDbRootHWMInfo_v& emDbRootHWMInfo =
dbRootHWMInfoColVec[columnIdx];
int colWidth = colWidths[columnIdx];
fBlksPerExtent = (long long)BRMWrapper::getInstance()->getExtentRows() *
(long long)colWidth / (long long)BYTE_PER_BLOCK;
std::vector<bool> resetState;
for (unsigned int i = 0; i < emDbRootHWMInfo.size(); i++)
{
resetState.push_back(false);
DBRootExtentInfoState state = determineState(
colWidths[columnIdx],
emDbRootHWMInfo[i].localHWM,
emDbRootHWMInfo[i].totalBlocks,
emDbRootHWMInfo[i].status);
// For a full extent...
// check to see if any of the column HWMs are partially full, in which
// case we consider all the columns for that DBRoot to be partially
// full. (This can happen if a table has columns with varying widths,
// as the HWM may be at the last extent block for a shorter column, and
// still have free blocks for wider columns.)
if (state == DBROOT_EXTENT_EXTENT_BOUNDARY)
{
for (unsigned int kCol = 0; kCol < dbRootHWMInfoColVec.size(); kCol++)
{
const BRM::EmDbRootHWMInfo_v& emDbRootHWMInfo2 =
dbRootHWMInfoColVec[kCol];
DBRootExtentInfoState state2 = determineState(
colWidths[kCol],
emDbRootHWMInfo2[i].localHWM,
emDbRootHWMInfo2[i].totalBlocks,
emDbRootHWMInfo2[i].status);
if (state2 == DBROOT_EXTENT_PARTIAL_EXTENT)
{
state = DBROOT_EXTENT_PARTIAL_EXTENT;
resetState[ resetState.size() - 1 ] = true;
break;
}
}
}
DBRootExtentInfo dbRootExtent(
emDbRootHWMInfo[i].dbRoot,
emDbRootHWMInfo[i].partitionNum,
emDbRootHWMInfo[i].segmentNum,
emDbRootHWMInfo[i].startLbid,
emDbRootHWMInfo[i].localHWM,
emDbRootHWMInfo[i].totalBlocks,
state);
fDBRootExtentList.push_back( dbRootExtent );
}
std::sort( fDBRootExtentList.begin(), fDBRootExtentList.end() );
if (fLog)
{
// Always log this info for now; may control with debug later
//if (fLog->isDebug(DEBUG_1))
{
std::ostringstream oss;
oss << "Starting DBRoot info for OID " << fOID;
for (unsigned int k = 0; k < fDBRootExtentList.size(); k++)
{
oss << std::endl;
oss << " DBRoot-" << fDBRootExtentList[k].fDbRoot <<
", part/seg/hwm/LBID/totBlks/state: " <<
fDBRootExtentList[k].fPartition <<
"/" << fDBRootExtentList[k].fSegment <<
"/" << fDBRootExtentList[k].fLocalHwm <<
"/" << fDBRootExtentList[k].fStartLbid <<
"/" << fDBRootExtentList[k].fDBRootTotalBlocks <<
"/" << stateStrings[ fDBRootExtentList[k].fState ];
if (resetState[k])
oss << ".";
}
fLog->logMsg( oss.str(), MSGLVL_INFO2 );
}
}
}
//------------------------------------------------------------------------------
// Determines the state of the HWM extent (for a DBRoot); considering the
// current BRM status, HWM, and total block count for the DBRoot.
//------------------------------------------------------------------------------
DBRootExtentInfoState DBRootExtentTracker::determineState(int colWidth,
HWM localHwm,
uint64_t dbRootTotalBlocks,
int16_t status)
{
DBRootExtentInfoState extentState;
if (status == BRM::EXTENTOUTOFSERVICE)
{
extentState = DBROOT_EXTENT_OUT_OF_SERVICE;
}
else
{
if (dbRootTotalBlocks == 0)
{
extentState = DBROOT_EXTENT_EMPTY_DBROOT;
}
else
{
extentState = DBROOT_EXTENT_PARTIAL_EXTENT;
// See if local hwm is on an extent bndry,in which case the extent
// is full and we won't be adding rows to the current HWM extent;
// we will instead need to allocate a new extent in order to begin
// adding any rows.
long long nRows = ((long long)(localHwm + 1) *
(long long)BYTE_PER_BLOCK) / (long long)colWidth;
long long nRem = nRows % BRMWrapper::getInstance()->getExtentRows();
if (nRem == 0)
{
extentState = DBROOT_EXTENT_EXTENT_BOUNDARY;
}
}
}
return extentState;
}
//------------------------------------------------------------------------------
// Select the first segment file to add rows to for the local PM.
// Function will first try to find the HWM extent with the fewest blocks.
// If all the HWM extents are full, then we select the DBRoot/segment file
// with the fewest total overall blocks for that DBRoot.
// Return value is 0 upon success, else non zero if no eligible entries found.
//
// Mutex lock not needed in this function as it is only called from main thread
// before processing threads are spawned.
//------------------------------------------------------------------------------
int DBRootExtentTracker::selectFirstSegFile(
DBRootExtentInfo& dbRootExtent, bool& bNoStartExtentOnThisPM,
bool& bEmptyPM,
std::string& errMsg )
{
int startExtentIdx = -1;
int fewestLocalBlocksIdx = -1; // track HWM extent with fewest blocks
int fewestTotalBlocksIdx = -1; // track DBRoot with fewest total blocks
bNoStartExtentOnThisPM = false;
unsigned int fewestTotalBlks = UINT_MAX;
unsigned int fewestLocalBlks = UINT_MAX;
uint16_t fewestTotalBlkSegNum = USHRT_MAX;
uint16_t fewestLocalBlkSegNum = USHRT_MAX;
// Find DBRoot having HWM extent with fewest blocks. If all HWM extents
// are full (remblks=0), then fall-back on selecting the DBRoot with fewest
// total blks.
//
// Selecting HWM extent with fewest blocks should be straight forward, be-
// cause all the DBRoots on a PM should end on an extent boundary except
// for the current last extent. But if the user has moved a DBRoot, then
// we can end up with 2 partially filled HWM extents on 2 DBRoots, on the
// same PM. That's why we loop through the DBRoots to see if we have more
// than 1 partially filled HWM extent.
for (unsigned int iroot = 0;
iroot < fDBRootExtentList.size();
iroot++)
{
// Skip over DBRoots which have no extents
if (fDBRootExtentList[iroot].fState == DBROOT_EXTENT_EMPTY_DBROOT)
continue;
fEmptyPM = false;
// Find DBRoot and segment file with most incomplete extent.
// Break a tie by selecting the lowest segment number.
long long remBlks = (long long)(fDBRootExtentList[iroot].fLocalHwm + 1) %
fBlksPerExtent;
if (remBlks > 0)
{
if ( (remBlks < fewestLocalBlks) ||
((remBlks == fewestLocalBlks) &&
(fDBRootExtentList[iroot].fSegment < fewestLocalBlkSegNum)) )
{
fewestLocalBlocksIdx = iroot;
fewestLocalBlks = remBlks;
fewestLocalBlkSegNum = fDBRootExtentList[iroot].fSegment;
}
}
// Find DBRoot with fewest total of blocks.
// Break a tie by selecting the highest segment number.
if ( (fDBRootExtentList[iroot].fDBRootTotalBlocks < fewestTotalBlks) ||
((fDBRootExtentList[iroot].fDBRootTotalBlocks == fewestTotalBlks) &&
(fDBRootExtentList[iroot].fSegment > fewestTotalBlkSegNum)) )
{
fewestTotalBlocksIdx = iroot;
fewestTotalBlks = fDBRootExtentList[iroot].fDBRootTotalBlocks;
fewestTotalBlkSegNum = fDBRootExtentList[iroot].fSegment;
}
}
// Select HWM extent with fewest number of blocks;
// If chosen extent is disabled, then treat like an empty PM,
// meaning we have to allocate a new extent before adding any rows
if (fewestLocalBlocksIdx != -1)
{
startExtentIdx = fewestLocalBlocksIdx;
if (fDBRootExtentList[startExtentIdx].fState ==
DBROOT_EXTENT_OUT_OF_SERVICE)
{
fDisabledHWM = true;
}
}
// If the HWM on each DBRoot ends on an extent boundary, then
// select the DBRoot with the fewest total number of blocks;
// If chosen extent is disabled, then treat like an empty PM,
// meaning we have to allocate a new extent before adding any rows
else if (fewestTotalBlocksIdx != -1)
{
startExtentIdx = fewestTotalBlocksIdx;
if (fDBRootExtentList[startExtentIdx].fState ==
DBROOT_EXTENT_OUT_OF_SERVICE)
{
fDisabledHWM = true;
}
}
// PM with no extents (or all extents disabled), so select DBRoot/segment
// file from DBRoot list, where we will start inserting rows.
// Select lowest segment file number.
else
{
RETURN_ON_ERROR( selectFirstSegFileForEmptyPM( errMsg ) );
startExtentIdx = fCurrentDBRootIdx;
}
if ((fEmptyOrDisabledPM) || (fDisabledHWM))
bNoStartExtentOnThisPM = true;
bEmptyPM = fEmptyPM;
fCurrentDBRootIdx = startExtentIdx;
// Finish Initializing DBRootExtentList for empty DBRoots w/o any extents
initEmptyDBRoots( );
logFirstDBRootSelection( );
dbRootExtent = fDBRootExtentList[startExtentIdx];
fDBRootExtentList[startExtentIdx].fState = DBROOT_EXTENT_EXTENT_BOUNDARY;
return NO_ERROR;
}
//------------------------------------------------------------------------------
// If we have encountered a PM with no extents (or all extent disabled), then
// this function can be called to determine the DBRoot to be used for the 1st
// extent for the applicable PM. First DBRoot for relevant PM is selected.
// At extent creation time, BRM will assign the segment number.
//
// Mutex lock not needed in this function as it is only called from main thread
// before processing threads are spawned.
//------------------------------------------------------------------------------
int DBRootExtentTracker::selectFirstSegFileForEmptyPM( std::string& errMsg )
{
fEmptyOrDisabledPM = true;
fCurrentDBRootIdx = 0; // Start with first DBRoot for this PM
// Always start empty PM with partition number 0. If the DBRoot has a HWM
// extent that is disabled, then BRM will override this partition number.
fDBRootExtentList[fCurrentDBRootIdx].fPartition = 0;
return NO_ERROR;
}
//------------------------------------------------------------------------------
// Finish Initializing fDBRootExtentList for any empty DBRoots w/o any extents.
//------------------------------------------------------------------------------
void DBRootExtentTracker::initEmptyDBRoots( )
{
int startExtentIdx = fCurrentDBRootIdx;
bool bAnyChanges = false; // If fDBRootExtentList changes, log the contents
// Fill in starting partition for any DBRoots having no extents
for (unsigned int iroot = 0;
iroot < fDBRootExtentList.size();
iroot++)
{
if ((fDBRootExtentList[iroot].fState == DBROOT_EXTENT_EMPTY_DBROOT) &&
((int)iroot != startExtentIdx)) // skip over selected dbroot
{
if (fDBRootExtentList[iroot].fPartition !=
fDBRootExtentList[startExtentIdx].fPartition)
{
bAnyChanges = true;
fDBRootExtentList[iroot].fPartition =
fDBRootExtentList[startExtentIdx].fPartition;
}
}
}
// Log fDBRootExtentList if modifications were made
if ((bAnyChanges) && (fLog))
{
// Always log this info for now; may control with debug later
//if (fLog->isDebug(DEBUG_1))
{
std::ostringstream oss;
oss << "Updated starting (empty) DBRoot info for OID " << fOID;
for (unsigned int k = 0; k < fDBRootExtentList.size(); k++)
{
oss << std::endl;
oss << " DBRoot-" << fDBRootExtentList[k].fDbRoot <<
", part/seg/hwm/LBID/totBlks/state: " <<
fDBRootExtentList[k].fPartition <<
"/" << fDBRootExtentList[k].fSegment <<
"/" << fDBRootExtentList[k].fLocalHwm <<
"/" << fDBRootExtentList[k].fStartLbid <<
"/" << fDBRootExtentList[k].fDBRootTotalBlocks <<
"/" << stateStrings[ fDBRootExtentList[k].fState ];
}
fLog->logMsg( oss.str(), MSGLVL_INFO2 );
}
}
}
//------------------------------------------------------------------------------
// Assign the DBRoot/segment file to be used for extent loading based on the
// setting in the specified reference tracker (set for a reference column).
//
// Mutex lock not needed in this function as it is only called from main thread
// before processing threads are spawned.
//------------------------------------------------------------------------------
void DBRootExtentTracker::assignFirstSegFile(
const DBRootExtentTracker& refTracker,
DBRootExtentInfo& dbRootExtent)
{
// Start with the same DBRoot index as the reference tracker; assumes that
// DBRoots for each column are listed in same order in fDBRootExtentList.
// That should be a safe assumption since DBRootExtentTracker constructor
// sorts the entries in fDBRootExtentList by fDbRoot.
int startExtentIdx = refTracker.fCurrentDBRootIdx;
fEmptyOrDisabledPM = refTracker.fEmptyOrDisabledPM;
fEmptyPM = refTracker.fEmptyPM;
fDisabledHWM = refTracker.fDisabledHWM;
// Always start empty PM with partition number 0. If the DBRoot has a HWM
// extent that is disabled, then BRM will override this partition number.
if (fEmptyOrDisabledPM)
{
fDBRootExtentList[startExtentIdx].fPartition = 0;
}
fCurrentDBRootIdx = startExtentIdx;
// Finish Initializing DBRootExtentList for empty DBRoots w/o any extents
initEmptyDBRoots( );
logFirstDBRootSelection( );
dbRootExtent = fDBRootExtentList[startExtentIdx];
fDBRootExtentList[startExtentIdx].fState = DBROOT_EXTENT_EXTENT_BOUNDARY;
}
//------------------------------------------------------------------------------
// Log information about the first DBRoot/segment file that is selected.
//------------------------------------------------------------------------------
void DBRootExtentTracker::logFirstDBRootSelection( ) const
{
if (fLog)
{
int extentIdx = fCurrentDBRootIdx;
if (fEmptyOrDisabledPM)
{
std::ostringstream oss;
oss << "No active extents; will add partition to start adding "
"rows for oid-" << fOID <<
"; DBRoot-" << fDBRootExtentList[extentIdx].fDbRoot;
fLog->logMsg( oss.str(), MSGLVL_INFO2 );
}
else if (fDisabledHWM)
{
std::ostringstream oss;
oss << "HWM extent disabled; will add partition to start adding "
"rows for oid-" << fOID <<
"; DBRoot-" << fDBRootExtentList[extentIdx].fDbRoot;
fLog->logMsg( oss.str(), MSGLVL_INFO2 );
}
else
{
std::ostringstream oss;
oss << "Selecting existing segFile to begin adding rows: oid-" << fOID <<
"; DBRoot-" << fDBRootExtentList[extentIdx].fDbRoot <<
", part/seg/hwm/LBID/totBlks/state: " <<
fDBRootExtentList[extentIdx].fPartition <<
"/" << fDBRootExtentList[extentIdx].fSegment <<
"/" << fDBRootExtentList[extentIdx].fLocalHwm <<
"/" << fDBRootExtentList[extentIdx].fStartLbid <<
"/" << fDBRootExtentList[extentIdx].fDBRootTotalBlocks <<
"/" << stateStrings[ fDBRootExtentList[extentIdx].fState ];
fLog->logMsg( oss.str(), MSGLVL_INFO2 );
}
}
}
//------------------------------------------------------------------------------
// Iterate/return next DBRoot to be used for the next extent
//
// If it is the "very" 1st extent for the specified DBRoot, then the applicable
// partition to be used for the first extent, is also returned.
// If a partial extent is to be filled in, then the current HWM
// and starting LBID for the relevant extent are returned.
// If a disabled extent is encountered, the return flag is true, so that
// we can allocate a new extent at the next physical partition. BRM should
// take care of figuring out where to allocate this next extent.
//
// Returns true if new extent needs to be allocated, else false indicates that
// the extent is partially full.
//------------------------------------------------------------------------------
bool DBRootExtentTracker::nextSegFile(
uint16_t& dbRoot,
uint32_t& partition,
uint16_t& segment,
HWM& localHwm,
BRM::LBID_t& startLbid)
{
boost::mutex::scoped_lock lock(fDBRootExtTrkMutex);
fCurrentDBRootIdx++;
if ((unsigned int)fCurrentDBRootIdx >= fDBRootExtentList.size())
fCurrentDBRootIdx = 0;
dbRoot = fDBRootExtentList[fCurrentDBRootIdx].fDbRoot;
segment = fDBRootExtentList[fCurrentDBRootIdx].fSegment;
partition = fDBRootExtentList[fCurrentDBRootIdx].fPartition;
localHwm = fDBRootExtentList[fCurrentDBRootIdx].fLocalHwm;
startLbid = fDBRootExtentList[fCurrentDBRootIdx].fStartLbid;
//std::cout << "NextSegFile: Current idx: " << fCurrentDBRootIdx <<
//"; new dbroot: " << dbRoot <<
//"; segment: " << segment <<
//"; partition: " << partition <<
//"; localHwm: " << localHwm <<
//"; startLbid: " << startLbid <<
//"; state: " << stateStrings[fDBRootExtentList[fCurrentDBRootIdx].fState]
// << std::endl;
bool bAllocExtentFlag = true;
if (fDBRootExtentList[fCurrentDBRootIdx].fState ==
DBROOT_EXTENT_PARTIAL_EXTENT)
bAllocExtentFlag = false;
// After we have taken care of the "first" extent for each DBRoot, we can
// zero out everything. The only thing we need to continue rotating thru
// the DBRoots, is the DBRoot number itself.
fDBRootExtentList[fCurrentDBRootIdx].fSegment = 0;
fDBRootExtentList[fCurrentDBRootIdx].fPartition = 0;
fDBRootExtentList[fCurrentDBRootIdx].fLocalHwm = 0;
fDBRootExtentList[fCurrentDBRootIdx].fStartLbid = 0;
fDBRootExtentList[fCurrentDBRootIdx].fDBRootTotalBlocks = 0;
fDBRootExtentList[fCurrentDBRootIdx].fState = DBROOT_EXTENT_EXTENT_BOUNDARY;
return bAllocExtentFlag;
}
const std::vector<DBRootExtentInfo>& DBRootExtentTracker::getDBRootExtentList()
{
boost::mutex::scoped_lock lock(fDBRootExtTrkMutex);
return fDBRootExtentList;
}
} // end of namespace
| 39.02418 | 85 | 0.576234 | [
"vector"
] |
17efae6a1723b2ce6442e085bcba6f60b6d27336 | 3,420 | hpp | C++ | src/libv/gl/matrix_stack.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 2 | 2018-04-11T03:07:03.000Z | 2019-03-29T15:24:12.000Z | src/libv/gl/matrix_stack.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | null | null | null | src/libv/gl/matrix_stack.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 1 | 2021-06-13T06:39:06.000Z | 2021-06-13T06:39:06.000Z | // Project: libv.gl, File: src/libv/gl/matrix_stack.hpp, Author: Császár Mátyás [Vader]
#pragma once
// std
#include <vector>
// libv
#include <libv/math/angle.hpp>
#include <libv/math/vec.hpp>
#include <libv/utility/guard.hpp>
// pro
#include <libv/gl/assert.hpp>
namespace libv {
namespace gl {
// -------------------------------------------------------------------------------------------------
template <typename Mat>
class MatrixStack {
private:
std::vector<Mat> stack;
public:
using value_type = Mat;
using T = typename Mat::value_type;
public:
inline MatrixStack() {
stack.emplace_back();
identity();
}
inline MatrixStack<Mat>& push() {
LIBV_GL_DEBUG_ASSERT(stack.size() > 0);
stack.push_back(top());
return *this;
}
inline MatrixStack<Mat>& push(const Mat& mx) {
stack.push_back(mx);
return *this;
}
[[nodiscard]] inline auto push_guard() noexcept {
push();
return Guard([this] { pop(); });
}
[[nodiscard]] inline auto push_guard(const Mat& mx) noexcept {
push(mx);
return Guard([this] { pop(); });
}
inline MatrixStack<Mat>& pop() {
// Asserting for 1 because because empty stack is not allowed
LIBV_GL_DEBUG_ASSERT(stack.size() > 1);
stack.pop_back();
return *this;
}
inline decltype(auto) top() const {
LIBV_GL_DEBUG_ASSERT(stack.size() > 0);
return stack.back();
}
inline decltype(auto) top() {
LIBV_GL_DEBUG_ASSERT(stack.size() > 0);
return stack.back();
}
inline MatrixStack& operator=(const Mat& mat) & {
top() = mat;
return *this;
}
inline decltype(auto) operator*(const vec4_t<T>& v) const {
return top() * v;
}
inline decltype(auto) operator*(const Mat& mat) const {
return top() * mat;
}
inline decltype(auto) operator*(const MatrixStack<Mat>& ms) const {
return top() * ms.top();
}
inline decltype(auto) operator*=(const Mat& mat) {
top() = top() * mat;
return *this;
}
inline decltype(auto) operator*=(const MatrixStack<Mat>& ms) {
top() = top() * ms.top();
return *this;
}
inline operator Mat() const {
return top();
}
inline operator Mat&() {
return top();
}
inline operator const Mat&() const {
return top();
}
// ---------------------------------------------------------------------------------------------
inline decltype(auto) rotate(const Radian<T> a, const vec3_t<T>& v) {
top().rotate(a, v);
return *this;
}
inline decltype(auto) rotate(const Radian<T> a, const T x, const T y, const T z) {
top().rotate(a, vec3_t<T>(x, y, z));
return *this;
}
inline decltype(auto) scale(const T s) {
top().scale(vec3_t<T>(s, s, s));
return *this;
}
inline decltype(auto) scale(const T x, const T y, const T z) {
top().scale(vec3_t<T>(x, y, z));
return *this;
}
inline decltype(auto) scale(const vec3_t<T>& v) {
top().scale(v);
return *this;
}
inline decltype(auto) translate(const T x, const T y, const T z) {
top().translate(vec3_t<T>(x, y, z));
return *this;
}
inline decltype(auto) translate(const vec3_t<T>& v) {
top().translate(v);
return *this;
}
inline decltype(auto) identity() {
top() = Mat::identity();
return *this;
}
// -------------------------------------------------------------------------------------------------
inline decltype(auto) size() const {
return stack.size();
}
};
// -------------------------------------------------------------------------------------------------s
} // namespace gl
} // namespace libv
| 23.265306 | 101 | 0.57076 | [
"vector"
] |
aa0a94749ec99c83a4f35fcb9c60443489214c14 | 3,020 | hpp | C++ | libraries/chain/include/eosio/chain/txfee_manager.hpp | xuyp1991/eosforce | de3655c35062616a6b52726b298124e27cf19cb5 | [
"MIT"
] | 1 | 2019-05-29T14:03:07.000Z | 2019-05-29T14:03:07.000Z | libraries/chain/include/eosio/chain/txfee_manager.hpp | xuyp1991/eosforce | de3655c35062616a6b52726b298124e27cf19cb5 | [
"MIT"
] | null | null | null | libraries/chain/include/eosio/chain/txfee_manager.hpp | xuyp1991/eosforce | de3655c35062616a6b52726b298124e27cf19cb5 | [
"MIT"
] | null | null | null | /**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eosio/chain/types.hpp>
#include <eosio/chain/asset.hpp>
#include <eosio/chain/multi_index_includes.hpp>
namespace eosio { namespace chain {
class controller;
struct transaction;
struct action;
class txfee_manager {
public:
explicit txfee_manager();
bool check_transaction( const transaction& trx)const;
asset get_required_fee( const controller& ctl, const transaction& trx)const;
asset get_required_fee( const controller& ctl, const action& act)const;
private:
inline void init_native_fee(const account_name &acc, const action_name &act, const asset &fee) {
fee_map[std::make_pair(acc, act)] = fee;
}
inline asset get_native_fee(const uint32_t block_num, const account_name &acc, const action_name &act) const {
const auto itr = fee_map.find(std::make_pair(acc, act));
if( itr != fee_map.end() ){
return itr->second;
}
// no find
return asset(0);
}
std::map<std::pair<account_name, action_name>, asset> fee_map;
};
class fee_paramter {
public:
account_name name;
asset fee;
account_name producer;
fee_paramter(account_name name, asset fee, account_name producer) : name(name), fee(fee), producer(producer) {};
};
// action fee info in db, for action exec by user def code
class action_fee_object : public chainbase::object<action_fee_object_type, action_fee_object> {
OBJECT_CTOR(action_fee_object);
id_type id;
account_name account;
action_name message_type;
asset fee;
uint32_t cpu_limit = 0;
uint32_t net_limit = 0;
uint32_t ram_limit = 0;
};
struct by_action_name;
struct by_contract_account;
using action_fee_object_index = chainbase::shared_multi_index_container<
action_fee_object,
indexed_by<
ordered_unique<tag<by_id>,
BOOST_MULTI_INDEX_MEMBER(action_fee_object, action_fee_object::id_type, id)
>,
ordered_unique< tag<by_action_name>,
composite_key<action_fee_object,
BOOST_MULTI_INDEX_MEMBER(action_fee_object, account_name, account),
BOOST_MULTI_INDEX_MEMBER(action_fee_object, action_name, message_type)
>
>,
ordered_non_unique< tag<by_contract_account>,
BOOST_MULTI_INDEX_MEMBER(action_fee_object, account_name, account)
>
>
>;
} } /// namespace eosio::chain
FC_REFLECT(eosio::chain::fee_paramter, (name)(fee)(producer))
FC_REFLECT(eosio::chain::action_fee_object, (id)(account)(message_type)(fee))
CHAINBASE_SET_INDEX_TYPE(eosio::chain::action_fee_object, eosio::chain::action_fee_object_index)
| 31.789474 | 119 | 0.628808 | [
"object"
] |
aa12fe34938d976f0d9dcb576bdfc23255c676ea | 2,887 | cpp | C++ | mercury/tests/blocking_queue_test.cpp | ZachAnders/OPLabs | 085030e60c23292c7860817233373ab6e1b19165 | [
"BSD-2-Clause"
] | 1 | 2018-02-06T17:43:51.000Z | 2018-02-06T17:43:51.000Z | mercury/tests/blocking_queue_test.cpp | ZachAnders/OPLabs | 085030e60c23292c7860817233373ab6e1b19165 | [
"BSD-2-Clause"
] | null | null | null | mercury/tests/blocking_queue_test.cpp | ZachAnders/OPLabs | 085030e60c23292c7860817233373ab6e1b19165 | [
"BSD-2-Clause"
] | null | null | null | #include <cstdio>
#include <test.h>
#include <vector>
#include <algorithm>
#include <containers/BlockingQueue.hpp>
using namespace containers;
using namespace os;
using namespace std;
#define TEST_SHORT 0xdead
#define TEST_INT 32
#define TEST_LONG 0xdeadbeefdeadbeefll
#define TEST_STRING "Hello, World!\n"
void blocking_queue_writer(BlockingQueue<int>*& bq) {
for( int i = 0 ; i < 5 ; ++ i ) {
bq->push( i );
Time::sleep( rand() % 1000000 );
}
}
int test_blocking_queue( BlockingQueue<int>* bq ) {
for( int i = 0 ; i < 5 ; ++ i ) {
int test = bq->front();
bq->pop();
char name[1024];
snprintf( name, 1024, "BlockingQueue::front#%d", i );
TEST_EQ_INT( name, test, i );
}
return 0;
}
int test_blocking_queue_stress( BlockingQueue<int>* bq ) {
vector<int> pulled;
for ( int i = 0; i < 25; ++ i ) {
int test = bq->front();
bq->pop();
pulled.push_back( test );
}
sort( pulled.begin(), pulled.end() );
int i = 0;
int rc = 1;
for( ; i < 5 ; ++ i ) rc &= pulled[i] == 0;
TEST_EQ("BQStress::Stage1", rc, 1);
for( ; i < 10 ; ++ i ) rc &= pulled[i] == 1;
TEST_EQ("BQStress::Stage2", rc, 1);
for( ; i < 15 ; ++ i ) rc &= pulled[i] == 2;
TEST_EQ("BQStress::Stage3", rc, 1);
for( ; i < 20 ; ++ i ) rc &= pulled[i] == 3;
TEST_EQ("BQStress::Stage4", rc, 1);
for( ; i < 25 ; ++ i ) rc &= pulled[i] == 4;
TEST_EQ("BQStress::Stage5", rc, 1);
return 0;
}
int test_blocking_queue_timeout( BlockingQueue<int>* bq ) {
int test;
TEST_EQ( "ShouldTimeout", bq->front_timed( test, 100 ), false );
test = (int)0xdeadbeef;
bq->push( test );
test = 0;
TEST_EQ( "ShouldNotTimeout", bq->front_timed( test, 100 ), true );
TEST_EQ( "ShouldEqualBeef", test, ((int)0xdeadbeef) );
return 0;
}
int main( int argc, char** argv ) {
try {
(void) argc;
(void) argv;
BlockingQueue<int> bq;
FunctionRunner< BlockingQueue<int>* >
runner( blocking_queue_writer, &bq );
Thread th( runner );
TEST_EQ( "ThreadStart", th.start(), 0 );
TEST_FN( test_blocking_queue( &bq ) );
TEST_EQ( "ThreadJoin", th.join(), 0 );
Thread* all_threads[5];
int rc = 0;
for( int i = 0 ; i < 5; ++ i ) {
all_threads[i] = new Thread(runner);
rc |= all_threads[i]->start();
}
TEST_EQ( "ThreadsStart", rc, 0 );
TEST_FN( test_blocking_queue_stress(&bq) );
for( int i = 0; i < 5; ++ i ) {
rc |= all_threads[i]->join();
}
TEST_EQ( "ThreadsJoin", rc, 0 );
TEST_FN( test_blocking_queue_timeout(&bq) );
return 0;
} catch(Exception& e) {
fprintf(stderr, "Unhandled Exception %s", e.getMessage());
}
}
| 25.104348 | 70 | 0.537929 | [
"vector"
] |
aa146dc44094d94bebf4458033bdf0789e2ba8d6 | 3,845 | cpp | C++ | cctbx/sgtbx/lattice_symmetry.cpp | rimmartin/cctbx_project | 644090f9432d9afc22cfb542fc3ab78ca8e15e5d | [
"BSD-3-Clause-LBNL"
] | 155 | 2016-11-23T12:52:16.000Z | 2022-03-31T15:35:44.000Z | cctbx/sgtbx/lattice_symmetry.cpp | rimmartin/cctbx_project | 644090f9432d9afc22cfb542fc3ab78ca8e15e5d | [
"BSD-3-Clause-LBNL"
] | 590 | 2016-12-10T11:31:18.000Z | 2022-03-30T23:10:09.000Z | cctbx/sgtbx/lattice_symmetry.cpp | rimmartin/cctbx_project | 644090f9432d9afc22cfb542fc3ab78ca8e15e5d | [
"BSD-3-Clause-LBNL"
] | 115 | 2016-11-15T08:17:28.000Z | 2022-02-09T15:30:14.000Z | #include <cctbx/sgtbx/lattice_symmetry.h>
#include <cctbx/sgtbx/rot_mx_info.h>
#include <scitbx/array_family/sort.h>
#include <limits>
namespace cctbx { namespace sgtbx { namespace lattice_symmetry {
double
find_max_delta(
uctbx::unit_cell const& reduced_cell,
sgtbx::space_group const& space_group)
{
CCTBX_ASSERT(space_group.n_ltr() == 1);
CCTBX_ASSERT(space_group.f_inv() == 1);
uc_mat3 const& frac = reduced_cell.fractionalization_matrix();
uc_mat3 const& orth = reduced_cell.orthogonalization_matrix();
double min_cos_delta = 1;
for(int i_smx=1;i_smx<space_group.n_smx();i_smx++) {
rot_mx const& r = space_group.smx()[i_smx].r();
rot_mx_info r_info = r.info();
if (r_info.type() != 2) continue;
uc_vec3 t = orth * r_info.ev();
uc_vec3 tau = r.transpose().info().ev() * frac;
double numerator = scitbx::fn::absolute(t * tau);
double denominator = std::sqrt(t.length_sq() * tau.length_sq());
CCTBX_ASSERT(denominator != 0);
double cos_delta = numerator / denominator;
scitbx::math::update_min(min_cos_delta, cos_delta);
}
if ((min_cos_delta) > 1.0-std::numeric_limits<double>::epsilon()) {
//take care of case where numeric precision isn't able to correctly
// identify the equality of numerator and denominator
return 0.0;
} else {
return std::acos(min_cos_delta)/scitbx::constants::pi_180;
}
}
space_group
group(
uctbx::unit_cell const& reduced_cell,
double max_delta,
bool enforce_max_delta_for_generated_two_folds)
{
uc_mat3 const& frac = reduced_cell.fractionalization_matrix();
uc_mat3 const& orth = reduced_cell.orthogonalization_matrix();
//take care of case where numeric precision isn't able to correctly
// identify the equality of numerator and denominator
double min_cos_delta = std::min(
std::cos(max_delta * scitbx::constants::pi_180),
1.0-std::numeric_limits<double>::epsilon());
unsigned n_two_folds = sizeof(reduced_cell_two_folds)
/ sizeof(reduced_cell_two_fold_info);
std::vector<unsigned> i_two_folds;
i_two_folds.reserve(n_two_folds);
std::vector<double> cos_deltas;
cos_deltas.reserve(n_two_folds);
for(unsigned i_two_fold=0;i_two_fold<n_two_folds;i_two_fold++) {
reduced_cell_two_fold_info const&
two_fold = reduced_cell_two_folds[i_two_fold];
uc_vec3 t = orth * two_fold.u;
uc_vec3 tau = two_fold.h * frac;
double numerator = scitbx::fn::absolute(t * tau);
double denominator = std::sqrt(t.length_sq() * tau.length_sq());
CCTBX_ASSERT(denominator != 0);
double cos_delta = numerator / denominator;
if (cos_delta >= min_cos_delta) {
i_two_folds.push_back(i_two_fold);
cos_deltas.push_back(numerator / denominator);
}
}
if (i_two_folds.size() == 0) {
return space_group();
}
bool reverse = true;
af::shared<std::size_t> perm_memory = af::sort_permutation(
af::const_ref<double>(&*cos_deltas.begin(), cos_deltas.size()), reverse);
af::const_ref<std::size_t> perm = perm_memory.const_ref();
space_group group;
for(std::size_t i=0;i<perm.size();i++) {
reduced_cell_two_fold_info const&
two_fold = reduced_cell_two_folds[i_two_folds[perm[i]]];
rt_mx s(rot_mx(two_fold.r,1));
space_group expanded_group(group);
try {
expanded_group.expand_smx(s);
}
catch (error_non_crystallographic_rotation_matrix_encountered const&) {
break;
}
if (enforce_max_delta_for_generated_two_folds
&& find_max_delta(reduced_cell, expanded_group) > max_delta) {
continue;
}
group = expanded_group;
}
return group;
}
}}} // namespace cctbx::sgtbx::lattice_symmetry
| 38.069307 | 79 | 0.673342 | [
"vector"
] |
aa1be61b355da71d3c8b354eabf811fcfd61e052 | 566 | cpp | C++ | #knowabc.cpp | LucasProcopio/code-forces-challanges | bdbe563dbdc4da7f5080314984079b6bfc3f93f5 | [
"MIT"
] | null | null | null | #knowabc.cpp | LucasProcopio/code-forces-challanges | bdbe563dbdc4da7f5080314984079b6bfc3f93f5 | [
"MIT"
] | null | null | null | #knowabc.cpp | LucasProcopio/code-forces-challanges | bdbe563dbdc4da7f5080314984079b6bfc3f93f5 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, n) for (int i = a; i < n; i++)
#define repe(i, a, n) for (int i = a; i <= n; i++)
#define pb push_back
typedef vector<int> VI;
//header
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int a;
VI n;
rep(i, 0, 7)
{
cin >> a;
n.push_back(a);
}
sort(n.begin(), n.end());
rep(i, 0, 7)
{
if ((n[0] + n[1] + n[i]) == n[6])
{
cout << n[0] << " " << n[1] << " " << n[i];
break;
}
}
return 0;
} | 16.647059 | 55 | 0.413428 | [
"vector"
] |
aa1c87fa8f471b10ac3590ccbe18880d477d1be8 | 499 | cpp | C++ | solutions/0416.partition-equal-subset-sum/0416.partition-equal-subset-sum.1552036382.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 1 | 2021-01-14T06:01:02.000Z | 2021-01-14T06:01:02.000Z | solutions/0416.partition-equal-subset-sum/0416.partition-equal-subset-sum.1552036382.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 8 | 2018-03-27T11:47:19.000Z | 2018-11-12T06:02:12.000Z | solutions/0416.partition-equal-subset-sum/0416.partition-equal-subset-sum.1552036382.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 2 | 2020-04-30T09:47:01.000Z | 2020-12-03T09:34:08.000Z | class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = accumulate(nums.begin(), nums.end(), 0);
if (sum % 2 == 1) {
return false;
}
int N = nums.size();
int S = sum / 2;
vector<bool> dp(S+1, false);
dp[0] = true;
for (int k = 1; k <= N; k++) {
for (int i = S; i >= nums[k-1]; i--) {
dp[i] = dp[i] || dp[i-nums[k-1]];
}
}
return dp[S];
}
};
| 24.95 | 58 | 0.392786 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.